如何设置或查找Sublime Text插件的命令名称

问题描述

我正在尝试为我的节点js服务器编写ST3插件。为了运行它,我调用命令view.run_command('Node js.nodejs')

我的Sublime Text Packages文件夹如下所示:

│   main.py
│   text_example_one.py
│
├───Node js
│       Nodejs.py
│
└───User
    │   main.py
    │   Package Control.last-run
    │   Package Control.sublime-settings
    │   Preferences.sublime-settings
    │
    └───Package Control.cache
            01524fae79697630d0454ba3fabd9414
            01524fae79697630d0454ba3fabd9414.info

../Packages/Node js/Nodejs.py文件包含以下代码:

import sublime,sublime_plugin

class TryCommand(sublime_plugin.TextCommand):
    def run(self,edit):
        print("It's working")
        self.view.insert(edit,"Hello,World!")

调用view.run_command('Node js.nodejs')时什么也没有发生,请参见the image of the window here

不会引发任何错误,但是不会插入"Hello,World!"消息,并且不会在控制台中打印"It's working"

解决方法

view.run_command('Node js.nodejs')命令不会调用您的插件。为了运行您的插件,您应该调用try命令,例如view.run_command("try")。这是原因的解释:

Sublime Text插件的命令名称源自其类名称。例如下面的类...

class PrintHelloInConsoleCommand(sublime_plugin.TextCommand):
    def run(self,edit):
        print("Hello")

...可以通过调用print_hello_in_console命令来运行。例如

// Run from a plugin or in the console
view.run_command("print_hello_in_console")

// Run from keys by adding a key binding
{"keys": ["ctrl+shift+y"],"command": "print_hello_in_console"},

要从类名获取命令名,请首先从类名中删除Command后缀。其次,将类名的剩余内容从CamelCase转换为snake_case。因此,class PrintHelloInConsoleCommand 命令调用定义了print_hello_in_console的插件。

  • 类名称为:PrintHelloInConsoleCommand
  • 从类名称中删除 Command
    PrintHelloInConsoleCommand --> PrintHelloInConsole
  • CamelCase 转换为 snake_case
    PrintHelloInConsole --> print_hello_in_console
  • 要调用的命令的名称为:print_hello_in_console

您的类class TryCommand(sublime_plugin.TextCommand)可以通过调用tryview.run_command("try")来运行。


还有其他一些例子:

  • class ClearConsoleCommand(sublime_plugin.WindowCommand)
    "clear_console"命令
  • class InsertDateTimeCommand(sublime_plugin.TextCommand)
    "insert_date_time"命令
  • class TestOKCommand(sublime_plugin.TextCommand)
    ""未创建命令-请勿使用大写单词,例如"OK"中的"TestOK"。请注意,这不会创建"test_o_k"命令
  • class MoveSelection(sublime_plugin.TextCommand)
    "move_selection"命令-尽管在类名中省略了"Command",该命令仍然有效。在撰写本文时,该要求尚未由ST严格执行(但在将来的版本中可能会更改)
  • class AutoSaverEvents(sublime_plugin.EventListener)
    ""未创建命令-未调用事件侦听器,因此未创建任何命令,ST也不希望类名以"Command"结尾/ li>

有关插件的更多信息,请参见Sublime Text plugins sectionUnofficial Documentation,其内容比官方文档多得多。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...