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