VI Useful Shortcuts

VI Useful Shortcuts

Using VI for the first time maybe difficult to some people, especially to those who are used to conventional editors like Notepad, Notepad++, Lime, Sublime. Using those editors is somehow easier, as it is more likely what you used in college/school, and it has a more user-friendly GUI.

Seeing those multi-colored texts and lines could be distracting and not easy on the eyes. It also doesn’t contain the instructions or menu usually found in Nano and other
conventional editors, which is very difficult for a first time VI user. But using VI has its advantages. Its faster than other conventional editors. When using FTP, saving in VI takes a split second to occur, while in Notepad++ it usually takes 3-8 seconds to save a file. VI is almost available anywhere in UNIX, be it on desktop or server.

Here I will tell you the VI shortcut keys that I use everyday for easier typing and coding in general.

  1. Basic:
    1.”i” – Inserts text to the left of the cursor.
    2.”I” – Inserts text at the beginning of the line, no matter where the cursor is positioned on the current line.
    3.”r” – Replace the character under the cursor with the next character you type.
    4.”u” – Undo.
    5.”ctrl+r” – Redo.
    6.”d” – Delete text.
    7.”x” – Delete character(s) to the right of the cursor, starting with the one beneath it.
    8.”ESC” – Escapes you out of the insert/replace/visual mode.
  2. Intermediate:
    1.”H” – Move cursor to the top line of the screen, (as opposed to the top of the document which may not be the same place).
    2.”M” – Move cursor to the middle of the screen.
    3.”L” – Move cursor to the last line on the screen.
    4.”ESC :wq RETURN” – Save and exit VI.
    5.”ESC :q! RETURN” – Exit WITHOUT saving changes
    6.”/the” – Finds the next occurrence of the. This will also find their, them, another, etc.
  3. Advance:
    1.”:s/[a-z]/\u&/g” – Capitalize all lowercase characters on a line.
    2.”:20,30/pattern/d” – Delete lines in range that contain pattern:
    3.”:g/oldword/s//newword/gc” – This will find all occurrences of oldword and replace them with new word. This is very useful when changing settings(.htaccess, YML files)
    4.Create file “.vimrc” then paste:
    “set smartindent
    set tabstop=4
    set shiftwidth=4
    set expandtab
    set number”

– Tabs are equal to 4 spaces(PSR2 coding standards), tabs are automatic after each line, lines are numbered and indent are also automatic
after functions, conditional statements etc.

So there it is. These are the commands that I usually use everyday as a programmer. Hope you learned something new.

Note: Most users will tell you that

You either love VI or you hate VI, there’s no middle ground.

Upon reading and using the above shortcuts, hopefully its the former.