2 * *****************************************************************************
4 * SPDX-License-Identifier: BSD-2-Clause
6 * Copyright (c) 2018-2021 Gavin D. Howard and contributors.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are met:
11 * * Redistributions of source code must retain the above copyright notice, this
12 * list of conditions and the following disclaimer.
14 * * Redistributions in binary form must reproduce the above copyright notice,
15 * this list of conditions and the following disclaimer in the documentation
16 * and/or other materials provided with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
22 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 * POSSIBILITY OF SUCH DAMAGE.
30 * *****************************************************************************
32 * Adapted from the following:
34 * linenoise.c -- guerrilla line editing library against the idea that a
35 * line editing lib needs to be 20,000 lines of C code.
37 * You can find the original source code at:
38 * http://github.com/antirez/linenoise
40 * You can find the fork that this code is based on at:
41 * https://github.com/rain-1/linenoise-mob
43 * ------------------------------------------------------------------------
45 * This code is also under the following license:
47 * Copyright (c) 2010-2016, Salvatore Sanfilippo <antirez at gmail dot com>
48 * Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis at gmail dot com>
50 * Redistribution and use in source and binary forms, with or without
51 * modification, are permitted provided that the following conditions are
54 * * Redistributions of source code must retain the above copyright
55 * notice, this list of conditions and the following disclaimer.
57 * * Redistributions in binary form must reproduce the above copyright
58 * notice, this list of conditions and the following disclaimer in the
59 * documentation and/or other materials provided with the distribution.
61 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
62 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
63 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
64 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
65 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
66 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
67 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
68 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
69 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
70 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
71 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
73 * ------------------------------------------------------------------------
75 * Does a number of crazy assumptions that happen to be true in 99.9999% of
76 * the 2010 UNIX computers around.
79 * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
80 * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
83 * - Filter bogus Ctrl+<char> combinations.
87 * - History search like Ctrl+r in readline?
89 * List of escape sequences used by this program, we do everything just
90 * with three sequences. In order to be so cheap we may have some
91 * flickering effect with some slow terminal, but the lesser sequences
92 * the more compatible.
96 * Effect: if n is 0 or missing, clear from cursor to end of line
97 * Effect: if n is 1, clear from beginning of line to cursor
98 * Effect: if n is 2, clear entire line
100 * CUF (CUrsor Forward)
101 * Sequence: ESC [ n C
102 * Effect: moves cursor forward n chars
104 * CUB (CUrsor Backward)
105 * Sequence: ESC [ n D
106 * Effect: moves cursor backward n chars
108 * The following is used to get the terminal width if getting
109 * the width with the TIOCGWINSZ ioctl fails
111 * DSR (Device Status Report)
112 * Sequence: ESC [ 6 n
113 * Effect: reports the current cusor position as ESC [ n ; m R
114 * where n is the row and m is the column
116 * When multi line mode is enabled, we also use two additional escape
117 * sequences. However multi line editing is disabled by default.
120 * Sequence: ESC [ n A
121 * Effect: moves cursor up of n chars.
124 * Sequence: ESC [ n B
125 * Effect: moves cursor down of n chars.
127 * When bc_history_clearScreen() is called, two additional escape sequences
128 * are used in order to clear the screen and position the cursor at home
131 * CUP (CUrsor Position)
133 * Effect: moves the cursor to upper left corner
136 * Sequence: ESC [ 2 J
137 * Effect: clear the whole screen
139 * *****************************************************************************
141 * Code for line history.
145 #if BC_ENABLE_HISTORY
158 #include <sys/stat.h>
159 #include <sys/types.h>
160 #include <sys/ioctl.h>
161 #include <sys/select.h>
169 static void bc_history_add(BcHistory *h, char *line);
170 static void bc_history_add_empty(BcHistory *h);
173 * Check if the code is a wide character.
175 static bool bc_history_wchar(uint32_t cp) {
179 for (i = 0; i < bc_history_wchars_len; ++i) {
181 // Ranges are listed in ascending order. Therefore, once the
182 // whole range is higher than the codepoint we're testing, the
183 // codepoint won't be found in any remaining range => bail early.
184 if (bc_history_wchars[i][0] > cp) return false;
187 if (bc_history_wchars[i][0] <= cp && cp <= bc_history_wchars[i][1])
195 * Check if the code is a combining character.
197 static bool bc_history_comboChar(uint32_t cp) {
201 for (i = 0; i < bc_history_combo_chars_len; ++i) {
203 // Combining chars are listed in ascending order, so once we pass
204 // the codepoint of interest, we know it's not a combining char.
205 if (bc_history_combo_chars[i] > cp) return false;
206 if (bc_history_combo_chars[i] == cp) return true;
213 * Get length of previous UTF8 character.
215 static size_t bc_history_prevCharLen(const char *buf, size_t pos) {
217 for (pos -= 1; pos < end && (buf[pos] & 0xC0) == 0x80; --pos);
218 return end - (pos >= end ? 0 : pos);
222 * Convert UTF-8 to Unicode code point.
224 static size_t bc_history_codePoint(const char *s, size_t len, uint32_t *cp) {
228 uchar byte = (uchar) s[0];
230 if ((byte & 0x80) == 0) {
234 else if ((byte & 0xE0) == 0xC0) {
237 *cp = (((uint32_t) (s[0] & 0x1F)) << 6) |
238 ((uint32_t) (s[1] & 0x3F));
242 else if ((byte & 0xF0) == 0xE0) {
245 *cp = (((uint32_t) (s[0] & 0x0F)) << 12) |
246 (((uint32_t) (s[1] & 0x3F)) << 6) |
247 ((uint32_t) (s[2] & 0x3F));
251 else if ((byte & 0xF8) == 0xF0) {
254 *cp = (((uint32_t) (s[0] & 0x07)) << 18) |
255 (((uint32_t) (s[1] & 0x3F)) << 12) |
256 (((uint32_t) (s[2] & 0x3F)) << 6) |
257 ((uint32_t) (s[3] & 0x3F));
273 * Get length of next grapheme.
275 static size_t bc_history_nextLen(const char *buf, size_t buf_len,
276 size_t pos, size_t *col_len)
280 size_t len = bc_history_codePoint(buf + pos, buf_len - pos, &cp);
282 if (bc_history_comboChar(cp)) {
283 // Currently unreachable?
287 if (col_len != NULL) *col_len = bc_history_wchar(cp) ? 2 : 1;
291 while (pos < buf_len) {
293 len = bc_history_codePoint(buf + pos, buf_len - pos, &cp);
295 if (!bc_history_comboChar(cp)) return pos - beg;
304 * Get length of previous grapheme.
306 static size_t bc_history_prevLen(const char *buf, size_t pos, size_t *col_len) {
313 size_t len = bc_history_prevCharLen(buf, pos);
316 bc_history_codePoint(buf + pos, len, &cp);
318 if (!bc_history_comboChar(cp)) {
319 if (col_len != NULL) *col_len = 1 + (bc_history_wchar(cp) != 0);
324 // Currently unreachable?
328 static ssize_t bc_history_read(char *buf, size_t n) {
335 ret = read(STDIN_FILENO, buf, n);
336 } while (ret == EINTR);
344 * Read a Unicode code point from a file.
346 static BcStatus bc_history_readCode(char *buf, size_t buf_len,
347 uint32_t *cp, size_t *nread)
351 assert(buf_len >= 1);
353 n = bc_history_read(buf, 1);
354 if (BC_ERR(n <= 0)) goto err;
356 uchar byte = (uchar) buf[0];
358 if ((byte & 0x80) != 0) {
360 if ((byte & 0xE0) == 0xC0) {
361 assert(buf_len >= 2);
362 n = bc_history_read(buf + 1, 1);
363 if (BC_ERR(n <= 0)) goto err;
365 else if ((byte & 0xF0) == 0xE0) {
366 assert(buf_len >= 3);
367 n = bc_history_read(buf + 1, 2);
368 if (BC_ERR(n <= 0)) goto err;
370 else if ((byte & 0xF8) == 0xF0) {
371 assert(buf_len >= 3);
372 n = bc_history_read(buf + 1, 3);
373 if (BC_ERR(n <= 0)) goto err;
381 *nread = bc_history_codePoint(buf, buf_len, cp);
383 return BC_STATUS_SUCCESS;
386 if (BC_ERR(n < 0)) bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
387 else *nread = (size_t) n;
388 return BC_STATUS_EOF;
392 * Get column length from begining of buffer to current byte position.
394 static size_t bc_history_colPos(const char *buf, size_t buf_len, size_t pos) {
396 size_t ret = 0, off = 0;
402 len = bc_history_nextLen(buf, buf_len, off, &col_len);
412 * Return true if the terminal name is in the list of terminals we know are
413 * not able to understand basic escape sequences.
415 static inline bool bc_history_isBadTerm(void) {
418 char *term = getenv("TERM");
420 if (term == NULL) return false;
422 for (i = 0; bc_history_bad_terms[i]; ++i) {
423 if (!strcasecmp(term, bc_history_bad_terms[i])) return true;
430 * Raw mode: 1960's black magic.
432 static void bc_history_enableRaw(BcHistory *h) {
439 if (h->rawMode) return;
443 if (BC_ERR(tcgetattr(STDIN_FILENO, &h->orig_termios) == -1))
444 bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
448 // Modify the original mode.
449 raw = h->orig_termios;
451 // Input modes: no break, no CR to NL, no parity check, no strip char,
452 // no start/stop output control.
453 raw.c_iflag &= (unsigned int) (~(BRKINT | ICRNL | INPCK | ISTRIP | IXON));
455 // Control modes - set 8 bit chars.
456 raw.c_cflag |= (CS8);
458 // Local modes - choing off, canonical off, no extended functions,
459 // no signal chars (^Z,^C).
460 raw.c_lflag &= (unsigned int) (~(ECHO | ICANON | IEXTEN | ISIG));
462 // Control chars - set return condition: min number of bytes and timer.
463 // We want read to give every single byte, w/o timeout (1 byte, no timer).
469 // Put terminal in raw mode after flushing.
471 err = tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw);
472 } while (BC_ERR(err < 0) && errno == EINTR);
476 if (BC_ERR(err < 0)) bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
481 static void bc_history_disableRaw(BcHistory *h) {
485 // Don't even check the return value as it's too late.
486 if (!h->rawMode) return;
488 BC_SIG_TRYLOCK(lock);
490 if (BC_ERR(tcsetattr(STDIN_FILENO, TCSAFLUSH, &h->orig_termios) != -1))
493 BC_SIG_TRYUNLOCK(lock);
497 * Use the ESC [6n escape sequence to query the horizontal cursor position
498 * and return it. On error -1 is returned, on success the position of the
501 static size_t bc_history_cursorPos(void) {
503 char buf[BC_HIST_SEQ_SIZE];
505 size_t cols, rows, i;
507 // Report cursor location.
508 bc_file_write(&vm.fout, bc_flush_none, "\x1b[6n", 4);
509 bc_file_flush(&vm.fout, bc_flush_none);
511 // Read the response: ESC [ rows ; cols R.
512 for (i = 0; i < sizeof(buf) - 1; ++i) {
513 if (bc_history_read(buf + i, 1) != 1 || buf[i] == 'R') break;
518 if (BC_ERR(buf[0] != BC_ACTION_ESC || buf[1] != '[')) return SIZE_MAX;
522 rows = strtoul(ptr, &ptr2, 10);
524 if (BC_ERR(!rows || ptr2[0] != ';')) return SIZE_MAX;
527 cols = strtoul(ptr, NULL, 10);
529 if (BC_ERR(!cols)) return SIZE_MAX;
531 return cols <= UINT16_MAX ? cols : 0;
535 * Try to get the number of columns in the current terminal, or assume 80
538 static size_t bc_history_columns(void) {
545 ret = ioctl(vm.fout.fd, TIOCGWINSZ, &ws);
549 if (BC_ERR(ret == -1 || !ws.ws_col)) {
551 // Calling ioctl() failed. Try to query the terminal itself.
554 // Get the initial position so we can restore it later.
555 start = bc_history_cursorPos();
556 if (BC_ERR(start == SIZE_MAX)) return BC_HIST_DEF_COLS;
558 // Go to right margin and get position.
559 bc_file_write(&vm.fout, bc_flush_none, "\x1b[999C", 6);
560 bc_file_flush(&vm.fout, bc_flush_none);
561 cols = bc_history_cursorPos();
562 if (BC_ERR(cols == SIZE_MAX)) return BC_HIST_DEF_COLS;
566 bc_file_printf(&vm.fout, "\x1b[%zuD", cols - start);
567 bc_file_flush(&vm.fout, bc_flush_none);
578 * Check if text is an ANSI escape sequence.
580 static bool bc_history_ansiEscape(const char *buf, size_t buf_len, size_t *len)
582 if (buf_len > 2 && !memcmp("\033[", buf, 2)) {
586 while (off < buf_len) {
590 if ((c >= 'A' && c <= 'K' && c != 'I') ||
591 c == 'S' || c == 'T' || c == 'f' || c == 'm')
603 * Get column length of prompt text.
605 static size_t bc_history_promptColLen(const char *prompt, size_t plen) {
607 char buf[BC_HIST_MAX_LINE + 1];
608 size_t buf_len = 0, off = 0;
614 if (bc_history_ansiEscape(prompt + off, plen - off, &len)) {
619 buf[buf_len++] = prompt[off++];
622 return bc_history_colPos(buf, buf_len, buf_len);
624 #endif // BC_ENABLE_PROMPT
627 * Rewrites the currently edited line accordingly to the buffer content,
628 * cursor position, and number of columns of the terminal.
630 static void bc_history_refresh(BcHistory *h) {
632 char* buf = h->buf.v;
633 size_t colpos, len = BC_HIST_BUF_LEN(h), pos = h->pos;
635 bc_file_flush(&vm.fout, bc_flush_none);
637 while(h->pcol + bc_history_colPos(buf, len, pos) >= h->cols) {
639 size_t chlen = bc_history_nextLen(buf, len, 0, NULL);
646 while (h->pcol + bc_history_colPos(buf, len, len) > h->cols)
647 len -= bc_history_prevLen(buf, len, NULL);
649 // Cursor to left edge.
650 bc_file_write(&vm.fout, bc_flush_none, "\r", 1);
652 // Take the extra stuff into account.
653 if (h->extras.len > 1) {
654 len += h->extras.len - 1;
655 pos += h->extras.len - 1;
656 bc_file_write(&vm.fout, bc_flush_none, h->extras.v, h->extras.len - 1);
659 // Write the prompt, if desired.
662 bc_file_write(&vm.fout, bc_flush_none, h->prompt, h->plen);
663 #endif // BC_ENABLE_PROMPT
665 bc_file_write(&vm.fout, bc_flush_none, buf, BC_HIST_BUF_LEN(h));
668 bc_file_write(&vm.fout, bc_flush_none, "\x1b[0K", 4);
670 // Move cursor to original position.
671 colpos = bc_history_colPos(buf, len, pos) + h->pcol;
673 if (colpos) bc_file_printf(&vm.fout, "\r\x1b[%zuC", colpos);
675 bc_file_flush(&vm.fout, bc_flush_none);
679 * Insert the character 'c' at cursor current position.
681 static void bc_history_edit_insert(BcHistory *h, const char *cbuf, size_t clen)
683 bc_vec_grow(&h->buf, clen);
685 if (h->pos == BC_HIST_BUF_LEN(h)) {
687 size_t colpos = 0, len;
689 memcpy(bc_vec_item(&h->buf, h->pos), cbuf, clen);
692 h->buf.len += clen - 1;
693 bc_vec_pushByte(&h->buf, '\0');
695 len = BC_HIST_BUF_LEN(h) + h->extras.len - 1;
697 colpos = bc_history_promptColLen(h->prompt, h->plen);
698 #endif // BC_ENABLE_PROMPT
699 colpos += bc_history_colPos(h->buf.v, len, len);
701 if (colpos < h->cols) {
703 // Avoid a full update of the line in the trivial case.
704 bc_file_write(&vm.fout, bc_flush_none, cbuf, clen);
705 bc_file_flush(&vm.fout, bc_flush_none);
707 else bc_history_refresh(h);
711 size_t amt = BC_HIST_BUF_LEN(h) - h->pos;
713 memmove(h->buf.v + h->pos + clen, h->buf.v + h->pos, amt);
714 memcpy(h->buf.v + h->pos, cbuf, clen);
718 h->buf.v[BC_HIST_BUF_LEN(h)] = '\0';
720 bc_history_refresh(h);
725 * Move cursor to the left.
727 static void bc_history_edit_left(BcHistory *h) {
729 if (h->pos <= 0) return;
731 h->pos -= bc_history_prevLen(h->buf.v, h->pos, NULL);
733 bc_history_refresh(h);
737 * Move cursor on the right.
739 static void bc_history_edit_right(BcHistory *h) {
741 if (h->pos == BC_HIST_BUF_LEN(h)) return;
743 h->pos += bc_history_nextLen(h->buf.v, BC_HIST_BUF_LEN(h), h->pos, NULL);
745 bc_history_refresh(h);
749 * Move cursor to the end of the current word.
751 static void bc_history_edit_wordEnd(BcHistory *h) {
753 size_t len = BC_HIST_BUF_LEN(h);
755 if (!len || h->pos >= len) return;
757 while (h->pos < len && isspace(h->buf.v[h->pos])) h->pos += 1;
758 while (h->pos < len && !isspace(h->buf.v[h->pos])) h->pos += 1;
760 bc_history_refresh(h);
764 * Move cursor to the start of the current word.
766 static void bc_history_edit_wordStart(BcHistory *h) {
768 size_t len = BC_HIST_BUF_LEN(h);
772 while (h->pos > 0 && isspace(h->buf.v[h->pos - 1])) h->pos -= 1;
773 while (h->pos > 0 && !isspace(h->buf.v[h->pos - 1])) h->pos -= 1;
775 bc_history_refresh(h);
779 * Move cursor to the start of the line.
781 static void bc_history_edit_home(BcHistory *h) {
787 bc_history_refresh(h);
791 * Move cursor to the end of the line.
793 static void bc_history_edit_end(BcHistory *h) {
795 if (h->pos == BC_HIST_BUF_LEN(h)) return;
797 h->pos = BC_HIST_BUF_LEN(h);
799 bc_history_refresh(h);
803 * Substitute the currently edited line with the next or previous history
804 * entry as specified by 'dir' (direction).
806 static void bc_history_edit_next(BcHistory *h, bool dir) {
808 const char *dup, *str;
810 if (h->history.len <= 1) return;
814 if (h->buf.v[0]) dup = bc_vm_strdup(h->buf.v);
817 // Update the current history entry before
818 // overwriting it with the next one.
819 bc_vec_replaceAt(&h->history, h->history.len - 1 - h->idx, &dup);
823 // Show the new entry.
824 h->idx += (dir == BC_HIST_PREV ? 1 : SIZE_MAX);
826 if (h->idx == SIZE_MAX) {
830 else if (h->idx >= h->history.len) {
831 h->idx = h->history.len - 1;
835 str = *((char**) bc_vec_item(&h->history, h->history.len - 1 - h->idx));
836 bc_vec_string(&h->buf, strlen(str), str);
837 assert(h->buf.len > 0);
839 h->pos = BC_HIST_BUF_LEN(h);
841 bc_history_refresh(h);
845 * Delete the character at the right of the cursor without altering the cursor
846 * position. Basically this is what happens with the "Delete" keyboard key.
848 static void bc_history_edit_delete(BcHistory *h) {
850 size_t chlen, len = BC_HIST_BUF_LEN(h);
852 if (!len || h->pos >= len) return;
854 chlen = bc_history_nextLen(h->buf.v, len, h->pos, NULL);
856 memmove(h->buf.v + h->pos, h->buf.v + h->pos + chlen, len - h->pos - chlen);
859 h->buf.v[BC_HIST_BUF_LEN(h)] = '\0';
861 bc_history_refresh(h);
864 static void bc_history_edit_backspace(BcHistory *h) {
866 size_t chlen, len = BC_HIST_BUF_LEN(h);
868 if (!h->pos || !len) return;
870 chlen = bc_history_prevLen(h->buf.v, h->pos, NULL);
872 memmove(h->buf.v + h->pos - chlen, h->buf.v + h->pos, len - h->pos);
876 h->buf.v[BC_HIST_BUF_LEN(h)] = '\0';
878 bc_history_refresh(h);
882 * Delete the previous word, maintaining the cursor at the start of the
885 static void bc_history_edit_deletePrevWord(BcHistory *h) {
887 size_t diff, old_pos = h->pos;
889 while (h->pos > 0 && h->buf.v[h->pos - 1] == ' ') --h->pos;
890 while (h->pos > 0 && h->buf.v[h->pos - 1] != ' ') --h->pos;
892 diff = old_pos - h->pos;
893 memmove(h->buf.v + h->pos, h->buf.v + old_pos,
894 BC_HIST_BUF_LEN(h) - old_pos + 1);
897 bc_history_refresh(h);
901 * Delete the next word, maintaining the cursor at the same position.
903 static void bc_history_edit_deleteNextWord(BcHistory *h) {
905 size_t next_end = h->pos, len = BC_HIST_BUF_LEN(h);
907 while (next_end < len && h->buf.v[next_end] == ' ') ++next_end;
908 while (next_end < len && h->buf.v[next_end] != ' ') ++next_end;
910 memmove(h->buf.v + h->pos, h->buf.v + next_end, len - next_end);
912 h->buf.len -= next_end - h->pos;
914 bc_history_refresh(h);
917 static void bc_history_swap(BcHistory *h) {
922 pcl = bc_history_prevLen(h->buf.v, h->pos, NULL);
923 ncl = bc_history_nextLen(h->buf.v, BC_HIST_BUF_LEN(h), h->pos, NULL);
925 // To perform a swap we need:
926 // * nonzero char length to the left
927 // * not at the end of the line
928 if (pcl && h->pos != BC_HIST_BUF_LEN(h) && pcl < 5 && ncl < 5) {
930 memcpy(auxb, h->buf.v + h->pos - pcl, pcl);
931 memcpy(h->buf.v + h->pos - pcl, h->buf.v + h->pos, ncl);
932 memcpy(h->buf.v + h->pos - pcl + ncl, auxb, pcl);
934 h->pos += -pcl + ncl;
936 bc_history_refresh(h);
941 * Handle escape sequences.
943 static void bc_history_escape(BcHistory *h) {
947 if (BC_ERR(BC_HIST_READ(seq, 1))) return;
952 if (c != '[' && c != 'O') {
953 if (c == 'f') bc_history_edit_wordEnd(h);
954 else if (c == 'b') bc_history_edit_wordStart(h);
955 else if (c == 'd') bc_history_edit_deleteNextWord(h);
959 if (BC_ERR(BC_HIST_READ(seq + 1, 1)))
960 bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
967 if (c >= '0' && c <= '9') {
969 // Extended escape, read additional byte.
970 if (BC_ERR(BC_HIST_READ(seq + 2, 1)))
971 bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
973 if (seq[2] == '~' && c == '3') bc_history_edit_delete(h);
974 else if(seq[2] == ';') {
976 if (BC_ERR(BC_HIST_READ(seq, 2)))
977 bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
979 if (seq[0] != '5') return;
980 else if (seq[1] == 'C') bc_history_edit_wordEnd(h);
981 else if (seq[1] == 'D') bc_history_edit_wordStart(h);
991 bc_history_edit_next(h, BC_HIST_PREV);
998 bc_history_edit_next(h, BC_HIST_NEXT);
1005 bc_history_edit_right(h);
1012 bc_history_edit_left(h);
1020 bc_history_edit_home(h);
1028 bc_history_edit_end(h);
1034 bc_history_edit_deleteNextWord(h);
1041 else if (c == 'O') {
1047 bc_history_edit_next(h, BC_HIST_PREV);
1053 bc_history_edit_next(h, BC_HIST_NEXT);
1059 bc_history_edit_right(h);
1065 bc_history_edit_left(h);
1071 bc_history_edit_end(h);
1077 bc_history_edit_home(h);
1085 static void bc_history_reset(BcHistory *h) {
1087 h->oldcolpos = h->pos = h->idx = 0;
1088 h->cols = bc_history_columns();
1090 // The latest history entry is always our current buffer, that
1091 // initially is just an empty string.
1092 bc_history_add_empty(h);
1094 // Buffer starts empty.
1095 bc_vec_empty(&h->buf);
1098 static void bc_history_printCtrl(BcHistory *h, unsigned int c) {
1101 const char newline[2] = "\n";
1103 str[1] = (char) (c + 'A' - BC_ACTION_CTRL_A);
1105 bc_vec_concat(&h->buf, str);
1107 bc_history_refresh(h);
1109 bc_vec_npop(&h->buf, sizeof(str));
1110 bc_vec_pushByte(&h->buf, '\0');
1112 if (c != BC_ACTION_CTRL_C && c != BC_ACTION_CTRL_D) {
1113 bc_file_write(&vm.fout, bc_flush_none, newline, sizeof(newline) - 1);
1114 bc_history_refresh(h);
1119 * This function is the core of the line editing capability of bc history.
1120 * It expects 'fd' to be already in "raw mode" so that every key pressed
1121 * will be returned ASAP to read().
1123 static BcStatus bc_history_edit(BcHistory *h, const char *prompt) {
1125 bc_history_reset(h);
1127 // Don't write the saved output the first time. This is because it has
1128 // already been written to output. In other words, don't uncomment the
1129 // line below or add anything like it.
1130 // bc_file_write(&vm.fout, bc_flush_none, h->extras.v, h->extras.len - 1);
1132 #if BC_ENABLE_PROMPT
1133 if (BC_USE_PROMPT) {
1136 h->plen = strlen(prompt);
1137 h->pcol = bc_history_promptColLen(prompt, h->plen);
1139 bc_file_write(&vm.fout, bc_flush_none, prompt, h->plen);
1140 bc_file_flush(&vm.fout, bc_flush_none);
1142 #endif // BC_ENABLE_PROMPT
1147 // Large enough for any encoding?
1152 s = bc_history_readCode(cbuf, sizeof(cbuf), &c, &nread);
1153 if (BC_ERR(s)) return s;
1157 case BC_ACTION_LINE_FEED:
1158 case BC_ACTION_ENTER:
1160 bc_vec_pop(&h->history);
1166 memcpy(cbuf, bc_history_tab, bc_history_tab_len + 1);
1167 bc_history_edit_insert(h, cbuf, bc_history_tab_len);
1171 case BC_ACTION_CTRL_C:
1173 bc_history_printCtrl(h, c);
1174 bc_file_write(&vm.fout, bc_flush_none, vm.sigmsg, vm.siglen);
1175 bc_file_write(&vm.fout, bc_flush_none, bc_program_ready_msg,
1176 bc_program_ready_msg_len);
1177 bc_history_reset(h);
1178 bc_history_refresh(h);
1182 case BC_ACTION_BACKSPACE:
1183 case BC_ACTION_CTRL_H:
1185 bc_history_edit_backspace(h);
1189 // Act as end-of-file.
1190 case BC_ACTION_CTRL_D:
1192 bc_history_printCtrl(h, c);
1193 return BC_STATUS_EOF;
1196 // Swaps current character with previous.
1197 case BC_ACTION_CTRL_T:
1203 case BC_ACTION_CTRL_B:
1205 bc_history_edit_left(h);
1209 case BC_ACTION_CTRL_F:
1211 bc_history_edit_right(h);
1215 case BC_ACTION_CTRL_P:
1217 bc_history_edit_next(h, BC_HIST_PREV);
1221 case BC_ACTION_CTRL_N:
1223 bc_history_edit_next(h, BC_HIST_NEXT);
1229 bc_history_escape(h);
1233 // Delete the whole line.
1234 case BC_ACTION_CTRL_U:
1236 bc_vec_string(&h->buf, 0, "");
1239 bc_history_refresh(h);
1244 // Delete from current to end of line.
1245 case BC_ACTION_CTRL_K:
1247 bc_vec_npop(&h->buf, h->buf.len - h->pos);
1248 bc_vec_pushByte(&h->buf, '\0');
1249 bc_history_refresh(h);
1253 // Go to the start of the line.
1254 case BC_ACTION_CTRL_A:
1256 bc_history_edit_home(h);
1260 // Go to the end of the line.
1261 case BC_ACTION_CTRL_E:
1263 bc_history_edit_end(h);
1268 case BC_ACTION_CTRL_L:
1270 bc_file_write(&vm.fout, bc_flush_none, "\x1b[H\x1b[2J", 7);
1271 bc_history_refresh(h);
1275 // Delete previous word.
1276 case BC_ACTION_CTRL_W:
1278 bc_history_edit_deletePrevWord(h);
1284 if (c >= BC_ACTION_CTRL_A && c <= BC_ACTION_CTRL_Z)
1285 bc_history_printCtrl(h, c);
1286 else bc_history_edit_insert(h, cbuf, nread);
1292 return BC_STATUS_SUCCESS;
1295 static inline bool bc_history_stdinHasData(BcHistory *h) {
1297 return pselect(1, &h->rdset, NULL, NULL, &h->ts, &h->sigmask) > 0 ||
1298 (ioctl(STDIN_FILENO, FIONREAD, &n) >= 0 && n > 0);
1302 * This function calls the line editing function bc_history_edit()
1303 * using the STDIN file descriptor set in raw mode.
1305 static BcStatus bc_history_raw(BcHistory *h, const char *prompt) {
1309 assert(vm.fout.len == 0);
1311 bc_history_enableRaw(h);
1313 s = bc_history_edit(h, prompt);
1315 h->stdin_has_data = bc_history_stdinHasData(h);
1316 if (!h->stdin_has_data) bc_history_disableRaw(h);
1318 bc_file_write(&vm.fout, bc_flush_none, "\n", 1);
1319 bc_file_flush(&vm.fout, bc_flush_none);
1324 BcStatus bc_history_line(BcHistory *h, BcVec *vec, const char *prompt) {
1329 s = bc_history_raw(h, prompt);
1330 assert(!s || s == BC_STATUS_EOF);
1332 bc_vec_string(vec, BC_HIST_BUF_LEN(h), h->buf.v);
1338 line = bc_vm_strdup(h->buf.v);
1342 bc_history_add(h, line);
1344 else bc_history_add_empty(h);
1346 bc_vec_concat(vec, "\n");
1351 static void bc_history_add(BcHistory *h, char *line) {
1353 if (h->history.len) {
1355 char *s = *((char**) bc_vec_item_rev(&h->history, 0));
1357 if (!strcmp(s, line)) {
1369 bc_vec_push(&h->history, &line);
1372 static void bc_history_add_empty(BcHistory *h) {
1374 const char *line = "";
1376 if (h->history.len) {
1378 char *s = *((char**) bc_vec_item_rev(&h->history, 0));
1383 bc_vec_push(&h->history, &line);
1386 static void bc_history_string_free(void *str) {
1387 char *s = *((char**) str);
1388 BC_SIG_ASSERT_LOCKED;
1392 void bc_history_init(BcHistory *h) {
1394 BC_SIG_ASSERT_LOCKED;
1396 bc_vec_init(&h->buf, sizeof(char), NULL);
1397 bc_vec_init(&h->history, sizeof(char*), bc_history_string_free);
1398 bc_vec_init(&h->extras, sizeof(char), NULL);
1401 FD_SET(STDIN_FILENO, &h->rdset);
1405 sigemptyset(&h->sigmask);
1406 sigaddset(&h->sigmask, SIGINT);
1408 h->rawMode = h->stdin_has_data = false;
1409 h->badTerm = bc_history_isBadTerm();
1412 void bc_history_free(BcHistory *h) {
1413 BC_SIG_ASSERT_LOCKED;
1414 bc_history_disableRaw(h);
1416 bc_vec_free(&h->buf);
1417 bc_vec_free(&h->history);
1418 bc_vec_free(&h->extras);
1423 * This special mode is used by bc history in order to print scan codes
1424 * on screen for debugging / development purposes.
1427 void bc_history_printKeyCodes(BcHistory *h) {
1431 bc_vm_printf("Linenoise key codes debugging mode.\n"
1432 "Press keys to see scan codes. "
1433 "Type 'quit' at any time to exit.\n");
1435 bc_history_enableRaw(h);
1436 memset(quit, ' ', 4);
1443 nread = bc_history_read(&c, 1);
1444 if (nread <= 0) continue;
1446 // Shift string to left.
1447 memmove(quit, quit + 1, sizeof(quit) - 1);
1449 // Insert current char on the right.
1450 quit[sizeof(quit) - 1] = c;
1451 if (!memcmp(quit, "quit", sizeof(quit))) break;
1453 bc_vm_printf("'%c' %lu (type quit to exit)\n",
1454 isprint(c) ? c : '?', (unsigned long) c);
1456 // Go left edge manually, we are in raw mode.
1457 bc_vm_putchar('\r', bc_flush_none);
1458 bc_file_flush(&vm.fout, bc_flush_none);
1461 bc_history_disableRaw(h);
1463 #endif // BC_DEBUG_CODE
1465 #endif // BC_ENABLE_HISTORY