xref: /freebsd/contrib/bc/include/history.h (revision d9a42747950146bf03cda7f6e25d219253f8a57a)
1 /*
2  * *****************************************************************************
3  *
4  * SPDX-License-Identifier: BSD-2-Clause
5  *
6  * Copyright (c) 2018-2023 Gavin D. Howard and contributors.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions are met:
10  *
11  * * Redistributions of source code must retain the above copyright notice, this
12  *   list of conditions and the following disclaimer.
13  *
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.
17  *
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.
29  *
30  * *****************************************************************************
31  *
32  * Adapted from the following:
33  *
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.
36  *
37  * You can find the original source code at:
38  *   http://github.com/antirez/linenoise
39  *
40  * You can find the fork that this code is based on at:
41  *   https://github.com/rain-1/linenoise-mob
42  *
43  * ------------------------------------------------------------------------
44  *
45  * This code is also under the following license:
46  *
47  * Copyright (c) 2010-2016, Salvatore Sanfilippo <antirez at gmail dot com>
48  * Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis at gmail dot com>
49  *
50  * Redistribution and use in source and binary forms, with or without
51  * modification, are permitted provided that the following conditions are
52  * met:
53  *
54  *  *  Redistributions of source code must retain the above copyright
55  *     notice, this list of conditions and the following disclaimer.
56  *
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.
60  *
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.
72  *
73  * *****************************************************************************
74  *
75  * Definitions for line history.
76  *
77  */
78 
79 #ifndef BC_HISTORY_H
80 #define BC_HISTORY_H
81 
82 // These must come before the #if BC_ENABLE_LINE_LIB below because status.h
83 // defines it.
84 #include <status.h>
85 #include <vector.h>
86 
87 #if BC_ENABLE_LINE_LIB
88 
89 #include <stdbool.h>
90 #include <setjmp.h>
91 #include <signal.h>
92 
93 extern sigjmp_buf bc_history_jmpbuf;
94 extern volatile sig_atomic_t bc_history_inlinelib;
95 
96 #endif // BC_ENABLE_LINE_LIB
97 
98 #if BC_ENABLE_EDITLINE
99 
100 #include <stdio.h>
101 #include <histedit.h>
102 
103 /**
104  * The history struct for editline.
105  */
106 typedef struct BcHistory
107 {
108 	/// A place to store the current line.
109 	EditLine* el;
110 
111 	/// The history.
112 	History* hist;
113 
114 	/// Whether the terminal is bad. This is more or less not used.
115 	bool badTerm;
116 
117 } BcHistory;
118 
119 // The path to the editrc and its length.
120 extern const char bc_history_editrc[];
121 extern const size_t bc_history_editrc_len;
122 
123 #else // BC_ENABLE_EDITLINE
124 
125 #if BC_ENABLE_READLINE
126 
127 #include <stdio.h>
128 #include <readline/readline.h>
129 #include <readline/history.h>
130 
131 /**
132  * The history struct for readline.
133  */
134 typedef struct BcHistory
135 {
136 	/// A place to store the current line.
137 	char* line;
138 
139 	/// Whether the terminal is bad. This is more or less not used.
140 	bool badTerm;
141 
142 } BcHistory;
143 
144 #else // BC_ENABLE_READLINE
145 
146 #if BC_ENABLE_HISTORY
147 
148 #include <stddef.h>
149 
150 #include <signal.h>
151 
152 #ifndef _WIN32
153 #include <termios.h>
154 #include <time.h>
155 #include <unistd.h>
156 #include <sys/select.h>
157 #else // _WIN32
158 
159 #ifndef WIN32_LEAN_AND_MEAN
160 #define WIN32_LEAN_AND_MEAN
161 #endif // WIN32_LEAN_AND_MEAN
162 
163 #include <Windows.h>
164 #include <io.h>
165 #include <conio.h>
166 
167 #define strncasecmp _strnicmp
168 #define strcasecmp _stricmp
169 
170 #endif // _WIN32
171 
172 #include <status.h>
173 #include <vector.h>
174 #include <read.h>
175 
176 #if BC_DEBUG_CODE
177 #include <file.h>
178 #endif // BC_DEBUG_CODE
179 
180 /// Default columns.
181 #define BC_HIST_DEF_COLS (80)
182 
183 /// Max number of history entries.
184 #define BC_HIST_MAX_LEN (128)
185 
186 /// Max length of a line.
187 #define BC_HIST_MAX_LINE (4095)
188 
189 /// Max size for cursor position buffer.
190 #define BC_HIST_SEQ_SIZE (64)
191 
192 /**
193  * The number of entries in the history.
194  * @param h  The history data.
195  */
196 #define BC_HIST_BUF_LEN(h) ((h)->buf.len - 1)
197 
198 /**
199  * Read n characters into s and check the error.
200  * @param s  The buffer to read into.
201  * @param n  The number of bytes to read.
202  * @return   True if there was an error, false otherwise.
203  */
204 #define BC_HIST_READ(s, n) (bc_history_read((s), (n)) == -1)
205 
206 /// Markers for direction when using arrow keys.
207 #define BC_HIST_NEXT (false)
208 #define BC_HIST_PREV (true)
209 
210 #if BC_DEBUG_CODE
211 
212 // These are just for debugging.
213 
214 #define BC_HISTORY_DEBUG_BUF_SIZE (1024)
215 
216 // clang-format off
217 #define lndebug(...)                                                        \
218 	do                                                                      \
219 	{                                                                       \
220 		if (bc_history_debug_fp.fd == 0)                                    \
221 		{                                                                   \
222 			bc_history_debug_buf = bc_vm_malloc(BC_HISTORY_DEBUG_BUF_SIZE); \
223 			bc_file_init(&bc_history_debug_fp,                              \
224 			             open("/tmp/lndebug.txt", O_APPEND),                \
225 		                 BC_HISTORY_DEBUG_BUF_SIZE);                        \
226 			bc_file_printf(&bc_history_debug_fp,                            \
227 			       "[%zu %zu %zu] p: %d, rows: %d, "                        \
228 			       "rpos: %d, max: %zu, oldmax: %d\n",                      \
229 			       l->len, l->pos, l->oldcolpos, plen, rows, rpos,          \
230 			       l->maxrows, old_rows);                                   \
231 		}                                                                   \
232 		bc_file_printf(&bc_history_debug_fp, ", " __VA_ARGS__);             \
233 		bc_file_flush(&bc_history_debug_fp);                                \
234 	}                                                                       \
235 	while (0)
236 #else // BC_DEBUG_CODE
237 #define lndebug(fmt, ...)
238 #endif // BC_DEBUG_CODE
239 // clang-format on
240 
241 /// An enum of useful actions. To understand what these mean, check terminal
242 /// emulators for their shortcuts or the VT100 codes.
243 typedef enum BcHistoryAction
244 {
245 	BC_ACTION_NULL = 0,
246 	BC_ACTION_CTRL_A = 1,
247 	BC_ACTION_CTRL_B = 2,
248 	BC_ACTION_CTRL_C = 3,
249 	BC_ACTION_CTRL_D = 4,
250 	BC_ACTION_CTRL_E = 5,
251 	BC_ACTION_CTRL_F = 6,
252 	BC_ACTION_CTRL_H = 8,
253 	BC_ACTION_TAB = 9,
254 	BC_ACTION_LINE_FEED = 10,
255 	BC_ACTION_CTRL_K = 11,
256 	BC_ACTION_CTRL_L = 12,
257 	BC_ACTION_ENTER = 13,
258 	BC_ACTION_CTRL_N = 14,
259 	BC_ACTION_CTRL_P = 16,
260 	BC_ACTION_CTRL_S = 19,
261 	BC_ACTION_CTRL_T = 20,
262 	BC_ACTION_CTRL_U = 21,
263 	BC_ACTION_CTRL_W = 23,
264 	BC_ACTION_CTRL_Z = 26,
265 	BC_ACTION_ESC = 27,
266 	BC_ACTION_CTRL_BSLASH = 28,
267 	BC_ACTION_BACKSPACE = 127
268 
269 } BcHistoryAction;
270 
271 /**
272  * This represents the state during line editing. We pass this state
273  * to functions implementing specific editing functionalities.
274  */
275 typedef struct BcHistory
276 {
277 	/// Edited line buffer.
278 	BcVec buf;
279 
280 	/// The history.
281 	BcVec history;
282 
283 	/// Any material printed without a trailing newline.
284 	BcVec extras;
285 
286 	/// Prompt to display.
287 	const char* prompt;
288 
289 	/// Prompt length.
290 	size_t plen;
291 
292 	/// Prompt column length.
293 	size_t pcol;
294 
295 	/// Current cursor position.
296 	size_t pos;
297 
298 	/// Previous refresh cursor column position.
299 	size_t oldcolpos;
300 
301 	/// Number of columns in terminal.
302 	size_t cols;
303 
304 	/// The history index we are currently editing.
305 	size_t idx;
306 
307 #ifndef _WIN32
308 	/// The original terminal state.
309 	struct termios orig_termios;
310 #else // _WIN32
311 	///  The original input console mode.
312 	DWORD orig_in;
313 
314 	///  The original output console mode.
315 	DWORD orig_out;
316 #endif // _WIN32
317 
318 	/// These next two are here because pahole found a 4 byte hole here.
319 
320 	/// Whether we are in rawmode.
321 	bool rawMode;
322 
323 	/// Whether the terminal is bad.
324 	bool badTerm;
325 
326 #ifndef _WIN32
327 	/// This is to check if stdin has more data.
328 	fd_set rdset;
329 
330 	/// This is to check if stdin has more data.
331 	struct timespec ts;
332 
333 	/// This is to check if stdin has more data.
334 	sigset_t sigmask;
335 #endif // _WIN32
336 
337 } BcHistory;
338 
339 /**
340  * Frees strings used by history.
341  * @param str  The string to free.
342  */
343 void
344 bc_history_string_free(void* str);
345 
346 // A list of terminals that don't work.
347 extern const char* bc_history_bad_terms[];
348 
349 // A tab in history and its length.
350 extern const char bc_history_tab[];
351 extern const size_t bc_history_tab_len;
352 
353 // A ctrl+c string.
354 extern const char bc_history_ctrlc[];
355 
356 // UTF-8 data arrays.
357 extern const uint32_t bc_history_wchars[][2];
358 extern const size_t bc_history_wchars_len;
359 extern const uint32_t bc_history_combo_chars[];
360 extern const size_t bc_history_combo_chars_len;
361 
362 #if BC_DEBUG_CODE
363 
364 // Debug data.
365 extern BcFile bc_history_debug_fp;
366 extern char* bc_history_debug_buf;
367 
368 /**
369  * A function to print keycodes for debugging.
370  * @param h  The history data.
371  */
372 void
373 bc_history_printKeyCodes(BcHistory* h);
374 
375 #endif // BC_DEBUG_CODE
376 
377 #endif // BC_ENABLE_HISTORY
378 
379 #endif // BC_ENABLE_READLINE
380 
381 #endif // BC_ENABLE_EDITLINE
382 
383 #if BC_ENABLE_HISTORY
384 
385 /**
386  * Get a line from stdin using history. This returns a status because I don't
387  * want to throw errors while the terminal is in raw mode.
388  * @param h       The history data.
389  * @param vec     A vector to put the line into.
390  * @param prompt  The prompt to display, if desired.
391  * @return        A status indicating an error, if any. Returning a status here
392  *                is better because if we throw an error out of history, we
393  *                leave the terminal in raw mode or in some other half-baked
394  *                state.
395  */
396 BcStatus
397 bc_history_line(BcHistory* h, BcVec* vec, const char* prompt);
398 
399 /**
400  * Initialize history data.
401  * @param h  The struct to initialize.
402  */
403 void
404 bc_history_init(BcHistory* h);
405 
406 /**
407  * Free history data (and recook the terminal).
408  * @param h  The struct to free.
409  */
410 void
411 bc_history_free(BcHistory* h);
412 
413 #endif // BC_ENABLE_HISTORY
414 
415 #endif // BC_HISTORY_H
416