*** empty log message ***
[dana/urxvt.git] / src / urxvt.pm
1 =encoding utf8
2
3 =head1 NAME
4
5 @@RXVT_NAME@@perl - rxvt-unicode's embedded perl interpreter
6
7 =head1 SYNOPSIS
8
9    # create a file grab_test in $HOME:
10
11    sub on_sel_grab {
12       warn "you selected ", $_[0]->selection;
13       ()
14    }
15
16    # start a @@RXVT_NAME@@ using it:
17
18    @@RXVT_NAME@@ --perl-lib $HOME -pe grab_test
19
20 =head1 DESCRIPTION
21
22 Everytime a terminal object gets created, scripts specified via the
23 C<perl> resource are loaded and associated with it.
24
25 Scripts are compiled in a 'use strict' and 'use utf8' environment, and
26 thus must be encoded as UTF-8.
27
28 Each script will only ever be loaded once, even in @@RXVT_NAME@@d, where
29 scripts will be shared (but not enabled) for all terminals.
30
31 =head2 Prepackaged Extensions
32
33 This section describes the extensiosn delivered with this version. You can
34 find them in F<@@RXVT_LIBDIR@@/urxvt/perl/>.
35
36 You can activate them like this:
37
38   @@RXVT_NAME@@ -pe <extensionname>
39
40 =over 4
41
42 =item selection
43
44 Miscellaneous selection modifications.
45
46 =over 4
47
48 =item rot13
49
50 Rot-13 the selection when activated. Used via keyboard trigger:
51
52    URxvt.keysym.C-M-r: perl:selection:rot13
53
54 =back
55
56 =item digital-clock
57
58 Displays a very simple digital clock in the upper right corner of the
59 window. Illustrates overwriting the refresh callbacks to create your own
60 overlays or changes.
61
62 =item simple-overlay-clock
63
64 Displays a digital clock using the built-in overlay (colourful, useless).
65
66 =back
67
68 =head2 General API Considerations
69
70 All objects (such as terminals, time watchers etc.) are typical
71 reference-to-hash objects. The hash can be used to store anything you
72 like. All members starting with an underscore (such as C<_ptr> or
73 C<_hook>) are reserved for internal uses and must not be accessed or
74 modified).
75
76 When objects are destroyed on the C++ side, the perl object hashes are
77 emptied, so its best to store related objects such as time watchers and
78 the like inside the terminal object so they get destroyed as soon as the
79 terminal is destroyed.
80
81 =head2 Hooks
82
83 The following subroutines can be declared in loaded scripts, and will be called
84 whenever the relevant event happens.
85
86 All of them must return a boolean value. If it is true, then the event
87 counts as being I<consumed>, and the invocation of other hooks is skipped,
88 and the relevant action might not be carried out by the C++ code.
89
90 When in doubt, return a false value (preferably C<()>).
91
92 =over 4
93
94 =item on_init $term
95
96 Called after a new terminal object has been initialized, but before
97 windows are created or the command gets run.
98
99 =item on_reset $term
100
101 Called after the screen is "reset" for any reason, such as resizing or
102 control sequences. Here is where you can react on changes to size-related
103 variables.
104
105 =item on_start $term
106
107 Called at the very end of initialisation of a new terminal, just before
108 returning to the mainloop.
109
110 =item on_sel_make $term, $eventtime
111
112 Called whenever a selection has been made by the user, but before the
113 selection text is copied, so changes to the beginning, end or type of the
114 selection will be honored.
115
116 Returning a true value aborts selection making by urxvt, in which case you
117 have to make a selection yourself by calling C<< $term->selection_grab >>.
118
119 =item on_sel_grab $term, $eventtime
120
121 Called whenever a selection has been copied, but before the selection is
122 requested from the server.  The selection text can be queried and changed
123 by calling C<< $term->selection >>.
124
125 Returning a true value aborts selection grabbing. It will still be hilighted.
126
127 =item on_focus_in $term
128
129 Called whenever the window gets the keyboard focus, before urxvt does
130 focus in processing.
131
132 =item on_focus_out $term
133
134 Called wheneever the window loses keyboard focus, before urxvt does focus
135 out processing.
136
137 =item on_view_change $term, $offset
138
139 Called whenever the view offset changes, i..e the user or program
140 scrolls. Offset C<0> means display the normal terminal, positive values
141 show this many lines of scrollback.
142
143 =item on_scroll_back $term, $lines, $saved
144
145 Called whenever lines scroll out of the terminal area into the scrollback
146 buffer. C<$lines> is the number of lines scrolled out and may be larger
147 than the scroll back buffer or the terminal.
148
149 It is called before lines are scrolled out (so rows 0 .. min ($lines - 1,
150 $nrow - 1) represent the lines to be scrolled out). C<$saved> is the total
151 number of lines that will be in the scrollback buffer.
152
153 =item on_tty_activity $term *NYI*
154
155 Called whenever the program(s) running in the urxvt window send output.
156
157 =item on_refresh_begin $term
158
159 Called just before the screen gets redrawn. Can be used for overlay
160 or similar effects by modify terminal contents in refresh_begin, and
161 restoring them in refresh_end. The built-in overlay and selection display
162 code is run after this hook, and takes precedence.
163
164 =item on_refresh_end $term
165
166 Called just after the screen gets redrawn. See C<on_refresh_begin>.
167
168 =item on_keyboard_command $term, $string
169
170 Called whenever the user presses a key combination that has a
171 C<perl:string> action bound to it (see description of the B<keysym>
172 resource in the @@RXVT_NAME@@(1) manpage).
173
174 =back
175
176 =head2 Functions in the C<urxvt> Package
177
178 =over 4
179
180 =item urxvt::fatal $errormessage
181
182 Fatally aborts execution with the given error message. Avoid at all
183 costs! The only time this is acceptable is when the terminal process
184 starts up.
185
186 =item urxvt::warn $string
187
188 Calls C<rxvt_warn> with the given string which should not include a
189 newline. The module also overwrites the C<warn> builtin with a function
190 that calls this function.
191
192 Using this function has the advantage that its output ends up in the
193 correct place, e.g. on stderr of the connecting urxvtc client.
194
195 =item $time = urxvt::NOW
196
197 Returns the "current time" (as per the event loop).
198
199 =head2 RENDITION
200
201 Rendition bitsets contain information about colour, font, font styles and
202 similar information for each screen cell.
203
204 The following "macros" deal with changes in rendition sets. You should
205 never just create a bitset, you should always modify an existing one,
206 as they contain important information required for correct operation of
207 rxvt-unicode.
208
209 =over 4
210
211 =item $rend = urxvt::DEFAULT_RSTYLE
212
213 Returns the default rendition, as used when the terminal is starting up or
214 being reset. Useful as a base to start when creating renditions.
215
216 =item $rend = urxvt::OVERLAY_RSTYLE
217
218 Return the rendition mask used for overlays by default.
219
220 =item $rendbit = urxvt::RS_Bold, RS_Italic, RS_Blink, RS_RVid, RS_Uline
221
222 Return the bit that enabled bold, italic, blink, reverse-video and
223 underline, respectively. To enable such a style, just logically OR it into
224 the bitset.
225
226 =item $foreground = urxvt::GET_BASEFG $rend
227
228 =item $background = urxvt::GET_BASEBG $rend
229
230 Return the foreground/background colour index, respectively.
231
232 =item $rend = urxvt::SET_FGCOLOR ($rend, $new_colour)
233
234 =item $rend = urxvt::SET_BGCOLOR ($rend, $new_colour)
235
236 Replace the foreground/background colour in the rendition mask with the
237 specified one.
238
239 =item $value = urxvt::GET_CUSTOM ($rend)
240
241 Return the "custom" value: Every rendition has 5 bits for use by
242 extensions. They can be set and changed as you like and are initially
243 zero.
244
245 =item $rend = urxvt::SET_CUSTOM ($rend, $new_value)
246
247 Change the custom value.
248
249 =back
250
251 =cut
252
253 package urxvt;
254
255 use strict;
256
257 our $term;
258 our @HOOKNAME;
259 our $LIBDIR;
260
261 BEGIN {
262    urxvt->bootstrap;
263
264    # overwrite perl's warn
265    *CORE::GLOBAL::warn = sub {
266       my $msg = join "", @_;
267       $msg .= "\n"
268          unless $msg =~ /\n$/;
269       urxvt::warn ($msg);
270    };
271 }
272
273 my @hook_count;
274 my $verbosity = $ENV{URXVT_PERL_VERBOSITY};
275
276 sub verbose {
277    my ($level, $msg) = @_;
278    warn "$msg\n" if $level <= $verbosity;
279 }
280
281 # find on_xxx subs in the package and register them
282 # as hooks
283 sub register_package($) {
284    my ($pkg) = @_;
285
286    for my $htype (0.. $#HOOKNAME) {
287       my $name = $HOOKNAME[$htype];
288
289       my $ref = $pkg->can ("on_" . lc $name)
290          or next;
291
292       $term->{_hook}[$htype]{$ref*1} = $ref;
293       $hook_count[$htype]++
294          or set_should_invoke $htype, 1;
295    }
296 }
297
298 my $script_pkg = "script0000";
299 my %script_pkg;
300
301 # load a single script into its own package, once only
302 sub script_package($) {
303    my ($path) = @_;
304
305    $script_pkg{$path} ||= do {
306       my $pkg = "urxvt::" . ($script_pkg++);
307
308       verbose 3, "loading script '$path' into package '$pkg'";
309
310       open my $fh, "<:raw", $path
311          or die "$path: $!";
312
313       my $source = "package $pkg; use strict; use utf8;\n"
314                    . "#line 1 \"$path\"\n{\n"
315                    . (do { local $/; <$fh> })
316                    . "\n};\n1";
317
318       eval $source or die "$path: $@";
319
320       $pkg
321    }
322 }
323
324 # called by the rxvt core
325 sub invoke {
326    local $term = shift;
327    my $htype = shift;
328
329    if ($htype == 0) { # INIT
330       my @dirs = ((split /:/, $term->resource ("perl_lib")), "$LIBDIR/perl");
331
332       for my $ext (split /:/, $term->resource ("perl_ext")) {
333          my @files = grep -f $_, map "$_/$ext", @dirs;
334
335          if (@files) {
336             register_package script_package $files[0];
337          } else {
338             warn "perl extension '$ext' not found in perl library search path\n";
339          }
340       }
341
342    } elsif ($htype == 1) { # DESTROY
343       if (my $hook = $term->{_hook}) {
344          for my $htype (0..$#$hook) {
345             $hook_count[$htype] -= scalar keys %{ $hook->[$htype] || {} }
346                or set_should_invoke $htype, 0;
347          }
348       }
349    }
350
351    my $cb = $term->{_hook}[$htype]
352       or return;
353
354    verbose 10, "$HOOKNAME[$htype] (" . (join ", ", $term, @_) . ")"
355       if $verbosity >= 10;
356
357    while (my ($k, $v) = each %$cb) {
358       return 1 if $v->($term, @_);
359    }
360
361    0
362 }
363
364 =back
365
366 =head2 The C<urxvt::term> Class
367
368 =over 4
369
370 =item $value = $term->resource ($name[, $newval])
371
372 Returns the current resource value associated with a given name and
373 optionally sets a new value. Setting values is most useful in the C<init>
374 hook. Unset resources are returned and accepted as C<undef>.
375
376 The new value must be properly encoded to a suitable character encoding
377 before passing it to this method. Similarly, the returned value may need
378 to be converted from the used encoding to text.
379
380 Resource names are as defined in F<src/rsinc.h>. Colours can be specified
381 as resource names of the form C<< color+<index> >>, e.g. C<color+5>. (will
382 likely change).
383
384 Please note that resource strings will currently only be freed when the
385 terminal is destroyed, so changing options frequently will eat memory.
386
387 Here is a a likely non-exhaustive list of resource names, not all of which
388 are supported in every build, please see the source to see the actual
389 list:
390
391   answerbackstring backgroundPixmap backspace_key boldFont boldItalicFont
392   borderLess color cursorBlink cursorUnderline cutchars delete_key
393   display_name embed ext_bwidth fade font geometry hold iconName
394   imFont imLocale inputMethod insecure int_bwidth intensityStyles
395   italicFont jumpScroll lineSpace loginShell mapAlert menu meta8 modifier
396   mouseWheelScrollPage name pastableTabs path perl_eval perl_ext
397   perl_lib pointerBlank pointerBlankDelay preeditType print_pipe pty_fd
398   reverseVideo saveLines scrollBar scrollBar_align scrollBar_floating
399   scrollBar_right scrollBar_thickness scrollTtyKeypress scrollTtyOutput
400   scrollWithBuffer scrollstyle secondaryScreen secondaryScroll selectstyle
401   shade term_name title transparent transparent_all tripleclickwords
402   utmpInhibit visualBell
403
404 =cut
405
406 sub urxvt::term::resource($$;$) {
407    my ($self, $name) = (shift, shift);
408    unshift @_, $self, $name, ($name =~ s/\s*\+\s*(\d+)$// ? $1 : 0);
409    goto &urxvt::term::_resource;
410 }
411
412 =item ($row, $col) = $term->selection_mark ([$row, $col])
413
414 =item ($row, $col) = $term->selection_beg ([$row, $col])
415
416 =item ($row, $col) = $term->selection_end ([$row, $col])
417
418 Return the current values of the selection mark, begin or end positions,
419 and optionally set them to new values.
420
421 =item $success = $term->selection_grab ($eventtime)
422
423 Try to request the primary selection from the server (for example, as set
424 by the next method).
425
426 =item $oldtext = $term->selection ([$newtext])
427
428 Return the current selection text and optionally replace it by C<$newtext>.
429
430 =item $term->scr_overlay ($x, $y, $text)
431
432 Create a simple multi-line overlay box. See the next method for details.
433
434 =cut
435
436 sub urxvt::term::scr_overlay {
437    my ($self, $x, $y, $text) = @_;
438
439    my @lines = split /\n/, $text;
440
441    my $w = 0;
442    for (map $self->strwidth ($_), @lines) {
443       $w = $_ if $w < $_;
444    }
445
446    $self->scr_overlay_new ($x, $y, $w, scalar @lines);
447    $self->scr_overlay_set (0, $_, $lines[$_]) for 0.. $#lines;
448 }
449
450 =item $term->scr_overlay_new ($x, $y, $width, $height)
451
452 Create a new (empty) overlay at the given position with the given
453 width/height. A border will be put around the box. If either C<$x> or
454 C<$y> is negative, then this is counted from the right/bottom side,
455 respectively.
456
457 =item $term->scr_overlay_off
458
459 Switch the overlay off again.
460
461 =item $term->scr_overlay_set_char ($x, $y, $char, $rend = OVERLAY_RSTYLE)
462
463 Put a single character (specified numerically) at the given overlay
464 position.
465
466 =item $term->scr_overlay_set ($x, $y, $text)
467
468 Write a string at the given position into the overlay.
469
470 =item $cellwidth = $term->strwidth $string
471
472 Returns the number of screen-cells this string would need. Correctly
473 accounts for wide and combining characters.
474
475 =item $octets = $term->locale_encode $string
476
477 Convert the given text string into the corresponding locale encoding.
478
479 =item $string = $term->locale_decode $octets
480
481 Convert the given locale-encoded octets into a perl string.
482
483 =item $term->tt_write ($octets)
484
485 Write the octets given in C<$data> to the tty (i.e. as program input). To
486 pass characters instead of octets, you should convert your strings first
487 to the locale-specific encoding using C<< $term->locale_encode >>.
488
489 =item $nrow = $term->nrow
490
491 =item $ncol = $term->ncol
492
493 Return the number of rows/columns of the terminal window (i.e. as
494 specified by C<-geometry>, excluding any scrollback).
495
496 =item $nsaved = $term->nsaved
497
498 Returns the number of lines in the scrollback buffer.
499
500 =item $view_start = $term->view_start ([$newvalue])
501
502 Returns the negative row number of the topmost line. Minimum value is
503 C<0>, which displays the normal terminal contents. Larger values scroll
504 this many lines into the scrollback buffer.
505
506 =item $term->want_refresh
507
508 Requests a screen refresh. At the next opportunity, rxvt-unicode will
509 compare the on-screen display with its stored representation. If they
510 differ, it redraws the differences.
511
512 Used after changing terminal contents to display them.
513
514 =item $text = $term->ROW_t ($row_number[, $new_text[, $start_col]])
515
516 Returns the text of the entire row with number C<$row_number>. Row C<0>
517 is the topmost terminal line, row C<< $term->$ncol-1 >> is the bottommost
518 terminal line. The scrollback buffer starts at line C<-1> and extends to
519 line C<< -$term->nsaved >>.
520
521 If C<$new_text> is specified, it will replace characters in the current
522 line, starting at column C<$start_col> (default C<0>), which is useful
523 to replace only parts of a line. The font index in the rendition will
524 automatically be updated.
525
526 C<$text> is in a special encoding: tabs and wide characters that use more
527 than one cell when displayed are padded with urxvt::NOCHAR characters
528 (C<chr 65535>). Characters with combining characters and other characters
529 that do not fit into the normal tetx encoding will be replaced with
530 characters in the private use area.
531
532 You have to obey this encoding when changing text. The advantage is
533 that C<substr> and similar functions work on screen cells and not on
534 characters.
535
536 The methods C<< $term->special_encode >> and C<< $term->special_decode >>
537 can be used to convert normal strings into this encoding and vice versa.
538
539 =item $rend = $term->ROW_r ($row_number[, $new_rend[, $start_col]])
540
541 Like C<< $term->ROW_t >>, but returns an arrayref with rendition
542 bitsets. Rendition bitsets contain information about colour, font, font
543 styles and similar information. See also C<< $term->ROW_t >>.
544
545 When setting rendition, the font mask will be ignored.
546
547 See the section on RENDITION, above.
548
549 =item $length = $term->ROW_l ($row_number[, $new_length])
550
551 Returns the number of screen cells that are in use ("the line length"). If
552 it is C<-1>, then the line is part of a multiple-row logical "line", which
553 means all characters are in use and it is continued on the next row.
554
555 =item $text = $term->special_encode $string
556
557 Converts a perl string into the special encoding used by rxvt-unicode,
558 where one character corresponds to one screen cell. See
559 C<< $term->ROW_t >> for details.
560
561 =item $string = $term->special_decode $text
562
563 Converts rxvt-unicodes text reprsentation into a perl string. See
564 C<< $term->ROW_t >> for details.
565
566 =back
567
568 =head2 The C<urxvt::timer> Class
569
570 This class implements timer watchers/events. Time is represented as a
571 fractional number of seconds since the epoch. Example:
572
573    # create a digital clock display in upper right corner
574    $term->{timer} = urxvt::timer
575                     ->new
576                     ->start (urxvt::NOW)
577                     ->cb (sub {
578                        my ($timer) = @_;
579                        my $time = $timer->at;
580                        $timer->start ($time + 1);
581                        $self->scr_overlay (-1, 0, 
582                           POSIX::strftime "%H:%M:%S", localtime $time);
583                     });
584
585 =over 4
586
587 =item $timer = new urxvt::timer
588
589 Create a new timer object in stopped state.
590
591 =item $timer = $timer->cb (sub { my ($timer) = @_; ... })
592
593 Set the callback to be called when the timer triggers.
594
595 =item $tstamp = $timer->at
596
597 Return the time this watcher will fire next.
598
599 =item $timer = $timer->set ($tstamp)
600
601 Set the time the event is generated to $tstamp.
602
603 =item $timer = $timer->start
604
605 Start the timer.
606
607 =item $timer = $timer->start ($tstamp)
608
609 Set the event trigger time to C<$tstamp> and start the timer.
610
611 =item $timer = $timer->stop
612
613 Stop the timer.
614
615 =back
616
617 =head2 The C<urxvt::iow> Class
618
619 This class implements io watchers/events. Example:
620
621   $term->{socket} = ...
622   $term->{iow} = urxvt::iow
623                  ->new
624                  ->fd (fileno $term->{socket})
625                  ->events (1) # wait for read data
626                  ->start
627                  ->cb (sub {
628                    my ($iow, $revents) = @_;
629                    # $revents must be 1 here, no need to check
630                    sysread $term->{socket}, my $buf, 8192
631                       or end-of-file;
632                  });
633
634
635 =over 4
636
637 =item $iow = new urxvt::iow
638
639 Create a new io watcher object in stopped state.
640
641 =item $iow = $iow->cb (sub { my ($iow, $reventmask) = @_; ... })
642
643 Set the callback to be called when io events are triggered. C<$reventmask>
644 is a bitset as described in the C<events> method.
645
646 =item $iow = $iow->fd ($fd)
647
648 Set the filedescriptor (not handle) to watch.
649
650 =item $iow = $iow->events ($eventmask)
651
652 Set the event mask to watch. Bit #0 (value C<1>) enables watching for read
653 data, Bit #1 (value C<2>) enables watching for write data.
654
655 =item $iow = $iow->start
656
657 Start watching for requested events on the given handle.
658
659 =item $iow = $iow->stop
660
661 Stop watching for events on the given filehandle.
662
663 =back
664
665 =head1 ENVIRONMENT
666
667 =head2 URXVT_PERL_VERBOSITY
668
669 This variable controls the verbosity level of the perl extension. Higher
670 numbers indicate more verbose output.
671
672 =over 4
673
674 =item 0 - only fatal messages
675
676 =item 3 - script loading and management
677
678 =item 10 - all events received
679
680 =back
681
682 =head1 AUTHOR
683
684  Marc Lehmann <pcg@goof.com>
685  http://software.schmorp.de/pkg/rxvt-unicode
686
687 =cut
688
689 1