Javascript autocomplete on Vim for a Rails project

Ken Alex Fassone
Carwow Product, Design & Engineering
2 min readJul 31, 2015

I worked for a couple of years in a C++ shop and got used to one of the best autocompletes available for vim, called ‘YouCompleteMe’. After a while I got used to the tool and I’m sure you can imagine how sad I was to transition to the less powerful autocomplete available for Ruby/Javascript.

I searched high and low for alternatives and I found Ternjs. It’s a Javascript code analysis engine intended to improve the editor’s support for autocomplete, hints, refactoring, type inference… in short, it was exactly what I was looking for.

Interested in setting it up? Let’s make the magic happen!

System, vim setup

First of all, install node and npm, we will need them later.

Done? Cool, now you can install the brilliant Tern plugin for Vim, this plugin will connect to the Tern server API to retrieve the information needed for omnicomplete to work.

Using vundle

Open your ~/.vimrc and add the line:

Bundle "https://github.com/marijnh/tern_for_vim.git"

Save the file and run the following in normal mode:

:so % 
:BundleInstall

Open a shell and run

cd ~/.vim/bundle/tern_for_vim/ npm install

Using pathogen

On a shell run:

cd ~/.vim/bundle 
git clone https://github.com/marijnh/tern_for_vim.git
cd tern_for_vim
npm install

Project configuration

Tern needs to know where to find the js files in your project. To tell Tern where to look, you can create a .tern-project file in your project directory. On our project it looks like this:

//.tern-project.js
{
"libs": [ "browser", "jquery" ],
"loadEagerly": [
"./app/assets/javascripts/*.js",
"./app/assets/javascripts/*/*.js",
"./vendor/assets/javascripts/*.js",
"../carwow-theme/lib/carwow-theme/app/assets/javascripts/responsive/*.js" ],
"dontLoad": ["public/assets"]
}

As you can see I’m pointing the Tern server to the app/assets, and vendor/assets directory. I then configured it to look for .js files from our theme project.

Wait for a little bit — it might take a while to digest the .js files. To see if it’s working, open one of your .js files, type jQuery and run :TernDef. If Tern is working you should receive a message saying see http://api.jquery.com/jquery. If that doesn’t work you can run Tern inside your project folder to look for errors in your configuration file: ~/.vim/bundle/tern_for_vim/node_modules/tern/bin/tern

The result is pretty neat:

Happy Vimming!

Originally published at underthehood.carwow.co.uk on July 31, 2015.

Interested in making an Impact? Join the carwow-team!
Feeling social? Connect with us on Twitter and LinkedIn :-)

--

--