Friday, March 28, 2014

Sublime - Correcting your common misspellings automatically

In the past 8 months or so that I've been using Sublime (version 2, as of this writing v3 is still in Beta), I have found it to be the best coding editor I have ever used.  I was a die-hard UltraEdit fan, but after trying Sublime, I haven't gone back to UltraEdit at all.
Enough with the fanboy raving, now to the meat of this post...
In our coding we use the "local" scope quite a bit.  I have a horrible habit I can't break myself of:  I type "lcoal", not "local", constantly.  Sometimes I catch it, most often the compiler does instead!  So I set out to solve it.
In Sublime, keyboard shortcuts aren't just ctrl+shift+x, they can be series of key combinations, like ctrl+k, ctrl+b to toggle the visibility of the file navigator on the left of the screen.  Sublime also supports macros, which are pre-recorded actions, such as typing.  Here's what you can do.
  1. First, record a macro of what you WANT to type.  To start recording a macro, choose "Record a macro" from the Tools menu or hit ctrl+q.  
  2. Next, type the correct word you want to appear.  In my case, I typed out the letters l-o-c-a-l-(period).   (I only wanted this to kick in when I typed "lcoal.", with the dot.)  
  3. Now, stop recording the macro with Tools...Stop Recording Macro or shift+ctrl+k.
  4. The next step is to save the macro, also available from the Tools menu.  In my case, I saved it as "type-local.sublime-macro" in the folder Sublime suggests, the Packages/User folder.
  5. Now, open your Key Bindings.  From the Preferences menu, choose "Keybindings - User".
  6. Now, add an entry like so:
    , { "keys": ["l","c","o","a","l","."], "command": "run_macro_file", "args": {"file": "Packages/User/type-local.sublime-macro"} }
    You'll notice that the keys value is a JSON array of keys, in order, that I always type incorrectly.  This is the incorrect order.  I want this misspelling to trigger the macro that types it correctly.  
  7. If you don't get the JSON format right (watch your commas and closing brackets and braces), Sublime will tell you and not let you save the file until you correct it.
It's important to note that the keys in the key combination array above are replaced with whatever actually happens.  It took me three times to wonder why my recorded macro of hitting backspace 6 times turned "" into "".  I was actually backspacing over the "cfset" portion of my text.  The key combination is just a trigger and after recognition by Sublime is no longer considered as text you've added to the file.
Enjoy, hope this works out for you!

Acknowledgement:  After much Googling for the right information, this post kind of got me on track, though it doesn't discuss macros specifically.  I needed it to be transparent and not slow down my work.  The use of key bindings combined with macros accomplished it perfectly.

No comments: