Vim for Rails Developers Screencast

words by Brian Racer

Ben Orenstein was kind enough to send me a review copy of his Vim for Rails Developers screencast. Vim is pretty much the only text editor I have used for a few years now and I consider myself a fairly experienced user. This screencast showed me some useful new tips that I have been able to integrate into my daily workflow.

Much of the screencast focuses on the excellent rails.vim plugin, primarily using it to move around your project in incredibly efficient ways. He also covers snipMate, ctags, and searching with ack. I found his advice on using ctags quite useful for jumping around the rails source code.

Ben is well spoken and well paced, and I hope to see more screencasts from him(especially ones focusing on vim). rails.vim in particular has much more functionality to offer that I would love to see covered. If you enjoy the visual/audible style of learning be sure to also checkout vimcasts.org for more vim related screencasts.

This screencast probably best for late-beginner to moderately skilled vim users, but even advanced users will probably learn a new technique or two. It might be a bit overwhelming if you are incredibly new to vim as it’s focus is on usage and not getting things setup or configured.

Overall I feel if you are looking to get serious with vim the $9 will quickly pay for itself.

More resources:

The Screencast: Vim for Rails Developers
My vimfiles
Ben’s vimfiles
Ben’s twitter


Write HTML Faster with Sparkup (Vim and Textmate)

words by Brian Racer

I recently came across a really great Vim(and Textmate) plug-in called sparkup.vim that “lets you write HTML code faster”. It’s actually a small python script, but has editor plug-ins to work with Vim and Textmate. It allows us to write HTML faster by leveraging the terse css selector syntax and converting it the much more verbose HTML.

Selector Expansion

Selector expansion is the plug-in’s primary purpose. It lets you write in a CSS selector syntax that get expanded to full HTML:

#album.photo

If you type that into vim and then press Ctrl-e on that line it will be expanded to:

<div id="album" class="photo">|</div>

This next one is a bit more complicated, I’ll explain what’s going on:

#container > #nav > ul > li.first {Home} + li*2 + li.last {About Us} < <  #content > p*2 < #footer > span.copyright {(c) 2010 Jetpack LLC}
  1. Creating a div with the id of “container”
  2. Creating a div with an id of “nav” that is a child of the “container” div. The > specifies we are creating a child element in the DOM tree.
  3. Creating a ul tag that is a child of “nav
  4. Creating an li tag with the class name “first“. Text in brackets will be plain text placed in-between the tag we are creating.
  5. Creating two sibling li elements. The + denotes what comes next will be a sibling. The * is a multiplier to create any number of similar elements.
  6. Creating an li tag with the class name “last” as a sibling to the previous li elements we have created. It will contain the text ‘About Us‘.
  7. Next now use the < symbol to go up two levels of the DOM tree.
  8. Next we create a div with the id of “content” that will contain two paragraph tags.
  9. We go back up a level and add a footer div that will have a span with the class of “copyright” that contains some boilerplate copyright text.

If we press Ctrl-e on that line, it will be expanded to the following:

  <div id="container">
    <div id="nav">
      <ul>
        <li class="first">Home</li>
        <li>|</li>
        <li></li>
        <li class="last">About Us</li>
      </ul>
    </div>
    <div id="content">
      <p></p>
      <p></p>
    </div>
    <div id="footer">
      <span class="copyright">(c) 2010 Jetpack LLC</span>
    </div>
  </div>

It will also place your cursor in the first empty tag denoted by the |. You can jump around to other empty tags with Ctrl-n (I change this mapping, more on that in a second).

If you are a fan of HAML but forced to use standard HTML in your projects this plug-in might make you a bit happier.

Shortcuts

The other piece of functionality this plug-in provides is a snipMate like shortcuts feature. These act much like snipMate snippets except they are hard-coded into the python script. However most are still quite useful and you can view the python script to review them.

Issues

After installing this plugin I was having tabbing/tab-expansion issues. I believe it’s Ctrl-n mapping which allows you to jump around to empty tags was conflicting with some other plug-in I had installed, possibly SuperTab. I remapped it by putting the following in my .vimrc:

let g:sparkupNextMapping = '<c-x>'

That doesn’t seem to conflict with anything for me, and since it only gets used in normal mode it doesn’t conflict with Tim Pope’s excellent ragtag plug-in (read more on that here).

Video Demonstration

Some of this might make more sense when you see it in action, so watch the following YouTube video(make sure to switch it to 720p for crisper text):

Conclusion

Have fun writing faster HTML! You can see more examples on sparkup’s Github page.


Vim Tips for Ruby (and your wrists)

words by Brian Racer

Each time I am forced to type non-alpha-numeric characters during a coding session I feel that the flow and speed of my typing suffers. Not to mention depending on the size of your hands and how (im)properly you type, those keys can also put extra strain on your wrists. Since Ruby and Rails make extensive use of :symbols and hash-rockets ( => ) I felt the need to optimize their entry.

Hash-Rocket Insertion

" bind control-l to hashrocket
imap <C-l> <Space>=><Space>"

This emulates TextMate’s hash-rocket insertion. Just press Ctrl-L when in insert mode for a hash-rocket and leading quote to be inserted. Thanks to TechnicalPickles for this one.

If you use this with autoClose.vim the trailing quote will be inserted too. There are times when you don’t want quotes surrounding the hash value like booleans and symbols, so use surround.vim and type ds”. Poof! gone are the quotes.

Word to Symbol

" convert word into ruby symbol
imap <C-k> <C-o>b:<Esc>Ea
nmap <C-k> lbi:<Esc>E

This will turn any word into a symbol by prefixing it with a colon. It works in either Insert or Command mode. In command mode just place your cursor over the word and press Ctrl-k. While in Insert mode pressing Ctrl-k will convert the current word you are typing into a symbol.

You could probably make the argument it’s easier just to type the colon. To each his own but I have seen a lot of people who bend their right wrist to press both Shift and ; entirely with their right hand which puts strain on the wrist. Since symbols are often used right before the hash-rocket, chaining these two shortcuts can be a bit more fluid IMHO(the caret denotes the cursor position):

render action^<Ctrl-k><Ctrl-l>
 
# Will be transformed to
 
render :action => "^"

Symbol to Proc snippets

snippet collecta
             collect(&:${1:symbol})${2}
snippet mapa
             map(&:${1:symbol})${2}

The collection.collect(&:symbol) is a great shortcut I use often in Rails, these snipMate.vim snippets make for less awkward entry.

Easy Command Mode Entry

" Easier non-interactive command insertion
nnoremap <Space> :

This one has nothing to do with Ruby, but instead of typing the colon every time to want to enter a new command in Command mode, just hit the spacebar!

Swap Esc and Caps-Lock

Another tip not specific to Ruby or even Vim really. I think using the Caps-Lock key as escape in Vim is the most efficient and quickest way to cancel some commands or exit certain modes. I prefer to swap them at the Operating System level rather than .vimrc hacks because I find the switch convenient in almost all applications, not just Vim. Consult Google to find out how to do it in your OS.

Conclusion

That’s it! If anyone has any other vim tips for ruby I would love to hear them! Also feel free to dig through my dotfiles and vimfiles to glean other tips.


How to keep your Vim Plugins up to date

words by Brian Racer

It’s not too hard to learn something new everyday about vim, but did you know there is an easy way to keep your plugins up-to-date? GetLatestVimScripts is a plugin that can do just that. You can grab the latest version from the webpage, but it’s most likely your distributions vim package already has it (Debian, Redhat, OSX, and MacPorts do anyway – check /usr/share/vim/vim72/plugin).

How does it know where to find updates? Either we manually add information about each of our plugins to a special config file, or plugin authors can embed a special comment in their scripts to be update friendly:

$ head ~/.vim/plugin/rails.vim
" rails.vim - Detect a rails application
" Author:       Tim Pope [email protected]
" GetLatestVimScripts: 1567 1 :AutoInstall: rails.vim
" URL:          http://rails.vim.tpope.net/

" Install this file as plugin/rails.vim.  See doc/rails.txt for details. (Grab
...

The bold-ed line will tell the plugin where to find updates. More on that in a minute. First lets create the directory where updates will be downloaded, and a configuration file will be placed:

mkdir ~/.vim/GetLatest
touch ~/.vim/GetLatest/GetLatestVimScripts.dat

By default the plugin will only download the updates and not install them. To enable auto-install put the following in your .vimrc:

let g:GetLatestVimScripts_allowautoinstall=1

Now run :GetLatestVimScripts or :GLVS. Vim will analyze your plugins, see if they contain information about their download location, and add it to the .dat file. Then it will wget the plugins and install them. If you had any plugins that were update friendly, they are now updated to the latest version! Since not all plugins are update friendly, you may have to manually add lines to the GetLatest/GetLatestVimScripts.dat. The format looks like this:

ScriptID SourceID Filename
--------------------------
294 10110 :AutoInstall: Align.vim
1896 7356 :AutoInstall: allml.vim
1066 7618 :AutoInstall: cecutil.vim
1984 11852 :AutoInstall: FuzzyFinder
1984 11852 :AutoInstall: fuzzyfinder.vim
1567 11920 :AutoInstall: rails.vim
1697 8283 :AutoInstall: surround.vim

The first two lines act as comments but are required, so don’t remove them! Next is the ScriptID which is the script_id url parameter on the plugin’s vim.org webpage (ex: http://www.vim.org/scripts/script.php?script_id=642). Then there is the SourceID which is a url parameter which identifies the version of the plugin (ex: http://www.vim.org/scripts/download_script.php?src_id=8283). The ScriptID is what is compared for newer versions. If you are adding a new plugin, you can just set it to 1, run an update, and the number will automatically be set to the latest version. :AutoInstall: is a flag that signifies the update should be installed after download, and lastly Filename is just the filename of the plugin.

GetLatestVimScripts.dat is an example of my update configuration. Also checkout my vimfiles and dotfiles git repos for more vim and shell scripts you might find useful!


Rails autocompletion in MacVim when using Macports

words by Brian Racer

In moving much of my development over to OS X, I started receiving errors when trying to use vim’s omnicompletion in Rails projects. An excerpt from my vim config to enable that functionality looks like this:

" Turn on language specific omnifuncs
autocmd FileType ruby,eruby set omnifunc=rubycomplete#Complete
autocmd FileType ruby,eruby let g:rubycomplete_buffer_loading = 1
autocmd FileType ruby,eruby let g:rubycomplete_rails = 1
autocmd FileType ruby,eruby let g:rubycomplete_classes_in_global = 1
autocmd FileType ruby,eruby let g:rubycomplete_include_object = 1
autocmd FileType ruby,eruby let g:rubycomplete_include_objectspace = 1

When I tried to auto-complete something(Ctrl^X^O), I would receive the following error:

"-- Omni completion (^O^N^P) -- Searching...Rails requires RubyGems >= 1.3.5 (you have 1.0.1). Please `gem update --system` and try again. Error loading rails environment"

Long story short, I was using MacPort’s ruby/gem packages, but a binary snapshot of MacVim that I downloaded off their website was using the libraries that come with OSX. There is not really a clean workaround for that, but luckily it turns out macport’s macvim builds the latest snapshot. So all you need to is to install macvim with ruby support:

sudo port install macvim +ruby

And you will get nice auto-completion:

macvim_omnicomplete