A VIM Script to Insert the Current Line Number

July 28, 2004 in General | Comments (0)

Sometimes scripting stuff really aggravates me. You can do so much with a scriptable tool, but sometimes the effort required to figure out how to simplify some mundane task is almost too great for the benefit derived. Coercing VIM into inserting the current line number into a file turned out to be that kind of headache. In fact, I’m publishing it here slightly unfinished because I just can’t take the time to dig for the rest, and it works “good enough” for right now.

All I wanted to be able to do was insert the current line number into the text of my script as I typed. This is because I am using Flash ActionScript, and Flash is so incredibly braindead and hard to debug that I have to resort to print statements to find out what’s going on in my program (see my previous rants about Flash and their form components before you post any instructions on using their useless debugger). It’s easier to figure out exactly where a message came from if you stick a number in there, so I figured a line number would get me pretty close to something unique. I realize that they become inaccurate over time, but for this rough sort of debugging beggars can’t be choosers.

To cut to the chase, here is the script:

imap ;; ^[:call InsertLineNumber()<CR>
function! InsertLineNumber()
let linenumber = line(".")
execute "normal a \<BS>".linenumber
endfunction

The first line maps a function named InsertLineNumber to the key combination ;;. The following lines declare that function. Drop this into your .vimrc file, then when you type ;;, VIM will insert the current line number into your buffer.

The only problem is that it doesn’t put you back into insert mode after it puts the number in, so you need to type a to keep going, but that’s not too big a hassle. One of these days I’ll figure out how to add that to the end.

I just posted it here because I couldn’t find crap about how to do this by searching on the web, at least nothing that was particularly straightforward.

Part of the problem is the unfortunate execute command. This is a very cumbersome way to insert text into the buffer. While they have functions for replacing lines and such, you would think that a nice printf derivative wouldn’t have been too hard, something to just insert text at the current cursor position, but there’s no such animal. Again, though, this is close enough, and it meets my needs for the moment. If you know a better way to write it, I’m all ears.

Note that the construct ^[ is created by typing ctr-V, then Esc in VIM. You can also use \<ESC> if you prefer (like the backspace key in the example).


Comments are closed.