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
- 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!")
- Save it as a .py file in Packages/User folder (it should be the default folder when you select save). I chose testPlugin.py
- 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.
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)