Search code examples
javascriptjquerycodemirror

CodeMirror - Is it possible to scroll to a line so that it is in the middle of window?


I'm highlighting lines of HTML code in CodeMirror and I want to add an anchor that scroll CodeMirror editor to a given line.

I can scroll to a line X via setCursor method. But I would like to have the line X in the middle of CodeMirror window. Can I do that? I studied the API and demos but with no luck.

Thanks!


Solution

  • Initialization:

    var editor = CodeMirror.fromTextArea(...);
    

    Function to show a line in the middle of editor:

    function jumpToLine(i) {
    
        // editor.getLineHandle does not help as it does not return the reference of line.
        editor.setCursor(i);
        window.setTimeout(function() {
           editor.setLineClass(i, null, "center-me");
           var line = $('.CodeMirror-lines .center-me');
           var h = line.parent();
    
           $('.CodeMirror-scroll').scrollTop(0).scrollTop(line.offset().top - $('.CodeMirror-scroll').offset().top - Math.round($('.CodeMirror-scroll').height()/2));
       }, 200);
    }