NAME

Term::Shell - A simple command-line shell framework.

SYNOPSIS

package MyShell;
use base qw(Term::Shell);

sub run_command1  { print "command 1!\n"; }
sub smry_command1 { "what does command1 do?" }
sub help_command1 {
    <<'END';
Help on 'command1', whatever that may be...
END
}

sub run_command2 { print "command 2!\n"; }

package main;
my $shell = MyShell->new;
$shell->cmdloop;

DESCRIPTION

Term::Shell lets you write simple command-line shells. All the boring details like command-line parsing, terminal handling, and tab completion are handled for you.

The base class comes with two commands pre-defined: exit and help.

To write a shell with an exec command, do something like this:

package MyShell;
use base qw(Term::Shell); # or manually edit @MyShell::ISA.

sub run_exec {
    my ($o, $cmd, @args) = @_;
    if ($cmd ne $0) {
        print "I'm sorry you're leaving us...\n";
    }
    exec $cmd, @args;
    exit 1;
}

When Term::Shell needs to handle the exec command, it will invoke this method. That's all there is to it! You write handlers, and Term::Shell handles the gory details.

Using Term::Shell Shells

How do you bring your shell to life? Assuming the package MyShell contains your actions, just do this:

use MyShell;
my $shell = MyShell->new;

# Setup code here (if you wish)

# Invoke the shell
$shell->cmdloop;

# Cleanup code here (if you wish)

Most people put the setup code in the shell itself, so you can usually get away with this:

use MyShell;
MyShell->new->cmdloop;

It's that simple! All the actions and command handlers go in MyShell.pm, and your main program is simple. In fact, it's so simple that some people like to write both the actions and the invocation in the same file:

package main;
MyShell->new->cmdloop;

package MyShell;
use base qw(Term::Shell);

# Actions here

Adding commands to your shell is just as easy, if not easier.

Adding Commands to Your Shell

For every command foo, Term::Shell needs a method called run_foo(), where 'foo' is what the user will type in. The method will be called with the Term::Shell object as the first parameter, followed by any arguments the user typed after the command.

Several prefixes other than run_ are supported; each prefix tells Term::Shell to call that handler under different circumstances. The following list enumerates all the "special" prefixes. Term::Shell will ignore any method that doesn't start with a prefix listed here.

  1. run_foo()

    Adds the command foo to the list of supported commands. The method's return value is saved by Term::Shell, but is not used.

    The method is called with the Term::Shell object as its first argument, followed by any arguments the user typed in.

    Special case: if you provide a method run_(), Term::Shell will call it whenever the user enters a blank line. A blank line is anything which matches the regular expression /^\s*$/.

  2. help_foo()

    Adds the command foo to the list of help topics. This means the user may enter 'help foo' and get a help screen. It should return a single string to be displayed to the user.

    The method is called with the Term::Shell object as its first argument, followed by any arguments the user typed in after 'help foo'. You can implement hierarchical help documents by using the arguments.

    If you do not provide a help_foo() method, typing 'help foo' produces an error message.

  3. smry_foo()

    Should return a one-line summary of foo, to be displayed in the help screen.

    This method is called with the Term::Shell object as its first argument, and no other arguments.

    If you do not provide a smry_foo() method, then the string 'undocumented' is used instead.

  4. comp_foo()

    Provides custom tab-completion for foo. That means if the user types 'foo ' and then hits <TAB>, this method will be called. It should return an array reference containing a list of possible completions.

    This method is called with the Term::Shell object as its first argument, followed by the three arguments:

    1. $word

      The word the user is trying to complete.

    2. $line

      The line as typed by the user so far.

    3. $start

      The offset into $line where $word starts.

    If you do not provide comp_foo(), Term::Shell will always return no completions for foo.

    Special case: if you provide comp_(), Term::Shell will call it when the user is trying to complete the name of a command. Term::Shell provides a default comp_() method, which completes the actions that you have written handlers for. If you want to provide tab-completion for commands that do not have handlers, override comp_().

  5. alias_foo()

    Returns a list of aliases for foo. When one of the aliases is used instead of foo, the corresponding handler for foo is called.

  6. catch_run()

    catch_help()

    catch_comp()

    catch_smry()

    Called when an undefined action is entered by the user. Normally when the user enters an unrecognized command, Term::Shell will print an error message and continue.

    This method is called with the Term::Shell object, the command typed by the user, and then the arguments which would normally be passed to the real handler.

    The catch_ methods may do anything the original function would have done. If you want, you can implement all the commands in it, but that means you're doing more work than you have to. Be lazy.

When you want something done right...

You sometimes have to do it yourself. Introducing add_handlers(). Naturally, it adds a handler to the list of defined handlers in the shell.

Term::Shell can't always find the commands you want to implement by searching the inheritance tree. Having an AUTOLOAD() method, for instance, will break this system. In that situation, you may wish to tell Term::Shell about the extra commands available using add_handlers():

package MyShell;
use base qw(Term::Shell);

sub AUTOLOAD {
    if ($AUTOLOAD =~ /::run_fuzz$/) {
        # code for 'fuzz' command
    }
    elsif ($AUTOLOAD =~ /::run_foozle$/) {
        # code for 'foozle' command
    }
}

sub init {
    my $o = shift;
    $o->add_handlers("run_fuzz", "run_foozle");
}

There are other ways to do this. You could write a catch_run routine and do the same thing from there. You'd have to override comp_ so that it would complete on "foozle" and "fuzz". The advantage to this method is that it adds the methods to the list of commands, so they show up in the help menu and you get completion for free.

Removing Commands from Your Shell

You're probably thinking "just don't write them". But remember, you can inherit from another shell class, and that parent may define commands you want to disable. Term::Shell provides a simple method to make itself forget about commands it already knows about:

  1. remove_commands()

    Removes all handlers associated with the given command (or list of commands).

    For example, Term::Shell comes with two commands (exit and help) implemented with seven handlers:

    1. smry_exit()

    2. help_exit()

    3. run_exit()

    4. smry_help()

    5. help_help()

    6. comp_help()

    7. run_help()

    If you want to create a shell that doesn't implement the help command, your code might look something like this example:

    package MyShell;
    use base qw(Term::Shell);
    
    sub init {
        my $o = shift;
        $o->remove_commands("help");
    }
    
    # ... define more handlers here ...
  2. remove_handlers()

    Removes the given handler (or handlers) from the list of defined commands. You have to specify a full handler name, including the 'run_' prefix. You can obviously specify any of the other prefixes too.

    If you wanted to remove the help for the exit command, but preserve the command itself, your code might look something like this:

    package MyShell;
    use base qw(Term::Shell);
    
    sub init {
        my $o = shift;
        $o->remove_handlers("help_exit");
    }
    
    # ... define more handlers here ...

Cover Your Tracks

If you do remove built in commands, you should be careful not to let Term::Shell print references to them. Messages like this are guaranteed to confuse people who use your shell:

shell> help
Unknown command 'help'; type 'help' for a list of commands.

Here's the innocuous looking code:

package MyShell;
use base qw(Term::Shell);

sub init {
    my $o = shift;
    $o->remove_commands("help");
}

MyShell->new->cmdloop;

The problem is that Term::Shell has to print an error message, and by default it tells the user to use the help command to see what's available. If you remove the help command, you still have to clean up after yourself and tell Term::Shell to change its error messages:

  1. msg_unknown_cmd()

    Called when the user has entered an unrecognized command, and no action was available to satisfy it. It receives the object and the command typed by the user as its arguments. It should return an error message; by default, it is defined thusly:

    sub msg_unknown_cmd {
        my ($o, $cmd) = @_;
        <<END;
    Unknown command '$cmd'; type 'help' for a list of commands.
    END
    }
  2. msg_ambiguous_cmd()

    Called when the user has entered a command for which more than handler exists. (For example, if both "quit" and "query" are commands, then "qu" is an ambiguous command, because it could be either.) It receives the object, the command, and the possible commands which could complete it. It should return an error message; by default it is defined thusly:

    sub msg_ambiguous_cmd {
        my ($o, $cmd, @c) = @_;
        local $" = "\n\t";
        <<END;
    Ambiguous command '$cmd': possible commands:
            @c
    END
    }

The Term::Shell API

Shell classes can use any of the methods in this list. Any other methods in Term::Shell may change.

  1. new()

    Creates a new Term::Shell object. It currently does not use its arguments. The arguments are saved in '$o->{API}{args}', in case you want to use them later.

    my $sh = Term::Shell->new(@arbitrary_args);
  2. cmd()

    cmd($txt);

    Invokes $txt as if it had been typed in at the prompt.

    $sh->cmd("echo 1 2 3");
  3. cmdloop()

    mainloop()

    Repeatedly prompts the user, reads a line, parses it, and invokes a handler. Uses cmd() internally.

    MyShell->new->cmdloop;

    mainloop() is a synonym for cmdloop(), provided for backwards compatibility. Earlier (unreleased) versions of Term::Shell have only provided mainloop(). All documentation and examples use cmdloop() instead.

  4. init()

    fini()

    Do any initialization or cleanup you need at shell creation (init()) and destruction (fini()) by defining these methods.

    No parameters are passed.

  5. preloop()

    postloop()

    Do any initialization or cleanup you need at shell startup (preloop()) and shutdown (postloop()) by defining these methods.

    No parameters are passed.

  6. precmd()

    postcmd()

    Do any initialization or cleanup before and after calling each handler.

    The parameters are:

    1. $handler

      A reference to the name of the handler that is about to be executed.

      Passed by reference so you can control which handler will be called.

    2. $cmd

      A reference to the command as the user typed it.

      Passed by reference so you can set the command. (If the handler is a "catch_" command, it can be fooled into thinking the user typed some other command, for example.)

    3. $args

      The arguments as typed by the user. This is passed as an array reference so that you can manipulate the arguments received by the handler.

    sub precmd {
        my $o = shift;
        my ($handler, $cmd, @args) = @_;
        # ...
    }
  7. stoploop()

    Sets a flag in the Term::Shell object that breaks out of cmdloop(). Note that cmdloop() resets this flag each time you call it, so code like this will work:

    my $sh = MyShell->new;
    $sh->cmdloop;	# an interactive session
    $sh->cmdloop;	# prompts the user again

    Term::Shell's built-in run_exit() command just calls stoploop().

  8. idle()

    If you set check_idle to a non-zero number (see "The Term::Shell Object") then this method is called every check_idle seconds. The idle() method defined in Term::Shell does nothing -- it exists only to be redefined in subclasses.

    package MyShell;
    use base qw(Term::Shell);
    
    sub init {
        my $o = shift;
        $o->{API}{check_idle} = 0.1;	# 10/s
    }
    
    sub idle {
        print "Idle!\n";
    }
  9. prompt_str()

    Returns a string to be used as the prompt. prompt_str() is called just before calling the readline() method of Term::ReadLine. If you do not override this method, the string `shell> ' is used.

    package MyShell;
    use base qw(Term::Shell);
    
    sub prompt_str { "search> " }
  10. prompt()

    Term::Shell provides this method for convenience. It's common for a handler to ask the user for more information. This method makes it easy to provide the user with a different prompt and custom completions provided by you.

    The prompt() method takes the following parameters:

    1. $prompt

      The prompt to display to the user. This can be any string you want.

    2. $default

      The default value to provide. If the user enters a blank line (all whitespace characters) then the this value will be returned.

      Note: unlike ExtUtils::MakeMaker's prompt(), Term::Shell's prompt() does not modify $prompt to indicate the $default response. You have to do that yourself.

    3. $completions

      An optional list of completion values. When the user hits <TAB>, Term::Shell prints the completions which match what they've typed so far. Term::Shell does not enforce that the user's response is one of these values.

    4. $casei

      An optional boolean value which indicates whether the completions should be matched case-insensitively or not. A true value indicates that FoO and foo should be considered the same.

    prompt() returns the unparsed line to give you maximum flexibility. If you need the line parsed, use the line_parsed() method on the return value.

  11. cmd_prefix()

    cmd_suffix()

    These methods should return a prefix and suffix for commands, respectively. For instance, an IRC client will have a prefix of /. Most shells have an empty prefix and suffix.

  12. page()

    page($txt)

    Prints $txt through a pager, prompting the user to press a key for the next screen full of text.

    Currently, this just prints out the text without any paging at all. The next version will have an internal pager, plus the ability to use an external pager. See "BUGS AND DEFICIENCIES".

  13. line()

    line_parsed()

    Although run_foo() is called with the parsed arguments from the command-line, you may wish to see the raw command-line. This is available through the line() method. If you want to retrieve the parsed line again, use line_parsed().

    line_parsed() accepts an optional string parameter: the line to parse. If you have your own line to parse, you can pass it to line_parsed() and get back a list of arguments. This is useful inside completion methods, since you don't get a parsed list there.

  14. run()

    If you want to run another handler from within a handler, and you have pre-parsed arguments, use run() instead of cmd(). cmd() parses its parameter, whereas run() takes each element as a separate parameter.

    It needs the name of the action to run and any arguments to pass to the handler.

    Term::Shell uses this method internally to invoke command handlers.

  15. help()

    If you want to get the raw text of a help message, use help(). It needs the name of the help topic and any arguments to pass to the handler.

    Term::Shell uses this method internally to invoke help handlers.

  16. summary()

    If you want to get the summary text of an action, use summary(). It needs the name of the action.

    Term::Shell uses this method internally to display the help page.

  17. possible_actions()

    You will probably want this method in comp_foo(). possible_actions() takes a word and a list, and returns a list of possible matches. Term::Shell uses this method internally to decide which handler to run when the user enters a command.

    There are several arguments, but you probably won't use them all in the simple cases:

    1. $needle

      The (possible incomplete) word to try to match against the list of actions (the haystack).

    2. $type

      The type with which to prefix $action. This is useful when completing a real action -- you have to specify whether you want it to look for "run_" or "help_" or something else. If you leave it blank, it will use $action without prefixing it.

    3. $strip

      If you pass in a true value here, possible_actions() will remove an initial $type from the beginning of each result before returning the results. This is useful if you want to know what the possible "run_" commands are, but you don't want to have the "run_" in the final result.

      If you do not specify this argument, it uses '0' (the default is not to strip the results).

    4. $haystack

      You can pass in a reference to a list of strings here. Each string will be compared with $needle.

      If you do not specify this argument, it uses the list of handlers. This is how Term::Shell matches commands typed in by the user with command handlers written by you.

  18. print_pairs()

    This overloaded beast is used whenever Term::Shell wants to print a set of keys and values. It handles wrapping long values, indenting the whole thing, inserting the separator between the key and value, and all the rest.

    There are lots of parameters, but most of them are optional:

    1. $keys

      A reference to a list of keys to print.

    2. $values

      A reference to a list of values to print.

    3. $sep

      The string used to separate the keys and values. If omitted, ': ' is used.

    4. $left

      The justification to be used to line up the keys. If true, the keys will be left-justified. If false or omitted, the keys will be right-justified.

    5. $ind

      A string used to indent the whole paragraph. Internally, print_pairs() uses length(), so you shouldn't use tabs in the indent string. If omitted, the empty string is used (no indent).

    6. $len

      An integer which describes the minimum length of the keys. Normally, print_pairs() calculates the longest key and assigns the column width to be as wide as the longest key plus the separator. You can force the column width to be larger using $len. If omitted, 0 is used.

    7. $wrap

      A boolean which indicates whether the value should be text-wrapped using Text::Autoformat. Text is only ever wrapped if it contains at least one space. If omitted, 0 is used.

    8. $cols

      An integer describing the number of columns available on the current terminal. Normally 78 is used, or the environment variable COLUMNS, but you can override the number here to simulate a right-indent.

  19. term()

    Returns the underlying Term::ReadLine object used to interact with the user. You can do powerful things with this object; in particular, you will cripple Term::Shell's completion scheme if you change the completion callback function.

  20. process_esc()

    This method may be overridden to provide shell-like escaping of backslashes inside quoted strings. It accepts two parameters:

    1. $c

      The character which was escaped by a backslash.

    2. $quote

      The quote character used to delimit this string. Either " or '.

    This method should return the string which should replace the backslash and the escaped character.

    By default, process_esc() uses escaping rules similar to Perl's single-quoted string:

    1. Escaped backslashes return backslashes. The string "123\\456" returns 123\456.

    2. Escaped quote characters return the quote character (to allow quote characters in strings). The string "abc\"def" returns abc"def.

    3. All other backslashes are returned verbatim. The string "123\456" returns 123\456.

    Term::Shell's quote characters cannot be overridden, unless you override line_parsed(): they are " or '. This may change in a future version of Term::Shell.

  21. add_handlers()

    See "Adding Commands to Your Shell" for information on add_handlers().

  22. remove_commands()

    remove_handlers()

    See "Removing Commands from Your Shell" for information on remove_handlers().

The Term::Shell Object

Term::Shell creates a hash based Perl object. The object contains information like what handlers it found, the underlying Term::ReadLine object, and any arguments passed to the constructor.

This hash is broken into several subhashes. The only two subhashes that a Shell should ever use are $o->{API} and $o->{SHELL}. The first one contains all the information that Term::Shell has gathered for you. The second one is a private area where your Shell can freely store data that it might need later on.

This section will describe all the Term::Shell object "API" attributes:

The args Attribute

This an array reference containing any arguments passed to the Term::Shell constructor.

The case_ignore Attribute

This boolean controls whether commands should be matched without regard to case. If this is true, then typing FoO will have the same effect as typing foo.

Defaults to true on MSWin32, and false on other platforms.

The class Attribute

The class of the object. This is probably the package containing the definition of your shell, but if someone subclasses your shell, it's their class.

The command Attribute

Whenever Term::Shell invokes an action, it stores information about the action in the command attribute. Information about the last "run" action to be invoked is stored in $o->{API}{command}{run}. The information itself is stored in a subhash containing these fields:

name

The name of the command, as typed by the user.

found

The a boolean value indicating whether a handler could be found.

handler

The full name of the handler, if found.

Note that this facility only stores information about the last action to be executed. It's good enough for retrieving the information about the last handler which ran, but not for much else.

The following example shows a case where run_foo() calls run_add(), and prints its return value (in this case, 42).

sub run_foo {
    my $o = shift;
    my $sum = $o->run("add", 21, 21);
    print "21 + 21 = ", $sum, "\n";
}

sub run_add {
    my $o = shift;
    my $sum = 0;
    $sum += $_ for @_;
    print "add(): sum = $sum\n";
    return $sum;
}

At the end of run_foo(), $o->{API}{command}{run}{handler} contains the string "run_add".

The match_uniq Attribute

This boolean controls whether the user can type in only enough of the command to make it unambiguous. If true, then if the shell has the commands foo and bar defined, the user can type f to run foo, and b to run bar.

Defaults to true.

The readline Attribute

Which Term::ReadLine module is being used. Currently, this is always one of Term::ReadLine::Stub, Term::ReadLine::Perl, or Term::ReadLine::Gnu.

The script Attribute

The name of the script that invoked your shell.

The version Attribute

The version of Term::Shell you are running under.

BUGS AND DEFICIENCIES

There are bound to be some bugs lurking about. Here are the things I know I haven't done:

  1. page()

    Currently page() just prints its text to the screen. This should really, um, page the text, either through an external program or by itself.

If you find bugs, please send them to NEILW@cpan.org.

SEE ALSO

For more information about the underlying ReadLine module, see Term::ReadLine. You may also want to look at Term::ReadLine::Gnu and Term::ReadLine::Perl.

For more information about the underlying formatter used by print_pairs(), see Text::Autoformat.

The API for Term::Shell was inspired by (gasp!) a Python package called cmd. For more information about this package, please look in the Python Library Reference, either in your Python distribution or at http://www.python.org/doc/current/lib/module-cmd.html

AUTHOR

Neil Watkiss (NEILW@cpan.org)

COPYRIGHT

Copyright (c) 2001, Neil Watkiss. All Rights Reserved.

All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the same terms as Perl itself.

See http://www.perl.com/perl/misc/Artistic.html

2 POD Errors

The following errors were encountered while parsing the POD:

Around line 211:

You forgot a '=back' before '=head2'

Around line 244:

=back without =over