getpassword(): fail right away unless OPT_TTYIN
[s-mailx.git] / tty.c
blob08baa3a4c9a414eab1e4a5cf1a9e92a695498fdd
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 - 2016 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 /* History support macros */
33 #ifdef HAVE_HISTORY
34 # define a_TTY_HISTFILE(S) \
35 do{\
36 char const *__hist_obsolete = ok_vlook(NAIL_HISTFILE);\
37 if(__hist_obsolete != NULL)\
38 OBSOLETE(_("please use *history-file* instead of *NAIL_HISTFILE*"));\
39 S = ok_vlook(history_file);\
40 if((S) == NULL)\
41 (S) = __hist_obsolete;\
42 if((S) != NULL)\
43 S = fexpand(S, FEXP_LOCAL | FEXP_NSHELL);\
44 }while(0)
46 # define a_TTY_HISTSIZE(V) \
47 do{\
48 char const *__hist_obsolete = ok_vlook(NAIL_HISTSIZE);\
49 char const *__sv = ok_vlook(history_size);\
50 long __rv;\
51 if(__hist_obsolete != NULL)\
52 OBSOLETE(_("please use *history-size* instead of *NAIL_HISTSIZE*"));\
53 if(__sv == NULL)\
54 __sv = __hist_obsolete;\
55 if(__sv == NULL || (__rv = strtol(__sv, NULL, 10)) == 0)\
56 __rv = HIST_SIZE;\
57 else if(__rv < 0)\
58 __rv = 0;\
59 (V) = __rv;\
60 }while(0)
62 # define a_TTY_CHECK_ADDHIST(S,ISGABBY,NOACT) \
63 do{\
64 if(!(pstate & (PS_ROOT | PS_LINE_EDITOR_INIT)) ||\
65 ok_blook(line_editor_disable) ||\
66 ((ISGABBY) && !ok_blook(history_gabby)) ||\
67 spacechar(*(S)) || *(S) == '\0')\
68 NOACT;\
69 }while(0)
71 # define C_HISTORY_SHARED \
72 char **argv = v;\
73 long entry;\
74 NYD_ENTER;\
76 if(ok_blook(line_editor_disable)){\
77 n_err(_("history: *line-editor-disable* is set\n"));\
78 goto jerr;\
80 if(!(pstate & PS_LINE_EDITOR_INIT)){\
81 n_tty_init();\
82 assert(pstate & PS_LINE_EDITOR_INIT);\
84 if(*argv == NULL)\
85 goto jlist;\
86 if(argv[1] != NULL)\
87 goto jerr;\
88 if(!asccasecmp(*argv, "show"))\
89 goto jlist;\
90 if(!asccasecmp(*argv, "clear"))\
91 goto jclear;\
92 if((entry = strtol(*argv, argv, 10)) > 0 && **argv == '\0')\
93 goto jentry;\
94 jerr:\
95 n_err(_("Synopsis: history: %s\n"),\
96 /* Same string as in cmd_tab.h, still hoping...) */\
97 _("<show> (default), <clear> or select <NO> from editor history"));\
98 v = NULL;\
99 jleave:\
100 NYD_LEAVE;\
101 return (v == NULL ? !STOP : !OKAY); /* xxx 1:bad 0:good -- do some */
102 #endif /* HAVE_HISTORY */
104 #ifdef a_TTY_SIGNALS
105 static sighandler_type a_tty_oint, a_tty_oquit, a_tty_oterm,
106 a_tty_ohup,
107 a_tty_otstp, a_tty_ottin, a_tty_ottou;
108 #endif
110 #ifdef a_TTY_SIGNALS
111 static void a_tty_sigs_up(void), a_tty_sigs_down(void);
112 #endif
114 #ifdef a_TTY_SIGNALS
115 static void
116 a_tty_sigs_up(void){
117 sigset_t nset, oset;
118 NYD2_ENTER;
120 sigfillset(&nset);
122 sigprocmask(SIG_BLOCK, &nset, &oset);
123 a_tty_oint = safe_signal(SIGINT, &n_tty_signal);
124 a_tty_oquit = safe_signal(SIGQUIT, &n_tty_signal);
125 a_tty_oterm = safe_signal(SIGTERM, &n_tty_signal);
126 a_tty_ohup = safe_signal(SIGHUP, &n_tty_signal);
127 a_tty_otstp = safe_signal(SIGTSTP, &n_tty_signal);
128 a_tty_ottin = safe_signal(SIGTTIN, &n_tty_signal);
129 a_tty_ottou = safe_signal(SIGTTOU, &n_tty_signal);
130 sigprocmask(SIG_SETMASK, &oset, NULL);
131 NYD2_LEAVE;
134 static void
135 a_tty_sigs_down(void){
136 sigset_t nset, oset;
137 NYD2_ENTER;
139 sigfillset(&nset);
141 sigprocmask(SIG_BLOCK, &nset, &oset);
142 safe_signal(SIGINT, a_tty_oint);
143 safe_signal(SIGQUIT, a_tty_oquit);
144 safe_signal(SIGTERM, a_tty_oterm);
145 safe_signal(SIGHUP, a_tty_ohup);
146 safe_signal(SIGTSTP, a_tty_otstp);
147 safe_signal(SIGTTIN, a_tty_ottin);
148 safe_signal(SIGTTOU, a_tty_ottou);
149 sigprocmask(SIG_SETMASK, &oset, NULL);
150 NYD2_LEAVE;
152 #endif /* a_TTY_SIGNALS */
154 static sigjmp_buf a_tty__actjmp; /* TODO someday, we won't need it no more */
155 static void
156 a_tty__acthdl(int s) /* TODO someday, we won't need it no more */
158 NYD_X; /* Signal handler */
159 termios_state_reset();
160 siglongjmp(a_tty__actjmp, s);
163 FL bool_t
164 getapproval(char const * volatile prompt, bool_t noninteract_default)
166 sighandler_type volatile oint, ohup;
167 bool_t volatile rv;
168 int volatile sig;
169 NYD_ENTER;
171 if (!(options & OPT_INTERACTIVE)) {
172 sig = 0;
173 rv = noninteract_default;
174 goto jleave;
176 rv = FAL0;
178 /* C99 */{
179 char const *quest = noninteract_default
180 ? _("[yes]/no? ") : _("[no]/yes? ");
182 if (prompt == NULL)
183 prompt = _("Continue");
184 prompt = savecatsep(prompt, ' ', quest);
187 oint = safe_signal(SIGINT, SIG_IGN);
188 ohup = safe_signal(SIGHUP, SIG_IGN);
189 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
190 goto jrestore;
191 safe_signal(SIGINT, &a_tty__acthdl);
192 safe_signal(SIGHUP, &a_tty__acthdl);
194 if (n_lex_input(n_LEXINPUT_CTX_DEFAULT | n_LEXINPUT_NL_ESC, prompt,
195 &termios_state.ts_linebuf, &termios_state.ts_linesize, NULL) >= 0)
196 rv = (boolify(termios_state.ts_linebuf, UIZ_MAX,
197 noninteract_default) > 0);
198 jrestore:
199 termios_state_reset();
201 safe_signal(SIGHUP, ohup);
202 safe_signal(SIGINT, oint);
203 jleave:
204 NYD_LEAVE;
205 if (sig != 0)
206 n_raise(sig);
207 return rv;
210 #ifdef HAVE_SOCKETS
211 FL char *
212 getuser(char const * volatile query) /* TODO v15-compat obsolete */
214 sighandler_type volatile oint, ohup;
215 char * volatile user = NULL;
216 int volatile sig;
217 NYD_ENTER;
219 if (query == NULL)
220 query = _("User: ");
222 oint = safe_signal(SIGINT, SIG_IGN);
223 ohup = safe_signal(SIGHUP, SIG_IGN);
224 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
225 goto jrestore;
226 safe_signal(SIGINT, &a_tty__acthdl);
227 safe_signal(SIGHUP, &a_tty__acthdl);
229 if (n_lex_input(n_LEXINPUT_CTX_DEFAULT | n_LEXINPUT_NL_ESC, query,
230 &termios_state.ts_linebuf, &termios_state.ts_linesize, NULL) >= 0)
231 user = termios_state.ts_linebuf;
232 jrestore:
233 termios_state_reset();
235 safe_signal(SIGHUP, ohup);
236 safe_signal(SIGINT, oint);
237 NYD_LEAVE;
238 if (sig != 0)
239 n_raise(sig);
240 return user;
243 FL char *
244 getpassword(char const *query)/* TODO v15: use _only_ n_tty_fp! */
246 sighandler_type volatile oint, ohup;
247 struct termios tios;
248 char * volatile pass;
249 int volatile sig;
250 NYD_ENTER;
252 pass = NULL;
253 if(!(options & OPT_TTYIN))
254 goto j_leave;
256 if (query == NULL)
257 query = _("Password: ");
258 fputs(query, n_tty_fp);
259 fflush(n_tty_fp);
261 /* FIXME everywhere: tcsetattr() generates SIGTTOU when we're not in
262 * FIXME foreground pgrp, and can fail with EINTR!! also affects
263 * FIXME termios_state_reset() */
264 tcgetattr(STDIN_FILENO, &termios_state.ts_tios);
265 memcpy(&tios, &termios_state.ts_tios, sizeof tios);
266 termios_state.ts_needs_reset = TRU1;
267 tios.c_iflag &= ~(ISTRIP);
268 tios.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
270 oint = safe_signal(SIGINT, SIG_IGN);
271 ohup = safe_signal(SIGHUP, SIG_IGN);
272 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
273 goto jrestore;
274 safe_signal(SIGINT, &a_tty__acthdl);
275 safe_signal(SIGHUP, &a_tty__acthdl);
277 tcsetattr(STDIN_FILENO, TCSAFLUSH, &tios);
278 if (readline_restart(stdin, &termios_state.ts_linebuf,
279 &termios_state.ts_linesize, 0) >= 0)
280 pass = termios_state.ts_linebuf;
281 jrestore:
282 termios_state_reset();
283 putc('\n', n_tty_fp);
285 safe_signal(SIGHUP, ohup);
286 safe_signal(SIGINT, oint);
287 NYD_LEAVE;
288 if (sig != 0)
289 n_raise(sig);
290 j_leave:
291 return pass;
293 #endif /* HAVE_SOCKETS */
295 FL ui32_t
296 n_tty_create_prompt(struct n_string *store, char const *xprompt,
297 enum n_lexinput_flags lif){
298 struct n_visual_info_ctx vic;
299 struct str in, out;
300 ui32_t pwidth;
301 char const *cp;
302 NYD2_ENTER;
304 /* Prompt creation indicates that prompt printing is directly ahead, so take
305 * this opportunity of UI-in-a-known-state and advertise the error ring */
306 #ifdef HAVE_ERRORS
307 if((options & OPT_INTERACTIVE) &&
308 (pstate & (PS_ERRORS_PROMPT | PS_ERRORS_NOTED)) == PS_ERRORS_PROMPT){
309 pstate |= PS_ERRORS_NOTED;
310 fprintf(stderr, _("There are new messages in the error message ring "
311 "(denoted by %s)\n"
312 " The `errors' command manages this message ring\n"),
313 V_(n_error));
315 #endif
317 jredo:
318 n_string_trunc(store, 0);
320 if(lif & n_LEXINPUT_PROMPT_NONE){
321 pwidth = 0;
322 goto jleave;
324 #ifdef HAVE_ERRORS
325 if(pstate & PS_ERRORS_PROMPT){
326 pstate &= ~PS_ERRORS_PROMPT;
327 store = n_string_push_cp(store, V_(n_error));
328 store = n_string_push_c(store, '#');
329 store = n_string_push_c(store, ' ');
331 #endif
333 cp = (lif & n_LEXINPUT_PROMPT_EVAL)
334 ? (lif & n_LEXINPUT_NL_FOLLOW ? ok_vlook(prompt2) : ok_vlook(prompt))
335 : xprompt;
336 if(cp != NULL && *cp != '\0'){
337 enum n_shexp_state shs;
339 store = n_string_push_cp(store, cp);
340 in.s = n_string_cp(store);
341 in.l = store->s_len;
342 out = in;
343 store = n_string_drop_ownership(store);
345 shs = n_shexp_parse_token(store, &in, n_SHEXP_PARSE_LOG |
346 n_SHEXP_PARSE_IGNORE_EMPTY | n_SHEXP_PARSE_QUOTE_AUTO_FIXED |
347 n_SHEXP_PARSE_QUOTE_AUTO_DSQ);
348 if((shs & n_SHEXP_STATE_ERR_MASK) || !(shs & n_SHEXP_STATE_STOP)){
349 store = n_string_clear(store);
350 store = n_string_take_ownership(store, out.s, out.l +1, out.l);
351 jeeval:
352 n_err(_("*prompt2?* evaluation failed, actively unsetting it\n"));
353 if(lif & n_LEXINPUT_NL_FOLLOW)
354 ok_vclear(prompt2);
355 else
356 ok_vclear(prompt);
357 goto jredo;
360 if(!store->s_auto)
361 free(out.s);
364 /* Make all printable TODO not know, we want to pass through ESC/CSI! */
365 #if 0
366 in.s = n_string_cp(store);
367 in.l = store->s_len;
368 makeprint(&in, &out);
369 store = n_string_assign_buf(store, out.s, out.l);
370 free(out.s);
371 #endif
373 /* We need the visual width.. */
374 memset(&vic, 0, sizeof vic);
375 vic.vic_indat = n_string_cp(store);
376 vic.vic_inlen = store->s_len;
377 for(pwidth = 0; vic.vic_inlen > 0;){
378 /* but \[ .. \] is not taken into account */
379 if(vic.vic_indat[0] == '\\' && vic.vic_inlen > 1 &&
380 vic.vic_indat[1] == '['){
381 size_t i;
383 i = PTR2SIZE(vic.vic_indat - store->s_dat);
384 store = n_string_cut(store, i, 2);
385 cp = &n_string_cp(store)[i];
386 i = store->s_len - i;
387 for(;; ++cp, --i){
388 if(i < 2){
389 n_err(_("Open \\[ sequence not closed in *prompt2?*\n"));
390 goto jeeval;
392 if(cp[0] == '\\' && cp[1] == ']')
393 break;
395 i = PTR2SIZE(cp - store->s_dat);
396 store = n_string_cut(store, i, 2);
397 vic.vic_indat = &n_string_cp(store)[i];
398 vic.vic_inlen = store->s_len - i;
399 }else if(!n_visual_info(&vic, n_VISUAL_INFO_WIDTH_QUERY |
400 n_VISUAL_INFO_ONE_CHAR)){
401 n_err(_("Character set error in evaluation of *prompt2?*\n"));
402 goto jeeval;
403 }else{
404 pwidth += (ui32_t)vic.vic_vi_width;
405 vic.vic_indat = vic.vic_oudat;
406 vic.vic_inlen = vic.vic_oulen;
410 /* And there may be colour support, too */
411 #ifdef HAVE_COLOUR
412 /* C99 */{
413 struct str const *psp, *rsp;
414 struct n_colour_pen *ccp;
416 if((ccp = n_colour_pen_create(n_COLOUR_ID_MLE_PROMPT, NULL)) != NULL &&
417 (psp = n_colour_pen_to_str(ccp)) != NULL &&
418 (rsp = n_colour_reset_to_str()) != NULL){
419 store = n_string_unshift_buf(store, psp->s, psp->l);
420 store = n_string_push_buf(store, rsp->s, rsp->l);
423 #endif /* HAVE_COLOUR */
425 jleave:
426 NYD2_LEAVE;
427 return pwidth;
431 * MLE: the Mailx-Line-Editor, our homebrew editor
432 * (inspired from NetBSDs sh(1) and dash(1)s hetio.c).
434 * Only used in interactive mode.
435 * TODO . This code should be splitted in funs/raw input/bind modules.
436 * TODO . We work with wide characters, but not for buffer takeovers and
437 * TODO cell2save()ings. This should be changed. For the former the buffer
438 * TODO thus needs to be converted to wide first, and then simply be fed in.
439 * TODO . We repaint too much. To overcome this use the same approach that my
440 * TODO terminal library uses, add a true "virtual screen line" that stores
441 * TODO the actually visible content, keep a notion of "first modified slot"
442 * TODO and "last modified slot" (including "unknown" and "any" specials),
443 * TODO update that virtual instead, then synchronize what has truly changed.
444 * TODO I.e., add an indirection layer.
445 * TODO . No BIDI support.
446 * TODO . `bind': we currently use only one lookup tree.
447 * TODO For absolute graceful behaviour in conjunction (with HAVE_TERMCAP) we
448 * TODO need a lower level tree, which possibly combines bytes into "symbolic
449 * TODO wchar_t values", into "keys" that is, as applicable, and an upper
450 * TODO layer which only works on "keys" in order to possibly combine them
451 * TODO into key sequences. We can reuse existent tree code for that.
452 * TODO We need an additional hashmap which maps termcap/terminfo names to
453 * TODO (their byte representations and) a dynamically assigned unique
454 * TODO "symbolic wchar_t value". This implies we may have incompatibilities
455 * TODO when __STDC_ISO_10646__ is not defined. Also we do need takeover-
456 * TODO bytes storage, but it can be a string_creat_auto in the line struct.
457 * TODO Until then we can run into ambiguities; in rare occasions.
459 #ifdef HAVE_MLE
460 /* To avoid memory leaks etc. with the current codebase that simply longjmp(3)s
461 * we're forced to use the very same buffer--the one that is passed through to
462 * us from the outside--to store anything we need, i.e., a "struct cell[]", and
463 * convert that on-the-fly back to the plain char* result once we're done.
464 * To simplify our live, use savestr() buffers for all other needed memory */
466 # ifdef HAVE_KEY_BINDINGS
467 /* Default *bind-timeout* key-sequence continuation timeout, in tenths of
468 * a second. Must fit in 8-bit! Update the manual upon change! */
469 # define a_TTY_BIND_TIMEOUT 2
470 # define a_TTY_BIND_TIMEOUT_MAX SI8_MAX
472 n_CTAV(a_TTY_BIND_TIMEOUT_MAX <= UI8_MAX);
474 /* We have a chicken-and-egg problem with `bind' and our termcap layer,
475 * because we may not initialize the latter automatically to allow users to
476 * specify *termcap-disable* and let it mean exactly that.
477 * On the other hand users can be expected to use `bind' in resource file(s).
478 * Therefore bindings which involve termcap/terminfo sequences, and which are
479 * defined before PS_STARTED signals usability of termcap/terminfo, will be
480 * (partially) delayed until tty_init() is called.
481 * And we preallocate space for the expansion of the resolved capability */
482 # define a_TTY_BIND_CAPNAME_MAX 15
483 # define a_TTY_BIND_CAPEXP_ROUNDUP 16
485 n_CTAV(n_ISPOW2(a_TTY_BIND_CAPEXP_ROUNDUP));
486 n_CTA(a_TTY_BIND_CAPEXP_ROUNDUP <= SI8_MAX / 2, "Variable must fit in 6-bit");
487 n_CTA(a_TTY_BIND_CAPEXP_ROUNDUP >= 8, "Variable too small");
488 # endif /* HAVE_KEY_BINDINGS */
490 /* The maximum size (of a_tty_cell's) in a line */
491 # define a_TTY_LINE_MAX SI32_MAX
493 /* (Some more CTAs around) */
494 n_CTA(a_TTY_LINE_MAX <= SI32_MAX,
495 "a_TTY_LINE_MAX larger than SI32_MAX, but the MLE uses 32-bit arithmetic");
497 /* When shall the visual screen be scrolled, in % of usable screen width */
498 # define a_TTY_SCROLL_MARGIN_LEFT 15
499 # define a_TTY_SCROLL_MARGIN_RIGHT 10
501 /* fexpand() flags for expand-on-tab */
502 # define a_TTY_TAB_FEXP_FL (FEXP_FULL | FEXP_SILENT | FEXP_MULTIOK)
504 /* Columns to ripoff: outermost may not be touched, plus position indicator.
505 * Must thus be at least 1, but should be >= 1+4 to dig the position indicator
506 * that we place (if there is sufficient space) */
507 # define a_TTY_WIDTH_RIPOFF 5
509 /* The implementation of the MLE functions always exists, and is based upon
510 * the a_TTY_BIND_FUN_* constants, so most of this enum is always necessary */
511 enum a_tty_bind_flags{
512 # ifdef HAVE_KEY_BINDINGS
513 a_TTY_BIND_RESOLVE = 1u<<8, /* Term cap. yet needs to be resolved */
514 a_TTY_BIND_DEFUNCT = 1u<<9, /* Unicode/term cap. used but not avail. */
515 a_TTY__BIND_MASK = a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT,
516 /* MLE fun assigned to a one-byte-sequence: this may be used for special
517 * key-sequence bypass processing */
518 a_TTY_BIND_MLE1CNTRL = 1u<<10,
519 a_TTY_BIND_NOCOMMIT = 1u<<11, /* Expansion shall be editable */
520 # endif
522 /* MLE internal commands */
523 a_TTY_BIND_FUN_INTERNAL = 1u<<15,
524 a_TTY__BIND_FUN_SHIFT = 16u,
525 a_TTY__BIND_FUN_SHIFTMAX = 24u,
526 a_TTY__BIND_FUN_MASK = ((1u << a_TTY__BIND_FUN_SHIFTMAX) - 1) &
527 ~((1u << a_TTY__BIND_FUN_SHIFT) - 1),
528 # define a_TTY_BIND_FUN_REDUCE(X) \
529 (((ui32_t)(X) & a_TTY__BIND_FUN_MASK) >> a_TTY__BIND_FUN_SHIFT)
530 # define a_TTY_BIND_FUN_EXPAND(X) \
531 (((ui32_t)(X) & (a_TTY__BIND_FUN_MASK >> a_TTY__BIND_FUN_SHIFT)) << \
532 a_TTY__BIND_FUN_SHIFT)
533 # undef a_X
534 # define a_X(N,I)\
535 a_TTY_BIND_FUN_ ## N = a_TTY_BIND_FUN_EXPAND(I),
537 a_X(BELL, 0)
538 a_X(GO_BWD, 1) a_X(GO_FWD, 2)
539 a_X(GO_WORD_BWD, 3) a_X(GO_WORD_FWD, 4)
540 a_X(GO_HOME, 5) a_X(GO_END, 6)
541 a_X(DEL_BWD, 7) a_X(DEL_FWD, 8)
542 a_X(SNARF_WORD_BWD, 9) a_X(SNARF_WORD_FWD, 10)
543 a_X(SNARF_END, 11) a_X(SNARF_LINE, 12)
544 a_X(HIST_BWD, 13) a_X(HIST_FWD, 14)
545 a_X(HIST_SRCH_BWD, 15) a_X(HIST_SRCH_FWD, 16)
546 a_X(REPAINT, 17)
547 a_X(QUOTE_RNDTRIP, 18)
548 a_X(PROMPT_CHAR, 19)
549 a_X(COMPLETE, 20)
550 a_X(PASTE, 21)
552 a_X(CANCEL, 22)
553 a_X(RESET, 23)
554 a_X(FULLRESET, 24)
555 a_X(COMMIT, 25) /* Must be last one! */
556 # undef a_X
558 a_TTY__BIND_LAST = 1<<25
560 # ifdef HAVE_KEY_BINDINGS
561 n_CTA((ui32_t)a_TTY_BIND_RESOLVE >= (ui32_t)n__LEXINPUT_CTX_MAX1,
562 "Bit carrier lower boundary must be raised to avoid value sharing");
563 # endif
564 n_CTA(a_TTY_BIND_FUN_EXPAND(a_TTY_BIND_FUN_COMMIT) <
565 (1 << a_TTY__BIND_FUN_SHIFTMAX),
566 "Bit carrier range must be expanded to represent necessary bits");
567 n_CTA(a_TTY__BIND_LAST >= (1u << a_TTY__BIND_FUN_SHIFTMAX),
568 "Bit carrier upper boundary must be raised to avoid value sharing");
569 n_CTA(UICMP(64, a_TTY__BIND_LAST, <=, SI32_MAX),
570 "Flag bits excess storage datatype" /* And we need one bit free */);
572 enum a_tty_fun_status{
573 a_TTY_FUN_STATUS_OK, /* Worked, next character */
574 a_TTY_FUN_STATUS_COMMIT, /* Line done */
575 a_TTY_FUN_STATUS_RESTART, /* Complete restart, reset multibyte etc. */
576 a_TTY_FUN_STATUS_END /* End, return EOF */
579 enum a_tty_visual_flags{
580 a_TTY_VF_NONE,
581 a_TTY_VF_MOD_CURSOR = 1u<<0, /* Cursor moved */
582 a_TTY_VF_MOD_CONTENT = 1u<<1, /* Content modified */
583 a_TTY_VF_MOD_DIRTY = 1u<<2, /* Needs complete repaint */
584 a_TTY_VF_MOD_SINGLE = 1u<<3, /* TODO Drop when indirection as above comes */
585 a_TTY_VF_REFRESH = a_TTY_VF_MOD_DIRTY | a_TTY_VF_MOD_CURSOR |
586 a_TTY_VF_MOD_CONTENT | a_TTY_VF_MOD_SINGLE,
587 a_TTY_VF_BELL = 1u<<8, /* Ring the bell */
588 a_TTY_VF_SYNC = 1u<<9, /* Flush/Sync I/O channel */
590 a_TTY_VF_ALL_MASK = a_TTY_VF_REFRESH | a_TTY_VF_BELL | a_TTY_VF_SYNC,
591 a_TTY__VF_LAST = a_TTY_VF_SYNC
594 # ifdef HAVE_KEY_BINDINGS
595 struct a_tty_bind_ctx{
596 struct a_tty_bind_ctx *tbc_next;
597 char *tbc_seq; /* quence as given (poss. re-quoted), in .tb__buf */
598 char *tbc_exp; /* ansion, in .tb__buf */
599 /* The .tbc_seq'uence with any terminal capabilities resolved; in fact an
600 * array of structures, the first entry of which is {si32_t buf_len_iscap;}
601 * where the signed bit indicates whether the buffer is a resolved terminal
602 * capability instead of a (possibly multibyte) character. In .tbc__buf */
603 char *tbc_cnv;
604 ui32_t tbc_seq_len;
605 ui32_t tbc_exp_len;
606 ui32_t tbc_cnv_len;
607 ui32_t tbc_flags;
608 char tbc__buf[n_VFIELD_SIZE(0)];
611 struct a_tty_bind_ctx_map{
612 enum n_lexinput_flags tbcm_ctx;
613 char const tbcm_name[12]; /* Name of `bind' context */
615 # endif /* HAVE_KEY_BINDINGS */
617 struct a_tty_bind_builtin_tuple{
618 bool_t tbbt_iskey; /* Whether this is a control key; else termcap query */
619 char tbbt_ckey; /* Control code */
620 ui16_t tbbt_query; /* enum n_termcap_query (instead) */
621 char tbbt_exp[12]; /* String or [0]=NUL/[1]=BIND_FUN_REDUCE() */
623 n_CTA(n__TERMCAP_QUERY_MAX1 <= UI16_MAX,
624 "Enumeration cannot be stored in datatype");
626 # ifdef HAVE_KEY_BINDINGS
627 struct a_tty_bind_parse_ctx{
628 char const *tbpc_cmd; /* Command which parses */
629 char const *tbpc_in_seq; /* In: key sequence */
630 struct str tbpc_exp; /* In/Out: expansion (or NULL) */
631 struct a_tty_bind_ctx *tbpc_tbcp; /* Out: if yet existent */
632 struct a_tty_bind_ctx *tbpc_ltbcp; /* Out: the one before .tbpc_tbcp */
633 char *tbpc_seq; /* Out: normalized sequence */
634 char *tbpc_cnv; /* Out: sequence when read(2)ing it */
635 ui32_t tbpc_seq_len;
636 ui32_t tbpc_cnv_len;
637 ui32_t tbpc_cnv_align_mask; /* For creating a_tty_bind_ctx.tbc_cnv */
638 ui32_t tbpc_flags; /* n_lexinput_flags | a_tty_bind_flags */
641 /* Input character tree */
642 struct a_tty_bind_tree{
643 struct a_tty_bind_tree *tbt_sibling; /* s at same level */
644 struct a_tty_bind_tree *tbt_childs; /* Sequence continues.. here */
645 struct a_tty_bind_tree *tbt_parent;
646 struct a_tty_bind_ctx *tbt_bind; /* NULL for intermediates */
647 wchar_t tbt_char; /* acter this level represents */
648 bool_t tbt_isseq; /* Belongs to multibyte sequence */
649 bool_t tbt_isseq_trail; /* ..is trailing byte of it */
650 ui8_t tbt__dummy[2];
652 # endif /* HAVE_KEY_BINDINGS */
654 struct a_tty_cell{
655 wchar_t tc_wc;
656 ui16_t tc_count; /* ..of bytes */
657 ui8_t tc_width; /* Visual width; TAB==UI8_MAX! */
658 bool_t tc_novis; /* Don't display visually as such (control character) */
659 char tc_cbuf[MB_LEN_MAX * 2]; /* .. plus reset shift sequence */
662 struct a_tty_global{
663 struct a_tty_line *tg_line; /* To be able to access it from signal hdl */
664 # ifdef HAVE_HISTORY
665 struct a_tty_hist *tg_hist;
666 struct a_tty_hist *tg_hist_tail;
667 size_t tg_hist_size;
668 size_t tg_hist_size_max;
669 # endif
670 # ifdef HAVE_KEY_BINDINGS
671 ui32_t tg_bind_cnt; /* Overall number of bindings */
672 bool_t tg_bind_isdirty;
673 bool_t tg_bind_isbuild;
674 # define a_TTY_SHCUT_MAX (3 +1) /* Note: update manual on change! */
675 ui8_t tg_bind__dummy[2];
676 char tg_bind_shcut_cancel[n__LEXINPUT_CTX_MAX1][a_TTY_SHCUT_MAX];
677 char tg_bind_shcut_prompt_char[n__LEXINPUT_CTX_MAX1][a_TTY_SHCUT_MAX];
678 struct a_tty_bind_ctx *tg_bind[n__LEXINPUT_CTX_MAX1];
679 struct a_tty_bind_tree *tg_bind_tree[n__LEXINPUT_CTX_MAX1][HSHSIZE];
680 # endif
681 struct termios tg_tios_old;
682 struct termios tg_tios_new;
684 # ifdef HAVE_KEY_BINDINGS
685 n_CTA(n__LEXINPUT_CTX_MAX1 == 3 && a_TTY_SHCUT_MAX == 4 &&
686 n_SIZEOF_FIELD(struct a_tty_global, tg_bind__dummy) == 2,
687 "Value results in array sizes that results in bad structure layout");
688 n_CTA(a_TTY_SHCUT_MAX > 1,
689 "Users need at least one shortcut, plus NUL terminator");
690 # endif
692 # ifdef HAVE_HISTORY
693 struct a_tty_hist{
694 struct a_tty_hist *th_older;
695 struct a_tty_hist *th_younger;
696 # ifdef HAVE_BYTE_ORDER_LITTLE
697 ui32_t th_isgabby : 1;
698 # endif
699 ui32_t th_len : 31;
700 # ifndef HAVE_BYTE_ORDER_LITTLE
701 ui32_t th_isgabby : 1;
702 # endif
703 char th_dat[n_VFIELD_SIZE(sizeof(ui32_t))];
705 # endif
707 struct a_tty_line{
708 /* Caller pointers */
709 char **tl_x_buf;
710 size_t *tl_x_bufsize;
711 /* Input processing */
712 # ifdef HAVE_KEY_BINDINGS
713 wchar_t tl_bind_takeover; /* Leftover byte to consume next */
714 ui8_t tl_bind_timeout; /* In-seq. inter-byte-timer, in 1/10th secs */
715 ui8_t tl__bind_dummy[3];
716 char (*tl_bind_shcut_cancel)[a_TTY_SHCUT_MAX]; /* Special _CANCEL control */
717 char (*tl_bind_shcut_prompt_char)[a_TTY_SHCUT_MAX]; /* ..for _PROMPT_CHAR */
718 struct a_tty_bind_tree *(*tl_bind_tree_hmap)[HSHSIZE]; /* Bind lookup tree */
719 struct a_tty_bind_tree *tl_bind_tree;
720 # endif
721 char const *tl_reenter_after_cmd; /* `bind' cmd to exec, then re-readline */
722 /* Line data / content handling */
723 ui32_t tl_count; /* ..of a_tty_cell's (<= a_TTY_LINE_MAX) */
724 ui32_t tl_cursor; /* Current a_tty_cell insertion point */
725 union{
726 char *cbuf; /* *.tl_x_buf */
727 struct a_tty_cell *cells;
728 } tl_line;
729 struct str tl_defc; /* Current default content */
730 size_t tl_defc_cursor_byte; /* Desired position of cursor after takeover */
731 struct str tl_savec; /* Saved default content */
732 struct str tl_pastebuf; /* Last snarfed data */
733 # ifdef HAVE_HISTORY
734 struct a_tty_hist *tl_hist; /* History cursor */
735 # endif
736 ui32_t tl_count_max; /* ..before buffer needs to grow */
737 /* Visual data representation handling */
738 ui32_t tl_vi_flags; /* enum a_tty_visual_flags */
739 ui32_t tl_lst_count; /* .tl_count after last sync */
740 ui32_t tl_lst_cursor; /* .tl_cursor after last sync */
741 /* TODO Add another indirection layer by adding a tl_phy_line of
742 * TODO a_tty_cell objects, incorporate changes in visual layer,
743 * TODO then check what _really_ has changed, sync those changes only */
744 struct a_tty_cell const *tl_phy_start; /* First visible cell, left border */
745 ui32_t tl_phy_cursor; /* Physical cursor position */
746 bool_t tl_quote_rndtrip; /* For _kht() expansion */
747 ui8_t tl__dummy2[3];
748 ui32_t tl_prompt_length; /* Preclassified (TODO needed as a_tty_cell) */
749 ui32_t tl_prompt_width;
750 char const *tl_prompt; /* Preformatted prompt (including colours) */
751 /* .tl_pos_buf is a hack */
752 # ifdef HAVE_COLOUR
753 char *tl_pos_buf; /* mle-position colour-on, [4], reset seq. */
754 char *tl_pos; /* Address of the [4] */
755 # endif
758 # ifdef HAVE_KEY_BINDINGS
759 /* C99: use [INDEX]={} */
760 n_CTAV(n_LEXINPUT_CTX_BASE == 0);
761 n_CTAV(n_LEXINPUT_CTX_DEFAULT == 1);
762 n_CTAV(n_LEXINPUT_CTX_COMPOSE == 2);
763 static struct a_tty_bind_ctx_map const
764 a_tty_bind_ctx_maps[n__LEXINPUT_CTX_MAX1] = {
765 {n_LEXINPUT_CTX_BASE, "base"},
766 {n_LEXINPUT_CTX_DEFAULT, "default"},
767 {n_LEXINPUT_CTX_COMPOSE, "compose"}
770 /* Special functions which our MLE provides internally.
771 * Update the manual upon change! */
772 static char const a_tty_bind_fun_names[][24] = {
773 # undef a_X
774 # define a_X(I,N) \
775 n_FIELD_INITI(a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## I)) "mle-" N "\0",
777 a_X(BELL, "bell")
778 a_X(GO_BWD, "go-bwd") a_X(GO_FWD, "go-fwd")
779 a_X(GO_WORD_BWD, "go-word-bwd") a_X(GO_WORD_FWD, "go-word-fwd")
780 a_X(GO_HOME, "go-home") a_X(GO_END, "go-end")
781 a_X(DEL_BWD, "del-bwd") a_X(DEL_FWD, "del-fwd")
782 a_X(SNARF_WORD_BWD, "snarf-word-bwd") a_X(SNARF_WORD_FWD, "snarf-word-fwd")
783 a_X(SNARF_END, "snarf-end") a_X(SNARF_LINE, "snarf-line")
784 a_X(HIST_BWD, "hist-bwd") a_X(HIST_FWD, "hist-fwd")
785 a_X(HIST_SRCH_BWD, "hist-srch-bwd") a_X(HIST_SRCH_FWD, "hist-srch-fwd")
786 a_X(REPAINT, "repaint")
787 a_X(QUOTE_RNDTRIP, "quote-rndtrip")
788 a_X(PROMPT_CHAR, "prompt-char")
789 a_X(COMPLETE, "complete")
790 a_X(PASTE, "paste")
792 a_X(CANCEL, "cancel")
793 a_X(RESET, "reset")
794 a_X(FULLRESET, "fullreset")
795 a_X(COMMIT, "commit")
797 # undef a_X
799 # endif /* HAVE_KEY_BINDINGS */
801 /* The default key bindings (unless disallowed). Update manual upon change!
802 * A logical subset of this table is also used if !HAVE_KEY_BINDINGS (more
803 * expensive than a switch() on control codes directly, but less redundant).
804 * The table for the "base" context */
805 static struct a_tty_bind_builtin_tuple const a_tty_bind_base_tuples[] = {
806 # undef a_X
807 # define a_X(K,S) \
808 {TRU1, K, 0, {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
810 a_X('A', GO_HOME)
811 a_X('B', GO_BWD)
812 /* C: SIGINT */
813 a_X('D', DEL_FWD)
814 a_X('E', GO_END)
815 a_X('F', GO_FWD)
816 a_X('G', RESET)
817 a_X('H', DEL_BWD)
818 a_X('I', COMPLETE)
819 a_X('J', COMMIT)
820 a_X('K', SNARF_END)
821 a_X('L', REPAINT)
822 /* M: same as J */
823 a_X('N', HIST_FWD)
824 /* O: below */
825 a_X('P', HIST_BWD)
826 a_X('Q', QUOTE_RNDTRIP)
827 a_X('R', HIST_SRCH_BWD)
828 a_X('S', HIST_SRCH_FWD)
829 a_X('T', PASTE)
830 a_X('U', SNARF_LINE)
831 a_X('V', PROMPT_CHAR)
832 a_X('W', SNARF_WORD_BWD)
833 a_X('X', GO_WORD_FWD)
834 a_X('Y', GO_WORD_BWD)
835 /* Z: SIGTSTP */
837 a_X('[', CANCEL)
838 /* \: below */
839 /* ]: below */
840 /* ^: below */
841 a_X('_', SNARF_WORD_FWD)
843 a_X('?', DEL_BWD)
845 # undef a_X
846 # define a_X(K,S) {TRU1, K, 0, {S}},
848 /* The remains only if we have `bind' functionality available */
849 # ifdef HAVE_KEY_BINDINGS
850 # undef a_X
851 # define a_X(Q,S) \
852 {FAL0, '\0', n_TERMCAP_QUERY_ ## Q,\
853 {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
855 a_X(key_backspace, DEL_BWD) a_X(key_dc, DEL_FWD)
856 a_X(key_eol, SNARF_END)
857 a_X(key_home, GO_HOME) a_X(key_end, GO_END)
858 a_X(key_left, GO_BWD) a_X(key_right, GO_FWD)
859 a_X(key_sleft, GO_HOME) a_X(key_sright, GO_END)
860 a_X(key_up, HIST_BWD) a_X(key_down, HIST_FWD)
861 # endif /* HAVE_KEY_BINDINGS */
864 /* The table for the "default" context */
865 static struct a_tty_bind_builtin_tuple const a_tty_bind_default_tuples[] = {
866 # undef a_X
867 # define a_X(K,S) \
868 {TRU1, K, 0, {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
870 # undef a_X
871 # define a_X(K,S) {TRU1, K, 0, {S}},
873 a_X('O', "dt")
875 a_X('\\', "z+")
876 a_X(']', "z$")
877 a_X('^', "z0")
879 /* The remains only if we have `bind' functionality available */
880 # ifdef HAVE_KEY_BINDINGS
881 # undef a_X
882 # define a_X(Q,S) {FAL0, '\0', n_TERMCAP_QUERY_ ## Q, {S}},
884 a_X(key_shome, "z0") a_X(key_send, "z$")
885 a_X(xkey_sup, "z0") a_X(xkey_sdown, "z$")
886 a_X(key_ppage, "z-") a_X(key_npage, "z+")
887 a_X(xkey_cup, "dotmove-") a_X(xkey_cdown, "dotmove+")
888 # endif /* HAVE_KEY_BINDINGS */
890 # undef a_X
892 static struct a_tty_global a_tty;
894 /* Change from canonical to raw, non-canonical mode, and way back */
895 static void a_tty_term_mode(bool_t raw);
897 /* Adjust an active raw mode to use / not use a timeout */
898 # ifdef HAVE_KEY_BINDINGS
899 static void a_tty_term_rawmode_timeout(struct a_tty_line *tlp, bool_t enable);
900 # endif
902 /* 0-X (2), UI8_MAX == \t / TAB */
903 static ui8_t a_tty_wcwidth(wchar_t wc);
905 /* Memory / cell / word generics */
906 static void a_tty_check_grow(struct a_tty_line *tlp, ui32_t no
907 n_MEMORY_DEBUG_ARGS);
908 static ssize_t a_tty_cell2dat(struct a_tty_line *tlp);
909 static void a_tty_cell2save(struct a_tty_line *tlp);
911 /* Save away data bytes of given range (max = non-inclusive) */
912 static void a_tty_copy2paste(struct a_tty_line *tlp, struct a_tty_cell *tcpmin,
913 struct a_tty_cell *tcpmax);
915 /* Ask user for hexadecimal number, interpret as UTF-32 */
916 static wchar_t a_tty_vinuni(struct a_tty_line *tlp);
918 /* Visual screen synchronization */
919 static bool_t a_tty_vi_refresh(struct a_tty_line *tlp);
921 static bool_t a_tty_vi__paint(struct a_tty_line *tlp);
923 /* Search for word boundary, starting at tl_cursor, in "dir"ection (<> 0).
924 * Return <0 when moving is impossible (backward direction but in position 0,
925 * forward direction but in outermost column), and relative distance to
926 * tl_cursor otherwise */
927 static si32_t a_tty_wboundary(struct a_tty_line *tlp, si32_t dir);
929 /* Most function implementations */
930 static void a_tty_khome(struct a_tty_line *tlp, bool_t dobell);
931 static void a_tty_kend(struct a_tty_line *tlp);
932 static void a_tty_kbs(struct a_tty_line *tlp);
933 static void a_tty_ksnarf(struct a_tty_line *tlp, bool_t cplline, bool_t dobell);
934 static si32_t a_tty_kdel(struct a_tty_line *tlp);
935 static void a_tty_kleft(struct a_tty_line *tlp);
936 static void a_tty_kright(struct a_tty_line *tlp);
937 static void a_tty_ksnarfw(struct a_tty_line *tlp, bool_t fwd);
938 static void a_tty_kgow(struct a_tty_line *tlp, si32_t dir);
939 static bool_t a_tty_kother(struct a_tty_line *tlp, wchar_t wc);
940 static ui32_t a_tty_kht(struct a_tty_line *tlp);
942 # ifdef HAVE_HISTORY
943 /* Return UI32_MAX on "exhaustion" */
944 static ui32_t a_tty_khist(struct a_tty_line *tlp, bool_t fwd);
945 static ui32_t a_tty_khist_search(struct a_tty_line *tlp, bool_t fwd);
947 static ui32_t a_tty__khist_shared(struct a_tty_line *tlp,
948 struct a_tty_hist *thp);
949 # endif
951 /* Handle a function */
952 static enum a_tty_fun_status a_tty_fun(struct a_tty_line *tlp,
953 enum a_tty_bind_flags tbf, size_t *len);
955 /* Readline core */
956 static ssize_t a_tty_readline(struct a_tty_line *tlp, size_t len
957 n_MEMORY_DEBUG_ARGS);
959 # ifdef HAVE_KEY_BINDINGS
960 /* Find context or -1 */
961 static enum n_lexinput_flags a_tty_bind_ctx_find(char const *name);
963 /* Create (or replace, if allowed) a binding */
964 static bool_t a_tty_bind_create(struct a_tty_bind_parse_ctx *tbpcp,
965 bool_t replace);
967 /* Shared implementation to parse `bind' and `unbind' "key-sequence" and
968 * "expansion" command line arguments into something that we can work with */
969 static bool_t a_tty_bind_parse(bool_t isbindcmd,
970 struct a_tty_bind_parse_ctx *tbpcp);
972 /* Lazy resolve a termcap(5)/terminfo(5) (or *termcap*!) capability */
973 static void a_tty_bind_resolve(struct a_tty_bind_ctx *tbcp);
975 /* Delete an existing binding */
976 static void a_tty_bind_del(struct a_tty_bind_parse_ctx *tbpcp);
978 /* Life cycle of all input node trees */
979 static void a_tty_bind_tree_build(void);
980 static void a_tty_bind_tree_teardown(void);
982 static void a_tty__bind_tree_add(ui32_t hmap_idx,
983 struct a_tty_bind_tree *store[HSHSIZE],
984 struct a_tty_bind_ctx *tbcp);
985 static struct a_tty_bind_tree *a_tty__bind_tree_add_wc(
986 struct a_tty_bind_tree **treep, struct a_tty_bind_tree *parentp,
987 wchar_t wc, bool_t isseq);
988 static void a_tty__bind_tree_free(struct a_tty_bind_tree *tbtp);
989 # endif /* HAVE_KEY_BINDINGS */
991 static void
992 a_tty_term_mode(bool_t raw){
993 struct termios *tiosp;
994 NYD2_ENTER;
996 tiosp = &a_tty.tg_tios_old;
997 if(!raw)
998 goto jleave;
1000 /* Always requery the attributes, in case we've been moved from background
1001 * to foreground or however else in between sessions */
1002 /* XXX Always enforce ECHO and ICANON in the OLD attributes - do so as long
1003 * XXX as we don't properly deal with TTIN and TTOU etc. */
1004 tcgetattr(STDIN_FILENO, tiosp); /* TODO v15: use _only_ n_tty_fp! */
1005 tiosp->c_lflag |= ECHO | ICANON;
1007 memcpy(&a_tty.tg_tios_new, tiosp, sizeof *tiosp);
1008 tiosp = &a_tty.tg_tios_new;
1009 tiosp->c_cc[VMIN] = 1;
1010 tiosp->c_cc[VTIME] = 0;
1011 /* Enable ^\, ^Q and ^S to be used for key bindings */
1012 tiosp->c_cc[VQUIT] = tiosp->c_cc[VSTART] = tiosp->c_cc[VSTOP] = '\0';
1013 tiosp->c_iflag &= ~(ISTRIP | IGNCR);
1014 tiosp->c_lflag &= ~(ECHO /*| ECHOE | ECHONL */| ICANON | IEXTEN);
1015 jleave:
1016 tcsetattr(STDIN_FILENO, TCSADRAIN, tiosp);
1017 NYD2_LEAVE;
1020 # ifdef HAVE_KEY_BINDINGS
1021 static void
1022 a_tty_term_rawmode_timeout(struct a_tty_line *tlp, bool_t enable){
1023 NYD2_ENTER;
1024 if(enable){
1025 ui8_t bt;
1027 a_tty.tg_tios_new.c_cc[VMIN] = 0;
1028 if((bt = tlp->tl_bind_timeout) == 0)
1029 bt = a_TTY_BIND_TIMEOUT;
1030 a_tty.tg_tios_new.c_cc[VTIME] = bt;
1031 }else{
1032 a_tty.tg_tios_new.c_cc[VMIN] = 1;
1033 a_tty.tg_tios_new.c_cc[VTIME] = 0;
1035 tcsetattr(STDIN_FILENO, TCSANOW, &a_tty.tg_tios_new);
1036 NYD2_LEAVE;
1038 # endif /* HAVE_KEY_BINDINGS */
1040 static ui8_t
1041 a_tty_wcwidth(wchar_t wc){
1042 ui8_t rv;
1043 NYD2_ENTER;
1045 /* Special case the backslash at first */
1046 if(wc == '\t')
1047 rv = UI8_MAX;
1048 else{
1049 int i;
1051 # ifdef HAVE_WCWIDTH
1052 rv = ((i = wcwidth(wc)) > 0) ? (ui8_t)i : 0;
1053 # else
1054 rv = iswprint(wc) ? 1 + (wc >= 0x1100u) : 0; /* TODO use S-CText */
1055 # endif
1057 NYD2_LEAVE;
1058 return rv;
1061 static void
1062 a_tty_check_grow(struct a_tty_line *tlp, ui32_t no n_MEMORY_DEBUG_ARGS){
1063 ui32_t cmax;
1064 NYD2_ENTER;
1066 if(n_UNLIKELY((cmax = tlp->tl_count + no) > tlp->tl_count_max)){
1067 size_t i;
1069 i = cmax * sizeof(struct a_tty_cell) + 2 * sizeof(struct a_tty_cell);
1070 if(n_LIKELY(i >= *tlp->tl_x_bufsize)){
1071 hold_all_sigs(); /* XXX v15 drop */
1072 i <<= 1;
1073 tlp->tl_line.cbuf =
1074 *tlp->tl_x_buf = (n_realloc)(*tlp->tl_x_buf, i
1075 n_MEMORY_DEBUG_ARGSCALL);
1076 rele_all_sigs(); /* XXX v15 drop */
1078 tlp->tl_count_max = cmax;
1079 *tlp->tl_x_bufsize = i;
1081 NYD2_LEAVE;
1084 static ssize_t
1085 a_tty_cell2dat(struct a_tty_line *tlp){
1086 size_t len, i;
1087 NYD2_ENTER;
1089 len = 0;
1091 if(n_LIKELY((i = tlp->tl_count) > 0)){
1092 struct a_tty_cell const *tcap;
1094 tcap = tlp->tl_line.cells;
1096 memcpy(tlp->tl_line.cbuf + len, tcap->tc_cbuf, tcap->tc_count);
1097 len += tcap->tc_count;
1098 }while(++tcap, --i > 0);
1101 tlp->tl_line.cbuf[len] = '\0';
1102 NYD2_LEAVE;
1103 return (ssize_t)len;
1106 static void
1107 a_tty_cell2save(struct a_tty_line *tlp){
1108 size_t len, i;
1109 struct a_tty_cell *tcap;
1110 NYD2_ENTER;
1112 tlp->tl_savec.s = NULL;
1113 tlp->tl_savec.l = 0;
1115 if(n_UNLIKELY(tlp->tl_count == 0))
1116 goto jleave;
1118 for(tcap = tlp->tl_line.cells, len = 0, i = tlp->tl_count; i > 0;
1119 ++tcap, --i)
1120 len += tcap->tc_count;
1122 tlp->tl_savec.s = salloc((tlp->tl_savec.l = len) +1);
1124 for(tcap = tlp->tl_line.cells, len = 0, i = tlp->tl_count; i > 0;
1125 ++tcap, --i){
1126 memcpy(tlp->tl_savec.s + len, tcap->tc_cbuf, tcap->tc_count);
1127 len += tcap->tc_count;
1129 tlp->tl_savec.s[len] = '\0';
1130 jleave:
1131 NYD2_LEAVE;
1134 static void
1135 a_tty_copy2paste(struct a_tty_line *tlp, struct a_tty_cell *tcpmin,
1136 struct a_tty_cell *tcpmax){
1137 char *cp;
1138 struct a_tty_cell *tcp;
1139 size_t l;
1140 NYD2_ENTER;
1142 l = 0;
1143 for(tcp = tcpmin; tcp < tcpmax; ++tcp)
1144 l += tcp->tc_count;
1146 tlp->tl_pastebuf.s = cp = salloc((tlp->tl_pastebuf.l = l) +1);
1148 l = 0;
1149 for(tcp = tcpmin; tcp < tcpmax; cp += l, ++tcp)
1150 memcpy(cp, tcp->tc_cbuf, l = tcp->tc_count);
1151 *cp = '\0';
1152 NYD2_LEAVE;
1155 static wchar_t
1156 a_tty_vinuni(struct a_tty_line *tlp){
1157 char buf[16], *eptr;
1158 union {size_t i; long l;} u;
1159 wchar_t wc;
1160 NYD2_ENTER;
1162 wc = '\0';
1164 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr) ||
1165 !n_termcap_cmd(n_TERMCAP_CMD_ce, 0, -1))
1166 goto jleave;
1168 /* C99 */{
1169 struct str const *cpre, *csuf;
1170 #ifdef HAVE_COLOUR
1171 struct n_colour_pen *cpen;
1173 cpen = n_colour_pen_create(n_COLOUR_ID_MLE_PROMPT, NULL);
1174 if((cpre = n_colour_pen_to_str(cpen)) != NULL)
1175 csuf = n_colour_reset_to_str();
1176 else
1177 csuf = NULL;
1178 #else
1179 cpre = csuf = NULL;
1180 #endif
1181 fprintf(n_tty_fp, _("%sPlease enter Unicode code point:%s "),
1182 (cpre != NULL ? cpre->s : n_empty),
1183 (csuf != NULL ? csuf->s : n_empty));
1185 fflush(n_tty_fp);
1187 buf[sizeof(buf) -1] = '\0';
1188 for(u.i = 0;;){
1189 if(read(STDIN_FILENO, &buf[u.i], 1) != 1){
1190 if(errno == EINTR) /* xxx #if !SA_RESTART ? */
1191 continue;
1192 goto jleave;
1194 if(buf[u.i] == '\n')
1195 break;
1196 if(!hexchar(buf[u.i])){
1197 char const emsg[] = "[0-9a-fA-F]";
1199 n_LCTA(sizeof emsg <= sizeof(buf), "Preallocated buffer too small");
1200 memcpy(buf, emsg, sizeof emsg);
1201 goto jerr;
1204 putc(buf[u.i], n_tty_fp);
1205 fflush(n_tty_fp);
1206 if(++u.i == sizeof buf)
1207 goto jerr;
1209 buf[u.i] = '\0';
1211 u.l = strtol(buf, &eptr, 16);
1212 if(u.l <= 0 || u.l >= 0x10FFFF/* XXX magic; CText */ || *eptr != '\0'){
1213 jerr:
1214 n_err(_("\nInvalid input: %s\n"), buf);
1215 goto jleave;
1218 wc = (wchar_t)u.l;
1219 jleave:
1220 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY | (wc == '\0' ? a_TTY_VF_BELL : 0);
1221 NYD2_LEAVE;
1222 return wc;
1225 static bool_t
1226 a_tty_vi_refresh(struct a_tty_line *tlp){
1227 bool_t rv;
1228 NYD2_ENTER;
1230 if(tlp->tl_vi_flags & a_TTY_VF_BELL){
1231 tlp->tl_vi_flags |= a_TTY_VF_SYNC;
1232 if(putc('\a', n_tty_fp) == EOF)
1233 goto jerr;
1236 if(tlp->tl_vi_flags & a_TTY_VF_REFRESH){
1237 /* kht may want to restore a cursor position after inserting some
1238 * data somewhere */
1239 if(tlp->tl_defc_cursor_byte > 0){
1240 size_t i, j;
1241 ssize_t k;
1243 a_tty_khome(tlp, FAL0);
1245 i = tlp->tl_defc_cursor_byte;
1246 tlp->tl_defc_cursor_byte = 0;
1247 for(j = 0; tlp->tl_cursor < tlp->tl_count; ++j){
1248 a_tty_kright(tlp);
1249 if((k = tlp->tl_line.cells[j].tc_count) > i)
1250 break;
1251 i -= k;
1255 if(!a_tty_vi__paint(tlp))
1256 goto jerr;
1259 if(tlp->tl_vi_flags & a_TTY_VF_SYNC){
1260 tlp->tl_vi_flags &= ~a_TTY_VF_SYNC;
1261 if(fflush(n_tty_fp))
1262 goto jerr;
1265 rv = TRU1;
1266 jleave:
1267 tlp->tl_vi_flags &= ~a_TTY_VF_ALL_MASK;
1268 NYD2_LEAVE;
1269 return rv;
1271 jerr:
1272 clearerr(n_tty_fp); /* xxx I/O layer rewrite */
1273 n_err(_("Visual refresh failed! Is $TERM set correctly?\n"
1274 " Setting *line-editor-disable* to get us through!\n"));
1275 ok_bset(line_editor_disable);
1276 rv = FAL0;
1277 goto jleave;
1280 static bool_t
1281 a_tty_vi__paint(struct a_tty_line *tlp){
1282 enum{
1283 a_TRUE_RV = a_TTY__VF_LAST<<1, /* Return value bit */
1284 a_HAVE_PROMPT = a_TTY__VF_LAST<<2, /* Have a prompt */
1285 a_SHOW_PROMPT = a_TTY__VF_LAST<<3, /* Shall print the prompt */
1286 a_MOVE_CURSOR = a_TTY__VF_LAST<<4, /* Move visual cursor for user! */
1287 a_LEFT_MIN = a_TTY__VF_LAST<<5, /* On left boundary */
1288 a_RIGHT_MAX = a_TTY__VF_LAST<<6,
1289 a_HAVE_POSITION = a_TTY__VF_LAST<<7, /* Print the position indicator */
1291 /* We carry some flags over invocations (not worth a specific field) */
1292 a_VISIBLE_PROMPT = a_TTY__VF_LAST<<8, /* The prompt is on the screen */
1293 a_PERSIST_MASK = a_VISIBLE_PROMPT,
1294 a__LAST = a_PERSIST_MASK
1297 ui32_t f, w, phy_wid_base, phy_wid, phy_base, phy_cur, cnt, lstcur, cur,
1298 vi_left, vi_right, phy_nxtcur;
1299 struct a_tty_cell const *tccp, *tcp_left, *tcp_right, *tcxp;
1300 NYD2_ENTER;
1301 n_LCTA(UICMP(64, a__LAST, <, UI32_MAX), "Flag bits excess storage datatype");
1303 f = tlp->tl_vi_flags;
1304 tlp->tl_vi_flags = (f & ~(a_TTY_VF_REFRESH | a_PERSIST_MASK)) |
1305 a_TTY_VF_SYNC;
1306 f |= a_TRUE_RV;
1307 if((w = tlp->tl_prompt_width) > 0)
1308 f |= a_HAVE_PROMPT;
1309 f |= a_HAVE_POSITION;
1311 /* XXX We don't have a OnTerminalResize event (see main.c) yet, so we need
1312 * XXX to reevaluate our circumstances over and over again */
1313 /* Don't display prompt or position indicator on very small screens */
1314 if((phy_wid_base = (ui32_t)scrnwidth) <= a_TTY_WIDTH_RIPOFF)
1315 f &= ~(a_HAVE_PROMPT | a_HAVE_POSITION);
1316 else{
1317 phy_wid_base -= a_TTY_WIDTH_RIPOFF;
1319 /* Disable the prompt if the screen is too small; due to lack of some
1320 * indicator simply add a second ripoff */
1321 if((f & a_HAVE_PROMPT) && w + a_TTY_WIDTH_RIPOFF >= phy_wid_base)
1322 f &= ~a_HAVE_PROMPT;
1325 phy_wid = phy_wid_base;
1326 phy_base = 0;
1327 phy_cur = tlp->tl_phy_cursor;
1328 cnt = tlp->tl_count;
1329 lstcur = tlp->tl_lst_cursor;
1331 /* XXX Assume dirty screen if shrunk */
1332 if(cnt < tlp->tl_lst_count)
1333 f |= a_TTY_VF_MOD_DIRTY;
1335 /* TODO Without HAVE_TERMCAP, it would likely be much cheaper to simply
1336 * TODO always "cr + paint + ce + ch", since ce is simulated via spaces.. */
1338 /* Quickshot: if the line is empty, possibly print prompt and out */
1339 if(cnt == 0){
1340 /* In that special case dirty anything if it seems better */
1341 if((f & a_TTY_VF_MOD_CONTENT) || tlp->tl_lst_count > 0)
1342 f |= a_TTY_VF_MOD_DIRTY;
1344 if((f & a_TTY_VF_MOD_DIRTY) && phy_cur != 0){
1345 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
1346 goto jerr;
1347 phy_cur = 0;
1350 if((f & (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)) ==
1351 (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)){
1352 if(fputs(tlp->tl_prompt, n_tty_fp) == EOF)
1353 goto jerr;
1354 phy_cur = tlp->tl_prompt_width + 1;
1357 /* May need to clear former line content */
1358 if((f & a_TTY_VF_MOD_DIRTY) &&
1359 !n_termcap_cmd(n_TERMCAP_CMD_ce, phy_cur, -1))
1360 goto jerr;
1362 tlp->tl_phy_start = tlp->tl_line.cells;
1363 goto jleave;
1366 /* Try to get an idea of the visual window */
1368 /* Find the left visual boundary */
1369 phy_wid = (phy_wid >> 1) + (phy_wid >> 2);
1370 if((cur = tlp->tl_cursor) == cnt)
1371 --cur;
1373 w = (tcp_left = tccp = tlp->tl_line.cells + cur)->tc_width;
1374 if(w == UI8_MAX) /* TODO yet TAB == SPC */
1375 w = 1;
1376 while(tcp_left > tlp->tl_line.cells){
1377 ui16_t cw = tcp_left[-1].tc_width;
1379 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1380 cw = 1;
1381 if(w + cw >= phy_wid)
1382 break;
1383 w += cw;
1384 --tcp_left;
1386 vi_left = w;
1388 /* If the left hand side of our visual viewpoint consumes less than half
1389 * of the screen width, show the prompt */
1390 if(tcp_left == tlp->tl_line.cells)
1391 f |= a_LEFT_MIN;
1393 if((f & (a_LEFT_MIN | a_HAVE_PROMPT)) == (a_LEFT_MIN | a_HAVE_PROMPT) &&
1394 w + tlp->tl_prompt_width < phy_wid){
1395 phy_base = tlp->tl_prompt_width;
1396 f |= a_SHOW_PROMPT;
1399 /* Then search for right boundary. We always leave the rightmost column
1400 * empty because some terminals [cw]ould wrap the line if we write into
1401 * that. XXX terminfo(5)/termcap(5) have the semi_auto_right_margin/sam/YE
1402 * XXX capability to indicate this, but we don't look at that */
1403 phy_wid = phy_wid_base - phy_base;
1404 tcp_right = tlp->tl_line.cells + cnt;
1406 while(&tccp[1] < tcp_right){
1407 ui16_t cw = tccp[1].tc_width;
1408 ui32_t i;
1410 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1411 cw = 1;
1412 i = w + cw;
1413 if(i > phy_wid)
1414 break;
1415 w = i;
1416 ++tccp;
1418 vi_right = w - vi_left;
1420 /* If the complete line including prompt fits on the screen, show prompt */
1421 if(--tcp_right == tccp){
1422 f |= a_RIGHT_MAX;
1424 /* Since we did brute-force walk also for the left boundary we may end up
1425 * in a situation were anything effectively fits on the screen, including
1426 * the prompt that is, but were we don't recognize this since we
1427 * restricted the search to fit in some visual viewpoint. Therefore try
1428 * again to extend the left boundary to overcome that */
1429 if(!(f & a_LEFT_MIN)){
1430 struct a_tty_cell const *tc1p = tlp->tl_line.cells;
1431 ui32_t vil1 = vi_left;
1433 assert(!(f & a_SHOW_PROMPT));
1434 w += tlp->tl_prompt_width;
1435 for(tcxp = tcp_left;;){
1436 ui32_t i = tcxp[-1].tc_width;
1438 if(i == UI8_MAX) /* TODO yet TAB == SPC */
1439 i = 1;
1440 vil1 += i;
1441 i += w;
1442 if(i > phy_wid)
1443 break;
1444 w = i;
1445 if(--tcxp == tc1p){
1446 tcp_left = tc1p;
1447 vi_left = vil1;
1448 f |= a_LEFT_MIN;
1449 break;
1452 /*w -= tlp->tl_prompt_width;*/
1455 tcp_right = tccp;
1456 tccp = tlp->tl_line.cells + cur;
1458 if((f & (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT | a_SHOW_PROMPT)) ==
1459 (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT) &&
1460 w + tlp->tl_prompt_width <= phy_wid){
1461 phy_wid -= (phy_base = tlp->tl_prompt_width);
1462 f |= a_SHOW_PROMPT;
1465 /* Try to avoid repainting the complete line - this is possible if the
1466 * cursor "did not leave the screen" and the prompt status hasn't changed.
1467 * I.e., after clamping virtual viewpoint, compare relation to physical */
1468 if((f & (a_TTY_VF_MOD_SINGLE/*FIXME*/ |
1469 a_TTY_VF_MOD_CONTENT/* xxx */ | a_TTY_VF_MOD_DIRTY)) ||
1470 (tcxp = tlp->tl_phy_start) == NULL ||
1471 tcxp > tccp || tcxp <= tcp_right)
1472 f |= a_TTY_VF_MOD_DIRTY;
1473 else{
1474 f |= a_TTY_VF_MOD_DIRTY;
1475 #if 0
1476 struct a_tty_cell const *tcyp;
1477 si32_t cur_displace;
1478 ui32_t phy_lmargin, phy_rmargin, fx, phy_displace;
1480 phy_lmargin = (fx = phy_wid) / 100;
1481 phy_rmargin = fx - (phy_lmargin * a_TTY_SCROLL_MARGIN_RIGHT);
1482 phy_lmargin *= a_TTY_SCROLL_MARGIN_LEFT;
1483 fx = (f & (a_SHOW_PROMPT | a_VISIBLE_PROMPT));
1485 if(fx == 0 || fx == (a_SHOW_PROMPT | a_VISIBLE_PROMPT)){
1487 #endif
1489 goto jpaint;
1491 /* We know what we have to paint, start synchronizing */
1492 jpaint:
1493 assert(phy_cur == tlp->tl_phy_cursor);
1494 assert(phy_wid == phy_wid_base - phy_base);
1495 assert(cnt == tlp->tl_count);
1496 assert(cnt > 0);
1497 assert(lstcur == tlp->tl_lst_cursor);
1498 assert(tccp == tlp->tl_line.cells + cur);
1500 phy_nxtcur = phy_base; /* FIXME only if repaint cpl. */
1502 /* Quickshot: is it only cursor movement within the visible screen? */
1503 if((f & a_TTY_VF_REFRESH) == a_TTY_VF_MOD_CURSOR){
1504 f |= a_MOVE_CURSOR;
1505 goto jcursor;
1508 /* To be able to apply some quick jump offs, clear line if possible */
1509 if(f & a_TTY_VF_MOD_DIRTY){
1510 /* Force complete clearance and cursor reinitialization */
1511 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr) ||
1512 !n_termcap_cmd(n_TERMCAP_CMD_ce, 0, -1))
1513 goto jerr;
1514 tlp->tl_phy_start = tcp_left;
1515 phy_cur = 0;
1518 if((f & (a_TTY_VF_MOD_DIRTY | a_SHOW_PROMPT)) && phy_cur != 0){
1519 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
1520 goto jerr;
1521 phy_cur = 0;
1524 if(f & a_SHOW_PROMPT){
1525 assert(phy_base == tlp->tl_prompt_width);
1526 if(fputs(tlp->tl_prompt, n_tty_fp) == EOF)
1527 goto jerr;
1528 phy_cur = phy_nxtcur;
1529 f |= a_VISIBLE_PROMPT;
1530 }else
1531 f &= ~a_VISIBLE_PROMPT;
1533 /* FIXME reposition cursor for paint */
1534 for(w = phy_nxtcur; tcp_left <= tcp_right; ++tcp_left){
1535 ui16_t cw;
1537 cw = tcp_left->tc_width;
1539 if(n_LIKELY(!tcp_left->tc_novis)){
1540 if(fwrite(tcp_left->tc_cbuf, sizeof *tcp_left->tc_cbuf,
1541 tcp_left->tc_count, n_tty_fp) != tcp_left->tc_count)
1542 goto jerr;
1543 }else{ /* XXX Shouldn't be here <-> CText, ui_str.c */
1544 char wbuf[8]; /* XXX magic */
1546 if(options & OPT_UNICODE){
1547 ui32_t wc;
1549 wc = (ui32_t)tcp_left->tc_wc;
1550 if((wc & ~0x1Fu) == 0)
1551 wc |= 0x2400;
1552 else if(wc == 0x7F)
1553 wc = 0x2421;
1554 else
1555 wc = 0x2426;
1556 n_utf32_to_utf8(wc, wbuf);
1557 }else
1558 wbuf[0] = '?', wbuf[1] = '\0';
1560 if(fputs(wbuf, n_tty_fp) == EOF)
1561 goto jerr;
1562 cw = 1;
1565 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1566 cw = 1;
1567 w += cw;
1568 if(tcp_left == tccp)
1569 phy_nxtcur = w;
1570 phy_cur += cw;
1573 /* Write something position marker alike if it doesn't fit on screen */
1574 if((f & a_HAVE_POSITION) &&
1575 ((f & (a_LEFT_MIN | a_RIGHT_MAX)) != (a_LEFT_MIN | a_RIGHT_MAX) ||
1576 ((f & a_HAVE_PROMPT) && !(f & a_SHOW_PROMPT)))){
1577 # ifdef HAVE_COLOUR
1578 char *posbuf = tlp->tl_pos_buf, *pos = tlp->tl_pos;
1579 # else
1580 char posbuf[5], *pos = posbuf;
1582 pos[4] = '\0';
1583 # endif
1585 if(phy_cur != (w = phy_wid_base) &&
1586 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = w, 0))
1587 goto jerr;
1589 *pos++ = '|';
1590 if((f & a_LEFT_MIN) && (!(f & a_HAVE_PROMPT) || (f & a_SHOW_PROMPT)))
1591 memcpy(pos, "^.+", 3);
1592 else if(f & a_RIGHT_MAX)
1593 memcpy(pos, ".+$", 3);
1594 else{
1595 /* Theoretical line length limit a_TTY_LINE_MAX, choose next power of
1596 * ten (10 ** 10) to represent 100 percent, since we don't have a macro
1597 * that generates a constant, and i don't trust the standard "u type
1598 * suffix automatically scales" calculate the large number */
1599 static char const itoa[] = "0123456789";
1601 ui64_t const fact100 = (ui64_t)0x3B9ACA00u * 10u, fact = fact100 / 100;
1602 ui32_t i = (ui32_t)(((fact100 / cnt) * tlp->tl_cursor) / fact);
1603 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1605 if(i < 10)
1606 pos[0] = ' ', pos[1] = itoa[i];
1607 else
1608 pos[1] = itoa[i % 10], pos[0] = itoa[i / 10];
1609 pos[2] = '%';
1612 if(fputs(posbuf, n_tty_fp) == EOF)
1613 goto jerr;
1614 phy_cur += 4;
1617 /* Users are used to see the cursor right of the point of interest, so we
1618 * need some further adjustments unless in special conditions. Be aware
1619 * that we may have adjusted cur at the beginning, too */
1620 if((cur = tlp->tl_cursor) == 0)
1621 phy_nxtcur = phy_base;
1622 else if(cur != cnt){
1623 ui16_t cw = tccp->tc_width;
1625 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1626 cw = 1;
1627 phy_nxtcur -= cw;
1630 jcursor:
1631 if(((f & a_MOVE_CURSOR) || phy_nxtcur != phy_cur) &&
1632 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = phy_nxtcur, 0))
1633 goto jerr;
1635 jleave:
1636 tlp->tl_vi_flags |= (f & a_PERSIST_MASK);
1637 tlp->tl_lst_count = tlp->tl_count;
1638 tlp->tl_lst_cursor = tlp->tl_cursor;
1639 tlp->tl_phy_cursor = phy_cur;
1641 NYD2_LEAVE;
1642 return ((f & a_TRUE_RV) != 0);
1643 jerr:
1644 f &= ~a_TRUE_RV;
1645 goto jleave;
1648 static si32_t
1649 a_tty_wboundary(struct a_tty_line *tlp, si32_t dir){/* TODO shell token-wise */
1650 bool_t anynon;
1651 struct a_tty_cell *tcap;
1652 ui32_t cur, cnt;
1653 si32_t rv;
1654 NYD2_ENTER;
1656 assert(dir == 1 || dir == -1);
1658 rv = -1;
1659 cnt = tlp->tl_count;
1660 cur = tlp->tl_cursor;
1662 if(dir < 0){
1663 if(cur == 0)
1664 goto jleave;
1665 }else if(cur + 1 >= cnt)
1666 goto jleave;
1667 else
1668 --cnt, --cur; /* xxx Unsigned wrapping may occur (twice), then */
1670 for(rv = 0, tcap = tlp->tl_line.cells, anynon = FAL0;;){
1671 wchar_t wc;
1673 wc = tcap[cur += (ui32_t)dir].tc_wc;
1674 if(iswblank(wc) || iswpunct(wc)){
1675 if(anynon)
1676 break;
1677 }else
1678 anynon = TRU1;
1680 ++rv;
1682 if(dir < 0){
1683 if(cur == 0)
1684 break;
1685 }else if(cur + 1 >= cnt){
1686 ++rv;
1687 break;
1690 jleave:
1691 NYD2_LEAVE;
1692 return rv;
1695 static void
1696 a_tty_khome(struct a_tty_line *tlp, bool_t dobell){
1697 ui32_t f;
1698 NYD2_ENTER;
1700 if(n_LIKELY(tlp->tl_cursor > 0)){
1701 tlp->tl_cursor = 0;
1702 f = a_TTY_VF_MOD_CURSOR;
1703 }else if(dobell)
1704 f = a_TTY_VF_BELL;
1705 else
1706 f = a_TTY_VF_NONE;
1708 tlp->tl_vi_flags |= f;
1709 NYD2_LEAVE;
1712 static void
1713 a_tty_kend(struct a_tty_line *tlp){
1714 ui32_t f;
1715 NYD2_ENTER;
1717 if(n_LIKELY(tlp->tl_cursor < tlp->tl_count)){
1718 tlp->tl_cursor = tlp->tl_count;
1719 f = a_TTY_VF_MOD_CURSOR;
1720 }else
1721 f = a_TTY_VF_BELL;
1723 tlp->tl_vi_flags |= f;
1724 NYD2_LEAVE;
1727 static void
1728 a_tty_kbs(struct a_tty_line *tlp){
1729 ui32_t f, cur, cnt;
1730 NYD2_ENTER;
1732 cur = tlp->tl_cursor;
1733 cnt = tlp->tl_count;
1735 if(n_LIKELY(cur > 0)){
1736 tlp->tl_cursor = --cur;
1737 tlp->tl_count = --cnt;
1739 if((cnt -= cur) > 0){
1740 struct a_tty_cell *tcap;
1742 tcap = tlp->tl_line.cells + cur;
1743 memmove(tcap, &tcap[1], cnt *= sizeof(*tcap));
1745 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
1746 }else
1747 f = a_TTY_VF_BELL;
1749 tlp->tl_vi_flags |= f;
1750 NYD2_LEAVE;
1753 static void
1754 a_tty_ksnarf(struct a_tty_line *tlp, bool_t cplline, bool_t dobell){
1755 ui32_t i, f;
1756 NYD2_ENTER;
1758 f = a_TTY_VF_NONE;
1759 i = tlp->tl_cursor;
1761 if(cplline && i > 0){
1762 tlp->tl_cursor = i = 0;
1763 f = a_TTY_VF_MOD_CURSOR;
1766 if(n_LIKELY(i < tlp->tl_count)){
1767 struct a_tty_cell *tcap;
1769 tcap = &tlp->tl_line.cells[0];
1770 a_tty_copy2paste(tlp, &tcap[i], &tcap[tlp->tl_count]);
1771 tlp->tl_count = i;
1772 f = a_TTY_VF_MOD_CONTENT;
1773 }else if(dobell)
1774 f |= a_TTY_VF_BELL;
1776 tlp->tl_vi_flags |= f;
1777 NYD2_LEAVE;
1780 static si32_t
1781 a_tty_kdel(struct a_tty_line *tlp){
1782 ui32_t cur, cnt, f;
1783 si32_t i;
1784 NYD2_ENTER;
1786 cur = tlp->tl_cursor;
1787 cnt = tlp->tl_count;
1788 i = (si32_t)(cnt - cur);
1790 if(n_LIKELY(i > 0)){
1791 tlp->tl_count = --cnt;
1793 if(n_LIKELY(--i > 0)){
1794 struct a_tty_cell *tcap;
1796 tcap = &tlp->tl_line.cells[cur];
1797 memmove(tcap, &tcap[1], (ui32_t)i * sizeof(*tcap));
1799 f = a_TTY_VF_MOD_CONTENT;
1800 }else if(cnt == 0 && !ok_blook(ignoreeof)){
1801 putc('^', n_tty_fp);
1802 putc('D', n_tty_fp);
1803 i = -1;
1804 f = a_TTY_VF_NONE;
1805 }else{
1806 i = 0;
1807 f = a_TTY_VF_BELL;
1810 tlp->tl_vi_flags |= f;
1811 NYD2_LEAVE;
1812 return i;
1815 static void
1816 a_tty_kleft(struct a_tty_line *tlp){
1817 ui32_t f;
1818 NYD2_ENTER;
1820 if(n_LIKELY(tlp->tl_cursor > 0)){
1821 --tlp->tl_cursor;
1822 f = a_TTY_VF_MOD_CURSOR;
1823 }else
1824 f = a_TTY_VF_BELL;
1826 tlp->tl_vi_flags |= f;
1827 NYD2_LEAVE;
1830 static void
1831 a_tty_kright(struct a_tty_line *tlp){
1832 ui32_t i;
1833 NYD2_ENTER;
1835 if(n_LIKELY((i = tlp->tl_cursor + 1) <= tlp->tl_count)){
1836 tlp->tl_cursor = i;
1837 i = a_TTY_VF_MOD_CURSOR;
1838 }else
1839 i = a_TTY_VF_BELL;
1841 tlp->tl_vi_flags |= i;
1842 NYD2_LEAVE;
1845 static void
1846 a_tty_ksnarfw(struct a_tty_line *tlp, bool_t fwd){
1847 struct a_tty_cell *tcap;
1848 ui32_t cnt, cur, f;
1849 si32_t i;
1850 NYD2_ENTER;
1852 if(n_UNLIKELY((i = a_tty_wboundary(tlp, (fwd ? +1 : -1))) <= 0)){
1853 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
1854 goto jleave;
1857 cnt = tlp->tl_count - (ui32_t)i;
1858 cur = tlp->tl_cursor;
1859 if(!fwd)
1860 cur -= (ui32_t)i;
1861 tcap = &tlp->tl_line.cells[cur];
1863 a_tty_copy2paste(tlp, &tcap[0], &tcap[i]);
1865 if((tlp->tl_count = cnt) != (tlp->tl_cursor = cur)){
1866 cnt -= cur;
1867 memmove(&tcap[0], &tcap[i], cnt * sizeof(*tcap)); /* FIXME*/
1870 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
1871 jleave:
1872 tlp->tl_vi_flags |= f;
1873 NYD2_LEAVE;
1876 static void
1877 a_tty_kgow(struct a_tty_line *tlp, si32_t dir){
1878 ui32_t f;
1879 si32_t i;
1880 NYD2_ENTER;
1882 if(n_UNLIKELY((i = a_tty_wboundary(tlp, dir)) <= 0))
1883 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
1884 else{
1885 if(dir < 0)
1886 i = -i;
1887 tlp->tl_cursor += (ui32_t)i;
1888 f = a_TTY_VF_MOD_CURSOR;
1891 tlp->tl_vi_flags |= f;
1892 NYD2_LEAVE;
1895 static bool_t
1896 a_tty_kother(struct a_tty_line *tlp, wchar_t wc){
1897 /* Append if at EOL, insert otherwise;
1898 * since we may move around character-wise, always use a fresh ps */
1899 mbstate_t ps;
1900 struct a_tty_cell tc, *tcap;
1901 ui32_t f, cur, cnt;
1902 bool_t rv;
1903 NYD2_ENTER;
1905 rv = FAL0;
1906 f = a_TTY_VF_NONE;
1908 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1909 if(tlp->tl_count + 1 >= a_TTY_LINE_MAX){
1910 n_err(_("Stop here, we can't extend line beyond size limit\n"));
1911 goto jleave;
1914 /* First init a cell and see whether we'll really handle this wc */
1915 memset(&ps, 0, sizeof ps);
1916 /* C99 */{
1917 size_t l;
1919 l = wcrtomb(tc.tc_cbuf, tc.tc_wc = wc, &ps);
1920 if(n_UNLIKELY(l > MB_LEN_MAX)){
1921 jemb:
1922 n_err(_("wcrtomb(3) error: too many multibyte character bytes\n"));
1923 goto jleave;
1925 tc.tc_count = (ui16_t)l;
1927 if(n_UNLIKELY((options & OPT_ENC_MBSTATE) != 0)){
1928 l = wcrtomb(&tc.tc_cbuf[l], L'\0', &ps);
1929 if(n_LIKELY(l == 1))
1930 /* Only NUL terminator */;
1931 else if(n_LIKELY(--l < MB_LEN_MAX))
1932 tc.tc_count += (ui16_t)l;
1933 else
1934 goto jemb;
1938 /* Yes, we will! Place it in the array */
1939 tc.tc_novis = (iswprint(wc) == 0);
1940 tc.tc_width = a_tty_wcwidth(wc);
1941 /* TODO if(tc.tc_novis && tc.tc_width > 0) */
1943 cur = tlp->tl_cursor++;
1944 cnt = tlp->tl_count++ - cur;
1945 tcap = &tlp->tl_line.cells[cur];
1946 if(cnt >= 1){
1947 memmove(&tcap[1], tcap, cnt * sizeof(*tcap));
1948 f = a_TTY_VF_MOD_CONTENT;
1949 }else
1950 f = a_TTY_VF_MOD_SINGLE;
1951 memcpy(tcap, &tc, sizeof *tcap);
1953 f |= a_TTY_VF_MOD_CURSOR;
1954 rv = TRU1;
1955 jleave:
1956 if(!rv)
1957 f |= a_TTY_VF_BELL;
1958 tlp->tl_vi_flags |= f;
1959 NYD2_LEAVE;
1960 return rv;
1963 static ui32_t
1964 a_tty_kht(struct a_tty_line *tlp){
1965 ui8_t (*autorecmem)[n_MEMORY_AUTOREC_TYPE_SIZEOF], *autorec_persist;
1966 struct stat sb;
1967 struct str orig, bot, topp, sub, exp, preexp;
1968 struct n_string shou, *shoup;
1969 struct a_tty_cell *cword, *ctop, *cx;
1970 bool_t wedid, set_savec;
1971 ui32_t rv, f;
1972 NYD2_ENTER;
1974 /* Get plain line data; if this is the first expansion/xy, update the
1975 * very original content so that ^G gets the origin back */
1976 orig = tlp->tl_savec;
1977 a_tty_cell2save(tlp);
1978 exp = tlp->tl_savec;
1979 if(orig.s != NULL){
1980 /*tlp->tl_savec = orig;*/
1981 set_savec = FAL0;
1982 }else
1983 set_savec = TRU1;
1984 orig = exp;
1986 autorec_persist = n_memory_autorec_current();
1987 n_memory_autorec_push(autorecmem = n_lofi_alloc(sizeof *autorecmem));
1989 shoup = n_string_creat_auto(&shou);
1990 f = a_TTY_VF_NONE;
1992 /* Find the word to be expanded */
1994 cword = tlp->tl_line.cells;
1995 ctop = cword + tlp->tl_cursor;
1996 cx = cword + tlp->tl_count;
1998 /* topp: separate data right of cursor */
1999 if(cx > ctop){
2000 for(rv = 0; ctop < cx; ++ctop)
2001 rv += ctop->tc_count;
2002 topp.l = rv;
2003 topp.s = orig.s + orig.l - rv;
2004 ctop = cword + tlp->tl_cursor;
2005 }else
2006 topp.s = NULL, topp.l = 0;
2008 /* Find the shell token that corresponds to the cursor position */
2009 /* C99 */{
2010 size_t max;
2012 max = 0;
2013 if(ctop > cword){
2014 for(; cword < ctop; ++cword)
2015 max += cword->tc_count;
2016 cword = tlp->tl_line.cells;
2018 bot = sub = orig;
2019 bot.l = 0;
2020 sub.l = max;
2022 if(max > 0){
2023 for(;;){
2024 enum n_shexp_state shs;
2026 exp = sub;
2027 shs = n_shexp_parse_token(NULL, &sub, n_SHEXP_PARSE_DRYRUN |
2028 n_SHEXP_PARSE_TRIMSPACE | n_SHEXP_PARSE_IGNORE_EMPTY |
2029 n_SHEXP_PARSE_QUOTE_AUTO_CLOSE);
2030 if(sub.l != 0){
2031 size_t x;
2033 assert(max >= sub.l);
2034 x = max - sub.l;
2035 bot.l += x;
2036 max -= x;
2037 continue;
2039 if(shs & n_SHEXP_STATE_ERR_MASK){
2040 n_err(_("Invalid completion pattern: %.*s\n"),
2041 (int)exp.l, exp.s);
2042 goto jnope;
2044 n_shexp_parse_token(shoup, &exp,
2045 n_SHEXP_PARSE_TRIMSPACE | n_SHEXP_PARSE_IGNORE_EMPTY |
2046 n_SHEXP_PARSE_QUOTE_AUTO_CLOSE);
2047 break;
2050 sub.s = n_string_cp(shoup);
2051 sub.l = shoup->s_len;
2055 /* Leave room for "implicit asterisk" expansion, as below */
2056 if(sub.l == 0){
2057 wedid = TRU1;
2058 sub.s = n_UNCONST("*");
2059 sub.l = 1;
2062 preexp.s = n_UNCONST(n_empty);
2063 preexp.l = 0;
2064 wedid = FAL0;
2065 jredo:
2066 /* TODO Super-Heavy-Metal: block all sigs, avoid leaks on jump */
2067 hold_all_sigs();
2068 exp.s = fexpand(sub.s, a_TTY_TAB_FEXP_FL);
2069 rele_all_sigs();
2071 if(exp.s == NULL || (exp.l = strlen(exp.s)) == 0){
2072 /* No. But maybe the users' desire was to complete only a part of the
2073 * shell token of interest! TODO This can be improved, we would need to
2074 * TODO have shexp_parse to create a DOM structure of parsed snippets, so
2075 * TODO that we can tell for each snippet which quote is active and
2076 * TODO whether we may cross its boundary and/or apply expansion for it */
2077 if(wedid == TRU1){
2078 size_t i, li;
2080 wedid = TRUM1;
2081 for(li = UIZ_MAX, i = sub.l; i-- > 0;){
2082 char c;
2084 if((c = sub.s[i]) == '/' || c == '+' /* *folder*! */)
2085 li = i;
2086 /* Do stop once some "magic" characters are seen XXX magic set */
2087 else if(c == '<' || c == '>' || c == '=' || c == ':')
2088 break;
2090 if(li != UIZ_MAX){
2091 preexp = sub;
2092 preexp.l = li;
2093 sub.l -= li;
2094 sub.s += li;
2095 goto jredo;
2098 goto jnope;
2101 if(wedid == TRUM1 && preexp.l > 0)
2102 preexp.s = savestrbuf(preexp.s, preexp.l);
2104 /* May be multi-return! */
2105 if(pstate & PS_EXPAND_MULTIRESULT)
2106 goto jmulti;
2108 /* xxx That is not really true since the limit counts characters not bytes */
2109 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
2110 if(exp.l >= a_TTY_LINE_MAX - 1 || a_TTY_LINE_MAX - 1 - exp.l < preexp.l){
2111 n_err(_("Tabulator expansion would extend beyond line size limit\n"));
2112 goto jnope;
2115 /* If the expansion equals the original string, assume the user wants what
2116 * is usually known as tab completion, append `*' and restart */
2117 if(!wedid && exp.l == sub.l && !memcmp(exp.s, sub.s, exp.l)){
2118 if(sub.s[sub.l - 1] == '*')
2119 goto jnope;
2121 wedid = TRU1;
2122 shoup = n_string_push_c(shoup, '*');
2123 sub.s = n_string_cp(shoup);
2124 sub.l = shoup->s_len;
2125 goto jredo;
2128 /* If it is a directory, and there is not yet a / appended, then we want the
2129 * user to confirm that he wants to dive in -- with only a HT */
2130 if(wedid && exp.l == --sub.l && !memcmp(exp.s, sub.s, exp.l) &&
2131 exp.s[exp.l - 1] != '/'){
2132 if(stat(exp.s, &sb) || !S_ISDIR(sb.st_mode))
2133 goto jnope;
2134 sub.s = salloc(exp.l + 1 +1);
2135 memcpy(sub.s, exp.s, exp.l);
2136 sub.s[exp.l++] = '/';
2137 sub.s[exp.l] = '\0';
2138 exp.s = sub.s;
2139 wedid = FAL0;
2140 goto jset;
2141 }else{
2142 if(wedid && (wedid = (exp.s[exp.l - 1] == '*')))
2143 --exp.l;
2144 exp.s[exp.l] = '\0';
2145 jset:
2146 exp.l = strlen(exp.s = n_shexp_quote_cp(exp.s, tlp->tl_quote_rndtrip));
2147 tlp->tl_defc_cursor_byte = bot.l + preexp.l + exp.l -1;
2148 if(wedid)
2149 goto jnope;
2152 orig.l = bot.l + preexp.l + exp.l + topp.l;
2153 orig.s = n_autorec_alloc(autorec_persist, orig.l + 5 +1);
2154 if((rv = (ui32_t)bot.l) > 0)
2155 memcpy(orig.s, bot.s, rv);
2156 if(preexp.l > 0){
2157 memcpy(&orig.s[rv], preexp.s, preexp.l);
2158 rv += preexp.l;
2160 memcpy(&orig.s[rv], exp.s, exp.l);
2161 rv += exp.l;
2162 if(topp.l > 0){
2163 memcpy(&orig.s[rv], topp.s, topp.l);
2164 rv += topp.l;
2166 orig.s[rv] = '\0';
2168 tlp->tl_defc = orig;
2169 tlp->tl_count = tlp->tl_cursor = 0;
2170 f |= a_TTY_VF_MOD_DIRTY;
2171 jleave:
2172 n_memory_autorec_pop(autorecmem);
2173 n_lofi_free(autorecmem);
2174 tlp->tl_vi_flags |= f;
2175 NYD2_LEAVE;
2176 return rv;
2178 jmulti:{
2179 struct n_visual_info_ctx vic;
2180 struct str input;
2181 wc_t c2, c1;
2182 bool_t isfirst;
2183 char const *lococp;
2184 size_t locolen, scrwid, lnlen, lncnt, prefixlen;
2185 FILE *fp;
2187 if((fp = Ftmp(NULL, "tabex", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
2188 n_perr(_("tmpfile"), 0);
2189 fp = n_tty_fp;
2192 /* How long is the result string for real? Search the NUL NUL
2193 * terminator. While here, detect the longest entry to perform an
2194 * initial allocation of our accumulator string */
2195 locolen = preexp.l;
2197 size_t i;
2199 i = strlen(&exp.s[++exp.l]);
2200 locolen = n_MAX(locolen, i);
2201 exp.l += i;
2202 }while(exp.s[exp.l + 1] != '\0');
2204 shoup = n_string_reserve(n_string_trunc(shoup, 0),
2205 locolen + (locolen >> 1));
2207 /* Iterate (once again) over all results */
2208 scrwid = (size_t)scrnwidth - ((size_t)scrnwidth >> 3);
2209 lnlen = lncnt = 0;
2210 n_UNINIT(prefixlen, 0);
2211 n_UNINIT(lococp, NULL);
2212 n_UNINIT(c1, '\0');
2213 for(isfirst = TRU1; exp.l > 0; isfirst = FAL0, c1 = c2){
2214 size_t i;
2215 char const *fullpath;
2217 /* Next result */
2218 sub = exp;
2219 sub.l = i = strlen(sub.s);
2220 assert(exp.l >= i);
2221 if((exp.l -= i) > 0)
2222 --exp.l;
2223 exp.s += ++i;
2225 /* Separate dirname and basename */
2226 fullpath = sub.s;
2227 if(isfirst){
2228 char const *cp;
2230 if((cp = strrchr(fullpath, '/')) != NULL)
2231 prefixlen = PTR2SIZE(++cp - fullpath);
2232 else
2233 prefixlen = 0;
2235 if(prefixlen > 0 && prefixlen < sub.l){
2236 sub.l -= prefixlen;
2237 sub.s += prefixlen;
2240 /* We want case-insensitive sort-order */
2241 memset(&vic, 0, sizeof vic);
2242 vic.vic_indat = sub.s;
2243 vic.vic_inlen = sub.l;
2244 c2 = n_visual_info(&vic, n_VISUAL_INFO_ONE_CHAR) ? vic.vic_waccu
2245 : (ui8_t)*sub.s;
2246 #ifdef HAVE_C90AMEND1
2247 c2 = towlower(c2);
2248 #else
2249 c2 = lowerconv(c2);
2250 #endif
2252 /* Query longest common prefix along the way */
2253 if(isfirst){
2254 c1 = c2;
2255 lococp = sub.s;
2256 locolen = sub.l;
2257 }else if(locolen > 0){
2258 for(i = 0; i < locolen; ++i)
2259 if(lococp[i] != sub.s[i]){
2260 i = field_detect_clip(i, lococp, i);
2261 locolen = i;
2262 break;
2266 /* Prepare display */
2267 input = sub;
2268 shoup = n_shexp_quote(n_string_trunc(shoup, 0), &input,
2269 tlp->tl_quote_rndtrip);
2270 memset(&vic, 0, sizeof vic);
2271 vic.vic_indat = shoup->s_dat;
2272 vic.vic_inlen = shoup->s_len;
2273 if(!n_visual_info(&vic,
2274 n_VISUAL_INFO_SKIP_ERRORS | n_VISUAL_INFO_WIDTH_QUERY))
2275 vic.vic_vi_width = shoup->s_len;
2277 /* Put on screen. Indent follow lines of same sort slot */
2278 c1 = (c1 != c2);
2279 if(isfirst || c1 ||
2280 scrwid < lnlen || scrwid - lnlen <= vic.vic_vi_width + 2){
2281 putc('\n', fp);
2282 if(scrwid < lnlen)
2283 ++lncnt;
2284 ++lncnt, lnlen = 0;
2285 if(!isfirst && !c1)
2286 goto jsep;
2287 }else if(lnlen > 0){
2288 jsep:
2289 fputs(" ", fp);
2290 lnlen += 2;
2292 fputs(n_string_cp(shoup), fp);
2293 lnlen += vic.vic_vi_width;
2295 /* Support the known file name tagging
2296 * XXX *line-editor-completion-filetype* or so */
2297 if(!lstat(fullpath, &sb)){
2298 char c = '\0';
2300 if(S_ISDIR(sb.st_mode))
2301 c = '/';
2302 else if(S_ISLNK(sb.st_mode))
2303 c = '@';
2304 # ifdef S_ISFIFO
2305 else if(S_ISFIFO(sb.st_mode))
2306 c = '|';
2307 # endif
2308 # ifdef S_ISSOCK
2309 else if(S_ISSOCK(sb.st_mode))
2310 c = '=';
2311 # endif
2312 # ifdef S_ISCHR
2313 else if(S_ISCHR(sb.st_mode))
2314 c = '%';
2315 # endif
2316 # ifdef S_ISBLK
2317 else if(S_ISBLK(sb.st_mode))
2318 c = '#';
2319 # endif
2321 if(c != '\0'){
2322 putc(c, fp);
2323 ++lnlen;
2327 putc('\n', fp);
2328 ++lncnt;
2330 page_or_print(fp, lncnt);
2331 if(fp != n_tty_fp)
2332 Fclose(fp);
2334 n_string_gut(shoup);
2336 /* A common prefix of 0 means we cannot provide the user any auto
2337 * completed characters */
2338 if(locolen == 0)
2339 goto jnope;
2341 /* Otherwise we can, so extend the visual line content by the common
2342 * prefix (in a reversible way) */
2343 (exp.s = n_UNCONST(lococp))[locolen] = '\0';
2344 exp.s -= prefixlen;
2345 exp.l = (locolen += prefixlen);
2347 /* XXX Indicate that there is multiple choice */
2348 /* XXX f |= a_TTY_VF_BELL; -> *line-editor-completion-bell*? or so */
2349 wedid = FAL0;
2350 goto jset;
2353 jnope:
2354 /* If we've provided a default content, but failed to expand, there is
2355 * nothing we can "revert to": drop that default again */
2356 if(set_savec){
2357 tlp->tl_savec.s = NULL;
2358 tlp->tl_savec.l = 0;
2360 f = a_TTY_VF_NONE;
2361 rv = 0;
2362 goto jleave;
2365 # ifdef HAVE_HISTORY
2366 static ui32_t
2367 a_tty__khist_shared(struct a_tty_line *tlp, struct a_tty_hist *thp){
2368 ui32_t f, rv;
2369 NYD2_ENTER;
2371 if(n_LIKELY((tlp->tl_hist = thp) != NULL)){
2372 tlp->tl_defc.s = savestrbuf(thp->th_dat, thp->th_len);
2373 rv = tlp->tl_defc.l = thp->th_len;
2374 f = (tlp->tl_count > 0) ? a_TTY_VF_MOD_DIRTY : a_TTY_VF_NONE;
2375 tlp->tl_count = tlp->tl_cursor = 0;
2376 }else{
2377 f = a_TTY_VF_BELL;
2378 rv = UI32_MAX;
2381 tlp->tl_vi_flags |= f;
2382 NYD2_LEAVE;
2383 return rv;
2386 static ui32_t
2387 a_tty_khist(struct a_tty_line *tlp, bool_t fwd){
2388 struct a_tty_hist *thp;
2389 ui32_t rv;
2390 NYD2_ENTER;
2392 /* If we're not in history mode yet, save line content;
2393 * also, disallow forward search, then, and, of course, bail unless we
2394 * do have any history at all */
2395 if((thp = tlp->tl_hist) == NULL){
2396 if(fwd)
2397 goto jleave;
2398 if((thp = a_tty.tg_hist) == NULL)
2399 goto jleave;
2400 a_tty_cell2save(tlp);
2401 goto jleave;
2404 thp = fwd ? thp->th_younger : thp->th_older;
2405 jleave:
2406 rv = a_tty__khist_shared(tlp, thp);
2407 NYD2_LEAVE;
2408 return rv;
2411 static ui32_t
2412 a_tty_khist_search(struct a_tty_line *tlp, bool_t fwd){
2413 struct str orig_savec;
2414 struct a_tty_hist *thp;
2415 ui32_t rv;
2416 NYD2_ENTER;
2418 thp = NULL;
2420 /* We cannot complete an empty line */
2421 if(n_UNLIKELY(tlp->tl_count == 0)){
2422 /* XXX The upcoming hard reset would restore a set savec buffer,
2423 * XXX so forcefully reset that. A cleaner solution would be to
2424 * XXX reset it whenever a restore is no longer desired */
2425 tlp->tl_savec.s = NULL;
2426 tlp->tl_savec.l = 0;
2427 goto jleave;
2430 if((thp = tlp->tl_hist) == NULL){
2431 if((thp = a_tty.tg_hist) == NULL)
2432 goto jleave;
2433 /* We don't support wraparound, searching forward must always step */
2434 if(fwd)
2435 thp = thp->th_younger;
2436 orig_savec.s = NULL;
2437 orig_savec.l = 0; /* silence CC */
2438 }else if((thp = (fwd ? thp->th_younger : thp->th_older)) == NULL)
2439 goto jleave;
2440 else
2441 orig_savec = tlp->tl_savec;
2443 if(orig_savec.s == NULL)
2444 a_tty_cell2save(tlp);
2446 for(; thp != NULL; thp = (fwd ? thp->th_younger : thp->th_older))
2447 if(is_prefix(tlp->tl_savec.s, thp->th_dat))
2448 break;
2450 if(orig_savec.s != NULL)
2451 tlp->tl_savec = orig_savec;
2452 jleave:
2453 rv = a_tty__khist_shared(tlp, thp);
2454 NYD2_LEAVE;
2455 return rv;
2457 # endif /* HAVE_HISTORY */
2459 static enum a_tty_fun_status
2460 a_tty_fun(struct a_tty_line *tlp, enum a_tty_bind_flags tbf, size_t *len){
2461 enum a_tty_fun_status rv;
2462 NYD2_ENTER;
2464 rv = a_TTY_FUN_STATUS_OK;
2465 # undef a_X
2466 # define a_X(N) a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## N)
2467 switch(a_TTY_BIND_FUN_REDUCE(tbf)){
2468 case a_X(BELL):
2469 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2470 break;
2471 case a_X(GO_BWD):
2472 a_tty_kleft(tlp);
2473 break;
2474 case a_X(GO_FWD):
2475 a_tty_kright(tlp);
2476 break;
2477 case a_X(GO_WORD_BWD):
2478 a_tty_kgow(tlp, -1);
2479 break;
2480 case a_X(GO_WORD_FWD):
2481 a_tty_kgow(tlp, +1);
2482 break;
2483 case a_X(GO_HOME):
2484 a_tty_khome(tlp, TRU1);
2485 break;
2486 case a_X(GO_END):
2487 a_tty_kend(tlp);
2488 break;
2489 case a_X(DEL_BWD):
2490 a_tty_kbs(tlp);
2491 break;
2492 case a_X(DEL_FWD):
2493 if(a_tty_kdel(tlp) < 0)
2494 rv = a_TTY_FUN_STATUS_END;
2495 break;
2496 case a_X(SNARF_WORD_BWD):
2497 a_tty_ksnarfw(tlp, FAL0);
2498 break;
2499 case a_X(SNARF_WORD_FWD):
2500 a_tty_ksnarfw(tlp, TRU1);
2501 break;
2502 case a_X(SNARF_END):
2503 a_tty_ksnarf(tlp, FAL0, TRU1);
2504 break;
2505 case a_X(SNARF_LINE):
2506 a_tty_ksnarf(tlp, TRU1, (tlp->tl_count == 0));
2507 break;
2509 case a_X(HIST_FWD):
2510 # ifdef HAVE_HISTORY
2511 if(tlp->tl_hist != NULL){
2512 bool_t isfwd = TRU1;
2514 if(0){
2515 # endif
2516 /* FALLTHRU */
2517 case a_X(HIST_BWD):
2518 # ifdef HAVE_HISTORY
2519 isfwd = FAL0;
2521 if((*len = a_tty_khist(tlp, isfwd)) != UI32_MAX){
2522 rv = a_TTY_FUN_STATUS_RESTART;
2523 break;
2525 goto jreset;
2526 # endif
2528 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2529 break;
2531 case a_X(HIST_SRCH_FWD):{
2532 # ifdef HAVE_HISTORY
2533 bool_t isfwd = TRU1;
2535 if(0){
2536 # endif
2537 /* FALLTHRU */
2538 case a_X(HIST_SRCH_BWD):
2539 # ifdef HAVE_HISTORY
2540 isfwd = FAL0;
2542 if((*len = a_tty_khist_search(tlp, isfwd)) != UI32_MAX){
2543 rv = a_TTY_FUN_STATUS_RESTART;
2544 break;
2546 goto jreset;
2547 # else
2548 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2549 # endif
2550 } break;
2552 case a_X(REPAINT):
2553 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2554 break;
2555 case a_X(QUOTE_RNDTRIP):
2556 tlp->tl_quote_rndtrip = !tlp->tl_quote_rndtrip;
2557 break;
2558 case a_X(PROMPT_CHAR):{
2559 wchar_t wc;
2561 if((wc = a_tty_vinuni(tlp)) > 0)
2562 a_tty_kother(tlp, wc);
2563 } break;
2564 case a_X(COMPLETE):
2565 if((*len = a_tty_kht(tlp)) > 0)
2566 rv = a_TTY_FUN_STATUS_RESTART;
2567 break;
2569 case a_X(PASTE):
2570 if(tlp->tl_pastebuf.l > 0)
2571 *len = (tlp->tl_defc = tlp->tl_pastebuf).l;
2572 else
2573 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2574 break;
2577 case a_X(CANCEL):
2578 /* Normally this just causes a restart and thus resets the state
2579 * machine */
2580 if(tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2582 # ifdef HAVE_KEY_BINDINGS
2583 tlp->tl_bind_takeover = '\0';
2584 # endif
2585 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2586 rv = a_TTY_FUN_STATUS_RESTART;
2587 break;
2589 case a_X(RESET):
2590 if(tlp->tl_count == 0 && tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2591 # ifdef HAVE_KEY_BINDINGS
2592 tlp->tl_bind_takeover = '\0';
2593 # endif
2594 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY | a_TTY_VF_BELL;
2595 break;
2596 }else if(0){
2597 case a_X(FULLRESET):
2598 tlp->tl_savec.s = tlp->tl_defc.s = NULL;
2599 tlp->tl_savec.l = tlp->tl_defc.l = 0;
2600 tlp->tl_defc_cursor_byte = 0;
2601 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2603 jreset:
2604 # ifdef HAVE_KEY_BINDINGS
2605 tlp->tl_bind_takeover = '\0';
2606 # endif
2607 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2608 tlp->tl_cursor = tlp->tl_count = 0;
2609 # ifdef HAVE_HISTORY
2610 tlp->tl_hist = NULL;
2611 # endif
2612 if((*len = tlp->tl_savec.l) != 0){
2613 tlp->tl_defc = tlp->tl_savec;
2614 tlp->tl_savec.s = NULL;
2615 tlp->tl_savec.l = 0;
2616 }else
2617 *len = tlp->tl_defc.l;
2618 rv = a_TTY_FUN_STATUS_RESTART;
2619 break;
2621 default:
2622 case a_X(COMMIT):
2623 rv = a_TTY_FUN_STATUS_COMMIT;
2624 break;
2626 # undef a_X
2628 NYD2_LEAVE;
2629 return rv;
2632 static ssize_t
2633 a_tty_readline(struct a_tty_line *tlp, size_t len n_MEMORY_DEBUG_ARGS){
2634 /* We want to save code, yet we may have to incorporate a lines'
2635 * default content and / or default input to switch back to after some
2636 * history movement; let "len > 0" mean "have to display some data
2637 * buffer" -> a_BUFMODE, and only otherwise read(2) it */
2638 mbstate_t ps[2];
2639 char cbuf_base[MB_LEN_MAX * 2], *cbuf, *cbufp;
2640 ssize_t rv;
2641 struct a_tty_bind_tree *tbtp;
2642 wchar_t wc;
2643 enum a_tty_bind_flags tbf;
2644 enum {a_NONE, a_WAS_HERE = 1<<0, a_BUFMODE = 1<<1, a_MAYBEFUN = 1<<2,
2645 a_TIMEOUT = 1<<3, a_TIMEOUT_EXPIRED = 1<<4,
2646 a_TIMEOUT_MASK = a_TIMEOUT | a_TIMEOUT_EXPIRED,
2647 a_READ_LOOP_MASK = ~(a_WAS_HERE | a_MAYBEFUN | a_TIMEOUT_MASK)
2648 } flags;
2649 NYD_ENTER;
2651 n_UNINIT(rv, 0);
2652 # ifdef HAVE_KEY_BINDINGS
2653 assert(tlp->tl_bind_takeover == '\0');
2654 # endif
2655 jrestart:
2656 memset(ps, 0, sizeof ps);
2657 flags = a_NONE;
2658 tbf = 0;
2659 tlp->tl_vi_flags |= a_TTY_VF_REFRESH | a_TTY_VF_SYNC;
2661 jinput_loop:
2662 for(;;){
2663 if(len != 0)
2664 flags |= a_BUFMODE;
2666 /* Ensure we have valid pointers, and room for grow */
2667 a_tty_check_grow(tlp, ((flags & a_BUFMODE) ? (ui32_t)len : 1)
2668 n_MEMORY_DEBUG_ARGSCALL);
2670 /* Handle visual state flags, except in buffer mode */
2671 if(!(flags & a_BUFMODE) && (tlp->tl_vi_flags & a_TTY_VF_ALL_MASK))
2672 if(!a_tty_vi_refresh(tlp)){
2673 rv = -1;
2674 goto jleave;
2677 /* Ready for messing around.
2678 * Normal read(2)? Else buffer mode: speed this one up */
2679 if(!(flags & a_BUFMODE)){
2680 cbufp =
2681 cbuf = cbuf_base;
2682 }else{
2683 assert(tlp->tl_defc.l > 0 && tlp->tl_defc.s != NULL);
2684 assert(tlp->tl_defc.l >= len);
2685 cbufp =
2686 cbuf = tlp->tl_defc.s + (tlp->tl_defc.l - len);
2687 cbufp += len;
2690 /* Read in the next complete multibyte character */
2691 /* C99 */{
2692 # ifdef HAVE_KEY_BINDINGS
2693 struct a_tty_bind_tree *xtbtp;
2694 struct inseq{
2695 struct inseq *last;
2696 struct inseq *next;
2697 struct a_tty_bind_tree *tbtp;
2698 } *isp_head, *isp;
2700 isp_head = isp = NULL;
2701 # endif
2703 for(flags &= a_READ_LOOP_MASK;;){
2704 # ifdef HAVE_KEY_BINDINGS
2705 if(!(flags & a_BUFMODE) && tlp->tl_bind_takeover != '\0'){
2706 wc = tlp->tl_bind_takeover;
2707 tlp->tl_bind_takeover = '\0';
2708 }else
2709 # endif
2711 if(!(flags & a_BUFMODE)){
2712 /* Let me at least once dream of iomon(itor), timer with
2713 * one-shot, enwrapped with key_event and key_sequence_event,
2714 * all driven by an event_loop */
2715 /* TODO v15 Until we have SysV signal handling all through we
2716 * TODO need to temporarily adjust our BSD signal handler with
2717 * TODO a SysV one, here */
2718 n_sighdl_t otstp, ottin, ottou;
2720 otstp = n_signal(SIGTSTP, &n_tty_signal);
2721 ottin = n_signal(SIGTTIN, &n_tty_signal);
2722 ottou = n_signal(SIGTTOU, &n_tty_signal);
2723 # ifdef HAVE_KEY_BINDINGS
2724 flags &= ~a_TIMEOUT_MASK;
2725 if(isp != NULL && (tbtp = isp->tbtp)->tbt_isseq &&
2726 !tbtp->tbt_isseq_trail){
2727 a_tty_term_rawmode_timeout(tlp, TRU1);
2728 flags |= a_TIMEOUT;
2730 # endif
2732 while((rv = read(STDIN_FILENO, cbufp, 1)) < 1){
2733 if(rv == -1){
2734 if(errno == EINTR){
2735 if((tlp->tl_vi_flags & a_TTY_VF_MOD_DIRTY) &&
2736 !a_tty_vi_refresh(tlp))
2737 break;
2738 continue;
2740 break;
2743 # ifdef HAVE_KEY_BINDINGS
2744 /* Timeout expiration */
2745 if(rv == 0){
2746 assert(flags & a_TIMEOUT);
2747 assert(isp != NULL);
2748 a_tty_term_rawmode_timeout(tlp, FAL0);
2750 /* Something "atomic" broke. Maybe the current one can
2751 * also be terminated already, by itself? xxx really? */
2752 if((tbtp = isp->tbtp)->tbt_bind != NULL){
2753 tlp->tl_bind_takeover = wc;
2754 goto jhave_bind;
2757 /* Or, maybe there is a second path without a timeout;
2758 * this should be covered by .tbt_isseq_trail, but then
2759 * again a single-layer implementation cannot "know" */
2760 for(xtbtp = tbtp; (xtbtp = xtbtp->tbt_sibling) != NULL;)
2761 if(xtbtp->tbt_char == tbtp->tbt_char){
2762 assert(!xtbtp->tbt_isseq);
2763 break;
2765 /* Lay down on read(2)? */
2766 if(xtbtp != NULL)
2767 continue;
2768 goto jtake_over;
2770 # endif /* HAVE_KEY_BINDINGS */
2773 # ifdef HAVE_KEY_BINDINGS
2774 if(flags & a_TIMEOUT)
2775 a_tty_term_rawmode_timeout(tlp, FAL0);
2776 # endif
2777 safe_signal(SIGTSTP, otstp);
2778 safe_signal(SIGTTIN, ottin);
2779 safe_signal(SIGTTOU, ottou);
2780 if(rv < 0)
2781 goto jleave;
2783 ++cbufp;
2786 rv = (ssize_t)mbrtowc(&wc, cbuf, PTR2SIZE(cbufp - cbuf), &ps[0]);
2787 if(rv <= 0){
2788 /* Any error during buffer mode can only result in a hard
2789 * reset; Otherwise, if it's a hard error, or if too many
2790 * redundant shift sequences overflow our buffer: perform
2791 * hard reset */
2792 if((flags & a_BUFMODE) || rv == -1 ||
2793 sizeof cbuf_base == PTR2SIZE(cbufp - cbuf)){
2794 a_tty_fun(tlp, a_TTY_BIND_FUN_FULLRESET, &len);
2795 goto jrestart;
2797 /* Otherwise, due to the way we deal with the buffer, we need
2798 * to restore the mbstate_t from before this conversion */
2799 ps[0] = ps[1];
2800 continue;
2802 cbufp = cbuf;
2803 ps[1] = ps[0];
2806 /* Normal read(2)ing is subject to detection of key-bindings */
2807 # ifdef HAVE_KEY_BINDINGS
2808 if(!(flags & a_BUFMODE)){
2809 /* Check for special bypass functions before we try to embed
2810 * this character into the tree */
2811 if(n_uasciichar(wc)){
2812 char c;
2813 char const *cp;
2815 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_prompt_char)[0];
2816 *cp != '\0'; ++cp){
2817 if(c == *cp){
2818 wc = a_tty_vinuni(tlp);
2819 break;
2822 if(wc == '\0'){
2823 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2824 goto jinput_loop;
2827 if(n_uasciichar(wc))
2828 flags |= a_MAYBEFUN;
2829 else
2830 flags &= ~a_MAYBEFUN;
2832 /* Search for this character in the bind tree */
2833 tbtp = (isp != NULL) ? isp->tbtp->tbt_childs
2834 : (*tlp->tl_bind_tree_hmap)[wc % HSHSIZE];
2835 for(; tbtp != NULL; tbtp = tbtp->tbt_sibling){
2836 if(tbtp->tbt_char == wc){
2837 struct inseq *nisp;
2839 /* If this one cannot continue we're likely finished! */
2840 if(tbtp->tbt_childs == NULL){
2841 assert(tbtp->tbt_bind != NULL);
2842 tbf = tbtp->tbt_bind->tbc_flags;
2843 goto jmle_fun;
2846 /* This needs to read more characters */
2847 nisp = salloc(sizeof *nisp);
2848 if((nisp->last = isp) == NULL)
2849 isp_head = nisp;
2850 else
2851 isp->next = nisp;
2852 nisp->next = NULL;
2853 nisp->tbtp = tbtp;
2854 isp = nisp;
2855 flags &= ~a_WAS_HERE;
2856 break;
2859 if(tbtp != NULL)
2860 continue;
2862 /* Was there a binding active, but couldn't be continued? */
2863 if(isp != NULL){
2864 /* A binding had a timeout, it didn't expire, but we saw
2865 * something non-expected. Something "atomic" broke.
2866 * Maybe there is a second path without a timeout, that
2867 * continues like we've seen it. I.e., it may just have been
2868 * the user, typing too fast. We definitely want to allow
2869 * bindings like \e,d etc. to succeed: users are so used to
2870 * them that a timeout cannot be the mechanism to catch up!
2871 * A single-layer implementation cannot "know" */
2872 if((tbtp = isp->tbtp)->tbt_isseq && (isp->last == NULL ||
2873 !(xtbtp = isp->last->tbtp)->tbt_isseq ||
2874 xtbtp->tbt_isseq_trail)){
2875 for(xtbtp = (tbtp = isp->tbtp);
2876 (xtbtp = xtbtp->tbt_sibling) != NULL;)
2877 if(xtbtp->tbt_char == tbtp->tbt_char){
2878 assert(!xtbtp->tbt_isseq);
2879 break;
2881 if(xtbtp != NULL){
2882 isp->tbtp = xtbtp;
2883 tlp->tl_bind_takeover = wc;
2884 continue;
2888 /* Check for CANCEL shortcut now */
2889 if(flags & a_MAYBEFUN){
2890 char c;
2891 char const *cp;
2893 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_cancel)[0];
2894 *cp != '\0'; ++cp)
2895 if(c == *cp){
2896 tbf = a_TTY_BIND_FUN_INTERNAL |a_TTY_BIND_FUN_CANCEL;
2897 goto jmle_fun;
2901 /* So: maybe the current sequence can be terminated here? */
2902 if((tbtp = isp->tbtp)->tbt_bind != NULL){
2903 jhave_bind:
2904 tbf = tbtp->tbt_bind->tbc_flags;
2905 jmle_fun:
2906 if(tbf & a_TTY_BIND_FUN_INTERNAL){
2907 switch(a_tty_fun(tlp, tbf, &len)){
2908 case a_TTY_FUN_STATUS_OK:
2909 goto jinput_loop;
2910 case a_TTY_FUN_STATUS_COMMIT:
2911 goto jdone;
2912 case a_TTY_FUN_STATUS_RESTART:
2913 goto jrestart;
2914 case a_TTY_FUN_STATUS_END:
2915 goto jleave;
2917 assert(0);
2918 }else if(tbtp->tbt_bind->tbc_flags & a_TTY_BIND_NOCOMMIT){
2919 struct a_tty_bind_ctx *tbcp;
2921 tbcp = tbtp->tbt_bind;
2922 memcpy(tlp->tl_defc.s = salloc(
2923 (tlp->tl_defc.l = len = tbcp->tbc_exp_len) +1),
2924 tbcp->tbc_exp, tbcp->tbc_exp_len +1);
2925 goto jrestart;
2926 }else{
2927 tlp->tl_reenter_after_cmd = tbtp->tbt_bind->tbc_exp;
2928 goto jdone;
2933 /* Otherwise take over all chars "as is" */
2934 jtake_over:
2935 for(; isp_head != NULL; isp_head = isp_head->next)
2936 if(a_tty_kother(tlp, isp_head->tbtp->tbt_char)){
2937 /* FIXME */
2939 /* And the current one too */
2940 goto jkother;
2942 # endif /* HAVE_KEY_BINDINGS */
2944 if((flags & a_BUFMODE) && (len -= (size_t)rv) == 0){
2945 /* Buffer mode completed */
2946 tlp->tl_defc.s = NULL;
2947 tlp->tl_defc.l = 0;
2948 flags &= ~a_BUFMODE;
2950 break;
2953 # ifndef HAVE_KEY_BINDINGS
2954 /* Don't interpret control bytes during buffer mode.
2955 * Otherwise, if it's a control byte check whether it is a MLE
2956 * function. Remarks: initially a complete duplicate to be able to
2957 * switch(), later converted to simply iterate over (an #ifdef'd
2958 * subset of) the MLE base_tuple table in order to have "a SPOF" */
2959 if(cbuf == cbuf_base && n_uasciichar(wc) && cntrlchar((char)wc)){
2960 struct a_tty_bind_builtin_tuple const *tbbtp, *tbbtp_max;
2961 char c;
2963 c = (char)wc ^ 0x40;
2964 tbbtp = a_tty_bind_base_tuples;
2965 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_base_tuples)];
2966 jbuiltin_redo:
2967 for(; tbbtp < tbbtp_max; ++tbbtp){
2968 /* Assert default_tuple table is properly subset'ed */
2969 assert(tbbtp->tbdt_iskey);
2970 if(tbbtp->tbbt_ckey == c){
2971 if(tbbtp->tbbt_exp[0] == '\0'){
2972 enum a_tty_bind_flags tbf;
2974 tbf = a_TTY_BIND_FUN_EXPAND((ui8_t)tbbtp->tbbt_exp[1]);
2975 switch(a_tty_fun(tlp, tbf, &len)){
2976 case a_TTY_FUN_STATUS_OK:
2977 goto jinput_loop;
2978 case a_TTY_FUN_STATUS_COMMIT:
2979 goto jdone;
2980 case a_TTY_FUN_STATUS_RESTART:
2981 goto jrestart;
2982 case a_TTY_FUN_STATUS_END:
2983 goto jleave;
2985 assert(0);
2986 }else{
2987 tlp->tl_reenter_after_cmd = tbbtp->tbbt_exp;
2988 goto jdone;
2992 if(tbbtp ==
2993 &a_tty_bind_base_tuples[n_NELEM(a_tty_bind_base_tuples)]){
2994 tbbtp = a_tty_bind_default_tuples;
2995 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_default_tuples)];
2996 goto jbuiltin_redo;
2999 # endif /* !HAVE_KEY_BINDINGS */
3001 # ifdef HAVE_KEY_BINDINGS
3002 jkother:
3003 # endif
3004 if(a_tty_kother(tlp, wc)){
3005 /* Don't clear the history during buffer mode.. */
3006 # ifdef HAVE_HISTORY
3007 if(!(flags & a_BUFMODE) && cbuf == cbuf_base)
3008 tlp->tl_hist = NULL;
3009 # endif
3014 /* We have a completed input line, convert the struct cell data to its
3015 * plain character equivalent */
3016 jdone:
3017 rv = a_tty_cell2dat(tlp);
3018 jleave:
3019 putc('\n', n_tty_fp);
3020 fflush(n_tty_fp);
3021 NYD_LEAVE;
3022 return rv;
3025 # ifdef HAVE_KEY_BINDINGS
3026 static enum n_lexinput_flags
3027 a_tty_bind_ctx_find(char const *name){
3028 enum n_lexinput_flags rv;
3029 struct a_tty_bind_ctx_map const *tbcmp;
3030 NYD2_ENTER;
3032 tbcmp = a_tty_bind_ctx_maps;
3033 do if(!asccasecmp(tbcmp->tbcm_name, name)){
3034 rv = tbcmp->tbcm_ctx;
3035 goto jleave;
3036 }while(PTRCMP(++tbcmp, <,
3037 &a_tty_bind_ctx_maps[n_NELEM(a_tty_bind_ctx_maps)]));
3039 rv = (enum n_lexinput_flags)-1;
3040 jleave:
3041 NYD2_LEAVE;
3042 return rv;
3045 static bool_t
3046 a_tty_bind_create(struct a_tty_bind_parse_ctx *tbpcp, bool_t replace){
3047 struct a_tty_bind_ctx *tbcp;
3048 bool_t rv;
3049 NYD2_ENTER;
3051 rv = FAL0;
3053 if(!a_tty_bind_parse(TRU1, tbpcp))
3054 goto jleave;
3056 /* Since we use a single buffer for it all, need to replace as such */
3057 if(tbpcp->tbpc_tbcp != NULL){
3058 if(!replace)
3059 goto jleave;
3060 a_tty_bind_del(tbpcp);
3061 }else if(a_tty.tg_bind_cnt == UI32_MAX){
3062 n_err(_("`bind': maximum number of bindings already established\n"));
3063 goto jleave;
3066 /* C99 */{
3067 size_t i, j;
3069 tbcp = smalloc(n_VSTRUCT_SIZEOF(struct a_tty_bind_ctx, tbc__buf) +
3070 tbpcp->tbpc_seq_len + tbpcp->tbpc_exp.l +
3071 n_MAX(sizeof(si32_t), sizeof(wc_t)) + tbpcp->tbpc_cnv_len +3);
3072 if(tbpcp->tbpc_ltbcp != NULL){
3073 tbcp->tbc_next = tbpcp->tbpc_ltbcp->tbc_next;
3074 tbpcp->tbpc_ltbcp->tbc_next = tbcp;
3075 }else{
3076 enum n_lexinput_flags lif = tbpcp->tbpc_flags & n__LEXINPUT_CTX_MASK;
3078 tbcp->tbc_next = a_tty.tg_bind[lif];
3079 a_tty.tg_bind[lif] = tbcp;
3081 memcpy(tbcp->tbc_seq = &tbcp->tbc__buf[0],
3082 tbpcp->tbpc_seq, i = (tbcp->tbc_seq_len = tbpcp->tbpc_seq_len) +1);
3083 memcpy(tbcp->tbc_exp = &tbcp->tbc__buf[i],
3084 tbpcp->tbpc_exp.s, j = (tbcp->tbc_exp_len = tbpcp->tbpc_exp.l) +1);
3085 i += j;
3086 i = (i + tbpcp->tbpc_cnv_align_mask) & ~tbpcp->tbpc_cnv_align_mask;
3087 memcpy(tbcp->tbc_cnv = &tbcp->tbc__buf[i],
3088 tbpcp->tbpc_cnv, (tbcp->tbc_cnv_len = tbpcp->tbpc_cnv_len) +1);
3089 tbcp->tbc_flags = tbpcp->tbpc_flags;
3092 /* Directly resolve any termcap(5) symbol if we are already setup */
3093 if((pstate & PS_STARTED) &&
3094 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
3095 a_TTY_BIND_RESOLVE)
3096 a_tty_bind_resolve(tbcp);
3098 ++a_tty.tg_bind_cnt;
3099 /* If this binding is usable invalidate the key input lookup trees */
3100 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3101 a_tty.tg_bind_isdirty = TRU1;
3102 rv = TRU1;
3103 jleave:
3104 NYD2_LEAVE;
3105 return rv;
3108 static bool_t
3109 a_tty_bind_parse(bool_t isbindcmd, struct a_tty_bind_parse_ctx *tbpcp){
3110 enum{a_TRUE_RV = a_TTY__BIND_LAST<<1};
3112 struct n_visual_info_ctx vic;
3113 struct str shin_save, shin;
3114 struct n_string shou, *shoup;
3115 size_t i;
3116 struct kse{
3117 struct kse *next;
3118 char *seq_dat;
3119 wc_t *cnv_dat;
3120 ui32_t seq_len;
3121 ui32_t cnv_len; /* High bit set if a termap to be resolved */
3122 ui32_t calc_cnv_len; /* Ditto, but aligned etc. */
3123 ui8_t kse__dummy[4];
3124 } *head, *tail;
3125 ui32_t f;
3126 NYD2_ENTER;
3127 n_LCTA(UICMP(64, a_TRUE_RV, <, UI32_MAX),
3128 "Flag bits excess storage datatype");
3130 f = n_LEXINPUT_NONE;
3131 shoup = n_string_creat_auto(&shou);
3132 head = tail = NULL;
3134 /* Parse the key-sequence */
3135 for(shin.s = n_UNCONST(tbpcp->tbpc_in_seq), shin.l = UIZ_MAX;;){
3136 struct kse *ep;
3137 enum n_shexp_state shs;
3139 shin_save = shin;
3140 shs = n_shexp_parse_token(shoup, &shin,
3141 n_SHEXP_PARSE_TRUNC | n_SHEXP_PARSE_TRIMSPACE |
3142 n_SHEXP_PARSE_IGNORE_EMPTY | n_SHEXP_PARSE_IFS_IS_COMMA);
3143 if(shs & n_SHEXP_STATE_ERR_UNICODE){
3144 f |= a_TTY_BIND_DEFUNCT;
3145 if(isbindcmd && (options & OPT_D_V))
3146 n_err(_("`%s': \\uNICODE not available in locale: %s\n"),
3147 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3149 if((shs & n_SHEXP_STATE_ERR_MASK) & ~n_SHEXP_STATE_ERR_UNICODE){
3150 n_err(_("`%s': failed to parse key-sequence: %s\n"),
3151 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3152 goto jleave;
3154 if((shs & (n_SHEXP_STATE_OUTPUT | n_SHEXP_STATE_STOP)) ==
3155 n_SHEXP_STATE_STOP)
3156 break;
3158 ep = salloc(sizeof *ep);
3159 if(head == NULL)
3160 head = ep;
3161 else
3162 tail->next = ep;
3163 tail = ep;
3164 ep->next = NULL;
3165 if(!(shs & n_SHEXP_STATE_ERR_UNICODE)){
3166 i = strlen(ep->seq_dat = n_shexp_quote_cp(n_string_cp(shoup), TRU1));
3167 if(i >= SI32_MAX - 1)
3168 goto jelen;
3169 ep->seq_len = (ui32_t)i;
3170 }else{
3171 /* Otherwise use the original buffer, _we_ can only quote it the wrong
3172 * way (e.g., an initial $'\u3a' becomes '\u3a'), _then_ */
3173 if((i = shin_save.l - shin.l) >= SI32_MAX - 1)
3174 goto jelen;
3175 ep->seq_len = (ui32_t)i;
3176 ep->seq_dat = savestrbuf(shin_save.s, i);
3179 memset(&vic, 0, sizeof vic);
3180 vic.vic_inlen = shoup->s_len;
3181 vic.vic_indat = shoup->s_dat;
3182 if(!n_visual_info(&vic,
3183 n_VISUAL_INFO_WOUT_CREATE | n_VISUAL_INFO_WOUT_SALLOC)){
3184 n_err(_("`%s': key-sequence seems to contain invalid "
3185 "characters: %s: %s\n"),
3186 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
3187 f |= a_TTY_BIND_DEFUNCT;
3188 goto jleave;
3189 }else if(vic.vic_woulen == 0 ||
3190 vic.vic_woulen >= (SI32_MAX - 2) / sizeof(wc_t)){
3191 jelen:
3192 n_err(_("`%s': length of key-sequence unsupported: %s: %s\n"),
3193 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
3194 f |= a_TTY_BIND_DEFUNCT;
3195 goto jleave;
3197 ep->cnv_dat = vic.vic_woudat;
3198 ep->cnv_len = (ui32_t)vic.vic_woulen;
3200 /* A termcap(5)/terminfo(5) identifier? */
3201 if(ep->cnv_len > 1 && ep->cnv_dat[0] == ':'){
3202 i = --ep->cnv_len, ++ep->cnv_dat;
3203 # ifndef HAVE_TERMCAP
3204 if(options & OPT_D_V)
3205 n_err(_("`%s': no termcap(5)/terminfo(5) support: %s: %s\n"),
3206 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3207 f |= a_TTY_BIND_DEFUNCT;
3208 # endif
3209 if(i > a_TTY_BIND_CAPNAME_MAX){
3210 n_err(_("`%s': termcap(5)/terminfo(5) name too long: %s: %s\n"),
3211 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3212 f |= a_TTY_BIND_DEFUNCT;
3214 while(i > 0)
3215 /* (We store it as char[]) */
3216 if((ui32_t)ep->cnv_dat[--i] & ~0x7Fu){
3217 n_err(_("`%s': invalid termcap(5)/terminfo(5) name content: "
3218 "%s: %s\n"),
3219 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3220 f |= a_TTY_BIND_DEFUNCT;
3221 break;
3223 ep->cnv_len |= SI32_MIN; /* Needs resolve */
3224 f |= a_TTY_BIND_RESOLVE;
3227 if(shs & n_SHEXP_STATE_STOP)
3228 break;
3231 if(head == NULL){
3232 jeempty:
3233 n_err(_("`%s': effectively empty key-sequence: %s\n"),
3234 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3235 goto jleave;
3238 if(isbindcmd) /* (Or always, just "1st time init") */
3239 tbpcp->tbpc_cnv_align_mask = n_MAX(sizeof(si32_t), sizeof(wc_t)) - 1;
3241 /* C99 */{
3242 struct a_tty_bind_ctx *ltbcp, *tbcp;
3243 char *cpbase, *cp, *cnv;
3244 size_t sl, cl;
3246 /* Unite the parsed sequence(s) into single string representations */
3247 for(sl = cl = 0, tail = head; tail != NULL; tail = tail->next){
3248 sl += tail->seq_len + 1;
3250 if(!isbindcmd)
3251 continue;
3253 /* Preserve room for terminal capabilities to be resolved.
3254 * Above we have ensured the buffer will fit in these calculations */
3255 if((i = tail->cnv_len) & SI32_MIN){
3256 /* For now
3257 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[]+NUL;}
3258 * later
3259 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3260 n_LCTAV(n_ISPOW2(a_TTY_BIND_CAPEXP_ROUNDUP));
3261 n_LCTA(a_TTY_BIND_CAPEXP_ROUNDUP >= sizeof(wc_t),
3262 "Aligning on this constant doesn't properly align wc_t");
3263 i &= SI32_MAX;
3264 i *= sizeof(wc_t);
3265 i += sizeof(si32_t);
3266 if(i < a_TTY_BIND_CAPEXP_ROUNDUP)
3267 i = (i + (a_TTY_BIND_CAPEXP_ROUNDUP - 1)) &
3268 ~(a_TTY_BIND_CAPEXP_ROUNDUP - 1);
3269 }else
3270 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3271 i *= sizeof(wc_t);
3272 i += sizeof(si32_t) + sizeof(wc_t); /* (buf_len_iscap, NUL) */
3273 cl += i;
3274 if(tail->cnv_len & SI32_MIN){
3275 tail->cnv_len &= SI32_MAX;
3276 i |= SI32_MIN;
3278 tail->calc_cnv_len = (ui32_t)i;
3280 --sl;
3282 tbpcp->tbpc_seq_len = sl;
3283 tbpcp->tbpc_cnv_len = cl;
3284 /* C99 */{
3285 size_t j;
3287 j = i = sl + 1; /* Room for comma separator */
3288 if(isbindcmd){
3289 i = (i + tbpcp->tbpc_cnv_align_mask) & ~tbpcp->tbpc_cnv_align_mask;
3290 j = i;
3291 i += cl;
3293 tbpcp->tbpc_seq = cp = cpbase = salloc(i);
3294 tbpcp->tbpc_cnv = cnv = &cpbase[j];
3297 for(tail = head; tail != NULL; tail = tail->next){
3298 memcpy(cp, tail->seq_dat, tail->seq_len);
3299 cp += tail->seq_len;
3300 *cp++ = ',';
3302 if(isbindcmd){
3303 char * const save_cnv = cnv;
3305 n_UNALIGN(si32_t*,cnv)[0] = (si32_t)(i = tail->calc_cnv_len);
3306 cnv += sizeof(si32_t);
3307 if(i & SI32_MIN){
3308 /* For now
3309 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];}
3310 * later
3311 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[];} */
3312 n_UNALIGN(si32_t*,cnv)[0] = tail->cnv_len;
3313 cnv += sizeof(si32_t);
3315 i = tail->cnv_len * sizeof(wc_t);
3316 memcpy(cnv, tail->cnv_dat, i);
3317 cnv += i;
3318 *n_UNALIGN(wc_t*,cnv) = '\0';
3320 cnv = save_cnv + (tail->calc_cnv_len & SI32_MAX);
3323 *--cp = '\0';
3325 /* Search for a yet existing identical mapping */
3326 for(ltbcp = NULL, tbcp = a_tty.tg_bind[tbpcp->tbpc_flags]; tbcp != NULL;
3327 ltbcp = tbcp, tbcp = tbcp->tbc_next)
3328 if(tbcp->tbc_seq_len == sl && !memcmp(tbcp->tbc_seq, cpbase, sl)){
3329 tbpcp->tbpc_tbcp = tbcp;
3330 break;
3332 tbpcp->tbpc_ltbcp = ltbcp;
3333 tbpcp->tbpc_flags |= (f & a_TTY__BIND_MASK);
3336 /* Create single string expansion if so desired */
3337 if(isbindcmd){
3338 char *exp;
3340 exp = tbpcp->tbpc_exp.s;
3342 i = tbpcp->tbpc_exp.l;
3343 if(i > 0 && exp[i - 1] == '@'){
3344 while(--i > 0){
3345 if(!blankspacechar(exp[i - 1]))
3346 break;
3348 if(i == 0)
3349 goto jeempty;
3351 exp[tbpcp->tbpc_exp.l = i] = '\0';
3352 tbpcp->tbpc_flags |= a_TTY_BIND_NOCOMMIT;
3355 /* Reverse solidus cannot be placed last in expansion to avoid (at the
3356 * time of this writing) possible problems with newline escaping.
3357 * Don't care about (un)even number thereof */
3358 if(i > 0 && exp[i - 1] == '\\'){
3359 n_err(_("`%s': reverse solidus cannot be last in expansion: %s\n"),
3360 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3361 goto jleave;
3364 /* It may map to an internal MLE command! */
3365 for(i = 0; i < n_NELEM(a_tty_bind_fun_names); ++i)
3366 if(!asccasecmp(exp, a_tty_bind_fun_names[i])){
3367 tbpcp->tbpc_flags |= a_TTY_BIND_FUN_EXPAND(i) |
3368 a_TTY_BIND_FUN_INTERNAL |
3369 (head->next == NULL ? a_TTY_BIND_MLE1CNTRL : 0);
3370 if((options & OPT_D_V) && (tbpcp->tbpc_flags & a_TTY_BIND_NOCOMMIT))
3371 n_err(_("`%s': MLE commands can't be made editable via @: %s\n"),
3372 tbpcp->tbpc_cmd, exp);
3373 tbpcp->tbpc_flags &= ~a_TTY_BIND_NOCOMMIT;
3374 break;
3378 f |= a_TRUE_RV; /* TODO because we only now true and false; DEFUNCT.. */
3379 jleave:
3380 n_string_gut(shoup);
3381 NYD2_LEAVE;
3382 return (f & a_TRUE_RV) != 0;
3385 static void
3386 a_tty_bind_resolve(struct a_tty_bind_ctx *tbcp){
3387 char capname[a_TTY_BIND_CAPNAME_MAX +1];
3388 struct n_termcap_value tv;
3389 size_t len;
3390 bool_t isfirst; /* TODO For now: first char must be control! */
3391 char *cp, *next;
3392 NYD2_ENTER;
3394 n_UNINIT(next, NULL);
3395 for(cp = tbcp->tbc_cnv, isfirst = TRU1, len = tbcp->tbc_cnv_len;
3396 len > 0; isfirst = FAL0, cp = next){
3397 /* C99 */{
3398 si32_t i, j;
3400 i = n_UNALIGN(si32_t*,cp)[0];
3401 j = i & SI32_MAX;
3402 next = &cp[j];
3403 len -= j;
3404 if(i == j)
3405 continue;
3407 /* struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];} */
3408 cp += sizeof(si32_t);
3409 i = n_UNALIGN(si32_t*,cp)[0];
3410 cp += sizeof(si32_t);
3411 for(j = 0; j < i; ++j)
3412 capname[j] = n_UNALIGN(wc_t*,cp)[j];
3413 capname[j] = '\0';
3416 /* Use generic lookup mechanism if not a known query */
3417 /* C99 */{
3418 si32_t tq;
3420 tq = n_termcap_query_for_name(capname, n_TERMCAP_CAPTYPE_STRING);
3421 if(tq == -1){
3422 tv.tv_data.tvd_string = capname;
3423 tq = n__TERMCAP_QUERY_MAX1;
3426 if(tq < 0 || !n_termcap_query(tq, &tv)){
3427 if(options & OPT_D_V)
3428 n_err(_("`bind': unknown or unsupported capability: %s: %s\n"),
3429 capname, tbcp->tbc_seq);
3430 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3431 break;
3435 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3436 /* C99 */{
3437 size_t i;
3439 i = strlen(tv.tv_data.tvd_string);
3440 if(/*i > SI32_MAX ||*/ i >= PTR2SIZE(next - cp)){
3441 if(options & OPT_D_V)
3442 n_err(_("`bind': capability expansion too long: %s: %s\n"),
3443 capname, tbcp->tbc_seq);
3444 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3445 break;
3446 }else if(i == 0){
3447 if(options & OPT_D_V)
3448 n_err(_("`bind': empty capability expansion: %s: %s\n"),
3449 capname, tbcp->tbc_seq);
3450 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3451 break;
3452 }else if(isfirst && !cntrlchar(*tv.tv_data.tvd_string)){
3453 if(options & OPT_D_V)
3454 n_err(_("`bind': capability expansion doesn't start with "
3455 "control: %s: %s\n"), capname, tbcp->tbc_seq);
3456 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3457 break;
3459 n_UNALIGN(si32_t*,cp)[-1] = (si32_t)i;
3460 memcpy(cp, tv.tv_data.tvd_string, i);
3461 cp[i] = '\0';
3464 NYD2_LEAVE;
3467 static void
3468 a_tty_bind_del(struct a_tty_bind_parse_ctx *tbpcp){
3469 struct a_tty_bind_ctx *ltbcp, *tbcp;
3470 NYD2_ENTER;
3472 tbcp = tbpcp->tbpc_tbcp;
3474 if((ltbcp = tbpcp->tbpc_ltbcp) != NULL)
3475 ltbcp->tbc_next = tbcp->tbc_next;
3476 else
3477 a_tty.tg_bind[tbpcp->tbpc_flags] = tbcp->tbc_next;
3478 free(tbcp);
3480 --a_tty.tg_bind_cnt;
3481 a_tty.tg_bind_isdirty = TRU1;
3482 NYD2_LEAVE;
3485 static void
3486 a_tty_bind_tree_build(void){
3487 size_t i;
3488 NYD2_ENTER;
3490 for(i = 0; i < n__LEXINPUT_CTX_MAX1; ++i){
3491 struct a_tty_bind_ctx *tbcp;
3492 n_LCTAV(n_LEXINPUT_CTX_BASE == 0);
3494 /* Somewhat wasteful, but easier to handle: simply clone the entire
3495 * primary key onto the secondary one, then only modify it */
3496 for(tbcp = a_tty.tg_bind[n_LEXINPUT_CTX_BASE]; tbcp != NULL;
3497 tbcp = tbcp->tbc_next)
3498 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3499 a_tty__bind_tree_add(n_LEXINPUT_CTX_BASE, &a_tty.tg_bind_tree[i][0],
3500 tbcp);
3502 if(i != n_LEXINPUT_CTX_BASE)
3503 for(tbcp = a_tty.tg_bind[i]; tbcp != NULL; tbcp = tbcp->tbc_next)
3504 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3505 a_tty__bind_tree_add(i, &a_tty.tg_bind_tree[i][0], tbcp);
3508 a_tty.tg_bind_isbuild = TRU1;
3509 NYD2_LEAVE;
3512 static void
3513 a_tty_bind_tree_teardown(void){
3514 size_t i, j;
3515 NYD2_ENTER;
3517 memset(&a_tty.tg_bind_shcut_cancel[0], 0,
3518 sizeof(a_tty.tg_bind_shcut_cancel));
3519 memset(&a_tty.tg_bind_shcut_prompt_char[0], 0,
3520 sizeof(a_tty.tg_bind_shcut_prompt_char));
3522 for(i = 0; i < n__LEXINPUT_CTX_MAX1; ++i)
3523 for(j = 0; j < HSHSIZE; ++j)
3524 a_tty__bind_tree_free(a_tty.tg_bind_tree[i][j]);
3525 memset(&a_tty.tg_bind_tree[0], 0, sizeof(a_tty.tg_bind_tree));
3527 a_tty.tg_bind_isdirty = a_tty.tg_bind_isbuild = FAL0;
3528 NYD2_LEAVE;
3531 static void
3532 a_tty__bind_tree_add(ui32_t hmap_idx, struct a_tty_bind_tree *store[HSHSIZE],
3533 struct a_tty_bind_ctx *tbcp){
3534 ui32_t cnvlen;
3535 char const *cnvdat;
3536 struct a_tty_bind_tree *ntbtp;
3537 NYD2_ENTER;
3538 n_UNUSED(hmap_idx);
3540 ntbtp = NULL;
3542 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len; cnvlen > 0;){
3543 union {wchar_t const *wp; char const *cp;} u;
3544 si32_t entlen;
3546 /* {si32_t buf_len_iscap;} */
3547 entlen = *n_UNALIGN(si32_t const*,cnvdat);
3549 if(entlen & SI32_MIN){
3550 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;}
3551 * Note that empty capabilities result in DEFUNCT */
3552 for(u.cp = (char const*)&n_UNALIGN(si32_t const*,cnvdat)[2];
3553 *u.cp != '\0'; ++u.cp)
3554 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.cp, TRU1);
3555 assert(ntbtp != NULL);
3556 ntbtp->tbt_isseq_trail = TRU1;
3557 entlen &= SI32_MAX;
3558 }else{
3559 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3560 bool_t isseq;
3562 u.wp = (wchar_t const*)&n_UNALIGN(si32_t const*,cnvdat)[1];
3564 /* May be a special shortcut function? */
3565 if(ntbtp == NULL && (tbcp->tbc_flags & a_TTY_BIND_MLE1CNTRL)){
3566 char *cp;
3567 ui32_t ctx, fun;
3569 ctx = tbcp->tbc_flags & n__LEXINPUT_CTX_MASK;
3570 fun = tbcp->tbc_flags & a_TTY__BIND_FUN_MASK;
3572 if(fun == a_TTY_BIND_FUN_CANCEL){
3573 for(cp = &a_tty.tg_bind_shcut_cancel[ctx][0];
3574 PTRCMP(cp, <, &a_tty.tg_bind_shcut_cancel[ctx]
3575 [n_NELEM(a_tty.tg_bind_shcut_cancel[ctx]) - 1]); ++cp)
3576 if(*cp == '\0'){
3577 *cp = (char)*u.wp;
3578 break;
3580 }else if(fun == a_TTY_BIND_FUN_PROMPT_CHAR){
3581 for(cp = &a_tty.tg_bind_shcut_prompt_char[ctx][0];
3582 PTRCMP(cp, <, &a_tty.tg_bind_shcut_prompt_char[ctx]
3583 [n_NELEM(a_tty.tg_bind_shcut_prompt_char[ctx]) - 1]);
3584 ++cp)
3585 if(*cp == '\0'){
3586 *cp = (char)*u.wp;
3587 break;
3592 isseq = (u.wp[1] != '\0');
3593 for(; *u.wp != '\0'; ++u.wp)
3594 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.wp, isseq);
3595 if(isseq)
3596 ntbtp->tbt_isseq_trail = TRU1;
3599 cnvlen -= entlen;
3600 cnvdat += entlen;
3603 /* Should have been rendered defunctional at first instead */
3604 assert(ntbtp != NULL);
3605 ntbtp->tbt_bind = tbcp;
3606 NYD2_LEAVE;
3609 static struct a_tty_bind_tree *
3610 a_tty__bind_tree_add_wc(struct a_tty_bind_tree **treep,
3611 struct a_tty_bind_tree *parentp, wchar_t wc, bool_t isseq){
3612 struct a_tty_bind_tree *tbtp, *xtbtp;
3613 NYD2_ENTER;
3615 if(parentp == NULL){
3616 treep += wc % HSHSIZE;
3618 /* Having no parent also means that the tree slot is possibly empty */
3619 for(tbtp = *treep; tbtp != NULL;
3620 parentp = tbtp, tbtp = tbtp->tbt_sibling){
3621 if(tbtp->tbt_char != wc)
3622 continue;
3623 if(tbtp->tbt_isseq == isseq)
3624 goto jleave;
3625 /* isseq MUST be linked before !isseq, so record this "parent"
3626 * sibling, but continue searching for now */
3627 if(!isseq)
3628 parentp = tbtp;
3629 /* Otherwise it is impossible that we'll find what we look for */
3630 else{
3631 #ifdef HAVE_DEBUG
3632 while((tbtp = tbtp->tbt_sibling) != NULL)
3633 assert(tbtp->tbt_char != wc);
3634 #endif
3635 break;
3639 tbtp = smalloc(sizeof *tbtp);
3640 memset(tbtp, 0, sizeof *tbtp);
3641 tbtp->tbt_char = wc;
3642 tbtp->tbt_isseq = isseq;
3644 if(parentp == NULL){
3645 tbtp->tbt_sibling = *treep;
3646 *treep = tbtp;
3647 }else{
3648 tbtp->tbt_sibling = parentp->tbt_sibling;
3649 parentp->tbt_sibling = tbtp;
3651 }else{
3652 if((tbtp = *(treep = &parentp->tbt_childs)) != NULL){
3653 for(;; tbtp = xtbtp){
3654 if(tbtp->tbt_char == wc){
3655 if(tbtp->tbt_isseq == isseq)
3656 goto jleave;
3657 /* isseq MUST be linked before, so it is impossible that we'll
3658 * find what we look for */
3659 if(isseq){
3660 #ifdef HAVE_DEBUG
3661 while((tbtp = tbtp->tbt_sibling) != NULL)
3662 assert(tbtp->tbt_char != wc);
3663 #endif
3664 tbtp = NULL;
3665 break;
3669 if((xtbtp = tbtp->tbt_sibling) == NULL){
3670 treep = &tbtp->tbt_sibling;
3671 break;
3676 xtbtp = smalloc(sizeof *xtbtp);
3677 memset(xtbtp, 0, sizeof *xtbtp);
3678 xtbtp->tbt_parent = parentp;
3679 xtbtp->tbt_char = wc;
3680 xtbtp->tbt_isseq = isseq;
3681 tbtp = xtbtp;
3682 *treep = tbtp;
3684 jleave:
3685 NYD2_LEAVE;
3686 return tbtp;
3689 static void
3690 a_tty__bind_tree_free(struct a_tty_bind_tree *tbtp){
3691 NYD2_ENTER;
3692 while(tbtp != NULL){
3693 struct a_tty_bind_tree *tmp;
3695 if((tmp = tbtp->tbt_childs) != NULL)
3696 a_tty__bind_tree_free(tmp);
3698 tmp = tbtp->tbt_sibling;
3699 free(tbtp);
3700 tbtp = tmp;
3702 NYD2_LEAVE;
3704 # endif /* HAVE_KEY_BINDINGS */
3706 FL void
3707 n_tty_init(void){
3708 NYD_ENTER;
3710 if(ok_blook(line_editor_disable))
3711 goto jleave;
3713 /* Load the history file */
3714 # ifdef HAVE_HISTORY
3715 do/* for break */{
3716 long hs;
3717 char const *v;
3718 char *lbuf;
3719 FILE *f;
3720 size_t lsize, cnt, llen;
3722 a_TTY_HISTSIZE(hs);
3723 a_tty.tg_hist_size = 0;
3724 a_tty.tg_hist_size_max = (size_t)hs;
3725 if(hs == 0)
3726 break;
3728 a_TTY_HISTFILE(v);
3729 if(v == NULL)
3730 break;
3732 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
3733 f = fopen(v, "r"); /* TODO HISTFILE LOAD: use linebuf pool */
3734 if(f == NULL)
3735 goto jhist_done;
3736 (void)n_file_lock(fileno(f), FLT_READ, 0,0, UIZ_MAX);
3738 assert(!(pstate & PS_ROOT));
3739 pstate |= PS_ROOT; /* Allow calling addhist() */
3740 lbuf = NULL;
3741 lsize = 0;
3742 cnt = (size_t)fsize(f);
3743 while(fgetline(&lbuf, &lsize, &cnt, &llen, f, FAL0) != NULL){
3744 if(llen > 0 && lbuf[llen - 1] == '\n')
3745 lbuf[--llen] = '\0';
3746 if(llen == 0 || lbuf[0] == '#') /* xxx comments? noone! */
3747 continue;
3748 else{
3749 bool_t isgabby;
3751 isgabby = (lbuf[0] == '*');
3752 n_tty_addhist(lbuf + isgabby, isgabby);
3755 if(lbuf != NULL)
3756 free(lbuf);
3757 pstate &= ~PS_ROOT;
3759 fclose(f);
3760 jhist_done:
3761 rele_all_sigs(); /* XXX remove jumps */
3762 }while(0);
3763 # endif /* HAVE_HISTORY */
3765 /* Force immediate resolve for anything which follows */
3766 pstate |= PS_LINE_EDITOR_INIT;
3768 # ifdef HAVE_KEY_BINDINGS
3769 /* `bind's (and `unbind's) done from within resource files couldn't be
3770 * performed for real since our termcap driver wasn't yet loaded, and we
3771 * can't perform automatic init since the user may have disallowed so */
3772 /* C99 */{
3773 struct a_tty_bind_ctx *tbcp;
3774 enum n_lexinput_flags lif;
3776 for(lif = 0; lif < n__LEXINPUT_CTX_MAX1; ++lif)
3777 for(tbcp = a_tty.tg_bind[lif]; tbcp != NULL; tbcp = tbcp->tbc_next)
3778 if((tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
3779 a_TTY_BIND_RESOLVE)
3780 a_tty_bind_resolve(tbcp);
3783 /* And we want to (try to) install some default key bindings */
3784 if(!ok_blook(line_editor_no_defaults)){
3785 char buf[8];
3786 struct a_tty_bind_parse_ctx tbpc;
3787 struct a_tty_bind_builtin_tuple const *tbbtp, *tbbtp_max;
3788 ui32_t flags;
3790 buf[0] = '$', buf[1] = '\'', buf[2] = '\\', buf[3] = 'c',
3791 buf[5] = '\'', buf[6] = '\0';
3793 tbbtp = a_tty_bind_base_tuples;
3794 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_base_tuples)];
3795 flags = n_LEXINPUT_CTX_BASE;
3796 jbuiltin_redo:
3797 for(; tbbtp < tbbtp_max; ++tbbtp){
3798 memset(&tbpc, 0, sizeof tbpc);
3799 tbpc.tbpc_cmd = "bind";
3800 if(tbbtp->tbbt_iskey){
3801 buf[4] = tbbtp->tbbt_ckey;
3802 tbpc.tbpc_in_seq = buf;
3803 }else
3804 tbpc.tbpc_in_seq = savecatsep(":", '\0',
3805 n_termcap_name_of_query(tbbtp->tbbt_query));
3806 tbpc.tbpc_exp.s = n_UNCONST(tbbtp->tbbt_exp[0] == '\0'
3807 ? a_tty_bind_fun_names[(ui8_t)tbbtp->tbbt_exp[1]]
3808 : tbbtp->tbbt_exp);
3809 tbpc.tbpc_exp.l = strlen(tbpc.tbpc_exp.s);
3810 tbpc.tbpc_flags = flags;
3811 /* ..but don't want to overwrite any user settings */
3812 a_tty_bind_create(&tbpc, FAL0);
3814 if(flags == n_LEXINPUT_CTX_BASE){
3815 tbbtp = a_tty_bind_default_tuples;
3816 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_default_tuples)];
3817 flags = n_LEXINPUT_CTX_DEFAULT;
3818 goto jbuiltin_redo;
3821 # endif /* HAVE_KEY_BINDINGS */
3823 jleave:
3824 NYD_LEAVE;
3827 FL void
3828 n_tty_destroy(void){
3829 NYD_ENTER;
3831 if(!(pstate & PS_LINE_EDITOR_INIT))
3832 goto jleave;
3834 # ifdef HAVE_HISTORY
3835 do/* for break */{
3836 long hs;
3837 char const *v;
3838 struct a_tty_hist *thp;
3839 bool_t dogabby;
3840 FILE *f;
3842 a_TTY_HISTSIZE(hs);
3843 if(hs == 0)
3844 break;
3846 a_TTY_HISTFILE(v);
3847 if(v == NULL)
3848 break;
3850 dogabby = ok_blook(history_gabby_persist);
3852 if((thp = a_tty.tg_hist) != NULL)
3853 for(; thp->th_older != NULL; thp = thp->th_older)
3854 if((dogabby || !thp->th_isgabby) && --hs == 0)
3855 break;
3857 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
3858 f = fopen(v, "w"); /* TODO temporary + rename?! */
3859 if(f == NULL)
3860 goto jhist_done;
3861 (void)n_file_lock(fileno(f), FLT_WRITE, 0,0, UIZ_MAX);
3863 for(; thp != NULL; thp = thp->th_younger){
3864 if(dogabby || !thp->th_isgabby){
3865 if(thp->th_isgabby)
3866 putc('*', f);
3867 fwrite(thp->th_dat, sizeof *thp->th_dat, thp->th_len, f);
3868 putc('\n', f);
3871 fclose(f);
3872 jhist_done:
3873 rele_all_sigs(); /* XXX remove jumps */
3874 }while(0);
3875 # endif /* HAVE_HISTORY */
3877 # if defined HAVE_KEY_BINDINGS && defined HAVE_DEBUG
3878 c_unbind(n_UNCONST("* *"));
3879 # endif
3881 # ifdef HAVE_DEBUG
3882 memset(&a_tty, 0, sizeof a_tty);
3883 # endif
3884 DBG( pstate &= ~PS_LINE_EDITOR_INIT; )
3885 jleave:
3886 NYD_LEAVE;
3889 FL void
3890 n_tty_signal(int sig){
3891 sigset_t nset, oset;
3892 NYD_X; /* Signal handler */
3894 switch(sig){
3895 # ifdef SIGWINCH
3896 case SIGWINCH:
3897 /* We don't deal with SIGWINCH, yet get called from main.c.
3898 * Note this case might get called even if !PS_LINE_EDITOR_INIT */
3899 break;
3900 # endif
3901 default:
3902 a_tty_term_mode(FAL0);
3903 n_TERMCAP_SUSPEND(TRU1);
3904 a_tty_sigs_down();
3906 sigemptyset(&nset);
3907 sigaddset(&nset, sig);
3908 sigprocmask(SIG_UNBLOCK, &nset, &oset);
3909 n_raise(sig);
3910 /* When we come here we'll continue editing, so reestablish */
3911 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
3913 a_tty_sigs_up();
3914 n_TERMCAP_RESUME(TRU1);
3915 a_tty_term_mode(TRU1);
3916 a_tty.tg_line->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
3917 break;
3921 FL int
3922 (n_tty_readline)(enum n_lexinput_flags lif, char const *prompt,
3923 char **linebuf, size_t *linesize, size_t n n_MEMORY_DEBUG_ARGS){
3924 struct a_tty_line tl;
3925 struct n_string xprompt;
3926 # ifdef HAVE_COLOUR
3927 char *posbuf, *pos;
3928 # endif
3929 ssize_t nn;
3930 ui32_t plen, pwidth;
3931 char const *orig_prompt;
3932 NYD_ENTER;
3933 n_UNUSED(lif);
3934 n_UNINIT(pwidth, 0);
3935 n_UNINIT(plen, 0);
3937 assert(!ok_blook(line_editor_disable));
3938 if(!(pstate & PS_LINE_EDITOR_INIT))
3939 n_tty_init();
3940 assert(pstate & PS_LINE_EDITOR_INIT);
3942 if(!(lif & n_LEXINPUT_PROMPT_NONE))
3943 n_string_creat_auto(&xprompt);
3944 orig_prompt = prompt;
3945 jredo:
3946 # ifdef HAVE_COLOUR
3947 n_colour_env_create(n_COLOUR_CTX_MLE, FAL0);
3948 # endif
3950 if(!(lif & n_LEXINPUT_PROMPT_NONE)){
3951 pwidth = n_tty_create_prompt(&xprompt, orig_prompt, lif);
3952 plen = (ui32_t)xprompt.s_len;
3953 prompt = (pwidth == 0) ? NULL : n_string_cp_const(&xprompt);
3956 # ifdef HAVE_COLOUR
3957 /* C99 */{
3958 char const *ccol;
3959 struct n_colour_pen *ccp;
3960 struct str const *sp;
3962 /* .tl_pos_buf is a hack */
3963 posbuf = pos = NULL;
3964 if((ccp = n_colour_pen_create(n_COLOUR_ID_MLE_POSITION, NULL)) != NULL &&
3965 (sp = n_colour_pen_to_str(ccp)) != NULL){
3966 ccol = sp->s;
3967 if((sp = n_colour_reset_to_str()) != NULL){
3968 size_t l1, l2;
3970 l1 = strlen(ccol);
3971 l2 = strlen(sp->s);
3972 posbuf = salloc(l1 + 4 + l2 +1);
3973 memcpy(posbuf, ccol, l1);
3974 pos = &posbuf[l1];
3975 memcpy(&pos[4], sp->s, ++l2);
3978 if(posbuf == NULL){
3979 posbuf = pos = salloc(4 +1);
3980 pos[4] = '\0';
3983 # endif /* HAVE_COLOUR */
3985 memset(&tl, 0, sizeof tl);
3987 # ifdef HAVE_KEY_BINDINGS
3988 /* C99 */{
3989 char const *cp = ok_vlook(bind_timeout);
3991 if(cp != NULL){
3992 ul_i ul;
3994 if((ul = strtoul(cp, NULL, 0)) > 0 &&
3995 /* Convert to tenths of a second, unfortunately */
3996 (ul = (ul + 99) / 100) <= a_TTY_BIND_TIMEOUT_MAX)
3997 tl.tl_bind_timeout = (ui8_t)ul;
3998 else if(options & OPT_D_V)
3999 n_err(_("Ignoring invalid *bind-timeout*: %s\n"), cp);
4003 if(a_tty.tg_bind_isdirty)
4004 a_tty_bind_tree_teardown();
4005 if(a_tty.tg_bind_cnt > 0 && !a_tty.tg_bind_isbuild)
4006 a_tty_bind_tree_build();
4007 tl.tl_bind_tree_hmap = &a_tty.tg_bind_tree[lif & n__LEXINPUT_CTX_MASK];
4008 tl.tl_bind_shcut_cancel =
4009 &a_tty.tg_bind_shcut_cancel[lif & n__LEXINPUT_CTX_MASK];
4010 tl.tl_bind_shcut_prompt_char =
4011 &a_tty.tg_bind_shcut_prompt_char[lif & n__LEXINPUT_CTX_MASK];
4012 # endif /* HAVE_KEY_BINDINGS */
4014 if(!(lif & n_LEXINPUT_PROMPT_NONE) && pwidth > 0){
4015 tl.tl_prompt = prompt;
4016 tl.tl_prompt_length = plen;
4017 tl.tl_prompt_width = pwidth;
4019 # ifdef HAVE_COLOUR
4020 tl.tl_pos_buf = posbuf;
4021 tl.tl_pos = pos;
4022 # endif
4024 tl.tl_line.cbuf = *linebuf;
4025 if(n != 0){
4026 tl.tl_defc.s = savestrbuf(*linebuf, n);
4027 tl.tl_defc.l = n;
4029 tl.tl_x_buf = linebuf;
4030 tl.tl_x_bufsize = linesize;
4032 a_tty.tg_line = &tl;
4033 a_tty_sigs_up();
4034 n_TERMCAP_RESUME(FAL0);
4035 a_tty_term_mode(TRU1);
4036 nn = a_tty_readline(&tl, n n_MEMORY_DEBUG_ARGSCALL);
4037 a_tty_term_mode(FAL0);
4038 n_TERMCAP_SUSPEND(FAL0);
4039 a_tty_sigs_down();
4040 a_tty.tg_line = NULL;
4042 # ifdef HAVE_COLOUR
4043 n_colour_env_gut(n_tty_fp);
4044 # endif
4046 if(tl.tl_reenter_after_cmd != NULL){
4047 n_source_command(lif, tl.tl_reenter_after_cmd);
4048 n = (nn <= 0) ? 0 : nn;
4049 if(!ok_blook(line_editor_disable))
4050 goto jredo;
4051 nn = (n_lex_input)(lif, orig_prompt, linebuf, linesize,
4052 (n == 0 ? n_empty : savestrbuf(*linebuf, n))
4053 n_MEMORY_DEBUG_ARGSCALL);
4055 NYD_LEAVE;
4056 return (int)nn;
4059 FL void
4060 n_tty_addhist(char const *s, bool_t isgabby){
4061 # ifdef HAVE_HISTORY
4062 /* Super-Heavy-Metal: block all sigs, avoid leaks+ on jump */
4063 ui32_t l;
4064 struct a_tty_hist *thp, *othp, *ythp;
4065 # endif
4066 NYD_ENTER;
4067 n_UNUSED(s);
4068 n_UNUSED(isgabby);
4070 # ifdef HAVE_HISTORY
4071 a_TTY_CHECK_ADDHIST(s, isgabby, goto j_leave);
4072 if(a_tty.tg_hist_size_max == 0)
4073 goto j_leave;
4075 l = (ui32_t)strlen(s);
4077 /* Eliminating duplicates is expensive, but simply inacceptable so
4078 * during the load of a potentially large history file! */
4079 if(pstate & PS_LINE_EDITOR_INIT)
4080 for(thp = a_tty.tg_hist; thp != NULL; thp = thp->th_older)
4081 if(thp->th_len == l && !strcmp(thp->th_dat, s)){
4082 hold_all_sigs(); /* TODO */
4083 if(thp->th_isgabby)
4084 thp->th_isgabby = !!isgabby;
4085 othp = thp->th_older;
4086 ythp = thp->th_younger;
4087 if(othp != NULL)
4088 othp->th_younger = ythp;
4089 else
4090 a_tty.tg_hist_tail = ythp;
4091 if(ythp != NULL)
4092 ythp->th_older = othp;
4093 else
4094 a_tty.tg_hist = othp;
4095 goto jleave;
4097 hold_all_sigs();
4099 ++a_tty.tg_hist_size;
4100 if((pstate & PS_LINE_EDITOR_INIT) &&
4101 a_tty.tg_hist_size > a_tty.tg_hist_size_max){
4102 --a_tty.tg_hist_size;
4103 if((thp = a_tty.tg_hist_tail) != NULL){
4104 if((a_tty.tg_hist_tail = thp->th_younger) == NULL)
4105 a_tty.tg_hist = NULL;
4106 else
4107 a_tty.tg_hist_tail->th_older = NULL;
4108 free(thp);
4112 thp = smalloc(n_VSTRUCT_SIZEOF(struct a_tty_hist, th_dat) + l +1);
4113 thp->th_isgabby = !!isgabby;
4114 thp->th_len = l;
4115 memcpy(thp->th_dat, s, l +1);
4116 jleave:
4117 if((thp->th_older = a_tty.tg_hist) != NULL)
4118 a_tty.tg_hist->th_younger = thp;
4119 else
4120 a_tty.tg_hist_tail = thp;
4121 thp->th_younger = NULL;
4122 a_tty.tg_hist = thp;
4124 rele_all_sigs();
4125 j_leave:
4126 # endif
4127 NYD_LEAVE;
4130 # ifdef HAVE_HISTORY
4131 FL int
4132 c_history(void *v){
4133 C_HISTORY_SHARED;
4135 jlist:{
4136 FILE *fp;
4137 size_t i, b;
4138 struct a_tty_hist *thp;
4140 if(a_tty.tg_hist == NULL)
4141 goto jleave;
4143 if((fp = Ftmp(NULL, "hist", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
4144 n_perr(_("tmpfile"), 0);
4145 v = NULL;
4146 goto jleave;
4149 i = a_tty.tg_hist_size;
4150 b = 0;
4151 for(thp = a_tty.tg_hist; thp != NULL;
4152 --i, b += thp->th_len, thp = thp->th_older)
4153 fprintf(fp,
4154 "%c%4" PRIuZ ". %-50.50s (%4" PRIuZ "+%2" PRIu32 " B)\n",
4155 (thp->th_isgabby ? '*' : ' '), i, thp->th_dat, b, thp->th_len);
4157 page_or_print(fp, i);
4158 Fclose(fp);
4160 goto jleave;
4162 jclear:{
4163 struct a_tty_hist *thp;
4165 while((thp = a_tty.tg_hist) != NULL){
4166 a_tty.tg_hist = thp->th_older;
4167 free(thp);
4169 a_tty.tg_hist_tail = NULL;
4170 a_tty.tg_hist_size = 0;
4172 goto jleave;
4174 jentry:{
4175 struct a_tty_hist *thp;
4177 if(UICMP(z, entry, <=, a_tty.tg_hist_size)){
4178 entry = (long)a_tty.tg_hist_size - entry;
4179 for(thp = a_tty.tg_hist;; thp = thp->th_older)
4180 if(thp == NULL)
4181 break;
4182 else if(entry-- != 0)
4183 continue;
4184 else{
4185 v = temporary_arg_v_store = thp->th_dat;
4186 goto jleave;
4189 v = NULL;
4191 goto jleave;
4193 # endif /* HAVE_HISTORY */
4195 # ifdef HAVE_KEY_BINDINGS
4196 FL int
4197 c_bind(void *v){
4198 n_CMD_ARG_DESC_SUBCLASS_DEF(bind, 3, a_tty_bind_cad) { /* TODO cmd_tab.h */
4199 {n_CMD_ARG_DESC_STRING, 0},
4200 {n_CMD_ARG_DESC_WYSH | n_CMD_ARG_DESC_OPTION |
4201 n_CMD_ARG_DESC_HONOUR_STOP,
4202 n_SHEXP_PARSE_DRYRUN | n_SHEXP_PARSE_LOG},
4203 {n_CMD_ARG_DESC_WYSH | n_CMD_ARG_DESC_OPTION | n_CMD_ARG_DESC_GREEDY |
4204 n_CMD_ARG_DESC_HONOUR_STOP,
4205 n_SHEXP_PARSE_IGNORE_EMPTY}
4206 } n_CMD_ARG_DESC_SUBCLASS_DEF_END;
4207 struct n_cmd_arg_ctx cac;
4208 struct a_tty_bind_ctx *tbcp;
4209 enum n_lexinput_flags lif;
4210 bool_t aster, show;
4211 union {char const *cp; char *p; char c;} c;
4212 NYD_ENTER;
4214 cac.cac_desc = n_CMD_ARG_DESC_SUBCLASS_CAST(&a_tty_bind_cad);
4215 cac.cac_indat = v;
4216 cac.cac_inlen = UIZ_MAX;
4217 if(!n_cmd_arg_parse(&cac)){
4218 v = NULL;
4219 goto jleave;
4222 c.cp = cac.cac_arg->ca_arg.ca_str.s;
4223 if(cac.cac_no == 1)
4224 show = TRU1;
4225 else
4226 show = !asccasecmp(cac.cac_arg->ca_next->ca_arg.ca_str.s, "show");
4227 aster = FAL0;
4229 if((lif = a_tty_bind_ctx_find(c.cp)) == (enum n_lexinput_flags)-1){
4230 if(!(aster = n_is_all_or_aster(c.cp)) || !show){
4231 n_err(_("`bind': invalid context: %s\n"), c.cp);
4232 v = NULL;
4233 goto jleave;
4235 lif = 0;
4238 if(show){
4239 ui32_t lns;
4240 FILE *fp;
4242 if((fp = Ftmp(NULL, "bind", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
4243 n_perr(_("tmpfile"), 0);
4244 v = NULL;
4245 goto jleave;
4248 lns = 0;
4249 for(;;){
4250 for(tbcp = a_tty.tg_bind[lif]; tbcp != NULL;
4251 ++lns, tbcp = tbcp->tbc_next){
4252 /* Print the bytes of resolved terminal capabilities, then */
4253 if((options & OPT_D_V) &&
4254 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)
4255 ) == a_TTY_BIND_RESOLVE){
4256 char cbuf[8];
4257 union {wchar_t const *wp; char const *cp;} u;
4258 si32_t entlen;
4259 ui32_t cnvlen;
4260 char const *cnvdat, *bsep, *cbufp;
4262 putc('#', fp);
4263 putc(' ', fp);
4265 cbuf[0] = '=', cbuf[2] = '\0';
4266 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len;
4267 cnvlen > 0;){
4268 if(cnvdat != tbcp->tbc_cnv)
4269 putc(',', fp);
4271 /* {si32_t buf_len_iscap;} */
4272 entlen = *n_UNALIGN(si32_t const*,cnvdat);
4273 if(entlen & SI32_MIN){
4274 /* struct{si32_t buf_len_iscap; si32_t cap_len;
4275 * char buf[]+NUL;} */
4276 for(bsep = n_empty,
4277 u.cp = (char const*)
4278 &n_UNALIGN(si32_t const*,cnvdat)[2];
4279 (c.c = *u.cp) != '\0'; ++u.cp){
4280 if(asciichar(c.c) && !cntrlchar(c.c))
4281 cbuf[1] = c.c, cbufp = cbuf;
4282 else
4283 cbufp = n_empty;
4284 fprintf(fp, "%s%02X%s",
4285 bsep, (ui32_t)(ui8_t)c.c, cbufp);
4286 bsep = " ";
4288 entlen &= SI32_MAX;
4289 }else
4290 putc('-', fp);
4292 cnvlen -= entlen;
4293 cnvdat += entlen;
4296 fputs("\n ", fp);
4297 ++lns;
4300 fprintf(fp, "%sbind %s %s %s%s%s\n",
4301 ((tbcp->tbc_flags & a_TTY_BIND_DEFUNCT)
4302 /* I18N: `bind' sequence not working, either because it is
4303 * I18N: using Unicode and that is not available in the locale,
4304 * I18N: or a termcap(5)/terminfo(5) sequence won't work out */
4305 ? _("# <Defunctional> ") : n_empty),
4306 a_tty_bind_ctx_maps[lif].tbcm_name, tbcp->tbc_seq,
4307 n_shexp_quote_cp(tbcp->tbc_exp, TRU1),
4308 (tbcp->tbc_flags & a_TTY_BIND_NOCOMMIT ? "@" : n_empty),
4309 (!(options & OPT_D_VV) ? n_empty
4310 : (tbcp->tbc_flags & a_TTY_BIND_FUN_INTERNAL
4311 ? _(" # MLE internal") : n_empty))
4314 if(!aster || ++lif >= n__LEXINPUT_CTX_MAX1)
4315 break;
4317 page_or_print(fp, lns);
4319 Fclose(fp);
4320 }else{
4321 struct a_tty_bind_parse_ctx tbpc;
4322 struct n_string store;
4324 memset(&tbpc, 0, sizeof tbpc);
4325 tbpc.tbpc_cmd = a_tty_bind_cad.cad_name;
4326 tbpc.tbpc_in_seq = cac.cac_arg->ca_next->ca_arg.ca_str.s;
4327 tbpc.tbpc_exp.s = n_string_cp(n_cmd_arg_join_greedy(&cac,
4328 n_string_creat_auto(&store)));
4329 tbpc.tbpc_exp.l = store.s_len;
4330 tbpc.tbpc_flags = lif;
4331 if(!a_tty_bind_create(&tbpc, TRU1))
4332 v = NULL;
4333 n_string_gut(&store);
4335 jleave:
4336 NYD_LEAVE;
4337 return (v != NULL) ? EXIT_OK : EXIT_ERR;
4340 FL int
4341 c_unbind(void *v){
4342 n_CMD_ARG_DESC_SUBCLASS_DEF(unbind, 2, a_tty_unbind_cad) {/* TODO cmd_tab.h*/
4343 {n_CMD_ARG_DESC_STRING, 0},
4344 {n_CMD_ARG_DESC_WYSH | n_CMD_ARG_DESC_HONOUR_STOP,
4345 n_SHEXP_PARSE_DRYRUN | n_SHEXP_PARSE_LOG}
4346 } n_CMD_ARG_DESC_SUBCLASS_DEF_END;
4347 struct a_tty_bind_parse_ctx tbpc;
4348 struct n_cmd_arg_ctx cac;
4349 struct a_tty_bind_ctx *tbcp;
4350 enum n_lexinput_flags lif;
4351 bool_t aster;
4352 union {char const *cp; char *p;} c;
4353 NYD_ENTER;
4355 cac.cac_desc = n_CMD_ARG_DESC_SUBCLASS_CAST(&a_tty_unbind_cad);
4356 cac.cac_indat = v;
4357 cac.cac_inlen = UIZ_MAX;
4358 if(!n_cmd_arg_parse(&cac)){
4359 v = NULL;
4360 goto jleave;
4363 c.cp = cac.cac_arg->ca_arg.ca_str.s;
4364 aster = FAL0;
4366 if((lif = a_tty_bind_ctx_find(c.cp)) == (enum n_lexinput_flags)-1){
4367 if(!(aster = n_is_all_or_aster(c.cp))){
4368 n_err(_("`unbind': invalid context: %s\n"), c.cp);
4369 v = NULL;
4370 goto jleave;
4372 lif = 0;
4375 c.cp = cac.cac_arg->ca_next->ca_arg.ca_str.s;
4376 jredo:
4377 if(n_is_all_or_aster(c.cp)){
4378 while((tbcp = a_tty.tg_bind[lif]) != NULL){
4379 memset(&tbpc, 0, sizeof tbpc);
4380 tbpc.tbpc_tbcp = tbcp;
4381 tbpc.tbpc_flags = lif;
4382 a_tty_bind_del(&tbpc);
4384 }else{
4385 memset(&tbpc, 0, sizeof tbpc);
4386 tbpc.tbpc_cmd = a_tty_unbind_cad.cad_name;
4387 tbpc.tbpc_in_seq = c.cp;
4388 tbpc.tbpc_flags = lif;
4390 if(n_UNLIKELY(!a_tty_bind_parse(FAL0, &tbpc)))
4391 v = NULL;
4392 else if(n_UNLIKELY((tbcp = tbpc.tbpc_tbcp) == NULL)){
4393 n_err(_("`unbind': no such `bind'ing: %s %s\n"),
4394 a_tty_bind_ctx_maps[lif].tbcm_name, c.cp);
4395 v = NULL;
4396 }else
4397 a_tty_bind_del(&tbpc);
4400 if(aster && ++lif < n__LEXINPUT_CTX_MAX1)
4401 goto jredo;
4402 jleave:
4403 NYD_LEAVE;
4404 return (v != NULL) ? EXIT_OK : EXIT_ERR;
4406 # endif /* HAVE_KEY_BINDINGS */
4408 #else /* HAVE_MLE */
4410 * The really-nothing-at-all implementation
4413 FL void
4414 n_tty_init(void){
4415 NYD_ENTER;
4416 NYD_LEAVE;
4419 FL void
4420 n_tty_destroy(void){
4421 NYD_ENTER;
4422 NYD_LEAVE;
4425 FL void
4426 n_tty_signal(int sig){
4427 NYD_X; /* Signal handler */
4428 n_UNUSED(sig);
4430 # ifdef HAVE_TERMCAP
4431 switch(sig){
4432 default:{
4433 sigset_t nset, oset;
4435 n_TERMCAP_SUSPEND(TRU1);
4436 a_tty_sigs_down();
4438 sigemptyset(&nset);
4439 sigaddset(&nset, sig);
4440 sigprocmask(SIG_UNBLOCK, &nset, &oset);
4441 n_raise(sig);
4442 /* When we come here we'll continue editing, so reestablish */
4443 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
4445 a_tty_sigs_up();
4446 n_TERMCAP_RESUME(TRU1);
4447 break;
4450 # endif /* HAVE_TERMCAP */
4453 FL int
4454 (n_tty_readline)(enum n_lexinput_flags lif, char const *prompt,
4455 char **linebuf, size_t *linesize, size_t n n_MEMORY_DEBUG_ARGS){
4456 struct n_string xprompt;
4457 int rv;
4458 NYD_ENTER;
4460 if(!(lif & n_LEXINPUT_PROMPT_NONE)){
4461 if(n_tty_create_prompt(n_string_creat_auto(&xprompt), prompt, lif) > 0){
4462 fwrite(xprompt.s_dat, 1, xprompt.s_len, n_tty_fp);
4463 fflush(n_tty_fp);
4467 # ifdef HAVE_TERMCAP
4468 a_tty_sigs_up();
4469 n_TERMCAP_RESUME(FAL0);
4470 # endif
4471 rv = (readline_restart)(stdin, linebuf, linesize,n n_MEMORY_DEBUG_ARGSCALL);
4472 # ifdef HAVE_TERMCAP
4473 n_TERMCAP_SUSPEND(FAL0);
4474 a_tty_sigs_down();
4475 # endif
4476 NYD_LEAVE;
4477 return rv;
4480 FL void
4481 n_tty_addhist(char const *s, bool_t isgabby){
4482 NYD_ENTER;
4483 n_UNUSED(s);
4484 n_UNUSED(isgabby);
4485 NYD_LEAVE;
4487 #endif /* nothing at all */
4489 #undef a_TTY_SIGNALS
4490 /* s-it-mode */