Search code examples
pythonsublimetext2sublimetextsublime-text-plugin

Sublime Text plugin class naming convention


In order to create a minimalist plugin for simple tasks in Sublime Text, I do:

  1. Add this line in C:\Users\User\AppData\Roaming\Sublime Text 2\Packages\User\Default (Windows).sublime-keymap" (available from menu Preferences > Key bindings - User):

    { "keys": ["ctrl+alt+enter"], "command": "myplugin123_blah" },
    
  2. I create a Python file with the same name, i.e. myplugin123_blah.py in C:\Users\User\AppData\Roaming\Sublime Text 2\Packages\User\

  3. I create the plugin code:

    import sublime
    import sublime_plugin
    import subprocess
    
    class Myplugin123BlahCommand(sublime_plugin.WindowCommand):
        def run(self):
            command = 'doanything'
            subprocess.Popen(command)
    

It seems that the "class name" should be:

  • The command name, where each _ is removed

  • Each word (separated by _ before it was removed) has to begin by an uppercase letter

  • Add Command at the end of the class name

Thus: myplugin123_blah => class Myplugin123BlahCommand

Is this correct (just found this with trial and error and looking at other examples)? Is this the general naming rule for subclasses of sublime_plugin.WindowCommand ?


Solution

  • Typically this is approached from the other direction - writing a Python plugin with some Text/Window commands and then "translating" that name into one you can call from ST - but in either case, knowing the rules is helpful when you don't want a needlessly unreadable name in your Python code or keybindings etc.

    The unofficial documentation (for ST3, which has the same rules as the deprecated ST2), explains it like this: http://docs.sublimetext.info/en/latest/reference/plugins.html#conventions-for-command-names

    By convention, Sublime Text command class names are suffixed with Command and written as NamesLikeThisCommand. However, command names are automatically transformed from NamesLikeThisCommand to name_like_this. Thus, ExampleCommand would become example, and AnotherExampleCommand would become another_example. In names for classes defining commands, use NameLikeThisCommand. To call a command from the API, use the standardized name_like_this.

    Which matches up with your discovery.