Inserting text at a position


Quick question - would appreciate any help.

I’m just getting started with making packages. I’ve been through the tutorial, and while I understood most of it, I don’t quite feel able to get what I need from the API alone.

I’m trying to insert text at some given points. I’m able to get the points, but I can’t figure how to insert text at those points. I think it;s something to do with a textbuffer… but really I can’t figure it out. Would really appreciate any help.


You don’t have to use TextBuffer. You can use TextEditor.insertText:

currentPosition = editor.getCursorBufferPosition()
editor.setCursorBufferPosition([row, column])


Many thanks! Solved my problem perfectly


The advanced version of the above would use editor.getCursorBufferPositions() (← note the plural) to handle the case where the user has multiple cursors.


Ah, that’d be great - except it seems to only return a single point for each selection - I need the start and end point of each highlighted piece of text, is there a way to find that?


You can use editor.getSelectedBufferRanges() to get all selections in a file


And here’s the documentation:


Thanks for the advice on getSelectedBufferRanges()

I’ve used it now, and it’s working great, except that it is inserting text at an earlier position than I expected. Here’s the code:

    var bufferPointsMultiple = editor.getSelectedBufferRanges();

    //text variables
    var startText = "foo";
    var endText = "bar"

    for (var i = 0; i < bufferPointsMultiple.length; i++){

      var pointTo = bufferPointsMultiple[i].serialize();

      var startPoint = pointTo[0];
      var endPoint = pointTo[1];


If I highlight the text:


I get the output


Can anyone explain this to me? I’d be much obliged. On another note… if someone could tell me how to set the inserted text to be an input from a prompt to the user… then that’d be great! I can’t find it in the API at all.


Here’s what’s happening:

  1. When you select hello the start of the range is X, Y and the end of the range is X+5, Y.
  2. You then insert foo at X, Y
  3. Then you move the cursor to X+5, Y … which is now at foohe|llo because of the inserted text (the pipe character signifies the cursor)
  4. You insert bar

Resulting in foohebarllo.

If you want a range that changes as the text is changed, you want a Marker, not a Range. Which can be created with editor.markBufferRange


Or you could do everything in reversed order: start with the last selection, end with the last, and do the end of the selection first and then the start.


Thanks - I went with this in the end. Seems to make the most sense. I would like to implement markers, but for now just reversing the order seems easiest. If I could just figure out how to get some input from the user…


You could take a look at tree-view’s add file dialog for how to do user input