Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set cursor position in Codemirror editor

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

like image 712
Shekhar Avatar asked Oct 28 '15 15:10

Shekhar


People also ask

How do I set up CodeMirror?

Download CodeMirror files. Download jQuery file. Inside the codemirror project folder create subfolders and name them js, css and plugin. The js folder will hold all the javascript files.

How do I use CodeMirror in textarea?

This could be used to, for example, replace a textarea with a real editor: var myCodeMirror = CodeMirror(function(elt) { myTextArea. parentNode. replaceChild(elt, myTextArea); }, {value: myTextArea.


2 Answers

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/

like image 134
Michael Schwartz Avatar answered Oct 12 '22 12:10

Michael Schwartz


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);
like image 32
VItaliiKalinbet Avatar answered Oct 12 '22 11:10

VItaliiKalinbet