Generalize and straigthen handling of the soft-exit-status *!*
[s-mailx.git] / tty.c
blob1524e858e0963209d28ecb6f225e3b92e20fffb3
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 #ifdef a_TTY_SIGNALS
43 static void
44 a_tty_sigs_up(void){
45 sigset_t nset, oset;
46 NYD2_ENTER;
48 sigfillset(&nset);
50 sigprocmask(SIG_BLOCK, &nset, &oset);
51 a_tty_oint = safe_signal(SIGINT, &n_tty_signal);
52 a_tty_oquit = safe_signal(SIGQUIT, &n_tty_signal);
53 a_tty_oterm = safe_signal(SIGTERM, &n_tty_signal);
54 a_tty_ohup = safe_signal(SIGHUP, &n_tty_signal);
55 a_tty_otstp = safe_signal(SIGTSTP, &n_tty_signal);
56 a_tty_ottin = safe_signal(SIGTTIN, &n_tty_signal);
57 a_tty_ottou = safe_signal(SIGTTOU, &n_tty_signal);
58 sigprocmask(SIG_SETMASK, &oset, NULL);
59 NYD2_LEAVE;
62 static void
63 a_tty_sigs_down(void){
64 sigset_t nset, oset;
65 NYD2_ENTER;
67 sigfillset(&nset);
69 sigprocmask(SIG_BLOCK, &nset, &oset);
70 safe_signal(SIGINT, a_tty_oint);
71 safe_signal(SIGQUIT, a_tty_oquit);
72 safe_signal(SIGTERM, a_tty_oterm);
73 safe_signal(SIGHUP, a_tty_ohup);
74 safe_signal(SIGTSTP, a_tty_otstp);
75 safe_signal(SIGTTIN, a_tty_ottin);
76 safe_signal(SIGTTOU, a_tty_ottou);
77 sigprocmask(SIG_SETMASK, &oset, NULL);
78 NYD2_LEAVE;
80 #endif /* a_TTY_SIGNALS */
82 static sigjmp_buf a_tty__actjmp; /* TODO someday, we won't need it no more */
83 static void
84 a_tty__acthdl(int s) /* TODO someday, we won't need it no more */
86 NYD_X; /* Signal handler */
87 termios_state_reset();
88 siglongjmp(a_tty__actjmp, s);
91 FL bool_t
92 getapproval(char const * volatile prompt, bool_t noninteract_default)
94 sighandler_type volatile oint, ohup;
95 bool_t volatile rv;
96 int volatile sig;
97 NYD_ENTER;
99 if(!(n_psonce & n_PSO_INTERACTIVE)){
100 sig = 0;
101 rv = noninteract_default;
102 goto jleave;
104 rv = FAL0;
106 /* C99 */{
107 char const *quest = noninteract_default
108 ? _("[yes]/no? ") : _("[no]/yes? ");
110 if (prompt == NULL)
111 prompt = _("Continue");
112 prompt = savecatsep(prompt, ' ', quest);
115 oint = safe_signal(SIGINT, SIG_IGN);
116 ohup = safe_signal(SIGHUP, SIG_IGN);
117 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
118 goto jrestore;
119 safe_signal(SIGINT, &a_tty__acthdl);
120 safe_signal(SIGHUP, &a_tty__acthdl);
122 if (n_lex_input(n_LEXINPUT_CTX_DEFAULT | n_LEXINPUT_NL_ESC, prompt,
123 &termios_state.ts_linebuf, &termios_state.ts_linesize, NULL) >= 0)
124 rv = (boolify(termios_state.ts_linebuf, UIZ_MAX,
125 noninteract_default) > 0);
126 jrestore:
127 termios_state_reset();
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_lex_input(n_LEXINPUT_CTX_DEFAULT | n_LEXINPUT_NL_ESC, query,
158 &termios_state.ts_linebuf, &termios_state.ts_linesize, NULL) >= 0)
159 user = termios_state.ts_linebuf;
160 jrestore:
161 termios_state_reset();
163 safe_signal(SIGHUP, ohup);
164 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_lexinput_flags lif){
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(lif & n_LEXINPUT_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 = (lif & n_LEXINPUT_PROMPT_EVAL)
262 ? (lif & n_LEXINPUT_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(lif & n_LEXINPUT_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 /* C99 */{
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 (FEXP_FULL | FEXP_SILENT | FEXP_MULTIOK)
432 /* Columns to ripoff: outermost may not be touched, plus position indicator.
433 * Must thus be at least 1, but should be >= 1+4 to dig the position indicator
434 * that we place (if there is sufficient space) */
435 # define a_TTY_WIDTH_RIPOFF 5
437 /* The implementation of the MLE functions always exists, and is based upon
438 * the a_TTY_BIND_FUN_* constants, so most of this enum is always necessary */
439 enum a_tty_bind_flags{
440 # ifdef HAVE_KEY_BINDINGS
441 a_TTY_BIND_RESOLVE = 1u<<8, /* Term cap. yet needs to be resolved */
442 a_TTY_BIND_DEFUNCT = 1u<<9, /* Unicode/term cap. used but not avail. */
443 a_TTY__BIND_MASK = a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT,
444 /* MLE fun assigned to a one-byte-sequence: this may be used for special
445 * key-sequence bypass processing */
446 a_TTY_BIND_MLE1CNTRL = 1u<<10,
447 a_TTY_BIND_NOCOMMIT = 1u<<11, /* Expansion shall be editable */
448 # endif
450 /* MLE internal commands */
451 a_TTY_BIND_FUN_INTERNAL = 1u<<15,
452 a_TTY__BIND_FUN_SHIFT = 16u,
453 a_TTY__BIND_FUN_SHIFTMAX = 24u,
454 a_TTY__BIND_FUN_MASK = ((1u << a_TTY__BIND_FUN_SHIFTMAX) - 1) &
455 ~((1u << a_TTY__BIND_FUN_SHIFT) - 1),
456 # define a_TTY_BIND_FUN_REDUCE(X) \
457 (((ui32_t)(X) & a_TTY__BIND_FUN_MASK) >> a_TTY__BIND_FUN_SHIFT)
458 # define a_TTY_BIND_FUN_EXPAND(X) \
459 (((ui32_t)(X) & (a_TTY__BIND_FUN_MASK >> a_TTY__BIND_FUN_SHIFT)) << \
460 a_TTY__BIND_FUN_SHIFT)
461 # undef a_X
462 # define a_X(N,I)\
463 a_TTY_BIND_FUN_ ## N = a_TTY_BIND_FUN_EXPAND(I),
465 a_X(BELL, 0)
466 a_X(GO_BWD, 1) a_X(GO_FWD, 2)
467 a_X(GO_WORD_BWD, 3) a_X(GO_WORD_FWD, 4)
468 a_X(GO_HOME, 5) a_X(GO_END, 6)
469 a_X(DEL_BWD, 7) a_X(DEL_FWD, 8)
470 a_X(SNARF_WORD_BWD, 9) a_X(SNARF_WORD_FWD, 10)
471 a_X(SNARF_END, 11) a_X(SNARF_LINE, 12)
472 a_X(HIST_BWD, 13) a_X(HIST_FWD, 14)
473 a_X(HIST_SRCH_BWD, 15) a_X(HIST_SRCH_FWD, 16)
474 a_X(REPAINT, 17)
475 a_X(QUOTE_RNDTRIP, 18)
476 a_X(PROMPT_CHAR, 19)
477 a_X(COMPLETE, 20)
478 a_X(PASTE, 21)
480 a_X(CANCEL, 22)
481 a_X(RESET, 23)
482 a_X(FULLRESET, 24)
483 a_X(COMMIT, 25) /* Must be last one! */
484 # undef a_X
486 a_TTY__BIND_LAST = 1<<25
488 # ifdef HAVE_KEY_BINDINGS
489 n_CTA((ui32_t)a_TTY_BIND_RESOLVE >= (ui32_t)n__LEXINPUT_CTX_MAX1,
490 "Bit carrier lower boundary must be raised to avoid value sharing");
491 # endif
492 n_CTA(a_TTY_BIND_FUN_EXPAND(a_TTY_BIND_FUN_COMMIT) <
493 (1 << a_TTY__BIND_FUN_SHIFTMAX),
494 "Bit carrier range must be expanded to represent necessary bits");
495 n_CTA(a_TTY__BIND_LAST >= (1u << a_TTY__BIND_FUN_SHIFTMAX),
496 "Bit carrier upper boundary must be raised to avoid value sharing");
497 n_CTA(UICMP(64, a_TTY__BIND_LAST, <=, SI32_MAX),
498 "Flag bits excess storage datatype" /* And we need one bit free */);
500 enum a_tty_fun_status{
501 a_TTY_FUN_STATUS_OK, /* Worked, next character */
502 a_TTY_FUN_STATUS_COMMIT, /* Line done */
503 a_TTY_FUN_STATUS_RESTART, /* Complete restart, reset multibyte etc. */
504 a_TTY_FUN_STATUS_END /* End, return EOF */
507 enum a_tty_visual_flags{
508 a_TTY_VF_NONE,
509 a_TTY_VF_MOD_CURSOR = 1u<<0, /* Cursor moved */
510 a_TTY_VF_MOD_CONTENT = 1u<<1, /* Content modified */
511 a_TTY_VF_MOD_DIRTY = 1u<<2, /* Needs complete repaint */
512 a_TTY_VF_MOD_SINGLE = 1u<<3, /* TODO Drop when indirection as above comes */
513 a_TTY_VF_REFRESH = a_TTY_VF_MOD_DIRTY | a_TTY_VF_MOD_CURSOR |
514 a_TTY_VF_MOD_CONTENT | a_TTY_VF_MOD_SINGLE,
515 a_TTY_VF_BELL = 1u<<8, /* Ring the bell */
516 a_TTY_VF_SYNC = 1u<<9, /* Flush/Sync I/O channel */
518 a_TTY_VF_ALL_MASK = a_TTY_VF_REFRESH | a_TTY_VF_BELL | a_TTY_VF_SYNC,
519 a_TTY__VF_LAST = a_TTY_VF_SYNC
522 # ifdef HAVE_KEY_BINDINGS
523 struct a_tty_bind_ctx{
524 struct a_tty_bind_ctx *tbc_next;
525 char *tbc_seq; /* quence as given (poss. re-quoted), in .tb__buf */
526 char *tbc_exp; /* ansion, in .tb__buf */
527 /* The .tbc_seq'uence with any terminal capabilities resolved; in fact an
528 * array of structures, the first entry of which is {si32_t buf_len_iscap;}
529 * where the signed bit indicates whether the buffer is a resolved terminal
530 * capability instead of a (possibly multibyte) character. In .tbc__buf */
531 char *tbc_cnv;
532 ui32_t tbc_seq_len;
533 ui32_t tbc_exp_len;
534 ui32_t tbc_cnv_len;
535 ui32_t tbc_flags;
536 char tbc__buf[n_VFIELD_SIZE(0)];
539 struct a_tty_bind_ctx_map{
540 enum n_lexinput_flags tbcm_ctx;
541 char const tbcm_name[12]; /* Name of `bind' context */
543 # endif /* HAVE_KEY_BINDINGS */
545 struct a_tty_bind_builtin_tuple{
546 bool_t tbbt_iskey; /* Whether this is a control key; else termcap query */
547 char tbbt_ckey; /* Control code */
548 ui16_t tbbt_query; /* enum n_termcap_query (instead) */
549 char tbbt_exp[12]; /* String or [0]=NUL/[1]=BIND_FUN_REDUCE() */
551 n_CTA(n__TERMCAP_QUERY_MAX1 <= UI16_MAX,
552 "Enumeration cannot be stored in datatype");
554 # ifdef HAVE_KEY_BINDINGS
555 struct a_tty_bind_parse_ctx{
556 char const *tbpc_cmd; /* Command which parses */
557 char const *tbpc_in_seq; /* In: key sequence */
558 struct str tbpc_exp; /* In/Out: expansion (or NULL) */
559 struct a_tty_bind_ctx *tbpc_tbcp; /* Out: if yet existent */
560 struct a_tty_bind_ctx *tbpc_ltbcp; /* Out: the one before .tbpc_tbcp */
561 char *tbpc_seq; /* Out: normalized sequence */
562 char *tbpc_cnv; /* Out: sequence when read(2)ing it */
563 ui32_t tbpc_seq_len;
564 ui32_t tbpc_cnv_len;
565 ui32_t tbpc_cnv_align_mask; /* For creating a_tty_bind_ctx.tbc_cnv */
566 ui32_t tbpc_flags; /* n_lexinput_flags | a_tty_bind_flags */
569 /* Input character tree */
570 struct a_tty_bind_tree{
571 struct a_tty_bind_tree *tbt_sibling; /* s at same level */
572 struct a_tty_bind_tree *tbt_childs; /* Sequence continues.. here */
573 struct a_tty_bind_tree *tbt_parent;
574 struct a_tty_bind_ctx *tbt_bind; /* NULL for intermediates */
575 wchar_t tbt_char; /* acter this level represents */
576 bool_t tbt_isseq; /* Belongs to multibyte sequence */
577 bool_t tbt_isseq_trail; /* ..is trailing byte of it */
578 ui8_t tbt__dummy[2];
580 # endif /* HAVE_KEY_BINDINGS */
582 struct a_tty_cell{
583 wchar_t tc_wc;
584 ui16_t tc_count; /* ..of bytes */
585 ui8_t tc_width; /* Visual width; TAB==UI8_MAX! */
586 bool_t tc_novis; /* Don't display visually as such (control character) */
587 char tc_cbuf[MB_LEN_MAX * 2]; /* .. plus reset shift sequence */
590 struct a_tty_global{
591 struct a_tty_line *tg_line; /* To be able to access it from signal hdl */
592 # ifdef HAVE_HISTORY
593 struct a_tty_hist *tg_hist;
594 struct a_tty_hist *tg_hist_tail;
595 size_t tg_hist_size;
596 size_t tg_hist_size_max;
597 # endif
598 # ifdef HAVE_KEY_BINDINGS
599 ui32_t tg_bind_cnt; /* Overall number of bindings */
600 bool_t tg_bind_isdirty;
601 bool_t tg_bind_isbuild;
602 # define a_TTY_SHCUT_MAX (3 +1) /* Note: update manual on change! */
603 ui8_t tg_bind__dummy[2];
604 char tg_bind_shcut_cancel[n__LEXINPUT_CTX_MAX1][a_TTY_SHCUT_MAX];
605 char tg_bind_shcut_prompt_char[n__LEXINPUT_CTX_MAX1][a_TTY_SHCUT_MAX];
606 struct a_tty_bind_ctx *tg_bind[n__LEXINPUT_CTX_MAX1];
607 struct a_tty_bind_tree *tg_bind_tree[n__LEXINPUT_CTX_MAX1][HSHSIZE];
608 # endif
609 struct termios tg_tios_old;
610 struct termios tg_tios_new;
612 # ifdef HAVE_KEY_BINDINGS
613 n_CTA(n__LEXINPUT_CTX_MAX1 == 3 && a_TTY_SHCUT_MAX == 4 &&
614 n_SIZEOF_FIELD(struct a_tty_global, tg_bind__dummy) == 2,
615 "Value results in array sizes that results in bad structure layout");
616 n_CTA(a_TTY_SHCUT_MAX > 1,
617 "Users need at least one shortcut, plus NUL terminator");
618 # endif
620 # ifdef HAVE_HISTORY
621 struct a_tty_hist{
622 struct a_tty_hist *th_older;
623 struct a_tty_hist *th_younger;
624 ui32_t th_isgabby : 1;
625 ui32_t th_len : 31;
626 char th_dat[n_VFIELD_SIZE(sizeof(ui32_t))];
628 # endif
630 struct a_tty_line{
631 /* Caller pointers */
632 char **tl_x_buf;
633 size_t *tl_x_bufsize;
634 /* Input processing */
635 # ifdef HAVE_KEY_BINDINGS
636 wchar_t tl_bind_takeover; /* Leftover byte to consume next */
637 ui8_t tl_bind_timeout; /* In-seq. inter-byte-timer, in 1/10th secs */
638 ui8_t tl__bind_dummy[3];
639 char (*tl_bind_shcut_cancel)[a_TTY_SHCUT_MAX]; /* Special _CANCEL control */
640 char (*tl_bind_shcut_prompt_char)[a_TTY_SHCUT_MAX]; /* ..for _PROMPT_CHAR */
641 struct a_tty_bind_tree *(*tl_bind_tree_hmap)[HSHSIZE]; /* Bind lookup tree */
642 struct a_tty_bind_tree *tl_bind_tree;
643 # endif
644 /* Line data / content handling */
645 ui32_t tl_count; /* ..of a_tty_cell's (<= a_TTY_LINE_MAX) */
646 ui32_t tl_cursor; /* Current a_tty_cell insertion point */
647 union{
648 char *cbuf; /* *.tl_x_buf */
649 struct a_tty_cell *cells;
650 } tl_line;
651 struct str tl_defc; /* Current default content */
652 size_t tl_defc_cursor_byte; /* Desired position of cursor after takeover */
653 struct str tl_savec; /* Saved default content */
654 struct str tl_pastebuf; /* Last snarfed data */
655 # ifdef HAVE_HISTORY
656 struct a_tty_hist *tl_hist; /* History cursor */
657 # endif
658 ui32_t tl_count_max; /* ..before buffer needs to grow */
659 /* Visual data representation handling */
660 ui32_t tl_vi_flags; /* enum a_tty_visual_flags */
661 ui32_t tl_lst_count; /* .tl_count after last sync */
662 ui32_t tl_lst_cursor; /* .tl_cursor after last sync */
663 /* TODO Add another indirection layer by adding a tl_phy_line of
664 * TODO a_tty_cell objects, incorporate changes in visual layer,
665 * TODO then check what _really_ has changed, sync those changes only */
666 struct a_tty_cell const *tl_phy_start; /* First visible cell, left border */
667 ui32_t tl_phy_cursor; /* Physical cursor position */
668 bool_t tl_quote_rndtrip; /* For _kht() expansion */
669 ui8_t tl__dummy2[3];
670 ui32_t tl_prompt_length; /* Preclassified (TODO needed as a_tty_cell) */
671 ui32_t tl_prompt_width;
672 char const *tl_prompt; /* Preformatted prompt (including colours) */
673 /* .tl_pos_buf is a hack */
674 # ifdef HAVE_COLOUR
675 char *tl_pos_buf; /* mle-position colour-on, [4], reset seq. */
676 char *tl_pos; /* Address of the [4] */
677 # endif
680 # ifdef HAVE_KEY_BINDINGS
681 /* C99: use [INDEX]={} */
682 n_CTAV(n_LEXINPUT_CTX_BASE == 0);
683 n_CTAV(n_LEXINPUT_CTX_DEFAULT == 1);
684 n_CTAV(n_LEXINPUT_CTX_COMPOSE == 2);
685 static struct a_tty_bind_ctx_map const
686 a_tty_bind_ctx_maps[n__LEXINPUT_CTX_MAX1] = {
687 {n_LEXINPUT_CTX_BASE, "base"},
688 {n_LEXINPUT_CTX_DEFAULT, "default"},
689 {n_LEXINPUT_CTX_COMPOSE, "compose"}
692 /* Special functions which our MLE provides internally.
693 * Update the manual upon change! */
694 static char const a_tty_bind_fun_names[][24] = {
695 # undef a_X
696 # define a_X(I,N) \
697 n_FIELD_INITI(a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## I)) "mle-" N "\0",
699 a_X(BELL, "bell")
700 a_X(GO_BWD, "go-bwd") a_X(GO_FWD, "go-fwd")
701 a_X(GO_WORD_BWD, "go-word-bwd") a_X(GO_WORD_FWD, "go-word-fwd")
702 a_X(GO_HOME, "go-home") a_X(GO_END, "go-end")
703 a_X(DEL_BWD, "del-bwd") a_X(DEL_FWD, "del-fwd")
704 a_X(SNARF_WORD_BWD, "snarf-word-bwd") a_X(SNARF_WORD_FWD, "snarf-word-fwd")
705 a_X(SNARF_END, "snarf-end") a_X(SNARF_LINE, "snarf-line")
706 a_X(HIST_BWD, "hist-bwd") a_X(HIST_FWD, "hist-fwd")
707 a_X(HIST_SRCH_BWD, "hist-srch-bwd") a_X(HIST_SRCH_FWD, "hist-srch-fwd")
708 a_X(REPAINT, "repaint")
709 a_X(QUOTE_RNDTRIP, "quote-rndtrip")
710 a_X(PROMPT_CHAR, "prompt-char")
711 a_X(COMPLETE, "complete")
712 a_X(PASTE, "paste")
714 a_X(CANCEL, "cancel")
715 a_X(RESET, "reset")
716 a_X(FULLRESET, "fullreset")
717 a_X(COMMIT, "commit")
719 # undef a_X
721 # endif /* HAVE_KEY_BINDINGS */
723 /* The default key bindings (unless disallowed). Update manual upon change!
724 * A logical subset of this table is also used if !HAVE_KEY_BINDINGS (more
725 * expensive than a switch() on control codes directly, but less redundant).
726 * The table for the "base" context */
727 static struct a_tty_bind_builtin_tuple const a_tty_bind_base_tuples[] = {
728 # undef a_X
729 # define a_X(K,S) \
730 {TRU1, K, 0, {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
732 a_X('A', GO_HOME)
733 a_X('B', GO_BWD)
734 /* C: SIGINT */
735 a_X('D', DEL_FWD)
736 a_X('E', GO_END)
737 a_X('F', GO_FWD)
738 a_X('G', RESET)
739 a_X('H', DEL_BWD)
740 a_X('I', COMPLETE)
741 a_X('J', COMMIT)
742 a_X('K', SNARF_END)
743 a_X('L', REPAINT)
744 /* M: same as J */
745 a_X('N', HIST_FWD)
746 /* O: below */
747 a_X('P', HIST_BWD)
748 a_X('Q', QUOTE_RNDTRIP)
749 a_X('R', HIST_SRCH_BWD)
750 a_X('S', HIST_SRCH_FWD)
751 a_X('T', PASTE)
752 a_X('U', SNARF_LINE)
753 a_X('V', PROMPT_CHAR)
754 a_X('W', SNARF_WORD_BWD)
755 a_X('X', GO_WORD_FWD)
756 a_X('Y', GO_WORD_BWD)
757 /* Z: SIGTSTP */
759 a_X('[', CANCEL)
760 /* \: below */
761 /* ]: below */
762 /* ^: below */
763 a_X('_', SNARF_WORD_FWD)
765 a_X('?', DEL_BWD)
767 # undef a_X
768 # define a_X(K,S) {TRU1, K, 0, {S}},
770 /* The remains only if we have `bind' functionality available */
771 # ifdef HAVE_KEY_BINDINGS
772 # undef a_X
773 # define a_X(Q,S) \
774 {FAL0, '\0', n_TERMCAP_QUERY_ ## Q,\
775 {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
777 a_X(key_backspace, DEL_BWD) a_X(key_dc, DEL_FWD)
778 a_X(key_eol, SNARF_END)
779 a_X(key_home, GO_HOME) a_X(key_end, GO_END)
780 a_X(key_left, GO_BWD) a_X(key_right, GO_FWD)
781 a_X(key_sleft, GO_HOME) a_X(key_sright, GO_END)
782 a_X(key_up, HIST_BWD) a_X(key_down, HIST_FWD)
783 # endif /* HAVE_KEY_BINDINGS */
786 /* The table for the "default" context.
787 * We don't want commands to end up in history, so place an initial space */
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 n_MEMORY_DEBUG_ARGS);
887 # ifdef HAVE_KEY_BINDINGS
888 /* Find context or -1 */
889 static enum n_lexinput_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_term_mode(bool_t raw){
921 struct termios *tiosp;
922 NYD2_ENTER;
924 tiosp = &a_tty.tg_tios_old;
925 if(!raw)
926 goto jleave;
928 /* Always requery the attributes, in case we've been moved from background
929 * to foreground or however else in between sessions */
930 /* XXX Always enforce ECHO and ICANON in the OLD attributes - do so as long
931 * XXX as we don't properly deal with TTIN and TTOU etc. */
932 tcgetattr(STDIN_FILENO, tiosp); /* TODO v15: use _only_ n_tty_fp! */
933 tiosp->c_lflag |= ECHO | ICANON;
935 memcpy(&a_tty.tg_tios_new, tiosp, sizeof *tiosp);
936 tiosp = &a_tty.tg_tios_new;
937 tiosp->c_cc[VMIN] = 1;
938 tiosp->c_cc[VTIME] = 0;
939 /* Enable ^\, ^Q and ^S to be used for key bindings */
940 tiosp->c_cc[VQUIT] = tiosp->c_cc[VSTART] = tiosp->c_cc[VSTOP] = '\0';
941 tiosp->c_iflag &= ~(ISTRIP | IGNCR);
942 tiosp->c_lflag &= ~(ECHO /*| ECHOE | ECHONL */| ICANON | IEXTEN);
943 jleave:
944 tcsetattr(STDIN_FILENO, TCSADRAIN, tiosp);
945 NYD2_LEAVE;
948 # ifdef HAVE_HISTORY
949 static char const *
950 a_tty_hist_query_config(void){
951 char const *rv, *cp;
952 NYD2_ENTER;
954 if((cp = ok_vlook(NAIL_HISTSIZE)) != NULL)
955 n_OBSOLETE(_("please use *history-size* instead of *NAIL_HISTSIZE*"));
956 if((rv = ok_vlook(history_size)) == NULL)
957 rv = cp;
958 if(rv == NULL)
959 a_tty.tg_hist_size_max = UIZ_MAX;
960 else
961 (void)n_idec_uiz_cp(&a_tty.tg_hist_size_max, rv, 10, NULL);
963 if((cp = ok_vlook(NAIL_HISTFILE)) != NULL)
964 n_OBSOLETE(_("please use *history-file* instead of *NAIL_HISTFILE*"));
965 if((rv = ok_vlook(history_file)) == NULL)
966 rv = cp;
967 if(rv != NULL)
968 rv = fexpand(rv, FEXP_LOCAL | FEXP_NSHELL);
969 NYD2_LEAVE;
970 return rv;
972 # endif /* HAVE_HISTORY */
974 # ifdef HAVE_KEY_BINDINGS
975 static void
976 a_tty_term_rawmode_timeout(struct a_tty_line *tlp, bool_t enable){
977 NYD2_ENTER;
978 if(enable){
979 ui8_t bt;
981 a_tty.tg_tios_new.c_cc[VMIN] = 0;
982 if((bt = tlp->tl_bind_timeout) == 0)
983 bt = a_TTY_BIND_TIMEOUT;
984 a_tty.tg_tios_new.c_cc[VTIME] = bt;
985 }else{
986 a_tty.tg_tios_new.c_cc[VMIN] = 1;
987 a_tty.tg_tios_new.c_cc[VTIME] = 0;
989 tcsetattr(STDIN_FILENO, TCSANOW, &a_tty.tg_tios_new);
990 NYD2_LEAVE;
992 # endif /* HAVE_KEY_BINDINGS */
994 static ui8_t
995 a_tty_wcwidth(wchar_t wc){
996 ui8_t rv;
997 NYD2_ENTER;
999 /* Special case the backslash at first */
1000 if(wc == '\t')
1001 rv = UI8_MAX;
1002 else{
1003 int i;
1005 # ifdef HAVE_WCWIDTH
1006 rv = ((i = wcwidth(wc)) > 0) ? (ui8_t)i : 0;
1007 # else
1008 rv = iswprint(wc) ? 1 + (wc >= 0x1100u) : 0; /* TODO use S-CText */
1009 # endif
1011 NYD2_LEAVE;
1012 return rv;
1015 static void
1016 a_tty_check_grow(struct a_tty_line *tlp, ui32_t no n_MEMORY_DEBUG_ARGS){
1017 ui32_t cmax;
1018 NYD2_ENTER;
1020 if(n_UNLIKELY((cmax = tlp->tl_count + no) > tlp->tl_count_max)){
1021 size_t i;
1023 i = cmax * sizeof(struct a_tty_cell) + 2 * sizeof(struct a_tty_cell);
1024 if(n_LIKELY(i >= *tlp->tl_x_bufsize)){
1025 hold_all_sigs(); /* XXX v15 drop */
1026 i <<= 1;
1027 tlp->tl_line.cbuf =
1028 *tlp->tl_x_buf = (n_realloc)(*tlp->tl_x_buf, i
1029 n_MEMORY_DEBUG_ARGSCALL);
1030 rele_all_sigs(); /* XXX v15 drop */
1032 tlp->tl_count_max = cmax;
1033 *tlp->tl_x_bufsize = i;
1035 NYD2_LEAVE;
1038 static ssize_t
1039 a_tty_cell2dat(struct a_tty_line *tlp){
1040 size_t len, i;
1041 NYD2_ENTER;
1043 len = 0;
1045 if(n_LIKELY((i = tlp->tl_count) > 0)){
1046 struct a_tty_cell const *tcap;
1048 tcap = tlp->tl_line.cells;
1050 memcpy(tlp->tl_line.cbuf + len, tcap->tc_cbuf, tcap->tc_count);
1051 len += tcap->tc_count;
1052 }while(++tcap, --i > 0);
1055 tlp->tl_line.cbuf[len] = '\0';
1056 NYD2_LEAVE;
1057 return (ssize_t)len;
1060 static void
1061 a_tty_cell2save(struct a_tty_line *tlp){
1062 size_t len, i;
1063 struct a_tty_cell *tcap;
1064 NYD2_ENTER;
1066 tlp->tl_savec.s = NULL;
1067 tlp->tl_savec.l = 0;
1069 if(n_UNLIKELY(tlp->tl_count == 0))
1070 goto jleave;
1072 for(tcap = tlp->tl_line.cells, len = 0, i = tlp->tl_count; i > 0;
1073 ++tcap, --i)
1074 len += tcap->tc_count;
1076 tlp->tl_savec.s = salloc((tlp->tl_savec.l = len) +1);
1078 for(tcap = tlp->tl_line.cells, len = 0, i = tlp->tl_count; i > 0;
1079 ++tcap, --i){
1080 memcpy(tlp->tl_savec.s + len, tcap->tc_cbuf, tcap->tc_count);
1081 len += tcap->tc_count;
1083 tlp->tl_savec.s[len] = '\0';
1084 jleave:
1085 NYD2_LEAVE;
1088 static void
1089 a_tty_copy2paste(struct a_tty_line *tlp, struct a_tty_cell *tcpmin,
1090 struct a_tty_cell *tcpmax){
1091 char *cp;
1092 struct a_tty_cell *tcp;
1093 size_t l;
1094 NYD2_ENTER;
1096 l = 0;
1097 for(tcp = tcpmin; tcp < tcpmax; ++tcp)
1098 l += tcp->tc_count;
1100 tlp->tl_pastebuf.s = cp = salloc((tlp->tl_pastebuf.l = l) +1);
1102 l = 0;
1103 for(tcp = tcpmin; tcp < tcpmax; cp += l, ++tcp)
1104 memcpy(cp, tcp->tc_cbuf, l = tcp->tc_count);
1105 *cp = '\0';
1106 NYD2_LEAVE;
1109 static wchar_t
1110 a_tty_vinuni(struct a_tty_line *tlp){
1111 char buf[16];
1112 uiz_t i;
1113 wchar_t wc;
1114 NYD2_ENTER;
1116 wc = '\0';
1118 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr) ||
1119 !n_termcap_cmd(n_TERMCAP_CMD_ce, 0, -1))
1120 goto jleave;
1122 /* C99 */{
1123 struct str const *cpre, *csuf;
1124 #ifdef HAVE_COLOUR
1125 struct n_colour_pen *cpen;
1127 cpen = n_colour_pen_create(n_COLOUR_ID_MLE_PROMPT, NULL);
1128 if((cpre = n_colour_pen_to_str(cpen)) != NULL)
1129 csuf = n_colour_reset_to_str();
1130 else
1131 csuf = NULL;
1132 #else
1133 cpre = csuf = NULL;
1134 #endif
1135 fprintf(n_tty_fp, _("%sPlease enter Unicode code point:%s "),
1136 (cpre != NULL ? cpre->s : n_empty),
1137 (csuf != NULL ? csuf->s : n_empty));
1139 fflush(n_tty_fp);
1141 buf[sizeof(buf) -1] = '\0';
1142 for(i = 0;;){
1143 if(read(STDIN_FILENO, &buf[i], 1) != 1){
1144 if(errno == EINTR) /* xxx #if !SA_RESTART ? */
1145 continue;
1146 goto jleave;
1148 if(buf[i] == '\n')
1149 break;
1150 if(!hexchar(buf[i])){
1151 char const emsg[] = "[0-9a-fA-F]";
1153 n_LCTA(sizeof emsg <= sizeof(buf), "Preallocated buffer too small");
1154 memcpy(buf, emsg, sizeof emsg);
1155 goto jerr;
1158 putc(buf[i], n_tty_fp);
1159 fflush(n_tty_fp);
1160 if(++i == sizeof buf)
1161 goto jerr;
1163 buf[i] = '\0';
1165 if((n_idec_uiz_cp(&i, buf, 16, NULL
1166 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
1167 ) != n_IDEC_STATE_CONSUMED || i > 0x10FFFF/* XXX magic; CText */){
1168 jerr:
1169 n_err(_("\nInvalid input: %s\n"), buf);
1170 goto jleave;
1173 wc = (wchar_t)i;
1174 jleave:
1175 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY | (wc == '\0' ? a_TTY_VF_BELL : 0);
1176 NYD2_LEAVE;
1177 return wc;
1180 static bool_t
1181 a_tty_vi_refresh(struct a_tty_line *tlp){
1182 bool_t rv;
1183 NYD2_ENTER;
1185 if(tlp->tl_vi_flags & a_TTY_VF_BELL){
1186 tlp->tl_vi_flags |= a_TTY_VF_SYNC;
1187 if(putc('\a', n_tty_fp) == EOF)
1188 goto jerr;
1191 if(tlp->tl_vi_flags & a_TTY_VF_REFRESH){
1192 /* kht may want to restore a cursor position after inserting some
1193 * data somewhere */
1194 if(tlp->tl_defc_cursor_byte > 0){
1195 size_t i, j;
1196 ssize_t k;
1198 a_tty_khome(tlp, FAL0);
1200 i = tlp->tl_defc_cursor_byte;
1201 tlp->tl_defc_cursor_byte = 0;
1202 for(j = 0; tlp->tl_cursor < tlp->tl_count; ++j){
1203 a_tty_kright(tlp);
1204 if((k = tlp->tl_line.cells[j].tc_count) > i)
1205 break;
1206 i -= k;
1210 if(!a_tty_vi__paint(tlp))
1211 goto jerr;
1214 if(tlp->tl_vi_flags & a_TTY_VF_SYNC){
1215 tlp->tl_vi_flags &= ~a_TTY_VF_SYNC;
1216 if(fflush(n_tty_fp))
1217 goto jerr;
1220 rv = TRU1;
1221 jleave:
1222 tlp->tl_vi_flags &= ~a_TTY_VF_ALL_MASK;
1223 NYD2_LEAVE;
1224 return rv;
1226 jerr:
1227 clearerr(n_tty_fp); /* xxx I/O layer rewrite */
1228 n_err(_("Visual refresh failed! Is $TERM set correctly?\n"
1229 " Setting *line-editor-disable* to get us through!\n"));
1230 ok_bset(line_editor_disable);
1231 rv = FAL0;
1232 goto jleave;
1235 static bool_t
1236 a_tty_vi__paint(struct a_tty_line *tlp){
1237 enum{
1238 a_TRUE_RV = a_TTY__VF_LAST<<1, /* Return value bit */
1239 a_HAVE_PROMPT = a_TTY__VF_LAST<<2, /* Have a prompt */
1240 a_SHOW_PROMPT = a_TTY__VF_LAST<<3, /* Shall print the prompt */
1241 a_MOVE_CURSOR = a_TTY__VF_LAST<<4, /* Move visual cursor for user! */
1242 a_LEFT_MIN = a_TTY__VF_LAST<<5, /* On left boundary */
1243 a_RIGHT_MAX = a_TTY__VF_LAST<<6,
1244 a_HAVE_POSITION = a_TTY__VF_LAST<<7, /* Print the position indicator */
1246 /* We carry some flags over invocations (not worth a specific field) */
1247 a_VISIBLE_PROMPT = a_TTY__VF_LAST<<8, /* The prompt is on the screen */
1248 a_PERSIST_MASK = a_VISIBLE_PROMPT,
1249 a__LAST = a_PERSIST_MASK
1252 ui32_t f, w, phy_wid_base, phy_wid, phy_base, phy_cur, cnt,
1253 DBG(lstcur COMMA) cur,
1254 vi_left, /*vi_right,*/ phy_nxtcur;
1255 struct a_tty_cell const *tccp, *tcp_left, *tcp_right, *tcxp;
1256 NYD2_ENTER;
1257 n_LCTA(UICMP(64, a__LAST, <, UI32_MAX), "Flag bits excess storage datatype");
1259 f = tlp->tl_vi_flags;
1260 tlp->tl_vi_flags = (f & ~(a_TTY_VF_REFRESH | a_PERSIST_MASK)) |
1261 a_TTY_VF_SYNC;
1262 f |= a_TRUE_RV;
1263 if((w = tlp->tl_prompt_width) > 0)
1264 f |= a_HAVE_PROMPT;
1265 f |= a_HAVE_POSITION;
1267 /* XXX We don't have a OnTerminalResize event (see main.c) yet, so we need
1268 * XXX to reevaluate our circumstances over and over again */
1269 /* Don't display prompt or position indicator on very small screens */
1270 if((phy_wid_base = (ui32_t)n_scrnwidth) <= a_TTY_WIDTH_RIPOFF)
1271 f &= ~(a_HAVE_PROMPT | a_HAVE_POSITION);
1272 else{
1273 phy_wid_base -= a_TTY_WIDTH_RIPOFF;
1275 /* Disable the prompt if the screen is too small; due to lack of some
1276 * indicator simply add a second ripoff */
1277 if((f & a_HAVE_PROMPT) && w + a_TTY_WIDTH_RIPOFF >= phy_wid_base)
1278 f &= ~a_HAVE_PROMPT;
1281 phy_wid = phy_wid_base;
1282 phy_base = 0;
1283 phy_cur = tlp->tl_phy_cursor;
1284 cnt = tlp->tl_count;
1285 DBG( lstcur = tlp->tl_lst_cursor; )
1287 /* XXX Assume dirty screen if shrunk */
1288 if(cnt < tlp->tl_lst_count)
1289 f |= a_TTY_VF_MOD_DIRTY;
1291 /* TODO Without HAVE_TERMCAP, it would likely be much cheaper to simply
1292 * TODO always "cr + paint + ce + ch", since ce is simulated via spaces.. */
1294 /* Quickshot: if the line is empty, possibly print prompt and out */
1295 if(cnt == 0){
1296 /* In that special case dirty anything if it seems better */
1297 if((f & a_TTY_VF_MOD_CONTENT) || tlp->tl_lst_count > 0)
1298 f |= a_TTY_VF_MOD_DIRTY;
1300 if((f & a_TTY_VF_MOD_DIRTY) && phy_cur != 0){
1301 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
1302 goto jerr;
1303 phy_cur = 0;
1306 if((f & (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)) ==
1307 (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)){
1308 if(fputs(tlp->tl_prompt, n_tty_fp) == EOF)
1309 goto jerr;
1310 phy_cur = tlp->tl_prompt_width + 1;
1313 /* May need to clear former line content */
1314 if((f & a_TTY_VF_MOD_DIRTY) &&
1315 !n_termcap_cmd(n_TERMCAP_CMD_ce, phy_cur, -1))
1316 goto jerr;
1318 tlp->tl_phy_start = tlp->tl_line.cells;
1319 goto jleave;
1322 /* Try to get an idea of the visual window */
1324 /* Find the left visual boundary */
1325 phy_wid = (phy_wid >> 1) + (phy_wid >> 2);
1326 if((cur = tlp->tl_cursor) == cnt)
1327 --cur;
1329 w = (tcp_left = tccp = tlp->tl_line.cells + cur)->tc_width;
1330 if(w == UI8_MAX) /* TODO yet TAB == SPC */
1331 w = 1;
1332 while(tcp_left > tlp->tl_line.cells){
1333 ui16_t cw = tcp_left[-1].tc_width;
1335 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1336 cw = 1;
1337 if(w + cw >= phy_wid)
1338 break;
1339 w += cw;
1340 --tcp_left;
1342 vi_left = w;
1344 /* If the left hand side of our visual viewpoint consumes less than half
1345 * of the screen width, show the prompt */
1346 if(tcp_left == tlp->tl_line.cells)
1347 f |= a_LEFT_MIN;
1349 if((f & (a_LEFT_MIN | a_HAVE_PROMPT)) == (a_LEFT_MIN | a_HAVE_PROMPT) &&
1350 w + tlp->tl_prompt_width < phy_wid){
1351 phy_base = tlp->tl_prompt_width;
1352 f |= a_SHOW_PROMPT;
1355 /* Then search for right boundary. We always leave the rightmost column
1356 * empty because some terminals [cw]ould wrap the line if we write into
1357 * that. XXX terminfo(5)/termcap(5) have the semi_auto_right_margin/sam/YE
1358 * XXX capability to indicate this, but we don't look at that */
1359 phy_wid = phy_wid_base - phy_base;
1360 tcp_right = tlp->tl_line.cells + cnt;
1362 while(&tccp[1] < tcp_right){
1363 ui16_t cw = tccp[1].tc_width;
1364 ui32_t i;
1366 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1367 cw = 1;
1368 i = w + cw;
1369 if(i > phy_wid)
1370 break;
1371 w = i;
1372 ++tccp;
1374 /*vi_right = w - vi_left;*/
1376 /* If the complete line including prompt fits on the screen, show prompt */
1377 if(--tcp_right == tccp){
1378 f |= a_RIGHT_MAX;
1380 /* Since we did brute-force walk also for the left boundary we may end up
1381 * in a situation were anything effectively fits on the screen, including
1382 * the prompt that is, but were we don't recognize this since we
1383 * restricted the search to fit in some visual viewpoint. Therefore try
1384 * again to extend the left boundary to overcome that */
1385 if(!(f & a_LEFT_MIN)){
1386 struct a_tty_cell const *tc1p = tlp->tl_line.cells;
1387 ui32_t vil1 = vi_left;
1389 assert(!(f & a_SHOW_PROMPT));
1390 w += tlp->tl_prompt_width;
1391 for(tcxp = tcp_left;;){
1392 ui32_t i = tcxp[-1].tc_width;
1394 if(i == UI8_MAX) /* TODO yet TAB == SPC */
1395 i = 1;
1396 vil1 += i;
1397 i += w;
1398 if(i > phy_wid)
1399 break;
1400 w = i;
1401 if(--tcxp == tc1p){
1402 tcp_left = tc1p;
1403 vi_left = vil1;
1404 f |= a_LEFT_MIN;
1405 break;
1408 /*w -= tlp->tl_prompt_width;*/
1411 tcp_right = tccp;
1412 tccp = tlp->tl_line.cells + cur;
1414 if((f & (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT | a_SHOW_PROMPT)) ==
1415 (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT) &&
1416 w + tlp->tl_prompt_width <= phy_wid){
1417 phy_wid -= (phy_base = tlp->tl_prompt_width);
1418 f |= a_SHOW_PROMPT;
1421 /* Try to avoid repainting the complete line - this is possible if the
1422 * cursor "did not leave the screen" and the prompt status hasn't changed.
1423 * I.e., after clamping virtual viewpoint, compare relation to physical */
1424 if((f & (a_TTY_VF_MOD_SINGLE/*FIXME*/ |
1425 a_TTY_VF_MOD_CONTENT/* xxx */ | a_TTY_VF_MOD_DIRTY)) ||
1426 (tcxp = tlp->tl_phy_start) == NULL ||
1427 tcxp > tccp || tcxp <= tcp_right)
1428 f |= a_TTY_VF_MOD_DIRTY;
1429 else{
1430 f |= a_TTY_VF_MOD_DIRTY;
1431 #if 0
1432 struct a_tty_cell const *tcyp;
1433 si32_t cur_displace;
1434 ui32_t phy_lmargin, phy_rmargin, fx, phy_displace;
1436 phy_lmargin = (fx = phy_wid) / 100;
1437 phy_rmargin = fx - (phy_lmargin * a_TTY_SCROLL_MARGIN_RIGHT);
1438 phy_lmargin *= a_TTY_SCROLL_MARGIN_LEFT;
1439 fx = (f & (a_SHOW_PROMPT | a_VISIBLE_PROMPT));
1441 if(fx == 0 || fx == (a_SHOW_PROMPT | a_VISIBLE_PROMPT)){
1443 #endif
1445 goto jpaint;
1447 /* We know what we have to paint, start synchronizing */
1448 jpaint:
1449 assert(phy_cur == tlp->tl_phy_cursor);
1450 assert(phy_wid == phy_wid_base - phy_base);
1451 assert(cnt == tlp->tl_count);
1452 assert(cnt > 0);
1453 assert(lstcur == tlp->tl_lst_cursor);
1454 assert(tccp == tlp->tl_line.cells + cur);
1456 phy_nxtcur = phy_base; /* FIXME only if repaint cpl. */
1458 /* Quickshot: is it only cursor movement within the visible screen? */
1459 if((f & a_TTY_VF_REFRESH) == a_TTY_VF_MOD_CURSOR){
1460 f |= a_MOVE_CURSOR;
1461 goto jcursor;
1464 /* To be able to apply some quick jump offs, clear line if possible */
1465 if(f & a_TTY_VF_MOD_DIRTY){
1466 /* Force complete clearance and cursor reinitialization */
1467 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr) ||
1468 !n_termcap_cmd(n_TERMCAP_CMD_ce, 0, -1))
1469 goto jerr;
1470 tlp->tl_phy_start = tcp_left;
1471 phy_cur = 0;
1474 if((f & (a_TTY_VF_MOD_DIRTY | a_SHOW_PROMPT)) && phy_cur != 0){
1475 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
1476 goto jerr;
1477 phy_cur = 0;
1480 if(f & a_SHOW_PROMPT){
1481 assert(phy_base == tlp->tl_prompt_width);
1482 if(fputs(tlp->tl_prompt, n_tty_fp) == EOF)
1483 goto jerr;
1484 phy_cur = phy_nxtcur;
1485 f |= a_VISIBLE_PROMPT;
1486 }else
1487 f &= ~a_VISIBLE_PROMPT;
1489 /* FIXME reposition cursor for paint */
1490 for(w = phy_nxtcur; tcp_left <= tcp_right; ++tcp_left){
1491 ui16_t cw;
1493 cw = tcp_left->tc_width;
1495 if(n_LIKELY(!tcp_left->tc_novis)){
1496 if(fwrite(tcp_left->tc_cbuf, sizeof *tcp_left->tc_cbuf,
1497 tcp_left->tc_count, n_tty_fp) != tcp_left->tc_count)
1498 goto jerr;
1499 }else{ /* XXX Shouldn't be here <-> CText, ui_str.c */
1500 char wbuf[8]; /* XXX magic */
1502 if(n_psonce & n_PSO_UNICODE){
1503 ui32_t wc;
1505 wc = (ui32_t)tcp_left->tc_wc;
1506 if((wc & ~0x1Fu) == 0)
1507 wc |= 0x2400;
1508 else if(wc == 0x7F)
1509 wc = 0x2421;
1510 else
1511 wc = 0x2426;
1512 n_utf32_to_utf8(wc, wbuf);
1513 }else
1514 wbuf[0] = '?', wbuf[1] = '\0';
1516 if(fputs(wbuf, n_tty_fp) == EOF)
1517 goto jerr;
1518 cw = 1;
1521 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1522 cw = 1;
1523 w += cw;
1524 if(tcp_left == tccp)
1525 phy_nxtcur = w;
1526 phy_cur += cw;
1529 /* Write something position marker alike if it doesn't fit on screen */
1530 if((f & a_HAVE_POSITION) &&
1531 ((f & (a_LEFT_MIN | a_RIGHT_MAX)) != (a_LEFT_MIN | a_RIGHT_MAX) ||
1532 ((f & a_HAVE_PROMPT) && !(f & a_SHOW_PROMPT)))){
1533 # ifdef HAVE_COLOUR
1534 char *posbuf = tlp->tl_pos_buf, *pos = tlp->tl_pos;
1535 # else
1536 char posbuf[5], *pos = posbuf;
1538 pos[4] = '\0';
1539 # endif
1541 if(phy_cur != (w = phy_wid_base) &&
1542 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = w, 0))
1543 goto jerr;
1545 *pos++ = '|';
1546 if((f & a_LEFT_MIN) && (!(f & a_HAVE_PROMPT) || (f & a_SHOW_PROMPT)))
1547 memcpy(pos, "^.+", 3);
1548 else if(f & a_RIGHT_MAX)
1549 memcpy(pos, ".+$", 3);
1550 else{
1551 /* Theoretical line length limit a_TTY_LINE_MAX, choose next power of
1552 * ten (10 ** 10) to represent 100 percent, since we don't have a macro
1553 * that generates a constant, and i don't trust the standard "u type
1554 * suffix automatically scales" calculate the large number */
1555 static char const itoa[] = "0123456789";
1557 ui64_t const fact100 = (ui64_t)0x3B9ACA00u * 10u, fact = fact100 / 100;
1558 ui32_t i = (ui32_t)(((fact100 / cnt) * tlp->tl_cursor) / fact);
1559 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1561 if(i < 10)
1562 pos[0] = ' ', pos[1] = itoa[i];
1563 else
1564 pos[1] = itoa[i % 10], pos[0] = itoa[i / 10];
1565 pos[2] = '%';
1568 if(fputs(posbuf, n_tty_fp) == EOF)
1569 goto jerr;
1570 phy_cur += 4;
1573 /* Users are used to see the cursor right of the point of interest, so we
1574 * need some further adjustments unless in special conditions. Be aware
1575 * that we may have adjusted cur at the beginning, too */
1576 if((cur = tlp->tl_cursor) == 0)
1577 phy_nxtcur = phy_base;
1578 else if(cur != cnt){
1579 ui16_t cw = tccp->tc_width;
1581 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1582 cw = 1;
1583 phy_nxtcur -= cw;
1586 jcursor:
1587 if(((f & a_MOVE_CURSOR) || phy_nxtcur != phy_cur) &&
1588 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = phy_nxtcur, 0))
1589 goto jerr;
1591 jleave:
1592 tlp->tl_vi_flags |= (f & a_PERSIST_MASK);
1593 tlp->tl_lst_count = tlp->tl_count;
1594 tlp->tl_lst_cursor = tlp->tl_cursor;
1595 tlp->tl_phy_cursor = phy_cur;
1597 NYD2_LEAVE;
1598 return ((f & a_TRUE_RV) != 0);
1599 jerr:
1600 f &= ~a_TRUE_RV;
1601 goto jleave;
1604 static si32_t
1605 a_tty_wboundary(struct a_tty_line *tlp, si32_t dir){/* TODO shell token-wise */
1606 bool_t anynon;
1607 struct a_tty_cell *tcap;
1608 ui32_t cur, cnt;
1609 si32_t rv;
1610 NYD2_ENTER;
1612 assert(dir == 1 || dir == -1);
1614 rv = -1;
1615 cnt = tlp->tl_count;
1616 cur = tlp->tl_cursor;
1618 if(dir < 0){
1619 if(cur == 0)
1620 goto jleave;
1621 }else if(cur + 1 >= cnt)
1622 goto jleave;
1623 else
1624 --cnt, --cur; /* xxx Unsigned wrapping may occur (twice), then */
1626 for(rv = 0, tcap = tlp->tl_line.cells, anynon = FAL0;;){
1627 wchar_t wc;
1629 wc = tcap[cur += (ui32_t)dir].tc_wc;
1630 if(iswblank(wc) || iswpunct(wc)){
1631 if(anynon)
1632 break;
1633 }else
1634 anynon = TRU1;
1636 ++rv;
1638 if(dir < 0){
1639 if(cur == 0)
1640 break;
1641 }else if(cur + 1 >= cnt){
1642 ++rv;
1643 break;
1646 jleave:
1647 NYD2_LEAVE;
1648 return rv;
1651 static void
1652 a_tty_khome(struct a_tty_line *tlp, bool_t dobell){
1653 ui32_t f;
1654 NYD2_ENTER;
1656 if(n_LIKELY(tlp->tl_cursor > 0)){
1657 tlp->tl_cursor = 0;
1658 f = a_TTY_VF_MOD_CURSOR;
1659 }else if(dobell)
1660 f = a_TTY_VF_BELL;
1661 else
1662 f = a_TTY_VF_NONE;
1664 tlp->tl_vi_flags |= f;
1665 NYD2_LEAVE;
1668 static void
1669 a_tty_kend(struct a_tty_line *tlp){
1670 ui32_t f;
1671 NYD2_ENTER;
1673 if(n_LIKELY(tlp->tl_cursor < tlp->tl_count)){
1674 tlp->tl_cursor = tlp->tl_count;
1675 f = a_TTY_VF_MOD_CURSOR;
1676 }else
1677 f = a_TTY_VF_BELL;
1679 tlp->tl_vi_flags |= f;
1680 NYD2_LEAVE;
1683 static void
1684 a_tty_kbs(struct a_tty_line *tlp){
1685 ui32_t f, cur, cnt;
1686 NYD2_ENTER;
1688 cur = tlp->tl_cursor;
1689 cnt = tlp->tl_count;
1691 if(n_LIKELY(cur > 0)){
1692 tlp->tl_cursor = --cur;
1693 tlp->tl_count = --cnt;
1695 if((cnt -= cur) > 0){
1696 struct a_tty_cell *tcap;
1698 tcap = tlp->tl_line.cells + cur;
1699 memmove(tcap, &tcap[1], cnt *= sizeof(*tcap));
1701 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
1702 }else
1703 f = a_TTY_VF_BELL;
1705 tlp->tl_vi_flags |= f;
1706 NYD2_LEAVE;
1709 static void
1710 a_tty_ksnarf(struct a_tty_line *tlp, bool_t cplline, bool_t dobell){
1711 ui32_t i, f;
1712 NYD2_ENTER;
1714 f = a_TTY_VF_NONE;
1715 i = tlp->tl_cursor;
1717 if(cplline && i > 0){
1718 tlp->tl_cursor = i = 0;
1719 f = a_TTY_VF_MOD_CURSOR;
1722 if(n_LIKELY(i < tlp->tl_count)){
1723 struct a_tty_cell *tcap;
1725 tcap = &tlp->tl_line.cells[0];
1726 a_tty_copy2paste(tlp, &tcap[i], &tcap[tlp->tl_count]);
1727 tlp->tl_count = i;
1728 f = a_TTY_VF_MOD_CONTENT;
1729 }else if(dobell)
1730 f |= a_TTY_VF_BELL;
1732 tlp->tl_vi_flags |= f;
1733 NYD2_LEAVE;
1736 static si32_t
1737 a_tty_kdel(struct a_tty_line *tlp){
1738 ui32_t cur, cnt, f;
1739 si32_t i;
1740 NYD2_ENTER;
1742 cur = tlp->tl_cursor;
1743 cnt = tlp->tl_count;
1744 i = (si32_t)(cnt - cur);
1746 if(n_LIKELY(i > 0)){
1747 tlp->tl_count = --cnt;
1749 if(n_LIKELY(--i > 0)){
1750 struct a_tty_cell *tcap;
1752 tcap = &tlp->tl_line.cells[cur];
1753 memmove(tcap, &tcap[1], (ui32_t)i * sizeof(*tcap));
1755 f = a_TTY_VF_MOD_CONTENT;
1756 }else if(cnt == 0 && !ok_blook(ignoreeof)){
1757 putc('^', n_tty_fp);
1758 putc('D', n_tty_fp);
1759 i = -1;
1760 f = a_TTY_VF_NONE;
1761 }else{
1762 i = 0;
1763 f = a_TTY_VF_BELL;
1766 tlp->tl_vi_flags |= f;
1767 NYD2_LEAVE;
1768 return i;
1771 static void
1772 a_tty_kleft(struct a_tty_line *tlp){
1773 ui32_t f;
1774 NYD2_ENTER;
1776 if(n_LIKELY(tlp->tl_cursor > 0)){
1777 --tlp->tl_cursor;
1778 f = a_TTY_VF_MOD_CURSOR;
1779 }else
1780 f = a_TTY_VF_BELL;
1782 tlp->tl_vi_flags |= f;
1783 NYD2_LEAVE;
1786 static void
1787 a_tty_kright(struct a_tty_line *tlp){
1788 ui32_t i;
1789 NYD2_ENTER;
1791 if(n_LIKELY((i = tlp->tl_cursor + 1) <= tlp->tl_count)){
1792 tlp->tl_cursor = i;
1793 i = a_TTY_VF_MOD_CURSOR;
1794 }else
1795 i = a_TTY_VF_BELL;
1797 tlp->tl_vi_flags |= i;
1798 NYD2_LEAVE;
1801 static void
1802 a_tty_ksnarfw(struct a_tty_line *tlp, bool_t fwd){
1803 struct a_tty_cell *tcap;
1804 ui32_t cnt, cur, f;
1805 si32_t i;
1806 NYD2_ENTER;
1808 if(n_UNLIKELY((i = a_tty_wboundary(tlp, (fwd ? +1 : -1))) <= 0)){
1809 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
1810 goto jleave;
1813 cnt = tlp->tl_count - (ui32_t)i;
1814 cur = tlp->tl_cursor;
1815 if(!fwd)
1816 cur -= (ui32_t)i;
1817 tcap = &tlp->tl_line.cells[cur];
1819 a_tty_copy2paste(tlp, &tcap[0], &tcap[i]);
1821 if((tlp->tl_count = cnt) != (tlp->tl_cursor = cur)){
1822 cnt -= cur;
1823 memmove(&tcap[0], &tcap[i], cnt * sizeof(*tcap)); /* FIXME*/
1826 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
1827 jleave:
1828 tlp->tl_vi_flags |= f;
1829 NYD2_LEAVE;
1832 static void
1833 a_tty_kgow(struct a_tty_line *tlp, si32_t dir){
1834 ui32_t f;
1835 si32_t i;
1836 NYD2_ENTER;
1838 if(n_UNLIKELY((i = a_tty_wboundary(tlp, dir)) <= 0))
1839 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
1840 else{
1841 if(dir < 0)
1842 i = -i;
1843 tlp->tl_cursor += (ui32_t)i;
1844 f = a_TTY_VF_MOD_CURSOR;
1847 tlp->tl_vi_flags |= f;
1848 NYD2_LEAVE;
1851 static bool_t
1852 a_tty_kother(struct a_tty_line *tlp, wchar_t wc){
1853 /* Append if at EOL, insert otherwise;
1854 * since we may move around character-wise, always use a fresh ps */
1855 mbstate_t ps;
1856 struct a_tty_cell tc, *tcap;
1857 ui32_t f, cur, cnt;
1858 bool_t rv;
1859 NYD2_ENTER;
1861 rv = FAL0;
1862 f = a_TTY_VF_NONE;
1864 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1865 if(tlp->tl_count + 1 >= a_TTY_LINE_MAX){
1866 n_err(_("Stop here, we can't extend line beyond size limit\n"));
1867 goto jleave;
1870 /* First init a cell and see whether we'll really handle this wc */
1871 memset(&ps, 0, sizeof ps);
1872 /* C99 */{
1873 size_t l;
1875 l = wcrtomb(tc.tc_cbuf, tc.tc_wc = wc, &ps);
1876 if(n_UNLIKELY(l > MB_LEN_MAX)){
1877 jemb:
1878 n_err(_("wcrtomb(3) error: too many multibyte character bytes\n"));
1879 goto jleave;
1881 tc.tc_count = (ui16_t)l;
1883 if(n_UNLIKELY((n_psonce & n_PSO_ENC_MBSTATE) != 0)){
1884 l = wcrtomb(&tc.tc_cbuf[l], L'\0', &ps);
1885 if(n_LIKELY(l == 1))
1886 /* Only NUL terminator */;
1887 else if(n_LIKELY(--l < MB_LEN_MAX))
1888 tc.tc_count += (ui16_t)l;
1889 else
1890 goto jemb;
1894 /* Yes, we will! Place it in the array */
1895 tc.tc_novis = (iswprint(wc) == 0);
1896 tc.tc_width = a_tty_wcwidth(wc);
1897 /* TODO if(tc.tc_novis && tc.tc_width > 0) */
1899 cur = tlp->tl_cursor++;
1900 cnt = tlp->tl_count++ - cur;
1901 tcap = &tlp->tl_line.cells[cur];
1902 if(cnt >= 1){
1903 memmove(&tcap[1], tcap, cnt * sizeof(*tcap));
1904 f = a_TTY_VF_MOD_CONTENT;
1905 }else
1906 f = a_TTY_VF_MOD_SINGLE;
1907 memcpy(tcap, &tc, sizeof *tcap);
1909 f |= a_TTY_VF_MOD_CURSOR;
1910 rv = TRU1;
1911 jleave:
1912 if(!rv)
1913 f |= a_TTY_VF_BELL;
1914 tlp->tl_vi_flags |= f;
1915 NYD2_LEAVE;
1916 return rv;
1919 static ui32_t
1920 a_tty_kht(struct a_tty_line *tlp){
1921 ui8_t (*autorecmem)[n_MEMORY_AUTOREC_TYPE_SIZEOF], *autorec_persist;
1922 struct stat sb;
1923 struct str orig, bot, topp, sub, exp, preexp;
1924 struct n_string shou, *shoup;
1925 struct a_tty_cell *cword, *ctop, *cx;
1926 bool_t wedid, set_savec;
1927 ui32_t rv, f;
1928 NYD2_ENTER;
1930 /* Get plain line data; if this is the first expansion/xy, update the
1931 * very original content so that ^G gets the origin back */
1932 orig = tlp->tl_savec;
1933 a_tty_cell2save(tlp);
1934 exp = tlp->tl_savec;
1935 if(orig.s != NULL){
1936 /*tlp->tl_savec = orig;*/
1937 set_savec = FAL0;
1938 }else
1939 set_savec = TRU1;
1940 orig = exp;
1942 autorec_persist = n_memory_autorec_current();
1943 n_memory_autorec_push(autorecmem = n_lofi_alloc(sizeof *autorecmem));
1945 shoup = n_string_creat_auto(&shou);
1946 f = a_TTY_VF_NONE;
1948 /* Find the word to be expanded */
1950 cword = tlp->tl_line.cells;
1951 ctop = cword + tlp->tl_cursor;
1952 cx = cword + tlp->tl_count;
1954 /* topp: separate data right of cursor */
1955 if(cx > ctop){
1956 for(rv = 0; ctop < cx; ++ctop)
1957 rv += ctop->tc_count;
1958 topp.l = rv;
1959 topp.s = orig.s + orig.l - rv;
1960 ctop = cword + tlp->tl_cursor;
1961 }else
1962 topp.s = NULL, topp.l = 0;
1964 /* Find the shell token that corresponds to the cursor position */
1965 /* C99 */{
1966 size_t max;
1968 max = 0;
1969 if(ctop > cword){
1970 for(; cword < ctop; ++cword)
1971 max += cword->tc_count;
1972 cword = tlp->tl_line.cells;
1974 bot = sub = orig;
1975 bot.l = 0;
1976 sub.l = max;
1978 if(max > 0){
1979 for(;;){
1980 enum n_shexp_state shs;
1982 exp = sub;
1983 shs = n_shexp_parse_token((n_SHEXP_PARSE_DRYRUN |
1984 n_SHEXP_PARSE_TRIMSPACE | n_SHEXP_PARSE_IGNORE_EMPTY |
1985 n_SHEXP_PARSE_QUOTE_AUTO_CLOSE), NULL, &sub, NULL);
1986 if(sub.l != 0){
1987 size_t x;
1989 assert(max >= sub.l);
1990 x = max - sub.l;
1991 bot.l += x;
1992 max -= x;
1993 continue;
1995 if(shs & n_SHEXP_STATE_ERR_MASK){
1996 n_err(_("Invalid completion pattern: %.*s\n"),
1997 (int)exp.l, exp.s);
1998 goto jnope;
2000 n_shexp_parse_token((n_SHEXP_PARSE_TRIMSPACE |
2001 n_SHEXP_PARSE_IGNORE_EMPTY | n_SHEXP_PARSE_QUOTE_AUTO_CLOSE),
2002 shoup, &exp, NULL);
2003 break;
2006 sub.s = n_string_cp(shoup);
2007 sub.l = shoup->s_len;
2011 /* Leave room for "implicit asterisk" expansion, as below */
2012 if(sub.l == 0){
2013 wedid = TRU1;
2014 sub.s = n_UNCONST("*");
2015 sub.l = 1;
2018 preexp.s = n_UNCONST(n_empty);
2019 preexp.l = 0;
2020 wedid = FAL0;
2021 jredo:
2022 /* TODO Super-Heavy-Metal: block all sigs, avoid leaks on jump */
2023 hold_all_sigs();
2024 exp.s = fexpand(sub.s, a_TTY_TAB_FEXP_FL);
2025 rele_all_sigs();
2027 if(exp.s == NULL || (exp.l = strlen(exp.s)) == 0){
2028 /* No. But maybe the users' desire was to complete only a part of the
2029 * shell token of interest! TODO This can be improved, we would need to
2030 * TODO have shexp_parse to create a DOM structure of parsed snippets, so
2031 * TODO that we can tell for each snippet which quote is active and
2032 * TODO whether we may cross its boundary and/or apply expansion for it */
2033 if(wedid == TRU1){
2034 size_t i, li;
2036 wedid = TRUM1;
2037 for(li = UIZ_MAX, i = sub.l; i-- > 0;){
2038 char c;
2040 if((c = sub.s[i]) == '/' || c == '+' /* *folder*! */)
2041 li = i;
2042 /* Do stop once some "magic" characters are seen XXX magic set */
2043 else if(c == '<' || c == '>' || c == '=' || c == ':')
2044 break;
2046 if(li != UIZ_MAX){
2047 preexp = sub;
2048 preexp.l = li;
2049 sub.l -= li;
2050 sub.s += li;
2051 goto jredo;
2054 goto jnope;
2057 if(wedid == TRUM1 && preexp.l > 0)
2058 preexp.s = savestrbuf(preexp.s, preexp.l);
2060 /* May be multi-return! */
2061 if(n_pstate & n_PS_EXPAND_MULTIRESULT)
2062 goto jmulti;
2064 /* xxx That is not really true since the limit counts characters not bytes */
2065 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
2066 if(exp.l >= a_TTY_LINE_MAX - 1 || a_TTY_LINE_MAX - 1 - exp.l < preexp.l){
2067 n_err(_("Tabulator expansion would extend beyond line size limit\n"));
2068 goto jnope;
2071 /* If the expansion equals the original string, assume the user wants what
2072 * is usually known as tab completion, append `*' and restart */
2073 if(!wedid && exp.l == sub.l && !memcmp(exp.s, sub.s, exp.l)){
2074 if(sub.s[sub.l - 1] == '*')
2075 goto jnope;
2077 wedid = TRU1;
2078 shoup = n_string_push_c(shoup, '*');
2079 sub.s = n_string_cp(shoup);
2080 sub.l = shoup->s_len;
2081 goto jredo;
2084 /* If it is a directory, and there is not yet a / appended, then we want the
2085 * user to confirm that he wants to dive in -- with only a HT */
2086 if(wedid && exp.l == --sub.l && !memcmp(exp.s, sub.s, exp.l) &&
2087 exp.s[exp.l - 1] != '/'){
2088 if(stat(exp.s, &sb) || !S_ISDIR(sb.st_mode))
2089 goto jnope;
2090 sub.s = salloc(exp.l + 1 +1);
2091 memcpy(sub.s, exp.s, exp.l);
2092 sub.s[exp.l++] = '/';
2093 sub.s[exp.l] = '\0';
2094 exp.s = sub.s;
2095 wedid = FAL0;
2096 goto jset;
2097 }else{
2098 if(wedid && (wedid = (exp.s[exp.l - 1] == '*')))
2099 --exp.l;
2100 exp.s[exp.l] = '\0';
2101 jset:
2102 exp.l = strlen(exp.s = n_shexp_quote_cp(exp.s, tlp->tl_quote_rndtrip));
2103 tlp->tl_defc_cursor_byte = bot.l + preexp.l + exp.l -1;
2104 if(wedid)
2105 goto jnope;
2108 orig.l = bot.l + preexp.l + exp.l + topp.l;
2109 orig.s = n_autorec_alloc(autorec_persist, orig.l + 5 +1);
2110 if((rv = (ui32_t)bot.l) > 0)
2111 memcpy(orig.s, bot.s, rv);
2112 if(preexp.l > 0){
2113 memcpy(&orig.s[rv], preexp.s, preexp.l);
2114 rv += preexp.l;
2116 memcpy(&orig.s[rv], exp.s, exp.l);
2117 rv += exp.l;
2118 if(topp.l > 0){
2119 memcpy(&orig.s[rv], topp.s, topp.l);
2120 rv += topp.l;
2122 orig.s[rv] = '\0';
2124 tlp->tl_defc = orig;
2125 tlp->tl_count = tlp->tl_cursor = 0;
2126 f |= a_TTY_VF_MOD_DIRTY;
2127 jleave:
2128 n_memory_autorec_pop(autorecmem);
2129 n_lofi_free(autorecmem);
2130 tlp->tl_vi_flags |= f;
2131 NYD2_LEAVE;
2132 return rv;
2134 jmulti:{
2135 struct n_visual_info_ctx vic;
2136 struct str input;
2137 wc_t c2, c1;
2138 bool_t isfirst;
2139 char const *lococp;
2140 size_t locolen, scrwid, lnlen, lncnt, prefixlen;
2141 FILE *fp;
2143 if((fp = Ftmp(NULL, "tabex", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
2144 n_perr(_("tmpfile"), 0);
2145 fp = n_tty_fp;
2148 /* How long is the result string for real? Search the NUL NUL
2149 * terminator. While here, detect the longest entry to perform an
2150 * initial allocation of our accumulator string */
2151 locolen = preexp.l;
2153 size_t i;
2155 i = strlen(&exp.s[++exp.l]);
2156 locolen = n_MAX(locolen, i);
2157 exp.l += i;
2158 }while(exp.s[exp.l + 1] != '\0');
2160 shoup = n_string_reserve(n_string_trunc(shoup, 0),
2161 locolen + (locolen >> 1));
2163 /* Iterate (once again) over all results */
2164 scrwid = (size_t)n_scrnwidth - ((size_t)n_scrnwidth >> 3);
2165 lnlen = lncnt = 0;
2166 n_UNINIT(prefixlen, 0);
2167 n_UNINIT(lococp, NULL);
2168 n_UNINIT(c1, '\0');
2169 for(isfirst = TRU1; exp.l > 0; isfirst = FAL0, c1 = c2){
2170 size_t i;
2171 char const *fullpath;
2173 /* Next result */
2174 sub = exp;
2175 sub.l = i = strlen(sub.s);
2176 assert(exp.l >= i);
2177 if((exp.l -= i) > 0)
2178 --exp.l;
2179 exp.s += ++i;
2181 /* Separate dirname and basename */
2182 fullpath = sub.s;
2183 if(isfirst){
2184 char const *cp;
2186 if((cp = strrchr(fullpath, '/')) != NULL)
2187 prefixlen = PTR2SIZE(++cp - fullpath);
2188 else
2189 prefixlen = 0;
2191 if(prefixlen > 0 && prefixlen < sub.l){
2192 sub.l -= prefixlen;
2193 sub.s += prefixlen;
2196 /* We want case-insensitive sort-order */
2197 memset(&vic, 0, sizeof vic);
2198 vic.vic_indat = sub.s;
2199 vic.vic_inlen = sub.l;
2200 c2 = n_visual_info(&vic, n_VISUAL_INFO_ONE_CHAR) ? vic.vic_waccu
2201 : (ui8_t)*sub.s;
2202 #ifdef HAVE_C90AMEND1
2203 c2 = towlower(c2);
2204 #else
2205 c2 = lowerconv(c2);
2206 #endif
2208 /* Query longest common prefix along the way */
2209 if(isfirst){
2210 c1 = c2;
2211 lococp = sub.s;
2212 locolen = sub.l;
2213 }else if(locolen > 0){
2214 for(i = 0; i < locolen; ++i)
2215 if(lococp[i] != sub.s[i]){
2216 i = field_detect_clip(i, lococp, i);
2217 locolen = i;
2218 break;
2222 /* Prepare display */
2223 input = sub;
2224 shoup = n_shexp_quote(n_string_trunc(shoup, 0), &input,
2225 tlp->tl_quote_rndtrip);
2226 memset(&vic, 0, sizeof vic);
2227 vic.vic_indat = shoup->s_dat;
2228 vic.vic_inlen = shoup->s_len;
2229 if(!n_visual_info(&vic,
2230 n_VISUAL_INFO_SKIP_ERRORS | n_VISUAL_INFO_WIDTH_QUERY))
2231 vic.vic_vi_width = shoup->s_len;
2233 /* Put on screen. Indent follow lines of same sort slot.
2234 * Leave enough room for filename tagging */
2235 if((c1 = (c1 != c2))){
2236 #ifdef HAVE_C90AMEND1
2237 c1 = (iswalnum(c2) != 0);
2238 #else
2239 c1 = (alnumchar(c2) != 0);
2240 #endif
2242 if(isfirst || c1 ||
2243 scrwid < lnlen || scrwid - lnlen <= vic.vic_vi_width + 2){
2244 putc('\n', fp);
2245 if(scrwid < lnlen)
2246 ++lncnt;
2247 ++lncnt, lnlen = 0;
2248 if(!isfirst && !c1)
2249 goto jsep;
2250 }else if(lnlen > 0){
2251 jsep:
2252 fputs(" ", fp);
2253 lnlen += 2;
2255 fputs(n_string_cp(shoup), fp);
2256 lnlen += vic.vic_vi_width;
2258 /* Support the known filename tagging
2259 * XXX *line-editor-completion-filetype* or so */
2260 if(!lstat(fullpath, &sb)){
2261 char c = '\0';
2263 if(S_ISDIR(sb.st_mode))
2264 c = '/';
2265 else if(S_ISLNK(sb.st_mode))
2266 c = '@';
2267 # ifdef S_ISFIFO
2268 else if(S_ISFIFO(sb.st_mode))
2269 c = '|';
2270 # endif
2271 # ifdef S_ISSOCK
2272 else if(S_ISSOCK(sb.st_mode))
2273 c = '=';
2274 # endif
2275 # ifdef S_ISCHR
2276 else if(S_ISCHR(sb.st_mode))
2277 c = '%';
2278 # endif
2279 # ifdef S_ISBLK
2280 else if(S_ISBLK(sb.st_mode))
2281 c = '#';
2282 # endif
2284 if(c != '\0'){
2285 putc(c, fp);
2286 ++lnlen;
2290 putc('\n', fp);
2291 ++lncnt;
2293 page_or_print(fp, lncnt);
2294 if(fp != n_tty_fp)
2295 Fclose(fp);
2297 n_string_gut(shoup);
2299 /* A common prefix of 0 means we cannot provide the user any auto
2300 * completed characters */
2301 if(locolen == 0)
2302 goto jnope;
2304 /* Otherwise we can, so extend the visual line content by the common
2305 * prefix (in a reversible way) */
2306 (exp.s = n_UNCONST(lococp))[locolen] = '\0';
2307 exp.s -= prefixlen;
2308 exp.l = (locolen += prefixlen);
2310 /* XXX Indicate that there is multiple choice */
2311 /* XXX f |= a_TTY_VF_BELL; -> *line-editor-completion-bell*? or so */
2312 wedid = FAL0;
2313 goto jset;
2316 jnope:
2317 /* If we've provided a default content, but failed to expand, there is
2318 * nothing we can "revert to": drop that default again */
2319 if(set_savec){
2320 tlp->tl_savec.s = NULL;
2321 tlp->tl_savec.l = 0;
2323 f = a_TTY_VF_NONE;
2324 rv = 0;
2325 goto jleave;
2328 # ifdef HAVE_HISTORY
2329 static ui32_t
2330 a_tty__khist_shared(struct a_tty_line *tlp, struct a_tty_hist *thp){
2331 ui32_t f, rv;
2332 NYD2_ENTER;
2334 if(n_LIKELY((tlp->tl_hist = thp) != NULL)){
2335 tlp->tl_defc.s = savestrbuf(thp->th_dat, thp->th_len);
2336 rv = tlp->tl_defc.l = thp->th_len;
2337 f = (tlp->tl_count > 0) ? a_TTY_VF_MOD_DIRTY : a_TTY_VF_NONE;
2338 tlp->tl_count = tlp->tl_cursor = 0;
2339 }else{
2340 f = a_TTY_VF_BELL;
2341 rv = UI32_MAX;
2344 tlp->tl_vi_flags |= f;
2345 NYD2_LEAVE;
2346 return rv;
2349 static ui32_t
2350 a_tty_khist(struct a_tty_line *tlp, bool_t fwd){
2351 struct a_tty_hist *thp;
2352 ui32_t rv;
2353 NYD2_ENTER;
2355 /* If we're not in history mode yet, save line content;
2356 * also, disallow forward search, then, and, of course, bail unless we
2357 * do have any history at all */
2358 if((thp = tlp->tl_hist) == NULL){
2359 if(fwd)
2360 goto jleave;
2361 if((thp = a_tty.tg_hist) == NULL)
2362 goto jleave;
2363 a_tty_cell2save(tlp);
2364 goto jleave;
2367 thp = fwd ? thp->th_younger : thp->th_older;
2368 jleave:
2369 rv = a_tty__khist_shared(tlp, thp);
2370 NYD2_LEAVE;
2371 return rv;
2374 static ui32_t
2375 a_tty_khist_search(struct a_tty_line *tlp, bool_t fwd){
2376 struct str orig_savec;
2377 struct a_tty_hist *thp;
2378 ui32_t rv;
2379 NYD2_ENTER;
2381 thp = NULL;
2383 /* We cannot complete an empty line */
2384 if(n_UNLIKELY(tlp->tl_count == 0)){
2385 /* XXX The upcoming hard reset would restore a set savec buffer,
2386 * XXX so forcefully reset that. A cleaner solution would be to
2387 * XXX reset it whenever a restore is no longer desired */
2388 tlp->tl_savec.s = NULL;
2389 tlp->tl_savec.l = 0;
2390 goto jleave;
2393 if((thp = tlp->tl_hist) == NULL){
2394 if((thp = a_tty.tg_hist) == NULL)
2395 goto jleave;
2396 /* We don't support wraparound, searching forward must always step */
2397 if(fwd)
2398 thp = thp->th_younger;
2399 orig_savec.s = NULL;
2400 orig_savec.l = 0; /* silence CC */
2401 }else if((thp = (fwd ? thp->th_younger : thp->th_older)) == NULL)
2402 goto jleave;
2403 else
2404 orig_savec = tlp->tl_savec;
2406 if(orig_savec.s == NULL)
2407 a_tty_cell2save(tlp);
2409 for(; thp != NULL; thp = (fwd ? thp->th_younger : thp->th_older))
2410 if(is_prefix(tlp->tl_savec.s, thp->th_dat))
2411 break;
2413 if(orig_savec.s != NULL)
2414 tlp->tl_savec = orig_savec;
2415 jleave:
2416 rv = a_tty__khist_shared(tlp, thp);
2417 NYD2_LEAVE;
2418 return rv;
2420 # endif /* HAVE_HISTORY */
2422 static enum a_tty_fun_status
2423 a_tty_fun(struct a_tty_line *tlp, enum a_tty_bind_flags tbf, size_t *len){
2424 enum a_tty_fun_status rv;
2425 NYD2_ENTER;
2427 rv = a_TTY_FUN_STATUS_OK;
2428 # undef a_X
2429 # define a_X(N) a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## N)
2430 switch(a_TTY_BIND_FUN_REDUCE(tbf)){
2431 case a_X(BELL):
2432 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2433 break;
2434 case a_X(GO_BWD):
2435 a_tty_kleft(tlp);
2436 break;
2437 case a_X(GO_FWD):
2438 a_tty_kright(tlp);
2439 break;
2440 case a_X(GO_WORD_BWD):
2441 a_tty_kgow(tlp, -1);
2442 break;
2443 case a_X(GO_WORD_FWD):
2444 a_tty_kgow(tlp, +1);
2445 break;
2446 case a_X(GO_HOME):
2447 a_tty_khome(tlp, TRU1);
2448 break;
2449 case a_X(GO_END):
2450 a_tty_kend(tlp);
2451 break;
2452 case a_X(DEL_BWD):
2453 a_tty_kbs(tlp);
2454 break;
2455 case a_X(DEL_FWD):
2456 if(a_tty_kdel(tlp) < 0)
2457 rv = a_TTY_FUN_STATUS_END;
2458 break;
2459 case a_X(SNARF_WORD_BWD):
2460 a_tty_ksnarfw(tlp, FAL0);
2461 break;
2462 case a_X(SNARF_WORD_FWD):
2463 a_tty_ksnarfw(tlp, TRU1);
2464 break;
2465 case a_X(SNARF_END):
2466 a_tty_ksnarf(tlp, FAL0, TRU1);
2467 break;
2468 case a_X(SNARF_LINE):
2469 a_tty_ksnarf(tlp, TRU1, (tlp->tl_count == 0));
2470 break;
2472 case a_X(HIST_FWD):
2473 # ifdef HAVE_HISTORY
2474 if(tlp->tl_hist != NULL){
2475 bool_t isfwd = TRU1;
2477 if(0){
2478 # endif
2479 /* FALLTHRU */
2480 case a_X(HIST_BWD):
2481 # ifdef HAVE_HISTORY
2482 isfwd = FAL0;
2484 if((*len = a_tty_khist(tlp, isfwd)) != UI32_MAX){
2485 rv = a_TTY_FUN_STATUS_RESTART;
2486 break;
2488 goto jreset;
2489 # endif
2491 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2492 break;
2494 case a_X(HIST_SRCH_FWD):{
2495 # ifdef HAVE_HISTORY
2496 bool_t isfwd = TRU1;
2498 if(0){
2499 # endif
2500 /* FALLTHRU */
2501 case a_X(HIST_SRCH_BWD):
2502 # ifdef HAVE_HISTORY
2503 isfwd = FAL0;
2505 if((*len = a_tty_khist_search(tlp, isfwd)) != UI32_MAX){
2506 rv = a_TTY_FUN_STATUS_RESTART;
2507 break;
2509 goto jreset;
2510 # else
2511 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2512 # endif
2513 } break;
2515 case a_X(REPAINT):
2516 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2517 break;
2518 case a_X(QUOTE_RNDTRIP):
2519 tlp->tl_quote_rndtrip = !tlp->tl_quote_rndtrip;
2520 break;
2521 case a_X(PROMPT_CHAR):{
2522 wchar_t wc;
2524 if((wc = a_tty_vinuni(tlp)) > 0)
2525 a_tty_kother(tlp, wc);
2526 } break;
2527 case a_X(COMPLETE):
2528 if((*len = a_tty_kht(tlp)) > 0)
2529 rv = a_TTY_FUN_STATUS_RESTART;
2530 break;
2532 case a_X(PASTE):
2533 if(tlp->tl_pastebuf.l > 0)
2534 *len = (tlp->tl_defc = tlp->tl_pastebuf).l;
2535 else
2536 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2537 break;
2540 case a_X(CANCEL):
2541 /* Normally this just causes a restart and thus resets the state
2542 * machine */
2543 if(tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2545 # ifdef HAVE_KEY_BINDINGS
2546 tlp->tl_bind_takeover = '\0';
2547 # endif
2548 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2549 rv = a_TTY_FUN_STATUS_RESTART;
2550 break;
2552 case a_X(RESET):
2553 if(tlp->tl_count == 0 && tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2554 # ifdef HAVE_KEY_BINDINGS
2555 tlp->tl_bind_takeover = '\0';
2556 # endif
2557 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY | a_TTY_VF_BELL;
2558 break;
2559 }else if(0){
2560 case a_X(FULLRESET):
2561 tlp->tl_savec.s = tlp->tl_defc.s = NULL;
2562 tlp->tl_savec.l = tlp->tl_defc.l = 0;
2563 tlp->tl_defc_cursor_byte = 0;
2564 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2566 jreset:
2567 # ifdef HAVE_KEY_BINDINGS
2568 tlp->tl_bind_takeover = '\0';
2569 # endif
2570 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2571 tlp->tl_cursor = tlp->tl_count = 0;
2572 # ifdef HAVE_HISTORY
2573 tlp->tl_hist = NULL;
2574 # endif
2575 if((*len = tlp->tl_savec.l) != 0){
2576 tlp->tl_defc = tlp->tl_savec;
2577 tlp->tl_savec.s = NULL;
2578 tlp->tl_savec.l = 0;
2579 }else
2580 *len = tlp->tl_defc.l;
2581 rv = a_TTY_FUN_STATUS_RESTART;
2582 break;
2584 default:
2585 case a_X(COMMIT):
2586 rv = a_TTY_FUN_STATUS_COMMIT;
2587 break;
2589 # undef a_X
2591 NYD2_LEAVE;
2592 return rv;
2595 static ssize_t
2596 a_tty_readline(struct a_tty_line *tlp, size_t len n_MEMORY_DEBUG_ARGS){
2597 /* We want to save code, yet we may have to incorporate a lines'
2598 * default content and / or default input to switch back to after some
2599 * history movement; let "len > 0" mean "have to display some data
2600 * buffer" -> a_BUFMODE, and only otherwise read(2) it */
2601 mbstate_t ps[2];
2602 char cbuf_base[MB_LEN_MAX * 2], *cbuf, *cbufp;
2603 ssize_t rv;
2604 struct a_tty_bind_tree *tbtp;
2605 wchar_t wc;
2606 enum a_tty_bind_flags tbf;
2607 enum {a_NONE, a_WAS_HERE = 1<<0, a_BUFMODE = 1<<1, a_MAYBEFUN = 1<<2,
2608 a_TIMEOUT = 1<<3, a_TIMEOUT_EXPIRED = 1<<4,
2609 a_TIMEOUT_MASK = a_TIMEOUT | a_TIMEOUT_EXPIRED,
2610 a_READ_LOOP_MASK = ~(a_WAS_HERE | a_MAYBEFUN | a_TIMEOUT_MASK)
2611 } flags;
2612 NYD_ENTER;
2614 n_UNINIT(rv, 0);
2615 # ifdef HAVE_KEY_BINDINGS
2616 assert(tlp->tl_bind_takeover == '\0');
2617 # endif
2618 jrestart:
2619 memset(ps, 0, sizeof ps);
2620 flags = a_NONE;
2621 tbf = 0;
2622 tlp->tl_vi_flags |= a_TTY_VF_REFRESH | a_TTY_VF_SYNC;
2624 jinput_loop:
2625 for(;;){
2626 if(len != 0)
2627 flags |= a_BUFMODE;
2629 /* Ensure we have valid pointers, and room for grow */
2630 a_tty_check_grow(tlp, ((flags & a_BUFMODE) ? (ui32_t)len : 1)
2631 n_MEMORY_DEBUG_ARGSCALL);
2633 /* Handle visual state flags, except in buffer mode */
2634 if(!(flags & a_BUFMODE) && (tlp->tl_vi_flags & a_TTY_VF_ALL_MASK))
2635 if(!a_tty_vi_refresh(tlp)){
2636 rv = -1;
2637 goto jleave;
2640 /* Ready for messing around.
2641 * Normal read(2)? Else buffer mode: speed this one up */
2642 if(!(flags & a_BUFMODE)){
2643 cbufp =
2644 cbuf = cbuf_base;
2645 }else{
2646 assert(tlp->tl_defc.l > 0 && tlp->tl_defc.s != NULL);
2647 assert(tlp->tl_defc.l >= len);
2648 cbufp =
2649 cbuf = tlp->tl_defc.s + (tlp->tl_defc.l - len);
2650 cbufp += len;
2653 /* Read in the next complete multibyte character */
2654 /* C99 */{
2655 # ifdef HAVE_KEY_BINDINGS
2656 struct a_tty_bind_tree *xtbtp;
2657 struct inseq{
2658 struct inseq *last;
2659 struct inseq *next;
2660 struct a_tty_bind_tree *tbtp;
2661 } *isp_head, *isp;
2663 isp_head = isp = NULL;
2664 # endif
2666 for(flags &= a_READ_LOOP_MASK;;){
2667 # ifdef HAVE_KEY_BINDINGS
2668 if(!(flags & a_BUFMODE) && tlp->tl_bind_takeover != '\0'){
2669 wc = tlp->tl_bind_takeover;
2670 tlp->tl_bind_takeover = '\0';
2671 }else
2672 # endif
2674 if(!(flags & a_BUFMODE)){
2675 /* Let me at least once dream of iomon(itor), timer with
2676 * one-shot, enwrapped with key_event and key_sequence_event,
2677 * all driven by an event_loop */
2678 /* TODO v15 Until we have SysV signal handling all through we
2679 * TODO need to temporarily adjust our BSD signal handler with
2680 * TODO a SysV one, here */
2681 n_sighdl_t otstp, ottin, ottou;
2683 otstp = n_signal(SIGTSTP, &n_tty_signal);
2684 ottin = n_signal(SIGTTIN, &n_tty_signal);
2685 ottou = n_signal(SIGTTOU, &n_tty_signal);
2686 # ifdef HAVE_KEY_BINDINGS
2687 flags &= ~a_TIMEOUT_MASK;
2688 if(isp != NULL && (tbtp = isp->tbtp)->tbt_isseq &&
2689 !tbtp->tbt_isseq_trail){
2690 a_tty_term_rawmode_timeout(tlp, TRU1);
2691 flags |= a_TIMEOUT;
2693 # endif
2695 while((rv = read(STDIN_FILENO, cbufp, 1)) < 1){
2696 if(rv == -1){
2697 if(errno == EINTR){
2698 if((tlp->tl_vi_flags & a_TTY_VF_MOD_DIRTY) &&
2699 !a_tty_vi_refresh(tlp))
2700 break;
2701 continue;
2703 break;
2706 # ifdef HAVE_KEY_BINDINGS
2707 /* Timeout expiration */
2708 if(rv == 0){
2709 assert(flags & a_TIMEOUT);
2710 assert(isp != NULL);
2711 a_tty_term_rawmode_timeout(tlp, FAL0);
2713 /* Something "atomic" broke. Maybe the current one can
2714 * also be terminated already, by itself? xxx really? */
2715 if((tbtp = isp->tbtp)->tbt_bind != NULL){
2716 tlp->tl_bind_takeover = wc;
2717 goto jhave_bind;
2720 /* Or, maybe there is a second path without a timeout;
2721 * this should be covered by .tbt_isseq_trail, but then
2722 * again a single-layer implementation cannot "know" */
2723 for(xtbtp = tbtp; (xtbtp = xtbtp->tbt_sibling) != NULL;)
2724 if(xtbtp->tbt_char == tbtp->tbt_char){
2725 assert(!xtbtp->tbt_isseq);
2726 break;
2728 /* Lay down on read(2)? */
2729 if(xtbtp != NULL)
2730 continue;
2731 goto jtake_over;
2733 # endif /* HAVE_KEY_BINDINGS */
2736 # ifdef HAVE_KEY_BINDINGS
2737 if(flags & a_TIMEOUT)
2738 a_tty_term_rawmode_timeout(tlp, FAL0);
2739 # endif
2740 safe_signal(SIGTSTP, otstp);
2741 safe_signal(SIGTTIN, ottin);
2742 safe_signal(SIGTTOU, ottou);
2743 if(rv < 0)
2744 goto jleave;
2746 ++cbufp;
2749 rv = (ssize_t)mbrtowc(&wc, cbuf, PTR2SIZE(cbufp - cbuf), &ps[0]);
2750 if(rv <= 0){
2751 /* Any error during buffer mode can only result in a hard
2752 * reset; Otherwise, if it's a hard error, or if too many
2753 * redundant shift sequences overflow our buffer: perform
2754 * hard reset */
2755 if((flags & a_BUFMODE) || rv == -1 ||
2756 sizeof cbuf_base == PTR2SIZE(cbufp - cbuf)){
2757 a_tty_fun(tlp, a_TTY_BIND_FUN_FULLRESET, &len);
2758 goto jrestart;
2760 /* Otherwise, due to the way we deal with the buffer, we need
2761 * to restore the mbstate_t from before this conversion */
2762 ps[0] = ps[1];
2763 continue;
2765 cbufp = cbuf;
2766 ps[1] = ps[0];
2769 /* Normal read(2)ing is subject to detection of key-bindings */
2770 # ifdef HAVE_KEY_BINDINGS
2771 if(!(flags & a_BUFMODE)){
2772 /* Check for special bypass functions before we try to embed
2773 * this character into the tree */
2774 if(n_uasciichar(wc)){
2775 char c;
2776 char const *cp;
2778 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_prompt_char)[0];
2779 *cp != '\0'; ++cp){
2780 if(c == *cp){
2781 wc = a_tty_vinuni(tlp);
2782 break;
2785 if(wc == '\0'){
2786 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2787 goto jinput_loop;
2790 if(n_uasciichar(wc))
2791 flags |= a_MAYBEFUN;
2792 else
2793 flags &= ~a_MAYBEFUN;
2795 /* Search for this character in the bind tree */
2796 tbtp = (isp != NULL) ? isp->tbtp->tbt_childs
2797 : (*tlp->tl_bind_tree_hmap)[wc % HSHSIZE];
2798 for(; tbtp != NULL; tbtp = tbtp->tbt_sibling){
2799 if(tbtp->tbt_char == wc){
2800 struct inseq *nisp;
2802 /* If this one cannot continue we're likely finished! */
2803 if(tbtp->tbt_childs == NULL){
2804 assert(tbtp->tbt_bind != NULL);
2805 tbf = tbtp->tbt_bind->tbc_flags;
2806 goto jmle_fun;
2809 /* This needs to read more characters */
2810 nisp = salloc(sizeof *nisp);
2811 if((nisp->last = isp) == NULL)
2812 isp_head = nisp;
2813 else
2814 isp->next = nisp;
2815 nisp->next = NULL;
2816 nisp->tbtp = tbtp;
2817 isp = nisp;
2818 flags &= ~a_WAS_HERE;
2819 break;
2822 if(tbtp != NULL)
2823 continue;
2825 /* Was there a binding active, but couldn't be continued? */
2826 if(isp != NULL){
2827 /* A binding had a timeout, it didn't expire, but we saw
2828 * something non-expected. Something "atomic" broke.
2829 * Maybe there is a second path without a timeout, that
2830 * continues like we've seen it. I.e., it may just have been
2831 * the user, typing too fast. We definitely want to allow
2832 * bindings like \e,d etc. to succeed: users are so used to
2833 * them that a timeout cannot be the mechanism to catch up!
2834 * A single-layer implementation cannot "know" */
2835 if((tbtp = isp->tbtp)->tbt_isseq && (isp->last == NULL ||
2836 !(xtbtp = isp->last->tbtp)->tbt_isseq ||
2837 xtbtp->tbt_isseq_trail)){
2838 for(xtbtp = (tbtp = isp->tbtp);
2839 (xtbtp = xtbtp->tbt_sibling) != NULL;)
2840 if(xtbtp->tbt_char == tbtp->tbt_char){
2841 assert(!xtbtp->tbt_isseq);
2842 break;
2844 if(xtbtp != NULL){
2845 isp->tbtp = xtbtp;
2846 tlp->tl_bind_takeover = wc;
2847 continue;
2851 /* Check for CANCEL shortcut now */
2852 if(flags & a_MAYBEFUN){
2853 char c;
2854 char const *cp;
2856 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_cancel)[0];
2857 *cp != '\0'; ++cp)
2858 if(c == *cp){
2859 tbf = a_TTY_BIND_FUN_INTERNAL |a_TTY_BIND_FUN_CANCEL;
2860 goto jmle_fun;
2864 /* So: maybe the current sequence can be terminated here? */
2865 if((tbtp = isp->tbtp)->tbt_bind != NULL){
2866 jhave_bind:
2867 tbf = tbtp->tbt_bind->tbc_flags;
2868 jmle_fun:
2869 if(tbf & a_TTY_BIND_FUN_INTERNAL){
2870 switch(a_tty_fun(tlp, tbf, &len)){
2871 case a_TTY_FUN_STATUS_OK:
2872 goto jinput_loop;
2873 case a_TTY_FUN_STATUS_COMMIT:
2874 goto jdone;
2875 case a_TTY_FUN_STATUS_RESTART:
2876 goto jrestart;
2877 case a_TTY_FUN_STATUS_END:
2878 goto jleave;
2880 assert(0);
2881 }else if(tbtp->tbt_bind->tbc_flags & a_TTY_BIND_NOCOMMIT){
2882 struct a_tty_bind_ctx *tbcp;
2884 tbcp = tbtp->tbt_bind;
2885 memcpy(tlp->tl_defc.s = salloc(
2886 (tlp->tl_defc.l = len = tbcp->tbc_exp_len) +1),
2887 tbcp->tbc_exp, tbcp->tbc_exp_len +1);
2888 goto jrestart;
2889 }else{
2890 cbufp = tbtp->tbt_bind->tbc_exp;
2891 goto jinject_input;
2896 /* Otherwise take over all chars "as is" */
2897 jtake_over:
2898 for(; isp_head != NULL; isp_head = isp_head->next)
2899 if(a_tty_kother(tlp, isp_head->tbtp->tbt_char)){
2900 /* FIXME */
2902 /* And the current one too */
2903 goto jkother;
2905 # endif /* HAVE_KEY_BINDINGS */
2907 if((flags & a_BUFMODE) && (len -= (size_t)rv) == 0){
2908 /* Buffer mode completed */
2909 tlp->tl_defc.s = NULL;
2910 tlp->tl_defc.l = 0;
2911 flags &= ~a_BUFMODE;
2913 break;
2916 # ifndef HAVE_KEY_BINDINGS
2917 /* Don't interpret control bytes during buffer mode.
2918 * Otherwise, if it's a control byte check whether it is a MLE
2919 * function. Remarks: initially a complete duplicate to be able to
2920 * switch(), later converted to simply iterate over (an #ifdef'd
2921 * subset of) the MLE base_tuple table in order to have "a SPOF" */
2922 if(cbuf == cbuf_base && n_uasciichar(wc) && cntrlchar((char)wc)){
2923 struct a_tty_bind_builtin_tuple const *tbbtp, *tbbtp_max;
2924 char c;
2926 c = (char)wc ^ 0x40;
2927 tbbtp = a_tty_bind_base_tuples;
2928 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_base_tuples)];
2929 jbuiltin_redo:
2930 for(; tbbtp < tbbtp_max; ++tbbtp){
2931 /* Assert default_tuple table is properly subset'ed */
2932 assert(tbbtp->tbdt_iskey);
2933 if(tbbtp->tbbt_ckey == c){
2934 if(tbbtp->tbbt_exp[0] == '\0'){
2935 enum a_tty_bind_flags tbf;
2937 tbf = a_TTY_BIND_FUN_EXPAND((ui8_t)tbbtp->tbbt_exp[1]);
2938 switch(a_tty_fun(tlp, tbf, &len)){
2939 case a_TTY_FUN_STATUS_OK:
2940 goto jinput_loop;
2941 case a_TTY_FUN_STATUS_COMMIT:
2942 goto jdone;
2943 case a_TTY_FUN_STATUS_RESTART:
2944 goto jrestart;
2945 case a_TTY_FUN_STATUS_END:
2946 goto jleave;
2948 assert(0);
2949 }else{
2950 cbufp = tbbtp->tbbt_exp;
2951 goto jinject_input;
2955 if(tbbtp ==
2956 &a_tty_bind_base_tuples[n_NELEM(a_tty_bind_base_tuples)]){
2957 tbbtp = a_tty_bind_default_tuples;
2958 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_default_tuples)];
2959 goto jbuiltin_redo;
2962 # endif /* !HAVE_KEY_BINDINGS */
2964 # ifdef HAVE_KEY_BINDINGS
2965 jkother:
2966 # endif
2967 if(a_tty_kother(tlp, wc)){
2968 /* Don't clear the history during buffer mode.. */
2969 # ifdef HAVE_HISTORY
2970 if(!(flags & a_BUFMODE) && cbuf == cbuf_base)
2971 tlp->tl_hist = NULL;
2972 # endif
2977 /* We have a completed input line, convert the struct cell data to its
2978 * plain character equivalent */
2979 jdone:
2980 rv = a_tty_cell2dat(tlp);
2981 jleave:
2982 putc('\n', n_tty_fp);
2983 fflush(n_tty_fp);
2984 NYD_LEAVE;
2985 return rv;
2987 jinject_input:{
2988 size_t i;
2990 hold_all_sigs(); /* XXX v15 drop */
2991 i = a_tty_cell2dat(tlp);
2992 n_source_inject_input(n_INPUT_INJECT_NONE, tlp->tl_line.cbuf, i);
2993 i = strlen(cbufp) +1;
2994 if(i >= *tlp->tl_x_bufsize){
2995 *tlp->tl_x_buf = (n_realloc)(*tlp->tl_x_buf, i n_MEMORY_DEBUG_ARGSCALL);
2996 *tlp->tl_x_bufsize = i;
2998 memcpy(*tlp->tl_x_buf, cbufp, i);
2999 rele_all_sigs(); /* XXX v15 drop */
3000 rv = (ssize_t)i -1;
3002 goto jleave;
3005 # ifdef HAVE_KEY_BINDINGS
3006 static enum n_lexinput_flags
3007 a_tty_bind_ctx_find(char const *name){
3008 enum n_lexinput_flags rv;
3009 struct a_tty_bind_ctx_map const *tbcmp;
3010 NYD2_ENTER;
3012 tbcmp = a_tty_bind_ctx_maps;
3013 do if(!asccasecmp(tbcmp->tbcm_name, name)){
3014 rv = tbcmp->tbcm_ctx;
3015 goto jleave;
3016 }while(PTRCMP(++tbcmp, <,
3017 &a_tty_bind_ctx_maps[n_NELEM(a_tty_bind_ctx_maps)]));
3019 rv = (enum n_lexinput_flags)-1;
3020 jleave:
3021 NYD2_LEAVE;
3022 return rv;
3025 static bool_t
3026 a_tty_bind_create(struct a_tty_bind_parse_ctx *tbpcp, bool_t replace){
3027 struct a_tty_bind_ctx *tbcp;
3028 bool_t rv;
3029 NYD2_ENTER;
3031 rv = FAL0;
3033 if(!a_tty_bind_parse(TRU1, tbpcp))
3034 goto jleave;
3036 /* Since we use a single buffer for it all, need to replace as such */
3037 if(tbpcp->tbpc_tbcp != NULL){
3038 if(!replace)
3039 goto jleave;
3040 a_tty_bind_del(tbpcp);
3041 }else if(a_tty.tg_bind_cnt == UI32_MAX){
3042 n_err(_("`bind': maximum number of bindings already established\n"));
3043 goto jleave;
3046 /* C99 */{
3047 size_t i, j;
3049 tbcp = smalloc(n_VSTRUCT_SIZEOF(struct a_tty_bind_ctx, tbc__buf) +
3050 tbpcp->tbpc_seq_len + tbpcp->tbpc_exp.l +
3051 n_MAX(sizeof(si32_t), sizeof(wc_t)) + tbpcp->tbpc_cnv_len +3);
3052 if(tbpcp->tbpc_ltbcp != NULL){
3053 tbcp->tbc_next = tbpcp->tbpc_ltbcp->tbc_next;
3054 tbpcp->tbpc_ltbcp->tbc_next = tbcp;
3055 }else{
3056 enum n_lexinput_flags lif = tbpcp->tbpc_flags & n__LEXINPUT_CTX_MASK;
3058 tbcp->tbc_next = a_tty.tg_bind[lif];
3059 a_tty.tg_bind[lif] = tbcp;
3061 memcpy(tbcp->tbc_seq = &tbcp->tbc__buf[0],
3062 tbpcp->tbpc_seq, i = (tbcp->tbc_seq_len = tbpcp->tbpc_seq_len) +1);
3063 memcpy(tbcp->tbc_exp = &tbcp->tbc__buf[i],
3064 tbpcp->tbpc_exp.s, j = (tbcp->tbc_exp_len = tbpcp->tbpc_exp.l) +1);
3065 i += j;
3066 i = (i + tbpcp->tbpc_cnv_align_mask) & ~tbpcp->tbpc_cnv_align_mask;
3067 memcpy(tbcp->tbc_cnv = &tbcp->tbc__buf[i],
3068 tbpcp->tbpc_cnv, (tbcp->tbc_cnv_len = tbpcp->tbpc_cnv_len) +1);
3069 tbcp->tbc_flags = tbpcp->tbpc_flags;
3072 /* Directly resolve any termcap(5) symbol if we are already setup */
3073 if((n_psonce & n_PSO_STARTED) &&
3074 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
3075 a_TTY_BIND_RESOLVE)
3076 a_tty_bind_resolve(tbcp);
3078 ++a_tty.tg_bind_cnt;
3079 /* If this binding is usable invalidate the key input lookup trees */
3080 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3081 a_tty.tg_bind_isdirty = TRU1;
3082 rv = TRU1;
3083 jleave:
3084 NYD2_LEAVE;
3085 return rv;
3088 static bool_t
3089 a_tty_bind_parse(bool_t isbindcmd, struct a_tty_bind_parse_ctx *tbpcp){
3090 enum{a_TRUE_RV = a_TTY__BIND_LAST<<1};
3092 struct n_visual_info_ctx vic;
3093 struct str shin_save, shin;
3094 struct n_string shou, *shoup;
3095 size_t i;
3096 struct kse{
3097 struct kse *next;
3098 char *seq_dat;
3099 wc_t *cnv_dat;
3100 ui32_t seq_len;
3101 ui32_t cnv_len; /* High bit set if a termap to be resolved */
3102 ui32_t calc_cnv_len; /* Ditto, but aligned etc. */
3103 ui8_t kse__dummy[4];
3104 } *head, *tail;
3105 ui32_t f;
3106 NYD2_ENTER;
3107 n_LCTA(UICMP(64, a_TRUE_RV, <, UI32_MAX),
3108 "Flag bits excess storage datatype");
3110 f = n_LEXINPUT_NONE;
3111 shoup = n_string_creat_auto(&shou);
3112 head = tail = NULL;
3114 /* Parse the key-sequence */
3115 for(shin.s = n_UNCONST(tbpcp->tbpc_in_seq), shin.l = UIZ_MAX;;){
3116 struct kse *ep;
3117 enum n_shexp_state shs;
3119 shin_save = shin;
3120 shs = n_shexp_parse_token((n_SHEXP_PARSE_TRUNC | n_SHEXP_PARSE_TRIMSPACE |
3121 n_SHEXP_PARSE_IGNORE_EMPTY | n_SHEXP_PARSE_IFS_IS_COMMA),
3122 shoup, &shin, NULL);
3123 if(shs & n_SHEXP_STATE_ERR_UNICODE){
3124 f |= a_TTY_BIND_DEFUNCT;
3125 if(isbindcmd && (n_poption & n_PO_D_V))
3126 n_err(_("`%s': \\uNICODE not available in locale: %s\n"),
3127 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3129 if((shs & n_SHEXP_STATE_ERR_MASK) & ~n_SHEXP_STATE_ERR_UNICODE){
3130 n_err(_("`%s': failed to parse key-sequence: %s\n"),
3131 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3132 goto jleave;
3134 if((shs & (n_SHEXP_STATE_OUTPUT | n_SHEXP_STATE_STOP)) ==
3135 n_SHEXP_STATE_STOP)
3136 break;
3138 ep = salloc(sizeof *ep);
3139 if(head == NULL)
3140 head = ep;
3141 else
3142 tail->next = ep;
3143 tail = ep;
3144 ep->next = NULL;
3145 if(!(shs & n_SHEXP_STATE_ERR_UNICODE)){
3146 i = strlen(ep->seq_dat = n_shexp_quote_cp(n_string_cp(shoup), TRU1));
3147 if(i >= SI32_MAX - 1)
3148 goto jelen;
3149 ep->seq_len = (ui32_t)i;
3150 }else{
3151 /* Otherwise use the original buffer, _we_ can only quote it the wrong
3152 * way (e.g., an initial $'\u3a' becomes '\u3a'), _then_ */
3153 if((i = shin_save.l - shin.l) >= SI32_MAX - 1)
3154 goto jelen;
3155 ep->seq_len = (ui32_t)i;
3156 ep->seq_dat = savestrbuf(shin_save.s, i);
3159 memset(&vic, 0, sizeof vic);
3160 vic.vic_inlen = shoup->s_len;
3161 vic.vic_indat = shoup->s_dat;
3162 if(!n_visual_info(&vic,
3163 n_VISUAL_INFO_WOUT_CREATE | n_VISUAL_INFO_WOUT_SALLOC)){
3164 n_err(_("`%s': key-sequence seems to contain invalid "
3165 "characters: %s: %s\n"),
3166 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
3167 f |= a_TTY_BIND_DEFUNCT;
3168 goto jleave;
3169 }else if(vic.vic_woulen == 0 ||
3170 vic.vic_woulen >= (SI32_MAX - 2) / sizeof(wc_t)){
3171 jelen:
3172 n_err(_("`%s': length of key-sequence unsupported: %s: %s\n"),
3173 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
3174 f |= a_TTY_BIND_DEFUNCT;
3175 goto jleave;
3177 ep->cnv_dat = vic.vic_woudat;
3178 ep->cnv_len = (ui32_t)vic.vic_woulen;
3180 /* A termcap(5)/terminfo(5) identifier? */
3181 if(ep->cnv_len > 1 && ep->cnv_dat[0] == ':'){
3182 i = --ep->cnv_len, ++ep->cnv_dat;
3183 # ifndef HAVE_TERMCAP
3184 if(n_poption & n_PO_D_V)
3185 n_err(_("`%s': no termcap(5)/terminfo(5) support: %s: %s\n"),
3186 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3187 f |= a_TTY_BIND_DEFUNCT;
3188 # endif
3189 if(i > a_TTY_BIND_CAPNAME_MAX){
3190 n_err(_("`%s': termcap(5)/terminfo(5) name too long: %s: %s\n"),
3191 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3192 f |= a_TTY_BIND_DEFUNCT;
3194 while(i > 0)
3195 /* (We store it as char[]) */
3196 if((ui32_t)ep->cnv_dat[--i] & ~0x7Fu){
3197 n_err(_("`%s': invalid termcap(5)/terminfo(5) name content: "
3198 "%s: %s\n"),
3199 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3200 f |= a_TTY_BIND_DEFUNCT;
3201 break;
3203 ep->cnv_len |= SI32_MIN; /* Needs resolve */
3204 f |= a_TTY_BIND_RESOLVE;
3207 if(shs & n_SHEXP_STATE_STOP)
3208 break;
3211 if(head == NULL){
3212 jeempty:
3213 n_err(_("`%s': effectively empty key-sequence: %s\n"),
3214 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3215 goto jleave;
3218 if(isbindcmd) /* (Or always, just "1st time init") */
3219 tbpcp->tbpc_cnv_align_mask = n_MAX(sizeof(si32_t), sizeof(wc_t)) - 1;
3221 /* C99 */{
3222 struct a_tty_bind_ctx *ltbcp, *tbcp;
3223 char *cpbase, *cp, *cnv;
3224 size_t sl, cl;
3226 /* Unite the parsed sequence(s) into single string representations */
3227 for(sl = cl = 0, tail = head; tail != NULL; tail = tail->next){
3228 sl += tail->seq_len + 1;
3230 if(!isbindcmd)
3231 continue;
3233 /* Preserve room for terminal capabilities to be resolved.
3234 * Above we have ensured the buffer will fit in these calculations */
3235 if((i = tail->cnv_len) & SI32_MIN){
3236 /* For now
3237 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[]+NUL;}
3238 * later
3239 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3240 n_LCTAV(n_ISPOW2(a_TTY_BIND_CAPEXP_ROUNDUP));
3241 n_LCTA(a_TTY_BIND_CAPEXP_ROUNDUP >= sizeof(wc_t),
3242 "Aligning on this constant doesn't properly align wc_t");
3243 i &= SI32_MAX;
3244 i *= sizeof(wc_t);
3245 i += sizeof(si32_t);
3246 if(i < a_TTY_BIND_CAPEXP_ROUNDUP)
3247 i = (i + (a_TTY_BIND_CAPEXP_ROUNDUP - 1)) &
3248 ~(a_TTY_BIND_CAPEXP_ROUNDUP - 1);
3249 }else
3250 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3251 i *= sizeof(wc_t);
3252 i += sizeof(si32_t) + sizeof(wc_t); /* (buf_len_iscap, NUL) */
3253 cl += i;
3254 if(tail->cnv_len & SI32_MIN){
3255 tail->cnv_len &= SI32_MAX;
3256 i |= SI32_MIN;
3258 tail->calc_cnv_len = (ui32_t)i;
3260 --sl;
3262 tbpcp->tbpc_seq_len = sl;
3263 tbpcp->tbpc_cnv_len = cl;
3264 /* C99 */{
3265 size_t j;
3267 j = i = sl + 1; /* Room for comma separator */
3268 if(isbindcmd){
3269 i = (i + tbpcp->tbpc_cnv_align_mask) & ~tbpcp->tbpc_cnv_align_mask;
3270 j = i;
3271 i += cl;
3273 tbpcp->tbpc_seq = cp = cpbase = salloc(i);
3274 tbpcp->tbpc_cnv = cnv = &cpbase[j];
3277 for(tail = head; tail != NULL; tail = tail->next){
3278 memcpy(cp, tail->seq_dat, tail->seq_len);
3279 cp += tail->seq_len;
3280 *cp++ = ',';
3282 if(isbindcmd){
3283 char * const save_cnv = cnv;
3285 n_UNALIGN(si32_t*,cnv)[0] = (si32_t)(i = tail->calc_cnv_len);
3286 cnv += sizeof(si32_t);
3287 if(i & SI32_MIN){
3288 /* For now
3289 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];}
3290 * later
3291 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[];} */
3292 n_UNALIGN(si32_t*,cnv)[0] = tail->cnv_len;
3293 cnv += sizeof(si32_t);
3295 i = tail->cnv_len * sizeof(wc_t);
3296 memcpy(cnv, tail->cnv_dat, i);
3297 cnv += i;
3298 *n_UNALIGN(wc_t*,cnv) = '\0';
3300 cnv = save_cnv + (tail->calc_cnv_len & SI32_MAX);
3303 *--cp = '\0';
3305 /* Search for a yet existing identical mapping */
3306 for(ltbcp = NULL, tbcp = a_tty.tg_bind[tbpcp->tbpc_flags]; tbcp != NULL;
3307 ltbcp = tbcp, tbcp = tbcp->tbc_next)
3308 if(tbcp->tbc_seq_len == sl && !memcmp(tbcp->tbc_seq, cpbase, sl)){
3309 tbpcp->tbpc_tbcp = tbcp;
3310 break;
3312 tbpcp->tbpc_ltbcp = ltbcp;
3313 tbpcp->tbpc_flags |= (f & a_TTY__BIND_MASK);
3316 /* Create single string expansion if so desired */
3317 if(isbindcmd){
3318 char *exp;
3320 exp = tbpcp->tbpc_exp.s;
3322 i = tbpcp->tbpc_exp.l;
3323 if(i > 0 && exp[i - 1] == '@'){
3324 while(--i > 0){
3325 if(!blankspacechar(exp[i - 1]))
3326 break;
3328 if(i == 0)
3329 goto jeempty;
3331 exp[tbpcp->tbpc_exp.l = i] = '\0';
3332 tbpcp->tbpc_flags |= a_TTY_BIND_NOCOMMIT;
3335 /* Reverse solidus cannot be placed last in expansion to avoid (at the
3336 * time of this writing) possible problems with newline escaping.
3337 * Don't care about (un)even number thereof */
3338 if(i > 0 && exp[i - 1] == '\\'){
3339 n_err(_("`%s': reverse solidus cannot be last in expansion: %s\n"),
3340 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3341 goto jleave;
3344 /* It may map to an internal MLE command! */
3345 for(i = 0; i < n_NELEM(a_tty_bind_fun_names); ++i)
3346 if(!asccasecmp(exp, a_tty_bind_fun_names[i])){
3347 tbpcp->tbpc_flags |= a_TTY_BIND_FUN_EXPAND(i) |
3348 a_TTY_BIND_FUN_INTERNAL |
3349 (head->next == NULL ? a_TTY_BIND_MLE1CNTRL : 0);
3350 if((n_poption & n_PO_D_V) &&
3351 (tbpcp->tbpc_flags & a_TTY_BIND_NOCOMMIT))
3352 n_err(_("`%s': MLE commands can't be made editable via @: %s\n"),
3353 tbpcp->tbpc_cmd, exp);
3354 tbpcp->tbpc_flags &= ~a_TTY_BIND_NOCOMMIT;
3355 break;
3359 f |= a_TRUE_RV; /* TODO because we only now true and false; DEFUNCT.. */
3360 jleave:
3361 n_string_gut(shoup);
3362 NYD2_LEAVE;
3363 return (f & a_TRUE_RV) != 0;
3366 static void
3367 a_tty_bind_resolve(struct a_tty_bind_ctx *tbcp){
3368 char capname[a_TTY_BIND_CAPNAME_MAX +1];
3369 struct n_termcap_value tv;
3370 size_t len;
3371 bool_t isfirst; /* TODO For now: first char must be control! */
3372 char *cp, *next;
3373 NYD2_ENTER;
3375 n_UNINIT(next, NULL);
3376 for(cp = tbcp->tbc_cnv, isfirst = TRU1, len = tbcp->tbc_cnv_len;
3377 len > 0; isfirst = FAL0, cp = next){
3378 /* C99 */{
3379 si32_t i, j;
3381 i = n_UNALIGN(si32_t*,cp)[0];
3382 j = i & SI32_MAX;
3383 next = &cp[j];
3384 len -= j;
3385 if(i == j)
3386 continue;
3388 /* struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];} */
3389 cp += sizeof(si32_t);
3390 i = n_UNALIGN(si32_t*,cp)[0];
3391 cp += sizeof(si32_t);
3392 for(j = 0; j < i; ++j)
3393 capname[j] = n_UNALIGN(wc_t*,cp)[j];
3394 capname[j] = '\0';
3397 /* Use generic lookup mechanism if not a known query */
3398 /* C99 */{
3399 si32_t tq;
3401 tq = n_termcap_query_for_name(capname, n_TERMCAP_CAPTYPE_STRING);
3402 if(tq == -1){
3403 tv.tv_data.tvd_string = capname;
3404 tq = n__TERMCAP_QUERY_MAX1;
3407 if(tq < 0 || !n_termcap_query(tq, &tv)){
3408 if(n_poption & n_PO_D_V)
3409 n_err(_("`bind': unknown or unsupported capability: %s: %s\n"),
3410 capname, tbcp->tbc_seq);
3411 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3412 break;
3416 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3417 /* C99 */{
3418 size_t i;
3420 i = strlen(tv.tv_data.tvd_string);
3421 if(/*i > SI32_MAX ||*/ i >= PTR2SIZE(next - cp)){
3422 if(n_poption & n_PO_D_V)
3423 n_err(_("`bind': capability expansion too long: %s: %s\n"),
3424 capname, tbcp->tbc_seq);
3425 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3426 break;
3427 }else if(i == 0){
3428 if(n_poption & n_PO_D_V)
3429 n_err(_("`bind': empty capability expansion: %s: %s\n"),
3430 capname, tbcp->tbc_seq);
3431 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3432 break;
3433 }else if(isfirst && !cntrlchar(*tv.tv_data.tvd_string)){
3434 if(n_poption & n_PO_D_V)
3435 n_err(_("`bind': capability expansion doesn't start with "
3436 "control: %s: %s\n"), capname, tbcp->tbc_seq);
3437 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3438 break;
3440 n_UNALIGN(si32_t*,cp)[-1] = (si32_t)i;
3441 memcpy(cp, tv.tv_data.tvd_string, i);
3442 cp[i] = '\0';
3445 NYD2_LEAVE;
3448 static void
3449 a_tty_bind_del(struct a_tty_bind_parse_ctx *tbpcp){
3450 struct a_tty_bind_ctx *ltbcp, *tbcp;
3451 NYD2_ENTER;
3453 tbcp = tbpcp->tbpc_tbcp;
3455 if((ltbcp = tbpcp->tbpc_ltbcp) != NULL)
3456 ltbcp->tbc_next = tbcp->tbc_next;
3457 else
3458 a_tty.tg_bind[tbpcp->tbpc_flags] = tbcp->tbc_next;
3459 free(tbcp);
3461 --a_tty.tg_bind_cnt;
3462 a_tty.tg_bind_isdirty = TRU1;
3463 NYD2_LEAVE;
3466 static void
3467 a_tty_bind_tree_build(void){
3468 size_t i;
3469 NYD2_ENTER;
3471 for(i = 0; i < n__LEXINPUT_CTX_MAX1; ++i){
3472 struct a_tty_bind_ctx *tbcp;
3473 n_LCTAV(n_LEXINPUT_CTX_BASE == 0);
3475 /* Somewhat wasteful, but easier to handle: simply clone the entire
3476 * primary key onto the secondary one, then only modify it */
3477 for(tbcp = a_tty.tg_bind[n_LEXINPUT_CTX_BASE]; tbcp != NULL;
3478 tbcp = tbcp->tbc_next)
3479 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3480 a_tty__bind_tree_add(n_LEXINPUT_CTX_BASE, &a_tty.tg_bind_tree[i][0],
3481 tbcp);
3483 if(i != n_LEXINPUT_CTX_BASE)
3484 for(tbcp = a_tty.tg_bind[i]; tbcp != NULL; tbcp = tbcp->tbc_next)
3485 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3486 a_tty__bind_tree_add(i, &a_tty.tg_bind_tree[i][0], tbcp);
3489 a_tty.tg_bind_isbuild = TRU1;
3490 NYD2_LEAVE;
3493 static void
3494 a_tty_bind_tree_teardown(void){
3495 size_t i, j;
3496 NYD2_ENTER;
3498 memset(&a_tty.tg_bind_shcut_cancel[0], 0,
3499 sizeof(a_tty.tg_bind_shcut_cancel));
3500 memset(&a_tty.tg_bind_shcut_prompt_char[0], 0,
3501 sizeof(a_tty.tg_bind_shcut_prompt_char));
3503 for(i = 0; i < n__LEXINPUT_CTX_MAX1; ++i)
3504 for(j = 0; j < HSHSIZE; ++j)
3505 a_tty__bind_tree_free(a_tty.tg_bind_tree[i][j]);
3506 memset(&a_tty.tg_bind_tree[0], 0, sizeof(a_tty.tg_bind_tree));
3508 a_tty.tg_bind_isdirty = a_tty.tg_bind_isbuild = FAL0;
3509 NYD2_LEAVE;
3512 static void
3513 a_tty__bind_tree_add(ui32_t hmap_idx, struct a_tty_bind_tree *store[HSHSIZE],
3514 struct a_tty_bind_ctx *tbcp){
3515 ui32_t cnvlen;
3516 char const *cnvdat;
3517 struct a_tty_bind_tree *ntbtp;
3518 NYD2_ENTER;
3519 n_UNUSED(hmap_idx);
3521 ntbtp = NULL;
3523 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len; cnvlen > 0;){
3524 union {wchar_t const *wp; char const *cp;} u;
3525 si32_t entlen;
3527 /* {si32_t buf_len_iscap;} */
3528 entlen = *n_UNALIGN(si32_t const*,cnvdat);
3530 if(entlen & SI32_MIN){
3531 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;}
3532 * Note that empty capabilities result in DEFUNCT */
3533 for(u.cp = (char const*)&n_UNALIGN(si32_t const*,cnvdat)[2];
3534 *u.cp != '\0'; ++u.cp)
3535 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.cp, TRU1);
3536 assert(ntbtp != NULL);
3537 ntbtp->tbt_isseq_trail = TRU1;
3538 entlen &= SI32_MAX;
3539 }else{
3540 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3541 bool_t isseq;
3543 u.wp = (wchar_t const*)&n_UNALIGN(si32_t const*,cnvdat)[1];
3545 /* May be a special shortcut function? */
3546 if(ntbtp == NULL && (tbcp->tbc_flags & a_TTY_BIND_MLE1CNTRL)){
3547 char *cp;
3548 ui32_t ctx, fun;
3550 ctx = tbcp->tbc_flags & n__LEXINPUT_CTX_MASK;
3551 fun = tbcp->tbc_flags & a_TTY__BIND_FUN_MASK;
3553 if(fun == a_TTY_BIND_FUN_CANCEL){
3554 for(cp = &a_tty.tg_bind_shcut_cancel[ctx][0];
3555 PTRCMP(cp, <, &a_tty.tg_bind_shcut_cancel[ctx]
3556 [n_NELEM(a_tty.tg_bind_shcut_cancel[ctx]) - 1]); ++cp)
3557 if(*cp == '\0'){
3558 *cp = (char)*u.wp;
3559 break;
3561 }else if(fun == a_TTY_BIND_FUN_PROMPT_CHAR){
3562 for(cp = &a_tty.tg_bind_shcut_prompt_char[ctx][0];
3563 PTRCMP(cp, <, &a_tty.tg_bind_shcut_prompt_char[ctx]
3564 [n_NELEM(a_tty.tg_bind_shcut_prompt_char[ctx]) - 1]);
3565 ++cp)
3566 if(*cp == '\0'){
3567 *cp = (char)*u.wp;
3568 break;
3573 isseq = (u.wp[1] != '\0');
3574 for(; *u.wp != '\0'; ++u.wp)
3575 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.wp, isseq);
3576 if(isseq)
3577 ntbtp->tbt_isseq_trail = TRU1;
3580 cnvlen -= entlen;
3581 cnvdat += entlen;
3584 /* Should have been rendered defunctional at first instead */
3585 assert(ntbtp != NULL);
3586 ntbtp->tbt_bind = tbcp;
3587 NYD2_LEAVE;
3590 static struct a_tty_bind_tree *
3591 a_tty__bind_tree_add_wc(struct a_tty_bind_tree **treep,
3592 struct a_tty_bind_tree *parentp, wchar_t wc, bool_t isseq){
3593 struct a_tty_bind_tree *tbtp, *xtbtp;
3594 NYD2_ENTER;
3596 if(parentp == NULL){
3597 treep += wc % HSHSIZE;
3599 /* Having no parent also means that the tree slot is possibly empty */
3600 for(tbtp = *treep; tbtp != NULL;
3601 parentp = tbtp, tbtp = tbtp->tbt_sibling){
3602 if(tbtp->tbt_char != wc)
3603 continue;
3604 if(tbtp->tbt_isseq == isseq)
3605 goto jleave;
3606 /* isseq MUST be linked before !isseq, so record this "parent"
3607 * sibling, but continue searching for now */
3608 if(!isseq)
3609 parentp = tbtp;
3610 /* Otherwise it is impossible that we'll find what we look for */
3611 else{
3612 #ifdef HAVE_DEBUG
3613 while((tbtp = tbtp->tbt_sibling) != NULL)
3614 assert(tbtp->tbt_char != wc);
3615 #endif
3616 break;
3620 tbtp = smalloc(sizeof *tbtp);
3621 memset(tbtp, 0, sizeof *tbtp);
3622 tbtp->tbt_char = wc;
3623 tbtp->tbt_isseq = isseq;
3625 if(parentp == NULL){
3626 tbtp->tbt_sibling = *treep;
3627 *treep = tbtp;
3628 }else{
3629 tbtp->tbt_sibling = parentp->tbt_sibling;
3630 parentp->tbt_sibling = tbtp;
3632 }else{
3633 if((tbtp = *(treep = &parentp->tbt_childs)) != NULL){
3634 for(;; tbtp = xtbtp){
3635 if(tbtp->tbt_char == wc){
3636 if(tbtp->tbt_isseq == isseq)
3637 goto jleave;
3638 /* isseq MUST be linked before, so it is impossible that we'll
3639 * find what we look for */
3640 if(isseq){
3641 #ifdef HAVE_DEBUG
3642 while((tbtp = tbtp->tbt_sibling) != NULL)
3643 assert(tbtp->tbt_char != wc);
3644 #endif
3645 tbtp = NULL;
3646 break;
3650 if((xtbtp = tbtp->tbt_sibling) == NULL){
3651 treep = &tbtp->tbt_sibling;
3652 break;
3657 xtbtp = smalloc(sizeof *xtbtp);
3658 memset(xtbtp, 0, sizeof *xtbtp);
3659 xtbtp->tbt_parent = parentp;
3660 xtbtp->tbt_char = wc;
3661 xtbtp->tbt_isseq = isseq;
3662 tbtp = xtbtp;
3663 *treep = tbtp;
3665 jleave:
3666 NYD2_LEAVE;
3667 return tbtp;
3670 static void
3671 a_tty__bind_tree_free(struct a_tty_bind_tree *tbtp){
3672 NYD2_ENTER;
3673 while(tbtp != NULL){
3674 struct a_tty_bind_tree *tmp;
3676 if((tmp = tbtp->tbt_childs) != NULL)
3677 a_tty__bind_tree_free(tmp);
3679 tmp = tbtp->tbt_sibling;
3680 free(tbtp);
3681 tbtp = tmp;
3683 NYD2_LEAVE;
3685 # endif /* HAVE_KEY_BINDINGS */
3687 FL void
3688 n_tty_init(void){
3689 NYD_ENTER;
3691 if(ok_blook(line_editor_disable))
3692 goto jleave;
3694 /* Load the history file */
3695 # ifdef HAVE_HISTORY
3696 do/* for break */{
3697 char const *v;
3698 char *lbuf;
3699 FILE *f;
3700 size_t lsize, cnt, llen;
3702 if((v = a_tty_hist_query_config()) == NULL ||
3703 a_tty.tg_hist_size_max == 0)
3704 break;
3706 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
3707 f = fopen(v, "r"); /* TODO HISTFILE LOAD: use linebuf pool */
3708 if(f == NULL)
3709 goto jhist_done;
3710 (void)n_file_lock(fileno(f), FLT_READ, 0,0, UIZ_MAX);
3712 assert(!(n_pstate & n_PS_ROOT));
3713 n_pstate |= n_PS_ROOT; /* Allow calling addhist() */
3714 lbuf = NULL;
3715 lsize = 0;
3716 cnt = (size_t)fsize(f);
3717 while(fgetline(&lbuf, &lsize, &cnt, &llen, f, FAL0) != NULL){
3718 if(llen > 0 && lbuf[llen - 1] == '\n')
3719 lbuf[--llen] = '\0';
3720 if(llen == 0 || lbuf[0] == '#') /* xxx comments? noone! */
3721 continue;
3722 else{
3723 bool_t isgabby;
3725 isgabby = (lbuf[0] == '*');
3726 n_tty_addhist(lbuf + isgabby, isgabby);
3729 if(lbuf != NULL)
3730 free(lbuf);
3731 n_pstate &= ~n_PS_ROOT;
3733 fclose(f);
3734 jhist_done:
3735 rele_all_sigs(); /* XXX remove jumps */
3736 }while(0);
3737 # endif /* HAVE_HISTORY */
3739 /* Force immediate resolve for anything which follows */
3740 n_psonce |= n_PSO_LINE_EDITOR_INIT;
3742 # ifdef HAVE_KEY_BINDINGS
3743 /* `bind's (and `unbind's) done from within resource files couldn't be
3744 * performed for real since our termcap driver wasn't yet loaded, and we
3745 * can't perform automatic init since the user may have disallowed so */
3746 /* C99 */{
3747 struct a_tty_bind_ctx *tbcp;
3748 enum n_lexinput_flags lif;
3750 for(lif = 0; lif < n__LEXINPUT_CTX_MAX1; ++lif)
3751 for(tbcp = a_tty.tg_bind[lif]; tbcp != NULL; tbcp = tbcp->tbc_next)
3752 if((tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
3753 a_TTY_BIND_RESOLVE)
3754 a_tty_bind_resolve(tbcp);
3757 /* And we want to (try to) install some default key bindings */
3758 if(!ok_blook(line_editor_no_defaults)){
3759 char buf[8];
3760 struct a_tty_bind_parse_ctx tbpc;
3761 struct a_tty_bind_builtin_tuple const *tbbtp, *tbbtp_max;
3762 ui32_t flags;
3764 buf[0] = '$', buf[1] = '\'', buf[2] = '\\', buf[3] = 'c',
3765 buf[5] = '\'', buf[6] = '\0';
3767 tbbtp = a_tty_bind_base_tuples;
3768 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_base_tuples)];
3769 flags = n_LEXINPUT_CTX_BASE;
3770 jbuiltin_redo:
3771 for(; tbbtp < tbbtp_max; ++tbbtp){
3772 memset(&tbpc, 0, sizeof tbpc);
3773 tbpc.tbpc_cmd = "bind";
3774 if(tbbtp->tbbt_iskey){
3775 buf[4] = tbbtp->tbbt_ckey;
3776 tbpc.tbpc_in_seq = buf;
3777 }else
3778 tbpc.tbpc_in_seq = savecatsep(":", '\0',
3779 n_termcap_name_of_query(tbbtp->tbbt_query));
3780 tbpc.tbpc_exp.s = n_UNCONST(tbbtp->tbbt_exp[0] == '\0'
3781 ? a_tty_bind_fun_names[(ui8_t)tbbtp->tbbt_exp[1]]
3782 : tbbtp->tbbt_exp);
3783 tbpc.tbpc_exp.l = strlen(tbpc.tbpc_exp.s);
3784 tbpc.tbpc_flags = flags;
3785 /* ..but don't want to overwrite any user settings */
3786 a_tty_bind_create(&tbpc, FAL0);
3788 if(flags == n_LEXINPUT_CTX_BASE){
3789 tbbtp = a_tty_bind_default_tuples;
3790 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_default_tuples)];
3791 flags = n_LEXINPUT_CTX_DEFAULT;
3792 goto jbuiltin_redo;
3795 # endif /* HAVE_KEY_BINDINGS */
3797 jleave:
3798 NYD_LEAVE;
3801 FL void
3802 n_tty_destroy(void){
3803 NYD_ENTER;
3805 if(!(n_psonce & n_PSO_LINE_EDITOR_INIT))
3806 goto jleave;
3808 # ifdef HAVE_HISTORY
3809 do/* for break */{
3810 size_t i;
3811 char const *v;
3812 struct a_tty_hist *thp;
3813 bool_t dogabby;
3814 FILE *f;
3816 if((v = a_tty_hist_query_config()) == NULL ||
3817 a_tty.tg_hist_size_max == 0)
3818 break;
3820 dogabby = ok_blook(history_gabby_persist);
3822 if((thp = a_tty.tg_hist) != NULL)
3823 for(i = a_tty.tg_hist_size_max; thp->th_older != NULL;
3824 thp = thp->th_older)
3825 if((dogabby || !thp->th_isgabby) && --i == 0)
3826 break;
3828 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
3829 f = fopen(v, "w"); /* TODO temporary + rename?! */
3830 if(f == NULL)
3831 goto jhist_done;
3832 (void)n_file_lock(fileno(f), FLT_WRITE, 0,0, UIZ_MAX);
3834 for(; thp != NULL; thp = thp->th_younger){
3835 if(dogabby || !thp->th_isgabby){
3836 if(thp->th_isgabby)
3837 putc('*', f);
3838 fwrite(thp->th_dat, sizeof *thp->th_dat, thp->th_len, f);
3839 putc('\n', f);
3842 fclose(f);
3843 jhist_done:
3844 rele_all_sigs(); /* XXX remove jumps */
3845 }while(0);
3846 # endif /* HAVE_HISTORY */
3848 # if defined HAVE_KEY_BINDINGS && defined HAVE_DEBUG
3849 c_unbind(n_UNCONST("* *"));
3850 # endif
3852 # ifdef HAVE_DEBUG
3853 memset(&a_tty, 0, sizeof a_tty);
3854 # endif
3855 DBG( n_psonce &= ~n_PSO_LINE_EDITOR_INIT; )
3856 jleave:
3857 NYD_LEAVE;
3860 FL void
3861 n_tty_signal(int sig){
3862 sigset_t nset, oset;
3863 NYD_X; /* Signal handler */
3865 switch(sig){
3866 # ifdef SIGWINCH
3867 case SIGWINCH:
3868 /* We don't deal with SIGWINCH, yet get called from main.c.
3869 * Note this case might get called even if !n_PO_LINE_EDITOR_INIT */
3870 break;
3871 # endif
3872 default:
3873 a_tty_term_mode(FAL0);
3874 n_TERMCAP_SUSPEND(TRU1);
3875 a_tty_sigs_down();
3877 sigemptyset(&nset);
3878 sigaddset(&nset, sig);
3879 sigprocmask(SIG_UNBLOCK, &nset, &oset);
3880 n_raise(sig);
3881 /* When we come here we'll continue editing, so reestablish */
3882 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
3884 a_tty_sigs_up();
3885 n_TERMCAP_RESUME(TRU1);
3886 a_tty_term_mode(TRU1);
3887 a_tty.tg_line->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
3888 break;
3892 FL int
3893 (n_tty_readline)(enum n_lexinput_flags lif, char const *prompt,
3894 char **linebuf, size_t *linesize, size_t n n_MEMORY_DEBUG_ARGS){
3895 struct a_tty_line tl;
3896 struct n_string xprompt;
3897 # ifdef HAVE_COLOUR
3898 char *posbuf, *pos;
3899 # endif
3900 ssize_t nn;
3901 NYD_ENTER;
3902 n_UNUSED(lif);
3904 assert(!ok_blook(line_editor_disable));
3905 if(!(n_psonce & n_PSO_LINE_EDITOR_INIT))
3906 n_tty_init();
3907 assert(n_psonce & n_PSO_LINE_EDITOR_INIT);
3909 # ifdef HAVE_COLOUR
3910 n_colour_env_create(n_COLOUR_CTX_MLE, FAL0);
3911 /* C99 */{
3912 char const *ccol;
3913 struct n_colour_pen *ccp;
3914 struct str const *sp;
3916 /* .tl_pos_buf is a hack */
3917 posbuf = pos = NULL;
3918 if((ccp = n_colour_pen_create(n_COLOUR_ID_MLE_POSITION, NULL)) != NULL &&
3919 (sp = n_colour_pen_to_str(ccp)) != NULL){
3920 ccol = sp->s;
3921 if((sp = n_colour_reset_to_str()) != NULL){
3922 size_t l1, l2;
3924 l1 = strlen(ccol);
3925 l2 = strlen(sp->s);
3926 posbuf = salloc(l1 + 4 + l2 +1);
3927 memcpy(posbuf, ccol, l1);
3928 pos = &posbuf[l1];
3929 memcpy(&pos[4], sp->s, ++l2);
3932 if(posbuf == NULL){
3933 posbuf = pos = salloc(4 +1);
3934 pos[4] = '\0';
3937 # endif /* HAVE_COLOUR */
3939 memset(&tl, 0, sizeof tl);
3941 # ifdef HAVE_KEY_BINDINGS
3942 /* C99 */{
3943 char const *cp;
3945 if((cp = ok_vlook(bind_timeout)) != NULL){
3946 ui64_t uib;
3948 n_idec_ui64_cp(&uib, cp, 0, NULL);
3950 if(uib > 0 &&
3951 /* Convert to tenths of a second, unfortunately */
3952 (uib = (uib + 99) / 100) <= a_TTY_BIND_TIMEOUT_MAX)
3953 tl.tl_bind_timeout = (ui8_t)uib;
3954 else if(n_poption & n_PO_D_V)
3955 n_err(_("Ignoring invalid *bind-timeout*: %s\n"), cp);
3959 if(a_tty.tg_bind_isdirty)
3960 a_tty_bind_tree_teardown();
3961 if(a_tty.tg_bind_cnt > 0 && !a_tty.tg_bind_isbuild)
3962 a_tty_bind_tree_build();
3963 tl.tl_bind_tree_hmap = &a_tty.tg_bind_tree[lif & n__LEXINPUT_CTX_MASK];
3964 tl.tl_bind_shcut_cancel =
3965 &a_tty.tg_bind_shcut_cancel[lif & n__LEXINPUT_CTX_MASK];
3966 tl.tl_bind_shcut_prompt_char =
3967 &a_tty.tg_bind_shcut_prompt_char[lif & n__LEXINPUT_CTX_MASK];
3968 # endif /* HAVE_KEY_BINDINGS */
3970 # ifdef HAVE_COLOUR
3971 tl.tl_pos_buf = posbuf;
3972 tl.tl_pos = pos;
3973 # endif
3975 if(!(lif & n_LEXINPUT_PROMPT_NONE)){
3976 n_string_creat_auto(&xprompt);
3978 if((tl.tl_prompt_width = n_tty_create_prompt(&xprompt, prompt, lif)
3979 ) > 0){
3980 tl.tl_prompt = n_string_cp_const(&xprompt);
3981 tl.tl_prompt_length = (ui32_t)xprompt.s_len;
3985 tl.tl_line.cbuf = *linebuf;
3986 if(n != 0){
3987 tl.tl_defc.s = savestrbuf(*linebuf, n);
3988 tl.tl_defc.l = n;
3990 tl.tl_x_buf = linebuf;
3991 tl.tl_x_bufsize = linesize;
3993 a_tty.tg_line = &tl;
3994 a_tty_sigs_up();
3995 n_TERMCAP_RESUME(FAL0);
3996 a_tty_term_mode(TRU1);
3997 nn = a_tty_readline(&tl, n n_MEMORY_DEBUG_ARGSCALL);
3998 a_tty_term_mode(FAL0);
3999 n_TERMCAP_SUSPEND(FAL0);
4000 a_tty_sigs_down();
4001 a_tty.tg_line = NULL;
4003 # ifdef HAVE_COLOUR
4004 n_colour_env_gut(n_tty_fp);
4005 # endif
4006 NYD_LEAVE;
4007 return (int)nn;
4010 FL void
4011 n_tty_addhist(char const *s, bool_t isgabby){
4012 # ifdef HAVE_HISTORY
4013 /* Super-Heavy-Metal: block all sigs, avoid leaks+ on jump */
4014 ui32_t l;
4015 struct a_tty_hist *thp, *othp, *ythp;
4016 # endif
4017 NYD_ENTER;
4018 n_UNUSED(s);
4019 n_UNUSED(isgabby);
4021 # ifdef HAVE_HISTORY
4022 if(spacechar(*s) || *s == '\0' ||
4023 (!(n_psonce & n_PSO_LINE_EDITOR_INIT) && !(n_pstate & n_PS_ROOT)) ||
4024 a_tty.tg_hist_size_max == 0 ||
4025 ok_blook(line_editor_disable) ||
4026 (isgabby && !ok_blook(history_gabby)))
4027 goto j_leave;
4029 l = (ui32_t)strlen(s);
4031 /* Eliminating duplicates is expensive, but simply inacceptable so
4032 * during the load of a potentially large history file! */
4033 if(n_psonce & n_PSO_LINE_EDITOR_INIT)
4034 for(thp = a_tty.tg_hist; thp != NULL; thp = thp->th_older)
4035 if(thp->th_len == l && !strcmp(thp->th_dat, s)){
4036 hold_all_sigs(); /* TODO */
4037 if(thp->th_isgabby)
4038 thp->th_isgabby = !!isgabby;
4039 othp = thp->th_older;
4040 ythp = thp->th_younger;
4041 if(othp != NULL)
4042 othp->th_younger = ythp;
4043 else
4044 a_tty.tg_hist_tail = ythp;
4045 if(ythp != NULL)
4046 ythp->th_older = othp;
4047 else
4048 a_tty.tg_hist = othp;
4049 goto jleave;
4051 hold_all_sigs();
4053 ++a_tty.tg_hist_size;
4054 if((n_psonce & n_PSO_LINE_EDITOR_INIT) &&
4055 a_tty.tg_hist_size > a_tty.tg_hist_size_max){
4056 --a_tty.tg_hist_size;
4057 if((thp = a_tty.tg_hist_tail) != NULL){
4058 if((a_tty.tg_hist_tail = thp->th_younger) == NULL)
4059 a_tty.tg_hist = NULL;
4060 else
4061 a_tty.tg_hist_tail->th_older = NULL;
4062 free(thp);
4066 thp = smalloc(n_VSTRUCT_SIZEOF(struct a_tty_hist, th_dat) + l +1);
4067 thp->th_isgabby = !!isgabby;
4068 thp->th_len = l;
4069 memcpy(thp->th_dat, s, l +1);
4070 jleave:
4071 if((thp->th_older = a_tty.tg_hist) != NULL)
4072 a_tty.tg_hist->th_younger = thp;
4073 else
4074 a_tty.tg_hist_tail = thp;
4075 thp->th_younger = NULL;
4076 a_tty.tg_hist = thp;
4078 rele_all_sigs();
4079 j_leave:
4080 # endif /* HAVE_HISTORY */
4081 NYD_LEAVE;
4084 # ifdef HAVE_HISTORY
4085 FL int
4086 c_history(void *v){
4087 siz_t entry;
4088 struct a_tty_hist *thp;
4089 char **argv;
4090 NYD_ENTER;
4092 if(ok_blook(line_editor_disable)){
4093 n_err(_("history: *line-editor-disable* is set\n"));
4094 goto jerr;
4097 if(!(n_psonce & n_PSO_LINE_EDITOR_INIT)){
4098 n_tty_init();
4099 assert(n_psonce & n_PSO_LINE_EDITOR_INIT);
4102 if(*(argv = v) == NULL)
4103 goto jlist;
4104 if(argv[1] != NULL)
4105 goto jerr;
4106 if(!asccasecmp(*argv, "show"))
4107 goto jlist;
4108 if(!asccasecmp(*argv, "clear"))
4109 goto jclear;
4110 if((n_idec_siz_cp(&entry, *argv, 10, NULL
4111 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
4112 ) == n_IDEC_STATE_CONSUMED)
4113 goto jentry;
4114 jerr:
4115 n_err(_("Synopsis: history: %s\n"),
4116 /* Same string as in cmd_tab.h, still hoping...) */
4117 _("<show> (default), <clear> or select <NO> from editor history"));
4118 v = NULL;
4119 jleave:
4120 NYD_LEAVE;
4121 return (v == NULL ? !STOP : !OKAY); /* xxx 1:bad 0:good -- do some */
4123 jlist:{
4124 FILE *fp;
4125 size_t i, b;
4127 if(a_tty.tg_hist == NULL)
4128 goto jleave;
4130 if((fp = Ftmp(NULL, "hist", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
4131 n_perr(_("tmpfile"), 0);
4132 v = NULL;
4133 goto jleave;
4136 i = a_tty.tg_hist_size;
4137 b = 0;
4138 for(thp = a_tty.tg_hist; thp != NULL;
4139 --i, b += thp->th_len, thp = thp->th_older)
4140 fprintf(fp,
4141 "%c%4" PRIuZ ". %-50.50s (%4" PRIuZ "+%2" PRIu32 " B)\n",
4142 (thp->th_isgabby ? '*' : ' '), i, thp->th_dat, b, thp->th_len);
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_source_inject_input((n_INPUT_INJECT_COMMIT |
4172 n_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 n_CMD_ARG_DESC_SUBCLASS_DEF(bind, 3, a_tty_bind_cad) { /* TODO cmd_tab.h */
4189 {n_CMD_ARG_DESC_STRING, 0},
4190 {n_CMD_ARG_DESC_WYSH | n_CMD_ARG_DESC_OPTION |
4191 n_CMD_ARG_DESC_HONOUR_STOP,
4192 n_SHEXP_PARSE_DRYRUN | n_SHEXP_PARSE_LOG},
4193 {n_CMD_ARG_DESC_WYSH | n_CMD_ARG_DESC_OPTION | n_CMD_ARG_DESC_GREEDY |
4194 n_CMD_ARG_DESC_HONOUR_STOP,
4195 n_SHEXP_PARSE_IGNORE_EMPTY}
4196 } n_CMD_ARG_DESC_SUBCLASS_DEF_END;
4197 struct n_cmd_arg_ctx cac;
4198 struct a_tty_bind_ctx *tbcp;
4199 enum n_lexinput_flags lif;
4200 bool_t aster, show;
4201 union {char const *cp; char *p; char c;} c;
4202 NYD_ENTER;
4204 cac.cac_desc = n_CMD_ARG_DESC_SUBCLASS_CAST(&a_tty_bind_cad);
4205 cac.cac_indat = v;
4206 cac.cac_inlen = UIZ_MAX;
4207 if(!n_cmd_arg_parse(&cac)){
4208 v = NULL;
4209 goto jleave;
4212 c.cp = cac.cac_arg->ca_arg.ca_str.s;
4213 if(cac.cac_no == 1)
4214 show = TRU1;
4215 else
4216 show = !asccasecmp(cac.cac_arg->ca_next->ca_arg.ca_str.s, "show");
4217 aster = FAL0;
4219 if((lif = a_tty_bind_ctx_find(c.cp)) == (enum n_lexinput_flags)-1){
4220 if(!(aster = n_is_all_or_aster(c.cp)) || !show){
4221 n_err(_("`bind': invalid context: %s\n"), c.cp);
4222 v = NULL;
4223 goto jleave;
4225 lif = 0;
4228 if(show){
4229 ui32_t lns;
4230 FILE *fp;
4232 if((fp = Ftmp(NULL, "bind", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
4233 n_perr(_("tmpfile"), 0);
4234 v = NULL;
4235 goto jleave;
4238 lns = 0;
4239 for(;;){
4240 for(tbcp = a_tty.tg_bind[lif]; tbcp != NULL;
4241 ++lns, tbcp = tbcp->tbc_next){
4242 /* Print the bytes of resolved terminal capabilities, then */
4243 if((n_poption & n_PO_D_V) &&
4244 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)
4245 ) == a_TTY_BIND_RESOLVE){
4246 char cbuf[8];
4247 union {wchar_t const *wp; char const *cp;} u;
4248 si32_t entlen;
4249 ui32_t cnvlen;
4250 char const *cnvdat, *bsep, *cbufp;
4252 putc('#', fp);
4253 putc(' ', fp);
4255 cbuf[0] = '=', cbuf[2] = '\0';
4256 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len;
4257 cnvlen > 0;){
4258 if(cnvdat != tbcp->tbc_cnv)
4259 putc(',', fp);
4261 /* {si32_t buf_len_iscap;} */
4262 entlen = *n_UNALIGN(si32_t const*,cnvdat);
4263 if(entlen & SI32_MIN){
4264 /* struct{si32_t buf_len_iscap; si32_t cap_len;
4265 * char buf[]+NUL;} */
4266 for(bsep = n_empty,
4267 u.cp = (char const*)
4268 &n_UNALIGN(si32_t const*,cnvdat)[2];
4269 (c.c = *u.cp) != '\0'; ++u.cp){
4270 if(asciichar(c.c) && !cntrlchar(c.c))
4271 cbuf[1] = c.c, cbufp = cbuf;
4272 else
4273 cbufp = n_empty;
4274 fprintf(fp, "%s%02X%s",
4275 bsep, (ui32_t)(ui8_t)c.c, cbufp);
4276 bsep = " ";
4278 entlen &= SI32_MAX;
4279 }else
4280 putc('-', fp);
4282 cnvlen -= entlen;
4283 cnvdat += entlen;
4286 fputs("\n ", fp);
4287 ++lns;
4290 fprintf(fp, "%sbind %s %s %s%s%s\n",
4291 ((tbcp->tbc_flags & a_TTY_BIND_DEFUNCT)
4292 /* I18N: `bind' sequence not working, either because it is
4293 * I18N: using Unicode and that is not available in the locale,
4294 * I18N: or a termcap(5)/terminfo(5) sequence won't work out */
4295 ? _("# <Defunctional> ") : n_empty),
4296 a_tty_bind_ctx_maps[lif].tbcm_name, tbcp->tbc_seq,
4297 n_shexp_quote_cp(tbcp->tbc_exp, TRU1),
4298 (tbcp->tbc_flags & a_TTY_BIND_NOCOMMIT ? "@" : n_empty),
4299 (!(n_poption & n_PO_D_VV) ? n_empty
4300 : (tbcp->tbc_flags & a_TTY_BIND_FUN_INTERNAL
4301 ? _(" # MLE internal") : n_empty))
4304 if(!aster || ++lif >= n__LEXINPUT_CTX_MAX1)
4305 break;
4307 page_or_print(fp, lns);
4309 Fclose(fp);
4310 }else{
4311 struct a_tty_bind_parse_ctx tbpc;
4312 struct n_string store;
4314 memset(&tbpc, 0, sizeof tbpc);
4315 tbpc.tbpc_cmd = a_tty_bind_cad.cad_name;
4316 tbpc.tbpc_in_seq = cac.cac_arg->ca_next->ca_arg.ca_str.s;
4317 tbpc.tbpc_exp.s = n_string_cp(n_cmd_arg_join_greedy(&cac,
4318 n_string_creat_auto(&store)));
4319 tbpc.tbpc_exp.l = store.s_len;
4320 tbpc.tbpc_flags = lif;
4321 if(!a_tty_bind_create(&tbpc, TRU1))
4322 v = NULL;
4323 n_string_gut(&store);
4325 jleave:
4326 NYD_LEAVE;
4327 return (v != NULL) ? n_EXIT_OK : n_EXIT_ERR;
4330 FL int
4331 c_unbind(void *v){
4332 n_CMD_ARG_DESC_SUBCLASS_DEF(unbind, 2, a_tty_unbind_cad) {/* TODO cmd_tab.h*/
4333 {n_CMD_ARG_DESC_STRING, 0},
4334 {n_CMD_ARG_DESC_WYSH | n_CMD_ARG_DESC_HONOUR_STOP,
4335 n_SHEXP_PARSE_DRYRUN | n_SHEXP_PARSE_LOG}
4336 } n_CMD_ARG_DESC_SUBCLASS_DEF_END;
4337 struct a_tty_bind_parse_ctx tbpc;
4338 struct n_cmd_arg_ctx cac;
4339 struct a_tty_bind_ctx *tbcp;
4340 enum n_lexinput_flags lif;
4341 bool_t aster;
4342 union {char const *cp; char *p;} c;
4343 NYD_ENTER;
4345 cac.cac_desc = n_CMD_ARG_DESC_SUBCLASS_CAST(&a_tty_unbind_cad);
4346 cac.cac_indat = v;
4347 cac.cac_inlen = UIZ_MAX;
4348 if(!n_cmd_arg_parse(&cac)){
4349 v = NULL;
4350 goto jleave;
4353 c.cp = cac.cac_arg->ca_arg.ca_str.s;
4354 aster = FAL0;
4356 if((lif = a_tty_bind_ctx_find(c.cp)) == (enum n_lexinput_flags)-1){
4357 if(!(aster = n_is_all_or_aster(c.cp))){
4358 n_err(_("`unbind': invalid context: %s\n"), c.cp);
4359 v = NULL;
4360 goto jleave;
4362 lif = 0;
4365 c.cp = cac.cac_arg->ca_next->ca_arg.ca_str.s;
4366 jredo:
4367 if(n_is_all_or_aster(c.cp)){
4368 while((tbcp = a_tty.tg_bind[lif]) != NULL){
4369 memset(&tbpc, 0, sizeof tbpc);
4370 tbpc.tbpc_tbcp = tbcp;
4371 tbpc.tbpc_flags = lif;
4372 a_tty_bind_del(&tbpc);
4374 }else{
4375 memset(&tbpc, 0, sizeof tbpc);
4376 tbpc.tbpc_cmd = a_tty_unbind_cad.cad_name;
4377 tbpc.tbpc_in_seq = c.cp;
4378 tbpc.tbpc_flags = lif;
4380 if(n_UNLIKELY(!a_tty_bind_parse(FAL0, &tbpc)))
4381 v = NULL;
4382 else if(n_UNLIKELY((tbcp = tbpc.tbpc_tbcp) == NULL)){
4383 n_err(_("`unbind': no such `bind'ing: %s %s\n"),
4384 a_tty_bind_ctx_maps[lif].tbcm_name, c.cp);
4385 v = NULL;
4386 }else
4387 a_tty_bind_del(&tbpc);
4390 if(aster && ++lif < n__LEXINPUT_CTX_MAX1)
4391 goto jredo;
4392 jleave:
4393 NYD_LEAVE;
4394 return (v != NULL) ? n_EXIT_OK : n_EXIT_ERR;
4396 # endif /* HAVE_KEY_BINDINGS */
4398 #else /* HAVE_MLE */
4400 * The really-nothing-at-all implementation
4403 FL void
4404 n_tty_init(void){
4405 NYD_ENTER;
4406 NYD_LEAVE;
4409 FL void
4410 n_tty_destroy(void){
4411 NYD_ENTER;
4412 NYD_LEAVE;
4415 FL void
4416 n_tty_signal(int sig){
4417 NYD_X; /* Signal handler */
4418 n_UNUSED(sig);
4420 # ifdef HAVE_TERMCAP
4421 switch(sig){
4422 default:{
4423 sigset_t nset, oset;
4425 n_TERMCAP_SUSPEND(TRU1);
4426 a_tty_sigs_down();
4428 sigemptyset(&nset);
4429 sigaddset(&nset, sig);
4430 sigprocmask(SIG_UNBLOCK, &nset, &oset);
4431 n_raise(sig);
4432 /* When we come here we'll continue editing, so reestablish */
4433 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
4435 a_tty_sigs_up();
4436 n_TERMCAP_RESUME(TRU1);
4437 break;
4440 # endif /* HAVE_TERMCAP */
4443 FL int
4444 (n_tty_readline)(enum n_lexinput_flags lif, char const *prompt,
4445 char **linebuf, size_t *linesize, size_t n n_MEMORY_DEBUG_ARGS){
4446 struct n_string xprompt;
4447 int rv;
4448 NYD_ENTER;
4450 if(!(lif & n_LEXINPUT_PROMPT_NONE)){
4451 if(n_tty_create_prompt(n_string_creat_auto(&xprompt), prompt, lif) > 0){
4452 fwrite(xprompt.s_dat, 1, xprompt.s_len, n_tty_fp);
4453 fflush(n_tty_fp);
4457 # ifdef HAVE_TERMCAP
4458 a_tty_sigs_up();
4459 n_TERMCAP_RESUME(FAL0);
4460 # endif
4461 rv = (readline_restart)(n_stdin, linebuf, linesize,n n_MEMORY_DEBUG_ARGSCALL);
4462 # ifdef HAVE_TERMCAP
4463 n_TERMCAP_SUSPEND(FAL0);
4464 a_tty_sigs_down();
4465 # endif
4466 NYD_LEAVE;
4467 return rv;
4470 FL void
4471 n_tty_addhist(char const *s, bool_t isgabby){
4472 NYD_ENTER;
4473 n_UNUSED(s);
4474 n_UNUSED(isgabby);
4475 NYD_LEAVE;
4477 #endif /* nothing at all */
4479 #undef a_TTY_SIGNALS
4480 /* s-it-mode */