App-AnteREPL
view release on metacpan or search on metacpan
lib/App/AnteREPL.pm view on Meta::CPAN
use 5.016;
use strict;
use warnings;
package App::AnteREPL;
use Data::Dumper ();
use Encode qw(decode encode FB_CROAK);
use File::Basename qw(dirname);
use File::Spec ();
use File::Temp ();
use Text::Balanced qw(extract_quotelike);
use Text::ParseWords qw(shellwords);
use App::AnteREPL::Shorthand ();
our $VERSION = '0.01';
our $PROGRAM_VERSION = '0.1';
our $FAREWELL = 'Thank, we hope something good happens to you today!';
my $next_workspace = 0;
my $max_line = 999_999_999;
# Exact, uppercase shortcuts only. V groups environment-variable operations.
my %short_commands = (
A => 'AUTO', A0 => 'AUTO OFF', A1 => 'AUTO ECHO ON', A2 => 'AUTO ECHO OFF',
C => 'CLS', C1 => 'CD', D => 'DUMP', D1 => 'DEL',
E => 'EVAL', E1 => 'EDIT', E2 => 'EXPORT', F => 'FUNCTIONS', H => 'HELP',
I => 'IMPORT', L => 'LIST', L1 => 'LOAD', L2 => 'LIST SLOW', L3 => 'LIST PAUSE',
N => 'NEW', P => 'PEEK', Q => 'QUIT',
R => 'RUN', R1 => 'RENUM', R2 => 'RESET', R3 => 'RECOVER',
S => 'SAVE', S1 => 'STATUS', U => 'UNDO',
V => 'ENV', V0 => 'ENV RESET', V1 => 'ENV SET', V2 => 'ENV UNSET',
V3 => 'ENV EDIT', V4 => 'ENV SAVE', V5 => 'ENV LOAD', V6 => 'ENV RELOAD',
);
my %guarded_shortcuts = map { $_ => 1 } qw(C D1 E1 E2 I L1 N Q R1 R2 R3 S U V V0 V1 V2 V3 V4 V5 V6);
sub _expand_short_command {
my ($source) = @_;
return $source unless $source =~ /\A(\s*)([A-Z][0-9]*)(!?)(?=\s|\z)/;
my ($leading, $short, $force, $end) = ($1, $2, $3, $+[0]);
return $source unless exists $short_commands{$short};
my ($command, $option) = split / /, $short_commands{$short}, 2;
my $tail = substr($source, $end);
# LIST's mode follows its optional range; other fixed options precede args.
return "$leading$command$force$tail $option" if $short eq 'L2' || $short eq 'L3';
return "$leading$command$force" . (defined $option ? " $option" : '') . $tail;
}
sub new {
my ($class) = @_;
return bless {
lines => {},
saved => '',
filename => undef,
undo => [],
workspace => 'App::AnteREPL::Workspace::S' . ++$next_workspace,
format => 'native',
initial_env => { %ENV },
}, $class;
}
sub _confirmation_answer {
my ($self, $description, $forced) = @_;
die "Confirmation required: $description. Try $forced to proceed without a prompt.\n"
unless $self->{interactive};
local $SIG{INT} = sub { die "Interrupted.\n" };
print "$description. Continue? [y/N] ";
my ($answer, $error);
lib/App/AnteREPL.pm view on Meta::CPAN
}
sub input_needs_more {
my ($self, $source) = @_;
return 0 if $self->{auto} && $source =~ /\A:/;
my $more = App::AnteREPL::Shorthand->needs_more($source, sub { $self->_has_function($_[0]) });
return $more if defined $more;
return needs_more($source);
}
sub _has_function {
my ($self, $name) = @_;
no strict 'refs';
return defined &{ $self->{workspace} . '::' . $name };
}
sub reset_workspace {
$_[0]->_confirm_destructive('Discard live workspace variables and functions');
$_[0]->{workspace} = 'App::AnteREPL::Workspace::S' . ++$next_workspace;
}
sub function_names {
my ($self) = @_;
my $package = $self->{workspace} . '::';
no strict 'refs';
return sort grep { defined &{ $package . $_ } } keys %{$package};
}
sub evaluate {
my ($self, $code, $stored) = @_;
my $label = $stored ? 'PERL_ANTE_REPL_program' : 'PERL_ANTE_REPL_prompt';
my $source = "package $self->{workspace};\n#line 1 \"$label\"\n" . $code . "\n";
my ($value, $error);
{
local $SIG{INT} = sub { die "Interrupted.\n" };
($value, $error) = App::AnteREPL::Evaluator::evaluate($source);
}
if (length $error) {
if ($stored) {
my @numbers = $self->numbers;
$error =~ s{at PERL_ANTE_REPL_program line ([0-9]+)}{
$1 >= 1 && $1 <= @numbers
? 'at stored line ' . $numbers[$1 - 1] . " (source line $1)"
: "at program source line $1"
}ge;
}
die $error;
}
return $value;
}
sub run {
my ($self) = @_;
return $self->evaluate($self->source, 1);
}
sub inspect_value {
my ($self, $command, $expression) = @_;
die "$command needs a Perl expression.\n" unless $expression =~ /\S/;
if ($command eq 'DUMP') {
local $Data::Dumper::Sortkeys = 1;
print $self->evaluate("Data::Dumper::Dumper(do { $expression\n })", 0);
return;
}
require Devel::Peek;
require POSIX;
# Devel::Peek writes to the native stderr descriptor, bypassing tied Perl
# handles. Redirect that descriptor temporarily so its output joins VRAM.
my $temporary = File::Temp->new(UNLINK => 1);
my $saved = POSIX::dup(2);
die "Cannot preserve stderr: $!\n" unless defined $saved && $saved >= 0;
unless (defined POSIX::dup2(fileno($temporary), 2)) {
POSIX::close($saved);
die "Cannot capture Devel::Peek output: $!\n";
}
$expression =~ s/;\s*\z//;
my $ok = eval { $self->evaluate("Devel::Peek::Dump($expression\n)", 0); 1 };
my $error = $@;
my $restored = POSIX::dup2($saved, 2);
POSIX::close($saved);
die "Cannot restore stderr: $!\n" unless defined $restored;
seek($temporary, 0, 0) or die "Cannot rewind peek output: $!\n";
local $/;
my $bytes = <$temporary>;
print decode('UTF-8', $bytes || '');
die $error unless $ok;
}
sub needs_more {
my ($source) = @_;
$source = _expand_short_command($source);
# Numbered lines and REPL/file/shell commands keep their own input grammar.
return 0 if $source =~ /\A\s*(?:[0-9]+(?:[\s:]|\z)|!)/;
return 0 if $source =~ /\A\s*(?:AUTO|ENV|LIST|RUN|EDIT|DEL|DELETE|RENUM|REORDER|UNDO|SAVE|LOAD|IMPORT|EXPORT|NEW|CLEAR|CLS|RECOVER|RESET|FUNCTIONS|STATUS|HELP|QUIT|EXIT|CD|CHDIR)\b/;
my @stack;
my %close = (')' => '(', ']' => '[', '}' => '{');
my $trivia = qr/(?:\s|\#[^\n]*(?:\n|\z))*/;
my $name = qr/[\p{L}_][\p{L}\p{N}_]*(?:(?:::|')[\p{L}_][\p{L}\p{N}_]*)*/;
local $@;
my $position = 0;
while ($position < length $source) {
my $rest = substr($source, $position);
if ($rest =~ /\A\#[^\n]*(?:\n|\z)/ || $rest =~ /\A\s+/) {
$position += length $&;
next;
}
# Prototype sigils are declarations, not variables: ($) ends with a
# closing parenthesis, not the special variable $). Skip only the
# prototype alphabet here; signatures/default expressions still use
# the normal scanner, and actual $) / $( variables remain untouched.
if ($rest =~ /\A(?:sub\b$trivia(?:$name$trivia)?|:$trivia prototype\b$trivia)
\([\$\@%&*+;_\\\[\]\s]*(\)|\z)/x) {
return 1 unless length $1;
$position += length $&;
next;
}
if ($rest =~ /\A([\$\@\%](?:\#?[\p{L}_][\p{L}\p{N}_]*(?:::[\p{L}_][\p{L}\p{N}_]*)*|[0-9]+|[^\w\s{]))/) {
$position += length $1;
next;
}
my $quoted = $rest =~ /\A['"`]/
|| $rest =~ /\A(?:qq|qw|qx|qr|q|m|s|tr|y)\b\s*(?!=>)[^\w\s]/;
lib/App/AnteREPL.pm view on Meta::CPAN
colors red, blue Define @colors; settings color => blue defines %settings.
E accepts lowercase definition tags s/a/ar/h/hr, followed by a name and body.
E s triple return 3 * shift defines triple. EVAL always takes literal Perl.
For a spaced substitution, type EVAL s /old/new/. E s/old/new/ also stays Perl.
Names have letters, digits, underscores; no sigil, namespace, or prototype.
Data definitions with no values make empty containers. A function needs a body.
Commas separate values; => separates each hash key/value. Trailing comma OK.
One optional final semicolon is allowed after a data definition.
Plain words are quoted exactly; decimal numbers stay numbers; undef is undef.
'quoted text', "interpolated text", $scalar, [nested, lists], and
{nested => hashes} work. Quote spaces, punctuation, empty text, and leading
zeroes: "two words", "red-blue", "", "042". No spelling correction occurs.
Native quotes q{a,b}, qq{hi $name}, qw(one two), qr/pattern/, substitutions,
and command quotes also work as values, using Perl's normal semantics.
Quote operators win over word quoting: write "q", "s" for those literal words
next to delimiters. Other Perl expressions can go in parentheses.
Parenthesize Perl expressions: (1 + 2), (1..3), ($ENV{HOME}), (\%ENV).
They use list context in arrays, scalar context for each hash key/value.
Nothing is executed merely to decide how to interpret input.
Bare destination lists need a top-level comma or => and AUTO off. Perl keywords
and existing functions take priority; E a colors red explicitly assigns @colors.
During AUTO, use explicit E forms; they execute without storing or ending AUTO.
Values/functions persist between entries. LIST/SAVE do not include them.
Open quotes/containers continue; Ctrl-N also inserts a line before submission.
Replacing an existing shorthand destination asks first. Forced examples:
E! s triple return 4 * shift; E! a colors green; colors! green, blue.
Functions contain ordinary Perl; approved redefinition still warns normally.
Outside its five reserved tags, E also evaluates Perl. EVAL always means Perl,
including function calls named a/ar/h/hr and declarations with prototypes.
Ambiguous shorthand is rejected with an explanation. Perl expressions and
function bodies retain Perl errors, warnings, and any side effects performed.
ENTERING AND RUNNING PERL
Perl code Execute immediately, unless AUTO is active.
10 Perl code Insert/replace line 10; supply a missing final ;.
10: exact source Store one literal line without adding a semicolon.
10 Delete line 10. Numbers range from 1 to 999999999.
AUTO [start [step]] Store unnumbered source; default increment is 5.
Default start: 5, or highest existing number plus 5.
Existing numbers are skipped. Use LIST to see numbers.
AUTO ECHO ON|OFF Echo numbered copies of stored entries; default OFF.
This preference persists for the session; it does not
start/end AUTO. Your typed text remains visible.
AUTO OFF End AUTO. Ctrl-C/Ctrl-D during entry also end AUTO,
keeping stored lines and cancelling unfinished input.
: exact source In AUTO, store a literal line without continuation.
RUN Execute the whole stored program in numerical order.
EVAL code Uppercase only: execute Perl, including during AUTO.
EVAL leaves AUTO on. AUTO OFF resumes ordinary input.
EVAL do { ... } groups multiline code without storing.
Lowercase eval keeps Perl's normal eval semantics.
EVAL sub name { ... } Define a session function without storing source.
Immediate code and RUN can call it. SAVE excludes it.
Redefining warns by default and replaces the function.
FUNCTIONS List defined names in this workspace, alphabetically.
Includes imports; excludes other packages and stubs.
Works during AUTO; does not execute or store source.
? expression Evaluate in scalar context and display the result.
DUMP expression Data::Dumper output: DUMP $FOO or DUMP \%ENV.
PEEK expression Devel::Peek internals: PEEK $FOO or PEEK $FOO, 10.
Use $x = 1 or our $x for persistent values; my is local to one evaluation.
say/print display output. RUN shares package variables with immediate input.
Stored subroutines become callable after RUN; LOAD/LIST do not define them.
Open quotes, braces, brackets, or parentheses continue on the next row.
A closed subroutine definition, including ($) or (@), submits with Enter.
Ctrl-C cancels unfinished input; commands inside it are still Perl text.
A complete multiline AUTO entry preserves literal source: supply its final ;.
Numbered and AUTO colon entries stay literal, one physical line at a time.
Blank input does nothing. Commands remain available during AUTO.
For heredocs/POD/unusual Perl, use EDIT or literal numbered/colon entries.
DUMP and PEEK are prompt commands; stored Perl uses the module functions.
LISTING, EDITING, AND RECOVERY
LIST List all source; numbers left-aligned, padded on right.
LIST 10 List only line 10.
LIST 10-50 Inclusive range. Also LIST 10-, LIST -50, LIST10-50.
LIST [range] SLOW Start slow. PAUSE instead pauses after each screenful.
Space: pause/resume; S: speed; Enter: step one row;
Q/Esc/Ctrl-C: stop. Other typing/movement ends LIST.
Plain/batch mode prints the whole range without pauses.
EDIT Open the program in $EDITOR, then $VISUAL, then vi
(notepad on Windows). Editor receives no line numbers.
Save and close: changed source becomes 10,20,... .
An unchanged file keeps its numbering. EDIT never runs
the source; use SAVE afterward to write the real file.
DEL range Delete a line/range; DELETE is an alias.
RENUM [start [step]] Renumber; defaults are 10 and 10. REORDER is an alias.
UNDO Undo a source edit (last 50), including EDIT or LOAD.
No rollback of executed Perl, %ENV, or file writes.
CLS Clear screen and resize bank; keep the
stored program, variables, %ENV, and AUTO.
No output in a pipe or on a dumb terminal.
RECOVER Restore the saved pre-shrink screen, only if it fits.
Replaces current screen text; never runs code or
changes stored source. Screen mode only. RECOVER has
no ! suffix; shortcut R3! bypasses confirmation.
NEW / CLEAR Clear source and its filename; retain Perl variables.
RESET Fresh Perl workspace; retain source and live %ENV.
STATUS Line count, save status, filename, and AUTO next/step.
FILES
LOAD file Read ordinary Perl or numbered PERL ANTE REPL source.
Plain source gets numbers 10,20,... . No execution.
.bperl files require a valid native header. Legacy
BASIC PERL V0.1 headers remain supported.
IMPORT file Read plain Perl as an unsaved copy; no save filename.
SAVE [file] Save; reuse last SAVE/LOAD filename and format.
.pl writes plain source; .bperl writes numbered source.
Other extensions retain the current format.
EXPORT file Plain Perl plus default pragmas, for standalone use.
Initialize any needed variables in the source itself.
LOAD!, IMPORT!, NEW!, CLEAR!, QUIT!, EXIT!
Explicitly discard unsaved source. No other command
accepts this ! suffix in its full name. For shortcuts,
see CONFIRMATION above. SAVE/EXPORT replace their file.
ENVIRONMENT
ENV [name] Display %ENV or one variable as sorted VAR=value lines.
lib/App/AnteREPL.pm view on Meta::CPAN
Use EDIT for code too large for the screen. Wide/combining glyphs may misalign.
Editing screen text alone changes nothing until Enter. Bracketed paste waits
for Enter. GUI editors need a wait option, e.g. $ENV{EDITOR} = 'code --wait'.
STARTUP
anterepl [--quiet] [--plain] [program.pl|program.bperl]
--quiet Hide the banner. A startup file is loaded, never run.
--plain Plain input; --no-readline is an alias.
--help / -h This reference. --version prints application version.
-- filename Accept a startup filename beginning with a hyphen.
Native Windows screen mode needs Term::ReadKey and an ANSI-capable terminal.
Piped input uses plain mode; errors/incomplete or unsaved input exit nonzero.
More examples: https://github.com/oodler577/p5-App-AnteREPL/wiki
Offline manual: perldoc App::AnteREPL
HELP
}
sub dispatch {
my ($self, $line) = @_;
$line =~ s/\r?\n\z//;
return 1 if $line =~ /\A\s*\z/;
my $definition = App::AnteREPL::Shorthand->explicit($line);
if (defined $definition) {
$self->_evaluate_definition($definition);
return 1;
}
local $self->{shortcut_guard};
if ($line =~ /\A\s*([A-Z][0-9]*)(!?)(?=\s|\z)/ && exists $short_commands{$1}) {
my ($short, $force) = ($1, $2);
if ($guarded_shortcuts{$short}) {
$self->{shortcut_guard} = {label=>$short, force=>$force};
# The shortcut layer owns confirmation and force. Do not give the
# long-command parser a new force spelling of its own.
$line =~ s/\A(\s*\Q$short\E)!/$1/ if $force;
}
elsif ($force) {
die "The ! suffix is supported only by destructive shortcuts and E! definitions.\n";
}
}
$line = _expand_short_command($line);
if ($line =~ /\A\s*LIST(?=[0-9-])(.*?)\s*\z/) {
$self->list_program($1);
return 1;
}
if ($line =~ /\A\s*([0-9]+):(?:[ \t]?(.*))?\z/) {
$self->set_line($1, defined $2 ? $2 : '', 1);
return 1;
}
if ($line =~ /\A\s*([0-9]+)(?:[ \t](.*))?\z/) {
my ($number, $code) = ($1, $2);
$self->set_line($number, _typed_source($code));
return 1;
}
if ($line =~ /\A\s*(DUMP|PEEK)\b\s*(.*)\z/s) {
$self->inspect_value($1, $2);
return 1;
}
if ($line =~ /\A\s*\?\s*(.*)\z/s) {
my $value = $self->evaluate($1, 0);
print Data::Dumper->new([$value])->Terse(1)->Indent(1)->Sortkeys(1)->Dump;
return 1;
}
if ($line =~ /\A\s*(!{1,2})\s*(\S.*)\z/) {
my ($escape, $command) = ($1, $2);
my @command = $^O eq 'MSWin32' ? ($ENV{COMSPEC} || 'cmd.exe', '/c', $command) : ('/bin/sh', '-c', $command);
my $status = $self->{screen}
? ($escape eq '!!' ? $self->{screen}->external(sub { system @command }, 1) : $self->{screen}->shell(\@command))
: system @command;
die "Cannot start shell: $!\n" if $status == -1;
die "Shell command failed (status $status).\n" if $status;
return 1;
}
if ($line =~ /\A\s*(AUTO|ENV|LIST|RUN|EDIT|DEL|DELETE|RENUM|REORDER|UNDO|SAVE|LOAD|IMPORT|EXPORT|NEW|CLEAR|CLS|RECOVER|RESET|FUNCTIONS|STATUS|HELP|QUIT|EXIT|EVAL|CD|CHDIR)(!?)(?:\s+(.*?))?\s*\z/s) {
my ($command, $force, $tail) = ($1, $2, defined $3 ? $3 : '');
die "The ! suffix is only supported by LOAD, IMPORT, NEW, CLEAR, QUIT, and EXIT.\n"
if $force && $command !~ /\A(?:LOAD|IMPORT|NEW|CLEAR|QUIT|EXIT)\z/;
if ($command eq 'EVAL') {
die "EVAL needs Perl code.\n" unless length $tail;
$self->evaluate($tail, 0);
}
elsif ($command eq 'AUTO') { $self->auto_mode($tail); }
elsif ($command eq 'ENV') { $self->environment($tail); }
elsif ($command eq 'CD' || $command eq 'CHDIR') { $self->change_directory($tail); }
elsif ($command eq 'EDIT' && $tail eq 'ENV') { $self->environment('EDIT'); }
elsif ($command eq 'LIST') {
$self->list_program($tail);
}
elsif ($command eq 'DEL' || $command eq 'DELETE') {
my ($range) = _args($tail, 1, 1, 'DEL line-or-range');
$self->delete_range($range);
}
elsif ($command eq 'RENUM' || $command eq 'REORDER') {
my @args = _args($tail, 0, 2, 'RENUM [start [step]]');
$self->renumber(@args);
}
elsif ($command eq 'SAVE') {
my ($path) = _args($tail, 0, 1, 'SAVE [file]');
print 'Saved ', $self->save($path), ".\n";
}
elsif ($command eq 'LOAD' || $command eq 'IMPORT') {
my ($path) = _args($tail, 1, 1, "$command file");
my $count = $command eq 'LOAD' ? $self->load($path, $force) : $self->import_source($path, $force);
print "Loaded $count lines.\n";
}
elsif ($command eq 'EXPORT') {
my ($path) = _args($tail, 1, 1, 'EXPORT file');
print 'Exported ', $self->export_source($path), ".\n";
}
else {
_args($tail, 0, 0, $command);
if ($command eq 'RUN') { $self->run; }
elsif ($command eq 'EDIT') {
print $self->edit ? "Program updated; lines numbered 10,20,...\n" : "Program unchanged.\n";
}
elsif ($command eq 'UNDO') { $self->undo; print "Program edit undone.\n"; }
elsif ($command eq 'CLS') { $self->clear_screen; }
elsif ($command eq 'RECOVER') { $self->recover_screen; }
elsif ($command eq 'NEW' || $command eq 'CLEAR') { $self->clear($force); }
elsif ($command eq 'RESET') { $self->reset_workspace; print "Perl workspace reset; program retained.\n"; }
elsif ($command eq 'FUNCTIONS') {
lib/App/AnteREPL.pm view on Meta::CPAN
stored in screen memory. SLOW starts slowly; PAUSE stops after each screenful.
Plain mode and piped output never wait for keys or insert listing delays.
=head1 IMPLICIT SEMICOLONS
Ordinary numbered entries supply a missing final semicolon when stored:
10 say "hi"
LIST
10 say "hi";
Existing terminators are retained. Full-line comments and common block or
continuation lines are left alone. A supplied semicolon goes before a trailing
comment, and hashes inside quoted strings are not treated as comments.
This convenience is not a complete Perl parser. For deliberate multiline
expressions, multiline strings, heredoc contents/terminators, POD, or unusual
syntax, use a colon immediately after the editing number to store exact source:
10: my $text = <<'TEXT';
20: hello
30: TEXT
40 say $text
The colon is an input instruction and is not part of the stored source. EDIT,
IMPORT, and LOAD also preserve literal source; they do not insert semicolons.
An already stored line is normalized only when re-entered without the colon.
=head1 EDIT
EDIT writes the current program, without line numbers, into a private temporary
C<program.pl> and starts C<$EDITOR>, falling back to C<$VISUAL>, then C<vi>
(C<notepad> on Windows). Set an editor that waits until editing is finished:
export EDITOR=vim
export EDITOR='code --wait'
The editor command is parsed into an executable and arguments; it is not passed
through a shell. Quote an executable path containing spaces. Windows paths
should use forward slashes when setting EDITOR. Shell expansions, pipes, and
redirections are not supported in EDITOR; use a wrapper script if needed.
After a successful exit, the saved UTF-8 file replaces the in-memory program,
renumbered 10,20,30,... . An unchanged file preserves the existing numbering.
Failure to start, nonzero exit, a missing/unreadable file, invalid UTF-8, NUL
bytes, or bare CR characters leaves the existing program intact. LF and CRLF
files are accepted. Blank lines are retained. UNDO restores the previous
program after a successful edit, including its numbering.
EDIT never runs or syntax-checks your source. Incomplete Perl is allowed in the
buffer; RUN reports errors. This avoids executing BEGIN blocks merely by
editing. Temporary editor files are removed when EDIT finishes.
=head1 WORKSPACE
Immediate input and RUN share a Perl package. C<$x = 1> and C<our $x = 1> persist
between evaluations, along with package arrays, hashes, and subroutines.
C<my> variables are local to one immediate evaluation or one complete RUN.
Pragmas and lexical imports must be repeated in each evaluation that needs
them; C<say> is enabled by default. Evaluation uses scalar context. Use
C<? expression> for Data::Dumper output; ordinary input does not automatically
print its return value. C<EVAL code> bypasses command and line-number parsing.
EVAL must be uppercase; lowercase C<eval> retains Perl's string/block evaluation
and exception-catching behavior. All REPL commands and subcommands must also
be uppercase.
RESET switches to a fresh workspace but keeps the source program. NEW/CLEAR
clear the source but retain the workspace. RUN does not reset variables first.
An exception does not roll back side effects. This runs ordinary Perl with
your account's privileges; C<exit> exits the tool. UNDO affects only stored
source, not executed Perl, shell commands, or saved files.
To execute several blocks together without storing source, leave AUTO off and
type or paste a C<do { ... }> entry, or use C<EVAL do { ... }> during AUTO:
EVAL do {
my $total = 0;
for my $n (1 .. 3) { $total += $n; }
if ($total > 0) { say $total; }
};
This prints 6 and leaves the stored program unchanged. Delimiter continuation
holds the entry until its closing brace. Bracketed paste also groups multiline
text and waits for Enter; the enclosing block works when typing line by line.
Named subroutines defined by immediate input persist in the shared workspace.
A definition in stored source becomes callable after RUN evaluates the program:
10 sub twice { return 2 * shift }
RUN
say twice 21
This prints 42. RUN executes the whole program, including other top-level
statements. LOAD and LIST only deal with source; they do not define functions.
Editing or deleting source does not change an already defined function until
it is redefined or RESET selects a fresh workspace. Use LIST or EDIT to revisit
the stored definition, and C<EVAL say twice 21> to call it during AUTO.
=head1 DIRECTORIES
CD and its alias CHDIR change AnteREPL's own working directory:
CD ..
CHDIR '/path/to/work'
CD 'directory with spaces'
With no argument they use C<HOME>, or C<USERPROFILE> on native Windows if HOME
is unset. Paths are literal; quote spaces. These commands do not expand shell
variables or C<~>. A failed change gives an explanation and retains the current
directory. Lowercase C<chdir> remains ordinary Perl, including expressions:
chdir $ENV{HOME} or die $!
Relative file commands and future child processes use the changed directory.
C<! cd ...> changes only its short-lived child shell, not AnteREPL. Neither
form can change the parent shell's directory.
=head1 FILES AND RECOVERY
LOAD accepts ordinary Perl source as well as UTF-8 numbered files bearing a
PERL ANTE REPL header. Plain source receives numbers 10,20,..., preserving comments,
lib/App/AnteREPL.pm view on Meta::CPAN
=head2 Editing visible entries
Interactive mode uses an ANSI screen with no input prompt or shell-style
command history. New output scrolls the view upward. Arrow keys move the cursor
through displayed input and output, including LIST output. Edit a numbered row
and press Enter to update the stored program. Editing screen text alone does
not change the program or execute it. When you resubmit an earlier entry, its
new output replaces its previous output immediately below the entry, and the
cursor stays just below the new result. If another entry follows, the cursor
moves to its start without inserting a blank spacer or erasing that entry.
Shorter or silent results remove stale output rows; blank lines deliberately
printed by Perl remain. Later entries and their output remain while they fit;
Esc or Ctrl-End moves to fresh input at the bottom. Multiline entries put their
result below the whole group, even when you press Enter on a row in the middle.
This changes only the screen display: executing Perl still repeats its normal
side effects.
C<CLS> clears the display and resize bank, returning the cursor
to the top left. The stored program, live Perl variables, C<%ENV>,
AUTO settings, save filename, unsaved status, and source UNDO remain intact.
C<LIST> displays the program again; C<RUN> still executes it. C<CLEAR> instead
erases the stored program, while Ctrl-L only redraws existing screen text.
In plain mode, CLS emits clear/home escapes only to a terminal whose TERM is
not C<dumb>; it produces no output when redirected or piped.
Typing inserts characters by default, including when editing earlier rows;
Insert switches between insert and overwrite. Backspace/Delete remove characters,
Home/End move within a row. Left at the start of a row moves to the end of
the previous row, stopping at the visible top row. Empty rows are visited
one at a time. PageUp/PageDown move within visible screen text.
Esc or Ctrl-End returns to a blank row at the bottom; Ctrl-Home visits the
top row. Ctrl-U clears a row, Ctrl-L redraws, and Ctrl-C cancels input or
interrupts running Perl. Ctrl-C also shows exit directions: QUIT, QUIT! to
discard unsaved source, or Ctrl-D when AUTO is off and source is saved.
There is no saved history. Wide/combining Unicode
glyphs can misalign the cursor; the editor assumes
one terminal cell per character.
Shift-Enter or Ctrl-N inserts a newline at the cursor without submitting,
splitting the current row and keeping it in the same multiline group. This
works even when the entry is already complete. Enter submits the entire group
once its delimiters are closed, including from a row in the middle. Insert
mode still controls whether subsequent typing inserts or overwrites text.
Shift-Enter requires the terminal to report a distinct key sequence. CSI-u
C<ESC [ 13 ; 2 u> and xterm C<ESC [ 27 ; 2 ; 13 ~> are recognized. If the
terminal sends ordinary Enter for both keys, AnteREPL cannot distinguish them;
use Ctrl-N or configure Shift-Enter to send one of those sequences. These
editing keys apply to screen input, not C<--plain> or program STDIN reads.
For immediate Perl, Enter continues on the next screen row while a brace,
bracket, parenthesis, or quoted literal remains open. Once closed, Enter
submits the whole entry. Earlier multiline entries remain grouped when edited
and resubmitted. Bracketed multiline paste waits for Enter before evaluating.
No extra continuation prompt is printed, and input is never compiled merely
to decide whether it needs another row. This is delimiter continuation, not a
complete Perl parser; use EDIT or literal numbered lines for heredocs/POD and
complex source. Numbered program lines retain their existing single-line rules.
DUMP expression is a prompt command backed by Data::Dumper::Dumper:
$FOO = {
bar => 1,
names => [qw(Alice Bob)],
};
DUMP $FOO
DUMP \%ENV
PEEK expression calls the core Devel::Peek::Dump directly on the expression,
including an optional limit, e.g. C<PEEK $FOO> or C<PEEK $FOO, 10>. Its native
stderr output is captured into the editable display. These are prompt commands;
in stored Perl use the module functions explicitly. They do not redefine Perl's
CORE::dump keyword.
Perl print/say/warn output and simple C<E<lt>STDINE<gt>> line input use the screen.
C<! command> captures external stdout/stderr into screen rows when it finishes,
with closed input. Use C<!! command> for interactive external programs; it lends
them the real terminal and waits for Enter before returning to the screen.
EDIT likewise restores normal terminal settings while your editor runs.
Use these escapes for external programs: direct system/exec calls and arbitrary
XS terminal output bypass the screen model.
Screen mode needs an ANSI-capable terminal. On Unix, it uses core POSIX terminal
support, or Term::ReadKey if installed. Native Windows requires Term::ReadKey
(C<cpanm Term::ReadKey>); its Windows backend has not been validated here.
C<--plain> disables screen editing and uses plain input with no prompt or history.
The old C<--no-readline> flag is an alias for C<--plain>.
C<--quiet> suppresses the banner. A startup filename is loaded but never
executed automatically. Piped input uses plain mode and supports the same
immediate delimiter continuation. Batches return a nonzero status after command
errors, incomplete input at EOF, or unsaved stored source at EOF. Outside AUTO,
Ctrl-D refuses to exit an interactive session with unsaved source. Source files and
workspace values have the same lifetime rules in both terminal modes.
=head1 SEE ALSO
L<https://github.com/oodler577/p5-App-AnteREPL/wiki> contains installation,
first-session, editing, environment, and troubleshooting walkthroughs.
Type HELP for the complete command and keyboard reference, also available
from C<anterepl --help>.
=head1 AUTHOR
Brett Estrade
=head1 COPYRIGHT AND LICENSE
Copyright (c) 2026 Brett Estrade.
This software is free software; you may redistribute it and/or modify it
under the same terms as Perl itself.
=cut
( run in 0.876 second using v1.01-cache-2.11-cpan-c32d3c3b8f1 )