imitatio creatio co we łbie piszczy

28Dec/110

vim as a pager for psql

I asked this question on stackexchange, about a pager with "freeze first line" support.

There was no easy answer, but someone hinted me at Emacs. My Emacs skill is close to zero, so I wanted to check if it's possible in Vim.

And yes it is! Here you are:

First, we need a Vim macro, which will do most of the work, I 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, I 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

Third, I need to override environment variable $PAGER, but only for psql (add this to my ~/.bash_aliases):

if which vimpager &>/dev/null; then
  alias psql='PAGER=vimpager psql';
fi

Fourth, I disabled "\pset pager always" in my ~/.psqlrc file, because I don't need to invoke vim on small listings.

That's all - and it works for me.

PS. There is "vimpager" here, but mine is much simpler and specific to psql query results.

10Dec/08Off

zliczanie błędów w logach postgresa

Kilka razy mi się przydało więc zapisuję...


for distance in {30..0}; do
date=`date +%Y-%m-%d --date "$distance days ago"`;
echo -n "$date ";
bzcat postgresql-$date*.bz2 |grep -wc ERROR;
done

Wersja ze zliczaniem nie tylko ERROR-ów:

for distance in {20..1}; do
date=`date +%Y-%m-%d --date "$distance days ago"`;
echo -n "$date ";
lzcat postgresql-$date*.lzma \
| perl -nle '$s{$1}++ if /\b(PANIC|FATAL|ERROR|WARNING|NOTICE)\b/; END{for(keys%s){$o.="$_:$s{$_};"};print $o}';
done

Tagged as: , No Comments