Colorize Glimpse

From EggeWiki
Jump to navigation Jump to search

Glimpse is a great little search engine that's easy to install on any *nix environment, including Cygwin. I like to use glimpse to search through source code, as I can't seem to find a better tool for the job.

First I created a .glimpse_exclude file with these entries: <geshi lang="bash"> .metadata 'CVS$' 'TAGS$'

~ '.class$' </geshi>

Next, I index my checkout directory

<geshi lang="bash"> glimpseindex.exe -H /cygdrive/c/Temp/glimpseindex /cygdrive/c/dev </geshi>

I created a bash function to invoke glimpse and run my Ruby colorizer

<geshi lang="bash"> function iglimpse() {

 # output the full file path
 if [ "$1" == "-w" ]; then
   options="-w"
   shift;
 else
   options=""
 fi
 glimpse -H /cygdrive/c/Temp/glimpseindex "$@" | ruby ${HOME}/bin/colorglimpse.rb -- $options "$@"

} </geshi>

Lastly, I created a Ruby script to colorize the output from glimpse

<geshi lang="ruby">

  1. !/bin/env ruby
  2. colorizes a glimpse output
  1. We only want to emit color codes if we're outputting to a terminal. If this is getting piped into grep or less, we'll ignore these

green=STDOUT.isatty ? "\e[32m" :"" red=STDOUT.isatty ? "\e[1;31m" :"" normal=STDOUT.isatty ? "\e[0;0m" : ""

wide=false options=nil

  1. process any arguments. These are the same ones passed into glimpse, plus optionally the wide option

while(ARGV[1] =~ /^-(.*)/) do

 case $1 
 when 'w'  
   wide=true 
 when 'i' 
   options = Regexp::IGNORECASE 
 end 
 ARGV.slice!(1) 

end

q=ARGV[1] while $stdin.gets() do

 if $_ =~ /^(.*:) (.*)$/ then  
   if wide then 
     file=$1 
   else 
     # cut off this much of the prefix.  Or you may want to display a fixed amount to the right, like [-30..-1]
     file=$1[29..-1] 
   end 
   match=$2.strip 
   print green + file + normal
   # if glimpse ignored case, then we need to ignore case as well 
   regex=Regexp.new("^(.*?)(#{q})(.*)$", options)
   # We may have more than one match on the line, so highlight each one 
   while(regex.match(match)) 
     print $1 + red + $2 + normal 
     match = $3 
   end 
   puts match 
 else 
   # we should not get here 
   puts "???" 
 end 

end </geshi>