Thursday, September 20, 2012

Sublime Text auto-complete plugin development

Introduction

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:
usually: 
\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.
Example:
mysign.py

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
    threading.Thread.__init__(self)

- 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:
           self.save_method_signature(file_name)
- 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
     fileList.append(dirfile)
   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 = re.search('(\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.stop()
   self._collector_thread = MySignCollectorThread(self, open_folder_arr, 30)
   self._collector_thread.start()

ON_QUERY_COMPLETIONS Method

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))
   completions.sort()
                        // 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_obj.name():
    method_str_to_append = method_obj.name() + '(' + 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: https://github.com/wbond/package_control_channel
  3. Add your plugin url from github to the repositories.json file:
Example:
{
     "schema_version": "1.2",
     "repositories": [
         ... 
         "https://github.com/eibbors/Bubububububad",
         "https://github.com/eladyarkoni/MySignaturePlugin",
         "https://github.com/EleazarCrusader/nexus-theme",
         ...
     "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!

82 comments:

  1. Hi!

    If you're interested in doing the same for Python, use the easy interface of Jedi: https://github.com/davidhalter/jedi#api-design-for-ides

    Cheers!
    David

    ReplyDelete
  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?

    ReplyDelete
  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.
    Elad.

    ReplyDelete
  4. Elad,

    This is tremendous! Thanks!

    -- Bobby

    ReplyDelete
  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

    muli

    ReplyDelete
  6. Would you like to support Sublime Text 3?

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

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

      Delete
  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?

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

    ReplyDelete
  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=)

    ReplyDelete
  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

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

    ReplyDelete
  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

    ReplyDelete
    Replies
    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

      Delete
  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

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

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

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

    ReplyDelete
  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

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

    Link Sarahah to Snapchat

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

    ReplyDelete
  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

    ReplyDelete
  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!. ActionLinkWireless.com

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

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

    ReplyDelete
  27. This comment has been removed by the author.

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

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

    ReplyDelete
  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

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



    shriram break free

    ReplyDelete
  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.
    notevibes.com

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

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

    prestige elysian


    ReplyDelete
  38. Thanks for sharing this blog
    [url=http://procinehub.com/]best baby photographer in jalandhar[/url]
    [url=http://procinehub.com/]best fashion photographer in Chandigarh[/url]
    [url=https://www.styleandgeek.com/home-remedies-hair-fall//]home remedies for hair fall[/url]
    [url=https://www.styleandgeek.com/top-25-home-remedies-to-remove-tanning//home-remedies-hair-fall//]home remedies to get rid of tanning[/url]
    [url=https://www.lms.coim.in//]Online Digital Marketing Training[/url]

    ReplyDelete
  39. I really appreciate your post and you explain each and every point very well. Thanks for sharing this information
    http://www.rankingsstar.com

    ReplyDelete
  40. I Appreciate Your Efforts In Preparing This Post. I Really Like Your Blog Articles.
    http://www.healthywealthydiet.in

    ReplyDelete
  41. 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

    ReplyDelete
  42. 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

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

    ReplyDelete
  44. 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

    ReplyDelete
  45. 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

    ReplyDelete
  46. 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

    ReplyDelete
  47. 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

    ReplyDelete
  48. 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

    ReplyDelete
  49. 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

    ReplyDelete
  50. 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

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

    ReplyDelete
  52. 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


    ReplyDelete
  53. 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
    courses

    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

    ReplyDelete
  54. 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.

    ReplyDelete