Sublime Forum

Insert string and move the cursor to a certain position

#1

I’d like to insert “Hello, World!” and move the cursor just before the “World” programmatically.
I tried specifying the cursor position by “$0” but it didn’t work.

import sublime, sublime_plugin

class ExampleCommand(sublime_plugin.TextCommand):
    def run(self, edit):
      self.view.insert(edit, self.view.sel()[0].begin(), "Hello, $0World!")

How do I specify where to put the cursor in a string?

1 Like

#2

If you want to add the text at the current cursor’s position without moving the cursor, you could use the insert_snippet command.

view.run_command('insert_snippet', {'contents': "$0Hello World"})

Otherwise you’ll need to save the cursor position before inserting text and restoring it afterwards.

import sublime
import sublime_plugin


class InsertWorldCommand(sublime_plugin.TextCommand):

    def run(self, edit):
        point = self.view.sel()[0].begin()
        self.view.insert(edit, point, "hello World")
        self.view.sel().clear()
        self.view.sel().add(point)

But you should add some logic to support multiple cursors in that case.

1 Like