head.c:a_head_idna_apply(): FIX IDNA result length calculation!
[s-mailx.git] / tty.c
blob9e4bbdc372146b0287462824f8c023d998c743a3
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ TTY (command line) editing interaction.
3 *@ Because we have (had) multiple line-editor implementations, including our
4 *@ own M(ailx) L(ine) E(ditor), change the file layout a bit and place those
5 *@ one after the other below the other externals.
7 * Copyright (c) 2012 - 2017 Steffen (Daode) Nurpmeso <steffen@sdaoden.eu>.
9 * Permission to use, copy, modify, and/or distribute this software for any
10 * purpose with or without fee is hereby granted, provided that the above
11 * copyright notice and this permission notice appear in all copies.
13 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
14 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
15 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
16 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
17 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21 #undef n_FILE
22 #define n_FILE tty
24 #ifndef HAVE_AMALGAMATION
25 # include "nail.h"
26 #endif
28 #if defined HAVE_MLE || defined HAVE_TERMCAP
29 # define a_TTY_SIGNALS
30 #endif
32 /* 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,
1298 DBG(lstcur COMMA) cur,
1299 vi_left, /*vi_right,*/ phy_nxtcur;
1300 struct a_tty_cell const *tccp, *tcp_left, *tcp_right, *tcxp;
1301 NYD2_ENTER;
1302 n_LCTA(UICMP(64, a__LAST, <, UI32_MAX), "Flag bits excess storage datatype");
1304 f = tlp->tl_vi_flags;
1305 tlp->tl_vi_flags = (f & ~(a_TTY_VF_REFRESH | a_PERSIST_MASK)) |
1306 a_TTY_VF_SYNC;
1307 f |= a_TRUE_RV;
1308 if((w = tlp->tl_prompt_width) > 0)
1309 f |= a_HAVE_PROMPT;
1310 f |= a_HAVE_POSITION;
1312 /* XXX We don't have a OnTerminalResize event (see main.c) yet, so we need
1313 * XXX to reevaluate our circumstances over and over again */
1314 /* Don't display prompt or position indicator on very small screens */
1315 if((phy_wid_base = (ui32_t)scrnwidth) <= a_TTY_WIDTH_RIPOFF)
1316 f &= ~(a_HAVE_PROMPT | a_HAVE_POSITION);
1317 else{
1318 phy_wid_base -= a_TTY_WIDTH_RIPOFF;
1320 /* Disable the prompt if the screen is too small; due to lack of some
1321 * indicator simply add a second ripoff */
1322 if((f & a_HAVE_PROMPT) && w + a_TTY_WIDTH_RIPOFF >= phy_wid_base)
1323 f &= ~a_HAVE_PROMPT;
1326 phy_wid = phy_wid_base;
1327 phy_base = 0;
1328 phy_cur = tlp->tl_phy_cursor;
1329 cnt = tlp->tl_count;
1330 DBG( lstcur = tlp->tl_lst_cursor; )
1332 /* XXX Assume dirty screen if shrunk */
1333 if(cnt < tlp->tl_lst_count)
1334 f |= a_TTY_VF_MOD_DIRTY;
1336 /* TODO Without HAVE_TERMCAP, it would likely be much cheaper to simply
1337 * TODO always "cr + paint + ce + ch", since ce is simulated via spaces.. */
1339 /* Quickshot: if the line is empty, possibly print prompt and out */
1340 if(cnt == 0){
1341 /* In that special case dirty anything if it seems better */
1342 if((f & a_TTY_VF_MOD_CONTENT) || tlp->tl_lst_count > 0)
1343 f |= a_TTY_VF_MOD_DIRTY;
1345 if((f & a_TTY_VF_MOD_DIRTY) && phy_cur != 0){
1346 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
1347 goto jerr;
1348 phy_cur = 0;
1351 if((f & (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)) ==
1352 (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)){
1353 if(fputs(tlp->tl_prompt, n_tty_fp) == EOF)
1354 goto jerr;
1355 phy_cur = tlp->tl_prompt_width + 1;
1358 /* May need to clear former line content */
1359 if((f & a_TTY_VF_MOD_DIRTY) &&
1360 !n_termcap_cmd(n_TERMCAP_CMD_ce, phy_cur, -1))
1361 goto jerr;
1363 tlp->tl_phy_start = tlp->tl_line.cells;
1364 goto jleave;
1367 /* Try to get an idea of the visual window */
1369 /* Find the left visual boundary */
1370 phy_wid = (phy_wid >> 1) + (phy_wid >> 2);
1371 if((cur = tlp->tl_cursor) == cnt)
1372 --cur;
1374 w = (tcp_left = tccp = tlp->tl_line.cells + cur)->tc_width;
1375 if(w == UI8_MAX) /* TODO yet TAB == SPC */
1376 w = 1;
1377 while(tcp_left > tlp->tl_line.cells){
1378 ui16_t cw = tcp_left[-1].tc_width;
1380 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1381 cw = 1;
1382 if(w + cw >= phy_wid)
1383 break;
1384 w += cw;
1385 --tcp_left;
1387 vi_left = w;
1389 /* If the left hand side of our visual viewpoint consumes less than half
1390 * of the screen width, show the prompt */
1391 if(tcp_left == tlp->tl_line.cells)
1392 f |= a_LEFT_MIN;
1394 if((f & (a_LEFT_MIN | a_HAVE_PROMPT)) == (a_LEFT_MIN | a_HAVE_PROMPT) &&
1395 w + tlp->tl_prompt_width < phy_wid){
1396 phy_base = tlp->tl_prompt_width;
1397 f |= a_SHOW_PROMPT;
1400 /* Then search for right boundary. We always leave the rightmost column
1401 * empty because some terminals [cw]ould wrap the line if we write into
1402 * that. XXX terminfo(5)/termcap(5) have the semi_auto_right_margin/sam/YE
1403 * XXX capability to indicate this, but we don't look at that */
1404 phy_wid = phy_wid_base - phy_base;
1405 tcp_right = tlp->tl_line.cells + cnt;
1407 while(&tccp[1] < tcp_right){
1408 ui16_t cw = tccp[1].tc_width;
1409 ui32_t i;
1411 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1412 cw = 1;
1413 i = w + cw;
1414 if(i > phy_wid)
1415 break;
1416 w = i;
1417 ++tccp;
1419 /*vi_right = w - vi_left;*/
1421 /* If the complete line including prompt fits on the screen, show prompt */
1422 if(--tcp_right == tccp){
1423 f |= a_RIGHT_MAX;
1425 /* Since we did brute-force walk also for the left boundary we may end up
1426 * in a situation were anything effectively fits on the screen, including
1427 * the prompt that is, but were we don't recognize this since we
1428 * restricted the search to fit in some visual viewpoint. Therefore try
1429 * again to extend the left boundary to overcome that */
1430 if(!(f & a_LEFT_MIN)){
1431 struct a_tty_cell const *tc1p = tlp->tl_line.cells;
1432 ui32_t vil1 = vi_left;
1434 assert(!(f & a_SHOW_PROMPT));
1435 w += tlp->tl_prompt_width;
1436 for(tcxp = tcp_left;;){
1437 ui32_t i = tcxp[-1].tc_width;
1439 if(i == UI8_MAX) /* TODO yet TAB == SPC */
1440 i = 1;
1441 vil1 += i;
1442 i += w;
1443 if(i > phy_wid)
1444 break;
1445 w = i;
1446 if(--tcxp == tc1p){
1447 tcp_left = tc1p;
1448 vi_left = vil1;
1449 f |= a_LEFT_MIN;
1450 break;
1453 /*w -= tlp->tl_prompt_width;*/
1456 tcp_right = tccp;
1457 tccp = tlp->tl_line.cells + cur;
1459 if((f & (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT | a_SHOW_PROMPT)) ==
1460 (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT) &&
1461 w + tlp->tl_prompt_width <= phy_wid){
1462 phy_wid -= (phy_base = tlp->tl_prompt_width);
1463 f |= a_SHOW_PROMPT;
1466 /* Try to avoid repainting the complete line - this is possible if the
1467 * cursor "did not leave the screen" and the prompt status hasn't changed.
1468 * I.e., after clamping virtual viewpoint, compare relation to physical */
1469 if((f & (a_TTY_VF_MOD_SINGLE/*FIXME*/ |
1470 a_TTY_VF_MOD_CONTENT/* xxx */ | a_TTY_VF_MOD_DIRTY)) ||
1471 (tcxp = tlp->tl_phy_start) == NULL ||
1472 tcxp > tccp || tcxp <= tcp_right)
1473 f |= a_TTY_VF_MOD_DIRTY;
1474 else{
1475 f |= a_TTY_VF_MOD_DIRTY;
1476 #if 0
1477 struct a_tty_cell const *tcyp;
1478 si32_t cur_displace;
1479 ui32_t phy_lmargin, phy_rmargin, fx, phy_displace;
1481 phy_lmargin = (fx = phy_wid) / 100;
1482 phy_rmargin = fx - (phy_lmargin * a_TTY_SCROLL_MARGIN_RIGHT);
1483 phy_lmargin *= a_TTY_SCROLL_MARGIN_LEFT;
1484 fx = (f & (a_SHOW_PROMPT | a_VISIBLE_PROMPT));
1486 if(fx == 0 || fx == (a_SHOW_PROMPT | a_VISIBLE_PROMPT)){
1488 #endif
1490 goto jpaint;
1492 /* We know what we have to paint, start synchronizing */
1493 jpaint:
1494 assert(phy_cur == tlp->tl_phy_cursor);
1495 assert(phy_wid == phy_wid_base - phy_base);
1496 assert(cnt == tlp->tl_count);
1497 assert(cnt > 0);
1498 assert(lstcur == tlp->tl_lst_cursor);
1499 assert(tccp == tlp->tl_line.cells + cur);
1501 phy_nxtcur = phy_base; /* FIXME only if repaint cpl. */
1503 /* Quickshot: is it only cursor movement within the visible screen? */
1504 if((f & a_TTY_VF_REFRESH) == a_TTY_VF_MOD_CURSOR){
1505 f |= a_MOVE_CURSOR;
1506 goto jcursor;
1509 /* To be able to apply some quick jump offs, clear line if possible */
1510 if(f & a_TTY_VF_MOD_DIRTY){
1511 /* Force complete clearance and cursor reinitialization */
1512 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr) ||
1513 !n_termcap_cmd(n_TERMCAP_CMD_ce, 0, -1))
1514 goto jerr;
1515 tlp->tl_phy_start = tcp_left;
1516 phy_cur = 0;
1519 if((f & (a_TTY_VF_MOD_DIRTY | a_SHOW_PROMPT)) && phy_cur != 0){
1520 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
1521 goto jerr;
1522 phy_cur = 0;
1525 if(f & a_SHOW_PROMPT){
1526 assert(phy_base == tlp->tl_prompt_width);
1527 if(fputs(tlp->tl_prompt, n_tty_fp) == EOF)
1528 goto jerr;
1529 phy_cur = phy_nxtcur;
1530 f |= a_VISIBLE_PROMPT;
1531 }else
1532 f &= ~a_VISIBLE_PROMPT;
1534 /* FIXME reposition cursor for paint */
1535 for(w = phy_nxtcur; tcp_left <= tcp_right; ++tcp_left){
1536 ui16_t cw;
1538 cw = tcp_left->tc_width;
1540 if(n_LIKELY(!tcp_left->tc_novis)){
1541 if(fwrite(tcp_left->tc_cbuf, sizeof *tcp_left->tc_cbuf,
1542 tcp_left->tc_count, n_tty_fp) != tcp_left->tc_count)
1543 goto jerr;
1544 }else{ /* XXX Shouldn't be here <-> CText, ui_str.c */
1545 char wbuf[8]; /* XXX magic */
1547 if(options & OPT_UNICODE){
1548 ui32_t wc;
1550 wc = (ui32_t)tcp_left->tc_wc;
1551 if((wc & ~0x1Fu) == 0)
1552 wc |= 0x2400;
1553 else if(wc == 0x7F)
1554 wc = 0x2421;
1555 else
1556 wc = 0x2426;
1557 n_utf32_to_utf8(wc, wbuf);
1558 }else
1559 wbuf[0] = '?', wbuf[1] = '\0';
1561 if(fputs(wbuf, n_tty_fp) == EOF)
1562 goto jerr;
1563 cw = 1;
1566 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1567 cw = 1;
1568 w += cw;
1569 if(tcp_left == tccp)
1570 phy_nxtcur = w;
1571 phy_cur += cw;
1574 /* Write something position marker alike if it doesn't fit on screen */
1575 if((f & a_HAVE_POSITION) &&
1576 ((f & (a_LEFT_MIN | a_RIGHT_MAX)) != (a_LEFT_MIN | a_RIGHT_MAX) ||
1577 ((f & a_HAVE_PROMPT) && !(f & a_SHOW_PROMPT)))){
1578 # ifdef HAVE_COLOUR
1579 char *posbuf = tlp->tl_pos_buf, *pos = tlp->tl_pos;
1580 # else
1581 char posbuf[5], *pos = posbuf;
1583 pos[4] = '\0';
1584 # endif
1586 if(phy_cur != (w = phy_wid_base) &&
1587 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = w, 0))
1588 goto jerr;
1590 *pos++ = '|';
1591 if((f & a_LEFT_MIN) && (!(f & a_HAVE_PROMPT) || (f & a_SHOW_PROMPT)))
1592 memcpy(pos, "^.+", 3);
1593 else if(f & a_RIGHT_MAX)
1594 memcpy(pos, ".+$", 3);
1595 else{
1596 /* Theoretical line length limit a_TTY_LINE_MAX, choose next power of
1597 * ten (10 ** 10) to represent 100 percent, since we don't have a macro
1598 * that generates a constant, and i don't trust the standard "u type
1599 * suffix automatically scales" calculate the large number */
1600 static char const itoa[] = "0123456789";
1602 ui64_t const fact100 = (ui64_t)0x3B9ACA00u * 10u, fact = fact100 / 100;
1603 ui32_t i = (ui32_t)(((fact100 / cnt) * tlp->tl_cursor) / fact);
1604 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1606 if(i < 10)
1607 pos[0] = ' ', pos[1] = itoa[i];
1608 else
1609 pos[1] = itoa[i % 10], pos[0] = itoa[i / 10];
1610 pos[2] = '%';
1613 if(fputs(posbuf, n_tty_fp) == EOF)
1614 goto jerr;
1615 phy_cur += 4;
1618 /* Users are used to see the cursor right of the point of interest, so we
1619 * need some further adjustments unless in special conditions. Be aware
1620 * that we may have adjusted cur at the beginning, too */
1621 if((cur = tlp->tl_cursor) == 0)
1622 phy_nxtcur = phy_base;
1623 else if(cur != cnt){
1624 ui16_t cw = tccp->tc_width;
1626 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1627 cw = 1;
1628 phy_nxtcur -= cw;
1631 jcursor:
1632 if(((f & a_MOVE_CURSOR) || phy_nxtcur != phy_cur) &&
1633 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = phy_nxtcur, 0))
1634 goto jerr;
1636 jleave:
1637 tlp->tl_vi_flags |= (f & a_PERSIST_MASK);
1638 tlp->tl_lst_count = tlp->tl_count;
1639 tlp->tl_lst_cursor = tlp->tl_cursor;
1640 tlp->tl_phy_cursor = phy_cur;
1642 NYD2_LEAVE;
1643 return ((f & a_TRUE_RV) != 0);
1644 jerr:
1645 f &= ~a_TRUE_RV;
1646 goto jleave;
1649 static si32_t
1650 a_tty_wboundary(struct a_tty_line *tlp, si32_t dir){/* TODO shell token-wise */
1651 bool_t anynon;
1652 struct a_tty_cell *tcap;
1653 ui32_t cur, cnt;
1654 si32_t rv;
1655 NYD2_ENTER;
1657 assert(dir == 1 || dir == -1);
1659 rv = -1;
1660 cnt = tlp->tl_count;
1661 cur = tlp->tl_cursor;
1663 if(dir < 0){
1664 if(cur == 0)
1665 goto jleave;
1666 }else if(cur + 1 >= cnt)
1667 goto jleave;
1668 else
1669 --cnt, --cur; /* xxx Unsigned wrapping may occur (twice), then */
1671 for(rv = 0, tcap = tlp->tl_line.cells, anynon = FAL0;;){
1672 wchar_t wc;
1674 wc = tcap[cur += (ui32_t)dir].tc_wc;
1675 if(iswblank(wc) || iswpunct(wc)){
1676 if(anynon)
1677 break;
1678 }else
1679 anynon = TRU1;
1681 ++rv;
1683 if(dir < 0){
1684 if(cur == 0)
1685 break;
1686 }else if(cur + 1 >= cnt){
1687 ++rv;
1688 break;
1691 jleave:
1692 NYD2_LEAVE;
1693 return rv;
1696 static void
1697 a_tty_khome(struct a_tty_line *tlp, bool_t dobell){
1698 ui32_t f;
1699 NYD2_ENTER;
1701 if(n_LIKELY(tlp->tl_cursor > 0)){
1702 tlp->tl_cursor = 0;
1703 f = a_TTY_VF_MOD_CURSOR;
1704 }else if(dobell)
1705 f = a_TTY_VF_BELL;
1706 else
1707 f = a_TTY_VF_NONE;
1709 tlp->tl_vi_flags |= f;
1710 NYD2_LEAVE;
1713 static void
1714 a_tty_kend(struct a_tty_line *tlp){
1715 ui32_t f;
1716 NYD2_ENTER;
1718 if(n_LIKELY(tlp->tl_cursor < tlp->tl_count)){
1719 tlp->tl_cursor = tlp->tl_count;
1720 f = a_TTY_VF_MOD_CURSOR;
1721 }else
1722 f = a_TTY_VF_BELL;
1724 tlp->tl_vi_flags |= f;
1725 NYD2_LEAVE;
1728 static void
1729 a_tty_kbs(struct a_tty_line *tlp){
1730 ui32_t f, cur, cnt;
1731 NYD2_ENTER;
1733 cur = tlp->tl_cursor;
1734 cnt = tlp->tl_count;
1736 if(n_LIKELY(cur > 0)){
1737 tlp->tl_cursor = --cur;
1738 tlp->tl_count = --cnt;
1740 if((cnt -= cur) > 0){
1741 struct a_tty_cell *tcap;
1743 tcap = tlp->tl_line.cells + cur;
1744 memmove(tcap, &tcap[1], cnt *= sizeof(*tcap));
1746 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
1747 }else
1748 f = a_TTY_VF_BELL;
1750 tlp->tl_vi_flags |= f;
1751 NYD2_LEAVE;
1754 static void
1755 a_tty_ksnarf(struct a_tty_line *tlp, bool_t cplline, bool_t dobell){
1756 ui32_t i, f;
1757 NYD2_ENTER;
1759 f = a_TTY_VF_NONE;
1760 i = tlp->tl_cursor;
1762 if(cplline && i > 0){
1763 tlp->tl_cursor = i = 0;
1764 f = a_TTY_VF_MOD_CURSOR;
1767 if(n_LIKELY(i < tlp->tl_count)){
1768 struct a_tty_cell *tcap;
1770 tcap = &tlp->tl_line.cells[0];
1771 a_tty_copy2paste(tlp, &tcap[i], &tcap[tlp->tl_count]);
1772 tlp->tl_count = i;
1773 f = a_TTY_VF_MOD_CONTENT;
1774 }else if(dobell)
1775 f |= a_TTY_VF_BELL;
1777 tlp->tl_vi_flags |= f;
1778 NYD2_LEAVE;
1781 static si32_t
1782 a_tty_kdel(struct a_tty_line *tlp){
1783 ui32_t cur, cnt, f;
1784 si32_t i;
1785 NYD2_ENTER;
1787 cur = tlp->tl_cursor;
1788 cnt = tlp->tl_count;
1789 i = (si32_t)(cnt - cur);
1791 if(n_LIKELY(i > 0)){
1792 tlp->tl_count = --cnt;
1794 if(n_LIKELY(--i > 0)){
1795 struct a_tty_cell *tcap;
1797 tcap = &tlp->tl_line.cells[cur];
1798 memmove(tcap, &tcap[1], (ui32_t)i * sizeof(*tcap));
1800 f = a_TTY_VF_MOD_CONTENT;
1801 }else if(cnt == 0 && !ok_blook(ignoreeof)){
1802 putc('^', n_tty_fp);
1803 putc('D', n_tty_fp);
1804 i = -1;
1805 f = a_TTY_VF_NONE;
1806 }else{
1807 i = 0;
1808 f = a_TTY_VF_BELL;
1811 tlp->tl_vi_flags |= f;
1812 NYD2_LEAVE;
1813 return i;
1816 static void
1817 a_tty_kleft(struct a_tty_line *tlp){
1818 ui32_t f;
1819 NYD2_ENTER;
1821 if(n_LIKELY(tlp->tl_cursor > 0)){
1822 --tlp->tl_cursor;
1823 f = a_TTY_VF_MOD_CURSOR;
1824 }else
1825 f = a_TTY_VF_BELL;
1827 tlp->tl_vi_flags |= f;
1828 NYD2_LEAVE;
1831 static void
1832 a_tty_kright(struct a_tty_line *tlp){
1833 ui32_t i;
1834 NYD2_ENTER;
1836 if(n_LIKELY((i = tlp->tl_cursor + 1) <= tlp->tl_count)){
1837 tlp->tl_cursor = i;
1838 i = a_TTY_VF_MOD_CURSOR;
1839 }else
1840 i = a_TTY_VF_BELL;
1842 tlp->tl_vi_flags |= i;
1843 NYD2_LEAVE;
1846 static void
1847 a_tty_ksnarfw(struct a_tty_line *tlp, bool_t fwd){
1848 struct a_tty_cell *tcap;
1849 ui32_t cnt, cur, f;
1850 si32_t i;
1851 NYD2_ENTER;
1853 if(n_UNLIKELY((i = a_tty_wboundary(tlp, (fwd ? +1 : -1))) <= 0)){
1854 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
1855 goto jleave;
1858 cnt = tlp->tl_count - (ui32_t)i;
1859 cur = tlp->tl_cursor;
1860 if(!fwd)
1861 cur -= (ui32_t)i;
1862 tcap = &tlp->tl_line.cells[cur];
1864 a_tty_copy2paste(tlp, &tcap[0], &tcap[i]);
1866 if((tlp->tl_count = cnt) != (tlp->tl_cursor = cur)){
1867 cnt -= cur;
1868 memmove(&tcap[0], &tcap[i], cnt * sizeof(*tcap)); /* FIXME*/
1871 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
1872 jleave:
1873 tlp->tl_vi_flags |= f;
1874 NYD2_LEAVE;
1877 static void
1878 a_tty_kgow(struct a_tty_line *tlp, si32_t dir){
1879 ui32_t f;
1880 si32_t i;
1881 NYD2_ENTER;
1883 if(n_UNLIKELY((i = a_tty_wboundary(tlp, dir)) <= 0))
1884 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
1885 else{
1886 if(dir < 0)
1887 i = -i;
1888 tlp->tl_cursor += (ui32_t)i;
1889 f = a_TTY_VF_MOD_CURSOR;
1892 tlp->tl_vi_flags |= f;
1893 NYD2_LEAVE;
1896 static bool_t
1897 a_tty_kother(struct a_tty_line *tlp, wchar_t wc){
1898 /* Append if at EOL, insert otherwise;
1899 * since we may move around character-wise, always use a fresh ps */
1900 mbstate_t ps;
1901 struct a_tty_cell tc, *tcap;
1902 ui32_t f, cur, cnt;
1903 bool_t rv;
1904 NYD2_ENTER;
1906 rv = FAL0;
1907 f = a_TTY_VF_NONE;
1909 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1910 if(tlp->tl_count + 1 >= a_TTY_LINE_MAX){
1911 n_err(_("Stop here, we can't extend line beyond size limit\n"));
1912 goto jleave;
1915 /* First init a cell and see whether we'll really handle this wc */
1916 memset(&ps, 0, sizeof ps);
1917 /* C99 */{
1918 size_t l;
1920 l = wcrtomb(tc.tc_cbuf, tc.tc_wc = wc, &ps);
1921 if(n_UNLIKELY(l > MB_LEN_MAX)){
1922 jemb:
1923 n_err(_("wcrtomb(3) error: too many multibyte character bytes\n"));
1924 goto jleave;
1926 tc.tc_count = (ui16_t)l;
1928 if(n_UNLIKELY((options & OPT_ENC_MBSTATE) != 0)){
1929 l = wcrtomb(&tc.tc_cbuf[l], L'\0', &ps);
1930 if(n_LIKELY(l == 1))
1931 /* Only NUL terminator */;
1932 else if(n_LIKELY(--l < MB_LEN_MAX))
1933 tc.tc_count += (ui16_t)l;
1934 else
1935 goto jemb;
1939 /* Yes, we will! Place it in the array */
1940 tc.tc_novis = (iswprint(wc) == 0);
1941 tc.tc_width = a_tty_wcwidth(wc);
1942 /* TODO if(tc.tc_novis && tc.tc_width > 0) */
1944 cur = tlp->tl_cursor++;
1945 cnt = tlp->tl_count++ - cur;
1946 tcap = &tlp->tl_line.cells[cur];
1947 if(cnt >= 1){
1948 memmove(&tcap[1], tcap, cnt * sizeof(*tcap));
1949 f = a_TTY_VF_MOD_CONTENT;
1950 }else
1951 f = a_TTY_VF_MOD_SINGLE;
1952 memcpy(tcap, &tc, sizeof *tcap);
1954 f |= a_TTY_VF_MOD_CURSOR;
1955 rv = TRU1;
1956 jleave:
1957 if(!rv)
1958 f |= a_TTY_VF_BELL;
1959 tlp->tl_vi_flags |= f;
1960 NYD2_LEAVE;
1961 return rv;
1964 static ui32_t
1965 a_tty_kht(struct a_tty_line *tlp){
1966 ui8_t (*autorecmem)[n_MEMORY_AUTOREC_TYPE_SIZEOF], *autorec_persist;
1967 struct stat sb;
1968 struct str orig, bot, topp, sub, exp, preexp;
1969 struct n_string shou, *shoup;
1970 struct a_tty_cell *cword, *ctop, *cx;
1971 bool_t wedid, set_savec;
1972 ui32_t rv, f;
1973 NYD2_ENTER;
1975 /* Get plain line data; if this is the first expansion/xy, update the
1976 * very original content so that ^G gets the origin back */
1977 orig = tlp->tl_savec;
1978 a_tty_cell2save(tlp);
1979 exp = tlp->tl_savec;
1980 if(orig.s != NULL){
1981 /*tlp->tl_savec = orig;*/
1982 set_savec = FAL0;
1983 }else
1984 set_savec = TRU1;
1985 orig = exp;
1987 autorec_persist = n_memory_autorec_current();
1988 n_memory_autorec_push(autorecmem = n_lofi_alloc(sizeof *autorecmem));
1990 shoup = n_string_creat_auto(&shou);
1991 f = a_TTY_VF_NONE;
1993 /* Find the word to be expanded */
1995 cword = tlp->tl_line.cells;
1996 ctop = cword + tlp->tl_cursor;
1997 cx = cword + tlp->tl_count;
1999 /* topp: separate data right of cursor */
2000 if(cx > ctop){
2001 for(rv = 0; ctop < cx; ++ctop)
2002 rv += ctop->tc_count;
2003 topp.l = rv;
2004 topp.s = orig.s + orig.l - rv;
2005 ctop = cword + tlp->tl_cursor;
2006 }else
2007 topp.s = NULL, topp.l = 0;
2009 /* Find the shell token that corresponds to the cursor position */
2010 /* C99 */{
2011 size_t max;
2013 max = 0;
2014 if(ctop > cword){
2015 for(; cword < ctop; ++cword)
2016 max += cword->tc_count;
2017 cword = tlp->tl_line.cells;
2019 bot = sub = orig;
2020 bot.l = 0;
2021 sub.l = max;
2023 if(max > 0){
2024 for(;;){
2025 enum n_shexp_state shs;
2027 exp = sub;
2028 shs = n_shexp_parse_token(NULL, &sub, n_SHEXP_PARSE_DRYRUN |
2029 n_SHEXP_PARSE_TRIMSPACE | n_SHEXP_PARSE_IGNORE_EMPTY |
2030 n_SHEXP_PARSE_QUOTE_AUTO_CLOSE);
2031 if(sub.l != 0){
2032 size_t x;
2034 assert(max >= sub.l);
2035 x = max - sub.l;
2036 bot.l += x;
2037 max -= x;
2038 continue;
2040 if(shs & n_SHEXP_STATE_ERR_MASK){
2041 n_err(_("Invalid completion pattern: %.*s\n"),
2042 (int)exp.l, exp.s);
2043 goto jnope;
2045 n_shexp_parse_token(shoup, &exp,
2046 n_SHEXP_PARSE_TRIMSPACE | n_SHEXP_PARSE_IGNORE_EMPTY |
2047 n_SHEXP_PARSE_QUOTE_AUTO_CLOSE);
2048 break;
2051 sub.s = n_string_cp(shoup);
2052 sub.l = shoup->s_len;
2056 /* Leave room for "implicit asterisk" expansion, as below */
2057 if(sub.l == 0){
2058 wedid = TRU1;
2059 sub.s = n_UNCONST("*");
2060 sub.l = 1;
2063 preexp.s = n_UNCONST(n_empty);
2064 preexp.l = 0;
2065 wedid = FAL0;
2066 jredo:
2067 /* TODO Super-Heavy-Metal: block all sigs, avoid leaks on jump */
2068 hold_all_sigs();
2069 exp.s = fexpand(sub.s, a_TTY_TAB_FEXP_FL);
2070 rele_all_sigs();
2072 if(exp.s == NULL || (exp.l = strlen(exp.s)) == 0){
2073 /* No. But maybe the users' desire was to complete only a part of the
2074 * shell token of interest! TODO This can be improved, we would need to
2075 * TODO have shexp_parse to create a DOM structure of parsed snippets, so
2076 * TODO that we can tell for each snippet which quote is active and
2077 * TODO whether we may cross its boundary and/or apply expansion for it */
2078 if(wedid == TRU1){
2079 size_t i, li;
2081 wedid = TRUM1;
2082 for(li = UIZ_MAX, i = sub.l; i-- > 0;){
2083 char c;
2085 if((c = sub.s[i]) == '/' || c == '+' /* *folder*! */)
2086 li = i;
2087 /* Do stop once some "magic" characters are seen XXX magic set */
2088 else if(c == '<' || c == '>' || c == '=' || c == ':')
2089 break;
2091 if(li != UIZ_MAX){
2092 preexp = sub;
2093 preexp.l = li;
2094 sub.l -= li;
2095 sub.s += li;
2096 goto jredo;
2099 goto jnope;
2102 if(wedid == TRUM1 && preexp.l > 0)
2103 preexp.s = savestrbuf(preexp.s, preexp.l);
2105 /* May be multi-return! */
2106 if(pstate & PS_EXPAND_MULTIRESULT)
2107 goto jmulti;
2109 /* xxx That is not really true since the limit counts characters not bytes */
2110 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
2111 if(exp.l >= a_TTY_LINE_MAX - 1 || a_TTY_LINE_MAX - 1 - exp.l < preexp.l){
2112 n_err(_("Tabulator expansion would extend beyond line size limit\n"));
2113 goto jnope;
2116 /* If the expansion equals the original string, assume the user wants what
2117 * is usually known as tab completion, append `*' and restart */
2118 if(!wedid && exp.l == sub.l && !memcmp(exp.s, sub.s, exp.l)){
2119 if(sub.s[sub.l - 1] == '*')
2120 goto jnope;
2122 wedid = TRU1;
2123 shoup = n_string_push_c(shoup, '*');
2124 sub.s = n_string_cp(shoup);
2125 sub.l = shoup->s_len;
2126 goto jredo;
2129 /* If it is a directory, and there is not yet a / appended, then we want the
2130 * user to confirm that he wants to dive in -- with only a HT */
2131 if(wedid && exp.l == --sub.l && !memcmp(exp.s, sub.s, exp.l) &&
2132 exp.s[exp.l - 1] != '/'){
2133 if(stat(exp.s, &sb) || !S_ISDIR(sb.st_mode))
2134 goto jnope;
2135 sub.s = salloc(exp.l + 1 +1);
2136 memcpy(sub.s, exp.s, exp.l);
2137 sub.s[exp.l++] = '/';
2138 sub.s[exp.l] = '\0';
2139 exp.s = sub.s;
2140 wedid = FAL0;
2141 goto jset;
2142 }else{
2143 if(wedid && (wedid = (exp.s[exp.l - 1] == '*')))
2144 --exp.l;
2145 exp.s[exp.l] = '\0';
2146 jset:
2147 exp.l = strlen(exp.s = n_shexp_quote_cp(exp.s, tlp->tl_quote_rndtrip));
2148 tlp->tl_defc_cursor_byte = bot.l + preexp.l + exp.l -1;
2149 if(wedid)
2150 goto jnope;
2153 orig.l = bot.l + preexp.l + exp.l + topp.l;
2154 orig.s = n_autorec_alloc(autorec_persist, orig.l + 5 +1);
2155 if((rv = (ui32_t)bot.l) > 0)
2156 memcpy(orig.s, bot.s, rv);
2157 if(preexp.l > 0){
2158 memcpy(&orig.s[rv], preexp.s, preexp.l);
2159 rv += preexp.l;
2161 memcpy(&orig.s[rv], exp.s, exp.l);
2162 rv += exp.l;
2163 if(topp.l > 0){
2164 memcpy(&orig.s[rv], topp.s, topp.l);
2165 rv += topp.l;
2167 orig.s[rv] = '\0';
2169 tlp->tl_defc = orig;
2170 tlp->tl_count = tlp->tl_cursor = 0;
2171 f |= a_TTY_VF_MOD_DIRTY;
2172 jleave:
2173 n_memory_autorec_pop(autorecmem);
2174 n_lofi_free(autorecmem);
2175 tlp->tl_vi_flags |= f;
2176 NYD2_LEAVE;
2177 return rv;
2179 jmulti:{
2180 struct n_visual_info_ctx vic;
2181 struct str input;
2182 wc_t c2, c1;
2183 bool_t isfirst;
2184 char const *lococp;
2185 size_t locolen, scrwid, lnlen, lncnt, prefixlen;
2186 FILE *fp;
2188 if((fp = Ftmp(NULL, "tabex", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
2189 n_perr(_("tmpfile"), 0);
2190 fp = n_tty_fp;
2193 /* How long is the result string for real? Search the NUL NUL
2194 * terminator. While here, detect the longest entry to perform an
2195 * initial allocation of our accumulator string */
2196 locolen = preexp.l;
2198 size_t i;
2200 i = strlen(&exp.s[++exp.l]);
2201 locolen = n_MAX(locolen, i);
2202 exp.l += i;
2203 }while(exp.s[exp.l + 1] != '\0');
2205 shoup = n_string_reserve(n_string_trunc(shoup, 0),
2206 locolen + (locolen >> 1));
2208 /* Iterate (once again) over all results */
2209 scrwid = (size_t)scrnwidth - ((size_t)scrnwidth >> 3);
2210 lnlen = lncnt = 0;
2211 n_UNINIT(prefixlen, 0);
2212 n_UNINIT(lococp, NULL);
2213 n_UNINIT(c1, '\0');
2214 for(isfirst = TRU1; exp.l > 0; isfirst = FAL0, c1 = c2){
2215 size_t i;
2216 char const *fullpath;
2218 /* Next result */
2219 sub = exp;
2220 sub.l = i = strlen(sub.s);
2221 assert(exp.l >= i);
2222 if((exp.l -= i) > 0)
2223 --exp.l;
2224 exp.s += ++i;
2226 /* Separate dirname and basename */
2227 fullpath = sub.s;
2228 if(isfirst){
2229 char const *cp;
2231 if((cp = strrchr(fullpath, '/')) != NULL)
2232 prefixlen = PTR2SIZE(++cp - fullpath);
2233 else
2234 prefixlen = 0;
2236 if(prefixlen > 0 && prefixlen < sub.l){
2237 sub.l -= prefixlen;
2238 sub.s += prefixlen;
2241 /* We want case-insensitive sort-order */
2242 memset(&vic, 0, sizeof vic);
2243 vic.vic_indat = sub.s;
2244 vic.vic_inlen = sub.l;
2245 c2 = n_visual_info(&vic, n_VISUAL_INFO_ONE_CHAR) ? vic.vic_waccu
2246 : (ui8_t)*sub.s;
2247 #ifdef HAVE_C90AMEND1
2248 c2 = towlower(c2);
2249 #else
2250 c2 = lowerconv(c2);
2251 #endif
2253 /* Query longest common prefix along the way */
2254 if(isfirst){
2255 c1 = c2;
2256 lococp = sub.s;
2257 locolen = sub.l;
2258 }else if(locolen > 0){
2259 for(i = 0; i < locolen; ++i)
2260 if(lococp[i] != sub.s[i]){
2261 i = field_detect_clip(i, lococp, i);
2262 locolen = i;
2263 break;
2267 /* Prepare display */
2268 input = sub;
2269 shoup = n_shexp_quote(n_string_trunc(shoup, 0), &input,
2270 tlp->tl_quote_rndtrip);
2271 memset(&vic, 0, sizeof vic);
2272 vic.vic_indat = shoup->s_dat;
2273 vic.vic_inlen = shoup->s_len;
2274 if(!n_visual_info(&vic,
2275 n_VISUAL_INFO_SKIP_ERRORS | n_VISUAL_INFO_WIDTH_QUERY))
2276 vic.vic_vi_width = shoup->s_len;
2278 /* Put on screen. Indent follow lines of same sort slot */
2279 c1 = (c1 != c2);
2280 if(isfirst || c1 ||
2281 scrwid < lnlen || scrwid - lnlen <= vic.vic_vi_width + 2){
2282 putc('\n', fp);
2283 if(scrwid < lnlen)
2284 ++lncnt;
2285 ++lncnt, lnlen = 0;
2286 if(!isfirst && !c1)
2287 goto jsep;
2288 }else if(lnlen > 0){
2289 jsep:
2290 fputs(" ", fp);
2291 lnlen += 2;
2293 fputs(n_string_cp(shoup), fp);
2294 lnlen += vic.vic_vi_width;
2296 /* Support the known file name tagging
2297 * XXX *line-editor-completion-filetype* or so */
2298 if(!lstat(fullpath, &sb)){
2299 char c = '\0';
2301 if(S_ISDIR(sb.st_mode))
2302 c = '/';
2303 else if(S_ISLNK(sb.st_mode))
2304 c = '@';
2305 # ifdef S_ISFIFO
2306 else if(S_ISFIFO(sb.st_mode))
2307 c = '|';
2308 # endif
2309 # ifdef S_ISSOCK
2310 else if(S_ISSOCK(sb.st_mode))
2311 c = '=';
2312 # endif
2313 # ifdef S_ISCHR
2314 else if(S_ISCHR(sb.st_mode))
2315 c = '%';
2316 # endif
2317 # ifdef S_ISBLK
2318 else if(S_ISBLK(sb.st_mode))
2319 c = '#';
2320 # endif
2322 if(c != '\0'){
2323 putc(c, fp);
2324 ++lnlen;
2328 putc('\n', fp);
2329 ++lncnt;
2331 page_or_print(fp, lncnt);
2332 if(fp != n_tty_fp)
2333 Fclose(fp);
2335 n_string_gut(shoup);
2337 /* A common prefix of 0 means we cannot provide the user any auto
2338 * completed characters */
2339 if(locolen == 0)
2340 goto jnope;
2342 /* Otherwise we can, so extend the visual line content by the common
2343 * prefix (in a reversible way) */
2344 (exp.s = n_UNCONST(lococp))[locolen] = '\0';
2345 exp.s -= prefixlen;
2346 exp.l = (locolen += prefixlen);
2348 /* XXX Indicate that there is multiple choice */
2349 /* XXX f |= a_TTY_VF_BELL; -> *line-editor-completion-bell*? or so */
2350 wedid = FAL0;
2351 goto jset;
2354 jnope:
2355 /* If we've provided a default content, but failed to expand, there is
2356 * nothing we can "revert to": drop that default again */
2357 if(set_savec){
2358 tlp->tl_savec.s = NULL;
2359 tlp->tl_savec.l = 0;
2361 f = a_TTY_VF_NONE;
2362 rv = 0;
2363 goto jleave;
2366 # ifdef HAVE_HISTORY
2367 static ui32_t
2368 a_tty__khist_shared(struct a_tty_line *tlp, struct a_tty_hist *thp){
2369 ui32_t f, rv;
2370 NYD2_ENTER;
2372 if(n_LIKELY((tlp->tl_hist = thp) != NULL)){
2373 tlp->tl_defc.s = savestrbuf(thp->th_dat, thp->th_len);
2374 rv = tlp->tl_defc.l = thp->th_len;
2375 f = (tlp->tl_count > 0) ? a_TTY_VF_MOD_DIRTY : a_TTY_VF_NONE;
2376 tlp->tl_count = tlp->tl_cursor = 0;
2377 }else{
2378 f = a_TTY_VF_BELL;
2379 rv = UI32_MAX;
2382 tlp->tl_vi_flags |= f;
2383 NYD2_LEAVE;
2384 return rv;
2387 static ui32_t
2388 a_tty_khist(struct a_tty_line *tlp, bool_t fwd){
2389 struct a_tty_hist *thp;
2390 ui32_t rv;
2391 NYD2_ENTER;
2393 /* If we're not in history mode yet, save line content;
2394 * also, disallow forward search, then, and, of course, bail unless we
2395 * do have any history at all */
2396 if((thp = tlp->tl_hist) == NULL){
2397 if(fwd)
2398 goto jleave;
2399 if((thp = a_tty.tg_hist) == NULL)
2400 goto jleave;
2401 a_tty_cell2save(tlp);
2402 goto jleave;
2405 thp = fwd ? thp->th_younger : thp->th_older;
2406 jleave:
2407 rv = a_tty__khist_shared(tlp, thp);
2408 NYD2_LEAVE;
2409 return rv;
2412 static ui32_t
2413 a_tty_khist_search(struct a_tty_line *tlp, bool_t fwd){
2414 struct str orig_savec;
2415 struct a_tty_hist *thp;
2416 ui32_t rv;
2417 NYD2_ENTER;
2419 thp = NULL;
2421 /* We cannot complete an empty line */
2422 if(n_UNLIKELY(tlp->tl_count == 0)){
2423 /* XXX The upcoming hard reset would restore a set savec buffer,
2424 * XXX so forcefully reset that. A cleaner solution would be to
2425 * XXX reset it whenever a restore is no longer desired */
2426 tlp->tl_savec.s = NULL;
2427 tlp->tl_savec.l = 0;
2428 goto jleave;
2431 if((thp = tlp->tl_hist) == NULL){
2432 if((thp = a_tty.tg_hist) == NULL)
2433 goto jleave;
2434 /* We don't support wraparound, searching forward must always step */
2435 if(fwd)
2436 thp = thp->th_younger;
2437 orig_savec.s = NULL;
2438 orig_savec.l = 0; /* silence CC */
2439 }else if((thp = (fwd ? thp->th_younger : thp->th_older)) == NULL)
2440 goto jleave;
2441 else
2442 orig_savec = tlp->tl_savec;
2444 if(orig_savec.s == NULL)
2445 a_tty_cell2save(tlp);
2447 for(; thp != NULL; thp = (fwd ? thp->th_younger : thp->th_older))
2448 if(is_prefix(tlp->tl_savec.s, thp->th_dat))
2449 break;
2451 if(orig_savec.s != NULL)
2452 tlp->tl_savec = orig_savec;
2453 jleave:
2454 rv = a_tty__khist_shared(tlp, thp);
2455 NYD2_LEAVE;
2456 return rv;
2458 # endif /* HAVE_HISTORY */
2460 static enum a_tty_fun_status
2461 a_tty_fun(struct a_tty_line *tlp, enum a_tty_bind_flags tbf, size_t *len){
2462 enum a_tty_fun_status rv;
2463 NYD2_ENTER;
2465 rv = a_TTY_FUN_STATUS_OK;
2466 # undef a_X
2467 # define a_X(N) a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## N)
2468 switch(a_TTY_BIND_FUN_REDUCE(tbf)){
2469 case a_X(BELL):
2470 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2471 break;
2472 case a_X(GO_BWD):
2473 a_tty_kleft(tlp);
2474 break;
2475 case a_X(GO_FWD):
2476 a_tty_kright(tlp);
2477 break;
2478 case a_X(GO_WORD_BWD):
2479 a_tty_kgow(tlp, -1);
2480 break;
2481 case a_X(GO_WORD_FWD):
2482 a_tty_kgow(tlp, +1);
2483 break;
2484 case a_X(GO_HOME):
2485 a_tty_khome(tlp, TRU1);
2486 break;
2487 case a_X(GO_END):
2488 a_tty_kend(tlp);
2489 break;
2490 case a_X(DEL_BWD):
2491 a_tty_kbs(tlp);
2492 break;
2493 case a_X(DEL_FWD):
2494 if(a_tty_kdel(tlp) < 0)
2495 rv = a_TTY_FUN_STATUS_END;
2496 break;
2497 case a_X(SNARF_WORD_BWD):
2498 a_tty_ksnarfw(tlp, FAL0);
2499 break;
2500 case a_X(SNARF_WORD_FWD):
2501 a_tty_ksnarfw(tlp, TRU1);
2502 break;
2503 case a_X(SNARF_END):
2504 a_tty_ksnarf(tlp, FAL0, TRU1);
2505 break;
2506 case a_X(SNARF_LINE):
2507 a_tty_ksnarf(tlp, TRU1, (tlp->tl_count == 0));
2508 break;
2510 case a_X(HIST_FWD):
2511 # ifdef HAVE_HISTORY
2512 if(tlp->tl_hist != NULL){
2513 bool_t isfwd = TRU1;
2515 if(0){
2516 # endif
2517 /* FALLTHRU */
2518 case a_X(HIST_BWD):
2519 # ifdef HAVE_HISTORY
2520 isfwd = FAL0;
2522 if((*len = a_tty_khist(tlp, isfwd)) != UI32_MAX){
2523 rv = a_TTY_FUN_STATUS_RESTART;
2524 break;
2526 goto jreset;
2527 # endif
2529 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2530 break;
2532 case a_X(HIST_SRCH_FWD):{
2533 # ifdef HAVE_HISTORY
2534 bool_t isfwd = TRU1;
2536 if(0){
2537 # endif
2538 /* FALLTHRU */
2539 case a_X(HIST_SRCH_BWD):
2540 # ifdef HAVE_HISTORY
2541 isfwd = FAL0;
2543 if((*len = a_tty_khist_search(tlp, isfwd)) != UI32_MAX){
2544 rv = a_TTY_FUN_STATUS_RESTART;
2545 break;
2547 goto jreset;
2548 # else
2549 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2550 # endif
2551 } break;
2553 case a_X(REPAINT):
2554 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2555 break;
2556 case a_X(QUOTE_RNDTRIP):
2557 tlp->tl_quote_rndtrip = !tlp->tl_quote_rndtrip;
2558 break;
2559 case a_X(PROMPT_CHAR):{
2560 wchar_t wc;
2562 if((wc = a_tty_vinuni(tlp)) > 0)
2563 a_tty_kother(tlp, wc);
2564 } break;
2565 case a_X(COMPLETE):
2566 if((*len = a_tty_kht(tlp)) > 0)
2567 rv = a_TTY_FUN_STATUS_RESTART;
2568 break;
2570 case a_X(PASTE):
2571 if(tlp->tl_pastebuf.l > 0)
2572 *len = (tlp->tl_defc = tlp->tl_pastebuf).l;
2573 else
2574 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2575 break;
2578 case a_X(CANCEL):
2579 /* Normally this just causes a restart and thus resets the state
2580 * machine */
2581 if(tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2583 # ifdef HAVE_KEY_BINDINGS
2584 tlp->tl_bind_takeover = '\0';
2585 # endif
2586 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2587 rv = a_TTY_FUN_STATUS_RESTART;
2588 break;
2590 case a_X(RESET):
2591 if(tlp->tl_count == 0 && tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2592 # ifdef HAVE_KEY_BINDINGS
2593 tlp->tl_bind_takeover = '\0';
2594 # endif
2595 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY | a_TTY_VF_BELL;
2596 break;
2597 }else if(0){
2598 case a_X(FULLRESET):
2599 tlp->tl_savec.s = tlp->tl_defc.s = NULL;
2600 tlp->tl_savec.l = tlp->tl_defc.l = 0;
2601 tlp->tl_defc_cursor_byte = 0;
2602 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2604 jreset:
2605 # ifdef HAVE_KEY_BINDINGS
2606 tlp->tl_bind_takeover = '\0';
2607 # endif
2608 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2609 tlp->tl_cursor = tlp->tl_count = 0;
2610 # ifdef HAVE_HISTORY
2611 tlp->tl_hist = NULL;
2612 # endif
2613 if((*len = tlp->tl_savec.l) != 0){
2614 tlp->tl_defc = tlp->tl_savec;
2615 tlp->tl_savec.s = NULL;
2616 tlp->tl_savec.l = 0;
2617 }else
2618 *len = tlp->tl_defc.l;
2619 rv = a_TTY_FUN_STATUS_RESTART;
2620 break;
2622 default:
2623 case a_X(COMMIT):
2624 rv = a_TTY_FUN_STATUS_COMMIT;
2625 break;
2627 # undef a_X
2629 NYD2_LEAVE;
2630 return rv;
2633 static ssize_t
2634 a_tty_readline(struct a_tty_line *tlp, size_t len n_MEMORY_DEBUG_ARGS){
2635 /* We want to save code, yet we may have to incorporate a lines'
2636 * default content and / or default input to switch back to after some
2637 * history movement; let "len > 0" mean "have to display some data
2638 * buffer" -> a_BUFMODE, and only otherwise read(2) it */
2639 mbstate_t ps[2];
2640 char cbuf_base[MB_LEN_MAX * 2], *cbuf, *cbufp;
2641 ssize_t rv;
2642 struct a_tty_bind_tree *tbtp;
2643 wchar_t wc;
2644 enum a_tty_bind_flags tbf;
2645 enum {a_NONE, a_WAS_HERE = 1<<0, a_BUFMODE = 1<<1, a_MAYBEFUN = 1<<2,
2646 a_TIMEOUT = 1<<3, a_TIMEOUT_EXPIRED = 1<<4,
2647 a_TIMEOUT_MASK = a_TIMEOUT | a_TIMEOUT_EXPIRED,
2648 a_READ_LOOP_MASK = ~(a_WAS_HERE | a_MAYBEFUN | a_TIMEOUT_MASK)
2649 } flags;
2650 NYD_ENTER;
2652 n_UNINIT(rv, 0);
2653 # ifdef HAVE_KEY_BINDINGS
2654 assert(tlp->tl_bind_takeover == '\0');
2655 # endif
2656 jrestart:
2657 memset(ps, 0, sizeof ps);
2658 flags = a_NONE;
2659 tbf = 0;
2660 tlp->tl_vi_flags |= a_TTY_VF_REFRESH | a_TTY_VF_SYNC;
2662 jinput_loop:
2663 for(;;){
2664 if(len != 0)
2665 flags |= a_BUFMODE;
2667 /* Ensure we have valid pointers, and room for grow */
2668 a_tty_check_grow(tlp, ((flags & a_BUFMODE) ? (ui32_t)len : 1)
2669 n_MEMORY_DEBUG_ARGSCALL);
2671 /* Handle visual state flags, except in buffer mode */
2672 if(!(flags & a_BUFMODE) && (tlp->tl_vi_flags & a_TTY_VF_ALL_MASK))
2673 if(!a_tty_vi_refresh(tlp)){
2674 rv = -1;
2675 goto jleave;
2678 /* Ready for messing around.
2679 * Normal read(2)? Else buffer mode: speed this one up */
2680 if(!(flags & a_BUFMODE)){
2681 cbufp =
2682 cbuf = cbuf_base;
2683 }else{
2684 assert(tlp->tl_defc.l > 0 && tlp->tl_defc.s != NULL);
2685 assert(tlp->tl_defc.l >= len);
2686 cbufp =
2687 cbuf = tlp->tl_defc.s + (tlp->tl_defc.l - len);
2688 cbufp += len;
2691 /* Read in the next complete multibyte character */
2692 /* C99 */{
2693 # ifdef HAVE_KEY_BINDINGS
2694 struct a_tty_bind_tree *xtbtp;
2695 struct inseq{
2696 struct inseq *last;
2697 struct inseq *next;
2698 struct a_tty_bind_tree *tbtp;
2699 } *isp_head, *isp;
2701 isp_head = isp = NULL;
2702 # endif
2704 for(flags &= a_READ_LOOP_MASK;;){
2705 # ifdef HAVE_KEY_BINDINGS
2706 if(!(flags & a_BUFMODE) && tlp->tl_bind_takeover != '\0'){
2707 wc = tlp->tl_bind_takeover;
2708 tlp->tl_bind_takeover = '\0';
2709 }else
2710 # endif
2712 if(!(flags & a_BUFMODE)){
2713 /* Let me at least once dream of iomon(itor), timer with
2714 * one-shot, enwrapped with key_event and key_sequence_event,
2715 * all driven by an event_loop */
2716 /* TODO v15 Until we have SysV signal handling all through we
2717 * TODO need to temporarily adjust our BSD signal handler with
2718 * TODO a SysV one, here */
2719 n_sighdl_t otstp, ottin, ottou;
2721 otstp = n_signal(SIGTSTP, &n_tty_signal);
2722 ottin = n_signal(SIGTTIN, &n_tty_signal);
2723 ottou = n_signal(SIGTTOU, &n_tty_signal);
2724 # ifdef HAVE_KEY_BINDINGS
2725 flags &= ~a_TIMEOUT_MASK;
2726 if(isp != NULL && (tbtp = isp->tbtp)->tbt_isseq &&
2727 !tbtp->tbt_isseq_trail){
2728 a_tty_term_rawmode_timeout(tlp, TRU1);
2729 flags |= a_TIMEOUT;
2731 # endif
2733 while((rv = read(STDIN_FILENO, cbufp, 1)) < 1){
2734 if(rv == -1){
2735 if(errno == EINTR){
2736 if((tlp->tl_vi_flags & a_TTY_VF_MOD_DIRTY) &&
2737 !a_tty_vi_refresh(tlp))
2738 break;
2739 continue;
2741 break;
2744 # ifdef HAVE_KEY_BINDINGS
2745 /* Timeout expiration */
2746 if(rv == 0){
2747 assert(flags & a_TIMEOUT);
2748 assert(isp != NULL);
2749 a_tty_term_rawmode_timeout(tlp, FAL0);
2751 /* Something "atomic" broke. Maybe the current one can
2752 * also be terminated already, by itself? xxx really? */
2753 if((tbtp = isp->tbtp)->tbt_bind != NULL){
2754 tlp->tl_bind_takeover = wc;
2755 goto jhave_bind;
2758 /* Or, maybe there is a second path without a timeout;
2759 * this should be covered by .tbt_isseq_trail, but then
2760 * again a single-layer implementation cannot "know" */
2761 for(xtbtp = tbtp; (xtbtp = xtbtp->tbt_sibling) != NULL;)
2762 if(xtbtp->tbt_char == tbtp->tbt_char){
2763 assert(!xtbtp->tbt_isseq);
2764 break;
2766 /* Lay down on read(2)? */
2767 if(xtbtp != NULL)
2768 continue;
2769 goto jtake_over;
2771 # endif /* HAVE_KEY_BINDINGS */
2774 # ifdef HAVE_KEY_BINDINGS
2775 if(flags & a_TIMEOUT)
2776 a_tty_term_rawmode_timeout(tlp, FAL0);
2777 # endif
2778 safe_signal(SIGTSTP, otstp);
2779 safe_signal(SIGTTIN, ottin);
2780 safe_signal(SIGTTOU, ottou);
2781 if(rv < 0)
2782 goto jleave;
2784 ++cbufp;
2787 rv = (ssize_t)mbrtowc(&wc, cbuf, PTR2SIZE(cbufp - cbuf), &ps[0]);
2788 if(rv <= 0){
2789 /* Any error during buffer mode can only result in a hard
2790 * reset; Otherwise, if it's a hard error, or if too many
2791 * redundant shift sequences overflow our buffer: perform
2792 * hard reset */
2793 if((flags & a_BUFMODE) || rv == -1 ||
2794 sizeof cbuf_base == PTR2SIZE(cbufp - cbuf)){
2795 a_tty_fun(tlp, a_TTY_BIND_FUN_FULLRESET, &len);
2796 goto jrestart;
2798 /* Otherwise, due to the way we deal with the buffer, we need
2799 * to restore the mbstate_t from before this conversion */
2800 ps[0] = ps[1];
2801 continue;
2803 cbufp = cbuf;
2804 ps[1] = ps[0];
2807 /* Normal read(2)ing is subject to detection of key-bindings */
2808 # ifdef HAVE_KEY_BINDINGS
2809 if(!(flags & a_BUFMODE)){
2810 /* Check for special bypass functions before we try to embed
2811 * this character into the tree */
2812 if(n_uasciichar(wc)){
2813 char c;
2814 char const *cp;
2816 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_prompt_char)[0];
2817 *cp != '\0'; ++cp){
2818 if(c == *cp){
2819 wc = a_tty_vinuni(tlp);
2820 break;
2823 if(wc == '\0'){
2824 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2825 goto jinput_loop;
2828 if(n_uasciichar(wc))
2829 flags |= a_MAYBEFUN;
2830 else
2831 flags &= ~a_MAYBEFUN;
2833 /* Search for this character in the bind tree */
2834 tbtp = (isp != NULL) ? isp->tbtp->tbt_childs
2835 : (*tlp->tl_bind_tree_hmap)[wc % HSHSIZE];
2836 for(; tbtp != NULL; tbtp = tbtp->tbt_sibling){
2837 if(tbtp->tbt_char == wc){
2838 struct inseq *nisp;
2840 /* If this one cannot continue we're likely finished! */
2841 if(tbtp->tbt_childs == NULL){
2842 assert(tbtp->tbt_bind != NULL);
2843 tbf = tbtp->tbt_bind->tbc_flags;
2844 goto jmle_fun;
2847 /* This needs to read more characters */
2848 nisp = salloc(sizeof *nisp);
2849 if((nisp->last = isp) == NULL)
2850 isp_head = nisp;
2851 else
2852 isp->next = nisp;
2853 nisp->next = NULL;
2854 nisp->tbtp = tbtp;
2855 isp = nisp;
2856 flags &= ~a_WAS_HERE;
2857 break;
2860 if(tbtp != NULL)
2861 continue;
2863 /* Was there a binding active, but couldn't be continued? */
2864 if(isp != NULL){
2865 /* A binding had a timeout, it didn't expire, but we saw
2866 * something non-expected. Something "atomic" broke.
2867 * Maybe there is a second path without a timeout, that
2868 * continues like we've seen it. I.e., it may just have been
2869 * the user, typing too fast. We definitely want to allow
2870 * bindings like \e,d etc. to succeed: users are so used to
2871 * them that a timeout cannot be the mechanism to catch up!
2872 * A single-layer implementation cannot "know" */
2873 if((tbtp = isp->tbtp)->tbt_isseq && (isp->last == NULL ||
2874 !(xtbtp = isp->last->tbtp)->tbt_isseq ||
2875 xtbtp->tbt_isseq_trail)){
2876 for(xtbtp = (tbtp = isp->tbtp);
2877 (xtbtp = xtbtp->tbt_sibling) != NULL;)
2878 if(xtbtp->tbt_char == tbtp->tbt_char){
2879 assert(!xtbtp->tbt_isseq);
2880 break;
2882 if(xtbtp != NULL){
2883 isp->tbtp = xtbtp;
2884 tlp->tl_bind_takeover = wc;
2885 continue;
2889 /* Check for CANCEL shortcut now */
2890 if(flags & a_MAYBEFUN){
2891 char c;
2892 char const *cp;
2894 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_cancel)[0];
2895 *cp != '\0'; ++cp)
2896 if(c == *cp){
2897 tbf = a_TTY_BIND_FUN_INTERNAL |a_TTY_BIND_FUN_CANCEL;
2898 goto jmle_fun;
2902 /* So: maybe the current sequence can be terminated here? */
2903 if((tbtp = isp->tbtp)->tbt_bind != NULL){
2904 jhave_bind:
2905 tbf = tbtp->tbt_bind->tbc_flags;
2906 jmle_fun:
2907 if(tbf & a_TTY_BIND_FUN_INTERNAL){
2908 switch(a_tty_fun(tlp, tbf, &len)){
2909 case a_TTY_FUN_STATUS_OK:
2910 goto jinput_loop;
2911 case a_TTY_FUN_STATUS_COMMIT:
2912 goto jdone;
2913 case a_TTY_FUN_STATUS_RESTART:
2914 goto jrestart;
2915 case a_TTY_FUN_STATUS_END:
2916 goto jleave;
2918 assert(0);
2919 }else if(tbtp->tbt_bind->tbc_flags & a_TTY_BIND_NOCOMMIT){
2920 struct a_tty_bind_ctx *tbcp;
2922 tbcp = tbtp->tbt_bind;
2923 memcpy(tlp->tl_defc.s = salloc(
2924 (tlp->tl_defc.l = len = tbcp->tbc_exp_len) +1),
2925 tbcp->tbc_exp, tbcp->tbc_exp_len +1);
2926 goto jrestart;
2927 }else{
2928 tlp->tl_reenter_after_cmd = tbtp->tbt_bind->tbc_exp;
2929 goto jdone;
2934 /* Otherwise take over all chars "as is" */
2935 jtake_over:
2936 for(; isp_head != NULL; isp_head = isp_head->next)
2937 if(a_tty_kother(tlp, isp_head->tbtp->tbt_char)){
2938 /* FIXME */
2940 /* And the current one too */
2941 goto jkother;
2943 # endif /* HAVE_KEY_BINDINGS */
2945 if((flags & a_BUFMODE) && (len -= (size_t)rv) == 0){
2946 /* Buffer mode completed */
2947 tlp->tl_defc.s = NULL;
2948 tlp->tl_defc.l = 0;
2949 flags &= ~a_BUFMODE;
2951 break;
2954 # ifndef HAVE_KEY_BINDINGS
2955 /* Don't interpret control bytes during buffer mode.
2956 * Otherwise, if it's a control byte check whether it is a MLE
2957 * function. Remarks: initially a complete duplicate to be able to
2958 * switch(), later converted to simply iterate over (an #ifdef'd
2959 * subset of) the MLE base_tuple table in order to have "a SPOF" */
2960 if(cbuf == cbuf_base && n_uasciichar(wc) && cntrlchar((char)wc)){
2961 struct a_tty_bind_builtin_tuple const *tbbtp, *tbbtp_max;
2962 char c;
2964 c = (char)wc ^ 0x40;
2965 tbbtp = a_tty_bind_base_tuples;
2966 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_base_tuples)];
2967 jbuiltin_redo:
2968 for(; tbbtp < tbbtp_max; ++tbbtp){
2969 /* Assert default_tuple table is properly subset'ed */
2970 assert(tbbtp->tbdt_iskey);
2971 if(tbbtp->tbbt_ckey == c){
2972 if(tbbtp->tbbt_exp[0] == '\0'){
2973 enum a_tty_bind_flags tbf;
2975 tbf = a_TTY_BIND_FUN_EXPAND((ui8_t)tbbtp->tbbt_exp[1]);
2976 switch(a_tty_fun(tlp, tbf, &len)){
2977 case a_TTY_FUN_STATUS_OK:
2978 goto jinput_loop;
2979 case a_TTY_FUN_STATUS_COMMIT:
2980 goto jdone;
2981 case a_TTY_FUN_STATUS_RESTART:
2982 goto jrestart;
2983 case a_TTY_FUN_STATUS_END:
2984 goto jleave;
2986 assert(0);
2987 }else{
2988 tlp->tl_reenter_after_cmd = tbbtp->tbbt_exp;
2989 goto jdone;
2993 if(tbbtp ==
2994 &a_tty_bind_base_tuples[n_NELEM(a_tty_bind_base_tuples)]){
2995 tbbtp = a_tty_bind_default_tuples;
2996 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_default_tuples)];
2997 goto jbuiltin_redo;
3000 # endif /* !HAVE_KEY_BINDINGS */
3002 # ifdef HAVE_KEY_BINDINGS
3003 jkother:
3004 # endif
3005 if(a_tty_kother(tlp, wc)){
3006 /* Don't clear the history during buffer mode.. */
3007 # ifdef HAVE_HISTORY
3008 if(!(flags & a_BUFMODE) && cbuf == cbuf_base)
3009 tlp->tl_hist = NULL;
3010 # endif
3015 /* We have a completed input line, convert the struct cell data to its
3016 * plain character equivalent */
3017 jdone:
3018 rv = a_tty_cell2dat(tlp);
3019 jleave:
3020 putc('\n', n_tty_fp);
3021 fflush(n_tty_fp);
3022 NYD_LEAVE;
3023 return rv;
3026 # ifdef HAVE_KEY_BINDINGS
3027 static enum n_lexinput_flags
3028 a_tty_bind_ctx_find(char const *name){
3029 enum n_lexinput_flags rv;
3030 struct a_tty_bind_ctx_map const *tbcmp;
3031 NYD2_ENTER;
3033 tbcmp = a_tty_bind_ctx_maps;
3034 do if(!asccasecmp(tbcmp->tbcm_name, name)){
3035 rv = tbcmp->tbcm_ctx;
3036 goto jleave;
3037 }while(PTRCMP(++tbcmp, <,
3038 &a_tty_bind_ctx_maps[n_NELEM(a_tty_bind_ctx_maps)]));
3040 rv = (enum n_lexinput_flags)-1;
3041 jleave:
3042 NYD2_LEAVE;
3043 return rv;
3046 static bool_t
3047 a_tty_bind_create(struct a_tty_bind_parse_ctx *tbpcp, bool_t replace){
3048 struct a_tty_bind_ctx *tbcp;
3049 bool_t rv;
3050 NYD2_ENTER;
3052 rv = FAL0;
3054 if(!a_tty_bind_parse(TRU1, tbpcp))
3055 goto jleave;
3057 /* Since we use a single buffer for it all, need to replace as such */
3058 if(tbpcp->tbpc_tbcp != NULL){
3059 if(!replace)
3060 goto jleave;
3061 a_tty_bind_del(tbpcp);
3062 }else if(a_tty.tg_bind_cnt == UI32_MAX){
3063 n_err(_("`bind': maximum number of bindings already established\n"));
3064 goto jleave;
3067 /* C99 */{
3068 size_t i, j;
3070 tbcp = smalloc(n_VSTRUCT_SIZEOF(struct a_tty_bind_ctx, tbc__buf) +
3071 tbpcp->tbpc_seq_len + tbpcp->tbpc_exp.l +
3072 n_MAX(sizeof(si32_t), sizeof(wc_t)) + tbpcp->tbpc_cnv_len +3);
3073 if(tbpcp->tbpc_ltbcp != NULL){
3074 tbcp->tbc_next = tbpcp->tbpc_ltbcp->tbc_next;
3075 tbpcp->tbpc_ltbcp->tbc_next = tbcp;
3076 }else{
3077 enum n_lexinput_flags lif = tbpcp->tbpc_flags & n__LEXINPUT_CTX_MASK;
3079 tbcp->tbc_next = a_tty.tg_bind[lif];
3080 a_tty.tg_bind[lif] = tbcp;
3082 memcpy(tbcp->tbc_seq = &tbcp->tbc__buf[0],
3083 tbpcp->tbpc_seq, i = (tbcp->tbc_seq_len = tbpcp->tbpc_seq_len) +1);
3084 memcpy(tbcp->tbc_exp = &tbcp->tbc__buf[i],
3085 tbpcp->tbpc_exp.s, j = (tbcp->tbc_exp_len = tbpcp->tbpc_exp.l) +1);
3086 i += j;
3087 i = (i + tbpcp->tbpc_cnv_align_mask) & ~tbpcp->tbpc_cnv_align_mask;
3088 memcpy(tbcp->tbc_cnv = &tbcp->tbc__buf[i],
3089 tbpcp->tbpc_cnv, (tbcp->tbc_cnv_len = tbpcp->tbpc_cnv_len) +1);
3090 tbcp->tbc_flags = tbpcp->tbpc_flags;
3093 /* Directly resolve any termcap(5) symbol if we are already setup */
3094 if((pstate & PS_STARTED) &&
3095 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
3096 a_TTY_BIND_RESOLVE)
3097 a_tty_bind_resolve(tbcp);
3099 ++a_tty.tg_bind_cnt;
3100 /* If this binding is usable invalidate the key input lookup trees */
3101 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3102 a_tty.tg_bind_isdirty = TRU1;
3103 rv = TRU1;
3104 jleave:
3105 NYD2_LEAVE;
3106 return rv;
3109 static bool_t
3110 a_tty_bind_parse(bool_t isbindcmd, struct a_tty_bind_parse_ctx *tbpcp){
3111 enum{a_TRUE_RV = a_TTY__BIND_LAST<<1};
3113 struct n_visual_info_ctx vic;
3114 struct str shin_save, shin;
3115 struct n_string shou, *shoup;
3116 size_t i;
3117 struct kse{
3118 struct kse *next;
3119 char *seq_dat;
3120 wc_t *cnv_dat;
3121 ui32_t seq_len;
3122 ui32_t cnv_len; /* High bit set if a termap to be resolved */
3123 ui32_t calc_cnv_len; /* Ditto, but aligned etc. */
3124 ui8_t kse__dummy[4];
3125 } *head, *tail;
3126 ui32_t f;
3127 NYD2_ENTER;
3128 n_LCTA(UICMP(64, a_TRUE_RV, <, UI32_MAX),
3129 "Flag bits excess storage datatype");
3131 f = n_LEXINPUT_NONE;
3132 shoup = n_string_creat_auto(&shou);
3133 head = tail = NULL;
3135 /* Parse the key-sequence */
3136 for(shin.s = n_UNCONST(tbpcp->tbpc_in_seq), shin.l = UIZ_MAX;;){
3137 struct kse *ep;
3138 enum n_shexp_state shs;
3140 shin_save = shin;
3141 shs = n_shexp_parse_token(shoup, &shin,
3142 n_SHEXP_PARSE_TRUNC | n_SHEXP_PARSE_TRIMSPACE |
3143 n_SHEXP_PARSE_IGNORE_EMPTY | n_SHEXP_PARSE_IFS_IS_COMMA);
3144 if(shs & n_SHEXP_STATE_ERR_UNICODE){
3145 f |= a_TTY_BIND_DEFUNCT;
3146 if(isbindcmd && (options & OPT_D_V))
3147 n_err(_("`%s': \\uNICODE not available in locale: %s\n"),
3148 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3150 if((shs & n_SHEXP_STATE_ERR_MASK) & ~n_SHEXP_STATE_ERR_UNICODE){
3151 n_err(_("`%s': failed to parse key-sequence: %s\n"),
3152 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3153 goto jleave;
3155 if((shs & (n_SHEXP_STATE_OUTPUT | n_SHEXP_STATE_STOP)) ==
3156 n_SHEXP_STATE_STOP)
3157 break;
3159 ep = salloc(sizeof *ep);
3160 if(head == NULL)
3161 head = ep;
3162 else
3163 tail->next = ep;
3164 tail = ep;
3165 ep->next = NULL;
3166 if(!(shs & n_SHEXP_STATE_ERR_UNICODE)){
3167 i = strlen(ep->seq_dat = n_shexp_quote_cp(n_string_cp(shoup), TRU1));
3168 if(i >= SI32_MAX - 1)
3169 goto jelen;
3170 ep->seq_len = (ui32_t)i;
3171 }else{
3172 /* Otherwise use the original buffer, _we_ can only quote it the wrong
3173 * way (e.g., an initial $'\u3a' becomes '\u3a'), _then_ */
3174 if((i = shin_save.l - shin.l) >= SI32_MAX - 1)
3175 goto jelen;
3176 ep->seq_len = (ui32_t)i;
3177 ep->seq_dat = savestrbuf(shin_save.s, i);
3180 memset(&vic, 0, sizeof vic);
3181 vic.vic_inlen = shoup->s_len;
3182 vic.vic_indat = shoup->s_dat;
3183 if(!n_visual_info(&vic,
3184 n_VISUAL_INFO_WOUT_CREATE | n_VISUAL_INFO_WOUT_SALLOC)){
3185 n_err(_("`%s': key-sequence seems to contain invalid "
3186 "characters: %s: %s\n"),
3187 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
3188 f |= a_TTY_BIND_DEFUNCT;
3189 goto jleave;
3190 }else if(vic.vic_woulen == 0 ||
3191 vic.vic_woulen >= (SI32_MAX - 2) / sizeof(wc_t)){
3192 jelen:
3193 n_err(_("`%s': length of key-sequence unsupported: %s: %s\n"),
3194 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
3195 f |= a_TTY_BIND_DEFUNCT;
3196 goto jleave;
3198 ep->cnv_dat = vic.vic_woudat;
3199 ep->cnv_len = (ui32_t)vic.vic_woulen;
3201 /* A termcap(5)/terminfo(5) identifier? */
3202 if(ep->cnv_len > 1 && ep->cnv_dat[0] == ':'){
3203 i = --ep->cnv_len, ++ep->cnv_dat;
3204 # ifndef HAVE_TERMCAP
3205 if(options & OPT_D_V)
3206 n_err(_("`%s': no termcap(5)/terminfo(5) support: %s: %s\n"),
3207 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3208 f |= a_TTY_BIND_DEFUNCT;
3209 # endif
3210 if(i > a_TTY_BIND_CAPNAME_MAX){
3211 n_err(_("`%s': termcap(5)/terminfo(5) name too long: %s: %s\n"),
3212 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3213 f |= a_TTY_BIND_DEFUNCT;
3215 while(i > 0)
3216 /* (We store it as char[]) */
3217 if((ui32_t)ep->cnv_dat[--i] & ~0x7Fu){
3218 n_err(_("`%s': invalid termcap(5)/terminfo(5) name content: "
3219 "%s: %s\n"),
3220 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3221 f |= a_TTY_BIND_DEFUNCT;
3222 break;
3224 ep->cnv_len |= SI32_MIN; /* Needs resolve */
3225 f |= a_TTY_BIND_RESOLVE;
3228 if(shs & n_SHEXP_STATE_STOP)
3229 break;
3232 if(head == NULL){
3233 jeempty:
3234 n_err(_("`%s': effectively empty key-sequence: %s\n"),
3235 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3236 goto jleave;
3239 if(isbindcmd) /* (Or always, just "1st time init") */
3240 tbpcp->tbpc_cnv_align_mask = n_MAX(sizeof(si32_t), sizeof(wc_t)) - 1;
3242 /* C99 */{
3243 struct a_tty_bind_ctx *ltbcp, *tbcp;
3244 char *cpbase, *cp, *cnv;
3245 size_t sl, cl;
3247 /* Unite the parsed sequence(s) into single string representations */
3248 for(sl = cl = 0, tail = head; tail != NULL; tail = tail->next){
3249 sl += tail->seq_len + 1;
3251 if(!isbindcmd)
3252 continue;
3254 /* Preserve room for terminal capabilities to be resolved.
3255 * Above we have ensured the buffer will fit in these calculations */
3256 if((i = tail->cnv_len) & SI32_MIN){
3257 /* For now
3258 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[]+NUL;}
3259 * later
3260 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3261 n_LCTAV(n_ISPOW2(a_TTY_BIND_CAPEXP_ROUNDUP));
3262 n_LCTA(a_TTY_BIND_CAPEXP_ROUNDUP >= sizeof(wc_t),
3263 "Aligning on this constant doesn't properly align wc_t");
3264 i &= SI32_MAX;
3265 i *= sizeof(wc_t);
3266 i += sizeof(si32_t);
3267 if(i < a_TTY_BIND_CAPEXP_ROUNDUP)
3268 i = (i + (a_TTY_BIND_CAPEXP_ROUNDUP - 1)) &
3269 ~(a_TTY_BIND_CAPEXP_ROUNDUP - 1);
3270 }else
3271 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3272 i *= sizeof(wc_t);
3273 i += sizeof(si32_t) + sizeof(wc_t); /* (buf_len_iscap, NUL) */
3274 cl += i;
3275 if(tail->cnv_len & SI32_MIN){
3276 tail->cnv_len &= SI32_MAX;
3277 i |= SI32_MIN;
3279 tail->calc_cnv_len = (ui32_t)i;
3281 --sl;
3283 tbpcp->tbpc_seq_len = sl;
3284 tbpcp->tbpc_cnv_len = cl;
3285 /* C99 */{
3286 size_t j;
3288 j = i = sl + 1; /* Room for comma separator */
3289 if(isbindcmd){
3290 i = (i + tbpcp->tbpc_cnv_align_mask) & ~tbpcp->tbpc_cnv_align_mask;
3291 j = i;
3292 i += cl;
3294 tbpcp->tbpc_seq = cp = cpbase = salloc(i);
3295 tbpcp->tbpc_cnv = cnv = &cpbase[j];
3298 for(tail = head; tail != NULL; tail = tail->next){
3299 memcpy(cp, tail->seq_dat, tail->seq_len);
3300 cp += tail->seq_len;
3301 *cp++ = ',';
3303 if(isbindcmd){
3304 char * const save_cnv = cnv;
3306 n_UNALIGN(si32_t*,cnv)[0] = (si32_t)(i = tail->calc_cnv_len);
3307 cnv += sizeof(si32_t);
3308 if(i & SI32_MIN){
3309 /* For now
3310 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];}
3311 * later
3312 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[];} */
3313 n_UNALIGN(si32_t*,cnv)[0] = tail->cnv_len;
3314 cnv += sizeof(si32_t);
3316 i = tail->cnv_len * sizeof(wc_t);
3317 memcpy(cnv, tail->cnv_dat, i);
3318 cnv += i;
3319 *n_UNALIGN(wc_t*,cnv) = '\0';
3321 cnv = save_cnv + (tail->calc_cnv_len & SI32_MAX);
3324 *--cp = '\0';
3326 /* Search for a yet existing identical mapping */
3327 for(ltbcp = NULL, tbcp = a_tty.tg_bind[tbpcp->tbpc_flags]; tbcp != NULL;
3328 ltbcp = tbcp, tbcp = tbcp->tbc_next)
3329 if(tbcp->tbc_seq_len == sl && !memcmp(tbcp->tbc_seq, cpbase, sl)){
3330 tbpcp->tbpc_tbcp = tbcp;
3331 break;
3333 tbpcp->tbpc_ltbcp = ltbcp;
3334 tbpcp->tbpc_flags |= (f & a_TTY__BIND_MASK);
3337 /* Create single string expansion if so desired */
3338 if(isbindcmd){
3339 char *exp;
3341 exp = tbpcp->tbpc_exp.s;
3343 i = tbpcp->tbpc_exp.l;
3344 if(i > 0 && exp[i - 1] == '@'){
3345 while(--i > 0){
3346 if(!blankspacechar(exp[i - 1]))
3347 break;
3349 if(i == 0)
3350 goto jeempty;
3352 exp[tbpcp->tbpc_exp.l = i] = '\0';
3353 tbpcp->tbpc_flags |= a_TTY_BIND_NOCOMMIT;
3356 /* Reverse solidus cannot be placed last in expansion to avoid (at the
3357 * time of this writing) possible problems with newline escaping.
3358 * Don't care about (un)even number thereof */
3359 if(i > 0 && exp[i - 1] == '\\'){
3360 n_err(_("`%s': reverse solidus cannot be last in expansion: %s\n"),
3361 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3362 goto jleave;
3365 /* It may map to an internal MLE command! */
3366 for(i = 0; i < n_NELEM(a_tty_bind_fun_names); ++i)
3367 if(!asccasecmp(exp, a_tty_bind_fun_names[i])){
3368 tbpcp->tbpc_flags |= a_TTY_BIND_FUN_EXPAND(i) |
3369 a_TTY_BIND_FUN_INTERNAL |
3370 (head->next == NULL ? a_TTY_BIND_MLE1CNTRL : 0);
3371 if((options & OPT_D_V) && (tbpcp->tbpc_flags & a_TTY_BIND_NOCOMMIT))
3372 n_err(_("`%s': MLE commands can't be made editable via @: %s\n"),
3373 tbpcp->tbpc_cmd, exp);
3374 tbpcp->tbpc_flags &= ~a_TTY_BIND_NOCOMMIT;
3375 break;
3379 f |= a_TRUE_RV; /* TODO because we only now true and false; DEFUNCT.. */
3380 jleave:
3381 n_string_gut(shoup);
3382 NYD2_LEAVE;
3383 return (f & a_TRUE_RV) != 0;
3386 static void
3387 a_tty_bind_resolve(struct a_tty_bind_ctx *tbcp){
3388 char capname[a_TTY_BIND_CAPNAME_MAX +1];
3389 struct n_termcap_value tv;
3390 size_t len;
3391 bool_t isfirst; /* TODO For now: first char must be control! */
3392 char *cp, *next;
3393 NYD2_ENTER;
3395 n_UNINIT(next, NULL);
3396 for(cp = tbcp->tbc_cnv, isfirst = TRU1, len = tbcp->tbc_cnv_len;
3397 len > 0; isfirst = FAL0, cp = next){
3398 /* C99 */{
3399 si32_t i, j;
3401 i = n_UNALIGN(si32_t*,cp)[0];
3402 j = i & SI32_MAX;
3403 next = &cp[j];
3404 len -= j;
3405 if(i == j)
3406 continue;
3408 /* struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];} */
3409 cp += sizeof(si32_t);
3410 i = n_UNALIGN(si32_t*,cp)[0];
3411 cp += sizeof(si32_t);
3412 for(j = 0; j < i; ++j)
3413 capname[j] = n_UNALIGN(wc_t*,cp)[j];
3414 capname[j] = '\0';
3417 /* Use generic lookup mechanism if not a known query */
3418 /* C99 */{
3419 si32_t tq;
3421 tq = n_termcap_query_for_name(capname, n_TERMCAP_CAPTYPE_STRING);
3422 if(tq == -1){
3423 tv.tv_data.tvd_string = capname;
3424 tq = n__TERMCAP_QUERY_MAX1;
3427 if(tq < 0 || !n_termcap_query(tq, &tv)){
3428 if(options & OPT_D_V)
3429 n_err(_("`bind': unknown or unsupported capability: %s: %s\n"),
3430 capname, tbcp->tbc_seq);
3431 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3432 break;
3436 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3437 /* C99 */{
3438 size_t i;
3440 i = strlen(tv.tv_data.tvd_string);
3441 if(/*i > SI32_MAX ||*/ i >= PTR2SIZE(next - cp)){
3442 if(options & OPT_D_V)
3443 n_err(_("`bind': capability expansion too long: %s: %s\n"),
3444 capname, tbcp->tbc_seq);
3445 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3446 break;
3447 }else if(i == 0){
3448 if(options & OPT_D_V)
3449 n_err(_("`bind': empty capability expansion: %s: %s\n"),
3450 capname, tbcp->tbc_seq);
3451 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3452 break;
3453 }else if(isfirst && !cntrlchar(*tv.tv_data.tvd_string)){
3454 if(options & OPT_D_V)
3455 n_err(_("`bind': capability expansion doesn't start with "
3456 "control: %s: %s\n"), capname, tbcp->tbc_seq);
3457 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3458 break;
3460 n_UNALIGN(si32_t*,cp)[-1] = (si32_t)i;
3461 memcpy(cp, tv.tv_data.tvd_string, i);
3462 cp[i] = '\0';
3465 NYD2_LEAVE;
3468 static void
3469 a_tty_bind_del(struct a_tty_bind_parse_ctx *tbpcp){
3470 struct a_tty_bind_ctx *ltbcp, *tbcp;
3471 NYD2_ENTER;
3473 tbcp = tbpcp->tbpc_tbcp;
3475 if((ltbcp = tbpcp->tbpc_ltbcp) != NULL)
3476 ltbcp->tbc_next = tbcp->tbc_next;
3477 else
3478 a_tty.tg_bind[tbpcp->tbpc_flags] = tbcp->tbc_next;
3479 free(tbcp);
3481 --a_tty.tg_bind_cnt;
3482 a_tty.tg_bind_isdirty = TRU1;
3483 NYD2_LEAVE;
3486 static void
3487 a_tty_bind_tree_build(void){
3488 size_t i;
3489 NYD2_ENTER;
3491 for(i = 0; i < n__LEXINPUT_CTX_MAX1; ++i){
3492 struct a_tty_bind_ctx *tbcp;
3493 n_LCTAV(n_LEXINPUT_CTX_BASE == 0);
3495 /* Somewhat wasteful, but easier to handle: simply clone the entire
3496 * primary key onto the secondary one, then only modify it */
3497 for(tbcp = a_tty.tg_bind[n_LEXINPUT_CTX_BASE]; tbcp != NULL;
3498 tbcp = tbcp->tbc_next)
3499 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3500 a_tty__bind_tree_add(n_LEXINPUT_CTX_BASE, &a_tty.tg_bind_tree[i][0],
3501 tbcp);
3503 if(i != n_LEXINPUT_CTX_BASE)
3504 for(tbcp = a_tty.tg_bind[i]; tbcp != NULL; tbcp = tbcp->tbc_next)
3505 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3506 a_tty__bind_tree_add(i, &a_tty.tg_bind_tree[i][0], tbcp);
3509 a_tty.tg_bind_isbuild = TRU1;
3510 NYD2_LEAVE;
3513 static void
3514 a_tty_bind_tree_teardown(void){
3515 size_t i, j;
3516 NYD2_ENTER;
3518 memset(&a_tty.tg_bind_shcut_cancel[0], 0,
3519 sizeof(a_tty.tg_bind_shcut_cancel));
3520 memset(&a_tty.tg_bind_shcut_prompt_char[0], 0,
3521 sizeof(a_tty.tg_bind_shcut_prompt_char));
3523 for(i = 0; i < n__LEXINPUT_CTX_MAX1; ++i)
3524 for(j = 0; j < HSHSIZE; ++j)
3525 a_tty__bind_tree_free(a_tty.tg_bind_tree[i][j]);
3526 memset(&a_tty.tg_bind_tree[0], 0, sizeof(a_tty.tg_bind_tree));
3528 a_tty.tg_bind_isdirty = a_tty.tg_bind_isbuild = FAL0;
3529 NYD2_LEAVE;
3532 static void
3533 a_tty__bind_tree_add(ui32_t hmap_idx, struct a_tty_bind_tree *store[HSHSIZE],
3534 struct a_tty_bind_ctx *tbcp){
3535 ui32_t cnvlen;
3536 char const *cnvdat;
3537 struct a_tty_bind_tree *ntbtp;
3538 NYD2_ENTER;
3539 n_UNUSED(hmap_idx);
3541 ntbtp = NULL;
3543 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len; cnvlen > 0;){
3544 union {wchar_t const *wp; char const *cp;} u;
3545 si32_t entlen;
3547 /* {si32_t buf_len_iscap;} */
3548 entlen = *n_UNALIGN(si32_t const*,cnvdat);
3550 if(entlen & SI32_MIN){
3551 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;}
3552 * Note that empty capabilities result in DEFUNCT */
3553 for(u.cp = (char const*)&n_UNALIGN(si32_t const*,cnvdat)[2];
3554 *u.cp != '\0'; ++u.cp)
3555 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.cp, TRU1);
3556 assert(ntbtp != NULL);
3557 ntbtp->tbt_isseq_trail = TRU1;
3558 entlen &= SI32_MAX;
3559 }else{
3560 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3561 bool_t isseq;
3563 u.wp = (wchar_t const*)&n_UNALIGN(si32_t const*,cnvdat)[1];
3565 /* May be a special shortcut function? */
3566 if(ntbtp == NULL && (tbcp->tbc_flags & a_TTY_BIND_MLE1CNTRL)){
3567 char *cp;
3568 ui32_t ctx, fun;
3570 ctx = tbcp->tbc_flags & n__LEXINPUT_CTX_MASK;
3571 fun = tbcp->tbc_flags & a_TTY__BIND_FUN_MASK;
3573 if(fun == a_TTY_BIND_FUN_CANCEL){
3574 for(cp = &a_tty.tg_bind_shcut_cancel[ctx][0];
3575 PTRCMP(cp, <, &a_tty.tg_bind_shcut_cancel[ctx]
3576 [n_NELEM(a_tty.tg_bind_shcut_cancel[ctx]) - 1]); ++cp)
3577 if(*cp == '\0'){
3578 *cp = (char)*u.wp;
3579 break;
3581 }else if(fun == a_TTY_BIND_FUN_PROMPT_CHAR){
3582 for(cp = &a_tty.tg_bind_shcut_prompt_char[ctx][0];
3583 PTRCMP(cp, <, &a_tty.tg_bind_shcut_prompt_char[ctx]
3584 [n_NELEM(a_tty.tg_bind_shcut_prompt_char[ctx]) - 1]);
3585 ++cp)
3586 if(*cp == '\0'){
3587 *cp = (char)*u.wp;
3588 break;
3593 isseq = (u.wp[1] != '\0');
3594 for(; *u.wp != '\0'; ++u.wp)
3595 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.wp, isseq);
3596 if(isseq)
3597 ntbtp->tbt_isseq_trail = TRU1;
3600 cnvlen -= entlen;
3601 cnvdat += entlen;
3604 /* Should have been rendered defunctional at first instead */
3605 assert(ntbtp != NULL);
3606 ntbtp->tbt_bind = tbcp;
3607 NYD2_LEAVE;
3610 static struct a_tty_bind_tree *
3611 a_tty__bind_tree_add_wc(struct a_tty_bind_tree **treep,
3612 struct a_tty_bind_tree *parentp, wchar_t wc, bool_t isseq){
3613 struct a_tty_bind_tree *tbtp, *xtbtp;
3614 NYD2_ENTER;
3616 if(parentp == NULL){
3617 treep += wc % HSHSIZE;
3619 /* Having no parent also means that the tree slot is possibly empty */
3620 for(tbtp = *treep; tbtp != NULL;
3621 parentp = tbtp, tbtp = tbtp->tbt_sibling){
3622 if(tbtp->tbt_char != wc)
3623 continue;
3624 if(tbtp->tbt_isseq == isseq)
3625 goto jleave;
3626 /* isseq MUST be linked before !isseq, so record this "parent"
3627 * sibling, but continue searching for now */
3628 if(!isseq)
3629 parentp = tbtp;
3630 /* Otherwise it is impossible that we'll find what we look for */
3631 else{
3632 #ifdef HAVE_DEBUG
3633 while((tbtp = tbtp->tbt_sibling) != NULL)
3634 assert(tbtp->tbt_char != wc);
3635 #endif
3636 break;
3640 tbtp = smalloc(sizeof *tbtp);
3641 memset(tbtp, 0, sizeof *tbtp);
3642 tbtp->tbt_char = wc;
3643 tbtp->tbt_isseq = isseq;
3645 if(parentp == NULL){
3646 tbtp->tbt_sibling = *treep;
3647 *treep = tbtp;
3648 }else{
3649 tbtp->tbt_sibling = parentp->tbt_sibling;
3650 parentp->tbt_sibling = tbtp;
3652 }else{
3653 if((tbtp = *(treep = &parentp->tbt_childs)) != NULL){
3654 for(;; tbtp = xtbtp){
3655 if(tbtp->tbt_char == wc){
3656 if(tbtp->tbt_isseq == isseq)
3657 goto jleave;
3658 /* isseq MUST be linked before, so it is impossible that we'll
3659 * find what we look for */
3660 if(isseq){
3661 #ifdef HAVE_DEBUG
3662 while((tbtp = tbtp->tbt_sibling) != NULL)
3663 assert(tbtp->tbt_char != wc);
3664 #endif
3665 tbtp = NULL;
3666 break;
3670 if((xtbtp = tbtp->tbt_sibling) == NULL){
3671 treep = &tbtp->tbt_sibling;
3672 break;
3677 xtbtp = smalloc(sizeof *xtbtp);
3678 memset(xtbtp, 0, sizeof *xtbtp);
3679 xtbtp->tbt_parent = parentp;
3680 xtbtp->tbt_char = wc;
3681 xtbtp->tbt_isseq = isseq;
3682 tbtp = xtbtp;
3683 *treep = tbtp;
3685 jleave:
3686 NYD2_LEAVE;
3687 return tbtp;
3690 static void
3691 a_tty__bind_tree_free(struct a_tty_bind_tree *tbtp){
3692 NYD2_ENTER;
3693 while(tbtp != NULL){
3694 struct a_tty_bind_tree *tmp;
3696 if((tmp = tbtp->tbt_childs) != NULL)
3697 a_tty__bind_tree_free(tmp);
3699 tmp = tbtp->tbt_sibling;
3700 free(tbtp);
3701 tbtp = tmp;
3703 NYD2_LEAVE;
3705 # endif /* HAVE_KEY_BINDINGS */
3707 FL void
3708 n_tty_init(void){
3709 NYD_ENTER;
3711 if(ok_blook(line_editor_disable))
3712 goto jleave;
3714 /* Load the history file */
3715 # ifdef HAVE_HISTORY
3716 do/* for break */{
3717 long hs;
3718 char const *v;
3719 char *lbuf;
3720 FILE *f;
3721 size_t lsize, cnt, llen;
3723 a_TTY_HISTSIZE(hs);
3724 a_tty.tg_hist_size = 0;
3725 a_tty.tg_hist_size_max = (size_t)hs;
3726 if(hs == 0)
3727 break;
3729 a_TTY_HISTFILE(v);
3730 if(v == NULL)
3731 break;
3733 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
3734 f = fopen(v, "r"); /* TODO HISTFILE LOAD: use linebuf pool */
3735 if(f == NULL)
3736 goto jhist_done;
3737 (void)n_file_lock(fileno(f), FLT_READ, 0,0, UIZ_MAX);
3739 assert(!(pstate & PS_ROOT));
3740 pstate |= PS_ROOT; /* Allow calling addhist() */
3741 lbuf = NULL;
3742 lsize = 0;
3743 cnt = (size_t)fsize(f);
3744 while(fgetline(&lbuf, &lsize, &cnt, &llen, f, FAL0) != NULL){
3745 if(llen > 0 && lbuf[llen - 1] == '\n')
3746 lbuf[--llen] = '\0';
3747 if(llen == 0 || lbuf[0] == '#') /* xxx comments? noone! */
3748 continue;
3749 else{
3750 bool_t isgabby;
3752 isgabby = (lbuf[0] == '*');
3753 n_tty_addhist(lbuf + isgabby, isgabby);
3756 if(lbuf != NULL)
3757 free(lbuf);
3758 pstate &= ~PS_ROOT;
3760 fclose(f);
3761 jhist_done:
3762 rele_all_sigs(); /* XXX remove jumps */
3763 }while(0);
3764 # endif /* HAVE_HISTORY */
3766 /* Force immediate resolve for anything which follows */
3767 pstate |= PS_LINE_EDITOR_INIT;
3769 # ifdef HAVE_KEY_BINDINGS
3770 /* `bind's (and `unbind's) done from within resource files couldn't be
3771 * performed for real since our termcap driver wasn't yet loaded, and we
3772 * can't perform automatic init since the user may have disallowed so */
3773 /* C99 */{
3774 struct a_tty_bind_ctx *tbcp;
3775 enum n_lexinput_flags lif;
3777 for(lif = 0; lif < n__LEXINPUT_CTX_MAX1; ++lif)
3778 for(tbcp = a_tty.tg_bind[lif]; tbcp != NULL; tbcp = tbcp->tbc_next)
3779 if((tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
3780 a_TTY_BIND_RESOLVE)
3781 a_tty_bind_resolve(tbcp);
3784 /* And we want to (try to) install some default key bindings */
3785 if(!ok_blook(line_editor_no_defaults)){
3786 char buf[8];
3787 struct a_tty_bind_parse_ctx tbpc;
3788 struct a_tty_bind_builtin_tuple const *tbbtp, *tbbtp_max;
3789 ui32_t flags;
3791 buf[0] = '$', buf[1] = '\'', buf[2] = '\\', buf[3] = 'c',
3792 buf[5] = '\'', buf[6] = '\0';
3794 tbbtp = a_tty_bind_base_tuples;
3795 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_base_tuples)];
3796 flags = n_LEXINPUT_CTX_BASE;
3797 jbuiltin_redo:
3798 for(; tbbtp < tbbtp_max; ++tbbtp){
3799 memset(&tbpc, 0, sizeof tbpc);
3800 tbpc.tbpc_cmd = "bind";
3801 if(tbbtp->tbbt_iskey){
3802 buf[4] = tbbtp->tbbt_ckey;
3803 tbpc.tbpc_in_seq = buf;
3804 }else
3805 tbpc.tbpc_in_seq = savecatsep(":", '\0',
3806 n_termcap_name_of_query(tbbtp->tbbt_query));
3807 tbpc.tbpc_exp.s = n_UNCONST(tbbtp->tbbt_exp[0] == '\0'
3808 ? a_tty_bind_fun_names[(ui8_t)tbbtp->tbbt_exp[1]]
3809 : tbbtp->tbbt_exp);
3810 tbpc.tbpc_exp.l = strlen(tbpc.tbpc_exp.s);
3811 tbpc.tbpc_flags = flags;
3812 /* ..but don't want to overwrite any user settings */
3813 a_tty_bind_create(&tbpc, FAL0);
3815 if(flags == n_LEXINPUT_CTX_BASE){
3816 tbbtp = a_tty_bind_default_tuples;
3817 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_default_tuples)];
3818 flags = n_LEXINPUT_CTX_DEFAULT;
3819 goto jbuiltin_redo;
3822 # endif /* HAVE_KEY_BINDINGS */
3824 jleave:
3825 NYD_LEAVE;
3828 FL void
3829 n_tty_destroy(void){
3830 NYD_ENTER;
3832 if(!(pstate & PS_LINE_EDITOR_INIT))
3833 goto jleave;
3835 # ifdef HAVE_HISTORY
3836 do/* for break */{
3837 long hs;
3838 char const *v;
3839 struct a_tty_hist *thp;
3840 bool_t dogabby;
3841 FILE *f;
3843 a_TTY_HISTSIZE(hs);
3844 if(hs == 0)
3845 break;
3847 a_TTY_HISTFILE(v);
3848 if(v == NULL)
3849 break;
3851 dogabby = ok_blook(history_gabby_persist);
3853 if((thp = a_tty.tg_hist) != NULL)
3854 for(; thp->th_older != NULL; thp = thp->th_older)
3855 if((dogabby || !thp->th_isgabby) && --hs == 0)
3856 break;
3858 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
3859 f = fopen(v, "w"); /* TODO temporary + rename?! */
3860 if(f == NULL)
3861 goto jhist_done;
3862 (void)n_file_lock(fileno(f), FLT_WRITE, 0,0, UIZ_MAX);
3864 for(; thp != NULL; thp = thp->th_younger){
3865 if(dogabby || !thp->th_isgabby){
3866 if(thp->th_isgabby)
3867 putc('*', f);
3868 fwrite(thp->th_dat, sizeof *thp->th_dat, thp->th_len, f);
3869 putc('\n', f);
3872 fclose(f);
3873 jhist_done:
3874 rele_all_sigs(); /* XXX remove jumps */
3875 }while(0);
3876 # endif /* HAVE_HISTORY */
3878 # if defined HAVE_KEY_BINDINGS && defined HAVE_DEBUG
3879 c_unbind(n_UNCONST("* *"));
3880 # endif
3882 # ifdef HAVE_DEBUG
3883 memset(&a_tty, 0, sizeof a_tty);
3884 # endif
3885 DBG( pstate &= ~PS_LINE_EDITOR_INIT; )
3886 jleave:
3887 NYD_LEAVE;
3890 FL void
3891 n_tty_signal(int sig){
3892 sigset_t nset, oset;
3893 NYD_X; /* Signal handler */
3895 switch(sig){
3896 # ifdef SIGWINCH
3897 case SIGWINCH:
3898 /* We don't deal with SIGWINCH, yet get called from main.c.
3899 * Note this case might get called even if !PS_LINE_EDITOR_INIT */
3900 break;
3901 # endif
3902 default:
3903 a_tty_term_mode(FAL0);
3904 n_TERMCAP_SUSPEND(TRU1);
3905 a_tty_sigs_down();
3907 sigemptyset(&nset);
3908 sigaddset(&nset, sig);
3909 sigprocmask(SIG_UNBLOCK, &nset, &oset);
3910 n_raise(sig);
3911 /* When we come here we'll continue editing, so reestablish */
3912 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
3914 a_tty_sigs_up();
3915 n_TERMCAP_RESUME(TRU1);
3916 a_tty_term_mode(TRU1);
3917 a_tty.tg_line->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
3918 break;
3922 FL int
3923 (n_tty_readline)(enum n_lexinput_flags lif, char const *prompt,
3924 char **linebuf, size_t *linesize, size_t n n_MEMORY_DEBUG_ARGS){
3925 struct a_tty_line tl;
3926 struct n_string xprompt;
3927 # ifdef HAVE_COLOUR
3928 char *posbuf, *pos;
3929 # endif
3930 ssize_t nn;
3931 ui32_t plen, pwidth;
3932 char const *orig_prompt;
3933 NYD_ENTER;
3934 n_UNUSED(lif);
3935 n_UNINIT(pwidth, 0);
3936 n_UNINIT(plen, 0);
3938 assert(!ok_blook(line_editor_disable));
3939 if(!(pstate & PS_LINE_EDITOR_INIT))
3940 n_tty_init();
3941 assert(pstate & PS_LINE_EDITOR_INIT);
3943 if(!(lif & n_LEXINPUT_PROMPT_NONE))
3944 n_string_creat_auto(&xprompt);
3945 orig_prompt = prompt;
3946 jredo:
3947 # ifdef HAVE_COLOUR
3948 n_colour_env_create(n_COLOUR_CTX_MLE, FAL0);
3949 # endif
3951 if(!(lif & n_LEXINPUT_PROMPT_NONE)){
3952 pwidth = n_tty_create_prompt(&xprompt, orig_prompt, lif);
3953 plen = (ui32_t)xprompt.s_len;
3954 prompt = (pwidth == 0) ? NULL : n_string_cp_const(&xprompt);
3957 # ifdef HAVE_COLOUR
3958 /* C99 */{
3959 char const *ccol;
3960 struct n_colour_pen *ccp;
3961 struct str const *sp;
3963 /* .tl_pos_buf is a hack */
3964 posbuf = pos = NULL;
3965 if((ccp = n_colour_pen_create(n_COLOUR_ID_MLE_POSITION, NULL)) != NULL &&
3966 (sp = n_colour_pen_to_str(ccp)) != NULL){
3967 ccol = sp->s;
3968 if((sp = n_colour_reset_to_str()) != NULL){
3969 size_t l1, l2;
3971 l1 = strlen(ccol);
3972 l2 = strlen(sp->s);
3973 posbuf = salloc(l1 + 4 + l2 +1);
3974 memcpy(posbuf, ccol, l1);
3975 pos = &posbuf[l1];
3976 memcpy(&pos[4], sp->s, ++l2);
3979 if(posbuf == NULL){
3980 posbuf = pos = salloc(4 +1);
3981 pos[4] = '\0';
3984 # endif /* HAVE_COLOUR */
3986 memset(&tl, 0, sizeof tl);
3988 # ifdef HAVE_KEY_BINDINGS
3989 /* C99 */{
3990 char const *cp = ok_vlook(bind_timeout);
3992 if(cp != NULL){
3993 ul_i ul;
3995 if((ul = strtoul(cp, NULL, 0)) > 0 &&
3996 /* Convert to tenths of a second, unfortunately */
3997 (ul = (ul + 99) / 100) <= a_TTY_BIND_TIMEOUT_MAX)
3998 tl.tl_bind_timeout = (ui8_t)ul;
3999 else if(options & OPT_D_V)
4000 n_err(_("Ignoring invalid *bind-timeout*: %s\n"), cp);
4004 if(a_tty.tg_bind_isdirty)
4005 a_tty_bind_tree_teardown();
4006 if(a_tty.tg_bind_cnt > 0 && !a_tty.tg_bind_isbuild)
4007 a_tty_bind_tree_build();
4008 tl.tl_bind_tree_hmap = &a_tty.tg_bind_tree[lif & n__LEXINPUT_CTX_MASK];
4009 tl.tl_bind_shcut_cancel =
4010 &a_tty.tg_bind_shcut_cancel[lif & n__LEXINPUT_CTX_MASK];
4011 tl.tl_bind_shcut_prompt_char =
4012 &a_tty.tg_bind_shcut_prompt_char[lif & n__LEXINPUT_CTX_MASK];
4013 # endif /* HAVE_KEY_BINDINGS */
4015 if(!(lif & n_LEXINPUT_PROMPT_NONE) && pwidth > 0){
4016 tl.tl_prompt = prompt;
4017 tl.tl_prompt_length = plen;
4018 tl.tl_prompt_width = pwidth;
4020 # ifdef HAVE_COLOUR
4021 tl.tl_pos_buf = posbuf;
4022 tl.tl_pos = pos;
4023 # endif
4025 tl.tl_line.cbuf = *linebuf;
4026 if(n != 0){
4027 tl.tl_defc.s = savestrbuf(*linebuf, n);
4028 tl.tl_defc.l = n;
4030 tl.tl_x_buf = linebuf;
4031 tl.tl_x_bufsize = linesize;
4033 a_tty.tg_line = &tl;
4034 a_tty_sigs_up();
4035 n_TERMCAP_RESUME(FAL0);
4036 a_tty_term_mode(TRU1);
4037 nn = a_tty_readline(&tl, n n_MEMORY_DEBUG_ARGSCALL);
4038 a_tty_term_mode(FAL0);
4039 n_TERMCAP_SUSPEND(FAL0);
4040 a_tty_sigs_down();
4041 a_tty.tg_line = NULL;
4043 # ifdef HAVE_COLOUR
4044 n_colour_env_gut(n_tty_fp);
4045 # endif
4047 if(tl.tl_reenter_after_cmd != NULL){
4048 n_source_command(lif, tl.tl_reenter_after_cmd);
4049 n = (nn <= 0) ? 0 : nn;
4050 if(!ok_blook(line_editor_disable))
4051 goto jredo;
4052 nn = (n_lex_input)(lif, orig_prompt, linebuf, linesize,
4053 (n == 0 ? n_empty : savestrbuf(*linebuf, n))
4054 n_MEMORY_DEBUG_ARGSCALL);
4056 NYD_LEAVE;
4057 return (int)nn;
4060 FL void
4061 n_tty_addhist(char const *s, bool_t isgabby){
4062 # ifdef HAVE_HISTORY
4063 /* Super-Heavy-Metal: block all sigs, avoid leaks+ on jump */
4064 ui32_t l;
4065 struct a_tty_hist *thp, *othp, *ythp;
4066 # endif
4067 NYD_ENTER;
4068 n_UNUSED(s);
4069 n_UNUSED(isgabby);
4071 # ifdef HAVE_HISTORY
4072 a_TTY_CHECK_ADDHIST(s, isgabby, goto j_leave);
4073 if(a_tty.tg_hist_size_max == 0)
4074 goto j_leave;
4076 l = (ui32_t)strlen(s);
4078 /* Eliminating duplicates is expensive, but simply inacceptable so
4079 * during the load of a potentially large history file! */
4080 if(pstate & PS_LINE_EDITOR_INIT)
4081 for(thp = a_tty.tg_hist; thp != NULL; thp = thp->th_older)
4082 if(thp->th_len == l && !strcmp(thp->th_dat, s)){
4083 hold_all_sigs(); /* TODO */
4084 if(thp->th_isgabby)
4085 thp->th_isgabby = !!isgabby;
4086 othp = thp->th_older;
4087 ythp = thp->th_younger;
4088 if(othp != NULL)
4089 othp->th_younger = ythp;
4090 else
4091 a_tty.tg_hist_tail = ythp;
4092 if(ythp != NULL)
4093 ythp->th_older = othp;
4094 else
4095 a_tty.tg_hist = othp;
4096 goto jleave;
4098 hold_all_sigs();
4100 ++a_tty.tg_hist_size;
4101 if((pstate & PS_LINE_EDITOR_INIT) &&
4102 a_tty.tg_hist_size > a_tty.tg_hist_size_max){
4103 --a_tty.tg_hist_size;
4104 if((thp = a_tty.tg_hist_tail) != NULL){
4105 if((a_tty.tg_hist_tail = thp->th_younger) == NULL)
4106 a_tty.tg_hist = NULL;
4107 else
4108 a_tty.tg_hist_tail->th_older = NULL;
4109 free(thp);
4113 thp = smalloc(n_VSTRUCT_SIZEOF(struct a_tty_hist, th_dat) + l +1);
4114 thp->th_isgabby = !!isgabby;
4115 thp->th_len = l;
4116 memcpy(thp->th_dat, s, l +1);
4117 jleave:
4118 if((thp->th_older = a_tty.tg_hist) != NULL)
4119 a_tty.tg_hist->th_younger = thp;
4120 else
4121 a_tty.tg_hist_tail = thp;
4122 thp->th_younger = NULL;
4123 a_tty.tg_hist = thp;
4125 rele_all_sigs();
4126 j_leave:
4127 # endif
4128 NYD_LEAVE;
4131 # ifdef HAVE_HISTORY
4132 FL int
4133 c_history(void *v){
4134 C_HISTORY_SHARED;
4136 jlist:{
4137 FILE *fp;
4138 size_t i, b;
4139 struct a_tty_hist *thp;
4141 if(a_tty.tg_hist == NULL)
4142 goto jleave;
4144 if((fp = Ftmp(NULL, "hist", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
4145 n_perr(_("tmpfile"), 0);
4146 v = NULL;
4147 goto jleave;
4150 i = a_tty.tg_hist_size;
4151 b = 0;
4152 for(thp = a_tty.tg_hist; thp != NULL;
4153 --i, b += thp->th_len, thp = thp->th_older)
4154 fprintf(fp,
4155 "%c%4" PRIuZ ". %-50.50s (%4" PRIuZ "+%2" PRIu32 " B)\n",
4156 (thp->th_isgabby ? '*' : ' '), i, thp->th_dat, b, thp->th_len);
4158 page_or_print(fp, i);
4159 Fclose(fp);
4161 goto jleave;
4163 jclear:{
4164 struct a_tty_hist *thp;
4166 while((thp = a_tty.tg_hist) != NULL){
4167 a_tty.tg_hist = thp->th_older;
4168 free(thp);
4170 a_tty.tg_hist_tail = NULL;
4171 a_tty.tg_hist_size = 0;
4173 goto jleave;
4175 jentry:{
4176 struct a_tty_hist *thp;
4178 if(UICMP(z, entry, <=, a_tty.tg_hist_size)){
4179 entry = (long)a_tty.tg_hist_size - entry;
4180 for(thp = a_tty.tg_hist;; thp = thp->th_older)
4181 if(thp == NULL)
4182 break;
4183 else if(entry-- != 0)
4184 continue;
4185 else{
4186 v = temporary_arg_v_store = thp->th_dat;
4187 goto jleave;
4190 v = NULL;
4192 goto jleave;
4194 # endif /* HAVE_HISTORY */
4196 # ifdef HAVE_KEY_BINDINGS
4197 FL int
4198 c_bind(void *v){
4199 n_CMD_ARG_DESC_SUBCLASS_DEF(bind, 3, a_tty_bind_cad) { /* TODO cmd_tab.h */
4200 {n_CMD_ARG_DESC_STRING, 0},
4201 {n_CMD_ARG_DESC_WYSH | n_CMD_ARG_DESC_OPTION |
4202 n_CMD_ARG_DESC_HONOUR_STOP,
4203 n_SHEXP_PARSE_DRYRUN | n_SHEXP_PARSE_LOG},
4204 {n_CMD_ARG_DESC_WYSH | n_CMD_ARG_DESC_OPTION | n_CMD_ARG_DESC_GREEDY |
4205 n_CMD_ARG_DESC_HONOUR_STOP,
4206 n_SHEXP_PARSE_IGNORE_EMPTY}
4207 } n_CMD_ARG_DESC_SUBCLASS_DEF_END;
4208 struct n_cmd_arg_ctx cac;
4209 struct a_tty_bind_ctx *tbcp;
4210 enum n_lexinput_flags lif;
4211 bool_t aster, show;
4212 union {char const *cp; char *p; char c;} c;
4213 NYD_ENTER;
4215 cac.cac_desc = n_CMD_ARG_DESC_SUBCLASS_CAST(&a_tty_bind_cad);
4216 cac.cac_indat = v;
4217 cac.cac_inlen = UIZ_MAX;
4218 if(!n_cmd_arg_parse(&cac)){
4219 v = NULL;
4220 goto jleave;
4223 c.cp = cac.cac_arg->ca_arg.ca_str.s;
4224 if(cac.cac_no == 1)
4225 show = TRU1;
4226 else
4227 show = !asccasecmp(cac.cac_arg->ca_next->ca_arg.ca_str.s, "show");
4228 aster = FAL0;
4230 if((lif = a_tty_bind_ctx_find(c.cp)) == (enum n_lexinput_flags)-1){
4231 if(!(aster = n_is_all_or_aster(c.cp)) || !show){
4232 n_err(_("`bind': invalid context: %s\n"), c.cp);
4233 v = NULL;
4234 goto jleave;
4236 lif = 0;
4239 if(show){
4240 ui32_t lns;
4241 FILE *fp;
4243 if((fp = Ftmp(NULL, "bind", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
4244 n_perr(_("tmpfile"), 0);
4245 v = NULL;
4246 goto jleave;
4249 lns = 0;
4250 for(;;){
4251 for(tbcp = a_tty.tg_bind[lif]; tbcp != NULL;
4252 ++lns, tbcp = tbcp->tbc_next){
4253 /* Print the bytes of resolved terminal capabilities, then */
4254 if((options & OPT_D_V) &&
4255 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)
4256 ) == a_TTY_BIND_RESOLVE){
4257 char cbuf[8];
4258 union {wchar_t const *wp; char const *cp;} u;
4259 si32_t entlen;
4260 ui32_t cnvlen;
4261 char const *cnvdat, *bsep, *cbufp;
4263 putc('#', fp);
4264 putc(' ', fp);
4266 cbuf[0] = '=', cbuf[2] = '\0';
4267 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len;
4268 cnvlen > 0;){
4269 if(cnvdat != tbcp->tbc_cnv)
4270 putc(',', fp);
4272 /* {si32_t buf_len_iscap;} */
4273 entlen = *n_UNALIGN(si32_t const*,cnvdat);
4274 if(entlen & SI32_MIN){
4275 /* struct{si32_t buf_len_iscap; si32_t cap_len;
4276 * char buf[]+NUL;} */
4277 for(bsep = n_empty,
4278 u.cp = (char const*)
4279 &n_UNALIGN(si32_t const*,cnvdat)[2];
4280 (c.c = *u.cp) != '\0'; ++u.cp){
4281 if(asciichar(c.c) && !cntrlchar(c.c))
4282 cbuf[1] = c.c, cbufp = cbuf;
4283 else
4284 cbufp = n_empty;
4285 fprintf(fp, "%s%02X%s",
4286 bsep, (ui32_t)(ui8_t)c.c, cbufp);
4287 bsep = " ";
4289 entlen &= SI32_MAX;
4290 }else
4291 putc('-', fp);
4293 cnvlen -= entlen;
4294 cnvdat += entlen;
4297 fputs("\n ", fp);
4298 ++lns;
4301 fprintf(fp, "%sbind %s %s %s%s%s\n",
4302 ((tbcp->tbc_flags & a_TTY_BIND_DEFUNCT)
4303 /* I18N: `bind' sequence not working, either because it is
4304 * I18N: using Unicode and that is not available in the locale,
4305 * I18N: or a termcap(5)/terminfo(5) sequence won't work out */
4306 ? _("# <Defunctional> ") : n_empty),
4307 a_tty_bind_ctx_maps[lif].tbcm_name, tbcp->tbc_seq,
4308 n_shexp_quote_cp(tbcp->tbc_exp, TRU1),
4309 (tbcp->tbc_flags & a_TTY_BIND_NOCOMMIT ? "@" : n_empty),
4310 (!(options & OPT_D_VV) ? n_empty
4311 : (tbcp->tbc_flags & a_TTY_BIND_FUN_INTERNAL
4312 ? _(" # MLE internal") : n_empty))
4315 if(!aster || ++lif >= n__LEXINPUT_CTX_MAX1)
4316 break;
4318 page_or_print(fp, lns);
4320 Fclose(fp);
4321 }else{
4322 struct a_tty_bind_parse_ctx tbpc;
4323 struct n_string store;
4325 memset(&tbpc, 0, sizeof tbpc);
4326 tbpc.tbpc_cmd = a_tty_bind_cad.cad_name;
4327 tbpc.tbpc_in_seq = cac.cac_arg->ca_next->ca_arg.ca_str.s;
4328 tbpc.tbpc_exp.s = n_string_cp(n_cmd_arg_join_greedy(&cac,
4329 n_string_creat_auto(&store)));
4330 tbpc.tbpc_exp.l = store.s_len;
4331 tbpc.tbpc_flags = lif;
4332 if(!a_tty_bind_create(&tbpc, TRU1))
4333 v = NULL;
4334 n_string_gut(&store);
4336 jleave:
4337 NYD_LEAVE;
4338 return (v != NULL) ? EXIT_OK : EXIT_ERR;
4341 FL int
4342 c_unbind(void *v){
4343 n_CMD_ARG_DESC_SUBCLASS_DEF(unbind, 2, a_tty_unbind_cad) {/* TODO cmd_tab.h*/
4344 {n_CMD_ARG_DESC_STRING, 0},
4345 {n_CMD_ARG_DESC_WYSH | n_CMD_ARG_DESC_HONOUR_STOP,
4346 n_SHEXP_PARSE_DRYRUN | n_SHEXP_PARSE_LOG}
4347 } n_CMD_ARG_DESC_SUBCLASS_DEF_END;
4348 struct a_tty_bind_parse_ctx tbpc;
4349 struct n_cmd_arg_ctx cac;
4350 struct a_tty_bind_ctx *tbcp;
4351 enum n_lexinput_flags lif;
4352 bool_t aster;
4353 union {char const *cp; char *p;} c;
4354 NYD_ENTER;
4356 cac.cac_desc = n_CMD_ARG_DESC_SUBCLASS_CAST(&a_tty_unbind_cad);
4357 cac.cac_indat = v;
4358 cac.cac_inlen = UIZ_MAX;
4359 if(!n_cmd_arg_parse(&cac)){
4360 v = NULL;
4361 goto jleave;
4364 c.cp = cac.cac_arg->ca_arg.ca_str.s;
4365 aster = FAL0;
4367 if((lif = a_tty_bind_ctx_find(c.cp)) == (enum n_lexinput_flags)-1){
4368 if(!(aster = n_is_all_or_aster(c.cp))){
4369 n_err(_("`unbind': invalid context: %s\n"), c.cp);
4370 v = NULL;
4371 goto jleave;
4373 lif = 0;
4376 c.cp = cac.cac_arg->ca_next->ca_arg.ca_str.s;
4377 jredo:
4378 if(n_is_all_or_aster(c.cp)){
4379 while((tbcp = a_tty.tg_bind[lif]) != NULL){
4380 memset(&tbpc, 0, sizeof tbpc);
4381 tbpc.tbpc_tbcp = tbcp;
4382 tbpc.tbpc_flags = lif;
4383 a_tty_bind_del(&tbpc);
4385 }else{
4386 memset(&tbpc, 0, sizeof tbpc);
4387 tbpc.tbpc_cmd = a_tty_unbind_cad.cad_name;
4388 tbpc.tbpc_in_seq = c.cp;
4389 tbpc.tbpc_flags = lif;
4391 if(n_UNLIKELY(!a_tty_bind_parse(FAL0, &tbpc)))
4392 v = NULL;
4393 else if(n_UNLIKELY((tbcp = tbpc.tbpc_tbcp) == NULL)){
4394 n_err(_("`unbind': no such `bind'ing: %s %s\n"),
4395 a_tty_bind_ctx_maps[lif].tbcm_name, c.cp);
4396 v = NULL;
4397 }else
4398 a_tty_bind_del(&tbpc);
4401 if(aster && ++lif < n__LEXINPUT_CTX_MAX1)
4402 goto jredo;
4403 jleave:
4404 NYD_LEAVE;
4405 return (v != NULL) ? EXIT_OK : EXIT_ERR;
4407 # endif /* HAVE_KEY_BINDINGS */
4409 #else /* HAVE_MLE */
4411 * The really-nothing-at-all implementation
4414 FL void
4415 n_tty_init(void){
4416 NYD_ENTER;
4417 NYD_LEAVE;
4420 FL void
4421 n_tty_destroy(void){
4422 NYD_ENTER;
4423 NYD_LEAVE;
4426 FL void
4427 n_tty_signal(int sig){
4428 NYD_X; /* Signal handler */
4429 n_UNUSED(sig);
4431 # ifdef HAVE_TERMCAP
4432 switch(sig){
4433 default:{
4434 sigset_t nset, oset;
4436 n_TERMCAP_SUSPEND(TRU1);
4437 a_tty_sigs_down();
4439 sigemptyset(&nset);
4440 sigaddset(&nset, sig);
4441 sigprocmask(SIG_UNBLOCK, &nset, &oset);
4442 n_raise(sig);
4443 /* When we come here we'll continue editing, so reestablish */
4444 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
4446 a_tty_sigs_up();
4447 n_TERMCAP_RESUME(TRU1);
4448 break;
4451 # endif /* HAVE_TERMCAP */
4454 FL int
4455 (n_tty_readline)(enum n_lexinput_flags lif, char const *prompt,
4456 char **linebuf, size_t *linesize, size_t n n_MEMORY_DEBUG_ARGS){
4457 struct n_string xprompt;
4458 int rv;
4459 NYD_ENTER;
4461 if(!(lif & n_LEXINPUT_PROMPT_NONE)){
4462 if(n_tty_create_prompt(n_string_creat_auto(&xprompt), prompt, lif) > 0){
4463 fwrite(xprompt.s_dat, 1, xprompt.s_len, n_tty_fp);
4464 fflush(n_tty_fp);
4468 # ifdef HAVE_TERMCAP
4469 a_tty_sigs_up();
4470 n_TERMCAP_RESUME(FAL0);
4471 # endif
4472 rv = (readline_restart)(stdin, linebuf, linesize,n n_MEMORY_DEBUG_ARGSCALL);
4473 # ifdef HAVE_TERMCAP
4474 n_TERMCAP_SUSPEND(FAL0);
4475 a_tty_sigs_down();
4476 # endif
4477 NYD_LEAVE;
4478 return rv;
4481 FL void
4482 n_tty_addhist(char const *s, bool_t isgabby){
4483 NYD_ENTER;
4484 n_UNUSED(s);
4485 n_UNUSED(isgabby);
4486 NYD_LEAVE;
4488 #endif /* nothing at all */
4490 #undef a_TTY_SIGNALS
4491 /* s-it-mode */