| 1 | # Term::ShellUI.pm | ||
| 2 | # Scott Bronson | ||
| 3 | # 3 Nov 2003 | ||
| 4 | # Covered by the MIT license. | ||
| 5 | |||
| 6 | # Makes it very easy to implement a GDB-like interface. | ||
| 7 | |||
| 8 | package Term::ShellUI; | ||
| 9 | |||
| 10 | use strict; | ||
| 11 | |||
| 12 | use Term::ReadLine (); | ||
| 13 | use Text::Shellwords::Cursor; | ||
| 14 | |||
| 15 | use vars qw($VERSION); | ||
| 16 | $VERSION = '0.92'; | ||
| 17 | |||
| 18 | |||
| 19 | =head1 NAME | ||
| 20 | |||
| 21 | Term::ShellUI - A fully-featured shell-like command line environment | ||
| 22 | |||
| 23 | =head1 SYNOPSIS | ||
| 24 | |||
| 25 | use Term::ShellUI; | ||
| 26 | my $term = new Term::ShellUI( | ||
| 27 | commands => { | ||
| 28 | "cd" => { | ||
| 29 | desc => "Change to directory DIR", | ||
| 30 | maxargs => 1, args => sub { shift->complete_onlydirs(@_); }, | ||
| 31 | proc => sub { chdir($_[0] || $ENV{HOME} || $ENV{LOGDIR}); }, | ||
| 32 | }, | ||
| 33 | "chdir" => { alias => 'cd' }, | ||
| 34 | "pwd" => { | ||
| 35 | desc => "Print the current working directory", | ||
| 36 | maxargs => 0, proc => sub { system('pwd'); }, | ||
| 37 | }, | ||
| 38 | "quit" => { | ||
| 39 | desc => "Quit this program", maxargs => 0, | ||
| 40 | method => sub { shift->exit_requested(1); }, | ||
| 41 | }}, | ||
| 42 | history_file => '~/.shellui-synopsis-history', | ||
| 43 | ); | ||
| 44 | print 'Using '.$term->{term}->ReadLine."\n"; | ||
| 45 | $term->run(); | ||
| 46 | |||
| 47 | =head1 DESCRIPTION | ||
| 48 | |||
| 49 | Term::ShellUI uses the history and autocompletion features of L<Term::ReadLine> | ||
| 50 | to present a sophisticated command-line interface to the user. It tries to | ||
| 51 | make every feature that one would expect to see in a fully interactive shell | ||
| 52 | trivial to implement. | ||
| 53 | You simply declare your command set and let ShellUI take | ||
| 54 | care of the heavy lifting. | ||
| 55 | |||
| 56 | This module was previously called L<Term::GDBUI>. | ||
| 57 | |||
| 58 | =head1 COMMAND SET | ||
| 59 | |||
| 60 | A command set is the data structure that | ||
| 61 | describes your application's entire user interface. | ||
| 62 | It's easiest to illustrate with a working example. | ||
| 63 | We shall implement the following 6 L</COMMAND>s: | ||
| 64 | |||
| 65 | =over 4 | ||
| 66 | |||
| 67 | =item help | ||
| 68 | |||
| 69 | Prints the help for the given command. | ||
| 70 | With no arguments, prints a list and short summary of all available commands. | ||
| 71 | |||
| 72 | =item h | ||
| 73 | |||
| 74 | This is just a synonym for "help". We don't want to list it in the | ||
| 75 | possible completions. | ||
| 76 | Of course, pressing "h<tab><return>" will autocomplete to "help" and | ||
| 77 | then execute the help command. Including this command allows you to | ||
| 78 | simply type "h<return>". | ||
| 79 | |||
| 80 | The 'alias' directive used to be called 'syn' (for synonym). | ||
| 81 | Either term works. | ||
| 82 | |||
| 83 | =item exists | ||
| 84 | |||
| 85 | This command shows how to use the | ||
| 86 | L</complete_files> | ||
| 87 | routines to complete on file names, | ||
| 88 | and how to provide more comprehensive help. | ||
| 89 | |||
| 90 | =item show | ||
| 91 | |||
| 92 | Demonstrates subcommands (like GDB's show command). | ||
| 93 | This makes it easy to implement commands like "show warranty" | ||
| 94 | and "show args". | ||
| 95 | |||
| 96 | =item show args | ||
| 97 | |||
| 98 | This shows more advanced argument processing. | ||
| 99 | First, it uses cusom argument completion: a static completion for the | ||
| 100 | first argument (either "create" or "delete") and the standard | ||
| 101 | file completion for the second. When executed, it echoes its own command | ||
| 102 | name followed by its arguments. | ||
| 103 | |||
| 104 | =item quit | ||
| 105 | |||
| 106 | How to nicely quit. | ||
| 107 | Term::ShellUI also follows Term::ReadLine's default of quitting | ||
| 108 | when Control-D is pressed. | ||
| 109 | |||
| 110 | =back | ||
| 111 | |||
| 112 | This code is fairly comprehensive because it attempts to | ||
| 113 | demonstrate most of Term::ShellUI's many features. You can find a working | ||
| 114 | version of this exact code titled "synopsis" in the examples directory. | ||
| 115 | For a more real-world example, see the fileman-example in the same | ||
| 116 | directory. | ||
| 117 | |||
| 118 | sub get_commands | ||
| 119 | { | ||
| 120 | return { | ||
| 121 | "help" => { | ||
| 122 | desc => "Print helpful information", | ||
| 123 | args => sub { shift->help_args(undef, @_); }, | ||
| 124 | method => sub { shift->help_call(undef, @_); } | ||
| 125 | }, | ||
| 126 | "h" => { alias => "help", exclude_from_completion=>1}, | ||
| 127 | "exists" => { | ||
| 128 | desc => "List whether files exist", | ||
| 129 | args => sub { shift->complete_files(@_); }, | ||
| 130 | proc => sub { | ||
| 131 | print "exists: " . | ||
| 132 | join(", ", map {-e($_) ? "<$_>":$_} @_) . | ||
| 133 | "\n"; | ||
| 134 | }, | ||
| 135 | doc => <<EOL, | ||
| 136 | Comprehensive documentation for our ls command. | ||
| 137 | If a file exists, it is printed in <angle brackets>. | ||
| 138 | The help can\nspan\nmany\nlines | ||
| 139 | EOL | ||
| 140 | }, | ||
| 141 | "show" => { | ||
| 142 | desc => "An example of using subcommands", | ||
| 143 | cmds => { | ||
| 144 | "warranty" => { proc => "You have no warranty!\n" }, | ||
| 145 | "args" => { | ||
| 146 | minargs => 2, maxargs => 2, | ||
| 147 | args => [ sub {qw(create delete)}, | ||
| 148 | \&Term::ShellUI::complete_files ], | ||
| 149 | desc => "Demonstrate method calling", | ||
| 150 | method => sub { | ||
| 151 | my $self = shift; | ||
| 152 | my $parms = shift; | ||
| 153 | print $self->get_cname($parms->{cname}) . | ||
| 154 | ": " . join(" ",@_), "\n"; | ||
| 155 | }, | ||
| 156 | }, | ||
| 157 | }, | ||
| 158 | }, | ||
| 159 | "quit" => { | ||
| 160 | desc => "Quit using Fileman", | ||
| 161 | maxargs => 0, | ||
| 162 | method => sub { shift->exit_requested(1); } | ||
| 163 | }, | ||
| 164 | "q" => { alias => 'quit', exclude_from_completion => 1 }, | ||
| 165 | }; | ||
| 166 | } | ||
| 167 | |||
| 168 | |||
| 169 | =head1 COMMAND | ||
| 170 | |||
| 171 | This data structure describes a single command implemented | ||
| 172 | by your application. | ||
| 173 | "help", "exit", etc. | ||
| 174 | All fields are optional. | ||
| 175 | Commands are passed to Term::ShellUI using a L</COMMAND SET>. | ||
| 176 | |||
| 177 | =over 4 | ||
| 178 | |||
| 179 | =item desc | ||
| 180 | |||
| 181 | A short, one-line description for the command. Normally this is | ||
| 182 | a simple string, but it may also be a subroutine that | ||
| 183 | will be called every time the description is printed. | ||
| 184 | The subroutine takes two arguments, $self (the Term::ShellUI object), | ||
| 185 | and $cmd (the command hash for the command), and returns the | ||
| 186 | command's description as a string. | ||
| 187 | |||
| 188 | =item doc | ||
| 189 | |||
| 190 | A comprehensive, many-line description for the command. | ||
| 191 | Like desc, this is normally a string but | ||
| 192 | if you store a reference to a subroutine in this field, | ||
| 193 | it will be called to calculate the documentation. | ||
| 194 | Your subroutine should accept three arguments: self (the Term::ShellUI object), | ||
| 195 | cmd (the command hash for the command), and the command's name. | ||
| 196 | It should return a string containing the command's documentation. | ||
| 197 | See examples/xmlexer to see how to read the doc | ||
| 198 | for a command out of the pod. | ||
| 199 | |||
| 200 | =item minargs | ||
| 201 | |||
| 202 | =item maxargs | ||
| 203 | |||
| 204 | These set the minimum and maximum number of arguments that this | ||
| 205 | command will accept. | ||
| 206 | |||
| 207 | =item proc | ||
| 208 | |||
| 209 | This contains a reference to the subroutine that should be executed | ||
| 210 | when this command is called. Arguments are those passed on the | ||
| 211 | command line and the return value is the value returned by | ||
| 212 | call_cmd and process_a_cmd (i.e. it is ignored unless your | ||
| 213 | application makes use of it). | ||
| 214 | |||
| 215 | If this field is a string instead of a subroutine ref, the string | ||
| 216 | is printed when the command is executed (good for things like | ||
| 217 | "Not implemented yet"). | ||
| 218 | Examples of both subroutine and string procs can be seen in the example | ||
| 219 | above. | ||
| 220 | |||
| 221 | =item method | ||
| 222 | |||
| 223 | Similar to proc, but passes more arguments. Where proc simply passes | ||
| 224 | the arguments for the command, method also passes the Term::ShellUI object | ||
| 225 | and the command's parms object (see L</call_cmd> | ||
| 226 | for more on parms). Most commands can be implemented entirely using | ||
| 227 | a simple proc procedure, but sometimes they require addtional information | ||
| 228 | supplied to the method. Like proc, method may also be a string. | ||
| 229 | |||
| 230 | =item args | ||
| 231 | |||
| 232 | This tells how to complete the command's arguments. It is usually | ||
| 233 | a subroutine. See L</complete_files> for an reasonably simple | ||
| 234 | example, and the L</complete> routine for a description of the | ||
| 235 | arguments and cmpl data structure. | ||
| 236 | |||
| 237 | Args can also be an arrayref. Each position in the array will be | ||
| 238 | used as the corresponding argument. | ||
| 239 | See "show args" in get_commands above for an example. | ||
| 240 | The last argument is repeated indefinitely (see L</maxargs> | ||
| 241 | for how to limit this). | ||
| 242 | |||
| 243 | Finally, args can also be a string. The string is intended to | ||
| 244 | be a reminder and is printed whenever the user types tab twice | ||
| 245 | (i.e. "a number between 0 and 65536"). | ||
| 246 | It does not affect completion at all. | ||
| 247 | |||
| 248 | =item cmds | ||
| 249 | |||
| 250 | Command sets can be recursive. This allows a command to have | ||
| 251 | subcommands (like GDB's info and show commands, and the | ||
| 252 | show command in the example above). | ||
| 253 | A command that has subcommands should only have two fields: | ||
| 254 | cmds (of course), and desc (briefly describe this collection of subcommands). | ||
| 255 | It may also implement doc, but ShellUI's default behavior of printing | ||
| 256 | a summary of the command's subcommands is usually sufficient. | ||
| 257 | Any other fields (args, method, maxargs, etc) will be taken from | ||
| 258 | the subcommand. | ||
| 259 | |||
| 260 | =item exclude_from_completion | ||
| 261 | |||
| 262 | If this field exists, then the command will be excluded from command-line | ||
| 263 | completion. This is useful for one-letter abbreviations, such as | ||
| 264 | "h"->"help": including "h" in the completions just clutters up | ||
| 265 | the screen. | ||
| 266 | |||
| 267 | =item exclude_from_history | ||
| 268 | |||
| 269 | If this field exists, the command will never be stored in history. | ||
| 270 | This is useful for commands like help and quit. | ||
| 271 | |||
| 272 | =back | ||
| 273 | |||
| 274 | =head2 Default Command | ||
| 275 | |||
| 276 | If your command set includes a command named '' (the empty | ||
| 277 | string), this pseudo-command will be called any time the actual | ||
| 278 | command cannot be found. Here's an example: | ||
| 279 | |||
| 280 | '' => { | ||
| 281 | proc => "HA ha. No command here by that name\n", | ||
| 282 | desc => "HA ha. No help for unknown commands.", | ||
| 283 | doc => "Yet more taunting...\n", | ||
| 284 | }, | ||
| 285 | |||
| 286 | Note that minargs and maxargs for the default command are ignored. | ||
| 287 | method and proc will be called no matter how many arguments the user | ||
| 288 | entered. | ||
| 289 | |||
| 290 | |||
| 291 | =head1 CATEGORIES | ||
| 292 | |||
| 293 | Normally, when the user types 'help', she receives a short | ||
| 294 | summary of all the commands in the command set. | ||
| 295 | However, if your application has 30 or more commands, this can | ||
| 296 | result in information overload. To manage this, you can organize | ||
| 297 | your commands into help categories | ||
| 298 | |||
| 299 | All help categories are assembled into a hash and passed to the | ||
| 300 | the default L<help_call> and | ||
| 301 | L</help_args> methods. If you don't | ||
| 302 | want to use help categories, simply pass undef for the categories. | ||
| 303 | |||
| 304 | Here is an example of how to declare a collection of help categories: | ||
| 305 | |||
| 306 | my $helpcats = { | ||
| 307 | breakpoints => { | ||
| 308 | desc => "Commands to halt the program", | ||
| 309 | cmds => qw(break tbreak delete disable enable), | ||
| 310 | }, | ||
| 311 | data => { | ||
| 312 | desc => "Commands to examine data", | ||
| 313 | cmds => ['info', 'show warranty', 'show args'], | ||
| 314 | } | ||
| 315 | }; | ||
| 316 | |||
| 317 | "show warranty" and "show args" on the last line above | ||
| 318 | are examples of how to include | ||
| 319 | subcommands in a help category: separate the command and | ||
| 320 | subcommands with whitespace. | ||
| 321 | |||
| 322 | =head1 CALLBACKS | ||
| 323 | |||
| 324 | Callbacks are functions supplied by ShellUI but intended to be called by | ||
| 325 | your application. | ||
| 326 | They implement common functions like 'help' and 'history'. | ||
| 327 | |||
| 328 | =over 4 | ||
| 329 | |||
| 330 | =item help_call(cats, parms, topic) | ||
| 331 | |||
| 332 | Call this routine to implement your help routine. Pass | ||
| 333 | the help categories or undef, followed by the command-line | ||
| 334 | arguments: | ||
| 335 | |||
| 336 | "help" => { desc => "Print helpful information", | ||
| 337 | args => sub { shift->help_args($helpcats, @_); }, | ||
| 338 | method => sub { shift->help_call($helpcats, @_); } }, | ||
| 339 | |||
| 340 | =cut | ||
| 341 | |||
| 342 | sub help_call | ||
| 343 | { | ||
| 344 | my $self = shift; | ||
| 345 | my $cats = shift; # help categories to use | ||
| 346 | my $parms = shift; # data block passed to methods | ||
| 347 | my $topic = $_[0]; # topics or commands to get help on | ||
| 348 | |||
| 349 | my $cset = $parms->{cset}; | ||
| 350 | my $OUT = $self->{OUT}; | ||
| 351 | |||
| 352 | if(defined($topic)) { | ||
| 353 | if(exists $cats->{$topic}) { | ||
| 354 | print $OUT $self->get_category_help($cats->{$topic}, $cset); | ||
| 355 | } else { | ||
| 356 | print $OUT $self->get_cmd_help(\@_, $cset); | ||
| 357 | } | ||
| 358 | } elsif(defined($cats)) { | ||
| 359 | # no topic -- print a list of the categories | ||
| 360 | print $OUT "\nHelp categories:\n\n"; | ||
| 361 | for(sort keys(%$cats)) { | ||
| 362 | print $OUT $self->get_category_summary($_, $cats->{$_}); | ||
| 363 | } | ||
| 364 | } else { | ||
| 365 | # no categories -- print a summary of all commands | ||
| 366 | print $OUT $self->get_all_cmd_summaries($cset); | ||
| 367 | } | ||
| 368 | } | ||
| 369 | |||
| 370 | |||
| 371 | =item help_args | ||
| 372 | |||
| 373 | This provides argument completion for help commands. | ||
| 374 | See the example above for how to call it. | ||
| 375 | |||
| 376 | =cut | ||
| 377 | |||
| 378 | sub help_args | ||
| 379 | { | ||
| 380 | my $self = shift; | ||
| 381 | my $helpcats = shift; | ||
| 382 | my $cmpl = shift; | ||
| 383 | |||
| 384 | my $args = $cmpl->{'args'}; | ||
| 385 | my $argno = $cmpl->{'argno'}; | ||
| 386 | my $cset = $cmpl->{'cset'}; | ||
| 387 | |||
| 388 | if($argno == 0) { | ||
| 389 | # return both categories and commands if we're on the first argument | ||
| 390 | return $self->get_cset_completions($cset, keys(%$helpcats)); | ||
| 391 | } | ||
| 392 | |||
| 393 | my($scset, $scmd, $scname, $sargs) = $self->get_deep_command($cset, $args); | ||
| 394 | |||
| 395 | # without this we'd complete with $scset for all further args | ||
| 396 | return [] if $argno >= @$scname; | ||
| 397 | |||
| 398 | return $self->get_cset_completions($scset); | ||
| 399 | } | ||
| 400 | |||
| 401 | |||
| 402 | |||
| 403 | =item complete_files | ||
| 404 | |||
| 405 | Completes on filesystem objects (files, directories, etc). | ||
| 406 | Use either | ||
| 407 | |||
| 408 | args => sub { shift->complete_files(@_) }, | ||
| 409 | |||
| 410 | or | ||
| 411 | |||
| 412 | args => \&complete_files, | ||
| 413 | |||
| 414 | Starts in the current directory. | ||
| 415 | |||
| 416 | =cut | ||
| 417 | |||
| 418 | sub complete_files | ||
| 419 | { | ||
| 420 | my $self = shift; | ||
| 421 | my $cmpl = shift; | ||
| 422 | |||
| 423 | $self->suppress_completion_append_character(); | ||
| 424 | |||
| 425 | use File::Spec; | ||
| 426 | my @path = File::Spec->splitdir($cmpl->{str} || "."); | ||
| 427 | my $dir = File::Spec->catdir(@path[0..$#path-1]); | ||
| 428 | |||
| 429 | # eradicate non-matches immediately (this is important if | ||
| 430 | # completing in a directory with 3000+ files) | ||
| 431 | my $file = $path[$#path]; | ||
| 432 | $file = '' unless $cmpl->{str}; | ||
| 433 | my $flen = length($file); | ||
| 434 | |||
| 435 | my @files = (); | ||
| 436 | if(opendir(DIR, length($dir) ? $dir : '.')) { | ||
| 437 | @files = grep { substr($_,0,$flen) eq $file } readdir DIR; | ||
| 438 | closedir DIR; | ||
| 439 | # eradicate dotfiles unless user's file begins with a dot | ||
| 440 | @files = grep { /^[^.]/ } @files unless $file =~ /^\./; | ||
| 441 | # reformat filenames to be exactly as user typed | ||
| 442 | @files = map { length($dir) ? ($dir eq '/' ? "/$_" : "$dir/$_") : $_ } @files; | ||
| 443 | } else { | ||
| 444 | $self->completemsg("Couldn't read dir: $!\n"); | ||
| 445 | } | ||
| 446 | |||
| 447 | return \@files; | ||
| 448 | } | ||
| 449 | |||
| 450 | |||
| 451 | =item complete_onlyfiles | ||
| 452 | |||
| 453 | Like L</complete_files"> | ||
| 454 | but excludes directories, device nodes, etc. | ||
| 455 | It returns regular files only. | ||
| 456 | |||
| 457 | =cut | ||
| 458 | |||
| 459 | sub complete_onlyfiles | ||
| 460 | { | ||
| 461 | my $self = shift; | ||
| 462 | |||
| 463 | # need to do our own escaping because we want to add a space ourselves | ||
| 464 | $self->suppress_completion_escape(); | ||
| 465 | my @c = grep { -f || -d } @{$self->complete_files(@_)}; | ||
| 466 | $self->{parser}->parse_escape(\@c); | ||
| 467 | # append a space if we've completed a unique file | ||
| 468 | $c[0] .= (-f($c[0]) ? ' ' : '') if @c == 1; | ||
| 469 | # append a helpful slash to indicate directories | ||
| 470 | @c = map { -d($_) ? "$_/" : $_ } @c; | ||
| 471 | return \@c; | ||
| 472 | } | ||
| 473 | |||
| 474 | |||
| 475 | =item complete_onlydirs | ||
| 476 | |||
| 477 | Like L</complete_files">, | ||
| 478 | but excludes files, device nodes, etc. | ||
| 479 | It returns only directories. | ||
| 480 | It I<does> return the . and .. special directories so you'll need | ||
| 481 | to remove those manually if you don't want to see them: | ||
| 482 | |||
| 483 | args = sub { grep { !/^\.?\.$/ } complete_onlydirs(@_) }, | ||
| 484 | |||
| 485 | =cut | ||
| 486 | |||
| 487 | sub complete_onlydirs | ||
| 488 | { | ||
| 489 | my $self = shift; | ||
| 490 | my @c = grep { -d } @{$self->complete_files(@_)}; | ||
| 491 | $c[0] .= '/' if @c == 1; # add a slash if it's a unique match | ||
| 492 | return \@c; | ||
| 493 | } | ||
| 494 | |||
| 495 | |||
| 496 | =item history_call | ||
| 497 | |||
| 498 | You can use this callback to implement the standard bash | ||
| 499 | history command. This command supports: | ||
| 500 | |||
| 501 | NUM display last N history items | ||
| 502 | (displays all history if N is omitted) | ||
| 503 | -c clear all history | ||
| 504 | -d NUM delete an item from the history | ||
| 505 | |||
| 506 | Add it to your command set using something like this: | ||
| 507 | |||
| 508 | "history" => { desc => "Prints the command history", | ||
| 509 | doc => "Specify a number to list the last N lines of history" . | ||
| 510 | "Pass -c to clear the command history, " . | ||
| 511 | "-d NUM to delete a single item\n", | ||
| 512 | args => "[-c] [-d] [number]", | ||
| 513 | method => sub { shift->history_call(@_) }, | ||
| 514 | }, | ||
| 515 | |||
| 516 | =cut | ||
| 517 | |||
| 518 | sub history_call | ||
| 519 | { | ||
| 520 | my $self = shift; | ||
| 521 | my $parms = shift; | ||
| 522 | my $arg = shift; | ||
| 523 | |||
| 524 | # clear history? | ||
| 525 | if($arg && $arg eq '-c') { | ||
| 526 | $self->{term}->clear_history(); | ||
| 527 | return; | ||
| 528 | } | ||
| 529 | if($arg && $arg eq '-d') { | ||
| 530 | @_ or die "Need the indexes of the items to delete.\n"; | ||
| 531 | for(@_) { | ||
| 532 | /^\d+$/ or die "'$_' needs to be numeric.\n"; | ||
| 533 | # function is autoloaded so we can't use can('remove_history') | ||
| 534 | # to see if it exists. So, we'll eval it and pray... | ||
| 535 | eval { $self->{term}->remove_history($_); } | ||
| 536 | } | ||
| 537 | return; | ||
| 538 | } | ||
| 539 | |||
| 540 | # number of lines to print (push maximum onto args if no arg supplied) | ||
| 541 | my $num = -1; | ||
| 542 | if($arg && $arg =~ /^(\d+)$/) { | ||
| 543 | $num = $1; | ||
| 544 | $arg = undef; | ||
| 545 | } | ||
| 546 | push @_, $arg if $arg; | ||
| 547 | |||
| 548 | die "Unknown argument" . (@_==1?'':'s') . ": '" . | ||
| 549 | join("', '", @_) . "'\n" if @_; | ||
| 550 | |||
| 551 | die "Your readline lib doesn't support history!\n" | ||
| 552 | unless $self->{term}->can('GetHistory'); | ||
| 553 | |||
| 554 | # argh, this has evolved badly... seems to work though. | ||
| 555 | my @history = $self->{term}->GetHistory(); | ||
| 556 | my $where = @history; | ||
| 557 | $num = @history if $num == -1 || $num > @history; | ||
| 558 | @history = @history[@history-$num..$#history]; | ||
| 559 | $where = $self->{term}->where_history() | ||
| 560 | if $self->{term}->can('where_history'); | ||
| 561 | my $i = $where - @history; | ||
| 562 | for(@history) { | ||
| 563 | print "$i: $_\n"; | ||
| 564 | $i += 1; | ||
| 565 | } | ||
| 566 | } | ||
| 567 | |||
| 568 | |||
| 569 | =back | ||
| 570 | |||
| 571 | =head1 METHODS | ||
| 572 | |||
| 573 | These are the routines that your application calls to create | ||
| 574 | and use a Term::ShellUI object. | ||
| 575 | Usually you simply call new() and then run() -- everything else | ||
| 576 | is handled automatically. | ||
| 577 | You only need to read this section if you wanted to do something out | ||
| 578 | of the ordinary. | ||
| 579 | |||
| 580 | =over 4 | ||
| 581 | |||
| 582 | =item new Term::ShellUI(I<C<named args...>>) | ||
| 583 | |||
| 584 | Creates a new ShellUI object. | ||
| 585 | |||
| 586 | It accepts the following named parameters: | ||
| 587 | |||
| 588 | =over 3 | ||
| 589 | |||
| 590 | =item app | ||
| 591 | |||
| 592 | The name of this application (will be passed to L<Term::ReadLine/new>). | ||
| 593 | Defaults to $0, the name of the current executable. | ||
| 594 | |||
| 595 | =item term | ||
| 596 | |||
| 597 | Usually Term::ShellUI uses its own Term::ReadLine object | ||
| 598 | (created with C<new Term::ReadLine $args{'app'}>). However, if | ||
| 599 | you can create a new Term::ReadLine object yourself and | ||
| 600 | supply it using the term argument. | ||
| 601 | |||
| 602 | =item blank_repeats_cmd | ||
| 603 | |||
| 604 | This tells Term::ShellUI what to do when the user enters a blank | ||
| 605 | line. Pass 0 (the default) to have it do nothing (like Bash), | ||
| 606 | or 1 to have it repeat the last command (like GDB). | ||
| 607 | |||
| 608 | =item commands | ||
| 609 | |||
| 610 | A hashref containing all the commands that ShellUI will respond to. | ||
| 611 | The format of this data structure can be found below in the | ||
| 612 | L<command set|/"COMMAND SET"> documentation. | ||
| 613 | If you do not supply any commands to the constructor, you must call | ||
| 614 | the L</commands> method to provide at least a minimal command set before | ||
| 615 | using many of the following calls. You may add or delete commands or | ||
| 616 | even change the entire command set at any time. | ||
| 617 | |||
| 618 | =item history_file | ||
| 619 | |||
| 620 | If defined then the command history is saved to this file on exit. | ||
| 621 | It should probably specify a dotfile in the user's home directory. | ||
| 622 | Tilde expansion is performed, so something like | ||
| 623 | C<~/.myprog-history> is perfectly acceptable. | ||
| 624 | |||
| 625 | =item history_max = 500 | ||
| 626 | |||
| 627 | This tells how many items to save to the history file. | ||
| 628 | The default is 500. | ||
| 629 | |||
| 630 | Note that this parameter does not affect in-memory history. Term::ShellUI | ||
| 631 | makes no attemt to cull history so you're at the mercy | ||
| 632 | of the default of whatever ReadLine library you are using. | ||
| 633 | See L<Term::ReadLine::Gnu/StifleHistory> for one way to change this. | ||
| 634 | |||
| 635 | =item keep_quotes | ||
| 636 | |||
| 637 | Normally all unescaped, unnecessary quote marks are stripped. | ||
| 638 | If you specify C<keep_quotes=E<gt>1>, however, they are preserved. | ||
| 639 | This is useful if your application uses quotes to delimit, say, | ||
| 640 | Perl-style strings. | ||
| 641 | |||
| 642 | =item backslash_continues_command | ||
| 643 | |||
| 644 | Normally commands don't respect backslash continuation. If you | ||
| 645 | pass backslash_continues_command=>1 to L</new>, then whenever a line | ||
| 646 | ends with a backslash, Term::ShellUI will continue reading. The backslash | ||
| 647 | is replaced with a space, so | ||
| 648 | $ abc \ | ||
| 649 | > def | ||
| 650 | |||
| 651 | Will produce the command string 'abc def'. | ||
| 652 | |||
| 653 | =item prompt | ||
| 654 | |||
| 655 | This is the prompt that should be displayed for every request. | ||
| 656 | It can be changed at any time using the L</prompt> method. | ||
| 657 | The default is S<<"$0> ">> (see L<app> above). | ||
| 658 | |||
| 659 | If you specify a code reference, then the coderef is executed and | ||
| 660 | its return value is set as the prompt. Two arguments are passed | ||
| 661 | to the coderef: the Term::ShellUI object, and the raw command. | ||
| 662 | The raw command is always "" unless you're using command completion, | ||
| 663 | where the raw command is the command line entered so far. | ||
| 664 | |||
| 665 | For example, the following | ||
| 666 | line sets the prompt to "## > " where ## is the current number of history | ||
| 667 | items. | ||
| 668 | |||
| 669 | $term->prompt(sub { $term->{term}->GetHistory() . " > " }); | ||
| 670 | |||
| 671 | If you specify an arrayref, then the first item is the normal prompt | ||
| 672 | and the second item is the prompt when the command is being continued. | ||
| 673 | For instance, this would emulate Bash's behavior ($ is the normal | ||
| 674 | prompt, but > is the prompt when continuing). | ||
| 675 | |||
| 676 | $term->prompt(['$', '>']); | ||
| 677 | |||
| 678 | Of course, you specify backslash_continues_command=>1 to to L</new> to cause | ||
| 679 | commands to continue. | ||
| 680 | |||
| 681 | And, of course, you can use an array of procs too. | ||
| 682 | |||
| 683 | $term->prompt([sub {'$'}, sub {'<'}]); | ||
| 684 | |||
| 685 | =item token_chars | ||
| 686 | |||
| 687 | This argument specifies the characters that should be considered | ||
| 688 | tokens all by themselves. For instance, if I pass | ||
| 689 | token_chars=>'=', then 'ab=123' would be parsed to ('ab', '=', '123'). | ||
| 690 | Without token_chars, 'ab=123' remains a single string. | ||
| 691 | |||
| 692 | NOTE: you cannot change token_chars after the constructor has been | ||
| 693 | called! The regexps that use it are compiled once (m//o). | ||
| 694 | |||
| 695 | =item display_summary_in_help | ||
| 696 | |||
| 697 | Usually it's easier to have the command's summary (desc) printed first, | ||
| 698 | then follow it with the documentation (doc). However, if the doc | ||
| 699 | already contains its description (for instance, if you're reading it | ||
| 700 | from a podfile), you don't want the summary up there too. Pass 0 | ||
| 701 | to prevent printing the desc above the doc. Defaults to 1. | ||
| 702 | |||
| 703 | =back | ||
| 704 | |||
| 705 | =cut | ||
| 706 | |||
| 707 | sub new | ||
| 708 | { | ||
| 709 | my $type = shift; | ||
| 710 | my %args = ( | ||
| 711 | app => $0, | ||
| 712 | prompt => "$0> ", | ||
| 713 | commands => undef, | ||
| 714 | blank_repeats_cmd => 0, | ||
| 715 | backslash_continues_command => 0, | ||
| 716 | history_file => undef, | ||
| 717 | history_max => 500, | ||
| 718 | token_chars => '', | ||
| 719 | keep_quotes => 0, | ||
| 720 | debug_complete => 0, | ||
| 721 | display_summary_in_help => 1, | ||
| 722 | @_ | ||
| 723 | ); | ||
| 724 | |||
| 725 | my $self = {}; | ||
| 726 | bless $self, $type; | ||
| 727 | |||
| 728 | $self->{done} = 0; | ||
| 729 | |||
| 730 | $self->{parser} = Text::Shellwords::Cursor->new( | ||
| 731 | token_chars => $args{token_chars}, | ||
| 732 | keep_quotes => $args{keep_quotes}, | ||
| 733 | debug => 0, | ||
| 734 | error => sub { shift; $self->error(@_); }, | ||
| 735 | ); | ||
| 736 | |||
| 737 | # expand tildes in the history file | ||
| 738 | if($args{history_file}) { | ||
| 739 | $args{history_file} =~ s/^~([^\/]*)/$1?(getpwnam($1))[7]: | ||
| 740 | $ENV{HOME}||$ENV{LOGDIR}||(getpwuid($>))[7]/e; | ||
| 741 | } | ||
| 742 | |||
| 743 | for(keys %args) { | ||
| 744 | next if $_ eq 'app'; # this param is not a member | ||
| 745 | $self->{$_} = $args{$_}; | ||
| 746 | } | ||
| 747 | |||
| 748 | $self->{term} ||= new Term::ReadLine($args{'app'}); | ||
| 749 | $self->{term}->MinLine(0); # manually call AddHistory | ||
| 750 | |||
| 751 | my $attrs = $self->{term}->Attribs; | ||
| 752 | # there appear to be catastrophic bugs with history_word_delimiters | ||
| 753 | # it goes into an infinite loop when =,[] are in token_chars | ||
| 754 | # $attrs->{history_word_delimiters} = " \t\n".$self->{token_chars}; | ||
| 755 | $attrs->{completion_function} = sub { completion_function($self, @_); }; | ||
| 756 | |||
| 757 | $self->{OUT} = $self->{term}->OUT || \*STDOUT; | ||
| 758 | $self->{prevcmd} = ""; # cmd to run again if user hits return | ||
| 759 | |||
| 760 | @{$self->{eof_exit_hooks}} = (); | ||
| 761 | |||
| 762 | return $self; | ||
| 763 | } | ||
| 764 | |||
| 765 | |||
| 766 | =item process_a_cmd([cmd]) | ||
| 767 | |||
| 768 | Runs the specified command or prompts for it if no arguments are supplied. | ||
| 769 | Returns the result or undef if no command was called. | ||
| 770 | |||
| 771 | =cut | ||
| 772 | |||
| 773 | sub process_a_cmd | ||
| 774 | { | ||
| 775 | my ($self, $incmd) = @_; | ||
| 776 | |||
| 777 | $self->{completeline} = ""; | ||
| 778 | my $OUT = $self->{'OUT'}; | ||
| 779 | |||
| 780 | my $rawline = ""; | ||
| 781 | if($incmd) { | ||
| 782 | $rawline = $incmd; | ||
| 783 | } else { | ||
| 784 | INPUT_LOOP: for(;;) { | ||
| 785 | my $prompt = $self->prompt(); | ||
| 786 | $prompt = $prompt->[length $rawline ? 1 : 0] if ref $prompt eq 'ARRAY'; | ||
| 787 | $prompt = $prompt->($self, $rawline) if ref $prompt eq 'CODE'; | ||
| 788 | my $newline = $self->{term}->readline($prompt); | ||
| 789 | |||
| 790 | # EOF exits | ||
| 791 | unless(defined $newline) { | ||
| 792 | # If we have eof_exit_hooks let them have a say | ||
| 793 | if(scalar(@{$self->{eof_exit_hooks}})) { | ||
| 794 | foreach my $sub (@{$self->{eof_exit_hooks}}) { | ||
| 795 | if(&$sub()) { | ||
| 796 | next INPUT_LOOP; | ||
| 797 | } | ||
| 798 | } | ||
| 799 | } | ||
| 800 | |||
| 801 | print $OUT "\n"; | ||
| 802 | $self->exit_requested(1); | ||
| 803 | return undef; | ||
| 804 | } | ||
| 805 | |||
| 806 | my $continued = ($newline =~ s/\\$//); | ||
| 807 | $rawline .= (length $rawline ? " " : "") . $newline; | ||
| 808 | last unless $self->{backslash_continues_command} && $continued; | ||
| 809 | } | ||
| 810 | } | ||
| 811 | |||
| 812 | # is it a blank line? | ||
| 813 | if($rawline =~ /^\s*$/) { | ||
| 814 | $rawline = $self->blank_line(); | ||
| 815 | return unless defined $rawline && $rawline !~ /^\s*$/; | ||
| 816 | } | ||
| 817 | |||
| 818 | my $tokens; | ||
| 819 | my $expcode = 0; | ||
| 820 | my $retval = undef; | ||
| 821 | my $str = $rawline; | ||
| 822 | my $save_to_history = 1; | ||
| 823 | |||
| 824 | ($tokens) = $self->{parser}->parse_line($rawline, messages=>1); | ||
| 825 | |||
| 826 | if(defined $tokens) { | ||
| 827 | $str = $self->{parser}->join_line($tokens); | ||
| 828 | if($expcode == 2) { | ||
| 829 | # user did an expansion that asked to be printed only | ||
| 830 | print $OUT "$str\n"; | ||
| 831 | } else { | ||
| 832 | print $OUT "$str\n" if $expcode == 1; | ||
| 833 | |||
| 834 | my($cset, $cmd, $cname, $args) = $self->get_deep_command($self->commands(), $tokens); | ||
| 835 | |||
| 836 | # this is a subset of the cmpl data structure | ||
| 837 | my $parms = { | ||
| 838 | cset => $cset, | ||
| 839 | cmd => $cmd, | ||
| 840 | cname => $cname, | ||
| 841 | args => $args, | ||
| 842 | tokens => $tokens, | ||
| 843 | rawline => $rawline, | ||
| 844 | }; | ||
| 845 | |||
| 846 | $retval = $self->call_command($parms); | ||
| 847 | |||
| 848 | if(exists $cmd->{exclude_from_history}) { | ||
| 849 | $save_to_history = 0; | ||
| 850 | } | ||
| 851 | } | ||
| 852 | } | ||
| 853 | |||
| 854 | # Add to history unless it's a dupe of the previous command. | ||
| 855 | if($save_to_history && $str ne $self->{prevcmd}) { | ||
| 856 | $self->{term}->addhistory($str); | ||
| 857 | } | ||
| 858 | $self->{prevcmd} = $str; | ||
| 859 | |||
| 860 | return $retval; | ||
| 861 | } | ||
| 862 | |||
| 863 | |||
| 864 | =item run() | ||
| 865 | |||
| 866 | The main loop. Processes all commands until someone calls | ||
| 867 | C<L</"exit_requested(exitflag)"|exit_requested>(true)>. | ||
| 868 | |||
| 869 | If you pass arguments, they are joined and run once. For | ||
| 870 | instance, $term->run(@ARGV) allows your program to be run | ||
| 871 | interactively or noninteractively: | ||
| 872 | |||
| 873 | =over | ||
| 874 | |||
| 875 | =item myshell help | ||
| 876 | |||
| 877 | Runs the help command and exits. | ||
| 878 | |||
| 879 | =item myshell | ||
| 880 | |||
| 881 | Invokes an interactive Term::ShellUI. | ||
| 882 | |||
| 883 | =back | ||
| 884 | |||
| 885 | =cut | ||
| 886 | |||
| 887 | sub run | ||
| 888 | { | ||
| 889 | my $self = shift; | ||
| 890 | my $incmd = join " ", @_; | ||
| 891 | |||
| 892 | $self->load_history(); | ||
| 893 | $self->getset('done', 0); | ||
| 894 | |||
| 895 | while(!$self->{done}) { | ||
| 896 | $self->process_a_cmd($incmd); | ||
| 897 | last if $incmd; # only loop if we're prompting for commands | ||
| 898 | } | ||
| 899 | |||
| 900 | $self->save_history(); | ||
| 901 | } | ||
| 902 | |||
| 903 | |||
| 904 | # This is a utility function that implements a getter/setter. | ||
| 905 | # Pass the field to modify for $self, and the new value for that | ||
| 906 | # field (if any) in $new. | ||
| 907 | |||
| 908 | sub getset | ||
| 909 | { | ||
| 910 | my $self = shift; | ||
| 911 | my $field = shift; | ||
| 912 | my $new = shift; # optional | ||
| 913 | |||
| 914 | my $old = $self->{$field}; | ||
| 915 | $self->{$field} = $new if defined $new; | ||
| 916 | return $old; | ||
| 917 | } | ||
| 918 | |||
| 919 | |||
| 920 | =item prompt(newprompt) | ||
| 921 | |||
| 922 | If supplied with an argument, this method sets the command-line prompt. | ||
| 923 | Returns the old prompt. | ||
| 924 | |||
| 925 | =cut | ||
| 926 | |||
| 927 | sub prompt { return shift->getset('prompt', shift); } | ||
| 928 | |||
| 929 | |||
| 930 | =item commands(newcmds) | ||
| 931 | |||
| 932 | If supplied with an argument, it sets the current command set. | ||
| 933 | This can be used to change the command set at any time. | ||
| 934 | Returns the old command set. | ||
| 935 | |||
| 936 | =cut | ||
| 937 | |||
| 938 | sub commands { return shift->getset('commands', shift); } | ||
| 939 | |||
| 940 | |||
| 941 | =item add_commands(newcmds) | ||
| 942 | |||
| 943 | Takes a command set as its first argument. | ||
| 944 | Adds all the commands in it the current command set. | ||
| 945 | It silently replaces any commands that have the same name. | ||
| 946 | |||
| 947 | =cut | ||
| 948 | |||
| 949 | sub add_commands | ||
| 950 | { | ||
| 951 | my $self = shift; | ||
| 952 | my $cmds = shift; | ||
| 953 | |||
| 954 | my $cset = $self->commands() || {}; | ||
| 955 | for (keys %$cmds) { | ||
| 956 | $cset->{$_} = $cmds->{$_}; | ||
| 957 | } | ||
| 958 | } | ||
| 959 | |||
| 960 | =item exit_requested(exitflag) | ||
| 961 | |||
| 962 | If supplied with an argument, sets Term::ShellUI's finished flag | ||
| 963 | to the argument (1=exit, 0=don't exit). So, to get the | ||
| 964 | interpreter to exit at the end of processing the current | ||
| 965 | command, call C<$self-E<gt>exit_requested(1)>. To cancel an exit | ||
| 966 | request before the command is finished, C<$self-E<gt>exit_requested(0)>. | ||
| 967 | Returns the old state of the flag. | ||
| 968 | |||
| 969 | =cut | ||
| 970 | |||
| 971 | sub exit_requested { return shift->getset('done', shift); } | ||
| 972 | |||
| 973 | =item add_eof_exit_hook(subroutine_reference) | ||
| 974 | |||
| 975 | Call this method to add a subroutine as a hook into Term::ShellUI's | ||
| 976 | "exit on EOF" (Ctrl-D) functionality. When a user enters Ctrl-D, | ||
| 977 | Term::ShellUI will call each function in this hook list, in order, | ||
| 978 | and will exit only if all of them return 0. The first function to | ||
| 979 | return a non-zero value will stop further processing of these hooks | ||
| 980 | and prevent the program from exiting. | ||
| 981 | |||
| 982 | The return value of this method is the placement of the hook routine | ||
| 983 | in the hook list (1 is first) or 0 (zero) on failure. | ||
| 984 | |||
| 985 | =cut | ||
| 986 | |||
| 987 | sub add_eof_exit_hook { | ||
| 988 | my $self = shift @_; | ||
| 989 | my $refcode = shift @_; | ||
| 990 | if(ref($refcode) eq 'CODE') { | ||
| 991 | push(@{$self->{eof_exit_hooks}}, $refcode); | ||
| 992 | return scalar @{$self->{eof_exit_hooks}}; | ||
| 993 | } | ||
| 994 | return 0; | ||
| 995 | } | ||
| 996 | |||
| 997 | =item get_cname(cname) | ||
| 998 | |||
| 999 | This is a tiny utility function that turns the cname (array ref | ||
| 1000 | of names for this command as returned by L</get_deep_command>) into | ||
| 1001 | a human-readable string. | ||
| 1002 | This function exists only to ensure that we do this consistently. | ||
| 1003 | |||
| 1004 | =cut | ||
| 1005 | |||
| 1006 | sub get_cname | ||
| 1007 | { | ||
| 1008 | my $self = shift; | ||
| 1009 | my $cname = shift; | ||
| 1010 | |||
| 1011 | return join(" ", @$cname); | ||
| 1012 | } | ||
| 1013 | |||
| 1014 | =back | ||
| 1015 | |||
| 1016 | =head1 OVERRIDES | ||
| 1017 | |||
| 1018 | These are routines that probably already do the right thing. | ||
| 1019 | If not, however, they are designed to be overridden. | ||
| 1020 | |||
| 1021 | =over | ||
| 1022 | |||
| 1023 | =item blank_line() | ||
| 1024 | |||
| 1025 | This routine is called when the user inputs a blank line. | ||
| 1026 | It returns a string specifying the command to run or | ||
| 1027 | undef if nothing should happen. | ||
| 1028 | |||
| 1029 | By default, ShellUI simply presents another command line. Pass | ||
| 1030 | C<blank_repeats_cmd=E<gt>1> to L<the constructor|/new> to get ShellUI to repeat the previous | ||
| 1031 | command. Override this method to supply your own behavior. | ||
| 1032 | |||
| 1033 | =cut | ||
| 1034 | |||
| 1035 | sub blank_line | ||
| 1036 | { | ||
| 1037 | my $self = shift; | ||
| 1038 | |||
| 1039 | if($self->{blank_repeats_cmd}) { | ||
| 1040 | my $OUT = $self->{OUT}; | ||
| 1041 | print $OUT $self->{prevcmd}, "\n"; | ||
| 1042 | return $self->{prevcmd}; | ||
| 1043 | } | ||
| 1044 | |||
| 1045 | return undef; | ||
| 1046 | } | ||
| 1047 | |||
| 1048 | |||
| 1049 | =item error(msg) | ||
| 1050 | |||
| 1051 | Called when an error occurrs. By default, the routine simply | ||
| 1052 | prints the msg to stderr. Override it to change this behavior. | ||
| 1053 | It takes any number of arguments, cocatenates them together and | ||
| 1054 | prints them to stderr. | ||
| 1055 | |||
| 1056 | =cut | ||
| 1057 | |||
| 1058 | sub error | ||
| 1059 | { | ||
| 1060 | my $self = shift; | ||
| 1061 | print STDERR @_; | ||
| 1062 | } | ||
| 1063 | |||
| 1064 | =back | ||
| 1065 | |||
| 1066 | =head1 WRITING A COMPLETION ROUTINE | ||
| 1067 | |||
| 1068 | Term::ReadLine makes writing a completion routine a | ||
| 1069 | notoriously difficult task. | ||
| 1070 | Term::ShellUI goes out of its way to make it as easy | ||
| 1071 | as possible. The best way to write a completion routine | ||
| 1072 | is to start with one that already does something similar to | ||
| 1073 | what you want (see the L</CALLBACKS> section for the completion | ||
| 1074 | routines that come with ShellUI). | ||
| 1075 | |||
| 1076 | Your routine returns an arrayref of possible completions, | ||
| 1077 | a string conaining a short but helpful note, | ||
| 1078 | or undef if an error prevented any completions from being generated. | ||
| 1079 | Return an empty array if there are simply no applicable competions. | ||
| 1080 | Be careful; the distinction between no completions and an error | ||
| 1081 | can be significant. | ||
| 1082 | |||
| 1083 | Your routine takes two arguments: a reference to the ShellUI | ||
| 1084 | object and cmpl, a data structure that contains all the information you need | ||
| 1085 | to calculate the completions. Set $term->{debug_complete}=5 | ||
| 1086 | to see the contents of cmpl: | ||
| 1087 | |||
| 1088 | =over 3 | ||
| 1089 | |||
| 1090 | =item str | ||
| 1091 | |||
| 1092 | The exact string that needs completion. Often, for simple completions, | ||
| 1093 | you don't need anything more than this. | ||
| 1094 | |||
| 1095 | NOTE: str does I<not> respect token_chars! It is supplied unchanged | ||
| 1096 | from Readline and so uses whatever tokenizing it implements. | ||
| 1097 | Unfortunately, if you've changed token_chars, this will often | ||
| 1098 | be different from how Term::ShellUI would tokenize the same string. | ||
| 1099 | |||
| 1100 | =item cset | ||
| 1101 | |||
| 1102 | Command set for the deepest command found (see L</get_deep_command>). | ||
| 1103 | If no command was found then cset is set to the topmost command | ||
| 1104 | set ($self->commands()). | ||
| 1105 | |||
| 1106 | =item cmd | ||
| 1107 | |||
| 1108 | The command hash for deepest command found or | ||
| 1109 | undef if no command was found (see L</get_deep_command>). | ||
| 1110 | cset is the command set that contains cmd. | ||
| 1111 | |||
| 1112 | =item cname | ||
| 1113 | |||
| 1114 | The full name of deepest command found as an array of tokens | ||
| 1115 | (see L</get_deep_command>). Use L</get_cname> to convert | ||
| 1116 | this into a human-readable string. | ||
| 1117 | |||
| 1118 | =item args | ||
| 1119 | |||
| 1120 | The arguments (as a list of tokens) that should be passed to the command | ||
| 1121 | (see L</get_deep_command>). Valid only if cmd is non-null. Undef if no | ||
| 1122 | args were passed. | ||
| 1123 | |||
| 1124 | =item argno | ||
| 1125 | |||
| 1126 | The index of the argument (in args) containing the cursor. | ||
| 1127 | If the user is trying to complete on the command name, then | ||
| 1128 | argno is negative (because the cursor comes before the arguments). | ||
| 1129 | |||
| 1130 | =item tokens | ||
| 1131 | |||
| 1132 | The tokenized command-line. | ||
| 1133 | |||
| 1134 | =item tokno | ||
| 1135 | |||
| 1136 | The index of the token containing the cursor. | ||
| 1137 | |||
| 1138 | =item tokoff | ||
| 1139 | |||
| 1140 | The character offset of the cursor in the token. | ||
| 1141 | |||
| 1142 | For instance, if the cursor is on the first character of the | ||
| 1143 | third token, tokno will be 2 and tokoff will be 0. | ||
| 1144 | |||
| 1145 | =item twice | ||
| 1146 | |||
| 1147 | True if user has hit tab twice in a row. This usually means that you | ||
| 1148 | should print a message explaining the possible completions. | ||
| 1149 | |||
| 1150 | If you return your completions as a list, then $twice is handled | ||
| 1151 | for you automatically. You could use it, for instance, to display | ||
| 1152 | an error message (using L<completemsg|/completemsg(msg)>) telling why no completions | ||
| 1153 | could be found. | ||
| 1154 | |||
| 1155 | =item rawline | ||
| 1156 | |||
| 1157 | The command line as a string, exactly as entered by the user. | ||
| 1158 | |||
| 1159 | =item rawstart | ||
| 1160 | |||
| 1161 | The character position of the cursor in rawline. | ||
| 1162 | |||
| 1163 | =back | ||
| 1164 | |||
| 1165 | The following are utility routines that your completion function | ||
| 1166 | can call. | ||
| 1167 | |||
| 1168 | =over | ||
| 1169 | |||
| 1170 | =item completemsg(msg) | ||
| 1171 | |||
| 1172 | Allows your completion routine to print to the screen while completing | ||
| 1173 | (i.e. to offer suggestions or print debugging info -- see debug_complete). | ||
| 1174 | If it just blindly calls print, the prompt will be corrupted and things | ||
| 1175 | will be confusing until the user redraws the screen (probably by hitting | ||
| 1176 | Control-L). | ||
| 1177 | |||
| 1178 | $self->completemsg("You cannot complete here!\n"); | ||
| 1179 | |||
| 1180 | Note that Term::ReadLine::Perl doesn't support this so the user will always | ||
| 1181 | have to hit Control-L after printing. If your completion routine returns | ||
| 1182 | a string rather than calling completemsg() then it should work everywhere. | ||
| 1183 | |||
| 1184 | =cut | ||
| 1185 | |||
| 1186 | sub completemsg | ||
| 1187 | { | ||
| 1188 | my $self = shift; | ||
| 1189 | my $msg = shift; | ||
| 1190 | |||
| 1191 | my $OUT = $self->{OUT}; | ||
| 1192 | print $OUT $msg; | ||
| 1193 | |||
| 1194 | # Now we need to tell the readline library to redraw the entire | ||
| 1195 | # command line. Term::ReadLine::Gnu offers rl_on_new_line() but, | ||
| 1196 | # because it's XS, it can't be detected using can(). | ||
| 1197 | # So, we just eval it and ignore any errors. If it doesn't exist | ||
| 1198 | # then the prompt is corrupted. Oh well, best we can do! | ||
| 1199 | eval { $self->{term}->rl_on_new_line() }; | ||
| 1200 | } | ||
| 1201 | |||
| 1202 | |||
| 1203 | =item suppress_completion_append_character() | ||
| 1204 | |||
| 1205 | When the ReadLine library finds a unique match among the list that | ||
| 1206 | you returned, it automatically appends a space. Normally this is | ||
| 1207 | what you want (i.e. when completing a command name, in help, etc.) | ||
| 1208 | However, if you're navigating the filesystem, this is definitely | ||
| 1209 | not desirable (picture having to hit backspace after completing | ||
| 1210 | each directory). | ||
| 1211 | |||
| 1212 | Your completion function needs to call this routine every time it | ||
| 1213 | runs if it doesn't want a space automatically appended to the | ||
| 1214 | completions that it returns. | ||
| 1215 | |||
| 1216 | =cut | ||
| 1217 | |||
| 1218 | sub suppress_completion_append_character | ||
| 1219 | { | ||
| 1220 | shift->{term}->Attribs->{completion_suppress_append} = 1; | ||
| 1221 | } | ||
| 1222 | |||
| 1223 | =item suppress_completion_escape() | ||
| 1224 | |||
| 1225 | Normally everything returned by your completion routine | ||
| 1226 | is escaped so that it doesn't get destroyed by shell metacharacter | ||
| 1227 | interpretation (quotes, backslashes, etc). To avoid escaping | ||
| 1228 | twice (disastrous), a completion routine that does its own escaping | ||
| 1229 | (perhaps using L<Text::Shellwords::Cursor>parse_escape) | ||
| 1230 | must call suppress_completion_escape every time is called. | ||
| 1231 | |||
| 1232 | =cut | ||
| 1233 | |||
| 1234 | sub suppress_completion_escape | ||
| 1235 | { | ||
| 1236 | shift->{suppress_completion_escape} = 1; | ||
| 1237 | } | ||
| 1238 | |||
| 1239 | |||
| 1240 | =item force_to_string(cmpl, commmpletions, default_quote) | ||
| 1241 | |||
| 1242 | If all the completions returned by your completion routine should be | ||
| 1243 | enclosed in single or double quotes, call force_to_string on them. | ||
| 1244 | You will most likely need this routine if L<keep_quotes> is 1. | ||
| 1245 | This is useful when completing a construct that you know must | ||
| 1246 | always be quoted. | ||
| 1247 | |||
| 1248 | force_to_string surrounds all completions with the quotes supplied by the user | ||
| 1249 | or, if the user didn't supply any quotes, the quote passed in default_quote. | ||
| 1250 | If the programmer didn't supply a default_quote and the user didn't start | ||
| 1251 | the token with an open quote, then force_to_string won't change anything. | ||
| 1252 | |||
| 1253 | Here's how to use it to force strings on two possible completions, | ||
| 1254 | aaa and bbb. If the user doesn't supply any quotes, the completions | ||
| 1255 | will be surrounded by double quotes. | ||
| 1256 | |||
| 1257 | args => sub { shift->force_to_string(@_,['aaa','bbb'],'"') }, | ||
| 1258 | |||
| 1259 | Calling force_to_string escapes your completions (unless your callback | ||
| 1260 | calls suppress_completion_escape itself), then calls | ||
| 1261 | suppress_completion_escape to ensure the final quote isn't mangled. | ||
| 1262 | |||
| 1263 | =cut | ||
| 1264 | |||
| 1265 | sub force_to_string | ||
| 1266 | { | ||
| 1267 | my $self = shift; | ||
| 1268 | my $cmpl = shift; | ||
| 1269 | my $results = shift; | ||
| 1270 | my $bq = shift; # optional: this is the default quote to use if none | ||
| 1271 | |||
| 1272 | my $fq = $bq; | ||
| 1273 | my $try = substr($cmpl->{rawline}, $cmpl->{rawstart}-1, 1); | ||
| 1274 | if($try eq '"' || $try eq "'") { | ||
| 1275 | $fq = ''; | ||
| 1276 | $bq = $try; | ||
| 1277 | } | ||
| 1278 | |||
| 1279 | if($bq) { | ||
| 1280 | $self->{parser}->parse_escape($results) unless $self->{suppress_completion_escape}; | ||
| 1281 | for(@$results) { | ||
| 1282 | $_ = "$fq$_$bq"; | ||
| 1283 | } | ||
| 1284 | $self->suppress_completion_escape(); | ||
| 1285 | } | ||
| 1286 | |||
| 1287 | return $results; | ||
| 1288 | } | ||
| 1289 | |||
| 1290 | =back | ||
| 1291 | |||
| 1292 | =head1 INTERNALS | ||
| 1293 | |||
| 1294 | These commands are internal to ShellUI. | ||
| 1295 | They are documented here only for completeness -- you | ||
| 1296 | should never need to call them. | ||
| 1297 | |||
| 1298 | =over | ||
| 1299 | |||
| 1300 | =item get_deep_command | ||
| 1301 | |||
| 1302 | Looks up the supplied command line in a command hash. | ||
| 1303 | Follows all synonyms and subcommands. | ||
| 1304 | Returns undef if the command could not be found. | ||
| 1305 | |||
| 1306 | my($cset, $cmd, $cname, $args) = | ||
| 1307 | $self->get_deep_command($self->commands(), $tokens); | ||
| 1308 | |||
| 1309 | This call takes two arguments: | ||
| 1310 | |||
| 1311 | =over 3 | ||
| 1312 | |||
| 1313 | =item cset | ||
| 1314 | |||
| 1315 | This is the command set to use. Pass $self->commands() | ||
| 1316 | unless you know exactly what you're doing. | ||
| 1317 | |||
| 1318 | =item tokens | ||
| 1319 | |||
| 1320 | This is the command line that the command should be read from. | ||
| 1321 | It is a reference to an array that has already been split | ||
| 1322 | on whitespace using L<Text::Shellwords::Cursor::parse_line>. | ||
| 1323 | |||
| 1324 | =back | ||
| 1325 | |||
| 1326 | and it returns a list of 4 values: | ||
| 1327 | |||
| 1328 | =over 3 | ||
| 1329 | |||
| 1330 | =item 1. | ||
| 1331 | |||
| 1332 | cset: the deepest command set found. Always returned. | ||
| 1333 | |||
| 1334 | =item 2. | ||
| 1335 | |||
| 1336 | cmd: the command hash for the command. Undef if no command was found. | ||
| 1337 | |||
| 1338 | =item 3. | ||
| 1339 | |||
| 1340 | cname: the full name of the command. This is an array of tokens, | ||
| 1341 | i.e. ('show', 'info'). Returns as deep as it could find commands | ||
| 1342 | even if the final command was not found. | ||
| 1343 | |||
| 1344 | =item 4. | ||
| 1345 | |||
| 1346 | args: the command's arguments (all remaining tokens after the | ||
| 1347 | command is found). | ||
| 1348 | |||
| 1349 | =back | ||
| 1350 | |||
| 1351 | =cut | ||
| 1352 | |||
| 1353 | sub get_deep_command | ||
| 1354 | { | ||
| 1355 | my $self = shift; | ||
| 1356 | my $cset = shift; | ||
| 1357 | my $tokens = shift; | ||
| 1358 | my $curtok = shift || 0; # points to the command name | ||
| 1359 | |||
| 1360 | #print "DBG get_deep_cmd: $#$tokens tokens: '" . join("', '", @$tokens) . "'\n"; | ||
| 1361 | #print "DBG cset: (" . join(", ", keys %$cset) . ")\n"; | ||
| 1362 | |||
| 1363 | my $name = $tokens->[$curtok]; | ||
| 1364 | |||
| 1365 | # loop through all synonyms to find the actual command | ||
| 1366 | while(exists($cset->{$name}) && ( | ||
| 1367 | exists($cset->{$name}->{'alias'}) || | ||
| 1368 | exists($cset->{$name}->{'syn'}) | ||
| 1369 | )) { | ||
| 1370 | $name = $cset->{$name}->{'alias'} || | ||
| 1371 | $cset->{$name}->{'syn'}; | ||
| 1372 | } | ||
| 1373 | |||
| 1374 | my $cmd = $cset->{$name}; | ||
| 1375 | |||
| 1376 | # update the tokens with the actual name of this command | ||
| 1377 | $tokens->[$curtok] = $name; | ||
| 1378 | |||
| 1379 | # should we recurse into subcommands? | ||
| 1380 | #print "$cmd " . exists($cmd->{'subcmds'}) . " (" . join(",", keys %$cmd) . ") $curtok < $#$tokens\n"; | ||
| 1381 | if($cmd && exists($cmd->{cmds}) && $curtok < $#$tokens) { | ||
| 1382 | #print "doing subcmd\n"; | ||
| 1383 | my $subname = $tokens->[$curtok+1]; | ||
| 1384 | my $subcmds = $cmd->{cmds}; | ||
| 1385 | return $self->get_deep_command($subcmds, $tokens, $curtok+1); | ||
| 1386 | } | ||
| 1387 | |||
| 1388 | #print "DBG splitting (" . join(",",@$tokens) . ") at curtok=$curtok\n"; | ||
| 1389 | |||
| 1390 | # split deep command name and its arguments into separate lists | ||
| 1391 | my @cname = @$tokens; | ||
| 1392 | my @args = ($#cname > $curtok ? splice(@cname, $curtok+1) : ()); | ||
| 1393 | |||
| 1394 | #print "DBG tokens (" . join(",",@$tokens) . ")\n"; | ||
| 1395 | #print "DBG cname (" . join(",",@cname) . ")\n"; | ||
| 1396 | #print "DBG args (" . join(",",@args) . ")\n"; | ||
| 1397 | |||
| 1398 | return ($cset, $cmd, \@cname, \@args); | ||
| 1399 | } | ||
| 1400 | |||
| 1401 | |||
| 1402 | =item get_cset_completions(cset) | ||
| 1403 | |||
| 1404 | Returns a list of commands from the passed command set that are suitable | ||
| 1405 | for completing. | ||
| 1406 | |||
| 1407 | =cut | ||
| 1408 | |||
| 1409 | sub get_cset_completions | ||
| 1410 | { | ||
| 1411 | my $self = shift; | ||
| 1412 | my $cset = shift; | ||
| 1413 | |||
| 1414 | # return all commands that aren't exluded from the completion | ||
| 1415 | # also exclude the default command ''. | ||
| 1416 | my @c = grep {$_ ne '' && !exists $cset->{$_}->{exclude_from_completion}} keys(%$cset); | ||
| 1417 | |||
| 1418 | return \@c; | ||
| 1419 | } | ||
| 1420 | |||
| 1421 | |||
| 1422 | =item call_args | ||
| 1423 | |||
| 1424 | Given a command set, does the correct thing at this stage in the | ||
| 1425 | completion (a surprisingly nontrivial task thanks to ShellUI's | ||
| 1426 | flexibility). Called by complete(). | ||
| 1427 | |||
| 1428 | =cut | ||
| 1429 | |||
| 1430 | sub call_args | ||
| 1431 | { | ||
| 1432 | my $self = shift; | ||
| 1433 | my $cmpl = shift; | ||
| 1434 | |||
| 1435 | my $cmd = $cmpl->{cmd}; | ||
| 1436 | |||
| 1437 | my $retval; | ||
| 1438 | if(exists($cmd->{args})) { | ||
| 1439 | if(ref($cmd->{args}) eq 'CODE') { | ||
| 1440 | $retval = eval { &{$cmd->{args}}($self, $cmpl) }; | ||
| 1441 | $self->completemsg($@) if $@; | ||
| 1442 | } elsif(ref($cmd->{args}) eq 'ARRAY') { | ||
| 1443 | # each element in array is a string describing corresponding argument | ||
| 1444 | my $args = $cmd->{args}; | ||
| 1445 | my $argno = $cmpl->{argno}; | ||
| 1446 | # repeat last arg indefinitely (use maxargs to stop) | ||
| 1447 | $argno = $#$args if $#$args < $argno; | ||
| 1448 | my $arg = $args->[$argno]; | ||
| 1449 | if(defined $arg) { | ||
| 1450 | if(ref($arg) eq 'CODE') { | ||
| 1451 | # it's a routine to call for this particular arg | ||
| 1452 | $retval = eval { &$arg($self, $cmpl) }; | ||
| 1453 | $self->completemsg($@) if $@; | ||
| 1454 | } elsif(ref($arg) eq 'ARRAY') { | ||
| 1455 | # it's an array of possible completions | ||
| 1456 | $retval = @$arg; | ||
| 1457 | } else { | ||
| 1458 | # it's a string reiminder of what this arg is meant to be | ||
| 1459 | $self->completemsg("$arg\n") if $cmpl->{twice}; | ||
| 1460 | } | ||
| 1461 | } | ||
| 1462 | } elsif(ref($cmd->{args}) eq 'HASH') { | ||
| 1463 | # not supported yet! (if ever...) | ||
| 1464 | } else { | ||
| 1465 | # this must be a string describing all arguments. | ||
| 1466 | $self->completemsg($cmd->{args} . "\n") if $cmpl->{twice}; | ||
| 1467 | } | ||
| 1468 | } | ||
| 1469 | |||
| 1470 | return $retval; | ||
| 1471 | } | ||
| 1472 | |||
| 1473 | =item complete | ||
| 1474 | |||
| 1475 | This routine figures out the command set of the completion routine | ||
| 1476 | that needs to be called, then calls call_args(). It is called | ||
| 1477 | by completion_function. | ||
| 1478 | |||
| 1479 | You should override this routine if your application has custom | ||
| 1480 | completion needs (like non-trivial tokenizing, where you'll need | ||
| 1481 | to modify the cmpl data structure). If you override | ||
| 1482 | this routine, you will probably need to override | ||
| 1483 | L<call_cmd|/call_cmd(parms)> as well. | ||
| 1484 | |||
| 1485 | =cut | ||
| 1486 | |||
| 1487 | sub complete | ||
| 1488 | { | ||
| 1489 | my $self = shift; | ||
| 1490 | my $cmpl = shift; | ||
| 1491 | |||
| 1492 | my $cset = $cmpl->{cset}; | ||
| 1493 | my $cmd = $cmpl->{cmd}; | ||
| 1494 | |||
| 1495 | my $cr; | ||
| 1496 | if($cmpl->{tokno} < @{$cmpl->{cname}}) { | ||
| 1497 | # if we're still in the command, return possible command completions | ||
| 1498 | # make sure to still call the default arg handler of course | ||
| 1499 | $cr = $self->get_cset_completions($cset); | ||
| 1500 | # fix suggested by Erick Calder | ||
| 1501 | $cr = [ grep {/^$cmpl->{str}/ && $_} @$cr ]; | ||
| 1502 | } | ||
| 1503 | |||
| 1504 | if($cr || !defined $cmd) { | ||
| 1505 | # call default argument handler if it exists | ||
| 1506 | if(exists $cset->{''}) { | ||
| 1507 | my %c2 = %$cmpl; | ||
| 1508 | $c2{cmd} = $cset->{''}; | ||
| 1509 | my $r2 = $self->call_args(\%c2); | ||
| 1510 | push @$cr, @$r2 if $r2; | ||
| 1511 | } | ||
| 1512 | return $cr; | ||
| 1513 | } | ||
| 1514 | |||
| 1515 | # don't complete if user has gone past max # of args | ||
| 1516 | return () if exists($cmd->{maxargs}) && $cmpl->{argno} >= $cmd->{maxargs}; | ||
| 1517 | |||
| 1518 | # everything checks out -- call the command's argument handler | ||
| 1519 | return $self->call_args($cmpl); | ||
| 1520 | } | ||
| 1521 | |||
| 1522 | |||
| 1523 | =item completion_function | ||
| 1524 | |||
| 1525 | This is the entrypoint to the ReadLine completion callback. | ||
| 1526 | It sets up a bunch of data, then calls L<complete|/complete(cmpl)> to calculate | ||
| 1527 | the actual completion. | ||
| 1528 | |||
| 1529 | To watch and debug the completion process, you can set $self->{debug_complete} | ||
| 1530 | to 2 (print tokenizing), 3 (print tokenizing and results) or 4 (print | ||
| 1531 | everything including the cmpl data structure). | ||
| 1532 | |||
| 1533 | Youu should never need to call or override this function. If | ||
| 1534 | you do (but, trust me, you don't), set | ||
| 1535 | $self->{term}->Attribs->{completion_function} to point to your own | ||
| 1536 | routine. | ||
| 1537 | |||
| 1538 | See the L<Term::ReadLine> documentation for a description of the arguments. | ||
| 1539 | |||
| 1540 | =cut | ||
| 1541 | |||
| 1542 | sub completion_function | ||
| 1543 | { | ||
| 1544 | my $self = shift; | ||
| 1545 | my $text = shift; # the word directly to the left of the cursor | ||
| 1546 | my $line = shift; # the entire line | ||
| 1547 | my $start = shift; # the position in the line of the beginning of $text | ||
| 1548 | |||
| 1549 | my $cursor = $start + length($text); | ||
| 1550 | |||
| 1551 | # reset the suppress_append flag | ||
| 1552 | # completion routine must set it every time it's called | ||
| 1553 | $self->{term}->Attribs->{completion_suppress_append} = 0; | ||
| 1554 | $self->{suppress_completion_escape} = 0; | ||
| 1555 | |||
| 1556 | # Twice is true if the user has hit tab twice on the same string | ||
| 1557 | my $twice = ($self->{completeline} eq $line); | ||
| 1558 | $self->{completeline} = $line; | ||
| 1559 | |||
| 1560 | my($tokens, $tokno, $tokoff) = $self->{parser}->parse_line($line, | ||
| 1561 | messages=>0, cursorpos=>$cursor, fixclosequote=>1); | ||
| 1562 | return unless defined($tokens); | ||
| 1563 | |||
| 1564 | # this just prints a whole bunch of completion/parsing debugging info | ||
| 1565 | if($self->{debug_complete} >= 1) { | ||
| 1566 | print "\ntext='$text', line='$line', start=$start, cursor=$cursor"; | ||
| 1567 | |||
| 1568 | print "\ntokens=(", join(", ", @$tokens), ") tokno=" . | ||
| 1569 | (defined($tokno) ? $tokno : 'undef') . " tokoff=" . | ||
| 1570 | (defined($tokoff) ? $tokoff : 'undef'); | ||
| 1571 | |||
| 1572 | print "\n"; | ||
| 1573 | my $str = " "; | ||
| 1574 | print "<"; | ||
| 1575 | my $i = 0; | ||
| 1576 | for(@$tokens) { | ||
| 1577 | my $s = (" " x length($_)) . " "; | ||
| 1578 | substr($s,$tokoff,1) = '^' if $i eq $tokno; | ||
| 1579 | $str .= $s; | ||
| 1580 | print $_; | ||
| 1581 | print ">"; | ||
| 1582 | $str .= " ", print ", <" if $i != $#$tokens; | ||
| 1583 | $i += 1; | ||
| 1584 | } | ||
| 1585 | $self->completemsg("\n$str\n"); | ||
| 1586 | } | ||
| 1587 | |||
| 1588 | my $str = $text; | ||
| 1589 | |||
| 1590 | my($cset, $cmd, $cname, $args) = $self->get_deep_command($self->commands(), $tokens); | ||
| 1591 | |||
| 1592 | # this structure hopefully contains everything you'll ever | ||
| 1593 | # need to easily compute a match. | ||
| 1594 | my $cmpl = { | ||
| 1595 | str => $str, # the exact string that needs completion | ||
| 1596 | # (usually, you don't need anything more than this) | ||
| 1597 | |||
| 1598 | cset => $cset, # cset of the deepest command found | ||
| 1599 | cmd => $cmd, # the deepest command or undef | ||
| 1600 | cname => $cname, # full name of deepest command | ||
| 1601 | args => $args, # anything that was determined to be an argument. | ||
| 1602 | argno => $tokno - @$cname, # the argument containing the cursor | ||
| 1603 | |||
| 1604 | tokens => $tokens, # tokenized command-line (arrayref). | ||
| 1605 | tokno => $tokno, # the index of the token containing the cursor | ||
| 1606 | tokoff => $tokoff, # the character offset of the cursor in $tokno. | ||
| 1607 | twice => $twice, # true if user has hit tab twice in a row | ||
| 1608 | |||
| 1609 | rawline => $line, # pre-tokenized command line | ||
| 1610 | rawstart => $start, # position in rawline of the start of str | ||
| 1611 | rawcursor => $cursor, # position in rawline of the cursor (end of str) | ||
| 1612 | }; | ||
| 1613 | |||
| 1614 | if($self->{debug_complete} >= 3) { | ||
| 1615 | print "tokens=(" . join(",", @$tokens) . ") tokno=$tokno tokoff=$tokoff str=$str twice=$twice\n"; | ||
| 1616 | print "cset=$cset cmd=" . (defined($cmd) ? $cmd : "(undef)") . | ||
| 1617 | " cname=(" . join(",", @$cname) . ") args=(" . join(",", @$args) . ") argno=".$cmpl->{argno}."\n"; | ||
| 1618 | print "rawline='$line' rawstart=$start rawcursor=$cursor\n"; | ||
| 1619 | } | ||
| 1620 | |||
| 1621 | my $retval = $self->complete($cmpl); | ||
| 1622 | $retval = [] unless defined($retval); | ||
| 1623 | unless(ref($retval) eq 'ARRAY') { | ||
| 1624 | $self->completemsg("$retval\n") if $cmpl->{twice}; | ||
| 1625 | $retval = []; | ||
| 1626 | } | ||
| 1627 | |||
| 1628 | if($self->{debug_complete} >= 2) { | ||
| 1629 | print "returning (", join(", ", @$retval), ")\n"; | ||
| 1630 | } | ||
| 1631 | |||
| 1632 | # escape the completions so they're valid on the command line | ||
| 1633 | $self->{parser}->parse_escape($retval) unless $self->{suppress_completion_escape}; | ||
| 1634 | |||
| 1635 | return @$retval; | ||
| 1636 | } | ||
| 1637 | |||
| 1638 | |||
| 1639 | # Converts a field name into a text string. | ||
| 1640 | # All fields can be code, if so, then they're called to return string value. | ||
| 1641 | # You need to ensure that the field exists before calling this routine. | ||
| 1642 | |||
| 1643 | sub get_field | ||
| 1644 | { | ||
| 1645 | my $self = shift; | ||
| 1646 | my $cmd = shift; | ||
| 1647 | my $field = shift; | ||
| 1648 | my $args = shift; | ||
| 1649 | |||
| 1650 | my $val = $cmd->{$field}; | ||
| 1651 | |||
| 1652 | if(ref($val) eq 'CODE') { | ||
| 1653 | $val = eval { &$val($self, $cmd, @$args) }; | ||
| 1654 | $self->error($@) if $@; | ||
| 1655 | } | ||
| 1656 | |||
| 1657 | return $val; | ||
| 1658 | } | ||
| 1659 | |||
| 1660 | |||
| 1661 | =item get_cmd_summary(tokens, cset) | ||
| 1662 | |||
| 1663 | Prints a one-line summary for the given command. | ||
| 1664 | Uses self->commands() if cset is not specified. | ||
| 1665 | |||
| 1666 | =cut | ||
| 1667 | |||
| 1668 | sub get_cmd_summary | ||
| 1669 | { | ||
| 1670 | my $self = shift; | ||
| 1671 | my $tokens = shift; | ||
| 1672 | my $topcset = shift || $self->commands(); | ||
| 1673 | |||
| 1674 | # print "DBG print_cmd_summary: cmd=$cmd args=(" . join(", ", @$args), ")\n"; | ||
| 1675 | |||
| 1676 | my($cset, $cmd, $cname, $args) = $self->get_deep_command($topcset, $tokens); | ||
| 1677 | |||
| 1678 | my $desc; | ||
| 1679 | if(!$cmd) { | ||
| 1680 | if(exists $topcset->{''}) { | ||
| 1681 | $cmd = $topcset->{''}; | ||
| 1682 | } else { | ||
| 1683 | return $self->get_cname($cname) . " doesn't exist.\n"; | ||
| 1684 | } | ||
| 1685 | } | ||
| 1686 | |||
| 1687 | $desc = $self->get_field($cmd, 'desc', $args) || "(no description)"; | ||
| 1688 | return sprintf("%20s -- $desc\n", $self->get_cname($cname)); | ||
| 1689 | } | ||
| 1690 | |||
| 1691 | =item get_cmd_help(tokens, cset) | ||
| 1692 | |||
| 1693 | Prints the full help text for the given command. | ||
| 1694 | Uses self->commands() if cset is not specified. | ||
| 1695 | |||
| 1696 | =cut | ||
| 1697 | |||
| 1698 | sub get_cmd_help | ||
| 1699 | { | ||
| 1700 | my $self = shift; | ||
| 1701 | my $tokens = shift; | ||
| 1702 | my $topcset = shift || $self->commands(); | ||
| 1703 | |||
| 1704 | my $str = ""; | ||
| 1705 | |||
| 1706 | # print "DBG print_cmd_help: cmd=$cmd args=(" . join(", ", @$args), ")\n"; | ||
| 1707 | |||
| 1708 | my($cset, $cmd, $cname, $args) = $self->get_deep_command($topcset, $tokens); | ||
| 1709 | if(!$cmd) { | ||
| 1710 | if(exists $topcset->{''}) { | ||
| 1711 | $cmd = $topcset->{''}; | ||
| 1712 | } else { | ||
| 1713 | return $self->get_cname($cname) . " doesn't exist.\n"; | ||
| 1714 | } | ||
| 1715 | } | ||
| 1716 | |||
| 1717 | if($self->{display_summary_in_help}) { | ||
| 1718 | if(exists($cmd->{desc})) { | ||
| 1719 | $str .= $self->get_cname($cname).": ".$self->get_field($cmd,'desc',$args)."\n"; | ||
| 1720 | } else { | ||
| 1721 | $str .= "No description for " . $self->get_cname($cname) . "\n"; | ||
| 1722 | } | ||
| 1723 | } | ||
| 1724 | |||
| 1725 | if(exists($cmd->{doc})) { | ||
| 1726 | $str .= $self->get_field($cmd, 'doc', | ||
| 1727 | [$self->get_cname($cname), @$args]); | ||
| 1728 | } elsif(exists($cmd->{cmds})) { | ||
| 1729 | $str .= $self->get_all_cmd_summaries($cmd->{cmds}); | ||
| 1730 | } else { | ||
| 1731 | # no data -- do nothing | ||
| 1732 | } | ||
| 1733 | |||
| 1734 | return $str; | ||
| 1735 | } | ||
| 1736 | |||
| 1737 | |||
| 1738 | =item get_category_summary(name, cats) | ||
| 1739 | |||
| 1740 | Prints a one-line summary for the named category | ||
| 1741 | in the category hash specified in cats. | ||
| 1742 | |||
| 1743 | =cut | ||
| 1744 | |||
| 1745 | sub get_category_summary | ||
| 1746 | { | ||
| 1747 | my $self = shift; | ||
| 1748 | my $name = shift; | ||
| 1749 | my $cat = shift; | ||
| 1750 | |||
| 1751 | my $title = $cat->{desc} || "(no description)"; | ||
| 1752 | return sprintf("%20s -- $title\n", $name); | ||
| 1753 | } | ||
| 1754 | |||
| 1755 | =item get_category_help(cat, cset) | ||
| 1756 | |||
| 1757 | Returns a summary of the commands listed in cat. | ||
| 1758 | You must pass the command set that contains those commands in cset. | ||
| 1759 | |||
| 1760 | =cut | ||
| 1761 | |||
| 1762 | sub get_category_help | ||
| 1763 | { | ||
| 1764 | my $self = shift; | ||
| 1765 | my $cat = shift; | ||
| 1766 | my $cset = shift; | ||
| 1767 | |||
| 1768 | my $str .= "\n" . $cat->{desc} . "\n\n"; | ||
| 1769 | for my $name (@{$cat->{cmds}}) { | ||
| 1770 | my @line = split /\s+/, $name; | ||
| 1771 | $str .= $self->get_cmd_summary(\@line, $cset); | ||
| 1772 | } | ||
| 1773 | $str .= "\n"; | ||
| 1774 | |||
| 1775 | return $str; | ||
| 1776 | } | ||
| 1777 | |||
| 1778 | |||
| 1779 | =item get_all_cmd_summaries(cset) | ||
| 1780 | |||
| 1781 | Pass it a command set, and it will return a string containing | ||
| 1782 | the summaries for each command in the set. | ||
| 1783 | |||
| 1784 | =cut | ||
| 1785 | |||
| 1786 | sub get_all_cmd_summaries | ||
| 1787 | { | ||
| 1788 | my $self = shift; | ||
| 1789 | my $cset = shift; | ||
| 1790 | |||
| 1791 | my $str = ""; | ||
| 1792 | |||
| 1793 | for(sort keys(%$cset)) { | ||
| 1794 | # we now exclude synonyms from the command summaries. | ||
| 1795 | # hopefully this is the right thing to do...? | ||
| 1796 | next if exists $cset->{$_}->{alias} || exists $cset->{$_}->{syn}; | ||
| 1797 | # don't show the default command in any summaries | ||
| 1798 | next if $_ eq ''; | ||
| 1799 | |||
| 1800 | $str .= $self->get_cmd_summary([$_], $cset); | ||
| 1801 | } | ||
| 1802 | |||
| 1803 | return $str; | ||
| 1804 | } | ||
| 1805 | |||
| 1806 | =item load_history() | ||
| 1807 | |||
| 1808 | If $self->{history_file} is set (see L</new>), this will load all | ||
| 1809 | history from that file. Called by L<run|/run()> on startup. If you | ||
| 1810 | don't use run, you will need to call this command manually. | ||
| 1811 | |||
| 1812 | =cut | ||
| 1813 | |||
| 1814 | sub load_history | ||
| 1815 | { | ||
| 1816 | my $self = shift; | ||
| 1817 | |||
| 1818 | return unless $self->{history_file} && $self->{history_max} > 0; | ||
| 1819 | |||
| 1820 | if(open HIST, '<'.$self->{history_file}) { | ||
| 1821 | while(<HIST>) { | ||
| 1822 | chomp(); | ||
| 1823 | next unless /\S/; | ||
| 1824 | $self->{term}->addhistory($_); | ||
| 1825 | } | ||
| 1826 | close HIST; | ||
| 1827 | } | ||
| 1828 | } | ||
| 1829 | |||
| 1830 | =item save_history() | ||
| 1831 | |||
| 1832 | If $self->{history_file} is set (see L</new>), this will save all | ||
| 1833 | history to that file. Called by L<run|/run()> on shutdown. If you | ||
| 1834 | don't use run, you will need to call this command manually. | ||
| 1835 | |||
| 1836 | The history routines don't use ReadHistory and WriteHistory so they | ||
| 1837 | can be used even if other ReadLine libs are being used. save_history | ||
| 1838 | requires that the ReadLine lib supply a GetHistory call. | ||
| 1839 | |||
| 1840 | =cut | ||
| 1841 | |||
| 1842 | sub save_history | ||
| 1843 | { | ||
| 1844 | my $self = shift; | ||
| 1845 | |||
| 1846 | return unless $self->{history_file} && $self->{history_max} > 0; | ||
| 1847 | return unless $self->{term}->can('GetHistory'); | ||
| 1848 | |||
| 1849 | if(open HIST, '>'.$self->{history_file}) { | ||
| 1850 | local $, = "\n"; | ||
| 1851 | my @list = $self->{term}->GetHistory(); | ||
| 1852 | if(@list) { | ||
| 1853 | my $max = $#list; | ||
| 1854 | $max = $self->{history_max}-1 if $self->{history_max}-1 < $max; | ||
| 1855 | print HIST @list[$#list-$max..$#list]; | ||
| 1856 | print HIST "\n"; | ||
| 1857 | } | ||
| 1858 | close HIST; | ||
| 1859 | } else { | ||
| 1860 | $self->error("Could not open ".$self->{history_file}." for writing $!\n"); | ||
| 1861 | } | ||
| 1862 | } | ||
| 1863 | |||
| 1864 | =item call_command(parms) | ||
| 1865 | |||
| 1866 | Executes a command and returns the result. It takes a single | ||
| 1867 | argument: the parms data structure. | ||
| 1868 | |||
| 1869 | parms is a subset of the cmpl data structure (see the L<complete/complete(cmpl)> | ||
| 1870 | routine for more). Briefly, it contains: | ||
| 1871 | cset, cmd, cname, args (see L</get_deep_command>), | ||
| 1872 | tokens and rawline (the tokenized and untokenized command lines). | ||
| 1873 | See L<complete|/complete(cmpl)> for full descriptions of these fields. | ||
| 1874 | |||
| 1875 | This call should be overridden if you have exotic command | ||
| 1876 | processing needs. If you override this routine, you will probably | ||
| 1877 | need to override the L<complete|/complete(cmpl)> routine too. | ||
| 1878 | |||
| 1879 | =cut | ||
| 1880 | |||
| 1881 | |||
| 1882 | # This is the low-level version of call_command. It does nothing but call. | ||
| 1883 | # Use call_command -- it's much smarter. | ||
| 1884 | |||
| 1885 | sub call_cmd | ||
| 1886 | { | ||
| 1887 | my $self = shift; | ||
| 1888 | my $parms = shift; | ||
| 1889 | |||
| 1890 | my $cmd = $parms->{cmd}; | ||
| 1891 | my $OUT = $self->{OUT}; | ||
| 1892 | |||
| 1893 | my $retval = undef; | ||
| 1894 | if(exists $cmd->{meth} || exists $cmd->{method}) { | ||
| 1895 | my $meth = $cmd->{meth} || $cmd->{method}; | ||
| 1896 | # if meth is a code ref, call it, else it's a string, print it. | ||
| 1897 | if(ref($meth) eq 'CODE') { | ||
| 1898 | $retval = eval { &$meth($self, $parms, @{$parms->{args}}) }; | ||
| 1899 | $self->error($@) if $@; | ||
| 1900 | } else { | ||
| 1901 | print $OUT $meth; | ||
| 1902 | } | ||
| 1903 | } elsif(exists $cmd->{proc}) { | ||
| 1904 | # if proc is a code ref, call it, else it's a string, print it. | ||
| 1905 | if(ref($cmd->{proc}) eq 'CODE') { | ||
| 1906 | $retval = eval { &{$cmd->{proc}}(@{$parms->{args}}) }; | ||
| 1907 | $self->error($@) if $@; | ||
| 1908 | } else { | ||
| 1909 | print $OUT $cmd->{proc}; | ||
| 1910 | } | ||
| 1911 | } else { | ||
| 1912 | if(exists $cmd->{cmds}) { | ||
| 1913 | # if not, but it has subcommands, then print a summary | ||
| 1914 | print $OUT $self->get_all_cmd_summaries($cmd->{cmds}); | ||
| 1915 | } else { | ||
| 1916 | $self->error("The ". $self->get_cname($parms->{cname}) . | ||
| 1917 | " command has no proc or method to call!\n"); | ||
| 1918 | } | ||
| 1919 | } | ||
| 1920 | |||
| 1921 | return $retval; | ||
| 1922 | } | ||
| 1923 | |||
| 1924 | |||
| 1925 | sub call_command | ||
| 1926 | { | ||
| 1927 | my $self = shift; | ||
| 1928 | my $parms = shift; | ||
| 1929 | |||
| 1930 | if(!$parms->{cmd}) { | ||
| 1931 | if( exists $parms->{cset}->{''} && | ||
| 1932 | (exists($parms->{cset}->{''}->{proc}) || | ||
| 1933 | exists($parms->{cset}->{''}->{meth}) || | ||
| 1934 | exists($parms->{cset}->{''}->{method}) | ||
| 1935 | ) | ||
| 1936 | ) { | ||
| 1937 | # default command exists and is callable | ||
| 1938 | my $save = $parms->{cmd}; | ||
| 1939 | $parms->{cmd} = $parms->{cset}->{''}; | ||
| 1940 | my $retval = $self->call_cmd($parms); | ||
| 1941 | $parms->{cmd} = $save; | ||
| 1942 | return $retval; | ||
| 1943 | } | ||
| 1944 | |||
| 1945 | $self->error( $self->get_cname($parms->{cname}) . ": unknown command\n"); | ||
| 1946 | return undef; | ||
| 1947 | } | ||
| 1948 | |||
| 1949 | my $cmd = $parms->{cmd}; | ||
| 1950 | |||
| 1951 | # check min and max args if they exist | ||
| 1952 | if(exists($cmd->{minargs}) && @{$parms->{args}} < $cmd->{minargs}) { | ||
| 1953 | $self->error("Too few args! " . $cmd->{minargs} . " minimum.\n"); | ||
| 1954 | return undef; | ||
| 1955 | } | ||
| 1956 | if(exists($cmd->{maxargs}) && @{$parms->{args}} > $cmd->{maxargs}) { | ||
| 1957 | $self->error("Too many args! " . $cmd->{maxargs} . " maximum.\n"); | ||
| 1958 | return undef; | ||
| 1959 | } | ||
| 1960 | |||
| 1961 | # everything checks out -- call the command | ||
| 1962 | return $self->call_cmd($parms); | ||
| 1963 | } | ||
| 1964 | |||
| 1965 | =back | ||
| 1966 | |||
| 1967 | =head1 LICENSE | ||
| 1968 | |||
| 1969 | Copyright (c) 2003-2011 Scott Bronson, all rights reserved. | ||
| 1970 | This program is free software released under the MIT license. | ||
| 1971 | |||
| 1972 | =head1 AUTHORS | ||
| 1973 | |||
| 1974 | Scott Bronson E<lt>bronson@rinspin.comE<gt> | ||
| 1975 | Lester Hightower E<lt>hightowe@cpan.orgE<gt> | ||
| 1976 | Ryan Gies E<lt>ryan@livesite.netE<gt> | ||
| 1977 | Martin Kluge E<lt>mk@elxsi.deE<gt> | ||
| 1978 | |||
| 1979 | =cut | ||
| 1980 | |||
| 1981 | 1; |