close

Day 3: Code from anywhere with a survival guide for Vim & the command line

Picture the scene: after a hard year of geekery, you’ve decided to spend a week out in the sticks to get away from it all. You’re cosied up by the fire in your remote cottage when suddenly you get the call every dev dreads – “the site’s down!”

It’s your biggest client, you’re the only one who can help and no, it can’t wait until next week. The problem needs to be fixed quickly, both for your professional and personal sanity.
The only problem is that your work machine’s at home and all you have is the knackered old laptop you use for watching DVDs. To compound things, your cottage doesn’t have broadband so you’re stuck with a 3G dongle for a ’net connection. How are you going to get out of this one?

The answer is a program that celebrated its 20th birthday this year – Vim. Vim was born as a clone of the much-older vi, but gradually added extra features and is now pretty much standard issue with Unix-like operating systems including Apple’s OS X.

Simply put, Vim is a text editor you can use on the command line. If you can SSH into the box, you can fix whatever the problem is without having to download and install IDEs, FTP programs and the like – get in, make the fix, get out.

SSH connections are also very light on bandwidth, so you can use them without problems even on a slow connection. All of which makes Vim the perfect solution for our worst-case scenario here.

What You’ll Need

The requirements list for this is pretty short. You’ll need:

  1. A machine running a Unix-like OS containing the files you want to edit
  2. A machine on which you’ll run your command line client (this can be the same machine)
  3. A command-line client – my recommendation is Terminal for Mac users and PuTTY for Windows users. If you’re using Linux then just use whatever the default text terminal is in your flavour of Linux.

If you’re logging into an external machine then you’ll need to know its IP address or URI and the SSH login details. Not all servers will have SSH enabled, especially if you’re on cheaper shared hosting, but check with your provider.

Get Connected

The first step is to make a connection to the machine you want to work on. If you’re working on your local machine, you can skip to the next section.

Mac / Linux Users: Connecting with a Terminal

Starting up an SSH connection from a terminal is very simple. All you need to do is type:

ssh [username]@[IP address / URI]

…and you’re away!

Windows Users: Connecting with PuTTY

PuTTY gives you lots of options but it already has a comprehensive user guide so I’ll keep it brief here. Just fill out the host name (or IP) field, hit “Open” and PuTTY will connect you to the server, prompting you for the login details.

Closing Your Connection

Once you’re finished working on the server you’ll want to disconnect. To do this simply type exit and your session will be ended gracefully.

Locating the Files

The second step is to ascertain where the files you want to edit reside. You’ll be in the home directory for your user account, which will hopefully be your document root too. Try typing ls and then hitting return. That’s the list command and lists the contents of the current directory. If you see a familiar list of files or folders then you should be good. If not, you might need to do a bit of navigation.

A good first move in this situation is to use the locate command. This is essentially a system-wide search which can find files for you very quickly.

You use it like this:

locate [filename]

This returns a list of files which match the search. So if you know the name of the file you need to edit, you should be able to easily find its full path.

locate will often return a long list of files, particularly if they have a common name so be as specific as you can. You can include directories as well, so if you know what directory said folder is in you can narrow the search down. For example:

locate bigclient/checkout/payment_details.php

You can even use regular expressions in the search if you want.

Having Trouble?

One snag is that locate checks against a pre-indexed database of files which is only updated periodically, usually weekly. So there is a chance that your file might not be indexed yet. In that case you can refresh the database manually (might be slow!) and see if your file turns up. The method for doing this varies depending on your server’s OS so it’s best to just search for “update locate database [OS]” and you should get your answer.

If you’re still having no joy, try searching for common files that will contain clues. For example, Apache uses a file called httpd.conf to define various settings, including the web root for any domains it serves. Find httpd.conf and you should be able to find the root directory of the site you want to work on.

Finding Your Way Around

Once you know where the troublesome file or files reside, you have two options. You can either just use the full path to edit them directly, or you can traverse the file system and get yourself to their parent folder first.

Navigating the command line is very easy. You already know the ls command for listing the contents of the current directory. There are two other main commands you need: cd and pwd.
cd means “change directory” and you use it like this:

cd [directory]

Simple, huh? If you ever want to go back up a level, there is a magic directory called “..” that always stands for the parent directory.

pwd means “print working directory” and does just that. If you ever need to know where you are in the filesystem, pwd is your friend.

A Couple of Tricks

To save yourself some typing, type the first few characters of a filename or directory and hit Tab – that should auto complete it for you. If it doesn’t, try double-tapping Tab and the system will give you a list of files and directories that match.

You don’t have to traverse one level at a time either. You can do this to your heart’s content:

cd directory/subdirectory/subsubdirectory

You can use the Tab trick at every level too.

Pitfalls to Avoid

Two common gotchas – some systems are case-sensitive and spaces need to be escaped with a to avoid getting error messages.

Protect Yourself

Once you’ve found the file you want to work on, it’s a good idea to make a backup copy of it so you can revert if you make any mistakes. Editing live on the server like this can be risky, so it’s nice to know you can restore back to a known-good copy of a file.

To copy a file, use the cp command:

cp [original filename] [copy filename]

To revert, you just reverse the two filenames and replace the modified original with the copy.

Working in Vim

Now we’re at the exciting point – being able to edit the file and fix that bug!

To start Vim and load the file for editing, we issue the command:

vim [filename]

You’ll now see the contents of your file.

Understanding Modes

Something which will probably be new to you is Vim’s concept of modes.

At first, Vim will be in normal mode which lets you navigate the file and issue various commands through the keyboard.

The main other mode we’ll be using is insert mode – as the name suggests, it’s in this mode that you insert text into the document.

Completing the trio is visual mode, which lets you highlight text and then perform tasks with that text, including copy/paste functionality.

Switching Between Modes

This is something that’s bound to catch you out loads when you first use Vim. Typing commands in insert mode is mildly irritating, but if you think you’re in insert mode and start typing free text you can make a big mess of your document very quickly. So it’s best to make sure you know what mode you’re in.

From normal mode, you can enter insert mode in a couple of different ways:

  • i enters insert mode and inserts text before the cursor
  • a enters insert mode and inserts text after the cursor

There are a bunch of other flavours too which you can check out on the cheat sheet in the further reading section.

To enter visual mode, just hit v to start highlighting single characters, or V (that’s Shift-v) to start highlighting lines.

To get back to normal mode, just hit Esc at any time.

Moving Around the File

The most basic way of moving the cursor around inside the file is to use the arrow keys, but there are some handy shortcuts you can use in normal mode.

Hitting $ will take you to the end of the current line, whereas 0 (zero) will take you to the start of the line.

A very useful one is jumping straight to a specific line, like this:

:[line number]

That is, type : to start entering your command, and then just type a line number.

Searching

Searching in Vim is very easy. You set up your search with the / command:

/[search pattern]

Then traverse the results with n to go forwards and N to go backwards. The search pattern can include regular expressions if you like.

Replacing

Doing a replace is a simple affair too. The substitute or s command takes the form:

:[range]s/[search]/[replace]/[flags]

If that looks a bit scary, don’t worry, it’s quite simple. After hitting : to start entering our command, we need to give the command a range. This could be nothing, which works just on the current line, a specific line number, or %, which works on the whole file.

Next we type the command itself, s, followed by a /. Now comes the text to search for, which works the same as in a straightforward search and again, can include regular expressions.
After another / we specify the replacement text, followed by another /. The last ingredients are the flags, which are extra options we can specify for the command. You can use any combination of:

  • g – do a global search. This makes Vim replace every occurrence of the search text; without it, Vim will just replace the first occurrence on each line, which probably isn’t what you want.
  • i – makes the search case-insensitive.
  • c – asks you before doing each substitution. You can confirm or deny with y and n, use a to say “yes to all” or q to stop substituting.

An example search/replace operation would look like this:

:%s/human/monkey/gc

This finds all occurrences of “human” in the file and then prompts you to ask if you want to replace them with “monkey”. I know, the answer is unlikely to be “no”, but it’s worth making sure.

Copying and Pasting

Vim has a slightly different language than the graphical world we’re used to when talking about copying and pasting text. In Vim-speak, you would yank and then put the text rather than copy and paste it. Instead of cut, you delete. Confusing yes, but you’ll get used to it.

In normal mode, you can yank or delete the current line with yy or dd respectively, and you can put text either before or after the cursor with p or P.

Yanking or deleting specific parts of a line is the domain of visual mode. Move the cursor to the start of the text you want to work with, enter visual mode with v and highlight the remaining characters. Then, hit y or d to yank or delete as required.

Yanking or deleting text in visual mode kicks you back to normal mode, so you can immediately navigate to the place where you want to put the contents of the clipboard.

Deleting Text

Simply hit x to delete a single character from the file, or issue the command dd to delete the current line.

Didn’t we just talk about deleting? Yup. Weirdly, in Vim “delete” actually means “remove this text from the file and add it to the Vim clipboard”. There’s no way to remove text from the file without moving it to the clipboard, so be careful not to lose content you want to paste later by deleting some other text.

Vim does actually have multiple clipboards but for most purposes it’s sufficient just to make sure you put text you want to keep before deleting text you want rid of.

Undo / Redo

Making mistakes is very easy when you’re first working with Vim, so the undo command is essential.

To undo the latest change, hit u in normal mode. To redo, hit Ctrl-r.

If you really make a mess of things, Vim can rescue you with its nifty time-machine functionality. To go back to how the document was five minutes ago, you would issue the command:

:earlier 5m

From here, we also have the option of going forwards in time. To go thirty seconds into the future, you type:

:later 30s

You can also just specify a number of changes. Let’s say you delete ten characters using x then realise you actually want to keep them. Instead of hitting u ten times you can just do this to take you back ten changes into the past:

:earlier 10

Syntax Highlighting

One thing you may be missing from your usual IDE is syntax highlighting. Luckily, Vim has this too. You can turn it on with the command:

:syntax on

Turn it off again, predictably, with:

:syntax off

Saving your Work

Once you’ve made that all-important fix, it’s time to save your work. To do this you can issue the :w command. :w can take a filename parameter if you want to save to a different file, like this:

:w [filename]

If you want to save the current file and then immediately quit, you can use the shortcut :x.

On saving, you may be told that the file is write-protected. If that happens, you can force Vim to save it anyway by adding ! to the save command, like this:

:w!

Quitting

To quit Vim, issue the command :q. If you have unsaved changes, Vim will refuse to quit – sensible behaviour in my opinion.

But if you really don’t want those unsaved changes, you can force Vim to let you quit by again adding ! to your command:

:q!

Wrapping Up

This tutorial should have provided you with a decent toolkit that you can use should you ever find yourself in a spot of bother.

These really are the bare essentials though. There’s an awful lot you can do in Vim and the command line, so I’d urge you to do some further reading.

As a Mac user I often find myself using the command line rather than the GUI simply because it’s quicker for certain tasks. You can also unlock the full power of the OS without having to install or pay for extra software.

If you’ve got any Vim or command line tips that you can’t live without, I’d love to hear about them in the comments.