How to use the vi (vim) editor in linux

Donald Daniel, Feb 2008, revised Aug 2021

up one level

If the lines of text are too long you can fix the problem with these instructions.

introduction

The vi editor is the most popular editor in linux. The current version is really "vim", but to invoke it simply type "vi". The text format that vi uses is the most plain elementary text format that exists, the ascii format. But files created by vi can be run through other programs that convert the files to other formats, if desired. In linux and other Unix clone operating systems the operating system and the editor do not care whether or not file names have suffixes or extensions.

Open a terminal window in your linux system and click on it to make sure it is active. You will do all your work in the terminal window. If you are not already familiar with how to open a terminal window, find what directory you are in, list the files in a directory, create a directory, move files, copy files, rename files, delete files, execute programs, add missing commands and linux command line operations in a terminal window you should first read my article how to use linux terminal .

To edit an existing file named "xyz", or create a new file named "xyz", type "vi xyz". When in vi, there are two major modes, the input mode and the edit mode. In the input mode, anything you type goes into the file. In the edit mode you can move around the file, copy, delete etc. Hit the "Esc" key to get from the input mode to the edit mode. When in the edit mode the mouse is not used to move the cursor, keyboard commands are used. The arrow keys move the cursor up, down, right, left. The space bar moves the cursor to the right. "$" moves the cursor to the end of the present line. The "enter" key moves the cursor to the beginning of the next line. "237" then the "enter" key will move ahead 237 lines in the file, unless there are less than 237 lines in the file, in which case the cursor will not move. Type "1G" to jump to the top of the file, "G" to move to the end of the file.

When the cursor is moved to a particular letter in a word in the file, press "a" to enter the insert mode after that letter, press "i" to enter the insert mode just before that letter. Type what you want in the insert mode then hit the "Esc" key to leave the insert mode and get back to the edit mode.

To write the file to disk and exit vi, type ":wq". To exit without saving the changes you have made, type ":q!".

delete

In the edit mode "d" followed by the space bar will delete one letter. "5 d" followed by the space bar will delete 5 letters. "dw" will delete to the end of the word. "dd" will delete the line. "5 dd" will delete the next 5 lines. "u" will "undelete" the last deletion if you make a mistake. "d /xyz" will delete from the present position to where the letters "xyz" are found. Suppose you have a file with many lines that have leading spaces in front of each line, and you would like to delete these leading spaces. The command ":%s/^ //g" will do this, where the number of spaces after the "^" character is the number that you want to delete. The "^" character represents the beginning of a line. To delete all complete lines containing "xyz", use ":g/xyz/d". To delete all complete lines that do NOT contain "xyz" use ":g!/xyz/d". An example of how to delete carriage returns is given below in the section about line numbers. Occasionally you may download a text file that is good except for some very long lines that are of no use. To remove these long lines, do not use vi, use sed. An example:

sed '/.\{398\}/d' file1 > file2 

This will create file2 with the lines longer than 398 characters removed from file1.

moving text

Delete what you want to copy. If you want to leave it there before you move elsewhere to copy it, type "u". Then move where you want to copy it. "p" will write out the last deletion on the line below where ever you are when you type "p", as many times as you type "p". To join the line below to the end of the current line, type "J". Suppose you want to copy an external file named "file" to the line below where your cursor is. If the file is in the same directory, type ":r file". If I were in my directory "wkspc/scratch", and wanted to copy a file from my home directory, I would type ":r ~/file", but if I wanted a file from my directory "wkspc/back" I would type ":r ~/wkspc/back/file" or ":r ../back/file", either one would work. For explanation of this see how to use linux terminal

find and replace

"/xyz" will find the next occurrence of "xyz". "n" will find the next one after that. "?xyz" will search backwards. If you are creating a large document or program with vi, and are repeatedly making changes to the middle of it, you can use the find command to quickly go back to the place where you left off. Just leave "xyz" or anything else you are sure would not be a legitimate part of the document at the place you will want to go back to when you get back to work, and you can quicly find your place. The next example is "/\<cat\>". This will find "cat" without finding "catalog". This is very handy for finding variables in a program you are writing. ":121,135s/cat/dog/g" will replace all occurrences of cat with dog from lines 121 to 135. ":%s/cat/dog/g will do the same for the whole file. But these will replace "catalog" with "dogalog". ":%s/cat//g" will delete all cat in the whole file. Another important example is ":%s/\<cat\>/dog/g". This will replace all occurrences of "cat" with "dog" without replacing "catalog" with "dogalog". This is very handy for changing variable names in a program. This command takes into account the conventions of computer programming. Thus "x:=cat+5;" would be changed, but "x:=cat2+5;" would not. Note that spaces are not necessary on either side of "cat". This is probably the most essential feature for any editor that is to be used for writing computer programs. If you are interested in learning to write programs click here. To search for the string "get / http" type "/get \/ http". This is because the the "\" means treat the next character as a character, not a command or a wildcard. If you have lots of different words that must be replaced by other words the "so" command can be used with a file listing the words and their replacements. An example is given in the "programming hints" article here.

commands that use line numbers

":nu" tells the number of the line that the cursor is on. ":13,26 w! temp" writes a copy of lines 13 to 26 to an external file named "temp" without deleting the lines. ":48,53 w >> temp" will add the contents of lines 48 to 53 to the end of file "temp". ":125,248 !fmt -uw 65" does word wrap to make all the lines from 125 to 248 equal to or less than 65 characters in length. To remove carriage returns such as windows files have from lines 22 to 44 type ":22,44 !tr -d '\r'". To make all letters from line 125 to line 248 lower case, use ":125,248 !tr A-Z a-z". Using the "!" symbol in this particular way when you are in the vi editor executes a program that is external to the vi editor. To see what else could be done with the "tr" program, when you are NOT in the vi editor enter "man tr".

There are many, many more commands in vi, but these are probably the most important.

spell checking

If you create the file xyz with the vi editor, you can correct the spelling errors with a program called "ispell". When you are not in vi, "ispell xyz" will find spelling errors, and ask you if you want to correct them. When finished, the file xyz will have errors corrected, and xyz.bak will be the original file with errors.

I have used ispell on an html document containing computer programs without messing up the programs.

If modifying or inserting a paragraph in a long existing document, you do not want to run ispell on the whole document. Use the "w" command to write the paragraph out to a temporary file called "temp". Modify temp as you wish. Run ispell on temp. Then use the "r" command to copy temp back into your long document.

fancy text and html

If you want to create a large formal document, and if ordinary ascii text is all you need, and you do not need fancy text, or special symbols, the vi editor can create files that will be formatted and indexed by the linux word processor programs "nroff", "groff" and "troff".

The vi editor is adequate for writing computer programs and simple text applications. If you want to create a document that requires advanced features such as characters that are not on the keyboard like greek letters or math symbols, or embedded graphics in your document, there are two ways to do this.

The first way to create fancy text is in the form of a pdf document. The vi editor can be used to create the source file for a fancy word processing system on linux known as latex, which is found in the "texlive-latex-base" package that can be installed on linux. The instructions are in the "texlive-latex-base-doc" package. This technique is described here. An example of this at this website is given by the pdf document here.

The second way to create fancy text is as a png file to be imbedded in an html document. The vi editor can be used to write html web pages. This entire website was written with vi, and the html checked for errors with the linux program "tidy". You can see how to write html by saving this page to disk as an html file, and looking at the html file with the vi editor. Unfortunately, many browsers modify html files before they save them to disk. To get the original unmodified form of this web page use the linux "wget" program as follows:

wget www.waltzballs.org/other/linux/vi.html

After issuing the above command, if you enter "ls" you will see "vi.html" listed in your terminal window, which you can then examine with the vi editor. The first few lines down to the word "title" are the same for all of my html files, and you can just copy them the way they are. The last two lines at the bottom of the file are necessary in any html file.

If you are going to use the tidy program, you will probably want a ".tidyrc" configuration file in your home directory. The leading period "." in the file name is essential. My .tidyrc is as follows:

indent: auto
-asxhtml
output-xhtml: yes
wrap: 63

If your html document contains the source code of a program, you can use tidy on it. You will need < pre > before your program and < / pre > after to preserve the original format of your program. Tidy will work fine with all programming conventions except one. While compilers often do not require spaces on either side of "<" and ">" characters, tidy does except when they are used in html formatting commands or between quotes. Tidy will make your program look in a browser the way that it originally looked. But if you use the vi editor to look at the program in your html document after running tidy, "<", ">", and "&" characters will look different. That is because they are expressed differently in html so they will display correctly in your browser.

The simplest way to make the simplest html document using vi is to create a document with each paragraph starting with <p> at the beginning of the first line of the paragraph. Leave a blank line between each paragraph. Then execute the command "tidy -m myfile". Tidy will complain with error messages. But the second time you execute the command you will see that there are no errors, you have a perfectly good html document. If errors persist, and you want to see what the errors are, "tidy -f err myfile" will put the errors in the file "err" so you can see what they are. If an error is on line 348, when in myfile at the top, enter 347 then hit enter key and the cursor will jump to line 348.

You will have a copy of your html web site on your computer. Suppose it is in your directory "doc". If you have the "linkchecker" program installed, you can check the links in your website by issuing the command "linkchecker doc > temp". Then examine the file "temp" with the vi editor to see any errors in your links.

After you have created an html file, if you want to upload it to a website you can use the linux program "ftp". Ftp will also work to download the log file on your website that records the usage of the website. If your web hosting service uses a secure version of ftp, you can use synaptic to install the "ftp-ssl" package or the "sftpcloudfs" package, depending on which version your hosting service requires. If your logfile is "logfile", then "webalizer logfile" will create an html document giving statistics on the hits on your website.

A very simple example of fancy text is the following equation that includes a greek letter:

demo.png

It was produced with the vi editor writing a file of postscript code as follows:

%!PS
100 400 moveto
/Latin-Modern-Roman 16 selectfont
(a = ) show
/Symbol 16 selectfont
(w) show
0 7 rmoveto
/Latin-Modern-Roman 16 selectfont
save
0.8 0.8 scale
(2) show
restore
7 -7 rmoveto
(r) show
showpage

You may worry that you have not had a course in programming postscript. Do not worry, read this program and you will be able to see how it works. The first line just says the file is postscript. The first "moveto" statement just moves to an arbitrary convenient location on the page. The units are 1/72 of an inch (0.03527cm). While we have the symbol font selected the letter "w" represents the greek letter omega.

The "gv" program was used to see our file as we created it and debugged it. As first created the postscript file represents a whole page with the text on it. We do not want a whole page, we just want a small snippet of text. So we must convert it from a plain postscript file to an encapsulated postscript file. We use the program "ps2eps" to produce an eps file. Now our file is encapsulated postscript. Then start the "gimp" program, "file" "open" "import" the eps file, then "file" "save as" change the suffix from eps to png, then "save". Now we have a good png version. We can imbed this in an html document with an "img" statement.

Some symbols in the symbol font are beyond the range of the keyboard, and must be specified by an octal number. For example, if you search the web for the symbol font, you can find that the decimal number for the first character of the square root sign is 214. If you install the wcalc command, "wcalc -o 214" gives the octal equivalent 0326. In your postscript file "(\326) show" will produce the character.

printing

After you have finished file "xyz" and got out of the vi editor, you could print it with "lpr xyz". However, this might not be very satisfactory, because the printout would have no left margin, no top and bottom margins, and no page numbers. If you have already formatted it with the previously mentioned programs such as "nroff", it will have margins ready to print. If not, there is a quick and dirty way that we will describe now. A slightly better result is obtained with the command "pr -fl 56 -o 8 xyz > temp". Here 56 is the number of lines arbitrarily chosen to be printed on each page. You can use the vi editor to see if the file "temp" is properly formatted, then "lpr temp" to print it.

I prefer one inch (2.54cm) margins on all four edges of the paper. The "pr" command is used when you are not in the vi editor. The left margin is determined by the "-o" option. The right margin is determined by the "fmt" command described in a previous paragraph, which is used when you are still in the vi editor. The top margin is determined by the "-h" option as described below. The bottom margin is determined by the "-l" option, shown here combined with the "-f" option as the "-fl" option.

pr -fl 59 -o 8 -D "" -h "
> 
> 
> 
> " xyz > temp

In this example the ">" characters on the left edge were not entered as such, and only appeared because we hit the "enter" key on the keyboard. But the > character before the word "temp" was entered as such. Note that a single double quote character follows the -h option and a second double quote character follows the fourth time we hit the enter key.

It is troublesome to enter such a complicated command manually. It is not necessary. Create the following file called "prt" with your vi editor:

pr -fl 59 -o 8 -D "" -h "
 
 
 
" $1 > temp

When you are NOT in the vi editor, enter the command "chmod +x prt". This will make the file an executable script. If this file is in the directory where you are working, then "./prt xyz" will produce the formatted file "temp". The leading period "." is essential. If you temporarily become superuser then you will be able to move the file "prt" to /usr/local/bin. Then as ordinary user simply "prt xyz" will produce the same result.

An even better simple formatter is given in source code here.

programming

Vi is a good editor for creating computer programs in linux for programming languages which require compilation with a compiler. Compiled languages run faster than interpreted languages. The program written with vi is then compiled with the compiler for the particular language that the program is written in. The file produced by the compiler is then linked by a linker with other compiled files, if any, to produce an executable file. The executable file is then executed to run the program.

Linux is a re-write of an older operating system, Unix. Unix was written in the compiled computer language C, so linux is written in C. As a result C is probably the most popular computer language today, just as a result of a historical accident. It is most definitely not the best programming language today. My favorite is Oberon-2, which is described in my article how to program a computer.

Program text cannot be formatted with the "fmt" command that is appropriate for ordinary text. Program text must be formatted manually. To do this it is helpful to create a file in your home directory named ".scale". The leading period makes it invisible when you list the contents of your home directory with the "ls" command. When you are in the vi editor in any directory working on a program, the command ":r ~/.scale" will add the scale file in your program like this:

1234567890123456789012345678901234567890123456789012345678901234567890
         10        20        30        40        50        60        70

This scale file will allow you to manually adjust program text to the number of characters per line you desire. You will delete the scale after you have adjusted the program text.

when not to use vi

Sometimes what you want to do could be done in vi, but there is a better way.

If you want to join several small files to make one big file, you could use the ":r" command in vi described above. But an easier way is to use the "cat" command when not in vi. "cat" stands for "concatenate", or "join". Thus "cat file1 file2 file3 > bigfile" is easier than using vi.

If you only want to see the last few lines of a large file, just the tail end, you could use the "G" command in vi, but an easier way is to use the "tail" command when not in vi. "tail file" will list the last few lines of a file.

Suppose you have many files in different directories and you want to find which files have the word "elephant". You could look at each file in each directory with the vi editor and search for the word in each file. But that would take a lot of time. When you are in your home directory and not in vi, the command "grep -r elephant *" will find it instantly.

up one level

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.