代码镜像每次内容更改时获取当前行号

Code Mirror Get Current Line Number every time content changes

我正在尝试使用 Code Mirror 创建一个文本编辑器。我想在显示屏底部向用户显示当前行号,就像文本编辑器一样。

到目前为止我试过这个:

function updateInfo(){
var lines = editor.lineCount();
document.getElementById('line-no.').innerText = lines;
editor.refresh();
}
editor.on("change", updateInfo());

line-no.span 我想显示行号的地方。这适用于第一个行号,但是当我转到其他行时,它什么也没做。控制台显示此错误:

codemirror.js:2154 Uncaught TypeError: Cannot read property 'apply' of undefined
at codemirror.js:2154
at fireCallbacksForOps (codemirror.js:2111)
at finishOperation (codemirror.js:2125)
at endOperation (codemirror.js:3747)
at HTMLTextAreaElement.<anonymous> (codemirror.js:3884)

更新

To follow updates in the editor, register a handler on the cursorActivity event. This event is fired when there is a change in the cursor or selection.
The handler is called with the instance of CodeMirror; on this you can call the getCursor method to be the an object that contains the current line number that the cursor is active on.
Note that the line number is zero-based, so you may or may not increment it by 1.

const STATUS_CURRENT_LINE = document.getElementById('line-no.');

const onCursorActivity = (instance) => {
  const cursor = cm.getCursor();
  STATUS_CURRENT_LINE.textContent = cursor.line + 1;
}

editor.on("cursorActivity", onCursorActivity);

当编辑器中有文档更改时设置当前行号

错误发生是因为 updateInfo 回调甚至在您注册之前就被调用了。这样注册为回调的值为undefined.

editor.on('change', updateInfo()) // -> editor.on('change', undefined)

这可以通过注册函数来解决。

editor.on('change', updateInfo)

但是,回调的签名应遵循记录的内容。

The change callback 传递给 CodeMirror 的 instance 和一个 changeObject,您可以从中检索当前行。

"change" (instance: CodeMirror, changeObj: object)
Fires every time the content of the editor is changed. The changeObj is a {from, too, text, removed, origin} object containing information about the changes that occurred as the second argument. from and to are the positions (in the pre-change coordinate system) where the change started and ended (for example, it might be {ch:0, line:18} if the position is at the beginning of line #19). text is an array of strings representing the text that replaced the changed range (split by line). removed is the text that used to be between from and to, which is overwritten by this change. This event is fired before the end of an operation before the DOM updates happen.

const STATUS_CURRENT_LINE = document.getElementById('line-no.');

function updateInfo(instance, changeObj){
   STATUS_CURRENT_LINE.innerText = changeObj.to.line;
}

editor.on("change", updateInfo);