CodeMirror 6将光标移动到行尾 2024-07-14

2024-07-13  本文已影响0人  齐格Insight

背景

在Windows系统上有Ctrl-e这个快捷键,如果我们想要它的行为保持与Mac系统上一样,即:移动光标到行尾。

监测快捷键被按下事件

第一步,我们需要监测Ctrl-e这个快捷键被按下的事件,代码如下:

document.addEventListener('keydown', e => {
            // windows: Ctrl + e
            if (e.ctrlKey && e.key === 'e') {
                e.preventDefault()   // 阻止默认事件触发
                this.editor.focus()    // cm选种
                //  current select position from to, if not selected, use cursor
                const curPos = this.editor.state.selection;  // 当前选种文本的位置,如果没选种任何文本即光标位置
                const from = curPos.ranges && curPos.ranges[0].from
                const to = curPos.ranges && curPos.ranges[0].to
                moveCursorToEndOfLine(this.editor)
            } 
        });

移动光标处理

将光标移动到行尾,实现代码如下:

// codemirror 6, move cursor to end of current line
export function moveCursorToEndOfLine(editor: EditorView) {
    const lineAt = editor.state.doc.lineAt(editor.state.selection.main.head)
    editor.dispatch({ selection: { anchor: lineAt.to, head: lineAt.to } })
}

其中lineAt为当前行的信息,里面有三个字段,如下:

{
   from: 0 
   number:1
   to:75
   text: ''
}

from表示这行开始的位置,to表示这行结束的位置, number表示当前行号, text 表示当前行内容。

image.png
上一篇 下一篇

猜你喜欢

热点阅读