我想创建一个键盘快捷键(如CTRL + T),它会在出现固定文本后自动将光标移动到该行,例如&todo
。
例:
foo
bar
&todo
fix bug #783
blah
blah2
按CTRL + T会自动将光标移动到以fix ...
开头的行。
目前我这样做:
&todo
,ENTERSearch
底部面板)但这需要太多的行动。
如何在单个快捷键中执行此操作?
最好的解决方案是使用插件来做到这一点。
下面的插件可以满足您的需求。它将在当前光标位置下方找到下一次出现的pattern
(即&todo
标记),将光标移动到它下面的线,并将该位置置于窗口中心。如果在当前光标位置下方找不到pattern
,它将从缓冲区顶部再次搜索,提供环绕特征。
将以下Python代码复制并粘贴到缓冲区中,并将其作为User
保存在Sublime Text config GoToPattern.py
文件夹中。
import sublime
import sublime_plugin
class GotoPatternCommand(sublime_plugin.TextCommand):
def run(self, edit, pattern):
sels = self.view.sel()
# Optional flags; see API.
flags = sublime.LITERAL | sublime.IGNORECASE
start_pos = sels[0].end() if len(sels) > 0 else 0
find_pos = self.view.find(pattern, start_pos, flags)
if not find_pos and start_pos > 0:
# Begin search again at the top of the buffer; wrap around
# feature, i.e. do not stop the search at the buffer's end.
find_pos = self.view.find(pattern, 0, flags)
if not find_pos:
sublime.status_message("'{}' not found".format(pattern))
return
sels.clear()
sels.add(find_pos.begin())
self.view.show_at_center(find_pos.begin())
row, col = self.view.rowcol(find_pos.begin())
self.view.run_command("goto_line", {"line": row + 2})
# Uncomment for: cursor to the end of the line.
# self.view.run_command("move_to", {"to": "eol"})
添加键绑定:
// The pattern arg, i.e. "&todo", can be changed to anything you want
// and other key bindings can also be added to use different patterns.
{"keys": ["???"], "command": "goto_pattern", "args": {"pattern": "&todo"}}
如果需要,可以向Default.sublime-commands
添加命令调色板条目:
{"caption": "GoToPattern: &todo", "command": "goto_pattern", "args": {"pattern": "&todo"}},
这些链接可能对您有用ST v. 2 API和ST v. 3 API。
附:你知道Sublime Text有书签吗? [以防万一你没有。]
我找到了一个解决方案:要做到这一点,首先在gototodo.py
中创建一个包含以下内容的"C:\Users\User\AppData\Roaming\Sublime Text 2\Packages\User\"
文件:
import sublime, sublime_plugin
class GototodoCommand(sublime_plugin.TextCommand):
def run(self, edit):
contents = self.view.substr(sublime.Region(0, self.view.size())) # https://stackoverflow.com/questions/20182008/sublime-text-3-api-get-all-text-from-a-file
a = contents.find('&todo')
cursors = self.view.sel()
cursors.clear()
location = sublime.Region(a, a)
cursors.add(location)
self.view.show_at_center(location)
(row, col) = self.view.rowcol(self.view.sel()[0].begin()) # go to the next line
self.view.run_command("goto_line", {"line": row+2})
然后在"C:\Users\User\AppData\Roaming\Sublime Text 2\Packages\User\Default (Windows).sublime-keymap"
中添加:
{ "keys": ["ctrl+t"], "command": "gototodo" }
完成!