Introduction

Thanks for joining me for Part 2 of this series. If you haven’t read Part 1, please do so or most of this won’t make sense. In fact, do it. DO IT NOW.

arnoldschwarzeneggerscreamingkindergartencop

Step 4 – Python Syntax

Before we get into modifying the Python code that makes up our plugin, let’s be clear on a few things:

  • Python is case sensitive
  • Indentation is used for classes and functions, no {brackets}
  • Semi-colons at the end of lines are not required but can be used to place several commands on one line

Knowing the above will help you clear syntax hurdles faster, especially if you are used to developing in PHP or other, more forgiving languages. Fortunately, ST3’s syntax highlighter is very helpful in this regard. I also recommend downloading package control and a decent Python Linter to help you troubleshoot easy errors.

Step 5 – Imports & Parameters

If you’ve written in .Net or other similar languages, you will be familiar with imports. They are how you include other code libraries to perform tasks that you don’t want to manually write on your own. These declarations go at the beginning of your plugin and you will see two of them already there:

import sublime
import sublime_plugin

These two imports are required for interaction with ST3 and will be the object that you perform interaction with when using the ST3 methods defined in the documentation. For my project, I also needed some others for handling time, json objects and url parsing.

At this point you should also take a moment to look at the default “run” method being created. You’ll notice two parameters being passed:

def run(self, edit):

“Self” is our default sublime object and “edit” is the edit token which allows our interaction with ST3 through Python. You will see these parameters mentioned throughout the API, so take note as you will be using them again.

Step 6 – Understanding Regions

This is by far one of the more confusing parts of the article, but bear with me, it’s in your best interest. The main confusion here (for me) was how you defined where text is going to be inserted / removed / edited. Even more baffling: ST3 has “multiple cursors” in which you can select multiple areas at the same time and carry out the same task on them. This definitely takes time to get used to, but is very powerful once mastered.

For my example, I was simply trying to select all text and replace it. The example inserts a line at the very beginning of the document instead and doesn’t show how to select. To do this you will use region selection to define a region for manipulation. Let’s look at the following function:

allcontent = sublime.Region(0, self.view.size())

“Region” is Sublime’s built-in function that you use to select an area. It is fed two variables: start and end position. For those of you familiar with cutting a string into pieces by position, it’s the same concept. So when I want to select all content, I feed it 0 for the start and then the length of all the content as the end. This is achieved by using “self.view.size()” which returns the size of the current sublime view being manipulated. We store this region in a new variable called “allcontent.”

The last thing I need to do is replace my region contents using the following line:

self.view.replace(edit, allcontent, 'Hello, World!')

The “replace” method receives the edit token (passed as the second parameter in your run definition), followed by the variable of our region (allcontent) and the string we wish to replace it with. You can use the “erase” method to similar effect (with the third parameter not being included).

Optionally, you can use the following if you wish to play a prank on your colleagues by mapping this to their paste keyboard shortcut:

self.view.replace(edit,allcontent,'                               ,|     \n                             //|                              ,|\n                           //,/                             -~ |\n                         // / |                         _-~   /  ,\n                       /\'/ / /                       _-~   _/_-~ |\n                      ( ( / /\'                   _ -~     _-~ ,/\'\n                       \\~\\/\'/|             __--~~__--\\ _-~  _/,\n               ,,)))))));, \\/~-_     __--~~  --~~  __/~  _-~ /\n            __))))))))))))));,>/\\   /        __--~~  \\-~~ _-~\n           -\\(((((\'\'\'\'(((((((( >~\\/     --~~   __--~\' _-~ ~|\n  --==//////((\'\'  .     `)))))), /     ___---~~  ~~\\~~__--~ \n          ))| @    ;-.     (((((/           __--~~~\'~~/\n          ( `|    /  )      )))/      ~~~~~__\\__---~~__--~~--_\n             |   |   |       (/      ---~~~/__-----~~  ,;::\'  \\         ,\n             o_);   ;        /      ----~~/           \\,-~~~\\  |       /|\n                   ;        (      ---~~/         `:::|      |;|      < >\n                  |   _      `----~~~~\'      /      `:|       \\;\\_____// \n            ______/\\/~    |                 /        /         ~------~\n          /~;;.____/;;\'  /          ___----(   `;;;/               \n         / //  _;______;\'------~~~~~    |;;/\\    /          \n        //  | |                        /  |  \\;;,\\              \n       (<_  | ;                      /\',/-----\'  _>\n        \\_| ||_                     //~;~~~~~~~~~ \n            `\\_|                   (,~~ \n                                    \\~\\ \n                                     ~~ \n')

This will result in all content being replaced with the desired string. Here’s the finished code:

import sublime
import sublime_plugin

class ExampleCommand(sublime_plugin.TextCommand):
	def run(self, edit):
		allcontent = sublime.Region(0, self.view.size())
		self.view.replace(edit, allcontent, 'Hello, world!')

In my case, I wanted to take all of that data and submit it to Premailer for in-line styling, so I used my captured region and sent it as a POST request, then erased the old and inserted the new received content. Again, this is a very simple example, but if you can get yourself familiar with the concepts of importing libraries, manipulating regions and dealing with Sublime’s required parameters, you will be creating hilarious prank plugins … I mean useful* plugins in no time.