Term::ShellUI(3pm)
π Term::ShellUI π
okay bestie, welcome to the <pink>Term::ShellUI(3pm)</pink> glow-up π«Ά β this is a User Contributed Perl Documentation page, and it's about a fully-featured, shell-like command line environment. yes, the whole vibe. sit down, grab a strawberry π, we're doing this.
β¨ NAME β¨
Term::ShellUI β a fully-featured shell-like command line environment π
β¨ SYNOPSIS β¨
use Term::ShellUI;
my $term = new Term::ShellUI(
commands => {
"cd" => {
desc => "Change to directory DIR",
maxargs => 1, args => sub { shift->complete_onlydirs(@_); },
proc => sub { chdir($_[0] || $ENV{HOME} || $ENV{LOGDIR}); },
},
"chdir" => { alias => 'cd' },
"pwd" => {
desc => "Print the current working directory",
maxargs => 0, proc => sub { system('pwd'); },
},
"quit" => {
desc => "Quit this program", maxargs => 0,
method => sub { shift->exit_requested(1); },
}},
history_file => '~/.shellui-synopsis-history',
);
print 'Using '.$term->{term}->ReadLine."\n";
$term->run();
β¨ DESCRIPTION β¨
so Term::ShellUI is lowkey iconic: it takes the history and autocompletion features of Term::ReadLine and serves you a sophisticated command-line interface to your user. the way it works is it tries to make every single feature you'd expect from a fully interactive shell β¨trivialβ¨ to implement. you literally just declare your command set and let ShellUI do the heavy lifting. main character energy fr fr π
fun fact: this module used to be called Term::GDBUI. glow-up era. π
πΈ COMMAND SET πΈ
a command set is the data structure that describes your application's entire user interface. it's easiest to show you with a working example, so let's implement the following 6 <pink>COMMAND</pink>s:
helpβ prints the help for the given command. with no arguments, prints a list and short summary of all available commands.hβ this is just a synonym forhelp. we do NOT want it showing up in the possible completions. ofc, pressingh<tab><return>will autocomplete tohelpand then execute the help command. including this command just lets you typeh<return>and be done. slay.
thealiasdirective used to be calledsyn(for synonym). either term works. no cap. π
existsβ shows you how to use thecomplete_filesroutines to complete on file names, and how to provide more comprehensive help. she's thorough πshowβ demonstrates subcommands (like GDB's show command). this makes it easy to implement commands likeshow warrantyandshow args.show argsβ this one shows more advanced argument processing. first, it uses custom argument completion: a static completion for the first argument (eithercreateordelete) and the standard file completion for the second. when executed, it echoes its own command name followed by its arguments. iconic behavior β¨quitβ how to nicely quit. Term::ShellUI also follows Term::ReadLine's default of quitting when Control-D is pressed.
this code is fairly comprehensive because it attempts to demonstrate most of Term::ShellUI's many features. you can find a working version of this exact code titled synopsis in the examples directory. for a more real-world example, see the fileman-example in the same directory. π¦
sub get_commands
{
return {
"help" => {
desc => "Print helpful information",
args => sub { shift->help_args(undef, @_); },
method => sub { shift->help_call(undef, @_); }
},
"h" => { alias => "help", exclude_from_completion=>1},
"exists" => {
desc => "List whether files exist",
args => sub { shift->complete_files(@_); },
proc => sub {
print "exists: " .
join(", ", map {-e($_) ? "<$_>":$_} @_) .
"\n";
},
doc => <<EOL,
Comprehensive documentation for our ls command.
If a file exists, it is printed in <angle brackets>.
The help can\nspan\nmany\nlines
EOL
},
"show" => {
desc => "An example of using subcommands",
cmds => {
"warranty" => { proc => "You have no warranty!\n" },
"args" => {
minargs => 2, maxargs => 2,
args => [ sub {qw(create delete)},
\&Term::ShellUI::complete_files ],
desc => "Demonstrate method calling",
method => sub {
my $self = shift;
my $parms = shift;
print $self->get_cname($parms->{cname}) .
": " . join(" ",@_), "\n";
},
},
},
},
"quit" => {
desc => "Quit using Fileman",
maxargs => 0,
method => sub { shift->exit_requested(1); }
},
"q" => { alias => 'quit', exclude_from_completion => 1 },
};
}
π COMMAND π
this data structure describes a single command implemented by your application. help, exit, etc. every single field is optional bestie, no pressure. commands get passed to Term::ShellUI using a COMMAND SET.
descβ a short, one-line description for the command. normally this is a simple string, but it may also be a subroutine that gets called every time the description is printed. the subroutine takes two arguments,$self(the Term::ShellUI object) and$cmd(the command hash for the command), and returns the command's description as a string.docβ a comprehensive, many-line description for the command. likedesc, this is normally a string, but if you store a reference to a subroutine in this field, it'll be called to calculate the documentation. your subroutine should accept three arguments:self(the Term::ShellUI object),cmd(the command hash for the command), and the command's name. it should return a string containing the command's documentation. seeexamples/xmlexerto see how to read the doc for a command out of the pod. πminargs,maxargsβ these set the minimum and maximum number of arguments that this command will accept.procβ this contains a reference to the subroutine that should be executed when this command is called. arguments are those passed on the command line, and the return value is the value returned bycall_cmdandprocess_a_cmd(i.e. it's ignored unless your application makes use of it).
if this field is a string instead of a subroutine ref, the string gets printed when the command is executed (good for things like "Not implemented yet"). examples of both subroutine and string procs can be seen in the example above. π
methodβ similar toproc, but passes more arguments. whereprocsimply passes the arguments for the command,methodalso passes the Term::ShellUI object and the command's parms object (see"call_cmd"for more on parms). most commands can be implemented entirely using a simple proc procedure, but sometimes they need that extra info supplied to the method. likeproc,methodmay also be a string.argsβ this tells how to complete the command's arguments. it's usually a subroutine. see"complete_files"for a reasonably simple example, and the"complete"routine for a description of the arguments and cmpl data structure.
args can also be an arrayref. each position in the array will be used as the corresponding argument. see "show args" in get_commands above for an example. the last argument is repeated indefinitely (see "maxargs" for how to limit this). π₯
finally, args can also be a string. the string is intended to be a reminder and is printed whenever the user types tab twice (i.e. "a number between 0 and 65536"). it does not affect completion at all.
cmdsβ command sets can be recursive π. this allows a command to have subcommands (like GDB's info and show commands, and the show command in the example above). a command that has subcommands should only have two fields:cmds(of course), anddesc(briefly describe this collection of subcommands). it may also implementdoc, but ShellUI's default behavior of printing a summary of the command's subcommands is usually sufficient. any other fields (args,method,maxargs, etc) will be taken from the subcommand.exclude_from_completionβ if this field exists, then the command will be excluded from command-line completion. this is useful for one-letter abbreviations, such as"h"->"help": including"h"in the completions just clutters up the screen. keep it clean bestie β¨exclude_from_historyβ if this field exists, the command will never be stored in history. this is useful for commands like help and quit.
π Default Command π
if your command set includes a command named '' (the empty string), this pseudo-command will be called any time the actual command cannot be found. here's an example:
'' => {
proc => "HA ha. No command here by that name\n",
desc => "HA ha. No help for unknown commands.",
doc => "Yet more taunting...\n",
},
note thatminargsandmaxargsfor the default command are ignored.methodandprocwill be called no matter how many arguments the user entered. π
π CATEGORIES π
normally, when the user types 'help', she receives a short summary of all the commands in the command set. however, if your application has 30 or more commands, this can result in information overload π. to manage this, you can organize your commands into help categories. periodt.
all help categories are assembled into a hash and passed to the default help_call and "help_args" methods. if you don't want to use help categories, simply pass undef for the categories.
here is an example of how to declare a collection of help categories:
my $helpcats = {
breakpoints => {
desc => "Commands to halt the program",
cmds => qw(break tbreak delete disable enable),
},
data => {
desc => "Commands to examine data",
cmds => ['info', 'show warranty', 'show args'],
}
};
"show warranty" and "show args" on the last line above are examples of how to include subcommands in a help category: separate the command and subcommands with whitespace. π¦
β¨ CALLBACKS β¨
okay so bestie, callbacks are these little functions that ShellUI hands you but you're the one who calls them from your app. they do the classic stuff β help, history, all that. think of them as the pre-made snacks in the fridge. π
help_call(cats, parms, topic)β call this to make your help routine actually work. you pass in the help categories (orundef), then the command-line arguments:
"help" => { desc => "Print helpful information",
args => sub { shift->help_args($helpcats, @_); },
method => sub { shift->help_call($helpcats, @_); } },
help_argsβ this one handles argument completion for your help commands. check the example right above for how you're supposed to call it. πcomplete_filesβ completes on filesystem stuff (files, dirs, whatever's there). you can use it either like
args => sub { shift->complete_files(@_) },
or like
args => \&complete_files,
it starts you off in the current directory, no cap.
complete_onlyfilesβ same energy ascomplete_filesbut it excludes directories, device nodes, etc. regular files only, periodt.complete_onlydirsβ again likecomplete_files, except this time it kicks out files, device nodes, etc. dirs only. heads up though: it does hand you the.and..special directories, so you gotta strip those yourself if you don't wanna see them:
args = sub { grep { !/^\.?\.$/ } complete_onlydirs(@_) },
history_callβ use this callback to get the standard bash history command in your app. it supports:
NUM display last N history items
(displays all history if N is omitted)
-c clear all history
-d NUM delete an item from the history
drop it into your command set kinda like this:
"history" => { desc => "Prints the command history",
doc => "Specify a number to list the last N lines of history" .
"Pass -c to clear the command history, " .
"-d NUM to delete a single item\n",
args => "[-c] [-d] [number]",
method => sub { shift->history_call(@_) },
},
πΈ METHODS πΈ
these are the routines your app calls to build and drive a Term::ShellUI object. most of the time you literally just call new() and then run() β everything else handles itself, bestie. the rest of this section is only for when you wanna do something β¨out of the ordinaryβ¨.
π«Ά new Term::ShellUI("named args...")
makes you a brand new ShellUI object. it takes these named params:
appβ the name of your application. this gets passed along tonewover inTerm::ReadLine. defaults to$0, which is the name of the current executable. iconic default tbh.termβ normally Term::ShellUI just makes its ownTerm::ReadLineobject (created withnew Term::ReadLine $args{'app'}). but if you wanna build your own Term::ReadLine object, go off β just hand it over with thetermargument.blank_repeats_cmdβ this tells Term::ShellUI what to do when the user hits enter on a blank line. pass0(that's the default) and it does absolutely nothing, just like Bash. pass1and it repeats the last command, just like GDB. pick your fighter. πcommandsβ a hashref of every command ShellUI will respond to. the format of that data structure lives below in the command set docs. if you don't give the constructor any commands, you have to call thecommandsmethod and supply at least a minimal command set before a bunch of the calls below will work. also you can add, delete, or swap out the entire command set whenever you want. no rules. πhistory_fileβ if you define this, your command history gets saved to this file on exit. probably should point at a dotfile in the user's home dir. tilde expansion happens, so something like~/.myprog-historyis completely acceptable.history_max = 500β tells it how many items to save into the history file. default is500.
lowkey important: this param does not touch your in-memory history. Term::ShellUI makes no attempt to cull history, so you're at the mercy of whatever default your ReadLine library ships with. see StifleHistory in Term::ReadLine::Gnu if you wanna change that.
keep_quotesβ normally every unescaped, unnecessary quote mark gets stripped. but if you passkeep_quotes=>1, they stay. this is useful if your app uses quotes to delimit stuff like Perl-style strings. πbackslash_continues_commandβ normally commands don't respect backslash continuation. if you passbackslash_continues_command=>1tonew, then any line ending in a backslash makes Term::ShellUI keep reading. the backslash gets swapped for a space, so
$ abc \
> def
will give you the command string 'abc def'.
promptβ the prompt that shows up for every request. you can change it anytime with thepromptmethod. default is"$0 "(seeappabove).
if you hand it a code reference, the coderef runs and whatever it returns becomes the prompt. two arguments get passed to that coderef: the Term::ShellUI object, and the raw command. the raw command is always "" unless you're using command completion β in that case the raw command is the command line entered so far.
for example, this line sets the prompt to "## > " where ## is the current number of history items:
$term->prompt(sub { $term->{term}->GetHistory() . " > " });
if you hand it an arrayref, the first item is the normal prompt and the second item is the prompt used while a command is being continued. like, this would emulate Bash's behavior ($ is the normal prompt, > is the continuation prompt):
$term->prompt(['$', '>']);
and obviously you'd pass backslash_continues_command=>1 to new to actually make commands continue.
and, obviously, you can use an array of procs too:
$term->prompt([sub {'$'}, sub {'<'}]);
token_charsβ this argument says which characters count as tokens all by themselves. so if I passtoken_chars=>'=', then'ab=123'gets parsed into('ab', '=', '123'). withouttoken_chars,'ab=123'stays one single string.
β οΈ NOTE: you cannot changetoken_charsafter the constructor has been called! the regexps that use it are compiled once (m//o). so decide early, bestie.
display_summary_in_helpβ usually it's easier to print the command's summary (desc) first and then follow it with the documentation (doc). but if the doc already contains its description (say, you're reading it from a podfile), you don't want the summary sitting up there too. pass0to stop printingdescabovedoc. defaults to1.
π process_a_cmd([cmd])
runs the command you give it, or prompts for one if you don't pass any arguments. returns the result, or undef if no command got called.
π run()
the main loop. it processes commands until somebody calls exit_requested(true). πββοΈ
if you pass arguments, they get joined together and run once. so like, $term->run(@ARGV) lets your program run either interactively or noninteractively:
myshell helpβ runs the help command and exits.myshellβ kicks off an interactive Term::ShellUI.
π prompt(newprompt)
if you give it an argument, this method sets the command-line prompt. returns the old prompt.
π commands(newcmds)
if you give it an argument, it sets the current command set. you can use this to swap the whole command set whenever you feel like it. returns the old command set.
π add_commands(newcmds)
takes a command set as its first argument and adds every command in it to the current command set. it silently replaces any commands with the same name. no drama, no warning, just replacement. π
π exit_requested(exitflag)
if you give it an argument, it sets Term::ShellUI's finished flag to that argument (1=exit, 0=don't exit). so to make the interpreter exit once it finishes processing the current command, call $self->exit_requested(1). to cancel an exit request before the command finishes, call $self->exit_requested(0). returns the old state of the flag.
π add_eof_exit_hook(subroutine_reference)
call this method to add a subroutine as a hook into Term::ShellUI's "exit on EOF" (Ctrl-D) functionality. when a user hits Ctrl-D, Term::ShellUI calls every function in this hook list, in order, and only exits if all of them return 0. the first function to return a non-zero value stops further processing of the hooks and stops the program from exiting. π
the return value of this method is the placement of the hook routine in the hook list (1 is first), or 0 (zero) on failure.
π get_cname(cname)
a tiny little utility function that turns the cname (an array ref of names for this command, as returned by get_deep_command) into a human-readable string. this function exists purely so we do that consistently. teamwork, bestie. π«Ά
π OVERRIDES π
these routines probably already do the right thing. but if they don't? they're literally designed to be overridden. go wild.
π blank_line()
this gets called when the user inputs a blank line. it returns a string specifying the command to run, or undef if nothing should happen.
by default, ShellUI just hands you another command line. pass blank_repeats_cmd=>1 to the constructor to make ShellUI repeat the previous command instead. override this method to supply your own behavior. main character energy. β¨
π error(msg)
called when an error occurs. by default it just prints msg to stderr. override it to change that behavior. it takes any number of arguments, concatenates them all together, and prints them to stderr.
β¨ WRITING A COMPLETION ROUTINE β¨
okay so real talk bestie: Term::ReadLine makes writing a completion routine a notoriously difficult task. it's giving cursed, fr. but Term::ShellUI goes out of its way to make it as easy as possible π«Ά. the best way to write a completion routine is to start with one that already does something similar to what you want (peep the "CALLBACKS" section for the completion routines that ship with ShellUI, they're lowkey iconic).
your routine returns an arrayref of possible completions, a string containing a short but helpful note, or undef if an error prevented any completions from being generated. return an empty array if there are simply no applicable completions. be careful though β the distinction between no completions and an error can be significant π.
your routine takes two arguments: a reference to the ShellUI object and cmpl, a data structure that contains all the information you need to calculate the completions. set $term->{debug_complete}=5 to see the contents of cmpl π
:
strβ the exact string that needs completion. often, for simple completions, you don't need anything more than this.
NOTE:strdoes not respecttoken_chars! it is supplied unchanged from Readline and so uses whatever tokenizing it implements. unfortunately, if you've changedtoken_chars, this will often be different from howTerm::ShellUIwould tokenize the same string π.
csetβ command set for the deepest command found (see "get_deep_command"). if no command was found thencsetis set to the topmost command set ($self->commands()).cmdβ the command hash for deepest command found orundefif no command was found (see "get_deep_command").csetis the command set that containscmd.cnameβ the full name of deepest command found as an array of tokens (see "get_deep_command"). useget_cnameto convert this into a human-readable string π.argsβ the arguments (as a list of tokens) that should be passed to the command (see "get_deep_command"). valid only ifcmdis non-null.undefif no args were passed.argnoβ the index of the argument (inargs) containing the cursor. if the user is trying to complete on the command name, thenargnois negative (because the cursor comes before the arguments).tokensβ the tokenized command-line β¨.toknoβ the index of the token containing the cursor.tokoffβ the character offset of the cursor in the token.
for instance, if the cursor is on the first character of the third token, tokno will be 2 and tokoff will be 0.
twiceβ true if user has hit tab twice in a row. this usually means that you should print a message explaining the possible completions.
if you return your completions as a list, then $twice is handled for you automatically π. you could use it, for instance, to display an error message (using completemsg) telling why no completions could be found.
rawlineβ the command line as a string, exactly as entered by the user.rawstartβ the character position of the cursor inrawline.
the following are utility routines that your completion function can call π οΈ.
completemsg(msg)β allows your completion routine to print to the screen while completing (i.e. to offer suggestions or print debugging info β seedebug_complete). if it just blindly calls print, the prompt will be corrupted and things will be confusing until the user redraws the screen (probably by hitting Control-L) π.
$self->completemsg("You cannot complete here!\n");
note that Term::ReadLine::Perl doesn't support this so the user will always have to hit Control-L after printing. if your completion routine returns a string rather than calling completemsg() then it should work everywhere π.
suppress_completion_append_character()β when the ReadLine library finds a unique match among the list that you returned, it automatically appends a space. normally this is what you want (i.e. when completing a command name, in help, etc.) however, if you're navigating the filesystem, this is definitely not desirable (picture having to hit backspace after completing each directory, absolutely not π).
your completion function needs to call this routine every time it runs if it doesn't want a space automatically appended to the completions that it returns.
suppress_completion_escape()β normally everything returned by your completion routine is escaped so that it doesn't get destroyed by shell metacharacter interpretation (quotes, backslashes, etc). to avoid escaping twice (disastrous π), a completion routine that does its own escaping (perhaps usingText::Shellwords::Cursorparse_escape) must callsuppress_completion_escapeevery time is called.force_to_string(cmpl, commmpletions, default_quote)β if all the completions returned by your completion routine should be enclosed in single or double quotes, callforce_to_stringon them. you will most likely need this routine ifkeep_quotesis 1. this is useful when completing a construct that you know must always be quoted β¨.
force_to_string surrounds all completions with the quotes supplied by the user or, if the user didn't supply any quotes, the quote passed in default_quote. if the programmer didn't supply a default_quote and the user didn't start the token with an open quote, then force_to_string won't change anything.
here's how to use it to force strings on two possible completions, aaa and bbb. if the user doesn't supply any quotes, the completions will be surrounded by double quotes:
args => sub { shift->force_to_string(@_,['aaa','bbb'],'"') },
calling force_to_string escapes your completions (unless your callback calls suppress_completion_escape itself), then calls suppress_completion_escape to ensure the final quote isn't mangled π«Ά.
π§ INTERNALS π§
these commands are internal to ShellUI. they are documented here only for completeness β you should never need to call them, bestie, i promise.
get_deep_commandβ looks up the supplied command line in a command hash. follows all synonyms and subcommands. returnsundefif the command could not be found.
my($cset, $cmd, $cname, $args) =
$self->get_deep_command($self->commands(), $tokens);
this call takes two arguments:
csetβ this is the command set to use. pass$self->commands()unless you know exactly what you're doing π.tokensβ this is the command line that the command should be read from. it is a reference to an array that has already been split on whitespace usingText::Shellwords::Cursor::parse_line.
and it returns a list of 4 values:
cset: the deepest command set found. always returned.cmd: the command hash for the command.undefif no command was found.cname: the full name of the command. this is an array of tokens, i.e.('show', 'info'). returns as deep as it could find commands even if the final command was not found.args: the command's arguments (all remaining tokens after the command is found).
get_cset_completions(cset)β returns a list of commands from the passed command set that are suitable for completing.call_argsβ given a command set, does the correct thing at this stage in the completion (a surprisingly nontrivial task thanks to ShellUI's flexibility π ). called bycomplete().completeβ this routine figures out the command set of the completion routine that needs to be called, then callscall_args(). it is called bycompletion_function.
you should override this routine if your application has custom completion needs (like non-trivial tokenizing, where you'll need to modify the cmpl data structure). if you override this routine, you will probably need to override call_cmd as well.
completion_functionβ this is the entrypoint to the ReadLine completion callback. it sets up a bunch of data, then callscompleteto calculate the actual completion.
to watch and debug the completion process, you can set $self->{debug_complete} to 2 (print tokenizing), 3 (print tokenizing and results) or 4 (print everything including the cmpl data structure) π.
you should never need to call or override this function. if you do (but, trust me, you don't), set $self->{term}->Attribs->{completion_function} to point to your own routine.
see the Term::ReadLine documentation for a description of the arguments.
get_cmd_summary(tokens, cset)β prints a one-line summary for the given command. usesself->commands()ifcsetis not specified.get_cmd_help(tokens, cset)β prints the full help text for the given command. usesself->commands()ifcsetis not specified.get_category_summary(name, cats)β prints a one-line summary for the named category in the category hash specified incats.get_category_help(cat, cset)β returns a summary of the commands listed incat. you must pass the command set that contains those commands incset.get_all_cmd_summaries(cset)β pass it a command set, and it will return a string containing the summaries for each command in the set πΈ.load_history()β if$self->{history_file}is set (see "new"), this will load all history from that file. called byrunon startup. if you don't userun, you will need to call this command manually.save_history()β if$self->{history_file}is set (see "new"), this will save all history to that file. called byrunon shutdown. if you don't userun, you will need to call this command manually.
the history routines don't use ReadHistory and WriteHistory so they can be used even if other ReadLine libs are being used. save_history requires that the ReadLine lib supply a GetHistory call.
call_command(parms)β executes a command and returns the result. it takes a single argument: theparmsdata structure.
parms is a subset of the cmpl data structure (see the "complete(cmpl)" in complete routine for more). briefly, it contains: cset, cmd, cname, args (see "get_deep_command"), tokens and rawline (the tokenized and untokenized command lines). see complete for full descriptions of these fields.
this call should be overridden if you have exotic command processing needs π₯. if you override this routine, you will probably need to override the complete routine too.
π LICENSE π
Copyright (c) 2003-2011 Scott Bronson, all rights reserved. This program is free software released under the MIT license.
π AUTHORS π
Bestie, this page was built by a whole squad, and we're giving them their flowers:
- Scott Bronson <bronson@rinspin.com>
- Lester Hightower <hightowe@cpan.org>
- Ryan Gies <ryan@livesite.net>
- Martin Kluge <mk@elxsi.de>
Four absolute icons, one module. The way that they collaborated? Main character energy, all of them. π β¨
And that's the whole page, fr fr. π This beauty is perl v5.36.0, dated 2022-11-20, and it lives at Term::ShellUI(3pm). Go build something cute with it bestie, you got this π«Άπ¦π
π¦ where this page comes from
- debian bookworm: libterm-shellui-perl 0.92-5 Β· MIT
- debian trixie: libterm-shellui-perl 0.92-5 Β· MIT
- ubuntu noble: libterm-shellui-perl 0.92-5 Β· MIT
- ubuntu resolute: libterm-shellui-perl 0.92-5 Β· MIT
- ubuntu stonking: libterm-shellui-perl 0.92-5 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms