Tuesday, July 17, 2018

Making code searches easier


When modifying source code I'm not familiar with, it's usually necessary to do some recursive searches to figure out what to change.  You can use a simple recursive grep but I prefer a tool called ack.  You can download ack in one of several forms.  I prefer the all-in-one perl script version.  I prefer ack because it can be configured via .rc (run command) file or command line to limit the searches to files of interest.  You can ignore files with certain extensions or entire directories.  Few things are more disheartening than searching for a term within the code only to find out it appears on many hundreds of lines.  Who feels like wading through hundreds of lines to find what you're actually looking for?
 
I also use the following bash function to pipe ack's output to gvim so I can weed out unwanted matches quickly.  This is handy if the search term is a common word which is also used as a variable or function name.  I delete lines containing any variations which aren't of interest which helps reduce the job to something more manageable.

The ack script may be replaced with a simple recursive grep if you'd like.  You can also use a different editor if you don't care for Vim/Gvim.  You'll just need an editor capable of accepting input from stdin.  The following function also tells gvim to highlight the search term which I find to be a time saver.

function    ackvr    # invoke ack perl script and edits the match
{
    if [ -z "$1" ]; then
        echo "Usage -- ackvr SearchPattern
    else
        echo "ack searching for $1"
        ack "$1" | gvim -c "/$1" -

    fi
}

No comments: