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

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 »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »
Explore some of BBCs' most iconic s...
Despite your personal opinion on the BBC at a managerial level, it is undeniable that it has overseen some fantastic British shows in the past, and now thanks to a partnership with Roblox, players will be able to interact with some of these... | Read more »

Price Scanner via MacPrices.net

You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more
Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more
Multiple Apple retailers are offering 13-inch...
Several 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... Read more
Roundup of Verizon’s April Apple iPhone Promo...
Verizon is offering a number of iPhone deals for the month of April. Switch, and open a new of service, and you can qualify for a free iPhone 15 or heavy monthly discounts on other models: – 128GB... Read more

Jobs Board

IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
Top Secret *Apple* System Admin - Insight G...
Job Description Day to Day: * Configure and maintain the client's Apple Device Management (ADM) solution. The current solution is JAMF supporting 250-500 end points, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.