<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">=head1 NAME

Term::ReadLine - Perl interface to various C&lt;readline&gt; packages.
If no real package is found, substitutes stubs instead of basic functions.

=head1 SYNOPSIS

  use Term::ReadLine;
  my $term = Term::ReadLine-&gt;new('Simple Perl calc');
  my $prompt = "Enter your arithmetic expression: ";
  my $OUT = $term-&gt;OUT || \*STDOUT;
  while ( defined ($_ = $term-&gt;readline($prompt)) ) {
    my $res = eval($_);
    warn $@ if $@;
    print $OUT $res, "\n" unless $@;
    $term-&gt;addhistory($_) if /\S/;
  }

=head1 DESCRIPTION

This package is just a front end to some other packages. It's a stub to
set up a common interface to the various ReadLine implementations found on
CPAN (under the C&lt;Term::ReadLine::*&gt; namespace).

=head1 Minimal set of supported functions

All the supported functions should be called as methods, i.e., either as 

  $term = Term::ReadLine-&gt;new('name');

or as 

  $term-&gt;addhistory('row');

where $term is a return value of Term::ReadLine-E&lt;gt&gt;new().

=over 12

=item C&lt;ReadLine&gt;

returns the actual package that executes the commands. Among possible
values are C&lt;Term::ReadLine::Gnu&gt;, C&lt;Term::ReadLine::Perl&gt;,
C&lt;Term::ReadLine::Stub&gt;.

=item C&lt;new&gt;

returns the handle for subsequent calls to following
functions. Argument is the name of the application. Optionally can be
followed by two arguments for C&lt;IN&gt; and C&lt;OUT&gt; filehandles. These
arguments should be globs.

=item C&lt;readline&gt;

gets an input line, I&lt;possibly&gt; with actual C&lt;readline&gt;
support. Trailing newline is removed. Returns C&lt;undef&gt; on C&lt;EOF&gt;.

=item C&lt;addhistory&gt;

adds the line to the history of input, from where it can be used if
the actual C&lt;readline&gt; is present.

=item C&lt;IN&gt;, C&lt;OUT&gt;

return the filehandles for input and output or C&lt;undef&gt; if C&lt;readline&gt;
input and output cannot be used for Perl.

=item C&lt;MinLine&gt;

If argument is specified, it is an advice on minimal size of line to
be included into history.  C&lt;undef&gt; means do not include anything into
history. Returns the old value.

=item C&lt;findConsole&gt;

returns an array with two strings that give most appropriate names for
files for input and output using conventions C&lt;"E&lt;lt&gt;$in"&gt;, C&lt;"E&lt;gt&gt;out"&gt;.

The strings returned may not be useful for 3-argument open().

=item Attribs

returns a reference to a hash which describes internal configuration
of the package. Names of keys in this hash conform to standard
conventions with the leading C&lt;rl_&gt; stripped.

=item C&lt;Features&gt;

Returns a reference to a hash with keys being features present in
current implementation. Several optional features are used in the
minimal interface: C&lt;appname&gt; should be present if the first argument
to C&lt;new&gt; is recognized, and C&lt;minline&gt; should be present if
C&lt;MinLine&gt; method is not dummy.  C&lt;autohistory&gt; should be present if
lines are put into history automatically (maybe subject to
C&lt;MinLine&gt;), and C&lt;addhistory&gt; if C&lt;addhistory&gt; method is not dummy.

If C&lt;Features&gt; method reports a feature C&lt;attribs&gt; as present, the
method C&lt;Attribs&gt; is not dummy.

=back

=head1 Additional supported functions

Actually C&lt;Term::ReadLine&gt; can use some other package, that will
support a richer set of commands.

All these commands are callable via method interface and have names
which conform to standard conventions with the leading C&lt;rl_&gt; stripped.

The stub package included with the perl distribution allows some
additional methods: 

=over 12

=item C&lt;tkRunning&gt;

makes Tk event loop run when waiting for user input (i.e., during
C&lt;readline&gt; method).

=item C&lt;event_loop&gt;

Registers call-backs to wait for user input (i.e., during C&lt;readline&gt;
method).  This supersedes tkRunning.

The first call-back registered is the call back for waiting.  It is
expected that the callback will call the current event loop until
there is something waiting to get on the input filehandle.  The parameter
passed in is the return value of the second call back.

The second call-back registered is the call back for registration.  The
input filehandle (often STDIN, but not necessarily) will be passed in.

For example, with AnyEvent:

  $term-&gt;event_loop(sub {
    my $data = shift;
    $data-&gt;[1] = AE::cv();
    $data-&gt;[1]-&gt;recv();
  }, sub {
    my $fh = shift;
    my $data = [];
    $data-&gt;[0] = AE::io($fh, 0, sub { $data-&gt;[1]-&gt;send() });
    $data;
  });

The second call-back is optional if the call back is registered prior to
the call to $term-E&lt;gt&gt;readline.

Deregistration is done in this case by calling event_loop with C&lt;undef&gt;
as its parameter:

    $term-&gt;event_loop(undef);

This will cause the data array ref to be removed, allowing normal garbage
collection to clean it up.  With AnyEvent, that will cause $data-&gt;[0] to
be cleaned up, and AnyEvent will automatically cancel the watcher at that
time.  If another loop requires more than that to clean up a file watcher,
that will be up to the caller to handle.

=item C&lt;ornaments&gt;

makes the command line stand out by using termcap data.  The argument
to C&lt;ornaments&gt; should be 0, 1, or a string of a form
C&lt;"aa,bb,cc,dd"&gt;.  Four components of this string should be names of
I&lt;terminal capacities&gt;, first two will be issued to make the prompt
standout, last two to make the input line standout.

=item C&lt;newTTY&gt;

takes two arguments which are input filehandle and output filehandle.
Switches to use these filehandles.

=back

One can check whether the currently loaded ReadLine package supports
these methods by checking for corresponding C&lt;Features&gt;.

=head1 EXPORTS

None

=head1 ENVIRONMENT

The environment variable C&lt;PERL_RL&gt; governs which ReadLine clone is
loaded. If the value is false, a dummy interface is used. If the value
is true, it should be tail of the name of the package to use, such as
C&lt;Perl&gt; or C&lt;Gnu&gt;.  

As a special case, if the value of this variable is space-separated,
the tail might be used to disable the ornaments by setting the tail to
be C&lt;o=0&gt; or C&lt;ornaments=0&gt;.  The head should be as described above, say

If the variable is not set, or if the head of space-separated list is
empty, the best available package is loaded.

  export "PERL_RL=Perl o=0" # Use Perl ReadLine sans ornaments
  export "PERL_RL= o=0"     # Use best available ReadLine sans ornaments

(Note that processing of C&lt;PERL_RL&gt; for ornaments is in the discretion of the 
particular used C&lt;Term::ReadLine::*&gt; package).

=cut

use strict;

package Term::ReadLine::Stub;
our @ISA = qw'Term::ReadLine::Tk Term::ReadLine::TermCap';

$DB::emacs = $DB::emacs;	# To pacify -w
our @rl_term_set;
*rl_term_set = \@Term::ReadLine::TermCap::rl_term_set;

sub PERL_UNICODE_STDIN () { 0x0001 }

sub ReadLine {'Term::ReadLine::Stub'}
sub readline {
  my $self = shift;
  my ($in,$out,$str) = @$self;
  my $prompt = shift;
  print $out $rl_term_set[0], $prompt, $rl_term_set[1], $rl_term_set[2]; 
  $self-&gt;register_Tk 
     if not $Term::ReadLine::registered and $Term::ReadLine::toloop;
  #$str = scalar &lt;$in&gt;;
  $str = $self-&gt;get_line;
  utf8::upgrade($str)
      if (${^UNICODE} &amp; PERL_UNICODE_STDIN || defined ${^ENCODING}) &amp;&amp;
         utf8::valid($str);
  print $out $rl_term_set[3]; 
  # bug in 5.000: chomping empty string creates length -1:
  chomp $str if defined $str;
  $str;
}
sub addhistory {}

# used for testing purpose
sub devtty { return '/dev/tty' }

sub findConsole {
    my $console;
    my $consoleOUT;

    my $devtty = devtty();

    if ($^O ne 'MSWin32' and -e $devtty) {
	$console = $devtty;
    } elsif ($^O eq 'MSWin32' or $^O eq 'msys' or -e "con") {
       $console = 'CONIN$';
       $consoleOUT = 'CONOUT$';
    } elsif ($^O eq 'VMS') {
	$console = "sys\$command";
    } elsif ($^O eq 'os2' &amp;&amp; !$DB::emacs) {
	$console = "/dev/con";
    } else {
	$console = undef;
    }

    $consoleOUT = $console unless defined $consoleOUT;
    $console = "&amp;STDIN" unless defined $console;
    if ($console eq $devtty &amp;&amp; !open(my $fh, "&lt;", $console)) {
      $console = "&amp;STDIN";
      undef($consoleOUT);
    }
    if (!defined $consoleOUT) {
      $consoleOUT = defined fileno(STDERR) &amp;&amp; $^O ne 'MSWin32' ? "&amp;STDERR" : "&amp;STDOUT";
    }
    ($console,$consoleOUT);
}

sub new {
  die "method new called with wrong number of arguments" 
    unless @_==2 or @_==4;
  #local (*FIN, *FOUT);
  my ($FIN, $FOUT, $ret);
  if (@_==2) {
    my($console, $consoleOUT) = $_[0]-&gt;findConsole;

    # the Windows CONIN$ needs GENERIC_WRITE mode to allow
    # a SetConsoleMode() if we end up using Term::ReadKey
    open FIN, (( $^O eq 'MSWin32' &amp;&amp; $console eq 'CONIN$' ) ? '+&lt;' : '&lt;' ), $console;
    # RT #132008:  Still need 2-arg open here
    open FOUT,"&gt;$consoleOUT";

    #OUT-&gt;autoflush(1);		# Conflicts with debugger?
    my $sel = select(FOUT);
    $| = 1;				# for DB::OUT
    select($sel);
    $ret = bless [\*FIN, \*FOUT];
  } else {			# Filehandles supplied
    $FIN = $_[2]; $FOUT = $_[3];
    #OUT-&gt;autoflush(1);		# Conflicts with debugger?
    my $sel = select($FOUT);
    $| = 1;				# for DB::OUT
    select($sel);
    $ret = bless [$FIN, $FOUT];
  }
  if ($ret-&gt;Features-&gt;{ornaments} 
      and not ($ENV{PERL_RL} and $ENV{PERL_RL} =~ /\bo\w*=0/)) {
    local $Term::ReadLine::termcap_nowarn = 1;
    $ret-&gt;ornaments(1);
  }
  return $ret;
}

sub newTTY {
  my ($self, $in, $out) = @_;
  $self-&gt;[0] = $in;
  $self-&gt;[1] = $out;
  my $sel = select($out);
  $| = 1;				# for DB::OUT
  select($sel);
}

sub IN { shift-&gt;[0] }
sub OUT { shift-&gt;[1] }
sub MinLine { undef }
sub Attribs { {} }

my %features = (tkRunning =&gt; 1, ornaments =&gt; 1, 'newTTY' =&gt; 1);
sub Features { \%features }

#sub get_line {
#  my $self = shift;
#  my $in = $self-&gt;IN;
#  local ($/) = "\n";
#  return scalar &lt;$in&gt;;
#}

package Term::ReadLine;		# So late to allow the above code be defined?

our $VERSION = '1.17';

my ($which) = exists $ENV{PERL_RL} ? split /\s+/, $ENV{PERL_RL} : undef;
if ($which) {
  if ($which =~ /\bgnu\b/i){
    eval "use Term::ReadLine::Gnu;";
  } elsif ($which =~ /\bperl\b/i) {
    eval "use Term::ReadLine::Perl;";
  } elsif ($which =~ /^(Stub|TermCap|Tk)$/) {
    # it is already in memory to avoid false exception as seen in:
    # PERL_RL=Stub perl -e'$SIG{__DIE__} = sub { print @_ }; require Term::ReadLine'
  } else {
    eval "use Term::ReadLine::$which;";
  }
} elsif (defined $which and $which ne '') {	# Defined but false
  # Do nothing fancy
} else {
  eval "use Term::ReadLine::Gnu; 1" or eval "use Term::ReadLine::EditLine; 1" or eval "use Term::ReadLine::Perl; 1";
}

#require FileHandle;

# To make possible switch off RL in debugger: (Not needed, work done
# in debugger).
our @ISA;
if (defined &amp;Term::ReadLine::Gnu::readline) {
  @ISA = qw(Term::ReadLine::Gnu Term::ReadLine::Stub);
} elsif (defined &amp;Term::ReadLine::EditLine::readline) {
  @ISA = qw(Term::ReadLine::EditLine Term::ReadLine::Stub);
} elsif (defined &amp;Term::ReadLine::Perl::readline) {
  @ISA = qw(Term::ReadLine::Perl Term::ReadLine::Stub);
} elsif (defined $which &amp;&amp; defined &amp;{"Term::ReadLine::$which\::readline"}) {
  @ISA = "Term::ReadLine::$which";
} else {
  @ISA = qw(Term::ReadLine::Stub);
}

package Term::ReadLine::TermCap;

# Prompt-start, prompt-end, command-line-start, command-line-end
#     -- zero-width beautifies to emit around prompt and the command line.
our @rl_term_set = ("","","","");
# string encoded:
our $rl_term_set = ',,,';

our $terminal;
sub LoadTermCap {
  return if defined $terminal;
  
  require Term::Cap;
  $terminal = Tgetent Term::Cap ({OSPEED =&gt; 9600}); # Avoid warning.
}

sub ornaments {
  shift;
  return $rl_term_set unless @_;
  $rl_term_set = shift;
  $rl_term_set ||= ',,,';
  $rl_term_set = 'us,ue,md,me' if $rl_term_set eq '1';
  my @ts = split /,/, $rl_term_set, 4;
  eval { LoadTermCap };
  unless (defined $terminal) {
    warn("Cannot find termcap: $@\n") unless $Term::ReadLine::termcap_nowarn;
    $rl_term_set = ',,,';
    return;
  }
  @rl_term_set = map {$_ ? $terminal-&gt;Tputs($_,1) || '' : ''} @ts;
  return $rl_term_set;
}


package Term::ReadLine::Tk;

# This package inserts a Tk-&gt;fileevent() before the diamond operator.
# The Tk watcher dispatches Tk events until the filehandle returned by
# the$term-&gt;IN() accessor becomes ready for reading.  It's assumed
# that the diamond operator will return a line of input immediately at
# that point.

my ($giveup);

# maybe in the future the Tk-specific aspects will be removed.
sub Tk_loop{
    if (ref $Term::ReadLine::toloop)
    {
        $Term::ReadLine::toloop-&gt;[0]-&gt;($Term::ReadLine::toloop-&gt;[2]);
    }
    else
    {
        Tk::DoOneEvent(0) until $giveup;
        $giveup = 0;
    }
};

sub register_Tk {
    my $self = shift;
    unless ($Term::ReadLine::registered++)
    {
        if (ref $Term::ReadLine::toloop)
        {
            $Term::ReadLine::toloop-&gt;[2] = $Term::ReadLine::toloop-&gt;[1]-&gt;($self-&gt;IN) if $Term::ReadLine::toloop-&gt;[1];
        }
        else
        {
            Tk-&gt;fileevent($self-&gt;IN,'readable',sub { $giveup = 1});
        }
    }
};

sub tkRunning {
  $Term::ReadLine::toloop = $_[1] if @_ &gt; 1;
  $Term::ReadLine::toloop;
}

sub event_loop {
    shift;

    # T::RL::Gnu and T::RL::Perl check that this exists, if not,
    # it doesn't call the loop.  Those modules will need to be
    # fixed before this can be removed.
    if (not defined &amp;Tk::DoOneEvent)
    {
        *Tk::DoOneEvent = sub {
            die "what?"; # this shouldn't be called.
        }
    }

    # store the callback in toloop, again so that other modules will
    # recognise it and call us for the loop.
    $Term::ReadLine::toloop = [ @_ ] if @_ &gt; 0; # 0 because we shifted off $self.
    $Term::ReadLine::toloop;
}

sub PERL_UNICODE_STDIN () { 0x0001 }

sub get_line {
  my $self = shift;
  my ($in,$out,$str) = @$self;

  if ($Term::ReadLine::toloop) {
    $self-&gt;register_Tk if not $Term::ReadLine::registered;
    $self-&gt;Tk_loop;
  }

  local ($/) = "\n";
  $str = &lt;$in&gt;;

  utf8::upgrade($str)
      if (${^UNICODE} &amp; PERL_UNICODE_STDIN || defined ${^ENCODING}) &amp;&amp;
         utf8::valid($str);
  print $out $rl_term_set[3];
  # bug in 5.000: chomping empty string creates length -1:
  chomp $str if defined $str;

  $str;
}

1;

</pre></body></html>