Untitled Document

Chapter - 15 Advanced Vi

In our Previous Chapter of vi ( Chapter - 7 ) we have seen different modes , commands and operations that we can perform on vi editor . In this chapter , we will see some advanced feature of vi editor. Editing can be productive and effective if we customize our editor to suit our requirements and we will do that in this chapter .

Operators - 

Most of the useful function in the command mode are derived from a combination of an operator and a command . With operators , you can frame a command to handle practically any situation. There re only a few operators and you must know at least the following ones :

  • d - Delete .
  • c - Change
  • y - Yank ( copy )
  • ! - Filter to act on text

An operator alone can't perform any function unless it is combined with a command or itself .When used with itself (i.e twice) , it can handle a very specialized function. In Chapter 7 , we have seen how these specialized functions were performed by using dd and yy to delete and copy a line respectively. all of these operators also take a repeat factor which greatly enhances their power.

An operator , when doubled by itself ( like dd, cc, yy and !! ) , acts only on the current line .

Deleting and Moving Text (d, p and P )-

We know how to delete characters and lines with x ,X and dd . dd is really a combination of the operator d with itself . In vi we can perform some complex deletion when we combined this operator with commands in command mode .

Consider that you have to delete text from the present cursor position to the end of line. You can frame command using our primary commands that we ahve seen in chapter -7 under Command Mode topic. Since $ is used to move the cursor to the end of line , now we can combine the operator d with $ to delete from the cursor position to the end of line

d$

Now taking a clue from here the command to delete a word will be - dw .dG should delete text from current position to the end of file . A repeat factor applies here too - 3dw deletes three words and 5dd deletes five lines including the current line.

To move text, there are no special considered . We have deleted the text using the dd ,x and X commands and then placed the deleted text at a different location with the p and P commands . p and P works differently depending on whether the deletion affects entire lines or parts of lines . When working with entire lines , p puts the text below the cursor and P places its above . However when you delete a word with dw you can put the deleted word only to the left ( with p) or right ( with p) of the cursor position and not above or below the current line.

Yanking Text (y)

The y operator yanks (or copies) text. It is used in the same way the d operator is combined with another command or by itself . With this operatoe we can yank a word ,group of words, lines etc . And we can use same p and P command to paste in the destination .

For example , to yank five lines of text , move the cursor to the first of these lines and press .

5yy

Now move the cursor to the destination and press . when we yank words p and P have the same significance as with d operaor

p or P

Changing Text (c) 

Text is changed with the c (change) operator. If dw deletes a word , cw changes it . This is the only operator which works in Input Mode . The change operation thus has to be terminated with [Esc] .

When we invoke c in command mode , you are taken to the Input Mode. The boundary limiting your area of Operation could be indicated by a $ . If you change three words with 3cw , a $ should appear at the end of the third word ( Except Linux). The inserted text overwrites the characters delimited by the $ that temporarily appears on the screen .If the replaced text is larger , then once the cursor moves up to the $ marker , further insertion shifts existing text to the right .

To change text from the present cursor position up to the end of a line , use

c$ or C

To chnage entire lines use

cc

Filtering Text ( ! ) 

vi has very strong feature of UNIX/ LINUX filter to act on text that display on terminal . We can run any command with the ! operator . In general filtering text on the screen requires three steps :

  • Move to the begining of the text to be acted upon and type !
  • Move to the other end of the text using any navigation command like G
  • Enter the UNIX command to act on the text . The text on the screen should change immediately .

For instance , to sort lines 11 to 30 of a file , move the cursor to the first character of line 11 ( with 11G) and the press the following sequence

!30Gsort [enter]

The destination line number is important , nothing will appear on screen until the second address ( 30 G) is entered . After you entered the word sort , the last line will be like this :

:11,30!sort -------------------- we have executed an ex Mode Command

The above command will sort the 20 lines from line 11 to 30 and the output replaces the current content , Actually we have executed the ex mode command without knowing it . We can enter the command directly as well . We can save the changes or undo it ( with u) if you didn't find the ouput is as expected .

Like other operators, the ! when doubled , uses the command following it to operates to the current line . This is how tr to change the case of text of the current line to upper .

!!tr '[a-z]' '[A-Z]'

To maske your editing work productive , we must have thorough knowledge of the command that are used for text manipulation. Combining the different commands and modes of vi can make your editing fatser and efficient .

The combination of these commands are listed in below table for reference -

Command Function
d$ or D Deletes from cursor to end of line
5dd Deletes 5 lines
d/} Deletes from cursor upto first occurence of }
d30G Deletes from cursor upto line number 30
df. Deletes from cursor to the first occurence of a dot
y$ or Y Yanks from cursor to the end of line
3yw or y3w Yanks three words from cursor position
5yy Yanks 5 lines
yG Yanks from cursor to end of file
y?case Yanks from cursor up to first occurence of string case in reverse direction
c0 Changes from cursor to the begining of line
c$ or C Chnages from cursor to end of line
3cw or c3w Changes three words
cc Changes current line
!Gsort Sorts all lines from current cursor position to end of file
!!tr '[a-z]' '[A-Z]' Converts current line to upper case
Doubling an operator (like dd,yy and cc) constitutes a special command , which always acts on the current line . Three operator-command combinations also have synonyms - D (d$), Y (y$) and C (c$) . They act on text from the current position to the end of line .

Multiple File handling in ex Mode : 

During shell scripting and code editing we play with multiple files and often need to switch from one file to other . As a developer , we need to know the multiple file handling technique to copy text from one file to another. We have already seen some basic file file handling commands now lets take a look at some advance file handling techniques .

Moving To Different Files -

Sometimes we need to ignore all the unsaved changes made to a file . So , insead of quiting vi and invoking it again , we can reload the last saved session of the file with -

:e!

We can also edit multiple files with leaving the editor . While editing one file , we can easily switch to another by using :e command

:e sample.txt

We can return to the orignal file by using one of these sequences :

[Ctrl-^ ] ---------------- Toggle between current and previous file

:e# --------------------- same

This toggling command will help you to switch from current file to previous file and back to current file again .

vi to open multiple files -

when vi is used with multiple filenames , say with vi sample[1-5] , it throws out a message 5 files to edit , and loads the first file (sample1) into the buffer. We can now switch to next file , sample2 using -

:n Next file in command line

We can go till the last file of the sequence in this manner , without leaving the editor . At any stage we can move back to the first file specified in the command line by "rewinding" the file list :

:rew Back to first file in command line

when you switch from one file to another , there is a protection mechanism which prevents the switch if changes have been made to the file . The system displays a terse message :

No write since last change (:edit! overrides)

Just as the command :q! quits the editor after discarding all changes , the :e! # command similarly switches to the last edited file after discarding the changes made to the current file. You can also use :n! or :rew! in the same vein .

Inserting File and Command Output -

We often need to copy and paste entire contents of an file into another file . In windows we do this by opening the file from where we have to copy and then need to open destination file to paste the contents . In vi we have a very smart featue which does this task in single command -

With vi , we don't need to visit other file at all . Just inserts its contents at the present cursor location :

:r emp.csv --------------------------------------------------- Inserts file emp.csv in current file

We can also place the output of a command in our file . Use :r like before , but instead of specifying the filename , enter the command name precedded by 1 :

:r !date --------------------------------------------------- Inserts output of date command
Command Function
:r sample.txt Reads File sample.txt below current line
:r !head -n 5 sample.txt Reads first 5 lines of file - sample.txt
:w >> sample.txt Appends buffer contents to file sample.txt
:e emp.csv Stops editing current file and edits file emp.csv
:e! emp.csv As above , but after abandoning changes made to current file
:e! Loads last saved edition of current file
:e# Returns to editing most recently edited file
:n Edits next file ( if vi is invoked with more than one filename)
:rew Rewinds file list to start editing from first file in command line
we have an useful shortcut available in Command Mode to toggle between files , use [ctrl-^] . For this to work all times , make the ex mode setting :set autowrite or :set aw . This ensures that the file is saved automatically before swicth occurs .

Spliting The Vi Screen ( Windows ) in Linux -

We can split our vim screen in multiple windows . The window can be empty , it can contains a file or even a copy of the same file .To view the same file in two seprate windows , use the :sp (split) command in ex mode :

:sp --------------------------------------------------- Splits existing window in two

In this case changes made ito the buffer in one window are also seen in the other window. we can also create a new window not associated with any file :

:new --------------------------------------------------- new blank window

We can move between the two windows by using the command .

[ctrl-w][ctrl-w] ---------------------------------------------------Cycles through windows

In any window ( empty or otherwise) , you can open a new file by using :e filename . We can also increase or decrease the vertical size of a window .

[ctrl-w]+--------------------------------------------------- Increase size of current window

[ctrl-w]- --------------------------------------------------- decrease size of current window

To make the current window the only window on the screen and close all other windows , use

:on --------------------------------------------------- Removes all other windows

We can kill the current window and move to th other window (f any) :

:q

Note that when we have multiple windows on , :q will quit from the current window and close it . To apply the save , quit and exit commands to all windows in vim , we have to append an a to the existing commands . To quit all windows without saving , use :qa . To save all buffers and quit , use :xa

 

Use of Buffers in vi-

Named Buffers -

So far we have copied or deleted the section of text of a file from one place to otther . vi Actually stores this copied or deleted data in an unnamed buffer .This buffer system has some limitations .First, you can use only one buffer at a time .Second, when moving text from one file to another ( using :e filename ) , the contents of this special buffer are lost (Linux Excepted).

vi actually has 26 special buffers , but by default we don't use them. There name are simple english letters and they are really straightforward to use . Just preccede the editing operation (deletion or yank) with a " ( double quote) and the buffer name , say a . Thus , to yank four lines into this buffer named a , just simply run -

"a4yy --------------------------------------------------- Copies 4 lines into buffer a

Now navigate to the desired location and run the below command .

"ap --------------------------------------------------- use P to put the text above

we can delete or copy another section of text into another buffer , say b and restore the same with "bp ( or "bP ) . In this way we can use all the 26 buffers to hold 26 sections of text .If you have to switch files , note that you can toggle between two files using [ctrl - ^] or :e#

Moving text from one file to another -

Now using this feature of buffers we can move or copy text freely across a file and even from oone file to another . This is how we copy text across two files :

   "a20yy   Copy 20 lines into  buffer  a 
   :e emp.csv  ------------------------------- Switch to file emp.csv
   20G ------------------- Move to line 20
   "ap ------------------- Put the 20 lines after line 20

The only precaution you need to take here is that , on no account , should uou exit vi to open a second file . The buffer contents are lost when you leave vi

if you perform an operation on a named buffer which already contains some text , the contents of the buffer are overwritten . vi uses the uppercase letters to append to these buffers - "Ayy instead of "ayy

Searching A character ( in current line )

There is an special facility to move cursor near or to the specific character in the current line . This is done with the f anf t commands , followed by the character to be searched for . To move cursor forward to the first occurences of the character , use

f ( followed by the character )

for example , f# moves the cursor to the first # following the current cursor position . This is a convenient way of moving to the end of a sentence when editing a document . t also acts in similar way exceot that the cursor is positioned a single character before the occurence .

F and T perform the operations of their lowercase counterparts in the reverse direction. We can even use the repeat factor for the occurence of a character . For example , 2f# places the cursor on the second occurence of the # in the line .

So far the operations that we have performed are restricted to the current line only .

The character search can be repeated by suing ; (semi-colon) and , (comma) charater . Table below table summarises the search and repeat character commands in Current line .

Command unction
fch Moves cursor forawrd to first occurence of character ch
tch Moves cursor forward onto but before first occurence of character ch
; Repeats search in same direction along which previous search was made with f or t .
. Repeats Search in a direction to that along which previous character was made with f or t

Marking Text -

We can mark up to 26 positions ( labeled a to z ) in the file and later we can locate them . The m command is used to mark the lines and ' ( single quote ) command locates a marked line .Any alphabetic character can be used in combination with m and ' for marking and locating different positions of text .

To mark any position of a file with label a , move the cursor to the required locations and press .

ma

An invsible mark is left at the corresponding point in the file .We can move back to this mark from any point in the file by simply using a ' in combination with the character used to mark that location, in this case :

'a

The ' when doubled ( two single quotes ) then it toggles the motion of the cursor between its present and immediate previous location .

This also applies for the situation where the cursor is not explicitly moved away from a line . If we have moved to line with 40G and then to the end of the file with G , we can alternate two locations by suing '' ( two single quotes )

Customizinf vi -

We can customize some of the aspects of vi which we need frequently in editing. There are three ex Mode commands - set,map and abbr - which allows us to do all that .

vi reads the file ~/.exrc only once , upon startup and its behaviour is determined by statements placed in that file. In the following topic we will see some more commands that we can place in this file. keep in mind that we have to restart vi whenever we make changes to .exrc . Linux users using vim may need to edit ~/.vimrc

The set Command -

The general vi environment is determined by its variable setting .The variables are controlled by the :set command .We have seen this command in our previous vi chapter . Now lets's take a look at some of these variables.

Automatic Indentation ( autoindent ) - Developer / Programmers need to provide indentation to their code for good readability .Nested if statements along with their corresponding fis should appear at the right indentation . This aspect is taken care of when we use the following set statement :

:set autoindent Or :set ai

Numbering Lines ( number ) - This setting shows all the lines duly numbered . This makes it wasier to debug programms. However the line numbers are not preserved when the file is saved. to reverse this setting , we simply have to prefix the string no to the option :

:set number --- To show line indent

:set nonumber --- To turn off line indent

Ignoring Case in Pattern Searches ( ignorecase ) - The search commands may or may not pursue a case - insensitive search . That depends on the ognorecase setting. By Default this is generally off , but we can tutn it on with-

:set ignorecase

No regular expression in search ( nomagic ) - Sometimes we may need to despecalize the regular expression characters when searching for a pattern . In such a case we need to use following settings -

:set inomagic ---------------- searching for /a* will now show a*

By default setting is magic i.e. the characters *,. , etc retain their special meaning .

See Matching } or ) ( showmatch) - Another option which is especially useful for developers or shell programmers which enables the programmer to see momentarily the matching bracket to a ) or }. The showmatch option helps you locate matching brackets -

:set showmatch

when text is entered in the input mode , the moment a ) or } is entered , the cursor will jump to its matching counterpart and stay there for a fraction of a second before returning to its current location . If a match is not found, it responds with a beep .

All settings made with set are displayed with the :set all command . Some of the important set options are shown in below table .

Command Abbreviation Function
autoindent ai Next Line starts at previous indented level
autowrite aw writes current file automatically whenever switching files with :n or :e
ignorecase ic Ignores case when searching a pattern
magic   Treats regular expression characters as special when searching for patterns
number nu Displays line number on screen
showmatch sm Shows momentarily match to a ) and }
showmode   Displays message when vi is in Input mode

Untitled Document Scroll To Top Untitled Document