Sublime plug-in development-simple code template plug-in

Source: Internet
Author: User

Recently, I have been using sublime for golang development. The overall experience is quite good. Although it is not as powerful as Eclipse, It is very lightweight and convenient to use, and golang development is enough. Some code is frequently used because of the high reuse rate of some code, and the memory is particularly poor, so I am too lazy to write it on my own every time. I hope that the code template can be directly inserted like other ide plug-ins, so I studied sublime plug-in Development (many people on the internet recommend gist, but it is found that it is slow to apply the gist Plug-In due to network reasons, and it takes a long time each time ).
All plug-ins installed know that sublime plug-ins are developed using python. Therefore, you need to have a preliminary understanding of python for development. The reason is that sublime plug-in development uses python to call the interfaces provided by subline for development, just like MFC, you don't need to pay attention to how each action is implemented at the underlying layer (as you can see). You just need to call these Action interfaces to complete a set of operations.
I will not go into details about the entry-level development process here. There is an entry-level tutorial that has been well explained. It should be relatively simple to add the official interface document:

  • How to Develop the sublime text2 plugin
  • Official sublime development example
  • Sublime2 interface document

The following describes the development of this small plug-in.

I. function determination

It's still the old rule. To do this, you must first sharpen the tool. Let's first determine the plug-in function. Because of the first development, you only need to meet the basic requirements. If you do not plan to develop a function that is too complex, you can determine the function:

  • Add the selected code to the template library
  • Select the specified code inserted to the current position from the template library
  • Some variables can be replaced. For example, replace {date} in the template with the current date.


Ii. Functional Design

Let's analyze these three functions one by one. First, there are many implementation methods. We can store all templates in the same file and use the delimiters for scoring, however, in this case, we need to traverse all the templates to judge whether to delete, modify, and add the template. This will cause a lot of trouble. Therefore, you can directly store a file in each template, and the file name is directly named after the Template Name. This is very convenient to handle. Some people may say that this will not generate a large number of files. Will it be slow to search when there are more files? I have always felt that any program design should balance the complexity and performance of implementation, rather than simply pursuing one aspect. For example, in sublime, the commonly used code templates are actually very limited. Generally, there are dozens of templates (which cannot be remembered even when there are too many templates). It is no problem to directly write files separately, instead, if you want to index the database more efficiently, it would be a bit cool-killing. Of course, for ease of use, it is more reasonable to store data by folder group, but it is not easy to do so now.
It is easy to insert code. First, traverse the template folder and read all the file names for selection. Then, read the corresponding file and insert it to the cursor position.
It is easier to replace variables. Replace the variables before insertion. Of course, you need to add a configuration file to implement custom variables.

Iii. Code Implementation

The code is not detailed. If you have read the previous tutorial documents, the following code is very simple.
First, let's look at the code structure:

Template # template folder codemanage. py # Plug-in code default (XXX). sublime-keymap # shortcut key profile, xxx value platform var-map.conf # Replace variable profile, key = Value

The codemanage. py code is as follows:

#-*-Coding: UTF-8-*-import sublime, sublime_pluginimport osimport OS. pathimport timeimport sysreload (sys) sys. setdefaultencoding ('utf8') # Write a template. If a new template is used to create a file based on the Template Name, overwrite the original file class codetpladdcommand (sublime_plugin.textcommand) in the old template ): def run (self, edit): # obtain the selected content selstr = ''sels = self. view. sel () for sel in sels: value = self. view. substr (SEL) If value = '': Continue selstr = selstr + value + '\ n' if selstr ='': sublime. message_dialog ("select content is empty. ") return def on_done (name): If name ='': sublime. message_dialog ("Template Name is empty. ") return # Write File Path = OS. path. join (sublime. packages_path (), "codemanage", "template", name + ". CTPL ") Try: F = open (path, 'w') print selstr. encode ("GBK") F. write (selstr) failed t exception, E: Print e sublime. message_dialog ("Write template file fail:" + STR (E) return finally: f. close () def on_change (name): Return def on_cancel (): return # enter the Template Name self. view. window (). show_input_panel ('plese input the Code Template name', 'template', on_done, on_change, on_cancel) # Insert the template to the current position class codetplinsertcommand (sublime_plugin.textcommand): def run (self, edit): filenames = [] rootdir = OS. path. join (sublime. packages_path (), "codemanage", "template") for P, D, files in OS. walk (rootdir): filenames = files def on_sel_done (selvalue): If selvalue =-1: Return filename = filenames [selvalue] content = ''if filename = '': sublime. message_dialog ("template is not exist. ") Return Path = OS. path. join (sublime. packages_path (), "codemanage", "template", filename) Try: F = open (path, 'R') content = f. read () If content = '': sublime. message_dialog ("template file is empty") return content = replacevar (content) handle T exception, E: sublime. message_dialog ("Open template file fail:" + STR (E) return finally: f. close () # insert content into the current position sels = self. view. sel () for sel in sels: Self. view. insert (edit, Sel. begin (), content) # Open the selection list self. view. window (). show_quick_panel (filenames, on_sel_done) # process some template replacement variables # Replace the {XXX} variable in the template with the variable in the configuration file (replace the {data} and other information directly) def replacevar (content): varmap = {' {date} ': time. strftime ('% Y-% m-% d', time. localtime (time. time ()} # Read the variable try: Path = OS. path. join (sublime. packages_path (), "codemanage", "var-map.conf") F = open (path, 'R') for line in F. readlines (): If line = '': Continue value = line. split ("=") varmap ["{" + value [0] + "}"] = value [1] failed t exception, E: sublime. message_dialog ("Open var-map file fail:" + STR (E) return finally: f. close () for (K, V) in varmap. items (): content = content. replace (K, v) return content

Python is easy to understand.

Iv. Summary

Although the functions are not complete yet, they are easy to use. It can be seen that sublime plug-in development is relatively simple. After getting started, you can easily customize your own lightweight IDE.
Plug-in address: GitHub


Sublime plug-in development-simple code template plug-in

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.