Debian Codegraph @

README

raw
1 NAME
2
3 Term::TermKey - perl wrapper around libtermkey
4
5 SYNOPSIS
6
7 use Term::TermKey;
8
9 my $tk = Term::TermKey->new( \*STDIN );
10
11 print "Press any key\n";
12
13 $tk->waitkey( my $key );
14
15 print "You pressed: " . $tk->format_key( $key, 0 );
16
17 DESCRIPTION
18
19 Note that libtermkey itself is deprecated in favour of its eventual
20 merge into libtickit. As a result, uses of this module should also be
21 considered deprecated. Consider rewriting code to use Tickit instead;
22 either by creating a Tickit::Term to receive key input events, or
23 perform a more wholescale rewrite into using Tickit generally for all
24 screen interaction purposes.
25
26 This module provides a light perl wrapper around the libtermkey
27 library. This library attempts to provide an abstract way to read
28 keypress events in terminal-based programs by providing structures that
29 describe keys, rather than simply returning raw bytes as read from the
30 TTY device.
31
32 This version of Term::TermKey requires libtermkey version at least
33 0.16.
34
35 Multi-byte keys, ambiguous keys, and waittime
36
37 Some keypresses generate multiple bytes from the terminal. There is
38 also the ambiguity between multi-byte CSI or SS3 sequences, and the
39 Escape key itself. The waittime timer is used to distinguish them.
40
41 When some bytes arrive that could be the start of possibly multiple
42 different keypress events, the library will attempt to wait for more
43 bytes to arrive that would finish it. If no more bytes arrive after
44 this time, then the bytes will be reported as events as they stand,
45 even if this results in interpreting a partially-complete Escape
46 sequence as a literal Escape key followed by some normal letters or
47 other symbols.
48
49 Similarly, if the start of an incomplete UTF-8 sequence arrives when
50 the library is in UTF-8 mode, this will be reported as the UTF-8
51 replacement character (U+FFFD) if it is incomplete after this time.
52
53 CONSTRUCTOR
54
55 new
56
57 $tk = Term::TermKey->new( $fh, $flags );
58
59 Construct a new Term::TermKey object that wraps the given term handle.
60 $fh should be either an IO handle reference, an integer referring to a
61 plain POSIX file descriptor, of undef. $flags is optional, but if given
62 should contain the flags to pass to libtermkey's constructor. Assumes a
63 default of 0 if not supplied. See the FLAG_* constants.
64
65 new_abstract
66
67 $tk = Term::TermKey->new_abstract( $termtype, $flags );
68
69 Construct a new abstract Term::TermKey object not associated with a
70 filehandle. Input may be fed to it using the push_bytes() method rather
71 than waitkey() or advisereadable(). The name of the termtype should be
72 given in the $termtype string.
73
74 METHODS
75
76 start
77
78 stop
79
80 $success = $tk->start;
81
82 $success = $tk->stop;
83
84 Start or stop IO interactions from the instance. Starting will send the
85 terminal initialisation sequence and set up termios(5) settings,
86 stopping will send the terminal shutdown sequence and restore
87 termios(5) back to the initial values. After construction, a
88 Term::TermKey instance is already started, but these methods may be
89 used to suspend and resume, for example, on receipt of a SIGTSTP signal
90 requesting that the application background itself.
91
92 Returns false if it fails; $! will contain an error code.
93
94 is_started
95
96 $started = $tk->is_started;
97
98 Returns true if the instance has been started, or false if it is
99 stopped.
100
101 get_flags
102
103 set_flags
104
105 $flags = $tk->get_flags;
106
107 $tk->set_flags( $newflags );
108
109 Accessor and mutator for the flags. One of the FLAG_UTF8 or FLAG_RAW
110 flags will be set, even if neither was present in the constructor, as
111 in this case the library will attempt to detect if the current locale
112 is UTF-8 aware or not.
113
114 get_canonflags
115
116 set_canonflags
117
118 $canonflags = $tk->get_canonflags;
119
120 $tk->set_canonflags( $newcanonflags );
121
122 Accessor and mutator for the canonicalisation flags.
123
124 get_waittime
125
126 set_waittime
127
128 $msec = $tk->get_waittime;
129
130 $tk->set_waittime( $msec );
131
132 Accessor and mutator for the maximum wait time in miliseconds. The
133 underlying libtermkey library will have specified a default value when
134 the object was constructed.
135
136 get_buffer_remaining
137
138 $bytes = $tk->get_buffer_remaining;
139
140 Accessor returning the number of bytes of buffer space remaining in the
141 buffer; the space in which push_bytes can write.
142
143 get_buffer_size
144
145 set_buffer_size
146
147 $bytes = $tk->get_buffer_size;
148
149 $tk->set_buffer_size( $size );
150
151 Accessor and mutator to for the total buffer size to store pending
152 bytes. If the underlying termkey_set_buffer_size(3) call fails, the
153 set_buffer_size method will throw an exception.
154
155 getkey
156
157 $res = $tk->getkey( $key );
158
159 Attempt to retrieve a single keypress event from the buffer, and put it
160 in $key. If successful, will return RES_KEY to indicate that the $key
161 structure now contains a new keypress event. If $key is an undefined
162 lvalue (such as a new scalar variable) it will be initialised to
163 contain a new key structure.
164
165 If nothing is in the buffer it will return RES_NONE. If the buffer
166 contains a partial keypress event which does not yet contain all the
167 bytes required, it will return RES_AGAIN (see above section about
168 multibyte events). If no events are ready and the input stream is now
169 closed, will return RES_EOF.
170
171 This method will not block, nor will it perform any IO on the
172 underlying file descriptor. For a normal blocking read, see waitkey().
173
174 getkey_force
175
176 $res = $tk->getkey_force( $key );
177
178 Similar to getkey(), but will not return RES_AGAIN if a partial match
179 was found. Instead, it will force an interpretation of the bytes, even
180 if this means interpreting the start of an <Esc>-prefixed multibyte
181 sequence as a literal Escape key followed by normal letters. If $key is
182 an undefined lvalue (such as a new scalar variable) it will be
183 initialised to contain a new key structure.
184
185 This method will not block, nor will it perform any IO on the
186 underlying file descriptor. For a normal blocking read, see waitkey().
187
188 waitkey
189
190 $res = $tk->waitkey( $key );
191
192 Attempt to retrieve a single keypress event from the buffer, or block
193 until one is available. If successful, will return RES_KEY to indicate
194 that the $key structure now contains a new keypress event. If an IO
195 error occurs it will return RES_ERROR, and if the input stream is now
196 closed it will return RES_EOF.
197
198 If $key is an undefined lvalue (such as a new scalar variable) it will
199 be initialised to contain a new key structure.
200
201 advisereadable
202
203 $res = $tk->advisereadable;
204
205 Inform the underlying library that new input may be available on the
206 underlying file descriptor and so it should call read() to obtain it.
207 Will return RES_AGAIN if it read at least one more byte, RES_NONE if no
208 more input was found, or RES_ERROR if an IO error occurs.
209
210 Normally this method would only be used in programs that want to use
211 Term::TermKey asynchronously; see the EXAMPLES section. This method
212 gracefully handles an EAGAIN error from the underlying read() syscall.
213
214 push_bytes
215
216 $len = $tk->push_bytes( $bytes );
217
218 Feed more bytes into the input buffer. This is primarily useful for
219 feeding input into filehandle-less instances, constructed by passing
220 undef or -1 as the filehandle to the constructor. After calling this
221 method, these bytes will be available to read as keypresses by the
222 getkey method.
223
224 get_keyname
225
226 $str = $tk->get_keyname( $sym );
227
228 Returns the name of a key sym, such as returned by
229 Term::TermKey::Key->sym().
230
231 keyname2sym
232
233 $sym = $tk->keyname2sym( $keyname );
234
235 Look up the sym for a named key. The result of this method call can be
236 compared directly against the value returned by
237 Term::TermKey::Key->sym(). Because this method has to perform a linear
238 search of key names, it is best called rarely, perhaps during program
239 initialisation, and the result stored for easier comparisons during
240 runtime.
241
242 interpret_unknown_csi
243
244 ( $cmd, @args ) = $tk->interpret_unknown_csi( $key );
245
246 If $key contains an unknown CSI event then its command and arguments
247 are returned in a list. $cmd will be a string of 1 to 3 characters
248 long, containing the initial and intermediate characters if present,
249 followed by the main command character. @args will contain the
250 numerical arguments, where missing arguments are replaced by -1. If
251 $key does not contain an unknown CSI event then an empty list is
252 returned.
253
254 Note that this method needs to be called immediately after getkey or
255 waitkey, or at least, before calling either of those methods again. The
256 actual CSI sequence is retained in the libtermkey buffer, and only
257 retrieved by this method call. Calling getkey or waitkey again may
258 overwrite that buffer.
259
260 format_key
261
262 $str = $tk->format_key( $key, $format );
263
264 Return a string representation of the keypress event in $key, following
265 the flags given. See the descriptions of the flags, below, for more
266 detail.
267
268 This may be useful for matching keypress events against keybindings
269 stored in a hash. See EXAMPLES section for more detail.
270
271 parse_key
272
273 $key = $tk->parse_key( $str, $format );
274
275 Return a keypress event by parsing the string representation in $str,
276 following the flags given. This method is an inverse of format_key.
277
278 This may be useful for parsing entries from a configuration file or
279 similar.
280
281 parse_key_at_pos
282
283 $key = $tk->parse_key_at_pos( $str, $format );
284
285 Return a keypress event by parsing the string representation in a
286 region of $str, following the flags given.
287
288 Where parse_key will start at the beginning of the string and requires
289 the entire input to be consumed, this method will start at the current
290 pos() position in $str (or at the beginning of the string if none is
291 yet set), and after a successful parse, will update it to the end of
292 the matched section. This position does not have to be at the end of
293 the string. $str must therefore be a real scalar variable, and not a
294 string literal.
295
296 This may be useful for incremental parsing of configuration or other
297 data, out of a larger string.
298
299 keycmp
300
301 $cmp = $tk->keycmp( $key1, $key2 );
302
303 Compares the two given keypress events, returning a number less than,
304 equal to, or greater than zero, depending on the ordering. Keys are
305 ordered first by type (unicode, keysym, function, mouse), then by value
306 within that type, then finally by modifier bits.
307
308 This may be useful in sort expressions:
309
310 my @sorted_keys = sort { $tk->keycmp( $a, $b ) } @keys;
311
312 KEY OBJECTS
313
314 The Term::TermKey::Key subclass is used to store a single keypress
315 event. Objects in this class cannot be changed by perl code. getkey(),
316 getkey_force() or waitkey() will overwrite the contents of the
317 structure with a new value.
318
319 Keys cannot be constructed, but getkey(), getkey_force() or waitkey()
320 will place a new key structure in the $key variable if it is undefined
321 when they are called. parse_key() and parse_key_at_pos() will return
322 new keys.
323
324 type
325
326 $key->type;
327
328 The type of event. One of TYPE_UNICODE, TYPE_FUNCTION, TYPE_KEYSYM,
329 TYPE_MOUSE, TYPE_POSITION, TYPE_MODEREPORT, TYPE_UNKNOWN_CSI.
330
331 type_is_...
332
333 $key->type_is_unicode;
334
335 $key->type_is_function;
336
337 $key->type_is_keysym;
338
339 $key->type_is_mouse;
340
341 $key->type_is_position;
342
343 $key->type_is_modereport;
344
345 $key->type_is_unknown_csi;
346
347 Shortcuts which return a boolean.
348
349 codepoint
350
351 $key->codepoint;
352
353 The Unicode codepoint number for TYPE_UNICODE, or 0 otherwise.
354
355 number
356
357 $key->number;
358
359 The function key number for TYPE_FUNCTION, or 0 otherwise.
360
361 sym
362
363 $key->sym;
364
365 The key symbol number for TYPE_KEYSYM, or 0 otherwise. This can be
366 passed to Term::TermKey->get_keyname(), or compared to a result earlier
367 obtained from Term::TermKey->keyname2sym().
368
369 modifiers
370
371 $key->modifiers;
372
373 The modifier bitmask. Can be compared against the KEYMOD_* constants.
374
375 modifier_...
376
377 $key->modifier_shift;
378
379 $key->modifier_alt;
380
381 $key->modifier_ctrl;
382
383 Shortcuts which return a boolean if the appropriate modifier is
384 present.
385
386 utf8
387
388 $key->utf8;
389
390 A string representation of the given Unicode codepoint. If the
391 underlying termkey library is in UTF-8 mode then this will be a UTF-8
392 string. If it is in raw mode, then this will be a single raw byte.
393
394 mouseev
395
396 button
397
398 $key->mouseev;
399
400 $key->button;
401
402 The details of a mouse event for TYPE_MOUSE, or undef for other types
403 of event.
404
405 line
406
407 col
408
409 $key->line;
410
411 $key->col;
412
413 The details of a mouse or position event, or undef for other types of
414 event.
415
416 termkey
417
418 $key->termkey;
419
420 Return the underlying Term::TermKey object this key was retrieved from.
421
422 format
423
424 $str = $key->format( $format );
425
426 Returns a string representation of the keypress event, identically to
427 calling format_key on the underlying Term::TermKey object.
428
429 EXPORTED CONSTANTS
430
431 The following constant names are all derived from the underlying
432 libtermkey library. For more detail see the documentation on the
433 library.
434
435 These constants are possible values of $key->type
436
437 TYPE_UNICODE
438
439 a Unicode codepoint
440
441 TYPE_FUNCTION
442
443 a numbered function key
444
445 TYPE_KEYSYM
446
447 a symbolic key
448
449 TYPE_MOUSE
450
451 a mouse movement or button press or release
452
453 TYPE_POSITION
454
455 a cursor position report
456
457 TYPE_MODEREPORT
458
459 an ANSI or DEC mode report
460
461 TYPE_UNKNOWN_CSI
462
463 an unrecognised CSI sequence
464
465 These constants are result values from getkey(), getkey_force(),
466 waitkey() or advisereadable()
467
468 RES_NONE
469
470 No key event is ready.
471
472 RES_KEY
473
474 A key event has been provided.
475
476 RES_EOF
477
478 No key events are ready and the terminal has been closed, so no more
479 will arrive.
480
481 RES_AGAIN
482
483 No key event is ready yet, but a partial one has been found. This is
484 only returned by getkey(). To obtain the partial result even if it
485 never completes, call getkey_force().
486
487 RES_ERROR
488
489 Returned by waitkey or advisereadable if an IO error occurs while
490 trying to read another key event.
491
492 These constants are key modifier masks for $key->modifiers
493
494 KEYMOD_SHIFT
495
496 KEYMOD_ALT
497
498 KEYMOD_CTRL
499
500 Should be obvious ;)
501
502 These constants are types of mouse event which may be returned by
503 $key->mouseev or interpret_mouse:
504
505 MOUSE_UNKNOWN
506
507 The type of mouse event was not recognised
508
509 MOUSE_PRESS
510
511 The event reports a mouse button being pressed
512
513 MOUSE_DRAG
514
515 The event reports the mouse being moved while a button is held down
516
517 MOUSE_RELEASE
518
519 The event reports the mouse buttons being released, or the mouse
520 moved without a button held.
521
522 These constants are flags for the constructor, Term::TermKey->new
523
524 FLAG_NOINTERPRET
525
526 Do not attempt to interpret C0 codes into keysyms (ie. Backspace,
527 Tab, Enter, Escape). Instead report them as plain Ctrl-letter events.
528
529 FLAG_CONVERTKP
530
531 Convert xterm's alternate keypad symbols into the plain ASCII codes
532 they would represent.
533
534 FLAG_RAW
535
536 Ignore locale settings; do not attempt to recombine UTF-8 sequences.
537 Instead report only raw values.
538
539 FLAG_UTF8
540
541 Ignore locale settings; force UTF-8 recombining on.
542
543 FLAG_NOTERMIOS
544
545 Even if the terminal file descriptor represents a TTY device, do not
546 call the tcsetattr() termios function on it to set in canonical input
547 mode.
548
549 FLAG_SPACESYMBOL
550
551 Sets the CANON_SPACESYMBOL canonicalisation flag. See below.
552
553 FLAG_CTRLC
554
555 Disable the SIGINT behaviour of the Ctrl-C key, allowing it to be
556 read as a modified Unicode keypress.
557
558 FLAG_EINTR
559
560 Disable retry on signal interrupt; instead report it as an error with
561 RES_ERROR and $! set to EINTR. Without this flag, IO operations will
562 be retried if interrupted.
563
564 These constants are canonicalisation flags for set_canonflags and
565 get_canonflags
566
567 CANON_SPACESYMBOL
568
569 With this flag set, the Space key will appear as a TYPE_KEYSYM key
570 event whose symname is "Space". Without this flag, it appears as a
571 normal TYPE_UNICODE character.
572
573 CANON_DELBS
574
575 With this flag set, the ASCII DEL byte is interpreted as the
576 "Backspace" keysym, rather than "DEL". This flag does not affect the
577 interpretation of ASCII BS, which is always represented as
578 "Backspace".
579
580 These constants are flags to format_key
581
582 FORMAT_LONGMOD
583
584 Print full modifier names e.g. Shift- instead of abbreviating to S-.
585
586 FORMAT_CARETCTRL
587
588 If the only modifier is Ctrl on a plain character, render it as ^X.
589
590 FORMAT_ALTISMETA
591
592 Use the name Meta or the letter M instead of Alt or A.
593
594 FORMAT_WRAPBRACKET
595
596 If the key event is a special key instead of unmodified Unicode, wrap
597 it in <brackets>.
598
599 FORMAT_MOUSE_POS
600
601 If the event is a mouse event, also include the cursor position;
602 rendered as @ ($col,$line)
603
604 FORMAT_VIM
605
606 Shortcut to FORMAT_ALTISMETA|FORMAT_WRAPBRACKET; which gives an
607 output close to the format the vim editor uses.
608
609 EXAMPLES
610
611 A simple print-until-Ctrl-C loop
612
613 This program just prints every keypress until the user presses Ctrl-C.
614
615 use Term::TermKey qw( FLAG_UTF8 RES_EOF FORMAT_VIM );
616
617 my $tk = Term::TermKey->new(\*STDIN);
618
619 # ensure perl and libtermkey agree on Unicode handling
620 binmode( STDOUT, ":encoding(UTF-8)" ) if $tk->get_flags & FLAG_UTF8;
621
622 while( ( my $ret = $tk->waitkey( my $key ) ) != RES_EOF ) {
623 print "Got key: ".$tk->format_key( $key, FORMAT_VIM )."\n";
624 }
625
626 Configuration of custom keypresses
627
628 Because format_key() yields a plain string representation of a keypress
629 it can be used as a hash key to look up a "handler" routine for the
630 key.
631
632 The following implements a simple line input program, though obviously
633 lacking many features in a true line editor like readline.
634
635 use Term::TermKey qw( FLAG_UTF8 RES_EOF FORMAT_LONGMOD );
636
637 my $tk = Term::TermKey->new(\*STDIN);
638
639 # ensure perl and libtermkey agree on Unicode handling
640 binmode( STDOUT, ":encoding(UTF-8)" ) if $tk->get_flags & FLAG_UTF8;
641
642 my $line = "";
643
644 $| = 1;
645
646 my %key_handlers = (
647 "Enter" => sub {
648 print "\nThe line is: $line\n";
649 $line = "";
650 },
651
652 "Backspace" => sub {
653 return unless length $line;
654 substr( $line, -1, 1 ) = "";
655 print "\cH \cH"; # erase it
656 },
657
658 # other handlers ...
659 );
660
661 while( ( my $ret = $tk->waitkey( my $key ) ) != RES_EOF ) {
662 my $handler = $key_handlers{ $tk->format_key( $key, FORMAT_LONGMOD ) };
663 if( $handler ) {
664 $handler->( $key );
665 }
666 elsif( $key->type_is_unicode and !$key->modifiers ) {
667 my $char = $key->utf8;
668
669 $line .= $char;
670 print $char;
671 }
672 }
673
674 Asynchronous operation
675
676 Because the getkey() method performs no IO itself, it can be combined
677 with the advisereadable() method in an asynchronous program.
678
679 use IO::Select;
680 use Term::TermKey qw(
681 FLAG_UTF8 RES_KEY RES_AGAIN RES_EOF FORMAT_VIM
682 );
683
684 my $select = IO::Select->new();
685
686 my $tk = Term::TermKey->new(\*STDIN);
687 $select->add(\*STDIN);
688
689 # ensure perl and libtermkey agree on Unicode handling
690 binmode( STDOUT, ":encoding(UTF-8)" ) if $tk->get_flags & FLAG_UTF8;
691
692 sub on_key
693 {
694 my ( $tk, $key ) = @_;
695
696 print "You pressed " . $tk->format_key( $key, FORMAT_VIM ) . "\n";
697 }
698
699 my $again = 0;
700
701 while(1) {
702 my $timeout = $again ? $tk->get_waittime/1000 : undef;
703 my @ready = $select->can_read($timeout);
704
705 if( !@ready ) {
706 my $ret;
707 while( ( $ret = $tk->getkey_force( my $key ) ) == RES_KEY ) {
708 on_key( $tk, $key );
709 }
710 }
711
712 while( my $fh = shift @ready ) {
713 if( $fh == \*STDIN ) {
714 $tk->advisereadable;
715 my $ret;
716 while( ( $ret = $tk->getkey( my $key ) ) == RES_KEY ) {
717 on_key( $tk, $key );
718 }
719
720 $again = ( $ret == RES_AGAIN );
721 exit if $ret == RES_EOF;
722 }
723 # Deal with other filehandles here
724 }
725 }
726
727 There may also be more appropriate modules on CPAN for particular event
728 frameworks; see the SEE ALSO section below.
729
730 SEE ALSO
731
732 * http://www.leonerd.org.uk/code/libtermkey/ - libtermkey home page
733
734 * Term::TermKey::Async - terminal key input using libtermkey with
735 IO::Async
736
737 * POE::Wheel::TermKey - terminal key input using libtermkey with POE
738
739 * AnyEvent::TermKey - terminal key input using libtermkey with
740 AnyEvent
741
742 AUTHOR
743
744 Paul Evans <[email protected]>
745