summaryrefslogtreecommitdiffstats
path: root/lib/Reply/Plugin/Editor.pm
blob: 5032a7dc79c6d63d4704f5c9a0c76fe213babf3e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package Reply::Plugin::Editor;
use strict;
use warnings;
# ABSTRACT: command to edit the current line in a text editor

use base 'Reply::Plugin';

use File::HomeDir;
use File::Spec;
use Proc::InvokeEditor;

=head1 SYNOPSIS

  ; .replyrc
  [Editor]
  editor = emacs

=head1 DESCRIPTION

This plugin provides the C<#e> command. It will launch your editor, and allow
you to edit bits of code in your editor, which will then be evaluated all at
once. The text you entered will be saved, and restored the next time you enter
the command. Alternatively, you can pass a filename to the C<#e> command, and
the contents of that file will be preloaded instead.

The C<editor> option can be specified to provide a different editor to use,
otherwise it will use the value of C<$ENV{VISUAL}> or C<$ENV{EDITOR}>.

=cut

sub new {
    my $class = shift;
    my %opts = @_;

    my $self = $class->SUPER::new(@_);
    $self->{editor} = Proc::InvokeEditor->new(
        (defined $opts{editor}
            ? (editors => [ $opts{editor} ])
            : ())
    );
    $self->{current_text} = '';

    return $self;
}

sub command_e {
    my $self = shift;
    my ($line) = @_;

    my $text;
    if (length $line) {
        if ($line =~ s+^~/++) {
            $line = File::Spec->catfile(File::HomeDir->my_home, $line);
        }
        elsif ($line =~ s+^~([^/]*)/++) {
            $line = File::Spec->catfile(File::HomeDir->users_home($1), $line);
        }

        my $current_text = do {
            local $/;
            if (open my $fh, '<', $line) {
                <$fh>;
            }
            else {
                warn "Couldn't open $line: $!";
                return '';
            }
        };
        $text = $self->{editor}->edit($current_text, '.pl');
    }
    else {
        $text = $self->{editor}->edit($self->{current_text}, '.pl');
        $self->{current_text} = $text;
    }

    return $text;
}

=for Pod::Coverage
  command_e

=cut

1;