I know subl myfile.txt:5 would open “myfile.txt” on line 5. I however want to be able to, from the command line, open a file with say lines 5,9,15 highlighted or selected. I know adding –command should enable me to do that, but how? What would the command be?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
There's no built-in command that I know of that can do this, but one can easily create one.
(Technically, it could be done using the bookmarks functionality from the Default package, and the built-in "Expand Selection to Line" functionality. However, experience shows that it would be better and more reliable to write a command in ST specifically for this purpose.)
In ST:
- from the Tools menu -> Developer -> New Plugin...
- select all and replace with the following
import sublime
import sublime_plugin
class SelectSpecificLinesCommand(sublime_plugin.TextCommand):
def run(self, edit, lines):
self.view.sel().clear()
for line in lines:
position = self.view.text_point(int(line) - 1, 0) # internally, line numbers start from 0
self.view.sel().add(self.view.line(position))
- save it, in the folder ST recommends (
Packages/User/
) as something likeselect_lines.py
(file extension is important). subl myfile.txt
subl --command "select_specific_lines { \"lines\": [5, 9, 15] }"
(this style of escaping the quotes for JSON strings works from the Windows Command Prompt and Linux's Bash)
Why did I specify the command on a separate line / call to subl
? Because of these 2 caveats:
- ST must already be running, otherwise commands specified on the command line may not get executed, because the plugins haven't loaded yet.
- the command could get executed before the file is loaded.
Arguably, point 2 could still happen with multiple invocations of subl
, but hopefully it is less likely. There is an open issue on the ST bug tracker for better command line command handling: https://github.com/SublimeTextIssues/Core/issues/1457.