Select text programmatically


I spent the last hour reading the documentation, this forum and searching GitHub for working code pieces. What I’m trying to do is as simple select text in the active editor, as seen on this screenshot in which UTF-8 is selected:

The way the contents of the editor is generated (not a snippet!), the string I’m trying to select will always be at the same position, in this case line 1, columns 31-36. I’m not even sure whether to use the setScreenRange (Selection) or markRange (MarkerLayer), but I’ve tried both.

I found the following pieces on GitHub, but they both don’t work for me:

editor = atom.workspace.getActiveTextEditor()

editor.markBufferRange([[0, 30], [0, 35]], invalidate: 'never')
# => Uncaught SyntaxError: missing ) after argument list(…)

# this one even looks weird ;-)
editor.getSelectionsOrderedByBufferPosition().setScreenRange([[0, 30], [0, 35]], preserveFolds: true)
# => Uncaught SyntaxError: missing ) after argument list(…)

I’d appreciate any help!


First of all, you get these SyntaxErrors because you try to run CoffeeScript code as JS (the dev console doesn’t understand CoffeeScript). You would have to write
editor.markBufferRange([[0, 30], [0, 35]], {invalidate: 'never'}) instead.

About your code snippet: These two functions do different things.

# or

But I don’t know which solution is better or if one of them has any unknown side effects. Also keep in mind that somethingBufferRange(...) != somethingScreenRange(...)

Hope that helps :slight_smile:


Thank you! This does exactly what I was after:

var editor = atom.workspace.getActiveTextEditor();
var range = [[0, 30], [0, 35]];
editor.selectMarker(editor.markBufferRange(range, {invalidate: 'never'}))