aboutsummaryrefslogtreecommitdiff
path: root/perl/readline.pm
blob: 149c3fb1d8de84c7f71bc9260f925f42355fa9ef (plain)
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
# To get readline line editing functionality, please install
# Term::ReadKey and either Term::ReadLine::Gnu (GPL) or
# Term::ReadLine::Perl (GPL, Artistic) from CPAN.

package readline;
use strict;
use warnings;
use Exporter 'import';
our @EXPORT_OK = qw( mal_readline set_rl_mode );

use Term::ReadLine;

my $_rl = Term::ReadLine->new('Mal');
$_rl->ornaments(0);
#print "Using ReadLine implementation: " . $_rl->ReadLine() . "\n";
my $OUT = $_rl->OUT || \*STDOUT;
my $_history_loaded = 0;

my $history_file = $ENV{"HOME"} . "/.mal-history";

sub save_line {
    my ($line) = @_;
    open(my $fh, '>>', $history_file) or return;
    say $fh $line;
    close $fh;
}

sub load_history {
    open my $fh, $history_file or return;

    while(my $line = <$fh>)  {   
        chomp $line;
        $_rl->addhistory($line) if $line =~ /\S/;
    }

    close $fh;
}

my $rl_mode = "terminal";

sub set_rl_mode {
    my($mode) = @_;
    $rl_mode = $mode;
}

sub mal_readline {
    my($prompt) = @_;
    my $line = undef;
    if (! $_history_loaded) {
        $_history_loaded = 1;
        load_history();
    }

    if ($rl_mode eq "terminal") {
        if (defined ($line = $_rl->readline($prompt))) {
            save_line($line);
            chomp $line;
            return $line;
        } else {
            return undef;
        }
    } else {
        print "$prompt";
        if (defined ($line = readline(*STDIN))) {
            save_line($line);
            chomp($line);
            return $line;
        } else {
            return undef;
        }
    }
}
1;