Re: New harness is failing things
[p5sagit/p5-mst-13.2.git] / lib / Term / ReadLine.pm
1 =head1 NAME
2
3 Term::ReadLine - Perl interface to various C<readline> packages. If
4 no real package is found, substitutes stubs instead of basic functions.
5
6 =head1 SYNOPSIS
7
8   use Term::ReadLine;
9   $term = new Term::ReadLine 'Simple Perl calc';
10   $prompt = "Enter your arithmetic expression: ";
11   $OUT = $term->OUT || STDOUT;
12   while ( defined ($_ = $term->readline($prompt)) ) {
13     $res = eval($_), "\n";
14     warn $@ if $@;
15     print $OUT $res, "\n" unless $@;
16     $term->addhistory($_) if /\S/;
17   }
18
19 =head1 DESCRIPTION
20
21 This package is just a front end to some other packages. At the moment
22 this description is written, the only such package is Term-ReadLine,
23 available on CPAN near you. The real target of this stub package is to
24 set up a common interface to whatever Readline emerges with time.
25
26 =head1 Minimal set of supported functions
27
28 All the supported functions should be called as methods, i.e., either as 
29
30   $term = new Term::ReadLine 'name';
31
32 or as 
33
34   $term->addhistory('row');
35
36 where $term is a return value of Term::ReadLine-E<gt>Init.
37
38 =over 12
39
40 =item C<ReadLine>
41
42 returns the actual package that executes the commands. Among possible
43 values are C<Term::ReadLine::Gnu>, C<Term::ReadLine::Perl>,
44 C<Term::ReadLine::Stub Exporter>.
45
46 =item C<new>
47
48 returns the handle for subsequent calls to following
49 functions. Argument is the name of the application. Optionally can be
50 followed by two arguments for C<IN> and C<OUT> filehandles. These
51 arguments should be globs.
52
53 =item C<readline>
54
55 gets an input line, I<possibly> with actual C<readline>
56 support. Trailing newline is removed. Returns C<undef> on C<EOF>.
57
58 =item C<addhistory>
59
60 adds the line to the history of input, from where it can be used if
61 the actual C<readline> is present.
62
63 =item C<IN>, $C<OUT>
64
65 return the filehandles for input and output or C<undef> if C<readline>
66 input and output cannot be used for Perl.
67
68 =item C<MinLine>
69
70 If argument is specified, it is an advice on minimal size of line to
71 be included into history.  C<undef> means do not include anything into
72 history. Returns the old value.
73
74 =item C<findConsole>
75
76 returns an array with two strings that give most appropriate names for
77 files for input and output using conventions C<"E<lt>$in">, C<"E<gt>out">.
78
79 =item Attribs
80
81 returns a reference to a hash which describes internal configuration
82 of the package. Names of keys in this hash conform to standard
83 conventions with the leading C<rl_> stripped.
84
85 =item C<Features>
86
87 Returns a reference to a hash with keys being features present in
88 current implementation. Several optional features are used in the
89 minimal interface: C<appname> should be present if the first argument
90 to C<new> is recognized, and C<minline> should be present if
91 C<MinLine> method is not dummy.  C<autohistory> should be present if
92 lines are put into history automatically (maybe subject to
93 C<MinLine>), and C<addhistory> if C<addhistory> method is not dummy.
94
95 If C<Features> method reports a feature C<attribs> as present, the
96 method C<Attribs> is not dummy.
97
98 =back
99
100 =head1 Additional supported functions
101
102 Actually C<Term::ReadLine> can use some other package, that will
103 support reacher set of commands.
104
105 All these commands are callable via method interface and have names
106 which conform to standard conventions with the leading C<rl_> stripped.
107
108 The stub package included with the perl distribution allows some
109 additional methods: 
110
111 =over 12
112
113 =item C<tkRunning>
114
115 makes Tk event loop run when waiting for user input (i.e., during
116 C<readline> method).
117
118 =item C<ornaments>
119
120 makes the command line stand out by using termcap data.  The argument
121 to C<ornaments> should be 0, 1, or a string of a form
122 C<"aa,bb,cc,dd">.  Four components of this string should be names of
123 I<terminal capacities>, first two will be issued to make the prompt
124 standout, last two to make the input line standout.
125
126 =item C<newTTY>
127
128 takes two arguments which are input filehandle and output filehandle.
129 Switches to use these filehandles.
130
131 =back
132
133 One can check whether the currently loaded ReadLine package supports
134 these methods by checking for corresponding C<Features>.
135
136 =head1 EXPORTS
137
138 None
139
140 =head1 ENVIRONMENT
141
142 The environment variable C<PERL_RL> governs which ReadLine clone is
143 loaded. If the value is false, a dummy interface is used. If the value
144 is true, it should be tail of the name of the package to use, such as
145 C<Perl> or C<Gnu>.  
146
147 As a special case, if the value of this variable is space-separated,
148 the tail might be used to disable the ornaments by setting the tail to
149 be C<o=0> or C<ornaments=0>.  The head should be as described above, say
150
151 If the variable is not set, or if the head of space-separated list is
152 empty, the best available package is loaded.
153
154   export "PERL_RL=Perl o=0"     # Use Perl ReadLine without ornaments
155   export "PERL_RL= o=0"         # Use best available ReadLine without ornaments
156
157 (Note that processing of C<PERL_RL> for ornaments is in the discretion of the 
158 particular used C<Term::ReadLine::*> package).
159
160 =cut
161
162 package Term::ReadLine::Stub;
163 @ISA = qw'Term::ReadLine::Tk Term::ReadLine::TermCap';
164
165 $DB::emacs = $DB::emacs;        # To peacify -w
166 *rl_term_set = \@Term::ReadLine::TermCap::rl_term_set;
167
168 sub ReadLine {'Term::ReadLine::Stub'}
169 sub readline {
170   my $self = shift;
171   my ($in,$out,$str) = @$self;
172   my $prompt = shift;
173   print $out $rl_term_set[0], $prompt, $rl_term_set[1], $rl_term_set[2]; 
174   $self->register_Tk 
175      if not $Term::ReadLine::registered and $Term::ReadLine::toloop
176         and defined &Tk::DoOneEvent;
177   #$str = scalar <$in>;
178   $str = $self->get_line;
179   $str =~ s/^\s*\Q$prompt\E// if ($^O eq 'MacOS');
180   print $out $rl_term_set[3]; 
181   # bug in 5.000: chomping empty string creats length -1:
182   chomp $str if defined $str;
183   $str;
184 }
185 sub addhistory {}
186
187 sub findConsole {
188     my $console;
189
190     if ($^O eq 'MacOS') {
191         $console = "Dev:Console";
192     } elsif (-e "/dev/tty") {
193         $console = "/dev/tty";
194     } elsif (-e "con" or $^O eq 'MSWin32') {
195         $console = "con";
196     } else {
197         $console = "sys\$command";
198     }
199
200     if (($^O eq 'amigaos') || ($^O eq 'beos') || ($^O eq 'epoc')) {
201         $console = undef;
202     }
203     elsif ($^O eq 'os2') {
204       if ($DB::emacs) {
205         $console = undef;
206       } else {
207         $console = "/dev/con";
208       }
209     }
210
211     $consoleOUT = $console;
212     $console = "&STDIN" unless defined $console;
213     if (!defined $consoleOUT) {
214       $consoleOUT = defined fileno(STDERR) ? "&STDERR" : "&STDOUT";
215     }
216     ($console,$consoleOUT);
217 }
218
219 sub new {
220   die "method new called with wrong number of arguments" 
221     unless @_==2 or @_==4;
222   #local (*FIN, *FOUT);
223   my ($FIN, $FOUT, $ret);
224   if (@_==2) {
225     ($console, $consoleOUT) = findConsole;
226
227     open(FIN, "<$console"); 
228     open(FOUT,">$consoleOUT");
229     #OUT->autoflush(1);         # Conflicts with debugger?
230     $sel = select(FOUT);
231     $| = 1;                             # for DB::OUT
232     select($sel);
233     $ret = bless [\*FIN, \*FOUT];
234   } else {                      # Filehandles supplied
235     $FIN = $_[2]; $FOUT = $_[3];
236     #OUT->autoflush(1);         # Conflicts with debugger?
237     $sel = select($FOUT);
238     $| = 1;                             # for DB::OUT
239     select($sel);
240     $ret = bless [$FIN, $FOUT];
241   }
242   if ($ret->Features->{ornaments} 
243       and not ($ENV{PERL_RL} and $ENV{PERL_RL} =~ /\bo\w*=0/)) {
244     local $Term::ReadLine::termcap_nowarn = 1;
245     $ret->ornaments(1);
246   }
247   return $ret;
248 }
249
250 sub newTTY {
251   my ($self, $in, $out) = @_;
252   $self->[0] = $in;
253   $self->[1] = $out;
254   my $sel = select($out);
255   $| = 1;                               # for DB::OUT
256   select($sel);
257 }
258
259 sub IN { shift->[0] }
260 sub OUT { shift->[1] }
261 sub MinLine { undef }
262 sub Attribs { {} }
263
264 my %features = (tkRunning => 1, ornaments => 1, 'newTTY' => 1);
265 sub Features { \%features }
266
267 package Term::ReadLine;         # So late to allow the above code be defined?
268
269 my ($which) = exists $ENV{PERL_RL} ? split /\s+/, $ENV{PERL_RL} : undef;
270 if ($which) {
271   if ($which =~ /\bgnu\b/i){
272     eval "use Term::ReadLine::Gnu;";
273   } elsif ($which =~ /\bperl\b/i) {
274     eval "use Term::ReadLine::Perl;";
275   } else {
276     eval "use Term::ReadLine::$which;";
277   }
278 } elsif (defined $which and $which ne '') {     # Defined but false
279   # Do nothing fancy
280 } else {
281   eval "use Term::ReadLine::Gnu; 1" or eval "use Term::ReadLine::Perl; 1";
282 }
283
284 #require FileHandle;
285
286 # To make possible switch off RL in debugger: (Not needed, work done
287 # in debugger).
288
289 if (defined &Term::ReadLine::Gnu::readline) {
290   @ISA = qw(Term::ReadLine::Gnu Term::ReadLine::Stub);
291 } elsif (defined &Term::ReadLine::Perl::readline) {
292   @ISA = qw(Term::ReadLine::Perl Term::ReadLine::Stub);
293 } else {
294   @ISA = qw(Term::ReadLine::Stub);
295 }
296
297 package Term::ReadLine::TermCap;
298
299 # Prompt-start, prompt-end, command-line-start, command-line-end
300 #     -- zero-width beautifies to emit around prompt and the command line.
301 @rl_term_set = ("","","","");
302 # string encoded:
303 $rl_term_set = ',,,';
304
305 sub LoadTermCap {
306   return if defined $terminal;
307   
308   require Term::Cap;
309   $terminal = Tgetent Term::Cap ({OSPEED => 9600}); # Avoid warning.
310 }
311
312 sub ornaments {
313   shift;
314   return $rl_term_set unless @_;
315   $rl_term_set = shift;
316   $rl_term_set ||= ',,,';
317   $rl_term_set = 'us,ue,md,me' if $rl_term_set eq '1';
318   my @ts = split /,/, $rl_term_set, 4;
319   eval { LoadTermCap };
320   unless (defined $terminal) {
321     warn("Cannot find termcap: $@\n") unless $Term::ReadLine::termcap_nowarn;
322     $rl_term_set = ',,,';
323     return;
324   }
325   @rl_term_set = map {$_ ? $terminal->Tputs($_,1) || '' : ''} @ts;
326   return $rl_term_set;
327 }
328
329
330 package Term::ReadLine::Tk;
331
332 $count_handle = $count_DoOne = $count_loop = 0;
333
334 sub handle {$giveup = 1; $count_handle++}
335
336 sub Tk_loop {
337   # Tk->tkwait('variable',\$giveup);    # needs Widget
338   $count_DoOne++, Tk::DoOneEvent(0) until $giveup;
339   $count_loop++;
340   $giveup = 0;
341 }
342
343 sub register_Tk {
344   my $self = shift;
345   $Term::ReadLine::registered++ 
346     or Tk->fileevent($self->IN,'readable',\&handle);
347 }
348
349 sub tkRunning {
350   $Term::ReadLine::toloop = $_[1] if @_ > 1;
351   $Term::ReadLine::toloop;
352 }
353
354 sub get_c {
355   my $self = shift;
356   $self->Tk_loop if $Term::ReadLine::toloop && defined &Tk::DoOneEvent;
357   return getc $self->IN;
358 }
359
360 sub get_line {
361   my $self = shift;
362   $self->Tk_loop if $Term::ReadLine::toloop && defined &Tk::DoOneEvent;
363   my $in = $self->IN;
364   local ($/) = "\n";
365   return scalar <$in>;
366 }
367
368 1;
369