Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 798
Martin Vseticka Avatar asked May 13 '12 21:05

Martin Vseticka


3 Answers

You want https://codemirror.net/doc/manual.html#scrollIntoView

Notice the optional margin parameter which should do what you want:

cm.scrollIntoView(what: {line, ch}|{left, top, right, bottom}|{from, to}|null, ?margin: number)

Your code would be something like:

cm.scrollIntoView({line:50, char:5}, 200)
like image 103
danday74 Avatar answered Sep 21 '22 02:09

danday74


This one should work:

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

function jumpToLine(i) { 
    var t = editor.charCoords({line: i, ch: 0}, "local").top; 
    var middleHeight = editor.getScrollerElement().offsetHeight / 2; 
    editor.scrollTo(null, t - middleHeight - 5); 
} 
like image 14
Eric Grivilers Avatar answered Nov 04 '22 13:11

Eric Grivilers


It is very simple.

Init:

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

If you want current position to set it later, you can use

editor.getScrollInfo();

It returns an JavaScript object:

{
  "left": 0,
  "top": 0,
  "height": 500,
  "width": 500,
  "clientHeight": 300,
  "clientWidth": 200
} 

now you can set set editor scroll position using:

editor.scrollTo(left,top);
like image 6
Raghavendra Avatar answered Nov 04 '22 13:11

Raghavendra