Fun with Vim


I use the Vim text editor all the time.  In an effort to try to post more here, I think I’ll put up snippets of my Vim usage now and then.

So I was simply trying to layout a line of text in my progress notebook. Its a text file I keep all my work in and edit with Vim. I do this for many reasons, but most of all because searching is so easy, and its simple to style (with syntax highlighting) and to program.

I had a line of text to separate sections of the notebook:

<<<<<<<<<<<<<<<<<<<<<<[ 2008-04-25 Apr.Fri 11:24 ]>>>

Okay, once you’ve stopped admiring^H^H^H^H^H^H^H^H laughing at my superior documentation formatting skills, you can read more. I just wanted to move the date portion around to see which way I liked it best. I used these some mappings to make it so that the left and right arrow keys would move the bracketed text left and right, leaving at least one of the leading and trailing characters. There’s a bunch of junk in there to maintain the search history and search highlighting option, so I moved that part to two commands:

:command! A :let _save_hls=&hls |:let &hls=0
:command! B :call histdel("/",-1) |:let @/=histget("/",-1) |:let &hls=_save_hls

:map <silent> <left>  :A<CR>:s/\v^(.)(\1+)(\[.*)(.)$/\2\3\4\4/e<CR>:B<CR>
:map <silent> <right> :A<CR>:s/\v^(.)(.*\])(.)(\3+)$/\1\1\2\4/e<CR>:B<CR>

An even better approach would be to search for the pattern you want to move around, and have the mapping use that.

" setup leading and trailing characters
let @a='<'
let @b='>'

" here's what I want to move. @/ is the search pattern register
let @/='\[ \d\{4}-\d\{2}-\d\{2} \S\+ \S\+ \]'

" here's the search pattern for moving it
let @s= '^\(' . @a .'\=\)\(\1*\)\(' . @/ .'\)\('. @b .'\=\)\(\4*\)$'

" now the mappings for left and right arrow keys:
map <silent> <left>  :exe ':s/'. @s .'/'. '\2\3\4\5'. @b .'/'<CR>
map <silent> <right> :exe ':s/'. @s .'/'. @a  .'\1\2\3\5'.'/'<CR>

That was fun!