Wednesday, September 2, 2009

Vim Tip: Debug Path

I work for a company whose code is in thousands of files in hundreds of directories. We have multiple VCS repositories. Function libraries, class files, HTML, XSL--a convoluted maze to navigate, especially when trying to debug something.

Whenever I'm debugging, I may follow the rabbit hole from function to function, through various libraries and classes, only to find that I'd taken a wrong turn somewhere and come to a dead end. I then either have to sift through the multiple tabs I've opened to find where I should pick up the search again, or, if I've been closing files along the way, I have to start the search from the beginning. This is annoying and time-consuming.

I decided to write a simple vim script to save my cursor's current line, along with the file name and line number, to a file in my home directory. I can then continually save lines as I follow a path through the code. If, at any time, I hit a dead end, I simply go through this "trace" file and find where to pick up the search again. Combined with vim's "gf" command, this file is very useful!

Here's the code you can add to your own .vimrc file:

nmap <F8> <ESC>:call WriteTrace()<CR>

function WriteTrace()
let lineNum = line('.')
let lineFile = bufname('%')
let lineVal = getline(lineNum)

let allLines = readfile("$HOME/trace.txt")
let allLines = add(allLines,lineFile.":".lineNum)
let allLines = add(allLines,lineVal)
let allLines = add(allLines,"")

call writefile(allLines,"$HOME/trace.txt")
endfunction

In the code above, F8 will save the line under the cursor, but the nmap can be changed to map to any key, of course.

No comments: