Vi editor

A collection of vi/vim tips and tricks.

  • Some useful links
  • Code cleanup actions
    • Delete spaces before tabs
      :%s/ \+\t/\t/gc
    • Delete whitespace (spaces and tabs) at end-of-line
      :%s/[ \t]\+$//g
    • Replace C++ style comments with C-style comments
      :%s/\/\/\(.*\)/\/*\1 *\//gc
  • Search & replace examples
    • To replace
      #ifdef LED_TRACE_ON
      	printf("blaat");
      #endif

      with
      LED_TRACE("blaat");

      :%s/#ifdef LED_TRACE_ON\n\(\t\+\)printf(\(.\+\));\n#endif/\1LED_TRACE(\2);/gc

  • Case sensitive/insensitive search & replace
    By default, vim does case-sensitive searches. This can be modified globally with
    :set ignorecase (or :set ic)
    :set noignorecase (or :set noic)

    However, it is also possible to force a certain search or search&replace command to be case-sensitive or case-insensitive (regardless of the global setting), by placing the switch \c (case-insensitive) or \C (case-sensitive) anywhere in the search pattern. For example:

    /needle (use global setting)
    /needle\c (case-insensitive)
    /\cneedle (case-insensitive)
    /nee\cdle (case-insensitive)
    /needle\C (case-sensitive)

    :%s/nEEdle\c/NeeDLE/g (replaces needle, Needle and nEEdle with NeeDLE)
    :%s/nEEdle\C/NeeDLE/g (replaces only nEEdle with NeeDLE)

    See :help ignorecase for more information.

  • Batch search & replace from shell
    for i in `find . -name '*.txt'`; do
    	vim -c "%s/findpattern/replacepattern/g | w | q" "$i";
    done

    Note: this type of commands should better be carried out with the sed command

  • Backspace key does not behave as it should
    On one system, pressing the backspace key showed '^?' on the screen instead of actually performing backspace. I had to press Ctrl-H to use backspace.
    This can be fixed by adding the following lines to your .vimrc:
    inoremap ^? ^H
    :fixdel
    :set backspace=indent,eol,start

    Note that ^ should not be entered literally, but using the Ctrl-V key. For ^? this didn't work, so I used the following to enter these codes:
    inoremap 'backspace' Ctrl-V Ctrl-h

  • Visual selection
    • Character selection: v
    • Line selection: SHIFT-v
    • Vertical block/array selection: CTRL-v