262b3b6862fb2b79676790c3812d8cf9200c2c98
[p5sagit/Filter-Keyword.git] / lib / Filter / Keyword / Filter.pm
1 package Filter::Keyword::Filter;
2 use Moo;
3
4 use Filter::Keyword::Parser;
5 use Filter::Util::Call;
6 use Scalar::Util qw(weaken);
7 use B::Hooks::EndOfScope;
8
9 use constant DEBUG => $ENV{FILTER_KEYWORD_DEBUG};
10 use constant DEBUG_VERBOSE => DEBUG && $ENV{FILTER_KEYWORD_DEBUG} > 1;
11
12 has parser => (is => 'lazy');
13 has active => (is => 'rwp', default => 0);
14
15 sub _build_parser {
16   my $self = shift;
17   weaken $self;
18   Filter::Keyword::Parser->new(
19     reader => sub { $_ = ''; my $r = filter_read; ($_, $r) },
20     re_add => sub {
21       DEBUG_VERBOSE && print STDERR "#re-add#";
22       filter_del;
23       filter_add($self)
24     },
25   );
26 }
27
28 our @ACTIVE_FILTERS;
29 sub install {
30   my ($self) = @_;
31   return if $self->active;
32   push @ACTIVE_FILTERS, $self;
33   $self->_set_active(1);
34   filter_add($self);
35   on_scope_end {
36     $self->_set_active(0);
37     filter_del;
38     pop @ACTIVE_FILTERS;
39   };
40   $self;
41 }
42
43 sub filter {
44   my ($self) = @_;
45   my ($string, $code) = $self->parser->get_next;
46   $_ = $string;
47   DEBUG && print $string;
48   return $code;
49 }
50
51 1;
52