#!/usr/bin/perl
#
# Created by Stefan "tommie" Tomanek [stefan@kann-nix.org]
# to free the world from  the evil inverted I
#
# 23.02.2002
# *First release
#
# 01.03.2002
# *Changed to GPL
#
# 15.07.2002
# Added proper tab expansion

use strict;
use vars qw($VERSION %IRSSI);
# signal_continue
use Irssi 20020427.2153;

$VERSION = "20021231";
%IRSSI = (
    authors     => "Stefan 'tommie' Tomanek, David Leadbeater",
    contact     => "stefan\@pico.ruhr.de, dgl\@dgl.cx",
    name        => "tab_stop",
    description => "This script replaces the evil inverted 'I' with a configurable number of whitespaces ",
    license     => "GPLv2",
    url         => "",
    changed     => "$VERSION",
);

my($replacement, $spacing);

sub event_server_incoming {
    if ($_[1] =~ /\t/) {
        Irssi::signal_continue($_[0], replace_tabs($_[1]));
    }
}

sub replace_tabs {
    my ($text) = @_;

    # this only works properly on the last parameter of a command
    # but generally that's where you care about tabs anyway
    my $startpos = 2 + index $text, ' :';
    
    my $correction = 0;
    $text =~ s/\t/
        my $x = $spacing - (pos($text) + $correction - $startpos) % $spacing;
        $correction += $x - 1;
        $replacement x $x;
     /eg;
    return($text);
}

sub set_replacement {
    # don't break with custom settings from old versions
    $replacement = substr Irssi::settings_get_str('tabstop_replacement'), 0, 1;
    $replacement = ' ' if $replacement =~ /\t/; # user setting mad option
    $spacing = Irssi::settings_get_int('tabstop_spacing');
}

Irssi::signal_add_first('server incoming', 'event_server_incoming');
Irssi::signal_add('setup changed', 'set_replacement');

Irssi::settings_add_str('misc', 'tabstop_replacement', " ");
Irssi::settings_add_int('misc', 'tabstop_spacing', 4);

set_replacement();

