Home arrow Articles arrow Intro to Vi ( Vim )
Intro to Vi ( Vim ) PDF Print
Saturday, 29 April 2006
This is bascially a primer for vi. Even if you're not new to vi, you will probally find something. It covers the basics needed to edit files on your system using one of the most widely available editors on UNIX/Linux systems. It a very complex beast, but with a basic understanding and memorizing a few commands it becomes a valuable tool.

Back when I first started with vi I wish I had something like this. After using vi for as long as I have, I'd be lost without it. It's definately worth learning if you are editing a lot of text or code.

It'll be in plain english. Written in a manner where it would be considered a tutorial and then notes to go back and use as a reference. If I mention something else along with an item i'll also try to explain it quickly. I'm not a great writer. My punctuation and spelling are not the best, but I've been told I can explain stuff easily and get the point across. You'll just have to Suffer :)

So lets get started!

 

  1. Using VI
    1. Opening files
    2. Moving around and editing
    3. Closing, writing and abandoning files
    4. Searching and replacing
    5. Color syntax highlighting
    6. Reference

    Ver 0.1.1 - Last updated: 10/05/2000




    Using VI

      I'll use 'vim' in this section, which is "Vi IMproved". All of this works with 'vi' except for the color related items later on.

      RPM Package Contains  
      vim-enhanced-5.6-11 vim ( ex - symlink to vim )  
      vim-X11-5.6-11 gvim the X version of vim ( vimx - symlink to gvim )  
      vim-minimal-5.6-11 vi ( ex, rvi, rview, and view - all symlinks to vi )  
      vim-common-5.6-11 Docs, syntax files, macros  

      DESCRIPTION

       

      "Vim  is  a  text  editor that is upwards compatible to Vi.  It can be used to edit any
      ASCII text.  It is especially useful for editing programs.
      
      There are a lot of enhancements above Vi: multi level undo, multi windows and buffers,
      syntax  highlighting,  command line editing, filename completion, on-line help, visual
      selection, etc..  See ":help vi_diff.txt" for a summary of the differences between Vim
      and Vi.
      

      If you install the packages above you will have 'vi' and 'vim' installed on your system.
      /bin/vi
      /usr/bin/vim

      What I like to do is create an alias for vi so I can just type 'vi' instead of 'vim'. This keeps the 'vi' in /bin for emergencys and makes it easier for me to start up vim instead
      > alias vi='/usr/bin/vim'

      So...any examples in this section where I use vi it's actaully vim

      One of the great things about learning vi is it's widespread use on UNIX systems. Every system i've every run across has at least vi on it. It's also available for Windows based systems.
      VIM allows color syntax highlighting for tons of different files. Some of these include html, perl, c and php3. This makes coding and editing much easier.

    1. Opening files
    2.  

      To open an existing file or create a new file if it doesn't exisit:

       

        > vi filename

      To open an existing file at a certain line:

       

        > vi +line_number filename

        Open inetd.conf at line 35:
        > vi +35 inetd.conf

      To open an existing file at first occurance of a string:

       

        > vi +/string filename

         

        Open inetd.conf to first occurance of "ftp":
        > vi +/ftp inetd.conf

    3. Moving around and editing
    4.  

      "Hey, I started vi one time and I couldn't even quit the program! It's a nightmare."

      Learning the basics of vi can be challenging. Once you understand the difference between command mode (ex) and the editing mode things get a lot easier.

      Let's start a new file and try a few things:
      > vi testing-vi

      Ok. You should see a bunch of ~'s going down the left side. This tells you that all those lines are blank and don't exist in your file. Looking along the bottom you'll see:
       "testing-vi" [New File] 0,0-1 All 

      Of coarse we already know the file name. But the status line (also command line) comes in handy to see what mode your in or file information when we save and don't exit. It'll give the filename and what was written to the file.

      The 0,0-1 is the [row],[col] were at in the file. -1 means the file is empty

      Before we start let me say that the Caps Lock will torture you in this program. Make sure it's off. Also if your commands aren't doing what you expect, look to see that you didn't hit it by accident

      Let's "insert" some text. Hit 'i' for insert mode and the status bar in the bottom will have "--INSERT--". This will start insterting text where the cursor is located. Type:
      test sentence number 1

      It'll stay in insert mode until you hit the <esc> key, so do that now. You'll notice that the cursor will stay at the point we were last editing at. There are a few ways to move the cursor around.

      Use the 'Home' and 'End' keys to move to the begining and end of the lines. You can also use shift-4 and shift-6. I use the shift method because not all terms map the Home and End keys correctly. You don't have to use that method, but it's nice to know when they aren't mapped correctly.

      The arrow keys will move the cursor around one character/line at a time.

      Now let's change the line to read "This is test sentence number 1"
      Hit 'Home' to get to the beginning of the line
      Hit 'i' for insert mode
      add "This is " and hit <esc>

      <esc> will always take you out of edit mode. When in doubt, smack <esc>

      You might be thinking "Hey, I could do this a lot easier in _____ editor with all this hitting esc and stuff". For the basics, maybe, but when you start learning a lot of the shortcuts in vi you won't be thinking that anymore.

      Try out the 'w', 'b' and 'e' keys.
      w = next word
      b = move back a word
      e = end of word

      You should be able to easily jump around the line. You'll notice all of these commands are easy to remember. Along with 'i' to go into insert mode there is 'a' to go into append mode. 'a' will start inserting text AFTER the cursor while 'i' inserts it at the cursor.

      Lets copy (yank) the first line. You can be anywhere on the line that you wish to copy.
      Hit 'yy' - This will copy the current line into the buffer.
      Now hit 'p' to paste it. Since we only have one line it will paste the buffer starting after the line you are at.

      Now go to the 1 on the end of the second line
      Hit 'r' and then 2 to 'replace' the text under the cursor.
      'r' will replace the character ( only one ) under the cursor. 'shift-r' would type over characters until <esc> is hit

      Now we know 'w' is word. And we know 'y' is yank. Let's combine these 2 together.
      Go to the beginning of the second line. The cursor should be on the 'T' in 'This'.
      Hit 'yw'. We now have the first word in the buffer. Hit the 'end' key and then 'p' to paste the word

      We now have "This is a test sentence2This". Doesn't make any sense. Lets delete the word 'This' that we just added
      There's a couple of ways we can go about this. If the cursor is on the end of the line and we hit 'x' it will act as a backspace and delete the text. If we are at the 'T' in 'This' and hit x it will delete one character at a time below the cursor. Since I think we know what a backspace looks like when we use it let's try the going to the 'T' in 'This' and hitting 'x'.
      Pretty simple.

      Now f we did 'dw' and we were at the start of the 'T' in 'This' would have deleted the entire word in one shot.

      Hitting 'dd' anywhere on the line would have deleted the entire line.

      Before using any movement commands, make sure your not in any of the insert modes by hitting<esc> a few times.
      Also keep a lookout for stray i's in your text. Yes, I took down a DNS server for hours with a stray 'i'. It took a while to find and was only found after running the thing in debug mode and searching. Not fun, but it made for a good joke between the admins. Everytime something got screwed up it was "Those damn lowercase i's *#@$ing up the system again!!" :)

      You can also tell vi to do the command multiple times by prefixing the command with a number.
      Examples:
      '4w' would move ahead 4 words.
      '5yy' would yank the next 5 lines which you could then paste somewhere.
      '2yw' would yank the next 2 words which you could then paste somewhere.
      '3dw' would delete the next 3 words.
      '10dd' would delete the next 10 lines from the file.
      Very cool once you get the hang of it.

      Another helpful one is 'shift-J' which takes the line below the current line and appends it to the current line.
      So if we had:
      This is my line and
      its broken
      Place the cursor on the first line and hit 'shift-j' it'll combine them:
      This is my line and its broken
      Not knowing that one would drive you crazy :)

      vi has an undo history.
      both 'u' and ':u' = undo. You can do this multiple times in a row to go back multiple edits

      "What's the : all about?"
      It one of vi's modes and it's called ex mode. I'm only going to go over a few of the important ones in this file but there are TONS of things available once your in ex mode

      Visual Mode

      Hit 'v' and then move around with the arrow keys to highlight your selection.
      You can then delete or yank (copy) the selection.

      Experiment with it awhile

      Cutting and pasting between terms ( terms in X )

      -This is very easily done. Make sure the vi in the term your going to paste into is in insert mode and the cursor is where you want the text to go
      -Select your text in the other window with the mouse
      -With a 2 button mouse click both buttons at the same time - With a 3 button or whee l mouse click the middle button to paste

      That's not just a vi thing, but works anywhere if you didn't already figure it out

    5. Closing, writing and abandoning files
    6.  

      Here are the important ones:

      :q			 Quit file
      :q!			 Quit file ( discarding any changes )
      :w			 Write. By default it saves the file as what it was named when vi was started.
      :w!			 Write file ( overiding protections - example: write a file that's read only )
      :30,50wfilename		write lines 30 thru 50 to filename
      
      :30,50w>>filename	write lines 30 thru 50 and append it to filename
      
      So 'w' is write and 'q' is quit. So
      :wq is write and quit and is the same as ':x'

      You can also write what you are editing to another file easily by doing
      :wfilename like ':wtesting-vi2' to save it as a different file and continue

    7. Searching and search/replace
    8.  

      Searching

      '/' puts vi into search mode
      /pattern

      So '/test' will search for the word 'test' stopping at the first match.
      Hitting '/<enter>' again will go the the next match. Every time you hit '/<enter>' it will continue to search until it hits the bottom. It will then print in the status window that the bottom of the file has been reached and will start at the top again. Being able to search in one keystroke makes life a lot easier.

      Searching backwards:
      ?pattern
      ?<enter> repeats the search

      Replacing

      There are simple string replacements or you can use regular expressions. We'll stick to the simple stuff for now

      If your familiar with 'sed' this will look familiar to you. If not, well your getting a basic lesson in using 'sed' too :)

      Replace the first occurance of 'old' with 'new' on the current line
      :s/old/new/

      Now if we add a 'g' on the end for 'global' we replace the all occurances of 'old' with 'new' on the current line
      :s/old/new/g

      Now if we add a '%' to the beginning of the line it will replace every instance of 'old' with 'new' in the entire file.
      :%s/old/new/g

      You can specify the lines to replace between by listing them first
      :100,110s/old/new/g

      You'll find this will work with basic words. Once you try searching for [ ] > < \ / and others your going to run into problems. That's because they are part of the syntax for 'regular expressions'. reg exp is a WHOLE other howto. I'll give you some basics here. I have a long way to go before I even think I know enough about reg exp to write a tut on it:)

      We'll be using the '\' character. You can use this to tell it that the next character is to be treated like a normal character, not a special one.

      Let's say we want to search and replace /home/jack in your entire file with /home/joe. If we look at the syntax for the search we see that the division between the old text and the new text is a /. So right off the bat we can see this is going to freak it out. We need to protect those characters in our search string and we'll use the \ to do it

      Wrong way:
      :%s//home/jack//home/joe/g

      That basically says replace '' with 'home' and it'll probally crap out.

      Right Way:
      :%s/\/home\/jack//home\/joe/g

      Notice the \ directly before each / in the strings telling it "Hey, the next character isn't yours..it's mine" :)
      Using the \ before special characters also works in searches..and in perl and in...

    9. Color syntax higlighting
    10.  

      This one of the things I love about vim.

      From /usr/doc/vim-commoni-version/doc/syntax.txt

      Syntax highlighting enables the possibility to show parts of the text in
      another font or color.  Those parts can be specific keywords or text
      matching a pattern.  Vim doesn't parse the whole file (to keep it fast), so
      the highlighting has its limitations.  Lexical highlighting might be a
      better name, but everybody calls it syntax highlighting, so we'll stick with
      that.
      
      Vim supports syntax highlighting on all terminals.  But since most ordinary
      terminals have very limited highlighting possibilities, it works best in the
      GUI version, gvim.
      

      The below example is a section of perl file with color syntax highlighting.

      
      
                              # Check the "label" and see what it is
                              if ( $label eq "description" ) {
                                      $dot{$dot_file}{description}=$data;
                                      next;
      
                              } elsif ( $label eq "size" ) {
      
                                      # Ok..in the file it's hex values seperated by a "-"
      
                                      # so split it up.
                                      ($hex_rows,$hex_cols) = split /-/,$data;
      
                                      # We create the "size" for Set Mem and Write DOT stuff
      
                                      $dot{$dot_file}{size}="$hex_rows$hex_cols";
      
                                      # We create "rows" and "cols" for other uses.
                                      $dot{$dot_file}{rows} = hex ($hex_rows);
                                      $dot{$dot_file}{cols} = hex ($hex_cols);
      
                                      next;
      
                              } elsif ( $label eq "bits" ) {
                                      $dot{$dot_file}{bits}="$data";
      
                                      # Now begin splitting it up into individual lines for other uses.
      
                                      ( @bits ) = split /\\r/,$data;
      
                                      #---------------------------------------------------------
      
      

      All the colors are configurable in both the '.vimrc' and '.gvimrc' files in your home directory.
      I can't remember what the default file looks like or if there is even one. I'm thinking there is no default .vimrc. If not save the stuff between the lines as '~/.vimrc'.

      Mine is customized, but also has a description for each type and a list of the colors. I also use Eterm which has much nicier colors than the rxvt or Xterms do. So it might be hideous in those :)
      Here is my .vimrc file ( the config file for vim )
      " denotes a comment line. So some things are commented out, but all the descriptions are there as a template to customize your vim

       


      set background=dark
      
      " The next line used to work, then it made your cursor disappear in later redhat distos..called a feature
      " set term=xterm-color
      
      " Turn on the colors!
      syntax on
      
      " shut off that STUPID 'highlight your searches' crap in the latest RedHat release of vim
      nohlsearch
      
      "           NR-16   NR-8    COLOR NAME ~
      "                                                       *cterm-colors*
      "           0       0       Black
      "           1       4       DarkBlue
      "           2       2       DarkGreen
      "           3       6       DarkCyan
      "           4       1       DarkRed
      "           5       5       DarkMagenta
      "           6       3       Brown
      "           7       7       LightGray, LightGrey, Gray, Grey
      "           8       0*      DarkGray, DarkGrey
      "           9       4*      Blue, LightBlue
      "           10      2*      Green, LightGreen
      "           11      6*      Cyan, LightCyan
      "           12      1*      Red, LightRed
      "           13      5*      Magenta, LightMagenta
      "           14      3*      Yellow
      "           15      7*      White
      
      
        " highlight Normal ctermbg=black ctermfg=darkgrey
      
        " the mouse cursor
        "  highlight Cursor ctermbg=none ctermfg=white
      
        " comment that start with #
        highlight Comment ctermbg=none ctermfg=lightblue
      
        " any constant
        highlight Constant ctermbg=none ctermfg=red
      
        " a string constant: "this is a string"
        highlight String ctermbg=none ctermfg=white
      
        " a charater constant: '\n', 'c'
         highlight Character ctermbg=grey ctermfg=red
      
        " a number constant: 234, 0xff
         highlight Number ctermbg=none ctermfg=red
      
       " a boolean constant: TRUE, false
       " highlight Boolean ctermbg=none ctermfg=green
      
        " a float constant: 2.3e10
         highlight Float ctermbg=none ctermfg=green
      
        "########
      
        " variables without $ as in declaring
        highlight Identifier ctermbg=none ctermfg=cyan
      
        " function name ( also: methods for classes - spaces in sub" "balh" " {
         highlight Function ctermbg=none ctermfg=green
      
        "########
      
        " Any statement    quotes >  for in read echo
        highlight Statement ctermbg=none ctermfg=green
      
        "if, then, else, endif, switch, etc
        highlight Conditional ctermbg=none ctermfg=brown
      
        "for, do, while, etc
        highlight Repeat ctermbg=none ctermfg=brown
      
        "case, default
        highlight Label ctermbg=none ctermfg=green
      
        " "sizeof","+","*", etc
        highlight Operator ctermbg=none ctermfg=lightblue
      
        " Any other keyword
        highlight Keyword ctermbg=none ctermfg=red
      
        "########
        "next does `expr' type stuff..not much really
        highlight Special ctermbg=none ctermfg=red
      
      
        " int, long, char, etc.
        " highlight Type ctermbg=none ctermfg=green
      

      The gvimrc is very similar except the lines have 'guibg=' and 'guifg=' instead of the 'ctermbg' and 'ctermfg'

    11. Reference
    12.  

      Here are some of the commands for vi.

      Movement Commands

      Character
      h,j,k,l Left,down,up,right( or arrows)
         
      Text
      w, W, b, B Forward, backward by word
      e, E End of word
      ), ( Beginning on next, previous sentence
      }, { Beginning of next, previous paragraph
      ]], [[ Beginning of next, previous section
         
      Lines
      0, $ First, last position of current line
      ^ First character of current line
      +, - First character of next, previous line
      n Column n of current line
      H Top line of screen
      M Middle line of screen
      L n (number) of lines after top line
      nL n (number) of lines before top line
         
      Screens
      [ctrl-F],[ctrl-B] Scroll forward, backward one screen
      [ctrl-D],[ctrl-U] Scroll down, up one-half screen
      [ctrl-E],[ctrl-Y] Show one more line at bottom, top of window
      z[return] Reposition line with cursor: to top of screen
      z. Reposition line with cursor: to middle of screen
      z- Reposition line with cursor: to bottom of screen
         
      Searches
      /pattern Search forward for pattern
      ?pattern Search backward for pattern
      n, N Repeat last search in smae, opposite direction
      /, ? Repeat previous search forward, backward
      fx Search forward for character x in current line
      Fx Search backward for character x in current line
      tx Search forward for character before x in current line
      Tx Search backward for character after x in current line
      ; (semicolon) Repeat previous current-line search
      , (comma) Repeat previous current-line search in opposite direction

       
         
      Line number
      [ctrl-G] Display current line number
      nG Move to line number n
      G Move to last line in file
      :n Move to line number n
         
      Marking position
      mx Mark current position as x
      `x Move cursor to x
      `` Return to previuos mark or context
      'x Move to beginning of line containing mark x
      '' Return to beginning of line containing previous mark

      Editing Commands

      Insert
      i,a Insert text before, after cursor
      I,A Insert text at beginning, end of line
      o,O Open new line for text below, above cursor
         
      Change*
      r Replace with next typed character
      ~ Change case of character
      cm Change text block defined by movement
      command m (e.g.,cw or cl)
      cc Change current line
      C Change to end of line
      R Type over characters
      s Delete character and substitute text
      S Delete Current line and substitute text
         
      Delete, move
      x Delete character
      X Delete character before cursor
      dm Delete text block defined by movement
      command m (e.g., d/pattern or dG)
      dd Delete current line
      D Delete to end of line
      p,P Put deleted text after, before cursor
      "np Put text from delete buffer number n after
      cursor ( for last nine deletions)
         
      Yank (copy)
      ym Yank (copy) text block defined by movement
      command m(e.g.,y]] or y})
      yy,Y Yank current line
      "ayy Yank current line into named buffer a
      p,P Put yanked text after, before cursor
      "aP Put text from buffer a before cursor
         
      Other commands
      . Repeat last edit command
      u,U Undo last edit; restore current line
      J Join two lines
      [ctrl-L],[ctrl-R] Redraw screen
         
      ex equivalents
      :d Delete lines
      :m Move lines
      :co or :t Copy lines
      :.,$d Delete from current line to end of file
      :30,60m. Move lines 30 through 60 after current line
      :.,/pattern /co$ Copy from current line through line containing
      pattern to end of file

      Exit Commands

      ZZ Write (save) and quit file
      :x Write (save) and quit file
      :wq Write (save) and quit file
      :w Write (save) file
      :w! Write (save)file (overriding permissions)
      :30,60wnewfile Write from line 30 through line 60 as newfile
      :30,60w>>newfile Write from line 30 through line 60 append
      to file
      :w %. new Write current buffer named file as file.new
      :q Quit file
      :q! Quit file (discarding any changes)
      Q Quit vi and invoke ex
      :e file2 Edit file2 without leaving vi
      :n edit next file
      :e! Return to version of current file at time of last
      write (save)
      :e# Edit alternate file

       


      Aditional information:
      man vim - manpage
      vimtutor - Vimtutor starts the Vim tutor. Another way to learn Vim
      /usr/share/vim/vim56/doc/*.txt - Vim docs
      :help - in vim

      For recent info read the VIM home page: www.vim.org

      Also, if you don't already have it, get Eterm. It's by far the best term.
      You can get it at:
      www.eterm.org

      This page coded in Vim :)



      This text written by Denis Hruza - Homepage
      Any comments, suggestions, corrections or additions should be sent to
      hruzaden@
      exit18.com
Last Updated ( Saturday, 29 April 2006 )
 
< Prev   Next >