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

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »

Price Scanner via MacPrices.net

B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more

Jobs Board

Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Business Analyst | *Apple* Pay - Banco Popu...
Business Analyst | Apple PayApply now " Apply now + Apply Now + Start applying with LinkedIn Start + Please wait Date:Mar 19, 2024 Location: San Juan-Cupey, PR Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.