Haui's bytes

news, diary, journal, whatever

Vim tips

Almost 4PM...time for some vim tips. :-)

  • autocmd Vim’s powerful autocmd feature can be used to automatically perform certain commands when a specific event occurs. The events that can be used as triggers range from creating a new file to resizing vim’s window. A complete list of available triggers can be obtained by typing :help autocmd-events in vim. So, how’s this useful? Let’s say you write most of your Perl scripts in vim, why should you insert the shebang and some other stuff manually in a new file, when the editor can do this for you? The following two steps show you how it’s done:

    1. Create a new file ~/.vim/skeletons/skeleton.pl containing a shebang for Perl as well as the recommended use strict/warnings statements:

      p=$(which perl); mkdir -p ~/.vim/skeletons; cat << EOF > ~/.vim/skeletons/skeleton.pl
      #!$p
      use strict;
      use warnings;
      EOF
      
    2. Put the following in your ~/.vimrc

      autocmd BufNewFile *.pl 0r ~/.vim/skeletons/skeleton.pl | :normal G
      

    Now, when you’re creating a new *.pl-file it is automatically prepended with the contents of ~/.vim/skeletons/skeleton.pl and vim starts at the end of the file. Needless to say, that you can use multiple autocmd commands to support languages other than Perl.

  • Syntax check Everyone knows about vim’s :make command, but did you know that it’s possible to set the make program for each file type separately?

    autocmd FileType perl set makeprg=perl\ -c\ %\ $*
    

    By adding this to your ~/.vimrc, :make will no longer invoke make file but perl -c file instead, when you’re editing a Perl script. As usual, Perl is just an example - i.e. Ruby programmers might use ruby -c or the like.

  • Y? There’s some inconsistency between deleting and yanking in vim: dd deletes the current line, D deletes from the cursor to the end of the line. yy yanks the current line, but Y also yanks the current line... To yank all characters from the cursor position to the end of the line, you either need to type y$, or add a custom mapping for Y to your ~/.vimrc:

    map Y y$
  • Matchit Typing % in normal mode finds the next item in the current line or under the cursor and jumps to its match. Items include c-style comments, parenthesis and some preprocessor statements. Unfortunately, there’s no native support for HTML or Latex, but there’s a handy little plugin, that adds support for these and many other languages: Matchit.

Enough for one day....