App-AnteREPL

 view release on metacpan or  search on metacpan

lib/App/AnteREPL.pm  view on Meta::CPAN

    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]/;
        if ($quoted || $rest =~ /\A\//) {
            my ($literal) = extract_quotelike("$rest", '');
            if (defined $literal && length $literal) { $position += length $literal; next; }
            return 1 if $quoted;
        }
        if ($rest =~ /\A[\p{L}_][\p{L}\p{N}_]*/) { $position += length $&; next; }
        my $char = substr($source, $position++, 1);
        if ($char =~ /[({\[]/) { push @stack, $char; }
        elsif (exists $close{$char}) {
            return 0 unless @stack && pop(@stack) eq $close{$char}; # Let Perl report a mismatch.
        }
    }
    return @stack ? 1 : 0;
}

sub _args {
    my ($tail, $min, $max, $usage) = @_;
    my @args = shellwords($tail);
    die "Usage: $usage\n" if @args < $min || @args > $max || (length($tail) && !@args);

lib/App/AnteREPL.pm  view on Meta::CPAN

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 1.223 second using v1.01-cache-2.11-cpan-60884a8df76 )