Sublime Text 原生的 move 和 move_to 命令不支持作用域或 cmets 作为参数,因此需要在 Python 中创建一个插件来实现此行为,并绑定 End 关键。
从 Sublime Text 的 Tools 菜单中,单击 New Plugin。
将内容替换为以下内容:
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
将其保存在ST建议的文件夹中,名称不重要,只要扩展名是.py。 (键绑定引用的命令名基于 Python 代码/类名,而不是文件名。)
转到 Preferences 菜单 -> Key Bindings - User 并插入以下内容:
{ "keys": ["end"], "command": "move_to_end_of_line_or_start_of_comment" }
当按End键时,它会像往常一样移动到行尾,除非它已经在行尾,并且有注释,在这种情况下它会移到评论的开头。
请注意,这与您的示例略有不同:
var str = 'press end to move the cursor here:'| // then here:|
因为它会将光标移动到代码末尾的空格之后,如下所示:
var str = 'press end to move the cursor here:' |// then here:|
但它应该为您提供一个工作框架。您可以使用view 的substr 方法来获取某个区域的字符,因此您可以很容易地使用它来检查空格。
编辑:请注意,自从编写了此答案以来,我已经为此功能创建了一个包,其中包含一些额外的注意事项、自定义和用例支持,如该问题的另一个答案中所述。