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