Project32.Edit with vim


Project 32. Edit with vim

"What do I do once I've outgrown the nano text editor?"

This project introduces the powerful, highly configurable vim text editor. Ideal for writing code and maintaining configuration files, vim is highly efficient, enabling you to edit with the minimum number of keystrokes. The vim text editor is an improved version of the standard vi (pronounced vee eye) text editor traditionally distributed with Unix systems. The three projects following this one33, 34, and 35cover some of the more advanced features of vim. Project 31 introduces the emacs text editor, and Project 30 introduces the simpler nano text editor.

Tip

Most people who don't like vim have never seriously tried it.


Basics

Fire up vim, and we'll take a look at what it can do. Use any text file; we'll once again work on a copy of ~/Sites/index.html.

$ cd ~/Sites $ cp index.html index-new.html $ vim index-new.html


You'll see a terminal window similar to that shown in Figure 4.3. The bottom line (the vim command line) shows important and informational messages such as the current mode, and is also where you type vim commands. In this project and the others covering vim (Projects 3335), the term command line refers to vim's command line, not that of the shell unless specifically stated.

Figure 4.3. The vim text editor takes a little getting used to, but it's incredibly flexible, powerful, and even fun after you become familiar with it.


Before we continue, there's something you should understand. To reap the benefits of vim, you must invest a little time in learning the basics. If you are prepared to do so, you'll be rewarded with a powerful and very productive editing tool. If not, take a look at nano.

Override vi Compatibility

Because it's based on the old vi editor, vim runs by default in vi-compatibility mode, which doesn't expose all its features. We'll want to run in full vim mode, and the easiest way to activate it is to create an empty vim configuration file in your home directory.

$ touch ~/.vimrc


You can edit this file later to change vim's default settings.

Official vim Information

The official home page for vim (called vim online) is at www.vim.org. You'll find lots of useful information, including a hyperlinked version of the vim help system, FAQs, tips including an RSS feed, and an online version of Steve Oualline's book about vim.

Mac OS X includes the Terminal version of vim, which is the one we'll be using in this project. There's also an Aqua (OS X-native) version that's essentially the same, but with the addition of menus and mouse clicks. It can be downloaded from http://macvim.org.

To quote vim online:

"vim is charityware. Its license is GPL-compatible, so it's distributed freely, but we ask that if you find it useful you make a donation to help children in Uganda through the ICCF."


Learn More

Project 35 covers vim configuration.


Understand vim Modes

You can't just plunge straight into vim and start typing; weird things will happen. vim operates in one of two modes:

  • Normal mode. vim starts up in normal mode. In this mode, characters you type are interpreted as commands, not additions to file content. There's no need to use the Escape and Control keys to prefix each command. To enter normal mode from insert mode (see below), press Escape.

    Some vim commands require arguments, and these are entered on the vim command line. Such commands are introduced by typing a colon (:). Type a colon now, and you'll see it echoed on the command line, followed by the cursor. This is known as vim command-line mode. Now type help and then press Return. A new vim window will open (the Terminal window will split into two horizontal sections) showing the vim help pages in the top window. Type :q (colon followed immediately by q) to quit help, closing the new window and returning to the main document.

  • Insert mode. You must change from normal mode to insert mode to insert text. The most common way to do this is simply to type i (other ways are described later). In this mode, typed characters are added to file content in the usual manner. When in insert mode, you'll notice the text -- INSERT -- on the left end of vim's command line. Press Escape when you wish to return to normal mode.

Tip

When in command-line mode (after having typed :), use the up and down arrow (cursor) keys to recall previous commands.


Why Two Modes?

vim's modal operation can scare people away, but it needn't. In normal mode, you are able to issue commands simply by typing letters. Compare this with the more traditional approach taken by emacs. Because emacs does not have separate modes, every command must be a control sequence or must be preceded by the Escape key. You effectively have to enter normal mode for almost every command keystroke, and in return, you benefit from being automatically thrown back into insert mode. You'll no doubt make up you own mind as to which of the two you prefer.


Move Around

The arrow (cursor) keys work as expected and, most important, do so in both normal and insert modes, so there's no need to switch modes just to cursor around the file. In X11's xterm, but not Apple's Terminal, you can enable positioning of the cursor via mouse clicks by entering normal mode, typing

:set mouse=a


and pressing Return. You'll see this echoed on the vim command line, as in the help example earlier.

To enable mouse-click positioning of the vim cursor within Terminal, turn on Terminal's Option-Click to Position Cursor feature. Launch the Terminal Inspector by choosing Terminal > Window Settings; select Emulation from the pop-up menu, and check Option-Click to Position Cursor. (If you did this already to enable mouse clicks in nano or emacs, you don't need to do it again for vim.) Option-clicking tells Terminal to send a series of cursor-movement keystrokes to vim, thereby moving the cursor to the point where you clicked.

In normal mode, vim supplements the arrow keys with several cursor-movement shortcut keystrokes. Following are some of the most useful, listed in an order that will become apparent as you read them:

  • gg Move back to the start of the file

  • { Move back one paragraph

  • ( Move back one sentence

  • - Move up (back) one line

  • ^ Move back to the start of the current line

  • b Move back one word

  • h j k l Equivalent to left, down, up, right

  • w Move forward one word

  • $ Move forward to the end of the current line

  • + Move down (forward) one line

  • ) Move forward one sentence

  • } Move forward one paragraph

  • G Move forward to the end of the file

The difference between minus (-) and k is that minus moves to the first nonblank character on the line, whereas k will happily move the cursor to leading white space. Plus (+) and j are similarly different.

Tip

If you forget which vim mode you're in, check the command line at the foot of the window for the text --INSERT--, or press Escape to go to normal mode. You can also press Escape to abandon a command that you're midway through typing.


Tip

The Page Up and Page Down keys scroll Apple's Terminal. Use Shift-Page Up and Shift-Page Down to get vim to scroll the document.

If you use X11's xterm as your terminal, the Page Up and Page Down work without the Shift key.


Jump to a Line

You may jump straight to line number n within a file by using either of the following command syntaxes within vim normal mode. Type

  • nG (for example, 24G to move to line 24).

  • :n (for example, :100 to move to line 100).

To jump halfway into a file, type 50%. I'll leave you to figure out how to jump one-third of the way into a file (but integer numbers only, please!).

Tip

Press Control-G in normal mode to display the current filename and cursor position on the vim command line.


Get Help

To enter the vim help system, press Escape if you are not in normal mode, and type

:help


and then press Return. (Remember that typing a colon positions the cursor on the vim command line, where you then type help.) The vim help pages will appear in the top half of a split screen. Use the arrow keys to move around the help pages. In fact, the help pages are simply a non-modifiable document.

Note

If a command is preceded by a colon when issued, you must precede it with a colon when getting help on it. Typing :help :s gives help on a different command from the one you get help on by typing :help s.


Cursor down a few lines until you reach the section labeled "BASIC:". Below it, you'll find sections labeled with vertical bars on either side, such as "|quickref|" and "|tutor|". Position the cursor on one of these tags, and press Control-] (hold down the Control key while pressing the ] key). A tag is like a hyperlink and takes you to the appropriate point in the help system. Press Control-t to move back from the linked page to the original page.

Tip

Read the 30-minute vim tutor by invoking vim from the shell prompt as (all one word)

$ vimtutor



To get help on a specific command, type

:help


in normal mode, followed by the keystroke(s) for the command you want to learn about. For example:

:help j :help ctrl-] :help :s


To get help on a particular topic, type

:help the-topic-here


To exit the help system and return to the main document, type

:q


Add and Remove Text

When you wish to insert text, type i for insert. From then on, editing is pretty much as you would expect. To add text, place the cursor at the location where you want your addition to begin. The Delete key (also referred to as the Backspace key) deletes the character behind the cursor. Forward-Delete (the key above the left arrow on full-size Mac keyboards, emulated by pressing Fn-Delete on laptops) removes the character under the cursor.

Different keystrokes for switching from normal to insert mode determine where text insertion begins after the mode switch. From normal mode, enter insert mode by typing one of the following:

  • I to start inserting at the beginning of the line

  • i to start inserting at the cursor

  • a to start inserting just after the cursor

  • A to start inserting after the end of the line

  • O to open a new line above the current line

  • o to open a new line below the current line

If you want to replace (overwrite) existing text instead of inserting new text, type the following in normal mode:

  • r to replace a single character. Typing rT, for example, replaces the character under the cursor with T, and you remain in normal mode.

  • R to replace continually. Every character you type overwrites a character in the file. You'll notice that vim's command line now displays the message -- REPLACE --.

  • C to delete to the end of the line and enter insert mode.

  • S to delete the entire line and enter insert mode.

Undo Changes

To undo changes, enter normal mode and type one of the following:

  • u to undo the last change.vim has multi-level undo, so you can repeat this many times to go farther back in the editing history.

  • U to undo all changes applied to the last line that was edited. If you inserted, deleted, and inserted some more, all on the same line, U undoes all three sets of changes and in this example is equivalent to uuu.

  • Control-r to redo changes that have just been undone. Like undo, redo is multi-level and can redo many undos.

Note

From here on, I won't continually remind you to enter normal mode or to press Return after typing a command on vim's command line.


Learn More

See Project 33 to learn more about cut, copy, and paste in vim.


Simple Cut, Copy, and Paste

Here are the most basic cut, copy, and paste commands for vim. Remember to enter normal mode when you issue these commands.

  • Cut text. Type dd to cut (delete) the current line, and type x to delete the character under the cursor.

  • Copy text. Type yy to copy (yank) the current line.

  • Paste text. Type p to paste (put) a cut or copied line below the current line, and type P to paste it above the current line. Similarly, cut characters are pasted after or before the cursor position.

To cut or copy a specific number of lines, precede the command with a count. To copy 20 lines and then paste them back elsewhere, for example, type 20yy, move the cursor, and then type p.

If you use Apple's Terminal application, you may also use the standard Mac methods of pressing Command-c to copy selected text and Command-v to paste it (in vim insert mode). It's not possible to cut text by using Command-x.

Save Your Edits

Here are some of the most useful commands. Type

  • :w to save changes to the current file.

  • :w new-file-name to save the changes to a new file.

  • :q to quit vim. If you have unsaved changes you wish to save first, type :wq.

  • :q! to quit vim and abandon all changes since the last save.

Tip

Follow a command with pling (!) to tell vim to proceed with the command where normally it might balk and issue a warning instead.


Edit as Root

System configuration files are writable only by root. To modify them, you must run vim as user root, using the sudo command, and type your administrator password when prompted.

$ sudo vim filename Password:


Learn More

See "How to Become the Root User" in Project 2 for more details on the sudo command.


Search and Replace

The vim text editor has search, and search-and-replace, capabilities. In addition, the search can be case sensitive, employ regular-expression matching, and be performed in the reverse direction.

To search for a term like web in vim, type / (forward slash) in normal mode. The cursor will be placed on the vim command line. Now type the search term web and press Return. The cursor will be placed on the first match. To move to the next match, type n; and to move backward to the previous match, type N. If a search reaches the end of the file, it will wrap back to the beginning, displaying the message Search hit BOTTOM, continuing at TOP on vim's command line.

To repeat the last search, type / and press Return. To search backward, use ? instead of / and then proceed as before.

Tip

After typing /, you can use the Cursor Up and Cursor Down keys to recall previous search terms.


Search Options

If you wish to change the way searches behave, vim has several options that you can enable (or set), either interactively on vim's command line or in the configuration file (see Project 35). When these options have been set, they affect all searches, not just the next search made. Here are some of the most useful. Type

  • :set ignorecase to make searches case insensitive. apple will match apple, Apple, and APPLE.

  • :set smartcase in conjunction with ignorecase. If the search term contains any uppercase characters, the search becomes case sensitive. If the search term is entirely lowercase, the search remains case insensitive.

  • :set hlsearch to tell vim to highlight all matches. (Typing :nohl switches off the highlighting resulting from the last search but won't switch off hlsearch for subsequent searches.)

  • :set incsearch to active incremental search mode. If you type slowly, you'll notice the search happening as you type, with the next match highlighted. As you type more letters, the search becomes more selective.

Tip

The substitute command takes several flags that modify its behavior (making it interactive or case insensitive, for example). To learn more about substitute, consult the vim help pages by typing

:help :s :help :s_flags



Switch off any of the above options by preceding the option name with no. For example:

:set noignorecase


Note

Because vim treats all search terms as regular expressions, search characters that have special meaning within regular expressionssuch as dot, star, question mark (query), and square bracketsmust be escaped within search terms, using the backslash character. For example: \. \* \? \[ \].


Replace

To perform a search and replace (substitute), type

:%s/search-text/replace-text/g


Let's analyze this command. The initial percent (%) symbol means "all lines in the file." Without it, the search operates on the current line only. The next part says to search for and then substitute (s) search-text with replace-text. The forward-slash characters delimit the text. The final g says do this globally across each line, as without it, only the first match on each line is substituted.

Learn More

See projects 77 and 78 to learn more about regular expressions.


Use Regular Expressions

vim is capable of searching for, and replacing, regular expressions. No special commands are necessary; simply use a regular expression as the search term.




Mac OS X UNIX 101 Byte-Sized Projects
Mac OS X Unix 101 Byte-Sized Projects
ISBN: 0321374118
EAN: 2147483647
Year: 2003
Pages: 153
Authors: Adrian Mayo

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net