diff --git a/contrib/libedit/chared.c b/contrib/libedit/chared.c index a96322aa6883..ff5545bbe168 100644 --- a/contrib/libedit/chared.c +++ b/contrib/libedit/chared.c @@ -1,747 +1,810 @@ -/* $NetBSD: chared.c,v 1.59 2019/07/23 10:18:52 christos Exp $ */ +/* $NetBSD: chared.c,v 1.62 2022/02/08 21:13:22 rillig Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "config.h" #if !defined(lint) && !defined(SCCSID) #if 0 static char sccsid[] = "@(#)chared.c 8.1 (Berkeley) 6/4/93"; #else -__RCSID("$NetBSD: chared.c,v 1.59 2019/07/23 10:18:52 christos Exp $"); +__RCSID("$NetBSD: chared.c,v 1.62 2022/02/08 21:13:22 rillig Exp $"); #endif #endif /* not lint && not SCCSID */ /* * chared.c: Character editor utilities */ #include #include #include #include "el.h" #include "common.h" #include "fcns.h" /* value to leave unused in line buffer */ #define EL_LEAVE 2 /* cv_undo(): * Handle state for the vi undo command */ libedit_private void cv_undo(EditLine *el) { c_undo_t *vu = &el->el_chared.c_undo; c_redo_t *r = &el->el_chared.c_redo; size_t size; /* Save entire line for undo */ size = (size_t)(el->el_line.lastchar - el->el_line.buffer); vu->len = (ssize_t)size; vu->cursor = (int)(el->el_line.cursor - el->el_line.buffer); (void)memcpy(vu->buf, el->el_line.buffer, size * sizeof(*vu->buf)); /* save command info for redo */ r->count = el->el_state.doingarg ? el->el_state.argument : 0; r->action = el->el_chared.c_vcmd.action; r->pos = r->buf; r->cmd = el->el_state.thiscmd; r->ch = el->el_state.thisch; } /* cv_yank(): * Save yank/delete data for paste */ libedit_private void cv_yank(EditLine *el, const wchar_t *ptr, int size) { c_kill_t *k = &el->el_chared.c_kill; (void)memcpy(k->buf, ptr, (size_t)size * sizeof(*k->buf)); k->last = k->buf + size; } /* c_insert(): * Insert num characters */ libedit_private void c_insert(EditLine *el, int num) { wchar_t *cp; if (el->el_line.lastchar + num >= el->el_line.limit) { if (!ch_enlargebufs(el, (size_t)num)) return; /* can't go past end of buffer */ } if (el->el_line.cursor < el->el_line.lastchar) { /* if I must move chars */ for (cp = el->el_line.lastchar; cp >= el->el_line.cursor; cp--) cp[num] = *cp; } el->el_line.lastchar += num; } /* c_delafter(): * Delete num characters after the cursor */ libedit_private void c_delafter(EditLine *el, int num) { if (el->el_line.cursor + num > el->el_line.lastchar) num = (int)(el->el_line.lastchar - el->el_line.cursor); if (el->el_map.current != el->el_map.emacs) { cv_undo(el); cv_yank(el, el->el_line.cursor, num); } if (num > 0) { wchar_t *cp; for (cp = el->el_line.cursor; cp <= el->el_line.lastchar; cp++) *cp = cp[num]; el->el_line.lastchar -= num; } } /* c_delafter1(): * Delete the character after the cursor, do not yank */ libedit_private void c_delafter1(EditLine *el) { wchar_t *cp; for (cp = el->el_line.cursor; cp <= el->el_line.lastchar; cp++) *cp = cp[1]; el->el_line.lastchar--; } /* c_delbefore(): * Delete num characters before the cursor */ libedit_private void c_delbefore(EditLine *el, int num) { if (el->el_line.cursor - num < el->el_line.buffer) num = (int)(el->el_line.cursor - el->el_line.buffer); if (el->el_map.current != el->el_map.emacs) { cv_undo(el); cv_yank(el, el->el_line.cursor - num, num); } if (num > 0) { wchar_t *cp; for (cp = el->el_line.cursor - num; &cp[num] <= el->el_line.lastchar; cp++) *cp = cp[num]; el->el_line.lastchar -= num; } } /* c_delbefore1(): * Delete the character before the cursor, do not yank */ libedit_private void c_delbefore1(EditLine *el) { wchar_t *cp; for (cp = el->el_line.cursor - 1; cp <= el->el_line.lastchar; cp++) *cp = cp[1]; el->el_line.lastchar--; } /* ce__isword(): * Return if p is part of a word according to emacs */ libedit_private int ce__isword(wint_t p) { return iswalnum(p) || wcschr(L"*?_-.[]~=", p) != NULL; } /* cv__isword(): * Return if p is part of a word according to vi */ libedit_private int cv__isword(wint_t p) { if (iswalnum(p) || p == L'_') return 1; if (iswgraph(p)) return 2; return 0; } /* cv__isWord(): * Return if p is part of a big word according to vi */ libedit_private int cv__isWord(wint_t p) { return !iswspace(p); } /* c__prev_word(): * Find the previous word */ libedit_private wchar_t * c__prev_word(wchar_t *p, wchar_t *low, int n, int (*wtest)(wint_t)) { p--; while (n--) { while ((p >= low) && !(*wtest)(*p)) p--; while ((p >= low) && (*wtest)(*p)) p--; } /* cp now points to one character before the word */ p++; if (p < low) p = low; /* cp now points where we want it */ return p; } /* c__next_word(): * Find the next word */ libedit_private wchar_t * c__next_word(wchar_t *p, wchar_t *high, int n, int (*wtest)(wint_t)) { while (n--) { while ((p < high) && !(*wtest)(*p)) p++; while ((p < high) && (*wtest)(*p)) p++; } if (p > high) p = high; /* p now points where we want it */ return p; } /* cv_next_word(): * Find the next word vi style */ libedit_private wchar_t * cv_next_word(EditLine *el, wchar_t *p, wchar_t *high, int n, int (*wtest)(wint_t)) { int test; while (n--) { test = (*wtest)(*p); while ((p < high) && (*wtest)(*p) == test) p++; /* * vi historically deletes with cw only the word preserving the * trailing whitespace! This is not what 'w' does.. */ if (n || el->el_chared.c_vcmd.action != (DELETE|INSERT)) while ((p < high) && iswspace(*p)) p++; } /* p now points where we want it */ if (p > high) return high; else return p; } /* cv_prev_word(): * Find the previous word vi style */ libedit_private wchar_t * cv_prev_word(wchar_t *p, wchar_t *low, int n, int (*wtest)(wint_t)) { int test; p--; while (n--) { while ((p > low) && iswspace(*p)) p--; test = (*wtest)(*p); while ((p >= low) && (*wtest)(*p) == test) p--; } p++; /* p now points where we want it */ if (p < low) return low; else return p; } /* cv_delfini(): * Finish vi delete action */ libedit_private void cv_delfini(EditLine *el) { int size; int action = el->el_chared.c_vcmd.action; if (action & INSERT) el->el_map.current = el->el_map.key; if (el->el_chared.c_vcmd.pos == 0) /* sanity */ return; size = (int)(el->el_line.cursor - el->el_chared.c_vcmd.pos); if (size == 0) size = 1; el->el_line.cursor = el->el_chared.c_vcmd.pos; if (action & YANK) { if (size > 0) cv_yank(el, el->el_line.cursor, size); else cv_yank(el, el->el_line.cursor + size, -size); } else { if (size > 0) { c_delafter(el, size); re_refresh_cursor(el); } else { c_delbefore(el, -size); el->el_line.cursor += size; } } el->el_chared.c_vcmd.action = NOP; } /* cv__endword(): * Go to the end of this word according to vi */ libedit_private wchar_t * cv__endword(wchar_t *p, wchar_t *high, int n, int (*wtest)(wint_t)) { int test; p++; while (n--) { while ((p < high) && iswspace(*p)) p++; test = (*wtest)(*p); while ((p < high) && (*wtest)(*p) == test) p++; } p--; return p; } /* ch_init(): * Initialize the character editor */ libedit_private int ch_init(EditLine *el) { el->el_line.buffer = el_calloc(EL_BUFSIZ, sizeof(*el->el_line.buffer)); if (el->el_line.buffer == NULL) return -1; el->el_line.cursor = el->el_line.buffer; el->el_line.lastchar = el->el_line.buffer; el->el_line.limit = &el->el_line.buffer[EL_BUFSIZ - EL_LEAVE]; el->el_chared.c_undo.buf = el_calloc(EL_BUFSIZ, sizeof(*el->el_chared.c_undo.buf)); if (el->el_chared.c_undo.buf == NULL) return -1; el->el_chared.c_undo.len = -1; el->el_chared.c_undo.cursor = 0; el->el_chared.c_redo.buf = el_calloc(EL_BUFSIZ, sizeof(*el->el_chared.c_redo.buf)); if (el->el_chared.c_redo.buf == NULL) return -1; el->el_chared.c_redo.pos = el->el_chared.c_redo.buf; el->el_chared.c_redo.lim = el->el_chared.c_redo.buf + EL_BUFSIZ; el->el_chared.c_redo.cmd = ED_UNASSIGNED; el->el_chared.c_vcmd.action = NOP; el->el_chared.c_vcmd.pos = el->el_line.buffer; el->el_chared.c_kill.buf = el_calloc(EL_BUFSIZ, sizeof(*el->el_chared.c_kill.buf)); if (el->el_chared.c_kill.buf == NULL) return -1; el->el_chared.c_kill.mark = el->el_line.buffer; el->el_chared.c_kill.last = el->el_chared.c_kill.buf; el->el_chared.c_resizefun = NULL; el->el_chared.c_resizearg = NULL; el->el_chared.c_aliasfun = NULL; el->el_chared.c_aliasarg = NULL; el->el_map.current = el->el_map.key; el->el_state.inputmode = MODE_INSERT; /* XXX: save a default */ el->el_state.doingarg = 0; el->el_state.metanext = 0; el->el_state.argument = 1; el->el_state.lastcmd = ED_UNASSIGNED; return 0; } /* ch_reset(): * Reset the character editor */ libedit_private void ch_reset(EditLine *el) { el->el_line.cursor = el->el_line.buffer; el->el_line.lastchar = el->el_line.buffer; el->el_chared.c_undo.len = -1; el->el_chared.c_undo.cursor = 0; el->el_chared.c_vcmd.action = NOP; el->el_chared.c_vcmd.pos = el->el_line.buffer; el->el_chared.c_kill.mark = el->el_line.buffer; el->el_map.current = el->el_map.key; el->el_state.inputmode = MODE_INSERT; /* XXX: save a default */ el->el_state.doingarg = 0; el->el_state.metanext = 0; el->el_state.argument = 1; el->el_state.lastcmd = ED_UNASSIGNED; el->el_history.eventno = 0; } /* ch_enlargebufs(): * Enlarge line buffer to be able to hold twice as much characters. * Returns 1 if successful, 0 if not. */ libedit_private int ch_enlargebufs(EditLine *el, size_t addlen) { size_t sz, newsz; wchar_t *newbuffer, *oldbuf, *oldkbuf; sz = (size_t)(el->el_line.limit - el->el_line.buffer + EL_LEAVE); newsz = sz * 2; /* * If newly required length is longer than current buffer, we need * to make the buffer big enough to hold both old and new stuff. */ if (addlen > sz) { while(newsz - sz < addlen) newsz *= 2; } /* * Reallocate line buffer. */ newbuffer = el_realloc(el->el_line.buffer, newsz * sizeof(*newbuffer)); if (!newbuffer) return 0; /* zero the newly added memory, leave old data in */ (void) memset(&newbuffer[sz], 0, (newsz - sz) * sizeof(*newbuffer)); oldbuf = el->el_line.buffer; el->el_line.buffer = newbuffer; el->el_line.cursor = newbuffer + (el->el_line.cursor - oldbuf); el->el_line.lastchar = newbuffer + (el->el_line.lastchar - oldbuf); /* don't set new size until all buffers are enlarged */ el->el_line.limit = &newbuffer[sz - EL_LEAVE]; /* * Reallocate kill buffer. */ newbuffer = el_realloc(el->el_chared.c_kill.buf, newsz * sizeof(*newbuffer)); if (!newbuffer) return 0; /* zero the newly added memory, leave old data in */ (void) memset(&newbuffer[sz], 0, (newsz - sz) * sizeof(*newbuffer)); oldkbuf = el->el_chared.c_kill.buf; el->el_chared.c_kill.buf = newbuffer; el->el_chared.c_kill.last = newbuffer + (el->el_chared.c_kill.last - oldkbuf); el->el_chared.c_kill.mark = el->el_line.buffer + (el->el_chared.c_kill.mark - oldbuf); /* * Reallocate undo buffer. */ newbuffer = el_realloc(el->el_chared.c_undo.buf, newsz * sizeof(*newbuffer)); if (!newbuffer) return 0; /* zero the newly added memory, leave old data in */ (void) memset(&newbuffer[sz], 0, (newsz - sz) * sizeof(*newbuffer)); el->el_chared.c_undo.buf = newbuffer; newbuffer = el_realloc(el->el_chared.c_redo.buf, newsz * sizeof(*newbuffer)); if (!newbuffer) return 0; el->el_chared.c_redo.pos = newbuffer + (el->el_chared.c_redo.pos - el->el_chared.c_redo.buf); el->el_chared.c_redo.lim = newbuffer + (el->el_chared.c_redo.lim - el->el_chared.c_redo.buf); el->el_chared.c_redo.buf = newbuffer; if (!hist_enlargebuf(el, sz, newsz)) return 0; /* Safe to set enlarged buffer size */ el->el_line.limit = &el->el_line.buffer[newsz - EL_LEAVE]; if (el->el_chared.c_resizefun) (*el->el_chared.c_resizefun)(el, el->el_chared.c_resizearg); return 1; } /* ch_end(): * Free the data structures used by the editor */ libedit_private void ch_end(EditLine *el) { el_free(el->el_line.buffer); el->el_line.buffer = NULL; el->el_line.limit = NULL; el_free(el->el_chared.c_undo.buf); el->el_chared.c_undo.buf = NULL; el_free(el->el_chared.c_redo.buf); el->el_chared.c_redo.buf = NULL; el->el_chared.c_redo.pos = NULL; el->el_chared.c_redo.lim = NULL; el->el_chared.c_redo.cmd = ED_UNASSIGNED; el_free(el->el_chared.c_kill.buf); el->el_chared.c_kill.buf = NULL; ch_reset(el); } /* el_insertstr(): * Insert string at cursor */ int el_winsertstr(EditLine *el, const wchar_t *s) { size_t len; if (s == NULL || (len = wcslen(s)) == 0) return -1; if (el->el_line.lastchar + len >= el->el_line.limit) { if (!ch_enlargebufs(el, len)) return -1; } c_insert(el, (int)len); while (*s) *el->el_line.cursor++ = *s++; return 0; } /* el_deletestr(): * Delete num characters before the cursor */ void el_deletestr(EditLine *el, int n) { if (n <= 0) return; if (el->el_line.cursor < &el->el_line.buffer[n]) return; c_delbefore(el, n); /* delete before dot */ el->el_line.cursor -= n; if (el->el_line.cursor < el->el_line.buffer) el->el_line.cursor = el->el_line.buffer; } +/* el_deletestr1(): + * Delete characters between start and end + */ +int +el_deletestr1(EditLine *el, int start, int end) +{ + size_t line_length, len; + wchar_t *p1, *p2; + + if (end <= start) + return 0; + + line_length = (size_t)(el->el_line.lastchar - el->el_line.buffer); + + if (start >= (int)line_length || end >= (int)line_length) + return 0; + + len = (size_t)(end - start); + if (len > line_length - (size_t)end) + len = line_length - (size_t)end; + + p1 = el->el_line.buffer + start; + p2 = el->el_line.buffer + end; + for (size_t i = 0; i < len; i++) { + *p1++ = *p2++; + el->el_line.lastchar--; + } + + if (el->el_line.cursor < el->el_line.buffer) + el->el_line.cursor = el->el_line.buffer; + + return end - start; +} + +/* el_wreplacestr(): + * Replace the contents of the line with the provided string + */ +int +el_wreplacestr(EditLine *el, const wchar_t *s) +{ + size_t len; + wchar_t * p; + + if (s == NULL || (len = wcslen(s)) == 0) + return -1; + + if (el->el_line.buffer + len >= el->el_line.limit) { + if (!ch_enlargebufs(el, len)) + return -1; + } + + p = el->el_line.buffer; + for (size_t i = 0; i < len; i++) + *p++ = *s++; + + el->el_line.buffer[len] = '\0'; + el->el_line.lastchar = el->el_line.buffer + len; + if (el->el_line.cursor > el->el_line.lastchar) + el->el_line.cursor = el->el_line.lastchar; + + return 0; +} + /* el_cursor(): * Move the cursor to the left or the right of the current position */ int el_cursor(EditLine *el, int n) { if (n == 0) goto out; el->el_line.cursor += n; if (el->el_line.cursor < el->el_line.buffer) el->el_line.cursor = el->el_line.buffer; if (el->el_line.cursor > el->el_line.lastchar) el->el_line.cursor = el->el_line.lastchar; out: return (int)(el->el_line.cursor - el->el_line.buffer); } /* c_gets(): * Get a string */ libedit_private int c_gets(EditLine *el, wchar_t *buf, const wchar_t *prompt) { ssize_t len; wchar_t *cp = el->el_line.buffer, ch; if (prompt) { len = (ssize_t)wcslen(prompt); (void)memcpy(cp, prompt, (size_t)len * sizeof(*cp)); cp += len; } len = 0; for (;;) { el->el_line.cursor = cp; *cp = ' '; el->el_line.lastchar = cp + 1; re_refresh(el); if (el_wgetc(el, &ch) != 1) { ed_end_of_file(el, 0); len = -1; break; } switch (ch) { case L'\b': /* Delete and backspace */ case 0177: if (len == 0) { len = -1; break; } len--; cp--; continue; case 0033: /* ESC */ case L'\r': /* Newline */ case L'\n': buf[len] = ch; break; default: if (len >= (ssize_t)(EL_BUFSIZ - 16)) terminal_beep(el); else { buf[len++] = ch; *cp++ = ch; } continue; } break; } el->el_line.buffer[0] = '\0'; el->el_line.lastchar = el->el_line.buffer; el->el_line.cursor = el->el_line.buffer; return (int)len; } /* c_hpos(): * Return the current horizontal position of the cursor */ libedit_private int c_hpos(EditLine *el) { wchar_t *ptr; /* * Find how many characters till the beginning of this line. */ if (el->el_line.cursor == el->el_line.buffer) return 0; else { for (ptr = el->el_line.cursor - 1; ptr >= el->el_line.buffer && *ptr != '\n'; ptr--) continue; return (int)(el->el_line.cursor - ptr - 1); } } libedit_private int ch_resizefun(EditLine *el, el_zfunc_t f, void *a) { el->el_chared.c_resizefun = f; el->el_chared.c_resizearg = a; return 0; } libedit_private int ch_aliasfun(EditLine *el, el_afunc_t f, void *a) { el->el_chared.c_aliasfun = f; el->el_chared.c_aliasarg = a; return 0; } diff --git a/contrib/libedit/chartype.h b/contrib/libedit/chartype.h index bfa3d54ec36c..bcdb293a12f4 100644 --- a/contrib/libedit/chartype.h +++ b/contrib/libedit/chartype.h @@ -1,119 +1,120 @@ -/* $NetBSD: chartype.h,v 1.36 2019/09/15 21:09:11 christos Exp $ */ +/* $NetBSD: chartype.h,v 1.37 2022/04/11 19:37:20 tnn Exp $ */ /*- * Copyright (c) 2009 The NetBSD Foundation, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef _h_chartype_f #define _h_chartype_f /* Ideally we should also test the value of the define to see if it * supports non-BMP code points without requiring UTF-16, but nothing * seems to actually advertise this properly, despite Unicode 3.1 having * been around since 2001... */ #if !defined(__NetBSD__) && \ !defined(__sun) && \ + !defined(__osf__) && \ !(defined(__APPLE__) && defined(__MACH__)) && \ !defined(__OpenBSD__) && \ !defined(__FreeBSD__) && \ !defined(__DragonFly__) #ifndef __STDC_ISO_10646__ /* In many places it is assumed that the first 127 code points are ASCII * compatible, so ensure wchar_t indeed does ISO 10646 and not some other * funky encoding that could break us in weird and wonderful ways. */ #error wchar_t must store ISO 10646 characters #endif #endif /* Oh for a with char32_t and __STDC_UTF_32__ in it... * ref: ISO/IEC DTR 19769 */ #if WCHAR_MAX < INT32_MAX #warning Build environment does not support non-BMP characters #endif /* * Conversion buffer */ typedef struct ct_buffer_t { char *cbuff; size_t csize; wchar_t *wbuff; size_t wsize; } ct_buffer_t; /* Encode a wide-character string and return the UTF-8 encoded result. */ char *ct_encode_string(const wchar_t *, ct_buffer_t *); /* Decode a (multi)?byte string and return the wide-character string result. */ wchar_t *ct_decode_string(const char *, ct_buffer_t *); /* Decode a (multi)?byte argv string array. * The pointer returned must be free()d when done. */ libedit_private wchar_t **ct_decode_argv(int, const char *[], ct_buffer_t *); /* Encode a character into the destination buffer, provided there is sufficient * buffer space available. Returns the number of bytes used up (zero if the * character cannot be encoded, -1 if there was not enough space available). */ libedit_private ssize_t ct_encode_char(char *, size_t, wchar_t); libedit_private size_t ct_enc_width(wchar_t); /* The maximum buffer size to hold the most unwieldy visual representation, * in this case \U+nnnnn. */ #define VISUAL_WIDTH_MAX ((size_t)8) /* The terminal is thought of in terms of X columns by Y lines. In the cases * where a wide character takes up more than one column, the adjacent * occupied column entries will contain this faux character. */ #define MB_FILL_CHAR ((wint_t)-1) /* Visual width of character c, taking into account ^? , \0177 and \U+nnnnn * style visual expansions. */ libedit_private int ct_visual_width(wchar_t); /* Turn the given character into the appropriate visual format, matching * the width given by ct_visual_width(). Returns the number of characters used * up, or -1 if insufficient space. Buffer length is in count of wchar_t's. */ libedit_private ssize_t ct_visual_char(wchar_t *, size_t, wchar_t); /* Convert the given string into visual format, using the ct_visual_char() * function. Uses a static buffer, so not threadsafe. */ libedit_private const wchar_t *ct_visual_string(const wchar_t *, ct_buffer_t *); /* printable character, use ct_visual_width() to find out display width */ #define CHTYPE_PRINT ( 0) /* control character found inside the ASCII portion of the charset */ #define CHTYPE_ASCIICTL (-1) /* a \t */ #define CHTYPE_TAB (-2) /* a \n */ #define CHTYPE_NL (-3) /* non-printable character */ #define CHTYPE_NONPRINT (-4) /* classification of character c, as one of the above defines */ libedit_private int ct_chr_class(wchar_t c); #endif /* _chartype_f */ diff --git a/contrib/libedit/eln.c b/contrib/libedit/eln.c index f432a2187c0d..563ec2a672a9 100644 --- a/contrib/libedit/eln.c +++ b/contrib/libedit/eln.c @@ -1,388 +1,394 @@ -/* $NetBSD: eln.c,v 1.36 2021/08/15 10:08:41 christos Exp $ */ +/* $NetBSD: eln.c,v 1.37 2022/01/11 18:30:15 christos Exp $ */ /*- * Copyright (c) 2009 The NetBSD Foundation, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #if !defined(lint) && !defined(SCCSID) -__RCSID("$NetBSD: eln.c,v 1.36 2021/08/15 10:08:41 christos Exp $"); +__RCSID("$NetBSD: eln.c,v 1.37 2022/01/11 18:30:15 christos Exp $"); #endif /* not lint && not SCCSID */ #include #include #include #include #include "el.h" int el_getc(EditLine *el, char *cp) { int num_read; wchar_t wc = 0; num_read = el_wgetc(el, &wc); *cp = '\0'; if (num_read <= 0) return num_read; num_read = wctob(wc); if (num_read == EOF) { errno = ERANGE; return -1; } else { *cp = (char)num_read; return 1; } } void el_push(EditLine *el, const char *str) { /* Using multibyte->wide string decoding works fine under single-byte * character sets too, and Does The Right Thing. */ el_wpush(el, ct_decode_string(str, &el->el_lgcyconv)); } const char * el_gets(EditLine *el, int *nread) { const wchar_t *tmp; tmp = el_wgets(el, nread); if (tmp != NULL) { int i; size_t nwread = 0; for (i = 0; i < *nread; i++) nwread += ct_enc_width(tmp[i]); *nread = (int)nwread; } return ct_encode_string(tmp, &el->el_lgcyconv); } int el_parse(EditLine *el, int argc, const char *argv[]) { int ret; const wchar_t **wargv; wargv = (void *)ct_decode_argv(argc, argv, &el->el_lgcyconv); if (!wargv) return -1; ret = el_wparse(el, argc, wargv); el_free(wargv); return ret; } int el_set(EditLine *el, int op, ...) { va_list ap; int ret; if (!el) return -1; va_start(ap, op); switch (op) { case EL_PROMPT: /* el_pfunc_t */ case EL_RPROMPT: { el_pfunc_t p = va_arg(ap, el_pfunc_t); ret = prompt_set(el, p, 0, op, 0); break; } case EL_RESIZE: { el_zfunc_t p = va_arg(ap, el_zfunc_t); void *arg = va_arg(ap, void *); ret = ch_resizefun(el, p, arg); break; } case EL_ALIAS_TEXT: { el_afunc_t p = va_arg(ap, el_afunc_t); void *arg = va_arg(ap, void *); ret = ch_aliasfun(el, p, arg); break; } case EL_PROMPT_ESC: case EL_RPROMPT_ESC: { el_pfunc_t p = va_arg(ap, el_pfunc_t); int c = va_arg(ap, int); ret = prompt_set(el, p, c, op, 0); break; } case EL_TERMINAL: /* const char * */ ret = el_wset(el, op, va_arg(ap, char *)); break; case EL_EDITOR: /* const wchar_t * */ ret = el_wset(el, op, ct_decode_string(va_arg(ap, char *), &el->el_lgcyconv)); break; case EL_SIGNAL: /* int */ case EL_EDITMODE: case EL_SAFEREAD: case EL_UNBUFFERED: case EL_PREP_TERM: ret = el_wset(el, op, va_arg(ap, int)); break; case EL_BIND: /* const char * list -> const wchar_t * list */ case EL_TELLTC: case EL_SETTC: case EL_ECHOTC: case EL_SETTY: { const char *argv[20]; int i; const wchar_t **wargv; for (i = 1; i < (int)__arraycount(argv) - 1; ++i) if ((argv[i] = va_arg(ap, const char *)) == NULL) break; argv[0] = argv[i] = NULL; wargv = (void *)ct_decode_argv(i + 1, argv, &el->el_lgcyconv); if (!wargv) { ret = -1; goto out; } /* * AFAIK we can't portably pass through our new wargv to * el_wset(), so we have to reimplement the body of * el_wset() for these ops. */ switch (op) { case EL_BIND: wargv[0] = L"bind"; ret = map_bind(el, i, wargv); break; case EL_TELLTC: wargv[0] = L"telltc"; ret = terminal_telltc(el, i, wargv); break; case EL_SETTC: wargv[0] = L"settc"; ret = terminal_settc(el, i, wargv); break; case EL_ECHOTC: wargv[0] = L"echotc"; ret = terminal_echotc(el, i, wargv); break; case EL_SETTY: wargv[0] = L"setty"; ret = tty_stty(el, i, wargv); break; default: ret = -1; } el_free(wargv); break; } /* XXX: do we need to change el_func_t too? */ case EL_ADDFN: { /* const char *, const char *, el_func_t */ const char *args[2]; el_func_t func; wchar_t **wargv; args[0] = va_arg(ap, const char *); args[1] = va_arg(ap, const char *); func = va_arg(ap, el_func_t); wargv = ct_decode_argv(2, args, &el->el_lgcyconv); if (!wargv) { ret = -1; goto out; } /* XXX: The two strdup's leak */ ret = map_addfunc(el, wcsdup(wargv[0]), wcsdup(wargv[1]), func); el_free(wargv); break; } case EL_HIST: { /* hist_fun_t, const char * */ hist_fun_t fun = va_arg(ap, hist_fun_t); void *ptr = va_arg(ap, void *); ret = hist_set(el, fun, ptr); el->el_flags |= NARROW_HISTORY; break; } case EL_GETCFN: /* el_rfunc_t */ ret = el_wset(el, op, va_arg(ap, el_rfunc_t)); break; case EL_CLIENTDATA: /* void * */ ret = el_wset(el, op, va_arg(ap, void *)); break; case EL_SETFP: { /* int, FILE * */ int what = va_arg(ap, int); FILE *fp = va_arg(ap, FILE *); ret = el_wset(el, op, what, fp); break; } case EL_REFRESH: re_clear_display(el); re_refresh(el); terminal__flush(el); ret = 0; break; default: ret = -1; break; } out: va_end(ap); return ret; } int el_get(EditLine *el, int op, ...) { va_list ap; int ret; if (!el) return -1; va_start(ap, op); switch (op) { case EL_PROMPT: /* el_pfunc_t * */ case EL_RPROMPT: { el_pfunc_t *p = va_arg(ap, el_pfunc_t *); ret = prompt_get(el, p, 0, op); break; } case EL_PROMPT_ESC: /* el_pfunc_t *, char **/ case EL_RPROMPT_ESC: { el_pfunc_t *p = va_arg(ap, el_pfunc_t *); char *c = va_arg(ap, char *); wchar_t wc = 0; ret = prompt_get(el, p, &wc, op); *c = (char)wc; break; } case EL_EDITOR: { const char **p = va_arg(ap, const char **); const wchar_t *pw; ret = el_wget(el, op, &pw); *p = ct_encode_string(pw, &el->el_lgcyconv); if (!el->el_lgcyconv.csize) ret = -1; break; } case EL_TERMINAL: /* const char ** */ ret = el_wget(el, op, va_arg(ap, const char **)); break; case EL_SIGNAL: /* int * */ case EL_EDITMODE: case EL_SAFEREAD: case EL_UNBUFFERED: case EL_PREP_TERM: ret = el_wget(el, op, va_arg(ap, int *)); break; case EL_GETTC: { char *argv[3]; static char gettc[] = "gettc"; argv[0] = gettc; argv[1] = va_arg(ap, char *); argv[2] = va_arg(ap, void *); ret = terminal_gettc(el, 3, argv); break; } case EL_GETCFN: /* el_rfunc_t */ ret = el_wget(el, op, va_arg(ap, el_rfunc_t *)); break; case EL_CLIENTDATA: /* void ** */ ret = el_wget(el, op, va_arg(ap, void **)); break; case EL_GETFP: { /* int, FILE ** */ int what = va_arg(ap, int); FILE **fpp = va_arg(ap, FILE **); ret = el_wget(el, op, what, fpp); break; } default: ret = -1; break; } va_end(ap); return ret; } const LineInfo * el_line(EditLine *el) { const LineInfoW *winfo = el_wline(el); LineInfo *info = &el->el_lgcylinfo; size_t offset; const wchar_t *p; info->buffer = ct_encode_string(winfo->buffer, &el->el_lgcyconv); offset = 0; for (p = winfo->buffer; p < winfo->cursor; p++) offset += ct_enc_width(*p); info->cursor = info->buffer + offset; offset = 0; for (p = winfo->buffer; p < winfo->lastchar; p++) offset += ct_enc_width(*p); info->lastchar = info->buffer + offset; return info; } int el_insertstr(EditLine *el, const char *str) { return el_winsertstr(el, ct_decode_string(str, &el->el_lgcyconv)); } + +int +el_replacestr(EditLine *el, const char *str) +{ + return el_wreplacestr(el, ct_decode_string(str, &el->el_lgcyconv)); +} diff --git a/contrib/libedit/filecomplete.c b/contrib/libedit/filecomplete.c index 6dc7cff1d055..844c3efa95dd 100644 --- a/contrib/libedit/filecomplete.c +++ b/contrib/libedit/filecomplete.c @@ -1,858 +1,861 @@ -/* $NetBSD: filecomplete.c,v 1.68 2021/05/05 14:49:59 christos Exp $ */ +/* $NetBSD: filecomplete.c,v 1.70 2022/03/12 15:29:17 christos Exp $ */ /*- * Copyright (c) 1997 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Jaromir Dolecek. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #if !defined(lint) && !defined(SCCSID) -__RCSID("$NetBSD: filecomplete.c,v 1.68 2021/05/05 14:49:59 christos Exp $"); +__RCSID("$NetBSD: filecomplete.c,v 1.70 2022/03/12 15:29:17 christos Exp $"); #endif /* not lint && not SCCSID */ #include #include #include #include #include #include #include #include #include #include #include #include "el.h" #include "filecomplete.h" static const wchar_t break_chars[] = L" \t\n\"\\'`@$><=;|&{("; /********************************/ /* completion functions */ /* * does tilde expansion of strings of type ``~user/foo'' * if ``user'' isn't valid user name or ``txt'' doesn't start * w/ '~', returns pointer to strdup()ed copy of ``txt'' * * it's the caller's responsibility to free() the returned string */ char * fn_tilde_expand(const char *txt) { #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT) struct passwd pwres; char pwbuf[1024]; #endif struct passwd *pass; + const char *pos; char *temp; size_t len = 0; if (txt[0] != '~') return strdup(txt); - temp = strchr(txt + 1, '/'); - if (temp == NULL) { + pos = strchr(txt + 1, '/'); + if (pos == NULL) { temp = strdup(txt + 1); if (temp == NULL) return NULL; } else { /* text until string after slash */ - len = (size_t)(temp - txt + 1); + len = (size_t)(pos - txt + 1); temp = el_calloc(len, sizeof(*temp)); if (temp == NULL) return NULL; (void)strlcpy(temp, txt + 1, len - 1); } if (temp[0] == 0) { #ifdef HAVE_GETPW_R_POSIX if (getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf), &pass) != 0) pass = NULL; #elif HAVE_GETPW_R_DRAFT pass = getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf)); #else pass = getpwuid(getuid()); #endif } else { #ifdef HAVE_GETPW_R_POSIX if (getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf), &pass) != 0) pass = NULL; #elif HAVE_GETPW_R_DRAFT pass = getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf)); #else pass = getpwnam(temp); #endif } el_free(temp); /* value no more needed */ if (pass == NULL) return strdup(txt); /* update pointer txt to point at string immedially following */ /* first slash */ txt += len; len = strlen(pass->pw_dir) + 1 + strlen(txt) + 1; temp = el_calloc(len, sizeof(*temp)); if (temp == NULL) return NULL; (void)snprintf(temp, len, "%s/%s", pass->pw_dir, txt); return temp; } static int -needs_escaping(char c) +needs_escaping(wchar_t c) { switch (c) { case '\'': case '"': case '(': case ')': case '\\': case '<': case '>': case '$': case '#': case ' ': case '\n': case '\t': case '?': case ';': case '`': case '@': case '=': case '|': case '{': case '}': case '&': case '*': case '[': return 1; default: return 0; } } static int needs_dquote_escaping(char c) { switch (c) { case '"': case '\\': case '`': case '$': return 1; default: return 0; } } static wchar_t * unescape_string(const wchar_t *string, size_t length) { size_t i; size_t j = 0; wchar_t *unescaped = el_calloc(length + 1, sizeof(*string)); if (unescaped == NULL) return NULL; for (i = 0; i < length ; i++) { if (string[i] == '\\') continue; unescaped[j++] = string[i]; } unescaped[j] = 0; return unescaped; } static char * escape_filename(EditLine * el, const char *filename, int single_match, const char *(*app_func)(const char *)) { size_t original_len = 0; size_t escaped_character_count = 0; size_t offset = 0; size_t newlen; const char *s; char c; size_t s_quoted = 0; /* does the input contain a single quote */ size_t d_quoted = 0; /* does the input contain a double quote */ char *escaped_str; wchar_t *temp = el->el_line.buffer; const char *append_char = NULL; if (filename == NULL) return NULL; while (temp != el->el_line.cursor) { /* * If we see a single quote but have not seen a double quote - * so far set/unset s_quote + * so far set/unset s_quote, unless it is already quoted */ - if (temp[0] == '\'' && !d_quoted) + if (temp[0] == '\'' && !d_quoted && + (temp == el->el_line.buffer || temp[-1] != '\\')) s_quoted = !s_quoted; /* * vice versa to the above condition */ else if (temp[0] == '"' && !s_quoted) d_quoted = !d_quoted; temp++; } /* Count number of special characters so that we can calculate * number of extra bytes needed in the new string */ for (s = filename; *s; s++, original_len++) { c = *s; /* Inside a single quote only single quotes need escaping */ if (s_quoted && c == '\'') { escaped_character_count += 3; continue; } /* Inside double quotes only ", \, ` and $ need escaping */ if (d_quoted && needs_dquote_escaping(c)) { escaped_character_count++; continue; } if (!s_quoted && !d_quoted && needs_escaping(c)) escaped_character_count++; } newlen = original_len + escaped_character_count + 1; if (s_quoted || d_quoted) newlen++; if (single_match && app_func) newlen++; if ((escaped_str = el_malloc(newlen)) == NULL) return NULL; for (s = filename; *s; s++) { c = *s; if (!needs_escaping(c)) { /* no escaping is required continue as usual */ escaped_str[offset++] = c; continue; } /* single quotes inside single quotes require special handling */ if (c == '\'' && s_quoted) { escaped_str[offset++] = '\''; escaped_str[offset++] = '\\'; escaped_str[offset++] = '\''; escaped_str[offset++] = '\''; continue; } /* Otherwise no escaping needed inside single quotes */ if (s_quoted) { escaped_str[offset++] = c; continue; } /* No escaping needed inside a double quoted string either * unless we see a '$', '\', '`', or '"' (itself) */ if (d_quoted && !needs_dquote_escaping(c)) { escaped_str[offset++] = c; continue; } /* If we reach here that means escaping is actually needed */ escaped_str[offset++] = '\\'; escaped_str[offset++] = c; } if (single_match && app_func) { escaped_str[offset] = 0; append_char = app_func(filename); /* we want to append space only if we are not inside quotes */ if (append_char[0] == ' ') { if (!s_quoted && !d_quoted) escaped_str[offset++] = append_char[0]; } else escaped_str[offset++] = append_char[0]; } /* close the quotes if single match and the match is not a directory */ if (single_match && (append_char && append_char[0] == ' ')) { if (s_quoted) escaped_str[offset++] = '\''; else if (d_quoted) escaped_str[offset++] = '"'; } escaped_str[offset] = 0; return escaped_str; } /* * return first found file name starting by the ``text'' or NULL if no * such file can be found * value of ``state'' is ignored * * it's the caller's responsibility to free the returned string */ char * fn_filename_completion_function(const char *text, int state) { static DIR *dir = NULL; static char *filename = NULL, *dirname = NULL, *dirpath = NULL; static size_t filename_len = 0; struct dirent *entry; char *temp; + const char *pos; size_t len; if (state == 0 || dir == NULL) { - temp = strrchr(text, '/'); - if (temp) { + pos = strrchr(text, '/'); + if (pos) { char *nptr; - temp++; - nptr = el_realloc(filename, (strlen(temp) + 1) * + pos++; + nptr = el_realloc(filename, (strlen(pos) + 1) * sizeof(*nptr)); if (nptr == NULL) { el_free(filename); filename = NULL; return NULL; } filename = nptr; - (void)strcpy(filename, temp); - len = (size_t)(temp - text); /* including last slash */ + (void)strcpy(filename, pos); + len = (size_t)(pos - text); /* including last slash */ nptr = el_realloc(dirname, (len + 1) * sizeof(*nptr)); if (nptr == NULL) { el_free(dirname); dirname = NULL; return NULL; } dirname = nptr; (void)strlcpy(dirname, text, len + 1); } else { el_free(filename); if (*text == 0) filename = NULL; else { filename = strdup(text); if (filename == NULL) return NULL; } el_free(dirname); dirname = NULL; } if (dir != NULL) { (void)closedir(dir); dir = NULL; } /* support for ``~user'' syntax */ el_free(dirpath); dirpath = NULL; if (dirname == NULL) { if ((dirname = strdup("")) == NULL) return NULL; dirpath = strdup("./"); } else if (*dirname == '~') dirpath = fn_tilde_expand(dirname); else dirpath = strdup(dirname); if (dirpath == NULL) return NULL; dir = opendir(dirpath); if (!dir) return NULL; /* cannot open the directory */ /* will be used in cycle */ filename_len = filename ? strlen(filename) : 0; } /* find the match */ while ((entry = readdir(dir)) != NULL) { /* skip . and .. */ if (entry->d_name[0] == '.' && (!entry->d_name[1] || (entry->d_name[1] == '.' && !entry->d_name[2]))) continue; if (filename_len == 0) break; /* otherwise, get first entry where first */ /* filename_len characters are equal */ if (entry->d_name[0] == filename[0] #if HAVE_STRUCT_DIRENT_D_NAMLEN && entry->d_namlen >= filename_len #else && strlen(entry->d_name) >= filename_len #endif && strncmp(entry->d_name, filename, filename_len) == 0) break; } if (entry) { /* match found */ #if HAVE_STRUCT_DIRENT_D_NAMLEN len = entry->d_namlen; #else len = strlen(entry->d_name); #endif len = strlen(dirname) + len + 1; temp = el_calloc(len, sizeof(*temp)); if (temp == NULL) return NULL; (void)snprintf(temp, len, "%s%s", dirname, entry->d_name); } else { (void)closedir(dir); dir = NULL; temp = NULL; } return temp; } static const char * append_char_function(const char *name) { struct stat stbuf; char *expname = *name == '~' ? fn_tilde_expand(name) : NULL; const char *rs = " "; if (stat(expname ? expname : name, &stbuf) == -1) goto out; if (S_ISDIR(stbuf.st_mode)) rs = "/"; out: if (expname) el_free(expname); return rs; } /* * returns list of completions for text given * non-static for readline. */ char ** completion_matches(const char *, char *(*)(const char *, int)); char ** completion_matches(const char *text, char *(*genfunc)(const char *, int)) { char **match_list = NULL, *retstr, *prevstr; size_t match_list_len, max_equal, which, i; size_t matches; matches = 0; match_list_len = 1; while ((retstr = (*genfunc) (text, (int)matches)) != NULL) { /* allow for list terminator here */ if (matches + 3 >= match_list_len) { char **nmatch_list; while (matches + 3 >= match_list_len) match_list_len <<= 1; nmatch_list = el_realloc(match_list, match_list_len * sizeof(*nmatch_list)); if (nmatch_list == NULL) { el_free(match_list); return NULL; } match_list = nmatch_list; } match_list[++matches] = retstr; } if (!match_list) return NULL; /* nothing found */ /* find least denominator and insert it to match_list[0] */ which = 2; prevstr = match_list[1]; max_equal = strlen(prevstr); for (; which <= matches; which++) { for (i = 0; i < max_equal && prevstr[i] == match_list[which][i]; i++) continue; max_equal = i; } retstr = el_calloc(max_equal + 1, sizeof(*retstr)); if (retstr == NULL) { el_free(match_list); return NULL; } (void)strlcpy(retstr, match_list[1], max_equal + 1); match_list[0] = retstr; /* add NULL as last pointer to the array */ match_list[matches + 1] = NULL; return match_list; } /* * Sort function for qsort(). Just wrapper around strcasecmp(). */ static int _fn_qsort_string_compare(const void *i1, const void *i2) { const char *s1 = ((const char * const *)i1)[0]; const char *s2 = ((const char * const *)i2)[0]; return strcasecmp(s1, s2); } /* * Display list of strings in columnar format on readline's output stream. * 'matches' is list of strings, 'num' is number of strings in 'matches', * 'width' is maximum length of string in 'matches'. * * matches[0] is not one of the match strings, but it is counted in * num, so the strings are matches[1] *through* matches[num-1]. */ void fn_display_match_list(EditLine * el, char **matches, size_t num, size_t width, const char *(*app_func) (const char *)) { size_t line, lines, col, cols, thisguy; int screenwidth = el->el_terminal.t_size.h; if (app_func == NULL) app_func = append_char_function; /* Ignore matches[0]. Avoid 1-based array logic below. */ matches++; num--; /* * Find out how many entries can be put on one line; count * with one space between strings the same way it's printed. */ cols = (size_t)screenwidth / (width + 2); if (cols == 0) cols = 1; /* how many lines of output, rounded up */ lines = (num + cols - 1) / cols; /* Sort the items. */ qsort(matches, num, sizeof(char *), _fn_qsort_string_compare); /* * On the ith line print elements i, i+lines, i+lines*2, etc. */ for (line = 0; line < lines; line++) { for (col = 0; col < cols; col++) { thisguy = line + col * lines; if (thisguy >= num) break; (void)fprintf(el->el_outfile, "%s%s%s", col == 0 ? "" : " ", matches[thisguy], (*app_func)(matches[thisguy])); (void)fprintf(el->el_outfile, "%-*s", (int) (width - strlen(matches[thisguy])), ""); } (void)fprintf(el->el_outfile, "\n"); } } static wchar_t * find_word_to_complete(const wchar_t * cursor, const wchar_t * buffer, const wchar_t * word_break, const wchar_t * special_prefixes, size_t * length, int do_unescape) { /* We now look backwards for the start of a filename/variable word */ const wchar_t *ctemp = cursor; wchar_t *temp; size_t len; /* if the cursor is placed at a slash or a quote, we need to find the * word before it */ if (ctemp > buffer) { switch (ctemp[-1]) { case '\\': case '\'': case '"': ctemp--; break; default: break; } } for (;;) { if (ctemp <= buffer) break; - if (wcschr(word_break, ctemp[-1])) { - if (ctemp - buffer >= 2 && ctemp[-2] == '\\') { - ctemp -= 2; - continue; - } - break; + if (ctemp - buffer >= 2 && ctemp[-2] == '\\' && + needs_escaping(ctemp[-1])) { + ctemp -= 2; + continue; } + if (wcschr(word_break, ctemp[-1])) + break; if (special_prefixes && wcschr(special_prefixes, ctemp[-1])) break; ctemp--; } len = (size_t) (cursor - ctemp); if (len == 1 && (ctemp[0] == '\'' || ctemp[0] == '"')) { len = 0; ctemp++; } *length = len; if (do_unescape) { wchar_t *unescaped_word = unescape_string(ctemp, len); if (unescaped_word == NULL) return NULL; return unescaped_word; } temp = el_malloc((len + 1) * sizeof(*temp)); (void) wcsncpy(temp, ctemp, len); temp[len] = '\0'; return temp; } /* * Complete the word at or before point, * 'what_to_do' says what to do with the completion. * \t means do standard completion. * `?' means list the possible completions. * `*' means insert all of the possible completions. * `!' means to do standard completion, and list all possible completions if * there is more than one. * * Note: '*' support is not implemented * '!' could never be invoked */ int fn_complete2(EditLine *el, char *(*complete_func)(const char *, int), char **(*attempted_completion_function)(const char *, int, int), const wchar_t *word_break, const wchar_t *special_prefixes, const char *(*app_func)(const char *), size_t query_items, int *completion_type, int *over, int *point, int *end, unsigned int flags) { const LineInfoW *li; wchar_t *temp; char **matches; char *completion; size_t len; int what_to_do = '\t'; int retval = CC_NORM; int do_unescape = flags & FN_QUOTE_MATCH; if (el->el_state.lastcmd == el->el_state.thiscmd) what_to_do = '?'; /* readline's rl_complete() has to be told what we did... */ if (completion_type != NULL) *completion_type = what_to_do; if (!complete_func) complete_func = fn_filename_completion_function; if (!app_func) app_func = append_char_function; li = el_wline(el); temp = find_word_to_complete(li->cursor, li->buffer, word_break, special_prefixes, &len, do_unescape); if (temp == NULL) goto out; /* these can be used by function called in completion_matches() */ /* or (*attempted_completion_function)() */ if (point != NULL) *point = (int)(li->cursor - li->buffer); if (end != NULL) *end = (int)(li->lastchar - li->buffer); if (attempted_completion_function) { int cur_off = (int)(li->cursor - li->buffer); matches = (*attempted_completion_function)( ct_encode_string(temp, &el->el_scratch), cur_off - (int)len, cur_off); } else matches = NULL; if (!attempted_completion_function || (over != NULL && !*over && !matches)) matches = completion_matches( ct_encode_string(temp, &el->el_scratch), complete_func); if (over != NULL) *over = 0; if (matches == NULL) { goto out; } int i; size_t matches_num, maxlen, match_len, match_display=1; int single_match = matches[2] == NULL && (matches[1] == NULL || strcmp(matches[0], matches[1]) == 0); retval = CC_REFRESH; if (matches[0][0] != '\0') { el_deletestr(el, (int)len); if (flags & FN_QUOTE_MATCH) completion = escape_filename(el, matches[0], single_match, app_func); else completion = strdup(matches[0]); if (completion == NULL) goto out2; /* * Replace the completed string with the common part of * all possible matches if there is a possible completion. */ el_winsertstr(el, ct_decode_string(completion, &el->el_scratch)); if (single_match && attempted_completion_function && !(flags & FN_QUOTE_MATCH)) { /* * We found an exact match. Add a space after * it, unless we do filename completion and the * object is a directory. Also do necessary * escape quoting */ el_winsertstr(el, ct_decode_string( (*app_func)(completion), &el->el_scratch)); } free(completion); } if (!single_match && (what_to_do == '!' || what_to_do == '?')) { /* * More than one match and requested to list possible * matches. */ for(i = 1, maxlen = 0; matches[i]; i++) { match_len = strlen(matches[i]); if (match_len > maxlen) maxlen = match_len; } /* matches[1] through matches[i-1] are available */ matches_num = (size_t)(i - 1); /* newline to get on next line from command line */ (void)fprintf(el->el_outfile, "\n"); /* * If there are too many items, ask user for display * confirmation. */ if (matches_num > query_items) { (void)fprintf(el->el_outfile, "Display all %zu possibilities? (y or n) ", matches_num); (void)fflush(el->el_outfile); if (getc(stdin) != 'y') match_display = 0; (void)fprintf(el->el_outfile, "\n"); } if (match_display) { /* * Interface of this function requires the * strings be matches[1..num-1] for compat. * We have matches_num strings not counting * the prefix in matches[0], so we need to * add 1 to matches_num for the call. */ fn_display_match_list(el, matches, matches_num+1, maxlen, app_func); } retval = CC_REDISPLAY; } else if (matches[0][0]) { /* * There was some common match, but the name was * not complete enough. Next tab will print possible * completions. */ el_beep(el); } else { /* lcd is not a valid object - further specification */ /* is needed */ el_beep(el); retval = CC_NORM; } /* free elements of array and the array itself */ out2: for (i = 0; matches[i]; i++) el_free(matches[i]); el_free(matches); matches = NULL; out: el_free(temp); return retval; } int fn_complete(EditLine *el, char *(*complete_func)(const char *, int), char **(*attempted_completion_function)(const char *, int, int), const wchar_t *word_break, const wchar_t *special_prefixes, const char *(*app_func)(const char *), size_t query_items, int *completion_type, int *over, int *point, int *end) { return fn_complete2(el, complete_func, attempted_completion_function, word_break, special_prefixes, app_func, query_items, completion_type, over, point, end, attempted_completion_function ? 0 : FN_QUOTE_MATCH); } /* * el-compatible wrapper around rl_complete; needed for key binding */ /* ARGSUSED */ unsigned char _el_fn_complete(EditLine *el, int ch __attribute__((__unused__))) { return (unsigned char)fn_complete(el, NULL, NULL, break_chars, NULL, NULL, (size_t)100, NULL, NULL, NULL, NULL); } /* * el-compatible wrapper around rl_complete; needed for key binding */ /* ARGSUSED */ unsigned char _el_fn_sh_complete(EditLine *el, int ch) { return _el_fn_complete(el, ch); } diff --git a/contrib/libedit/filecomplete.h b/contrib/libedit/filecomplete.h index 60ea4894414b..796ae7ab3276 100644 --- a/contrib/libedit/filecomplete.h +++ b/contrib/libedit/filecomplete.h @@ -1,51 +1,51 @@ -/* $NetBSD: filecomplete.h,v 1.13 2021/03/28 13:38:10 christos Exp $ */ +/* $NetBSD: filecomplete.h,v 1.14 2021/09/26 13:45:54 christos Exp $ */ /*- * Copyright (c) 1997 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Jaromir Dolecek. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef _FILECOMPLETE_H_ #define _FILECOMPLETE_H_ int fn_complete(EditLine *, char *(*)(const char *, int), char **(*)(const char *, int, int), const wchar_t *, const wchar_t *, const char *(*)(const char *), size_t, int *, int *, int *, int *); int fn_complete2(EditLine *, char *(*)(const char *, int), char **(*)(const char *, int, int), const wchar_t *, const wchar_t *, const char *(*)(const char *), size_t, int *, int *, int *, int *, unsigned int); -#define FN_QUOTE_MATCH 1 /* Quote the returned match */ +#define FN_QUOTE_MATCH 1U /* Quote the returned match */ void fn_display_match_list(EditLine *, char **, size_t, size_t, const char *(*)(const char *)); char *fn_tilde_expand(const char *); char *fn_filename_completion_function(const char *, int); #endif diff --git a/contrib/libedit/histedit.h b/contrib/libedit/histedit.h index 511750e0137e..507c71a6ceb1 100644 --- a/contrib/libedit/histedit.h +++ b/contrib/libedit/histedit.h @@ -1,316 +1,318 @@ -/* $NetBSD: histedit.h,v 1.58 2021/08/15 10:08:41 christos Exp $ */ +/* $NetBSD: histedit.h,v 1.61 2022/02/08 21:13:22 rillig Exp $ */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Christos Zoulas of Cornell University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)histedit.h 8.2 (Berkeley) 1/3/94 */ /* * histedit.h: Line editor and history interface. */ #ifndef _HISTEDIT_H_ #define _HISTEDIT_H_ #define LIBEDIT_MAJOR 2 #define LIBEDIT_MINOR 11 #include #include #ifdef __cplusplus extern "C" { #endif /* * ==== Editing ==== */ typedef struct editline EditLine; /* * For user-defined function interface */ typedef struct lineinfo { const char *buffer; const char *cursor; const char *lastchar; } LineInfo; /* * EditLine editor function return codes. * For user-defined function interface */ #define CC_NORM 0 #define CC_NEWLINE 1 #define CC_EOF 2 #define CC_ARGHACK 3 #define CC_REFRESH 4 #define CC_CURSOR 5 #define CC_ERROR 6 #define CC_FATAL 7 #define CC_REDISPLAY 8 #define CC_REFRESH_BEEP 9 /* * Initialization, cleanup, and resetting */ EditLine *el_init(const char *, FILE *, FILE *, FILE *); EditLine *el_init_fd(const char *, FILE *, FILE *, FILE *, int, int, int); void el_end(EditLine *); void el_reset(EditLine *); /* * Get a line, a character or push a string back in the input queue */ const char *el_gets(EditLine *, int *); int el_getc(EditLine *, char *); void el_push(EditLine *, const char *); /* * Beep! */ void el_beep(EditLine *); /* * High level function internals control * Parses argc, argv array and executes builtin editline commands */ int el_parse(EditLine *, int, const char **); /* * Low level editline access functions */ int el_set(EditLine *, int, ...); int el_get(EditLine *, int, ...); unsigned char _el_fn_complete(EditLine *, int); unsigned char _el_fn_sh_complete(EditLine *, int); /* * el_set/el_get parameters * * When using el_wset/el_wget (as opposed to el_set/el_get): * Char is wchar_t, otherwise it is char. * prompt_func is el_wpfunc_t, otherwise it is el_pfunc_t . * Prompt function prototypes are: * typedef char *(*el_pfunct_t) (EditLine *); * typedef wchar_t *(*el_wpfunct_t) (EditLine *); * * For operations that support set or set/get, the argument types listed are for * the "set" operation. For "get", each listed type must be a pointer. * E.g. EL_EDITMODE takes an int when set, but an int* when get. * * Operations that only support "get" have the correct argument types listed. */ #define EL_PROMPT 0 /* , prompt_func); set/get */ #define EL_TERMINAL 1 /* , const char *); set/get */ #define EL_EDITOR 2 /* , const Char *); set/get */ #define EL_SIGNAL 3 /* , int); set/get */ #define EL_BIND 4 /* , const Char *, ..., NULL); set */ #define EL_TELLTC 5 /* , const Char *, ..., NULL); set */ #define EL_SETTC 6 /* , const Char *, ..., NULL); set */ #define EL_ECHOTC 7 /* , const Char *, ..., NULL); set */ #define EL_SETTY 8 /* , const Char *, ..., NULL); set */ #define EL_ADDFN 9 /* , const Char *, const Char, set */ /* el_func_t); */ #define EL_HIST 10 /* , hist_fun_t, const void *); set */ #define EL_EDITMODE 11 /* , int); set/get */ #define EL_RPROMPT 12 /* , prompt_func); set/get */ #define EL_GETCFN 13 /* , el_rfunc_t); set/get */ #define EL_CLIENTDATA 14 /* , void *); set/get */ #define EL_UNBUFFERED 15 /* , int); set/get */ #define EL_PREP_TERM 16 /* , int); set */ #define EL_GETTC 17 /* , const Char *, ..., NULL); get */ #define EL_GETFP 18 /* , int, FILE **); get */ #define EL_SETFP 19 /* , int, FILE *); set */ #define EL_REFRESH 20 /* , void); set */ #define EL_PROMPT_ESC 21 /* , prompt_func, Char); set/get */ #define EL_RPROMPT_ESC 22 /* , prompt_func, Char); set/get */ #define EL_RESIZE 23 /* , el_zfunc_t, void *); set */ #define EL_ALIAS_TEXT 24 /* , el_afunc_t, void *); set */ #define EL_SAFEREAD 25 /* , int); set/get */ #define EL_BUILTIN_GETCFN (NULL) /* * Source named file or $PWD/.editrc or $HOME/.editrc */ int el_source(EditLine *, const char *); /* * Must be called when the terminal changes size; If EL_SIGNAL * is set this is done automatically otherwise it is the responsibility * of the application */ void el_resize(EditLine *); /* * User-defined function interface. */ const LineInfo *el_line(EditLine *); int el_insertstr(EditLine *, const char *); void el_deletestr(EditLine *, int); - +int el_replacestr(EditLine *, const char *); +int el_deletestr1(EditLine *, int, int); /* * ==== History ==== */ typedef struct history History; typedef struct HistEvent { int num; const char *str; } HistEvent; /* * History access functions. */ History * history_init(void); void history_end(History *); int history(History *, HistEvent *, int, ...); #define H_FUNC 0 /* , UTSL */ #define H_SETSIZE 1 /* , const int); */ #define H_GETSIZE 2 /* , void); */ #define H_FIRST 3 /* , void); */ #define H_LAST 4 /* , void); */ #define H_PREV 5 /* , void); */ #define H_NEXT 6 /* , void); */ #define H_CURR 8 /* , const int); */ #define H_SET 7 /* , int); */ #define H_ADD 9 /* , const wchar_t *); */ #define H_ENTER 10 /* , const wchar_t *); */ #define H_APPEND 11 /* , const wchar_t *); */ #define H_END 12 /* , void); */ #define H_NEXT_STR 13 /* , const wchar_t *); */ #define H_PREV_STR 14 /* , const wchar_t *); */ #define H_NEXT_EVENT 15 /* , const int); */ #define H_PREV_EVENT 16 /* , const int); */ #define H_LOAD 17 /* , const char *); */ #define H_SAVE 18 /* , const char *); */ #define H_CLEAR 19 /* , void); */ #define H_SETUNIQUE 20 /* , int); */ #define H_GETUNIQUE 21 /* , void); */ #define H_DEL 22 /* , int); */ #define H_NEXT_EVDATA 23 /* , const int, histdata_t *); */ #define H_DELDATA 24 /* , int, histdata_t *);*/ #define H_REPLACE 25 /* , const char *, histdata_t); */ #define H_SAVE_FP 26 /* , FILE *); */ #define H_NSAVE_FP 27 /* , size_t, FILE *); */ /* * ==== Tokenization ==== */ typedef struct tokenizer Tokenizer; /* * String tokenization functions, using simplified sh(1) quoting rules */ Tokenizer *tok_init(const char *); void tok_end(Tokenizer *); void tok_reset(Tokenizer *); int tok_line(Tokenizer *, const LineInfo *, int *, const char ***, int *, int *); int tok_str(Tokenizer *, const char *, int *, const char ***); /* * Begin Wide Character Support */ #include #include /* * ==== Editing ==== */ typedef struct lineinfow { const wchar_t *buffer; const wchar_t *cursor; const wchar_t *lastchar; } LineInfoW; typedef int (*el_rfunc_t)(EditLine *, wchar_t *); const wchar_t *el_wgets(EditLine *, int *); int el_wgetc(EditLine *, wchar_t *); void el_wpush(EditLine *, const wchar_t *); int el_wparse(EditLine *, int, const wchar_t **); int el_wset(EditLine *, int, ...); int el_wget(EditLine *, int, ...); int el_cursor(EditLine *, int); const LineInfoW *el_wline(EditLine *); int el_winsertstr(EditLine *, const wchar_t *); #define el_wdeletestr el_deletestr +int el_wreplacestr(EditLine *, const wchar_t *); /* * ==== History ==== */ typedef struct histeventW { int num; const wchar_t *str; } HistEventW; typedef struct historyW HistoryW; HistoryW * history_winit(void); void history_wend(HistoryW *); int history_w(HistoryW *, HistEventW *, int, ...); /* * ==== Tokenization ==== */ typedef struct tokenizerW TokenizerW; /* Wide character tokenizer support */ TokenizerW *tok_winit(const wchar_t *); void tok_wend(TokenizerW *); void tok_wreset(TokenizerW *); int tok_wline(TokenizerW *, const LineInfoW *, int *, const wchar_t ***, int *, int *); int tok_wstr(TokenizerW *, const wchar_t *, int *, const wchar_t ***); #ifdef __cplusplus } #endif #endif /* _HISTEDIT_H_ */ diff --git a/contrib/libedit/readline.c b/contrib/libedit/readline.c index c12eb7481bf4..7d7f1ec3b9fa 100644 --- a/contrib/libedit/readline.c +++ b/contrib/libedit/readline.c @@ -1,2521 +1,2617 @@ -/* $NetBSD: readline.c,v 1.168 2021/09/10 18:51:36 rillig Exp $ */ +/* $NetBSD: readline.c,v 1.174 2022/04/08 20:11:31 christos Exp $ */ /*- * Copyright (c) 1997 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Jaromir Dolecek. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #if !defined(lint) && !defined(SCCSID) -__RCSID("$NetBSD: readline.c,v 1.168 2021/09/10 18:51:36 rillig Exp $"); +__RCSID("$NetBSD: readline.c,v 1.174 2022/04/08 20:11:31 christos Exp $"); #endif /* not lint && not SCCSID */ #include #include #include #include #include #include #include #include #include +#include #include #include #include #include #include #include #include "readline/readline.h" #include "el.h" #include "fcns.h" #include "filecomplete.h" void rl_prep_terminal(int); void rl_deprep_terminal(void); /* for rl_complete() */ #define TAB '\r' /* see comment at the #ifdef for sense of this */ /* #define GDB_411_HACK */ /* readline compatibility stuff - look at readline sources/documentation */ /* to see what these variables mean */ const char *rl_library_version = "EditLine wrapper"; int rl_readline_version = RL_READLINE_VERSION; static char empty[] = { '\0' }; static char expand_chars[] = { ' ', '\t', '\n', '=', '(', '\0' }; static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$', '>', '<', '=', ';', '|', '&', '{', '(', '\0' }; const char *rl_readline_name = empty; FILE *rl_instream = NULL; FILE *rl_outstream = NULL; int rl_point = 0; int rl_end = 0; char *rl_line_buffer = NULL; rl_vcpfunc_t *rl_linefunc = NULL; int rl_done = 0; rl_hook_func_t *rl_event_hook = NULL; KEYMAP_ENTRY_ARRAY emacs_standard_keymap, emacs_meta_keymap, emacs_ctlx_keymap; /* * The following is not implemented; we always catch signals in the * libedit fashion: set handlers on entry to el_gets() and clear them * on the way out. This simplistic approach works for most cases; if * it does not work for your application, please let us know. */ int rl_catch_signals = 1; int rl_catch_sigwinch = 1; int history_base = 1; /* probably never subject to change */ int history_length = 0; int history_offset = 0; int max_input_history = 0; char history_expansion_char = '!'; char history_subst_char = '^'; char *history_no_expand_chars = expand_chars; Function *history_inhibit_expansion_function = NULL; char *history_arg_extract(int start, int end, const char *str); int rl_inhibit_completion = 0; int rl_attempted_completion_over = 0; const char *rl_basic_word_break_characters = break_chars; char *rl_completer_word_break_characters = NULL; const char *rl_completer_quote_characters = NULL; const char *rl_basic_quote_characters = "\"'"; rl_compentry_func_t *rl_completion_entry_function = NULL; char *(*rl_completion_word_break_hook)(void) = NULL; rl_completion_func_t *rl_attempted_completion_function = NULL; -Function *rl_pre_input_hook = NULL; -Function *rl_startup1_hook = NULL; +rl_hook_func_t *rl_pre_input_hook = NULL; +rl_hook_func_t *rl_startup1_hook = NULL; int (*rl_getc_function)(FILE *) = NULL; char *rl_terminal_name = NULL; int rl_already_prompted = 0; int rl_filename_completion_desired = 0; int rl_ignore_completion_duplicates = 0; int readline_echoing_p = 1; int _rl_print_completions_horizontally = 0; VFunction *rl_redisplay_function = NULL; -Function *rl_startup_hook = NULL; +rl_hook_func_t *rl_startup_hook = NULL; VFunction *rl_completion_display_matches_hook = NULL; VFunction *rl_prep_term_function = (VFunction *)rl_prep_terminal; VFunction *rl_deprep_term_function = (VFunction *)rl_deprep_terminal; KEYMAP_ENTRY_ARRAY emacs_meta_keymap; -unsigned long rl_readline_state; +unsigned long rl_readline_state = RL_STATE_NONE; int _rl_complete_mark_directories; rl_icppfunc_t *rl_directory_completion_hook; int rl_completion_suppress_append; int rl_sort_completion_matches; int _rl_completion_prefix_display_length; int _rl_echoing_p; int history_max_entries; char *rl_display_prompt; +int rl_erase_empty_line; /* * The current prompt string. */ char *rl_prompt = NULL; +char *rl_prompt_saved = NULL; /* * This is set to character indicating type of completion being done by * rl_complete_internal(); this is available for application completion * functions. */ int rl_completion_type = 0; /* * If more than this number of items results from query for possible * completions, we ask user if they are sure to really display the list. */ int rl_completion_query_items = 100; /* * List of characters which are word break characters, but should be left * in the parsed text when it is passed to the completion function. * Shell uses this to help determine what kind of completing to do. */ const char *rl_special_prefixes = NULL; /* * This is the character appended to the completed words if at the end of * the line. Default is ' ' (a space). */ int rl_completion_append_character = ' '; /* stuff below is used internally by libedit for readline emulation */ static History *h = NULL; static EditLine *e = NULL; static rl_command_func_t *map[256]; static jmp_buf topbuf; /* internal functions */ static unsigned char _el_rl_complete(EditLine *, int); static unsigned char _el_rl_tstp(EditLine *, int); static char *_get_prompt(EditLine *); static int _getc_function(EditLine *, wchar_t *); static int _history_expand_command(const char *, size_t, size_t, char **); static char *_rl_compat_sub(const char *, const char *, const char *, int); static int _rl_event_read_char(EditLine *, wchar_t *); static void _rl_update_pos(void); static HIST_ENTRY rl_he; /* ARGSUSED */ static char * _get_prompt(EditLine *el __attribute__((__unused__))) { rl_already_prompted = 1; return rl_prompt; } /* * read one key from user defined input function */ static int /*ARGSUSED*/ _getc_function(EditLine *el __attribute__((__unused__)), wchar_t *c) { int i; i = (*rl_getc_function)(rl_instream); if (i == -1) return 0; *c = (wchar_t)i; return 1; } static void _resize_fun(EditLine *el, void *a) { const LineInfo *li; const char **ap = a; li = el_line(el); *ap = li->buffer; } static const char * _default_history_file(void) { struct passwd *p; static char *path; size_t len; if (path) return path; if ((p = getpwuid(getuid())) == NULL) return NULL; len = strlen(p->pw_dir) + sizeof("/.history"); if ((path = malloc(len)) == NULL) return NULL; (void)snprintf(path, len, "%s/.history", p->pw_dir); return path; } /* * READLINE compatibility stuff */ /* * Set the prompt */ int rl_set_prompt(const char *prompt) { char *p; if (!prompt) prompt = ""; if (rl_prompt != NULL && strcmp(rl_prompt, prompt) == 0) return 0; if (rl_prompt) el_free(rl_prompt); rl_prompt = strdup(prompt); if (rl_prompt == NULL) return -1; while ((p = strchr(rl_prompt, RL_PROMPT_END_IGNORE)) != NULL) { /* Remove adjacent end/start markers to avoid double-escapes. */ if (p[1] == RL_PROMPT_START_IGNORE) { memmove(p, p + 2, 1 + strlen(p + 2)); } else { *p = RL_PROMPT_START_IGNORE; } } return 0; } +void +rl_save_prompt(void) +{ + rl_prompt_saved = strdup(rl_prompt); +} + +void +rl_restore_prompt(void) +{ + if (!rl_prompt_saved) + return; + rl_prompt = rl_prompt_saved; + rl_prompt_saved = NULL; +} + /* * initialize rl compat stuff */ int rl_initialize(void) { HistEvent ev; int editmode = 1; struct termios t; if (e != NULL) el_end(e); if (h != NULL) history_end(h); + RL_UNSETSTATE(RL_STATE_DONE); + if (!rl_instream) rl_instream = stdin; if (!rl_outstream) rl_outstream = stdout; /* * See if we don't really want to run the editor */ if (tcgetattr(fileno(rl_instream), &t) != -1 && (t.c_lflag & ECHO) == 0) editmode = 0; e = el_init_internal(rl_readline_name, rl_instream, rl_outstream, stderr, fileno(rl_instream), fileno(rl_outstream), fileno(stderr), NO_RESET); if (!editmode) el_set(e, EL_EDITMODE, 0); h = history_init(); if (!e || !h) return -1; history(h, &ev, H_SETSIZE, INT_MAX); /* unlimited */ history_length = 0; max_input_history = INT_MAX; el_set(e, EL_HIST, history, h); /* Setup resize function */ el_set(e, EL_RESIZE, _resize_fun, &rl_line_buffer); /* setup getc function if valid */ if (rl_getc_function) el_set(e, EL_GETCFN, _getc_function); /* for proper prompt printing in readline() */ if (rl_set_prompt("") == -1) { history_end(h); el_end(e); return -1; } el_set(e, EL_PROMPT_ESC, _get_prompt, RL_PROMPT_START_IGNORE); el_set(e, EL_SIGNAL, rl_catch_signals); /* set default mode to "emacs"-style and read setting afterwards */ /* so this can be overridden */ el_set(e, EL_EDITOR, "emacs"); if (rl_terminal_name != NULL) el_set(e, EL_TERMINAL, rl_terminal_name); else el_get(e, EL_TERMINAL, &rl_terminal_name); /* * Word completion - this has to go AFTER rebinding keys * to emacs-style. */ el_set(e, EL_ADDFN, "rl_complete", "ReadLine compatible completion function", _el_rl_complete); el_set(e, EL_BIND, "^I", "rl_complete", NULL); /* * Send TSTP when ^Z is pressed. */ el_set(e, EL_ADDFN, "rl_tstp", "ReadLine compatible suspend function", _el_rl_tstp); el_set(e, EL_BIND, "^Z", "rl_tstp", NULL); /* * Set some readline compatible key-bindings. */ el_set(e, EL_BIND, "^R", "em-inc-search-prev", NULL); /* * Allow the use of Home/End keys. */ el_set(e, EL_BIND, "\\e[1~", "ed-move-to-beg", NULL); el_set(e, EL_BIND, "\\e[4~", "ed-move-to-end", NULL); el_set(e, EL_BIND, "\\e[7~", "ed-move-to-beg", NULL); el_set(e, EL_BIND, "\\e[8~", "ed-move-to-end", NULL); el_set(e, EL_BIND, "\\e[H", "ed-move-to-beg", NULL); el_set(e, EL_BIND, "\\e[F", "ed-move-to-end", NULL); /* * Allow the use of the Delete/Insert keys. */ el_set(e, EL_BIND, "\\e[3~", "ed-delete-next-char", NULL); el_set(e, EL_BIND, "\\e[2~", "ed-quoted-insert", NULL); /* * Ctrl-left-arrow and Ctrl-right-arrow for word moving. */ el_set(e, EL_BIND, "\\e[1;5C", "em-next-word", NULL); el_set(e, EL_BIND, "\\e[1;5D", "ed-prev-word", NULL); el_set(e, EL_BIND, "\\e[5C", "em-next-word", NULL); el_set(e, EL_BIND, "\\e[5D", "ed-prev-word", NULL); el_set(e, EL_BIND, "\\e\\e[C", "em-next-word", NULL); el_set(e, EL_BIND, "\\e\\e[D", "ed-prev-word", NULL); /* read settings from configuration file */ el_source(e, NULL); /* * Unfortunately, some applications really do use rl_point * and rl_line_buffer directly. */ _resize_fun(e, &rl_line_buffer); _rl_update_pos(); tty_end(e, TCSADRAIN); return 0; } /* * read one line from input stream and return it, chomping * trailing newline (if there is any) */ char * readline(const char *p) { HistEvent ev; const char * volatile prompt = p; int count; const char *ret; char *buf; static int used_event_hook; if (e == NULL || h == NULL) rl_initialize(); if (rl_startup_hook) { - (*rl_startup_hook)(NULL, 0); + (*rl_startup_hook)(); } tty_init(e); rl_done = 0; (void)setjmp(topbuf); buf = NULL; /* update prompt accordingly to what has been passed */ if (rl_set_prompt(prompt) == -1) goto out; if (rl_pre_input_hook) - (*rl_pre_input_hook)(NULL, 0); + (*rl_pre_input_hook)(); if (rl_event_hook && !(e->el_flags & NO_TTY)) { el_set(e, EL_GETCFN, _rl_event_read_char); used_event_hook = 1; } if (!rl_event_hook && used_event_hook) { el_set(e, EL_GETCFN, EL_BUILTIN_GETCFN); used_event_hook = 0; } rl_already_prompted = 0; /* get one line from input stream */ ret = el_gets(e, &count); if (ret && count > 0) { buf = strdup(ret); if (buf == NULL) goto out; buf[strcspn(buf, "\n")] = '\0'; } else buf = NULL; history(h, &ev, H_GETSIZE); history_length = ev.num; out: tty_end(e, TCSADRAIN); return buf; } /* * history functions */ /* * is normally called before application starts to use * history expansion functions */ void using_history(void) { if (h == NULL || e == NULL) rl_initialize(); history_offset = history_length; } /* * substitute ``what'' with ``with'', returning resulting string; if * globally == 1, substitutes all occurrences of what, otherwise only the * first one */ static char * _rl_compat_sub(const char *str, const char *what, const char *with, int globally) { const char *s; char *r, *result; size_t len, with_len, what_len; len = strlen(str); with_len = strlen(with); what_len = strlen(what); /* calculate length we need for result */ s = str; while (*s) { if (*s == *what && !strncmp(s, what, what_len)) { len += with_len - what_len; if (!globally) break; s += what_len; } else s++; } r = result = el_calloc(len + 1, sizeof(*r)); if (result == NULL) return NULL; s = str; while (*s) { if (*s == *what && !strncmp(s, what, what_len)) { memcpy(r, with, with_len); r += with_len; s += what_len; if (!globally) { (void)strcpy(r, s); return result; } } else *r++ = *s++; } *r = '\0'; return result; } static char *last_search_pat; /* last !?pat[?] search pattern */ static char *last_search_match; /* last !?pat[?] that matched */ const char * get_history_event(const char *cmd, int *cindex, int qchar) { int idx, sign, sub, num, begin, ret; size_t len; char *pat; const char *rptr; HistEvent ev; idx = *cindex; if (cmd[idx++] != history_expansion_char) return NULL; /* find out which event to take */ if (cmd[idx] == history_expansion_char || cmd[idx] == '\0') { if (history(h, &ev, H_FIRST) != 0) return NULL; *cindex = cmd[idx]? (idx + 1):idx; return ev.str; } sign = 0; if (cmd[idx] == '-') { sign = 1; idx++; } if ('0' <= cmd[idx] && cmd[idx] <= '9') { HIST_ENTRY *he; num = 0; while (cmd[idx] && '0' <= cmd[idx] && cmd[idx] <= '9') { num = num * 10 + cmd[idx] - '0'; idx++; } if (sign) num = history_length - num + history_base; if (!(he = history_get(num))) return NULL; *cindex = idx; return he->line; } sub = 0; if (cmd[idx] == '?') { sub = 1; idx++; } begin = idx; while (cmd[idx]) { if (cmd[idx] == '\n') break; if (sub && cmd[idx] == '?') break; if (!sub && (cmd[idx] == ':' || cmd[idx] == ' ' || cmd[idx] == '\t' || cmd[idx] == qchar)) break; idx++; } len = (size_t)idx - (size_t)begin; if (sub && cmd[idx] == '?') idx++; if (sub && len == 0 && last_search_pat && *last_search_pat) pat = last_search_pat; else if (len == 0) return NULL; else { if ((pat = el_calloc(len + 1, sizeof(*pat))) == NULL) return NULL; (void)strlcpy(pat, cmd + begin, len + 1); } if (history(h, &ev, H_CURR) != 0) { if (pat != last_search_pat) el_free(pat); return NULL; } num = ev.num; if (sub) { if (pat != last_search_pat) { el_free(last_search_pat); last_search_pat = pat; } ret = history_search(pat, -1); } else ret = history_search_prefix(pat, -1); if (ret == -1) { /* restore to end of list on failed search */ history(h, &ev, H_FIRST); (void)fprintf(rl_outstream, "%s: Event not found\n", pat); if (pat != last_search_pat) el_free(pat); return NULL; } if (sub && len) { el_free(last_search_match); last_search_match = strdup(pat); } if (pat != last_search_pat) el_free(pat); if (history(h, &ev, H_CURR) != 0) return NULL; *cindex = idx; rptr = ev.str; /* roll back to original position */ (void)history(h, &ev, H_SET, num); return rptr; } static int getfrom(const char **cmdp, char **fromp, const char *search, int delim) { size_t size = 16; size_t len = 0; const char *cmd = *cmdp; char *what = el_realloc(*fromp, size * sizeof(*what)); if (what == NULL){ el_free(*fromp); *fromp = NULL; return 0; } for (; *cmd && *cmd != delim; cmd++) { if (*cmd == '\\' && cmd[1] == delim) cmd++; if (len - 1 >= size) { char *nwhat; nwhat = el_realloc(what, (size <<= 1) * sizeof(*nwhat)); if (nwhat == NULL) { el_free(what); el_free(*fromp); *cmdp = cmd; *fromp = NULL; return 0; } what = nwhat; } what[len++] = *cmd; } what[len] = '\0'; *fromp = what; *cmdp = cmd; if (*what == '\0') { el_free(what); if (search) { *fromp = strdup(search); if (*fromp == NULL) { return 0; } } else { *fromp = NULL; return -1; } } if (!*cmd) { el_free(what); *fromp = NULL; return -1; } cmd++; /* shift after delim */ *cmdp = cmd; if (!*cmd) { el_free(what); *fromp = NULL; return -1; } return 1; } static int getto(const char **cmdp, char **top, const char *from, int delim) { size_t size = 16; size_t len = 0; size_t from_len = strlen(from); const char *cmd = *cmdp; char *with = el_realloc(*top, size * sizeof(*with)); *top = NULL; if (with == NULL) goto out; for (; *cmd && *cmd != delim; cmd++) { if (len + from_len + 1 >= size) { char *nwith; size += from_len + 1; nwith = el_realloc(with, size * sizeof(*nwith)); if (nwith == NULL) goto out; with = nwith; } if (*cmd == '&') { /* safe */ strcpy(&with[len], from); len += from_len; continue; } if (*cmd == '\\' && (*(cmd + 1) == delim || *(cmd + 1) == '&')) cmd++; with[len++] = *cmd; } if (!*cmd) goto out; with[len] = '\0'; *top = with; *cmdp = cmd; return 1; out: el_free(with); el_free(*top); *top = NULL; *cmdp = cmd; return -1; } static void replace(char **tmp, int c) { char *aptr; if ((aptr = strrchr(*tmp, c)) == NULL) return; aptr = strdup(aptr + 1); // XXX: check el_free(*tmp); *tmp = aptr; } /* * the real function doing history expansion - takes as argument command * to do and data upon which the command should be executed * does expansion the way I've understood readline documentation * * returns 0 if data was not modified, 1 if it was and 2 if the string * should be only printed and not executed; in case of error, * returns -1 and *result points to NULL * it's the caller's responsibility to free() the string returned in *result */ static int _history_expand_command(const char *command, size_t offs, size_t cmdlen, char **result) { char *tmp, *search = NULL, *aptr, delim; const char *ptr, *cmd; static char *from = NULL, *to = NULL; int start, end, idx, has_mods = 0; int p_on = 0, g_on = 0, ev; *result = NULL; aptr = NULL; ptr = NULL; /* First get event specifier */ idx = 0; if (strchr(":^*$", command[offs + 1])) { char str[4]; /* * "!:" is shorthand for "!!:". * "!^", "!*" and "!$" are shorthand for * "!!:^", "!!:*" and "!!:$" respectively. */ str[0] = str[1] = '!'; str[2] = '0'; ptr = get_history_event(str, &idx, 0); idx = (command[offs + 1] == ':')? 1:0; has_mods = 1; } else { if (command[offs + 1] == '#') { /* use command so far */ if ((aptr = el_calloc(offs + 1, sizeof(*aptr))) == NULL) return -1; (void)strlcpy(aptr, command, offs + 1); idx = 1; } else { int qchar; qchar = (offs > 0 && command[offs - 1] == '"') ? '"' : '\0'; ptr = get_history_event(command + offs, &idx, qchar); } has_mods = command[offs + (size_t)idx] == ':'; } if (ptr == NULL && aptr == NULL) return -1; if (!has_mods) { *result = strdup(aptr ? aptr : ptr); if (aptr) el_free(aptr); if (*result == NULL) return -1; return 1; } cmd = command + offs + idx + 1; /* Now parse any word designators */ if (*cmd == '%') /* last word matched by ?pat? */ tmp = strdup(last_search_match ? last_search_match : ""); else if (strchr("^*$-0123456789", *cmd)) { start = end = -1; if (*cmd == '^') start = end = 1, cmd++; else if (*cmd == '$') start = -1, cmd++; else if (*cmd == '*') start = 1, cmd++; else if (*cmd == '-' || isdigit((unsigned char) *cmd)) { start = 0; while (*cmd && '0' <= *cmd && *cmd <= '9') start = start * 10 + *cmd++ - '0'; if (*cmd == '-') { if (isdigit((unsigned char) cmd[1])) { cmd++; end = 0; while (*cmd && '0' <= *cmd && *cmd <= '9') end = end * 10 + *cmd++ - '0'; } else if (cmd[1] == '$') { cmd += 2; end = -1; } else { cmd++; end = -2; } } else if (*cmd == '*') end = -1, cmd++; else end = start; } tmp = history_arg_extract(start, end, aptr? aptr:ptr); if (tmp == NULL) { (void)fprintf(rl_outstream, "%s: Bad word specifier", command + offs + idx); if (aptr) el_free(aptr); return -1; } } else tmp = strdup(aptr? aptr:ptr); if (aptr) el_free(aptr); if (*cmd == '\0' || ((size_t)(cmd - (command + offs)) >= cmdlen)) { *result = tmp; return 1; } for (; *cmd; cmd++) { switch (*cmd) { case ':': continue; case 'h': /* remove trailing path */ if ((aptr = strrchr(tmp, '/')) != NULL) *aptr = '\0'; continue; case 't': /* remove leading path */ replace(&tmp, '/'); continue; case 'r': /* remove trailing suffix */ if ((aptr = strrchr(tmp, '.')) != NULL) *aptr = '\0'; continue; case 'e': /* remove all but suffix */ replace(&tmp, '.'); continue; case 'p': /* print only */ p_on = 1; continue; case 'g': g_on = 2; continue; case '&': if (from == NULL || to == NULL) continue; /*FALLTHROUGH*/ case 's': ev = -1; delim = *++cmd; if (delim == '\0' || *++cmd == '\0') goto out; if ((ev = getfrom(&cmd, &from, search, delim)) != 1) goto out; if ((ev = getto(&cmd, &to, from, delim)) != 1) goto out; aptr = _rl_compat_sub(tmp, from, to, g_on); if (aptr) { el_free(tmp); tmp = aptr; } g_on = 0; cmd--; continue; } } *result = tmp; return p_on ? 2 : 1; out: el_free(tmp); return ev; } /* * csh-style history expansion */ int history_expand(char *str, char **output) { int ret = 0; size_t idx, i, size; char *tmp, *result; if (h == NULL || e == NULL) rl_initialize(); if (history_expansion_char == 0) { *output = strdup(str); return 0; } *output = NULL; if (str[0] == history_subst_char) { /* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */ *output = el_calloc(strlen(str) + 4 + 1, sizeof(**output)); if (*output == NULL) return 0; (*output)[0] = (*output)[1] = history_expansion_char; (*output)[2] = ':'; (*output)[3] = 's'; (void)strcpy((*output) + 4, str); str = *output; } else { *output = strdup(str); if (*output == NULL) return 0; } #define ADD_STRING(what, len, fr) \ { \ if (idx + len + 1 > size) { \ char *nresult = el_realloc(result, \ (size += len + 1) * sizeof(*nresult)); \ if (nresult == NULL) { \ el_free(*output); \ el_free(fr); \ return 0; \ } \ result = nresult; \ } \ (void)strlcpy(&result[idx], what, len + 1); \ idx += len; \ } result = NULL; size = idx = 0; tmp = NULL; for (i = 0; str[i];) { int qchar, loop_again; size_t len, start, j; qchar = 0; loop_again = 1; start = j = i; loop: for (; str[j]; j++) { if (str[j] == '\\' && str[j + 1] == history_expansion_char) { len = strlen(&str[j + 1]) + 1; memmove(&str[j], &str[j + 1], len); continue; } if (!loop_again) { if (isspace((unsigned char) str[j]) || str[j] == qchar) break; } if (str[j] == history_expansion_char && !strchr(history_no_expand_chars, str[j + 1]) && (!history_inhibit_expansion_function || (*history_inhibit_expansion_function)(str, (int)j) == 0)) break; } if (str[j] && loop_again) { i = j; qchar = (j > 0 && str[j - 1] == '"' )? '"':0; j++; if (str[j] == history_expansion_char) j++; loop_again = 0; goto loop; } len = i - start; ADD_STRING(&str[start], len, NULL); if (str[i] == '\0' || str[i] != history_expansion_char) { len = j - i; ADD_STRING(&str[i], len, NULL); if (start == 0) ret = 0; else ret = 1; break; } ret = _history_expand_command (str, i, (j - i), &tmp); if (ret > 0 && tmp) { len = strlen(tmp); ADD_STRING(tmp, len, tmp); } if (tmp) { el_free(tmp); tmp = NULL; } i = j; } /* ret is 2 for "print only" option */ if (ret == 2) { add_history(result); #ifdef GDB_411_HACK /* gdb 4.11 has been shipped with readline, where */ /* history_expand() returned -1 when the line */ /* should not be executed; in readline 2.1+ */ /* it should return 2 in such a case */ ret = -1; #endif } el_free(*output); *output = result; return ret; } /* * Return a string consisting of arguments of "str" from "start" to "end". */ char * history_arg_extract(int start, int end, const char *str) { size_t i, len, max; char **arr, *result = NULL; arr = history_tokenize(str); if (!arr) return NULL; if (arr && *arr == NULL) goto out; for (max = 0; arr[max]; max++) continue; max--; if (start == '$') start = (int)max; if (end == '$') end = (int)max; if (end < 0) end = (int)max + end + 1; if (start < 0) start = end; if (start < 0 || end < 0 || (size_t)start > max || (size_t)end > max || start > end) goto out; for (i = (size_t)start, len = 0; i <= (size_t)end; i++) len += strlen(arr[i]) + 1; len++; result = el_calloc(len, sizeof(*result)); if (result == NULL) goto out; for (i = (size_t)start, len = 0; i <= (size_t)end; i++) { (void)strcpy(result + len, arr[i]); len += strlen(arr[i]); if (i < (size_t)end) result[len++] = ' '; } result[len] = '\0'; out: for (i = 0; arr[i]; i++) el_free(arr[i]); el_free(arr); return result; } /* * Parse the string into individual tokens, * similar to how shell would do it. */ char ** history_tokenize(const char *str) { int size = 1, idx = 0, i, start; size_t len; char **result = NULL, *temp, delim = '\0'; for (i = 0; str[i];) { while (isspace((unsigned char) str[i])) i++; start = i; for (; str[i];) { if (str[i] == '\\') { if (str[i+1] != '\0') i++; } else if (str[i] == delim) delim = '\0'; else if (!delim && (isspace((unsigned char) str[i]) || strchr("()<>;&|$", str[i]))) break; else if (!delim && strchr("'`\"", str[i])) delim = str[i]; if (str[i]) i++; } if (idx + 2 >= size) { char **nresult; size <<= 1; nresult = el_realloc(result, (size_t)size * sizeof(*nresult)); if (nresult == NULL) { el_free(result); return NULL; } result = nresult; } len = (size_t)i - (size_t)start; temp = el_calloc(len + 1, sizeof(*temp)); if (temp == NULL) { for (i = 0; i < idx; i++) el_free(result[i]); el_free(result); return NULL; } (void)strlcpy(temp, &str[start], len + 1); result[idx++] = temp; result[idx] = NULL; if (str[i]) i++; } return result; } /* * limit size of history record to ``max'' events */ void stifle_history(int max) { HistEvent ev; HIST_ENTRY *he; if (h == NULL || e == NULL) rl_initialize(); if (history(h, &ev, H_SETSIZE, max) == 0) { max_input_history = max; if (history_length > max) history_base = history_length - max; while (history_length > max) { he = remove_history(0); el_free(he->data); el_free((void *)(unsigned long)he->line); el_free(he); } } } /* * "unlimit" size of history - set the limit to maximum allowed int value */ int unstifle_history(void) { HistEvent ev; int omax; history(h, &ev, H_SETSIZE, INT_MAX); omax = max_input_history; max_input_history = INT_MAX; return omax; /* some value _must_ be returned */ } int history_is_stifled(void) { /* cannot return true answer */ return max_input_history != INT_MAX; } static const char _history_tmp_template[] = "/tmp/.historyXXXXXX"; int history_truncate_file (const char *filename, int nlines) { int ret = 0; FILE *fp, *tp; char template[sizeof(_history_tmp_template)]; char buf[4096]; int fd; char *cp; off_t off; int count = 0; ssize_t left = 0; if (filename == NULL && (filename = _default_history_file()) == NULL) return errno; if ((fp = fopen(filename, "r+")) == NULL) return errno; strcpy(template, _history_tmp_template); if ((fd = mkstemp(template)) == -1) { ret = errno; goto out1; } if ((tp = fdopen(fd, "r+")) == NULL) { close(fd); ret = errno; goto out2; } for(;;) { if (fread(buf, sizeof(buf), (size_t)1, fp) != 1) { if (ferror(fp)) { ret = errno; break; } if (fseeko(fp, (off_t)sizeof(buf) * count, SEEK_SET) == (off_t)-1) { ret = errno; break; } left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), fp); if (ferror(fp)) { ret = errno; break; } if (left == 0) { count--; left = sizeof(buf); } else if (fwrite(buf, (size_t)left, (size_t)1, tp) != 1) { ret = errno; break; } fflush(tp); break; } if (fwrite(buf, sizeof(buf), (size_t)1, tp) != 1) { ret = errno; break; } count++; } if (ret) goto out3; cp = buf + left - 1; if(*cp != '\n') cp++; for(;;) { while (--cp >= buf) { if (*cp == '\n') { if (--nlines == 0) { if (++cp >= buf + sizeof(buf)) { count++; cp = buf; } break; } } } if (nlines <= 0 || count == 0) break; count--; if (fseeko(tp, (off_t)sizeof(buf) * count, SEEK_SET) < 0) { ret = errno; break; } if (fread(buf, sizeof(buf), (size_t)1, tp) != 1) { if (ferror(tp)) { ret = errno; break; } ret = EAGAIN; break; } cp = buf + sizeof(buf); } if (ret || nlines > 0) goto out3; if (fseeko(fp, (off_t)0, SEEK_SET) == (off_t)-1) { ret = errno; goto out3; } if (fseeko(tp, (off_t)sizeof(buf) * count + (cp - buf), SEEK_SET) == (off_t)-1) { ret = errno; goto out3; } for(;;) { if ((left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), tp)) == 0) { if (ferror(fp)) ret = errno; break; } if (fwrite(buf, (size_t)left, (size_t)1, fp) != 1) { ret = errno; break; } } fflush(fp); if((off = ftello(fp)) > 0) (void)ftruncate(fileno(fp), off); out3: fclose(tp); out2: unlink(template); out1: fclose(fp); return ret; } /* * read history from a file given */ int read_history(const char *filename) { HistEvent ev; if (h == NULL || e == NULL) rl_initialize(); if (filename == NULL && (filename = _default_history_file()) == NULL) return errno; errno = 0; if (history(h, &ev, H_LOAD, filename) == -1) return errno ? errno : EINVAL; if (history(h, &ev, H_GETSIZE) == 0) history_length = ev.num; if (history_length < 0) return EINVAL; return 0; } /* * write history to a file given */ int write_history(const char *filename) { HistEvent ev; if (h == NULL || e == NULL) rl_initialize(); if (filename == NULL && (filename = _default_history_file()) == NULL) return errno; return history(h, &ev, H_SAVE, filename) == -1 ? (errno ? errno : EINVAL) : 0; } int append_history(int n, const char *filename) { HistEvent ev; FILE *fp; if (h == NULL || e == NULL) rl_initialize(); if (filename == NULL && (filename = _default_history_file()) == NULL) return errno; if ((fp = fopen(filename, "a")) == NULL) return errno; if (history(h, &ev, H_NSAVE_FP, (size_t)n, fp) == -1) { int serrno = errno ? errno : EINVAL; fclose(fp); return serrno; } fclose(fp); return 0; } /* * returns history ``num''th event * * returned pointer points to static variable */ HIST_ENTRY * history_get(int num) { static HIST_ENTRY she; HistEvent ev; int curr_num; if (h == NULL || e == NULL) rl_initialize(); if (num < history_base) return NULL; /* save current position */ if (history(h, &ev, H_CURR) != 0) return NULL; curr_num = ev.num; /* * use H_DELDATA to set to nth history (without delete) by passing * (void **)-1 -- as in history_set_pos */ if (history(h, &ev, H_DELDATA, num - history_base, (void **)-1) != 0) goto out; /* get current entry */ if (history(h, &ev, H_CURR) != 0) goto out; if (history(h, &ev, H_NEXT_EVDATA, ev.num, &she.data) != 0) goto out; she.line = ev.str; /* restore pointer to where it was */ (void)history(h, &ev, H_SET, curr_num); return &she; out: /* restore pointer to where it was */ (void)history(h, &ev, H_SET, curr_num); return NULL; } /* * add the line to history table */ int add_history(const char *line) { HistEvent ev; if (h == NULL || e == NULL) rl_initialize(); if (history(h, &ev, H_ENTER, line) == -1) return 0; (void)history(h, &ev, H_GETSIZE); if (ev.num == history_length) history_base++; else { history_offset++; history_length = ev.num; } return 0; } /* * remove the specified entry from the history list and return it. */ HIST_ENTRY * remove_history(int num) { HIST_ENTRY *he; HistEvent ev; if (h == NULL || e == NULL) rl_initialize(); if ((he = el_malloc(sizeof(*he))) == NULL) return NULL; if (history(h, &ev, H_DELDATA, num, &he->data) != 0) { el_free(he); return NULL; } he->line = ev.str; if (history(h, &ev, H_GETSIZE) == 0) history_length = ev.num; return he; } /* * replace the line and data of the num-th entry */ HIST_ENTRY * replace_history_entry(int num, const char *line, histdata_t data) { HIST_ENTRY *he; HistEvent ev; int curr_num; if (h == NULL || e == NULL) rl_initialize(); /* save current position */ if (history(h, &ev, H_CURR) != 0) return NULL; curr_num = ev.num; /* start from the oldest */ if (history(h, &ev, H_LAST) != 0) return NULL; /* error */ if ((he = el_malloc(sizeof(*he))) == NULL) return NULL; /* look forwards for event matching specified offset */ if (history(h, &ev, H_NEXT_EVDATA, num, &he->data)) goto out; he->line = strdup(ev.str); if (he->line == NULL) goto out; if (history(h, &ev, H_REPLACE, line, data)) goto out; /* restore pointer to where it was */ if (history(h, &ev, H_SET, curr_num)) goto out; return he; out: el_free(he); return NULL; } /* * clear the history list - delete all entries */ void clear_history(void) { HistEvent ev; if (h == NULL || e == NULL) rl_initialize(); (void)history(h, &ev, H_CLEAR); history_offset = history_length = 0; } /* * returns offset of the current history event */ int where_history(void) { return history_offset; } static HIST_ENTRY **_history_listp; static HIST_ENTRY *_history_list; HIST_ENTRY ** history_list(void) { HistEvent ev; HIST_ENTRY **nlp, *nl; int i; if (history(h, &ev, H_LAST) != 0) return NULL; if ((nlp = el_realloc(_history_listp, ((size_t)history_length + 1) * sizeof(*nlp))) == NULL) return NULL; _history_listp = nlp; if ((nl = el_realloc(_history_list, (size_t)history_length * sizeof(*nl))) == NULL) return NULL; _history_list = nl; i = 0; do { _history_listp[i] = &_history_list[i]; _history_list[i].line = ev.str; _history_list[i].data = NULL; if (i++ == history_length) abort(); } while (history(h, &ev, H_PREV) == 0); _history_listp[i] = NULL; return _history_listp; } /* * returns current history event or NULL if there is no such event */ HIST_ENTRY * current_history(void) { HistEvent ev; if (history(h, &ev, H_PREV_EVENT, history_offset + 1) != 0) return NULL; rl_he.line = ev.str; rl_he.data = NULL; return &rl_he; } /* * returns total number of bytes history events' data are using */ int history_total_bytes(void) { HistEvent ev; int curr_num; size_t size; if (history(h, &ev, H_CURR) != 0) return -1; curr_num = ev.num; (void)history(h, &ev, H_FIRST); size = 0; do size += strlen(ev.str) * sizeof(*ev.str); while (history(h, &ev, H_NEXT) == 0); /* get to the same position as before */ history(h, &ev, H_PREV_EVENT, curr_num); return (int)size; } /* * sets the position in the history list to ``pos'' */ int history_set_pos(int pos) { if (pos >= history_length || pos < 0) return 0; history_offset = pos; return 1; } /* * returns previous event in history and shifts pointer accordingly * Note that readline and editline define directions in opposite ways. */ HIST_ENTRY * previous_history(void) { HistEvent ev; if (history_offset == 0) return NULL; if (history(h, &ev, H_LAST) != 0) return NULL; history_offset--; return current_history(); } /* * returns next event in history and shifts pointer accordingly */ HIST_ENTRY * next_history(void) { HistEvent ev; if (history_offset >= history_length) return NULL; if (history(h, &ev, H_LAST) != 0) return NULL; history_offset++; return current_history(); } /* * searches for first history event containing the str */ int history_search(const char *str, int direction) { HistEvent ev; const char *strp; int curr_num; if (history(h, &ev, H_CURR) != 0) return -1; curr_num = ev.num; for (;;) { if ((strp = strstr(ev.str, str)) != NULL) return (int)(strp - ev.str); if (history(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0) break; } (void)history(h, &ev, H_SET, curr_num); return -1; } /* * searches for first history event beginning with str */ int history_search_prefix(const char *str, int direction) { HistEvent ev; return (history(h, &ev, direction < 0 ? H_PREV_STR : H_NEXT_STR, str)); } /* * search for event in history containing str, starting at offset * abs(pos); continue backward, if pos<0, forward otherwise */ /* ARGSUSED */ int history_search_pos(const char *str, int direction __attribute__((__unused__)), int pos) { HistEvent ev; int curr_num, off; off = (pos > 0) ? pos : -pos; pos = (pos > 0) ? 1 : -1; if (history(h, &ev, H_CURR) != 0) return -1; curr_num = ev.num; if (!history_set_pos(off) || history(h, &ev, H_CURR) != 0) return -1; for (;;) { if (strstr(ev.str, str)) return off; if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0) break; } /* set "current" pointer back to previous state */ (void)history(h, &ev, pos < 0 ? H_NEXT_EVENT : H_PREV_EVENT, curr_num); return -1; } /********************************/ /* completion functions */ char * tilde_expand(char *name) { return fn_tilde_expand(name); } char * filename_completion_function(const char *name, int state) { return fn_filename_completion_function(name, state); } /* * a completion generator for usernames; returns _first_ username * which starts with supplied text * text contains a partial username preceded by random character * (usually '~'); state resets search from start (??? should we do that anyway) * it's the caller's responsibility to free the returned value */ char * username_completion_function(const char *text, int state) { #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT) struct passwd pwres; char pwbuf[1024]; #endif struct passwd *pass = NULL; if (text[0] == '\0') return NULL; if (*text == '~') text++; if (state == 0) setpwent(); while ( #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT) getpwent_r(&pwres, pwbuf, sizeof(pwbuf), &pass) == 0 && pass != NULL #else (pass = getpwent()) != NULL #endif && text[0] == pass->pw_name[0] && strcmp(text, pass->pw_name) == 0) continue; if (pass == NULL) { endpwent(); return NULL; } return strdup(pass->pw_name); } /* * el-compatible wrapper to send TSTP on ^Z */ /* ARGSUSED */ static unsigned char _el_rl_tstp(EditLine *el __attribute__((__unused__)), int ch __attribute__((__unused__))) { (void)kill(0, SIGTSTP); return CC_NORM; } static const char * /*ARGSUSED*/ _rl_completion_append_character_function(const char *dummy __attribute__((__unused__))) { static char buf[2]; buf[0] = (char)rl_completion_append_character; buf[1] = '\0'; return buf; } /* * Display list of strings in columnar format on readline's output stream. * 'matches' is list of strings, 'len' is number of strings in 'matches', * 'max' is maximum length of string in 'matches'. */ void rl_display_match_list(char **matches, int len, int max) { fn_display_match_list(e, matches, (size_t)len, (size_t)max, _rl_completion_append_character_function); } /* * complete word at current point */ /* ARGSUSED */ int rl_complete(int ignore __attribute__((__unused__)), int invoking_key) { static ct_buffer_t wbreak_conv, sprefix_conv; const char *breakchars; if (h == NULL || e == NULL) rl_initialize(); if (rl_inhibit_completion) { char arr[2]; arr[0] = (char)invoking_key; arr[1] = '\0'; el_insertstr(e, arr); return CC_REFRESH; } if (rl_completion_word_break_hook != NULL) breakchars = (*rl_completion_word_break_hook)(); else breakchars = rl_basic_word_break_characters; _rl_update_pos(); /* Just look at how many global variables modify this operation! */ return fn_complete(e, (rl_compentry_func_t *)rl_completion_entry_function, rl_attempted_completion_function, ct_decode_string(rl_basic_word_break_characters, &wbreak_conv), ct_decode_string(breakchars, &sprefix_conv), _rl_completion_append_character_function, (size_t)rl_completion_query_items, &rl_completion_type, &rl_attempted_completion_over, &rl_point, &rl_end); } /* ARGSUSED */ static unsigned char _el_rl_complete(EditLine *el __attribute__((__unused__)), int ch) { return (unsigned char)rl_complete(0, ch); } /* * misc other functions */ /* * bind key c to readline-type function func */ int rl_bind_key(int c, rl_command_func_t *func) { int retval = -1; if (h == NULL || e == NULL) rl_initialize(); if (func == rl_insert) { /* XXX notice there is no range checking of ``c'' */ e->el_map.key[c] = ED_INSERT; retval = 0; } return retval; } /* * read one key from input - handles chars pushed back * to input stream also */ int rl_read_key(void) { char fooarr[2 * sizeof(int)]; if (e == NULL || h == NULL) rl_initialize(); return el_getc(e, fooarr); } /* * reset the terminal */ /* ARGSUSED */ int rl_reset_terminal(const char *p __attribute__((__unused__))) { if (h == NULL || e == NULL) rl_initialize(); el_reset(e); return 0; } /* * insert character ``c'' back into input stream, ``count'' times */ int rl_insert(int count, int c) { char arr[2]; if (h == NULL || e == NULL) rl_initialize(); /* XXX - int -> char conversion can lose on multichars */ arr[0] = (char)c; arr[1] = '\0'; for (; count > 0; count--) el_push(e, arr); return 0; } int rl_insert_text(const char *text) { if (!text || *text == 0) return 0; if (h == NULL || e == NULL) rl_initialize(); if (el_insertstr(e, text) < 0) return 0; return (int)strlen(text); } /*ARGSUSED*/ int rl_newline(int count __attribute__((__unused__)), int c __attribute__((__unused__))) { /* * Readline-4.0 appears to ignore the args. */ return rl_insert(1, '\n'); } /*ARGSUSED*/ static unsigned char rl_bind_wrapper(EditLine *el __attribute__((__unused__)), unsigned char c) { if (map[c] == NULL) return CC_ERROR; _rl_update_pos(); (*map[c])(1, c); /* If rl_done was set by the above call, deal with it here */ if (rl_done) return CC_EOF; return CC_NORM; } int rl_add_defun(const char *name, rl_command_func_t *fun, int c) { char dest[8]; if ((size_t)c >= sizeof(map) / sizeof(map[0]) || c < 0) return -1; map[(unsigned char)c] = fun; el_set(e, EL_ADDFN, name, name, rl_bind_wrapper); vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0); el_set(e, EL_BIND, dest, name, NULL); return 0; } void rl_callback_read_char(void) { int count = 0, done = 0; const char *buf = el_gets(e, &count); char *wbuf; el_set(e, EL_UNBUFFERED, 1); if (buf == NULL || count-- <= 0) return; if (count == 0 && buf[0] == e->el_tty.t_c[TS_IO][C_EOF]) done = 1; if (buf[count] == '\n' || buf[count] == '\r') done = 2; if (done && rl_linefunc != NULL) { el_set(e, EL_UNBUFFERED, 0); if (done == 2) { if ((wbuf = strdup(buf)) != NULL) wbuf[count] = '\0'; + RL_SETSTATE(RL_STATE_DONE); } else wbuf = NULL; (*(void (*)(const char *))rl_linefunc)(wbuf); } + _rl_update_pos(); } void rl_callback_handler_install(const char *prompt, rl_vcpfunc_t *linefunc) { if (e == NULL) { rl_initialize(); } (void)rl_set_prompt(prompt); rl_linefunc = linefunc; el_set(e, EL_UNBUFFERED, 1); } void rl_callback_handler_remove(void) { el_set(e, EL_UNBUFFERED, 0); rl_linefunc = NULL; } void rl_redisplay(void) { char a[2]; a[0] = (char)e->el_tty.t_c[TS_IO][C_REPRINT]; a[1] = '\0'; el_push(e, a); + rl_forced_update_display(); } int rl_get_previous_history(int count, int key) { char a[2]; a[0] = (char)key; a[1] = '\0'; while (count--) el_push(e, a); return 0; } void /*ARGSUSED*/ rl_prep_terminal(int meta_flag __attribute__((__unused__))) { el_set(e, EL_PREP_TERM, 1); } void rl_deprep_terminal(void) { el_set(e, EL_PREP_TERM, 0); } int rl_read_init_file(const char *s) { return el_source(e, s); } int rl_parse_and_bind(const char *line) { const char **argv; int argc; Tokenizer *tok; tok = tok_init(NULL); tok_str(tok, line, &argc, &argv); argc = el_parse(e, argc, argv); tok_end(tok); return argc ? 1 : 0; } int rl_variable_bind(const char *var, const char *value) { /* * The proper return value is undocument, but this is what the * readline source seems to do. */ return el_set(e, EL_BIND, "", var, value, NULL) == -1 ? 1 : 0; } int rl_stuff_char(int c) { char buf[2]; buf[0] = (char)c; buf[1] = '\0'; el_insertstr(e, buf); return 1; } static int _rl_event_read_char(EditLine *el, wchar_t *wc) { char ch; int n; ssize_t num_read = 0; ch = '\0'; *wc = L'\0'; while (rl_event_hook) { (*rl_event_hook)(); #if defined(FIONREAD) if (ioctl(el->el_infd, FIONREAD, &n) < 0) return -1; if (n) num_read = read(el->el_infd, &ch, (size_t)1); else num_read = 0; #elif defined(F_SETFL) && defined(O_NDELAY) if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0) return -1; if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0) return -1; num_read = read(el->el_infd, &ch, 1); if (fcntl(el->el_infd, F_SETFL, n)) return -1; #else /* not non-blocking, but what you gonna do? */ num_read = read(el->el_infd, &ch, 1); return -1; #endif if (num_read < 0 && errno == EAGAIN) continue; if (num_read == 0) continue; break; } if (!rl_event_hook) el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN); *wc = (wchar_t)ch; return (int)num_read; } static void _rl_update_pos(void) { const LineInfo *li = el_line(e); rl_point = (int)(li->cursor - li->buffer); rl_end = (int)(li->lastchar - li->buffer); rl_line_buffer[rl_end] = '\0'; } +char * +rl_copy_text(int from, int to) +{ + const LineInfo *li; + size_t len; + char * out; + + if (h == NULL || e == NULL) + rl_initialize(); + + li = el_line(e); + + if (from > to) + return NULL; + + if (li->buffer + from > li->lastchar) + from = (int)(li->lastchar - li->buffer); + + if (li->buffer + to > li->lastchar) + to = (int)(li->lastchar - li->buffer); + + len = (size_t)(to - from); + out = el_malloc((size_t)len + 1); + (void)strlcpy(out, li->buffer + from , len); + + return out; +} + +void +rl_replace_line(const char * text, int clear_undo __attribute__((__unused__))) +{ + if (!text || *text == 0) + return; + + if (h == NULL || e == NULL) + rl_initialize(); + + el_replacestr(e, text); +} + +int +rl_delete_text(int start, int end) +{ + + if (h == NULL || e == NULL) + rl_initialize(); + + return el_deletestr1(e, start, end); +} + void rl_get_screen_size(int *rows, int *cols) { if (rows) el_get(e, EL_GETTC, "li", rows); if (cols) el_get(e, EL_GETTC, "co", cols); } +#define MAX_MESSAGE 160 +void +rl_message(const char *format, ...) +{ + char msg[MAX_MESSAGE]; + va_list args; + + va_start(args, format); + vsnprintf(msg, sizeof(msg), format, args); + va_end(args); + + rl_set_prompt(msg); + rl_forced_update_display(); +} + void rl_set_screen_size(int rows, int cols) { char buf[64]; (void)snprintf(buf, sizeof(buf), "%d", rows); el_set(e, EL_SETTC, "li", buf, NULL); (void)snprintf(buf, sizeof(buf), "%d", cols); el_set(e, EL_SETTC, "co", buf, NULL); } char ** rl_completion_matches(const char *str, rl_compentry_func_t *fun) { size_t len, max, i, j, min; char **list, *match, *a, *b; len = 1; max = 10; if ((list = el_calloc(max, sizeof(*list))) == NULL) return NULL; while ((match = (*fun)(str, (int)(len - 1))) != NULL) { list[len++] = match; if (len == max) { char **nl; max += 10; if ((nl = el_realloc(list, max * sizeof(*nl))) == NULL) goto out; list = nl; } } if (len == 1) goto out; list[len] = NULL; if (len == 2) { if ((list[0] = strdup(list[1])) == NULL) goto out; return list; } qsort(&list[1], len - 1, sizeof(*list), (int (*)(const void *, const void *)) strcmp); min = SIZE_MAX; for (i = 1, a = list[i]; i < len - 1; i++, a = b) { b = list[i + 1]; for (j = 0; a[j] && a[j] == b[j]; j++) continue; if (min > j) min = j; } if (min == 0 && *str) { if ((list[0] = strdup(str)) == NULL) goto out; } else { if ((list[0] = el_calloc(min + 1, sizeof(*list[0]))) == NULL) goto out; (void)memcpy(list[0], list[1], min); list[0][min] = '\0'; } return list; out: el_free(list); return NULL; } char * rl_filename_completion_function (const char *text, int state) { return fn_filename_completion_function(text, state); } void rl_forced_update_display(void) { el_set(e, EL_REFRESH); } int _rl_abort_internal(void) { el_beep(e); longjmp(topbuf, 1); /*NOTREACHED*/ } int _rl_qsort_string_compare(char **s1, char **s2) { return strcoll(*s1, *s2); } HISTORY_STATE * history_get_history_state(void) { HISTORY_STATE *hs; if ((hs = el_malloc(sizeof(*hs))) == NULL) return NULL; hs->length = history_length; return hs; } int /*ARGSUSED*/ rl_kill_text(int from __attribute__((__unused__)), int to __attribute__((__unused__))) { return 0; } Keymap rl_make_bare_keymap(void) { return NULL; } Keymap rl_get_keymap(void) { return NULL; } void /*ARGSUSED*/ rl_set_keymap(Keymap k __attribute__((__unused__))) { } int /*ARGSUSED*/ rl_generic_bind(int type __attribute__((__unused__)), const char * keyseq __attribute__((__unused__)), const char * data __attribute__((__unused__)), Keymap k __attribute__((__unused__))) { return 0; } int /*ARGSUSED*/ rl_bind_key_in_map(int key __attribute__((__unused__)), rl_command_func_t *fun __attribute__((__unused__)), Keymap k __attribute__((__unused__))) { return 0; } +int +rl_set_key(const char *keyseq __attribute__((__unused__)), + rl_command_func_t *function __attribute__((__unused__)), + Keymap k __attribute__((__unused__))) +{ + return 0; +} + /* unsupported, but needed by python */ void rl_cleanup_after_signal(void) { } int rl_on_new_line(void) { return 0; } void rl_free_line_state(void) { } int /*ARGSUSED*/ rl_set_keyboard_input_timeout(int u __attribute__((__unused__))) { return 0; } void rl_resize_terminal(void) { el_resize(e); } void rl_reset_after_signal(void) { if (rl_prep_term_function) (*rl_prep_term_function)(); } void rl_echo_signal_char(int sig) { int c = tty_get_signal_character(e, sig); if (c == -1) return; re_putc(e, c, 0); } int rl_crlf(void) { re_putc(e, '\n', 0); return 0; } int rl_ding(void) { re_putc(e, '\a', 0); return 0; } int rl_abort(int count, int key) { return count && key ? 0 : 0; } int rl_set_keymap_name(const char *name, Keymap k) { return name && k ? 0 : 0; } histdata_t free_history_entry(HIST_ENTRY *he) { return he ? NULL : NULL; } void _rl_erase_entire_line(void) { } diff --git a/contrib/libedit/readline/readline.h b/contrib/libedit/readline/readline.h index e9f941aeb249..2bd0b7e80ab6 100644 --- a/contrib/libedit/readline/readline.h +++ b/contrib/libedit/readline/readline.h @@ -1,251 +1,267 @@ -/* $NetBSD: readline.h,v 1.47 2021/08/21 12:34:59 christos Exp $ */ +/* $NetBSD: readline.h,v 1.53 2022/02/19 17:45:02 christos Exp $ */ /*- * Copyright (c) 1997 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Jaromir Dolecek. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef _READLINE_H_ #define _READLINE_H_ #include #include /* list of readline stuff supported by editline library's readline wrapper */ /* typedefs */ typedef int Function(const char *, int); typedef char *CPFunction(const char *, int); typedef void VFunction(void); typedef void rl_vcpfunc_t(char *); typedef char **rl_completion_func_t(const char *, int, int); typedef char *rl_compentry_func_t(const char *, int); typedef int rl_command_func_t(int, int); typedef int rl_hook_func_t(void); typedef int rl_icppfunc_t(char **); /* only supports length */ typedef struct { int length; } HISTORY_STATE; typedef void *histdata_t; typedef struct _hist_entry { const char *line; histdata_t data; } HIST_ENTRY; typedef struct _keymap_entry { char type; #define ISFUNC 0 #define ISKMAP 1 #define ISMACR 2 Function *function; } KEYMAP_ENTRY; #define KEYMAP_SIZE 256 typedef KEYMAP_ENTRY KEYMAP_ENTRY_ARRAY[KEYMAP_SIZE]; typedef KEYMAP_ENTRY *Keymap; #define control_character_threshold 0x20 #define control_character_bit 0x40 #ifndef CTRL #include #if !defined(__sun) && !defined(__hpux) && !defined(_AIX) #include #endif #ifndef CTRL #define CTRL(c) ((c) & 037) #endif #endif #ifndef UNCTRL #define UNCTRL(c) (((c) - 'a' + 'A')|control_character_bit) #endif #define RUBOUT 0x7f #define ABORT_CHAR CTRL('G') #define RL_READLINE_VERSION 0x0402 #define RL_PROMPT_START_IGNORE '\1' #define RL_PROMPT_END_IGNORE '\2' +#define RL_STATE_NONE 0x000000 +#define RL_STATE_DONE 0x000001 + +#define RL_SETSTATE(x) (rl_readline_state |= ((unsigned long) x)) +#define RL_UNSETSTATE(x) (rl_readline_state &= ~((unsigned long) x)) +#define RL_ISSTATE(x) (rl_readline_state & ((unsigned long) x)) + /* global variables used by readline enabled applications */ #ifdef __cplusplus extern "C" { #endif extern const char *rl_library_version; extern int rl_readline_version; extern const char *rl_readline_name; extern FILE *rl_instream; extern FILE *rl_outstream; extern char *rl_line_buffer; extern int rl_point, rl_end; extern int history_base, history_length; extern int max_input_history; extern const char *rl_basic_quote_characters; extern const char *rl_basic_word_break_characters; extern char *rl_completer_word_break_characters; extern const char *rl_completer_quote_characters; extern rl_compentry_func_t *rl_completion_entry_function; extern char *(*rl_completion_word_break_hook)(void); extern rl_completion_func_t *rl_attempted_completion_function; extern int rl_attempted_completion_over; extern int rl_completion_type; extern int rl_completion_query_items; extern const char *rl_special_prefixes; extern int rl_completion_append_character; extern int rl_inhibit_completion; -extern Function *rl_pre_input_hook; -extern Function *rl_startup_hook; +extern rl_hook_func_t *rl_pre_input_hook; +extern rl_hook_func_t *rl_startup_hook; extern char *rl_terminal_name; extern int rl_already_prompted; extern char *rl_prompt; extern int rl_done; /* * The following is not implemented */ extern unsigned long rl_readline_state; extern int rl_catch_signals; extern int rl_catch_sigwinch; extern KEYMAP_ENTRY_ARRAY emacs_standard_keymap, emacs_meta_keymap, emacs_ctlx_keymap; extern int rl_filename_completion_desired; extern int rl_ignore_completion_duplicates; extern int (*rl_getc_function)(FILE *); extern VFunction *rl_redisplay_function; extern VFunction *rl_completion_display_matches_hook; extern VFunction *rl_prep_term_function; extern VFunction *rl_deprep_term_function; extern rl_hook_func_t *rl_event_hook; extern int readline_echoing_p; extern int _rl_print_completions_horizontally; extern int _rl_complete_mark_directories; extern rl_icppfunc_t *rl_directory_completion_hook; extern int rl_completion_suppress_append; extern int rl_sort_completion_matches; extern int _rl_completion_prefix_display_length; extern int _rl_echoing_p; extern int history_max_entries; extern char *rl_display_prompt; +extern int rl_erase_empty_line; /* supported functions */ char *readline(const char *); int rl_initialize(void); void using_history(void); int add_history(const char *); void clear_history(void); int append_history(int, const char *); void stifle_history(int); int unstifle_history(void); int history_is_stifled(void); int where_history(void); HIST_ENTRY *current_history(void); HIST_ENTRY *history_get(int); HIST_ENTRY *remove_history(int); HIST_ENTRY *replace_history_entry(int, const char *, histdata_t); int history_total_bytes(void); int history_set_pos(int); HIST_ENTRY *previous_history(void); HIST_ENTRY *next_history(void); HIST_ENTRY **history_list(void); int history_search(const char *, int); int history_search_prefix(const char *, int); int history_search_pos(const char *, int, int); int read_history(const char *); int write_history(const char *); -int history_truncate_file (const char *, int); +int history_truncate_file(const char *, int); int history_expand(char *, char **); char **history_tokenize(const char *); const char *get_history_event(const char *, int *, int); char *history_arg_extract(int, int, const char *); char *tilde_expand(char *); char *filename_completion_function(const char *, int); char *username_completion_function(const char *, int); int rl_complete(int, int); int rl_read_key(void); char **completion_matches(/* const */ char *, rl_compentry_func_t *); void rl_display_match_list(char **, int, int); int rl_insert(int, int); int rl_insert_text(const char *); int rl_reset_terminal(const char *); void rl_resize_terminal(void); int rl_bind_key(int, rl_command_func_t *); int rl_newline(int, int); void rl_callback_read_char(void); void rl_callback_handler_install(const char *, rl_vcpfunc_t *); void rl_callback_handler_remove(void); void rl_redisplay(void); int rl_get_previous_history(int, int); void rl_prep_terminal(int); void rl_deprep_terminal(void); int rl_read_init_file(const char *); int rl_parse_and_bind(const char *); int rl_variable_bind(const char *, const char *); int rl_stuff_char(int); int rl_add_defun(const char *, rl_command_func_t *, int); HISTORY_STATE *history_get_history_state(void); void rl_get_screen_size(int *, int *); void rl_set_screen_size(int, int); -char *rl_filename_completion_function (const char *, int); +char *rl_filename_completion_function(const char *, int); int _rl_abort_internal(void); int _rl_qsort_string_compare(char **, char **); char **rl_completion_matches(const char *, rl_compentry_func_t *); void rl_forced_update_display(void); int rl_set_prompt(const char *); int rl_on_new_line(void); void rl_reset_after_signal(void); void rl_echo_signal_char(int); int rl_crlf(void); int rl_ding(void); +char *rl_copy_text(int, int); +void rl_replace_line(const char *, int); +int rl_delete_text(int, int); +void rl_message(const char *format, ...) + __attribute__((__format__(__printf__, 1, 2))); +void rl_save_prompt(void); +void rl_restore_prompt(void); /* * The following are not implemented */ int rl_kill_text(int, int); Keymap rl_get_keymap(void); void rl_set_keymap(Keymap); Keymap rl_make_bare_keymap(void); int rl_generic_bind(int, const char *, const char *, Keymap); int rl_bind_key_in_map(int, rl_command_func_t *, Keymap); +int rl_set_key(const char *, rl_command_func_t *, Keymap); void rl_cleanup_after_signal(void); void rl_free_line_state(void); int rl_set_keyboard_input_timeout(int); int rl_abort(int, int); int rl_set_keymap_name(const char *, Keymap); histdata_t free_history_entry(HIST_ENTRY *); void _rl_erase_entire_line(void); #ifdef __cplusplus } #endif #endif /* _READLINE_H_ */