Softpanorama

May the source be with you, but remember the KISS principle ;-)
Contents Bulletin Scripting in shell and Perl Network troubleshooting History Humor

VIM Tips

Old News ;-) VIM -- VI-style Editor with folding capabilities Recommended Links Vim Options and Set command VIM Configuration .vimrc
Vim Buffers and Text-buffer Execution Vimrc Examples VIM Syntax Highlighting  Color schemes in VIM VIM Multiwindows Support Indenting Your Code in VIM
To switch from vertical split to File managers in VI Copying and Moving sections of text VIM Humor Humor Etc

Note: Non-Ex commands (normal mode commands) can be also executed from the command line using :norm[al]non-ex command  mechanism.

Some set command options are really useful.

The first in this like is  set number  which adds line numbers as the first column 

To remove  number column use

set nonumber
It makes sense to put some set command in your in your .exrc :
    set showmode number ai 
    set shiftwidth=3
    set tabstop=3
    set showmatch 

Notes:

See also


Top Visited
Switchboard
Latest
Past week
Past month

NEWS CONTENTS

Old News ;-)

[Jun 19, 2014] Tricks UrFix's Blog Page 3

"...I often forget to sudo before editing a file I don't have write permissions on. When you come to save that file and get the infamous "E212: Can't open file for writing", just issue that vim command in order to save the file without the need to save it to a temp file and then copy it back again."
1) Save a file you edited in vim without the needed permissions
:w !sudo tee %

I often forget to sudo before editing a file I don't have write permissions on. When you come to save that file and get the infamous "E212: Can't open file for writing", just issue that vim command in order to save the file without the need to save it to a temp file and then copy it back again.

[Dec 05, 2013] If your colors are screwed and elements of text are not visible well

If you colors are screwed you can see text without system highlighting by turning it off
: syntax off
Another way to deal with this situation is to change the colorscheme. See Color schemes in VIM

[Dec 16, 2009] Finally! A decent text editor for Linux with Windows key bindings. 46palermo

Vim Tip, on November 8th, 2009 at 19:32

just thought you might like to know, that vim does actually support windows keybindings. There should be an mswin.vim file on your system, which you can load to get ctrl-x, ctrl-v etc. You may just owe me a White Russian

[Dec 31, 2005] Seven useful tips from Editor of Softpanorama (New Year present for readers of this page):

  1. Find a word under cursor: "*" - forward, "#" - backward
  2. Matching bracket - "%".
  3. autocompletion of words: Ctrl-N
  4. change of case in the line: "guu", "gUU"
  5. goto the line with the last change: "'." ("`.")
  6. cursor walk back: Ctrl-O, Ctrl-I.
  7. Visual selection of the block: v - start of the block (V like, Ctrl-V - vertical block), after that any operation like d or y

Tip 1:

frequently you need to do S&R in a text which contains UNIX file paths - text strings with slashes ("/") inside. Because S&R command uses slashes for pattern/replacement separation you have to escape every slash in your pattern, i.e. use "\/" for every "/" in your pattern:

s/\/dir1\/dir2\/dir3\/file/dir4\/dir5\/file2/g

To avoid this so-called "backslashitis" you can use different separators in S&R (I prefer ":")

s:/dir1/dir2/dir3/file:/dir4/dir5/file2:g

Tip 2: You may find these mappings useful (put them in your .vimrc file)

noremap ;; :%s:::g<Left><Left><Left>
noremap ;' :%s:::cg<Left><Left><Left><Left>

These mappings save you some keystrokes and put you where you start typing your search pattern. After typing it you move to the replacement part , type it and hit return. The second version adds confirmation flag.

Useful options for .exrc file:

set ai
set wrapmargin=1
map @* I/*^[A*/^[
map @f !}fmt^M
map @d :r !date +"\%a \%b \%d \%y"^M
map @t :%s/^I/    /g^M

Some set command options are really useful. for example set number . It makes sense to put it in your in your .exrc :

set showmode number ai
set shiftwidth=3
set tabstop=4
set showmatch

#The shiftwidth options allows one to easily indent blocks of code. At any line enter >> ; the line should be shifted 3 spaces; enter 3<< and the 3 lines at the cursor should be shifted 4 spaces. This is useful for increasing the indentation of a block of code.

#Most programmers like tab stops of 4, but the rest of the world use tab stops of 8. If we wish to communicate with the rest of the world, (i.e. send code over email and have it look reasonable) it would be a good idea to remove the tabs, replacing all tabs with spaces. The command that does this from the shell is: pr -t -e4 file.c > file.txt

A solution for the non-writable files problem

Have you ever started editing a file, made a bunch of changes, and then typed :w to write your changes, only to find that the file is read-only? You can deal with that in a couple of ways, but one of the easiest things to do is to invoke a shell from within Vim and change the file's permissions before you save it again.

A vi macro to display line numbers using F1 and F2

While the vi editor has been known to be a little rough around the edges, it still has some pretty nice features. One of those features is the ability to define cool macros. Here we'll show you how to create two macros--one to display line numbers of the file you're editing, and one to hide the line numbers.

First, create a file named .exrc in your home directory (or edit the current file if it already exists). This is the configuration file that vi reads when it is started. Put the following two lines into this file:

:map #1 :set number^M
:map #2 :set nonumber^M

(A very important note: create the ^M characters in this file by typing the key sequence [CTRL-V][CTRL-M]. This key sequence embeds an actual ^M
character (the carriage return) into the file.)

Now, save this file and re-start vi. From vi's command-mode, you'll now be able to display line numbers beside your file contents by hitting the [F1] function key, and clear line numbers by hitting the [F2] key. If you like these macros, create your own powerful macros by following this same technique!

Creating outline

For this example you need to know a bit of HTML. We want to make a table of contents out of h1 and h2 headings, which I will call majors and minors. HTML heading h1 is a text enclosed by <h1> tags as in <h1>Heading</h1>.

(1) First let's make named anchors in all headings, i.e. put <h1><a name="anchor">Heading</a></h1> around all headings. The "anchor" is a unique identifier of this particular place in HTML document. The following S&R does exactly this:

:s:\(<h[12]>\)\(.*\s\+\([-a-zA-Z]\+\)\)\s*\(</h[12]>\):\1<a name="\3">\2</a>\4:

Explanation: the first pair of \(\) saves the opening tag (h1 or h2) to the \1, the second pair saves all heading text before the closing tag, the third pair saves the last word in the heading which we will later use for "anchor" and the last pair saves the closing tag. The replacement is quite obvious - we just reconstruct a new "named" heading using \1-\4 and link tag <a>.

(2) Now let's copy all headings to one place:

:%g/<h[12]>/ t$

Knowledge Base - ECN @ Purdue

1 Creating Line Numbers

The developers of the VI editor designed VI to be used without line numbers, feeling that the average user would locate and manipulate text by content rather than by line numbers. Additionally, because line numbers are constantly changing due to insertions and deletions, adjusting what you "think" is in a particular line can be dangerous.

The VI editor allows you to view line numbers in your file four ways: determining your current line number, a quick glance at line numbers for the complete file, insertion of line numbers for the current editing session only, and inclusion of line numbers for every session.

To determine the line number for the line the cursor is on, type "control g" as discussed in the Positioning Text on the Screen section.

To have a quick one time glance at line numbers, while you are in the file, type:

     :%nu

This will cause line numbers to be assigned to all lines; unfortunately, this also causes the complete file to scroll past quickly stopping on the last screenful of text. Now if you are working with a short 20-line file, this is great; however, if your file contains 200 lines, you will see the first 180 lines whiz past. To stop the scrolling action, you must press the "control s" to "stop" screen movement and later "control q" to "quit" the frozen screen. Some people get very good at timing the "control s" in order to get the exact point of the file to stop on the screen, most do not.

Many users find it more convenient to have numbers added to a file for the current editing session; knowing that the next time the editor is invoked, the numbers will not appear. To have line numbers inserted for the current session, type:

     :set number

Immediately you will see the line numbers appear in your file and they will remain until you exit the editor or type:

     :set nonu

The long-term line numbering option available with VI is to place a line numbering command in the .exrc file located in your HOME directory. The .exrc file is your personal control file to instruct all faces of the editor (VI, EX, and EDIT) on how you want it to perform when invoked. Not everyone creates a .exrc file. For those without this file, the automatic defaults of the editor are imposed, such as no line numbers. If you place the command "set number" in your .exrc file, the next time you invoke VI the editor will check this file for instructions and will present the file to you with line numbers. Later, if you decide you prefer to forgo line numbers, open your .exrc file and delete the "set number" line.

Type the following to get automatic line numbering each and every time you use the VI editor on all files in your .exrc:

     %  cd
     %  echo  'set number'  >>  .exrc
     %

Alternately, you can set the EXINIT to set nu.

You can set this in your .login or your shell start-up files.

  1. Open your editor to edit your .login or your shell start-up file. Add the following lines:

    For C-Shell:

    	setenv EXINIT "set nu"
    For Bourne or Korn Shell:
    	EXINIT="set nu"; export EXINIT 
    For Korn Shell Only (alternate method):
    	typeset -x EXINIT="set nu"
  2. Either log-out and log back in or "source" your shell start-up file.

2 Lines and Sentences in VI

To be successful in your editing, it is necessary to understand what the editor considers a line and a sentence. Just for clarity, a line and a sentence are different animals to the editor. To the editor, a line begins on the left of a screen and terminates at a carriage return . The carriage return is the invisible character placed in your file every time you press the "RETURN" key. A sentence to the editor is a string of characters of unspecified length (a few characters to many lines) terminating with the punctuation marks " . ", " ? ", " ! " followed by either a carriage return or two blank spaces.

Technical typists, secretaries, and students who produce lots of reports and papers find that editing is much easier to complete if as you are keying in text you make lines very short. The breaking up of sentences into many lines is helpful. Placing a carriage return after phrases and punctuation will make editing words and lines less of a problem.

Some people like wraparound typing (straight typing without inserting carriage returns), this is not recommended. The next example demonstrates the use of the delete operator with the end-of-line scope "d$" on text where the "RETURN" key follows phrases and punctuation versus using the same operator-scope command on wraparound typing. The results are drastically different.

When you print out your file using a text processor, the computer will connect lines and phrases plus insert spacing between sentences to make your material look presentable. For example:

3. Joining Lines

As you are editing files, you will find it is desirable to combine or join lines. This is easily done using the "J" (join) command. An illustration of joining lines is given below. The cursor is located on the top line when the "J" command is issued. VI will move the lower line and butt it to the end of the upper line. The editor takes care of necessary spacing for you.

4 Redrawing the Screen

The VI editor requires cpu (central processing unit) time to function. Each command and action takes a minute amount of time. This interaction is not a problem if only one or two people are accessing the system. However, the Engineering Computer Network has thousands of users and at any given moment many hundreds of users may be editing, running programs, and other system jobs, all competing for cpu time.

The VI designers foresaw that the editor could be a "time hog" and decided that one way to reduce some of the editing interaction with the cpu was to minimize redrawing the screen. This is why when you are in the text input mode you do not see the screen being updated until the action is completed and you return to command mode.

With time conservation as the impetus, the screen is also not redrawn each time a line is deleted. Rather, a removed line is replaced with the "@" symbol to symbolize an empty line, much as the tilde (~) is used. Further editing of the text that remains on the screen is still possible. These "@" symbols remain viewable as long as editing continues on this screen even though they are never inserted into the text.

Sometimes these "@" symbols are distracting and annoying. If a user would prefer not to see the "@" symbols, the screen may be redrawn and the "@" symbols eliminated by issuing the command "control r" or "control l". Experiment to see which command works on the terminal you are using.

5 Accessing the EX Editor

The VI editor has a powerful and useful companion editor, EX. In reality VI and EX are different faces of the same editor; both were developed from and use the same program base. VI is a screen oriented editor, while EX is a line oriented editor. Since both of these editors are built upon the same base, when one editor face is installed on a computer by default the other editor face is also there. This offers great advantages to the user because each face possesses individual strengths. Easy to use commands allow you to transfer from one face to another in order to increase your editing power by permitting you to use the desirable features of both editors and thereby better meet your editing requirements. The "global substitute" and "text marking" are two favorite EX commands.

All VI users, frequently without knowing it, make use of the dual face capability of this editor. For example, ":w", ":wq", or the ":quit!" are in reality EX commands. Also, the "read" command discussed in the Text Insertion section is an EX command! During an editing session, anytime you wish to invoke a single EX command, you must first make sure you are in command mode then type ":" followed by the command. The cursor will hop to the bottom of the screen and the command is echoed. When you press "RETURN", the EX command is executed and you are brought back to the command mode of VI.

Sometimes it is useful to issue a series of EX commands. This is done by typing "Q" while in command mode and you will enter and remain in the EX face until you type "vi" at the EX prompt (:), such as ":vi". Immediately you are returned to VI and can continue the editing session using VI commands.

It is suggested that users do not try to learn both VI and EX at the same time. Learn VI well, then proceed to learn EX. Attempting to learn both faces of the editor at the same time leads to frustration and confusion, as invariably the user mixes up which command to use when.

6 Repeating a Command

To make life a bit easier, VI allows text alteration commands to be repeated by using the "." (repeat) command. A handy way to illustrate the repeat command is with the "cw" command replacing a single word with two new words throughout a paragraph.

In this example, the first occurrence of "PU" is located with the search command PU". Then with the cursor on the "P" of "PU", the "cw" command is issued followed with "Purdue University" and the "ESC". The "n" key is pressed to find the next occurrence of "PU". The cursor relocates on the "P" of the next "PU" and all that is required to change it to "Purdue University" is to type "."

7 Temporarily Interrupting VI

The ability to access the UNIX shell while keeping the current file open with VI is a true convenience. To do this, you should first "write" the current buffer contents to the disk file with ":w". The current editing session may be interrupted by then typing ":!" followed by the desired command. When the requested command action is completed, the message:

     [Hit return to continue]
will appear at the bottom of the screen. After pressing "RETURN", you will be returned to the VI editor to the same location you were at when you temporarily interrupted the editing session.

A common way to use this interrupt ability during a current editing session is to read a recently received mail message, ":! mail". As you work more with UNIX, you will begin to see many ways to make this command work for you.

8 Editing Multiple Files Using VI

The VI editor provides an advanced feature which allows a user to invoke the editor and then edit multiple files by use of the ":e" (edit) command. This ability to access multiple files without leaving the editor permits a user to look up information in another file without exiting the editor. Additionally, because files are opened within the same editor invocation they can share the same named buffers, thereby making the transfer of text possible between the files. The example on page 40 demonstrates how two lines can be "yanked" from the file oranges, placed into a named buffer "k", and then "put" into the file apples.

When VI is invoked, a work area called a buffer is created for editing purposes. It is into this work space that a copy of a specified disk file is placed. The editor permits only one file copy in this buffer space at a time. Thus after making changes to a file (delete, add, or change), you must inform the editor what you wish done to the current buffer contents before you will be permitted to bring another file into this space. You do this by use of the ":w" (write current buffer contents to opened file), ":e!\ newfile" (toss current buffer contents, no update to opened file, and place a copy of newly called file in buffer), or ":quit!" (exit editor and toss buffer and buffer contents). The editor is smart enough to know that if all you have done is copy or read from a file, it can dispose of the unneeded buffer copy without further instructions from you when a new file is called.

When you have two files open, VI permits toggling between files by use of ":e\ #". This works because whenever VI sees the character "#" used in a command where a filename is expected, it substitutes the "#" with the name of the previous file. For example if you had been in apples then opened oranges, the command ":e #" would return you to where you were in the apples file. Repeat ":e #" and you would be back in oranges.

Another method to "cut" and "paste" between files is to use the mark command (m) in conjunction with named buffers ("). Move the cursor to the first line you wish to copy from oranges and type "ma" (m to mark the line and a to specify which mark). Next move the cursor to the last line you wish to copy and type ""zy'a". This command tells VI to open up "z (buffer named z) and y (yank) a copy of all the lines from the line marked 'a to the current line and place them in the aforementioned buffer. Return to apples with ":e #" and proceed to paste the contents of "z by moving to the desired location and p (put) the buffer contents by typing ""zp".

  1. Open the original file with "vi apples".
  2. Correct typo.
  3. Write the contents of the buffer to the file apples using the ":w" command.
  4. Issue the command ":e oranges" to open the second file.
  5. Yank a copy of two lines from the file oranges and put them into the named buffer "k" using the ""k2yy" command.
  6. Recall the original file, apples, to the buffer using the ":e apples" or ":e #" command.
  7. Contents of buffer discarded when apples is recalled to the buffer. The disk copy of oranges remains unaltered.
  8. Position the cursor and put the lines from the buffer "k" into apples using the ""kp" command.
  9. Write and quit the editor with the ":wq" command.
  10. Buffer is discarded upon leaving the editor.

9 Printing from VI

Print the current file (printer name is required if no default printer is set):
:!lp [-d printername] %
Print others files
:!lp [-d printername] filename

Tip #298 - Changing case with regular expressions vim online

I stumbled across this factoid on a website about vi. I haven't been able to locate it in the Vim documentation, but it works in Vim, and it's very handy.

There are times that you might like to go through a file and change the case of characters that match some arbitrary criteria. If you understand regular expressions well, you can actually do this fairly easily.

It's as simple as placing \U or \L in front of any backreferences in your regular expressions. Vim will make the text in the backreference uppercase or lowercase (respectively).

(A "backreference" is a part of a regular expression that refers to a previous part of a regular expression. The most common backrefernces are &, \1, \2, \3, ... , \9).

Some examples that demonstrate the power of this technique:

Lowercase the entire file -
:%s/.*/\L&/g

(& is a handy backreference that refers to the complete text of the match.)

Uppercase all words that are preceded by a < (i.e. opening HTML tag names):
:%s/<\(\w*\)/<\U\1/g

Please add a note if you know where this is in the documentation. I have done Ctrl-D searches on upper, lower, \U, and \L with no luck.

Vim Regular Expressions 101

(1) sent by Antonio Colombo:

"a simple regexp I use quite often to clean up a text: it drops the blanks at the end of the line:"

s:\s*$::

or (to avoid acting on all lines):

s:\s\+$::

[Chapter 30] vi Tips and Tricks

from the old edition of Unix Power Tools

30.37 Neatening Lines

Have you made edits that left some of your lines too short or long? The fmt utility can clean that up. Here's an example. Let's say you're editing a file (email message, whatever) in vi and the lines aren't even. They look like this:

This file is a mess
with some short lines
and some lines that are too long - like this one, which goes on and on for quite a while and etc.
Let's see what 'fmt' does with it.

You put your cursor on the first line and type (in command mode):

5!! 
5!!fmt

which means " filter 5 lines through fmt." Then the lines will look like this:

This file is a mess with some short lines and some lines that are too
long - like this one, which goes on and on for quite a while and etc.
Let's see what 'fmt' does with it.

This is handiest for formatting paragraphs. Put your cursor on the first line of the paragraph and type (in command mode):

!}fmt

If you don't have any text in your file that needs to be kept as is, you can neaten the whole file at once by typing:

% 
:%!fmt

There are a few different versions of fmt, some fancier than others. Most of the articles in the chapter about editing-related tools can be handy too. For example,

To neaten columns, try filtering through with the setup in article 35.22. In general, if the utility will read its standard input and write converted text to its standard output, you can use the utility as a vi filter.

- JP

more vi tips - wagoneers.com - Copyright © 1995 - 2001 John Meister

buffers
35 buffers based on 26 letters and 9 numbers.

"a5yy - copy 5 lines in buffer a
"ap - paste buffer a

"4p - paste 4th delete

"r5dd - delete five lines, place in bufffer r
"R2dd - delete 2 lines and APPEND them to buffer r

To copy text from a named buffer preface the p or P (put) command,
aka, "paste", with a double quote and the lowercase letter naming the buffer.
markers
ma - mark block of text for buffer a
d'a - delete from cursor to ma
y'a - copy from cursor to ma

If you type 'a you will move to the location of marker a

To sort a section:  mk
	            !'ksort

to sort a list and then place into three columns:
	!'ksort | pr -3tw50

aaaaaa
ccccc
cccc
ddddd
ffff
zzzz

pr option -3 specifies columns,
	the -t suppresses the header
	and the -w50 causes the output to fit within a page of 50 characters.
more ex
:args - lists file(s) working on
:rew - rewind, when editing multiple files

:w !spell to check spelling in work area

more magic
:set magic - enables * and . for pattern searches
:set nomagic - disables, to use meta characters, escape them (\).

:set wrapscan (ws) - allows wrapping of searches

VIM - Questions and Answers -- the most authoritative collection of tips

viTricks -- What every lazy C programmer should know about VI

  1. Running any shell command with within vi . The command
    :! command 

    will run the command without leaving vi. In particular

    :! a.sh

    will run a.sh

    :! cc z.c 

    will compile the program z.c After : the % is a short hand for the current file, so you can compile the current file with the command

    :! cc % 
          
    :!! 

    repeats last shell command you entered. This cuts down on typing when you do repeated compiles. you can compile the current file, place error messages on a file list

    :! cc % 2> err_lst 

    You can move back and forth between two files easily. If you are in file a , and want to edit file b enter :e b . Now you want to go back to file a enter :e # . This is useful if you place the compilation errors on the file err_lst (see above) and want to go back and forth between your file and the error file.

Vi has options which may be useful in programming

  1. the show match option allows one to check check opposite parenthesis or braces. Enter
            :set showmatch 
            

    and type the following

            while ( blah blah blah ) {
                do this loop }

    When you type the closing parenthesis or closing brace you should see the cursor jump to the opening parenthesis or brace. Next place the cursor at one of the parens or braces, and press the % key. The cursor should jump to the matching paren or brace. (also works for square brackets).

  2. the shiftwidth options allows one to easily 
          indent blocks of code. enter
          
            :set shiftwidth=4

    Now at any line enter >> ; the line should be shifted 4 spaces; enter 3<< and the 3 lines at the cursor should be shifted 4 spaces. This is useful for increasing the indentation of a block of code.

  3. the tabstop option allows one to tab over when in insert mode. Enter the command
        :set tabstop=4

    and pressing the tab key in insert mode will move the code over 4 spaces

  4. Most programmers like tab stops of 4, but the rest of the world use tab stops of 8. If we wish to communicate with the rest of the world, (i.e. send code over email and have it look reasonable) it would be a good idea to remove the tabs, replacing all tabs with spaces. The command that does this from the shell is:
            pr -t -e4 file.c > file.txt
  5. It is too much trouble to set all the options everytime we login. In your home directory name .exrc and put in it
        :set showmatch
        :set shiftwidth=4
        :set tabstop=4   

    Everytime vi starts up, it looks for this file and executes all commands in it

  6. How to cut and paste from a terminal. Suppose you had some text like
       while  (a > 0 ) {
            do thing
            
        }
        .....
        more stuff
        .....

    and you wanted to copy the while loop after the more stuff. There are several ways to do the; the more general way may

    1. mark the while loop. Place the cursor at line including 
            the enter :ma (create marker a at current position ) 
    2. move cursor to end of while loop and enter :mb 
            create a marker at the end of while loop 
    3. enter 'a (that's apostrophe a) to move to marker
            a 
    4. enter "aY'b This will copy the text between the 
            between the current postion and 'b into a buffer called a
            
    5. move the cursor to were you want to place the while 
            loop, i.e. after more stuff. 
    6. enter "aP this will put what's in buffer a
            into current position.

  7. You can move text from file a to file b . 
        Suppose you want to place the while loop into another file. Copy the while 
        loop into the buffer a as above, move to the to file b , and 
        paste the while loop into the file.    

  8. This command will replace the 3rd character from the end 
        of each and every line with '::' (nothing else will be changed). Try doing 
        this in Word!
        

    1,$s/.\(..\)$/::\1

TALUG Vi Tips & Tricks

I have the Quickref sheet and the Tips & Tricks sheet available on-line here:

File Postscript PDF
VI Quick Reference quickref.ps (38K) quickref.pdf (24K)
VI Tips & Tricks tips-tricks.ps (21K) tips-tricks. PDF (9K)


EX Command Mode
EX commands begin with a : and are are often used with a command address range to indicate which lines the EX command should be applied to. : commands are executed only after you press Enter. If you want to exit last line mode without executing a command, type Ctrl-c.

The following EX command deletes lines 10 through 25:
:10,25d

The address in the above example is 10,25. The : indicates that this is an EX command, and d is the actual command (delete).

Some of the commonly used ex command addresses are:

. the current line.
$ the last line in the file.
% all the lines in the file.
n line n
n,m lines n through m
-n start at n lines above the current line
+n start at n lines below the current line

For example, to delete the first line in the file through the current line, type:
:1,.d

Summary of EX commands

:n1,n2d Delete from line n1 through line n2.
:n1,n2y Yank lines n1 through n2 into the default buffer.
:n1mn2 Move line n1 below line n2.
:n1,n2mn3 Move lines n1 through n2 below line n3.
:n1tn2 Copy line n1 below line n2.
:n1,n2tn3 Copy lines n1 through n2 below line n3.
:r filename Insert file filename below current line.
:r !command Inserts the results of command at the cursor.
:nr !command Same as above, but place output at line n.
:w! file Force write to file.
:n1,n2w !command Send address specified to command.
:n1,n2w newfile Place lines n1 through n2 into the file newfile.
:n1,n2w >> otherfile Append lines n1 through n2 to otherfile.
:!command Execute a single command.
:n1,n2!command Run the lines specified by the address range through the command and replace with the output.
:sh Execute a shell.
:vi Leave EX mode and return to VI mode.
:args Show files in edit list.
:rew Move to the front of the file edit list.

Search & Substitution

The search and substitute command has two option flags: the g flag for making global changes, and the c flag for making conditional changes (these are described below). The format of the search and substitute command is:

:[address]s/search_string/replace_string/flags

Changing case

:n1,n2s/[a-z]/\U&/g Changes lowercase letters to uppercase in lines n1 through n2.
:n1,n2s/[A-Z]/\L&/g Changes uppercase letters to lowercase in lines n1 through n2.

Global Actions

Global actions allow you to run commands (substitution, delete, etc.) against all lines in a file. The format of the search and substitute command is:

:[address]g/search_string/command

Conversly, you can use the following format to run commands against any lines not matching the pattern:

:[address]v/search_string/command

If [address] is not specified, all lines in the file are evaluated against the EX command.

Jumping to a file

One of VIM's enhanced features allow for a quick jump to a file name. This is usefull in editting HTML documents that have the same directory structure. For example:

<a href="products/index.html">Our products</a>

by placing the cursor on the word products in the anchor tag, then pressing Ctrl-W f, the file will be brought up in a split window for viewing/editing.

Counting words, lines, etc.

To count how often any pattern occurs in a buffer, set 'report' to 0, and use the substitute command to replace the pattern with itself. The reported number of substitutions is the number of items. Examples:

:set report=0
:%s/./&/g characters
:%s/\i\+/&/g words
:%s/^//g lines
:%s/the/&/g "the"

Sample Files

VI Editor Help Tips And Tricks

To use most of the following macros you will need to know how to key in control characters in the map string. For example an escape character is: ^] , to key this in you cannot just hit the escape character or the control and the right bracket keys. You will have to key in a ^V, this character in unix quotes a control character. Basically when you hit CTRL and V keys together you will see a ^ symbol. This is the indication that it is waiting to quote a control character.

To invert order of characters           -    xp
To pluralize a word                     -    eas
To delete till beginning of the line    -    d0
To browse all lines with 'pattern'      -    :g/pattern/p
To browse through numbered buffers      -    "1pu.u.u (u and . alternating)
To substitute 'str' with 'replace' globally -

        :g/str/s//replace/[g][c]
Use word erase, line erase while inserting to backup, for ex:

        hello tim^W     -       would back cursor to 't' of tim
        hello tim^U     -       backs up cursor to beginning of line
Since these keys can be redefined check their status by the Unix
command :
        stty -a
look for : werase , kill
To copy a set of lines from one file to another:
(1)     save current file use :w
(2)     edit the file with reqd. data, use :e <filename>

(3)     now yank lines into a buffer e.g. "a3Y would
        yank 3 lines into buffer `a`.
(4)     edit original file use :e! <filename>

(5)     place cursor where using command "ap or "aP the text in
        the buffer 'a' will be pasted.

To switch back to the place in previous file being edited use:
        CTRL^ (hold control key while pressing ^ key)
this is a short key for :e #
To comment in C language (/*...*/) you can map characters say v
& V in the following manner:

        map v I/*^[$a*/^[^M
        map V /\/\*/^MNxx/\*\//^Mxx``

v will comment a single line by placing /* and */ at the
beginning and end of the line respectively, and V will remove
these from a commented line or paragraph (you must be at or
within the comments).
To print a certain range of lines straight to printer without
having to save in between in a file :

:#1,#2 w !lpr

would send lines from #1 to #2 to the default printer.
Deleted lines can be recovered by going through the numbered buffers:
The nubered buffers 1 through 9 hold the last 9 deletes.
To look through the buffers :

(1) type :       "1p      : this will echo the buffer #1
(2) type :       u        : this will undo the paste
(3) type :       .        : this will exec. the last cmd "1p ..but
                          : in this unique case adds 1 and execs. 
                          : "2p another . would exec. "3p 
(4) when you hit the correct buffer ... keep it!
   Here's a good one. This macro searches for text that is right under the
cursor. It eases the pain of typing search strings.  This map is for
^A (this comes standard in "elvis"), so when your cursor is at
the beginning of a word, and ^A is typed, the cursor will jump
to the next occurrence.

map ^A mz:.t.`zd0:s/[0-9a-zA-Z-><\*\.\:\"#@%&_]*/& /^MEa/ ^[DI/^[:.d z^M@z

Explanation :
mz    mark current position as z
:.t.  copy line below
`z    jump back to marked position z ( note the ` instead of ' )
d0    delete till beginning of line
:s/.../& /^M  find a whole word; include in the word: alphanumeric, and 
        some assorted junk characters. substitute the word with
        a word and a space after.
E     go to end of word ( note E instead of e )
a/ ^[ add a  slash and a space (if the word was at eol then D won't work)
D     delete from the space till eol
I/    insert slash at beginning of line
:.d z delete line into buffer z
@z    execute buffer z ( which is /word/ , will grab same word on same line)

executing a `n' command in vi would go to the `next' occurrence.

        COOL!
 A similar mapping for ^K, this one EDITS the file which is defined by the
  string in the file. For example if you are in a file called `a' and this file
  contains a string such as: jump to file b 
  then setting cursor on `b' and typing ^K jumps to file b.
  the word is delimited slightly differently in this mapping.

                        W A R N I N G
This macro uses :e! , the exclamation will implies that if this command
is used before saving the edits will be lost. Therefore save the file
then use this command. This was necessary because the command itself
edits the file, and hence to jump to another file needs the :e!


map ^K mz:.t.^M`zd0:s/[0-9a-zA-Z-/\._]*/& /^MElDI:e! ^[:.d z^M@z

explanation:

pretty much the same as above.

instead of adding a `/` adds the line :e!

SEAS Computer Operations Vi Useful Tips

  1. What is the best way to learn Vi?
  2. How do I get into a file using Vi?
  3. How do I move the cursor in the file?
  4. How do I insert text?
  5. How do I delete something?
  6. How to undo and repeat commands?
  7. I just finished my document, how do I save?
  8. How can I include text in my document?
  9. How can I edit my text?
  10. Is there a way I can cut and paste?
  11. How do I change the case of letters?
  12. How do I switch between files when editing multiple files?
  13. Is there a way I can switch two characters?
  14. How can I search for specific text?
  15. Can deleting be used with a search operation?
  16. What are some examples of search and replace patterns?
  17. Is there a way to execute a unix command from inside Vi?
  18. How can I set options inside Vi?
  19. I'm tired of having to redefine all of my options every time I go into Vi, is there any way around this?
  20. How do I reformat paragraphs in Vi?
  1. I just finished my document, how do I save?

    There are several save options. One of these should work for you:

    • :w           writes the file and save the changes
      
    • :w name      same, but the changes go into a file with the new name
      
    • :x,y w name  writes only the lines x to y to the file (for excerpting)
      
    • :wq          writes and quits at the same time
      
    • ZZ           writes and quits at the same time
       
  2. How can I include text in my document?

    • :r name      reads in the file name at the point of the cursor
      
    • :r!cmd       executes the shell command cmd and inserts output
                    at the point of the cursor
  3. How can I edit my text?

    • J		joins next line to current line
    • x		deletes the character under the cursor
    • r*		replaces the character under the cursor with *
    • sstring ESC	substitutes the character under the cursor with string
    • cwstring ESC	changes current word to string 
    • c$string ESC	changes from cursor to end of line with string 
    • ccstring ESC	changes current line to string 
  4. Is there a way I can cut and paste?

    • yy      yanks lines into a temporary buffer, where they are
              saved for later use
    • p       pastes the previously yanked lines

    The yanked lines can be put as often as one likes, which is a good way to repeat things. Also, deleted lines can be put as well, so dd is the same as yy dd. Also, there is only one default buffer. To move two things, or to yank and put with other work in between, you can save to named buffers. For example "ayy will yank a line in buffer a. Then buffer a can be pasted using "ap.

  5. How do I change the case of letters?

    Use the tilde (~) to toggle the case (lower/upper) of letters. It will ignore non alphabetical characters.

  6. How do I switch between files when editing multiple files?

    When editing several files, you can switch to file #x using the command: :e#x

  7. Is there a way I can switch two characters?

    You can reverse 2 characters in a word by typing xp (x to delete and p to paste).

  8. Can deleting be used with a search operation?

    d/pattern ESC deletes up to the pattern, but leaves the pattern. Then neat thing about this principle is it works with most other Vi commands such as y.

       
    • :s/pattern/xx/      changes first pattern in current line to xx
      
    • :s/pattern/xx/g     changes every pattern in current line to xx
      
    • :%s/pattern/xx/g    changes every pattern in all lines to xx
      
    • :%s/pat/xx&yy/g     changes every pat in all lines to xxpatyy
      
    • :3s/pattern/\U&     changes first pattern in third line to PATTERN
      
      

    As usual, type u to undo and & to repeat a substitution.

Tips and Tricks for the vi Editor

NOTE: The following collection of tips and tricks is intended for advanced vi users. If you need an introduction to the vi Editor, buy "Learning the vi Editor" by Linda Lamb (from O'Reilly & Associates) or try these online references.

You might also want to take a look at some simple Perl one-liners I wrote that can be used with filtering in vi.

If you want to join every two lines, and you don't have any markings to guide you, you can do this. This script also illustrates VIM's ability to define functions etc. VIM is really closing the functionality gap of vi to EMACS ;-).

:set tabstop=4 # the tabstop option allows one to tab over when in insert mode. Enter the command

Recommended Links

Softpanorama hot topic of the month

Softpanorama Recommended

Top articles

Sites

tips vim online

Vim Cookbook



Etc

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available in our efforts to advance understanding of environmental, political, human rights, economic, democracy, scientific, and social justice issues, etc. We believe this constitutes a 'fair use' of any such copyrighted material as provided for in section 107 of the US Copyright Law. In accordance with Title 17 U.S.C. Section 107, the material on this site is distributed without profit exclusivly for research and educational purposes.   If you wish to use copyrighted material from this site for purposes of your own that go beyond 'fair use', you must obtain permission from the copyright owner. 

ABUSE: IPs or network segments from which we detect a stream of probes might be blocked for no less then 90 days. Multiple types of probes increase this period.  

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Haterís Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least


Copyright © 1996-2016 by Dr. Nikolai Bezroukov. www.softpanorama.org was created as a service to the UN Sustainable Development Networking Programme (SDNP) in the author free time. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License.

The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to make a contribution, supporting development of this site and speed up access. In case softpanorama.org is down you can use the at softpanorama.info

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the author present and former employers, SDNP or any other organization the author may be associated with. We do not warrant the correctness of the information provided or its fitness for any purpose.

Last modified: September 12, 2017