Vi: Difference between revisions

2,593 bytes added ,  6 years ago
Line 35:
To decrypt the encrypted file, open the file and type below command and hit the Enter key twice; then save and exit the Vi editor by typing :wq, the file will be saved in the decrypted format:
:X
 
* Inserting the contents of an existing file
: r filename
 
Running an external command within Vi
You can execute any command within the Vi editor by typing the following command within the command mode of Vi:
:!commandname
 
Insert the output of a Linux command
You can insert the output of a command by giving the following command:
:r! :commandname
 
The command is executed and the output is inserted from the position where the cursor is located.
 
Opening Vi directly at a particular line
You can open the Vim editor with the cursor placed directly at the line you want, by giving the following command:
$vim filename +n
 
The number ‘n’ in the command is the line number.
 
Opening Vi at the end of the file
Adding the + sign and a space before the file name, opens the file and places the cursor at the last line.
This is useful if you have to work on large files.
$vim + filename
 
Writing the buffer to a new file
:w can be used to save the complete buffer, that is, the file being edited currently, under a new file name.
This can be used when you have made a lot of changes in the file, but then realise that you do not want to overwrite the original file.
To save the contents of the buffer, use the following command:
:w newname
 
You can now quit the original file by typing :q.
 
Indenting the source code
In case you have typed dozens of lines of code without bothering about indentation, the quickest way to indent the code is to do the following;
Press the Esc key to go to command mode and then type the following:
gg=G
 
…where gg indicates the beginning of the file, = is for indenting and G indicates the end of the file.
 
Repeating the last change
We can use the . (period) key to repeat the last change.
This helps to reduce the typing required when carrying out repetitive tasks.
 
Undoing and redoing
Type u to undo the last change.
Type Ctrl-R to repeat a change that has been undone.
figure-2-a-code-snippet-with-indent
 
Jumping to matching braces
We can jump to the matching parenthesis (the curly brace or square bracket) by pressing the % key.
This is very useful when editing source code.
 
Preventing auto-indent
When text is pasted in Vim from an already indented source file, Vim will further apply its auto-indenting feature (if it is enabled) to the pasted text, which will have a cascading effect on the text.
To prevent auto-indenting, use the following command:
:set pastetoggle=<F2>
 
You can then press <F2> in the insert mode when you are ready to paste. After pasting, you can press <F2> again to go to the auto-indent mode.
 
= Advanced =