home *** CD-ROM | disk | FTP | other *** search
/ Il CD di internet / CD.iso / SOURCE / AP / TERMNET / READLINE.1 / DOC / RLTECH.TEX < prev    next >
Encoding:
Text File  |  1995-04-20  |  31.8 KB  |  1,011 lines

  1. @comment %**start of header (This is for running Texinfo on a region.)
  2. @setfilename rltech.info
  3. @synindex fn vr
  4. @comment %**end of header (This is for running Texinfo on a region.)
  5. @setchapternewpage odd
  6.  
  7. @ifinfo
  8. This document describes the GNU Readline Library, a utility for aiding
  9. in the consitency of user interface across discrete programs that need
  10. to provide a command line interface.
  11.  
  12. Copyright (C) 1988 Free Software Foundation, Inc.
  13.  
  14. Permission is granted to make and distribute verbatim copies of
  15. this manual provided the copyright notice and this permission notice
  16. pare preserved on all copies.
  17.  
  18. @ignore
  19. Permission is granted to process this file through TeX and print the
  20. results, provided the printed document carries copying permission
  21. notice identical to this one except for the removal of this paragraph
  22. (this paragraph not being relevant to the printed manual).
  23. @end ignore
  24.  
  25. Permission is granted to copy and distribute modified versions of this
  26. manual under the conditions for verbatim copying, provided that the entire
  27. resulting derived work is distributed under the terms of a permission
  28. notice identical to this one.
  29.  
  30. Permission is granted to copy and distribute translations of this manual
  31. into another language, under the above conditions for modified versions,
  32. except that this permission notice may be stated in a translation approved
  33. by the Foundation.
  34. @end ifinfo
  35.  
  36. @node Programming with GNU Readline
  37. @chapter Programming with GNU Readline
  38.  
  39. This manual describes the interface between the GNU Readline Library and
  40. user programs.  If you are a programmer, and you wish to include the
  41. features found in GNU Readline in your own programs, such as completion,
  42. line editing, and interactive history manipulation, this documentation
  43. is for you.
  44.  
  45. @menu
  46. * Default Behaviour::    Using the default behaviour of Readline.
  47. * Custom Functions::    Adding your own functions to Readline.
  48. * Custom Completers::    Supplanting or supplementing Readline's
  49.             completion functions.
  50. @end menu
  51.  
  52. @node Default Behaviour
  53. @section Default Behaviour
  54.  
  55. Many programs provide a command line interface, such as @code{mail},
  56. @code{ftp}, and @code{sh}.  For such programs, the default behaviour of
  57. Readline is sufficient.  This section describes how to use Readline in
  58. the simplest way possible, perhaps to replace calls in your code to
  59. @code{gets ()}.
  60.  
  61. @findex readline ()
  62. @cindex readline, function
  63. The function @code{readline} prints a prompt and then reads and returns
  64. a single line of text from the user.  The line which @code{readline ()}
  65. returns is allocated with @code{malloc ()}; you should @code{free ()}
  66. the line when you are done with it.  The declaration for @code{readline}
  67. in ANSI C is
  68.  
  69. @example
  70. @code{char *readline (char *@var{prompt});}
  71. @end example
  72.  
  73. So, one might say
  74. @example
  75. @code{char *line = readline ("Enter a line: ");}
  76. @end example
  77. in order to read a line of text from the user.
  78.  
  79. The line which is returned has the final newline removed, so only the
  80. text of the line remains.
  81.  
  82. If readline encounters an @code{EOF} while reading the line, and the
  83. line is empty at that point, then @code{(char *)NULL} is returned.
  84. Otherwise, the line is ended just as if a newline was typed.
  85.  
  86. If you want the user to be able to get at the line later, (with
  87. @key{C-p} for example), you must call @code{add_history ()} to save the
  88. line away in a @dfn{history} list of such lines.
  89.  
  90. @example
  91. @code{add_history (line)};
  92. @end example
  93.  
  94. For full details on the GNU History Library, see the associated manual.
  95.  
  96. It is polite to avoid saving empty lines on the history list, since it
  97. is rare than someone has a burning need to reuse a blank line.  Here is
  98. a function which usefully replaces the standard @code{gets ()} library
  99. function:
  100.  
  101. @example
  102. /* A static variable for holding the line. */
  103. static char *line_read = (char *)NULL;
  104.  
  105. /* Read a string, and return a pointer to it.  Returns NULL on EOF. */
  106. char *
  107. do_gets ()
  108. @{
  109.   /* If the buffer has already been allocated, return the memory
  110.      to the free pool. */
  111.   if (line_read != (char *)NULL)
  112.     @{
  113.       free (line_read);
  114.       line_read = (char *)NULL;
  115.     @}
  116.  
  117.   /* Get a line from the user. */
  118.   line_read = readline ("");
  119.  
  120.   /* If the line has any text in it, save it on the history. */
  121.   if (line_read && *line_read)
  122.     add_history (line_read);
  123.  
  124.   return (line_read);
  125. @}
  126. @end example
  127.  
  128. The above code gives the user the default behaviour of @key{TAB}
  129. completion: completion on file names.  If you do not want readline to
  130. complete on filenames, you can change the binding of the @key{TAB} key
  131. with @code{rl_bind_key ()}.
  132.  
  133. @findex rl_bind_key ()
  134. @example
  135. @code{int rl_bind_key (int @var{key}, (int (*)())@var{function});}
  136. @end example
  137.  
  138. @code{rl_bind_key ()} takes 2 arguments; @var{key} is the character that
  139. you want to bind, and @var{function} is the address of the function to
  140. run when @var{key} is pressed.  Binding @key{TAB} to @code{rl_insert ()}
  141. makes @key{TAB} just insert itself.
  142.  
  143. @code{rl_bind_key ()} returns non-zero if @var{key} is not a valid
  144. ASCII character code (between 0 and 255).
  145.  
  146. @example
  147. @code{rl_bind_key ('\t', rl_insert);}
  148. @end example
  149.  
  150. This code should be executed once at the start of your program; you
  151. might write a function called @code{initialize_readline ()} which
  152. performs this and other desired initializations, such as installing
  153. custom completers, etc.
  154.  
  155. @node Custom Functions
  156. @section Custom Functions
  157.  
  158. Readline provides a great many functions for manipulating the text of
  159. the line.  But it isn't possible to anticipate the needs of all
  160. programs.  This section describes the various functions and variables
  161. defined in within the Readline library which allow a user program to add
  162. customized functionality to Readline.
  163.  
  164. @menu
  165. * The Function Type::    C declarations to make code readable.
  166. * Function Naming::    How to give a function you write a name.
  167. * Keymaps::        Making keymaps.
  168. * Binding Keys::    Changing Keymaps.
  169. * Function Writing::    Variables and calling conventions.
  170. * Allowing Undoing::    How to make your functions undoable.
  171. @end menu
  172.  
  173. @node The Function Type
  174. @subsection The Function Type
  175.  
  176. For the sake of readabilty, we declare a new type of object, called
  177. @dfn{Function}.  A @code{Function} is a C language function which
  178. returns an @code{int}.  The type declaration for @code{Function} is:
  179.  
  180. @noindent
  181. @code{typedef int Function ();}
  182.  
  183. The reason for declaring this new type is to make it easier to write
  184. code describing pointers to C functions.  Let us say we had a variable
  185. called @var{func} which was a pointer to a function.  Instead of the
  186. classic C declaration
  187.  
  188. @code{int (*)()func;}
  189.  
  190. we have
  191.  
  192. @code{Function *func;}
  193.  
  194. @node Function Naming
  195. @subsection Naming a Function
  196.  
  197. The user can dynamically change the bindings of keys while using
  198. Readline.  This is done by representing the function with a descriptive
  199. name.  The user is able to type the descriptive name when referring to
  200. the function.  Thus, in an init file, one might find
  201.  
  202. @example
  203. Meta-Rubout:    backward-kill-word
  204. @end example
  205.  
  206. This binds the keystroke @key{Meta-Rubout} to the function
  207. @emph{descriptively} named @code{backward-kill-word}.  You, as the
  208. programmer, should bind the functions you write to descriptive names as
  209. well.  Readline provides a function for doing that:
  210.  
  211. @defun rl_add_defun (char *name, Function *function, int key)
  212. Add @var{name} to the list of named functions.  Make @var{function} be
  213. the function that gets called.  If @var{key} is not -1, then bind it to
  214. @var{function} using @code{rl_bind_key ()}.
  215. @end defun
  216.  
  217. Using this function alone is sufficient for most applications.  It is
  218. the recommended way to add a few functions to the default functions that
  219. Readline has built in already.  If you need to do more or different
  220. things than adding a function to Readline, you may need to use the
  221. underlying functions described below.
  222.  
  223. @node Keymaps
  224. @subsection Selecting a Keymap
  225.  
  226. Key bindings take place on a @dfn{keymap}.  The keymap is the
  227. association between the keys that the user types and the functions that
  228. get run.  You can make your own keymaps, copy existing keymaps, and tell
  229. Readline which keymap to use.
  230.  
  231. @defun {Keymap rl_make_bare_keymap} ()
  232. Returns a new, empty keymap.  The space for the keymap is allocated with
  233. @code{malloc ()}; you should @code{free ()} it when you are done.
  234. @end defun
  235.  
  236. @defun {Keymap rl_copy_keymap} (Keymap map)
  237. Return a new keymap which is a copy of @var{map}.
  238. @end defun
  239.  
  240. @defun {Keymap rl_make_keymap} ()
  241. Return a new keymap with the printing characters bound to rl_insert,
  242. the lowercase Meta characters bound to run their equivalents, and
  243. the Meta digits bound to produce numeric arguments.
  244. @end defun
  245.  
  246. @node Binding Keys
  247. @subsection Binding Keys
  248.  
  249. You associate keys with functions through the keymap.  Here are
  250. functions for doing that.
  251.  
  252. @defun {int rl_bind_key} (int key, Function *function)
  253. Binds @var{key} to @var{function} in the currently selected keymap.
  254. Returns non-zero in the case of an invalid @var{key}.
  255. @end defun
  256.  
  257. @defun {int rl_bind_key_in_map} (int key, Function *function, Keymap map)
  258. Bind @var{key} to @var{function} in @var{map}.  Returns non-zero in the case
  259. of an invalid @var{key}.
  260. @end defun
  261.  
  262. @defun {int rl_unbind_key} (int key)
  263. Make @var{key} do nothing in the currently selected keymap.
  264. Returns non-zero in case of error.
  265. @end defun
  266.  
  267. @defun {int rl_unbind_key_in_map} (int key, Keymap map)
  268. Make @var{key} be bound to the null function in @var{map}.
  269. Returns non-zero in case of error.
  270. @end defun
  271.  
  272. @defun rl_generic_bind (int type, char *keyseq, char *data, Keymap map)
  273. Bind the key sequence represented by the string @var{keyseq} to the arbitrary
  274. pointer @var{data}.  @var{type} says what kind of data is pointed to by
  275. @var{data}; right now this can be a function (@code{ISFUNC}), a macro
  276. (@code{ISMACR}), or a keymap (@code{ISKMAP}).  This makes new keymaps as
  277. necessary.  The initial place to do bindings is in @var{map}.
  278. @end defun
  279.  
  280. @node Function Writing
  281. @subsection Writing a New Function
  282.  
  283. In order to write new functions for Readline, you need to know the
  284. calling conventions for keyboard invoked functions, and the names of the
  285. variables that describe the current state of the line gathered so far.
  286.  
  287. @defvar {char *rl_line_buffer}
  288. This is the line gathered so far.  You are welcome to modify the
  289. contents of this, but see Undoing, below.
  290. @end defvar
  291.  
  292. @defvar {int rl_point}
  293. The offset of the current cursor position in @var{rl_line_buffer}.
  294. @end defvar
  295.  
  296. @defvar {int rl_end}
  297. The number of characters present in @code{rl_line_buffer}.  When
  298. @code{rl_point} is at the end of the line, then @code{rl_point} and
  299. @code{rl_end} are equal.
  300. @end defvar
  301.  
  302. The calling sequence for a command @code{foo} looks like
  303.  
  304. @example
  305. @code{foo (int count, int key)}
  306. @end example
  307.  
  308. where @var{count} is the numeric argument (or 1 if defaulted) and
  309. @var{key} is the key that invoked this function.
  310.  
  311. It is completely up to the function as to what should be done with the
  312. numeric argument; some functions use it as a repeat count, other
  313. functions as a flag, and some choose to ignore it.  In general, if a
  314. function uses the numeric argument as a repeat count, it should be able
  315. to do something useful with a negative argument as well as a positive
  316. argument.  At the very least, it should be aware that it can be passed a
  317. negative argument.
  318.  
  319. @node Allowing Undoing
  320. @subsection Allowing Undoing
  321.  
  322. Supporting the undo command is a painless thing to do, and makes your
  323. functions much more useful to the end user.  It is certainly easy to try
  324. something if you know you can undo it.  I could use an undo function for
  325. the stock market.
  326.  
  327. If your function simply inserts text once, or deletes text once, and it
  328. calls @code{rl_insert_text ()} or @code{rl_delete_text ()} to do it, then
  329. undoing is already done for you automatically, and you can safely skip
  330. this section.
  331.  
  332. If you do multiple insertions or multiple deletions, or any combination
  333. of these operations, you should group them together into one operation.
  334. This can be done with @code{rl_begin_undo_group ()} and
  335. @code{rl_end_undo_group ()}.
  336.  
  337. @defun rl_begin_undo_group ()
  338. Begins saving undo information in a group construct.  The undo
  339. information usually comes from calls to @code{rl_insert_text ()} and
  340. @code{rl_delete_text ()}, but they could be direct calls to
  341. @code{rl_add_undo ()}.
  342. @end defun
  343.  
  344. @defun rl_end_undo_group ()
  345. Closes the current undo group started with @code{rl_begin_undo_group
  346. ()}.  There should be exactly one call to @code{rl_end_undo_group ()}
  347. for every call to @code{rl_begin_undo_group ()}.
  348. @end defun
  349.  
  350. Finally, if you neither insert nor delete text, but directly modify the
  351. existing text (e.g. change its case), you call @code{rl_modifying ()}
  352. once, just before you modify the text.  You must supply the indices of
  353. the text range that you are going to modify.
  354.  
  355. @defun rl_modifying (int start, int end)
  356. Tell Readline to save the text between @var{start} and @var{end} as a
  357. single undo unit.  It is assumed that subsequent to this call you will
  358. modify that range of text in some way.
  359. @end defun
  360.  
  361. @subsection An Example
  362.  
  363. Here is a function which changes lowercase characters to the uppercase
  364. equivalents, and uppercase characters to the lowercase equivalents.  If
  365. this function was bound to @samp{M-c}, then typing @samp{M-c} would
  366. change the case of the character under point.  Typing @samp{10 M-c}
  367. would change the case of the following 10 characters, leaving the cursor on
  368. the last character changed.
  369.  
  370. @example
  371. /* Invert the case of the COUNT following characters. */
  372. invert_case_line (count, key)
  373.      int count, key;
  374. @{
  375.   register int start, end;
  376.  
  377.   start = rl_point;
  378.  
  379.   if (count < 0)
  380.     @{
  381.       direction = -1;
  382.       count = -count;
  383.     @}
  384.   else
  385.     direction = 1;
  386.       
  387.   /* Find the end of the range to modify. */
  388.   end = start + (count * direction);
  389.  
  390.   /* Force it to be within range. */
  391.   if (end > rl_end)
  392.     end = rl_end;
  393.   else if (end < 0)
  394.     end = -1;
  395.  
  396.   if (start > end)
  397.     @{
  398.       int temp = start;
  399.       start = end;
  400.       end = temp;
  401.     @}
  402.  
  403.   if (start == end)
  404.     return;
  405.  
  406.   /* Tell readline that we are modifying the line, so save the undo
  407.      information. */
  408.   rl_modifying (start, end);
  409.  
  410.   for (; start != end; start += direction)
  411.     @{
  412.       if (uppercase_p (rl_line_buffer[start]))
  413.         rl_line_buffer[start] = to_lower (rl_line_buffer[start]);
  414.       else if (lowercase_p (rl_line_buffer[start]))
  415.         rl_line_buffer[start] = to_upper (rl_line_buffer[start]);
  416.     @}
  417.   /* Move point to on top of the last character changed. */
  418.   rl_point = end - direction;
  419. @}
  420. @end example
  421.  
  422. @node Custom Completers
  423. @section Custom Completers
  424.  
  425. Typically, a program that reads commands from the user has a way of
  426. disambiguating between commands and data.  If your program is one of
  427. these, then it can provide completion for either commands, or data, or
  428. both commands and data.  The following sections describe how your
  429. program and Readline cooperate to provide this service to end users.
  430.  
  431. @menu
  432. * How Completing Works::    The logic used to do completion.
  433. * Completion Functions::    Functions provided by Readline.
  434. * Completion Variables::    Variables which control completion.
  435. * A Short Completion Example::    An example of writing completer subroutines.
  436. @end menu
  437.  
  438. @node How Completing Works
  439. @subsection How Completing Works
  440.  
  441. In order to complete some text, the full list of possible completions
  442. must be available.  That is to say, it is not possible to accurately
  443. expand a partial word without knowing what all of the possible words
  444. that make sense in that context are.  The GNU Readline library provides
  445. the user interface to completion, and additionally, two of the most common
  446. completion functions; filename and username.  For completing other types
  447. of text, you must write your own completion function.  This section
  448. describes exactly what those functions must do, and provides an example
  449. function.
  450.  
  451. There are three major functions used to perform completion:
  452.  
  453. @enumerate
  454. @item
  455. The user-interface function @code{rl_complete ()}.  This function is
  456. called interactively with the same calling conventions as other
  457. functions in readline intended for interactive use; i.e. @var{count},
  458. and @code{invoking-key}.  It isolates the word to be completed and calls
  459. @code{completion_matches ()} to generate a list of possible completions.
  460. It then either lists the possible completions or actually performs the
  461. completion, depending on which behaviour is desired.
  462.  
  463. @item
  464. The internal function @code{completion_matches ()} uses your
  465. @dfn{generator} function to generate the list of possible matches, and
  466. then returns the array of these matches.  You should place the address
  467. of your generator function in @code{rl_completion_entry_function}.
  468.  
  469. @item
  470. The generator function is called repeatedly from
  471. @code{completion_matches ()}, returning a string each time.  The
  472. arguments to the generator function are @var{text} and @var{state}.
  473. @var{text} is the partial word to be completed.  @var{state} is zero the
  474. first time the function is called, and a positive non-zero integer for
  475. each subsequent call.  When the generator function returns @code{(char
  476. *)NULL} this signals @code{completion_matches ()} that there are no more
  477. possibilities left.
  478.  
  479. @end enumerate
  480.  
  481. @defun rl_complete (int ignore, int invoking_key)
  482. Complete the word at or before point.  You have supplied the function
  483. that does the initial simple matching selection algorithm (see
  484. @code{completion_matches ()}).  The default is to do filename completion.
  485. @end defun
  486.  
  487. Note that @code{rl_complete ()} has the identical calling conventions as
  488. any other key-invokable function; this is because by default it is bound
  489. to the @samp{TAB} key.
  490.  
  491. @defvar {Function *rl_completion_entry_function}
  492. This is a pointer to the generator function for @code{completion_matches
  493. ()}.  If the value of @code{rl_completion_entry_function} is
  494. @code{(Function *)NULL} then the default filename generator function is
  495. used, namely @code{filename_entry_function ()}.
  496. @end defvar
  497.  
  498. @node Completion Functions
  499. @subsection Completion Functions
  500.  
  501. Here is the complete list of callable completion functions present in
  502. Readline.
  503.  
  504. @defun rl_complete_internal (int what_to_do)
  505. Complete the word at or before point.  @var{what_to_do} says what to do
  506. with the completion.  A value of @samp{?} means list the possible
  507. completions.  @samp{TAB} means do standard completion.  @samp{*} means
  508. insert all of the possible completions.
  509. @end defun
  510.  
  511. @defun rl_complete (int ignore, int invoking_key)
  512. Complete the word at or before point.  You have supplied the function
  513. that does the initial simple matching selection algorithm (see
  514. @code{completion_matches ()}).  The default is to do filename
  515. completion.  This just calls @code{rl_complete_internal ()} with an
  516. argument of @samp{TAB}.
  517. @end defun
  518.  
  519. @defun rl_possible_completions ()
  520. List the possible completions.  See description of @code{rl_complete
  521. ()}.  This just calls @code{rl_complete_internal ()} with an argument of
  522. @samp{?}.
  523. @end defun
  524.  
  525. @defun {char **completion_matches} (char *text, char *(*entry_function) ())
  526. Returns an array of @code{(char *)} which is a list of completions for
  527. @var{text}.  If there are no completions, returns @code{(char **)NULL}.
  528. The first entry in the returned array is the substitution for @var{text}.
  529. The remaining entries are the possible completions.  The array is
  530. terminated with a @code{NULL} pointer.
  531.  
  532. @var{entry_function} is a function of two args, and returns a
  533. @code{(char *)}.  The first argument is @var{text}.  The second is a
  534. state argument; it is zero on the first call, and non-zero on subsequent
  535. calls.  It returns a @code{NULL}  pointer to the caller when there are
  536. no more matches.
  537. @end defun
  538.  
  539. @defun {char *filename_completion_function} (char *text, int state)
  540. A generator function for filename completion in the general case.  Note
  541. that completion in the Bash shell is a little different because of all
  542. the pathnames that must be followed when looking up the completion for a
  543. command.
  544. @end defun
  545.  
  546. @defun {char *username_completion_function} (char *text, int state)
  547. A completion generator for usernames.  @var{text} contains a partial
  548. username preceded by a random character (usually @samp{~}).
  549. @end defun
  550.  
  551. @node Completion Variables
  552. @subsection Completion Variables
  553.  
  554. @defvar {Function *rl_completion_entry_function}
  555. A pointer to the generator function for @code{completion_matches ()}.
  556. @code{NULL} means to use @code{filename_entry_function ()}, the default
  557. filename completer.
  558. @end defvar
  559.  
  560. @defvar {Function *rl_attempted_completion_function}
  561. A pointer to an alternative function to create matches.
  562. The function is called with @var{text}, @var{start}, and @var{end}.
  563. @var{start} and @var{end} are indices in @code{rl_line_buffer} saying
  564. what the boundaries of @var{text} are.  If this function exists and
  565. returns @code{NULL} then @code{rl_complete ()} will call the value of
  566. @code{rl_completion_entry_function} to generate matches, otherwise the
  567. array of strings returned will be used.
  568. @end defvar
  569.  
  570. @defvar {int rl_completion_query_items}
  571. Up to this many items will be displayed in response to a
  572. possible-completions call.  After that, we ask the user if she is sure
  573. she wants to see them all.  The default value is 100.
  574. @end defvar
  575.  
  576. @defvar {char *rl_basic_word_break_characters}
  577. The basic list of characters that signal a break between words for the
  578. completer routine.  The contents of this variable is what breaks words
  579. in the Bash shell, i.e. " \t\n\"\\'`@@$><=".
  580. @end defvar
  581.  
  582. @defvar {char *rl_completer_word_break_characters}
  583. The list of characters that signal a break between words for
  584. @code{rl_complete_internal ()}.  The default list is the contents of
  585. @code{rl_basic_word_break_characters}.
  586. @end defvar
  587.  
  588. @defvar {char *rl_special_prefixes}
  589. The list of characters that are word break characters, but should be
  590. left in @var{text} when it is passed to the completion function.
  591. Programs can use this to help determine what kind of completing to do.
  592. @end defvar
  593.  
  594. @defvar {int rl_ignore_completion_duplicates}
  595. If non-zero, then disallow duplicates in the matches.  Default is 1.
  596. @end defvar
  597.  
  598. @defvar {int rl_filename_completion_desired}
  599. Non-zero means that the results of the matches are to be treated as
  600. filenames.  This is @emph{always} zero on entry, and can only be changed
  601. within a completion entry generator function.
  602. @end defvar
  603.  
  604. @defvar {Function *rl_ignore_some_completions_function}
  605. This function, if defined, is called by the completer when real filename
  606. completion is done, after all the matching names have been generated.  It
  607. is passed a @code{NULL} terminated array of pointers to @code{(char *)}
  608. known as @var{matches} in the code.  The 1st element (@code{matches[0]})
  609. is the maximal substring that is common to all matches. This function
  610. can re-arrange the list of matches as required, but each deleted
  611. element of the array must be @code{free()}'d.
  612. @end defvar
  613.  
  614. @node A Short Completion Example
  615. @subsection A Short Completion Example
  616.  
  617. Here is a small application demonstrating the use of the GNU Readline
  618. library.  It is called @code{fileman}, and the source code resides in
  619. @file{readline/examples/fileman.c}.  This sample application provides
  620. completion of command names, line editing features, and access to the
  621. history list.
  622.  
  623. @page
  624. @smallexample
  625. /* fileman.c -- A tiny application which demonstrates how to use the
  626.    GNU Readline library.  This application interactively allows users
  627.    to manipulate files and their modes. */
  628.  
  629. #include <stdio.h>
  630. #include <readline/readline.h>
  631. #include <readline/history.h>
  632. #include <sys/types.h>
  633. #include <sys/file.h>
  634. #include <sys/stat.h>
  635. #include <sys/errno.h>
  636.  
  637. /* The names of functions that actually do the manipulation. */
  638. int com_list (), com_view (), com_rename (), com_stat (), com_pwd ();
  639. int com_delete (), com_help (), com_cd (), com_quit ();
  640.  
  641. /* A structure which contains information on the commands this program
  642.    can understand. */
  643.  
  644. typedef struct @{
  645.   char *name;                   /* User printable name of the function. */
  646.   Function *func;               /* Function to call to do the job. */
  647.   char *doc;                    /* Documentation for this function.  */
  648. @} COMMAND;
  649.  
  650. COMMAND commands[] = @{
  651.   @{ "cd", com_cd, "Change to directory DIR" @},
  652.   @{ "delete", com_delete, "Delete FILE" @},
  653.   @{ "help", com_help, "Display this text" @},
  654.   @{ "?", com_help, "Synonym for `help'" @},
  655.   @{ "list", com_list, "List files in DIR" @},
  656.   @{ "ls", com_list, "Synonym for `list'" @},
  657.   @{ "pwd", com_pwd, "Print the current working directory" @},
  658.   @{ "quit", com_quit, "Quit using Fileman" @},
  659.   @{ "rename", com_rename, "Rename FILE to NEWNAME" @},
  660.   @{ "stat", com_stat, "Print out statistics on FILE" @},
  661.   @{ "view", com_view, "View the contents of FILE" @},
  662.   @{ (char *)NULL, (Function *)NULL, (char *)NULL @}
  663. @};
  664.  
  665. /* The name of this program, as taken from argv[0]. */
  666. char *progname;
  667.  
  668. /* When non-zero, this global means the user is done using this program. */
  669. int done = 0;
  670. @page
  671. main (argc, argv)
  672.      int argc;
  673.      char **argv;
  674. @{
  675.   progname = argv[0];
  676.  
  677.   initialize_readline ();       /* Bind our completer. */
  678.  
  679.   /* Loop reading and executing lines until the user quits. */
  680.   while (!done)
  681.     @{
  682.       char *line;
  683.  
  684.       line = readline ("FileMan: ");
  685.  
  686.       if (!line)
  687.         @{
  688.           done = 1;             /* Encountered EOF at top level. */
  689.         @}
  690.       else
  691.         @{
  692.           /* Remove leading and trailing whitespace from the line.
  693.              Then, if there is anything left, add it to the history list
  694.              and execute it. */
  695.           stripwhite (line);
  696.  
  697.           if (*line)
  698.             @{
  699.               add_history (line);
  700.               execute_line (line);
  701.             @}
  702.         @}
  703.  
  704.       if (line)
  705.         free (line);
  706.     @}
  707.   exit (0);
  708. @}
  709.  
  710. /* Execute a command line. */
  711. execute_line (line)
  712.      char *line;
  713. @{
  714.   register int i;
  715.   COMMAND *find_command (), *command;
  716.   char *word;
  717.  
  718.   /* Isolate the command word. */
  719.   i = 0;
  720.   while (line[i] && !whitespace (line[i]))
  721.     i++;
  722.  
  723.   word = line;
  724.  
  725.   if (line[i])
  726.     line[i++] = '\0';
  727.  
  728.   command = find_command (word);
  729.  
  730.   if (!command)
  731.     @{
  732.       fprintf (stderr, "%s: No such command for FileMan.\n", word);
  733.       return;
  734.     @}
  735.  
  736.   /* Get argument to command, if any. */
  737.   while (whitespace (line[i]))
  738.     i++;
  739.  
  740.   word = line + i;
  741.  
  742.   /* Call the function. */
  743.   (*(command->func)) (word);
  744. @}
  745.  
  746. /* Look up NAME as the name of a command, and return a pointer to that
  747.    command.  Return a NULL pointer if NAME isn't a command name. */
  748. COMMAND *
  749. find_command (name)
  750.      char *name;
  751. @{
  752.   register int i;
  753.  
  754.   for (i = 0; commands[i].name; i++)
  755.     if (strcmp (name, commands[i].name) == 0)
  756.       return (&commands[i]);
  757.  
  758.   return ((COMMAND *)NULL);
  759. @}
  760.  
  761. /* Strip whitespace from the start and end of STRING. */
  762. stripwhite (string)
  763.      char *string;
  764. @{
  765.   register int i = 0;
  766.  
  767.   while (whitespace (string[i]))
  768.     i++;
  769.  
  770.   if (i)
  771.     strcpy (string, string + i);
  772.  
  773.   i = strlen (string) - 1;
  774.  
  775.   while (i > 0 && whitespace (string[i]))
  776.     i--;
  777.  
  778.   string[++i] = '\0';
  779. @}
  780. @page
  781. /* **************************************************************** */
  782. /*                                                                  */
  783. /*                  Interface to Readline Completion                */
  784. /*                                                                  */
  785. /* **************************************************************** */
  786.  
  787. /* Tell the GNU Readline library how to complete.  We want to try to complete
  788.    on command names if this is the first word in the line, or on filenames
  789.    if not. */
  790. initialize_readline ()
  791. @{
  792.   char **fileman_completion ();
  793.  
  794.   /* Allow conditional parsing of the ~/.inputrc file. */
  795.   rl_readline_name = "FileMan";
  796.  
  797.   /* Tell the completer that we want a crack first. */
  798.   rl_attempted_completion_function = (Function *)fileman_completion;
  799. @}
  800.  
  801. /* Attempt to complete on the contents of TEXT.  START and END show the
  802.    region of TEXT that contains the word to complete.  We can use the
  803.    entire line in case we want to do some simple parsing.  Return the
  804.    array of matches, or NULL if there aren't any. */
  805. char **
  806. fileman_completion (text, start, end)
  807.      char *text;
  808.      int start, end;
  809. @{
  810.   char **matches;
  811.   char *command_generator ();
  812.  
  813.   matches = (char **)NULL;
  814.  
  815.   /* If this word is at the start of the line, then it is a command
  816.      to complete.  Otherwise it is the name of a file in the current
  817.      directory. */
  818.   if (start == 0)
  819.     matches = completion_matches (text, command_generator);
  820.  
  821.   return (matches);
  822. @}
  823.  
  824. /* Generator function for command completion.  STATE lets us know whether
  825.    to start from scratch; without any state (i.e. STATE == 0), then we
  826.    start at the top of the list. */
  827. char *
  828. command_generator (text, state)
  829.      char *text;
  830.      int state;
  831. @{
  832.   static int list_index, len;
  833.   char *name;
  834.  
  835.   /* If this is a new word to complete, initialize now.  This includes
  836.      saving the length of TEXT for efficiency, and initializing the index
  837.      variable to 0. */
  838.   if (!state)
  839.     @{
  840.       list_index = 0;
  841.       len = strlen (text);
  842.     @}
  843.  
  844.   /* Return the next name which partially matches from the command list. */
  845.   while (name = commands[list_index].name)
  846.     @{
  847.       list_index++;
  848.  
  849.       if (strncmp (name, text, len) == 0)
  850.         return (name);
  851.     @}
  852.  
  853.   /* If no names matched, then return NULL. */
  854.   return ((char *)NULL);
  855. @}
  856. @page
  857. /* **************************************************************** */
  858. /*                                                                  */
  859. /*                       FileMan Commands                           */
  860. /*                                                                  */
  861. /* **************************************************************** */
  862.  
  863. /* String to pass to system ().  This is for the LIST, VIEW and RENAME
  864.    commands. */
  865. static char syscom[1024];
  866.  
  867. /* List the file(s) named in arg. */
  868. com_list (arg)
  869.      char *arg;
  870. @{
  871.   sprintf (syscom, "ls -FClg %s", arg);
  872.   system (syscom);
  873. @}
  874.  
  875. com_view (arg)
  876.      char *arg;
  877. @{
  878.   if (!valid_argument ("view", arg))
  879.     return;
  880.  
  881.   sprintf (syscom, "cat %s | more", arg);
  882.   system (syscom);
  883. @}
  884.  
  885. com_rename (arg)
  886.      char *arg;
  887. @{
  888.   too_dangerous ("rename");
  889. @}
  890.  
  891. com_stat (arg)
  892.      char *arg;
  893. @{
  894.   struct stat finfo;
  895.  
  896.   if (!valid_argument ("stat", arg))
  897.     return;
  898.  
  899.   if (stat (arg, &finfo) == -1)
  900.     @{
  901.       perror (arg);
  902.       return;
  903.     @}
  904.  
  905.   printf ("Statistics for `%s':\n", arg);
  906.  
  907.   printf ("%s has %d link%s, and is %d bytes in length.\n", arg,
  908.           finfo.st_nlink, (finfo.st_nlink == 1) ? "" : "s",  finfo.st_size);
  909.   printf ("      Created on: %s", ctime (&finfo.st_ctime));
  910.   printf ("  Last access at: %s", ctime (&finfo.st_atime));
  911.   printf ("Last modified at: %s", ctime (&finfo.st_mtime));
  912. @}
  913.  
  914. com_delete (arg)
  915.      char *arg;
  916. @{
  917.   too_dangerous ("delete");
  918. @}
  919.  
  920. /* Print out help for ARG, or for all of the commands if ARG is
  921.    not present. */
  922. com_help (arg)
  923.      char *arg;
  924. @{
  925.   register int i;
  926.   int printed = 0;
  927.  
  928.   for (i = 0; commands[i].name; i++)
  929.     @{
  930.       if (!*arg || (strcmp (arg, commands[i].name) == 0))
  931.         @{
  932.           printf ("%s\t\t%s.\n", commands[i].name, commands[i].doc);
  933.           printed++;
  934.         @}
  935.     @}
  936.  
  937.   if (!printed)
  938.     @{
  939.       printf ("No commands match `%s'.  Possibilties are:\n", arg);
  940.  
  941.       for (i = 0; commands[i].name; i++)
  942.         @{
  943.           /* Print in six columns. */
  944.           if (printed == 6)
  945.             @{
  946.               printed = 0;
  947.               printf ("\n");
  948.             @}
  949.  
  950.           printf ("%s\t", commands[i].name);
  951.           printed++;
  952.         @}
  953.  
  954.       if (printed)
  955.         printf ("\n");
  956.     @}
  957. @}
  958.  
  959. /* Change to the directory ARG. */
  960. com_cd (arg)
  961.      char *arg;
  962. @{
  963.   if (chdir (arg) == -1)
  964.     perror (arg);
  965.  
  966.   com_pwd ("");
  967. @}
  968.  
  969. /* Print out the current working directory. */
  970. com_pwd (ignore)
  971.      char *ignore;
  972. @{
  973.   char dir[1024];
  974.  
  975.   (void) getwd (dir);
  976.  
  977.   printf ("Current directory is %s\n", dir);
  978. @}
  979.  
  980. /* The user wishes to quit using this program.  Just set DONE non-zero. */
  981. com_quit (arg)
  982.      char *arg;
  983. @{
  984.   done = 1;
  985. @}
  986.  
  987. /* Function which tells you that you can't do this. */
  988. too_dangerous (caller)
  989.      char *caller;
  990. @{
  991.   fprintf (stderr,
  992.            "%s: Too dangerous for me to distribute.  Write it yourself.\n",
  993.            caller);
  994. @}
  995.  
  996. /* Return non-zero if ARG is a valid argument for CALLER, else print
  997.    an error message and return zero. */
  998. int
  999. valid_argument (caller, arg)
  1000.      char *caller, *arg;
  1001. @{
  1002.   if (!arg || !*arg)
  1003.     @{
  1004.       fprintf (stderr, "%s: Argument required.\n", caller);
  1005.       return (0);
  1006.     @}
  1007.  
  1008.   return (1);
  1009. @}
  1010. @end smallexample
  1011.