]> ruderich.org/simon Gitweb - fcscs/fcscs.git/blob - bin/fcscs
add alternative_return setting as additional return mapping
[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         - u: URLs
66         - ...
67         - /: search mode
68     - for `normal' modes:
69         - select match by displayed number or <return> for lowest numbered
70           match
71         - configured action is run, e.g. URL is opened with browser
72     - for `search' mode:
73         - perform incremental search
74         - on <return> go to `normal' mode to select a match
75         - after the match is selected wait for confirmation or extension
76         - confirmation: <return> run previously selected action
77         - extension: change match, e.g. select complete word or line
78
79 GNU Screen setup (add to F<~/.screenrc>):
80
81     bind ^B eval "hardcopy $HOME/.tmp/screen-fcscs" "screen fcscs $HOME/.tmp/screen-fcscs"
82
83 Tmux setup (add to F<~/.tmux.conf>):
84
85     bind-key C-b capture-pane \; save-buffer ~/.tmp/tmux-fcscs \; delete-buffer \; new-window "fcscs ~/.tmp/tmux-fcscs"
86
87 This requires a writable ~/.tmp directory. Adapt the mapping according to your
88 preferences. Ensure these files are not readable by others as they can contain
89 private data (umask or protected directory). B<fcscs> must be in your C<$PATH>
90 for the above mappings to work.
91
92 Pressing the configured mapping (Prefix Ctrl-B in this example) opens B<fcscs>
93 in a new GNU screen/Tmux window. After selection, the content is either passed
94 to external programs (e.g. for URLs) or copied to the paste buffer or directly
95 pasted in your previous window and the new window is closed.
96
97 To select a match just type its number. If the match is unique, the entry is
98 automatically selected (e.g. you press 2 and there are only 19 matches). If
99 there are multiple matches left (e.g. you press 1 and there are more than ten
100 matches available), press return to select the current match (1 in this case)
101 or another number to select the longer match. Use backspace to remove the last
102 entered number.
103
104 Press return before entering a number to select the last (lowest numbered)
105 match (underlined by default). To abort without selecting any match either use
106 "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         }
370
371         foreach (@args) {
372             $_ = $self->encode($_);
373         }
374         say $fh "$module: @args";
375         return;
376     }
377
378
379     sub prompt {
380         my ($self, %settings) = @_;
381
382         foreach (keys %settings) {
383             CORE::die if not exists $self->{prompt}{$_};
384             $self->{prompt}{$_} = $settings{$_};
385         }
386         return;
387     }
388
389     # Wrapper for Curses.
390     sub width   { return $Curses::COLS; }
391     sub height  { return $Curses::LINES; }
392     sub refresh { return $_[0]->{curses}->refresh; }
393     sub getch   { return $_[0]->{curses}->getch; }
394     sub cursor  { Curses::curs_set($_[1]); return; }
395 }
396
397
398
399 # FUNCTIONS
400
401 sub prepare_input {
402     my ($screen, $input_ref) = @_;
403
404     # Make sure the input fits on the screen by removing the top lines if
405     # necessary.
406     splice @{$input_ref}, 0, -$screen->height;
407
408     # Pad each line with spaces to the screen width to correctly handle
409     # multi-line regexes.
410     # FIXME: wide characters
411     my @padded = map { sprintf '%-*s', $screen->width, $_ } @{$input_ref};
412
413     my $string = join "\n", @padded;
414     return {
415         string => $string,
416         lines  => $input_ref,
417         width  => $screen->width + 1,
418                   # + 1 = "\n", used in input_match_offset_to_coordinates
419     };
420 }
421
422 sub input_match_offset_to_coordinates {
423     my ($width, $offset) = @_;
424
425     die unless defined $offset;
426
427     my $y = int($offset / $width);
428     my $x = $offset - $y * $width;
429     return ($x, $y);
430 }
431
432 sub get_regex_matches {
433     my ($input, $regex) = @_;
434
435     my @matches;
436     while ($input->{string} =~ /$regex/g) {
437         my $offset = $-[1];
438         die "Match group required in regex '$regex'" if not defined $offset;
439
440         my ($x, $y) = input_match_offset_to_coordinates($input->{width},
441                                                         $offset);
442         push @matches, { x => $x, y => $y, offset => $offset, string => $1 };
443     }
444     return @matches;
445 }
446
447
448 sub run_command {
449     my ($screen, $config, $cmd) = @_;
450
451     $screen->debug('run_command', "running @{$cmd}");
452
453     my $exit = do {
454         # Perl's system() combined with a $SIG{__WARN__} which die()s has
455         # issues due to the fork. The die() in the __WARN__ handler doesn't
456         # die but the program continues after the system().
457         #
458         # If the forked process fails to exec (e.g. program not found) then
459         # the __WARN__ handler is called (because a warning is about to be
460         # displayed) and the die() should display a message and terminate the
461         # process. But due to the fork it doesn't terminate the parent process
462         # and instead changes the return value of system(); it's no longer -1
463         # which makes it impossible to detect that case.
464         #
465         # Perl < 5.18 (found in 5.14) doesn't setup $$ during system() which
466         # makes it impossible to detect if the handler was called from inside
467         # the child.
468         #
469         # Instead, just ignore any warnings during the system(). Thanks to
470         # mauke in #perl on Freenode (2013-10-29 23:30 CET) for the idea to
471         # use no warnings and anno for testing a more recent Perl version with
472         # a working $$.
473         no warnings;
474
475         my @cmd = map { $screen->encode($_) } @{$cmd};
476         system { $cmd[0] } @cmd;
477     };
478     if ($exit != 0) {
479         my $msg;
480         if ($? == -1) {
481             $msg = 'failed to execute: ' . $!;
482         } elsif ($? & 127) {
483             $msg = 'killed by signal ' . ($? & 127);
484         } else {
485             $msg = 'exited with code ' . ($? >> 8);
486         }
487         die "system(@{$cmd}) $msg.";
488     }
489     return;
490 }
491 sub run_in_background {
492     my ($screen, $sub) = @_;
493
494     $screen->debug('run_in_background', "running $sub");
495
496     my $pid = fork;
497     defined $pid or die $!;
498
499     if ($pid == 0) {
500         # The terminal multiplexer sends a SIGHUP to the process when it
501         # closes the window (because the parent process has exited).
502         local $SIG{HUP} = 'IGNORE';
503
504         # Necessary for GNU screen or it'll keep the window open until the
505         # paste command has run.
506         close STDIN  or die $!;
507         close STDOUT or die $!;
508         close STDERR or die $!;
509
510         # Double-fork to prevent zombies.
511         my $pid = fork;
512         defined $pid or die $!;
513         if ($pid == 0) { # child
514             $sub->();
515         }
516         exit;
517     }
518     waitpid $pid, 0 or die $!;
519     return;
520 }
521
522
523 sub select_match {
524     my ($name, $screen, $config, $input, $matches) = @_;
525
526     $screen->debug('select_match', 'started');
527
528     return if @{$matches} == 0;
529     # Don't return on initial run to give the user a chance to select another
530     # mode, e.g. to switch from URL selection to search selection.
531     if (@{$matches} == 1 and not $config->{state}{initial}) {
532         return { match => $matches->[0] };
533     }
534     $config->{state}{initial} = 0;
535
536     my @sorted = sort { $b->{y} <=> $a->{y} or $b->{x} <=> $a->{x} } @{$matches};
537
538     my $i = 1;
539     foreach (@sorted) {
540         $_->{id} = $i++;
541     }
542
543     $screen->prompt(name => $name, value => undef);
544     $screen->draw_prompt($config);
545
546     $screen->draw_matches($config, [], $matches);
547     $screen->refresh;
548
549     my $number = 0;
550     while (1) {
551         my $char = $screen->getch;
552         if ($char =~ /^\d$/) {
553             $number = $number * 10 + $char;
554         } elsif ($char eq "\b" or $char eq "\x7f") { # backspace
555             $number = int($number / 10);
556         } elsif ($char eq "\n"
557                 or $char eq $config->{setting}{alternative_return}) {
558             if ($number == 0) { # number without selection matches last entry
559                 $number = 1;
560             }
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             $m->($char, $screen, $config, $input);
571             next;
572
573         } else {
574             next; # ignore unknown mappings
575         }
576
577         last if $number > 0 and $number * 10 > @{$matches}; # unique match
578
579         my @remaining = $number == 0
580                       ? @{$matches}
581                       : grep { $_->{id} =~ /^$number/ } @{$matches};
582         $screen->draw_matches($config, $matches, \@remaining);
583         $screen->refresh;
584     }
585
586     $screen->draw_matches($config, $matches, []); # remove matches
587
588     foreach (@{$matches}) {
589         return { match => $_ } if $_->{id} == $number;
590     }
591     $screen->debug('select_match', 'no match selected');
592     return { match => undef };
593 }
594
595 sub extend_match_regex_left {
596     my ($line, $match, $regex) = @_;
597
598     my $s = reverse substr $line, 0, $match->{x};
599     if ($s =~ /^($regex)/) {
600         $match->{string}  = reverse($1) . $match->{string};
601         $match->{x}      -= length $1;
602         $match->{offset} -= length $1;
603     }
604     return;
605 }
606 sub extend_match_regex_right {
607     my ($line, $match, $regex) = @_;
608
609     my $s = substr $line, $match->{x} + length $match->{string};
610     if ($s =~ /^($regex)/) {
611         $match->{string} .= $1;
612     }
613     return;
614 }
615 sub extend_match {
616     my ($screen, $config, $input, $match) = @_;
617
618     $screen->debug('extend_match', 'started');
619
620     return if not defined $match;
621
622     $screen->prompt(name => 'extend', value => undef);
623     $screen->draw_prompt($config);
624
625     delete $match->{id}; # don't draw any match ids
626     $screen->draw_matches($config, [], [$match]);
627     $screen->refresh;
628
629     my $line = $input->{lines}[$match->{y}];
630
631     while (1) {
632         my $match_old = \%{$match};
633
634         my $char = $screen->getch;
635         if ($char eq "\n"
636                 or $char eq $config->{setting}{alternative_return}) {
637             last; # accept match
638
639         } elsif ($char eq 'w') { # select current word (both directions)
640             extend_match_regex_left($line,  $match, qr/\w+/);
641             extend_match_regex_right($line, $match, qr/\w+/);
642         } elsif ($char eq 'b') { # select current word (only left)
643             extend_match_regex_left($line,  $match, qr/\w+/);
644         } elsif ($char eq 'e') { # select current word (only right)
645             extend_match_regex_right($line, $match, qr/\w+/);
646
647         } elsif ($char eq 'W') { # select current WORD (both directions)
648             extend_match_regex_left($line,  $match, qr/\S+/);
649             extend_match_regex_right($line, $match, qr/\S+/);
650         } elsif ($char eq 'B') { # select current WORD (only left)
651             extend_match_regex_left($line,  $match, qr/\S+/);
652         } elsif ($char eq 'E') { # select current WORD (only right)
653             extend_match_regex_right($line, $match, qr/\S+/);
654
655         } elsif ($char eq '0') { # select to beginning of line
656             extend_match_regex_left($line, $match, qr/.+/);
657         } elsif ($char eq '$') { # select to end of line
658             extend_match_regex_right($line, $match, qr/.+/);
659
660         # Allow mode changes if not overwritten by local mappings.
661         } elsif (defined $config->{mapping}{mode}{$char}) {
662             $screen->draw_matches($config, [$match_old], []); # clear match
663             return { key => $char };
664
665         } else {
666             next; # ignore unknown mappings
667         }
668
669         $screen->draw_matches($config, [$match_old], [$match]);
670         $screen->refresh;
671     }
672
673     $screen->debug('extend_match', 'done');
674
675     return { match => $match };
676 }
677
678
679 sub mapping_paste {
680     my ($key, $screen, $config, $input) = @_;
681
682     $screen->debug('mapping_paste', 'started');
683
684     $config->{state}{handler} = $config->{handler}{paste};
685
686     $screen->prompt(flags => 'P'); # paste
687     $screen->draw_prompt($config);
688     $screen->refresh;
689
690     return {};
691 }
692 sub mapping_yank {
693     my ($key, $screen, $config, $input) = @_;
694
695     $screen->debug('mapping_yank', 'started');
696
697     $config->{state}{handler} = $config->{handler}{yank};
698
699     $screen->prompt(flags => 'Y'); # yank
700     $screen->draw_prompt($config);
701     $screen->refresh;
702
703     return {};
704 }
705
706
707 =head2 NORMAL MODES
708
709 Normal modes select matches by calling a function which returns them, e.g. by
710 using a regex.
711
712 The following normal modes are available:
713
714 =over 4
715
716 =item B<path mode> select relative/absolute paths
717
718 =item B<url mode>  select URLs
719
720 =back
721
722 =cut
723 sub mapping_mode_path {
724     my ($key, $screen, $config, $input) = @_;
725
726     $screen->debug('mapping_mode_path', 'started');
727
728     my @matches = get_regex_matches($input, $config->{regex}{path});
729     return {
730         select  => 'path select',
731         matches => \@matches,
732         handler => $config->{handler}{yank},
733     };
734 }
735 sub mapping_mode_url {
736     my ($key, $screen, $config, $input) = @_;
737
738     $screen->debug('mapping_mode_url', 'started');
739
740     my @matches = get_regex_matches($input, $config->{regex}{url});
741     return {
742         select  => 'url select',
743         matches => \@matches,
744         handler => $config->{handler}{url},
745     };
746 }
747
748 =head2 SEARCH MODE (AND EXTEND MODE)
749
750 Search mode is a special mode which lets you type a search string (a Perl
751 regex) and then select one of the matches. Afterwards you can extend the
752 match. For example select the complete word or to the end of the line. This
753 allows quick selection of arbitrary text.
754
755 The following mappings are available during the extension mode (not
756 configurable at the moment):
757
758 =over 4
759
760 =item B<w> select current word
761
762 =item B<b> extend word to the left
763
764 =item B<e> extend word to the right
765
766 =item B<W> select current WORD
767
768 =item B<B> extend WORD to the left
769
770 =item B<E> extend WORD to the right
771
772 =item B<0> extend to beginning of line
773
774 =item B<$> extend to end of line
775
776 =back
777
778 C<word> includes any characters matching C<\w+>, C<WORD> any non-whitespace
779 characters (C<\S+>), just like in Vim.
780
781 =cut
782 sub mapping_mode_search {
783     my ($key, $screen, $config, $input) = @_;
784
785     $screen->debug('mapping_mode_search', 'started');
786
787     $screen->cursor(1);
788
789     my $search = ''; # encoded
790     my @last_matches;
791     while (1) {
792         # getch doesn't return decoded characters but raw input bytes. Wait
793         # until the input character is complete.
794         my $value = $screen->decode($search);
795         $value = '' unless defined $value; # undef on decode failure
796
797         $screen->prompt(name => 'search', value => $value);
798         $screen->draw_prompt($config);
799         $screen->refresh;
800
801         my $char = $screen->getch;
802         # TODO: readline editing support
803         if ($char eq "\n") {
804             last;
805         } elsif ($char eq "\b" or $char eq "\x7f") { # backspace
806             # Remove a character, not a byte.
807             $search = $screen->decode($search);
808             chop $search;
809             $search = $screen->encode($search);
810         } else {
811             $search .= $char;
812             next unless defined $screen->decode($search);
813         }
814
815         my @matches;
816         if ($search ne '') {
817             my $case = '';
818             if (($config->{setting}{smartcase} and $search eq lc $search)
819                     or $config->{setting}{ignorecase}) {
820                 $case = '(?i)';
821             }
822             # Ignore invalid regexps.
823             # TODO: display warning on error?
824             eval {
825                 @matches = get_regex_matches($input, qr/($case$search)/);
826             };
827         }
828         $screen->draw_matches($config, \@last_matches, \@matches);
829         @last_matches = @matches;
830     }
831
832     $screen->cursor(0);
833
834     return {
835         select  => 'search',
836         matches => \@last_matches,
837         extend  => 1,
838         handler => $config->{handler}{yank},
839     };
840 }
841
842 sub mapping_quit {
843     my ($key, $screen, $config, $input) = @_;
844
845     # Key is necessary to fall through to main event loop which then quits.
846     return { key => $key, quit => 1 };
847 }
848
849
850 sub handler_yank {
851     my ($screen, $config, $match) = @_;
852
853     $screen->debug('handler_yank', 'started');
854
855     require File::Temp;
856
857     # Use a temporary file to prevent leaking the yanked data to other users
858     # with the command line, e.g. ps aux or top.
859     my ($fh, $tmp) = File::Temp::tempfile(); # dies on its own
860     print $fh $screen->encode($match->{value});
861     close $fh or die $!;
862
863     if ($config->{setting}{multiplexer} eq 'screen') {
864         $screen->debug('handler_yank', 'using screen');
865
866         # GNU screen displays an annoying "Slurping X characters into buffer".
867         # Use 'msgwait 0' as a hack to disable it.
868         my $msgwait = $config->{setting}{screen_msgwait};
869         run_command($screen, $config, ['screen', '-X', 'msgwait', 0]);
870         run_command($screen, $config, ['screen', '-X', 'readbuf', $tmp]);
871         run_command($screen, $config, ['screen', '-X', 'msgwait', $msgwait]);
872     } elsif ($config->{setting}{multiplexer} eq 'tmux') {
873         $screen->debug('handler_yank', 'using tmux');
874
875         run_command($screen, $config, ['tmux', 'load-buffer', $tmp]);
876     } else {
877         die 'unsupported multiplexer';
878     }
879
880     unlink $tmp or die $!;
881     return;
882 }
883 sub handler_paste {
884     my ($screen, $config, $match) = @_;
885
886     $screen->debug('handler_paste', 'started');
887
888     require Time::HiRes;
889
890     my @cmd;
891     if ($config->{setting}{multiplexer} eq 'screen') {
892         $screen->debug('handler_paste', 'using screen');
893         @cmd = qw( screen -X paste . );
894     } elsif ($config->{setting}{multiplexer} eq 'tmux') {
895         $screen->debug('handler_paste', 'using tmux');
896         @cmd = qw( tmux paste-buffer );
897     } else {
898         die 'unsupported multiplexer';
899     }
900
901     run_in_background($screen, sub {
902         # We need to get the data in the paste buffer before we can paste
903         # it.
904         handler_yank($screen, $config, $match);
905
906         # Sleep until we switch back to the current window.
907         Time::HiRes::usleep($config->{setting}{paste_sleep});
908
909         run_command($screen, $config, \@cmd);
910     });
911     return;
912 }
913 sub handler_url {
914     my ($screen, $config, $match) = @_;
915
916     $screen->debug('handler_url', "opening $match->{value}");
917
918     run_in_background($screen, sub {
919         my @cmd = ( @{$config->{setting}{browser}}, $match->{value} );
920         run_command($screen, $config, \@cmd);
921     });
922     return;
923 }
924
925
926
927 # CONFIGURATION DEFAULTS
928
929 =head1 CONFIGURATION
930
931 fcscs is configured through F<~/.fcscsrc> or F<~/.config/fcscs/fcscsrc> which
932 is a normal Perl script with all of Perl's usual features.
933
934 All configuration values are stored in the hash C<%config>. All manually
935 defined keys overwrite the default settings.
936
937 A simple F<~/.fcscsrc> could look like this (for details about the used
938 settings see below):
939
940     use strict;
941     use warnings;
942
943     use Curses; # for COLOR_* and A_* constants
944
945     our %config;
946
947     # Draw matches in blue.
948     $config{attribute}{match_string} = color_pair(COLOR_BLUE, -1);
949     # Enable Vim-like 'smartcase', ignore case until an upper character is
950     # searched.
951     $config{setting}{smartcase} = 1;
952
953     # Use chromium to open URLs if running under X, elinks otherwise.
954     if (defined $ENV{DISPLAY}) {
955         $config{setting}{browser} = ['chromium'];
956     } else {
957         $config{setting}{browser} = ['elinks'];
958     }
959
960     # Let fcscs know the file was loaded successfully.
961     1;
962
963 =cut
964
965
966 if (@ARGV != 1) {
967     require Pod::Usage;
968     Pod::Usage::pod2usage(2);
969 }
970
971
972 # Determine terminal encoding from the environment ($ENV{LANG} or similar).
973 my $encoding = I18N::Langinfo::langinfo(I18N::Langinfo::CODESET);
974
975 my $screen = Screen->init($encoding);
976
977 # We must restore the screen before exiting.
978 local $SIG{INT} = sub {
979     $screen->deinit;
980     exit 128 + 2;
981 };
982 # Make all warnings fatal to make sure they don't get lost (stderr is normally
983 # not displayed).
984 local $SIG{__WARN__} = sub {
985     $screen->die('warning', @_);
986 };
987
988
989
990 =head2 MAPPINGS
991
992 I<NOTE>: Mappings are split in two categories: Mode mappings which change the
993 selection and may receive additional input (e.g. a search string) and simple
994 mappings which only change some value. Mode mappings are configured via
995 C<$config{mapping}{mode}>, simple mappings via C<$config{mapping}{simple}>.
996
997 The following mode mappings are available by default (the function to remap
998 them in parentheses):
999
1000 =over
1001
1002 =item B<f> select absolute/relative paths (C<\&mapping_mode_path>)
1003
1004 =item B<u> select URLs (C<\&mapping_mode_url>)
1005
1006 =item B</> search for regex to get selection (C<\&mapping_mode_search>)
1007
1008 =item B<q> quit fcscs (C<\&mapping_quit>)
1009
1010 =back
1011
1012 The following simple mappings are available by default:
1013
1014 =over
1015
1016 =item B<p> enable pasting (C<\&mapping_paste>)
1017
1018 =item B<y> enable yanking (copying) (C<\&mapping_yank>)
1019
1020 =back
1021
1022 The following additional mappings are available by default:
1023
1024 =over
1025
1026 =item B<\n> accept current selection (not customizable)
1027
1028 =item B<s>  additional key to accept selection (B<alternative_return> option)
1029
1030 =back
1031
1032 All (single-byte) keys except numbers, backspace and return can be mapped.
1033
1034 Unknown mappings are ignored when pressing keys.
1035
1036 To remove a default mapping, delete it from the mapping hash.
1037
1038 Example:
1039
1040     # Map 'p' to select paths, 'P' to enable pasting.
1041     $config{mapping}{mode}{p} = \&mapping_mode_path;
1042     $config{mapping}{simple}{P} = \&mapping_paste;
1043
1044     # Disable 'f' mapping.
1045     delete $config{mapping}{mode}{f};
1046
1047 =cut
1048 my %mapping_mode = (
1049     f   => \&mapping_mode_path,
1050     u   => \&mapping_mode_url,
1051     '/' => \&mapping_mode_search,
1052     q   => \&mapping_quit,
1053 );
1054 my %mapping_simple = (
1055     p => \&mapping_paste,
1056     y => \&mapping_yank,
1057 );
1058
1059 =head2 ATTRIBUTES
1060
1061 Attributes are used to style the output. They must be Curses attributes.
1062 Defaults in parentheses (foreground, background, attribute).
1063
1064 =over
1065
1066 =item B<match_id>      attribute for match numbers (red, default, bold)
1067
1068 =item B<match_string>  attribute for matches (yellow, default, normal)
1069
1070 =item B<match_last>    attribute for the match selected by return (yellow, default, underline)
1071
1072 =item B<prompt_name>   attribute for prompt name (standout)
1073
1074 =item B<prompt_flags>  attribute for prompt flags (standout)
1075
1076 =back
1077
1078 Example:
1079
1080     # Draw prompt flags in bold red with default background color.
1081     $config{attribute}{prompt_flags}
1082         = Curses::A_BOLD
1083         | color_pair(Curses::COLOR_RED, -1);
1084
1085 =cut
1086 my %attribute = (
1087     match_id     => $screen->color_pair(Curses::COLOR_RED, -1)
1088                     | Curses::A_BOLD,
1089     match_string => $screen->color_pair(Curses::COLOR_YELLOW, -1),
1090     match_last   => $screen->color_pair(Curses::COLOR_YELLOW, -1)
1091                     | Curses::A_UNDERLINE,
1092     prompt_name  => Curses::A_STANDOUT,
1093     prompt_flags => Curses::A_STANDOUT,
1094 );
1095
1096 =head2 SETTINGS
1097
1098 Defaults in parentheses.
1099
1100 =over
1101
1102 =item B<debug>          enable debug mode, writes to I<~/.config/fcscs/log> (C<0>)
1103
1104 =item B<initial_mode>   start in this mode, must be a valid mode mapping (C<\&mapping_mode_url>)
1105
1106 =item B<multiplexer>    set multiplexer ("screen" or "tmux") if not autodetected (C<undef>)
1107
1108 =item B<ignorecase>     ignore case when searching (C<0>)
1109
1110 =item B<smartcase>      ignore case unless one uppercase character is searched (C<1>)
1111
1112 =item B<paste_sleep>    sleep x us before running paste command (C<100_000>)
1113
1114 =item B<screen_msgwait> GNU Screen's msgwait variable, used when yanking (C<5>)
1115
1116 =item B<alternative_return> additional accept key like return, set to C<\n> to disable (C<s>)
1117
1118 =item B<browser>        browser command as array reference (C<['x-www-browser']>)
1119
1120 =back
1121
1122 Example:
1123
1124     # Select paths on startup instead of URLs.
1125     $config{setting}{initial_mode} = \&mapping_mode_path;
1126
1127 =cut
1128 my %setting = (
1129     # options
1130     debug          => 0,
1131     initial_mode   => \&mapping_mode_url,
1132     multiplexer    => undef,
1133     ignorecase     => 0,
1134     smartcase      => 1,
1135     paste_sleep    => 100_000,
1136     screen_msgwait => 5,
1137     # global mappings
1138     alternative_return => 's',
1139     # commands
1140     browser        => ['x-www-browser'],
1141 );
1142
1143 =head2 REGEXPS
1144
1145 =over
1146
1147 =item B<url>  used by C<\&mapping_mode_url()>
1148
1149 =item B<path> used by C<\&mapping_mode_path()>
1150
1151 =back
1152
1153 Example:
1154
1155     # Select all non-whitespace characters when searching for paths.
1156     $config{regex}{path} = qr{(\S+)};
1157
1158 =cut
1159 my %regex = (
1160     # Taken from urlview's default configuration file, thanks.
1161     url  => qr{((?:(?:(?:http|https|ftp|gopher)|mailto):(?://)?[^ <>"\t]*|(?:www|ftp)[0-9]?\.[-a-z0-9.]+)[^ .,;\t\n\r<">\):]?[^, <>"\t]*[^ .,;\t\n\r<">\):])},
1162     path => qr{(~?[a-zA-Z0-9_./-]*/[a-zA-Z0-9_./-]+)},
1163 );
1164
1165 =head2 HANDLERS
1166
1167 Handlers are used to perform actions on the selected string.
1168
1169 The following handlers are available, defaults in parentheses.
1170
1171 =over
1172
1173 =item B<yank>  used to yank (copy) selection to paste buffer (C<\&handler_yank>)
1174
1175 =item B<paste> used to paste selection into window (C<\&handler_paste>)
1176
1177 =item B<url>   used to open URLs (e.g. in a browser) (C<\&handler_url>)
1178
1179 =back
1180
1181 Example:
1182
1183     # Download YouTube videos with a custom wrapper, handle all other URLs
1184     # with the default URL handler.
1185     $config{handler}{url} = sub {
1186         my ($screen, $config, $match) = @_;
1187
1188         if ($match->{value} =~ m{^https://www.youtube.com/}) {
1189             return run_in_background($screen, sub {
1190                 run_command($screen, $config,
1191                             ['youtube-dl-wrapper', $match->{value}]);
1192             });
1193         }
1194         handler_url(@_);
1195     };
1196
1197 =cut
1198 my %handler = (
1199     yank  => \&handler_yank,
1200     paste => \&handler_paste,
1201     url   => \&handler_url,
1202 );
1203
1204 my %state = (
1205     initial => 1, # used by select_match() for 'initial_mode'
1206     handler => undef,
1207 );
1208
1209
1210
1211 # CONFIGURATION "API"
1212
1213 =head2 FUNCTIONS
1214
1215 The following functions are available:
1216
1217     color_pair($fg, $bg)
1218
1219 Create a new Curses attribute with the given fore- and background color.
1220
1221     mapping_mode_path()
1222     mapping_mode_url()
1223     mapping_mode_search()
1224
1225     mapping_paste()
1226     mapping_yank()
1227     mapping_quit()
1228
1229 Used as mappings, see L</MAPPINGS> above.
1230
1231     handler_yank()
1232     handler_paste()
1233     handler_url()
1234
1235 Used as handler to yank, paste selection or open URL in browser.
1236
1237     debug()
1238     get_regex_matches()
1239     select_match()
1240     run_command()
1241     run_in_background()
1242
1243 Helper functions when writing custom mappings, see the source for details.
1244
1245 Example:
1246
1247     TODO
1248
1249 =cut
1250
1251 # All variables and functions which are usable by ~/.fcscsrc.
1252 package Fcscs {
1253     our $screen; # "private"
1254     our %config;
1255
1256     sub color_pair { return $screen->color_pair(@_); }
1257
1258     sub mapping_mode_path { return main::mapping_mode_path(@_); }
1259     sub mapping_mode_url { return main::mapping_mode_url(@_); }
1260     sub mapping_mode_search { return main::mapping_mode_search(@_); }
1261
1262     sub mapping_paste { return main::mapping_paste(@_); }
1263     sub mapping_yank { return main::mapping_yank(@_); }
1264     sub mapping_quit { return main::mapping_quit(@_); }
1265
1266     sub handler_yank { return main::handler_yank(@_); }
1267     sub handler_paste { return main::handler_paste(@_); }
1268     sub handler_url { return main::handler_url(@_); }
1269
1270     sub debug { return main::debug(@_); }
1271
1272     sub get_regex_matches { return main::get_regex_matches(@_); }
1273     sub select_match { return main::select_match(@_); }
1274
1275     sub run_command { return main::run_command(@_); }
1276     sub run_in_background { return main::run_in_background(@_); }
1277 }
1278 $Fcscs::screen = $screen;
1279
1280
1281
1282 # LOAD USER CONFIG
1283
1284 # Alias %config and %Fcscs::config. %config is less to type.
1285 our %config;
1286 local *config = \%Fcscs::config;
1287
1288 $config{mapping}{mode}   = \%mapping_mode;
1289 $config{mapping}{simple} = \%mapping_simple;
1290 $config{attribute}       = \%attribute;
1291 $config{setting}         = \%setting;
1292 $config{regex}           = \%regex;
1293 $config{handler}         = \%handler;
1294 $config{state}           = \%state;
1295
1296 package Fcscs {
1297     my @configs = ("$ENV{HOME}/.fcscsrc",
1298                    "$ENV{HOME}/.config/fcscs/fcscsrc");
1299     foreach my $path (@configs) {
1300         my $decoded = $screen->decode($path);
1301
1302         # Load configuration file. Checks have a race condition if the home
1303         # directory is writable by an attacker (but then the user is screwed
1304         # anyway).
1305         next unless -e $path;
1306         if (not -O $path) {
1307             $screen->die("Config '$decoded' not owned by current user!");
1308         }
1309         # Make sure the file is not writable by other users. Doesn't handle
1310         # ACLs and see comment above about race conditions.
1311         my @stat = stat $path or die $!;
1312         my $mode = $stat[2];
1313         if (($mode & Fcntl::S_IWGRP) or ($mode & Fcntl::S_IWOTH)) {
1314             die "Config '$decoded' must not be writable by other users.";
1315         }
1316
1317         my $result = do $path;
1318         if (not $result) {
1319             $screen->die("Failed to parse '$decoded': $@") if $@;
1320             $screen->die("Failed to do '$decoded': $!") unless defined $result;
1321             $screen->die("Failed to run '$decoded'.");
1322         }
1323
1324         last; # success, don't load more files
1325     }
1326 }
1327 $screen->{debug} = $config{setting}{debug};
1328
1329
1330 # MAIN
1331
1332 eval {
1333     # Auto-detect current multiplexer.
1334     if (not defined $config{setting}{multiplexer}) {
1335         if (defined $ENV{STY} and defined $ENV{TMUX}) {
1336             die 'Found both $STY and $TMUX, set $config{setting}{multiplexer}.';
1337         } elsif (defined $ENV{STY}) {
1338             $config{setting}{multiplexer} = 'screen';
1339         } elsif (defined $ENV{TMUX}) {
1340             $config{setting}{multiplexer} = 'tmux';
1341         } else {
1342             die 'No multiplexer found.';
1343         }
1344     }
1345
1346     my $binmode = $encoding;
1347     # GNU screen stores the screen dump for unknown reasons as ISO-8859-1
1348     # instead of the currently active encoding.
1349     if ($config{setting}{multiplexer} eq 'screen') {
1350         $binmode = 'ISO-8859-1';
1351     }
1352
1353     my @input_lines;
1354     open my $fh, '<', $ARGV[0] or die $!;
1355     binmode $fh, ":encoding($binmode)" or die $!;
1356     while (<$fh>) {
1357         chomp;
1358         push @input_lines, $_;
1359     }
1360     close $fh or die $!;
1361
1362     my $input = prepare_input($screen, \@input_lines);
1363
1364     # Display original screen content.
1365     my $y = 0;
1366     foreach (@{$input->{lines}}) {
1367         $screen->draw_simple($y++, 0, undef, $_);
1368     }
1369     $screen->refresh;
1370
1371
1372     my $mapping = $config{setting}{initial_mode};
1373
1374     my $key;
1375     while (1) {
1376         if (not defined $mapping) {
1377             $key = $screen->getch unless defined $key;
1378             $screen->debug('input', "got key '$key'");
1379
1380             $mapping = $config{mapping}{mode}{$key};
1381             $mapping = $config{mapping}{simple}{$key} unless defined $mapping;
1382             if (not defined $mapping) { # ignore unknown mappings
1383                 $key = undef;
1384                 next;
1385             }
1386         }
1387
1388         $screen->debug('input', 'running mapping');
1389         my $result = $mapping->($key, $screen, \%config, $input);
1390         $mapping = undef;
1391
1392 RESULT:
1393         if (defined $result->{quit}) {
1394             $screen->debug('input', 'quitting');
1395             last;
1396         }
1397         if (defined $result->{key}) {
1398             $key = $result->{key}; # lookup another mapping
1399             $screen->debug('input', "processing new key: '$key'");
1400             next;
1401         }
1402         if (defined $result->{select}) {
1403             $screen->debug('input', 'selecting match');
1404             my $tmp = $result;
1405             $result = select_match($result->{select},
1406                                    $screen, \%config, $input,
1407                                    $result->{matches});
1408             $result->{handler} = $tmp->{handler};
1409             $result->{extend}  = $tmp->{extend};
1410             goto RESULT; # reprocess special entries in result
1411         }
1412         if (defined $result->{extend}) {
1413             $screen->debug('input', 'extending match');
1414             $result = extend_match($screen, \%config, $input,
1415                                    $result->{match});
1416             goto RESULT; # reprocess special entries in result
1417         }
1418         if (defined $result->{match}) {
1419             if (not defined $result->{match}{value}) {
1420                 $result->{match}{value} = $result->{match}{string};
1421             }
1422
1423             $screen->debug('input', 'running handler');
1424
1425             # Choose handler with falling priority.
1426             my @handlers = (
1427                 $config{state}{handler},     # set by user
1428                 $result->{match}{handler},   # set by match
1429                 $result->{handler},          # set by mapping
1430                 $config{handler}{yank},      # fallback
1431             );
1432             foreach my $handler (@handlers) {
1433                 next unless defined $handler;
1434
1435                 $handler->($screen, \%config, $result->{match});
1436                 last;
1437             }
1438             last;
1439         }
1440
1441         $key = undef; # get next key from user
1442     }
1443 };
1444 if ($@) {
1445     $screen->die("$@");
1446 }
1447
1448 $screen->deinit;
1449
1450 __END__
1451
1452 =head1 EXIT STATUS
1453
1454 =over 4
1455
1456 =item B<0>
1457
1458 Success.
1459
1460 =item B<1>
1461
1462 An error occurred.
1463
1464 =item B<2>
1465
1466 Invalid arguments/options.
1467
1468 =back
1469
1470 =head1 AUTHOR
1471
1472 Simon Ruderich E<lt>simon@ruderich.orgE<gt>
1473
1474 =head1 LICENSE AND COPYRIGHT
1475
1476 Copyright (C) 2013-2016 by Simon Ruderich
1477
1478 This program is free software: you can redistribute it and/or modify
1479 it under the terms of the GNU General Public License as published by
1480 the Free Software Foundation, either version 3 of the License, or
1481 (at your option) any later version.
1482
1483 This program is distributed in the hope that it will be useful,
1484 but WITHOUT ANY WARRANTY; without even the implied warranty of
1485 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
1486 GNU General Public License for more details.
1487
1488 You should have received a copy of the GNU General Public License
1489 along with this program.  If not, see E<lt>http://www.gnu.org/licenses/E<gt>.
1490
1491 =head1 SEE ALSO
1492
1493 L<screen(1)>, L<tmux(1)>, L<urlview(1)>
1494
1495 =cut