#!/usr/bin/perl

=pod

=head1 NAME

wide.pl - print double-width characters

=head1 SYNOPSIS

=head2 From the shell:

wide.pl <[args ...]>

=head2 From within irssi:

/script load wide.pl

/wide [args]

=head1 DESCRIPTION

wide.pl converts printable ASCII characters to their double-width
equivalent from the Unicode 0xff block. See:

https://en.wikipedia.org/wiki/Halfwidth_and_Fullwidth_Forms_(Unicode_block)

Characters that don't have double-wide equivalents are simply printed
with a trailing space.

This script can be run standalone or as an irssi /script. For things to work
properly in irssi, you'll need UTF-8 and Unicode support in irssi and in the
terminal you're using to run irssi.

When run standalone with no arguments, reads from stdin and writes to stdout.
If arguments are given, they're treated as input (not filenames). Use shell
redirection to read from a file: wide.pl < message.txt

=head1 AUTHOR

Urchlay <urchlay@slackware.uk>

=head1 LICENSE

wide.pl is released under the WTFPL: Do WTF you want with this.

=cut

use warnings;
use strict;

sub wide {
	my $text = shift;
	my $res = "";

	for (split "", $text) {
		my $c = ord($_);
		if($c >= 0x21 && $c <= 0x7e) {
			$res .= chr($c + 0xfee0);
		} else {
			$res .= "$_$_";
		}
	}

	return $res;
}

# main() if we're not running under irssi
if(__PACKAGE__ eq 'main') {
	no warnings 'utf8';

	exec "perldoc $0" if @ARGV && $ARGV[0] =~ /--?h(elp)?/;

	if(@ARGV) {
		print wide($_) for @ARGV;
		print "\n";
	} else {
		while(<>) {
			chomp;
			print wide($_);
			print "\n";
		}
	}

	exit 0;
}

# irssi stuff here
require Irssi;
Irssi->import(qw/command command_bind/);

our $VERSION = "0.1";
our %IRSSI = (
		authors     => 'Urchlay',
		contact     => 'Urchlay on FreeNode',
		name        => 'wide',
		description => 'print double-width characters',
		license     => 'WTFPL',
		url         => 'none',
		);

sub cmd_wide {
	my ($text, $srv, $chan) = @_;

	return unless $text;
	return unless $srv;
	return unless $chan;

	$chan->command('MSG ' . $chan->{name} . ' ' . wide($text));
}

command_bind("wide", \&cmd_wide);
