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-2001 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 @sc{gnu} Readline Library and
39 other programs. If you are a programmer, and you wish to include the
40 features found in @sc{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 custom
52 * Readline Signal Handling:: How Readline behaves when it receives signals.
53 * Custom Completers:: Supplanting or supplementing Readline's
58 @section Basic Behavior
60 Many programs provide a command line interface, such as @code{mail},
61 @code{ftp}, and @code{sh}. For such programs, the default behaviour of
62 Readline is sufficient. This section describes how to use Readline in
63 the simplest way possible, perhaps to replace calls in your code to
64 @code{gets()} or @code{fgets()}.
67 @cindex readline, function
69 The function @code{readline()} prints a prompt @var{prompt}
70 and then reads and returns a single line of text from the user.
71 If @var{prompt} is @code{NULL} or the empty string, no prompt is displayed.
72 The line @code{readline} returns is allocated with @code{malloc()};
73 the caller should @code{free()} the line when it has finished with it.
74 The declaration for @code{readline} in ANSI C is
77 @code{char *readline (const char *@var{prompt});}
83 @code{char *line = readline ("Enter a line: ");}
86 in order to read a line of text from the user.
87 The line returned has the final newline removed, so only the
90 If @code{readline} encounters an @code{EOF} while reading the line, and the
91 line is empty at that point, then @code{(char *)NULL} is returned.
92 Otherwise, the line is ended just as if a newline had been typed.
94 If you want the user to be able to get at the line later, (with
95 @key{C-p} for example), you must call @code{add_history()} to save the
96 line away in a @dfn{history} list of such lines.
99 @code{add_history (line)};
103 For full details on the GNU History Library, see the associated manual.
105 It is preferable to avoid saving empty lines on the history list, since
106 users rarely have a burning need to reuse a blank line. Here is
107 a function which usefully replaces the standard @code{gets()} library
108 function, and has the advantage of no static buffer to overflow:
111 /* A static variable for holding the line. */
112 static char *line_read = (char *)NULL;
114 /* Read a string, and return a pointer to it. Returns NULL on EOF. */
118 /* If the buffer has already been allocated, return the memory
123 line_read = (char *)NULL;
126 /* Get a line from the user. */
127 line_read = readline ("");
129 /* If the line has any text in it, save it on the history. */
130 if (line_read && *line_read)
131 add_history (line_read);
137 This function gives the user the default behaviour of @key{TAB}
138 completion: completion on file names. If you do not want Readline to
139 complete on filenames, you can change the binding of the @key{TAB} key
140 with @code{rl_bind_key()}.
143 @code{int rl_bind_key (int @var{key}, rl_command_func_t *@var{function});}
146 @code{rl_bind_key()} takes two arguments: @var{key} is the character that
147 you want to bind, and @var{function} is the address of the function to
148 call when @var{key} is pressed. Binding @key{TAB} to @code{rl_insert()}
149 makes @key{TAB} insert itself.
150 @code{rl_bind_key()} returns non-zero if @var{key} is not a valid
151 ASCII character code (between 0 and 255).
153 Thus, to disable the default @key{TAB} behavior, the following suffices:
155 @code{rl_bind_key ('\t', rl_insert);}
158 This code should be executed once at the start of your program; you
159 might write a function called @code{initialize_readline()} which
160 performs this and other desired initializations, such as installing
161 custom completers (@pxref{Custom Completers}).
163 @node Custom Functions
164 @section Custom Functions
166 Readline provides many functions for manipulating the text of
167 the line, but it isn't possible to anticipate the needs of all
168 programs. This section describes the various functions and variables
169 defined within the Readline library which allow a user program to add
170 customized functionality to Readline.
172 Before declaring any functions that customize Readline's behavior, or
173 using any functionality Readline provides in other code, an
174 application writer should include the file @code{<readline/readline.h>}
175 in any file that uses Readline's features. Since some of the definitions
176 in @code{readline.h} use the @code{stdio} library, the file
177 @code{<stdio.h>} should be included before @code{readline.h}.
180 * Readline Typedefs:: C declarations to make code readable.
181 * Function Writing:: Variables and calling conventions.
184 @node Readline Typedefs
185 @subsection Readline Typedefs
187 For readabilty, we declare a number of new object types, all pointers
190 The reason for declaring these new types is to make it easier to write
191 code describing pointers to C functions with appropriately prototyped
192 arguments and return values.
194 For instance, say we want to declare a variable @var{func} as a pointer
195 to a function which takes two @code{int} arguments and returns an
196 @code{int} (this is the type of all of the Readline bindable functions).
197 Instead of the classic C declaration
199 @code{int (*func)();}
202 or the ANSI-C style declaration
204 @code{int (*func)(int, int);}
209 @code{rl_command_func_t *func;}
211 The full list of function pointer types available is
214 @item typedef int rl_command_func_t (int, int);
216 @item typedef char *rl_compentry_func_t (const char *, int);
218 @item typedef char **rl_completion_func_t (const char *, int, int);
220 @item typedef char *rl_quote_func_t (char *, int, char *);
222 @item typedef char *rl_dequote_func_t (char *, int);
224 @item typedef int rl_compignore_func_t (char **);
226 @item typedef void rl_compdisp_func_t (char **, int, int);
228 @item typedef int rl_hook_func_t (void);
230 @item typedef int rl_getc_func_t (FILE *);
232 @item typedef int rl_linebuf_func_t (char *, int);
234 @item typedef int rl_intfunc_t (int);
235 @item #define rl_ivoidfunc_t rl_hook_func_t
236 @item typedef int rl_icpfunc_t (char *);
237 @item typedef int rl_icppfunc_t (char **);
239 @item typedef void rl_voidfunc_t (void);
240 @item typedef void rl_vintfunc_t (int);
241 @item typedef void rl_vcpfunc_t (char *);
242 @item typedef void rl_vcppfunc_t (char **);
246 @node Function Writing
247 @subsection Writing a New Function
249 In order to write new functions for Readline, you need to know the
250 calling conventions for keyboard-invoked functions, and the names of the
251 variables that describe the current state of the line read so far.
253 The calling sequence for a command @code{foo} looks like
256 @code{foo (int count, int key)}
260 where @var{count} is the numeric argument (or 1 if defaulted) and
261 @var{key} is the key that invoked this function.
263 It is completely up to the function as to what should be done with the
264 numeric argument. Some functions use it as a repeat count, some
265 as a flag, and others to choose alternate behavior (refreshing the current
266 line as opposed to refreshing the screen, for example). Some choose to
267 ignore it. In general, if a
268 function uses the numeric argument as a repeat count, it should be able
269 to do something useful with both negative and positive arguments.
270 At the very least, it should be aware that it can be passed a
273 @node Readline Variables
274 @section Readline Variables
276 These variables are available to function writers.
278 @deftypevar {char *} rl_line_buffer
279 This is the line gathered so far. You are welcome to modify the
280 contents of the line, but see @ref{Allowing Undoing}. The
281 function @code{rl_extend_line_buffer} is available to increase
282 the memory allocated to @code{rl_line_buffer}.
285 @deftypevar int rl_point
286 The offset of the current cursor position in @code{rl_line_buffer}
290 @deftypevar int rl_end
291 The number of characters present in @code{rl_line_buffer}. When
292 @code{rl_point} is at the end of the line, @code{rl_point} and
293 @code{rl_end} are equal.
296 @deftypevar int rl_mark
297 The @var{mark} (saved position) in the current line. If set, the mark
298 and point define a @emph{region}.
301 @deftypevar int rl_done
302 Setting this to a non-zero value causes Readline to return the current
306 @deftypevar int rl_num_chars_to_read
307 Setting this to a positive value before calling @code{readline()} causes
308 Readline to return after accepting that many characters, rather
309 than reading up to a character bound to @code{accept-line}.
312 @deftypevar int rl_pending_input
313 Setting this to a value makes it the next keystroke read. This is a
314 way to stuff a single character into the input stream.
317 @deftypevar int rl_dispatching
318 Set to a non-zero value if a function is being called from a key binding;
319 zero otherwise. Application functions can test this to discover whether
320 they were called directly or by Readline's dispatching mechanism.
323 @deftypevar int rl_erase_empty_line
324 Setting this to a non-zero value causes Readline to completely erase
325 the current line, including any prompt, any time a newline is typed as
326 the only character on an otherwise-empty line. The cursor is moved to
327 the beginning of the newly-blank line.
330 @deftypevar {char *} rl_prompt
331 The prompt Readline uses. This is set from the argument to
332 @code{readline()}, and should not be assigned to directly.
333 The @code{rl_set_prompt()} function (@pxref{Redisplay}) may
334 be used to modify the prompt string after calling @code{readline()}.
337 @deftypevar int rl_already_prompted
338 If an application wishes to display the prompt itself, rather than have
339 Readline do it the first time @code{readline()} is called, it should set
340 this variable to a non-zero value after displaying the prompt.
341 The prompt must also be passed as the argument to @code{readline()} so
342 the redisplay functions can update the display properly.
343 The calling application is responsible for managing the value; Readline
347 @deftypevar {const char *} rl_library_version
348 The version number of this revision of the library.
351 @deftypevar {int} rl_gnu_readline_p
352 Always set to 1, denoting that this is @sc{gnu} readline rather than some
356 @deftypevar {const char *} rl_terminal_name
357 The terminal type, used for initialization. If not set by the application,
358 Readline sets this to the value of the @env{TERM} environment variable
359 the first time it is called.
362 @deftypevar {const char *} rl_readline_name
363 This variable is set to a unique name by each application using Readline.
364 The value allows conditional parsing of the inputrc file
365 (@pxref{Conditional Init Constructs}).
368 @deftypevar {FILE *} rl_instream
369 The stdio stream from which Readline reads input.
372 @deftypevar {FILE *} rl_outstream
373 The stdio stream to which Readline performs output.
376 @deftypevar {rl_command_func_t *} rl_last_func
377 The address of the last command function Readline executed. May be used to
378 test whether or not a function is being executed twice in succession, for
382 @deftypevar {rl_hook_func_t *} rl_startup_hook
383 If non-zero, this is the address of a function to call just
384 before @code{readline} prints the first prompt.
387 @deftypevar {rl_hook_func_t *} rl_pre_input_hook
388 If non-zero, this is the address of a function to call after
389 the first prompt has been printed and just before @code{readline}
390 starts reading input characters.
393 @deftypevar {rl_hook_func_t *} rl_event_hook
394 If non-zero, this is the address of a function to call periodically
395 when Readline is waiting for terminal input.
396 By default, this will be called at most ten times a second if there
397 is no keyboard input.
400 @deftypevar {rl_getc_func_t *} rl_getc_function
401 If non-zero, Readline will call indirectly through this pointer
402 to get a character from the input stream. By default, it is set to
403 @code{rl_getc}, the default Readline character input function
404 (@pxref{Character Input}).
407 @deftypevar {rl_voidfunc_t *} rl_redisplay_function
408 If non-zero, Readline will call indirectly through this pointer
409 to update the display with the current contents of the editing buffer.
410 By default, it is set to @code{rl_redisplay}, the default Readline
411 redisplay function (@pxref{Redisplay}).
414 @deftypevar {rl_vintfunc_t *} rl_prep_term_function
415 If non-zero, Readline will call indirectly through this pointer
416 to initialize the terminal. The function takes a single argument, an
417 @code{int} flag that says whether or not to use eight-bit characters.
418 By default, this is set to @code{rl_prep_terminal}
419 (@pxref{Terminal Management}).
422 @deftypevar {rl_voidfunc_t *} rl_deprep_term_function
423 If non-zero, Readline will call indirectly through this pointer
424 to reset the terminal. This function should undo the effects of
425 @code{rl_prep_term_function}.
426 By default, this is set to @code{rl_deprep_terminal}
427 (@pxref{Terminal Management}).
430 @deftypevar {Keymap} rl_executing_keymap
431 This variable is set to the keymap (@pxref{Keymaps}) in which the
432 currently executing readline function was found.
435 @deftypevar {Keymap} rl_binding_keymap
436 This variable is set to the keymap (@pxref{Keymaps}) in which the
437 last key binding occurred.
440 @deftypevar {char *} rl_executing_macro
441 This variable is set to the text of any currently-executing macro.
444 @deftypevar {int} rl_readline_state
445 A variable with bit values that encapsulate the current Readline state.
446 A bit is set with the @code{RL_SETSTATE} macro, and unset with the
447 @code{RL_UNSETSTATE} macro. Use the @code{RL_ISSTATE} macro to test
448 whether a particular state bit is set. Current state bits include:
452 Readline has not yet been called, nor has it begun to intialize.
453 @item RL_STATE_INITIALIZING
454 Readline is initializing its internal data structures.
455 @item RL_STATE_INITIALIZED
456 Readline has completed its initialization.
457 @item RL_STATE_TERMPREPPED
458 Readline has modified the terminal modes to do its own input and redisplay.
459 @item RL_STATE_READCMD
460 Readline is reading a command from the keyboard.
461 @item RL_STATE_METANEXT
462 Readline is reading more input after reading the meta-prefix character.
463 @item RL_STATE_DISPATCHING
464 Readline is dispatching to a command.
465 @item RL_STATE_MOREINPUT
466 Readline is reading more input while executing an editing command.
467 @item RL_STATE_ISEARCH
468 Readline is performing an incremental history search.
469 @item RL_STATE_NSEARCH
470 Readline is performing a non-incremental history search.
471 @item RL_STATE_SEARCH
472 Readline is searching backward or forward through the history for a string.
473 @item RL_STATE_NUMERICARG
474 Readline is reading a numeric argument.
475 @item RL_STATE_MACROINPUT
476 Readline is currently getting its input from a previously-defined keyboard
478 @item RL_STATE_MACRODEF
479 Readline is currently reading characters defining a keyboard macro.
480 @item RL_STATE_OVERWRITE
481 Readline is in overwrite mode.
482 @item RL_STATE_COMPLETING
483 Readline is performing word completion.
484 @item RL_STATE_SIGHANDLER
485 Readline is currently executing the readline signal handler.
486 @item RL_STATE_UNDOING
487 Readline is performing an undo.
489 Readline has read a key sequence bound to @code{accept-line}
490 and is about to return the line to the caller.
495 @deftypevar {int} rl_explicit_arg
496 Set to a non-zero value if an explicit numeric argument was specified by
497 the user. Only valid in a bindable command function.
500 @deftypevar {int} rl_numeric_arg
501 Set to the value of any numeric argument explicitly specified by the user
502 before executing the current Readline function. Only valid in a bindable
506 @deftypevar {int} rl_editing_mode
507 Set to a value denoting Readline's current editing mode. A value of
508 @var{1} means Readline is currently in emacs mode; @var{0}
509 means that vi mode is active.
513 @node Readline Convenience Functions
514 @section Readline Convenience Functions
517 * Function Naming:: How to give a function you write a name.
518 * Keymaps:: Making keymaps.
519 * Binding Keys:: Changing Keymaps.
520 * Associating Function Names and Bindings:: Translate function names to
522 * Allowing Undoing:: How to make your functions undoable.
523 * Redisplay:: Functions to control line display.
524 * Modifying Text:: Functions to modify @code{rl_line_buffer}.
525 * Character Input:: Functions to read keyboard input.
526 * Terminal Management:: Functions to manage terminal settings.
527 * Utility Functions:: Generally useful functions and hooks.
528 * Miscellaneous Functions:: Functions that don't fall into any category.
529 * Alternate Interface:: Using Readline in a `callback' fashion.
530 * A Readline Example:: An example Readline function.
533 @node Function Naming
534 @subsection Naming a Function
536 The user can dynamically change the bindings of keys while using
537 Readline. This is done by representing the function with a descriptive
538 name. The user is able to type the descriptive name when referring to
539 the function. Thus, in an init file, one might find
542 Meta-Rubout: backward-kill-word
545 This binds the keystroke @key{Meta-Rubout} to the function
546 @emph{descriptively} named @code{backward-kill-word}. You, as the
547 programmer, should bind the functions you write to descriptive names as
548 well. Readline provides a function for doing that:
550 @deftypefun int rl_add_defun (const char *name, rl_command_func_t *function, int key)
551 Add @var{name} to the list of named functions. Make @var{function} be
552 the function that gets called. If @var{key} is not -1, then bind it to
553 @var{function} using @code{rl_bind_key()}.
556 Using this function alone is sufficient for most applications. It is
557 the recommended way to add a few functions to the default functions that
558 Readline has built in. If you need to do something other
559 than adding a function to Readline, you may need to use the
560 underlying functions described below.
563 @subsection Selecting a Keymap
565 Key bindings take place on a @dfn{keymap}. The keymap is the
566 association between the keys that the user types and the functions that
567 get run. You can make your own keymaps, copy existing keymaps, and tell
568 Readline which keymap to use.
570 @deftypefun Keymap rl_make_bare_keymap (void)
571 Returns a new, empty keymap. The space for the keymap is allocated with
572 @code{malloc()}; the caller should free it by calling
573 @code{rl_discard_keymap()} when done.
576 @deftypefun Keymap rl_copy_keymap (Keymap map)
577 Return a new keymap which is a copy of @var{map}.
580 @deftypefun Keymap rl_make_keymap (void)
581 Return a new keymap with the printing characters bound to rl_insert,
582 the lowercase Meta characters bound to run their equivalents, and
583 the Meta digits bound to produce numeric arguments.
586 @deftypefun void rl_discard_keymap (Keymap keymap)
587 Free the storage associated with @var{keymap}.
590 Readline has several internal keymaps. These functions allow you to
591 change which keymap is active.
593 @deftypefun Keymap rl_get_keymap (void)
594 Returns the currently active keymap.
597 @deftypefun void rl_set_keymap (Keymap keymap)
598 Makes @var{keymap} the currently active keymap.
601 @deftypefun Keymap rl_get_keymap_by_name (const char *name)
602 Return the keymap matching @var{name}. @var{name} is one which would
603 be supplied in a @code{set keymap} inputrc line (@pxref{Readline Init File}).
606 @deftypefun {char *} rl_get_keymap_name (Keymap keymap)
607 Return the name matching @var{keymap}. @var{name} is one which would
608 be supplied in a @code{set keymap} inputrc line (@pxref{Readline Init File}).
612 @subsection Binding Keys
614 Key sequences are associate with functions through the keymap.
615 Readline has several internal keymaps: @code{emacs_standard_keymap},
616 @code{emacs_meta_keymap}, @code{emacs_ctlx_keymap},
617 @code{vi_movement_keymap}, and @code{vi_insertion_keymap}.
618 @code{emacs_standard_keymap} is the default, and the examples in
619 this manual assume that.
621 Since @code{readline()} installs a set of default key bindings the first
622 time it is called, there is always the danger that a custom binding
623 installed before the first call to @code{readline()} will be overridden.
624 An alternate mechanism is to install custom key bindings in an
625 initialization function assigned to the @code{rl_startup_hook} variable
626 (@pxref{Readline Variables}).
628 These functions manage key bindings.
630 @deftypefun int rl_bind_key (int key, rl_command_func_t *function)
631 Binds @var{key} to @var{function} in the currently active keymap.
632 Returns non-zero in the case of an invalid @var{key}.
635 @deftypefun int rl_bind_key_in_map (int key, rl_command_func_t *function, Keymap map)
636 Bind @var{key} to @var{function} in @var{map}. Returns non-zero in the case
637 of an invalid @var{key}.
640 @deftypefun int rl_unbind_key (int key)
641 Bind @var{key} to the null function in the currently active keymap.
642 Returns non-zero in case of error.
645 @deftypefun int rl_unbind_key_in_map (int key, Keymap map)
646 Bind @var{key} to the null function in @var{map}.
647 Returns non-zero in case of error.
650 @deftypefun int rl_unbind_function_in_map (rl_command_func_t *function, Keymap map)
651 Unbind all keys that execute @var{function} in @var{map}.
654 @deftypefun int rl_unbind_command_in_map (const char *command, Keymap map)
655 Unbind all keys that are bound to @var{command} in @var{map}.
658 @deftypefun int rl_set_key (const char *keyseq, rl_command_func_t *function, Keymap map)
659 Bind the key sequence represented by the string @var{keyseq} to the function
660 @var{function}. This makes new keymaps as
661 necessary. The initial keymap in which to do bindings is @var{map}.
664 @deftypefun int rl_generic_bind (int type, const char *keyseq, char *data, Keymap map)
665 Bind the key sequence represented by the string @var{keyseq} to the arbitrary
666 pointer @var{data}. @var{type} says what kind of data is pointed to by
667 @var{data}; this can be a function (@code{ISFUNC}), a macro
668 (@code{ISMACR}), or a keymap (@code{ISKMAP}). This makes new keymaps as
669 necessary. The initial keymap in which to do bindings is @var{map}.
672 @deftypefun int rl_parse_and_bind (char *line)
673 Parse @var{line} as if it had been read from the @code{inputrc} file and
674 perform any key bindings and variable assignments found
675 (@pxref{Readline Init File}).
678 @deftypefun int rl_read_init_file (const char *filename)
679 Read keybindings and variable assignments from @var{filename}
680 (@pxref{Readline Init File}).
683 @node Associating Function Names and Bindings
684 @subsection Associating Function Names and Bindings
686 These functions allow you to find out what keys invoke named functions
687 and the functions invoked by a particular key sequence. You may also
688 associate a new function name with an arbitrary function.
690 @deftypefun {rl_command_func_t *} rl_named_function (const char *name)
691 Return the function with name @var{name}.
694 @deftypefun {rl_command_func_t *} rl_function_of_keyseq (const char *keyseq, Keymap map, int *type)
695 Return the function invoked by @var{keyseq} in keymap @var{map}.
696 If @var{map} is @code{NULL}, the current keymap is used. If @var{type} is
697 not @code{NULL}, the type of the object is returned in the @code{int} variable
698 it points to (one of @code{ISFUNC}, @code{ISKMAP}, or @code{ISMACR}).
701 @deftypefun {char **} rl_invoking_keyseqs (rl_command_func_t *function)
702 Return an array of strings representing the key sequences used to
703 invoke @var{function} in the current keymap.
706 @deftypefun {char **} rl_invoking_keyseqs_in_map (rl_command_func_t *function, Keymap map)
707 Return an array of strings representing the key sequences used to
708 invoke @var{function} in the keymap @var{map}.
711 @deftypefun void rl_function_dumper (int readable)
712 Print the readline function names and the key sequences currently
713 bound to them to @code{rl_outstream}. If @var{readable} is non-zero,
714 the list is formatted in such a way that it can be made part of an
715 @code{inputrc} file and re-read.
718 @deftypefun void rl_list_funmap_names (void)
719 Print the names of all bindable Readline functions to @code{rl_outstream}.
722 @deftypefun {const char **} rl_funmap_names (void)
723 Return a NULL terminated array of known function names. The array is
724 sorted. The array itself is allocated, but not the strings inside. You
725 should @code{free()} the array when you are done, but not the pointers.
728 @deftypefun int rl_add_funmap_entry (const char *name, rl_command_func_t *function)
729 Add @var{name} to the list of bindable Readline command names, and make
730 @var{function} the function to be called when @var{name} is invoked.
733 @node Allowing Undoing
734 @subsection Allowing Undoing
736 Supporting the undo command is a painless thing, and makes your
737 functions much more useful. It is certainly easy to try
738 something if you know you can undo it.
740 If your function simply inserts text once, or deletes text once, and
741 uses @code{rl_insert_text()} or @code{rl_delete_text()} to do it, then
742 undoing is already done for you automatically.
744 If you do multiple insertions or multiple deletions, or any combination
745 of these operations, you should group them together into one operation.
746 This is done with @code{rl_begin_undo_group()} and
747 @code{rl_end_undo_group()}.
749 The types of events that can be undone are:
752 enum undo_code @{ UNDO_DELETE, UNDO_INSERT, UNDO_BEGIN, UNDO_END @};
755 Notice that @code{UNDO_DELETE} means to insert some text, and
756 @code{UNDO_INSERT} means to delete some text. That is, the undo code
757 tells what to undo, not how to undo it. @code{UNDO_BEGIN} and
758 @code{UNDO_END} are tags added by @code{rl_begin_undo_group()} and
759 @code{rl_end_undo_group()}.
761 @deftypefun int rl_begin_undo_group (void)
762 Begins saving undo information in a group construct. The undo
763 information usually comes from calls to @code{rl_insert_text()} and
764 @code{rl_delete_text()}, but could be the result of calls to
765 @code{rl_add_undo()}.
768 @deftypefun int rl_end_undo_group (void)
769 Closes the current undo group started with @code{rl_begin_undo_group
770 ()}. There should be one call to @code{rl_end_undo_group()}
771 for each call to @code{rl_begin_undo_group()}.
774 @deftypefun void rl_add_undo (enum undo_code what, int start, int end, char *text)
775 Remember how to undo an event (according to @var{what}). The affected
776 text runs from @var{start} to @var{end}, and encompasses @var{text}.
779 @deftypefun void rl_free_undo_list (void)
780 Free the existing undo list.
783 @deftypefun int rl_do_undo (void)
784 Undo the first thing on the undo list. Returns @code{0} if there was
785 nothing to undo, non-zero if something was undone.
788 Finally, if you neither insert nor delete text, but directly modify the
789 existing text (e.g., change its case), call @code{rl_modifying()}
790 once, just before you modify the text. You must supply the indices of
791 the text range that you are going to modify.
793 @deftypefun int rl_modifying (int start, int end)
794 Tell Readline to save the text between @var{start} and @var{end} as a
795 single undo unit. It is assumed that you will subsequently modify
800 @subsection Redisplay
802 @deftypefun void rl_redisplay (void)
803 Change what's displayed on the screen to reflect the current contents
804 of @code{rl_line_buffer}.
807 @deftypefun int rl_forced_update_display (void)
808 Force the line to be updated and redisplayed, whether or not
809 Readline thinks the screen display is correct.
812 @deftypefun int rl_on_new_line (void)
813 Tell the update functions that we have moved onto a new (empty) line,
814 usually after ouputting a newline.
817 @deftypefun int rl_on_new_line_with_prompt (void)
818 Tell the update functions that we have moved onto a new line, with
819 @var{rl_prompt} already displayed.
820 This could be used by applications that want to output the prompt string
821 themselves, but still need Readline to know the prompt string length for
823 It should be used after setting @var{rl_already_prompted}.
826 @deftypefun int rl_reset_line_state (void)
827 Reset the display state to a clean state and redisplay the current line
828 starting on a new line.
831 @deftypefun int rl_crlf (void)
832 Move the cursor to the start of the next screen line.
835 @deftypefun int rl_show_char (int c)
836 Display character @var{c} on @code{rl_outstream}.
837 If Readline has not been set to display meta characters directly, this
838 will convert meta characters to a meta-prefixed key sequence.
839 This is intended for use by applications which wish to do their own
843 @deftypefun int rl_message (const char *, @dots{})
844 The arguments are a format string as would be supplied to @code{printf},
845 possibly containing conversion specifications such as @samp{%d}, and
846 any additional arguments necessary to satisfy the conversion specifications.
847 The resulting string is displayed in the @dfn{echo area}. The echo area
848 is also used to display numeric arguments and search strings.
851 @deftypefun int rl_clear_message (void)
852 Clear the message in the echo area.
855 @deftypefun void rl_save_prompt (void)
856 Save the local Readline prompt display state in preparation for
857 displaying a new message in the message area with @code{rl_message()}.
860 @deftypefun void rl_restore_prompt (void)
861 Restore the local Readline prompt display state saved by the most
862 recent call to @code{rl_save_prompt}.
865 @deftypefun int rl_expand_prompt (char *prompt)
866 Expand any special character sequences in @var{prompt} and set up the
867 local Readline prompt redisplay variables.
868 This function is called by @code{readline()}. It may also be called to
869 expand the primary prompt if the @code{rl_on_new_line_with_prompt()}
870 function or @code{rl_already_prompted} variable is used.
871 It returns the number of visible characters on the last line of the
872 (possibly multi-line) prompt.
875 @deftypefun int rl_set_prompt (const char *prompt)
876 Make Readline use @var{prompt} for subsequent redisplay. This calls
877 @code{rl_expand_prompt()} to expand the prompt and sets @code{rl_prompt}
882 @subsection Modifying Text
884 @deftypefun int rl_insert_text (const char *text)
885 Insert @var{text} into the line at the current cursor position.
888 @deftypefun int rl_delete_text (int start, int end)
889 Delete the text between @var{start} and @var{end} in the current line.
892 @deftypefun {char *} rl_copy_text (int start, int end)
893 Return a copy of the text between @var{start} and @var{end} in
897 @deftypefun int rl_kill_text (int start, int end)
898 Copy the text between @var{start} and @var{end} in the current line
899 to the kill ring, appending or prepending to the last kill if the
900 last command was a kill command. The text is deleted.
901 If @var{start} is less than @var{end},
902 the text is appended, otherwise prepended. If the last command was
903 not a kill, a new kill ring slot is used.
906 @deftypefun int rl_push_macro_input (char *macro)
907 Cause @var{macro} to be inserted into the line, as if it had been invoked
908 by a key bound to a macro. Not especially useful; use
909 @code{rl_insert_text()} instead.
912 @node Character Input
913 @subsection Character Input
915 @deftypefun int rl_read_key (void)
916 Return the next character available from Readline's current input stream.
917 This handles input inserted into
918 the input stream via @var{rl_pending_input} (@pxref{Readline Variables})
919 and @code{rl_stuff_char()}, macros, and characters read from the keyboard.
920 While waiting for input, this function will call any function assigned to
921 the @code{rl_event_hook} variable.
924 @deftypefun int rl_getc (FILE *stream)
925 Return the next character available from @var{stream}, which is assumed to
929 @deftypefun int rl_stuff_char (int c)
930 Insert @var{c} into the Readline input stream. It will be "read"
931 before Readline attempts to read characters from the terminal with
932 @code{rl_read_key()}.
935 @deftypefun int rl_execute_next (int c)
936 Make @var{c} be the next command to be executed when @code{rl_read_key()}
937 is called. This sets @var{rl_pending_input}.
940 @deftypefun int rl_clear_pending_input (void)
941 Unset @var{rl_pending_input}, effectively negating the effect of any
942 previous call to @code{rl_execute_next()}. This works only if the
943 pending input has not already been read with @code{rl_read_key()}.
946 @deftypefun int rl_set_keyboard_input_timeout (int u)
947 While waiting for keyboard input in @code{rl_read_key()}, Readline will
948 wait for @var{u} microseconds for input before calling any function
949 assigned to @code{rl_event_hook}. The default waiting period is
950 one-tenth of a second. Returns the old timeout value.
953 @node Terminal Management
954 @subsection Terminal Management
956 @deftypefun void rl_prep_terminal (int meta_flag)
957 Modify the terminal settings for Readline's use, so @code{readline()}
958 can read a single character at a time from the keyboard.
959 The @var{meta_flag} argument should be non-zero if Readline should
960 read eight-bit input.
963 @deftypefun void rl_deprep_terminal (void)
964 Undo the effects of @code{rl_prep_terminal()}, leaving the terminal in
965 the state in which it was before the most recent call to
966 @code{rl_prep_terminal()}.
969 @deftypefun void rl_tty_set_default_bindings (Keymap kmap)
970 Read the operating system's terminal editing characters (as would be displayed
971 by @code{stty}) to their Readline equivalents. The bindings are performed
975 @deftypefun int rl_reset_terminal (const char *terminal_name)
976 Reinitialize Readline's idea of the terminal settings using
977 @var{terminal_name} as the terminal type (e.g., @code{vt100}).
978 If @var{terminal_name} is @code{NULL}, the value of the @code{TERM}
979 environment variable is used.
982 @node Utility Functions
983 @subsection Utility Functions
985 @deftypefun int rl_extend_line_buffer (int len)
986 Ensure that @code{rl_line_buffer} has enough space to hold @var{len}
987 characters, possibly reallocating it if necessary.
990 @deftypefun int rl_initialize (void)
991 Initialize or re-initialize Readline's internal state.
992 It's not strictly necessary to call this; @code{readline()} calls it before
996 @deftypefun int rl_ding (void)
997 Ring the terminal bell, obeying the setting of @code{bell-style}.
1000 @deftypefun int rl_alphabetic (int c)
1001 Return 1 if @var{c} is an alphabetic character.
1004 @deftypefun void rl_display_match_list (char **matches, int len, int max)
1005 A convenience function for displaying a list of strings in
1006 columnar format on Readline's output stream. @code{matches} is the list
1007 of strings, in argv format, such as a list of completion matches.
1008 @code{len} is the number of strings in @code{matches}, and @code{max}
1009 is the length of the longest string in @code{matches}. This function uses
1010 the setting of @code{print-completions-horizontally} to select how the
1011 matches are displayed (@pxref{Readline Init File Syntax}).
1014 The following are implemented as macros, defined in @code{chardefs.h}.
1015 Applications should refrain from using them.
1017 @deftypefun int _rl_uppercase_p (int c)
1018 Return 1 if @var{c} is an uppercase alphabetic character.
1021 @deftypefun int _rl_lowercase_p (int c)
1022 Return 1 if @var{c} is a lowercase alphabetic character.
1025 @deftypefun int _rl_digit_p (int c)
1026 Return 1 if @var{c} is a numeric character.
1029 @deftypefun int _rl_to_upper (int c)
1030 If @var{c} is a lowercase alphabetic character, return the corresponding
1031 uppercase character.
1034 @deftypefun int _rl_to_lower (int c)
1035 If @var{c} is an uppercase alphabetic character, return the corresponding
1036 lowercase character.
1039 @deftypefun int _rl_digit_value (int c)
1040 If @var{c} is a number, return the value it represents.
1043 @node Miscellaneous Functions
1044 @subsection Miscellaneous Functions
1046 @deftypefun int rl_macro_bind (const char *keyseq, const char *macro, Keymap map)
1047 Bind the key sequence @var{keyseq} to invoke the macro @var{macro}.
1048 The binding is performed in @var{map}. When @var{keyseq} is invoked, the
1049 @var{macro} will be inserted into the line. This function is deprecated;
1050 use @code{rl_generic_bind()} instead.
1053 @deftypefun void rl_macro_dumper (int readable)
1054 Print the key sequences bound to macros and their values, using
1055 the current keymap, to @code{rl_outstream}.
1056 If @var{readable} is non-zero, the list is formatted in such a way
1057 that it can be made part of an @code{inputrc} file and re-read.
1060 @deftypefun int rl_variable_bind (const char *variable, const char *value)
1061 Make the Readline variable @var{variable} have @var{value}.
1062 This behaves as if the readline command
1063 @samp{set @var{variable} @var{value}} had been executed in an @code{inputrc}
1064 file (@pxref{Readline Init File Syntax}).
1067 @deftypefun void rl_variable_dumper (int readable)
1068 Print the readline variable names and their current values
1069 to @code{rl_outstream}.
1070 If @var{readable} is non-zero, the list is formatted in such a way
1071 that it can be made part of an @code{inputrc} file and re-read.
1074 @deftypefun int rl_set_paren_blink_timeout (int u)
1075 Set the time interval (in microseconds) that Readline waits when showing
1076 a balancing character when @code{blink-matching-paren} has been enabled.
1079 @node Alternate Interface
1080 @subsection Alternate Interface
1082 An alternate interface is available to plain @code{readline()}. Some
1083 applications need to interleave keyboard I/O with file, device, or
1084 window system I/O, typically by using a main loop to @code{select()}
1085 on various file descriptors. To accomodate this need, readline can
1086 also be invoked as a `callback' function from an event loop. There
1087 are functions available to make this easy.
1089 @deftypefun void rl_callback_handler_install (const char *prompt, rl_vcpfunc_t *lhandler)
1090 Set up the terminal for readline I/O and display the initial
1091 expanded value of @var{prompt}. Save the value of @var{lhandler} to
1092 use as a function to call when a complete line of input has been entered.
1093 The function takes the text of the line as an argument.
1096 @deftypefun void rl_callback_read_char (void)
1097 Whenever an application determines that keyboard input is available, it
1098 should call @code{rl_callback_read_char()}, which will read the next
1099 character from the current input source. If that character completes the
1100 line, @code{rl_callback_read_char} will invoke the @var{lhandler}
1101 function saved by @code{rl_callback_handler_install} to process the
1102 line. @code{EOF} is indicated by calling @var{lhandler} with a
1106 @deftypefun void rl_callback_handler_remove (void)
1107 Restore the terminal to its initial state and remove the line handler.
1108 This may be called from within a callback as well as independently.
1111 @node A Readline Example
1112 @subsection A Readline Example
1114 Here is a function which changes lowercase characters to their uppercase
1115 equivalents, and uppercase characters to lowercase. If
1116 this function was bound to @samp{M-c}, then typing @samp{M-c} would
1117 change the case of the character under point. Typing @samp{M-1 0 M-c}
1118 would change the case of the following 10 characters, leaving the cursor on
1119 the last character changed.
1122 /* Invert the case of the COUNT following characters. */
1124 invert_case_line (count, key)
1127 register int start, end, i;
1131 if (rl_point >= rl_end)
1142 /* Find the end of the range to modify. */
1143 end = start + (count * direction);
1145 /* Force it to be within range. */
1161 /* Tell readline that we are modifying the line, so it will save
1162 the undo information. */
1163 rl_modifying (start, end);
1165 for (i = start; i != end; i++)
1167 if (_rl_uppercase_p (rl_line_buffer[i]))
1168 rl_line_buffer[i] = _rl_to_lower (rl_line_buffer[i]);
1169 else if (_rl_lowercase_p (rl_line_buffer[i]))
1170 rl_line_buffer[i] = _rl_to_upper (rl_line_buffer[i]);
1172 /* Move point to on top of the last character changed. */
1173 rl_point = (direction == 1) ? end - 1 : start;
1178 @node Readline Signal Handling
1179 @section Readline Signal Handling
1181 Signals are asynchronous events sent to a process by the Unix kernel,
1182 sometimes on behalf of another process. They are intended to indicate
1183 exceptional events, like a user pressing the interrupt key on his terminal,
1184 or a network connection being broken. There is a class of signals that can
1185 be sent to the process currently reading input from the keyboard. Since
1186 Readline changes the terminal attributes when it is called, it needs to
1187 perform special processing when such a signal is received in order to
1188 restore the terminal to a sane state, or provide application writers with
1189 functions to do so manually.
1191 Readline contains an internal signal handler that is installed for a
1192 number of signals (@code{SIGINT}, @code{SIGQUIT}, @code{SIGTERM},
1193 @code{SIGALRM}, @code{SIGTSTP}, @code{SIGTTIN}, and @code{SIGTTOU}).
1194 When one of these signals is received, the signal handler
1195 will reset the terminal attributes to those that were in effect before
1196 @code{readline()} was called, reset the signal handling to what it was
1197 before @code{readline()} was called, and resend the signal to the calling
1199 If and when the calling application's signal handler returns, Readline
1200 will reinitialize the terminal and continue to accept input.
1201 When a @code{SIGINT} is received, the Readline signal handler performs
1202 some additional work, which will cause any partially-entered line to be
1203 aborted (see the description of @code{rl_free_line_state()} below).
1205 There is an additional Readline signal handler, for @code{SIGWINCH}, which
1206 the kernel sends to a process whenever the terminal's size changes (for
1207 example, if a user resizes an @code{xterm}). The Readline @code{SIGWINCH}
1208 handler updates Readline's internal screen size information, and then calls
1209 any @code{SIGWINCH} signal handler the calling application has installed.
1210 Readline calls the application's @code{SIGWINCH} signal handler without
1211 resetting the terminal to its original state. If the application's signal
1212 handler does more than update its idea of the terminal size and return (for
1213 example, a @code{longjmp} back to a main processing loop), it @emph{must}
1214 call @code{rl_cleanup_after_signal()} (described below), to restore the
1217 Readline provides two variables that allow application writers to
1218 control whether or not it will catch certain signals and act on them
1219 when they are received. It is important that applications change the
1220 values of these variables only when calling @code{readline()}, not in
1221 a signal handler, so Readline's internal signal state is not corrupted.
1223 @deftypevar int rl_catch_signals
1224 If this variable is non-zero, Readline will install signal handlers for
1225 @code{SIGINT}, @code{SIGQUIT}, @code{SIGTERM}, @code{SIGALRM},
1226 @code{SIGTSTP}, @code{SIGTTIN}, and @code{SIGTTOU}.
1228 The default value of @code{rl_catch_signals} is 1.
1231 @deftypevar int rl_catch_sigwinch
1232 If this variable is non-zero, Readline will install a signal handler for
1235 The default value of @code{rl_catch_sigwinch} is 1.
1238 If an application does not wish to have Readline catch any signals, or
1239 to handle signals other than those Readline catches (@code{SIGHUP},
1241 Readline provides convenience functions to do the necessary terminal
1242 and internal state cleanup upon receipt of a signal.
1244 @deftypefun void rl_cleanup_after_signal (void)
1245 This function will reset the state of the terminal to what it was before
1246 @code{readline()} was called, and remove the Readline signal handlers for
1247 all signals, depending on the values of @code{rl_catch_signals} and
1248 @code{rl_catch_sigwinch}.
1251 @deftypefun void rl_free_line_state (void)
1252 This will free any partial state associated with the current input line
1253 (undo information, any partial history entry, any partially-entered
1254 keyboard macro, and any partially-entered numeric argument). This
1255 should be called before @code{rl_cleanup_after_signal()}. The
1256 Readline signal handler for @code{SIGINT} calls this to abort the
1260 @deftypefun void rl_reset_after_signal (void)
1261 This will reinitialize the terminal and reinstall any Readline signal
1262 handlers, depending on the values of @code{rl_catch_signals} and
1263 @code{rl_catch_sigwinch}.
1266 If an application does not wish Readline to catch @code{SIGWINCH}, it may
1267 call @code{rl_resize_terminal()} or @code{rl_set_screen_size()} to force
1268 Readline to update its idea of the terminal size when a @code{SIGWINCH}
1271 @deftypefun void rl_resize_terminal (void)
1272 Update Readline's internal screen size by reading values from the kernel.
1275 @deftypefun void rl_set_screen_size (int rows, int cols)
1276 Set Readline's idea of the terminal size to @var{rows} rows and
1280 If an application does not want to install a @code{SIGWINCH} handler, but
1281 is still interested in the screen dimensions, Readline's idea of the screen
1282 size may be queried.
1284 @deftypefun void rl_get_screen_size (int *rows, int *cols)
1285 Return Readline's idea of the terminal's size in the
1286 variables pointed to by the arguments.
1289 The following functions install and remove Readline's signal handlers.
1291 @deftypefun int rl_set_signals (void)
1292 Install Readline's signal handler for @code{SIGINT}, @code{SIGQUIT},
1293 @code{SIGTERM}, @code{SIGALRM}, @code{SIGTSTP}, @code{SIGTTIN},
1294 @code{SIGTTOU}, and @code{SIGWINCH}, depending on the values of
1295 @code{rl_catch_signals} and @code{rl_catch_sigwinch}.
1298 @deftypefun int rl_clear_signals (void)
1299 Remove all of the Readline signal handlers installed by
1300 @code{rl_set_signals()}.
1303 @node Custom Completers
1304 @section Custom Completers
1306 Typically, a program that reads commands from the user has a way of
1307 disambiguating commands and data. If your program is one of these, then
1308 it can provide completion for commands, data, or both.
1309 The following sections describe how your program and Readline
1310 cooperate to provide this service.
1313 * How Completing Works:: The logic used to do completion.
1314 * Completion Functions:: Functions provided by Readline.
1315 * Completion Variables:: Variables which control completion.
1316 * A Short Completion Example:: An example of writing completer subroutines.
1319 @node How Completing Works
1320 @subsection How Completing Works
1322 In order to complete some text, the full list of possible completions
1323 must be available. That is, it is not possible to accurately
1324 expand a partial word without knowing all of the possible words
1325 which make sense in that context. The Readline library provides
1326 the user interface to completion, and two of the most common
1327 completion functions: filename and username. For completing other types
1328 of text, you must write your own completion function. This section
1329 describes exactly what such functions must do, and provides an example.
1331 There are three major functions used to perform completion:
1335 The user-interface function @code{rl_complete()}. This function is
1336 called with the same arguments as other bindable Readline functions:
1337 @var{count} and @var{invoking_key}.
1338 It isolates the word to be completed and calls
1339 @code{rl_completion_matches()} to generate a list of possible completions.
1340 It then either lists the possible completions, inserts the possible
1341 completions, or actually performs the
1342 completion, depending on which behavior is desired.
1345 The internal function @code{rl_completion_matches()} uses an
1346 application-supplied @dfn{generator} function to generate the list of
1347 possible matches, and then returns the array of these matches.
1348 The caller should place the address of its generator function in
1349 @code{rl_completion_entry_function}.
1352 The generator function is called repeatedly from
1353 @code{rl_completion_matches()}, returning a string each time. The
1354 arguments to the generator function are @var{text} and @var{state}.
1355 @var{text} is the partial word to be completed. @var{state} is zero the
1356 first time the function is called, allowing the generator to perform
1357 any necessary initialization, and a positive non-zero integer for
1358 each subsequent call. The generator function returns
1359 @code{(char *)NULL} to inform @code{rl_completion_matches()} that there are
1360 no more possibilities left. Usually the generator function computes the
1361 list of possible completions when @var{state} is zero, and returns them
1362 one at a time on subsequent calls. Each string the generator function
1363 returns as a match must be allocated with @code{malloc()}; Readline
1364 frees the strings when it has finished with them.
1368 @deftypefun int rl_complete (int ignore, int invoking_key)
1369 Complete the word at or before point. You have supplied the function
1370 that does the initial simple matching selection algorithm (see
1371 @code{rl_completion_matches()}). The default is to do filename completion.
1374 @deftypevar {rl_compentry_func_t *} rl_completion_entry_function
1375 This is a pointer to the generator function for
1376 @code{rl_completion_matches()}.
1377 If the value of @code{rl_completion_entry_function} is
1378 @code{NULL} then the default filename generator
1379 function, @code{rl_filename_completion_function()}, is used.
1382 @node Completion Functions
1383 @subsection Completion Functions
1385 Here is the complete list of callable completion functions present in
1388 @deftypefun int rl_complete_internal (int what_to_do)
1389 Complete the word at or before point. @var{what_to_do} says what to do
1390 with the completion. A value of @samp{?} means list the possible
1391 completions. @samp{TAB} means do standard completion. @samp{*} means
1392 insert all of the possible completions. @samp{!} means to display
1393 all of the possible completions, if there is more than one, as well as
1394 performing partial completion.
1397 @deftypefun int rl_complete (int ignore, int invoking_key)
1398 Complete the word at or before point. You have supplied the function
1399 that does the initial simple matching selection algorithm (see
1400 @code{rl_completion_matches()} and @code{rl_completion_entry_function}).
1401 The default is to do filename
1402 completion. This calls @code{rl_complete_internal()} with an
1403 argument depending on @var{invoking_key}.
1406 @deftypefun int rl_possible_completions (int count, int invoking_key)
1407 List the possible completions. See description of @code{rl_complete
1408 ()}. This calls @code{rl_complete_internal()} with an argument of
1412 @deftypefun int rl_insert_completions (int count, int invoking_key)
1413 Insert the list of possible completions into the line, deleting the
1414 partially-completed word. See description of @code{rl_complete()}.
1415 This calls @code{rl_complete_internal()} with an argument of @samp{*}.
1418 @deftypefun {char **} rl_completion_matches (const char *text, rl_compentry_func_t *entry_func)
1419 Returns an array of strings which is a list of completions for
1420 @var{text}. If there are no completions, returns @code{NULL}.
1421 The first entry in the returned array is the substitution for @var{text}.
1422 The remaining entries are the possible completions. The array is
1423 terminated with a @code{NULL} pointer.
1425 @var{entry_func} is a function of two args, and returns a
1426 @code{char *}. The first argument is @var{text}. The second is a
1427 state argument; it is zero on the first call, and non-zero on subsequent
1428 calls. @var{entry_func} returns a @code{NULL} pointer to the caller
1429 when there are no more matches.
1432 @deftypefun {char *} rl_filename_completion_function (const char *text, int state)
1433 A generator function for filename completion in the general case.
1434 @var{text} is a partial filename.
1435 The Bash source is a useful reference for writing custom
1436 completion functions (the Bash completion functions call this and other
1437 Readline functions).
1440 @deftypefun {char *} rl_username_completion_function (const char *text, int state)
1441 A completion generator for usernames. @var{text} contains a partial
1442 username preceded by a random character (usually @samp{~}). As with all
1443 completion generators, @var{state} is zero on the first call and non-zero
1444 for subsequent calls.
1447 @node Completion Variables
1448 @subsection Completion Variables
1450 @deftypevar {rl_compentry_func_t *} rl_completion_entry_function
1451 A pointer to the generator function for @code{rl_completion_matches()}.
1452 @code{NULL} means to use @code{rl_filename_completion_function()}, the default
1456 @deftypevar {rl_completion_func_t *} rl_attempted_completion_function
1457 A pointer to an alternative function to create matches.
1458 The function is called with @var{text}, @var{start}, and @var{end}.
1459 @var{start} and @var{end} are indices in @code{rl_line_buffer} defining
1460 the boundaries of @var{text}, which is a character string.
1461 If this function exists and returns @code{NULL}, or if this variable is
1462 set to @code{NULL}, then @code{rl_complete()} will call the value of
1463 @code{rl_completion_entry_function} to generate matches, otherwise the
1464 array of strings returned will be used.
1465 If this function sets the @code{rl_attempted_completion_over}
1466 variable to a non-zero value, Readline will not perform its default
1467 completion even if this function returns no matches.
1470 @deftypevar {rl_quote_func_t *} rl_filename_quoting_function
1471 A pointer to a function that will quote a filename in an
1472 application-specific fashion. This is called if filename completion is being
1473 attempted and one of the characters in @code{rl_filename_quote_characters}
1474 appears in a completed filename. The function is called with
1475 @var{text}, @var{match_type}, and @var{quote_pointer}. The @var{text}
1476 is the filename to be quoted. The @var{match_type} is either
1477 @code{SINGLE_MATCH}, if there is only one completion match, or
1478 @code{MULT_MATCH}. Some functions use this to decide whether or not to
1479 insert a closing quote character. The @var{quote_pointer} is a pointer
1480 to any opening quote character the user typed. Some functions choose
1481 to reset this character.
1484 @deftypevar {rl_dequote_func_t *} rl_filename_dequoting_function
1485 A pointer to a function that will remove application-specific quoting
1486 characters from a filename before completion is attempted, so those
1487 characters do not interfere with matching the text against names in
1488 the filesystem. It is called with @var{text}, the text of the word
1489 to be dequoted, and @var{quote_char}, which is the quoting character
1490 that delimits the filename (usually @samp{'} or @samp{"}). If
1491 @var{quote_char} is zero, the filename was not in an embedded string.
1494 @deftypevar {rl_linebuf_func_t *} rl_char_is_quoted_p
1495 A pointer to a function to call that determines whether or not a specific
1496 character in the line buffer is quoted, according to whatever quoting
1497 mechanism the program calling Readline uses. The function is called with
1498 two arguments: @var{text}, the text of the line, and @var{index}, the
1499 index of the character in the line. It is used to decide whether a
1500 character found in @code{rl_completer_word_break_characters} should be
1501 used to break words for the completer.
1504 @deftypevar int rl_completion_query_items
1505 Up to this many items will be displayed in response to a
1506 possible-completions call. After that, we ask the user if she is sure
1507 she wants to see them all. The default value is 100.
1510 @deftypevar {const char *} rl_basic_word_break_characters
1511 The basic list of characters that signal a break between words for the
1512 completer routine. The default value of this variable is the characters
1513 which break words for completion in Bash:
1514 @code{" \t\n\"\\'`@@$><=;|&@{("}.
1517 @deftypevar {const char *} rl_basic_quote_characters
1518 A list of quote characters which can cause a word break.
1521 @deftypevar {const char *} rl_completer_word_break_characters
1522 The list of characters that signal a break between words for
1523 @code{rl_complete_internal()}. The default list is the value of
1524 @code{rl_basic_word_break_characters}.
1527 @deftypevar {const char *} rl_completer_quote_characters
1528 A list of characters which can be used to quote a substring of the line.
1529 Completion occurs on the entire substring, and within the substring
1530 @code{rl_completer_word_break_characters} are treated as any other character,
1531 unless they also appear within this list.
1534 @deftypevar {const char *} rl_filename_quote_characters
1535 A list of characters that cause a filename to be quoted by the completer
1536 when they appear in a completed filename. The default is the null string.
1539 @deftypevar {const char *} rl_special_prefixes
1540 The list of characters that are word break characters, but should be
1541 left in @var{text} when it is passed to the completion function.
1542 Programs can use this to help determine what kind of completing to do.
1543 For instance, Bash sets this variable to "$@@" so that it can complete
1544 shell variables and hostnames.
1547 @deftypevar {int} rl_completion_append_character
1548 When a single completion alternative matches at the end of the command
1549 line, this character is appended to the inserted completion text. The
1550 default is a space character (@samp{ }). Setting this to the null
1551 character (@samp{\0}) prevents anything being appended automatically.
1552 This can be changed in custom completion functions to
1553 provide the ``most sensible word separator character'' according to
1554 an application-specific command line syntax specification.
1557 @deftypevar int rl_ignore_completion_duplicates
1558 If non-zero, then duplicates in the matches are removed.
1562 @deftypevar int rl_filename_completion_desired
1563 Non-zero means that the results of the matches are to be treated as
1564 filenames. This is @emph{always} zero on entry, and can only be changed
1565 within a completion entry generator function. If it is set to a non-zero
1566 value, directory names have a slash appended and Readline attempts to
1567 quote completed filenames if they contain any characters in
1568 @code{rl_filename_quote_characters} and @code{rl_filename_quoting_desired}
1569 is set to a non-zero value.
1572 @deftypevar int rl_filename_quoting_desired
1573 Non-zero means that the results of the matches are to be quoted using
1574 double quotes (or an application-specific quoting mechanism) if the
1575 completed filename contains any characters in
1576 @code{rl_filename_quote_chars}. This is @emph{always} non-zero
1577 on entry, and can only be changed within a completion entry generator
1578 function. The quoting is effected via a call to the function pointed to
1579 by @code{rl_filename_quoting_function}.
1582 @deftypevar int rl_attempted_completion_over
1583 If an application-specific completion function assigned to
1584 @code{rl_attempted_completion_function} sets this variable to a non-zero
1585 value, Readline will not perform its default filename completion even
1586 if the application's completion function returns no matches.
1587 It should be set only by an application's completion function.
1590 @deftypevar int rl_completion_type
1591 Set to a character describing the type of completion Readline is currently
1592 attempting; see the description of @code{rl_complete_internal()}
1593 (@pxref{Completion Functions}) for the list of characters.
1596 @deftypevar int rl_inhibit_completion
1597 If this variable is non-zero, completion is inhibited. The completion
1598 character will be inserted as any other bound to @code{self-insert}.
1601 @deftypevar {rl_compignore_func_t *} rl_ignore_some_completions_function
1602 This function, if defined, is called by the completer when real filename
1603 completion is done, after all the matching names have been generated.
1604 It is passed a @code{NULL} terminated array of matches.
1605 The first element (@code{matches[0]}) is the
1606 maximal substring common to all matches. This function can
1607 re-arrange the list of matches as required, but each element deleted
1608 from the array must be freed.
1611 @deftypevar {rl_icppfunc_t *} rl_directory_completion_hook
1612 This function, if defined, is allowed to modify the directory portion
1613 of filenames Readline completes. It is called with the address of a
1614 string (the current directory name) as an argument, and may modify that string.
1615 If the string is replaced with a new string, the old value should be freed.
1616 Any modified directory name should have a trailing slash.
1617 The modified value will be displayed as part of the completion, replacing
1618 the directory portion of the pathname the user typed.
1619 It returns an integer that should be non-zero if the function modifies
1620 its directory argument.
1621 It could be used to expand symbolic links or shell variables in pathnames.
1624 @deftypevar {rl_compdisp_func_t *} rl_completion_display_matches_hook
1625 If non-zero, then this is the address of a function to call when
1626 completing a word would normally display the list of possible matches.
1627 This function is called in lieu of Readline displaying the list.
1628 It takes three arguments:
1629 (@code{char **}@var{matches}, @code{int} @var{num_matches}, @code{int} @var{max_length})
1630 where @var{matches} is the array of matching strings,
1631 @var{num_matches} is the number of strings in that array, and
1632 @var{max_length} is the length of the longest string in that array.
1633 Readline provides a convenience function, @code{rl_display_match_list},
1634 that takes care of doing the display to Readline's output stream. That
1635 function may be called from this hook.
1638 @node A Short Completion Example
1639 @subsection A Short Completion Example
1641 Here is a small application demonstrating the use of the GNU Readline
1642 library. It is called @code{fileman}, and the source code resides in
1643 @file{examples/fileman.c}. This sample application provides
1644 completion of command names, line editing features, and access to the
1649 /* fileman.c -- A tiny application which demonstrates how to use the
1650 GNU Readline library. This application interactively allows users
1651 to manipulate files and their modes. */
1654 #include <sys/types.h>
1655 #include <sys/file.h>
1656 #include <sys/stat.h>
1657 #include <sys/errno.h>
1659 #include <readline/readline.h>
1660 #include <readline/history.h>
1662 extern char *xmalloc ();
1664 /* The names of functions that actually do the manipulation. */
1665 int com_list __P((char *));
1666 int com_view __P((char *));
1667 int com_rename __P((char *));
1668 int com_stat __P((char *));
1669 int com_pwd __P((char *));
1670 int com_delete __P((char *));
1671 int com_help __P((char *));
1672 int com_cd __P((char *));
1673 int com_quit __P((char *));
1675 /* A structure which contains information on the commands this program
1679 char *name; /* User printable name of the function. */
1680 rl_icpfunc_t *func; /* Function to call to do the job. */
1681 char *doc; /* Documentation for this function. */
1684 COMMAND commands[] = @{
1685 @{ "cd", com_cd, "Change to directory DIR" @},
1686 @{ "delete", com_delete, "Delete FILE" @},
1687 @{ "help", com_help, "Display this text" @},
1688 @{ "?", com_help, "Synonym for `help'" @},
1689 @{ "list", com_list, "List files in DIR" @},
1690 @{ "ls", com_list, "Synonym for `list'" @},
1691 @{ "pwd", com_pwd, "Print the current working directory" @},
1692 @{ "quit", com_quit, "Quit using Fileman" @},
1693 @{ "rename", com_rename, "Rename FILE to NEWNAME" @},
1694 @{ "stat", com_stat, "Print out statistics on FILE" @},
1695 @{ "view", com_view, "View the contents of FILE" @},
1696 @{ (char *)NULL, (rl_icpfunc_t *)NULL, (char *)NULL @}
1699 /* Forward declarations. */
1700 char *stripwhite ();
1701 COMMAND *find_command ();
1703 /* The name of this program, as taken from argv[0]. */
1706 /* When non-zero, this means the user is done using this program. */
1715 r = xmalloc (strlen (s) + 1);
1728 initialize_readline (); /* Bind our completer. */
1730 /* Loop reading and executing lines until the user quits. */
1731 for ( ; done == 0; )
1733 line = readline ("FileMan: ");
1738 /* Remove leading and trailing whitespace from the line.
1739 Then, if there is anything left, add it to the history list
1741 s = stripwhite (line);
1754 /* Execute a command line. */
1763 /* Isolate the command word. */
1765 while (line[i] && whitespace (line[i]))
1769 while (line[i] && !whitespace (line[i]))
1775 command = find_command (word);
1779 fprintf (stderr, "%s: No such command for FileMan.\n", word);
1783 /* Get argument to command, if any. */
1784 while (whitespace (line[i]))
1789 /* Call the function. */
1790 return ((*(command->func)) (word));
1793 /* Look up NAME as the name of a command, and return a pointer to that
1794 command. Return a NULL pointer if NAME isn't a command name. */
1801 for (i = 0; commands[i].name; i++)
1802 if (strcmp (name, commands[i].name) == 0)
1803 return (&commands[i]);
1805 return ((COMMAND *)NULL);
1808 /* Strip whitespace from the start and end of STRING. Return a pointer
1814 register char *s, *t;
1816 for (s = string; whitespace (*s); s++)
1822 t = s + strlen (s) - 1;
1823 while (t > s && whitespace (*t))
1830 /* **************************************************************** */
1832 /* Interface to Readline Completion */
1834 /* **************************************************************** */
1836 char *command_generator __P((const char *, int));
1837 char **fileman_completion __P((const char *, int, int));
1839 /* Tell the GNU Readline library how to complete. We want to try to
1840 complete on command names if this is the first word in the line, or
1841 on filenames if not. */
1842 initialize_readline ()
1844 /* Allow conditional parsing of the ~/.inputrc file. */
1845 rl_readline_name = "FileMan";
1847 /* Tell the completer that we want a crack first. */
1848 rl_attempted_completion_function = fileman_completion;
1851 /* Attempt to complete on the contents of TEXT. START and END
1852 bound the region of rl_line_buffer that contains the word to
1853 complete. TEXT is the word to complete. We can use the entire
1854 contents of rl_line_buffer in case we want to do some simple
1855 parsing. Returnthe array of matches, or NULL if there aren't any. */
1857 fileman_completion (text, start, end)
1863 matches = (char **)NULL;
1865 /* If this word is at the start of the line, then it is a command
1866 to complete. Otherwise it is the name of a file in the current
1869 matches = rl_completion_matches (text, command_generator);
1874 /* Generator function for command completion. STATE lets us
1875 know whether to start from scratch; without any state
1876 (i.e. STATE == 0), then we start at the top of the list. */
1878 command_generator (text, state)
1882 static int list_index, len;
1885 /* If this is a new word to complete, initialize now. This
1886 includes saving the length of TEXT for efficiency, and
1887 initializing the index variable to 0. */
1891 len = strlen (text);
1894 /* Return the next name which partially matches from the
1896 while (name = commands[list_index].name)
1900 if (strncmp (name, text, len) == 0)
1901 return (dupstr(name));
1904 /* If no names matched, then return NULL. */
1905 return ((char *)NULL);
1908 /* **************************************************************** */
1910 /* FileMan Commands */
1912 /* **************************************************************** */
1914 /* String to pass to system (). This is for the LIST, VIEW and RENAME
1916 static char syscom[1024];
1918 /* List the file(s) named in arg. */
1925 sprintf (syscom, "ls -FClg %s", arg);
1926 return (system (syscom));
1932 if (!valid_argument ("view", arg))
1935 sprintf (syscom, "more %s", arg);
1936 return (system (syscom));
1942 too_dangerous ("rename");
1951 if (!valid_argument ("stat", arg))
1954 if (stat (arg, &finfo) == -1)
1960 printf ("Statistics for `%s':\n", arg);
1962 printf ("%s has %d link%s, and is %d byte%s in length.\n", arg,
1964 (finfo.st_nlink == 1) ? "" : "s",
1966 (finfo.st_size == 1) ? "" : "s");
1967 printf ("Inode Last Change at: %s", ctime (&finfo.st_ctime));
1968 printf (" Last access at: %s", ctime (&finfo.st_atime));
1969 printf (" Last modified at: %s", ctime (&finfo.st_mtime));
1976 too_dangerous ("delete");
1980 /* Print out help for ARG, or for all of the commands if ARG is
1988 for (i = 0; commands[i].name; i++)
1990 if (!*arg || (strcmp (arg, commands[i].name) == 0))
1992 printf ("%s\t\t%s.\n", commands[i].name, commands[i].doc);
1999 printf ("No commands match `%s'. Possibilties are:\n", arg);
2001 for (i = 0; commands[i].name; i++)
2003 /* Print in six columns. */
2010 printf ("%s\t", commands[i].name);
2020 /* Change to the directory ARG. */
2024 if (chdir (arg) == -1)
2034 /* Print out the current working directory. */
2040 s = getcwd (dir, sizeof(dir) - 1);
2043 printf ("Error getting pwd: %s\n", dir);
2047 printf ("Current directory is %s\n", dir);
2051 /* The user wishes to quit using this program. Just set DONE
2060 /* Function which tells you that you can't do this. */
2061 too_dangerous (caller)
2065 "%s: Too dangerous for me to distribute. Write it yourself.\n",
2069 /* Return non-zero if ARG is a valid argument for CALLER, else print
2070 an error message and return zero. */
2072 valid_argument (caller, arg)
2077 fprintf (stderr, "%s: Argument required.\n", caller);