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!
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)
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);
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With