3 package Devel::REPL::Plugin::MultiLine::PPI;
5 use Devel::REPL::Plugin;
7 use namespace::autoclean;
9 has 'continuation_prompt' => (
12 default => sub { '> ' }
21 around 'read' => sub {
23 my ($self, @args) = @_;
24 my $line = $self->$orig(@args);
27 return $self->continue_reading_if_necessary($line, @args);
33 sub continue_reading_if_necessary {
34 my ( $self, $line, @args ) = @_;
36 while ($self->line_needs_continuation($line)) {
37 my $orig_prompt = $self->prompt;
38 $self->prompt($self->continuation_prompt);
40 $self->line_depth($self->line_depth + 1);
41 my $append = $self->read(@args);
42 $self->line_depth($self->line_depth - 1);
44 $line .= "\n$append" if defined($append);
46 $self->prompt($orig_prompt);
48 # ^D means "shut up and eval already"
49 return $line if !defined($append);
55 sub line_needs_continuation
60 # add this so we can test whether the document ends in PPI::Statement::Null
63 my $document = PPI::Document->new(\$line);
64 return 0 if !defined($document);
66 # adding ";" to a complete document adds a PPI::Statement::Null. we added a ;;
67 # so if it doesn't end in null then there's probably something that's
69 return 0 if $document->child(-1)->isa('PPI::Statement::Null');
71 # this could use more logic, such as returning 1 on s/foo/ba<Enter>
72 my $unfinished_structure = sub
74 my ($document, $element) = @_;
75 return 0 unless $element->isa('PPI::Structure');
76 return 1 unless $element->finish;
80 return $document->find_any($unfinished_structure);
89 Devel::REPL::Plugin::MultiLine::PPI - read lines until all blocks are closed
95 my $repl = Devel::REPL->new;
96 $repl->load_plugin('LexEnv');
97 $repl->load_plugin('History');
98 $repl->load_plugin('MultiLine::PPI');
103 Plugin that will collect lines until you have no unfinished structures. This
104 lets you write subroutines, C<if> statements, loops, etc. more naturally.
106 For example, without a MultiLine plugin,
112 will throw a compile error, because that C<if> statement is incomplete. With a
125 you may write the code across multiple lines, such as in C<irb> and C<python>.
127 This module uses L<PPI>. This plugin is named C<MultiLine::PPI> because someone
128 else may conceivably implement similar behavior some other less
129 dependency-heavy way.
137 Shawn M Moore, C<< <sartak at gmail dot com> >>
139 =head1 COPYRIGHT AND LICENSE
141 Copyright (C) 2007 by Shawn M Moore
143 This library is free software; you can redistribute it and/or modify
144 it under the same terms as Perl itself.