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):
69 - select match by displayed number or <return> for lowest numbered
71 - configured action is run, e.g. URL is opened with browser
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
79 GNU Screen setup (add to F<~/.screenrc>):
81 bind ^B eval "hardcopy $HOME/.tmp/screen-fcscs" "screen fcscs $HOME/.tmp/screen-fcscs"
83 Tmux setup (add to F<~/.tmux.conf>):
85 bind-key C-b capture-pane \; save-buffer ~/.tmp/tmux-fcscs \; delete-buffer \; new-window "fcscs ~/.tmp/tmux-fcscs"
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.
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.
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
104 Press return before entering a number to select the last (lowest numbered)
105 match. To abort without selecting any match either use "q".
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
111 I<NOTE>: Opening URLs in the browser passes the URL via the command line which
112 leaks URLs to other users on the current system via C<ps aux> or C<top>.
114 I<NOTE>: When yanking (copying) a temporary file is used to pass the data to
115 GNU screen/Tmux without exposing it to C<ps aux> or C<top>. However this may
116 leak data if those temporary files are written to disk. To prevent this change
117 your C<$TMP> to point to a memory-only location or encrypted storage.
119 If no window appears, try running B<fcscs> manually to catch the error message
120 and please report the bug:
122 fcscs /path/to/screen-or-tmux-fcscs-file
132 # Helper class for drawing on the screen using Curses.
135 my ($class, $encoding) = @_;
137 # Prefer strict UTF-8 handling (see perldoc Encode); just in case.
138 if (lc $encoding eq 'utf8') {
141 # Get Encode object to speed up decode()/encode().
142 my $encoding_object = Encode::find_encoding($encoding);
143 die "unsupported encoding '$encoding'" unless ref $encoding_object;
145 my $curses = Curses->new or die $!;
148 encoding => $encoding,
149 encoding_object => $encoding_object,
161 # Allow default colors by passing -1 to init_pair. A default color is
162 # not drawn on screen thus allowing terminals with pseudo-transparency
163 # to use the transparent background in place of the default color.
164 Curses::use_default_colors;
183 # Convert between Perl's internal encoding and the terminal's encoding.
185 my ($self, $string) = @_;
186 return $self->{encoding_object}->encode($string);
189 my ($self, $string) = @_;
190 return eval { # returns undef on decode failure
191 $self->{encoding_object}->decode($string, Encode::FB_CROAK);
195 # Create attribute for the given fore-/background colors.
197 my ($self, $fg, $bg) = @_;
199 state $next_color_pair = 1; # must start at 1 for init_pair()
201 Curses::init_pair($next_color_pair, $fg, $bg);
202 return Curses::COLOR_PAIR($next_color_pair++);
205 # Draw a string which must fit in the current line. Wrapping/clipping is
206 # not supported and must be handled by the caller.
208 my ($self, $y, $x, $attributes, $string) = @_;
210 die if $string =~ /\n/;
211 # FIXME: wide characters
212 die if $x + length $string > $self->width;
214 $self->{curses}->attron($attributes) if defined $attributes;
215 $self->{curses}->addstr($y, $x, $self->encode($string));
216 $self->{curses}->attroff($attributes) if defined $attributes;
219 # Like draw_simple(), but the string is automatically clipped.
221 my ($self, $y, $x, $attributes, $string) = @_;
223 # FIXME: wide characters
224 $string = substr $string, 0, $self->width - $x;
225 $self->draw_simple($y, $x, $attributes, $string);
229 my ($self, $y, $x, $attributes, $string) = @_;
231 die unless defined $string;
235 # We must print each line separately. Search for next newline or
236 # line end, whichever is closer.
237 if ($string =~ /\n/) {
240 # FIXME: wide characters
241 if ($x + length $string > $self->width) {
242 my $new_offset = $self->width - $x;
243 if (not defined $offset or $offset > $new_offset) {
244 $offset = $new_offset;
247 last unless defined $offset;
249 # FIXME: wide characters
250 $self->draw_simple($y, $x, $attributes, substr $string, 0, $offset);
252 # Don't draw "\n" itself.
253 if ("\n" eq substr $string, $offset, 1) {
257 $string = substr $string, $offset;
263 $self->draw_simple($y, $x, $attributes, $string);
268 my ($self, $config) = @_;
270 $self->debug('draw_prompt', 'started');
273 my $y = $self->height - 1;
275 # Clear line for better visibility.
276 $self->draw_simple($y, $x, undef, ' ' x $self->width);
279 if (defined (my $s = $self->{prompt}{flags})) {
281 $self->debug('draw_prompt', $s);
282 $self->draw_clipped($y, $x, $config->{attribute}{prompt_flags}, $s);
283 $x += length($s) + 1; # space between next element
286 if (defined (my $s = $self->{prompt}{name})) {
288 $self->debug('draw_prompt', $s);
289 $self->draw_clipped($y, $x, $config->{attribute}{prompt_name}, $s);
290 $x += length($s) + 1;
292 # Draw prompt value, e.g. a search field.
293 if (defined (my $s = $self->{prompt}{value})) {
294 $self->debug('draw_prompt', $s);
295 $self->draw_clipped($y, $x, undef, $s);
296 $x += length($s) + 1;
302 my ($self, $config, $matches_remove, $matches_add) = @_;
304 foreach (@{$matches_remove}) {
305 $self->draw($_->{y}, $_->{x}, Curses::A_NORMAL, $_->{string});
308 my $attr_id = $config->{attribute}{match_id};
309 my $attr_string = $config->{attribute}{match_string};
311 foreach (@{$matches_add}) {
312 $self->draw($_->{y}, $_->{x}, $attr_string, $_->{string});
313 if (defined $_->{id}) {
314 $self->draw($_->{y}, $_->{x}, $attr_id, $_->{id});
321 my ($self, @args) = @_;
323 my $attr = $self->color_pair(Curses::COLOR_RED, -1) | Curses::A_BOLD;
325 # Clear the screen to improve visibility of the error message.
326 $self->{curses}->clear;
328 my $y = $self->draw(0, 0, $attr, "@args");
330 if ($self->{debug}) {
333 require Devel::StackTrace;
336 $msg = "Devel::StackTrace missing, no stack trace.\n";
338 my $trace = Devel::StackTrace->new;
339 $msg = "Stack trace:\n" . $trace->as_string;
341 $y = $self->draw($y + 1, 0, Curses::A_NORMAL, $msg);
344 $self->draw($y + 1, 0, Curses::A_NORMAL,
345 'Press any key to terminate fcscs.');
353 my ($self, $module, @args) = @_;
355 return if not $self->{debug};
357 state $fh; # only open the file once per run
358 if (not defined $fh) {
359 # Ignore errors if the directory doesn't exist.
360 if (not open $fh, '>', "$ENV{HOME}/.config/fcscs/log") {
361 $fh = undef; # a failed open still writes a value to $fh
367 $_ = $self->encode($_);
369 say $fh "$module: @args";
375 my ($self, %settings) = @_;
377 foreach (keys %settings) {
378 CORE::die if not exists $self->{prompt}{$_};
379 $self->{prompt}{$_} = $settings{$_};
384 # Wrapper for Curses.
385 sub width { return $Curses::COLS; }
386 sub height { return $Curses::LINES; }
387 sub refresh { return $_[0]->{curses}->refresh; }
388 sub getch { return $_[0]->{curses}->getch; }
389 sub cursor { Curses::curs_set($_[1]); return; }
397 my ($screen, $input_ref) = @_;
399 # Make sure the input fits on the screen by removing the top lines if
401 splice @{$input_ref}, 0, -$screen->height;
403 # Pad each line with spaces to the screen width to correctly handle
404 # multi-line regexes.
405 # FIXME: wide characters
406 my @padded = map { sprintf '%-*s', $screen->width, $_ } @{$input_ref};
408 my $string = join "\n", @padded;
412 width => $screen->width + 1,
413 # + 1 = "\n", used in input_match_offset_to_coordinates
417 sub input_match_offset_to_coordinates {
418 my ($width, $offset) = @_;
420 die unless defined $offset;
422 my $y = int($offset / $width);
423 my $x = $offset - $y * $width;
427 sub get_regex_matches {
428 my ($input, $regex) = @_;
431 while ($input->{string} =~ /$regex/g) {
433 die "Match group required in regex '$regex'" if not defined $offset;
435 my ($x, $y) = input_match_offset_to_coordinates($input->{width},
437 push @matches, { x => $x, y => $y, offset => $offset, string => $1 };
444 my ($screen, $config, $cmd) = @_;
446 $screen->debug('run_command', "running @{$cmd}");
449 # Perl's system() combined with a $SIG{__WARN__} which die()s has
450 # issues due to the fork. The die() in the __WARN__ handler doesn't
451 # die but the program continues after the system().
453 # If the forked process fails to exec (e.g. program not found) then
454 # the __WARN__ handler is called (because a warning is about to be
455 # displayed) and the die() should display a message and terminate the
456 # process. But due to the fork it doesn't terminate the parent process
457 # and instead changes the return value of system(); it's no longer -1
458 # which makes it impossible to detect that case.
460 # Perl < 5.18 (found in 5.14) doesn't setup $$ during system() which
461 # makes it impossible to detect if the handler was called from inside
464 # Instead, just ignore any warnings during the system(). Thanks to
465 # mauke in #perl on Freenode (2013-10-29 23:30 CET) for the idea to
466 # use no warnings and anno for testing a more recent Perl version with
470 my @cmd = map { $screen->encode($_) } @{$cmd};
471 system { $cmd[0] } @cmd;
476 $msg = 'failed to execute: ' . $!;
478 $msg = 'killed by signal ' . ($? & 127);
480 $msg = 'exited with code ' . ($? >> 8);
482 die "system(@{$cmd}) $msg.";
486 sub run_in_background {
487 my ($screen, $sub) = @_;
489 $screen->debug('run_in_background', "running $sub");
492 defined $pid or die $!;
495 # The terminal multiplexer sends a SIGHUP to the process when it
496 # closes the window (because the parent process has exited).
497 local $SIG{HUP} = 'IGNORE';
499 # Necessary for GNU screen or it'll keep the window open until the
500 # paste command has run.
501 close STDIN or die $!;
502 close STDOUT or die $!;
503 close STDERR or die $!;
505 # Double-fork to prevent zombies.
507 defined $pid or die $!;
508 if ($pid == 0) { # child
513 waitpid $pid, 0 or die $!;
519 my ($name, $screen, $config, $input, $matches) = @_;
521 $screen->debug('select_match', 'started');
523 return if @{$matches} == 0;
524 # Don't return on initial run to give the user a chance to select another
525 # mode, e.g. to switch from URL selection to search selection.
526 if (@{$matches} == 1 and not $config->{state}{initial}) {
527 return { match => $matches->[0] };
529 $config->{state}{initial} = 0;
531 my @sorted = sort { $b->{y} <=> $a->{y} or $b->{x} <=> $a->{x} } @{$matches};
538 $screen->prompt(name => $name, value => undef);
539 $screen->draw_prompt($config);
541 $screen->draw_matches($config, [], $matches);
546 my $char = $screen->getch;
547 if ($char =~ /^\d$/) {
548 $number = $number * 10 + $char;
549 } elsif ($char eq "\b" or $char eq "\x7f") { # backspace
550 $number = int($number / 10);
551 } elsif ($char eq "\n") {
552 if ($number == 0) { # number without selection matches last entry
557 # Selecting a new mode requires falling through into the main input
558 # loop and then starting the new mode.
559 } elsif (defined $config->{mapping}{mode}{$char}) {
560 $screen->draw_matches($config, $matches, []); # clear matches
561 return { key => $char };
562 # All other mappings stay in the current mode.
563 } elsif (defined (my $m = $config->{mapping}{simple}{$char})) {
564 $m->($char, $screen, $config, $input);
568 next; # ignore unknown mappings
571 last if $number > 0 and $number * 10 > @{$matches}; # unique match
573 my @remaining = $number == 0
575 : grep { $_->{id} =~ /^$number/ } @{$matches};
576 $screen->draw_matches($config, $matches, \@remaining);
580 $screen->draw_matches($config, $matches, []); # remove matches
582 foreach (@{$matches}) {
583 return { match => $_ } if $_->{id} == $number;
585 $screen->debug('select_match', 'no match selected');
586 return { match => undef };
589 sub extend_match_regex_left {
590 my ($line, $match, $regex) = @_;
592 my $s = reverse substr $line, 0, $match->{x};
593 if ($s =~ /^($regex)/) {
594 $match->{string} = reverse($1) . $match->{string};
595 $match->{x} -= length $1;
596 $match->{offset} -= length $1;
600 sub extend_match_regex_right {
601 my ($line, $match, $regex) = @_;
603 my $s = substr $line, $match->{x} + length $match->{string};
604 if ($s =~ /^($regex)/) {
605 $match->{string} .= $1;
610 my ($screen, $config, $input, $match) = @_;
612 $screen->debug('extend_match', 'started');
614 $screen->prompt(name => 'extend', value => undef);
615 $screen->draw_prompt($config);
617 delete $match->{id}; # don't draw any match ids
618 $screen->draw_matches($config, [], [$match]);
621 my $line = $input->{lines}[$match->{y}];
624 my $match_old = \%{$match};
626 my $char = $screen->getch;
627 if ($char eq "\n") { # accept match
630 } elsif ($char eq 'w') { # select current word (both directions)
631 extend_match_regex_left($line, $match, qr/\w+/);
632 extend_match_regex_right($line, $match, qr/\w+/);
633 } elsif ($char eq 'b') { # select current word (only left)
634 extend_match_regex_left($line, $match, qr/\w+/);
635 } elsif ($char eq 'e') { # select current word (only right)
636 extend_match_regex_right($line, $match, qr/\w+/);
638 } elsif ($char eq 'W') { # select current WORD (both directions)
639 extend_match_regex_left($line, $match, qr/\S+/);
640 extend_match_regex_right($line, $match, qr/\S+/);
641 } elsif ($char eq 'B') { # select current WORD (only left)
642 extend_match_regex_left($line, $match, qr/\S+/);
643 } elsif ($char eq 'E') { # select current WORD (only right)
644 extend_match_regex_right($line, $match, qr/\S+/);
646 } elsif ($char eq '^') { # select to beginning of line
647 extend_match_regex_left($line, $match, qr/.+/);
648 } elsif ($char eq '$') { # select to end of line
649 extend_match_regex_right($line, $match, qr/.+/);
651 # Allow mode changes if not overwritten by local mappings.
652 } elsif (defined $config->{mapping}{mode}{$char}) {
653 $screen->draw_matches($config, [$match_old], []); # clear match
654 return { key => $char };
657 next; # ignore unknown mappings
660 $screen->draw_matches($config, [$match_old], [$match]);
664 $screen->debug('extend_match', 'done');
666 return { match => $match };
671 my ($key, $screen, $config, $input) = @_;
673 $screen->debug('mapping_paste', 'started');
675 $config->{state}{handler} = $config->{handler}{paste};
677 $screen->prompt(flags => 'P'); # paste
678 $screen->draw_prompt($config);
684 my ($key, $screen, $config, $input) = @_;
686 $screen->debug('mapping_yank', 'started');
688 $config->{state}{handler} = $config->{handler}{yank};
690 $screen->prompt(flags => 'Y'); # yank
691 $screen->draw_prompt($config);
700 Normal modes select matches by calling a function which returns them, e.g. by
703 The following normal modes are available:
707 =item B<path mode> select relative/absolute paths
709 =item B<url mode> select URLs
714 sub mapping_mode_path {
715 my ($key, $screen, $config, $input) = @_;
717 $screen->debug('mapping_mode_path', 'started');
719 my @matches = get_regex_matches($input, $config->{regex}{path});
721 select => 'path select',
722 matches => \@matches,
723 handler => $config->{handler}{yank},
726 sub mapping_mode_url {
727 my ($key, $screen, $config, $input) = @_;
729 $screen->debug('mapping_mode_url', 'started');
731 my @matches = get_regex_matches($input, $config->{regex}{url});
733 select => 'url select',
734 matches => \@matches,
735 handler => $config->{handler}{url},
739 =head2 SEARCH MODE (AND EXTEND MODE)
741 Search mode is a special mode which lets you type a search string (a Perl
742 regex) and then select one of the matches. Afterwards you can extend the
743 match. For example select the complete word or to the end of the line. This
744 allows quick selection of arbitrary text.
746 The following mappings are available during the extension mode (not
747 configurable at the moment):
751 =item B<w> select current word
753 =item B<b> extend word to the left
755 =item B<e> extend word to the right
757 =item B<W> select current WORD
759 =item B<B> extend WORD to the left
761 =item B<E> extend WORD to the right
763 =item B<^> extend to beginning of line
765 =item B<$> extend to end of line
769 C<word> includes any characters matching C<\w+>, C<WORD> any non-whitespace
770 characters (C<\S+>), just like in Vim.
773 sub mapping_mode_search {
774 my ($key, $screen, $config, $input) = @_;
776 $screen->debug('mapping_mode_search', 'started');
780 my $search = ''; # encoded
783 # getch doesn't return decoded characters but raw input bytes. Wait
784 # until the input character is complete.
785 my $value = $screen->decode($search);
786 $value = '' unless defined $value; # undef on decode failure
788 $screen->prompt(name => 'search', value => $value);
789 $screen->draw_prompt($config);
792 my $char = $screen->getch;
793 # TODO: readline editing support
796 } elsif ($char eq "\b" or $char eq "\x7f") { # backspace
797 # Remove a character, not a byte.
798 $search = $screen->decode($search);
800 $search = $screen->encode($search);
803 next unless defined $screen->decode($search);
809 if (($config->{setting}{smartcase} and $search eq lc $search)
810 or $config->{setting}{ignorecase}) {
813 # Ignore invalid regexps.
814 # TODO: display warning on error?
816 @matches = get_regex_matches($input, qr/($case$search)/);
819 $screen->draw_matches($config, \@last_matches, \@matches);
820 @last_matches = @matches;
827 matches => \@last_matches,
829 handler => $config->{handler}{yank},
834 my ($key, $screen, $config, $input) = @_;
836 # Key is necessary to fall through to main event loop which then quits.
837 return { key => $key, quit => 1 };
842 my ($screen, $config, $match) = @_;
844 $screen->debug('handler_yank', 'started');
848 # Use a temporary file to prevent leaking the yanked data to other users
849 # with the command line, e.g. ps aux or top.
850 my ($fh, $tmp) = File::Temp::tempfile(); # dies on its own
851 print $fh $screen->encode($match->{value});
854 if ($config->{setting}{multiplexer} eq 'screen') {
855 $screen->debug('handler_yank', 'using screen');
857 # GNU screen displays an annoying "Slurping X characters into buffer".
858 # Use 'msgwait 0' as a hack to disable it.
859 my $msgwait = $config->{setting}{screen_msgwait};
860 run_command($screen, $config, ['screen', '-X', 'msgwait', 0]);
861 run_command($screen, $config, ['screen', '-X', 'readbuf', $tmp]);
862 run_command($screen, $config, ['screen', '-X', 'msgwait', $msgwait]);
863 } elsif ($config->{setting}{multiplexer} eq 'tmux') {
864 $screen->debug('handler_yank', 'using tmux');
866 run_command($screen, $config, ['tmux', 'load-buffer', $tmp]);
868 die 'unsupported multiplexer';
871 unlink $tmp or die $!;
875 my ($screen, $config, $match) = @_;
877 $screen->debug('handler_paste', 'started');
882 if ($config->{setting}{multiplexer} eq 'screen') {
883 $screen->debug('handler_paste', 'using screen');
884 @cmd = qw( screen -X paste . );
885 } elsif ($config->{setting}{multiplexer} eq 'tmux') {
886 $screen->debug('handler_paste', 'using tmux');
887 @cmd = qw( tmux paste-buffer );
889 die 'unsupported multiplexer';
892 run_in_background($screen, sub {
893 # We need to get the data in the paste buffer before we can paste
895 handler_yank($screen, $config, $match);
897 # Sleep until we switch back to the current window.
898 Time::HiRes::usleep($config->{setting}{paste_sleep});
900 run_command($screen, $config, \@cmd);
905 my ($screen, $config, $match) = @_;
907 $screen->debug('handler_url', "opening $match->{value}");
909 run_in_background($screen, sub {
910 my @cmd = ( @{$config->{setting}{browser}}, $match->{value} );
911 run_command($screen, $config, \@cmd);
918 # CONFIGURATION DEFAULTS
922 fcscs is configured through F<~/.fcscsrc> or F<~/.config/fcscs/fcscsrc> which
923 is a normal Perl script with all of Perl's usual features.
925 All configuration values are stored in the hash C<%config>. All manually
926 defined keys overwrite the default settings.
928 A simple F<~/.fcscsrc> could look like this (for details about the used
934 use Curses; # for COLOR_* and A_* constants
938 # Draw matches in blue.
939 $config{attribute}{match_string} = color_pair(COLOR_BLUE, -1);
940 # Enable Vim-like 'smartcase', ignore case until an upper character is
942 $config{setting}{smartcase} = 1;
944 # Use chromium to open URLs if running under X, elinks otherwise.
945 if (defined $ENV{DISPLAY}) {
946 $config{setting}{browser} = ['chromium'];
948 $config{setting}{browser} = ['elinks'];
951 # Let fcscs know the file was loaded successfully.
959 Pod::Usage::pod2usage(2);
963 # Determine terminal encoding from the environment ($ENV{LANG} or similar).
964 my $encoding = I18N::Langinfo::langinfo(I18N::Langinfo::CODESET);
966 my $screen = Screen->init($encoding);
968 # We must restore the screen before exiting.
969 local $SIG{INT} = sub {
973 # Make all warnings fatal to make sure they don't get lost (stderr is normally
975 local $SIG{__WARN__} = sub {
976 $screen->die('warning', @_);
983 I<NOTE>: Mappings are split in two categories: Mode mappings which change the
984 selection and may receive additional input (e.g. a search string) and simple
985 mappings which only change some value. Mode mappings are configured via
986 C<$config{mapping}{mode}>, simple mappings via C<$config{mapping}{simple}>.
988 The following mode mappings are available by default (the function to remap
989 them in parentheses):
993 =item B<f> select absolute/relative paths (C<\&mapping_mode_path>)
995 =item B<u> select URLs (C<\&mapping_mode_url>)
997 =item B</> search for regex to get selection (C<\&mapping_mode_search>)
999 =item B<q> quit fcscs (C<\&mapping_quit>)
1003 The following simple mappings are available by default:
1007 =item B<p> enable pasting (C<\&mapping_paste>)
1009 =item B<y> enable yanking (copying) (C<\&mapping_yank>)
1013 All (single-byte) keys except numbers, backspace and return can be mapped.
1015 Unknown mappings are ignored when pressing keys.
1017 To remove a default mapping, delete it from the mapping hash.
1021 # Map 'p' to select paths, 'P' to enable pasting.
1022 $config{mapping}{mode}{p} = \&mapping_mode_path;
1023 $config{mapping}{simple}{P} = \&mapping_paste;
1025 # Disable 'f' mapping.
1026 delete $config{mapping}{mode}{f};
1029 my %mapping_mode = (
1030 f => \&mapping_mode_path,
1031 u => \&mapping_mode_url,
1032 '/' => \&mapping_mode_search,
1033 q => \&mapping_quit,
1035 my %mapping_simple = (
1036 p => \&mapping_paste,
1037 y => \&mapping_yank,
1042 Attributes are used to style the output. They must be Curses attributes.
1043 Defaults in parentheses (foreground, background, attribute).
1047 =item B<match_id> attribute for match numbers (red, default, bold)
1049 =item B<match_string> attribute for matches (yellow, default, normal)
1051 =item B<prompt_name> attribute for prompt name (standout)
1053 =item B<prompt_flags> attribute for prompt flags (standout)
1059 # Draw prompt flags in bold red with default background color.
1060 $config{attribute}{prompt_flags}
1062 | color_pair(Curses::COLOR_RED, -1);
1066 match_id => $screen->color_pair(Curses::COLOR_RED, -1)
1068 match_string => $screen->color_pair(Curses::COLOR_YELLOW, -1),
1069 prompt_name => Curses::A_STANDOUT,
1070 prompt_flags => Curses::A_STANDOUT,
1075 Defaults in parentheses.
1079 =item B<debug> enable debug mode, writes to I<~/.config/fcscs/log> (C<0>)
1081 =item B<initial_mode> start in this mode, must be a valid mode mapping (C<\&mapping_mode_url>)
1083 =item B<multiplexer> set multiplexer ("screen" or "tmux") if not autodetected (C<undef>)
1085 =item B<ignorecase> ignore case when searching (C<0>)
1087 =item B<smartcase> ignore case unless one uppercase character is searched (C<1>)
1089 =item B<paste_sleep> sleep x us before running paste command (C<100_000>)
1091 =item B<screen_msgwait> GNU Screen's msgwait variable, used when yanking (C<5>)
1093 =item B<browser> browser command as array reference (C<['x-www-browser']>)
1099 # Select paths on startup instead of URLs.
1100 $config{setting}{initial_mode} = \&mapping_mode_path;
1106 initial_mode => \&mapping_mode_url,
1107 multiplexer => undef,
1110 paste_sleep => 100_000,
1111 screen_msgwait => 5,
1113 browser => ['x-www-browser'],
1120 =item B<url> used by C<\&mapping_mode_url()>
1122 =item B<path> used by C<\&mapping_mode_path()>
1128 # Select all non-whitespace characters when searching for paths.
1129 $config{regex}{path} = qr{(\S+)};
1133 # Taken from urlview's default configuration file, thanks.
1134 url => qr{((?:(?:(?:http|https|ftp|gopher)|mailto):(?://)?[^ <>"\t]*|(?:www|ftp)[0-9]?\.[-a-z0-9.]+)[^ .,;\t\n\r<">\):]?[^, <>"\t]*[^ .,;\t\n\r<">\):])},
1135 path => qr{(~?[a-zA-Z0-9_./-]*/[a-zA-Z0-9_./-]+)},
1140 Handlers are used to perform actions on the selected string.
1142 The following handlers are available, defaults in parentheses.
1146 =item B<yank> used to yank (copy) selection to paste buffer (C<\&handler_yank>)
1148 =item B<paste> used to paste selection into window (C<\&handler_paste>)
1150 =item B<url> used to open URLs (e.g. in a browser) (C<\&handler_url>)
1156 # Download YouTube videos with a custom wrapper, handle all other URLs
1157 # with the default URL handler.
1158 $config{handler}{url} = sub {
1159 my ($screen, $config, $match) = @_;
1161 if ($match->{value} =~ m{^https://www.youtube.com/}) {
1162 return run_in_background($screen, sub {
1163 run_command($screen, $config,
1164 ['youtube-dl-wrapper', $match->{value}]);
1172 yank => \&handler_yank,
1173 paste => \&handler_paste,
1174 url => \&handler_url,
1178 initial => 1, # used by select_match() for 'initial_mode'
1184 # CONFIGURATION "API"
1188 The following functions are available:
1190 color_pair($fg, $bg)
1192 Create a new Curses attribute with the given fore- and background color.
1196 mapping_mode_search()
1202 Used as mappings, see L</MAPPINGS> above.
1208 Used as handler to yank, paste selection or open URL in browser.
1216 Helper functions when writing custom mappings, see the source for details.
1224 # All variables and functions which are usable by ~/.fcscsrc.
1226 our $screen; # "private"
1229 sub color_pair { return $screen->color_pair(@_); }
1231 sub mapping_mode_path { return main::mapping_mode_path(@_); }
1232 sub mapping_mode_url { return main::mapping_mode_url(@_); }
1233 sub mapping_mode_search { return main::mapping_mode_search(@_); }
1235 sub mapping_paste { return main::mapping_paste(@_); }
1236 sub mapping_yank { return main::mapping_yank(@_); }
1237 sub mapping_quit { return main::mapping_quit(@_); }
1239 sub handler_yank { return main::handler_yank(@_); }
1240 sub handler_paste { return main::handler_paste(@_); }
1241 sub handler_url { return main::handler_url(@_); }
1243 sub debug { return main::debug(@_); }
1245 sub get_regex_matches { return main::get_regex_matches(@_); }
1246 sub select_match { return main::select_match(@_); }
1248 sub run_command { return main::run_command(@_); }
1249 sub run_in_background { return main::run_in_background(@_); }
1251 $Fcscs::screen = $screen;
1257 # Alias %config and %Fcscs::config. %config is less to type.
1259 local *config = \%Fcscs::config;
1261 $config{mapping}{mode} = \%mapping_mode;
1262 $config{mapping}{simple} = \%mapping_simple;
1263 $config{attribute} = \%attribute;
1264 $config{setting} = \%setting;
1265 $config{regex} = \%regex;
1266 $config{handler} = \%handler;
1267 $config{state} = \%state;
1270 my @configs = ("$ENV{HOME}/.fcscsrc",
1271 "$ENV{HOME}/.config/fcscs/fcscsrc");
1272 foreach my $path (@configs) {
1273 my $decoded = $screen->decode($path);
1275 # Load configuration file. Checks have a race condition if the home
1276 # directory is writable by an attacker (but then the user is screwed
1278 next unless -e $path;
1280 $screen->die("Config '$decoded' not owned by current user!");
1282 # Make sure the file is not writable by other users. Doesn't handle
1283 # ACLs and see comment above about race conditions.
1284 my @stat = stat $path or die $!;
1285 my $mode = $stat[2];
1286 if (($mode & Fcntl::S_IWGRP) or ($mode & Fcntl::S_IWOTH)) {
1287 die "Config '$decoded' must not be writable by other users.";
1290 my $result = do $path;
1292 $screen->die("Failed to parse '$decoded': $@") if $@;
1293 $screen->die("Failed to do '$decoded': $!") unless defined $result;
1294 $screen->die("Failed to run '$decoded'.");
1297 last; # success, don't load more files
1300 $screen->{debug} = $config{setting}{debug};
1306 # Auto-detect current multiplexer.
1307 if (not defined $config{setting}{multiplexer}) {
1308 if (defined $ENV{STY} and defined $ENV{TMUX}) {
1309 die 'Found both $STY and $TMUX, set $config{setting}{multiplexer}.';
1310 } elsif (defined $ENV{STY}) {
1311 $config{setting}{multiplexer} = 'screen';
1312 } elsif (defined $ENV{TMUX}) {
1313 $config{setting}{multiplexer} = 'tmux';
1315 die 'No multiplexer found.';
1319 my $binmode = $encoding;
1320 # GNU screen stores the screen dump for unknown reasons as ISO-8859-1
1321 # instead of the currently active encoding.
1322 if ($config{setting}{multiplexer} eq 'screen') {
1323 $binmode = 'ISO-8859-1';
1327 open my $fh, '<', $ARGV[0] or die $!;
1328 binmode $fh, ":encoding($binmode)" or die $!;
1331 push @input_lines, $_;
1333 close $fh or die $!;
1335 my $input = prepare_input($screen, \@input_lines);
1337 # Display original screen content.
1339 foreach (@{$input->{lines}}) {
1340 $screen->draw_simple($y++, 0, undef, $_);
1345 my $mapping = $config{setting}{initial_mode};
1349 if (not defined $mapping) {
1350 $key = $screen->getch unless defined $key;
1351 $screen->debug('input', "got key '$key'");
1353 $mapping = $config{mapping}{mode}{$key};
1354 $mapping = $config{mapping}{simple}{$key} unless defined $mapping;
1355 if (not defined $mapping) { # ignore unknown mappings
1361 $screen->debug('input', 'running mapping');
1362 my $result = $mapping->($key, $screen, \%config, $input);
1366 if (defined $result->{quit}) {
1367 $screen->debug('input', 'quitting');
1370 if (defined $result->{key}) {
1371 $key = $result->{key}; # lookup another mapping
1372 $screen->debug('input', "processing new key: '$key'");
1375 if (defined $result->{select}) {
1376 $screen->debug('input', 'selecting match');
1378 $result = select_match($result->{select},
1379 $screen, \%config, $input,
1380 $result->{matches});
1381 $result->{handler} = $tmp->{handler};
1382 $result->{extend} = $tmp->{extend};
1383 goto RESULT; # reprocess special entries in result
1385 if (defined $result->{extend}) {
1386 $screen->debug('input', 'extending match');
1387 $result = extend_match($screen, \%config, $input,
1389 goto RESULT; # reprocess special entries in result
1391 if (defined $result->{match}) {
1392 if (not defined $result->{match}{value}) {
1393 $result->{match}{value} = $result->{match}{string};
1396 $screen->debug('input', 'running handler');
1398 # Choose handler with falling priority.
1400 $config{state}{handler}, # set by user
1401 $result->{match}{handler}, # set by match
1402 $result->{handler}, # set by mapping
1403 $config{handler}{yank}, # fallback
1405 foreach my $handler (@handlers) {
1406 next unless defined $handler;
1408 $handler->($screen, \%config, $result->{match});
1414 $key = undef; # get next key from user
1439 Invalid arguments/options.
1445 Simon Ruderich E<lt>simon@ruderich.orgE<gt>
1447 =head1 LICENSE AND COPYRIGHT
1449 Copyright (C) 2013-2016 by Simon Ruderich
1451 This program is free software: you can redistribute it and/or modify
1452 it under the terms of the GNU General Public License as published by
1453 the Free Software Foundation, either version 3 of the License, or
1454 (at your option) any later version.
1456 This program is distributed in the hope that it will be useful,
1457 but WITHOUT ANY WARRANTY; without even the implied warranty of
1458 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1459 GNU General Public License for more details.
1461 You should have received a copy of the GNU General Public License
1462 along with this program. If not, see E<lt>http://www.gnu.org/licenses/E<gt>.
1466 L<screen(1)>, L<tmux(1)>, L<urlview(1)>