How to set cursor position in Codemirror editor
Asked Answered
O

3

14

I am implementing "find and correct" functionality using codemirror. I know there is an addon for search and replace, but it doesn't fulfill my requirement. the editor is for writing particular queries. It creates spans in

<pre> <span class="cm-field">field</span>:jet <span class="cm-other-operator active" >adj3</span> engine <span class="cm-operator">OR</span> jet <span class="cm-other-operator" >near5</span> engine </pre>

please refer snapshot. If i click on any of the operator (orange colored), the cursor starts blinking there and the functionality is working. On clicking find next button i am able to find the respective span but unble to set cursor there. So How can i set Cursor position there. Thanks in advance. enter image description here

Overtake answered 28/10, 2015 at 15:16 Comment(2)
You can use doc.setCursor(pos: {line, ch}) to set the cursror to any specific position.Kilmer
On CodeMirror 6, the cursor position is a single number: editor.dispatch({selection: {anchor: N, head: N}}) discuss.codemirror.net/t/set-cursor-position-in-v6/4476Eagre
F
26

Before you set the cursor position you have to focus on the editor.

editor.focus()

Then just like @djadmin said you would use doc.setCursor(pos: {line, ch}) to set the cursor position.

editor.setCursor({line: 1, ch: 5})

Here's a JSFiddle you can play with that does this: https://jsfiddle.net/stpmu61y/

Fichte answered 22/4, 2016 at 23:46 Comment(2)
Could you specify whether the line and ch (column) are 0- or 1-indexed?Pudendas
There's no such function on CodeMirror 6Eagre
O
2

If your cursor is installed, but only at the beginning of the line: 0, symbol: 0, this means that only focus is triggered, since setValue is delayed, wrap your SetCursor in SetTimeOut with 0 delay and enjoy =)

      

       codeEditor.setValue (code);

       setTimeout (() => {
           codeEditor.focus();
           codeEditor.setCursor({
             line: 3,
             ch: 10,
           });
       }, 0);
Onfre answered 21/5, 2020 at 11:58 Comment(0)
C
1

Using https://uiwjs.github.io/react-codemirror/,

const codemirrorRef = React.useRef();
      <CodeMirror
        ref={codemirrorRef}
    codemirrorRef.current.view.dispatch({selection: {anchor: 5, head: 5}})
Caplan answered 17/11, 2022 at 12:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.