Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving the cursor/point in a Sublime Text 2 Plugin

I'm writing a plugin for Sublime Text which among other things moves the cursor to the beginning of the document.

Vintage mode has a keybinding for this sort of thing:

{ "keys": ["g", "g"], "command": "set_motion", "args": {
    "motion": "vi_goto_line",
    "motion_args": {"repeat": 1, "explicit_repeat": true, "extend": true,
                    "ending": "bof" },
    "linewise": true },
    "context": [{"key": "setting.command_mode"}]
}

How can I achieve the same effect or call the same command from a plugin?

like image 880
severin Avatar asked Jan 25 '26 12:01

severin


1 Answers

In the default plugins folder there is a plugin called goto_line.py that does pretty much exactly this.

import sublime, sublime_plugin

class PromptGotoLineCommand(sublime_plugin.WindowCommand):

    def run(self):
        self.window.show_input_panel("Goto Line:", "", self.on_done, None, None)
        pass

    def on_done(self, text):
        try:
            line = int(text)
            if self.window.active_view():
                self.window.active_view().run_command("goto_line", {"line": line} )
        except ValueError:
            pass

class GotoLineCommand(sublime_plugin.TextCommand):

    def run(self, edit, line):
        # Convert from 1 based to a 0 based line number
        line = int(line) - 1

        # Negative line numbers count from the end of the buffer
        if line < 0:
            lines, _ = self.view.rowcol(self.view.size())
            line = lines + line + 1

        pt = self.view.text_point(line, 0)

        self.view.sel().clear()
        self.view.sel().add(sublime.Region(pt))

        self.view.show(pt)
like image 122
David Avatar answered Jan 28 '26 19:01

David