Friday, November 04, 2005

Vim - highlight and capitalize SQL words

As many programmers I use VIM as editor because I think it's the best. You can customize it to the extreme, and get it to do simply whatever you need or want. A way to extend its capabilities is using scripts: in the main site (www.vim.org) you can find a large collection of scripts with relative descriptions.

These days I'm designing a simple database schema, and I'm using vim to write it. So I wanted to search for a script that beautify and simplify me the result script by capitalizing sql (in my case, PostgreSQL) keywords.

First I found the syntax highlight schema for PostgreSQL, because this great open source dmbs extends the standard SQL syntax with some own keywords and constructs, and the standard vim sql hightlight don't parse them. You can download it at this location:

http://www.vim.org/scripts/script.php?script_id=952

After downloading it, you should copy the script (psql.vim) under your syntax files location, /usr/share/vim/vim63/syntax for my linux box, then add these lines to your filetype.vim file, I found it in the path /usr/share/vim/vim63/filetype.vim (or create a personal filetype.vim file under $HOME/.vim/ directory, the same is possible even for the syntax file):


" PostgreSQL
au BufNewFile,BufRead *.psql          setf psql


The highlight section is done :) Let's go for keywords capitalization.

The script I used is stored here: http://www.vim.org/scripts/script.php?script_id=305

after downloading it, I copied under my $HOME/.vim/plugin/ directory. All ok, but it capitalizes some (frequent) words even in non-sql files! If I'm using vim to write a plain text file I don't want it to make words like "in" to "IN" automatically. How to fix this ?

I moved the script from the .vim/plugin/ directory to .vim/other/ (just created), and added this line to filetype.vim (system wide or personal as described above):


if exists("did_load_filetypes")
    finish
endif
augroup filetypedetect
    au! BufRead,BufNewFile *.psql *.sql          source /home/stc/.vim/other/sql_iabbr.vim
augroup END


Now only in case the file has a .psql or .sql extension the script is loaded! Exactly what I wanted.. great. Many thanks to:

Devdas Bhagat for psql.vim
Hari Krishna Dara for sql_iabbr.vim