3 # fcscs - fast curses screen content select
5 # Copyright (C) 2013-2016 Simon Ruderich
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.
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.
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/>.
24 use v5.10; # say, state
28 use I18N::Langinfo ();
32 our $VERSION = '0.01';
37 fcscs - fast curses screen content select
41 B<fcscs> [I<options>] I<path/to/screen/capture/file>
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.
57 Short overview of the general usage, details below:
60 - configure actions (optional)
63 - select mode (optional, URL mode is used on startup):
70 - select match by displayed number or <return> for lowest numbered
72 - configured action is run, e.g. URL is opened with browser
74 - perform incremental search
75 - on <return> go to `normal' mode to select a match
76 - after the match is selected wait for confirmation or extension
77 - confirmation: <return> run previously selected action
78 - extension: change match, e.g. select complete word or line
80 GNU Screen setup (add to F<~/.screenrc>):
82 bind ^B eval "hardcopy $HOME/.tmp/screen-fcscs" "screen fcscs $HOME/.tmp/screen-fcscs"
84 Tmux setup (add to F<~/.tmux.conf>):
86 bind-key C-b capture-pane \; save-buffer ~/.tmp/tmux-fcscs \; delete-buffer \; new-window "fcscs ~/.tmp/tmux-fcscs"
88 This requires a writable ~/.tmp directory. Adapt the mapping according to your
89 preferences. Ensure these files are not readable by others as they can contain
90 private data (umask or protected directory). B<fcscs> must be in your C<$PATH>
91 for the above mappings to work.
93 Pressing the configured mapping (Prefix Ctrl-B in this example) opens B<fcscs>
94 in a new GNU screen/Tmux window. After selection, the content is either passed
95 to external programs (e.g. for URLs) or copied to the paste buffer or directly
96 pasted in your previous window and the new window is closed.
98 To select a match just type its number. If the match is unique, the entry is
99 automatically selected (e.g. you press 2 and there are only 19 matches). If
100 there are multiple matches left (e.g. you press 1 and there are more than ten
101 matches available), press return to select the current match (1 in this case)
102 or another number to select the longer match. Use backspace to remove the last
105 Press return before entering a number to select the last (lowest numbered)
106 match (underlined by default). To abort without selecting any match use "q".
108 To change the selection mode (e.g. paths, files, etc.) use one of the mappings
109 explained below. Per default URLs are selected, see options for a way to
112 I<NOTE>: Opening URLs in the browser passes the URL via the command line which
113 leaks URLs to other users on the current system via C<ps aux> or C<top>.
115 I<NOTE>: When yanking (copying) a temporary file is used to pass the data to
116 GNU screen/Tmux without exposing it to C<ps aux> or C<top>. However this may
117 leak data if those temporary files are written to disk. To prevent this change
118 your C<$TMP> to point to a memory-only location or encrypted storage.
120 If no window appears, try running B<fcscs> manually to catch the error message
121 and please report the bug:
123 fcscs /path/to/screen-or-tmux-fcscs-file
133 # Helper class for drawing on the screen using Curses.
136 my ($class, $encoding) = @_;
138 # Prefer strict UTF-8 handling (see perldoc Encode); just in case.
139 if (lc $encoding eq 'utf8') {
142 # Get Encode object to speed up decode()/encode().
143 my $encoding_object = Encode::find_encoding($encoding);
144 die "unsupported encoding '$encoding'" unless ref $encoding_object;
146 my $curses = Curses->new or die $!;
149 encoding => $encoding,
150 encoding_object => $encoding_object,
162 # Allow default colors by passing -1 to init_pair. A default color is
163 # not drawn on screen thus allowing terminals with pseudo-transparency
164 # to use the transparent background in place of the default color.
165 Curses::use_default_colors;
184 # Convert between Perl's internal encoding and the terminal's encoding.
186 my ($self, $string) = @_;
187 return $self->{encoding_object}->encode($string);
190 my ($self, $string) = @_;
191 return eval { # returns undef on decode failure
192 $self->{encoding_object}->decode($string, Encode::FB_CROAK);
196 # Create attribute for the given fore-/background colors.
198 my ($self, $fg, $bg) = @_;
200 state $next_color_pair = 1; # must start at 1 for init_pair()
202 Curses::init_pair($next_color_pair, $fg, $bg);
203 return Curses::COLOR_PAIR($next_color_pair++);
206 # Draw a string which must fit in the current line. Wrapping/clipping is
207 # not supported and must be handled by the caller.
209 my ($self, $y, $x, $attributes, $string) = @_;
211 die if $string =~ /\n/;
212 # FIXME: wide characters
213 die if $x + length $string > $self->width;
215 $self->{curses}->attron($attributes) if defined $attributes;
216 $self->{curses}->addstr($y, $x, $self->encode($string));
217 $self->{curses}->attroff($attributes) if defined $attributes;
220 # Like draw_simple(), but the string is automatically clipped.
222 my ($self, $y, $x, $attributes, $string) = @_;
224 # FIXME: wide characters
225 $string = substr $string, 0, $self->width - $x;
226 $self->draw_simple($y, $x, $attributes, $string);
230 my ($self, $y, $x, $attributes, $string) = @_;
232 die unless defined $string;
236 # We must print each line separately. Search for next newline or
237 # line end, whichever is closer.
238 if ($string =~ /\n/) {
241 # FIXME: wide characters
242 if ($x + length $string > $self->width) {
243 my $new_offset = $self->width - $x;
244 if (not defined $offset or $offset > $new_offset) {
245 $offset = $new_offset;
248 last unless defined $offset;
250 # FIXME: wide characters
251 $self->draw_simple($y, $x, $attributes, substr $string, 0, $offset);
253 # Don't draw "\n" itself.
254 if ("\n" eq substr $string, $offset, 1) {
258 $string = substr $string, $offset;
264 $self->draw_simple($y, $x, $attributes, $string);
269 my ($self, $config) = @_;
271 $self->debug('draw_prompt', 'started');
274 my $y = $self->height - 1;
276 # Clear line for better visibility.
277 $self->draw_simple($y, $x, undef, ' ' x $self->width);
280 if (defined (my $s = $self->{prompt}{flags})) {
282 $self->debug('draw_prompt', $s);
283 $self->draw_clipped($y, $x, $config->{attribute}{prompt_flags}, $s);
284 $x += length($s) + 1; # space between next element
287 if (defined (my $s = $self->{prompt}{name})) {
289 $self->debug('draw_prompt', $s);
290 $self->draw_clipped($y, $x, $config->{attribute}{prompt_name}, $s);
291 $x += length($s) + 1;
293 # Draw prompt value, e.g. a search field.
294 if (defined (my $s = $self->{prompt}{value})) {
295 $self->debug('draw_prompt', $s);
296 $self->draw_clipped($y, $x, undef, $s);
297 $x += length($s) + 1;
303 my ($self, $config, $matches_remove, $matches_add) = @_;
305 foreach (@{$matches_remove}) {
306 $self->draw($_->{y}, $_->{x}, Curses::A_NORMAL, $_->{string});
309 my $attr_id = $config->{attribute}{match_id};
310 my $attr_string = $config->{attribute}{match_string};
311 my $attr_last = $config->{attribute}{match_last};
313 foreach (@{$matches_add}) {
314 my $attr = (defined $_->{id} and $_->{id} == 1)
317 $self->draw($_->{y}, $_->{x}, $attr, $_->{string});
318 if (defined $_->{id}) {
319 $self->draw($_->{y}, $_->{x}, $attr_id, $_->{id});
326 my ($self, @args) = @_;
328 my $attr = $self->color_pair(Curses::COLOR_RED, -1) | Curses::A_BOLD;
330 # Clear the screen to improve visibility of the error message.
331 $self->{curses}->clear;
333 my $y = $self->draw(0, 0, $attr, "@args");
335 if ($self->{debug}) {
338 require Devel::StackTrace;
341 $msg = "Devel::StackTrace missing, no stack trace.\n";
343 my $trace = Devel::StackTrace->new;
344 $msg = "Stack trace:\n" . $trace->as_string;
346 $y = $self->draw($y + 1, 0, Curses::A_NORMAL, $msg);
349 $self->draw($y + 1, 0, Curses::A_NORMAL,
350 'Press any key to terminate fcscs.');
358 my ($self, $module, @args) = @_;
360 return if not $self->{debug};
362 state $fh; # only open the file once per run
363 if (not defined $fh) {
364 # Ignore errors if the directory doesn't exist.
365 if (not open $fh, '>', "$ENV{HOME}/.config/fcscs/log") {
366 $fh = undef; # a failed open still writes a value to $fh
373 $_ = $self->encode($_);
375 say $fh "$module: @args" or CORE::die $!;
381 my ($self, %settings) = @_;
383 foreach (keys %settings) {
384 CORE::die if not exists $self->{prompt}{$_};
385 $self->{prompt}{$_} = $settings{$_};
390 # Wrapper for Curses.
391 sub width { return $Curses::COLS; }
392 sub height { return $Curses::LINES; }
393 sub refresh { return $_[0]->{curses}->refresh; }
394 sub getch { return $_[0]->{curses}->getch; }
395 sub cursor { Curses::curs_set($_[1]); return; }
403 my ($screen, $input_ref) = @_;
405 # Make sure the input fits on the screen by removing the top lines if
407 splice @{$input_ref}, 0, -$screen->height;
409 # Pad each line with spaces to the screen width to correctly handle
410 # multi-line regexes.
411 # FIXME: wide characters
412 my @padded = map { sprintf '%-*s', $screen->width, $_ } @{$input_ref};
414 my $string = join "\n", @padded;
418 width => $screen->width + 1,
419 # + 1 = "\n", used in input_match_offset_to_coordinates
423 sub input_match_offset_to_coordinates {
424 my ($width, $offset) = @_;
426 die unless defined $offset;
428 my $y = int($offset / $width);
429 my $x = $offset - $y * $width;
433 sub get_regex_matches {
434 my ($input, $regex) = @_;
437 while ($input->{string} =~ /$regex/g) {
439 die "Match group required in regex '$regex'" if not defined $offset;
441 my ($x, $y) = input_match_offset_to_coordinates($input->{width},
443 push @matches, { x => $x, y => $y, offset => $offset, string => $1 };
450 my ($screen, $cmd) = @_;
452 $screen->debug('run_command', "running @{$cmd}");
455 # Perl's system() combined with a $SIG{__WARN__} which die()s has
456 # issues due to the fork. The die() in the __WARN__ handler doesn't
457 # die but the program continues after the system().
459 # If the forked process fails to exec (e.g. program not found) then
460 # the __WARN__ handler is called (because a warning is about to be
461 # displayed) and the die() should display a message and terminate the
462 # process. But due to the fork it doesn't terminate the parent process
463 # and instead changes the return value of system(); it's no longer -1
464 # which makes it impossible to detect that case.
466 # Perl < 5.18 (found in 5.14) doesn't setup $$ during system() which
467 # makes it impossible to detect if the handler was called from inside
470 # Instead, just ignore any warnings during the system(). Thanks to
471 # mauke in #perl on Freenode (2013-10-29 23:30 CET) for the idea to
472 # use no warnings and anno for testing a more recent Perl version with
476 my @cmd = map { $screen->encode($_) } @{$cmd};
477 system { $cmd[0] } @cmd;
482 $msg = 'failed to execute: ' . $!;
484 $msg = 'killed by signal ' . ($? & 127);
486 $msg = 'exited with code ' . ($? >> 8);
488 die "system(@{$cmd}) $msg.";
492 sub run_in_background {
493 my ($screen, $sub) = @_;
495 $screen->debug('run_in_background', "running $sub");
498 defined $pid or die $!;
501 # The terminal multiplexer sends a SIGHUP to the process when it
502 # closes the window (because the parent process has exited).
503 local $SIG{HUP} = 'IGNORE';
505 # Necessary for GNU screen or it'll keep the window open until an
506 # external command has run.
508 my $devnull = File::Spec->devnull();
509 open STDIN, '<', $devnull or die $!;
510 open STDOUT, '>', $devnull or die $!;
511 open STDERR, '>', $devnull or die $!;
513 # Double-fork to prevent zombies.
515 defined $pid or die $!;
516 if ($pid == 0) { # child
521 waitpid $pid, 0 or die $!;
527 my ($name, $screen, $config, $input, $matches) = @_;
529 $screen->debug('select_match', 'started');
531 return if @{$matches} == 0;
532 # Don't return on initial run to give the user a chance to select another
533 # mode, e.g. to switch from URL selection to search selection.
534 if (@{$matches} == 1 and not $config->{state}{initial}) {
535 return { match => $matches->[0] };
537 $config->{state}{initial} = 0;
539 my @sorted = sort { $b->{y} <=> $a->{y} or $b->{x} <=> $a->{x} } @{$matches};
546 $screen->prompt(name => $name, value => undef);
547 $screen->draw_prompt($config);
549 $screen->draw_matches($config, [], $matches);
554 my $char = $screen->getch;
555 if ($char =~ /^\d$/) {
556 $number = $number * 10 + $char;
557 } elsif ($char eq "\b" or $char eq "\x7f") { # backspace
558 $number = int($number / 10);
559 } elsif ($char eq "\n"
560 or $char eq $config->{setting}{alternative_return}) {
561 if ($number == 0) { # number without selection matches last entry
566 # Selecting a new mode requires falling through into the main input
567 # loop and then starting the new mode.
568 } elsif (defined $config->{mapping}{mode}{$char}) {
569 $screen->draw_matches($config, $matches, []); # clear matches
570 return { key => $char };
571 # All other mappings stay in the current mode.
572 } elsif (defined (my $m = $config->{mapping}{simple}{$char})) {
573 $m->($char, $screen, $config, $input);
577 next; # ignore unknown mappings
580 last if $number > 0 and $number * 10 > @{$matches}; # unique match
582 my @remaining = $number == 0
584 : grep { $_->{id} =~ /^$number/ } @{$matches};
585 $screen->draw_matches($config, $matches, \@remaining);
589 $screen->draw_matches($config, $matches, []); # remove matches
591 foreach (@{$matches}) {
592 return { match => $_ } if $_->{id} == $number;
594 $screen->debug('select_match', 'no match selected');
595 return { match => undef };
598 sub extend_match_regex_left {
599 my ($line, $match, $regex) = @_;
601 my $s = reverse substr $line, 0, $match->{x};
602 if ($s =~ /^($regex)/) {
603 $match->{string} = reverse($1) . $match->{string};
604 $match->{x} -= length $1;
605 $match->{offset} -= length $1;
609 sub extend_match_regex_right {
610 my ($line, $match, $regex) = @_;
612 my $s = substr $line, $match->{x} + length $match->{string};
613 if ($s =~ /^($regex)/) {
614 $match->{string} .= $1;
619 my ($screen, $config, $input, $match) = @_;
621 $screen->debug('extend_match', 'started');
623 return if not defined $match;
625 $screen->prompt(name => 'extend', value => undef);
626 $screen->draw_prompt($config);
628 delete $match->{id}; # don't draw any match ids
629 $screen->draw_matches($config, [], [$match]);
632 my $line = $input->{lines}[$match->{y}];
635 my $match_old = \%{$match};
637 my $char = $screen->getch;
639 or $char eq $config->{setting}{alternative_return}) {
642 } elsif ($char eq 'w') { # select current word (both directions)
643 extend_match_regex_left($line, $match, qr/\w+/);
644 extend_match_regex_right($line, $match, qr/\w+/);
645 } elsif ($char eq 'b') { # select current word (only left)
646 extend_match_regex_left($line, $match, qr/\w+/);
647 } elsif ($char eq 'e') { # select current word (only right)
648 extend_match_regex_right($line, $match, qr/\w+/);
650 } elsif ($char eq 'W') { # select current WORD (both directions)
651 extend_match_regex_left($line, $match, qr/\S+/);
652 extend_match_regex_right($line, $match, qr/\S+/);
653 } elsif ($char eq 'B') { # select current WORD (only left)
654 extend_match_regex_left($line, $match, qr/\S+/);
655 } elsif ($char eq 'E') { # select current WORD (only right)
656 extend_match_regex_right($line, $match, qr/\S+/);
658 } elsif ($char eq '0') { # select to beginning of line
659 extend_match_regex_left($line, $match, qr/.+/);
660 } elsif ($char eq '$') { # select to end of line
661 extend_match_regex_right($line, $match, qr/.+/);
663 # Allow mode changes if not overwritten by local mappings.
664 } elsif (defined $config->{mapping}{mode}{$char}) {
665 $screen->draw_matches($config, [$match_old], []); # clear match
666 return { key => $char };
669 next; # ignore unknown mappings
672 $screen->draw_matches($config, [$match_old], [$match]);
676 $screen->debug('extend_match', 'done');
678 return { match => $match };
683 my ($key, $screen, $config, $input) = @_;
685 $screen->debug('mapping_paste', 'started');
687 $config->{state}{handler} = $config->{handler}{paste};
689 $screen->prompt(flags => 'P'); # paste
690 $screen->draw_prompt($config);
696 my ($key, $screen, $config, $input) = @_;
698 $screen->debug('mapping_yank', 'started');
700 $config->{state}{handler} = $config->{handler}{yank};
702 $screen->prompt(flags => 'Y'); # yank
703 $screen->draw_prompt($config);
712 Normal modes select matches by calling a function which returns them, e.g. by
715 The following normal modes are available:
719 =item B<path mode> select relative/absolute paths
721 =item B<url mode> select URLs
723 =item B<ip mode> select IPv4 and IPv6 addresses
728 sub mapping_mode_path {
729 my ($key, $screen, $config, $input) = @_;
731 $screen->debug('mapping_mode_path', 'started');
733 my @matches = get_regex_matches($input, $config->{regex}{path});
735 select => 'path select',
736 matches => \@matches,
737 handler => $config->{handler}{yank},
740 sub mapping_mode_url {
741 my ($key, $screen, $config, $input) = @_;
743 $screen->debug('mapping_mode_url', 'started');
745 my @matches = get_regex_matches($input, $config->{regex}{url});
747 select => 'url select',
748 matches => \@matches,
749 handler => $config->{handler}{url},
752 sub mapping_mode_ip {
753 my ($key, $screen, $config, $input) = @_;
755 $screen->debug('mapping_mode_ip', 'started');
757 my @ipv4 = get_regex_matches($input, $config->{regex}{ipv4});
758 my @ipv6 = get_regex_matches($input, $config->{regex}{ipv6});
760 select => 'ip select',
761 matches => [@ipv4, @ipv6],
762 handler => $config->{handler}{ip},
766 =head2 SEARCH MODE (AND EXTEND MODE)
768 Search mode is a special mode which lets you type a search string (a Perl
769 regex) and then select one of the matches. Afterwards you can extend the
770 match. For example select the complete word or to the end of the line. This
771 allows quick selection of arbitrary text.
773 The following mappings are available during the extension mode (not
774 configurable at the moment):
778 =item B<w> select current word
780 =item B<b> extend word to the left
782 =item B<e> extend word to the right
784 =item B<W> select current WORD
786 =item B<B> extend WORD to the left
788 =item B<E> extend WORD to the right
790 =item B<0> extend to beginning of line
792 =item B<$> extend to end of line
796 C<word> includes any characters matching C<\w+>, C<WORD> any non-whitespace
797 characters (C<\S+>), just like in Vim.
800 sub mapping_mode_search {
801 my ($key, $screen, $config, $input) = @_;
803 $screen->debug('mapping_mode_search', 'started');
807 my $search = ''; # encoded
810 # getch doesn't return decoded characters but raw input bytes. Wait
811 # until the input character is complete.
812 my $value = $screen->decode($search);
813 $value = '' unless defined $value; # undef on decode failure
815 $screen->prompt(name => 'search', value => $value);
816 $screen->draw_prompt($config);
819 my $char = $screen->getch;
820 # TODO: readline editing support
823 } elsif ($char eq "\b" or $char eq "\x7f") { # backspace
824 # Remove a character, not a byte.
825 $search = $screen->decode($search);
827 $search = $screen->encode($search);
830 next unless defined $screen->decode($search);
836 if (($config->{setting}{smartcase} and $search eq lc $search)
837 or $config->{setting}{ignorecase}) {
840 # Ignore invalid regexps.
841 # TODO: display warning on error?
843 @matches = get_regex_matches($input, qr/($case$search)/);
846 $screen->draw_matches($config, \@last_matches, \@matches);
847 @last_matches = @matches;
852 $screen->prompt(name => undef, value => undef); # clear prompt
853 $screen->draw_prompt($config);
855 $screen->debug('mapping_mode_search', 'done');
859 matches => \@last_matches,
861 handler => $config->{handler}{yank},
866 my ($key, $screen, $config, $input) = @_;
868 # Key is necessary to fall through to main event loop which then quits.
869 return { key => $key, quit => 1 };
874 my ($screen, $config, $match) = @_;
876 $screen->debug('handler_yank', 'started');
880 # Use a temporary file to prevent leaking the yanked data to other users
881 # with the command line, e.g. ps aux or top.
882 my ($fh, $tmp) = File::Temp::tempfile(); # dies on its own
883 print $fh $screen->encode($match->{value}) or die $!;
886 if ($config->{setting}{multiplexer} eq 'screen') {
887 $screen->debug('handler_yank', 'using screen');
889 # GNU screen displays an annoying "Slurping X characters into buffer".
890 # Use 'msgwait 0' as a hack to disable it.
891 my $msgwait = $config->{setting}{screen_msgwait};
892 run_command($screen, ['screen', '-X', 'msgwait', 0]);
893 run_command($screen, ['screen', '-X', 'readbuf', $tmp]);
894 run_command($screen, ['screen', '-X', 'msgwait', $msgwait]);
895 } elsif ($config->{setting}{multiplexer} eq 'tmux') {
896 $screen->debug('handler_yank', 'using tmux');
898 run_command($screen, ['tmux', 'load-buffer', $tmp]);
900 die 'unsupported multiplexer';
903 unlink $tmp or die $!;
905 if ($config->{setting}{yank_x11}) {
906 $screen->debug('handler_yank', 'setting X11 selection');
908 my @xsel_cmd = qw( xsel --input --primary );
909 my @xclip_cmd = qw( xclip -in -selection primary );
913 # We don't care if a program doesn't exist.
916 if (not open $fh, '|-', @xsel_cmd) {
917 if (not open $fh, '|-', @xclip_cmd) {
918 die "install xsel or xlip to yank to X11 selection\n";
922 print $fh $match->{value} or die $!;
929 my ($screen, $config, $match) = @_;
931 $screen->debug('handler_paste', 'started');
936 if ($config->{setting}{multiplexer} eq 'screen') {
937 $screen->debug('handler_paste', 'using screen');
938 @cmd = qw( screen -X paste . );
939 } elsif ($config->{setting}{multiplexer} eq 'tmux') {
940 $screen->debug('handler_paste', 'using tmux');
941 @cmd = qw( tmux paste-buffer );
943 die 'unsupported multiplexer';
946 run_in_background($screen, sub {
947 # We need to get the data in the paste buffer before we can paste
949 handler_yank($screen, $config, $match);
951 # Sleep until we switch back to the current window.
952 Time::HiRes::usleep($config->{setting}{paste_sleep});
954 run_command($screen, \@cmd);
959 my ($screen, $config, $match) = @_;
961 $screen->debug('handler_url', "opening $match->{value}");
963 run_in_background($screen, sub {
964 my @cmd = ( @{$config->{setting}{browser}}, $match->{value} );
965 run_command($screen, \@cmd);
972 # CONFIGURATION DEFAULTS
976 fcscs is configured through F<~/.fcscsrc> or F<~/.config/fcscs/fcscsrc> which
977 is a normal Perl script with all of Perl's usual features.
979 All configuration values are stored in the hash C<%config>. All manually
980 defined keys overwrite the default settings.
982 A simple F<~/.fcscsrc> could look like this (for details about the used
988 use Curses; # for COLOR_* and A_* constants
992 # Draw matches in blue.
993 $config{attribute}{match_string} = color_pair(COLOR_BLUE, -1);
994 # Draw numbers in bold yellow.
995 $config{attribute}{match_id} = color_pair(COLOR_YELLOW, -1)
997 # Disable Vim-like 'smartcase', ignore case until an upper character is
999 $config{setting}{smartcase} = 0;
1001 # Use chromium to open URLs if running under X, elinks otherwise.
1002 if (defined $ENV{DISPLAY}) {
1003 $config{setting}{browser} = ['chromium'];
1005 $config{setting}{browser} = ['elinks', '-remote'];
1008 # Let fcscs know the file was loaded successfully.
1016 Pod::Usage::pod2usage(2);
1020 # Determine terminal encoding from the environment ($ENV{LANG} or similar).
1021 my $encoding = I18N::Langinfo::langinfo(I18N::Langinfo::CODESET);
1023 my $screen = Screen->init($encoding);
1025 # We must restore the screen before exiting.
1026 local $SIG{INT} = sub {
1030 # Make all warnings fatal to make sure they don't get lost (stderr is normally
1032 local $SIG{__WARN__} = sub {
1033 $screen->die('warning', @_);
1040 I<NOTE>: Mappings are split in two categories: Mode mappings which change the
1041 selection and may receive additional input (e.g. a search string) and simple
1042 mappings which only change some config value. Mode mappings are configured via
1043 C<$config{mapping}{mode}>, simple mappings via C<$config{mapping}{simple}>.
1045 The following mode mappings are available by default (the function to remap
1046 them in parentheses):
1050 =item B<f> select absolute/relative paths (C<\&mapping_mode_path>)
1052 =item B<u> select URLs (C<\&mapping_mode_url>)
1054 =item B<i> select IPv4 and IPv6 addresses (C<\&mapping_mode_ip>)
1056 =item B</> search for regex to get selection (C<\&mapping_mode_search>)
1058 =item B<q> quit fcscs (C<\&mapping_quit>)
1062 The following simple mappings are available by default:
1066 =item B<p> enable pasting (C<\&mapping_paste>)
1068 =item B<y> enable yanking (copying) (C<\&mapping_yank>)
1072 Note that yanking only uses the GNU screen or Tmux paste buffer by default. To
1073 also copy to X11 selection, enable the B<yank_x11> option.
1075 The following additional mappings are available by default:
1079 =item B<\n> accept current selection (not customizable)
1081 =item B<s> additional key to accept selection (B<alternative_return> option)
1085 All (single-byte) keys except numbers, backspace and return can be mapped.
1087 Unknown mappings are ignored when pressing keys.
1089 To remove a default mapping, delete it from the mapping hash.
1093 # Map 'p' to select paths, 'P' to enable pasting.
1094 $config{mapping}{mode}{p} = \&mapping_mode_path;
1095 $config{mapping}{simple}{P} = \&mapping_paste;
1097 # Disable 'f' mapping.
1098 delete $config{mapping}{mode}{f};
1101 my %mapping_mode = (
1102 f => \&mapping_mode_path,
1103 u => \&mapping_mode_url,
1104 i => \&mapping_mode_ip,
1105 '/' => \&mapping_mode_search,
1106 q => \&mapping_quit,
1108 my %mapping_simple = (
1109 p => \&mapping_paste,
1110 y => \&mapping_yank,
1115 Attributes are used to style the output. They must be Curses attributes.
1116 Defaults in parentheses (foreground, background, attribute).
1120 =item B<match_id> attribute for match numbers (red, default, bold)
1122 =item B<match_string> attribute for matches (yellow, default, normal)
1124 =item B<match_last> attribute for the match selected by return (yellow, default, underline)
1126 =item B<prompt_name> attribute for prompt name (standout)
1128 =item B<prompt_flags> attribute for prompt flags (standout)
1134 # Draw prompt flags in bold red with default background color.
1135 $config{attribute}{prompt_flags}
1137 | color_pair(Curses::COLOR_RED, -1);
1141 match_id => $screen->color_pair(Curses::COLOR_RED, -1)
1143 match_string => $screen->color_pair(Curses::COLOR_YELLOW, -1),
1144 match_last => $screen->color_pair(Curses::COLOR_YELLOW, -1)
1145 | Curses::A_UNDERLINE,
1146 prompt_name => Curses::A_STANDOUT,
1147 prompt_flags => Curses::A_STANDOUT,
1152 Defaults in parentheses.
1156 =item B<debug> enable debug mode, writes to I<~/.config/fcscs/log> (C<0>)
1158 =item B<initial_mode> start in this mode, must be a valid mode mapping (C<\&mapping_mode_url>)
1160 =item B<multiplexer> set multiplexer ("screen" or "tmux") if not autodetected (C<undef>)
1162 =item B<ignorecase> ignore case when searching (C<0>)
1164 =item B<smartcase> ignore case unless one uppercase character is searched (C<1>)
1166 =item B<yank_x11> copy selection also to X11 primary selection when yanking (C<0>)
1168 =item B<paste_sleep> sleep x us before running paste command (C<100_000>)
1170 =item B<screen_msgwait> GNU Screen's msgwait variable, used when yanking (C<5>)
1172 =item B<alternative_return> additional accept key like return, set to C<\n> to disable (C<s>)
1174 =item B<browser> browser command as array reference (C<['x-www-browser']>)
1180 # Select paths on startup instead of URLs.
1181 $config{setting}{initial_mode} = \&mapping_mode_path;
1187 initial_mode => \&mapping_mode_url,
1188 multiplexer => undef,
1192 paste_sleep => 100_000,
1193 screen_msgwait => 5,
1195 alternative_return => 's',
1197 browser => ['x-www-browser'],
1204 =item B<url> used by C<\&mapping_mode_url>
1206 =item B<path> used by C<\&mapping_mode_path>
1208 =item B<ipv4> used by C<\&mapping_mode_ip>
1210 =item B<ipv6> used by C<\&mapping_mode_ip>
1216 # Select all non-whitespace characters when searching for paths.
1217 $config{regex}{path} = qr{(\S+)};
1221 # Taken from urlview's default configuration file, thanks.
1222 url => qr{((?:(?:(?:http|https|ftp|gopher)|mailto):(?://)?[^ <>"\t]*|(?:www|ftp)[0-9]?\.[-a-z0-9.]+)[^ .,;\t\n\r<">\):]?[^, <>"\t]*[^ .,;\t\n\r<">\):])},
1223 path => qr{(~?[a-zA-Z0-9_./-]*/[a-zA-Z0-9_./-]+)},
1224 # IP addresses with optional prefix. Not perfectly accurate but good
1226 ipv4 => qr!\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?:/\d{1,2})?)\b!,
1227 ipv6 => qr!\b((?:[0-9a-fA-F]{1,4})?(?::+[0-9a-fA-F]{1,4})+(?:/\d{1,3})?)\b!,
1232 Handlers are used to perform actions on the selected string.
1234 The following handlers are available, defaults in parentheses.
1238 =item B<yank> used to yank (copy) selection to paste buffer (C<\&handler_yank>)
1240 =item B<paste> used to paste selection into window (C<\&handler_paste>)
1242 =item B<url> used to open URLs (e.g. in a browser) (C<\&handler_url>)
1244 =item B<ip> used to handle IPs (C<\&handler_yank>)
1250 # Download YouTube videos with a custom wrapper, handle all other URLs
1251 # with the default URL handler.
1252 $config{handler}{url} = sub {
1253 my ($screen, $config, $match) = @_;
1255 if ($match->{value} =~ m{^https://www.youtube.com/}) {
1256 return run_in_background($screen, sub {
1257 run_command($screen, ['youtube-dl-wrapper', $match->{value}]);
1265 yank => \&handler_yank,
1266 paste => \&handler_paste,
1267 url => \&handler_url,
1268 ip => \&handler_yank,
1272 initial => 1, # used by select_match() for 'initial_mode'
1278 # CONFIGURATION "API"
1282 The following functions are available:
1284 color_pair($fg, $bg)
1286 Create a new Curses attribute with the given fore- and background color.
1291 mapping_mode_search()
1297 Used as mappings, see L</MAPPINGS> above.
1303 Used as handler to yank, paste selection or open URL in browser.
1310 Helper functions when writing custom mappings, see the source for details.
1314 # Enhance URL mode by updating the mapping.
1315 $config{mapping}{mode}{u} = sub {
1316 my ($key, $screen, $config, $input) = @_;
1318 # First get matches of normal URL mode.
1319 my $result = mapping_mode_url(@_);
1321 # Add all strings matching "CVE-1234-1234" with URLs pointing to the
1322 # Debian security tracker. "->{value}" is the string which is used as
1323 # result of the match (e.g. the URL in this case).
1324 my @matches = get_regex_matches($input, qr/\b(CVE-\d+-\d+)\b/);
1325 foreach (@matches) {
1326 $_->{value} = "https://security-tracker.debian.org/$_->{string}";
1328 push @{$result->{matches}}, @matches;
1330 # Change all YouTube links to use the custom "youtube" handler (see
1331 # below). This will allow us to automatically open YouTube URLs with a
1332 # custom program, like `youtube-dl` or `mpv`.
1333 foreach (@{$result->{matches}}) {
1334 if ($_->{string} =~ m{^https://www.youtube.com/}) {
1335 $_->{handler} = $config{handler}{youtube};
1341 # Also update initial mode to use our new "URL mode".
1342 $config{setting}{initial_mode} = $config{mapping}{mode}{u};
1344 # Special handler to download YouTube URLs with `youtube-dl`. You could
1345 # also use `mpv` here to immediately play them.
1346 $config{handler}{youtube} = sub {
1347 my ($screen, $config, $match) = @_;
1349 return run_in_background($screen, sub {
1350 run_command($screen, ['youtube-dl', $match->{value}]);
1358 # All variables and functions which are usable by ~/.fcscsrc.
1360 our $screen; # "private"
1363 sub color_pair { return $screen->color_pair(@_); }
1365 sub mapping_mode_path { return main::mapping_mode_path(@_); }
1366 sub mapping_mode_url { return main::mapping_mode_url(@_); }
1367 sub mapping_mode_ip { return main::mapping_mode_ip(@_); }
1368 sub mapping_mode_search { return main::mapping_mode_search(@_); }
1370 sub mapping_paste { return main::mapping_paste(@_); }
1371 sub mapping_yank { return main::mapping_yank(@_); }
1372 sub mapping_quit { return main::mapping_quit(@_); }
1374 sub handler_yank { return main::handler_yank(@_); }
1375 sub handler_paste { return main::handler_paste(@_); }
1376 sub handler_url { return main::handler_url(@_); }
1378 sub debug { return main::debug(@_); }
1380 sub get_regex_matches { return main::get_regex_matches(@_); }
1381 sub select_match { return main::select_match(@_); }
1383 sub run_command { return main::run_command(@_); }
1384 sub run_in_background { return main::run_in_background(@_); }
1386 $Fcscs::screen = $screen;
1392 # Alias %config and %Fcscs::config. %config is less to type.
1394 local *config = \%Fcscs::config;
1396 $config{mapping}{mode} = \%mapping_mode;
1397 $config{mapping}{simple} = \%mapping_simple;
1398 $config{attribute} = \%attribute;
1399 $config{setting} = \%setting;
1400 $config{regex} = \%regex;
1401 $config{handler} = \%handler;
1402 $config{state} = \%state;
1405 my @configs = ("$ENV{HOME}/.fcscsrc",
1406 "$ENV{HOME}/.config/fcscs/fcscsrc");
1407 foreach my $path (@configs) {
1408 my $decoded = $screen->decode($path);
1410 # Load configuration file. Checks have a race condition if the home
1411 # directory is writable by an attacker (but then the user is screwed
1413 next unless -e $path;
1415 $screen->die("Config '$decoded' not owned by current user!");
1417 # Make sure the file is not writable by other users. Doesn't handle
1418 # ACLs and see comment above about race conditions.
1419 my @stat = stat $path or die $!;
1420 my $mode = $stat[2];
1421 if (($mode & Fcntl::S_IWGRP) or ($mode & Fcntl::S_IWOTH)) {
1422 die "Config '$decoded' must not be writable by other users.";
1425 my $result = do $path;
1427 $screen->die("Failed to parse '$decoded': $@") if $@;
1428 $screen->die("Failed to do '$decoded': $!") unless defined $result;
1429 $screen->die("Failed to run '$decoded'.");
1432 last; # success, don't load more files
1435 $screen->{debug} = $config{setting}{debug};
1441 # Auto-detect current multiplexer.
1442 if (not defined $config{setting}{multiplexer}) {
1443 if (defined $ENV{STY} and defined $ENV{TMUX}) {
1444 die 'Found both $STY and $TMUX, set $config{setting}{multiplexer}.';
1445 } elsif (defined $ENV{STY}) {
1446 $config{setting}{multiplexer} = 'screen';
1447 } elsif (defined $ENV{TMUX}) {
1448 $config{setting}{multiplexer} = 'tmux';
1450 die 'No multiplexer found.';
1454 my $binmode = $encoding;
1455 # GNU screen stores the screen dump for unknown reasons as ISO-8859-1
1456 # instead of the currently active encoding.
1457 if ($config{setting}{multiplexer} eq 'screen') {
1458 $binmode = 'ISO-8859-1';
1462 open my $fh, '<', $ARGV[0] or die $!;
1463 binmode $fh, ":encoding($binmode)" or die $!;
1466 push @input_lines, $_;
1468 close $fh or die $!;
1470 my $input = prepare_input($screen, \@input_lines);
1472 # Display original screen content.
1474 foreach (@{$input->{lines}}) {
1475 $screen->draw_simple($y++, 0, undef, $_);
1480 my $mapping = $config{setting}{initial_mode};
1484 if (not defined $mapping) {
1485 $key = $screen->getch unless defined $key;
1486 $screen->debug('input', "got key '$key'");
1488 $mapping = $config{mapping}{mode}{$key};
1489 $mapping = $config{mapping}{simple}{$key} unless defined $mapping;
1490 if (not defined $mapping) { # ignore unknown mappings
1496 $screen->debug('input', 'running mapping');
1497 my $result = $mapping->($key, $screen, \%config, $input);
1501 if (defined $result->{quit}) {
1502 $screen->debug('input', 'quitting');
1505 if (defined $result->{key}) {
1506 $key = $result->{key}; # lookup another mapping
1507 $screen->debug('input', "processing new key: '$key'");
1510 if (defined $result->{select}) {
1511 $screen->debug('input', 'selecting match');
1513 $result = select_match($result->{select},
1514 $screen, \%config, $input,
1515 $result->{matches});
1516 $result->{handler} = $tmp->{handler};
1517 $result->{extend} = $tmp->{extend};
1518 goto RESULT; # reprocess special entries in result
1520 if (defined $result->{extend}) {
1521 $screen->debug('input', 'extending match');
1522 $result = extend_match($screen, \%config, $input,
1524 goto RESULT; # reprocess special entries in result
1526 if (defined $result->{match}) {
1527 if (not defined $result->{match}{value}) {
1528 $result->{match}{value} = $result->{match}{string};
1531 $screen->debug('input', 'running handler');
1533 # Choose handler with falling priority.
1535 $config{state}{handler}, # set by user
1536 $result->{match}{handler}, # set by match
1537 $result->{handler}, # set by mapping
1538 $config{handler}{yank}, # fallback
1540 foreach my $handler (@handlers) {
1541 next unless defined $handler;
1543 $handler->($screen, \%config, $result->{match});
1549 $key = undef; # get next key from user
1574 Invalid arguments/options.
1580 Simon Ruderich E<lt>simon@ruderich.orgE<gt>
1582 =head1 LICENSE AND COPYRIGHT
1584 Copyright (C) 2013-2016 by Simon Ruderich
1586 This program is free software: you can redistribute it and/or modify
1587 it under the terms of the GNU General Public License as published by
1588 the Free Software Foundation, either version 3 of the License, or
1589 (at your option) any later version.
1591 This program is distributed in the hope that it will be useful,
1592 but WITHOUT ANY WARRANTY; without even the implied warranty of
1593 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1594 GNU General Public License for more details.
1596 You should have received a copy of the GNU General Public License
1597 along with this program. If not, see E<lt>http://www.gnu.org/licenses/E<gt>.
1601 L<screen(1)>, L<tmux(1)>, L<urlview(1)>