# Reformat pasted text ready to paste onto channels.

use Irssi;
use Irssi::Irc;
use Text::Wrap;
use Text::Tabs;
use POSIX qw(strftime);
use strict;

=pod

=head1 paste.pl

B<paste.pl> - a script for irssi to manage reformatting before pasting to channels

To stop people pasting from webpages with very poor formatting this script
allows you to reformat as you paste.

=head1 USAGE

Load the script then create a new unused window and paste your text into it.
The defaults should be reasonable so then B</paste> will paste it.

Try altering I<paste_width> (0 is the autoformatted default based on your
nick length) to affect the width of the pasted text.

Alter I<paste_prefix> to change the prefix added to each line (B</set -clear
paste_prefix> to remove it altogether).

=head1 VERSION

Version 0.0.2,  Wed, 12 Sep 2001 00:17:49 +0100

=head1 AUTHOR

Send suggestions to Simon Huggins <huggie@earth.li>

=cut

Irssi::settings_add_int("misc","paste_width",0);
Irssi::settings_add_str("misc","paste_prefix",">> ");

{
	my $buffer;
	my $last_ts;

sub event_send_text {
	my ($line, $server, $windowitem) = @_;

	return if $windowitem;

	if ($last_ts < (time() - 60)) {
		$buffer = "";
	}
	$line =~ s/^\s+/ /;
	$line =~ s/\s+$/ /;
	$buffer .= $line;
	$last_ts = time();

	Irssi::signal_stop();
}

sub paste {
	my ($data, $server, $witem) = @_;

	my $offset;

	if (!$buffer or $buffer eq "") {
		Irssi::print("No buffer to paste!",MSGLEVEL_CLIENTERROR);
		return;
	}

	my $anyoldwin = Irssi::active_win();
	my $width = Irssi::settings_get_int("paste_width");
	my $prefix = Irssi::settings_get_str("paste_prefix");
	my $prefixlen = length($prefix);
	if ($width > 0) {
		if ($width < 3+$prefixlen) {
			Irssi::print("paste_width is too small ($width<".
					(3+$prefixlen).")!",
					MSGLEVEL_CLIENTERROR);
			return;
		}
		$Text::Wrap::columns = $width;
	} else {
		if ($server->{nick}) {
			$offset+=length($server->{nick})+$prefixlen+15;
		}
		$Text::Wrap::columns = $anyoldwin->{'width'} - $offset;
		if ($Text::Wrap::columns < 3+$prefixlen) {
			Irssi::print("Width would be too small (".
					$Text::Wrap::columns."<".
					(3+$prefixlen).", window width was ".
					$anyoldwin->{'width'}.
					")!",
					MSGLEVEL_CLIENTERROR);
			return;
		}
	}

	my $outbuffer = $buffer;
	$outbuffer =~ s/^\s*//;
	$outbuffer =~ s/\s*$//;
	$outbuffer = wrap("","", $outbuffer);
	$outbuffer = expand($outbuffer);

	if ($witem) {
		foreach (split '\n', $outbuffer) {
			$witem->command("/ ".$prefix.$_);
		}
	} else {
		foreach (split '\n', $outbuffer) {
			$anyoldwin->print($prefix.$_, MSGLEVEL_CLIENTCRAP);
		}
	}
}

sub clear_buffer {
	$buffer = "";
}

}

Irssi::signal_add_first("send text", "event_send_text");
Irssi::command_bind("paste", "paste");
Irssi::command_bind("clear_buffer", "clear_buffer");

