html/grep.pl


   1 # /GREP [-i] [-w] [-v] [-F] <perl-regexp> <command to run>
   2 #
   3 # -i: match case insensitive
   4 # -w: only print matches that form whole words
   5 # -v: Invert the sense of matching, to print non-matching lines.
   6 # -F: match as a fixed string, not a regexp
   7 #
   8 # if you want /FGREP, do: /alias FGREP GREP -F
   9 
  10 use Irssi;
  11 use strict;
  12 use Text::ParseWords;
  13 use vars qw($VERSION %IRSSI); 
  14 $VERSION = "2.1";
  15 %IRSSI = (
  16 	authors	    => "Timo \'cras\' Sirainen, Wouter Coekaerts",
  17 	contact	    => "tss\@iki.fi, wouter\@coekaerts.be", 
  18 	name        => "grep",
  19 	description => "/GREP [-i] [-w] [-v] [-F] <perl-regexp> <command to run>",
  20 	license     => "Public Domain",
  21 	url         => "http://wouter.coekaerts.be/irssi/",
  22 	changed	    => "2008-01-13"
  23 );
  24 
  25 my ($match, $v);
  26 
  27 sub sig_text {
  28 	my ($dest, $text, $stripped_text) = @_;
  29 	Irssi::signal_stop() if (($stripped_text =~ /$match/) == $v);	
  30 }
  31 
  32 sub cmd_grep {
  33 	my ($data,$server,$item) = @_;
  34 	my ($option,$cmd,$i,$w,$F);
  35 	$v = 0;
  36 	$F = 0;
  37   
  38 	# split the arguments, keep quotes
  39 	my (@args)  = &quotewords(' ', 1, $data);
  40 
  41 	# search for options
  42 	while ($args[0] =~ /^-/) {
  43 		$option = shift(@args);
  44 		if ($option eq '-i') {$i = 1;}
  45 		elsif ($option eq '-v') {$v = 1;}
  46 		elsif ($option eq '-w') {$w = 1;}
  47 		elsif ($option eq '-F') {$F = 1;}	
  48 		else {
  49 			Irssi::print("Unknown option: $option",MSGLEVEL_CLIENTERROR);
  50 			return;
  51 		}
  52 	}
  53 
  54 	# match = first argument, but remove quotes
  55 	($match) = &quotewords(' ', 0, shift(@args));
  56 	# cmd = the rest (with quotes)
  57 	$cmd = join(' ',@args);
  58 
  59 	# check if the regexp is valid
  60 	eval("'' =~ /$match/");
  61 	if($@) { # there was an error
  62 		chomp $@;
  63 		Irssi::print($@,MSGLEVEL_CLIENTERROR);
  64 		return;
  65 	}
  66 	
  67 	if ($F) {
  68 		$match =~ s/(\(|\)|\[|\]|\{|\}|\\|\*|\.|\?|\|)/\\$1/g;
  69 	}
  70 	if ($w) {
  71 		$match = '\b' . $match . '\b';
  72 	}
  73 	if ($i) {
  74 		$match = '(?i)' . $match;
  75 	}
  76 
  77 	Irssi::signal_add_first('print text', 'sig_text');
  78 	Irssi::signal_emit('send command', $cmd, $server, $item);
  79 	Irssi::signal_remove('print text', 'sig_text');
  80 }
  81 
  82 Irssi::command_bind('grep', 'cmd_grep');