Sublime isn’t moving the cursor to a previous position; the view.insert()
method is specifying the exact position in the file (here the 0
means “start of the file”) that the insert should happen in. This just inserts the text directly into the buffer at the position you say, regardless of where the cursor might be, if any text is selected, etc.
To move the cursor too, you want to do what @UltraInstinct05 says here; modify the selection after the insert to put the cursor where you expect it to be. You might want to capture the return value of view.insert()
, which tells you how many characters it actually inserted and use that instead of taking the length of the text, if there’s a possibility that the text might contain a tab character though.
If you happen to be in a situation where you want to insert text at the position the cursor is currently sitting at, you can also do self.view.run_command("insert", {"characters": "Hello, World\n"})
to have the text insert and move the cursor for you.
In doing so you lose the ability to specify the insertion point of the text that you get via view.insert()
though, so this isn’t always a handy trick as it would require you to modify the selection anyway to move the cursor first.
On the other hand, running the insert
command will take the same action as would happen if the user typed text, which includes inserting text at every cursor, replacing selected text with the new text, etc. So in that regard this is a good thing to keep in mind. You can also do it from any command and not just a TextCommand
, which can be handy.