TweetFollow Us on Twitter

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.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.