1use strict;
2use vars qw($VERSION %IRSSI);
3
4$VERSION = '1.3';
5
6%IRSSI = (
7    authors     => 'Tijmen "timing" Ruizendaal & Wilmer van der Gaast',
8    contact     => 'tijmen.ruizendaal@gmail.com',
9    name        => 'BitlBee_tab_completion',
10    description => 'Intelligent Tab-completion for BitlBee commands.',
11    license     => 'GPLv2',
12    url         => 'http://the-timing.nl/stuff/irssi-bitlbee',
13    changed     => '2009-08-11',
14);
15
16my $root_nick = 'root';
17my $bitlbee_channel = '&bitlbee';
18my $bitlbee_server_tag = 'localhost';
19my $get_completions = 0;
20
21my @commands;
22
23Irssi::signal_add_last 'channel sync' => sub {
24        my( $channel ) = @_;
25        if( $channel->{topic} eq "Welcome to the control channel. Type \x02help\x02 for help information." ){
26                $bitlbee_server_tag = $channel->{server}->{tag};
27                $bitlbee_channel = $channel->{name};
28		request_completions();
29        }
30};
31
32if (get_channel()) {
33	request_completions();
34}
35
36sub request_completions {
37	$get_completions = 1;
38	Irssi::server_find_tag($bitlbee_server_tag)->send_raw( 'COMPLETIONS' );
39}
40
41sub get_channel {
42        my @channels = Irssi::channels();
43        foreach my $channel(@channels) {
44                if ($channel->{topic} eq "Welcome to the control channel. Type \x02help\x02 for help information.") {
45                        $bitlbee_channel = $channel->{name};
46                        $bitlbee_server_tag = $channel->{server}->{tag};
47			return 1;
48                }
49        }
50	return 0;
51}
52
53sub irc_notice {
54	return unless $get_completions;
55	my( $server, $msg, $from, $address, $target ) = @_;
56
57	if( $msg =~ s/^COMPLETIONS // )	{
58		$root_nick = $from;
59		if( $msg eq 'OK' ) {
60			@commands = ();
61		}
62		elsif( $msg eq 'END' ) {
63			$get_completions = 0;
64		}
65		@commands = ( @commands, $msg );
66
67		Irssi::signal_stop();
68	}
69}
70
71sub complete_word {
72	my ($complist, $window, $word, $linestart, $want_space) = @_;
73	my $channel = $window->get_active_name();
74	if ($channel eq $bitlbee_channel or $channel eq $root_nick or $linestart =~ /^\/(msg|query) \Q$root_nick\E */i){
75		$linestart =~ s/^\/(msg|query) \Q$root_nick\E *//i;
76		$linestart =~ s/^\Q$root_nick\E[:,] *//i;
77		foreach my $command(@commands) {
78			if ($command =~ /^$word/i) {
79				push @$complist, $command;
80		    	}
81		}
82	}
83}
84
85
86Irssi::signal_add_last('complete word', 'complete_word');
87Irssi::signal_add_first('message irc notice', 'irc_notice');
88
89