Hello all, I modified the typewriter scrolling addon so that it will keep the position on “soft line breaks” when lineWrapping is true and not only when enter is pressed at the end of the line. I am using the last version of codemirror (5.6).
It works like a charm if:
- the current paragraph (line) is not the first paragraph
- the current paragraph (line) is not the last paragraph
If those two conditions are not true, the text jumps up and down. I can’t see why. Does anyone know how to fix that?
I am attaching the code!
Thanks!
iztok
The code:
/**
* WM TYPEWRITER SCROLLING
*/
"use strict";
(function(mod) {
if (typeof exports == "object" && typeof module == "object") {
mod(require("codemirror"));
} else if (typeof define == "function" && define.amd) {
define(["codemirror"], mod);
} else {
mod(CodeMirror);
}
})(function(CodeMirror) {
CodeMirror.defineOption("typewriterScrolling", false, function(cm, val, old) {
if (old && old != CodeMirror.Init) {
cm.off("changes", onChanges);
}
if (val) {
cm.on("changes", onChanges);
}
});
"use strict";
CodeMirror.commands.scrollSelectionToCenter = function (cm) {
if (cm.getOption("disableInput")) {
return CodeMirror.Pass;
}
var cursor = cm.getCursor("from");
var top = cm.charCoords({line: cursor.line, ch: cursor.ch}, "local").top;
var halfWindowHeight = cm.getWrapperElement().offsetHeight / 4;
var scrollTo = Math.round((top - halfWindowHeight));
cm.scrollTo(null, scrollTo);
};
var oldPos = 0;
function onChanges(cm, changes) {
if (cm.getSelection().length !== 0) {
return;
}
var currentPos = cm.cursorCoords().top;
if (currentPos !== oldPos) {
cm.execCommand("scrollSelectionToCenter");
oldPos = cm.cursorCoords().top;
return;
}
}
});