create sublime text 3 plugin

Sublime Text 3 Plugin to Webify HTML Entities Tutorial

Creating A Sublime Text 3 Plugin

In this article, I want to share with you how to create a basic Sublime Text 3 plugin (or package). Sublime Text 3 (ST3) comes with a running ‘Hello World’ plugin example, however, if you have read any of my previous posts, I am not a big fan of simple ‘Hello World’ applications. I will, however, walk you through setting up the ‘Hello World’ plugin and then we will create our own Sublime Text 3 plugin named ‘Webify’. ‘Webify’ will replace the less than (<) and greater than (>) signs in your block of code to &lt; and &gt;, also referred to as HTML Entities.

If you use the less than (<) or greater than (>) signs in your text, the browser might mix them with tags.w3schools.com

If you do not have Sublime Text 3 setup on your Linux or Windows box, please see my tutorial on How to Use Sublime Text 3 as an IDE. It will guide you through the setup process for Linux and Windows.

create sublime text 3 pluginThe ‘Webify’ Sublime Text 3 plugin (which we will be creating) will translate our HTML code markup characters so we can publish it on the web. In case you did not already know, in HTML, you can’t simply type the string <HTML> without the web browsers interpreter thinking it is actual HTML code for it to interpret. This can cause problems, especially if you are thinking about displaying actual code on your webpage. After you run ‘Webify’ ST3 plugin, your selected block of code will use HTML Entities instead, and therefore can just be copied and pasted to your website to display.

Our Webify plugin will also have an ‘UnWebify’ class to change the code back to HTML tags. Of course you can always use the search & replace utility in ST3, and then undo changes (CTRL + Z), however it gets annoying after a while, and defeats the purpose of this article (I’m assuming you’re reading it to learn how to create a Sublime Text 3 plugin). Especially when your website teaches people how to program. 😉

Finally, we will create a Context-Menu Entry so all we have to do is right click and select our plugin, from the ST3 menu, to run it.

Sublime Text 3 ‘Hello World’ Example

Open Sublime Text 3, then navigate to:

create sublime text 3 plugin

Tools Developer New Plugin

This will open a new ST3 ‘view’ and create a basic ‘Hello World’ plugin example for you, all you have to do is save it in your “Packages/User” directory. Name the file hello-world.py and save it. ST3 uses the Python language hence the .py extension. Here is our ST3 generated ‘Hello World’ example:


#Sublime Text 3 plugin - Hello World
import sublime, sublime_plugin  #import required sublime modules
class ExampleCommand(sublime_plugin.TextCommand): #Create Example Command
	def run(self, edit):
		self.view.insert(edit, 0, "Hello, World!")


To run the above code, you must use ST3 Console. To show the console, goto ‘View Show Console’ (or CTRL+’). Once you have the console up, you can run your plugin by typing:

view.run_command("example")

After running the command you should see a ST3 window with “Hello, World!” written inside it automatically generated by Sublime Text 3.

For more information regarding the Hello World example, I suggest reading:

Sublimetext.info – Good Hello World example explanation.

Sublime Text 3 Layout

It’s important to understand what I mean when I mention region, view, sidebar, and console. If you are having trouble grasping this, I created a very basic diagram:

sublime text 3 plugin tutorial

Create Sublime Text 3 Plugin – Webify

Let’s start creating the Webify plugin. Go ahead and setup the directory structure for our plugin first. In the ST3 Packages directory, create a folder named Webify.

Package directories

Windows%APPDATA%\Sublime Text 3\Packages
Linux~/.config/sublime-text-3/Packages
Mac/OSX~/Library/Application Support/Sublime Text 3/Packages

Next, open a new, blank Sublime Text 3 file and type the following code:


#TechSideOnline.com Webify Sublime Text 3 plugin example

import sublime, sublime_plugin, re, string   #import the required modules

class WebifyCommand(sublime_plugin.TextCommand): #create Webify Text Command
	def run(self, edit):   #implement run method
		for region in self.view.sel():  #get user selection
			if not region.empty():  #if selection not empty then
				s = self.view.substr(region)  #assign s variable the selected region
				news = s.replace('<', '&lt;')
				news = news.replace('>', '&gt;')
				self.view.replace(edit, region, news) #replace content in view

Save the above file as Packages/Webify/webify.py. In the above code, we create a Webify Command.

Commands are an essential building block in Sublime Text. They are simply Python classes that can be called in similar ways from different Sublime Text facilities, like the plugin API, menu files, macros, etc. sublimetext.info

As you can see, the first line of code creates the WebifyCommand class and passes it sublime_plugin.TextCommand. Sublime supports Text Commands and Window Commands (sublime_plugin.WindowCommand). TextCommand is concerned with the current “view” (more on views later) of ST3, while WindowCommand is concerned with commands that operate at the “window” level. Since all our Webify plugin will be doing is replacing text, we are good with the TextCommand().

The next line implements the run() method. The run() method can take an arbitrary number of parameters, however when using TextCommand instance, the run() method requires edit as it’s first argument.

The next few commands deal with the “region” of the view. Region is the current selected user text in the current view. If the region is not empty, then the Webify command will take the selection (region) and pass it to the s variable. We then take the contents of the s variable and replace any < with &lt; and pass it to a new variable news (new string). Lastly, we update the news string and replace > with &gt;.

Finally, our WebifyCommand replaces the selected region in our view to the contents of our news variable, which contain the HTML Entities.

Webify In Action

Open any file with HTML markup in ST3, or simply generate one:


<!DOCTYPE html>
<html>
<head>
	<title>Webify Test</title>
</head>
<body>
        <p>This is the file we will be testing our Sublime Text 3 Plugin - Webify</p>
</body>
</html>

Now, highlight all the code in our HTML file (or CTRL + A) and in the ST3 Console, type:

view.run_command("webify")

This will call our WebifyCommand Python class.

As you can see, Webify will replace the < (less than) and > (greater than) symbols with their HTML Entities. Now you can simply copy the new code inside the ST3 view and paste it into your HTML code, and the browser interpreter will not "interpret" it as HTML markup.

Likewise, let's create a Unwebify command in our existing webify.py file. Append the following bit of code to the file:


class UnwebifyCommand(sublime_plugin.TextCommand):  #Unwebify command
	def run(self, edit):
		for region in self.view.sel():
			if not region.empty():
				s = self.view.substr(region)
				news = s.replace('&lt;', '<')  #reversed from Webify
				news = news.replace('&gt;', '>')  #reversed from Webify
				self.view.replace(edit, region, news)

The UnwebifyCommand class is the same as WebifyCommand class, however the news.replace is translating the HTML Entity back to it's original symbol. It replaces &lt; and &gt; back to < and > respectively, therefore your code should look like HTML markup again.

In the ST3 Console, run the following command to see it in action (make sure you have the text selected):

view.run_command("unwebify")

As you can see, automating this step can save you a lot of time, however using the console and manually typing in view.run_command("webify") or view.run_command("unwebify") is not very convenient. Might as well use Find & Replace feature in ST3, right? Let's solve that issue by adding our Webify plugin/package to the right-click menu (context menu) of our view.

Add Webify Sublime Text 3 plugin to Context-Menu

Sublime Text 3 menus are generated by files with the .sublime-menu extension. These files use the same format as JSON files. The "context-menu" is the menu that pops up when you right-click the view of your ST3 window.

JSON (JavaScript Object Notation) is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML. -- squarespace.com

In our Packages/Webify/ directory, create a file named context.sublime-menu. Copy and paste the following code for our context-menu:


[
{ 
        "caption": "Webify", 
	"id": "Webify", 
	"children":
	[
	{
	"caption": "Webify Selection",
	"command": "webify"
	},
	{
	"caption": "UnWebify Selection",
	"command": "unwebify"
	}
	]
}
]

Once you save it in your project directory (/Packages/Webify/Context.sublime-menu), go back to your HTML file, make a selection and right-click it for the context-menu to pop up. Once the context-menu appears, you should see "Webify" with children "Webify selection" and "Unwebify selection" (as shown in the image below). From now on, all you have to do to take advantage of our Webify plugin is to select the block of code you wish to "webify" and right-click it in Sublime Text 3 and select the appropriate Webify command (Webify Selection, or UnWebify Selection). Lot better than having to use the ST3 console, huh?

sublime text 3 plugin tutorial
Webify and childern in ST3 context-menu

GIT Download Link

To download or clone the complete Webify plugin code:

git clone https://github.com/TechSideOnline/ST-Webify.git

Summary

Congratulations, you have just created your first useful Sublime Text 3 plugin. ST3 makes it easy to create and utilize packages, and modify the layout to make your workflow better. Initially we generated the 'Hello World' built-in example, to look at the structure. We then used a similar structure to create our Webify plugin. After creating the plugin, we learned how to modify Sublime Text 3's menu structure to include our plugin. Feel free to add/edit the code. You can even add more HTML Entity conversions to the Python code for practice.

Further Reading regarding Sublime Text 3 Plugins

One of the best ways to learn to create a Sublime Text 3 plugin (besides improving your Python skills) is to look at the previously included plugins/packages in the Sublime Text 3 installation directory. The following websites may also be useful:

Leave a Reply

Your email address will not be published. Required fields are marked *