# /script load hilight-better.pl
use Irssi::Irc;
use strict;
use vars qw($VERSION %IRSSI);

$VERSION = '1.02';
%IRSSI = (
	authors         => '',
	contact         => '',
	name            => 'hilight-better',
	description     => 'Highlight your nick mid-sentence without resorting
                        to /hilight',
	license         => 'GPLv3',
	url             => '',
	changed         => 'Thu Dec 6 03:15 EST 2012',
);

sub hilight_nick {
	my ($dest, $text, $stripped) = @_;
	my $server = $dest->{server};
	my $nick = $server->{nick};
	my $color = Irssi::settings_get_str("hilight_color");
	# default attempts to use format message though this is broken
	# by nickcolors if you use nick colours I recommend switching
	# method to msg and doing /set hilight_nick_matches OFF
	my $method = "msg";
	if ($dest->{server} && $dest->{level} &
	(MSGLEVEL_PUBLIC|MSGLEVEL_MSGS|MSGLEVEL_ACTIONS)) {
		# return if you are the source of a msg/public or action
		return if ($stripped =~ /<.$nick>/ || $stripped =~ /\* $nick/);
		if ($text =~ /$nick/i) {
			if ($method eq "default") {
				$server->command('/^format pubmsg '.
				'{pubmsgnick $2 {pubnick '.chr(3).$color.'$0}}$1');
				$dest->{window}->print($text,
				MSGLEVEL_PUBLIC+MSGLEVEL_HILIGHT) if($dest->{window});
				$server->command('/^format -reset pubmsg');
			}
			else {
				$text =~ s/($nick)/$color$1%n%N/gi;
				$dest->{window}->print($text,
				MSGLEVEL_PUBLIC+MSGLEVEL_HILIGHT) if($dest->{window});
			}
			Irssi::signal_stop();
		}
	}
}

# Signals

#printtext.c:
#"print text", TEXT_DEST_REC *dest, char *text, char *stripped
Irssi::signal_add('print text', 'hilight_nick');
