简体   繁体   中英

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?

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.

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()))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM