Sublime Text's native move
and move_to
commands don't support scopes or comments as an argument, therefore it is necessary to create a plugin in Python to achieve this behavior, and bind the End key to it.
From the Tools
menu in Sublime Text, click New Plugin
.
Replace the contents with the following:
import sublime, sublime_plugin
class MoveToEndOfLineOrStartOfCommentCommand(sublime_plugin.TextCommand):
def run(self, edit):
new_cursors = []
for cursor in self.view.sel():
cursor_end_pos = cursor.end()
line_end_pos = self.view.line(cursor_end_pos).end()
if line_end_pos == cursor_end_pos and self.view.match_selector(line_end_pos, 'comment'): # if the cursor is already at the end of the line and there is a comment at the end of the line
# move the cursor to the start of the comment
new_cursors.append(sublime.Region(self.view.extract_scope(line_end_pos).begin()))
else:
new_cursors.append(sublime.Region(line_end_pos)) # use default end of line behavior
self.view.sel().clear()
self.view.sel().add_all(new_cursors)
self.view.show(new_cursors[0]) # scroll to show the first cursor, if it is not already visible
Save it in the folder ST suggests, the name is unimportant as long as the extension is .py
. (The command name for reference by the keybinding is based on the Python code/class name, not the file name.)
Goto Preferences
menu -> Key Bindings - User
and insert the following:
{ "keys": ["end"], "command": "move_to_end_of_line_or_start_of_comment" }
When pressing the End key, it will move to the end of the line as usual, unless it is already at the end of the line, and there is a comment, in which case it will move to the start of the comment.
Note that this is a tiny bit different to your example of:
var str = 'press end to move the cursor here:'| // then here:|
because it will move the cursor to after the whitespace at the end of the code like this:
var str = 'press end to move the cursor here:' |// then here:|
but it should give you a framework to work from. You can use the substr
method of the view
to get the characters in a certain region, so you can check for spaces using this quite easily.
EDIT: Note that since this answer was written, I have created a package for this functionality with some extra considerations, customization and use case support, as mentioned in another answer to this question.