Can markers be retained when completely replacing text?


#1

I think this code is pretty self explanatory. I’m using a backend to format the code. I send the whole buffer and get a new formatted text back that I insert. I’m thinking that I want the cursor to stay at the same logical place so I tried a marker:

  formatCurrentSourceFile: ->
    editor = atom.workspace.getActiveTextEditor()
    
    cursorPos = editor.getCursorBufferPosition()
    cursorMarker = editor.markBufferRange([cursorPos, cursorPos], {invalidate: 'never'})
    req =
      typehint: "FormatOneSourceReq"
      file:
        file: editor.getPath()
        contents: editor.getText()
    @client?.post(req, (msg) ->
      editor.setText(msg)
      newCursorPos = cursorMarker.getStartBufferPosition()
      cursorMarker.destroy()
      editor.setCursorBufferPosition(newCursorPos)
    )

However, this set the cursor to the end of the buffer which was a lot worse than just:

formatCurrentSourceFile: ->
    editor = atom.workspace.getActiveTextEditor()
    cursorPos = editor.getCursorBufferPosition()
    req =
      typehint: "FormatOneSourceReq"
      file:
        file: editor.getPath()
        contents: editor.getText()
    @client?.post(req, (msg) ->
      editor.setText(msg)
      editor.setCursorBufferPosition(cursorPos)
    )

#2

To my understanding, markers work by tracking the changes before, after and/or within the marker and adjusting accordingly. But if you just setText, the marker has no point of reference because you deleted them and then put in a bunch of new text.

I found this blog post very enlightening on how markers work:


#3

Yes, that’s how I understand it too. So this use case is probably not doable by markers. Unless use a diffing tool to create a patch first instead and apply that instead of replacing full text.

Really interested if someone has any ideas - it shouldn’t be the first time someone want to use an API that gives the full modified text and want to keep cursor. Pretty sure some IDE:s do it with external formatters.