1 package Devel::REPL::Plugin::MultiLine::PPI;
3 use Devel::REPL::Plugin;
5 use namespace::clean -except => [ 'meta' ];
7 has 'continuation_prompt' => (
8 is => 'rw', required => 1, lazy => 1,
9 default => sub { '> ' }
13 is => 'rw', required => 1, lazy => 1,
17 around 'read' => sub {
19 my ($self, @args) = @_;
20 my $line = $self->$orig(@args);
23 return $self->continue_reading_if_necessary($line, @args);
29 sub continue_reading_if_necessary {
30 my ( $self, $line, @args ) = @_;
32 while ($self->line_needs_continuation($line)) {
33 my $orig_prompt = $self->prompt;
34 $self->prompt($self->continuation_prompt);
36 $self->line_depth($self->line_depth + 1);
37 my $append = $self->read(@args);
38 $self->line_depth($self->line_depth - 1);
40 $line .= "\n$append" if defined($append);
42 $self->prompt($orig_prompt);
44 # ^D means "shut up and eval already"
45 return $line if !defined($append);
51 sub line_needs_continuation
56 # add this so we can test whether the document ends in PPI::Statement::Null
59 my $document = PPI::Document->new(\$line);
60 return 0 if !defined($document);
62 # adding ";" to a complete document adds a PPI::Statement::Null. we added a ;;
63 # so if it doesn't end in null then there's probably something that's
65 return 0 if $document->child(-1)->isa('PPI::Statement::Null');
67 # this could use more logic, such as returning 1 on s/foo/ba<Enter>
68 my $unfinished_structure = sub
70 my ($document, $element) = @_;
71 return 0 unless $element->isa('PPI::Structure');
72 return 1 unless $element->finish;
76 return $document->find_any($unfinished_structure);
85 Devel::REPL::Plugin::MultiLine::PPI - read lines until all blocks are closed
94 my $repl = Devel::REPL->new;
95 $repl->load_plugin('LexEnv');
96 $repl->load_plugin('History');
97 $repl->load_plugin('MultiLine::PPI');
102 Plugin that will collect lines until you have no unfinished structures. This
103 lets you write subroutines, C<if> statements, loops, etc. more naturally.
105 For example, without a MultiLine plugin,
111 will throw a compile error, because that C<if> statement is incomplete. With a
124 you may write the code across multiple lines, such as in C<irb> and C<python>.
126 This module uses L<PPI>. This plugin is named C<MultiLine::PPI> because someone
127 else may conceivably implement similar behavior some other less
128 dependency-heavy way.
136 Shawn M Moore, C<< <sartak at gmail dot com> >>
138 =head1 COPYRIGHT AND LICENSE
140 Copyright (C) 2007 by Shawn M Moore
142 This library is free software; you can redistribute it and/or modify
143 it under the same terms as Perl itself.