n_shexp_parse_token(): show erroneous substring
[s-mailx.git] / tty.c
blob7386c6ea3eb18f2a124cbf738cea96d38c3d772a
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 - 2017 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 if (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) >= 0)
126 rv = (boolify(termios_state.ts_linebuf, UIZ_MAX,
127 noninteract_default) > 0);
128 jrestore:
129 safe_signal(SIGHUP, ohup);
130 safe_signal(SIGINT, oint);
131 jleave:
132 NYD_LEAVE;
133 if (sig != 0)
134 n_raise(sig);
135 return rv;
138 #ifdef HAVE_SOCKETS
139 FL char *
140 getuser(char const * volatile query) /* TODO v15-compat obsolete */
142 sighandler_type volatile oint, ohup;
143 char * volatile user = NULL;
144 int volatile sig;
145 NYD_ENTER;
147 if (query == NULL)
148 query = _("User: ");
150 oint = safe_signal(SIGINT, SIG_IGN);
151 ohup = safe_signal(SIGHUP, SIG_IGN);
152 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
153 goto jrestore;
154 safe_signal(SIGINT, &a_tty__acthdl);
155 safe_signal(SIGHUP, &a_tty__acthdl);
157 if (n_go_input(n_GO_INPUT_CTX_DEFAULT | n_GO_INPUT_NL_ESC, query,
158 &termios_state.ts_linebuf, &termios_state.ts_linesize, NULL,NULL) >= 0)
159 user = termios_state.ts_linebuf;
161 jrestore:
162 safe_signal(SIGHUP, ohup);
163 safe_signal(SIGINT, oint);
165 NYD_LEAVE;
166 if (sig != 0)
167 n_raise(sig);
168 return user;
171 FL char *
172 getpassword(char const *query)/* TODO v15: use _only_ n_tty_fp! */
174 sighandler_type volatile oint, ohup;
175 struct termios tios;
176 char * volatile pass;
177 int volatile sig;
178 NYD_ENTER;
180 pass = NULL;
181 if(!(n_psonce & n_PSO_TTYIN))
182 goto j_leave;
184 if (query == NULL)
185 query = _("Password: ");
186 fputs(query, n_tty_fp);
187 fflush(n_tty_fp);
189 /* FIXME everywhere: tcsetattr() generates SIGTTOU when we're not in
190 * FIXME foreground pgrp, and can fail with EINTR!! also affects
191 * FIXME termios_state_reset() */
192 tcgetattr(STDIN_FILENO, &termios_state.ts_tios);
193 memcpy(&tios, &termios_state.ts_tios, sizeof tios);
194 termios_state.ts_needs_reset = TRU1;
195 tios.c_iflag &= ~(ISTRIP);
196 tios.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
198 oint = safe_signal(SIGINT, SIG_IGN);
199 ohup = safe_signal(SIGHUP, SIG_IGN);
200 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
201 goto jrestore;
202 safe_signal(SIGINT, &a_tty__acthdl);
203 safe_signal(SIGHUP, &a_tty__acthdl);
205 tcsetattr(STDIN_FILENO, TCSAFLUSH, &tios);
206 if (readline_restart(n_stdin, &termios_state.ts_linebuf,
207 &termios_state.ts_linesize, 0) >= 0)
208 pass = termios_state.ts_linebuf;
209 jrestore:
210 termios_state_reset();
211 putc('\n', n_tty_fp);
213 safe_signal(SIGHUP, ohup);
214 safe_signal(SIGINT, oint);
215 NYD_LEAVE;
216 if (sig != 0)
217 n_raise(sig);
218 j_leave:
219 return pass;
221 #endif /* HAVE_SOCKETS */
223 FL ui32_t
224 n_tty_create_prompt(struct n_string *store, char const *xprompt,
225 enum n_go_input_flags gif){
226 struct n_visual_info_ctx vic;
227 struct str in, out;
228 ui32_t pwidth;
229 char const *cp;
230 NYD2_ENTER;
232 /* Prompt creation indicates that prompt printing is directly ahead, so take
233 * this opportunity of UI-in-a-known-state and advertise the error ring */
234 #ifdef HAVE_ERRORS
235 if((n_psonce & (n_PSO_INTERACTIVE | n_PSO_ERRORS_NOTED)
236 ) == n_PSO_INTERACTIVE && (n_pstate & n_PS_ERRORS_PROMPT)){
237 n_psonce |= n_PSO_ERRORS_NOTED;
238 fprintf(n_stdout, _("There are new messages in the error message ring "
239 "(denoted by %s)\n"
240 " The `errors' command manages this message ring\n"),
241 V_(n_error));
243 #endif
245 jredo:
246 n_string_trunc(store, 0);
248 if(gif & n_GO_INPUT_PROMPT_NONE){
249 pwidth = 0;
250 goto jleave;
252 #ifdef HAVE_ERRORS
253 if(n_pstate & n_PS_ERRORS_PROMPT){
254 n_pstate &= ~n_PS_ERRORS_PROMPT;
255 store = n_string_push_cp(store, V_(n_error));
256 store = n_string_push_c(store, '#');
257 store = n_string_push_c(store, ' ');
259 #endif
261 cp = (gif & n_GO_INPUT_PROMPT_EVAL)
262 ? (gif & n_GO_INPUT_NL_FOLLOW ? ok_vlook(prompt2) : ok_vlook(prompt))
263 : xprompt;
264 if(cp != NULL && *cp != '\0'){
265 enum n_shexp_state shs;
267 store = n_string_push_cp(store, cp);
268 in.s = n_string_cp(store);
269 in.l = store->s_len;
270 out = in;
271 store = n_string_drop_ownership(store);
273 shs = n_shexp_parse_token((n_SHEXP_PARSE_LOG |
274 n_SHEXP_PARSE_IGNORE_EMPTY | n_SHEXP_PARSE_QUOTE_AUTO_FIXED |
275 n_SHEXP_PARSE_QUOTE_AUTO_DSQ), store, &in, NULL);
276 if((shs & n_SHEXP_STATE_ERR_MASK) || !(shs & n_SHEXP_STATE_STOP)){
277 store = n_string_clear(store);
278 store = n_string_take_ownership(store, out.s, out.l +1, out.l);
279 jeeval:
280 n_err(_("*prompt2?* evaluation failed, actively unsetting it\n"));
281 if(gif & n_GO_INPUT_NL_FOLLOW)
282 ok_vclear(prompt2);
283 else
284 ok_vclear(prompt);
285 goto jredo;
288 if(!store->s_auto)
289 free(out.s);
292 /* Make all printable TODO not know, we want to pass through ESC/CSI! */
293 #if 0
294 in.s = n_string_cp(store);
295 in.l = store->s_len;
296 makeprint(&in, &out);
297 store = n_string_assign_buf(store, out.s, out.l);
298 free(out.s);
299 #endif
301 /* We need the visual width.. */
302 memset(&vic, 0, sizeof vic);
303 vic.vic_indat = n_string_cp(store);
304 vic.vic_inlen = store->s_len;
305 for(pwidth = 0; vic.vic_inlen > 0;){
306 /* but \[ .. \] is not taken into account */
307 if(vic.vic_indat[0] == '\\' && vic.vic_inlen > 1 &&
308 vic.vic_indat[1] == '['){
309 size_t i;
311 i = PTR2SIZE(vic.vic_indat - store->s_dat);
312 store = n_string_cut(store, i, 2);
313 cp = &n_string_cp(store)[i];
314 i = store->s_len - i;
315 for(;; ++cp, --i){
316 if(i < 2){
317 n_err(_("Open \\[ sequence not closed in *prompt2?*\n"));
318 goto jeeval;
320 if(cp[0] == '\\' && cp[1] == ']')
321 break;
323 i = PTR2SIZE(cp - store->s_dat);
324 store = n_string_cut(store, i, 2);
325 vic.vic_indat = &n_string_cp(store)[i];
326 vic.vic_inlen = store->s_len - i;
327 }else if(!n_visual_info(&vic, n_VISUAL_INFO_WIDTH_QUERY |
328 n_VISUAL_INFO_ONE_CHAR)){
329 n_err(_("Character set error in evaluation of *prompt2?*\n"));
330 goto jeeval;
331 }else{
332 pwidth += (ui32_t)vic.vic_vi_width;
333 vic.vic_indat = vic.vic_oudat;
334 vic.vic_inlen = vic.vic_oulen;
338 /* And there may be colour support, too */
339 #ifdef HAVE_COLOUR
340 if(n_COLOUR_IS_ACTIVE()){
341 struct str const *psp, *rsp;
342 struct n_colour_pen *ccp;
344 if((ccp = n_colour_pen_create(n_COLOUR_ID_MLE_PROMPT, NULL)) != NULL &&
345 (psp = n_colour_pen_to_str(ccp)) != NULL &&
346 (rsp = n_colour_reset_to_str()) != NULL){
347 store = n_string_unshift_buf(store, psp->s, psp->l);
348 /*store =*/ n_string_push_buf(store, rsp->s, rsp->l);
351 #endif /* HAVE_COLOUR */
353 jleave:
354 NYD2_LEAVE;
355 return pwidth;
359 * MLE: the Mailx-Line-Editor, our homebrew editor
360 * (inspired from NetBSDs sh(1) and dash(1)s hetio.c).
362 * Only used in interactive mode.
363 * TODO . This code should be splitted in funs/raw input/bind modules.
364 * TODO . We work with wide characters, but not for buffer takeovers and
365 * TODO cell2save()ings. This should be changed. For the former the buffer
366 * TODO thus needs to be converted to wide first, and then simply be fed in.
367 * TODO . We repaint too much. To overcome this use the same approach that my
368 * TODO terminal library uses, add a true "virtual screen line" that stores
369 * TODO the actually visible content, keep a notion of "first modified slot"
370 * TODO and "last modified slot" (including "unknown" and "any" specials),
371 * TODO update that virtual instead, then synchronize what has truly changed.
372 * TODO I.e., add an indirection layer.
373 * TODO . No BIDI support.
374 * TODO . `bind': we currently use only one lookup tree.
375 * TODO For absolute graceful behaviour in conjunction (with HAVE_TERMCAP) we
376 * TODO need a lower level tree, which possibly combines bytes into "symbolic
377 * TODO wchar_t values", into "keys" that is, as applicable, and an upper
378 * TODO layer which only works on "keys" in order to possibly combine them
379 * TODO into key sequences. We can reuse existent tree code for that.
380 * TODO We need an additional hashmap which maps termcap/terminfo names to
381 * TODO (their byte representations and) a dynamically assigned unique
382 * TODO "symbolic wchar_t value". This implies we may have incompatibilities
383 * TODO when __STDC_ISO_10646__ is not defined. Also we do need takeover-
384 * TODO bytes storage, but it can be a string_creat_auto in the line struct.
385 * TODO Until then we can run into ambiguities; in rare occasions.
387 #ifdef HAVE_MLE
388 /* To avoid memory leaks etc. with the current codebase that simply longjmp(3)s
389 * we're forced to use the very same buffer--the one that is passed through to
390 * us from the outside--to store anything we need, i.e., a "struct cell[]", and
391 * convert that on-the-fly back to the plain char* result once we're done.
392 * To simplify our live, use savestr() buffers for all other needed memory */
394 # ifdef HAVE_KEY_BINDINGS
395 /* Default *bind-timeout* key-sequence continuation timeout, in tenths of
396 * a second. Must fit in 8-bit! Update the manual upon change! */
397 # define a_TTY_BIND_TIMEOUT 2
398 # define a_TTY_BIND_TIMEOUT_MAX SI8_MAX
400 n_CTAV(a_TTY_BIND_TIMEOUT_MAX <= UI8_MAX);
402 /* We have a chicken-and-egg problem with `bind' and our termcap layer,
403 * because we may not initialize the latter automatically to allow users to
404 * specify *termcap-disable* and let it mean exactly that.
405 * On the other hand users can be expected to use `bind' in resource file(s).
406 * Therefore bindings which involve termcap/terminfo sequences, and which are
407 * defined before n_PSO_STARTED signals usability of termcap/terminfo, will be
408 * (partially) delayed until tty_init() is called.
409 * And we preallocate space for the expansion of the resolved capability */
410 # define a_TTY_BIND_CAPNAME_MAX 15
411 # define a_TTY_BIND_CAPEXP_ROUNDUP 16
413 n_CTAV(n_ISPOW2(a_TTY_BIND_CAPEXP_ROUNDUP));
414 n_CTA(a_TTY_BIND_CAPEXP_ROUNDUP <= SI8_MAX / 2, "Variable must fit in 6-bit");
415 n_CTA(a_TTY_BIND_CAPEXP_ROUNDUP >= 8, "Variable too small");
416 # endif /* HAVE_KEY_BINDINGS */
418 /* The maximum size (of a_tty_cell's) in a line */
419 # define a_TTY_LINE_MAX SI32_MAX
421 /* (Some more CTAs around) */
422 n_CTA(a_TTY_LINE_MAX <= SI32_MAX,
423 "a_TTY_LINE_MAX larger than SI32_MAX, but the MLE uses 32-bit arithmetic");
425 /* When shall the visual screen be scrolled, in % of usable screen width */
426 # define a_TTY_SCROLL_MARGIN_LEFT 15
427 # define a_TTY_SCROLL_MARGIN_RIGHT 10
429 /* fexpand() flags for expand-on-tab */
430 # define a_TTY_TAB_FEXP_FL \
431 (FEXP_NOPROTO | FEXP_FULL | FEXP_SILENT | FEXP_MULTIOK)
433 /* Columns to ripoff: outermost may not be touched, plus position indicator.
434 * Must thus be at least 1, but should be >= 1+4 to dig the position indicator
435 * that we place (if there is sufficient space) */
436 # define a_TTY_WIDTH_RIPOFF 5
438 /* The implementation of the MLE functions always exists, and is based upon
439 * the a_TTY_BIND_FUN_* constants, so most of this enum is always necessary */
440 enum a_tty_bind_flags{
441 # ifdef HAVE_KEY_BINDINGS
442 a_TTY_BIND_RESOLVE = 1u<<8, /* Term cap. yet needs to be resolved */
443 a_TTY_BIND_DEFUNCT = 1u<<9, /* Unicode/term cap. used but not avail. */
444 a_TTY__BIND_MASK = a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT,
445 /* MLE fun assigned to a one-byte-sequence: this may be used for special
446 * key-sequence bypass processing */
447 a_TTY_BIND_MLE1CNTRL = 1u<<10,
448 a_TTY_BIND_NOCOMMIT = 1u<<11, /* Expansion shall be editable */
449 # endif
451 /* MLE internal commands */
452 a_TTY_BIND_FUN_INTERNAL = 1u<<15,
453 a_TTY__BIND_FUN_SHIFT = 16u,
454 a_TTY__BIND_FUN_SHIFTMAX = 24u,
455 a_TTY__BIND_FUN_MASK = ((1u << a_TTY__BIND_FUN_SHIFTMAX) - 1) &
456 ~((1u << a_TTY__BIND_FUN_SHIFT) - 1),
457 # define a_TTY_BIND_FUN_REDUCE(X) \
458 (((ui32_t)(X) & a_TTY__BIND_FUN_MASK) >> a_TTY__BIND_FUN_SHIFT)
459 # define a_TTY_BIND_FUN_EXPAND(X) \
460 (((ui32_t)(X) & (a_TTY__BIND_FUN_MASK >> a_TTY__BIND_FUN_SHIFT)) << \
461 a_TTY__BIND_FUN_SHIFT)
462 # undef a_X
463 # define a_X(N,I)\
464 a_TTY_BIND_FUN_ ## N = a_TTY_BIND_FUN_EXPAND(I),
466 a_X(BELL, 0)
467 a_X(GO_BWD, 1) a_X(GO_FWD, 2)
468 a_X(GO_WORD_BWD, 3) a_X(GO_WORD_FWD, 4)
469 a_X(GO_HOME, 5) a_X(GO_END, 6)
470 a_X(DEL_BWD, 7) a_X(DEL_FWD, 8)
471 a_X(SNARF_WORD_BWD, 9) a_X(SNARF_WORD_FWD, 10)
472 a_X(SNARF_END, 11) a_X(SNARF_LINE, 12)
473 a_X(HIST_BWD, 13) a_X(HIST_FWD, 14)
474 a_X(HIST_SRCH_BWD, 15) a_X(HIST_SRCH_FWD, 16)
475 a_X(REPAINT, 17)
476 a_X(QUOTE_RNDTRIP, 18)
477 a_X(PROMPT_CHAR, 19)
478 a_X(COMPLETE, 20)
479 a_X(PASTE, 21)
481 a_X(CANCEL, 22)
482 a_X(RESET, 23)
483 a_X(FULLRESET, 24)
484 a_X(COMMIT, 25) /* Must be last one! */
485 # undef a_X
487 a_TTY__BIND_LAST = 1<<25
489 # ifdef HAVE_KEY_BINDINGS
490 n_CTA((ui32_t)a_TTY_BIND_RESOLVE >= (ui32_t)n__GO_INPUT_CTX_MAX1,
491 "Bit carrier lower boundary must be raised to avoid value sharing");
492 # endif
493 n_CTA(a_TTY_BIND_FUN_EXPAND(a_TTY_BIND_FUN_COMMIT) <
494 (1 << a_TTY__BIND_FUN_SHIFTMAX),
495 "Bit carrier range must be expanded to represent necessary bits");
496 n_CTA(a_TTY__BIND_LAST >= (1u << a_TTY__BIND_FUN_SHIFTMAX),
497 "Bit carrier upper boundary must be raised to avoid value sharing");
498 n_CTA(UICMP(64, a_TTY__BIND_LAST, <=, SI32_MAX),
499 "Flag bits excess storage datatype" /* And we need one bit free */);
501 enum a_tty_fun_status{
502 a_TTY_FUN_STATUS_OK, /* Worked, next character */
503 a_TTY_FUN_STATUS_COMMIT, /* Line done */
504 a_TTY_FUN_STATUS_RESTART, /* Complete restart, reset multibyte etc. */
505 a_TTY_FUN_STATUS_END /* End, return EOF */
508 enum a_tty_visual_flags{
509 a_TTY_VF_NONE,
510 a_TTY_VF_MOD_CURSOR = 1u<<0, /* Cursor moved */
511 a_TTY_VF_MOD_CONTENT = 1u<<1, /* Content modified */
512 a_TTY_VF_MOD_DIRTY = 1u<<2, /* Needs complete repaint */
513 a_TTY_VF_MOD_SINGLE = 1u<<3, /* TODO Drop when indirection as above comes */
514 a_TTY_VF_REFRESH = a_TTY_VF_MOD_DIRTY | a_TTY_VF_MOD_CURSOR |
515 a_TTY_VF_MOD_CONTENT | a_TTY_VF_MOD_SINGLE,
516 a_TTY_VF_BELL = 1u<<8, /* Ring the bell */
517 a_TTY_VF_SYNC = 1u<<9, /* Flush/Sync I/O channel */
519 a_TTY_VF_ALL_MASK = a_TTY_VF_REFRESH | a_TTY_VF_BELL | a_TTY_VF_SYNC,
520 a_TTY__VF_LAST = a_TTY_VF_SYNC
523 # ifdef HAVE_KEY_BINDINGS
524 struct a_tty_bind_ctx{
525 struct a_tty_bind_ctx *tbc_next;
526 char *tbc_seq; /* quence as given (poss. re-quoted), in .tb__buf */
527 char *tbc_exp; /* ansion, in .tb__buf */
528 /* The .tbc_seq'uence with any terminal capabilities resolved; in fact an
529 * array of structures, the first entry of which is {si32_t buf_len_iscap;}
530 * where the signed bit indicates whether the buffer is a resolved terminal
531 * capability instead of a (possibly multibyte) character. In .tbc__buf */
532 char *tbc_cnv;
533 ui32_t tbc_seq_len;
534 ui32_t tbc_exp_len;
535 ui32_t tbc_cnv_len;
536 ui32_t tbc_flags;
537 char tbc__buf[n_VFIELD_SIZE(0)];
540 struct a_tty_bind_ctx_map{
541 enum n_go_input_flags tbcm_ctx;
542 char const tbcm_name[12]; /* Name of `bind' context */
544 # endif /* HAVE_KEY_BINDINGS */
546 struct a_tty_bind_builtin_tuple{
547 bool_t tbbt_iskey; /* Whether this is a control key; else termcap query */
548 char tbbt_ckey; /* Control code */
549 ui16_t tbbt_query; /* enum n_termcap_query (instead) */
550 char tbbt_exp[12]; /* String or [0]=NUL/[1]=BIND_FUN_REDUCE() */
552 n_CTA(n__TERMCAP_QUERY_MAX1 <= UI16_MAX,
553 "Enumeration cannot be stored in datatype");
555 # ifdef HAVE_KEY_BINDINGS
556 struct a_tty_bind_parse_ctx{
557 char const *tbpc_cmd; /* Command which parses */
558 char const *tbpc_in_seq; /* In: key sequence */
559 struct str tbpc_exp; /* In/Out: expansion (or NULL) */
560 struct a_tty_bind_ctx *tbpc_tbcp; /* Out: if yet existent */
561 struct a_tty_bind_ctx *tbpc_ltbcp; /* Out: the one before .tbpc_tbcp */
562 char *tbpc_seq; /* Out: normalized sequence */
563 char *tbpc_cnv; /* Out: sequence when read(2)ing it */
564 ui32_t tbpc_seq_len;
565 ui32_t tbpc_cnv_len;
566 ui32_t tbpc_cnv_align_mask; /* For creating a_tty_bind_ctx.tbc_cnv */
567 ui32_t tbpc_flags; /* n_go_input_flags | a_tty_bind_flags */
570 /* Input character tree */
571 struct a_tty_bind_tree{
572 struct a_tty_bind_tree *tbt_sibling; /* s at same level */
573 struct a_tty_bind_tree *tbt_childs; /* Sequence continues.. here */
574 struct a_tty_bind_tree *tbt_parent;
575 struct a_tty_bind_ctx *tbt_bind; /* NULL for intermediates */
576 wchar_t tbt_char; /* acter this level represents */
577 bool_t tbt_isseq; /* Belongs to multibyte sequence */
578 bool_t tbt_isseq_trail; /* ..is trailing byte of it */
579 ui8_t tbt__dummy[2];
581 # endif /* HAVE_KEY_BINDINGS */
583 struct a_tty_cell{
584 wchar_t tc_wc;
585 ui16_t tc_count; /* ..of bytes */
586 ui8_t tc_width; /* Visual width; TAB==UI8_MAX! */
587 bool_t tc_novis; /* Don't display visually as such (control character) */
588 char tc_cbuf[MB_LEN_MAX * 2]; /* .. plus reset shift sequence */
591 struct a_tty_global{
592 struct a_tty_line *tg_line; /* To be able to access it from signal hdl */
593 # ifdef HAVE_HISTORY
594 struct a_tty_hist *tg_hist;
595 struct a_tty_hist *tg_hist_tail;
596 size_t tg_hist_size;
597 size_t tg_hist_size_max;
598 # endif
599 # ifdef HAVE_KEY_BINDINGS
600 ui32_t tg_bind_cnt; /* Overall number of bindings */
601 bool_t tg_bind_isdirty;
602 bool_t tg_bind_isbuild;
603 # define a_TTY_SHCUT_MAX (3 +1) /* Note: update manual on change! */
604 ui8_t tg_bind__dummy[2];
605 char tg_bind_shcut_cancel[n__GO_INPUT_CTX_MAX1][a_TTY_SHCUT_MAX];
606 char tg_bind_shcut_prompt_char[n__GO_INPUT_CTX_MAX1][a_TTY_SHCUT_MAX];
607 struct a_tty_bind_ctx *tg_bind[n__GO_INPUT_CTX_MAX1];
608 struct a_tty_bind_tree *tg_bind_tree[n__GO_INPUT_CTX_MAX1][HSHSIZE];
609 # endif
610 struct termios tg_tios_old;
611 struct termios tg_tios_new;
613 # ifdef HAVE_KEY_BINDINGS
614 n_CTA(n__GO_INPUT_CTX_MAX1 == 3 && a_TTY_SHCUT_MAX == 4 &&
615 n_SIZEOF_FIELD(struct a_tty_global, tg_bind__dummy) == 2,
616 "Value results in array sizes that results in bad structure layout");
617 n_CTA(a_TTY_SHCUT_MAX > 1,
618 "Users need at least one shortcut, plus NUL terminator");
619 # endif
621 # ifdef HAVE_HISTORY
622 struct a_tty_hist{
623 struct a_tty_hist *th_older;
624 struct a_tty_hist *th_younger;
625 ui32_t th_isgabby : 1;
626 ui32_t th_len : 31;
627 char th_dat[n_VFIELD_SIZE(sizeof(ui32_t))];
629 # endif
631 struct a_tty_line{
632 /* Caller pointers */
633 char **tl_x_buf;
634 size_t *tl_x_bufsize;
635 /* Input processing */
636 # ifdef HAVE_KEY_BINDINGS
637 wchar_t tl_bind_takeover; /* Leftover byte to consume next */
638 ui8_t tl_bind_timeout; /* In-seq. inter-byte-timer, in 1/10th secs */
639 ui8_t tl__bind_dummy[3];
640 char (*tl_bind_shcut_cancel)[a_TTY_SHCUT_MAX]; /* Special _CANCEL control */
641 char (*tl_bind_shcut_prompt_char)[a_TTY_SHCUT_MAX]; /* ..for _PROMPT_CHAR */
642 struct a_tty_bind_tree *(*tl_bind_tree_hmap)[HSHSIZE]; /* Bind lookup tree */
643 struct a_tty_bind_tree *tl_bind_tree;
644 # endif
645 /* Line data / content handling */
646 ui32_t tl_count; /* ..of a_tty_cell's (<= a_TTY_LINE_MAX) */
647 ui32_t tl_cursor; /* Current a_tty_cell insertion point */
648 union{
649 char *cbuf; /* *.tl_x_buf */
650 struct a_tty_cell *cells;
651 } tl_line;
652 struct str tl_defc; /* Current default content */
653 size_t tl_defc_cursor_byte; /* Desired position of cursor after takeover */
654 struct str tl_savec; /* Saved default content */
655 struct str tl_pastebuf; /* Last snarfed data */
656 # ifdef HAVE_HISTORY
657 struct a_tty_hist *tl_hist; /* History cursor */
658 # endif
659 ui32_t tl_count_max; /* ..before buffer needs to grow */
660 /* Visual data representation handling */
661 ui32_t tl_vi_flags; /* enum a_tty_visual_flags */
662 ui32_t tl_lst_count; /* .tl_count after last sync */
663 ui32_t tl_lst_cursor; /* .tl_cursor after last sync */
664 /* TODO Add another indirection layer by adding a tl_phy_line of
665 * TODO a_tty_cell objects, incorporate changes in visual layer,
666 * TODO then check what _really_ has changed, sync those changes only */
667 struct a_tty_cell const *tl_phy_start; /* First visible cell, left border */
668 ui32_t tl_phy_cursor; /* Physical cursor position */
669 bool_t tl_quote_rndtrip; /* For _kht() expansion */
670 ui8_t tl__dummy2[3];
671 ui32_t tl_prompt_length; /* Preclassified (TODO needed as a_tty_cell) */
672 ui32_t tl_prompt_width;
673 char const *tl_prompt; /* Preformatted prompt (including colours) */
674 /* .tl_pos_buf is a hack */
675 # ifdef HAVE_COLOUR
676 char *tl_pos_buf; /* mle-position colour-on, [4], reset seq. */
677 char *tl_pos; /* Address of the [4] */
678 # endif
681 # ifdef HAVE_KEY_BINDINGS
682 /* C99: use [INDEX]={} */
683 n_CTAV(n_GO_INPUT_CTX_BASE == 0);
684 n_CTAV(n_GO_INPUT_CTX_DEFAULT == 1);
685 n_CTAV(n_GO_INPUT_CTX_COMPOSE == 2);
686 static struct a_tty_bind_ctx_map const
687 a_tty_bind_ctx_maps[n__GO_INPUT_CTX_MAX1] = {
688 {n_GO_INPUT_CTX_BASE, "base"},
689 {n_GO_INPUT_CTX_DEFAULT, "default"},
690 {n_GO_INPUT_CTX_COMPOSE, "compose"}
693 /* Special functions which our MLE provides internally.
694 * Update the manual upon change! */
695 static char const a_tty_bind_fun_names[][24] = {
696 # undef a_X
697 # define a_X(I,N) \
698 n_FIELD_INITI(a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## I)) "mle-" N "\0",
700 a_X(BELL, "bell")
701 a_X(GO_BWD, "go-bwd") a_X(GO_FWD, "go-fwd")
702 a_X(GO_WORD_BWD, "go-word-bwd") a_X(GO_WORD_FWD, "go-word-fwd")
703 a_X(GO_HOME, "go-home") a_X(GO_END, "go-end")
704 a_X(DEL_BWD, "del-bwd") a_X(DEL_FWD, "del-fwd")
705 a_X(SNARF_WORD_BWD, "snarf-word-bwd") a_X(SNARF_WORD_FWD, "snarf-word-fwd")
706 a_X(SNARF_END, "snarf-end") a_X(SNARF_LINE, "snarf-line")
707 a_X(HIST_BWD, "hist-bwd") a_X(HIST_FWD, "hist-fwd")
708 a_X(HIST_SRCH_BWD, "hist-srch-bwd") a_X(HIST_SRCH_FWD, "hist-srch-fwd")
709 a_X(REPAINT, "repaint")
710 a_X(QUOTE_RNDTRIP, "quote-rndtrip")
711 a_X(PROMPT_CHAR, "prompt-char")
712 a_X(COMPLETE, "complete")
713 a_X(PASTE, "paste")
715 a_X(CANCEL, "cancel")
716 a_X(RESET, "reset")
717 a_X(FULLRESET, "fullreset")
718 a_X(COMMIT, "commit")
720 # undef a_X
722 # endif /* HAVE_KEY_BINDINGS */
724 /* The default key bindings (unless disallowed). Update manual upon change!
725 * A logical subset of this table is also used if !HAVE_KEY_BINDINGS (more
726 * expensive than a switch() on control codes directly, but less redundant).
727 * The table for the "base" context */
728 static struct a_tty_bind_builtin_tuple const a_tty_bind_base_tuples[] = {
729 # undef a_X
730 # define a_X(K,S) \
731 {TRU1, K, 0, {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
733 a_X('A', GO_HOME)
734 a_X('B', GO_BWD)
735 /* C: SIGINT */
736 a_X('D', DEL_FWD)
737 a_X('E', GO_END)
738 a_X('F', GO_FWD)
739 a_X('G', RESET)
740 a_X('H', DEL_BWD)
741 a_X('I', COMPLETE)
742 a_X('J', COMMIT)
743 a_X('K', SNARF_END)
744 a_X('L', REPAINT)
745 /* M: same as J */
746 a_X('N', HIST_FWD)
747 /* O: below */
748 a_X('P', HIST_BWD)
749 a_X('Q', QUOTE_RNDTRIP)
750 a_X('R', HIST_SRCH_BWD)
751 a_X('S', HIST_SRCH_FWD)
752 a_X('T', PASTE)
753 a_X('U', SNARF_LINE)
754 a_X('V', PROMPT_CHAR)
755 a_X('W', SNARF_WORD_BWD)
756 a_X('X', GO_WORD_FWD)
757 a_X('Y', GO_WORD_BWD)
758 /* Z: SIGTSTP */
760 a_X('[', CANCEL)
761 /* \: below */
762 /* ]: below */
763 /* ^: below */
764 a_X('_', SNARF_WORD_FWD)
766 a_X('?', DEL_BWD)
768 # undef a_X
769 # define a_X(K,S) {TRU1, K, 0, {S}},
771 /* The remains only if we have `bind' functionality available */
772 # ifdef HAVE_KEY_BINDINGS
773 # undef a_X
774 # define a_X(Q,S) \
775 {FAL0, '\0', n_TERMCAP_QUERY_ ## Q,\
776 {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
778 a_X(key_backspace, DEL_BWD) a_X(key_dc, DEL_FWD)
779 a_X(key_eol, SNARF_END)
780 a_X(key_home, GO_HOME) a_X(key_end, GO_END)
781 a_X(key_left, GO_BWD) a_X(key_right, GO_FWD)
782 a_X(key_sleft, GO_HOME) a_X(key_sright, GO_END)
783 a_X(key_up, HIST_BWD) a_X(key_down, HIST_FWD)
784 # endif /* HAVE_KEY_BINDINGS */
787 /* The table for the "default" context */
788 static struct a_tty_bind_builtin_tuple const a_tty_bind_default_tuples[] = {
789 # undef a_X
790 # define a_X(K,S) \
791 {TRU1, K, 0, {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
793 # undef a_X
794 # define a_X(K,S) {TRU1, K, 0, {S}},
796 a_X('O', "dt")
798 a_X('\\', "z+")
799 a_X(']', "z$")
800 a_X('^', "z0")
802 /* The remains only if we have `bind' functionality available */
803 # ifdef HAVE_KEY_BINDINGS
804 # undef a_X
805 # define a_X(Q,S) {FAL0, '\0', n_TERMCAP_QUERY_ ## Q, {S}},
807 a_X(key_shome, "z0") a_X(key_send, "z$")
808 a_X(xkey_sup, "z0") a_X(xkey_sdown, "z$")
809 a_X(key_ppage, "z-") a_X(key_npage, "z+")
810 a_X(xkey_cup, "dotmove-") a_X(xkey_cdown, "dotmove+")
811 # endif /* HAVE_KEY_BINDINGS */
813 # undef a_X
815 static struct a_tty_global a_tty;
817 /* Change from canonical to raw, non-canonical mode, and way back */
818 static void a_tty_term_mode(bool_t raw);
820 /* Initialize .tg_hist_size_max and return desired history file, or NULL */
821 # ifdef HAVE_HISTORY
822 static char const *a_tty_hist_query_config(void);
823 # endif
825 /* Adjust an active raw mode to use / not use a timeout */
826 # ifdef HAVE_KEY_BINDINGS
827 static void a_tty_term_rawmode_timeout(struct a_tty_line *tlp, bool_t enable);
828 # endif
830 /* 0-X (2), UI8_MAX == \t / TAB */
831 static ui8_t a_tty_wcwidth(wchar_t wc);
833 /* Memory / cell / word generics */
834 static void a_tty_check_grow(struct a_tty_line *tlp, ui32_t no
835 n_MEMORY_DEBUG_ARGS);
836 static ssize_t a_tty_cell2dat(struct a_tty_line *tlp);
837 static void a_tty_cell2save(struct a_tty_line *tlp);
839 /* Save away data bytes of given range (max = non-inclusive) */
840 static void a_tty_copy2paste(struct a_tty_line *tlp, struct a_tty_cell *tcpmin,
841 struct a_tty_cell *tcpmax);
843 /* Ask user for hexadecimal number, interpret as UTF-32 */
844 static wchar_t a_tty_vinuni(struct a_tty_line *tlp);
846 /* Visual screen synchronization */
847 static bool_t a_tty_vi_refresh(struct a_tty_line *tlp);
849 static bool_t a_tty_vi__paint(struct a_tty_line *tlp);
851 /* Search for word boundary, starting at tl_cursor, in "dir"ection (<> 0).
852 * Return <0 when moving is impossible (backward direction but in position 0,
853 * forward direction but in outermost column), and relative distance to
854 * tl_cursor otherwise */
855 static si32_t a_tty_wboundary(struct a_tty_line *tlp, si32_t dir);
857 /* Most function implementations */
858 static void a_tty_khome(struct a_tty_line *tlp, bool_t dobell);
859 static void a_tty_kend(struct a_tty_line *tlp);
860 static void a_tty_kbs(struct a_tty_line *tlp);
861 static void a_tty_ksnarf(struct a_tty_line *tlp, bool_t cplline, bool_t dobell);
862 static si32_t a_tty_kdel(struct a_tty_line *tlp);
863 static void a_tty_kleft(struct a_tty_line *tlp);
864 static void a_tty_kright(struct a_tty_line *tlp);
865 static void a_tty_ksnarfw(struct a_tty_line *tlp, bool_t fwd);
866 static void a_tty_kgow(struct a_tty_line *tlp, si32_t dir);
867 static bool_t a_tty_kother(struct a_tty_line *tlp, wchar_t wc);
868 static ui32_t a_tty_kht(struct a_tty_line *tlp);
870 # ifdef HAVE_HISTORY
871 /* Return UI32_MAX on "exhaustion" */
872 static ui32_t a_tty_khist(struct a_tty_line *tlp, bool_t fwd);
873 static ui32_t a_tty_khist_search(struct a_tty_line *tlp, bool_t fwd);
875 static ui32_t a_tty__khist_shared(struct a_tty_line *tlp,
876 struct a_tty_hist *thp);
877 # endif
879 /* Handle a function */
880 static enum a_tty_fun_status a_tty_fun(struct a_tty_line *tlp,
881 enum a_tty_bind_flags tbf, size_t *len);
883 /* Readline core */
884 static ssize_t a_tty_readline(struct a_tty_line *tlp, size_t len,
885 bool_t *histok_or_null n_MEMORY_DEBUG_ARGS);
887 # ifdef HAVE_KEY_BINDINGS
888 /* Find context or -1 */
889 static enum n_go_input_flags a_tty_bind_ctx_find(char const *name);
891 /* Create (or replace, if allowed) a binding */
892 static bool_t a_tty_bind_create(struct a_tty_bind_parse_ctx *tbpcp,
893 bool_t replace);
895 /* Shared implementation to parse `bind' and `unbind' "key-sequence" and
896 * "expansion" command line arguments into something that we can work with */
897 static bool_t a_tty_bind_parse(bool_t isbindcmd,
898 struct a_tty_bind_parse_ctx *tbpcp);
900 /* Lazy resolve a termcap(5)/terminfo(5) (or *termcap*!) capability */
901 static void a_tty_bind_resolve(struct a_tty_bind_ctx *tbcp);
903 /* Delete an existing binding */
904 static void a_tty_bind_del(struct a_tty_bind_parse_ctx *tbpcp);
906 /* Life cycle of all input node trees */
907 static void a_tty_bind_tree_build(void);
908 static void a_tty_bind_tree_teardown(void);
910 static void a_tty__bind_tree_add(ui32_t hmap_idx,
911 struct a_tty_bind_tree *store[HSHSIZE],
912 struct a_tty_bind_ctx *tbcp);
913 static struct a_tty_bind_tree *a_tty__bind_tree_add_wc(
914 struct a_tty_bind_tree **treep, struct a_tty_bind_tree *parentp,
915 wchar_t wc, bool_t isseq);
916 static void a_tty__bind_tree_free(struct a_tty_bind_tree *tbtp);
917 # endif /* HAVE_KEY_BINDINGS */
919 static void
920 a_tty_signal(int sig){
921 /* Prototype at top */
922 sigset_t nset, oset;
923 NYD_X; /* Signal handler */
925 n_COLOUR( n_colour_env_gut(); ) /* TODO NO SIMPLE SUSPENSION POSSIBLE.. */
926 a_tty_term_mode(FAL0);
927 n_TERMCAP_SUSPEND(TRU1);
928 a_tty_sigs_down();
930 sigemptyset(&nset);
931 sigaddset(&nset, sig);
932 sigprocmask(SIG_UNBLOCK, &nset, &oset);
933 n_raise(sig);
934 /* When we come here we'll continue editing, so reestablish */
935 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
937 /* TODO THEREFORE NEED TO _GUT() .. _CREATE() ENTIRE ENVS!! */
938 n_COLOUR( n_colour_env_create(n_COLOUR_CTX_MLE, n_tty_fp, FAL0); )
939 a_tty_sigs_up();
940 n_TERMCAP_RESUME(TRU1);
941 a_tty_term_mode(TRU1);
942 a_tty.tg_line->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
945 static void
946 a_tty_term_mode(bool_t raw){
947 struct termios *tiosp;
948 NYD2_ENTER;
950 tiosp = &a_tty.tg_tios_old;
951 if(!raw)
952 goto jleave;
954 /* Always requery the attributes, in case we've been moved from background
955 * to foreground or however else in between sessions */
956 /* XXX Always enforce ECHO and ICANON in the OLD attributes - do so as long
957 * XXX as we don't properly deal with TTIN and TTOU etc. */
958 tcgetattr(STDIN_FILENO, tiosp); /* TODO v15: use _only_ n_tty_fp! */
959 tiosp->c_lflag |= ECHO | ICANON;
961 memcpy(&a_tty.tg_tios_new, tiosp, sizeof *tiosp);
962 tiosp = &a_tty.tg_tios_new;
963 tiosp->c_cc[VMIN] = 1;
964 tiosp->c_cc[VTIME] = 0;
965 /* Enable ^\, ^Q and ^S to be used for key bindings */
966 tiosp->c_cc[VQUIT] = tiosp->c_cc[VSTART] = tiosp->c_cc[VSTOP] = '\0';
967 tiosp->c_iflag &= ~(ISTRIP | IGNCR);
968 tiosp->c_lflag &= ~(ECHO /*| ECHOE | ECHONL */| ICANON | IEXTEN);
969 jleave:
970 tcsetattr(STDIN_FILENO, TCSADRAIN, tiosp);
971 NYD2_LEAVE;
974 # ifdef HAVE_HISTORY
975 static char const *
976 a_tty_hist_query_config(void){
977 char const *rv, *cp;
978 NYD2_ENTER;
980 if((cp = ok_vlook(NAIL_HISTSIZE)) != NULL)
981 n_OBSOLETE(_("please use *history-size* instead of *NAIL_HISTSIZE*"));
982 if((rv = ok_vlook(history_size)) == NULL)
983 rv = cp;
984 if(rv == NULL)
985 a_tty.tg_hist_size_max = UIZ_MAX;
986 else
987 (void)n_idec_uiz_cp(&a_tty.tg_hist_size_max, rv, 10, NULL);
989 if((cp = ok_vlook(NAIL_HISTFILE)) != NULL)
990 n_OBSOLETE(_("please use *history-file* instead of *NAIL_HISTFILE*"));
991 if((rv = ok_vlook(history_file)) == NULL)
992 rv = cp;
993 if(rv != NULL)
994 rv = fexpand(rv, FEXP_LOCAL | FEXP_NSHELL);
995 NYD2_LEAVE;
996 return rv;
998 # endif /* HAVE_HISTORY */
1000 # ifdef HAVE_KEY_BINDINGS
1001 static void
1002 a_tty_term_rawmode_timeout(struct a_tty_line *tlp, bool_t enable){
1003 NYD2_ENTER;
1004 if(enable){
1005 ui8_t bt;
1007 a_tty.tg_tios_new.c_cc[VMIN] = 0;
1008 if((bt = tlp->tl_bind_timeout) == 0)
1009 bt = a_TTY_BIND_TIMEOUT;
1010 a_tty.tg_tios_new.c_cc[VTIME] = bt;
1011 }else{
1012 a_tty.tg_tios_new.c_cc[VMIN] = 1;
1013 a_tty.tg_tios_new.c_cc[VTIME] = 0;
1015 tcsetattr(STDIN_FILENO, TCSANOW, &a_tty.tg_tios_new);
1016 NYD2_LEAVE;
1018 # endif /* HAVE_KEY_BINDINGS */
1020 static ui8_t
1021 a_tty_wcwidth(wchar_t wc){
1022 ui8_t rv;
1023 NYD2_ENTER;
1025 /* Special case the reverse solidus at first */
1026 if(wc == '\t')
1027 rv = UI8_MAX;
1028 else{
1029 int i;
1031 # ifdef HAVE_WCWIDTH
1032 rv = ((i = wcwidth(wc)) > 0) ? (ui8_t)i : 0;
1033 # else
1034 rv = iswprint(wc) ? 1 + (wc >= 0x1100u) : 0; /* TODO use S-CText */
1035 # endif
1037 NYD2_LEAVE;
1038 return rv;
1041 static void
1042 a_tty_check_grow(struct a_tty_line *tlp, ui32_t no n_MEMORY_DEBUG_ARGS){
1043 ui32_t cmax;
1044 NYD2_ENTER;
1046 if(n_UNLIKELY((cmax = tlp->tl_count + no) > tlp->tl_count_max)){
1047 size_t i;
1049 i = cmax * sizeof(struct a_tty_cell) + 2 * sizeof(struct a_tty_cell);
1050 if(n_LIKELY(i >= *tlp->tl_x_bufsize)){
1051 hold_all_sigs(); /* XXX v15 drop */
1052 i <<= 1;
1053 tlp->tl_line.cbuf =
1054 *tlp->tl_x_buf = (n_realloc)(*tlp->tl_x_buf, i
1055 n_MEMORY_DEBUG_ARGSCALL);
1056 rele_all_sigs(); /* XXX v15 drop */
1058 tlp->tl_count_max = cmax;
1059 *tlp->tl_x_bufsize = i;
1061 NYD2_LEAVE;
1064 static ssize_t
1065 a_tty_cell2dat(struct a_tty_line *tlp){
1066 size_t len, i;
1067 NYD2_ENTER;
1069 len = 0;
1071 if(n_LIKELY((i = tlp->tl_count) > 0)){
1072 struct a_tty_cell const *tcap;
1074 tcap = tlp->tl_line.cells;
1076 memcpy(tlp->tl_line.cbuf + len, tcap->tc_cbuf, tcap->tc_count);
1077 len += tcap->tc_count;
1078 }while(++tcap, --i > 0);
1081 tlp->tl_line.cbuf[len] = '\0';
1082 NYD2_LEAVE;
1083 return (ssize_t)len;
1086 static void
1087 a_tty_cell2save(struct a_tty_line *tlp){
1088 size_t len, i;
1089 struct a_tty_cell *tcap;
1090 NYD2_ENTER;
1092 tlp->tl_savec.s = NULL;
1093 tlp->tl_savec.l = 0;
1095 if(n_UNLIKELY(tlp->tl_count == 0))
1096 goto jleave;
1098 for(tcap = tlp->tl_line.cells, len = 0, i = tlp->tl_count; i > 0;
1099 ++tcap, --i)
1100 len += tcap->tc_count;
1102 tlp->tl_savec.s = salloc((tlp->tl_savec.l = len) +1);
1104 for(tcap = tlp->tl_line.cells, len = 0, i = tlp->tl_count; i > 0;
1105 ++tcap, --i){
1106 memcpy(tlp->tl_savec.s + len, tcap->tc_cbuf, tcap->tc_count);
1107 len += tcap->tc_count;
1109 tlp->tl_savec.s[len] = '\0';
1110 jleave:
1111 NYD2_LEAVE;
1114 static void
1115 a_tty_copy2paste(struct a_tty_line *tlp, struct a_tty_cell *tcpmin,
1116 struct a_tty_cell *tcpmax){
1117 char *cp;
1118 struct a_tty_cell *tcp;
1119 size_t l;
1120 NYD2_ENTER;
1122 l = 0;
1123 for(tcp = tcpmin; tcp < tcpmax; ++tcp)
1124 l += tcp->tc_count;
1126 tlp->tl_pastebuf.s = cp = salloc((tlp->tl_pastebuf.l = l) +1);
1128 for(tcp = tcpmin; tcp < tcpmax; cp += l, ++tcp)
1129 memcpy(cp, tcp->tc_cbuf, l = tcp->tc_count);
1130 *cp = '\0';
1131 NYD2_LEAVE;
1134 static wchar_t
1135 a_tty_vinuni(struct a_tty_line *tlp){
1136 char buf[16];
1137 uiz_t i;
1138 wchar_t wc;
1139 NYD2_ENTER;
1141 wc = '\0';
1143 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr) ||
1144 !n_termcap_cmd(n_TERMCAP_CMD_ce, 0, -1))
1145 goto jleave;
1147 /* C99 */{
1148 struct str const *cpre, *csuf;
1150 cpre = csuf = NULL;
1151 #ifdef HAVE_COLOUR
1152 if(n_COLOUR_IS_ACTIVE()){
1153 struct n_colour_pen *cpen;
1155 cpen = n_colour_pen_create(n_COLOUR_ID_MLE_PROMPT, NULL);
1156 if((cpre = n_colour_pen_to_str(cpen)) != NULL)
1157 csuf = n_colour_reset_to_str();
1159 #endif
1160 fprintf(n_tty_fp, _("%sPlease enter Unicode code point:%s "),
1161 (cpre != NULL ? cpre->s : n_empty),
1162 (csuf != NULL ? csuf->s : n_empty));
1164 fflush(n_tty_fp);
1166 buf[sizeof(buf) -1] = '\0';
1167 for(i = 0;;){
1168 if(read(STDIN_FILENO, &buf[i], 1) != 1){
1169 if(n_err_no == n_ERR_INTR) /* xxx #if !SA_RESTART ? */
1170 continue;
1171 goto jleave;
1173 if(buf[i] == '\n')
1174 break;
1175 if(!hexchar(buf[i])){
1176 char const emsg[] = "[0-9a-fA-F]";
1178 n_LCTA(sizeof emsg <= sizeof(buf), "Preallocated buffer too small");
1179 memcpy(buf, emsg, sizeof emsg);
1180 goto jerr;
1183 putc(buf[i], n_tty_fp);
1184 fflush(n_tty_fp);
1185 if(++i == sizeof buf)
1186 goto jerr;
1188 buf[i] = '\0';
1190 if((n_idec_uiz_cp(&i, buf, 16, NULL
1191 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
1192 ) != n_IDEC_STATE_CONSUMED || i > 0x10FFFF/* XXX magic; CText */){
1193 jerr:
1194 n_err(_("\nInvalid input: %s\n"), buf);
1195 goto jleave;
1198 wc = (wchar_t)i;
1199 jleave:
1200 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY | (wc == '\0' ? a_TTY_VF_BELL : 0);
1201 NYD2_LEAVE;
1202 return wc;
1205 static bool_t
1206 a_tty_vi_refresh(struct a_tty_line *tlp){
1207 bool_t rv;
1208 NYD2_ENTER;
1210 if(tlp->tl_vi_flags & a_TTY_VF_BELL){
1211 tlp->tl_vi_flags |= a_TTY_VF_SYNC;
1212 if(putc('\a', n_tty_fp) == EOF)
1213 goto jerr;
1216 if(tlp->tl_vi_flags & a_TTY_VF_REFRESH){
1217 /* kht may want to restore a cursor position after inserting some
1218 * data somewhere */
1219 if(tlp->tl_defc_cursor_byte > 0){
1220 size_t i, j;
1221 ssize_t k;
1223 a_tty_khome(tlp, FAL0);
1225 i = tlp->tl_defc_cursor_byte;
1226 tlp->tl_defc_cursor_byte = 0;
1227 for(j = 0; tlp->tl_cursor < tlp->tl_count; ++j){
1228 a_tty_kright(tlp);
1229 if((k = tlp->tl_line.cells[j].tc_count) > i)
1230 break;
1231 i -= k;
1235 if(!a_tty_vi__paint(tlp))
1236 goto jerr;
1239 if(tlp->tl_vi_flags & a_TTY_VF_SYNC){
1240 tlp->tl_vi_flags &= ~a_TTY_VF_SYNC;
1241 if(fflush(n_tty_fp))
1242 goto jerr;
1245 rv = TRU1;
1246 jleave:
1247 tlp->tl_vi_flags &= ~a_TTY_VF_ALL_MASK;
1248 NYD2_LEAVE;
1249 return rv;
1251 jerr:
1252 clearerr(n_tty_fp); /* xxx I/O layer rewrite */
1253 n_err(_("Visual refresh failed! Is $TERM set correctly?\n"
1254 " Setting *line-editor-disable* to get us through!\n"));
1255 ok_bset(line_editor_disable);
1256 rv = FAL0;
1257 goto jleave;
1260 static bool_t
1261 a_tty_vi__paint(struct a_tty_line *tlp){
1262 enum{
1263 a_TRUE_RV = a_TTY__VF_LAST<<1, /* Return value bit */
1264 a_HAVE_PROMPT = a_TTY__VF_LAST<<2, /* Have a prompt */
1265 a_SHOW_PROMPT = a_TTY__VF_LAST<<3, /* Shall print the prompt */
1266 a_MOVE_CURSOR = a_TTY__VF_LAST<<4, /* Move visual cursor for user! */
1267 a_LEFT_MIN = a_TTY__VF_LAST<<5, /* On left boundary */
1268 a_RIGHT_MAX = a_TTY__VF_LAST<<6,
1269 a_HAVE_POSITION = a_TTY__VF_LAST<<7, /* Print the position indicator */
1271 /* We carry some flags over invocations (not worth a specific field) */
1272 a_VISIBLE_PROMPT = a_TTY__VF_LAST<<8, /* The prompt is on the screen */
1273 a_PERSIST_MASK = a_VISIBLE_PROMPT,
1274 a__LAST = a_PERSIST_MASK
1277 ui32_t f, w, phy_wid_base, phy_wid, phy_base, phy_cur, cnt,
1278 DBG(lstcur COMMA) cur,
1279 vi_left, /*vi_right,*/ phy_nxtcur;
1280 struct a_tty_cell const *tccp, *tcp_left, *tcp_right, *tcxp;
1281 NYD2_ENTER;
1282 n_LCTA(UICMP(64, a__LAST, <, UI32_MAX), "Flag bits excess storage datatype");
1284 f = tlp->tl_vi_flags;
1285 tlp->tl_vi_flags = (f & ~(a_TTY_VF_REFRESH | a_PERSIST_MASK)) |
1286 a_TTY_VF_SYNC;
1287 f |= a_TRUE_RV;
1288 if((w = tlp->tl_prompt_width) > 0)
1289 f |= a_HAVE_PROMPT;
1290 f |= a_HAVE_POSITION;
1292 /* XXX We don't have a OnTerminalResize event (see main.c) yet, so we need
1293 * XXX to reevaluate our circumstances over and over again */
1294 /* Don't display prompt or position indicator on very small screens */
1295 if((phy_wid_base = (ui32_t)n_scrnwidth) <= a_TTY_WIDTH_RIPOFF)
1296 f &= ~(a_HAVE_PROMPT | a_HAVE_POSITION);
1297 else{
1298 phy_wid_base -= a_TTY_WIDTH_RIPOFF;
1300 /* Disable the prompt if the screen is too small; due to lack of some
1301 * indicator simply add a second ripoff */
1302 if((f & a_HAVE_PROMPT) && w + a_TTY_WIDTH_RIPOFF >= phy_wid_base)
1303 f &= ~a_HAVE_PROMPT;
1306 phy_wid = phy_wid_base;
1307 phy_base = 0;
1308 phy_cur = tlp->tl_phy_cursor;
1309 cnt = tlp->tl_count;
1310 DBG( lstcur = tlp->tl_lst_cursor; )
1312 /* XXX Assume dirty screen if shrunk */
1313 if(cnt < tlp->tl_lst_count)
1314 f |= a_TTY_VF_MOD_DIRTY;
1316 /* TODO Without HAVE_TERMCAP, it would likely be much cheaper to simply
1317 * TODO always "cr + paint + ce + ch", since ce is simulated via spaces.. */
1319 /* Quickshot: if the line is empty, possibly print prompt and out */
1320 if(cnt == 0){
1321 /* In that special case dirty anything if it seems better */
1322 if((f & a_TTY_VF_MOD_CONTENT) || tlp->tl_lst_count > 0)
1323 f |= a_TTY_VF_MOD_DIRTY;
1325 if((f & a_TTY_VF_MOD_DIRTY) && phy_cur != 0){
1326 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
1327 goto jerr;
1328 phy_cur = 0;
1331 if((f & (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)) ==
1332 (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)){
1333 if(fputs(tlp->tl_prompt, n_tty_fp) == EOF)
1334 goto jerr;
1335 phy_cur = tlp->tl_prompt_width + 1;
1338 /* May need to clear former line content */
1339 if((f & a_TTY_VF_MOD_DIRTY) &&
1340 !n_termcap_cmd(n_TERMCAP_CMD_ce, phy_cur, -1))
1341 goto jerr;
1343 tlp->tl_phy_start = tlp->tl_line.cells;
1344 goto jleave;
1347 /* Try to get an idea of the visual window */
1349 /* Find the left visual boundary */
1350 phy_wid = (phy_wid >> 1) + (phy_wid >> 2);
1351 if((cur = tlp->tl_cursor) == cnt)
1352 --cur;
1354 w = (tcp_left = tccp = tlp->tl_line.cells + cur)->tc_width;
1355 if(w == UI8_MAX) /* TODO yet TAB == SPC */
1356 w = 1;
1357 while(tcp_left > tlp->tl_line.cells){
1358 ui16_t cw = tcp_left[-1].tc_width;
1360 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1361 cw = 1;
1362 if(w + cw >= phy_wid)
1363 break;
1364 w += cw;
1365 --tcp_left;
1367 vi_left = w;
1369 /* If the left hand side of our visual viewpoint consumes less than half
1370 * of the screen width, show the prompt */
1371 if(tcp_left == tlp->tl_line.cells)
1372 f |= a_LEFT_MIN;
1374 if((f & (a_LEFT_MIN | a_HAVE_PROMPT)) == (a_LEFT_MIN | a_HAVE_PROMPT) &&
1375 w + tlp->tl_prompt_width < phy_wid){
1376 phy_base = tlp->tl_prompt_width;
1377 f |= a_SHOW_PROMPT;
1380 /* Then search for right boundary. We always leave the rightmost column
1381 * empty because some terminals [cw]ould wrap the line if we write into
1382 * that. XXX terminfo(5)/termcap(5) have the semi_auto_right_margin/sam/YE
1383 * XXX capability to indicate this, but we don't look at that */
1384 phy_wid = phy_wid_base - phy_base;
1385 tcp_right = tlp->tl_line.cells + cnt;
1387 while(&tccp[1] < tcp_right){
1388 ui16_t cw = tccp[1].tc_width;
1389 ui32_t i;
1391 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1392 cw = 1;
1393 i = w + cw;
1394 if(i > phy_wid)
1395 break;
1396 w = i;
1397 ++tccp;
1399 /*vi_right = w - vi_left;*/
1401 /* If the complete line including prompt fits on the screen, show prompt */
1402 if(--tcp_right == tccp){
1403 f |= a_RIGHT_MAX;
1405 /* Since we did brute-force walk also for the left boundary we may end up
1406 * in a situation were anything effectively fits on the screen, including
1407 * the prompt that is, but were we don't recognize this since we
1408 * restricted the search to fit in some visual viewpoint. Therefore try
1409 * again to extend the left boundary to overcome that */
1410 if(!(f & a_LEFT_MIN)){
1411 struct a_tty_cell const *tc1p = tlp->tl_line.cells;
1412 ui32_t vil1 = vi_left;
1414 assert(!(f & a_SHOW_PROMPT));
1415 w += tlp->tl_prompt_width;
1416 for(tcxp = tcp_left;;){
1417 ui32_t i = tcxp[-1].tc_width;
1419 if(i == UI8_MAX) /* TODO yet TAB == SPC */
1420 i = 1;
1421 vil1 += i;
1422 i += w;
1423 if(i > phy_wid)
1424 break;
1425 w = i;
1426 if(--tcxp == tc1p){
1427 tcp_left = tc1p;
1428 /*vi_left = vil1;*/
1429 f |= a_LEFT_MIN;
1430 break;
1433 /*w -= tlp->tl_prompt_width;*/
1436 tcp_right = tccp;
1437 tccp = tlp->tl_line.cells + cur;
1439 if((f & (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT | a_SHOW_PROMPT)) ==
1440 (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT) &&
1441 w + tlp->tl_prompt_width <= phy_wid){
1442 phy_wid -= (phy_base = tlp->tl_prompt_width);
1443 f |= a_SHOW_PROMPT;
1446 /* Try to avoid repainting the complete line - this is possible if the
1447 * cursor "did not leave the screen" and the prompt status hasn't changed.
1448 * I.e., after clamping virtual viewpoint, compare relation to physical */
1449 if((f & (a_TTY_VF_MOD_SINGLE/*FIXME*/ |
1450 a_TTY_VF_MOD_CONTENT/* xxx */ | a_TTY_VF_MOD_DIRTY)) ||
1451 (tcxp = tlp->tl_phy_start) == NULL ||
1452 tcxp > tccp || tcxp <= tcp_right)
1453 f |= a_TTY_VF_MOD_DIRTY;
1454 else{
1455 f |= a_TTY_VF_MOD_DIRTY;
1456 #if 0
1457 struct a_tty_cell const *tcyp;
1458 si32_t cur_displace;
1459 ui32_t phy_lmargin, phy_rmargin, fx, phy_displace;
1461 phy_lmargin = (fx = phy_wid) / 100;
1462 phy_rmargin = fx - (phy_lmargin * a_TTY_SCROLL_MARGIN_RIGHT);
1463 phy_lmargin *= a_TTY_SCROLL_MARGIN_LEFT;
1464 fx = (f & (a_SHOW_PROMPT | a_VISIBLE_PROMPT));
1466 if(fx == 0 || fx == (a_SHOW_PROMPT | a_VISIBLE_PROMPT)){
1468 #endif
1470 goto jpaint;
1472 /* We know what we have to paint, start synchronizing */
1473 jpaint:
1474 assert(phy_cur == tlp->tl_phy_cursor);
1475 assert(phy_wid == phy_wid_base - phy_base);
1476 assert(cnt == tlp->tl_count);
1477 assert(cnt > 0);
1478 assert(lstcur == tlp->tl_lst_cursor);
1479 assert(tccp == tlp->tl_line.cells + cur);
1481 phy_nxtcur = phy_base; /* FIXME only if repaint cpl. */
1483 /* Quickshot: is it only cursor movement within the visible screen? */
1484 if((f & a_TTY_VF_REFRESH) == a_TTY_VF_MOD_CURSOR){
1485 f |= a_MOVE_CURSOR;
1486 goto jcursor;
1489 /* To be able to apply some quick jump offs, clear line if possible */
1490 if(f & a_TTY_VF_MOD_DIRTY){
1491 /* Force complete clearance and cursor reinitialization */
1492 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr) ||
1493 !n_termcap_cmd(n_TERMCAP_CMD_ce, 0, -1))
1494 goto jerr;
1495 tlp->tl_phy_start = tcp_left;
1496 phy_cur = 0;
1499 if((f & (a_TTY_VF_MOD_DIRTY | a_SHOW_PROMPT)) && phy_cur != 0){
1500 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
1501 goto jerr;
1502 phy_cur = 0;
1505 if(f & a_SHOW_PROMPT){
1506 assert(phy_base == tlp->tl_prompt_width);
1507 if(fputs(tlp->tl_prompt, n_tty_fp) == EOF)
1508 goto jerr;
1509 phy_cur = phy_nxtcur;
1510 f |= a_VISIBLE_PROMPT;
1511 }else
1512 f &= ~a_VISIBLE_PROMPT;
1514 /* FIXME reposition cursor for paint */
1515 for(w = phy_nxtcur; tcp_left <= tcp_right; ++tcp_left){
1516 ui16_t cw;
1518 cw = tcp_left->tc_width;
1520 if(n_LIKELY(!tcp_left->tc_novis)){
1521 if(fwrite(tcp_left->tc_cbuf, sizeof *tcp_left->tc_cbuf,
1522 tcp_left->tc_count, n_tty_fp) != tcp_left->tc_count)
1523 goto jerr;
1524 }else{ /* XXX Shouldn't be here <-> CText, ui_str.c */
1525 char wbuf[8]; /* XXX magic */
1527 if(n_psonce & n_PSO_UNICODE){
1528 ui32_t wc;
1530 wc = (ui32_t)tcp_left->tc_wc;
1531 if((wc & ~0x1Fu) == 0)
1532 wc |= 0x2400;
1533 else if(wc == 0x7F)
1534 wc = 0x2421;
1535 else
1536 wc = 0x2426;
1537 n_utf32_to_utf8(wc, wbuf);
1538 }else
1539 wbuf[0] = '?', wbuf[1] = '\0';
1541 if(fputs(wbuf, n_tty_fp) == EOF)
1542 goto jerr;
1543 cw = 1;
1546 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1547 cw = 1;
1548 w += cw;
1549 if(tcp_left == tccp)
1550 phy_nxtcur = w;
1551 phy_cur += cw;
1554 /* Write something position marker alike if it does not fit on screen */
1555 if((f & a_HAVE_POSITION) &&
1556 ((f & (a_LEFT_MIN | a_RIGHT_MAX)) != (a_LEFT_MIN | a_RIGHT_MAX) ||
1557 ((f & a_HAVE_PROMPT) && !(f & a_SHOW_PROMPT)))){
1558 # ifdef HAVE_COLOUR
1559 char *posbuf = tlp->tl_pos_buf, *pos = tlp->tl_pos;
1560 # else
1561 char posbuf[5], *pos = posbuf;
1563 pos[4] = '\0';
1564 # endif
1566 if(phy_cur != (w = phy_wid_base) &&
1567 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = w, 0))
1568 goto jerr;
1570 *pos++ = '|';
1571 if((f & a_LEFT_MIN) && (!(f & a_HAVE_PROMPT) || (f & a_SHOW_PROMPT)))
1572 memcpy(pos, "^.+", 3);
1573 else if(f & a_RIGHT_MAX)
1574 memcpy(pos, ".+$", 3);
1575 else{
1576 /* Theoretical line length limit a_TTY_LINE_MAX, choose next power of
1577 * ten (10 ** 10) to represent 100 percent, since we don't have a macro
1578 * that generates a constant, and i don't trust the standard "u type
1579 * suffix automatically scales" calculate the large number */
1580 static char const itoa[] = "0123456789";
1582 ui64_t const fact100 = (ui64_t)0x3B9ACA00u * 10u, fact = fact100 / 100;
1583 ui32_t i = (ui32_t)(((fact100 / cnt) * tlp->tl_cursor) / fact);
1584 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1586 if(i < 10)
1587 pos[0] = ' ', pos[1] = itoa[i];
1588 else
1589 pos[1] = itoa[i % 10], pos[0] = itoa[i / 10];
1590 pos[2] = '%';
1593 if(fputs(posbuf, n_tty_fp) == EOF)
1594 goto jerr;
1595 phy_cur += 4;
1598 /* Users are used to see the cursor right of the point of interest, so we
1599 * need some further adjustments unless in special conditions. Be aware
1600 * that we may have adjusted cur at the beginning, too */
1601 if((cur = tlp->tl_cursor) == 0)
1602 phy_nxtcur = phy_base;
1603 else if(cur != cnt){
1604 ui16_t cw = tccp->tc_width;
1606 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1607 cw = 1;
1608 phy_nxtcur -= cw;
1611 jcursor:
1612 if(((f & a_MOVE_CURSOR) || phy_nxtcur != phy_cur) &&
1613 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = phy_nxtcur, 0))
1614 goto jerr;
1616 jleave:
1617 tlp->tl_vi_flags |= (f & a_PERSIST_MASK);
1618 tlp->tl_lst_count = tlp->tl_count;
1619 tlp->tl_lst_cursor = tlp->tl_cursor;
1620 tlp->tl_phy_cursor = phy_cur;
1622 NYD2_LEAVE;
1623 return ((f & a_TRUE_RV) != 0);
1624 jerr:
1625 f &= ~a_TRUE_RV;
1626 goto jleave;
1629 static si32_t
1630 a_tty_wboundary(struct a_tty_line *tlp, si32_t dir){/* TODO shell token-wise */
1631 bool_t anynon;
1632 struct a_tty_cell *tcap;
1633 ui32_t cur, cnt;
1634 si32_t rv;
1635 NYD2_ENTER;
1637 assert(dir == 1 || dir == -1);
1639 rv = -1;
1640 cnt = tlp->tl_count;
1641 cur = tlp->tl_cursor;
1643 if(dir < 0){
1644 if(cur == 0)
1645 goto jleave;
1646 }else if(cur + 1 >= cnt)
1647 goto jleave;
1648 else
1649 --cnt, --cur; /* xxx Unsigned wrapping may occur (twice), then */
1651 for(rv = 0, tcap = tlp->tl_line.cells, anynon = FAL0;;){
1652 wchar_t wc;
1654 wc = tcap[cur += (ui32_t)dir].tc_wc;
1655 if(/*TODO not everywhere iswblank(wc)*/ wc == L' ' || wc == L'\t' ||
1656 iswpunct(wc)){
1657 if(anynon)
1658 break;
1659 }else
1660 anynon = TRU1;
1662 ++rv;
1664 if(dir < 0){
1665 if(cur == 0)
1666 break;
1667 }else if(cur + 1 >= cnt){
1668 ++rv;
1669 break;
1672 jleave:
1673 NYD2_LEAVE;
1674 return rv;
1677 static void
1678 a_tty_khome(struct a_tty_line *tlp, bool_t dobell){
1679 ui32_t f;
1680 NYD2_ENTER;
1682 if(n_LIKELY(tlp->tl_cursor > 0)){
1683 tlp->tl_cursor = 0;
1684 f = a_TTY_VF_MOD_CURSOR;
1685 }else if(dobell)
1686 f = a_TTY_VF_BELL;
1687 else
1688 f = a_TTY_VF_NONE;
1690 tlp->tl_vi_flags |= f;
1691 NYD2_LEAVE;
1694 static void
1695 a_tty_kend(struct a_tty_line *tlp){
1696 ui32_t f;
1697 NYD2_ENTER;
1699 if(n_LIKELY(tlp->tl_cursor < tlp->tl_count)){
1700 tlp->tl_cursor = tlp->tl_count;
1701 f = a_TTY_VF_MOD_CURSOR;
1702 }else
1703 f = a_TTY_VF_BELL;
1705 tlp->tl_vi_flags |= f;
1706 NYD2_LEAVE;
1709 static void
1710 a_tty_kbs(struct a_tty_line *tlp){
1711 ui32_t f, cur, cnt;
1712 NYD2_ENTER;
1714 cur = tlp->tl_cursor;
1715 cnt = tlp->tl_count;
1717 if(n_LIKELY(cur > 0)){
1718 tlp->tl_cursor = --cur;
1719 tlp->tl_count = --cnt;
1721 if((cnt -= cur) > 0){
1722 struct a_tty_cell *tcap;
1724 tcap = tlp->tl_line.cells + cur;
1725 memmove(tcap, &tcap[1], cnt *= sizeof(*tcap));
1727 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
1728 }else
1729 f = a_TTY_VF_BELL;
1731 tlp->tl_vi_flags |= f;
1732 NYD2_LEAVE;
1735 static void
1736 a_tty_ksnarf(struct a_tty_line *tlp, bool_t cplline, bool_t dobell){
1737 ui32_t i, f;
1738 NYD2_ENTER;
1740 f = a_TTY_VF_NONE;
1741 i = tlp->tl_cursor;
1743 if(cplline && i > 0){
1744 tlp->tl_cursor = i = 0;
1745 f = a_TTY_VF_MOD_CURSOR;
1748 if(n_LIKELY(i < tlp->tl_count)){
1749 struct a_tty_cell *tcap;
1751 tcap = &tlp->tl_line.cells[0];
1752 a_tty_copy2paste(tlp, &tcap[i], &tcap[tlp->tl_count]);
1753 tlp->tl_count = i;
1754 f = a_TTY_VF_MOD_CONTENT;
1755 }else if(dobell)
1756 f |= a_TTY_VF_BELL;
1758 tlp->tl_vi_flags |= f;
1759 NYD2_LEAVE;
1762 static si32_t
1763 a_tty_kdel(struct a_tty_line *tlp){
1764 ui32_t cur, cnt, f;
1765 si32_t i;
1766 NYD2_ENTER;
1768 cur = tlp->tl_cursor;
1769 cnt = tlp->tl_count;
1770 i = (si32_t)(cnt - cur);
1772 if(n_LIKELY(i > 0)){
1773 tlp->tl_count = --cnt;
1775 if(n_LIKELY(--i > 0)){
1776 struct a_tty_cell *tcap;
1778 tcap = &tlp->tl_line.cells[cur];
1779 memmove(tcap, &tcap[1], (ui32_t)i * sizeof(*tcap));
1781 f = a_TTY_VF_MOD_CONTENT;
1782 }else if(cnt == 0 && !ok_blook(ignoreeof)){
1783 putc('^', n_tty_fp);
1784 putc('D', n_tty_fp);
1785 i = -1;
1786 f = a_TTY_VF_NONE;
1787 }else{
1788 i = 0;
1789 f = a_TTY_VF_BELL;
1792 tlp->tl_vi_flags |= f;
1793 NYD2_LEAVE;
1794 return i;
1797 static void
1798 a_tty_kleft(struct a_tty_line *tlp){
1799 ui32_t f;
1800 NYD2_ENTER;
1802 if(n_LIKELY(tlp->tl_cursor > 0)){
1803 --tlp->tl_cursor;
1804 f = a_TTY_VF_MOD_CURSOR;
1805 }else
1806 f = a_TTY_VF_BELL;
1808 tlp->tl_vi_flags |= f;
1809 NYD2_LEAVE;
1812 static void
1813 a_tty_kright(struct a_tty_line *tlp){
1814 ui32_t i;
1815 NYD2_ENTER;
1817 if(n_LIKELY((i = tlp->tl_cursor + 1) <= tlp->tl_count)){
1818 tlp->tl_cursor = i;
1819 i = a_TTY_VF_MOD_CURSOR;
1820 }else
1821 i = a_TTY_VF_BELL;
1823 tlp->tl_vi_flags |= i;
1824 NYD2_LEAVE;
1827 static void
1828 a_tty_ksnarfw(struct a_tty_line *tlp, bool_t fwd){
1829 struct a_tty_cell *tcap;
1830 ui32_t cnt, cur, f;
1831 si32_t i;
1832 NYD2_ENTER;
1834 if(n_UNLIKELY((i = a_tty_wboundary(tlp, (fwd ? +1 : -1))) <= 0)){
1835 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
1836 goto jleave;
1839 cnt = tlp->tl_count - (ui32_t)i;
1840 cur = tlp->tl_cursor;
1841 if(!fwd)
1842 cur -= (ui32_t)i;
1843 tcap = &tlp->tl_line.cells[cur];
1845 a_tty_copy2paste(tlp, &tcap[0], &tcap[i]);
1847 if((tlp->tl_count = cnt) != (tlp->tl_cursor = cur)){
1848 cnt -= cur;
1849 memmove(&tcap[0], &tcap[i], cnt * sizeof(*tcap)); /* FIXME*/
1852 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
1853 jleave:
1854 tlp->tl_vi_flags |= f;
1855 NYD2_LEAVE;
1858 static void
1859 a_tty_kgow(struct a_tty_line *tlp, si32_t dir){
1860 ui32_t f;
1861 si32_t i;
1862 NYD2_ENTER;
1864 if(n_UNLIKELY((i = a_tty_wboundary(tlp, dir)) <= 0))
1865 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
1866 else{
1867 if(dir < 0)
1868 i = -i;
1869 tlp->tl_cursor += (ui32_t)i;
1870 f = a_TTY_VF_MOD_CURSOR;
1873 tlp->tl_vi_flags |= f;
1874 NYD2_LEAVE;
1877 static bool_t
1878 a_tty_kother(struct a_tty_line *tlp, wchar_t wc){
1879 /* Append if at EOL, insert otherwise;
1880 * since we may move around character-wise, always use a fresh ps */
1881 mbstate_t ps;
1882 struct a_tty_cell tc, *tcap;
1883 ui32_t f, cur, cnt;
1884 bool_t rv;
1885 NYD2_ENTER;
1887 rv = FAL0;
1888 f = a_TTY_VF_NONE;
1890 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1891 if(tlp->tl_count + 1 >= a_TTY_LINE_MAX){
1892 n_err(_("Stop here, we can't extend line beyond size limit\n"));
1893 goto jleave;
1896 /* First init a cell and see whether we'll really handle this wc */
1897 memset(&ps, 0, sizeof ps);
1898 /* C99 */{
1899 size_t l;
1901 l = wcrtomb(tc.tc_cbuf, tc.tc_wc = wc, &ps);
1902 if(n_UNLIKELY(l > MB_LEN_MAX)){
1903 jemb:
1904 n_err(_("wcrtomb(3) error: too many multibyte character bytes\n"));
1905 goto jleave;
1907 tc.tc_count = (ui16_t)l;
1909 if(n_UNLIKELY((n_psonce & n_PSO_ENC_MBSTATE) != 0)){
1910 l = wcrtomb(&tc.tc_cbuf[l], L'\0', &ps);
1911 if(n_LIKELY(l == 1))
1912 /* Only NUL terminator */;
1913 else if(n_LIKELY(--l < MB_LEN_MAX))
1914 tc.tc_count += (ui16_t)l;
1915 else
1916 goto jemb;
1920 /* Yes, we will! Place it in the array */
1921 tc.tc_novis = (iswprint(wc) == 0);
1922 tc.tc_width = a_tty_wcwidth(wc);
1923 /* TODO if(tc.tc_novis && tc.tc_width > 0) */
1925 cur = tlp->tl_cursor++;
1926 cnt = tlp->tl_count++ - cur;
1927 tcap = &tlp->tl_line.cells[cur];
1928 if(cnt >= 1){
1929 memmove(&tcap[1], tcap, cnt * sizeof(*tcap));
1930 f = a_TTY_VF_MOD_CONTENT;
1931 }else
1932 f = a_TTY_VF_MOD_SINGLE;
1933 memcpy(tcap, &tc, sizeof *tcap);
1935 f |= a_TTY_VF_MOD_CURSOR;
1936 rv = TRU1;
1937 jleave:
1938 if(!rv)
1939 f |= a_TTY_VF_BELL;
1940 tlp->tl_vi_flags |= f;
1941 NYD2_LEAVE;
1942 return rv;
1945 static ui32_t
1946 a_tty_kht(struct a_tty_line *tlp){
1947 ui8_t (*mempool)[n_MEMORY_POOL_TYPE_SIZEOF], *mempool_persist;
1948 struct stat sb;
1949 struct str orig, bot, topp, sub, exp, preexp;
1950 struct n_string shou, *shoup;
1951 struct a_tty_cell *ctop, *cx;
1952 bool_t wedid, set_savec;
1953 ui32_t rv, f;
1954 NYD2_ENTER;
1956 /* Get plain line data; if this is the first expansion/xy, update the
1957 * very original content so that ^G gets the origin back */
1958 orig = tlp->tl_savec;
1959 a_tty_cell2save(tlp);
1960 exp = tlp->tl_savec;
1961 if(orig.s != NULL){
1962 /*tlp->tl_savec = orig;*/
1963 set_savec = FAL0;
1964 }else
1965 set_savec = TRU1;
1966 orig = exp;
1968 mempool_persist = n_go_data->gdc_mempool;
1969 n_memory_pool_push(mempool = n_lofi_alloc(sizeof *mempool));
1971 shoup = n_string_creat_auto(&shou);
1972 f = a_TTY_VF_NONE;
1974 /* C99 */{
1975 size_t max;
1976 struct a_tty_cell *cword;
1978 /* Find the word to be expanded */
1979 cword = tlp->tl_line.cells;
1980 ctop = &cword[tlp->tl_cursor];
1981 cx = &cword[tlp->tl_count];
1983 /* topp: separate data right of cursor */
1984 if(cx > ctop){
1985 for(rv = 0; ctop < cx; ++ctop)
1986 rv += ctop->tc_count;
1987 topp.l = rv;
1988 topp.s = orig.s + orig.l - rv;
1989 ctop = cword + tlp->tl_cursor;
1990 }else
1991 topp.s = NULL, topp.l = 0;
1993 /* Find the shell token that corresponds to the cursor position */
1994 max = 0;
1995 if(ctop > cword){
1996 for(; cword < ctop; ++cword)
1997 max += cword->tc_count;
1999 bot = sub = orig;
2000 bot.l = 0;
2001 sub.l = max;
2003 if(max > 0){
2004 for(;;){
2005 enum n_shexp_state shs;
2007 exp = sub;
2008 shs = n_shexp_parse_token((n_SHEXP_PARSE_DRYRUN |
2009 n_SHEXP_PARSE_TRIM_SPACE | n_SHEXP_PARSE_IGNORE_EMPTY |
2010 n_SHEXP_PARSE_QUOTE_AUTO_CLOSE), NULL, &sub, NULL);
2011 if(sub.l != 0){
2012 size_t x;
2014 assert(max >= sub.l);
2015 x = max - sub.l;
2016 bot.l += x;
2017 max -= x;
2018 continue;
2020 if(shs & n_SHEXP_STATE_ERR_MASK){
2021 n_err(_("Invalid completion pattern: %.*s\n"),
2022 (int)exp.l, exp.s);
2023 f |= a_TTY_VF_BELL;
2024 goto jnope;
2027 /* All WS? Trailing WS that has been "jumped over"? */
2028 if(exp.l == 0 || (shs & n_SHEXP_STATE_WS_TRAIL))
2029 break;
2031 n_shexp_parse_token((n_SHEXP_PARSE_TRIM_SPACE |
2032 n_SHEXP_PARSE_IGNORE_EMPTY | n_SHEXP_PARSE_QUOTE_AUTO_CLOSE),
2033 shoup, &exp, NULL);
2034 break;
2037 sub.s = n_string_cp(shoup);
2038 sub.l = shoup->s_len;
2042 /* Leave room for "implicit asterisk" expansion, as below */
2043 if(sub.l == 0){
2044 sub.s = n_UNCONST(n_star);
2045 sub.l = sizeof(n_star) -1;
2048 preexp.s = n_UNCONST(n_empty);
2049 preexp.l = sizeof(n_empty) -1;
2050 wedid = FAL0;
2051 jredo:
2052 /* TODO Super-Heavy-Metal: block all sigs, avoid leaks on jump */
2053 hold_all_sigs();
2054 exp.s = fexpand(sub.s, a_TTY_TAB_FEXP_FL);
2055 rele_all_sigs();
2057 if(exp.s == NULL || (exp.l = strlen(exp.s)) == 0){
2058 /* No. But maybe the users' desire was to complete only a part of the
2059 * shell token of interest! TODO This can be improved, we would need to
2060 * TODO have shexp_parse to create a DOM structure of parsed snippets, so
2061 * TODO that we can tell for each snippet which quote is active and
2062 * TODO whether we may cross its boundary and/or apply expansion for it */
2063 if(wedid == TRU1){
2064 size_t i, li;
2066 wedid = TRUM1;
2067 for(li = UIZ_MAX, i = sub.l; i-- > 0;){
2068 char c;
2070 if((c = sub.s[i]) == '/' || c == '+' /* *folder*! */)
2071 li = i;
2072 /* Do stop once some "magic" characters are seen XXX magic set */
2073 else if(c == '<' || c == '>' || c == '=' || c == ':')
2074 break;
2076 if(li != UIZ_MAX){
2077 preexp = sub;
2078 preexp.l = li;
2079 sub.l -= li;
2080 sub.s += li;
2081 goto jredo;
2084 goto jnope;
2087 if(wedid == TRUM1 && preexp.l > 0)
2088 preexp.s = savestrbuf(preexp.s, preexp.l);
2090 /* May be multi-return! */
2091 if(n_pstate & n_PS_EXPAND_MULTIRESULT)
2092 goto jmulti;
2094 /* xxx That is not really true since the limit counts characters not bytes */
2095 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
2096 if(exp.l >= a_TTY_LINE_MAX - 1 || a_TTY_LINE_MAX - 1 - exp.l < preexp.l){
2097 n_err(_("Tabulator expansion would extend beyond line size limit\n"));
2098 f |= a_TTY_VF_BELL;
2099 goto jnope;
2102 /* If the expansion equals the original string, assume the user wants what
2103 * is usually known as tab completion, append `*' and restart */
2104 if(!wedid && exp.l == sub.l && !memcmp(exp.s, sub.s, exp.l)){
2105 if(sub.s[sub.l - 1] == '*')
2106 goto jnope;
2108 wedid = TRU1;
2109 shoup = n_string_push_c(shoup, '*');
2110 sub.s = n_string_cp(shoup);
2111 sub.l = shoup->s_len;
2112 goto jredo;
2115 if(exp.s[exp.l - 1] != '/'){
2116 if(!stat(exp.s, &sb) && S_ISDIR(sb.st_mode)){
2117 shoup = n_string_assign_buf(shoup, exp.s, exp.l);
2118 shoup = n_string_push_c(shoup, '/');
2119 exp.s = n_string_cp(shoup);
2120 goto jset;
2123 exp.s[exp.l] = '\0';
2125 jset:
2126 exp.l = strlen(exp.s = n_shexp_quote_cp(exp.s, tlp->tl_quote_rndtrip));
2127 tlp->tl_defc_cursor_byte = bot.l + preexp.l + exp.l -1;
2129 orig.l = bot.l + preexp.l + exp.l + topp.l;
2130 orig.s = n_autorec_alloc_from_pool(mempool_persist, orig.l + 5 +1);
2131 if((rv = (ui32_t)bot.l) > 0)
2132 memcpy(orig.s, bot.s, rv);
2133 if(preexp.l > 0){
2134 memcpy(&orig.s[rv], preexp.s, preexp.l);
2135 rv += preexp.l;
2137 memcpy(&orig.s[rv], exp.s, exp.l);
2138 rv += exp.l;
2139 if(topp.l > 0){
2140 memcpy(&orig.s[rv], topp.s, topp.l);
2141 rv += topp.l;
2143 orig.s[rv] = '\0';
2145 tlp->tl_defc = orig;
2146 tlp->tl_count = tlp->tl_cursor = 0;
2147 f |= a_TTY_VF_MOD_DIRTY;
2148 jleave:
2149 n_memory_pool_pop(mempool);
2150 n_lofi_free(mempool);
2151 tlp->tl_vi_flags |= f;
2152 NYD2_LEAVE;
2153 return rv;
2155 jmulti:{
2156 struct n_visual_info_ctx vic;
2157 struct str input;
2158 wc_t c2, c1;
2159 bool_t isfirst;
2160 char const *lococp;
2161 size_t locolen, scrwid, lnlen, lncnt, prefixlen;
2162 FILE *fp;
2164 if((fp = Ftmp(NULL, "tabex", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
2165 n_perr(_("tmpfile"), 0);
2166 fp = n_tty_fp;
2169 /* How long is the result string for real? Search the NUL NUL
2170 * terminator. While here, detect the longest entry to perform an
2171 * initial allocation of our accumulator string */
2172 locolen = preexp.l;
2174 size_t i;
2176 i = strlen(&exp.s[++exp.l]);
2177 locolen = n_MAX(locolen, i);
2178 exp.l += i;
2179 }while(exp.s[exp.l + 1] != '\0');
2181 shoup = n_string_reserve(n_string_trunc(shoup, 0),
2182 locolen + (locolen >> 1));
2184 /* Iterate (once again) over all results */
2185 scrwid = n_SCRNWIDTH_FOR_LISTS;
2186 lnlen = lncnt = 0;
2187 n_UNINIT(prefixlen, 0);
2188 n_UNINIT(lococp, NULL);
2189 n_UNINIT(c1, '\0');
2190 for(isfirst = TRU1; exp.l > 0; isfirst = FAL0, c1 = c2){
2191 size_t i;
2192 char const *fullpath;
2194 /* Next result */
2195 sub = exp;
2196 sub.l = i = strlen(sub.s);
2197 assert(exp.l >= i);
2198 if((exp.l -= i) > 0)
2199 --exp.l;
2200 exp.s += ++i;
2202 /* Separate dirname and basename */
2203 fullpath = sub.s;
2204 if(isfirst){
2205 char const *cp;
2207 if((cp = strrchr(fullpath, '/')) != NULL)
2208 prefixlen = PTR2SIZE(++cp - fullpath);
2209 else
2210 prefixlen = 0;
2212 if(prefixlen > 0 && prefixlen < sub.l){
2213 sub.l -= prefixlen;
2214 sub.s += prefixlen;
2217 /* We want case-insensitive sort-order */
2218 memset(&vic, 0, sizeof vic);
2219 vic.vic_indat = sub.s;
2220 vic.vic_inlen = sub.l;
2221 c2 = n_visual_info(&vic, n_VISUAL_INFO_ONE_CHAR) ? vic.vic_waccu
2222 : (ui8_t)*sub.s;
2223 #ifdef HAVE_C90AMEND1
2224 c2 = towlower(c2);
2225 #else
2226 c2 = lowerconv(c2);
2227 #endif
2229 /* Query longest common prefix along the way */
2230 if(isfirst){
2231 c1 = c2;
2232 lococp = sub.s;
2233 locolen = sub.l;
2234 }else if(locolen > 0){
2235 for(i = 0; i < locolen; ++i)
2236 if(lococp[i] != sub.s[i]){
2237 i = field_detect_clip(i, lococp, i);
2238 locolen = i;
2239 break;
2243 /* Prepare display */
2244 input = sub;
2245 shoup = n_shexp_quote(n_string_trunc(shoup, 0), &input,
2246 tlp->tl_quote_rndtrip);
2247 memset(&vic, 0, sizeof vic);
2248 vic.vic_indat = shoup->s_dat;
2249 vic.vic_inlen = shoup->s_len;
2250 if(!n_visual_info(&vic,
2251 n_VISUAL_INFO_SKIP_ERRORS | n_VISUAL_INFO_WIDTH_QUERY))
2252 vic.vic_vi_width = shoup->s_len;
2254 /* Put on screen. Indent follow lines of same sort slot.
2255 * Leave enough room for filename tagging */
2256 if((c1 = (c1 != c2))){
2257 #ifdef HAVE_C90AMEND1
2258 c1 = (iswalnum(c2) != 0);
2259 #else
2260 c1 = (alnumchar(c2) != 0);
2261 #endif
2263 if(isfirst || c1 ||
2264 scrwid < lnlen || scrwid - lnlen <= vic.vic_vi_width + 2){
2265 putc('\n', fp);
2266 if(scrwid < lnlen)
2267 ++lncnt;
2268 ++lncnt, lnlen = 0;
2269 if(!isfirst && !c1)
2270 goto jsep;
2271 }else if(lnlen > 0){
2272 jsep:
2273 fputs(" ", fp);
2274 lnlen += 2;
2276 fputs(n_string_cp(shoup), fp);
2277 lnlen += vic.vic_vi_width;
2279 /* Support the known filename tagging
2280 * XXX *line-editor-completion-filetype* or so */
2281 if(!lstat(fullpath, &sb)){
2282 char c = '\0';
2284 if(S_ISDIR(sb.st_mode))
2285 c = '/';
2286 else if(S_ISLNK(sb.st_mode))
2287 c = '@';
2288 # ifdef S_ISFIFO
2289 else if(S_ISFIFO(sb.st_mode))
2290 c = '|';
2291 # endif
2292 # ifdef S_ISSOCK
2293 else if(S_ISSOCK(sb.st_mode))
2294 c = '=';
2295 # endif
2296 # ifdef S_ISCHR
2297 else if(S_ISCHR(sb.st_mode))
2298 c = '%';
2299 # endif
2300 # ifdef S_ISBLK
2301 else if(S_ISBLK(sb.st_mode))
2302 c = '#';
2303 # endif
2305 if(c != '\0'){
2306 putc(c, fp);
2307 ++lnlen;
2311 putc('\n', fp);
2312 ++lncnt;
2314 page_or_print(fp, lncnt);
2315 if(fp != n_tty_fp)
2316 Fclose(fp);
2318 n_string_gut(shoup);
2320 /* A common prefix of 0 means we cannot provide the user any auto
2321 * completed characters for the multiple possible results.
2322 * Otherwise we can, so extend the visual line content by the common
2323 * prefix (in a reversible way) */
2324 f |= a_TTY_VF_BELL; /* XXX -> *line-editor-completion-bell*? or so */
2325 if(locolen > 0){
2326 (exp.s = n_UNCONST(lococp))[locolen] = '\0';
2327 exp.s -= prefixlen;
2328 exp.l = (locolen += prefixlen);
2329 goto jset;
2333 jnope:
2334 /* If we've provided a default content, but failed to expand, there is
2335 * nothing we can "revert to": drop that default again */
2336 if(set_savec){
2337 tlp->tl_savec.s = NULL;
2338 tlp->tl_savec.l = 0;
2340 f &= a_TTY_VF_BELL; /* XXX -> *line-editor-completion-bell*? or so */
2341 rv = 0;
2342 goto jleave;
2345 # ifdef HAVE_HISTORY
2346 static ui32_t
2347 a_tty__khist_shared(struct a_tty_line *tlp, struct a_tty_hist *thp){
2348 ui32_t f, rv;
2349 NYD2_ENTER;
2351 if(n_LIKELY((tlp->tl_hist = thp) != NULL)){
2352 tlp->tl_defc.s = savestrbuf(thp->th_dat, thp->th_len);
2353 rv = tlp->tl_defc.l = thp->th_len;
2354 f = (tlp->tl_count > 0) ? a_TTY_VF_MOD_DIRTY : a_TTY_VF_NONE;
2355 tlp->tl_count = tlp->tl_cursor = 0;
2356 }else{
2357 f = a_TTY_VF_BELL;
2358 rv = UI32_MAX;
2361 tlp->tl_vi_flags |= f;
2362 NYD2_LEAVE;
2363 return rv;
2366 static ui32_t
2367 a_tty_khist(struct a_tty_line *tlp, bool_t fwd){
2368 struct a_tty_hist *thp;
2369 ui32_t rv;
2370 NYD2_ENTER;
2372 /* If we're not in history mode yet, save line content */
2373 if((thp = tlp->tl_hist) == NULL){
2374 a_tty_cell2save(tlp);
2375 if((thp = a_tty.tg_hist) == NULL)
2376 goto jleave;
2377 if(fwd)
2378 while(thp->th_older != NULL)
2379 thp = thp->th_older;
2380 goto jleave;
2383 thp = fwd ? thp->th_younger : thp->th_older;
2384 jleave:
2385 rv = a_tty__khist_shared(tlp, thp);
2386 NYD2_LEAVE;
2387 return rv;
2390 static ui32_t
2391 a_tty_khist_search(struct a_tty_line *tlp, bool_t fwd){
2392 struct str orig_savec;
2393 struct a_tty_hist *thp;
2394 ui32_t rv;
2395 NYD2_ENTER;
2397 thp = NULL;
2399 /* We cannot complete an empty line */
2400 if(n_UNLIKELY(tlp->tl_count == 0)){
2401 /* XXX The upcoming hard reset would restore a set savec buffer,
2402 * XXX so forcefully reset that. A cleaner solution would be to
2403 * XXX reset it whenever a restore is no longer desired */
2404 tlp->tl_savec.s = NULL;
2405 tlp->tl_savec.l = 0;
2406 goto jleave;
2409 if((thp = tlp->tl_hist) == NULL){
2410 a_tty_cell2save(tlp);
2411 if((thp = a_tty.tg_hist) == NULL) /* TODO Should end "doing nothing"! */
2412 goto jleave;
2413 if(fwd)
2414 while(thp->th_older != NULL)
2415 thp = thp->th_older;
2416 orig_savec.s = NULL;
2417 orig_savec.l = 0; /* silence CC */
2418 }else if((thp = (fwd ? thp->th_younger : thp->th_older)) == NULL)
2419 goto jleave;
2420 else
2421 orig_savec = tlp->tl_savec;
2423 if(orig_savec.s == NULL)
2424 a_tty_cell2save(tlp);
2426 for(; thp != NULL; thp = (fwd ? thp->th_younger : thp->th_older))
2427 if(is_prefix(tlp->tl_savec.s, thp->th_dat))
2428 break;
2430 if(orig_savec.s != NULL)
2431 tlp->tl_savec = orig_savec;
2432 jleave:
2433 rv = a_tty__khist_shared(tlp, thp);
2434 NYD2_LEAVE;
2435 return rv;
2437 # endif /* HAVE_HISTORY */
2439 static enum a_tty_fun_status
2440 a_tty_fun(struct a_tty_line *tlp, enum a_tty_bind_flags tbf, size_t *len){
2441 enum a_tty_fun_status rv;
2442 NYD2_ENTER;
2444 rv = a_TTY_FUN_STATUS_OK;
2445 # undef a_X
2446 # define a_X(N) a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## N)
2447 switch(a_TTY_BIND_FUN_REDUCE(tbf)){
2448 case a_X(BELL):
2449 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2450 break;
2451 case a_X(GO_BWD):
2452 a_tty_kleft(tlp);
2453 break;
2454 case a_X(GO_FWD):
2455 a_tty_kright(tlp);
2456 break;
2457 case a_X(GO_WORD_BWD):
2458 a_tty_kgow(tlp, -1);
2459 break;
2460 case a_X(GO_WORD_FWD):
2461 a_tty_kgow(tlp, +1);
2462 break;
2463 case a_X(GO_HOME):
2464 a_tty_khome(tlp, TRU1);
2465 break;
2466 case a_X(GO_END):
2467 a_tty_kend(tlp);
2468 break;
2469 case a_X(DEL_BWD):
2470 a_tty_kbs(tlp);
2471 break;
2472 case a_X(DEL_FWD):
2473 if(a_tty_kdel(tlp) < 0)
2474 rv = a_TTY_FUN_STATUS_END;
2475 break;
2476 case a_X(SNARF_WORD_BWD):
2477 a_tty_ksnarfw(tlp, FAL0);
2478 break;
2479 case a_X(SNARF_WORD_FWD):
2480 a_tty_ksnarfw(tlp, TRU1);
2481 break;
2482 case a_X(SNARF_END):
2483 a_tty_ksnarf(tlp, FAL0, TRU1);
2484 break;
2485 case a_X(SNARF_LINE):
2486 a_tty_ksnarf(tlp, TRU1, (tlp->tl_count == 0));
2487 break;
2489 case a_X(HIST_FWD):{
2490 # ifdef HAVE_HISTORY
2491 bool_t isfwd = TRU1;
2493 if(0){
2494 # endif
2495 /* FALLTHRU */
2496 case a_X(HIST_BWD):
2497 # ifdef HAVE_HISTORY
2498 isfwd = FAL0;
2500 if((*len = a_tty_khist(tlp, isfwd)) != UI32_MAX){
2501 rv = a_TTY_FUN_STATUS_RESTART;
2502 break;
2504 goto jreset;
2505 # endif
2507 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2508 break;
2510 case a_X(HIST_SRCH_FWD):{
2511 # ifdef HAVE_HISTORY
2512 bool_t isfwd = TRU1;
2514 if(0){
2515 # endif
2516 /* FALLTHRU */
2517 case a_X(HIST_SRCH_BWD):
2518 # ifdef HAVE_HISTORY
2519 isfwd = FAL0;
2521 if((*len = a_tty_khist_search(tlp, isfwd)) != UI32_MAX){
2522 rv = a_TTY_FUN_STATUS_RESTART;
2523 break;
2525 goto jreset;
2526 # else
2527 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2528 # endif
2529 }break;
2531 case a_X(REPAINT):
2532 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2533 break;
2534 case a_X(QUOTE_RNDTRIP):
2535 tlp->tl_quote_rndtrip = !tlp->tl_quote_rndtrip;
2536 break;
2537 case a_X(PROMPT_CHAR):{
2538 wchar_t wc;
2540 if((wc = a_tty_vinuni(tlp)) > 0)
2541 a_tty_kother(tlp, wc);
2542 }break;
2543 case a_X(COMPLETE):
2544 if((*len = a_tty_kht(tlp)) > 0)
2545 rv = a_TTY_FUN_STATUS_RESTART;
2546 break;
2548 case a_X(PASTE):
2549 if(tlp->tl_pastebuf.l > 0)
2550 *len = (tlp->tl_defc = tlp->tl_pastebuf).l;
2551 else
2552 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2553 break;
2556 case a_X(CANCEL):
2557 /* Normally this just causes a restart and thus resets the state
2558 * machine */
2559 if(tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2561 # ifdef HAVE_KEY_BINDINGS
2562 tlp->tl_bind_takeover = '\0';
2563 # endif
2564 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2565 rv = a_TTY_FUN_STATUS_RESTART;
2566 break;
2568 case a_X(RESET):
2569 if(tlp->tl_count == 0 && tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2570 # ifdef HAVE_KEY_BINDINGS
2571 tlp->tl_bind_takeover = '\0';
2572 # endif
2573 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY | a_TTY_VF_BELL;
2574 break;
2575 }else if(0){
2576 case a_X(FULLRESET):
2577 tlp->tl_savec.s = tlp->tl_defc.s = NULL;
2578 tlp->tl_savec.l = tlp->tl_defc.l = 0;
2579 tlp->tl_defc_cursor_byte = 0;
2580 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2582 jreset:
2583 # ifdef HAVE_KEY_BINDINGS
2584 tlp->tl_bind_takeover = '\0';
2585 # endif
2586 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2587 tlp->tl_cursor = tlp->tl_count = 0;
2588 # ifdef HAVE_HISTORY
2589 tlp->tl_hist = NULL;
2590 # endif
2591 if((*len = tlp->tl_savec.l) != 0){
2592 tlp->tl_defc = tlp->tl_savec;
2593 tlp->tl_savec.s = NULL;
2594 tlp->tl_savec.l = 0;
2595 }else
2596 *len = tlp->tl_defc.l;
2597 rv = a_TTY_FUN_STATUS_RESTART;
2598 break;
2600 default:
2601 case a_X(COMMIT):
2602 rv = a_TTY_FUN_STATUS_COMMIT;
2603 break;
2605 # undef a_X
2607 NYD2_LEAVE;
2608 return rv;
2611 static ssize_t
2612 a_tty_readline(struct a_tty_line *tlp, size_t len, bool_t *histok_or_null
2613 n_MEMORY_DEBUG_ARGS){
2614 /* We want to save code, yet we may have to incorporate a lines'
2615 * default content and / or default input to switch back to after some
2616 * history movement; let "len > 0" mean "have to display some data
2617 * buffer" -> a_BUFMODE, and only otherwise read(2) it */
2618 mbstate_t ps[2];
2619 char cbuf_base[MB_LEN_MAX * 2], *cbuf, *cbufp;
2620 ssize_t rv;
2621 struct a_tty_bind_tree *tbtp;
2622 wchar_t wc;
2623 enum a_tty_bind_flags tbf;
2624 enum {a_NONE, a_WAS_HERE = 1<<0, a_BUFMODE = 1<<1, a_MAYBEFUN = 1<<2,
2625 a_TIMEOUT = 1<<3, a_TIMEOUT_EXPIRED = 1<<4,
2626 a_TIMEOUT_MASK = a_TIMEOUT | a_TIMEOUT_EXPIRED,
2627 a_READ_LOOP_MASK = ~(a_WAS_HERE | a_MAYBEFUN | a_TIMEOUT_MASK)
2628 } flags;
2629 NYD_ENTER;
2631 n_UNINIT(rv, 0);
2632 # ifdef HAVE_KEY_BINDINGS
2633 assert(tlp->tl_bind_takeover == '\0');
2634 # endif
2635 jrestart:
2636 memset(ps, 0, sizeof ps);
2637 flags = a_NONE;
2638 tlp->tl_vi_flags |= a_TTY_VF_REFRESH | a_TTY_VF_SYNC;
2640 jinput_loop:
2641 for(;;){
2642 if(len != 0)
2643 flags |= a_BUFMODE;
2645 /* Ensure we have valid pointers, and room for grow */
2646 a_tty_check_grow(tlp, ((flags & a_BUFMODE) ? (ui32_t)len : 1)
2647 n_MEMORY_DEBUG_ARGSCALL);
2649 /* Handle visual state flags, except in buffer mode */
2650 if(!(flags & a_BUFMODE) && (tlp->tl_vi_flags & a_TTY_VF_ALL_MASK))
2651 if(!a_tty_vi_refresh(tlp)){
2652 rv = -1;
2653 goto jleave;
2656 /* Ready for messing around.
2657 * Normal read(2)? Else buffer mode: speed this one up */
2658 if(!(flags & a_BUFMODE)){
2659 cbufp =
2660 cbuf = cbuf_base;
2661 }else{
2662 assert(tlp->tl_defc.l > 0 && tlp->tl_defc.s != NULL);
2663 assert(tlp->tl_defc.l >= len);
2664 cbufp =
2665 cbuf = tlp->tl_defc.s + (tlp->tl_defc.l - len);
2666 cbufp += len;
2669 /* Read in the next complete multibyte character */
2670 /* C99 */{
2671 # ifdef HAVE_KEY_BINDINGS
2672 struct a_tty_bind_tree *xtbtp;
2673 struct inseq{
2674 struct inseq *last;
2675 struct inseq *next;
2676 struct a_tty_bind_tree *tbtp;
2677 } *isp_head, *isp;
2679 isp_head = isp = NULL;
2680 # endif
2682 for(flags &= a_READ_LOOP_MASK;;){
2683 # ifdef HAVE_KEY_BINDINGS
2684 if(!(flags & a_BUFMODE) && tlp->tl_bind_takeover != '\0'){
2685 wc = tlp->tl_bind_takeover;
2686 tlp->tl_bind_takeover = '\0';
2687 }else
2688 # endif
2690 if(!(flags & a_BUFMODE)){
2691 /* Let me at least once dream of iomon(itor), timer with
2692 * one-shot, enwrapped with key_event and key_sequence_event,
2693 * all driven by an event_loop */
2694 /* TODO v15 Until we have SysV signal handling all through we
2695 * TODO need to temporarily adjust our BSD signal handler with
2696 * TODO a SysV one, here */
2697 n_sighdl_t otstp, ottin, ottou;
2699 otstp = n_signal(SIGTSTP, &a_tty_signal);
2700 ottin = n_signal(SIGTTIN, &a_tty_signal);
2701 ottou = n_signal(SIGTTOU, &a_tty_signal);
2702 # ifdef HAVE_KEY_BINDINGS
2703 flags &= ~a_TIMEOUT_MASK;
2704 if(isp != NULL && (tbtp = isp->tbtp)->tbt_isseq &&
2705 !tbtp->tbt_isseq_trail){
2706 a_tty_term_rawmode_timeout(tlp, TRU1);
2707 flags |= a_TIMEOUT;
2709 # endif
2711 while((rv = read(STDIN_FILENO, cbufp, 1)) < 1){
2712 if(rv == -1){
2713 if(n_err_no == n_ERR_INTR){
2714 if((tlp->tl_vi_flags & a_TTY_VF_MOD_DIRTY) &&
2715 !a_tty_vi_refresh(tlp))
2716 break;
2717 continue;
2719 break;
2722 # ifdef HAVE_KEY_BINDINGS
2723 /* Timeout expiration */
2724 if(rv == 0){
2725 assert(flags & a_TIMEOUT);
2726 assert(isp != NULL);
2727 a_tty_term_rawmode_timeout(tlp, FAL0);
2729 /* Something "atomic" broke. Maybe the current one can
2730 * also be terminated already, by itself? xxx really? */
2731 if((tbtp = isp->tbtp)->tbt_bind != NULL){
2732 tlp->tl_bind_takeover = wc;
2733 goto jhave_bind;
2736 /* Or, maybe there is a second path without a timeout;
2737 * this should be covered by .tbt_isseq_trail, but then
2738 * again a single-layer implementation cannot "know" */
2739 for(xtbtp = tbtp; (xtbtp = xtbtp->tbt_sibling) != NULL;)
2740 if(xtbtp->tbt_char == tbtp->tbt_char){
2741 assert(!xtbtp->tbt_isseq);
2742 break;
2744 /* Lay down on read(2)? */
2745 if(xtbtp != NULL)
2746 continue;
2747 goto jtake_over;
2749 # endif /* HAVE_KEY_BINDINGS */
2752 # ifdef HAVE_KEY_BINDINGS
2753 if(flags & a_TIMEOUT)
2754 a_tty_term_rawmode_timeout(tlp, FAL0);
2755 # endif
2756 safe_signal(SIGTSTP, otstp);
2757 safe_signal(SIGTTIN, ottin);
2758 safe_signal(SIGTTOU, ottou);
2759 if(rv < 0)
2760 goto jleave;
2762 ++cbufp;
2765 rv = (ssize_t)mbrtowc(&wc, cbuf, PTR2SIZE(cbufp - cbuf), &ps[0]);
2766 if(rv <= 0){
2767 /* Any error during buffer mode can only result in a hard
2768 * reset; Otherwise, if it's a hard error, or if too many
2769 * redundant shift sequences overflow our buffer: perform
2770 * hard reset */
2771 if((flags & a_BUFMODE) || rv == -1 ||
2772 sizeof cbuf_base == PTR2SIZE(cbufp - cbuf)){
2773 a_tty_fun(tlp, a_TTY_BIND_FUN_FULLRESET, &len);
2774 goto jrestart;
2776 /* Otherwise, due to the way we deal with the buffer, we need
2777 * to restore the mbstate_t from before this conversion */
2778 ps[0] = ps[1];
2779 continue;
2781 cbufp = cbuf;
2782 ps[1] = ps[0];
2785 /* Normal read(2)ing is subject to detection of key-bindings */
2786 # ifdef HAVE_KEY_BINDINGS
2787 if(!(flags & a_BUFMODE)){
2788 /* Check for special bypass functions before we try to embed
2789 * this character into the tree */
2790 if(n_uasciichar(wc)){
2791 char c;
2792 char const *cp;
2794 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_prompt_char)[0];
2795 *cp != '\0'; ++cp){
2796 if(c == *cp){
2797 wc = a_tty_vinuni(tlp);
2798 break;
2801 if(wc == '\0'){
2802 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2803 goto jinput_loop;
2806 if(n_uasciichar(wc))
2807 flags |= a_MAYBEFUN;
2808 else
2809 flags &= ~a_MAYBEFUN;
2811 /* Search for this character in the bind tree */
2812 tbtp = (isp != NULL) ? isp->tbtp->tbt_childs
2813 : (*tlp->tl_bind_tree_hmap)[wc % HSHSIZE];
2814 for(; tbtp != NULL; tbtp = tbtp->tbt_sibling){
2815 if(tbtp->tbt_char == wc){
2816 struct inseq *nisp;
2818 /* If this one cannot continue we're likely finished! */
2819 if(tbtp->tbt_childs == NULL){
2820 assert(tbtp->tbt_bind != NULL);
2821 tbf = tbtp->tbt_bind->tbc_flags;
2822 goto jmle_fun;
2825 /* This needs to read more characters */
2826 nisp = salloc(sizeof *nisp);
2827 if((nisp->last = isp) == NULL)
2828 isp_head = nisp;
2829 else
2830 isp->next = nisp;
2831 nisp->next = NULL;
2832 nisp->tbtp = tbtp;
2833 isp = nisp;
2834 flags &= ~a_WAS_HERE;
2835 break;
2838 if(tbtp != NULL)
2839 continue;
2841 /* Was there a binding active, but couldn't be continued? */
2842 if(isp != NULL){
2843 /* A binding had a timeout, it didn't expire, but we saw
2844 * something non-expected. Something "atomic" broke.
2845 * Maybe there is a second path without a timeout, that
2846 * continues like we've seen it. I.e., it may just have been
2847 * the user, typing too fast. We definitely want to allow
2848 * bindings like \e,d etc. to succeed: users are so used to
2849 * them that a timeout cannot be the mechanism to catch up!
2850 * A single-layer implementation cannot "know" */
2851 if((tbtp = isp->tbtp)->tbt_isseq && (isp->last == NULL ||
2852 !(xtbtp = isp->last->tbtp)->tbt_isseq ||
2853 xtbtp->tbt_isseq_trail)){
2854 for(xtbtp = (tbtp = isp->tbtp);
2855 (xtbtp = xtbtp->tbt_sibling) != NULL;)
2856 if(xtbtp->tbt_char == tbtp->tbt_char){
2857 assert(!xtbtp->tbt_isseq);
2858 break;
2860 if(xtbtp != NULL){
2861 isp->tbtp = xtbtp;
2862 tlp->tl_bind_takeover = wc;
2863 continue;
2867 /* Check for CANCEL shortcut now */
2868 if(flags & a_MAYBEFUN){
2869 char c;
2870 char const *cp;
2872 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_cancel)[0];
2873 *cp != '\0'; ++cp)
2874 if(c == *cp){
2875 tbf = a_TTY_BIND_FUN_INTERNAL |a_TTY_BIND_FUN_CANCEL;
2876 goto jmle_fun;
2880 /* So: maybe the current sequence can be terminated here? */
2881 if((tbtp = isp->tbtp)->tbt_bind != NULL){
2882 jhave_bind:
2883 tbf = tbtp->tbt_bind->tbc_flags;
2884 jmle_fun:
2885 if(tbf & a_TTY_BIND_FUN_INTERNAL){
2886 switch(a_tty_fun(tlp, tbf, &len)){
2887 case a_TTY_FUN_STATUS_OK:
2888 goto jinput_loop;
2889 case a_TTY_FUN_STATUS_COMMIT:
2890 goto jdone;
2891 case a_TTY_FUN_STATUS_RESTART:
2892 goto jrestart;
2893 case a_TTY_FUN_STATUS_END:
2894 rv = -1;
2895 goto jleave;
2897 assert(0);
2898 }else if(tbtp->tbt_bind->tbc_flags & a_TTY_BIND_NOCOMMIT){
2899 struct a_tty_bind_ctx *tbcp;
2901 tbcp = tbtp->tbt_bind;
2902 memcpy(tlp->tl_defc.s = salloc(
2903 (tlp->tl_defc.l = len = tbcp->tbc_exp_len) +1),
2904 tbcp->tbc_exp, tbcp->tbc_exp_len +1);
2905 goto jrestart;
2906 }else{
2907 cbufp = tbtp->tbt_bind->tbc_exp;
2908 goto jinject_input;
2913 /* Otherwise take over all chars "as is" */
2914 jtake_over:
2915 for(; isp_head != NULL; isp_head = isp_head->next)
2916 if(a_tty_kother(tlp, isp_head->tbtp->tbt_char)){
2917 /* FIXME */
2919 /* And the current one too */
2920 goto jkother;
2922 # endif /* HAVE_KEY_BINDINGS */
2924 if((flags & a_BUFMODE) && (len -= (size_t)rv) == 0){
2925 /* Buffer mode completed */
2926 tlp->tl_defc.s = NULL;
2927 tlp->tl_defc.l = 0;
2928 flags &= ~a_BUFMODE;
2930 break;
2933 # ifndef HAVE_KEY_BINDINGS
2934 /* Don't interpret control bytes during buffer mode.
2935 * Otherwise, if it's a control byte check whether it is a MLE
2936 * function. Remarks: initially a complete duplicate to be able to
2937 * switch(), later converted to simply iterate over (an #ifdef'd
2938 * subset of) the MLE base_tuple table in order to have "a SPOF" */
2939 if(cbuf == cbuf_base && n_uasciichar(wc) && cntrlchar((char)wc)){
2940 struct a_tty_bind_builtin_tuple const *tbbtp, *tbbtp_max;
2941 char c;
2943 c = (char)wc ^ 0x40;
2944 tbbtp = a_tty_bind_base_tuples;
2945 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_base_tuples)];
2946 jbuiltin_redo:
2947 for(; tbbtp < tbbtp_max; ++tbbtp){
2948 /* Assert default_tuple table is properly subset'ed */
2949 assert(tbbtp->tbdt_iskey);
2950 if(tbbtp->tbbt_ckey == c){
2951 if(tbbtp->tbbt_exp[0] == '\0'){
2952 tbf = a_TTY_BIND_FUN_EXPAND((ui8_t)tbbtp->tbbt_exp[1]);
2953 switch(a_tty_fun(tlp, tbf, &len)){
2954 case a_TTY_FUN_STATUS_OK:
2955 goto jinput_loop;
2956 case a_TTY_FUN_STATUS_COMMIT:
2957 goto jdone;
2958 case a_TTY_FUN_STATUS_RESTART:
2959 goto jrestart;
2960 case a_TTY_FUN_STATUS_END:
2961 rv = -1;
2962 goto jleave;
2964 assert(0);
2965 }else{
2966 cbufp = tbbtp->tbbt_exp;
2967 goto jinject_input;
2971 if(tbbtp ==
2972 &a_tty_bind_base_tuples[n_NELEM(a_tty_bind_base_tuples)]){
2973 tbbtp = a_tty_bind_default_tuples;
2974 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_default_tuples)];
2975 goto jbuiltin_redo;
2978 # endif /* !HAVE_KEY_BINDINGS */
2980 # ifdef HAVE_KEY_BINDINGS
2981 jkother:
2982 # endif
2983 if(a_tty_kother(tlp, wc)){
2984 /* Don't clear the history during buffer mode.. */
2985 # ifdef HAVE_HISTORY
2986 if(!(flags & a_BUFMODE) && cbuf == cbuf_base)
2987 tlp->tl_hist = NULL;
2988 # endif
2993 /* We have a completed input line, convert the struct cell data to its
2994 * plain character equivalent */
2995 jdone:
2996 rv = a_tty_cell2dat(tlp);
2997 jleave:
2998 putc('\n', n_tty_fp);
2999 fflush(n_tty_fp);
3000 NYD_LEAVE;
3001 return rv;
3003 jinject_input:{
3004 size_t i;
3006 hold_all_sigs(); /* XXX v15 drop */
3007 i = a_tty_cell2dat(tlp);
3008 n_go_input_inject(n_GO_INPUT_INJECT_NONE, tlp->tl_line.cbuf, i);
3009 i = strlen(cbufp) +1;
3010 if(i >= *tlp->tl_x_bufsize){
3011 *tlp->tl_x_buf = (n_realloc)(*tlp->tl_x_buf, i n_MEMORY_DEBUG_ARGSCALL);
3012 *tlp->tl_x_bufsize = i;
3014 memcpy(*tlp->tl_x_buf, cbufp, i);
3015 rele_all_sigs(); /* XXX v15 drop */
3016 if(histok_or_null != NULL)
3017 *histok_or_null = FAL0;
3018 rv = (ssize_t)--i;
3020 goto jleave;
3023 # ifdef HAVE_KEY_BINDINGS
3024 static enum n_go_input_flags
3025 a_tty_bind_ctx_find(char const *name){
3026 enum n_go_input_flags rv;
3027 struct a_tty_bind_ctx_map const *tbcmp;
3028 NYD2_ENTER;
3030 tbcmp = a_tty_bind_ctx_maps;
3031 do if(!asccasecmp(tbcmp->tbcm_name, name)){
3032 rv = tbcmp->tbcm_ctx;
3033 goto jleave;
3034 }while(PTRCMP(++tbcmp, <,
3035 &a_tty_bind_ctx_maps[n_NELEM(a_tty_bind_ctx_maps)]));
3037 rv = (enum n_go_input_flags)-1;
3038 jleave:
3039 NYD2_LEAVE;
3040 return rv;
3043 static bool_t
3044 a_tty_bind_create(struct a_tty_bind_parse_ctx *tbpcp, bool_t replace){
3045 struct a_tty_bind_ctx *tbcp;
3046 bool_t rv;
3047 NYD2_ENTER;
3049 rv = FAL0;
3051 if(!a_tty_bind_parse(TRU1, tbpcp))
3052 goto jleave;
3054 /* Since we use a single buffer for it all, need to replace as such */
3055 if(tbpcp->tbpc_tbcp != NULL){
3056 if(!replace)
3057 goto jleave;
3058 a_tty_bind_del(tbpcp);
3059 }else if(a_tty.tg_bind_cnt == UI32_MAX){
3060 n_err(_("`bind': maximum number of bindings already established\n"));
3061 goto jleave;
3064 /* C99 */{
3065 size_t i, j;
3067 tbcp = smalloc(n_VSTRUCT_SIZEOF(struct a_tty_bind_ctx, tbc__buf) +
3068 tbpcp->tbpc_seq_len + tbpcp->tbpc_exp.l +
3069 n_MAX(sizeof(si32_t), sizeof(wc_t)) + tbpcp->tbpc_cnv_len +3);
3070 if(tbpcp->tbpc_ltbcp != NULL){
3071 tbcp->tbc_next = tbpcp->tbpc_ltbcp->tbc_next;
3072 tbpcp->tbpc_ltbcp->tbc_next = tbcp;
3073 }else{
3074 enum n_go_input_flags gif;
3076 gif = tbpcp->tbpc_flags & n__GO_INPUT_CTX_MASK;
3077 tbcp->tbc_next = a_tty.tg_bind[gif];
3078 a_tty.tg_bind[gif] = tbcp;
3080 memcpy(tbcp->tbc_seq = &tbcp->tbc__buf[0],
3081 tbpcp->tbpc_seq, i = (tbcp->tbc_seq_len = tbpcp->tbpc_seq_len) +1);
3082 memcpy(tbcp->tbc_exp = &tbcp->tbc__buf[i],
3083 tbpcp->tbpc_exp.s, j = (tbcp->tbc_exp_len = tbpcp->tbpc_exp.l) +1);
3084 i += j;
3085 i = (i + tbpcp->tbpc_cnv_align_mask) & ~tbpcp->tbpc_cnv_align_mask;
3086 memcpy(tbcp->tbc_cnv = &tbcp->tbc__buf[i],
3087 tbpcp->tbpc_cnv, (tbcp->tbc_cnv_len = tbpcp->tbpc_cnv_len) +1);
3088 tbcp->tbc_flags = tbpcp->tbpc_flags;
3091 /* Directly resolve any termcap(5) symbol if we are already setup */
3092 if((n_psonce & n_PSO_STARTED) &&
3093 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
3094 a_TTY_BIND_RESOLVE)
3095 a_tty_bind_resolve(tbcp);
3097 ++a_tty.tg_bind_cnt;
3098 /* If this binding is usable invalidate the key input lookup trees */
3099 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3100 a_tty.tg_bind_isdirty = TRU1;
3101 rv = TRU1;
3102 jleave:
3103 NYD2_LEAVE;
3104 return rv;
3107 static bool_t
3108 a_tty_bind_parse(bool_t isbindcmd, struct a_tty_bind_parse_ctx *tbpcp){
3109 enum{a_TRUE_RV = a_TTY__BIND_LAST<<1};
3111 struct n_visual_info_ctx vic;
3112 struct str shin_save, shin;
3113 struct n_string shou, *shoup;
3114 size_t i;
3115 struct kse{
3116 struct kse *next;
3117 char *seq_dat;
3118 wc_t *cnv_dat;
3119 ui32_t seq_len;
3120 ui32_t cnv_len; /* High bit set if a termap to be resolved */
3121 ui32_t calc_cnv_len; /* Ditto, but aligned etc. */
3122 ui8_t kse__dummy[4];
3123 } *head, *tail;
3124 ui32_t f;
3125 NYD2_ENTER;
3126 n_LCTA(UICMP(64, a_TRUE_RV, <, UI32_MAX),
3127 "Flag bits excess storage datatype");
3129 f = n_GO_INPUT_NONE;
3130 shoup = n_string_creat_auto(&shou);
3131 head = tail = NULL;
3133 /* Parse the key-sequence */
3134 for(shin.s = n_UNCONST(tbpcp->tbpc_in_seq), shin.l = UIZ_MAX;;){
3135 struct kse *ep;
3136 enum n_shexp_state shs;
3138 shin_save = shin;
3139 shs = n_shexp_parse_token((n_SHEXP_PARSE_TRUNC |
3140 n_SHEXP_PARSE_TRIM_SPACE | n_SHEXP_PARSE_IGNORE_EMPTY |
3141 n_SHEXP_PARSE_IFS_IS_COMMA), shoup, &shin, NULL);
3142 if(shs & n_SHEXP_STATE_ERR_UNICODE){
3143 f |= a_TTY_BIND_DEFUNCT;
3144 if(isbindcmd && (n_poption & n_PO_D_V))
3145 n_err(_("`%s': \\uNICODE not available in locale: %s\n"),
3146 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3148 if((shs & n_SHEXP_STATE_ERR_MASK) & ~n_SHEXP_STATE_ERR_UNICODE){
3149 n_err(_("`%s': failed to parse key-sequence: %s\n"),
3150 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3151 goto jleave;
3153 if((shs & (n_SHEXP_STATE_OUTPUT | n_SHEXP_STATE_STOP)) ==
3154 n_SHEXP_STATE_STOP)
3155 break;
3157 ep = salloc(sizeof *ep);
3158 if(head == NULL)
3159 head = ep;
3160 else
3161 tail->next = ep;
3162 tail = ep;
3163 ep->next = NULL;
3164 if(!(shs & n_SHEXP_STATE_ERR_UNICODE)){
3165 i = strlen(ep->seq_dat = n_shexp_quote_cp(n_string_cp(shoup), TRU1));
3166 if(i >= SI32_MAX - 1)
3167 goto jelen;
3168 ep->seq_len = (ui32_t)i;
3169 }else{
3170 /* Otherwise use the original buffer, _we_ can only quote it the wrong
3171 * way (e.g., an initial $'\u3a' becomes '\u3a'), _then_ */
3172 if((i = shin_save.l - shin.l) >= SI32_MAX - 1)
3173 goto jelen;
3174 ep->seq_len = (ui32_t)i;
3175 ep->seq_dat = savestrbuf(shin_save.s, i);
3178 memset(&vic, 0, sizeof vic);
3179 vic.vic_inlen = shoup->s_len;
3180 vic.vic_indat = shoup->s_dat;
3181 if(!n_visual_info(&vic,
3182 n_VISUAL_INFO_WOUT_CREATE | n_VISUAL_INFO_WOUT_SALLOC)){
3183 n_err(_("`%s': key-sequence seems to contain invalid "
3184 "characters: %s: %s\n"),
3185 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
3186 f |= a_TTY_BIND_DEFUNCT;
3187 goto jleave;
3188 }else if(vic.vic_woulen == 0 ||
3189 vic.vic_woulen >= (SI32_MAX - 2) / sizeof(wc_t)){
3190 jelen:
3191 n_err(_("`%s': length of key-sequence unsupported: %s: %s\n"),
3192 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
3193 f |= a_TTY_BIND_DEFUNCT;
3194 goto jleave;
3196 ep->cnv_dat = vic.vic_woudat;
3197 ep->cnv_len = (ui32_t)vic.vic_woulen;
3199 /* A termcap(5)/terminfo(5) identifier? */
3200 if(ep->cnv_len > 1 && ep->cnv_dat[0] == ':'){
3201 i = --ep->cnv_len, ++ep->cnv_dat;
3202 # if 0 /* ndef HAVE_TERMCAP xxx User can, via *termcap*! */
3203 if(n_poption & n_PO_D_V)
3204 n_err(_("`%s': no termcap(5)/terminfo(5) support: %s: %s\n"),
3205 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3206 f |= a_TTY_BIND_DEFUNCT;
3207 # endif
3208 if(i > a_TTY_BIND_CAPNAME_MAX){
3209 n_err(_("`%s': termcap(5)/terminfo(5) name too long: %s: %s\n"),
3210 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3211 f |= a_TTY_BIND_DEFUNCT;
3213 while(i > 0)
3214 /* (We store it as char[]) */
3215 if((ui32_t)ep->cnv_dat[--i] & ~0x7Fu){
3216 n_err(_("`%s': invalid termcap(5)/terminfo(5) name content: "
3217 "%s: %s\n"),
3218 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3219 f |= a_TTY_BIND_DEFUNCT;
3220 break;
3222 ep->cnv_len |= SI32_MIN; /* Needs resolve */
3223 f |= a_TTY_BIND_RESOLVE;
3226 if(shs & n_SHEXP_STATE_STOP)
3227 break;
3230 if(head == NULL){
3231 jeempty:
3232 n_err(_("`%s': effectively empty key-sequence: %s\n"),
3233 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3234 goto jleave;
3237 if(isbindcmd) /* (Or always, just "1st time init") */
3238 tbpcp->tbpc_cnv_align_mask = n_MAX(sizeof(si32_t), sizeof(wc_t)) - 1;
3240 /* C99 */{
3241 struct a_tty_bind_ctx *ltbcp, *tbcp;
3242 char *cpbase, *cp, *cnv;
3243 size_t sl, cl;
3245 /* Unite the parsed sequence(s) into single string representations */
3246 for(sl = cl = 0, tail = head; tail != NULL; tail = tail->next){
3247 sl += tail->seq_len + 1;
3249 if(!isbindcmd)
3250 continue;
3252 /* Preserve room for terminal capabilities to be resolved.
3253 * Above we have ensured the buffer will fit in these calculations */
3254 if((i = tail->cnv_len) & SI32_MIN){
3255 /* For now
3256 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[]+NUL;}
3257 * later
3258 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3259 n_LCTAV(n_ISPOW2(a_TTY_BIND_CAPEXP_ROUNDUP));
3260 n_LCTA(a_TTY_BIND_CAPEXP_ROUNDUP >= sizeof(wc_t),
3261 "Aligning on this constant does not properly align wc_t");
3262 i &= SI32_MAX;
3263 i *= sizeof(wc_t);
3264 i += sizeof(si32_t);
3265 if(i < a_TTY_BIND_CAPEXP_ROUNDUP)
3266 i = (i + (a_TTY_BIND_CAPEXP_ROUNDUP - 1)) &
3267 ~(a_TTY_BIND_CAPEXP_ROUNDUP - 1);
3268 }else
3269 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3270 i *= sizeof(wc_t);
3271 i += sizeof(si32_t) + sizeof(wc_t); /* (buf_len_iscap, NUL) */
3272 cl += i;
3273 if(tail->cnv_len & SI32_MIN){
3274 tail->cnv_len &= SI32_MAX;
3275 i |= SI32_MIN;
3277 tail->calc_cnv_len = (ui32_t)i;
3279 --sl;
3281 tbpcp->tbpc_seq_len = sl;
3282 tbpcp->tbpc_cnv_len = cl;
3283 /* C99 */{
3284 size_t j;
3286 j = i = sl + 1; /* Room for comma separator */
3287 if(isbindcmd){
3288 i = (i + tbpcp->tbpc_cnv_align_mask) & ~tbpcp->tbpc_cnv_align_mask;
3289 j = i;
3290 i += cl;
3292 tbpcp->tbpc_seq = cp = cpbase = salloc(i);
3293 tbpcp->tbpc_cnv = cnv = &cpbase[j];
3296 for(tail = head; tail != NULL; tail = tail->next){
3297 memcpy(cp, tail->seq_dat, tail->seq_len);
3298 cp += tail->seq_len;
3299 *cp++ = ',';
3301 if(isbindcmd){
3302 char * const save_cnv = cnv;
3304 n_UNALIGN(si32_t*,cnv)[0] = (si32_t)(i = tail->calc_cnv_len);
3305 cnv += sizeof(si32_t);
3306 if(i & SI32_MIN){
3307 /* For now
3308 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];}
3309 * later
3310 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[];} */
3311 n_UNALIGN(si32_t*,cnv)[0] = tail->cnv_len;
3312 cnv += sizeof(si32_t);
3314 i = tail->cnv_len * sizeof(wc_t);
3315 memcpy(cnv, tail->cnv_dat, i);
3316 cnv += i;
3317 *n_UNALIGN(wc_t*,cnv) = '\0';
3319 cnv = save_cnv + (tail->calc_cnv_len & SI32_MAX);
3322 *--cp = '\0';
3324 /* Search for a yet existing identical mapping */
3325 /* C99 */{
3326 enum n_go_input_flags gif;
3328 gif = tbpcp->tbpc_flags & n__GO_INPUT_CTX_MASK;
3330 for(ltbcp = NULL, tbcp = a_tty.tg_bind[gif]; tbcp != NULL;
3331 ltbcp = tbcp, tbcp = tbcp->tbc_next)
3332 if(tbcp->tbc_seq_len == sl && !memcmp(tbcp->tbc_seq, cpbase, sl)){
3333 tbpcp->tbpc_tbcp = tbcp;
3334 break;
3337 tbpcp->tbpc_ltbcp = ltbcp;
3338 tbpcp->tbpc_flags |= (f & a_TTY__BIND_MASK);
3341 /* Create single string expansion if so desired */
3342 if(isbindcmd){
3343 char *exp;
3345 exp = tbpcp->tbpc_exp.s;
3347 i = tbpcp->tbpc_exp.l;
3348 if(i > 0 && exp[i - 1] == '@'){
3349 while(--i > 0){
3350 if(!blankspacechar(exp[i - 1]))
3351 break;
3353 if(i == 0)
3354 goto jeempty;
3356 exp[tbpcp->tbpc_exp.l = i] = '\0';
3357 tbpcp->tbpc_flags |= a_TTY_BIND_NOCOMMIT;
3360 /* Reverse solidus cannot be placed last in expansion to avoid (at the
3361 * time of this writing) possible problems with newline escaping.
3362 * Don't care about (un)even number thereof */
3363 if(i > 0 && exp[i - 1] == '\\'){
3364 n_err(_("`%s': reverse solidus cannot be last in expansion: %s\n"),
3365 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3366 goto jleave;
3369 /* It may map to an internal MLE command! */
3370 for(i = 0; i < n_NELEM(a_tty_bind_fun_names); ++i)
3371 if(!asccasecmp(exp, a_tty_bind_fun_names[i])){
3372 tbpcp->tbpc_flags |= a_TTY_BIND_FUN_EXPAND(i) |
3373 a_TTY_BIND_FUN_INTERNAL |
3374 (head->next == NULL ? a_TTY_BIND_MLE1CNTRL : 0);
3375 if((n_poption & n_PO_D_V) &&
3376 (tbpcp->tbpc_flags & a_TTY_BIND_NOCOMMIT))
3377 n_err(_("`%s': MLE commands can't be made editable via @: %s\n"),
3378 tbpcp->tbpc_cmd, exp);
3379 tbpcp->tbpc_flags &= ~a_TTY_BIND_NOCOMMIT;
3380 break;
3384 f |= a_TRUE_RV; /* TODO because we only now true and false; DEFUNCT.. */
3385 jleave:
3386 n_string_gut(shoup);
3387 NYD2_LEAVE;
3388 return (f & a_TRUE_RV) != 0;
3391 static void
3392 a_tty_bind_resolve(struct a_tty_bind_ctx *tbcp){
3393 char capname[a_TTY_BIND_CAPNAME_MAX +1];
3394 struct n_termcap_value tv;
3395 size_t len;
3396 bool_t isfirst; /* TODO For now: first char must be control! */
3397 char *cp, *next;
3398 NYD2_ENTER;
3400 n_UNINIT(next, NULL);
3401 for(cp = tbcp->tbc_cnv, isfirst = TRU1, len = tbcp->tbc_cnv_len;
3402 len > 0; isfirst = FAL0, cp = next){
3403 /* C99 */{
3404 si32_t i, j;
3406 i = n_UNALIGN(si32_t*,cp)[0];
3407 j = i & SI32_MAX;
3408 next = &cp[j];
3409 len -= j;
3410 if(i == j)
3411 continue;
3413 /* struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];} */
3414 cp += sizeof(si32_t);
3415 i = n_UNALIGN(si32_t*,cp)[0];
3416 cp += sizeof(si32_t);
3417 for(j = 0; j < i; ++j)
3418 capname[j] = n_UNALIGN(wc_t*,cp)[j];
3419 capname[j] = '\0';
3422 /* Use generic lookup mechanism if not a known query */
3423 /* C99 */{
3424 si32_t tq;
3426 tq = n_termcap_query_for_name(capname, n_TERMCAP_CAPTYPE_STRING);
3427 if(tq == -1){
3428 tv.tv_data.tvd_string = capname;
3429 tq = n__TERMCAP_QUERY_MAX1;
3432 if(tq < 0 || !n_termcap_query(tq, &tv)){
3433 if(n_poption & n_PO_D_V)
3434 n_err(_("`bind': unknown or unsupported capability: %s: %s\n"),
3435 capname, tbcp->tbc_seq);
3436 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3437 break;
3441 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3442 /* C99 */{
3443 size_t i;
3445 i = strlen(tv.tv_data.tvd_string);
3446 if(/*i > SI32_MAX ||*/ i >= PTR2SIZE(next - cp)){
3447 if(n_poption & n_PO_D_V)
3448 n_err(_("`bind': capability expansion too long: %s: %s\n"),
3449 capname, tbcp->tbc_seq);
3450 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3451 break;
3452 }else if(i == 0){
3453 if(n_poption & n_PO_D_V)
3454 n_err(_("`bind': empty capability expansion: %s: %s\n"),
3455 capname, tbcp->tbc_seq);
3456 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3457 break;
3458 }else if(isfirst && !cntrlchar(*tv.tv_data.tvd_string)){
3459 if(n_poption & n_PO_D_V)
3460 n_err(_("`bind': capability expansion does not start with "
3461 "control: %s: %s\n"), capname, tbcp->tbc_seq);
3462 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3463 break;
3465 n_UNALIGN(si32_t*,cp)[-1] = (si32_t)i;
3466 memcpy(cp, tv.tv_data.tvd_string, i);
3467 cp[i] = '\0';
3470 NYD2_LEAVE;
3473 static void
3474 a_tty_bind_del(struct a_tty_bind_parse_ctx *tbpcp){
3475 struct a_tty_bind_ctx *ltbcp, *tbcp;
3476 NYD2_ENTER;
3478 tbcp = tbpcp->tbpc_tbcp;
3480 if((ltbcp = tbpcp->tbpc_ltbcp) != NULL)
3481 ltbcp->tbc_next = tbcp->tbc_next;
3482 else
3483 a_tty.tg_bind[tbpcp->tbpc_flags & n__GO_INPUT_CTX_MASK] = tbcp->tbc_next;
3484 free(tbcp);
3486 --a_tty.tg_bind_cnt;
3487 a_tty.tg_bind_isdirty = TRU1;
3488 NYD2_LEAVE;
3491 static void
3492 a_tty_bind_tree_build(void){
3493 size_t i;
3494 NYD2_ENTER;
3496 for(i = 0; i < n__GO_INPUT_CTX_MAX1; ++i){
3497 struct a_tty_bind_ctx *tbcp;
3498 n_LCTAV(n_GO_INPUT_CTX_BASE == 0);
3500 /* Somewhat wasteful, but easier to handle: simply clone the entire
3501 * primary key onto the secondary one, then only modify it */
3502 for(tbcp = a_tty.tg_bind[n_GO_INPUT_CTX_BASE]; tbcp != NULL;
3503 tbcp = tbcp->tbc_next)
3504 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3505 a_tty__bind_tree_add(n_GO_INPUT_CTX_BASE, &a_tty.tg_bind_tree[i][0],
3506 tbcp);
3508 if(i != n_GO_INPUT_CTX_BASE)
3509 for(tbcp = a_tty.tg_bind[i]; tbcp != NULL; tbcp = tbcp->tbc_next)
3510 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3511 a_tty__bind_tree_add(i, &a_tty.tg_bind_tree[i][0], tbcp);
3514 a_tty.tg_bind_isbuild = TRU1;
3515 NYD2_LEAVE;
3518 static void
3519 a_tty_bind_tree_teardown(void){
3520 size_t i, j;
3521 NYD2_ENTER;
3523 memset(&a_tty.tg_bind_shcut_cancel[0], 0,
3524 sizeof(a_tty.tg_bind_shcut_cancel));
3525 memset(&a_tty.tg_bind_shcut_prompt_char[0], 0,
3526 sizeof(a_tty.tg_bind_shcut_prompt_char));
3528 for(i = 0; i < n__GO_INPUT_CTX_MAX1; ++i)
3529 for(j = 0; j < HSHSIZE; ++j)
3530 a_tty__bind_tree_free(a_tty.tg_bind_tree[i][j]);
3531 memset(&a_tty.tg_bind_tree[0], 0, sizeof(a_tty.tg_bind_tree));
3533 a_tty.tg_bind_isdirty = a_tty.tg_bind_isbuild = FAL0;
3534 NYD2_LEAVE;
3537 static void
3538 a_tty__bind_tree_add(ui32_t hmap_idx, struct a_tty_bind_tree *store[HSHSIZE],
3539 struct a_tty_bind_ctx *tbcp){
3540 ui32_t cnvlen;
3541 char const *cnvdat;
3542 struct a_tty_bind_tree *ntbtp;
3543 NYD2_ENTER;
3544 n_UNUSED(hmap_idx);
3546 ntbtp = NULL;
3548 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len; cnvlen > 0;){
3549 union {wchar_t const *wp; char const *cp;} u;
3550 si32_t entlen;
3552 /* {si32_t buf_len_iscap;} */
3553 entlen = *n_UNALIGN(si32_t const*,cnvdat);
3555 if(entlen & SI32_MIN){
3556 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;}
3557 * Note that empty capabilities result in DEFUNCT */
3558 for(u.cp = (char const*)&n_UNALIGN(si32_t const*,cnvdat)[2];
3559 *u.cp != '\0'; ++u.cp)
3560 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.cp, TRU1);
3561 assert(ntbtp != NULL);
3562 ntbtp->tbt_isseq_trail = TRU1;
3563 entlen &= SI32_MAX;
3564 }else{
3565 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3566 bool_t isseq;
3568 u.wp = (wchar_t const*)&n_UNALIGN(si32_t const*,cnvdat)[1];
3570 /* May be a special shortcut function? */
3571 if(ntbtp == NULL && (tbcp->tbc_flags & a_TTY_BIND_MLE1CNTRL)){
3572 char *cp;
3573 ui32_t ctx, fun;
3575 ctx = tbcp->tbc_flags & n__GO_INPUT_CTX_MASK;
3576 fun = tbcp->tbc_flags & a_TTY__BIND_FUN_MASK;
3578 if(fun == a_TTY_BIND_FUN_CANCEL){
3579 for(cp = &a_tty.tg_bind_shcut_cancel[ctx][0];
3580 PTRCMP(cp, <, &a_tty.tg_bind_shcut_cancel[ctx]
3581 [n_NELEM(a_tty.tg_bind_shcut_cancel[ctx]) - 1]); ++cp)
3582 if(*cp == '\0'){
3583 *cp = (char)*u.wp;
3584 break;
3586 }else if(fun == a_TTY_BIND_FUN_PROMPT_CHAR){
3587 for(cp = &a_tty.tg_bind_shcut_prompt_char[ctx][0];
3588 PTRCMP(cp, <, &a_tty.tg_bind_shcut_prompt_char[ctx]
3589 [n_NELEM(a_tty.tg_bind_shcut_prompt_char[ctx]) - 1]);
3590 ++cp)
3591 if(*cp == '\0'){
3592 *cp = (char)*u.wp;
3593 break;
3598 isseq = (u.wp[1] != '\0');
3599 for(; *u.wp != '\0'; ++u.wp)
3600 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.wp, isseq);
3601 if(isseq){
3602 assert(ntbtp != NULL);
3603 ntbtp->tbt_isseq_trail = TRU1;
3607 cnvlen -= entlen;
3608 cnvdat += entlen;
3611 /* Should have been rendered defunctional at first instead */
3612 assert(ntbtp != NULL);
3613 ntbtp->tbt_bind = tbcp;
3614 NYD2_LEAVE;
3617 static struct a_tty_bind_tree *
3618 a_tty__bind_tree_add_wc(struct a_tty_bind_tree **treep,
3619 struct a_tty_bind_tree *parentp, wchar_t wc, bool_t isseq){
3620 struct a_tty_bind_tree *tbtp, *xtbtp;
3621 NYD2_ENTER;
3623 if(parentp == NULL){
3624 treep += wc % HSHSIZE;
3626 /* Having no parent also means that the tree slot is possibly empty */
3627 for(tbtp = *treep; tbtp != NULL;
3628 parentp = tbtp, tbtp = tbtp->tbt_sibling){
3629 if(tbtp->tbt_char != wc)
3630 continue;
3631 if(tbtp->tbt_isseq == isseq)
3632 goto jleave;
3633 /* isseq MUST be linked before !isseq, so record this "parent"
3634 * sibling, but continue searching for now.
3635 * Otherwise it is impossible that we'll find what we look for */
3636 if(isseq){
3637 #ifdef HAVE_DEBUG
3638 while((tbtp = tbtp->tbt_sibling) != NULL)
3639 assert(tbtp->tbt_char != wc);
3640 #endif
3641 break;
3645 tbtp = smalloc(sizeof *tbtp);
3646 memset(tbtp, 0, sizeof *tbtp);
3647 tbtp->tbt_char = wc;
3648 tbtp->tbt_isseq = isseq;
3650 if(parentp == NULL){
3651 tbtp->tbt_sibling = *treep;
3652 *treep = tbtp;
3653 }else{
3654 tbtp->tbt_sibling = parentp->tbt_sibling;
3655 parentp->tbt_sibling = tbtp;
3657 }else{
3658 if((tbtp = *(treep = &parentp->tbt_childs)) != NULL){
3659 for(;; tbtp = xtbtp){
3660 if(tbtp->tbt_char == wc){
3661 if(tbtp->tbt_isseq == isseq)
3662 goto jleave;
3663 /* isseq MUST be linked before, so it is impossible that we'll
3664 * find what we look for */
3665 if(isseq){
3666 #ifdef HAVE_DEBUG
3667 while((tbtp = tbtp->tbt_sibling) != NULL)
3668 assert(tbtp->tbt_char != wc);
3669 #endif
3670 tbtp = NULL;
3671 break;
3675 if((xtbtp = tbtp->tbt_sibling) == NULL){
3676 treep = &tbtp->tbt_sibling;
3677 break;
3682 xtbtp = smalloc(sizeof *xtbtp);
3683 memset(xtbtp, 0, sizeof *xtbtp);
3684 xtbtp->tbt_parent = parentp;
3685 xtbtp->tbt_char = wc;
3686 xtbtp->tbt_isseq = isseq;
3687 tbtp = xtbtp;
3688 *treep = tbtp;
3690 jleave:
3691 NYD2_LEAVE;
3692 return tbtp;
3695 static void
3696 a_tty__bind_tree_free(struct a_tty_bind_tree *tbtp){
3697 NYD2_ENTER;
3698 while(tbtp != NULL){
3699 struct a_tty_bind_tree *tmp;
3701 if((tmp = tbtp->tbt_childs) != NULL)
3702 a_tty__bind_tree_free(tmp);
3704 tmp = tbtp->tbt_sibling;
3705 free(tbtp);
3706 tbtp = tmp;
3708 NYD2_LEAVE;
3710 # endif /* HAVE_KEY_BINDINGS */
3712 FL void
3713 n_tty_init(void){
3714 NYD_ENTER;
3716 if(ok_blook(line_editor_disable))
3717 goto jleave;
3719 /* Load the history file */
3720 # ifdef HAVE_HISTORY
3721 do/* for break */{
3722 char const *v;
3723 char *lbuf;
3724 FILE *f;
3725 size_t lsize, cnt, llen;
3727 if((v = a_tty_hist_query_config()) == NULL ||
3728 a_tty.tg_hist_size_max == 0)
3729 break;
3731 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
3732 f = fopen(v, "r"); /* TODO HISTFILE LOAD: use linebuf pool */
3733 if(f == NULL)
3734 goto jhist_done;
3735 (void)n_file_lock(fileno(f), FLT_READ, 0,0, UIZ_MAX);
3737 assert(!(n_pstate & n_PS_ROOT));
3738 n_pstate |= n_PS_ROOT; /* Allow calling addhist() */
3739 lbuf = NULL;
3740 lsize = 0;
3741 cnt = (size_t)fsize(f);
3742 while(fgetline(&lbuf, &lsize, &cnt, &llen, f, FAL0) != NULL){
3743 if(llen > 0 && lbuf[llen - 1] == '\n')
3744 lbuf[--llen] = '\0';
3745 if(llen == 0 || lbuf[0] == '#') /* xxx comments? noone! */
3746 continue;
3747 else{
3748 bool_t isgabby;
3750 isgabby = (lbuf[0] == '*');
3751 n_tty_addhist(lbuf + isgabby, isgabby);
3754 if(lbuf != NULL)
3755 free(lbuf);
3756 n_pstate &= ~n_PS_ROOT;
3758 fclose(f);
3759 jhist_done:
3760 rele_all_sigs(); /* XXX remove jumps */
3761 }while(0);
3762 # endif /* HAVE_HISTORY */
3764 /* Force immediate resolve for anything which follows */
3765 n_psonce |= n_PSO_LINE_EDITOR_INIT;
3767 # ifdef HAVE_KEY_BINDINGS
3768 /* `bind's (and `unbind's) done from within resource files couldn't be
3769 * performed for real since our termcap driver wasn't yet loaded, and we
3770 * can't perform automatic init since the user may have disallowed so */
3771 /* C99 */{
3772 struct a_tty_bind_ctx *tbcp;
3773 enum n_go_input_flags gif;
3775 for(gif = 0; gif < n__GO_INPUT_CTX_MAX1; ++gif)
3776 for(tbcp = a_tty.tg_bind[gif]; tbcp != NULL; tbcp = tbcp->tbc_next)
3777 if((tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
3778 a_TTY_BIND_RESOLVE)
3779 a_tty_bind_resolve(tbcp);
3782 /* And we want to (try to) install some default key bindings */
3783 if(!ok_blook(line_editor_no_defaults)){
3784 char buf[8];
3785 struct a_tty_bind_parse_ctx tbpc;
3786 struct a_tty_bind_builtin_tuple const *tbbtp, *tbbtp_max;
3787 ui32_t flags;
3789 buf[0] = '$', buf[1] = '\'', buf[2] = '\\', buf[3] = 'c',
3790 buf[5] = '\'', buf[6] = '\0';
3792 tbbtp = a_tty_bind_base_tuples;
3793 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_base_tuples)];
3794 flags = n_GO_INPUT_CTX_BASE;
3795 jbuiltin_redo:
3796 for(; tbbtp < tbbtp_max; ++tbbtp){
3797 memset(&tbpc, 0, sizeof tbpc);
3798 tbpc.tbpc_cmd = "bind";
3799 if(tbbtp->tbbt_iskey){
3800 buf[4] = tbbtp->tbbt_ckey;
3801 tbpc.tbpc_in_seq = buf;
3802 }else
3803 tbpc.tbpc_in_seq = savecatsep(":", '\0',
3804 n_termcap_name_of_query(tbbtp->tbbt_query));
3805 tbpc.tbpc_exp.s = n_UNCONST(tbbtp->tbbt_exp[0] == '\0'
3806 ? a_tty_bind_fun_names[(ui8_t)tbbtp->tbbt_exp[1]]
3807 : tbbtp->tbbt_exp);
3808 tbpc.tbpc_exp.l = strlen(tbpc.tbpc_exp.s);
3809 tbpc.tbpc_flags = flags;
3810 /* ..but don't want to overwrite any user settings */
3811 a_tty_bind_create(&tbpc, FAL0);
3813 if(flags == n_GO_INPUT_CTX_BASE){
3814 tbbtp = a_tty_bind_default_tuples;
3815 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_default_tuples)];
3816 flags = n_GO_INPUT_CTX_DEFAULT;
3817 goto jbuiltin_redo;
3820 # endif /* HAVE_KEY_BINDINGS */
3822 jleave:
3823 NYD_LEAVE;
3826 FL void
3827 n_tty_destroy(bool_t xit_fastpath){
3828 NYD_ENTER;
3830 if(!(n_psonce & n_PSO_LINE_EDITOR_INIT))
3831 goto jleave;
3833 # ifdef HAVE_HISTORY
3834 if(!xit_fastpath) do/* for break */{
3835 size_t i;
3836 char const *v;
3837 struct a_tty_hist *thp;
3838 bool_t dogabby;
3839 FILE *f;
3841 if((v = a_tty_hist_query_config()) == NULL ||
3842 a_tty.tg_hist_size_max == 0)
3843 break;
3845 dogabby = ok_blook(history_gabby_persist);
3847 if((thp = a_tty.tg_hist) != NULL)
3848 for(i = a_tty.tg_hist_size_max; thp->th_older != NULL;
3849 thp = thp->th_older)
3850 if((dogabby || !thp->th_isgabby) && --i == 0)
3851 break;
3853 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
3854 f = fopen(v, "w"); /* TODO temporary + rename?! */
3855 if(f == NULL)
3856 goto jhist_done;
3857 (void)n_file_lock(fileno(f), FLT_WRITE, 0,0, UIZ_MAX);
3859 for(; thp != NULL; thp = thp->th_younger){
3860 if(dogabby || !thp->th_isgabby){
3861 if(thp->th_isgabby)
3862 putc('*', f);
3863 fwrite(thp->th_dat, sizeof *thp->th_dat, thp->th_len, f);
3864 putc('\n', f);
3867 fclose(f);
3868 jhist_done:
3869 rele_all_sigs(); /* XXX remove jumps */
3870 }while(0);
3871 # endif /* HAVE_HISTORY */
3873 # if defined HAVE_KEY_BINDINGS && defined HAVE_DEBUG
3874 n_go_command(n_GO_INPUT_NONE, "unbind * *");
3875 # endif
3877 # ifdef HAVE_DEBUG
3878 memset(&a_tty, 0, sizeof a_tty);
3880 n_psonce &= ~n_PSO_LINE_EDITOR_INIT;
3881 # endif
3882 jleave:
3883 NYD_LEAVE;
3886 FL int
3887 (n_tty_readline)(enum n_go_input_flags gif, char const *prompt,
3888 char **linebuf, size_t *linesize, size_t n, bool_t *histok_or_null
3889 n_MEMORY_DEBUG_ARGS){
3890 struct a_tty_line tl;
3891 struct n_string xprompt;
3892 # ifdef HAVE_COLOUR
3893 char *posbuf, *pos;
3894 # endif
3895 ssize_t nn;
3896 NYD_ENTER;
3897 n_UNUSED(gif);
3899 assert(!ok_blook(line_editor_disable));
3900 if(!(n_psonce & n_PSO_LINE_EDITOR_INIT))
3901 n_tty_init();
3902 assert(n_psonce & n_PSO_LINE_EDITOR_INIT);
3904 # ifdef HAVE_COLOUR
3905 n_colour_env_create(n_COLOUR_CTX_MLE, n_tty_fp, FAL0);
3907 /* .tl_pos_buf is a hack */
3908 posbuf = pos = NULL;
3910 if(n_COLOUR_IS_ACTIVE()){
3911 char const *ccol;
3912 struct n_colour_pen *ccp;
3913 struct str const *sp;
3915 if((ccp = n_colour_pen_create(n_COLOUR_ID_MLE_POSITION, NULL)) != NULL &&
3916 (sp = n_colour_pen_to_str(ccp)) != NULL){
3917 ccol = sp->s;
3918 if((sp = n_colour_reset_to_str()) != NULL){
3919 size_t l1, l2;
3921 l1 = strlen(ccol);
3922 l2 = strlen(sp->s);
3923 posbuf = salloc(l1 + 4 + l2 +1);
3924 memcpy(posbuf, ccol, l1);
3925 pos = &posbuf[l1];
3926 memcpy(&pos[4], sp->s, ++l2);
3931 if(posbuf == NULL){
3932 posbuf = pos = salloc(4 +1);
3933 pos[4] = '\0';
3935 # endif /* HAVE_COLOUR */
3937 memset(&tl, 0, sizeof tl);
3939 # ifdef HAVE_KEY_BINDINGS
3940 /* C99 */{
3941 char const *cp;
3943 if((cp = ok_vlook(bind_timeout)) != NULL){
3944 ui64_t uib;
3946 n_idec_ui64_cp(&uib, cp, 0, NULL);
3948 if(uib > 0 &&
3949 /* Convert to tenths of a second, unfortunately */
3950 (uib = (uib + 99) / 100) <= a_TTY_BIND_TIMEOUT_MAX)
3951 tl.tl_bind_timeout = (ui8_t)uib;
3952 else if(n_poption & n_PO_D_V)
3953 n_err(_("Ignoring invalid *bind-timeout*: %s\n"), cp);
3957 if(a_tty.tg_bind_isdirty)
3958 a_tty_bind_tree_teardown();
3959 if(a_tty.tg_bind_cnt > 0 && !a_tty.tg_bind_isbuild)
3960 a_tty_bind_tree_build();
3961 tl.tl_bind_tree_hmap = &a_tty.tg_bind_tree[gif & n__GO_INPUT_CTX_MASK];
3962 tl.tl_bind_shcut_cancel =
3963 &a_tty.tg_bind_shcut_cancel[gif & n__GO_INPUT_CTX_MASK];
3964 tl.tl_bind_shcut_prompt_char =
3965 &a_tty.tg_bind_shcut_prompt_char[gif & n__GO_INPUT_CTX_MASK];
3966 # endif /* HAVE_KEY_BINDINGS */
3968 # ifdef HAVE_COLOUR
3969 tl.tl_pos_buf = posbuf;
3970 tl.tl_pos = pos;
3971 # endif
3973 if(!(gif & n_GO_INPUT_PROMPT_NONE)){
3974 n_string_creat_auto(&xprompt);
3976 if((tl.tl_prompt_width = n_tty_create_prompt(&xprompt, prompt, gif)
3977 ) > 0){
3978 tl.tl_prompt = n_string_cp_const(&xprompt);
3979 tl.tl_prompt_length = (ui32_t)xprompt.s_len;
3983 tl.tl_line.cbuf = *linebuf;
3984 if(n != 0){
3985 tl.tl_defc.s = savestrbuf(*linebuf, n);
3986 tl.tl_defc.l = n;
3988 tl.tl_x_buf = linebuf;
3989 tl.tl_x_bufsize = linesize;
3991 a_tty.tg_line = &tl;
3992 a_tty_sigs_up();
3993 n_TERMCAP_RESUME(FAL0);
3994 a_tty_term_mode(TRU1);
3995 nn = a_tty_readline(&tl, n, histok_or_null n_MEMORY_DEBUG_ARGSCALL);
3996 n_COLOUR( n_colour_env_gut(); )
3997 a_tty_term_mode(FAL0);
3998 n_TERMCAP_SUSPEND(FAL0);
3999 a_tty_sigs_down();
4000 a_tty.tg_line = NULL;
4002 NYD_LEAVE;
4003 return (int)nn;
4006 FL void
4007 n_tty_addhist(char const *s, bool_t isgabby){
4008 # ifdef HAVE_HISTORY
4009 /* Super-Heavy-Metal: block all sigs, avoid leaks+ on jump */
4010 ui32_t l;
4011 struct a_tty_hist *thp, *othp, *ythp;
4012 # endif
4013 NYD_ENTER;
4014 n_UNUSED(s);
4015 n_UNUSED(isgabby);
4017 # ifdef HAVE_HISTORY
4018 if(*s == '\0' ||
4019 (!(n_psonce & n_PSO_LINE_EDITOR_INIT) && !(n_pstate & n_PS_ROOT)) ||
4020 a_tty.tg_hist_size_max == 0 ||
4021 ok_blook(line_editor_disable) ||
4022 (isgabby && !ok_blook(history_gabby)))
4023 goto j_leave;
4025 l = (ui32_t)strlen(s);
4027 /* Eliminating duplicates is expensive, but simply inacceptable so
4028 * during the load of a potentially large history file! */
4029 if(n_psonce & n_PSO_LINE_EDITOR_INIT)
4030 for(thp = a_tty.tg_hist; thp != NULL; thp = thp->th_older)
4031 if(thp->th_len == l && !strcmp(thp->th_dat, s)){
4032 hold_all_sigs(); /* TODO */
4033 if(thp->th_isgabby)
4034 thp->th_isgabby = !!isgabby;
4035 othp = thp->th_older;
4036 ythp = thp->th_younger;
4037 if(othp != NULL)
4038 othp->th_younger = ythp;
4039 else
4040 a_tty.tg_hist_tail = ythp;
4041 if(ythp != NULL)
4042 ythp->th_older = othp;
4043 else
4044 a_tty.tg_hist = othp;
4045 goto jleave;
4047 hold_all_sigs();
4049 ++a_tty.tg_hist_size;
4050 if((n_psonce & n_PSO_LINE_EDITOR_INIT) &&
4051 a_tty.tg_hist_size > a_tty.tg_hist_size_max){
4052 --a_tty.tg_hist_size;
4053 if((thp = a_tty.tg_hist_tail) != NULL){
4054 if((a_tty.tg_hist_tail = thp->th_younger) == NULL)
4055 a_tty.tg_hist = NULL;
4056 else
4057 a_tty.tg_hist_tail->th_older = NULL;
4058 free(thp);
4062 thp = smalloc(n_VSTRUCT_SIZEOF(struct a_tty_hist, th_dat) + l +1);
4063 thp->th_isgabby = !!isgabby;
4064 thp->th_len = l;
4065 memcpy(thp->th_dat, s, l +1);
4066 jleave:
4067 if((thp->th_older = a_tty.tg_hist) != NULL)
4068 a_tty.tg_hist->th_younger = thp;
4069 else
4070 a_tty.tg_hist_tail = thp;
4071 thp->th_younger = NULL;
4072 a_tty.tg_hist = thp;
4074 rele_all_sigs();
4075 j_leave:
4076 # endif /* HAVE_HISTORY */
4077 NYD_LEAVE;
4080 # ifdef HAVE_HISTORY
4081 FL int
4082 c_history(void *v){
4083 siz_t entry;
4084 struct a_tty_hist *thp;
4085 char **argv;
4086 NYD_ENTER;
4088 if(ok_blook(line_editor_disable)){
4089 n_err(_("history: *line-editor-disable* is set\n"));
4090 goto jerr;
4093 if(!(n_psonce & n_PSO_LINE_EDITOR_INIT)){
4094 n_tty_init();
4095 assert(n_psonce & n_PSO_LINE_EDITOR_INIT);
4098 if(*(argv = v) == NULL)
4099 goto jlist;
4100 if(argv[1] != NULL)
4101 goto jerr;
4102 if(!asccasecmp(*argv, "show"))
4103 goto jlist;
4104 if(!asccasecmp(*argv, "clear"))
4105 goto jclear;
4106 if((n_idec_siz_cp(&entry, *argv, 10, NULL
4107 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
4108 ) == n_IDEC_STATE_CONSUMED)
4109 goto jentry;
4110 jerr:
4111 n_err(_("Synopsis: history: %s\n"),
4112 /* Same string as in cmd-tab.h, still hoping...) */
4113 _("<show> (default), <clear> or select <NO> from editor history"));
4114 v = NULL;
4115 jleave:
4116 NYD_LEAVE;
4117 return (v == NULL ? !STOP : !OKAY); /* xxx 1:bad 0:good -- do some */
4119 jlist:{
4120 size_t i, b;
4121 FILE *fp;
4123 if(a_tty.tg_hist == NULL)
4124 goto jleave;
4126 if((fp = Ftmp(NULL, "hist", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
4127 n_perr(_("tmpfile"), 0);
4128 v = NULL;
4129 goto jleave;
4132 i = a_tty.tg_hist_size;
4133 b = 0;
4134 for(thp = a_tty.tg_hist; thp != NULL;
4135 --i, b += thp->th_len, thp = thp->th_older){
4136 fprintf(fp, "%c%" PRIuZ, (thp->th_isgabby ? '*' : ' '), i);
4137 if(n_poption & n_PO_D_V)
4138 fprintf(fp, " (%" PRIuZ "+%" PRIu32 ")", b, thp->th_len);
4139 putc('\t', fp);
4140 fputs(thp->th_dat, fp);
4141 putc('\n', fp);
4144 page_or_print(fp, i);
4145 Fclose(fp);
4147 goto jleave;
4149 jclear:
4150 while((thp = a_tty.tg_hist) != NULL){
4151 a_tty.tg_hist = thp->th_older;
4152 free(thp);
4154 a_tty.tg_hist_tail = NULL;
4155 a_tty.tg_hist_size = 0;
4156 goto jleave;
4158 jentry:{
4159 siz_t ep;
4161 ep = (entry < 0) ? -entry : entry;
4163 if(ep != 0 && UICMP(z, ep, <=, a_tty.tg_hist_size)){
4164 if(ep != entry)
4165 --ep;
4166 else
4167 ep = (siz_t)a_tty.tg_hist_size - ep;
4168 for(thp = a_tty.tg_hist;; thp = thp->th_older){
4169 assert(thp != NULL);
4170 if(ep-- == 0){
4171 n_go_input_inject((n_GO_INPUT_INJECT_COMMIT |
4172 n_GO_INPUT_INJECT_HISTORY), v = thp->th_dat, thp->th_len);
4173 break;
4176 }else{
4177 n_err(_("`history': no such entry: %" PRIdZ "\n"), entry);
4178 v = NULL;
4181 goto jleave;
4183 # endif /* HAVE_HISTORY */
4185 # ifdef HAVE_KEY_BINDINGS
4186 FL int
4187 c_bind(void *v){
4188 struct a_tty_bind_ctx *tbcp;
4189 enum n_go_input_flags gif;
4190 bool_t aster, show;
4191 union {char const *cp; char *p; char c;} c;
4192 struct n_cmd_arg_ctx *cacp;
4193 NYD_ENTER;
4195 cacp = v;
4197 c.cp = cacp->cac_arg->ca_arg.ca_str.s;
4198 if(cacp->cac_no == 1)
4199 show = TRU1;
4200 else
4201 show = !asccasecmp(cacp->cac_arg->ca_next->ca_arg.ca_str.s, "show");
4202 aster = FAL0;
4204 if((gif = a_tty_bind_ctx_find(c.cp)) == (enum n_go_input_flags)-1){
4205 if(!(aster = n_is_all_or_aster(c.cp)) || !show){
4206 n_err(_("`bind': invalid context: %s\n"), c.cp);
4207 v = NULL;
4208 goto jleave;
4210 gif = 0;
4213 if(show){
4214 ui32_t lns;
4215 FILE *fp;
4217 if((fp = Ftmp(NULL, "bind", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
4218 n_perr(_("tmpfile"), 0);
4219 v = NULL;
4220 goto jleave;
4223 lns = 0;
4224 for(;;){
4225 for(tbcp = a_tty.tg_bind[gif]; tbcp != NULL;
4226 ++lns, tbcp = tbcp->tbc_next){
4227 /* Print the bytes of resolved terminal capabilities, then */
4228 if((n_poption & n_PO_D_V) &&
4229 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)
4230 ) == a_TTY_BIND_RESOLVE){
4231 char cbuf[8];
4232 union {wchar_t const *wp; char const *cp;} u;
4233 si32_t entlen;
4234 ui32_t cnvlen;
4235 char const *cnvdat, *bsep, *cbufp;
4237 putc('#', fp);
4238 putc(' ', fp);
4240 cbuf[0] = '=', cbuf[2] = '\0';
4241 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len;
4242 cnvlen > 0;){
4243 if(cnvdat != tbcp->tbc_cnv)
4244 putc(',', fp);
4246 /* {si32_t buf_len_iscap;} */
4247 entlen = *n_UNALIGN(si32_t const*,cnvdat);
4248 if(entlen & SI32_MIN){
4249 /* struct{si32_t buf_len_iscap; si32_t cap_len;
4250 * char buf[]+NUL;} */
4251 for(bsep = n_empty,
4252 u.cp = (char const*)
4253 &n_UNALIGN(si32_t const*,cnvdat)[2];
4254 (c.c = *u.cp) != '\0'; ++u.cp){
4255 if(asciichar(c.c) && !cntrlchar(c.c))
4256 cbuf[1] = c.c, cbufp = cbuf;
4257 else
4258 cbufp = n_empty;
4259 fprintf(fp, "%s%02X%s",
4260 bsep, (ui32_t)(ui8_t)c.c, cbufp);
4261 bsep = " ";
4263 entlen &= SI32_MAX;
4264 }else
4265 putc('-', fp);
4267 cnvlen -= entlen;
4268 cnvdat += entlen;
4271 fputs("\n ", fp);
4272 ++lns;
4275 fprintf(fp, "%sbind %s %s %s%s%s\n",
4276 ((tbcp->tbc_flags & a_TTY_BIND_DEFUNCT)
4277 /* I18N: `bind' sequence not working, either because it is
4278 * I18N: using Unicode and that is not available in the locale,
4279 * I18N: or a termcap(5)/terminfo(5) sequence won't work out */
4280 ? _("# <Defunctional> ") : n_empty),
4281 a_tty_bind_ctx_maps[gif].tbcm_name, tbcp->tbc_seq,
4282 n_shexp_quote_cp(tbcp->tbc_exp, TRU1),
4283 (tbcp->tbc_flags & a_TTY_BIND_NOCOMMIT ? n_at : n_empty),
4284 (!(n_poption & n_PO_D_VV) ? n_empty
4285 : (tbcp->tbc_flags & a_TTY_BIND_FUN_INTERNAL
4286 ? _(" # MLE internal") : n_empty))
4289 if(!aster || ++gif >= n__GO_INPUT_CTX_MAX1)
4290 break;
4292 page_or_print(fp, lns);
4294 Fclose(fp);
4295 }else{
4296 struct a_tty_bind_parse_ctx tbpc;
4297 struct n_cmd_arg *cap;
4299 memset(&tbpc, 0, sizeof tbpc);
4300 tbpc.tbpc_cmd = cacp->cac_desc->cad_name;
4301 tbpc.tbpc_in_seq = (cap = cacp->cac_arg->ca_next)->ca_arg.ca_str.s;
4302 if((cap = cap->ca_next) != NULL){
4303 tbpc.tbpc_exp.s = cap->ca_arg.ca_str.s;
4304 tbpc.tbpc_exp.l = cap->ca_arg.ca_str.l;
4306 tbpc.tbpc_flags = gif;
4307 if(!a_tty_bind_create(&tbpc, TRU1))
4308 v = NULL;
4310 jleave:
4311 NYD_LEAVE;
4312 return (v != NULL) ? n_EXIT_OK : n_EXIT_ERR;
4315 FL int
4316 c_unbind(void *v){
4317 struct a_tty_bind_parse_ctx tbpc;
4318 struct a_tty_bind_ctx *tbcp;
4319 enum n_go_input_flags gif;
4320 bool_t aster;
4321 union {char const *cp; char *p;} c;
4322 struct n_cmd_arg_ctx *cacp;
4323 NYD_ENTER;
4325 cacp = v;
4326 c.cp = cacp->cac_arg->ca_arg.ca_str.s;
4327 aster = FAL0;
4329 if((gif = a_tty_bind_ctx_find(c.cp)) == (enum n_go_input_flags)-1){
4330 if(!(aster = n_is_all_or_aster(c.cp))){
4331 n_err(_("`unbind': invalid context: %s\n"), c.cp);
4332 v = NULL;
4333 goto jleave;
4335 gif = 0;
4338 c.cp = cacp->cac_arg->ca_next->ca_arg.ca_str.s;
4339 jredo:
4340 if(n_is_all_or_aster(c.cp)){
4341 while((tbcp = a_tty.tg_bind[gif]) != NULL){
4342 memset(&tbpc, 0, sizeof tbpc);
4343 tbpc.tbpc_tbcp = tbcp;
4344 tbpc.tbpc_flags = gif;
4345 a_tty_bind_del(&tbpc);
4347 }else{
4348 memset(&tbpc, 0, sizeof tbpc);
4349 tbpc.tbpc_cmd = cacp->cac_desc->cad_name;
4350 tbpc.tbpc_in_seq = c.cp;
4351 tbpc.tbpc_flags = gif;
4353 if(n_UNLIKELY(!a_tty_bind_parse(FAL0, &tbpc)))
4354 v = NULL;
4355 else if(n_UNLIKELY((tbcp = tbpc.tbpc_tbcp) == NULL)){
4356 n_err(_("`unbind': no such `bind'ing: %s %s\n"),
4357 a_tty_bind_ctx_maps[gif].tbcm_name, c.cp);
4358 v = NULL;
4359 }else
4360 a_tty_bind_del(&tbpc);
4363 if(aster && ++gif < n__GO_INPUT_CTX_MAX1)
4364 goto jredo;
4365 jleave:
4366 NYD_LEAVE;
4367 return (v != NULL) ? n_EXIT_OK : n_EXIT_ERR;
4369 # endif /* HAVE_KEY_BINDINGS */
4371 #else /* HAVE_MLE */
4373 * The really-nothing-at-all implementation
4376 static void
4377 a_tty_signal(int sig){
4378 /* Prototype at top */
4379 # ifdef HAVE_TERMCAP
4380 sigset_t nset, oset;
4381 # endif
4382 NYD_X; /* Signal handler */
4383 n_UNUSED(sig);
4385 # ifdef HAVE_TERMCAP
4386 n_TERMCAP_SUSPEND(TRU1);
4387 a_tty_sigs_down();
4389 sigemptyset(&nset);
4390 sigaddset(&nset, sig);
4391 sigprocmask(SIG_UNBLOCK, &nset, &oset);
4392 n_raise(sig);
4393 /* When we come here we'll continue editing, so reestablish */
4394 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
4396 a_tty_sigs_up();
4397 n_TERMCAP_RESUME(TRU1);
4398 # endif /* HAVE_TERMCAP */
4401 # if 0
4402 FL void
4403 n_tty_init(void){
4404 NYD_ENTER;
4405 NYD_LEAVE;
4408 FL void
4409 n_tty_destroy(bool_t xit_fastpath){
4410 NYD_ENTER;
4411 n_UNUSED(xit_fastpath);
4412 NYD_LEAVE;
4414 # endif /* 0 */
4416 FL int
4417 (n_tty_readline)(enum n_go_input_flags gif, char const *prompt,
4418 char **linebuf, size_t *linesize, size_t n, bool_t *histok_or_null
4419 n_MEMORY_DEBUG_ARGS){
4420 struct n_string xprompt;
4421 int rv;
4422 NYD_ENTER;
4423 n_UNUSED(histok_or_null);
4425 if(!(gif & n_GO_INPUT_PROMPT_NONE)){
4426 if(n_tty_create_prompt(n_string_creat_auto(&xprompt), prompt, gif) > 0){
4427 fwrite(xprompt.s_dat, 1, xprompt.s_len, n_tty_fp);
4428 fflush(n_tty_fp);
4432 # ifdef HAVE_TERMCAP
4433 a_tty_sigs_up();
4434 n_TERMCAP_RESUME(FAL0);
4435 # endif
4436 rv = (readline_restart)(n_stdin, linebuf, linesize, n
4437 n_MEMORY_DEBUG_ARGSCALL);
4438 # ifdef HAVE_TERMCAP
4439 n_TERMCAP_SUSPEND(FAL0);
4440 a_tty_sigs_down();
4441 # endif
4442 NYD_LEAVE;
4443 return rv;
4446 FL void
4447 n_tty_addhist(char const *s, bool_t isgabby){
4448 NYD_ENTER;
4449 n_UNUSED(s);
4450 n_UNUSED(isgabby);
4451 NYD_LEAVE;
4453 #endif /* nothing at all */
4455 #undef a_TTY_SIGNALS
4456 /* s-it-mode */