PageRenderTime 55ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/src/mswin/rdln/history.c

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