ワードプレスのクラシックエディタを直接使っているといつも思うことがありました
[Tab]キー押して空白入れて見やすくインデントしたい!
この記事を書くまでは入れないか、スペースキーを押して誤魔化してましたがやり方が判明したので記載する
また、[Shift+Tab]で空白が消える処理も入れてます。文字選択中も空白の挿入、削除が可能となってます。
とはいえ何かバグがあったらすみません。
こちらにプラグインも用意しております。
2025/01/18 コード修正。
(「Ctrl+zで戻らないのを修正」「Tabで開けた空白はShit+Tabで消えるが、スペースで開けた空白が消えないのを修正」)
2025/01/18 「行の後半にカーソルがあっている状態でShit+Tabを押しても行の先頭のスペースが消えてしまうバグあり」「undoで戻らない場合がある(戻らないパターンがあるがパターン不明)」「行選択状態でtabキーを押すと選択が解除される」
2025/01/19 コード修正。
「行の後半にカーソルがあっている状態でShit+Tabを押しても行の先頭のスペースが消えてしまうバグ修正」「行選択状態でtabキーを押すと選択が解除されるバグ修正」)「undoで戻らない場合がある(Shift+Tabでスペースを消すとUndoできなくなる)バグ修正」「段落も削除してしまうバグ修正」「無選択状態でTabキーでスペースを複数空けた場合のアンドゥの動作がおかしいバグ修正」
function custom_editor_script() { ?> <style type="text/css"> /* タブの幅を4スペースに設定 */ .wp-editor-area { tab-size: 4; } </style> <script type="text/javascript"> document.addEventListener('DOMContentLoaded', function () { var editorArea = document.querySelector('.wp-editor-area'); if (editorArea) { editorArea.addEventListener('keydown', function (e) { var start = editorArea.selectionStart; var end = editorArea.selectionEnd; var value = editorArea.value; var tabSize = 4; // タブ幅を定義(CSSと一致させる) // Tabキーが押された場合 if (e.key === 'Tab') { e.preventDefault(); // デフォルトのタブ動作を無効化 if (!e.shiftKey) { // Tabキーのみ押下時:インデントを挿入 if (start === end) { document.execCommand('insertText', false, '\t'); // 選択範囲を保持 editorArea.selectionStart = editorArea.selectionEnd = start + 1; } else { var lines = value.substring(start, end).split('\n'); var updatedLines = lines.map(function (line) { return '\t' + line; }); var updatedText = updatedLines.join('\n'); document.execCommand('insertText', false, updatedText); // 選択範囲を保持 editorArea.selectionStart = start; editorArea.selectionEnd = start + updatedText.length; } } else { // Shift + Tab:カーソル位置または選択範囲内の空白を削除 if (start === end) { var beforeCursor = value.substring(0, start); var afterCursor = value.substring(start); var updatedBeforeCursor = beforeCursor.replace(/([\t ]{1,4})$/, ''); // 半角スペースと全角スペースに対応 var deletedLength = beforeCursor.length - updatedBeforeCursor.length; if (deletedLength > 0) { document.execCommand('delete', false, deletedLength); } } else { // 複数行選択の場合の処理 var lines = value.substring(start, end).split('\n'); var updatedLines = lines.map(function (line) { // 各行の先頭からタブサイズ分の空白またはタブを削除 if (line.startsWith('\t')) { return line.slice(1); // タブ1つ削除 } else { var match = line.match(/^[ ]{1,4}/); return match ? line.slice(match[0].length) : line; // 最大タブサイズ分の空白を削除 } }); var updatedText = updatedLines.join('\n'); document.execCommand('insertText', false, updatedText); // 選択範囲を保持 editorArea.selectionStart = start; editorArea.selectionEnd = start + updatedText.length; } } // アンドゥスタックに追加 document.execCommand('save'); } }); } }); </script> <?php } add_action('admin_footer', 'custom_editor_script');