summaryrefslogtreecommitdiffstats
path: root/lib/Reply/Plugin/Editor.pm
blob: 8f980cd018e307188d21ae87f974c5db32e782cc (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
package main;
use strict;
use warnings;
# ABSTRACT: command to edit the current line in a text editor

use mop;

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

class Reply::Plugin::Editor extends Reply::Plugin {
    has $editor;
    has $current_text = '';

    submethod BUILD ($opts) {
        $editor = Proc::InvokeEditor->new(
            (defined $opts->{editor}
                ? (editors => [ $opts->{editor} ])
                : ())
        );
    }

    method command_e ($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 = $editor->edit($current_text, '.pl');
        }
        else {
            $text = $editor->edit($current_text, '.pl');
            $current_text = $text;
        }

        return $text;
    }
}

=for Pod::Coverage
  command_e

=cut

1;