Vim Tips Wiki
Advertisement

Previous TipNext Tip

Tip: #1141 - List lines with current search pattern highlighted

Created: February 20, 2006 1:14 Complexity: intermediate Author: Yakov Lerner Version: 6.0 Karma: 10/4 Imported from: Tip#1141

This command (PP) prints lines (like :p or :#) with search pattern highlighted. I use g//p

quite often, and I was missing the highlighting of search pattern. To test this command, try

something like:

:g/a/PP 

If you supply optional argument # (PP #) then line numbers are also printed a-la :#


"-------------------------------------------------------------------------------------------------

" command PP: print lines like :p or :# but with with current search pattern highlighted

command! -nargs=? -range -bar PP :call PrintWithSearchHighlighted(<line1>,<line2>,<q-args>)

function! PrintWithSearchHighlighted(line1,line2,arg)

let line=a:line1 
while line <= a:line2 
echo "" 
if a:arg =~ "#" 
echohl LineNr 
echo strpart(" ",0,7-strlen(line)).line."\t" 
echohl None 
endif 
let l=getline(line) 
let index=0 
while 1 
let b=match(l,@/,index) 
if b==-1

Comments

Good idea, Yakov. Just a small issue, it chokes on:

g/^/PP

Gerald Lai , February 23, 2006 18:50


A small addition:

nmap [I :execute 'SS g/\<' . expand( '<cword>' ) . '\>/PP #'<CR>

Changes the behaviour of the internal [I to highlight the text now.

I noticed that it breaks on ^ and $ (if they're alone), also, but that doesn't really happen that often -- I don't think I've ever searched for ^ or $ -- that's just like looking at the main edit window, to me, cuz it returns every line :)

salmanhalim--AT--hotmail.com , February 25, 2006 12:21


I think you meant (without SS) :) nmap [I :execute 'g/\<' . expand( '<cword>' ) . '\>/PP #'<CR>

Yes, [I with highlighting is a great idea. Now the only thing lacking is the jump numbers at the start of each line that are right-aligned.

About choking on ^ and $ anchors, it actually poses minor practical problems. Searching for ^ or $ alone is useful to indicate the whole line. In the case for ranges:

"print lines 3 to 34, including empty lines

3,34g/^/p

"how would we do this without using ^ or $?

3,34g/\_./PP

"is almost the same but not quite (at EOF)

Anything that can possibly evaluate to matching nothing but anchors ^ or $ or void will choke it too. But these aren't practical:

g/^\s*\(function\)\=/PP

"number

g/^\s*\d\{,4}/PP

"trailing spaces

g/\s*$/PP

"dash line

g/-*/PP

Gerald Lai , February 25, 2006 15:14


...

let e=matchend(l,--AT--/,index) 

+ if e == b + let e = e+1 + endif ...

should solve problem with zero length regexps - they are displayed as in vim - next character is highlighted. (there is still another problem with match function - so '^', '\<' aren't matched correctly)

Marian Csontos , March 2, 2006 3:50


and this: - echon strpart(l." ",b,e-b) + echon strpart(l." ",b,e-b) will display '$' correctly too

M.C. , March 2, 2006 3:53


Advertisement