Search code examples
javascriptcodemirror

Using CodeMirror search function scrolling to show the string found


In this jsFiddle I have a CodeMirror editor that has three lines. I'm trying to implement the search/searchcursor addons by clicking on a button to find a string on the third line and position the highlighted result.

When the search button is clicked, the cursor should be positioned in the word ccc (the third line that is out of the editor view, so CodeMirror should scroll to that position and make the third line visible).

I'm getting an error Cannot read property 'line' of undefined even though I added the addons. Any ideas how to make this work?

<button type=button onclick="search()">Search</button>
<textarea rows="4" cols="30" id="cm" name="cm">aaa 
bbb 
ccc</textarea>


var editor = CodeMirror.fromTextArea(document.getElementById('cm'), {
    lineNumbers: true
});  

editor.setSize(null,30);

function search() {
  var text = 'ccc';
  var cursor = editor.getSearchCursor(text, editor.getCursor());
  editor.setSelection(cursor.from(), cursor.to());
}

Solution

  • try loading corresponding search.js file

    https://codemirror.net/addon/search/search.js

    https://codemirror.net/demo/search.html