--- rxvt-unicode/src/urxvt.pm 2006/01/20 22:49:34 1.121 +++ rxvt-unicode/src/urxvt.pm 2012/06/06 15:09:49 1.213 @@ -19,7 +19,7 @@ =head1 DESCRIPTION -Everytime a terminal object gets created, extension scripts specified via +Every time a terminal object gets created, extension scripts specified via the C resource are loaded and associated with it. Scripts are compiled in a 'use strict' and 'use utf8' environment, and @@ -28,6 +28,9 @@ Each script will only ever be loaded once, even in @@RXVT_NAME@@d, where scripts will be shared (but not enabled) for all terminals. +You can disable the embedded perl interpreter by setting both "perl-ext" +and "perl-ext-common" resources to the empty string. + =head1 PREPACKAGED EXTENSIONS This section describes the extensions delivered with this release. You can @@ -39,7 +42,7 @@ Or by adding them to the resource for extensions loaded by default: - URxvt.perl-ext-common: default,automove-background,selection-autotransform + URxvt.perl-ext-common: default,selection-autotransform =over 4 @@ -64,11 +67,18 @@ The index number (0, 1...) must not have any holes, and each regex must contain at least one pair of capturing parentheses, which will be used for -the match. For example, the followign adds a regex that matches everything +the match. For example, the following adds a regex that matches everything between two vertical bars: URxvt.selection.pattern-0: \\|([^|]+)\\| +Another example: Programs I use often output "absolute path: " at the +beginning of a line when they process multiple files. The following +pattern matches the filename (note, there is a single space at the very +end): + + URxvt.selection.pattern-0: ^(/[^:]+):\ + You can look at the source of the selection extension to see more interesting uses, such as parsing a line from beginning to end. @@ -89,6 +99,23 @@ Binds a popup menu to Ctrl-Button2 that lets you toggle (some) options at runtime. +Other extensions can extend this popup menu by pushing a code reference +onto C<@{ $term->{option_popup_hook} }>, which gets called whenever the +popup is being displayed. + +Its sole argument is the popup menu, which can be modified. It should +either return nothing or a string, the initial boolean value and a code +reference. The string will be used as button text and the code reference +will be called when the toggle changes, with the new boolean value as +first argument. + +The following will add an entry C that changes +C<< $self->{myoption} >>: + + push @{ $self->{term}{option_popup_hook} }, sub { + ("my option" => $myoption, sub { $self->{myoption} = $_[0] }) + }; + =item selection-popup (enabled by default) Binds a popup menu to Ctrl-Button3 that lets you convert the selection @@ -96,11 +123,11 @@ evaluation, web-browser starting etc.), depending on content. Other extensions can extend this popup menu by pushing a code reference -onto C<@{ $term->{selection_popup_hook} }>, that is called whenever the -popup is displayed. +onto C<@{ $term->{selection_popup_hook} }>, which gets called whenever the +popup is being displayed. -It's sole argument is the popup menu, which can be modified. The selection -is in C<$_>, which can be used to decide wether to add something or not. +Its sole argument is the popup menu, which can be modified. The selection +is in C<$_>, which can be used to decide whether to add something or not. It should either return nothing or a string and a code reference. The string will be used as button text and the code reference will be called when the button gets activated and should transform C<$_>. @@ -110,7 +137,7 @@ Cs: push @{ $self->{term}{selection_popup_hook} }, sub { - /a/ ? ("a to be" => sub { s/a/b/g } + /a/ ? ("a to b" => sub { s/a/b/g } : () }; @@ -127,7 +154,38 @@ bottom. C leaves search mode and returns to the point where search was started, while C or C stay at the current position and additionally stores the first match in the current line into the primary -selection. +selection if the C modifier is active. + +The regex defaults to "(?i)", resulting in a case-insensitive search. To +get a case-sensitive search you can delete this prefix using C +or simply use an uppercase character which removes the "(?i)" prefix. + +See L for more info about perl regular expression syntax. + +=item readline (enabled by default) + +A support package that tries to make editing with readline easier. At +the moment, it reacts to clicking shift-left mouse button by trying to +move the text cursor to this position. It does so by generating as many +cursor-left or cursor-right keypresses as required (this only works +for programs that correctly support wide characters). + +To avoid too many false positives, this is only done when: + +=over 4 + +=item - the tty is in ICANON state. + +=item - the text cursor is visible. + +=item - the primary screen is currently being displayed. + +=item - the mouse is on the same (multi-row-) line as the text cursor. + +=back + +The normal selection mechanism isn't disabled, so quick successive clicks +might interfere with selection creation in harmless ways. =item selection-autotransform @@ -164,24 +222,10 @@ every error message as a selection pattern, and the second line transforms the message into vi commands to load the file. -=item readline - -A support package that tries to make editing with readline easier. At the -moment, it reacts to clicking with the left mouse button by trying to -move the text cursor to this position. It does so by generating as many -cursor-left or cursor-right keypresses as required (the this only works -for programs that correctly support wide characters). - -It only works when clicking into the same line (possibly extended over -multiple rows) as the text cursor and on the primary screen, to reduce the -risk of misinterpreting. The normal selection isn't disabled, so quick -successive clicks might interfere with selection creation in harmless -ways. - =item tabbed This transforms the terminal into a tabbar with additional terminals, that -is, it implements what is commonly refered to as "tabbed terminal". The topmost line +is, it implements what is commonly referred to as "tabbed terminal". The topmost line displays a "[NEW]" button, which, when clicked, will add a new tab, followed by one button per tab. @@ -189,24 +233,89 @@ B will switch to the tab left or right of the current one, while B creates a new tab. -=item mark-urls +The tabbar itself can be configured similarly to a normal terminal, but +with a resource class of C. In addition, it supports the +following four resources (shown with defaults): + + URxvt.tabbed.tabbar-fg: + URxvt.tabbed.tabbar-bg: + URxvt.tabbed.tab-fg: + URxvt.tabbed.tab-bg: + +See I in the @@RXVT_NAME@@(1) manpage for valid +indices. + +=item matcher + +Uses per-line display filtering (C) to underline text +matching a certain pattern and make it clickable. When clicked with the +mouse button specified in the C resource (default 2, or +middle), the program specified in the C resource +(default, the C resource, C) will be started +with the matched text as first argument. The default configuration is +suitable for matching URLs and launching a web browser, like the +former "mark-urls" extension. + +The default pattern to match URLs can be overridden with the +C resource, and additional patterns can be specified +with numbered patterns, in a manner similar to the "selection" extension. +The launcher can also be overridden on a per-pattern basis. + +It is possible to activate the most recently seen match or a list of matches +from the keyboard. Simply bind a keysym to "perl:matcher:last" or +"perl:matcher:list" as seen in the example below. + +Example configuration: + + URxvt.perl-ext: default,matcher + URxvt.urlLauncher: sensible-browser + URxvt.keysym.C-Delete: perl:matcher:last + URxvt.keysym.M-Delete: perl:matcher:list + URxvt.matcher.button: 1 + URxvt.matcher.pattern.1: \\bwww\\.[\\w-]+\\.[\\w./?&@#-]*[\\w/-] + URxvt.matcher.pattern.2: \\B(/\\S+?):(\\d+)(?=:|$) + URxvt.matcher.launcher.2: gvim +$2 $1 + +=item xim-onthespot -Uses per-line display filtering (C) to underline urls and -make them clickable. When middle-clicked, the program specified in the -resource C (default C) will be started with -the URL as first argument. +This (experimental) perl extension implements OnTheSpot editing. It does +not work perfectly, and some input methods don't seem to work well with +OnTheSpot editing in general, but it seems to work at least for SCIM and +kinput2. -=item automove-background +You enable it by specifying this extension and a preedit style of +C, i.e.: -This is basically a one-line extension that dynamically changes the background pixmap offset -to the window position, in effect creating the same effect as pseudo transparency with -a custom pixmap. No scaling is supported in this mode. Exmaple: + @@RXVT_NAME@@ -pt OnTheSpot -pe xim-onthespot - @@RXVT_NAME@@ -pixmap background.xpm -pe automove-background +=item kuake + +A very primitive quake-console-like extension. It was inspired by a +description of how the programs C and C work: Whenever the +user presses a global accelerator key (by default C), the terminal +will show or hide itself. Another press of the accelerator key will hide +or show it again. + +Initially, the window will not be shown when using this extension. + +This is useful if you need a single terminal that is not using any desktop +space most of the time but is quickly available at the press of a key. + +The accelerator key is grabbed regardless of any modifiers, so this +extension will actually grab a physical key just for this function. + +If you want a quake-like animation, tell your window manager to do so +(fvwm can do it). + +=item overlay-osc + +This extension implements some OSC commands to display timed popups on the +screen - useful for status displays from within scripts. You have to read +the sources for more info. =item block-graphics-to-ascii -A not very useful example of filtering all text output to the terminal, +A not very useful example of filtering all text output to the terminal by replacing all line-drawing characters (U+2500 .. U+259F) by a similar-looking ascii character. @@ -214,15 +323,29 @@ Displays a digital clock using the built-in overlay. -=item example-refresh-hooks +=item remote-clipboard -Displays a very simple digital clock in the upper right corner of the -window. Illustrates overwriting the refresh callbacks to create your own -overlays or changes. +Somewhat of a misnomer, this extension adds two menu entries to the +selection popup that allows one to run external commands to store the +selection somewhere and fetch it again. + +We use it to implement a "distributed selection mechanism", which just +means that one command uploads the file to a remote server, and another +reads it. + +The commands can be set using the C and +C resources. The first should read the +selection to store from STDIN (always in UTF-8), the second should provide +the selection data on STDOUT (also in UTF-8). + +The defaults (which are likely useless to you) use rsh and cat: + + URxvt.remote-selection.store: rsh ruth 'cat >/tmp/distributed-selection' + URxvt.remote-selection.fetch: rsh ruth 'cat /tmp/distributed-selection' =item selection-pastebin -This is a little rarely useful extension that Uploads the selection as +This is a little rarely useful extension that uploads the selection as textfile to a remote site (or does other things). (The implementation is not currently secure for use in a multiuser environment as it writes to F directly.). @@ -249,6 +372,44 @@ URxvt.selection-pastebin.url: http://www.ta-sa.org/files/txt/% +I xrdb uses the C preprocessor, which might interpret +the double C characters as comment start. Use C<\057\057> instead, +which works regardless of whether xrdb is used to parse the resource file +or not. + +=item macosx-clipboard and macosx-clipboard-native + +These two modules implement an extended clipboard for Mac OS X. They are +used like this: + + URxvt.perl-ext-common: default,macosx-clipboard + URxvt.keysym.M-c: perl:macosx-clipboard:copy + URxvt.keysym.M-v: perl:macosx-clipboard:paste + +The difference between them is that the native variant requires a +perl from apple's devkit or so, and C requires the +C module, works with other perls, has fewer bugs, is +simpler etc. etc. + +=item example-refresh-hooks + +Displays a very simple digital clock in the upper right corner of the +window. Illustrates overwriting the refresh callbacks to create your own +overlays or changes. + +=item confirm-paste + +Displays a confirmation dialog when a paste containing at least a full +line is detected. + +=item bell-command + +Runs the command specified by the C resource when +a bell event occurs. For example, the following pops up a notification +bubble with the text "Beep, Beep" using notify-send: + + URxvt.bell-command: notify-send "Beep, Beep" + =back =head1 API DOCUMENTATION @@ -273,7 +434,7 @@ =item $text -Rxvt-unicodes special way of encoding text, where one "unicode" character +Rxvt-unicode's special way of encoding text, where one "unicode" character always represents one screen cell. See L for a discussion of this format. =item $string @@ -287,16 +448,23 @@ Either binary data or - more common - a text string encoded in a locale-specific way. +=item $keysym + +an integer that is a valid X11 keysym code. You can convert a string +into a keysym and viceversa by using C and +C. + =back =head2 Extension Objects -Very perl extension is a perl class. A separate perl object is created -for each terminal and each extension and passed as the first parameter to -hooks. So extensions can use their C<$self> object without having to think -about other extensions, with the exception of methods and members that -begin with an underscore character C<_>: these are reserved for internal -use. +Every perl extension is a perl class. A separate perl object is created +for each terminal, and each terminal has its own set of extension objects, +which are passed as the first parameter to hooks. So extensions can use +their C<$self> object without having to think about clashes with other +extensions or other terminals, with the exception of methods and members +that begin with an underscore character C<_>: these are reserved for +internal use. Although it isn't a C object, you can call all methods of the C class on this object. @@ -327,7 +495,7 @@ The following subroutines can be declared in extension files, and will be called whenever the relevant event happens. -The first argument passed to them is an extension oject as described in +The first argument passed to them is an extension object as described in the in the C section. B of these hooks must return a boolean value. If any of the called @@ -350,13 +518,12 @@ =item on_start $term Called at the very end of initialisation of a new terminal, just before -trying to map (display) the toplevel and returning to the mainloop. +trying to map (display) the toplevel and returning to the main loop. =item on_destroy $term -Called whenever something tries to destroy terminal, before doing anything -yet. If this hook returns true, then destruction is skipped, but this is -rarely a good idea. +Called whenever something tries to destroy terminal, when the terminal is +still fully functional (not for long, though). =item on_reset $term @@ -388,13 +555,13 @@ requested from the server. The selection text can be queried and changed by calling C<< $term->selection >>. -Returning a true value aborts selection grabbing. It will still be hilighted. +Returning a true value aborts selection grabbing. It will still be highlighted. =item on_sel_extend $term Called whenever the user tries to extend the selection (e.g. with a double click) and is either supposed to return false (normal operation), or -should extend the selection itelf and return true to suppress the built-in +should extend the selection itself and return true to suppress the built-in processing. This can happen multiple times, as long as the callback returns true, it will be called on every further click by the user and is supposed to enlarge the selection more and more, if possible. @@ -403,7 +570,7 @@ =item on_view_change $term, $offset -Called whenever the view offset changes, i..e the user or program +Called whenever the view offset changes, i.e. the user or program scrolls. Offset C<0> means display the normal terminal, positive values show this many lines of scrollback. @@ -417,19 +584,42 @@ $nrow - 1) represent the lines to be scrolled out). C<$saved> is the total number of lines that will be in the scrollback buffer. -=item on_osc_seq $term, $string +=item on_osc_seq $term, $op, $args, $resp + +Called on every OSC sequence and can be used to suppress it or modify its +behaviour. The default should be to return an empty list. A true value +suppresses execution of the request completely. Make sure you don't get +confused by recursive invocations when you output an OSC sequence within +this callback. + +C should be used for new behaviour. + +=item on_osc_seq_perl $term, $args, $resp Called whenever the B command sequence (OSC = operating system command) is processed. Cursor position and other state information is up-to-date when this happens. For interoperability, the -string should start with the extension name and a colon, to distinguish -it from commands for other extensions, and this might be enforced in the -future. +string should start with the extension name (sans -osc) and a semicolon, +to distinguish it from commands for other extensions, and this might be +enforced in the future. + +For example, C uses this: + + sub on_osc_seq_perl { + my ($self, $osc, $resp) = @_; + + return unless $osc =~ s/^overlay;//; + + ... process remaining $osc string + } Be careful not ever to trust (in a security sense) the data you receive, -as its source can not easily be controleld (e-mail content, messages from +as its source can not easily be controlled (e-mail content, messages from other users on the same system etc.). +For responses, C<$resp> contains the end-of-args separator used by the +sender. + =item on_add_lines $term, $string Called whenever text is about to be output, with the text as argument. You @@ -443,6 +633,13 @@ Called whenever some data is written to the tty/pty and can be used to suppress or filter tty input. +=item on_tt_paste $term, $octets + +Called whenever text is about to be pasted, with the text as argument. You +can filter/change and paste the text yourself by returning a true value +and calling C<< $term->tt_paste >> yourself. C<$octets> is +locale-encoded. + =item on_line_update $term, $row Called whenever a line was updated or changed. Can be used to filter @@ -459,8 +656,8 @@ =item on_refresh_begin $term -Called just before the screen gets redrawn. Can be used for overlay -or similar effects by modify terminal contents in refresh_begin, and +Called just before the screen gets redrawn. Can be used for overlay or +similar effects by modifying the terminal contents in refresh_begin, and restoring them in refresh_end. The built-in overlay and selection display code is run after this hook, and takes precedence. @@ -468,18 +665,38 @@ Called just after the screen gets redrawn. See C. -=item on_keyboard_command $term, $string +=item on_user_command $term, $string -Called whenever the user presses a key combination that has a -C action bound to it (see description of the B +Called whenever a user-configured event is being activated (e.g. via +a C action bound to a key, see description of the B resource in the @@RXVT_NAME@@(1) manpage). +The event is simply the action string. This interface is assumed to change +slightly in the future. + +=item on_register_command $term, $keysym, $modifiermask, $string + +Called after parsing a keysym resource but before registering the +associated binding. If this hook returns TRUE the binding is not +registered. It can be used to modify a binding by calling +C. + +=item on_resize_all_windows $term, $new_width, $new_height + +Called just after the new window size has been calculated, but before +windows are actually being resized or hints are being set. If this hook +returns TRUE, setting of the window hints is being skipped. + =item on_x_event $term, $event Called on every X event received on the vt window (and possibly other windows). Should only be used as a last resort. Most event structure members are not passed. +=item on_root_event $term, $event + +Like C, but is called for events on the root window. + =item on_focus_in $term Called whenever the window gets the keyboard focus, before rxvt-unicode @@ -487,7 +704,7 @@ =item on_focus_out $term -Called wheneever the window loses keyboard focus, before rxvt-unicode does +Called whenever the window loses keyboard focus, before rxvt-unicode does focus out processing. =item on_configure_notify $term, $event @@ -508,8 +725,8 @@ =item on_unmap_notify $term, $event -Called whenever the corresponding X event is received for the terminal If -the hook returns true, then the even will be ignored by rxvt-unicode. +Called whenever the corresponding X event is received for the terminal. If +the hook returns true, then the event will be ignored by rxvt-unicode. The event is a hash with most values as named by Xlib (see the XEvent manpage), with the additional members C and C, which are the @@ -529,6 +746,10 @@ Called when various types of ClientMessage events are received (all with format=32, WM_PROTOCOLS or WM_PROTOCOLS:WM_DELETE_WINDOW). +=item on_bell $term + +Called on receipt of a bell character. + =back =cut @@ -543,8 +764,8 @@ our $VERSION = 1; our $TERM; -our @TERM_INIT; -our @TERM_EXT; +our @TERM_INIT; # should go, prevents async I/O etc. +our @TERM_EXT; # should go, prevents async I/O etc. our @HOOKNAME; our %HOOKTYPE = map +($HOOKNAME[$_] => $_), 0..$#HOOKNAME; our %OPTION; @@ -554,7 +775,7 @@ our $RESCLASS; our $RXVTNAME; -our $NOCHAR = chr 0xfffe; +our $NOCHAR = chr 0xffff; =head2 Variables in the C Package @@ -580,12 +801,12 @@ =item @urxvt::TERM_INIT -All coderefs in this array will be called as methods of the next newly +All code references in this array will be called as methods of the next newly created C object (during the C phase). The array -gets cleared before the codereferences that were in it are being executed, -so coderefs can push themselves onto it again if they so desire. +gets cleared before the code references that were in it are being executed, +so references can push themselves onto it again if they so desire. -This complements to the perl-eval commandline option, but gets executed +This complements to the perl-eval command line option, but gets executed first. =item @urxvt::TERM_EXT @@ -602,13 +823,14 @@ =item urxvt::fatal $errormessage -Fatally aborts execution with the given error message. Avoid at all -costs! The only time this is acceptable is when the terminal process -starts up. +Fatally aborts execution with the given error message (which should +include a trailing newline). Avoid at all costs! The only time this +is acceptable (and useful) is in the init hook, where it prevents the +terminal from starting up. =item urxvt::warn $string -Calls C with the given string which should not include a +Calls C with the given string which should include a trailing newline. The module also overwrites the C builtin with a function that calls this function. @@ -617,6 +839,13 @@ Messages have a size limit of 1023 bytes currently. +=item @terms = urxvt::termlist + +Returns all urxvt::term objects that exist in this process, regardless of +whether they are started, being destroyed etc., so be careful. Only term +objects that have perl extensions attached will be returned (because there +is no urxvt::term object associated with others). + =item $time = urxvt::NOW Returns the "current time" (as per the event loop). @@ -668,7 +897,8 @@ Return the rendition mask used for overlays by default. -=item $rendbit = urxvt::RS_Bold, RS_Italic, RS_Blink, RS_RVid, RS_Uline +=item $rendbit = urxvt::RS_Bold, urxvt::RS_Italic, urxvt::RS_Blink, +urxvt::RS_RVid, urxvt::RS_Uline Return the bit that enabled bold, italic, blink, reverse-video and underline, respectively. To enable such a style, just logically OR it into @@ -684,6 +914,8 @@ =item $rend = urxvt::SET_BGCOLOR $rend, $new_colour +=item $rend = urxvt::SET_COLOR $rend, $new_fg, $new_bg + Replace the foreground/background colour in the rendition mask with the specified one. @@ -711,6 +943,67 @@ }; } +no warnings 'utf8'; + +sub parse_resource { + my ($term, $name, $isarg, $longopt, $flag, $value) = @_; + + $term->scan_meta; + + my $r = $term->{meta}{resource}; + while (my ($pattern, $v) = each %$r) { + $name =~ y/-/./ if $isarg; + + if ( + $pattern =~ /\.$/ + ? $pattern eq substr $name, 0, length $pattern + : $pattern eq $name + ) { + $name = "$urxvt::RESCLASS.$name"; + + push @TERM_EXT, $v->[0]; + + if ($v->[1] eq "boolean") { + $term->put_option_db ($name, $flag ? "true" : "false"); + return 1; + } else { + $term->put_option_db ($name, $value); + return 1 + 2; + } + } + } + + 0 +} + +sub usage { + my ($term, $usage_type) = @_; + + $term->scan_meta; + + my $r = $term->{meta}{resource}; + + for my $pattern (sort keys %$r) { + my ($ext, $type, $desc) = @{ $r->{$pattern} }; + + $desc .= " (-pe $ext)"; + + if ($usage_type == 1) { + $pattern =~ y/./-/; + $pattern =~ s/-$/-.../g; + + if ($type eq "boolean") { + urxvt::log sprintf " -%-30s %s\n", "/+$pattern", $desc; + } else { + urxvt::log sprintf " -%-30s %s\n", "$pattern $type", $desc; + } + } else { + $pattern =~ s/\.$/.*/g; + urxvt::log sprintf " %-31s %s\n", "$pattern:", $type; + } + } +} + my $verbosity = $ENV{URXVT_PERL_VERBOSITY}; sub verbose { @@ -736,7 +1029,7 @@ or die "$path: $!"; my $source = - "package $pkg; use strict; use utf8;\n" + "package $pkg; use strict; use utf8; no warnings 'utf8';\n" . "#line 1 \"$path\"\n{\n" . (do { local $/; <$fh> }) . "\n};\n1"; @@ -756,8 +1049,8 @@ my $htype = shift; if ($htype == 0) { # INIT - my @dirs = ((split /:/, $TERM->resource ("perl_lib")), "$LIBDIR/perl"); - + my @dirs = $TERM->perl_libdirs; + my %ext_arg; { @@ -771,7 +1064,7 @@ for (grep $_, map { split /,/, $TERM->resource ("perl_ext_$_") } 1, 2) { if ($_ eq "default") { - $ext_arg{$_} ||= [] for qw(selection option-popup selection-popup searchable-scrollback); + $ext_arg{$_} ||= [] for qw(selection option-popup selection-popup searchable-scrollback readline); } elsif (/^-(.*)$/) { delete $ext_arg{$1}; } elsif (/^([^<]+)<(.*)>$/) { @@ -781,11 +1074,11 @@ } } - while (my ($ext, $argv) = each %ext_arg) { + for my $ext (sort keys %ext_arg) { my @files = grep -f $_, map "$_/$ext", @dirs; if (@files) { - $TERM->register_package (extension_package $files[0], $argv); + $TERM->register_package (extension_package $files[0], $ext_arg{$ext}); } else { warn "perl extension '$ext' not found in perl library search path\n"; } @@ -801,10 +1094,8 @@ verbose 10, "$HOOKNAME[$htype] (" . (join ", ", $TERM, @_) . ")" if $verbosity >= 10; - keys %$cb; - - while (my ($pkg, $cb) = each %$cb) { - my $retval_ = eval { $cb->($TERM->{_pkg}{$pkg}, @_) }; + for my $pkg (keys %$cb) { + my $retval_ = eval { $cb->{$pkg}->($TERM->{_pkg}{$pkg}, @_) }; $retval ||= $retval_; if ($@) { @@ -828,6 +1119,35 @@ $retval } +sub SET_COLOR($$$) { + SET_BGCOLOR (SET_FGCOLOR ($_[0], $_[1]), $_[2]) +} + +sub rend2mask { + no strict 'refs'; + my ($str, $mask) = (@_, 0); + my %color = ( fg => undef, bg => undef ); + my @failed; + for my $spec ( split /\s+/, $str ) { + if ( $spec =~ /^([fb]g)[_:-]?(\d+)/i ) { + $color{lc($1)} = $2; + } else { + my $neg = $spec =~ s/^[-^]//; + unless ( exists &{"RS_$spec"} ) { + push @failed, $spec; + next; + } + my $cur = &{"RS_$spec"}; + if ( $neg ) { + $mask &= ~$cur; + } else { + $mask |= $cur; + } + } + } + ($mask, @color{qw(fg bg)}, \@failed) +} + # urxvt::term::extension package urxvt::term::extension; @@ -900,13 +1220,14 @@ The sole purpose of this class is to deliver an interface to the C module - any module using it will work inside urxvt without further programming. The only exception is that you cannot wait on -condition variables, but non-blocking condvar use is ok. What this means -is that you cannot use blocking APIs, but the non-blocking variant should -work. +condition variables, but non-blocking condvar use is ok. + +In practical terms this means is that you cannot use blocking APIs, but +the non-blocking variant should work. =cut -our $VERSION = 1; +our $VERSION = '5.23'; $INC{"urxvt/anyevent.pm"} = 1; # mark us as there push @AnyEvent::REGISTRY, [urxvt => urxvt::anyevent::]; @@ -918,8 +1239,8 @@ urxvt::timer ->new - ->start (urxvt::NOW + $arg{after}) - ->cb (sub { + ->after ($arg{after}, $arg{interval}) + ->cb ($arg{interval} ? $cb : sub { $_[0]->stop; # need to cancel manually $cb->(); }) @@ -929,36 +1250,51 @@ my ($class, %arg) = @_; my $cb = $arg{cb}; + my $fd = fileno $arg{fh}; + defined $fd or $fd = $arg{fh}; bless [$arg{fh}, urxvt::iow ->new - ->fd (fileno $arg{fh}) + ->fd ($fd) ->events (($arg{poll} =~ /r/ ? 1 : 0) | ($arg{poll} =~ /w/ ? 2 : 0)) ->start - ->cb (sub { - $cb->(($_[1] & 1 ? 'r' : '') - . ($_[1] & 2 ? 'w' : '')); - })], - urxvt::anyevent:: + ->cb ($cb) + ], urxvt::anyevent:: } -sub DESTROY { - $_[0][1]->stop; +sub idle { + my ($class, %arg) = @_; + + my $cb = $arg{cb}; + + urxvt::iw + ->new + ->start + ->cb ($cb) } -sub condvar { - bless \my $flag, urxvt::anyevent::condvar:: +sub child { + my ($class, %arg) = @_; + + my $cb = $arg{cb}; + + urxvt::pw + ->new + ->start ($arg{pid}) + ->cb (sub { + $_[0]->stop; # need to cancel manually + $cb->($_[0]->rpid, $_[0]->rstatus); + }) } -sub urxvt::anyevent::condvar::broadcast { - ${$_[0]}++; +sub DESTROY { + $_[0][1]->stop; } -sub urxvt::anyevent::condvar::wait { - unless (${$_[0]}) { - Carp::croak "AnyEvent->condvar blocking wait unsupported in urxvt, use a non-blocking API"; - } +# only needed for AnyEvent < 6 compatibility +sub one_event { + Carp::croak "AnyEvent->one_event blocking wait unsupported in urxvt, use a non-blocking API"; } package urxvt::term; @@ -995,6 +1331,53 @@ } } +sub perl_libdirs { + map { split /:/ } + $_[0]->resource ("perl_lib"), + $ENV{URXVT_PERL_LIB}, + "$ENV{HOME}/.urxvt/ext", + "$LIBDIR/perl" +} + +sub scan_meta { + my ($self) = @_; + my @libdirs = perl_libdirs $self; + + return if $self->{meta_libdirs} eq join "\x00", @libdirs; + + my %meta; + + $self->{meta_libdirs} = join "\x00", @libdirs; + $self->{meta} = \%meta; + + for my $dir (reverse @libdirs) { + opendir my $fh, $dir + or next; + for my $ext (readdir $fh) { + $ext ne "." + and $ext ne ".." + and open my $fh, "<", "$dir/$ext" + or next; + + while (<$fh>) { + if (/^#:META:X_RESOURCE:(.*)/) { + my ($pattern, $type, $desc) = split /:/, $1; + $pattern =~ s/^%(?:\.|$)/$ext./g; # % in pattern == extension name + if ($pattern =~ /[^a-zA-Z0-9\-\.]/) { + warn "$dir/$ext: meta resource '$pattern' contains illegal characters (not alphanumeric nor . nor *)\n"; + } else { + $meta{resource}{$pattern} = [$ext, $type, $desc]; + } + } elsif (/^\s*(?:#|$)/) { + # skip other comments and empty lines + } else { + last; # stop parsing on first non-empty non-comment line + } + } + } + } +} + =item $term = new urxvt::term $envhashref, $rxvtname, [arg...] Creates a new terminal, very similar as if you had started it with system @@ -1004,14 +1387,18 @@ Croaks (and probably outputs an error message) if the new instance couldn't be created. Returns C if the new instance didn't initialise perl, and the terminal object otherwise. The C and -C hooks will be called during this call. +C hooks will be called before this call returns, and are free to +refer to global data (which is race free). =cut sub new { my ($class, $env, @args) = @_; - _new ([ map "$_=$env->{$_}", keys %$env ], @args); + $env or Carp::croak "environment hash missing in call to urxvt::term->new"; + @args or Carp::croak "name argument missing in call to urxvt::term->new"; + + _new ([ map "$_=$env->{$_}", keys %$env ], \@args); } =item $term->destroy @@ -1051,15 +1438,16 @@ optionally change it. All option values are stored by name in the hash C<%urxvt::OPTION>. Options not enabled in this binary are not in the hash. -Here is a a likely non-exhaustive list of option names, please see the +Here is a likely non-exhaustive list of option names, please see the source file F to see the actual list: - borderLess console cursorBlink cursorUnderline hold iconic insecure - intensityStyles jumpScroll loginShell mapAlert meta8 mouseWheelScrollPage - override-redirect pastableTabs pointerBlank reverseVideo scrollBar - scrollBar_floating scrollBar_right scrollTtyKeypress scrollTtyOutput - scrollWithBuffer secondaryScreen secondaryScroll skipBuiltinGlyphs - transparent tripleclickwords utmpInhibit visualBell + borderLess buffered console cursorBlink cursorUnderline hold iconic + insecure intensityStyles iso14755 iso14755_52 jumpScroll loginShell + mapAlert meta8 mouseWheelScrollPage override_redirect pastableTabs + pointerBlank reverseVideo scrollBar scrollBar_floating scrollBar_right + scrollTtyKeypress scrollTtyOutput scrollWithBuffer secondaryScreen + secondaryScroll skipBuiltinGlyphs skipScroll transparent tripleclickwords + urgentOnBell utmpInhibit visualBell =item $value = $term->resource ($name[, $newval]) @@ -1078,30 +1466,31 @@ Please note that resource strings will currently only be freed when the terminal is destroyed, so changing options frequently will eat memory. -Here is a a likely non-exhaustive list of resource names, not all of which +Here is a likely non-exhaustive list of resource names, not all of which are supported in every build, please see the source file F to see the actual list: - answerbackstring backgroundPixmap backspace_key boldFont boldItalicFont - borderLess color cursorBlink cursorUnderline cutchars delete_key - display_name embed ext_bwidth fade font geometry hold iconName - imFont imLocale inputMethod insecure int_bwidth intensityStyles - italicFont jumpScroll lineSpace loginShell mapAlert meta8 modifier + answerbackstring backgroundPixmap backspace_key blendtype blurradius + boldFont boldItalicFont borderLess buffered chdir color cursorBlink + cursorUnderline cutchars delete_key depth display_name embed ext_bwidth + fade font geometry hold iconName iconfile imFont imLocale inputMethod + insecure int_bwidth intensityStyles iso14755 iso14755_52 italicFont + jumpScroll letterSpace lineSpace loginShell mapAlert meta8 modifier mouseWheelScrollPage name override_redirect pastableTabs path perl_eval perl_ext_1 perl_ext_2 perl_lib pointerBlank pointerBlankDelay preeditType print_pipe pty_fd reverseVideo saveLines scrollBar scrollBar_align scrollBar_floating scrollBar_right scrollBar_thickness scrollTtyKeypress scrollTtyOutput scrollWithBuffer scrollstyle - secondaryScreen secondaryScroll selectstyle shade term_name title - transient_for transparent transparent_all tripleclickwords utmpInhibit - visualBell + secondaryScreen secondaryScroll shade skipBuiltinGlyphs skipScroll + term_name title transient_for transparent tripleclickwords urgentOnBell + utmpInhibit visualBell =cut sub resource($$;$) { my ($self, $name) = (shift, shift); unshift @_, $self, $name, ($name =~ s/\s*\+\s*(\d+)$// ? $1 : 0); - &urxvt::term::_resource + goto &urxvt::term::_resource } =item $value = $term->x_resource ($pattern) @@ -1115,11 +1504,34 @@ only one resource database per display, and later invocations might return the wrong resources. -=item $success = $term->parse_keysym ($keysym_spec, $command_string) +=item $value = $term->x_resource_boolean ($pattern) + +Like C, above, but interprets the string value as a boolean +and returns C<1> for true values, C<0> for false values and C if +the resource or option isn't specified. + +You should always use this method to parse boolean resources. + +=cut + +sub x_resource_boolean { + my $res = &x_resource; -Adds a keymap translation exactly as specified via a resource. See the + $res =~ /^\s*(?:true|yes|on|1)\s*$/i ? 1 : defined $res && 0 +} + +=item $success = $term->parse_keysym ($key, $octets) + +Adds a key binding exactly as specified via a resource. See the C resource in the @@RXVT_NAME@@(1) manpage. +=item $term->register_command ($keysym, $modifiermask, $string) + +Adds a key binding. This is a lower level api compared to +C, as it expects a parsed key description, and can be +used only inside either the C hook, to add a binding, or the +C hook, to modify a parsed binding. + =item $rend = $term->rstyle ([$new_rstyle]) Return and optionally change the current rendition. Text that is output by @@ -1136,25 +1548,38 @@ =item ($row, $col) = $term->selection_end ([$row, $col]) -Return the current values of the selection mark, begin or end positions, -and optionally set them to new values. +Return the current values of the selection mark, begin or end positions. + +When arguments are given, then the selection coordinates are set to +C<$row> and C<$col>, and the selection screen is set to the current +screen. + +=item $screen = $term->selection_screen ([$screen]) + +Returns the current selection screen, and then optionally sets it. =item $term->selection_make ($eventtime[, $rectangular]) Tries to make a selection as set by C and C. If C<$rectangular> is true (default: false), a -rectangular selection will be made. This is the prefered function to make +rectangular selection will be made. This is the preferred function to make a selection. -=item $success = $term->selection_grab ($eventtime) +=item $success = $term->selection_grab ($eventtime[, $clipboard]) -Try to request the primary selection text from the server (for example, as -set by the next method). No visual feedback will be given. This function +Try to acquire ownership of the primary (clipboard if C<$clipboard> is +true) selection from the server. The corresponding text can be set +with the next method. No visual feedback will be given. This function is mostly useful from within C hooks. -=item $oldtext = $term->selection ([$newtext]) +=item $oldtext = $term->selection ([$newtext, $clipboard]) + +Return the current selection (clipboard if C<$clipboard> is true) text +and optionally replace it by C<$newtext>. -Return the current selection text and optionally replace it by C<$newtext>. +=item $term->selection_clear ([$clipboard]) + +Revoke ownership of the primary (clipboard if C<$clipboard> is true) selection. =item $term->overlay_simple ($x, $y, $text) @@ -1194,12 +1619,14 @@ =over 4 -=item $overlay->set ($x, $y, $text, $rend) +=item $overlay->set ($x, $y, $text[, $rend]) Similar to C<< $term->ROW_t >> and C<< $term->ROW_r >> in that it puts text in rxvt-unicode's special encoding and an array of rendition values at a specific position inside the overlay. +If C<$rend> is missing, then the rendition will not be changed. + =item $overlay->hide If visible, hide the overlay, but do not destroy it. @@ -1290,10 +1717,16 @@ =item $term->tt_write ($octets) -Write the octets given in C<$data> to the tty (i.e. as program input). To +Write the octets given in C<$octets> to the tty (i.e. as program input). To pass characters instead of octets, you should convert your strings first to the locale-specific encoding using C<< $term->locale_encode >>. +=item $term->tt_paste ($octets) + +Write the octets given in C<$octets> to the tty as a paste, converting NL to +CR and bracketing the data with control sequences if bracketed paste mode +is set. + =item $old_events = $term->pty_ev_events ([$new_events]) Replaces the event mask of the pty watcher by the given event mask. Can @@ -1301,6 +1734,11 @@ description of C<< urxvt::timer->events >>. Make sure to always restore the previous value. +=item $fd = $term->pty_fd + +Returns the master file descriptor for the pty in use, or C<-1> if no pty +is used. + =item $windowid = $term->parent Return the window id of the toplevel window. @@ -1316,6 +1754,20 @@ $term->vt_emask_add (urxvt::PointerMotionMask); +=item $term->set_urgency ($set) + +Enable/disable the urgency hint on the toplevel window. + +=item $term->focus_in + +=item $term->focus_out + +=item $term->key_press ($state, $keycode[, $time]) + +=item $term->key_release ($state, $keycode[, $time]) + +Deliver various fake events to to terminal. + =item $window_width = $term->width =item $window_height = $term->height @@ -1355,14 +1807,19 @@ Returns a copy of the environment in effect for the terminal as a hashref similar to C<\%ENV>. +=item @envv = $term->envv + +Returns the environment as array of strings of the form C. + +=item @argv = $term->argv + +Return the argument vector as this terminal, similar to @ARGV, but +includes the program name as first element. + =cut sub env { - if (my $env = $_[0]->_env) { - +{ map /^([^=]+)(?:=(.*))?$/s && ($1 => $2), @$env } - } else { - +{ %ENV } - } + +{ map /^([^=]+)(?:=(.*))?$/s && ($1 => $2), $_[0]->envv } } =item $modifiermask = $term->ModLevel3Mask @@ -1378,6 +1835,10 @@ Returns the currently displayed screen (0 primary, 1 secondary). +=item $cursor_is_hidden = $term->hidden_cursor + +Returns whether the cursor is currently hidden or not. + =item $view_start = $term->view_start ([$newvalue]) Returns the row number of the topmost displayed line. Maximum value is @@ -1394,10 +1855,9 @@ =item $text = $term->ROW_t ($row_number[, $new_text[, $start_col]]) -Returns the text of the entire row with number C<$row_number>. Row C<0> -is the topmost terminal line, row C<< $term->$ncol-1 >> is the bottommost -terminal line. The scrollback buffer starts at line C<-1> and extends to -line C<< -$term->nsaved >>. Nothing will be returned if a nonexistent line +Returns the text of the entire row with number C<$row_number>. Row C<< $term->top_row >> +is the topmost terminal line, row C<< $term->nrow-1 >> is the bottommost +terminal line. Nothing will be returned if a nonexistent line is requested. If C<$new_text> is specified, it will replace characters in the current @@ -1405,10 +1865,10 @@ to replace only parts of a line. The font index in the rendition will automatically be updated. -C<$text> is in a special encoding: tabs and wide characters that use -more than one cell when displayed are padded with C<$urxvt::NOCHAR> +C<$text> is in a special encoding: tabs and wide characters that use more +than one cell when displayed are padded with C<$urxvt::NOCHAR> (chr 65535) characters. Characters with combining characters and other characters that -do not fit into the normal tetx encoding will be replaced with characters +do not fit into the normal text encoding will be replaced with characters in the private use area. You have to obey this encoding when changing text. The advantage is @@ -1563,17 +2023,20 @@ =item $string = $term->special_decode $text -Converts rxvt-unicodes text reprsentation into a perl string. See +Converts rxvt-unicodes text representation into a perl string. See C<< $term->ROW_t >> for details. -=item $success = $term->grab_button ($button, $modifiermask) +=item $success = $term->grab_button ($button, $modifiermask[, $window = $term->vt]) + +=item $term->ungrab_button ($button, $modifiermask[, $window = $term->vt]) -Registers a synchronous button grab. See the XGrabButton manpage. +Register/unregister a synchronous button grab. See the XGrabButton +manpage. =item $success = $term->grab ($eventtime[, $sync]) Calls XGrabPointer and XGrabKeyboard in asynchronous (default) or -synchronous (C<$sync> is true). Also remembers the grab timestampe. +synchronous (C<$sync> is true). Also remembers the grab timestamp. =item $term->allow_events_async @@ -1590,7 +2053,7 @@ =item $term->ungrab -Calls XUngrab for the most recent grab. Is called automatically on +Calls XUngrabPointer and XUngrabKeyboard for the most recent grab. Is called automatically on evaluation errors, as it is better to lose the grab in the error case as the session. @@ -1602,7 +2065,7 @@ =item ($type,$format,$octets) = $term->XGetWindowProperty ($window, $property) -=item $term->XChangeWindowProperty ($window, $property, $type, $format, $octets) +=item $term->XChangeProperty ($window, $property, $type, $format, $octets) =item $term->XDeleteProperty ($window, $property) @@ -1620,9 +2083,13 @@ =item $term->XChangeInput ($window, $add_events[, $del_events]) +=item $keysym = $term->XStringToKeysym ($string) + +=item $string = $term->XKeysymToString ($keysym) + Various X or X-related functions. The C<$term> object only serves as the source of the display, otherwise those functions map more-or-less -directory onto the X functions of the same name. +directly onto the X functions of the same name. =back @@ -1696,16 +2163,16 @@ $self->add_item ({ type => "button", text => $text, activate => $cb}); } -=item $popup->add_toggle ($text, $cb, $initial_value) +=item $popup->add_toggle ($text, $initial_value, $cb) -Adds a toggle/checkbox item to the popup. Teh callback gets called -whenever it gets toggled, with a boolean indicating its value as its first -argument. +Adds a toggle/checkbox item to the popup. The callback gets called +whenever it gets toggled, with a boolean indicating its new value as its +first argument. =cut sub add_toggle { - my ($self, $text, $cb, $value) = @_; + my ($self, $text, $value, $cb) = @_; my $item; $item = { type => "button", @@ -1734,14 +2201,21 @@ delete $env->{LC_ALL}; $env->{LC_CTYPE} = $self->{term}->locale; - urxvt::term->new ($env, "popup", - "--perl-lib" => "", "--perl-ext-common" => "", - "-pty-fd" => -1, "-sl" => 0, - "-b" => 1, "-bd" => "grey80", "-bl", "-override-redirect", - "--transient-for" => $self->{term}->parent, - "-display" => $self->{term}->display_id, - "-pe" => "urxvt-popup") - or die "unable to create popup window\n"; + my $term = urxvt::term->new ( + $env, "popup", + "--perl-lib" => "", "--perl-ext-common" => "", + "-pty-fd" => -1, "-sl" => 0, + "-b" => 1, "-bd" => "grey80", "-bl", "-override-redirect", + "--transient-for" => $self->{term}->parent, + "-display" => $self->{term}->display_id, + "-pe" => "urxvt-popup", + ) or die "unable to create popup window\n"; + + unless (delete $term->{urxvt_popup_init_done}) { + $term->ungrab; + $term->destroy; + die "unable to initialise popup window\n"; + } } sub DESTROY { @@ -1757,11 +2231,6 @@ package urxvt::watcher; -@urxvt::timer::ISA = __PACKAGE__; -@urxvt::iow::ISA = __PACKAGE__; -@urxvt::pw::ISA = __PACKAGE__; -@urxvt::iw::ISA = __PACKAGE__; - =head2 The C Class This class implements timer watchers/events. Time is represented as a @@ -1774,7 +2243,7 @@ ->cb (sub { $term->{overlay}->set (0, 0, sprintf "%2d:%02d:%02d", (localtime urxvt::NOW)[2,1,0]); - }); + }); =over 4 @@ -1787,17 +2256,14 @@ Set the callback to be called when the timer triggers. -=item $tstamp = $timer->at +=item $timer = $timer->set ($tstamp[, $interval]) -Return the time this watcher will fire next. - -=item $timer = $timer->set ($tstamp) - -Set the time the event is generated to $tstamp. +Set the time the event is generated to $tstamp (and optionally specifies a +new $interval). =item $timer = $timer->interval ($interval) -Normally (and when C<$interval> is C<0>), the timer will automatically +By default (and when C<$interval> is C<0>), the timer will automatically stop after it has fired once. If C<$interval> is non-zero, then the timer is automatically rescheduled at the given intervals. @@ -1805,11 +2271,12 @@ Start the timer. -=item $timer = $timer->start ($tstamp) +=item $timer = $timer->start ($tstamp[, $interval]) -Set the event trigger time to C<$tstamp> and start the timer. +Set the event trigger time to C<$tstamp> and start the timer. Optionally +also replaces the interval. -=item $timer = $timer->after ($delay) +=item $timer = $timer->after ($delay[, $interval]) Like C, but sets the expiry timer to c. @@ -1827,7 +2294,7 @@ $term->{iow} = urxvt::iow ->new ->fd (fileno $term->{socket}) - ->events (urxvt::EVENT_READ) + ->events (urxvt::EV_READ) ->start ->cb (sub { my ($iow, $revents) = @_; @@ -1850,13 +2317,13 @@ =item $iow = $iow->fd ($fd) -Set the filedescriptor (not handle) to watch. +Set the file descriptor (not handle) to watch. =item $iow = $iow->events ($eventmask) Set the event mask to watch. The only allowed values are -C and C, which might be ORed -together, or C. +C and C, which might be ORed +together, or C. =item $iow = $iow->start @@ -1864,7 +2331,7 @@ =item $iow = $iow->stop -Stop watching for events on the given filehandle. +Stop watching for events on the given file handle. =back @@ -1907,7 +2374,7 @@ ->cb (sub { my ($pw, $exit_status) = @_; ... - }); + }); =over 4 @@ -1921,7 +2388,7 @@ =item $pw = $timer->start ($pid) -Tells the wqtcher to start watching for process C<$pid>. +Tells the watcher to start watching for process C<$pid>. =item $pw = $pw->stop @@ -1944,15 +2411,17 @@ =item >=10 - all called hooks -=item >=11 - hook reutrn values +=item >=11 - hook return values =back =head1 AUTHOR - Marc Lehmann + Marc Lehmann http://software.schmorp.de/pkg/rxvt-unicode =cut 1 + +# vim: sw=3: