Nuxified

FOSS technologies explained

  • Useful Articles
  • Blogs
  • Images
  • Tips
  • Archives
You are here: Home / vi survival guide

vi survival guide

1. Introduction
2. Basic crash course
3. Other Modes
3.1. A guide to NORMAL mode
3.1.1. Movement
3.1.2. Modifying, Deleting, Copying, Pasting
3.1.3. Repetition and how to avoid it
3.2. Ex mode
4. Searching and replacing
APPENDIX. VIM – Vi IMproved
APPENDIX.1. VISUAL mode
APPENDIX.2. Multiple Windows
Final Words

1. Introduction

If you are trying to work at a command line in pretty much any Operating System, no matter if it is a GNU/Linux brand such as Ubuntu or Fedora Core, another UNIX-like system like Mac OS X or FreeBSD or even Microsoft Windows, you will most definately need a text editor sooner or later. If you are using a UNIX-like system, like GNU/Linux variants, there are many text editors that may or may not be installed. Luckily there is one de-facto standard:
vi is included in almost every GNU/Linux or UNIX distribution. “vi” is a truncation of the word “visual” and has, contrary to popular belief, nothing to do with the Roman number 6. Many people are not too fond of vi, but are, alas, often forced into using it when it is the only known option. You may prefer easier editors like gedit (Gnome), kate (KDE), emacs or ne (command line), but these may not be present when working at the command line.
Therefore, it is best to know at least the basics of vi and to understand it a little better; the basics of survival in vi, which you will learn in this guide. Unlike what you may have heard about the invention of the language C, the vi editor was not the idea of some kind of sick joke. It was for real and it served a real purpose. I am writing this in vi.

vi is very old, 1976 to be exact – that is only 6 years after 1970-01-01, which is the second no. 0, the big bang, the birth of Jesus Christ of UNIX system clocks. In the age of informatin and the internet, 30 years is practically a century. Remembering the age can help you to accept it if you do not particularly like it. Still, however, many people like the fact that they can memorize the keystrokes and be at home with it for quick tasks, and they like its tiny footprint of disk space and RAM. They like it both as the old reliable standard on most distributions of GNU/Linux and as a simple but powerful editing tool.

Individuals who use computers for office work or leisure purposes may find the vi editor as an excellent tool for editing scripts in GNU/Linux and other UNIX like systems. In addition, this command line text editor may also be handy when configuring remote terminals over broadband internet connection, such as dedicated or virtual private servers.

The vi editor has an interesting history. It was created in a Berkeley University dorm room, Evans Hall, in 1976 by Bill Joy and some of his friends, although he was the one who fleshed most of it out, using the Pascal language. He designed it for a version of Unix he was working on at Berkeley University called BSD Unix, which stands for Berkeley Software Distribution Unix and forms the base of some modern Unices such as the polular FreeBSD.
Bill Joy eventually moved on to Sun Microsystems as one of its original founding members and has since moved on to other projects. Before Bill wrote vi, the students at the university were using an editor called ed. The ed tool, still as widespread as vi, unfortunately, is much harder to use. The students
discovered that they could use terminal escape codes so that the terminal moved the cursor to the bottom, and they dubbed this “open mode” where short commands could be typed. There were later derivatives of the ed tool called em and en, and students were experimenting with reprogramming each and borrowing each other’s features. Eventually the most popular became Bill’s project, vi. When the VAX came about, the terminal escape codes standardized as VT100 (Vax Terminal 100) and this carried over into the BSD Unix and is still there today, implemented, for example, in the Linux console and xterm. These codes were utilized in moving the cursor around in the editor, scrolling sections, blocking off certain sections so that they do not
scroll, and other cursor movement features. Anyway, what is most important to note about vi’s history is that there was very limited memory and disk space, so commands seemed to be more efficient if they were short keystrokes, rather than typing words. Also, menus and even a mouse weren’t invented yet at XEROX PARC center, so short keystroke commands seemed to fit the ticket. Dan Bricklin’s Visicalc program would later hinge off of that aspect and use keystrokes the brought up menus, and that approach led to the success of Lotus 1-2-3. So short keystrokes it became, and each of us who use Linux should get to know how to survive in using these keystrokes. Like many things in Unix and Linux, when enough people know about a command and
depend on it, it becomes one of the defacto items that just has to be rolled in with it, like it or leave it, or enough people will complain.

back to top

2. Basic crash course

Let’s start with the most basic vi knowledge – what you will need to use vi when it is the only choice. vi is different from most editors in that it has different so-called modes. When you start vi, you are in NORMAL mode. Here every key has some special function. For example, pressing ‘x’ deletes the character under the cursor. Beginners will start off preferring the INSERT mode; you enter it by pressing ‘i’ in NORMAL mode. Here letters are letters, backspace is backspace etc – like in any old editor. This is a kind of “safe” mode for beginners, as, unlike in NORMAL mode, keys don’t do unexpected things. When you have made the changes you want, switch back to NORMAL mode by pressing <ESC>. You can always return to insert mode by pressing i. Now you will want to do some special things such as saving. Here are some command you
should know:

:w <ENTER> write file
:wq <ENTER> write file and quit
:w FILENAME <ENTER> write file as FILENAME
:e FILENAME <ENTER> edit file FILENAME
:q <ENTER> quit
:q! <ENTER> quit without saving

back to top

3. Other Modes

By now you should be able to survive in vi for a quick config file edit, code hack or simple ASCII art.But vi is a lot more than insert mode…

3.1. A guide to NORMAL mode

Normal mode is, as you may have gathered or guessed the vi mode. You can do almost anything from inside NORMAL mode.

3.1.1. Movement

Even in NORMAL mode, you can use the arrow keys to navigate, but this always means moving your hand from the letters to the arrow keys and back, resulting in some latency. On laptop keyboards, this is especially inconvieneant. Instead, vi offers the following movement keys:

k up
h left l right
j down

On most keyboards, these keys are under a touch typist’s right hand
and thus very accessible. By the way, vi is a perfect editor to learn
touch
typing with ! These keys can be memorized in different ways. h and l are the furthest left and right of the set; the letter j
looks slightly like it’s pointing downward and the key usually has a little stud (for finding the key when touch typing) at the bottom.

Here are some more movement keys, some of which are especially useful in combination with other commands (see next section):

Inside the line
$ moves to the end of the line
0 moves to the beginning of the line
^ moves to the first non-whitespace character – i.e. the beginning of an indented line.
Movement via words (where a word is a sequence of alphanumeric OR punctuation signs)
w next word
e end of current word
b previous word
Movement via words (where a word is a sequence of non-blank characters)
W next word
E end of current word
B previous word
Other Jumps
H jump to top of screen
L jump to bottom of screen
{ jump to previous paragraph
} jump to next paragraph
fx jump to next occurence of character x (where x is any character, of course)
tx jump right before next occurence of character x (’till x) (again, x in anything)
Fx jump to previous occurence of character x (again, x in anything)
Tx jump right after previous occurence of character x (back ’till x) (again, x in anything)
G jump to EOF (End of file)
LINE G jump to line no. LINE

3.1.2. Modifying, Deleting, Copying, Pasting

Obviously, you are in vi to edit text. You could also be in vi to hear beeps when you press some wierd keys, but then you probably wouldn’t be reading a guide to vi. You have already learned about INSERT mode, but there is more to it that just ‘i’ ! To “just” get into INSERT mode, you can use the following commands:

i places you in INSERT mode before the current character.
I places you in INSERT mode at the beginning of the line. Same as ^i
a places you in INSERT mode after the current character. Same as i<RIGHT-ARROW> (or li when not at the eng of the line)
A places you in INSERT mode at the end of the line. Same as $a
o places you in INSERT mode in a new line below the current one. Same as $i<ENTER>
O places you in INSERT mode in a new line above the current one. Same as ko

vi also offers simple command for single-character deleting and editing:

x delete character under cursor. like <DEL> in INSERT mode.
X deletes the previous character. like Backspace in INSERT mode.
rx replace the character under the cursor with character x (where x is any character)

Now let’s go over to some more larger-scale editing in NORMAL mode, as you seriously don’t want to use ‘x’ or ‘X’ to delete a paragraph of text, for example. This is also the movement commands from section 3.1.1. become really useful.

d{motion} delete all text up to the destination of movement {motion}
c{motion} delete all text up to the destination of movement {motion} and enter INSERT mode (change the text)
y{motion} copy (yank in vi-speak) all text up to the destination of movement {motion}
p paste (or put) the last deleted, changed or yanked text after the current position
P paste (or put) the last deleted, changed or yanked text before the current position

for better comprehention, a few examples are in order.

dw delete up to the beginning of the next word
{c} change current paragraph
ywP duplicate word

There are also a few special cases, namely:

dd deleted current line
cc change current line
yy yank current line

when you delete, change or yank a line, p and P also operate line-wise: p places the yanked line after the current line, P places it before the current line.

3.1.3. Repetition and how to avoid it

Repetition is annoying and senceless. vi has some features to make your edit easier in this respect. First of all comes the command . (yes, the period.); it repeats the last command. For instance, if your last command wasdd, then pressing . deletes another line.
Counts are another very useful feature that let you repeat a command a specific number of times. The syntax is as follows:

{number}{command} do {command} {number} times.

This also works for motions that are part of a command. A few examples:

10j move 10 lines down
3yy yank three lines
c3w change 3 words

To round the section off, I’ll show you some commands that every editor, including Microsoft® Notepad, supports:

u undo last command (including INSERT mode sessions)
<Ctrl+r> redo last undone command

Unlike Microsoft® Notepad, vi supports doing this multiple times.

3.2. Ex mode

“ex mode” is a command-line like mode. in it you can type certain longer commands, which are executed by typing <ENTER> There are multiple ways to use it:

:{ex-mode command} execute one ex mode command
gQ enter ex mode

Sound familiar ? the saving, editing and quitting commands in section 2 where actually ex mode commands. Here are some important ex mode commands:
(without the colon): part in square brackets are optional.

w[rite] [FILENAME] write file to FILENAME (if given)
w[rite]! FILENAME write file to FILENAME, overwriting if it exists.
e[dit] FILENAME edit FILENAME
e[dit]! FILENAME edit FILENAME without saving
q[uit] quit
q[uit]! quit without saving
! COMMAND execute shell command COMMAND
vi[sual] exit ex mode

back to top

4. Searching and replacing

Searching and replacing are two very important features when editing text files; just think of how easy it is to lose a line in a large config file or on an enourmous screen. I’ll start with the simpler of the two: searching. The commands are issued in NORMAL mode.

/REGEX search for strings matching the regular expression /REGEX/.
?REGEX search for strings matching the regular expression /REGEX/ backwards.
n go to next occurence
N go to previous occurence

This may sound dreadfully complicated to you, who may be thinking along the lines of “regular expression… huh?”. Well, don’t panic. Regular expressions are a standardized way of expressing patterns to search for. The syntax is not easy to understand and is beyond the scope of this document. So you get the idea what it is, I’ll give a few examples: ‘[0-9]{1,3}’ matches any one to three-digit number and ‘joe’ matches the three letters ‘joe’ (lowercase) and nothing else. If you’re not dealing with special characters, you can forget about the regex buisiness.

Now to replacing. The syntax was inherited from [s]ed, so it will be familiar to the gurus Eye These are ex mode commands, and again use regular expressions, this time with bracket substitution, as it is replacing. (again, you can safely ignore that mostof the time)

s/foo/bar/ replace the first occurence of foo on the current line with bar
s/foo/bar/g replace all occurences of foo on the current line with bar
%s/foo/bar/[g] perform s/foo/bar/[g] on every line in the file.
X,Ys/foo/bar/ perform s/foo/bar/[g] on every line between line # X and # Y.

APPENDIX. VIM – Vi IMproved

There are many vi clones and dereviatives out there. In fact, when you open “vi”, you will probably not see the original vi, but a clone like nvi or vim. VIM is probably by far the most advanced clone; it has numerous features that are, among others, interesting for programmers. Here I will explain two
features that are, in my eyes, the most interesting additions apart from syntax highlighting, which is enabled with the ex command syntax on: Multiple windows and VISUAL mode.

APPENDIX.1. VISUAL mode

Yes, another mode. In this mode, you can select text and perform operations that usually take a movement as argument. For example, selecting text and pressing ‘d’ will delete the text. As usual, you enter VISUAL mode from NORMAL mode, but unlike the other modes, VISUAL has multiple (three) sub-modes.

v Enter normal VISUAL mode
V Enter VISUAL LINE mode
<Ctrl+v> Enter VISUAL BLOCK mode

normal VISUAL mode

This is pretty much like selecting in most graphical editors: you select character-wise. Let me show you an example:

Some text text text just to show the readers what VISUAL mode is all about. As I said this is:
    Some text text text just to show the readers what VISUAL mode is all about. As I said this is:
        Some text text text just to show the readers what VISUAL mode is all about. As I said this is:
Some text text text just to show the readers what VISUAL mode is all about. As I said this is:
    Some text text text just to show the readers what VISUAL mode is all about. As I said this is:
        Some text text text just to show the readers what VISUAL mode is all about. As I said this is:

VISUAL LINE

This is a little bit niftier. It selects line-wise, not
character-wise. Doing ‘d’ on VISUAL LINE selected text is like doing
‘dd’ on all the lines.

Some text text text just to show the readers what VISUAL mode is all about. As I said this is:
    Some text text text just to show the readers what VISUAL mode is all about. As I said this is:
Some text text text just to show the readers what VISUAL mode is all about. As I said this is: Some text text text just to show the readers what VISUAL mode is all about. As I said this is: Some text text text just to show the readers what VISUAL mode is all about. As I said this is:
        Some text text text just to show the readers what VISUAL mode is all about. As I said this is:

VISUAL BLOCK

This is the niftiest of selection modes. Here you select blocks (duh). I cannot convey this better than with the example below.

Some text text text just to show the readers what VISUAL mode is all about. As I said this is:

Some text text text just to show the readers what VISUAL mode is all about. As I said this is:
Some text text text just to show the readers what VISUAL mode is all about. As I said this is:
Some text text text just to show the readers what VISUAL mode is all about. As I said this is:
Some text text text just to show the readers what VISUAL mode is all about. As I said this is:
Some text text text just to show the readers what VISUAL mode is all about. As I said this is:

APPENDIX.2. Multiple Windows

Vim has support for splitting the screen into multiple windows. These are not the overlapping windows you know from popular graphical user interfaces, these parts of a split screen as users of GNU Emacs and GNU screen will know. With them you can, for example, edit in one part of the screen and look at a different file or a different
part of the current file at the same time. To see what this is, well, grab a copy of vim and try it out ! Here I will only list the most important window-related commands. use the ex command help usr_08 in vim to get to the relevant section in the online documentation.

Window-related ex commands
split horizontally split the current window and display the current buffer (=file) in the new window
vsplit vertically split the current window and display the current buffer in the new window
new horizontally split the current window and create a new buffer in the new window.
vnew vertically split the current window and create a new buffer in the new window.
only destroy all other windows.
only! destroy all other windows, discarding unsaved changes
q destroy the current window.
qa destroy all windows (exiting vim)
qa! destroy all windows (exiting vim), discarding unsaved changes
Window-related NORMAL commands
<ctrl+w> h move one window left
<ctrl+w> j move one window down
<ctrl+w> k move one window up
<ctrl+w> l move one window right

back to top

Final Words

As you have seen, vi is a complicated, unusual editor with many annoyances to the normal user. Surprisingly, the vi editing model has greatly improved productivity of many, and, if you edit much, like a programmer, could increase your efficiency. But if you actually do decide to seriously learn vi or vim, try to use it exclusively, at least for a time. And, above all, stay away from INSERT mode as much as you can. over-using INSERT mode won’t help in the slightest if you want to really use it.

—————-
Original printable version | digg

Learn Unix

I run Unix Tutorial website and help anyone interested to pick up Unix skills. If you have questions or just want to share your ideas – please join the Unix Tutorial on Facebook.

Tech Stack Solutions

Tech Stack Solutions is my company that provides Unix support. Sign up or simply get in touch to find out how I can help!

Search this Website

You May Also Like

Recent Posts

  • Advice on using SUDO
  • FFmpeg 4.0
  • KDE Plasma 5.9.0 Release
  • How to Install Ubuntu Linux without a DVD or USB
  • How to Securely Save All Your Passwords with Keepass
  • 9 Signs You Should Use Linux on Your Computer
  • The Easiest Way to Optimize Your MySQL Database Performance
  • Setting up a Linux Web Development Environment in Windows
  • Hunting Down Disk Space Hogs on Linux Command Line
  • 6 Simple Android Apps for Monitoring and Managing Your Linux Server

Archives

Categories

  • Community Blogs
  • Images and Screenshots
  • News
  • Technical Topics
  • Useful Articles

Basic Unix Commands

Basic Unix Commands
  • ls command
  • mkdir command
  • man command in unix
  • cd command - change directory
  • uname command

Advanced Unix Commands

Advanced Unix Commands
  • ln command - symlinks
  • tune2fs unix command - filesystem parameters
  • du command - disk usage
  • lsb_release command
  • find unix command

Unix Reference

Unix Reference
  • SSH port forwarding
  • unix commands
  • visudo tutorial
  • mtime unix
  • lrwxrwxrwx
  • Unix Tutorial digest

Unix Books

Unix Tutorials

Unix How-Tos
  • check raspbian version
  • autostart in KVM
  • List files in Ubuntu package
  • check CentOS version
  • create bootable USB in MacOS
  • Useful Articles
  • Blogs
  • Images
  • Tips
  • Archives

Copyright © 2023 · Education Pro Theme on Genesis Framework · WordPress · Log in