Vim Tips Wiki
Register
Advertisement
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
Tip 1141 Printable Monobook Previous Next

created 2006 · complexity intermediate · author Yakov Lerner · version 6.0


This command (PP) prints lines (like :p or :#) with the 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 the optional argument # (PP #) then line numbers are also printed.

" 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 |
        echon strpart(l,index)
        break
      endif
      let e=matchend(l,@/,index) |
      echon strpart(l,index,b-index)
      echohl Search
      echon strpart(l,b,e-b)
      echohl None
      let index = e
    endw
    let line=line+1
  endw
endfunction

Comments

Just a small issue, it chokes on:

:g/^/PP

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 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

...
 let e=matchend(l,@/,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)


and this:

- echon strpart(l." ",b,e-b)
+ echon strpart(l." ",b,e-b)

will display '$' correctly too.


Advertisement