Mac in the Shell: Tweaking Vim
Volume Number: 25
Issue Number: 12
Column Tag: Mac in the Shell
Mac in the Shell: Tweaking Vim
Or, How I learned to love the shell
by Edward Marczak
Welcome
Well, OK, I already do love life in a command shell. I've gotten a lot of good feedback on the Python tutorials in the column, but I've also heard from people looking to get back to bash and shell tips. I figure I can combine those two a little. I've already written about the basics of vi - the console-based text editor. But that's not going to make anyone love it. To love it, you need to control it. Command it. Personalize it. No matter if you're whipping up a shell script, editing a text document or writing a long Python program, a customized vim will go a long way toward making your job easier and more pleasurable.
Refrain
I won't go too deeply into the basic operation of Vim, as I've already done that in a past column (available on-line at http://www.mactech.com/articles/mactech/Vol.22/22.12/2212macintheshell/index.html). I'll mention a few quick reminders, first, though.
On OS X, and most modern Unix machines, vi is just a link to vim, so they're relatively interchangeable. You can still run vim in vi compatibility mode, however, there's rarely reason to do so.
Vim is a modal editor, meaning that your interactions with it depend on a particular mode. The six basic modes are:
Normal mode: In normal mode, you enter editor commands. This is the mode Vim defaults to at start. This is also known as "command mode."
Visual mode: This is like normal mode, however, the movement commands highlight a selection of text. When a command is given, it is executed for the highlighted area.
Select mode: Typing a printable character deletes the selection and starts insert mode.
Insert mode: The most often used mode, the text you type is inserted into the buffer.
Command-line mode: Typing a ":" in normal mode puts the editor into command-line mode where you can execute Ex commands.
Ex mode: After entering a command in command-line mode, you remain in Ex mode.
Turning up the throttle on vim editing will require you to recognize these modes and how to enter and exit them. If you ever do not know which mode you are in, press escape twice: this will put the editor in normal mode.
Don't be Afraid
There are plenty of actions in Vim that even people who have been using it for a while don't always take in. Let's start at the beginning. Open a terminal window and type vim, with no arguments. This brings you to an opening splash screen, ready for action. Figure 1 shows this screen.
Figure 1: Vim at startup.
As mentioned, Vim starts in normal mode. To give Vim a command, type a colon (":") and the command, followed by a carriage return (read: press return). To edit a file, you can specify it with the edit command:
:e some_file.txt
This presumes you know the name of the file. Or does it? Vim supports wildcard completion using the wildchar - Tab by default. The :e command followed by Space-Tab will cycle though the directories and files in the current working directory. You can go one better, though.
One Vim function I rarely see used is the file browser. It's built right into Vim. Rather than supply the edit command with a file, give it a directory:
:e .
...and that directory will be displayed interactively. Figure 2 shows Vim's file browser.
Figure 2: Vim's file browser
As you can see, there's not only a listing of the files in this particular directory, but interactive commands listed along the top portion of the buffer. Pressing 's' will change the sort order between name, time and size. Pressing return will enter the directory under the cursor. Pressing '-' will go to the parent directory. Ultimately, when you find a file you want to edit, just press return while the cursor is over that filename and it will be loaded into the buffer. Go find a file to edit - either your own, download something, or copy and open a lengthy file from /etc. If you're at a total loss, the test file I'm using is up on the MacTech ftp site (ftp://ftp.mactech.com/src/mactech/volume25_2009).
Of course, the vast majority of the time, you'll pass in the name of the file you're initially editing as an argument to Vim. However, there are many times that once you're editing one file, it's nice to know how to open a new file without leaving Vim.
Make it Better
Those tips are fine on their own, but now, you're faced with repeating this in the future, and ultimately editing the file. Vim runs fairly bare-bones out of the box, but there are many settings that can be adjusted. This is done via the :set command. Just to get the hang of it, here are two basic ones that I can't do without in a text editor:
:set ruler
:set number
Turning on the ruler presents a guide in the lower right corner of the Vim window that displays the co-ordinates of the cursor, and a percentage of how deep into the file the buffer is displaying (or "Top" or "Bottom" as appropriate).
Turning on line numbers I personally consider critical. Perhaps not for word processing-like tasks, but certainly for any kind of coding.
Of course, we can do better. First, editors are personal. We like to tweak them until they're just right. I have too many customizations to handle, and there's no way I'm going to type in :set this and :set that each time I run Vim. So let's get this out of the way right now. In your home directory, create a file—using Vim, of course—named .vimrc. This is Vim's default startup file that it will process each time it is invoked. If you like seeing the ruler and line numbers all the time, add:
set ruler
set number
to the .vimrc at the root of your home directory. Note that there are no leading colon characters—.vimrc is read and commands are executed just as if they were typed in ex mode.
One alteration I should mention early: we're using Vim—vi improved—so let's actually take advantage of that. We should always set nocompatible to ditch the vi compatibility mode: there's very little reason anyone needs this nowadays. (What are you waiting for? Go type ":set nocompatible" now!).
I happen to use Vim for just about everything text editing-related. This includes word processing. Vim easily rivals Word or Open Office...if it's configured correctly (and, of course, if you're not trying to use a word processor as a page layout application). Many people don't realize that Vim can even real-time spell-check documents. Here are the options I use in ~/.vimrc for word processing:
set formatoptions=1
set lbr
set linebreak
set wrap
setlocal spell spelllang=en_us
There are many options that are available to you in the formatoptions setting, but I'll just note this one for now: a value of '1' causes one-letter words to break a line where you'd expect (based on current word processing idioms). Similarly, enabling the lbr, linebreak and wrap settings sets word wrap and line breaks to break the way you'd expect.
As you'd expect, the 'setlocal spell spelllang=en_us' incantation enables real-time spell checking. If you're using a plain ASCII terminal, misspelled (and mis-capitalized, etc.) words will be highlighted. Modern terminals will underline the potential mistake.
One other nicety—not a necessity, in my book—is a better wildcard completion when editing a new file. Enabling the wildmenu setting (sadly, not what it sounds like), presents a better wildcard menu. Enable it with set wildmenu, and then try :e<Space><Tab>. You'll see the difference immediately.
Under Your Skin
Now, if you use all the settings shown so far, Vim is a great word processor. But try to edit code now! It'll look pretty ugly as Vim tries to correct all of your "spelling mistakes." We should be able to use Vim as both a word processor and programmer's editor, right? Would I be bringing it up if you couldn't?
There are actually several ways to do this, but I'm going to show you the somewhat manual way, and it relies on key mappings. Vim allows you to map any keyboard key to any Vim function. This includes function keys.
A key mapping is generated with the map command, and consists of keystrokes that Vim will execute when pressed. You can even think of it more as mini-macros. The following map links F7 to disable spelling and F6 to turn it on:
map <F7> <Esc>:setlocal nospell<CR>
map <F6> <Esc>:setlocal spell spelllang=en_us<CR>
Note that you do need to include the colon character here if you're supplying a command. A map needs to represent the exact keystrokes you would press, including the final <CR>.
As far as spelling, you may want to leave spelling disabled by default and enable/disable it at will via function keys. Tailor it to your liking.
Going back to being a great code editor, there are some other basic settings we can enable at this stage:
syntax enable
filetype on
let is_bash=1
set statusline=%F%m%r%h%w\ [FORMAT=%{&ff}]\ [TYPE=%Y]\ [ASCII=\%03.3b]\ [HEX=\%02.2B]\ [POS=%04l,%04v][%p%%]\ [LEN=%L]
set laststatus=2
The syntax enable option gives you what you expect from any code editor: color coded keywords. Setting filetype on allows Vim to recognize files by file extension. The is_bash variable allows Vim to treat bash scripts with a ".sh" extension properly.
Speaking of things you expect from a code editor, particularly one on the Mac: you expect it to look good! If you've been looking at the screen captures in this article thus far and have thought, "yuck!," there's more we can do!
First, you have to be comfortable with the colors you have set up in your terminal. Terminal.app and iTerm both are customizable in this regard. Let's say you choose a terminal with a black background and white text. Two settings that will immediately make things more palatable are:
set background=dark
colorscheme evening
The first setting simply tells Vim that we're using a dark background. From there, we can load a particular color scheme that defines the colors used for various keywords. You can make your own, but Vim ships with several color schemes ready to use. You'll find them in /usr/share/vim/vim72/colors. Load up a file, and then try different schemes interactively until you find one that is easy on your eyes. Using everything we've come up with so far, editing your ~/.vimrc file in vim will look like the picture in Figure 3.
Figure 3: Vim in color
That's much better, isn't it?
Let it Out and Let it In
While we've just scratched the surface with built-in settings, there's another way to modify Vim's behavior: plugins.
Plugins sit in your ~/.vim/plugin directory and are loaded automatically as part of Vim's startup initialization. At their most simple, plugins are just Vim scripts: nothing more than you can already do in ~/.vimrc. At this level, it's a nice way to modularize different functions of all the different bits of configuration. However, there's more, and I need to admit something.
I don't use the version of Vim that ships with OS X. There, I said it. Some of the cooler things you can do with Vim require functionality to be included at compile time. Unfortunately, Apple's version misses many of these additions. There's two ways to get a version of Vim with these extra options.
First, you can go download a pre-compiled version. Particularly attractive is the MacVim distribution. This gives you a GUI (Aqua) version of Vim, along with a command-line version. The pure command-line version is found inside the MacVim.app bundle at Contents/MacOS/Vim. This is the best of both worlds.
Secondly, you can compile your own. Macports makes this particularly easy. I include the +python, +huge, +perl and +ruby variants. If you're already using Macports, this is a logical way to go.
Finally, another little tip: Vim takes advantage of higher color modes of terminals. Apple's own Terminal.app is constrained to 16 colors. iTerm, however, is not constrained in such a way and supports 256 colors. iTerm and Vim in 256 color mode is a wonderful combination. If you go back and forth between iTerm and Terminal.app, there's a nice solution to having the best display for each. You can conditionally set the color depth. I have iTerm set $TERM to "xterm-256color" and test for this within ~/.vimrc:if &term ==? "xterm-256color"
set t_Co=256
colorscheme evening
else
colorscheme default
endif
You can determine the value to test for by checking for the value of $TERM in your shell.
Back to plugins. Where does one obtain plugins? One place to start is vim.org: there's a huge amount of them on the scripts page (http://www.vim.org/scripts/index.php). Otherwise, you'll typically find them by search once you're using Vim for a while and think, "I wish Vim could (insert wish here)." That's when you find that other people had that wish, too, and did something about it. Most plugins come with instructions on how to install (drop this file in your ~/.vim/plugins directory) and the commands or functionality they enable. Some of my favorites:
MiniBufExplorer: Emulate tabbed editing. Show a 'tab' for each buffer open for editing. Info and download at http://www.vim.org/scripts/script.php?script_id=159.
Snipmate: TextMate style snippets for Vim. If you write any amount of code, Snipmate accelerates. Description and download at http://www.vim.org/scripts/script.php?script_id=2540 - be sure to watch the video linked to in that page to see it in action.
Taglist: If you're using Vim as a code editor and load anything with more than a handful of functions, you should look at taglist
(http://www.vim.org/scripts/script.php?script_id=273). Taglist shows an overview of code in a separate pane, showing variable names, functions and more.
commentToggle: Toggle comments on and off for a given line or block of text. Information and download at http://www.vim.org/scripts/script.php?script_id=2431.
Again, it's likely that you won't find something until you realize that you need it and go searching.
You'll Begin to Make It
Learning Vim/vi—even just the basics—is really one of the more useful things you can do as a techie. You'll find it on just about every system you touch, certainly all OS X machines. This is especially great when troubleshooting a remote machine over ssh. You won't always have your favorite GUI editor, but Vim will always be available. Vim is the default editor when you create a new account, and will likely remain that if you're on a foreign system. Man pages use vi key bindings to navigate.
If you come to rely on your now customized set up, you can either work in an environment where you always mount your home over the network, or, you can just keep your settings available on a flash drive or someplace accessible. Really, though, for the most part, just learning the basics well (opening files, cursor movement) will serve you in the vast majority of the situations where you'll need it.
Media of the month: Here's a good next step for the people now infatuated with Python after the last few columns - "Python Programming: An Introduction to Computer Science" by John Zelle. This book really focuses on algorithms and high-level practices of computer science. It just happens to use Python as the language for delivery.
Finally, remember that Macworld is only a short time away. MacTech will be there, and we hope to see you, too. It's not too late to make plans to attend.
Until next month, keep practicing!
Ed Marczak is the Executive Editor of MacTech Magazine. He has written for MacTech since 2004.