#!/usr/bin/perl
use strict;
use Clipboard;
use IO::All;
my $orig = Clipboard->paste;
my $tmpfile = "/tmp/clipedit$$";
io($tmpfile)->write($orig);
my $ed = $ENV{VISUAL} || $ENV{EDITOR} || 'vim';
system($ed, $tmpfile);
my $edited = io($tmpfile)->all;
my $current = Clipboard->paste;
if ($current ne $orig) {
    local $| = 1;
    boldprint("1) When you started, the Clipboard contained:\n");
    print $orig;
    boldprint("\n2) ...but now the Clipboard contains:\n");
    print $current;
    boldprint("\n3) and you edited to this:\n");
    print $edited;
    boldprint("\nWhich would you like to use? (1, 2, or 3) ");
    my %actions = (
        1 => $orig,
        2 => $current,
        3 => $edited,
    );
    my $answer;
    while (1) {
        $answer = <STDIN>;
        chomp $answer;
        last if exists $actions{$answer};
        my @puzzles = qw(hrm what huh uhh who because sneevle);
        boldprint(ucfirst($puzzles[int rand $#puzzles]) . "? ");
    }
    $edited = $actions{$answer};
}
Clipboard->copy($edited);
print Clipboard->paste, "\n...is now in the Clipboard\n";
unlink($tmpfile) or die "Couldn't remove $tmpfile: $!";

sub boldprint {
    # If you are in a situation where this output is annoying (such as in a
    # DOS console without ANSI parsing, please send a patch.  For now, I'll
    # just do the simplest thing:
    printf "\e[033m%s\e[0m", shift;
}

=head1 NAME

clipedit - Edit clipboard contents in one swoop.

=head1 MOTIVATION

Eliminating the "Open editor, edit stuff, copy back to the clipboard" shuffle.

=head1 NOTE

If for some reason the clipboard contents changes during the edit session, you
will be prompted, so `clipedit` without fear.

=head1 CONFIGURATION

If you don't want the script to use C<vim> to edit, set either the
environment variable C<$VISUAL> or C<$EDITOR>.

=head1 AUTHOR

Ryan King <rking@panoptic.com>

=head1 COPYRIGHT

Copyright (c) 2005.  Ryan King.  All rights reserved.

This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

See L<http://www.perl.com/perl/misc/Artistic.html>
