]> ruderich.org/simon Gitweb - fcscs/fcscs.git/blob - bin/fcscs
971cb8098e3d46bc47a455fcfdcb4cdbe1a2d314
[fcscs/fcscs.git] / bin / fcscs
1 #!/usr/bin/perl
2
3 # fcscs - fast curses screen content select
4
5 # Copyright (C) 2013-2016  Simon Ruderich
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20
21 use strict;
22 use warnings;
23
24 use v5.10; # say, state
25
26 use Encode ();
27 use Fcntl ();
28 use I18N::Langinfo ();
29
30 use Curses ();
31
32 our $VERSION = '0.01';
33
34
35 =head1 NAME
36
37 fcscs - fast curses screen content select
38
39 =head1 SYNOPSIS
40
41 B<fcscs> [I<options>] I<path/to/screen/capture/file>
42
43 =head1 DESCRIPTION
44
45 B<fcscs> is a small tool which allows quick selection of terminal screen
46 contents (like URLs, paths, regex matches, etc.) and passes the selection to
47 GNU Screen's or Tmux's buffer or any other program. The selection can then
48 quickly be pasted, e.g. in the shell. Requires GNU Screen or Tmux. It's
49 licensed under the GPL 3 or later.
50
51 =head1 OPTIONS
52
53 None so far.
54
55 =head1 USAGE
56
57 Short overview of the general usage, details below:
58
59     - start fcscs
60     - configure actions (optional)
61         - enable pasting
62         - ...
63     - select mode (optional, URL mode is used on startup):
64         - f: file paths
65         - i: IPs
66         - u: URLs
67         - ...
68         - /: search mode
69     - for `normal' modes:
70         - select match by displayed number or <return> for lowest numbered
71           match
72         - configured action is run, e.g. URL is opened with browser
73     - for `search' mode:
74         - perform incremental search
75         - on <return> go to `normal' mode to select a match
76         - after the match is selected wait for confirmation or extension
77         - confirmation: <return> run previously selected action
78         - extension: change match, e.g. select complete word or line
79
80 GNU Screen setup (add to F<~/.screenrc>):
81
82     bind ^B eval "hardcopy $HOME/.tmp/screen-fcscs" "screen fcscs $HOME/.tmp/screen-fcscs"
83
84 Tmux setup (add to F<~/.tmux.conf>):
85
86     bind-key C-b capture-pane \; save-buffer ~/.tmp/tmux-fcscs \; delete-buffer \; new-window "fcscs ~/.tmp/tmux-fcscs"
87
88 This requires a writable ~/.tmp directory. Adapt the mapping according to your
89 preferences. Ensure these files are not readable by others as they can contain
90 private data (umask or protected directory). B<fcscs> must be in your C<$PATH>
91 for the above mappings to work.
92
93 Pressing the configured mapping (Prefix Ctrl-B in this example) opens B<fcscs>
94 in a new GNU screen/Tmux window. After selection, the content is either passed
95 to external programs (e.g. for URLs) or copied to the paste buffer or directly
96 pasted in your previous window and the new window is closed.
97
98 To select a match just type its number. If the match is unique, the entry is
99 automatically selected (e.g. you press 2 and there are only 19 matches). If
100 there are multiple matches left (e.g. you press 1 and there are more than ten
101 matches available), press return to select the current match (1 in this case)
102 or another number to select the longer match. Use backspace to remove the last
103 entered number.
104
105 Press return before entering a number to select the last (lowest numbered)
106 match (underlined by default). To abort without selecting any match use "q".
107
108 To change the selection mode (e.g. paths, files, etc.) use one of the mappings
109 explained below. Per default URLs are selected, see options for a way to
110 change this.
111
112 I<NOTE>: Opening URLs in the browser passes the URL via the command line which
113 leaks URLs to other users on the current system via C<ps aux> or C<top>.
114
115 I<NOTE>: When yanking (copying) a temporary file is used to pass the data to
116 GNU screen/Tmux without exposing it to C<ps aux> or C<top>. However this may
117 leak data if those temporary files are written to disk. To prevent this change
118 your C<$TMP> to point to a memory-only location or encrypted storage.
119
120 If no window appears, try running B<fcscs> manually to catch the error message
121 and please report the bug:
122
123     fcscs /path/to/screen-or-tmux-fcscs-file
124
125
126 =head1 MODES
127
128 =cut
129
130
131 # CLASSES
132
133 # Helper class for drawing on the screen using Curses.
134 package Screen {
135     sub init {
136         my ($class, $encoding) = @_;
137
138         # Prefer strict UTF-8 handling (see perldoc Encode); just in case.
139         if (lc $encoding eq 'utf8') {
140             $encoding = 'UTF-8';
141         }
142         # Get Encode object to speed up decode()/encode().
143         my $encoding_object = Encode::find_encoding($encoding);
144         die "unsupported encoding '$encoding'" unless ref $encoding_object;
145
146         my $curses = Curses->new or die $!;
147
148         my $self = {
149             encoding        => $encoding,
150             encoding_object => $encoding_object,
151             curses          => $curses,
152             debug           => 0,
153             prompt          => {
154                 flags => undef,
155                 name  => undef,
156                 value => undef,
157             },
158         };
159         bless $self, $class;
160
161         Curses::start_color;
162         # Allow default colors by passing -1 to init_pair. A default color is
163         # not drawn on screen thus allowing terminals with pseudo-transparency
164         # to use the transparent background in place of the default color.
165         Curses::use_default_colors;
166
167         Curses::cbreak;
168         Curses::noecho;
169         $self->cursor(0);
170
171         return $self;
172     }
173     sub deinit {
174         my ($self) = @_;
175
176         Curses::nocbreak;
177         Curses::echo;
178         $self->cursor(1);
179
180         Curses::endwin;
181         return;
182     }
183
184     # Convert between Perl's internal encoding and the terminal's encoding.
185     sub encode {
186         my ($self, $string) = @_;
187         return $self->{encoding_object}->encode($string);
188     }
189     sub decode {
190         my ($self, $string) = @_;
191         return eval { # returns undef on decode failure
192             $self->{encoding_object}->decode($string, Encode::FB_CROAK);
193         };
194     }
195
196     # Create attribute for the given fore-/background colors.
197     sub color_pair {
198         my ($self, $fg, $bg) = @_;
199
200         state $next_color_pair = 1; # must start at 1 for init_pair()
201
202         Curses::init_pair($next_color_pair, $fg, $bg);
203         return Curses::COLOR_PAIR($next_color_pair++);
204     }
205
206     # Draw a string which must fit in the current line. Wrapping/clipping is
207     # not supported and must be handled by the caller.
208     sub draw_simple {
209         my ($self, $y, $x, $attributes, $string) = @_;
210
211         die if $string =~ /\n/;
212         # FIXME: wide characters
213         die if $x + length $string > $self->width;
214
215         $self->{curses}->attron($attributes) if defined $attributes;
216         $self->{curses}->addstr($y, $x, $self->encode($string));
217         $self->{curses}->attroff($attributes) if defined $attributes;
218         return;
219     }
220     # Like draw_simple(), but the string is automatically clipped.
221     sub draw_clipped {
222         my ($self, $y, $x, $attributes, $string) = @_;
223
224         # FIXME: wide characters
225         $string = substr $string, 0, $self->width - $x;
226         $self->draw_simple($y, $x, $attributes, $string);
227         return;
228     }
229     sub draw {
230         my ($self, $y, $x, $attributes, $string) = @_;
231
232         die unless defined $string;
233
234         while (1) {
235             my $offset;
236             # We must print each line separately. Search for next newline or
237             # line end, whichever is closer.
238             if ($string =~ /\n/) {
239                 $offset = $-[0];
240             }
241             # FIXME: wide characters
242             if ($x + length $string > $self->width) {
243                 my $new_offset = $self->width - $x;
244                 if (not defined $offset or $offset > $new_offset) {
245                     $offset = $new_offset;
246                 }
247             }
248             last unless defined $offset;
249
250             # FIXME: wide characters
251             $self->draw_simple($y, $x, $attributes, substr $string, 0, $offset);
252
253             # Don't draw "\n" itself.
254             if ("\n" eq substr $string, $offset, 1) {
255                 $offset++;
256             }
257
258             $string = substr $string, $offset;
259
260             $y++;
261             $x = 0;
262         }
263
264         $self->draw_simple($y, $x, $attributes, $string);
265         return $y;
266     }
267
268     sub draw_prompt {
269         my ($self, $config) = @_;
270
271         $self->debug('draw_prompt', 'started');
272
273         my $x = 0;
274         my $y = $self->height - 1;
275
276         # Clear line for better visibility.
277         $self->draw_simple($y, $x, undef, ' ' x $self->width);
278
279         # Draw prompt flags.
280         if (defined (my $s = $self->{prompt}{flags})) {
281             $s = "[$s]";
282             $self->debug('draw_prompt', $s);
283             $self->draw_clipped($y, $x, $config->{attribute}{prompt_flags}, $s);
284             $x += length($s) + 1; # space between next element
285         }
286         # Draw prompt name.
287         if (defined (my $s = $self->{prompt}{name})) {
288             $s = "[$s]";
289             $self->debug('draw_prompt', $s);
290             $self->draw_clipped($y, $x, $config->{attribute}{prompt_name}, $s);
291             $x += length($s) + 1;
292         }
293         # Draw prompt value, e.g. a search field.
294         if (defined (my $s = $self->{prompt}{value})) {
295             $self->debug('draw_prompt', $s);
296             $self->draw_clipped($y, $x, undef, $s);
297             $x += length($s) + 1;
298         }
299         return;
300     }
301
302     sub draw_matches {
303         my ($self, $config, $matches_remove, $matches_add) = @_;
304
305         foreach (@{$matches_remove}) {
306             $self->draw($_->{y}, $_->{x}, Curses::A_NORMAL, $_->{string});
307         }
308
309         my $attr_id     = $config->{attribute}{match_id};
310         my $attr_string = $config->{attribute}{match_string};
311         my $attr_last   = $config->{attribute}{match_last};
312
313         foreach (@{$matches_add}) {
314             my $attr = (defined $_->{id} and $_->{id} == 1)
315                      ? $attr_last
316                      : $attr_string;
317             $self->draw($_->{y}, $_->{x}, $attr, $_->{string});
318             if (defined $_->{id}) {
319                 $self->draw($_->{y}, $_->{x}, $attr_id, $_->{id});
320             }
321         }
322         return;
323     }
324
325     sub die {
326         my ($self, @args) = @_;
327
328         my $attr = $self->color_pair(Curses::COLOR_RED, -1) | Curses::A_BOLD;
329
330         # Clear the screen to improve visibility of the error message.
331         $self->{curses}->clear;
332
333         my $y = $self->draw(0, 0, $attr, "@args");
334
335         if ($self->{debug}) {
336             my $msg;
337             eval {
338                 require Devel::StackTrace;
339             };
340             if ($@) {
341                 $msg = "Devel::StackTrace missing, no stack trace.\n";
342             } else {
343                 my $trace = Devel::StackTrace->new;
344                 $msg = "Stack trace:\n" . $trace->as_string;
345             }
346             $y = $self->draw($y + 1, 0, Curses::A_NORMAL, $msg);
347         }
348
349         $self->draw($y + 1, 0, Curses::A_NORMAL,
350                     'Press any key to terminate fcscs.');
351         $self->refresh;
352
353         $self->getch;
354         $self->deinit;
355         exit 1;
356     }
357     sub debug {
358         my ($self, $module, @args) = @_;
359
360         return if not $self->{debug};
361
362         state $fh; # only open the file once per run
363         if (not defined $fh) {
364             # Ignore errors if the directory doesn't exist.
365             if (not open $fh, '>', "$ENV{HOME}/.config/fcscs/log") {
366                 $fh = undef; # a failed open still writes a value to $fh
367                 return;
368             }
369             $fh->autoflush(1);
370         }
371
372         foreach (@args) {
373             $_ = $self->encode($_);
374         }
375         say $fh "$module: @args" or CORE::die $!;
376         return;
377     }
378
379
380     sub prompt {
381         my ($self, %settings) = @_;
382
383         foreach (keys %settings) {
384             CORE::die if not exists $self->{prompt}{$_};
385             $self->{prompt}{$_} = $settings{$_};
386         }
387         return;
388     }
389
390     # Wrapper for Curses.
391     sub width   { return $Curses::COLS; }
392     sub height  { return $Curses::LINES; }
393     sub refresh { return $_[0]->{curses}->refresh; }
394     sub getch   { return $_[0]->{curses}->getch; }
395     sub cursor  { Curses::curs_set($_[1]); return; }
396 }
397
398
399
400 # FUNCTIONS
401
402 sub prepare_input {
403     my ($screen, $input_ref) = @_;
404
405     # Make sure the input fits on the screen by removing the top lines if
406     # necessary.
407     splice @{$input_ref}, 0, -$screen->height;
408
409     # Pad each line with spaces to the screen width to correctly handle
410     # multi-line regexes.
411     # FIXME: wide characters
412     my @padded = map { sprintf '%-*s', $screen->width, $_ } @{$input_ref};
413
414     my $string = join "\n", @padded;
415     return {
416         string => $string,
417         lines  => $input_ref,
418         width  => $screen->width + 1,
419                   # + 1 = "\n", used in input_match_offset_to_coordinates
420     };
421 }
422
423 sub input_match_offset_to_coordinates {
424     my ($width, $offset) = @_;
425
426     die unless defined $offset;
427
428     my $y = int($offset / $width);
429     my $x = $offset - $y * $width;
430     return ($x, $y);
431 }
432
433 sub get_regex_matches {
434     my ($input, $regex) = @_;
435
436     my @matches;
437     while ($input->{string} =~ /$regex/g) {
438         my $offset = $-[1];
439         die "Match group required in regex '$regex'" if not defined $offset;
440
441         my ($x, $y) = input_match_offset_to_coordinates($input->{width},
442                                                         $offset);
443         push @matches, { x => $x, y => $y, offset => $offset, string => $1 };
444     }
445     return @matches;
446 }
447
448
449 sub run_command {
450     my ($screen, $cmd) = @_;
451
452     $screen->debug('run_command', "running @{$cmd}");
453
454     my $exit = do {
455         # Perl's system() combined with a $SIG{__WARN__} which die()s has
456         # issues due to the fork. The die() in the __WARN__ handler doesn't
457         # die but the program continues after the system().
458         #
459         # If the forked process fails to exec (e.g. program not found) then
460         # the __WARN__ handler is called (because a warning is about to be
461         # displayed) and the die() should display a message and terminate the
462         # process. But due to the fork it doesn't terminate the parent process
463         # and instead changes the return value of system(); it's no longer -1
464         # which makes it impossible to detect that case.
465         #
466         # Perl < 5.18 (found in 5.14) doesn't setup $$ during system() which
467         # makes it impossible to detect if the handler was called from inside
468         # the child.
469         #
470         # Instead, just ignore any warnings during the system(). Thanks to
471         # mauke in #perl on Freenode (2013-10-29 23:30 CET) for the idea to
472         # use no warnings and anno for testing a more recent Perl version with
473         # a working $$.
474         no warnings;
475
476         my @cmd = map { $screen->encode($_) } @{$cmd};
477         system { $cmd[0] } @cmd;
478     };
479     if ($exit != 0) {
480         my $msg;
481         if ($? == -1) {
482             $msg = 'failed to execute: ' . $!;
483         } elsif ($? & 127) {
484             $msg = 'killed by signal ' . ($? & 127);
485         } else {
486             $msg = 'exited with code ' . ($? >> 8);
487         }
488         die "system(@{$cmd}) $msg.";
489     }
490     return;
491 }
492 sub run_in_background {
493     my ($screen, $sub) = @_;
494
495     $screen->debug('run_in_background', "running $sub");
496
497     my $pid = fork;
498     defined $pid or die $!;
499
500     if ($pid == 0) {
501         # The terminal multiplexer sends a SIGHUP to the process when it
502         # closes the window (because the parent process has exited).
503         local $SIG{HUP} = 'IGNORE';
504
505         # Necessary for GNU screen or it'll keep the window open until an
506         # external command has run.
507         require File::Spec;
508         my $devnull = File::Spec->devnull();
509         open STDIN,  '<', $devnull or die $!;
510         open STDOUT, '>', $devnull or die $!;
511         open STDERR, '>', $devnull or die $!;
512
513         # Double-fork to prevent zombies.
514         my $pid = fork;
515         defined $pid or die $!;
516         if ($pid == 0) { # child
517             $sub->();
518         }
519         exit;
520     }
521     waitpid $pid, 0 or die $!;
522     return;
523 }
524
525
526 sub select_match {
527     my ($name, $screen, $config, $input, $matches) = @_;
528
529     $screen->debug('select_match', 'started');
530
531     return if @{$matches} == 0;
532     # Don't return on initial run to give the user a chance to select another
533     # mode, e.g. to switch from URL selection to search selection.
534     if (@{$matches} == 1 and not $config->{state}{initial}) {
535         return { match => $matches->[0] };
536     }
537     $config->{state}{initial} = 0;
538
539     my @sorted = sort { $b->{y} <=> $a->{y} or $b->{x} <=> $a->{x} } @{$matches};
540
541     my $i = 1;
542     foreach (@sorted) {
543         $_->{id} = $i++;
544     }
545
546     $screen->prompt(name => $name, value => undef);
547     $screen->draw_prompt($config);
548
549     $screen->draw_matches($config, [], $matches);
550     $screen->refresh;
551
552     my $number = 0;
553     while (1) {
554         my $char = $screen->getch;
555         if ($char =~ /^\d$/) {
556             $number = $number * 10 + $char;
557         } elsif ($char eq "\b" or $char eq "\x7f") { # backspace
558             $number = int($number / 10);
559         } elsif ($char eq "\n"
560                 or $char eq $config->{setting}{alternative_return}) {
561             last;
562
563         # Selecting a new mode requires falling through into the main input
564         # loop and then starting the new mode.
565         } elsif (defined $config->{mapping}{mode}{$char}) {
566             $screen->draw_matches($config, $matches, []); # clear matches
567             return { key => $char };
568         # All other mappings stay in the current mode.
569         } elsif (defined (my $m = $config->{mapping}{simple}{$char})) {
570             my $result = $m->($char, $screen, $config, $input);
571             last if defined $result->{select_match};
572             next;
573
574         } else {
575             next; # ignore unknown mappings
576         }
577
578         last if $number > 0 and $number * 10 > @{$matches}; # unique match
579
580         my @remaining = $number == 0
581                       ? @{$matches}
582                       : grep { $_->{id} =~ /^$number/ } @{$matches};
583         $screen->draw_matches($config, $matches, \@remaining);
584         $screen->refresh;
585     }
586     # Number without selection matches last entry.
587     if ($number == 0) {
588         $number = 1;
589     }
590
591     $screen->draw_matches($config, $matches, []); # remove matches
592
593     foreach (@{$matches}) {
594         return { match => $_ } if $_->{id} == $number;
595     }
596     $screen->debug('select_match', 'no match selected');
597     return { match => undef };
598 }
599
600 sub extend_match_regex_left {
601     my ($line, $match, $regex) = @_;
602
603     my $s = reverse substr $line, 0, $match->{x};
604     if ($s =~ /^($regex)/) {
605         $match->{string}  = reverse($1) . $match->{string};
606         $match->{x}      -= length $1;
607         $match->{offset} -= length $1;
608     }
609     return;
610 }
611 sub extend_match_regex_right {
612     my ($line, $match, $regex) = @_;
613
614     my $s = substr $line, $match->{x} + length $match->{string};
615     if ($s =~ /^($regex)/) {
616         $match->{string} .= $1;
617     }
618     return;
619 }
620 sub extend_match {
621     my ($screen, $config, $input, $match) = @_;
622
623     $screen->debug('extend_match', 'started');
624
625     return if not defined $match;
626
627     $screen->prompt(name => 'extend', value => undef);
628     $screen->draw_prompt($config);
629
630     delete $match->{id}; # don't draw any match ids
631     $screen->draw_matches($config, [], [$match]);
632     $screen->refresh;
633
634     my $line = $input->{lines}[$match->{y}];
635
636     while (1) {
637         my $match_old = \%{$match};
638
639         my $char = $screen->getch;
640         if ($char eq "\n"
641                 or $char eq $config->{setting}{alternative_return}) {
642             last; # accept match
643
644         } elsif ($char eq 'w') { # select current word (both directions)
645             extend_match_regex_left($line,  $match, qr/\w+/);
646             extend_match_regex_right($line, $match, qr/\w+/);
647         } elsif ($char eq 'b') { # select current word (only left)
648             extend_match_regex_left($line,  $match, qr/\w+/);
649         } elsif ($char eq 'e') { # select current word (only right)
650             extend_match_regex_right($line, $match, qr/\w+/);
651
652         } elsif ($char eq 'W') { # select current WORD (both directions)
653             extend_match_regex_left($line,  $match, qr/\S+/);
654             extend_match_regex_right($line, $match, qr/\S+/);
655         } elsif ($char eq 'B') { # select current WORD (only left)
656             extend_match_regex_left($line,  $match, qr/\S+/);
657         } elsif ($char eq 'E') { # select current WORD (only right)
658             extend_match_regex_right($line, $match, qr/\S+/);
659
660         } elsif ($char eq '0') { # select to beginning of line
661             extend_match_regex_left($line, $match, qr/.+/);
662         } elsif ($char eq '$') { # select to end of line
663             extend_match_regex_right($line, $match, qr/.+/);
664
665         # Allow mode changes if not overwritten by local mappings.
666         } elsif (defined $config->{mapping}{mode}{$char}) {
667             $screen->draw_matches($config, [$match_old], []); # clear match
668             return { key => $char };
669
670         } else {
671             next; # ignore unknown mappings
672         }
673
674         $screen->draw_matches($config, [$match_old], [$match]);
675         $screen->refresh;
676     }
677
678     $screen->debug('extend_match', 'done');
679
680     return { match => $match };
681 }
682
683
684 sub mapping_paste {
685     my ($key, $screen, $config, $input) = @_;
686
687     $screen->debug('mapping_paste', 'started');
688
689     $config->{state}{handler} = $config->{handler}{paste};
690
691     $screen->prompt(flags => 'P'); # paste
692     $screen->draw_prompt($config);
693     $screen->refresh;
694
695     return {};
696 }
697 sub mapping_paste_now {
698     my ($key, $screen, $config, $input) = @_;
699
700     $screen->debug('mapping_paste_now', 'started');
701
702     $config->{state}{handler} = $config->{handler}{paste};
703
704     return {
705         select_match => 1,
706     };
707 }
708
709 sub mapping_yank {
710     my ($key, $screen, $config, $input) = @_;
711
712     $screen->debug('mapping_yank', 'started');
713
714     $config->{state}{handler} = $config->{handler}{yank};
715
716     $screen->prompt(flags => 'Y'); # yank
717     $screen->draw_prompt($config);
718     $screen->refresh;
719
720     return {};
721 }
722 sub mapping_yank_now {
723     my ($key, $screen, $config, $input) = @_;
724
725     $screen->debug('mapping_yank_now', 'started');
726
727     $config->{state}{handler} = $config->{handler}{yank};
728
729     return {
730         select_match => 1,
731     };
732 }
733
734
735 =head2 NORMAL MODES
736
737 Normal modes select matches by calling a function which returns them, e.g. by
738 using a regex.
739
740 The following normal modes are available:
741
742 =over 4
743
744 =item B<path mode> select relative/absolute paths
745
746 =item B<url mode>  select URLs
747
748 =item B<ip mode>   select IPv4 and IPv6 addresses
749
750 =back
751
752 =cut
753 sub mapping_mode_path {
754     my ($key, $screen, $config, $input) = @_;
755
756     $screen->debug('mapping_mode_path', 'started');
757
758     my @matches = get_regex_matches($input, $config->{regex}{path});
759     return {
760         select  => 'path select',
761         matches => \@matches,
762         handler => $config->{handler}{yank},
763     };
764 }
765 sub mapping_mode_url {
766     my ($key, $screen, $config, $input) = @_;
767
768     $screen->debug('mapping_mode_url', 'started');
769
770     my @matches = get_regex_matches($input, $config->{regex}{url});
771     return {
772         select  => 'url select',
773         matches => \@matches,
774         handler => $config->{handler}{url},
775     };
776 }
777 sub mapping_mode_ip {
778     my ($key, $screen, $config, $input) = @_;
779
780     $screen->debug('mapping_mode_ip', 'started');
781
782     my @ipv4 = get_regex_matches($input, $config->{regex}{ipv4});
783     my @ipv6 = get_regex_matches($input, $config->{regex}{ipv6});
784     return {
785         select  => 'ip select',
786         matches => [@ipv4, @ipv6],
787         handler => $config->{handler}{ip},
788     };
789 }
790
791 =head2 SEARCH MODE (AND EXTEND MODE)
792
793 Search mode is a special mode which lets you type a search string (a Perl
794 regex) and then select one of the matches. Afterwards you can extend the
795 match. For example select the complete word or to the end of the line. This
796 allows quick selection of arbitrary text.
797
798 The following mappings are available during the extension mode (not
799 configurable at the moment):
800
801 =over 4
802
803 =item B<w> select current word
804
805 =item B<b> extend word to the left
806
807 =item B<e> extend word to the right
808
809 =item B<W> select current WORD
810
811 =item B<B> extend WORD to the left
812
813 =item B<E> extend WORD to the right
814
815 =item B<0> extend to beginning of line
816
817 =item B<$> extend to end of line
818
819 =back
820
821 C<word> includes any characters matching C<\w+>, C<WORD> any non-whitespace
822 characters (C<\S+>), just like in Vim.
823
824 =cut
825 sub mapping_mode_search {
826     my ($key, $screen, $config, $input) = @_;
827
828     $screen->debug('mapping_mode_search', 'started');
829
830     $screen->cursor(1);
831
832     my $search = ''; # encoded
833     my @last_matches;
834     while (1) {
835         # getch doesn't return decoded characters but raw input bytes. Wait
836         # until the input character is complete.
837         my $value = $screen->decode($search);
838         $value = '' unless defined $value; # undef on decode failure
839
840         $screen->prompt(name => 'search', value => $value);
841         $screen->draw_prompt($config);
842         $screen->refresh;
843
844         my $char = $screen->getch;
845         # TODO: readline editing support
846         if ($char eq "\n") {
847             last;
848         } elsif ($char eq "\b" or $char eq "\x7f") { # backspace
849             # Remove a character, not a byte.
850             $search = $screen->decode($search);
851             chop $search;
852             $search = $screen->encode($search);
853         } else {
854             $search .= $char;
855             next unless defined $screen->decode($search);
856         }
857
858         my @matches;
859         if ($search ne '') {
860             my $case = '';
861             if (($config->{setting}{smartcase} and $search eq lc $search)
862                     or $config->{setting}{ignorecase}) {
863                 $case = '(?i)';
864             }
865             # Ignore invalid regexps.
866             # TODO: display warning on error?
867             eval {
868                 @matches = get_regex_matches($input, qr/($case$search)/);
869             };
870         }
871         $screen->draw_matches($config, \@last_matches, \@matches);
872         @last_matches = @matches;
873     }
874
875     $screen->cursor(0);
876
877     $screen->prompt(name => undef, value => undef); # clear prompt
878     $screen->draw_prompt($config);
879
880     $screen->debug('mapping_mode_search', 'done');
881
882     return {
883         select  => 'search',
884         matches => \@last_matches,
885         extend  => 1,
886         handler => $config->{handler}{yank},
887     };
888 }
889
890 sub mapping_quit {
891     my ($key, $screen, $config, $input) = @_;
892
893     # Key is necessary to fall through to main event loop which then quits.
894     return { key => $key, quit => 1 };
895 }
896
897
898 sub handler_yank {
899     my ($screen, $config, $match) = @_;
900
901     $screen->debug('handler_yank', 'started');
902
903     require File::Temp;
904
905     # Use a temporary file to prevent leaking the yanked data to other users
906     # with the command line, e.g. ps aux or top.
907     my ($fh, $tmp) = File::Temp::tempfile(); # dies on its own
908     print $fh $screen->encode($match->{value}) or die $!;
909     close $fh or die $!;
910
911     if ($config->{setting}{multiplexer} eq 'screen') {
912         $screen->debug('handler_yank', 'using screen');
913
914         # GNU screen displays an annoying "Slurping X characters into buffer".
915         # Use 'msgwait 0' as a hack to disable it.
916         my $msgwait = $config->{setting}{screen_msgwait};
917         run_command($screen, ['screen', '-X', 'msgwait', 0]);
918         run_command($screen, ['screen', '-X', 'readbuf', $tmp]);
919         run_command($screen, ['screen', '-X', 'msgwait', $msgwait]);
920     } elsif ($config->{setting}{multiplexer} eq 'tmux') {
921         $screen->debug('handler_yank', 'using tmux');
922
923         run_command($screen, ['tmux', 'load-buffer', $tmp]);
924     } else {
925         die 'unsupported multiplexer';
926     }
927
928     unlink $tmp or die $!;
929
930     if ($config->{setting}{yank_x11}) {
931         $screen->debug('handler_yank', 'setting X11 selection');
932
933         my @xsel_cmd  = qw( xsel --input --primary );
934         my @xclip_cmd = qw( xclip -in -selection primary );
935
936         my $fh;
937         {
938             # We don't care if a program doesn't exist.
939             no warnings;
940
941             if (not open $fh, '|-', @xsel_cmd) {
942                 if (not open $fh, '|-', @xclip_cmd) {
943                     die "install xsel or xlip to yank to X11 selection\n";
944                 }
945             }
946         }
947         print $fh $match->{value} or die $!;
948         close $fh or die $!;
949     }
950
951     return;
952 }
953 sub handler_paste {
954     my ($screen, $config, $match) = @_;
955
956     $screen->debug('handler_paste', 'started');
957
958     require Time::HiRes;
959
960     my @cmd;
961     if ($config->{setting}{multiplexer} eq 'screen') {
962         $screen->debug('handler_paste', 'using screen');
963         @cmd = qw( screen -X paste . );
964     } elsif ($config->{setting}{multiplexer} eq 'tmux') {
965         $screen->debug('handler_paste', 'using tmux');
966         @cmd = qw( tmux paste-buffer );
967     } else {
968         die 'unsupported multiplexer';
969     }
970
971     run_in_background($screen, sub {
972         # We need to get the data in the paste buffer before we can paste
973         # it.
974         handler_yank($screen, $config, $match);
975
976         # Sleep until we switch back to the current window.
977         Time::HiRes::usleep($config->{setting}{paste_sleep});
978
979         run_command($screen, \@cmd);
980     });
981     return;
982 }
983 sub handler_url {
984     my ($screen, $config, $match) = @_;
985
986     $screen->debug('handler_url', "opening $match->{value}");
987
988     run_in_background($screen, sub {
989         my @cmd = ( @{$config->{setting}{browser}}, $match->{value} );
990         run_command($screen, \@cmd);
991     });
992     return;
993 }
994
995
996
997 # CONFIGURATION DEFAULTS
998
999 =head1 CONFIGURATION
1000
1001 fcscs is configured through F<~/.fcscsrc> or F<~/.config/fcscs/fcscsrc> which
1002 is a normal Perl script with all of Perl's usual features.
1003
1004 All configuration values are stored in the hash C<%config>. All manually
1005 defined keys overwrite the default settings.
1006
1007 A simple F<~/.fcscsrc> could look like this (for details about the used
1008 settings see below):
1009
1010     use strict;
1011     use warnings;
1012
1013     use Curses; # for COLOR_* and A_* constants
1014
1015     our %config;
1016
1017     # Draw matches in blue.
1018     $config{attribute}{match_string} = color_pair(COLOR_BLUE, -1);
1019     # Draw numbers in bold yellow.
1020     $config{attribute}{match_id} = color_pair(COLOR_YELLOW, -1)
1021                                  | A_BOLD;
1022     # Disable Vim-like 'smartcase', ignore case until an upper character is
1023     # searched.
1024     $config{setting}{smartcase} = 0;
1025
1026     # Use chromium to open URLs if running under X, elinks otherwise.
1027     if (defined $ENV{DISPLAY}) {
1028         $config{setting}{browser} = ['chromium'];
1029     } else {
1030         $config{setting}{browser} = ['elinks', '-remote'];
1031     }
1032
1033     # Let fcscs know the file was loaded successfully.
1034     1;
1035
1036 =cut
1037
1038
1039 if (@ARGV != 1) {
1040     require Pod::Usage;
1041     Pod::Usage::pod2usage(2);
1042 }
1043
1044
1045 # Determine terminal encoding from the environment ($ENV{LANG} or similar).
1046 my $encoding = I18N::Langinfo::langinfo(I18N::Langinfo::CODESET);
1047
1048 my $screen = Screen->init($encoding);
1049
1050 # We must restore the screen before exiting.
1051 local $SIG{INT} = sub {
1052     $screen->deinit;
1053     exit 128 + 2;
1054 };
1055 # Make all warnings fatal to make sure they don't get lost (stderr is normally
1056 # not displayed).
1057 local $SIG{__WARN__} = sub {
1058     $screen->die('warning', @_);
1059 };
1060
1061
1062
1063 =head2 MAPPINGS
1064
1065 I<NOTE>: Mappings are split in two categories: Mode mappings which change the
1066 selection and may receive additional input (e.g. a search string) and simple
1067 mappings which only change some config value. Mode mappings are configured via
1068 C<$config{mapping}{mode}>, simple mappings via C<$config{mapping}{simple}>.
1069
1070 The following mode mappings are available by default (the function to remap
1071 them in parentheses):
1072
1073 =over
1074
1075 =item B<f> select absolute/relative paths (C<\&mapping_mode_path>)
1076
1077 =item B<u> select URLs (C<\&mapping_mode_url>)
1078
1079 =item B<i> select IPv4 and IPv6 addresses (C<\&mapping_mode_ip>)
1080
1081 =item B</> search for regex to get selection (C<\&mapping_mode_search>)
1082
1083 =item B<q> quit fcscs (C<\&mapping_quit>)
1084
1085 =back
1086
1087 The following simple mappings are available by default:
1088
1089 =over
1090
1091 =item B<p> enable pasting (C<\&mapping_paste>)
1092
1093 =item B<P> paste current selection (like C<\n> but paste) (C<\&mapping_paste_now>)
1094
1095 =item B<y> enable yanking (copying) (C<\&mapping_yank>)
1096
1097 =item B<Y> yank current selection (like C<\n> but yank) (C<\&mapping_yank_now>)
1098
1099 =back
1100
1101 Note that yanking only uses the GNU screen or Tmux paste buffer by default. To
1102 also copy to X11 selection, enable the B<yank_x11> option.
1103
1104 The following additional mappings are available by default:
1105
1106 =over
1107
1108 =item B<\n> accept current selection (not customizable)
1109
1110 =item B<s>  additional key to accept selection (B<alternative_return> option)
1111
1112 =back
1113
1114 All (single-byte) keys except numbers, backspace and return can be mapped.
1115
1116 Unknown mappings are ignored when pressing keys.
1117
1118 To remove a default mapping, delete it from the mapping hash.
1119
1120 Example:
1121
1122     # Map 'p' to select paths, 'P' to enable pasting.
1123     $config{mapping}{mode}{p} = \&mapping_mode_path;
1124     $config{mapping}{simple}{P} = \&mapping_paste;
1125
1126     # Disable 'f' mapping.
1127     delete $config{mapping}{mode}{f};
1128
1129 =cut
1130 my %mapping_mode = (
1131     f   => \&mapping_mode_path,
1132     u   => \&mapping_mode_url,
1133     i   => \&mapping_mode_ip,
1134     '/' => \&mapping_mode_search,
1135     q   => \&mapping_quit,
1136 );
1137 my %mapping_simple = (
1138     p => \&mapping_paste,
1139     P => \&mapping_paste_now,
1140     y => \&mapping_yank,
1141     Y => \&mapping_yank_now,
1142 );
1143
1144 =head2 ATTRIBUTES
1145
1146 Attributes are used to style the output. They must be Curses attributes.
1147 Defaults in parentheses (foreground, background, attribute).
1148
1149 =over
1150
1151 =item B<match_id>      attribute for match numbers (red, default, bold)
1152
1153 =item B<match_string>  attribute for matches (yellow, default, normal)
1154
1155 =item B<match_last>    attribute for the match selected by return (yellow, default, underline)
1156
1157 =item B<prompt_name>   attribute for prompt name (standout)
1158
1159 =item B<prompt_flags>  attribute for prompt flags (standout)
1160
1161 =back
1162
1163 Example:
1164
1165     # Draw prompt flags in bold red with default background color.
1166     $config{attribute}{prompt_flags}
1167         = Curses::A_BOLD
1168         | color_pair(Curses::COLOR_RED, -1);
1169
1170 =cut
1171 my %attribute = (
1172     match_id     => $screen->color_pair(Curses::COLOR_RED, -1)
1173                     | Curses::A_BOLD,
1174     match_string => $screen->color_pair(Curses::COLOR_YELLOW, -1),
1175     match_last   => $screen->color_pair(Curses::COLOR_YELLOW, -1)
1176                     | Curses::A_UNDERLINE,
1177     prompt_name  => Curses::A_STANDOUT,
1178     prompt_flags => Curses::A_STANDOUT,
1179 );
1180
1181 =head2 SETTINGS
1182
1183 Defaults in parentheses.
1184
1185 =over
1186
1187 =item B<debug>              enable debug mode, writes to I<~/.config/fcscs/log> (C<0>)
1188
1189 =item B<initial_mode>       start in this mode, must be a valid mode mapping (C<\&mapping_mode_url>)
1190
1191 =item B<multiplexer>        set multiplexer ("screen" or "tmux") if not autodetected (C<undef>)
1192
1193 =item B<ignorecase>         ignore case when searching (C<0>)
1194
1195 =item B<smartcase>          ignore case unless one uppercase character is searched (C<1>)
1196
1197 =item B<yank_x11>           copy selection also to X11 primary selection when yanking (C<0>)
1198
1199 =item B<paste_sleep>        sleep x us before running paste command (C<100_000>)
1200
1201 =item B<screen_msgwait>     GNU Screen's msgwait variable, used when yanking (C<5>)
1202
1203 =item B<alternative_return> additional accept key like return, set to C<\n> to disable (C<s>)
1204
1205 =item B<browser>            browser command as array reference (C<['x-www-browser']>)
1206
1207 =back
1208
1209 Example:
1210
1211     # Select paths on startup instead of URLs.
1212     $config{setting}{initial_mode} = \&mapping_mode_path;
1213
1214 =cut
1215 my %setting = (
1216     # options
1217     debug              => 0,
1218     initial_mode       => \&mapping_mode_url,
1219     multiplexer        => undef,
1220     ignorecase         => 0,
1221     smartcase          => 1,
1222     yank_x11           => 0,
1223     paste_sleep        => 100_000,
1224     screen_msgwait     => 5,
1225     # global mappings
1226     alternative_return => 's',
1227     # commands
1228     browser            => ['x-www-browser'],
1229 );
1230
1231 =head2 REGEXPS
1232
1233 =over
1234
1235 =item B<url>  used by C<\&mapping_mode_url>
1236
1237 =item B<path> used by C<\&mapping_mode_path>
1238
1239 =item B<ipv4> used by C<\&mapping_mode_ip>
1240
1241 =item B<ipv6> used by C<\&mapping_mode_ip>
1242
1243 =back
1244
1245 Example:
1246
1247     # Select all non-whitespace characters when searching for paths.
1248     $config{regex}{path} = qr{(\S+)};
1249
1250 =cut
1251 my %regex = (
1252     # Taken from urlview's default configuration file, thanks.
1253     url  => qr{((?:(?:(?:http|https|ftp|gopher)|mailto):(?://)?[^ <>"\t]*|(?:www|ftp)[0-9]?\.[-a-z0-9.]+)[^ .,;\t\n\r<">\):]?[^, <>"\t]*[^ .,;\t\n\r<">\):])},
1254     path => qr{(~?[a-zA-Z0-9_./-]*/[a-zA-Z0-9_./-]+)},
1255     # IP addresses with optional prefix. Not perfectly accurate but good
1256     # enough.
1257     ipv4 => qr!\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?:/\d{1,2})?)\b!,
1258     ipv6 => qr!\b((?:[0-9a-fA-F]{1,4})?(?::+[0-9a-fA-F]{1,4})+(?:/\d{1,3})?)\b!,
1259 );
1260
1261 =head2 HANDLERS
1262
1263 Handlers are used to perform actions on the selected string.
1264
1265 The following handlers are available, defaults in parentheses.
1266
1267 =over
1268
1269 =item B<yank>  used to yank (copy) selection to paste buffer (C<\&handler_yank>)
1270
1271 =item B<paste> used to paste selection into window (C<\&handler_paste>)
1272
1273 =item B<url>   used to open URLs (e.g. in a browser) (C<\&handler_url>)
1274
1275 =item B<ip>    used to handle IPs (C<\&handler_yank>)
1276
1277 =back
1278
1279 Example:
1280
1281     # Download YouTube videos with a custom wrapper, handle all other URLs
1282     # with the default URL handler.
1283     $config{handler}{url} = sub {
1284         my ($screen, $config, $match) = @_;
1285
1286         if ($match->{value} =~ m{^https://www.youtube.com/}) {
1287             return run_in_background($screen, sub {
1288                 run_command($screen, ['youtube-dl-wrapper', $match->{value}]);
1289             });
1290         }
1291         handler_url(@_);
1292     };
1293
1294 =cut
1295 my %handler = (
1296     yank  => \&handler_yank,
1297     paste => \&handler_paste,
1298     url   => \&handler_url,
1299     ip    => \&handler_yank,
1300 );
1301
1302 my %state = (
1303     initial => 1, # used by select_match() for 'initial_mode'
1304     handler => undef,
1305 );
1306
1307
1308
1309 # CONFIGURATION "API"
1310
1311 =head2 FUNCTIONS
1312
1313 The following functions are available:
1314
1315     color_pair($fg, $bg)
1316
1317 Create a new Curses attribute with the given fore- and background color.
1318
1319     mapping_mode_path()
1320     mapping_mode_url()
1321     mapping_mode_ip()
1322     mapping_mode_search()
1323
1324     mapping_paste()
1325     mapping_paste_now()
1326     mapping_yank()
1327     mapping_yank_now()
1328     mapping_quit()
1329
1330 Used as mappings, see L</MAPPINGS> above.
1331
1332     handler_yank()
1333     handler_paste()
1334     handler_url()
1335
1336 Used as handler to yank, paste selection or open URL in browser.
1337
1338     get_regex_matches()
1339     select_match()
1340     run_command()
1341     run_in_background()
1342
1343 Helper functions when writing custom mappings, see the source for details.
1344
1345 Example:
1346
1347     # Enhance URL mode by updating the mapping.
1348     $config{mapping}{mode}{u} = sub {
1349         my ($key, $screen, $config, $input) = @_;
1350
1351         # First get matches of normal URL mode.
1352         my $result = mapping_mode_url(@_);
1353
1354         # Add all strings matching "CVE-1234-1234" with URLs pointing to the
1355         # Debian security tracker. "->{value}" is the string which is used as
1356         # result of the match (e.g. the URL in this case).
1357         my @matches = get_regex_matches($input, qr/\b(CVE-\d+-\d+)\b/);
1358         foreach (@matches) {
1359             $_->{value} = "https://security-tracker.debian.org/$_->{string}";
1360         }
1361         push @{$result->{matches}}, @matches;
1362
1363         # Change all YouTube links to use the custom "youtube" handler (see
1364         # below). This will allow us to automatically open YouTube URLs with a
1365         # custom program, like `youtube-dl` or `mpv`.
1366         foreach (@{$result->{matches}}) {
1367             if ($_->{string} =~ m{^https://www.youtube.com/}) {
1368                 $_->{handler} = $config{handler}{youtube};
1369             }
1370         }
1371
1372         return $result;
1373     }
1374     # Also update initial mode to use our new "URL mode".
1375     $config{setting}{initial_mode} = $config{mapping}{mode}{u};
1376
1377     # Special handler to download YouTube URLs with `youtube-dl`. You could
1378     # also use `mpv` here to immediately play them.
1379     $config{handler}{youtube} = sub {
1380         my ($screen, $config, $match) = @_;
1381
1382         return run_in_background($screen, sub {
1383             run_command($screen, ['youtube-dl', $match->{value}]);
1384         });
1385     };
1386
1387
1388
1389 =cut
1390
1391 # All variables and functions which are usable by ~/.fcscsrc.
1392 package Fcscs {
1393     our $screen; # "private"
1394     our %config;
1395
1396     sub color_pair { return $screen->color_pair(@_); }
1397
1398     sub mapping_mode_path { return main::mapping_mode_path(@_); }
1399     sub mapping_mode_url { return main::mapping_mode_url(@_); }
1400     sub mapping_mode_ip { return main::mapping_mode_ip(@_); }
1401     sub mapping_mode_search { return main::mapping_mode_search(@_); }
1402
1403     sub mapping_paste { return main::mapping_paste(@_); }
1404     sub mapping_paste_now { return main::mapping_paste_now(@_); }
1405     sub mapping_yank { return main::mapping_yank(@_); }
1406     sub mapping_yank_now { return main::mapping_yank_now(@_); }
1407     sub mapping_quit { return main::mapping_quit(@_); }
1408
1409     sub handler_yank { return main::handler_yank(@_); }
1410     sub handler_paste { return main::handler_paste(@_); }
1411     sub handler_url { return main::handler_url(@_); }
1412
1413     sub get_regex_matches { return main::get_regex_matches(@_); }
1414     sub select_match { return main::select_match(@_); }
1415
1416     sub run_command { return main::run_command(@_); }
1417     sub run_in_background { return main::run_in_background(@_); }
1418 }
1419 $Fcscs::screen = $screen;
1420
1421
1422
1423 # LOAD USER CONFIG
1424
1425 # Alias %config and %Fcscs::config. %config is less to type.
1426 our %config;
1427 local *config = \%Fcscs::config;
1428
1429 $config{mapping}{mode}   = \%mapping_mode;
1430 $config{mapping}{simple} = \%mapping_simple;
1431 $config{attribute}       = \%attribute;
1432 $config{setting}         = \%setting;
1433 $config{regex}           = \%regex;
1434 $config{handler}         = \%handler;
1435 $config{state}           = \%state;
1436
1437 package Fcscs {
1438     my @configs = ("$ENV{HOME}/.fcscsrc",
1439                    "$ENV{HOME}/.config/fcscs/fcscsrc");
1440     foreach my $path (@configs) {
1441         my $decoded = $screen->decode($path);
1442
1443         # Load configuration file. Checks have a race condition if the home
1444         # directory is writable by an attacker (but then the user is screwed
1445         # anyway).
1446         next unless -e $path;
1447         if (not -O $path) {
1448             $screen->die("Config '$decoded' not owned by current user!");
1449         }
1450         # Make sure the file is not writable by other users. Doesn't handle
1451         # ACLs and see comment above about race conditions.
1452         my @stat = stat $path or $screen->die("Config '$decoded': $!");
1453         my $mode = $stat[2];
1454         if (($mode & Fcntl::S_IWGRP) or ($mode & Fcntl::S_IWOTH)) {
1455             $screen->die("Config '$decoded' must not be writable by other users.");
1456         }
1457
1458         my $result = do $path;
1459         if (not $result) {
1460             $screen->die("Failed to parse '$decoded': $@") if $@;
1461             $screen->die("Failed to do '$decoded': $!") unless defined $result;
1462             $screen->die("Failed to run '$decoded'.");
1463         }
1464
1465         last; # success, don't load more files
1466     }
1467 }
1468 $screen->{debug} = $config{setting}{debug};
1469
1470
1471 # MAIN
1472
1473 eval {
1474     # Auto-detect current multiplexer.
1475     if (not defined $config{setting}{multiplexer}) {
1476         if (defined $ENV{STY} and defined $ENV{TMUX}) {
1477             die 'Found both $STY and $TMUX, set $config{setting}{multiplexer}.';
1478         } elsif (defined $ENV{STY}) {
1479             $config{setting}{multiplexer} = 'screen';
1480         } elsif (defined $ENV{TMUX}) {
1481             $config{setting}{multiplexer} = 'tmux';
1482         } else {
1483             die 'No multiplexer found.';
1484         }
1485     }
1486
1487     my $binmode = $encoding;
1488     # GNU screen stores the screen dump for unknown reasons as ISO-8859-1
1489     # instead of the currently active encoding.
1490     if ($config{setting}{multiplexer} eq 'screen') {
1491         $binmode = 'ISO-8859-1';
1492     }
1493
1494     my @input_lines;
1495     open my $fh, '<', $ARGV[0] or die $!;
1496     binmode $fh, ":encoding($binmode)" or die $!;
1497     while (<$fh>) {
1498         chomp;
1499         push @input_lines, $_;
1500     }
1501     close $fh or die $!;
1502
1503     my $input = prepare_input($screen, \@input_lines);
1504
1505     # Display original screen content.
1506     my $y = 0;
1507     foreach (@{$input->{lines}}) {
1508         $screen->draw_simple($y++, 0, undef, $_);
1509     }
1510     $screen->refresh;
1511
1512
1513     my $mapping = $config{setting}{initial_mode};
1514
1515     my $key;
1516     while (1) {
1517         if (not defined $mapping) {
1518             $key = $screen->getch unless defined $key;
1519             $screen->debug('input', "got key '$key'");
1520
1521             $mapping = $config{mapping}{mode}{$key};
1522             $mapping = $config{mapping}{simple}{$key} unless defined $mapping;
1523             if (not defined $mapping) { # ignore unknown mappings
1524                 $key = undef;
1525                 next;
1526             }
1527         }
1528
1529         $screen->debug('input', 'running mapping');
1530         my $result = $mapping->($key, $screen, \%config, $input);
1531         $mapping = undef;
1532
1533 RESULT:
1534         if (defined $result->{quit}) {
1535             $screen->debug('input', 'quitting');
1536             last;
1537         }
1538         if (defined $result->{key}) {
1539             $key = $result->{key}; # lookup another mapping
1540             $screen->debug('input', "processing new key: '$key'");
1541             next;
1542         }
1543         if (defined $result->{select}) {
1544             $screen->debug('input', 'selecting match');
1545             my $tmp = $result;
1546             $result = select_match($result->{select},
1547                                    $screen, \%config, $input,
1548                                    $result->{matches});
1549             $result->{handler} = $tmp->{handler};
1550             $result->{extend}  = $tmp->{extend};
1551             goto RESULT; # reprocess special entries in result
1552         }
1553         if (defined $result->{extend}) {
1554             $screen->debug('input', 'extending match');
1555             $result = extend_match($screen, \%config, $input,
1556                                    $result->{match});
1557             goto RESULT; # reprocess special entries in result
1558         }
1559         if (defined $result->{match}) {
1560             if (not defined $result->{match}{value}) {
1561                 $result->{match}{value} = $result->{match}{string};
1562             }
1563
1564             $screen->debug('input', 'running handler');
1565
1566             # Choose handler with falling priority.
1567             my @handlers = (
1568                 $config{state}{handler},     # set by user
1569                 $result->{match}{handler},   # set by match
1570                 $result->{handler},          # set by mapping
1571                 $config{handler}{yank},      # fallback
1572             );
1573             foreach my $handler (@handlers) {
1574                 next unless defined $handler;
1575
1576                 $handler->($screen, \%config, $result->{match});
1577                 last;
1578             }
1579             last;
1580         }
1581
1582         $key = undef; # get next key from user
1583     }
1584 };
1585 if ($@) {
1586     $screen->die("$@");
1587 }
1588
1589 $screen->deinit;
1590
1591 __END__
1592
1593 =head1 EXIT STATUS
1594
1595 =over 4
1596
1597 =item B<0>
1598
1599 Success.
1600
1601 =item B<1>
1602
1603 An error occurred.
1604
1605 =item B<2>
1606
1607 Invalid arguments/options.
1608
1609 =back
1610
1611 =head1 AUTHOR
1612
1613 Simon Ruderich E<lt>simon@ruderich.orgE<gt>
1614
1615 =head1 LICENSE AND COPYRIGHT
1616
1617 Copyright (C) 2013-2016 by Simon Ruderich
1618
1619 This program is free software: you can redistribute it and/or modify
1620 it under the terms of the GNU General Public License as published by
1621 the Free Software Foundation, either version 3 of the License, or
1622 (at your option) any later version.
1623
1624 This program is distributed in the hope that it will be useful,
1625 but WITHOUT ANY WARRANTY; without even the implied warranty of
1626 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
1627 GNU General Public License for more details.
1628
1629 You should have received a copy of the GNU General Public License
1630 along with this program.  If not, see E<lt>http://www.gnu.org/licenses/E<gt>.
1631
1632 =head1 SEE ALSO
1633
1634 L<screen(1)>, L<tmux(1)>, L<urlview(1)>
1635
1636 =cut