How to open a file and select/highlight several li

2019-09-08 10:08发布

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条回答
时光不老,我们不散
2楼-- · 2019-09-08 11:04

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 like select_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:

  1. ST must already be running, otherwise commands specified on the command line may not get executed, because the plugins haven't loaded yet.
  2. 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.

查看更多
登录 后发表回答