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

The secrets of Penacony might soon come...
Version 2.2 of Honkai: Star Rail is on the horizon and brings the culmination of the Penacony adventure after quite the escalation in the latest story quests. To help you through this new expansion is the introduction of two powerful new... | Read more »
The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »

Price Scanner via MacPrices.net

Apple’s 13-inch M2 MacBook Airs return to rec...
Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices currently... Read more
Best Buy is clearing out iPad Airs for up to...
In advance of next week’s probably release of new and updated iPad Airs, Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices for up to $200 off Apple’s MSRP, starting at $399. Sale prices... Read more
Every version of Apple Pencil is on sale toda...
Best Buy has all Apple Pencils on sale today for $79, ranging up to 39% off MSRP for some models. Sale prices for online orders only, in-store prices may vary. Order online and choose free shipping... Read more
Sunday Sale: Apple Studio Display with Standa...
Amazon has the standard-glass Apple Studio Display on sale for $300 off MSRP for a limited time. Shipping is free: – Studio Display (Standard glass): $1299.97 $300 off MSRP For the latest prices and... Read more
Apple is offering significant discounts on 16...
Apple has a full line of 16″ M3 Pro and M3 Max MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free... Read more
Apple HomePods on sale for $30-$50 off MSRP t...
Best Buy is offering a $30-$50 discount on Apple HomePods this weekend on their online store. The HomePod mini is on sale for $69.99, $30 off MSRP, while Best Buy has the full-size HomePod on sale... Read more
Limited-time sale: 13-inch M3 MacBook Airs fo...
Amazon has the base 13″ M3 MacBook Air (8GB/256GB) in stock and on sale for a limited time for $989 shipped. That’s $110 off MSRP, and it’s the lowest price we’ve seen so far for an M3-powered... Read more
13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more

Jobs Board

Licensed Practical Nurse - Womens Imaging *A...
Licensed Practical Nurse - Womens Imaging Apple Hill - PRN Location: York Hospital, York, PA Schedule: PRN/Per Diem Sign-On Bonus Eligible Remote/Hybrid Regular Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Operating Room Assistant - *Apple* Hill Sur...
Operating Room Assistant - Apple Hill Surgical Center - Day Location: WellSpan Health, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.