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