Get char number from start to cursor

I couldn’t find any methods in the manual so thought I’d ask here. What’s the cheapest way to:

  • Provide a {line, ch} cursor and get back number of chars from start of doc to that
  • The opposite (provide a number and get back a {line, ch})

I have this so far which works find but wonder if I’m missing a better approach:

// {line, ch} to num
num = cm.getRange({line: 0, ch: 0}, cm.getCursor()).length;

// num to {line, ch}
let len = 0, thisLine = 0, thisChar = 0;
cm.eachLine(function(line) {
    if (num > len + (line.text + "\n").length) {
    } else if (thisChar === 0) {
        // ^ Means we set thisChar once
        thisChar = num - len;
        return {line: thisLine, ch: thisChar};
    len += (line.text + "\n").length;
1 Like

See indexFromPos and posFromIndex

1 Like

Ah thank you (didn’t find them in manual as searched for word “cursor” and didn’t see anything relevant).