]> git.ipfire.org Git - thirdparty/bash.git/blame - lib/readline/doc/rltech.texi
commit bash-20040121 snapshot
[thirdparty/bash.git] / lib / readline / doc / rltech.texi
CommitLineData
d3a24ed2
CR
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@setchapternewpage odd
5
6@ifinfo
7This document describes the GNU Readline Library, a utility for aiding
8in the consitency of user interface across discrete programs that need
9to provide a command line interface.
10
11Copyright (C) 1988-2002 Free Software Foundation, Inc.
12
13Permission is granted to make and distribute verbatim copies of
14this manual provided the copyright notice and this permission notice
15pare preserved on all copies.
16
17@ignore
18Permission is granted to process this file through TeX and print the
19results, provided the printed document carries copying permission
20notice identical to this one except for the removal of this paragraph
21(this paragraph not being relevant to the printed manual).
22@end ignore
23
24Permission is granted to copy and distribute modified versions of this
25manual under the conditions for verbatim copying, provided that the entire
26resulting derived work is distributed under the terms of a permission
27notice identical to this one.
28
29Permission is granted to copy and distribute translations of this manual
30into another language, under the above conditions for modified versions,
31except that this permission notice may be stated in a translation approved
32by the Foundation.
33@end ifinfo
34
35@node Programming with GNU Readline
36@chapter Programming with GNU Readline
37
38This chapter describes the interface between the @sc{gnu} Readline Library and
39other programs. If you are a programmer, and you wish to include the
40features found in @sc{gnu} Readline
41such as completion, line editing, and interactive history manipulation
42in your own programs, this section is for you.
43
44@menu
45* Basic Behavior:: Using the default behavior of Readline.
46* Custom Functions:: Adding your own functions to Readline.
47* Readline Variables:: Variables accessible to custom
48 functions.
49* Readline Convenience Functions:: Functions which Readline supplies to
50 aid in writing your own custom
51 functions.
52* Readline Signal Handling:: How Readline behaves when it receives signals.
53* Custom Completers:: Supplanting or supplementing Readline's
54 completion functions.
55@end menu
56
57@node Basic Behavior
58@section Basic Behavior
59
60Many programs provide a command line interface, such as @code{mail},
61@code{ftp}, and @code{sh}. For such programs, the default behaviour of
62Readline is sufficient. This section describes how to use Readline in
63the simplest way possible, perhaps to replace calls in your code to
64@code{gets()} or @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.
71If @var{prompt} is @code{NULL} or the empty string, no prompt is displayed.
72The line @code{readline} returns is allocated with @code{malloc()};
73the caller should @code{free()} the line when it has finished with it.
74The declaration for @code{readline} in ANSI C is
75
76@example
77@code{char *readline (const char *@var{prompt});}
78@end example
79
80@noindent
81So, one might say
82@example
83@code{char *line = readline ("Enter a line: ");}
84@end example
85@noindent
86in order to read a line of text from the user.
87The line returned has the final newline removed, so only the
88text remains.
89
90If @code{readline} encounters an @code{EOF} while reading the line, and the
91line is empty at that point, then @code{(char *)NULL} is returned.
92Otherwise, the line is ended just as if a newline had been typed.
93
94If you want the user to be able to get at the line later, (with
95@key{C-p} for example), you must call @code{add_history()} to save the
96line away in a @dfn{history} list of such lines.
97
98@example
99@code{add_history (line)};
100@end example
101
102@noindent
103For full details on the GNU History Library, see the associated manual.
104
105It is preferable to avoid saving empty lines on the history list, since
106users rarely have a burning need to reuse a blank line. Here is
107a function which usefully replaces the standard @code{gets()} library
108function, and has the advantage of no static buffer to overflow:
109
110@example
111/* A static variable for holding the line. */
112static char *line_read = (char *)NULL;
113
114/* Read a string, and return a pointer to it.
115 Returns NULL on EOF. */
116char *
117rl_gets ()
118@{
119 /* If the buffer has already been allocated,
120 return the memory to the free pool. */
121 if (line_read)
122 @{
123 free (line_read);
124 line_read = (char *)NULL;
125 @}
126
127 /* Get a line from the user. */
128 line_read = readline ("");
129
130 /* If the line has any text in it,
131 save it on the history. */
132 if (line_read && *line_read)
133 add_history (line_read);
134
135 return (line_read);
136@}
137@end example
138
139This function gives the user the default behaviour of @key{TAB}
140completion: completion on file names. If you do not want Readline to
141complete on filenames, you can change the binding of the @key{TAB} key
142with @code{rl_bind_key()}.
143
144@example
145@code{int rl_bind_key (int @var{key}, rl_command_func_t *@var{function});}
146@end example
147
148@code{rl_bind_key()} takes two arguments: @var{key} is the character that
149you want to bind, and @var{function} is the address of the function to
150call when @var{key} is pressed. Binding @key{TAB} to @code{rl_insert()}
151makes @key{TAB} insert itself.
152@code{rl_bind_key()} returns non-zero if @var{key} is not a valid
153ASCII character code (between 0 and 255).
154
155Thus, to disable the default @key{TAB} behavior, the following suffices:
156@example
157@code{rl_bind_key ('\t', rl_insert);}
158@end example
159
160This code should be executed once at the start of your program; you
161might write a function called @code{initialize_readline()} which
162performs this and other desired initializations, such as installing
163custom completers (@pxref{Custom Completers}).
164
165@node Custom Functions
166@section Custom Functions
167
168Readline provides many functions for manipulating the text of
169the line, but it isn't possible to anticipate the needs of all
170programs. This section describes the various functions and variables
171defined within the Readline library which allow a user program to add
172customized functionality to Readline.
173
174Before declaring any functions that customize Readline's behavior, or
175using any functionality Readline provides in other code, an
176application writer should include the file @code{<readline/readline.h>}
177in any file that uses Readline's features. Since some of the definitions
178in @code{readline.h} use the @code{stdio} library, the file
179@code{<stdio.h>} should be included before @code{readline.h}.
180
181@code{readline.h} defines a C preprocessor variable that should
182be treated as an integer, @code{RL_READLINE_VERSION}, which may
183be used to conditionally compile application code depending on
184the installed Readline version. The value is a hexadecimal
185encoding of the major and minor version numbers of the library,
186of the form 0x@var{MMmm}. @var{MM} is the two-digit major
187version number; @var{mm} is the two-digit minor version number.
188For Readline 4.2, for example, the value of
189@code{RL_READLINE_VERSION} would be @code{0x0402}.
190
191@menu
192* Readline Typedefs:: C declarations to make code readable.
193* Function Writing:: Variables and calling conventions.
194@end menu
195
196@node Readline Typedefs
197@subsection Readline Typedefs
198
199For readabilty, we declare a number of new object types, all pointers
200to functions.
201
202The reason for declaring these new types is to make it easier to write
203code describing pointers to C functions with appropriately prototyped
204arguments and return values.
205
206For instance, say we want to declare a variable @var{func} as a pointer
207to a function which takes two @code{int} arguments and returns an
208@code{int} (this is the type of all of the Readline bindable functions).
209Instead of the classic C declaration
210
211@code{int (*func)();}
212
213@noindent
214or the ANSI-C style declaration
215
216@code{int (*func)(int, int);}
217
218@noindent
219we may write
220
221@code{rl_command_func_t *func;}
222
223The full list of function pointer types available is
224
225@table @code
226@item typedef int rl_command_func_t (int, int);
227
228@item typedef char *rl_compentry_func_t (const char *, int);
229
230@item typedef char **rl_completion_func_t (const char *, int, int);
231
232@item typedef char *rl_quote_func_t (char *, int, char *);
233
234@item typedef char *rl_dequote_func_t (char *, int);
235
236@item typedef int rl_compignore_func_t (char **);
237
238@item typedef void rl_compdisp_func_t (char **, int, int);
239
240@item typedef int rl_hook_func_t (void);
241
242@item typedef int rl_getc_func_t (FILE *);
243
244@item typedef int rl_linebuf_func_t (char *, int);
245
246@item typedef int rl_intfunc_t (int);
247@item #define rl_ivoidfunc_t rl_hook_func_t
248@item typedef int rl_icpfunc_t (char *);
249@item typedef int rl_icppfunc_t (char **);
250
251@item typedef void rl_voidfunc_t (void);
252@item typedef void rl_vintfunc_t (int);
253@item typedef void rl_vcpfunc_t (char *);
254@item typedef void rl_vcppfunc_t (char **);
255
256@end table
257
258@node Function Writing
259@subsection Writing a New Function
260
261In order to write new functions for Readline, you need to know the
262calling conventions for keyboard-invoked functions, and the names of the
263variables that describe the current state of the line read so far.
264
265The calling sequence for a command @code{foo} looks like
266
267@example
268@code{int foo (int count, int key)}
269@end example
270
271@noindent
272where @var{count} is the numeric argument (or 1 if defaulted) and
273@var{key} is the key that invoked this function.
274
275It is completely up to the function as to what should be done with the
276numeric argument. Some functions use it as a repeat count, some
277as a flag, and others to choose alternate behavior (refreshing the current
278line as opposed to refreshing the screen, for example). Some choose to
279ignore it. In general, if a
280function uses the numeric argument as a repeat count, it should be able
281to do something useful with both negative and positive arguments.
282At the very least, it should be aware that it can be passed a
283negative argument.
284
285A command function should return 0 if its action completes successfully,
286and a non-zero value if some error occurs.
287
288@node Readline Variables
289@section Readline Variables
290
291These variables are available to function writers.
292
293@deftypevar {char *} rl_line_buffer
294This is the line gathered so far. You are welcome to modify the
295contents of the line, but see @ref{Allowing Undoing}. The
296function @code{rl_extend_line_buffer} is available to increase
297the memory allocated to @code{rl_line_buffer}.
298@end deftypevar
299
300@deftypevar int rl_point
301The offset of the current cursor position in @code{rl_line_buffer}
302(the @emph{point}).
303@end deftypevar
304
305@deftypevar int rl_end
306The number of characters present in @code{rl_line_buffer}. When
307@code{rl_point} is at the end of the line, @code{rl_point} and
308@code{rl_end} are equal.
309@end deftypevar
310
311@deftypevar int rl_mark
312The @var{mark} (saved position) in the current line. If set, the mark
313and point define a @emph{region}.
314@end deftypevar
315
316@deftypevar int rl_done
317Setting this to a non-zero value causes Readline to return the current
318line immediately.
319@end deftypevar
320
321@deftypevar int rl_num_chars_to_read
322Setting this to a positive value before calling @code{readline()} causes
323Readline to return after accepting that many characters, rather
324than reading up to a character bound to @code{accept-line}.
325@end deftypevar
326
327@deftypevar int rl_pending_input
328Setting this to a value makes it the next keystroke read. This is a
329way to stuff a single character into the input stream.
330@end deftypevar
331
332@deftypevar int rl_dispatching
333Set to a non-zero value if a function is being called from a key binding;
334zero otherwise. Application functions can test this to discover whether
335they were called directly or by Readline's dispatching mechanism.
336@end deftypevar
337
338@deftypevar int rl_erase_empty_line
339Setting this to a non-zero value causes Readline to completely erase
340the current line, including any prompt, any time a newline is typed as
341the only character on an otherwise-empty line. The cursor is moved to
342the beginning of the newly-blank line.
343@end deftypevar
344
345@deftypevar {char *} rl_prompt
346The prompt Readline uses. This is set from the argument to
347@code{readline()}, and should not be assigned to directly.
348The @code{rl_set_prompt()} function (@pxref{Redisplay}) may
349be used to modify the prompt string after calling @code{readline()}.
350@end deftypevar
351
352@deftypevar int rl_already_prompted
353If an application wishes to display the prompt itself, rather than have
354Readline do it the first time @code{readline()} is called, it should set
355this variable to a non-zero value after displaying the prompt.
356The prompt must also be passed as the argument to @code{readline()} so
357the redisplay functions can update the display properly.
358The calling application is responsible for managing the value; Readline
359never sets it.
360@end deftypevar
361
362@deftypevar {const char *} rl_library_version
363The version number of this revision of the library.
364@end deftypevar
365
366@deftypevar int rl_readline_version
367An integer encoding the current version of the library. The encoding is
368of the form 0x@var{MMmm}, where @var{MM} is the two-digit major version
369number, and @var{mm} is the two-digit minor version number.
370For example, for Readline-4.2, @code{rl_readline_version} would have the
371value 0x0402.
372@end deftypevar
373
374@deftypevar {int} rl_gnu_readline_p
375Always set to 1, denoting that this is @sc{gnu} readline rather than some
376emulation.
377@end deftypevar
378
379@deftypevar {const char *} rl_terminal_name
380The terminal type, used for initialization. If not set by the application,
381Readline sets this to the value of the @env{TERM} environment variable
382the first time it is called.
383@end deftypevar
384
385@deftypevar {const char *} rl_readline_name
386This variable is set to a unique name by each application using Readline.
387The value allows conditional parsing of the inputrc file
388(@pxref{Conditional Init Constructs}).
389@end deftypevar
390
391@deftypevar {FILE *} rl_instream
392The stdio stream from which Readline reads input.
393If @code{NULL}, Readline defaults to @var{stdin}.
394@end deftypevar
395
396@deftypevar {FILE *} rl_outstream
397The stdio stream to which Readline performs output.
398If @code{NULL}, Readline defaults to @var{stdout}.
399@end deftypevar
400
401@deftypevar {rl_command_func_t *} rl_last_func
402The address of the last command function Readline executed. May be used to
403test whether or not a function is being executed twice in succession, for
404example.
405@end deftypevar
406
407@deftypevar {rl_hook_func_t *} rl_startup_hook
408If non-zero, this is the address of a function to call just
409before @code{readline} prints the first prompt.
410@end deftypevar
411
412@deftypevar {rl_hook_func_t *} rl_pre_input_hook
413If non-zero, this is the address of a function to call after
414the first prompt has been printed and just before @code{readline}
415starts reading input characters.
416@end deftypevar
417
418@deftypevar {rl_hook_func_t *} rl_event_hook
419If non-zero, this is the address of a function to call periodically
420when Readline is waiting for terminal input.
421By default, this will be called at most ten times a second if there
422is no keyboard input.
423@end deftypevar
424
425@deftypevar {rl_getc_func_t *} rl_getc_function
426If non-zero, Readline will call indirectly through this pointer
427to get a character from the input stream. By default, it is set to
428@code{rl_getc}, the default Readline character input function
429(@pxref{Character Input}).
430@end deftypevar
431
432@deftypevar {rl_voidfunc_t *} rl_redisplay_function
433If non-zero, Readline will call indirectly through this pointer
434to update the display with the current contents of the editing buffer.
435By default, it is set to @code{rl_redisplay}, the default Readline
436redisplay function (@pxref{Redisplay}).
437@end deftypevar
438
439@deftypevar {rl_vintfunc_t *} rl_prep_term_function
440If non-zero, Readline will call indirectly through this pointer
441to initialize the terminal. The function takes a single argument, an
442@code{int} flag that says whether or not to use eight-bit characters.
443By default, this is set to @code{rl_prep_terminal}
444(@pxref{Terminal Management}).
445@end deftypevar
446
447@deftypevar {rl_voidfunc_t *} rl_deprep_term_function
448If non-zero, Readline will call indirectly through this pointer
449to reset the terminal. This function should undo the effects of
450@code{rl_prep_term_function}.
451By default, this is set to @code{rl_deprep_terminal}
452(@pxref{Terminal Management}).
453@end deftypevar
454
455@deftypevar {Keymap} rl_executing_keymap
456This variable is set to the keymap (@pxref{Keymaps}) in which the
457currently executing readline function was found.
458@end deftypevar
459
460@deftypevar {Keymap} rl_binding_keymap
461This variable is set to the keymap (@pxref{Keymaps}) in which the
462last key binding occurred.
463@end deftypevar
464
465@deftypevar {char *} rl_executing_macro
466This variable is set to the text of any currently-executing macro.
467@end deftypevar
468
469@deftypevar {int} rl_readline_state
470A variable with bit values that encapsulate the current Readline state.
471A bit is set with the @code{RL_SETSTATE} macro, and unset with the
472@code{RL_UNSETSTATE} macro. Use the @code{RL_ISSTATE} macro to test
473whether a particular state bit is set. Current state bits include:
474
475@table @code
476@item RL_STATE_NONE
477Readline has not yet been called, nor has it begun to intialize.
478@item RL_STATE_INITIALIZING
479Readline is initializing its internal data structures.
480@item RL_STATE_INITIALIZED
481Readline has completed its initialization.
482@item RL_STATE_TERMPREPPED
483Readline has modified the terminal modes to do its own input and redisplay.
484@item RL_STATE_READCMD
485Readline is reading a command from the keyboard.
486@item RL_STATE_METANEXT
487Readline is reading more input after reading the meta-prefix character.
488@item RL_STATE_DISPATCHING
489Readline is dispatching to a command.
490@item RL_STATE_MOREINPUT
491Readline is reading more input while executing an editing command.
492@item RL_STATE_ISEARCH
493Readline is performing an incremental history search.
494@item RL_STATE_NSEARCH
495Readline is performing a non-incremental history search.
496@item RL_STATE_SEARCH
497Readline is searching backward or forward through the history for a string.
498@item RL_STATE_NUMERICARG
499Readline is reading a numeric argument.
500@item RL_STATE_MACROINPUT
501Readline is currently getting its input from a previously-defined keyboard
502macro.
503@item RL_STATE_MACRODEF
504Readline is currently reading characters defining a keyboard macro.
505@item RL_STATE_OVERWRITE
506Readline is in overwrite mode.
507@item RL_STATE_COMPLETING
508Readline is performing word completion.
509@item RL_STATE_SIGHANDLER
510Readline is currently executing the readline signal handler.
511@item RL_STATE_UNDOING
512Readline is performing an undo.
513@item RL_STATE_DONE
514Readline has read a key sequence bound to @code{accept-line}
515and is about to return the line to the caller.
516@end table
517
518@end deftypevar
519
520@deftypevar {int} rl_explicit_arg
521Set to a non-zero value if an explicit numeric argument was specified by
522the user. Only valid in a bindable command function.
523@end deftypevar
524
525@deftypevar {int} rl_numeric_arg
526Set to the value of any numeric argument explicitly specified by the user
527before executing the current Readline function. Only valid in a bindable
528command function.
529@end deftypevar
530
531@deftypevar {int} rl_editing_mode
532Set to a value denoting Readline's current editing mode. A value of
533@var{1} means Readline is currently in emacs mode; @var{0}
534means that vi mode is active.
535@end deftypevar
536
537
538@node Readline Convenience Functions
539@section Readline Convenience Functions
540
541@menu
542* Function Naming:: How to give a function you write a name.
543* Keymaps:: Making keymaps.
544* Binding Keys:: Changing Keymaps.
545* Associating Function Names and Bindings:: Translate function names to
546 key sequences.
547* Allowing Undoing:: How to make your functions undoable.
548* Redisplay:: Functions to control line display.
549* Modifying Text:: Functions to modify @code{rl_line_buffer}.
550* Character Input:: Functions to read keyboard input.
551* Terminal Management:: Functions to manage terminal settings.
552* Utility Functions:: Generally useful functions and hooks.
553* Miscellaneous Functions:: Functions that don't fall into any category.
554* Alternate Interface:: Using Readline in a `callback' fashion.
555* A Readline Example:: An example Readline function.
556@end menu
557
558@node Function Naming
559@subsection Naming a Function
560
561The user can dynamically change the bindings of keys while using
562Readline. This is done by representing the function with a descriptive
563name. The user is able to type the descriptive name when referring to
564the function. Thus, in an init file, one might find
565
566@example
567Meta-Rubout: backward-kill-word
568@end example
569
570This binds the keystroke @key{Meta-Rubout} to the function
571@emph{descriptively} named @code{backward-kill-word}. You, as the
572programmer, should bind the functions you write to descriptive names as
573well. Readline provides a function for doing that:
574
575@deftypefun int rl_add_defun (const char *name, rl_command_func_t *function, int key)
576Add @var{name} to the list of named functions. Make @var{function} be
577the function that gets called. If @var{key} is not -1, then bind it to
578@var{function} using @code{rl_bind_key()}.
579@end deftypefun
580
581Using this function alone is sufficient for most applications.
582It is the recommended way to add a few functions to the default
583functions that Readline has built in.
584If you need to do something other than adding a function to Readline,
585you may need to use the underlying functions described below.
586
587@node Keymaps
588@subsection Selecting a Keymap
589
590Key bindings take place on a @dfn{keymap}. The keymap is the
591association between the keys that the user types and the functions that
592get run. You can make your own keymaps, copy existing keymaps, and tell
593Readline which keymap to use.
594
595@deftypefun Keymap rl_make_bare_keymap (void)
596Returns a new, empty keymap. The space for the keymap is allocated with
597@code{malloc()}; the caller should free it by calling
598@code{rl_discard_keymap()} when done.
599@end deftypefun
600
601@deftypefun Keymap rl_copy_keymap (Keymap map)
602Return a new keymap which is a copy of @var{map}.
603@end deftypefun
604
605@deftypefun Keymap rl_make_keymap (void)
606Return a new keymap with the printing characters bound to rl_insert,
607the lowercase Meta characters bound to run their equivalents, and
608the Meta digits bound to produce numeric arguments.
609@end deftypefun
610
611@deftypefun void rl_discard_keymap (Keymap keymap)
612Free the storage associated with @var{keymap}.
613@end deftypefun
614
615Readline has several internal keymaps. These functions allow you to
616change which keymap is active.
617
618@deftypefun Keymap rl_get_keymap (void)
619Returns the currently active keymap.
620@end deftypefun
621
622@deftypefun void rl_set_keymap (Keymap keymap)
623Makes @var{keymap} the currently active keymap.
624@end deftypefun
625
626@deftypefun Keymap rl_get_keymap_by_name (const char *name)
627Return the keymap matching @var{name}. @var{name} is one which would
628be supplied in a @code{set keymap} inputrc line (@pxref{Readline Init File}).
629@end deftypefun
630
631@deftypefun {char *} rl_get_keymap_name (Keymap keymap)
632Return the name matching @var{keymap}. @var{name} is one which would
633be supplied in a @code{set keymap} inputrc line (@pxref{Readline Init File}).
634@end deftypefun
635
636@node Binding Keys
637@subsection Binding Keys
638
639Key sequences are associate with functions through the keymap.
640Readline has several internal keymaps: @code{emacs_standard_keymap},
641@code{emacs_meta_keymap}, @code{emacs_ctlx_keymap},
642@code{vi_movement_keymap}, and @code{vi_insertion_keymap}.
643@code{emacs_standard_keymap} is the default, and the examples in
644this manual assume that.
645
646Since @code{readline()} installs a set of default key bindings the first
647time it is called, there is always the danger that a custom binding
648installed before the first call to @code{readline()} will be overridden.
649An alternate mechanism is to install custom key bindings in an
650initialization function assigned to the @code{rl_startup_hook} variable
651(@pxref{Readline Variables}).
652
653These functions manage key bindings.
654
655@deftypefun int rl_bind_key (int key, rl_command_func_t *function)
656Binds @var{key} to @var{function} in the currently active keymap.
657Returns non-zero in the case of an invalid @var{key}.
658@end deftypefun
659
660@deftypefun int rl_bind_key_in_map (int key, rl_command_func_t *function, Keymap map)
661Bind @var{key} to @var{function} in @var{map}.
662Returns non-zero in the case of an invalid @var{key}.
663@end deftypefun
664
665@deftypefun int rl_bind_key_if_unbound (int key, rl_command_func_t *function)
666Binds @var{key} to @var{function} if it is not already bound in the
667currently active keymap.
668Returns non-zero in the case of an invalid @var{key} or if @var{key} is
669already bound.
670@end deftypefun
671
672@deftypefun int rl_bind_key_if_unbound_in_map (int key, rl_command_func_t *function, Keymap map)
673Binds @var{key} to @var{function} if it is not already bound in @var{map}.
674Returns non-zero in the case of an invalid @var{key} or if @var{key} is
675already bound.
676@end deftypefun
677
678@deftypefun int rl_unbind_key (int key)
679Bind @var{key} to the null function in the currently active keymap.
680Returns non-zero in case of error.
681@end deftypefun
682
683@deftypefun int rl_unbind_key_in_map (int key, Keymap map)
684Bind @var{key} to the null function in @var{map}.
685Returns non-zero in case of error.
686@end deftypefun
687
688@deftypefun int rl_unbind_function_in_map (rl_command_func_t *function, Keymap map)
689Unbind all keys that execute @var{function} in @var{map}.
690@end deftypefun
691
692@deftypefun int rl_unbind_command_in_map (const char *command, Keymap map)
693Unbind all keys that are bound to @var{command} in @var{map}.
694@end deftypefun
695
696@deftypefun int rl_bind_keyseq (const char *keyseq, rl_command_func_t *function)
697Bind the key sequence represented by the string @var{keyseq} to the function
698@var{function}, beginning in the current keymap.
699This makes new keymaps as necessary.
700The return value is non-zero if @var{keyseq} is invalid.
701@end deftypefun
702
703@deftypefun int rl_bind_keyseq_in_map (const char *keyseq, rl_command_func_t *function, Keymap map)
704Bind the key sequence represented by the string @var{keyseq} to the function
705@var{function}. This makes new keymaps as necessary.
706Initial bindings are performed in @var{map}.
707The return value is non-zero if @var{keyseq} is invalid.
708@end deftypefun
709
710@deftypefun int rl_set_key (const char *keyseq, rl_command_func_t *function, Keymap map)
711Equivalent to @code{rl_bind_keyseq_in_map}.
712@end deftypefun
713
714@deftypefun int rl_bind_keyseq_if_unbound (const char *keyseq, rl_command_func_t *function)
715Binds @var{keyseq} to @var{function} if it is not already bound in the
716currently active keymap.
717Returns non-zero in the case of an invalid @var{keyseq} or if @var{keyseq} is
718already bound.
719@end deftypefun
720
721@deftypefun int rl_bind_keyseq_if_unbound_in_map (const char *keyseq, rl_command_func_t *function, Keymap map)
722Binds @var{keyseq} to @var{function} if it is not already bound in @var{map}.
723Returns non-zero in the case of an invalid @var{keyseq} or if @var{keyseq} is
724already bound.
725@end deftypefun
726
727@deftypefun int rl_generic_bind (int type, const char *keyseq, char *data, Keymap map)
728Bind the key sequence represented by the string @var{keyseq} to the arbitrary
729pointer @var{data}. @var{type} says what kind of data is pointed to by
730@var{data}; this can be a function (@code{ISFUNC}), a macro
731(@code{ISMACR}), or a keymap (@code{ISKMAP}). This makes new keymaps as
732necessary. The initial keymap in which to do bindings is @var{map}.
733@end deftypefun
734
735@deftypefun int rl_parse_and_bind (char *line)
736Parse @var{line} as if it had been read from the @code{inputrc} file and
737perform any key bindings and variable assignments found
738(@pxref{Readline Init File}).
739@end deftypefun
740
741@deftypefun int rl_read_init_file (const char *filename)
742Read keybindings and variable assignments from @var{filename}
743(@pxref{Readline Init File}).
744@end deftypefun
745
746@node Associating Function Names and Bindings
747@subsection Associating Function Names and Bindings
748
749These functions allow you to find out what keys invoke named functions
750and the functions invoked by a particular key sequence. You may also
751associate a new function name with an arbitrary function.
752
753@deftypefun {rl_command_func_t *} rl_named_function (const char *name)
754Return the function with name @var{name}.
755@end deftypefun
756
757@deftypefun {rl_command_func_t *} rl_function_of_keyseq (const char *keyseq, Keymap map, int *type)
758Return the function invoked by @var{keyseq} in keymap @var{map}.
759If @var{map} is @code{NULL}, the current keymap is used. If @var{type} is
760not @code{NULL}, the type of the object is returned in the @code{int} variable
761it points to (one of @code{ISFUNC}, @code{ISKMAP}, or @code{ISMACR}).
762@end deftypefun
763
764@deftypefun {char **} rl_invoking_keyseqs (rl_command_func_t *function)
765Return an array of strings representing the key sequences used to
766invoke @var{function} in the current keymap.
767@end deftypefun
768
769@deftypefun {char **} rl_invoking_keyseqs_in_map (rl_command_func_t *function, Keymap map)
770Return an array of strings representing the key sequences used to
771invoke @var{function} in the keymap @var{map}.
772@end deftypefun
773
774@deftypefun void rl_function_dumper (int readable)
775Print the readline function names and the key sequences currently
776bound to them to @code{rl_outstream}. If @var{readable} is non-zero,
777the list is formatted in such a way that it can be made part of an
778@code{inputrc} file and re-read.
779@end deftypefun
780
781@deftypefun void rl_list_funmap_names (void)
782Print the names of all bindable Readline functions to @code{rl_outstream}.
783@end deftypefun
784
785@deftypefun {const char **} rl_funmap_names (void)
786Return a NULL terminated array of known function names. The array is
787sorted. The array itself is allocated, but not the strings inside. You
788should @code{free()} the array when you are done, but not the pointers.
789@end deftypefun
790
791@deftypefun int rl_add_funmap_entry (const char *name, rl_command_func_t *function)
792Add @var{name} to the list of bindable Readline command names, and make
793@var{function} the function to be called when @var{name} is invoked.
794@end deftypefun
795
796@node Allowing Undoing
797@subsection Allowing Undoing
798
799Supporting the undo command is a painless thing, and makes your
800functions much more useful. It is certainly easy to try
801something if you know you can undo it.
802
803If your function simply inserts text once, or deletes text once, and
804uses @code{rl_insert_text()} or @code{rl_delete_text()} to do it, then
805undoing is already done for you automatically.
806
807If you do multiple insertions or multiple deletions, or any combination
808of these operations, you should group them together into one operation.
809This is done with @code{rl_begin_undo_group()} and
810@code{rl_end_undo_group()}.
811
812The types of events that can be undone are:
813
814@smallexample
815enum undo_code @{ UNDO_DELETE, UNDO_INSERT, UNDO_BEGIN, UNDO_END @};
816@end smallexample
817
818Notice that @code{UNDO_DELETE} means to insert some text, and
819@code{UNDO_INSERT} means to delete some text. That is, the undo code
820tells what to undo, not how to undo it. @code{UNDO_BEGIN} and
821@code{UNDO_END} are tags added by @code{rl_begin_undo_group()} and
822@code{rl_end_undo_group()}.
823
824@deftypefun int rl_begin_undo_group (void)
825Begins saving undo information in a group construct. The undo
826information usually comes from calls to @code{rl_insert_text()} and
827@code{rl_delete_text()}, but could be the result of calls to
828@code{rl_add_undo()}.
829@end deftypefun
830
831@deftypefun int rl_end_undo_group (void)
832Closes the current undo group started with @code{rl_begin_undo_group
833()}. There should be one call to @code{rl_end_undo_group()}
834for each call to @code{rl_begin_undo_group()}.
835@end deftypefun
836
837@deftypefun void rl_add_undo (enum undo_code what, int start, int end, char *text)
838Remember how to undo an event (according to @var{what}). The affected
839text runs from @var{start} to @var{end}, and encompasses @var{text}.
840@end deftypefun
841
842@deftypefun void rl_free_undo_list (void)
843Free the existing undo list.
844@end deftypefun
845
846@deftypefun int rl_do_undo (void)
847Undo the first thing on the undo list. Returns @code{0} if there was
848nothing to undo, non-zero if something was undone.
849@end deftypefun
850
851Finally, if you neither insert nor delete text, but directly modify the
852existing text (e.g., change its case), call @code{rl_modifying()}
853once, just before you modify the text. You must supply the indices of
854the text range that you are going to modify.
855
856@deftypefun int rl_modifying (int start, int end)
857Tell Readline to save the text between @var{start} and @var{end} as a
858single undo unit. It is assumed that you will subsequently modify
859that text.
860@end deftypefun
861
862@node Redisplay
863@subsection Redisplay
864
865@deftypefun void rl_redisplay (void)
866Change what's displayed on the screen to reflect the current contents
867of @code{rl_line_buffer}.
868@end deftypefun
869
870@deftypefun int rl_forced_update_display (void)
871Force the line to be updated and redisplayed, whether or not
872Readline thinks the screen display is correct.
873@end deftypefun
874
875@deftypefun int rl_on_new_line (void)
876Tell the update functions that we have moved onto a new (empty) line,
877usually after ouputting a newline.
878@end deftypefun
879
880@deftypefun int rl_on_new_line_with_prompt (void)
881Tell the update functions that we have moved onto a new line, with
882@var{rl_prompt} already displayed.
883This could be used by applications that want to output the prompt string
884themselves, but still need Readline to know the prompt string length for
885redisplay.
886It should be used after setting @var{rl_already_prompted}.
887@end deftypefun
888
889@deftypefun int rl_reset_line_state (void)
890Reset the display state to a clean state and redisplay the current line
891starting on a new line.
892@end deftypefun
893
894@deftypefun int rl_crlf (void)
895Move the cursor to the start of the next screen line.
896@end deftypefun
897
898@deftypefun int rl_show_char (int c)
899Display character @var{c} on @code{rl_outstream}.
900If Readline has not been set to display meta characters directly, this
901will convert meta characters to a meta-prefixed key sequence.
902This is intended for use by applications which wish to do their own
903redisplay.
904@end deftypefun
905
906@deftypefun int rl_message (const char *, @dots{})
907The arguments are a format string as would be supplied to @code{printf},
908possibly containing conversion specifications such as @samp{%d}, and
909any additional arguments necessary to satisfy the conversion specifications.
910The resulting string is displayed in the @dfn{echo area}. The echo area
911is also used to display numeric arguments and search strings.
912@end deftypefun
913
914@deftypefun int rl_clear_message (void)
915Clear the message in the echo area.
916@end deftypefun
917
918@deftypefun void rl_save_prompt (void)
919Save the local Readline prompt display state in preparation for
920displaying a new message in the message area with @code{rl_message()}.
921@end deftypefun
922
923@deftypefun void rl_restore_prompt (void)
924Restore the local Readline prompt display state saved by the most
925recent call to @code{rl_save_prompt}.
926@end deftypefun
927
928@deftypefun int rl_expand_prompt (char *prompt)
929Expand any special character sequences in @var{prompt} and set up the
930local Readline prompt redisplay variables.
931This function is called by @code{readline()}. It may also be called to
932expand the primary prompt if the @code{rl_on_new_line_with_prompt()}
933function or @code{rl_already_prompted} variable is used.
934It returns the number of visible characters on the last line of the
935(possibly multi-line) prompt.
12d937f9
CR
936Applications may indicate that the prompt contains characters that take
937up no physical screen space when displayed by bracketing a sequence of
938such characters with the special markers @code{RL_PROMPT_START_IGNORE}
939and @code{RL_PROMPT_END_IGNORE} (declared in @file{readline.h}. This may
940be used to embed terminal-specific escape sequences in prompts.
d3a24ed2
CR
941@end deftypefun
942
943@deftypefun int rl_set_prompt (const char *prompt)
944Make Readline use @var{prompt} for subsequent redisplay. This calls
945@code{rl_expand_prompt()} to expand the prompt and sets @code{rl_prompt}
946to the result.
947@end deftypefun
948
949@node Modifying Text
950@subsection Modifying Text
951
952@deftypefun int rl_insert_text (const char *text)
953Insert @var{text} into the line at the current cursor position.
954Returns the number of characters inserted.
955@end deftypefun
956
957@deftypefun int rl_delete_text (int start, int end)
958Delete the text between @var{start} and @var{end} in the current line.
959Returns the number of characters deleted.
960@end deftypefun
961
962@deftypefun {char *} rl_copy_text (int start, int end)
963Return a copy of the text between @var{start} and @var{end} in
964the current line.
965@end deftypefun
966
967@deftypefun int rl_kill_text (int start, int end)
968Copy the text between @var{start} and @var{end} in the current line
969to the kill ring, appending or prepending to the last kill if the
970last command was a kill command. The text is deleted.
971If @var{start} is less than @var{end},
972the text is appended, otherwise prepended. If the last command was
973not a kill, a new kill ring slot is used.
974@end deftypefun
975
976@deftypefun int rl_push_macro_input (char *macro)
977Cause @var{macro} to be inserted into the line, as if it had been invoked
978by a key bound to a macro. Not especially useful; use
979@code{rl_insert_text()} instead.
980@end deftypefun
981
982@node Character Input
983@subsection Character Input
984
985@deftypefun int rl_read_key (void)
986Return the next character available from Readline's current input stream.
987This handles input inserted into
988the input stream via @var{rl_pending_input} (@pxref{Readline Variables})
989and @code{rl_stuff_char()}, macros, and characters read from the keyboard.
990While waiting for input, this function will call any function assigned to
991the @code{rl_event_hook} variable.
992@end deftypefun
993
994@deftypefun int rl_getc (FILE *stream)
995Return the next character available from @var{stream}, which is assumed to
996be the keyboard.
997@end deftypefun
998
999@deftypefun int rl_stuff_char (int c)
1000Insert @var{c} into the Readline input stream. It will be "read"
1001before Readline attempts to read characters from the terminal with
1002@code{rl_read_key()}. Up to 512 characters may be pushed back.
1003@code{rl_stuff_char} returns 1 if the character was successfully inserted;
10040 otherwise.
1005@end deftypefun
1006
1007@deftypefun int rl_execute_next (int c)
1008Make @var{c} be the next command to be executed when @code{rl_read_key()}
1009is called. This sets @var{rl_pending_input}.
1010@end deftypefun
1011
1012@deftypefun int rl_clear_pending_input (void)
1013Unset @var{rl_pending_input}, effectively negating the effect of any
1014previous call to @code{rl_execute_next()}. This works only if the
1015pending input has not already been read with @code{rl_read_key()}.
1016@end deftypefun
1017
1018@deftypefun int rl_set_keyboard_input_timeout (int u)
1019While waiting for keyboard input in @code{rl_read_key()}, Readline will
1020wait for @var{u} microseconds for input before calling any function
1021assigned to @code{rl_event_hook}. The default waiting period is
1022one-tenth of a second. Returns the old timeout value.
1023@end deftypefun
1024
1025@node Terminal Management
1026@subsection Terminal Management
1027
1028@deftypefun void rl_prep_terminal (int meta_flag)
1029Modify the terminal settings for Readline's use, so @code{readline()}
1030can read a single character at a time from the keyboard.
1031The @var{meta_flag} argument should be non-zero if Readline should
1032read eight-bit input.
1033@end deftypefun
1034
1035@deftypefun void rl_deprep_terminal (void)
1036Undo the effects of @code{rl_prep_terminal()}, leaving the terminal in
1037the state in which it was before the most recent call to
1038@code{rl_prep_terminal()}.
1039@end deftypefun
1040
1041@deftypefun void rl_tty_set_default_bindings (Keymap kmap)
1042Read the operating system's terminal editing characters (as would be
1043displayed by @code{stty}) to their Readline equivalents.
1044The bindings are performed in @var{kmap}.
1045@end deftypefun
1046
1047@deftypefun void rl_tty_unset_default_bindings (Keymap kmap)
1048Reset the bindings manipulated by @code{rl_tty_set_default_bindings} so
1049that the terminal editing characters are bound to @code{rl_insert}.
1050The bindings are performed in @var{kmap}.
1051@end deftypefun
1052
1053@deftypefun int rl_reset_terminal (const char *terminal_name)
1054Reinitialize Readline's idea of the terminal settings using
1055@var{terminal_name} as the terminal type (e.g., @code{vt100}).
1056If @var{terminal_name} is @code{NULL}, the value of the @code{TERM}
1057environment variable is used.
1058@end deftypefun
1059
1060@node Utility Functions
1061@subsection Utility Functions
1062
1063@deftypefun void rl_replace_line (const char *text, int clear_undo)
1064Replace the contents of @code{rl_line_buffer} with @var{text}.
1065The point and mark are preserved, if possible.
1066If @var{clear_undo} is non-zero, the undo list associated with the
1067current line is cleared.
1068@end deftypefun
1069
1070@deftypefun int rl_extend_line_buffer (int len)
1071Ensure that @code{rl_line_buffer} has enough space to hold @var{len}
1072characters, possibly reallocating it if necessary.
1073@end deftypefun
1074
1075@deftypefun int rl_initialize (void)
1076Initialize or re-initialize Readline's internal state.
1077It's not strictly necessary to call this; @code{readline()} calls it before
1078reading any input.
1079@end deftypefun
1080
1081@deftypefun int rl_ding (void)
1082Ring the terminal bell, obeying the setting of @code{bell-style}.
1083@end deftypefun
1084
1085@deftypefun int rl_alphabetic (int c)
1086Return 1 if @var{c} is an alphabetic character.
1087@end deftypefun
1088
1089@deftypefun void rl_display_match_list (char **matches, int len, int max)
1090A convenience function for displaying a list of strings in
1091columnar format on Readline's output stream. @code{matches} is the list
1092of strings, in argv format, such as a list of completion matches.
1093@code{len} is the number of strings in @code{matches}, and @code{max}
1094is the length of the longest string in @code{matches}. This function uses
1095the setting of @code{print-completions-horizontally} to select how the
1096matches are displayed (@pxref{Readline Init File Syntax}).
1097@end deftypefun
1098
1099The following are implemented as macros, defined in @code{chardefs.h}.
1100Applications should refrain from using them.
1101
1102@deftypefun int _rl_uppercase_p (int c)
1103Return 1 if @var{c} is an uppercase alphabetic character.
1104@end deftypefun
1105
1106@deftypefun int _rl_lowercase_p (int c)
1107Return 1 if @var{c} is a lowercase alphabetic character.
1108@end deftypefun
1109
1110@deftypefun int _rl_digit_p (int c)
1111Return 1 if @var{c} is a numeric character.
1112@end deftypefun
1113
1114@deftypefun int _rl_to_upper (int c)
1115If @var{c} is a lowercase alphabetic character, return the corresponding
1116uppercase character.
1117@end deftypefun
1118
1119@deftypefun int _rl_to_lower (int c)
1120If @var{c} is an uppercase alphabetic character, return the corresponding
1121lowercase character.
1122@end deftypefun
1123
1124@deftypefun int _rl_digit_value (int c)
1125If @var{c} is a number, return the value it represents.
1126@end deftypefun
1127
1128@node Miscellaneous Functions
1129@subsection Miscellaneous Functions
1130
1131@deftypefun int rl_macro_bind (const char *keyseq, const char *macro, Keymap map)
1132Bind the key sequence @var{keyseq} to invoke the macro @var{macro}.
1133The binding is performed in @var{map}. When @var{keyseq} is invoked, the
1134@var{macro} will be inserted into the line. This function is deprecated;
1135use @code{rl_generic_bind()} instead.
1136@end deftypefun
1137
1138@deftypefun void rl_macro_dumper (int readable)
1139Print the key sequences bound to macros and their values, using
1140the current keymap, to @code{rl_outstream}.
1141If @var{readable} is non-zero, the list is formatted in such a way
1142that it can be made part of an @code{inputrc} file and re-read.
1143@end deftypefun
1144
1145@deftypefun int rl_variable_bind (const char *variable, const char *value)
1146Make the Readline variable @var{variable} have @var{value}.
1147This behaves as if the readline command
1148@samp{set @var{variable} @var{value}} had been executed in an @code{inputrc}
1149file (@pxref{Readline Init File Syntax}).
1150@end deftypefun
1151
1152@deftypefun void rl_variable_dumper (int readable)
1153Print the readline variable names and their current values
1154to @code{rl_outstream}.
1155If @var{readable} is non-zero, the list is formatted in such a way
1156that it can be made part of an @code{inputrc} file and re-read.
1157@end deftypefun
1158
1159@deftypefun int rl_set_paren_blink_timeout (int u)
1160Set the time interval (in microseconds) that Readline waits when showing
1161a balancing character when @code{blink-matching-paren} has been enabled.
1162@end deftypefun
1163
1164@deftypefun {char *} rl_get_termcap (const char *cap)
1165Retrieve the string value of the termcap capability @var{cap}.
1166Readline fetches the termcap entry for the current terminal name and
1167uses those capabilities to move around the screen line and perform other
1168terminal-specific operations, like erasing a line. Readline does not
1169use all of a terminal's capabilities, and this function will return
1170values for only those capabilities Readline uses.
1171@end deftypefun
1172
1173@node Alternate Interface
1174@subsection Alternate Interface
1175
1176An alternate interface is available to plain @code{readline()}. Some
1177applications need to interleave keyboard I/O with file, device, or
1178window system I/O, typically by using a main loop to @code{select()}
1179on various file descriptors. To accomodate this need, readline can
1180also be invoked as a `callback' function from an event loop. There
1181are functions available to make this easy.
1182
1183@deftypefun void rl_callback_handler_install (const char *prompt, rl_vcpfunc_t *lhandler)
1184Set up the terminal for readline I/O and display the initial
1185expanded value of @var{prompt}. Save the value of @var{lhandler} to
1186use as a function to call when a complete line of input has been entered.
1187The function takes the text of the line as an argument.
1188@end deftypefun
1189
1190@deftypefun void rl_callback_read_char (void)
1191Whenever an application determines that keyboard input is available, it
1192should call @code{rl_callback_read_char()}, which will read the next
1193character from the current input source.
1194If that character completes the line, @code{rl_callback_read_char} will
1195invoke the @var{lhandler} function saved by @code{rl_callback_handler_install}
1196to process the line.
1197Before calling the @var{lhandler} function, the terminal settings are
1198reset to the values they had before calling
1199@code{rl_callback_handler_install}.
1200If the @var{lhandler} function returns,
1201the terminal settings are modified for Readline's use again.
1202@code{EOF} is indicated by calling @var{lhandler} with a
1203@code{NULL} line.
1204@end deftypefun
1205
1206@deftypefun void rl_callback_handler_remove (void)
1207Restore the terminal to its initial state and remove the line handler.
1208This may be called from within a callback as well as independently.
1209If the @var{lhandler} installed by @code{rl_callback_handler_install}
1210does not exit the program, either this function or the function referred
1211to by the value of @code{rl_deprep_term_function} should be called before
1212the program exits to reset the terminal settings.
1213@end deftypefun
1214
1215@node A Readline Example
1216@subsection A Readline Example
1217
1218Here is a function which changes lowercase characters to their uppercase
1219equivalents, and uppercase characters to lowercase. If
1220this function was bound to @samp{M-c}, then typing @samp{M-c} would
1221change the case of the character under point. Typing @samp{M-1 0 M-c}
1222would change the case of the following 10 characters, leaving the cursor on
1223the last character changed.
1224
1225@example
1226/* Invert the case of the COUNT following characters. */
1227int
1228invert_case_line (count, key)
1229 int count, key;
1230@{
1231 register int start, end, i;
1232
1233 start = rl_point;
1234
1235 if (rl_point >= rl_end)
1236 return (0);
1237
1238 if (count < 0)
1239 @{
1240 direction = -1;
1241 count = -count;
1242 @}
1243 else
1244 direction = 1;
1245
1246 /* Find the end of the range to modify. */
1247 end = start + (count * direction);
1248
1249 /* Force it to be within range. */
1250 if (end > rl_end)
1251 end = rl_end;
1252 else if (end < 0)
1253 end = 0;
1254
1255 if (start == end)
1256 return (0);
1257
1258 if (start > end)
1259 @{
1260 int temp = start;
1261 start = end;
1262 end = temp;
1263 @}
1264
1265 /* Tell readline that we are modifying the line,
1266 so it will save the undo information. */
1267 rl_modifying (start, end);
1268
1269 for (i = start; i != end; i++)
1270 @{
1271 if (_rl_uppercase_p (rl_line_buffer[i]))
1272 rl_line_buffer[i] = _rl_to_lower (rl_line_buffer[i]);
1273 else if (_rl_lowercase_p (rl_line_buffer[i]))
1274 rl_line_buffer[i] = _rl_to_upper (rl_line_buffer[i]);
1275 @}
1276 /* Move point to on top of the last character changed. */
1277 rl_point = (direction == 1) ? end - 1 : start;
1278 return (0);
1279@}
1280@end example
1281
1282@node Readline Signal Handling
1283@section Readline Signal Handling
1284
1285Signals are asynchronous events sent to a process by the Unix kernel,
1286sometimes on behalf of another process. They are intended to indicate
1287exceptional events, like a user pressing the interrupt key on his terminal,
1288or a network connection being broken. There is a class of signals that can
1289be sent to the process currently reading input from the keyboard. Since
1290Readline changes the terminal attributes when it is called, it needs to
1291perform special processing when such a signal is received in order to
1292restore the terminal to a sane state, or provide application writers with
1293functions to do so manually.
1294
1295Readline contains an internal signal handler that is installed for a
1296number of signals (@code{SIGINT}, @code{SIGQUIT}, @code{SIGTERM},
1297@code{SIGALRM}, @code{SIGTSTP}, @code{SIGTTIN}, and @code{SIGTTOU}).
1298When one of these signals is received, the signal handler
1299will reset the terminal attributes to those that were in effect before
1300@code{readline()} was called, reset the signal handling to what it was
1301before @code{readline()} was called, and resend the signal to the calling
1302application.
1303If and when the calling application's signal handler returns, Readline
1304will reinitialize the terminal and continue to accept input.
1305When a @code{SIGINT} is received, the Readline signal handler performs
1306some additional work, which will cause any partially-entered line to be
1307aborted (see the description of @code{rl_free_line_state()} below).
1308
1309There is an additional Readline signal handler, for @code{SIGWINCH}, which
1310the kernel sends to a process whenever the terminal's size changes (for
1311example, if a user resizes an @code{xterm}). The Readline @code{SIGWINCH}
1312handler updates Readline's internal screen size information, and then calls
1313any @code{SIGWINCH} signal handler the calling application has installed.
1314Readline calls the application's @code{SIGWINCH} signal handler without
1315resetting the terminal to its original state. If the application's signal
1316handler does more than update its idea of the terminal size and return (for
1317example, a @code{longjmp} back to a main processing loop), it @emph{must}
1318call @code{rl_cleanup_after_signal()} (described below), to restore the
1319terminal state.
1320
1321Readline provides two variables that allow application writers to
1322control whether or not it will catch certain signals and act on them
1323when they are received. It is important that applications change the
1324values of these variables only when calling @code{readline()}, not in
1325a signal handler, so Readline's internal signal state is not corrupted.
1326
1327@deftypevar int rl_catch_signals
1328If this variable is non-zero, Readline will install signal handlers for
1329@code{SIGINT}, @code{SIGQUIT}, @code{SIGTERM}, @code{SIGALRM},
1330@code{SIGTSTP}, @code{SIGTTIN}, and @code{SIGTTOU}.
1331
1332The default value of @code{rl_catch_signals} is 1.
1333@end deftypevar
1334
1335@deftypevar int rl_catch_sigwinch
1336If this variable is non-zero, Readline will install a signal handler for
1337@code{SIGWINCH}.
1338
1339The default value of @code{rl_catch_sigwinch} is 1.
1340@end deftypevar
1341
1342If an application does not wish to have Readline catch any signals, or
1343to handle signals other than those Readline catches (@code{SIGHUP},
1344for example),
1345Readline provides convenience functions to do the necessary terminal
1346and internal state cleanup upon receipt of a signal.
1347
1348@deftypefun void rl_cleanup_after_signal (void)
1349This function will reset the state of the terminal to what it was before
1350@code{readline()} was called, and remove the Readline signal handlers for
1351all signals, depending on the values of @code{rl_catch_signals} and
1352@code{rl_catch_sigwinch}.
1353@end deftypefun
1354
1355@deftypefun void rl_free_line_state (void)
1356This will free any partial state associated with the current input line
1357(undo information, any partial history entry, any partially-entered
1358keyboard macro, and any partially-entered numeric argument). This
1359should be called before @code{rl_cleanup_after_signal()}. The
1360Readline signal handler for @code{SIGINT} calls this to abort the
1361current input line.
1362@end deftypefun
1363
1364@deftypefun void rl_reset_after_signal (void)
1365This will reinitialize the terminal and reinstall any Readline signal
1366handlers, depending on the values of @code{rl_catch_signals} and
1367@code{rl_catch_sigwinch}.
1368@end deftypefun
1369
1370If an application does not wish Readline to catch @code{SIGWINCH}, it may
1371call @code{rl_resize_terminal()} or @code{rl_set_screen_size()} to force
1372Readline to update its idea of the terminal size when a @code{SIGWINCH}
1373is received.
1374
1375@deftypefun void rl_resize_terminal (void)
1376Update Readline's internal screen size by reading values from the kernel.
1377@end deftypefun
1378
1379@deftypefun void rl_set_screen_size (int rows, int cols)
1380Set Readline's idea of the terminal size to @var{rows} rows and
1381@var{cols} columns.
1382@end deftypefun
1383
1384If an application does not want to install a @code{SIGWINCH} handler, but
1385is still interested in the screen dimensions, Readline's idea of the screen
1386size may be queried.
1387
1388@deftypefun void rl_get_screen_size (int *rows, int *cols)
1389Return Readline's idea of the terminal's size in the
1390variables pointed to by the arguments.
1391@end deftypefun
1392
1393The following functions install and remove Readline's signal handlers.
1394
1395@deftypefun int rl_set_signals (void)
1396Install Readline's signal handler for @code{SIGINT}, @code{SIGQUIT},
1397@code{SIGTERM}, @code{SIGALRM}, @code{SIGTSTP}, @code{SIGTTIN},
1398@code{SIGTTOU}, and @code{SIGWINCH}, depending on the values of
1399@code{rl_catch_signals} and @code{rl_catch_sigwinch}.
1400@end deftypefun
1401
1402@deftypefun int rl_clear_signals (void)
1403Remove all of the Readline signal handlers installed by
1404@code{rl_set_signals()}.
1405@end deftypefun
1406
1407@node Custom Completers
1408@section Custom Completers
1409@cindex application-specific completion functions
1410
1411Typically, a program that reads commands from the user has a way of
1412disambiguating commands and data. If your program is one of these, then
1413it can provide completion for commands, data, or both.
1414The following sections describe how your program and Readline
1415cooperate to provide this service.
1416
1417@menu
1418* How Completing Works:: The logic used to do completion.
1419* Completion Functions:: Functions provided by Readline.
1420* Completion Variables:: Variables which control completion.
1421* A Short Completion Example:: An example of writing completer subroutines.
1422@end menu
1423
1424@node How Completing Works
1425@subsection How Completing Works
1426
1427In order to complete some text, the full list of possible completions
1428must be available. That is, it is not possible to accurately
1429expand a partial word without knowing all of the possible words
1430which make sense in that context. The Readline library provides
1431the user interface to completion, and two of the most common
1432completion functions: filename and username. For completing other types
1433of text, you must write your own completion function. This section
1434describes exactly what such functions must do, and provides an example.
1435
1436There are three major functions used to perform completion:
1437
1438@enumerate
1439@item
1440The user-interface function @code{rl_complete()}. This function is
1441called with the same arguments as other bindable Readline functions:
1442@var{count} and @var{invoking_key}.
1443It isolates the word to be completed and calls
1444@code{rl_completion_matches()} to generate a list of possible completions.
1445It then either lists the possible completions, inserts the possible
1446completions, or actually performs the
1447completion, depending on which behavior is desired.
1448
1449@item
1450The internal function @code{rl_completion_matches()} uses an
1451application-supplied @dfn{generator} function to generate the list of
1452possible matches, and then returns the array of these matches.
1453The caller should place the address of its generator function in
1454@code{rl_completion_entry_function}.
1455
1456@item
1457The generator function is called repeatedly from
1458@code{rl_completion_matches()}, returning a string each time. The
1459arguments to the generator function are @var{text} and @var{state}.
1460@var{text} is the partial word to be completed. @var{state} is zero the
1461first time the function is called, allowing the generator to perform
1462any necessary initialization, and a positive non-zero integer for
1463each subsequent call. The generator function returns
1464@code{(char *)NULL} to inform @code{rl_completion_matches()} that there are
1465no more possibilities left. Usually the generator function computes the
1466list of possible completions when @var{state} is zero, and returns them
1467one at a time on subsequent calls. Each string the generator function
1468returns as a match must be allocated with @code{malloc()}; Readline
1469frees the strings when it has finished with them.
1470Such a generator function is referred to as an
1471@dfn{application-specific completion function}.
1472
1473@end enumerate
1474
1475@deftypefun int rl_complete (int ignore, int invoking_key)
1476Complete the word at or before point. You have supplied the function
1477that does the initial simple matching selection algorithm (see
1478@code{rl_completion_matches()}). The default is to do filename completion.
1479@end deftypefun
1480
1481@deftypevar {rl_compentry_func_t *} rl_completion_entry_function
1482This is a pointer to the generator function for
1483@code{rl_completion_matches()}.
1484If the value of @code{rl_completion_entry_function} is
1485@code{NULL} then the default filename generator
1486function, @code{rl_filename_completion_function()}, is used.
1487An @dfn{application-specific completion function} is a function whose
1488address is assigned to @code{rl_completion_entry_function} and whose
1489return values are used to generate possible completions.
1490@end deftypevar
1491
1492@node Completion Functions
1493@subsection Completion Functions
1494
1495Here is the complete list of callable completion functions present in
1496Readline.
1497
1498@deftypefun int rl_complete_internal (int what_to_do)
1499Complete the word at or before point. @var{what_to_do} says what to do
1500with the completion. A value of @samp{?} means list the possible
1501completions. @samp{TAB} means do standard completion. @samp{*} means
1502insert all of the possible completions. @samp{!} means to display
1503all of the possible completions, if there is more than one, as well as
1504performing partial completion. @samp{@@} is similar to @samp{!}, but
1505possible completions are not listed if the possible completions share
1506a common prefix.
1507@end deftypefun
1508
1509@deftypefun int rl_complete (int ignore, int invoking_key)
1510Complete the word at or before point. You have supplied the function
1511that does the initial simple matching selection algorithm (see
1512@code{rl_completion_matches()} and @code{rl_completion_entry_function}).
1513The default is to do filename
1514completion. This calls @code{rl_complete_internal()} with an
1515argument depending on @var{invoking_key}.
1516@end deftypefun
1517
1518@deftypefun int rl_possible_completions (int count, int invoking_key)
1519List the possible completions. See description of @code{rl_complete
1520()}. This calls @code{rl_complete_internal()} with an argument of
1521@samp{?}.
1522@end deftypefun
1523
1524@deftypefun int rl_insert_completions (int count, int invoking_key)
1525Insert the list of possible completions into the line, deleting the
1526partially-completed word. See description of @code{rl_complete()}.
1527This calls @code{rl_complete_internal()} with an argument of @samp{*}.
1528@end deftypefun
1529
1530@deftypefun int rl_completion_mode (rl_command_func_t *cfunc)
1531Returns the apppriate value to pass to @code{rl_complete_internal()}
1532depending on whether @var{cfunc} was called twice in succession and
1533the values of the @code{show-all-if-ambiguous} and
1534@code{show-all-if-unmodified} variables.
1535Application-specific completion functions may use this function to present
1536the same interface as @code{rl_complete()}.
1537@end deftypefun
1538
1539@deftypefun {char **} rl_completion_matches (const char *text, rl_compentry_func_t *entry_func)
1540Returns an array of strings which is a list of completions for
1541@var{text}. If there are no completions, returns @code{NULL}.
1542The first entry in the returned array is the substitution for @var{text}.
1543The remaining entries are the possible completions. The array is
1544terminated with a @code{NULL} pointer.
1545
1546@var{entry_func} is a function of two args, and returns a
1547@code{char *}. The first argument is @var{text}. The second is a
1548state argument; it is zero on the first call, and non-zero on subsequent
1549calls. @var{entry_func} returns a @code{NULL} pointer to the caller
1550when there are no more matches.
1551@end deftypefun
1552
1553@deftypefun {char *} rl_filename_completion_function (const char *text, int state)
1554A generator function for filename completion in the general case.
1555@var{text} is a partial filename.
1556The Bash source is a useful reference for writing application-specific
1557completion functions (the Bash completion functions call this and other
1558Readline functions).
1559@end deftypefun
1560
1561@deftypefun {char *} rl_username_completion_function (const char *text, int state)
1562A completion generator for usernames. @var{text} contains a partial
1563username preceded by a random character (usually @samp{~}). As with all
1564completion generators, @var{state} is zero on the first call and non-zero
1565for subsequent calls.
1566@end deftypefun
1567
1568@node Completion Variables
1569@subsection Completion Variables
1570
1571@deftypevar {rl_compentry_func_t *} rl_completion_entry_function
1572A pointer to the generator function for @code{rl_completion_matches()}.
1573@code{NULL} means to use @code{rl_filename_completion_function()},
1574the default filename completer.
1575@end deftypevar
1576
1577@deftypevar {rl_completion_func_t *} rl_attempted_completion_function
1578A pointer to an alternative function to create matches.
1579The function is called with @var{text}, @var{start}, and @var{end}.
1580@var{start} and @var{end} are indices in @code{rl_line_buffer} defining
1581the boundaries of @var{text}, which is a character string.
1582If this function exists and returns @code{NULL}, or if this variable is
1583set to @code{NULL}, then @code{rl_complete()} will call the value of
1584@code{rl_completion_entry_function} to generate matches, otherwise the
1585array of strings returned will be used.
1586If this function sets the @code{rl_attempted_completion_over}
1587variable to a non-zero value, Readline will not perform its default
1588completion even if this function returns no matches.
1589@end deftypevar
1590
1591@deftypevar {rl_quote_func_t *} rl_filename_quoting_function
1592A pointer to a function that will quote a filename in an
1593application-specific fashion. This is called if filename completion is being
1594attempted and one of the characters in @code{rl_filename_quote_characters}
1595appears in a completed filename. The function is called with
1596@var{text}, @var{match_type}, and @var{quote_pointer}. The @var{text}
1597is the filename to be quoted. The @var{match_type} is either
1598@code{SINGLE_MATCH}, if there is only one completion match, or
1599@code{MULT_MATCH}. Some functions use this to decide whether or not to
1600insert a closing quote character. The @var{quote_pointer} is a pointer
1601to any opening quote character the user typed. Some functions choose
1602to reset this character.
1603@end deftypevar
1604
1605@deftypevar {rl_dequote_func_t *} rl_filename_dequoting_function
1606A pointer to a function that will remove application-specific quoting
1607characters from a filename before completion is attempted, so those
1608characters do not interfere with matching the text against names in
1609the filesystem. It is called with @var{text}, the text of the word
1610to be dequoted, and @var{quote_char}, which is the quoting character
1611that delimits the filename (usually @samp{'} or @samp{"}). If
1612@var{quote_char} is zero, the filename was not in an embedded string.
1613@end deftypevar
1614
1615@deftypevar {rl_linebuf_func_t *} rl_char_is_quoted_p
1616A pointer to a function to call that determines whether or not a specific
1617character in the line buffer is quoted, according to whatever quoting
1618mechanism the program calling Readline uses. The function is called with
1619two arguments: @var{text}, the text of the line, and @var{index}, the
1620index of the character in the line. It is used to decide whether a
1621character found in @code{rl_completer_word_break_characters} should be
1622used to break words for the completer.
1623@end deftypevar
1624
1625@deftypevar {rl_compignore_func_t *} rl_ignore_some_completions_function
1626This function, if defined, is called by the completer when real filename
1627completion is done, after all the matching names have been generated.
1628It is passed a @code{NULL} terminated array of matches.
1629The first element (@code{matches[0]}) is the
1630maximal substring common to all matches. This function can
1631re-arrange the list of matches as required, but each element deleted
1632from the array must be freed.
1633@end deftypevar
1634
1635@deftypevar {rl_icppfunc_t *} rl_directory_completion_hook
1636This function, if defined, is allowed to modify the directory portion
1637of filenames Readline completes. It is called with the address of a
1638string (the current directory name) as an argument, and may modify that string.
1639If the string is replaced with a new string, the old value should be freed.
1640Any modified directory name should have a trailing slash.
1641The modified value will be displayed as part of the completion, replacing
1642the directory portion of the pathname the user typed.
1643It returns an integer that should be non-zero if the function modifies
1644its directory argument.
1645It could be used to expand symbolic links or shell variables in pathnames.
1646@end deftypevar
1647
1648@deftypevar {rl_compdisp_func_t *} rl_completion_display_matches_hook
1649If non-zero, then this is the address of a function to call when
1650completing a word would normally display the list of possible matches.
1651This function is called in lieu of Readline displaying the list.
1652It takes three arguments:
1653(@code{char **}@var{matches}, @code{int} @var{num_matches}, @code{int} @var{max_length})
1654where @var{matches} is the array of matching strings,
1655@var{num_matches} is the number of strings in that array, and
1656@var{max_length} is the length of the longest string in that array.
1657Readline provides a convenience function, @code{rl_display_match_list},
1658that takes care of doing the display to Readline's output stream. That
1659function may be called from this hook.
1660@end deftypevar
1661
1662@deftypevar {const char *} rl_basic_word_break_characters
1663The basic list of characters that signal a break between words for the
1664completer routine. The default value of this variable is the characters
1665which break words for completion in Bash:
1666@code{" \t\n\"\\'`@@$><=;|&@{("}.
1667@end deftypevar
1668
1669@deftypevar {const char *} rl_basic_quote_characters
1670A list of quote characters which can cause a word break.
1671@end deftypevar
1672
1673@deftypevar {const char *} rl_completer_word_break_characters
1674The list of characters that signal a break between words for
1675@code{rl_complete_internal()}. The default list is the value of
1676@code{rl_basic_word_break_characters}.
1677@end deftypevar
1678
1679@deftypevar {const char *} rl_completer_quote_characters
1680A list of characters which can be used to quote a substring of the line.
1681Completion occurs on the entire substring, and within the substring
1682@code{rl_completer_word_break_characters} are treated as any other character,
1683unless they also appear within this list.
1684@end deftypevar
1685
1686@deftypevar {const char *} rl_filename_quote_characters
1687A list of characters that cause a filename to be quoted by the completer
1688when they appear in a completed filename. The default is the null string.
1689@end deftypevar
1690
1691@deftypevar {const char *} rl_special_prefixes
1692The list of characters that are word break characters, but should be
1693left in @var{text} when it is passed to the completion function.
1694Programs can use this to help determine what kind of completing to do.
1695For instance, Bash sets this variable to "$@@" so that it can complete
1696shell variables and hostnames.
1697@end deftypevar
1698
1699@deftypevar int rl_completion_query_items
1700Up to this many items will be displayed in response to a
1701possible-completions call. After that, we ask the user if she is sure
1702she wants to see them all. The default value is 100.
1703@end deftypevar
1704
1705@deftypevar {int} rl_completion_append_character
1706When a single completion alternative matches at the end of the command
1707line, this character is appended to the inserted completion text. The
1708default is a space character (@samp{ }). Setting this to the null
1709character (@samp{\0}) prevents anything being appended automatically.
1710This can be changed in application-specific completion functions to
1711provide the ``most sensible word separator character'' according to
1712an application-specific command line syntax specification.
1713@end deftypevar
1714
1715@deftypevar int rl_completion_suppress_append
1716If non-zero, @var{rl_completion_append_character} is not appended to
5e13499c
CR
1717matches at the end of the command line, as described above.
1718It is set to 0 before any application-specific completion function
1719is called, and may only be changed within such a function.
1720@end deftypevar
1721
1722@deftypevar int rl_completion_quote_character
1723When Readline is completing quoted text, as delimited by one of the
1724characters in @var{rl_completer_quote_characters}, it sets this variable
1725to the quoting character found.
1726This is set before any application-specific completion function is called.
1727@end deftypevar
1728
1729@deftypevar int rl_completion_suppress_quote
1730If non-zero, Readline does not append a matching quote character when
1731performing completion on a quoted string.
1732It is set to 0 before any application-specific completion function
1733is called, and may only be changed within such a function.
d3a24ed2
CR
1734@end deftypevar
1735
545f34cf
CR
1736@deftypevar int rl_completion_found_quote
1737When Readline is completing quoted text, it sets this variable
1738to a non-zero value if the word being completed contains or is delimited
1739by any quoting characters, including backslashes.
1740This is set before any application-specific completion function is called.
1741@end deftypevar
1742
d3a24ed2
CR
1743@deftypevar int rl_completion_mark_symlink_dirs
1744If non-zero, a slash will be appended to completed filenames that are
1745symbolic links to directory names, subject to the value of the
1746user-settable @var{mark-directories} variable.
1747This variable exists so that application-specific completion functions
1748can override the user's global preference (set via the
1749@var{mark-symlinked-directories} Readline variable) if appropriate.
1750This variable is set to the user's preference before any
1751application-specific completion function is called, so unless that
1752function modifies the value, the user's preferences are honored.
1753@end deftypevar
1754
1755@deftypevar int rl_ignore_completion_duplicates
1756If non-zero, then duplicates in the matches are removed.
1757The default is 1.
1758@end deftypevar
1759
1760@deftypevar int rl_filename_completion_desired
1761Non-zero means that the results of the matches are to be treated as
1762filenames. This is @emph{always} zero when completion is attempted,
1763and can only be changed
1764within an application-specific completion function. If it is set to a
1765non-zero value by such a function, directory names have a slash appended
1766and Readline attempts to quote completed filenames if they contain any
1767characters in @code{rl_filename_quote_characters} and
1768@code{rl_filename_quoting_desired} is set to a non-zero value.
1769@end deftypevar
1770
1771@deftypevar int rl_filename_quoting_desired
1772Non-zero means that the results of the matches are to be quoted using
1773double quotes (or an application-specific quoting mechanism) if the
1774completed filename contains any characters in
1775@code{rl_filename_quote_chars}. This is @emph{always} non-zero
1776when completion is attempted, and can only be changed within an
1777application-specific completion function.
1778The quoting is effected via a call to the function pointed to
1779by @code{rl_filename_quoting_function}.
1780@end deftypevar
1781
1782@deftypevar int rl_attempted_completion_over
1783If an application-specific completion function assigned to
1784@code{rl_attempted_completion_function} sets this variable to a non-zero
1785value, Readline will not perform its default filename completion even
1786if the application's completion function returns no matches.
1787It should be set only by an application's completion function.
1788@end deftypevar
1789
1790@deftypevar int rl_completion_type
1791Set to a character describing the type of completion Readline is currently
1792attempting; see the description of @code{rl_complete_internal()}
1793(@pxref{Completion Functions}) for the list of characters.
1794This is set to the appropriate value before any application-specific
1795completion function is called, allowing such functions to present
1796the same interface as @code{rl_complete()}.
1797@end deftypevar
1798
1799@deftypevar int rl_inhibit_completion
1800If this variable is non-zero, completion is inhibited. The completion
1801character will be inserted as any other bound to @code{self-insert}.
1802@end deftypevar
1803
1804@node A Short Completion Example
1805@subsection A Short Completion Example
1806
1807Here is a small application demonstrating the use of the GNU Readline
1808library. It is called @code{fileman}, and the source code resides in
1809@file{examples/fileman.c}. This sample application provides
1810completion of command names, line editing features, and access to the
1811history list.
1812
1813@page
1814@smallexample
1815/* fileman.c -- A tiny application which demonstrates how to use the
1816 GNU Readline library. This application interactively allows users
1817 to manipulate files and their modes. */
1818
1819#include <stdio.h>
1820#include <sys/types.h>
1821#include <sys/file.h>
1822#include <sys/stat.h>
1823#include <sys/errno.h>
1824
1825#include <readline/readline.h>
1826#include <readline/history.h>
1827
1828extern char *xmalloc ();
1829
1830/* The names of functions that actually do the manipulation. */
1831int com_list __P((char *));
1832int com_view __P((char *));
1833int com_rename __P((char *));
1834int com_stat __P((char *));
1835int com_pwd __P((char *));
1836int com_delete __P((char *));
1837int com_help __P((char *));
1838int com_cd __P((char *));
1839int com_quit __P((char *));
1840
1841/* A structure which contains information on the commands this program
1842 can understand. */
1843
1844typedef struct @{
1845 char *name; /* User printable name of the function. */
1846 rl_icpfunc_t *func; /* Function to call to do the job. */
1847 char *doc; /* Documentation for this function. */
1848@} COMMAND;
1849
1850COMMAND commands[] = @{
1851 @{ "cd", com_cd, "Change to directory DIR" @},
1852 @{ "delete", com_delete, "Delete FILE" @},
1853 @{ "help", com_help, "Display this text" @},
1854 @{ "?", com_help, "Synonym for `help'" @},
1855 @{ "list", com_list, "List files in DIR" @},
1856 @{ "ls", com_list, "Synonym for `list'" @},
1857 @{ "pwd", com_pwd, "Print the current working directory" @},
1858 @{ "quit", com_quit, "Quit using Fileman" @},
1859 @{ "rename", com_rename, "Rename FILE to NEWNAME" @},
1860 @{ "stat", com_stat, "Print out statistics on FILE" @},
1861 @{ "view", com_view, "View the contents of FILE" @},
1862 @{ (char *)NULL, (rl_icpfunc_t *)NULL, (char *)NULL @}
1863@};
1864
1865/* Forward declarations. */
1866char *stripwhite ();
1867COMMAND *find_command ();
1868
1869/* The name of this program, as taken from argv[0]. */
1870char *progname;
1871
1872/* When non-zero, this means the user is done using this program. */
1873int done;
1874
1875char *
1876dupstr (s)
1877 int s;
1878@{
1879 char *r;
1880
1881 r = xmalloc (strlen (s) + 1);
1882 strcpy (r, s);
1883 return (r);
1884@}
1885
1886main (argc, argv)
1887 int argc;
1888 char **argv;
1889@{
1890 char *line, *s;
1891
1892 progname = argv[0];
1893
1894 initialize_readline (); /* Bind our completer. */
1895
1896 /* Loop reading and executing lines until the user quits. */
1897 for ( ; done == 0; )
1898 @{
1899 line = readline ("FileMan: ");
1900
1901 if (!line)
1902 break;
1903
1904 /* Remove leading and trailing whitespace from the line.
1905 Then, if there is anything left, add it to the history list
1906 and execute it. */
1907 s = stripwhite (line);
1908
1909 if (*s)
1910 @{
1911 add_history (s);
1912 execute_line (s);
1913 @}
1914
1915 free (line);
1916 @}
1917 exit (0);
1918@}
1919
1920/* Execute a command line. */
1921int
1922execute_line (line)
1923 char *line;
1924@{
1925 register int i;
1926 COMMAND *command;
1927 char *word;
1928
1929 /* Isolate the command word. */
1930 i = 0;
1931 while (line[i] && whitespace (line[i]))
1932 i++;
1933 word = line + i;
1934
1935 while (line[i] && !whitespace (line[i]))
1936 i++;
1937
1938 if (line[i])
1939 line[i++] = '\0';
1940
1941 command = find_command (word);
1942
1943 if (!command)
1944 @{
1945 fprintf (stderr, "%s: No such command for FileMan.\n", word);
1946 return (-1);
1947 @}
1948
1949 /* Get argument to command, if any. */
1950 while (whitespace (line[i]))
1951 i++;
1952
1953 word = line + i;
1954
1955 /* Call the function. */
1956 return ((*(command->func)) (word));
1957@}
1958
1959/* Look up NAME as the name of a command, and return a pointer to that
1960 command. Return a NULL pointer if NAME isn't a command name. */
1961COMMAND *
1962find_command (name)
1963 char *name;
1964@{
1965 register int i;
1966
1967 for (i = 0; commands[i].name; i++)
1968 if (strcmp (name, commands[i].name) == 0)
1969 return (&commands[i]);
1970
1971 return ((COMMAND *)NULL);
1972@}
1973
1974/* Strip whitespace from the start and end of STRING. Return a pointer
1975 into STRING. */
1976char *
1977stripwhite (string)
1978 char *string;
1979@{
1980 register char *s, *t;
1981
1982 for (s = string; whitespace (*s); s++)
1983 ;
1984
1985 if (*s == 0)
1986 return (s);
1987
1988 t = s + strlen (s) - 1;
1989 while (t > s && whitespace (*t))
1990 t--;
1991 *++t = '\0';
1992
1993 return s;
1994@}
1995
1996/* **************************************************************** */
1997/* */
1998/* Interface to Readline Completion */
1999/* */
2000/* **************************************************************** */
2001
2002char *command_generator __P((const char *, int));
2003char **fileman_completion __P((const char *, int, int));
2004
2005/* Tell the GNU Readline library how to complete. We want to try to
2006 complete on command names if this is the first word in the line, or
2007 on filenames if not. */
2008initialize_readline ()
2009@{
2010 /* Allow conditional parsing of the ~/.inputrc file. */
2011 rl_readline_name = "FileMan";
2012
2013 /* Tell the completer that we want a crack first. */
2014 rl_attempted_completion_function = fileman_completion;
2015@}
2016
2017/* Attempt to complete on the contents of TEXT. START and END
2018 bound the region of rl_line_buffer that contains the word to
2019 complete. TEXT is the word to complete. We can use the entire
2020 contents of rl_line_buffer in case we want to do some simple
2021 parsing. Returnthe array of matches, or NULL if there aren't any. */
2022char **
2023fileman_completion (text, start, end)
2024 const char *text;
2025 int start, end;
2026@{
2027 char **matches;
2028
2029 matches = (char **)NULL;
2030
2031 /* If this word is at the start of the line, then it is a command
2032 to complete. Otherwise it is the name of a file in the current
2033 directory. */
2034 if (start == 0)
2035 matches = rl_completion_matches (text, command_generator);
2036
2037 return (matches);
2038@}
2039
2040/* Generator function for command completion. STATE lets us
2041 know whether to start from scratch; without any state
2042 (i.e. STATE == 0), then we start at the top of the list. */
2043char *
2044command_generator (text, state)
2045 const char *text;
2046 int state;
2047@{
2048 static int list_index, len;
2049 char *name;
2050
2051 /* If this is a new word to complete, initialize now. This
2052 includes saving the length of TEXT for efficiency, and
2053 initializing the index variable to 0. */
2054 if (!state)
2055 @{
2056 list_index = 0;
2057 len = strlen (text);
2058 @}
2059
2060 /* Return the next name which partially matches from the
2061 command list. */
2062 while (name = commands[list_index].name)
2063 @{
2064 list_index++;
2065
2066 if (strncmp (name, text, len) == 0)
2067 return (dupstr(name));
2068 @}
2069
2070 /* If no names matched, then return NULL. */
2071 return ((char *)NULL);
2072@}
2073
2074/* **************************************************************** */
2075/* */
2076/* FileMan Commands */
2077/* */
2078/* **************************************************************** */
2079
2080/* String to pass to system (). This is for the LIST, VIEW and RENAME
2081 commands. */
2082static char syscom[1024];
2083
2084/* List the file(s) named in arg. */
2085com_list (arg)
2086 char *arg;
2087@{
2088 if (!arg)
2089 arg = "";
2090
2091 sprintf (syscom, "ls -FClg %s", arg);
2092 return (system (syscom));
2093@}
2094
2095com_view (arg)
2096 char *arg;
2097@{
2098 if (!valid_argument ("view", arg))
2099 return 1;
2100
2101 sprintf (syscom, "more %s", arg);
2102 return (system (syscom));
2103@}
2104
2105com_rename (arg)
2106 char *arg;
2107@{
2108 too_dangerous ("rename");
2109 return (1);
2110@}
2111
2112com_stat (arg)
2113 char *arg;
2114@{
2115 struct stat finfo;
2116
2117 if (!valid_argument ("stat", arg))
2118 return (1);
2119
2120 if (stat (arg, &finfo) == -1)
2121 @{
2122 perror (arg);
2123 return (1);
2124 @}
2125
2126 printf ("Statistics for `%s':\n", arg);
2127
2128 printf ("%s has %d link%s, and is %d byte%s in length.\n", arg,
2129 finfo.st_nlink,
2130 (finfo.st_nlink == 1) ? "" : "s",
2131 finfo.st_size,
2132 (finfo.st_size == 1) ? "" : "s");
2133 printf ("Inode Last Change at: %s", ctime (&finfo.st_ctime));
2134 printf (" Last access at: %s", ctime (&finfo.st_atime));
2135 printf (" Last modified at: %s", ctime (&finfo.st_mtime));
2136 return (0);
2137@}
2138
2139com_delete (arg)
2140 char *arg;
2141@{
2142 too_dangerous ("delete");
2143 return (1);
2144@}
2145
2146/* Print out help for ARG, or for all of the commands if ARG is
2147 not present. */
2148com_help (arg)
2149 char *arg;
2150@{
2151 register int i;
2152 int printed = 0;
2153
2154 for (i = 0; commands[i].name; i++)
2155 @{
2156 if (!*arg || (strcmp (arg, commands[i].name) == 0))
2157 @{
2158 printf ("%s\t\t%s.\n", commands[i].name, commands[i].doc);
2159 printed++;
2160 @}
2161 @}
2162
2163 if (!printed)
2164 @{
2165 printf ("No commands match `%s'. Possibilties are:\n", arg);
2166
2167 for (i = 0; commands[i].name; i++)
2168 @{
2169 /* Print in six columns. */
2170 if (printed == 6)
2171 @{
2172 printed = 0;
2173 printf ("\n");
2174 @}
2175
2176 printf ("%s\t", commands[i].name);
2177 printed++;
2178 @}
2179
2180 if (printed)
2181 printf ("\n");
2182 @}
2183 return (0);
2184@}
2185
2186/* Change to the directory ARG. */
2187com_cd (arg)
2188 char *arg;
2189@{
2190 if (chdir (arg) == -1)
2191 @{
2192 perror (arg);
2193 return 1;
2194 @}
2195
2196 com_pwd ("");
2197 return (0);
2198@}
2199
2200/* Print out the current working directory. */
2201com_pwd (ignore)
2202 char *ignore;
2203@{
2204 char dir[1024], *s;
2205
2206 s = getcwd (dir, sizeof(dir) - 1);
2207 if (s == 0)
2208 @{
2209 printf ("Error getting pwd: %s\n", dir);
2210 return 1;
2211 @}
2212
2213 printf ("Current directory is %s\n", dir);
2214 return 0;
2215@}
2216
2217/* The user wishes to quit using this program. Just set DONE
2218 non-zero. */
2219com_quit (arg)
2220 char *arg;
2221@{
2222 done = 1;
2223 return (0);
2224@}
2225
2226/* Function which tells you that you can't do this. */
2227too_dangerous (caller)
2228 char *caller;
2229@{
2230 fprintf (stderr,
2231 "%s: Too dangerous for me to distribute.\n"
2232 caller);
2233 fprintf (stderr, "Write it yourself.\n");
2234@}
2235
2236/* Return non-zero if ARG is a valid argument for CALLER,
2237 else print an error message and return zero. */
2238int
2239valid_argument (caller, arg)
2240 char *caller, *arg;
2241@{
2242 if (!arg || !*arg)
2243 @{
2244 fprintf (stderr, "%s: Argument required.\n", caller);
2245 return (0);
2246 @}
2247
2248 return (1);
2249@}
2250@end smallexample