0% found this document useful (0 votes)
27 views

Unix Unit 2 Part 1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Unix Unit 2 Part 1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

The vi Editor

1211
complet ion and multiple
• Learn t~ use the two powerfu l features available in via--wo rd
undoing .
7 .1 vi BASICS
filename s01Detext:
For a quick tour ofvi, let's add some text to a file. Invoke vi with the
Th e Vi Edita vi sometex t
In all probabili ty, the file doesn't exist, and vi presents you a full screen
with the filename shown at
(
NoIImatter
h
at ~or
d
k you o w1'th the UNIX
h e to edit
system, you'Jl eventual
some of
fil
B
ly .write some C progr,._
the system I es at times. For all this You~,
. J
I the bonom with the qualifier , [New File]. The cursor is position ed at
lines ofthe screen (except the last) show a -. You can't take your cursor there
the top and alJ remaini ng
yet; they arc nonexist ent
text. This line is also used
lines. The last line is reserved for comman ds that you can enter to act on
1
w .
) cnpts You may av
..
• •and UNIX provides a very versatile one-vf . 1B11 oy created
M this cd''
she
I to peransc:d1tor,
oruse: II UNIX lltf~
by the system to display messages .
earnBSD system. The program is now standard on d' a h systems.
t d' dram1 oolenaar imp 1 is the mode where you
the
. 'll
the fe•ru. You are now in the Comman d Mode, one ofthe three modes used by vi. This
d " II , d ..
..• ••available • (..• ,·mproved). In this text we 1scuss t e v e ttor an a so note
•in• iLinux.
can pass comman ds to act on text, using most of the keys of the keyboard
. Pressing a key doesn't
the next line, or deleting a
show it on screen but may perform a function like moving the cursor to
1.w, any «lito, ,t • .,,. nombe, of intemal command, 10 navigate to any point
in a "'' fil line. You can't use the Comman d Mode to enter or replace text.
«lit thmxt tb;.,_ h ,l,oallow, you to copy •nd move text within a file and also from
.,
a terminal . To enter text,
For text editing, vi uses 24 of the 25 lines that arc normally available in
,notbe,. ri offe,, eryptk, and ,om,tim« tnn<monk, intemal comman d, fo, editing Wotl0
It~
arc in this mode ready to
• ma,1 you must switch to the Input Mode. First press the key marked i, and you
<ompleo, w, ofth, keybo,ro wh,,, P"tti<ally evc,y key ha, a function . You don't need input text. Subsequ ent key depressio ns will then show up on the screen as
text input. Stan insening
,, upoow;
righ, IT of thisknowl,dg,
• wodcing book. i, all th,i i, <equin,d initially. The advance d fcatu,e, of,,;
taken in Part a few lines of text, each line followed by [Enter}, as shown in Fig. 7.1.
r of the last line. This is
WHATYouwlLLLEARJv After text entry is complete , the cursor is positione d on the last characte
is the current cursor
known as the current line and the characte r where the cursor is stationed
• Th< th.,, mod,, ;. whi,h ,, op,,a1c, fo, sharing the woddoad . key to wipe it out. If a
position . If you ~cc somethin g that shouldn 't be there, use the backspac e
• Use a r~eat factor to repeat a command multiple times. word has been m1sspelled, use [Ctrl-w} to erase the entire word.
• Use: the: Input Mode to insc:n and replace text. you'll hear a beep; a beep
• Use: the ex Mode to save: your Work. ~ow ~re~s the [Esc] key to tevert to Comman d Mode. Press it again and
m vi _md1cates that a key has been pressed unnecess arily.
• Use the Command Mode to n,...l'orm . .
Unit fo navigation.
• Use: the: word as a navigationr•u
• Delete, Yank (copy) a d . r _movement along a line.
• Undo the last ed'ti n move . text using 0'Perator.r. This is the vi editor{E nter}
J ng action and rep th I It is slow in getting started but is quite powerful [Enter}
• Search for a Pattern and repeat the eat h e ast command . It operates in three rnodes[Enter}
• Use the Cle M d scare .
All the features of ex are also availabl e[Enterj
r.
o e to perform String substitutio You can even escape to the UNIX shell{En ter}
O
T Pics OF SP£c1,u_b r,.w, __ n. I
It maintain s 26 buffers for storing chunks of text
Master the techniqu f ~ - - ~
, CO Us1
OllJe action and ("') ng a three-fun ·
111 repeat
, "ftdCtio~
the SC.arch ... sequence to (i) search for a pattern (ii) take
, action.
Fig. i'.l Inserting Some Text
i_,_~} UNIX: Concepts and Applications

The file sometext doesn't exist yet. Actually, the text that you entered hasn't bee·n saved on disk but
'
• in some temporary storage called a buffer.
extSls
• h to.thc
To save the entered text, you mu st switc
ex Mode (also known as Last Line Mode). Invoke the ex Mode from the Command Mode by entenng
a : (colon), which shows up in the last line. Enter an x and press [Enter}:
:x[Enter)
"sometext" 6 lines, 232 characters
$ _ Quits editor-back to shell prompt
The file is saved on disk and vi returns the shell prompt. To modify this file, you'll have to invoke
vi sometext again. But before moving ahead, let's summarize the modes used by vf:
• Command Mode-The default mode of the editor where every key pressed is interpreted as
a command to run on text. You'll have to be in this mode to copy and delete text. Unnecessary
pressing of [Esc] in this mode sounds a beep but also confirms that you are in this mode. .
• lnput_~odc-Every key pressed after switching to this mode actually shows up as text. This
mode is invoked by pressing one of the keys shown in Table 7.1.
• ex Mode (or Last Line Mode)-The mode used to handle files (Jike saving) and perform

substitution. p ressing a : in tile Command Mode invokes this mode. You then en ter an ex
1

I
Mod~ command followed by [Enter}. After the command is run, ~ou are back to the defau t
Command Mode.
Much of the chapter deals with Command Mode commands where most of the action is, Some of
these commands also have ex Mode equivalents which are sometimes easier to use. But a~l th_ree
:odes also have their own exclusive features and an editing session in vi involves constant switching
etwecn modes as depicted in Fig. 7.2.

7 •1-1 The Repeat Factor /


Wh en d'iscussmg ' the repeat factor as a command prefix to repeat the
• 110re (5.5), we introduced
~mqiand as many times as the prefix. vi also provides the repeat factor with many ofits Command
ode and Input Mode commands. So if the Command Mode command k moves the cursor up
~ne line, then 10k moves it up 10 lines. The repeat factor thus speeds up operations. You'H be using
it several times in this chapter.
7•1,2 The File .exrc /
The default behavior ofvi is adequate for novices, but as !?u get comfortable with it, you 'II feel the
need to customize it to behave in a way that makes wntmg programs and documents easier. vf
rea_~s the file $HOME/ .exrc (same as -/. exrc in some shell~) on star:u: Ifls _-a doesn't show this
file in your home directory, you can create or copy one. Lmux ~ser USt note that v11 generally
doesn't use .exrc but .vimrc (with exceptions). .
Many ex Mode commands can be placed mt • h.1s fil1 e so they arc davailable kin every se • v. •
. SSion. ,ou can
I
create abbreviations redefine your keys to behave differently an a. s~ ma Jle vhanable settings. ~ur
. ' . "l'b y" containmg a s ortcuts d .
• exrc will progressively develop into an exclusive 1 rar. !ways keep ab cku an settings
tbat you use regularly. It could be your most prized possession, so a a P~fthisfiJe.
The vi Editor .123 I

Fig. 7.2 The Three Modes

7.1.3 A Few Tips First


We are about to take off, but before we do that, a few tips at this stage will stand you in good stead.
You must keep them in mind at all times when you are doing work with vi:
• Undo whenev~you make a mistake. Ifyou have made a mistake in editing, either by wrongly
deleting text or insening it at a wrong location, then as a first measure, just press [Esc] and
then u to undo the last action. If that makes matters worse, use u again. Linux users should
instead use {Ctrl-r].
• Clearing the screen Ifthe screen gets garbled for some reason, use {Ctrl-l] (el) in the Command
Mode to redraw the screen. If you hit {Ctrl-l] in the Input Mode, you'll see the symbol "Lon
the screen. Use the backspace key to wipe it out, press [Esc] and then hit {Ctr/-/].
• Don't use [CapsLocJu vt commands are case-sensitive; a and A are different commands. ,
Even ifyou activate this key to enter a large block oftext in uppercase, make sure you deactivate
it after text entry is complete. \
• Avoid using the PC navigation kers As far as possible, avoid using all the standard navigation
keys like Up, Down, Left and Right, [PageUp] and [PageDown]. Many of them could fail
when you use vi over a network connection. vt provides an eta.borate set of keys for
navigation purposes.
tJ.~J UNIX: Concepts and Applications

• vi reads the TERM variable to determine the file that contains the terminal's characteriScics.Ai
discussed later (10.3), vi actually reads a system file to know the control sequences that app_ly
to the terminal name assigned to TERM. You should always check TERM whenever vi behavmn
an awkward manner.

Note: Only the keys g, K, q, v, V and z have no function in the standard vi implement.ation. Somed
them are defined, however, in vim.

7.2 INPUT MODE-ENTERING AND REPLACING TEXT


. . M d r. m
In this section, we take up all the commands that let you enter the Input O e iro the Command
k
Mode. '."'hen a key of the Input Mode is pressed, it doesn't appear on screen but subsequent cy
depressions do. We'll consider the following commands:
• Insert and append (i, a, I and A)
• Replace (r, R, sand S)
• Open a line (o and O)
Always keep • · d h
tn mm t at after you have completed text entry using any Of t hese commands
d
(except r)' you _must return to the Command Mode by pressing [Esc]. Most of these comman scan
also be used with a repeat factor, though you'll need to use it with only some of th e~.

Tip: Before you start using the Input Mode commands, enter this ex Mode command:

:set showmode[Enter}

Enter a : (the ex Mode prompt) and you'll see it appear in the last line. Follow it with the two words;;Ed
press {Enter]. showmode sets one of the parameters of the vi environment Messages like INSERT M '
REPLACE MODE or CHANGE MODE, etc. will now appear in the last line when you run an Input Mode
command. We'U learn later to make the setting permanent by placing it in $HOME/. exrc.

7.2.1 Insertion of Text (i and a)


The simplest type of input is insertion of text. Just press
Existing text will be shifted right
Pressing this key changes the mode from Command to Input. Since the showmode setting was
~ade at the beginning (with :set showmode), you'll see the ~ords IN~ERT MODE at the ?ottom-
nght corner of the screen. Further key depressions wilJ result JO text being entered and displayed
on the screen.
If the f command is invoked with the cursor positioned on exi 5cing ~e~t, text, 0 ~ its right wiJI be
·r.. d fu h · • overwntten.
. . • of text with f 1s shown 10 Fig• 7.3, aIoog
shJue rt er without bemg The msert10n
with tbe position of the cursor.
.\
The vi Edftor

the vi

t t ful 1-screen [Esc]

the vi full-screer 9editor


t
the vi full-screen editol

a. a 1ink of ex[Esc]

the vi full-screen editor. a link of ea

Fig. 7.3 Text Insertion with i Fig. 7.'I Text Appending with a

There are other methods of inputting text. To append text to the right of the cursor position, use

a Existing text will also be shifted right

followed by the text you wish to key in (Fig. 7.4). After you have finished editing, press {Esc]. With
t and a, you can append several lines of text in this way.

7.2.2 Insertion of Text at Line Extremes (I and A)


I and A behave somewhat like f and a except that they work at line extremes by performing the
necessary navigation to move there: •

I Inserts text at beginning of line.


A Appends text at end of line.

These two commands arc suitable: for converting code to comment lines in a C program (Fig. 7.5).
A comment line in C is of the: form /* comment */. Use I on an existing line that you now wish to
convert to a comment, and then enter the symbols/*. After pressing {Esc}, use A to append*/ at the
end of the line and press [Esc] again.A document author often needs to use A to continue text entry
from the point work was suspended -adding a sentence to a paragraph, for instance.

The following ll>de forks a process

t I/* [Esc]

/*lrhe following code forks a process

• A *l[E_sc}

/* The following code forks a process••


Fig. '1.5 Using I and A to Create a Comment Line in a C Program
l126J UNIX: Concepts and Applications

vi and ex aYJI one and the same editor

••It is due to Ntlltu Joy[Esc}

vi and ex are one and the same editor


It is due to William Joi
Fig. 7.6 Opening a New Line with o -

Tip: C language programmers sometimes precede a block of comment lines with a pattern likethi;'
/**********************************************************************
It seems that there are 70 asterisks here, and to draw them you should use a repeat factor. Mer YoU
have entered / in the Input Mode, press [Escj, and then enter 70a*[Escj, You'll see 70 asterisks appended
to the/.

7 .2.3 Opening a New Line (o and 0)


Many a time it has been observed that people migrating from a word-processing environment use
a convoluted sequence to open a new line below the current line. Th_ey move the cursor past the
end of the current line and press [Enter]. In vi, you use o and Oinstead. To open a line below from
anywhere in a line, simply press
0 . Opens neui line below curren_t line
This inserts an empty line below the current line (Fig. 7.6). 0 also opens a line but' above the
current line. You are free to enter as much text as you choose, spanning multiple lines if required.
Press the [Esc] key after completing text input.

7.2.4 Replacing Text (r, s, Rand S)


\
To change existing text, vi provides mainly four commands (actually, more) as shown in the heading.
To replace a single character with another, you should use 1

r No {Esc] required

lhis is the vi full-screen editor

rT
9lis is the vi full-screen editor

Fig. 7.7 Replacing a Single Character with r


The vi Editor

v1 1s


I link of ex

sone[EscJ t
vi is one of the Inks of the ex program

Rmodes[fac]

vi is one of the model of the ex program


vi is onllink of ex

Fig. 7.8 Replacing Text with s Fig. 7.9 Replacing Text with R

followed by the character that replaces the one under the cursor (Fig. 7.7). You can replace a single
character only in this way. vi momentarily switches from Command Mode to Input Mode when r
is pressed. It returns to Command Mode as soon as the new character is entered. There's no need
to press [Esc] when using r and the replacement character, since vi expects a single character
anyway.
When you want to replace the letter d with !Of in a printf statement in C, you need to replace one
character with three. In that case, press
Replaces one character with many
s
vf deletes the character under the cursor and switches to Input Mode. It may also show a $ at that
location to indicate that replacement will not affect text on its right. Now enter lOf and press [Esc}.
To replace multiple characters, use a repeat factor. 3s replaces three characters with new text. Use
of sis shown in Fig. 7.8.
Rand S act in a similar manner compared to their lowercase ones except that they act on a larger
group of characters:
R Replaces all tex_t on the right of the cursor position.
S Replaces t!ie entire line irrespective of cursor position. (Existing line disappears)
Try using the repeat factor with Rand Sand see whether you can take advantage ofthis feature. Use
ofR is showrl in Fig. 7.9.
You have now been able to enter the Input Mode in ten ways. The functions of these ten keys are
summarized in Table 7.1.

Caution: You must press /Esc/ to switch to Command Mode after you have keyed in text. Repeated
pressing of /Esc/ won't make any difference to vi except that it has a built-in capability to indicate with
a beep If a key has been pressed unnecessarily. Try this by pressing [Esc} several times. You are now in
the Command Mode.

feature Is available in If the string printf is available in the fil~


string eve. Just key in as much as is necessary to make the string
-1
• • , • _; •• a!':!"P:S ~°,;:'....~_t_le_te. . . t_n.,.·~-~.,_--~---;...~_.._.·.'"""'"'....,,~-•.........
...
. ..
s ·]
[12s UNIX: Concep
- - "' ts and Applica
tions
~ ,. expands pr ,r ,\..: • e t}lete are olhe
'repeated pressingto pr\ntf II uuS \Salth only word beg. • g with pr. In r~
of the key showS l tcrungw iM ln
ordsintum, lnc c ase . tttelist
i. .-
aseyou ..... to v ie W ~
use [C trl-nJ. ma -
1.. • - _ . .. ., ;) : . w•
• . -
--
ia ~ ~ h ~ ~ c ~
Command 7 ~ ·: _ 1 ~ :t n ~ p ~
Function u t~ M io d ~ e
~C~o~ mman~~~d
Inserts text to s :: :: :: :; :; :: :;
left of cursor (E • • t t shifted ;; ;; :: ;~
a Appends text to XIStl~g _ex right)
ri hifted right)
l Inserts text at ght of cursor (Ex1st1ng text
beginning of \i s .ft d •ght)
"0
Appends text at
Opens line belo
c:nd of line
nc (Existing te
xt sh1 e n
0 w
Opens line abov
rch Replaces single e .
R character under n;,cJ req
cursor with ch
s
Rep\aces text
from cursor to n. h (E • • (Not....,. ) uired)
Replaces single g t x1st1ng te t 0 ..,erwntten
s character under x
cursor with an f har
Rep\am entire
\inc y numbero-c acters
----
7.3 SAVING T _
EXT AND QU\T
When you edit T\NG-THE ex
a file using 'I i- MODE
such, but only o
a copy of it that r for that matter, any editor- . 't d1s ' urbed as
.
ume, yous ou h is placed in a b the on•gin • l file 1s
a n t
• e 10
\d save your w uffer (a tempo ) fro in utll
(or, as we say, in ork by writing rary form of st
ora : k file
also need to q
sync). When w the bu
e talk of saving ffer contents to dis .
k to k thgeedis current
uit 'Ii after or a file, we actual ~e p is buffer. Y 111ay
the ex Mode. T withou ly mean saving th ou
he basic file han t saving the buffer. These feat I h an d led by
dling features ures arc adequ
7.3.1 Saving ar e sh ow n in Table 7.2. ate y
Wt h Your Work {:w
c ave aIrca dy )
u
extendcd sess·io se·dhthe· ex Mode command
. ns wit '41, you , :x, to save the · th for
ume, you must m buff
use- the :w com ust able to save the buffer and er and ciut c c ditor (7, J)·ti.le
mand to write to
line of the scre
en, then wand the buffer to disk rm1ain in the cd.,tor. f rolll ti th
fi na lly [Enter]: . E nt er a . h
:, wh1c appca rson e st la
:w[Enter}
•sometext•, 8
li n e s , 275 ch
You can now co aracters
ntinue your ed
regularly. Wit
h the :w comm iting work normally, but mak
and you can o e
contents arc se
parately written ptionally specif sure that you execute this com
y a filename as w rna;
to another file. ell. In that case !
1ip: It's comm ,
o
permission bit n practice to ignore the read
o
Fi le is read set. When you attempt to nly label on opening a file that
only. You shou save the file w doe~'t have the
ld
t name (say, :w have been careful in the firs ith :w, vi retorts with the m write
with a differen
foo) after mak t pl es
command to u
se when foo ex ing sure that fo ace, but there's hope: Just save sage
o d oesnt exist Loo the
ists. k up Table 7.2 fo file
r the
The vi Editor 12 ~1
7.3.2 Saving and Quitting (:x and :wq)
The previous command returns you to the Command Mode so you can continue editing. However,
to save and quit the editor (i.e., return to the shell), use the :x (exit) command instead:
:x{Enter}
"sometext", 8 lines, 303 characters
s
-
You can also use :wq to save and quit the editor. But that requires an additional keystroke and is not
recommended for use.

Tip: The best way to save and quit the editor is to use ZZ, a Command Mode command, instead of
:x or :wq.

7.3.3 Aborting Editing (:q)


It's also possible to abort the editing process and quit the editing mode without savi~g the buffer.
The :q (quit) command docs that job: •
:q{Enter} Won't work ifbuffer is unsaved
$
vi also has a safety mechanism that prevents you from aborting accidentally if you have modified
the file (buffer) in any way. The following message is typical when you try to do so:
No write since last change (:quit! overrides)
If the buffer has been changed and you still want to abandon the changes, then use
:q! Ignores all changes made and quits

to return you to the prompt irrespective ofthe status ofthe buffer-no questions asked. vi suggests
appending a I to an ex Mode command every time it feels that you could be doing something that
is potentially unsafe.

Note: In general, any ex Mode command used with a ! signifies an abort of some type. It can be used
to SWitch to another file without saving the current one, or reload the last saved version of a file. You can
e1.en use it to overwrite a separate file.

7.3.4 Writing Selected Lines


The :w command is an abbreviated way of executing the ex Mode instruction :l,$w. w cal' be
prefixed by one or two addresses separated by a comma. The command
:10,SOw n2words.pl Writes41 lines'toanotherfile

saves lines 10 through ~0 to the file n2words. pl. You can save a single line as well:
: Sw n2words. p1 Writes 5th line to anotherfile
Co UNIX: Concepts and
Applications
. . d S T he do t
T he re are tw o sym •th ha -t
bols used w1 w~ t have special significance h e do t an • . binaoon•
th e cu rr en t line w hi \ si
le $ represents e tl in eo ft he file. You ca n us e th em ng ly or in coJll
as
· (where cursor tJ positioned)
.
: .w te m pf H e Saves current 1m e
:$w te m pf ile Saves lastline .
: . ,$-.. te m pf ne Saves current line th h end
roug
If tempfl 1e exists an d . . . .
is w nt ab le by you, •
vi issues yet an ot he r w ar ni ng .
"tempfi1e" FH e ex
is ts - use •w! tem f"1 " to ov er
p 1 e 'fl rit e
T he message is de ar : .
vi 1s te \h.ng yo u to ffi h , o th e w ri te tetnP file,
:w co m m ar .d to ov erd
L.
As m en tio ne d be fo su ix t e • t u' ll""
re , th e ! is th e un iv
er sa l ov em·d·mg oper at or 1•n th e ex M o e an d yo
us in g it of te n.

Note: In th e ex Mod ~ ~" d tedbYS-


e, th e current line nu Une iS e,..,
:w is the sa m e as : mber is represented (d ot ' an d th e la st
1, $w. Both comman by • '
ds address th e entir
e file.
7 .3.5 Escape to th
e UNIX Shell (: shand [Ctrl-zll
H ow do do yo u ed ke a telllPor2l1
it and compile your
escape to th e shell C program repeatedl ? Y<0 u need to
M od e co m m an d,
to ru n the cc comm
and. Th er e arc two
Y· thm
oda is to us e the eX
: sh: ways,. th e first me
: sh
$
.

T hi s- re tu rn s a shel You haven't quit v,. Yet
l prompt. Execute cc the editor
us in g {Ctrl-d] or ex or any UNIX comm
it . D on 't make th e and here an_d then re tu rn to
instances of v i- an mistake of running
vi once again, as yo
'II then have two
undesirable situatio u
n.
Ifyo ur shell su pp or
ts job control (which i session,
Jus t press letrl-z m
] an d you ,II be return ost shells do) you can alsosuspend the cudrrent v fg
ed a shell prompt' . R he
co m m an d to re tu rn
to th e editor. Job co un your comm ands an t n use the
ntrol is discussed in
Section 9.10.
7. 3. 6 Recovering fr o
ma Crash (:recover
Acc1"d and -r )
en ts ca n an d w1·11
pa ni c, vi stores m os ha pp en . T he power ca n go o ff. I • don't
t of its bu ff er , caving wark unsaved• H owever,
fil co n succ information in a hi h i removes t h'1s
essful ex•it, a po w er . dden swap file. Even th
on disk. vi will th gl itc h or an improper shutdown othu~ v p file: remain
en co m pl ai n th e ne proccdu re lets ,s swa
xt time you invoke
T he co m pl ai•nt usua .
it with the same file.
lly al so co nt ai ns some advice rega . d . d
to us e ci•ther t he ex rd in g th
I op eratio n. You'll be
M od e co m m an d :r e savage h f too as poaSSv!1bscle.
After yo u have do ne ecover or vi -r fo er as rn
th at , have a lo ok at th e ' o to rcco v uc 0
d amage co
nt roI exerci•se. If ev buffer contents and • fy oursc If fthe success ofth e
erything seems fine, sa us Y P
do es n' t do th at on
its own. save the bu ffier 3 nd remove the swap file if vt
.
The vi Edito r :,i7 I
times, vf may show you absolute
Note: You can't be assur ed of complete recoveiy eveiy time. Some
junk when using the -r optio n (or : recover). In that case,
don't save the file and simply quit (with :qi).
should note that in these situations,
Start vf again normally; recovery is not possible here. Linux users
they need to delet e the file having a • swp extension manually;
otherwise the file will not be editable.

Table 7.J. Save and Exit Comm ands ofthe ex Mode


Command Actio n
Saves file and remains in editing mode
:W
Saves file and quits editing mode
:x
:wq
As abov e
:w n2w.p1 Like Save AJ ..... in Microsoft Windows
:w! n2w.p1 As above, but overwrites existing file
Quit s editin g mode when no changes are made to file
:Q
Quits editin g mode but after abandoning changes
:qi
:nJ,n2w build .sql Writes Jines nl to n2 to file buil d.sql
:.w build .sql Writes curre nt line to file build .sq]
:Sw build .sql Writes last line to file build .sql
Runs cmd comm and and returns to Command Mode
:lcrnd
Esca pes to UNIX shell
:sh
:recover Recovers file from a crash

7.4 NAVIGATION
is the mode you come to when you
We'll now consi der the funct ions of the Com mand Mode. This
command doesn't show up on
have finished enter ing or chan ging your text. A Comm and Mode
Don't forget to avoid the cursor
screen but simply perfo rms a funct ion. We begin with navigation.
control keys for navig ation as advised in Section 7.13.

7.4.1 Mov eme nt in the Fou r Dire ction s (h, J, k and 1)


yf provides the keys h, j, k and 1 to move the curso r in
the four directions. These keys arc placed
ut a repeat factor, they move the
adjacent to one anoth er in the midd le row of the keyboard. Witho
ally:
cursor by one posit ion. Use these keys for moving the cursor vertic
k Moves curso r up
j Moves curso r down

To move the curso r along a line, use these comm ands:


h Moves curso r left
I Moves curso r right
h~ UNIX: Concepts and Ap
plications

I takes you ri gh t and h ta ke s you le ft


31
(\
2k k takes yof u
j

I takes you
'--/
13h
Fig. 7.10 Relative Navi
gation wi th h, j, k an d 1
Th r
e repeat 1a ~tor ca n be used as a co
the curso mmand prefix wi th all r us
m ands. Th ' 4k moves•
r 4 lines up an d 20h tak these 1o u~ co ~ .th th e four keys_ JS
sh ow n in Fi g. 7.10. No es it 20 characters to th
e left. Nav1gat.1on ~ 1
these keys.
te th at this motion is rel
ative; you ca n't move to r umberwith
a specific in e n
Tip •
Th ·Tc
• 0 remember th e keys
th
e left-most key, h, move at move the cursor left or right, observe these fou k o n ~
s th e cursor to th e left, an r
d the right-most key, 1 (el eys 1. ri hl
), moves ~
7 •4
.2 W or d Navi gation (b, e and w)
Movin b .
g Yon e character is no \
u nderstands a word as t always enough· you'l
ter a Iong a lin
a navigation un it which l often need to move fas e. vi
presdsed. I~ yo ur curso ~an be defined in two wa th key
r is a nu m be r of word ys, de pe nd in g on e the
Wor -n av s away from your desir
ig ati•on co mm an ds to go ed position, you ca n us
there directly. Th er e are • e
three basic comm•an ds:
b Moves ba ck to be gi nn in
g of word
e Moves forward to en d
ofwo rd
w Moves forward to be gi
nn in g of word
A re pe at factor speeds
up cursor movement alo
:io~~s back,. while 3w ng a line. For example,
takes th e cursor three Sb takes the cursor five
p nu m en c characters wo rds ~orward. A wor~ he
an d th e (underscore). re is simply a s~ in g of
"'Ords; th e hy ph en by Bash 1s one word; so 1s sh
_p rofi 1e. tcp -f p 1s three
definition becomes a wo
rd too.
Th e keys B, Ean d Wpe
rform functions simila
pu n~ tu ati on is skipped r to those of th eit lowerc
deta ds . . Th e word definition als ase counterparts except th
o gets changed here, bu at
• • t we'll ignore these mino
r
The vi Editor
Fl
7 .4.3 Moving to Line Extremes {O, I and $)
Mo~ipg to the beginning or end of a line is a common requirement. This is handled by the keys O,
I and $. To move to the first char~cter of a line, use
0 (zero) or I 30 I moves cursor to column 30

The I takes a repeat factor and using that, you can position the cursor on a certain column. To
position the cursor on column 30, use 30 I-
We used$ as the line address in the ex Mode to represent the last line of the file. The same symbol
in the Command Mode represents the end ofline. To move to the end of the current line, use

$ Moves to md ofline

The use of these two commands along with those that use units of words (b, e and w) is shown
in Fig. 7.11.

Note: When you use the keys b, e and w, remember that a word is simply a string of alphanumeric
characters and the _ (underscore).

7.4.4 Scrolling ([Ctrl-f], [Ctrl-b], [Ctrl-d] and [Ctrl-u])


Faster movement can be achieved by scrolling text in the window using the control keys. The two
commands for scrolling a page at a time arc

{Ctrl-j] Scrolls forward


[Ctrl-b} Scrolls backward

Oor I

lou can move of worcl


to e ~ ~ o ; t ,

e 4e 4w

Fig. 7.11 Navigation Along a Linc


UNIX: Concepts and Applications
ate faster in thrpr
You can use the repeat factor, like in 10[Ctrl-j}, to scroll IO pages and navig
"
You can scroll by half a page as well:

{Ctrl-d} Scrolls half page forward


{Ctrl-u} Scrolls half page backward

The repeat factor can also be used here.

7.4.5 Absolute Movement (G)


rime, you can pr~
Upon startup, vi displays the total number of lines in the last line. Ar any
{Ctrl-g] to know the current line number:
"/etc/passwd" [Read only] line 89 of 179 --49%--
in all. CompiJ
Thc cursor is on line 89 (49% ofl79), and this read-protected file has 179 lincs
and with the,:
also indicate line numbers in their error messages. You need to use the Gcomm
use
number as repeat factor to locate the offending Jines. To move to the 40th line,
40G Goes to line number 40

and to ·move to the beginning of the file, use


lG Goes to line number 1

The end of the file is reached by simply using


G Goes to end offile

s three commands
Note: The exMode offers equivalent commands for moving between lines. The previou
can be replaced with : 40, : 1 and : $, respectively (along with /Enterfl
.

7.5 EDITING TEXT


h operators arc
The editi~g facilities in ~i are very elaborate and involv~ the use ofoperators. Thoug
to enable us to
taken up m Part II of this text, we need to know a special form of their usage now
that we will use in this chapter:
perform the essential editing functions. These are the two operators
d Delete
y Yank (copy)
g and . .
d and y are not commands, but they can be used (as dd and yy) for deletinWe'll socopymg ehntire
Jines. The "pastin. g" operation is performed by the p and P commands• on use t ese
. .
commands for ed1tmg operatwns.
The vi Editor 1351

t
This is the vi fullascreen editor· from UCB

This is the vi fullllcreen editor from UCB

Four spaces back

t
This is the vi lillscreen editor from UCB

4x

This is the vi llcreen editor from UCB


Fig. 7.12 Deleting Text with x

-, •5 .1 Deleting Text (x and dd)


1'he simplest text deletion is achieved with the x command. This command deletes the character
linder the- cursor. Move the cursor to the character that needs to be deleted and then press
)( Deletes a single character
lhe character under the cursor gets deleted, and the text on the right shifts left to fill up the space.
Arepeat factor also applies here, so 4x deletes the current character as well as three characters from
the right (Fig. 7.12).

A Windows Notepad user would be surprised to note that when the cursor is at the end of a line, x
doesn't pull up the following line but works instead on text on the left ofthe cursor. Deletion oftext
from the left is otherwise handled by the Xcommand. Keep it pressed, and you'll sec that you have
erased all text to the beginning of the line.
Entire lines are removed with the dd "command" (rather a doubled operator). Move the cursor to
any line and then press

dd Cursor can be anywhere in line

6dd deletes the current line and five lines below. Fig. 7.13 illustrates the use of dd both with and
without a repeat factor. There are other forms of deletion available in vi and you'll know them all
after you have understood the d operator well (20.1.l).

7.5.2 Moving Text (p)


Text movement requires you to perform an additional task: Put the text at the new location with p
or P. Yi uses these two commands for all "put" operations that follow delete or copy operations. The
significance of p and P depends on whether they are used on parts of lines or complete lines. We
need some examples to illustrate their behavior.
... - - - - - - -

I~ UNIX: Concepts and Applications

t,i s is thevt edi tor from UCB


It is superior toe d, and fri en
dli er too
It is due to William Joy
It is slow in get tin g sta rte d but
is qu ite powerful

• dd
a is superior toed, and friendlier too
It is due to William Joy
It is slow in get tin g sta rte d but

i
is qu ite powerful

2dd
f: is slow in get tin g sta rte d but is
qu ite powerful
Fig. 7.13 Deleting Lines with dd
For instance, to correct sdt io. h to std
io.h, you'll have to transpose the
delete thed and put it after the t. Move characters d and t,t
your cursor to the din sdt i o. han d use
these two commao
x sdtio.h becomes stio .h- -cu rso r on t
P d put on rig ht- sti o. h becomes std io.
h
Since we worked on parts oflines, asso
ciate the word "right" with p and "le
on the left of the cursor. ft" with P. Pplaces tat
.
To put entire (deleted) lines at a differen
t location, you'll need to use the sam
that we have to think in terms of "below e commaods, except
" and "above" the current line. p pla
current line and Pplaces text above. ces text below tbe

Note: P and P place text on right and


left only when you delete parts of Jines.
associated with "below• and "above" whe But the same keys get
n you delete complete lines.
.
7.5.3 Copying Text (y and p)
vi uses the term yanking for copying
text, the reason why the operator is nam
are exactly the same as compared to dele ed y. The principles
tion with d. For instance, to copy (or yan
lines, use theyy ucommand": k) one or more
yy Yanks ct'"tnt lint
/ lOyy
Yanks ct'" tnt lint and 9 lines below
This yanked text has to be placed at the
new location. The put commands are the
Since we copied entire lines, we can only sam e-p and P.
place the copied text below or abdve the
not on the left or right. But suppose you current Ji ne, and
need to place an entire line at theend of
have to place it below the line first and another line. You
then join the two_lines. Just read on.
The vi Editor

7 .5.4 Joinin g Lines (J)


In word processo rs, you join the current and next line by moving the cursor to the end ofline and
pressing [Delete]. This techniqu e won't work in vt. To join the current line and the line followin g
it, use
J 4J joins followin g 3 lines with cu"ent one

J removes the newline characte r between the two lines to pull up the line below it.Joinin g, however
,
is restricte d to the maximu m line size that your vi editor can support. It could be below 2000 (as in
Solaris) or unlimite d (in Linux).
To solve the problem posed at the end of the previous section, if you place a line below the current
line with p, you can use J to join the two lines.

7.6 UNDO ING LAST EDITING INSTRUCTIONS (u and U)


If you have inadvert ently made an editing change that' you shouldn 't have, vt provides the u
comman d to undo the last change made. Before you do anything else, reverse the last change you
made to the buffer by pressing
u Mu.rt use in Command Mode; press [&c] ifnecessary
This will undo the most recent single editing change by restoring the position before the change.
Another u at this stage will undo this too, i.e., restore the original status (doesn't apply to Linux).
This"facility is very useful, especially for beginners, who may accidentally delete a group of lines.
Any deletion can be undone with u provided it is pressed immediately after deletion , and before
fresh editing action has been perform ed.
When a number of editing changes have been made to a single line, vt allows you to discard all
changes before you move away from the line. The comman d
u Don't mo11e away from cu"rot line

reverses all changes made to the cuccent line, i.e., all modifications that have been made since the
cursor was moved to this li~e.

Caution: Make sure the cursor h~s.not been moved to another line before invoking U, in which case it
won't work. "-'

i.iii i:'~ Cindolng and Ids you undo "'anct redo • l e editing
here; repeated use d this key progresslYely ·unc1oes your previous actions.

t- =":""'..!".~"'""'"""'.""":::--... t•~ =i
1badel nd mark when you keep II P'essed. In whldl case me /Ctrl-1/ to redo~
iiriilalns wlthDII can be campletely nN'elSed wab-10/0rl-l/.The undoing 11m1
sset undoltv els~ wheren ~•to tOOObydefault. J

You might also like