1Term::Shell(3)        User Contributed Perl Documentation       Term::Shell(3)
2
3
4

NAME

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

SYNOPSIS

9           package MyShell;
10           use base qw(Term::Shell);
11
12           sub run_command1  { print "command 1!\n"; }
13           sub smry_command1 { "what does command1 do?" }
14           sub help_command1 {
15               <<'END';
16           Help on 'command1', whatever that may be...
17           END
18           }
19
20           sub run_command2 { print "command 2!\n"; }
21
22           package main;
23           my $shell = MyShell->new;
24           $shell->cmdloop;
25

DESCRIPTION

27       Term::Shell lets you write simple command-line shells. All the boring
28       details like command-line parsing, terminal handling, and tab
29       completion are handled for you.
30
31       The base class comes with two commands pre-defined: exit and help.
32
33       To write a shell with an "exec" command, do something like this:
34
35          package MyShell;
36          use base qw(Term::Shell); # or manually edit @MyShell::ISA.
37
38          sub run_exec {
39              my ($o, $cmd, @args) = @_;
40              if ($cmd ne $0) {
41                  print "I'm sorry you're leaving us...\n";
42              }
43              exec $cmd, @args;
44              exit 1;
45          }
46
47       When Term::Shell needs to handle the "exec" command, it will invoke
48       this method. That's all there is to it! You write handlers, and
49       Term::Shell handles the gory details.
50

Using Term::Shell Shells

52       How do you bring your shell to life? Assuming the package "MyShell"
53       contains your actions, just do this:
54
55          use MyShell;
56          my $shell = MyShell->new;
57
58          # Setup code here (if you wish)
59
60          # Invoke the shell
61          $shell->cmdloop;
62
63          # Cleanup code here (if you wish)
64
65       Most people put the setup code in the shell itself, so you can usually
66       get away with this:
67
68          use MyShell;
69          MyShell->new->cmdloop;
70
71       It's that simple! All the actions and command handlers go in
72       "MyShell.pm", and your main program is simple. In fact, it's so simple
73       that some people like to write both the actions and the invocation in
74       the same file:
75
76          package main;
77          MyShell->new->cmdloop;
78
79          package MyShell;
80          use base qw(Term::Shell);
81
82          # Actions here
83
84       Adding commands to your shell is just as easy, if not easier.
85

Adding Commands to Your Shell

87       For every command "foo", Term::Shell needs a method called "run_foo()",
88       where 'foo' is what the user will type in. The method will be called
89       with the Term::Shell object as the first parameter, followed by any
90       arguments the user typed after the command.
91
92       Several prefixes other than "run_" are supported; each prefix tells
93       Term::Shell to call that handler under different circumstances. The
94       following list enumerates all the "special" prefixes. Term::Shell will
95       ignore any method that doesn't start with a prefix listed here.
96
97       1.  run_foo()
98
99           Adds the command "foo" to the list of supported commands. The
100           method's return value is saved by Term::Shell, but is not used.
101
102           The method is called with the Term::Shell object as its first
103           argument, followed by any arguments the user typed in.
104
105           Special case: if you provide a method "run_()", Term::Shell will
106           call it whenever the user enters a blank line. A blank line is
107           anything which matches the regular expression "/^\s*$/".
108
109       2.  help_foo()
110
111           Adds the command "foo" to the list of help topics. This means the
112           user may enter 'help foo' and get a help screen. It should return a
113           single string to be displayed to the user.
114
115           The method is called with the Term::Shell object as its first
116           argument, followed by any arguments the user typed in after 'help
117           foo'. You can implement hierarchical help documents by using the
118           arguments.
119
120           If you do not provide a "help_foo()" method, typing 'help foo'
121           produces an error message.
122
123       3.  smry_foo()
124
125           Should return a one-line summary of "foo", to be displayed in the
126           help screen.
127
128           This method is called with the Term::Shell object as its first
129           argument, and no other arguments.
130
131           If you do not provide a "smry_foo()" method, then the string
132           'undocumented' is used instead.
133
134       4.  comp_foo()
135
136           Provides custom tab-completion for "foo". That means if the user
137           types 'foo ' and then hits <TAB>, this method will be called. It
138           should return an array reference containing a list of possible
139           completions.
140
141           This method is called with the Term::Shell object as its first
142           argument, followed by the three arguments:
143
144           1.  $word
145
146               The word the user is trying to complete.
147
148           2.  $line
149
150               The line as typed by the user so far.
151
152           3.  $start
153
154               The offset into $line where $word starts.
155
156           If you do not provide "comp_foo()", Term::Shell will always return
157           no completions for "foo".
158
159           Special case: if you provide "comp_()", Term::Shell will call it
160           when the user is trying to complete the name of a command.
161           Term::Shell provides a default "comp_()" method, which completes
162           the actions that you have written handlers for. If you want to
163           provide tab-completion for commands that do not have handlers,
164           override "comp_()".
165
166       5.  alias_foo()
167
168           Returns a list of aliases for "foo". When one of the aliases is
169           used instead of "foo", the corresponding handler for "foo" is
170           called.
171
172       6.  catch_run()
173
174           catch_help()
175
176           catch_comp()
177
178           catch_smry()
179
180           Called when an undefined action is entered by the user. Normally
181           when the user enters an unrecognized command, Term::Shell will
182           print an error message and continue.
183
184           This method is called with the Term::Shell object, the command
185           typed by the user, and then the arguments which would normally be
186           passed to the real handler.
187
188           The "catch_" methods may do anything the original function would
189           have done.  If you want, you can implement all the commands in it,
190           but that means you're doing more work than you have to. Be lazy.
191
192   When you want something done right...
193       You sometimes have to do it yourself. Introducing add_handlers().
194       Naturally, it adds a handler to the list of defined handlers in the
195       shell.
196
197       Term::Shell can't always find the commands you want to implement by
198       searching the inheritance tree. Having an AUTOLOAD() method, for
199       instance, will break this system. In that situation, you may wish to
200       tell Term::Shell about the extra commands available using
201       add_handlers():
202
203          package MyShell;
204          use base qw(Term::Shell);
205
206          sub AUTOLOAD {
207              if ($AUTOLOAD =~ /::run_fuzz$/) {
208                  # code for 'fuzz' command
209              }
210              elsif ($AUTOLOAD =~ /::run_foozle$/) {
211                  # code for 'foozle' command
212              }
213          }
214
215          sub init {
216              my $o = shift;
217              $o->add_handlers("run_fuzz", "run_foozle");
218          }
219
220       There are other ways to do this. You could write a "catch_run" routine
221       and do the same thing from there. You'd have to override "comp_" so
222       that it would complete on "foozle" and "fuzz". The advantage to this
223       method is that it adds the methods to the list of commands, so they
224       show up in the help menu and you get completion for free.
225

Removing Commands from Your Shell

227       You're probably thinking "just don't write them". But remember, you can
228       inherit from another shell class, and that parent may define commands
229       you want to disable. Term::Shell provides a simple method to make
230       itself forget about commands it already knows about:
231
232       1.  remove_commands()
233
234           Removes all handlers associated with the given command (or list of
235           commands).
236
237           For example, Term::Shell comes with two commands ("exit" and
238           "help") implemented with seven handlers:
239
240           1.  smry_exit()
241
242           2.  help_exit()
243
244           3.  run_exit()
245
246           4.  smry_help()
247
248           5.  help_help()
249
250           6.  comp_help()
251
252           7.  run_help()
253
254           If you want to create a shell that doesn't implement the "help"
255           command, your code might look something like this example:
256
257              package MyShell;
258              use base qw(Term::Shell);
259
260              sub init {
261                  my $o = shift;
262                  $o->remove_commands("help");
263              }
264
265              # ... define more handlers here ...
266
267       2.  remove_handlers()
268
269           Removes the given handler (or handlers) from the list of defined
270           commands. You have to specify a full handler name, including the
271           'run_' prefix. You can obviously specify any of the other prefixes
272           too.
273
274           If you wanted to remove the help for the "exit" command, but
275           preserve the command itself, your code might look something like
276           this:
277
278              package MyShell;
279              use base qw(Term::Shell);
280
281              sub init {
282                  my $o = shift;
283                  $o->remove_handlers("help_exit");
284              }
285
286              # ... define more handlers here ...
287
288   Cover Your Tracks
289       If you do remove built in commands, you should be careful not to let
290       Term::Shell print references to them. Messages like this are guaranteed
291       to confuse people who use your shell:
292
293          shell> help
294          Unknown command 'help'; type 'help' for a list of commands.
295
296       Here's the innocuous looking code:
297
298          package MyShell;
299          use base qw(Term::Shell);
300
301          sub init {
302              my $o = shift;
303              $o->remove_commands("help");
304          }
305
306          MyShell->new->cmdloop;
307
308       The problem is that Term::Shell has to print an error message, and by
309       default it tells the user to use the "help" command to see what's
310       available. If you remove the "help" command, you still have to clean up
311       after yourself and tell Term::Shell to change its error messages:
312
313       1.  msg_unknown_cmd()
314
315           Called when the user has entered an unrecognized command, and no
316           action was available to satisfy it. It receives the object and the
317           command typed by the user as its arguments. It should return an
318           error message; by default, it is defined thusly:
319
320              sub msg_unknown_cmd {
321                  my ($o, $cmd) = @_;
322                  <<END;
323              Unknown command '$cmd'; type 'help' for a list of commands.
324              END
325              }
326
327       2.  msg_ambiguous_cmd()
328
329           Called when the user has entered a command for which more than
330           handler exists.  (For example, if both "quit" and "query" are
331           commands, then "qu" is an ambiguous command, because it could be
332           either.) It receives the object, the command, and the possible
333           commands which could complete it. It should return an error
334           message; by default it is defined thusly:
335
336              sub msg_ambiguous_cmd {
337                  my ($o, $cmd, @c) = @_;
338                  local $" = "\n\t";
339                  <<END;
340              Ambiguous command '$cmd': possible commands:
341                      @c
342              END
343              }
344

The Term::Shell API

346       Shell classes can use any of the methods in this list. Any other
347       methods in Term::Shell may change.
348
349       1.  new()
350
351           Creates a new Term::Shell object. It currently does not use its
352           arguments. The arguments are saved in '$o->{API}{args}', in case
353           you want to use them later.
354
355              my $sh = Term::Shell->new(@arbitrary_args);
356
357       2.  cmd()
358
359              cmd($txt);
360
361           Invokes $txt as if it had been typed in at the prompt.
362
363              $sh->cmd("echo 1 2 3");
364
365       3.  cmdloop()
366
367           mainloop()
368
369           Repeatedly prompts the user, reads a line, parses it, and invokes a
370           handler.  Uses "cmd()" internally.
371
372              MyShell->new->cmdloop;
373
374           mainloop() is a synonym for cmdloop(), provided for backwards
375           compatibility.  Earlier (unreleased) versions of Term::Shell have
376           only provided mainloop().  All documentation and examples use
377           cmdloop() instead.
378
379       4.  init()
380
381           fini()
382
383           Do any initialization or cleanup you need at shell creation
384           (init()) and destruction (fini()) by defining these methods.
385
386           No parameters are passed.
387
388       5.  preloop()
389
390           postloop()
391
392           Do any initialization or cleanup you need at shell startup
393           (preloop()) and shutdown (postloop()) by defining these methods.
394
395           No parameters are passed.
396
397       6.  precmd()
398
399           postcmd()
400
401           Do any initialization or cleanup before and after calling each
402           handler.
403
404           The parameters are:
405
406           1.  $handler
407
408               A reference to the name of the handler that is about to be
409               executed.
410
411               Passed by reference so you can control which handler will be
412               called.
413
414           2.  $cmd
415
416               A reference to the command as the user typed it.
417
418               Passed by reference so you can set the command. (If the handler
419               is a "catch_" command, it can be fooled into thinking the user
420               typed some other command, for example.)
421
422           3.  $args
423
424               The arguments as typed by the user. This is passed as an array
425               reference so that you can manipulate the arguments received by
426               the handler.
427
428              sub precmd {
429                  my $o = shift;
430                  my ($handler, $cmd, @args) = @_;
431                  # ...
432              }
433
434       7.  stoploop()
435
436           Sets a flag in the Term::Shell object that breaks out of cmdloop().
437           Note that cmdloop() resets this flag each time you call it, so code
438           like this will work:
439
440              my $sh = MyShell->new;
441              $sh->cmdloop;        # an interactive session
442              $sh->cmdloop;        # prompts the user again
443
444           Term::Shell's built-in run_exit() command just calls stoploop().
445
446       8.  idle()
447
448           If you set "check_idle" to a non-zero number (see "The Term::Shell
449           Object") then this method is called every "check_idle" seconds. The
450           idle() method defined in Term::Shell does nothing -- it exists only
451           to be redefined in subclasses.
452
453              package MyShell;
454              use base qw(Term::Shell);
455
456              sub init {
457                  my $o = shift;
458                  $o->{API}{check_idle} = 0.1;     # 10/s
459              }
460
461              sub idle {
462                  print "Idle!\n";
463              }
464
465       9.  prompt_str()
466
467           Returns a string to be used as the prompt. prompt_str() is called
468           just before calling the readline() method of Term::ReadLine. If you
469           do not override this method, the string `shell> ' is used.
470
471              package MyShell;
472              use base qw(Term::Shell);
473
474              sub prompt_str { "search> " }
475
476       10. prompt()
477
478           Term::Shell provides this method for convenience. It's common for a
479           handler to ask the user for more information. This method makes it
480           easy to provide the user with a different prompt and custom
481           completions provided by you.
482
483           The prompt() method takes the following parameters:
484
485           1.  $prompt
486
487               The prompt to display to the user. This can be any string you
488               want.
489
490           2.  $default
491
492               The default value to provide. If the user enters a blank line
493               (all whitespace characters) then the this value will be
494               returned.
495
496               Note: unlike ExtUtils::MakeMaker's prompt(), Term::Shell's
497               prompt() does not modify $prompt to indicate the $default
498               response. You have to do that yourself.
499
500           3.  $completions
501
502               An optional list of completion values. When the user hits
503               <TAB>, Term::Shell prints the completions which match what
504               they've typed so far. Term::Shell does not enforce that the
505               user's response is one of these values.
506
507           4.  $casei
508
509               An optional boolean value which indicates whether the
510               completions should be matched case-insensitively or not. A true
511               value indicates that "FoO" and "foo" should be considered the
512               same.
513
514           prompt() returns the unparsed line to give you maximum flexibility.
515           If you need the line parsed, use the line_parsed() method on the
516           return value.
517
518       11. cmd_prefix()
519
520           cmd_suffix()
521
522           These methods should return a prefix and suffix for commands,
523           respectively.  For instance, an IRC client will have a prefix of
524           "/". Most shells have an empty prefix and suffix.
525
526       12. page()
527
528              page($txt)
529
530           Prints $txt through a pager, prompting the user to press a key for
531           the next screen full of text.
532
533       13. line()
534
535           line_parsed()
536
537           Although "run_foo()" is called with the parsed arguments from the
538           command-line, you may wish to see the raw command-line. This is
539           available through the line() method. If you want to retrieve the
540           parsed line again, use line_parsed().
541
542           line_parsed() accepts an optional string parameter: the line to
543           parse. If you have your own line to parse, you can pass it to
544           line_parsed() and get back a list of arguments. This is useful
545           inside completion methods, since you don't get a parsed list there.
546
547       14. run()
548
549           If you want to run another handler from within a handler, and you
550           have pre-parsed arguments, use run() instead of cmd(). cmd() parses
551           its parameter, whereas run() takes each element as a separate
552           parameter.
553
554           It needs the name of the action to run and any arguments to pass to
555           the handler.
556
557           Term::Shell uses this method internally to invoke command handlers.
558
559       15. help()
560
561           If you want to get the raw text of a help message, use help(). It
562           needs the name of the help topic and any arguments to pass to the
563           handler.
564
565           Term::Shell uses this method internally to invoke help handlers.
566
567       16. summary()
568
569           If you want to get the summary text of an action, use summary(). It
570           needs the name of the action.
571
572           Term::Shell uses this method internally to display the help page.
573
574       17. possible_actions()
575
576           You will probably want this method in comp_foo().
577           possible_actions() takes a word and a list, and returns a list of
578           possible matches. Term::Shell uses this method internally to decide
579           which handler to run when the user enters a command.
580
581           There are several arguments, but you probably won't use them all in
582           the simple cases:
583
584           1.  $needle
585
586               The (possible incomplete) word to try to match against the list
587               of actions (the haystack).
588
589           2.  $type
590
591               The type with which to prefix $action. This is useful when
592               completing a real action -- you have to specify whether you
593               want it to look for "run_" or "help_" or something else. If you
594               leave it blank, it will use $action without prefixing it.
595
596           3.  $strip
597
598               If you pass in a true value here, possible_actions() will
599               remove an initial $type from the beginning of each result
600               before returning the results. This is useful if you want to
601               know what the possible "run_" commands are, but you don't want
602               to have the "run_" in the final result.
603
604               If you do not specify this argument, it uses '0' (the default
605               is not to strip the results).
606
607           4.  $haystack
608
609               You can pass in a reference to a list of strings here. Each
610               string will be compared with $needle.
611
612               If you do not specify this argument, it uses the list of
613               handlers. This is how Term::Shell matches commands typed in by
614               the user with command handlers written by you.
615
616       18. print_pairs()
617
618           This overloaded beast is used whenever Term::Shell wants to print a
619           set of keys and values. It handles wrapping long values, indenting
620           the whole thing, inserting the separator between the key and value,
621           and all the rest.
622
623           There are lots of parameters, but most of them are optional:
624
625           1.  $keys
626
627               A reference to a list of keys to print.
628
629           2.  $values
630
631               A reference to a list of values to print.
632
633           3.  $sep
634
635               The string used to separate the keys and values. If omitted, ':
636               ' is used.
637
638           4.  $left
639
640               The justification to be used to line up the keys. If true, the
641               keys will be left-justified. If false or omitted, the keys will
642               be right-justified.
643
644           5.  $ind
645
646               A string used to indent the whole paragraph. Internally,
647               print_pairs() uses length(), so you shouldn't use tabs in the
648               indent string. If omitted, the empty string is used (no
649               indent).
650
651           6.  $len
652
653               An integer which describes the minimum length of the keys.
654               Normally, print_pairs() calculates the longest key and assigns
655               the column width to be as wide as the longest key plus the
656               separator. You can force the column width to be larger using
657               $len. If omitted, 0 is used.
658
659           7.  $wrap
660
661               A boolean which indicates whether the value should be text-
662               wrapped using Text::Autoformat. Text is only ever wrapped if it
663               contains at least one space.  If omitted, 0 is used.
664
665           8.  $cols
666
667               An integer describing the number of columns available on the
668               current terminal.  Normally 78 is used, or the environment
669               variable COLUMNS, but you can override the number here to
670               simulate a right-indent.
671
672       19. term()
673
674           Returns the underlying "Term::ReadLine" object used to interact
675           with the user. You can do powerful things with this object; in
676           particular, you will cripple Term::Shell's completion scheme if you
677           change the completion callback function.
678
679       20. process_esc()
680
681           This method may be overridden to provide shell-like escaping of
682           backslashes inside quoted strings. It accepts two parameters:
683
684           1.  $c
685
686               The character which was escaped by a backslash.
687
688           2.  $quote
689
690               The quote character used to delimit this string. Either """ or
691               "'".
692
693           This method should return the string which should replace the
694           backslash and the escaped character.
695
696           By default, process_esc() uses escaping rules similar to Perl's
697           single-quoted string:
698
699           1.  Escaped backslashes return backslashes. The string "123\\456"
700               returns "123\456".
701
702           2.  Escaped quote characters return the quote character (to allow
703               quote characters in strings). The string "abc\"def" returns
704               "abc"def".
705
706           3.  All other backslashes are returned verbatim. The string
707               "123\456" returns "123\456".
708
709           Term::Shell's quote characters cannot be overridden, unless you
710           override line_parsed(): they are """ or "'". This may change in a
711           future version of Term::Shell.
712
713       21. add_handlers()
714
715           See "Adding Commands to Your Shell" for information on
716           add_handlers().
717
718       22. remove_commands()
719
720           remove_handlers()
721
722           See "Removing Commands from Your Shell" for information on
723           remove_handlers().
724

The Term::Shell Object

726       Term::Shell creates a hash based Perl object. The object contains
727       information like what handlers it found, the underlying Term::ReadLine
728       object, and any arguments passed to the constructor.
729
730       This hash is broken into several subhashes. The only two subhashes that
731       a Shell should ever use are $o->{API} and $o->{SHELL}. The first one
732       contains all the information that Term::Shell has gathered for you. The
733       second one is a private area where your Shell can freely store data
734       that it might need later on.
735
736       This section will describe all the Term::Shell object "API" attributes:
737
738   The args Attribute
739       This an array reference containing any arguments passed to the
740       Term::Shell constructor.
741
742   The case_ignore Attribute
743       This boolean controls whether commands should be matched without regard
744       to case. If this is true, then typing "FoO" will have the same effect
745       as typing "foo".
746
747       Defaults to true on MSWin32, and false on other platforms.
748
749   The class Attribute
750       The class of the object. This is probably the package containing the
751       definition of your shell, but if someone subclasses your shell, it's
752       their class.
753
754   The command Attribute
755       Whenever Term::Shell invokes an action, it stores information about the
756       action in the "command" attribute. Information about the last "run"
757       action to be invoked is stored in $o->{API}{command}{run}. The
758       information itself is stored in a subhash containing these fields:
759
760       name
761           The name of the command, as typed by the user.
762
763       found
764           The a boolean value indicating whether a handler could be found.
765
766       handler
767           The full name of the handler, if found.
768
769       Note that this facility only stores information about the last action
770       to be executed. It's good enough for retrieving the information about
771       the last handler which ran, but not for much else.
772
773       The following example shows a case where "run_foo()" calls "run_add()",
774       and prints its return value (in this case, 42).
775
776          sub run_foo {
777              my $o = shift;
778              my $sum = $o->run("add", 21, 21);
779              print "21 + 21 = ", $sum, "\n";
780          }
781
782          sub run_add {
783              my $o = shift;
784              my $sum = 0;
785              $sum += $_ for @_;
786              print "add(): sum = $sum\n";
787              return $sum;
788          }
789
790       At the end of run_foo(), $o->{API}{command}{run}{handler} contains the
791       string "run_add".
792
793   The match_uniq Attribute
794       This boolean controls whether the user can type in only enough of the
795       command to make it unambiguous. If true, then if the shell has the
796       commands "foo" and "bar" defined, the user can type "f" to run "foo",
797       and "b" to run "bar".
798
799       Defaults to true.
800
801   The readline Attribute
802       Which Term::ReadLine module is being used. Currently, this is always
803       one of "Term::ReadLine::Stub", "Term::ReadLine::Perl", or
804       "Term::ReadLine::Gnu".
805
806   The script Attribute
807       The name of the script that invoked your shell.
808
809   The version Attribute
810       The version of Term::Shell you are running under.
811

BUGS AND DEFICIENCIES

813       There are bound to be some bugs lurking about.
814
815       If you find bugs, please send them to "NEILW@cpan.org".
816

SEE ALSO

818       For more information about the underlying ReadLine module, see
819       Term::ReadLine. You may also want to look at Term::ReadLine::Gnu and
820       Term::ReadLine::Perl.
821
822       For more information about the underlying formatter used by
823       print_pairs(), see Text::Autoformat.
824
825       The API for Term::Shell was inspired by (gasp!) a Python package called
826       "cmd". For more information about this package, please look in the
827       Python Library Reference, either in your Python distribution or at
828       http://www.python.org/doc/current/lib/module-cmd.html
829

AUTHOR

831       Neil Watkiss (NEILW@cpan.org)
832
834       Copyright (c) 2001, Neil Watkiss. All Rights Reserved.
835
836       All Rights Reserved. This module is free software. It may be used,
837       redistributed and/or modified under the same terms as Perl itself.
838
839       See http://www.perl.com/perl/misc/Artistic.html
840

POD ERRORS

842       Hey! The above document had some coding errors, which are explained
843       below:
844
845       Around line 211:
846           You forgot a '=back' before '=head2'
847
848       Around line 244:
849           =back without =over
850
851
852
853perl v5.12.1                      2007-02-23                    Term::Shell(3)
Impressum