-s, ~s: normalize NL/CR characters (Debian #419840)
[s-mailx.git] / tty.c
blob621c751aeb40fa80e5c28a143d662ff9e43f9c9c
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ TTY (command line) editing interaction.
3 *@ Because we have multiple line-editor implementations, including our own
4 *@ M(ailx) L(ine) E(ditor), change the file layout a bit and place those
5 *@ one after the other below the other externals.
7 * Copyright (c) 2012 - 2016 Steffen (Daode) Nurpmeso <steffen@sdaoden.eu>.
9 * Permission to use, copy, modify, and/or distribute this software for any
10 * purpose with or without fee is hereby granted, provided that the above
11 * copyright notice and this permission notice appear in all copies.
13 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
14 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
15 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
16 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
17 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21 #undef n_FILE
22 #define n_FILE tty
24 #ifndef HAVE_AMALGAMATION
25 # include "nail.h"
26 #endif
28 #if defined HAVE_MLE || defined HAVE_TERMCAP
29 # define a_TTY_SIGNALS
30 #endif
32 /* History support macros */
33 #ifdef HAVE_HISTORY
34 # define a_TTY_HISTFILE(S) \
35 do{\
36 char const *__hist_obsolete = ok_vlook(NAIL_HISTFILE);\
37 if(__hist_obsolete != NULL)\
38 OBSOLETE(_("please use *history-file* instead of *NAIL_HISTFILE*"));\
39 S = ok_vlook(history_file);\
40 if((S) == NULL)\
41 (S) = __hist_obsolete;\
42 if((S) != NULL)\
43 S = fexpand(S, FEXP_LOCAL | FEXP_NSHELL);\
44 }while(0)
46 # define a_TTY_HISTSIZE(V) \
47 do{\
48 char const *__hist_obsolete = ok_vlook(NAIL_HISTSIZE);\
49 char const *__sv = ok_vlook(history_size);\
50 long __rv;\
51 if(__hist_obsolete != NULL)\
52 OBSOLETE(_("please use *history-size* instead of *NAIL_HISTSIZE*"));\
53 if(__sv == NULL)\
54 __sv = __hist_obsolete;\
55 if(__sv == NULL || (__rv = strtol(__sv, NULL, 10)) == 0)\
56 __rv = HIST_SIZE;\
57 else if(__rv < 0)\
58 __rv = 0;\
59 (V) = __rv;\
60 }while(0)
62 # define a_TTY_CHECK_ADDHIST(S,ISGABBY,NOACT) \
63 do{\
64 if(!(pstate & (PS_ROOT | PS_LINE_EDITOR_INIT)) ||\
65 ok_blook(line_editor_disable) ||\
66 ((ISGABBY) && !ok_blook(history_gabby)) ||\
67 spacechar(*(S)) || *(S) == '\0')\
68 NOACT;\
69 }while(0)
71 # define C_HISTORY_SHARED \
72 char **argv = v;\
73 long entry;\
74 NYD_ENTER;\
76 if(ok_blook(line_editor_disable)){\
77 n_err(_("history: *line-editor-disable* is set\n"));\
78 goto jerr;\
80 if(!(pstate & PS_LINE_EDITOR_INIT)){\
81 n_tty_init();\
82 assert(pstate & PS_LINE_EDITOR_INIT);\
84 if(*argv == NULL)\
85 goto jlist;\
86 if(argv[1] != NULL)\
87 goto jerr;\
88 if(!asccasecmp(*argv, "show"))\
89 goto jlist;\
90 if(!asccasecmp(*argv, "clear"))\
91 goto jclear;\
92 if((entry = strtol(*argv, argv, 10)) > 0 && **argv == '\0')\
93 goto jentry;\
94 jerr:\
95 n_err(_("Synopsis: history: %s\n"),\
96 /* Same string as in cmd_tab.h, still hoping...) */\
97 _("<show> (default), <clear> or select <NO> from editor history"));\
98 v = NULL;\
99 jleave:\
100 NYD_LEAVE;\
101 return (v == NULL ? !STOP : !OKAY); /* xxx 1:bad 0:good -- do some */
102 #endif /* HAVE_HISTORY */
104 #ifdef a_TTY_SIGNALS
105 static sighandler_type a_tty_oint, a_tty_oquit, a_tty_oterm,
106 a_tty_ohup,
107 a_tty_otstp, a_tty_ottin, a_tty_ottou;
108 #endif
110 #ifdef a_TTY_SIGNALS
111 static void a_tty_sigs_up(void), a_tty_sigs_down(void);
112 #endif
114 #ifdef a_TTY_SIGNALS
115 static void
116 a_tty_sigs_up(void){
117 sigset_t nset, oset;
118 NYD2_ENTER;
120 sigfillset(&nset);
122 sigprocmask(SIG_BLOCK, &nset, &oset);
123 a_tty_oint = safe_signal(SIGINT, &n_tty_signal);
124 a_tty_oquit = safe_signal(SIGQUIT, &n_tty_signal);
125 a_tty_oterm = safe_signal(SIGTERM, &n_tty_signal);
126 a_tty_ohup = safe_signal(SIGHUP, &n_tty_signal);
127 a_tty_otstp = safe_signal(SIGTSTP, &n_tty_signal);
128 a_tty_ottin = safe_signal(SIGTTIN, &n_tty_signal);
129 a_tty_ottou = safe_signal(SIGTTOU, &n_tty_signal);
130 sigprocmask(SIG_SETMASK, &oset, NULL);
131 NYD2_LEAVE;
134 static void
135 a_tty_sigs_down(void){
136 sigset_t nset, oset;
137 NYD2_ENTER;
139 sigfillset(&nset);
141 sigprocmask(SIG_BLOCK, &nset, &oset);
142 safe_signal(SIGINT, a_tty_oint);
143 safe_signal(SIGQUIT, a_tty_oquit);
144 safe_signal(SIGTERM, a_tty_oterm);
145 safe_signal(SIGHUP, a_tty_ohup);
146 safe_signal(SIGTSTP, a_tty_otstp);
147 safe_signal(SIGTTIN, a_tty_ottin);
148 safe_signal(SIGTTOU, a_tty_ottou);
149 sigprocmask(SIG_SETMASK, &oset, NULL);
150 NYD2_LEAVE;
152 #endif /* a_TTY_SIGNALS */
154 static sigjmp_buf a_tty__actjmp; /* TODO someday, we won't need it no more */
155 static void
156 a_tty__acthdl(int s) /* TODO someday, we won't need it no more */
158 NYD_X; /* Signal handler */
159 termios_state_reset();
160 siglongjmp(a_tty__actjmp, s);
163 FL bool_t
164 getapproval(char const * volatile prompt, bool_t noninteract_default)
166 sighandler_type volatile oint, ohup;
167 bool_t volatile rv;
168 int volatile sig;
169 NYD_ENTER;
171 if (!(options & OPT_INTERACTIVE)) {
172 sig = 0;
173 rv = noninteract_default;
174 goto jleave;
176 rv = FAL0;
178 /* C99 */{
179 char const *quest = noninteract_default
180 ? _("[yes]/no? ") : _("[no]/yes? ");
182 if (prompt == NULL)
183 prompt = _("Continue");
184 prompt = savecatsep(prompt, ' ', quest);
187 oint = safe_signal(SIGINT, SIG_IGN);
188 ohup = safe_signal(SIGHUP, SIG_IGN);
189 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
190 goto jrestore;
191 safe_signal(SIGINT, &a_tty__acthdl);
192 safe_signal(SIGHUP, &a_tty__acthdl);
194 if (n_lex_input(n_LEXINPUT_CTX_DEFAULT | n_LEXINPUT_NL_ESC, prompt,
195 &termios_state.ts_linebuf, &termios_state.ts_linesize, NULL) >= 0)
196 rv = (boolify(termios_state.ts_linebuf, UIZ_MAX,
197 noninteract_default) > 0);
198 jrestore:
199 termios_state_reset();
201 safe_signal(SIGHUP, ohup);
202 safe_signal(SIGINT, oint);
203 jleave:
204 NYD_LEAVE;
205 if (sig != 0)
206 n_raise(sig);
207 return rv;
210 #ifdef HAVE_SOCKETS
211 FL char *
212 getuser(char const * volatile query) /* TODO v15-compat obsolete */
214 sighandler_type volatile oint, ohup;
215 char * volatile user = NULL;
216 int volatile sig;
217 NYD_ENTER;
219 if (query == NULL)
220 query = _("User: ");
222 oint = safe_signal(SIGINT, SIG_IGN);
223 ohup = safe_signal(SIGHUP, SIG_IGN);
224 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
225 goto jrestore;
226 safe_signal(SIGINT, &a_tty__acthdl);
227 safe_signal(SIGHUP, &a_tty__acthdl);
229 if (n_lex_input(n_LEXINPUT_CTX_DEFAULT | n_LEXINPUT_NL_ESC, query,
230 &termios_state.ts_linebuf, &termios_state.ts_linesize, NULL) >= 0)
231 user = termios_state.ts_linebuf;
232 jrestore:
233 termios_state_reset();
235 safe_signal(SIGHUP, ohup);
236 safe_signal(SIGINT, oint);
237 NYD_LEAVE;
238 if (sig != 0)
239 n_raise(sig);
240 return user;
243 FL char *
244 getpassword(char const *query)
246 sighandler_type volatile oint, ohup;
247 struct termios tios;
248 char * volatile pass = NULL;
249 int volatile sig;
250 NYD_ENTER;
252 if (query == NULL)
253 query = _("Password: ");
254 fputs(query, stdout);
255 fflush(stdout);
257 /* FIXME everywhere: tcsetattr() generates SIGTTOU when we're not in
258 * FIXME foreground pgrp, and can fail with EINTR!! also affects
259 * FIXME termios_state_reset() */
260 if (options & OPT_TTYIN) {
261 tcgetattr(STDIN_FILENO, &termios_state.ts_tios);
262 memcpy(&tios, &termios_state.ts_tios, sizeof tios);
263 termios_state.ts_needs_reset = TRU1;
264 tios.c_iflag &= ~(ISTRIP);
265 tios.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
268 oint = safe_signal(SIGINT, SIG_IGN);
269 ohup = safe_signal(SIGHUP, SIG_IGN);
270 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
271 goto jrestore;
272 safe_signal(SIGINT, &a_tty__acthdl);
273 safe_signal(SIGHUP, &a_tty__acthdl);
275 if (options & OPT_TTYIN)
276 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 if (options & OPT_TTYIN)
284 putc('\n', stdout);
286 safe_signal(SIGHUP, ohup);
287 safe_signal(SIGINT, oint);
288 NYD_LEAVE;
289 if (sig != 0)
290 n_raise(sig);
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, simply use STDIN_FILENO as point of interest.
435 * TODO . This code should be splitted in funs/raw input/bind modules.
436 * TODO . After I/O layer rewrite, also "output to STDIN_FILENO".
437 * TODO . We work with wide characters, but not for buffer takeovers and
438 * TODO cell2save()ings. This should be changed. For the former the buffer
439 * TODO thus needs to be converted to wide first, and then simply be fed in.
440 * TODO . We repaint too much. To overcome this use the same approach that my
441 * TODO terminal library uses, add a true "virtual screen line" that stores
442 * TODO the actually visible content, keep a notion of "first modified slot"
443 * TODO and "last modified slot" (including "unknown" and "any" specials),
444 * TODO update that virtual instead, then synchronize what has truly changed.
445 * TODO I.e., add an indirection layer.
446 * TODO . No BIDI support.
447 * TODO . `bind': we currently use only one lookup tree.
448 * TODO For absolute graceful behaviour in conjunction (with HAVE_TERMCAP) we
449 * TODO need a lower level tree, which possibly combines bytes into "symbolic
450 * TODO wchar_t values", into "keys" that is, as applicable, and an upper
451 * TODO layer which only works on "keys" in order to possibly combine them
452 * TODO into key sequences. We can reuse existent tree code for that.
453 * TODO We need an additional hashmap which maps termcap/terminfo names to
454 * TODO (their byte representations and) a dynamically assigned unique
455 * TODO "symbolic wchar_t value". This implies we may have incompatibilities
456 * TODO when __STDC_ISO_10646__ is not defined. Also we do need takeover-
457 * TODO bytes storage, but it can be a string_creat_auto in the line struct.
458 * TODO Until then we can run into ambiguities; in rare occasions.
460 #ifdef HAVE_MLE
461 /* To avoid memory leaks etc. with the current codebase that simply longjmp(3)s
462 * we're forced to use the very same buffer--the one that is passed through to
463 * us from the outside--to store anything we need, i.e., a "struct cell[]", and
464 * convert that on-the-fly back to the plain char* result once we're done.
465 * To simplify our live, use savestr() buffers for all other needed memory */
467 # ifdef HAVE_KEY_BINDINGS
468 /* Default *bind-timeout* key-sequence continuation timeout, in tenths of
469 * a second. Must fit in 8-bit! Update the manual upon change! */
470 # define a_TTY_BIND_TIMEOUT 2
471 # define a_TTY_BIND_TIMEOUT_MAX SI8_MAX
473 n_CTAV(a_TTY_BIND_TIMEOUT_MAX <= UI8_MAX);
475 /* We have a chicken-and-egg problem with `bind' and our termcap layer,
476 * because we may not initialize the latter automatically to allow users to
477 * specify *termcap-disable* and let it mean exactly that.
478 * On the other hand users can be expected to use `bind' in resource file(s).
479 * Therefore bindings which involve termcap/terminfo sequences, and which are
480 * defined before PS_STARTED signals usability of termcap/terminfo, will be
481 * (partially) delayed until tty_init() is called.
482 * And we preallocate space for the expansion of the resolved capability */
483 # define a_TTY_BIND_CAPNAME_MAX 15
484 # define a_TTY_BIND_CAPEXP_ROUNDUP 16
486 n_CTAV(n_ISPOW2(a_TTY_BIND_CAPEXP_ROUNDUP));
487 n_CTA(a_TTY_BIND_CAPEXP_ROUNDUP <= SI8_MAX / 2, "Variable must fit in 6-bit");
488 n_CTA(a_TTY_BIND_CAPEXP_ROUNDUP >= 8, "Variable too small");
489 # endif /* HAVE_KEY_BINDINGS */
491 /* The maximum size (of a_tty_cell's) in a line */
492 # define a_TTY_LINE_MAX SI32_MAX
494 /* (Some more CTAs around) */
495 n_CTA(a_TTY_LINE_MAX <= SI32_MAX,
496 "a_TTY_LINE_MAX larger than SI32_MAX, but the MLE uses 32-bit arithmetic");
498 /* When shall the visual screen be scrolled, in % of usable screen width */
499 # define a_TTY_SCROLL_MARGIN_LEFT 15
500 # define a_TTY_SCROLL_MARGIN_RIGHT 10
502 /* fexpand() flags for expand-on-tab */
503 # define a_TTY_TAB_FEXP_FL (FEXP_FULL | FEXP_SILENT | FEXP_MULTIOK)
505 /* Columns to ripoff: outermost may not be touched, plus position indicator.
506 * Must thus be at least 1, but should be >= 1+4 to dig the position indicator
507 * that we place (if there is sufficient space) */
508 # define a_TTY_WIDTH_RIPOFF 5
510 /* The implementation of the MLE functions always exists, and is based upon
511 * the a_TTY_BIND_FUN_* constants, so most of this enum is always necessary */
512 enum a_tty_bind_flags{
513 # ifdef HAVE_KEY_BINDINGS
514 a_TTY_BIND_RESOLVE = 1u<<8, /* Term cap. yet needs to be resolved */
515 a_TTY_BIND_DEFUNCT = 1u<<9, /* Unicode/term cap. used but not avail. */
516 a_TTY__BIND_MASK = a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT,
517 /* MLE fun assigned to a one-byte-sequence: this may be used for special
518 * key-sequence bypass processing */
519 a_TTY_BIND_MLE1CNTRL = 1u<<10,
520 a_TTY_BIND_NOCOMMIT = 1u<<11, /* Expansion shall be editable */
521 # endif
523 /* MLE internal commands */
524 a_TTY_BIND_FUN_INTERNAL = 1u<<15,
525 a_TTY__BIND_FUN_SHIFT = 16u,
526 a_TTY__BIND_FUN_SHIFTMAX = 24u,
527 a_TTY__BIND_FUN_MASK = ((1u << a_TTY__BIND_FUN_SHIFTMAX) - 1) &
528 ~((1u << a_TTY__BIND_FUN_SHIFT) - 1),
529 # define a_TTY_BIND_FUN_REDUCE(X) \
530 (((ui32_t)(X) & a_TTY__BIND_FUN_MASK) >> a_TTY__BIND_FUN_SHIFT)
531 # define a_TTY_BIND_FUN_EXPAND(X) \
532 (((ui32_t)(X) & (a_TTY__BIND_FUN_MASK >> a_TTY__BIND_FUN_SHIFT)) << \
533 a_TTY__BIND_FUN_SHIFT)
534 # undef a_X
535 # define a_X(N,I)\
536 a_TTY_BIND_FUN_ ## N = a_TTY_BIND_FUN_EXPAND(I),
538 a_X(BELL, 0)
539 a_X(GO_BWD, 1) a_X(GO_FWD, 2)
540 a_X(GO_WORD_BWD, 3) a_X(GO_WORD_FWD, 4)
541 a_X(GO_HOME, 5) a_X(GO_END, 6)
542 a_X(DEL_BWD, 7) a_X(DEL_FWD, 8)
543 a_X(SNARF_WORD_BWD, 9) a_X(SNARF_WORD_FWD, 10)
544 a_X(SNARF_END, 11) a_X(SNARF_LINE, 12)
545 a_X(HIST_BWD, 13) a_X(HIST_FWD, 14)
546 a_X(HIST_SRCH_BWD, 15) a_X(HIST_SRCH_FWD, 16)
547 a_X(REPAINT, 17)
548 a_X(QUOTE_RNDTRIP, 18)
549 a_X(PROMPT_CHAR, 19)
550 a_X(COMPLETE, 20)
551 a_X(PASTE, 21)
553 a_X(CANCEL, 22)
554 a_X(RESET, 23)
555 a_X(FULLRESET, 24)
556 a_X(COMMIT, 25) /* Must be last one! */
557 # undef a_X
559 a_TTY__BIND_LAST = 1<<25
561 # ifdef HAVE_KEY_BINDINGS
562 n_CTA((ui32_t)a_TTY_BIND_RESOLVE >= (ui32_t)n__LEXINPUT_CTX_MAX1,
563 "Bit carrier lower boundary must be raised to avoid value sharing");
564 # endif
565 n_CTA(a_TTY_BIND_FUN_EXPAND(a_TTY_BIND_FUN_COMMIT) <
566 (1 << a_TTY__BIND_FUN_SHIFTMAX),
567 "Bit carrier range must be expanded to represent necessary bits");
568 n_CTA(a_TTY__BIND_LAST >= (1u << a_TTY__BIND_FUN_SHIFTMAX),
569 "Bit carrier upper boundary must be raised to avoid value sharing");
570 n_CTA(UICMP(64, a_TTY__BIND_LAST, <=, SI32_MAX),
571 "Flag bits excess storage datatype" /* And we need one bit free */);
573 enum a_tty_fun_status{
574 a_TTY_FUN_STATUS_OK, /* Worked, next character */
575 a_TTY_FUN_STATUS_COMMIT, /* Line done */
576 a_TTY_FUN_STATUS_RESTART, /* Complete restart, reset multibyte etc. */
577 a_TTY_FUN_STATUS_END /* End, return EOF */
580 enum a_tty_visual_flags{
581 a_TTY_VF_NONE,
582 a_TTY_VF_MOD_CURSOR = 1u<<0, /* Cursor moved */
583 a_TTY_VF_MOD_CONTENT = 1u<<1, /* Content modified */
584 a_TTY_VF_MOD_DIRTY = 1u<<2, /* Needs complete repaint */
585 a_TTY_VF_MOD_SINGLE = 1u<<3, /* TODO Drop when indirection as above comes */
586 a_TTY_VF_REFRESH = a_TTY_VF_MOD_DIRTY | a_TTY_VF_MOD_CURSOR |
587 a_TTY_VF_MOD_CONTENT | a_TTY_VF_MOD_SINGLE,
588 a_TTY_VF_BELL = 1u<<8, /* Ring the bell */
589 a_TTY_VF_SYNC = 1u<<9, /* Flush/Sync I/O channel */
591 a_TTY_VF_ALL_MASK = a_TTY_VF_REFRESH | a_TTY_VF_BELL | a_TTY_VF_SYNC,
592 a_TTY__VF_LAST = a_TTY_VF_SYNC
595 # ifdef HAVE_KEY_BINDINGS
596 struct a_tty_bind_ctx{
597 struct a_tty_bind_ctx *tbc_next;
598 char *tbc_seq; /* quence as given (poss. re-quoted), in .tb__buf */
599 char *tbc_exp; /* ansion, in .tb__buf */
600 /* The .tbc_seq'uence with any terminal capabilities resolved; in fact an
601 * array of structures, the first entry of which is {si32_t buf_len_iscap;}
602 * where the signed bit indicates whether the buffer is a resolved terminal
603 * capability instead of a (possibly multibyte) character. In .tbc__buf */
604 char *tbc_cnv;
605 ui32_t tbc_seq_len;
606 ui32_t tbc_exp_len;
607 ui32_t tbc_cnv_len;
608 ui32_t tbc_flags;
609 char tbc__buf[n_VFIELD_SIZE(0)];
612 struct a_tty_bind_ctx_map{
613 enum n_lexinput_flags tbcm_ctx;
614 char const tbcm_name[12]; /* Name of `bind' context */
616 # endif /* HAVE_KEY_BINDINGS */
618 struct a_tty_bind_default_tuple{
619 bool_t tbdt_iskey; /* Whether this is a control key; else termcap query */
620 char tbdt_ckey; /* Control code */
621 ui16_t tbdt_query; /* enum n_termcap_query (instead) */
622 char tbdt_exp[12]; /* String or [0]=NUL/[1]=BIND_FUN_REDUCE() */
624 n_CTA(n__TERMCAP_QUERY_MAX1 <= UI16_MAX,
625 "Enumeration cannot be stored in datatype");
627 # ifdef HAVE_KEY_BINDINGS
628 struct a_tty_bind_parse_ctx{
629 char const *tbpc_cmd; /* Command which parses */
630 char const *tbpc_in_seq; /* In: key sequence */
631 struct str tbpc_exp; /* In/Out: expansion (or NULL) */
632 struct a_tty_bind_ctx *tbpc_tbcp; /* Out: if yet existent */
633 struct a_tty_bind_ctx *tbpc_ltbcp; /* Out: the one before .tbpc_tbcp */
634 char *tbpc_seq; /* Out: normalized sequence */
635 char *tbpc_cnv; /* Out: sequence when read(2)ing it */
636 ui32_t tbpc_seq_len;
637 ui32_t tbpc_cnv_len;
638 ui32_t tbpc_cnv_align_mask; /* For creating a_tty_bind_ctx.tbc_cnv */
639 ui32_t tbpc_flags; /* n_lexinput_flags | a_tty_bind_flags */
642 /* Input character tree */
643 struct a_tty_bind_tree{
644 struct a_tty_bind_tree *tbt_sibling; /* s at same level */
645 struct a_tty_bind_tree *tbt_childs; /* Sequence continues.. here */
646 struct a_tty_bind_tree *tbt_parent;
647 struct a_tty_bind_ctx *tbt_bind; /* NULL for intermediates */
648 wchar_t tbt_char; /* acter this level represents */
649 bool_t tbt_isseq; /* Belongs to multibyte sequence */
650 bool_t tbt_isseq_trail; /* ..is trailing byte of it */
651 ui8_t tbt__dummy[2];
653 # endif /* HAVE_KEY_BINDINGS */
655 struct a_tty_cell{
656 wchar_t tc_wc;
657 ui16_t tc_count; /* ..of bytes */
658 ui8_t tc_width; /* Visual width; TAB==UI8_MAX! */
659 bool_t tc_novis; /* Don't display visually as such (control character) */
660 char tc_cbuf[MB_LEN_MAX * 2]; /* .. plus reset shift sequence */
663 struct a_tty_global{
664 struct a_tty_line *tg_line; /* To be able to access it from signal hdl */
665 # ifdef HAVE_HISTORY
666 struct a_tty_hist *tg_hist;
667 struct a_tty_hist *tg_hist_tail;
668 size_t tg_hist_size;
669 size_t tg_hist_size_max;
670 # endif
671 # ifdef HAVE_KEY_BINDINGS
672 ui32_t tg_bind_cnt; /* Overall number of bindings */
673 bool_t tg_bind_isdirty;
674 bool_t tg_bind_isbuild;
675 # define a_TTY_SHCUT_MAX (3 +1) /* Note: update manual on change! */
676 ui8_t tg_bind__dummy[2];
677 char tg_bind_shcut_cancel[n__LEXINPUT_CTX_MAX1][a_TTY_SHCUT_MAX];
678 char tg_bind_shcut_prompt_char[n__LEXINPUT_CTX_MAX1][a_TTY_SHCUT_MAX];
679 struct a_tty_bind_ctx *tg_bind[n__LEXINPUT_CTX_MAX1];
680 struct a_tty_bind_tree *tg_bind_tree[n__LEXINPUT_CTX_MAX1][HSHSIZE];
681 # endif
682 struct termios tg_tios_old;
683 struct termios tg_tios_new;
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");
691 # ifdef HAVE_HISTORY
692 struct a_tty_hist{
693 struct a_tty_hist *th_older;
694 struct a_tty_hist *th_younger;
695 # ifdef HAVE_BYTE_ORDER_LITTLE
696 ui32_t th_isgabby : 1;
697 # endif
698 ui32_t th_len : 31;
699 # ifndef HAVE_BYTE_ORDER_LITTLE
700 ui32_t th_isgabby : 1;
701 # endif
702 char th_dat[n_VFIELD_SIZE(sizeof(ui32_t))];
704 # endif
706 struct a_tty_line{
707 /* Caller pointers */
708 char **tl_x_buf;
709 size_t *tl_x_bufsize;
710 /* Input processing */
711 # ifdef HAVE_KEY_BINDINGS
712 wchar_t tl_bind_takeover; /* Leftover byte to consume next */
713 ui8_t tl_bind_timeout; /* In-seq. inter-byte-timer, in 1/10th secs */
714 ui8_t tl__bind_dummy[3];
715 char (*tl_bind_shcut_cancel)[a_TTY_SHCUT_MAX]; /* Special _CANCEL control */
716 char (*tl_bind_shcut_prompt_char)[a_TTY_SHCUT_MAX]; /* ..for _PROMPT_CHAR */
717 struct a_tty_bind_tree *(*tl_bind_tree_hmap)[HSHSIZE]; /* Bind lookup tree */
718 struct a_tty_bind_tree *tl_bind_tree;
719 # endif
720 char const *tl_reenter_after_cmd; /* `bind' cmd to exec, then re-readline */
721 /* Line data / content handling */
722 ui32_t tl_count; /* ..of a_tty_cell's (<= a_TTY_LINE_MAX) */
723 ui32_t tl_cursor; /* Current a_tty_cell insertion point */
724 union{
725 char *cbuf; /* *.tl_x_buf */
726 struct a_tty_cell *cells;
727 } tl_line;
728 struct str tl_defc; /* Current default content */
729 size_t tl_defc_cursor_byte; /* Desired position of cursor after takeover */
730 struct str tl_savec; /* Saved default content */
731 struct str tl_pastebuf; /* Last snarfed data */
732 # ifdef HAVE_HISTORY
733 struct a_tty_hist *tl_hist; /* History cursor */
734 # endif
735 ui32_t tl_count_max; /* ..before buffer needs to grow */
736 /* Visual data representation handling */
737 ui32_t tl_vi_flags; /* enum a_tty_visual_flags */
738 ui32_t tl_lst_count; /* .tl_count after last sync */
739 ui32_t tl_lst_cursor; /* .tl_cursor after last sync */
740 /* TODO Add another indirection layer by adding a tl_phy_line of
741 * TODO a_tty_cell objects, incorporate changes in visual layer,
742 * TODO then check what _really_ has changed, sync those changes only */
743 struct a_tty_cell const *tl_phy_start; /* First visible cell, left border */
744 ui32_t tl_phy_cursor; /* Physical cursor position */
745 bool_t tl_quote_rndtrip; /* For _kht() expansion */
746 ui8_t tl__dummy2[3];
747 ui32_t tl_prompt_length; /* Preclassified (TODO needed as a_tty_cell) */
748 ui32_t tl_prompt_width;
749 char const *tl_prompt; /* Preformatted prompt (including colours) */
750 /* .tl_pos_buf is a hack */
751 # ifdef HAVE_COLOUR
752 char *tl_pos_buf; /* mle-position colour-on, [4], reset seq. */
753 char *tl_pos; /* Address of the [4] */
754 # endif
757 # ifdef HAVE_KEY_BINDINGS
758 /* C99: use [INDEX]={} */
759 n_CTAV(n_LEXINPUT_CTX_BASE == 0);
760 n_CTAV(n_LEXINPUT_CTX_DEFAULT == 1);
761 n_CTAV(n_LEXINPUT_CTX_COMPOSE == 2);
762 static struct a_tty_bind_ctx_map const
763 a_tty_bind_ctx_maps[n__LEXINPUT_CTX_MAX1] = {
764 {n_LEXINPUT_CTX_BASE, "base"},
765 {n_LEXINPUT_CTX_DEFAULT, "default"},
766 {n_LEXINPUT_CTX_COMPOSE, "compose"}
769 /* Special functions which our MLE provides internally.
770 * Update the manual upon change! */
771 static char const a_tty_bind_fun_names[][24] = {
772 # undef a_X
773 # define a_X(I,N) \
774 n_FIELD_INITI(a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## I)) "mle-" N "\0",
776 a_X(BELL, "bell")
777 a_X(GO_BWD, "go-bwd") a_X(GO_FWD, "go-fwd")
778 a_X(GO_WORD_BWD, "go-word-bwd") a_X(GO_WORD_FWD, "go-word-fwd")
779 a_X(GO_HOME, "go-home") a_X(GO_END, "go-end")
780 a_X(DEL_BWD, "del-bwd") a_X(DEL_FWD, "del-fwd")
781 a_X(SNARF_WORD_BWD, "snarf-word-bwd") a_X(SNARF_WORD_FWD, "snarf-word-fwd")
782 a_X(SNARF_END, "snarf-end") a_X(SNARF_LINE, "snarf-line")
783 a_X(HIST_BWD, "hist-bwd") a_X(HIST_FWD, "hist-fwd")
784 a_X(HIST_SRCH_BWD, "hist-srch-bwd") a_X(HIST_SRCH_FWD, "hist-srch-fwd")
785 a_X(REPAINT, "repaint")
786 a_X(QUOTE_RNDTRIP, "quote-rndtrip")
787 a_X(PROMPT_CHAR, "prompt-char")
788 a_X(COMPLETE, "complete")
789 a_X(PASTE, "paste")
791 a_X(CANCEL, "cancel")
792 a_X(RESET, "reset")
793 a_X(FULLRESET, "fullreset")
794 a_X(COMMIT, "commit")
796 # undef a_X
798 # endif /* HAVE_KEY_BINDINGS */
800 /* The default key bindings (unless disallowed). Update manual upon change!
801 * A logical subset of this table is also used if !HAVE_KEY_BINDINGS (more
802 * expensive than a switch() on control codes directly, but less redundant) */
803 static struct a_tty_bind_default_tuple const a_tty_bind_default_tuples[] = {
804 # undef a_X
805 # define a_X(K,S) \
806 {TRU1, K, 0, {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
808 a_X('A', GO_HOME)
809 a_X('B', GO_BWD)
810 /* C: SIGINT */
811 a_X('D', DEL_FWD)
812 a_X('E', GO_END)
813 a_X('F', GO_FWD)
814 a_X('G', RESET)
815 a_X('H', DEL_BWD)
816 a_X('I', COMPLETE)
817 a_X('J', COMMIT)
818 a_X('K', SNARF_END)
819 a_X('L', REPAINT)
820 /* M: same as J */
821 a_X('N', HIST_FWD)
822 /* O: below */
823 a_X('P', HIST_BWD)
824 a_X('Q', QUOTE_RNDTRIP)
825 a_X('R', HIST_SRCH_BWD)
826 a_X('S', HIST_SRCH_FWD)
827 a_X('T', PASTE)
828 a_X('U', SNARF_LINE)
829 a_X('V', PROMPT_CHAR)
830 a_X('W', SNARF_WORD_BWD)
831 a_X('X', GO_WORD_FWD)
832 a_X('Y', GO_WORD_BWD)
833 /* Z: SIGTSTP */
835 a_X('[', CANCEL)
836 /* \: below */
837 /* ]: below */
838 /* ^: below */
839 a_X('_', SNARF_WORD_FWD)
841 a_X('?', DEL_BWD)
843 # undef a_X
844 # define a_X(K,S) {TRU1, K, 0, {S}},
846 a_X('O', "dt")
847 a_X('\\', "z+")
848 a_X(']', "z$")
849 a_X('^', "z0")
851 # ifdef HAVE_KEY_BINDINGS
852 # undef a_X
853 # define a_X(Q,S) \
854 {FAL0, '\0', n_TERMCAP_QUERY_ ## Q,\
855 {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
857 a_X(key_backspace, DEL_BWD) a_X(key_dc, DEL_FWD)
858 a_X(key_eol, SNARF_END)
859 a_X(key_home, GO_HOME) a_X(key_end, GO_END)
860 a_X(key_left, GO_BWD) a_X(key_right, GO_FWD)
861 a_X(key_sleft, GO_HOME) a_X(key_sright, GO_END)
862 a_X(key_up, HIST_BWD) a_X(key_down, HIST_FWD)
864 # undef a_X
865 # define a_X(Q,S) {FAL0, '\0', n_TERMCAP_QUERY_ ## Q, {S}},
867 a_X(key_shome, "z0") a_X(key_send, "z$")
868 a_X(xkey_sup, "z0") a_X(xkey_sdown, "z$")
869 a_X(key_ppage, "z-") a_X(key_npage, "z+")
870 a_X(xkey_cup, "dotmove-") a_X(xkey_cdown, "dotmove+")
872 # endif /* HAVE_KEY_BINDINGS */
873 # undef a_X
876 static struct a_tty_global a_tty;
878 /* Change from canonical to raw, non-canonical mode, and way back */
879 static void a_tty_term_mode(bool_t raw);
881 /* Adjust an active raw mode to use / not use a timeout */
882 # ifdef HAVE_KEY_BINDINGS
883 static void a_tty_term_rawmode_timeout(struct a_tty_line *tlp, bool_t enable);
884 # endif
886 /* 0-X (2), UI8_MAX == \t / TAB */
887 static ui8_t a_tty_wcwidth(wchar_t wc);
889 /* Memory / cell / word generics */
890 static void a_tty_check_grow(struct a_tty_line *tlp, ui32_t no
891 n_MEMORY_DEBUG_ARGS);
892 static ssize_t a_tty_cell2dat(struct a_tty_line *tlp);
893 static void a_tty_cell2save(struct a_tty_line *tlp);
895 /* Save away data bytes of given range (max = non-inclusive) */
896 static void a_tty_copy2paste(struct a_tty_line *tlp, struct a_tty_cell *tcpmin,
897 struct a_tty_cell *tcpmax);
899 /* Ask user for hexadecimal number, interpret as UTF-32 */
900 static wchar_t a_tty_vinuni(struct a_tty_line *tlp);
902 /* Visual screen synchronization */
903 static bool_t a_tty_vi_refresh(struct a_tty_line *tlp);
905 static bool_t a_tty_vi__paint(struct a_tty_line *tlp);
907 /* Search for word boundary, starting at tl_cursor, in "dir"ection (<> 0).
908 * Return <0 when moving is impossible (backward direction but in position 0,
909 * forward direction but in outermost column), and relative distance to
910 * tl_cursor otherwise */
911 static si32_t a_tty_wboundary(struct a_tty_line *tlp, si32_t dir);
913 /* Most function implementations */
914 static void a_tty_khome(struct a_tty_line *tlp, bool_t dobell);
915 static void a_tty_kend(struct a_tty_line *tlp);
916 static void a_tty_kbs(struct a_tty_line *tlp);
917 static void a_tty_ksnarf(struct a_tty_line *tlp, bool_t cplline, bool_t dobell);
918 static si32_t a_tty_kdel(struct a_tty_line *tlp);
919 static void a_tty_kleft(struct a_tty_line *tlp);
920 static void a_tty_kright(struct a_tty_line *tlp);
921 static void a_tty_ksnarfw(struct a_tty_line *tlp, bool_t fwd);
922 static void a_tty_kgow(struct a_tty_line *tlp, si32_t dir);
923 static bool_t a_tty_kother(struct a_tty_line *tlp, wchar_t wc);
924 static ui32_t a_tty_kht(struct a_tty_line *tlp);
926 # ifdef HAVE_HISTORY
927 /* Return UI32_MAX on "exhaustion" */
928 static ui32_t a_tty_khist(struct a_tty_line *tlp, bool_t fwd);
929 static ui32_t a_tty_khist_search(struct a_tty_line *tlp, bool_t fwd);
931 static ui32_t a_tty__khist_shared(struct a_tty_line *tlp,
932 struct a_tty_hist *thp);
933 # endif
935 /* Handle a function */
936 static enum a_tty_fun_status a_tty_fun(struct a_tty_line *tlp,
937 enum a_tty_bind_flags tbf, size_t *len);
939 /* Readline core */
940 static ssize_t a_tty_readline(struct a_tty_line *tlp, size_t len
941 n_MEMORY_DEBUG_ARGS);
943 # ifdef HAVE_KEY_BINDINGS
944 /* Find context or -1 */
945 static enum n_lexinput_flags a_tty_bind_ctx_find(char const *name);
947 /* Create (or replace, if allowed) a binding */
948 static bool_t a_tty_bind_create(struct a_tty_bind_parse_ctx *tbpcp,
949 bool_t replace);
951 /* Shared implementation to parse `bind' and `unbind' "key-sequence" and
952 * "expansion" command line arguments into something that we can work with */
953 static bool_t a_tty_bind_parse(bool_t isbindcmd,
954 struct a_tty_bind_parse_ctx *tbpcp);
956 /* Lazy resolve a termcap(5)/terminfo(5) (or *termcap*!) capability */
957 static void a_tty_bind_resolve(struct a_tty_bind_ctx *tbcp);
959 /* Delete an existing binding */
960 static void a_tty_bind_del(struct a_tty_bind_parse_ctx *tbpcp);
962 /* Life cycle of all input node trees */
963 static void a_tty_bind_tree_build(void);
964 static void a_tty_bind_tree_teardown(void);
966 static void a_tty__bind_tree_add(ui32_t hmap_idx,
967 struct a_tty_bind_tree *store[HSHSIZE],
968 struct a_tty_bind_ctx *tbcp);
969 static struct a_tty_bind_tree *a_tty__bind_tree_add_wc(
970 struct a_tty_bind_tree **treep, struct a_tty_bind_tree *parentp,
971 wchar_t wc, bool_t isseq);
972 static void a_tty__bind_tree_free(struct a_tty_bind_tree *tbtp);
973 # endif /* HAVE_KEY_BINDINGS */
975 static void
976 a_tty_term_mode(bool_t raw){
977 struct termios *tiosp;
978 NYD2_ENTER;
980 tiosp = &a_tty.tg_tios_old;
981 if(!raw)
982 goto jleave;
984 /* Always requery the attributes, in case we've been moved from background
985 * to foreground or however else in between sessions */
986 /* XXX Always enforce ECHO and ICANON in the OLD attributes - do so as long
987 * XXX as we don't properly deal with TTIN and TTOU etc. */
988 tcgetattr(STDIN_FILENO, tiosp);
989 tiosp->c_lflag |= ECHO | ICANON;
991 memcpy(&a_tty.tg_tios_new, tiosp, sizeof *tiosp);
992 tiosp = &a_tty.tg_tios_new;
993 tiosp->c_cc[VMIN] = 1;
994 tiosp->c_cc[VTIME] = 0;
995 /* Enable ^\, ^Q and ^S to be used for key bindings */
996 tiosp->c_cc[VQUIT] = tiosp->c_cc[VSTART] = tiosp->c_cc[VSTOP] = '\0';
997 tiosp->c_iflag &= ~(ISTRIP | IGNCR);
998 tiosp->c_lflag &= ~(ECHO /*| ECHOE | ECHONL */| ICANON | IEXTEN);
999 jleave:
1000 tcsetattr(STDIN_FILENO, TCSADRAIN, tiosp);
1001 NYD2_LEAVE;
1004 # ifdef HAVE_KEY_BINDINGS
1005 static void
1006 a_tty_term_rawmode_timeout(struct a_tty_line *tlp, bool_t enable){
1007 NYD2_ENTER;
1008 if(enable){
1009 ui8_t bt;
1011 a_tty.tg_tios_new.c_cc[VMIN] = 0;
1012 if((bt = tlp->tl_bind_timeout) == 0)
1013 bt = a_TTY_BIND_TIMEOUT;
1014 a_tty.tg_tios_new.c_cc[VTIME] = bt;
1015 }else{
1016 a_tty.tg_tios_new.c_cc[VMIN] = 1;
1017 a_tty.tg_tios_new.c_cc[VTIME] = 0;
1019 tcsetattr(STDIN_FILENO, TCSANOW, &a_tty.tg_tios_new);
1020 NYD2_LEAVE;
1022 # endif /* HAVE_KEY_BINDINGS */
1024 static ui8_t
1025 a_tty_wcwidth(wchar_t wc){
1026 ui8_t rv;
1027 NYD2_ENTER;
1029 /* Special case the backslash at first */
1030 if(wc == '\t')
1031 rv = UI8_MAX;
1032 else{
1033 int i;
1035 # ifdef HAVE_WCWIDTH
1036 rv = ((i = wcwidth(wc)) > 0) ? (ui8_t)i : 0;
1037 # else
1038 rv = iswprint(wc) ? 1 + (wc >= 0x1100u) : 0; /* TODO use S-CText */
1039 # endif
1041 NYD2_LEAVE;
1042 return rv;
1045 static void
1046 a_tty_check_grow(struct a_tty_line *tlp, ui32_t no n_MEMORY_DEBUG_ARGS){
1047 ui32_t cmax;
1048 NYD2_ENTER;
1050 if(n_UNLIKELY((cmax = tlp->tl_count + no) > tlp->tl_count_max)){
1051 size_t i;
1053 i = cmax * sizeof(struct a_tty_cell) + 2 * sizeof(struct a_tty_cell);
1054 if(n_LIKELY(i >= *tlp->tl_x_bufsize)){
1055 hold_all_sigs(); /* XXX v15 drop */
1056 i <<= 1;
1057 tlp->tl_line.cbuf =
1058 *tlp->tl_x_buf = (n_realloc)(*tlp->tl_x_buf, i
1059 n_MEMORY_DEBUG_ARGSCALL);
1060 rele_all_sigs(); /* XXX v15 drop */
1062 tlp->tl_count_max = cmax;
1063 *tlp->tl_x_bufsize = i;
1065 NYD2_LEAVE;
1068 static ssize_t
1069 a_tty_cell2dat(struct a_tty_line *tlp){
1070 size_t len, i;
1071 NYD2_ENTER;
1073 len = 0;
1075 if(n_LIKELY((i = tlp->tl_count) > 0)){
1076 struct a_tty_cell const *tcap;
1078 tcap = tlp->tl_line.cells;
1080 memcpy(tlp->tl_line.cbuf + len, tcap->tc_cbuf, tcap->tc_count);
1081 len += tcap->tc_count;
1082 }while(++tcap, --i > 0);
1085 tlp->tl_line.cbuf[len] = '\0';
1086 NYD2_LEAVE;
1087 return (ssize_t)len;
1090 static void
1091 a_tty_cell2save(struct a_tty_line *tlp){
1092 size_t len, i;
1093 struct a_tty_cell *tcap;
1094 NYD2_ENTER;
1096 tlp->tl_savec.s = NULL;
1097 tlp->tl_savec.l = 0;
1099 if(n_UNLIKELY(tlp->tl_count == 0))
1100 goto jleave;
1102 for(tcap = tlp->tl_line.cells, len = 0, i = tlp->tl_count; i > 0;
1103 ++tcap, --i)
1104 len += tcap->tc_count;
1106 tlp->tl_savec.s = salloc((tlp->tl_savec.l = len) +1);
1108 for(tcap = tlp->tl_line.cells, len = 0, i = tlp->tl_count; i > 0;
1109 ++tcap, --i){
1110 memcpy(tlp->tl_savec.s + len, tcap->tc_cbuf, tcap->tc_count);
1111 len += tcap->tc_count;
1113 tlp->tl_savec.s[len] = '\0';
1114 jleave:
1115 NYD2_LEAVE;
1118 static void
1119 a_tty_copy2paste(struct a_tty_line *tlp, struct a_tty_cell *tcpmin,
1120 struct a_tty_cell *tcpmax){
1121 char *cp;
1122 struct a_tty_cell *tcp;
1123 size_t l;
1124 NYD2_ENTER;
1126 l = 0;
1127 for(tcp = tcpmin; tcp < tcpmax; ++tcp)
1128 l += tcp->tc_count;
1130 tlp->tl_pastebuf.s = cp = salloc((tlp->tl_pastebuf.l = l) +1);
1132 l = 0;
1133 for(tcp = tcpmin; tcp < tcpmax; cp += l, ++tcp)
1134 memcpy(cp, tcp->tc_cbuf, l = tcp->tc_count);
1135 *cp = '\0';
1136 NYD2_LEAVE;
1139 static wchar_t
1140 a_tty_vinuni(struct a_tty_line *tlp){
1141 char buf[16], *eptr;
1142 union {size_t i; long l;} u;
1143 wchar_t wc;
1144 NYD2_ENTER;
1146 wc = '\0';
1148 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr) ||
1149 !n_termcap_cmd(n_TERMCAP_CMD_ce, 0, -1))
1150 goto jleave;
1152 /* C99 */{
1153 struct str const *cpre, *csuf;
1154 #ifdef HAVE_COLOUR
1155 struct n_colour_pen *cpen;
1157 cpen = n_colour_pen_create(n_COLOUR_ID_MLE_PROMPT, NULL);
1158 if((cpre = n_colour_pen_to_str(cpen)) != NULL)
1159 csuf = n_colour_reset_to_str();
1160 else
1161 csuf = NULL;
1162 #else
1163 cpre = csuf = NULL;
1164 #endif
1165 printf(_("%sPlease enter Unicode code point:%s "),
1166 (cpre != NULL ? cpre->s : n_empty),
1167 (csuf != NULL ? csuf->s : n_empty));
1169 fflush(stdout);
1171 buf[sizeof(buf) -1] = '\0';
1172 for(u.i = 0;;){
1173 if(read(STDIN_FILENO, &buf[u.i], 1) != 1){
1174 if(errno == EINTR) /* xxx #if !SA_RESTART ? */
1175 continue;
1176 goto jleave;
1178 if(buf[u.i] == '\n')
1179 break;
1180 if(!hexchar(buf[u.i])){
1181 char const emsg[] = "[0-9a-fA-F]";
1183 n_LCTA(sizeof emsg <= sizeof(buf), "Preallocated buffer too small");
1184 memcpy(buf, emsg, sizeof emsg);
1185 goto jerr;
1188 putc(buf[u.i], stdout);
1189 fflush(stdout);
1190 if(++u.i == sizeof buf)
1191 goto jerr;
1193 buf[u.i] = '\0';
1195 u.l = strtol(buf, &eptr, 16);
1196 if(u.l <= 0 || u.l >= 0x10FFFF/* XXX magic; CText */ || *eptr != '\0'){
1197 jerr:
1198 n_err(_("\nInvalid input: %s\n"), buf);
1199 goto jleave;
1202 wc = (wchar_t)u.l;
1203 jleave:
1204 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY | (wc == '\0' ? a_TTY_VF_BELL : 0);
1205 NYD2_LEAVE;
1206 return wc;
1209 static bool_t
1210 a_tty_vi_refresh(struct a_tty_line *tlp){
1211 bool_t rv;
1212 NYD2_ENTER;
1214 if(tlp->tl_vi_flags & a_TTY_VF_BELL){
1215 tlp->tl_vi_flags |= a_TTY_VF_SYNC;
1216 if(putchar('\a') == EOF)
1217 goto jerr;
1220 if(tlp->tl_vi_flags & a_TTY_VF_REFRESH){
1221 /* kht may want to restore a cursor position after inserting some
1222 * data somewhere */
1223 if(tlp->tl_defc_cursor_byte > 0){
1224 size_t i, j;
1225 ssize_t k;
1227 a_tty_khome(tlp, FAL0);
1229 i = tlp->tl_defc_cursor_byte;
1230 tlp->tl_defc_cursor_byte = 0;
1231 for(j = 0; tlp->tl_cursor < tlp->tl_count; ++j){
1232 a_tty_kright(tlp);
1233 if((k = tlp->tl_line.cells[j].tc_count) > i)
1234 break;
1235 i -= k;
1239 if(!a_tty_vi__paint(tlp))
1240 goto jerr;
1243 if(tlp->tl_vi_flags & a_TTY_VF_SYNC){
1244 tlp->tl_vi_flags &= ~a_TTY_VF_SYNC;
1245 if(fflush(stdout))
1246 goto jerr;
1249 rv = TRU1;
1250 jleave:
1251 tlp->tl_vi_flags &= ~a_TTY_VF_ALL_MASK;
1252 NYD2_LEAVE;
1253 return rv;
1255 jerr:
1256 clearerr(stdout); /* xxx I/O layer rewrite */
1257 n_err(_("Visual refresh failed! Is $TERM set correctly?\n"
1258 " Setting *line-editor-disable* to get us through!\n"));
1259 ok_bset(line_editor_disable);
1260 rv = FAL0;
1261 goto jleave;
1264 static bool_t
1265 a_tty_vi__paint(struct a_tty_line *tlp){
1266 enum{
1267 a_TRUE_RV = a_TTY__VF_LAST<<1, /* Return value bit */
1268 a_HAVE_PROMPT = a_TTY__VF_LAST<<2, /* Have a prompt */
1269 a_SHOW_PROMPT = a_TTY__VF_LAST<<3, /* Shall print the prompt */
1270 a_MOVE_CURSOR = a_TTY__VF_LAST<<4, /* Move visual cursor for user! */
1271 a_LEFT_MIN = a_TTY__VF_LAST<<5, /* On left boundary */
1272 a_RIGHT_MAX = a_TTY__VF_LAST<<6,
1273 a_HAVE_POSITION = a_TTY__VF_LAST<<7, /* Print the position indicator */
1275 /* We carry some flags over invocations (not worth a specific field) */
1276 a_VISIBLE_PROMPT = a_TTY__VF_LAST<<8, /* The prompt is on the screen */
1277 a_PERSIST_MASK = a_VISIBLE_PROMPT,
1278 a__LAST = a_PERSIST_MASK
1281 ui32_t f, w, phy_wid_base, phy_wid, phy_base, phy_cur, cnt, lstcur, cur,
1282 vi_left, vi_right, phy_nxtcur;
1283 struct a_tty_cell const *tccp, *tcp_left, *tcp_right, *tcxp;
1284 NYD2_ENTER;
1285 n_LCTA(UICMP(64, a__LAST, <, UI32_MAX), "Flag bits excess storage datatype");
1287 f = tlp->tl_vi_flags;
1288 tlp->tl_vi_flags = (f & ~(a_TTY_VF_REFRESH | a_PERSIST_MASK)) |
1289 a_TTY_VF_SYNC;
1290 f |= a_TRUE_RV;
1291 if((w = tlp->tl_prompt_width) > 0)
1292 f |= a_HAVE_PROMPT;
1293 f |= a_HAVE_POSITION;
1295 /* XXX We don't have a OnTerminalResize event (see main.c) yet, so we need
1296 * XXX to reevaluate our circumstances over and over again */
1297 /* Don't display prompt or position indicator on very small screens */
1298 if((phy_wid_base = (ui32_t)scrnwidth) <= a_TTY_WIDTH_RIPOFF)
1299 f &= ~(a_HAVE_PROMPT | a_HAVE_POSITION);
1300 else{
1301 phy_wid_base -= a_TTY_WIDTH_RIPOFF;
1303 /* Disable the prompt if the screen is too small; due to lack of some
1304 * indicator simply add a second ripoff */
1305 if((f & a_HAVE_PROMPT) && w + a_TTY_WIDTH_RIPOFF >= phy_wid_base)
1306 f &= ~a_HAVE_PROMPT;
1309 phy_wid = phy_wid_base;
1310 phy_base = 0;
1311 phy_cur = tlp->tl_phy_cursor;
1312 cnt = tlp->tl_count;
1313 lstcur = tlp->tl_lst_cursor;
1315 /* XXX Assume dirty screen if shrunk */
1316 if(cnt < tlp->tl_lst_count)
1317 f |= a_TTY_VF_MOD_DIRTY;
1319 /* TODO Without HAVE_TERMCAP, it would likely be much cheaper to simply
1320 * TODO always "cr + paint + ce + ch", since ce is simulated via spaces.. */
1322 /* Quickshot: if the line is empty, possibly print prompt and out */
1323 if(cnt == 0){
1324 /* In that special case dirty anything if it seems better */
1325 if((f & a_TTY_VF_MOD_CONTENT) || tlp->tl_lst_count > 0)
1326 f |= a_TTY_VF_MOD_DIRTY;
1328 if((f & a_TTY_VF_MOD_DIRTY) && phy_cur != 0){
1329 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
1330 goto jerr;
1331 phy_cur = 0;
1334 if((f & (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)) ==
1335 (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)){
1336 if(fputs(tlp->tl_prompt, stdout) == EOF)
1337 goto jerr;
1338 phy_cur = tlp->tl_prompt_width + 1;
1341 /* May need to clear former line content */
1342 if((f & a_TTY_VF_MOD_DIRTY) &&
1343 !n_termcap_cmd(n_TERMCAP_CMD_ce, phy_cur, -1))
1344 goto jerr;
1346 tlp->tl_phy_start = tlp->tl_line.cells;
1347 goto jleave;
1350 /* Try to get an idea of the visual window */
1352 /* Find the left visual boundary */
1353 phy_wid = (phy_wid >> 1) + (phy_wid >> 2);
1354 if((cur = tlp->tl_cursor) == cnt)
1355 --cur;
1357 w = (tcp_left = tccp = tlp->tl_line.cells + cur)->tc_width;
1358 if(w == UI8_MAX) /* TODO yet TAB == SPC */
1359 w = 1;
1360 while(tcp_left > tlp->tl_line.cells){
1361 ui16_t cw = tcp_left[-1].tc_width;
1363 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1364 cw = 1;
1365 if(w + cw >= phy_wid)
1366 break;
1367 w += cw;
1368 --tcp_left;
1370 vi_left = w;
1372 /* If the left hand side of our visual viewpoint consumes less than half
1373 * of the screen width, show the prompt */
1374 if(tcp_left == tlp->tl_line.cells)
1375 f |= a_LEFT_MIN;
1377 if((f & (a_LEFT_MIN | a_HAVE_PROMPT)) == (a_LEFT_MIN | a_HAVE_PROMPT) &&
1378 w + tlp->tl_prompt_width < phy_wid){
1379 phy_base = tlp->tl_prompt_width;
1380 f |= a_SHOW_PROMPT;
1383 /* Then search for right boundary. We always leave the rightmost column
1384 * empty because some terminals [cw]ould wrap the line if we write into
1385 * that. XXX terminfo(5)/termcap(5) have the semi_auto_right_margin/sam/YE
1386 * XXX capability to indicate this, but we don't look at that */
1387 phy_wid = phy_wid_base - phy_base;
1388 tcp_right = tlp->tl_line.cells + cnt;
1390 while(&tccp[1] < tcp_right){
1391 ui16_t cw = tccp[1].tc_width;
1392 ui32_t i;
1394 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1395 cw = 1;
1396 i = w + cw;
1397 if(i > phy_wid)
1398 break;
1399 w = i;
1400 ++tccp;
1402 vi_right = w - vi_left;
1404 /* If the complete line including prompt fits on the screen, show prompt */
1405 if(--tcp_right == tccp){
1406 f |= a_RIGHT_MAX;
1408 /* Since we did brute-force walk also for the left boundary we may end up
1409 * in a situation were anything effectively fits on the screen, including
1410 * the prompt that is, but were we don't recognize this since we
1411 * restricted the search to fit in some visual viewpoint. Therefore try
1412 * again to extend the left boundary to overcome that */
1413 if(!(f & a_LEFT_MIN)){
1414 struct a_tty_cell const *tc1p = tlp->tl_line.cells;
1415 ui32_t vil1 = vi_left;
1417 assert(!(f & a_SHOW_PROMPT));
1418 w += tlp->tl_prompt_width;
1419 for(tcxp = tcp_left;;){
1420 ui32_t i = tcxp[-1].tc_width;
1422 if(i == UI8_MAX) /* TODO yet TAB == SPC */
1423 i = 1;
1424 vil1 += i;
1425 i += w;
1426 if(i > phy_wid)
1427 break;
1428 w = i;
1429 if(--tcxp == tc1p){
1430 tcp_left = tc1p;
1431 vi_left = vil1;
1432 f |= a_LEFT_MIN;
1433 break;
1436 /*w -= tlp->tl_prompt_width;*/
1439 tcp_right = tccp;
1440 tccp = tlp->tl_line.cells + cur;
1442 if((f & (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT | a_SHOW_PROMPT)) ==
1443 (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT) &&
1444 w + tlp->tl_prompt_width <= phy_wid){
1445 phy_wid -= (phy_base = tlp->tl_prompt_width);
1446 f |= a_SHOW_PROMPT;
1449 /* Try to avoid repainting the complete line - this is possible if the
1450 * cursor "did not leave the screen" and the prompt status hasn't changed.
1451 * I.e., after clamping virtual viewpoint, compare relation to physical */
1452 if((f & (a_TTY_VF_MOD_SINGLE/*FIXME*/ |
1453 a_TTY_VF_MOD_CONTENT/* xxx */ | a_TTY_VF_MOD_DIRTY)) ||
1454 (tcxp = tlp->tl_phy_start) == NULL ||
1455 tcxp > tccp || tcxp <= tcp_right)
1456 f |= a_TTY_VF_MOD_DIRTY;
1457 else{
1458 f |= a_TTY_VF_MOD_DIRTY;
1459 #if 0
1460 struct a_tty_cell const *tcyp;
1461 si32_t cur_displace;
1462 ui32_t phy_lmargin, phy_rmargin, fx, phy_displace;
1464 phy_lmargin = (fx = phy_wid) / 100;
1465 phy_rmargin = fx - (phy_lmargin * a_TTY_SCROLL_MARGIN_RIGHT);
1466 phy_lmargin *= a_TTY_SCROLL_MARGIN_LEFT;
1467 fx = (f & (a_SHOW_PROMPT | a_VISIBLE_PROMPT));
1469 if(fx == 0 || fx == (a_SHOW_PROMPT | a_VISIBLE_PROMPT)){
1471 #endif
1473 goto jpaint;
1475 /* We know what we have to paint, start synchronizing */
1476 jpaint:
1477 assert(phy_cur == tlp->tl_phy_cursor);
1478 assert(phy_wid == phy_wid_base - phy_base);
1479 assert(cnt == tlp->tl_count);
1480 assert(cnt > 0);
1481 assert(lstcur == tlp->tl_lst_cursor);
1482 assert(tccp == tlp->tl_line.cells + cur);
1484 phy_nxtcur = phy_base; /* FIXME only if repaint cpl. */
1486 /* Quickshot: is it only cursor movement within the visible screen? */
1487 if((f & a_TTY_VF_REFRESH) == a_TTY_VF_MOD_CURSOR){
1488 f |= a_MOVE_CURSOR;
1489 goto jcursor;
1492 /* To be able to apply some quick jump offs, clear line if possible */
1493 if(f & a_TTY_VF_MOD_DIRTY){
1494 /* Force complete clearance and cursor reinitialization */
1495 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr) ||
1496 !n_termcap_cmd(n_TERMCAP_CMD_ce, 0, -1))
1497 goto jerr;
1498 tlp->tl_phy_start = tcp_left;
1499 phy_cur = 0;
1502 if((f & (a_TTY_VF_MOD_DIRTY | a_SHOW_PROMPT)) && phy_cur != 0){
1503 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
1504 goto jerr;
1505 phy_cur = 0;
1508 if(f & a_SHOW_PROMPT){
1509 assert(phy_base == tlp->tl_prompt_width);
1510 if(fputs(tlp->tl_prompt, stdout) == EOF)
1511 goto jerr;
1512 phy_cur = phy_nxtcur;
1513 f |= a_VISIBLE_PROMPT;
1514 }else
1515 f &= ~a_VISIBLE_PROMPT;
1517 /* FIXME reposition cursor for paint */
1518 for(w = phy_nxtcur; tcp_left <= tcp_right; ++tcp_left){
1519 ui16_t cw;
1521 cw = tcp_left->tc_width;
1523 if(n_LIKELY(!tcp_left->tc_novis)){
1524 if(fwrite(tcp_left->tc_cbuf, sizeof *tcp_left->tc_cbuf,
1525 tcp_left->tc_count, stdout) != tcp_left->tc_count)
1526 goto jerr;
1527 }else{ /* XXX Shouldn't be here <-> CText, ui_str.c */
1528 char wbuf[8]; /* XXX magic */
1530 if(options & OPT_UNICODE){
1531 ui32_t wc;
1533 wc = (ui32_t)tcp_left->tc_wc;
1534 if((wc & ~0x1Fu) == 0)
1535 wc |= 0x2400;
1536 else if(wc == 0x7F)
1537 wc = 0x2421;
1538 else
1539 wc = 0x2426;
1540 n_utf32_to_utf8(wc, wbuf);
1541 }else
1542 wbuf[0] = '?', wbuf[1] = '\0';
1544 if(fputs(wbuf, stdout) == EOF)
1545 goto jerr;
1546 cw = 1;
1549 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1550 cw = 1;
1551 w += cw;
1552 if(tcp_left == tccp)
1553 phy_nxtcur = w;
1554 phy_cur += cw;
1557 /* Write something position marker alike if it doesn't fit on screen */
1558 if((f & a_HAVE_POSITION) &&
1559 ((f & (a_LEFT_MIN | a_RIGHT_MAX)) != (a_LEFT_MIN | a_RIGHT_MAX) ||
1560 ((f & a_HAVE_PROMPT) && !(f & a_SHOW_PROMPT)))){
1561 # ifdef HAVE_COLOUR
1562 char *posbuf = tlp->tl_pos_buf, *pos = tlp->tl_pos;
1563 # else
1564 char posbuf[5], *pos = posbuf;
1566 pos[4] = '\0';
1567 # endif
1569 if(phy_cur != (w = phy_wid_base) &&
1570 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = w, 0))
1571 goto jerr;
1573 *pos++ = '|';
1574 if((f & a_LEFT_MIN) && (!(f & a_HAVE_PROMPT) || (f & a_SHOW_PROMPT)))
1575 memcpy(pos, "^.+", 3);
1576 else if(f & a_RIGHT_MAX)
1577 memcpy(pos, ".+$", 3);
1578 else{
1579 /* Theoretical line length limit a_TTY_LINE_MAX, choose next power of
1580 * ten (10 ** 10) to represent 100 percent, since we don't have a macro
1581 * that generates a constant, and i don't trust the standard "u type
1582 * suffix automatically scales" calculate the large number */
1583 static char const itoa[] = "0123456789";
1585 ui64_t const fact100 = (ui64_t)0x3B9ACA00u * 10u, fact = fact100 / 100;
1586 ui32_t i = (ui32_t)(((fact100 / cnt) * tlp->tl_cursor) / fact);
1587 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1589 if(i < 10)
1590 pos[0] = ' ', pos[1] = itoa[i];
1591 else
1592 pos[1] = itoa[i % 10], pos[0] = itoa[i / 10];
1593 pos[2] = '%';
1596 if(fputs(posbuf, stdout) == EOF)
1597 goto jerr;
1598 phy_cur += 4;
1601 /* Users are used to see the cursor right of the point of interest, so we
1602 * need some further adjustments unless in special conditions. Be aware
1603 * that we may have adjusted cur at the beginning, too */
1604 if((cur = tlp->tl_cursor) == 0)
1605 phy_nxtcur = phy_base;
1606 else if(cur != cnt){
1607 ui16_t cw = tccp->tc_width;
1609 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1610 cw = 1;
1611 phy_nxtcur -= cw;
1614 jcursor:
1615 if(((f & a_MOVE_CURSOR) || phy_nxtcur != phy_cur) &&
1616 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = phy_nxtcur, 0))
1617 goto jerr;
1619 jleave:
1620 tlp->tl_vi_flags |= (f & a_PERSIST_MASK);
1621 tlp->tl_lst_count = tlp->tl_count;
1622 tlp->tl_lst_cursor = tlp->tl_cursor;
1623 tlp->tl_phy_cursor = phy_cur;
1625 NYD2_LEAVE;
1626 return ((f & a_TRUE_RV) != 0);
1627 jerr:
1628 f &= ~a_TRUE_RV;
1629 goto jleave;
1632 static si32_t
1633 a_tty_wboundary(struct a_tty_line *tlp, si32_t dir){/* TODO shell token-wise */
1634 bool_t anynon;
1635 struct a_tty_cell *tcap;
1636 ui32_t cur, cnt;
1637 si32_t rv;
1638 NYD2_ENTER;
1640 assert(dir == 1 || dir == -1);
1642 rv = -1;
1643 cnt = tlp->tl_count;
1644 cur = tlp->tl_cursor;
1646 if(dir < 0){
1647 if(cur == 0)
1648 goto jleave;
1649 }else if(cur + 1 >= cnt)
1650 goto jleave;
1651 else
1652 --cnt, --cur; /* xxx Unsigned wrapping may occur (twice), then */
1654 for(rv = 0, tcap = tlp->tl_line.cells, anynon = FAL0;;){
1655 wchar_t wc;
1657 wc = tcap[cur += (ui32_t)dir].tc_wc;
1658 if(iswblank(wc) || iswpunct(wc)){
1659 if(anynon)
1660 break;
1661 }else
1662 anynon = TRU1;
1664 ++rv;
1666 if(dir < 0){
1667 if(cur == 0)
1668 break;
1669 }else if(cur + 1 >= cnt){
1670 ++rv;
1671 break;
1674 jleave:
1675 NYD2_LEAVE;
1676 return rv;
1679 static void
1680 a_tty_khome(struct a_tty_line *tlp, bool_t dobell){
1681 ui32_t f;
1682 NYD2_ENTER;
1684 if(n_LIKELY(tlp->tl_cursor > 0)){
1685 tlp->tl_cursor = 0;
1686 f = a_TTY_VF_MOD_CURSOR;
1687 }else if(dobell)
1688 f = a_TTY_VF_BELL;
1689 else
1690 f = a_TTY_VF_NONE;
1692 tlp->tl_vi_flags |= f;
1693 NYD2_LEAVE;
1696 static void
1697 a_tty_kend(struct a_tty_line *tlp){
1698 ui32_t f;
1699 NYD2_ENTER;
1701 if(n_LIKELY(tlp->tl_cursor < tlp->tl_count)){
1702 tlp->tl_cursor = tlp->tl_count;
1703 f = a_TTY_VF_MOD_CURSOR;
1704 }else
1705 f = a_TTY_VF_BELL;
1707 tlp->tl_vi_flags |= f;
1708 NYD2_LEAVE;
1711 static void
1712 a_tty_kbs(struct a_tty_line *tlp){
1713 ui32_t f, cur, cnt;
1714 NYD2_ENTER;
1716 cur = tlp->tl_cursor;
1717 cnt = tlp->tl_count;
1719 if(n_LIKELY(cur > 0)){
1720 tlp->tl_cursor = --cur;
1721 tlp->tl_count = --cnt;
1723 if((cnt -= cur) > 0){
1724 struct a_tty_cell *tcap;
1726 tcap = tlp->tl_line.cells + cur;
1727 memmove(tcap, &tcap[1], cnt *= sizeof(*tcap));
1729 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
1730 }else
1731 f = a_TTY_VF_BELL;
1733 tlp->tl_vi_flags |= f;
1734 NYD2_LEAVE;
1737 static void
1738 a_tty_ksnarf(struct a_tty_line *tlp, bool_t cplline, bool_t dobell){
1739 ui32_t i, f;
1740 NYD2_ENTER;
1742 f = a_TTY_VF_NONE;
1743 i = tlp->tl_cursor;
1745 if(cplline && i > 0){
1746 tlp->tl_cursor = i = 0;
1747 f = a_TTY_VF_MOD_CURSOR;
1750 if(n_LIKELY(i < tlp->tl_count)){
1751 struct a_tty_cell *tcap;
1753 tcap = &tlp->tl_line.cells[0];
1754 a_tty_copy2paste(tlp, &tcap[i], &tcap[tlp->tl_count]);
1755 tlp->tl_count = i;
1756 f = a_TTY_VF_MOD_CONTENT;
1757 }else if(dobell)
1758 f |= a_TTY_VF_BELL;
1760 tlp->tl_vi_flags |= f;
1761 NYD2_LEAVE;
1764 static si32_t
1765 a_tty_kdel(struct a_tty_line *tlp){
1766 ui32_t cur, cnt, f;
1767 si32_t i;
1768 NYD2_ENTER;
1770 cur = tlp->tl_cursor;
1771 cnt = tlp->tl_count;
1772 i = (si32_t)(cnt - cur);
1774 if(n_LIKELY(i > 0)){
1775 tlp->tl_count = --cnt;
1777 if(n_LIKELY(--i > 0)){
1778 struct a_tty_cell *tcap;
1780 tcap = &tlp->tl_line.cells[cur];
1781 memmove(tcap, &tcap[1], (ui32_t)i * sizeof(*tcap));
1783 f = a_TTY_VF_MOD_CONTENT;
1784 }else if(cnt == 0 && !ok_blook(ignoreeof)){
1785 putchar('^');
1786 putchar('D');
1787 i = -1;
1788 f = a_TTY_VF_NONE;
1789 }else{
1790 i = 0;
1791 f = a_TTY_VF_BELL;
1794 tlp->tl_vi_flags |= f;
1795 NYD2_LEAVE;
1796 return i;
1799 static void
1800 a_tty_kleft(struct a_tty_line *tlp){
1801 ui32_t f;
1802 NYD2_ENTER;
1804 if(n_LIKELY(tlp->tl_cursor > 0)){
1805 --tlp->tl_cursor;
1806 f = a_TTY_VF_MOD_CURSOR;
1807 }else
1808 f = a_TTY_VF_BELL;
1810 tlp->tl_vi_flags |= f;
1811 NYD2_LEAVE;
1814 static void
1815 a_tty_kright(struct a_tty_line *tlp){
1816 ui32_t i;
1817 NYD2_ENTER;
1819 if(n_LIKELY((i = tlp->tl_cursor + 1) <= tlp->tl_count)){
1820 tlp->tl_cursor = i;
1821 i = a_TTY_VF_MOD_CURSOR;
1822 }else
1823 i = a_TTY_VF_BELL;
1825 tlp->tl_vi_flags |= i;
1826 NYD2_LEAVE;
1829 static void
1830 a_tty_ksnarfw(struct a_tty_line *tlp, bool_t fwd){
1831 struct a_tty_cell *tcap;
1832 ui32_t cnt, cur, f;
1833 si32_t i;
1834 NYD2_ENTER;
1836 if(n_UNLIKELY((i = a_tty_wboundary(tlp, (fwd ? +1 : -1))) <= 0)){
1837 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
1838 goto jleave;
1841 cnt = tlp->tl_count - (ui32_t)i;
1842 cur = tlp->tl_cursor;
1843 if(!fwd)
1844 cur -= (ui32_t)i;
1845 tcap = &tlp->tl_line.cells[cur];
1847 a_tty_copy2paste(tlp, &tcap[0], &tcap[i]);
1849 if((tlp->tl_count = cnt) != (tlp->tl_cursor = cur)){
1850 cnt -= cur;
1851 memmove(&tcap[0], &tcap[i], cnt * sizeof(*tcap)); /* FIXME*/
1854 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
1855 jleave:
1856 tlp->tl_vi_flags |= f;
1857 NYD2_LEAVE;
1860 static void
1861 a_tty_kgow(struct a_tty_line *tlp, si32_t dir){
1862 ui32_t f;
1863 si32_t i;
1864 NYD2_ENTER;
1866 if(n_UNLIKELY((i = a_tty_wboundary(tlp, dir)) <= 0))
1867 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
1868 else{
1869 if(dir < 0)
1870 i = -i;
1871 tlp->tl_cursor += (ui32_t)i;
1872 f = a_TTY_VF_MOD_CURSOR;
1875 tlp->tl_vi_flags |= f;
1876 NYD2_LEAVE;
1879 static bool_t
1880 a_tty_kother(struct a_tty_line *tlp, wchar_t wc){
1881 /* Append if at EOL, insert otherwise;
1882 * since we may move around character-wise, always use a fresh ps */
1883 mbstate_t ps;
1884 struct a_tty_cell tc, *tcap;
1885 ui32_t f, cur, cnt;
1886 bool_t rv;
1887 NYD2_ENTER;
1889 rv = FAL0;
1890 f = a_TTY_VF_NONE;
1892 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1893 if(tlp->tl_count + 1 >= a_TTY_LINE_MAX){
1894 n_err(_("Stop here, we can't extend line beyond size limit\n"));
1895 goto jleave;
1898 /* First init a cell and see whether we'll really handle this wc */
1899 memset(&ps, 0, sizeof ps);
1900 /* C99 */{
1901 size_t l;
1903 l = wcrtomb(tc.tc_cbuf, tc.tc_wc = wc, &ps);
1904 if(n_UNLIKELY(l > MB_LEN_MAX)){
1905 jemb:
1906 n_err(_("wcrtomb(3) error: too many multibyte character bytes\n"));
1907 goto jleave;
1909 tc.tc_count = (ui16_t)l;
1911 if(n_UNLIKELY((options & OPT_ENC_MBSTATE) != 0)){
1912 l = wcrtomb(&tc.tc_cbuf[l], L'\0', &ps);
1913 if(n_LIKELY(l == 1))
1914 /* Only NUL terminator */;
1915 else if(n_LIKELY(--l < MB_LEN_MAX))
1916 tc.tc_count += (ui16_t)l;
1917 else
1918 goto jemb;
1922 /* Yes, we will! Place it in the array */
1923 tc.tc_novis = (iswprint(wc) == 0);
1924 tc.tc_width = a_tty_wcwidth(wc);
1925 /* TODO if(tc.tc_novis && tc.tc_width > 0) */
1927 cur = tlp->tl_cursor++;
1928 cnt = tlp->tl_count++ - cur;
1929 tcap = &tlp->tl_line.cells[cur];
1930 if(cnt >= 1){
1931 memmove(&tcap[1], tcap, cnt * sizeof(*tcap));
1932 f = a_TTY_VF_MOD_CONTENT;
1933 }else
1934 f = a_TTY_VF_MOD_SINGLE;
1935 memcpy(tcap, &tc, sizeof *tcap);
1937 f |= a_TTY_VF_MOD_CURSOR;
1938 rv = TRU1;
1939 jleave:
1940 if(!rv)
1941 f |= a_TTY_VF_BELL;
1942 tlp->tl_vi_flags |= f;
1943 NYD2_LEAVE;
1944 return rv;
1947 static ui32_t
1948 a_tty_kht(struct a_tty_line *tlp){
1949 ui8_t (*autorecmem)[n_MEMORY_AUTOREC_TYPE_SIZEOF], *autorec_persist;
1950 struct stat sb;
1951 struct str orig, bot, topp, sub, exp, preexp;
1952 struct n_string shou, *shoup;
1953 struct a_tty_cell *cword, *ctop, *cx;
1954 bool_t wedid, set_savec;
1955 ui32_t rv, f;
1956 NYD2_ENTER;
1958 /* Get plain line data; if this is the first expansion/xy, update the
1959 * very original content so that ^G gets the origin back */
1960 orig = tlp->tl_savec;
1961 a_tty_cell2save(tlp);
1962 exp = tlp->tl_savec;
1963 if(orig.s != NULL){
1964 /*tlp->tl_savec = orig;*/
1965 set_savec = FAL0;
1966 }else
1967 set_savec = TRU1;
1968 orig = exp;
1970 autorec_persist = n_memory_autorec_current();
1971 n_memory_autorec_push(autorecmem = n_lofi_alloc(sizeof *autorecmem));
1973 shoup = n_string_creat_auto(&shou);
1974 f = a_TTY_VF_NONE;
1976 /* Find the word to be expanded */
1978 cword = tlp->tl_line.cells;
1979 ctop = cword + tlp->tl_cursor;
1980 cx = cword + tlp->tl_count;
1982 /* topp: separate data right of cursor */
1983 if(cx > ctop){
1984 for(rv = 0; ctop < cx; ++ctop)
1985 rv += ctop->tc_count;
1986 topp.l = rv;
1987 topp.s = orig.s + orig.l - rv;
1988 ctop = cword + tlp->tl_cursor;
1989 }else
1990 topp.s = NULL, topp.l = 0;
1992 /* Find the shell token that corresponds to the cursor position */
1993 /* C99 */{
1994 size_t max;
1996 max = 0;
1997 if(ctop > cword){
1998 for(; cword < ctop; ++cword)
1999 max += cword->tc_count;
2000 cword = tlp->tl_line.cells;
2002 bot = sub = orig;
2003 bot.l = 0;
2004 sub.l = max;
2006 if(max > 0){
2007 for(;;){
2008 enum n_shexp_state shs;
2010 exp = sub;
2011 shs = n_shexp_parse_token(NULL, &sub, n_SHEXP_PARSE_DRYRUN |
2012 n_SHEXP_PARSE_TRIMSPACE | n_SHEXP_PARSE_IGNORE_EMPTY |
2013 n_SHEXP_PARSE_QUOTE_AUTO_CLOSE);
2014 if(sub.l != 0){
2015 size_t x;
2017 assert(max >= sub.l);
2018 x = max - sub.l;
2019 bot.l += x;
2020 max -= x;
2021 continue;
2023 if(shs & n_SHEXP_STATE_ERR_MASK){
2024 n_err(_("Invalid completion pattern: %.*s\n"),
2025 (int)exp.l, exp.s);
2026 goto jnope;
2028 n_shexp_parse_token(shoup, &exp,
2029 n_SHEXP_PARSE_TRIMSPACE | n_SHEXP_PARSE_IGNORE_EMPTY |
2030 n_SHEXP_PARSE_QUOTE_AUTO_CLOSE);
2031 break;
2034 sub.s = n_string_cp(shoup);
2035 sub.l = shoup->s_len;
2039 /* Leave room for "implicit asterisk" expansion, as below */
2040 if(sub.l == 0){
2041 wedid = TRU1;
2042 sub.s = n_UNCONST("*");
2043 sub.l = 1;
2046 preexp.s = n_UNCONST(n_empty);
2047 preexp.l = 0;
2048 wedid = FAL0;
2049 jredo:
2050 /* TODO Super-Heavy-Metal: block all sigs, avoid leaks on jump */
2051 hold_all_sigs();
2052 exp.s = fexpand(sub.s, a_TTY_TAB_FEXP_FL);
2053 rele_all_sigs();
2055 if(exp.s == NULL || (exp.l = strlen(exp.s)) == 0){
2056 /* No. But maybe the users' desire was to complete only a part of the
2057 * shell token of interest! TODO This can be improved, we would need to
2058 * TODO have shexp_parse to create a DOM structure of parsed snippets, so
2059 * TODO that we can tell for each snippet which quote is active and
2060 * TODO whether we may cross its boundary and/or apply expansion for it */
2061 if(wedid == TRU1){
2062 size_t i, li;
2064 wedid = TRUM1;
2065 for(li = UIZ_MAX, i = sub.l; i-- > 0;){
2066 char c;
2068 if((c = sub.s[i]) == '/' || c == '+' /* *folder*! */)
2069 li = i;
2070 /* Do stop once some "magic" characters are seen XXX magic set */
2071 else if(c == '<' || c == '>' || c == '=' || c == ':')
2072 break;
2074 if(li != UIZ_MAX){
2075 preexp = sub;
2076 preexp.l = li;
2077 sub.l -= li;
2078 sub.s += li;
2079 goto jredo;
2082 goto jnope;
2085 if(wedid == TRUM1 && preexp.l > 0)
2086 preexp.s = savestrbuf(preexp.s, preexp.l);
2088 /* May be multi-return! */
2089 if(pstate & PS_EXPAND_MULTIRESULT)
2090 goto jmulti;
2092 /* xxx That is not really true since the limit counts characters not bytes */
2093 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
2094 if(exp.l >= a_TTY_LINE_MAX - 1 || a_TTY_LINE_MAX - 1 - exp.l < preexp.l){
2095 n_err(_("Tabulator expansion would extend beyond line size limit\n"));
2096 goto jnope;
2099 /* If the expansion equals the original string, assume the user wants what
2100 * is usually known as tab completion, append `*' and restart */
2101 if(!wedid && exp.l == sub.l && !memcmp(exp.s, sub.s, exp.l)){
2102 if(sub.s[sub.l - 1] == '*')
2103 goto jnope;
2105 wedid = TRU1;
2106 shoup = n_string_push_c(shoup, '*');
2107 sub.s = n_string_cp(shoup);
2108 sub.l = shoup->s_len;
2109 goto jredo;
2112 /* If it is a directory, and there is not yet a / appended, then we want the
2113 * user to confirm that he wants to dive in -- with only a HT */
2114 if(wedid && exp.l == --sub.l && !memcmp(exp.s, sub.s, exp.l) &&
2115 exp.s[exp.l - 1] != '/'){
2116 if(stat(exp.s, &sb) || !S_ISDIR(sb.st_mode))
2117 goto jnope;
2118 sub.s = salloc(exp.l + 1 +1);
2119 memcpy(sub.s, exp.s, exp.l);
2120 sub.s[exp.l++] = '/';
2121 sub.s[exp.l] = '\0';
2122 exp.s = sub.s;
2123 wedid = FAL0;
2124 goto jset;
2125 }else{
2126 if(wedid && (wedid = (exp.s[exp.l - 1] == '*')))
2127 --exp.l;
2128 exp.s[exp.l] = '\0';
2129 jset:
2130 exp.l = strlen(exp.s = n_shexp_quote_cp(exp.s, tlp->tl_quote_rndtrip));
2131 tlp->tl_defc_cursor_byte = bot.l + preexp.l + exp.l -1;
2132 if(wedid)
2133 goto jnope;
2136 orig.l = bot.l + preexp.l + exp.l + topp.l;
2137 orig.s = n_autorec_alloc(autorec_persist, orig.l + 5 +1);
2138 if((rv = (ui32_t)bot.l) > 0)
2139 memcpy(orig.s, bot.s, rv);
2140 if(preexp.l > 0){
2141 memcpy(&orig.s[rv], preexp.s, preexp.l);
2142 rv += preexp.l;
2144 memcpy(&orig.s[rv], exp.s, exp.l);
2145 rv += exp.l;
2146 if(topp.l > 0){
2147 memcpy(&orig.s[rv], topp.s, topp.l);
2148 rv += topp.l;
2150 orig.s[rv] = '\0';
2152 tlp->tl_defc = orig;
2153 tlp->tl_count = tlp->tl_cursor = 0;
2154 f |= a_TTY_VF_MOD_DIRTY;
2155 jleave:
2156 n_memory_autorec_pop(autorecmem);
2157 n_lofi_free(autorecmem);
2158 tlp->tl_vi_flags |= f;
2159 NYD2_LEAVE;
2160 return rv;
2162 jmulti:{
2163 struct n_visual_info_ctx vic;
2164 struct str input;
2165 wc_t c2, c1;
2166 bool_t isfirst;
2167 char const *lococp;
2168 size_t locolen, scrwid, lnlen, lncnt, prefixlen;
2169 FILE *fp;
2171 if((fp = Ftmp(NULL, "tabex", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
2172 n_perr(_("tmpfile"), 0);
2173 fp = stdout;
2176 /* How long is the result string for real? Search the NUL NUL
2177 * terminator. While here, detect the longest entry to perform an
2178 * initial allocation of our accumulator string */
2179 locolen = preexp.l;
2181 size_t i;
2183 i = strlen(&exp.s[++exp.l]);
2184 locolen = n_MAX(locolen, i);
2185 exp.l += i;
2186 }while(exp.s[exp.l + 1] != '\0');
2188 shoup = n_string_reserve(n_string_trunc(shoup, 0),
2189 locolen + (locolen >> 1));
2191 /* Iterate (once again) over all results */
2192 scrwid = (size_t)scrnwidth - ((size_t)scrnwidth >> 3);
2193 lnlen = lncnt = 0;
2194 n_UNINIT(prefixlen, 0);
2195 n_UNINIT(lococp, NULL);
2196 n_UNINIT(c1, '\0');
2197 for(isfirst = TRU1; exp.l > 0; isfirst = FAL0, c1 = c2){
2198 size_t i;
2199 char const *fullpath;
2201 /* Next result */
2202 sub = exp;
2203 sub.l = i = strlen(sub.s);
2204 assert(exp.l >= i);
2205 if((exp.l -= i) > 0)
2206 --exp.l;
2207 exp.s += ++i;
2209 /* Separate dirname and basename */
2210 fullpath = sub.s;
2211 if(isfirst){
2212 char const *cp;
2214 if((cp = strrchr(fullpath, '/')) != NULL)
2215 prefixlen = PTR2SIZE(++cp - fullpath);
2216 else
2217 prefixlen = 0;
2219 if(prefixlen > 0 && prefixlen < sub.l){
2220 sub.l -= prefixlen;
2221 sub.s += prefixlen;
2224 /* We want case-insensitive sort-order */
2225 memset(&vic, 0, sizeof vic);
2226 vic.vic_indat = sub.s;
2227 vic.vic_inlen = sub.l;
2228 c2 = n_visual_info(&vic, n_VISUAL_INFO_ONE_CHAR) ? vic.vic_waccu
2229 : (ui8_t)*sub.s;
2230 #ifdef HAVE_C90AMEND1
2231 c2 = towlower(c2);
2232 #else
2233 c2 = lowerconv(c2);
2234 #endif
2236 /* Query longest common prefix along the way */
2237 if(isfirst){
2238 c1 = c2;
2239 lococp = sub.s;
2240 locolen = sub.l;
2241 }else if(locolen > 0){
2242 for(i = 0; i < locolen; ++i)
2243 if(lococp[i] != sub.s[i]){
2244 i = field_detect_clip(i, lococp, i);
2245 locolen = i;
2246 break;
2250 /* Prepare display */
2251 input = sub;
2252 shoup = n_shexp_quote(n_string_trunc(shoup, 0), &input,
2253 tlp->tl_quote_rndtrip);
2254 memset(&vic, 0, sizeof vic);
2255 vic.vic_indat = shoup->s_dat;
2256 vic.vic_inlen = shoup->s_len;
2257 if(!n_visual_info(&vic,
2258 n_VISUAL_INFO_SKIP_ERRORS | n_VISUAL_INFO_WIDTH_QUERY))
2259 vic.vic_vi_width = shoup->s_len;
2261 /* Put on screen. Indent follow lines of same sort slot */
2262 c1 = (c1 != c2);
2263 if(isfirst || c1 ||
2264 scrwid < lnlen || scrwid - lnlen <= vic.vic_vi_width + 2){
2265 putc('\n', fp);
2266 if(scrwid < lnlen)
2267 ++lncnt;
2268 ++lncnt, lnlen = 0;
2269 if(!isfirst && !c1)
2270 goto jsep;
2271 }else if(lnlen > 0){
2272 jsep:
2273 fputs(" ", fp);
2274 lnlen += 2;
2276 fputs(n_string_cp(shoup), fp);
2277 lnlen += vic.vic_vi_width;
2279 /* Support the known file name tagging
2280 * XXX *line-editor-completion-filetype* or so */
2281 if(!lstat(fullpath, &sb)){
2282 char c = '\0';
2284 if(S_ISDIR(sb.st_mode))
2285 c = '/';
2286 else if(S_ISLNK(sb.st_mode))
2287 c = '@';
2288 # ifdef S_ISFIFO
2289 else if(S_ISFIFO(sb.st_mode))
2290 c = '|';
2291 # endif
2292 # ifdef S_ISSOCK
2293 else if(S_ISSOCK(sb.st_mode))
2294 c = '=';
2295 # endif
2296 # ifdef S_ISCHR
2297 else if(S_ISCHR(sb.st_mode))
2298 c = '%';
2299 # endif
2300 # ifdef S_ISBLK
2301 else if(S_ISBLK(sb.st_mode))
2302 c = '#';
2303 # endif
2305 if(c != '\0'){
2306 putc(c, fp);
2307 ++lnlen;
2311 putc('\n', fp);
2312 ++lncnt;
2314 page_or_print(fp, lncnt);
2315 if(fp != stdout)
2316 Fclose(fp);
2318 n_string_gut(shoup);
2320 /* A common prefix of 0 means we cannot provide the user any auto
2321 * completed characters */
2322 if(locolen == 0)
2323 goto jnope;
2325 /* Otherwise we can, so extend the visual line content by the common
2326 * prefix (in a reversible way) */
2327 (exp.s = n_UNCONST(lococp))[locolen] = '\0';
2328 exp.s -= prefixlen;
2329 exp.l = (locolen += prefixlen);
2331 /* XXX Indicate that there is multiple choice */
2332 /* XXX f |= a_TTY_VF_BELL; -> *line-editor-completion-bell*? or so */
2333 wedid = FAL0;
2334 goto jset;
2337 jnope:
2338 /* If we've provided a default content, but failed to expand, there is
2339 * nothing we can "revert to": drop that default again */
2340 if(set_savec){
2341 tlp->tl_savec.s = NULL;
2342 tlp->tl_savec.l = 0;
2344 f = a_TTY_VF_NONE;
2345 rv = 0;
2346 goto jleave;
2349 # ifdef HAVE_HISTORY
2350 static ui32_t
2351 a_tty__khist_shared(struct a_tty_line *tlp, struct a_tty_hist *thp){
2352 ui32_t f, rv;
2353 NYD2_ENTER;
2355 if(n_LIKELY((tlp->tl_hist = thp) != NULL)){
2356 tlp->tl_defc.s = savestrbuf(thp->th_dat, thp->th_len);
2357 rv = tlp->tl_defc.l = thp->th_len;
2358 f = (tlp->tl_count > 0) ? a_TTY_VF_MOD_DIRTY : a_TTY_VF_NONE;
2359 tlp->tl_count = tlp->tl_cursor = 0;
2360 }else{
2361 f = a_TTY_VF_BELL;
2362 rv = UI32_MAX;
2365 tlp->tl_vi_flags |= f;
2366 NYD2_LEAVE;
2367 return rv;
2370 static ui32_t
2371 a_tty_khist(struct a_tty_line *tlp, bool_t fwd){
2372 struct a_tty_hist *thp;
2373 ui32_t rv;
2374 NYD2_ENTER;
2376 /* If we're not in history mode yet, save line content;
2377 * also, disallow forward search, then, and, of course, bail unless we
2378 * do have any history at all */
2379 if((thp = tlp->tl_hist) == NULL){
2380 if(fwd)
2381 goto jleave;
2382 if((thp = a_tty.tg_hist) == NULL)
2383 goto jleave;
2384 a_tty_cell2save(tlp);
2385 goto jleave;
2388 thp = fwd ? thp->th_younger : thp->th_older;
2389 jleave:
2390 rv = a_tty__khist_shared(tlp, thp);
2391 NYD2_LEAVE;
2392 return rv;
2395 static ui32_t
2396 a_tty_khist_search(struct a_tty_line *tlp, bool_t fwd){
2397 struct str orig_savec;
2398 struct a_tty_hist *thp;
2399 ui32_t rv;
2400 NYD2_ENTER;
2402 thp = NULL;
2404 /* We cannot complete an empty line */
2405 if(n_UNLIKELY(tlp->tl_count == 0)){
2406 /* XXX The upcoming hard reset would restore a set savec buffer,
2407 * XXX so forcefully reset that. A cleaner solution would be to
2408 * XXX reset it whenever a restore is no longer desired */
2409 tlp->tl_savec.s = NULL;
2410 tlp->tl_savec.l = 0;
2411 goto jleave;
2414 if((thp = tlp->tl_hist) == NULL){
2415 if((thp = a_tty.tg_hist) == NULL)
2416 goto jleave;
2417 /* We don't support wraparound, searching forward must always step */
2418 if(fwd)
2419 thp = thp->th_younger;
2420 orig_savec.s = NULL;
2421 orig_savec.l = 0; /* silence CC */
2422 }else if((thp = (fwd ? thp->th_younger : thp->th_older)) == NULL)
2423 goto jleave;
2424 else
2425 orig_savec = tlp->tl_savec;
2427 if(orig_savec.s == NULL)
2428 a_tty_cell2save(tlp);
2430 for(; thp != NULL; thp = (fwd ? thp->th_younger : thp->th_older))
2431 if(is_prefix(tlp->tl_savec.s, thp->th_dat))
2432 break;
2434 if(orig_savec.s != NULL)
2435 tlp->tl_savec = orig_savec;
2436 jleave:
2437 rv = a_tty__khist_shared(tlp, thp);
2438 NYD2_LEAVE;
2439 return rv;
2441 # endif /* HAVE_HISTORY */
2443 static enum a_tty_fun_status
2444 a_tty_fun(struct a_tty_line *tlp, enum a_tty_bind_flags tbf, size_t *len){
2445 enum a_tty_fun_status rv;
2446 NYD2_ENTER;
2448 rv = a_TTY_FUN_STATUS_OK;
2449 # undef a_X
2450 # define a_X(N) a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## N)
2451 switch(a_TTY_BIND_FUN_REDUCE(tbf)){
2452 case a_X(BELL):
2453 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2454 break;
2455 case a_X(GO_BWD):
2456 a_tty_kleft(tlp);
2457 break;
2458 case a_X(GO_FWD):
2459 a_tty_kright(tlp);
2460 break;
2461 case a_X(GO_WORD_BWD):
2462 a_tty_kgow(tlp, -1);
2463 break;
2464 case a_X(GO_WORD_FWD):
2465 a_tty_kgow(tlp, +1);
2466 break;
2467 case a_X(GO_HOME):
2468 a_tty_khome(tlp, TRU1);
2469 break;
2470 case a_X(GO_END):
2471 a_tty_kend(tlp);
2472 break;
2473 case a_X(DEL_BWD):
2474 a_tty_kbs(tlp);
2475 break;
2476 case a_X(DEL_FWD):
2477 if(a_tty_kdel(tlp) < 0)
2478 rv = a_TTY_FUN_STATUS_END;
2479 break;
2480 case a_X(SNARF_WORD_BWD):
2481 a_tty_ksnarfw(tlp, FAL0);
2482 break;
2483 case a_X(SNARF_WORD_FWD):
2484 a_tty_ksnarfw(tlp, TRU1);
2485 break;
2486 case a_X(SNARF_END):
2487 a_tty_ksnarf(tlp, FAL0, TRU1);
2488 break;
2489 case a_X(SNARF_LINE):
2490 a_tty_ksnarf(tlp, TRU1, (tlp->tl_count == 0));
2491 break;
2493 case a_X(HIST_FWD):
2494 # ifdef HAVE_HISTORY
2495 if(tlp->tl_hist != NULL){
2496 bool_t isfwd = TRU1;
2498 if(0){
2499 # endif
2500 /* FALLTHRU */
2501 case a_X(HIST_BWD):
2502 # ifdef HAVE_HISTORY
2503 isfwd = FAL0;
2505 if((*len = a_tty_khist(tlp, isfwd)) != UI32_MAX){
2506 rv = a_TTY_FUN_STATUS_RESTART;
2507 break;
2509 goto jreset;
2510 # endif
2512 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2513 break;
2515 case a_X(HIST_SRCH_FWD):{
2516 # ifdef HAVE_HISTORY
2517 bool_t isfwd = TRU1;
2519 if(0){
2520 # endif
2521 /* FALLTHRU */
2522 case a_X(HIST_SRCH_BWD):
2523 # ifdef HAVE_HISTORY
2524 isfwd = FAL0;
2526 if((*len = a_tty_khist_search(tlp, isfwd)) != UI32_MAX){
2527 rv = a_TTY_FUN_STATUS_RESTART;
2528 break;
2530 goto jreset;
2531 # else
2532 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2533 # endif
2534 } break;
2536 case a_X(REPAINT):
2537 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2538 break;
2539 case a_X(QUOTE_RNDTRIP):
2540 tlp->tl_quote_rndtrip = !tlp->tl_quote_rndtrip;
2541 break;
2542 case a_X(PROMPT_CHAR):{
2543 wchar_t wc;
2545 if((wc = a_tty_vinuni(tlp)) > 0)
2546 a_tty_kother(tlp, wc);
2547 } break;
2548 case a_X(COMPLETE):
2549 if((*len = a_tty_kht(tlp)) > 0)
2550 rv = a_TTY_FUN_STATUS_RESTART;
2551 break;
2553 case a_X(PASTE):
2554 if(tlp->tl_pastebuf.l > 0)
2555 *len = (tlp->tl_defc = tlp->tl_pastebuf).l;
2556 else
2557 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2558 break;
2561 case a_X(CANCEL):
2562 /* Normally this just causes a restart and thus resets the state
2563 * machine */
2564 if(tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2566 # ifdef HAVE_KEY_BINDINGS
2567 tlp->tl_bind_takeover = '\0';
2568 # endif
2569 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2570 rv = a_TTY_FUN_STATUS_RESTART;
2571 break;
2573 case a_X(RESET):
2574 if(tlp->tl_count == 0 && tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2575 # ifdef HAVE_KEY_BINDINGS
2576 tlp->tl_bind_takeover = '\0';
2577 # endif
2578 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY | a_TTY_VF_BELL;
2579 break;
2580 }else if(0){
2581 case a_X(FULLRESET):
2582 tlp->tl_savec.s = tlp->tl_defc.s = NULL;
2583 tlp->tl_savec.l = tlp->tl_defc.l = 0;
2584 tlp->tl_defc_cursor_byte = 0;
2585 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2587 jreset:
2588 # ifdef HAVE_KEY_BINDINGS
2589 tlp->tl_bind_takeover = '\0';
2590 # endif
2591 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2592 tlp->tl_cursor = tlp->tl_count = 0;
2593 # ifdef HAVE_HISTORY
2594 tlp->tl_hist = NULL;
2595 # endif
2596 if((*len = tlp->tl_savec.l) != 0){
2597 tlp->tl_defc = tlp->tl_savec;
2598 tlp->tl_savec.s = NULL;
2599 tlp->tl_savec.l = 0;
2600 }else
2601 *len = tlp->tl_defc.l;
2602 rv = a_TTY_FUN_STATUS_RESTART;
2603 break;
2605 default:
2606 case a_X(COMMIT):
2607 rv = a_TTY_FUN_STATUS_COMMIT;
2608 break;
2610 # undef a_X
2612 NYD2_LEAVE;
2613 return rv;
2616 static ssize_t
2617 a_tty_readline(struct a_tty_line *tlp, size_t len n_MEMORY_DEBUG_ARGS){
2618 /* We want to save code, yet we may have to incorporate a lines'
2619 * default content and / or default input to switch back to after some
2620 * history movement; let "len > 0" mean "have to display some data
2621 * buffer" -> a_BUFMODE, and only otherwise read(2) it */
2622 mbstate_t ps[2];
2623 char cbuf_base[MB_LEN_MAX * 2], *cbuf, *cbufp;
2624 ssize_t rv;
2625 struct a_tty_bind_tree *tbtp;
2626 wchar_t wc;
2627 enum a_tty_bind_flags tbf;
2628 enum {a_NONE, a_WAS_HERE = 1<<0, a_BUFMODE = 1<<1, a_MAYBEFUN = 1<<2,
2629 a_TIMEOUT = 1<<3, a_TIMEOUT_EXPIRED = 1<<4,
2630 a_TIMEOUT_MASK = a_TIMEOUT | a_TIMEOUT_EXPIRED,
2631 a_READ_LOOP_MASK = ~(a_WAS_HERE | a_MAYBEFUN | a_TIMEOUT_MASK)
2632 } flags;
2633 NYD_ENTER;
2635 n_UNINIT(rv, 0);
2636 # ifdef HAVE_KEY_BINDINGS
2637 assert(tlp->tl_bind_takeover == '\0');
2638 # endif
2639 jrestart:
2640 memset(ps, 0, sizeof ps);
2641 flags = a_NONE;
2642 tbf = 0;
2643 tlp->tl_vi_flags |= a_TTY_VF_REFRESH | a_TTY_VF_SYNC;
2645 jinput_loop:
2646 for(;;){
2647 if(len != 0)
2648 flags |= a_BUFMODE;
2650 /* Ensure we have valid pointers, and room for grow */
2651 a_tty_check_grow(tlp, ((flags & a_BUFMODE) ? (ui32_t)len : 1)
2652 n_MEMORY_DEBUG_ARGSCALL);
2654 /* Handle visual state flags, except in buffer mode */
2655 if(!(flags & a_BUFMODE) && (tlp->tl_vi_flags & a_TTY_VF_ALL_MASK))
2656 if(!a_tty_vi_refresh(tlp)){
2657 rv = -1;
2658 goto jleave;
2661 /* Ready for messing around.
2662 * Normal read(2)? Else buffer mode: speed this one up */
2663 if(!(flags & a_BUFMODE)){
2664 cbufp =
2665 cbuf = cbuf_base;
2666 }else{
2667 assert(tlp->tl_defc.l > 0 && tlp->tl_defc.s != NULL);
2668 assert(tlp->tl_defc.l >= len);
2669 cbufp =
2670 cbuf = tlp->tl_defc.s + (tlp->tl_defc.l - len);
2671 cbufp += len;
2674 /* Read in the next complete multibyte character */
2675 /* C99 */{
2676 # ifdef HAVE_KEY_BINDINGS
2677 struct a_tty_bind_tree *xtbtp;
2678 struct inseq{
2679 struct inseq *last;
2680 struct inseq *next;
2681 struct a_tty_bind_tree *tbtp;
2682 } *isp_head, *isp;
2684 isp_head = isp = NULL;
2685 # endif
2687 for(flags &= a_READ_LOOP_MASK;;){
2688 # ifdef HAVE_KEY_BINDINGS
2689 if(!(flags & a_BUFMODE) && tlp->tl_bind_takeover != '\0'){
2690 wc = tlp->tl_bind_takeover;
2691 tlp->tl_bind_takeover = '\0';
2692 }else
2693 # endif
2695 if(!(flags & a_BUFMODE)){
2696 /* Let me at least once dream of iomon(itor), timer with
2697 * one-shot, enwrapped with key_event and key_sequence_event,
2698 * all driven by an event_loop */
2699 /* TODO v15 Until we have SysV signal handling all through we
2700 * TODO need to temporarily adjust our BSD signal handler with
2701 * TODO a SysV one, here */
2702 n_sighdl_t otstp, ottin, ottou;
2704 otstp = n_signal(SIGTSTP, &n_tty_signal);
2705 ottin = n_signal(SIGTTIN, &n_tty_signal);
2706 ottou = n_signal(SIGTTOU, &n_tty_signal);
2707 # ifdef HAVE_KEY_BINDINGS
2708 flags &= ~a_TIMEOUT_MASK;
2709 if(isp != NULL && (tbtp = isp->tbtp)->tbt_isseq &&
2710 !tbtp->tbt_isseq_trail){
2711 a_tty_term_rawmode_timeout(tlp, TRU1);
2712 flags |= a_TIMEOUT;
2714 # endif
2716 while((rv = read(STDIN_FILENO, cbufp, 1)) < 1){
2717 if(rv == -1){
2718 if(errno == EINTR){
2719 if((tlp->tl_vi_flags & a_TTY_VF_MOD_DIRTY) &&
2720 !a_tty_vi_refresh(tlp))
2721 break;
2722 continue;
2724 break;
2727 # ifdef HAVE_KEY_BINDINGS
2728 /* Timeout expiration */
2729 if(rv == 0){
2730 assert(flags & a_TIMEOUT);
2731 assert(isp != NULL);
2732 a_tty_term_rawmode_timeout(tlp, FAL0);
2734 /* Something "atomic" broke. Maybe the current one can
2735 * also be terminated already, by itself? xxx really? */
2736 if((tbtp = isp->tbtp)->tbt_bind != NULL){
2737 tlp->tl_bind_takeover = wc;
2738 goto jhave_bind;
2741 /* Or, maybe there is a second path without a timeout;
2742 * this should be covered by .tbt_isseq_trail, but then
2743 * again a single-layer implementation cannot "know" */
2744 for(xtbtp = tbtp; (xtbtp = xtbtp->tbt_sibling) != NULL;)
2745 if(xtbtp->tbt_char == tbtp->tbt_char){
2746 assert(!xtbtp->tbt_isseq);
2747 break;
2749 /* Lay down on read(2)? */
2750 if(xtbtp != NULL)
2751 continue;
2752 goto jtake_over;
2754 # endif /* HAVE_KEY_BINDINGS */
2757 # ifdef HAVE_KEY_BINDINGS
2758 if(flags & a_TIMEOUT)
2759 a_tty_term_rawmode_timeout(tlp, FAL0);
2760 # endif
2761 safe_signal(SIGTSTP, otstp);
2762 safe_signal(SIGTTIN, ottin);
2763 safe_signal(SIGTTOU, ottou);
2764 if(rv < 0)
2765 goto jleave;
2767 ++cbufp;
2770 rv = (ssize_t)mbrtowc(&wc, cbuf, PTR2SIZE(cbufp - cbuf), &ps[0]);
2771 if(rv <= 0){
2772 /* Any error during buffer mode can only result in a hard
2773 * reset; Otherwise, if it's a hard error, or if too many
2774 * redundant shift sequences overflow our buffer: perform
2775 * hard reset */
2776 if((flags & a_BUFMODE) || rv == -1 ||
2777 sizeof cbuf_base == PTR2SIZE(cbufp - cbuf)){
2778 a_tty_fun(tlp, a_TTY_BIND_FUN_FULLRESET, &len);
2779 goto jrestart;
2781 /* Otherwise, due to the way we deal with the buffer, we need
2782 * to restore the mbstate_t from before this conversion */
2783 ps[0] = ps[1];
2784 continue;
2786 cbufp = cbuf;
2787 ps[1] = ps[0];
2790 /* Normal read(2)ing is subject to detection of key-bindings */
2791 # ifdef HAVE_KEY_BINDINGS
2792 if(!(flags & a_BUFMODE)){
2793 /* Check for special bypass functions before we try to embed
2794 * this character into the tree */
2795 if(n_uasciichar(wc)){
2796 char c;
2797 char const *cp;
2799 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_prompt_char)[0];
2800 *cp != '\0'; ++cp){
2801 if(c == *cp){
2802 wc = a_tty_vinuni(tlp);
2803 break;
2806 if(wc == '\0'){
2807 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2808 goto jinput_loop;
2811 if(n_uasciichar(wc))
2812 flags |= a_MAYBEFUN;
2813 else
2814 flags &= ~a_MAYBEFUN;
2816 /* Search for this character in the bind tree */
2817 tbtp = (isp != NULL) ? isp->tbtp->tbt_childs
2818 : (*tlp->tl_bind_tree_hmap)[wc % HSHSIZE];
2819 for(; tbtp != NULL; tbtp = tbtp->tbt_sibling){
2820 if(tbtp->tbt_char == wc){
2821 struct inseq *nisp;
2823 /* If this one cannot continue we're likely finished! */
2824 if(tbtp->tbt_childs == NULL){
2825 assert(tbtp->tbt_bind != NULL);
2826 tbf = tbtp->tbt_bind->tbc_flags;
2827 goto jmle_fun;
2830 /* This needs to read more characters */
2831 nisp = salloc(sizeof *nisp);
2832 if((nisp->last = isp) == NULL)
2833 isp_head = nisp;
2834 else
2835 isp->next = nisp;
2836 nisp->next = NULL;
2837 nisp->tbtp = tbtp;
2838 isp = nisp;
2839 flags &= ~a_WAS_HERE;
2840 break;
2843 if(tbtp != NULL)
2844 continue;
2846 /* Was there a binding active, but couldn't be continued? */
2847 if(isp != NULL){
2848 /* A binding had a timeout, it didn't expire, but we saw
2849 * something non-expected. Something "atomic" broke.
2850 * Maybe there is a second path without a timeout, that
2851 * continues like we've seen it. I.e., it may just have been
2852 * the user, typing two fast. We definitely want to allow
2853 * bindings like \e,d etc. to succeed: users are so used to
2854 * them that a timeout cannot be the mechanism to catch up!
2855 * A single-layer implementation cannot "know" */
2856 if((tbtp = isp->tbtp)->tbt_isseq && (isp->last == NULL ||
2857 !(xtbtp = isp->last->tbtp)->tbt_isseq ||
2858 xtbtp->tbt_isseq_trail)){
2859 for(xtbtp = (tbtp = isp->tbtp);
2860 (xtbtp = xtbtp->tbt_sibling) != NULL;)
2861 if(xtbtp->tbt_char == tbtp->tbt_char){
2862 assert(!xtbtp->tbt_isseq);
2863 break;
2865 if(xtbtp != NULL){
2866 isp->tbtp = xtbtp;
2867 tlp->tl_bind_takeover = wc;
2868 continue;
2872 /* Check for CANCEL shortcut now */
2873 if(flags & a_MAYBEFUN){
2874 char c;
2875 char const *cp;
2877 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_cancel)[0];
2878 *cp != '\0'; ++cp)
2879 if(c == *cp){
2880 tbf = a_TTY_BIND_FUN_INTERNAL |a_TTY_BIND_FUN_CANCEL;
2881 goto jmle_fun;
2885 /* So: maybe the current sequence can be terminated here? */
2886 if((tbtp = isp->tbtp)->tbt_bind != NULL){
2887 jhave_bind:
2888 tbf = tbtp->tbt_bind->tbc_flags;
2889 jmle_fun:
2890 if(tbf & a_TTY_BIND_FUN_INTERNAL){
2891 switch(a_tty_fun(tlp, tbf, &len)){
2892 case a_TTY_FUN_STATUS_OK:
2893 goto jinput_loop;
2894 case a_TTY_FUN_STATUS_COMMIT:
2895 goto jdone;
2896 case a_TTY_FUN_STATUS_RESTART:
2897 goto jrestart;
2898 case a_TTY_FUN_STATUS_END:
2899 goto jleave;
2901 assert(0);
2902 }else if(tbtp->tbt_bind->tbc_flags & a_TTY_BIND_NOCOMMIT){
2903 struct a_tty_bind_ctx *tbcp;
2905 tbcp = tbtp->tbt_bind;
2906 memcpy(tlp->tl_defc.s = salloc(
2907 (tlp->tl_defc.l = len = tbcp->tbc_exp_len) +1),
2908 tbcp->tbc_exp, tbcp->tbc_exp_len +1);
2909 goto jrestart;
2910 }else{
2911 tlp->tl_reenter_after_cmd = tbtp->tbt_bind->tbc_exp;
2912 goto jdone;
2917 /* Otherwise take over all chars "as is" */
2918 jtake_over:
2919 for(; isp_head != NULL; isp_head = isp_head->next)
2920 if(a_tty_kother(tlp, isp_head->tbtp->tbt_char)){
2921 /* FIXME */
2923 /* And the current one too */
2924 goto jkother;
2926 # endif /* HAVE_KEY_BINDINGS */
2928 if((flags & a_BUFMODE) && (len -= (size_t)rv) == 0){
2929 /* Buffer mode completed */
2930 tlp->tl_defc.s = NULL;
2931 tlp->tl_defc.l = 0;
2932 flags &= ~a_BUFMODE;
2934 break;
2937 # ifndef HAVE_KEY_BINDINGS
2938 /* Don't interpret control bytes during buffer mode.
2939 * Otherwise, if it's a control byte check whether it is a MLE
2940 * function. Remarks: initially a complete duplicate to be able to
2941 * switch(), later converted to simply iterate over (an #ifdef'd
2942 * subset of) the MLE default_tuple table in order to have "a SPOF" */
2943 if(cbuf == cbuf_base && n_uasciichar(wc) && cntrlchar((char)wc)){
2944 struct a_tty_bind_default_tuple const *tbdtp;
2945 char c;
2947 for(c = (char)wc ^ 0x40, tbdtp = a_tty_bind_default_tuples;
2948 PTRCMP(tbdtp, <, &a_tty_bind_default_tuples[
2949 n_NELEM(a_tty_bind_default_tuples)]);
2950 ++tbdtp){
2951 /* Assert default_tuple table is properly subset'ed */
2952 assert(tbdtp->tbdt_iskey);
2953 if(tbdtp->tbdt_ckey == c){
2954 if(tbdtp->tbdt_exp[0] == '\0'){
2955 enum a_tty_bind_flags tbf;
2957 tbf = a_TTY_BIND_FUN_EXPAND((ui8_t)tbdtp->tbdt_exp[1]);
2958 switch(a_tty_fun(tlp, tbf, &len)){
2959 case a_TTY_FUN_STATUS_OK:
2960 goto jinput_loop;
2961 case a_TTY_FUN_STATUS_COMMIT:
2962 goto jdone;
2963 case a_TTY_FUN_STATUS_RESTART:
2964 goto jrestart;
2965 case a_TTY_FUN_STATUS_END:
2966 goto jleave;
2968 assert(0);
2969 }else{
2970 tlp->tl_reenter_after_cmd = tbdtp->tbdt_exp;
2971 goto jdone;
2976 # endif /* !HAVE_KEY_BINDINGS */
2978 # ifdef HAVE_KEY_BINDINGS
2979 jkother:
2980 # endif
2981 if(a_tty_kother(tlp, wc)){
2982 /* Don't clear the history during buffer mode.. */
2983 # ifdef HAVE_HISTORY
2984 if(!(flags & a_BUFMODE) && cbuf == cbuf_base)
2985 tlp->tl_hist = NULL;
2986 # endif
2991 /* We have a completed input line, convert the struct cell data to its
2992 * plain character equivalent */
2993 jdone:
2994 rv = a_tty_cell2dat(tlp);
2995 jleave:
2996 putchar('\n');
2997 fflush(stdout);
2998 NYD_LEAVE;
2999 return rv;
3002 # ifdef HAVE_KEY_BINDINGS
3003 static enum n_lexinput_flags
3004 a_tty_bind_ctx_find(char const *name){
3005 enum n_lexinput_flags rv;
3006 struct a_tty_bind_ctx_map const *tbcmp;
3007 NYD2_ENTER;
3009 tbcmp = a_tty_bind_ctx_maps;
3010 do if(!asccasecmp(tbcmp->tbcm_name, name)){
3011 rv = tbcmp->tbcm_ctx;
3012 goto jleave;
3013 }while(PTRCMP(++tbcmp, <,
3014 &a_tty_bind_ctx_maps[n_NELEM(a_tty_bind_ctx_maps)]));
3016 rv = (enum n_lexinput_flags)-1;
3017 jleave:
3018 NYD2_LEAVE;
3019 return rv;
3022 static bool_t
3023 a_tty_bind_create(struct a_tty_bind_parse_ctx *tbpcp, bool_t replace){
3024 struct a_tty_bind_ctx *tbcp;
3025 bool_t rv;
3026 NYD2_ENTER;
3028 rv = FAL0;
3030 if(!a_tty_bind_parse(TRU1, tbpcp))
3031 goto jleave;
3033 /* Since we use a single buffer for it all, need to replace as such */
3034 if(tbpcp->tbpc_tbcp != NULL){
3035 if(!replace)
3036 goto jleave;
3037 a_tty_bind_del(tbpcp);
3038 }else if(a_tty.tg_bind_cnt == UI32_MAX){
3039 n_err(_("`bind': maximum number of bindings already established\n"));
3040 goto jleave;
3043 /* C99 */{
3044 size_t i, j;
3046 tbcp = smalloc(sizeof(*tbcp) -
3047 n_VFIELD_SIZEOF(struct a_tty_bind_ctx, tbc__buf) +
3048 tbpcp->tbpc_seq_len + tbpcp->tbpc_exp.l +
3049 n_MAX(sizeof(si32_t), sizeof(wc_t)) + tbpcp->tbpc_cnv_len +3);
3050 if(tbpcp->tbpc_ltbcp != NULL){
3051 tbcp->tbc_next = tbpcp->tbpc_ltbcp->tbc_next;
3052 tbpcp->tbpc_ltbcp->tbc_next = tbcp;
3053 }else{
3054 enum n_lexinput_flags lif = tbpcp->tbpc_flags & n__LEXINPUT_CTX_MASK;
3056 tbcp->tbc_next = a_tty.tg_bind[lif];
3057 a_tty.tg_bind[lif] = tbcp;
3059 memcpy(tbcp->tbc_seq = &tbcp->tbc__buf[0],
3060 tbpcp->tbpc_seq, i = (tbcp->tbc_seq_len = tbpcp->tbpc_seq_len) +1);
3061 memcpy(tbcp->tbc_exp = &tbcp->tbc__buf[i],
3062 tbpcp->tbpc_exp.s, j = (tbcp->tbc_exp_len = tbpcp->tbpc_exp.l) +1);
3063 i += j;
3064 i = (i + tbpcp->tbpc_cnv_align_mask) & ~tbpcp->tbpc_cnv_align_mask;
3065 memcpy(tbcp->tbc_cnv = &tbcp->tbc__buf[i],
3066 tbpcp->tbpc_cnv, (tbcp->tbc_cnv_len = tbpcp->tbpc_cnv_len) +1);
3067 tbcp->tbc_flags = tbpcp->tbpc_flags;
3070 /* Directly resolve any termcap(5) symbol if we are already setup */
3071 if((pstate & PS_STARTED) &&
3072 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
3073 a_TTY_BIND_RESOLVE)
3074 a_tty_bind_resolve(tbcp);
3076 ++a_tty.tg_bind_cnt;
3077 /* If this binding is usable invalidate the key input lookup trees */
3078 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3079 a_tty.tg_bind_isdirty = TRU1;
3080 rv = TRU1;
3081 jleave:
3082 NYD2_LEAVE;
3083 return rv;
3086 static bool_t
3087 a_tty_bind_parse(bool_t isbindcmd, struct a_tty_bind_parse_ctx *tbpcp){
3088 enum{a_TRUE_RV = a_TTY__BIND_LAST<<1};
3090 struct n_visual_info_ctx vic;
3091 struct str shin_save, shin;
3092 struct n_string shou, *shoup;
3093 size_t i;
3094 struct kse{
3095 struct kse *next;
3096 char *seq_dat;
3097 wc_t *cnv_dat;
3098 ui32_t seq_len;
3099 ui32_t cnv_len; /* High bit set if a termap to be resolved */
3100 ui32_t calc_cnv_len; /* Ditto, but aligned etc. */
3101 ui8_t kse__dummy[4];
3102 } *head, *tail;
3103 ui32_t f;
3104 NYD2_ENTER;
3105 n_LCTA(UICMP(64, a_TRUE_RV, <, UI32_MAX),
3106 "Flag bits excess storage datatype");
3108 f = n_LEXINPUT_NONE;
3109 shoup = n_string_creat_auto(&shou);
3110 head = tail = NULL;
3112 /* Parse the key-sequence */
3113 for(shin.s = n_UNCONST(tbpcp->tbpc_in_seq), shin.l = UIZ_MAX;;){
3114 struct kse *ep;
3115 enum n_shexp_state shs;
3117 shin_save = shin;
3118 shs = n_shexp_parse_token(shoup, &shin,
3119 n_SHEXP_PARSE_TRUNC | n_SHEXP_PARSE_TRIMSPACE |
3120 n_SHEXP_PARSE_IGNORE_EMPTY | n_SHEXP_PARSE_IFS_IS_COMMA);
3121 if(shs & n_SHEXP_STATE_ERR_UNICODE){
3122 f |= a_TTY_BIND_DEFUNCT;
3123 if(isbindcmd && (options & OPT_D_V))
3124 n_err(_("`%s': \\uNICODE not available in locale: %s\n"),
3125 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3127 if((shs & n_SHEXP_STATE_ERR_MASK) & ~n_SHEXP_STATE_ERR_UNICODE){
3128 n_err(_("`%s': failed to parse key-sequence: %s\n"),
3129 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3130 goto jleave;
3132 if((shs & (n_SHEXP_STATE_OUTPUT | n_SHEXP_STATE_STOP)) ==
3133 n_SHEXP_STATE_STOP)
3134 break;
3136 ep = salloc(sizeof *ep);
3137 if(head == NULL)
3138 head = ep;
3139 else
3140 tail->next = ep;
3141 tail = ep;
3142 ep->next = NULL;
3143 if(!(shs & n_SHEXP_STATE_ERR_UNICODE)){
3144 i = strlen(ep->seq_dat = n_shexp_quote_cp(n_string_cp(shoup), TRU1));
3145 if(i >= SI32_MAX - 1)
3146 goto jelen;
3147 ep->seq_len = (ui32_t)i;
3148 }else{
3149 /* Otherwise use the original buffer, _we_ can only quote it the wrong
3150 * way (e.g., an initial $'\u3a' becomes '\u3a'), _then_ */
3151 if((i = shin_save.l - shin.l) >= SI32_MAX - 1)
3152 goto jelen;
3153 ep->seq_len = (ui32_t)i;
3154 ep->seq_dat = savestrbuf(shin_save.s, i);
3157 memset(&vic, 0, sizeof vic);
3158 vic.vic_inlen = shoup->s_len;
3159 vic.vic_indat = shoup->s_dat;
3160 if(!n_visual_info(&vic,
3161 n_VISUAL_INFO_WOUT_CREATE | n_VISUAL_INFO_WOUT_SALLOC)){
3162 n_err(_("`%s': key-sequence seems to contain invalid "
3163 "characters: %s: %s\n"),
3164 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
3165 f |= a_TTY_BIND_DEFUNCT;
3166 goto jleave;
3167 }else if(vic.vic_woulen == 0 ||
3168 vic.vic_woulen >= (SI32_MAX - 2) / sizeof(wc_t)){
3169 jelen:
3170 n_err(_("`%s': length of key-sequence unsupported: %s: %s\n"),
3171 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
3172 f |= a_TTY_BIND_DEFUNCT;
3173 goto jleave;
3175 ep->cnv_dat = vic.vic_woudat;
3176 ep->cnv_len = (ui32_t)vic.vic_woulen;
3178 /* A termcap(5)/terminfo(5) identifier? */
3179 if(ep->cnv_len > 1 && ep->cnv_dat[0] == ':'){
3180 i = --ep->cnv_len, ++ep->cnv_dat;
3181 # ifndef HAVE_TERMCAP
3182 if(options & OPT_D_V)
3183 n_err(_("`%s': no termcap(5)/terminfo(5) support: %s: %s\n"),
3184 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3185 f |= a_TTY_BIND_DEFUNCT;
3186 # endif
3187 if(i > a_TTY_BIND_CAPNAME_MAX){
3188 n_err(_("`%s': termcap(5)/terminfo(5) name too long: %s: %s\n"),
3189 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3190 f |= a_TTY_BIND_DEFUNCT;
3192 while(i > 0)
3193 /* (We store it as char[]) */
3194 if((ui32_t)ep->cnv_dat[--i] & ~0x7Fu){
3195 n_err(_("`%s': invalid termcap(5)/terminfo(5) name content: "
3196 "%s: %s\n"),
3197 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3198 f |= a_TTY_BIND_DEFUNCT;
3199 break;
3201 ep->cnv_len |= SI32_MIN; /* Needs resolve */
3202 f |= a_TTY_BIND_RESOLVE;
3205 if(shs & n_SHEXP_STATE_STOP)
3206 break;
3209 if(head == NULL){
3210 jeempty:
3211 n_err(_("`%s': effectively empty key-sequence: %s\n"),
3212 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3213 goto jleave;
3216 if(isbindcmd) /* (Or always, just "1st time init") */
3217 tbpcp->tbpc_cnv_align_mask = n_MAX(sizeof(si32_t), sizeof(wc_t)) - 1;
3219 /* C99 */{
3220 struct a_tty_bind_ctx *ltbcp, *tbcp;
3221 char *cpbase, *cp, *cnv;
3222 size_t sl, cl;
3224 /* Unite the parsed sequence(s) into single string representations */
3225 for(sl = cl = 0, tail = head; tail != NULL; tail = tail->next){
3226 sl += tail->seq_len + 1;
3228 if(!isbindcmd)
3229 continue;
3231 /* Preserve room for terminal capabilities to be resolved.
3232 * Above we have ensured the buffer will fit in these calculations */
3233 if((i = tail->cnv_len) & SI32_MIN){
3234 /* For now
3235 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[]+NUL;}
3236 * later
3237 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3238 n_LCTAV(n_ISPOW2(a_TTY_BIND_CAPEXP_ROUNDUP));
3239 n_LCTA(a_TTY_BIND_CAPEXP_ROUNDUP >= sizeof(wc_t),
3240 "Aligning on this constant doesn't properly align wc_t");
3241 i &= SI32_MAX;
3242 i *= sizeof(wc_t);
3243 i += sizeof(si32_t);
3244 if(i < a_TTY_BIND_CAPEXP_ROUNDUP)
3245 i = (i + (a_TTY_BIND_CAPEXP_ROUNDUP - 1)) &
3246 ~(a_TTY_BIND_CAPEXP_ROUNDUP - 1);
3247 }else
3248 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3249 i *= sizeof(wc_t);
3250 i += sizeof(si32_t) + sizeof(wc_t); /* (buf_len_iscap, NUL) */
3251 cl += i;
3252 if(tail->cnv_len & SI32_MIN){
3253 tail->cnv_len &= SI32_MAX;
3254 i |= SI32_MIN;
3256 tail->calc_cnv_len = (ui32_t)i;
3258 --sl;
3260 tbpcp->tbpc_seq_len = sl;
3261 tbpcp->tbpc_cnv_len = cl;
3262 /* C99 */{
3263 size_t j;
3265 j = i = sl + 1; /* Room for comma separator */
3266 if(isbindcmd){
3267 i = (i + tbpcp->tbpc_cnv_align_mask) & ~tbpcp->tbpc_cnv_align_mask;
3268 j = i;
3269 i += cl;
3271 tbpcp->tbpc_seq = cp = cpbase = salloc(i);
3272 tbpcp->tbpc_cnv = cnv = &cpbase[j];
3275 for(tail = head; tail != NULL; tail = tail->next){
3276 memcpy(cp, tail->seq_dat, tail->seq_len);
3277 cp += tail->seq_len;
3278 *cp++ = ',';
3280 if(isbindcmd){
3281 char * const save_cnv = cnv;
3283 n_UNALIGN(si32_t*,cnv)[0] = (si32_t)(i = tail->calc_cnv_len);
3284 cnv += sizeof(si32_t);
3285 if(i & SI32_MIN){
3286 /* For now
3287 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];}
3288 * later
3289 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[];} */
3290 n_UNALIGN(si32_t*,cnv)[0] = tail->cnv_len;
3291 cnv += sizeof(si32_t);
3293 i = tail->cnv_len * sizeof(wc_t);
3294 memcpy(cnv, tail->cnv_dat, i);
3295 cnv += i;
3296 *n_UNALIGN(wc_t*,cnv) = '\0';
3298 cnv = save_cnv + (tail->calc_cnv_len & SI32_MAX);
3301 *--cp = '\0';
3303 /* Search for a yet existing identical mapping */
3304 for(ltbcp = NULL, tbcp = a_tty.tg_bind[tbpcp->tbpc_flags]; tbcp != NULL;
3305 ltbcp = tbcp, tbcp = tbcp->tbc_next)
3306 if(tbcp->tbc_seq_len == sl && !memcmp(tbcp->tbc_seq, cpbase, sl)){
3307 tbpcp->tbpc_tbcp = tbcp;
3308 break;
3310 tbpcp->tbpc_ltbcp = ltbcp;
3311 tbpcp->tbpc_flags |= (f & a_TTY__BIND_MASK);
3314 /* Create single string expansion if so desired */
3315 if(isbindcmd){
3316 char *exp;
3318 exp = tbpcp->tbpc_exp.s;
3320 i = tbpcp->tbpc_exp.l;
3321 if(i > 0 && exp[i - 1] == '@'){
3322 while(--i > 0){
3323 if(!blankspacechar(exp[i - 1]))
3324 break;
3326 if(i == 0)
3327 goto jeempty;
3329 exp[tbpcp->tbpc_exp.l = i] = '\0';
3330 tbpcp->tbpc_flags |= a_TTY_BIND_NOCOMMIT;
3333 /* Reverse solidus cannot be placed last in expansion to avoid (at the
3334 * time of this writing) possible problems with newline escaping.
3335 * Don't care about (un)even number thereof */
3336 if(i > 0 && exp[i - 1] == '\\'){
3337 n_err(_("`%s': reverse solidus cannot be last in expansion: %s\n"),
3338 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3339 goto jleave;
3342 /* It may map to an internal MLE command! */
3343 for(i = 0; i < n_NELEM(a_tty_bind_fun_names); ++i)
3344 if(!asccasecmp(exp, a_tty_bind_fun_names[i])){
3345 tbpcp->tbpc_flags |= a_TTY_BIND_FUN_EXPAND(i) |
3346 a_TTY_BIND_FUN_INTERNAL |
3347 (head->next == NULL ? a_TTY_BIND_MLE1CNTRL : 0);
3348 if((options & OPT_D_V) && (tbpcp->tbpc_flags & a_TTY_BIND_NOCOMMIT))
3349 n_err(_("`%s': MLE commands can't be made editable via @: %s\n"),
3350 tbpcp->tbpc_cmd, exp);
3351 tbpcp->tbpc_flags &= ~a_TTY_BIND_NOCOMMIT;
3352 break;
3356 f |= a_TRUE_RV; /* TODO because we only now true and false; DEFUNCT.. */
3357 jleave:
3358 n_string_gut(shoup);
3359 NYD2_LEAVE;
3360 return (f & a_TRUE_RV) != 0;
3363 static void
3364 a_tty_bind_resolve(struct a_tty_bind_ctx *tbcp){
3365 char capname[a_TTY_BIND_CAPNAME_MAX +1];
3366 struct n_termcap_value tv;
3367 size_t len;
3368 bool_t isfirst; /* TODO For now: first char must be control! */
3369 char *cp, *next;
3370 NYD2_ENTER;
3372 n_UNINIT(next, NULL);
3373 for(cp = tbcp->tbc_cnv, isfirst = TRU1, len = tbcp->tbc_cnv_len;
3374 len > 0; isfirst = FAL0, cp = next){
3375 /* C99 */{
3376 si32_t i, j;
3378 i = n_UNALIGN(si32_t*,cp)[0];
3379 j = i & SI32_MAX;
3380 next = &cp[j];
3381 len -= j;
3382 if(i == j)
3383 continue;
3385 /* struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];} */
3386 cp += sizeof(si32_t);
3387 i = n_UNALIGN(si32_t*,cp)[0];
3388 cp += sizeof(si32_t);
3389 for(j = 0; j < i; ++j)
3390 capname[j] = n_UNALIGN(wc_t*,cp)[j];
3391 capname[j] = '\0';
3394 /* Use generic lookup mechanism if not a known query */
3395 /* C99 */{
3396 si32_t tq;
3398 tq = n_termcap_query_for_name(capname, n_TERMCAP_CAPTYPE_STRING);
3399 if(tq == -1){
3400 tv.tv_data.tvd_string = capname;
3401 tq = n__TERMCAP_QUERY_MAX1;
3404 if(tq < 0 || !n_termcap_query(tq, &tv)){
3405 if(options & OPT_D_V)
3406 n_err(_("`bind': unknown or unsupported capability: %s: %s\n"),
3407 capname, tbcp->tbc_seq);
3408 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3409 break;
3413 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3414 /* C99 */{
3415 size_t i;
3417 i = strlen(tv.tv_data.tvd_string);
3418 if(/*i > SI32_MAX ||*/ i >= PTR2SIZE(next - cp)){
3419 if(options & OPT_D_V)
3420 n_err(_("`bind': capability expansion too long: %s: %s\n"),
3421 capname, tbcp->tbc_seq);
3422 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3423 break;
3424 }else if(i == 0){
3425 if(options & OPT_D_V)
3426 n_err(_("`bind': empty capability expansion: %s: %s\n"),
3427 capname, tbcp->tbc_seq);
3428 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3429 break;
3430 }else if(isfirst && !cntrlchar(*tv.tv_data.tvd_string)){
3431 if(options & OPT_D_V)
3432 n_err(_("`bind': capability expansion doesn't start with "
3433 "control: %s: %s\n"), capname, tbcp->tbc_seq);
3434 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3435 break;
3437 n_UNALIGN(si32_t*,cp)[-1] = (si32_t)i;
3438 memcpy(cp, tv.tv_data.tvd_string, i);
3439 cp[i] = '\0';
3442 NYD2_LEAVE;
3445 static void
3446 a_tty_bind_del(struct a_tty_bind_parse_ctx *tbpcp){
3447 struct a_tty_bind_ctx *ltbcp, *tbcp;
3448 NYD2_ENTER;
3450 tbcp = tbpcp->tbpc_tbcp;
3452 if((ltbcp = tbpcp->tbpc_ltbcp) != NULL)
3453 ltbcp->tbc_next = tbcp->tbc_next;
3454 else
3455 a_tty.tg_bind[tbpcp->tbpc_flags] = tbcp->tbc_next;
3456 free(tbcp);
3458 --a_tty.tg_bind_cnt;
3459 a_tty.tg_bind_isdirty = TRU1;
3460 NYD2_LEAVE;
3463 static void
3464 a_tty_bind_tree_build(void){
3465 size_t i;
3466 NYD2_ENTER;
3468 for(i = 0; i < n__LEXINPUT_CTX_MAX1; ++i){
3469 struct a_tty_bind_ctx *tbcp;
3470 n_LCTAV(n_LEXINPUT_CTX_BASE == 0);
3472 /* Somewhat wasteful, but easier to handle: simply clone the entire
3473 * primary key onto the secondary one, then only modify it */
3474 for(tbcp = a_tty.tg_bind[n_LEXINPUT_CTX_BASE]; tbcp != NULL;
3475 tbcp = tbcp->tbc_next)
3476 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3477 a_tty__bind_tree_add(n_LEXINPUT_CTX_BASE, &a_tty.tg_bind_tree[i][0],
3478 tbcp);
3480 if(i != n_LEXINPUT_CTX_BASE)
3481 for(tbcp = a_tty.tg_bind[i]; tbcp != NULL; tbcp = tbcp->tbc_next)
3482 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3483 a_tty__bind_tree_add(i, &a_tty.tg_bind_tree[i][0], tbcp);
3486 a_tty.tg_bind_isbuild = TRU1;
3487 NYD2_LEAVE;
3490 static void
3491 a_tty_bind_tree_teardown(void){
3492 size_t i, j;
3493 NYD2_ENTER;
3495 memset(&a_tty.tg_bind_shcut_cancel[0], 0,
3496 sizeof(a_tty.tg_bind_shcut_cancel));
3497 memset(&a_tty.tg_bind_shcut_prompt_char[0], 0,
3498 sizeof(a_tty.tg_bind_shcut_prompt_char));
3500 for(i = 0; i < n__LEXINPUT_CTX_MAX1; ++i)
3501 for(j = 0; j < HSHSIZE; ++j)
3502 a_tty__bind_tree_free(a_tty.tg_bind_tree[i][j]);
3503 memset(&a_tty.tg_bind_tree[0], 0, sizeof(a_tty.tg_bind_tree));
3505 a_tty.tg_bind_isdirty = a_tty.tg_bind_isbuild = FAL0;
3506 NYD2_LEAVE;
3509 static void
3510 a_tty__bind_tree_add(ui32_t hmap_idx, struct a_tty_bind_tree *store[HSHSIZE],
3511 struct a_tty_bind_ctx *tbcp){
3512 ui32_t cnvlen;
3513 char const *cnvdat;
3514 struct a_tty_bind_tree *ntbtp;
3515 NYD2_ENTER;
3516 n_UNUSED(hmap_idx);
3518 ntbtp = NULL;
3520 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len; cnvlen > 0;){
3521 union {wchar_t const *wp; char const *cp;} u;
3522 si32_t entlen;
3524 /* {si32_t buf_len_iscap;} */
3525 entlen = *n_UNALIGN(si32_t const*,cnvdat);
3527 if(entlen & SI32_MIN){
3528 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;}
3529 * Note that empty capabilities result in DEFUNCT */
3530 for(u.cp = (char const*)&n_UNALIGN(si32_t const*,cnvdat)[2];
3531 *u.cp != '\0'; ++u.cp)
3532 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.cp, TRU1);
3533 assert(ntbtp != NULL);
3534 ntbtp->tbt_isseq_trail = TRU1;
3535 entlen &= SI32_MAX;
3536 }else{
3537 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3538 bool_t isseq;
3540 u.wp = (wchar_t const*)&n_UNALIGN(si32_t const*,cnvdat)[1];
3542 /* May be a special shortcut function? */
3543 if(ntbtp == NULL && (tbcp->tbc_flags & a_TTY_BIND_MLE1CNTRL)){
3544 char *cp;
3545 ui32_t ctx, fun;
3547 ctx = tbcp->tbc_flags & n__LEXINPUT_CTX_MASK;
3548 fun = tbcp->tbc_flags & a_TTY__BIND_FUN_MASK;
3550 if(fun == a_TTY_BIND_FUN_CANCEL){
3551 for(cp = &a_tty.tg_bind_shcut_cancel[ctx][0];
3552 PTRCMP(cp, <, &a_tty.tg_bind_shcut_cancel[ctx]
3553 [n_NELEM(a_tty.tg_bind_shcut_cancel[ctx]) - 1]); ++cp)
3554 if(*cp == '\0'){
3555 *cp = (char)*u.wp;
3556 break;
3558 }else if(fun == a_TTY_BIND_FUN_PROMPT_CHAR){
3559 for(cp = &a_tty.tg_bind_shcut_prompt_char[ctx][0];
3560 PTRCMP(cp, <, &a_tty.tg_bind_shcut_prompt_char[ctx]
3561 [n_NELEM(a_tty.tg_bind_shcut_prompt_char[ctx]) - 1]);
3562 ++cp)
3563 if(*cp == '\0'){
3564 *cp = (char)*u.wp;
3565 break;
3570 isseq = (u.wp[1] != '\0');
3571 for(; *u.wp != '\0'; ++u.wp)
3572 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.wp, isseq);
3573 if(isseq)
3574 ntbtp->tbt_isseq_trail = TRU1;
3577 cnvlen -= entlen;
3578 cnvdat += entlen;
3581 /* Should have been rendered defunctional at first instead */
3582 assert(ntbtp != NULL);
3583 ntbtp->tbt_bind = tbcp;
3584 NYD2_LEAVE;
3587 static struct a_tty_bind_tree *
3588 a_tty__bind_tree_add_wc(struct a_tty_bind_tree **treep,
3589 struct a_tty_bind_tree *parentp, wchar_t wc, bool_t isseq){
3590 struct a_tty_bind_tree *tbtp, *xtbtp;
3591 NYD2_ENTER;
3593 if(parentp == NULL){
3594 treep += wc % HSHSIZE;
3596 /* Having no parent also means that the tree slot is possibly empty */
3597 for(tbtp = *treep; tbtp != NULL;
3598 parentp = tbtp, tbtp = tbtp->tbt_sibling){
3599 if(tbtp->tbt_char != wc)
3600 continue;
3601 if(tbtp->tbt_isseq == isseq)
3602 goto jleave;
3603 /* isseq MUST be linked before !isseq, so record this "parent"
3604 * sibling, but continue searching for now */
3605 if(!isseq)
3606 parentp = tbtp;
3607 /* Otherwise it is impossible that we'll find what we look for */
3608 else{
3609 #ifdef HAVE_DEBUG
3610 while((tbtp = tbtp->tbt_sibling) != NULL)
3611 assert(tbtp->tbt_char != wc);
3612 #endif
3613 break;
3617 tbtp = smalloc(sizeof *tbtp);
3618 memset(tbtp, 0, sizeof *tbtp);
3619 tbtp->tbt_char = wc;
3620 tbtp->tbt_isseq = isseq;
3622 if(parentp == NULL){
3623 tbtp->tbt_sibling = *treep;
3624 *treep = tbtp;
3625 }else{
3626 tbtp->tbt_sibling = parentp->tbt_sibling;
3627 parentp->tbt_sibling = tbtp;
3629 }else{
3630 if((tbtp = *(treep = &parentp->tbt_childs)) != NULL){
3631 for(;; tbtp = xtbtp){
3632 if(tbtp->tbt_char == wc){
3633 if(tbtp->tbt_isseq == isseq)
3634 goto jleave;
3635 /* isseq MUST be linked before, so it is impossible that we'll
3636 * find what we look for */
3637 if(isseq){
3638 #ifdef HAVE_DEBUG
3639 while((tbtp = tbtp->tbt_sibling) != NULL)
3640 assert(tbtp->tbt_char != wc);
3641 #endif
3642 tbtp = NULL;
3643 break;
3647 if((xtbtp = tbtp->tbt_sibling) == NULL){
3648 treep = &tbtp->tbt_sibling;
3649 break;
3654 xtbtp = smalloc(sizeof *xtbtp);
3655 memset(xtbtp, 0, sizeof *xtbtp);
3656 xtbtp->tbt_parent = parentp;
3657 xtbtp->tbt_char = wc;
3658 xtbtp->tbt_isseq = isseq;
3659 tbtp = xtbtp;
3660 *treep = tbtp;
3662 jleave:
3663 NYD2_LEAVE;
3664 return tbtp;
3667 static void
3668 a_tty__bind_tree_free(struct a_tty_bind_tree *tbtp){
3669 NYD2_ENTER;
3670 while(tbtp != NULL){
3671 struct a_tty_bind_tree *tmp;
3673 if((tmp = tbtp->tbt_childs) != NULL)
3674 a_tty__bind_tree_free(tmp);
3676 tmp = tbtp->tbt_sibling;
3677 free(tbtp);
3678 tbtp = tmp;
3680 NYD2_LEAVE;
3682 # endif /* HAVE_KEY_BINDINGS */
3684 FL void
3685 n_tty_init(void){
3686 NYD_ENTER;
3688 if(ok_blook(line_editor_disable))
3689 goto jleave;
3691 /* Load the history file */
3692 # ifdef HAVE_HISTORY
3693 do/* for break */{
3694 long hs;
3695 char const *v;
3696 char *lbuf;
3697 FILE *f;
3698 size_t lsize, cnt, llen;
3700 a_TTY_HISTSIZE(hs);
3701 a_tty.tg_hist_size = 0;
3702 a_tty.tg_hist_size_max = (size_t)hs;
3703 if(hs == 0)
3704 break;
3706 a_TTY_HISTFILE(v);
3707 if(v == NULL)
3708 break;
3710 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
3711 f = fopen(v, "r"); /* TODO HISTFILE LOAD: use linebuf pool */
3712 if(f == NULL)
3713 goto jhist_done;
3714 (void)n_file_lock(fileno(f), FLT_READ, 0,0, UIZ_MAX);
3716 assert(!(pstate & PS_ROOT));
3717 pstate |= PS_ROOT; /* Allow calling addhist() */
3718 lbuf = NULL;
3719 lsize = 0;
3720 cnt = (size_t)fsize(f);
3721 while(fgetline(&lbuf, &lsize, &cnt, &llen, f, FAL0) != NULL){
3722 if(llen > 0 && lbuf[llen - 1] == '\n')
3723 lbuf[--llen] = '\0';
3724 if(llen == 0 || lbuf[0] == '#') /* xxx comments? noone! */
3725 continue;
3726 else{
3727 bool_t isgabby;
3729 isgabby = (lbuf[0] == '*');
3730 n_tty_addhist(lbuf + isgabby, isgabby);
3733 if(lbuf != NULL)
3734 free(lbuf);
3735 pstate &= ~PS_ROOT;
3737 fclose(f);
3738 jhist_done:
3739 rele_all_sigs(); /* XXX remove jumps */
3740 }while(0);
3741 # endif /* HAVE_HISTORY */
3743 /* Force immediate resolve for anything which follows */
3744 pstate |= PS_LINE_EDITOR_INIT;
3746 # ifdef HAVE_KEY_BINDINGS
3747 /* `bind's (and `unbind's) done from within resource files couldn't be
3748 * performed for real since our termcap driver wasn't yet loaded, and we
3749 * can't perform automatic init since the user may have disallowed so */
3750 /* C99 */{
3751 struct a_tty_bind_ctx *tbcp;
3752 enum n_lexinput_flags lif;
3754 for(lif = 0; lif < n__LEXINPUT_CTX_MAX1; ++lif)
3755 for(tbcp = a_tty.tg_bind[lif]; tbcp != NULL; tbcp = tbcp->tbc_next)
3756 if((tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
3757 a_TTY_BIND_RESOLVE)
3758 a_tty_bind_resolve(tbcp);
3761 /* And we want to (try to) install some default key bindings */
3762 if(!ok_blook(line_editor_no_defaults)){
3763 char buf[8];
3764 struct a_tty_bind_parse_ctx tbpc;
3765 struct a_tty_bind_default_tuple const *tbdtp;
3767 buf[0] = '$', buf[1] = '\'', buf[2] = '\\', buf[3] = 'c',
3768 buf[5] = '\'', buf[6] = '\0';
3769 for(tbdtp = a_tty_bind_default_tuples;
3770 PTRCMP(tbdtp, <,
3771 &a_tty_bind_default_tuples[n_NELEM(a_tty_bind_default_tuples)]);
3772 ++tbdtp){
3773 memset(&tbpc, 0, sizeof tbpc);
3774 tbpc.tbpc_cmd = "bind";
3775 if(tbdtp->tbdt_iskey){
3776 buf[4] = tbdtp->tbdt_ckey;
3777 tbpc.tbpc_in_seq = buf;
3778 }else
3779 tbpc.tbpc_in_seq = savecatsep(":", '\0',
3780 n_termcap_name_of_query(tbdtp->tbdt_query));
3781 tbpc.tbpc_exp.s = n_UNCONST(tbdtp->tbdt_exp[0] == '\0'
3782 ? a_tty_bind_fun_names[(ui8_t)tbdtp->tbdt_exp[1]]
3783 : tbdtp->tbdt_exp);
3784 tbpc.tbpc_exp.l = strlen(tbpc.tbpc_exp.s);
3785 tbpc.tbpc_flags = n_LEXINPUT_CTX_BASE;
3786 /* ..but don't want to overwrite any user settings */
3787 a_tty_bind_create(&tbpc, FAL0);
3790 # endif /* HAVE_KEY_BINDINGS */
3792 jleave:
3793 NYD_LEAVE;
3796 FL void
3797 n_tty_destroy(void){
3798 NYD_ENTER;
3800 if(!(pstate & PS_LINE_EDITOR_INIT))
3801 goto jleave;
3803 # ifdef HAVE_HISTORY
3804 do/* for break */{
3805 long hs;
3806 char const *v;
3807 struct a_tty_hist *thp;
3808 bool_t dogabby;
3809 FILE *f;
3811 a_TTY_HISTSIZE(hs);
3812 if(hs == 0)
3813 break;
3815 a_TTY_HISTFILE(v);
3816 if(v == NULL)
3817 break;
3819 dogabby = ok_blook(history_gabby_persist);
3821 if((thp = a_tty.tg_hist) != NULL)
3822 for(; thp->th_older != NULL; thp = thp->th_older)
3823 if((dogabby || !thp->th_isgabby) && --hs == 0)
3824 break;
3826 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
3827 f = fopen(v, "w"); /* TODO temporary + rename?! */
3828 if(f == NULL)
3829 goto jhist_done;
3830 (void)n_file_lock(fileno(f), FLT_WRITE, 0,0, UIZ_MAX);
3832 for(; thp != NULL; thp = thp->th_younger){
3833 if(dogabby || !thp->th_isgabby){
3834 if(thp->th_isgabby)
3835 putc('*', f);
3836 fwrite(thp->th_dat, sizeof *thp->th_dat, thp->th_len, f);
3837 putc('\n', f);
3840 fclose(f);
3841 jhist_done:
3842 rele_all_sigs(); /* XXX remove jumps */
3843 }while(0);
3844 # endif /* HAVE_HISTORY */
3846 # if defined HAVE_KEY_BINDINGS && defined HAVE_DEBUG
3847 c_unbind(n_UNCONST("* *"));
3848 # endif
3850 # ifdef HAVE_DEBUG
3851 memset(&a_tty, 0, sizeof a_tty);
3852 # endif
3853 DBG( pstate &= ~PS_LINE_EDITOR_INIT; )
3854 jleave:
3855 NYD_LEAVE;
3858 FL void
3859 n_tty_signal(int sig){
3860 sigset_t nset, oset;
3861 NYD_X; /* Signal handler */
3863 switch(sig){
3864 # ifdef SIGWINCH
3865 case SIGWINCH:
3866 /* We don't deal with SIGWINCH, yet get called from main.c.
3867 * Note this case might get called even if !PS_LINE_EDITOR_INIT */
3868 break;
3869 # endif
3870 default:
3871 a_tty_term_mode(FAL0);
3872 n_TERMCAP_SUSPEND(TRU1);
3873 a_tty_sigs_down();
3875 sigemptyset(&nset);
3876 sigaddset(&nset, sig);
3877 sigprocmask(SIG_UNBLOCK, &nset, &oset);
3878 n_raise(sig);
3879 /* When we come here we'll continue editing, so reestablish */
3880 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
3882 a_tty_sigs_up();
3883 n_TERMCAP_RESUME(TRU1);
3884 a_tty_term_mode(TRU1);
3885 a_tty.tg_line->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
3886 break;
3890 FL int
3891 (n_tty_readline)(enum n_lexinput_flags lif, char const *prompt,
3892 char **linebuf, size_t *linesize, size_t n n_MEMORY_DEBUG_ARGS){
3893 struct a_tty_line tl;
3894 struct n_string xprompt;
3895 # ifdef HAVE_COLOUR
3896 char *posbuf, *pos;
3897 # endif
3898 ssize_t nn;
3899 ui32_t plen, pwidth;
3900 char const *orig_prompt;
3901 NYD_ENTER;
3902 n_UNUSED(lif);
3903 n_UNINIT(pwidth, 0);
3904 n_UNINIT(plen, 0);
3906 assert(!ok_blook(line_editor_disable));
3907 if(!(pstate & PS_LINE_EDITOR_INIT))
3908 n_tty_init();
3909 assert(pstate & PS_LINE_EDITOR_INIT);
3911 if(!(lif & n_LEXINPUT_PROMPT_NONE))
3912 n_string_creat_auto(&xprompt);
3913 orig_prompt = prompt;
3914 jredo:
3915 # ifdef HAVE_COLOUR
3916 n_colour_env_create(n_COLOUR_CTX_MLE, FAL0);
3917 # endif
3919 if(!(lif & n_LEXINPUT_PROMPT_NONE)){
3920 pwidth = n_tty_create_prompt(&xprompt, orig_prompt, lif);
3921 plen = (ui32_t)xprompt.s_len;
3922 prompt = (pwidth == 0) ? NULL : n_string_cp_const(&xprompt);
3925 # ifdef HAVE_COLOUR
3926 /* C99 */{
3927 char const *ccol;
3928 struct n_colour_pen *ccp;
3929 struct str const *sp;
3931 /* .tl_pos_buf is a hack */
3932 posbuf = pos = NULL;
3933 if((ccp = n_colour_pen_create(n_COLOUR_ID_MLE_POSITION, NULL)) != NULL &&
3934 (sp = n_colour_pen_to_str(ccp)) != NULL){
3935 ccol = sp->s;
3936 if((sp = n_colour_reset_to_str()) != NULL){
3937 size_t l1, l2;
3939 l1 = strlen(ccol);
3940 l2 = strlen(sp->s);
3941 posbuf = salloc(l1 + 4 + l2 +1);
3942 memcpy(posbuf, ccol, l1);
3943 pos = &posbuf[l1];
3944 memcpy(&pos[4], sp->s, ++l2);
3947 if(posbuf == NULL){
3948 posbuf = pos = salloc(4 +1);
3949 pos[4] = '\0';
3952 # endif /* HAVE_COLOUR */
3954 memset(&tl, 0, sizeof tl);
3956 # ifdef HAVE_KEY_BINDINGS
3957 /* C99 */{
3958 char const *cp = ok_vlook(bind_timeout);
3960 if(cp != NULL){
3961 ul_i ul;
3963 if((ul = strtoul(cp, NULL, 0)) > 0 &&
3964 /* Convert to tenths of a second, unfortunately */
3965 (ul = (ul + 99) / 100) <= a_TTY_BIND_TIMEOUT_MAX)
3966 tl.tl_bind_timeout = (ui8_t)ul;
3967 else if(options & OPT_D_V)
3968 n_err(_("Ignoring invalid *bind-timeout*: %s\n"), cp);
3972 if(a_tty.tg_bind_isdirty)
3973 a_tty_bind_tree_teardown();
3974 if(a_tty.tg_bind_cnt > 0 && !a_tty.tg_bind_isbuild)
3975 a_tty_bind_tree_build();
3976 tl.tl_bind_tree_hmap = &a_tty.tg_bind_tree[lif & n__LEXINPUT_CTX_MASK];
3977 tl.tl_bind_shcut_cancel =
3978 &a_tty.tg_bind_shcut_cancel[lif & n__LEXINPUT_CTX_MASK];
3979 tl.tl_bind_shcut_prompt_char =
3980 &a_tty.tg_bind_shcut_prompt_char[lif & n__LEXINPUT_CTX_MASK];
3981 # endif /* HAVE_KEY_BINDINGS */
3983 if(!(lif & n_LEXINPUT_PROMPT_NONE) && pwidth > 0){
3984 tl.tl_prompt = prompt;
3985 tl.tl_prompt_length = plen;
3986 tl.tl_prompt_width = pwidth;
3988 # ifdef HAVE_COLOUR
3989 tl.tl_pos_buf = posbuf;
3990 tl.tl_pos = pos;
3991 # endif
3993 tl.tl_line.cbuf = *linebuf;
3994 if(n != 0){
3995 tl.tl_defc.s = savestrbuf(*linebuf, n);
3996 tl.tl_defc.l = n;
3998 tl.tl_x_buf = linebuf;
3999 tl.tl_x_bufsize = linesize;
4001 a_tty.tg_line = &tl;
4002 a_tty_sigs_up();
4003 n_TERMCAP_RESUME(FAL0);
4004 a_tty_term_mode(TRU1);
4005 nn = a_tty_readline(&tl, n n_MEMORY_DEBUG_ARGSCALL);
4006 a_tty_term_mode(FAL0);
4007 n_TERMCAP_SUSPEND(FAL0);
4008 a_tty_sigs_down();
4009 a_tty.tg_line = NULL;
4011 # ifdef HAVE_COLOUR
4012 n_colour_env_gut(stdout);
4013 # endif
4015 if(tl.tl_reenter_after_cmd != NULL){
4016 n_source_command(lif, tl.tl_reenter_after_cmd);
4017 n = (nn <= 0) ? 0 : nn;
4018 if(!ok_blook(line_editor_disable))
4019 goto jredo;
4020 nn = (n_lex_input)(lif, orig_prompt, linebuf, linesize,
4021 (n == 0 ? n_empty : savestrbuf(*linebuf, n))
4022 n_MEMORY_DEBUG_ARGSCALL);
4024 NYD_LEAVE;
4025 return (int)nn;
4028 FL void
4029 n_tty_addhist(char const *s, bool_t isgabby){
4030 # ifdef HAVE_HISTORY
4031 /* Super-Heavy-Metal: block all sigs, avoid leaks+ on jump */
4032 ui32_t l;
4033 struct a_tty_hist *thp, *othp, *ythp;
4034 # endif
4035 NYD_ENTER;
4036 n_UNUSED(s);
4037 n_UNUSED(isgabby);
4039 # ifdef HAVE_HISTORY
4040 a_TTY_CHECK_ADDHIST(s, isgabby, goto j_leave);
4041 if(a_tty.tg_hist_size_max == 0)
4042 goto j_leave;
4044 l = (ui32_t)strlen(s);
4046 /* Eliminating duplicates is expensive, but simply inacceptable so
4047 * during the load of a potentially large history file! */
4048 if(pstate & PS_LINE_EDITOR_INIT)
4049 for(thp = a_tty.tg_hist; thp != NULL; thp = thp->th_older)
4050 if(thp->th_len == l && !strcmp(thp->th_dat, s)){
4051 hold_all_sigs(); /* TODO */
4052 if(thp->th_isgabby)
4053 thp->th_isgabby = !!isgabby;
4054 othp = thp->th_older;
4055 ythp = thp->th_younger;
4056 if(othp != NULL)
4057 othp->th_younger = ythp;
4058 else
4059 a_tty.tg_hist_tail = ythp;
4060 if(ythp != NULL)
4061 ythp->th_older = othp;
4062 else
4063 a_tty.tg_hist = othp;
4064 goto jleave;
4066 hold_all_sigs();
4068 ++a_tty.tg_hist_size;
4069 if((pstate & PS_LINE_EDITOR_INIT) &&
4070 a_tty.tg_hist_size > a_tty.tg_hist_size_max){
4071 --a_tty.tg_hist_size;
4072 if((thp = a_tty.tg_hist_tail) != NULL){
4073 if((a_tty.tg_hist_tail = thp->th_younger) == NULL)
4074 a_tty.tg_hist = NULL;
4075 else
4076 a_tty.tg_hist_tail->th_older = NULL;
4077 free(thp);
4081 thp = smalloc((sizeof(struct a_tty_hist) -
4082 n_VFIELD_SIZEOF(struct a_tty_hist, th_dat)) + l +1);
4083 thp->th_isgabby = !!isgabby;
4084 thp->th_len = l;
4085 memcpy(thp->th_dat, s, l +1);
4086 jleave:
4087 if((thp->th_older = a_tty.tg_hist) != NULL)
4088 a_tty.tg_hist->th_younger = thp;
4089 else
4090 a_tty.tg_hist_tail = thp;
4091 thp->th_younger = NULL;
4092 a_tty.tg_hist = thp;
4094 rele_all_sigs();
4095 j_leave:
4096 # endif
4097 NYD_LEAVE;
4100 # ifdef HAVE_HISTORY
4101 FL int
4102 c_history(void *v){
4103 C_HISTORY_SHARED;
4105 jlist:{
4106 FILE *fp;
4107 size_t i, b;
4108 struct a_tty_hist *thp;
4110 if(a_tty.tg_hist == NULL)
4111 goto jleave;
4113 if((fp = Ftmp(NULL, "hist", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
4114 n_perr(_("tmpfile"), 0);
4115 v = NULL;
4116 goto jleave;
4119 i = a_tty.tg_hist_size;
4120 b = 0;
4121 for(thp = a_tty.tg_hist; thp != NULL;
4122 --i, b += thp->th_len, thp = thp->th_older)
4123 fprintf(fp,
4124 "%c%4" PRIuZ ". %-50.50s (%4" PRIuZ "+%2" PRIu32 " B)\n",
4125 (thp->th_isgabby ? '*' : ' '), i, thp->th_dat, b, thp->th_len);
4127 page_or_print(fp, i);
4128 Fclose(fp);
4130 goto jleave;
4132 jclear:{
4133 struct a_tty_hist *thp;
4135 while((thp = a_tty.tg_hist) != NULL){
4136 a_tty.tg_hist = thp->th_older;
4137 free(thp);
4139 a_tty.tg_hist_tail = NULL;
4140 a_tty.tg_hist_size = 0;
4142 goto jleave;
4144 jentry:{
4145 struct a_tty_hist *thp;
4147 if(UICMP(z, entry, <=, a_tty.tg_hist_size)){
4148 entry = (long)a_tty.tg_hist_size - entry;
4149 for(thp = a_tty.tg_hist;; thp = thp->th_older)
4150 if(thp == NULL)
4151 break;
4152 else if(entry-- != 0)
4153 continue;
4154 else{
4155 v = temporary_arg_v_store = thp->th_dat;
4156 goto jleave;
4159 v = NULL;
4161 goto jleave;
4163 # endif /* HAVE_HISTORY */
4165 # ifdef HAVE_KEY_BINDINGS
4166 FL int
4167 c_bind(void *v){
4168 n_CMD_ARG_DESC_SUBCLASS_DEF(bind, 3, a_tty_bind_cad) { /* TODO cmd_tab.h */
4169 {n_CMD_ARG_DESC_STRING, 0},
4170 {n_CMD_ARG_DESC_WYSH | n_CMD_ARG_DESC_OPTION |
4171 n_CMD_ARG_DESC_HONOUR_STOP,
4172 n_SHEXP_PARSE_DRYRUN | n_SHEXP_PARSE_LOG},
4173 {n_CMD_ARG_DESC_WYSH | n_CMD_ARG_DESC_OPTION | n_CMD_ARG_DESC_GREEDY |
4174 n_CMD_ARG_DESC_HONOUR_STOP,
4175 n_SHEXP_PARSE_IGNORE_EMPTY}
4176 } n_CMD_ARG_DESC_SUBCLASS_DEF_END;
4177 struct n_cmd_arg_ctx cac;
4178 struct a_tty_bind_ctx *tbcp;
4179 enum n_lexinput_flags lif;
4180 bool_t aster, show;
4181 union {char const *cp; char *p; char c;} c;
4182 NYD_ENTER;
4184 cac.cac_desc = n_CMD_ARG_DESC_SUBCLASS_CAST(&a_tty_bind_cad);
4185 cac.cac_indat = v;
4186 cac.cac_inlen = UIZ_MAX;
4187 if(!n_cmd_arg_parse(&cac)){
4188 v = NULL;
4189 goto jleave;
4192 c.cp = cac.cac_arg->ca_arg.ca_str.s;
4193 if(cac.cac_no == 1)
4194 show = TRU1;
4195 else
4196 show = !asccasecmp(cac.cac_arg->ca_next->ca_arg.ca_str.s, "show");
4197 aster = FAL0;
4199 if((lif = a_tty_bind_ctx_find(c.cp)) == (enum n_lexinput_flags)-1){
4200 if(!(aster = n_is_all_or_aster(c.cp)) || !show){
4201 n_err(_("`bind': invalid context: %s\n"), c.cp);
4202 v = NULL;
4203 goto jleave;
4205 lif = 0;
4208 if(show){
4209 ui32_t lns;
4210 FILE *fp;
4212 if((fp = Ftmp(NULL, "bind", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
4213 n_perr(_("tmpfile"), 0);
4214 v = NULL;
4215 goto jleave;
4218 lns = 0;
4219 for(;;){
4220 for(tbcp = a_tty.tg_bind[lif]; tbcp != NULL;
4221 ++lns, tbcp = tbcp->tbc_next){
4222 /* Print the bytes of resolved terminal capabilities, then */
4223 if((options & OPT_D_V) &&
4224 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)
4225 ) == a_TTY_BIND_RESOLVE){
4226 char cbuf[8];
4227 union {wchar_t const *wp; char const *cp;} u;
4228 si32_t entlen;
4229 ui32_t cnvlen;
4230 char const *cnvdat, *bsep, *cbufp;
4232 putc('#', fp);
4233 putc(' ', fp);
4235 cbuf[0] = '=', cbuf[2] = '\0';
4236 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len;
4237 cnvlen > 0;){
4238 if(cnvdat != tbcp->tbc_cnv)
4239 putc(',', fp);
4241 /* {si32_t buf_len_iscap;} */
4242 entlen = *n_UNALIGN(si32_t const*,cnvdat);
4243 if(entlen & SI32_MIN){
4244 /* struct{si32_t buf_len_iscap; si32_t cap_len;
4245 * char buf[]+NUL;} */
4246 for(bsep = n_empty,
4247 u.cp = (char const*)
4248 &n_UNALIGN(si32_t const*,cnvdat)[2];
4249 (c.c = *u.cp) != '\0'; ++u.cp){
4250 if(asciichar(c.c) && !cntrlchar(c.c))
4251 cbuf[1] = c.c, cbufp = cbuf;
4252 else
4253 cbufp = n_empty;
4254 fprintf(fp, "%s%02X%s",
4255 bsep, (ui32_t)(ui8_t)c.c, cbufp);
4256 bsep = " ";
4258 entlen &= SI32_MAX;
4259 }else
4260 putc('-', fp);
4262 cnvlen -= entlen;
4263 cnvdat += entlen;
4266 fputs("\n ", fp);
4267 ++lns;
4270 fprintf(fp, "%sbind %s %s %s%s%s\n",
4271 ((tbcp->tbc_flags & a_TTY_BIND_DEFUNCT)
4272 /* I18N: `bind' sequence not working, either because it is
4273 * I18N: using Unicode and that is not available in the locale,
4274 * I18N: or a termcap(5)/terminfo(5) sequence won't work out */
4275 ? _("# <Defunctional> ") : n_empty),
4276 a_tty_bind_ctx_maps[lif].tbcm_name, tbcp->tbc_seq,
4277 n_shexp_quote_cp(tbcp->tbc_exp, TRU1),
4278 (tbcp->tbc_flags & a_TTY_BIND_NOCOMMIT ? "@" : n_empty),
4279 (!(options & OPT_D_VV) ? n_empty
4280 : (tbcp->tbc_flags & a_TTY_BIND_FUN_INTERNAL
4281 ? _(" # MLE internal") : n_empty))
4284 if(!aster || ++lif >= n__LEXINPUT_CTX_MAX1)
4285 break;
4287 page_or_print(fp, lns);
4289 Fclose(fp);
4290 }else{
4291 struct a_tty_bind_parse_ctx tbpc;
4292 struct n_string store;
4294 memset(&tbpc, 0, sizeof tbpc);
4295 tbpc.tbpc_cmd = a_tty_bind_cad.cad_name;
4296 tbpc.tbpc_in_seq = cac.cac_arg->ca_next->ca_arg.ca_str.s;
4297 tbpc.tbpc_exp.s = n_string_cp(n_cmd_arg_join_greedy(&cac,
4298 n_string_creat_auto(&store)));
4299 tbpc.tbpc_exp.l = store.s_len;
4300 tbpc.tbpc_flags = lif;
4301 if(!a_tty_bind_create(&tbpc, TRU1))
4302 v = NULL;
4303 n_string_gut(&store);
4305 jleave:
4306 NYD_LEAVE;
4307 return (v != NULL) ? EXIT_OK : EXIT_ERR;
4310 FL int
4311 c_unbind(void *v){
4312 n_CMD_ARG_DESC_SUBCLASS_DEF(unbind, 2, a_tty_unbind_cad) {/* TODO cmd_tab.h*/
4313 {n_CMD_ARG_DESC_STRING, 0},
4314 {n_CMD_ARG_DESC_WYSH | n_CMD_ARG_DESC_HONOUR_STOP,
4315 n_SHEXP_PARSE_DRYRUN | n_SHEXP_PARSE_LOG}
4316 } n_CMD_ARG_DESC_SUBCLASS_DEF_END;
4317 struct a_tty_bind_parse_ctx tbpc;
4318 struct n_cmd_arg_ctx cac;
4319 struct a_tty_bind_ctx *tbcp;
4320 enum n_lexinput_flags lif;
4321 bool_t aster;
4322 union {char const *cp; char *p;} c;
4323 NYD_ENTER;
4325 cac.cac_desc = n_CMD_ARG_DESC_SUBCLASS_CAST(&a_tty_unbind_cad);
4326 cac.cac_indat = v;
4327 cac.cac_inlen = UIZ_MAX;
4328 if(!n_cmd_arg_parse(&cac)){
4329 v = NULL;
4330 goto jleave;
4333 c.cp = cac.cac_arg->ca_arg.ca_str.s;
4334 aster = FAL0;
4336 if((lif = a_tty_bind_ctx_find(c.cp)) == (enum n_lexinput_flags)-1){
4337 if(!(aster = n_is_all_or_aster(c.cp))){
4338 n_err(_("`unbind': invalid context: %s\n"), c.cp);
4339 v = NULL;
4340 goto jleave;
4342 lif = 0;
4345 c.cp = cac.cac_arg->ca_next->ca_arg.ca_str.s;
4346 jredo:
4347 if(n_is_all_or_aster(c.cp)){
4348 while((tbcp = a_tty.tg_bind[lif]) != NULL){
4349 memset(&tbpc, 0, sizeof tbpc);
4350 tbpc.tbpc_tbcp = tbcp;
4351 tbpc.tbpc_flags = lif;
4352 a_tty_bind_del(&tbpc);
4354 }else{
4355 memset(&tbpc, 0, sizeof tbpc);
4356 tbpc.tbpc_cmd = a_tty_unbind_cad.cad_name;
4357 tbpc.tbpc_in_seq = c.cp;
4358 tbpc.tbpc_flags = lif;
4360 if(n_UNLIKELY(!a_tty_bind_parse(FAL0, &tbpc)))
4361 v = NULL;
4362 else if(n_UNLIKELY((tbcp = tbpc.tbpc_tbcp) == NULL)){
4363 n_err(_("`unbind': no such `bind'ing: %s %s\n"),
4364 a_tty_bind_ctx_maps[lif].tbcm_name, c.cp);
4365 v = NULL;
4366 }else
4367 a_tty_bind_del(&tbpc);
4370 if(aster && ++lif < n__LEXINPUT_CTX_MAX1)
4371 goto jredo;
4372 jleave:
4373 NYD_LEAVE;
4374 return (v != NULL) ? EXIT_OK : EXIT_ERR;
4376 # endif /* HAVE_KEY_BINDINGS */
4378 #else /* HAVE_MLE */
4380 * The really-nothing-at-all implementation
4383 FL void
4384 n_tty_init(void){
4385 NYD_ENTER;
4386 NYD_LEAVE;
4389 FL void
4390 n_tty_destroy(void){
4391 NYD_ENTER;
4392 NYD_LEAVE;
4395 FL void
4396 n_tty_signal(int sig){
4397 NYD_X; /* Signal handler */
4398 n_UNUSED(sig);
4400 # ifdef HAVE_TERMCAP
4401 switch(sig){
4402 default:{
4403 sigset_t nset, oset;
4405 n_TERMCAP_SUSPEND(TRU1);
4406 a_tty_sigs_down();
4408 sigemptyset(&nset);
4409 sigaddset(&nset, sig);
4410 sigprocmask(SIG_UNBLOCK, &nset, &oset);
4411 n_raise(sig);
4412 /* When we come here we'll continue editing, so reestablish */
4413 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
4415 a_tty_sigs_up();
4416 n_TERMCAP_RESUME(TRU1);
4417 break;
4420 # endif /* HAVE_TERMCAP */
4423 FL int
4424 (n_tty_readline)(enum n_lexinput_flags lif, char const *prompt,
4425 char **linebuf, size_t *linesize, size_t n n_MEMORY_DEBUG_ARGS){
4426 struct n_string xprompt;
4427 int rv;
4428 NYD_ENTER;
4430 if(!(lif & n_LEXINPUT_PROMPT_NONE)){
4431 if(n_tty_create_prompt(n_string_creat_auto(&xprompt), prompt, lif) > 0){
4432 fwrite(xprompt.s_dat, 1, xprompt.s_len, stdout);
4433 fflush(stdout);
4437 # ifdef HAVE_TERMCAP
4438 a_tty_sigs_up();
4439 n_TERMCAP_RESUME(FAL0);
4440 # endif
4441 rv = (readline_restart)(stdin, linebuf, linesize,n n_MEMORY_DEBUG_ARGSCALL);
4442 # ifdef HAVE_TERMCAP
4443 n_TERMCAP_SUSPEND(FAL0);
4444 a_tty_sigs_down();
4445 # endif
4446 NYD_LEAVE;
4447 return rv;
4450 FL void
4451 n_tty_addhist(char const *s, bool_t isgabby){
4452 NYD_ENTER;
4453 n_UNUSED(s);
4454 n_UNUSED(isgabby);
4455 NYD_LEAVE;
4457 #endif /* nothing at all */
4459 #undef a_TTY_SIGNALS
4460 /* s-it-mode */