--- rxvt-unicode/src/urxvt.pm 2006/01/02 15:35:43 1.1 +++ rxvt-unicode/src/urxvt.pm 2006/01/05 01:04:10 1.33 @@ -1,29 +1,128 @@ +=encoding utf8 + =head1 NAME -urxvt - rxvt-unicode's embedded perl interpreter +@@RXVT_NAME@@perl - rxvt-unicode's embedded perl interpreter =head1 SYNOPSIS -Put your scripts into $LIBDIR/perl-init/, they will be loaded automatically. - -Each script will only be loaded once, even in urxvtd, and will be valid -globally. - -Scripts are evaluated in a 'use strict' and 'use utf8' environment, and -thus must be written in utf-8. + # create a file grab_test in $HOME: sub on_sel_grab { warn "you selected ", $_[0]->selection; + () } - 1 + # start a @@RXVT_NAME@@ using it: + + @@RXVT_NAME@@ --perl-lib $HOME -pe grab_test =head1 DESCRIPTION +Everytime a terminal object gets created, scripts specified via the +C resource are loaded and associated with it. + +Scripts are compiled in a 'use strict' and 'use utf8' environment, and +thus must be encoded as UTF-8. + +Each script will only ever be loaded once, even in @@RXVT_NAME@@d, where +scripts will be shared (but not enabled) for all terminals. + +=head2 Prepackaged Extensions + +This section describes the extensiosn delivered with this version. You can +find them in F<@@RXVT_LIBDIR@@/urxvt/perl/>. + +You can activate them like this: + + @@RXVT_NAME@@ -pe + +=over 4 + +=item selection + +Intelligent selection. This extension tries to be more intelligent when +the user extends selections (double-click). Right now, it tries to select +urls and complete shell-quoted arguments, which is very convenient, too, +if your F supports C<--quoting-style=shell>. + +It also offers the following bindable event: + +=over 4 + +=item rot13 + +Rot-13 the selection when activated. Used via keyboard trigger: + + URxvt.keysym.C-M-r: perl:selection:rot13 + +=back + +=item digital-clock + +Displays a digital clock using the built-in overlay. + +=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 mark-urls + +A not very useful example of filtering all text output to the terminal, by +underlining all urls that matches a certain regex (i.e. some urls :). It +is not very useful because urls that are output in multiple steps (e.g. +when typing them) do not get marked. + +=back + +=head2 General API Considerations + +All objects (such as terminals, time watchers etc.) are typical +reference-to-hash objects. The hash can be used to store anything you +like. All members starting with an underscore (such as C<_ptr> or +C<_hook>) are reserved for internal uses and B be accessed or +modified). + +When objects are destroyed on the C++ side, the perl object hashes are +emptied, so its best to store related objects such as time watchers and +the like inside the terminal object so they get destroyed as soon as the +terminal is destroyed. + +Argument names also often indicate the type of a parameter. Here are some +hints on what they mean: + +=over 4 + +=item $text + +Rxvt-unicodes special way of encoding text, where one "unicode" character +always represents one screen cell. See L for a discussion of this format. + +=item $string + +A perl text string, with an emphasis on I. It can store all unicode +characters and is to be distinguished with text encoded in a specific +encoding (often locale-specific) and binary data. + +=item $octets + +Either binary data or - more common - a text string encoded in a +locale-specific way. + +=back + =head2 Hooks -The following subroutines can be declared in loaded scripts, and will be called -whenever the relevant event happens. +The following subroutines can be declared in loaded scripts, and will be +called whenever the relevant event happens. + +The first argument passed to them is an object private to each terminal +and extension package. You can call all C methods on it, but +its not a real C object. Instead, the real C +object that is shared between all packages is stored in the C +member. All of them must return a boolean value. If it is true, then the event counts as being I, and the invocation of other hooks is skipped, @@ -66,6 +165,15 @@ Returning a true value aborts selection grabbing. It will still be hilighted. +=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 +processing. + +See the F example extension. + =item on_focus_in $term Called whenever the window gets the keyboard focus, before urxvt does @@ -96,6 +204,27 @@ Called whenever the program(s) running in the urxvt window send output. +=item on_osc_seq $term, $string + +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. + +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 +other users on the same system etc.). + +=item on_add_lines $term, $string + +Called whenever text is about to be output, with the text as argument. You +can filter/change and output the text yourself by returning a true value +and calling C<< $term->scr_add_lines >> yourself. Please note that this +might be very slow, however, as your hook is called for B text being +output. + =item on_refresh_begin $term Called just before the screen gets redrawn. Can be used for overlay @@ -107,6 +236,23 @@ Called just after the screen gets redrawn. See C. +=item on_keyboard_command $term, $string + +Called whenever the user presses a key combination that has a +C action bound to it (see description of the B +resource in the @@RXVT_NAME@@(1) manpage). + +=back + +=head2 Variables in the C Package + +=over 4 + +=item $urxvt::TERM + +The current terminal. Whenever a callback/Hook is bein executed, this +variable stores the current C object. + =back =head2 Functions in the C Package @@ -121,29 +267,79 @@ =item urxvt::warn $string -Calls C witht eh given string which should not include a +Calls C with the given string which should not include a newline. The module also overwrites the C builtin with a function that calls this function. Using this function has the advantage that its output ends up in the correct place, e.g. on stderr of the connecting urxvtc client. -=item $cellwidth = urxvt::wcswidth $string - -Returns the number of screen-cells this string would need. Correctly -accounts for wide and combining characters. - =item $time = urxvt::NOW Returns the "current time" (as per the event loop). +=back + +=head2 RENDITION + +Rendition bitsets contain information about colour, font, font styles and +similar information for each screen cell. + +The following "macros" deal with changes in rendition sets. You should +never just create a bitset, you should always modify an existing one, +as they contain important information required for correct operation of +rxvt-unicode. + +=over 4 + +=item $rend = urxvt::DEFAULT_RSTYLE + +Returns the default rendition, as used when the terminal is starting up or +being reset. Useful as a base to start when creating renditions. + +=item $rend = urxvt::OVERLAY_RSTYLE + +Return the rendition mask used for overlays by default. + +=item $rendbit = urxvt::RS_Bold, RS_Italic, RS_Blink, RS_RVid, 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 +the bitset. + +=item $foreground = urxvt::GET_BASEFG $rend + +=item $background = urxvt::GET_BASEBG $rend + +Return the foreground/background colour index, respectively. + +=item $rend = urxvt::SET_FGCOLOR ($rend, $new_colour) + +=item $rend = urxvt::SET_BGCOLOR ($rend, $new_colour) + +Replace the foreground/background colour in the rendition mask with the +specified one. + +=item $value = urxvt::GET_CUSTOM ($rend) + +Return the "custom" value: Every rendition has 5 bits for use by +extensions. They can be set and changed as you like and are initially +zero. + +=item $rend = urxvt::SET_CUSTOM ($rend, $new_value) + +Change the custom value. + +=back + =cut package urxvt; use strict; +use Scalar::Util (); -our $term; +our $TERM; our @HOOKNAME; our $LIBDIR; @@ -159,30 +355,12 @@ }; } -my $verbosity = $ENV{URXVT_PERL_VERBOSITY} || 10; +my @hook_count; +my $verbosity = $ENV{URXVT_PERL_VERBOSITY}; sub verbose { my ($level, $msg) = @_; - warn "$msg\n"; #d# -} - -my @invoke_cb; - -# called by the rxvt core -sub invoke { - local $term = shift; - my $htype = shift; - - my $cb = $invoke_cb[$htype]; - - verbose 10, "$HOOKNAME[$htype] (" . (join ", ", $term, @_) . ")" - if $verbosity >= 10; - - while (my ($k, $v) = each %$cb) { - return 1 if $v->($term, @_); - } - - 0 + warn "$msg\n" if $level <= $verbosity; } # find on_xxx subs in the package and register them @@ -190,14 +368,15 @@ sub register_package($) { my ($pkg) = @_; - for my $hook (0.. $#HOOKNAME) { - my $name = $HOOKNAME[$hook]; + for my $htype (0.. $#HOOKNAME) { + my $name = $HOOKNAME[$htype]; my $ref = $pkg->can ("on_" . lc $name) or next; - $invoke_cb[$hook]{$ref*1} = $ref; - set_should_invoke $hook, 1; + $TERM->{_hook}[$htype]{$pkg} = $ref; + $hook_count[$htype]++ + or set_should_invoke $htype, 1; } } @@ -205,36 +384,159 @@ my %script_pkg; # load a single script into its own package, once only -sub load_script($) { +sub script_package($) { my ($path) = @_; $script_pkg{$path} ||= do { - my $pkg = $script_pkg++; + my $pkg = "urxvt::" . ($script_pkg++); + verbose 3, "loading script '$path' into package '$pkg'"; open my $fh, "<:raw", $path or die "$path: $!"; - eval "package $pkg; use strict; use utf8;\n" - . "#line 1 \"$path\"\n" - . do { local $/; <$fh> } - or die "$path: $@"; + my $source = "package $pkg; use strict; use utf8;\n" + . "#line 1 \"$path\"\n{\n" + . (do { local $/; <$fh> }) + . "\n};\n1"; - register_package $pkg; + eval $source or die "$path: $@"; $pkg - }; + } } -load_script $_ for grep -f $_, <$LIBDIR/perl-init/*>; +our $retval; # return value for urxvt +# called by the rxvt core +sub invoke { + local $TERM = shift; + my $htype = shift; -=back + if ($htype == 0) { # INIT + my @dirs = ((split /:/, $TERM->resource ("perl_lib")), "$LIBDIR/perl"); + + for my $ext (map { split /:/, $TERM->resource ("perl_ext_$_") } 1, 2) { + my @files = grep -f $_, map "$_/$ext", @dirs; + + if (@files) { + register_package script_package $files[0]; + } else { + warn "perl extension '$ext' not found in perl library search path\n"; + } + } + } + + $retval = undef; + + if (my $cb = $TERM->{_hook}[$htype]) { + verbose 10, "$HOOKNAME[$htype] (" . (join ", ", $TERM, @_) . ")" + if $verbosity >= 10; + + keys %$cb; + + while (my ($pkg, $cb) = each %$cb) { + $retval = $cb->( + $TERM->{_pkg}{$pkg} ||= do { + my $proxy = bless { }, urxvt::term::proxy::; + Scalar::Util::weaken ($proxy->{term} = $TERM); + $proxy + }, + @_, + ) and last; + } + } + + if ($htype == 1) { # DESTROY + # remove hooks if unused + if (my $hook = $TERM->{_hook}) { + for my $htype (0..$#$hook) { + $hook_count[$htype] -= scalar keys %{ $hook->[$htype] || {} } + or set_should_invoke $htype, 0; + } + } + + # clear package objects + %$_ = () for values %{ $TERM->{_pkg} }; + + # clear package + %$TERM = (); + } + + $retval +} + +sub urxvt::term::proxy::AUTOLOAD { + $urxvt::term::proxy::AUTOLOAD =~ /:([^:]+)$/ + or die "FATAL: \$AUTOLOAD '$urxvt::term::proxy::AUTOLOAD' unparsable"; + + eval qq{ + sub $urxvt::term::proxy::AUTOLOAD { + my \$proxy = shift; + \$proxy->{term}->$1 (\@_) + } + 1 + } or die "FATAL: unable to compile method forwarder: $@"; + + goto &$urxvt::term::proxy::AUTOLOAD; +} =head2 The C Class =over 4 +=item $value = $term->resource ($name[, $newval]) + +Returns the current resource value associated with a given name and +optionally sets a new value. Setting values is most useful in the C +hook. Unset resources are returned and accepted as C. + +The new value must be properly encoded to a suitable character encoding +before passing it to this method. Similarly, the returned value may need +to be converted from the used encoding to text. + +Resource names are as defined in F. Colours can be specified +as resource names of the form C<< color+ >>, e.g. C. (will +likely change). + +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 +are supported in every build, please see the source 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 menu meta8 modifier + mouseWheelScrollPage name 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 transparent transparent_all tripleclickwords + utmpInhibit visualBell + +=cut + +sub urxvt::term::resource($$;$) { + my ($self, $name) = (shift, shift); + unshift @_, $self, $name, ($name =~ s/\s*\+\s*(\d+)$// ? $1 : 0); + goto &urxvt::term::_resource; +} + +=item $rend = $term->rstyle ([$new_rstyle]) + +Return and optionally change the current rendition. Text that is output by +the terminal application will use this style. + +=item ($row, $col) = $term->screen_cur ([$row, $col]) + +Return the current coordinates of the text cursor position and optionally +set it (which is usually bad as applications don't expect that). + =item ($row, $col) = $term->selection_mark ([$row, $col]) =item ($row, $col) = $term->selection_beg ([$row, $col]) @@ -253,45 +555,286 @@ Return the current selection text and optionally replace it by C<$newtext>. -=item $term->scr_overlay ($x, $y, $text) +#=item $term->overlay ($x, $y, $text) +# +#Create a simple multi-line overlay box. See the next method for details. +# +#=cut +# +#sub urxvt::term::scr_overlay { +# my ($self, $x, $y, $text) = @_; +# +# my @lines = split /\n/, $text; +# +# my $w = 0; +# for (map $self->strwidth ($_), @lines) { +# $w = $_ if $w < $_; +# } +# +# $self->scr_overlay_new ($x, $y, $w, scalar @lines); +# $self->scr_overlay_set (0, $_, $lines[$_]) for 0.. $#lines; +#} + +=item $term->overlay ($x, $y, $width, $height[, $rstyle[, $border]]) + +Create a new (empty) overlay at the given position with the given +width/height. C<$rstyle> defines the initial rendition style +(default: C). + +If C<$border> is C<2> (default), then a decorative border will be put +around the box. + +If either C<$x> or C<$y> is negative, then this is counted from the +right/bottom side, respectively. + +This method returns an urxvt::overlay object. The overlay will be visible +as long as the perl object is referenced. + +The methods currently supported on C objects are: + +=over 4 + +=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. + +=item $overlay->hide + +If visible, hide the overlay, but do not destroy it. + +=item $overlay->show + +If hidden, display the overlay again. + +=back + +=item $cellwidth = $term->strwidth $string + +Returns the number of screen-cells this string would need. Correctly +accounts for wide and combining characters. + +=item $octets = $term->locale_encode $string + +Convert the given text string into the corresponding locale encoding. + +=item $string = $term->locale_decode $octets + +Convert the given locale-encoded octets into a perl string. + +=item $term->scr_add_lines ($string) + +Write the given text string to the screen, as if output by the application +running inside the terminal. It may not contain command sequences (escape +codes), but is free to use line feeds, carriage returns and tabs. The +string is a normal text string, not in locale-dependent encoding. + +Normally its not a good idea to use this function, as programs might be +confused by changes in cursor position or scrolling. Its useful inside a +C hook, though. + +=item $term->tt_write ($octets) + +Write the octets given in C<$data> 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 $window_width = $term->width + +=item $window_height = $term->height + +=item $font_width = $term->fwidth + +=item $font_height = $term->fheight + +=item $font_ascent = $term->fbase + +=item $terminal_rows = $term->nrow + +=item $terminal_columns = $term->ncol + +=item $has_focus = $term->focus + +=item $is_mapped = $term->mapped + +=item $max_scrollback = $term->saveLines + +=item $nrow_plus_saveLines = $term->total_rows + +=item $lines_in_scrollback = $term->nsaved + +Return various integers describing terminal characteristics. + +=item $view_start = $term->view_start ([$newvalue]) + +Returns the negative row number of the topmost line. Minimum value is +C<0>, which displays the normal terminal contents. Larger values scroll +this many lines into the scrollback buffer. + +=item $term->want_refresh -Create a simple multi-line overlay box. See the next method for details. +Requests a screen refresh. At the next opportunity, rxvt-unicode will +compare the on-screen display with its stored representation. If they +differ, it redraws the differences. + +Used after changing terminal contents to display them. + +=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 +is requested. + +If C<$new_text> is specified, it will replace characters in the current +line, starting at column C<$start_col> (default C<0>), which is useful +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 urxvt::NOCHAR characters +(C). Characters with combining characters and other characters +that do not fit into the normal tetx encoding will be replaced with +characters in the private use area. + +You have to obey this encoding when changing text. The advantage is +that C and similar functions work on screen cells and not on +characters. + +The methods C<< $term->special_encode >> and C<< $term->special_decode >> +can be used to convert normal strings into this encoding and vice versa. + +=item $rend = $term->ROW_r ($row_number[, $new_rend[, $start_col]]) + +Like C<< $term->ROW_t >>, but returns an arrayref with rendition +bitsets. Rendition bitsets contain information about colour, font, font +styles and similar information. See also C<< $term->ROW_t >>. + +When setting rendition, the font mask will be ignored. + +See the section on RENDITION, above. + +=item $length = $term->ROW_l ($row_number[, $new_length]) + +Returns the number of screen cells that are in use ("the line +length"). Unlike the urxvt core, this returns C<< $term->ncol >> if the +line is joined with the following one. + +=item $bool = $term->is_longer ($row_number) + +Returns true if the row is part of a multiple-row logical "line" (i.e. +joined with the following row), which means all characters are in use +and it is continued on the next row (and possibly a continuation of the +previous row(s)). + +=item $line = $term->line ($row_number) + +Create and return a new C object that stores information +about the logical line that row C<$row_number> is part of. It supports the +following methods: + +=over 4 + +=item $text = $line->t + +Returns the full text of the line, similar to C + +=item $rend = $line->r + +Returns the full rendition array of the line, similar to C + +=item $length = $line->l + +Returns the length of the line in cells, similar to C. + +=item $rownum = $line->beg + +=item $rownum = $line->end + +Return the row number of the first/last row of the line, respectively. + +=item $offset = $line->offset_of ($row, $col) + +Returns the character offset of the given row|col pair within the logical +line. + +=item ($row, $col) = $line->coord_of ($offset) + +Translates a string offset into terminal coordinates again. + +=back =cut -sub urxvt::term::scr_overlay { - my ($self, $x, $y, $text) = @_; +sub urxvt::term::line { + my ($self, $row) = @_; - my @lines = split /\n/, $text; + my $maxrow = $self->nrow - 1; - my $w = 0; - for (map urxvt::wcswidth $_, @lines) { - $w = $_ if $w < $_; - } + my ($beg, $end) = ($row, $row); - $self->scr_overlay_new ($x, $y, $w, scalar @lines); - $self->scr_overlay_set (0, $_, $lines[$_]) for 0.. $#lines; + --$beg while $self->ROW_is_longer ($beg - 1); + ++$end while $self->ROW_is_longer ($end) && $end < $maxrow; + + bless { + term => $self, + beg => $beg, + end => $end, + len => ($end - $beg) * $self->ncol + $self->ROW_l ($end), + }, urxvt::line:: } -=item $term->scr_overlay_new ($x, $y, $width, $height) +sub urxvt::line::t { + my ($self) = @_; -Create a new (empty) overlay at the given position with the given -width/height. A border will be put around the box. If either C<$x> or -C<$y> is negative, then this is counted from the right/bottom side, -respectively. + substr +(join "", map $self->{term}->ROW_t ($_), $self->{beg} .. $self->{end}), + 0, $self->{len} +} -=item $term->scr_overlay_off +sub urxvt::line::r { + my ($self) = @_; -Switch the overlay off again. + my $rend = [ + map @{ $self->{term}->ROW_r ($_) }, $self->{beg} .. $self->{end} + ]; + $#$rend = $self->{len} - 1; + $rend +} + +sub urxvt::line::beg { $_[0]{beg} } +sub urxvt::line::end { $_[0]{end} } +sub urxvt::line::l { $_[0]{len} } -=item $term->scr_overlay_set_char ($x, $y, $char, $rend = OVERLAY_RSTYLE) +sub urxvt::line::offset_of { + my ($self, $row, $col) = @_; + + ($row - $self->{beg}) * $self->{term}->ncol + $col +} -Put a single character (specified numerically) at the given overlay -position. +sub urxvt::line::coord_of { + my ($self, $offset) = @_; + + use integer; + + ( + $offset / $self->{term}->ncol + $self->{beg}, + $offset % $self->{term}->ncol + ) +} -=item $term->scr_overlay_set ($x, $y, $text) +=item ($row, $col) = $line->coord_of ($offset) +=item $text = $term->special_encode $string -Write a string at the given position into the overlay. +Converts a perl string into the special encoding used by rxvt-unicode, +where one character corresponds to one screen cell. See +C<< $term->ROW_t >> for details. + +=item $string = $term->special_decode $text + +Converts rxvt-unicodes text reprsentation into a perl string. See +C<< $term->ROW_t >> for details. =back @@ -300,23 +843,21 @@ This class implements timer watchers/events. Time is represented as a fractional number of seconds since the epoch. Example: - # create a digital clock display in upper right corner + $term->{overlay} = $term->overlay (-1, 0, 8, 1, urxvt::OVERLAY_RSTYLE, 0); $term->{timer} = urxvt::timer ->new - ->start (urxvt::NOW) + ->interval (1) ->cb (sub { - my ($timer) = @_; - my $time = $timer->at; - $timer->start ($time + 1); - $self->scr_overlay (-1, 0, - POSIX::strftime "%H:%M:%S", localtime $time); - }); + $term->{overlay}->set (0, 0, + sprintf "%2d:%02d:%02d", (localtime urxvt::NOW)[2,1,0]); + }); =over 4 =item $timer = new urxvt::timer -Create a new timer object in stopped state. +Create a new timer object in started state. It is scheduled to fire +immediately. =item $timer = $timer->cb (sub { my ($timer) = @_; ... }) @@ -330,6 +871,12 @@ Set the time the event is generated to $tstamp. +=item $timer = $timer->interval ($interval) + +Normally (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. + =item $timer = $timer->start Start the timer. @@ -392,6 +939,23 @@ =back +=head1 ENVIRONMENT + +=head2 URXVT_PERL_VERBOSITY + +This variable controls the verbosity level of the perl extension. Higher +numbers indicate more verbose output. + +=over 4 + +=item =0 - only fatal messages + +=item =3 - script loading and management + +=item =10 - all events received + +=back + =head1 AUTHOR Marc Lehmann