1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

概要

CodeMirrorのlintパッケージの使い方です。サーバサイドでチェックした結果を表示する際の参考にどうぞ。

package.json

"dependencies": {
  "codemirror": "^6.0.1",
  "@codemirror/commands": "^6.5.0",
  "@codemirror/legacy-modes": "^6.4.0",
  "@codemirror/lint": "^6.7.0",
  "@codemirror/state": "^6.4.1"
},

実装

basicSetupを指定しておくと行番号表示など基本的な拡張が使えます。

import { EditorState } from "@codemirror/state";
import { EditorView, basicSetup } from "codemirror";
import { keymap } from "@codemirror/view"
import { linter, forceLinting } from "@codemirror/lint";
import { indentUnit } from "@codemirror/language";
import { indentWithTab } from "@codemirror/commands";

const lintExtention = linter(view => {
  return /* ここでAPIで取得したlint結果を返す */;
});

const editorState = EditorState.create({
  doc: '',
  extensions: [
    updateListener,
    basicSetup,
    lintExtention,
    keymap.of([indentWithTab]),
    indentUnit.of("    "),
  ],
});

const editor = document.querySelector('#editor');
const editorView = new EditorView({
  state: editorState,
  parent: editor,
});

変更の検知

docChangedtrueの場合にテキストが変更されています。

const updateListener = EditorView.updateListener.of((update) => {
  if (!update.docChanged) {
    return;
  }
  const newDocument = update.state.doc.toString();
  // ここでAPI呼出すればOK
  return;
});

linterに指定した関数で返す内容

以下のようなオブジェクトの配列をreturnで返します。

{
  from: /* 開始位置 */,
  to: /* 終了位置 */,
  message: 'メッセージ',
  severity : /* "error", "hint", "info", "warning"のどれかを指定 */,
}

行番号から位置を取得するのはTextクラスのline関数を使えばできます。

editorView.state.doc.line(/* 行番号を指定 */);

更新する

以下のようにforceLintingを呼び出すことで表示を更新できます。

forceLinting(editorView);
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?