Enhancements to debugger, Term::ReadLine, Term::Cap
[p5sagit/p5-mst-13.2.git] / lib / Term / Cap.pm
1 package Term::Cap;
2 use Carp;
3
4 # Last updated: Thu Dec 14 20:02:42 CST 1995 by sanders@bsdi.com
5
6 # TODO:
7 # support Berkeley DB termcaps
8 # should probably be a .xs module
9 # force $FH into callers package?
10 # keep $FH in object at Tgetent time?
11
12 =head1 NAME
13
14 Term::Cap - Perl termcap interface
15
16 =head1 SYNOPSIS
17
18     require Term::Cap;
19     $terminal = Tgetent Term::Cap { TERM => undef, OSPEED => $ospeed };
20     $terminal->Trequire(qw/ce ku kd/);
21     $terminal->Tgoto('cm', $col, $row, $FH);
22     $terminal->Tputs('dl', $count, $FH);
23     $terminal->Tpad($string, $count, $FH);
24
25 =head1 DESCRIPTION
26
27 These are low-level functions to extract and use capabilities from
28 a terminal capability (termcap) database.
29
30 The B<Tgetent> function extracts the entry of the specified terminal
31 type I<TERM> (defaults to the environment variable I<TERM>) from the
32 database.
33
34 It will look in the environment for a I<TERMCAP> variable.  If
35 found, and the value does not begin with a slash, and the terminal
36 type name is the same as the environment string I<TERM>, the
37 I<TERMCAP> string is used instead of reading a termcap file.  If
38 it does begin with a slash, the string is used as a path name of
39 the termcap file to search.  If I<TERMCAP> does not begin with a
40 slash and name is different from I<TERM>, B<Tgetent> searches the
41 files F<$HOME/.termcap>, F</etc/termcap>, and F</usr/share/misc/termcap>,
42 in that order, unless the environment variable I<TERMPATH> exists,
43 in which case it specifies a list of file pathnames (separated by
44 spaces or colons) to be searched B<instead>.  Whenever multiple
45 files are searched and a tc field occurs in the requested entry,
46 the entry it names must be found in the same file or one of the
47 succeeding files.  If there is a C<:tc=...:> in the I<TERMCAP>
48 environment variable string it will continue the search in the
49 files as above.
50
51 I<OSPEED> is the terminal output bit rate (often mistakenly called
52 the baud rate).  I<OSPEED> can be specified as either a POSIX
53 termios/SYSV termio speeds (where 9600 equals 9600) or an old
54 BSD-style speeds (where 13 equals 9600).
55
56 B<Tgetent> returns a blessed object reference which the user can
57 then use to send the control strings to the terminal using B<Tputs>
58 and B<Tgoto>.  It calls C<croak> on failure.
59
60 B<Tgoto> decodes a cursor addressing string with the given parameters.
61
62 The output strings for B<Tputs> are cached for counts of 1 for performance.
63 B<Tgoto> and B<Tpad> do not cache.  C<$self-E<gt>{_xx}> is the raw termcap
64 data and C<$self-E<gt>{xx}> is the cached version.
65
66     print $terminal->Tpad($self->{_xx}, 1);
67
68 B<Tgoto>, B<Tputs>, and B<Tpad> return the string and will also
69 output the string to $FH if specified.
70
71 The extracted termcap entry is available in the object
72 as C<$self-E<gt>{TERMCAP}>.
73
74 =head1 EXAMPLES
75
76     # Get terminal output speed
77     require POSIX;
78     my $termios = new POSIX::Termios;
79     $termios->getattr;
80     my $ospeed = $termios->getospeed;
81
82     # Old-style ioctl code to get ospeed:
83     #     require 'ioctl.pl';
84     #     ioctl(TTY,$TIOCGETP,$sgtty);
85     #     ($ispeed,$ospeed) = unpack('cc',$sgtty);
86
87     # allocate and initialize a terminal structure
88     $terminal = Tgetent Term::Cap { TERM => undef, OSPEED => $ospeed };
89
90     # require certain capabilities to be available
91     $terminal->Trequire(qw/ce ku kd/);
92
93     # Output Routines, if $FH is undefined these just return the string
94
95     # Tgoto does the % expansion stuff with the given args
96     $terminal->Tgoto('cm', $col, $row, $FH);
97
98     # Tputs doesn't do any % expansion.
99     $terminal->Tputs('dl', $count = 1, $FH);
100
101 =cut
102
103 # Returns a list of termcap files to check.
104 sub termcap_path { ## private
105     my @termcap_path;
106     # $TERMCAP, if it's a filespec
107     push(@termcap_path, $ENV{TERMCAP}) if ((exists $ENV{TERMCAP}) &&
108                                            ($ENV{TERMCAP} =~ /^\//
109                                             or $^O eq 'os2' and
110                                             $ENV{TERMCAP} =~ /^[a-z]:\//i));
111     if ((exists $ENV{TERMPATH}) && ($ENV{TERMPATH})) {
112         # Add the users $TERMPATH
113         push(@termcap_path, split(/(:|\s+)/, $ENV{TERMPATH}))
114     }
115     else {
116         # Defaults
117         push(@termcap_path,
118             $ENV{'HOME'} . '/.termcap',
119             '/etc/termcap',
120             '/usr/share/misc/termcap',
121         );
122     }
123     # return the list of those termcaps that exist
124     grep(-f, @termcap_path);
125 }
126
127 sub Tgetent { ## public -- static method
128     my $class = shift;
129     my $self = bless shift, $class;
130     my($term,$cap,$search,$field,$max,$tmp_term,$TERMCAP);
131     local($termpat,$state,$first,$entry);       # used inside eval
132     local $_;
133
134     # Compute PADDING factor from OSPEED (to be used by Tpad)
135     if (! $self->{OSPEED}) {
136         carp "OSPEED was not set, defaulting to 9600";
137         $self->{OSPEED} = 9600;
138     }
139     if ($self->{OSPEED} < 16) {
140         # delays for old style speeds
141         my @pad = (0,200,133.3,90.9,74.3,66.7,50,33.3,16.7,8.3,5.5,4.1,2,1,.5,.2);
142         $self->{PADDING} = $pad[$self->{OSPEED}];
143     }
144     else {
145         $self->{PADDING} = 10000 / $self->{OSPEED};
146     }
147
148     $self->{TERM} = ($self->{TERM} || $ENV{TERM} || croak "TERM not set");
149     $term = $self->{TERM};      # $term is the term type we are looking for
150
151     # $tmp_term is always the next term (possibly :tc=...:) we are looking for
152     $tmp_term = $self->{TERM};
153     # protect any pattern metacharacters in $tmp_term 
154     $termpat = $tmp_term; $termpat =~ s/(\W)/\\$1/g;
155
156     my $foo = (exists $ENV{TERMCAP} ? $ENV{TERMCAP} : '');
157
158     # $entry is the extracted termcap entry
159     if (($foo !~ m:^/:) && ($foo =~ m/(^|\|)${termpat}[:|]/)) {
160         $entry = $foo;
161     }
162
163     my @termcap_path = termcap_path;
164     croak "Can't find a valid termcap file" unless @termcap_path || $entry;
165
166     $state = 1;                                 # 0 == finished
167                                                 # 1 == next file
168                                                 # 2 == search again
169
170     $first = 0;                                 # first entry (keeps term name)
171
172     $max = 32;                                  # max :tc=...:'s
173
174     if ($entry) {
175         # ok, we're starting with $TERMCAP
176         $first++;                               # we're the first entry
177         # do we need to continue?
178         if ($entry =~ s/:tc=([^:]+):/:/) {
179             $tmp_term = $1;
180             # protect any pattern metacharacters in $tmp_term 
181             $termpat = $tmp_term; $termpat =~ s/(\W)/\\$1/g;
182         }
183         else {
184             $state = 0;                         # we're already finished
185         }
186     }
187
188     # This is eval'ed inside the while loop for each file
189     $search = q{
190         while (<TERMCAP>) {
191             next if /^\\t/ || /^#/;
192             if ($_ =~ m/(^|\\|)${termpat}[:|]/o) {
193                 chomp;
194                 s/^[^:]*:// if $first++;
195                 $state = 0;
196                 while ($_ =~ s/\\\\$//) {
197                     defined(my $x = <TERMCAP>) or last;
198                     $_ .= $x; chomp;
199                 }
200                 last;
201             }
202         }
203         defined $entry or $entry = '';
204         $entry .= $_;
205     };
206
207     while ($state != 0) {
208         if ($state == 1) {
209             # get the next TERMCAP
210             $TERMCAP = shift @termcap_path
211                 || croak "failed termcap lookup on $tmp_term";
212         }
213         else {
214             # do the same file again
215             # prevent endless recursion
216             $max-- || croak "failed termcap loop at $tmp_term";
217             $state = 1;         # ok, maybe do a new file next time
218         }
219
220         open(TERMCAP,"< $TERMCAP\0") || croak "open $TERMCAP: $!";
221         eval $search;
222         die $@ if $@;
223         close TERMCAP;
224
225         # If :tc=...: found then search this file again
226         $entry =~ s/:tc=([^:]+):/:/ && ($tmp_term = $1, $state = 2);
227         # protect any pattern metacharacters in $tmp_term 
228         $termpat = $tmp_term; $termpat =~ s/(\W)/\\$1/g;
229     }
230
231     croak "Can't find $term" if $entry eq '';
232     $entry =~ s/:+\s*:+/:/g;                            # cleanup $entry
233     $entry =~ s/:+/:/g;                                 # cleanup $entry
234     $self->{TERMCAP} = $entry;                          # save it
235     # print STDERR "DEBUG: $entry = ", $entry, "\n";
236
237     # Precompile $entry into the object
238     $entry =~ s/^[^:]*://;
239     foreach $field (split(/:[\s:\\]*/,$entry)) {
240         if ($field =~ /^(\w\w)$/) {
241             $self->{'_' . $field} = 1 unless defined $self->{'_' . $1};
242             # print STDERR "DEBUG: flag $1\n";
243         }
244         elsif ($field =~ /^(\w\w)\@/) {
245             $self->{'_' . $1} = "";
246             # print STDERR "DEBUG: unset $1\n";
247         }
248         elsif ($field =~ /^(\w\w)#(.*)/) {
249             $self->{'_' . $1} = $2 unless defined $self->{'_' . $1};
250             # print STDERR "DEBUG: numeric $1 = $2\n";
251         }
252         elsif ($field =~ /^(\w\w)=(.*)/) {
253             # print STDERR "DEBUG: string $1 = $2\n";
254             next if defined $self->{'_' . ($cap = $1)};
255             $_ = $2;
256             s/\\E/\033/g;
257             s/\\(\d\d\d)/pack('c',oct($1) & 0177)/eg;
258             s/\\n/\n/g;
259             s/\\r/\r/g;
260             s/\\t/\t/g;
261             s/\\b/\b/g;
262             s/\\f/\f/g;
263             s/\\\^/\377/g;
264             s/\^\?/\177/g;
265             s/\^(.)/pack('c',ord($1) & 31)/eg;
266             s/\\(.)/$1/g;
267             s/\377/^/g;
268             $self->{'_' . $cap} = $_;
269         }
270         # else { carp "junk in $term ignored: $field"; }
271     }
272     $self->{'_pc'} = "\0" unless defined $self->{'_pc'};
273     $self->{'_bc'} = "\b" unless defined $self->{'_bc'};
274     $self;
275 }
276
277 # $terminal->Tpad($string, $cnt, $FH);
278 sub Tpad { ## public
279     my $self = shift;
280     my($string, $cnt, $FH) = @_;
281     my($decr, $ms);
282
283     if ($string =~ /(^[\d.]+)(\*?)(.*)$/) {
284         $ms = $1;
285         $ms *= $cnt if $2;
286         $string = $3;
287         $decr = $self->{PADDING};
288         if ($decr > .1) {
289             $ms += $decr / 2;
290             $string .= $self->{'_pc'} x ($ms / $decr);
291         }
292     }
293     print $FH $string if $FH;
294     $string;
295 }
296
297 # $terminal->Tputs($cap, $cnt, $FH);
298 sub Tputs { ## public
299     my $self = shift;
300     my($cap, $cnt, $FH) = @_;
301     my $string;
302
303     if ($cnt > 1) {
304         $string = Tpad($self, $self->{'_' . $cap}, $cnt);
305     } else {
306         # cache result because Tpad can be slow
307         $string = defined $self->{$cap} ? $self->{$cap} :
308             ($self->{$cap} = Tpad($self, $self->{'_' . $cap}, 1));
309     }
310     print $FH $string if $FH;
311     $string;
312 }
313
314 # %%   output `%'
315 # %d   output value as in printf %d
316 # %2   output value as in printf %2d
317 # %3   output value as in printf %3d
318 # %.   output value as in printf %c
319 # %+x  add x to value, then do %.
320 #
321 # %>xy if value > x then add y, no output
322 # %r   reverse order of two parameters, no output
323 # %i   increment by one, no output
324 # %B   BCD (16*(value/10)) + (value%10), no output
325 #
326 # %n   exclusive-or all parameters with 0140 (Datamedia 2500)
327 # %D   Reverse coding (value - 2*(value%16)), no output (Delta Data)
328 #
329 # $terminal->Tgoto($cap, $col, $row, $FH);
330 sub Tgoto { ## public
331     my $self = shift;
332     my($cap, $code, $tmp, $FH) = @_;
333     my $string = $self->{'_' . $cap};
334     my $result = '';
335     my $after = '';
336     my $online = 0;
337     my @tmp = ($tmp,$code);
338     my $cnt = $code;
339
340     while ($string =~ /^([^%]*)%(.)(.*)/) {
341         $result .= $1;
342         $code = $2;
343         $string = $3;
344         if ($code eq 'd') {
345             $result .= sprintf("%d",shift(@tmp));
346         }
347         elsif ($code eq '.') {
348             $tmp = shift(@tmp);
349             if ($tmp == 0 || $tmp == 4 || $tmp == 10) {
350                 if ($online) {
351                     ++$tmp, $after .= $self->{'_up'} if $self->{'_up'};
352                 }
353                 else {
354                     ++$tmp, $after .= $self->{'_bc'};
355                 }
356             }
357             $result .= sprintf("%c",$tmp);
358             $online = !$online;
359         }
360         elsif ($code eq '+') {
361             $result .= sprintf("%c",shift(@tmp)+ord($string));
362             $string = substr($string,1,99);
363             $online = !$online;
364         }
365         elsif ($code eq 'r') {
366             ($code,$tmp) = @tmp;
367             @tmp = ($tmp,$code);
368             $online = !$online;
369         }
370         elsif ($code eq '>') {
371             ($code,$tmp,$string) = unpack("CCa99",$string);
372             if ($tmp[$[] > $code) {
373                 $tmp[$[] += $tmp;
374             }
375         }
376         elsif ($code eq '2') {
377             $result .= sprintf("%02d",shift(@tmp));
378             $online = !$online;
379         }
380         elsif ($code eq '3') {
381             $result .= sprintf("%03d",shift(@tmp));
382             $online = !$online;
383         }
384         elsif ($code eq 'i') {
385             ($code,$tmp) = @tmp;
386             @tmp = ($code+1,$tmp+1);
387         }
388         else {
389             return "OOPS";
390         }
391     }
392     $string = Tpad($self, $result . $string . $after, $cnt);
393     print $FH $string if $FH;
394     $string;
395 }
396
397 # $terminal->Trequire(qw/ce ku kd/);
398 sub Trequire { ## public
399     my $self = shift;
400     my($cap,@undefined);
401     foreach $cap (@_) {
402         push(@undefined, $cap)
403             unless defined $self->{'_' . $cap} && $self->{'_' . $cap};
404     }
405     croak "Terminal does not support: (@undefined)" if @undefined;
406 }
407
408 1;
409