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):
67 - c: checksums (e.g. MD5, SHA1, ..)
71 - select match by displayed number or <return> for lowest numbered
73 - configured action is run, e.g. URL is opened with browser
75 - perform incremental search
76 - on <return> go to `normal' mode to select a match
77 - after the match is selected wait for confirmation or extension
78 - confirmation: <return> run previously selected action
79 - extension: change match, e.g. select complete word or line
81 GNU Screen setup (add to F<~/.screenrc>):
83 bind ^B eval "hardcopy $HOME/.tmp/screen-fcscs" "screen fcscs $HOME/.tmp/screen-fcscs"
85 Tmux setup (add to F<~/.tmux.conf>):
87 bind-key C-b capture-pane \; save-buffer ~/.tmp/tmux-fcscs \; delete-buffer \; new-window "fcscs ~/.tmp/tmux-fcscs"
89 This requires a writable ~/.tmp directory. Adapt the mapping according to your
90 preferences. Ensure these files are not readable by others as they can contain
91 private data (umask or protected directory). B<fcscs> must be in your C<$PATH>
92 for the above mappings to work.
94 Pressing the configured mapping (Prefix Ctrl-B in this example) opens B<fcscs>
95 in a new GNU screen/Tmux window. After selection, the content is either passed
96 to external programs (e.g. for URLs) or copied to the paste buffer or directly
97 pasted in your previous window and the new window is closed.
99 To select a match just type its number. If the match is unique, the entry is
100 automatically selected (e.g. you press 2 and there are only 19 matches). If
101 there are multiple matches left (e.g. you press 1 and there are more than ten
102 matches available), press return to select the current match (1 in this case)
103 or another number to select the longer match. Use backspace to remove the last
106 Press return before entering a number to select the last (lowest numbered)
107 match (underlined by default). To abort without selecting any match use "q".
109 To change the selection mode (e.g. paths, files, etc.) use one of the mappings
110 explained below. Per default URLs are selected, see options for a way to
113 I<NOTE>: Opening URLs in the browser passes the URL via the command line which
114 leaks URLs to other users on the current system via C<ps aux> or C<top>.
116 I<NOTE>: When yanking (copying) a temporary file is used to pass the data to
117 GNU screen/Tmux without exposing it to C<ps aux> or C<top>. However this may
118 leak data if those temporary files are written to disk. To prevent this change
119 your C<$TMP> to point to a memory-only location or encrypted storage.
121 If no window appears, try running B<fcscs> manually to catch the error message
122 and please report the bug:
124 fcscs /path/to/screen-or-tmux-fcscs-file
134 # Helper class for drawing on the screen using Curses.
137 my ($class, $encoding) = @_;
139 # Prefer strict UTF-8 handling (see perldoc Encode); just in case.
140 if (lc $encoding eq 'utf8') {
143 # Get Encode object to speed up decode()/encode().
144 my $encoding_object = Encode::find_encoding($encoding);
145 die "unsupported encoding '$encoding'" unless ref $encoding_object;
147 my $curses = Curses->new or die $!;
150 encoding => $encoding,
151 encoding_object => $encoding_object,
163 # Allow default colors by passing -1 to init_pair. A default color is
164 # not drawn on screen thus allowing terminals with pseudo-transparency
165 # to use the transparent background in place of the default color.
166 Curses::use_default_colors;
185 # Convert between Perl's internal encoding and the terminal's encoding.
187 my ($self, $string) = @_;
188 return $self->{encoding_object}->encode($string);
191 my ($self, $string) = @_;
192 return eval { # returns undef on decode failure
193 $self->{encoding_object}->decode($string, Encode::FB_CROAK);
197 # Create attribute for the given fore-/background colors.
199 my ($self, $fg, $bg) = @_;
201 state $next_color_pair = 1; # must start at 1 for init_pair()
203 Curses::init_pair($next_color_pair, $fg, $bg);
204 return Curses::COLOR_PAIR($next_color_pair++);
207 # Draw a string which must fit in the current line. Wrapping/clipping is
208 # not supported and must be handled by the caller.
210 my ($self, $y, $x, $attributes, $string) = @_;
212 die if $string =~ /\n/;
213 # FIXME: wide characters
214 die if $x + length $string > $self->width;
216 $self->{curses}->attron($attributes) if defined $attributes;
217 $self->{curses}->addstr($y, $x, $self->encode($string));
218 $self->{curses}->attroff($attributes) if defined $attributes;
221 # Like draw_simple(), but the string is automatically clipped.
223 my ($self, $y, $x, $attributes, $string) = @_;
225 # FIXME: wide characters
226 $string = substr $string, 0, $self->width - $x;
227 $self->draw_simple($y, $x, $attributes, $string);
231 my ($self, $y, $x, $attributes, $string) = @_;
233 die unless defined $string;
237 # We must print each line separately. Search for next newline or
238 # line end, whichever is closer.
239 if ($string =~ /\n/) {
242 # FIXME: wide characters
243 if ($x + length $string > $self->width) {
244 my $new_offset = $self->width - $x;
245 if (not defined $offset or $offset > $new_offset) {
246 $offset = $new_offset;
249 last unless defined $offset;
251 # FIXME: wide characters
252 $self->draw_simple($y, $x, $attributes, substr $string, 0, $offset);
254 # Don't draw "\n" itself.
255 if ("\n" eq substr $string, $offset, 1) {
259 $string = substr $string, $offset;
265 $self->draw_simple($y, $x, $attributes, $string);
270 my ($self, $config) = @_;
272 $self->debug('draw_prompt', 'started');
275 my $y = $self->height - 1;
277 # Clear line for better visibility.
278 $self->draw_simple($y, $x, undef, ' ' x $self->width);
281 if (defined (my $s = $self->{prompt}{flags})) {
283 $self->debug('draw_prompt', $s);
284 $self->draw_clipped($y, $x, $config->{attribute}{prompt_flags}, $s);
285 $x += length($s) + 1; # space between next element
288 if (defined (my $s = $self->{prompt}{name})) {
290 $self->debug('draw_prompt', $s);
291 $self->draw_clipped($y, $x, $config->{attribute}{prompt_name}, $s);
292 $x += length($s) + 1;
294 # Draw prompt value, e.g. a search field.
295 if (defined (my $s = $self->{prompt}{value})) {
296 $self->debug('draw_prompt', $s);
297 $self->draw_clipped($y, $x, undef, $s);
298 $x += length($s) + 1;
304 my ($self, $config, $matches_remove, $matches_add) = @_;
306 foreach (@{$matches_remove}) {
307 $self->draw($_->{y}, $_->{x}, Curses::A_NORMAL, $_->{string});
310 my $attr_id = $config->{attribute}{match_id};
311 my $attr_string = $config->{attribute}{match_string};
312 my $attr_last = $config->{attribute}{match_last};
314 foreach (@{$matches_add}) {
315 my $attr = (defined $_->{id} and $_->{id} == 1)
318 $self->draw($_->{y}, $_->{x}, $attr, $_->{string});
319 if (defined $_->{id}) {
320 $self->draw($_->{y}, $_->{x}, $attr_id, $_->{id});
327 my ($self, @args) = @_;
329 my $attr = $self->color_pair(Curses::COLOR_RED, -1) | Curses::A_BOLD;
331 # Clear the screen to improve visibility of the error message.
332 $self->{curses}->clear;
334 my $y = $self->draw(0, 0, $attr, "@args");
336 if ($self->{debug}) {
339 require Devel::StackTrace;
342 $msg = "Devel::StackTrace missing, no stack trace.\n";
344 my $trace = Devel::StackTrace->new;
345 $msg = "Stack trace:\n" . $trace->as_string;
347 $y = $self->draw($y + 1, 0, Curses::A_NORMAL, $msg);
350 $self->draw($y + 1, 0, Curses::A_NORMAL,
351 'Press any key to terminate fcscs.');
359 my ($self, $module, @args) = @_;
361 return if not $self->{debug};
363 state $fh; # only open the file once per run
364 if (not defined $fh) {
365 # Ignore errors if the directory doesn't exist.
366 if (not open $fh, '>', "$ENV{HOME}/.config/fcscs/log") {
367 $fh = undef; # a failed open still writes a value to $fh
374 $_ = $self->encode($_);
376 say $fh "$module: @args" or CORE::die $!;
382 my ($self, %settings) = @_;
384 foreach (keys %settings) {
385 CORE::die if not exists $self->{prompt}{$_};
386 $self->{prompt}{$_} = $settings{$_};
391 # Wrapper for Curses.
392 sub width { return $Curses::COLS; }
393 sub height { return $Curses::LINES; }
394 sub refresh { return $_[0]->{curses}->refresh; }
395 sub getch { return $_[0]->{curses}->getch; }
396 sub cursor { Curses::curs_set($_[1]); return; }
404 my ($screen, $input_ref) = @_;
406 # Make sure the input fits on the screen by removing the top lines if
408 splice @{$input_ref}, 0, -$screen->height;
410 # Pad each line with spaces to the screen width to correctly handle
411 # multi-line regexes.
412 # FIXME: wide characters
413 my @padded = map { sprintf '%-*s', $screen->width, $_ } @{$input_ref};
415 my $string = join "\n", @padded;
419 width => $screen->width + 1,
420 # + 1 = "\n", used in input_match_offset_to_coordinates
424 sub input_match_offset_to_coordinates {
425 my ($width, $offset) = @_;
427 die unless defined $offset;
429 my $y = int($offset / $width);
430 my $x = $offset - $y * $width;
434 sub get_regex_matches {
435 my ($input, $regex) = @_;
438 while ($input->{string} =~ /$regex/g) {
440 die "Match group required in regex '$regex'" if not defined $offset;
442 my ($x, $y) = input_match_offset_to_coordinates($input->{width},
444 push @matches, { x => $x, y => $y, offset => $offset, string => $1 };
451 my ($screen, $cmd) = @_;
453 $screen->debug('run_command', "running @{$cmd}");
456 # Perl's system() combined with a $SIG{__WARN__} which die()s has
457 # issues due to the fork. The die() in the __WARN__ handler doesn't
458 # die but the program continues after the system().
460 # If the forked process fails to exec (e.g. program not found) then
461 # the __WARN__ handler is called (because a warning is about to be
462 # displayed) and the die() should display a message and terminate the
463 # process. But due to the fork it doesn't terminate the parent process
464 # and instead changes the return value of system(); it's no longer -1
465 # which makes it impossible to detect that case.
467 # Perl < 5.18 (found in 5.14) doesn't setup $$ during system() which
468 # makes it impossible to detect if the handler was called from inside
471 # Instead, just ignore any warnings during the system(). Thanks to
472 # mauke in #perl on Freenode (2013-10-29 23:30 CET) for the idea to
473 # use no warnings and anno for testing a more recent Perl version with
477 my @cmd = map { $screen->encode($_) } @{$cmd};
478 system { $cmd[0] } @cmd;
483 $msg = 'failed to execute: ' . $!;
485 $msg = 'killed by signal ' . ($? & 127);
487 $msg = 'exited with code ' . ($? >> 8);
489 die "system(@{$cmd}) $msg.";
493 sub run_in_background {
494 my ($screen, $sub) = @_;
496 $screen->debug('run_in_background', "running $sub");
499 defined $pid or die $!;
502 # The terminal multiplexer sends a SIGHUP to the process when it
503 # closes the window (because the parent process has exited).
504 local $SIG{HUP} = 'IGNORE';
506 # Necessary for GNU screen or it'll keep the window open until an
507 # external command has run.
509 my $devnull = File::Spec->devnull();
510 open STDIN, '<', $devnull or die $!;
511 open STDOUT, '>', $devnull or die $!;
512 open STDERR, '>', $devnull or die $!;
514 # Double-fork to prevent zombies.
516 defined $pid or die $!;
517 if ($pid == 0) { # child
522 waitpid $pid, 0 or die $!;
528 my ($name, $screen, $config, $input, $matches) = @_;
530 $screen->debug('select_match', 'started');
532 return if @{$matches} == 0;
533 # Don't return on initial run to give the user a chance to select another
534 # mode, e.g. to switch from URL selection to search selection.
535 if (@{$matches} == 1 and not $config->{state}{initial}) {
536 return { match => $matches->[0] };
538 $config->{state}{initial} = 0;
540 my @sorted = sort { $b->{y} <=> $a->{y} or $b->{x} <=> $a->{x} } @{$matches};
547 $screen->prompt(name => $name, value => undef);
548 $screen->draw_prompt($config);
550 $screen->draw_matches($config, [], $matches);
555 my $char = $screen->getch;
556 if ($char =~ /^\d$/) {
557 $number = $number * 10 + $char;
558 } elsif ($char eq "\b" or $char eq "\x7f") { # backspace
559 $number = int($number / 10);
560 } elsif ($char eq "\n"
561 or $char eq $config->{setting}{alternative_return}) {
564 # Selecting a new mode requires falling through into the main input
565 # loop and then starting the new mode.
566 } elsif (defined $config->{mapping}{mode}{$char}) {
567 $screen->draw_matches($config, $matches, []); # clear matches
568 return { key => $char };
569 # All other mappings stay in the current mode.
570 } elsif (defined (my $m = $config->{mapping}{simple}{$char})) {
571 my $result = $m->($char, $screen, $config, $input);
572 last if defined $result->{select_match};
576 next; # ignore unknown mappings
579 last if $number > 0 and $number * 10 > @{$matches}; # unique match
581 my @remaining = $number == 0
583 : grep { $_->{id} =~ /^$number/ } @{$matches};
584 $screen->draw_matches($config, $matches, \@remaining);
587 # Number without selection matches last entry.
592 $screen->draw_matches($config, $matches, []); # remove matches
594 foreach (@{$matches}) {
595 return { match => $_ } if $_->{id} == $number;
597 $screen->debug('select_match', 'no match selected');
598 return { match => undef };
601 sub extend_match_regex_left {
602 my ($line, $match, $regex) = @_;
604 my $s = reverse substr $line, 0, $match->{x};
605 if ($s =~ /^($regex)/) {
606 $match->{string} = reverse($1) . $match->{string};
607 $match->{x} -= length $1;
608 $match->{offset} -= length $1;
612 sub extend_match_regex_right {
613 my ($line, $match, $regex) = @_;
615 my $s = substr $line, $match->{x} + length $match->{string};
616 if ($s =~ /^($regex)/) {
617 $match->{string} .= $1;
622 my ($screen, $config, $input, $match) = @_;
624 $screen->debug('extend_match', 'started');
626 return if not defined $match;
628 $screen->prompt(name => 'extend', value => undef);
629 $screen->draw_prompt($config);
631 delete $match->{id}; # don't draw any match ids
632 $screen->draw_matches($config, [], [$match]);
635 my $line = $input->{lines}[$match->{y}];
638 my $match_old = \%{$match};
640 my $char = $screen->getch;
642 or $char eq $config->{setting}{alternative_return}) {
645 } elsif ($char eq 'w') { # select current word (both directions)
646 extend_match_regex_left($line, $match, qr/\w+/);
647 extend_match_regex_right($line, $match, qr/\w+/);
648 } elsif ($char eq 'b') { # select current word (only left)
649 extend_match_regex_left($line, $match, qr/\w+/);
650 } elsif ($char eq 'e') { # select current word (only right)
651 extend_match_regex_right($line, $match, qr/\w+/);
653 } elsif ($char eq 'W') { # select current WORD (both directions)
654 extend_match_regex_left($line, $match, qr/\S+/);
655 extend_match_regex_right($line, $match, qr/\S+/);
656 } elsif ($char eq 'B') { # select current WORD (only left)
657 extend_match_regex_left($line, $match, qr/\S+/);
658 } elsif ($char eq 'E') { # select current WORD (only right)
659 extend_match_regex_right($line, $match, qr/\S+/);
661 } elsif ($char eq '0') { # select to beginning of line
662 extend_match_regex_left($line, $match, qr/.+/);
663 } elsif ($char eq '$') { # select to end of line
664 extend_match_regex_right($line, $match, qr/.+/);
666 # Allow mode changes if not overwritten by local mappings.
667 } elsif (defined $config->{mapping}{mode}{$char}) {
668 $screen->draw_matches($config, [$match_old], []); # clear match
669 return { key => $char };
672 next; # ignore unknown mappings
675 $screen->draw_matches($config, [$match_old], [$match]);
679 $screen->debug('extend_match', 'done');
681 return { match => $match };
686 my ($key, $screen, $config, $input) = @_;
688 $screen->debug('mapping_paste', 'started');
690 $config->{state}{handler} = $config->{handler}{paste};
692 $screen->prompt(flags => 'P'); # paste
693 $screen->draw_prompt($config);
698 sub mapping_paste_now {
699 my ($key, $screen, $config, $input) = @_;
701 $screen->debug('mapping_paste_now', 'started');
703 $config->{state}{handler} = $config->{handler}{paste};
711 my ($key, $screen, $config, $input) = @_;
713 $screen->debug('mapping_yank', 'started');
715 $config->{state}{handler} = $config->{handler}{yank};
717 $screen->prompt(flags => 'Y'); # yank
718 $screen->draw_prompt($config);
723 sub mapping_yank_now {
724 my ($key, $screen, $config, $input) = @_;
726 $screen->debug('mapping_yank_now', 'started');
728 $config->{state}{handler} = $config->{handler}{yank};
738 Normal modes select matches by calling a function which returns them, e.g. by
741 The following normal modes are available:
745 =item B<path mode> select relative/absolute paths
747 =item B<url mode> select URLs
749 =item B<ip mode> select IPv4 and IPv6 addresses
751 =item B<checksum mode> select checksums (MD5, SHA1, SHA256, SHA512)
756 sub mapping_mode_helper {
757 my ($name, $select, $key, $screen, $config, $input) = @_;
759 $screen->debug("mapping_mode_$name", 'started');
761 my @matches = get_regex_matches($input, $config->{regex}{$name});
764 matches => \@matches,
765 handler => $config->{handler}{$name},
768 sub mapping_mode_path {
769 return mapping_mode_helper('path', 'path select', @_);
771 sub mapping_mode_url {
772 return mapping_mode_helper('url', 'url select', @_);
774 sub mapping_mode_ip {
775 my ($key, $screen, $config, $input) = @_;
777 $screen->debug('mapping_mode_ip', 'started');
779 my @ipv4 = get_regex_matches($input, $config->{regex}{ipv4});
780 my @ipv6 = get_regex_matches($input, $config->{regex}{ipv6});
782 select => 'ip select',
783 matches => [@ipv4, @ipv6],
784 handler => $config->{handler}{ip},
787 sub mapping_mode_checksum {
788 return mapping_mode_helper('checksum', 'checksum select', @_);
791 =head2 SEARCH MODE (AND EXTEND MODE)
793 Search mode is a special mode which lets you type a search string (a Perl
794 regex) and then select one of the matches. Afterwards you can extend the
795 match. For example select the complete word or to the end of the line. This
796 allows quick selection of arbitrary text.
798 The following mappings are available during the extension mode (not
799 configurable at the moment):
803 =item B<w> select current word
805 =item B<b> extend word to the left
807 =item B<e> extend word to the right
809 =item B<W> select current WORD
811 =item B<B> extend WORD to the left
813 =item B<E> extend WORD to the right
815 =item B<0> extend to beginning of line
817 =item B<$> extend to end of line
821 C<word> includes any characters matching C<\w+>, C<WORD> any non-whitespace
822 characters (C<\S+>), just like in Vim.
825 sub mapping_mode_search {
826 my ($key, $screen, $config, $input) = @_;
828 $screen->debug('mapping_mode_search', 'started');
832 my $search = ''; # encoded
835 # getch doesn't return decoded characters but raw input bytes. Wait
836 # until the input character is complete.
837 my $value = $screen->decode($search);
838 $value = '' unless defined $value; # undef on decode failure
840 $screen->prompt(name => 'search', value => $value);
841 $screen->draw_prompt($config);
844 my $char = $screen->getch;
845 # TODO: readline editing support
848 } elsif ($char eq "\b" or $char eq "\x7f") { # backspace
849 # Remove a character, not a byte.
850 $search = $screen->decode($search);
852 $search = $screen->encode($search);
855 next unless defined $screen->decode($search);
861 if (($config->{setting}{smartcase} and $search eq lc $search)
862 or $config->{setting}{ignorecase}) {
865 # Ignore invalid regexps.
866 # TODO: display warning on error?
868 @matches = get_regex_matches($input, qr/($case$search)/);
871 $screen->draw_matches($config, \@last_matches, \@matches);
872 @last_matches = @matches;
877 $screen->prompt(name => undef, value => undef); # clear prompt
878 $screen->draw_prompt($config);
880 $screen->debug('mapping_mode_search', 'done');
884 matches => \@last_matches,
886 handler => $config->{handler}{yank},
891 my ($key, $screen, $config, $input) = @_;
893 # Key is necessary to fall through to main event loop which then quits.
894 return { key => $key, quit => 1 };
899 my ($screen, $config, $match) = @_;
901 $screen->debug('handler_yank', 'started');
905 # Use a temporary file to prevent leaking the yanked data to other users
906 # with the command line, e.g. ps aux or top.
907 my ($fh, $tmp) = File::Temp::tempfile(); # dies on its own
908 print $fh $screen->encode($match->{value}) or die $!;
911 if ($config->{setting}{multiplexer} eq 'screen') {
912 $screen->debug('handler_yank', 'using screen');
914 # GNU screen displays an annoying "Slurping X characters into buffer".
915 # Use 'msgwait 0' as a hack to disable it.
916 my $msgwait = $config->{setting}{screen_msgwait};
917 run_command($screen, ['screen', '-X', 'msgwait', 0]);
918 run_command($screen, ['screen', '-X', 'readbuf', $tmp]);
919 run_command($screen, ['screen', '-X', 'msgwait', $msgwait]);
920 } elsif ($config->{setting}{multiplexer} eq 'tmux') {
921 $screen->debug('handler_yank', 'using tmux');
923 run_command($screen, ['tmux', 'load-buffer', $tmp]);
925 die 'unsupported multiplexer';
928 unlink $tmp or die $!;
930 if ($config->{setting}{yank_x11}) {
931 $screen->debug('handler_yank', 'setting X11 selection');
933 my @xsel_cmd = qw( xsel --input --primary );
934 my @xclip_cmd = qw( xclip -in -selection primary );
938 # We don't care if a program doesn't exist.
941 if (not open $fh, '|-', @xsel_cmd) {
942 if (not open $fh, '|-', @xclip_cmd) {
943 die "install xsel or xlip to yank to X11 selection\n";
947 print $fh $match->{value} or die $!;
954 my ($screen, $config, $match) = @_;
956 $screen->debug('handler_paste', 'started');
961 if ($config->{setting}{multiplexer} eq 'screen') {
962 $screen->debug('handler_paste', 'using screen');
963 @cmd = qw( screen -X paste . );
964 } elsif ($config->{setting}{multiplexer} eq 'tmux') {
965 $screen->debug('handler_paste', 'using tmux');
966 @cmd = qw( tmux paste-buffer );
968 die 'unsupported multiplexer';
971 run_in_background($screen, sub {
972 # We need to get the data in the paste buffer before we can paste
974 handler_yank($screen, $config, $match);
976 # Sleep until we switch back to the current window.
977 Time::HiRes::usleep($config->{setting}{paste_sleep});
979 run_command($screen, \@cmd);
984 my ($screen, $config, $match) = @_;
986 $screen->debug('handler_url', "opening $match->{value}");
988 run_in_background($screen, sub {
989 my @cmd = ( @{$config->{setting}{browser}}, $match->{value} );
990 run_command($screen, \@cmd);
997 # CONFIGURATION DEFAULTS
1001 fcscs is configured through F<~/.fcscsrc> or F<~/.config/fcscs/fcscsrc> which
1002 is a normal Perl script with all of Perl's usual features.
1004 All configuration values are stored in the hash C<%config>. All manually
1005 defined keys overwrite the default settings.
1007 A simple F<~/.fcscsrc> could look like this (for details about the used
1008 settings see below):
1013 use Curses; # for COLOR_* and A_* constants
1017 # Draw matches in blue.
1018 $config{attribute}{match_string} = color_pair(COLOR_BLUE, -1);
1019 # Draw numbers in bold yellow.
1020 $config{attribute}{match_id} = color_pair(COLOR_YELLOW, -1)
1022 # Disable Vim-like 'smartcase', ignore case until an upper character is
1024 $config{setting}{smartcase} = 0;
1026 # Use chromium to open URLs if running under X, elinks otherwise.
1027 if (defined $ENV{DISPLAY}) {
1028 $config{setting}{browser} = ['chromium'];
1030 $config{setting}{browser} = ['elinks', '-remote'];
1033 # Let fcscs know the file was loaded successfully.
1041 Pod::Usage::pod2usage(2);
1045 # Determine terminal encoding from the environment ($ENV{LANG} or similar).
1046 my $encoding = I18N::Langinfo::langinfo(I18N::Langinfo::CODESET);
1048 my $screen = Screen->init($encoding);
1050 # We must restore the screen before exiting.
1051 local $SIG{INT} = sub {
1055 # Make all warnings fatal to make sure they don't get lost (stderr is normally
1057 local $SIG{__WARN__} = sub {
1058 $screen->die('warning', @_);
1065 I<NOTE>: Mappings are split in two categories: Mode mappings which change the
1066 selection and may receive additional input (e.g. a search string) and simple
1067 mappings which only change some config value. Mode mappings are configured via
1068 C<$config{mapping}{mode}>, simple mappings via C<$config{mapping}{simple}>.
1070 The following mode mappings are available by default (the function to remap
1071 them in parentheses):
1075 =item B<f> select absolute/relative paths (C<\&mapping_mode_path>)
1077 =item B<u> select URLs (C<\&mapping_mode_url>)
1079 =item B<i> select IPv4 and IPv6 addresses (C<\&mapping_mode_ip>)
1081 =item B<c> select checksums (e.g. MD5, SHA) (C<\&mapping_mode_checksum>)
1083 =item B</> search for regex to get selection (C<\&mapping_mode_search>)
1085 =item B<q> quit fcscs (C<\&mapping_quit>)
1089 The following simple mappings are available by default:
1093 =item B<p> enable pasting (C<\&mapping_paste>)
1095 =item B<P> paste current selection (like C<\n> but paste) (C<\&mapping_paste_now>)
1097 =item B<y> enable yanking (copying) (C<\&mapping_yank>)
1099 =item B<Y> yank current selection (like C<\n> but yank) (C<\&mapping_yank_now>)
1103 Note that yanking only uses the GNU screen or Tmux paste buffer by default. To
1104 also copy to X11 selection, enable the B<yank_x11> option.
1106 The following additional mappings are available by default:
1110 =item B<\n> accept current selection (not customizable)
1112 =item B<s> additional key to accept selection (B<alternative_return> option)
1116 All (single-byte) keys except numbers, backspace and return can be mapped.
1118 Unknown mappings are ignored when pressing keys.
1120 To remove a default mapping, delete it from the mapping hash.
1124 # Map 'p' to select paths, 'P' to enable pasting.
1125 $config{mapping}{mode}{p} = \&mapping_mode_path;
1126 $config{mapping}{simple}{P} = \&mapping_paste;
1128 # Disable 'f' mapping.
1129 delete $config{mapping}{mode}{f};
1132 my %mapping_mode = (
1133 f => \&mapping_mode_path,
1134 u => \&mapping_mode_url,
1135 i => \&mapping_mode_ip,
1136 c => \&mapping_mode_checksum,
1137 '/' => \&mapping_mode_search,
1138 q => \&mapping_quit,
1140 my %mapping_simple = (
1141 p => \&mapping_paste,
1142 P => \&mapping_paste_now,
1143 y => \&mapping_yank,
1144 Y => \&mapping_yank_now,
1149 Attributes are used to style the output. They must be Curses attributes.
1150 Defaults in parentheses (foreground, background, attribute).
1154 =item B<match_id> attribute for match numbers (red, default, bold)
1156 =item B<match_string> attribute for matches (yellow, default, normal)
1158 =item B<match_last> attribute for the match selected by return (yellow, default, underline)
1160 =item B<prompt_name> attribute for prompt name (standout)
1162 =item B<prompt_flags> attribute for prompt flags (standout)
1168 # Draw prompt flags in bold red with default background color.
1169 $config{attribute}{prompt_flags}
1171 | color_pair(Curses::COLOR_RED, -1);
1175 match_id => $screen->color_pair(Curses::COLOR_RED, -1)
1177 match_string => $screen->color_pair(Curses::COLOR_YELLOW, -1),
1178 match_last => $screen->color_pair(Curses::COLOR_YELLOW, -1)
1179 | Curses::A_UNDERLINE,
1180 prompt_name => Curses::A_STANDOUT,
1181 prompt_flags => Curses::A_STANDOUT,
1186 Defaults in parentheses.
1190 =item B<debug> enable debug mode, writes to I<~/.config/fcscs/log> (C<0>)
1192 =item B<initial_mode> start in this mode, must be a valid mode mapping (C<\&mapping_mode_url>)
1194 =item B<multiplexer> set multiplexer ("screen" or "tmux"), defaults to autodetection (C<undef>)
1196 =item B<ignorecase> ignore case when searching (C<0>)
1198 =item B<smartcase> ignore case unless one uppercase character is searched (C<1>)
1200 =item B<yank_x11> copy selection also to X11 primary selection when yanking (C<0>)
1202 =item B<paste_sleep> sleep x us before running paste command (C<100_000>)
1204 =item B<screen_msgwait> GNU Screen's msgwait variable, used when yanking (C<5>)
1206 =item B<alternative_return> additional accept key like return, set to C<\n> to disable (C<s>)
1208 =item B<browser> browser command as array reference (C<['x-www-browser']>)
1214 # Select paths on startup instead of URLs.
1215 $config{setting}{initial_mode} = \&mapping_mode_path;
1221 initial_mode => \&mapping_mode_url,
1222 multiplexer => undef,
1226 paste_sleep => 100_000,
1227 screen_msgwait => 5,
1229 alternative_return => 's',
1231 browser => ['x-www-browser'],
1238 =item B<url> used by C<\&mapping_mode_url>
1240 =item B<path> used by C<\&mapping_mode_path>
1242 =item B<ipv4> used by C<\&mapping_mode_ip>
1244 =item B<ipv6> used by C<\&mapping_mode_ip>
1250 # Select all non-whitespace characters when searching for paths.
1251 $config{regex}{path} = qr{(\S+)};
1255 # Taken from urlview's default configuration file, thanks.
1256 url => qr{((?:(?:(?:http|https|ftp|gopher)|mailto):(?://)?[^ <>"\t]*|(?:www|ftp)[0-9]?\.[-a-z0-9.]+)[^ .,;\t\n\r<">\):]?[^, <>"\t]*[^ .,;\t\n\r<">\):])},
1257 path => qr{(~?[a-zA-Z0-9_./-]*/[a-zA-Z0-9_./-]+)},
1258 # IP addresses with optional prefix. Not perfectly accurate but good
1260 ipv4 => qr!\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?:/\d{1,2})?)\b!,
1261 ipv6 => qr!\b((?:[0-9a-fA-F]{1,4})?(?::+[0-9a-fA-F]{1,4})+(?:/\d{1,3})?)\b!,
1262 # MD5, SHA1, SHA256, SHA512
1263 checksum => qr!\b([0-9a-fA-F]{32}|[0-9a-fA-F]{40}|[0-9a-fA-F]{64}|[0-9a-fA-F]{128})\b!,
1268 Handlers are used to perform actions on the selected string.
1270 The following handlers are available, defaults in parentheses.
1274 =item B<yank> used to yank (copy) selection to paste buffer (C<\&handler_yank>)
1276 =item B<paste> used to paste selection into window (C<\&handler_paste>)
1278 =item B<path> used to handle paths (C<\&handler_yank>)
1280 =item B<url> used to open URLs (e.g. in a browser) (C<\&handler_url>)
1282 =item B<ip> used to handle IPs (C<\&handler_yank>)
1284 =item B<checksum> used to handle checksums (C<\&handler_yank>)
1290 # Download YouTube videos with a custom wrapper, handle all other URLs
1291 # with the default URL handler.
1292 $config{handler}{url} = sub {
1293 my ($screen, $config, $match) = @_;
1295 if ($match->{value} =~ m{^https://www.youtube.com/}) {
1296 return run_in_background($screen, sub {
1297 run_command($screen, ['youtube-dl-wrapper', $match->{value}]);
1305 yank => \&handler_yank,
1306 paste => \&handler_paste,
1307 path => \&handler_yank,
1308 url => \&handler_url,
1309 ip => \&handler_yank,
1310 checksum => \&handler_yank,
1314 initial => 1, # used by select_match() for 'initial_mode'
1320 # CONFIGURATION "API"
1324 The following functions are available:
1326 color_pair($fg, $bg)
1328 Create a new Curses attribute with the given fore- and background color.
1333 mapping_mode_checksum()
1334 mapping_mode_search()
1342 Used as mappings, see L</MAPPINGS> above.
1348 Used as handler to yank, paste selection or open URL in browser.
1355 Helper functions when writing custom mappings, see the source and example for
1360 # Enhance URL mode by updating the mapping.
1361 $config{mapping}{mode}{u} = sub {
1362 my ($key, $screen, $config, $input) = @_;
1364 # First get matches of normal URL mode.
1365 my $result = mapping_mode_url(@_);
1367 # Add all strings matching "CVE-1234-1234" with URLs pointing to the
1368 # Debian security tracker. "->{value}" is the string which is used as
1369 # result of the match (e.g. the URL in this case).
1370 my @matches = get_regex_matches($input, qr/\b(CVE-\d+-\d+)\b/);
1371 foreach (@matches) {
1372 $_->{value} = "https://security-tracker.debian.org/$_->{string}";
1374 push @{$result->{matches}}, @matches;
1376 # Change all YouTube links to use the custom "youtube" handler (see
1377 # below). This will allow us to automatically open YouTube URLs with a
1378 # custom program, like `youtube-dl` or `mpv`.
1379 foreach (@{$result->{matches}}) {
1380 if ($_->{string} =~ m{^https://www.youtube.com/}) {
1381 $_->{handler} = $config{handler}{youtube};
1387 # Also update initial mode to use our new "URL mode".
1388 $config{setting}{initial_mode} = $config{mapping}{mode}{u};
1390 # Special handler to download YouTube URLs with `youtube-dl`. You could
1391 # also use `mpv` here to immediately play them.
1392 $config{handler}{youtube} = sub {
1393 my ($screen, $config, $match) = @_;
1395 return run_in_background($screen, sub {
1396 run_command($screen, ['youtube-dl', $match->{value}]);
1402 # All variables and functions which are usable by ~/.fcscsrc.
1404 our $screen; # "private"
1407 sub color_pair { return $screen->color_pair(@_); }
1409 sub mapping_mode_path { return main::mapping_mode_path(@_); }
1410 sub mapping_mode_url { return main::mapping_mode_url(@_); }
1411 sub mapping_mode_ip { return main::mapping_mode_ip(@_); }
1412 sub mapping_mode_checksum { return main::mapping_mode_checksum(@_); }
1413 sub mapping_mode_search { return main::mapping_mode_search(@_); }
1415 sub mapping_paste { return main::mapping_paste(@_); }
1416 sub mapping_paste_now { return main::mapping_paste_now(@_); }
1417 sub mapping_yank { return main::mapping_yank(@_); }
1418 sub mapping_yank_now { return main::mapping_yank_now(@_); }
1419 sub mapping_quit { return main::mapping_quit(@_); }
1421 sub handler_yank { return main::handler_yank(@_); }
1422 sub handler_paste { return main::handler_paste(@_); }
1423 sub handler_url { return main::handler_url(@_); }
1425 sub get_regex_matches { return main::get_regex_matches(@_); }
1426 sub select_match { return main::select_match(@_); }
1428 sub run_command { return main::run_command(@_); }
1429 sub run_in_background { return main::run_in_background(@_); }
1431 $Fcscs::screen = $screen;
1437 # Alias %config and %Fcscs::config. %config is less to type.
1439 local *config = \%Fcscs::config;
1441 $config{mapping}{mode} = \%mapping_mode;
1442 $config{mapping}{simple} = \%mapping_simple;
1443 $config{attribute} = \%attribute;
1444 $config{setting} = \%setting;
1445 $config{regex} = \%regex;
1446 $config{handler} = \%handler;
1447 $config{state} = \%state;
1450 my @configs = ("$ENV{HOME}/.fcscsrc",
1451 "$ENV{HOME}/.config/fcscs/fcscsrc");
1452 foreach my $path (@configs) {
1453 my $decoded = $screen->decode($path);
1455 # Load configuration file. Checks have a race condition if the home
1456 # directory is writable by an attacker (but then the user is screwed
1458 next unless -e $path;
1460 $screen->die("Config '$decoded' not owned by current user!");
1462 # Make sure the file is not writable by other users. Doesn't handle
1463 # ACLs and see comment above about race conditions.
1464 my @stat = stat $path or $screen->die("Config '$decoded': $!");
1465 my $mode = $stat[2];
1466 if (($mode & Fcntl::S_IWGRP) or ($mode & Fcntl::S_IWOTH)) {
1467 $screen->die("Config '$decoded' must not be writable by other users.");
1470 my $result = do $path;
1472 $screen->die("Failed to parse '$decoded': $@") if $@;
1473 $screen->die("Failed to do '$decoded': $!") unless defined $result;
1474 $screen->die("Failed to run '$decoded'.");
1477 last; # success, don't load more files
1480 $screen->{debug} = $config{setting}{debug};
1486 # Auto-detect current multiplexer.
1487 if (not defined $config{setting}{multiplexer}) {
1488 if (defined $ENV{STY} and defined $ENV{TMUX}) {
1489 die 'Found both $STY and $TMUX, set $config{setting}{multiplexer}.';
1490 } elsif (defined $ENV{STY}) {
1491 $config{setting}{multiplexer} = 'screen';
1492 } elsif (defined $ENV{TMUX}) {
1493 $config{setting}{multiplexer} = 'tmux';
1495 die 'No multiplexer found.';
1499 my $binmode = $encoding;
1500 # GNU screen stores the screen dump for unknown reasons as ISO-8859-1
1501 # instead of the currently active encoding.
1502 if ($config{setting}{multiplexer} eq 'screen') {
1503 $binmode = 'ISO-8859-1';
1507 open my $fh, '<', $ARGV[0] or die $!;
1508 binmode $fh, ":encoding($binmode)" or die $!;
1511 push @input_lines, $_;
1513 close $fh or die $!;
1515 my $input = prepare_input($screen, \@input_lines);
1517 # Display original screen content.
1519 foreach (@{$input->{lines}}) {
1520 $screen->draw_simple($y++, 0, undef, $_);
1525 my $mapping = $config{setting}{initial_mode};
1529 if (not defined $mapping) {
1530 $key = $screen->getch unless defined $key;
1531 $screen->debug('input', "got key '$key'");
1533 $mapping = $config{mapping}{mode}{$key};
1534 $mapping = $config{mapping}{simple}{$key} unless defined $mapping;
1535 if (not defined $mapping) { # ignore unknown mappings
1541 $screen->debug('input', 'running mapping');
1542 my $result = $mapping->($key, $screen, \%config, $input);
1546 if (defined $result->{quit}) {
1547 $screen->debug('input', 'quitting');
1550 if (defined $result->{key}) {
1551 $key = $result->{key}; # lookup another mapping
1552 $screen->debug('input', "processing new key: '$key'");
1555 if (defined $result->{select}) {
1556 $screen->debug('input', 'selecting match');
1558 $result = select_match($result->{select},
1559 $screen, \%config, $input,
1560 $result->{matches});
1561 $result->{handler} = $tmp->{handler};
1562 $result->{extend} = $tmp->{extend};
1563 goto RESULT; # reprocess special entries in result
1565 if (defined $result->{extend}) {
1566 $screen->debug('input', 'extending match');
1567 $result = extend_match($screen, \%config, $input,
1569 goto RESULT; # reprocess special entries in result
1571 if (defined $result->{match}) {
1572 if (not defined $result->{match}{value}) {
1573 $result->{match}{value} = $result->{match}{string};
1576 $screen->debug('input', 'running handler');
1578 # Choose handler with falling priority.
1580 $config{state}{handler}, # set by user
1581 $result->{match}{handler}, # set by match
1582 $result->{handler}, # set by mapping
1583 $config{handler}{yank}, # fallback
1585 foreach my $handler (@handlers) {
1586 next unless defined $handler;
1588 $handler->($screen, \%config, $result->{match});
1594 $key = undef; # get next key from user
1619 Invalid arguments/options.
1625 Simon Ruderich E<lt>simon@ruderich.orgE<gt>
1627 =head1 LICENSE AND COPYRIGHT
1629 Copyright (C) 2013-2016 by Simon Ruderich
1631 This program is free software: you can redistribute it and/or modify
1632 it under the terms of the GNU General Public License as published by
1633 the Free Software Foundation, either version 3 of the License, or
1634 (at your option) any later version.
1636 This program is distributed in the hope that it will be useful,
1637 but WITHOUT ANY WARRANTY; without even the implied warranty of
1638 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1639 GNU General Public License for more details.
1641 You should have received a copy of the GNU General Public License
1642 along with this program. If not, see E<lt>http://www.gnu.org/licenses/E<gt>.
1646 L<screen(1)>, L<tmux(1)>, L<urlview(1)>