/** * @file edit_libedit.c * @brief The line editor implemented with libedit (BSD editline). * * This is the compile-time alternative to edit_builtin.c: * * make EDIT=libedit LDLIBS=-ledit * * It provides the same two functions, edit_usable() and edit_readline(), * so nothing else in the shell knows which editor is linked. libedit * brings its own key bindings (including a fuller vi mode) and reads * `~/.editrc`. It also brings a dependency on the library and on * terminfo or termcap, which is why it is not the default. * * The shell's own history list (history.c) stays the single source of * truth, because `fc` works on it. Before each line is read the list is * copied into libedit's history so that the arrow keys and searches see * the same entries. */ #include #include #include #include #include #include #include "exec.h" #include "interact.h" #include "shell.h" /** * @brief The libedit editor, created on first use. */ static EditLine *el; /** * @brief libedit's copy of the history. */ static History *el_hist; /** * @brief The prompt for the line being read. */ static const char *cur_prompt = ""; /** * @brief libedit callback: the prompt for the line being read. * @param e Unused. * @return The prompt set by edit_readline(). */ static char *prompt_cb(EditLine *e) { (void)e; return (char *)cur_prompt; } /** * @brief Can lines be edited on this terminal? * @return true if stdin and stderr are terminals and TERM is not "dumb". */ bool edit_usable(void) { const char *term = var_get("TERM"); if (!term || !*term || !strcmp(term, "dumb")) return false; return isatty(0) && isatty(2); } /** * @brief Read one line with editing. * * @param prompt Text to show before the line. * @param len Receives the length of the line. * @return The line without its newline, valid until the next call; * NULL at end of input. */ char *edit_readline(const char *prompt, size_t *len) { static char *line; HistEvent ev; if (!el) { el = el_init("zash", stdin, stderr, stderr); el_hist = history_init(); if (!el || !el_hist) return NULL; history(el_hist, &ev, H_SETSIZE, 100000); el_set(el, EL_HIST, history, el_hist); el_set(el, EL_PROMPT, prompt_cb); el_set(el, EL_SIGNAL, 0); el_source(el, NULL); } el_set(el, EL_EDITOR, opt.vi ? "vi" : "emacs"); history(el_hist, &ev, H_CLEAR); for (int i = 0; i < hist_count(); i++) history(el_hist, &ev, H_ENTER, hist_entry(i)); cur_prompt = prompt; for (;;) { int n = 0; const char *s = el_gets(el, &n); if (s && n > 0) { size_t k = (size_t)n; while (k && (s[k - 1] == '\n' || s[k - 1] == '\r')) k--; free(line); line = xmalloc(k + 1); memcpy(line, s, k); line[k] = '\0'; *len = k; return line; } if (n < 0 && errno == EINTR) { trap_poll(); /* ^C abandons the line and does not return */ continue; } return NULL; } } int edit_bind(const char *spec) { sh_warn("bind: %s: this editor reads its bindings from ~/.editrc", spec); return -1; } void edit_bind_list(void) { sh_warn("bind: -l: this editor reads its bindings from ~/.editrc"); }