Jon
Jon

Reputation: 40062

Setting caret position in Sublime

I have a plugin which opens a file and then when loaded calls

view.run_command("goto_line", {"line": item["Line"]})

In the gutter in the left hand side it seems to go to that line as its line number is highlighted in the gutter however, there is no caret in that file. Is there someway to get the caret to start blinking on that line too?

UPDATE: I have noticed if the file is already opened the caret appears on that line so its only when you open a closed file that the caret is not there

Upvotes: 1

Views: 281

Answers (1)

Austin Dean
Austin Dean

Reputation: 414

Short Story:

I ran into this issue far too many times while developing a plugin. Here's the line that did it for me:

self.view.window().open_file("{0}:{1}:{2}".format(full_file_path, line_num, 0), sublime.ENCODED_POSITION)

This will open full_file_path and jump to line_num, even if the file is not already opened.

Long Story:

The first few words of this line will depend on what your command class inherits from. For my purposes, this line is placed in a class that extends sublime_plugin.TextCommand. Classes that extend sublime_plugin.TextCommand do not have a direct way of communicating with the window. Instead, they reference window as a method of the view object, which is native to sublime_plugin.TextCommands. (The method returns a reference to the window object).

If this line were to be placed in a class that extends sublime_plugin.WindowCommand, it would need to be modified as such:

self.window.open_file("{0}:{1}:{2}".format(full_file_path, line_num, 0), sublime.ENCODED_POSITION)

Notice: no view object, and the parentheses following window are omitted because we're no longer referencing it through a method of view.

As seen here, the window() method "returns a reference to the window containing the view," thus allowing us access to these methods even though we're not inhereiting directly from sublime_plugin.WindowCommand.

Upvotes: 2

Related Questions