Search code examples
ace-editor

How to get the cursor position (not row or column) in Ace Editor?


Is there a way to get the cursor position (not the row and column) in Ace Editor.

For example, if the contents of the Ace Editor are the following:

Hello
World

And the cursor was after the "Wo" in "World". The position or index would be 7 or 8 (if you count newline).

Is there a method to get the position?


Solution

  • Ace calls {row, column} objects position, and the number of characters since the document start index.
    You can convert position to index using editor.session.doc.positionToIndex method https://github.com/ajaxorg/ace/blob/v1.2.6/lib/ace/document.js#L678, but note that this method is not very fast since it has to iterate over the whole document, so use it and indexToPosition as sparingly as possible.