Sublime Text Plugin Quickstart

Based on the fact that the Sublime Text plugin example page is outdated below is a quick guide to create a Sublime Text Plugin for Sublime Text 2

  1. Go to Tools > New Plugin to auto generate a template for a plug-in
    import sublime, sublime_plugin
    
    class ExampleCommand(sublime_plugin.TextCommand):
        def run(self, edit):
            self.view.insert(edit, 0, "Hello, World!")
  2. Save it as a .py file in Packages/User folder (it should be the default folder when you select save). I chose testPlugin.py
  3. You can run in from the Sublime Text console (Ctrl + ~ in Windows) using the following command. (if it doesn’t work try, try saving the file again with the console open to see any errors and also try closing and reopening Sublime Text)
    view.run_command("example")

Running Camel Case Commands

Use underscores

class ExampleTextCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        self.view.insert(edit, 0, "Hello, World!")
 view.run_command("example_text")

sublime.Edit & sublime_plugin.EventListener

If an edit object is needed (seems to be needed for writing things on the page), use view.begin_edit() but don’t forget to end_edit()

They can be created by view.begin_edit(). Every call to view.begin_edit() must have a corresponding call to view.end_edit(), typically wrapped in a try … finally block.

Sublime Text 2 API reference

The EventListener class let’s you trigger things on an event happening and the code below shows inserting text to a document when it is opened. (Disclaimer: I’m not fluent in Python so I’m not sure if the below is fully correct but it does seem to work)

import sublime, sublime_plugin
class OnOpenCommand( sublime_plugin.EventListener):
   def on_load(self, view):
       try :
           edit = view.begin_edit()
           view.insert(edit, 0, "on load")
       finally :
           view.end_edit(edit)
Advertisement

Sublime Text: “ImportError: No module named sublimeplugin” i.e. bad plugin documentation

TLDR: Sublime Text’s plugin Examples page is out of date as of 30th May 2014. Look at “How to Create a Sublime Text 2 Plugin” for proper guidance.

For the popularity that Sublime Text gets, it seems that their plugin documentation has been left by the wayside

Their Plugin Examples page is out of date showing an example for SublimeText 1. I found that out when creating the plugin only to see the following error message in the Sublime Text console (Ctrl+~ in Windows)

ImportError: No module named sublimeplugin

Searching for this error I landed on this forum post which the link to “How to Create a Sublime Text 2 Plugin” from Tuts+ which seems to work.

There seems to be a change from camelCase to snake_case for functions thus all the instructions on the plugin page are incorrect.

Links API References: choose appropriate link for Sublime Text version