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. Thanks for sharing this information is a great help for me.
    digital marketing company in hyderabad

  24. 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

  25. 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

  26. 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

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

  28. This comment has been removed by the author.

  29. 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

  30. 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

  31. 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

  32. 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

  33. 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.

  34. 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

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

    shriram break free

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

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

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

    prestige elysian

  39. 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]

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

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

  42. You have a good point here!I totally agree with what you have said!!Thanks for sharing your views...hope more people will read this article!!!
    Haroon Ullah

  43. Hi, This is nice article you shared great information i have read it thanks for giving such a wonderful Blog for reader.
    bathroom remodeling fort worth tx

  44. Very nice bro, thanks for sharing this with us. Keep up the good work and Thank you for sharing information
    hard drive failure

  45. Hello, I have browsed most of your posts. This post is probably where I got the most useful information for my research. Thanks for posting, maybe we can see more on this. Are you aware of any other websites on this subject.
    remodeling contractors san antonio tx

  46. I think this is one of the most significant information for me. And i’m glad reading your article. But should remark on some general things, The web site style is perfect, the articles is really great : D. Good job, cheers.
    tree removal okeechobee county

  47. Thanks for a wonderful share. Your article has proved your hard work and experience you have got in this field. Brilliant .i love it reading.
    kitchen & bath los angeles ca

  48. 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..
    ac repair west palm beach

  49. Hello, I have browsed most of your posts. This post is probably where I got the most useful information for my research. Thanks for posting, maybe we can see more on this. Are you aware of any other websites on this subject.
    tree removal service greenacres

  50. Thanks for a wonderful share. Your article has proved your hard work and experience you have got in this field. Brilliant .i love it reading.
    kitchen remodeling atlanta

  51. 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..
    ac company royal palm beach

  52. 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.. nyc escorts

  53. A IEEE project is an interrelated arrangement of exercises, having a positive beginning and end point and bringing about an interesting result in Engineering Colleges for a particular asset assignment working under a triple limitation - time, cost and execution. Final Year Project Domains for CSE In Engineering Colleges, final year IEEE Project Management requires the utilization of abilities and information to arrange, plan, plan, direct, control, screen, and assess a final year project for cse. The utilization of Project Management to accomplish authoritative objectives has expanded quickly and many engineering colleges have reacted with final year IEEE projects Project Centers in Chennai for CSE to help students in learning these remarkable abilities.

    Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Spring Framework Corporate TRaining the authors explore the idea of using Java in Big Data platforms.
    Specifically, Spring Framework provides various tasks are geared around preparing data for further analysis and visualization. Spring Training in Chennai

  54. I have been reading for the past two days about your blogs and topics, still on fetching! Wondering about your words on each line was massively effective. Techno-based information has been fetched in each of your topics. Sure it will enhance and fill the queries of the public needs. Feeling so glad about your article. Thanks…!
    best software testing training in chennai
    best software testing training institute in chennai with placement
    software testing training

    software testing training and placement
    software testing training online
    software testing class
    software testing classes in chennai
    best software testing courses in chennai
    automation testing courses in chennai

  55. The development of artificial intelligence (AI) has propelled more programming architects, information scientists, and different experts to investigate the plausibility of a vocation in machine learning. Notwithstanding, a few newcomers will in general spotlight a lot on hypothesis and insufficient on commonsense application. IEEE final year projects on machine learning In case you will succeed, you have to begin building machine learning projects in the near future.

    Projects assist you with improving your applied ML skills rapidly while allowing you to investigate an intriguing point. Furthermore, you can include projects into your portfolio, making it simpler to get a vocation, discover cool profession openings, and Final Year Project Centers in Chennai even arrange a more significant compensation.

    Data analytics is the study of dissecting crude data so as to make decisions about that data. Data analytics advances and procedures are generally utilized in business ventures to empower associations to settle on progressively Python Training in Chennai educated business choices. In the present worldwide commercial center, it isn't sufficient to assemble data and do the math; you should realize how to apply that data to genuine situations such that will affect conduct. In the program you will initially gain proficiency with the specialized skills, including R and Python dialects most usually utilized in data analytics programming and usage; Python Training in Chennai at that point center around the commonsense application, in view of genuine business issues in a scope of industry segments, for example, wellbeing, promoting and account.

  56. Super blog. You have some nice content. Thanks for sharing. McAfee Security Purchase Online

  57. Great efforts put to publish these kinds of articles that are very useful to know. I’m thoroughly enjoying your blog. And Good comments create great relations. You’re doing an excellent job. Keep it up.

    Magento Development Training Course in Chennai Zuan Education

    Selenium Training Course in Chennai Zuan Education

  58. Thanks for sharing an informative blog keep rocking bring more details.I like the helpful info you provide in your articles....Latest Sarkari result are available on this page. We have created this page to provide all the latest information about the latest and Upcoming India Results 2020

  59. This is a great article thanks for sharing this informative information. I will visit your blog regularly for some latest post.I also would like to share some COVID 19 Customised Awareness Vinly Stickers Printing Online.

  60. Thank you for such a wonderful blog. It's a very great concept and I learn more details from your blog. Try
    Elasticsearch Training
    AWS Devops Training
    CyberSecurity Training

  61. If you too are blessed with good programming knowledge or analytical skills and want your knowledge to be used to the best and wish to stand out against the competition, get yourself enrolled to The Best Institute artificial intelligence course in hyderabad

  62. Потрясающе познавательныеда еще удивительно правдивые онлайн гадания для познания нашего будущего - это то, что поразит тебя на портале гаданий. Гадание на имя любимого является действенным быстрым и легким вариантом для получения нужных знаний из информационного поля нашей планеты.

  63. After reading your blog I was amazed. The blog was explained clearly. And I hope all other readers will understand and experience how I felt after reading such a wonderful blog.
    IELTS Coaching in chennai

    German Classes in Chennai

    GRE Coaching Classes in Chennai

    TOEFL Coaching in Chennai

    spoken english classes in chennai | Communication training