man Term::ReadLine::Gnu () - Perl extension for the GNU Readline/History Library

NAME

Term::ReadLine::Gnu - Perl extension for the GNU Readline/History Library

SYNOPSIS

  use Term::ReadLine;
  $term = new Term::ReadLine 'ProgramName';
  while ( defined ($_ = $term->readline('prompt>')) ) {
    ...
  }

DESCRIPTION

Overview

This is an implementation of Term::ReadLine using the GNU Readline/History Library.

For basic functions object oriented interface is provided. These are described in the section Standard Methods and "CWTerm::ReadLine::Gnu Functions".

This package also has the interface with the almost all functions and variables which are documented in the GNU Readline/History Library Manual. They are documented in the section "CWTerm::ReadLine::Gnu Functions" and "CWTerm::ReadLine::Gnu Variables" briefly. For more detail of the GNU Readline/History Library, see 'GNU Readline Library Manual' and 'GNU History Library Manual'.

The sample programs under CWeg/ directory and test programs under CWt/ directory in the CWTerm::ReadLine::Gnu distribution include many example of this module.

Standard Methods

These methods are standard methods defined by Term::ReadLine. returns the actual package that executes the commands. If you have installed this package, possible value is CWTerm::ReadLine::Gnu. returns the handle for subsequent calls to following functions. Argument is the name of the application. Optionally can be followed by two arguments for CWIN and CWOUT file handles. These arguments should be globs. gets an input line, with actual CWGNU Readline support. Trailing newline is removed. Returns CWundef on CWEOF. CWPREPUT is an optional argument meaning the initial value of input. The optional argument CWPREPUT is granted only if the value CWpreput is in CWFeatures. CWPROMPT may include some escape sequences. Use CWRL_PROMPT_START_IGNORE to begin a sequence of non-printing characters, and CWRL_PROMPT_END_IGNORE to end of such a sequence. adds the lines to the history of input, from where it can be used if the actual CWreadline is present. return the file handles for input and output or CWundef if CWreadline input and output cannot be used for Perl. If argument CWMAX is specified, it is an advice on minimal size of line to be included into history. CWundef means do not include anything into history. Returns the old value. returns an array with two strings that give most appropriate names for files for input and output using conventions CW"<$in", CW">$out". returns a reference to a hash which describes internal configuration (variables) of the package. Names of keys in this hash conform to standard conventions with the leading CWrl_ stripped. See section Variables for supported variables. Returns a reference to a hash with keys being features present in current implementation. Several optional features are used in the minimal interface: CWappname should be present if the first argument to CWnew is recognized, and CWminline should be present if CWMinLine method is not dummy. CWautohistory should be present if lines are put into history automatically (maybe subject to CWMinLine), and CWaddHistory if CWAddHistory method is not dummy. CWpreput means the second argument to CWreadline method is processed. CWgetHistory and CWsetHistory denote that the corresponding methods are present. CWtkRunning denotes that a Tk application may run while ReadLine is getting input. All these GNU Readline/History Library functions are callable via method interface and have names which conform to standard conventions with the leading CWrl_ stripped.

Almost methods have lower level functions in CWTerm::ReadLine::Gnu::XS package. To use them full qualified name is required. Using method interface is preferred.

Readline Convenience Functions
Naming Function
Add name to the Perl function CWFUNC. If optional argument CWKEY is specified, bind it to the CWFUNC. Returns reference to CWFunctionPtr.
  Example:
        # name name `reverse-line' to a function reverse_line(),
        # and bind it to "\C-t"
        $term->add_defun('reverse-line', \&reverse_line, ord "\ct");
Selecting a Keymap
        Keymap  rl_make_bare_keymap()
        Keymap  rl_copy_keymap(Keymap|str map)
        Keymap  rl_make_keymap()
        Keymap  rl_discard_keymap(Keymap|str map)
        Keymap  rl_get_keymap()
        Keymap  rl_set_keymap(Keymap|str map)
        Keymap  rl_get_keymap_by_name(str name)
        str     rl_get_keymap_name(Keymap map)
Binding Keys
        int     rl_bind_key(int key, FunctionPtr|str function,
                            Keymap|str map = rl_get_keymap())
Bind CWKEY to the CWFUNCTION. CWFUNCTION is the name added by the CWadd_defun method. If optional argument CWMAP is specified, binds in CWMAP. Returns non-zero in case of error.
        int     rl_bind_key_if_unbound(int key, FunctionPtr|str function,
                                       Keymap|str map = rl_get_keymap()) #GRL5.0
        int     rl_unbind_key(int key, Keymap|str map = rl_get_keymap())
Bind CWKEY to the null function. Returns non-zero in case of error.
        int     rl_unbind_function(FunctionPtr|str function,
                                   Keymap|str map = rl_get_keymap())
        int     rl_unbind_command(str command,
                                  Keymap|str map = rl_get_keymap())
        int     rl_bind_keyseq(str keyseq, FunctionPtr|str function,
                               Keymap|str map = rl_get_keymap()) # GRL 5.0
        int     rl_set_key(str keyseq, FunctionPtr|str function,
                           Keymap|str map = rl_get_keymap())
        int     rl_bind_keyseq_if_unbound(str keyseq, FunctionPtr|str function,
                                          Keymap|str map = rl_get_keymap()) # GRL 5.0
        int     rl_generic_bind(int type, str keyseq,
                                FunctionPtr|Keymap|str data,
                                Keymap|str map = rl_get_keymap())
        void    rl_parse_and_bind(str line)
Parse CWLINE as if it had been read from the ~/.inputrc file and perform any key bindings and variable assignments found. For more detail see 'GNU Readline Library Manual'.
        int     rl_read_init_file(str filename = '~/.inputrc')
Associating Function Names and Bindings
        FunctionPtr rl_named_function(str name)
        str     rl_get_function_name(FunctionPtr function)
        (FunctionPtr|Keymap|str data, int type)
                rl_function_of_keyseq(str keyseq,
                                      Keymap|str map = rl_get_keymap())
        (@str)  rl_invoking_keyseqs(FunctionPtr|str function,
                                    Keymap|str map = rl_get_keymap())
        void    rl_function_dumper(int readable = 0)
        void    rl_list_funmap_names()
        (@str)  rl_funmap_names()
        int     rl_add_funmap_entry(char *name, FunctionPtr|str function)
Allowing Undoing
        int     rl_begin_undo_group()
        int     rl_end_undo_group()
        int     rl_add_undo(int what, int start, int end, str text)
        void    rl_free_undo_list()
        int     rl_do_undo()
        int     rl_modifying(int start = 0, int end = rl_end)
Redisplay
        void    rl_redisplay()
        int     rl_forced_update_display()
        int     rl_on_new_line()
        int     rl_on_new_line_with_prompt()    # GRL 4.1
        int     rl_reset_line_state()
        int     rl_show_char(int c)
        int     rl_message(str fmt, ...)
        int     rl_crlf()                       # GRL 4.2
        int     rl_clear_message()
        void    rl_save_prompt()
        void    rl_restore_prompt()
        int     rl_expand_prompt(str prompt)    # GRL 4.2
        int     rl_set_prompt(const str prompt) # GRL 4.2
Modifying Text
        int     rl_insert_text(str text)
        int     rl_delete_text(int start = 0, int end = rl_end)
        str     rl_copy_text(int start = 0, int end = rl_end)
        int     rl_kill_text(int start = 0, int end = rl_end)
        int     rl_push_macro_input(str macro)
Character Input
        int     rl_read_key()
        int     rl_getc(FILE *STREAM)
        int     rl_stuff_char(int c)
        int     rl_execute_next(int c)          # GRL 4.2
        int     rl_clear_pending_input()        # GRL 4.2
        int     rl_set_keyboard_input_timeout(int usec) # GRL 4.2
Terminal Management
        void    rl_prep_terminal(int META_FLAG) # GRL 4.2
        void    rl_deprep_terminal()            # GRL 4.2
        void    rl_tty_set_default_bindings([Keymap KMAP])      # GRL 4.2
        void    rl_tty_unset_default_bindings([Keymap KMAP])    # GRL 5.0
        int     rl_reset_terminal(str terminal_name = getenv($TERM)) # GRL 4.2
Utility Functions
        int     rl_replace_line(str text, int clear_undo)       # GRL 4.3
        int     rl_initialize()
        int     rl_ding()
        int     rl_alphabetic(int C)
        void    rl_display_match_list(\@matches, len = $#maches, max) # GRL 4.0
Since the first element of an array CW@matches as treated as a possible completion, it is not displayed. See the descriptions of CWcompletion_matches(). When CWMAX is ommited, the max length of an item in CW@matches is used.
Miscellaneous Functions
        int     rl_macro_bind(const str keyseq, const str macro, Keymap map)
        int     rl_macro_dumper(int readline)
        int     rl_variable_bind(const str variable, const str value)
        int     rl_variable_dumper(int readline)
        int     rl_set_paren_blink_timeout(usec)        # GRL 4.2
        str     rl_get_termcap(cap)
Alternate Interface
        void    rl_callback_handler_install(str prompt, pfunc lhandler)
        void    rl_callback_read_char()
        void    rl_callback_handler_remove()
Readline Signal Handling
        void    rl_cleanup_after_signal()       # GRL 4.0
        void    rl_free_line_state()    # GRL 4.0
        void    rl_reset_after_signal() # GRL 4.0
        void    rl_resize_terminal()    # GRL 4.0
        void    rl_set_screen_size(int ROWS, int COLS)  # GRL 4.2
        (int rows, int cols)    rl_get_screen_size()    # GRL 4.2
        int     rl_set_signals()        # GRL 4.0
        int     rl_clear_signals()      # GRL 4.0
Completion Functions
        int     rl_complete_internal(int what_to_do = TAB)
        int     rl_completion_mode(FunctionPtr|str function)
        (@str)  rl_completion_matches(str text,
                                      pfunc func = filename_completion_function)
        str     rl_filename_completion_function(str text, int state)
        str     rl_username_completion_function(str text, int state)
        str     list_completion_function(str text, int state)
History Functions
Initializing History and State Management
        void    using_history()
History List Management
        void    add_history(str string)
        int     stifle_history(int max|undef)
stifles the history list, remembering only the last CWMAX entries. If CWMAX is undef, remembers all entries. This is a replacement of unstifle_history().
        int     unstifle_history()
This is equivalent with 'stifle_history(undef)'. sets the history of input, from where it can be used if the actual CWreadline is present.
        void    add_history_time(str string)    # GRL 5.0
        str     remove_history(int which)
        str     replace_history_entry(int which, str line)
        void    clear_history()
        int     history_is_stifled()
Information About the History List
        int     where_history()
        str     current_history()
        str     history_get(offset)
        time_t  history_get_time(offset)
        int     history_total_bytes()
returns the history of input as a list, if actual CWreadline is present.
Moving Around the History List
        int     history_set_pos(int pos)
        str     previous_history()
        str     next_history()
Searching the History List
        int     history_search(str string, int direction = -1)
        int     history_search_prefix(str string, int direction = -1)
        int     history_search_pos(str string,
                                   int direction = -1,
                                   int pos = where_history())
Managing the History File
        int     read_history(str filename = '~/.history',
                             int from = 0, int to = -1)
        int     read_history_range(str filename = '~/.history',
                                   int from = 0, int to = -1)
adds the contents of CWFILENAME to the history list, a line at a time. If CWFILENAME is false, then read from ~/.history. Start reading at line CWFROM and end at CWTO. If CWFROM is omitted or zero, start at the beginning. If CWTO is omitted or less than CWFROM, then read until the end of the file. Returns true if successful, or false if not. CWread_history() is an aliase of CWread_history_range().
        int     write_history(str filename = '~/.history')
writes the current history to CWFILENAME, overwriting CWFILENAME if necessary. If CWFILENAME is false, then write the history list to ~/.history. Returns true if successful, or false if not.
        int     append_history(int nelements, str filename = '~/.history')
        int     history_truncate_file(str filename = '~/.history',
                                      int nlines = 0)
History Expansion
        (int result, str expansion) history_expand(str line)
Note that this function returns CWexpansion in scalar context.
        (str text, int cindex) = get_history_event(str  string,
                                                   int  cindex,
                                                   char qchar = '\0')
        (@str)  history_tokenize(str line)
        str history_arg_extract(str line, int first = 0, int last = '$')
Following GNU Readline/History Library variables can be accessed from Perl program. See 'GNU Readline Library Manual' and ' GNU History Library Manual' for each variable. You can access them with CWAttribs methods. Names of keys in this hash conform to standard conventions with the leading CWrl_ stripped.

Examples:

    $attribs = $term->Attribs;
    $v = $attribs->{library_version};   # rl_library_version
    $v = $attribs->{history_base};      # history_base
Readline Variables
        str rl_line_buffer
        int rl_point
        int rl_end
        int rl_mark
        int rl_done
        int rl_num_chars_to_read (GRL 4.2)
        int rl_pending_input
        int rl_dispatching (GRL 4.2)
        int rl_erase_empty_line (GRL 4.0)
        str rl_prompt (read only)
        int rl_already_prompted (GRL 4.1)
        str rl_library_version (read only)
        int rl_readline_version (read only)
        int rl_gnu_readline_p (GRL 4.2)
        str rl_terminal_name
        str rl_readline_name
        filehandle rl_instream
        filehandle rl_outstream
        pfunc rl_startup_hook
        pfunc rl_pre_input_hook (GRL 4.0)
        pfunc rl_event_hook
        pfunc rl_getc_function
        pfunc rl_redisplay_function
        pfunc rl_prep_term_function (GRL 4.2)
        pfunc rl_deprep_term_function (GRL 4.2)
        pfunc rl_last_func (GRL 4.2)
        Keymap rl_executing_keymap (read only)
        Keymap rl_binding_keymap (read only)
        str rl_executing_macro (GRL 4.2)
        int rl_readline_state (GRL 4.2)
        int rl_explicit_arg (GRL 4.2)
        int rl_numeric_arg (GRL 4.2)
        int rl_editing_mode (GRL 4.2)
Signal Handling Variables
        int rl_catch_signals (GRL 4.0)
        int rl_catch_sigwinch (GRL 4.0)
Completion Variables
        pfunc rl_completion_entry_function
        pfunc rl_attempted_completion_function
        pfunc rl_filename_quoting_function
        pfunc rl_filename_dequoting_function
        pfunc rl_char_is_quoted_p
        int rl_completion_query_items
        str rl_basic_word_break_characters
        str rl_basic_quote_characters
        str rl_completer_word_break_characters
        pfunc rl_completion_word_break_hook (GRL 5.0)
        str rl_completer_quote_characters
        str rl_filename_quote_characters
        str rl_special_prefixes
        int rl_completion_append_character
        int rl_completion_suppress_append (GRL 4.3)
        int rl_completion_quote_charactor (GRL 5.0)
        int rl_completion_suppress_quote (GRL 5.0)
        int rl_completion_found_quote (GRL 5.0)
        int rl_completion_mark_symlink_dirs (GRL 4.3)
        int rl_ignore_completion_duplicates
        int rl_filename_completion_desired
        int rl_filename_quoting_desired
        int rl_attempted_completion_over (GRL 4.2)
        int rl_completion_type (GRL 4.2)
        int rl_inhibit_completion
        pfunc rl_ignore_some_completion_function
        pfunc rl_directory_completion_hook
        pfunc rl_completion_display_matches_hook (GRL 4.0)
History Variables
        int history_base
        int history_length
        int history_max_entries (called `max_input_history'. read only)
        int history_write_timestamps (GRL 5.0)
        char history_expansion_char
        char history_subst_char
        char history_comment_char
        str history_word_delimiters (GRL 4.2)
        str history_no_expand_chars
        str history_search_delimiter_chars
        int history_quotes_inhibit_expansion
        pfunc history_inhibit_expansion_function
Function References
        rl_getc
        rl_redisplay
        rl_callback_read_char
        rl_display_match_list
        rl_filename_completion_function
        rl_username_completion_function
        list_completion_function
        shadow_redisplay
        Tk_getc

Custom Completion

In this section variables and functions for custom completion is described with examples.

Most of descriptions in this section is cited from GNU Readline Library manual. This variable holds reference refers to a generator function for CWcompletion_matches(). A generator function is called repeatedly from CWcompletion_matches(), returning a string each time. The arguments to the generator function are CWTEXT and CWSTATE. CWTEXT is the partial word to be completed. CWSTATE is zero the first time the function is called, allowing the generator to perform any necessary initialization, and a positive non-zero integer for each subsequent call. When the generator function returns CWundef this signals CWcompletion_matches() that there are no more possibilities left. If the value is undef, built-in CWfilename_completion_function is used. A sample generator function, CWlist_completion_function, is defined in Gnu.pm. You can use it as follows;

    use Term::ReadLine;
    ...
    my $term = new Term::ReadLine 'sample';
    my $attribs = $term->Attribs;
    ...
    $attribs->{completion_entry_function} =
        $attribs->{list_completion_function};
    ...
    $attribs->{completion_word} =
        [qw(reference to a list of words which you want to use for completion)];
    $term->readline("custom completion>");
See also CWcompletion_matches. A reference to an alternative function to create matches. The function is called with CWTEXT, CWLINE_BUFFER, CWSTART, and CWEND. CWLINE_BUFFER is a current input buffer string. CWSTART and CWEND are indices in CWLINE_BUFFER saying what the boundaries of CWTEXT are. If this function exists and returns null list or CWundef, or if this variable is set to CWundef, then an internal function CWrl_complete() will call the value of CW$rl_completion_entry_function to generate matches, otherwise the array of strings returned will be used. The default value of this variable is CWundef. You can use it as follows;
    use Term::ReadLine;
    ...
    my $term = new Term::ReadLine 'sample';
    my $attribs = $term->Attribs;
    ...
    sub sample_completion {
        my ($text, $line, $start, $end) = @_;
        # If first word then username completion, else filename completion
        if (substr($line, 0, $start) =~ /^\s*$/) {
            return $term->completion_matches($text,
                                             $attribs->{'username_completion_function'});
        } else {
            return ();
        }
    }
    ...
    $attribs->{attempted_completion_function} = \&sample_completion;
Returns an array of strings which is a list of completions for CWTEXT. If there are no completions, returns CWundef. The first entry in the returned array is the substitution for CWTEXT. The remaining entries are the possible completions. CWENTRY_FUNC is a generator function which has two arguments, and returns a string. The first argument is CWTEXT. The second is a state argument; it is zero on the first call, and non-zero on subsequent calls. CWENTRY_FUNC returns a CWundef to the caller when there are no more matches. If the value of CWENTRY_FUNC is undef, built-in CWfilename_completion_function is used. CWcompletion_matches is a Perl wrapper function of an internal function CWcompletion_matches(). See also CW$rl_completion_entry_function. A variable whose content is a reference to a function which returns a list of candidates to complete. This variable is compatible with CWTerm::ReadLine::Perl and very easy to use.
    use Term::ReadLine;
    ...
    my $term = new Term::ReadLine 'sample';
    my $attribs = $term->Attribs;
    ...
    $attribs->{completion_function} = sub {
        my ($text, $line, $start) = @_;
        return qw(a list of candidates to complete);
    }
A sample generator function defined by CWTerm::ReadLine::Gnu. Example code at CWrl_completion_entry_function shows how to use this function. This method provides the function CWrl_callback_handler_install() with the following addtional feature compatible with CWreadline method; ornament feature, CWTerm::ReadLine::Perl compatible completion function, histroy expansion, and addition to history buffer.
        int     rl_call_function(FunctionPtr|str function, count = 1, key = -1)
Returns a list of all function names. A redisplay function for password input. You can use it as follows;
        $attribs->{redisplay_function} = $attribs->{shadow_redisplay};
        $line = $term->readline("password> ");
Returns candidates of filename to complete. This function can be used with CWcompletion_function and is implemented for the compatibility with CWTerm::ReadLine::Perl. See the description of section Custom Completion. When true, the history expansion is enabled. By default false. See the description of section Custom Completion. A reference to a list of candidates to complete for CWlist_completion_function. The equivalent of the Bash CWhistory-expand-line editing command. The equivalent of the Korn shell CWoperate-and-get-next-history-line editing command and the Bash CWoperate-and-get-next. This command is bound to CW\C-o by default for the compatibility with the Bash and CWTerm::ReadLine::Perl. Shows the version of CWTerm::ReadLine::Gnu and the one of the GNU Readline Library. Change ornaments interactively.

FILES

~/.inputrc
Readline init file. Using this file it is possible that you would like to use a different set of key bindings. When a program which uses the Readline library starts up, the init file is read, and the key bindings are set. Conditional key binding is also available. The program name which is specified by the first argument of CWnew method is used as the application construct. For example, when your program call CWnew method like this;
        ...
        $term = new Term::ReadLine 'PerlSh';
        ...
your ~/.inputrc can define key bindings only for it as follows;
        ...
        $if PerlSh
        Meta-Rubout: backward-kill-word
        "\C-x\C-r": re-read-init-file
        "\e[11~": "Function Key 1"
        $endif
        ...

EXPORTS

None.

SEE ALSO

GNU Readline Library Manual
GNU History Library Manual
eg/* and t/* in the Term::ReadLine::Gnu distribution
Articles related to Term::ReadLine::Gnu
effective perl programming
        http://www.usenix.org/publications/login/2000-7/features/effective.html
This article demonstrates how to integrate Term::ReadLine::Gnu into an interactive command line program.
eijiro (Japanese)
        http://bulknews.net/lib/columns/02_eijiro/column.html
A command line interface to Eijiro, Japanese-English dictionary service on WWW.
Works which use Term::ReadLine::Gnu
Perl Debugger
        perl -d
The Perl Shell (psh)
        http://www.focusresearch.com/gregor/psh/
The Perl Shell is a shell that combines the interactive nature of a Unix shell with the power of Perl. A programmable completion feature compatible with bash is implemented.
SPP (Synopsys Plus Perl)
        http://www.stanford.edu/~jsolomon/SPP/
SPP (Synopsys Plus Perl) is a Perl module that wraps around Synopsys' shell programs. SPP is inspired by the original dc_perl written by Steve Golson, but it's an entirely new implementation. Why is it called SPP and not dc_perl? Well, SPP was written to wrap around any of Synopsys' shells.
PFM (Personal File Manager for Unix/Linux)
        http://p-f-m.sourceforge.net/
Pfm is a terminal-based file manager written in Perl, based on PFM.COM for MS-DOS (originally by Paul Culley and Henk de Heer).
The soundgrab
        http://rawrec.sourceforge.net/soundgrab/soundgrab.html
soundgrab is designed to help you slice up a big long raw audio file (by default 44.1 kHz 2 channel signed sixteen bit little endian) and save your favorite sections to other files. It does this by providing you with a cassette player like command line interface.
PDL (The Perl Data Language)
        http://pdl.perl.org/index_en.html
PDL (``Perl Data Language'') gives standard Perl the ability to compactly store and speedily manipulate the large N-dimensional data arrays which are the bread and butter of scientific computing.
PIQT (Perl Interactive DBI Query Tool)
        http://piqt.sourceforge.net/
PIQT is an interactive query tool using the Perl DBI database interface. It supports ReadLine, provides a built in scripting language with a Lisp like syntax, an online help system, and uses wrappers to interface to the DBD modules.
Ghostscript Shell
        http://www.panix.com/~jdf/gshell/
It provides a friendly way to play with the Ghostscript interpreter, including command history and auto-completion of Postscript font names and reserved words.
vshnu (the New Visual Shell)
        http://www.cs.indiana.edu/~kinzler/vshnu/
A visual shell and CLI shell supplement. If you know any other works which can be listed here, please let me know.

AUTHOR

Hiroo Hayashi CW<hiroo.hayashi@computer.org>

CWhttp://www.perl.org/CPAN/authors/Hiroo_HAYASHI/

TODO

GTK+ support in addition to Tk.

BUGS

CWrl_add_defun() can define up to 16 functions.

Ornament feature works only on prompt strings. It requires very hard hacking of CWdisplay.c:rl_redisplay() in GNU Readline library to ornament input line.

CWnewTTY() is not tested yet.