How to get cursor position as buffer offset (one dimensional, in chars)?


I’m trying to integrate atom with Ensime for Scala development. When doing stuff like “go to type” I need to communicate with Ensime using a protocol which is one-dimensional for positions in file/buffer. So I need to convert the two-dimensional Point i get from:


in this case to a one dimensional character offset. It’s really important that this is performant as well, it doesn’t seem reasonable to need to traverse the whole buffer up to the row I’m at and sum up the characters. Isn’t there a one-dimensional position lying around there somewhere that I can use?


Oh, think I found it:



I’d guess I can combine:

  editor = atom.workspace.getActiveTextEditor()
  pos = editor.getCursorBufferPosition()


but how to I get the TextBuffer of a TextEditor? Call me blind, but I can’t find it…


but how to I get the TextBuffer of a TextEditor? Call me blind, but I can’t find it…

You should use the TextEditor::getBuffer method:

editor = atom.workspace.getActiveTextEditor()
buffer = editor.getBuffer()


Awesome, thanks!

Meta question: does this mean that code is the only updated doc? Since it’s not here:



It is not a public API, that is correct.


What does this mean? That it might go away? Is there any public way to achieve what I need?


I opened this Issue:

To discuss making it a public API.

I’ve also submitted a Pull Request for it:


The functionality certainly won’t go away so the worst that can happen is you’ll have to change your code to keep up. I have used some really low-level hacks for many of my packages the last year and have not been bitten yet. And by low-level I even mean replacing a method on a core class.

This is ironic since the api calls have changed a lot and I’ve had to rewrite to keep up but I’ve had no problems with the hacks.


The change has been merged, TextEditor::getBuffer is now a public API and should show up in the documentation when v0.190.0 is released :grinning:


Is there any way of invoking this method in the UI? in a given scenario I would like to navigate sources by character offset, not only by line and row.


I need it also. There are some parsers that give the error only by the offset position, not by the line and char.

I suppose that could be easily embedded into an addon, with a goto-char command, like emacs or vim.