How to Create a Sublime Text 2 Plugin
Like a lot of people, I write in Markdown, which has great reference-style links.
This is [some text][st] that I am writing.
[st]: http://sometext.com
I do my writing in Sublime Text 2, and I use these links all the time, but I never like to interrupt what I’m writing by searching for URLs. Instead, after I’ve finished writing, I then go through grab out the reference links to be researched.
With this goal, and with the documentation here’s how to create a simple plugin or package for Sublime Text 2.
-
In the Menu Bar, click Tools → New Plugin.
-
This will open a new tab with some default code.
import sublime, sublime_plugin class ExampleCommand(sublime_plugin.TextCommand): def run(self, edit): self.view.insert(edit, 0, "Hello, World!")
- Hit Save, which will open a dialog in the
Packages/User
directory. We don’t want this. Instead, create a new directory within thePackages
directory. Call itExtract Markdown Links
. So, after this, there should be a directory calledPackages/Extract Markdown Links
. Save the file there, and call itMarkdown Links.py
. -
Create a new file (Command + N) and paste in the following code
[{ "id": "markdownlinks", "caption": "Extract Markdown Reference Links", "command": "markdown_links" }]
- Save this file in the directory we created above, calling it
Default.sublime-commands
. - Switch back to your
Markdown Links.py
file, and replace its contents with the following. Save the file.
A quick run through of the code (skip if you like):
import
the necessary modules—the two sublime modules for access to the API andre
for regular expressions.MarkdownLinksCommand
is the name of the class. Note that this name has to correspond tomarkdown_links
(under the keycommand
) in the fileDefault.sublime-commands
. StripCommand
, convert camel-case to underscores, and make everything lowercase to get from the class name to the command.self.view.substr
with this region gets the contents of the currently active document, from the first character to the last.- Extract the matches from the contents.
- Insert the matches, inserting colons and new lines, at the current cursor location.
Now you should be able to run your command. Open up a Markdown file with some reference links, hit Command + Shift + P, and search for ‘Extract Markdown Reference Links’.
💅 Vanilla – hide icons from your Mac menu bar for free
🚀 Rocket – super-fast emoji shortcuts everywhere on Mac… :clap: → 👏
⏳ Horo – the best free timer app for Mac
📂 FastFolderFinder – a lightning-fast launchbar app for folders and apps
📖 Kubernetes – my book on Kubernetes for web app developers
😄 Emoji Bullet List – easily emojify your bullet point lists (like this one!)
Jump on my email list to get sent the stuff that’s too raunchy for the blog.
(Seriously though, it’s an occasional update on apps I’ve built and posts I’ve written recently.)