ProseMirror Position Mapping functions in CodeMirror?


#1

Hi! I’m wondering if there is any method or utility in CodeMirror which takes a CodeMirror.Pos and a change, and maps it to an updated position in the document, much like the functionality described here?


#2

This exists internally as adjustForChange, but isn’t currently exported. The function is pretty simple, and looks like this:

function adjustForChange(pos, change) {
  if (cmp(pos, change.from) < 0) { return pos }
  if (cmp(pos, change.to) <= 0) { return changeEnd(change) }

  var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
  return Pos(line, ch)
}

#3

Thanks for the quick reply! I’m writing a thing which caches text markers by start position so I need to update the positions on change. Had to also copy the cmp and changeEnd functions from the codebase as well.


#4

changeEnd is exported (CodeMirror.changeEnd), and cmp is exported as CodeMirror.cmpPos