Saturday, February 09, 2013

Vim: Sorting section titles in a file

Here is vim trick to sort section titles in a file. Inspired from a vim book which I read.

Imagine a input file where the sections needs to be sorted. The content of the section needs to be kept intact.

Section Z
Item1
Item2
SectionEnd
Section A
Item1
Item2
SectionEnd 
Section D
Item1
Item2
SectionEnd
Here is the VIM exscript to do the job:

" Mark lines between each Section/End block
:g/^Section/,/^End/-1s/$/@@/
"  Now join the blocks into one line
:g/^Section/,/^End/j
" Sort each block
:%!sort
" Restore the joined lines to original blocks.
:%s/@@ /^M/g

Output file after sourcing the exscript:

Section A
Item1
Item2
End
Section D
Item1
Item2
End
Section Z
Item1
Item2
End



Sunday, February 03, 2013

Elinks pre_format_html using perl

Elinks is a fantastic text based browser. It also provide HTML re-writing. You can see HTM re-writing as your grease monkey script to update the HTML of the page. Elinks supports HTML re-writing using Lua, Ruby and perl.

To implement HTML re-writing using perl, create a file called hooks.pl under ~/.elinks. You can implement various hooks (see example file or search google for elinks manual and HTML rewriting). I have implemented pre_format_html_hook and here is my code.

Blogger does not allow me to use angular brackets in my code. You need to make following changes to the code:
*Replace LESSTHANSIGN with actual HTML start tag angular bracket.
*Replace GREATERTHANSIGN with actual HTML end tag angular bracket.



sub pre_format_html_hook
{
 my $url = shift;
 my $html = shift;

 if ($url =~ 'google\.com')
 {
        # User .*? to not use greedy pattern matching.
        $html =~ s/LESSTHANSIGNdiv id=.*?gbar.*?\/divGREATERTHANSIGN//;
        $html =~ s/LESSTHANSIGNdiv id=.*?modeselector.*?\/divGREATERTHANSIGN//;
        $html =~ s/LESSTHANSIGNdivGREATERTHANSIGNLESSTHANSIGNh2 class=\"hd\">Search Options.*?\/divGREATERTHANSIGN//;
 }

 return $html;
}