wortwart
wortwart

Reputation: 3360

Move cursor in Sublime Text Python Plugin

I wrote a simple plugin for Sublime Text which inserts tags at cursor position(s) or wraps them around selected text:

import sublime, sublime_plugin
class mySimpleCommand(sublime_plugin.TextCommand):
  def run(self, edit):
    sels = self.view.sel()
    for sel in sels:
      sel.start = sel.a if (sel.a < sel.b) else sel.b
      sel.end = sel.b if (sel.a < sel.b) else sel.a
      insert1Length = self.view.insert(edit, sel.start, '<tag>')
      self.view.insert(edit, sel.end + insert1Length, '</tag>')

But how can I move the cursor(s) after inserting the tags? I looked at the API documentation in https://www.sublimetext.com/docs/2/api_reference.html and at several example plugins but still fail to solve this silly problem. Can anybody help?

Upvotes: 1

Views: 930

Answers (2)

daphtdazz
daphtdazz

Reputation: 8159

Here's an example of how to move the cursor to the end of the line. It should be obvious how to generalize!

With reference to the API reference.

import sublime
import sublime_plugin


class MoveToEolCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        # get the current "selection"
        sel = self.view.sel()

        # get the first insertion point, i.e. the cursor
        cursor_point = sel[0].begin()

        # get the region of the line we're on
        line_region = self.view.line(cursor_point)

        # clear the current selection as we're moving the cursor
        sel.clear()

        # set the selection to an empty region at the end of the line
        # i.e. move the cursor to the end of the line
        sel.add(sublime.Region(line_region.end(), line_region.end()))

Upvotes: 0

Cornishman
Cornishman

Reputation: 21

I've just had the same problem - moving the cursor to the end of a line in a plugin after appending text to it. I fixed it using sergioFC's hint of:

# Place cursor at the end of the line
self.view.run_command("move_to", {"to": "eol"})

Works for me.

Upvotes: 2

Related Questions