PageRenderTime 54ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/src/readline/history.c

https://bitbucket.org/ramcdougal/neuronrxd
C | 1713 lines | 1299 code | 192 blank | 222 comment | 186 complexity | 5734108b72c49be0f5d414a2c29b6056 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. #include <../../nrnconf.h>
  2. /* History.c -- standalone history library */
  3. /* Copyright (C) 1989 Free Software Foundation, Inc.
  4. This file contains the GNU History Library (the Library), a set of
  5. routines for managing the text of previously typed lines.
  6. The Library is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 1, or (at your option)
  9. any later version.
  10. The Library is distributed in the hope that it will be useful, but
  11. WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. General Public License for more details.
  14. The GNU General Public License is often shipped with GNU software, and
  15. is generally kept in a file called COPYING or LICENSE. If you do not
  16. have a copy of the license, write to the Free Software Foundation,
  17. 675 Mass Ave, Cambridge, MA 02139, USA. */
  18. /* The goal is to make the implementation transparent, so that you
  19. don't have to know what data types are used, just what functions
  20. you can call. I think I have done that. */
  21. #if SYSV
  22. #define rindex strrchr
  23. #define index strchr
  24. #endif
  25. #if __STDC__
  26. #include <string.h>
  27. #if HAVE_MALLOC_H
  28. #include <malloc.h>
  29. #endif
  30. #include <stdlib.h>
  31. #endif
  32. /* Remove these declarations when we have a complete libgnu.a. */
  33. #define STATIC_MALLOC
  34. #ifndef STATIC_MALLOC
  35. extern char *xmalloc (), *xrealloc ();
  36. #else
  37. static char *xmalloc (), *xrealloc ();
  38. #endif
  39. #include <errno.h>
  40. #include <stdio.h>
  41. #include <sys/types.h>
  42. #include <sys/file.h>
  43. #include <sys/stat.h>
  44. #include <fcntl.h>
  45. #ifdef HAVE_ALLOCA
  46. #ifdef HAVE_ALLOCA_H
  47. #include <alloca.h>
  48. #endif
  49. #define NO_ALLOCA 0
  50. #define Alloca alloca
  51. #else
  52. #define NO_ALLOCA 1
  53. #define Alloca malloc
  54. #endif
  55. #include "history.h"
  56. #ifndef savestring
  57. #define savestring(x) (char *)strcpy (xmalloc (1 + strlen (x)), (x))
  58. #endif
  59. #ifndef whitespace
  60. #define whitespace(c) (((c) == ' ') || ((c) == '\t'))
  61. #endif
  62. #ifndef digit
  63. #define digit(c) ((c) >= '0' && (c) <= '9')
  64. #endif
  65. #ifndef member
  66. #define member(c, s) ((c) ? index ((s), (c)) : 0)
  67. #endif
  68. /* **************************************************************** */
  69. /* */
  70. /* History Functions */
  71. /* */
  72. /* **************************************************************** */
  73. /* An array of HIST_ENTRY. This is where we store the history. */
  74. static HIST_ENTRY **the_history = (HIST_ENTRY **)NULL;
  75. /* Non-zero means that we have enforced a limit on the amount of
  76. history that we save. */
  77. int history_stifled = 0;
  78. /* If HISTORY_STIFLED is non-zero, then this is the maximum number of
  79. entries to remember. */
  80. int max_input_history;
  81. /* The current location of the interactive history pointer. Just makes
  82. life easier for outside callers. */
  83. static int history_offset = 0;
  84. /* The number of strings currently stored in the input_history list. */
  85. int history_length = 0;
  86. /* The current number of slots allocated to the input_history. */
  87. static int history_size = 0;
  88. /* The number of slots to increase the_history by. */
  89. #define DEFAULT_HISTORY_GROW_SIZE 50
  90. /* The character that represents the start of a history expansion
  91. request. This is usually `!'. */
  92. char history_expansion_char = '!';
  93. /* The character that invokes word substitution if found at the start of
  94. a line. This is usually `^'. */
  95. char history_subst_char = '^';
  96. /* During tokenization, if this character is seen as the first character
  97. of a word, then it, and all subsequent characters upto a newline are
  98. ignored. For a Bourne shell, this should be '#'. Bash special cases
  99. the interactive comment character to not be a comment delimiter. */
  100. char history_comment_char = '\0';
  101. /* The list of characters which inhibit the expansion of text if found
  102. immediately following history_expansion_char. */
  103. char *history_no_expand_chars = " \t\n\r=";
  104. /* The logical `base' of the history array. It defaults to 1. */
  105. int history_base = 1;
  106. /* Begin a session in which the history functions might be used. This
  107. initializes interactive variables. */
  108. void
  109. using_history ()
  110. {
  111. history_offset = history_length;
  112. }
  113. /* Return the number of bytes that the primary history entries are using.
  114. This just adds up the lengths of the_history->lines. */
  115. int
  116. history_total_bytes ()
  117. {
  118. register int i, result;
  119. for (i = 0; the_history && the_history[i]; i++)
  120. result += strlen (the_history[i]->line);
  121. return (result);
  122. }
  123. /* Place STRING at the end of the history list. The data field
  124. is set to NULL. */
  125. void
  126. add_history (string)
  127. char *string;
  128. {
  129. HIST_ENTRY *temp;
  130. if (history_stifled && (history_length == max_input_history))
  131. {
  132. register int i;
  133. /* If the history is stifled, and history_length is zero,
  134. and it equals max_input_history, we don't save items. */
  135. if (!history_length)
  136. return;
  137. /* If there is something in the slot, then remove it. */
  138. if (the_history[0])
  139. {
  140. free (the_history[0]->line);
  141. free (the_history[0]);
  142. }
  143. for (i = 0; i < history_length; i++)
  144. the_history[i] = the_history[i + 1];
  145. history_base++;
  146. }
  147. else
  148. {
  149. if (!history_size)
  150. {
  151. the_history = (HIST_ENTRY **)
  152. xmalloc ((history_size = DEFAULT_HISTORY_GROW_SIZE)
  153. * sizeof (HIST_ENTRY *));
  154. history_length = 1;
  155. }
  156. else
  157. {
  158. if (history_length == (history_size - 1))
  159. {
  160. the_history = (HIST_ENTRY **)
  161. xrealloc (the_history,
  162. ((history_size += DEFAULT_HISTORY_GROW_SIZE)
  163. * sizeof (HIST_ENTRY *)));
  164. }
  165. history_length++;
  166. }
  167. }
  168. temp = (HIST_ENTRY *)xmalloc (sizeof (HIST_ENTRY));
  169. temp->line = savestring (string);
  170. temp->data = (char *)NULL;
  171. the_history[history_length] = (HIST_ENTRY *)NULL;
  172. the_history[history_length - 1] = temp;
  173. }
  174. /* Make the history entry at WHICH have LINE and DATA. This returns
  175. the old entry so you can dispose of the data. In the case of an
  176. invalid WHICH, a NULL pointer is returned. */
  177. HIST_ENTRY *
  178. replace_history_entry (which, line, data)
  179. int which;
  180. char *line;
  181. char *data;
  182. {
  183. HIST_ENTRY *temp = (HIST_ENTRY *)xmalloc (sizeof (HIST_ENTRY));
  184. HIST_ENTRY *old_value;
  185. if (which >= history_length)
  186. return ((HIST_ENTRY *)NULL);
  187. old_value = the_history[which];
  188. temp->line = savestring (line);
  189. temp->data = data;
  190. the_history[which] = temp;
  191. return (old_value);
  192. }
  193. /* Returns the magic number which says what history element we are
  194. looking at now. In this implementation, it returns history_offset. */
  195. int
  196. where_history ()
  197. {
  198. return (history_offset);
  199. }
  200. /* Search the history for STRING, starting at history_offset.
  201. If DIRECTION < 0, then the search is through previous entries,
  202. else through subsequent. If the string is found, then
  203. current_history () is the history entry, and the value of this function
  204. is the offset in the line of that history entry that the string was
  205. found in. Otherwise, nothing is changed, and a -1 is returned. */
  206. int
  207. history_search (string, direction)
  208. char *string;
  209. int direction;
  210. {
  211. register int i = history_offset;
  212. register int reverse = (direction < 0);
  213. register char *line;
  214. register int index;
  215. int string_len = strlen (string);
  216. /* Take care of trivial cases first. */
  217. if (!history_length || ((i == history_length) && !reverse))
  218. return (-1);
  219. if (reverse && (i == history_length))
  220. i--;
  221. while (1)
  222. {
  223. /* Search each line in the history list for STRING. */
  224. /* At limit for direction? */
  225. if ((reverse && i < 0) ||
  226. (!reverse && i == history_length))
  227. return (-1);
  228. line = the_history[i]->line;
  229. index = strlen (line);
  230. /* If STRING is longer than line, no match. */
  231. if (string_len > index)
  232. goto next_line;
  233. /* Do the actual search. */
  234. if (reverse)
  235. {
  236. index -= string_len;
  237. while (index >= 0)
  238. {
  239. if (strncmp (string, line + index, string_len) == 0)
  240. {
  241. history_offset = i;
  242. return (index);
  243. }
  244. index--;
  245. }
  246. }
  247. else
  248. {
  249. register int limit = (string_len - index) + 1;
  250. index = 0;
  251. while (index < limit)
  252. {
  253. if (strncmp (string, line + index, string_len) == 0)
  254. {
  255. history_offset = i;
  256. return (index);
  257. }
  258. index++;
  259. }
  260. }
  261. next_line:
  262. if (reverse)
  263. i--;
  264. else
  265. i++;
  266. }
  267. }
  268. /* Remove history element WHICH from the history. The removed
  269. element is returned to you so you can free the line, data,
  270. and containing structure. */
  271. HIST_ENTRY *
  272. remove_history (which)
  273. int which;
  274. {
  275. HIST_ENTRY *return_value;
  276. if (which >= history_length || !history_length)
  277. return_value = (HIST_ENTRY *)NULL;
  278. else
  279. {
  280. register int i;
  281. return_value = the_history[which];
  282. for (i = which; i < history_length; i++)
  283. the_history[i] = the_history[i + 1];
  284. history_length--;
  285. }
  286. return (return_value);
  287. }
  288. /* Stifle the history list, remembering only MAX number of lines. */
  289. void
  290. stifle_history (max)
  291. int max;
  292. {
  293. if (history_length > max)
  294. {
  295. register int i, j;
  296. /* This loses because we cannot free the data. */
  297. for (i = 0; i < (history_length - max); i++)
  298. {
  299. free (the_history[i]->line);
  300. free (the_history[i]);
  301. }
  302. history_base = i;
  303. for (j = 0, i = history_length - max; j < max; i++, j++)
  304. the_history[j] = the_history[i];
  305. the_history[j] = (HIST_ENTRY *)NULL;
  306. history_length = j;
  307. }
  308. history_stifled = 1;
  309. max_input_history = max;
  310. }
  311. /* Stop stifling the history. This returns the previous amount the history
  312. was stifled by. The value is positive if the history was stifled, negative
  313. if it wasn't. */
  314. int
  315. unstifle_history ()
  316. {
  317. int result = max_input_history;
  318. if (history_stifled)
  319. {
  320. result = - result;
  321. history_stifled = 0;
  322. }
  323. return (result);
  324. }
  325. /* Return the string that should be used in the place of this
  326. filename. This only matters when you don't specify the
  327. filename to read_history (), or write_history (). */
  328. static char *
  329. history_filename (filename)
  330. char *filename;
  331. {
  332. char *return_val = filename ? savestring (filename) : (char *)NULL;
  333. if (!return_val)
  334. {
  335. char *home = (char *)getenv ("HOME");
  336. if (!home) home = ".";
  337. return_val = (char *)xmalloc (2 + strlen (home) + strlen (".history"));
  338. sprintf (return_val, "%s/.history", home);
  339. }
  340. return (return_val);
  341. }
  342. /* Add the contents of FILENAME to the history list, a line at a time.
  343. If FILENAME is NULL, then read from ~/.history. Returns 0 if
  344. successful, or errno if not. */
  345. int
  346. read_history (filename)
  347. char *filename;
  348. {
  349. return (read_history_range (filename, 0, -1));
  350. }
  351. /* Read a range of lines from FILENAME, adding them to the history list.
  352. Start reading at the FROM'th line and end at the TO'th. If FROM
  353. is zero, start at the beginning. If TO is less than FROM, read
  354. until the end of the file. If FILENAME is NULL, then read from
  355. ~/.history. Returns 0 if successful, or errno if not. */
  356. int
  357. read_history_range (filename, from, to)
  358. char *filename;
  359. int from, to;
  360. {
  361. register int line_start, line_end;
  362. char *input, *buffer = (char *)NULL;
  363. int file, current_line, done;
  364. struct stat finfo;
  365. input = history_filename (filename);
  366. file = open (input, O_RDONLY, 0666);
  367. if ((file < 0) ||
  368. (stat (input, &finfo) == -1))
  369. goto error_and_exit;
  370. buffer = (char *)xmalloc (finfo.st_size + 1);
  371. if (read (file, buffer, finfo.st_size) != finfo.st_size)
  372. error_and_exit:
  373. {
  374. if (file >= 0)
  375. close (file);
  376. if (buffer)
  377. free (buffer);
  378. return (errno);
  379. }
  380. close (file);
  381. /* Set TO to larger than end of file if negative. */
  382. if (to < 0)
  383. to = finfo.st_size;
  384. /* Start at beginning of file, work to end. */
  385. line_start = line_end = current_line = 0;
  386. /* Skip lines until we are at FROM. */
  387. while (line_start < finfo.st_size && current_line < from)
  388. {
  389. for (line_end = line_start; line_end < finfo.st_size; line_end++)
  390. if (buffer[line_end] == '\n')
  391. {
  392. current_line++;
  393. line_start = line_end + 1;
  394. if (current_line == from)
  395. break;
  396. }
  397. }
  398. /* If there are lines left to gobble, then gobble them now. */
  399. for (line_end = line_start; line_end < finfo.st_size; line_end++)
  400. if (buffer[line_end] == '\n')
  401. {
  402. buffer[line_end] = '\0';
  403. if (buffer[line_start])
  404. add_history (buffer + line_start);
  405. current_line++;
  406. if (current_line >= to)
  407. break;
  408. line_start = line_end + 1;
  409. }
  410. return (0);
  411. }
  412. /* Truncate the history file FNAME, leaving only LINES trailing lines.
  413. If FNAME is NULL, then use ~/.history. */
  414. history_truncate_file (fname, lines)
  415. char *fname;
  416. register int lines;
  417. {
  418. register int i;
  419. int file;
  420. char *buffer = (char *)NULL, *filename;
  421. struct stat finfo;
  422. filename = history_filename (fname);
  423. if (stat (filename, &finfo) == -1)
  424. goto truncate_exit;
  425. file = open (filename, O_RDONLY, 066);
  426. if (file == -1)
  427. goto truncate_exit;
  428. buffer = (char *)xmalloc (finfo.st_size + 1);
  429. read (file, buffer, finfo.st_size);
  430. close (file);
  431. /* Count backwards from the end of buffer until we have passed
  432. LINES lines. */
  433. for (i = finfo.st_size; lines && i; i--)
  434. {
  435. if (buffer[i] == '\n')
  436. lines--;
  437. }
  438. /* If there are fewer lines in the file than we want to truncate to,
  439. then we are all done. */
  440. if (!i)
  441. goto truncate_exit;
  442. /* Otherwise, write from the start of this line until the end of the
  443. buffer. */
  444. for (--i; i; i--)
  445. if (buffer[i] == '\n')
  446. {
  447. i++;
  448. break;
  449. }
  450. file = open (filename, O_WRONLY | O_TRUNC | O_CREAT, 0666);
  451. if (file == -1)
  452. goto truncate_exit;
  453. write (file, buffer + i, finfo.st_size - i);
  454. close (file);
  455. truncate_exit:
  456. if (buffer)
  457. free (buffer);
  458. free (filename);
  459. }
  460. #define HISTORY_APPEND 0
  461. #define HISTORY_OVERWRITE 1
  462. /* Workhorse function for writing history. Writes NELEMENT entries
  463. from the history list to FILENAME. OVERWRITE is non-zero if you
  464. wish to replace FILENAME with the entries. */
  465. static int
  466. history_do_write (filename, nelements, overwrite)
  467. char *filename;
  468. int nelements, overwrite;
  469. {
  470. register int i;
  471. char *output = history_filename (filename);
  472. int file, mode;
  473. char cr = '\n';
  474. if (overwrite)
  475. mode = O_WRONLY | O_CREAT | O_TRUNC;
  476. else
  477. mode = O_WRONLY | O_APPEND;
  478. if ((file = open (output, mode, 0666)) == -1)
  479. return (errno);
  480. if (nelements > history_length)
  481. nelements = history_length;
  482. for (i = history_length - nelements; i < history_length; i++)
  483. {
  484. if (write (file, the_history[i]->line, strlen (the_history[i]->line)) < 0)
  485. break;
  486. if (write (file, &cr, 1) < 0)
  487. break;
  488. }
  489. close (file);
  490. return (0);
  491. }
  492. /* Append NELEMENT entries to FILENAME. The entries appended are from
  493. the end of the list minus NELEMENTs up to the end of the list. */
  494. int
  495. append_history (nelements, filename)
  496. int nelements;
  497. char *filename;
  498. {
  499. return (history_do_write (filename, nelements, HISTORY_APPEND));
  500. }
  501. /* Overwrite FILENAME with the current history. If FILENAME is NULL,
  502. then write the history list to ~/.history. Values returned
  503. are as in read_history ().*/
  504. int
  505. write_history (filename)
  506. char *filename;
  507. {
  508. return (history_do_write (filename, history_length, HISTORY_OVERWRITE));
  509. }
  510. /* Return the history entry at the current position, as determined by
  511. history_offset. If there is no entry there, return a NULL pointer. */
  512. HIST_ENTRY *
  513. current_history ()
  514. {
  515. if ((history_offset == history_length) || !the_history)
  516. return ((HIST_ENTRY *)NULL);
  517. else
  518. return (the_history[history_offset]);
  519. }
  520. /* Back up history_offset to the previous history entry, and return
  521. a pointer to that entry. If there is no previous entry then return
  522. a NULL pointer. */
  523. HIST_ENTRY *
  524. previous_history ()
  525. {
  526. if (!history_offset)
  527. return ((HIST_ENTRY *)NULL);
  528. else
  529. return (the_history[--history_offset]);
  530. }
  531. /* Move history_offset forward to the next history entry, and return
  532. a pointer to that entry. If there is no next entry then return a
  533. NULL pointer. */
  534. HIST_ENTRY *
  535. next_history ()
  536. {
  537. if (history_offset == history_length)
  538. return ((HIST_ENTRY *)NULL);
  539. else
  540. return (the_history[++history_offset]);
  541. }
  542. /* Return the current history array. The caller has to be carefull, since this
  543. is the actual array of data, and could be bashed or made corrupt easily.
  544. The array is terminated with a NULL pointer. */
  545. HIST_ENTRY **
  546. history_list ()
  547. {
  548. return (the_history);
  549. }
  550. /* Return the history entry which is logically at OFFSET in the history array.
  551. OFFSET is relative to history_base. */
  552. HIST_ENTRY *
  553. history_get (offset)
  554. int offset;
  555. {
  556. int index = offset - history_base;
  557. if (index >= history_length ||
  558. index < 0 ||
  559. !the_history)
  560. return ((HIST_ENTRY *)NULL);
  561. return (the_history[index]);
  562. }
  563. /* Search for STRING in the history list. DIR is < 0 for searching
  564. backwards. POS is an absolute index into the history list at
  565. which point to begin searching. */
  566. int
  567. history_search_pos (string, dir, pos)
  568. char *string;
  569. int dir, pos;
  570. {
  571. int ret, old = where_history ();
  572. history_set_pos (pos);
  573. if (history_search (string, dir) == -1)
  574. {
  575. history_set_pos (old);
  576. return (-1);
  577. }
  578. ret = where_history ();
  579. history_set_pos (old);
  580. return ret;
  581. }
  582. /* Make the current history item be the one at POS, an absolute index.
  583. Returns zero if POS is out of range, else non-zero. */
  584. int
  585. history_set_pos (pos)
  586. int pos;
  587. {
  588. if (pos > history_length || pos < 0 || !the_history)
  589. return (0);
  590. history_offset = pos;
  591. return (1);
  592. }
  593. /* **************************************************************** */
  594. /* */
  595. /* History Expansion */
  596. /* */
  597. /* **************************************************************** */
  598. /* Hairy history expansion on text, not tokens. This is of general
  599. use, and thus belongs in this library. */
  600. /* The last string searched for in a !?string? search. */
  601. static char *search_string = (char *)NULL;
  602. /* Return the event specified at TEXT + OFFSET modifying OFFSET to
  603. point to after the event specifier. Just a pointer to the history
  604. line is returned; NULL is returned in the event of a bad specifier.
  605. You pass STRING with *INDEX equal to the history_expansion_char that
  606. begins this specification.
  607. DELIMITING_QUOTE is a character that is allowed to end the string
  608. specification for what to search for in addition to the normal
  609. characters `:', ` ', `\t', `\n', and sometimes `?'.
  610. So you might call this function like:
  611. line = get_history_event ("!echo:p", &index, 0); */
  612. char *
  613. get_history_event (string, caller_index, delimiting_quote)
  614. char *string;
  615. int *caller_index;
  616. int delimiting_quote;
  617. {
  618. register int i = *caller_index;
  619. int which, sign = 1;
  620. HIST_ENTRY *entry;
  621. /* The event can be specified in a number of ways.
  622. !! the previous command
  623. !n command line N
  624. !-n current command-line minus N
  625. !str the most recent command starting with STR
  626. !?str[?]
  627. the most recent command containing STR
  628. All values N are determined via HISTORY_BASE. */
  629. if (string[i] != history_expansion_char)
  630. return ((char *)NULL);
  631. /* Move on to the specification. */
  632. i++;
  633. /* Handle !! case. */
  634. if (string[i] == history_expansion_char)
  635. {
  636. i++;
  637. which = history_base + (history_length - 1);
  638. *caller_index = i;
  639. goto get_which;
  640. }
  641. /* Hack case of numeric line specification. */
  642. read_which:
  643. if (string[i] == '-')
  644. {
  645. sign = -1;
  646. i++;
  647. }
  648. if (digit (string[i]))
  649. {
  650. int start = i;
  651. /* Get the extent of the digits. */
  652. for (; digit (string[i]); i++);
  653. /* Get the digit value. */
  654. sscanf (string + start, "%d", &which);
  655. *caller_index = i;
  656. if (sign < 0)
  657. which = (history_length + history_base) - which;
  658. get_which:
  659. if (entry = history_get (which))
  660. return (entry->line);
  661. return ((char *)NULL);
  662. }
  663. /* This must be something to search for. If the spec begins with
  664. a '?', then the string may be anywhere on the line. Otherwise,
  665. the string must be found at the start of a line. */
  666. {
  667. int index;
  668. char *temp;
  669. int substring_okay = 0;
  670. if (string[i] == '?')
  671. {
  672. substring_okay++;
  673. i++;
  674. }
  675. for (index = i; string[i]; i++)
  676. if (whitespace (string[i]) ||
  677. string[i] == '\n' ||
  678. string[i] == ':' ||
  679. (substring_okay && string[i] == '?') ||
  680. string[i] == delimiting_quote)
  681. break;
  682. temp = (char *)Alloca (1 + (i - index));
  683. strncpy (temp, &string[index], (i - index));
  684. temp[i - index] = '\0';
  685. if (string[i] == '?')
  686. i++;
  687. *caller_index = i;
  688. search_again:
  689. index = history_search (temp, -1);
  690. if (index < 0)
  691. search_lost:
  692. {
  693. history_offset = history_length;
  694. #if NO_ALLOCA
  695. free(temp);
  696. #endif
  697. return ((char *)NULL);
  698. }
  699. if (index == 0 || substring_okay ||
  700. (strncmp (temp, the_history[history_offset]->line,
  701. strlen (temp)) == 0))
  702. {
  703. search_won:
  704. entry = current_history ();
  705. history_offset = history_length;
  706. /* If this was a substring search, then remember the string that
  707. we matched for word substitution. */
  708. if (substring_okay)
  709. {
  710. if (search_string)
  711. free (search_string);
  712. search_string = savestring (temp);
  713. }
  714. #if NO_ALLOCA
  715. free(temp);
  716. #endif
  717. return (entry->line);
  718. }
  719. if (history_offset)
  720. history_offset--;
  721. else
  722. goto search_lost;
  723. goto search_again;
  724. }
  725. }
  726. /* Expand the string STRING, placing the result into OUTPUT, a pointer
  727. to a string. Returns:
  728. 0) If no expansions took place (or, if the only change in
  729. the text was the de-slashifying of the history expansion
  730. character)
  731. 1) If expansions did take place
  732. -1) If there was an error in expansion.
  733. If an error ocurred in expansion, then OUTPUT contains a descriptive
  734. error message. */
  735. int
  736. history_expand (string, output)
  737. char *string;
  738. char **output;
  739. {
  740. register int j, l = strlen (string);
  741. int i, word_spec_error = 0;
  742. int cc, modified = 0;
  743. char *word_spec, *event;
  744. int starting_index, only_printing = 0, substitute_globally = 0;
  745. char *get_history_word_specifier (), *rindex ();
  746. /* The output string, and its length. */
  747. int len = 0;
  748. char *result = (char *)NULL;
  749. /* Used in add_string; */
  750. char *temp, tt[2], tbl[3];
  751. #if NO_ALLOCA
  752. #define USED_SIZE 128
  753. char ** saved_alloc;
  754. int allocs_used = 0;
  755. int allocs_alloced = USED_SIZE;
  756. saved_alloc = (char **) malloc(USED_SIZE * sizeof(char *));
  757. #define save_an_alloc(ptr) \
  758. if (allocs_used >= allocs_alloced) \
  759. saved_alloc = (char **) \
  760. realloc(saved_alloc, (sizeof(char *) * (allocs_alloced += USED_SIZE)));\
  761. saved_alloc[allocs_used++] = ptr
  762. #define free_the_allocs() \
  763. while (allocs_used > 0) \
  764. free(saved_alloc[--allocs_used]); \
  765. free(saved_alloc)
  766. #endif
  767. /* Prepare the buffer for printing error messages. */
  768. result = (char *)xmalloc (len = 255);
  769. result[0] = tt[1] = tbl[2] = '\0';
  770. tbl[0] = '\\';
  771. tbl[1] = history_expansion_char;
  772. /* Grovel the string. Only backslash can quote the history escape
  773. character. We also handle arg specifiers. */
  774. /* Before we grovel forever, see if the history_expansion_char appears
  775. anywhere within the text. */
  776. /* The quick substitution character is a history expansion all right. That
  777. is to say, "^this^that^" is equivalent to "!!:s^this^that^", and in fact,
  778. that is the substitution that we do. */
  779. if (string[0] == history_subst_char)
  780. {
  781. char *format_string = (char *)Alloca (10 + strlen (string));
  782. #if NO_ALLOCA
  783. save_an_alloc(format_string);
  784. #endif
  785. sprintf (format_string, "%c%c:s%s",
  786. history_expansion_char, history_expansion_char,
  787. string);
  788. string = format_string;
  789. l += 4;
  790. goto grovel;
  791. }
  792. /* If not quick substitution, still maybe have to do expansion. */
  793. /* `!' followed by one of the characters in history_no_expand_chars
  794. is NOT an expansion. */
  795. for (i = 0; string[i]; i++)
  796. if (string[i] == history_expansion_char)
  797. if (!string[i + 1] || member (string[i + 1], history_no_expand_chars))
  798. continue;
  799. else
  800. goto grovel;
  801. free (result);
  802. *output = savestring (string);
  803. return (0);
  804. grovel:
  805. for (i = j = 0; i < l; i++)
  806. {
  807. int tchar = string[i];
  808. if (tchar == history_expansion_char)
  809. tchar = -3;
  810. switch (tchar)
  811. {
  812. case '\\':
  813. if (string[i + 1] == history_expansion_char)
  814. {
  815. i++;
  816. temp = tbl;
  817. goto do_add;
  818. }
  819. else
  820. goto add_char;
  821. /* case history_expansion_char: */
  822. case -3:
  823. starting_index = i + 1;
  824. cc = string[i + 1];
  825. /* If the history_expansion_char is followed by one of the
  826. characters in history_no_expand_chars, then it is not a
  827. candidate for expansion of any kind. */
  828. if (member (cc, history_no_expand_chars))
  829. goto add_char;
  830. /* There is something that is listed as a `word specifier' in csh
  831. documentation which means `the expanded text to this point'.
  832. That is not a word specifier, it is an event specifier. */
  833. if (cc == '#')
  834. goto hack_pound_sign;
  835. /* If it is followed by something that starts a word specifier,
  836. then !! is implied as the event specifier. */
  837. if (member (cc, ":$*%^"))
  838. {
  839. char fake_s[3];
  840. int fake_i = 0;
  841. i++;
  842. fake_s[0] = fake_s[1] = history_expansion_char;
  843. fake_s[2] = '\0';
  844. event = get_history_event (fake_s, &fake_i, 0);
  845. }
  846. else
  847. {
  848. int quoted_search_delimiter = 0;
  849. /* If the character before this `!' is a double or single
  850. quote, then this expansion takes place inside of the
  851. quoted string. If we have to search for some text ("!foo"),
  852. allow the delimiter to end the search string. */
  853. if (i && (string[i - 1] == '\'' || string[i - 1] == '"'))
  854. quoted_search_delimiter = string[i - 1];
  855. event = get_history_event (string, &i, quoted_search_delimiter);
  856. }
  857. if (!event)
  858. event_not_found:
  859. {
  860. int l = 1 + (i - starting_index);
  861. temp = (char *)Alloca (1 + l);
  862. #if NO_ALLOCA
  863. save_an_alloc(temp);
  864. #endif
  865. strncpy (temp, string + starting_index, l);
  866. temp[l - 1] = 0;
  867. sprintf (result, "%s: %s.", temp,
  868. word_spec_error ? "Bad word specifier" : "Event not found");
  869. error_exit:
  870. *output = result;
  871. #if NO_ALLOCA
  872. free_the_allocs();
  873. #endif
  874. return (-1);
  875. }
  876. /* If a word specifier is found, then do what that requires. */
  877. starting_index = i;
  878. word_spec = get_history_word_specifier (string, event, &i);
  879. /* There is no such thing as a `malformed word specifier'. However,
  880. it is possible for a specifier that has no match. In that case,
  881. we complain. */
  882. if (word_spec == (char *)-1)
  883. bad_word_spec:
  884. {
  885. word_spec_error++;
  886. goto event_not_found;
  887. }
  888. /* If no word specifier, than the thing of interest was the event. */
  889. if (!word_spec)
  890. temp = event;
  891. else
  892. {
  893. temp = (char *)Alloca (1 + strlen (word_spec));
  894. #if NO_ALLOCA
  895. save_an_alloc(temp);
  896. #endif
  897. strcpy (temp, word_spec);
  898. free (word_spec);
  899. }
  900. /* Perhaps there are other modifiers involved. Do what they say. */
  901. hack_specials:
  902. if (string[i] == ':')
  903. {
  904. char *tstr;
  905. switch (string[i + 1])
  906. {
  907. /* :p means make this the last executed line. So we
  908. return an error state after adding this line to the
  909. history. */
  910. case 'p':
  911. only_printing++;
  912. goto next_special;
  913. /* :t discards all but the last part of the pathname. */
  914. case 't':
  915. tstr = rindex (temp, '/');
  916. if (tstr)
  917. temp = ++tstr;
  918. goto next_special;
  919. /* :h discards the last part of a pathname. */
  920. case 'h':
  921. tstr = rindex (temp, '/');
  922. if (tstr)
  923. *tstr = '\0';
  924. goto next_special;
  925. /* :r discards the suffix. */
  926. case 'r':
  927. tstr = rindex (temp, '.');
  928. if (tstr)
  929. *tstr = '\0';
  930. goto next_special;
  931. /* :e discards everything but the suffix. */
  932. case 'e':
  933. tstr = rindex (temp, '.');
  934. if (tstr)
  935. temp = tstr;
  936. goto next_special;
  937. /* :s/this/that substitutes `this' for `that'. */
  938. /* :gs/this/that substitutes `this' for `that' globally. */
  939. case 'g':
  940. if (string[i + 2] == 's')
  941. {
  942. i++;
  943. substitute_globally = 1;
  944. goto substitute;
  945. }
  946. else
  947. case 's':
  948. substitute:
  949. {
  950. char *this, *that, *new_event;
  951. int delimiter = 0;
  952. int si, l_this, l_that, l_temp = strlen (temp);
  953. if (i + 2 < strlen (string))
  954. delimiter = string[i + 2];
  955. if (!delimiter)
  956. break;
  957. i += 3;
  958. /* Get THIS. */
  959. for (si = i; string[si] && string[si] != delimiter; si++);
  960. l_this = (si - i);
  961. this = (char *)Alloca (1 + l_this);
  962. #if NO_ALLOCA
  963. save_an_alloc(this);
  964. #endif
  965. strncpy (this, string + i, l_this);
  966. this[l_this] = '\0';
  967. i = si;
  968. if (string[si])
  969. i++;
  970. /* Get THAT. */
  971. for (si = i; string[si] && string[si] != delimiter; si++);
  972. l_that = (si - i);
  973. that = (char *)Alloca (1 + l_that);
  974. #if NO_ALLOCA
  975. save_an_alloc(that);
  976. #endif
  977. strncpy (that, string + i, l_that);
  978. that[l_that] = '\0';
  979. i = si;
  980. if (string[si]) i++;
  981. /* Ignore impossible cases. */
  982. if (l_this > l_temp)
  983. goto cant_substitute;
  984. /* Find the first occurrence of THIS in TEMP. */
  985. si = 0;
  986. for (; (si + l_this) <= l_temp; si++)
  987. if (strncmp (temp + si, this, l_this) == 0)
  988. {
  989. new_event =
  990. (char *)Alloca (1 + (l_that - l_this) + l_temp);
  991. #if NO_ALLOCA
  992. save_an_alloc(new_event);
  993. #endif
  994. strncpy (new_event, temp, si);
  995. strncpy (new_event + si, that, l_that);
  996. strncpy (new_event + si + l_that,
  997. temp + si + l_this,
  998. l_temp - (si + l_this));
  999. new_event[(l_that - l_this) + l_temp] = '\0';
  1000. temp = new_event;
  1001. if (substitute_globally)
  1002. {
  1003. si += l_that;
  1004. l_temp = strlen (temp);
  1005. substitute_globally++;
  1006. continue;
  1007. }
  1008. goto hack_specials;
  1009. }
  1010. cant_substitute:
  1011. if (substitute_globally > 1)
  1012. {
  1013. substitute_globally = 0;
  1014. goto hack_specials;
  1015. }
  1016. goto event_not_found;
  1017. }
  1018. /* :# is the line so far. Note that we have to
  1019. alloca () it since RESULT could be realloc ()'ed
  1020. below in add_string. */
  1021. case '#':
  1022. hack_pound_sign:
  1023. if (result)
  1024. {
  1025. temp = (char *)Alloca (1 + strlen (result));
  1026. #if NO_ALLOCA
  1027. save_an_alloc(temp);
  1028. #endif
  1029. strcpy (temp, result);
  1030. }
  1031. else
  1032. temp = "";
  1033. next_special:
  1034. i += 2;
  1035. goto hack_specials;
  1036. }
  1037. }
  1038. /* Believe it or not, we have to back the pointer up by one. */
  1039. --i;
  1040. goto add_string;
  1041. /* A regular character. Just add it to the output string. */
  1042. default:
  1043. add_char:
  1044. tt[0] = string[i];
  1045. temp = tt;
  1046. goto do_add;
  1047. add_string:
  1048. modified++;
  1049. do_add:
  1050. j += strlen (temp);
  1051. while (j > len)
  1052. result = (char *)xrealloc (result, (len += 255));
  1053. strcpy (result + (j - strlen (temp)), temp);
  1054. }
  1055. }
  1056. *output = result;
  1057. if (only_printing)
  1058. {
  1059. add_history (result);
  1060. #if NO_ALLOCA
  1061. free_the_allocs();
  1062. #endif
  1063. return (-1);
  1064. }
  1065. #if NO_ALLOCA
  1066. free_the_allocs();
  1067. #endif
  1068. return (modified != 0);
  1069. }
  1070. /* Return a consed string which is the word specified in SPEC, and found
  1071. in FROM. NULL is returned if there is no spec. -1 is returned if
  1072. the word specified cannot be found. CALLER_INDEX is the offset in
  1073. SPEC to start looking; it is updated to point to just after the last
  1074. character parsed. */
  1075. char *
  1076. get_history_word_specifier (spec, from, caller_index)
  1077. char *spec, *from;
  1078. int *caller_index;
  1079. {
  1080. register int i = *caller_index;
  1081. int first, last;
  1082. int expecting_word_spec = 0;
  1083. char *history_arg_extract ();
  1084. /* The range of words to return doesn't exist yet. */
  1085. first = last = 0;
  1086. /* If we found a colon, then this *must* be a word specification. If
  1087. it isn't, then it is an error. */
  1088. if (spec[i] == ':')
  1089. i++, expecting_word_spec++;
  1090. /* Handle special cases first. */
  1091. /* `%' is the word last searched for. */
  1092. if (spec[i] == '%')
  1093. {
  1094. *caller_index = i + 1;
  1095. if (search_string)
  1096. return (savestring (search_string));
  1097. else
  1098. return (savestring (""));
  1099. }
  1100. /* `*' matches all of the arguments, but not the command. */
  1101. if (spec[i] == '*')
  1102. {
  1103. char *star_result;
  1104. *caller_index = i + 1;
  1105. star_result = history_arg_extract (1, '$', from);
  1106. if (!star_result)
  1107. star_result = savestring ("");
  1108. return (star_result);
  1109. }
  1110. /* `$' is last arg. */
  1111. if (spec[i] == '$')
  1112. {
  1113. *caller_index = i + 1;
  1114. return (history_arg_extract ('$', '$', from));
  1115. }
  1116. /* Try to get FIRST and LAST figured out. */
  1117. if (spec[i] == '-' || spec[i] == '^')
  1118. {
  1119. first = 1;
  1120. goto get_last;
  1121. }
  1122. get_first:
  1123. if (digit (spec[i]) && expecting_word_spec)
  1124. {
  1125. sscanf (spec + i, "%d", &first);
  1126. for (; digit (spec[i]); i++);
  1127. }
  1128. else
  1129. return ((char *)NULL);
  1130. get_last:
  1131. if (spec[i] == '^')
  1132. {
  1133. i++;
  1134. last = 1;
  1135. goto get_args;
  1136. }
  1137. if (spec[i] != '-')
  1138. {
  1139. last = first;
  1140. goto get_args;
  1141. }
  1142. i++;
  1143. if (digit (spec[i]))
  1144. {
  1145. sscanf (spec + i, "%d", &last);
  1146. for (; digit (spec[i]); i++);
  1147. }
  1148. else
  1149. if (spec[i] == '$')
  1150. {
  1151. i++;
  1152. last = '$';
  1153. }
  1154. get_args:
  1155. {
  1156. char *result = (char *)NULL;
  1157. *caller_index = i;
  1158. if (last >= first)
  1159. result = history_arg_extract (first, last, from);
  1160. if (result)
  1161. return (result);
  1162. else
  1163. return ((char *)-1);
  1164. }
  1165. }
  1166. /* Extract the args specified, starting at FIRST, and ending at LAST.
  1167. The args are taken from STRING. If either FIRST or LAST is < 0,
  1168. then make that arg count from the right (subtract from the number of
  1169. tokens, so that FIRST = -1 means the next to last token on the line). */
  1170. char *
  1171. history_arg_extract (first, last, string)
  1172. int first, last;
  1173. char *string;
  1174. {
  1175. register int i, len;
  1176. char *result = (char *)NULL;
  1177. int size = 0, offset = 0;
  1178. char **history_tokenize (), **list;
  1179. if (!(list = history_tokenize (string)))
  1180. return ((char *)NULL);
  1181. for (len = 0; list[len]; len++);
  1182. if (last < 0)
  1183. last = len + last - 1;
  1184. if (first < 0)
  1185. first = len + first - 1;
  1186. if (last == '$')
  1187. last = len - 1;
  1188. if (first == '$')
  1189. first = len - 1;
  1190. last++;
  1191. if (first > len || last > len || first < 0 || last < 0)
  1192. result = ((char *)NULL);
  1193. else
  1194. {
  1195. for (i = first; i < last; i++)
  1196. {
  1197. int l = strlen (list[i]);
  1198. if (!result)
  1199. result = (char *)xmalloc ((size = (2 + l)));
  1200. else
  1201. result = (char *)xrealloc (result, (size += (2 + l)));
  1202. strcpy (result + offset, list[i]);
  1203. offset += l;
  1204. if (i + 1 < last)
  1205. {
  1206. strcpy (result + offset, " ");
  1207. offset++;
  1208. }
  1209. }
  1210. }
  1211. for (i = 0; i < len; i++)
  1212. free (list[i]);
  1213. free (list);
  1214. return (result);
  1215. }
  1216. #define slashify_in_quotes "\\`\"$"
  1217. /* Return an array of tokens, much as the shell might. The tokens are
  1218. parsed out of STRING. */
  1219. char **
  1220. history_tokenize (string)
  1221. char *string;
  1222. {
  1223. char **result = (char **)NULL;
  1224. register int i, start, result_index, size;
  1225. int len;
  1226. i = result_index = size = 0;
  1227. /* Get a token, and stuff it into RESULT. The tokens are split
  1228. exactly where the shell would split them. */
  1229. get_token:
  1230. /* Skip leading whitespace. */
  1231. for (; string[i] && whitespace(string[i]); i++);
  1232. start = i;
  1233. if (!string[i] || string[i] == history_comment_char)
  1234. return (result);
  1235. if (member (string[i], "()\n")) {
  1236. i++;
  1237. goto got_token;
  1238. }
  1239. if (member (string[i], "<>;&|")) {
  1240. int peek = string[i + 1];
  1241. if (peek == string[i]) {
  1242. if (peek == '<') {
  1243. if (string[1 + 2] == '-')
  1244. i++;
  1245. i += 2;
  1246. goto got_token;
  1247. }
  1248. if (member (peek, ">:&|")) {
  1249. i += 2;
  1250. goto got_token;
  1251. }
  1252. } else {
  1253. if ((peek == '&' &&
  1254. (string[i] == '>' || string[i] == '<')) ||
  1255. ((peek == '>') &&
  1256. (string[i] == '&'))) {
  1257. i += 2;
  1258. goto got_token;
  1259. }
  1260. }
  1261. i++;
  1262. goto got_token;
  1263. }
  1264. /* Get word from string + i; */
  1265. {
  1266. int delimiter = 0;
  1267. if (member (string[i], "\"'`"))
  1268. delimiter = string[i++];
  1269. for (;string[i]; i++) {
  1270. if (string[i] == '\\') {
  1271. if (string[i + 1] == '\n') {
  1272. i++;
  1273. continue;
  1274. } else {
  1275. if (delimiter != '\'')
  1276. if ((delimiter != '"') ||
  1277. (member (string[i], slashify_in_quotes))) {
  1278. i++;
  1279. continue;
  1280. }
  1281. }
  1282. }
  1283. if (delimiter && string[i] == delimiter) {
  1284. delimiter = 0;
  1285. continue;
  1286. }
  1287. if (!delimiter && (member (string[i], " \t\n;&()|<>")))
  1288. goto got_token;
  1289. if (!delimiter && member (string[i], "\"'`")) {
  1290. delimiter = string[i];
  1291. continue;
  1292. }
  1293. }
  1294. got_token:
  1295. len = i - start;
  1296. if (result_index + 2 >= size) {
  1297. if (!size)
  1298. result = (char **)xmalloc ((size = 10) * (sizeof (char *)));
  1299. else
  1300. result =
  1301. (char **)xrealloc (result, ((size += 10) * (sizeof (char *))));
  1302. }
  1303. result[result_index] = (char *)xmalloc (1 + len);
  1304. strncpy (result[result_index], string + start, len);
  1305. result[result_index][len] = '\0';
  1306. result_index++;
  1307. result[result_index] = (char *)NULL;
  1308. }
  1309. if (string[i])
  1310. goto get_token;
  1311. return (result);
  1312. }
  1313. #if defined (STATIC_MALLOC)
  1314. /* **************************************************************** */
  1315. /* */
  1316. /* xmalloc and xrealloc () */
  1317. /* */
  1318. /* **************************************************************** */
  1319. static void memory_error_and_abort ();
  1320. static char *
  1321. xmalloc (bytes)
  1322. int bytes;
  1323. {
  1324. char *temp = (char *)malloc (bytes);
  1325. if (!temp)
  1326. memory_error_and_abort ();
  1327. return (temp);
  1328. }
  1329. static char *
  1330. xrealloc (pointer, bytes)
  1331. char *pointer;
  1332. int bytes;
  1333. {
  1334. char *temp;
  1335. if (!pointer)
  1336. temp = (char *)xmalloc (bytes);
  1337. else
  1338. temp = (char *)realloc (pointer, bytes);
  1339. if (!temp)
  1340. memory_error_and_abort ();
  1341. return (temp);
  1342. }
  1343. static void
  1344. memory_error_and_abort ()
  1345. {
  1346. fprintf (stderr, "history: Out of virtual memory!\n");
  1347. abort ();
  1348. }
  1349. #endif /* STATIC_MALLOC */
  1350. /* **************************************************************** */
  1351. /* */
  1352. /* Test Code */
  1353. /* */
  1354. /* **************************************************************** */
  1355. #ifdef TEST
  1356. main ()
  1357. {
  1358. char line[1024], *t;
  1359. int done = 0;
  1360. line[0] = 0;
  1361. while (!done)
  1362. {
  1363. fprintf (stdout, "history%% ");
  1364. t = gets (line);
  1365. if (!t)
  1366. strcpy (line, "quit");
  1367. if (line[0])
  1368. {
  1369. char *expansion;
  1370. int result;
  1371. using_history ();
  1372. result = history_expand (line, &expansion);
  1373. strcpy (line, expansion);
  1374. free (expansion);
  1375. if (result)
  1376. fprintf (stderr, "%s\n", line);
  1377. if (result < 0)
  1378. continue;
  1379. add_history (line);
  1380. }
  1381. if (strcmp (line, "quit") == 0) done = 1;
  1382. if (strcmp (line, "save") == 0) write_history (0);
  1383. if (strcmp (line, "read") == 0) read_history (0);
  1384. if (strcmp (line, "list") == 0)
  1385. {
  1386. register HIST_ENTRY **the_list = history_list ();
  1387. register int i;
  1388. if (the_list)
  1389. for (i = 0; the_list[i]; i++)
  1390. fprintf (stdout, "%d: %s\n", i + history_base, the_list[i]->line);
  1391. }
  1392. if (strncmp (line, "delete", strlen ("delete")) == 0)
  1393. {
  1394. int which;
  1395. if ((sscanf (line + strlen ("delete"), "%d", &which)) == 1)
  1396. {
  1397. HIST_ENTRY *entry = remove_history (which);
  1398. if (!entry)
  1399. fprintf (stderr, "No such entry %d\n", which);
  1400. else
  1401. {
  1402. free (entry->line);
  1403. free (entry);
  1404. }
  1405. }
  1406. else
  1407. {
  1408. fprintf (stderr, "non-numeric arg given to `delete'\n");
  1409. }
  1410. }
  1411. }
  1412. }
  1413. #endif /* TEST */
  1414. /*
  1415. * Local variables:
  1416. * compile-command: "gcc -g -DTEST -o history history.c"
  1417. * end:
  1418. */