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

问题描述 投票:0回答:2

如果我没记错的话,在 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 中实现此功能吗?

sublimetext3 sublimetext
2个回答
2
投票

Sublime Text 的原生

move
move_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 代码/类名,而不是文件名。) 转到
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:|

但它应该给你一个框架来工作。您可以使用

substr
view
方法来获取特定区域中的字符,因此您可以很容易地使用它来检查空格。

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


0
投票

多年后,我偶然发现了这个包: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 键在行尾和注释定界符左侧之间切换,在任何尾随代码的空格之前。它还将首先移动到代码末尾,然后移动到行尾,从而在预期行为处保存按键。虽然很明显,但很容易调整。

它也可以用于突出显示/选择文本,例如。使用 Shift 键。

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

comment
范围(如上面 Keith Hall 的回答中所用)也有效,但我不喜欢块/多行评论中的切换行为,所以
comment.line
是一个不错的发现。

© www.soinside.com 2019 - 2024. All rights reserved.