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)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s