This commit was generated by cvs2svn to track changes on a CVS vendor
[deliverable/binutils-gdb.git] / readline / doc / rltech.texinfo
CommitLineData
d60d9f65
SS
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
c862e87b 11Copyright (C) 1988, 1994, 1996, 1998, 1999 Free Software Foundation, Inc.
d60d9f65
SS
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 GNU Readline Library and
39other programs. If you are a programmer, and you wish to include the
40features found in 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
c862e87b
JM
50 aid in writing your own custom
51 functions.
52* Readline Signal Handling:: How Readline behaves when it receives signals.
d60d9f65
SS
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
68The function @code{readline ()} prints a prompt and then reads and returns
69a single line of text from the user. The line @code{readline}
70returns is allocated with @code{malloc ()}; you should @code{free ()}
71the line when you are done with it. The declaration for @code{readline}
72in ANSI C is
73
74@example
75@code{char *readline (char *@var{prompt});}
76@end example
77
78@noindent
79So, one might say
80@example
81@code{char *line = readline ("Enter a line: ");}
82@end example
83@noindent
84in order to read a line of text from the user.
85The line returned has the final newline removed, so only the
86text remains.
87
88If @code{readline} encounters an @code{EOF} while reading the line, and the
89line is empty at that point, then @code{(char *)NULL} is returned.
90Otherwise, the line is ended just as if a newline had been typed.
91
92If you want the user to be able to get at the line later, (with
93@key{C-p} for example), you must call @code{add_history ()} to save the
94line away in a @dfn{history} list of such lines.
95
96@example
97@code{add_history (line)};
98@end example
99
100@noindent
101For full details on the GNU History Library, see the associated manual.
102
103It is preferable to avoid saving empty lines on the history list, since
104users rarely have a burning need to reuse a blank line. Here is
105a function which usefully replaces the standard @code{gets ()} library
106function, and has the advantage of no static buffer to overflow:
107
108@example
109/* A static variable for holding the line. */
110static char *line_read = (char *)NULL;
111
112/* Read a string, and return a pointer to it. Returns NULL on EOF. */
113char *
114rl_gets ()
115@{
116 /* If the buffer has already been allocated, return the memory
117 to the free pool. */
118 if (line_read)
119 @{
120 free (line_read);
121 line_read = (char *)NULL;
122 @}
123
124 /* Get a line from the user. */
125 line_read = readline ("");
126
127 /* If the line has any text in it, save it on the history. */
128 if (line_read && *line_read)
129 add_history (line_read);
130
131 return (line_read);
132@}
133@end example
134
135This function gives the user the default behaviour of @key{TAB}
136completion: completion on file names. If you do not want Readline to
137complete on filenames, you can change the binding of the @key{TAB} key
138with @code{rl_bind_key ()}.
139
140@example
141@code{int rl_bind_key (int @var{key}, int (*@var{function})());}
142@end example
143
144@code{rl_bind_key ()} takes two arguments: @var{key} is the character that
145you want to bind, and @var{function} is the address of the function to
146call when @var{key} is pressed. Binding @key{TAB} to @code{rl_insert ()}
147makes @key{TAB} insert itself.
148@code{rl_bind_key ()} returns non-zero if @var{key} is not a valid
149ASCII character code (between 0 and 255).
150
151Thus, to disable the default @key{TAB} behavior, the following suffices:
152@example
153@code{rl_bind_key ('\t', rl_insert);}
154@end example
155
156This code should be executed once at the start of your program; you
157might write a function called @code{initialize_readline ()} which
158performs this and other desired initializations, such as installing
159custom completers (@pxref{Custom Completers}).
160
161@node Custom Functions
162@section Custom Functions
163
164Readline provides many functions for manipulating the text of
165the line, but it isn't possible to anticipate the needs of all
166programs. This section describes the various functions and variables
167defined within the Readline library which allow a user program to add
168customized functionality to Readline.
169
170@menu
171* The Function Type:: C declarations to make code readable.
172* Function Writing:: Variables and calling conventions.
173@end menu
174
175@node The Function Type
176@subsection The Function Type
177
178For readabilty, we declare a new type of object, called
179@dfn{Function}. A @code{Function} is a C function which
180returns an @code{int}. The type declaration for @code{Function} is:
181
182@noindent
183@code{typedef int Function ();}
184
185The reason for declaring this new type is to make it easier to write
186code describing pointers to C functions. Let us say we had a variable
187called @var{func} which was a pointer to a function. Instead of the
188classic C declaration
189
190@code{int (*)()func;}
191
192@noindent
193we may write
194
195@code{Function *func;}
196
197@noindent
198Similarly, there are
199
200@example
201typedef void VFunction ();
202typedef char *CPFunction (); @r{and}
203typedef char **CPPFunction ();
204@end example
205
206@noindent
207for functions returning no value, @code{pointer to char}, and
208@code{pointer to pointer to char}, respectively.
209
210@node Function Writing
211@subsection Writing a New Function
212
213In order to write new functions for Readline, you need to know the
214calling conventions for keyboard-invoked functions, and the names of the
215variables that describe the current state of the line read so far.
216
217The calling sequence for a command @code{foo} looks like
218
219@example
220@code{foo (int count, int key)}
221@end example
222
223@noindent
224where @var{count} is the numeric argument (or 1 if defaulted) and
225@var{key} is the key that invoked this function.
226
227It is completely up to the function as to what should be done with the
228numeric argument. Some functions use it as a repeat count, some
229as a flag, and others to choose alternate behavior (refreshing the current
230line as opposed to refreshing the screen, for example). Some choose to
231ignore it. In general, if a
232function uses the numeric argument as a repeat count, it should be able
233to do something useful with both negative and positive arguments.
234At the very least, it should be aware that it can be passed a
235negative argument.
236
237@node Readline Variables
238@section Readline Variables
239
240These variables are available to function writers.
241
242@deftypevar {char *} rl_line_buffer
243This is the line gathered so far. You are welcome to modify the
244contents of the line, but see @ref{Allowing Undoing}.
245@end deftypevar
246
247@deftypevar int rl_point
248The offset of the current cursor position in @code{rl_line_buffer}
249(the @emph{point}).
250@end deftypevar
251
252@deftypevar int rl_end
253The number of characters present in @code{rl_line_buffer}. When
254@code{rl_point} is at the end of the line, @code{rl_point} and
255@code{rl_end} are equal.
256@end deftypevar
257
258@deftypevar int rl_mark
259The mark (saved position) in the current line. If set, the mark
260and point define a @emph{region}.
261@end deftypevar
262
263@deftypevar int rl_done
264Setting this to a non-zero value causes Readline to return the current
265line immediately.
266@end deftypevar
267
268@deftypevar int rl_pending_input
269Setting this to a value makes it the next keystroke read. This is a
270way to stuff a single character into the input stream.
271@end deftypevar
272
c862e87b
JM
273@deftypevar int rl_erase_empty_line
274Setting this to a non-zero value causes Readline to completely erase
275the current line, including any prompt, any time a newline is typed as
276the only character on an otherwise-empty line. The cursor is moved to
277the beginning of the newly-blank line.
278@end deftypevar
279
d60d9f65
SS
280@deftypevar {char *} rl_prompt
281The prompt Readline uses. This is set from the argument to
282@code{readline ()}, and should not be assigned to directly.
283@end deftypevar
284
285@deftypevar {char *} rl_library_version
286The version number of this revision of the library.
287@end deftypevar
288
289@deftypevar {char *} rl_terminal_name
290The terminal type, used for initialization.
291@end deftypevar
292
293@deftypevar {char *} rl_readline_name
294This variable is set to a unique name by each application using Readline.
295The value allows conditional parsing of the inputrc file
296(@pxref{Conditional Init Constructs}).
297@end deftypevar
298
299@deftypevar {FILE *} rl_instream
300The stdio stream from which Readline reads input.
301@end deftypevar
302
303@deftypevar {FILE *} rl_outstream
304The stdio stream to which Readline performs output.
305@end deftypevar
306
307@deftypevar {Function *} rl_startup_hook
308If non-zero, this is the address of a function to call just
309before @code{readline} prints the first prompt.
310@end deftypevar
311
c862e87b
JM
312@deftypevar {Function *} rl_pre_input_hook
313If non-zero, this is the address of a function to call after
314the first prompt has been printed and just before @code{readline}
315starts reading input characters.
316@end deftypevar
317
d60d9f65
SS
318@deftypevar {Function *} rl_event_hook
319If non-zero, this is the address of a function to call periodically
320when readline is waiting for terminal input.
321@end deftypevar
322
323@deftypevar {Function *} rl_getc_function
324If non-zero, @code{readline} will call indirectly through this pointer
325to get a character from the input stream. By default, it is set to
326@code{rl_getc}, the default @code{readline} character input function
327(@pxref{Utility Functions}).
328@end deftypevar
329
330@deftypevar {VFunction *} rl_redisplay_function
331If non-zero, @code{readline} will call indirectly through this pointer
332to update the display with the current contents of the editing buffer.
333By default, it is set to @code{rl_redisplay}, the default @code{readline}
334redisplay function (@pxref{Redisplay}).
335@end deftypevar
336
337@deftypevar {Keymap} rl_executing_keymap
338This variable is set to the keymap (@pxref{Keymaps}) in which the
339currently executing readline function was found.
340@end deftypevar
341
342@deftypevar {Keymap} rl_binding_keymap
343This variable is set to the keymap (@pxref{Keymaps}) in which the
344last key binding occurred.
345@end deftypevar
346
347@node Readline Convenience Functions
348@section Readline Convenience Functions
349
350@menu
351* Function Naming:: How to give a function you write a name.
352* Keymaps:: Making keymaps.
353* Binding Keys:: Changing Keymaps.
354* Associating Function Names and Bindings:: Translate function names to
355 key sequences.
356* Allowing Undoing:: How to make your functions undoable.
357* Redisplay:: Functions to control line display.
358* Modifying Text:: Functions to modify @code{rl_line_buffer}.
359* Utility Functions:: Generally useful functions and hooks.
360* Alternate Interface:: Using Readline in a `callback' fashion.
361@end menu
362
363@node Function Naming
364@subsection Naming a Function
365
366The user can dynamically change the bindings of keys while using
367Readline. This is done by representing the function with a descriptive
368name. The user is able to type the descriptive name when referring to
369the function. Thus, in an init file, one might find
370
371@example
372Meta-Rubout: backward-kill-word
373@end example
374
375This binds the keystroke @key{Meta-Rubout} to the function
376@emph{descriptively} named @code{backward-kill-word}. You, as the
377programmer, should bind the functions you write to descriptive names as
378well. Readline provides a function for doing that:
379
380@deftypefun int rl_add_defun (char *name, Function *function, int key)
381Add @var{name} to the list of named functions. Make @var{function} be
382the function that gets called. If @var{key} is not -1, then bind it to
383@var{function} using @code{rl_bind_key ()}.
384@end deftypefun
385
386Using this function alone is sufficient for most applications. It is
387the recommended way to add a few functions to the default functions that
388Readline has built in. If you need to do something other
389than adding a function to Readline, you may need to use the
390underlying functions described below.
391
392@node Keymaps
393@subsection Selecting a Keymap
394
395Key bindings take place on a @dfn{keymap}. The keymap is the
396association between the keys that the user types and the functions that
397get run. You can make your own keymaps, copy existing keymaps, and tell
398Readline which keymap to use.
399
400@deftypefun Keymap rl_make_bare_keymap ()
401Returns a new, empty keymap. The space for the keymap is allocated with
402@code{malloc ()}; you should @code{free ()} it when you are done.
403@end deftypefun
404
405@deftypefun Keymap rl_copy_keymap (Keymap map)
406Return a new keymap which is a copy of @var{map}.
407@end deftypefun
408
409@deftypefun Keymap rl_make_keymap ()
410Return a new keymap with the printing characters bound to rl_insert,
411the lowercase Meta characters bound to run their equivalents, and
412the Meta digits bound to produce numeric arguments.
413@end deftypefun
414
415@deftypefun void rl_discard_keymap (Keymap keymap)
416Free the storage associated with @var{keymap}.
417@end deftypefun
418
419Readline has several internal keymaps. These functions allow you to
420change which keymap is active.
421
422@deftypefun Keymap rl_get_keymap ()
423Returns the currently active keymap.
424@end deftypefun
425
426@deftypefun void rl_set_keymap (Keymap keymap)
427Makes @var{keymap} the currently active keymap.
428@end deftypefun
429
430@deftypefun Keymap rl_get_keymap_by_name (char *name)
431Return the keymap matching @var{name}. @var{name} is one which would
432be supplied in a @code{set keymap} inputrc line (@pxref{Readline Init File}).
433@end deftypefun
434
435@deftypefun {char *} rl_get_keymap_name (Keymap keymap)
436Return the name matching @var{keymap}. @var{name} is one which would
437be supplied in a @code{set keymap} inputrc line (@pxref{Readline Init File}).
438@end deftypefun
439
440@node Binding Keys
441@subsection Binding Keys
442
443You associate keys with functions through the keymap. Readline has
444several internal keymaps: @code{emacs_standard_keymap},
445@code{emacs_meta_keymap}, @code{emacs_ctlx_keymap},
446@code{vi_movement_keymap}, and @code{vi_insertion_keymap}.
447@code{emacs_standard_keymap} is the default, and the examples in
448this manual assume that.
449
450These functions manage key bindings.
451
452@deftypefun int rl_bind_key (int key, Function *function)
453Binds @var{key} to @var{function} in the currently active keymap.
454Returns non-zero in the case of an invalid @var{key}.
455@end deftypefun
456
457@deftypefun int rl_bind_key_in_map (int key, Function *function, Keymap map)
458Bind @var{key} to @var{function} in @var{map}. Returns non-zero in the case
459of an invalid @var{key}.
460@end deftypefun
461
462@deftypefun int rl_unbind_key (int key)
463Bind @var{key} to the null function in the currently active keymap.
464Returns non-zero in case of error.
465@end deftypefun
466
467@deftypefun int rl_unbind_key_in_map (int key, Keymap map)
468Bind @var{key} to the null function in @var{map}.
469Returns non-zero in case of error.
470@end deftypefun
471
472@deftypefun int rl_unbind_function_in_map (Function *function, Keymap map)
473Unbind all keys that execute @var{function} in @var{map}.
474@end deftypefun
475
476@deftypefun int rl_unbind_command_in_map (char *command, Keymap map)
477Unbind all keys that are bound to @var{command} in @var{map}.
478@end deftypefun
479
480@deftypefun int rl_generic_bind (int type, char *keyseq, char *data, Keymap map)
481Bind the key sequence represented by the string @var{keyseq} to the arbitrary
482pointer @var{data}. @var{type} says what kind of data is pointed to by
483@var{data}; this can be a function (@code{ISFUNC}), a macro
484(@code{ISMACR}), or a keymap (@code{ISKMAP}). This makes new keymaps as
485necessary. The initial keymap in which to do bindings is @var{map}.
486@end deftypefun
487
488@deftypefun int rl_parse_and_bind (char *line)
489Parse @var{line} as if it had been read from the @code{inputrc} file and
490perform any key bindings and variable assignments found
491(@pxref{Readline Init File}).
492@end deftypefun
493
494@deftypefun int rl_read_init_file (char *filename)
495Read keybindings and variable assignments from @var{filename}
496(@pxref{Readline Init File}).
497@end deftypefun
498
499@node Associating Function Names and Bindings
500@subsection Associating Function Names and Bindings
501
502These functions allow you to find out what keys invoke named functions
503and the functions invoked by a particular key sequence.
504
505@deftypefun {Function *} rl_named_function (char *name)
506Return the function with name @var{name}.
507@end deftypefun
508
509@deftypefun {Function *} rl_function_of_keyseq (char *keyseq, Keymap map, int *type)
510Return the function invoked by @var{keyseq} in keymap @var{map}.
511If @var{map} is NULL, the current keymap is used. If @var{type} is
512not NULL, the type of the object is returned in it (one of @code{ISFUNC},
513@code{ISKMAP}, or @code{ISMACR}).
514@end deftypefun
515
516@deftypefun {char **} rl_invoking_keyseqs (Function *function)
517Return an array of strings representing the key sequences used to
518invoke @var{function} in the current keymap.
519@end deftypefun
520
521@deftypefun {char **} rl_invoking_keyseqs_in_map (Function *function, Keymap map)
522Return an array of strings representing the key sequences used to
523invoke @var{function} in the keymap @var{map}.
524@end deftypefun
525
526@deftypefun void rl_function_dumper (int readable)
527Print the readline function names and the key sequences currently
528bound to them to @code{rl_outstream}. If @var{readable} is non-zero,
529the list is formatted in such a way that it can be made part of an
530@code{inputrc} file and re-read.
531@end deftypefun
532
533@deftypefun void rl_list_funmap_names ()
534Print the names of all bindable Readline functions to @code{rl_outstream}.
535@end deftypefun
536
537@node Allowing Undoing
538@subsection Allowing Undoing
539
540Supporting the undo command is a painless thing, and makes your
541functions much more useful. It is certainly easy to try
542something if you know you can undo it. I could use an undo function for
543the stock market.
544
545If your function simply inserts text once, or deletes text once, and
546uses @code{rl_insert_text ()} or @code{rl_delete_text ()} to do it, then
547undoing is already done for you automatically.
548
549If you do multiple insertions or multiple deletions, or any combination
550of these operations, you should group them together into one operation.
551This is done with @code{rl_begin_undo_group ()} and
552@code{rl_end_undo_group ()}.
553
554The types of events that can be undone are:
555
556@example
557enum undo_code @{ UNDO_DELETE, UNDO_INSERT, UNDO_BEGIN, UNDO_END @};
558@end example
559
560Notice that @code{UNDO_DELETE} means to insert some text, and
561@code{UNDO_INSERT} means to delete some text. That is, the undo code
562tells undo what to undo, not how to undo it. @code{UNDO_BEGIN} and
563@code{UNDO_END} are tags added by @code{rl_begin_undo_group ()} and
564@code{rl_end_undo_group ()}.
565
566@deftypefun int rl_begin_undo_group ()
567Begins saving undo information in a group construct. The undo
568information usually comes from calls to @code{rl_insert_text ()} and
569@code{rl_delete_text ()}, but could be the result of calls to
570@code{rl_add_undo ()}.
571@end deftypefun
572
573@deftypefun int rl_end_undo_group ()
574Closes the current undo group started with @code{rl_begin_undo_group
575()}. There should be one call to @code{rl_end_undo_group ()}
576for each call to @code{rl_begin_undo_group ()}.
577@end deftypefun
578
579@deftypefun void rl_add_undo (enum undo_code what, int start, int end, char *text)
580Remember how to undo an event (according to @var{what}). The affected
581text runs from @var{start} to @var{end}, and encompasses @var{text}.
582@end deftypefun
583
584@deftypefun void free_undo_list ()
585Free the existing undo list.
586@end deftypefun
587
588@deftypefun int rl_do_undo ()
589Undo the first thing on the undo list. Returns @code{0} if there was
590nothing to undo, non-zero if something was undone.
591@end deftypefun
592
593Finally, if you neither insert nor delete text, but directly modify the
594existing text (e.g., change its case), call @code{rl_modifying ()}
595once, just before you modify the text. You must supply the indices of
596the text range that you are going to modify.
597
598@deftypefun int rl_modifying (int start, int end)
599Tell Readline to save the text between @var{start} and @var{end} as a
600single undo unit. It is assumed that you will subsequently modify
601that text.
602@end deftypefun
603
604@node Redisplay
605@subsection Redisplay
606
607@deftypefun void rl_redisplay ()
608Change what's displayed on the screen to reflect the current contents
609of @code{rl_line_buffer}.
610@end deftypefun
611
612@deftypefun int rl_forced_update_display ()
613Force the line to be updated and redisplayed, whether or not
614Readline thinks the screen display is correct.
615@end deftypefun
616
617@deftypefun int rl_on_new_line ()
618Tell the update routines that we have moved onto a new (empty) line,
619usually after ouputting a newline.
620@end deftypefun
621
622@deftypefun int rl_reset_line_state ()
623Reset the display state to a clean state and redisplay the current line
624starting on a new line.
625@end deftypefun
626
627@deftypefun int rl_message (va_alist)
628The arguments are a string as would be supplied to @code{printf}. The
629resulting string is displayed in the @dfn{echo area}. The echo area
630is also used to display numeric arguments and search strings.
631@end deftypefun
632
633@deftypefun int rl_clear_message ()
634Clear the message in the echo area.
635@end deftypefun
636
c862e87b
JM
637@deftypefun void rl_save_prompt ()
638Save the local Readline prompt display state in preparation for
639displaying a new message in the message area with @code{rl_message}.
640@end deftypefun
641
642@deftypefun void rl_restore_prompt ()
643Restore the local Readline prompt display state saved by the most
644recent call to @code{rl_save_prompt}.
645@end deftypefun
646
d60d9f65
SS
647@node Modifying Text
648@subsection Modifying Text
649
650@deftypefun int rl_insert_text (char *text)
651Insert @var{text} into the line at the current cursor position.
652@end deftypefun
653
654@deftypefun int rl_delete_text (int start, int end)
655Delete the text between @var{start} and @var{end} in the current line.
656@end deftypefun
657
658@deftypefun {char *} rl_copy_text (int start, int end)
659Return a copy of the text between @var{start} and @var{end} in
660the current line.
661@end deftypefun
662
663@deftypefun int rl_kill_text (int start, int end)
664Copy the text between @var{start} and @var{end} in the current line
665to the kill ring, appending or prepending to the last kill if the
666last command was a kill command. The text is deleted.
667If @var{start} is less than @var{end},
668the text is appended, otherwise prepended. If the last command was
669not a kill, a new kill ring slot is used.
670@end deftypefun
671
672@node Utility Functions
673@subsection Utility Functions
674
675@deftypefun int rl_read_key ()
676Return the next character available. This handles input inserted into
677the input stream via @var{pending input} (@pxref{Readline Variables})
678and @code{rl_stuff_char ()}, macros, and characters read from the keyboard.
679@end deftypefun
680
681@deftypefun int rl_getc (FILE *)
682Return the next character available from the keyboard.
683@end deftypefun
684
685@deftypefun int rl_stuff_char (int c)
686Insert @var{c} into the Readline input stream. It will be "read"
687before Readline attempts to read characters from the terminal with
688@code{rl_read_key ()}.
689@end deftypefun
690
691@deftypefun rl_extend_line_buffer (int len)
692Ensure that @code{rl_line_buffer} has enough space to hold @var{len}
693characters, possibly reallocating it if necessary.
694@end deftypefun
695
696@deftypefun int rl_initialize ()
697Initialize or re-initialize Readline's internal state.
698@end deftypefun
699
700@deftypefun int rl_reset_terminal (char *terminal_name)
701Reinitialize Readline's idea of the terminal settings using
702@var{terminal_name} as the terminal type (e.g., @code{vt100}).
703@end deftypefun
704
705@deftypefun int alphabetic (int c)
706Return 1 if @var{c} is an alphabetic character.
707@end deftypefun
708
709@deftypefun int numeric (int c)
710Return 1 if @var{c} is a numeric character.
711@end deftypefun
712
713@deftypefun int ding ()
714Ring the terminal bell, obeying the setting of @code{bell-style}.
715@end deftypefun
716
c862e87b
JM
717@deftypefun void rl_display_match_list (char **matches, int len, int max)
718A convenience function for displaying a list of strings in
719columnar format on Readline's output stream. @code{matches} is the list
720of strings, in argv format, such as a list of completion matches.
721@code{len} is the number of strings in @code{matches}, and @code{max}
722is the length of the longest string in @code{matches}. This function uses
723the setting of @code{print-completions-horizontally} to select how the
724matches are displayed (@pxref{Readline Init File Syntax}).
725@end deftypefun
726
d60d9f65
SS
727The following are implemented as macros, defined in @code{chartypes.h}.
728
729@deftypefun int uppercase_p (int c)
730Return 1 if @var{c} is an uppercase alphabetic character.
731@end deftypefun
732
733@deftypefun int lowercase_p (int c)
734Return 1 if @var{c} is a lowercase alphabetic character.
735@end deftypefun
736
737@deftypefun int digit_p (int c)
738Return 1 if @var{c} is a numeric character.
739@end deftypefun
740
741@deftypefun int to_upper (int c)
742If @var{c} is a lowercase alphabetic character, return the corresponding
743uppercase character.
744@end deftypefun
745
746@deftypefun int to_lower (int c)
747If @var{c} is an uppercase alphabetic character, return the corresponding
748lowercase character.
749@end deftypefun
750
751@deftypefun int digit_value (int c)
752If @var{c} is a number, return the value it represents.
753@end deftypefun
754
755@node Alternate Interface
756@subsection Alternate Interface
757
758An alternate interface is available to plain @code{readline()}. Some
759applications need to interleave keyboard I/O with file, device, or
760window system I/O, typically by using a main loop to @code{select()}
761on various file descriptors. To accomodate this need, readline can
762also be invoked as a `callback' function from an event loop. There
763are functions available to make this easy.
764
765@deftypefun void rl_callback_handler_install (char *prompt, Vfunction *lhandler)
766Set up the terminal for readline I/O and display the initial
767expanded value of @var{prompt}. Save the value of @var{lhandler} to
768use as a callback when a complete line of input has been entered.
769@end deftypefun
770
771@deftypefun void rl_callback_read_char ()
772Whenever an application determines that keyboard input is available, it
773should call @code{rl_callback_read_char()}, which will read the next
774character from the current input source. If that character completes the
775line, @code{rl_callback_read_char} will invoke the @var{lhandler}
776function saved by @code{rl_callback_handler_install} to process the
777line. @code{EOF} is indicated by calling @var{lhandler} with a
778@code{NULL} line.
779@end deftypefun
780
781@deftypefun void rl_callback_handler_remove ()
782Restore the terminal to its initial state and remove the line handler.
783This may be called from within a callback as well as independently.
784@end deftypefun
785
786@subsection An Example
787
788Here is a function which changes lowercase characters to their uppercase
789equivalents, and uppercase characters to lowercase. If
790this function was bound to @samp{M-c}, then typing @samp{M-c} would
791change the case of the character under point. Typing @samp{M-1 0 M-c}
792would change the case of the following 10 characters, leaving the cursor on
793the last character changed.
794
795@example
796/* Invert the case of the COUNT following characters. */
797int
798invert_case_line (count, key)
799 int count, key;
800@{
801 register int start, end, i;
802
803 start = rl_point;
804
805 if (rl_point >= rl_end)
806 return (0);
807
808 if (count < 0)
809 @{
810 direction = -1;
811 count = -count;
812 @}
813 else
814 direction = 1;
815
816 /* Find the end of the range to modify. */
817 end = start + (count * direction);
818
819 /* Force it to be within range. */
820 if (end > rl_end)
821 end = rl_end;
822 else if (end < 0)
823 end = 0;
824
825 if (start == end)
826 return (0);
827
828 if (start > end)
829 @{
830 int temp = start;
831 start = end;
832 end = temp;
833 @}
834
835 /* Tell readline that we are modifying the line, so it will save
836 the undo information. */
837 rl_modifying (start, end);
838
839 for (i = start; i != end; i++)
840 @{
841 if (uppercase_p (rl_line_buffer[i]))
842 rl_line_buffer[i] = to_lower (rl_line_buffer[i]);
843 else if (lowercase_p (rl_line_buffer[i]))
844 rl_line_buffer[i] = to_upper (rl_line_buffer[i]);
845 @}
846 /* Move point to on top of the last character changed. */
847 rl_point = (direction == 1) ? end - 1 : start;
848 return (0);
849@}
850@end example
851
c862e87b
JM
852@node Readline Signal Handling
853@section Readline Signal Handling
854
855Signals are asynchronous events sent to a process by the Unix kernel,
856sometimes on behalf of another process. They are intended to indicate
857exceptional events, like a user pressing the interrupt key on his
858terminal, or a network connection being broken. There is a class of
859signals that can be sent to the process currently reading input from
860the keyboard. Since Readline changes the terminal attributes when it
861is called, it needs to perform special processing when a signal is
862received to restore the terminal to a sane state, or provide application
863writers with functions to do so manually.
864
865Readline contains an internal signal handler that is installed for a
866number of signals (@code{SIGINT}, @code{SIGQUIT}, @code{SIGTERM},
867@code{SIGALRM}, @code{SIGTSTP}, @code{SIGTTIN}, and @code{SIGTTOU}).
868When one of these signals is received, the signal handler
869will reset the terminal attributes to those that were in effect before
870@code{readline ()} was called, reset the signal handling to what it was
871before @code{readline ()} was called, and resend the signal to the calling
872application.
873If and when the calling application's signal handler returns, Readline
874will reinitialize the terminal and continue to accept input.
875When a @code{SIGINT} is received, the Readline signal handler performs
876some additional work, which will cause any partially-entered line to be
877aborted (see the description of @code{rl_free_line_state ()}).
878
879There is an additional Readline signal handler, for @code{SIGWINCH}, which
880the kernel sends to a process whenever the terminal's size changes (for
881example, if a user resizes an @code{xterm}). The Readline @code{SIGWINCH}
882handler updates Readline's internal screen size state, and then calls any
883@code{SIGWINCH} signal handler the calling application has installed.
884Readline calls the application's @code{SIGWINCH} signal handler without
885resetting the terminal to its original state. If the application's signal
886handler does more than update its idea of the terminal size and return (for
887example, a @code{longjmp} back to a main processing loop), it @emph{must}
888call @code{rl_cleanup_after_signal ()} (described below), to restore the
889terminal state.
890
891Readline provides two variables that allow application writers to
892control whether or not it will catch certain signals and act on them
893when they are received. It is important that applications change the
894values of these variables only when calling @code{readline ()}, not in
895a signal handler, so Readline's internal signal state is not corrupted.
896
897@deftypevar int rl_catch_signals
898If this variable is non-zero, Readline will install signal handlers for
899@code{SIGINT}, @code{SIGQUIT}, @code{SIGTERM}, @code{SIGALRM},
900@code{SIGTSTP}, @code{SIGTTIN}, and @code{SIGTTOU}.
901
902The default value of @code{rl_catch_signals} is 1.
903@end deftypevar
904
905@deftypevar int rl_catch_sigwinch
906If this variable is non-zero, Readline will install a signal handler for
907@code{SIGWINCH}.
908
909The default value of @code{rl_catch_sigwinch} is 1.
910@end deftypevar
911
912If an application does not wish to have Readline catch any signals, or
913to handle signals other than those Readline catches (@code{SIGHUP},
914for example),
915Readline provides convenience functions to do the necessary terminal
916and internal state cleanup upon receipt of a signal.
917
918@deftypefun void rl_cleanup_after_signal (void)
919This function will reset the state of the terminal to what it was before
920@code{readline ()} was called, and remove the Readline signal handlers for
921all signals, depending on the values of @code{rl_catch_signals} and
922@code{rl_catch_sigwinch}.
923@end deftypefun
924
925@deftypefun void rl_free_line_state (void)
926This will free any partial state associated with the current input line
927(undo information, any partial history entry, any partially-entered
928keyboard macro, and any partially-entered numeric argument). This
929should be called before @code{rl_cleanup_after_signal ()}. The
930Readline signal handler for @code{SIGINT} calls this to abort the
931current input line.
932@end deftypefun
933
934@deftypefun void rl_reset_after_signal (void)
935This will reinitialize the terminal and reinstall any Readline signal
936handlers, depending on the values of @code{rl_catch_signals} and
937@code{rl_catch_sigwinch}.
938@end deftypefun
939
940If an application does not wish Readline to catch @code{SIGWINCH}, it may
941call @code{rl_resize_terminal ()} to force Readline to update its idea of
942the terminal size when a @code{SIGWINCH} is received.
943
944@deftypefun void rl_resize_terminal (void)
945Update Readline's internal screen size.
946@end deftypefun
947
948The following functions install and remove Readline's signal handlers.
949
950@deftypefun int rl_set_signals (void)
951Install Readline's signal handler for @code{SIGINT}, @code{SIGQUIT},
952@code{SIGTERM}, @code{SIGALRM}, @code{SIGTSTP}, @code{SIGTTIN},
953@code{SIGTTOU}, and @code{SIGWINCH}, depending on the values of
954@code{rl_catch_signals} and @code{rl_catch_sigwinch}.
955@end deftypefun
956
957@deftypefun int rl_clear_signals (void)
958Remove all of the Readline signal handlers installed by
959@code{rl_set_signals ()}.
960@end deftypefun
961
d60d9f65
SS
962@node Custom Completers
963@section Custom Completers
964
965Typically, a program that reads commands from the user has a way of
966disambiguating commands and data. If your program is one of these, then
967it can provide completion for commands, data, or both.
968The following sections describe how your program and Readline
969cooperate to provide this service.
970
971@menu
972* How Completing Works:: The logic used to do completion.
973* Completion Functions:: Functions provided by Readline.
974* Completion Variables:: Variables which control completion.
975* A Short Completion Example:: An example of writing completer subroutines.
976@end menu
977
978@node How Completing Works
979@subsection How Completing Works
980
981In order to complete some text, the full list of possible completions
982must be available. That is, it is not possible to accurately
983expand a partial word without knowing all of the possible words
984which make sense in that context. The Readline library provides
985the user interface to completion, and two of the most common
986completion functions: filename and username. For completing other types
987of text, you must write your own completion function. This section
988describes exactly what such functions must do, and provides an example.
989
990There are three major functions used to perform completion:
991
992@enumerate
993@item
994The user-interface function @code{rl_complete ()}. This function is
995called with the same arguments as other Readline
996functions intended for interactive use: @var{count} and
997@var{invoking_key}. It isolates the word to be completed and calls
998@code{completion_matches ()} to generate a list of possible completions.
999It then either lists the possible completions, inserts the possible
1000completions, or actually performs the
1001completion, depending on which behavior is desired.
1002
1003@item
1004The internal function @code{completion_matches ()} uses your
1005@dfn{generator} function to generate the list of possible matches, and
1006then returns the array of these matches. You should place the address
1007of your generator function in @code{rl_completion_entry_function}.
1008
1009@item
1010The generator function is called repeatedly from
1011@code{completion_matches ()}, returning a string each time. The
1012arguments to the generator function are @var{text} and @var{state}.
1013@var{text} is the partial word to be completed. @var{state} is zero the
1014first time the function is called, allowing the generator to perform
1015any necessary initialization, and a positive non-zero integer for
1016each subsequent call. When the generator function returns
1017@code{(char *)NULL} this signals @code{completion_matches ()} that there are
1018no more possibilities left. Usually the generator function computes the
1019list of possible completions when @var{state} is zero, and returns them
1020one at a time on subsequent calls. Each string the generator function
1021returns as a match must be allocated with @code{malloc()}; Readline
1022frees the strings when it has finished with them.
1023
1024@end enumerate
1025
1026@deftypefun int rl_complete (int ignore, int invoking_key)
1027Complete the word at or before point. You have supplied the function
1028that does the initial simple matching selection algorithm (see
1029@code{completion_matches ()}). The default is to do filename completion.
1030@end deftypefun
1031
1032@deftypevar {Function *} rl_completion_entry_function
1033This is a pointer to the generator function for @code{completion_matches
1034()}. If the value of @code{rl_completion_entry_function} is
1035@code{(Function *)NULL} then the default filename generator function,
1036@code{filename_completion_function ()}, is used.
1037@end deftypevar
1038
1039@node Completion Functions
1040@subsection Completion Functions
1041
1042Here is the complete list of callable completion functions present in
1043Readline.
1044
1045@deftypefun int rl_complete_internal (int what_to_do)
1046Complete the word at or before point. @var{what_to_do} says what to do
1047with the completion. A value of @samp{?} means list the possible
1048completions. @samp{TAB} means do standard completion. @samp{*} means
1049insert all of the possible completions. @samp{!} means to display
1050all of the possible completions, if there is more than one, as well as
1051performing partial completion.
1052@end deftypefun
1053
1054@deftypefun int rl_complete (int ignore, int invoking_key)
1055Complete the word at or before point. You have supplied the function
1056that does the initial simple matching selection algorithm (see
1057@code{completion_matches ()} and @code{rl_completion_entry_function}).
1058The default is to do filename
1059completion. This calls @code{rl_complete_internal ()} with an
1060argument depending on @var{invoking_key}.
1061@end deftypefun
1062
1063@deftypefun int rl_possible_completions (int count, int invoking_key))
1064List the possible completions. See description of @code{rl_complete
1065()}. This calls @code{rl_complete_internal ()} with an argument of
1066@samp{?}.
1067@end deftypefun
1068
1069@deftypefun int rl_insert_completions (int count, int invoking_key))
1070Insert the list of possible completions into the line, deleting the
1071partially-completed word. See description of @code{rl_complete ()}.
1072This calls @code{rl_complete_internal ()} with an argument of @samp{*}.
1073@end deftypefun
1074
1075@deftypefun {char **} completion_matches (char *text, CPFunction *entry_func)
1076Returns an array of @code{(char *)} which is a list of completions for
1077@var{text}. If there are no completions, returns @code{(char **)NULL}.
1078The first entry in the returned array is the substitution for @var{text}.
1079The remaining entries are the possible completions. The array is
1080terminated with a @code{NULL} pointer.
1081
1082@var{entry_func} is a function of two args, and returns a
1083@code{(char *)}. The first argument is @var{text}. The second is a
1084state argument; it is zero on the first call, and non-zero on subsequent
1085calls. @var{entry_func} returns a @code{NULL} pointer to the caller
1086when there are no more matches.
1087@end deftypefun
1088
1089@deftypefun {char *} filename_completion_function (char *text, int state)
1090A generator function for filename completion in the general case. Note
1091that completion in Bash is a little different because of all
1092the pathnames that must be followed when looking up completions for a
1093command. The Bash source is a useful reference for writing custom
1094completion functions.
1095@end deftypefun
1096
1097@deftypefun {char *} username_completion_function (char *text, int state)
1098A completion generator for usernames. @var{text} contains a partial
1099username preceded by a random character (usually @samp{~}). As with all
1100completion generators, @var{state} is zero on the first call and non-zero
1101for subsequent calls.
1102@end deftypefun
1103
1104@node Completion Variables
1105@subsection Completion Variables
1106
1107@deftypevar {Function *} rl_completion_entry_function
1108A pointer to the generator function for @code{completion_matches ()}.
1109@code{NULL} means to use @code{filename_entry_function ()}, the default
1110filename completer.
1111@end deftypevar
1112
1113@deftypevar {CPPFunction *} rl_attempted_completion_function
1114A pointer to an alternative function to create matches.
1115The function is called with @var{text}, @var{start}, and @var{end}.
1116@var{start} and @var{end} are indices in @code{rl_line_buffer} saying
1117what the boundaries of @var{text} are. If this function exists and
1118returns @code{NULL}, or if this variable is set to @code{NULL}, then
1119@code{rl_complete ()} will call the value of
1120@code{rl_completion_entry_function} to generate matches, otherwise the
1121array of strings returned will be used.
1122@end deftypevar
1123
1124@deftypevar {CPFunction *} rl_filename_quoting_function
1125A pointer to a function that will quote a filename in an application-
1126specific fashion. This is called if filename completion is being
1127attempted and one of the characters in @code{rl_filename_quote_characters}
1128appears in a completed filename. The function is called with
1129@var{text}, @var{match_type}, and @var{quote_pointer}. The @var{text}
1130is the filename to be quoted. The @var{match_type} is either
1131@code{SINGLE_MATCH}, if there is only one completion match, or
1132@code{MULT_MATCH}. Some functions use this to decide whether or not to
1133insert a closing quote character. The @var{quote_pointer} is a pointer
1134to any opening quote character the user typed. Some functions choose
1135to reset this character.
1136@end deftypevar
1137
1138@deftypevar {CPFunction *} rl_filename_dequoting_function
1139A pointer to a function that will remove application-specific quoting
1140characters from a filename before completion is attempted, so those
1141characters do not interfere with matching the text against names in
1142the filesystem. It is called with @var{text}, the text of the word
1143to be dequoted, and @var{quote_char}, which is the quoting character
1144that delimits the filename (usually @samp{'} or @samp{"}). If
1145@var{quote_char} is zero, the filename was not in an embedded string.
1146@end deftypevar
1147
1148@deftypevar {Function *} rl_char_is_quoted_p
1149A pointer to a function to call that determines whether or not a specific
1150character in the line buffer is quoted, according to whatever quoting
1151mechanism the program calling readline uses. The function is called with
1152two arguments: @var{text}, the text of the line, and @var{index}, the
1153index of the character in the line. It is used to decide whether a
1154character found in @code{rl_completer_word_break_characters} should be
1155used to break words for the completer.
1156@end deftypevar
1157
1158@deftypevar int rl_completion_query_items
1159Up to this many items will be displayed in response to a
1160possible-completions call. After that, we ask the user if she is sure
1161she wants to see them all. The default value is 100.
1162@end deftypevar
1163
1164@deftypevar {char *} rl_basic_word_break_characters
1165The basic list of characters that signal a break between words for the
1166completer routine. The default value of this variable is the characters
1167which break words for completion in Bash, i.e.,
1168@code{" \t\n\"\\'`@@$><=;|&@{("}.
1169@end deftypevar
1170
1171@deftypevar {char *} rl_basic_quote_characters
1172List of quote characters which can cause a word break.
1173@end deftypevar
1174
1175@deftypevar {char *} rl_completer_word_break_characters
1176The list of characters that signal a break between words for
1177@code{rl_complete_internal ()}. The default list is the value of
1178@code{rl_basic_word_break_characters}.
1179@end deftypevar
1180
1181@deftypevar {char *} rl_completer_quote_characters
1182List of characters which can be used to quote a substring of the line.
1183Completion occurs on the entire substring, and within the substring
1184@code{rl_completer_word_break_characters} are treated as any other character,
1185unless they also appear within this list.
1186@end deftypevar
1187
1188@deftypevar {char *} rl_filename_quote_characters
1189A list of characters that cause a filename to be quoted by the completer
1190when they appear in a completed filename. The default is the null string.
1191@end deftypevar
1192
1193@deftypevar {char *} rl_special_prefixes
1194The list of characters that are word break characters, but should be
1195left in @var{text} when it is passed to the completion function.
1196Programs can use this to help determine what kind of completing to do.
1197For instance, Bash sets this variable to "$@@" so that it can complete
1198shell variables and hostnames.
1199@end deftypevar
1200
1201@deftypevar {int} rl_completion_append_character
1202When a single completion alternative matches at the end of the command
1203line, this character is appended to the inserted completion text. The
1204default is a space character (@samp{ }). Setting this to the null
1205character (@samp{\0}) prevents anything being appended automatically.
1206This can be changed in custom completion functions to
1207provide the ``most sensible word separator character'' according to
1208an application-specific command line syntax specification.
1209@end deftypevar
1210
1211@deftypevar int rl_ignore_completion_duplicates
1212If non-zero, then disallow duplicates in the matches. Default is 1.
1213@end deftypevar
1214
1215@deftypevar int rl_filename_completion_desired
1216Non-zero means that the results of the matches are to be treated as
1217filenames. This is @emph{always} zero on entry, and can only be changed
1218within a completion entry generator function. If it is set to a non-zero
1219value, directory names have a slash appended and Readline attempts to
1220quote completed filenames if they contain any embedded word break
1221characters.
1222@end deftypevar
1223
1224@deftypevar int rl_filename_quoting_desired
1225Non-zero means that the results of the matches are to be quoted using
1226double quotes (or an application-specific quoting mechanism) if the
1227completed filename contains any characters in
1228@code{rl_filename_quote_chars}. This is @emph{always} non-zero
1229on entry, and can only be changed within a completion entry generator
1230function. The quoting is effected via a call to the function pointed to
1231by @code{rl_filename_quoting_function}.
1232@end deftypevar
1233
1234@deftypevar int rl_inhibit_completion
1235If this variable is non-zero, completion is inhibit<ed. The completion
1236character will be inserted as any other bound to @code{self-insert}.
1237@end deftypevar
1238
1239@deftypevar {Function *} rl_ignore_some_completions_function
1240This function, if defined, is called by the completer when real filename
1241completion is done, after all the matching names have been generated.
1242It is passed a @code{NULL} terminated array of matches.
1243The first element (@code{matches[0]}) is the
1244maximal substring common to all matches. This function can
1245re-arrange the list of matches as required, but each element deleted
1246from the array must be freed.
1247@end deftypevar
1248
1249@deftypevar {Function *} rl_directory_completion_hook
1250This function, if defined, is allowed to modify the directory portion
1251of filenames Readline completes. It is called with the address of a
1252string (the current directory name) as an argument. It could be used
1253to expand symbolic links or shell variables in pathnames.
1254@end deftypevar
c862e87b
JM
1255
1256@deftypevar {VFunction *} rl_completion_display_matches_hook
1257If non-zero, then this is the address of a function to call when
1258completing a word would normally display the list of possible matches.
1259This function is called in lieu of Readline displaying the list.
1260It takes three arguments:
1261(@code{char **}@var{matches}, @code{int} @var{num_matches}, @code{int} @var{max_length})
1262where @var{matches} is the array of matching strings,
1263@var{num_matches} is the number of strings in that array, and
1264@var{max_length} is the length of the longest string in that array.
1265Readline provides a convenience function, @code{rl_display_match_list},
1266that takes care of doing the display to Readline's output stream. That
1267function may be called from this hook.
1268@end deftypevar
d60d9f65
SS
1269
1270@node A Short Completion Example
1271@subsection A Short Completion Example
1272
1273Here is a small application demonstrating the use of the GNU Readline
1274library. It is called @code{fileman}, and the source code resides in
1275@file{examples/fileman.c}. This sample application provides
1276completion of command names, line editing features, and access to the
1277history list.
1278
1279@page
1280@smallexample
1281/* fileman.c -- A tiny application which demonstrates how to use the
1282 GNU Readline library. This application interactively allows users
1283 to manipulate files and their modes. */
1284
1285#include <stdio.h>
1286#include <sys/types.h>
1287#include <sys/file.h>
1288#include <sys/stat.h>
1289#include <sys/errno.h>
1290
1291#include <readline/readline.h>
1292#include <readline/history.h>
1293
1294extern char *getwd ();
1295extern char *xmalloc ();
1296
1297/* The names of functions that actually do the manipulation. */
1298int com_list (), com_view (), com_rename (), com_stat (), com_pwd ();
1299int com_delete (), com_help (), com_cd (), com_quit ();
1300
1301/* A structure which contains information on the commands this program
1302 can understand. */
1303
1304typedef struct @{
1305 char *name; /* User printable name of the function. */
1306 Function *func; /* Function to call to do the job. */
1307 char *doc; /* Documentation for this function. */
1308@} COMMAND;
1309
1310COMMAND commands[] = @{
1311 @{ "cd", com_cd, "Change to directory DIR" @},
1312 @{ "delete", com_delete, "Delete FILE" @},
1313 @{ "help", com_help, "Display this text" @},
1314 @{ "?", com_help, "Synonym for `help'" @},
1315 @{ "list", com_list, "List files in DIR" @},
1316 @{ "ls", com_list, "Synonym for `list'" @},
1317 @{ "pwd", com_pwd, "Print the current working directory" @},
1318 @{ "quit", com_quit, "Quit using Fileman" @},
1319 @{ "rename", com_rename, "Rename FILE to NEWNAME" @},
1320 @{ "stat", com_stat, "Print out statistics on FILE" @},
1321 @{ "view", com_view, "View the contents of FILE" @},
1322 @{ (char *)NULL, (Function *)NULL, (char *)NULL @}
1323@};
1324
1325/* Forward declarations. */
1326char *stripwhite ();
1327COMMAND *find_command ();
1328
1329/* The name of this program, as taken from argv[0]. */
1330char *progname;
1331
1332/* When non-zero, this global means the user is done using this program. */
1333int done;
1334
1335char *
1336dupstr (s)
1337 int s;
1338@{
1339 char *r;
1340
1341 r = xmalloc (strlen (s) + 1);
1342 strcpy (r, s);
1343 return (r);
1344@}
1345
1346main (argc, argv)
1347 int argc;
1348 char **argv;
1349@{
1350 char *line, *s;
1351
1352 progname = argv[0];
1353
1354 initialize_readline (); /* Bind our completer. */
1355
1356 /* Loop reading and executing lines until the user quits. */
1357 for ( ; done == 0; )
1358 @{
1359 line = readline ("FileMan: ");
1360
1361 if (!line)
1362 break;
1363
1364 /* Remove leading and trailing whitespace from the line.
1365 Then, if there is anything left, add it to the history list
1366 and execute it. */
1367 s = stripwhite (line);
1368
1369 if (*s)
1370 @{
1371 add_history (s);
1372 execute_line (s);
1373 @}
1374
1375 free (line);
1376 @}
1377 exit (0);
1378@}
1379
1380/* Execute a command line. */
1381int
1382execute_line (line)
1383 char *line;
1384@{
1385 register int i;
1386 COMMAND *command;
1387 char *word;
1388
1389 /* Isolate the command word. */
1390 i = 0;
1391 while (line[i] && whitespace (line[i]))
1392 i++;
1393 word = line + i;
1394
1395 while (line[i] && !whitespace (line[i]))
1396 i++;
1397
1398 if (line[i])
1399 line[i++] = '\0';
1400
1401 command = find_command (word);
1402
1403 if (!command)
1404 @{
1405 fprintf (stderr, "%s: No such command for FileMan.\n", word);
1406 return (-1);
1407 @}
1408
1409 /* Get argument to command, if any. */
1410 while (whitespace (line[i]))
1411 i++;
1412
1413 word = line + i;
1414
1415 /* Call the function. */
1416 return ((*(command->func)) (word));
1417@}
1418
1419/* Look up NAME as the name of a command, and return a pointer to that
1420 command. Return a NULL pointer if NAME isn't a command name. */
1421COMMAND *
1422find_command (name)
1423 char *name;
1424@{
1425 register int i;
1426
1427 for (i = 0; commands[i].name; i++)
1428 if (strcmp (name, commands[i].name) == 0)
1429 return (&commands[i]);
1430
1431 return ((COMMAND *)NULL);
1432@}
1433
1434/* Strip whitespace from the start and end of STRING. Return a pointer
1435 into STRING. */
1436char *
1437stripwhite (string)
1438 char *string;
1439@{
1440 register char *s, *t;
1441
1442 for (s = string; whitespace (*s); s++)
1443 ;
1444
1445 if (*s == 0)
1446 return (s);
1447
1448 t = s + strlen (s) - 1;
1449 while (t > s && whitespace (*t))
1450 t--;
1451 *++t = '\0';
1452
1453 return s;
1454@}
1455
1456/* **************************************************************** */
1457/* */
1458/* Interface to Readline Completion */
1459/* */
1460/* **************************************************************** */
1461
1462char *command_generator ();
1463char **fileman_completion ();
1464
1465/* Tell the GNU Readline library how to complete. We want to try to complete
1466 on command names if this is the first word in the line, or on filenames
1467 if not. */
1468initialize_readline ()
1469@{
1470 /* Allow conditional parsing of the ~/.inputrc file. */
1471 rl_readline_name = "FileMan";
1472
1473 /* Tell the completer that we want a crack first. */
1474 rl_attempted_completion_function = (CPPFunction *)fileman_completion;
1475@}
1476
1477/* Attempt to complete on the contents of TEXT. START and END bound the
1478 region of rl_line_buffer that contains the word to complete. TEXT is
1479 the word to complete. We can use the entire contents of rl_line_buffer
1480 in case we want to do some simple parsing. Return the array of matches,
1481 or NULL if there aren't any. */
1482char **
1483fileman_completion (text, start, end)
1484 char *text;
1485 int start, end;
1486@{
1487 char **matches;
1488
1489 matches = (char **)NULL;
1490
1491 /* If this word is at the start of the line, then it is a command
1492 to complete. Otherwise it is the name of a file in the current
1493 directory. */
1494 if (start == 0)
1495 matches = completion_matches (text, command_generator);
1496
1497 return (matches);
1498@}
1499
1500/* Generator function for command completion. STATE lets us know whether
1501 to start from scratch; without any state (i.e. STATE == 0), then we
1502 start at the top of the list. */
1503char *
1504command_generator (text, state)
1505 char *text;
1506 int state;
1507@{
1508 static int list_index, len;
1509 char *name;
1510
1511 /* If this is a new word to complete, initialize now. This includes
1512 saving the length of TEXT for efficiency, and initializing the index
1513 variable to 0. */
1514 if (!state)
1515 @{
1516 list_index = 0;
1517 len = strlen (text);
1518 @}
1519
1520 /* Return the next name which partially matches from the command list. */
1521 while (name = commands[list_index].name)
1522 @{
1523 list_index++;
1524
1525 if (strncmp (name, text, len) == 0)
1526 return (dupstr(name));
1527 @}
1528
1529 /* If no names matched, then return NULL. */
1530 return ((char *)NULL);
1531@}
1532
1533/* **************************************************************** */
1534/* */
1535/* FileMan Commands */
1536/* */
1537/* **************************************************************** */
1538
1539/* String to pass to system (). This is for the LIST, VIEW and RENAME
1540 commands. */
1541static char syscom[1024];
1542
1543/* List the file(s) named in arg. */
1544com_list (arg)
1545 char *arg;
1546@{
1547 if (!arg)
1548 arg = "";
1549
1550 sprintf (syscom, "ls -FClg %s", arg);
1551 return (system (syscom));
1552@}
1553
1554com_view (arg)
1555 char *arg;
1556@{
1557 if (!valid_argument ("view", arg))
1558 return 1;
1559
1560 sprintf (syscom, "more %s", arg);
1561 return (system (syscom));
1562@}
1563
1564com_rename (arg)
1565 char *arg;
1566@{
1567 too_dangerous ("rename");
1568 return (1);
1569@}
1570
1571com_stat (arg)
1572 char *arg;
1573@{
1574 struct stat finfo;
1575
1576 if (!valid_argument ("stat", arg))
1577 return (1);
1578
1579 if (stat (arg, &finfo) == -1)
1580 @{
1581 perror (arg);
1582 return (1);
1583 @}
1584
1585 printf ("Statistics for `%s':\n", arg);
1586
1587 printf ("%s has %d link%s, and is %d byte%s in length.\n", arg,
1588 finfo.st_nlink,
1589 (finfo.st_nlink == 1) ? "" : "s",
1590 finfo.st_size,
1591 (finfo.st_size == 1) ? "" : "s");
1592 printf ("Inode Last Change at: %s", ctime (&finfo.st_ctime));
1593 printf (" Last access at: %s", ctime (&finfo.st_atime));
1594 printf (" Last modified at: %s", ctime (&finfo.st_mtime));
1595 return (0);
1596@}
1597
1598com_delete (arg)
1599 char *arg;
1600@{
1601 too_dangerous ("delete");
1602 return (1);
1603@}
1604
1605/* Print out help for ARG, or for all of the commands if ARG is
1606 not present. */
1607com_help (arg)
1608 char *arg;
1609@{
1610 register int i;
1611 int printed = 0;
1612
1613 for (i = 0; commands[i].name; i++)
1614 @{
1615 if (!*arg || (strcmp (arg, commands[i].name) == 0))
1616 @{
1617 printf ("%s\t\t%s.\n", commands[i].name, commands[i].doc);
1618 printed++;
1619 @}
1620 @}
1621
1622 if (!printed)
1623 @{
1624 printf ("No commands match `%s'. Possibilties are:\n", arg);
1625
1626 for (i = 0; commands[i].name; i++)
1627 @{
1628 /* Print in six columns. */
1629 if (printed == 6)
1630 @{
1631 printed = 0;
1632 printf ("\n");
1633 @}
1634
1635 printf ("%s\t", commands[i].name);
1636 printed++;
1637 @}
1638
1639 if (printed)
1640 printf ("\n");
1641 @}
1642 return (0);
1643@}
1644
1645/* Change to the directory ARG. */
1646com_cd (arg)
1647 char *arg;
1648@{
1649 if (chdir (arg) == -1)
1650 @{
1651 perror (arg);
1652 return 1;
1653 @}
1654
1655 com_pwd ("");
1656 return (0);
1657@}
1658
1659/* Print out the current working directory. */
1660com_pwd (ignore)
1661 char *ignore;
1662@{
1663 char dir[1024], *s;
1664
1665 s = getwd (dir);
1666 if (s == 0)
1667 @{
1668 printf ("Error getting pwd: %s\n", dir);
1669 return 1;
1670 @}
1671
1672 printf ("Current directory is %s\n", dir);
1673 return 0;
1674@}
1675
1676/* The user wishes to quit using this program. Just set DONE non-zero. */
1677com_quit (arg)
1678 char *arg;
1679@{
1680 done = 1;
1681 return (0);
1682@}
1683
1684/* Function which tells you that you can't do this. */
1685too_dangerous (caller)
1686 char *caller;
1687@{
1688 fprintf (stderr,
1689 "%s: Too dangerous for me to distribute. Write it yourself.\n",
1690 caller);
1691@}
1692
1693/* Return non-zero if ARG is a valid argument for CALLER, else print
1694 an error message and return zero. */
1695int
1696valid_argument (caller, arg)
1697 char *caller, *arg;
1698@{
1699 if (!arg || !*arg)
1700 @{
1701 fprintf (stderr, "%s: Argument required.\n", caller);
1702 return (0);
1703 @}
1704
1705 return (1);
1706@}
1707@end smallexample
This page took 0.120355 seconds and 4 git commands to generate.