SEND_TODISP(_ALL)?: append newline if message does have no final one
[s-mailx.git] / tty.c
blob6211742cf7ea558aca5475ede551b10692c802f9
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 - 2015 Steffen (Daode) Nurpmeso <sdaoden@users.sf.net>.
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 #ifdef HAVE_READLINE
29 # include <readline/readline.h>
30 # ifdef HAVE_HISTORY
31 # include <readline/history.h>
32 # endif
33 #endif
35 #if defined HAVE_READLINE || defined HAVE_MLE || defined HAVE_TERMCAP
36 # define a_TTY_SIGNALS
37 #endif
39 /* Shared history support macros */
40 #ifdef HAVE_HISTORY
41 # define a_TTY_HISTFILE(S) \
42 do{\
43 char const *__hist_obsolete = ok_vlook(NAIL_HISTFILE);\
44 if(__hist_obsolete != NULL)\
45 OBSOLETE(_("please use *history-file* instead of *NAIL_HISTFILE*"));\
46 S = ok_vlook(history_file);\
47 if((S) == NULL)\
48 (S) = __hist_obsolete;\
49 if((S) != NULL)\
50 S = fexpand(S, FEXP_LOCAL | FEXP_NSHELL);\
51 }while(0)
53 # define a_TTY_HISTSIZE(V) \
54 do{\
55 char const *__hist_obsolete = ok_vlook(NAIL_HISTSIZE);\
56 char const *__sv = ok_vlook(history_size);\
57 long __rv;\
58 if(__hist_obsolete != NULL)\
59 OBSOLETE(_("please use *history-size* instead of *NAIL_HISTSIZE*"));\
60 if(__sv == NULL)\
61 __sv = __hist_obsolete;\
62 if(__sv == NULL || (__rv = strtol(__sv, NULL, 10)) == 0)\
63 (V) = HIST_SIZE;\
64 else if(__rv < 0)\
65 __rv = 0;\
66 else\
67 (V) = __rv;\
68 }while(0)
70 # define a_TTY_CHECK_ADDHIST(S,NOACT) \
71 do{\
72 switch(*(S)){\
73 case '\0':\
74 case ' ':\
75 case '\t':\
76 NOACT;\
77 default:\
78 break;\
80 }while(0)
82 # define C_HISTORY_SHARED \
83 char **argv = v;\
84 long entry;\
85 NYD_ENTER;\
87 if(!(pstate & PS_LINE_EDITOR_INIT))\
88 goto jleave;\
89 if(*argv == NULL)\
90 goto jlist;\
91 if(argv[1] != NULL)\
92 goto jerr;\
93 if(!asccasecmp(*argv, "show"))\
94 goto jlist;\
95 if(!asccasecmp(*argv, "clear"))\
96 goto jclear;\
97 if((entry = strtol(*argv, argv, 10)) > 0 && **argv == '\0')\
98 goto jentry;\
99 jerr:\
100 n_err(_("Synopsis: history: %s\n" \
101 "<show> (default), <clear> or select <NO> from editor history"));\
102 v = NULL;\
103 jleave:\
104 NYD_LEAVE;\
105 return (v == NULL ? !STOP : !OKAY); /* xxx 1:bad 0:good -- do some */
106 #endif /* HAVE_HISTORY */
108 #ifdef a_TTY_SIGNALS
109 static sighandler_type a_tty_oint, a_tty_oquit, a_tty_oterm,
110 a_tty_ohup,
111 a_tty_otstp, a_tty_ottin, a_tty_ottou;
112 #endif
114 #ifdef a_TTY_SIGNALS
115 static void a_tty_sigs_up(void), a_tty_sigs_down(void);
116 #endif
118 #ifdef a_TTY_SIGNALS
119 static void
120 a_tty_sigs_up(void){
121 sigset_t nset, oset;
122 NYD2_ENTER;
124 sigfillset(&nset);
126 sigprocmask(SIG_BLOCK, &nset, &oset);
127 a_tty_oint = safe_signal(SIGINT, &n_tty_signal);
128 a_tty_oquit = safe_signal(SIGQUIT, &n_tty_signal);
129 a_tty_oterm = safe_signal(SIGTERM, &n_tty_signal);
130 a_tty_ohup = safe_signal(SIGHUP, &n_tty_signal);
131 a_tty_otstp = safe_signal(SIGTSTP, &n_tty_signal);
132 a_tty_ottin = safe_signal(SIGTTIN, &n_tty_signal);
133 a_tty_ottou = safe_signal(SIGTTOU, &n_tty_signal);
134 sigprocmask(SIG_SETMASK, &oset, NULL);
135 NYD2_LEAVE;
138 static void
139 a_tty_sigs_down(void){
140 sigset_t nset, oset;
141 NYD2_ENTER;
143 sigfillset(&nset);
145 sigprocmask(SIG_BLOCK, &nset, &oset);
146 safe_signal(SIGINT, a_tty_oint);
147 safe_signal(SIGQUIT, a_tty_oquit);
148 safe_signal(SIGTERM, a_tty_oterm);
149 safe_signal(SIGHUP, a_tty_ohup);
150 safe_signal(SIGTSTP, a_tty_otstp);
151 safe_signal(SIGTTIN, a_tty_ottin);
152 safe_signal(SIGTTOU, a_tty_ottou);
153 sigprocmask(SIG_SETMASK, &oset, NULL);
154 NYD2_LEAVE;
156 #endif /* a_TTY_SIGNALS */
158 static sigjmp_buf a_tty__actjmp; /* TODO someday, we won't need it no more */
159 static void
160 a_tty__acthdl(int s) /* TODO someday, we won't need it no more */
162 NYD_X; /* Signal handler */
163 termios_state_reset();
164 siglongjmp(a_tty__actjmp, s);
167 FL bool_t
168 getapproval(char const * volatile prompt, bool_t noninteract_default)
170 sighandler_type volatile oint, ohup;
171 bool_t volatile rv;
172 int volatile sig;
173 NYD_ENTER;
175 if (!(options & OPT_INTERACTIVE)) {
176 sig = 0;
177 rv = noninteract_default;
178 goto jleave;
180 rv = FAL0;
182 /* C99 */{
183 char const *quest = noninteract_default
184 ? _("[yes]/no? ") : _("[no]/yes? ");
186 if (prompt == NULL)
187 prompt = _("Continue");
188 prompt = savecatsep(prompt, ' ', quest);
191 oint = safe_signal(SIGINT, SIG_IGN);
192 ohup = safe_signal(SIGHUP, SIG_IGN);
193 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
194 goto jrestore;
195 safe_signal(SIGINT, &a_tty__acthdl);
196 safe_signal(SIGHUP, &a_tty__acthdl);
198 if (n_lex_input(prompt, TRU1, &termios_state.ts_linebuf,
199 &termios_state.ts_linesize, NULL) >= 0)
200 rv = (boolify(termios_state.ts_linebuf, UIZ_MAX,
201 noninteract_default) > 0);
202 jrestore:
203 termios_state_reset();
205 safe_signal(SIGHUP, ohup);
206 safe_signal(SIGINT, oint);
207 jleave:
208 NYD_LEAVE;
209 if (sig != 0)
210 n_raise(sig);
211 return rv;
214 #ifdef HAVE_SOCKETS
215 FL char *
216 getuser(char const * volatile query) /* TODO v15-compat obsolete */
218 sighandler_type volatile oint, ohup;
219 char * volatile user = NULL;
220 int volatile sig;
221 NYD_ENTER;
223 if (query == NULL)
224 query = _("User: ");
226 oint = safe_signal(SIGINT, SIG_IGN);
227 ohup = safe_signal(SIGHUP, SIG_IGN);
228 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
229 goto jrestore;
230 safe_signal(SIGINT, &a_tty__acthdl);
231 safe_signal(SIGHUP, &a_tty__acthdl);
233 if (n_lex_input(query, TRU1, &termios_state.ts_linebuf,
234 &termios_state.ts_linesize, NULL) >= 0)
235 user = termios_state.ts_linebuf;
236 jrestore:
237 termios_state_reset();
239 safe_signal(SIGHUP, ohup);
240 safe_signal(SIGINT, oint);
241 NYD_LEAVE;
242 if (sig != 0)
243 n_raise(sig);
244 return user;
247 FL char *
248 getpassword(char const *query)
250 sighandler_type volatile oint, ohup;
251 struct termios tios;
252 char * volatile pass = NULL;
253 int volatile sig;
254 NYD_ENTER;
256 if (query == NULL)
257 query = _("Password: ");
258 fputs(query, stdout);
259 fflush(stdout);
261 /* FIXME everywhere: tcsetattr() generates SIGTTOU when we're not in
262 * FIXME foreground pgrp, and can fail with EINTR!! also affects
263 * FIXME termios_state_reset() */
264 if (options & OPT_TTYIN) {
265 tcgetattr(STDIN_FILENO, &termios_state.ts_tios);
266 memcpy(&tios, &termios_state.ts_tios, sizeof tios);
267 termios_state.ts_needs_reset = TRU1;
268 tios.c_iflag &= ~(ISTRIP);
269 tios.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
272 oint = safe_signal(SIGINT, SIG_IGN);
273 ohup = safe_signal(SIGHUP, SIG_IGN);
274 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
275 goto jrestore;
276 safe_signal(SIGINT, &a_tty__acthdl);
277 safe_signal(SIGHUP, &a_tty__acthdl);
279 if (options & OPT_TTYIN)
280 tcsetattr(STDIN_FILENO, TCSAFLUSH, &tios);
282 if (readline_restart(stdin, &termios_state.ts_linebuf,
283 &termios_state.ts_linesize, 0) >= 0)
284 pass = termios_state.ts_linebuf;
285 jrestore:
286 termios_state_reset();
287 if (options & OPT_TTYIN)
288 putc('\n', stdout);
290 safe_signal(SIGHUP, ohup);
291 safe_signal(SIGINT, oint);
292 NYD_LEAVE;
293 if (sig != 0)
294 n_raise(sig);
295 return pass;
297 #endif /* HAVE_SOCKETS */
300 * readline(3)
302 #ifdef HAVE_READLINE
304 static char *a_tty_rl_buf; /* pre_input() hook: initial line */
305 static int a_tty_rl_buflen; /* content, and its length */
307 /* Our rl_pre_input_hook */
308 static int a_tty_rl_pre_input(void);
310 static int
311 a_tty_rl_pre_input(void){
312 NYD2_ENTER;
313 /* Handle leftover data from \ escaped former line */
314 rl_extend_line_buffer(a_tty_rl_buflen + 10);
315 memcpy(rl_line_buffer, a_tty_rl_buf, a_tty_rl_buflen +1);
316 rl_point = rl_end = a_tty_rl_buflen;
317 rl_pre_input_hook = (rl_hook_func_t*)NULL;
318 rl_redisplay();
319 NYD2_LEAVE;
320 return 0;
323 FL void
324 n_tty_init(void){
325 # ifdef HAVE_HISTORY
326 long hs;
327 char const *v;
328 # endif
329 NYD_ENTER;
331 rl_readline_name = UNCONST(uagent);
332 # ifdef HAVE_HISTORY
333 a_TTY_HISTSIZE(hs);
334 using_history();
335 stifle_history((int)hs);
336 # endif
337 rl_read_init_file(NULL);
339 /* Because rl_read_init_file() may have introduced yet a different
340 * history size limit, simply load and incorporate the history, leave
341 * it up to readline(3) to do the rest */
342 # ifdef HAVE_HISTORY
343 a_TTY_HISTFILE(v);
344 if(v != NULL)
345 read_history(v);
346 # endif
348 pstate |= PS_LINE_EDITOR_INIT;
349 NYD_LEAVE;
352 FL void
353 n_tty_destroy(void){
354 # ifdef HAVE_HISTORY
355 char const *v;
356 # endif
357 NYD_ENTER;
359 # ifdef HAVE_HISTORY
360 a_TTY_HISTFILE(v);
361 if(v != NULL)
362 write_history(v);
363 # endif
365 DBG( pstate &= ~PS_LINE_EDITOR_INIT; )
366 NYD_LEAVE;
369 FL void
370 n_tty_signal(int sig){
371 NYD_X; /* Signal handler */
373 /* WINCH comes from main.c */
374 switch(sig){
375 # ifdef SIGWINCH
376 case SIGWINCH:
377 break;
378 # endif
379 default:{
380 sigset_t nset, oset;
382 /* readline(3) doesn't catch SIGHUP :( */
383 if(sig == SIGHUP){
384 rl_free_line_state();
385 rl_cleanup_after_signal();
387 n_TERMCAP_SUSPEND(TRU1);
388 a_tty_sigs_down();
390 sigemptyset(&nset);
391 sigaddset(&nset, sig);
392 sigprocmask(SIG_UNBLOCK, &nset, &oset);
393 n_raise(sig);
394 /* When we come here we'll continue editing, so reestablish */
395 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
397 a_tty_sigs_up();
398 n_TERMCAP_RESUME(TRU1);
399 if(sig == SIGHUP)
400 rl_reset_after_signal();
401 } break;
405 FL int
406 (n_tty_readline)(char const *prompt, char **linebuf, size_t *linesize, size_t n
407 SMALLOC_DEBUG_ARGS){
408 int nn;
409 char *line;
410 NYD_ENTER;
412 assert(pstate & PS_LINE_EDITOR_INIT);
414 if(n > 0){
415 a_tty_rl_buf = *linebuf;
416 a_tty_rl_buflen = (int)n;
417 rl_pre_input_hook = &a_tty_rl_pre_input;
420 a_tty_sigs_up();
421 n_TERMCAP_SUSPEND(FAL0);
422 line = readline(prompt != NULL ? prompt : "");
423 n_TERMCAP_RESUME(FAL0);
424 a_tty_sigs_down();
426 if(line == NULL){
427 nn = -1;
428 goto jleave;
430 n = strlen(line);
432 if(n >= *linesize){
433 *linesize = LINESIZE + n +1;
434 *linebuf = (srealloc)(*linebuf, *linesize SMALLOC_DEBUG_ARGSCALL);
436 memcpy(*linebuf, line, n);
437 (free)(line);
438 (*linebuf)[n] = '\0';
439 nn = (int)n;
440 jleave:
441 NYD_LEAVE;
442 return nn;
445 FL void
446 n_tty_addhist(char const *s, bool_t isgabby){
447 NYD_ENTER;
448 UNUSED(s);
449 UNUSED(isgabby);
451 # ifdef HAVE_HISTORY
452 if(!(pstate & PS_LINE_EDITOR_INIT) || (isgabby && !ok_blook(history_gabby)))
453 goto jleave;
454 a_TTY_CHECK_ADDHIST(s, goto jleave);
455 hold_all_sigs(); /* XXX too heavy */
456 add_history(s); /* XXX yet we jump away! */
457 rele_all_sigs(); /* XXX remove jumps */
458 jleave:
459 # endif
460 NYD_LEAVE;
463 # ifdef HAVE_HISTORY
464 FL int
465 c_history(void *v){
466 C_HISTORY_SHARED;
468 jlist:{
469 FILE *fp;
470 HISTORY_STATE *hs;
471 HIST_ENTRY **hl;
472 ul_i i, b;
474 if((fp = Ftmp(NULL, "hist", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
475 n_perr(_("tmpfile"), 0);
476 v = NULL;
477 goto jleave;
480 hs = history_get_history_state();
482 for(i = (ul_i)hs->length, hl = hs->entries + i, b = 0; i > 0; --i){
483 char *cp = (*--hl)->line;
484 size_t sl = strlen(cp);
486 fprintf(fp, "%4lu. %-50.50s (%4lu+%2lu B)\n", i, cp, b, sl);
487 b += sl;
490 page_or_print(fp, (size_t)hs->length);
491 Fclose(fp);
493 goto jleave;
495 jclear:
496 clear_history();
497 goto jleave;
499 jentry:{
500 HISTORY_STATE *hs = history_get_history_state();
502 if(UICMP(z, entry, <=, hs->length))
503 v = temporary_arg_v_store = hs->entries[entry - 1]->line;
504 else
505 v = NULL;
507 goto jleave;
509 # endif /* HAVE_HISTORY */
510 #endif /* HAVE_READLINE */
513 * MLE: the Mailx-Line-Editor, our homebrew editor
514 * (inspired from NetBSDs sh(1) and dash(1)s hetio.c).
516 * Only used in interactive mode, simply use STDIN_FILENO as point of interest.
517 * TODO . This code should be splitted in funs/raw input/bind modules.
518 * TODO . After I/O layer rewrite, also "output to STDIN_FILENO".
519 * TODO . We work with wide characters, but not for buffer takeovers and
520 * TODO cell2save()ings. This should be changed. For the former the buffer
521 * TODO thus needs to be converted to wide first, and then simply be fed in.
522 * TODO . We repaint too much. To overcome this use the same approach that my
523 * TODO terminal library uses, add a true "virtual screen line" that stores
524 * TODO the actually visible content, keep a notion of "first modified slot"
525 * TODO and "last modified slot" (including "unknown" and "any" specials),
526 * TODO update that virtual instead, then synchronize what has truly changed.
527 * TODO I.e., add an indirection layer.
528 * TODO . No BIDI support.
529 * TODO . `bind': we currently use only one lookup tree.
530 * TODO For absolute graceful behaviour in conjunction (with HAVE_TERMCAP) we
531 * TODO need a lower level tree, which possibly combines bytes into "symbolic
532 * TODO wchar_t values", into "keys" that is, as applicable, and an upper
533 * TODO layer which only works on "keys" in order to possibly combine them
534 * TODO into key sequences. We can reuse existent tree code for that.
535 * TODO We need an additional hashmap which maps termcap/terminfo names to
536 * TODO (their byte representations and) a dynamically assigned unique
537 * TODO "symbolic wchar_t value". This implies we may have incompatibilities
538 * TODO when __STDC_ISO_10646__ is not defined. Also we do need takeover-
539 * TODO bytes storage, but it can be a string_creat_auto in the line struct.
540 * TODO Until then we can run into ambiguities; in rare occasions.
542 #ifdef HAVE_MLE
543 /* To avoid memory leaks etc. with the current codebase that simply longjmp(3)s
544 * we're forced to use the very same buffer--the one that is passed through to
545 * us from the outside--to store anything we need, i.e., a "struct cell[]", and
546 * convert that on-the-fly back to the plain char* result once we're done.
547 * To simplify our live, use savestr() buffers for all other needed memory */
549 # ifdef HAVE_KEY_BINDINGS
550 /* Default *bind-timeout* key-sequence continuation timeout, in tenths of
551 * a second. Must fit in 8-bit! Update the manual upon change! */
552 # define a_TTY_BIND_TIMEOUT 2
553 # define a_TTY_BIND_TIMEOUT_MAX SI8_MAX
555 n_CTAV(a_TTY_BIND_TIMEOUT_MAX <= UI8_MAX);
557 /* We have a chicken-and-egg problem with `bind' and our termcap layer,
558 * because we may not initialize the latter automatically to allow users to
559 * specify *termcap-disable* and let it mean exactly that.
560 * On the other hand users can be expected to use `bind' in resource file(s).
561 * Therefore bindings which involve termcap/terminfo sequences, and which are
562 * defined before PS_STARTED signals usability of termcap/terminfo, will be
563 * (partially) delayed until tty_init() is called.
564 * And we preallocate space for the expansion of the resolved capability */
565 # define a_TTY_BIND_CAPNAME_MAX 15
566 # define a_TTY_BIND_CAPEXP_ROUNDUP 16
568 n_CTAV(ISPOW2(a_TTY_BIND_CAPEXP_ROUNDUP));
569 n_CTA(a_TTY_BIND_CAPEXP_ROUNDUP <= SI8_MAX / 2, "Variable must fit in 6-bit");
570 n_CTA(a_TTY_BIND_CAPEXP_ROUNDUP >= 8, "Variable too small");
571 # endif /* HAVE_KEY_BINDINGS */
573 /* The maximum size (of a_tty_cell's) in a line */
574 # define a_TTY_LINE_MAX SI32_MAX
576 /* (Some more CTAs around) */
577 n_CTA(a_TTY_LINE_MAX <= SI32_MAX,
578 "a_TTY_LINE_MAX larger than SI32_MAX, but the MLE uses 32-bit arithmetic");
580 /* When shall the visual screen be scrolled, in % of usable screen width */
581 # define a_TTY_SCROLL_MARGIN_LEFT 15
582 # define a_TTY_SCROLL_MARGIN_RIGHT 10
584 /* fexpand() flags for expand-on-tab */
585 # define a_TTY_TAB_FEXP_FL (FEXP_FULL | FEXP_SILENT | FEXP_MULTIOK)
587 /* Columns to ripoff: outermost may not be touched, plus position indicator.
588 * Must thus be at least 1, but should be >= 1+4 to dig the position indicator
589 * that we place (if there is sufficient space) */
590 # define a_TTY_WIDTH_RIPOFF 5
592 /* The implementation of the MLE functions always exists, and is based upon
593 * the a_TTY_BIND_FUN_* constants, so most of this enum is always necessary */
594 enum a_tty_bind_flags{
595 # ifdef HAVE_KEY_BINDINGS
596 a_TTY_BIND_RESOLVE = 1<<8, /* Term cap. yet needs to be resolved */
597 a_TTY_BIND_DEFUNCT = 1<<9, /* Unicode/term cap. used but not avail. */
598 a_TTY__BIND_MASK = a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT,
599 /* MLE fun assigned to a one-byte-sequence: this may be used for special
600 * key-sequence bypass processing */
601 a_TTY_BIND_MLE1CNTRL = 1<<10,
602 a_TTY_BIND_NOCOMMIT = 1<<11, /* Expansion shall be editable */
603 # endif
605 /* MLE internal commands */
606 a_TTY_BIND_FUN_INTERNAL = 1<<15,
607 a_TTY__BIND_FUN_SHIFT = 16,
608 a_TTY__BIND_FUN_SHIFTMAX = 24,
609 a_TTY__BIND_FUN_MASK = ((1 << a_TTY__BIND_FUN_SHIFTMAX) - 1) &
610 ~((1 << a_TTY__BIND_FUN_SHIFT) - 1),
611 # define a_TTY_BIND_FUN_REDUCE(X) \
612 (((ui32_t)(X) & a_TTY__BIND_FUN_MASK) >> a_TTY__BIND_FUN_SHIFT)
613 # define a_TTY_BIND_FUN_EXPAND(X) \
614 (((ui32_t)(X) & (a_TTY__BIND_FUN_MASK >> a_TTY__BIND_FUN_SHIFT)) << \
615 a_TTY__BIND_FUN_SHIFT)
616 # undef a_X
617 # define a_X(N,I)\
618 a_TTY_BIND_FUN_ ## N = a_TTY_BIND_FUN_EXPAND(I),
620 a_X(BELL, 0)
621 a_X(GO_BWD, 1) a_X(GO_FWD, 2)
622 a_X(GO_WORD_BWD, 3) a_X(GO_WORD_FWD, 4)
623 a_X(GO_HOME, 5) a_X(GO_END, 6)
624 a_X(DEL_BWD, 7) a_X(DEL_FWD, 8)
625 a_X(SNARF_WORD_BWD, 9) a_X(SNARF_WORD_FWD, 10)
626 a_X(SNARF_END, 11) a_X(SNARF_LINE, 12)
627 a_X(HIST_BWD, 13) a_X(HIST_FWD, 14)
628 a_X(HIST_SRCH_BWD, 15) a_X(HIST_SRCH_FWD, 16)
629 a_X(REPAINT, 17)
630 a_X(QUOTE_RNDTRIP, 18)
631 a_X(PROMPT_CHAR, 19)
632 a_X(COMPLETE, 20)
633 a_X(PASTE, 21)
635 a_X(CANCEL, 22)
636 a_X(RESET, 23)
637 a_X(FULLRESET, 24)
638 a_X(COMMIT, 25) /* Must be last one! */
639 # undef a_X
641 a_TTY__BIND_LAST = 1<<25
643 # ifdef HAVE_KEY_BINDINGS
644 n_CTA((ui32_t)a_TTY_BIND_RESOLVE > (ui32_t)n__LEXINPUT_CTX_MAX,
645 "Bit carrier lower boundary must be raised to avoid value sharing");
646 # endif
647 n_CTA(a_TTY_BIND_FUN_EXPAND(a_TTY_BIND_FUN_COMMIT) <
648 (1 << a_TTY__BIND_FUN_SHIFTMAX),
649 "Bit carrier range must be expanded to represent necessary bits");
650 n_CTA(a_TTY__BIND_LAST >= (1 << a_TTY__BIND_FUN_SHIFTMAX),
651 "Bit carrier upper boundary must be raised to avoid value sharing");
652 n_CTA(UICMP(64, a_TTY__BIND_LAST, <=, SI32_MAX),
653 "Flag bits excess storage datatype" /* And we need one bit free */);
655 enum a_tty_fun_status{
656 a_TTY_FUN_STATUS_OK, /* Worked, next character */
657 a_TTY_FUN_STATUS_COMMIT, /* Line done */
658 a_TTY_FUN_STATUS_RESTART, /* Complete restart, reset multibyte etc. */
659 a_TTY_FUN_STATUS_END /* End, return EOF */
662 enum a_tty_visual_flags{
663 a_TTY_VF_NONE,
664 a_TTY_VF_MOD_CURSOR = 1<<0, /* Cursor moved */
665 a_TTY_VF_MOD_CONTENT = 1<<1, /* Content modified */
666 a_TTY_VF_MOD_DIRTY = 1<<2, /* Needs complete repaint */
667 a_TTY_VF_MOD_SINGLE = 1<<3, /* TODO Drop when indirection as above comes */
668 a_TTY_VF_REFRESH = a_TTY_VF_MOD_DIRTY | a_TTY_VF_MOD_CURSOR |
669 a_TTY_VF_MOD_CONTENT | a_TTY_VF_MOD_SINGLE,
670 a_TTY_VF_BELL = 1<<8, /* Ring the bell */
671 a_TTY_VF_SYNC = 1<<9, /* Flush/Sync I/O channel */
673 a_TTY_VF_ALL_MASK = a_TTY_VF_REFRESH | a_TTY_VF_BELL | a_TTY_VF_SYNC,
674 a_TTY__VF_LAST = a_TTY_VF_SYNC
677 # ifdef HAVE_KEY_BINDINGS
678 struct a_tty_bind_ctx{
679 struct a_tty_bind_ctx *tbc_next;
680 char *tbc_seq; /* quence as given (poss. re-quoted), in .tb__buf */
681 char *tbc_exp; /* ansion, in .tb__buf */
682 /* The .tbc_seq'uence with any terminal capabilities resolved; in fact an
683 * array of structures, the first entry of which is {si32_t buf_len_iscap;}
684 * where the signed bit indicates whether the buffer is a resolved terminal
685 * capability instead of a (possibly multibyte) character. In .tbc__buf */
686 char *tbc_cnv;
687 ui32_t tbc_seq_len;
688 ui32_t tbc_exp_len;
689 ui32_t tbc_cnv_len;
690 ui32_t tbc_flags;
691 char tbc__buf[VFIELD_SIZE(0)];
694 struct a_tty_bind_ctx_map{
695 enum n_lexinput_flags tbcm_ctx;
696 char const tbcm_name[12]; /* Name of `bind' context */
698 # endif /* HAVE_KEY_BINDINGS */
700 struct a_tty_bind_default_tuple{
701 bool_t tbdt_iskey; /* Whether this is a control key; else termcap query */
702 char tbdt_ckey; /* Control code */
703 ui16_t tbdt_query; /* enum n_termcap_query (instead) */
704 char tbdt_exp[12]; /* String or [0]=NUL/[1]=BIND_FUN_REDUCE() */
706 n_CTA(n__TERMCAP_QUERY_MAX <= UI16_MAX,
707 "Enumeration cannot be stored in datatype");
709 # ifdef HAVE_KEY_BINDINGS
710 struct a_tty_bind_parse_ctx{
711 char const *tbpc_cmd; /* Command which parses */
712 char const *tbpc_in_seq; /* In: key sequence */
713 struct str tbpc_exp; /* In/Out: expansion (or NULL) */
714 struct a_tty_bind_ctx *tbpc_tbcp; /* Out: if yet existent */
715 struct a_tty_bind_ctx *tbpc_ltbcp; /* Out: the one before .tbpc_tbcp */
716 char *tbpc_seq; /* Out: normalized sequence */
717 char *tbpc_cnv; /* Out: sequence when read(2)ing it */
718 ui32_t tbpc_seq_len;
719 ui32_t tbpc_cnv_len;
720 ui32_t tbpc_flags; /* n_lexinput_flags | a_tty_bind_flags */
721 ui8_t tbpc__dummy[4];
724 /* Input character tree */
725 struct a_tty_bind_tree{
726 struct a_tty_bind_tree *tbt_sibling; /* s at same level */
727 struct a_tty_bind_tree *tbt_childs; /* Sequence continues.. here */
728 struct a_tty_bind_tree *tbt_parent;
729 struct a_tty_bind_ctx *tbt_bind; /* NULL for intermediates */
730 wchar_t tbt_char; /* acter this level represents */
731 bool_t tbt_isseq; /* Belongs to multibyte sequence */
732 bool_t tbt_isseq_trail; /* ..is trailing byte of it */
733 ui8_t tbt__dummy[2];
735 # endif /* HAVE_KEY_BINDINGS */
737 struct a_tty_cell{
738 wchar_t tc_wc;
739 ui16_t tc_count; /* ..of bytes */
740 ui8_t tc_width; /* Visual width; TAB==UI8_MAX! */
741 bool_t tc_novis; /* Don't display visually as such (control character) */
742 char tc_cbuf[MB_LEN_MAX * 2]; /* .. plus reset shift sequence */
745 struct a_tty_global{
746 struct a_tty_line *tg_line; /* To be able to access it from signal hdl */
747 # ifdef HAVE_HISTORY
748 struct a_tty_hist *tg_hist;
749 struct a_tty_hist *tg_hist_tail;
750 size_t tg_hist_size;
751 size_t tg_hist_size_max;
752 # endif
753 # ifdef HAVE_KEY_BINDINGS
754 ui32_t tg_bind_cnt; /* Overall number of bindings */
755 bool_t tg_bind_isdirty;
756 bool_t tg_bind_isbuild;
757 char tg_bind_shcut_cancel[n__LEXINPUT_CTX_MAX][5];
758 char tg_bind_shcut_prompt_char[n__LEXINPUT_CTX_MAX][5];
759 struct a_tty_bind_ctx *tg_bind[n__LEXINPUT_CTX_MAX];
760 struct a_tty_bind_tree *tg_bind_tree[n__LEXINPUT_CTX_MAX][HSHSIZE];
761 # endif
762 struct termios tg_tios_old;
763 struct termios tg_tios_new;
765 n_CTA(n__LEXINPUT_CTX_MAX == 2,
766 "Value results in array sizes that results in bad structure layout");
768 # ifdef HAVE_HISTORY
769 struct a_tty_hist{
770 struct a_tty_hist *th_older;
771 struct a_tty_hist *th_younger;
772 # ifdef HAVE_BYTE_ORDER_LITTLE
773 ui32_t th_isgabby : 1;
774 # endif
775 ui32_t th_len : 31;
776 # ifndef HAVE_BYTE_ORDER_LITTLE
777 ui32_t th_isgabby : 1;
778 # endif
779 char th_dat[VFIELD_SIZE(sizeof(ui32_t))];
781 # endif
783 struct a_tty_line{
784 /* Caller pointers */
785 char **tl_x_buf;
786 size_t *tl_x_bufsize;
787 /* Input processing */
788 # ifdef HAVE_KEY_BINDINGS
789 wchar_t tl_bind_takeover; /* Leftover byte to consume next */
790 ui8_t tl_bind_timeout; /* In-seq. inter-byte-timer, in 1/10th secs */
791 ui8_t tl__bind_dummy[3];
792 char (*tl_bind_shcut_cancel)[5]; /* Special _CANCEL shortcut control */
793 char (*tl_bind_shcut_prompt_char)[5]; /* ..for _PROMPT_CHAR */
794 struct a_tty_bind_tree *(*tl_bind_tree_hmap)[HSHSIZE]; /* Bind lookup tree */
795 struct a_tty_bind_tree *tl_bind_tree;
796 # endif
797 char const *tl_reenter_after_cmd; /* `bind' cmd to exec, then re-readline */
798 /* Line data / content handling */
799 ui32_t tl_count; /* ..of a_tty_cell's (<= a_TTY_LINE_MAX) */
800 ui32_t tl_cursor; /* Current a_tty_cell insertion point */
801 union{
802 char *cbuf; /* *.tl_x_buf */
803 struct a_tty_cell *cells;
804 } tl_line;
805 struct str tl_defc; /* Current default content */
806 size_t tl_defc_cursor_byte; /* Desired position of cursor after takeover */
807 struct str tl_savec; /* Saved default content */
808 struct str tl_pastebuf; /* Last snarfed data */
809 # ifdef HAVE_HISTORY
810 struct a_tty_hist *tl_hist; /* History cursor */
811 # endif
812 ui32_t tl_count_max; /* ..before buffer needs to grow */
813 /* Visual data representation handling */
814 ui32_t tl_vi_flags; /* enum a_tty_visual_flags */
815 ui32_t tl_lst_count; /* .tl_count after last sync */
816 ui32_t tl_lst_cursor; /* .tl_cursor after last sync */
817 /* TODO Add another indirection layer by adding a tl_phy_line of
818 * TODO a_tty_cell objects, incorporate changes in visual layer,
819 * TODO then check what _really_ has changed, sync those changes only */
820 struct a_tty_cell const *tl_phy_start; /* First visible cell, left border */
821 ui32_t tl_phy_cursor; /* Physical cursor position */
822 bool_t tl_quote_rndtrip; /* For _kht() expansion */
823 ui8_t tl__dummy2[3];
824 ui32_t tl_prompt_length; /* Preclassified (TODO needed as a_tty_cell) */
825 ui32_t tl_prompt_width;
826 char const *tl_prompt; /* Preformatted prompt (including colours) */
827 /* .tl_pos_buf is a hack */
828 # ifdef HAVE_COLOUR
829 char *tl_pos_buf; /* mle-position colour-on, [4], reset seq. */
830 char *tl_pos; /* Address of the [4] */
831 # endif
834 # ifdef HAVE_KEY_BINDINGS
835 /* C99: use [INDEX]={} */
836 n_CTAV(n_LEXINPUT_CTX_BASE == 0);
837 n_CTAV(n_LEXINPUT_CTX_COMPOSE == 1);
838 static struct a_tty_bind_ctx_map const
839 a_tty_bind_ctx_maps[n__LEXINPUT_CTX_MAX] = {
840 {n_LEXINPUT_CTX_BASE, "base"},
841 {n_LEXINPUT_CTX_COMPOSE, "compose"}
844 /* Special functions which our MLE provides internally.
845 * Update the manual upon change! */
846 static char const a_tty_bind_fun_names[][24] = {
847 # undef a_X
848 # define a_X(I,N) \
849 n_FIELD_INITI(a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## I)) "mle-" N "\0",
851 a_X(BELL, "bell")
852 a_X(GO_BWD, "go-bwd") a_X(GO_FWD, "go-fwd")
853 a_X(GO_WORD_BWD, "go-word-bwd") a_X(GO_WORD_FWD, "go-word-fwd")
854 a_X(GO_HOME, "go-home") a_X(GO_END, "go-end")
855 a_X(DEL_BWD, "del-bwd") a_X(DEL_FWD, "del-fwd")
856 a_X(SNARF_WORD_BWD, "snarf-word-bwd") a_X(SNARF_WORD_FWD, "snarf-word-fwd")
857 a_X(SNARF_END, "snarf-end") a_X(SNARF_LINE, "snarf-line")
858 a_X(HIST_BWD, "hist-bwd") a_X(HIST_FWD, "hist-fwd")
859 a_X(HIST_SRCH_BWD, "hist-srch-bwd") a_X(HIST_SRCH_FWD, "hist-srch-fwd")
860 a_X(REPAINT, "repaint")
861 a_X(QUOTE_RNDTRIP, "quote-rndtrip")
862 a_X(PROMPT_CHAR, "prompt-char")
863 a_X(COMPLETE, "complete")
864 a_X(PASTE, "paste")
866 a_X(CANCEL, "cancel")
867 a_X(RESET, "reset")
868 a_X(FULLRESET, "fullreset")
869 a_X(COMMIT, "commit")
871 # undef a_X
873 # endif /* HAVE_KEY_BINDINGS */
875 /* The default key bindings (unless disallowed). Update manual upon change!
876 * A logical subset of this table is also used if !HAVE_KEY_BINDINGS (more
877 * expensive than a switch() on control codes directly, but less redundant) */
878 static struct a_tty_bind_default_tuple const a_tty_bind_default_tuples[] = {
879 # undef a_X
880 # define a_X(K,S) \
881 {TRU1, K, 0, {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
883 a_X('A', GO_HOME)
884 a_X('B', GO_BWD)
885 /* C: SIGINT */
886 a_X('D', DEL_FWD)
887 a_X('E', GO_END)
888 a_X('F', GO_FWD)
889 a_X('G', RESET)
890 a_X('H', DEL_BWD)
891 a_X('I', COMPLETE)
892 a_X('J', COMMIT)
893 a_X('K', SNARF_END)
894 a_X('L', REPAINT)
895 /* M: same as J */
896 a_X('N', HIST_FWD)
897 /* O: below */
898 a_X('P', HIST_BWD)
899 a_X('Q', QUOTE_RNDTRIP)
900 a_X('R', HIST_SRCH_BWD)
901 a_X('S', HIST_SRCH_FWD)
902 a_X('T', PASTE)
903 a_X('U', SNARF_LINE)
904 a_X('V', PROMPT_CHAR)
905 a_X('W', SNARF_WORD_BWD)
906 a_X('X', GO_WORD_FWD)
907 a_X('Y', GO_WORD_BWD)
908 /* Z: SIGTSTP */
910 a_X('[', CANCEL)
911 /* \: below */
912 /* ]: below */
913 /* ^: below */
914 a_X('_', SNARF_WORD_FWD)
916 a_X('?', DEL_BWD)
918 # undef a_X
919 # define a_X(K,S) {TRU1, K, 0, {S}},
921 a_X('O', "dt")
922 a_X('\\', "z+")
923 a_X(']', "z$")
924 a_X('^', "z0")
926 # ifdef HAVE_KEY_BINDINGS
927 # undef a_X
928 # define a_X(Q,S) \
929 {FAL0, '\0', n_TERMCAP_QUERY_ ## Q,\
930 {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
932 a_X(key_backspace, DEL_BWD) a_X(key_dc, DEL_FWD)
933 a_X(key_eol, SNARF_END)
934 a_X(key_home, GO_HOME) a_X(key_end, GO_END)
935 a_X(key_left, GO_BWD) a_X(key_right, GO_FWD)
936 a_X(key_sleft, GO_HOME) a_X(key_sright, GO_END)
937 a_X(key_up, HIST_BWD) a_X(key_down, HIST_FWD)
939 # undef a_X
940 # define a_X(Q,S) {FAL0, '\0', n_TERMCAP_QUERY_ ## Q, {S}},
942 a_X(key_shome, "z0") a_X(key_send, "z$")
943 a_X(xkey_sup, "z0") a_X(xkey_sdown, "z$")
944 a_X(key_ppage, "z-") a_X(key_npage, "z+")
945 a_X(xkey_cup, "dotmove-") a_X(xkey_cdown, "dotmove+")
947 # endif /* HAVE_KEY_BINDINGS */
948 # undef a_X
951 static struct a_tty_global a_tty;
953 /* Change from canonical to raw, non-canonical mode, and way back */
954 static void a_tty_term_mode(bool_t raw);
956 /* Adjust an active raw mode to use / not use a timeout */
957 # ifdef HAVE_KEY_BINDINGS
958 static void a_tty_term_rawmode_timeout(struct a_tty_line *tlp, bool_t enable);
959 # endif
961 /* 0-X (2), UI8_MAX == \t / TAB */
962 static ui8_t a_tty_wcwidth(wchar_t wc);
964 /* Memory / cell / word generics */
965 static void a_tty_check_grow(struct a_tty_line *tlp, ui32_t no
966 SMALLOC_DEBUG_ARGS);
967 static ssize_t a_tty_cell2dat(struct a_tty_line *tlp);
968 static void a_tty_cell2save(struct a_tty_line *tlp);
970 /* Save away data bytes of given range (max = non-inclusive) */
971 static void a_tty_copy2paste(struct a_tty_line *tlp, struct a_tty_cell *tcpmin,
972 struct a_tty_cell *tcpmax);
974 /* Ask user for hexadecimal number, interpret as UTF-32 */
975 static wchar_t a_tty_vinuni(struct a_tty_line *tlp);
977 /* Visual screen synchronization */
978 static bool_t a_tty_vi_refresh(struct a_tty_line *tlp);
980 static bool_t a_tty_vi__paint(struct a_tty_line *tlp);
982 /* Search for word boundary, starting at tl_cursor, in "dir"ection (<> 0).
983 * Return <0 when moving is impossible (backward direction but in position 0,
984 * forward direction but in outermost column), and relative distance to
985 * tl_cursor otherwise */
986 static si32_t a_tty_wboundary(struct a_tty_line *tlp, si32_t dir);
988 /* Most function implementations */
989 static void a_tty_khome(struct a_tty_line *tlp, bool_t dobell);
990 static void a_tty_kend(struct a_tty_line *tlp);
991 static void a_tty_kbs(struct a_tty_line *tlp);
992 static void a_tty_ksnarf(struct a_tty_line *tlp, bool_t cplline, bool_t dobell);
993 static si32_t a_tty_kdel(struct a_tty_line *tlp);
994 static void a_tty_kleft(struct a_tty_line *tlp);
995 static void a_tty_kright(struct a_tty_line *tlp);
996 static void a_tty_ksnarfw(struct a_tty_line *tlp, bool_t fwd);
997 static void a_tty_kgow(struct a_tty_line *tlp, si32_t dir);
998 static bool_t a_tty_kother(struct a_tty_line *tlp, wchar_t wc);
999 static ui32_t a_tty_kht(struct a_tty_line *tlp);
1000 # ifdef HAVE_HISTORY
1001 static ui32_t a_tty__khist_shared(struct a_tty_line *tlp,
1002 struct a_tty_hist *thp);
1003 static ui32_t a_tty_khist(struct a_tty_line *tlp, bool_t fwd);
1004 static ui32_t a_tty_khist_search(struct a_tty_line *tlp, bool_t fwd);
1005 # endif
1007 /* Handle a function */
1008 static enum a_tty_fun_status a_tty_fun(struct a_tty_line *tlp,
1009 enum a_tty_bind_flags tbf, size_t *len);
1011 /* Readline core */
1012 static ssize_t a_tty_readline(struct a_tty_line *tlp, size_t len
1013 SMALLOC_DEBUG_ARGS);
1015 # ifdef HAVE_KEY_BINDINGS
1016 /* Find context or -1 */
1017 static enum n_lexinput_flags a_tty_bind_ctx_find(char const *name);
1019 /* Create (or replace, if allowed) a binding */
1020 static bool_t a_tty_bind_create(struct a_tty_bind_parse_ctx *tbpcp,
1021 bool_t replace);
1023 /* Shared implementation to parse `bind' and `unbind' "key-sequence" and
1024 * "expansion" command line arguments into something that we can work with */
1025 static bool_t a_tty_bind_parse(bool_t isbindcmd,
1026 struct a_tty_bind_parse_ctx *tbpcp);
1028 /* Lazy resolve a termcap(5)/terminfo(5) (or *termcap*!) capability */
1029 static void a_tty_bind_resolve(struct a_tty_bind_ctx *tbcp);
1031 /* Delete an existing binding */
1032 static void a_tty_bind_del(struct a_tty_bind_parse_ctx *tbpcp);
1034 /* Life cycle of all input node trees */
1035 static void a_tty_bind_tree_build(void);
1036 static void a_tty_bind_tree_teardown(void);
1038 static void a_tty__bind_tree_add(ui32_t hmap_idx,
1039 struct a_tty_bind_tree *store[HSHSIZE],
1040 struct a_tty_bind_ctx *tbcp);
1041 static struct a_tty_bind_tree *a_tty__bind_tree_add_wc(
1042 struct a_tty_bind_tree **treep, struct a_tty_bind_tree *parentp,
1043 wchar_t wc, bool_t isseq);
1044 static void a_tty__bind_tree_free(struct a_tty_bind_tree *tbtp);
1045 # endif /* HAVE_KEY_BINDINGS */
1047 static void
1048 a_tty_term_mode(bool_t raw){
1049 struct termios *tiosp;
1050 NYD2_ENTER;
1052 tiosp = &a_tty.tg_tios_old;
1053 if(!raw)
1054 goto jleave;
1056 /* Always requery the attributes, in case we've been moved from background
1057 * to foreground or however else in between sessions */
1058 /* XXX Always enforce ECHO and ICANON in the OLD attributes - do so as long
1059 * XXX as we don't properly deal with TTIN and TTOU etc. */
1060 tcgetattr(STDIN_FILENO, tiosp);
1061 tiosp->c_lflag |= ECHO | ICANON;
1063 memcpy(&a_tty.tg_tios_new, tiosp, sizeof *tiosp);
1064 tiosp = &a_tty.tg_tios_new;
1065 tiosp->c_cc[VMIN] = 1;
1066 tiosp->c_cc[VTIME] = 0;
1067 /* Enable ^\, ^Q and ^S to be used for key bindings */
1068 tiosp->c_cc[VQUIT] = tiosp->c_cc[VSTART] = tiosp->c_cc[VSTOP] = '\0';
1069 tiosp->c_iflag &= ~(ISTRIP | IGNCR);
1070 tiosp->c_lflag &= ~(ECHO /*| ECHOE | ECHONL */| ICANON | IEXTEN);
1071 jleave:
1072 tcsetattr(STDIN_FILENO, TCSADRAIN, tiosp);
1073 NYD2_LEAVE;
1076 # ifdef HAVE_KEY_BINDINGS
1077 static void
1078 a_tty_term_rawmode_timeout(struct a_tty_line *tlp, bool_t enable){
1079 NYD2_ENTER;
1080 if(enable){
1081 ui8_t bt;
1083 a_tty.tg_tios_new.c_cc[VMIN] = 0;
1084 if((bt = tlp->tl_bind_timeout) == 0)
1085 bt = a_TTY_BIND_TIMEOUT;
1086 a_tty.tg_tios_new.c_cc[VTIME] = bt;
1087 }else{
1088 a_tty.tg_tios_new.c_cc[VMIN] = 1;
1089 a_tty.tg_tios_new.c_cc[VTIME] = 0;
1091 tcsetattr(STDIN_FILENO, TCSANOW, &a_tty.tg_tios_new);
1092 NYD2_LEAVE;
1094 # endif /* HAVE_KEY_BINDINGS */
1096 static ui8_t
1097 a_tty_wcwidth(wchar_t wc){
1098 ui8_t rv;
1099 NYD2_ENTER;
1101 /* Special case the backslash at first */
1102 if(wc == '\t')
1103 rv = UI8_MAX;
1104 else{
1105 int i;
1107 # ifdef HAVE_WCWIDTH
1108 rv = ((i = wcwidth(wc)) > 0) ? (ui8_t)i : 0;
1109 # else
1110 rv = iswprint(wc) ? 1 + (wc >= 0x1100u) : 0; /* TODO use S-CText */
1111 # endif
1113 NYD2_LEAVE;
1114 return rv;
1117 static void
1118 a_tty_check_grow(struct a_tty_line *tlp, ui32_t no SMALLOC_DEBUG_ARGS){
1119 ui32_t cmax;
1120 NYD2_ENTER;
1122 if(UNLIKELY((cmax = tlp->tl_count + no) > tlp->tl_count_max)){
1123 size_t i;
1125 i = cmax * sizeof(struct a_tty_cell) + 2 * sizeof(struct a_tty_cell);
1126 if(LIKELY(i >= *tlp->tl_x_bufsize)){
1127 hold_all_sigs(); /* XXX v15 drop */
1128 i <<= 1;
1129 tlp->tl_line.cbuf =
1130 *tlp->tl_x_buf = (srealloc)(*tlp->tl_x_buf, i SMALLOC_DEBUG_ARGSCALL);
1131 rele_all_sigs(); /* XXX v15 drop */
1133 tlp->tl_count_max = cmax;
1134 *tlp->tl_x_bufsize = i;
1136 NYD2_LEAVE;
1139 static ssize_t
1140 a_tty_cell2dat(struct a_tty_line *tlp){
1141 size_t len, i;
1142 NYD2_ENTER;
1144 len = 0;
1146 if(LIKELY((i = tlp->tl_count) > 0)){
1147 struct a_tty_cell const *tcap;
1149 tcap = tlp->tl_line.cells;
1151 memcpy(tlp->tl_line.cbuf + len, tcap->tc_cbuf, tcap->tc_count);
1152 len += tcap->tc_count;
1153 }while(++tcap, --i > 0);
1156 tlp->tl_line.cbuf[len] = '\0';
1157 NYD2_LEAVE;
1158 return (ssize_t)len;
1161 static void
1162 a_tty_cell2save(struct a_tty_line *tlp){
1163 size_t len, i;
1164 struct a_tty_cell *tcap;
1165 NYD2_ENTER;
1167 tlp->tl_savec.s = NULL;
1168 tlp->tl_savec.l = 0;
1170 if(UNLIKELY(tlp->tl_count == 0))
1171 goto jleave;
1173 for(tcap = tlp->tl_line.cells, len = 0, i = tlp->tl_count; i > 0;
1174 ++tcap, --i)
1175 len += tcap->tc_count;
1177 tlp->tl_savec.s = salloc((tlp->tl_savec.l = len) +1);
1179 for(tcap = tlp->tl_line.cells, len = 0, i = tlp->tl_count; i > 0;
1180 ++tcap, --i){
1181 memcpy(tlp->tl_savec.s + len, tcap->tc_cbuf, tcap->tc_count);
1182 len += tcap->tc_count;
1184 tlp->tl_savec.s[len] = '\0';
1185 jleave:
1186 NYD2_LEAVE;
1189 static void
1190 a_tty_copy2paste(struct a_tty_line *tlp, struct a_tty_cell *tcpmin,
1191 struct a_tty_cell *tcpmax){
1192 char *cp;
1193 struct a_tty_cell *tcp;
1194 size_t l;
1195 NYD2_ENTER;
1197 l = 0;
1198 for(tcp = tcpmin; tcp < tcpmax; ++tcp)
1199 l += tcp->tc_count;
1201 tlp->tl_pastebuf.s = cp = salloc((tlp->tl_pastebuf.l = l) +1);
1203 l = 0;
1204 for(tcp = tcpmin; tcp < tcpmax; cp += l, ++tcp)
1205 memcpy(cp, tcp->tc_cbuf, l = tcp->tc_count);
1206 *cp = '\0';
1207 NYD2_LEAVE;
1210 static wchar_t
1211 a_tty_vinuni(struct a_tty_line *tlp){
1212 char buf[16], *eptr;
1213 union {size_t i; long l;} u;
1214 wchar_t wc;
1215 NYD2_ENTER;
1217 wc = '\0';
1219 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr) ||
1220 !n_termcap_cmd(n_TERMCAP_CMD_ce, 0, -1))
1221 goto jleave;
1223 /* C99 */{
1224 struct str const *cpre, *csuf;
1225 #ifdef HAVE_COLOUR
1226 struct n_colour_pen *cpen;
1228 cpen = n_colour_pen_create(n_COLOUR_ID_MLE_PROMPT, NULL);
1229 if((cpre = n_colour_pen_to_str(cpen)) != NULL)
1230 csuf = n_colour_reset_to_str();
1231 else
1232 csuf = NULL;
1233 #else
1234 cpre = csuf = NULL;
1235 #endif
1236 printf(_("%sPlease enter Unicode code point:%s "),
1237 (cpre != NULL ? cpre->s : ""), (csuf != NULL ? csuf->s : ""));
1239 fflush(stdout);
1241 buf[sizeof(buf) -1] = '\0';
1242 for(u.i = 0;;){
1243 if(read(STDIN_FILENO, &buf[u.i], 1) != 1){
1244 if(errno == EINTR) /* xxx #if !SA_RESTART ? */
1245 continue;
1246 goto jleave;
1248 if(buf[u.i] == '\n')
1249 break;
1250 if(!hexchar(buf[u.i])){
1251 char const emsg[] = "[0-9a-fA-F]";
1253 LCTA(sizeof emsg <= sizeof(buf));
1254 memcpy(buf, emsg, sizeof emsg);
1255 goto jerr;
1258 putc(buf[u.i], stdout);
1259 fflush(stdout);
1260 if(++u.i == sizeof buf)
1261 goto jerr;
1263 buf[u.i] = '\0';
1265 u.l = strtol(buf, &eptr, 16);
1266 if(u.l <= 0 || u.l >= 0x10FFFF/* XXX magic; CText */ || *eptr != '\0'){
1267 jerr:
1268 n_err(_("\nInvalid input: %s\n"), buf);
1269 goto jleave;
1272 wc = (wchar_t)u.l;
1273 jleave:
1274 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY | (wc == '\0' ? a_TTY_VF_BELL : 0);
1275 NYD2_LEAVE;
1276 return wc;
1279 static bool_t
1280 a_tty_vi_refresh(struct a_tty_line *tlp){
1281 bool_t rv;
1282 NYD2_ENTER;
1284 if(tlp->tl_vi_flags & a_TTY_VF_BELL){
1285 tlp->tl_vi_flags |= a_TTY_VF_SYNC;
1286 if(putchar('\a') == EOF)
1287 goto jerr;
1290 if(tlp->tl_vi_flags & a_TTY_VF_REFRESH){
1291 /* kht may want to restore a cursor position after inserting some
1292 * data somewhere */
1293 if(tlp->tl_defc_cursor_byte > 0){
1294 size_t i, j;
1295 ssize_t k;
1297 a_tty_khome(tlp, FAL0);
1299 i = tlp->tl_defc_cursor_byte;
1300 tlp->tl_defc_cursor_byte = 0;
1301 for(j = 0; tlp->tl_cursor < tlp->tl_count; ++j){
1302 a_tty_kright(tlp);
1303 if((k = tlp->tl_line.cells[j].tc_count) > i)
1304 break;
1305 i -= k;
1309 if(!a_tty_vi__paint(tlp))
1310 goto jerr;
1313 if(tlp->tl_vi_flags & a_TTY_VF_SYNC){
1314 tlp->tl_vi_flags &= ~a_TTY_VF_SYNC;
1315 if(fflush(stdout))
1316 goto jerr;
1319 rv = TRU1;
1320 jleave:
1321 tlp->tl_vi_flags &= ~a_TTY_VF_ALL_MASK;
1322 NYD2_LEAVE;
1323 return rv;
1325 jerr:
1326 clearerr(stdout); /* xxx I/O layer rewrite */
1327 n_err(_("Visual refresh failed! Is $TERM set correctly?\n"
1328 " Setting *line-editor-disable* to get us through!\n"));
1329 ok_bset(line_editor_disable, TRU1);
1330 rv = FAL0;
1331 goto jleave;
1334 static bool_t
1335 a_tty_vi__paint(struct a_tty_line *tlp){
1336 enum{
1337 a_TRUE_RV = a_TTY__VF_LAST<<1, /* Return value bit */
1338 a_HAVE_PROMPT = a_TTY__VF_LAST<<2, /* Have a prompt */
1339 a_SHOW_PROMPT = a_TTY__VF_LAST<<3, /* Shall print the prompt */
1340 a_MOVE_CURSOR = a_TTY__VF_LAST<<4, /* Move visual cursor for user! */
1341 a_LEFT_MIN = a_TTY__VF_LAST<<5, /* On left boundary */
1342 a_RIGHT_MAX = a_TTY__VF_LAST<<6,
1343 a_HAVE_POSITION = a_TTY__VF_LAST<<7, /* Print the position indicator */
1345 /* We carry some flags over invocations (not worth a specific field) */
1346 a_VISIBLE_PROMPT = a_TTY__VF_LAST<<8, /* The prompt is on the screen */
1347 a_PERSIST_MASK = a_VISIBLE_PROMPT,
1348 a__LAST = a_PERSIST_MASK
1351 ui32_t f, w, phy_wid_base, phy_wid, phy_base, phy_cur, cnt, lstcur, cur,
1352 vi_left, vi_right, phy_nxtcur;
1353 struct a_tty_cell const *tccp, *tcp_left, *tcp_right, *tcxp;
1354 NYD2_ENTER;
1355 n_LCTA(UICMP(64, a__LAST, <, UI32_MAX), "Flag bits excess storage datatype");
1357 f = tlp->tl_vi_flags;
1358 tlp->tl_vi_flags = (f & ~(a_TTY_VF_REFRESH | a_PERSIST_MASK)) |
1359 a_TTY_VF_SYNC;
1360 f |= a_TRUE_RV;
1361 if((w = tlp->tl_prompt_length) > 0)
1362 f |= a_HAVE_PROMPT;
1363 f |= a_HAVE_POSITION;
1365 /* XXX We don't have a OnTerminalResize event (see main.c) yet, so we need
1366 * XXX to reevaluate our circumstances over and over again */
1367 /* Don't display prompt or position indicator on very small screens */
1368 if((phy_wid_base = (ui32_t)scrnwidth) <= a_TTY_WIDTH_RIPOFF)
1369 f &= ~(a_HAVE_PROMPT | a_HAVE_POSITION);
1370 else{
1371 phy_wid_base -= a_TTY_WIDTH_RIPOFF;
1373 /* Disable the prompt if the screen is too small; due to lack of some
1374 * indicator simply add a second ripoff */
1375 if((f & a_HAVE_PROMPT) && w + a_TTY_WIDTH_RIPOFF >= phy_wid_base)
1376 f &= ~a_HAVE_PROMPT;
1379 phy_wid = phy_wid_base;
1380 phy_base = 0;
1381 phy_cur = tlp->tl_phy_cursor;
1382 cnt = tlp->tl_count;
1383 lstcur = tlp->tl_lst_cursor;
1385 /* XXX Assume dirty screen if shrunk */
1386 if(cnt < tlp->tl_lst_count)
1387 f |= a_TTY_VF_MOD_DIRTY;
1389 /* TODO Without HAVE_TERMCAP, it would likely be much cheaper to simply
1390 * TODO always "cr + paint + ce + ch", since ce is simulated via spaces.. */
1392 /* Quickshot: if the line is empty, possibly print prompt and out */
1393 if(cnt == 0){
1394 /* In that special case dirty anything if it seems better */
1395 if((f & a_TTY_VF_MOD_CONTENT) || tlp->tl_lst_count > 0)
1396 f |= a_TTY_VF_MOD_DIRTY;
1398 if((f & a_TTY_VF_MOD_DIRTY) && phy_cur != 0){
1399 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
1400 goto jerr;
1401 phy_cur = 0;
1404 if((f & (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)) ==
1405 (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)){
1406 if(fputs(tlp->tl_prompt, stdout) == EOF)
1407 goto jerr;
1408 phy_cur = tlp->tl_prompt_width + 1;
1411 /* May need to clear former line content */
1412 if((f & a_TTY_VF_MOD_DIRTY) &&
1413 !n_termcap_cmd(n_TERMCAP_CMD_ce, phy_cur, -1))
1414 goto jerr;
1416 tlp->tl_phy_start = tlp->tl_line.cells;
1417 goto jleave;
1420 /* Try to get an idea of the visual window */
1422 /* Find the left visual boundary */
1423 phy_wid = (phy_wid >> 1) + (phy_wid >> 2);
1424 if((cur = tlp->tl_cursor) == cnt)
1425 --cur;
1427 w = (tcp_left = tccp = tlp->tl_line.cells + cur)->tc_width;
1428 if(w == UI8_MAX) /* TODO yet TAB == SPC */
1429 w = 1;
1430 while(tcp_left > tlp->tl_line.cells){
1431 ui16_t cw = tcp_left[-1].tc_width;
1433 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1434 cw = 1;
1435 if(w + cw >= phy_wid)
1436 break;
1437 w += cw;
1438 --tcp_left;
1440 vi_left = w;
1442 /* If the left hand side of our visual viewpoint consumes less than half
1443 * of the screen width, show the prompt */
1444 if(tcp_left == tlp->tl_line.cells)
1445 f |= a_LEFT_MIN;
1447 if((f & (a_LEFT_MIN | a_HAVE_PROMPT)) == (a_LEFT_MIN | a_HAVE_PROMPT) &&
1448 w + tlp->tl_prompt_width < phy_wid){
1449 phy_base = tlp->tl_prompt_width;
1450 f |= a_SHOW_PROMPT;
1453 /* Then search for right boundary. We always leave the rightmost column
1454 * empty because some terminals [cw]ould wrap the line if we write into
1455 * that. XXX terminfo(5)/termcap(5) have the semi_auto_right_margin/sam/YE
1456 * XXX capability to indicate this, but we don't look at that */
1457 phy_wid = phy_wid_base - phy_base;
1458 tcp_right = tlp->tl_line.cells + cnt;
1460 while(&tccp[1] < tcp_right){
1461 ui16_t cw = tccp[1].tc_width;
1462 ui32_t i;
1464 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1465 cw = 1;
1466 i = w + cw;
1467 if(i > phy_wid)
1468 break;
1469 w = i;
1470 ++tccp;
1472 vi_right = w - vi_left;
1474 /* If the complete line including prompt fits on the screen, show prompt */
1475 if(--tcp_right == tccp){
1476 f |= a_RIGHT_MAX;
1478 /* Since we did brute-force walk also for the left boundary we may end up
1479 * in a situation were anything effectively fits on the screen, including
1480 * the prompt that is, but were we don't recognize this since we
1481 * restricted the search to fit in some visual viewpoint. Therefore try
1482 * again to extend the left boundary to overcome that */
1483 if(!(f & a_LEFT_MIN)){
1484 struct a_tty_cell const *tc1p = tlp->tl_line.cells;
1485 ui32_t vil1 = vi_left;
1487 assert(!(f & a_SHOW_PROMPT));
1488 w += tlp->tl_prompt_width;
1489 for(tcxp = tcp_left;;){
1490 ui32_t i = tcxp[-1].tc_width;
1492 if(i == UI8_MAX) /* TODO yet TAB == SPC */
1493 i = 1;
1494 vil1 += i;
1495 i += w;
1496 if(i > phy_wid)
1497 break;
1498 w = i;
1499 if(--tcxp == tc1p){
1500 tcp_left = tc1p;
1501 vi_left = vil1;
1502 f |= a_LEFT_MIN;
1503 break;
1506 /*w -= tlp->tl_prompt_width;*/
1509 tcp_right = tccp;
1510 tccp = tlp->tl_line.cells + cur;
1512 if((f & (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT | a_SHOW_PROMPT)) ==
1513 (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT) &&
1514 w + tlp->tl_prompt_width <= phy_wid){
1515 phy_wid -= (phy_base = tlp->tl_prompt_width);
1516 f |= a_SHOW_PROMPT;
1519 /* Try to avoid repainting the complete line - this is possible if the
1520 * cursor "did not leave the screen" and the prompt status hasn't changed.
1521 * I.e., after clamping virtual viewpoint, compare relation to physical */
1522 if((f & (a_TTY_VF_MOD_SINGLE/*FIXME*/ |
1523 a_TTY_VF_MOD_CONTENT/* xxx */ | a_TTY_VF_MOD_DIRTY)) ||
1524 (tcxp = tlp->tl_phy_start) == NULL ||
1525 tcxp > tccp || tcxp <= tcp_right)
1526 f |= a_TTY_VF_MOD_DIRTY;
1527 else{
1528 f |= a_TTY_VF_MOD_DIRTY;
1529 #if 0
1530 struct a_tty_cell const *tcyp;
1531 si32_t cur_displace;
1532 ui32_t phy_lmargin, phy_rmargin, fx, phy_displace;
1534 phy_lmargin = (fx = phy_wid) / 100;
1535 phy_rmargin = fx - (phy_lmargin * a_TTY_SCROLL_MARGIN_RIGHT);
1536 phy_lmargin *= a_TTY_SCROLL_MARGIN_LEFT;
1537 fx = (f & (a_SHOW_PROMPT | a_VISIBLE_PROMPT));
1539 if(fx == 0 || fx == (a_SHOW_PROMPT | a_VISIBLE_PROMPT)){
1541 #endif
1543 goto jpaint;
1545 /* We know what we have to paint, start synchronizing */
1546 jpaint:
1547 assert(phy_cur == tlp->tl_phy_cursor);
1548 assert(phy_wid == phy_wid_base - phy_base);
1549 assert(cnt == tlp->tl_count);
1550 assert(cnt > 0);
1551 assert(lstcur == tlp->tl_lst_cursor);
1552 assert(tccp == tlp->tl_line.cells + cur);
1554 phy_nxtcur = phy_base; /* FIXME only if repaint cpl. */
1556 /* Quickshot: is it only cursor movement within the visible screen? */
1557 if((f & a_TTY_VF_REFRESH) == a_TTY_VF_MOD_CURSOR){
1558 f |= a_MOVE_CURSOR;
1559 goto jcursor;
1562 /* To be able to apply some quick jump offs, clear line if possible */
1563 if(f & a_TTY_VF_MOD_DIRTY){
1564 /* Force complete clearance and cursor reinitialization */
1565 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr) ||
1566 !n_termcap_cmd(n_TERMCAP_CMD_ce, 0, -1))
1567 goto jerr;
1568 tlp->tl_phy_start = tcp_left;
1569 phy_cur = 0;
1572 if((f & (a_TTY_VF_MOD_DIRTY | a_SHOW_PROMPT)) && phy_cur != 0){
1573 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
1574 goto jerr;
1575 phy_cur = 0;
1578 if(f & a_SHOW_PROMPT){
1579 assert(phy_base == tlp->tl_prompt_width);
1580 if(fputs(tlp->tl_prompt, stdout) == EOF)
1581 goto jerr;
1582 phy_cur = phy_nxtcur;
1583 f |= a_VISIBLE_PROMPT;
1584 }else
1585 f &= ~a_VISIBLE_PROMPT;
1587 /* FIXME reposition cursor for paint */
1588 for(w = phy_nxtcur; tcp_left <= tcp_right; ++tcp_left){
1589 ui16_t cw;
1591 cw = tcp_left->tc_width;
1593 if(LIKELY(!tcp_left->tc_novis)){
1594 if(fwrite(tcp_left->tc_cbuf, sizeof *tcp_left->tc_cbuf,
1595 tcp_left->tc_count, stdout) != tcp_left->tc_count)
1596 goto jerr;
1597 }else{ /* XXX Shouldn't be here <-> CText, ui_str.c */
1598 char wbuf[8]; /* XXX magic */
1600 if(options & OPT_UNICODE){
1601 ui32_t wc;
1603 wc = (ui32_t)tcp_left->tc_wc;
1604 if((wc & ~0x1Fu) == 0)
1605 wc |= 0x2400;
1606 else if(wc == 0x7F)
1607 wc = 0x2421;
1608 else
1609 wc = 0x2426;
1610 n_utf32_to_utf8(wc, wbuf);
1611 }else
1612 wbuf[0] = '?', wbuf[1] = '\0';
1614 if(fputs(wbuf, stdout) == EOF)
1615 goto jerr;
1616 cw = 1;
1619 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1620 cw = 1;
1621 w += cw;
1622 if(tcp_left == tccp)
1623 phy_nxtcur = w;
1624 phy_cur += cw;
1627 /* Write something position marker alike if it doesn't fit on screen */
1628 if((f & a_HAVE_POSITION) &&
1629 ((f & (a_LEFT_MIN | a_RIGHT_MAX)) != (a_LEFT_MIN | a_RIGHT_MAX) ||
1630 ((f & a_HAVE_PROMPT) && !(f & a_SHOW_PROMPT)))){
1631 # ifdef HAVE_COLOUR
1632 char *posbuf = tlp->tl_pos_buf, *pos = tlp->tl_pos;
1633 # else
1634 char posbuf[5], *pos = posbuf;
1636 pos[4] = '\0';
1637 # endif
1639 if(phy_cur != (w = phy_wid_base) &&
1640 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = w, 0))
1641 goto jerr;
1643 *pos++ = '|';
1644 if((f & a_LEFT_MIN) && (!(f & a_HAVE_PROMPT) || (f & a_SHOW_PROMPT)))
1645 memcpy(pos, "^.+", 3);
1646 else if(f & a_RIGHT_MAX)
1647 memcpy(pos, ".+$", 3);
1648 else{
1649 /* Theoretical line length limit a_TTY_LINE_MAX, choose next power of
1650 * ten (10 ** 10) to represent 100 percent, since we don't have a macro
1651 * that generates a constant, and i don't trust the standard "u type
1652 * suffix automatically scales" calculate the large number */
1653 static char const itoa[] = "0123456789";
1655 ui64_t const fact100 = (ui64_t)0x3B9ACA00u * 10u, fact = fact100 / 100;
1656 ui32_t i = (ui32_t)(((fact100 / cnt) * tlp->tl_cursor) / fact);
1657 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1659 if(i < 10)
1660 pos[0] = ' ', pos[1] = itoa[i];
1661 else
1662 pos[1] = itoa[i % 10], pos[0] = itoa[i / 10];
1663 pos[2] = '%';
1666 if(fputs(posbuf, stdout) == EOF)
1667 goto jerr;
1668 phy_cur += 4;
1671 /* Users are used to see the cursor right of the point of interest, so we
1672 * need some further adjustments unless in special conditions. Be aware
1673 * that we may have adjusted cur at the beginning, too */
1674 if((cur = tlp->tl_cursor) == 0)
1675 phy_nxtcur = phy_base;
1676 else if(cur != cnt){
1677 ui16_t cw = tccp->tc_width;
1679 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1680 cw = 1;
1681 phy_nxtcur -= cw;
1684 jcursor:
1685 if(((f & a_MOVE_CURSOR) || phy_nxtcur != phy_cur) &&
1686 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = phy_nxtcur, 0))
1687 goto jerr;
1689 jleave:
1690 tlp->tl_vi_flags |= (f & a_PERSIST_MASK);
1691 tlp->tl_lst_count = tlp->tl_count;
1692 tlp->tl_lst_cursor = tlp->tl_cursor;
1693 tlp->tl_phy_cursor = phy_cur;
1695 NYD2_LEAVE;
1696 return ((f & a_TRUE_RV) != 0);
1697 jerr:
1698 f &= ~a_TRUE_RV;
1699 goto jleave;
1702 static si32_t
1703 a_tty_wboundary(struct a_tty_line *tlp, si32_t dir){/* TODO shell token-wise */
1704 bool_t anynon;
1705 struct a_tty_cell *tcap;
1706 ui32_t cur, cnt;
1707 si32_t rv;
1708 NYD2_ENTER;
1710 assert(dir == 1 || dir == -1);
1712 rv = -1;
1713 cnt = tlp->tl_count;
1714 cur = tlp->tl_cursor;
1716 if(dir < 0){
1717 if(cur == 0)
1718 goto jleave;
1719 }else if(cur + 1 >= cnt)
1720 goto jleave;
1721 else
1722 --cnt, --cur; /* xxx Unsigned wrapping may occur (twice), then */
1724 for(rv = 0, tcap = tlp->tl_line.cells, anynon = FAL0;;){
1725 wchar_t wc;
1727 wc = tcap[cur += (ui32_t)dir].tc_wc;
1728 if(iswblank(wc) || iswpunct(wc)){
1729 if(anynon)
1730 break;
1731 }else
1732 anynon = TRU1;
1734 ++rv;
1736 if(dir < 0){
1737 if(cur == 0)
1738 break;
1739 }else if(cur + 1 >= cnt){
1740 ++rv;
1741 break;
1744 jleave:
1745 NYD2_LEAVE;
1746 return rv;
1749 static void
1750 a_tty_khome(struct a_tty_line *tlp, bool_t dobell){
1751 ui32_t f;
1752 NYD2_ENTER;
1754 if(LIKELY(tlp->tl_cursor > 0)){
1755 tlp->tl_cursor = 0;
1756 f = a_TTY_VF_MOD_CURSOR;
1757 }else if(dobell)
1758 f = a_TTY_VF_BELL;
1759 else
1760 f = a_TTY_VF_NONE;
1762 tlp->tl_vi_flags |= f;
1763 NYD2_LEAVE;
1766 static void
1767 a_tty_kend(struct a_tty_line *tlp){
1768 ui32_t f;
1769 NYD2_ENTER;
1771 if(LIKELY(tlp->tl_cursor < tlp->tl_count)){
1772 tlp->tl_cursor = tlp->tl_count;
1773 f = a_TTY_VF_MOD_CURSOR;
1774 }else
1775 f = a_TTY_VF_BELL;
1777 tlp->tl_vi_flags |= f;
1778 NYD2_LEAVE;
1781 static void
1782 a_tty_kbs(struct a_tty_line *tlp){
1783 ui32_t f, cur, cnt;
1784 NYD2_ENTER;
1786 cur = tlp->tl_cursor;
1787 cnt = tlp->tl_count;
1789 if(LIKELY(cur > 0)){
1790 tlp->tl_cursor = --cur;
1791 tlp->tl_count = --cnt;
1793 if((cnt -= cur) > 0){
1794 struct a_tty_cell *tcap;
1796 tcap = tlp->tl_line.cells + cur;
1797 memmove(tcap, &tcap[1], cnt *= sizeof(*tcap));
1799 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
1800 }else
1801 f = a_TTY_VF_BELL;
1803 tlp->tl_vi_flags |= f;
1804 NYD2_LEAVE;
1807 static void
1808 a_tty_ksnarf(struct a_tty_line *tlp, bool_t cplline, bool_t dobell){
1809 ui32_t i, f;
1810 NYD2_ENTER;
1812 f = a_TTY_VF_NONE;
1813 i = tlp->tl_cursor;
1815 if(cplline && i > 0){
1816 tlp->tl_cursor = i = 0;
1817 f = a_TTY_VF_MOD_CURSOR;
1820 if(LIKELY(i < tlp->tl_count)){
1821 struct a_tty_cell *tcap;
1823 tcap = &tlp->tl_line.cells[0];
1824 a_tty_copy2paste(tlp, &tcap[i], &tcap[tlp->tl_count]);
1825 tlp->tl_count = i;
1826 f = a_TTY_VF_MOD_CONTENT;
1827 }else if(dobell)
1828 f |= a_TTY_VF_BELL;
1830 tlp->tl_vi_flags |= f;
1831 NYD2_LEAVE;
1834 static si32_t
1835 a_tty_kdel(struct a_tty_line *tlp){
1836 ui32_t cur, cnt, f;
1837 si32_t i;
1838 NYD2_ENTER;
1840 cur = tlp->tl_cursor;
1841 cnt = tlp->tl_count;
1842 i = (si32_t)(cnt - cur);
1844 if(LIKELY(i > 0)){
1845 tlp->tl_count = --cnt;
1847 if(LIKELY(--i > 0)){
1848 struct a_tty_cell *tcap;
1850 tcap = &tlp->tl_line.cells[cur];
1851 memmove(tcap, &tcap[1], (ui32_t)i * sizeof(*tcap));
1853 f = a_TTY_VF_MOD_CONTENT;
1854 }else if(cnt == 0 && !ok_blook(ignoreeof)){
1855 putchar('^');
1856 putchar('D');
1857 i = -1;
1858 f = a_TTY_VF_NONE;
1859 }else{
1860 i = 0;
1861 f = a_TTY_VF_BELL;
1864 tlp->tl_vi_flags |= f;
1865 NYD2_LEAVE;
1866 return i;
1869 static void
1870 a_tty_kleft(struct a_tty_line *tlp){
1871 ui32_t f;
1872 NYD2_ENTER;
1874 if(LIKELY(tlp->tl_cursor > 0)){
1875 --tlp->tl_cursor;
1876 f = a_TTY_VF_MOD_CURSOR;
1877 }else
1878 f = a_TTY_VF_BELL;
1880 tlp->tl_vi_flags |= f;
1881 NYD2_LEAVE;
1884 static void
1885 a_tty_kright(struct a_tty_line *tlp){
1886 ui32_t i;
1887 NYD2_ENTER;
1889 if(LIKELY((i = tlp->tl_cursor + 1) <= tlp->tl_count)){
1890 tlp->tl_cursor = i;
1891 i = a_TTY_VF_MOD_CURSOR;
1892 }else
1893 i = a_TTY_VF_BELL;
1895 tlp->tl_vi_flags |= i;
1896 NYD2_LEAVE;
1899 static void
1900 a_tty_ksnarfw(struct a_tty_line *tlp, bool_t fwd){
1901 struct a_tty_cell *tcap;
1902 ui32_t cnt, cur, f;
1903 si32_t i;
1904 NYD2_ENTER;
1906 if(UNLIKELY((i = a_tty_wboundary(tlp, (fwd ? +1 : -1))) <= 0)){
1907 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
1908 goto jleave;
1911 cnt = tlp->tl_count - (ui32_t)i;
1912 cur = tlp->tl_cursor;
1913 if(!fwd)
1914 cur -= (ui32_t)i;
1915 tcap = &tlp->tl_line.cells[cur];
1917 a_tty_copy2paste(tlp, &tcap[0], &tcap[i]);
1919 if((tlp->tl_count = cnt) != (tlp->tl_cursor = cur)){
1920 cnt -= cur;
1921 memmove(&tcap[0], &tcap[i], cnt * sizeof(*tcap)); /* FIXME*/
1924 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
1925 jleave:
1926 tlp->tl_vi_flags |= f;
1927 NYD2_LEAVE;
1930 static void
1931 a_tty_kgow(struct a_tty_line *tlp, si32_t dir){
1932 ui32_t f;
1933 si32_t i;
1934 NYD2_ENTER;
1936 if(UNLIKELY((i = a_tty_wboundary(tlp, dir)) <= 0))
1937 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
1938 else{
1939 if(dir < 0)
1940 i = -i;
1941 tlp->tl_cursor += (ui32_t)i;
1942 f = a_TTY_VF_MOD_CURSOR;
1945 tlp->tl_vi_flags |= f;
1946 NYD2_LEAVE;
1949 static bool_t
1950 a_tty_kother(struct a_tty_line *tlp, wchar_t wc){
1951 /* Append if at EOL, insert otherwise;
1952 * since we may move around character-wise, always use a fresh ps */
1953 mbstate_t ps;
1954 struct a_tty_cell tc, *tcap;
1955 ui32_t f, cur, cnt;
1956 bool_t rv;
1957 NYD2_ENTER;
1959 rv = FAL0;
1960 f = a_TTY_VF_NONE;
1962 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1963 if(tlp->tl_count + 1 >= a_TTY_LINE_MAX){
1964 n_err(_("Stop here, we can't extend line beyond size limit\n"));
1965 goto jleave;
1968 /* First init a cell and see whether we'll really handle this wc */
1969 memset(&ps, 0, sizeof ps);
1970 /* C99 */{
1971 size_t l;
1973 l = wcrtomb(tc.tc_cbuf, tc.tc_wc = wc, &ps);
1974 if(UNLIKELY(l > MB_LEN_MAX)){
1975 jemb:
1976 n_err(_("wcrtomb(3) error: too many multibyte character bytes\n"));
1977 goto jleave;
1979 tc.tc_count = (ui16_t)l;
1981 if(UNLIKELY((options & OPT_ENC_MBSTATE) != 0)){
1982 l = wcrtomb(&tc.tc_cbuf[l], L'\0', &ps);
1983 if(LIKELY(l == 1))
1984 /* Only NUL terminator */;
1985 else if(LIKELY(--l < MB_LEN_MAX))
1986 tc.tc_count += (ui16_t)l;
1987 else
1988 goto jemb;
1992 /* Yes, we will! Place it in the array */
1993 tc.tc_novis = (iswprint(wc) == 0);
1994 tc.tc_width = a_tty_wcwidth(wc);
1995 /* TODO if(tc.tc_novis && tc.tc_width > 0) */
1997 cur = tlp->tl_cursor++;
1998 cnt = tlp->tl_count++ - cur;
1999 tcap = &tlp->tl_line.cells[cur];
2000 if(cnt >= 1){
2001 memmove(&tcap[1], tcap, cnt * sizeof(*tcap));
2002 f = a_TTY_VF_MOD_CONTENT;
2003 }else
2004 f = a_TTY_VF_MOD_SINGLE;
2005 memcpy(tcap, &tc, sizeof *tcap);
2007 f |= a_TTY_VF_MOD_CURSOR;
2008 rv = TRU1;
2009 jleave:
2010 if(!rv)
2011 f |= a_TTY_VF_BELL;
2012 tlp->tl_vi_flags |= f;
2013 NYD2_LEAVE;
2014 return rv;
2017 static ui32_t
2018 a_tty_kht(struct a_tty_line *tlp){
2019 struct stat sb;
2020 struct str orig, bot, topp, sub, exp;
2021 struct n_string shou, *shoup;
2022 struct a_tty_cell *cword, *ctop, *cx;
2023 bool_t wedid, set_savec;
2024 ui32_t rv, f;
2025 NYD2_ENTER;
2027 f = a_TTY_VF_NONE;
2028 shoup = n_string_creat_auto(&shou);
2030 /* Get plain line data; if this is the first expansion/xy, update the
2031 * very original content so that ^G gets the origin back */
2032 orig = tlp->tl_savec;
2033 a_tty_cell2save(tlp);
2034 exp = tlp->tl_savec;
2035 if(orig.s != NULL){
2036 /*tlp->tl_savec = orig;*/
2037 set_savec = FAL0;
2038 }else
2039 set_savec = TRU1;
2040 orig = exp;
2042 /* Find the word to be expanded */
2044 cword = tlp->tl_line.cells;
2045 ctop = cword + tlp->tl_cursor;
2046 cx = cword + tlp->tl_count;
2048 /* topp: separate data right of cursor */
2049 if(cx > ctop){
2050 for(rv = 0; ctop < cx; ++ctop)
2051 rv += ctop->tc_count;
2052 topp.l = rv;
2053 topp.s = orig.s + orig.l - rv;
2054 ctop = cword + tlp->tl_cursor;
2055 }else
2056 topp.s = NULL, topp.l = 0;
2058 /* Find the shell token that corresponds to the cursor position */
2059 /* C99 */{
2060 size_t max;
2062 max = 0;
2063 if(ctop > cword){
2064 for(; cword < ctop; ++cword)
2065 max += cword->tc_count;
2066 cword = tlp->tl_line.cells;
2068 bot = sub = orig;
2069 bot.l = 0;
2070 sub.l = max;
2072 if(max > 0){
2073 for(;;){
2074 enum n_shexp_state shs;
2076 exp = sub;
2077 shs = n_shell_parse_token(NULL, &sub, n_SHEXP_PARSE_DRYRUN |
2078 n_SHEXP_PARSE_TRIMSPACE | n_SHEXP_PARSE_IGNORE_EMPTY);
2079 if(sub.l != 0){
2080 size_t x;
2082 assert(max >= sub.l);
2083 x = max - sub.l;
2084 bot.l += x;
2085 max -= x;
2086 continue;
2088 if(shs & n_SHEXP_STATE_ERR_MASK){
2089 n_err(_("Invalid completion pattern: %.*s\n"),
2090 (int)exp.l, exp.s);
2091 goto jnope;
2093 n_shell_parse_token(shoup, &exp,
2094 n_SHEXP_PARSE_TRIMSPACE | n_SHEXP_PARSE_IGNORE_EMPTY);
2095 break;
2098 sub.s = n_string_cp(shoup);
2099 sub.l = shoup->s_len;
2103 /* Leave room for "implicit asterisk" expansion, as below */
2104 if(sub.l == 0){
2105 wedid = TRU1;
2106 sub.s = UNCONST("*");
2107 sub.l = 1;
2110 wedid = FAL0;
2111 jredo:
2112 /* TODO Super-Heavy-Metal: block all sigs, avoid leaks on jump */
2113 hold_all_sigs();
2114 exp.s = fexpand(sub.s, a_TTY_TAB_FEXP_FL);
2115 rele_all_sigs();
2117 if(exp.s == NULL || (exp.l = strlen(exp.s)) == 0)
2118 goto jnope;
2120 /* May be multi-return! */
2121 if(pstate & PS_EXPAND_MULTIRESULT)
2122 goto jmulti;
2124 /* xxx That is not really true since the limit counts characters not bytes */
2125 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
2126 if(exp.l + 1 >= a_TTY_LINE_MAX){
2127 n_err(_("Tabulator expansion would extend beyond line size limit\n"));
2128 goto jnope;
2131 /* If the expansion equals the original string, assume the user wants what
2132 * is usually known as tab completion, append `*' and restart */
2133 if(!wedid && exp.l == sub.l && !memcmp(exp.s, sub.s, exp.l)){
2134 if(sub.s[sub.l - 1] == '*')
2135 goto jnope;
2137 wedid = TRU1;
2138 sub.s[sub.l++] = '*';
2139 sub.s[sub.l] = '\0';
2140 goto jredo;
2142 /* If it is a directory, and there is not yet a / appended, then we want the
2143 * user to confirm that he wants to dive in -- with only a HT */
2144 else if(wedid && exp.l == --sub.l && !memcmp(exp.s, sub.s, exp.l) &&
2145 exp.s[exp.l - 1] != '/'){
2146 if(stat(exp.s, &sb) || !S_ISDIR(sb.st_mode))
2147 goto jnope;
2148 sub.s = salloc(exp.l + 1 +1);
2149 memcpy(sub.s, exp.s, exp.l);
2150 sub.s[exp.l++] = '/';
2151 sub.s[exp.l] = '\0';
2152 exp.s = sub.s;
2153 wedid = FAL0;
2154 goto jset;
2155 }else{
2156 if(wedid && (wedid = (exp.s[exp.l - 1] == '*')))
2157 --exp.l;
2158 exp.s[exp.l] = '\0';
2159 jset:
2160 exp.l = strlen(exp.s = n_shell_quote_cp(exp.s, tlp->tl_quote_rndtrip));
2161 tlp->tl_defc_cursor_byte = bot.l + exp.l -1;
2162 if(wedid)
2163 goto jnope;
2166 orig.l = bot.l + exp.l + topp.l;
2167 orig.s = salloc(orig.l + 5 +1);
2168 if((rv = (ui32_t)bot.l) > 0)
2169 memcpy(orig.s, bot.s, rv);
2170 memcpy(orig.s + rv, exp.s, exp.l);
2171 rv += exp.l;
2172 if(topp.l > 0){
2173 memcpy(orig.s + rv, topp.s, topp.l);
2174 rv += topp.l;
2176 orig.s[rv] = '\0';
2178 tlp->tl_defc = orig;
2179 tlp->tl_count = tlp->tl_cursor = 0;
2180 f |= a_TTY_VF_MOD_DIRTY;
2181 jleave:
2182 n_string_gut(shoup);
2183 tlp->tl_vi_flags |= f;
2184 NYD2_LEAVE;
2185 return rv;
2187 jmulti:{
2188 struct n_visual_info_ctx vic;
2189 struct str input;
2190 wc_t c2, c1;
2191 bool_t isfirst;
2192 char const *lococp;
2193 size_t locolen, scrwid, lnlen, lncnt, prefixlen;
2194 FILE *fp;
2196 if((fp = Ftmp(NULL, "tabex", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
2197 n_perr(_("tmpfile"), 0);
2198 fp = stdout;
2201 /* How long is the result string for real? Search the NUL NUL
2202 * terminator. While here, detect the longest entry to perform an
2203 * initial allocation of our accumulator string */
2204 locolen = 0;
2206 size_t i;
2208 i = strlen(&exp.s[++exp.l]);
2209 locolen = MAX(locolen, i);
2210 exp.l += i;
2211 }while(exp.s[exp.l + 1] != '\0');
2213 shoup = n_string_reserve(n_string_trunc(shoup, 0),
2214 locolen + (locolen >> 1));
2216 /* Iterate (once again) over all results */
2217 scrwid = (size_t)scrnwidth - ((size_t)scrnwidth >> 3);
2218 lnlen = lncnt = 0;
2219 UNINIT(prefixlen, 0);
2220 UNINIT(lococp, NULL);
2221 UNINIT(c1, '\0');
2222 for(isfirst = TRU1; exp.l > 0; isfirst = FAL0, c1 = c2){
2223 size_t i;
2224 char const *fullpath;
2226 /* Next result */
2227 sub = exp;
2228 sub.l = i = strlen(sub.s);
2229 assert(exp.l >= i);
2230 if((exp.l -= i) > 0)
2231 --exp.l;
2232 exp.s += ++i;
2234 /* Separate dirname and basename */
2235 fullpath = sub.s;
2236 if(isfirst){
2237 char const *cp;
2239 if((cp = strrchr(fullpath, '/')) != NULL)
2240 prefixlen = PTR2SIZE(++cp - fullpath);
2241 else
2242 prefixlen = 0;
2244 if(prefixlen > 0 && prefixlen < sub.l){
2245 sub.l -= prefixlen;
2246 sub.s += prefixlen;
2249 /* We want case-insensitive sort-order */
2250 memset(&vic, 0, sizeof vic);
2251 vic.vic_indat = sub.s;
2252 vic.vic_inlen = sub.l;
2253 c2 = n_visual_info(&vic, n_VISUAL_INFO_ONE_CHAR) ? vic.vic_waccu
2254 : (ui8_t)*sub.s;
2255 #ifdef HAVE_C90AMEND1
2256 c2 = towlower(c2);
2257 #else
2258 c2 = lowerconv(c2);
2259 #endif
2261 /* Query longest common prefix along the way */
2262 if(isfirst){
2263 c1 = c2;
2264 lococp = sub.s;
2265 locolen = sub.l;
2266 }else if(locolen > 0){
2267 for(i = 0; i < locolen; ++i)
2268 if(lococp[i] != sub.s[i]){
2269 i = field_detect_clip(i, lococp, i);
2270 locolen = i;
2271 break;
2275 /* Prepare display */
2276 input = sub;
2277 shoup = n_shell_quote(n_string_trunc(shoup, 0), &input,
2278 tlp->tl_quote_rndtrip);
2279 memset(&vic, 0, sizeof vic);
2280 vic.vic_indat = shoup->s_dat;
2281 vic.vic_inlen = shoup->s_len;
2282 if(!n_visual_info(&vic,
2283 n_VISUAL_INFO_SKIP_ERRORS | n_VISUAL_INFO_WIDTH_QUERY))
2284 vic.vic_vi_width = shoup->s_len;
2286 /* Put on screen. Indent follow lines of same sort slot */
2287 c1 = (c1 != c2);
2288 if(isfirst || c1 ||
2289 scrwid < lnlen || scrwid - lnlen <= vic.vic_vi_width + 2){
2290 putc('\n', fp);
2291 if(scrwid < lnlen)
2292 ++lncnt;
2293 ++lncnt, lnlen = 0;
2294 if(!isfirst && !c1)
2295 goto jsep;
2296 }else if(lnlen > 0){
2297 jsep:
2298 fputs(" ", fp);
2299 lnlen += 2;
2301 fputs(n_string_cp(shoup), fp);
2302 lnlen += vic.vic_vi_width;
2304 /* Support the known file name tagging
2305 * XXX *line-editor-completion-filetype* or so */
2306 if(!lstat(fullpath, &sb)){
2307 char c = '\0';
2309 if(S_ISDIR(sb.st_mode))
2310 c = '/';
2311 else if(S_ISLNK(sb.st_mode))
2312 c = '@';
2313 # ifdef S_ISFIFO
2314 else if(S_ISFIFO(sb.st_mode))
2315 c = '|';
2316 # endif
2317 # ifdef S_ISSOCK
2318 else if(S_ISSOCK(sb.st_mode))
2319 c = '=';
2320 # endif
2321 # ifdef S_ISCHR
2322 else if(S_ISCHR(sb.st_mode))
2323 c = '%';
2324 # endif
2325 # ifdef S_ISBLK
2326 else if(S_ISBLK(sb.st_mode))
2327 c = '#';
2328 # endif
2330 if(c != '\0'){
2331 putc(c, fp);
2332 ++lnlen;
2336 putc('\n', fp);
2337 ++lncnt;
2339 page_or_print(fp, lncnt);
2340 if(fp != stdout)
2341 Fclose(fp);
2343 n_string_gut(shoup);
2345 /* A common prefix of 0 means we cannot provide the user any auto
2346 * completed characters */
2347 if(locolen == 0)
2348 goto jnope;
2350 /* Otherwise we can, so extend the visual line content by the common
2351 * prefix (in a reversible way) */
2352 (exp.s = UNCONST(lococp))[locolen] = '\0';
2353 exp.s -= prefixlen;
2354 exp.l = (locolen += prefixlen);
2356 /* XXX Indicate that there is multiple choice */
2357 /* XXX f |= a_TTY_VF_BELL; -> *line-editor-completion-bell*? or so */
2358 wedid = FAL0;
2359 goto jset;
2362 jnope:
2363 /* If we've provided a default content, but failed to expand, there is
2364 * nothing we can "revert to": drop that default again */
2365 if(set_savec){
2366 tlp->tl_savec.s = NULL;
2367 tlp->tl_savec.l = 0;
2369 f = a_TTY_VF_NONE;
2370 rv = 0;
2371 goto jleave;
2374 # ifdef HAVE_HISTORY
2375 static ui32_t
2376 a_tty__khist_shared(struct a_tty_line *tlp, struct a_tty_hist *thp){
2377 ui32_t f, rv;
2378 NYD2_ENTER;
2380 if(LIKELY((tlp->tl_hist = thp) != NULL)){
2381 tlp->tl_defc.s = savestrbuf(thp->th_dat, thp->th_len);
2382 rv = tlp->tl_defc.l = thp->th_len;
2383 f = (tlp->tl_count > 0) ? a_TTY_VF_MOD_DIRTY : a_TTY_VF_NONE;
2384 tlp->tl_count = tlp->tl_cursor = 0;
2385 }else{
2386 f = a_TTY_VF_BELL;
2387 rv = 0;
2390 tlp->tl_vi_flags |= f;
2391 NYD2_LEAVE;
2392 return rv;
2395 static ui32_t
2396 a_tty_khist(struct a_tty_line *tlp, bool_t fwd){
2397 struct a_tty_hist *thp;
2398 ui32_t rv;
2399 NYD2_ENTER;
2401 /* If we're not in history mode yet, save line content;
2402 * also, disallow forward search, then, and, of course, bail unless we
2403 * do have any history at all */
2404 if((thp = tlp->tl_hist) == NULL){
2405 if(fwd)
2406 goto jleave;
2407 if((thp = a_tty.tg_hist) == NULL)
2408 goto jleave;
2409 a_tty_cell2save(tlp);
2410 goto jleave;
2413 thp = fwd ? thp->th_younger : thp->th_older;
2414 jleave:
2415 rv = a_tty__khist_shared(tlp, thp);
2416 NYD2_LEAVE;
2417 return rv;
2420 static ui32_t
2421 a_tty_khist_search(struct a_tty_line *tlp, bool_t fwd){
2422 struct str orig_savec;
2423 struct a_tty_hist *thp;
2424 ui32_t rv;
2425 NYD2_ENTER;
2427 thp = NULL;
2429 /* We cannot complete an empty line */
2430 if(UNLIKELY(tlp->tl_count == 0)){
2431 /* XXX The upcoming hard reset would restore a set savec buffer,
2432 * XXX so forcefully reset that. A cleaner solution would be to
2433 * XXX reset it whenever a restore is no longer desired */
2434 tlp->tl_savec.s = NULL;
2435 tlp->tl_savec.l = 0;
2436 goto jleave;
2439 if((thp = tlp->tl_hist) == NULL){
2440 if((thp = a_tty.tg_hist) == NULL)
2441 goto jleave;
2442 /* We don't support wraparound, searching forward must always step */
2443 if(fwd)
2444 thp = thp->th_younger;
2445 orig_savec.s = NULL;
2446 orig_savec.l = 0; /* silence CC */
2447 }else if((thp = (fwd ? thp->th_younger : thp->th_older)) == NULL)
2448 goto jleave;
2449 else
2450 orig_savec = tlp->tl_savec;
2452 if(orig_savec.s == NULL)
2453 a_tty_cell2save(tlp);
2455 for(; thp != NULL; thp = (fwd ? thp->th_younger : thp->th_older))
2456 if(is_prefix(tlp->tl_savec.s, thp->th_dat))
2457 break;
2459 if(orig_savec.s != NULL)
2460 tlp->tl_savec = orig_savec;
2461 jleave:
2462 rv = a_tty__khist_shared(tlp, thp);
2463 NYD2_LEAVE;
2464 return rv;
2466 # endif /* HAVE_HISTORY */
2468 static enum a_tty_fun_status
2469 a_tty_fun(struct a_tty_line *tlp, enum a_tty_bind_flags tbf, size_t *len){
2470 enum a_tty_fun_status rv;
2471 NYD2_ENTER;
2473 rv = a_TTY_FUN_STATUS_OK;
2474 # undef a_X
2475 # define a_X(N) a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## N)
2476 switch(a_TTY_BIND_FUN_REDUCE(tbf)){
2477 case a_X(BELL):
2478 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2479 break;
2480 case a_X(GO_BWD):
2481 a_tty_kleft(tlp);
2482 break;
2483 case a_X(GO_FWD):
2484 a_tty_kright(tlp);
2485 break;
2486 case a_X(GO_WORD_BWD):
2487 a_tty_kgow(tlp, -1);
2488 break;
2489 case a_X(GO_WORD_FWD):
2490 a_tty_kgow(tlp, +1);
2491 break;
2492 case a_X(GO_HOME):
2493 a_tty_khome(tlp, TRU1);
2494 break;
2495 case a_X(GO_END):
2496 a_tty_kend(tlp);
2497 break;
2498 case a_X(DEL_BWD):
2499 a_tty_kbs(tlp);
2500 break;
2501 case a_X(DEL_FWD):
2502 if(a_tty_kdel(tlp) < 0)
2503 rv = a_TTY_FUN_STATUS_END;
2504 break;
2505 case a_X(SNARF_WORD_BWD):
2506 a_tty_ksnarfw(tlp, FAL0);
2507 break;
2508 case a_X(SNARF_WORD_FWD):
2509 a_tty_ksnarfw(tlp, TRU1);
2510 break;
2511 case a_X(SNARF_END):
2512 a_tty_ksnarf(tlp, FAL0, TRU1);
2513 break;
2514 case a_X(SNARF_LINE):
2515 a_tty_ksnarf(tlp, TRU1, (tlp->tl_count == 0));
2516 break;
2518 case a_X(HIST_FWD):
2519 # ifdef HAVE_HISTORY
2520 if(tlp->tl_hist != NULL){
2521 bool_t isfwd = TRU1;
2523 if(0){
2524 # endif
2525 /* FALLTHRU */
2526 case a_X(HIST_BWD):
2527 # ifdef HAVE_HISTORY
2528 isfwd = FAL0;
2530 if((*len = a_tty_khist(tlp, isfwd)) > 0){
2531 rv = a_TTY_FUN_STATUS_RESTART;
2532 break;
2534 goto jreset;
2535 # endif
2537 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2538 break;
2540 case a_X(HIST_SRCH_FWD):{
2541 # ifdef HAVE_HISTORY
2542 bool_t isfwd = TRU1;
2544 if(0){
2545 # endif
2546 /* FALLTHRU */
2547 case a_X(HIST_SRCH_BWD):
2548 # ifdef HAVE_HISTORY
2549 isfwd = FAL0;
2551 if((*len = a_tty_khist_search(tlp, isfwd)) > 0){
2552 rv = a_TTY_FUN_STATUS_RESTART;
2553 break;
2555 goto jreset;
2556 # else
2557 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2558 # endif
2559 } break;
2561 case a_X(REPAINT):
2562 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2563 break;
2564 case a_X(QUOTE_RNDTRIP):
2565 tlp->tl_quote_rndtrip = !tlp->tl_quote_rndtrip;
2566 break;
2567 case a_X(PROMPT_CHAR):{
2568 wchar_t wc;
2570 if((wc = a_tty_vinuni(tlp)) > 0)
2571 a_tty_kother(tlp, wc);
2572 } break;
2573 case a_X(COMPLETE):
2574 if((*len = a_tty_kht(tlp)) > 0)
2575 rv = a_TTY_FUN_STATUS_RESTART;
2576 break;
2578 case a_X(PASTE):
2579 if(tlp->tl_pastebuf.l > 0)
2580 *len = (tlp->tl_defc = tlp->tl_pastebuf).l;
2581 else
2582 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2583 break;
2586 case a_X(CANCEL):
2587 /* Normally this just causes a restart and thus resets the state
2588 * machine */
2589 if(tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2591 # ifdef HAVE_KEY_BINDINGS
2592 tlp->tl_bind_takeover = '\0';
2593 # endif
2594 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2595 rv = a_TTY_FUN_STATUS_RESTART;
2596 break;
2598 case a_X(RESET):
2599 if(tlp->tl_count == 0 && tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2600 # ifdef HAVE_KEY_BINDINGS
2601 tlp->tl_bind_takeover = '\0';
2602 # endif
2603 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY | a_TTY_VF_BELL;
2604 break;
2605 }else if(0){
2606 case a_X(FULLRESET):
2607 tlp->tl_savec.s = tlp->tl_defc.s = NULL;
2608 tlp->tl_savec.l = tlp->tl_defc.l = 0;
2609 tlp->tl_defc_cursor_byte = 0;
2610 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2612 jreset:
2613 # ifdef HAVE_KEY_BINDINGS
2614 tlp->tl_bind_takeover = '\0';
2615 # endif
2616 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2617 tlp->tl_cursor = tlp->tl_count = 0;
2618 # ifdef HAVE_HISTORY
2619 tlp->tl_hist = NULL;
2620 # endif
2621 if((*len = tlp->tl_savec.l) != 0){
2622 tlp->tl_defc = tlp->tl_savec;
2623 tlp->tl_savec.s = NULL;
2624 tlp->tl_savec.l = 0;
2625 }else
2626 *len = tlp->tl_defc.l;
2627 rv = a_TTY_FUN_STATUS_RESTART;
2628 break;
2630 default:
2631 case a_X(COMMIT):
2632 rv = a_TTY_FUN_STATUS_COMMIT;
2633 break;
2635 # undef a_X
2637 NYD2_LEAVE;
2638 return rv;
2641 static ssize_t
2642 a_tty_readline(struct a_tty_line *tlp, size_t len SMALLOC_DEBUG_ARGS){
2643 /* We want to save code, yet we may have to incorporate a lines'
2644 * default content and / or default input to switch back to after some
2645 * history movement; let "len > 0" mean "have to display some data
2646 * buffer" -> a_BUFMODE, and only otherwise read(2) it */
2647 mbstate_t ps[2];
2648 char cbuf_base[MB_LEN_MAX * 2], *cbuf, *cbufp;
2649 ssize_t rv;
2650 struct a_tty_bind_tree *tbtp;
2651 wchar_t wc;
2652 enum a_tty_bind_flags tbf;
2653 enum {a_NONE, a_WAS_HERE = 1<<0, a_BUFMODE = 1<<1, a_MAYBEFUN = 1<<2,
2654 a_TIMEOUT = 1<<3, a_TIMEOUT_EXPIRED = 1<<4,
2655 a_TIMEOUT_MASK = a_TIMEOUT | a_TIMEOUT_EXPIRED,
2656 a_READ_LOOP_MASK = ~(a_WAS_HERE | a_MAYBEFUN | a_TIMEOUT_MASK)
2657 } flags;
2658 NYD_ENTER;
2660 UNINIT(rv, 0);
2661 # ifdef HAVE_KEY_BINDINGS
2662 assert(tlp->tl_bind_takeover == '\0');
2663 # endif
2664 jrestart:
2665 memset(ps, 0, sizeof ps);
2666 flags = a_NONE;
2667 tbf = 0;
2668 tlp->tl_vi_flags |= a_TTY_VF_REFRESH | a_TTY_VF_SYNC;
2670 jinput_loop:
2671 for(;;){
2672 if(len != 0)
2673 flags |= a_BUFMODE;
2675 /* Ensure we have valid pointers, and room for grow */
2676 a_tty_check_grow(tlp, ((flags & a_BUFMODE) ? (ui32_t)len : 1)
2677 SMALLOC_DEBUG_ARGSCALL);
2679 /* Handle visual state flags, except in buffer mode */
2680 if(!(flags & a_BUFMODE) && (tlp->tl_vi_flags & a_TTY_VF_ALL_MASK))
2681 if(!a_tty_vi_refresh(tlp)){
2682 rv = -1;
2683 goto jleave;
2686 /* Ready for messing around.
2687 * Normal read(2)? Else buffer mode: speed this one up */
2688 if(!(flags & a_BUFMODE)){
2689 cbufp =
2690 cbuf = cbuf_base;
2691 }else{
2692 assert(tlp->tl_defc.l > 0 && tlp->tl_defc.s != NULL);
2693 assert(tlp->tl_defc.l >= len);
2694 cbufp =
2695 cbuf = tlp->tl_defc.s + (tlp->tl_defc.l - len);
2696 cbufp += len;
2699 /* Read in the next complete multibyte character */
2700 /* C99 */{
2701 # ifdef HAVE_KEY_BINDINGS
2702 struct a_tty_bind_tree *xtbtp;
2703 struct inseq{
2704 struct inseq *last;
2705 struct inseq *next;
2706 struct a_tty_bind_tree *tbtp;
2707 } *isp_head, *isp;
2709 isp_head = isp = NULL;
2710 # endif
2712 for(flags &= a_READ_LOOP_MASK;;){
2713 # ifdef HAVE_KEY_BINDINGS
2714 if(!(flags & a_BUFMODE) && tlp->tl_bind_takeover != '\0'){
2715 wc = tlp->tl_bind_takeover;
2716 tlp->tl_bind_takeover = '\0';
2717 }else
2718 # endif
2720 if(!(flags & a_BUFMODE)){
2721 /* Let me at least once dream of iomon(itor), timer with
2722 * one-shot, enwrapped with key_event and key_sequence_event,
2723 * all driven by an event_loop */
2724 /* TODO v15 Until we have SysV signal handling all through we
2725 * TODO need to temporarily adjust our BSD signal handler with
2726 * TODO a SysV one, here */
2727 n_sighdl_t otstp, ottin, ottou;
2729 otstp = n_signal(SIGTSTP, &n_tty_signal);
2730 ottin = n_signal(SIGTTIN, &n_tty_signal);
2731 ottou = n_signal(SIGTTOU, &n_tty_signal);
2732 # ifdef HAVE_KEY_BINDINGS
2733 flags &= ~a_TIMEOUT_MASK;
2734 if(isp != NULL && (tbtp = isp->tbtp)->tbt_isseq &&
2735 !tbtp->tbt_isseq_trail){
2736 a_tty_term_rawmode_timeout(tlp, TRU1);
2737 flags |= a_TIMEOUT;
2739 # endif
2741 while((rv = read(STDIN_FILENO, cbufp, 1)) < 1){
2742 if(rv == -1){
2743 if(errno == EINTR){
2744 if((tlp->tl_vi_flags & a_TTY_VF_MOD_DIRTY) &&
2745 !a_tty_vi_refresh(tlp))
2746 break;
2747 continue;
2749 break;
2752 # ifdef HAVE_KEY_BINDINGS
2753 /* Timeout expiration */
2754 if(rv == 0){
2755 assert(flags & a_TIMEOUT);
2756 assert(isp != NULL);
2757 a_tty_term_rawmode_timeout(tlp, FAL0);
2759 /* Something "atomic" broke. Maybe the current one can
2760 * also be terminated already, by itself? xxx really? */
2761 if((tbtp = isp->tbtp)->tbt_bind != NULL){
2762 tlp->tl_bind_takeover = wc;
2763 goto jhave_bind;
2766 /* Or, maybe there is a second path without a timeout;
2767 * this should be covered by .tbt_isseq_trail, but then
2768 * again a single-layer implementation cannot "know" */
2769 for(xtbtp = tbtp; (xtbtp = xtbtp->tbt_sibling) != NULL;)
2770 if(xtbtp->tbt_char == tbtp->tbt_char){
2771 assert(!xtbtp->tbt_isseq);
2772 break;
2774 /* Lay down on read(2)? */
2775 if(xtbtp != NULL)
2776 continue;
2777 goto jtake_over;
2779 # endif /* HAVE_KEY_BINDINGS */
2782 # ifdef HAVE_KEY_BINDINGS
2783 if(flags & a_TIMEOUT)
2784 a_tty_term_rawmode_timeout(tlp, FAL0);
2785 # endif
2786 safe_signal(SIGTSTP, otstp);
2787 safe_signal(SIGTTIN, ottin);
2788 safe_signal(SIGTTOU, ottou);
2789 if(rv < 0)
2790 goto jleave;
2792 ++cbufp;
2795 rv = (ssize_t)mbrtowc(&wc, cbuf, PTR2SIZE(cbufp - cbuf), &ps[0]);
2796 if(rv <= 0){
2797 /* Any error during buffer mode can only result in a hard
2798 * reset; Otherwise, if it's a hard error, or if too many
2799 * redundant shift sequences overflow our buffer: perform
2800 * hard reset */
2801 if((flags & a_BUFMODE) || rv == -1 ||
2802 sizeof cbuf_base == PTR2SIZE(cbufp - cbuf)){
2803 a_tty_fun(tlp, a_TTY_BIND_FUN_FULLRESET, &len);
2804 goto jrestart;
2806 /* Otherwise, due to the way we deal with the buffer, we need
2807 * to restore the mbstate_t from before this conversion */
2808 ps[0] = ps[1];
2809 continue;
2811 cbufp = cbuf;
2812 ps[1] = ps[0];
2815 /* Normal read(2)ing is subject to detection of key-bindings */
2816 # ifdef HAVE_KEY_BINDINGS
2817 if(!(flags & a_BUFMODE)){
2818 /* Check for special bypass functions before we try to embed
2819 * this character into the tree */
2820 if(n_uasciichar(wc)){
2821 char c;
2822 char const *cp;
2824 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_prompt_char)[0];
2825 *cp != '\0'; ++cp){
2826 if(c == *cp){
2827 wc = a_tty_vinuni(tlp);
2828 break;
2831 if(wc == '\0'){
2832 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2833 goto jinput_loop;
2836 if(n_uasciichar(wc))
2837 flags |= a_MAYBEFUN;
2838 else
2839 flags &= ~a_MAYBEFUN;
2841 /* Search for this character in the bind tree */
2842 tbtp = (isp != NULL) ? isp->tbtp->tbt_childs
2843 : (*tlp->tl_bind_tree_hmap)[wc % HSHSIZE];
2844 for(; tbtp != NULL; tbtp = tbtp->tbt_sibling){
2845 if(tbtp->tbt_char == wc){
2846 struct inseq *nisp;
2848 /* If this one cannot continue we're likely finished! */
2849 if(tbtp->tbt_childs == NULL){
2850 assert(tbtp->tbt_bind != NULL);
2851 tbf = tbtp->tbt_bind->tbc_flags;
2852 goto jmle_fun;
2855 /* This needs to read more characters */
2856 nisp = salloc(sizeof *nisp);
2857 if((nisp->last = isp) == NULL)
2858 isp_head = nisp;
2859 else
2860 isp->next = nisp;
2861 nisp->next = NULL;
2862 nisp->tbtp = tbtp;
2863 isp = nisp;
2864 flags &= ~a_WAS_HERE;
2865 break;
2868 if(tbtp != NULL)
2869 continue;
2871 /* Was there a binding active, but couldn't be continued? */
2872 if(isp != NULL){
2873 /* A binding had a timeout, it didn't expire, but we saw
2874 * something non-expected. Something "atomic" broke.
2875 * Maybe there is a second path without a timeout, that
2876 * continues like we've seen it. I.e., it may just have been
2877 * the user, typing two fast. We definitely want to allow
2878 * bindings like \e,d etc. to succeed: users are so used to
2879 * them that a timeout cannot be the mechanism to catch up!
2880 * A single-layer implementation cannot "know" */
2881 if((tbtp = isp->tbtp)->tbt_isseq && (isp->last == NULL ||
2882 !(xtbtp = isp->last->tbtp)->tbt_isseq ||
2883 xtbtp->tbt_isseq_trail)){
2884 for(xtbtp = (tbtp = isp->tbtp);
2885 (xtbtp = xtbtp->tbt_sibling) != NULL;)
2886 if(xtbtp->tbt_char == tbtp->tbt_char){
2887 assert(!xtbtp->tbt_isseq);
2888 break;
2890 if(xtbtp != NULL){
2891 isp->tbtp = xtbtp;
2892 tlp->tl_bind_takeover = wc;
2893 continue;
2897 /* Check for CANCEL shortcut now */
2898 if(flags & a_MAYBEFUN){
2899 char c;
2900 char const *cp;
2902 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_cancel)[0];
2903 *cp != '\0'; ++cp)
2904 if(c == *cp){
2905 tbf = a_TTY_BIND_FUN_INTERNAL |a_TTY_BIND_FUN_CANCEL;
2906 goto jmle_fun;
2910 /* So: maybe the current sequence can be terminated here? */
2911 if((tbtp = isp->tbtp)->tbt_bind != NULL){
2912 jhave_bind:
2913 tbf = tbtp->tbt_bind->tbc_flags;
2914 jmle_fun:
2915 if(tbf & a_TTY_BIND_FUN_INTERNAL){
2916 switch(a_tty_fun(tlp, tbf, &len)){
2917 case a_TTY_FUN_STATUS_OK:
2918 goto jinput_loop;
2919 case a_TTY_FUN_STATUS_COMMIT:
2920 goto jdone;
2921 case a_TTY_FUN_STATUS_RESTART:
2922 goto jrestart;
2923 case a_TTY_FUN_STATUS_END:
2924 goto jleave;
2926 assert(0);
2927 }else if(tbtp->tbt_bind->tbc_flags & a_TTY_BIND_NOCOMMIT){
2928 struct a_tty_bind_ctx *tbcp;
2930 tbcp = tbtp->tbt_bind;
2931 memcpy(tlp->tl_defc.s = salloc(
2932 (tlp->tl_defc.l = len = tbcp->tbc_exp_len) +1),
2933 tbcp->tbc_exp, tbcp->tbc_exp_len +1);
2934 goto jrestart;
2935 }else{
2936 tlp->tl_reenter_after_cmd = tbtp->tbt_bind->tbc_exp;
2937 goto jdone;
2942 /* Otherwise take over all chars "as is" */
2943 jtake_over:
2944 for(; isp_head != NULL; isp_head = isp_head->next)
2945 if(a_tty_kother(tlp, isp_head->tbtp->tbt_char)){
2946 /* FIXME */
2948 /* And the current one too */
2949 goto jkother;
2951 # endif /* HAVE_KEY_BINDINGS */
2953 if((flags & a_BUFMODE) && (len -= (size_t)rv) == 0){
2954 /* Buffer mode completed */
2955 tlp->tl_defc.s = NULL;
2956 tlp->tl_defc.l = 0;
2957 flags &= ~a_BUFMODE;
2959 break;
2962 # ifndef HAVE_KEY_BINDINGS
2963 /* Don't interpret control bytes during buffer mode.
2964 * Otherwise, if it's a control byte check whether it is a MLE
2965 * function. Remarks: initially a complete duplicate to be able to
2966 * switch(), later converted to simply iterate over (an #ifdef'd
2967 * subset of) the MLE default_tuple table in order to have "a SPOF" */
2968 if(cbuf == cbuf_base && n_uasciichar(wc) && cntrlchar((char)wc)){
2969 struct a_tty_bind_default_tuple const *tbdtp;
2970 char c;
2972 for(c = (char)wc ^ 0x40, tbdtp = a_tty_bind_default_tuples;
2973 PTRCMP(tbdtp, <, &a_tty_bind_default_tuples[
2974 NELEM(a_tty_bind_default_tuples)]);
2975 ++tbdtp){
2976 /* Assert default_tuple table is properly subset'ed */
2977 assert(tbdtp->tbdt_iskey);
2978 if(tbdtp->tbdt_ckey == c){
2979 if(tbdtp->tbdt_exp[0] == '\0'){
2980 enum a_tty_bind_flags tbf;
2982 tbf = a_TTY_BIND_FUN_EXPAND((ui8_t)tbdtp->tbdt_exp[1]);
2983 switch(a_tty_fun(tlp, tbf, &len)){
2984 case a_TTY_FUN_STATUS_OK:
2985 goto jinput_loop;
2986 case a_TTY_FUN_STATUS_COMMIT:
2987 goto jdone;
2988 case a_TTY_FUN_STATUS_RESTART:
2989 goto jrestart;
2990 case a_TTY_FUN_STATUS_END:
2991 goto jleave;
2993 assert(0);
2994 }else{
2995 tlp->tl_reenter_after_cmd = tbdtp->tbdt_exp;
2996 goto jdone;
3001 # endif /* !HAVE_KEY_BINDINGS */
3003 # ifdef HAVE_KEY_BINDINGS
3004 jkother:
3005 # endif
3006 if(a_tty_kother(tlp, wc)){
3007 /* Don't clear the history during buffer mode.. */
3008 # ifdef HAVE_HISTORY
3009 if(!(flags & a_BUFMODE) && cbuf == cbuf_base)
3010 tlp->tl_hist = NULL;
3011 # endif
3016 /* We have a completed input line, convert the struct cell data to its
3017 * plain character equivalent */
3018 jdone:
3019 rv = a_tty_cell2dat(tlp);
3020 jleave:
3021 putchar('\n');
3022 fflush(stdout);
3023 NYD_LEAVE;
3024 return rv;
3027 # ifdef HAVE_KEY_BINDINGS
3028 static enum n_lexinput_flags
3029 a_tty_bind_ctx_find(char const *name){
3030 enum n_lexinput_flags rv;
3031 struct a_tty_bind_ctx_map const *tbcmp;
3032 NYD2_ENTER;
3034 tbcmp = a_tty_bind_ctx_maps;
3035 do if(!asccasecmp(tbcmp->tbcm_name, name)){
3036 rv = tbcmp->tbcm_ctx;
3037 goto jleave;
3038 }while(PTRCMP(++tbcmp, <, &a_tty_bind_ctx_maps[NELEM(a_tty_bind_ctx_maps)]));
3040 rv = (enum n_lexinput_flags)-1;
3041 jleave:
3042 NYD2_LEAVE;
3043 return rv;
3046 static bool_t
3047 a_tty_bind_create(struct a_tty_bind_parse_ctx *tbpcp, bool_t replace){
3048 struct a_tty_bind_ctx *tbcp;
3049 bool_t rv;
3050 NYD2_ENTER;
3052 rv = FAL0;
3054 if(!a_tty_bind_parse(TRU1, tbpcp))
3055 goto jleave;
3057 /* Since we use a single buffer for it all, need to replace as such */
3058 if(tbpcp->tbpc_tbcp != NULL){
3059 if(!replace)
3060 goto jleave;
3061 a_tty_bind_del(tbpcp);
3062 }else if(a_tty.tg_bind_cnt == UI32_MAX){
3063 n_err(_("`bind': maximum number of bindings already established\n"));
3064 goto jleave;
3067 /* C99 */{
3068 size_t i, j;
3070 tbcp = smalloc(sizeof(*tbcp) -
3071 VFIELD_SIZEOF(struct a_tty_bind_ctx, tbc__buf) +
3072 tbpcp->tbpc_seq_len + tbpcp->tbpc_exp.l + tbpcp->tbpc_cnv_len +3);
3073 if(tbpcp->tbpc_ltbcp != NULL){
3074 tbcp->tbc_next = tbpcp->tbpc_ltbcp->tbc_next;
3075 tbpcp->tbpc_ltbcp->tbc_next = tbcp;
3076 }else{
3077 enum n_lexinput_flags lif = tbpcp->tbpc_flags & n__LEXINPUT_CTX_MASK;
3079 tbcp->tbc_next = a_tty.tg_bind[lif];
3080 a_tty.tg_bind[lif] = tbcp;
3082 memcpy(tbcp->tbc_seq = &tbcp->tbc__buf[0],
3083 tbpcp->tbpc_seq, i = (tbcp->tbc_seq_len = tbpcp->tbpc_seq_len) +1);
3084 memcpy(tbcp->tbc_exp = &tbcp->tbc__buf[i],
3085 tbpcp->tbpc_exp.s, j = (tbcp->tbc_exp_len = tbpcp->tbpc_exp.l) +1);
3086 memcpy(tbcp->tbc_cnv = &tbcp->tbc__buf[i += j],
3087 tbpcp->tbpc_cnv, (tbcp->tbc_cnv_len = tbpcp->tbpc_cnv_len) +1);
3088 tbcp->tbc_flags = tbpcp->tbpc_flags;
3091 /* Directly resolve any termcap(5) symbol if we are already setup */
3092 if((pstate & PS_STARTED) &&
3093 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
3094 a_TTY_BIND_RESOLVE)
3095 a_tty_bind_resolve(tbcp);
3097 ++a_tty.tg_bind_cnt;
3098 /* If this binding is usable invalidate the key input lookup trees */
3099 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3100 a_tty.tg_bind_isdirty = TRU1;
3101 rv = TRU1;
3102 jleave:
3103 NYD2_LEAVE;
3104 return rv;
3107 static bool_t
3108 a_tty_bind_parse(bool_t isbindcmd, struct a_tty_bind_parse_ctx *tbpcp){
3109 enum{a_TRUE_RV = a_TTY__BIND_LAST<<1};
3111 struct n_visual_info_ctx vic;
3112 struct str shin_save, shin;
3113 struct n_string shou, *shoup;
3114 size_t i;
3115 struct kse{
3116 struct kse *next;
3117 char *seq_dat;
3118 wc_t *cnv_dat;
3119 ui32_t seq_len;
3120 ui32_t cnv_len; /* High bit set if a termap to be resolved */
3121 ui32_t calc_cnv_len; /* Ditto, but aligned etc. */
3122 } *head, *tail;
3123 ui32_t f;
3124 NYD2_ENTER;
3125 n_LCTA(UICMP(64, a_TRUE_RV, <, UI32_MAX),
3126 "Flag bits excess storage datatype");
3128 f = n_LEXINPUT_NONE;
3129 shoup = n_string_creat_auto(&shou);
3130 head = tail = NULL;
3132 /* Parse the key-sequence */
3133 for(shin.s = UNCONST(tbpcp->tbpc_in_seq), shin.l = UIZ_MAX;;){
3134 struct kse *ep;
3135 enum n_shexp_state shs;
3137 shin_save = shin;
3138 shs = n_shell_parse_token(shoup, &shin,
3139 n_SHEXP_PARSE_TRUNC | n_SHEXP_PARSE_TRIMSPACE |
3140 n_SHEXP_PARSE_IGNORE_EMPTY | n_SHEXP_PARSE_IFS_IS_COMMA);
3141 if(shs & n_SHEXP_STATE_ERR_UNICODE){
3142 f |= a_TTY_BIND_DEFUNCT;
3143 if(isbindcmd && (options & OPT_D_V))
3144 n_err(_("`%s': \\uNICODE not available in locale: %s\n"),
3145 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3147 if((shs & n_SHEXP_STATE_ERR_MASK) & ~n_SHEXP_STATE_ERR_UNICODE){
3148 n_err(_("`%s': failed to parse key-sequence: %s\n"),
3149 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3150 goto jleave;
3152 if((shs & (n_SHEXP_STATE_OUTPUT | n_SHEXP_STATE_STOP)) ==
3153 n_SHEXP_STATE_STOP)
3154 break;
3156 ep = salloc(sizeof *ep);
3157 if(head == NULL)
3158 head = ep;
3159 else
3160 tail->next = ep;
3161 tail = ep;
3162 ep->next = NULL;
3163 if(!(shs & n_SHEXP_STATE_ERR_UNICODE)){
3164 i = strlen(ep->seq_dat = n_shell_quote_cp(n_string_cp(shoup), TRU1));
3165 if(i >= SI32_MAX - 1)
3166 goto jelen;
3167 ep->seq_len = (ui32_t)i;
3168 }else{
3169 /* Otherwise use the original buffer, _we_ can only quote it the wrong
3170 * way (e.g., an initial $'\u3a' becomes '\u3a'), _then_ */
3171 if((i = shin_save.l - shin.l) >= SI32_MAX - 1)
3172 goto jelen;
3173 ep->seq_len = (ui32_t)i;
3174 ep->seq_dat = savestrbuf(shin_save.s, i);
3177 memset(&vic, 0, sizeof vic);
3178 vic.vic_inlen = shoup->s_len;
3179 vic.vic_indat = shoup->s_dat;
3180 if(!n_visual_info(&vic,
3181 n_VISUAL_INFO_WOUT_CREATE | n_VISUAL_INFO_WOUT_SALLOC)){
3182 n_err(_("`%s': key-sequence seems to contain invalid "
3183 "characters: %s: %s\n"),
3184 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
3185 f |= a_TTY_BIND_DEFUNCT;
3186 goto jleave;
3187 }else if(vic.vic_woulen == 0 ||
3188 vic.vic_woulen >= (SI32_MAX - 2) / sizeof(wc_t)){
3189 jelen:
3190 n_err(_("`%s': length of key-sequence unsupported: %s: %s\n"),
3191 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
3192 f |= a_TTY_BIND_DEFUNCT;
3193 goto jleave;
3195 ep->cnv_dat = vic.vic_woudat;
3196 ep->cnv_len = (ui32_t)vic.vic_woulen;
3198 /* A termcap(5)/terminfo(5) identifier? */
3199 if(ep->cnv_len > 1 && ep->cnv_dat[0] == ':'){
3200 i = --ep->cnv_len, ++ep->cnv_dat;
3201 # ifndef HAVE_TERMCAP
3202 if(options & OPT_D_V)
3203 n_err(_("`%s': no termcap(5)/terminfo(5) support: %s: %s\n"),
3204 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3205 f |= a_TTY_BIND_DEFUNCT;
3206 # endif
3207 if(i > a_TTY_BIND_CAPNAME_MAX){
3208 n_err(_("`%s': termcap(5)/terminfo(5) name too long: %s: %s\n"),
3209 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3210 f |= a_TTY_BIND_DEFUNCT;
3212 while(i > 0)
3213 /* (We store it as char[]) */
3214 if((ui32_t)ep->cnv_dat[--i] & ~0x7Fu){
3215 n_err(_("`%s': invalid termcap(5)/terminfo(5) name content: "
3216 "%s: %s\n"),
3217 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3218 f |= a_TTY_BIND_DEFUNCT;
3219 break;
3221 ep->cnv_len |= SI32_MIN; /* Needs resolve */
3222 f |= a_TTY_BIND_RESOLVE;
3225 if(shs & n_SHEXP_STATE_STOP)
3226 break;
3229 if(head == NULL){
3230 jeempty:
3231 n_err(_("`%s': effectively empty key-sequence: %s\n"),
3232 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3233 goto jleave;
3236 /* C99 */{
3237 struct a_tty_bind_ctx *ltbcp, *tbcp;
3238 char *cpbase, *cp, *cnv;
3239 size_t sl, cl;
3241 /* Unite the parsed sequence(s) into single string representations */
3242 for(sl = cl = 0, tail = head; tail != NULL; tail = tail->next){
3243 sl += tail->seq_len + 1;
3245 if(!isbindcmd)
3246 continue;
3248 /* Preserve room for terminal capabilities to be resolved.
3249 * Above we have ensured the buffer will fit in these calculations */
3250 if((i = tail->cnv_len) & SI32_MIN){
3251 /* For now
3252 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[]+NUL;}
3253 * later
3254 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3255 n_LCTAV(ISPOW2(a_TTY_BIND_CAPEXP_ROUNDUP));
3256 n_LCTA(a_TTY_BIND_CAPEXP_ROUNDUP >= sizeof(wc_t),
3257 "Aligning on this constant doesn't properly align wc_t");
3258 i &= SI32_MAX;
3259 i *= sizeof(wc_t);
3260 i += sizeof(si32_t);
3261 if(i < a_TTY_BIND_CAPEXP_ROUNDUP)
3262 i = (i + (a_TTY_BIND_CAPEXP_ROUNDUP - 1)) &
3263 ~(a_TTY_BIND_CAPEXP_ROUNDUP - 1);
3264 }else
3265 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3266 i *= sizeof(wc_t);
3267 i += sizeof(si32_t) + sizeof(wc_t); /* (buf_len_iscap, NUL) */
3268 cl += i;
3269 if(tail->cnv_len & SI32_MIN){
3270 tail->cnv_len &= SI32_MAX;
3271 i |= SI32_MIN;
3273 tail->calc_cnv_len = (ui32_t)i;
3275 --sl;
3277 tbpcp->tbpc_seq_len = sl;
3278 tbpcp->tbpc_cnv_len = cl;
3279 /* C99 */{
3280 size_t j;
3282 j = i = sl + 1; /* Room for comma separator */
3283 if(isbindcmd){
3284 size_t const al = MAX(sizeof(si32_t), sizeof(wc_t)) - 1;
3286 i = (i + al) & ~al;
3287 j = i;
3288 i += cl;
3290 tbpcp->tbpc_seq = cp = cpbase = salloc(i);
3291 tbpcp->tbpc_cnv = cnv = &cpbase[j];
3294 for(tail = head; tail != NULL; tail = tail->next){
3295 memcpy(cp, tail->seq_dat, tail->seq_len);
3296 cp += tail->seq_len;
3297 *cp++ = ',';
3299 if(isbindcmd){
3300 char * const save_cnv = cnv;
3302 ((si32_t*)cnv)[0] = (si32_t)(i = tail->calc_cnv_len);
3303 cnv += sizeof(si32_t);
3304 if(i & SI32_MIN){
3305 /* For now
3306 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];}
3307 * later
3308 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[];} */
3309 ((si32_t*)cnv)[0] = tail->cnv_len;
3310 cnv += sizeof(si32_t);
3312 i = tail->cnv_len * sizeof(wc_t);
3313 memcpy(cnv, tail->cnv_dat, i);
3314 cnv += i;
3315 *(wc_t*)cnv = '\0';
3317 cnv = save_cnv + (tail->calc_cnv_len & SI32_MAX);
3320 *--cp = '\0';
3322 /* Search for a yet existing identical mapping */
3323 for(ltbcp = NULL, tbcp = a_tty.tg_bind[tbpcp->tbpc_flags]; tbcp != NULL;
3324 ltbcp = tbcp, tbcp = tbcp->tbc_next)
3325 if(tbcp->tbc_seq_len == sl && !memcmp(tbcp->tbc_seq, cpbase, sl)){
3326 tbpcp->tbpc_tbcp = tbcp;
3327 break;
3329 tbpcp->tbpc_ltbcp = ltbcp;
3330 tbpcp->tbpc_flags |= (f & a_TTY__BIND_MASK);
3333 /* Create single string expansion if so desired */
3334 if(isbindcmd){
3335 char *exp;
3337 exp = tbpcp->tbpc_exp.s;
3339 i = tbpcp->tbpc_exp.l;
3340 if(i > 0 && exp[i - 1] == '@'){
3341 while(--i > 0){
3342 if(!blankspacechar(exp[i - 1]))
3343 break;
3345 if(i == 0)
3346 goto jeempty;
3348 exp[tbpcp->tbpc_exp.l = i] = '\0';
3349 tbpcp->tbpc_flags |= a_TTY_BIND_NOCOMMIT;
3352 /* It may map to an internal MLE command! */
3353 for(i = 0; i < NELEM(a_tty_bind_fun_names); ++i)
3354 if(!asccasecmp(exp, a_tty_bind_fun_names[i])){
3355 tbpcp->tbpc_flags |= a_TTY_BIND_FUN_EXPAND(i) |
3356 a_TTY_BIND_FUN_INTERNAL |
3357 (head->next == NULL ? a_TTY_BIND_MLE1CNTRL : 0);
3358 if((options & OPT_D_V) && (tbpcp->tbpc_flags & a_TTY_BIND_NOCOMMIT))
3359 n_err(_("`%s': MLE commands can't be made editable via @: %s\n"),
3360 tbpcp->tbpc_cmd, exp);
3361 tbpcp->tbpc_flags &= ~a_TTY_BIND_NOCOMMIT;
3362 break;
3366 f |= a_TRUE_RV; /* TODO because we only now true and false; DEFUNCT.. */
3367 jleave:
3368 n_string_gut(shoup);
3369 NYD2_LEAVE;
3370 return (f & a_TRUE_RV) != 0;
3373 static void
3374 a_tty_bind_resolve(struct a_tty_bind_ctx *tbcp){
3375 char capname[a_TTY_BIND_CAPNAME_MAX +1];
3376 struct n_termcap_value tv;
3377 size_t len;
3378 bool_t isfirst; /* TODO For now: first char must be control! */
3379 char *cp, *next;
3380 NYD2_ENTER;
3382 UNINIT(next, NULL);
3383 for(cp = tbcp->tbc_cnv, isfirst = TRU1, len = tbcp->tbc_cnv_len;
3384 len > 0; isfirst = FAL0, cp = next){
3385 /* C99 */{
3386 si32_t i, j;
3388 i = ((si32_t*)cp)[0];
3389 j = i & SI32_MAX;
3390 next = &cp[j];
3391 len -= j;
3392 if(i == j)
3393 continue;
3395 /* struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];} */
3396 cp += sizeof(si32_t);
3397 i = ((si32_t*)cp)[0];
3398 cp += sizeof(si32_t);
3399 for(j = 0; j < i; ++j)
3400 capname[j] = ((wc_t*)cp)[j];
3401 capname[j] = '\0';
3404 /* Use generic lookup mechanism if not a known query */
3405 /* C99 */{
3406 si32_t tq;
3408 tq = n_termcap_query_for_name(capname, n_TERMCAP_CAPTYPE_STRING);
3409 if(tq == -1){
3410 tv.tv_data.tvd_string = capname;
3411 tq = n__TERMCAP_QUERY_MAX;
3414 if(tq < 0 || !n_termcap_query(tq, &tv)){
3415 if(options & OPT_D_V)
3416 n_err(_("`bind': unknown or unsupported capability: %s: %s\n"),
3417 capname, tbcp->tbc_seq);
3418 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3419 break;
3423 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3424 /* C99 */{
3425 size_t i;
3427 i = strlen(tv.tv_data.tvd_string);
3428 if(/*i > SI32_MAX ||*/ i >= PTR2SIZE(next - cp)){
3429 if(options & OPT_D_V)
3430 n_err(_("`bind': capability expansion too long: %s: %s\n"),
3431 capname, tbcp->tbc_seq);
3432 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3433 break;
3434 }else if(i == 0){
3435 if(options & OPT_D_V)
3436 n_err(_("`bind': empty capability expansion: %s: %s\n"),
3437 capname, tbcp->tbc_seq);
3438 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3439 break;
3440 }else if(isfirst && !cntrlchar(*tv.tv_data.tvd_string)){
3441 if(options & OPT_D_V)
3442 n_err(_("`bind': capability expansion doesn't start with "
3443 "control: %s: %s\n"), capname, tbcp->tbc_seq);
3444 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3445 break;
3447 ((si32_t*)cp)[-1] = (si32_t)i;
3448 memcpy(cp, tv.tv_data.tvd_string, i);
3449 cp[i] = '\0';
3452 NYD2_LEAVE;
3455 static void
3456 a_tty_bind_del(struct a_tty_bind_parse_ctx *tbpcp){
3457 struct a_tty_bind_ctx *ltbcp, *tbcp;
3458 NYD2_ENTER;
3460 tbcp = tbpcp->tbpc_tbcp;
3462 if((ltbcp = tbpcp->tbpc_ltbcp) != NULL)
3463 ltbcp->tbc_next = tbcp->tbc_next;
3464 else
3465 a_tty.tg_bind[tbpcp->tbpc_flags] = tbcp->tbc_next;
3466 free(tbcp);
3468 --a_tty.tg_bind_cnt;
3469 a_tty.tg_bind_isdirty = TRU1;
3470 NYD2_LEAVE;
3473 static void
3474 a_tty_bind_tree_build(void){
3475 size_t i;
3476 NYD2_ENTER;
3478 for(i = 0; i < n__LEXINPUT_CTX_MAX; ++i){
3479 struct a_tty_bind_ctx *tbcp;
3480 n_LCTAV(n_LEXINPUT_CTX_BASE == 0);
3482 /* Somewhat wasteful, but easier to handle: simply clone the entire
3483 * primary key onto the secondary one, then only modify it */
3484 for(tbcp = a_tty.tg_bind[n_LEXINPUT_CTX_BASE]; tbcp != NULL;
3485 tbcp = tbcp->tbc_next)
3486 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3487 a_tty__bind_tree_add(n_LEXINPUT_CTX_BASE, &a_tty.tg_bind_tree[i][0],
3488 tbcp);
3490 if(i != n_LEXINPUT_CTX_BASE)
3491 for(tbcp = a_tty.tg_bind[i]; tbcp != NULL; tbcp = tbcp->tbc_next)
3492 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3493 a_tty__bind_tree_add(i, &a_tty.tg_bind_tree[i][0], tbcp);
3496 a_tty.tg_bind_isbuild = TRU1;
3497 NYD2_LEAVE;
3500 static void
3501 a_tty_bind_tree_teardown(void){
3502 size_t i, j;
3503 NYD2_ENTER;
3505 memset(&a_tty.tg_bind_shcut_cancel[0], 0,
3506 sizeof(a_tty.tg_bind_shcut_cancel));
3507 memset(&a_tty.tg_bind_shcut_prompt_char[0], 0,
3508 sizeof(a_tty.tg_bind_shcut_prompt_char));
3510 for(i = 0; i < n__LEXINPUT_CTX_MAX; ++i)
3511 for(j = 0; j < HSHSIZE; ++j)
3512 a_tty__bind_tree_free(a_tty.tg_bind_tree[i][j]);
3513 memset(&a_tty.tg_bind_tree[0], 0, sizeof(a_tty.tg_bind_tree));
3515 a_tty.tg_bind_isdirty = a_tty.tg_bind_isbuild = FAL0;
3516 NYD2_LEAVE;
3519 static void
3520 a_tty__bind_tree_add(ui32_t hmap_idx, struct a_tty_bind_tree *store[HSHSIZE],
3521 struct a_tty_bind_ctx *tbcp){
3522 ui32_t cnvlen;
3523 char const *cnvdat;
3524 struct a_tty_bind_tree *ntbtp;
3525 NYD2_ENTER;
3526 UNUSED(hmap_idx);
3528 ntbtp = NULL;
3530 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len; cnvlen > 0;){
3531 union {wchar_t const *wp; char const *cp;} u;
3532 si32_t entlen;
3534 /* {si32_t buf_len_iscap;} */
3535 entlen = *(si32_t const*)cnvdat;
3537 if(entlen & SI32_MIN){
3538 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;}
3539 * Note that empty capabilities result in DEFUNCT */
3540 for(u.cp = (char const*)&((si32_t const*)cnvdat)[2];
3541 *u.cp != '\0'; ++u.cp)
3542 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.cp, TRU1);
3543 ntbtp->tbt_isseq_trail = TRU1;
3544 entlen &= SI32_MAX;
3545 }else{
3546 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3547 bool_t isseq;
3549 u.wp = (wchar_t const*)&((si32_t const*)cnvdat)[1];
3551 /* May be a special shortcut function? */
3552 if(ntbtp == NULL && (tbcp->tbc_flags & a_TTY_BIND_MLE1CNTRL)){
3553 char *cp;
3554 ui32_t ctx, fun;
3556 ctx = tbcp->tbc_flags & n__LEXINPUT_CTX_MAX;
3557 fun = tbcp->tbc_flags & a_TTY__BIND_FUN_MASK;
3559 if(fun == a_TTY_BIND_FUN_CANCEL){
3560 for(cp = &a_tty.tg_bind_shcut_cancel[ctx][0];
3561 PTRCMP(cp, <, &a_tty.tg_bind_shcut_cancel[ctx]
3562 [NELEM(a_tty.tg_bind_shcut_cancel[ctx]) - 1]); ++cp)
3563 if(*cp == '\0'){
3564 *cp = (char)*u.wp;
3565 break;
3567 }else if(fun == a_TTY_BIND_FUN_PROMPT_CHAR){
3568 for(cp = &a_tty.tg_bind_shcut_prompt_char[ctx][0];
3569 PTRCMP(cp, <, &a_tty.tg_bind_shcut_prompt_char[ctx]
3570 [NELEM(a_tty.tg_bind_shcut_prompt_char[ctx]) - 1]);
3571 ++cp)
3572 if(*cp == '\0'){
3573 *cp = (char)*u.wp;
3574 break;
3579 isseq = (u.wp[1] != '\0');
3580 for(; *u.wp != '\0'; ++u.wp)
3581 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.wp, isseq);
3582 if(isseq)
3583 ntbtp->tbt_isseq_trail = TRU1;
3586 cnvlen -= entlen;
3587 cnvdat += entlen;
3590 /* Should have been rendered defunctional at first instead */
3591 assert(ntbtp != NULL);
3592 ntbtp->tbt_bind = tbcp;
3593 NYD2_LEAVE;
3596 static struct a_tty_bind_tree *
3597 a_tty__bind_tree_add_wc(struct a_tty_bind_tree **treep,
3598 struct a_tty_bind_tree *parentp, wchar_t wc, bool_t isseq){
3599 struct a_tty_bind_tree *tbtp, *xtbtp;
3600 NYD2_ENTER;
3602 if(parentp == NULL){
3603 treep += wc % HSHSIZE;
3605 /* Having no parent also means that the tree slot is possibly empty */
3606 for(tbtp = *treep; tbtp != NULL;
3607 parentp = tbtp, tbtp = tbtp->tbt_sibling){
3608 if(tbtp->tbt_char != wc)
3609 continue;
3610 if(tbtp->tbt_isseq == isseq)
3611 goto jleave;
3612 /* isseq MUST be linked before !isseq, so record this "parent"
3613 * sibling, but continue searching for now */
3614 if(!isseq)
3615 parentp = tbtp;
3616 /* Otherwise it is impossible that we'll find what we look for */
3617 else{
3618 #ifdef HAVE_DEBUG
3619 while((tbtp = tbtp->tbt_sibling) != NULL)
3620 assert(tbtp->tbt_char != wc);
3621 #endif
3622 break;
3626 tbtp = smalloc(sizeof *tbtp);
3627 memset(tbtp, 0, sizeof *tbtp);
3628 tbtp->tbt_char = wc;
3629 tbtp->tbt_isseq = isseq;
3631 if(parentp == NULL){
3632 tbtp->tbt_sibling = *treep;
3633 *treep = tbtp;
3634 }else{
3635 tbtp->tbt_sibling = parentp->tbt_sibling;
3636 parentp->tbt_sibling = tbtp;
3638 }else{
3639 if((tbtp = *(treep = &parentp->tbt_childs)) != NULL){
3640 for(;; tbtp = xtbtp){
3641 if(tbtp->tbt_char == wc){
3642 if(tbtp->tbt_isseq == isseq)
3643 goto jleave;
3644 /* isseq MUST be linked before, so it is impossible that we'll
3645 * find what we look for */
3646 if(isseq){
3647 #ifdef HAVE_DEBUG
3648 while((tbtp = tbtp->tbt_sibling) != NULL)
3649 assert(tbtp->tbt_char != wc);
3650 #endif
3651 tbtp = NULL;
3652 break;
3656 if((xtbtp = tbtp->tbt_sibling) == NULL){
3657 treep = &tbtp->tbt_sibling;
3658 break;
3663 xtbtp = smalloc(sizeof *xtbtp);
3664 memset(xtbtp, 0, sizeof *xtbtp);
3665 xtbtp->tbt_parent = parentp;
3666 xtbtp->tbt_char = wc;
3667 xtbtp->tbt_isseq = isseq;
3668 tbtp = xtbtp;
3669 *treep = tbtp;
3671 jleave:
3672 NYD2_LEAVE;
3673 return tbtp;
3676 static void
3677 a_tty__bind_tree_free(struct a_tty_bind_tree *tbtp){
3678 NYD2_ENTER;
3679 while(tbtp != NULL){
3680 struct a_tty_bind_tree *tmp;
3682 if((tmp = tbtp->tbt_childs) != NULL)
3683 a_tty__bind_tree_free(tmp);
3685 tmp = tbtp->tbt_sibling;
3686 free(tbtp);
3687 tbtp = tmp;
3689 NYD2_LEAVE;
3691 # endif /* HAVE_KEY_BINDINGS */
3693 FL void
3694 n_tty_init(void){
3695 NYD_ENTER;
3697 /* Load the history file */
3698 # ifdef HAVE_HISTORY
3699 do/* for break */{
3700 long hs;
3701 char const *v;
3702 char *lbuf;
3703 FILE *f;
3704 size_t lsize, cnt, llen;
3706 a_TTY_HISTSIZE(hs);
3707 a_tty.tg_hist_size = 0;
3708 a_tty.tg_hist_size_max = (size_t)hs;
3709 if(hs == 0)
3710 break;
3712 a_TTY_HISTFILE(v);
3713 if(v == NULL)
3714 break;
3716 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
3717 f = fopen(v, "r"); /* TODO HISTFILE LOAD: use linebuf pool */
3718 if(f == NULL)
3719 goto jhist_done;
3720 (void)n_file_lock(fileno(f), FLT_READ, 0,0, UIZ_MAX);
3722 lbuf = NULL;
3723 lsize = 0;
3724 cnt = (size_t)fsize(f);
3725 while(fgetline(&lbuf, &lsize, &cnt, &llen, f, FAL0) != NULL){
3726 if(llen > 0 && lbuf[llen - 1] == '\n')
3727 lbuf[--llen] = '\0';
3728 if(llen == 0 || lbuf[0] == '#') /* xxx comments? noone! */
3729 continue;
3730 else{
3731 bool_t isgabby;
3733 isgabby = (lbuf[0] == '*');
3734 n_tty_addhist(lbuf + isgabby, isgabby);
3737 if(lbuf != NULL)
3738 free(lbuf);
3740 fclose(f);
3741 jhist_done:
3742 rele_all_sigs(); /* XXX remove jumps */
3743 }while(0);
3744 # endif /* HAVE_HISTORY */
3746 /* Force immediate resolve for anything which follows */
3747 pstate |= PS_LINE_EDITOR_INIT;
3749 # ifdef HAVE_KEY_BINDINGS
3750 /* `bind's (and `unbind's) done from within resource files couldn't be
3751 * performed for real since our termcap driver wasn't yet loaded, and we
3752 * can't perform automatic init since the user may have disallowed so */
3753 /* C99 */{
3754 struct a_tty_bind_ctx *tbcp;
3755 enum n_lexinput_flags lif;
3757 for(lif = 0; lif < n__LEXINPUT_CTX_MAX; ++lif)
3758 for(tbcp = a_tty.tg_bind[lif]; tbcp != NULL; tbcp = tbcp->tbc_next)
3759 if((tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
3760 a_TTY_BIND_RESOLVE)
3761 a_tty_bind_resolve(tbcp);
3764 /* And we want to (try to) install some default key bindings */
3765 if(!ok_blook(line_editor_no_defaults)){
3766 char buf[8];
3767 struct a_tty_bind_parse_ctx tbpc;
3768 struct a_tty_bind_default_tuple const *tbdtp;
3770 buf[0] = '$', buf[1] = '\'', buf[2] = '\\', buf[3] = 'c',
3771 buf[5] = '\'', buf[6] = '\0';
3772 for(tbdtp = a_tty_bind_default_tuples;
3773 PTRCMP(tbdtp, <,
3774 &a_tty_bind_default_tuples[NELEM(a_tty_bind_default_tuples)]);
3775 ++tbdtp){
3776 memset(&tbpc, 0, sizeof tbpc);
3777 tbpc.tbpc_cmd = "bind";
3778 if(tbdtp->tbdt_iskey){
3779 buf[4] = tbdtp->tbdt_ckey;
3780 tbpc.tbpc_in_seq = buf;
3781 }else
3782 tbpc.tbpc_in_seq = savecatsep(":", '\0',
3783 n_termcap_name_of_query(tbdtp->tbdt_query));
3784 tbpc.tbpc_exp.s = UNCONST(tbdtp->tbdt_exp[0] == '\0'
3785 ? a_tty_bind_fun_names[(ui8_t)tbdtp->tbdt_exp[1]]
3786 : tbdtp->tbdt_exp);
3787 tbpc.tbpc_exp.l = strlen(tbpc.tbpc_exp.s);
3788 tbpc.tbpc_flags = n_LEXINPUT_CTX_BASE;
3789 /* ..but don't want to overwrite any user settings */
3790 a_tty_bind_create(&tbpc, FAL0);
3793 # endif /* HAVE_KEY_BINDINGS */
3795 NYD_LEAVE;
3798 FL void
3799 n_tty_destroy(void){
3800 NYD_ENTER;
3802 # ifdef HAVE_HISTORY
3803 do/* for break */{
3804 long hs;
3805 char const *v;
3806 struct a_tty_hist *thp;
3807 bool_t dogabby;
3808 FILE *f;
3810 a_TTY_HISTSIZE(hs);
3811 if(hs == 0)
3812 break;
3814 a_TTY_HISTFILE(v);
3815 if(v == NULL)
3816 break;
3818 dogabby = ok_blook(history_gabby_persist);
3820 if((thp = a_tty.tg_hist) != NULL)
3821 for(; thp->th_older != NULL; thp = thp->th_older)
3822 if((dogabby || !thp->th_isgabby) && --hs == 0)
3823 break;
3825 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
3826 f = fopen(v, "w"); /* TODO temporary + rename?! */
3827 if(f == NULL)
3828 goto jhist_done;
3829 (void)n_file_lock(fileno(f), FLT_WRITE, 0,0, UIZ_MAX);
3831 for(; thp != NULL; thp = thp->th_younger){
3832 if(dogabby || !thp->th_isgabby){
3833 if(thp->th_isgabby)
3834 putc('*', f);
3835 fwrite(thp->th_dat, sizeof *thp->th_dat, thp->th_len, f);
3836 putc('\n', f);
3839 fclose(f);
3840 jhist_done:
3841 rele_all_sigs(); /* XXX remove jumps */
3842 }while(0);
3843 # endif /* HAVE_HISTORY */
3845 # if defined HAVE_KEY_BINDINGS && defined HAVE_DEBUG
3846 c_unbind(UNCONST("* *"));
3847 # endif
3849 #ifdef HAVE_DEBUG
3850 memset(&a_tty, 0, sizeof a_tty);
3851 #endif
3852 DBG( pstate &= ~PS_LINE_EDITOR_INIT; )
3853 NYD_LEAVE;
3856 FL void
3857 n_tty_signal(int sig){
3858 sigset_t nset, oset;
3859 NYD_X; /* Signal handler */
3861 switch(sig){
3862 case SIGWINCH:
3863 /* We don't deal with SIGWINCH, yet get called from main.c */
3864 break;
3865 default:
3866 a_tty_term_mode(FAL0);
3867 n_TERMCAP_SUSPEND(TRU1);
3868 a_tty_sigs_down();
3870 sigemptyset(&nset);
3871 sigaddset(&nset, sig);
3872 sigprocmask(SIG_UNBLOCK, &nset, &oset);
3873 n_raise(sig);
3874 /* When we come here we'll continue editing, so reestablish */
3875 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
3877 a_tty_sigs_up();
3878 n_TERMCAP_RESUME(TRU1);
3879 a_tty_term_mode(TRU1);
3880 a_tty.tg_line->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
3881 break;
3885 FL int
3886 (n_tty_readline)(char const *prompt, char **linebuf, size_t *linesize, size_t n
3887 SMALLOC_DEBUG_ARGS){
3888 struct a_tty_line tl;
3889 # ifdef HAVE_COLOUR
3890 char *posbuf, *pos;
3891 # endif
3892 ui32_t plen, pwidth;
3893 ssize_t nn;
3894 char const *orig_prompt;
3895 NYD_ENTER;
3897 assert(pstate & PS_LINE_EDITOR_INIT);
3899 orig_prompt = prompt;
3900 jredo:
3901 /* TODO because of jumping away we cannot use srelax()ation: would be good */
3902 prompt = orig_prompt;
3904 # ifdef HAVE_COLOUR
3905 n_colour_env_create(n_COLOUR_CTX_MLE, FAL0);
3906 # endif
3908 /* Classify prompt */
3909 UNINIT(plen, 0);
3910 UNINIT(pwidth, 0);
3911 if(prompt != NULL){
3912 size_t i = strlen(prompt);
3914 if(i == 0 || i >= UI32_MAX)
3915 prompt = NULL;
3916 else{
3917 /* TODO *prompt* is in multibyte and not in a_tty_cell, therefore
3918 * TODO we cannot handle it in parts, it's all or nothing.
3919 * TODO Later (S-CText, SysV signals) the prompt should be some global
3920 * TODO carrier thing, fully evaluated and passed around as UI-enabled
3921 * TODO string, then we can print it character by character */
3922 struct n_visual_info_ctx vic;
3924 memset(&vic, 0, sizeof vic);
3925 vic.vic_indat = prompt;
3926 vic.vic_inlen = i;
3927 if(n_visual_info(&vic, n_VISUAL_INFO_WIDTH_QUERY)){
3928 pwidth = (ui32_t)vic.vic_vi_width;
3929 plen = (ui32_t)i;
3930 }else{
3931 n_err(_("Character set error in evaluation of prompt\n"));
3932 prompt = NULL;
3937 # ifdef HAVE_COLOUR
3938 /* C99 */{
3939 struct n_colour_pen *ccp;
3940 struct str const *sp;
3942 if(prompt != NULL &&
3943 (ccp = n_colour_pen_create(n_COLOUR_ID_MLE_PROMPT, NULL)) != NULL &&
3944 (sp = n_colour_pen_to_str(ccp)) != NULL){
3945 char const *ccol = sp->s;
3947 if((sp = n_colour_reset_to_str()) != NULL){
3948 size_t l1 = strlen(ccol), l2 = strlen(sp->s);
3949 ui32_t nplen = (ui32_t)(l1 + plen + l2);
3950 char *nprompt = salloc(nplen +1);
3952 memcpy(nprompt, ccol, l1);
3953 memcpy(&nprompt[l1], prompt, plen);
3954 memcpy(&nprompt[l1 += plen], sp->s, ++l2);
3956 prompt = nprompt;
3957 plen = nplen;
3961 /* .tl_pos_buf is a hack */
3962 posbuf = pos = NULL;
3963 if((ccp = n_colour_pen_create(n_COLOUR_ID_MLE_POSITION, NULL)) != NULL &&
3964 (sp = n_colour_pen_to_str(ccp)) != NULL){
3965 char const *ccol = sp->s;
3967 if((sp = n_colour_reset_to_str()) != NULL){
3968 size_t l1 = strlen(ccol), l2 = strlen(sp->s);
3970 posbuf = salloc(l1 + 4 + l2 +1);
3971 memcpy(posbuf, ccol, l1);
3972 pos = &posbuf[l1];
3973 memcpy(&pos[4], sp->s, ++l2);
3976 if(posbuf == NULL){
3977 posbuf = pos = salloc(4 +1);
3978 pos[4] = '\0';
3981 # endif /* HAVE_COLOUR */
3983 memset(&tl, 0, sizeof tl);
3985 # ifdef HAVE_KEY_BINDINGS
3986 /* C99 */{
3987 char const *cp = ok_vlook(bind_timeout);
3989 if(cp != NULL){
3990 ul_i ul;
3992 if((ul = strtoul(cp, NULL, 0)) > 0 &&
3993 /* Convert to tenths of a second, unfortunately */
3994 (ul = (ul + 99) / 100) <= a_TTY_BIND_TIMEOUT_MAX)
3995 tl.tl_bind_timeout = (ui8_t)ul;
3996 else if(options & OPT_D_V)
3997 n_err(_("Ignoring invalid *bind-timeout*: %s\n"), cp);
4001 /* TODO honour other bind contexts, like "compose" */
4002 if(a_tty.tg_bind_isdirty)
4003 a_tty_bind_tree_teardown();
4004 if(a_tty.tg_bind_cnt > 0 && !a_tty.tg_bind_isbuild)
4005 a_tty_bind_tree_build();
4006 tl.tl_bind_tree_hmap = &a_tty.tg_bind_tree[n_LEXINPUT_CTX_BASE];
4007 tl.tl_bind_shcut_cancel =
4008 &a_tty.tg_bind_shcut_cancel[n_LEXINPUT_CTX_BASE];
4009 tl.tl_bind_shcut_prompt_char =
4010 &a_tty.tg_bind_shcut_prompt_char[n_LEXINPUT_CTX_BASE];
4011 # endif /* HAVE_KEY_BINDINGS */
4013 if((tl.tl_prompt = prompt) != NULL){ /* XXX not re-evaluated */
4014 tl.tl_prompt_length = plen;
4015 tl.tl_prompt_width = pwidth;
4017 # ifdef HAVE_COLOUR
4018 tl.tl_pos_buf = posbuf;
4019 tl.tl_pos = pos;
4020 # endif
4022 tl.tl_line.cbuf = *linebuf;
4023 if(n != 0){
4024 tl.tl_defc.s = savestrbuf(*linebuf, n);
4025 tl.tl_defc.l = n;
4027 tl.tl_x_buf = linebuf;
4028 tl.tl_x_bufsize = linesize;
4030 a_tty.tg_line = &tl;
4031 a_tty_sigs_up();
4032 a_tty_term_mode(TRU1);
4033 nn = a_tty_readline(&tl, n SMALLOC_DEBUG_ARGSCALL);
4034 a_tty_term_mode(FAL0);
4035 a_tty_sigs_down();
4036 a_tty.tg_line = NULL;
4038 # ifdef HAVE_COLOUR
4039 n_colour_env_gut(stdout);
4040 # endif
4042 if(tl.tl_reenter_after_cmd != NULL){
4043 n = (nn <= 0) ? 0 : nn;
4044 n_source_command(tl.tl_reenter_after_cmd);
4045 goto jredo;
4047 NYD_LEAVE;
4048 return (int)nn;
4051 FL void
4052 n_tty_addhist(char const *s, bool_t isgabby){
4053 # ifdef HAVE_HISTORY
4054 /* Super-Heavy-Metal: block all sigs, avoid leaks+ on jump */
4055 ui32_t l;
4056 struct a_tty_hist *thp, *othp, *ythp;
4057 # endif
4058 NYD_ENTER;
4059 UNUSED(s);
4060 UNUSED(isgabby);
4062 # ifdef HAVE_HISTORY
4063 if(isgabby && !ok_blook(history_gabby))
4064 goto j_leave;
4066 if(a_tty.tg_hist_size_max == 0)
4067 goto j_leave;
4068 a_TTY_CHECK_ADDHIST(s, goto j_leave);
4070 l = (ui32_t)strlen(s);
4072 /* Eliminating duplicates is expensive, but simply inacceptable so
4073 * during the load of a potentially large history file! */
4074 if(pstate & PS_LINE_EDITOR_INIT)
4075 for(thp = a_tty.tg_hist; thp != NULL; thp = thp->th_older)
4076 if(thp->th_len == l && !strcmp(thp->th_dat, s)){
4077 hold_all_sigs(); /* TODO */
4078 if(thp->th_isgabby)
4079 thp->th_isgabby = !!isgabby;
4080 othp = thp->th_older;
4081 ythp = thp->th_younger;
4082 if(othp != NULL)
4083 othp->th_younger = ythp;
4084 else
4085 a_tty.tg_hist_tail = ythp;
4086 if(ythp != NULL)
4087 ythp->th_older = othp;
4088 else
4089 a_tty.tg_hist = othp;
4090 goto jleave;
4092 hold_all_sigs();
4094 ++a_tty.tg_hist_size;
4095 if((pstate & PS_LINE_EDITOR_INIT) &&
4096 a_tty.tg_hist_size > a_tty.tg_hist_size_max){
4097 --a_tty.tg_hist_size;
4098 if((thp = a_tty.tg_hist_tail) != NULL){
4099 if((a_tty.tg_hist_tail = thp->th_younger) == NULL)
4100 a_tty.tg_hist = NULL;
4101 else
4102 a_tty.tg_hist_tail->th_older = NULL;
4103 free(thp);
4107 thp = smalloc((sizeof(struct a_tty_hist) -
4108 VFIELD_SIZEOF(struct a_tty_hist, th_dat)) + l +1);
4109 thp->th_isgabby = !!isgabby;
4110 thp->th_len = l;
4111 memcpy(thp->th_dat, s, l +1);
4112 jleave:
4113 if((thp->th_older = a_tty.tg_hist) != NULL)
4114 a_tty.tg_hist->th_younger = thp;
4115 else
4116 a_tty.tg_hist_tail = thp;
4117 thp->th_younger = NULL;
4118 a_tty.tg_hist = thp;
4120 rele_all_sigs();
4121 j_leave:
4122 # endif
4123 NYD_LEAVE;
4126 # ifdef HAVE_HISTORY
4127 FL int
4128 c_history(void *v){
4129 C_HISTORY_SHARED;
4131 jlist:{
4132 FILE *fp;
4133 size_t i, b;
4134 struct a_tty_hist *thp;
4136 if(a_tty.tg_hist == NULL)
4137 goto jleave;
4139 if((fp = Ftmp(NULL, "hist", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
4140 n_perr(_("tmpfile"), 0);
4141 v = NULL;
4142 goto jleave;
4145 i = a_tty.tg_hist_size;
4146 b = 0;
4147 for(thp = a_tty.tg_hist; thp != NULL;
4148 --i, b += thp->th_len, thp = thp->th_older)
4149 fprintf(fp,
4150 "%c%4" PRIuZ ". %-50.50s (%4" PRIuZ "+%2" PRIu32 " B)\n",
4151 (thp->th_isgabby ? '*' : ' '), i, thp->th_dat, b, thp->th_len);
4153 page_or_print(fp, i);
4154 Fclose(fp);
4156 goto jleave;
4158 jclear:{
4159 struct a_tty_hist *thp;
4161 while((thp = a_tty.tg_hist) != NULL){
4162 a_tty.tg_hist = thp->th_older;
4163 free(thp);
4165 a_tty.tg_hist_tail = NULL;
4166 a_tty.tg_hist_size = 0;
4168 goto jleave;
4170 jentry:{
4171 struct a_tty_hist *thp;
4173 if(UICMP(z, entry, <=, a_tty.tg_hist_size)){
4174 entry = (long)a_tty.tg_hist_size - entry;
4175 for(thp = a_tty.tg_hist;; thp = thp->th_older)
4176 if(thp == NULL)
4177 break;
4178 else if(entry-- != 0)
4179 continue;
4180 else{
4181 v = temporary_arg_v_store = thp->th_dat;
4182 goto jleave;
4185 v = NULL;
4187 goto jleave;
4189 # endif /* HAVE_HISTORY */
4191 # ifdef HAVE_KEY_BINDINGS
4192 FL int
4193 c_bind(void *v){
4194 n_CMD_ARG_DESC_SUBCLASS_DEF(bind, 3, a_tty_bind_cad) { /* TODO cmd_tab.h */
4195 {n_CMD_ARG_DESC_STRING, 0},
4196 {n_CMD_ARG_DESC_WYSH | n_CMD_ARG_DESC_OPTION |
4197 n_CMD_ARG_DESC_HONOUR_STOP,
4198 n_SHEXP_PARSE_DRYRUN | n_SHEXP_PARSE_LOG},
4199 {n_CMD_ARG_DESC_WYSH | n_CMD_ARG_DESC_OPTION | n_CMD_ARG_DESC_GREEDY |
4200 n_CMD_ARG_DESC_HONOUR_STOP,
4201 n_SHEXP_PARSE_IGNORE_EMPTY}
4202 } n_CMD_ARG_DESC_SUBCLASS_DEF_END;
4203 struct n_cmd_arg_ctx cac;
4204 struct a_tty_bind_ctx *tbcp;
4205 enum n_lexinput_flags lif;
4206 bool_t aster, show;
4207 union {char const *cp; char *p; char c;} c;
4208 NYD_ENTER;
4210 cac.cac_desc = n_CMD_ARG_DESC_SUBCLASS_CAST(&a_tty_bind_cad);
4211 cac.cac_indat = v;
4212 cac.cac_inlen = UIZ_MAX;
4213 if(!n_cmd_arg_parse(&cac)){
4214 v = NULL;
4215 goto jleave;
4218 c.cp = cac.cac_arg->ca_arg.ca_str.s;
4219 if(cac.cac_no == 1)
4220 show = TRU1;
4221 else
4222 show = !asccasecmp(cac.cac_arg->ca_next->ca_arg.ca_str.s, "show");
4223 aster = FAL0;
4225 if((lif = a_tty_bind_ctx_find(c.cp)) == (enum n_lexinput_flags)-1){
4226 if(!(aster = n_is_all_or_aster(c.cp)) || !show){
4227 n_err(_("`bind': invalid context: %s\n"), c.cp);
4228 v = NULL;
4229 goto jleave;
4231 lif = 0;
4234 if(show){
4235 ui32_t lns;
4236 FILE *fp;
4238 if((fp = Ftmp(NULL, "bind", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
4239 n_perr(_("tmpfile"), 0);
4240 v = NULL;
4241 goto jleave;
4244 lns = 0;
4245 for(;;){
4246 for(tbcp = a_tty.tg_bind[lif]; tbcp != NULL;
4247 ++lns, tbcp = tbcp->tbc_next){
4248 /* Print the bytes of resolved terminal capabilities, then */
4249 if((options & OPT_D_V) &&
4250 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)
4251 ) == a_TTY_BIND_RESOLVE){
4252 char cbuf[8];
4253 union {wchar_t const *wp; char const *cp;} u;
4254 si32_t entlen;
4255 ui32_t cnvlen;
4256 char const *cnvdat, *bsep, *cbufp;
4258 putc('#', fp);
4259 putc(' ', fp);
4261 cbuf[0] = '=', cbuf[2] = '\0';
4262 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len;
4263 cnvlen > 0;){
4264 if(cnvdat != tbcp->tbc_cnv)
4265 putc(',', fp);
4267 /* {si32_t buf_len_iscap;} */
4268 entlen = *(si32_t const*)cnvdat;
4269 if(entlen & SI32_MIN){
4270 /* struct{si32_t buf_len_iscap; si32_t cap_len;
4271 * char buf[]+NUL;} */
4272 for(bsep = "",
4273 u.cp = (char const*)&((si32_t const*)cnvdat)[2];
4274 (c.c = *u.cp) != '\0'; ++u.cp){
4275 if(asciichar(c.c) && !cntrlchar(c.c))
4276 cbuf[1] = c.c, cbufp = cbuf;
4277 else
4278 cbufp = "";
4279 fprintf(fp, "%s%02X%s",
4280 bsep, (ui32_t)(ui8_t)c.c, cbufp);
4281 bsep = " ";
4283 entlen &= SI32_MAX;
4284 }else
4285 putc('-', fp);
4287 cnvlen -= entlen;
4288 cnvdat += entlen;
4291 fputs("\n ", fp);
4292 ++lns;
4295 fprintf(fp, "%sbind %s %s %s%s%s\n",
4296 ((tbcp->tbc_flags & a_TTY_BIND_DEFUNCT)
4297 /* I18N: `bind' sequence not working, either because it is
4298 * I18N: using Unicode and that is not available in the locale,
4299 * I18N: or a termcap(5)/terminfo(5) sequence won't work out */
4300 ? _("# <Defunctional> ") : ""),
4301 a_tty_bind_ctx_maps[lif].tbcm_name, tbcp->tbc_seq,
4302 n_shell_quote_cp(tbcp->tbc_exp, TRU1),
4303 (tbcp->tbc_flags & a_TTY_BIND_NOCOMMIT ? "@" : ""),
4304 (!(options & OPT_D_VV) ? ""
4305 : (tbcp->tbc_flags & a_TTY_BIND_FUN_INTERNAL
4306 ? _(" # MLE internal") : ""))
4309 if(!aster || ++lif >= n__LEXINPUT_CTX_MAX)
4310 break;
4312 page_or_print(fp, lns);
4314 Fclose(fp);
4315 }else{
4316 struct a_tty_bind_parse_ctx tbpc;
4317 struct n_string store;
4319 memset(&tbpc, 0, sizeof tbpc);
4320 tbpc.tbpc_cmd = a_tty_bind_cad.cad_name;
4321 tbpc.tbpc_in_seq = cac.cac_arg->ca_next->ca_arg.ca_str.s;
4322 tbpc.tbpc_exp.s = n_string_cp(n_cmd_arg_join_greedy(&cac,
4323 n_string_creat_auto(&store)));
4324 tbpc.tbpc_exp.l = store.s_len;
4325 tbpc.tbpc_flags = lif;
4326 if(!a_tty_bind_create(&tbpc, TRU1))
4327 v = NULL;
4328 n_string_gut(&store);
4330 jleave:
4331 NYD_LEAVE;
4332 return (v != NULL) ? EXIT_OK : EXIT_ERR;
4335 FL int
4336 c_unbind(void *v){
4337 n_CMD_ARG_DESC_SUBCLASS_DEF(unbind, 2, a_tty_unbind_cad) {/* TODO cmd_tab.h*/
4338 {n_CMD_ARG_DESC_STRING, 0},
4339 {n_CMD_ARG_DESC_WYSH | n_CMD_ARG_DESC_HONOUR_STOP,
4340 n_SHEXP_PARSE_DRYRUN | n_SHEXP_PARSE_LOG}
4341 } n_CMD_ARG_DESC_SUBCLASS_DEF_END;
4342 struct a_tty_bind_parse_ctx tbpc;
4343 struct n_cmd_arg_ctx cac;
4344 struct a_tty_bind_ctx *tbcp;
4345 enum n_lexinput_flags lif;
4346 bool_t aster;
4347 union {char const *cp; char *p;} c;
4348 NYD_ENTER;
4350 cac.cac_desc = n_CMD_ARG_DESC_SUBCLASS_CAST(&a_tty_unbind_cad);
4351 cac.cac_indat = v;
4352 cac.cac_inlen = UIZ_MAX;
4353 if(!n_cmd_arg_parse(&cac)){
4354 v = NULL;
4355 goto jleave;
4358 c.cp = cac.cac_arg->ca_arg.ca_str.s;
4359 aster = FAL0;
4361 if((lif = a_tty_bind_ctx_find(c.cp)) == (enum n_lexinput_flags)-1){
4362 if(!(aster = n_is_all_or_aster(c.cp))){
4363 n_err(_("`unbind': invalid context: %s\n"), c.cp);
4364 v = NULL;
4365 goto jleave;
4367 lif = 0;
4370 c.cp = cac.cac_arg->ca_next->ca_arg.ca_str.s;
4371 jredo:
4372 if(n_is_all_or_aster(c.cp)){
4373 while((tbcp = a_tty.tg_bind[lif]) != NULL){
4374 memset(&tbpc, 0, sizeof tbpc);
4375 tbpc.tbpc_tbcp = tbcp;
4376 tbpc.tbpc_flags = lif;
4377 a_tty_bind_del(&tbpc);
4379 }else{
4380 memset(&tbpc, 0, sizeof tbpc);
4381 tbpc.tbpc_cmd = a_tty_unbind_cad.cad_name;
4382 tbpc.tbpc_in_seq = c.cp;
4383 tbpc.tbpc_flags = lif;
4385 if(UNLIKELY(!a_tty_bind_parse(FAL0, &tbpc)))
4386 v = NULL;
4387 else if(UNLIKELY((tbcp = tbpc.tbpc_tbcp) == NULL)){
4388 n_err(_("`unbind': no such `bind'ing: %s %s\n"),
4389 a_tty_bind_ctx_maps[lif].tbcm_name, c.cp);
4390 v = NULL;
4391 }else
4392 a_tty_bind_del(&tbpc);
4395 if(aster && ++lif < n__LEXINPUT_CTX_MAX)
4396 goto jredo;
4397 jleave:
4398 NYD_LEAVE;
4399 return (v != NULL) ? EXIT_OK : EXIT_ERR;
4401 # endif /* HAVE_KEY_BINDINGS */
4402 #endif /* HAVE_MLE */
4405 * The really-nothing-at-all implementation
4407 #if !defined HAVE_READLINE && !defined HAVE_MLE
4409 FL void
4410 n_tty_init(void){
4411 NYD_ENTER;
4412 NYD_LEAVE;
4415 FL void
4416 n_tty_destroy(void){
4417 NYD_ENTER;
4418 NYD_LEAVE;
4421 FL void
4422 n_tty_signal(int sig){
4423 NYD_X; /* Signal handler */
4424 UNUSED(sig);
4426 # ifdef HAVE_TERMCAP
4427 switch(sig){
4428 default:{
4429 sigset_t nset, oset;
4431 n_TERMCAP_SUSPEND(TRU1);
4432 a_tty_sigs_down();
4434 sigemptyset(&nset);
4435 sigaddset(&nset, sig);
4436 sigprocmask(SIG_UNBLOCK, &nset, &oset);
4437 n_raise(sig);
4438 /* When we come here we'll continue editing, so reestablish */
4439 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
4441 a_tty_sigs_up();
4442 n_TERMCAP_RESUME(TRU1);
4443 break;
4446 # endif /* HAVE_TERMCAP */
4449 FL int
4450 (n_tty_readline)(char const *prompt, char **linebuf, size_t *linesize, size_t n
4451 SMALLOC_DEBUG_ARGS){
4452 int rv;
4453 NYD_ENTER;
4455 if(prompt != NULL){
4456 if(*prompt != '\0')
4457 fputs(prompt, stdout);
4458 fflush(stdout);
4460 # ifdef HAVE_TERMCAP
4461 a_tty_sigs_up();
4462 # endif
4463 rv = (readline_restart)(stdin, linebuf, linesize,n SMALLOC_DEBUG_ARGSCALL);
4464 # ifdef HAVE_TERMCAP
4465 a_tty_sigs_down();
4466 # endif
4467 NYD_LEAVE;
4468 return rv;
4471 FL void
4472 n_tty_addhist(char const *s, bool_t isgabby){
4473 NYD_ENTER;
4474 UNUSED(s);
4475 UNUSED(isgabby);
4476 NYD_LEAVE;
4478 #endif /* nothing at all */
4480 #undef a_TTY_SIGNALS
4481 /* s-it-mode */