Section 3.36. Editing a File: vim


[Page 82 (continued)]

3.36. Editing a File: vim

The two most common Linux text editors are vi and emacs. This section and the next contain enough information about each editor to allow you to perform essential editing tasks. They also contain references to other books for obtaining more advanced information.

3.36.1. Starting vim

Bill Joy of Sun Microsystems, Inc., originally developed vi (standing for visual editor) for BSD UNIX while at the University of California at Berkeley. vi proved so popular in the UNIX world that it was later adopted as a standard utility for System V and most other versions of UNIX. Today vi is found on virtually every UNIX system. The version of vi contributed to the GNU Project started out as a different full-screen editor, but it is compatible with vi. Because it was "vi with some improvements," it was renamed vim. Conveniently, most shell startup scripts created for Linux users define an alias for "vi" that points to vim, so old UNIX hacks can still type vi and feel like they're using vi. Those wanting to learn everything about vim can also run the vimtutor training program.

To start vim with a blank slate, enter the command vim without any parameters. To edit an existing file, supply the name of the file as a command-line parameter (i.e., "vim filename"). When vim is started with a new or empty file, lines past the end of the file containing no data are indicated by tilde characters (~). vim then enters command mode and awaits instructions. To conserve space, I'll draw screens that are only six lines long. For example, Figure 3-47 shows what I saw when I executed vim with no parameters.


[Page 83]

Figure 3-47. Example of the screen when starting vim.

~

  

~

  

~

  

~

  

~

  

~

0,0-1

All


In the lower right-hand corner, you see the line number and character indentation of the current location of the cursor and how far into the file you are positioned (this is usually a percentage value; "All" means you're looking at the entire file, and other values you might see here are "Top" and "Bot" for top and bottom of the file).

Command mode is one of the two modes that vim may be in; the other mode is called text entry mode. Since it's easier to describe command mode when there's some text on the screen, I'll start by describing text entry mode.

3.36.2. Text Entry Mode

To enter text entry mode from command mode, press one of the keys listed in Figure 3-48. Each key enters you into text entry mode in a slightly different way.

Figure 3-48. Text input commands in vim.

Key

Action

i

Text is inserted in front of the cursor.

I

Text is inserted at the beginning of the current line.

a

Text is appended after the cursor.

A

Text is appended to the end of the current line.

o

Text insertion point is opened after the current line.

O

Text insertion point is opened before the current line.

R

Text is replaced (overwritten).


Any text that you enter at this point will be displayed on the screen. To move to the next line, press the Enter key. You may use the backspace key to delete the last character that you entered. You may still move around the screen using the cursor keys even when you're in text entry mode.


[Page 84]

To go from text entry mode to command mode, press the Esc or Escape key.

To enter a short four-line poem, I pressed the a key to add characters in text entry mode, entered the text of the poem, and then pressed the Esc key to return to command mode. Figure 3-49 shows what I ended up with.

Figure 3-49. Editing a file with vim.

[View full width]

I always remember standing in the rains, On a cold and damp september, Brown Autumn leaves were falling softly to the ground, Like the dreams of a life as they slide away. ~ ~ 4 ,45 All



The next section describes the editing features of vim that allowed me to change this poem to something a little more appealing.

3.36.3. Command Mode

To edit text, you must enter command mode. To travel from text entry mode to command mode, press the Esc key. If you accidentally press the Esc key when in command mode, nothing bad happens (depending on your terminal settings, you may hear a beep or bell that tells you are already in command mode).

vim's editing features are selected by pressing special character sequences. For example, to erase a single word, position the cursor at the beginning of a particular word and press the d key followed by the w key (delete word).

Some editing features require parameters, and are accessed by pressing the colon (:) key, followed by the command sequence, followed by the Enter key. When the colon key is pressed, the remainder of the command sequence is displayed at the bottom of the screen. In the following example, the Enter key is indicated as <Enter>. The < and > characters act as delimiters and should not be entered. For example, to delete lines 1 through 3, you'd enter the following command sequence:

:1,3d<Enter>


Some editing features, such as the block delete command that I just described, act upon a range of lines. vim accepts a couple of formats for a line range:

  • To select a single line, state its line number.

  • To select a block of lines, state the first and last line numbers inclusively, separated by a comma.


[Page 85]

vim allows you to use $ to denote the line number of the last line in the file, and . to denote the line number of the line currently containing the cursor. vim also allows you to use arithmetic expressions when stating line numbers. For example, the sequence

:.,.+2d<Enter>


would delete the current line and the two lines that follow it. Figure 3-50 shows some other examples of line ranges.

Figure 3-50. Specifying a line range in vim.

Range

Selects

1,$

All of the lines in the file.

1,.

All of the lines from the start of the file to the current line, inclusive.

.,$

All of the lines from the current line to the end of the file, inclusive.

.-2

The single line that's two lines before the current line.


In what follows, the term <range> indicates a range of lines in the format described above.

3.36.4. Memory Buffer and Temporary Files

While you are editing your file, vim stores a copy of your file in memory and makes the changes to that copy of your file. The disk file is not modified until you explicitly tell vim to write the file or you exit vim with one of the commands that also writes the file (discussed below). For this reason, I recommend that you not spend hours and hours editing a file without either writing or exiting vim and getting back in on a regular basis. If your system were to crash (for whatever reason) while you were editing, all changes you made since the last time you either wrote the file or started vim would be lost.

Even if the system does crash while you are editing, all may not be lost. vim also uses a temporary file to manage the in-memory copy of your file while you edit (if your file is very large, it won't all be kept in memory at the same time). vim may be able to recover the file using the -r argument. While this is a nice feature, it is much safer to not depend on this and just write the file periodically. Even though today's systems are much more reliable, it is still wise to save your work often.

3.36.5. Common Editing Features

The most common vim editing features can be grouped into the following categories:

  • moving the cursor

  • deleting text

  • replacing text

  • pasting text


  • [Page 86]
  • searching text

  • search/replace text

  • saving/loading files

  • miscellaneous (including how to quit vi)

These categories are described and illustrated in the subsections that follow, using the sample poem that I entered at the start of this section.

3.36.6. Cursor Movement

Figure 3-51 is a table of the common cursor movement commands.

Figure 3-51. Cursor movement commands in vim.

Movement

Key sequence

Up one line

<cursor up> or k

Down one line

<cursor down> or j

Right one character

<cursor right> or l (will not wrap around)

Left one character

<cursor left> or h (will not wrap around)

To start of line

^

To end of line

$

Back one word

b

Forward one word

w

Forward to end of current word

e

To top of screen

H

To middle of screen

M

To bottom of screen

L

Down a half screen

Control-D

Forward one screen

Control-F

Up a half screen

Control-U

Back one screen

Control-B

To line nn

:nn<Enter> (nnG also works)

To end of file

G


For example, to insert the word "Just" before the word "Like" on the fourth line, I moved the cursor to the fourth line, pressed the i key to enter text entry mode, entered the text, and pressed the Esc key to return to command mode. To move the cursor to the fourth line, I used the key sequence :4<Enter> (or I could have used 4G).


[Page 87]

3.36.7. Deleting Text

Figure 3-52 is a table of the common text deletion commands.

Figure 3-52. Commands that delete text in vim.

Item to delete

Key sequence

Character

Position the cursor over the character and then press x.

Word

Position the cursor at start of word and then press dw.

Line

Position the cursor anywhere the line and then press dd (typing a number ahead of dd will cause vim to delete the specified number of lines beginning with the current line).

Current position to end of current line

Press D.

Block of lines

:<range>d<Enter>


For example, to delete the word "always," I typed :1<Enter> to move to the start of line one, pressed w to move forward one word, and then typed the letters dw. To delete the trailing "s" on the end of "rains" on the first line, I moved my cursor over the letter "s" and then pressed the x key. My poem now looked as shown in Figure 3-53.

Figure 3-53. Our file after deleting some text.

[View full width]

I remember standing in the rain, On a cold and damp september, Brown Autumn leaves were falling softly to the ground, Just Like the dreams of a life as they slide away. ~ ~ 4,1 All



3.36.8. Replacing Text

Figure 3-54 is a table of the common text replacement commands.

Figure 3-54. Commands that replace text in vim.

Item to replace

Key sequence

Character

Position the cursor over the character, press r, and then type the replacement character.

Word

Position the cursor at start of word, press cw, and then type the replacement text followed by Esc.

Line

Position the cursor anywhere in line, press cc, and then type the replacement text followed by Esc.



[Page 88]

For example, to replace the word "standing" by "walking," I moved to the start of the word and then typed the letters cw. I then typed the word "walking" and pressed the Esc key. To replace the lowercase "s" of september by an uppercase "S," I positioned the cursor over the "s," pressed the r key, and then pressed the "S" key.

I then performed a few more tidy-up operations, replacing "damp" by "dark," "slide" by "slip," and the "L" of "like" by "l". Figure 3-55 shows the final version of the poem.

Figure 3-55. Our file after replacing text.

[View full width]

I remember walking in the rain, On a cold and dark September, Brown Autumn leaves were falling softly to the ground, Just like the dreams of a life as they slip away. ~ ~ 4,1 All



3.36.9. Pasting Text

vim maintains a paste buffer that may be used for copying and pasting text between areas of a file. Figure 3-56 is a table of the most common pasting operations.

Figure 3-56. Commands that paste text in vim.

Action

Key sequence

Copy (yank) lines into paste buffer.

:<range>y<Enter>

Copy (yank) current line into paste buffer.

Y

Insert (put) paste buffer after current line.

p or :pu<Enter> (contents of paste buffer are unchanged)

Insert paste buffer after line nn.

:nnpu<Enter> (contents of paste buffer are unchanged)


For example, to copy the first two lines into the paste buffer and then paste them after the third line, I entered the following two commands:

:1,2y :3pu 


The poem then looked as shown in Figure 3-57.

Figure 3-57. Our file after pasting text.

I remember walking in the rain, On a cold and dark September, Brown Autumn leaves were falling softly to the ground, I remember walking in the rain, On a cold and dark September, Just like the dreams of a life as they slip away. 




[Page 89]

To restore the poem, I typed :4,5d<Enter>.

3.36.10. Searching

vim allows you to search forward and backward through a file, relative to the current line, for a particular substring. Figure 3-58 is a table of the most common search operations.

Figure 3-58. Search commands in vim.

Action

Key sequence

Search forward from current position for string sss.

/sss/<Enter>

Search backward from current position for string sss.

?sss?<Enter>

Repeat last search.

n

Repeat last search in the opposite direction.

N


The trailing "/" and "?" in the first two searches are optional (vim figures out what you mean when you type Enter, but it's a good habit to be in, since you can add other commands after that rather than simply hitting Enter.

For example, I searched for the substring "ark" from line 1 of the poem by entering the following commands:

:1<Enter> /ark/<Enter> 


vim positioned the cursor at the start of the substring "ark" located in the word "dark" on the second line (Figure 3-59).

Figure 3-59. Searching in vim.

[View full width]

I remember walking in the rain, On a cold and dark September, Brown Autumn leaves were falling softly to the ground, Just like the dreams of a life as they slip away. ~ ~ 4,1 All



3.36.11. Search/Replace

You may perform global "search and replace" operations by using the following commands in Figure 3-60.


[Page 90]

Figure 3-60. Searching and replacing in vim.

Action

Key sequence

Replace the first occurrence of sss on each line with ttt.

:<range>s/ sss/ ttt/<Enter>

Replace every occurrence of sss on each line with ttt (global replace).

:<range>s/ sss/ ttt/g<Enter>


For example, to replace every occurrence of the substring "re" by "XXX," I entered the command displayed in Figure 3-61.

Figure 3-61. Example of searching and replacing in vim.

[View full width]

I XXXmember walking in the rain, On a cold and dark September, Brown Autumn leaves weXXX falling softly to the ground, Just like the dXXXams of a life as they slip away. ~ :1,$s/re/XXX/g



3.36.12. Saving/Loading Files

Figure 3-62 is a table of the most common save/load file commands.

Figure 3-62. Commands that write to and read from files in vim.

Action

Key sequence

Save file as <name>.

:w <name> <Enter>

Save file with current name.

:w<Enter>

Save file with current name and exit.

:wq<Enter> (ZZ also works)

Save only certain lines to another file.

:<range> w <name> <Enter>

Read in contents of another file at current position.

:r <name> <Enter>

Discard current file and edit file <name> instead.

:e <name> <Enter>

Edit next file on initial command line.

:n<Enter>


For example, I saved the poem in a file called "rain.doc" by entering the command displayed in Figure 3-63.


[Page 91]

Figure 3-63. Example of writing a buffer to a file in vim.

I remember walking in the rain, On a cold and dark September, Brown Autumn leaves were falling softly to the ground, Just like the dreams of a life as they slip away. ~ :w rain.doc 



vim tells you how many bytes a file occupies when you save it.

If you place more than one file on the command line when you first invoke vim, it starts by loading the first file. You may edit the next file by using the key sequence :n.

3.36.13. Miscellaneous

Figure 3-64 is a list of the most common miscellaneous commands, including the commands for quitting vi.

Figure 3-64. Miscellaneous vim commands.

Action

Key sequence

Redraw screen.

Control-L

Undo the last operation.

u

Undo multiple changes made on current line.

U

Join next line with current line.

J

Repeat the last operation.

.

Execute command in a subshell and then return to vim.

:!<command> <Enter>

Execute command in a subshell and read its output into the edit buffer at the current position.

:r !<command> <Enter>

Quit vim if work is saved.

:q<Enter>

Quit vim and discard unsaved work.

:q!<Enter>


Control-L is particularly useful for refreshing the screen if a message pops up and messes up your screen, or if some static interferes with your modem connection during a vim session.

To finally quit vim after saving the final version of the poem, I typed the command illustrated in Figure 3-65.


[Page 92]

Figure 3-65. Quitting vim.

I remember walking in the rain, On a cold and dark September, Brown Autumn leaves were falling softly to the ground, Just like the dreams of a life as they slip away. ~ :q 



3.36.14. Customizing vim

vim can be customized by setting options that determine its behavior in certain situations. The ":set" command is used to set and unset vim's options. By typing ":set all" you will see a list of all the options supported by your version of vim and their current settings. Settings are either toggled (on or off) or set to a numeric or string value. Figure 3-66 shows the most commonly used options.

Figure 3-66. Commands to customize vim.

Option

Description

Default setting

autoindent

When set, subsequent lines you type are indented to the same point as the previous line.

off

ignorecase

When set, during searches and substitutes, the upper- and lowercase characters both satisfy the match criteria.

off

number

When set, vim displays line numbers on the left-hand side of the screen.

off

showmode

Causes vim to indicate when you are in a text input mode (open, insert, append, or replace) rather than the normal command mode.

on

showmatch

Causes vim to briefly move the cursor back to the opening parenthesis or brace when you type the matching closing one.

off


To turn autoindent on, type ":set autoindent<Enter>". To turn autoindent off again, type ":set noautoindent<Enter>".

3.36.15. Keeping Your Customizations

You don't want to have to type every ":set" command you want every time you enter vim. You would quickly decide most settings weren't worth that much effort. But you can create a special file in your home directory that vim recognizes and put your preferred settings there. Then every time you run vim, your settings will be the way you want them (and you can always modify the file as you find others you like).


[Page 93]

To make vim set autoindent and ignorecase every time we run it, create a file called ".exrc" (note that the filename begins with a period; this is a special convention that we will see again later when we look at command shells). In that file, put the following lines:

set autoindent set ignorecase set nonumber 


We don't really need to set "nonumber" since its initial value is off, but this shows how you would turn an option off if the default was that it was set. Now every time you start vim, autoindent and ignorecase will be on.




Linux for Programmers and Users
Linux for Programmers and Users
ISBN: 0131857487
EAN: 2147483647
Year: 2007
Pages: 339

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