]> git.ipfire.org Git - thirdparty/bash.git/blame_incremental - lib/readline/doc/rltech.texi
Bash-5.3 distribution sources and documentation
[thirdparty/bash.git] / lib / readline / doc / rltech.texi
... / ...
CommitLineData
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.)
4
5@ifinfo
6This document describes the GNU Readline Library, a utility for aiding
7in the consistency of user interface across discrete programs that need
8to provide a command line interface.
9
10Copyright (C) 1988--2025 Free Software Foundation, Inc.
11
12Permission is granted to make and distribute verbatim copies of
13this manual provided the copyright notice and this permission notice
14pare preserved on all copies.
15
16@ignore
17Permission is granted to process this file through TeX and print the
18results, provided the printed document carries copying permission
19notice identical to this one except for the removal of this paragraph
20(this paragraph not being relevant to the printed manual).
21@end ignore
22
23Permission is granted to copy and distribute modified versions of this
24manual under the conditions for verbatim copying, provided that the entire
25resulting derived work is distributed under the terms of a permission
26notice identical to this one.
27
28Permission is granted to copy and distribute translations of this manual
29into another language, under the above conditions for modified versions,
30except that this permission notice may be stated in a translation approved
31by the Foundation.
32@end ifinfo
33
34@node Programming with GNU Readline
35@chapter Programming with GNU Readline
36
37This chapter describes the interface between the @sc{gnu} Readline Library and
38other programs. If you are a programmer, and you wish to include the
39features found in @sc{gnu} Readline
40such as completion, line editing, and interactive history manipulation
41in your own programs, this section is for you.
42
43@menu
44* Basic Behavior:: Using the default behavior of Readline.
45* Custom Functions:: Adding your own functions to Readline.
46* Readline Variables:: Variables accessible to custom
47 functions.
48* Readline Convenience Functions:: Functions which Readline supplies to
49 aid in writing your own custom
50 functions.
51* Readline Signal Handling:: How Readline behaves when it receives signals.
52* Custom Completers:: Supplanting or supplementing Readline's
53 completion functions.
54@end menu
55
56@node Basic Behavior
57@section Basic Behavior
58
59Many programs provide a command line interface, such as @code{mail},
60@code{ftp}, and @code{sh}.
61For such programs, the default behavior of Readline is sufficient.
62This section describes how to use Readline in
63the simplest way possible, perhaps to replace calls in your code to
64@code{fgets()}.
65
66@findex readline
67@cindex readline, function
68
69The function @code{readline()} prints a prompt @var{prompt}
70and then reads and returns a single line of text from the user.
71Since it's possible to enter characters into the line while quoting
72them to disable any Readline editing function they might normally have,
73this line may include embedded newlines and other special characters.
74If @var{prompt} is @code{NULL} or the empty string,
75@code{readline()} does not display a prompt.
76The line @code{readline()} returns is allocated with @code{malloc()};
77the caller should @code{free()} the line when it has finished with it.
78The declaration for @code{readline} in ANSI C is
79
80@example
81@code{char *readline (const char *@var{prompt});}
82@end example
83
84@noindent
85So, one might say
86@example
87@code{char *line = readline ("Enter a line: ");}
88@end example
89@noindent
90in order to read a line of text from the user.
91The line returned has the final newline removed, so only the
92text remains.
93This means that lines consisting of a newline return the empty string.
94
95If Readline encounters an @code{EOF} while reading the line,
96and the line is empty at that point,
97then @code{readline()} returns @code{(char *)NULL}.
98Otherwise, the line is ended just as if a newline had been typed.
99
100Readline performs some expansion on the @var{prompt} before it is
101displayed on the screen.
102See the description of @code{rl_expand_prompt}
103(@pxref{Redisplay}) for additional details, especially if @var{prompt}
104will contain characters that do not consume physical screen space when
105displayed.
106
107If you want the user to be able to get at the line later, (with
108@key{C-p} for example), you must call @code{add_history()} to save the
109line away in a @dfn{history} list of such lines.
110
111@example
112@code{add_history (line)};
113@end example
114
115@noindent
116For full details on the GNU History Library, see the associated manual.
117
118It is preferable to avoid saving empty lines on the history list, since
119users rarely have a burning need to reuse a blank line.
120Here is a function which usefully replaces the standard @code{gets()} library
121function, and has the advantage of no static buffer to overflow:
122
123@example
124/* A static variable for holding the line. */
125static char *line_read = (char *)NULL;
126
127/* Read a string, and return a pointer to it.
128 Returns NULL on EOF. */
129char *
130rl_gets ()
131@{
132 /* If the buffer has already been allocated,
133 return the memory to the free pool. */
134 if (line_read)
135 @{
136 free (line_read);
137 line_read = (char *)NULL;
138 @}
139
140 /* Get a line from the user. */
141 line_read = readline ("");
142
143 /* If the line has any text in it,
144 save it on the history. */
145 if (line_read && *line_read)
146 add_history (line_read);
147
148 return (line_read);
149@}
150@end example
151
152This function gives the user the default behavior of @key{TAB}
153completion: filename completion.
154If you do not want Readline to
155complete filenames, you can change the binding of the @key{TAB} key
156with @code{rl_bind_key()}.
157
158@example
159@code{int rl_bind_key (int @var{key}, rl_command_func_t *@var{function});}
160@end example
161
162@code{rl_bind_key()} takes two arguments: @var{key} is the character that
163you want to bind, and @var{function} is the address of the function to
164call when @var{key} is pressed.
165Binding @key{TAB} to @code{rl_insert()} makes @key{TAB} insert itself.
166@code{rl_bind_key()} returns non-zero if @var{key} is not a valid
167ASCII character code (between 0 and 255).
168
169Thus, to disable the default @key{TAB} behavior, the following suffices:
170@example
171@code{rl_bind_key ('\t', rl_insert);}
172@end example
173
174This code should be executed once at the start of your program; you
175might write a function called @code{initialize_readline()} which
176performs this and other desired initializations, such as installing
177custom completers (@pxref{Custom Completers}).
178
179@node Custom Functions
180@section Custom Functions
181
182Readline provides many functions for manipulating the text of
183the line, but it isn't possible to anticipate the needs of all
184programs.
185This section describes the various functions and variables
186defined within the Readline library which allow a program to add
187customized functionality to Readline.
188
189Before declaring any functions that customize Readline's behavior, or
190using any functionality Readline provides in other code, an
191application writer should include the file @code{<readline/readline.h>}
192in any file that uses Readline's features.
193Since some of the definitions
194in @code{readline.h} use the @code{stdio} library, the program
195should include the file @code{<stdio.h>}
196before @code{readline.h}.
197
198@code{readline.h} defines a C preprocessor variable that should
199be treated as an integer, @code{RL_READLINE_VERSION}, which may
200be used to conditionally compile application code depending on
201the installed Readline version.
202The value is a hexadecimal
203encoding of the major and minor version numbers of the library,
204of the form 0x@var{MMmm}. @var{MM} is the two-digit major
205version number; @var{mm} is the two-digit minor version number.
206For Readline 4.2, for example, the value of
207@code{RL_READLINE_VERSION} would be @code{0x0402}.
208
209@menu
210* Readline Typedefs:: C declarations to make code readable.
211* Function Writing:: Variables and calling conventions.
212@end menu
213
214@node Readline Typedefs
215@subsection Readline Typedefs
216
217For readability, we declare a number of new object types, all pointers
218to functions.
219
220The reason for declaring these new types is to make it easier to write
221code describing pointers to C functions with appropriately prototyped
222arguments and return values.
223
224For instance, say we want to declare a variable @var{func} as a pointer
225to a function which takes two @code{int} arguments and returns an
226@code{int} (this is the type of all of the Readline bindable functions).
227Instead of the classic C declaration
228
229@code{int (*func)();}
230
231@noindent
232or the ANSI-C style declaration
233
234@code{int (*func)(int, int);}
235
236@noindent
237we may write
238
239@code{rl_command_func_t *func;}
240
241The full list of function pointer types available is
242
243@table @code
244@item typedef int rl_command_func_t (int, int);
245
246@item typedef char *rl_compentry_func_t (const char *, int);
247
248@item typedef char **rl_completion_func_t (const char *, int, int);
249
250@item typedef char *rl_quote_func_t (char *, int, char *);
251
252@item typedef char *rl_dequote_func_t (char *, int);
253
254@item typedef int rl_compignore_func_t (char **);
255
256@item typedef void rl_compdisp_func_t (char **, int, int);
257
258@item typedef void rl_macro_print_func_t (const char *, const char *, int, const char *);
259
260@item typedef int rl_hook_func_t (void);
261
262@item typedef int rl_getc_func_t (FILE *);
263
264@item typedef int rl_linebuf_func_t (char *, int);
265
266@item typedef int rl_intfunc_t (int);
267@item #define rl_ivoidfunc_t rl_hook_func_t
268@item typedef int rl_icpfunc_t (char *);
269@item typedef int rl_icppfunc_t (char **);
270
271@item typedef void rl_voidfunc_t (void);
272@item typedef void rl_vintfunc_t (int);
273@item typedef void rl_vcpfunc_t (char *);
274@item typedef void rl_vcppfunc_t (char **);
275
276@end table
277
278@noindent
279The @file{rltypedefs.h} file has more documentation for these types.
280
281@node Function Writing
282@subsection Writing a New Function
283
284In order to write new functions for Readline, you need to know the
285calling conventions for keyboard-invoked functions, and the names of the
286variables that describe the current state of the line read so far.
287
288The calling sequence for a command @code{foo} looks like
289
290@example
291@code{int foo (int count, int key)}
292@end example
293
294@noindent
295where @var{count} is the numeric argument (or 1 if defaulted) and
296@var{key} is the key that invoked this function.
297
298It is completely up to the function as to what should be done with the
299numeric argument.
300Some functions use it as a repeat count, some
301as a flag, and others to choose alternate behavior (refreshing the current
302line as opposed to refreshing the screen, for example).
303Some choose to ignore it.
304In general, if a
305function uses the numeric argument as a repeat count, it should be able
306to do something useful with both negative and positive arguments.
307At the very least, it should be aware that it can be passed a
308negative argument.
309
310A command function should return 0 if its action completes successfully,
311and a value greater than zero if some error occurs.
312All of the builtin Readline bindable command functions
313obey this convention.
314
315@node Readline Variables
316@section Readline Variables
317
318These variables are available to function writers.
319
320@deftypevar {char *} rl_line_buffer
321This is the line gathered so far.
322You are welcome to modify the contents of the line,
323but see @ref{Allowing Undoing}.
324The function @code{rl_extend_line_buffer} will increase
325the memory allocated to @code{rl_line_buffer}.
326@end deftypevar
327
328@deftypevar int rl_point
329The offset of the current cursor position in @code{rl_line_buffer}
330(the @emph{point}).
331@end deftypevar
332
333@deftypevar int rl_end
334The number of characters present in @code{rl_line_buffer}.
335When @code{rl_point} is at the end of the line,
336@code{rl_point} and @code{rl_end} are equal.
337@end deftypevar
338
339@deftypevar int rl_mark
340The @var{mark} (saved position) in the current line.
341If set, the mark and point define a @emph{region}.
342Some Readline commands set the mark as part of operating;
343users can also set the mark explicitly.
344@end deftypevar
345
346@deftypevar int rl_done
347Setting this to a non-zero value causes Readline to return the current
348line immediately.
349Readline will set this variable when it has read a key sequence bound
350to @code{accept-line} and is about to return the line to the caller.
351@end deftypevar
352
353@deftypevar int rl_eof_found
354Readline will set this variable when it has read an EOF character
355(e.g., the stty @samp{EOF} character) on an empty line
356or has encountered a read error or EOF and
357is about to return a NULL line to the caller.
358@end deftypevar
359
360@deftypevar int rl_num_chars_to_read
361Setting this to a positive value before calling @code{readline()} causes
362Readline to return after accepting that many characters, rather
363than reading up to a character bound to @code{accept-line}.
364@end deftypevar
365
366@deftypevar int rl_pending_input
367Setting this to a value makes it the next keystroke read.
368This is a way to stuff a single character into the input stream.
369@end deftypevar
370
371@deftypevar int rl_dispatching
372Set to a non-zero value if a function is being called from a key binding;
373zero otherwise.
374Application functions can test this to discover whether
375they were called directly or by Readline's dispatching mechanism.
376@end deftypevar
377
378@deftypevar int rl_erase_empty_line
379Setting this to a non-zero value causes Readline to completely erase
380the current line, including any prompt, any time a newline is typed as
381the only character on an otherwise-empty line.
382This moves the cursor to the beginning of the newly-blank line.
383@end deftypevar
384
385@deftypevar {char *} rl_prompt
386The prompt Readline uses.
387This is set from the argument to
388@code{readline()}, and should not be assigned to directly.
389The @code{rl_set_prompt()} function (@pxref{Redisplay}) may
390be used to modify the prompt string after calling @code{readline()}.
391Readline performs some prompt expansions and analyzes the prompt for
392line breaks, so @code{rl_set_prompt()} is preferred.
393@end deftypevar
394
395@deftypevar {char *} rl_display_prompt
396The string displayed as the prompt.
397This is usually identical to
398@var{rl_prompt}, but may be changed temporarily by functions that
399use the prompt string as a message area, such as incremental search.
400@end deftypevar
401
402@deftypevar int rl_already_prompted
403If an application wishes to display the prompt itself, rather than have
404Readline do it the first time @code{readline()} is called, it should set
405this variable to a non-zero value after displaying the prompt.
406The prompt must also be passed as the argument to @code{readline()} so
407the redisplay functions can update the display properly.
408The calling application is responsible for managing the value; Readline
409never sets it.
410@end deftypevar
411
412@deftypevar {const char *} rl_library_version
413The version number of this revision of the Readline library, as a string
414(e.g., "4.2").
415@end deftypevar
416
417@deftypevar {int} rl_readline_version
418An integer encoding the current version of the library.
419The encoding is of the form 0x@var{MMmm},
420where @var{MM} is the two-digit major version number,
421and @var{mm} is the two-digit minor version number.
422For example, for Readline-4.2, @code{rl_readline_version} would have the
423value 0x0402.
424@end deftypevar
425
426@deftypevar {int} rl_gnu_readline_p
427Always set to 1, denoting that this is @sc{gnu} Readline rather than some
428emulation.
429@end deftypevar
430
431@deftypevar {const char *} rl_terminal_name
432The terminal type, used for initialization.
433If not set by the application,
434Readline sets this to the value of the @env{TERM} environment variable
435the first time it is called.
436Readline uses this to look up the terminal capabilities it needs in
437the terminfo database.
438@end deftypevar
439
440@deftypevar {const char *} rl_readline_name
441This variable is set to a unique name by each application using Readline.
442The value allows conditional parsing of the inputrc file
443(@pxref{Conditional Init Constructs}).
444@end deftypevar
445
446@deftypevar {FILE *} rl_instream
447The stdio stream from which Readline reads input.
448If @code{NULL}, Readline defaults to @var{stdin}.
449@end deftypevar
450
451@deftypevar {FILE *} rl_outstream
452The stdio stream to which Readline performs output.
453If @code{NULL}, Readline defaults to @var{stdout}.
454@end deftypevar
455
456@deftypevar int rl_prefer_env_winsize
457If non-zero, Readline gives values found in the @env{LINES} and
458@env{COLUMNS} environment variables greater precedence than values fetched
459from the kernel when computing the screen dimensions.
460@end deftypevar
461
462@deftypevar {rl_command_func_t *} rl_last_func
463The address of the last command function Readline executed.
464This may be used to test whether or not a function is being executed
465twice in succession, for example.
466@end deftypevar
467
468@deftypevar {rl_hook_func_t *} rl_startup_hook
469If non-zero, this is the address of a function to call just
470before Readline prints the first prompt.
471@end deftypevar
472
473@deftypevar {rl_hook_func_t *} rl_pre_input_hook
474If non-zero, this is the address of a function to call after
475the first prompt has been printed and just before Readline
476starts reading input characters.
477@end deftypevar
478
479@deftypevar {rl_hook_func_t *} rl_event_hook
480If non-zero, this is the address of a function to call periodically
481when Readline is waiting for terminal input.
482By default, this will be called at most ten times a second if there
483is no keyboard input.
484@end deftypevar
485
486@deftypevar {rl_getc_func_t *} rl_getc_function
487If non-zero, Readline will call indirectly through this pointer
488to get a character from the input stream.
489By default, it is set to @code{rl_getc}, the Readline character
490input function (@pxref{Character Input}).
491In general, an application that sets @var{rl_getc_function} should consider
492setting @var{rl_input_available_hook} as well.
493@end deftypevar
494
495@deftypevar {rl_hook_func_t *} rl_signal_event_hook
496If non-zero, this is the address of a function to call if a read system
497call is interrupted by a signal when Readline is reading terminal input.
498@end deftypevar
499
500@deftypevar {rl_hook_func_t *} rl_timeout_event_hook
501If non-zero, this is the address of a function to call if Readline times
502out while reading input.
503@end deftypevar
504
505@deftypevar {rl_hook_func_t *} rl_input_available_hook
506If non-zero, Readline will use this function's return value when it needs
507to determine whether or not there is available input on the current input
508source.
509The default hook checks @code{rl_instream}; if an application is using a
510different input source, it should set the hook appropriately.
511Readline queries for available input when implementing intra-key-sequence
512timeouts during input and incremental searches.
513This function must return zero if there is no input available, and non-zero
514if input is available.
515This may use an application-specific timeout before returning a value;
516Readline uses the value passed to @code{rl_set_keyboard_input_timeout()}
517or the value of the user-settable @var{keyseq-timeout} variable.
518This is designed for use by applications using Readline's callback interface
519(@pxref{Alternate Interface}), which may not use the traditional
520@code{read(2)} and file descriptor interface, or other applications using
521a different input mechanism.
522If an application uses an input mechanism or hook that can potentially exceed
523the value of @var{keyseq-timeout}, it should increase the timeout or set
524this hook appropriately even when not using the callback interface.
525In general, an application that sets @var{rl_getc_function} should consider
526setting @var{rl_input_available_hook} as well.
527@end deftypevar
528
529@deftypevar {rl_voidfunc_t *} rl_redisplay_function
530Readline will call indirectly through this pointer
531to update the display with the current contents of the editing buffer.
532By default, it is set to @code{rl_redisplay}, the default Readline
533redisplay function (@pxref{Redisplay}).
534@end deftypevar
535
536@deftypevar {rl_vintfunc_t *} rl_prep_term_function
537If non-zero, Readline will call indirectly through this pointer
538to initialize the terminal.
539The function takes a single argument, an
540@code{int} flag that says whether or not to use eight-bit characters.
541By default, this is set to @code{rl_prep_terminal}
542(@pxref{Terminal Management}).
543@end deftypevar
544
545@deftypevar {rl_voidfunc_t *} rl_deprep_term_function
546If non-zero, Readline will call indirectly through this pointer
547to reset the terminal.
548This function should undo the effects of @code{rl_prep_term_function}.
549By default, this is set to @code{rl_deprep_terminal}
550(@pxref{Terminal Management}).
551@end deftypevar
552
553@deftypevar {void} rl_macro_display_hook
554If set, this points to a function that @code{rl_macro_dumper} will call to
555display a key sequence bound to a macro.
556It is called with the key sequence, the "untranslated" macro value (i.e.,
557with backslash escapes included, as when passed to @code{rl_macro_bind}),
558the @code{readable} argument passed to @code{rl_macro_dumper}, and any
559prefix to display before the key sequence.
560@end deftypevar
561
562@deftypevar {Keymap} rl_executing_keymap
563This variable is set to the keymap (@pxref{Keymaps}) in which the
564currently executing Readline function was found.
565@end deftypevar
566
567@deftypevar {Keymap} rl_binding_keymap
568This variable is set to the keymap (@pxref{Keymaps}) in which the
569last key binding occurred.
570@end deftypevar
571
572@deftypevar {char *} rl_executing_macro
573This variable is set to the text of any currently-executing macro.
574@end deftypevar
575
576@deftypevar int rl_executing_key
577The key that caused the dispatch to the currently-executing Readline function.
578@end deftypevar
579
580@deftypevar {char *} rl_executing_keyseq
581The full key sequence that caused the dispatch to the currently-executing
582Readline function.
583@end deftypevar
584
585@deftypevar int rl_key_sequence_length
586The number of characters in @var{rl_executing_keyseq}.
587@end deftypevar
588
589@deftypevar {int} rl_readline_state
590A variable with bit values that encapsulate the current Readline state.
591A bit is set with the @code{RL_SETSTATE} macro, and unset with the
592@code{RL_UNSETSTATE} macro.
593Use the @code{RL_ISSTATE} macro to test whether a particular state
594bit is set.
595Current state bits include:
596
597@table @code
598@item RL_STATE_NONE
599Readline has not yet been called, nor has it begun to initialize.
600@item RL_STATE_INITIALIZING
601Readline is initializing its internal data structures.
602@item RL_STATE_INITIALIZED
603Readline has completed its initialization.
604@item RL_STATE_TERMPREPPED
605Readline has modified the terminal modes to do its own input and redisplay.
606@item RL_STATE_READCMD
607Readline is reading a command from the keyboard.
608@item RL_STATE_METANEXT
609Readline is reading more input after reading the meta-prefix character.
610@item RL_STATE_DISPATCHING
611Readline is dispatching to a command.
612@item RL_STATE_MOREINPUT
613Readline is reading more input while executing an editing command.
614@item RL_STATE_ISEARCH
615Readline is performing an incremental history search.
616@item RL_STATE_NSEARCH
617Readline is performing a non-incremental history search.
618@item RL_STATE_SEARCH
619Readline is searching backward or forward through the history for a string.
620@item RL_STATE_NUMERICARG
621Readline is reading a numeric argument.
622@item RL_STATE_MACROINPUT
623Readline is currently getting its input from a previously-defined keyboard
624macro.
625@item RL_STATE_MACRODEF
626Readline is currently reading characters defining a keyboard macro.
627@item RL_STATE_OVERWRITE
628Readline is in overwrite mode.
629@item RL_STATE_COMPLETING
630Readline is performing word completion.
631@item RL_STATE_SIGHANDLER
632Readline is currently executing the Readline signal handler.
633@item RL_STATE_UNDOING
634Readline is performing an undo.
635@item RL_STATE_INPUTPENDING
636Readline has input pending due to a call to @code{rl_execute_next()}.
637@item RL_STATE_TTYCSAVED
638Readline has saved the values of the terminal's special characters.
639@item RL_STATE_CALLBACK
640Readline is currently using the alternate (callback) interface
641(@pxref{Alternate Interface}).
642@item RL_STATE_VIMOTION
643Readline is reading the argument to a vi-mode "motion" command.
644@item RL_STATE_MULTIKEY
645Readline is reading a multiple-keystroke command.
646@item RL_STATE_VICMDONCE
647Readline has entered vi command (movement) mode at least one time during
648the current call to @code{readline()}.
649@item RL_STATE_DONE
650Readline has read a key sequence bound to @code{accept-line}
651and is about to return the line to the caller.
652@item RL_STATE_TIMEOUT
653Readline has timed out (it did not receive a line or specified number of
654characters before the timeout duration specified by @code{rl_set_timeout}
655elapsed) and is returning that status to the caller.
656@item RL_STATE_EOF
657Readline has read an EOF character (e.g., the stty @samp{EOF} character)
658or encountered a read error or EOF
659and is about to return a NULL line to the caller.
660@end table
661
662@end deftypevar
663
664@deftypevar {int} rl_explicit_arg
665Set to a non-zero value if an explicit numeric argument was specified by
666the user.
667It is only valid in a bindable command function.
668@end deftypevar
669
670@deftypevar {int} rl_numeric_arg
671Set to the value of any numeric argument explicitly specified by the user
672before executing the current Readline function.
673It is only valid in a bindable command function.
674@end deftypevar
675
676@deftypevar {int} rl_editing_mode
677Set to a value denoting Readline's current editing mode.
678A value of @var{1} means Readline is currently in emacs mode;
679@var{0} means that vi mode is active.
680This determines the current keymap and key bindings.
681@end deftypevar
682
683@node Readline Convenience Functions
684@section Readline Convenience Functions
685
686@menu
687* Function Naming:: How to give a function you write a name.
688* Keymaps:: Making keymaps.
689* Binding Keys:: Changing Keymaps.
690* Associating Function Names and Bindings:: Translate function names to
691 key sequences.
692* Allowing Undoing:: How to make your functions undoable.
693* Redisplay:: Functions to control line display.
694* Modifying Text:: Functions to modify @code{rl_line_buffer}.
695* Character Input:: Functions to read keyboard input.
696* Terminal Management:: Functions to manage terminal settings.
697* Utility Functions:: Generally useful functions and hooks.
698* Miscellaneous Functions:: Functions that don't fall into any category.
699* Alternate Interface:: Using Readline in a `callback' fashion.
700* A Readline Example:: An example Readline function.
701* Alternate Interface Example:: An example program using the alternate interface.
702@end menu
703
704@node Function Naming
705@subsection Naming a Function
706
707Readline has a descriptive
708string name for every function a user can bind to a key sequence,
709so users can dynamically change the bindings associated with key
710sequences while using Readline,
711using the descriptive name when referring to the function.
712Thus, in an init file, one might find
713
714@example
715Meta-Rubout: backward-kill-word
716@end example
717
718This binds the keystroke @key{Meta-Rubout} to the function
719@emph{descriptively} named @code{backward-kill-word}.
720As the programmer, you
721should bind the functions you write to descriptive names as well.
722Readline provides a function for doing that:
723
724@deftypefun int rl_add_defun (const char *name, rl_command_func_t *function, int key)
725Add @var{name} to the list of named functions.
726Make @var{function} be the function that gets called by key sequences
727that bind to @var{name}.
728If @var{key} is not -1, then bind it to
729@var{function} using @code{rl_bind_key()}.
730@end deftypefun
731
732Using this function alone is sufficient for most applications.
733It is the recommended way to add a few functions to the default
734functions that Readline has built in.
735If you need to do something other than adding a function to Readline,
736you may need to use the underlying functions described below.
737
738@node Keymaps
739@subsection Selecting a Keymap
740
741Key bindings take place on a @dfn{keymap}.
742The keymap is the association between the keys that the user types and
743the functions that get run.
744You can make your own keymaps, copy existing keymaps, and tell
745Readline which keymap to use.
746
747@deftypefun Keymap rl_make_bare_keymap (void)
748Returns a new, empty keymap.
749The space for the keymap is allocated with
750@code{malloc()}; the caller should free it by calling
751@code{rl_free_keymap()} when done.
752@end deftypefun
753
754@deftypefun Keymap rl_copy_keymap (Keymap map)
755Return a new keymap which is a copy of @var{map}.
756@end deftypefun
757
758@deftypefun Keymap rl_make_keymap (void)
759Return a new keymap with the printing characters bound to rl_insert,
760the lowercase Meta characters bound to run their equivalents, and
761the Meta digits bound to produce numeric arguments.
762@end deftypefun
763
764@deftypefun void rl_discard_keymap (Keymap keymap)
765Free the storage associated with the data in @var{keymap}.
766The caller should free @var{keymap}.
767@end deftypefun
768
769@deftypefun void rl_free_keymap (Keymap keymap)
770Free all storage associated with @var{keymap}.
771This calls @code{rl_discard_keymap} to free subordinate
772keymaps and macros.
773@end deftypefun
774
775@deftypefun int rl_empty_keymap (Keymap keymap)
776Return non-zero if there are no keys bound to functions in @var{keymap};
777zero if there are any keys bound.
778@end deftypefun
779
780Readline has several internal keymaps.
781These functions allow you to change which keymap is active.
782This is one way to switch editing modes, for example.
783
784@deftypefun Keymap rl_get_keymap (void)
785Returns the currently active keymap.
786@end deftypefun
787
788@deftypefun void rl_set_keymap (Keymap keymap)
789Makes @var{keymap} the currently active keymap.
790@end deftypefun
791
792@deftypefun Keymap rl_get_keymap_by_name (const char *name)
793Return the keymap matching @var{name}.
794@var{name} is one which would be supplied in a
795@code{set keymap} inputrc line (@pxref{Readline Init File}).
796@end deftypefun
797
798@deftypefun {char *} rl_get_keymap_name (Keymap keymap)
799Return the name matching @var{keymap}.
800@var{name} is one which would be supplied in a
801@code{set keymap} inputrc line (@pxref{Readline Init File}).
802@end deftypefun
803
804@deftypefun int rl_set_keymap_name (const char *name, Keymap keymap)
805Set the name of @var{keymap}.
806This name will then be "registered" and
807available for use in a @code{set keymap} inputrc directive
808@pxref{Readline Init File}).
809The @var{name} may not be one of Readline's builtin keymap names;
810you may not add a different name for one of Readline's builtin keymaps.
811You may replace the name associated with a given keymap by calling this
812function more than once with the same @var{keymap} argument.
813You may associate a registered @var{name} with a new keymap by calling this
814function more than once with the same @var{name} argument.
815There is no way to remove a named keymap once the name has been
816registered.
817Readline will make a copy of @var{name}.
818The return value is greater than zero unless @var{name} is one of
819Readline's builtin keymap names or @var{keymap} is one of Readline's
820builtin keymaps.
821@end deftypefun
822
823@node Binding Keys
824@subsection Binding Keys
825
826Key sequences are associated with functions through the keymap.
827Readline has several internal keymaps: @code{emacs_standard_keymap},
828@code{emacs_meta_keymap}, @code{emacs_ctlx_keymap},
829@code{vi_movement_keymap}, and @code{vi_insertion_keymap}.
830@code{emacs_standard_keymap} is the default, and the examples in
831this manual assume that.
832
833Since @code{readline()} installs a set of default key bindings the first
834time it is called, there is always the danger that a custom binding
835installed before the first call to @code{readline()} will be overridden.
836An alternate mechanism that can avoid this
837is to install custom key bindings in an
838initialization function assigned to the @code{rl_startup_hook} variable
839(@pxref{Readline Variables}).
840
841These functions manage key bindings.
842
843@deftypefun int rl_bind_key (int key, rl_command_func_t *function)
844Binds @var{key} to @var{function} in the currently active keymap.
845Returns non-zero in the case of an invalid @var{key}.
846@end deftypefun
847
848@deftypefun int rl_bind_key_in_map (int key, rl_command_func_t *function, Keymap map)
849Bind @var{key} to @var{function} in @var{map}.
850Returns non-zero in the case of an invalid @var{key}.
851@end deftypefun
852
853@deftypefun int rl_bind_key_if_unbound (int key, rl_command_func_t *function)
854Binds @var{key} to @var{function} if it is not already bound in the
855currently active keymap.
856Returns non-zero in the case of an invalid @var{key} or if @var{key} is
857already bound.
858@end deftypefun
859
860@deftypefun int rl_bind_key_if_unbound_in_map (int key, rl_command_func_t *function, Keymap map)
861Binds @var{key} to @var{function} if it is not already bound in @var{map}.
862Returns non-zero in the case of an invalid @var{key} or if @var{key} is
863already bound.
864@end deftypefun
865
866@deftypefun int rl_unbind_key (int key)
867Bind @var{key} to the null function in the currently active keymap.
868This is not the same as binding it to @code{self-insert}.
869Returns non-zero in case of error.
870@end deftypefun
871
872@deftypefun int rl_unbind_key_in_map (int key, Keymap map)
873Bind @var{key} to the null function in @var{map}.
874This is not the same as binding it to @code{self-insert}.
875Returns non-zero in case of error.
876@end deftypefun
877
878@deftypefun int rl_unbind_function_in_map (rl_command_func_t *function, Keymap map)
879Unbind all keys that execute @var{function} in @var{map}.
880@end deftypefun
881
882@deftypefun int rl_unbind_command_in_map (const char *command, Keymap map)
883Unbind all keys that are bound to @var{command} in @var{map}.
884@end deftypefun
885
886@deftypefun int rl_bind_keyseq (const char *keyseq, rl_command_func_t *function)
887Bind the key sequence represented by the string @var{keyseq} to the function
888@var{function}, beginning in the current keymap.
889This makes new keymaps as necessary.
890The return value is non-zero if @var{keyseq} is invalid.
891@end deftypefun
892
893@deftypefun int rl_bind_keyseq_in_map (const char *keyseq, rl_command_func_t *function, Keymap map)
894Bind the key sequence represented by the string @var{keyseq} to the function
895@var{function} in @var{map}.
896This makes new keymaps as necessary.
897Initial bindings are performed in @var{map}.
898The return value is non-zero if @var{keyseq} is invalid.
899@end deftypefun
900
901@deftypefun int rl_set_key (const char *keyseq, rl_command_func_t *function, Keymap map)
902Equivalent to @code{rl_bind_keyseq_in_map}.
903@end deftypefun
904
905@deftypefun int rl_bind_keyseq_if_unbound (const char *keyseq, rl_command_func_t *function)
906Binds @var{keyseq} to @var{function} if it is not already bound in the
907currently active keymap.
908Returns non-zero in the case of an invalid @var{keyseq} or if @var{keyseq} is
909already bound.
910@end deftypefun
911
912@deftypefun int rl_bind_keyseq_if_unbound_in_map (const char *keyseq, rl_command_func_t *function, Keymap map)
913Binds @var{keyseq} to @var{function} if it is not already bound in @var{map}.
914Returns non-zero in the case of an invalid @var{keyseq} or if @var{keyseq} is
915already bound.
916@end deftypefun
917
918@deftypefun int rl_generic_bind (int type, const char *keyseq, char *data, Keymap map)
919Bind the key sequence represented by the string @var{keyseq} to the arbitrary
920pointer @var{data}.
921@var{type} says what kind of data is pointed to by @var{data}; this can be
922a function (@code{ISFUNC}),
923a macro (@code{ISMACR}),
924or a keymap (@code{ISKMAP}).
925This makes new keymaps as necessary.
926The initial keymap in which to do bindings is @var{map}.
927Returns non-zero in the case of an invalid @var{keyseq}, zero otherwise.
928@end deftypefun
929
930@deftypefun int rl_parse_and_bind (char *line)
931Parse @var{line} as if it had been read from the @code{inputrc} file and
932perform any key bindings and variable assignments found
933(@pxref{Readline Init File}).
934@end deftypefun
935
936@deftypefun int rl_read_init_file (const char *filename)
937Read keybindings and variable assignments from @var{filename}
938(@pxref{Readline Init File}).
939@end deftypefun
940
941@node Associating Function Names and Bindings
942@subsection Associating Function Names and Bindings
943
944These functions allow you to find out what keys invoke named functions
945and the functions invoked by a particular key sequence.
946You may also associate a new function name with an arbitrary function.
947
948@deftypefun {rl_command_func_t *} rl_named_function (const char *name)
949Return the function with name @var{name}.
950@var{name} is a descriptive name users might use in a key binding.
951@end deftypefun
952
953@deftypefun {rl_command_func_t *} rl_function_of_keyseq (const char *keyseq, Keymap map, int *type)
954Return the function invoked by @var{keyseq} in keymap @var{map}.
955If @var{map} is @code{NULL}, this uses the current keymap.
956If @var{type} is not @code{NULL}, this returns the type of the object
957in the @code{int} variable it points to
958(one of @code{ISFUNC}, @code{ISKMAP}, or @code{ISMACR}).
959It takes a "translated" key sequence and should not be used
960if the key sequence can include NUL.
961@end deftypefun
962
963@deftypefun {rl_command_func_t *} rl_function_of_keyseq_len (const char *keyseq, size_t len, Keymap map, int *type)
964Return the function invoked by @var{keyseq} of length @var{len}
965in keymap @var{map}.
966Equivalent to @code{rl_function_of_keyseq} with the addition
967of the @var{len} parameter.
968It takes a "translated" key sequence and should be used
969if the key sequence can include NUL.
970@end deftypefun
971
972@deftypefun {int} rl_trim_arg_from_keyseq (const char *keyseq, size_t len, Keymap map)
973If there is a numeric argument at the beginning of @var{keyseq}, possibly
974including digits, return the index of the first character in @var{keyseq}
975following the numeric argument.
976This can be used to skip over the numeric argument (which is available as
977@code{rl_numeric_arg}) while traversing the key sequence that invoked the
978current command.
979@end deftypefun
980
981@deftypefun {char **} rl_invoking_keyseqs (rl_command_func_t *function)
982Return an array of strings representing the key sequences used to
983invoke @var{function} in the current keymap.
984@end deftypefun
985
986@deftypefun {char **} rl_invoking_keyseqs_in_map (rl_command_func_t *function, Keymap map)
987Return an array of strings representing the key sequences used to
988invoke @var{function} in the keymap @var{map}.
989@end deftypefun
990
991@deftypefun void rl_print_keybinding (const char *name, Keymap map, int readable)
992Print key sequences bound to Readline function name @var{name} in
993keymap @var{map}.
994If @var{map} is NULL, this uses the current keymap.
995If @var{readable} is non-zero,
996the list is formatted in such a way that it can be made part of an
997@code{inputrc} file and re-read to recreate the key binding.
998@end deftypefun
999
1000@deftypefun void rl_function_dumper (int readable)
1001Print the Readline function names and the key sequences currently
1002bound to them to @code{rl_outstream}.
1003If @var{readable} is non-zero,
1004the list is formatted in such a way that it can be made part of an
1005@code{inputrc} file and re-read.
1006@end deftypefun
1007
1008@deftypefun void rl_list_funmap_names (void)
1009Print the names of all bindable Readline functions to @code{rl_outstream}.
1010@end deftypefun
1011
1012@deftypefun {const char **} rl_funmap_names (void)
1013Return a NULL terminated array of known function names.
1014The array is sorted.
1015The array itself is allocated, but not the strings inside.
1016You should free the array, but not the pointers, using @code{free}
1017or @code{rl_free} when you are done.
1018@end deftypefun
1019
1020@deftypefun int rl_add_funmap_entry (const char *name, rl_command_func_t *function)
1021Add @var{name} to the list of bindable Readline command names, and make
1022@var{function} the function to be called when @var{name} is invoked.
1023This returns the index of the newly-added @var{name} in the array of
1024function names.
1025@end deftypefun
1026
1027@node Allowing Undoing
1028@subsection Allowing Undoing
1029
1030Supporting the undo command is a painless thing, and makes your
1031functions much more useful.
1032It is certainly easier to try something if you know you can undo it.
1033
1034If your function simply inserts text once, or deletes text once,
1035and uses @code{rl_insert_text()} or @code{rl_delete_text()} to do it,
1036then Readline does the undoing for you automatically.
1037
1038If you do multiple insertions or multiple deletions, or any combination
1039of these operations, you should group them together into one operation.
1040This is done with @code{rl_begin_undo_group()} and
1041@code{rl_end_undo_group()}.
1042
1043The types of events Readline can undo are:
1044
1045@smallexample
1046enum undo_code @{ UNDO_DELETE, UNDO_INSERT, UNDO_BEGIN, UNDO_END @};
1047@end smallexample
1048
1049Notice that @code{UNDO_DELETE} means to insert some text, and
1050@code{UNDO_INSERT} means to delete some text.
1051That is, the undo code tells what to undo, not how to undo it.
1052@code{UNDO_BEGIN} and @code{UNDO_END} are tags
1053added by @code{rl_begin_undo_group()} and @code{rl_end_undo_group()};
1054they are how Readline delimits groups of commands that should be
1055undone together.
1056
1057@deftypefun int rl_begin_undo_group (void)
1058Begins saving undo information in a group construct.
1059The undo information usually comes from calls to @code{rl_insert_text()}
1060and @code{rl_delete_text()}, but could be the result of calls to
1061@code{rl_add_undo()}.
1062@end deftypefun
1063
1064@deftypefun int rl_end_undo_group (void)
1065Closes the current undo group started with @code{rl_begin_undo_group()}.
1066There should be one call to @code{rl_end_undo_group()}
1067for each call to @code{rl_begin_undo_group()}.
1068@end deftypefun
1069
1070@deftypefun void rl_add_undo (enum undo_code what, int start, int end, char *text)
1071Remember how to undo an event (according to @var{what}).
1072The affected text runs from @var{start} to @var{end},
1073and encompasses @var{text}.
1074@end deftypefun
1075
1076@deftypefun void rl_free_undo_list (void)
1077Free the existing undo list.
1078@end deftypefun
1079
1080@deftypefun int rl_do_undo (void)
1081Undo the first thing on the undo list.
1082Returns @code{0} if there was nothing to undo,
1083non-zero if something was undone.
1084@end deftypefun
1085
1086Finally, if you neither insert nor delete text, but directly modify the
1087existing text (e.g., change its case), call @code{rl_modifying()}
1088once, just before you modify the text.
1089You must supply the indices of the text range that you are going to modify.
1090Readline will create an undo group for you.
1091
1092@deftypefun int rl_modifying (int start, int end)
1093Tell Readline to save the text between @var{start} and @var{end} as a
1094single undo unit.
1095It is assumed that you will subsequently modify that text.
1096@end deftypefun
1097
1098@node Redisplay
1099@subsection Redisplay
1100
1101@deftypefun void rl_redisplay (void)
1102Change what's displayed on the screen to reflect the current contents
1103of @code{rl_line_buffer}.
1104@end deftypefun
1105
1106@deftypefun int rl_forced_update_display (void)
1107Force the line to be updated and redisplayed, whether or not
1108Readline thinks the screen display is correct.
1109@end deftypefun
1110
1111@deftypefun int rl_on_new_line (void)
1112Tell the update functions that we have moved onto a new (empty) line,
1113usually after outputting a newline.
1114@end deftypefun
1115
1116@deftypefun int rl_on_new_line_with_prompt (void)
1117Tell the update functions that we have moved onto a new line, with
1118@var{rl_prompt} already displayed.
1119This could be used by applications that want to output the prompt string
1120themselves, but still need Readline to know the prompt string length for
1121redisplay.
1122It should be used after setting @var{rl_already_prompted}.
1123@end deftypefun
1124
1125@deftypefun int rl_clear_visible_line (void)
1126Clear the screen lines corresponding to the current line's contents.
1127@end deftypefun
1128
1129@deftypefun int rl_reset_line_state (void)
1130Reset the display state to a clean state and redisplay the current line
1131starting on a new line.
1132@end deftypefun
1133
1134@deftypefun int rl_crlf (void)
1135Move the cursor to the start of the next screen line.
1136@end deftypefun
1137
1138@deftypefun int rl_show_char (int c)
1139Display character @var{c} on @code{rl_outstream}.
1140If Readline has not been set to display meta characters directly, this
1141will convert meta characters to a meta-prefixed key sequence.
1142This is intended for use by applications which wish to do their own
1143redisplay.
1144@end deftypefun
1145
1146@deftypefun int rl_message (const char *, @dots{})
1147The arguments are a format string as would be supplied to @code{printf},
1148possibly containing conversion specifications such as @samp{%d}, and
1149any additional arguments necessary to satisfy the conversion specifications.
1150The resulting string is displayed in the @dfn{echo area}.
1151The echo area is also used to display numeric arguments and search strings.
1152You should call @code{rl_save_prompt} to save the prompt information
1153before calling this function.
1154@end deftypefun
1155
1156@deftypefun int rl_clear_message (void)
1157Clear the message in the echo area.
1158If the prompt was saved with a call to
1159@code{rl_save_prompt} before the last call to @code{rl_message},
1160you must call @code{rl_restore_prompt} before calling this function.
1161@end deftypefun
1162
1163@deftypefun void rl_save_prompt (void)
1164Save the local Readline prompt display state in preparation for
1165displaying a new message in the message area with @code{rl_message()}.
1166@end deftypefun
1167
1168@deftypefun void rl_restore_prompt (void)
1169Restore the local Readline prompt display state saved by the most
1170recent call to @code{rl_save_prompt}.
1171If you called @code{rl_save_prompt} to save the prompt before a call
1172to @code{rl_message}, you should call this function before the
1173corresponding call to @code{rl_clear_message}.
1174@end deftypefun
1175
1176@deftypefun int rl_expand_prompt (char *prompt)
1177Expand any special character sequences in @var{prompt} and set up the
1178local Readline prompt redisplay variables.
1179This function is called by @code{readline()}.
1180It may also be called to
1181expand the primary prompt if the application uses the
1182@code{rl_on_new_line_with_prompt()} function or
1183@code{rl_already_prompted} variable.
1184It returns the number of visible characters on the last line of the
1185(possibly multi-line) prompt.
1186Applications may indicate that the prompt contains characters that take
1187up no physical screen space when displayed by bracketing a sequence of
1188such characters with the special markers @code{RL_PROMPT_START_IGNORE}
1189and @code{RL_PROMPT_END_IGNORE} (declared in @file{readline.h} as
1190@samp{\001} and @samp{\002}, respectively).
1191This may be used to embed terminal-specific escape sequences in prompts.
1192If you don't use these indicators, redisplay will likely produce screen
1193contents that don't match the line buffer.
1194@end deftypefun
1195
1196@deftypefun int rl_set_prompt (const char *prompt)
1197Make Readline use @var{prompt} for subsequent redisplay.
1198This calls @code{rl_expand_prompt()} to expand the prompt
1199and sets @code{rl_prompt} to the result.
1200@end deftypefun
1201
1202@node Modifying Text
1203@subsection Modifying Text
1204
1205@deftypefun int rl_insert_text (const char *text)
1206Insert @var{text} into the line at the current cursor position.
1207Returns the number of characters inserted.
1208@end deftypefun
1209
1210@deftypefun int rl_delete_text (int start, int end)
1211Delete the text between @var{start} and @var{end} in the current line.
1212Returns the number of characters deleted.
1213@end deftypefun
1214
1215@deftypefun {char *} rl_copy_text (int start, int end)
1216Return a copy of the text between @var{start} and @var{end} in
1217the current line.
1218@end deftypefun
1219
1220@deftypefun int rl_kill_text (int start, int end)
1221Copy the text between @var{start} and @var{end} in the current line
1222to the kill ring, appending or prepending to the last kill if the
1223last command was a kill command.
1224This deletes the text from the line.
1225If @var{start} is less than @var{end}, the text is appended,
1226otherwise it is prepended.
1227If the last command was not a kill, this uses a new kill ring slot.
1228@end deftypefun
1229
1230@deftypefun void rl_replace_line (const char *text, int clear_undo)
1231Replace the contents of @code{rl_line_buffer} with @var{text}.
1232This preserves the point and mark, if possible.
1233If @var{clear_undo} is non-zero, this clears the undo list associated
1234with the current line.
1235@end deftypefun
1236
1237@deftypefun int rl_push_macro_input (char *macro)
1238Insert @var{macro} into the line, as if it had been invoked
1239by a key bound to a macro.
1240Not especially useful; use @code{rl_insert_text()} instead.
1241@end deftypefun
1242
1243@node Character Input
1244@subsection Character Input
1245
1246@deftypefun int rl_read_key (void)
1247Return the next character available from Readline's current input stream.
1248This handles input inserted into
1249the input stream via @var{rl_pending_input} (@pxref{Readline Variables})
1250and @code{rl_stuff_char()}, macros, and characters read from the keyboard.
1251While waiting for input, this function will call any function assigned to
1252the @code{rl_event_hook} variable.
1253@end deftypefun
1254
1255@deftypefun int rl_getc (FILE *stream)
1256Return the next character available from @var{stream}, which is assumed to
1257be the keyboard.
1258@end deftypefun
1259
1260@deftypefun int rl_stuff_char (int c)
1261Insert @var{c} into the Readline input stream.
1262It will be "read" before Readline attempts to read characters
1263from the terminal with @code{rl_read_key()}.
1264Applications can push back up to 512 characters.
1265@code{rl_stuff_char} returns 1 if the character was successfully inserted;
12660 otherwise.
1267@end deftypefun
1268
1269@deftypefun int rl_execute_next (int c)
1270Make @var{c} be the next command to be executed when @code{rl_read_key()}
1271is called.
1272This sets @var{rl_pending_input}.
1273@end deftypefun
1274
1275@deftypefun int rl_clear_pending_input (void)
1276Unset @var{rl_pending_input}, effectively negating the effect of any
1277previous call to @code{rl_execute_next()}.
1278This works only if the pending input has not already been read
1279with @code{rl_read_key()}.
1280@end deftypefun
1281
1282@deftypefun int rl_set_keyboard_input_timeout (int u)
1283While waiting for keyboard input in @code{rl_read_key()}, Readline will
1284wait for @var{u} microseconds for input before calling any function
1285assigned to @code{rl_event_hook}.
1286@var{u} must be greater than or equal
1287to zero (a zero-length timeout is equivalent to a poll).
1288The default waiting period is one-tenth of a second.
1289Returns the old timeout value.
1290@end deftypefun
1291
1292@deftypefun int rl_set_timeout (unsigned int secs, unsigned int usecs)
1293Set a timeout for subsequent calls to @code{readline()}.
1294If Readline does not read a complete line, or the number of characters
1295specified by @code{rl_num_chars_to_read},
1296before the duration specified by @var{secs} (in seconds)
1297and @var{usecs} (microseconds), it returns and sets
1298@code{RL_STATE_TIMEOUT} in @code{rl_readline_state}.
1299Passing 0 for @code{secs} and @code{usecs} cancels any previously set
1300timeout; the convenience macro @code{rl_clear_timeout()} is shorthand
1301for this.
1302Returns 0 if the timeout is set successfully.
1303@end deftypefun
1304
1305@deftypefun int rl_timeout_remaining (unsigned int *secs, unsigned int *usecs)
1306Return the number of seconds and microseconds remaining in the current
1307timeout duration in @var{*secs} and @var{*usecs}, respectively.
1308Both @var{*secs} and @var{*usecs} must be non-NULL to return any values.
1309The return value is -1 on error or when there is no timeout set,
13100 when the timeout has expired (leaving @var{*secs} and @var{*usecs}
1311unchanged),
1312and 1 if the timeout has not expired.
1313If either of @var{secs} and @var{usecs} is @code{NULL},
1314the return value indicates whether the timeout has expired.
1315@end deftypefun
1316
1317@node Terminal Management
1318@subsection Terminal Management
1319
1320@deftypefun void rl_prep_terminal (int meta_flag)
1321Modify the terminal settings for Readline's use, so @code{readline()}
1322can read a single character at a time from the keyboard
1323and perform redisplay.
1324The @var{meta_flag} argument should be non-zero if Readline should
1325read eight-bit input.
1326@end deftypefun
1327
1328@deftypefun void rl_deprep_terminal (void)
1329Undo the effects of @code{rl_prep_terminal()}, leaving the terminal in
1330the state in which it was before the most recent call to
1331@code{rl_prep_terminal()}.
1332@end deftypefun
1333
1334@deftypefun void rl_tty_set_default_bindings (Keymap kmap)
1335Read the operating system's terminal editing characters (as would be
1336displayed by @code{stty}) to their Readline equivalents.
1337The bindings are performed in @var{kmap}.
1338@end deftypefun
1339
1340@deftypefun void rl_tty_unset_default_bindings (Keymap kmap)
1341Reset the bindings manipulated by @code{rl_tty_set_default_bindings} so
1342that the terminal editing characters are bound to @code{rl_insert}.
1343The bindings are performed in @var{kmap}.
1344@end deftypefun
1345
1346@deftypefun int rl_tty_set_echoing (int value)
1347Set Readline's idea of whether or not it is
1348echoing output to its output stream (@var{rl_outstream}).
1349If @var{value} is 0,
1350Readline does not display output to @var{rl_outstream}; any other
1351value enables output.
1352The initial value is set when Readline initializes the terminal settings.
1353This function returns the previous value.
1354@end deftypefun
1355
1356@deftypefun int rl_reset_terminal (const char *terminal_name)
1357Reinitialize Readline's idea of the terminal settings using
1358@var{terminal_name} as the terminal type (e.g., @code{xterm}).
1359If @var{terminal_name} is @code{NULL}, Readline uses the value of the
1360@code{TERM} environment variable.
1361@end deftypefun
1362
1363@node Utility Functions
1364@subsection Utility Functions
1365
1366@deftypefun int rl_save_state (struct readline_state *sp)
1367Save a snapshot of Readline's internal state to @var{sp}.
1368The contents of the @var{readline_state} structure are
1369documented in @file{readline.h}.
1370The caller is responsible for allocating the structure.
1371@end deftypefun
1372
1373@deftypefun int rl_restore_state (struct readline_state *sp)
1374Restore Readline's internal state to that stored in @var{sp},
1375which must have been saved by a call to @code{rl_save_state}.
1376The contents of the @var{readline_state} structure are documented in
1377@file{readline.h}.
1378The caller is responsible for freeing the structure.
1379@end deftypefun
1380
1381@deftypefun void rl_free (void *mem)
1382Deallocate the memory pointed to by @var{mem}.
1383@var{mem} must have been allocated by @code{malloc}.
1384@end deftypefun
1385
1386@deftypefun void rl_extend_line_buffer (int len)
1387Ensure that @code{rl_line_buffer} has enough space to hold @var{len}
1388characters, reallocating it if necessary.
1389@end deftypefun
1390
1391@deftypefun int rl_initialize (void)
1392Initialize or re-initialize Readline's internal state.
1393It's not strictly necessary to call this;
1394@code{readline()} calls it before reading any input.
1395@end deftypefun
1396
1397@deftypefun int rl_ding (void)
1398Ring the terminal bell, obeying the setting of @code{bell-style}.
1399@end deftypefun
1400
1401@deftypefun int rl_alphabetic (int c)
1402Return 1 if @var{c} is an alphabetic character.
1403@end deftypefun
1404
1405@deftypefun void rl_display_match_list (char **matches, int len, int max)
1406A convenience function for displaying a list of strings in
1407columnar format on Readline's output stream.
1408@code{matches} is the list of strings, in argv format,
1409such as a list of completion matches.
1410@code{len} is the number of strings in @code{matches}, and @code{max}
1411is the length of the longest string in @code{matches}.
1412This function uses the setting of @code{print-completions-horizontally}
1413to select how the matches are displayed (@pxref{Readline Init File Syntax}).
1414When displaying completions, this function sets the number of columns used
1415for display to the value of @code{completion-display-width}, the value of
1416the environment variable @env{COLUMNS}, or the screen width, in that order.
1417@end deftypefun
1418
1419The following are implemented as macros, defined in @code{chardefs.h}.
1420Applications should refrain from using them.
1421
1422@deftypefun int _rl_uppercase_p (int c)
1423Return 1 if @var{c} is an uppercase alphabetic character.
1424@end deftypefun
1425
1426@deftypefun int _rl_lowercase_p (int c)
1427Return 1 if @var{c} is a lowercase alphabetic character.
1428@end deftypefun
1429
1430@deftypefun int _rl_digit_p (int c)
1431Return 1 if @var{c} is a numeric character.
1432@end deftypefun
1433
1434@deftypefun int _rl_to_upper (int c)
1435If @var{c} is a lowercase alphabetic character, return the corresponding
1436uppercase character.
1437@end deftypefun
1438
1439@deftypefun int _rl_to_lower (int c)
1440If @var{c} is an uppercase alphabetic character, return the corresponding
1441lowercase character.
1442@end deftypefun
1443
1444@deftypefun int _rl_digit_value (int c)
1445If @var{c} is a number, return the value it represents.
1446@end deftypefun
1447
1448@node Miscellaneous Functions
1449@subsection Miscellaneous Functions
1450
1451@deftypefun int rl_macro_bind (const char *keyseq, const char *macro, Keymap map)
1452Bind the key sequence @var{keyseq} to invoke the macro @var{macro}.
1453The binding is performed in @var{map}.
1454When @var{keyseq} is invoked, the @var{macro} will be inserted into the line.
1455This function is deprecated; use @code{rl_generic_bind} instead.
1456@end deftypefun
1457
1458@deftypefun void rl_macro_dumper (int readable)
1459Print the key sequences bound to macros and their values, using
1460the current keymap, to @code{rl_outstream}.
1461If the application has assigned a value to @code{rl_macro_display_hook},
1462@code{rl_macro_dumper} calls it instead of printing anything.
1463If @var{readable} is greater than zero, the list is formatted in such a way
1464that it can be made part of an @code{inputrc} file and re-read.
1465@end deftypefun
1466
1467@deftypefun int rl_variable_bind (const char *variable, const char *value)
1468Make the Readline variable @var{variable} have @var{value}.
1469This behaves as if the Readline command
1470@samp{set @var{variable} @var{value}} had been executed in an @code{inputrc}
1471file (@pxref{Readline Init File Syntax})
1472or by @code{rl_parse_and_bind}.
1473@end deftypefun
1474
1475@deftypefun {char *} rl_variable_value (const char *variable)
1476Return a string representing the value of the Readline variable @var{variable}.
1477For boolean variables, this string is either @samp{on} or @samp{off}.
1478@end deftypefun
1479
1480@deftypefun void rl_variable_dumper (int readable)
1481Print the Readline variable names and their current values
1482to @code{rl_outstream}.
1483If @var{readable} is non-zero, the list is formatted in such a way
1484that it can be made part of an @code{inputrc} file and re-read.
1485@end deftypefun
1486
1487@deftypefun int rl_set_paren_blink_timeout (int u)
1488Set the time interval (in microseconds) that Readline waits when showing
1489a balancing character when @code{blink-matching-paren} has been enabled.
1490@end deftypefun
1491
1492@deftypefun {char *} rl_get_termcap (const char *cap)
1493Retrieve the string value of the termcap capability @var{cap}.
1494Readline fetches the termcap entry for the current terminal name and
1495uses those capabilities to move around the screen line and perform other
1496terminal-specific operations, like erasing a line.
1497Readline does not fetch or use all of a terminal's capabilities,
1498and this function will return
1499values for only those capabilities Readline fetches.
1500@end deftypefun
1501
1502@deftypefun {void} rl_reparse_colors (void)
1503Read or re-read color definitions from @env{LS_COLORS}.
1504@end deftypefun
1505
1506@deftypefun {void} rl_clear_history (void)
1507Clear the history list by deleting all of the entries, in the same manner
1508as the History library's @code{clear_history()} function.
1509This differs from @code{clear_history} because it frees private data
1510Readline saves in the history list.
1511@end deftypefun
1512
1513@deftypefun {void} rl_activate_mark (void)
1514Enable an @emph{active} region.
1515When this is enabled, the text between point and mark (the @var{region}) is
1516displayed using the color specified by the value of the
1517@code{active-region-start-color} variable (a @var{face}).
1518The default face is the terminal's standout mode.
1519This is called by various Readline functions that set the mark and insert
1520text, and is available for applications to call.
1521@end deftypefun
1522
1523@deftypefun {void} rl_deactivate_mark (void)
1524Turn off the active region.
1525@end deftypefun
1526
1527@deftypefun {void} rl_keep_mark_active (void)
1528Indicate that the mark should remain active when the current Readline
1529function completes and after redisplay occurs.
1530In most cases, the mark remains active for only the duration of a single
1531bindable Readline function.
1532@end deftypefun
1533
1534@deftypefun {int} rl_mark_active_p (void)
1535Return a non-zero value if the mark is currently active; zero otherwise.
1536@end deftypefun
1537
1538@node Alternate Interface
1539@subsection Alternate Interface
1540
1541For applications that need more granular control than
1542plain @code{readline()} provides, there is
1543an alternate interface.
1544Some applications need to interleave keyboard I/O with file, device,
1545or window system I/O, typically by using a main loop to @code{select()}
1546on various file descriptors.
1547To accommodate this use case, Readline can
1548also be invoked as a `callback' function from an event loop.
1549There are functions available to make this easy.
1550
1551@deftypefun void rl_callback_handler_install (const char *prompt, rl_vcpfunc_t *line_handler)
1552Set up the terminal for Readline I/O and display the initial
1553expanded value of @var{prompt}.
1554Save the value of @var{line_handler} to
1555use as a handler function to call when a complete line of input has been
1556entered.
1557The handler function receives the text of the line as an argument.
1558As with @code{readline()}, the handler function should @code{free} the
1559line when it it finished with it.
1560@end deftypefun
1561
1562@deftypefun void rl_callback_read_char (void)
1563Whenever an application determines that keyboard input is available, it
1564should call @code{rl_callback_read_char()}, which will read the next
1565character from the current input source.
1566If that character completes the line, @code{rl_callback_read_char} will
1567invoke the @var{line_handler} function installed by
1568@code{rl_callback_handler_install} to process the line.
1569Before calling the @var{line_handler} function, Readline resets
1570the terminal settings to the values they had before calling
1571@code{rl_callback_handler_install}.
1572If the @var{line_handler} function returns,
1573and the line handler remains installed,
1574Readline modifies the terminal settings for its use again.
1575@code{EOF} is indicated by calling @var{line_handler} with a
1576@code{NULL} line.
1577@end deftypefun
1578
1579@deftypefun void rl_callback_sigcleanup (void)
1580Clean up any internal state the callback interface uses to maintain state
1581between calls to rl_callback_read_char (e.g., the state of any active
1582incremental searches).
1583This is intended to be used by applications that
1584wish to perform their own signal handling;
1585Readline's internal signal handler calls this when appropriate.
1586@end deftypefun
1587
1588@deftypefun void rl_callback_handler_remove (void)
1589Restore the terminal to its initial state and remove the line handler.
1590You may call this function from within a callback as well as independently.
1591If the @var{line_handler} installed by @code{rl_callback_handler_install}
1592does not exit the program, your program should call
1593either this function or the function referred
1594to by the value of @code{rl_deprep_term_function}
1595before the program exits to reset the terminal settings.
1596@end deftypefun
1597
1598@node A Readline Example
1599@subsection A Readline Example
1600
1601Here is a function which changes lowercase characters to their uppercase
1602equivalents, and uppercase characters to lowercase.
1603If this function was bound to @samp{M-c}, then typing @samp{M-c} would
1604change the case of the character under point.
1605Typing @samp{M-1 0 M-c} would change the case
1606of the following 10 characters, leaving the cursor on
1607the last character changed.
1608
1609@example
1610/* Invert the case of the COUNT following characters. */
1611int
1612invert_case_line (count, key)
1613 int count, key;
1614@{
1615 int start, end, i;
1616
1617 start = rl_point;
1618
1619 if (rl_point >= rl_end)
1620 return (0);
1621
1622 /* Find the end of the range to modify. */
1623 end = start + count;
1624
1625 /* Force it to be within range. */
1626 if (end > rl_end)
1627 end = rl_end;
1628 else if (end < 0)
1629 end = 0;
1630
1631 if (start == end)
1632 return (0);
1633
1634 /* For positive arguments, put point after the last changed character. For
1635 negative arguments, put point before the last changed character. */
1636 rl_point = end;
1637
1638 /* Swap start and end if we are moving backwards */
1639 if (start > end)
1640 @{
1641 int temp = start;
1642 start = end;
1643 end = temp;
1644 @}
1645
1646 /* Tell readline that we are modifying the line,
1647 so it will save the undo information. */
1648 rl_modifying (start, end);
1649
1650 for (i = start; i != end; i++)
1651 @{
1652 if (_rl_uppercase_p (rl_line_buffer[i]))
1653 rl_line_buffer[i] = _rl_to_lower (rl_line_buffer[i]);
1654 else if (_rl_lowercase_p (rl_line_buffer[i]))
1655 rl_line_buffer[i] = _rl_to_upper (rl_line_buffer[i]);
1656 @}
1657
1658 return (0);
1659@}
1660@end example
1661
1662@node Alternate Interface Example
1663@subsection Alternate Interface Example
1664
1665Here is a complete program that illustrates Readline's alternate interface.
1666It reads lines from the terminal and displays them, providing the
1667standard history and TAB completion functions.
1668It understands the EOF character or "exit" to exit the program.
1669
1670@example
1671/* Standard include files. stdio.h is required. */
1672#include <stdlib.h>
1673#include <string.h>
1674#include <unistd.h>
1675
1676/* Used for select(2) */
1677#include <sys/types.h>
1678#include <sys/select.h>
1679
1680#include <signal.h>
1681
1682#include <errno.h>
1683#include <stdio.h>
1684
1685#include <locale.h>
1686
1687/* Standard readline include files. */
1688#include <readline/readline.h>
1689#include <readline/history.h>
1690
1691#if !defined (errno)
1692extern int errno;
1693#endif
1694
1695static void cb_linehandler (char *);
1696static void sighandler (int);
1697
1698int running;
1699int sigwinch_received;
1700const char *prompt = "rltest$ ";
1701
1702/* Handle SIGWINCH and window size changes when readline is not active and
1703 reading a character. */
1704static void
1705sighandler (int sig)
1706@{
1707 sigwinch_received = 1;
1708@}
1709
1710/* Callback function called for each line when accept-line executed, EOF
1711 seen, or EOF character read. This sets a flag and returns; it could
1712 also call exit(3). */
1713static void
1714cb_linehandler (char *line)
1715@{
1716 /* Can use ^D (stty eof) or `exit' to exit. */
1717 if (line == NULL || strcmp (line, "exit") == 0)
1718 @{
1719 if (line == 0)
1720 printf ("\n");
1721 printf ("exit\n");
1722 /* This function needs to be called to reset the terminal settings,
1723 and calling it from the line handler keeps one extra prompt from
1724 being displayed. */
1725 rl_callback_handler_remove ();
1726
1727 running = 0;
1728 @}
1729 else
1730 @{
1731 if (*line)
1732 add_history (line);
1733 printf ("input line: %s\n", line);
1734 free (line);
1735 @}
1736@}
1737
1738int
1739main (int c, char **v)
1740@{
1741 fd_set fds;
1742 int r;
1743
1744 /* Set the default locale values according to environment variables. */
1745 setlocale (LC_ALL, "");
1746
1747 /* Handle window size changes when readline is not active and reading
1748 characters. */
1749 signal (SIGWINCH, sighandler);
1750
1751 /* Install the line handler. */
1752 rl_callback_handler_install (prompt, cb_linehandler);
1753
1754 /* Enter a simple event loop. This waits until something is available
1755 to read on readline's input stream (defaults to standard input) and
1756 calls the builtin character read callback to read it. It does not
1757 have to modify the user's terminal settings. */
1758 running = 1;
1759 while (running)
1760 @{
1761 FD_ZERO (&fds);
1762 FD_SET (fileno (rl_instream), &fds);
1763
1764 r = select (FD_SETSIZE, &fds, NULL, NULL, NULL);
1765 if (r < 0 && errno != EINTR)
1766 @{
1767 perror ("rltest: select");
1768 rl_callback_handler_remove ();
1769 break;
1770 @}
1771 if (sigwinch_received)
1772 @{
1773 rl_resize_terminal ();
1774 sigwinch_received = 0;
1775 @}
1776 if (r < 0)
1777 continue;
1778
1779 if (FD_ISSET (fileno (rl_instream), &fds))
1780 rl_callback_read_char ();
1781 @}
1782
1783 printf ("rltest: Event loop has exited\n");
1784 return 0;
1785@}
1786@end example
1787
1788@node Readline Signal Handling
1789@section Readline Signal Handling
1790
1791Signals are asynchronous events sent to a process by the Unix kernel,
1792sometimes on behalf of another process.
1793They are intended to indicate exceptional events,
1794like a user pressing the terminal's interrupt key,
1795or a network connection being broken.
1796There is a class of signals that can
1797be sent to the process currently reading input from the keyboard.
1798Since Readline changes the terminal attributes when it is called, it needs
1799to perform special processing when such a signal is received in order to
1800restore the terminal to a sane state, or provide applications using
1801Readline with functions to do so manually.
1802
1803Readline contains an internal signal handler that is installed for a
1804number of signals (@code{SIGINT}, @code{SIGQUIT}, @code{SIGTERM},
1805@code{SIGHUP},
1806@code{SIGALRM}, @code{SIGTSTP}, @code{SIGTTIN}, and @code{SIGTTOU}).
1807When Readline receives one of these signals, the signal handler
1808will reset the terminal attributes to those that were in effect before
1809@code{readline()} was called, reset the signal handling to what it was
1810before @code{readline()} was called, and resend the signal to the calling
1811application.
1812If and when the calling application's signal handler returns, Readline
1813will reinitialize the terminal and continue to accept input.
1814When a @code{SIGINT} is received, the Readline signal handler performs
1815some additional work, which will cause any partially-entered line to be
1816aborted (see the description of @code{rl_free_line_state()} below).
1817
1818There is an additional Readline signal handler, for @code{SIGWINCH}, which
1819the kernel sends to a process whenever the terminal's size changes (for
1820example, if a user resizes an @code{xterm}).
1821The Readline @code{SIGWINCH} handler updates
1822Readline's internal screen size information, and then calls any
1823@code{SIGWINCH} signal handler the calling application has installed.
1824Readline calls the application's @code{SIGWINCH} signal handler without
1825resetting the terminal to its original state.
1826If the application's signal
1827handler does more than update its idea of the terminal size and return
1828(for example, a @code{longjmp} back to a main processing loop),
1829it @emph{must} call @code{rl_cleanup_after_signal()} (described below),
1830to restore the terminal state.
1831
1832When an application is using the callback interface
1833(@pxref{Alternate Interface}), Readline installs signal handlers only for
1834the duration of the call to @code{rl_callback_read_char}.
1835Applications using the callback interface should be prepared
1836to clean up Readline's state if they wish to handle the signal
1837before the line handler completes and restores the terminal state.
1838
1839If an application using the callback interface wishes to have Readline
1840install its signal handlers at the time the application calls
1841@code{rl_callback_handler_install} and remove them only when a complete
1842line of input has been read, it should set the
1843@code{rl_persistent_signal_handlers} variable to a non-zero value.
1844This allows an application to defer all of the handling of the signals
1845Readline catches to Readline.
1846Applications should use this variable with care; it can result in Readline
1847catching signals and not acting on them (or allowing the application to react
1848to them) until the application calls @code{rl_callback_read_char}.
1849This can result in an application becoming less responsive to keyboard
1850signals like SIGINT.
1851If an application does not want or need to perform any signal handling, or
1852does not need to do any processing
1853between calls to @code{rl_callback_read_char},
1854setting this variable may be appropriate.
1855
1856Readline provides two variables that allow application writers to
1857control whether or not it will catch certain signals and act on them
1858when they are received.
1859It is important that applications change the
1860values of these variables only when calling @code{readline()},
1861not in a signal handler, so Readline's internal signal state
1862is not corrupted.
1863
1864@deftypevar int rl_catch_signals
1865If this variable is non-zero, Readline will install signal handlers for
1866@code{SIGINT}, @code{SIGQUIT}, @code{SIGTERM}, @code{SIGHUP}, @code{SIGALRM},
1867@code{SIGTSTP}, @code{SIGTTIN}, and @code{SIGTTOU}.
1868
1869The default value of @code{rl_catch_signals} is 1.
1870@end deftypevar
1871
1872@deftypevar int rl_catch_sigwinch
1873If this variable is set to a non-zero value,
1874Readline will install a signal handler for @code{SIGWINCH}.
1875
1876The default value of @code{rl_catch_sigwinch} is 1.
1877@end deftypevar
1878
1879@deftypevar int rl_persistent_signal_handlers
1880If an application using the callback interface wishes Readline's signal
1881handlers to be installed and active during the set of calls to
1882@code{rl_callback_read_char} that constitutes an entire single line,
1883it should set this variable to a non-zero value.
1884
1885The default value of @code{rl_persistent_signal_handlers} is 0.
1886@end deftypevar
1887
1888@deftypevar int rl_change_environment
1889If this variable is set to a non-zero value,
1890and Readline is handling @code{SIGWINCH}, Readline will modify the
1891@var{LINES} and @var{COLUMNS} environment variables upon receipt of a
1892@code{SIGWINCH}.
1893
1894The default value of @code{rl_change_environment} is 1.
1895@end deftypevar
1896
1897If an application does not wish to have Readline catch any signals, or
1898to handle signals other than those Readline catches (@code{SIGHUP},
1899for example),
1900Readline provides convenience functions to do the necessary terminal
1901and internal state cleanup upon receipt of a signal.
1902
1903@deftypefun int rl_pending_signal (void)
1904Return the signal number of the most recent signal Readline received but
1905has not yet handled, or 0 if there is no pending signal.
1906@end deftypefun
1907
1908@deftypefun void rl_cleanup_after_signal (void)
1909This function will reset the state of the terminal to what it was before
1910@code{readline()} was called, and remove the Readline signal handlers for
1911all signals, depending on the values of @code{rl_catch_signals} and
1912@code{rl_catch_sigwinch}.
1913@end deftypefun
1914
1915@deftypefun void rl_free_line_state (void)
1916This will free any partial state associated with the current input line
1917(undo information, any partial history entry, any partially-entered
1918keyboard macro, and any partially-entered numeric argument).
1919This should be called before @code{rl_cleanup_after_signal()}.
1920The Readline signal handler for @code{SIGINT} calls this to abort
1921the current input line.
1922@end deftypefun
1923
1924@deftypefun void rl_reset_after_signal (void)
1925This will reinitialize the terminal and reinstall any Readline signal
1926handlers, depending on the values of @code{rl_catch_signals} and
1927@code{rl_catch_sigwinch}.
1928@end deftypefun
1929
1930If an application wants to force Readline to handle any signals that
1931have arrived while it has been executing, @code{rl_check_signals()}
1932will call Readline's internal signal handler if there are any pending
1933signals.
1934This is primarily intended for those applications that use
1935a custom @code{rl_getc_function} (@pxref{Readline Variables}) and wish
1936to handle signals received while waiting for input.
1937
1938@deftypefun void rl_check_signals (void)
1939If there are any pending signals, call Readline's internal signal
1940handling functions to process them.
1941@code{rl_pending_signal()} can be used independently
1942to determine whether or not there are any pending signals.
1943@end deftypefun
1944
1945If an application does not wish Readline to catch @code{SIGWINCH},
1946it may call @code{rl_resize_terminal()} or @code{rl_set_screen_size()}
1947to force Readline to update its idea of the terminal size when it receives
1948a @code{SIGWINCH}.
1949
1950@deftypefun void rl_echo_signal_char (int sig)
1951If an application wishes to install its own signal handlers, but still
1952have Readline display characters that generate signals, calling this
1953function with @var{sig} set to @code{SIGINT}, @code{SIGQUIT}, or
1954@code{SIGTSTP} will display the character generating that signal.
1955@end deftypefun
1956
1957@deftypefun void rl_resize_terminal (void)
1958Update Readline's internal screen size by reading values from the kernel.
1959@end deftypefun
1960
1961@deftypefun void rl_set_screen_size (int rows, int cols)
1962Set Readline's idea of the terminal size to @var{rows} rows and
1963@var{cols} columns.
1964If either @var{rows} or @var{columns} is less than or equal to 0,
1965Readline doesn't change that terminal dimension.
1966This is intended to tell Readline the physical dimensions of the terminal,
1967and is used internally to calculate the maximum number of characters that
1968may appear on a single line and on the screen.
1969@end deftypefun
1970
1971If an application does not want to install a @code{SIGWINCH} handler, but
1972is still interested in the screen dimensions, it may query Readline's idea
1973of the screen size.
1974
1975@deftypefun void rl_get_screen_size (int *rows, int *cols)
1976Return Readline's idea of the terminal's size in the
1977variables pointed to by the arguments.
1978@end deftypefun
1979
1980@deftypefun void rl_reset_screen_size (void)
1981Cause Readline to reobtain the screen size and recalculate its dimensions.
1982@end deftypefun
1983
1984The following functions install and remove Readline's signal handlers.
1985
1986@deftypefun int rl_set_signals (void)
1987Install Readline's signal handler for @code{SIGINT}, @code{SIGQUIT},
1988@code{SIGTERM}, @code{SIGHUP}, @code{SIGALRM}, @code{SIGTSTP}, @code{SIGTTIN},
1989@code{SIGTTOU}, and @code{SIGWINCH}, depending on the values of
1990@code{rl_catch_signals} and @code{rl_catch_sigwinch}.
1991@end deftypefun
1992
1993@deftypefun int rl_clear_signals (void)
1994Remove all of the Readline signal handlers installed by
1995@code{rl_set_signals()}.
1996@end deftypefun
1997
1998@node Custom Completers
1999@section Custom Completers
2000@cindex application-specific completion functions
2001
2002Typically, a program that reads commands from the user has a way of
2003disambiguating commands and data.
2004If your program is one of these, then
2005it can provide completion for commands, data, or both.
2006The following sections describe how your program and Readline
2007cooperate to provide this service.
2008
2009@menu
2010* How Completing Works:: The logic used to do completion.
2011* Completion Functions:: Functions provided by Readline.
2012* Completion Variables:: Variables which control completion.
2013* A Short Completion Example:: An example of writing completer subroutines.
2014@end menu
2015
2016@node How Completing Works
2017@subsection How Completing Works
2018
2019In order to complete some text, the full list of possible completions
2020must be available.
2021That is, it is not possible to accurately
2022expand a partial word without knowing all of the possible words
2023which make sense in that context.
2024The Readline library provides
2025the user interface to completion, and two of the most common
2026completion functions: filename and username.
2027For completing other types
2028of text, you must write your own completion function.
2029This section
2030describes exactly what such functions must do, and provides an example.
2031
2032There are three major functions used to perform completion:
2033
2034@enumerate
2035@item
2036The user-interface function @code{rl_complete()}.
2037This function is called with the same arguments as other bindable
2038Readline functions: @var{count} and @var{invoking_key}.
2039It isolates the word to be completed and calls
2040@code{rl_completion_matches()} to generate a list of possible completions.
2041It then either lists the possible completions, inserts the possible
2042completions, or actually performs the
2043completion, depending on which behavior is desired.
2044
2045@item
2046The internal function @code{rl_completion_matches()} uses an
2047application-supplied @dfn{generator} function to generate the list of
2048possible matches, and then returns the array of these matches.
2049The caller should place the address of its generator function in
2050@code{rl_completion_entry_function}.
2051
2052@item
2053The generator function is called repeatedly from
2054@code{rl_completion_matches()}, returning a string each time.
2055The arguments to the generator function are @var{text} and @var{state}.
2056@var{text} is the partial word to be completed.
2057@var{state} is zero the first time the function is called,
2058allowing the generator to perform any necessary initialization,
2059and a positive integer for each subsequent call.
2060The generator function returns
2061@code{(char *)NULL} to inform @code{rl_completion_matches()} that there are
2062no more possibilities left.
2063Usually the generator function computes the
2064list of possible completions when @var{state} is zero, and returns them
2065one at a time on subsequent calls.
2066Each string the generator function
2067returns as a match must be allocated with @code{malloc()}; Readline
2068frees the strings when it has finished with them.
2069Such a generator function is referred to as an
2070@dfn{application-specific completion function}.
2071
2072@end enumerate
2073
2074@deftypefun int rl_complete (int ignore, int invoking_key)
2075Complete the word at or before point.
2076You have supplied the function that does the initial simple matching
2077selection algorithm (see @code{rl_completion_matches()}).
2078The default is to do filename completion.
2079@end deftypefun
2080
2081@deftypevar {rl_compentry_func_t *} rl_completion_entry_function
2082This is a pointer to the generator function for
2083@code{rl_completion_matches()}.
2084If the value of @code{rl_completion_entry_function} is
2085@code{NULL} then Readline uses the default filename generator
2086function, @code{rl_filename_completion_function()}.
2087An @dfn{application-specific completion function} is a function whose
2088address is assigned to @code{rl_completion_entry_function} and whose
2089return values are used to generate possible completions.
2090@end deftypevar
2091
2092@node Completion Functions
2093@subsection Completion Functions
2094
2095Here is the complete list of callable completion functions present in
2096Readline.
2097
2098@deftypefun int rl_complete_internal (int what_to_do)
2099Complete the word at or before point.
2100@var{what_to_do} says what to do with the completion.
2101A value of @samp{?} means list the possible completions.
2102@samp{TAB} means do standard completion.
2103@samp{*} means insert all of the possible completions.
2104@samp{!} means to display all of the possible completions,
2105if there is more than one, as well as performing partial completion.
2106@samp{@@} is similar to @samp{!}, but does not list possible completions
2107if the possible completions share a common prefix.
2108@end deftypefun
2109
2110@deftypefun int rl_complete (int ignore, int invoking_key)
2111Complete the word at or before point.
2112You have supplied the function that does the initial simple
2113matching selection algorithm (see @code{rl_completion_matches()} and
2114@code{rl_completion_entry_function}).
2115The default is to do filename completion.
2116This calls @code{rl_complete_internal()} with an
2117argument depending on @var{invoking_key}.
2118@end deftypefun
2119
2120@deftypefun int rl_possible_completions (int count, int invoking_key)
2121List the possible completions.
2122See description of @code{rl_complete()}.
2123This calls @code{rl_complete_internal()} with an argument of @samp{?}.
2124@end deftypefun
2125
2126@deftypefun int rl_insert_completions (int count, int invoking_key)
2127Insert the list of possible completions into the line, deleting the
2128partially-completed word.
2129See description of @code{rl_complete()}.
2130This calls @code{rl_complete_internal()} with an argument of @samp{*}.
2131@end deftypefun
2132
2133@deftypefun int rl_completion_mode (rl_command_func_t *cfunc)
2134Returns the appropriate value to pass to @code{rl_complete_internal()}
2135depending on whether @var{cfunc} was called twice in succession and
2136the values of the @code{show-all-if-ambiguous} and
2137@code{show-all-if-unmodified} variables.
2138Application-specific completion functions may use this function to present
2139the same interface as @code{rl_complete()}.
2140@end deftypefun
2141
2142@deftypefun {char **} rl_completion_matches (const char *text, rl_compentry_func_t *entry_func)
2143Returns an array of strings which is a list of completions for @var{text}.
2144If there are no completions, returns @code{NULL}.
2145The first entry in the returned array is the substitution for @var{text}.
2146The remaining entries are the possible completions.
2147The array is terminated with a @code{NULL} pointer.
2148
2149@var{entry_func} is a function of two args, and returns a @code{char *}.
2150The first argument is @var{text}.
2151The second is a state argument;
2152it is zero on the first call, and non-zero on subsequent calls.
2153@var{entry_func} returns a @code{NULL} pointer to the caller
2154when there are no more matches.
2155@end deftypefun
2156
2157@deftypefun {char *} rl_filename_completion_function (const char *text, int state)
2158A generator function for filename completion in the general case.
2159@var{text} is a partial filename.
2160The Bash source is a useful reference for writing application-specific
2161completion functions (the Bash completion functions call this and other
2162Readline functions).
2163@end deftypefun
2164
2165@deftypefun {char *} rl_username_completion_function (const char *text, int state)
2166A completion generator for usernames.
2167@var{text} contains a partial username preceded by a
2168random character (usually @samp{~}).
2169As with all completion generators,
2170@var{state} is zero on the first call and non-zero for subsequent calls.
2171@end deftypefun
2172
2173@node Completion Variables
2174@subsection Completion Variables
2175
2176@deftypevar {rl_compentry_func_t *} rl_completion_entry_function
2177A pointer to the generator function for @code{rl_completion_matches()}.
2178@code{NULL} means to use @code{rl_filename_completion_function()},
2179the default filename completer.
2180@end deftypevar
2181
2182@deftypevar {rl_completion_func_t *} rl_attempted_completion_function
2183A pointer to an alternative function to create matches.
2184The function is called with @var{text}, @var{start}, and @var{end}.
2185@var{start} and @var{end} are indices in @code{rl_line_buffer} defining
2186the boundaries of @var{text}, which is a character string.
2187If this function exists and returns @code{NULL}, or if this variable is
2188set to @code{NULL}, then @code{rl_complete()} will call the value of
2189@code{rl_completion_entry_function} to generate matches, otherwise
2190completion will use the array of strings this function returns.
2191If this function sets the @code{rl_attempted_completion_over}
2192variable to a non-zero value, Readline will not perform its default
2193completion even if this function returns no matches.
2194@end deftypevar
2195
2196@deftypevar {rl_quote_func_t *} rl_filename_quoting_function
2197A pointer to a function that will quote a filename in an
2198application-specific fashion.
2199Readline calls this function during filename completion
2200if one of the characters in @code{rl_filename_quote_characters}
2201appears in a completed filename.
2202The function is called with
2203@var{text}, @var{match_type}, and @var{quote_pointer}.
2204The @var{text} is the filename to be quoted.
2205The @var{match_type} is either @code{SINGLE_MATCH},
2206if there is only one completion match, or @code{MULT_MATCH}.
2207Some functions use this to decide whether or not to
2208insert a closing quote character.
2209The @var{quote_pointer} is a pointer
2210to any opening quote character the user typed.
2211Some functions choose to reset this character if they decide to quote
2212the filename in a different style.
2213It's preferable to preserve the user's quoting as much as possible --
2214it's less disruptive.
2215@end deftypevar
2216
2217@deftypevar {rl_dequote_func_t *} rl_filename_dequoting_function
2218A pointer to a function that will remove application-specific quoting
2219characters from a filename before attempting completion,
2220so those characters do not interfere with matching the text against
2221names in the filesystem.
2222It is called with @var{text}, the text of the word
2223to be dequoted, and @var{quote_char}, which is the quoting character
2224that delimits the filename (usually @samp{'} or @samp{"}).
2225If @var{quote_char} is zero, the filename was not in a quoted string.
2226@end deftypevar
2227
2228@deftypevar {rl_linebuf_func_t *} rl_char_is_quoted_p
2229A pointer to a function to call that determines whether or not a specific
2230character in the line buffer is quoted, according to whatever quoting
2231mechanism the application uses.
2232The function is called with two arguments:
2233@var{text}, the text of the line,
2234and @var{index}, the index of the character in the line.
2235It is used to decide whether a character found in
2236@code{rl_completer_word_break_characters} should be
2237used to break words for the completer.
2238@end deftypevar
2239
2240@deftypevar {rl_compignore_func_t *} rl_ignore_some_completions_function
2241Readline calls this function, if defined, when filename
2242completion is done, after all the matching names have been generated.
2243It is passed a @code{NULL} terminated array of matches.
2244The first element (@code{matches[0]}) is the maximal substring
2245common to all matches.
2246This function can re-arrange the list of matches as required, but
2247must free each element it deletes from the array.
2248@end deftypevar
2249
2250@deftypevar {rl_icppfunc_t *} rl_directory_completion_hook
2251This function, if defined, is allowed to modify the directory portion
2252of filenames during completion.
2253It could be used to expand symbolic links or shell variables in pathnames.
2254It is called with the address of a string (the current directory name) as an
2255argument, and may modify that string.
2256If the function replaces the string with a new string, it
2257should free the old value.
2258Any modified directory name should have a trailing slash.
2259The modified value will be used as part of the completion, replacing
2260the directory portion of the pathname the user typed.
2261At the least, even if no other expansion is performed, this function should
2262remove any quote characters from the directory name, because its result will
2263be passed directly to @code{opendir()}.
2264
2265The directory completion hook returns an integer that should be non-zero if
2266the function modifies its directory argument.
2267The function should not modify the directory argument if it returns 0.
2268@end deftypevar
2269
2270@deftypevar {rl_icppfunc_t *} rl_directory_rewrite_hook;
2271If non-zero, this is the address of a function to call when completing
2272a directory name.
2273This function takes the address of the directory name
2274to be modified as an argument.
2275Unlike @code{rl_directory_completion_hook},
2276it only modifies the directory name used in @code{opendir()},
2277not what Readline displays when it prints or inserts
2278the possible completions.
2279Readline calls this before rl_directory_completion_hook.
2280At the least, even if no other expansion is performed, this function should
2281remove any quote characters from the directory name, because its result will
2282be passed directly to @code{opendir()}.
2283
2284The directory rewrite hook returns an integer that should be non-zero if
2285the function modifies its directory argument.
2286The function should not modify the directory argument if it returns 0.
2287@end deftypevar
2288
2289@deftypevar {rl_icppfunc_t *} rl_filename_stat_hook
2290If non-zero, this is the address of a function for the completer to
2291call before deciding which character to append to a completed name.
2292This function modifies its filename name argument, and Readline passes
2293the modified value to @code{stat()}
2294to determine the file's type and characteristics.
2295This function does not need to remove quote characters from the filename.
2296
2297The stat hook returns an integer that should be non-zero if
2298the function modifies its directory argument.
2299The function should not modify the directory argument if it returns 0.
2300@end deftypevar
2301
2302@deftypevar {rl_dequote_func_t *} rl_filename_rewrite_hook
2303If non-zero, this is the address of a function
2304for Readline to call when reading
2305directory entries from the filesystem for completion and comparing
2306them to the filename portion of the partial word being completed.
2307It modifies the filesystem entries,
2308as opposed to @code{rl_completion_rewrite_hook},
2309which modifies the word being completed.
2310The function takes two arguments:
2311@var{fname}, the filename to be converted,
2312and @var{fnlen}, its length in bytes.
2313It must either return its first argument (if no conversion takes place)
2314or the converted filename in newly-allocated memory.
2315The function should perform any necessary application or system-specific
2316conversion on the filename, such as converting between character sets
2317or converting from a filesystem format to a character input format.
2318Readline compares the converted form against the word to be completed,
2319and, if it matches, adds it to the list of matches.
2320Readline will free the allocated string.
2321@end deftypevar
2322
2323@deftypevar {rl_dequote_func_t *} rl_completion_rewrite_hook
2324If non-zero, this is the address of a function
2325for Readline to call before
2326comparing the filename portion of a word to be completed with directory
2327entries from the filesystem.
2328It modifies the word being completed,
2329as opposed to @code{rl_filename_rewrite_hook},
2330which modifies filesystem entries.
2331The function takes two arguments:
2332@var{fname}, the word to be converted,
2333after any @code{rl_filename_dequoting_function} has been applied,
2334and @var{fnlen}, its length in bytes.
2335It must either return its first argument (if no conversion takes place)
2336or the converted filename in newly-allocated memory.
2337The function should perform any necessary application or system-specific
2338conversion on the filename, such as converting between character sets or
2339converting from a character input format to some other format.
2340Readline compares the converted form against directory entries, after
2341their potential modification by @code{rl_filename_rewrite_hook},
2342and adds any matches to the list of matches.
2343Readline will free the allocated string.
2344@end deftypevar
2345
2346@deftypevar {rl_compdisp_func_t *} rl_completion_display_matches_hook
2347If non-zero, then this is the address of a function to call when
2348completing a word would normally display the list of possible matches.
2349Readline calls this function instead of displaying the list itself.
2350It takes three arguments:
2351(@code{char **}@var{matches}, @code{int} @var{num_matches}, @code{int} @var{max_length})
2352where @var{matches} is the array of matching strings,
2353@var{num_matches} is the number of strings in that array, and
2354@var{max_length} is the length of the longest string in that array.
2355Readline provides a convenience function, @code{rl_display_match_list},
2356that takes care of doing the display to Readline's output stream.
2357You may call that function from this hook.
2358@end deftypevar
2359
2360@deftypevar {const char *} rl_basic_word_break_characters
2361The basic list of characters that signal a break between words for the
2362completer routine.
2363The default value of this variable is the characters
2364which break words for completion in Bash:
2365@code{" \t\n\"\\'`@@$><=;|&@{("}.
2366@end deftypevar
2367
2368@deftypevar {const char *} rl_basic_quote_characters
2369A list of quote characters which can cause a word break.
2370The default value includes single and double quotes.
2371@end deftypevar
2372
2373@deftypevar {const char *} rl_completer_word_break_characters
2374The list of characters that signal a break between words for
2375@code{rl_complete_internal()}.
2376These characters determine how Readline decides what to complete.
2377The default list is the value of
2378@code{rl_basic_word_break_characters}.
2379@end deftypevar
2380
2381@deftypevar {rl_cpvfunc_t *} rl_completion_word_break_hook
2382If non-zero, this is the address of a function to call when Readline is
2383deciding where to separate words for word completion.
2384It should return a character string like
2385@code{rl_completer_word_break_characters} to be
2386used to perform the current completion.
2387The function may choose to set
2388@code{rl_completer_word_break_characters} itself.
2389If the function returns @code{NULL}, Readline uses
2390@code{rl_completer_word_break_characters}.
2391@end deftypevar
2392
2393@deftypevar {const char *} rl_completer_quote_characters
2394A list of characters which can be used to quote a substring of the line.
2395Completion occurs on the entire substring, and within the substring,
2396@code{rl_completer_word_break_characters} are treated as any other character,
2397unless they also appear within this list.
2398@end deftypevar
2399
2400@deftypevar {const char *} rl_filename_quote_characters
2401A list of characters that cause Readline to quote a filename
2402when they appear in a completed filename.
2403The default is the null string.
2404@end deftypevar
2405
2406@deftypevar {const char *} rl_special_prefixes
2407The list of characters that are word break characters, but should be
2408left in @var{text} when it is passed to the completion function.
2409Programs can use this to help determine what kind of completing to do.
2410For instance, Bash sets this variable to "$@@" so that it can complete
2411shell variables and hostnames.
2412@end deftypevar
2413
2414@deftypevar int rl_completion_query_items
2415This determines the maximum number of items
2416that possible-completions will display unconditionally.
2417If there are more possible completions than this,
2418Readline asks the user for confirmation before displaying them.
2419The default value is 100.
2420A negative value
2421indicates that Readline should never ask for confirmation.
2422@end deftypevar
2423
2424@deftypevar {int} rl_completion_append_character
2425When a single completion alternative matches at the end of the command
2426line, Readline appends this character to the inserted completion text.
2427The default is a space character (@samp{ }).
2428Setting this to the null
2429character (@samp{\0}) prevents anything being appended automatically.
2430This can be changed in application-specific completion functions to
2431provide the ``most sensible word separator character'' according to
2432an application-specific command line syntax specification.
2433It is set to the default before calling any application-specific completion
2434function, and may only be changed within such a function.
2435@end deftypevar
2436
2437@deftypevar int rl_completion_suppress_append
2438If non-zero, Readline will not append the
2439@var{rl_completion_append_character} to
2440matches at the end of the command line, as described above.
2441It is set to 0 before calling any application-specific completion function,
2442and may only be changed within such a function.
2443@end deftypevar
2444
2445@deftypevar int rl_completion_suppress_quote
2446If non-zero, Readline does not append a matching quote character when
2447performing completion on a quoted string.
2448It is set to 0 before calling any application-specific completion function,
2449and may only be changed within such a function.
2450@end deftypevar
2451
2452@deftypevar int rl_completion_found_quote
2453When Readline is completing quoted text, it sets this variable
2454to a non-zero value if the word being completed contains or is delimited
2455by any quoting characters, including backslashes.
2456This is set before calling any application-specific completion function.
2457@end deftypevar
2458
2459@deftypevar int rl_completion_quote_character
2460When Readline is completing quoted text, as delimited by one of the
2461characters in @var{rl_completer_quote_characters}, it sets this variable
2462to the quoting character it found.
2463This is set before calling any application-specific completion function.
2464@end deftypevar
2465
2466@deftypevar int rl_completion_mark_symlink_dirs
2467If non-zero, Readline appends a slash to completed filenames that are
2468symbolic links to directory names, subject to the value of the
2469user-settable @var{mark-directories} variable.
2470This variable exists so that application-specific completion functions
2471can override the user's global preference (set via the
2472@var{mark-symlinked-directories} Readline variable) if appropriate.
2473This variable is set to the user's preference before calling any
2474application-specific completion function,
2475so unless that function modifies the value,
2476Readline will honor the user's preferences.
2477@end deftypevar
2478
2479@deftypevar int rl_ignore_completion_duplicates
2480If non-zero, then Readline removes duplicates in the set of possible
2481completions.
2482The default is 1.
2483@end deftypevar
2484
2485@deftypevar int rl_filename_completion_desired
2486A non-zero value means that Readline should treat the results of the
2487matches as filenames.
2488This is @emph{always} zero when completion is attempted,
2489and can only be changed
2490within an application-specific completion function.
2491If it is set to a
2492non-zero value by such a function, Readline
2493appends a slash to directory names
2494and attempts to quote completed filenames if they contain any
2495characters in @code{rl_filename_quote_characters} and
2496@code{rl_filename_quoting_desired} is set to a non-zero value.
2497@end deftypevar
2498
2499@deftypevar int rl_filename_quoting_desired
2500A non-zero value means that Readline should quote the results of the
2501matches using double quotes (or an application-specific quoting mechanism)
2502if the completed filename contains any characters in
2503@code{rl_filename_quote_chars}.
2504This is @emph{always} non-zero when completion is attempted,
2505and can only be changed within an
2506application-specific completion function.
2507The quoting is performed via a call to the function pointed to
2508by @code{rl_filename_quoting_function}.
2509@end deftypevar
2510
2511@deftypevar int rl_full_quoting_desired
2512A non-zero value means that Readline should apply filename-style quoting,
2513including any application-specified quoting mechanism,
2514to all completion matches even if it is not otherwise treating the
2515matches as filenames.
2516This is @emph{always} zero when completion is attempted,
2517and can only be changed within an
2518application-specific completion function.
2519The quoting is performed via a call to the function pointed to
2520by @code{rl_filename_quoting_function}.
2521@end deftypevar
2522
2523@deftypevar int rl_attempted_completion_over
2524If an application-specific completion function assigned to
2525@code{rl_attempted_completion_function} sets this variable to a non-zero
2526value, Readline will not perform its default filename completion even
2527if the application's completion function returns no matches.
2528It should be set only by an application's completion function.
2529@end deftypevar
2530
2531@deftypevar int rl_sort_completion_matches
2532If an application sets this variable to 0, Readline will not sort the
2533list of completions (which implies that it cannot remove any duplicate
2534completions).
2535The default value is 1, which means that Readline will
2536sort the completions and, depending on the value of
2537@code{rl_ignore_completion_duplicates}, will attempt to remove
2538duplicate matches.
2539@end deftypevar
2540
2541@deftypevar int rl_completion_type
2542Set to a character describing the type of completion Readline is currently
2543attempting; see the description of @code{rl_complete_internal()}
2544(@pxref{Completion Functions}) for the list of characters.
2545This is set to the appropriate value before calling
2546any application-specific completion function,
2547so these functions can present
2548the same interface as @code{rl_complete()}.
2549@end deftypevar
2550
2551@deftypevar int rl_completion_invoking_key
2552Set to the final character in the key sequence that invoked one of the
2553completion functions that call @code{rl_complete_internal()}.
2554This is set to the appropriate value before calling
2555any application-specific completion function.
2556@end deftypevar
2557
2558@deftypevar int rl_inhibit_completion
2559If this variable is non-zero, Readline does not perform completion,
2560even if a key binding indicates it should.
2561The completion character
2562is inserted as if it were bound to @code{self-insert}.
2563@end deftypevar
2564
2565@node A Short Completion Example
2566@subsection A Short Completion Example
2567
2568Here is a small application demonstrating the use of the GNU Readline
2569library.
2570It is called @code{fileman}, and the source code resides in
2571@file{examples/fileman.c}.
2572This sample application provides
2573command name completion, line editing features,
2574and access to the history list.
2575
2576@page
2577@smallexample
2578/* fileman.c -- A tiny application which demonstrates how to use the
2579 GNU Readline library. This application interactively allows users
2580 to manipulate files and their modes. */
2581
2582#ifdef HAVE_CONFIG_H
2583# include <config.h>
2584#endif
2585
2586#include <sys/types.h>
2587#ifdef HAVE_SYS_FILE_H
2588# include <sys/file.h>
2589#endif
2590#include <sys/stat.h>
2591
2592#ifdef HAVE_UNISTD_H
2593# include <unistd.h>
2594#endif
2595
2596#include <fcntl.h>
2597#include <stdio.h>
2598#include <errno.h>
2599#include <locale.h>
2600
2601#if defined (HAVE_STRING_H)
2602# include <string.h>
2603#else /* !HAVE_STRING_H */
2604# include <strings.h>
2605#endif /* !HAVE_STRING_H */
2606
2607#ifdef HAVE_STDLIB_H
2608# include <stdlib.h>
2609#endif
2610
2611#include <time.h>
2612
2613#include <readline/readline.h>
2614#include <readline/history.h>
2615
2616extern char *xmalloc PARAMS((size_t));
2617
2618/* The names of functions that actually do the manipulation. */
2619int com_list PARAMS((char *));
2620int com_view PARAMS((char *));
2621int com_rename PARAMS((char *));
2622int com_stat PARAMS((char *));
2623int com_pwd PARAMS((char *));
2624int com_delete PARAMS((char *));
2625int com_help PARAMS((char *));
2626int com_cd PARAMS((char *));
2627int com_quit PARAMS((char *));
2628
2629/* A structure which contains information on the commands this program
2630 can understand. */
2631
2632typedef struct @{
2633 char *name; /* User printable name of the function. */
2634 rl_icpfunc_t *func; /* Function to call to do the job. */
2635 char *doc; /* Documentation for this function. */
2636@} COMMAND;
2637
2638COMMAND commands[] = @{
2639 @{ "cd", com_cd, "Change to directory DIR" @},
2640 @{ "delete", com_delete, "Delete FILE" @},
2641 @{ "help", com_help, "Display this text" @},
2642 @{ "?", com_help, "Synonym for `help'" @},
2643 @{ "list", com_list, "List files in DIR" @},
2644 @{ "ls", com_list, "Synonym for `list'" @},
2645 @{ "pwd", com_pwd, "Print the current working directory" @},
2646 @{ "quit", com_quit, "Quit using Fileman" @},
2647 @{ "rename", com_rename, "Rename FILE to NEWNAME" @},
2648 @{ "stat", com_stat, "Print out statistics on FILE" @},
2649 @{ "view", com_view, "View the contents of FILE" @},
2650 @{ (char *)NULL, (rl_icpfunc_t *)NULL, (char *)NULL @}
2651@};
2652
2653/* Forward declarations. */
2654char *stripwhite (char *);
2655COMMAND *find_command (char *);
2656
2657/* The name of this program, as taken from argv[0]. */
2658char *progname;
2659
2660/* When non-zero, this global means the user is done using this program. */
2661int done;
2662
2663char *
2664dupstr (char *s)
2665@{
2666 char *r;
2667
2668 r = xmalloc (strlen (s) + 1);
2669 strcpy (r, s);
2670 return (r);
2671@}
2672
2673int
2674main (int argc, char **argv)
2675@{
2676 char *line, *s;
2677
2678 setlocale (LC_ALL, "");
2679
2680 progname = argv[0];
2681
2682 initialize_readline (); /* Bind our completer. */
2683
2684 /* Loop reading and executing lines until the user quits. */
2685 for ( ; done == 0; )
2686 @{
2687 line = readline ("FileMan: ");
2688
2689 if (!line)
2690 break;
2691
2692 /* Remove leading and trailing whitespace from the line.
2693 Then, if there is anything left, add it to the history list
2694 and execute it. */
2695 s = stripwhite (line);
2696
2697 if (*s)
2698 @{
2699 add_history (s);
2700 execute_line (s);
2701 @}
2702
2703 free (line);
2704 @}
2705 exit (0);
2706@}
2707
2708/* Execute a command line. */
2709int
2710execute_line (char *line)
2711@{
2712 register int i;
2713 COMMAND *command;
2714 char *word;
2715
2716 /* Isolate the command word. */
2717 i = 0;
2718 while (line[i] && whitespace (line[i]))
2719 i++;
2720 word = line + i;
2721
2722 while (line[i] && !whitespace (line[i]))
2723 i++;
2724
2725 if (line[i])
2726 line[i++] = '\0';
2727
2728 command = find_command (word);
2729
2730 if (!command)
2731 @{
2732 fprintf (stderr, "%s: No such command for FileMan.\n", word);
2733 return (-1);
2734 @}
2735
2736 /* Get argument to command, if any. */
2737 while (whitespace (line[i]))
2738 i++;
2739
2740 word = line + i;
2741
2742 /* Call the function. */
2743 return ((*(command->func)) (word));
2744@}
2745
2746/* Look up NAME as the name of a command, and return a pointer to that
2747 command. Return a NULL pointer if NAME isn't a command name. */
2748COMMAND *
2749find_command (char *name)
2750@{
2751 register int i;
2752
2753 for (i = 0; commands[i].name; i++)
2754 if (strcmp (name, commands[i].name) == 0)
2755 return (&commands[i]);
2756
2757 return ((COMMAND *)NULL);
2758@}
2759
2760/* Strip whitespace from the start and end of STRING. Return a pointer
2761 into STRING. */
2762char *
2763stripwhite (char *string)
2764@{
2765 register char *s, *t;
2766
2767 for (s = string; whitespace (*s); s++)
2768 ;
2769
2770 if (*s == 0)
2771 return (s);
2772
2773 t = s + strlen (s) - 1;
2774 while (t > s && whitespace (*t))
2775 t--;
2776 *++t = '\0';
2777
2778 return s;
2779@}
2780
2781/* **************************************************************** */
2782/* */
2783/* Interface to Readline Completion */
2784/* */
2785/* **************************************************************** */
2786
2787char *command_generator (const char *, int);
2788char **fileman_completion (const char *, int, int);
2789
2790/* Tell the GNU Readline library how to complete. We want to try to complete
2791 on command names if this is the first word in the line, or on filenames
2792 if not. */
2793void
2794initialize_readline (void)
2795@{
2796 /* Allow conditional parsing of the ~/.inputrc file. */
2797 rl_readline_name = "FileMan";
2798
2799 /* Tell the completer that we want a crack first. */
2800 rl_attempted_completion_function = fileman_completion;
2801@}
2802
2803/* Attempt to complete on the contents of TEXT. START and END bound the
2804 region of rl_line_buffer that contains the word to complete. TEXT is
2805 the word to complete. We can use the entire contents of rl_line_buffer
2806 in case we want to do some simple parsing. Return the array of matches,
2807 or NULL if there aren't any. */
2808char **
2809fileman_completion (const char *text, int start, int end)
2810@{
2811 char **matches;
2812
2813 matches = (char **)NULL;
2814
2815 /* If this word is at the start of the line, then it is a command
2816 to complete. Otherwise it is the name of a file in the current
2817 directory. */
2818 if (start == 0)
2819 matches = rl_completion_matches (text, command_generator);
2820
2821 return (matches);
2822@}
2823
2824/* Generator function for command completion. STATE lets us know whether
2825 to start from scratch; without any state (i.e. STATE == 0), then we
2826 start at the top of the list. */
2827char *
2828command_generator (const char *text, int state)
2829@{
2830 static int list_index, len;
2831 char *name;
2832
2833 /* If this is a new word to complete, initialize now. This includes
2834 saving the length of TEXT for efficiency, and initializing the index
2835 variable to 0. */
2836 if (!state)
2837 @{
2838 list_index = 0;
2839 len = strlen (text);
2840 @}
2841
2842 /* Return the next name which partially matches from the command list. */
2843 while (name = commands[list_index].name)
2844 @{
2845 list_index++;
2846
2847 if (strncmp (name, text, len) == 0)
2848 return (dupstr(name));
2849 @}
2850
2851 /* If no names matched, then return NULL. */
2852 return ((char *)NULL);
2853@}
2854
2855/* **************************************************************** */
2856/* */
2857/* FileMan Commands */
2858/* */
2859/* **************************************************************** */
2860
2861/* String to pass to system (). This is for the LIST, VIEW and RENAME
2862 commands. */
2863static char syscom[1024];
2864
2865/* List the file(s) named in arg. */
2866int
2867com_list (char *arg)
2868@{
2869 if (!arg)
2870 arg = "";
2871
2872 snprintf (syscom, sizeof (syscom), "ls -FClg %s", arg);
2873 return (system (syscom));
2874@}
2875
2876int
2877com_view (char *arg)
2878@{
2879 if (!valid_argument ("view", arg))
2880 return 1;
2881
2882#if defined (__MSDOS__)
2883 /* more.com doesn't grok slashes in pathnames */
2884 snprintf (syscom, sizeof (syscom), "less %s", arg);
2885#else
2886 snprintf (syscom, sizeof (syscom), "more %s", arg);
2887#endif
2888 return (system (syscom));
2889@}
2890
2891int
2892com_rename (char *arg)
2893@{
2894 too_dangerous ("rename");
2895 return (1);
2896@}
2897
2898int
2899com_stat (char *arg)
2900@{
2901 struct stat finfo;
2902
2903 if (!valid_argument ("stat", arg))
2904 return (1);
2905
2906 if (stat (arg, &finfo) == -1)
2907 @{
2908 perror (arg);
2909 return (1);
2910 @}
2911
2912 printf ("Statistics for `%s':\n", arg);
2913
2914 printf ("%s has %d link%s, and is %d byte%s in length.\n",
2915 arg,
2916 finfo.st_nlink,
2917 (finfo.st_nlink == 1) ? "" : "s",
2918 finfo.st_size,
2919 (finfo.st_size == 1) ? "" : "s");
2920 printf ("Inode Last Change at: %s", ctime (&finfo.st_ctime));
2921 printf (" Last access at: %s", ctime (&finfo.st_atime));
2922 printf (" Last modified at: %s", ctime (&finfo.st_mtime));
2923 return (0);
2924@}
2925
2926int
2927com_delete (char *arg)
2928@{
2929 too_dangerous ("delete");
2930 return (1);
2931@}
2932
2933/* Print out help for ARG, or for all of the commands if ARG is
2934 not present. */
2935int
2936com_help (char *arg)
2937@{
2938 register int i;
2939 int printed = 0;
2940
2941 for (i = 0; commands[i].name; i++)
2942 @{
2943 if (!*arg || (strcmp (arg, commands[i].name) == 0))
2944 @{
2945 printf ("%s\t\t%s.\n", commands[i].name, commands[i].doc);
2946 printed++;
2947 @}
2948 @}
2949
2950 if (!printed)
2951 @{
2952 printf ("No commands match `%s'. Possibilities are:\n", arg);
2953
2954 for (i = 0; commands[i].name; i++)
2955 @{
2956 /* Print in six columns. */
2957 if (printed == 6)
2958 @{
2959 printed = 0;
2960 printf ("\n");
2961 @}
2962
2963 printf ("%s\t", commands[i].name);
2964 printed++;
2965 @}
2966
2967 if (printed)
2968 printf ("\n");
2969 @}
2970 return (0);
2971@}
2972
2973/* Change to the directory ARG. */
2974int
2975com_cd (char *arg)
2976@{
2977 if (chdir (arg) == -1)
2978 @{
2979 perror (arg);
2980 return 1;
2981 @}
2982
2983 com_pwd ("");
2984 return (0);
2985@}
2986
2987/* Print out the current working directory. */
2988int
2989com_pwd (char *ignore)
2990@{
2991 char dir[1024], *s;
2992
2993 s = getcwd (dir, sizeof(dir) - 1);
2994 if (s == 0)
2995 @{
2996 printf ("Error getting pwd: %s\n", dir);
2997 return 1;
2998 @}
2999
3000 printf ("Current directory is %s\n", dir);
3001 return 0;
3002@}
3003
3004/* The user wishes to quit using this program. Just set DONE non-zero. */
3005int
3006com_quit (char *arg)
3007@{
3008 done = 1;
3009 return (0);
3010@}
3011
3012/* Function which tells you that you can't do this. */
3013void
3014too_dangerous (char *caller)
3015@{
3016 fprintf (stderr,
3017 "%s: Too dangerous for me to distribute. Write it yourself.\n",
3018 caller);
3019@}
3020
3021/* Return non-zero if ARG is a valid argument for CALLER, else print
3022 an error message and return zero. */
3023int
3024valid_argument (char *caller, char *arg)
3025@{
3026 if (!arg || !*arg)
3027 @{
3028 fprintf (stderr, "%s: Argument required.\n", caller);
3029 return (0);
3030 @}
3031
3032 return (1);
3033@}
3034@end smallexample