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

NAME

6       Term::Completion - read one line of user input, with convenience
7       functions
8

USAGE

10         use Term::Completion;
11         my $tc = Term::Completion->new(
12           prompt  => "Enter your first name: ",
13           choices => [ qw(Alice Bob Chris Dave Ellen) ]
14         );
15         my $name = $tc->complete();
16         print "You entered: $name\n";
17

DESCRIPTION

19       Term::Completion is an extensible, highly configurable replacement for
20       the venerable Term::Complete package. It is object-oriented and thus
21       allows subclassing. Two derived classes are Term::Completion::Multi and
22       Term::Completion::Path.
23
24       A prompt is printed and the user may enter one line of input,
25       submitting the answer by pressing the ENTER key. This basic scenario
26       can be implemented like this:
27
28           my $answer = <STDIN>;
29           chomp $answer;
30
31       But often you don't want the user to type in the full word (from a list
32       of choices), but allow completion, i.e. expansion of the word as far as
33       possible by pressing as few keys as necessary.
34
35       Some users like to cycle through the choices, preferably with the
36       up/down arrow keys.
37
38       And finally, you may not want the user to enter any random characters,
39       but validate what was enter and come back if the entry did not pass the
40       validation.
41
42       If you are missing full line editing (left/right, delete to the left
43       and right, jump to the beginning and the end etc.), you are probably
44       wrong here, and want to consider Term::ReadLine and friends.
45
46   Global Setup
47       The technical challenge for this package is to read single keystrokes
48       from the input handle - usually STDIN, the user's terminal. There are
49       various ways how to accomplish that, and Term::Completion supports them
50       all:
51
52       use Term::Completion qw(:stty);
53           Use the external "stty" command to configure the terminal. This is
54           what Term::Complete does, and works fine on systems that have a
55           working "stty". However, using an external command seems like an
56           ugly overhead.  See also Term::Completion::_stty.
57
58       use Term::Completion qw(:readkey);
59           This is the default for all systems, as we assume  you have
60           Term::ReadKey installed. This seems to be the right approach to
61           also support various platforms. See also
62           Term::Completion::_readkey.
63
64       use Term::Completion qw(:POSIX);
65           This uses the POSIX interface ("POSIX::Termios") to set the
66           terminal in the right mode. It should be well portable on UNIX
67           systems.  See also Term::Completion::_POSIX.
68
69   Exports
70       Term::Completion does not export anything by default, in order not to
71       pollute your namespace. Here are the exportable methods:
72
73       Complete(...)
74           For compatibility with Term::Complete, you can import the
75           "Complete" function:
76
77             use Term::Completion qw(Complete);
78             my $result = Complete($prompt, @choices);
79
80   Methods
81       Term::Completion objects are simple hashes. All fields are fully
82       accessible and can be tweaked directly, without accessor methods.
83
84       Term::Completion offers the following methods:
85
86       new(...)
87           The constructor for Term::Completion objects. Arguments are
88           key/value pairs. See "Configuration" for a description of all
89           options. Note that "columns" and "rows" overrides the real terminal
90           size from Term::Size.
91
92           Usually you'd supply the list of choices and the prompt string:
93
94             my $tc = Term::Completion->new(
95               prompt => "Pick a color: ",
96               choices => [ qw(red green blue) ]
97             );
98
99           The object can be reused several times for the same purpose.
100           Term::Completion objects are simple hashes. All fields are fully
101           accessible and can be tweaked directly, without accessor methods.
102           In the example above, you can manipulate the choice list:
103
104             push(@{$tc->{choices}}, qw(cyan magenta yellow));
105
106           Note that the constructor won't actually execute the query - that
107           is done by the "complete()" method.
108
109       complete()
110           This method executes the query and returns the result string.  It
111           is guaranteed that the result is a defined value, it may however be
112           empty or 0.
113
114       post_process($answer)
115           This method is called on the answer string entered by the user
116           after the ENTER key was pressed. The implementation in the base
117           class is just stripping any leading and trailing whitespace.  The
118           method returnes the postprocessed answer string.
119
120       validate($answer)
121           This method is called on the postprocessed answer and returns:
122
123           1. in case of success
124
125           The correct answer string. Please note that the validate method may
126           alter the answer, e.g. to adapt it to certain conventions
127           (lowercase only).
128
129           2. in case of failure
130
131           The undef value. This indicates a failure of the validation. In
132           that situation an error message should be printed to tell the user
133           why the validation failed. This should be done using the following
134           idiom for maximum portability:
135
136             $this->{out}->print("ERROR: no such choice available",
137                                 $this->{eol});
138
139           Validation is turned on by the "validation" parameter.  See
140           "Predefined Validations" for a list of available validation
141           options.
142
143           You can override this method in derived classes to implement your
144           own validation strategy - but in some situations this could be too
145           much overhead. So the base class understands this callback:
146
147             my $tc = Term::Completion->new(
148               prompt => 'Enter voltage: ',
149               choices => [ qw(1.2 1.5 1.8 2.0 2.5 3.3) ],
150               validate => [
151                 'Voltage must be a positive, non-zero value' =>
152                 sub { $_[0] > 0.0 }
153               ]
154             );
155
156       get_choices($answer)
157           This method returns the items from the choice list which match the
158           current answer string. This method is used by the completion
159           algorithm and the list of choices. This can be overridden to
160           implement a completely different way to get the choices (other than
161           a static list) - e.g. by querying a database.
162
163       show_choices($answer)
164           This method is called when the user types CTRL-D (or TAB-TAB) to
165           show the list of choices, available with the current answer string.
166           Basically "get_choices($answer)" is called and then the list is
167           pretty-printed using "_show_choices(...)".
168
169       _show_choices(...)
170           Pretty-print the list of items given as arguments. The list is
171           formatted into columns, like in UNIX' "ls" command, according to
172           the current terminal width (if Term::Size is available). If the
173           list is long, then poor man's paging is enabled, comparable to the
174           UNIX "more" command. The user can use ENTER to proceed by one line,
175           SPACE to proceed to the next page and Q or CTRL-C to quit paging.
176           After listing the choices and return from this method, the prompt
177           and the current answer are redisplayed.
178
179           Override this method if you have a better pretty-printer/pager. :-)
180
181   Configuration
182       There is a global hash %Term::Completion::DEFAULTS that contains the
183       default values for all configurable options. Upon object construction
184       (see "new(...)" any of these defaults can be overridden by placing the
185       corresponding key/value pair in the arguments. Find below the list of
186       configurable options, their default value and their purpose.
187
188       The key definitions are regular expressions ("qr/.../") - this allows
189       to match multiple keys for the same action, as well as diable the
190       action completely by specifying an expression that will never match a
191       single character, e.g. "qr/-disable-/".
192
193       "in"
194           The input file handle, default is "\*STDIN". Can be any filehandle-
195           like object, has to understand the "getc()" method.
196
197       "out"
198           The output file handle, default is "\*STDOUT". Can be basically any
199           filehandle-like object, has to understand the "print()" method.
200
201       "tab"
202           Regular expression matching those keys that should work as the TAB
203           key, i.e. complete the current answer string as far as possible,
204           and when pressed twice, show the list of matching choices. Default
205           is the tab key, i.e. "qr/\t/".
206
207       "list"
208           Regular expression matching those keys that should trigger the
209           listing of choices. Default is - like in Term::Complete - CTRL-D,
210           i.e.  "qr/\cd/".
211
212       "kill"
213           Regular expression matching those keys that should delete all
214           input.  Default is CTRL-U, i.e. "qr/\cu/".
215
216       "erase"
217           Regular expression matching those keys that should delete one
218           character (backspace). Default is the BACKSPACE and the DELETE
219           keys, i.e.  "qr/[\177\010]/".
220
221       "wipe"
222           This is a special control: if either "sep" or "delim" are defined
223           (see below), then this key "wipes" all characters (from the right)
224           until (and including) the last separator or delimiter. Default is
225           CTRL-W, i.e.  "qr/\cw/".
226
227       "enter"
228           Regular expression matching those keys that finish the entry
229           process.  Default is the ENTER key, and for paranoia reasons we use
230           "qr/[\r\n]/".
231
232       "up"
233           Regular expression matching those keys that select the previous
234           item from the choice list. Default is CTRL-P, left and up arrow
235           keys, i.e.  "qr/\cp|\x1b\[[AD]/".
236
237       "down"
238           Regular expression matching those keys that select the next item
239           from the choice list. Default is CTRL-N, right and down arrow keys,
240           i.e.  "qr/\cn|\x1b\[[BC]/".
241
242       "quit"
243           Regular expression matching those keys that exit from paging when
244           the list of choices is displayed. Default is 'q' and CTRL-C, i.e.
245           "qr/[\ccq]/".
246
247       "prompt"
248           A default prompt string to apply for all Term::Completion objects.
249           Default is the empty string.
250
251       "columns"
252           Default number of terminal columns for the list of choices. This
253           default is only applicable if Term::Size is unavailable to get the
254           real number of columns. The default is 80.
255
256       "rows"
257           Default number of terminal rows for the list of choices. This
258           default is only applicable if Term::Size is unavailable to get the
259           real number of rows. The default is 24. If set to 0 (zero) there
260           won't be any paging when the list of choices is displayed.
261
262       "bell"
263           The character which rings the terminal bell, default is "\a". Used
264           when completing with the TAB key and there are multiple choices
265           available, and when paging is restarted because the terminal size
266           was changed.
267
268       "page_str"
269           The string to display when max number of lines on the terminal has
270           been reached when displaying the choices. Default is '--more--'.
271
272       "eol"
273           The characters to print for a new line in raw terminal mode.
274           Default is "\r\n".
275
276       "del_one"
277           The characters to print for deleting one character (to the left).
278           Default is "\b \b".
279
280       "helptext"
281           This is an optional text which is printed by the "complete()"
282           method before the actual completion process starts. It may be a
283           multi-line string and should end with a newline character. Default
284           is undef. The text could for example look like this:
285             helptext => <<'EOT',
286               You may use the following control keys here:
287                 TAB      complete the word
288                 CTRL-D   show list of matching choices (same as TAB-TAB)
289                 CTRL-U   delete the input
290                 CTRL-H   delete a character (backspace)
291                 CTRL-P   cycle through choices (backward) (also up arrow)
292                 CTRL-N   cycle through choices (forward) (also down arrow)
293             EOT
294
295       "choices"
296           The default list of choices for all Term::Completion objects
297           (unless overridden by the "new(...)" constructor. Has to be an
298           array reference.  Default is the empty array reference "[]".
299           Undefined items are filtered out.
300
301   Predefined Validations
302       Whenever you need validation of the user's input, you can always
303       specify your own code, see "validate($answer)" above. To support
304       everybody's laziness, there are a couple of predefined validation
305       methods available.  You can specify them as a blank or comma separated
306       string in the "new(...)" constructor:
307
308         my $tc = Term::Completion->new(
309           prompt => 'Fruit: ',
310           choices => [ qw(apple banana cherry) ],
311           validation => 'nonblank fromchoices'
312         );
313
314       In the example above, you are guaranteed the user will choose one of
315       the given choices. Here's a list of all pre-implemented validations:
316
317       "uppercase"
318           Map all the answer string to upper case before proceeding with any
319           further validation.
320
321       "lowercase"
322           Map all the answer string to lower case before proceeding with any
323           further validation.
324
325       "match_one"
326           This option has some magic: it tries to match the answer string
327           first at the beginning of all choices; if that yields a unique
328           match, the match is returned. If not, the answer string is matched
329           at any position in the choices, and if that yields a unique match,
330           the match is returned.  Otherwise an error will be raised that the
331           answer does not match a unique item.
332
333       "nonempty"
334           Raises an error if the answer has a length of zero characters.
335
336       "nonblank"
337           Raises an error if the answer does not contain any non-whitespace
338           character.
339
340       "fromchoices"
341           Only allow literal entries from the choice list, or the empty
342           string. If you don't like the latter, combine this with "nonempty".
343
344       "numeric"
345           Only allow numeric values, e.g. -1.234 or 987.
346
347       "integer"
348           Only allow integer numbers, e.g. -1 or 234.
349
350       "nonzero"
351           Prohibit the numeric value 0 (zero). To avoid warnings about non-
352           numeric values, this should be used together with one of "numeric"
353           or "integer".
354
355       "positive"
356           Only allow numeric values greater than zero. To avoid warnings
357           about non-numeric values, this should be used together with one of
358           "numeric" or "integer".
359
360       This list obviously can be arbitrarily extended. Suggestions (submitted
361       as patches) are welcome.
362

CAVEATS

364   Terminal handling
365       This package temporarily has to set the terminal into 'raw' mode, which
366       means that all keys lose their special meaning (like CTRL-C, which
367       normally interrupts the script). This is a highly platform-specific
368       operation, and therefore this package depends on the portability of
369       Term::ReadKey and POSIX. Reports about failing platforms are welcome,
370       but there is probably little that can be fixed here.
371
372   Terminal size changes
373       This package does the best it can to handle changes of the terminal
374       size during the completion process. It redisplays the prompt and the
375       current entry during completion, and restarts paging when showing the
376       list of choices. The latter however only after you press a key - the
377       bell sounds to indicate that something happened. This is because it
378       does not seem possible to jump out of a getc().
379
380   Arrow key handling
381       On UNIX variants, the arrow keys generate a sequence of bytes, starting
382       with the escape character, followed by a square brackets and others.
383       Term::Completion accumulates these characters until they either match
384       this sequence, or not. In the latter case, it will drop the previous
385       characters and proceed with the last one typed. That however means that
386       you won't be able to assign the bare escape key to an action. I found
387       this to be the lesser of the evils. Suggestions on how to solve this in
388       a clean way are welcome. Yes, I read "How can I tell whether there's a
389       character waiting on a filehandle?" in perlfaq5 but that's probably
390       little portable.
391

SEE ALSO

393       Term::Complete, Term::ReadKey, Term::Size, POSIX, Term::ReadLine
394

AUTHOR

396       Marek Rouchal, <rouchal@muc.infineon.com>
397
399       Copyright (C) 2009 by Marek Rouchal
400
401       This library is free software; you can redistribute it and/or modify it
402       under the same terms as Perl itself, either Perl version 5.8.8 or, at
403       your option, any later version of Perl 5 you may have available.
404

POD ERRORS

406       Hey! The above document had some coding errors, which are explained
407       below:
408
409       Around line 623:
410           You forgot a '=back' before '=head2'
411
412
413
414perl v5.12.0                      2009-02-27               Term::Completion(3)
Impressum