nail.1: (re)add s_client certificate fetch (Olav Mørkrid)
[s-mailx.git] / tty.c
blobfef82059d83fa6abcc85f8a45a107326b4567a1b
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ TTY (command line) editing interaction.
3 *@ Because we have (had) multiple line-editor implementations, including our
4 *@ own M(ailx) L(ine) E(ditor), change the file layout a bit and place those
5 *@ one after the other below the other externals.
7 * Copyright (c) 2012 - 2018 Steffen (Daode) Nurpmeso <steffen@sdaoden.eu>.
9 * Permission to use, copy, modify, and/or distribute this software for any
10 * purpose with or without fee is hereby granted, provided that the above
11 * copyright notice and this permission notice appear in all copies.
13 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
14 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
15 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
16 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
17 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21 #undef n_FILE
22 #define n_FILE tty
24 #ifndef HAVE_AMALGAMATION
25 # include "nail.h"
26 #endif
28 #if defined HAVE_MLE || defined HAVE_TERMCAP
29 # define a_TTY_SIGNALS
30 #endif
32 #ifdef a_TTY_SIGNALS
33 static sighandler_type a_tty_oint, a_tty_oquit, a_tty_oterm,
34 a_tty_ohup,
35 a_tty_otstp, a_tty_ottin, a_tty_ottou;
36 #endif
38 #ifdef a_TTY_SIGNALS
39 static void a_tty_sigs_up(void), a_tty_sigs_down(void);
40 #endif
42 /* Prototype here, implementation is specific to chosen editor */
43 static void a_tty_signal(int sig);
45 #ifdef a_TTY_SIGNALS
46 static void
47 a_tty_sigs_up(void){
48 sigset_t nset, oset;
49 NYD2_ENTER;
51 sigfillset(&nset);
53 sigprocmask(SIG_BLOCK, &nset, &oset);
54 a_tty_oint = safe_signal(SIGINT, &a_tty_signal);
55 a_tty_oquit = safe_signal(SIGQUIT, &a_tty_signal);
56 a_tty_oterm = safe_signal(SIGTERM, &a_tty_signal);
57 a_tty_ohup = safe_signal(SIGHUP, &a_tty_signal);
58 a_tty_otstp = safe_signal(SIGTSTP, &a_tty_signal);
59 a_tty_ottin = safe_signal(SIGTTIN, &a_tty_signal);
60 a_tty_ottou = safe_signal(SIGTTOU, &a_tty_signal);
61 sigprocmask(SIG_SETMASK, &oset, NULL);
62 NYD2_LEAVE;
65 static void
66 a_tty_sigs_down(void){
67 sigset_t nset, oset;
68 NYD2_ENTER;
70 sigfillset(&nset);
72 sigprocmask(SIG_BLOCK, &nset, &oset);
73 safe_signal(SIGINT, a_tty_oint);
74 safe_signal(SIGQUIT, a_tty_oquit);
75 safe_signal(SIGTERM, a_tty_oterm);
76 safe_signal(SIGHUP, a_tty_ohup);
77 safe_signal(SIGTSTP, a_tty_otstp);
78 safe_signal(SIGTTIN, a_tty_ottin);
79 safe_signal(SIGTTOU, a_tty_ottou);
80 sigprocmask(SIG_SETMASK, &oset, NULL);
81 NYD2_LEAVE;
83 #endif /* a_TTY_SIGNALS */
85 static sigjmp_buf a_tty__actjmp; /* TODO someday, we won't need it no more */
86 static void
87 a_tty__acthdl(int s) /* TODO someday, we won't need it no more */
89 NYD_X; /* Signal handler */
90 siglongjmp(a_tty__actjmp, s);
93 FL bool_t
94 getapproval(char const * volatile prompt, bool_t noninteract_default)
96 sighandler_type volatile oint, ohup;
97 bool_t volatile rv;
98 int volatile sig;
99 NYD_ENTER;
101 if(!(n_psonce & n_PSO_INTERACTIVE) || (n_pstate & n_PS_ROBOT)){
102 sig = 0;
103 rv = noninteract_default;
104 goto jleave;
106 rv = FAL0;
108 /* C99 */{
109 char const *quest = noninteract_default
110 ? _("[yes]/no? ") : _("[no]/yes? ");
112 if (prompt == NULL)
113 prompt = _("Continue");
114 prompt = savecatsep(prompt, ' ', quest);
117 oint = safe_signal(SIGINT, SIG_IGN);
118 ohup = safe_signal(SIGHUP, SIG_IGN);
119 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
120 goto jrestore;
121 safe_signal(SIGINT, &a_tty__acthdl);
122 safe_signal(SIGHUP, &a_tty__acthdl);
124 while(n_go_input(n_GO_INPUT_CTX_DEFAULT | n_GO_INPUT_NL_ESC, prompt,
125 &termios_state.ts_linebuf, &termios_state.ts_linesize, NULL,NULL
126 ) >= 0){
127 bool_t x;
129 x = n_boolify(termios_state.ts_linebuf, UIZ_MAX, noninteract_default);
130 if(x >= FAL0){
131 rv = x;
132 break;
135 jrestore:
136 safe_signal(SIGHUP, ohup);
137 safe_signal(SIGINT, oint);
138 jleave:
139 NYD_LEAVE;
140 if (sig != 0)
141 n_raise(sig);
142 return rv;
145 #ifdef HAVE_SOCKETS
146 FL char *
147 getuser(char const * volatile query) /* TODO v15-compat obsolete */
149 sighandler_type volatile oint, ohup;
150 char * volatile user = NULL;
151 int volatile sig;
152 NYD_ENTER;
154 if (query == NULL)
155 query = _("User: ");
157 oint = safe_signal(SIGINT, SIG_IGN);
158 ohup = safe_signal(SIGHUP, SIG_IGN);
159 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
160 goto jrestore;
161 safe_signal(SIGINT, &a_tty__acthdl);
162 safe_signal(SIGHUP, &a_tty__acthdl);
164 if (n_go_input(n_GO_INPUT_CTX_DEFAULT | n_GO_INPUT_NL_ESC, query,
165 &termios_state.ts_linebuf, &termios_state.ts_linesize, NULL,NULL) >= 0)
166 user = termios_state.ts_linebuf;
168 jrestore:
169 safe_signal(SIGHUP, ohup);
170 safe_signal(SIGINT, oint);
172 NYD_LEAVE;
173 if (sig != 0)
174 n_raise(sig);
175 return user;
178 FL char *
179 getpassword(char const *query)/* TODO v15: use _only_ n_tty_fp! */
181 sighandler_type volatile oint, ohup;
182 struct termios tios;
183 char * volatile pass;
184 int volatile sig;
185 NYD_ENTER;
187 pass = NULL;
188 if(!(n_psonce & n_PSO_TTYIN))
189 goto j_leave;
191 if (query == NULL)
192 query = _("Password: ");
193 fputs(query, n_tty_fp);
194 fflush(n_tty_fp);
196 /* FIXME everywhere: tcsetattr() generates SIGTTOU when we're not in
197 * FIXME foreground pgrp, and can fail with EINTR!! also affects
198 * FIXME termios_state_reset() */
199 tcgetattr(STDIN_FILENO, &termios_state.ts_tios);
200 memcpy(&tios, &termios_state.ts_tios, sizeof tios);
201 termios_state.ts_needs_reset = TRU1;
202 tios.c_iflag &= ~(ISTRIP);
203 tios.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
205 oint = safe_signal(SIGINT, SIG_IGN);
206 ohup = safe_signal(SIGHUP, SIG_IGN);
207 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
208 goto jrestore;
209 safe_signal(SIGINT, &a_tty__acthdl);
210 safe_signal(SIGHUP, &a_tty__acthdl);
212 tcsetattr(STDIN_FILENO, TCSAFLUSH, &tios);
213 if (readline_restart(n_stdin, &termios_state.ts_linebuf,
214 &termios_state.ts_linesize, 0) >= 0)
215 pass = termios_state.ts_linebuf;
216 jrestore:
217 termios_state_reset();
218 putc('\n', n_tty_fp);
220 safe_signal(SIGHUP, ohup);
221 safe_signal(SIGINT, oint);
222 NYD_LEAVE;
223 if (sig != 0)
224 n_raise(sig);
225 j_leave:
226 return pass;
228 #endif /* HAVE_SOCKETS */
230 FL ui32_t
231 n_tty_create_prompt(struct n_string *store, char const *xprompt,
232 enum n_go_input_flags gif){
233 struct n_visual_info_ctx vic;
234 struct str in, out;
235 ui32_t pwidth;
236 char const *cp;
237 NYD2_ENTER;
239 /* Prompt creation indicates that prompt printing is directly ahead, so take
240 * this opportunity of UI-in-a-known-state and advertise the error ring */
241 #ifdef HAVE_ERRORS
242 if((n_psonce & (n_PSO_INTERACTIVE | n_PSO_ERRORS_NOTED)
243 ) == n_PSO_INTERACTIVE && (n_pstate & n_PS_ERRORS_PROMPT)){
244 n_psonce |= n_PSO_ERRORS_NOTED;
245 fprintf(n_stdout, _("There are new messages in the error message ring "
246 "(denoted by %s)\n"
247 " The `errors' command manages this message ring\n"),
248 V_(n_error));
250 #endif
252 jredo:
253 n_string_trunc(store, 0);
255 if(gif & n_GO_INPUT_PROMPT_NONE){
256 pwidth = 0;
257 goto jleave;
259 #ifdef HAVE_ERRORS
260 if(n_pstate & n_PS_ERRORS_PROMPT){
261 n_pstate &= ~n_PS_ERRORS_PROMPT;
262 store = n_string_push_cp(store, V_(n_error));
263 store = n_string_push_c(store, '#');
264 store = n_string_push_c(store, ' ');
266 #endif
268 cp = (gif & n_GO_INPUT_PROMPT_EVAL)
269 ? (gif & n_GO_INPUT_NL_FOLLOW ? ok_vlook(prompt2) : ok_vlook(prompt))
270 : xprompt;
271 if(cp != NULL && *cp != '\0'){
272 enum n_shexp_state shs;
274 store = n_string_push_cp(store, cp);
275 in.s = n_string_cp(store);
276 in.l = store->s_len;
277 out = in;
278 store = n_string_drop_ownership(store);
280 shs = n_shexp_parse_token((n_SHEXP_PARSE_LOG |
281 n_SHEXP_PARSE_IGNORE_EMPTY | n_SHEXP_PARSE_QUOTE_AUTO_FIXED |
282 n_SHEXP_PARSE_QUOTE_AUTO_DSQ), store, &in, NULL);
283 if((shs & n_SHEXP_STATE_ERR_MASK) || !(shs & n_SHEXP_STATE_STOP)){
284 store = n_string_clear(store);
285 store = n_string_take_ownership(store, out.s, out.l +1, out.l);
286 jeeval:
287 n_err(_("*prompt2?* evaluation failed, actively unsetting it\n"));
288 if(gif & n_GO_INPUT_NL_FOLLOW)
289 ok_vclear(prompt2);
290 else
291 ok_vclear(prompt);
292 goto jredo;
295 if(!store->s_auto)
296 n_free(out.s);
299 /* Make all printable TODO not know, we want to pass through ESC/CSI! */
300 #if 0
301 in.s = n_string_cp(store);
302 in.l = store->s_len;
303 makeprint(&in, &out);
304 store = n_string_assign_buf(store, out.s, out.l);
305 n_free(out.s);
306 #endif
308 /* We need the visual width.. */
309 memset(&vic, 0, sizeof vic);
310 vic.vic_indat = n_string_cp(store);
311 vic.vic_inlen = store->s_len;
312 for(pwidth = 0; vic.vic_inlen > 0;){
313 /* but \[ .. \] is not taken into account */
314 if(vic.vic_indat[0] == '\\' && vic.vic_inlen > 1 &&
315 vic.vic_indat[1] == '['){
316 size_t i;
318 i = PTR2SIZE(vic.vic_indat - store->s_dat);
319 store = n_string_cut(store, i, 2);
320 cp = &n_string_cp(store)[i];
321 i = store->s_len - i;
322 for(;; ++cp, --i){
323 if(i < 2){
324 n_err(_("Open \\[ sequence not closed in *prompt2?*\n"));
325 goto jeeval;
327 if(cp[0] == '\\' && cp[1] == ']')
328 break;
330 i = PTR2SIZE(cp - store->s_dat);
331 store = n_string_cut(store, i, 2);
332 vic.vic_indat = &n_string_cp(store)[i];
333 vic.vic_inlen = store->s_len - i;
334 }else if(!n_visual_info(&vic, n_VISUAL_INFO_WIDTH_QUERY |
335 n_VISUAL_INFO_ONE_CHAR)){
336 n_err(_("Character set error in evaluation of *prompt2?*\n"));
337 goto jeeval;
338 }else{
339 pwidth += (ui32_t)vic.vic_vi_width;
340 vic.vic_indat = vic.vic_oudat;
341 vic.vic_inlen = vic.vic_oulen;
345 /* And there may be colour support, too */
346 #ifdef HAVE_COLOUR
347 if(n_COLOUR_IS_ACTIVE()){
348 struct str const *psp, *rsp;
349 struct n_colour_pen *ccp;
351 if((ccp = n_colour_pen_create(n_COLOUR_ID_MLE_PROMPT, NULL)) != NULL &&
352 (psp = n_colour_pen_to_str(ccp)) != NULL &&
353 (rsp = n_colour_reset_to_str()) != NULL){
354 store = n_string_unshift_buf(store, psp->s, psp->l);
355 /*store =*/ n_string_push_buf(store, rsp->s, rsp->l);
358 #endif /* HAVE_COLOUR */
360 jleave:
361 NYD2_LEAVE;
362 return pwidth;
366 * MLE: the Mailx-Line-Editor, our homebrew editor
367 * (inspired from NetBSDs sh(1) and dash(1)s hetio.c).
369 * Only used in interactive mode.
370 * TODO . This code should be splitted in funs/raw input/bind modules.
371 * TODO . We work with wide characters, but not for buffer takeovers and
372 * TODO cell2save()ings. This should be changed. For the former the buffer
373 * TODO thus needs to be converted to wide first, and then simply be fed in.
374 * TODO . We repaint too much. To overcome this use the same approach that my
375 * TODO terminal library uses, add a true "virtual screen line" that stores
376 * TODO the actually visible content, keep a notion of "first modified slot"
377 * TODO and "last modified slot" (including "unknown" and "any" specials),
378 * TODO update that virtual instead, then synchronize what has truly changed.
379 * TODO I.e., add an indirection layer.
380 * TODO . No BIDI support.
381 * TODO . `bind': we currently use only one lookup tree.
382 * TODO For absolute graceful behaviour (in conjunction with HAVE_TERMCAP) we
383 * TODO need a lower level tree, which possibly combines bytes into "symbolic
384 * TODO wchar_t values", into "keys" that is, as applicable, and an upper
385 * TODO layer which only works on "keys" in order to possibly combine them
386 * TODO into key sequences. We can reuse existent tree code for that.
387 * TODO We need an additional hashmap which maps termcap/terminfo names to
388 * TODO (their byte representations and) a dynamically assigned unique
389 * TODO "symbolic wchar_t value". This implies we may have incompatibilities
390 * TODO when __STDC_ISO_10646__ is not defined. Also we do need takeover-
391 * TODO bytes storage, but it can be a string_creat_auto in the line struct.
392 * TODO Until then we can run into ambiguities; in rare occasions.
394 #ifdef HAVE_MLE
395 /* To avoid memory leaks etc. with the current codebase that simply longjmp(3)s
396 * we're forced to use the very same buffer--the one that is passed through to
397 * us from the outside--to store anything we need, i.e., a "struct cell[]", and
398 * convert that on-the-fly back to the plain char* result once we're done.
399 * To simplify our live, use savestr() buffers for all other needed memory */
401 # ifdef HAVE_KEY_BINDINGS
402 /* Default *bind-timeout* key-sequence continuation timeout, in tenths of
403 * a second. Must fit in 8-bit! Update the manual upon change! */
404 # define a_TTY_BIND_TIMEOUT 2
405 # define a_TTY_BIND_TIMEOUT_MAX SI8_MAX
407 n_CTAV(a_TTY_BIND_TIMEOUT_MAX <= UI8_MAX);
409 /* We have a chicken-and-egg problem with `bind' and our termcap layer,
410 * because we may not initialize the latter automatically to allow users to
411 * specify *termcap-disable* and let it mean exactly that.
412 * On the other hand users can be expected to use `bind' in resources.
413 * Therefore bindings which involve termcap/terminfo sequences, and which
414 * are defined before n_PSO_STARTED signals usability of termcap/terminfo,
415 * will be (partially) delayed until tty_init() is called.
416 * And we preallocate space for the expansion of the resolved capability */
417 # define a_TTY_BIND_CAPNAME_MAX 15
418 # define a_TTY_BIND_CAPEXP_ROUNDUP 16
420 n_CTAV(n_ISPOW2(a_TTY_BIND_CAPEXP_ROUNDUP));
421 n_CTA(a_TTY_BIND_CAPEXP_ROUNDUP <= SI8_MAX / 2, "Variable must fit in 6-bit");
422 n_CTA(a_TTY_BIND_CAPEXP_ROUNDUP >= 8, "Variable too small");
423 # endif /* HAVE_KEY_BINDINGS */
425 # ifdef HAVE_HISTORY
426 /* The first line of the history file is used as a marker after >v14.9.6 */
427 # define a_TTY_HIST_MARKER "@s-mailx history v2"
428 # endif
430 /* The maximum size (of a_tty_cell's) in a line */
431 # define a_TTY_LINE_MAX SI32_MAX
433 /* (Some more CTAs around) */
434 n_CTA(a_TTY_LINE_MAX <= SI32_MAX,
435 "a_TTY_LINE_MAX larger than SI32_MAX, but the MLE uses 32-bit arithmetic");
437 /* When shall the visual screen be scrolled, in % of usable screen width */
438 # define a_TTY_SCROLL_MARGIN_LEFT 15
439 # define a_TTY_SCROLL_MARGIN_RIGHT 10
441 /* fexpand() flags for expand-on-tab */
442 # define a_TTY_TAB_FEXP_FL \
443 (FEXP_NOPROTO | FEXP_FULL | FEXP_SILENT | FEXP_MULTIOK)
445 /* Columns to ripoff: outermost may not be touched, plus position indicator.
446 * Must thus be at least 1, but should be >= 1+4 to dig the position indicator
447 * that we place (if there is sufficient space) */
448 # define a_TTY_WIDTH_RIPOFF 5
450 /* The implementation of the MLE functions always exists, and is based upon
451 * the a_TTY_BIND_FUN_* constants, so most of this enum is always necessary */
452 enum a_tty_bind_flags{
453 # ifdef HAVE_KEY_BINDINGS
454 a_TTY_BIND_RESOLVE = 1u<<8, /* Term cap. yet needs to be resolved */
455 a_TTY_BIND_DEFUNCT = 1u<<9, /* Unicode/term cap. used but not avail. */
456 a_TTY__BIND_MASK = a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT,
457 /* MLE fun assigned to a one-byte-sequence: this may be used for special
458 * key-sequence bypass processing */
459 a_TTY_BIND_MLE1CNTRL = 1u<<10,
460 a_TTY_BIND_NOCOMMIT = 1u<<11, /* Expansion shall be editable */
461 # endif
463 /* MLE internal commands */
464 a_TTY_BIND_FUN_INTERNAL = 1u<<15,
465 a_TTY__BIND_FUN_SHIFT = 16u,
466 a_TTY__BIND_FUN_SHIFTMAX = 24u,
467 a_TTY__BIND_FUN_MASK = ((1u << a_TTY__BIND_FUN_SHIFTMAX) - 1) &
468 ~((1u << a_TTY__BIND_FUN_SHIFT) - 1),
469 # define a_TTY_BIND_FUN_REDUCE(X) \
470 (((ui32_t)(X) & a_TTY__BIND_FUN_MASK) >> a_TTY__BIND_FUN_SHIFT)
471 # define a_TTY_BIND_FUN_EXPAND(X) \
472 (((ui32_t)(X) & (a_TTY__BIND_FUN_MASK >> a_TTY__BIND_FUN_SHIFT)) << \
473 a_TTY__BIND_FUN_SHIFT)
474 # undef a_X
475 # define a_X(N,I)\
476 a_TTY_BIND_FUN_ ## N = a_TTY_BIND_FUN_EXPAND(I),
478 a_X(BELL, 0)
479 a_X(GO_BWD, 1) a_X(GO_FWD, 2)
480 a_X(GO_WORD_BWD, 3) a_X(GO_WORD_FWD, 4)
481 a_X(GO_HOME, 5) a_X(GO_END, 6)
482 a_X(DEL_BWD, 7) a_X(DEL_FWD, 8)
483 a_X(SNARF_WORD_BWD, 9) a_X(SNARF_WORD_FWD, 10)
484 a_X(SNARF_END, 11) a_X(SNARF_LINE, 12)
485 a_X(HIST_BWD, 13) a_X(HIST_FWD, 14)
486 a_X(HIST_SRCH_BWD, 15) a_X(HIST_SRCH_FWD, 16)
487 a_X(REPAINT, 17)
488 a_X(QUOTE_RNDTRIP, 18)
489 a_X(PROMPT_CHAR, 19)
490 a_X(COMPLETE, 20)
491 a_X(PASTE, 21)
493 a_X(CANCEL, 22)
494 a_X(RESET, 23)
495 a_X(FULLRESET, 24)
496 a_X(COMMIT, 25) /* Must be last one! */
497 # undef a_X
499 a_TTY__BIND_LAST = 1<<25
501 # ifdef HAVE_KEY_BINDINGS
502 n_CTA((ui32_t)a_TTY_BIND_RESOLVE >= (ui32_t)n__GO_INPUT_CTX_MAX1,
503 "Bit carrier lower boundary must be raised to avoid value sharing");
504 # endif
505 n_CTA(a_TTY_BIND_FUN_EXPAND(a_TTY_BIND_FUN_COMMIT) <
506 (1 << a_TTY__BIND_FUN_SHIFTMAX),
507 "Bit carrier range must be expanded to represent necessary bits");
508 n_CTA(a_TTY__BIND_LAST >= (1u << a_TTY__BIND_FUN_SHIFTMAX),
509 "Bit carrier upper boundary must be raised to avoid value sharing");
510 n_CTA(UICMP(64, a_TTY__BIND_LAST, <=, SI32_MAX),
511 "Flag bits excess storage datatype" /* And we need one bit free */);
513 enum a_tty_fun_status{
514 a_TTY_FUN_STATUS_OK, /* Worked, next character */
515 a_TTY_FUN_STATUS_COMMIT, /* Line done */
516 a_TTY_FUN_STATUS_RESTART, /* Complete restart, reset multibyte etc. */
517 a_TTY_FUN_STATUS_END /* End, return EOF */
520 # ifdef HAVE_HISTORY
521 enum a_tty_hist_flags{
522 a_TTY_HIST_CTX_DEFAULT = n_GO_INPUT_CTX_DEFAULT,
523 a_TTY_HIST_CTX_COMPOSE = n_GO_INPUT_CTX_COMPOSE,
524 a_TTY_HIST_CTX_MASK = n__GO_INPUT_CTX_MASK,
525 /* Cannot use enum n_go_input_flags for the rest, need to stay in 8-bit */
526 a_TTY_HIST_GABBY = 1u<<7,
527 a_TTY_HIST__MAX = a_TTY_HIST_GABBY
529 n_CTA(a_TTY_HIST_CTX_MASK < a_TTY_HIST_GABBY, "Enumeration value overlap");
530 # endif
532 enum a_tty_visual_flags{
533 a_TTY_VF_NONE,
534 a_TTY_VF_MOD_CURSOR = 1u<<0, /* Cursor moved */
535 a_TTY_VF_MOD_CONTENT = 1u<<1, /* Content modified */
536 a_TTY_VF_MOD_DIRTY = 1u<<2, /* Needs complete repaint */
537 a_TTY_VF_MOD_SINGLE = 1u<<3, /* TODO Drop when indirection as above comes */
538 a_TTY_VF_REFRESH = a_TTY_VF_MOD_DIRTY | a_TTY_VF_MOD_CURSOR |
539 a_TTY_VF_MOD_CONTENT | a_TTY_VF_MOD_SINGLE,
540 a_TTY_VF_BELL = 1u<<8, /* Ring the bell */
541 a_TTY_VF_SYNC = 1u<<9, /* Flush/Sync I/O channel */
543 a_TTY_VF_ALL_MASK = a_TTY_VF_REFRESH | a_TTY_VF_BELL | a_TTY_VF_SYNC,
544 a_TTY__VF_LAST = a_TTY_VF_SYNC
547 # ifdef HAVE_KEY_BINDINGS
548 struct a_tty_bind_ctx{
549 struct a_tty_bind_ctx *tbc_next;
550 char *tbc_seq; /* quence as given (poss. re-quoted), in .tb__buf */
551 char *tbc_exp; /* ansion, in .tb__buf */
552 /* The .tbc_seq'uence with any terminal capabilities resolved; in fact an
553 * array of structures, the first entry of which is {si32_t buf_len_iscap;}
554 * where the signed bit indicates whether the buffer is a resolved terminal
555 * capability instead of a (possibly multibyte) character. In .tbc__buf */
556 char *tbc_cnv;
557 ui32_t tbc_seq_len;
558 ui32_t tbc_exp_len;
559 ui32_t tbc_cnv_len;
560 ui32_t tbc_flags;
561 char tbc__buf[n_VFIELD_SIZE(0)];
564 struct a_tty_bind_ctx_map{
565 enum n_go_input_flags tbcm_ctx;
566 char const tbcm_name[12]; /* Name of `bind' context */
568 # endif /* HAVE_KEY_BINDINGS */
570 struct a_tty_bind_builtin_tuple{
571 bool_t tbbt_iskey; /* Whether this is a control key; else termcap query */
572 char tbbt_ckey; /* Control code */
573 ui16_t tbbt_query; /* enum n_termcap_query (instead) */
574 char tbbt_exp[12]; /* String or [0]=NUL/[1]=BIND_FUN_REDUCE() */
576 n_CTA(n__TERMCAP_QUERY_MAX1 <= UI16_MAX,
577 "Enumeration cannot be stored in datatype");
579 # ifdef HAVE_KEY_BINDINGS
580 struct a_tty_bind_parse_ctx{
581 char const *tbpc_cmd; /* Command which parses */
582 char const *tbpc_in_seq; /* In: key sequence */
583 struct str tbpc_exp; /* In/Out: expansion (or NULL) */
584 struct a_tty_bind_ctx *tbpc_tbcp; /* Out: if yet existent */
585 struct a_tty_bind_ctx *tbpc_ltbcp; /* Out: the one before .tbpc_tbcp */
586 char *tbpc_seq; /* Out: normalized sequence */
587 char *tbpc_cnv; /* Out: sequence when read(2)ing it */
588 ui32_t tbpc_seq_len;
589 ui32_t tbpc_cnv_len;
590 ui32_t tbpc_cnv_align_mask; /* For creating a_tty_bind_ctx.tbc_cnv */
591 ui32_t tbpc_flags; /* n_go_input_flags | a_tty_bind_flags */
594 /* Input character tree */
595 struct a_tty_bind_tree{
596 struct a_tty_bind_tree *tbt_sibling; /* s at same level */
597 struct a_tty_bind_tree *tbt_childs; /* Sequence continues.. here */
598 struct a_tty_bind_tree *tbt_parent;
599 struct a_tty_bind_ctx *tbt_bind; /* NULL for intermediates */
600 wchar_t tbt_char; /* acter this level represents */
601 bool_t tbt_isseq; /* Belongs to multibyte sequence */
602 bool_t tbt_isseq_trail; /* ..is trailing byte of it */
603 ui8_t tbt__dummy[2];
605 # endif /* HAVE_KEY_BINDINGS */
607 struct a_tty_cell{
608 wchar_t tc_wc;
609 ui16_t tc_count; /* ..of bytes */
610 ui8_t tc_width; /* Visual width; TAB==UI8_MAX! */
611 bool_t tc_novis; /* Don't display visually as such (control character) */
612 char tc_cbuf[MB_LEN_MAX * 2]; /* .. plus reset shift sequence */
615 struct a_tty_global{
616 struct a_tty_line *tg_line; /* To be able to access it from signal hdl */
617 # ifdef HAVE_HISTORY
618 struct a_tty_hist *tg_hist;
619 struct a_tty_hist *tg_hist_tail;
620 size_t tg_hist_size;
621 size_t tg_hist_size_max;
622 # endif
623 # ifdef HAVE_KEY_BINDINGS
624 ui32_t tg_bind_cnt; /* Overall number of bindings */
625 bool_t tg_bind_isdirty;
626 bool_t tg_bind_isbuild;
627 # define a_TTY_SHCUT_MAX (3 +1) /* Note: update manual on change! */
628 ui8_t tg_bind__dummy[2];
629 char tg_bind_shcut_cancel[n__GO_INPUT_CTX_MAX1][a_TTY_SHCUT_MAX];
630 char tg_bind_shcut_prompt_char[n__GO_INPUT_CTX_MAX1][a_TTY_SHCUT_MAX];
631 struct a_tty_bind_ctx *tg_bind[n__GO_INPUT_CTX_MAX1];
632 struct a_tty_bind_tree *tg_bind_tree[n__GO_INPUT_CTX_MAX1][HSHSIZE];
633 # endif
634 struct termios tg_tios_old;
635 struct termios tg_tios_new;
637 # ifdef HAVE_KEY_BINDINGS
638 n_CTA(n__GO_INPUT_CTX_MAX1 == 3 && a_TTY_SHCUT_MAX == 4 &&
639 n_SIZEOF_FIELD(struct a_tty_global, tg_bind__dummy) == 2,
640 "Value results in array sizes that results in bad structure layout");
641 n_CTA(a_TTY_SHCUT_MAX > 1,
642 "Users need at least one shortcut, plus NUL terminator");
643 # endif
645 # ifdef HAVE_HISTORY
646 struct a_tty_hist{
647 struct a_tty_hist *th_older;
648 struct a_tty_hist *th_younger;
649 ui32_t th_len;
650 ui8_t th_flags; /* enum a_tty_hist_flags */
651 char th_dat[n_VFIELD_SIZE(3)];
653 n_CTA(UI8_MAX >= a_TTY_HIST__MAX, "Value exceeds datatype storage");
654 # endif
656 struct a_tty_line{
657 /* Caller pointers */
658 char **tl_x_buf;
659 size_t *tl_x_bufsize;
660 /* Input processing */
661 # ifdef HAVE_KEY_BINDINGS
662 wchar_t tl_bind_takeover; /* Leftover byte to consume next */
663 ui8_t tl_bind_timeout; /* In-seq. inter-byte-timer, in 1/10th secs */
664 ui8_t tl__bind_dummy[3];
665 char (*tl_bind_shcut_cancel)[a_TTY_SHCUT_MAX]; /* Special _CANCEL control */
666 char (*tl_bind_shcut_prompt_char)[a_TTY_SHCUT_MAX]; /* ..for _PROMPT_CHAR */
667 struct a_tty_bind_tree *(*tl_bind_tree_hmap)[HSHSIZE]; /* Bind lookup tree */
668 struct a_tty_bind_tree *tl_bind_tree;
669 # endif
670 /* Line data / content handling */
671 ui32_t tl_count; /* ..of a_tty_cell's (<= a_TTY_LINE_MAX) */
672 ui32_t tl_cursor; /* Current a_tty_cell insertion point */
673 union{
674 char *cbuf; /* *.tl_x_buf */
675 struct a_tty_cell *cells;
676 } tl_line;
677 struct str tl_defc; /* Current default content */
678 size_t tl_defc_cursor_byte; /* Desired position of cursor after takeover */
679 struct str tl_savec; /* Saved default content */
680 struct str tl_pastebuf; /* Last snarfed data */
681 # ifdef HAVE_HISTORY
682 struct a_tty_hist *tl_hist; /* History cursor */
683 # endif
684 ui32_t tl_count_max; /* ..before buffer needs to grow */
685 /* Visual data representation handling */
686 ui32_t tl_vi_flags; /* enum a_tty_visual_flags */
687 ui32_t tl_lst_count; /* .tl_count after last sync */
688 ui32_t tl_lst_cursor; /* .tl_cursor after last sync */
689 /* TODO Add another indirection layer by adding a tl_phy_line of
690 * TODO a_tty_cell objects, incorporate changes in visual layer,
691 * TODO then check what _really_ has changed, sync those changes only */
692 struct a_tty_cell const *tl_phy_start; /* First visible cell, left border */
693 ui32_t tl_phy_cursor; /* Physical cursor position */
694 bool_t tl_quote_rndtrip; /* For _kht() expansion */
695 ui8_t tl__dummy2[3 + 4];
696 ui32_t tl_goinflags; /* enum n_go_input_flags */
697 ui32_t tl_prompt_length; /* Preclassified (TODO needed as a_tty_cell) */
698 ui32_t tl_prompt_width;
699 char const *tl_prompt; /* Preformatted prompt (including colours) */
700 /* .tl_pos_buf is a hack */
701 # ifdef HAVE_COLOUR
702 char *tl_pos_buf; /* mle-position colour-on, [4], reset seq. */
703 char *tl_pos; /* Address of the [4] */
704 # endif
707 # ifdef HAVE_KEY_BINDINGS
708 /* C99: use [INDEX]={} */
709 n_CTAV(n_GO_INPUT_CTX_BASE == 0);
710 n_CTAV(n_GO_INPUT_CTX_DEFAULT == 1);
711 n_CTAV(n_GO_INPUT_CTX_COMPOSE == 2);
712 static struct a_tty_bind_ctx_map const
713 a_tty_bind_ctx_maps[n__GO_INPUT_CTX_MAX1] = {
714 {n_GO_INPUT_CTX_BASE, "base"},
715 {n_GO_INPUT_CTX_DEFAULT, "default"},
716 {n_GO_INPUT_CTX_COMPOSE, "compose"}
719 /* Special functions which our MLE provides internally.
720 * Update the manual upon change! */
721 static char const a_tty_bind_fun_names[][24] = {
722 # undef a_X
723 # define a_X(I,N) \
724 n_FIELD_INITI(a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## I)) "mle-" N "\0",
726 a_X(BELL, "bell")
727 a_X(GO_BWD, "go-bwd") a_X(GO_FWD, "go-fwd")
728 a_X(GO_WORD_BWD, "go-word-bwd") a_X(GO_WORD_FWD, "go-word-fwd")
729 a_X(GO_HOME, "go-home") a_X(GO_END, "go-end")
730 a_X(DEL_BWD, "del-bwd") a_X(DEL_FWD, "del-fwd")
731 a_X(SNARF_WORD_BWD, "snarf-word-bwd") a_X(SNARF_WORD_FWD, "snarf-word-fwd")
732 a_X(SNARF_END, "snarf-end") a_X(SNARF_LINE, "snarf-line")
733 a_X(HIST_BWD, "hist-bwd") a_X(HIST_FWD, "hist-fwd")
734 a_X(HIST_SRCH_BWD, "hist-srch-bwd") a_X(HIST_SRCH_FWD, "hist-srch-fwd")
735 a_X(REPAINT, "repaint")
736 a_X(QUOTE_RNDTRIP, "quote-rndtrip")
737 a_X(PROMPT_CHAR, "prompt-char")
738 a_X(COMPLETE, "complete")
739 a_X(PASTE, "paste")
741 a_X(CANCEL, "cancel")
742 a_X(RESET, "reset")
743 a_X(FULLRESET, "fullreset")
744 a_X(COMMIT, "commit")
746 # undef a_X
748 # endif /* HAVE_KEY_BINDINGS */
750 /* The default key bindings (unless disallowed). Update manual upon change!
751 * A logical subset of this table is also used if !HAVE_KEY_BINDINGS (more
752 * expensive than a switch() on control codes directly, but less redundant).
753 * The table for the "base" context */
754 static struct a_tty_bind_builtin_tuple const a_tty_bind_base_tuples[] = {
755 # undef a_X
756 # define a_X(K,S) \
757 {TRU1, K, 0, {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
759 a_X('A', GO_HOME)
760 a_X('B', GO_BWD)
761 /* C: SIGINT */
762 a_X('D', DEL_FWD)
763 a_X('E', GO_END)
764 a_X('F', GO_FWD)
765 a_X('G', RESET)
766 a_X('H', DEL_BWD)
767 a_X('I', COMPLETE)
768 a_X('J', COMMIT)
769 a_X('K', SNARF_END)
770 a_X('L', REPAINT)
771 /* M: same as J */
772 a_X('N', HIST_FWD)
773 /* O: below */
774 a_X('P', HIST_BWD)
775 a_X('Q', QUOTE_RNDTRIP)
776 a_X('R', HIST_SRCH_BWD)
777 a_X('S', HIST_SRCH_FWD)
778 a_X('T', PASTE)
779 a_X('U', SNARF_LINE)
780 a_X('V', PROMPT_CHAR)
781 a_X('W', SNARF_WORD_BWD)
782 a_X('X', GO_WORD_FWD)
783 a_X('Y', GO_WORD_BWD)
784 /* Z: SIGTSTP */
786 a_X('[', CANCEL)
787 /* \: below */
788 /* ]: below */
789 /* ^: below */
790 a_X('_', SNARF_WORD_FWD)
792 a_X('?', DEL_BWD)
794 # undef a_X
795 # define a_X(K,S) {TRU1, K, 0, {S}},
797 /* The remains only if we have `bind' functionality available */
798 # ifdef HAVE_KEY_BINDINGS
799 # undef a_X
800 # define a_X(Q,S) \
801 {FAL0, '\0', n_TERMCAP_QUERY_ ## Q,\
802 {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
804 a_X(key_backspace, DEL_BWD) a_X(key_dc, DEL_FWD)
805 a_X(key_eol, SNARF_END)
806 a_X(key_home, GO_HOME) a_X(key_end, GO_END)
807 a_X(key_left, GO_BWD) a_X(key_right, GO_FWD)
808 a_X(key_sleft, GO_HOME) a_X(key_sright, GO_END)
809 a_X(key_up, HIST_BWD) a_X(key_down, HIST_FWD)
810 # endif /* HAVE_KEY_BINDINGS */
813 /* The table for the "default" context */
814 static struct a_tty_bind_builtin_tuple const a_tty_bind_default_tuples[] = {
815 # undef a_X
816 # define a_X(K,S) \
817 {TRU1, K, 0, {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
819 # undef a_X
820 # define a_X(K,S) {TRU1, K, 0, {S}},
822 a_X('O', "dt")
824 a_X('\\', "z+")
825 a_X(']', "z$")
826 a_X('^', "z0")
828 /* The remains only if we have `bind' functionality available */
829 # ifdef HAVE_KEY_BINDINGS
830 # undef a_X
831 # define a_X(Q,S) {FAL0, '\0', n_TERMCAP_QUERY_ ## Q, {S}},
833 a_X(key_shome, "z0") a_X(key_send, "z$")
834 a_X(xkey_sup, "z0") a_X(xkey_sdown, "z$")
835 a_X(key_ppage, "z-") a_X(key_npage, "z+")
836 a_X(xkey_cup, "dotmove-") a_X(xkey_cdown, "dotmove+")
837 # endif /* HAVE_KEY_BINDINGS */
839 # undef a_X
841 static struct a_tty_global a_tty;
843 /* Change from canonical to raw, non-canonical mode, and way back */
844 static void a_tty_term_mode(bool_t raw);
846 # ifdef HAVE_HISTORY
847 /* Load and save the history file, respectively */
848 static bool_t a_tty_hist_load(void);
849 static bool_t a_tty_hist_save(void);
851 /* Initialize .tg_hist_size_max and return desired history file, or NULL */
852 static char const *a_tty_hist__query_config(void);
853 # endif
855 /* Adjust an active raw mode to use / not use a timeout */
856 # ifdef HAVE_KEY_BINDINGS
857 static void a_tty_term_rawmode_timeout(struct a_tty_line *tlp, bool_t enable);
858 # endif
860 /* 0-X (2), UI8_MAX == \t / HT */
861 static ui8_t a_tty_wcwidth(wchar_t wc);
863 /* Memory / cell / word generics */
864 static void a_tty_check_grow(struct a_tty_line *tlp, ui32_t no
865 n_MEMORY_DEBUG_ARGS);
866 static ssize_t a_tty_cell2dat(struct a_tty_line *tlp);
867 static void a_tty_cell2save(struct a_tty_line *tlp);
869 /* Save away data bytes of given range (max = non-inclusive) */
870 static void a_tty_copy2paste(struct a_tty_line *tlp, struct a_tty_cell *tcpmin,
871 struct a_tty_cell *tcpmax);
873 /* Ask user for hexadecimal number, interpret as UTF-32 */
874 static wchar_t a_tty_vinuni(struct a_tty_line *tlp);
876 /* Visual screen synchronization */
877 static bool_t a_tty_vi_refresh(struct a_tty_line *tlp);
879 static bool_t a_tty_vi__paint(struct a_tty_line *tlp);
881 /* Search for word boundary, starting at tl_cursor, in "dir"ection (<> 0).
882 * Return <0 when moving is impossible (backward direction but in position 0,
883 * forward direction but in outermost column), and relative distance to
884 * tl_cursor otherwise */
885 static si32_t a_tty_wboundary(struct a_tty_line *tlp, si32_t dir);
887 /* Most function implementations */
888 static void a_tty_khome(struct a_tty_line *tlp, bool_t dobell);
889 static void a_tty_kend(struct a_tty_line *tlp);
890 static void a_tty_kbs(struct a_tty_line *tlp);
891 static void a_tty_ksnarf(struct a_tty_line *tlp, bool_t cplline, bool_t dobell);
892 static si32_t a_tty_kdel(struct a_tty_line *tlp);
893 static void a_tty_kleft(struct a_tty_line *tlp);
894 static void a_tty_kright(struct a_tty_line *tlp);
895 static void a_tty_ksnarfw(struct a_tty_line *tlp, bool_t fwd);
896 static void a_tty_kgow(struct a_tty_line *tlp, si32_t dir);
897 static bool_t a_tty_kother(struct a_tty_line *tlp, wchar_t wc);
898 static ui32_t a_tty_kht(struct a_tty_line *tlp);
900 # ifdef HAVE_HISTORY
901 /* Return UI32_MAX on "exhaustion" */
902 static ui32_t a_tty_khist(struct a_tty_line *tlp, bool_t fwd);
903 static ui32_t a_tty_khist_search(struct a_tty_line *tlp, bool_t fwd);
905 static ui32_t a_tty__khist_shared(struct a_tty_line *tlp,
906 struct a_tty_hist *thp);
907 # endif
909 /* Handle a function */
910 static enum a_tty_fun_status a_tty_fun(struct a_tty_line *tlp,
911 enum a_tty_bind_flags tbf, size_t *len);
913 /* Readline core */
914 static ssize_t a_tty_readline(struct a_tty_line *tlp, size_t len,
915 bool_t *histok_or_null n_MEMORY_DEBUG_ARGS);
917 # ifdef HAVE_KEY_BINDINGS
918 /* Find context or -1 */
919 static enum n_go_input_flags a_tty_bind_ctx_find(char const *name);
921 /* Create (or replace, if allowed) a binding */
922 static bool_t a_tty_bind_create(struct a_tty_bind_parse_ctx *tbpcp,
923 bool_t replace);
925 /* Shared implementation to parse `bind' and `unbind' "key-sequence" and
926 * "expansion" command line arguments into something that we can work with */
927 static bool_t a_tty_bind_parse(bool_t isbindcmd,
928 struct a_tty_bind_parse_ctx *tbpcp);
930 /* Lazy resolve a termcap(5)/terminfo(5) (or *termcap*!) capability */
931 static void a_tty_bind_resolve(struct a_tty_bind_ctx *tbcp);
933 /* Delete an existing binding */
934 static void a_tty_bind_del(struct a_tty_bind_parse_ctx *tbpcp);
936 /* Life cycle of all input node trees */
937 static void a_tty_bind_tree_build(void);
938 static void a_tty_bind_tree_teardown(void);
940 static void a_tty__bind_tree_add(ui32_t hmap_idx,
941 struct a_tty_bind_tree *store[HSHSIZE],
942 struct a_tty_bind_ctx *tbcp);
943 static struct a_tty_bind_tree *a_tty__bind_tree_add_wc(
944 struct a_tty_bind_tree **treep, struct a_tty_bind_tree *parentp,
945 wchar_t wc, bool_t isseq);
946 static void a_tty__bind_tree_free(struct a_tty_bind_tree *tbtp);
947 # endif /* HAVE_KEY_BINDINGS */
949 static void
950 a_tty_signal(int sig){
951 /* Prototype at top */
952 sigset_t nset, oset;
953 NYD_X; /* Signal handler */
955 n_COLOUR( n_colour_env_gut(); ) /* TODO NO SIMPLE SUSPENSION POSSIBLE.. */
956 a_tty_term_mode(FAL0);
957 n_TERMCAP_SUSPEND(TRU1);
958 a_tty_sigs_down();
960 sigemptyset(&nset);
961 sigaddset(&nset, sig);
962 sigprocmask(SIG_UNBLOCK, &nset, &oset);
963 n_raise(sig);
964 /* When we come here we'll continue editing, so reestablish */
965 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
967 /* TODO THEREFORE NEED TO _GUT() .. _CREATE() ENTIRE ENVS!! */
968 n_COLOUR( n_colour_env_create(n_COLOUR_CTX_MLE, n_tty_fp, FAL0); )
969 a_tty_sigs_up();
970 n_TERMCAP_RESUME(TRU1);
971 a_tty_term_mode(TRU1);
972 a_tty.tg_line->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
975 static void
976 a_tty_term_mode(bool_t raw){
977 struct termios *tiosp;
978 NYD2_ENTER;
980 tiosp = &a_tty.tg_tios_old;
981 if(!raw)
982 goto jleave;
984 /* Always requery the attributes, in case we've been moved from background
985 * to foreground or however else in between sessions */
986 /* XXX Always enforce ECHO and ICANON in the OLD attributes - do so as long
987 * XXX as we don't properly deal with TTIN and TTOU etc. */
988 tcgetattr(STDIN_FILENO, tiosp); /* TODO v15: use _only_ n_tty_fp! */
989 tiosp->c_lflag |= ECHO | ICANON;
991 memcpy(&a_tty.tg_tios_new, tiosp, sizeof *tiosp);
992 tiosp = &a_tty.tg_tios_new;
993 tiosp->c_cc[VMIN] = 1;
994 tiosp->c_cc[VTIME] = 0;
995 /* Enable ^\, ^Q and ^S to be used for key bindings */
996 tiosp->c_cc[VQUIT] = tiosp->c_cc[VSTART] = tiosp->c_cc[VSTOP] = '\0';
997 tiosp->c_iflag &= ~(ISTRIP | IGNCR);
998 tiosp->c_lflag &= ~(ECHO /*| ECHOE | ECHONL */| ICANON | IEXTEN);
999 jleave:
1000 tcsetattr(STDIN_FILENO, TCSADRAIN, tiosp);
1001 NYD2_LEAVE;
1004 # ifdef HAVE_HISTORY
1005 static bool_t
1006 a_tty_hist_load(void){
1007 ui8_t version;
1008 size_t lsize, cnt, llen;
1009 char *lbuf, *cp;
1010 FILE *f;
1011 char const *v;
1012 bool_t rv;
1013 NYD_ENTER;
1015 rv = TRU1;
1017 if((v = a_tty_hist__query_config()) == NULL ||
1018 a_tty.tg_hist_size_max == 0)
1019 goto jleave;
1021 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
1022 f = fopen(v, "r"); /* TODO HISTFILE LOAD: use linebuf pool */
1023 if(f == NULL){
1024 int e;
1026 e = errno;
1027 n_err(_("Cannot read *history-file*=%s: %s\n"),
1028 n_shexp_quote_cp(v, FAL0), n_err_to_doc(e));
1029 rv = FAL0;
1030 goto jrele;
1032 (void)n_file_lock(fileno(f), FLT_READ, 0,0, UIZ_MAX);
1034 /* Clear old history */
1035 /* C99 */{
1036 struct a_tty_hist *thp;
1038 while((thp = a_tty.tg_hist) != NULL){
1039 a_tty.tg_hist = thp->th_older;
1040 n_free(thp);
1042 a_tty.tg_hist_tail = NULL;
1043 a_tty.tg_hist_size = 0;
1046 assert(!(n_pstate & n_PS_ROOT));
1047 n_pstate |= n_PS_ROOT; /* Allow calling addhist() */
1048 lbuf = NULL;
1049 lsize = 0;
1050 cnt = (size_t)fsize(f);
1051 version = 0;
1053 while(fgetline(&lbuf, &lsize, &cnt, &llen, f, FAL0) != NULL){
1054 cp = lbuf;
1055 /* Hand-edited history files may have this, probably */
1056 while(llen > 0 && spacechar(cp[0])){
1057 ++cp;
1058 --llen;
1060 if(llen > 0 && cp[llen - 1] == '\n')
1061 cp[--llen] = '\0';
1063 /* Skip empty and comment lines */
1064 if(llen == 0 || cp[0] == '#')
1065 continue;
1067 if(n_UNLIKELY(version == 0) &&
1068 (version = strcmp(cp, a_TTY_HIST_MARKER) ? 1 : 2) != 1)
1069 continue;
1071 /* C99 */{
1072 enum n_go_input_flags gif;
1074 if(version == 2){
1075 if(llen <= 2){
1076 /* XXX n_err(_("Skipped invalid *history-file* entry: %s\n"),
1077 * XXX n_shexp_quote_cp(cp));*/
1078 continue;
1080 switch(*cp++){
1081 default:
1082 case 'd':
1083 gif = n_GO_INPUT_CTX_DEFAULT; /* == a_TTY_HIST_CTX_DEFAULT */
1084 break;
1085 case 'c':
1086 gif = n_GO_INPUT_CTX_COMPOSE; /* == a_TTY_HIST_CTX_COMPOSE */
1087 break;
1090 if(*cp++ == '*')
1091 gif |= n_GO_INPUT_HIST_GABBY;
1093 while(*cp == ' ')
1094 ++cp;
1095 }else{
1096 gif = n_GO_INPUT_CTX_DEFAULT;
1097 if(cp[0] == '*'){
1098 ++cp;
1099 gif |= n_GO_INPUT_HIST_GABBY;
1103 n_tty_addhist(cp, gif);
1107 if(lbuf != NULL)
1108 n_free(lbuf);
1109 n_pstate &= ~n_PS_ROOT;
1111 fclose(f);
1112 jrele:
1113 rele_all_sigs(); /* XXX remove jumps */
1114 jleave:
1115 NYD_LEAVE;
1116 return rv;
1119 static bool_t
1120 a_tty_hist_save(void){
1121 size_t i;
1122 struct a_tty_hist *thp;
1123 FILE *f;
1124 char const *v;
1125 bool_t rv, dogabby;
1126 NYD_ENTER;
1128 rv = TRU1;
1130 if((v = a_tty_hist__query_config()) == NULL ||
1131 a_tty.tg_hist_size_max == 0)
1132 goto jleave;
1134 dogabby = ok_blook(history_gabby_persist);
1136 if((thp = a_tty.tg_hist) != NULL)
1137 for(i = a_tty.tg_hist_size_max; thp->th_older != NULL;
1138 thp = thp->th_older)
1139 if((dogabby || !(thp->th_flags & a_TTY_HIST_GABBY)) && --i == 0)
1140 break;
1142 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
1143 if((f = fopen(v, "w")) == NULL){ /* TODO temporary + rename?! */
1144 int e;
1146 e = errno;
1147 n_err(_("Cannot write *history-file*=%s: %s\n"),
1148 n_shexp_quote_cp(v, FAL0), n_err_to_doc(e));
1149 rv = FAL0;
1150 goto jrele;
1152 (void)n_file_lock(fileno(f), FLT_WRITE, 0,0, UIZ_MAX);
1154 if(fwrite(a_TTY_HIST_MARKER "\n", sizeof *a_TTY_HIST_MARKER,
1155 sizeof(a_TTY_HIST_MARKER "\n") -1, f) !=
1156 sizeof(a_TTY_HIST_MARKER "\n") -1)
1157 goto jioerr;
1158 else for(; thp != NULL; thp = thp->th_younger){
1159 if(dogabby || !(thp->th_flags & a_TTY_HIST_GABBY)){
1160 char c;
1162 switch(thp->th_flags & a_TTY_HIST_CTX_MASK){
1163 default:
1164 case a_TTY_HIST_CTX_DEFAULT:
1165 c = 'd';
1166 break;
1167 case a_TTY_HIST_CTX_COMPOSE:
1168 c = 'c';
1169 break;
1171 if(putc(c, f) == EOF)
1172 goto jioerr;
1174 if((thp->th_flags & a_TTY_HIST_GABBY) && putc('*', f) == EOF)
1175 goto jioerr;
1177 if(putc(' ', f) == EOF ||
1178 fwrite(thp->th_dat, sizeof *thp->th_dat, thp->th_len, f) !=
1179 sizeof(*thp->th_dat) * thp->th_len ||
1180 putc('\n', f) == EOF){
1181 jioerr:
1182 n_err(_("I/O error while writing *history-file* %s\n"),
1183 n_shexp_quote_cp(v, FAL0));
1184 rv = FAL0;
1185 break;
1190 fclose(f);
1191 jrele:
1192 rele_all_sigs(); /* XXX remove jumps */
1193 jleave:
1194 NYD_LEAVE;
1195 return rv;
1198 static char const *
1199 a_tty_hist__query_config(void){
1200 char const *rv, *cp;
1201 NYD2_ENTER;
1203 if((cp = ok_vlook(NAIL_HISTSIZE)) != NULL)
1204 n_OBSOLETE(_("please use *history-size* instead of *NAIL_HISTSIZE*"));
1205 if((rv = ok_vlook(history_size)) == NULL)
1206 rv = cp;
1207 if(rv == NULL)
1208 a_tty.tg_hist_size_max = UIZ_MAX;
1209 else
1210 (void)n_idec_uiz_cp(&a_tty.tg_hist_size_max, rv, 10, NULL);
1212 if((cp = ok_vlook(NAIL_HISTFILE)) != NULL)
1213 n_OBSOLETE(_("please use *history-file* instead of *NAIL_HISTFILE*"));
1214 if((rv = ok_vlook(history_file)) == NULL)
1215 rv = cp;
1216 if(rv != NULL)
1217 rv = fexpand(rv, FEXP_LOCAL | FEXP_NSHELL);
1218 NYD2_LEAVE;
1219 return rv;
1221 # endif /* HAVE_HISTORY */
1223 # ifdef HAVE_KEY_BINDINGS
1224 static void
1225 a_tty_term_rawmode_timeout(struct a_tty_line *tlp, bool_t enable){
1226 NYD2_ENTER;
1227 if(enable){
1228 ui8_t bt;
1230 a_tty.tg_tios_new.c_cc[VMIN] = 0;
1231 if((bt = tlp->tl_bind_timeout) == 0)
1232 bt = a_TTY_BIND_TIMEOUT;
1233 a_tty.tg_tios_new.c_cc[VTIME] = bt;
1234 }else{
1235 a_tty.tg_tios_new.c_cc[VMIN] = 1;
1236 a_tty.tg_tios_new.c_cc[VTIME] = 0;
1238 tcsetattr(STDIN_FILENO, TCSANOW, &a_tty.tg_tios_new);
1239 NYD2_LEAVE;
1241 # endif /* HAVE_KEY_BINDINGS */
1243 static ui8_t
1244 a_tty_wcwidth(wchar_t wc){
1245 ui8_t rv;
1246 NYD2_ENTER;
1248 /* Special case the reverse solidus at first */
1249 if(wc == '\t')
1250 rv = UI8_MAX;
1251 else{
1252 int i;
1254 # ifdef HAVE_WCWIDTH
1255 rv = ((i = wcwidth(wc)) > 0) ? (ui8_t)i : 0;
1256 # else
1257 rv = iswprint(wc) ? 1 + (wc >= 0x1100u) : 0; /* TODO use S-CText */
1258 # endif
1260 NYD2_LEAVE;
1261 return rv;
1264 static void
1265 a_tty_check_grow(struct a_tty_line *tlp, ui32_t no n_MEMORY_DEBUG_ARGS){
1266 ui32_t cmax;
1267 NYD2_ENTER;
1269 if(n_UNLIKELY((cmax = tlp->tl_count + no) > tlp->tl_count_max)){
1270 size_t i;
1272 i = cmax * sizeof(struct a_tty_cell) + 2 * sizeof(struct a_tty_cell);
1273 if(n_LIKELY(i >= *tlp->tl_x_bufsize)){
1274 hold_all_sigs(); /* XXX v15 drop */
1275 i <<= 1;
1276 tlp->tl_line.cbuf =
1277 *tlp->tl_x_buf = (n_realloc)(*tlp->tl_x_buf, i
1278 n_MEMORY_DEBUG_ARGSCALL);
1279 rele_all_sigs(); /* XXX v15 drop */
1281 tlp->tl_count_max = cmax;
1282 *tlp->tl_x_bufsize = i;
1284 NYD2_LEAVE;
1287 static ssize_t
1288 a_tty_cell2dat(struct a_tty_line *tlp){
1289 size_t len, i;
1290 NYD2_ENTER;
1292 len = 0;
1294 if(n_LIKELY((i = tlp->tl_count) > 0)){
1295 struct a_tty_cell const *tcap;
1297 tcap = tlp->tl_line.cells;
1299 memcpy(tlp->tl_line.cbuf + len, tcap->tc_cbuf, tcap->tc_count);
1300 len += tcap->tc_count;
1301 }while(++tcap, --i > 0);
1304 tlp->tl_line.cbuf[len] = '\0';
1305 NYD2_LEAVE;
1306 return (ssize_t)len;
1309 static void
1310 a_tty_cell2save(struct a_tty_line *tlp){
1311 size_t len, i;
1312 struct a_tty_cell *tcap;
1313 NYD2_ENTER;
1315 tlp->tl_savec.s = NULL;
1316 tlp->tl_savec.l = 0;
1318 if(n_UNLIKELY(tlp->tl_count == 0))
1319 goto jleave;
1321 for(tcap = tlp->tl_line.cells, len = 0, i = tlp->tl_count; i > 0;
1322 ++tcap, --i)
1323 len += tcap->tc_count;
1325 tlp->tl_savec.s = n_autorec_alloc((tlp->tl_savec.l = len) +1);
1327 for(tcap = tlp->tl_line.cells, len = 0, i = tlp->tl_count; i > 0;
1328 ++tcap, --i){
1329 memcpy(tlp->tl_savec.s + len, tcap->tc_cbuf, tcap->tc_count);
1330 len += tcap->tc_count;
1332 tlp->tl_savec.s[len] = '\0';
1333 jleave:
1334 NYD2_LEAVE;
1337 static void
1338 a_tty_copy2paste(struct a_tty_line *tlp, struct a_tty_cell *tcpmin,
1339 struct a_tty_cell *tcpmax){
1340 char *cp;
1341 struct a_tty_cell *tcp;
1342 size_t l;
1343 NYD2_ENTER;
1345 l = 0;
1346 for(tcp = tcpmin; tcp < tcpmax; ++tcp)
1347 l += tcp->tc_count;
1349 tlp->tl_pastebuf.s = cp = n_autorec_alloc((tlp->tl_pastebuf.l = l) +1);
1351 for(tcp = tcpmin; tcp < tcpmax; cp += l, ++tcp)
1352 memcpy(cp, tcp->tc_cbuf, l = tcp->tc_count);
1353 *cp = '\0';
1354 NYD2_LEAVE;
1357 static wchar_t
1358 a_tty_vinuni(struct a_tty_line *tlp){
1359 char buf[16];
1360 uiz_t i;
1361 wchar_t wc;
1362 NYD2_ENTER;
1364 wc = '\0';
1366 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr) ||
1367 !n_termcap_cmd(n_TERMCAP_CMD_ce, 0, -1))
1368 goto jleave;
1370 /* C99 */{
1371 struct str const *cpre, *csuf;
1373 cpre = csuf = NULL;
1374 #ifdef HAVE_COLOUR
1375 if(n_COLOUR_IS_ACTIVE()){
1376 struct n_colour_pen *cpen;
1378 cpen = n_colour_pen_create(n_COLOUR_ID_MLE_PROMPT, NULL);
1379 if((cpre = n_colour_pen_to_str(cpen)) != NULL)
1380 csuf = n_colour_reset_to_str();
1382 #endif
1383 fprintf(n_tty_fp, _("%sPlease enter Unicode code point:%s "),
1384 (cpre != NULL ? cpre->s : n_empty),
1385 (csuf != NULL ? csuf->s : n_empty));
1387 fflush(n_tty_fp);
1389 buf[sizeof(buf) -1] = '\0';
1390 for(i = 0;;){
1391 if(read(STDIN_FILENO, &buf[i], 1) != 1){
1392 if(n_err_no == n_ERR_INTR) /* xxx #if !SA_RESTART ? */
1393 continue;
1394 goto jleave;
1396 if(buf[i] == '\n')
1397 break;
1398 if(!hexchar(buf[i])){
1399 char const emsg[] = "[0-9a-fA-F]";
1401 n_LCTA(sizeof emsg <= sizeof(buf), "Preallocated buffer too small");
1402 memcpy(buf, emsg, sizeof emsg);
1403 goto jerr;
1406 putc(buf[i], n_tty_fp);
1407 fflush(n_tty_fp);
1408 if(++i == sizeof buf)
1409 goto jerr;
1411 buf[i] = '\0';
1413 if((n_idec_uiz_cp(&i, buf, 16, NULL
1414 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
1415 ) != n_IDEC_STATE_CONSUMED || i > 0x10FFFF/* XXX magic; CText */){
1416 jerr:
1417 n_err(_("\nInvalid input: %s\n"), buf);
1418 goto jleave;
1421 wc = (wchar_t)i;
1422 jleave:
1423 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY | (wc == '\0' ? a_TTY_VF_BELL : 0);
1424 NYD2_LEAVE;
1425 return wc;
1428 static bool_t
1429 a_tty_vi_refresh(struct a_tty_line *tlp){
1430 bool_t rv;
1431 NYD2_ENTER;
1433 if(tlp->tl_vi_flags & a_TTY_VF_BELL){
1434 tlp->tl_vi_flags |= a_TTY_VF_SYNC;
1435 if(putc('\a', n_tty_fp) == EOF)
1436 goto jerr;
1439 if(tlp->tl_vi_flags & a_TTY_VF_REFRESH){
1440 /* kht may want to restore a cursor position after inserting some
1441 * data somewhere */
1442 if(tlp->tl_defc_cursor_byte > 0){
1443 size_t i, j;
1444 ssize_t k;
1446 a_tty_khome(tlp, FAL0);
1448 i = tlp->tl_defc_cursor_byte;
1449 tlp->tl_defc_cursor_byte = 0;
1450 for(j = 0; tlp->tl_cursor < tlp->tl_count; ++j){
1451 a_tty_kright(tlp);
1452 if((k = tlp->tl_line.cells[j].tc_count) > i)
1453 break;
1454 i -= k;
1458 if(!a_tty_vi__paint(tlp))
1459 goto jerr;
1462 if(tlp->tl_vi_flags & a_TTY_VF_SYNC){
1463 tlp->tl_vi_flags &= ~a_TTY_VF_SYNC;
1464 if(fflush(n_tty_fp))
1465 goto jerr;
1468 rv = TRU1;
1469 jleave:
1470 tlp->tl_vi_flags &= ~a_TTY_VF_ALL_MASK;
1471 NYD2_LEAVE;
1472 return rv;
1474 jerr:
1475 clearerr(n_tty_fp); /* xxx I/O layer rewrite */
1476 n_err(_("Visual refresh failed! Is $TERM set correctly?\n"
1477 " Setting *line-editor-disable* to get us through!\n"));
1478 ok_bset(line_editor_disable);
1479 rv = FAL0;
1480 goto jleave;
1483 static bool_t
1484 a_tty_vi__paint(struct a_tty_line *tlp){
1485 enum{
1486 a_TRUE_RV = a_TTY__VF_LAST<<1, /* Return value bit */
1487 a_HAVE_PROMPT = a_TTY__VF_LAST<<2, /* Have a prompt */
1488 a_SHOW_PROMPT = a_TTY__VF_LAST<<3, /* Shall print the prompt */
1489 a_MOVE_CURSOR = a_TTY__VF_LAST<<4, /* Move visual cursor for user! */
1490 a_LEFT_MIN = a_TTY__VF_LAST<<5, /* On left boundary */
1491 a_RIGHT_MAX = a_TTY__VF_LAST<<6,
1492 a_HAVE_POSITION = a_TTY__VF_LAST<<7, /* Print the position indicator */
1494 /* We carry some flags over invocations (not worth a specific field) */
1495 a_VISIBLE_PROMPT = a_TTY__VF_LAST<<8, /* The prompt is on the screen */
1496 a_PERSIST_MASK = a_VISIBLE_PROMPT,
1497 a__LAST = a_PERSIST_MASK
1500 ui32_t f, w, phy_wid_base, phy_wid, phy_base, phy_cur, cnt,
1501 DBG(lstcur COMMA) cur,
1502 vi_left, /*vi_right,*/ phy_nxtcur;
1503 struct a_tty_cell const *tccp, *tcp_left, *tcp_right, *tcxp;
1504 NYD2_ENTER;
1505 n_LCTA(UICMP(64, a__LAST, <, UI32_MAX), "Flag bits excess storage datatype");
1507 f = tlp->tl_vi_flags;
1508 tlp->tl_vi_flags = (f & ~(a_TTY_VF_REFRESH | a_PERSIST_MASK)) |
1509 a_TTY_VF_SYNC;
1510 f |= a_TRUE_RV;
1511 if((w = tlp->tl_prompt_width) > 0)
1512 f |= a_HAVE_PROMPT;
1513 f |= a_HAVE_POSITION;
1515 /* XXX We don't have a OnTerminalResize event (see main.c) yet, so we need
1516 * XXX to reevaluate our circumstances over and over again */
1517 /* Don't display prompt or position indicator on very small screens */
1518 if((phy_wid_base = (ui32_t)n_scrnwidth) <= a_TTY_WIDTH_RIPOFF)
1519 f &= ~(a_HAVE_PROMPT | a_HAVE_POSITION);
1520 else{
1521 phy_wid_base -= a_TTY_WIDTH_RIPOFF;
1523 /* Disable the prompt if the screen is too small; due to lack of some
1524 * indicator simply add a second ripoff */
1525 if((f & a_HAVE_PROMPT) && w + a_TTY_WIDTH_RIPOFF >= phy_wid_base)
1526 f &= ~a_HAVE_PROMPT;
1529 phy_wid = phy_wid_base;
1530 phy_base = 0;
1531 phy_cur = tlp->tl_phy_cursor;
1532 cnt = tlp->tl_count;
1533 DBG( lstcur = tlp->tl_lst_cursor; )
1535 /* XXX Assume dirty screen if shrunk */
1536 if(cnt < tlp->tl_lst_count)
1537 f |= a_TTY_VF_MOD_DIRTY;
1539 /* TODO Without HAVE_TERMCAP, it would likely be much cheaper to simply
1540 * TODO always "cr + paint + ce + ch", since ce is simulated via spaces.. */
1542 /* Quickshot: if the line is empty, possibly print prompt and out */
1543 if(cnt == 0){
1544 /* In that special case dirty anything if it seems better */
1545 if((f & a_TTY_VF_MOD_CONTENT) || tlp->tl_lst_count > 0)
1546 f |= a_TTY_VF_MOD_DIRTY;
1548 if((f & a_TTY_VF_MOD_DIRTY) && phy_cur != 0){
1549 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
1550 goto jerr;
1551 phy_cur = 0;
1554 if((f & (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)) ==
1555 (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)){
1556 if(fputs(tlp->tl_prompt, n_tty_fp) == EOF)
1557 goto jerr;
1558 phy_cur = tlp->tl_prompt_width + 1;
1561 /* May need to clear former line content */
1562 if((f & a_TTY_VF_MOD_DIRTY) &&
1563 !n_termcap_cmd(n_TERMCAP_CMD_ce, phy_cur, -1))
1564 goto jerr;
1566 tlp->tl_phy_start = tlp->tl_line.cells;
1567 goto jleave;
1570 /* Try to get an idea of the visual window */
1572 /* Find the left visual boundary */
1573 phy_wid = (phy_wid >> 1) + (phy_wid >> 2);
1574 if((cur = tlp->tl_cursor) == cnt)
1575 --cur;
1577 w = (tcp_left = tccp = tlp->tl_line.cells + cur)->tc_width;
1578 if(w == UI8_MAX) /* TODO yet HT == SPACE */
1579 w = 1;
1580 while(tcp_left > tlp->tl_line.cells){
1581 ui16_t cw = tcp_left[-1].tc_width;
1583 if(cw == UI8_MAX) /* TODO yet HT == SPACE */
1584 cw = 1;
1585 if(w + cw >= phy_wid)
1586 break;
1587 w += cw;
1588 --tcp_left;
1590 vi_left = w;
1592 /* If the left hand side of our visual viewpoint consumes less than half
1593 * of the screen width, show the prompt */
1594 if(tcp_left == tlp->tl_line.cells)
1595 f |= a_LEFT_MIN;
1597 if((f & (a_LEFT_MIN | a_HAVE_PROMPT)) == (a_LEFT_MIN | a_HAVE_PROMPT) &&
1598 w + tlp->tl_prompt_width < phy_wid){
1599 phy_base = tlp->tl_prompt_width;
1600 f |= a_SHOW_PROMPT;
1603 /* Then search for right boundary. We always leave the rightmost column
1604 * empty because some terminals [cw]ould wrap the line if we write into
1605 * that. XXX terminfo(5)/termcap(5) have the semi_auto_right_margin/sam/YE
1606 * XXX capability to indicate this, but we don't look at that */
1607 phy_wid = phy_wid_base - phy_base;
1608 tcp_right = tlp->tl_line.cells + cnt;
1610 while(&tccp[1] < tcp_right){
1611 ui16_t cw = tccp[1].tc_width;
1612 ui32_t i;
1614 if(cw == UI8_MAX) /* TODO yet HT == SPACE */
1615 cw = 1;
1616 i = w + cw;
1617 if(i > phy_wid)
1618 break;
1619 w = i;
1620 ++tccp;
1622 /*vi_right = w - vi_left;*/
1624 /* If the complete line including prompt fits on the screen, show prompt */
1625 if(--tcp_right == tccp){
1626 f |= a_RIGHT_MAX;
1628 /* Since we did brute-force walk also for the left boundary we may end up
1629 * in a situation were anything effectively fits on the screen, including
1630 * the prompt that is, but were we don't recognize this since we
1631 * restricted the search to fit in some visual viewpoint. Therefore try
1632 * again to extend the left boundary to overcome that */
1633 if(!(f & a_LEFT_MIN)){
1634 struct a_tty_cell const *tc1p = tlp->tl_line.cells;
1635 ui32_t vil1 = vi_left;
1637 assert(!(f & a_SHOW_PROMPT));
1638 w += tlp->tl_prompt_width;
1639 for(tcxp = tcp_left;;){
1640 ui32_t i = tcxp[-1].tc_width;
1642 if(i == UI8_MAX) /* TODO yet HT == SPACE */
1643 i = 1;
1644 vil1 += i;
1645 i += w;
1646 if(i > phy_wid)
1647 break;
1648 w = i;
1649 if(--tcxp == tc1p){
1650 tcp_left = tc1p;
1651 /*vi_left = vil1;*/
1652 f |= a_LEFT_MIN;
1653 break;
1656 /*w -= tlp->tl_prompt_width;*/
1659 tcp_right = tccp;
1660 tccp = tlp->tl_line.cells + cur;
1662 if((f & (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT | a_SHOW_PROMPT)) ==
1663 (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT) &&
1664 w + tlp->tl_prompt_width <= phy_wid){
1665 phy_wid -= (phy_base = tlp->tl_prompt_width);
1666 f |= a_SHOW_PROMPT;
1669 /* Try to avoid repainting the complete line - this is possible if the
1670 * cursor "did not leave the screen" and the prompt status hasn't changed.
1671 * I.e., after clamping virtual viewpoint, compare relation to physical */
1672 if((f & (a_TTY_VF_MOD_SINGLE/*FIXME*/ |
1673 a_TTY_VF_MOD_CONTENT/* xxx */ | a_TTY_VF_MOD_DIRTY)) ||
1674 (tcxp = tlp->tl_phy_start) == NULL ||
1675 tcxp > tccp || tcxp <= tcp_right)
1676 f |= a_TTY_VF_MOD_DIRTY;
1677 else{
1678 f |= a_TTY_VF_MOD_DIRTY;
1679 #if 0
1680 struct a_tty_cell const *tcyp;
1681 si32_t cur_displace;
1682 ui32_t phy_lmargin, phy_rmargin, fx, phy_displace;
1684 phy_lmargin = (fx = phy_wid) / 100;
1685 phy_rmargin = fx - (phy_lmargin * a_TTY_SCROLL_MARGIN_RIGHT);
1686 phy_lmargin *= a_TTY_SCROLL_MARGIN_LEFT;
1687 fx = (f & (a_SHOW_PROMPT | a_VISIBLE_PROMPT));
1689 if(fx == 0 || fx == (a_SHOW_PROMPT | a_VISIBLE_PROMPT)){
1691 #endif
1693 goto jpaint;
1695 /* We know what we have to paint, start synchronizing */
1696 jpaint:
1697 assert(phy_cur == tlp->tl_phy_cursor);
1698 assert(phy_wid == phy_wid_base - phy_base);
1699 assert(cnt == tlp->tl_count);
1700 assert(cnt > 0);
1701 assert(lstcur == tlp->tl_lst_cursor);
1702 assert(tccp == tlp->tl_line.cells + cur);
1704 phy_nxtcur = phy_base; /* FIXME only if repaint cpl. */
1706 /* Quickshot: is it only cursor movement within the visible screen? */
1707 if((f & a_TTY_VF_REFRESH) == a_TTY_VF_MOD_CURSOR){
1708 f |= a_MOVE_CURSOR;
1709 goto jcursor;
1712 /* To be able to apply some quick jump offs, clear line if possible */
1713 if(f & a_TTY_VF_MOD_DIRTY){
1714 /* Force complete clearance and cursor reinitialization */
1715 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr) ||
1716 !n_termcap_cmd(n_TERMCAP_CMD_ce, 0, -1))
1717 goto jerr;
1718 tlp->tl_phy_start = tcp_left;
1719 phy_cur = 0;
1722 if((f & (a_TTY_VF_MOD_DIRTY | a_SHOW_PROMPT)) && phy_cur != 0){
1723 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
1724 goto jerr;
1725 phy_cur = 0;
1728 if(f & a_SHOW_PROMPT){
1729 assert(phy_base == tlp->tl_prompt_width);
1730 if(fputs(tlp->tl_prompt, n_tty_fp) == EOF)
1731 goto jerr;
1732 phy_cur = phy_nxtcur;
1733 f |= a_VISIBLE_PROMPT;
1734 }else
1735 f &= ~a_VISIBLE_PROMPT;
1737 /* FIXME reposition cursor for paint */
1738 for(w = phy_nxtcur; tcp_left <= tcp_right; ++tcp_left){
1739 ui16_t cw;
1741 cw = tcp_left->tc_width;
1743 if(n_LIKELY(!tcp_left->tc_novis)){
1744 if(fwrite(tcp_left->tc_cbuf, sizeof *tcp_left->tc_cbuf,
1745 tcp_left->tc_count, n_tty_fp) != tcp_left->tc_count)
1746 goto jerr;
1747 }else{ /* XXX Shouldn't be here <-> CText, ui_str.c */
1748 char wbuf[8]; /* XXX magic */
1750 if(n_psonce & n_PSO_UNICODE){
1751 ui32_t wc;
1753 wc = (ui32_t)tcp_left->tc_wc;
1754 if((wc & ~0x1Fu) == 0)
1755 wc |= 0x2400;
1756 else if(wc == 0x7F)
1757 wc = 0x2421;
1758 else
1759 wc = 0x2426;
1760 n_utf32_to_utf8(wc, wbuf);
1761 }else
1762 wbuf[0] = '?', wbuf[1] = '\0';
1764 if(fputs(wbuf, n_tty_fp) == EOF)
1765 goto jerr;
1766 cw = 1;
1769 if(cw == UI8_MAX) /* TODO yet HT == SPACE */
1770 cw = 1;
1771 w += cw;
1772 if(tcp_left == tccp)
1773 phy_nxtcur = w;
1774 phy_cur += cw;
1777 /* Write something position marker alike if it does not fit on screen */
1778 if((f & a_HAVE_POSITION) &&
1779 ((f & (a_LEFT_MIN | a_RIGHT_MAX)) != (a_LEFT_MIN | a_RIGHT_MAX) ||
1780 ((f & a_HAVE_PROMPT) && !(f & a_SHOW_PROMPT)))){
1781 # ifdef HAVE_COLOUR
1782 char *posbuf = tlp->tl_pos_buf, *pos = tlp->tl_pos;
1783 # else
1784 char posbuf[5], *pos = posbuf;
1786 pos[4] = '\0';
1787 # endif
1789 if(phy_cur != (w = phy_wid_base) &&
1790 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = w, 0))
1791 goto jerr;
1793 *pos++ = '|';
1794 if((f & a_LEFT_MIN) && (!(f & a_HAVE_PROMPT) || (f & a_SHOW_PROMPT)))
1795 memcpy(pos, "^.+", 3);
1796 else if(f & a_RIGHT_MAX)
1797 memcpy(pos, ".+$", 3);
1798 else{
1799 /* Theoretical line length limit a_TTY_LINE_MAX, choose next power of
1800 * ten (10 ** 10) to represent 100 percent, since we don't have a macro
1801 * that generates a constant, and i don't trust the standard "u type
1802 * suffix automatically scales" calculate the large number */
1803 static char const itoa[] = "0123456789";
1805 ui64_t const fact100 = (ui64_t)0x3B9ACA00u * 10u, fact = fact100 / 100;
1806 ui32_t i = (ui32_t)(((fact100 / cnt) * tlp->tl_cursor) / fact);
1807 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1809 if(i < 10)
1810 pos[0] = ' ', pos[1] = itoa[i];
1811 else
1812 pos[1] = itoa[i % 10], pos[0] = itoa[i / 10];
1813 pos[2] = '%';
1816 if(fputs(posbuf, n_tty_fp) == EOF)
1817 goto jerr;
1818 phy_cur += 4;
1821 /* Users are used to see the cursor right of the point of interest, so we
1822 * need some further adjustments unless in special conditions. Be aware
1823 * that we may have adjusted cur at the beginning, too */
1824 if((cur = tlp->tl_cursor) == 0)
1825 phy_nxtcur = phy_base;
1826 else if(cur != cnt){
1827 ui16_t cw = tccp->tc_width;
1829 if(cw == UI8_MAX) /* TODO yet HT == SPACE */
1830 cw = 1;
1831 phy_nxtcur -= cw;
1834 jcursor:
1835 if(((f & a_MOVE_CURSOR) || phy_nxtcur != phy_cur) &&
1836 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = phy_nxtcur, 0))
1837 goto jerr;
1839 jleave:
1840 tlp->tl_vi_flags |= (f & a_PERSIST_MASK);
1841 tlp->tl_lst_count = tlp->tl_count;
1842 tlp->tl_lst_cursor = tlp->tl_cursor;
1843 tlp->tl_phy_cursor = phy_cur;
1845 NYD2_LEAVE;
1846 return ((f & a_TRUE_RV) != 0);
1847 jerr:
1848 f &= ~a_TRUE_RV;
1849 goto jleave;
1852 static si32_t
1853 a_tty_wboundary(struct a_tty_line *tlp, si32_t dir){/* TODO shell token-wise */
1854 bool_t anynon;
1855 struct a_tty_cell *tcap;
1856 ui32_t cur, cnt;
1857 si32_t rv;
1858 NYD2_ENTER;
1860 assert(dir == 1 || dir == -1);
1862 rv = -1;
1863 cnt = tlp->tl_count;
1864 cur = tlp->tl_cursor;
1866 if(dir < 0){
1867 if(cur == 0)
1868 goto jleave;
1869 }else if(cur + 1 >= cnt)
1870 goto jleave;
1871 else
1872 --cnt, --cur; /* xxx Unsigned wrapping may occur (twice), then */
1874 for(rv = 0, tcap = tlp->tl_line.cells, anynon = FAL0;;){
1875 wchar_t wc;
1877 wc = tcap[cur += (ui32_t)dir].tc_wc;
1878 if(/*TODO not everywhere iswblank(wc)*/ wc == L' ' || wc == L'\t' ||
1879 iswpunct(wc)){
1880 if(anynon)
1881 break;
1882 }else
1883 anynon = TRU1;
1885 ++rv;
1887 if(dir < 0){
1888 if(cur == 0)
1889 break;
1890 }else if(cur + 1 >= cnt){
1891 ++rv;
1892 break;
1895 jleave:
1896 NYD2_LEAVE;
1897 return rv;
1900 static void
1901 a_tty_khome(struct a_tty_line *tlp, bool_t dobell){
1902 ui32_t f;
1903 NYD2_ENTER;
1905 if(n_LIKELY(tlp->tl_cursor > 0)){
1906 tlp->tl_cursor = 0;
1907 f = a_TTY_VF_MOD_CURSOR;
1908 }else if(dobell)
1909 f = a_TTY_VF_BELL;
1910 else
1911 f = a_TTY_VF_NONE;
1913 tlp->tl_vi_flags |= f;
1914 NYD2_LEAVE;
1917 static void
1918 a_tty_kend(struct a_tty_line *tlp){
1919 ui32_t f;
1920 NYD2_ENTER;
1922 if(n_LIKELY(tlp->tl_cursor < tlp->tl_count)){
1923 tlp->tl_cursor = tlp->tl_count;
1924 f = a_TTY_VF_MOD_CURSOR;
1925 }else
1926 f = a_TTY_VF_BELL;
1928 tlp->tl_vi_flags |= f;
1929 NYD2_LEAVE;
1932 static void
1933 a_tty_kbs(struct a_tty_line *tlp){
1934 ui32_t f, cur, cnt;
1935 NYD2_ENTER;
1937 cur = tlp->tl_cursor;
1938 cnt = tlp->tl_count;
1940 if(n_LIKELY(cur > 0)){
1941 tlp->tl_cursor = --cur;
1942 tlp->tl_count = --cnt;
1944 if((cnt -= cur) > 0){
1945 struct a_tty_cell *tcap;
1947 tcap = tlp->tl_line.cells + cur;
1948 memmove(tcap, &tcap[1], cnt *= sizeof(*tcap));
1950 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
1951 }else
1952 f = a_TTY_VF_BELL;
1954 tlp->tl_vi_flags |= f;
1955 NYD2_LEAVE;
1958 static void
1959 a_tty_ksnarf(struct a_tty_line *tlp, bool_t cplline, bool_t dobell){
1960 ui32_t i, f;
1961 NYD2_ENTER;
1963 f = a_TTY_VF_NONE;
1964 i = tlp->tl_cursor;
1966 if(cplline && i > 0){
1967 tlp->tl_cursor = i = 0;
1968 f = a_TTY_VF_MOD_CURSOR;
1971 if(n_LIKELY(i < tlp->tl_count)){
1972 struct a_tty_cell *tcap;
1974 tcap = &tlp->tl_line.cells[0];
1975 a_tty_copy2paste(tlp, &tcap[i], &tcap[tlp->tl_count]);
1976 tlp->tl_count = i;
1977 f = a_TTY_VF_MOD_CONTENT;
1978 }else if(dobell)
1979 f |= a_TTY_VF_BELL;
1981 tlp->tl_vi_flags |= f;
1982 NYD2_LEAVE;
1985 static si32_t
1986 a_tty_kdel(struct a_tty_line *tlp){
1987 ui32_t cur, cnt, f;
1988 si32_t i;
1989 NYD2_ENTER;
1991 cur = tlp->tl_cursor;
1992 cnt = tlp->tl_count;
1993 i = (si32_t)(cnt - cur);
1995 if(n_LIKELY(i > 0)){
1996 tlp->tl_count = --cnt;
1998 if(n_LIKELY(--i > 0)){
1999 struct a_tty_cell *tcap;
2001 tcap = &tlp->tl_line.cells[cur];
2002 memmove(tcap, &tcap[1], (ui32_t)i * sizeof(*tcap));
2004 f = a_TTY_VF_MOD_CONTENT;
2005 }else if(cnt == 0 && !ok_blook(ignoreeof)){
2006 putc('^', n_tty_fp);
2007 putc('D', n_tty_fp);
2008 i = -1;
2009 f = a_TTY_VF_NONE;
2010 }else{
2011 i = 0;
2012 f = a_TTY_VF_BELL;
2015 tlp->tl_vi_flags |= f;
2016 NYD2_LEAVE;
2017 return i;
2020 static void
2021 a_tty_kleft(struct a_tty_line *tlp){
2022 ui32_t f;
2023 NYD2_ENTER;
2025 if(n_LIKELY(tlp->tl_cursor > 0)){
2026 --tlp->tl_cursor;
2027 f = a_TTY_VF_MOD_CURSOR;
2028 }else
2029 f = a_TTY_VF_BELL;
2031 tlp->tl_vi_flags |= f;
2032 NYD2_LEAVE;
2035 static void
2036 a_tty_kright(struct a_tty_line *tlp){
2037 ui32_t i;
2038 NYD2_ENTER;
2040 if(n_LIKELY((i = tlp->tl_cursor + 1) <= tlp->tl_count)){
2041 tlp->tl_cursor = i;
2042 i = a_TTY_VF_MOD_CURSOR;
2043 }else
2044 i = a_TTY_VF_BELL;
2046 tlp->tl_vi_flags |= i;
2047 NYD2_LEAVE;
2050 static void
2051 a_tty_ksnarfw(struct a_tty_line *tlp, bool_t fwd){
2052 struct a_tty_cell *tcap;
2053 ui32_t cnt, cur, f;
2054 si32_t i;
2055 NYD2_ENTER;
2057 if(n_UNLIKELY((i = a_tty_wboundary(tlp, (fwd ? +1 : -1))) <= 0)){
2058 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
2059 goto jleave;
2062 cnt = tlp->tl_count - (ui32_t)i;
2063 cur = tlp->tl_cursor;
2064 if(!fwd)
2065 cur -= (ui32_t)i;
2066 tcap = &tlp->tl_line.cells[cur];
2068 a_tty_copy2paste(tlp, &tcap[0], &tcap[i]);
2070 if((tlp->tl_count = cnt) != (tlp->tl_cursor = cur)){
2071 cnt -= cur;
2072 memmove(&tcap[0], &tcap[i], cnt * sizeof(*tcap)); /* FIXME*/
2075 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
2076 jleave:
2077 tlp->tl_vi_flags |= f;
2078 NYD2_LEAVE;
2081 static void
2082 a_tty_kgow(struct a_tty_line *tlp, si32_t dir){
2083 ui32_t f;
2084 si32_t i;
2085 NYD2_ENTER;
2087 if(n_UNLIKELY((i = a_tty_wboundary(tlp, dir)) <= 0))
2088 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
2089 else{
2090 if(dir < 0)
2091 i = -i;
2092 tlp->tl_cursor += (ui32_t)i;
2093 f = a_TTY_VF_MOD_CURSOR;
2096 tlp->tl_vi_flags |= f;
2097 NYD2_LEAVE;
2100 static bool_t
2101 a_tty_kother(struct a_tty_line *tlp, wchar_t wc){
2102 /* Append if at EOL, insert otherwise;
2103 * since we may move around character-wise, always use a fresh ps */
2104 mbstate_t ps;
2105 struct a_tty_cell tc, *tcap;
2106 ui32_t f, cur, cnt;
2107 bool_t rv;
2108 NYD2_ENTER;
2110 rv = FAL0;
2111 f = a_TTY_VF_NONE;
2113 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
2114 if(tlp->tl_count + 1 >= a_TTY_LINE_MAX){
2115 n_err(_("Stop here, we can't extend line beyond size limit\n"));
2116 goto jleave;
2119 /* First init a cell and see whether we'll really handle this wc */
2120 memset(&ps, 0, sizeof ps);
2121 /* C99 */{
2122 size_t l;
2124 l = wcrtomb(tc.tc_cbuf, tc.tc_wc = wc, &ps);
2125 if(n_UNLIKELY(l > MB_LEN_MAX)){
2126 jemb:
2127 n_err(_("wcrtomb(3) error: too many multibyte character bytes\n"));
2128 goto jleave;
2130 tc.tc_count = (ui16_t)l;
2132 if(n_UNLIKELY((n_psonce & n_PSO_ENC_MBSTATE) != 0)){
2133 l = wcrtomb(&tc.tc_cbuf[l], L'\0', &ps);
2134 if(n_LIKELY(l == 1))
2135 /* Only NUL terminator */;
2136 else if(n_LIKELY(--l < MB_LEN_MAX))
2137 tc.tc_count += (ui16_t)l;
2138 else
2139 goto jemb;
2143 /* Yes, we will! Place it in the array */
2144 tc.tc_novis = (iswprint(wc) == 0);
2145 tc.tc_width = a_tty_wcwidth(wc);
2146 /* TODO if(tc.tc_novis && tc.tc_width > 0) */
2148 cur = tlp->tl_cursor++;
2149 cnt = tlp->tl_count++ - cur;
2150 tcap = &tlp->tl_line.cells[cur];
2151 if(cnt >= 1){
2152 memmove(&tcap[1], tcap, cnt * sizeof(*tcap));
2153 f = a_TTY_VF_MOD_CONTENT;
2154 }else
2155 f = a_TTY_VF_MOD_SINGLE;
2156 memcpy(tcap, &tc, sizeof *tcap);
2158 f |= a_TTY_VF_MOD_CURSOR;
2159 rv = TRU1;
2160 jleave:
2161 if(!rv)
2162 f |= a_TTY_VF_BELL;
2163 tlp->tl_vi_flags |= f;
2164 NYD2_LEAVE;
2165 return rv;
2168 static ui32_t
2169 a_tty_kht(struct a_tty_line *tlp){
2170 ui8_t (*mempool)[n_MEMORY_POOL_TYPE_SIZEOF], *mempool_persist;
2171 struct stat sb;
2172 struct str orig, bot, topp, sub, exp, preexp;
2173 struct n_string shou, *shoup;
2174 struct a_tty_cell *ctop, *cx;
2175 bool_t wedid, set_savec;
2176 ui32_t rv, f;
2177 NYD2_ENTER;
2179 /* Get plain line data; if this is the first expansion/xy, update the
2180 * very original content so that ^G gets the origin back */
2181 orig = tlp->tl_savec;
2182 a_tty_cell2save(tlp);
2183 exp = tlp->tl_savec;
2184 if(orig.s != NULL){
2185 /*tlp->tl_savec = orig;*/
2186 set_savec = FAL0;
2187 }else
2188 set_savec = TRU1;
2189 orig = exp;
2191 mempool_persist = n_go_data->gdc_mempool;
2192 n_memory_pool_push(mempool = n_lofi_alloc(sizeof *mempool));
2194 shoup = n_string_creat_auto(&shou);
2195 f = a_TTY_VF_NONE;
2197 /* C99 */{
2198 size_t max;
2199 struct a_tty_cell *cword;
2201 /* Find the word to be expanded */
2202 cword = tlp->tl_line.cells;
2203 ctop = &cword[tlp->tl_cursor];
2204 cx = &cword[tlp->tl_count];
2206 /* topp: separate data right of cursor */
2207 if(cx > ctop){
2208 for(rv = 0; ctop < cx; ++ctop)
2209 rv += ctop->tc_count;
2210 topp.l = rv;
2211 topp.s = orig.s + orig.l - rv;
2212 ctop = cword + tlp->tl_cursor;
2213 }else
2214 topp.s = NULL, topp.l = 0;
2216 /* Find the shell token that corresponds to the cursor position */
2217 max = 0;
2218 if(ctop > cword){
2219 for(; cword < ctop; ++cword)
2220 max += cword->tc_count;
2222 bot = sub = orig;
2223 bot.l = 0;
2224 sub.l = max;
2226 if(max > 0){
2227 for(;;){
2228 enum n_shexp_state shs;
2230 exp = sub;
2231 shs = n_shexp_parse_token((n_SHEXP_PARSE_DRYRUN |
2232 n_SHEXP_PARSE_TRIM_SPACE | n_SHEXP_PARSE_IGNORE_EMPTY |
2233 n_SHEXP_PARSE_QUOTE_AUTO_CLOSE), NULL, &sub, NULL);
2234 if(sub.l != 0){
2235 size_t x;
2237 assert(max >= sub.l);
2238 x = max - sub.l;
2239 bot.l += x;
2240 max -= x;
2241 continue;
2243 if(shs & n_SHEXP_STATE_ERR_MASK){
2244 n_err(_("Invalid completion pattern: %.*s\n"),
2245 (int)exp.l, exp.s);
2246 f |= a_TTY_VF_BELL;
2247 goto jnope;
2250 /* All WS? Trailing WS that has been "jumped over"? */
2251 if(exp.l == 0 || (shs & n_SHEXP_STATE_WS_TRAIL))
2252 break;
2254 n_shexp_parse_token((n_SHEXP_PARSE_TRIM_SPACE |
2255 n_SHEXP_PARSE_IGNORE_EMPTY | n_SHEXP_PARSE_QUOTE_AUTO_CLOSE),
2256 shoup, &exp, NULL);
2257 break;
2260 sub.s = n_string_cp(shoup);
2261 sub.l = shoup->s_len;
2265 /* Leave room for "implicit asterisk" expansion, as below */
2266 if(sub.l == 0){
2267 sub.s = n_UNCONST(n_star);
2268 sub.l = sizeof(n_star) -1;
2271 preexp.s = n_UNCONST(n_empty);
2272 preexp.l = sizeof(n_empty) -1;
2273 wedid = FAL0;
2274 jredo:
2275 /* TODO Super-Heavy-Metal: block all sigs, avoid leaks on jump */
2276 hold_all_sigs();
2277 exp.s = fexpand(sub.s, a_TTY_TAB_FEXP_FL);
2278 rele_all_sigs();
2280 if(exp.s == NULL || (exp.l = strlen(exp.s)) == 0){
2281 if(wedid < FAL0)
2282 goto jnope;
2283 /* No. But maybe the users' desire was to complete only a part of the
2284 * shell token of interest! TODO This can be improved, we would need to
2285 * TODO have shexp_parse to create a DOM structure of parsed snippets, so
2286 * TODO that we can tell for each snippet which quote is active and
2287 * TODO whether we may cross its boundary and/or apply expansion for it!
2288 * TODO Only like that we would be able to properly requote user input
2289 * TODO like "'['a-z]<TAB>" to e.g. "\[a-z]" for glob purposes! */
2290 if(wedid == TRU1){
2291 size_t i, li;
2293 wedid = TRUM1;
2294 for(li = UIZ_MAX, i = sub.l; i-- > 0;){
2295 char c;
2297 if((c = sub.s[i]) == '/' || c == '+' /* *folder*! */)
2298 li = i;
2299 /* Do stop once some "magic" characters are seen XXX magic set */
2300 else if(c == '<' || c == '>' || c == '=' || c == ':')
2301 break;
2303 if(li != UIZ_MAX){
2304 preexp = sub;
2305 preexp.l = li;
2306 sub.l -= li;
2307 sub.s += li;
2308 goto jredo;
2312 /* A different case is that the user input includes for example character
2313 * classes: here fexpand() will go over glob, and that will not find any
2314 * match, thus returning NULL; try to wildcard expand this pattern! */
2315 jaster_check:
2316 if(sub.s[sub.l - 1] != '*'){
2317 wedid = TRU1;
2318 shoup = n_string_push_c(shoup, '*');
2319 sub.s = n_string_cp(shoup);
2320 sub.l = shoup->s_len;
2321 goto jredo;
2323 goto jnope;
2326 if(wedid == TRUM1 && preexp.l > 0)
2327 preexp.s = savestrbuf(preexp.s, preexp.l);
2329 /* May be multi-return! */
2330 if(n_pstate & n_PS_EXPAND_MULTIRESULT)
2331 goto jmulti;
2333 /* xxx That is not really true since the limit counts characters not bytes */
2334 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
2335 if(exp.l >= a_TTY_LINE_MAX - 1 || a_TTY_LINE_MAX - 1 - exp.l < preexp.l){
2336 n_err(_("Tabulator expansion would extend beyond line size limit\n"));
2337 f |= a_TTY_VF_BELL;
2338 goto jnope;
2341 /* If the expansion equals the original string, assume the user wants what
2342 * is usually known as tab completion, append `*' and restart */
2343 if(!wedid && exp.l == sub.l && !memcmp(exp.s, sub.s, exp.l))
2344 goto jaster_check;
2346 if(exp.s[exp.l - 1] != '/'){
2347 if(!stat(exp.s, &sb) && S_ISDIR(sb.st_mode)){
2348 shoup = n_string_assign_buf(shoup, exp.s, exp.l);
2349 shoup = n_string_push_c(shoup, '/');
2350 exp.s = n_string_cp(shoup);
2351 goto jset;
2354 exp.s[exp.l] = '\0';
2356 jset:
2357 exp.l = strlen(exp.s = n_shexp_quote_cp(exp.s, tlp->tl_quote_rndtrip));
2358 tlp->tl_defc_cursor_byte = bot.l + preexp.l + exp.l -1;
2360 orig.l = bot.l + preexp.l + exp.l + topp.l;
2361 orig.s = n_autorec_alloc_from_pool(mempool_persist, orig.l + 5 +1);
2362 if((rv = (ui32_t)bot.l) > 0)
2363 memcpy(orig.s, bot.s, rv);
2364 if(preexp.l > 0){
2365 memcpy(&orig.s[rv], preexp.s, preexp.l);
2366 rv += preexp.l;
2368 memcpy(&orig.s[rv], exp.s, exp.l);
2369 rv += exp.l;
2370 if(topp.l > 0){
2371 memcpy(&orig.s[rv], topp.s, topp.l);
2372 rv += topp.l;
2374 orig.s[rv] = '\0';
2376 tlp->tl_defc = orig;
2377 tlp->tl_count = tlp->tl_cursor = 0;
2378 f |= a_TTY_VF_MOD_DIRTY;
2379 jleave:
2380 n_memory_pool_pop(mempool);
2381 n_lofi_free(mempool);
2382 tlp->tl_vi_flags |= f;
2383 NYD2_LEAVE;
2384 return rv;
2386 jmulti:{
2387 struct n_visual_info_ctx vic;
2388 struct str input;
2389 wc_t c2, c1;
2390 bool_t isfirst;
2391 char const *lococp;
2392 size_t locolen, scrwid, lnlen, lncnt, prefixlen;
2393 FILE *fp;
2395 if((fp = Ftmp(NULL, "tabex", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
2396 n_perr(_("tmpfile"), 0);
2397 fp = n_tty_fp;
2400 /* How long is the result string for real? Search the NUL NUL
2401 * terminator. While here, detect the longest entry to perform an
2402 * initial allocation of our accumulator string */
2403 locolen = preexp.l;
2405 size_t i;
2407 i = strlen(&exp.s[++exp.l]);
2408 locolen = n_MAX(locolen, i);
2409 exp.l += i;
2410 }while(exp.s[exp.l + 1] != '\0');
2412 shoup = n_string_reserve(n_string_trunc(shoup, 0),
2413 locolen + (locolen >> 1));
2415 /* Iterate (once again) over all results */
2416 scrwid = n_SCRNWIDTH_FOR_LISTS;
2417 lnlen = lncnt = 0;
2418 n_UNINIT(prefixlen, 0);
2419 n_UNINIT(lococp, NULL);
2420 n_UNINIT(c1, '\0');
2421 for(isfirst = TRU1; exp.l > 0; isfirst = FAL0, c1 = c2){
2422 size_t i;
2423 char const *fullpath;
2425 /* Next result */
2426 sub = exp;
2427 sub.l = i = strlen(sub.s);
2428 assert(exp.l >= i);
2429 if((exp.l -= i) > 0)
2430 --exp.l;
2431 exp.s += ++i;
2433 /* Separate dirname and basename */
2434 fullpath = sub.s;
2435 if(isfirst){
2436 char const *cp;
2438 if((cp = strrchr(fullpath, '/')) != NULL)
2439 prefixlen = PTR2SIZE(++cp - fullpath);
2440 else
2441 prefixlen = 0;
2443 if(prefixlen > 0 && prefixlen < sub.l){
2444 sub.l -= prefixlen;
2445 sub.s += prefixlen;
2448 /* We want case-insensitive sort-order */
2449 memset(&vic, 0, sizeof vic);
2450 vic.vic_indat = sub.s;
2451 vic.vic_inlen = sub.l;
2452 c2 = n_visual_info(&vic, n_VISUAL_INFO_ONE_CHAR) ? vic.vic_waccu
2453 : (ui8_t)*sub.s;
2454 #ifdef HAVE_C90AMEND1
2455 c2 = towlower(c2);
2456 #else
2457 c2 = lowerconv(c2);
2458 #endif
2460 /* Query longest common prefix along the way */
2461 if(isfirst){
2462 c1 = c2;
2463 lococp = sub.s;
2464 locolen = sub.l;
2465 }else if(locolen > 0){
2466 for(i = 0; i < locolen; ++i)
2467 if(lococp[i] != sub.s[i]){
2468 i = field_detect_clip(i, lococp, i);
2469 locolen = i;
2470 break;
2474 /* Prepare display */
2475 input = sub;
2476 shoup = n_shexp_quote(n_string_trunc(shoup, 0), &input,
2477 tlp->tl_quote_rndtrip);
2478 memset(&vic, 0, sizeof vic);
2479 vic.vic_indat = shoup->s_dat;
2480 vic.vic_inlen = shoup->s_len;
2481 if(!n_visual_info(&vic,
2482 n_VISUAL_INFO_SKIP_ERRORS | n_VISUAL_INFO_WIDTH_QUERY))
2483 vic.vic_vi_width = shoup->s_len;
2485 /* Put on screen. Indent follow lines of same sort slot.
2486 * Leave enough room for filename tagging */
2487 if((c1 = (c1 != c2))){
2488 #ifdef HAVE_C90AMEND1
2489 c1 = (iswalnum(c2) != 0);
2490 #else
2491 c1 = (alnumchar(c2) != 0);
2492 #endif
2494 if(isfirst || c1 ||
2495 scrwid < lnlen || scrwid - lnlen <= vic.vic_vi_width + 2){
2496 putc('\n', fp);
2497 if(scrwid < lnlen)
2498 ++lncnt;
2499 ++lncnt, lnlen = 0;
2500 if(!isfirst && !c1)
2501 goto jsep;
2502 }else if(lnlen > 0){
2503 jsep:
2504 fputs(" ", fp);
2505 lnlen += 2;
2507 fputs(n_string_cp(shoup), fp);
2508 lnlen += vic.vic_vi_width;
2510 /* Support the known filename tagging
2511 * XXX *line-editor-completion-filetype* or so */
2512 if(!lstat(fullpath, &sb)){
2513 char c = '\0';
2515 if(S_ISDIR(sb.st_mode))
2516 c = '/';
2517 else if(S_ISLNK(sb.st_mode))
2518 c = '@';
2519 # ifdef S_ISFIFO
2520 else if(S_ISFIFO(sb.st_mode))
2521 c = '|';
2522 # endif
2523 # ifdef S_ISSOCK
2524 else if(S_ISSOCK(sb.st_mode))
2525 c = '=';
2526 # endif
2527 # ifdef S_ISCHR
2528 else if(S_ISCHR(sb.st_mode))
2529 c = '%';
2530 # endif
2531 # ifdef S_ISBLK
2532 else if(S_ISBLK(sb.st_mode))
2533 c = '#';
2534 # endif
2536 if(c != '\0'){
2537 putc(c, fp);
2538 ++lnlen;
2542 putc('\n', fp);
2543 ++lncnt;
2545 page_or_print(fp, lncnt);
2546 if(fp != n_tty_fp)
2547 Fclose(fp);
2549 n_string_gut(shoup);
2551 /* A common prefix of 0 means we cannot provide the user any auto
2552 * completed characters for the multiple possible results.
2553 * Otherwise we can, so extend the visual line content by the common
2554 * prefix (in a reversible way) */
2555 f |= a_TTY_VF_BELL; /* XXX -> *line-editor-completion-bell*? or so */
2556 if(locolen > 0){
2557 (exp.s = n_UNCONST(lococp))[locolen] = '\0';
2558 exp.s -= prefixlen;
2559 exp.l = (locolen += prefixlen);
2560 goto jset;
2564 jnope:
2565 /* If we've provided a default content, but failed to expand, there is
2566 * nothing we can "revert to": drop that default again */
2567 if(set_savec){
2568 tlp->tl_savec.s = NULL;
2569 tlp->tl_savec.l = 0;
2571 f &= a_TTY_VF_BELL; /* XXX -> *line-editor-completion-bell*? or so */
2572 rv = 0;
2573 goto jleave;
2576 # ifdef HAVE_HISTORY
2577 static ui32_t
2578 a_tty__khist_shared(struct a_tty_line *tlp, struct a_tty_hist *thp){
2579 ui32_t f, rv;
2580 NYD2_ENTER;
2582 if(n_LIKELY((tlp->tl_hist = thp) != NULL)){
2583 char *cp;
2584 size_t i;
2586 i = thp->th_len;
2587 if(tlp->tl_goinflags & n_GO_INPUT_CTX_COMPOSE){
2588 ++i;
2589 if(!(thp->th_flags & a_TTY_HIST_CTX_COMPOSE))
2590 ++i;
2592 tlp->tl_defc.s = cp = n_autorec_alloc(i +1);
2593 if(tlp->tl_goinflags & n_GO_INPUT_CTX_COMPOSE){
2594 if((*cp = ok_vlook(escape)[0]) == '\0')
2595 *cp = n_ESCAPE[0];
2596 ++cp;
2597 if(!(thp->th_flags & a_TTY_HIST_CTX_COMPOSE))
2598 *cp++ = ':';
2600 memcpy(cp, thp->th_dat, thp->th_len +1);
2601 rv = tlp->tl_defc.l = i;
2603 f = (tlp->tl_count > 0) ? a_TTY_VF_MOD_DIRTY : a_TTY_VF_NONE;
2604 tlp->tl_count = tlp->tl_cursor = 0;
2605 }else{
2606 f = a_TTY_VF_BELL;
2607 rv = UI32_MAX;
2610 tlp->tl_vi_flags |= f;
2611 NYD2_LEAVE;
2612 return rv;
2615 static ui32_t
2616 a_tty_khist(struct a_tty_line *tlp, bool_t fwd){
2617 struct a_tty_hist *thp;
2618 ui32_t rv;
2619 NYD2_ENTER;
2621 /* If we're not in history mode yet, save line content */
2622 if((thp = tlp->tl_hist) == NULL){
2623 a_tty_cell2save(tlp);
2624 if((thp = a_tty.tg_hist) == NULL)
2625 goto jleave;
2626 if(fwd)
2627 while(thp->th_older != NULL)
2628 thp = thp->th_older;
2629 goto jleave;
2632 while((thp = fwd ? thp->th_younger : thp->th_older) != NULL){
2633 /* Applicable to input context? Compose mode swallows anything */
2634 if((tlp->tl_goinflags & n__GO_INPUT_CTX_MASK) == n_GO_INPUT_CTX_COMPOSE)
2635 break;
2636 if((thp->th_flags & a_TTY_HIST_CTX_MASK) != a_TTY_HIST_CTX_COMPOSE)
2637 break;
2639 jleave:
2640 rv = a_tty__khist_shared(tlp, thp);
2641 NYD2_LEAVE;
2642 return rv;
2645 static ui32_t
2646 a_tty_khist_search(struct a_tty_line *tlp, bool_t fwd){
2647 struct str orig_savec;
2648 ui32_t xoff, rv;
2649 struct a_tty_hist *thp;
2650 NYD2_ENTER;
2652 thp = NULL;
2654 /* We cannot complete an empty line */
2655 if(n_UNLIKELY(tlp->tl_count == 0)){
2656 /* XXX The upcoming hard reset would restore a set savec buffer,
2657 * XXX so forcefully reset that. A cleaner solution would be to
2658 * XXX reset it whenever a restore is no longer desired */
2659 tlp->tl_savec.s = NULL;
2660 tlp->tl_savec.l = 0;
2661 goto jleave;
2664 /* xxx It is a bit of a hack, but let's just hard-code the knowledge that
2665 * xxx in compose mode the first character is *escape* and must be skipped
2666 * xxx when searching the history. Alternatively we would need to have
2667 * xxx context-specific history search hooks which would do the search,
2668 * xxx which is overkill for our sole special case compose mode */
2669 if((tlp->tl_goinflags & n__GO_INPUT_CTX_MASK) == n_GO_INPUT_CTX_COMPOSE)
2670 xoff = 1;
2671 else
2672 xoff = 0;
2674 if((thp = tlp->tl_hist) == NULL){
2675 a_tty_cell2save(tlp);
2676 if((thp = a_tty.tg_hist) == NULL) /* TODO Should end "doing nothing"! */
2677 goto jleave;
2678 if(fwd)
2679 while(thp->th_older != NULL)
2680 thp = thp->th_older;
2681 orig_savec.s = NULL;
2682 orig_savec.l = 0; /* silence CC */
2683 }else{
2684 while((thp = fwd ? thp->th_younger : thp->th_older) != NULL){
2685 /* Applicable to input context? Compose mode swallows anything */
2686 if(xoff != 0)
2687 break;
2688 if((thp->th_flags & a_TTY_HIST_CTX_MASK) != a_TTY_HIST_CTX_COMPOSE)
2689 break;
2691 if(thp == NULL)
2692 goto jleave;
2694 orig_savec = tlp->tl_savec;
2697 if(xoff >= tlp->tl_savec.l){
2698 thp = NULL;
2699 goto jleave;
2702 if(orig_savec.s == NULL)
2703 a_tty_cell2save(tlp);
2705 for(; thp != NULL; thp = fwd ? thp->th_younger : thp->th_older){
2706 /* Applicable to input context? Compose mode swallows anything */
2707 if(xoff != 1 && (thp->th_flags & a_TTY_HIST_CTX_MASK) ==
2708 a_TTY_HIST_CTX_COMPOSE)
2709 continue;
2710 if(is_prefix(&tlp->tl_savec.s[xoff], thp->th_dat))
2711 break;
2714 if(orig_savec.s != NULL)
2715 tlp->tl_savec = orig_savec;
2716 jleave:
2717 rv = a_tty__khist_shared(tlp, thp);
2718 NYD2_LEAVE;
2719 return rv;
2721 # endif /* HAVE_HISTORY */
2723 static enum a_tty_fun_status
2724 a_tty_fun(struct a_tty_line *tlp, enum a_tty_bind_flags tbf, size_t *len){
2725 enum a_tty_fun_status rv;
2726 NYD2_ENTER;
2728 rv = a_TTY_FUN_STATUS_OK;
2729 # undef a_X
2730 # define a_X(N) a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## N)
2731 switch(a_TTY_BIND_FUN_REDUCE(tbf)){
2732 case a_X(BELL):
2733 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2734 break;
2735 case a_X(GO_BWD):
2736 a_tty_kleft(tlp);
2737 break;
2738 case a_X(GO_FWD):
2739 a_tty_kright(tlp);
2740 break;
2741 case a_X(GO_WORD_BWD):
2742 a_tty_kgow(tlp, -1);
2743 break;
2744 case a_X(GO_WORD_FWD):
2745 a_tty_kgow(tlp, +1);
2746 break;
2747 case a_X(GO_HOME):
2748 a_tty_khome(tlp, TRU1);
2749 break;
2750 case a_X(GO_END):
2751 a_tty_kend(tlp);
2752 break;
2753 case a_X(DEL_BWD):
2754 a_tty_kbs(tlp);
2755 break;
2756 case a_X(DEL_FWD):
2757 if(a_tty_kdel(tlp) < 0)
2758 rv = a_TTY_FUN_STATUS_END;
2759 break;
2760 case a_X(SNARF_WORD_BWD):
2761 a_tty_ksnarfw(tlp, FAL0);
2762 break;
2763 case a_X(SNARF_WORD_FWD):
2764 a_tty_ksnarfw(tlp, TRU1);
2765 break;
2766 case a_X(SNARF_END):
2767 a_tty_ksnarf(tlp, FAL0, TRU1);
2768 break;
2769 case a_X(SNARF_LINE):
2770 a_tty_ksnarf(tlp, TRU1, (tlp->tl_count == 0));
2771 break;
2773 case a_X(HIST_FWD):{
2774 # ifdef HAVE_HISTORY
2775 bool_t isfwd = TRU1;
2777 if(0){
2778 # endif
2779 /* FALLTHRU */
2780 case a_X(HIST_BWD):
2781 # ifdef HAVE_HISTORY
2782 isfwd = FAL0;
2784 if((*len = a_tty_khist(tlp, isfwd)) != UI32_MAX){
2785 rv = a_TTY_FUN_STATUS_RESTART;
2786 break;
2788 goto jreset;
2789 # endif
2791 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2792 break;
2794 case a_X(HIST_SRCH_FWD):{
2795 # ifdef HAVE_HISTORY
2796 bool_t isfwd = TRU1;
2798 if(0){
2799 # endif
2800 /* FALLTHRU */
2801 case a_X(HIST_SRCH_BWD):
2802 # ifdef HAVE_HISTORY
2803 isfwd = FAL0;
2805 if((*len = a_tty_khist_search(tlp, isfwd)) != UI32_MAX){
2806 rv = a_TTY_FUN_STATUS_RESTART;
2807 break;
2809 goto jreset;
2810 # else
2811 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2812 # endif
2813 }break;
2815 case a_X(REPAINT):
2816 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2817 break;
2818 case a_X(QUOTE_RNDTRIP):
2819 tlp->tl_quote_rndtrip = !tlp->tl_quote_rndtrip;
2820 break;
2821 case a_X(PROMPT_CHAR):{
2822 wchar_t wc;
2824 if((wc = a_tty_vinuni(tlp)) > 0)
2825 a_tty_kother(tlp, wc);
2826 }break;
2827 case a_X(COMPLETE):
2828 if((*len = a_tty_kht(tlp)) > 0)
2829 rv = a_TTY_FUN_STATUS_RESTART;
2830 break;
2832 case a_X(PASTE):
2833 if(tlp->tl_pastebuf.l > 0)
2834 *len = (tlp->tl_defc = tlp->tl_pastebuf).l;
2835 else
2836 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2837 break;
2840 case a_X(CANCEL):
2841 /* Normally this just causes a restart and thus resets the state
2842 * machine */
2843 if(tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2845 # ifdef HAVE_KEY_BINDINGS
2846 tlp->tl_bind_takeover = '\0';
2847 # endif
2848 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2849 rv = a_TTY_FUN_STATUS_RESTART;
2850 break;
2852 case a_X(RESET):
2853 if(tlp->tl_count == 0 && tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2854 # ifdef HAVE_KEY_BINDINGS
2855 tlp->tl_bind_takeover = '\0';
2856 # endif
2857 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY | a_TTY_VF_BELL;
2858 break;
2859 }else if(0){
2860 case a_X(FULLRESET):
2861 tlp->tl_savec.s = tlp->tl_defc.s = NULL;
2862 tlp->tl_savec.l = tlp->tl_defc.l = 0;
2863 tlp->tl_defc_cursor_byte = 0;
2864 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2866 jreset:
2867 # ifdef HAVE_KEY_BINDINGS
2868 tlp->tl_bind_takeover = '\0';
2869 # endif
2870 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2871 tlp->tl_cursor = tlp->tl_count = 0;
2872 # ifdef HAVE_HISTORY
2873 tlp->tl_hist = NULL;
2874 # endif
2875 if((*len = tlp->tl_savec.l) != 0){
2876 tlp->tl_defc = tlp->tl_savec;
2877 tlp->tl_savec.s = NULL;
2878 tlp->tl_savec.l = 0;
2879 }else
2880 *len = tlp->tl_defc.l;
2881 rv = a_TTY_FUN_STATUS_RESTART;
2882 break;
2884 default:
2885 case a_X(COMMIT):
2886 rv = a_TTY_FUN_STATUS_COMMIT;
2887 break;
2889 # undef a_X
2891 NYD2_LEAVE;
2892 return rv;
2895 static ssize_t
2896 a_tty_readline(struct a_tty_line *tlp, size_t len, bool_t *histok_or_null
2897 n_MEMORY_DEBUG_ARGS){
2898 /* We want to save code, yet we may have to incorporate a lines'
2899 * default content and / or default input to switch back to after some
2900 * history movement; let "len > 0" mean "have to display some data
2901 * buffer" -> a_BUFMODE, and only otherwise read(2) it */
2902 mbstate_t ps[2];
2903 char cbuf_base[MB_LEN_MAX * 2], *cbuf, *cbufp;
2904 ssize_t rv;
2905 struct a_tty_bind_tree *tbtp;
2906 wchar_t wc;
2907 enum a_tty_bind_flags tbf;
2908 enum {a_NONE, a_WAS_HERE = 1<<0, a_BUFMODE = 1<<1, a_MAYBEFUN = 1<<2,
2909 a_TIMEOUT = 1<<3, a_TIMEOUT_EXPIRED = 1<<4,
2910 a_TIMEOUT_MASK = a_TIMEOUT | a_TIMEOUT_EXPIRED,
2911 a_READ_LOOP_MASK = ~(a_WAS_HERE | a_MAYBEFUN | a_TIMEOUT_MASK)
2912 } flags;
2913 NYD_ENTER;
2915 n_UNINIT(rv, 0);
2916 # ifdef HAVE_KEY_BINDINGS
2917 assert(tlp->tl_bind_takeover == '\0');
2918 # endif
2919 jrestart:
2920 memset(ps, 0, sizeof ps);
2921 flags = a_NONE;
2922 tlp->tl_vi_flags |= a_TTY_VF_REFRESH | a_TTY_VF_SYNC;
2924 jinput_loop:
2925 for(;;){
2926 if(len != 0)
2927 flags |= a_BUFMODE;
2929 /* Ensure we have valid pointers, and room for grow */
2930 a_tty_check_grow(tlp, ((flags & a_BUFMODE) ? (ui32_t)len : 1)
2931 n_MEMORY_DEBUG_ARGSCALL);
2933 /* Handle visual state flags, except in buffer mode */
2934 if(!(flags & a_BUFMODE) && (tlp->tl_vi_flags & a_TTY_VF_ALL_MASK))
2935 if(!a_tty_vi_refresh(tlp)){
2936 rv = -1;
2937 goto jleave;
2940 /* Ready for messing around.
2941 * Normal read(2)? Else buffer mode: speed this one up */
2942 if(!(flags & a_BUFMODE)){
2943 cbufp =
2944 cbuf = cbuf_base;
2945 }else{
2946 assert(tlp->tl_defc.l > 0 && tlp->tl_defc.s != NULL);
2947 assert(tlp->tl_defc.l >= len);
2948 cbufp =
2949 cbuf = tlp->tl_defc.s + (tlp->tl_defc.l - len);
2950 cbufp += len;
2953 /* Read in the next complete multibyte character */
2954 /* C99 */{
2955 # ifdef HAVE_KEY_BINDINGS
2956 struct a_tty_bind_tree *xtbtp;
2957 struct inseq{
2958 struct inseq *last;
2959 struct inseq *next;
2960 struct a_tty_bind_tree *tbtp;
2961 } *isp_head, *isp;
2963 isp_head = isp = NULL;
2964 # endif
2966 for(flags &= a_READ_LOOP_MASK;;){
2967 # ifdef HAVE_KEY_BINDINGS
2968 if(!(flags & a_BUFMODE) && tlp->tl_bind_takeover != '\0'){
2969 wc = tlp->tl_bind_takeover;
2970 tlp->tl_bind_takeover = '\0';
2971 }else
2972 # endif
2974 if(!(flags & a_BUFMODE)){
2975 /* Let me at least once dream of iomon(itor), timer with
2976 * one-shot, enwrapped with key_event and key_sequence_event,
2977 * all driven by an event_loop */
2978 /* TODO v15 Until we have SysV signal handling all through we
2979 * TODO need to temporarily adjust our BSD signal handler with
2980 * TODO a SysV one, here */
2981 n_sighdl_t otstp, ottin, ottou;
2983 otstp = n_signal(SIGTSTP, &a_tty_signal);
2984 ottin = n_signal(SIGTTIN, &a_tty_signal);
2985 ottou = n_signal(SIGTTOU, &a_tty_signal);
2986 # ifdef HAVE_KEY_BINDINGS
2987 flags &= ~a_TIMEOUT_MASK;
2988 if(isp != NULL && (tbtp = isp->tbtp)->tbt_isseq &&
2989 !tbtp->tbt_isseq_trail){
2990 a_tty_term_rawmode_timeout(tlp, TRU1);
2991 flags |= a_TIMEOUT;
2993 # endif
2995 while((rv = read(STDIN_FILENO, cbufp, 1)) < 1){
2996 if(rv == -1){
2997 if(n_err_no == n_ERR_INTR){
2998 if((tlp->tl_vi_flags & a_TTY_VF_MOD_DIRTY) &&
2999 !a_tty_vi_refresh(tlp))
3000 break;
3001 continue;
3003 break;
3006 # ifdef HAVE_KEY_BINDINGS
3007 /* Timeout expiration */
3008 if(rv == 0){
3009 assert(flags & a_TIMEOUT);
3010 assert(isp != NULL);
3011 a_tty_term_rawmode_timeout(tlp, FAL0);
3013 /* Something "atomic" broke. Maybe the current one can
3014 * also be terminated already, by itself? xxx really? */
3015 if((tbtp = isp->tbtp)->tbt_bind != NULL){
3016 tlp->tl_bind_takeover = wc;
3017 goto jhave_bind;
3020 /* Or, maybe there is a second path without a timeout;
3021 * this should be covered by .tbt_isseq_trail, but then
3022 * again a single-layer implementation cannot "know" */
3023 for(xtbtp = tbtp; (xtbtp = xtbtp->tbt_sibling) != NULL;)
3024 if(xtbtp->tbt_char == tbtp->tbt_char){
3025 assert(!xtbtp->tbt_isseq);
3026 break;
3028 /* Lay down on read(2)? */
3029 if(xtbtp != NULL)
3030 continue;
3031 goto jtake_over;
3033 # endif /* HAVE_KEY_BINDINGS */
3036 # ifdef HAVE_KEY_BINDINGS
3037 if(flags & a_TIMEOUT)
3038 a_tty_term_rawmode_timeout(tlp, FAL0);
3039 # endif
3040 safe_signal(SIGTSTP, otstp);
3041 safe_signal(SIGTTIN, ottin);
3042 safe_signal(SIGTTOU, ottou);
3043 if(rv < 0)
3044 goto jleave;
3046 ++cbufp;
3049 rv = (ssize_t)mbrtowc(&wc, cbuf, PTR2SIZE(cbufp - cbuf), &ps[0]);
3050 if(rv <= 0){
3051 /* Any error during buffer mode can only result in a hard
3052 * reset; Otherwise, if it's a hard error, or if too many
3053 * redundant shift sequences overflow our buffer: perform
3054 * hard reset */
3055 if((flags & a_BUFMODE) || rv == -1 ||
3056 sizeof cbuf_base == PTR2SIZE(cbufp - cbuf)){
3057 a_tty_fun(tlp, a_TTY_BIND_FUN_FULLRESET, &len);
3058 goto jrestart;
3060 /* Otherwise, due to the way we deal with the buffer, we need
3061 * to restore the mbstate_t from before this conversion */
3062 ps[0] = ps[1];
3063 continue;
3065 cbufp = cbuf;
3066 ps[1] = ps[0];
3069 /* Normal read(2)ing is subject to detection of key-bindings */
3070 # ifdef HAVE_KEY_BINDINGS
3071 if(!(flags & a_BUFMODE)){
3072 /* Check for special bypass functions before we try to embed
3073 * this character into the tree */
3074 if(n_uasciichar(wc)){
3075 char c;
3076 char const *cp;
3078 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_prompt_char)[0];
3079 *cp != '\0'; ++cp){
3080 if(c == *cp){
3081 wc = a_tty_vinuni(tlp);
3082 break;
3085 if(wc == '\0'){
3086 tlp->tl_vi_flags |= a_TTY_VF_BELL;
3087 goto jinput_loop;
3090 if(n_uasciichar(wc))
3091 flags |= a_MAYBEFUN;
3092 else
3093 flags &= ~a_MAYBEFUN;
3095 /* Search for this character in the bind tree */
3096 tbtp = (isp != NULL) ? isp->tbtp->tbt_childs
3097 : (*tlp->tl_bind_tree_hmap)[wc % HSHSIZE];
3098 for(; tbtp != NULL; tbtp = tbtp->tbt_sibling){
3099 if(tbtp->tbt_char == wc){
3100 struct inseq *nisp;
3102 /* If this one cannot continue we're likely finished! */
3103 if(tbtp->tbt_childs == NULL){
3104 assert(tbtp->tbt_bind != NULL);
3105 tbf = tbtp->tbt_bind->tbc_flags;
3106 goto jmle_fun;
3109 /* This needs to read more characters */
3110 nisp = n_autorec_alloc(sizeof *nisp);
3111 if((nisp->last = isp) == NULL)
3112 isp_head = nisp;
3113 else
3114 isp->next = nisp;
3115 nisp->next = NULL;
3116 nisp->tbtp = tbtp;
3117 isp = nisp;
3118 flags &= ~a_WAS_HERE;
3119 break;
3122 if(tbtp != NULL)
3123 continue;
3125 /* Was there a binding active, but couldn't be continued? */
3126 if(isp != NULL){
3127 /* A binding had a timeout, it didn't expire, but we saw
3128 * something non-expected. Something "atomic" broke.
3129 * Maybe there is a second path without a timeout, that
3130 * continues like we've seen it. I.e., it may just have been
3131 * the user, typing too fast. We definitely want to allow
3132 * bindings like \e,d etc. to succeed: users are so used to
3133 * them that a timeout cannot be the mechanism to catch up!
3134 * A single-layer implementation cannot "know" */
3135 if((tbtp = isp->tbtp)->tbt_isseq && (isp->last == NULL ||
3136 !(xtbtp = isp->last->tbtp)->tbt_isseq ||
3137 xtbtp->tbt_isseq_trail)){
3138 for(xtbtp = (tbtp = isp->tbtp);
3139 (xtbtp = xtbtp->tbt_sibling) != NULL;)
3140 if(xtbtp->tbt_char == tbtp->tbt_char){
3141 assert(!xtbtp->tbt_isseq);
3142 break;
3144 if(xtbtp != NULL){
3145 isp->tbtp = xtbtp;
3146 tlp->tl_bind_takeover = wc;
3147 continue;
3151 /* Check for CANCEL shortcut now */
3152 if(flags & a_MAYBEFUN){
3153 char c;
3154 char const *cp;
3156 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_cancel)[0];
3157 *cp != '\0'; ++cp)
3158 if(c == *cp){
3159 tbf = a_TTY_BIND_FUN_INTERNAL |a_TTY_BIND_FUN_CANCEL;
3160 goto jmle_fun;
3164 /* So: maybe the current sequence can be terminated here? */
3165 if((tbtp = isp->tbtp)->tbt_bind != NULL){
3166 jhave_bind:
3167 tbf = tbtp->tbt_bind->tbc_flags;
3168 jmle_fun:
3169 if(tbf & a_TTY_BIND_FUN_INTERNAL){
3170 switch(a_tty_fun(tlp, tbf, &len)){
3171 case a_TTY_FUN_STATUS_OK:
3172 goto jinput_loop;
3173 case a_TTY_FUN_STATUS_COMMIT:
3174 goto jdone;
3175 case a_TTY_FUN_STATUS_RESTART:
3176 goto jrestart;
3177 case a_TTY_FUN_STATUS_END:
3178 rv = -1;
3179 goto jleave;
3181 assert(0);
3182 }else if(tbtp->tbt_bind->tbc_flags & a_TTY_BIND_NOCOMMIT){
3183 struct a_tty_bind_ctx *tbcp;
3185 tbcp = tbtp->tbt_bind;
3186 memcpy(tlp->tl_defc.s = n_autorec_alloc(
3187 (tlp->tl_defc.l = len = tbcp->tbc_exp_len) +1),
3188 tbcp->tbc_exp, tbcp->tbc_exp_len +1);
3189 goto jrestart;
3190 }else{
3191 cbufp = tbtp->tbt_bind->tbc_exp;
3192 goto jinject_input;
3197 /* Otherwise take over all chars "as is" */
3198 jtake_over:
3199 for(; isp_head != NULL; isp_head = isp_head->next)
3200 if(a_tty_kother(tlp, isp_head->tbtp->tbt_char)){
3201 /* FIXME */
3203 /* And the current one too */
3204 goto jkother;
3206 # endif /* HAVE_KEY_BINDINGS */
3208 if((flags & a_BUFMODE) && (len -= (size_t)rv) == 0){
3209 /* Buffer mode completed */
3210 tlp->tl_defc.s = NULL;
3211 tlp->tl_defc.l = 0;
3212 flags &= ~a_BUFMODE;
3214 break;
3217 # ifndef HAVE_KEY_BINDINGS
3218 /* Don't interpret control bytes during buffer mode.
3219 * Otherwise, if it's a control byte check whether it is a MLE
3220 * function. Remarks: initially a complete duplicate to be able to
3221 * switch(), later converted to simply iterate over (an #ifdef'd
3222 * subset of) the MLE base_tuple table in order to have "a SPOF" */
3223 if(cbuf == cbuf_base && n_uasciichar(wc) && cntrlchar((char)wc)){
3224 struct a_tty_bind_builtin_tuple const *tbbtp, *tbbtp_max;
3225 char c;
3227 c = (char)wc ^ 0x40;
3228 tbbtp = a_tty_bind_base_tuples;
3229 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_base_tuples)];
3230 jbuiltin_redo:
3231 for(; tbbtp < tbbtp_max; ++tbbtp){
3232 /* Assert default_tuple table is properly subset'ed */
3233 assert(tbbtp->tbdt_iskey);
3234 if(tbbtp->tbbt_ckey == c){
3235 if(tbbtp->tbbt_exp[0] == '\0'){
3236 tbf = a_TTY_BIND_FUN_EXPAND((ui8_t)tbbtp->tbbt_exp[1]);
3237 switch(a_tty_fun(tlp, tbf, &len)){
3238 case a_TTY_FUN_STATUS_OK:
3239 goto jinput_loop;
3240 case a_TTY_FUN_STATUS_COMMIT:
3241 goto jdone;
3242 case a_TTY_FUN_STATUS_RESTART:
3243 goto jrestart;
3244 case a_TTY_FUN_STATUS_END:
3245 rv = -1;
3246 goto jleave;
3248 assert(0);
3249 }else{
3250 cbufp = tbbtp->tbbt_exp;
3251 goto jinject_input;
3255 if(tbbtp ==
3256 &a_tty_bind_base_tuples[n_NELEM(a_tty_bind_base_tuples)]){
3257 tbbtp = a_tty_bind_default_tuples;
3258 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_default_tuples)];
3259 goto jbuiltin_redo;
3262 # endif /* !HAVE_KEY_BINDINGS */
3264 # ifdef HAVE_KEY_BINDINGS
3265 jkother:
3266 # endif
3267 if(a_tty_kother(tlp, wc)){
3268 /* Don't clear the history during buffer mode.. */
3269 # ifdef HAVE_HISTORY
3270 if(!(flags & a_BUFMODE) && cbuf == cbuf_base)
3271 tlp->tl_hist = NULL;
3272 # endif
3277 /* We have a completed input line, convert the struct cell data to its
3278 * plain character equivalent */
3279 jdone:
3280 rv = a_tty_cell2dat(tlp);
3281 jleave:
3282 putc('\n', n_tty_fp);
3283 fflush(n_tty_fp);
3284 NYD_LEAVE;
3285 return rv;
3287 jinject_input:{
3288 size_t i;
3290 hold_all_sigs(); /* XXX v15 drop */
3291 i = a_tty_cell2dat(tlp);
3292 n_go_input_inject(n_GO_INPUT_INJECT_NONE, tlp->tl_line.cbuf, i);
3293 i = strlen(cbufp) +1;
3294 if(i >= *tlp->tl_x_bufsize){
3295 *tlp->tl_x_buf = (n_realloc)(*tlp->tl_x_buf, i n_MEMORY_DEBUG_ARGSCALL);
3296 *tlp->tl_x_bufsize = i;
3298 memcpy(*tlp->tl_x_buf, cbufp, i);
3299 rele_all_sigs(); /* XXX v15 drop */
3300 if(histok_or_null != NULL)
3301 *histok_or_null = FAL0;
3302 rv = (ssize_t)--i;
3304 goto jleave;
3307 # ifdef HAVE_KEY_BINDINGS
3308 static enum n_go_input_flags
3309 a_tty_bind_ctx_find(char const *name){
3310 enum n_go_input_flags rv;
3311 struct a_tty_bind_ctx_map const *tbcmp;
3312 NYD2_ENTER;
3314 tbcmp = a_tty_bind_ctx_maps;
3315 do if(!asccasecmp(tbcmp->tbcm_name, name)){
3316 rv = tbcmp->tbcm_ctx;
3317 goto jleave;
3318 }while(PTRCMP(++tbcmp, <,
3319 &a_tty_bind_ctx_maps[n_NELEM(a_tty_bind_ctx_maps)]));
3321 rv = (enum n_go_input_flags)-1;
3322 jleave:
3323 NYD2_LEAVE;
3324 return rv;
3327 static bool_t
3328 a_tty_bind_create(struct a_tty_bind_parse_ctx *tbpcp, bool_t replace){
3329 struct a_tty_bind_ctx *tbcp;
3330 bool_t rv;
3331 NYD2_ENTER;
3333 rv = FAL0;
3335 if(!a_tty_bind_parse(TRU1, tbpcp))
3336 goto jleave;
3338 /* Since we use a single buffer for it all, need to replace as such */
3339 if(tbpcp->tbpc_tbcp != NULL){
3340 if(!replace)
3341 goto jleave;
3342 a_tty_bind_del(tbpcp);
3343 }else if(a_tty.tg_bind_cnt == UI32_MAX){
3344 n_err(_("`bind': maximum number of bindings already established\n"));
3345 goto jleave;
3348 /* C99 */{
3349 size_t i, j;
3351 tbcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_tty_bind_ctx, tbc__buf) +
3352 tbpcp->tbpc_seq_len + tbpcp->tbpc_exp.l +
3353 n_MAX(sizeof(si32_t), sizeof(wc_t)) + tbpcp->tbpc_cnv_len +3);
3354 if(tbpcp->tbpc_ltbcp != NULL){
3355 tbcp->tbc_next = tbpcp->tbpc_ltbcp->tbc_next;
3356 tbpcp->tbpc_ltbcp->tbc_next = tbcp;
3357 }else{
3358 enum n_go_input_flags gif;
3360 gif = tbpcp->tbpc_flags & n__GO_INPUT_CTX_MASK;
3361 tbcp->tbc_next = a_tty.tg_bind[gif];
3362 a_tty.tg_bind[gif] = tbcp;
3364 memcpy(tbcp->tbc_seq = &tbcp->tbc__buf[0],
3365 tbpcp->tbpc_seq, i = (tbcp->tbc_seq_len = tbpcp->tbpc_seq_len) +1);
3366 memcpy(tbcp->tbc_exp = &tbcp->tbc__buf[i],
3367 tbpcp->tbpc_exp.s, j = (tbcp->tbc_exp_len = tbpcp->tbpc_exp.l) +1);
3368 i += j;
3369 i = (i + tbpcp->tbpc_cnv_align_mask) & ~tbpcp->tbpc_cnv_align_mask;
3370 memcpy(tbcp->tbc_cnv = &tbcp->tbc__buf[i],
3371 tbpcp->tbpc_cnv, (tbcp->tbc_cnv_len = tbpcp->tbpc_cnv_len) +1);
3372 tbcp->tbc_flags = tbpcp->tbpc_flags;
3375 /* Directly resolve any termcap(5) symbol if we are already setup */
3376 if((n_psonce & n_PSO_STARTED) &&
3377 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
3378 a_TTY_BIND_RESOLVE)
3379 a_tty_bind_resolve(tbcp);
3381 ++a_tty.tg_bind_cnt;
3382 /* If this binding is usable invalidate the key input lookup trees */
3383 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3384 a_tty.tg_bind_isdirty = TRU1;
3385 rv = TRU1;
3386 jleave:
3387 NYD2_LEAVE;
3388 return rv;
3391 static bool_t
3392 a_tty_bind_parse(bool_t isbindcmd, struct a_tty_bind_parse_ctx *tbpcp){
3393 enum{a_TRUE_RV = a_TTY__BIND_LAST<<1};
3395 struct n_visual_info_ctx vic;
3396 struct str shin_save, shin;
3397 struct n_string shou, *shoup;
3398 size_t i;
3399 struct kse{
3400 struct kse *next;
3401 char *seq_dat;
3402 wc_t *cnv_dat;
3403 ui32_t seq_len;
3404 ui32_t cnv_len; /* High bit set if a termap to be resolved */
3405 ui32_t calc_cnv_len; /* Ditto, but aligned etc. */
3406 ui8_t kse__dummy[4];
3407 } *head, *tail;
3408 ui32_t f;
3409 NYD2_ENTER;
3410 n_LCTA(UICMP(64, a_TRUE_RV, <, UI32_MAX),
3411 "Flag bits excess storage datatype");
3413 f = n_GO_INPUT_NONE;
3414 shoup = n_string_creat_auto(&shou);
3415 head = tail = NULL;
3417 /* Parse the key-sequence */
3418 for(shin.s = n_UNCONST(tbpcp->tbpc_in_seq), shin.l = UIZ_MAX;;){
3419 struct kse *ep;
3420 enum n_shexp_state shs;
3422 shin_save = shin;
3423 shs = n_shexp_parse_token((n_SHEXP_PARSE_TRUNC |
3424 n_SHEXP_PARSE_TRIM_SPACE | n_SHEXP_PARSE_IGNORE_EMPTY |
3425 n_SHEXP_PARSE_IFS_IS_COMMA), shoup, &shin, NULL);
3426 if(shs & n_SHEXP_STATE_ERR_UNICODE){
3427 f |= a_TTY_BIND_DEFUNCT;
3428 if(isbindcmd && (n_poption & n_PO_D_V))
3429 n_err(_("`%s': \\uNICODE not available in locale: %s\n"),
3430 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3432 if((shs & n_SHEXP_STATE_ERR_MASK) & ~n_SHEXP_STATE_ERR_UNICODE){
3433 n_err(_("`%s': failed to parse key-sequence: %s\n"),
3434 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3435 goto jleave;
3437 if((shs & (n_SHEXP_STATE_OUTPUT | n_SHEXP_STATE_STOP)) ==
3438 n_SHEXP_STATE_STOP)
3439 break;
3441 ep = n_autorec_alloc(sizeof *ep);
3442 if(head == NULL)
3443 head = ep;
3444 else
3445 tail->next = ep;
3446 tail = ep;
3447 ep->next = NULL;
3448 if(!(shs & n_SHEXP_STATE_ERR_UNICODE)){
3449 i = strlen(ep->seq_dat = n_shexp_quote_cp(n_string_cp(shoup), TRU1));
3450 if(i >= SI32_MAX - 1)
3451 goto jelen;
3452 ep->seq_len = (ui32_t)i;
3453 }else{
3454 /* Otherwise use the original buffer, _we_ can only quote it the wrong
3455 * way (e.g., an initial $'\u3a' becomes '\u3a'), _then_ */
3456 if((i = shin_save.l - shin.l) >= SI32_MAX - 1)
3457 goto jelen;
3458 ep->seq_len = (ui32_t)i;
3459 ep->seq_dat = savestrbuf(shin_save.s, i);
3462 memset(&vic, 0, sizeof vic);
3463 vic.vic_inlen = shoup->s_len;
3464 vic.vic_indat = shoup->s_dat;
3465 if(!n_visual_info(&vic,
3466 n_VISUAL_INFO_WOUT_CREATE | n_VISUAL_INFO_WOUT_SALLOC)){
3467 n_err(_("`%s': key-sequence seems to contain invalid "
3468 "characters: %s: %s\n"),
3469 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
3470 f |= a_TTY_BIND_DEFUNCT;
3471 goto jleave;
3472 }else if(vic.vic_woulen == 0 ||
3473 vic.vic_woulen >= (SI32_MAX - 2) / sizeof(wc_t)){
3474 jelen:
3475 n_err(_("`%s': length of key-sequence unsupported: %s: %s\n"),
3476 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
3477 f |= a_TTY_BIND_DEFUNCT;
3478 goto jleave;
3480 ep->cnv_dat = vic.vic_woudat;
3481 ep->cnv_len = (ui32_t)vic.vic_woulen;
3483 /* A termcap(5)/terminfo(5) identifier? */
3484 if(ep->cnv_len > 1 && ep->cnv_dat[0] == ':'){
3485 i = --ep->cnv_len, ++ep->cnv_dat;
3486 # if 0 /* ndef HAVE_TERMCAP xxx User can, via *termcap*! */
3487 if(n_poption & n_PO_D_V)
3488 n_err(_("`%s': no termcap(5)/terminfo(5) support: %s: %s\n"),
3489 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3490 f |= a_TTY_BIND_DEFUNCT;
3491 # endif
3492 if(i > a_TTY_BIND_CAPNAME_MAX){
3493 n_err(_("`%s': termcap(5)/terminfo(5) name too long: %s: %s\n"),
3494 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3495 f |= a_TTY_BIND_DEFUNCT;
3497 while(i > 0)
3498 /* (We store it as char[]) */
3499 if((ui32_t)ep->cnv_dat[--i] & ~0x7Fu){
3500 n_err(_("`%s': invalid termcap(5)/terminfo(5) name content: "
3501 "%s: %s\n"),
3502 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3503 f |= a_TTY_BIND_DEFUNCT;
3504 break;
3506 ep->cnv_len |= SI32_MIN; /* Needs resolve */
3507 f |= a_TTY_BIND_RESOLVE;
3510 if(shs & n_SHEXP_STATE_STOP)
3511 break;
3514 if(head == NULL){
3515 jeempty:
3516 n_err(_("`%s': effectively empty key-sequence: %s\n"),
3517 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3518 goto jleave;
3521 if(isbindcmd) /* (Or always, just "1st time init") */
3522 tbpcp->tbpc_cnv_align_mask = n_MAX(sizeof(si32_t), sizeof(wc_t)) - 1;
3524 /* C99 */{
3525 struct a_tty_bind_ctx *ltbcp, *tbcp;
3526 char *cpbase, *cp, *cnv;
3527 size_t sl, cl;
3529 /* Unite the parsed sequence(s) into single string representations */
3530 for(sl = cl = 0, tail = head; tail != NULL; tail = tail->next){
3531 sl += tail->seq_len + 1;
3533 if(!isbindcmd)
3534 continue;
3536 /* Preserve room for terminal capabilities to be resolved.
3537 * Above we have ensured the buffer will fit in these calculations */
3538 if((i = tail->cnv_len) & SI32_MIN){
3539 /* For now
3540 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[]+NUL;}
3541 * later
3542 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3543 n_LCTAV(n_ISPOW2(a_TTY_BIND_CAPEXP_ROUNDUP));
3544 n_LCTA(a_TTY_BIND_CAPEXP_ROUNDUP >= sizeof(wc_t),
3545 "Aligning on this constant does not properly align wc_t");
3546 i &= SI32_MAX;
3547 i *= sizeof(wc_t);
3548 i += sizeof(si32_t);
3549 if(i < a_TTY_BIND_CAPEXP_ROUNDUP)
3550 i = (i + (a_TTY_BIND_CAPEXP_ROUNDUP - 1)) &
3551 ~(a_TTY_BIND_CAPEXP_ROUNDUP - 1);
3552 }else
3553 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3554 i *= sizeof(wc_t);
3555 i += sizeof(si32_t) + sizeof(wc_t); /* (buf_len_iscap, NUL) */
3556 cl += i;
3557 if(tail->cnv_len & SI32_MIN){
3558 tail->cnv_len &= SI32_MAX;
3559 i |= SI32_MIN;
3561 tail->calc_cnv_len = (ui32_t)i;
3563 --sl;
3565 tbpcp->tbpc_seq_len = sl;
3566 tbpcp->tbpc_cnv_len = cl;
3567 /* C99 */{
3568 size_t j;
3570 j = i = sl + 1; /* Room for comma separator */
3571 if(isbindcmd){
3572 i = (i + tbpcp->tbpc_cnv_align_mask) & ~tbpcp->tbpc_cnv_align_mask;
3573 j = i;
3574 i += cl;
3576 tbpcp->tbpc_seq = cp = cpbase = n_autorec_alloc(i);
3577 tbpcp->tbpc_cnv = cnv = &cpbase[j];
3580 for(tail = head; tail != NULL; tail = tail->next){
3581 memcpy(cp, tail->seq_dat, tail->seq_len);
3582 cp += tail->seq_len;
3583 *cp++ = ',';
3585 if(isbindcmd){
3586 char * const save_cnv = cnv;
3588 n_UNALIGN(si32_t*,cnv)[0] = (si32_t)(i = tail->calc_cnv_len);
3589 cnv += sizeof(si32_t);
3590 if(i & SI32_MIN){
3591 /* For now
3592 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];}
3593 * later
3594 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[];} */
3595 n_UNALIGN(si32_t*,cnv)[0] = tail->cnv_len;
3596 cnv += sizeof(si32_t);
3598 i = tail->cnv_len * sizeof(wc_t);
3599 memcpy(cnv, tail->cnv_dat, i);
3600 cnv += i;
3601 *n_UNALIGN(wc_t*,cnv) = '\0';
3603 cnv = save_cnv + (tail->calc_cnv_len & SI32_MAX);
3606 *--cp = '\0';
3608 /* Search for a yet existing identical mapping */
3609 /* C99 */{
3610 enum n_go_input_flags gif;
3612 gif = tbpcp->tbpc_flags & n__GO_INPUT_CTX_MASK;
3614 for(ltbcp = NULL, tbcp = a_tty.tg_bind[gif]; tbcp != NULL;
3615 ltbcp = tbcp, tbcp = tbcp->tbc_next)
3616 if(tbcp->tbc_seq_len == sl && !memcmp(tbcp->tbc_seq, cpbase, sl)){
3617 tbpcp->tbpc_tbcp = tbcp;
3618 break;
3621 tbpcp->tbpc_ltbcp = ltbcp;
3622 tbpcp->tbpc_flags |= (f & a_TTY__BIND_MASK);
3625 /* Create single string expansion if so desired */
3626 if(isbindcmd){
3627 char *exp;
3629 exp = tbpcp->tbpc_exp.s;
3631 i = tbpcp->tbpc_exp.l;
3632 if(i > 0 && exp[i - 1] == '@'){
3633 while(--i > 0){
3634 if(!blankspacechar(exp[i - 1]))
3635 break;
3637 if(i == 0)
3638 goto jeempty;
3640 exp[tbpcp->tbpc_exp.l = i] = '\0';
3641 tbpcp->tbpc_flags |= a_TTY_BIND_NOCOMMIT;
3644 /* Reverse solidus cannot be placed last in expansion to avoid (at the
3645 * time of this writing) possible problems with newline escaping.
3646 * Don't care about (un)even number thereof */
3647 if(i > 0 && exp[i - 1] == '\\'){
3648 n_err(_("`%s': reverse solidus cannot be last in expansion: %s\n"),
3649 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3650 goto jleave;
3653 /* It may map to an internal MLE command! */
3654 for(i = 0; i < n_NELEM(a_tty_bind_fun_names); ++i)
3655 if(!asccasecmp(exp, a_tty_bind_fun_names[i])){
3656 tbpcp->tbpc_flags |= a_TTY_BIND_FUN_EXPAND(i) |
3657 a_TTY_BIND_FUN_INTERNAL |
3658 (head->next == NULL ? a_TTY_BIND_MLE1CNTRL : 0);
3659 if((n_poption & n_PO_D_V) &&
3660 (tbpcp->tbpc_flags & a_TTY_BIND_NOCOMMIT))
3661 n_err(_("`%s': MLE commands can't be made editable via @: %s\n"),
3662 tbpcp->tbpc_cmd, exp);
3663 tbpcp->tbpc_flags &= ~a_TTY_BIND_NOCOMMIT;
3664 break;
3668 f |= a_TRUE_RV; /* TODO because we only now true and false; DEFUNCT.. */
3669 jleave:
3670 n_string_gut(shoup);
3671 NYD2_LEAVE;
3672 return (f & a_TRUE_RV) != 0;
3675 static void
3676 a_tty_bind_resolve(struct a_tty_bind_ctx *tbcp){
3677 char capname[a_TTY_BIND_CAPNAME_MAX +1];
3678 struct n_termcap_value tv;
3679 size_t len;
3680 bool_t isfirst; /* TODO For now: first char must be control! */
3681 char *cp, *next;
3682 NYD2_ENTER;
3684 n_UNINIT(next, NULL);
3685 for(cp = tbcp->tbc_cnv, isfirst = TRU1, len = tbcp->tbc_cnv_len;
3686 len > 0; isfirst = FAL0, cp = next){
3687 /* C99 */{
3688 si32_t i, j;
3690 i = n_UNALIGN(si32_t*,cp)[0];
3691 j = i & SI32_MAX;
3692 next = &cp[j];
3693 len -= j;
3694 if(i == j)
3695 continue;
3697 /* struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];} */
3698 cp += sizeof(si32_t);
3699 i = n_UNALIGN(si32_t*,cp)[0];
3700 cp += sizeof(si32_t);
3701 for(j = 0; j < i; ++j)
3702 capname[j] = n_UNALIGN(wc_t*,cp)[j];
3703 capname[j] = '\0';
3706 /* Use generic lookup mechanism if not a known query */
3707 /* C99 */{
3708 si32_t tq;
3710 tq = n_termcap_query_for_name(capname, n_TERMCAP_CAPTYPE_STRING);
3711 if(tq == -1){
3712 tv.tv_data.tvd_string = capname;
3713 tq = n__TERMCAP_QUERY_MAX1;
3716 if(tq < 0 || !n_termcap_query(tq, &tv)){
3717 if(n_poption & n_PO_D_V)
3718 n_err(_("`bind': unknown or unsupported capability: %s: %s\n"),
3719 capname, tbcp->tbc_seq);
3720 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3721 break;
3725 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3726 /* C99 */{
3727 size_t i;
3729 i = strlen(tv.tv_data.tvd_string);
3730 if(/*i > SI32_MAX ||*/ i >= PTR2SIZE(next - cp)){
3731 if(n_poption & n_PO_D_V)
3732 n_err(_("`bind': capability expansion too long: %s: %s\n"),
3733 capname, tbcp->tbc_seq);
3734 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3735 break;
3736 }else if(i == 0){
3737 if(n_poption & n_PO_D_V)
3738 n_err(_("`bind': empty capability expansion: %s: %s\n"),
3739 capname, tbcp->tbc_seq);
3740 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3741 break;
3742 }else if(isfirst && !cntrlchar(*tv.tv_data.tvd_string)){
3743 if(n_poption & n_PO_D_V)
3744 n_err(_("`bind': capability expansion does not start with "
3745 "control: %s: %s\n"), capname, tbcp->tbc_seq);
3746 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3747 break;
3749 n_UNALIGN(si32_t*,cp)[-1] = (si32_t)i;
3750 memcpy(cp, tv.tv_data.tvd_string, i);
3751 cp[i] = '\0';
3754 NYD2_LEAVE;
3757 static void
3758 a_tty_bind_del(struct a_tty_bind_parse_ctx *tbpcp){
3759 struct a_tty_bind_ctx *ltbcp, *tbcp;
3760 NYD2_ENTER;
3762 tbcp = tbpcp->tbpc_tbcp;
3764 if((ltbcp = tbpcp->tbpc_ltbcp) != NULL)
3765 ltbcp->tbc_next = tbcp->tbc_next;
3766 else
3767 a_tty.tg_bind[tbpcp->tbpc_flags & n__GO_INPUT_CTX_MASK] = tbcp->tbc_next;
3768 n_free(tbcp);
3770 --a_tty.tg_bind_cnt;
3771 a_tty.tg_bind_isdirty = TRU1;
3772 NYD2_LEAVE;
3775 static void
3776 a_tty_bind_tree_build(void){
3777 size_t i;
3778 NYD2_ENTER;
3780 for(i = 0; i < n__GO_INPUT_CTX_MAX1; ++i){
3781 struct a_tty_bind_ctx *tbcp;
3782 n_LCTAV(n_GO_INPUT_CTX_BASE == 0);
3784 /* Somewhat wasteful, but easier to handle: simply clone the entire
3785 * primary key onto the secondary one, then only modify it */
3786 for(tbcp = a_tty.tg_bind[n_GO_INPUT_CTX_BASE]; tbcp != NULL;
3787 tbcp = tbcp->tbc_next)
3788 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3789 a_tty__bind_tree_add(n_GO_INPUT_CTX_BASE, &a_tty.tg_bind_tree[i][0],
3790 tbcp);
3792 if(i != n_GO_INPUT_CTX_BASE)
3793 for(tbcp = a_tty.tg_bind[i]; tbcp != NULL; tbcp = tbcp->tbc_next)
3794 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3795 a_tty__bind_tree_add(i, &a_tty.tg_bind_tree[i][0], tbcp);
3798 a_tty.tg_bind_isbuild = TRU1;
3799 NYD2_LEAVE;
3802 static void
3803 a_tty_bind_tree_teardown(void){
3804 size_t i, j;
3805 NYD2_ENTER;
3807 memset(&a_tty.tg_bind_shcut_cancel[0], 0,
3808 sizeof(a_tty.tg_bind_shcut_cancel));
3809 memset(&a_tty.tg_bind_shcut_prompt_char[0], 0,
3810 sizeof(a_tty.tg_bind_shcut_prompt_char));
3812 for(i = 0; i < n__GO_INPUT_CTX_MAX1; ++i)
3813 for(j = 0; j < HSHSIZE; ++j)
3814 a_tty__bind_tree_free(a_tty.tg_bind_tree[i][j]);
3815 memset(&a_tty.tg_bind_tree[0], 0, sizeof(a_tty.tg_bind_tree));
3817 a_tty.tg_bind_isdirty = a_tty.tg_bind_isbuild = FAL0;
3818 NYD2_LEAVE;
3821 static void
3822 a_tty__bind_tree_add(ui32_t hmap_idx, struct a_tty_bind_tree *store[HSHSIZE],
3823 struct a_tty_bind_ctx *tbcp){
3824 ui32_t cnvlen;
3825 char const *cnvdat;
3826 struct a_tty_bind_tree *ntbtp;
3827 NYD2_ENTER;
3828 n_UNUSED(hmap_idx);
3830 ntbtp = NULL;
3832 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len; cnvlen > 0;){
3833 union {wchar_t const *wp; char const *cp;} u;
3834 si32_t entlen;
3836 /* {si32_t buf_len_iscap;} */
3837 entlen = *n_UNALIGN(si32_t const*,cnvdat);
3839 if(entlen & SI32_MIN){
3840 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;}
3841 * Note that empty capabilities result in DEFUNCT */
3842 for(u.cp = (char const*)&n_UNALIGN(si32_t const*,cnvdat)[2];
3843 *u.cp != '\0'; ++u.cp)
3844 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.cp, TRU1);
3845 assert(ntbtp != NULL);
3846 ntbtp->tbt_isseq_trail = TRU1;
3847 entlen &= SI32_MAX;
3848 }else{
3849 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3850 bool_t isseq;
3852 u.wp = (wchar_t const*)&n_UNALIGN(si32_t const*,cnvdat)[1];
3854 /* May be a special shortcut function? */
3855 if(ntbtp == NULL && (tbcp->tbc_flags & a_TTY_BIND_MLE1CNTRL)){
3856 char *cp;
3857 ui32_t ctx, fun;
3859 ctx = tbcp->tbc_flags & n__GO_INPUT_CTX_MASK;
3860 fun = tbcp->tbc_flags & a_TTY__BIND_FUN_MASK;
3862 if(fun == a_TTY_BIND_FUN_CANCEL){
3863 for(cp = &a_tty.tg_bind_shcut_cancel[ctx][0];
3864 PTRCMP(cp, <, &a_tty.tg_bind_shcut_cancel[ctx]
3865 [n_NELEM(a_tty.tg_bind_shcut_cancel[ctx]) - 1]); ++cp)
3866 if(*cp == '\0'){
3867 *cp = (char)*u.wp;
3868 break;
3870 }else if(fun == a_TTY_BIND_FUN_PROMPT_CHAR){
3871 for(cp = &a_tty.tg_bind_shcut_prompt_char[ctx][0];
3872 PTRCMP(cp, <, &a_tty.tg_bind_shcut_prompt_char[ctx]
3873 [n_NELEM(a_tty.tg_bind_shcut_prompt_char[ctx]) - 1]);
3874 ++cp)
3875 if(*cp == '\0'){
3876 *cp = (char)*u.wp;
3877 break;
3882 isseq = (u.wp[1] != '\0');
3883 for(; *u.wp != '\0'; ++u.wp)
3884 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.wp, isseq);
3885 if(isseq){
3886 assert(ntbtp != NULL);
3887 ntbtp->tbt_isseq_trail = TRU1;
3891 cnvlen -= entlen;
3892 cnvdat += entlen;
3895 /* Should have been rendered defunctional at first instead */
3896 assert(ntbtp != NULL);
3897 ntbtp->tbt_bind = tbcp;
3898 NYD2_LEAVE;
3901 static struct a_tty_bind_tree *
3902 a_tty__bind_tree_add_wc(struct a_tty_bind_tree **treep,
3903 struct a_tty_bind_tree *parentp, wchar_t wc, bool_t isseq){
3904 struct a_tty_bind_tree *tbtp, *xtbtp;
3905 NYD2_ENTER;
3907 if(parentp == NULL){
3908 treep += wc % HSHSIZE;
3910 /* Having no parent also means that the tree slot is possibly empty */
3911 for(tbtp = *treep; tbtp != NULL;
3912 parentp = tbtp, tbtp = tbtp->tbt_sibling){
3913 if(tbtp->tbt_char != wc)
3914 continue;
3915 if(tbtp->tbt_isseq == isseq)
3916 goto jleave;
3917 /* isseq MUST be linked before !isseq, so record this "parent"
3918 * sibling, but continue searching for now.
3919 * Otherwise it is impossible that we'll find what we look for */
3920 if(isseq){
3921 #ifdef HAVE_DEBUG
3922 while((tbtp = tbtp->tbt_sibling) != NULL)
3923 assert(tbtp->tbt_char != wc);
3924 #endif
3925 break;
3929 tbtp = n_alloc(sizeof *tbtp);
3930 memset(tbtp, 0, sizeof *tbtp);
3931 tbtp->tbt_char = wc;
3932 tbtp->tbt_isseq = isseq;
3934 if(parentp == NULL){
3935 tbtp->tbt_sibling = *treep;
3936 *treep = tbtp;
3937 }else{
3938 tbtp->tbt_sibling = parentp->tbt_sibling;
3939 parentp->tbt_sibling = tbtp;
3941 }else{
3942 if((tbtp = *(treep = &parentp->tbt_childs)) != NULL){
3943 for(;; tbtp = xtbtp){
3944 if(tbtp->tbt_char == wc){
3945 if(tbtp->tbt_isseq == isseq)
3946 goto jleave;
3947 /* isseq MUST be linked before, so it is impossible that we'll
3948 * find what we look for */
3949 if(isseq){
3950 #ifdef HAVE_DEBUG
3951 while((tbtp = tbtp->tbt_sibling) != NULL)
3952 assert(tbtp->tbt_char != wc);
3953 #endif
3954 tbtp = NULL;
3955 break;
3959 if((xtbtp = tbtp->tbt_sibling) == NULL){
3960 treep = &tbtp->tbt_sibling;
3961 break;
3966 xtbtp = n_alloc(sizeof *xtbtp);
3967 memset(xtbtp, 0, sizeof *xtbtp);
3968 xtbtp->tbt_parent = parentp;
3969 xtbtp->tbt_char = wc;
3970 xtbtp->tbt_isseq = isseq;
3971 tbtp = xtbtp;
3972 *treep = tbtp;
3974 jleave:
3975 NYD2_LEAVE;
3976 return tbtp;
3979 static void
3980 a_tty__bind_tree_free(struct a_tty_bind_tree *tbtp){
3981 NYD2_ENTER;
3982 while(tbtp != NULL){
3983 struct a_tty_bind_tree *tmp;
3985 if((tmp = tbtp->tbt_childs) != NULL)
3986 a_tty__bind_tree_free(tmp);
3988 tmp = tbtp->tbt_sibling;
3989 n_free(tbtp);
3990 tbtp = tmp;
3992 NYD2_LEAVE;
3994 # endif /* HAVE_KEY_BINDINGS */
3996 FL void
3997 n_tty_init(void){
3998 NYD_ENTER;
4000 if(ok_blook(line_editor_disable))
4001 goto jleave;
4003 /* Load the history file */
4004 # ifdef HAVE_HISTORY
4005 a_tty_hist_load();
4006 # endif
4008 /* Force immediate resolve for anything which follows */
4009 n_psonce |= n_PSO_LINE_EDITOR_INIT;
4011 # ifdef HAVE_KEY_BINDINGS
4012 /* `bind's (and `unbind's) done from within resource files couldn't be
4013 * performed for real since our termcap driver wasn't yet loaded, and we
4014 * can't perform automatic init since the user may have disallowed so */
4015 /* C99 */{ /* TODO outsource into own file */
4016 struct a_tty_bind_ctx *tbcp;
4017 enum n_go_input_flags gif;
4019 for(gif = 0; gif < n__GO_INPUT_CTX_MAX1; ++gif)
4020 for(tbcp = a_tty.tg_bind[gif]; tbcp != NULL; tbcp = tbcp->tbc_next)
4021 if((tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
4022 a_TTY_BIND_RESOLVE)
4023 a_tty_bind_resolve(tbcp);
4026 /* And we want to (try to) install some default key bindings */
4027 if(!ok_blook(line_editor_no_defaults)){
4028 char buf[8];
4029 struct a_tty_bind_parse_ctx tbpc;
4030 struct a_tty_bind_builtin_tuple const *tbbtp, *tbbtp_max;
4031 ui32_t flags;
4033 buf[0] = '$', buf[1] = '\'', buf[2] = '\\', buf[3] = 'c',
4034 buf[5] = '\'', buf[6] = '\0';
4036 tbbtp = a_tty_bind_base_tuples;
4037 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_base_tuples)];
4038 flags = n_GO_INPUT_CTX_BASE;
4039 jbuiltin_redo:
4040 for(; tbbtp < tbbtp_max; ++tbbtp){
4041 memset(&tbpc, 0, sizeof tbpc);
4042 tbpc.tbpc_cmd = "bind";
4043 if(tbbtp->tbbt_iskey){
4044 buf[4] = tbbtp->tbbt_ckey;
4045 tbpc.tbpc_in_seq = buf;
4046 }else
4047 tbpc.tbpc_in_seq = savecatsep(":", '\0',
4048 n_termcap_name_of_query(tbbtp->tbbt_query));
4049 tbpc.tbpc_exp.s = n_UNCONST(tbbtp->tbbt_exp[0] == '\0'
4050 ? a_tty_bind_fun_names[(ui8_t)tbbtp->tbbt_exp[1]]
4051 : tbbtp->tbbt_exp);
4052 tbpc.tbpc_exp.l = strlen(tbpc.tbpc_exp.s);
4053 tbpc.tbpc_flags = flags;
4054 /* ..but don't want to overwrite any user settings */
4055 a_tty_bind_create(&tbpc, FAL0);
4057 if(flags == n_GO_INPUT_CTX_BASE){
4058 tbbtp = a_tty_bind_default_tuples;
4059 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_default_tuples)];
4060 flags = n_GO_INPUT_CTX_DEFAULT;
4061 goto jbuiltin_redo;
4064 # endif /* HAVE_KEY_BINDINGS */
4066 jleave:
4067 NYD_LEAVE;
4070 FL void
4071 n_tty_destroy(bool_t xit_fastpath){
4072 NYD_ENTER;
4074 if(!(n_psonce & n_PSO_LINE_EDITOR_INIT))
4075 goto jleave;
4077 /* Write the history file */
4078 # ifdef HAVE_HISTORY
4079 if(!xit_fastpath)
4080 a_tty_hist_save();
4081 # endif
4083 # if defined HAVE_KEY_BINDINGS && defined HAVE_DEBUG
4084 n_go_command(n_GO_INPUT_NONE, "unbind * *");
4085 # endif
4087 # ifdef HAVE_DEBUG
4088 memset(&a_tty, 0, sizeof a_tty);
4090 n_psonce &= ~n_PSO_LINE_EDITOR_INIT;
4091 # endif
4092 jleave:
4093 NYD_LEAVE;
4096 FL int
4097 (n_tty_readline)(enum n_go_input_flags gif, char const *prompt,
4098 char **linebuf, size_t *linesize, size_t n, bool_t *histok_or_null
4099 n_MEMORY_DEBUG_ARGS){
4100 struct a_tty_line tl;
4101 struct n_string xprompt;
4102 # ifdef HAVE_COLOUR
4103 char *posbuf, *pos;
4104 # endif
4105 ssize_t nn;
4106 NYD_ENTER;
4108 assert(!ok_blook(line_editor_disable));
4109 if(!(n_psonce & n_PSO_LINE_EDITOR_INIT))
4110 n_tty_init();
4111 assert(n_psonce & n_PSO_LINE_EDITOR_INIT);
4113 # ifdef HAVE_COLOUR
4114 n_colour_env_create(n_COLOUR_CTX_MLE, n_tty_fp, FAL0);
4116 /* .tl_pos_buf is a hack */
4117 posbuf = pos = NULL;
4119 if(n_COLOUR_IS_ACTIVE()){
4120 char const *ccol;
4121 struct n_colour_pen *ccp;
4122 struct str const *sp;
4124 if((ccp = n_colour_pen_create(n_COLOUR_ID_MLE_POSITION, NULL)) != NULL &&
4125 (sp = n_colour_pen_to_str(ccp)) != NULL){
4126 ccol = sp->s;
4127 if((sp = n_colour_reset_to_str()) != NULL){
4128 size_t l1, l2;
4130 l1 = strlen(ccol);
4131 l2 = strlen(sp->s);
4132 posbuf = n_autorec_alloc(l1 + 4 + l2 +1);
4133 memcpy(posbuf, ccol, l1);
4134 pos = &posbuf[l1];
4135 memcpy(&pos[4], sp->s, ++l2);
4140 if(posbuf == NULL){
4141 posbuf = pos = n_autorec_alloc(4 +1);
4142 pos[4] = '\0';
4144 # endif /* HAVE_COLOUR */
4146 memset(&tl, 0, sizeof tl);
4147 tl.tl_goinflags = gif;
4149 # ifdef HAVE_KEY_BINDINGS
4150 /* C99 */{
4151 char const *cp;
4153 if((cp = ok_vlook(bind_timeout)) != NULL){
4154 ui64_t uib;
4156 n_idec_ui64_cp(&uib, cp, 0, NULL);
4158 if(uib > 0 &&
4159 /* Convert to tenths of a second, unfortunately */
4160 (uib = (uib + 99) / 100) <= a_TTY_BIND_TIMEOUT_MAX)
4161 tl.tl_bind_timeout = (ui8_t)uib;
4162 else if(n_poption & n_PO_D_V)
4163 n_err(_("Ignoring invalid *bind-timeout*: %s\n"), cp);
4167 if(a_tty.tg_bind_isdirty)
4168 a_tty_bind_tree_teardown();
4169 if(a_tty.tg_bind_cnt > 0 && !a_tty.tg_bind_isbuild)
4170 a_tty_bind_tree_build();
4171 tl.tl_bind_tree_hmap = &a_tty.tg_bind_tree[gif & n__GO_INPUT_CTX_MASK];
4172 tl.tl_bind_shcut_cancel =
4173 &a_tty.tg_bind_shcut_cancel[gif & n__GO_INPUT_CTX_MASK];
4174 tl.tl_bind_shcut_prompt_char =
4175 &a_tty.tg_bind_shcut_prompt_char[gif & n__GO_INPUT_CTX_MASK];
4176 # endif /* HAVE_KEY_BINDINGS */
4178 # ifdef HAVE_COLOUR
4179 tl.tl_pos_buf = posbuf;
4180 tl.tl_pos = pos;
4181 # endif
4183 if(!(gif & n_GO_INPUT_PROMPT_NONE)){
4184 n_string_creat_auto(&xprompt);
4186 if((tl.tl_prompt_width = n_tty_create_prompt(&xprompt, prompt, gif)
4187 ) > 0){
4188 tl.tl_prompt = n_string_cp_const(&xprompt);
4189 tl.tl_prompt_length = (ui32_t)xprompt.s_len;
4193 tl.tl_line.cbuf = *linebuf;
4194 if(n != 0){
4195 tl.tl_defc.s = savestrbuf(*linebuf, n);
4196 tl.tl_defc.l = n;
4198 tl.tl_x_buf = linebuf;
4199 tl.tl_x_bufsize = linesize;
4201 a_tty.tg_line = &tl;
4202 a_tty_sigs_up();
4203 n_TERMCAP_RESUME(FAL0);
4204 a_tty_term_mode(TRU1);
4205 nn = a_tty_readline(&tl, n, histok_or_null n_MEMORY_DEBUG_ARGSCALL);
4206 n_COLOUR( n_colour_env_gut(); )
4207 a_tty_term_mode(FAL0);
4208 n_TERMCAP_SUSPEND(FAL0);
4209 a_tty_sigs_down();
4210 a_tty.tg_line = NULL;
4212 NYD_LEAVE;
4213 return (int)nn;
4216 FL void
4217 n_tty_addhist(char const *s, enum n_go_input_flags gif){
4218 # ifdef HAVE_HISTORY
4219 /* Super-Heavy-Metal: block all sigs, avoid leaks+ on jump */
4220 ui32_t l;
4221 struct a_tty_hist *thp, *othp, *ythp;
4222 # endif
4223 NYD_ENTER;
4224 n_UNUSED(s);
4225 n_UNUSED(gif);
4227 # ifdef HAVE_HISTORY
4228 if(*s == '\0' ||
4229 (!(n_psonce & n_PSO_LINE_EDITOR_INIT) && !(n_pstate & n_PS_ROOT)) ||
4230 a_tty.tg_hist_size_max == 0 ||
4231 ok_blook(line_editor_disable) ||
4232 ((gif & n_GO_INPUT_HIST_GABBY) && !ok_blook(history_gabby)))
4233 goto j_leave;
4235 l = (ui32_t)strlen(s);
4237 /* Eliminating duplicates is expensive, but simply inacceptable so
4238 * during the load of a potentially large history file! */
4239 if(n_psonce & n_PSO_LINE_EDITOR_INIT)
4240 for(thp = a_tty.tg_hist; thp != NULL; thp = thp->th_older)
4241 if(thp->th_len == l && !strcmp(thp->th_dat, s)){
4242 hold_all_sigs(); /* TODO */
4243 thp->th_flags = (gif & a_TTY_HIST_CTX_MASK) |
4244 (gif & n_GO_INPUT_HIST_GABBY ? a_TTY_HIST_GABBY : 0);
4245 othp = thp->th_older;
4246 ythp = thp->th_younger;
4247 if(othp != NULL)
4248 othp->th_younger = ythp;
4249 else
4250 a_tty.tg_hist_tail = ythp;
4251 if(ythp != NULL)
4252 ythp->th_older = othp;
4253 else
4254 a_tty.tg_hist = othp;
4255 goto jleave;
4257 hold_all_sigs();
4259 ++a_tty.tg_hist_size;
4260 if((n_psonce & n_PSO_LINE_EDITOR_INIT) &&
4261 a_tty.tg_hist_size > a_tty.tg_hist_size_max){
4262 --a_tty.tg_hist_size;
4263 if((thp = a_tty.tg_hist_tail) != NULL){
4264 if((a_tty.tg_hist_tail = thp->th_younger) == NULL)
4265 a_tty.tg_hist = NULL;
4266 else
4267 a_tty.tg_hist_tail->th_older = NULL;
4268 n_free(thp);
4272 thp = n_alloc(n_VSTRUCT_SIZEOF(struct a_tty_hist, th_dat) + l +1);
4273 thp->th_len = l;
4274 thp->th_flags = (gif & a_TTY_HIST_CTX_MASK) |
4275 (gif & n_GO_INPUT_HIST_GABBY ? a_TTY_HIST_GABBY : 0);
4276 memcpy(thp->th_dat, s, l +1);
4277 jleave:
4278 if((thp->th_older = a_tty.tg_hist) != NULL)
4279 a_tty.tg_hist->th_younger = thp;
4280 else
4281 a_tty.tg_hist_tail = thp;
4282 thp->th_younger = NULL;
4283 a_tty.tg_hist = thp;
4285 rele_all_sigs();
4286 j_leave:
4287 # endif /* HAVE_HISTORY */
4288 NYD_LEAVE;
4291 # ifdef HAVE_HISTORY
4292 FL int
4293 c_history(void *v){
4294 siz_t entry;
4295 struct a_tty_hist *thp;
4296 char **argv;
4297 NYD_ENTER;
4299 if(ok_blook(line_editor_disable)){
4300 n_err(_("history: *line-editor-disable* is set\n"));
4301 goto jerr;
4304 if(!(n_psonce & n_PSO_LINE_EDITOR_INIT)){
4305 n_tty_init();
4306 assert(n_psonce & n_PSO_LINE_EDITOR_INIT);
4309 if(*(argv = v) == NULL)
4310 goto jlist;
4311 if(argv[1] != NULL)
4312 goto jerr;
4313 if(!asccasecmp(*argv, "show"))
4314 goto jlist;
4315 if(!asccasecmp(*argv, "clear"))
4316 goto jclear;
4318 if(!asccasecmp(*argv, "load")){
4319 if(!a_tty_hist_load())
4320 v = NULL;
4321 goto jleave;
4323 if(!asccasecmp(*argv, "save")){
4324 if(!a_tty_hist_save())
4325 v = NULL;
4326 goto jleave;
4329 if((n_idec_siz_cp(&entry, *argv, 10, NULL
4330 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
4331 ) == n_IDEC_STATE_CONSUMED)
4332 goto jentry;
4333 jerr:
4334 n_err(_("Synopsis: history: %s\n"),
4335 /* Same string as in cmd-tab.h, still hoping...) */
4336 _("<show (default)|load|save|clear> or select history <NO>"));
4337 v = NULL;
4338 jleave:
4339 NYD_LEAVE;
4340 return (v == NULL ? !STOP : !OKAY); /* xxx 1:bad 0:good -- do some */
4342 jlist:{
4343 size_t no, l, b;
4344 FILE *fp;
4346 if(a_tty.tg_hist == NULL)
4347 goto jleave;
4349 if((fp = Ftmp(NULL, "hist", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
4350 n_perr(_("tmpfile"), 0);
4351 v = NULL;
4352 goto jleave;
4355 no = a_tty.tg_hist_size;
4356 l = b = 0;
4358 for(thp = a_tty.tg_hist; thp != NULL;
4359 --no, ++l, thp = thp->th_older){
4360 char c1, c2;
4362 b += thp->th_len;
4364 switch(thp->th_flags & a_TTY_HIST_CTX_MASK){
4365 default:
4366 case a_TTY_HIST_CTX_DEFAULT:
4367 c1 = 'd';
4368 break;
4369 case a_TTY_HIST_CTX_COMPOSE:
4370 c1 = 'c';
4371 break;
4373 c2 = (thp->th_flags & a_TTY_HIST_GABBY) ? '*' : ' ';
4375 if(n_poption & n_PO_D_V)
4376 fprintf(fp, "# Length +%" PRIu32 ", total %" PRIuZ "\n",
4377 thp->th_len, b);
4378 fprintf(fp, "%c%c%4" PRIuZ "\t%s\n", c1, c2, no, thp->th_dat);
4381 page_or_print(fp, l);
4382 Fclose(fp);
4384 goto jleave;
4386 jclear:
4387 while((thp = a_tty.tg_hist) != NULL){
4388 a_tty.tg_hist = thp->th_older;
4389 n_free(thp);
4391 a_tty.tg_hist_tail = NULL;
4392 a_tty.tg_hist_size = 0;
4393 goto jleave;
4395 jentry:{
4396 siz_t ep;
4398 ep = (entry < 0) ? -entry : entry;
4400 if(ep != 0 && UICMP(z, ep, <=, a_tty.tg_hist_size)){
4401 if(ep != entry)
4402 --ep;
4403 else
4404 ep = (siz_t)a_tty.tg_hist_size - ep;
4405 for(thp = a_tty.tg_hist;; thp = thp->th_older){
4406 assert(thp != NULL);
4407 if(ep-- == 0){
4408 n_go_input_inject((n_GO_INPUT_INJECT_COMMIT |
4409 n_GO_INPUT_INJECT_HISTORY), v = thp->th_dat, thp->th_len);
4410 break;
4413 }else{
4414 n_err(_("`history': no such entry: %" PRIdZ "\n"), entry);
4415 v = NULL;
4418 goto jleave;
4420 # endif /* HAVE_HISTORY */
4422 # ifdef HAVE_KEY_BINDINGS
4423 FL int
4424 c_bind(void *v){
4425 struct a_tty_bind_ctx *tbcp;
4426 enum n_go_input_flags gif;
4427 bool_t aster, show;
4428 union {char const *cp; char *p; char c;} c;
4429 struct n_cmd_arg_ctx *cacp;
4430 NYD_ENTER;
4432 cacp = v;
4434 c.cp = cacp->cac_arg->ca_arg.ca_str.s;
4435 if(cacp->cac_no == 1)
4436 show = TRU1;
4437 else
4438 show = !asccasecmp(cacp->cac_arg->ca_next->ca_arg.ca_str.s, "show");
4439 aster = FAL0;
4441 if((gif = a_tty_bind_ctx_find(c.cp)) == (enum n_go_input_flags)-1){
4442 if(!(aster = n_is_all_or_aster(c.cp)) || !show){
4443 n_err(_("`bind': invalid context: %s\n"), c.cp);
4444 v = NULL;
4445 goto jleave;
4447 gif = 0;
4450 if(show){
4451 ui32_t lns;
4452 FILE *fp;
4454 if((fp = Ftmp(NULL, "bind", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
4455 n_perr(_("tmpfile"), 0);
4456 v = NULL;
4457 goto jleave;
4460 lns = 0;
4461 for(;;){
4462 for(tbcp = a_tty.tg_bind[gif]; tbcp != NULL;
4463 ++lns, tbcp = tbcp->tbc_next){
4464 /* Print the bytes of resolved terminal capabilities, then */
4465 if((n_poption & n_PO_D_V) &&
4466 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)
4467 ) == a_TTY_BIND_RESOLVE){
4468 char cbuf[8];
4469 union {wchar_t const *wp; char const *cp;} u;
4470 si32_t entlen;
4471 ui32_t cnvlen;
4472 char const *cnvdat, *bsep, *cbufp;
4474 putc('#', fp);
4475 putc(' ', fp);
4477 cbuf[0] = '=', cbuf[2] = '\0';
4478 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len;
4479 cnvlen > 0;){
4480 if(cnvdat != tbcp->tbc_cnv)
4481 putc(',', fp);
4483 /* {si32_t buf_len_iscap;} */
4484 entlen = *n_UNALIGN(si32_t const*,cnvdat);
4485 if(entlen & SI32_MIN){
4486 /* struct{si32_t buf_len_iscap; si32_t cap_len;
4487 * char buf[]+NUL;} */
4488 for(bsep = n_empty,
4489 u.cp = (char const*)
4490 &n_UNALIGN(si32_t const*,cnvdat)[2];
4491 (c.c = *u.cp) != '\0'; ++u.cp){
4492 if(asciichar(c.c) && !cntrlchar(c.c))
4493 cbuf[1] = c.c, cbufp = cbuf;
4494 else
4495 cbufp = n_empty;
4496 fprintf(fp, "%s\\x%02X%s",
4497 bsep, (ui32_t)(ui8_t)c.c, cbufp);
4498 bsep = " ";
4500 entlen &= SI32_MAX;
4501 }else
4502 putc('-', fp);
4504 cnvlen -= entlen;
4505 cnvdat += entlen;
4508 fputs("\n ", fp);
4509 ++lns;
4512 fprintf(fp, "%sbind %s %s %s%s%s\n",
4513 ((tbcp->tbc_flags & a_TTY_BIND_DEFUNCT)
4514 /* I18N: `bind' sequence not working, either because it is
4515 * I18N: using Unicode and that is not available in the locale,
4516 * I18N: or a termcap(5)/terminfo(5) sequence won't work out */
4517 ? _("# <Defunctional> ") : n_empty),
4518 a_tty_bind_ctx_maps[gif].tbcm_name, tbcp->tbc_seq,
4519 n_shexp_quote_cp(tbcp->tbc_exp, TRU1),
4520 (tbcp->tbc_flags & a_TTY_BIND_NOCOMMIT ? n_at : n_empty),
4521 (!(n_poption & n_PO_D_VV) ? n_empty
4522 : (tbcp->tbc_flags & a_TTY_BIND_FUN_INTERNAL
4523 ? _(" # MLE internal") : n_empty))
4526 if(!aster || ++gif >= n__GO_INPUT_CTX_MAX1)
4527 break;
4529 page_or_print(fp, lns);
4531 Fclose(fp);
4532 }else{
4533 struct a_tty_bind_parse_ctx tbpc;
4534 struct n_cmd_arg *cap;
4536 memset(&tbpc, 0, sizeof tbpc);
4537 tbpc.tbpc_cmd = cacp->cac_desc->cad_name;
4538 tbpc.tbpc_in_seq = (cap = cacp->cac_arg->ca_next)->ca_arg.ca_str.s;
4539 if((cap = cap->ca_next) != NULL){
4540 tbpc.tbpc_exp.s = cap->ca_arg.ca_str.s;
4541 tbpc.tbpc_exp.l = cap->ca_arg.ca_str.l;
4543 tbpc.tbpc_flags = gif;
4544 if(!a_tty_bind_create(&tbpc, TRU1))
4545 v = NULL;
4547 jleave:
4548 NYD_LEAVE;
4549 return (v != NULL) ? n_EXIT_OK : n_EXIT_ERR;
4552 FL int
4553 c_unbind(void *v){
4554 struct a_tty_bind_parse_ctx tbpc;
4555 struct a_tty_bind_ctx *tbcp;
4556 enum n_go_input_flags gif;
4557 bool_t aster;
4558 union {char const *cp; char *p;} c;
4559 struct n_cmd_arg_ctx *cacp;
4560 NYD_ENTER;
4562 cacp = v;
4563 c.cp = cacp->cac_arg->ca_arg.ca_str.s;
4564 aster = FAL0;
4566 if((gif = a_tty_bind_ctx_find(c.cp)) == (enum n_go_input_flags)-1){
4567 if(!(aster = n_is_all_or_aster(c.cp))){
4568 n_err(_("`unbind': invalid context: %s\n"), c.cp);
4569 v = NULL;
4570 goto jleave;
4572 gif = 0;
4575 c.cp = cacp->cac_arg->ca_next->ca_arg.ca_str.s;
4576 jredo:
4577 if(n_is_all_or_aster(c.cp)){
4578 while((tbcp = a_tty.tg_bind[gif]) != NULL){
4579 memset(&tbpc, 0, sizeof tbpc);
4580 tbpc.tbpc_tbcp = tbcp;
4581 tbpc.tbpc_flags = gif;
4582 a_tty_bind_del(&tbpc);
4584 }else{
4585 memset(&tbpc, 0, sizeof tbpc);
4586 tbpc.tbpc_cmd = cacp->cac_desc->cad_name;
4587 tbpc.tbpc_in_seq = c.cp;
4588 tbpc.tbpc_flags = gif;
4590 if(n_UNLIKELY(!a_tty_bind_parse(FAL0, &tbpc)))
4591 v = NULL;
4592 else if(n_UNLIKELY((tbcp = tbpc.tbpc_tbcp) == NULL)){
4593 n_err(_("`unbind': no such `bind'ing: %s %s\n"),
4594 a_tty_bind_ctx_maps[gif].tbcm_name, c.cp);
4595 v = NULL;
4596 }else
4597 a_tty_bind_del(&tbpc);
4600 if(aster && ++gif < n__GO_INPUT_CTX_MAX1)
4601 goto jredo;
4602 jleave:
4603 NYD_LEAVE;
4604 return (v != NULL) ? n_EXIT_OK : n_EXIT_ERR;
4606 # endif /* HAVE_KEY_BINDINGS */
4608 #else /* HAVE_MLE */
4610 * The really-nothing-at-all implementation
4613 static void
4614 a_tty_signal(int sig){
4615 /* Prototype at top */
4616 # ifdef HAVE_TERMCAP
4617 sigset_t nset, oset;
4618 # endif
4619 NYD_X; /* Signal handler */
4620 n_UNUSED(sig);
4622 # ifdef HAVE_TERMCAP
4623 n_TERMCAP_SUSPEND(TRU1);
4624 a_tty_sigs_down();
4626 sigemptyset(&nset);
4627 sigaddset(&nset, sig);
4628 sigprocmask(SIG_UNBLOCK, &nset, &oset);
4629 n_raise(sig);
4630 /* When we come here we'll continue editing, so reestablish */
4631 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
4633 a_tty_sigs_up();
4634 n_TERMCAP_RESUME(TRU1);
4635 # endif /* HAVE_TERMCAP */
4638 # if 0
4639 FL void
4640 n_tty_init(void){
4641 NYD_ENTER;
4642 NYD_LEAVE;
4645 FL void
4646 n_tty_destroy(bool_t xit_fastpath){
4647 NYD_ENTER;
4648 n_UNUSED(xit_fastpath);
4649 NYD_LEAVE;
4651 # endif /* 0 */
4653 FL int
4654 (n_tty_readline)(enum n_go_input_flags gif, char const *prompt,
4655 char **linebuf, size_t *linesize, size_t n, bool_t *histok_or_null
4656 n_MEMORY_DEBUG_ARGS){
4657 struct n_string xprompt;
4658 int rv;
4659 NYD_ENTER;
4660 n_UNUSED(histok_or_null);
4662 if(!(gif & n_GO_INPUT_PROMPT_NONE)){
4663 if(n_tty_create_prompt(n_string_creat_auto(&xprompt), prompt, gif) > 0){
4664 fwrite(xprompt.s_dat, 1, xprompt.s_len, n_tty_fp);
4665 fflush(n_tty_fp);
4669 # ifdef HAVE_TERMCAP
4670 a_tty_sigs_up();
4671 n_TERMCAP_RESUME(FAL0);
4672 # endif
4673 rv = (readline_restart)(n_stdin, linebuf, linesize, n
4674 n_MEMORY_DEBUG_ARGSCALL);
4675 # ifdef HAVE_TERMCAP
4676 n_TERMCAP_SUSPEND(FAL0);
4677 a_tty_sigs_down();
4678 # endif
4679 NYD_LEAVE;
4680 return rv;
4683 FL void
4684 n_tty_addhist(char const *s, enum n_go_input_flags gif){
4685 NYD_ENTER;
4686 n_UNUSED(s);
4687 n_UNUSED(gif);
4688 NYD_LEAVE;
4690 #endif /* nothing at all */
4692 #undef a_TTY_SIGNALS
4693 /* s-it-mode */