Writing a Simple Sublime Text 2 Plugin

Introduction

It is strange, but after searching on Habré for the mention of the text editor Sublime Text 2, I almost did not find anything. I hasten to rectify the situation and tell the habrausers about this beautiful tool. First, I’ll talk very briefly about why he is so good, then we will write a simple but useful plugin.

Why Sublime Text 2

I can not say that Sublime Text 2 is the best text editor, but I liked it very much, and here's why:
  • Nice looking dark interface, visual effects and Distraction Free Mode
  • Socket with editable text in miniature. An interesting and really convenient find!
  • Multiple selection and editing
  • All features typical of most advanced editors: syntax highlighting, code formatting, auto-completion, etc.
  • What is not in the box can be downloaded from the repository! Yes, after performing the simplest manipulations in Sublime, a complete package management system appears, almost like in ubunt or debian.
  • If this is not enough - right in the main menu there is an item “New Plugin”. Click on it and write a plugin that implements the functionality we need in Python. This will be discussed.
  • This miracle costs $ 59 for one, or $ 500 for 10 licenses. However, if you do not want to, then you can not pay. There are no restrictions in this case, just a reminder will occasionally pop up.

Formulation of the problem

A real example from engineering practice. Translation of the selected number in the text from decimal to hexadecimal number system. The feature should be accessible from the main and context menus as well as by the keyboard shortcut Ctrl + Shift + H. Execution result: the number in the hex written using numbers and uppercase letters without any leading characters like “0x”. If the selected text is not a number, we swear about this with the status bar. I draw your attention to the fact that the example is intentionally simplified to the maximum, so that the details are not lost: the simplicity of creating plugins for Sublime.

Writing a plugin

Click Tools -> New Plugin ... and see the workpiece. Change the name of the class and write the functional in the run method. I got the following:
import sublime, sublime_plugin
class DecToHexCommand(sublime_plugin.TextCommand):
	MAX_STR_LEN = 10
	def run(self, edit):
		v = self.view
		# Получаем значение первого выделенного блока
		dec = v.substr(v.sel()[0])
		# Заменяем десятичное число шестнадцатеричным или выводим сообщение об ошибке		
		if dec.isdigit():
			v.replace(edit, v.sel()[0], hex(int(dec))[2:].upper())
		else:
			# Обрезаем слишком длинные строки, которые не поместятся в статусбар 
			if len(dec) > self.MAX_STR_LEN:
				logMsg = dec[0:self.MAX_STR_LEN]+ "..."
			else:
				logMsg = dec
			sublime.status_message("\"" + logMsg + "\" isn't a decimal number!")

We save there where the editor with the name dec_to_hex.py suggests

Add menu items. Prescribe a keyboard shortcut

Let's start with the hot keys. In the menu, click Preferences -> Key Bindings-User . A file with settings in the JSON format opens. Most likely empty. Add a line to it
 { "keys": ["ctrl+shift+h"], "command": "dec_to_hex" }

Save. All. In principle, you can already use it. If it doesn’t work, you should look at what is written in the console on this subject (Ctrl + `).
In order to add an item to the context menu, create a Context.sublime-menu file with the following contents:

[  
    {  
        "command": "dec_to_hex"
    }  
]  


I think that, as in the previous case, everything is clear without comment. We save to the same directory in which the plug-in was saved. Those. % USERPROFILE% \ AppData \ Roaming \ Sublime Text 2 \ Packages \ User , for Windows users. In the same place we create the Main.sublime-menu file . I thought that this item would be most appropriate in the Edit menu, so I wrote the following in the Main.sublime-menu file:
[  
    {  
        "id": "edit",  
        "children":  
        [  
            { "command": "dec_to_hex" }  
        ]  
    }    
]

We check. In the main and context menu items should appear called Dec To Hex

That's all. And how to pack our plug-in into a package and share it with friends, as well as other interesting Sublime features, I’ll tell you next time if the topic is interesting to anyone.

References:



UPD: wrote about Dev Builds and the cost of a license. Thanks to Sky4eg , VCoder and vtx

Also popular now: