Speaking UNIX: The new and improved Vim editor

Edit your code on virtually any platform

If you've worked on IBM® AIX®, another flavor of UNIX®, or Linux®, you've more than likely used the vi editor. Since its conception in 1976, vi has become a staple for anyone wanting to edit files. How could someone make a more powerful editing tool than vi, you may ask? The answer is Vim, and this article provides details on the many enhancements that have made Vim a highly used and acceptable editor in the world of UNIX and Linux.

Share:

Adam Cormany, National Data Center Manager, Scientific Games Corporation

Adam Cormany is currently the manager of the National Data Center, but he has also been a UNIX systems engineer, a UNIX administrator, and operations manager for Scientific Games Corporation. Adam has worked extensively with AIX as well as in Solaris and Red Hat Linux administration for more than 10 years. He is an IBM eServer-Certified Specialist in pSeries AIX System Administration. In addition to administration, Adam has extensive knowledge of shell scripting in Bash, CSH, and KSH as well as programming in C, PHP, and Perl. You can reach him at acormany@yahoo.com.



19 August 2008

Also available in Chinese Russian

The vi program is a powerful text editor. William Joy, co-founder of Sun Microsystems, originally wrote the vi editor in 1976 for an early version of Berkeley Software Distribution (BSD) UNIX. Rumor has it that Bill wrote vi in a weekend, but he says the claim is untrue. The program was named after the visual command in the extended line editor for UNIX—ex, for short.

The vi editor is an extremely powerful editor, with several features that many don't know even exist. Vi is a modal editor, meaning that the program produces different results when other settings are placed on the program. There are three distinct modes in vi: command, insert (or input), and line. When operating in insert mode, text is written to a temporary file being edited; while in normal mode, the same keystrokes provoke commands embedded in the editor. To enter insert mode, simply press the I key; to exit to command mode, press Escape. (I explain line mode in further detail later in this article.)

For example, in insert mode, if a you type the string 10dd, that string would be written to the temporary file, as shown in Figure 1.

Figure 1. Typing dd in insert mode
Typing dd in insert mode

However, if you were in command mode, the string 10dd would delete the 10 lines from the temporary file starting from where the cursor is currently placed, as shown in Figure 2.

Figure 2. Typing dd in command mode
Typing dd in command mode

Another example is cursor movement. In command mode, the keys H, J, K, and L move the cursor left, down, up, and right, respectively, as shown in Figure 3. In insert mode, these letters are displayed, instead.

Figure 3. Cursor movement in vi
Cursor movement in vi

Typically, UNIX users either use vi or another editor called Editor Macros (Emacs) written by Richard Stallman in 1976. Many choose vi, however, because it's lightweight, starts faster, and uses less memory.

What is Vim?

Vim, or Vi Improved, is an extended version of vi written by Bram Moolenaar in 1991. The editor was originally designed for the Amiga computer but soon spread through UNIX in 1992. Like vi, Vim is based on command mode and insert mode as a text user interface (TUI)—shown in Figure 4.

Figure 4. The Vim TUI
Vim TUI

However, it does offer a graphical user interface (GUI) appropriately named gVim—shown in Figure 5.

Figure 5. The Vim GUI
Vim GUI

Vim commands

Internal commands within Vim are similar to those within the vi editor. Table 1 provides the cursor movement commands within Vim.

Table 1. Vim commands for effecting cursor movement
CommandAction
hMove cursor left
j, Plus Sign (+), Enter, or ReturnMove cursor down
k, Minus Sign (-)Move cursor up
lMove cursor right
}Move cursor to the end of the current paragraph
{Move cursor to the beginning of the current paragraph
)Move cursor to the end of the current sentence
(Move cursor to the beginning of the current sentence
^Move to the first non-blank character in the current line
$Move to the end of the current line
0 (zero)Move to the beginning of the current line
w or WMove to the beginning of the next word
b or BMove to the beginning of the previous word
eMove to the end of the next word
HMove to the first line of the screen
MMove to the middle line of the screen
LMove to the last line of the screen
GMove to the end of the file
ggMove to the beginning of the file
:nMove to line n

Table 2 shows the Vim commands for deleting text.

Table 2. Vim commands for deleting text
CommandAction
dDelete region selected
ddDelete the entire current line
10ddDelete 10 lines, starting with the current line
dwDelete words from the current position onward
dbDelete words from the left of the current cursor position backwards
dlDelete the character at the current cursor position
dhDelete the character to the left of the current cursor position
d0 (zero)Delete text from the current cursor position to the beginning of the line
D | d$Delete the entire line starting at the current cursor position
xDelete the character at the cursor's current position
XDelete the character before the cursor's current position

Table 3 provides several other useful Vim commands.

Table 3. Common Vim commands
CommandAction
ihEnter insert mode and insert at the current cursor position
IEnter insert mode and insert at the beginning of the current line
aEnter insert mode and append after the cursor
AEnter insert mode and append to the end of the current line
cChange the region selected
CChange the entire line starting at the cursor's current position
oCreate a new blank line beneath the line in which the cursor is currently located and move the cursor to the beginning of the new blank line
OCreate a new blank line above the line in which the cursor is currently located and move the cursor to the beginning of the new blank line
rReplace a single character at the cursor's current position
RReplace multiple characters starting at the cursor's current position and ending when exiting insert mode
<Esc>Exit insert or visual mode
> or <Tab>Indent to the right the region selected
<Indent to the left the region selected
vStart highlighting characters
VStart highlighting entire lines
yyYank/Copy the current line into memory
10yyYank/Copy 10 lines starting with the current line into memory
pPut text yanked or deleted; if characters were yanked (ywdw, or D), put the characters after the cursor's current position. If lines were yanked, put the lines below the cursor's current line.
PSame as p, but place characters before the cursor's current position or lines above the cursor's current line
uUndo the last change
<Ctrl> RRedo
/<pattern>Search for the next pattern found, and place the cursor at the beginning of the pattern found
?<pattern>Search for the previous pattern found, and place the cursor at the beginning of the pattern found
nRepeat the last search
NRepeat the last search, but reverse the search direction
!<cmd>Execute <cmd> outside the Vim session

Line mode

Although command and insert modes are widely used, line mode is equally powerful but sometimes not fully understood or used. Line mode enters into a line editor, allowing you to process commands on single or multiple lines. Considering that vi was named after the ex editor, it's only fitting that line mode puts you into an ex editor.

To enter line mode, from command mode, simply type a colon (:). The cursor then moves to the lower-left corner of the window. When you resume typing, all text appears after the colon at the bottom of the window. When you click Enter, the line mode command is evaluated and executed. If you decide not to execute the line entered in line mode, click Escape to return to command mode.

When working with the line mode of the editor, keep two styles of commands in mind. First, when you type a command, vi or Vim executes the command as is. If the command executed pertains to modifying data, the current line will be the target. However, with the second method, you can supply line numbers to process the specified lines. To enter lines, after the colon, type the line number or range of lines to process, separating the start and end range with a comma (,).

For example, to process only line 23, the command would begin with :23. If you want to modify lines 2319 through 3819, you would type :2319,3819. To process a command from a starting position of line 45 to the end of the file, replace the last line argument with a dollar sign ($)—that is, :45,$.

The following commands are only the beginning of what you can execute in line mode:

  • :w <file name>: Write the file to disk. If an argument is supplied, the editor attempts to write the data to <file name>.

    Note: If you supply an argument and <file name> exists, the editor will not overwrite the existing file's data.

  • :w! <file name>: Write the file to disk and overwrite any data in the file.
  • :<x>,<y> w <file name>: Write lines <x> through <y> to <file name>.
  • :q: Attempt to exit the editor without saving.

    Note: If data has been modified, the editor will not exit until the file has been saved or you exit without saving.

  • :q!: Exit the editor without attempting to write the file to disk.
  • :n: If editing multiple files, begin editing the next file in the edit list.
  • :e <file name>: Edit <file name>.
  • :e#: If editing two files, switch between files.
  • :s/<str1>/<str2>/: Replace the first occurrence of <str1> with <str2> on the current line.
  • :1,$ s/<str1>/<str2>/g: Starting at line 1 and continuing throughout the file, replace <str1> with <str2> globally.
  • :r <file name>: Read <file name> into the current editor session.
  • :<x>,<y> d: Delete lines <x> through <y>.
  • :<x>,<y> y: Yank lines <x> through <y>.

Differences between vi and Vim

Although vi and Vim do have the same look and feel, they definitely have differences. The following are just a few differences between these two powerful text editors:

  • vimscript: Using the internal scripting language vimscript, Vim allows complex scripts to add extended functionality to the editor. In addition to vimscript, Vim supports Perl, Python, Ruby, Tcl, and other languages.
  • vimdiff: A useful command called vimdiff is bundled with the Vim package. Using vimdiff, you can display multiple files next to each other, similar to sdiff, as shown in Figure 6.
    Figure 6. An example of vimdiff
    Example of vimdiff
  • Editing a compressed file: To conserve space on a system, administrators often compress log files or other large files. It never fails: A file is compressed, and then someone asks you, "Hey, can you take a look at this log from two months ago?" Rather than decompressing the file, and then editing it with vi, Vim can edit the compressed file. Vim can handle editing files compressed with bzip2, gzip, and zip.
  • Editing an archived file: Vim also has the ability to edit files concatenated by tar. When editing a .tar file, Vim displays a handy screen allowing you to select which file in the archive you want to edit, as shown in Figure 7. When you finish editing the file, simply save and exit the file normally (:wq), and Vim returns to the display, allowing you to select another file to edit in the archive, or you can quit from the selection window (:q).
    Figure 7. Selecting which file to edit in an archived file using Vim
    Selecting an archieved file

    In the example shown in Figure 8, four ASCII text files were archived using the tar command, and then Vim was used to select the second file in the archive to edit.

    Figure 8. Editing a file within an archive through Vim
    Edit an archived file
  • Split windows: Rather than switching back and forth from window to window while editing multiple files, gVim allows you to open several windows from existing files as well as create new files on the fly, as Figure 9 shows.
    Figure 9. Split windows in Vim
    Split windows in Vim
  • Syntax highlights: Debugging someone's shell script or other code that the editor didn't write originally can feel like an overwhelming task. Thankfully, Vim has helped alleviate some of the headaches that come with editing someone else's code. Using Vim, you can color-coad blocks of code, making debugging much easier in shell scripts as well as in other programming languages, as Figure 10 shows.
    Figure 10. Syntax highlights
    Syntax highlights
  • Last cursor position: When editing a file, it's sometimes necessary to exit the file and perform other tasks. But when you're ready to return to the file, you've forgotten where you left off! Not to worry: Vim remembers the last cursor position when exiting a file. This becomes extremely helpful when modifying files that are several thousands of lines long.
  • Multiple undo/redo operations: In the past, vi only allowed you to undo your last change when editing a file. This was a great start, but it needed to be increased. Sometimes, when writing scripts or other code, what may seem like a good idea turns out not to be the best way to handle an issue, so you must be able to back out of the last 10 changes you've made in the file. Vim allows you to do just this.
  • Visual mode: Vim allows for certain blocks of text to be selected using "visual" mode. Using this mode, you can select any amount of text within the file being edited, and then use a single command to affect the highlighted text. For example, if the middle of a paragraph of text must be removed, you simply type v to enter visual mode, move the cursor through the text to be modified, then type d to delete the highlighted text.

How do I get Vim?

Now that you've seen a few of the enhancements and differences between vi and Vim, you're probably saying, "I want Vim! Where do I get it?" Good news: Vim has been ported to several different operating systems.

Here are just a few of the platforms to which Vim has been ported:

  • Amiga
  • AIX
  • BSD
  • Cygwin
  • IBM OS/2®
  • Linux
  • Apple Mac OS and Mac OS X
  • Microsoft® MS-DOS®
  • Microsoft Windows® 95 though Windows Vista®
  • Microsoft Windows CE
  • OpenVMS

Vim on Windows

So, you saw that Vim is available for Windows in the previous section, and now you're saying, "I can use Vim on Windows? I want that!" You're in luck!

Simply download the latest version (currently version 7.1) of Vim, ported to Windows, from the Vim Web site. The easiest method is to download the self-installing executable file, execute it, and follow the steps. When installed, you can right-click a file, click Edit with Vim (as shown in Figure 11 below, and violà! you're now editing the file in Vim in Windows!

Figure 11. Editing a file with Vim in Windows
Editing a file with Vim in Windows

Now that you've installed Vim on your Windows computer, you can enjoy the genius behind Vim and forget about all the other text editors in Windows.


Conclusion

The vi editor started to pave the way for text editors in UNIX, and Vim has continued along this path. After reading this article, my hope is that you've learned some new things about the Vim editor, how to use its many features to help make your life easier, and appreciate how such a simple concept as an editor has proven a stable and robust application in the UNIX world and now most other operating systems. I trust that if you haven't used Vim much, after learning the ins and outs of the editor, you'll agree that no other editor can compare.

Resources

Learn

Get products and technologies

  • IBM trial software: Build your next development project with software for download directly from developerWorks.

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into AIX and Unix on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=AIX and UNIX, Linux
ArticleID=331843
ArticleTitle=Speaking UNIX: The new and improved Vim editor
publish-date=08192008