Programmatically search and select a keyword

Greetings Marijn
Having searched for a solution to this problem, I found only the search demo example in the online documentation. I debugged through the js code and reversed engineered the following programmatic search,

     //keyword is a lowercase string I wish to search for in my cmEditor instance of codemirror editor.
     var cursor = cmEditor.getSearchCursor(keyword , CodeMirror.Pos(cmEditor.firstLine(), 0), {caseFold: true, multiline: true});
     if(cursor.find(false)){ //move to that position.
       cmEditor.scrollIntoView({from: cursor.from(), to:}, 20);

this works, but maybe you could shed some light on the following questions I have,

  • is this an acceptable way to solve this ?
  • what is the number 20 in the function scrollIntoView do?
  • my editor automatically scrolls down to the lcoation of the keyword in my code, however, the line of interest is a few lines above the editor window, meaning it is hidden and I have to scroll back up to see it. How can I fix this?


See the docs.

Scroll to the actual position you want to see, rather than the keyword?

1 Like

thanks for the quick reply. I guess the last 2 questions I related. I am not sure why a value of 20 did not initially solve this. I played around with some number for the margin, and settled to 30 which is giving a good result.

yes, very much so. Unfortunately, repeated keyword search loads rather eratic positions, sometimes within the visual window frame, sometime below the line with highlight, such one has to scroll up to see the line. I also experimented without giving a margin value to the scrollIntoView function, but somehow it doesn’t seem to make much difference.

My cm instance is stored in memory and reused each time, do I need to flush the cursor position each time I do a new search?

Finally i used the following change in the above code to get the best results,

      var from = cursor.from();
      var to =;
      cmEditor.setSelection(CodeMirror.Pos(from.line, 0), to);
      cmEditor.scrollIntoView({from: from, to: CodeMirror.Pos(to.line + 10, 0)});