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 ? $_[0] : undef }
153               ]
154             );
155
156           Note that the given code reference will be passed the one single
157           argument, namely the current input string, and is supposed to
158           return undef if the input is invalid, or the (potentially
159           corrected) string, like in the example above.
160
161       get_choices($answer)
162           This method returns the items from the choice list which match the
163           current answer string. This method is used by the completion
164           algorithm and the list of choices. This can be overridden to
165           implement a completely different way to get the choices (other than
166           a static list) - e.g. by querying a database.
167
168       show_choices($answer)
169           This method is called when the user types CTRL-D (or TAB-TAB) to
170           show the list of choices, available with the current answer string.
171           Basically get_choices($answer) is called and then the list is
172           pretty-printed using _show_choices(...).
173
174       _show_choices(...)
175           Pretty-print the list of items given as arguments. The list is
176           formatted into columns, like in UNIX' "ls" command, according to
177           the current terminal width (if Term::Size is available). If the
178           list is long, then poor man's paging is enabled, comparable to the
179           UNIX "more" command. The user can use ENTER to proceed by one line,
180           SPACE to proceed to the next page and Q or CTRL-C to quit paging.
181           After listing the choices and return from this method, the prompt
182           and the current answer are redisplayed.
183
184           Override this method if you have a better pretty-printer/pager. :-)
185
186   Configuration
187       There is a global hash %Term::Completion::DEFAULTS that contains the
188       default values for all configurable options. Upon object construction
189       (see "new(...)" any of these defaults can be overridden by placing the
190       corresponding key/value pair in the arguments. Find below the list of
191       configurable options, their default value and their purpose.
192
193       The key definitions are regular expressions ("qr/.../") - this allows
194       to match multiple keys for the same action, as well as disable the
195       action completely by specifying an expression that will never match a
196       single character, e.g. "qr/-disable-/".
197
198       "in"
199           The input file handle, default is "\*STDIN". Can be any filehandle-
200           like object, has to understand the getc() method.
201
202       "out"
203           The output file handle, default is "\*STDOUT". Can be basically any
204           filehandle-like object, has to understand the print() method.
205
206       "tab"
207           Regular expression matching those keys that should work as the TAB
208           key, i.e. complete the current answer string as far as possible,
209           and when pressed twice, show the list of matching choices. Default
210           is the tab key, i.e. "qr/\t/".
211
212       "list"
213           Regular expression matching those keys that should trigger the
214           listing of choices. Default is - like in Term::Complete - CTRL-D,
215           i.e.  "qr/\cd/".
216
217       "kill"
218           Regular expression matching those keys that should delete all
219           input.  Default is CTRL-U, i.e. "qr/\cu/".
220
221       "erase"
222           Regular expression matching those keys that should delete one
223           character (backspace). Default is the BACKSPACE and the DELETE
224           keys, i.e.  "qr/[\177\010]/".
225
226       "wipe"
227           This is a special control: if either "sep" or "delim" are defined
228           (see below), then this key "wipes" all characters (from the right)
229           until (and including) the last separator or delimiter. Default is
230           CTRL-W, i.e.  "qr/\cw/".
231
232       "enter"
233           Regular expression matching those keys that finish the entry
234           process.  Default is the ENTER key, and for paranoia reasons we use
235           "qr/[\r\n]/".
236
237       "up"
238           Regular expression matching those keys that select the previous
239           item from the choice list. Default is CTRL-P, left and up arrow
240           keys, i.e.  "qr/\cp|\x1b\[[AD]/".
241
242       "down"
243           Regular expression matching those keys that select the next item
244           from the choice list. Default is CTRL-N, right and down arrow keys,
245           i.e.  "qr/\cn|\x1b\[[BC]/".
246
247       "quit"
248           Regular expression matching those keys that exit from paging when
249           the list of choices is displayed. Default is 'q' and CTRL-C, i.e.
250           "qr/[\ccq]/".
251
252       "prompt"
253           A default prompt string to apply for all Term::Completion objects.
254           Default is the empty string.
255
256       "columns"
257           Default number of terminal columns for the list of choices. This
258           default is only applicable if Term::Size is unavailable to get the
259           real number of columns. The default is 80.
260
261       "rows"
262           Default number of terminal rows for the list of choices. This
263           default is only applicable if Term::Size is unavailable to get the
264           real number of rows. The default is 24. If set to 0 (zero) there
265           won't be any paging when the list of choices is displayed.
266
267       "bell"
268           The character which rings the terminal bell, default is "\a". Used
269           when completing with the TAB key and there are multiple choices
270           available, and when paging is restarted because the terminal size
271           was changed.
272
273       "page_str"
274           The string to display when max number of lines on the terminal has
275           been reached when displaying the choices. Default is '--more--'.
276
277       "eol"
278           The characters to print for a new line in raw terminal mode.
279           Default is "\r\n".
280
281       "del_one"
282           The characters to print for deleting one character (to the left).
283           Default is "\b \b".
284
285       "help"
286           Regular expression matching those keys that print "helptext" on-
287           demand.  Furthermore, with "help" defined (undef), automatic
288           printing of "helptext" by the complete() method is disabled
289           (enabled).  Default is undef, for backwards compatibility; "qr/\?/"
290           is suggested.
291
292       "helptext"
293           This is an optional text which is printed by the complete() method
294           before the actual completion process starts, unless "help" is
295           defined.  It may be a multi-line string and should end with a
296           newline character.  Default is undef. The text could for example
297           look like this:
298
299             helptext => <<'EOT',
300               You may use the following control keys here:
301                 TAB      complete the word
302                 CTRL-D   show list of matching choices (same as TAB-TAB)
303                 CTRL-U   delete the entire input
304                 CTRL-H   delete a character (backspace)
305                 CTRL-P   cycle through choices (backward) (also up arrow)
306                 CTRL-N   cycle through choices (forward) (also down arrow)
307             EOT
308
309       "choices"
310           The default list of choices for all Term::Completion objects
311           (unless overridden by the new(...) constructor. Has to be an array
312           reference.  Default is the empty array reference "[]". Undefined
313           items are filtered out.
314
315   Predefined Validations
316       Whenever you need validation of the user's input, you can always
317       specify your own code, see "validate($answer)" above. To support
318       everybody's laziness, there are a couple of predefined validation
319       methods available.  You can specify them as a blank or comma separated
320       string in the new(...) constructor:
321
322         my $tc = Term::Completion->new(
323           prompt => 'Fruit: ',
324           choices => [ qw(apple banana cherry) ],
325           validation => 'nonblank fromchoices'
326         );
327
328       In the example above, you are guaranteed the user will choose one of
329       the given choices. Here's a list of all pre-implemented validations:
330
331       "uppercase"
332           Map all the answer string to upper case before proceeding with any
333           further validation.
334
335       "lowercase"
336           Map all the answer string to lower case before proceeding with any
337           further validation.
338
339       "match_one"
340           This option has some magic: it tries to match the answer string
341           first at the beginning of all choices; if that yields a unique
342           match, the match is returned. If not, the answer string is matched
343           at any position in the choices, and if that yields a unique match,
344           the match is returned.  Otherwise an error will be raised that the
345           answer does not match a unique item.
346
347       "nonempty"
348           Raises an error if the answer has a length of zero characters.
349
350       "nonblank"
351           Raises an error if the answer does not contain any non-whitespace
352           character.
353
354       "fromchoices"
355           Only allow literal entries from the choice list, or the empty
356           string. If you don't like the latter, combine this with "nonempty".
357
358       "numeric"
359           Only allow numeric values, e.g. -1.234 or 987.
360
361       "integer"
362           Only allow integer numbers, e.g. -1 or 234.
363
364       "nonzero"
365           Prohibit the numeric value 0 (zero). To avoid warnings about non-
366           numeric values, this should be used together with one of "numeric"
367           or "integer".
368
369       "positive"
370           Only allow numeric values greater than zero. To avoid warnings
371           about non-numeric values, this should be used together with one of
372           "numeric" or "integer".
373
374       This list obviously can be arbitrarily extended. Suggestions (submitted
375       as patches) are welcome.
376

CAVEATS

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

SEE ALSO

407       Term::Complete, Term::ReadKey, Term::Size, POSIX, Term::ReadLine
408

AUTHOR

410       Marek Rouchal, <marekr@cpan.org<gt>
411

BUGS

413       Please submit patches, bug reports and suggestions via the CPAN tracker
414       <http://rt.cpan.org>.
415
417       Copyright (C) 2009-2013 by Marek Rouchal
418
419       This library is free software; you can redistribute it and/or modify it
420       under the same terms as Perl itself, either Perl version 5.8.8 or, at
421       your option, any later version of Perl 5 you may have available.
422
423
424
425perl v5.38.0                      2023-07-21               Term::Completion(3)
Impressum