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