2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【monaco-editor】閉じタグの補完

Last updated at Posted at 2021-03-13

概要

monaco-editorhtml のタグを閉じた際に、閉じタグの補完する。
monaco の標準の機能では実現できなかったので(2021年3月13日時点)、独自に実装する。

f0a1d036d04bdff363f63b0b2eac75dc.gif

手順

  1. keyUp のイベントを講読
  2. > か否か
  3. 補完前のコードを取得
  4. 補完するタグを取得
  5. 閉じタグを補完
  6. 補完後にタグの中央へ位置を戻す
editor.onKeyUp((event) => {
    // 1. `>` か否か
    const keyCode = event.keyCode as number;
    if (keyCode !== 84) return;

    const model = editor.getModel();
    if (!model) return;
    const position = editor.getPosition();
    if (!position) return;

    // 2. 補完前のコードを取得
    const codePre = model.getValueInRange({
        startLineNumber: position.lineNumber,
        startColumn: 1,
        endLineNumber: position.lineNumber,
        endColumn: position.column,
    });

    // 3. 補完するタグを取得
    const tag = codePre.match(/.*<(\w+)>$/)?.[1];
    if (!tag) return;

    // 4. 閉じタグを補完
    editor.trigger('bra', 'type', {
        text: `</${tag}>`,
    });

    // 5. 補完後にタグの中央へ位置を戻す
    editor.setPosition(position);
});

参考文献

関連記事

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?