Thursday, September 20, 2012

Sublime Text auto-complete plugin development


Sublime Text is my favorite code editor, It's very fast and lightweight and I find it very useful for web development.

Sublime Text has a nice API to create sublime packages (plugins) and today I'm going to show you step by step how to do so.

For more information, please visit the Sublime Text API documentation.

MySignature Plugin

The Sublime Text editor comes with default auto-complete feature which contains the words in your current file. 
you cannot auto-complete words from another file and if you have methods in your code (of course you have), it contains only the method names.

MySignature plugin solves this problem and add to the auto-complete pop-up box methods from all your project files with their signature:

When you choose a method from the pop-up box, It pastes the method with its signature and all you have to do is to replace the method parameters.

Step By Step AutoComplete Plugin Tutorial

Plugins in Sublime Text are written in Python.
You can view my full plugin code on MySignature gihub.

Create the plugin folder

Create your plugin folder inside the sublime plugins folder:
\Users\<username>\AppData\Roaming\Sublime Text 2\Packages - on windows
/Users/<username>/Library/Application Support/Sublime Text 2/Packages - on mac

Create a new python file inside your plugin directory.

Listen to Sublime Text events

This plugin needs to listen to two Sublime Text events:
  1. When file is saved - to load all the methods from all files into the memory.
  2. When auto-complete pop-up box appears - to display the relevant methods inside.
Create a new class which inherit from sublime_plugin.EventListener (see API):

class MyPlugin(MySign, sublime_plugin.EventListener):
    def on_post_save(self, view):
    def on_query_completions(self, view, prefix, locations):

When the plugin is loaded into the memory, on_post_save becomes a callback to file save event and the on_query_completions becomes a callback to auto-complete events. (when you type ctrl+space or type an exists string)   

ON_POST_SAVE(self, view) Method

First, I get all the opened folders in the Sublime Text editor.

open_folder_array = view.window().folders() // view represents the sublime current view object. (see API)
The next step is to scan all the files inside and load the methods into the memory.
Note that this is a heavy task and the editor may stuck so I uses python thread to do it:

- Import python thread library: import threading

- Create a new thread class: class MySignCollectorThread(threading.Thread):

- Create constructor, send the open_folder_array as a parameter and save it as a class data member.

def __init__(self, collector, open_folder_arr, timeout_seconds):
    self.collector = collector
    self.timeout = timeout_seconds
    self.open_folder_arr = open_folder_arr

- Implement the 'run' method which is called when the thread is started:
def run(self):
    for folder in self.open_folder_arr:
       jsfiles = self.get_javascript_files(folder)
       for file_name in jsfiles:
- Implement the recursive method  get_javascript_files to get all files inside the folder:
def get_javascript_files(self, dir_name, *args):
  fileList = []
  for file in os.listdir(dir_name):
   dirfile = os.path.join(dir_name, file)
   if os.path.isfile(dirfile):
    fileName, fileExtension = os.path.splitext(dirfile)
    if fileExtension == ".js" and ".min." not in fileName: // ignore minified files
   elif os.path.isdir(dirfile):
    fileList += self.get_javascript_files(dirfile, *args)
  return fileList
- Implement the method save_method_signature which search the javascript methods inside a specific file and store it inside an array:
def save_method_signature(self, file_name):
  file_lines = open(file_name, 'rU')
  for line in file_lines:
   if "function" in line:
    matches ='(\w+)\s*[:|=]\s*function\s*\((.*)\)', line)
    if matches != None:
    // store the method somewhere
- Create the thread and run it
if self._collector_thread != None:
   self._collector_thread = MySignCollectorThread(self, open_folder_arr, 30)


This method is called when auto-complete pop-up box is displayed and this method returns an array with tuples:

('<label>', '<text-to-paste>'),

The '<label>' represents the label which will be displayed inside the pop-up box.
This label will be separated with tab ('\t') when the first string is the method signature and the second string is the description (method file in my plugin).
The method description will be displayed in italic font. 

- Implements the on_query_completions:
def on_query_completions(self, view, prefix, locations):
  current_file = view.file_name()
  completions = []
  if self.get_lang(current_file) == 'javascript':
   completions = // get the saved methods from the memory which contains the prefix string
                        // remove duplicate lines
   completions = list(set(completions))
                        // return the array
   return (completions,sublime.INHIBIT_EXPLICIT_COMPLETIONS)
- Implements the method get_autocomplete_list
def get_autocomplete_list(self, word):
  autocomplete_list = []
  for method_obj in self._functions:
   if word in
    method_str_to_append = + '(' + method_obj.signature()+ ')'
    method_file_location = method_obj.filename();
    autocomplete_list.append((method_str_to_append + '\t' + method_file_location,method_str_to_append))
  return autocomplete_list

Publish Sublime Text Plugin

Sublime Package Control is a repository of Sublime Text plugins.

You can activate it with Ctrl+Shift+P shortcut in the Sublime Text editor, type 'package install' and you get a list of plugins to install with just one click.

To publish your plugin to the Sublime Package Manager you must store it as a project inside Gihub.

These are the steps to publish your plugin:

  1. Push your plugin source code to Github as an open source project.
  2. Fork the 'Sublime Package Manager' project from:
  3. Add your plugin url from github to the repositories.json file:
     "schema_version": "1.2",
     "repositories": [
     "package_name_map": {
         "modx-sublimetext-2": "MODx Revolution Snippets",
         "MySignaturePlugin": "Autocomplete Javascript with Method Signature",
         "Nette-package-for-Sublime-Text-2": "Nette",

Then, make a pull request with your changes.
Wait for your pull request to be approved by wbond.

That's It, You are now a Sublime Text Plugin Expert :)
Very simple, very useful and you can do whatever you want to make your perfect code editor!


  1. Hi!

    If you're interested in doing the same for Python, use the easy interface of Jedi:


  2. Hi! Sorry for my bad Engish. I need autocomplete from my personal dictionary (maybe .txt file with words). This dictionary was dont included to project. As example, I use Sublime for write code on Lua for game framefork and I want add functions of that framework to autocomplete. Is it possible with that plugin?

  3. Hi Dmitry,

    This plugin detects functions inside Javascript files (files with .js extension.) which included inside your project directory.
    If the framework is a part of your project and its not minified, MySign plugin will detect its functions.
    I hope that I answered your question.

  4. Elad,

    This is tremendous! Thanks!

    -- Bobby

  5. hello Elad,

    for install the plugin on mac i just need to drag the folder "MySignaturePlugin-master" to "Packages" ?
    i didn't understand all the above explanations (just a beginner)
    does the plgin available via package manager?

    best regards


  6. Would you like to support Sublime Text 3?

  7. Yes indeed!
    As soon as It come out from beta.

    1. the troops are chomping at their bits for sublime 3

  8. Hi Elad,

    This is awesome plugin, just what I needed for my project. I edited this plugin to work with Lua. Is it ok to use and share it it if I credit you in the source?

    There is no license information in this site or in GitHub. Can I assume that this is licensed with MIT license or something similar?

  9. Hi.
    Im very glad to know that my plugun helps you. You can use it as a MIT license and give me some credit.
    Thank you.

  10. Hi Elad. I'm beginner. Can you please describe step-by-spep:
    1) howto install this wonderful plugin on my Windows + ST3. I did not find it in Packadge Control => Install Package.
    2) Howto run it ? I have some .js in my folder. When I creating new file and start typing the name of some func which located in another file nothing happing.. running only default text autocomplete.
    Many thanks=)

  11. Just about every driver tried using to overcom the following driver in manoeuvring through a junction. Hawkers applied the ability supplied by this drivers' eagerness as well as the prolonged targeted traffic jam to sell handkerchiefs to sweaty car or truck occupiers car parts nigeria

  12. Will be good if support prototype function eg:
    o.prototype.nameOfFunction = function(a,b,c){}

  13. Thank you for taking the time to provide us with your valuable information. We strive to provide our candidates with excellent care.As always, we appreciate you confidence and trust in us.

    Digital Marketing Company in Chennnai

    1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or learn thru JavaScript Online Training India. Nowadays JavaScript has tons of job opportunities on various vertical industry. JavaScript Training in Chennai

  14. Superb. I really enjoyed very much with this article here. Really it is an amazing article I had ever read. I hope it will help a lot for all. Thank you so much for this amazing posts and please keep update like this excellent article.thank you for sharing such a great blog with us. expecting for your.
    Digital Marketing Company in India

  15. That was interesting for me. I would like to thank you for adding those materials here. I hope that I'll get more information on the topic from your blog.

  16. The publication of the plugin includes a number of simple operations. This allows you to create your own code editor without any effort.

  17. The editor code of this type is quite effective for the web development. This makes it possible to implement the autocomplete of plugins in more convenient form.

  18. Superb. I really enjoyed very much with this article here. Really it is an amazing article I had ever read. I hope it will help a lot for all. Thank you so much for this amazing posts and please keep update like this excellent article.thank you for sharing such a great blog with us. expecting for your.

    Mobile App Development Company in India

  19. This is awesome plugin, just what I needed for my project. Will give you credit when I use it.

    Link Sarahah to Snapchat

  20. Good post and I like it very much. By the way, anybody try this increase app downloads? I do not how to use.

  21. It is imperative that we read blog post very carefully. I am already done it and find that this post is really amazing. AC Market

  22. I felt very happy while reading this site. This was really very informative site for me. I really liked it. This was really a cordial post. Thanks a lot!.

  23. I have read your article, it is very informative and helpful for me.I admire the valuable information you offer in your articles. Thanks for posting it.. Moviebox

  24. I admit, I have not been on this web page in a long time... however it was another joy to see It is such an important topic and ignored by so many, even professionals. professionals. I thank you to help making people more aware of possible issues. Xmodgames Download

  25. Very useful post. This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. Really its great article. Keep it up. Jailbreak iOS 11.3

  26. The post is indeed useful, since everyone is able to solve the existing issue! I am glad you have shared this information!

  27. This comment has been removed by the author.

  28. Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too. john deere tractor parts

  29. Along these lines, in the wake of spending numerous hours on the web finally We have revealed a person that unquestionably knows what they are talking about an abundance of thanks an extraordinary arrangement magnificent post. Iron Casting

  30. On the off chance that you are moving and have an issue that you figure a clairvoyant could enable you to answer our advanced universe of correspondences has met up with the old as text mystics.text to speech robot

  31. It was a wonderful chance to visit this kind of site and I am happy to know. Thank you so much for giving us a chance to have this opportunity. BMW 5-Series

  32. AWS Training in Bangalore - Live Online & Classroom
    myTectra Amazon Web Services (AWS) certification training helps you to gain real time hands on experience on AWS. myTectra offers AWS training in Bangalore using classroom and AWS Online Training globally. AWS Training at myTectra delivered by the experienced professional who has atleast 4 years of relavent AWS experince and overall 8-15 years of IT experience. myTectra Offers AWS Training since 2013 and retained the positions of Top AWS Training Company in Bangalore and India.

    IOT Training in Bangalore - Live Online & Classroom
    IOT Training course observes iot as the platform for networking of different devices on the internet and their inter related communication. Reading data through the sensors and processing it with applications sitting in the cloud and thereafter passing the processed data to generate different kind of output is the motive of the complete curricula. Students are made to understand the type of input devices and communications among the devices in a wireless media.

  33. Its an incredible joy perusing your post.Its brimming with data I am searching for and I want to post a remark that "The substance of your post is magnificent" Great work.  Online plagiarism checker

  34. It's Really A Great Post. Looking For Some More Stuff.

    shriram break free

  35. Another accommodating component of TTS is the altering of elocution. Now and again, you'll have to modify the articulation of certain surprising words.

  36. The post was really very good.Thanks for sharing
    prestige elysian

  37. Information provided by you is very helpful and informative. Keep On updating such information.

    prestige elysian

  38. Thanks for sharing this blog
    [url=]best baby photographer in jalandhar[/url]
    [url=]best fashion photographer in Chandigarh[/url]
    [url=]home remedies for hair fall[/url]
    [url=]home remedies to get rid of tanning[/url]
    [url=]Online Digital Marketing Training[/url]

  39. I really appreciate your post and you explain each and every point very well. Thanks for sharing this information

  40. I Appreciate Your Efforts In Preparing This Post. I Really Like Your Blog Articles.