Command Line – Pager Program Like Less to Repeat Top N Lines

command linelesspager

Is there any way to make less program repeat first line (or first 2 lines) on every displayed page?

Is there any other pager program which can do this?

This would be a killer-app for database table browsing, think mysql or psql or gqlplus

See the screenshot in the bottom of this page. I want to repeat header line + horizontal ascii bar.

Best Answer

There is a solution using Vim.

First, you need a Vim macro, which will do most of the work. Save it in ~/.vim/plugin/less.vim:

" :Less
" turn vim into a pager for psql aligned results 
fun! Less()
  set nocompatible
  set nowrap
  set scrollopt=hor
  set scrollbind
  set number
  execute 'above split'
  " resize upper window to one line; two lines are not needed because vim adds separating line
  execute 'resize 1'
  " switch to lower window and scroll 2 lines down 
  wincmd j
  execute 'norm! 2^E'
  " hide statusline in lower window
  set laststatus=0
  " hide contents of upper statusline. editor note: do not remove trailing spaces in next line!
  set statusline=\  
  " arrows do scrolling instead of moving
  nmap ^[OC zL
  nmap ^[OB ^E
  nmap ^[OD zH
  nmap ^[OA ^Y
  nmap <Space> <PageDown>
  " faster quit (I tend to forget about the upper panel)
  nmap q :qa^M
  nmap Q :qa^M
endfun
command! -nargs=0 Less call Less()

Second, to emulate a pager, you need to invoke vim so that it will:

  • read standard input
  • but if argument is given on command line, read whatever comes there
  • work in read-only mode
  • skip all init scripts, but instead execute Less macro defined above

I put this together as helper script in ~/bin/vimpager:

#!/bin/bash
what=-
test "$@" && what="$@"
exec vim -u NONE -R -S ~/.vim/plugin/less.vim -c Less $what

Make the script executable with chmod +x ~/bin/vimpager.

Third, you need to override pager program for psql. Do not set variable PAGER globally, as it can affect other programs, not only psql. Instead, add this to your ~/.psqlrc file:

\setenv PAGER ~/bin/vimpager

Voila! After reloading your profile, you can enjoy the result, which should behave as expected (arrow keys browse both vertically and horizontally) and look like this: vimpager in action. Plus, all the power of Vim is right there if you need it.

Related Question