Vim

Article by on September 19, 2012, last modified on August 14, 2014

About

Vim is a text editor that is very simple and lightweight, but extremely powerful. Some would say it's too simplistic (i.e. the EMACS camp?), and others would say it's too complex (i.e. the GUI of any kind camp?). Almost no one starts out in an editor like Vim or EMACS these days, and admittedly there is a large learning curve. However, there are success stories, I included, and I believe it is worth the short term overhead because of the productivity achieved in the long term.

One important thing to keep in mind when working with Vim is best said by Alexis Sellier on cloudhead.io:

Insert mode is vi's weakest mode. In this mode, it's no better than any other editor, and you may as well be using any other editor. Vi's true power lies in its 'Normal mode'. Yes, inserting text is not normal in vi-land. The more time you spend in Normal mode, the more super-powers you will have.

I love Vim, but I think Will Haldean Brown's problem with Vim should serve as a disclaimer to anyone interested:

Vim has reduced me to a pathetic teary wreck every time I have to use a text editor that isn't vim.

Coming Soon

Thanks to a post on Intermediaware, I'm going to be trying the following three plugins out at some point and I'll post my findings here:

  • Taglist - quickly list and navigation functions and variables in a file.
  • SnipMate - very basic but extremely useful code completion, similar to TextMate's snippets.
  • tComment - quickly comment in/out lines of code with language detection, including HTML and PHP.
  • Jon Cairns wrote an excellent article on "Using Vim as a PHP IDE", and at some point I will process it and update this page with things I find useful. In the mean time I highly recommend it for PHP devs who like Vim.
  • Thomas Hunter II also wrote an article about "VIM as a PHP IDE" which I will look at too.
  • And Thomas Koch has an article "VIM as a PHP IDE"
  • And Tobias Schlitt explains his Vim setup in his article "Comfortable PHP Editing With VIM -8-"
  • This is a great presentation "VIM for (PHP) Programmers", I discovered a lot of tips that I'll include from it at some point.

Cheat Sheet

By far the best cheat sheet is Laurent Gregoire's: http://tnerual.eriogerg.free.fr/vim.html. You can download the PDF here.

Configuration

Tip! For getting a quick configuration file, theming, and a couple plugin options, check out Sachet: yoursachet.com. It is pretty much amazing.

How to make MacVim maximize both vertically and horizontally

I have been waiting for this trick for a long time. Thanks to a wiki on GitHub, all you have to do is run:

$ defaults write org.vim.MacVim MMZoomBoth 1

And, logout and login. Now, when you hit "Zoom" (i.e. maximize) on the MacVim window it will maximize in both directions.

How to toggle line numbers

Option 1: Use set

To turn on line numbers type:

:set nu

To turn off line numbers type:

:set nonu

Option 2: Map a shortcut

A much easier way is to make this a shortcut. I set mine to CTRL+n by adding the following to my .vimrc:

nnoremap <C-n> :set nonumber!<CR>

Now, hitting CTRL+n will toggle line numbers.

The Status Line

The status line is a nice little bar at the bottom of the screen that tells you fun information. The possibilities are endless:

And don't forget to turn on the status line by adding "set laststatus=2" to your vimrc.

Paste

The paste command is 'p'. But, if you're reading this you will probably already know that. What you may not know is how to prevent auto-indenting when you paste. The Vim Wiki's suggestionworks perfectly. Simply add the following to your vimrc:

set pastetoggle=<F2>

Then, before you paste hit F2, then paste, then hit F2 again to toggle out of paste mode. Alternatively, you can simply type ":set paste" and then ":set nopaste" when you are done pasting.

Navigation

Navigating a File

For basic navigation, please refer to: http://www.thegeekstuff.com/2009/03/8-essential-vim-editor-navigation-fundamentals/. The most important things to remember:

  • j - down a line
  • k - up a line
  • h - left a character
  • l - right a character
  • H - top of the window
  • M - middle of the window
  • L - bottom of the window
  • gg - top of a file
  • G - bottom of a file
  • A - insert at end of the line (and then hit escape if you want to get out of insert mode; I remember this instead of "$")
  • I - insert at beginning of the line (and then hit escape if you want to get out of insert mode; I remember this instead of "^")
  • o - insert below the current line
  • O - insert before the current line

And, here is some more advanced navigation to remember:

  • zt - scroll current line to top of window
  • z. - scroll current line to middle of window
  • zb - scroll current line to bottom of window
  • } - the next blank line
  • { - the previous blank line
  • w - the next word (also W)
  • b - the previous word (also B)
  • ci<char> - delete and insert text between <char>; for example, ci" will find the nearest enclosing quote characters, delete that text, and place your cursor there for inserting

Navigating Windows

Here are some basic commands for navigating windows:

  • CTRL+v - split window vertically
  • CTRL+n - split window horizontally, opening a new buffer in top window
  • CTRL+w<direction> - move to the window in <direction>, where <direction> is l (left), h (right), k (up), j (down); for example, CTRL+wh will move to the right window
  • CTRL+- - will resize the current window to take the full height of the screen
  • CTRL+| - will resize the current window to take the full width of the screen
  • CTRL+= - will resize all windows to the same size

For more tips, check out http://vimdoc.sourceforge.net/htmldoc/windows.html and http://robots.thoughtbot.com/post/48275867281/vim-splits-move-faster-and-more-naturally.

Navigating the File System

For navigating the file system, please refer to: http://stackoverflow.com/questions/1445992/vim-file-navigation. However, CTRL-P is a must-have. For installation, check out the home page. The basic usage is:

  • hit "CTRL + P" (this gets you into "CTRL-P" mode)
  • start typing anything: the full path to the file, part of the path, the full file name, part of the file name
  • if the current line is the file you want, hit "ENTER", else (a) keep typing, or (b) hit the up and down keys to select a different file

Here are some other commands to remember:

  • :e <filename> - will open <filename> in the current window
  • CTRL+f - will open the filename under the cursor in a window above the current window; this is very useful if you open a directory, for example if you run ":e /tmp"

.vimrc

Your .vimrc file is a file that you create and place in your user's home folder to customize how vim operates and to extend it. You can see my .vimrc file on my GitHub account.

Linting

If you frequently work with XML, JSON, JavaScript, or any other markup or programming language you will want a quick way to lint a file. To make this easier I have added the following shortcuts to my .vimrc:

let @x = ":%!xmllint --format %\n"
let @s = ":%!jsonlint %\n"
let @j = ":%!jshint --show-non-errors %\n"
:map @jj :%!js-beautify %"

Now, if I'm editing an XML file I can hit "@ + x" and Vim will run xmllint on the file. In the same manner, "@ + s" will run jsonlint and "@ + j" will run jshint, linters for JSON and JavaScript respectively. What is really handy about these commands is that they will also "prettify" the file. At least in the case of xmllint and jsonlint. However, there is no linter + prettifier combo for JavaScript. So, I added the last line there which runs js-beautify on the file when I hit "@ + j + j".

It is important to note that these shortcuts will overwrite the current buffer for the opened file with the output from xmllint, jsonlint, etc. This is nice because if there are errors it will print them in your current buffer and you can just hit "u" and Vim will revert the buffer back to the previous state. Obviously, you wouldn't want to save the file after you've run one of these "@" shortcuts I'm mentioning or it will overwrite the file.

Installing Linter Tools

I suppose I should also mention how to install these tools:

  • xmllint: this should be already on your system, though you may have to go find it.
  • npm (required for jsonlint, jshint, and jslint): $ sudo port install npm
  • jsonlint: $ npm install jsonlint -g
  • jshint: $ npm install jshint -g
  • js-beautify:
    1. $ git clone https://github.com/einars/js-beautify.git
    2. $ cd js-beautify/python/
    3. $ ./setup.py build
    4. $ sudo ./setup.py install
  • jslint: (an alternative to jshint): $ sudo npm install jslint

For some other ideas, specifically for JavaScript, check out this Stack Overflow thread: http://stackoverflow.com/questions/473478/vim-jslint.

Minifying

JavaScript

First of all, thank you Gabriel at Low Fat Cats design for the blog post and bash script that makes YUI Compressor much more usable from the command line, specifically, for supporting compression of multiple files. Now, here is how to get a shortcut in Vim for minifying JavaScript:

  1. Install YUI Compressor
    1. Download the latest YUI Build Tool
    2. Copy the latest yuicompressor-*.jar file to /usr/local/lib (in other words, replace "2.4" with the latest):
      $ cp ~/Downloads/builder/componentbuild/lib/yuicompressor/yuicompressor-2.4.jar /usr/local/lib/
    3. Download Gabriel's yuicompressor bash script from Low Fat Cats design
    4. Configure the script by changing line 8 to point to the YUI Compressor jar file:
      YUI=/usr/local/lib/yuicompressor-2.4.jar
    5. Copy the script to /usr/local/bin:
      $ sudo cp ~/Downloads/yuicompress /usr/local/bin/
    6. Make the script executable:
      $ sudo chmod +x /usr/local/bin/yuicompress
  2. Finally, add our shortcut to your .vimrc:
    :map @jm :%!yuicompress -s %<cr>

Now, when we hit "@ + j + m" it will replace the current buffer with the minified contents of the file.

Syntax Highlighting

CSS

Thanks to a StackOverflow thread I found a nice syntax for LESS sheets: https://github.com/groenewege/vim-less.

Installation for me was as follows:

  1. Install Tim Pope's pathogen script (also on GitHub)
    1. Make sure you have "autoload" and "bundle" folders inside your .vim folder:
       $ mkdir -p ~/.vim/autoload ~/.vim/bundle
    2. Add the pathogen.vim file to the .vim/autoload folder:
       $ curl -Sso ~/.vim/autoload/pathogen.vim https://raw.github.com/tpope/vim-pathogen/master/autoload/pathogen.vim
    3. Add the following to your .vimrc file:
       execute pathogen#infect()
  2. Install Gunther Groenewege's vim-less repo:
    1. Make sure you have the "bundle" folder created:
      $ mkdir -p ~/.vim/bundle
    2. Download the vim-less repo to ~/.vim/bundle
      $ cd ~/.vim/bundle
      $ git clone https://github.com/groenewege/vim-less
    3. Add the following to your .vimrc:
      nnoremap ,m :w <BAR> !lessc % > %:t:r.css<CR><space>

Encryption

Vim is actually a pretty great encryption tool. The default encryption is not that great, but you can integrate it with GPG.

Vim and GPG

  1. Install James McCoy's GNUPG Vim plugin (also on GitHub). The easiest way I've found is to use Tim Pope's Pathogen plugin, and then:
    $ cd ~/.vim/bundle
    $ git clone https://github.com/jamessan/vim-gnupg.git
  2. Next, you are ready to write a file:
    1. Open up a new file:
      $ vim file.gpg
    2. Here you will see two windows, in the top one enter the recipient on a new line. If the user isn't in your GPG keyring already, it will give you fits. After typing the recipient's email, save and exit the window.
    3. In the second window, type your message. When done, save and exit.
  3. Now, when you open the file, it will prompt you for the passphrase to your GPG key.

As Tyler Wagner writes, you will want to add the following to your .vimrc file:

let g:GPGPreferArmor=1

This flag will save the GPG file in an ASCII format, which will allow you to copy and paste into an email, for example.

Further Reading

Older Articles »