1 @comment %**start of header (This is for running Texinfo on a region.)
2 @setfilename rltech.info
3 @comment %**end of header (This is for running Texinfo on a region.)
7 This document describes the GNU Readline Library, a utility for aiding
8 in the consitency of user interface across discrete programs that need
9 to provide a command line interface.
11 Copyright (C) 1988, 1994, 1996 Free Software Foundation, Inc.
13 Permission is granted to make and distribute verbatim copies of
14 this manual provided the copyright notice and this permission notice
15 pare preserved on all copies.
18 Permission is granted to process this file through TeX and print the
19 results, provided the printed document carries copying permission
20 notice identical to this one except for the removal of this paragraph
21 (this paragraph not being relevant to the printed manual).
24 Permission is granted to copy and distribute modified versions of this
25 manual under the conditions for verbatim copying, provided that the entire
26 resulting derived work is distributed under the terms of a permission
27 notice identical to this one.
29 Permission is granted to copy and distribute translations of this manual
30 into another language, under the above conditions for modified versions,
31 except that this permission notice may be stated in a translation approved
35 @node Programming with GNU Readline
36 @chapter Programming with GNU Readline
38 This chapter describes the interface between the GNU Readline Library and
39 other programs. If you are a programmer, and you wish to include the
40 features found in GNU Readline
41 such as completion, line editing, and interactive history manipulation
42 in your own programs, this section is for you.
45 * Basic Behavior:: Using the default behavior of Readline.
46 * Custom Functions:: Adding your own functions to Readline.
47 * Readline Variables:: Variables accessible to custom
49 * Readline Convenience Functions:: Functions which Readline supplies to
50 aid in writing your own
51 * Custom Completers:: Supplanting or supplementing Readline's
56 @section Basic Behavior
58 Many programs provide a command line interface, such as @code{mail},
59 @code{ftp}, and @code{sh}. For such programs, the default behaviour of
60 Readline is sufficient. This section describes how to use Readline in
61 the simplest way possible, perhaps to replace calls in your code to
62 @code{gets()} or @code{fgets ()}.
65 @cindex readline, function
66 The function @code{readline ()} prints a prompt and then reads and returns
67 a single line of text from the user. The line @code{readline}
68 returns is allocated with @code{malloc ()}; you should @code{free ()}
69 the line when you are done with it. The declaration for @code{readline}
73 @code{char *readline (char *@var{prompt});}
79 @code{char *line = readline ("Enter a line: ");}
82 in order to read a line of text from the user.
83 The line returned has the final newline removed, so only the
86 If @code{readline} encounters an @code{EOF} while reading the line, and the
87 line is empty at that point, then @code{(char *)NULL} is returned.
88 Otherwise, the line is ended just as if a newline had been typed.
90 If you want the user to be able to get at the line later, (with
91 @key{C-p} for example), you must call @code{add_history ()} to save the
92 line away in a @dfn{history} list of such lines.
95 @code{add_history (line)};
99 For full details on the GNU History Library, see the associated manual.
101 It is preferable to avoid saving empty lines on the history list, since
102 users rarely have a burning need to reuse a blank line. Here is
103 a function which usefully replaces the standard @code{gets ()} library
104 function, and has the advantage of no static buffer to overflow:
107 /* A static variable for holding the line. */
108 static char *line_read = (char *)NULL;
110 /* Read a string, and return a pointer to it. Returns NULL on EOF. */
114 /* If the buffer has already been allocated, return the memory
119 line_read = (char *)NULL;
122 /* Get a line from the user. */
123 line_read = readline ("");
125 /* If the line has any text in it, save it on the history. */
126 if (line_read && *line_read)
127 add_history (line_read);
133 This function gives the user the default behaviour of @key{TAB}
134 completion: completion on file names. If you do not want Readline to
135 complete on filenames, you can change the binding of the @key{TAB} key
136 with @code{rl_bind_key ()}.
139 @code{int rl_bind_key (int @var{key}, int (*@var{function})());}
142 @code{rl_bind_key ()} takes two arguments: @var{key} is the character that
143 you want to bind, and @var{function} is the address of the function to
144 call when @var{key} is pressed. Binding @key{TAB} to @code{rl_insert ()}
145 makes @key{TAB} insert itself.
146 @code{rl_bind_key ()} returns non-zero if @var{key} is not a valid
147 ASCII character code (between 0 and 255).
149 Thus, to disable the default @key{TAB} behavior, the following suffices:
151 @code{rl_bind_key ('\t', rl_insert);}
154 This code should be executed once at the start of your program; you
155 might write a function called @code{initialize_readline ()} which
156 performs this and other desired initializations, such as installing
157 custom completers (@pxref{Custom Completers}).
159 @node Custom Functions
160 @section Custom Functions
162 Readline provides many functions for manipulating the text of
163 the line, but it isn't possible to anticipate the needs of all
164 programs. This section describes the various functions and variables
165 defined within the Readline library which allow a user program to add
166 customized functionality to Readline.
169 * The Function Type:: C declarations to make code readable.
170 * Function Writing:: Variables and calling conventions.
173 @node The Function Type
174 @subsection The Function Type
176 For readabilty, we declare a new type of object, called
177 @dfn{Function}. A @code{Function} is a C function which
178 returns an @code{int}. The type declaration for @code{Function} is:
181 @code{typedef int Function ();}
183 The reason for declaring this new type is to make it easier to write
184 code describing pointers to C functions. Let us say we had a variable
185 called @var{func} which was a pointer to a function. Instead of the
186 classic C declaration
188 @code{int (*)()func;}
193 @code{Function *func;}
199 typedef void VFunction ();
200 typedef char *CPFunction (); @r{and}
201 typedef char **CPPFunction ();
205 for functions returning no value, @code{pointer to char}, and
206 @code{pointer to pointer to char}, respectively.
208 @node Function Writing
209 @subsection Writing a New Function
211 In order to write new functions for Readline, you need to know the
212 calling conventions for keyboard-invoked functions, and the names of the
213 variables that describe the current state of the line read so far.
215 The calling sequence for a command @code{foo} looks like
218 @code{foo (int count, int key)}
222 where @var{count} is the numeric argument (or 1 if defaulted) and
223 @var{key} is the key that invoked this function.
225 It is completely up to the function as to what should be done with the
226 numeric argument. Some functions use it as a repeat count, some
227 as a flag, and others to choose alternate behavior (refreshing the current
228 line as opposed to refreshing the screen, for example). Some choose to
229 ignore it. In general, if a
230 function uses the numeric argument as a repeat count, it should be able
231 to do something useful with both negative and positive arguments.
232 At the very least, it should be aware that it can be passed a
235 @node Readline Variables
236 @section Readline Variables
238 These variables are available to function writers.
240 @deftypevar {char *} rl_line_buffer
241 This is the line gathered so far. You are welcome to modify the
242 contents of the line, but see @ref{Allowing Undoing}.
245 @deftypevar int rl_point
246 The offset of the current cursor position in @code{rl_line_buffer}
250 @deftypevar int rl_end
251 The number of characters present in @code{rl_line_buffer}. When
252 @code{rl_point} is at the end of the line, @code{rl_point} and
253 @code{rl_end} are equal.
256 @deftypevar int rl_mark
257 The mark (saved position) in the current line. If set, the mark
258 and point define a @emph{region}.
261 @deftypevar int rl_done
262 Setting this to a non-zero value causes Readline to return the current
266 @deftypevar int rl_pending_input
267 Setting this to a value makes it the next keystroke read. This is a
268 way to stuff a single character into the input stream.
271 @deftypevar {char *} rl_prompt
272 The prompt Readline uses. This is set from the argument to
273 @code{readline ()}, and should not be assigned to directly.
276 @deftypevar {char *} rl_library_version
277 The version number of this revision of the library.
280 @deftypevar {char *} rl_terminal_name
281 The terminal type, used for initialization.
284 @deftypevar {char *} rl_readline_name
285 This variable is set to a unique name by each application using Readline.
286 The value allows conditional parsing of the inputrc file
287 (@pxref{Conditional Init Constructs}).
290 @deftypevar {FILE *} rl_instream
291 The stdio stream from which Readline reads input.
294 @deftypevar {FILE *} rl_outstream
295 The stdio stream to which Readline performs output.
298 @deftypevar {Function *} rl_startup_hook
299 If non-zero, this is the address of a function to call just
300 before @code{readline} prints the first prompt.
303 @deftypevar {Function *} rl_event_hook
304 If non-zero, this is the address of a function to call periodically
305 when readline is waiting for terminal input.
308 @deftypevar {Function *} rl_getc_function
309 If non-zero, @code{readline} will call indirectly through this pointer
310 to get a character from the input stream. By default, it is set to
311 @code{rl_getc}, the default @code{readline} character input function
312 (@pxref{Utility Functions}).
315 @deftypevar {Function *} rl_redisplay_function
316 If non-zero, @code{readline} will call indirectly through this pointer
317 to update the display with the current contents of the editing buffer.
318 By default, it is set to @code{rl_redisplay}, the default @code{readline}
319 redisplay function (@pxref{Redisplay}).
322 @deftypevar {Keymap} rl_executing_keymap
323 This variable is set to the keymap (@pxref{Keymaps}) in which the
324 currently executing readline function was found.
327 @deftypevar {Keymap} rl_binding_keymap
328 This variable is set to the keymap (@pxref{Keymaps}) in which the
329 last key binding occurred.
332 @node Readline Convenience Functions
333 @section Readline Convenience Functions
336 * Function Naming:: How to give a function you write a name.
337 * Keymaps:: Making keymaps.
338 * Binding Keys:: Changing Keymaps.
339 * Associating Function Names and Bindings:: Translate function names to
341 * Allowing Undoing:: How to make your functions undoable.
342 * Redisplay:: Functions to control line display.
343 * Modifying Text:: Functions to modify @code{rl_line_buffer}.
344 * Utility Functions:: Generally useful functions and hooks.
345 * Alternate Interface:: Using Readline in a `callback' fashion.
348 @node Function Naming
349 @subsection Naming a Function
351 The user can dynamically change the bindings of keys while using
352 Readline. This is done by representing the function with a descriptive
353 name. The user is able to type the descriptive name when referring to
354 the function. Thus, in an init file, one might find
357 Meta-Rubout: backward-kill-word
360 This binds the keystroke @key{Meta-Rubout} to the function
361 @emph{descriptively} named @code{backward-kill-word}. You, as the
362 programmer, should bind the functions you write to descriptive names as
363 well. Readline provides a function for doing that:
365 @deftypefun int rl_add_defun (char *name, Function *function, int key)
366 Add @var{name} to the list of named functions. Make @var{function} be
367 the function that gets called. If @var{key} is not -1, then bind it to
368 @var{function} using @code{rl_bind_key ()}.
371 Using this function alone is sufficient for most applications. It is
372 the recommended way to add a few functions to the default functions that
373 Readline has built in. If you need to do something other
374 than adding a function to Readline, you may need to use the
375 underlying functions described below.
378 @subsection Selecting a Keymap
380 Key bindings take place on a @dfn{keymap}. The keymap is the
381 association between the keys that the user types and the functions that
382 get run. You can make your own keymaps, copy existing keymaps, and tell
383 Readline which keymap to use.
385 @deftypefun Keymap rl_make_bare_keymap ()
386 Returns a new, empty keymap. The space for the keymap is allocated with
387 @code{malloc ()}; you should @code{free ()} it when you are done.
390 @deftypefun Keymap rl_copy_keymap (Keymap map)
391 Return a new keymap which is a copy of @var{map}.
394 @deftypefun Keymap rl_make_keymap ()
395 Return a new keymap with the printing characters bound to rl_insert,
396 the lowercase Meta characters bound to run their equivalents, and
397 the Meta digits bound to produce numeric arguments.
400 @deftypefun void rl_discard_keymap (Keymap keymap)
401 Free the storage associated with @var{keymap}.
404 Readline has several internal keymaps. These functions allow you to
405 change which keymap is active.
407 @deftypefun Keymap rl_get_keymap ()
408 Returns the currently active keymap.
411 @deftypefun void rl_set_keymap (Keymap keymap)
412 Makes @var{keymap} the currently active keymap.
415 @deftypefun Keymap rl_get_keymap_by_name (char *name)
416 Return the keymap matching @var{name}. @var{name} is one which would
417 be supplied in a @code{set keymap} inputrc line (@pxref{Readline Init File}).
421 @subsection Binding Keys
423 You associate keys with functions through the keymap. Readline has
424 several internal keymaps: @code{emacs_standard_keymap},
425 @code{emacs_meta_keymap}, @code{emacs_ctlx_keymap},
426 @code{vi_movement_keymap}, and @code{vi_insertion_keymap}.
427 @code{emacs_standard_keymap} is the default, and the examples in
428 this manual assume that.
430 These functions manage key bindings.
432 @deftypefun int rl_bind_key (int key, Function *function)
433 Binds @var{key} to @var{function} in the currently active keymap.
434 Returns non-zero in the case of an invalid @var{key}.
437 @deftypefun int rl_bind_key_in_map (int key, Function *function, Keymap map)
438 Bind @var{key} to @var{function} in @var{map}. Returns non-zero in the case
439 of an invalid @var{key}.
442 @deftypefun int rl_unbind_key (int key)
443 Bind @var{key} to the null function in the currently active keymap.
444 Returns non-zero in case of error.
447 @deftypefun int rl_unbind_key_in_map (int key, Keymap map)
448 Bind @var{key} to the null function in @var{map}.
449 Returns non-zero in case of error.
452 @deftypefun int rl_generic_bind (int type, char *keyseq, char *data, Keymap map)
453 Bind the key sequence represented by the string @var{keyseq} to the arbitrary
454 pointer @var{data}. @var{type} says what kind of data is pointed to by
455 @var{data}; this can be a function (@code{ISFUNC}), a macro
456 (@code{ISMACR}), or a keymap (@code{ISKMAP}). This makes new keymaps as
457 necessary. The initial keymap in which to do bindings is @var{map}.
460 @deftypefun int rl_parse_and_bind (char *line)
461 Parse @var{line} as if it had been read from the @code{inputrc} file and
462 perform any key bindings and variable assignments found
463 (@pxref{Readline Init File}).
466 @deftypefun int rl_read_init_file (char *filename)
467 Read keybindings and variable assignments from @var{filename}
468 (@pxref{Readline Init File}).
471 @node Associating Function Names and Bindings
472 @subsection Associating Function Names and Bindings
474 These functions allow you to find out what keys invoke named functions
475 and the functions invoked by a particular key sequence.
477 @deftypefun {Function *} rl_named_function (char *name)
478 Return the function with name @var{name}.
481 @deftypefun {Function *} rl_function_of_keyseq (char *keyseq, Keymap map, int *type)
482 Return the function invoked by @var{keyseq} in keymap @var{map}.
483 If @var{map} is NULL, the current keymap is used. If @var{type} is
484 not NULL, the type of the object is returned in it (one of @code{ISFUNC},
485 @code{ISKMAP}, or @code{ISMACR}).
488 @deftypefun {char **} rl_invoking_keyseqs (Function *function)
489 Return an array of strings representing the key sequences used to
490 invoke @var{function} in the current keymap.
493 @deftypefun {char **} rl_invoking_keyseqs_in_map (Function *function, Keymap map)
494 Return an array of strings representing the key sequences used to
495 invoke @var{function} in the keymap @var{map}.
498 @deftypefun void rl_function_dumper (int readable)
499 Print the readline function names and the key sequences currently
500 bound to them to @code{rl_outstream}. If @var{readable} is non-zero,
501 the list is formatted in such a way that it can be made part of an
502 @code{inputrc} file and re-read.
505 @deftypefun void rl_list_funmap_names ()
506 Print the names of all bindable Readline functions to @code{rl_outstream}.
509 @node Allowing Undoing
510 @subsection Allowing Undoing
512 Supporting the undo command is a painless thing, and makes your
513 functions much more useful. It is certainly easy to try
514 something if you know you can undo it. I could use an undo function for
517 If your function simply inserts text once, or deletes text once, and
518 uses @code{rl_insert_text ()} or @code{rl_delete_text ()} to do it, then
519 undoing is already done for you automatically.
521 If you do multiple insertions or multiple deletions, or any combination
522 of these operations, you should group them together into one operation.
523 This is done with @code{rl_begin_undo_group ()} and
524 @code{rl_end_undo_group ()}.
526 The types of events that can be undone are:
529 enum undo_code @{ UNDO_DELETE, UNDO_INSERT, UNDO_BEGIN, UNDO_END @};
532 Notice that @code{UNDO_DELETE} means to insert some text, and
533 @code{UNDO_INSERT} means to delete some text. That is, the undo code
534 tells undo what to undo, not how to undo it. @code{UNDO_BEGIN} and
535 @code{UNDO_END} are tags added by @code{rl_begin_undo_group ()} and
536 @code{rl_end_undo_group ()}.
538 @deftypefun int rl_begin_undo_group ()
539 Begins saving undo information in a group construct. The undo
540 information usually comes from calls to @code{rl_insert_text ()} and
541 @code{rl_delete_text ()}, but could be the result of calls to
542 @code{rl_add_undo ()}.
545 @deftypefun int rl_end_undo_group ()
546 Closes the current undo group started with @code{rl_begin_undo_group
547 ()}. There should be one call to @code{rl_end_undo_group ()}
548 for each call to @code{rl_begin_undo_group ()}.
551 @deftypefun void rl_add_undo (enum undo_code what, int start, int end, char *text)
552 Remember how to undo an event (according to @var{what}). The affected
553 text runs from @var{start} to @var{end}, and encompasses @var{text}.
556 @deftypefun void free_undo_list ()
557 Free the existing undo list.
560 @deftypefun int rl_do_undo ()
561 Undo the first thing on the undo list. Returns @code{0} if there was
562 nothing to undo, non-zero if something was undone.
565 Finally, if you neither insert nor delete text, but directly modify the
566 existing text (e.g., change its case), call @code{rl_modifying ()}
567 once, just before you modify the text. You must supply the indices of
568 the text range that you are going to modify.
570 @deftypefun int rl_modifying (int start, int end)
571 Tell Readline to save the text between @var{start} and @var{end} as a
572 single undo unit. It is assumed that you will subsequently modify
577 @subsection Redisplay
579 @deftypefun int rl_redisplay ()
580 Change what's displayed on the screen to reflect the current contents
581 of @code{rl_line_buffer}.
584 @deftypefun int rl_forced_update_display ()
585 Force the line to be updated and redisplayed, whether or not
586 Readline thinks the screen display is correct.
589 @deftypefun int rl_on_new_line ()
590 Tell the update routines that we have moved onto a new (empty) line,
591 usually after ouputting a newline.
594 @deftypefun int rl_reset_line_state ()
595 Reset the display state to a clean state and redisplay the current line
596 starting on a new line.
599 @deftypefun int rl_message (va_alist)
600 The arguments are a string as would be supplied to @code{printf}. The
601 resulting string is displayed in the @dfn{echo area}. The echo area
602 is also used to display numeric arguments and search strings.
605 @deftypefun int rl_clear_message ()
606 Clear the message in the echo area.
610 @subsection Modifying Text
612 @deftypefun int rl_insert_text (char *text)
613 Insert @var{text} into the line at the current cursor position.
616 @deftypefun int rl_delete_text (int start, int end)
617 Delete the text between @var{start} and @var{end} in the current line.
620 @deftypefun {char *} rl_copy_text (int start, int end)
621 Return a copy of the text between @var{start} and @var{end} in
625 @deftypefun int rl_kill_text (int start, int end)
626 Copy the text between @var{start} and @var{end} in the current line
627 to the kill ring, appending or prepending to the last kill if the
628 last command was a kill command. The text is deleted.
629 If @var{start} is less than @var{end},
630 the text is appended, otherwise prepended. If the last command was
631 not a kill, a new kill ring slot is used.
634 @node Utility Functions
635 @subsection Utility Functions
637 @deftypefun int rl_read_key ()
638 Return the next character available. This handles input inserted into
639 the input stream via @var{pending input} (@pxref{Readline Variables})
640 and @code{rl_stuff_char ()}, macros, and characters read from the keyboard.
643 @deftypefun int rl_getc (FILE *)
644 Return the next character available from the keyboard.
647 @deftypefun int rl_stuff_char (int c)
648 Insert @var{c} into the Readline input stream. It will be "read"
649 before Readline attempts to read characters from the terminal with
650 @code{rl_read_key ()}.
653 @deftypefun int rl_initialize ()
654 Initialize or re-initialize Readline's internal state.
657 @deftypefun int rl_reset_terminal (char *terminal_name)
658 Reinitialize Readline's idea of the terminal settings using
659 @var{terminal_name} as the terminal type (e.g., @code{vt100}).
662 @deftypefun int alphabetic (int c)
663 Return 1 if @var{c} is an alphabetic character.
666 @deftypefun int numeric (int c)
667 Return 1 if @var{c} is a numeric character.
670 @deftypefun int ding ()
671 Ring the terminal bell, obeying the setting of @code{bell-style}.
674 The following are implemented as macros, defined in @code{chartypes.h}.
676 @deftypefun int uppercase_p (int c)
677 Return 1 if @var{c} is an uppercase alphabetic character.
680 @deftypefun int lowercase_p (int c)
681 Return 1 if @var{c} is a lowercase alphabetic character.
684 @deftypefun int digit_p (int c)
685 Return 1 if @var{c} is a numeric character.
688 @deftypefun int to_upper (int c)
689 If @var{c} is a lowercase alphabetic character, return the corresponding
693 @deftypefun int to_lower (int c)
694 If @var{c} is an uppercase alphabetic character, return the corresponding
698 @deftypefun int digit_value (int c)
699 If @var{c} is a number, return the value it represents.
702 @node Alternate Interface
703 @subsection Alternate Interface
705 An alternate interface is available to plain @code{readline()}. Some
706 applications need to interleave keyboard I/O with file, device, or
707 window system I/O, typically by using a main loop to @code{select()}
708 on various file descriptors. To accomodate this need, readline can
709 also be invoked as a `callback' function from an event loop. There
710 are functions available to make this easy.
712 @deftypefun void rl_callback_handler_install (char *prompt, Vfunction *lhandler)
713 Set up the terminal for readline I/O and display the initial
714 expanded value of @var{prompt}. Save the value of @var{lhandler} to
715 use as a callback when a complete line of input has been entered.
718 @deftypefun void rl_callback_read_char ()
719 Whenever an application determines that keyboard input is available, it
720 should call @code{rl_callback_read_char()}, which will read the next
721 character from the current input source. If that character completes the
722 line, @code{rl_callback_read_char} will invoke the @var{lhandler}
723 function saved by @code{rl_callback_handler_install} to process the
724 line. @code{EOF} is indicated by calling @var{lhandler} with a
728 @deftypefun void rl_callback_handler_remove ()
729 Restore the terminal to its initial state and remove the line handler.
730 This may be called from within a callback as well as independently.
733 @subsection An Example
735 Here is a function which changes lowercase characters to their uppercase
736 equivalents, and uppercase characters to lowercase. If
737 this function was bound to @samp{M-c}, then typing @samp{M-c} would
738 change the case of the character under point. Typing @samp{M-1 0 M-c}
739 would change the case of the following 10 characters, leaving the cursor on
740 the last character changed.
743 /* Invert the case of the COUNT following characters. */
745 invert_case_line (count, key)
748 register int start, end, i;
752 if (rl_point >= rl_end)
763 /* Find the end of the range to modify. */
764 end = start + (count * direction);
766 /* Force it to be within range. */
782 /* Tell readline that we are modifying the line, so it will save
783 the undo information. */
784 rl_modifying (start, end);
786 for (i = start; i != end; i++)
788 if (uppercase_p (rl_line_buffer[i]))
789 rl_line_buffer[i] = to_lower (rl_line_buffer[i]);
790 else if (lowercase_p (rl_line_buffer[i]))
791 rl_line_buffer[i] = to_upper (rl_line_buffer[i]);
793 /* Move point to on top of the last character changed. */
794 rl_point = (direction == 1) ? end - 1 : start;
799 @node Custom Completers
800 @section Custom Completers
802 Typically, a program that reads commands from the user has a way of
803 disambiguating commands and data. If your program is one of these, then
804 it can provide completion for commands, data, or both.
805 The following sections describe how your program and Readline
806 cooperate to provide this service.
809 * How Completing Works:: The logic used to do completion.
810 * Completion Functions:: Functions provided by Readline.
811 * Completion Variables:: Variables which control completion.
812 * A Short Completion Example:: An example of writing completer subroutines.
815 @node How Completing Works
816 @subsection How Completing Works
818 In order to complete some text, the full list of possible completions
819 must be available. That is, it is not possible to accurately
820 expand a partial word without knowing all of the possible words
821 which make sense in that context. The Readline library provides
822 the user interface to completion, and two of the most common
823 completion functions: filename and username. For completing other types
824 of text, you must write your own completion function. This section
825 describes exactly what such functions must do, and provides an example.
827 There are three major functions used to perform completion:
831 The user-interface function @code{rl_complete ()}. This function is
832 called with the same arguments as other Readline
833 functions intended for interactive use: @var{count} and
834 @var{invoking_key}. It isolates the word to be completed and calls
835 @code{completion_matches ()} to generate a list of possible completions.
836 It then either lists the possible completions, inserts the possible
837 completions, or actually performs the
838 completion, depending on which behavior is desired.
841 The internal function @code{completion_matches ()} uses your
842 @dfn{generator} function to generate the list of possible matches, and
843 then returns the array of these matches. You should place the address
844 of your generator function in @code{rl_completion_entry_function}.
847 The generator function is called repeatedly from
848 @code{completion_matches ()}, returning a string each time. The
849 arguments to the generator function are @var{text} and @var{state}.
850 @var{text} is the partial word to be completed. @var{state} is zero the
851 first time the function is called, allowing the generator to perform
852 any necessary initialization, and a positive non-zero integer for
853 each subsequent call. When the generator function returns
854 @code{(char *)NULL} this signals @code{completion_matches ()} that there are
855 no more possibilities left. Usually the generator function computes the
856 list of possible completions when @var{state} is zero, and returns them
857 one at a time on subsequent calls. Each string the generator function
858 returns as a match must be allocated with @code{malloc()}; Readline
859 frees the strings when it has finished with them.
863 @deftypefun int rl_complete (int ignore, int invoking_key)
864 Complete the word at or before point. You have supplied the function
865 that does the initial simple matching selection algorithm (see
866 @code{completion_matches ()}). The default is to do filename completion.
869 @deftypevar {Function *} rl_completion_entry_function
870 This is a pointer to the generator function for @code{completion_matches
871 ()}. If the value of @code{rl_completion_entry_function} is
872 @code{(Function *)NULL} then the default filename generator function,
873 @code{filename_entry_function ()}, is used.
876 @node Completion Functions
877 @subsection Completion Functions
879 Here is the complete list of callable completion functions present in
882 @deftypefun int rl_complete_internal (int what_to_do)
883 Complete the word at or before point. @var{what_to_do} says what to do
884 with the completion. A value of @samp{?} means list the possible
885 completions. @samp{TAB} means do standard completion. @samp{*} means
886 insert all of the possible completions. @samp{!} means to display
887 all of the possible completions, if there is more than one, as well as
888 performing partial completion.
891 @deftypefun int rl_complete (int ignore, int invoking_key)
892 Complete the word at or before point. You have supplied the function
893 that does the initial simple matching selection algorithm (see
894 @code{completion_matches ()} and @code{rl_completion_entry_function}).
895 The default is to do filename
896 completion. This calls @code{rl_complete_internal ()} with an
897 argument depending on @var{invoking_key}.
900 @deftypefun int rl_possible_completions (int count, int invoking_key))
901 List the possible completions. See description of @code{rl_complete
902 ()}. This calls @code{rl_complete_internal ()} with an argument of
906 @deftypefun int rl_insert_completions (int count, int invoking_key))
907 Insert the list of possible completions into the line, deleting the
908 partially-completed word. See description of @code{rl_complete ()}.
909 This calls @code{rl_complete_internal ()} with an argument of @samp{*}.
912 @deftypefun {char **} completion_matches (char *text, CPFunction *entry_func)
913 Returns an array of @code{(char *)} which is a list of completions for
914 @var{text}. If there are no completions, returns @code{(char **)NULL}.
915 The first entry in the returned array is the substitution for @var{text}.
916 The remaining entries are the possible completions. The array is
917 terminated with a @code{NULL} pointer.
919 @var{entry_func} is a function of two args, and returns a
920 @code{(char *)}. The first argument is @var{text}. The second is a
921 state argument; it is zero on the first call, and non-zero on subsequent
922 calls. @var{entry_func} returns a @code{NULL} pointer to the caller
923 when there are no more matches.
926 @deftypefun {char *} filename_completion_function (char *text, int state)
927 A generator function for filename completion in the general case. Note
928 that completion in Bash is a little different because of all
929 the pathnames that must be followed when looking up completions for a
930 command. The Bash source is a useful reference for writing custom
931 completion functions.
934 @deftypefun {char *} username_completion_function (char *text, int state)
935 A completion generator for usernames. @var{text} contains a partial
936 username preceded by a random character (usually @samp{~}). As with all
937 completion generators, @var{state} is zero on the first call and non-zero
938 for subsequent calls.
941 @node Completion Variables
942 @subsection Completion Variables
944 @deftypevar {Function *} rl_completion_entry_function
945 A pointer to the generator function for @code{completion_matches ()}.
946 @code{NULL} means to use @code{filename_entry_function ()}, the default
950 @deftypevar {CPPFunction *} rl_attempted_completion_function
951 A pointer to an alternative function to create matches.
952 The function is called with @var{text}, @var{start}, and @var{end}.
953 @var{start} and @var{end} are indices in @code{rl_line_buffer} saying
954 what the boundaries of @var{text} are. If this function exists and
955 returns @code{NULL}, or if this variable is set to @code{NULL}, then
956 @code{rl_complete ()} will call the value of
957 @code{rl_completion_entry_function} to generate matches, otherwise the
958 array of strings returned will be used.
961 @deftypevar {CPFunction *} rl_filename_quoting_function
962 A pointer to a function that will quote a filename in an application-
963 specific fashion. This is called if filename completion is being
964 attempted and one of the characters in @code{rl_filename_quote_characters}
965 appears in a completed filename. The function is called with
966 @var{text}, @var{match_type}, and @var{quote_pointer}. The @var{text}
967 is the filename to be quoted. The @var{match_type} is either
968 @code{SINGLE_MATCH}, if there is only one completion match, or
969 @code{MULT_MATCH}. Some functions use this to decide whether or not to
970 insert a closing quote character. The @var{quote_pointer} is a pointer
971 to any opening quote character the user typed. Some functions choose
972 to reset this character.
975 @deftypevar {CPFunction *} rl_filename_dequoting_function
976 A pointer to a function that will remove application-specific quoting
977 characters from a filename before completion is attempted, so those
978 characters do not interfere with matching the text against names in
979 the filesystem. It is called with @var{text}, the text of the word
980 to be dequoted, and @var{quote_char}, which is the quoting character
981 that delimits the filename (usually @samp{'} or @samp{"}). If
982 @var{quote_char} is zero, the filename was not in an embedded string.
985 @deftypevar {Function *} rl_char_is_quoted_p
986 A pointer to a function to call that determines whether or not a specific
987 character in the line buffer is quoted, according to whatever quoting
988 mechanism the program calling readline uses. The function is called with
989 two arguments: @var{text}, the text of the line, and @var{index}, the
990 index of the character in the line. It is used to decide whether a
991 character found in @code{rl_completer_word_break_characters} should be
992 used to break words for the completer.
995 @deftypevar int rl_completion_query_items
996 Up to this many items will be displayed in response to a
997 possible-completions call. After that, we ask the user if she is sure
998 she wants to see them all. The default value is 100.
1001 @deftypevar {char *} rl_basic_word_break_characters
1002 The basic list of characters that signal a break between words for the
1003 completer routine. The default value of this variable is the characters
1004 which break words for completion in Bash, i.e.,
1005 @code{" \t\n\"\\'`@@$><=;|&@{("}.
1008 @deftypevar {char *} rl_basic_quote_characters
1009 List of quote characters which can cause a word break.
1012 @deftypevar {char *} rl_completer_word_break_characters
1013 The list of characters that signal a break between words for
1014 @code{rl_complete_internal ()}. The default list is the value of
1015 @code{rl_basic_word_break_characters}.
1018 @deftypevar {char *} rl_completer_quote_characters
1019 List of characters which can be used to quote a substring of the line.
1020 Completion occurs on the entire substring, and within the substring
1021 @code{rl_completer_word_break_characters} are treated as any other character,
1022 unless they also appear within this list.
1025 @deftypevar {char *} rl_filename_quote_characters
1026 A list of characters that cause a filename to be quoted by the completer
1027 when they appear in a completed filename. The default is empty.
1030 @deftypevar {char *} rl_special_prefixes
1031 The list of characters that are word break characters, but should be
1032 left in @var{text} when it is passed to the completion function.
1033 Programs can use this to help determine what kind of completing to do.
1034 For instance, Bash sets this variable to "$@@" so that it can complete
1035 shell variables and hostnames.
1038 @deftypevar {int} rl_completion_append_character
1039 When a single completion alternative matches at the end of the command
1040 line, this character is appended to the inserted completion text. The
1041 default is a space character (@samp{ }). Setting this to the null
1042 character (@samp{\0}) prevents anything being appended automatically.
1043 This can be changed in custom completion functions to
1044 provide the ``most sensible word separator character'' according to
1045 an application-specific command line syntax specification.
1048 @deftypevar int rl_ignore_completion_duplicates
1049 If non-zero, then disallow duplicates in the matches. Default is 1.
1052 @deftypevar int rl_filename_completion_desired
1053 Non-zero means that the results of the matches are to be treated as
1054 filenames. This is @emph{always} zero on entry, and can only be changed
1055 within a completion entry generator function. If it is set to a non-zero
1056 value, directory names have a slash appended and Readline attempts to
1057 quote completed filenames if they contain any embedded word break
1061 @deftypevar int rl_filename_quoting_desired
1062 Non-zero means that the results of the matches are to be quoted using
1063 double quotes (or an application-specific quoting mechanism) if the
1064 completed filename contains any characters in
1065 @code{rl_filename_quote_chars}. This is @emph{always} non-zero
1066 on entry, and can only be changed within a completion entry generator
1067 function. The quoting is effected via a call to the function pointed to
1068 by @code{rl_filename_quoting_function}.
1071 @deftypevar int rl_inhibit_completion
1072 If this variable is non-zero, completion is inhibited. The completion
1073 character will be inserted as any other bound to @code{self-insert}.
1076 @deftypevar {Function *} rl_ignore_some_completions_function
1077 This function, if defined, is called by the completer when real filename
1078 completion is done, after all the matching names have been generated.
1079 It is passed a @code{NULL} terminated array of matches.
1080 The first element (@code{matches[0]}) is the
1081 maximal substring common to all matches. This function can
1082 re-arrange the list of matches as required, but each element deleted
1083 from the array must be freed.
1086 @deftypevar {Function *} rl_directory_completion_hook
1087 This function, if defined, is allowed to modify the directory portion
1088 of filenames Readline completes. It is called with the address of a
1089 string (the current directory name) as an argument. It could be used
1090 to expand symbolic links or shell variables in pathnames.
1093 @node A Short Completion Example
1094 @subsection A Short Completion Example
1096 Here is a small application demonstrating the use of the GNU Readline
1097 library. It is called @code{fileman}, and the source code resides in
1098 @file{examples/fileman.c}. This sample application provides
1099 completion of command names, line editing features, and access to the
1104 /* fileman.c -- A tiny application which demonstrates how to use the
1105 GNU Readline library. This application interactively allows users
1106 to manipulate files and their modes. */
1109 #include <sys/types.h>
1110 #include <sys/file.h>
1111 #include <sys/stat.h>
1112 #include <sys/errno.h>
1114 #include <readline/readline.h>
1115 #include <readline/history.h>
1117 extern char *getwd ();
1118 extern char *xmalloc ();
1120 /* The names of functions that actually do the manipulation. */
1121 int com_list (), com_view (), com_rename (), com_stat (), com_pwd ();
1122 int com_delete (), com_help (), com_cd (), com_quit ();
1124 /* A structure which contains information on the commands this program
1128 char *name; /* User printable name of the function. */
1129 Function *func; /* Function to call to do the job. */
1130 char *doc; /* Documentation for this function. */
1133 COMMAND commands[] = @{
1134 @{ "cd", com_cd, "Change to directory DIR" @},
1135 @{ "delete", com_delete, "Delete FILE" @},
1136 @{ "help", com_help, "Display this text" @},
1137 @{ "?", com_help, "Synonym for `help'" @},
1138 @{ "list", com_list, "List files in DIR" @},
1139 @{ "ls", com_list, "Synonym for `list'" @},
1140 @{ "pwd", com_pwd, "Print the current working directory" @},
1141 @{ "quit", com_quit, "Quit using Fileman" @},
1142 @{ "rename", com_rename, "Rename FILE to NEWNAME" @},
1143 @{ "stat", com_stat, "Print out statistics on FILE" @},
1144 @{ "view", com_view, "View the contents of FILE" @},
1145 @{ (char *)NULL, (Function *)NULL, (char *)NULL @}
1148 /* Forward declarations. */
1149 char *stripwhite ();
1150 COMMAND *find_command ();
1152 /* The name of this program, as taken from argv[0]. */
1155 /* When non-zero, this global means the user is done using this program. */
1164 r = xmalloc (strlen (s) + 1);
1177 initialize_readline (); /* Bind our completer. */
1179 /* Loop reading and executing lines until the user quits. */
1180 for ( ; done == 0; )
1182 line = readline ("FileMan: ");
1187 /* Remove leading and trailing whitespace from the line.
1188 Then, if there is anything left, add it to the history list
1190 s = stripwhite (line);
1203 /* Execute a command line. */
1212 /* Isolate the command word. */
1214 while (line[i] && whitespace (line[i]))
1218 while (line[i] && !whitespace (line[i]))
1224 command = find_command (word);
1228 fprintf (stderr, "%s: No such command for FileMan.\n", word);
1232 /* Get argument to command, if any. */
1233 while (whitespace (line[i]))
1238 /* Call the function. */
1239 return ((*(command->func)) (word));
1242 /* Look up NAME as the name of a command, and return a pointer to that
1243 command. Return a NULL pointer if NAME isn't a command name. */
1250 for (i = 0; commands[i].name; i++)
1251 if (strcmp (name, commands[i].name) == 0)
1252 return (&commands[i]);
1254 return ((COMMAND *)NULL);
1257 /* Strip whitespace from the start and end of STRING. Return a pointer
1263 register char *s, *t;
1265 for (s = string; whitespace (*s); s++)
1271 t = s + strlen (s) - 1;
1272 while (t > s && whitespace (*t))
1279 /* **************************************************************** */
1281 /* Interface to Readline Completion */
1283 /* **************************************************************** */
1285 char *command_generator ();
1286 char **fileman_completion ();
1288 /* Tell the GNU Readline library how to complete. We want to try to complete
1289 on command names if this is the first word in the line, or on filenames
1291 initialize_readline ()
1293 /* Allow conditional parsing of the ~/.inputrc file. */
1294 rl_readline_name = "FileMan";
1296 /* Tell the completer that we want a crack first. */
1297 rl_attempted_completion_function = (CPPFunction *)fileman_completion;
1300 /* Attempt to complete on the contents of TEXT. START and END bound the
1301 region of rl_line_buffer that contains the word to complete. TEXT is
1302 the word to complete. We can use the entire contents of rl_line_buffer
1303 in case we want to do some simple parsing. Return the array of matches,
1304 or NULL if there aren't any. */
1306 fileman_completion (text, start, end)
1312 matches = (char **)NULL;
1314 /* If this word is at the start of the line, then it is a command
1315 to complete. Otherwise it is the name of a file in the current
1318 matches = completion_matches (text, command_generator);
1323 /* Generator function for command completion. STATE lets us know whether
1324 to start from scratch; without any state (i.e. STATE == 0), then we
1325 start at the top of the list. */
1327 command_generator (text, state)
1331 static int list_index, len;
1334 /* If this is a new word to complete, initialize now. This includes
1335 saving the length of TEXT for efficiency, and initializing the index
1340 len = strlen (text);
1343 /* Return the next name which partially matches from the command list. */
1344 while (name = commands[list_index].name)
1348 if (strncmp (name, text, len) == 0)
1349 return (dupstr(name));
1352 /* If no names matched, then return NULL. */
1353 return ((char *)NULL);
1356 /* **************************************************************** */
1358 /* FileMan Commands */
1360 /* **************************************************************** */
1362 /* String to pass to system (). This is for the LIST, VIEW and RENAME
1364 static char syscom[1024];
1366 /* List the file(s) named in arg. */
1373 sprintf (syscom, "ls -FClg %s", arg);
1374 return (system (syscom));
1380 if (!valid_argument ("view", arg))
1383 sprintf (syscom, "more %s", arg);
1384 return (system (syscom));
1390 too_dangerous ("rename");
1399 if (!valid_argument ("stat", arg))
1402 if (stat (arg, &finfo) == -1)
1408 printf ("Statistics for `%s':\n", arg);
1410 printf ("%s has %d link%s, and is %d byte%s in length.\n", arg,
1412 (finfo.st_nlink == 1) ? "" : "s",
1414 (finfo.st_size == 1) ? "" : "s");
1415 printf ("Inode Last Change at: %s", ctime (&finfo.st_ctime));
1416 printf (" Last access at: %s", ctime (&finfo.st_atime));
1417 printf (" Last modified at: %s", ctime (&finfo.st_mtime));
1424 too_dangerous ("delete");
1428 /* Print out help for ARG, or for all of the commands if ARG is
1436 for (i = 0; commands[i].name; i++)
1438 if (!*arg || (strcmp (arg, commands[i].name) == 0))
1440 printf ("%s\t\t%s.\n", commands[i].name, commands[i].doc);
1447 printf ("No commands match `%s'. Possibilties are:\n", arg);
1449 for (i = 0; commands[i].name; i++)
1451 /* Print in six columns. */
1458 printf ("%s\t", commands[i].name);
1468 /* Change to the directory ARG. */
1472 if (chdir (arg) == -1)
1482 /* Print out the current working directory. */
1491 printf ("Error getting pwd: %s\n", dir);
1495 printf ("Current directory is %s\n", dir);
1499 /* The user wishes to quit using this program. Just set DONE non-zero. */
1507 /* Function which tells you that you can't do this. */
1508 too_dangerous (caller)
1512 "%s: Too dangerous for me to distribute. Write it yourself.\n",
1516 /* Return non-zero if ARG is a valid argument for CALLER, else print
1517 an error message and return zero. */
1519 valid_argument (caller, arg)
1524 fprintf (stderr, "%s: Argument required.\n", caller);