The VI (VIM) Text Editor

Ian! D. Allen –

Fall 2013 - September to December 2013 - Updated 2019-01-29 15:49 EST

1 The VI/VIM family of text editorsIndexup to index

Welcome to the vi family of text editors. It is the universal text editor for the Unix/Linux operating systems.

The stock Unix vi and the open-source vim (and various other clone editors such as neovim, nvi, elvis, and stevie) are all based on the original 1980’s Berkeley vi program written by Bill Joy (the same guy who wrote the C Shell).

1.1 VIM is Universal: Unix, Linux, MacOSX, BSD, embeddedIndexup to index

The vi editor is the standard editor available on most every Unix-derived system, including Unix, Linux, MacOSX, and BSD. Every Unix and Unix-like system has it. Even the embedded software in your home router may have a version installed (e.g. DDWRT, OpenWRT).

2 How to learn VIMIndexup to index

How to use this document to learn VIM:

  1. Understand that vim is a plain text editor.
  2. Be sure you are using the modern vim version of the vi editor.
  3. Print the front of the recommmended reference card.
  4. Set the essential options, especially if you have a dark screen (PuTTY).
  5. The vimtutor command starts a tutorial that teaches you the basics.

2.1 Terminal-based: no fonts, no mouseIndexup to index

vi is a pure (plain) text editor – just text, no fonts, no formatting. It will not edit word-processing documents such as MSWord or OpenOffice or printer-ready documents such as PDF files.

The vi family of editors can be used on most any terminal, over the slowest of dial-up links. They are pure console terminal-based programs that need no mouse or graphical display screen. Everything is done via the keyboard. (Put your mouse away; you won’t have one at a server text console.)

2.2 Versions of the editorIndexup to index

The name vim means “Vi IMproved”. It is a rewrite and massive enhancement of the original vi editor written in the 1980s. You will occasionally come across the old vi version in embedded or non-Linux systems; the basic editor commands are the same.

Some versions of Linux install a smaller, limited version of vi as the default editor and you have to explicitly ask for an upgrade to get the full vim version with all the great features. The command gvim (if available) starts an X11 GUI-based version of vim in its own window.

The Linux command vi is usually a link to vim; they are the same. Some distributions (e.g. Fedora 12) install a smaller, less feature-filled version of vim as vi (e.g. /bin/vi), but then use system aliases to alias vi to a larger version with the name vim (e.g. /usr/bin/vim), so that you never really know which version you’re getting.

You can find out which version of vim you’re running using the :version and :help commands. (Under Fedora, the smaller vi version has the wrong help files installed. Use vim not vi on Fedora 12.)

This document will assume that vi and vim are the same, fully-featured, program. It will use vi and vim interchangeably.

Choose Your editor carefully

3 Learning the VIM Text Editor: Difficult to Learn – Easy to UseIndexup to index

VIM is an easy-to-use but hard-to-learn text editor. It is notoriously difficult to learn, but once learned, is very easy to use.

Learning curves showing difficulty of vi

It took about a month before I could do anything with any proficiency in vi and I still didn’t love it, but by then I’d realized that there was an insanely powerful editor hiding behind this bizarre facade. So I stuck with it, and eventually found out that once you know what you’re doing, it’s an incredibly fast editor. […] I never hated any editor as much as I hated vi, and now I’ve stuck with it for 17 years because I can no longer imagine a better editor.

The vim editor is keyboard-based; it doesn’t use the mouse. It doesn’t need the X Windows GUI system to be running; you can use it over a serial line and a dial-up modem.

Similar to learning to touch-type on a keyboard, the vim editor is difficult to learn but easy to use once you have some mastery of it. Until you get used to it, you will find using vi awkward. Once you master it, you will easily outperform anyone using a mouse-based editor such as Notepad. Learn the tool!

The single-character command keys used in vi have found their way into other programs. The bash shell supports a vi mode for editing command lines, and the less and more pager programs (used by the man command) use vi commands to move around the screen and search for text.

The vi editor is incredibly powerful. Most students refuse to learn it well enough to get out of the awkward stage. They go into vi insert mode and perform all text editing using the arrow and backspace keys, turning vi into a slower, mouse-less version of Notepad! If you want a Unix/Linux job, learn the editor tool! If you want to use arrow keys, us the Pico or Nano editors instead (but don’t expect to get a Linux job).

VIM is a moded text editor; you need to know what mode the program is in before you can start typing text into it. When VIM starts, it treats your keyboard as a command device and every letter you type is a VIM command. (VIM is a poor editor to use if you have cats; the cat walking across your keyboard can change your file in fifteen ways.)

You can get by in VI with knowing how to read in a file, delete and append single characters and lines, and write the file back out. (See the list of “bare minimum” commands, below.)

The more you learn about VI, the faster you will edit files and the better you will look at your job interview. VI skill is essential to you as a Unix/Linux programmer; it is now the universal text editor. (Even Microsoft Windows has versions of VI you can download!)

Almost every letter, upper and lower case, is a VI command. The more you learn, the faster you can edit. While you may begin by learning to delete a word slowly using ten x commands, eventually you should evolve into knowing how to use the single quick dw command.

3.3 INSERT mode and Arrow Keys slow you downIndexup to index

  1. Stay out of INSERT mode!
  2. Do not use the arrow keys!

Most of what you do in an editor is move around and change text. That means you should always be in command mode in VIM, not INSERT mode. In command mode, your keyboard lets you move around and edit text. In INSERT mode, all you can do easily is type text; moving has to be done with the arrow key and that is very slow.

Do not use the arrow keys to move the cursor – keep your hands on the keyboard “home” row and use the command-mode letters h,j,k,l instead. The letters don’t require you to move your hands from the home row on your keyboard, and they encourage you to remain in command mode where you can use all the VIM commands.

Constant use of INSERT mode and arrow keys will slow you down and make you look like an amateur.

3.4 Avoid wrapping of long lines: 80 columns maxIndexup to index

When you edit a file containing a line of text longer than the width of your VIM window, the long line of text will usually “wrap around” to the beginning of the next line, and keep wrapping onto following lines if the line is really long. One long line will appear to be many lines.

A wrapped line of text is still one line in the file and in the editor; it simply displays as multiple lines on your screen. When you delete the one line, the entire line disappears, including all its wrapped parts.

(You can optionally tell VIM to only display the part of the line that fits in your terminal window, so that you have to scroll to the right to see the rest of the line.)

Because wrapped lines are messy to look at on your screen – it’s easier when every line on the screen is really one line in the file – avoid writing long lines of text. For historical reasons (the number of characters on a punch card!), a line length of no more than 80 characters is still fairly standard. Keep your lines shorter than 80 characters. (VIM can display a column number in it status line.)

4 Setting VIM Options – Getting HelpIndexup to index

VIM comes with hundreds of options that influence how it works. You can set the options at any time; but, to save them and have them used every time you start VIM, you need to put commands into a file named .vimrc in your HOME directory.

4.1 Getting help inside VIMIndexup to index

The full vim editor has help available by typing :help, e.g. you can type :help showcmd. This splits your terminal screen and opens up a help file inside vim for the showcmd option. To close the help file, just do :q as you would do to close any open file.

4.2 Essential optionsIndexup to index

The following are good options that you should set in your .vimrc file, if VIM does not already have them set for you:

$ cd                    # go to my HOME directory
$ cat .vimrc            # see what is in the file already, if anything
$ echo "set showcmd showmode confirm ruler" >>.vimrc
$ cat .vimrc
set showcmd showmode confirm ruler

The above shell command line appends the options to your .vimrc file. You only need to do this once; VIM will read the file on start-up. If you execute the above command more than once, you will put multiple copies of the options into the file. This isn’t an error; but, it isn’t necessary either. Edit the file and remove the duplicate lines.

Some people also like to have options set number and set spell in their .vimrc.

4.2.1 Options for dark screens (e.g. in PuTTY)Indexup to index

If you use a terminal emulator with a dark/black background (e.g. PuTTY), you will find that VIM chooses poor colours for syntax highlighting. In particular, comment lines (starting with hashtag #) are shown as an unreadable dark blue colour on black.

You can tell VIM to use a different colour scheme for dark terminal backgrounds using either of these commands (which can be put in your .vimrc too). Pick one or the other:

:set background=dark
:colorscheme desert

Note the American spelling of color. You can get direct help on the colorscheme command inside VIM, and you can get help on the set command inside VIM and search for background in the set help page.

4.2.2 Enable your keypad (e.g. in PuTTY)Indexup to index

If you find that your keypad doesn’t work properly inside VI, try turning off “Application Keypad Mode” in your terminal program. In the PuTTY terminal program, you do that under Terminal, Features, Disable application keypad mode: screenshot

5 Absolute bare minimum basic VI commandsIndexup to index

All these commands are coverd in the vimtutor tutorial program. You may also look up the meaning of these VI/VIM commands on your reference sheet:

a i x dd
h j k l
:r file
:w file

The above commands will perform most any edit on any file you have. All the other things in VI simply make the editing faster and get you better marks (and a better job) in less time. Any job interview will ask you to edit a file and watch how proficient you are at making changes.

Some of the other VI commands make the editing much, much faster. Compare dd (delete a whole line) with typing 80 x commands, or :1,$s/idallen/alleni/g to replace every occurence of idallen with alleni in the whole file using a single global search and replace!

6 What to learn Next in VIIndexup to index

Use any of the online tutorials to learn more.

Other useful things to know in VI, in vague order of importance:

u ^R                     -- undo and redo
p P                      -- put (after yank or delete)
/search string           -- search for pattern in file
.                        -- repeat last change
r                        -- replace one character
o O                      -- start a new, empty input line
5dd 10x                  -- repeat counts on most commands
0 ^ $ H L M              -- position cursor on screen
A I                      -- insert text at end/start of line
U                        -- undo all changes on current line
cc s                     -- change current line, current char
f F                      -- move forward/backward to character
!!                       -- pipe text into any Unix command
:1,$s/pattern/new text/g -- global search and replace
:set showcmd             -- show partial commands in status line
:set showmode            -- show INPUT mode
:set confirm             -- ask before quitting modified buffer
:set ruler               -- show current file position
:set autoindent          -- auto-indent lines of code
:set wrapmargin=5        -- wrap input text at column 75
:set number              -- show buffer with line numbers
:syntax off              -- turn off syntax highlighting
:$r file                 -- read file in at end of buffer
:$r! program             -- read standard output of executing program

The VIM tutoral has details on many of these commands.

7 Appendix: Two cool VIM features used by sysadminIndexup to index

7.1 Send any number of lines to an external commandIndexup to index

You can send any number of lines from your editor buffer into the standard input of any command. The command may process those lines and the output of the command will replace the lines in the editor buffer. The command you run doesn’t even need to read standard input; the output of the command will replace the lines in the editor buffer.

  1. Open a new file in VIM and enter a dozen lines of random text into the editor.
  2. Move your cursor to the first line in the file and type this four-character command followed by [Enter]: !Gwc
    • This sends all lines from the cursor to end-of-file into wc and replaces all the lines with the output of wc
  3. Undo the last change. (The output from wc disappears and the original lines return.)
  4. Move your cursor to the first line of the file and type this five-character command followed by [Enter]: !Gsum
    • This sends all lines from the cursor to end-of-file into sum and replaces all the lines with the output of sum
  5. Undo the last change. (The output from sum disappears and the original lines return.)
  6. Move the cursor to the first line in the file and type this six-character command followed by [Enter]: !Gsort
    • All the lines are run through the sort command.
  7. Go to any line and execute: !!date
    • The line is replaced by the output of the date command.
  8. Move the cursor to any line in the file and open a new blank line.
  9. On the new blank line type this command text: ls -li /etc/passwd*
  10. Now, use VIM to send the current line into bash by typing this six-character command followed by [Enter]: !!bash
    • This sends just the current line (!!) into the bash shell program
    • The bash shell executes the commands it is reading on standard input and the output goes on standard output, into the editor
    • you should see the output of the ls command replacing the line
  11. Quit the editor without saving anything.

7.2 Record any sequence of VIM edit commands in a repeatable macroIndexup to index

You can record any simple or complex sequence of editor commands into a single-letter macro that you can re-execute. Recorded macros are not saved when you exit the editor, but you can save them yourself by defining them in your .vimrc file.

We will define a macro that adds stars after the fourth colon character in a line.

  1. Copy the text file /etc/passwd into the current directory. Open the copy of the file in the vim editor.
  2. Go to the beginning of the top line of the file (type two characters): gg
  3. Record a macro named q by typing qq that will turn on the recording flag in the bottom line status bar. You are now recording all the vim commands you are typing into buffer q. Do these exact commands:
    1. Move forward in this top line to the fourth colon (type three characters): 4f:
    2. Append three asterisks and a space after the cursor (and always exit insert mode with ESC; type five characters): a*** ESC The first line of the file should now have three asterisks in it, located after the fourth colon character.
    3. Make sure you are no longer in input mode. (Use ESC!) Close the editing macro by typing a single q that turns off the recording flag. The recording flag should be gone from the status bar at the bottom of your screen. Macro q is ready to use.
  4. Move to the beginning of any other line in the file and re-execute this macro by typing: @q Note how the macro executes the same editor commands and makes the same change to this line.
  5. Move to the second colon in any line in the document and re-execute the macro: @q Note how the macro makes the same change after the sixth colon, because it moves forward four colons from your current position.

You can record macros that make extremely complex changes to a file and then make those same changes in other parts of the file using the macro.

You can view or modify the contents of any recorded macro:

  1. Go to the last line of the file and create a new blank line (type two characters followed by ESC): GoESC
  2. Make sure you are not in input mode. On this blank line dump the macro contents by typing three characters: "qp (that is just one double quote character at the start) You should see this: 4f:a*** ^[
  3. Change the three asterisks on the line to be the words Fancy Macro. The line should now look like this: 4f:aFancy Macro ^[
  4. Save the line into the macro buffer q using four characters: "qyy (that is just one double quote character at the start)
  5. Go to any line and try the new macro. Instead of adding asterisks, it will add the words “Fancy Macro”.

You can dump and modify any macro after you have recorded it.

8 Appendix: Using VIM over a remote connectionIndexup to index

This section is only for people using VI/VIM over a remote connection. If you use VI/VIM in a Linux terminal window, things usually work fine.

Make sure your terminal is correctly configured before you enter VI remotely! The VI/VIM editors must know how to drive your terminal during an edit session; if you see anything about an “unknown” terminal type when you start up the editor, you must exit immediately and fix the terminal type to be one that VI/VIM recognizes.

Be careful when you resize a window containing a VI/VIM session. A remote session of VI on another machine may not pick up the new window size, and what you see on your screen may get garbled. (If this happens, quit VI, type “resize” at the shell prompt, and restart VI again.)

To be safe, do not change the size of a VI/VIM window when the editor is open in a remote window.

If you use telnet/PuTTY from under Windows to connect to a Unix machine, make sure you have NO SCROLL BARS VISIBLE in your telnet window! Set the correct number of lines and correct terminal type when you start telnet, and don’t change them. (This won’t be a problem for people working from a Unix machine, since Unix is good about passing the window size to VI.)

The “resize” command is useful to set the number of lines correctly after you use telnet or ssh to connect to the remote machine:

$ resize

9 Appendix: Finding a missing vimtutor VIM TutorialIndexup to index

If the command vimtutor doesn’t work, you will have to locate and copy the tutorial file yourself. On most Unix/Linux machines, you will find the tutorial somewhere under the directories /usr/share/vim* or /usr/local/share/vim*, e.g. possibly /usr/share/vim/tutor/tutor. Different Unix systems put the tutorial in different places; go look for the file named tutor under the above places.

The VIM tutorial is a file named tutor under directory /usr/share/vim/vim63/tutor/ on Fedora 12 and under /usr/share/vim/tutor/ on most Linux systems.

The vimtutor command startes up VIM on a fresh copy of the tutorial file. If you are not using vimtutor, you must copy the tutorial file into your own directory first:

$ cd
$ cp /usr/share/vim/tutor/tutor tutor     # use the actual pathname!
$ vim tutor

Use the actual pathname to the tutor file on your system. Follow the instructions in the tutorial.

The VIM tutorial was written to be used under various operating systems, including MS-DOS; so, it has one or two MS-DOS specific external commands in it (e.g. there is no DEL command in Unix – use rm instead!). Also, if you have set ruler turned on, the Ctrl-g command will not show your current line number; because, the ruler line already shows it for you.

10 Appendix: Other VIM resourcesIndexup to index

You can find good “cheat sheets” on VI by searching on the Internet for “vi editor cheat sheet” or “vi editor summary pdf” or “vi reference card”.

I’ve edited the front side to make some of the text clearer and to add some missing “essential” commands such as ^R (redo). The back side is optional.

You may find these useful. URLs come and go; but, these were working at one point:

There are other reference cards and cheat sheets. Here are a few more:

VIM User
Browserling – Trying to Exit VIM
Real Programmers Use VIM
| Ian! D. Allen, BA, MMath  -  -  Ottawa, Ontario, Canada
| Home Page:   Contact Improv:
| College professor (Free/Libre GNU+Linux) at:
| Defend digital freedom:  and have fun:

Plain Text - plain text version of this page in Pandoc Markdown format

Campaign for non-browser-specific HTML   Valid XHTML 1.0 Transitional   Valid CSS!   Creative Commons by nc sa 3.0   Hacker Ideals Emblem   Author Ian! D. Allen