1 /* $NetBSD: histedit.c,v 1.66 2023/04/07 10:34:13 kre Exp $ */ 2 3 /*- 4 * Copyright (c) 1993 5 * The Regents of the University of California. All rights reserved. 6 * 7 * This code is derived from software contributed to Berkeley by 8 * Kenneth Almquist. 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 * 3. Neither the name of the University nor the names of its contributors 19 * may be used to endorse or promote products derived from this software 20 * without specific prior written permission. 21 * 22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 32 * SUCH DAMAGE. 33 */ 34 35 #include <sys/cdefs.h> 36 #ifndef lint 37 #if 0 38 static char sccsid[] = "@(#)histedit.c 8.2 (Berkeley) 5/4/95"; 39 #else 40 __RCSID("$NetBSD: histedit.c,v 1.66 2023/04/07 10:34:13 kre Exp $"); 41 #endif 42 #endif /* not lint */ 43 44 #include <sys/param.h> 45 #include <sys/stat.h> 46 #include <dirent.h> 47 #include <paths.h> 48 #include <stdio.h> 49 #include <stdlib.h> 50 #include <unistd.h> 51 /* 52 * Editline and history functions (and glue). 53 */ 54 #include "shell.h" 55 #include "parser.h" 56 #include "var.h" 57 #include "options.h" 58 #include "builtins.h" 59 #include "main.h" 60 #include "output.h" 61 #include "mystring.h" 62 #include "myhistedit.h" 63 #include "error.h" 64 #include "alias.h" 65 #ifndef SMALL 66 #include "eval.h" 67 #include "memalloc.h" 68 #include "show.h" 69 70 #define MAXHISTLOOPS 4 /* max recursions through fc */ 71 #define DEFEDITOR "ed" /* default editor *should* be $EDITOR */ 72 73 History *hist; /* history cookie */ 74 EditLine *el; /* editline cookie */ 75 int displayhist; 76 static FILE *el_in, *el_out; 77 static int curpos; 78 79 #ifdef DEBUG 80 extern FILE *tracefile; 81 #endif 82 83 static const char *fc_replace(const char *, char *, char *); 84 static int not_fcnumber(const char *); 85 static int str_to_event(const char *, int); 86 static int comparator(const void *, const void *); 87 static char **sh_matches(const char *, int, int); 88 static unsigned char sh_complete(EditLine *, int); 89 90 /* 91 * Set history and editing status. Called whenever the status may 92 * have changed (figures out what to do). 93 */ 94 void 95 histedit(void) 96 { 97 FILE *el_err; 98 99 #define editing (Eflag || Vflag) 100 101 CTRACE(DBG_HISTORY, ("histedit: %cE%cV %sinteractive\n", 102 Eflag ? '-' : '+', Vflag ? '-' : '+', iflag ? "" : "not ")); 103 104 if (iflag == 1) { 105 if (!hist) { 106 /* 107 * turn history on 108 */ 109 INTOFF; 110 hist = history_init(); 111 INTON; 112 113 if (hist != NULL) 114 sethistsize(histsizeval()); 115 else 116 out2str("sh: can't initialize history\n"); 117 } 118 if (editing && !el && isatty(0)) { /* && isatty(2) ??? */ 119 /* 120 * turn editing on 121 */ 122 char *term; 123 124 INTOFF; 125 if (el_in == NULL) 126 el_in = fdopen(0, "r"); 127 if (el_out == NULL) 128 el_out = fdopen(2, "w"); 129 if (el_in == NULL || el_out == NULL) 130 goto bad; 131 el_err = el_out; 132 #if DEBUG 133 if (tracefile) 134 el_err = tracefile; 135 #endif 136 /* 137 * This odd piece of code doesn't affect the shell 138 * at all, the environment modified here is the 139 * stuff accessed via "environ" (the incoming 140 * environment to the shell) which is only ever 141 * touched at sh startup time (long before we get 142 * here) and ignored thereafter. 143 * 144 * But libedit calls getenv() to discover TERM 145 * and that searches the "environ" environment, 146 * not the shell's internal variable data struct, 147 * so we need to make sure that TERM in there is 148 * correct. 149 * 150 * This sequence copies TERM from the shell into 151 * the old "environ" environment. 152 */ 153 term = lookupvar("TERM"); 154 if (term) 155 setenv("TERM", term, 1); 156 else 157 unsetenv("TERM"); 158 el = el_init("sh", el_in, el_out, el_err); 159 VTRACE(DBG_HISTORY, ("el_init() %sed\n", 160 el != NULL ? "succeed" : "fail")); 161 if (el != NULL) { 162 if (hist) 163 el_set(el, EL_HIST, history, hist); 164 165 set_prompt_lit(lookupvar("PSlit")); 166 el_set(el, EL_SIGNAL, 1); 167 el_set(el, EL_SAFEREAD, 1); 168 el_set(el, EL_ALIAS_TEXT, alias_text, NULL); 169 el_set(el, EL_ADDFN, "rl-complete", 170 "ReadLine compatible completion function", 171 sh_complete); 172 } else { 173 bad: 174 out2str("sh: can't initialize editing\n"); 175 } 176 INTON; 177 } else if (!editing && el) { 178 INTOFF; 179 el_end(el); 180 el = NULL; 181 VTRACE(DBG_HISTORY, ("line editing disabled\n")); 182 INTON; 183 } 184 if (el) { 185 INTOFF; 186 if (Vflag) 187 el_set(el, EL_EDITOR, "vi"); 188 else if (Eflag) 189 el_set(el, EL_EDITOR, "emacs"); 190 VTRACE(DBG_HISTORY, ("reading $EDITRC\n")); 191 el_source(el, lookupvar("EDITRC")); 192 el_set(el, EL_BIND, "^I", 193 tabcomplete ? "rl-complete" : "ed-insert", NULL); 194 INTON; 195 } 196 } else { 197 INTOFF; 198 if (el) { /* no editing if not interactive */ 199 el_end(el); 200 el = NULL; 201 } 202 if (hist) { 203 history_end(hist); 204 hist = NULL; 205 } 206 INTON; 207 VTRACE(DBG_HISTORY, ("line editing & history disabled\n")); 208 } 209 } 210 211 void 212 set_prompt_lit(const char *lit_ch) 213 { 214 wchar_t wc; 215 216 if (!(iflag && editing && el)) 217 return; 218 219 if (lit_ch == NULL) { 220 el_set(el, EL_PROMPT, getprompt); 221 return; 222 } 223 224 mbtowc(&wc, NULL, 1); /* state init */ 225 226 INTOFF; 227 if (mbtowc(&wc, lit_ch, strlen(lit_ch)) <= 0) 228 el_set(el, EL_PROMPT, getprompt); 229 else 230 el_set(el, EL_PROMPT_ESC, getprompt, (int)wc); 231 INTON; 232 } 233 234 void 235 set_editrc(const char *fname) 236 { 237 INTOFF; 238 if (iflag && editing && el) 239 el_source(el, fname); 240 INTON; 241 } 242 243 void 244 sethistsize(const char *hs) 245 { 246 int histsize; 247 HistEvent he; 248 249 if (hist != NULL) { 250 if (hs == NULL || *hs == '\0' || *hs == '-' || 251 (histsize = number(hs)) < 0) 252 histsize = 100; 253 INTOFF; 254 history(hist, &he, H_SETSIZE, histsize); 255 history(hist, &he, H_SETUNIQUE, 1); 256 INTON; 257 } 258 } 259 260 void 261 setterm(const char *term) 262 { 263 INTOFF; 264 if (el != NULL && term != NULL) 265 if (el_set(el, EL_TERMINAL, term) != 0) { 266 outfmt(out2, "sh: Can't set terminal type %s\n", term); 267 outfmt(out2, "sh: Using dumb terminal settings.\n"); 268 } 269 INTON; 270 } 271 272 int 273 inputrc(int argc, char **argv) 274 { 275 CTRACE(DBG_HISTORY, ("inputrc (%d arg%s)", argc-1, argc==2?"":"s")); 276 if (argc != 2) { 277 CTRACE(DBG_HISTORY, (" -- bad\n")); 278 out2str("usage: inputrc file\n"); 279 return 1; 280 } 281 CTRACE(DBG_HISTORY, (" file: \"%s\"\n", argv[1])); 282 if (el != NULL) { 283 INTOFF; 284 if (el_source(el, argv[1])) { 285 INTON; 286 out2str("inputrc: failed\n"); 287 return 1; 288 } 289 INTON; 290 return 0; 291 } else { 292 out2str("sh: inputrc ignored, not editing\n"); 293 return 1; 294 } 295 } 296 297 /* 298 * This command is provided since POSIX decided to standardize 299 * the Korn shell fc command. Oh well... 300 */ 301 int 302 histcmd(volatile int argc, char ** volatile argv) 303 { 304 int ch; 305 const char * volatile editor = NULL; 306 HistEvent he; 307 volatile int lflg = 0, nflg = 0, rflg = 0, sflg = 0; 308 int i, retval; 309 const char *firststr, *laststr; 310 int first, last, direction; 311 char * volatile pat = NULL, * volatile repl; /* ksh "fc old=new" crap */ 312 static int active = 0; 313 struct jmploc jmploc; 314 struct jmploc *volatile savehandler; 315 char editfile[MAXPATHLEN + 1]; 316 FILE * volatile efp; 317 #ifdef __GNUC__ 318 repl = NULL; /* XXX gcc4 */ 319 efp = NULL; /* XXX gcc4 */ 320 #endif 321 322 if (hist == NULL) 323 error("history not active"); 324 325 CTRACE(DBG_HISTORY, ("histcmd (fc) %d arg%s\n", argc, argc==1?"":"s")); 326 if (argc == 1) 327 error("missing history argument"); 328 329 optreset = 1; optind = 1; /* initialize getopt */ 330 while (not_fcnumber(argv[optind]) && 331 (ch = getopt(argc, argv, ":e:lnrs")) != -1) 332 switch ((char)ch) { 333 case 'e': 334 editor = optarg; 335 VTRACE(DBG_HISTORY, ("histcmd -e %s\n", editor)); 336 break; 337 case 'l': 338 lflg = 1; 339 VTRACE(DBG_HISTORY, ("histcmd -l\n")); 340 break; 341 case 'n': 342 nflg = 1; 343 VTRACE(DBG_HISTORY, ("histcmd -n\n")); 344 break; 345 case 'r': 346 rflg = 1; 347 VTRACE(DBG_HISTORY, ("histcmd -r\n")); 348 break; 349 case 's': 350 sflg = 1; 351 VTRACE(DBG_HISTORY, ("histcmd -s\n")); 352 break; 353 case ':': 354 error("option -%c expects argument", optopt); 355 /* NOTREACHED */ 356 case '?': 357 default: 358 error("unknown option: -%c", optopt); 359 /* NOTREACHED */ 360 } 361 argc -= optind, argv += optind; 362 363 /* 364 * If executing... 365 */ 366 if (lflg == 0 || editor || sflg) { 367 lflg = 0; /* ignore */ 368 editfile[0] = '\0'; 369 /* 370 * Catch interrupts to reset active counter and 371 * cleanup temp files. 372 */ 373 savehandler = handler; 374 if (setjmp(jmploc.loc)) { 375 active = 0; 376 if (*editfile) { 377 VTRACE(DBG_HISTORY, 378 ("histcmd err jump unlink temp \"%s\"\n", 379 *editfile)); 380 unlink(editfile); 381 } 382 handler = savehandler; 383 longjmp(handler->loc, 1); 384 } 385 handler = &jmploc; 386 VTRACE(DBG_HISTORY, ("histcmd was active %d (++)\n", active)); 387 if (++active > MAXHISTLOOPS) { 388 active = 0; 389 displayhist = 0; 390 error("called recursively too many times"); 391 } 392 /* 393 * Set editor. 394 */ 395 if (sflg == 0) { 396 if (editor == NULL && 397 (editor = bltinlookup("FCEDIT", 1)) == NULL && 398 (editor = bltinlookup("EDITOR", 1)) == NULL) 399 editor = DEFEDITOR; 400 if (editor[0] == '-' && editor[1] == '\0') { 401 sflg = 1; /* no edit */ 402 editor = NULL; 403 } 404 VTRACE(DBG_HISTORY, ("histcmd using %s as editor\n", 405 editor == NULL ? "-nothing-" : editor)); 406 } 407 } 408 409 /* 410 * If executing, parse [old=new] now 411 */ 412 if (lflg == 0 && argc > 0 && 413 ((repl = strchr(argv[0], '=')) != NULL)) { 414 pat = argv[0]; 415 *repl++ = '\0'; 416 argc--, argv++; 417 VTRACE(DBG_HISTORY, ("histcmd replace old=\"%s\" new=\"%s\"" 418 " (%d args)\n", pat, repl, argc)); 419 } 420 421 /* 422 * If -s is specified, accept only one operand 423 */ 424 if (sflg && argc >= 2) 425 error("too many args"); 426 427 /* 428 * determine [first] and [last] 429 */ 430 switch (argc) { 431 case 0: 432 firststr = lflg ? "-16" : "-1"; 433 laststr = "-1"; 434 break; 435 case 1: 436 firststr = argv[0]; 437 laststr = lflg ? "-1" : argv[0]; 438 break; 439 case 2: 440 firststr = argv[0]; 441 laststr = argv[1]; 442 break; 443 default: 444 error("too many args"); 445 /* NOTREACHED */ 446 } 447 /* 448 * Turn into event numbers. 449 */ 450 first = str_to_event(firststr, 0); 451 last = str_to_event(laststr, 1); 452 453 if (rflg) { 454 i = last; 455 last = first; 456 first = i; 457 } 458 VTRACE(DBG_HISTORY, ("histcmd%s first=\"%s\" (#%d) last=\"%s\" (#%d)\n", 459 rflg ? " reversed" : "", rflg ? laststr : firststr, first, 460 rflg ? firststr : laststr, last)); 461 462 /* 463 * XXX - this should not depend on the event numbers 464 * always increasing. Add sequence numbers or offset 465 * to the history element in next (diskbased) release. 466 */ 467 direction = first < last ? H_PREV : H_NEXT; 468 469 /* 470 * If editing, grab a temp file. 471 */ 472 if (editor) { 473 int fd; 474 INTOFF; /* easier */ 475 snprintf(editfile, sizeof(editfile), "%s_shXXXXXX", _PATH_TMP); 476 if ((fd = mkstemp(editfile)) < 0) 477 error("can't create temporary file %s", editfile); 478 if ((efp = fdopen(fd, "w")) == NULL) { 479 close(fd); 480 error("can't allocate stdio buffer for temp"); 481 } 482 VTRACE(DBG_HISTORY, ("histcmd created \"%s\" for edit buffer" 483 " fd=%d\n", editfile, fd)); 484 } 485 486 /* 487 * Loop through selected history events. If listing or executing, 488 * do it now. Otherwise, put into temp file and call the editor 489 * after. 490 * 491 * The history interface needs rethinking, as the following 492 * convolutions will demonstrate. 493 */ 494 history(hist, &he, H_FIRST); 495 retval = history(hist, &he, H_NEXT_EVENT, first); 496 for (;retval != -1; retval = history(hist, &he, direction)) { 497 if (lflg) { 498 if (!nflg) 499 out1fmt("%5d ", he.num); 500 out1str(he.str); 501 } else { 502 const char *s = pat ? 503 fc_replace(he.str, pat, repl) : he.str; 504 505 if (sflg) { 506 VTRACE(DBG_HISTORY, ("histcmd -s \"%s\"\n", s)); 507 if (displayhist) { 508 out2str(s); 509 } 510 511 evalstring(strcpy(stalloc(strlen(s) + 1), s), 0); 512 if (displayhist && hist) { 513 /* 514 * XXX what about recursive and 515 * relative histnums. 516 */ 517 history(hist, &he, H_ENTER, s); 518 } 519 520 break; 521 } else 522 fputs(s, efp); 523 } 524 /* 525 * At end? (if we were to lose last, we'd sure be 526 * messed up). 527 */ 528 if (he.num == last) 529 break; 530 } 531 if (editor) { 532 char *editcmd; 533 size_t cmdlen; 534 535 fclose(efp); 536 cmdlen = strlen(editor) + strlen(editfile) + 2; 537 editcmd = stalloc(cmdlen); 538 snprintf(editcmd, cmdlen, "%s %s", editor, editfile); 539 VTRACE(DBG_HISTORY, ("histcmd editing: \"%s\"\n", editcmd)); 540 evalstring(editcmd, 0); /* XXX - should use no JC command */ 541 stunalloc(editcmd); 542 VTRACE(DBG_HISTORY, ("histcmd read cmds from %s\n", editfile)); 543 readcmdfile(editfile); /* XXX - should read back - quick tst */ 544 VTRACE(DBG_HISTORY, ("histcmd unlink %s\n", editfile)); 545 unlink(editfile); 546 INTON; 547 } 548 549 if (lflg == 0 && active > 0) 550 --active; 551 if (displayhist) 552 displayhist = 0; 553 return 0; 554 } 555 556 static const char * 557 fc_replace(const char *s, char *p, char *r) 558 { 559 char *dest; 560 int plen = strlen(p); 561 562 VTRACE(DBG_HISTORY, ("histcmd s/%s/%s/ in \"%s\" -> ", p, r, s)); 563 STARTSTACKSTR(dest); 564 while (*s) { 565 if (*s == *p && strncmp(s, p, plen) == 0) { 566 while (*r) 567 STPUTC(*r++, dest); 568 s += plen; 569 *p = '\0'; /* so no more matches */ 570 } else 571 STPUTC(*s++, dest); 572 } 573 STACKSTRNUL(dest); 574 dest = grabstackstr(dest); 575 VTRACE(DBG_HISTORY, ("\"%s\"\n", dest)); 576 577 return dest; 578 } 579 580 581 /* 582 * Comparator function for qsort(). The use of curpos here is to skip 583 * characters that we already know to compare equal (common prefix). 584 */ 585 static int 586 comparator(const void *a, const void *b) 587 { 588 return strcmp(*(char *const *)a + curpos, 589 *(char *const *)b + curpos); 590 } 591 592 /* 593 * This function is passed to libedit's fn_complete(). The library will 594 * use it instead of its standard function to find matches, which 595 * searches for files in current directory. If we're at the start of the 596 * line, we want to look for available commands from all paths in $PATH. 597 */ 598 static char 599 **sh_matches(const char *text, int start, int end) 600 { 601 char *free_path = NULL, *dirname, *path; 602 char **matches = NULL; 603 size_t i = 0, size = 16; 604 605 if (start > 0) 606 return NULL; 607 curpos = end - start; 608 if ((free_path = path = strdup(pathval())) == NULL) 609 goto out; 610 if ((matches = malloc(size * sizeof(matches[0]))) == NULL) 611 goto out; 612 while ((dirname = strsep(&path, ":")) != NULL) { 613 struct dirent *entry; 614 DIR *dir; 615 int dfd; 616 617 if ((dir = opendir(dirname)) == NULL) 618 continue; 619 if ((dfd = dirfd(dir)) == -1) 620 continue; 621 while ((entry = readdir(dir)) != NULL) { 622 struct stat statb; 623 624 if (strncmp(entry->d_name, text, curpos) != 0) 625 continue; 626 if (entry->d_type == DT_UNKNOWN || entry->d_type == DT_LNK) { 627 if (fstatat(dfd, entry->d_name, &statb, 0) == -1) 628 continue; 629 if (!S_ISREG(statb.st_mode)) 630 continue; 631 } else if (entry->d_type != DT_REG) 632 continue; 633 if (++i >= size - 1) { 634 size *= 2; 635 if (reallocarr(&matches, size, 636 sizeof(*matches))) 637 { 638 closedir(dir); 639 goto out; 640 } 641 } 642 matches[i] = strdup(entry->d_name); 643 } 644 closedir(dir); 645 } 646 out: 647 free(free_path); 648 if (i == 0) { 649 free(matches); 650 return NULL; 651 } 652 if (i == 1) { 653 matches[0] = strdup(matches[1]); 654 matches[i + 1] = NULL; 655 } else { 656 size_t j, k; 657 658 qsort(matches + 1, i, sizeof(matches[0]), comparator); 659 for (j = 1, k = 2; k <= i; k++) 660 if (strcmp(matches[j] + curpos, matches[k] + curpos) 661 == 0) 662 free(matches[k]); 663 else 664 matches[++j] = matches[k]; 665 matches[0] = strdup(text); 666 matches[j + 1] = NULL; 667 } 668 return matches; 669 } 670 671 /* 672 * This is passed to el_set(el, EL_ADDFN, ...) so that it's possible to 673 * bind a key (tab by default) to execute the function. 674 */ 675 unsigned char 676 sh_complete(EditLine *sel, int ch __unused) 677 { 678 return (unsigned char)fn_complete2(sel, NULL, sh_matches, 679 L" \t\n\"\\'`@$><=;|&{(", NULL, NULL, (size_t)100, 680 NULL, &((int) {0}), NULL, NULL, FN_QUOTE_MATCH); 681 } 682 683 static int 684 not_fcnumber(const char *s) 685 { 686 if (s == NULL) 687 return 0; 688 if (*s == '-') 689 s++; 690 return !is_number(s); 691 } 692 693 static int 694 str_to_event(const char *str, int last) 695 { 696 HistEvent he; 697 const char *s = str; 698 int relative = 0; 699 int i, retval; 700 701 retval = history(hist, &he, H_FIRST); 702 switch (*s) { 703 case '-': 704 relative = 1; 705 /*FALLTHROUGH*/ 706 case '+': 707 s++; 708 } 709 if (is_number(s)) { 710 i = number(s); 711 if (relative) { 712 while (retval != -1 && i--) { 713 retval = history(hist, &he, H_NEXT); 714 } 715 if (retval == -1) 716 retval = history(hist, &he, H_LAST); 717 } else { 718 retval = history(hist, &he, H_NEXT_EVENT, i); 719 if (retval == -1) { 720 /* 721 * the notion of first and last is 722 * backwards to that of the history package 723 */ 724 retval = history(hist, &he, 725 last ? H_FIRST : H_LAST); 726 } 727 } 728 if (retval == -1) 729 error("history number %s not found (internal error)", 730 str); 731 } else { 732 /* 733 * pattern 734 */ 735 retval = history(hist, &he, H_PREV_STR, str); 736 if (retval == -1) 737 error("history pattern not found: %s", str); 738 } 739 return he.num; 740 } 741 #else 742 int 743 histcmd(int argc, char **argv) 744 { 745 error("not compiled with history support"); 746 /* NOTREACHED */ 747 } 748 int 749 inputrc(int argc, char **argv) 750 { 751 error("not compiled with history support"); 752 /* NOTREACHED */ 753 } 754 #endif 755