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