Sublime Text 3 - 结束键切换行尾和评论开始

Sublime Text 3 - End key toggles end of line and start of comment

如果我没记错的话,在 Eclipse IDE 中,您可以按 End 键转到行尾,然后再次转到行尾你的代码行,在评论开始之前。这是一个以 | 作为光标的示例:

          var str = 'press end to move the cursor here:'| // then here:|

这与当您按下 Home 时它会转到行的最开头,然后再按一次将光标移动到代码开头的方式非常相似,如下所示:

|        |var str = 'press home to toggle cursor position';

有人知道如何在 Sublime Text 3 中实现此功能吗?

Sublime Text 的原生 movemove_to 命令不支持范围或注释作为参数,因此有必要在 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 code/class 名称,而不是文件名。) 转到 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:|

但它应该为您提供一个工作框架。您可以使用 viewsubstr 方法来获取特定区域中的字符,因此您可以很容易地使用它来检查空格。

编辑:请注意,由于写了这个答案,我已经为这个功能创建了一个包,有一些额外的考虑、定制和用例支持,如这个问题的另一个答案中提到的。

多年后,我偶然发现了这个包:https://github.com/SublimeText/GoToEndOfLineOrScope

Sublime 的 scope 文档不是很容易理解,因此需要进行一些挖掘和反复试验,但这里有一个使其工作得很好的键绑定:

{
    "keys": ["end"],
    "command": "move_to_end_of_line_or_before_specified_scope",
    "args": {
        "scope": "comment.line",
        "before_whitespace": true,
        "eol_first": false
    }
},

这使得 End 键在行尾和注释分隔符的左侧之间切换,在任何尾随代码的白色 space 之前。它还将首先移动到代码末尾,然后移动到行尾,从而在预期行为处保存按键。虽然很明显,但很容易调整。

comment 作用域(如上面 Keith Hall 的回答中所用)也有效,但我不喜欢 block/multiline 评论中的切换行为,因此 comment.line 是一个不错的选择找到。