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


#1

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:

editor.getCursorBufferPosition()

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?


#2

Oh, think I found it:


#3

Huh,

I’d guess I can combine:

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

and https://atom.io/docs/api/v0.189.0/TextBuffer#instance-characterIndexForPosition

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


#4

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()

#5

Awesome, thanks!

Meta question: does this mean that code is the only updated doc? Since it’s not here: https://atom.io/docs/api/v0.189.0/TextEditor

Cheers,
Viktor


#6

It is not a public API, that is correct.


#7

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


#8

I opened this Issue:

To discuss making it a public API.

I’ve also submitted a Pull Request for it:


#9

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.


#10

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:


#11

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.


#12

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.