1 /* $NetBSD: readline.c,v 1.151 2019/02/15 23:20:35 christos Exp $ */ 2 3 /*- 4 * Copyright (c) 1997 The NetBSD Foundation, Inc. 5 * All rights reserved. 6 * 7 * This code is derived from software contributed to The NetBSD Foundation 8 * by Jaromir Dolecek. 9 * 10 * Redistribution and use in source and binary forms, with or without 11 * modification, are permitted provided that the following conditions 12 * are met: 13 * 1. Redistributions of source code must retain the above copyright 14 * notice, this list of conditions and the following disclaimer. 15 * 2. Redistributions in binary form must reproduce the above copyright 16 * notice, this list of conditions and the following disclaimer in the 17 * documentation and/or other materials provided with the distribution. 18 * 19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 29 * POSSIBILITY OF SUCH DAMAGE. 30 */ 31 32 #include "config.h" 33 #if !defined(lint) && !defined(SCCSID) 34 __RCSID("$NetBSD: readline.c,v 1.151 2019/02/15 23:20:35 christos Exp $"); 35 #endif /* not lint && not SCCSID */ 36 37 #include <sys/types.h> 38 #include <sys/stat.h> 39 #include <ctype.h> 40 #include <dirent.h> 41 #include <errno.h> 42 #include <fcntl.h> 43 #include <limits.h> 44 #include <pwd.h> 45 #include <setjmp.h> 46 #include <stdint.h> 47 #include <stdio.h> 48 #include <stdlib.h> 49 #include <string.h> 50 #include <unistd.h> 51 #include <vis.h> 52 53 #include "editline/readline.h" 54 #include "el.h" 55 #include "fcns.h" 56 #include "filecomplete.h" 57 58 #if !defined(SIZE_T_MAX) 59 # define SIZE_T_MAX (size_t)(-1) 60 #endif 61 62 void rl_prep_terminal(int); 63 void rl_deprep_terminal(void); 64 65 /* for rl_complete() */ 66 #define TAB '\r' 67 68 /* see comment at the #ifdef for sense of this */ 69 /* #define GDB_411_HACK */ 70 71 /* readline compatibility stuff - look at readline sources/documentation */ 72 /* to see what these variables mean */ 73 const char *rl_library_version = "EditLine wrapper"; 74 int rl_readline_version = RL_READLINE_VERSION; 75 static char empty[] = { '\0' }; 76 static char expand_chars[] = { ' ', '\t', '\n', '=', '(', '\0' }; 77 static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$', 78 '>', '<', '=', ';', '|', '&', '{', '(', '\0' }; 79 const char *rl_readline_name = empty; 80 FILE *rl_instream = NULL; 81 FILE *rl_outstream = NULL; 82 int rl_point = 0; 83 int rl_end = 0; 84 char *rl_line_buffer = NULL; 85 rl_vcpfunc_t *rl_linefunc = NULL; 86 int rl_done = 0; 87 rl_hook_func_t *rl_event_hook = NULL; 88 KEYMAP_ENTRY_ARRAY emacs_standard_keymap, 89 emacs_meta_keymap, 90 emacs_ctlx_keymap; 91 /* 92 * The following is not implemented; we always catch signals in the 93 * libedit fashion: set handlers on entry to el_gets() and clear them 94 * on the way out. This simplistic approach works for most cases; if 95 * it does not work for your application, please let us know. 96 */ 97 int rl_catch_signals = 1; 98 int rl_catch_sigwinch = 1; 99 100 int history_base = 1; /* probably never subject to change */ 101 int history_length = 0; 102 int history_offset = 0; 103 int max_input_history = 0; 104 char history_expansion_char = '!'; 105 char history_subst_char = '^'; 106 char *history_no_expand_chars = expand_chars; 107 Function *history_inhibit_expansion_function = NULL; 108 char *history_arg_extract(int start, int end, const char *str); 109 110 int rl_inhibit_completion = 0; 111 int rl_attempted_completion_over = 0; 112 const char *rl_basic_word_break_characters = break_chars; 113 char *rl_completer_word_break_characters = NULL; 114 char *rl_completer_quote_characters = NULL; 115 rl_compentry_func_t *rl_completion_entry_function = NULL; 116 char *(*rl_completion_word_break_hook)(void) = NULL; 117 rl_completion_func_t *rl_attempted_completion_function = NULL; 118 Function *rl_pre_input_hook = NULL; 119 Function *rl_startup1_hook = NULL; 120 int (*rl_getc_function)(FILE *) = NULL; 121 char *rl_terminal_name = NULL; 122 int rl_already_prompted = 0; 123 int rl_filename_completion_desired = 0; 124 int rl_ignore_completion_duplicates = 0; 125 int readline_echoing_p = 1; 126 int _rl_print_completions_horizontally = 0; 127 VFunction *rl_redisplay_function = NULL; 128 Function *rl_startup_hook = NULL; 129 int rl_did_startup_hook = 0; 130 VFunction *rl_completion_display_matches_hook = NULL; 131 VFunction *rl_prep_term_function = (VFunction *)rl_prep_terminal; 132 VFunction *rl_deprep_term_function = (VFunction *)rl_deprep_terminal; 133 KEYMAP_ENTRY_ARRAY emacs_meta_keymap; 134 135 /* 136 * The current prompt string. 137 */ 138 char *rl_prompt = NULL; 139 /* 140 * This is set to character indicating type of completion being done by 141 * rl_complete_internal(); this is available for application completion 142 * functions. 143 */ 144 int rl_completion_type = 0; 145 146 /* 147 * If more than this number of items results from query for possible 148 * completions, we ask user if they are sure to really display the list. 149 */ 150 int rl_completion_query_items = 100; 151 152 /* 153 * List of characters which are word break characters, but should be left 154 * in the parsed text when it is passed to the completion function. 155 * Shell uses this to help determine what kind of completing to do. 156 */ 157 const char *rl_special_prefixes = NULL; 158 159 /* 160 * This is the character appended to the completed words if at the end of 161 * the line. Default is ' ' (a space). 162 */ 163 int rl_completion_append_character = ' '; 164 165 /* stuff below is used internally by libedit for readline emulation */ 166 167 static History *h = NULL; 168 static EditLine *e = NULL; 169 static rl_command_func_t *map[256]; 170 static jmp_buf topbuf; 171 172 /* internal functions */ 173 static unsigned char _el_rl_complete(EditLine *, int); 174 static unsigned char _el_rl_tstp(EditLine *, int); 175 static char *_get_prompt(EditLine *); 176 static int _getc_function(EditLine *, wchar_t *); 177 static int _history_expand_command(const char *, size_t, size_t, 178 char **); 179 static char *_rl_compat_sub(const char *, const char *, 180 const char *, int); 181 static int _rl_event_read_char(EditLine *, wchar_t *); 182 static void _rl_update_pos(void); 183 184 static HIST_ENTRY rl_he; 185 186 /* ARGSUSED */ 187 static char * 188 _get_prompt(EditLine *el __attribute__((__unused__))) 189 { 190 rl_already_prompted = 1; 191 return rl_prompt; 192 } 193 194 195 /* 196 * read one key from user defined input function 197 */ 198 static int 199 /*ARGSUSED*/ 200 _getc_function(EditLine *el __attribute__((__unused__)), wchar_t *c) 201 { 202 int i; 203 204 i = (*rl_getc_function)(rl_instream); 205 if (i == -1) 206 return 0; 207 *c = (wchar_t)i; 208 return 1; 209 } 210 211 static void 212 _resize_fun(EditLine *el, void *a) 213 { 214 const LineInfo *li; 215 char **ap = a; 216 217 li = el_line(el); 218 /* a cheesy way to get rid of const cast. */ 219 *ap = memchr(li->buffer, *li->buffer, (size_t)1); 220 } 221 222 static const char * 223 _default_history_file(void) 224 { 225 struct passwd *p; 226 static char *path; 227 size_t len; 228 229 if (path) 230 return path; 231 232 if ((p = getpwuid(getuid())) == NULL) 233 return NULL; 234 235 len = strlen(p->pw_dir) + sizeof("/.history"); 236 if ((path = malloc(len)) == NULL) 237 return NULL; 238 239 (void)snprintf(path, len, "%s/.history", p->pw_dir); 240 return path; 241 } 242 243 /* 244 * READLINE compatibility stuff 245 */ 246 247 /* 248 * Set the prompt 249 */ 250 int 251 rl_set_prompt(const char *prompt) 252 { 253 char *p; 254 255 if (!prompt) 256 prompt = ""; 257 if (rl_prompt != NULL && strcmp(rl_prompt, prompt) == 0) 258 return 0; 259 if (rl_prompt) 260 el_free(rl_prompt); 261 rl_prompt = strdup(prompt); 262 if (rl_prompt == NULL) 263 return -1; 264 265 while ((p = strchr(rl_prompt, RL_PROMPT_END_IGNORE)) != NULL) 266 *p = RL_PROMPT_START_IGNORE; 267 268 return 0; 269 } 270 271 /* 272 * initialize rl compat stuff 273 */ 274 int 275 rl_initialize(void) 276 { 277 HistEvent ev; 278 int editmode = 1; 279 struct termios t; 280 281 if (e != NULL) 282 el_end(e); 283 if (h != NULL) 284 history_end(h); 285 286 if (!rl_instream) 287 rl_instream = stdin; 288 if (!rl_outstream) 289 rl_outstream = stdout; 290 291 /* 292 * See if we don't really want to run the editor 293 */ 294 if (tcgetattr(fileno(rl_instream), &t) != -1 && (t.c_lflag & ECHO) == 0) 295 editmode = 0; 296 297 e = el_init_internal(rl_readline_name, rl_instream, rl_outstream, 298 stderr, fileno(rl_instream), fileno(rl_outstream), fileno(stderr), 299 NO_RESET); 300 301 if (!editmode) 302 el_set(e, EL_EDITMODE, 0); 303 304 h = history_init(); 305 if (!e || !h) 306 return -1; 307 308 history(h, &ev, H_SETSIZE, INT_MAX); /* unlimited */ 309 history_length = 0; 310 max_input_history = INT_MAX; 311 el_set(e, EL_HIST, history, h); 312 313 /* Setup resize function */ 314 el_set(e, EL_RESIZE, _resize_fun, &rl_line_buffer); 315 316 /* setup getc function if valid */ 317 if (rl_getc_function) 318 el_set(e, EL_GETCFN, _getc_function); 319 320 /* for proper prompt printing in readline() */ 321 if (rl_set_prompt("") == -1) { 322 history_end(h); 323 el_end(e); 324 return -1; 325 } 326 el_set(e, EL_PROMPT_ESC, _get_prompt, RL_PROMPT_START_IGNORE); 327 el_set(e, EL_SIGNAL, rl_catch_signals); 328 329 /* set default mode to "emacs"-style and read setting afterwards */ 330 /* so this can be overridden */ 331 el_set(e, EL_EDITOR, "emacs"); 332 if (rl_terminal_name != NULL) 333 el_set(e, EL_TERMINAL, rl_terminal_name); 334 else 335 el_get(e, EL_TERMINAL, &rl_terminal_name); 336 337 /* 338 * Word completion - this has to go AFTER rebinding keys 339 * to emacs-style. 340 */ 341 el_set(e, EL_ADDFN, "rl_complete", 342 "ReadLine compatible completion function", 343 _el_rl_complete); 344 el_set(e, EL_BIND, "^I", "rl_complete", NULL); 345 346 /* 347 * Send TSTP when ^Z is pressed. 348 */ 349 el_set(e, EL_ADDFN, "rl_tstp", 350 "ReadLine compatible suspend function", 351 _el_rl_tstp); 352 el_set(e, EL_BIND, "^Z", "rl_tstp", NULL); 353 354 /* 355 * Set some readline compatible key-bindings. 356 */ 357 el_set(e, EL_BIND, "^R", "em-inc-search-prev", NULL); 358 359 /* 360 * Allow the use of Home/End keys. 361 */ 362 el_set(e, EL_BIND, "\\e[1~", "ed-move-to-beg", NULL); 363 el_set(e, EL_BIND, "\\e[4~", "ed-move-to-end", NULL); 364 el_set(e, EL_BIND, "\\e[7~", "ed-move-to-beg", NULL); 365 el_set(e, EL_BIND, "\\e[8~", "ed-move-to-end", NULL); 366 el_set(e, EL_BIND, "\\e[H", "ed-move-to-beg", NULL); 367 el_set(e, EL_BIND, "\\e[F", "ed-move-to-end", NULL); 368 369 /* 370 * Allow the use of the Delete/Insert keys. 371 */ 372 el_set(e, EL_BIND, "\\e[3~", "ed-delete-next-char", NULL); 373 el_set(e, EL_BIND, "\\e[2~", "ed-quoted-insert", NULL); 374 375 /* 376 * Ctrl-left-arrow and Ctrl-right-arrow for word moving. 377 */ 378 el_set(e, EL_BIND, "\\e[1;5C", "em-next-word", NULL); 379 el_set(e, EL_BIND, "\\e[1;5D", "ed-prev-word", NULL); 380 el_set(e, EL_BIND, "\\e[5C", "em-next-word", NULL); 381 el_set(e, EL_BIND, "\\e[5D", "ed-prev-word", NULL); 382 el_set(e, EL_BIND, "\\e\\e[C", "em-next-word", NULL); 383 el_set(e, EL_BIND, "\\e\\e[D", "ed-prev-word", NULL); 384 385 /* read settings from configuration file */ 386 el_source(e, NULL); 387 388 /* 389 * Unfortunately, some applications really do use rl_point 390 * and rl_line_buffer directly. 391 */ 392 _resize_fun(e, &rl_line_buffer); 393 _rl_update_pos(); 394 395 tty_end(e, TCSADRAIN); 396 397 return 0; 398 } 399 400 401 /* 402 * read one line from input stream and return it, chomping 403 * trailing newline (if there is any) 404 */ 405 char * 406 readline(const char *p) 407 { 408 HistEvent ev; 409 const char * volatile prompt = p; 410 int count; 411 const char *ret; 412 char *buf; 413 static int used_event_hook; 414 415 if (e == NULL || h == NULL) 416 rl_initialize(); 417 if (rl_did_startup_hook == 0 && rl_startup_hook) { 418 rl_did_startup_hook = 1; 419 (*rl_startup_hook)(NULL, 0); 420 } 421 tty_init(e); 422 423 424 rl_done = 0; 425 426 (void)setjmp(topbuf); 427 buf = NULL; 428 429 /* update prompt accordingly to what has been passed */ 430 if (rl_set_prompt(prompt) == -1) 431 goto out; 432 433 if (rl_pre_input_hook) 434 (*rl_pre_input_hook)(NULL, 0); 435 436 if (rl_event_hook && !(e->el_flags & NO_TTY)) { 437 el_set(e, EL_GETCFN, _rl_event_read_char); 438 used_event_hook = 1; 439 } 440 441 if (!rl_event_hook && used_event_hook) { 442 el_set(e, EL_GETCFN, EL_BUILTIN_GETCFN); 443 used_event_hook = 0; 444 } 445 446 rl_already_prompted = 0; 447 448 /* get one line from input stream */ 449 ret = el_gets(e, &count); 450 451 if (ret && count > 0) { 452 int lastidx; 453 454 buf = strdup(ret); 455 if (buf == NULL) 456 goto out; 457 lastidx = count - 1; 458 if (buf[lastidx] == '\n') 459 buf[lastidx] = '\0'; 460 } else 461 buf = NULL; 462 463 history(h, &ev, H_GETSIZE); 464 history_length = ev.num; 465 466 out: 467 tty_end(e, TCSADRAIN); 468 return buf; 469 } 470 471 /* 472 * history functions 473 */ 474 475 /* 476 * is normally called before application starts to use 477 * history expansion functions 478 */ 479 void 480 using_history(void) 481 { 482 if (h == NULL || e == NULL) 483 rl_initialize(); 484 history_offset = history_length; 485 } 486 487 488 /* 489 * substitute ``what'' with ``with'', returning resulting string; if 490 * globally == 1, substitutes all occurrences of what, otherwise only the 491 * first one 492 */ 493 static char * 494 _rl_compat_sub(const char *str, const char *what, const char *with, 495 int globally) 496 { 497 const char *s; 498 char *r, *result; 499 size_t len, with_len, what_len; 500 501 len = strlen(str); 502 with_len = strlen(with); 503 what_len = strlen(what); 504 505 /* calculate length we need for result */ 506 s = str; 507 while (*s) { 508 if (*s == *what && !strncmp(s, what, what_len)) { 509 len += with_len - what_len; 510 if (!globally) 511 break; 512 s += what_len; 513 } else 514 s++; 515 } 516 r = result = el_malloc((len + 1) * sizeof(*r)); 517 if (result == NULL) 518 return NULL; 519 s = str; 520 while (*s) { 521 if (*s == *what && !strncmp(s, what, what_len)) { 522 (void)strncpy(r, with, with_len); 523 r += with_len; 524 s += what_len; 525 if (!globally) { 526 (void)strcpy(r, s); 527 return result; 528 } 529 } else 530 *r++ = *s++; 531 } 532 *r = '\0'; 533 return result; 534 } 535 536 static char *last_search_pat; /* last !?pat[?] search pattern */ 537 static char *last_search_match; /* last !?pat[?] that matched */ 538 539 const char * 540 get_history_event(const char *cmd, int *cindex, int qchar) 541 { 542 int idx, sign, sub, num, begin, ret; 543 size_t len; 544 char *pat; 545 const char *rptr; 546 HistEvent ev; 547 548 idx = *cindex; 549 if (cmd[idx++] != history_expansion_char) 550 return NULL; 551 552 /* find out which event to take */ 553 if (cmd[idx] == history_expansion_char || cmd[idx] == '\0') { 554 if (history(h, &ev, H_FIRST) != 0) 555 return NULL; 556 *cindex = cmd[idx]? (idx + 1):idx; 557 return ev.str; 558 } 559 sign = 0; 560 if (cmd[idx] == '-') { 561 sign = 1; 562 idx++; 563 } 564 565 if ('0' <= cmd[idx] && cmd[idx] <= '9') { 566 HIST_ENTRY *he; 567 568 num = 0; 569 while (cmd[idx] && '0' <= cmd[idx] && cmd[idx] <= '9') { 570 num = num * 10 + cmd[idx] - '0'; 571 idx++; 572 } 573 if (sign) 574 num = history_length - num + history_base; 575 576 if (!(he = history_get(num))) 577 return NULL; 578 579 *cindex = idx; 580 return he->line; 581 } 582 sub = 0; 583 if (cmd[idx] == '?') { 584 sub = 1; 585 idx++; 586 } 587 begin = idx; 588 while (cmd[idx]) { 589 if (cmd[idx] == '\n') 590 break; 591 if (sub && cmd[idx] == '?') 592 break; 593 if (!sub && (cmd[idx] == ':' || cmd[idx] == ' ' 594 || cmd[idx] == '\t' || cmd[idx] == qchar)) 595 break; 596 idx++; 597 } 598 len = (size_t)idx - (size_t)begin; 599 if (sub && cmd[idx] == '?') 600 idx++; 601 if (sub && len == 0 && last_search_pat && *last_search_pat) 602 pat = last_search_pat; 603 else if (len == 0) 604 return NULL; 605 else { 606 if ((pat = el_malloc((len + 1) * sizeof(*pat))) == NULL) 607 return NULL; 608 (void)strncpy(pat, cmd + begin, len); 609 pat[len] = '\0'; 610 } 611 612 if (history(h, &ev, H_CURR) != 0) { 613 if (pat != last_search_pat) 614 el_free(pat); 615 return NULL; 616 } 617 num = ev.num; 618 619 if (sub) { 620 if (pat != last_search_pat) { 621 if (last_search_pat) 622 el_free(last_search_pat); 623 last_search_pat = pat; 624 } 625 ret = history_search(pat, -1); 626 } else 627 ret = history_search_prefix(pat, -1); 628 629 if (ret == -1) { 630 /* restore to end of list on failed search */ 631 history(h, &ev, H_FIRST); 632 (void)fprintf(rl_outstream, "%s: Event not found\n", pat); 633 if (pat != last_search_pat) 634 el_free(pat); 635 return NULL; 636 } 637 638 if (sub && len) { 639 if (last_search_match && last_search_match != pat) 640 el_free(last_search_match); 641 last_search_match = pat; 642 } 643 644 if (pat != last_search_pat) 645 el_free(pat); 646 647 if (history(h, &ev, H_CURR) != 0) 648 return NULL; 649 *cindex = idx; 650 rptr = ev.str; 651 652 /* roll back to original position */ 653 (void)history(h, &ev, H_SET, num); 654 655 return rptr; 656 } 657 658 /* 659 * the real function doing history expansion - takes as argument command 660 * to do and data upon which the command should be executed 661 * does expansion the way I've understood readline documentation 662 * 663 * returns 0 if data was not modified, 1 if it was and 2 if the string 664 * should be only printed and not executed; in case of error, 665 * returns -1 and *result points to NULL 666 * it's the caller's responsibility to free() the string returned in *result 667 */ 668 static int 669 _history_expand_command(const char *command, size_t offs, size_t cmdlen, 670 char **result) 671 { 672 char *tmp, *search = NULL, *aptr; 673 const char *ptr, *cmd; 674 static char *from = NULL, *to = NULL; 675 int start, end, idx, has_mods = 0; 676 int p_on = 0, g_on = 0; 677 678 *result = NULL; 679 aptr = NULL; 680 ptr = NULL; 681 682 /* First get event specifier */ 683 idx = 0; 684 685 if (strchr(":^*$", command[offs + 1])) { 686 char str[4]; 687 /* 688 * "!:" is shorthand for "!!:". 689 * "!^", "!*" and "!$" are shorthand for 690 * "!!:^", "!!:*" and "!!:$" respectively. 691 */ 692 str[0] = str[1] = '!'; 693 str[2] = '0'; 694 ptr = get_history_event(str, &idx, 0); 695 idx = (command[offs + 1] == ':')? 1:0; 696 has_mods = 1; 697 } else { 698 if (command[offs + 1] == '#') { 699 /* use command so far */ 700 if ((aptr = el_malloc((offs + 1) * sizeof(*aptr))) 701 == NULL) 702 return -1; 703 (void)strncpy(aptr, command, offs); 704 aptr[offs] = '\0'; 705 idx = 1; 706 } else { 707 int qchar; 708 709 qchar = (offs > 0 && command[offs - 1] == '"')? '"':0; 710 ptr = get_history_event(command + offs, &idx, qchar); 711 } 712 has_mods = command[offs + (size_t)idx] == ':'; 713 } 714 715 if (ptr == NULL && aptr == NULL) 716 return -1; 717 718 if (!has_mods) { 719 *result = strdup(aptr ? aptr : ptr); 720 if (aptr) 721 el_free(aptr); 722 if (*result == NULL) 723 return -1; 724 return 1; 725 } 726 727 cmd = command + offs + idx + 1; 728 729 /* Now parse any word designators */ 730 731 if (*cmd == '%') /* last word matched by ?pat? */ 732 tmp = strdup(last_search_match? last_search_match:""); 733 else if (strchr("^*$-0123456789", *cmd)) { 734 start = end = -1; 735 if (*cmd == '^') 736 start = end = 1, cmd++; 737 else if (*cmd == '$') 738 start = -1, cmd++; 739 else if (*cmd == '*') 740 start = 1, cmd++; 741 else if (*cmd == '-' || isdigit((unsigned char) *cmd)) { 742 start = 0; 743 while (*cmd && '0' <= *cmd && *cmd <= '9') 744 start = start * 10 + *cmd++ - '0'; 745 746 if (*cmd == '-') { 747 if (isdigit((unsigned char) cmd[1])) { 748 cmd++; 749 end = 0; 750 while (*cmd && '0' <= *cmd && *cmd <= '9') 751 end = end * 10 + *cmd++ - '0'; 752 } else if (cmd[1] == '$') { 753 cmd += 2; 754 end = -1; 755 } else { 756 cmd++; 757 end = -2; 758 } 759 } else if (*cmd == '*') 760 end = -1, cmd++; 761 else 762 end = start; 763 } 764 tmp = history_arg_extract(start, end, aptr? aptr:ptr); 765 if (tmp == NULL) { 766 (void)fprintf(rl_outstream, "%s: Bad word specifier", 767 command + offs + idx); 768 if (aptr) 769 el_free(aptr); 770 return -1; 771 } 772 } else 773 tmp = strdup(aptr? aptr:ptr); 774 775 if (aptr) 776 el_free(aptr); 777 778 if (*cmd == '\0' || ((size_t)(cmd - (command + offs)) >= cmdlen)) { 779 *result = tmp; 780 return 1; 781 } 782 783 for (; *cmd; cmd++) { 784 if (*cmd == ':') 785 continue; 786 else if (*cmd == 'h') { /* remove trailing path */ 787 if ((aptr = strrchr(tmp, '/')) != NULL) 788 *aptr = '\0'; 789 } else if (*cmd == 't') { /* remove leading path */ 790 if ((aptr = strrchr(tmp, '/')) != NULL) { 791 aptr = strdup(aptr + 1); 792 el_free(tmp); 793 tmp = aptr; 794 } 795 } else if (*cmd == 'r') { /* remove trailing suffix */ 796 if ((aptr = strrchr(tmp, '.')) != NULL) 797 *aptr = '\0'; 798 } else if (*cmd == 'e') { /* remove all but suffix */ 799 if ((aptr = strrchr(tmp, '.')) != NULL) { 800 aptr = strdup(aptr); 801 el_free(tmp); 802 tmp = aptr; 803 } 804 } else if (*cmd == 'p') /* print only */ 805 p_on = 1; 806 else if (*cmd == 'g') 807 g_on = 2; 808 else if (*cmd == 's' || *cmd == '&') { 809 char *what, *with, delim; 810 size_t len, from_len; 811 size_t size; 812 813 if (*cmd == '&' && (from == NULL || to == NULL)) 814 continue; 815 else if (*cmd == 's') { 816 delim = *(++cmd), cmd++; 817 size = 16; 818 what = el_realloc(from, size * sizeof(*what)); 819 if (what == NULL) { 820 el_free(from); 821 el_free(tmp); 822 return 0; 823 } 824 len = 0; 825 for (; *cmd && *cmd != delim; cmd++) { 826 if (*cmd == '\\' && cmd[1] == delim) 827 cmd++; 828 if (len >= size) { 829 char *nwhat; 830 nwhat = el_realloc(what, 831 (size <<= 1) * 832 sizeof(*nwhat)); 833 if (nwhat == NULL) { 834 el_free(what); 835 el_free(tmp); 836 return 0; 837 } 838 what = nwhat; 839 } 840 what[len++] = *cmd; 841 } 842 what[len] = '\0'; 843 from = what; 844 if (*what == '\0') { 845 el_free(what); 846 if (search) { 847 from = strdup(search); 848 if (from == NULL) { 849 el_free(tmp); 850 return 0; 851 } 852 } else { 853 from = NULL; 854 el_free(tmp); 855 return -1; 856 } 857 } 858 cmd++; /* shift after delim */ 859 if (!*cmd) 860 continue; 861 862 size = 16; 863 with = el_realloc(to, size * sizeof(*with)); 864 if (with == NULL) { 865 el_free(to); 866 el_free(tmp); 867 return -1; 868 } 869 len = 0; 870 from_len = strlen(from); 871 for (; *cmd && *cmd != delim; cmd++) { 872 if (len + from_len + 1 >= size) { 873 char *nwith; 874 size += from_len + 1; 875 nwith = el_realloc(with, 876 size * sizeof(*nwith)); 877 if (nwith == NULL) { 878 el_free(with); 879 el_free(tmp); 880 return -1; 881 } 882 with = nwith; 883 } 884 if (*cmd == '&') { 885 /* safe */ 886 (void)strcpy(&with[len], from); 887 len += from_len; 888 continue; 889 } 890 if (*cmd == '\\' 891 && (*(cmd + 1) == delim 892 || *(cmd + 1) == '&')) 893 cmd++; 894 with[len++] = *cmd; 895 } 896 with[len] = '\0'; 897 to = with; 898 } 899 900 aptr = _rl_compat_sub(tmp, from, to, g_on); 901 if (aptr) { 902 el_free(tmp); 903 tmp = aptr; 904 } 905 g_on = 0; 906 } 907 } 908 *result = tmp; 909 return p_on? 2:1; 910 } 911 912 913 /* 914 * csh-style history expansion 915 */ 916 int 917 history_expand(char *str, char **output) 918 { 919 int ret = 0; 920 size_t idx, i, size; 921 char *tmp, *result; 922 923 if (h == NULL || e == NULL) 924 rl_initialize(); 925 926 if (history_expansion_char == 0) { 927 *output = strdup(str); 928 return 0; 929 } 930 931 *output = NULL; 932 if (str[0] == history_subst_char) { 933 /* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */ 934 *output = el_malloc((strlen(str) + 4 + 1) * sizeof(**output)); 935 if (*output == NULL) 936 return 0; 937 (*output)[0] = (*output)[1] = history_expansion_char; 938 (*output)[2] = ':'; 939 (*output)[3] = 's'; 940 (void)strcpy((*output) + 4, str); 941 str = *output; 942 } else { 943 *output = strdup(str); 944 if (*output == NULL) 945 return 0; 946 } 947 948 #define ADD_STRING(what, len, fr) \ 949 { \ 950 if (idx + len + 1 > size) { \ 951 char *nresult = el_realloc(result, \ 952 (size += len + 1) * sizeof(*nresult)); \ 953 if (nresult == NULL) { \ 954 el_free(*output); \ 955 if (/*CONSTCOND*/fr) \ 956 el_free(tmp); \ 957 return 0; \ 958 } \ 959 result = nresult; \ 960 } \ 961 (void)strncpy(&result[idx], what, len); \ 962 idx += len; \ 963 result[idx] = '\0'; \ 964 } 965 966 result = NULL; 967 size = idx = 0; 968 tmp = NULL; 969 for (i = 0; str[i];) { 970 int qchar, loop_again; 971 size_t len, start, j; 972 973 qchar = 0; 974 loop_again = 1; 975 start = j = i; 976 loop: 977 for (; str[j]; j++) { 978 if (str[j] == '\\' && 979 str[j + 1] == history_expansion_char) { 980 len = strlen(&str[j + 1]) + 1; 981 memmove(&str[j], &str[j + 1], len); 982 continue; 983 } 984 if (!loop_again) { 985 if (isspace((unsigned char) str[j]) 986 || str[j] == qchar) 987 break; 988 } 989 if (str[j] == history_expansion_char 990 && !strchr(history_no_expand_chars, str[j + 1]) 991 && (!history_inhibit_expansion_function || 992 (*history_inhibit_expansion_function)(str, 993 (int)j) == 0)) 994 break; 995 } 996 997 if (str[j] && loop_again) { 998 i = j; 999 qchar = (j > 0 && str[j - 1] == '"' )? '"':0; 1000 j++; 1001 if (str[j] == history_expansion_char) 1002 j++; 1003 loop_again = 0; 1004 goto loop; 1005 } 1006 len = i - start; 1007 ADD_STRING(&str[start], len, 0); 1008 1009 if (str[i] == '\0' || str[i] != history_expansion_char) { 1010 len = j - i; 1011 ADD_STRING(&str[i], len, 0); 1012 if (start == 0) 1013 ret = 0; 1014 else 1015 ret = 1; 1016 break; 1017 } 1018 ret = _history_expand_command (str, i, (j - i), &tmp); 1019 if (ret > 0 && tmp) { 1020 len = strlen(tmp); 1021 ADD_STRING(tmp, len, 1); 1022 } 1023 if (tmp) { 1024 el_free(tmp); 1025 tmp = NULL; 1026 } 1027 i = j; 1028 } 1029 1030 /* ret is 2 for "print only" option */ 1031 if (ret == 2) { 1032 add_history(result); 1033 #ifdef GDB_411_HACK 1034 /* gdb 4.11 has been shipped with readline, where */ 1035 /* history_expand() returned -1 when the line */ 1036 /* should not be executed; in readline 2.1+ */ 1037 /* it should return 2 in such a case */ 1038 ret = -1; 1039 #endif 1040 } 1041 el_free(*output); 1042 *output = result; 1043 1044 return ret; 1045 } 1046 1047 /* 1048 * Return a string consisting of arguments of "str" from "start" to "end". 1049 */ 1050 char * 1051 history_arg_extract(int start, int end, const char *str) 1052 { 1053 size_t i, len, max; 1054 char **arr, *result = NULL; 1055 1056 arr = history_tokenize(str); 1057 if (!arr) 1058 return NULL; 1059 if (arr && *arr == NULL) 1060 goto out; 1061 1062 for (max = 0; arr[max]; max++) 1063 continue; 1064 max--; 1065 1066 if (start == '$') 1067 start = (int)max; 1068 if (end == '$') 1069 end = (int)max; 1070 if (end < 0) 1071 end = (int)max + end + 1; 1072 if (start < 0) 1073 start = end; 1074 1075 if (start < 0 || end < 0 || (size_t)start > max || 1076 (size_t)end > max || start > end) 1077 goto out; 1078 1079 for (i = (size_t)start, len = 0; i <= (size_t)end; i++) 1080 len += strlen(arr[i]) + 1; 1081 len++; 1082 result = el_malloc(len * sizeof(*result)); 1083 if (result == NULL) 1084 goto out; 1085 1086 for (i = (size_t)start, len = 0; i <= (size_t)end; i++) { 1087 (void)strcpy(result + len, arr[i]); 1088 len += strlen(arr[i]); 1089 if (i < (size_t)end) 1090 result[len++] = ' '; 1091 } 1092 result[len] = '\0'; 1093 1094 out: 1095 for (i = 0; arr[i]; i++) 1096 el_free(arr[i]); 1097 el_free(arr); 1098 1099 return result; 1100 } 1101 1102 /* 1103 * Parse the string into individual tokens, 1104 * similar to how shell would do it. 1105 */ 1106 char ** 1107 history_tokenize(const char *str) 1108 { 1109 int size = 1, idx = 0, i, start; 1110 size_t len; 1111 char **result = NULL, *temp, delim = '\0'; 1112 1113 for (i = 0; str[i];) { 1114 while (isspace((unsigned char) str[i])) 1115 i++; 1116 start = i; 1117 for (; str[i];) { 1118 if (str[i] == '\\') { 1119 if (str[i+1] != '\0') 1120 i++; 1121 } else if (str[i] == delim) 1122 delim = '\0'; 1123 else if (!delim && 1124 (isspace((unsigned char) str[i]) || 1125 strchr("()<>;&|$", str[i]))) 1126 break; 1127 else if (!delim && strchr("'`\"", str[i])) 1128 delim = str[i]; 1129 if (str[i]) 1130 i++; 1131 } 1132 1133 if (idx + 2 >= size) { 1134 char **nresult; 1135 size <<= 1; 1136 nresult = el_realloc(result, (size_t)size * sizeof(*nresult)); 1137 if (nresult == NULL) { 1138 el_free(result); 1139 return NULL; 1140 } 1141 result = nresult; 1142 } 1143 len = (size_t)i - (size_t)start; 1144 temp = el_malloc((size_t)(len + 1) * sizeof(*temp)); 1145 if (temp == NULL) { 1146 for (i = 0; i < idx; i++) 1147 el_free(result[i]); 1148 el_free(result); 1149 return NULL; 1150 } 1151 (void)strncpy(temp, &str[start], len); 1152 temp[len] = '\0'; 1153 result[idx++] = temp; 1154 result[idx] = NULL; 1155 if (str[i]) 1156 i++; 1157 } 1158 return result; 1159 } 1160 1161 1162 /* 1163 * limit size of history record to ``max'' events 1164 */ 1165 void 1166 stifle_history(int max) 1167 { 1168 HistEvent ev; 1169 HIST_ENTRY *he; 1170 1171 if (h == NULL || e == NULL) 1172 rl_initialize(); 1173 1174 if (history(h, &ev, H_SETSIZE, max) == 0) { 1175 max_input_history = max; 1176 if (history_length > max) 1177 history_base = history_length - max; 1178 while (history_length > max) { 1179 he = remove_history(0); 1180 el_free(he->data); 1181 el_free((void *)(unsigned long)he->line); 1182 el_free(he); 1183 } 1184 } 1185 } 1186 1187 1188 /* 1189 * "unlimit" size of history - set the limit to maximum allowed int value 1190 */ 1191 int 1192 unstifle_history(void) 1193 { 1194 HistEvent ev; 1195 int omax; 1196 1197 history(h, &ev, H_SETSIZE, INT_MAX); 1198 omax = max_input_history; 1199 max_input_history = INT_MAX; 1200 return omax; /* some value _must_ be returned */ 1201 } 1202 1203 1204 int 1205 history_is_stifled(void) 1206 { 1207 1208 /* cannot return true answer */ 1209 return max_input_history != INT_MAX; 1210 } 1211 1212 static const char _history_tmp_template[] = "/tmp/.historyXXXXXX"; 1213 1214 int 1215 history_truncate_file (const char *filename, int nlines) 1216 { 1217 int ret = 0; 1218 FILE *fp, *tp; 1219 char template[sizeof(_history_tmp_template)]; 1220 char buf[4096]; 1221 int fd; 1222 char *cp; 1223 off_t off; 1224 int count = 0; 1225 ssize_t left = 0; 1226 1227 if (filename == NULL && (filename = _default_history_file()) == NULL) 1228 return errno; 1229 if ((fp = fopen(filename, "r+")) == NULL) 1230 return errno; 1231 strcpy(template, _history_tmp_template); 1232 if ((fd = mkstemp(template)) == -1) { 1233 ret = errno; 1234 goto out1; 1235 } 1236 1237 if ((tp = fdopen(fd, "r+")) == NULL) { 1238 close(fd); 1239 ret = errno; 1240 goto out2; 1241 } 1242 1243 for(;;) { 1244 if (fread(buf, sizeof(buf), (size_t)1, fp) != 1) { 1245 if (ferror(fp)) { 1246 ret = errno; 1247 break; 1248 } 1249 if (fseeko(fp, (off_t)sizeof(buf) * count, SEEK_SET) == 1250 (off_t)-1) { 1251 ret = errno; 1252 break; 1253 } 1254 left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), fp); 1255 if (ferror(fp)) { 1256 ret = errno; 1257 break; 1258 } 1259 if (left == 0) { 1260 count--; 1261 left = sizeof(buf); 1262 } else if (fwrite(buf, (size_t)left, (size_t)1, tp) 1263 != 1) { 1264 ret = errno; 1265 break; 1266 } 1267 fflush(tp); 1268 break; 1269 } 1270 if (fwrite(buf, sizeof(buf), (size_t)1, tp) != 1) { 1271 ret = errno; 1272 break; 1273 } 1274 count++; 1275 } 1276 if (ret) 1277 goto out3; 1278 cp = buf + left - 1; 1279 if(*cp != '\n') 1280 cp++; 1281 for(;;) { 1282 while (--cp >= buf) { 1283 if (*cp == '\n') { 1284 if (--nlines == 0) { 1285 if (++cp >= buf + sizeof(buf)) { 1286 count++; 1287 cp = buf; 1288 } 1289 break; 1290 } 1291 } 1292 } 1293 if (nlines <= 0 || count == 0) 1294 break; 1295 count--; 1296 if (fseeko(tp, (off_t)sizeof(buf) * count, SEEK_SET) < 0) { 1297 ret = errno; 1298 break; 1299 } 1300 if (fread(buf, sizeof(buf), (size_t)1, tp) != 1) { 1301 if (ferror(tp)) { 1302 ret = errno; 1303 break; 1304 } 1305 ret = EAGAIN; 1306 break; 1307 } 1308 cp = buf + sizeof(buf); 1309 } 1310 1311 if (ret || nlines > 0) 1312 goto out3; 1313 1314 if (fseeko(fp, (off_t)0, SEEK_SET) == (off_t)-1) { 1315 ret = errno; 1316 goto out3; 1317 } 1318 1319 if (fseeko(tp, (off_t)sizeof(buf) * count + (cp - buf), SEEK_SET) == 1320 (off_t)-1) { 1321 ret = errno; 1322 goto out3; 1323 } 1324 1325 for(;;) { 1326 if ((left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), tp)) == 0) { 1327 if (ferror(fp)) 1328 ret = errno; 1329 break; 1330 } 1331 if (fwrite(buf, (size_t)left, (size_t)1, fp) != 1) { 1332 ret = errno; 1333 break; 1334 } 1335 } 1336 fflush(fp); 1337 if((off = ftello(fp)) > 0) 1338 (void)ftruncate(fileno(fp), off); 1339 out3: 1340 fclose(tp); 1341 out2: 1342 unlink(template); 1343 out1: 1344 fclose(fp); 1345 1346 return ret; 1347 } 1348 1349 1350 /* 1351 * read history from a file given 1352 */ 1353 int 1354 read_history(const char *filename) 1355 { 1356 HistEvent ev; 1357 1358 if (h == NULL || e == NULL) 1359 rl_initialize(); 1360 if (filename == NULL && (filename = _default_history_file()) == NULL) 1361 return errno; 1362 errno = 0; 1363 if (history(h, &ev, H_LOAD, filename) == -1) 1364 return errno ? errno : EINVAL; 1365 if (history(h, &ev, H_GETSIZE) == 0) 1366 history_length = ev.num; 1367 if (history_length < 0) 1368 return EINVAL; 1369 return 0; 1370 } 1371 1372 1373 /* 1374 * write history to a file given 1375 */ 1376 int 1377 write_history(const char *filename) 1378 { 1379 HistEvent ev; 1380 1381 if (h == NULL || e == NULL) 1382 rl_initialize(); 1383 if (filename == NULL && (filename = _default_history_file()) == NULL) 1384 return errno; 1385 return history(h, &ev, H_SAVE, filename) == -1 ? 1386 (errno ? errno : EINVAL) : 0; 1387 } 1388 1389 int 1390 append_history(int n, const char *filename) 1391 { 1392 HistEvent ev; 1393 FILE *fp; 1394 1395 if (h == NULL || e == NULL) 1396 rl_initialize(); 1397 if (filename == NULL && (filename = _default_history_file()) == NULL) 1398 return errno; 1399 1400 if ((fp = fopen(filename, "a")) == NULL) 1401 return errno; 1402 1403 if (history(h, &ev, H_NSAVE_FP, (size_t)n, fp) == -1) { 1404 int serrno = errno ? errno : EINVAL; 1405 fclose(fp); 1406 return serrno; 1407 } 1408 fclose(fp); 1409 return 0; 1410 } 1411 1412 /* 1413 * returns history ``num''th event 1414 * 1415 * returned pointer points to static variable 1416 */ 1417 HIST_ENTRY * 1418 history_get(int num) 1419 { 1420 static HIST_ENTRY she; 1421 HistEvent ev; 1422 int curr_num; 1423 1424 if (h == NULL || e == NULL) 1425 rl_initialize(); 1426 1427 if (num < history_base) 1428 return NULL; 1429 1430 /* save current position */ 1431 if (history(h, &ev, H_CURR) != 0) 1432 return NULL; 1433 curr_num = ev.num; 1434 1435 /* 1436 * use H_DELDATA to set to nth history (without delete) by passing 1437 * (void **)-1 -- as in history_set_pos 1438 */ 1439 if (history(h, &ev, H_DELDATA, num - history_base, (void **)-1) != 0) 1440 goto out; 1441 1442 /* get current entry */ 1443 if (history(h, &ev, H_CURR) != 0) 1444 goto out; 1445 if (history(h, &ev, H_NEXT_EVDATA, ev.num, &she.data) != 0) 1446 goto out; 1447 she.line = ev.str; 1448 1449 /* restore pointer to where it was */ 1450 (void)history(h, &ev, H_SET, curr_num); 1451 1452 return &she; 1453 1454 out: 1455 /* restore pointer to where it was */ 1456 (void)history(h, &ev, H_SET, curr_num); 1457 return NULL; 1458 } 1459 1460 1461 /* 1462 * add the line to history table 1463 */ 1464 int 1465 add_history(const char *line) 1466 { 1467 HistEvent ev; 1468 1469 if (h == NULL || e == NULL) 1470 rl_initialize(); 1471 1472 if (history(h, &ev, H_ENTER, line) == -1) 1473 return 0; 1474 1475 (void)history(h, &ev, H_GETSIZE); 1476 if (ev.num == history_length) 1477 history_base++; 1478 else 1479 history_length = ev.num; 1480 return 0; 1481 } 1482 1483 1484 /* 1485 * remove the specified entry from the history list and return it. 1486 */ 1487 HIST_ENTRY * 1488 remove_history(int num) 1489 { 1490 HIST_ENTRY *he; 1491 HistEvent ev; 1492 1493 if (h == NULL || e == NULL) 1494 rl_initialize(); 1495 1496 if ((he = el_malloc(sizeof(*he))) == NULL) 1497 return NULL; 1498 1499 if (history(h, &ev, H_DELDATA, num, &he->data) != 0) { 1500 el_free(he); 1501 return NULL; 1502 } 1503 1504 he->line = ev.str; 1505 if (history(h, &ev, H_GETSIZE) == 0) 1506 history_length = ev.num; 1507 1508 return he; 1509 } 1510 1511 1512 /* 1513 * replace the line and data of the num-th entry 1514 */ 1515 HIST_ENTRY * 1516 replace_history_entry(int num, const char *line, histdata_t data) 1517 { 1518 HIST_ENTRY *he; 1519 HistEvent ev; 1520 int curr_num; 1521 1522 if (h == NULL || e == NULL) 1523 rl_initialize(); 1524 1525 /* save current position */ 1526 if (history(h, &ev, H_CURR) != 0) 1527 return NULL; 1528 curr_num = ev.num; 1529 1530 /* start from the oldest */ 1531 if (history(h, &ev, H_LAST) != 0) 1532 return NULL; /* error */ 1533 1534 if ((he = el_malloc(sizeof(*he))) == NULL) 1535 return NULL; 1536 1537 /* look forwards for event matching specified offset */ 1538 if (history(h, &ev, H_NEXT_EVDATA, num, &he->data)) 1539 goto out; 1540 1541 he->line = strdup(ev.str); 1542 if (he->line == NULL) 1543 goto out; 1544 1545 if (history(h, &ev, H_REPLACE, line, data)) 1546 goto out; 1547 1548 /* restore pointer to where it was */ 1549 if (history(h, &ev, H_SET, curr_num)) 1550 goto out; 1551 1552 return he; 1553 out: 1554 el_free(he); 1555 return NULL; 1556 } 1557 1558 /* 1559 * clear the history list - delete all entries 1560 */ 1561 void 1562 clear_history(void) 1563 { 1564 HistEvent ev; 1565 1566 if (h == NULL || e == NULL) 1567 rl_initialize(); 1568 1569 (void)history(h, &ev, H_CLEAR); 1570 history_offset = history_length = 0; 1571 } 1572 1573 1574 /* 1575 * returns offset of the current history event 1576 */ 1577 int 1578 where_history(void) 1579 { 1580 return history_offset; 1581 } 1582 1583 static HIST_ENTRY **_history_listp; 1584 static HIST_ENTRY *_history_list; 1585 1586 HIST_ENTRY ** 1587 history_list(void) 1588 { 1589 HistEvent ev; 1590 HIST_ENTRY **nlp, *nl; 1591 int i; 1592 1593 if (history(h, &ev, H_LAST) != 0) 1594 return NULL; 1595 1596 if ((nlp = el_realloc(_history_listp, 1597 ((size_t)history_length + 1) * sizeof(*nlp))) == NULL) 1598 return NULL; 1599 _history_listp = nlp; 1600 1601 if ((nl = el_realloc(_history_list, 1602 (size_t)history_length * sizeof(*nl))) == NULL) 1603 return NULL; 1604 _history_list = nl; 1605 1606 i = 0; 1607 do { 1608 _history_listp[i] = &_history_list[i]; 1609 _history_list[i].line = ev.str; 1610 _history_list[i].data = NULL; 1611 if (i++ == history_length) 1612 abort(); 1613 } while (history(h, &ev, H_PREV) == 0); 1614 _history_listp[i] = NULL; 1615 return _history_listp; 1616 } 1617 1618 /* 1619 * returns current history event or NULL if there is no such event 1620 */ 1621 HIST_ENTRY * 1622 current_history(void) 1623 { 1624 HistEvent ev; 1625 1626 if (history(h, &ev, H_PREV_EVENT, history_offset + 1) != 0) 1627 return NULL; 1628 1629 rl_he.line = ev.str; 1630 rl_he.data = NULL; 1631 return &rl_he; 1632 } 1633 1634 1635 /* 1636 * returns total number of bytes history events' data are using 1637 */ 1638 int 1639 history_total_bytes(void) 1640 { 1641 HistEvent ev; 1642 int curr_num; 1643 size_t size; 1644 1645 if (history(h, &ev, H_CURR) != 0) 1646 return -1; 1647 curr_num = ev.num; 1648 1649 (void)history(h, &ev, H_FIRST); 1650 size = 0; 1651 do 1652 size += strlen(ev.str) * sizeof(*ev.str); 1653 while (history(h, &ev, H_NEXT) == 0); 1654 1655 /* get to the same position as before */ 1656 history(h, &ev, H_PREV_EVENT, curr_num); 1657 1658 return (int)size; 1659 } 1660 1661 1662 /* 1663 * sets the position in the history list to ``pos'' 1664 */ 1665 int 1666 history_set_pos(int pos) 1667 { 1668 if (pos >= history_length || pos < 0) 1669 return 0; 1670 1671 history_offset = pos; 1672 return 1; 1673 } 1674 1675 1676 /* 1677 * returns previous event in history and shifts pointer accordingly 1678 * Note that readline and editline define directions in opposite ways. 1679 */ 1680 HIST_ENTRY * 1681 previous_history(void) 1682 { 1683 HistEvent ev; 1684 1685 if (history_offset == 0) 1686 return NULL; 1687 1688 if (history(h, &ev, H_LAST) != 0) 1689 return NULL; 1690 1691 history_offset--; 1692 return current_history(); 1693 } 1694 1695 1696 /* 1697 * returns next event in history and shifts pointer accordingly 1698 */ 1699 HIST_ENTRY * 1700 next_history(void) 1701 { 1702 HistEvent ev; 1703 1704 if (history_offset >= history_length) 1705 return NULL; 1706 1707 if (history(h, &ev, H_LAST) != 0) 1708 return NULL; 1709 1710 history_offset++; 1711 return current_history(); 1712 } 1713 1714 1715 /* 1716 * searches for first history event containing the str 1717 */ 1718 int 1719 history_search(const char *str, int direction) 1720 { 1721 HistEvent ev; 1722 const char *strp; 1723 int curr_num; 1724 1725 if (history(h, &ev, H_CURR) != 0) 1726 return -1; 1727 curr_num = ev.num; 1728 1729 for (;;) { 1730 if ((strp = strstr(ev.str, str)) != NULL) 1731 return (int)(strp - ev.str); 1732 if (history(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0) 1733 break; 1734 } 1735 (void)history(h, &ev, H_SET, curr_num); 1736 return -1; 1737 } 1738 1739 1740 /* 1741 * searches for first history event beginning with str 1742 */ 1743 int 1744 history_search_prefix(const char *str, int direction) 1745 { 1746 HistEvent ev; 1747 1748 return (history(h, &ev, direction < 0 ? 1749 H_PREV_STR : H_NEXT_STR, str)); 1750 } 1751 1752 1753 /* 1754 * search for event in history containing str, starting at offset 1755 * abs(pos); continue backward, if pos<0, forward otherwise 1756 */ 1757 /* ARGSUSED */ 1758 int 1759 history_search_pos(const char *str, 1760 int direction __attribute__((__unused__)), int pos) 1761 { 1762 HistEvent ev; 1763 int curr_num, off; 1764 1765 off = (pos > 0) ? pos : -pos; 1766 pos = (pos > 0) ? 1 : -1; 1767 1768 if (history(h, &ev, H_CURR) != 0) 1769 return -1; 1770 curr_num = ev.num; 1771 1772 if (!history_set_pos(off) || history(h, &ev, H_CURR) != 0) 1773 return -1; 1774 1775 for (;;) { 1776 if (strstr(ev.str, str)) 1777 return off; 1778 if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0) 1779 break; 1780 } 1781 1782 /* set "current" pointer back to previous state */ 1783 (void)history(h, &ev, 1784 pos < 0 ? H_NEXT_EVENT : H_PREV_EVENT, curr_num); 1785 1786 return -1; 1787 } 1788 1789 1790 /********************************/ 1791 /* completion functions */ 1792 1793 char * 1794 tilde_expand(char *name) 1795 { 1796 return fn_tilde_expand(name); 1797 } 1798 1799 char * 1800 filename_completion_function(const char *name, int state) 1801 { 1802 return fn_filename_completion_function(name, state); 1803 } 1804 1805 /* 1806 * a completion generator for usernames; returns _first_ username 1807 * which starts with supplied text 1808 * text contains a partial username preceded by random character 1809 * (usually '~'); state resets search from start (??? should we do that anyway) 1810 * it's the caller's responsibility to free the returned value 1811 */ 1812 char * 1813 username_completion_function(const char *text, int state) 1814 { 1815 struct passwd *pass = NULL; 1816 1817 if (text[0] == '\0') 1818 return NULL; 1819 1820 if (*text == '~') 1821 text++; 1822 1823 if (state == 0) 1824 setpwent(); 1825 1826 while ( 1827 (pass = getpwent()) != NULL 1828 && text[0] == pass->pw_name[0] 1829 && strcmp(text, pass->pw_name) == 0) 1830 continue; 1831 1832 if (pass == NULL) { 1833 endpwent(); 1834 return NULL; 1835 } 1836 return strdup(pass->pw_name); 1837 } 1838 1839 1840 /* 1841 * el-compatible wrapper to send TSTP on ^Z 1842 */ 1843 /* ARGSUSED */ 1844 static unsigned char 1845 _el_rl_tstp(EditLine *el __attribute__((__unused__)), int ch __attribute__((__unused__))) 1846 { 1847 (void)kill(0, SIGTSTP); 1848 return CC_NORM; 1849 } 1850 1851 static const char * 1852 /*ARGSUSED*/ 1853 _rl_completion_append_character_function(const char *dummy 1854 __attribute__((__unused__))) 1855 { 1856 static char buf[2]; 1857 buf[0] = (char)rl_completion_append_character; 1858 buf[1] = '\0'; 1859 return buf; 1860 } 1861 1862 1863 /* 1864 * Display list of strings in columnar format on readline's output stream. 1865 * 'matches' is list of strings, 'len' is number of strings in 'matches', 1866 * 'max' is maximum length of string in 'matches'. 1867 */ 1868 void 1869 rl_display_match_list(char **matches, int len, int max) 1870 { 1871 1872 fn_display_match_list(e, matches, (size_t)len, (size_t)max, 1873 _rl_completion_append_character_function); 1874 } 1875 1876 /* 1877 * complete word at current point 1878 */ 1879 /* ARGSUSED */ 1880 int 1881 rl_complete(int ignore __attribute__((__unused__)), int invoking_key) 1882 { 1883 static ct_buffer_t wbreak_conv, sprefix_conv; 1884 const char *breakchars; 1885 1886 if (h == NULL || e == NULL) 1887 rl_initialize(); 1888 1889 if (rl_inhibit_completion) { 1890 char arr[2]; 1891 arr[0] = (char)invoking_key; 1892 arr[1] = '\0'; 1893 el_insertstr(e, arr); 1894 return CC_REFRESH; 1895 } 1896 1897 if (rl_completion_word_break_hook != NULL) 1898 breakchars = (*rl_completion_word_break_hook)(); 1899 else 1900 breakchars = rl_basic_word_break_characters; 1901 1902 _rl_update_pos(); 1903 1904 /* Just look at how many global variables modify this operation! */ 1905 return fn_complete(e, 1906 (rl_compentry_func_t *)rl_completion_entry_function, 1907 rl_attempted_completion_function, 1908 ct_decode_string(rl_basic_word_break_characters, &wbreak_conv), 1909 ct_decode_string(breakchars, &sprefix_conv), 1910 _rl_completion_append_character_function, 1911 (size_t)rl_completion_query_items, 1912 &rl_completion_type, &rl_attempted_completion_over, 1913 &rl_point, &rl_end); 1914 1915 1916 } 1917 1918 1919 /* ARGSUSED */ 1920 static unsigned char 1921 _el_rl_complete(EditLine *el __attribute__((__unused__)), int ch) 1922 { 1923 return (unsigned char)rl_complete(0, ch); 1924 } 1925 1926 /* 1927 * misc other functions 1928 */ 1929 1930 /* 1931 * bind key c to readline-type function func 1932 */ 1933 int 1934 rl_bind_key(int c, rl_command_func_t *func) 1935 { 1936 int retval = -1; 1937 1938 if (h == NULL || e == NULL) 1939 rl_initialize(); 1940 1941 if (func == rl_insert) { 1942 /* XXX notice there is no range checking of ``c'' */ 1943 e->el_map.key[c] = ED_INSERT; 1944 retval = 0; 1945 } 1946 return retval; 1947 } 1948 1949 1950 /* 1951 * read one key from input - handles chars pushed back 1952 * to input stream also 1953 */ 1954 int 1955 rl_read_key(void) 1956 { 1957 char fooarr[2 * sizeof(int)]; 1958 1959 if (e == NULL || h == NULL) 1960 rl_initialize(); 1961 1962 return el_getc(e, fooarr); 1963 } 1964 1965 1966 /* 1967 * reset the terminal 1968 */ 1969 /* ARGSUSED */ 1970 int 1971 rl_reset_terminal(const char *p __attribute__((__unused__))) 1972 { 1973 1974 if (h == NULL || e == NULL) 1975 rl_initialize(); 1976 el_reset(e); 1977 return 0; 1978 } 1979 1980 1981 /* 1982 * insert character ``c'' back into input stream, ``count'' times 1983 */ 1984 int 1985 rl_insert(int count, int c) 1986 { 1987 char arr[2]; 1988 1989 if (h == NULL || e == NULL) 1990 rl_initialize(); 1991 1992 /* XXX - int -> char conversion can lose on multichars */ 1993 arr[0] = (char)c; 1994 arr[1] = '\0'; 1995 1996 for (; count > 0; count--) 1997 el_push(e, arr); 1998 1999 return 0; 2000 } 2001 2002 int 2003 rl_insert_text(const char *text) 2004 { 2005 if (!text || *text == 0) 2006 return 0; 2007 2008 if (h == NULL || e == NULL) 2009 rl_initialize(); 2010 2011 if (el_insertstr(e, text) < 0) 2012 return 0; 2013 return (int)strlen(text); 2014 } 2015 2016 /*ARGSUSED*/ 2017 int 2018 rl_newline(int count __attribute__((__unused__)), 2019 int c __attribute__((__unused__))) 2020 { 2021 /* 2022 * Readline-4.0 appears to ignore the args. 2023 */ 2024 return rl_insert(1, '\n'); 2025 } 2026 2027 /*ARGSUSED*/ 2028 static unsigned char 2029 rl_bind_wrapper(EditLine *el __attribute__((__unused__)), unsigned char c) 2030 { 2031 if (map[c] == NULL) 2032 return CC_ERROR; 2033 2034 _rl_update_pos(); 2035 2036 (*map[c])(1, c); 2037 2038 /* If rl_done was set by the above call, deal with it here */ 2039 if (rl_done) 2040 return CC_EOF; 2041 2042 return CC_NORM; 2043 } 2044 2045 int 2046 rl_add_defun(const char *name, rl_command_func_t *fun, int c) 2047 { 2048 char dest[8]; 2049 if ((size_t)c >= sizeof(map) / sizeof(map[0]) || c < 0) 2050 return -1; 2051 map[(unsigned char)c] = fun; 2052 el_set(e, EL_ADDFN, name, name, rl_bind_wrapper); 2053 vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0); 2054 el_set(e, EL_BIND, dest, name, NULL); 2055 return 0; 2056 } 2057 2058 void 2059 rl_callback_read_char(void) 2060 { 2061 int count = 0, done = 0; 2062 const char *buf = el_gets(e, &count); 2063 char *wbuf; 2064 2065 if (buf == NULL || count-- <= 0) 2066 return; 2067 if (count == 0 && buf[0] == e->el_tty.t_c[TS_IO][C_EOF]) 2068 done = 1; 2069 if (buf[count] == '\n' || buf[count] == '\r') 2070 done = 2; 2071 2072 if (done && rl_linefunc != NULL) { 2073 el_set(e, EL_UNBUFFERED, 0); 2074 if (done == 2) { 2075 if ((wbuf = strdup(buf)) != NULL) 2076 wbuf[count] = '\0'; 2077 } else 2078 wbuf = NULL; 2079 (*(void (*)(const char *))rl_linefunc)(wbuf); 2080 el_set(e, EL_UNBUFFERED, 1); 2081 } 2082 } 2083 2084 void 2085 rl_callback_handler_install(const char *prompt, rl_vcpfunc_t *linefunc) 2086 { 2087 if (e == NULL) { 2088 rl_initialize(); 2089 } 2090 (void)rl_set_prompt(prompt); 2091 rl_linefunc = linefunc; 2092 el_set(e, EL_UNBUFFERED, 1); 2093 } 2094 2095 void 2096 rl_callback_handler_remove(void) 2097 { 2098 rl_linefunc = NULL; 2099 el_end(e); 2100 e = NULL; 2101 } 2102 2103 void 2104 rl_redisplay(void) 2105 { 2106 char a[2]; 2107 a[0] = (char)e->el_tty.t_c[TS_IO][C_REPRINT]; 2108 a[1] = '\0'; 2109 el_push(e, a); 2110 } 2111 2112 int 2113 rl_get_previous_history(int count, int key) 2114 { 2115 char a[2]; 2116 a[0] = (char)key; 2117 a[1] = '\0'; 2118 while (count--) 2119 el_push(e, a); 2120 return 0; 2121 } 2122 2123 void 2124 /*ARGSUSED*/ 2125 rl_prep_terminal(int meta_flag __attribute__((__unused__))) 2126 { 2127 el_set(e, EL_PREP_TERM, 1); 2128 } 2129 2130 void 2131 rl_deprep_terminal(void) 2132 { 2133 el_set(e, EL_PREP_TERM, 0); 2134 } 2135 2136 int 2137 rl_read_init_file(const char *s) 2138 { 2139 return el_source(e, s); 2140 } 2141 2142 int 2143 rl_parse_and_bind(const char *line) 2144 { 2145 const char **argv; 2146 int argc; 2147 Tokenizer *tok; 2148 2149 tok = tok_init(NULL); 2150 tok_str(tok, line, &argc, &argv); 2151 argc = el_parse(e, argc, argv); 2152 tok_end(tok); 2153 return argc ? 1 : 0; 2154 } 2155 2156 int 2157 rl_variable_bind(const char *var, const char *value) 2158 { 2159 /* 2160 * The proper return value is undocument, but this is what the 2161 * readline source seems to do. 2162 */ 2163 return el_set(e, EL_BIND, "", var, value, NULL) == -1 ? 1 : 0; 2164 } 2165 2166 int 2167 rl_stuff_char(int c) 2168 { 2169 char buf[2]; 2170 2171 buf[0] = (char)c; 2172 buf[1] = '\0'; 2173 el_insertstr(e, buf); 2174 return 1; 2175 } 2176 2177 static int 2178 _rl_event_read_char(EditLine *el, wchar_t *wc) 2179 { 2180 char ch; 2181 int n; 2182 ssize_t num_read = 0; 2183 2184 ch = '\0'; 2185 *wc = L'\0'; 2186 while (rl_event_hook) { 2187 2188 (*rl_event_hook)(); 2189 2190 #if defined(FIONREAD) 2191 if (ioctl(el->el_infd, FIONREAD, &n) < 0) 2192 return -1; 2193 if (n) 2194 num_read = read(el->el_infd, &ch, (size_t)1); 2195 else 2196 num_read = 0; 2197 #elif defined(F_SETFL) && defined(O_NDELAY) 2198 if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0) 2199 return -1; 2200 if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0) 2201 return -1; 2202 num_read = read(el->el_infd, &ch, 1); 2203 if (fcntl(el->el_infd, F_SETFL, n)) 2204 return -1; 2205 #else 2206 /* not non-blocking, but what you gonna do? */ 2207 num_read = read(el->el_infd, &ch, 1); 2208 return -1; 2209 #endif 2210 2211 if (num_read < 0 && errno == EAGAIN) 2212 continue; 2213 if (num_read == 0) 2214 continue; 2215 break; 2216 } 2217 if (!rl_event_hook) 2218 el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN); 2219 *wc = (wchar_t)ch; 2220 return (int)num_read; 2221 } 2222 2223 static void 2224 _rl_update_pos(void) 2225 { 2226 const LineInfo *li = el_line(e); 2227 2228 rl_point = (int)(li->cursor - li->buffer); 2229 rl_end = (int)(li->lastchar - li->buffer); 2230 } 2231 2232 void 2233 rl_get_screen_size(int *rows, int *cols) 2234 { 2235 if (rows) 2236 el_get(e, EL_GETTC, "li", rows, (void *)0); 2237 if (cols) 2238 el_get(e, EL_GETTC, "co", cols, (void *)0); 2239 } 2240 2241 void 2242 rl_set_screen_size(int rows, int cols) 2243 { 2244 char buf[64]; 2245 (void)snprintf(buf, sizeof(buf), "%d", rows); 2246 el_set(e, EL_SETTC, "li", buf, NULL); 2247 (void)snprintf(buf, sizeof(buf), "%d", cols); 2248 el_set(e, EL_SETTC, "co", buf, NULL); 2249 } 2250 2251 char ** 2252 rl_completion_matches(const char *str, rl_compentry_func_t *fun) 2253 { 2254 size_t len, max, i, j, min; 2255 char **list, *match, *a, *b; 2256 2257 len = 1; 2258 max = 10; 2259 if ((list = el_malloc(max * sizeof(*list))) == NULL) 2260 return NULL; 2261 2262 while ((match = (*fun)(str, (int)(len - 1))) != NULL) { 2263 list[len++] = match; 2264 if (len == max) { 2265 char **nl; 2266 max += 10; 2267 if ((nl = el_realloc(list, max * sizeof(*nl))) == NULL) 2268 goto out; 2269 list = nl; 2270 } 2271 } 2272 if (len == 1) 2273 goto out; 2274 list[len] = NULL; 2275 if (len == 2) { 2276 if ((list[0] = strdup(list[1])) == NULL) 2277 goto out; 2278 return list; 2279 } 2280 qsort(&list[1], len - 1, sizeof(*list), 2281 (int (*)(const void *, const void *)) strcmp); 2282 min = SIZE_MAX; 2283 for (i = 1, a = list[i]; i < len - 1; i++, a = b) { 2284 b = list[i + 1]; 2285 for (j = 0; a[j] && a[j] == b[j]; j++) 2286 continue; 2287 if (min > j) 2288 min = j; 2289 } 2290 if (min == 0 && *str) { 2291 if ((list[0] = strdup(str)) == NULL) 2292 goto out; 2293 } else { 2294 if ((list[0] = el_malloc((min + 1) * sizeof(*list[0]))) == NULL) 2295 goto out; 2296 (void)memcpy(list[0], list[1], min); 2297 list[0][min] = '\0'; 2298 } 2299 return list; 2300 2301 out: 2302 el_free(list); 2303 return NULL; 2304 } 2305 2306 char * 2307 rl_filename_completion_function (const char *text, int state) 2308 { 2309 return fn_filename_completion_function(text, state); 2310 } 2311 2312 void 2313 rl_forced_update_display(void) 2314 { 2315 el_set(e, EL_REFRESH); 2316 } 2317 2318 int 2319 _rl_abort_internal(void) 2320 { 2321 el_beep(e); 2322 longjmp(topbuf, 1); 2323 /*NOTREACHED*/ 2324 } 2325 2326 int 2327 _rl_qsort_string_compare(char **s1, char **s2) 2328 { 2329 return strcoll(*s1, *s2); 2330 } 2331 2332 HISTORY_STATE * 2333 history_get_history_state(void) 2334 { 2335 HISTORY_STATE *hs; 2336 2337 if ((hs = el_malloc(sizeof(*hs))) == NULL) 2338 return NULL; 2339 hs->length = history_length; 2340 return hs; 2341 } 2342 2343 int 2344 /*ARGSUSED*/ 2345 rl_kill_text(int from __attribute__((__unused__)), 2346 int to __attribute__((__unused__))) 2347 { 2348 return 0; 2349 } 2350 2351 Keymap 2352 rl_make_bare_keymap(void) 2353 { 2354 return NULL; 2355 } 2356 2357 Keymap 2358 rl_get_keymap(void) 2359 { 2360 return NULL; 2361 } 2362 2363 void 2364 /*ARGSUSED*/ 2365 rl_set_keymap(Keymap k __attribute__((__unused__))) 2366 { 2367 } 2368 2369 int 2370 /*ARGSUSED*/ 2371 rl_generic_bind(int type __attribute__((__unused__)), 2372 const char * keyseq __attribute__((__unused__)), 2373 const char * data __attribute__((__unused__)), 2374 Keymap k __attribute__((__unused__))) 2375 { 2376 return 0; 2377 } 2378 2379 int 2380 /*ARGSUSED*/ 2381 rl_bind_key_in_map(int key __attribute__((__unused__)), 2382 rl_command_func_t *fun __attribute__((__unused__)), 2383 Keymap k __attribute__((__unused__))) 2384 { 2385 return 0; 2386 } 2387 2388 /* unsupported, but needed by python */ 2389 void 2390 rl_cleanup_after_signal(void) 2391 { 2392 } 2393 2394 int 2395 rl_on_new_line(void) 2396 { 2397 return 0; 2398 } 2399 2400 void 2401 rl_free_line_state(void) 2402 { 2403 } 2404 2405 int 2406 /*ARGSUSED*/ 2407 rl_set_keyboard_input_timeout(int u __attribute__((__unused__))) 2408 { 2409 return 0; 2410 } 2411 2412 void 2413 rl_resize_terminal(void) 2414 { 2415 el_resize(e); 2416 } 2417 2418 void 2419 rl_reset_after_signal(void) 2420 { 2421 if (rl_prep_term_function) 2422 (*rl_prep_term_function)(); 2423 } 2424 2425 void 2426 rl_echo_signal_char(int sig) 2427 { 2428 int c = tty_get_signal_character(e, sig); 2429 if (c == -1) 2430 return; 2431 re_putc(e, c, 0); 2432 } 2433