a_go_evaluate(): fix un/signed comparison
[s-mailx.git] / tty.c
blobc9d170dbfaf02c1e61f0c7ebe8f1e36117587908
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ TTY (command line) editing interaction.
3 *@ Because we have (had) multiple line-editor implementations, including our
4 *@ own M(ailx) L(ine) E(ditor), change the file layout a bit and place those
5 *@ one after the other below the other externals.
7 * Copyright (c) 2012 - 2018 Steffen (Daode) Nurpmeso <steffen@sdaoden.eu>.
9 * Permission to use, copy, modify, and/or distribute this software for any
10 * purpose with or without fee is hereby granted, provided that the above
11 * copyright notice and this permission notice appear in all copies.
13 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
14 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
15 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
16 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
17 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21 #undef n_FILE
22 #define n_FILE tty
24 #ifndef HAVE_AMALGAMATION
25 # include "nail.h"
26 #endif
28 #if defined HAVE_MLE || defined HAVE_TERMCAP
29 # define a_TTY_SIGNALS
30 #endif
32 #ifdef a_TTY_SIGNALS
33 static sighandler_type a_tty_oint, a_tty_oquit, a_tty_oterm,
34 a_tty_ohup,
35 a_tty_otstp, a_tty_ottin, a_tty_ottou;
36 #endif
38 #ifdef a_TTY_SIGNALS
39 static void a_tty_sigs_up(void), a_tty_sigs_down(void);
40 #endif
42 /* Prototype here, implementation is specific to chosen editor */
43 static void a_tty_signal(int sig);
45 #ifdef a_TTY_SIGNALS
46 static void
47 a_tty_sigs_up(void){
48 sigset_t nset, oset;
49 NYD2_ENTER;
51 sigfillset(&nset);
53 sigprocmask(SIG_BLOCK, &nset, &oset);
54 a_tty_oint = safe_signal(SIGINT, &a_tty_signal);
55 a_tty_oquit = safe_signal(SIGQUIT, &a_tty_signal);
56 a_tty_oterm = safe_signal(SIGTERM, &a_tty_signal);
57 a_tty_ohup = safe_signal(SIGHUP, &a_tty_signal);
58 a_tty_otstp = safe_signal(SIGTSTP, &a_tty_signal);
59 a_tty_ottin = safe_signal(SIGTTIN, &a_tty_signal);
60 a_tty_ottou = safe_signal(SIGTTOU, &a_tty_signal);
61 sigprocmask(SIG_SETMASK, &oset, NULL);
62 NYD2_LEAVE;
65 static void
66 a_tty_sigs_down(void){
67 sigset_t nset, oset;
68 NYD2_ENTER;
70 sigfillset(&nset);
72 sigprocmask(SIG_BLOCK, &nset, &oset);
73 safe_signal(SIGINT, a_tty_oint);
74 safe_signal(SIGQUIT, a_tty_oquit);
75 safe_signal(SIGTERM, a_tty_oterm);
76 safe_signal(SIGHUP, a_tty_ohup);
77 safe_signal(SIGTSTP, a_tty_otstp);
78 safe_signal(SIGTTIN, a_tty_ottin);
79 safe_signal(SIGTTOU, a_tty_ottou);
80 sigprocmask(SIG_SETMASK, &oset, NULL);
81 NYD2_LEAVE;
83 #endif /* a_TTY_SIGNALS */
85 static sigjmp_buf a_tty__actjmp; /* TODO someday, we won't need it no more */
86 static void
87 a_tty__acthdl(int s) /* TODO someday, we won't need it no more */
89 NYD_X; /* Signal handler */
90 siglongjmp(a_tty__actjmp, s);
93 FL bool_t
94 getapproval(char const * volatile prompt, bool_t noninteract_default)
96 sighandler_type volatile oint, ohup;
97 bool_t volatile rv;
98 int volatile sig;
99 NYD_ENTER;
101 if(!(n_psonce & n_PSO_INTERACTIVE) || (n_pstate & n_PS_ROBOT)){
102 sig = 0;
103 rv = noninteract_default;
104 goto jleave;
106 rv = FAL0;
108 /* C99 */{
109 char const *quest = noninteract_default
110 ? _("[yes]/no? ") : _("[no]/yes? ");
112 if (prompt == NULL)
113 prompt = _("Continue");
114 prompt = savecatsep(prompt, ' ', quest);
117 oint = safe_signal(SIGINT, SIG_IGN);
118 ohup = safe_signal(SIGHUP, SIG_IGN);
119 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
120 goto jrestore;
121 safe_signal(SIGINT, &a_tty__acthdl);
122 safe_signal(SIGHUP, &a_tty__acthdl);
124 while(n_go_input(n_GO_INPUT_CTX_DEFAULT | n_GO_INPUT_NL_ESC, prompt,
125 &termios_state.ts_linebuf, &termios_state.ts_linesize, NULL,NULL
126 ) >= 0){
127 bool_t x;
129 x = n_boolify(termios_state.ts_linebuf, UIZ_MAX, noninteract_default);
130 if(x >= FAL0){
131 rv = x;
132 break;
135 jrestore:
136 safe_signal(SIGHUP, ohup);
137 safe_signal(SIGINT, oint);
138 jleave:
139 NYD_LEAVE;
140 if (sig != 0)
141 n_raise(sig);
142 return rv;
145 #ifdef HAVE_SOCKETS
146 FL char *
147 getuser(char const * volatile query) /* TODO v15-compat obsolete */
149 sighandler_type volatile oint, ohup;
150 char * volatile user = NULL;
151 int volatile sig;
152 NYD_ENTER;
154 if (query == NULL)
155 query = _("User: ");
157 oint = safe_signal(SIGINT, SIG_IGN);
158 ohup = safe_signal(SIGHUP, SIG_IGN);
159 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
160 goto jrestore;
161 safe_signal(SIGINT, &a_tty__acthdl);
162 safe_signal(SIGHUP, &a_tty__acthdl);
164 if (n_go_input(n_GO_INPUT_CTX_DEFAULT | n_GO_INPUT_NL_ESC, query,
165 &termios_state.ts_linebuf, &termios_state.ts_linesize, NULL,NULL) >= 0)
166 user = termios_state.ts_linebuf;
168 jrestore:
169 safe_signal(SIGHUP, ohup);
170 safe_signal(SIGINT, oint);
172 NYD_LEAVE;
173 if (sig != 0)
174 n_raise(sig);
175 return user;
178 FL char *
179 getpassword(char const *query)/* TODO v15: use _only_ n_tty_fp! */
181 sighandler_type volatile oint, ohup;
182 struct termios tios;
183 char * volatile pass;
184 int volatile sig;
185 NYD_ENTER;
187 pass = NULL;
188 if(!(n_psonce & n_PSO_TTYIN))
189 goto j_leave;
191 if (query == NULL)
192 query = _("Password: ");
193 fputs(query, n_tty_fp);
194 fflush(n_tty_fp);
196 /* FIXME everywhere: tcsetattr() generates SIGTTOU when we're not in
197 * FIXME foreground pgrp, and can fail with EINTR!! also affects
198 * FIXME termios_state_reset() */
199 tcgetattr(STDIN_FILENO, &termios_state.ts_tios);
200 memcpy(&tios, &termios_state.ts_tios, sizeof tios);
201 termios_state.ts_needs_reset = TRU1;
202 tios.c_iflag &= ~(ISTRIP);
203 tios.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
205 oint = safe_signal(SIGINT, SIG_IGN);
206 ohup = safe_signal(SIGHUP, SIG_IGN);
207 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
208 goto jrestore;
209 safe_signal(SIGINT, &a_tty__acthdl);
210 safe_signal(SIGHUP, &a_tty__acthdl);
212 tcsetattr(STDIN_FILENO, TCSAFLUSH, &tios);
213 if (readline_restart(n_stdin, &termios_state.ts_linebuf,
214 &termios_state.ts_linesize, 0) >= 0)
215 pass = termios_state.ts_linebuf;
216 jrestore:
217 termios_state_reset();
218 putc('\n', n_tty_fp);
220 safe_signal(SIGHUP, ohup);
221 safe_signal(SIGINT, oint);
222 NYD_LEAVE;
223 if (sig != 0)
224 n_raise(sig);
225 j_leave:
226 return pass;
228 #endif /* HAVE_SOCKETS */
230 FL ui32_t
231 n_tty_create_prompt(struct n_string *store, char const *xprompt,
232 enum n_go_input_flags gif){
233 struct n_visual_info_ctx vic;
234 struct str in, out;
235 ui32_t pwidth;
236 char const *cp;
237 NYD2_ENTER;
239 /* Prompt creation indicates that prompt printing is directly ahead, so take
240 * this opportunity of UI-in-a-known-state and advertise the error ring */
241 #ifdef HAVE_ERRORS
242 if((n_psonce & (n_PSO_INTERACTIVE | n_PSO_ERRORS_NOTED)
243 ) == n_PSO_INTERACTIVE && (n_pstate & n_PS_ERRORS_PROMPT)){
244 n_psonce |= n_PSO_ERRORS_NOTED;
245 fprintf(n_stdout, _("There are new messages in the error message ring "
246 "(denoted by %s)\n"
247 " The `errors' command manages this message ring\n"),
248 V_(n_error));
250 #endif
252 jredo:
253 n_string_trunc(store, 0);
255 if(gif & n_GO_INPUT_PROMPT_NONE){
256 pwidth = 0;
257 goto jleave;
259 #ifdef HAVE_ERRORS
260 if(n_pstate & n_PS_ERRORS_PROMPT){
261 n_pstate &= ~n_PS_ERRORS_PROMPT;
262 store = n_string_push_cp(store, V_(n_error));
263 store = n_string_push_c(store, '#');
264 store = n_string_push_c(store, ' ');
266 #endif
268 cp = (gif & n_GO_INPUT_PROMPT_EVAL)
269 ? (gif & n_GO_INPUT_NL_FOLLOW ? ok_vlook(prompt2) : ok_vlook(prompt))
270 : xprompt;
271 if(cp != NULL && *cp != '\0'){
272 enum n_shexp_state shs;
274 store = n_string_push_cp(store, cp);
275 in.s = n_string_cp(store);
276 in.l = store->s_len;
277 out = in;
278 store = n_string_drop_ownership(store);
280 shs = n_shexp_parse_token((n_SHEXP_PARSE_LOG |
281 n_SHEXP_PARSE_IGNORE_EMPTY | n_SHEXP_PARSE_QUOTE_AUTO_FIXED |
282 n_SHEXP_PARSE_QUOTE_AUTO_DSQ), store, &in, NULL);
283 if((shs & n_SHEXP_STATE_ERR_MASK) || !(shs & n_SHEXP_STATE_STOP)){
284 store = n_string_clear(store);
285 store = n_string_take_ownership(store, out.s, out.l +1, out.l);
286 jeeval:
287 n_err(_("*prompt2?* evaluation failed, actively unsetting it\n"));
288 if(gif & n_GO_INPUT_NL_FOLLOW)
289 ok_vclear(prompt2);
290 else
291 ok_vclear(prompt);
292 goto jredo;
295 if(!store->s_auto)
296 n_free(out.s);
299 /* Make all printable TODO not know, we want to pass through ESC/CSI! */
300 #if 0
301 in.s = n_string_cp(store);
302 in.l = store->s_len;
303 makeprint(&in, &out);
304 store = n_string_assign_buf(store, out.s, out.l);
305 n_free(out.s);
306 #endif
308 /* We need the visual width.. */
309 memset(&vic, 0, sizeof vic);
310 vic.vic_indat = n_string_cp(store);
311 vic.vic_inlen = store->s_len;
312 for(pwidth = 0; vic.vic_inlen > 0;){
313 /* but \[ .. \] is not taken into account */
314 if(vic.vic_indat[0] == '\\' && vic.vic_inlen > 1 &&
315 vic.vic_indat[1] == '['){
316 size_t i;
318 i = PTR2SIZE(vic.vic_indat - store->s_dat);
319 store = n_string_cut(store, i, 2);
320 cp = &n_string_cp(store)[i];
321 i = store->s_len - i;
322 for(;; ++cp, --i){
323 if(i < 2){
324 n_err(_("Open \\[ sequence not closed in *prompt2?*\n"));
325 goto jeeval;
327 if(cp[0] == '\\' && cp[1] == ']')
328 break;
330 i = PTR2SIZE(cp - store->s_dat);
331 store = n_string_cut(store, i, 2);
332 vic.vic_indat = &n_string_cp(store)[i];
333 vic.vic_inlen = store->s_len - i;
334 }else if(!n_visual_info(&vic, n_VISUAL_INFO_WIDTH_QUERY |
335 n_VISUAL_INFO_ONE_CHAR)){
336 n_err(_("Character set error in evaluation of *prompt2?*\n"));
337 goto jeeval;
338 }else{
339 pwidth += (ui32_t)vic.vic_vi_width;
340 vic.vic_indat = vic.vic_oudat;
341 vic.vic_inlen = vic.vic_oulen;
345 /* And there may be colour support, too */
346 #ifdef HAVE_COLOUR
347 if(n_COLOUR_IS_ACTIVE()){
348 struct str const *psp, *rsp;
349 struct n_colour_pen *ccp;
351 if((ccp = n_colour_pen_create(n_COLOUR_ID_MLE_PROMPT, NULL)) != NULL &&
352 (psp = n_colour_pen_to_str(ccp)) != NULL &&
353 (rsp = n_colour_reset_to_str()) != NULL){
354 store = n_string_unshift_buf(store, psp->s, psp->l);
355 /*store =*/ n_string_push_buf(store, rsp->s, rsp->l);
358 #endif /* HAVE_COLOUR */
360 jleave:
361 NYD2_LEAVE;
362 return pwidth;
366 * MLE: the Mailx-Line-Editor, our homebrew editor
367 * (inspired from NetBSDs sh(1) and dash(1)s hetio.c).
369 * Only used in interactive mode.
370 * TODO . This code should be splitted in funs/raw input/bind modules.
371 * TODO . We work with wide characters, but not for buffer takeovers and
372 * TODO cell2save()ings. This should be changed. For the former the buffer
373 * TODO thus needs to be converted to wide first, and then simply be fed in.
374 * TODO . We repaint too much. To overcome this use the same approach that my
375 * TODO terminal library uses, add a true "virtual screen line" that stores
376 * TODO the actually visible content, keep a notion of "first modified slot"
377 * TODO and "last modified slot" (including "unknown" and "any" specials),
378 * TODO update that virtual instead, then synchronize what has truly changed.
379 * TODO I.e., add an indirection layer.
380 * TODO . No BIDI support.
381 * TODO . `bind': we currently use only one lookup tree.
382 * TODO For absolute graceful behaviour (in conjunction with HAVE_TERMCAP) we
383 * TODO need a lower level tree, which possibly combines bytes into "symbolic
384 * TODO wchar_t values", into "keys" that is, as applicable, and an upper
385 * TODO layer which only works on "keys" in order to possibly combine them
386 * TODO into key sequences. We can reuse existent tree code for that.
387 * TODO We need an additional hashmap which maps termcap/terminfo names to
388 * TODO (their byte representations and) a dynamically assigned unique
389 * TODO "symbolic wchar_t value". This implies we may have incompatibilities
390 * TODO when __STDC_ISO_10646__ is not defined. Also we do need takeover-
391 * TODO bytes storage, but it can be a string_creat_auto in the line struct.
392 * TODO Until then we can run into ambiguities; in rare occasions.
394 #ifdef HAVE_MLE
395 /* To avoid memory leaks etc. with the current codebase that simply longjmp(3)s
396 * we're forced to use the very same buffer--the one that is passed through to
397 * us from the outside--to store anything we need, i.e., a "struct cell[]", and
398 * convert that on-the-fly back to the plain char* result once we're done.
399 * To simplify our live, use savestr() buffers for all other needed memory */
401 # ifdef HAVE_KEY_BINDINGS
402 /* Default *bind-timeout* key-sequence continuation timeout, in tenths of
403 * a second. Must fit in 8-bit! Update the manual upon change! */
404 # define a_TTY_BIND_TIMEOUT 2
405 # define a_TTY_BIND_TIMEOUT_MAX SI8_MAX
407 n_CTAV(a_TTY_BIND_TIMEOUT_MAX <= UI8_MAX);
409 /* We have a chicken-and-egg problem with `bind' and our termcap layer,
410 * because we may not initialize the latter automatically to allow users to
411 * specify *termcap-disable* and let it mean exactly that.
412 * On the other hand users can be expected to use `bind' in resources.
413 * Therefore bindings which involve termcap/terminfo sequences, and which
414 * are defined before n_PSO_STARTED signals usability of termcap/terminfo,
415 * will be (partially) delayed until tty_init() is called.
416 * And we preallocate space for the expansion of the resolved capability */
417 # define a_TTY_BIND_CAPNAME_MAX 15
418 # define a_TTY_BIND_CAPEXP_ROUNDUP 16
420 n_CTAV(n_ISPOW2(a_TTY_BIND_CAPEXP_ROUNDUP));
421 n_CTA(a_TTY_BIND_CAPEXP_ROUNDUP <= SI8_MAX / 2, "Variable must fit in 6-bit");
422 n_CTA(a_TTY_BIND_CAPEXP_ROUNDUP >= 8, "Variable too small");
423 # endif /* HAVE_KEY_BINDINGS */
425 # ifdef HAVE_HISTORY
426 /* The first line of the history file is used as a marker after >v14.9.6 */
427 # define a_TTY_HIST_MARKER "@s-mailx history v2"
428 # endif
430 /* The maximum size (of a_tty_cell's) in a line */
431 # define a_TTY_LINE_MAX SI32_MAX
433 /* (Some more CTAs around) */
434 n_CTA(a_TTY_LINE_MAX <= SI32_MAX,
435 "a_TTY_LINE_MAX larger than SI32_MAX, but the MLE uses 32-bit arithmetic");
437 /* When shall the visual screen be scrolled, in % of usable screen width */
438 # define a_TTY_SCROLL_MARGIN_LEFT 15
439 # define a_TTY_SCROLL_MARGIN_RIGHT 10
441 /* fexpand() flags for expand-on-tab */
442 # define a_TTY_TAB_FEXP_FL \
443 (FEXP_NOPROTO | FEXP_FULL | FEXP_SILENT | FEXP_MULTIOK)
445 /* Columns to ripoff: outermost may not be touched, plus position indicator.
446 * Must thus be at least 1, but should be >= 1+4 to dig the position indicator
447 * that we place (if there is sufficient space) */
448 # define a_TTY_WIDTH_RIPOFF 5
450 /* The implementation of the MLE functions always exists, and is based upon
451 * the a_TTY_BIND_FUN_* constants, so most of this enum is always necessary */
452 enum a_tty_bind_flags{
453 # ifdef HAVE_KEY_BINDINGS
454 a_TTY_BIND_RESOLVE = 1u<<8, /* Term cap. yet needs to be resolved */
455 a_TTY_BIND_DEFUNCT = 1u<<9, /* Unicode/term cap. used but not avail. */
456 a_TTY__BIND_MASK = a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT,
457 /* MLE fun assigned to a one-byte-sequence: this may be used for special
458 * key-sequence bypass processing */
459 a_TTY_BIND_MLE1CNTRL = 1u<<10,
460 a_TTY_BIND_NOCOMMIT = 1u<<11, /* Expansion shall be editable */
461 # endif
463 /* MLE internal commands XXX Can these be values not bits? */
464 a_TTY_BIND_FUN_INTERNAL = 1u<<15,
465 a_TTY__BIND_FUN_SHIFT = 16u,
466 a_TTY__BIND_FUN_SHIFTMAX = 24u,
467 a_TTY__BIND_FUN_MASK = ((1u << a_TTY__BIND_FUN_SHIFTMAX) - 1) &
468 ~((1u << a_TTY__BIND_FUN_SHIFT) - 1),
469 # define a_TTY_BIND_FUN_REDUCE(X) \
470 (((ui32_t)(X) & a_TTY__BIND_FUN_MASK) >> a_TTY__BIND_FUN_SHIFT)
471 # define a_TTY_BIND_FUN_EXPAND(X) \
472 (((ui32_t)(X) & (a_TTY__BIND_FUN_MASK >> a_TTY__BIND_FUN_SHIFT)) << \
473 a_TTY__BIND_FUN_SHIFT)
474 # undef a_X
475 # define a_X(N,I)\
476 a_TTY_BIND_FUN_ ## N = a_TTY_BIND_FUN_EXPAND(I),
478 a_X(BELL, 0)
479 a_X(GO_BWD, 1) a_X(GO_FWD, 2)
480 a_X(GO_WORD_BWD, 3) a_X(GO_WORD_FWD, 4)
481 a_X(GO_SCREEN_BWD, 5) a_X(GO_SCREEN_FWD, 6)
482 a_X(GO_HOME, 7) a_X(GO_END, 8)
483 a_X(DEL_BWD, 9) a_X(DEL_FWD, 10)
484 a_X(SNARF_WORD_BWD, 11) a_X(SNARF_WORD_FWD, 12)
485 a_X(SNARF_END, 13) a_X(SNARF_LINE, 14)
486 a_X(HIST_BWD, 15) a_X(HIST_FWD, 16)
487 a_X(HIST_SRCH_BWD, 17) a_X(HIST_SRCH_FWD, 18)
488 a_X(REPAINT, 19)
489 a_X(QUOTE_RNDTRIP, 20)
490 a_X(PROMPT_CHAR, 21)
491 a_X(COMPLETE, 22)
492 a_X(PASTE, 23)
493 a_X(CLEAR_SCREEN, 24)
495 a_X(CANCEL, 25)
496 a_X(RESET, 26)
497 a_X(FULLRESET, 27)
498 a_X(COMMIT, 28) /* Must be last one! */
499 # undef a_X
501 a_TTY__BIND_LAST = 1<<28
503 # ifdef HAVE_KEY_BINDINGS
504 n_CTA((ui32_t)a_TTY_BIND_RESOLVE >= (ui32_t)n__GO_INPUT_CTX_MAX1,
505 "Bit carrier lower boundary must be raised to avoid value sharing");
506 # endif
507 n_CTA(a_TTY_BIND_FUN_EXPAND(a_TTY_BIND_FUN_COMMIT) <
508 (1 << a_TTY__BIND_FUN_SHIFTMAX),
509 "Bit carrier range must be expanded to represent necessary bits");
510 n_CTA(a_TTY__BIND_LAST >= (1u << a_TTY__BIND_FUN_SHIFTMAX),
511 "Bit carrier upper boundary must be raised to avoid value sharing");
512 n_CTA(UICMP(64, a_TTY__BIND_LAST, <=, SI32_MAX),
513 "Flag bits excess storage datatype" /* And we need one bit free */);
515 enum a_tty_fun_status{
516 a_TTY_FUN_STATUS_OK, /* Worked, next character */
517 a_TTY_FUN_STATUS_COMMIT, /* Line done */
518 a_TTY_FUN_STATUS_RESTART, /* Complete restart, reset multibyte etc. */
519 a_TTY_FUN_STATUS_END /* End, return EOF */
522 # ifdef HAVE_HISTORY
523 enum a_tty_hist_flags{
524 a_TTY_HIST_CTX_DEFAULT = n_GO_INPUT_CTX_DEFAULT,
525 a_TTY_HIST_CTX_COMPOSE = n_GO_INPUT_CTX_COMPOSE,
526 a_TTY_HIST_CTX_MASK = n__GO_INPUT_CTX_MASK,
527 /* Cannot use enum n_go_input_flags for the rest, need to stay in 8-bit */
528 a_TTY_HIST_GABBY = 1u<<7,
529 a_TTY_HIST__MAX = a_TTY_HIST_GABBY
531 n_CTA(a_TTY_HIST_CTX_MASK < a_TTY_HIST_GABBY, "Enumeration value overlap");
532 # endif
534 enum a_tty_visual_flags{
535 a_TTY_VF_NONE,
536 a_TTY_VF_MOD_CURSOR = 1u<<0, /* Cursor moved */
537 a_TTY_VF_MOD_CONTENT = 1u<<1, /* Content modified */
538 a_TTY_VF_MOD_DIRTY = 1u<<2, /* Needs complete repaint */
539 a_TTY_VF_MOD_SINGLE = 1u<<3, /* TODO Drop when indirection as above comes */
540 a_TTY_VF_REFRESH = a_TTY_VF_MOD_DIRTY | a_TTY_VF_MOD_CURSOR |
541 a_TTY_VF_MOD_CONTENT | a_TTY_VF_MOD_SINGLE,
542 a_TTY_VF_BELL = 1u<<8, /* Ring the bell */
543 a_TTY_VF_SYNC = 1u<<9, /* Flush/Sync I/O channel */
545 a_TTY_VF_ALL_MASK = a_TTY_VF_REFRESH | a_TTY_VF_BELL | a_TTY_VF_SYNC,
546 a_TTY__VF_LAST = a_TTY_VF_SYNC
549 # ifdef HAVE_KEY_BINDINGS
550 struct a_tty_bind_ctx{
551 struct a_tty_bind_ctx *tbc_next;
552 char *tbc_seq; /* quence as given (poss. re-quoted), in .tb__buf */
553 char *tbc_exp; /* ansion, in .tb__buf */
554 /* The .tbc_seq'uence with any terminal capabilities resolved; in fact an
555 * array of structures, the first entry of which is {si32_t buf_len_iscap;}
556 * where the signed bit indicates whether the buffer is a resolved terminal
557 * capability instead of a (possibly multibyte) character. In .tbc__buf */
558 char *tbc_cnv;
559 ui32_t tbc_seq_len;
560 ui32_t tbc_exp_len;
561 ui32_t tbc_cnv_len;
562 ui32_t tbc_flags;
563 char tbc__buf[n_VFIELD_SIZE(0)];
566 struct a_tty_bind_ctx_map{
567 enum n_go_input_flags tbcm_ctx;
568 char const tbcm_name[12]; /* Name of `bind' context */
570 # endif /* HAVE_KEY_BINDINGS */
572 struct a_tty_bind_builtin_tuple{
573 bool_t tbbt_iskey; /* Whether this is a control key; else termcap query */
574 char tbbt_ckey; /* Control code */
575 ui16_t tbbt_query; /* enum n_termcap_query (instead) */
576 char tbbt_exp[12]; /* String or [0]=NUL/[1]=BIND_FUN_REDUCE() */
578 n_CTA(n__TERMCAP_QUERY_MAX1 <= UI16_MAX,
579 "Enumeration cannot be stored in datatype");
581 # ifdef HAVE_KEY_BINDINGS
582 struct a_tty_bind_parse_ctx{
583 char const *tbpc_cmd; /* Command which parses */
584 char const *tbpc_in_seq; /* In: key sequence */
585 struct str tbpc_exp; /* In/Out: expansion (or NULL) */
586 struct a_tty_bind_ctx *tbpc_tbcp; /* Out: if yet existent */
587 struct a_tty_bind_ctx *tbpc_ltbcp; /* Out: the one before .tbpc_tbcp */
588 char *tbpc_seq; /* Out: normalized sequence */
589 char *tbpc_cnv; /* Out: sequence when read(2)ing it */
590 ui32_t tbpc_seq_len;
591 ui32_t tbpc_cnv_len;
592 ui32_t tbpc_cnv_align_mask; /* For creating a_tty_bind_ctx.tbc_cnv */
593 ui32_t tbpc_flags; /* n_go_input_flags | a_tty_bind_flags */
596 /* Input character tree */
597 struct a_tty_bind_tree{
598 struct a_tty_bind_tree *tbt_sibling; /* s at same level */
599 struct a_tty_bind_tree *tbt_childs; /* Sequence continues.. here */
600 struct a_tty_bind_tree *tbt_parent;
601 struct a_tty_bind_ctx *tbt_bind; /* NULL for intermediates */
602 wchar_t tbt_char; /* acter this level represents */
603 bool_t tbt_isseq; /* Belongs to multibyte sequence */
604 bool_t tbt_isseq_trail; /* ..is trailing byte of it */
605 ui8_t tbt__dummy[2];
607 # endif /* HAVE_KEY_BINDINGS */
609 struct a_tty_cell{
610 wchar_t tc_wc;
611 ui16_t tc_count; /* ..of bytes */
612 ui8_t tc_width; /* Visual width; TAB==UI8_MAX! */
613 bool_t tc_novis; /* Don't display visually as such (control character) */
614 char tc_cbuf[MB_LEN_MAX * 2]; /* .. plus reset shift sequence */
617 struct a_tty_global{
618 struct a_tty_line *tg_line; /* To be able to access it from signal hdl */
619 # ifdef HAVE_HISTORY
620 struct a_tty_hist *tg_hist;
621 struct a_tty_hist *tg_hist_tail;
622 size_t tg_hist_size;
623 size_t tg_hist_size_max;
624 # endif
625 # ifdef HAVE_KEY_BINDINGS
626 ui32_t tg_bind_cnt; /* Overall number of bindings */
627 bool_t tg_bind_isdirty;
628 bool_t tg_bind_isbuild;
629 # define a_TTY_SHCUT_MAX (3 +1) /* Note: update manual on change! */
630 ui8_t tg_bind__dummy[2];
631 char tg_bind_shcut_cancel[n__GO_INPUT_CTX_MAX1][a_TTY_SHCUT_MAX];
632 char tg_bind_shcut_prompt_char[n__GO_INPUT_CTX_MAX1][a_TTY_SHCUT_MAX];
633 struct a_tty_bind_ctx *tg_bind[n__GO_INPUT_CTX_MAX1];
634 struct a_tty_bind_tree *tg_bind_tree[n__GO_INPUT_CTX_MAX1][HSHSIZE];
635 # endif
636 struct termios tg_tios_old;
637 struct termios tg_tios_new;
639 # ifdef HAVE_KEY_BINDINGS
640 n_CTA(n__GO_INPUT_CTX_MAX1 == 3 && a_TTY_SHCUT_MAX == 4 &&
641 n_SIZEOF_FIELD(struct a_tty_global, tg_bind__dummy) == 2,
642 "Value results in array sizes that results in bad structure layout");
643 n_CTA(a_TTY_SHCUT_MAX > 1,
644 "Users need at least one shortcut, plus NUL terminator");
645 # endif
647 # ifdef HAVE_HISTORY
648 struct a_tty_hist{
649 struct a_tty_hist *th_older;
650 struct a_tty_hist *th_younger;
651 ui32_t th_len;
652 ui8_t th_flags; /* enum a_tty_hist_flags */
653 char th_dat[n_VFIELD_SIZE(3)];
655 n_CTA(UI8_MAX >= a_TTY_HIST__MAX, "Value exceeds datatype storage");
656 # endif
658 struct a_tty_line{
659 /* Caller pointers */
660 char **tl_x_buf;
661 size_t *tl_x_bufsize;
662 /* Input processing */
663 # ifdef HAVE_KEY_BINDINGS
664 wchar_t tl_bind_takeover; /* Leftover byte to consume next */
665 ui8_t tl_bind_timeout; /* In-seq. inter-byte-timer, in 1/10th secs */
666 ui8_t tl__bind_dummy[3];
667 char (*tl_bind_shcut_cancel)[a_TTY_SHCUT_MAX]; /* Special _CANCEL control */
668 char (*tl_bind_shcut_prompt_char)[a_TTY_SHCUT_MAX]; /* ..for _PROMPT_CHAR */
669 struct a_tty_bind_tree *(*tl_bind_tree_hmap)[HSHSIZE]; /* Bind lookup tree */
670 struct a_tty_bind_tree *tl_bind_tree;
671 # endif
672 /* Line data / content handling */
673 ui32_t tl_count; /* ..of a_tty_cell's (<= a_TTY_LINE_MAX) */
674 ui32_t tl_cursor; /* Current a_tty_cell insertion point */
675 union{
676 char *cbuf; /* *.tl_x_buf */
677 struct a_tty_cell *cells;
678 } tl_line;
679 struct str tl_defc; /* Current default content */
680 size_t tl_defc_cursor_byte; /* Desired position of cursor after takeover */
681 struct str tl_savec; /* Saved default content */
682 struct str tl_pastebuf; /* Last snarfed data */
683 # ifdef HAVE_HISTORY
684 struct a_tty_hist *tl_hist; /* History cursor */
685 # endif
686 ui32_t tl_count_max; /* ..before buffer needs to grow */
687 /* Visual data representation handling */
688 ui32_t tl_vi_flags; /* enum a_tty_visual_flags */
689 ui32_t tl_lst_count; /* .tl_count after last sync */
690 ui32_t tl_lst_cursor; /* .tl_cursor after last sync */
691 /* TODO Add another indirection layer by adding a tl_phy_line of
692 * TODO a_tty_cell objects, incorporate changes in visual layer,
693 * TODO then check what _really_ has changed, sync those changes only */
694 struct a_tty_cell const *tl_phy_start; /* First visible cell, left border */
695 ui32_t tl_phy_cursor; /* Physical cursor position */
696 bool_t tl_quote_rndtrip; /* For _kht() expansion */
697 ui8_t tl__dummy2[3 + 4];
698 ui32_t tl_goinflags; /* enum n_go_input_flags */
699 ui32_t tl_prompt_length; /* Preclassified (TODO needed as a_tty_cell) */
700 ui32_t tl_prompt_width;
701 char const *tl_prompt; /* Preformatted prompt (including colours) */
702 /* .tl_pos_buf is a hack */
703 # ifdef HAVE_COLOUR
704 char *tl_pos_buf; /* mle-position colour-on, [4], reset seq. */
705 char *tl_pos; /* Address of the [4] */
706 # endif
709 # ifdef HAVE_KEY_BINDINGS
710 /* C99: use [INDEX]={} */
711 n_CTAV(n_GO_INPUT_CTX_BASE == 0);
712 n_CTAV(n_GO_INPUT_CTX_DEFAULT == 1);
713 n_CTAV(n_GO_INPUT_CTX_COMPOSE == 2);
714 static struct a_tty_bind_ctx_map const
715 a_tty_bind_ctx_maps[n__GO_INPUT_CTX_MAX1] = {
716 {n_GO_INPUT_CTX_BASE, "base"},
717 {n_GO_INPUT_CTX_DEFAULT, "default"},
718 {n_GO_INPUT_CTX_COMPOSE, "compose"}
721 /* Special functions which our MLE provides internally.
722 * Update the manual upon change! */
723 static char const a_tty_bind_fun_names[][24] = {
724 # undef a_X
725 # define a_X(I,N) \
726 n_FIELD_INITI(a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## I)) "mle-" N "\0",
728 a_X(BELL, "bell")
729 a_X(GO_BWD, "go-bwd") a_X(GO_FWD, "go-fwd")
730 a_X(GO_WORD_BWD, "go-word-bwd") a_X(GO_WORD_FWD, "go-word-fwd")
731 a_X(GO_SCREEN_BWD, "go-screen-bwd") a_X(GO_SCREEN_FWD, "go-screen-fwd")
732 a_X(GO_HOME, "go-home") a_X(GO_END, "go-end")
733 a_X(DEL_BWD, "del-bwd") a_X(DEL_FWD, "del-fwd")
734 a_X(SNARF_WORD_BWD, "snarf-word-bwd") a_X(SNARF_WORD_FWD, "snarf-word-fwd")
735 a_X(SNARF_END, "snarf-end") a_X(SNARF_LINE, "snarf-line")
736 a_X(HIST_BWD, "hist-bwd") a_X(HIST_FWD, "hist-fwd")
737 a_X(HIST_SRCH_BWD, "hist-srch-bwd") a_X(HIST_SRCH_FWD, "hist-srch-fwd")
738 a_X(REPAINT, "repaint")
739 a_X(QUOTE_RNDTRIP, "quote-rndtrip")
740 a_X(PROMPT_CHAR, "prompt-char")
741 a_X(COMPLETE, "complete")
742 a_X(PASTE, "paste")
743 a_X(CLEAR_SCREEN, "clear-screen")
745 a_X(CANCEL, "cancel")
746 a_X(RESET, "reset")
747 a_X(FULLRESET, "fullreset")
748 a_X(COMMIT, "commit")
750 # undef a_X
752 # endif /* HAVE_KEY_BINDINGS */
754 /* The default key bindings (unless disallowed). Update manual upon change!
755 * A logical subset of this table is also used if !HAVE_KEY_BINDINGS (more
756 * expensive than a switch() on control codes directly, but less redundant).
757 * The table for the "base" context */
758 static struct a_tty_bind_builtin_tuple const a_tty_bind_base_tuples[] = {
759 # undef a_X
760 # define a_X(K,S) \
761 {TRU1, K, 0, {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
763 a_X('A', GO_HOME)
764 a_X('B', GO_BWD)
765 /* C: SIGINT */
766 a_X('D', DEL_FWD)
767 a_X('E', GO_END)
768 a_X('F', GO_FWD)
769 a_X('G', RESET)
770 a_X('H', DEL_BWD)
771 a_X('I', COMPLETE)
772 a_X('J', COMMIT)
773 a_X('K', SNARF_END)
774 a_X('L', REPAINT)
775 /* M: same as J */
776 a_X('N', HIST_FWD)
777 /* O: below */
778 a_X('P', HIST_BWD)
779 a_X('Q', QUOTE_RNDTRIP)
780 a_X('R', HIST_SRCH_BWD)
781 a_X('S', HIST_SRCH_FWD)
782 a_X('T', PASTE)
783 a_X('U', SNARF_LINE)
784 a_X('V', PROMPT_CHAR)
785 a_X('W', SNARF_WORD_BWD)
786 a_X('X', GO_WORD_FWD)
787 a_X('Y', GO_WORD_BWD)
788 /* Z: SIGTSTP */
790 a_X('[', CANCEL)
791 /* \: below */
792 /* ]: below */
793 /* ^: below */
794 a_X('_', SNARF_WORD_FWD)
796 a_X('?', DEL_BWD)
798 # undef a_X
799 # define a_X(K,S) {TRU1, K, 0, {S}},
801 /* The remains only if we have `bind' functionality available */
802 # ifdef HAVE_KEY_BINDINGS
803 # undef a_X
804 # define a_X(Q,S) \
805 {FAL0, '\0', n_TERMCAP_QUERY_ ## Q,\
806 {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
808 a_X(key_backspace, DEL_BWD) a_X(key_dc, DEL_FWD)
809 a_X(key_eol, SNARF_END)
810 a_X(key_home, GO_HOME) a_X(key_end, GO_END)
811 a_X(key_left, GO_BWD) a_X(key_right, GO_FWD)
812 a_X(xkey_aleft, GO_WORD_BWD) a_X(xkey_aright, GO_WORD_FWD)
813 a_X(xkey_cleft, GO_SCREEN_BWD) a_X(xkey_cright, GO_SCREEN_FWD)
814 a_X(key_sleft, GO_HOME) a_X(key_sright, GO_END)
815 a_X(key_up, HIST_BWD) a_X(key_down, HIST_FWD)
816 # endif /* HAVE_KEY_BINDINGS */
819 /* The table for the "default" context */
820 static struct a_tty_bind_builtin_tuple const a_tty_bind_default_tuples[] = {
821 # undef a_X
822 # define a_X(K,S) \
823 {TRU1, K, 0, {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
825 # undef a_X
826 # define a_X(K,S) {TRU1, K, 0, {S}},
828 a_X('O', "dt")
830 a_X('\\', "z+")
831 a_X(']', "z$")
832 a_X('^', "z0")
834 /* The remains only if we have `bind' functionality available */
835 # ifdef HAVE_KEY_BINDINGS
836 # undef a_X
837 # define a_X(Q,S) {FAL0, '\0', n_TERMCAP_QUERY_ ## Q, {S}},
839 a_X(key_shome, "z0") a_X(key_send, "z$")
840 a_X(xkey_sup, "z0") a_X(xkey_sdown, "z$")
841 a_X(key_ppage, "z-") a_X(key_npage, "z+")
842 a_X(xkey_cup, "dotmove-") a_X(xkey_cdown, "dotmove+")
843 # endif /* HAVE_KEY_BINDINGS */
845 # undef a_X
847 static struct a_tty_global a_tty;
849 /* Change from canonical to raw, non-canonical mode, and way back */
850 static void a_tty_term_mode(bool_t raw);
852 # ifdef HAVE_HISTORY
853 /* Load and save the history file, respectively */
854 static bool_t a_tty_hist_load(void);
855 static bool_t a_tty_hist_save(void);
857 /* Initialize .tg_hist_size_max and return desired history file, or NULL */
858 static char const *a_tty_hist__query_config(void);
860 /* (Definetely) Add an entry TODO yet assumes hold_all_sigs() is held! */
861 static void a_tty_hist_add(char const *s, enum n_go_input_flags gif);
862 # endif
864 /* Adjust an active raw mode to use / not use a timeout */
865 # ifdef HAVE_KEY_BINDINGS
866 static void a_tty_term_rawmode_timeout(struct a_tty_line *tlp, bool_t enable);
867 # endif
869 /* 0-X (2), UI8_MAX == \t / HT */
870 static ui8_t a_tty_wcwidth(wchar_t wc);
872 /* Memory / cell / word generics */
873 static void a_tty_check_grow(struct a_tty_line *tlp, ui32_t no
874 n_MEMORY_DEBUG_ARGS);
875 static ssize_t a_tty_cell2dat(struct a_tty_line *tlp);
876 static void a_tty_cell2save(struct a_tty_line *tlp);
878 /* Save away data bytes of given range (max = non-inclusive) */
879 static void a_tty_copy2paste(struct a_tty_line *tlp, struct a_tty_cell *tcpmin,
880 struct a_tty_cell *tcpmax);
882 /* Ask user for hexadecimal number, interpret as UTF-32 */
883 static wchar_t a_tty_vinuni(struct a_tty_line *tlp);
885 /* Visual screen synchronization */
886 static bool_t a_tty_vi_refresh(struct a_tty_line *tlp);
888 static bool_t a_tty_vi__paint(struct a_tty_line *tlp);
890 /* Search for word boundary, starting at tl_cursor, in "dir"ection (<> 0).
891 * Return <0 when moving is impossible (backward direction but in position 0,
892 * forward direction but in outermost column), and relative distance to
893 * tl_cursor otherwise */
894 static si32_t a_tty_wboundary(struct a_tty_line *tlp, si32_t dir);
896 /* Most function implementations */
897 static void a_tty_khome(struct a_tty_line *tlp, bool_t dobell);
898 static void a_tty_kend(struct a_tty_line *tlp);
899 static void a_tty_kbs(struct a_tty_line *tlp);
900 static void a_tty_ksnarf(struct a_tty_line *tlp, bool_t cplline, bool_t dobell);
901 static si32_t a_tty_kdel(struct a_tty_line *tlp);
902 static void a_tty_kleft(struct a_tty_line *tlp);
903 static void a_tty_kright(struct a_tty_line *tlp);
904 static void a_tty_ksnarfw(struct a_tty_line *tlp, bool_t fwd);
905 static void a_tty_kgow(struct a_tty_line *tlp, si32_t dir);
906 static void a_tty_kgoscr(struct a_tty_line *tlp, si32_t dir);
907 static bool_t a_tty_kother(struct a_tty_line *tlp, wchar_t wc);
908 static ui32_t a_tty_kht(struct a_tty_line *tlp);
910 # ifdef HAVE_HISTORY
911 /* Return UI32_MAX on "exhaustion" */
912 static ui32_t a_tty_khist(struct a_tty_line *tlp, bool_t fwd);
913 static ui32_t a_tty_khist_search(struct a_tty_line *tlp, bool_t fwd);
915 static ui32_t a_tty__khist_shared(struct a_tty_line *tlp,
916 struct a_tty_hist *thp);
917 # endif
919 /* Handle a function */
920 static enum a_tty_fun_status a_tty_fun(struct a_tty_line *tlp,
921 enum a_tty_bind_flags tbf, size_t *len);
923 /* Readline core */
924 static ssize_t a_tty_readline(struct a_tty_line *tlp, size_t len,
925 bool_t *histok_or_null n_MEMORY_DEBUG_ARGS);
927 # ifdef HAVE_KEY_BINDINGS
928 /* Find context or -1 */
929 static enum n_go_input_flags a_tty_bind_ctx_find(char const *name);
931 /* Create (or replace, if allowed) a binding */
932 static bool_t a_tty_bind_create(struct a_tty_bind_parse_ctx *tbpcp,
933 bool_t replace);
935 /* Shared implementation to parse `bind' and `unbind' "key-sequence" and
936 * "expansion" command line arguments into something that we can work with */
937 static bool_t a_tty_bind_parse(bool_t isbindcmd,
938 struct a_tty_bind_parse_ctx *tbpcp);
940 /* Lazy resolve a termcap(5)/terminfo(5) (or *termcap*!) capability */
941 static void a_tty_bind_resolve(struct a_tty_bind_ctx *tbcp);
943 /* Delete an existing binding */
944 static void a_tty_bind_del(struct a_tty_bind_parse_ctx *tbpcp);
946 /* Life cycle of all input node trees */
947 static void a_tty_bind_tree_build(void);
948 static void a_tty_bind_tree_teardown(void);
950 static void a_tty__bind_tree_add(ui32_t hmap_idx,
951 struct a_tty_bind_tree *store[HSHSIZE],
952 struct a_tty_bind_ctx *tbcp);
953 static struct a_tty_bind_tree *a_tty__bind_tree_add_wc(
954 struct a_tty_bind_tree **treep, struct a_tty_bind_tree *parentp,
955 wchar_t wc, bool_t isseq);
956 static void a_tty__bind_tree_free(struct a_tty_bind_tree *tbtp);
957 # endif /* HAVE_KEY_BINDINGS */
959 static void
960 a_tty_signal(int sig){
961 /* Prototype at top */
962 sigset_t nset, oset;
963 NYD_X; /* Signal handler */
965 n_COLOUR( n_colour_env_gut(); ) /* TODO NO SIMPLE SUSPENSION POSSIBLE.. */
966 a_tty_term_mode(FAL0);
967 n_TERMCAP_SUSPEND(TRU1);
968 a_tty_sigs_down();
970 sigemptyset(&nset);
971 sigaddset(&nset, sig);
972 sigprocmask(SIG_UNBLOCK, &nset, &oset);
973 n_raise(sig);
974 /* When we come here we'll continue editing, so reestablish */
975 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
977 /* TODO THEREFORE NEED TO _GUT() .. _CREATE() ENTIRE ENVS!! */
978 n_COLOUR( n_colour_env_create(n_COLOUR_CTX_MLE, n_tty_fp, FAL0); )
979 a_tty_sigs_up();
980 n_TERMCAP_RESUME(TRU1);
981 a_tty_term_mode(TRU1);
982 a_tty.tg_line->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
985 static void
986 a_tty_term_mode(bool_t raw){
987 struct termios *tiosp;
988 NYD2_ENTER;
990 tiosp = &a_tty.tg_tios_old;
991 if(!raw)
992 goto jleave;
994 /* Always requery the attributes, in case we've been moved from background
995 * to foreground or however else in between sessions */
996 /* XXX Always enforce ECHO and ICANON in the OLD attributes - do so as long
997 * XXX as we don't properly deal with TTIN and TTOU etc. */
998 tcgetattr(STDIN_FILENO, tiosp); /* TODO v15: use _only_ n_tty_fp! */
999 tiosp->c_lflag |= ECHO | ICANON;
1001 memcpy(&a_tty.tg_tios_new, tiosp, sizeof *tiosp);
1002 tiosp = &a_tty.tg_tios_new;
1003 tiosp->c_cc[VMIN] = 1;
1004 tiosp->c_cc[VTIME] = 0;
1005 /* Enable ^\, ^Q and ^S to be used for key bindings */
1006 tiosp->c_cc[VQUIT] = tiosp->c_cc[VSTART] = tiosp->c_cc[VSTOP] = '\0';
1007 tiosp->c_iflag &= ~(ISTRIP | IGNCR);
1008 tiosp->c_lflag &= ~(ECHO /*| ECHOE | ECHONL */| ICANON | IEXTEN);
1009 jleave:
1010 tcsetattr(STDIN_FILENO, TCSADRAIN, tiosp);
1011 NYD2_LEAVE;
1014 # ifdef HAVE_HISTORY
1015 static bool_t
1016 a_tty_hist_load(void){
1017 ui8_t version;
1018 size_t lsize, cnt, llen;
1019 char *lbuf, *cp;
1020 FILE *f;
1021 char const *v;
1022 bool_t rv;
1023 NYD_ENTER;
1025 rv = TRU1;
1027 if((v = a_tty_hist__query_config()) == NULL ||
1028 a_tty.tg_hist_size_max == 0)
1029 goto jleave;
1031 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
1032 f = fopen(v, "r"); /* TODO HISTFILE LOAD: use linebuf pool */
1033 if(f == NULL){
1034 int e;
1036 e = errno;
1037 n_err(_("Cannot read *history-file*=%s: %s\n"),
1038 n_shexp_quote_cp(v, FAL0), n_err_to_doc(e));
1039 rv = FAL0;
1040 goto jrele;
1042 (void)n_file_lock(fileno(f), FLT_READ, 0,0, UIZ_MAX);
1044 /* Clear old history */
1045 /* C99 */{
1046 struct a_tty_hist *thp;
1048 while((thp = a_tty.tg_hist) != NULL){
1049 a_tty.tg_hist = thp->th_older;
1050 n_free(thp);
1052 a_tty.tg_hist_tail = NULL;
1053 a_tty.tg_hist_size = 0;
1056 lbuf = NULL;
1057 lsize = 0;
1058 cnt = (size_t)fsize(f);
1059 version = 0;
1061 while(fgetline(&lbuf, &lsize, &cnt, &llen, f, FAL0) != NULL){
1062 cp = lbuf;
1063 /* Hand-edited history files may have this, probably */
1064 while(llen > 0 && spacechar(cp[0])){
1065 ++cp;
1066 --llen;
1068 if(llen > 0 && cp[llen - 1] == '\n')
1069 cp[--llen] = '\0';
1071 /* Skip empty and comment lines */
1072 if(llen == 0 || cp[0] == '#')
1073 continue;
1075 if(n_UNLIKELY(version == 0) &&
1076 (version = strcmp(cp, a_TTY_HIST_MARKER) ? 1 : 2) != 1)
1077 continue;
1079 /* C99 */{
1080 enum n_go_input_flags gif;
1082 if(version == 2){
1083 if(llen <= 2){
1084 /* XXX n_err(_("Skipped invalid *history-file* entry: %s\n"),
1085 * XXX n_shexp_quote_cp(cp));*/
1086 continue;
1088 switch(*cp++){
1089 default:
1090 case 'd':
1091 gif = n_GO_INPUT_CTX_DEFAULT; /* == a_TTY_HIST_CTX_DEFAULT */
1092 break;
1093 case 'c':
1094 gif = n_GO_INPUT_CTX_COMPOSE; /* == a_TTY_HIST_CTX_COMPOSE */
1095 break;
1098 if(*cp++ == '*')
1099 gif |= n_GO_INPUT_HIST_GABBY;
1101 while(*cp == ' ')
1102 ++cp;
1103 }else{
1104 gif = n_GO_INPUT_CTX_DEFAULT;
1105 if(cp[0] == '*'){
1106 ++cp;
1107 gif |= n_GO_INPUT_HIST_GABBY;
1111 a_tty_hist_add(cp, gif);
1115 if(lbuf != NULL)
1116 n_free(lbuf);
1118 fclose(f);
1119 jrele:
1120 rele_all_sigs(); /* XXX remove jumps */
1121 jleave:
1122 NYD_LEAVE;
1123 return rv;
1126 static bool_t
1127 a_tty_hist_save(void){
1128 size_t i;
1129 struct a_tty_hist *thp;
1130 FILE *f;
1131 char const *v;
1132 bool_t rv, dogabby;
1133 NYD_ENTER;
1135 rv = TRU1;
1137 if((v = a_tty_hist__query_config()) == NULL ||
1138 a_tty.tg_hist_size_max == 0)
1139 goto jleave;
1141 dogabby = ok_blook(history_gabby_persist);
1143 if((thp = a_tty.tg_hist) != NULL)
1144 for(i = a_tty.tg_hist_size_max; thp->th_older != NULL;
1145 thp = thp->th_older)
1146 if((dogabby || !(thp->th_flags & a_TTY_HIST_GABBY)) && --i == 0)
1147 break;
1149 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
1150 if((f = fopen(v, "w")) == NULL){ /* TODO temporary + rename?! */
1151 int e;
1153 e = errno;
1154 n_err(_("Cannot write *history-file*=%s: %s\n"),
1155 n_shexp_quote_cp(v, FAL0), n_err_to_doc(e));
1156 rv = FAL0;
1157 goto jrele;
1159 (void)n_file_lock(fileno(f), FLT_WRITE, 0,0, UIZ_MAX);
1161 if(fwrite(a_TTY_HIST_MARKER "\n", sizeof *a_TTY_HIST_MARKER,
1162 sizeof(a_TTY_HIST_MARKER "\n") -1, f) !=
1163 sizeof(a_TTY_HIST_MARKER "\n") -1)
1164 goto jioerr;
1165 else for(; thp != NULL; thp = thp->th_younger){
1166 if(dogabby || !(thp->th_flags & a_TTY_HIST_GABBY)){
1167 char c;
1169 switch(thp->th_flags & a_TTY_HIST_CTX_MASK){
1170 default:
1171 case a_TTY_HIST_CTX_DEFAULT:
1172 c = 'd';
1173 break;
1174 case a_TTY_HIST_CTX_COMPOSE:
1175 c = 'c';
1176 break;
1178 if(putc(c, f) == EOF)
1179 goto jioerr;
1181 if((thp->th_flags & a_TTY_HIST_GABBY) && putc('*', f) == EOF)
1182 goto jioerr;
1184 if(putc(' ', f) == EOF ||
1185 fwrite(thp->th_dat, sizeof *thp->th_dat, thp->th_len, f) !=
1186 sizeof(*thp->th_dat) * thp->th_len ||
1187 putc('\n', f) == EOF){
1188 jioerr:
1189 n_err(_("I/O error while writing *history-file* %s\n"),
1190 n_shexp_quote_cp(v, FAL0));
1191 rv = FAL0;
1192 break;
1197 fclose(f);
1198 jrele:
1199 rele_all_sigs(); /* XXX remove jumps */
1200 jleave:
1201 NYD_LEAVE;
1202 return rv;
1205 static char const *
1206 a_tty_hist__query_config(void){
1207 char const *rv, *cp;
1208 NYD2_ENTER;
1210 if((cp = ok_vlook(NAIL_HISTSIZE)) != NULL)
1211 n_OBSOLETE(_("please use *history-size* instead of *NAIL_HISTSIZE*"));
1212 if((rv = ok_vlook(history_size)) == NULL)
1213 rv = cp;
1214 if(rv == NULL)
1215 a_tty.tg_hist_size_max = UIZ_MAX;
1216 else
1217 (void)n_idec_uiz_cp(&a_tty.tg_hist_size_max, rv, 10, NULL);
1219 if((cp = ok_vlook(NAIL_HISTFILE)) != NULL)
1220 n_OBSOLETE(_("please use *history-file* instead of *NAIL_HISTFILE*"));
1221 if((rv = ok_vlook(history_file)) == NULL)
1222 rv = cp;
1223 if(rv != NULL)
1224 rv = fexpand(rv, FEXP_LOCAL | FEXP_NSHELL);
1225 NYD2_LEAVE;
1226 return rv;
1229 static void
1230 a_tty_hist_add(char const *s, enum n_go_input_flags gif){
1231 ui32_t l;
1232 struct a_tty_hist *thp, *othp, *ythp;
1233 NYD2_ENTER;
1235 l = (ui32_t)strlen(s); /* xxx simply do not store if >= SI32_MAX */
1237 /* Eliminating duplicates is expensive, but simply inacceptable so
1238 * during the load of a potentially large history file! */
1239 if(n_psonce & n_PSO_LINE_EDITOR_INIT)
1240 for(thp = a_tty.tg_hist; thp != NULL; thp = thp->th_older)
1241 if(thp->th_len == l && !strcmp(thp->th_dat, s)){
1242 thp->th_flags = (gif & a_TTY_HIST_CTX_MASK) |
1243 (gif & n_GO_INPUT_HIST_GABBY ? a_TTY_HIST_GABBY : 0);
1244 othp = thp->th_older;
1245 ythp = thp->th_younger;
1246 if(othp != NULL)
1247 othp->th_younger = ythp;
1248 else
1249 a_tty.tg_hist_tail = ythp;
1250 if(ythp != NULL)
1251 ythp->th_older = othp;
1252 else
1253 a_tty.tg_hist = othp;
1254 goto jleave;
1257 if(n_LIKELY(a_tty.tg_hist_size <= a_tty.tg_hist_size_max))
1258 ++a_tty.tg_hist_size;
1259 else{
1260 --a_tty.tg_hist_size;
1261 if((thp = a_tty.tg_hist_tail) != NULL){
1262 if((a_tty.tg_hist_tail = thp->th_younger) == NULL)
1263 a_tty.tg_hist = NULL;
1264 else
1265 a_tty.tg_hist_tail->th_older = NULL;
1266 n_free(thp);
1270 thp = n_alloc(n_VSTRUCT_SIZEOF(struct a_tty_hist, th_dat) + l +1);
1271 thp->th_len = l;
1272 thp->th_flags = (gif & a_TTY_HIST_CTX_MASK) |
1273 (gif & n_GO_INPUT_HIST_GABBY ? a_TTY_HIST_GABBY : 0);
1274 memcpy(thp->th_dat, s, l +1);
1275 jleave:
1276 if((thp->th_older = a_tty.tg_hist) != NULL)
1277 a_tty.tg_hist->th_younger = thp;
1278 else
1279 a_tty.tg_hist_tail = thp;
1280 thp->th_younger = NULL;
1281 a_tty.tg_hist = thp;
1282 NYD2_LEAVE;
1284 # endif /* HAVE_HISTORY */
1286 # ifdef HAVE_KEY_BINDINGS
1287 static void
1288 a_tty_term_rawmode_timeout(struct a_tty_line *tlp, bool_t enable){
1289 NYD2_ENTER;
1290 if(enable){
1291 ui8_t bt;
1293 a_tty.tg_tios_new.c_cc[VMIN] = 0;
1294 if((bt = tlp->tl_bind_timeout) == 0)
1295 bt = a_TTY_BIND_TIMEOUT;
1296 a_tty.tg_tios_new.c_cc[VTIME] = bt;
1297 }else{
1298 a_tty.tg_tios_new.c_cc[VMIN] = 1;
1299 a_tty.tg_tios_new.c_cc[VTIME] = 0;
1301 tcsetattr(STDIN_FILENO, TCSANOW, &a_tty.tg_tios_new);
1302 NYD2_LEAVE;
1304 # endif /* HAVE_KEY_BINDINGS */
1306 static ui8_t
1307 a_tty_wcwidth(wchar_t wc){
1308 ui8_t rv;
1309 NYD2_ENTER;
1311 /* Special case the reverse solidus at first */
1312 if(wc == '\t')
1313 rv = UI8_MAX;
1314 else{
1315 int i;
1317 # ifdef HAVE_WCWIDTH
1318 rv = ((i = wcwidth(wc)) > 0) ? (ui8_t)i : 0;
1319 # else
1320 rv = iswprint(wc) ? 1 + (wc >= 0x1100u) : 0; /* TODO use S-CText */
1321 # endif
1323 NYD2_LEAVE;
1324 return rv;
1327 static void
1328 a_tty_check_grow(struct a_tty_line *tlp, ui32_t no n_MEMORY_DEBUG_ARGS){
1329 ui32_t cmax;
1330 NYD2_ENTER;
1332 if(n_UNLIKELY((cmax = tlp->tl_count + no) > tlp->tl_count_max)){
1333 size_t i;
1335 i = cmax * sizeof(struct a_tty_cell) + 2 * sizeof(struct a_tty_cell);
1336 if(n_LIKELY(i >= *tlp->tl_x_bufsize)){
1337 hold_all_sigs(); /* XXX v15 drop */
1338 i <<= 1;
1339 tlp->tl_line.cbuf =
1340 *tlp->tl_x_buf = (n_realloc)(*tlp->tl_x_buf, i
1341 n_MEMORY_DEBUG_ARGSCALL);
1342 rele_all_sigs(); /* XXX v15 drop */
1344 tlp->tl_count_max = cmax;
1345 *tlp->tl_x_bufsize = i;
1347 NYD2_LEAVE;
1350 static ssize_t
1351 a_tty_cell2dat(struct a_tty_line *tlp){
1352 size_t len, i;
1353 NYD2_ENTER;
1355 len = 0;
1357 if(n_LIKELY((i = tlp->tl_count) > 0)){
1358 struct a_tty_cell const *tcap;
1360 tcap = tlp->tl_line.cells;
1362 memcpy(tlp->tl_line.cbuf + len, tcap->tc_cbuf, tcap->tc_count);
1363 len += tcap->tc_count;
1364 }while(++tcap, --i > 0);
1367 tlp->tl_line.cbuf[len] = '\0';
1368 NYD2_LEAVE;
1369 return (ssize_t)len;
1372 static void
1373 a_tty_cell2save(struct a_tty_line *tlp){
1374 size_t len, i;
1375 struct a_tty_cell *tcap;
1376 NYD2_ENTER;
1378 tlp->tl_savec.s = NULL;
1379 tlp->tl_savec.l = 0;
1381 if(n_UNLIKELY(tlp->tl_count == 0))
1382 goto jleave;
1384 for(tcap = tlp->tl_line.cells, len = 0, i = tlp->tl_count; i > 0;
1385 ++tcap, --i)
1386 len += tcap->tc_count;
1388 tlp->tl_savec.s = n_autorec_alloc((tlp->tl_savec.l = len) +1);
1390 for(tcap = tlp->tl_line.cells, len = 0, i = tlp->tl_count; i > 0;
1391 ++tcap, --i){
1392 memcpy(tlp->tl_savec.s + len, tcap->tc_cbuf, tcap->tc_count);
1393 len += tcap->tc_count;
1395 tlp->tl_savec.s[len] = '\0';
1396 jleave:
1397 NYD2_LEAVE;
1400 static void
1401 a_tty_copy2paste(struct a_tty_line *tlp, struct a_tty_cell *tcpmin,
1402 struct a_tty_cell *tcpmax){
1403 char *cp;
1404 struct a_tty_cell *tcp;
1405 size_t l;
1406 NYD2_ENTER;
1408 l = 0;
1409 for(tcp = tcpmin; tcp < tcpmax; ++tcp)
1410 l += tcp->tc_count;
1412 tlp->tl_pastebuf.s = cp = n_autorec_alloc((tlp->tl_pastebuf.l = l) +1);
1414 for(tcp = tcpmin; tcp < tcpmax; cp += l, ++tcp)
1415 memcpy(cp, tcp->tc_cbuf, l = tcp->tc_count);
1416 *cp = '\0';
1417 NYD2_LEAVE;
1420 static wchar_t
1421 a_tty_vinuni(struct a_tty_line *tlp){
1422 char buf[16];
1423 uiz_t i;
1424 wchar_t wc;
1425 NYD2_ENTER;
1427 wc = '\0';
1429 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr) ||
1430 !n_termcap_cmd(n_TERMCAP_CMD_ce, 0, -1))
1431 goto jleave;
1433 /* C99 */{
1434 struct str const *cpre, *csuf;
1436 cpre = csuf = NULL;
1437 #ifdef HAVE_COLOUR
1438 if(n_COLOUR_IS_ACTIVE()){
1439 struct n_colour_pen *cpen;
1441 cpen = n_colour_pen_create(n_COLOUR_ID_MLE_PROMPT, NULL);
1442 if((cpre = n_colour_pen_to_str(cpen)) != NULL)
1443 csuf = n_colour_reset_to_str();
1445 #endif
1446 fprintf(n_tty_fp, _("%sPlease enter Unicode code point:%s "),
1447 (cpre != NULL ? cpre->s : n_empty),
1448 (csuf != NULL ? csuf->s : n_empty));
1450 fflush(n_tty_fp);
1452 buf[sizeof(buf) -1] = '\0';
1453 for(i = 0;;){
1454 if(read(STDIN_FILENO, &buf[i], 1) != 1){
1455 if(n_err_no == n_ERR_INTR) /* xxx #if !SA_RESTART ? */
1456 continue;
1457 goto jleave;
1459 if(buf[i] == '\n')
1460 break;
1461 if(!hexchar(buf[i])){
1462 char const emsg[] = "[0-9a-fA-F]";
1464 n_LCTA(sizeof emsg <= sizeof(buf), "Preallocated buffer too small");
1465 memcpy(buf, emsg, sizeof emsg);
1466 goto jerr;
1469 putc(buf[i], n_tty_fp);
1470 fflush(n_tty_fp);
1471 if(++i == sizeof buf)
1472 goto jerr;
1474 buf[i] = '\0';
1476 if((n_idec_uiz_cp(&i, buf, 16, NULL
1477 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
1478 ) != n_IDEC_STATE_CONSUMED || i > 0x10FFFF/* XXX magic; CText */){
1479 jerr:
1480 n_err(_("\nInvalid input: %s\n"), buf);
1481 goto jleave;
1484 wc = (wchar_t)i;
1485 jleave:
1486 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY | (wc == '\0' ? a_TTY_VF_BELL : 0);
1487 NYD2_LEAVE;
1488 return wc;
1491 static bool_t
1492 a_tty_vi_refresh(struct a_tty_line *tlp){
1493 bool_t rv;
1494 NYD2_ENTER;
1496 if(tlp->tl_vi_flags & a_TTY_VF_BELL){
1497 tlp->tl_vi_flags |= a_TTY_VF_SYNC;
1498 if(putc('\a', n_tty_fp) == EOF)
1499 goto jerr;
1502 if(tlp->tl_vi_flags & a_TTY_VF_REFRESH){
1503 /* kht may want to restore a cursor position after inserting some
1504 * data somewhere */
1505 if(tlp->tl_defc_cursor_byte > 0){
1506 size_t i, j;
1507 ssize_t k;
1509 a_tty_khome(tlp, FAL0);
1511 i = tlp->tl_defc_cursor_byte;
1512 tlp->tl_defc_cursor_byte = 0;
1513 for(j = 0; tlp->tl_cursor < tlp->tl_count; ++j){
1514 a_tty_kright(tlp);
1515 if((k = tlp->tl_line.cells[j].tc_count) > i)
1516 break;
1517 i -= k;
1521 if(!a_tty_vi__paint(tlp))
1522 goto jerr;
1525 if(tlp->tl_vi_flags & a_TTY_VF_SYNC){
1526 tlp->tl_vi_flags &= ~a_TTY_VF_SYNC;
1527 if(fflush(n_tty_fp))
1528 goto jerr;
1531 rv = TRU1;
1532 jleave:
1533 tlp->tl_vi_flags &= ~a_TTY_VF_ALL_MASK;
1534 NYD2_LEAVE;
1535 return rv;
1537 jerr:
1538 clearerr(n_tty_fp); /* xxx I/O layer rewrite */
1539 n_err(_("Visual refresh failed! Is $TERM set correctly?\n"
1540 " Setting *line-editor-disable* to get us through!\n"));
1541 ok_bset(line_editor_disable);
1542 rv = FAL0;
1543 goto jleave;
1546 static bool_t
1547 a_tty_vi__paint(struct a_tty_line *tlp){
1548 enum{
1549 a_TRUE_RV = a_TTY__VF_LAST<<1, /* Return value bit */
1550 a_HAVE_PROMPT = a_TTY__VF_LAST<<2, /* Have a prompt */
1551 a_SHOW_PROMPT = a_TTY__VF_LAST<<3, /* Shall print the prompt */
1552 a_MOVE_CURSOR = a_TTY__VF_LAST<<4, /* Move visual cursor for user! */
1553 a_LEFT_MIN = a_TTY__VF_LAST<<5, /* On left boundary */
1554 a_RIGHT_MAX = a_TTY__VF_LAST<<6,
1555 a_HAVE_POSITION = a_TTY__VF_LAST<<7, /* Print the position indicator */
1557 /* We carry some flags over invocations (not worth a specific field) */
1558 a_VISIBLE_PROMPT = a_TTY__VF_LAST<<8, /* The prompt is on the screen */
1559 a_PERSIST_MASK = a_VISIBLE_PROMPT,
1560 a__LAST = a_PERSIST_MASK
1563 ui32_t f, w, phy_wid_base, phy_wid, phy_base, phy_cur, cnt,
1564 DBG(lstcur COMMA) cur,
1565 vi_left, /*vi_right,*/ phy_nxtcur;
1566 struct a_tty_cell const *tccp, *tcp_left, *tcp_right, *tcxp;
1567 NYD2_ENTER;
1568 n_LCTA(UICMP(64, a__LAST, <, UI32_MAX), "Flag bits excess storage datatype");
1570 f = tlp->tl_vi_flags;
1571 tlp->tl_vi_flags = (f & ~(a_TTY_VF_REFRESH | a_PERSIST_MASK)) |
1572 a_TTY_VF_SYNC;
1573 f |= a_TRUE_RV;
1574 if((w = tlp->tl_prompt_width) > 0)
1575 f |= a_HAVE_PROMPT;
1576 f |= a_HAVE_POSITION;
1578 /* XXX We don't have a OnTerminalResize event (see main.c) yet, so we need
1579 * XXX to reevaluate our circumstances over and over again */
1580 /* Don't display prompt or position indicator on very small screens */
1581 if((phy_wid_base = (ui32_t)n_scrnwidth) <= a_TTY_WIDTH_RIPOFF)
1582 f &= ~(a_HAVE_PROMPT | a_HAVE_POSITION);
1583 else{
1584 phy_wid_base -= a_TTY_WIDTH_RIPOFF;
1586 /* Disable the prompt if the screen is too small; due to lack of some
1587 * indicator simply add a second ripoff */
1588 if((f & a_HAVE_PROMPT) && w + a_TTY_WIDTH_RIPOFF >= phy_wid_base)
1589 f &= ~a_HAVE_PROMPT;
1592 phy_wid = phy_wid_base;
1593 phy_base = 0;
1594 phy_cur = tlp->tl_phy_cursor;
1595 cnt = tlp->tl_count;
1596 DBG( lstcur = tlp->tl_lst_cursor; )
1598 /* XXX Assume dirty screen if shrunk */
1599 if(cnt < tlp->tl_lst_count)
1600 f |= a_TTY_VF_MOD_DIRTY;
1602 /* TODO Without HAVE_TERMCAP, it would likely be much cheaper to simply
1603 * TODO always "cr + paint + ce + ch", since ce is simulated via spaces.. */
1605 /* Quickshot: if the line is empty, possibly print prompt and out */
1606 if(cnt == 0){
1607 /* In that special case dirty anything if it seems better */
1608 if((f & a_TTY_VF_MOD_CONTENT) || tlp->tl_lst_count > 0)
1609 f |= a_TTY_VF_MOD_DIRTY;
1611 if((f & a_TTY_VF_MOD_DIRTY) && phy_cur != 0){
1612 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
1613 goto jerr;
1614 phy_cur = 0;
1617 if((f & (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)) ==
1618 (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)){
1619 if(fputs(tlp->tl_prompt, n_tty_fp) == EOF)
1620 goto jerr;
1621 phy_cur = tlp->tl_prompt_width + 1;
1624 /* May need to clear former line content */
1625 if((f & a_TTY_VF_MOD_DIRTY) &&
1626 !n_termcap_cmd(n_TERMCAP_CMD_ce, phy_cur, -1))
1627 goto jerr;
1629 tlp->tl_phy_start = tlp->tl_line.cells;
1630 goto jleave;
1633 /* Try to get an idea of the visual window */
1635 /* Find the left visual boundary */
1636 phy_wid = (phy_wid >> 1) + (phy_wid >> 2);
1637 if((cur = tlp->tl_cursor) == cnt)
1638 --cur;
1640 w = (tcp_left = tccp = tlp->tl_line.cells + cur)->tc_width;
1641 if(w == UI8_MAX) /* TODO yet HT == SPACE */
1642 w = 1;
1643 while(tcp_left > tlp->tl_line.cells){
1644 ui16_t cw = tcp_left[-1].tc_width;
1646 if(cw == UI8_MAX) /* TODO yet HT == SPACE */
1647 cw = 1;
1648 if(w + cw >= phy_wid)
1649 break;
1650 w += cw;
1651 --tcp_left;
1653 vi_left = w;
1655 /* If the left hand side of our visual viewpoint consumes less than half
1656 * of the screen width, show the prompt */
1657 if(tcp_left == tlp->tl_line.cells)
1658 f |= a_LEFT_MIN;
1660 if((f & (a_LEFT_MIN | a_HAVE_PROMPT)) == (a_LEFT_MIN | a_HAVE_PROMPT) &&
1661 w + tlp->tl_prompt_width < phy_wid){
1662 phy_base = tlp->tl_prompt_width;
1663 f |= a_SHOW_PROMPT;
1666 /* Then search for right boundary. We always leave the rightmost column
1667 * empty because some terminals [cw]ould wrap the line if we write into
1668 * that. XXX terminfo(5)/termcap(5) have the semi_auto_right_margin/sam/YE
1669 * XXX capability to indicate this, but we don't look at that */
1670 phy_wid = phy_wid_base - phy_base;
1671 tcp_right = tlp->tl_line.cells + cnt;
1673 while(&tccp[1] < tcp_right){
1674 ui16_t cw = tccp[1].tc_width;
1675 ui32_t i;
1677 if(cw == UI8_MAX) /* TODO yet HT == SPACE */
1678 cw = 1;
1679 i = w + cw;
1680 if(i > phy_wid)
1681 break;
1682 w = i;
1683 ++tccp;
1685 /*vi_right = w - vi_left;*/
1687 /* If the complete line including prompt fits on the screen, show prompt */
1688 if(--tcp_right == tccp){
1689 f |= a_RIGHT_MAX;
1691 /* Since we did brute-force walk also for the left boundary we may end up
1692 * in a situation were anything effectively fits on the screen, including
1693 * the prompt that is, but were we don't recognize this since we
1694 * restricted the search to fit in some visual viewpoint. Therefore try
1695 * again to extend the left boundary to overcome that */
1696 if(!(f & a_LEFT_MIN)){
1697 struct a_tty_cell const *tc1p = tlp->tl_line.cells;
1698 ui32_t vil1 = vi_left;
1700 assert(!(f & a_SHOW_PROMPT));
1701 w += tlp->tl_prompt_width;
1702 for(tcxp = tcp_left;;){
1703 ui32_t i = tcxp[-1].tc_width;
1705 if(i == UI8_MAX) /* TODO yet HT == SPACE */
1706 i = 1;
1707 vil1 += i;
1708 i += w;
1709 if(i > phy_wid)
1710 break;
1711 w = i;
1712 if(--tcxp == tc1p){
1713 tcp_left = tc1p;
1714 /*vi_left = vil1;*/
1715 f |= a_LEFT_MIN;
1716 break;
1719 /*w -= tlp->tl_prompt_width;*/
1722 tcp_right = tccp;
1723 tccp = tlp->tl_line.cells + cur;
1725 if((f & (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT | a_SHOW_PROMPT)) ==
1726 (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT) &&
1727 w + tlp->tl_prompt_width <= phy_wid){
1728 phy_wid -= (phy_base = tlp->tl_prompt_width);
1729 f |= a_SHOW_PROMPT;
1732 /* Try to avoid repainting the complete line - this is possible if the
1733 * cursor "did not leave the screen" and the prompt status hasn't changed.
1734 * I.e., after clamping virtual viewpoint, compare relation to physical */
1735 if((f & (a_TTY_VF_MOD_SINGLE/*FIXME*/ |
1736 a_TTY_VF_MOD_CONTENT/* xxx */ | a_TTY_VF_MOD_DIRTY)) ||
1737 (tcxp = tlp->tl_phy_start) == NULL ||
1738 tcxp > tccp || tcxp <= tcp_right)
1739 f |= a_TTY_VF_MOD_DIRTY;
1740 else{
1741 f |= a_TTY_VF_MOD_DIRTY;
1742 #if 0
1743 struct a_tty_cell const *tcyp;
1744 si32_t cur_displace;
1745 ui32_t phy_lmargin, phy_rmargin, fx, phy_displace;
1747 phy_lmargin = (fx = phy_wid) / 100;
1748 phy_rmargin = fx - (phy_lmargin * a_TTY_SCROLL_MARGIN_RIGHT);
1749 phy_lmargin *= a_TTY_SCROLL_MARGIN_LEFT;
1750 fx = (f & (a_SHOW_PROMPT | a_VISIBLE_PROMPT));
1752 if(fx == 0 || fx == (a_SHOW_PROMPT | a_VISIBLE_PROMPT)){
1754 #endif
1756 goto jpaint;
1758 /* We know what we have to paint, start synchronizing */
1759 jpaint:
1760 assert(phy_cur == tlp->tl_phy_cursor);
1761 assert(phy_wid == phy_wid_base - phy_base);
1762 assert(cnt == tlp->tl_count);
1763 assert(cnt > 0);
1764 assert(lstcur == tlp->tl_lst_cursor);
1765 assert(tccp == tlp->tl_line.cells + cur);
1767 phy_nxtcur = phy_base; /* FIXME only if repaint cpl. */
1769 /* Quickshot: is it only cursor movement within the visible screen? */
1770 if((f & a_TTY_VF_REFRESH) == a_TTY_VF_MOD_CURSOR){
1771 f |= a_MOVE_CURSOR;
1772 goto jcursor;
1775 /* To be able to apply some quick jump offs, clear line if possible */
1776 if(f & a_TTY_VF_MOD_DIRTY){
1777 /* Force complete clearance and cursor reinitialization */
1778 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr) ||
1779 !n_termcap_cmd(n_TERMCAP_CMD_ce, 0, -1))
1780 goto jerr;
1781 tlp->tl_phy_start = tcp_left;
1782 phy_cur = 0;
1785 if((f & (a_TTY_VF_MOD_DIRTY | a_SHOW_PROMPT)) && phy_cur != 0){
1786 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
1787 goto jerr;
1788 phy_cur = 0;
1791 if(f & a_SHOW_PROMPT){
1792 assert(phy_base == tlp->tl_prompt_width);
1793 if(fputs(tlp->tl_prompt, n_tty_fp) == EOF)
1794 goto jerr;
1795 phy_cur = phy_nxtcur;
1796 f |= a_VISIBLE_PROMPT;
1797 }else
1798 f &= ~a_VISIBLE_PROMPT;
1800 /* FIXME reposition cursor for paint */
1801 for(w = phy_nxtcur; tcp_left <= tcp_right; ++tcp_left){
1802 ui16_t cw;
1804 cw = tcp_left->tc_width;
1806 if(n_LIKELY(!tcp_left->tc_novis)){
1807 if(fwrite(tcp_left->tc_cbuf, sizeof *tcp_left->tc_cbuf,
1808 tcp_left->tc_count, n_tty_fp) != tcp_left->tc_count)
1809 goto jerr;
1810 }else{ /* XXX Shouldn't be here <-> CText, ui_str.c */
1811 char wbuf[8]; /* XXX magic */
1813 if(n_psonce & n_PSO_UNICODE){
1814 ui32_t wc;
1816 wc = (ui32_t)tcp_left->tc_wc;
1817 if((wc & ~0x1Fu) == 0)
1818 wc |= 0x2400;
1819 else if(wc == 0x7F)
1820 wc = 0x2421;
1821 else
1822 wc = 0x2426;
1823 n_utf32_to_utf8(wc, wbuf);
1824 }else
1825 wbuf[0] = '?', wbuf[1] = '\0';
1827 if(fputs(wbuf, n_tty_fp) == EOF)
1828 goto jerr;
1829 cw = 1;
1832 if(cw == UI8_MAX) /* TODO yet HT == SPACE */
1833 cw = 1;
1834 w += cw;
1835 if(tcp_left == tccp)
1836 phy_nxtcur = w;
1837 phy_cur += cw;
1840 /* Write something position marker alike if it does not fit on screen */
1841 if((f & a_HAVE_POSITION) &&
1842 ((f & (a_LEFT_MIN | a_RIGHT_MAX)) != (a_LEFT_MIN | a_RIGHT_MAX) ||
1843 ((f & a_HAVE_PROMPT) && !(f & a_SHOW_PROMPT)))){
1844 # ifdef HAVE_COLOUR
1845 char *posbuf = tlp->tl_pos_buf, *pos = tlp->tl_pos;
1846 # else
1847 char posbuf[5], *pos = posbuf;
1849 pos[4] = '\0';
1850 # endif
1852 if(phy_cur != (w = phy_wid_base) &&
1853 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = w, 0))
1854 goto jerr;
1856 *pos++ = '|';
1857 if((f & a_LEFT_MIN) && (!(f & a_HAVE_PROMPT) || (f & a_SHOW_PROMPT)))
1858 memcpy(pos, "^.+", 3);
1859 else if(f & a_RIGHT_MAX)
1860 memcpy(pos, ".+$", 3);
1861 else{
1862 /* Theoretical line length limit a_TTY_LINE_MAX, choose next power of
1863 * ten (10 ** 10) to represent 100 percent, since we don't have a macro
1864 * that generates a constant, and i don't trust the standard "u type
1865 * suffix automatically scales" calculate the large number */
1866 static char const itoa[] = "0123456789";
1868 ui64_t const fact100 = (ui64_t)0x3B9ACA00u * 10u, fact = fact100 / 100;
1869 ui32_t i = (ui32_t)(((fact100 / cnt) * tlp->tl_cursor) / fact);
1870 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1872 if(i < 10)
1873 pos[0] = ' ', pos[1] = itoa[i];
1874 else
1875 pos[1] = itoa[i % 10], pos[0] = itoa[i / 10];
1876 pos[2] = '%';
1879 if(fputs(posbuf, n_tty_fp) == EOF)
1880 goto jerr;
1881 phy_cur += 4;
1884 /* Users are used to see the cursor right of the point of interest, so we
1885 * need some further adjustments unless in special conditions. Be aware
1886 * that we may have adjusted cur at the beginning, too */
1887 if((cur = tlp->tl_cursor) == 0)
1888 phy_nxtcur = phy_base;
1889 else if(cur != cnt){
1890 ui16_t cw = tccp->tc_width;
1892 if(cw == UI8_MAX) /* TODO yet HT == SPACE */
1893 cw = 1;
1894 phy_nxtcur -= cw;
1897 jcursor:
1898 if(((f & a_MOVE_CURSOR) || phy_nxtcur != phy_cur) &&
1899 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = phy_nxtcur, 0))
1900 goto jerr;
1902 jleave:
1903 tlp->tl_vi_flags |= (f & a_PERSIST_MASK);
1904 tlp->tl_lst_count = tlp->tl_count;
1905 tlp->tl_lst_cursor = tlp->tl_cursor;
1906 tlp->tl_phy_cursor = phy_cur;
1908 NYD2_LEAVE;
1909 return ((f & a_TRUE_RV) != 0);
1910 jerr:
1911 f &= ~a_TRUE_RV;
1912 goto jleave;
1915 static si32_t
1916 a_tty_wboundary(struct a_tty_line *tlp, si32_t dir){/* TODO shell token-wise */
1917 bool_t anynon;
1918 struct a_tty_cell *tcap;
1919 ui32_t cur, cnt;
1920 si32_t rv;
1921 NYD2_ENTER;
1923 assert(dir == 1 || dir == -1);
1925 rv = -1;
1926 cnt = tlp->tl_count;
1927 cur = tlp->tl_cursor;
1929 if(dir < 0){
1930 if(cur == 0)
1931 goto jleave;
1932 }else if(cur + 1 >= cnt)
1933 goto jleave;
1934 else
1935 --cnt, --cur; /* xxx Unsigned wrapping may occur (twice), then */
1937 for(rv = 0, tcap = tlp->tl_line.cells, anynon = FAL0;;){
1938 wchar_t wc;
1940 wc = tcap[cur += (ui32_t)dir].tc_wc;
1941 if(/*TODO not everywhere iswblank(wc)*/ wc == L' ' || wc == L'\t' ||
1942 iswpunct(wc)){
1943 if(anynon)
1944 break;
1945 }else
1946 anynon = TRU1;
1948 ++rv;
1950 if(dir < 0){
1951 if(cur == 0)
1952 break;
1953 }else if(cur + 1 >= cnt){
1954 ++rv;
1955 break;
1958 jleave:
1959 NYD2_LEAVE;
1960 return rv;
1963 static void
1964 a_tty_khome(struct a_tty_line *tlp, bool_t dobell){
1965 ui32_t f;
1966 NYD2_ENTER;
1968 if(n_LIKELY(tlp->tl_cursor > 0)){
1969 tlp->tl_cursor = 0;
1970 f = a_TTY_VF_MOD_CURSOR;
1971 }else if(dobell)
1972 f = a_TTY_VF_BELL;
1973 else
1974 f = a_TTY_VF_NONE;
1976 tlp->tl_vi_flags |= f;
1977 NYD2_LEAVE;
1980 static void
1981 a_tty_kend(struct a_tty_line *tlp){
1982 ui32_t f;
1983 NYD2_ENTER;
1985 if(n_LIKELY(tlp->tl_cursor < tlp->tl_count)){
1986 tlp->tl_cursor = tlp->tl_count;
1987 f = a_TTY_VF_MOD_CURSOR;
1988 }else
1989 f = a_TTY_VF_BELL;
1991 tlp->tl_vi_flags |= f;
1992 NYD2_LEAVE;
1995 static void
1996 a_tty_kbs(struct a_tty_line *tlp){
1997 ui32_t f, cur, cnt;
1998 NYD2_ENTER;
2000 cur = tlp->tl_cursor;
2001 cnt = tlp->tl_count;
2003 if(n_LIKELY(cur > 0)){
2004 tlp->tl_cursor = --cur;
2005 tlp->tl_count = --cnt;
2007 if((cnt -= cur) > 0){
2008 struct a_tty_cell *tcap;
2010 tcap = tlp->tl_line.cells + cur;
2011 memmove(tcap, &tcap[1], cnt *= sizeof(*tcap));
2013 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
2014 }else
2015 f = a_TTY_VF_BELL;
2017 tlp->tl_vi_flags |= f;
2018 NYD2_LEAVE;
2021 static void
2022 a_tty_ksnarf(struct a_tty_line *tlp, bool_t cplline, bool_t dobell){
2023 ui32_t i, f;
2024 NYD2_ENTER;
2026 f = a_TTY_VF_NONE;
2027 i = tlp->tl_cursor;
2029 if(cplline && i > 0){
2030 tlp->tl_cursor = i = 0;
2031 f = a_TTY_VF_MOD_CURSOR;
2034 if(n_LIKELY(i < tlp->tl_count)){
2035 struct a_tty_cell *tcap;
2037 tcap = &tlp->tl_line.cells[0];
2038 a_tty_copy2paste(tlp, &tcap[i], &tcap[tlp->tl_count]);
2039 tlp->tl_count = i;
2040 f = a_TTY_VF_MOD_CONTENT;
2041 }else if(dobell)
2042 f |= a_TTY_VF_BELL;
2044 tlp->tl_vi_flags |= f;
2045 NYD2_LEAVE;
2048 static si32_t
2049 a_tty_kdel(struct a_tty_line *tlp){
2050 ui32_t cur, cnt, f;
2051 si32_t i;
2052 NYD2_ENTER;
2054 cur = tlp->tl_cursor;
2055 cnt = tlp->tl_count;
2056 i = (si32_t)(cnt - cur);
2058 if(n_LIKELY(i > 0)){
2059 tlp->tl_count = --cnt;
2061 if(n_LIKELY(--i > 0)){
2062 struct a_tty_cell *tcap;
2064 tcap = &tlp->tl_line.cells[cur];
2065 memmove(tcap, &tcap[1], (ui32_t)i * sizeof(*tcap));
2067 f = a_TTY_VF_MOD_CONTENT;
2068 }else if(cnt == 0 && !ok_blook(ignoreeof)){
2069 putc('^', n_tty_fp);
2070 putc('D', n_tty_fp);
2071 i = -1;
2072 f = a_TTY_VF_NONE;
2073 }else{
2074 i = 0;
2075 f = a_TTY_VF_BELL;
2078 tlp->tl_vi_flags |= f;
2079 NYD2_LEAVE;
2080 return i;
2083 static void
2084 a_tty_kleft(struct a_tty_line *tlp){
2085 ui32_t f;
2086 NYD2_ENTER;
2088 if(n_LIKELY(tlp->tl_cursor > 0)){
2089 --tlp->tl_cursor;
2090 f = a_TTY_VF_MOD_CURSOR;
2091 }else
2092 f = a_TTY_VF_BELL;
2094 tlp->tl_vi_flags |= f;
2095 NYD2_LEAVE;
2098 static void
2099 a_tty_kright(struct a_tty_line *tlp){
2100 ui32_t i;
2101 NYD2_ENTER;
2103 if(n_LIKELY((i = tlp->tl_cursor + 1) <= tlp->tl_count)){
2104 tlp->tl_cursor = i;
2105 i = a_TTY_VF_MOD_CURSOR;
2106 }else
2107 i = a_TTY_VF_BELL;
2109 tlp->tl_vi_flags |= i;
2110 NYD2_LEAVE;
2113 static void
2114 a_tty_ksnarfw(struct a_tty_line *tlp, bool_t fwd){
2115 struct a_tty_cell *tcap;
2116 ui32_t cnt, cur, f;
2117 si32_t i;
2118 NYD2_ENTER;
2120 if(n_UNLIKELY((i = a_tty_wboundary(tlp, (fwd ? +1 : -1))) <= 0)){
2121 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
2122 goto jleave;
2125 cnt = tlp->tl_count - (ui32_t)i;
2126 cur = tlp->tl_cursor;
2127 if(!fwd)
2128 cur -= (ui32_t)i;
2129 tcap = &tlp->tl_line.cells[cur];
2131 a_tty_copy2paste(tlp, &tcap[0], &tcap[i]);
2133 if((tlp->tl_count = cnt) != (tlp->tl_cursor = cur)){
2134 cnt -= cur;
2135 memmove(&tcap[0], &tcap[i], cnt * sizeof(*tcap)); /* FIXME*/
2138 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
2139 jleave:
2140 tlp->tl_vi_flags |= f;
2141 NYD2_LEAVE;
2144 static void
2145 a_tty_kgow(struct a_tty_line *tlp, si32_t dir){
2146 ui32_t f;
2147 si32_t i;
2148 NYD2_ENTER;
2150 if(n_UNLIKELY((i = a_tty_wboundary(tlp, dir)) <= 0))
2151 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
2152 else{
2153 if(dir < 0)
2154 i = -i;
2155 tlp->tl_cursor += (ui32_t)i;
2156 f = a_TTY_VF_MOD_CURSOR;
2159 tlp->tl_vi_flags |= f;
2160 NYD2_LEAVE;
2163 static void
2164 a_tty_kgoscr(struct a_tty_line *tlp, si32_t dir){
2165 ui32_t sw, i, cur, f, cnt;
2166 NYD2_ENTER;
2168 sw = (ui32_t)n_scrnwidth - 2;
2169 if(sw > (i = tlp->tl_prompt_width))
2170 sw -= i;
2171 cur = tlp->tl_cursor;
2172 f = a_TTY_VF_BELL;
2174 if(dir > 0){
2175 for(cnt = tlp->tl_count; cur < cnt && sw > 0; ++cur){
2176 i = tlp->tl_line.cells[cur].tc_width;
2177 i = n_MIN(sw, i);
2178 sw -= i;
2180 }else{
2181 while(cur > 0 && sw > 0){
2182 i = tlp->tl_line.cells[--cur].tc_width;
2183 i = n_MIN(sw, i);
2184 sw -= i;
2187 if(cur != tlp->tl_cursor){
2188 tlp->tl_cursor = cur;
2189 f = a_TTY_VF_MOD_CURSOR;
2192 tlp->tl_vi_flags |= f;
2193 NYD2_LEAVE;
2196 static bool_t
2197 a_tty_kother(struct a_tty_line *tlp, wchar_t wc){
2198 /* Append if at EOL, insert otherwise;
2199 * since we may move around character-wise, always use a fresh ps */
2200 mbstate_t ps;
2201 struct a_tty_cell tc, *tcap;
2202 ui32_t f, cur, cnt;
2203 bool_t rv;
2204 NYD2_ENTER;
2206 rv = FAL0;
2207 f = a_TTY_VF_NONE;
2209 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
2210 if(tlp->tl_count + 1 >= a_TTY_LINE_MAX){
2211 n_err(_("Stop here, we can't extend line beyond size limit\n"));
2212 goto jleave;
2215 /* First init a cell and see whether we'll really handle this wc */
2216 memset(&ps, 0, sizeof ps);
2217 /* C99 */{
2218 size_t l;
2220 l = wcrtomb(tc.tc_cbuf, tc.tc_wc = wc, &ps);
2221 if(n_UNLIKELY(l > MB_LEN_MAX)){
2222 jemb:
2223 n_err(_("wcrtomb(3) error: too many multibyte character bytes\n"));
2224 goto jleave;
2226 tc.tc_count = (ui16_t)l;
2228 if(n_UNLIKELY((n_psonce & n_PSO_ENC_MBSTATE) != 0)){
2229 l = wcrtomb(&tc.tc_cbuf[l], L'\0', &ps);
2230 if(n_LIKELY(l == 1))
2231 /* Only NUL terminator */;
2232 else if(n_LIKELY(--l < MB_LEN_MAX))
2233 tc.tc_count += (ui16_t)l;
2234 else
2235 goto jemb;
2239 /* Yes, we will! Place it in the array */
2240 tc.tc_novis = (iswprint(wc) == 0);
2241 tc.tc_width = a_tty_wcwidth(wc);
2242 /* TODO if(tc.tc_novis && tc.tc_width > 0) */
2244 cur = tlp->tl_cursor++;
2245 cnt = tlp->tl_count++ - cur;
2246 tcap = &tlp->tl_line.cells[cur];
2247 if(cnt >= 1){
2248 memmove(&tcap[1], tcap, cnt * sizeof(*tcap));
2249 f = a_TTY_VF_MOD_CONTENT;
2250 }else
2251 f = a_TTY_VF_MOD_SINGLE;
2252 memcpy(tcap, &tc, sizeof *tcap);
2254 f |= a_TTY_VF_MOD_CURSOR;
2255 rv = TRU1;
2256 jleave:
2257 if(!rv)
2258 f |= a_TTY_VF_BELL;
2259 tlp->tl_vi_flags |= f;
2260 NYD2_LEAVE;
2261 return rv;
2264 static ui32_t
2265 a_tty_kht(struct a_tty_line *tlp){
2266 ui8_t (*mempool)[n_MEMORY_POOL_TYPE_SIZEOF], *mempool_persist;
2267 struct stat sb;
2268 struct str orig, bot, topp, sub, exp, preexp;
2269 struct n_string shou, *shoup;
2270 struct a_tty_cell *ctop, *cx;
2271 bool_t wedid, set_savec;
2272 ui32_t rv, f;
2273 NYD2_ENTER;
2275 /* Get plain line data; if this is the first expansion/xy, update the
2276 * very original content so that ^G gets the origin back */
2277 orig = tlp->tl_savec;
2278 a_tty_cell2save(tlp);
2279 exp = tlp->tl_savec;
2280 if(orig.s != NULL){
2281 /*tlp->tl_savec = orig;*/
2282 set_savec = FAL0;
2283 }else
2284 set_savec = TRU1;
2285 orig = exp;
2287 mempool_persist = n_go_data->gdc_mempool;
2288 n_memory_pool_push(mempool = n_lofi_alloc(sizeof *mempool));
2290 shoup = n_string_creat_auto(&shou);
2291 f = a_TTY_VF_NONE;
2293 /* C99 */{
2294 size_t max;
2295 struct a_tty_cell *cword;
2297 /* Find the word to be expanded */
2298 cword = tlp->tl_line.cells;
2299 ctop = &cword[tlp->tl_cursor];
2300 cx = &cword[tlp->tl_count];
2302 /* topp: separate data right of cursor */
2303 if(cx > ctop){
2304 for(rv = 0; ctop < cx; ++ctop)
2305 rv += ctop->tc_count;
2306 topp.l = rv;
2307 topp.s = orig.s + orig.l - rv;
2308 ctop = cword + tlp->tl_cursor;
2309 }else
2310 topp.s = NULL, topp.l = 0;
2312 /* Find the shell token that corresponds to the cursor position */
2313 max = 0;
2314 if(ctop > cword){
2315 for(; cword < ctop; ++cword)
2316 max += cword->tc_count;
2318 bot = sub = orig;
2319 bot.l = 0;
2320 sub.l = max;
2322 if(max > 0){
2323 for(;;){
2324 enum n_shexp_state shs;
2326 exp = sub;
2327 shs = n_shexp_parse_token((n_SHEXP_PARSE_DRYRUN |
2328 n_SHEXP_PARSE_TRIM_SPACE | n_SHEXP_PARSE_IGNORE_EMPTY |
2329 n_SHEXP_PARSE_QUOTE_AUTO_CLOSE), NULL, &sub, NULL);
2330 if(sub.l != 0){
2331 size_t x;
2333 assert(max >= sub.l);
2334 x = max - sub.l;
2335 bot.l += x;
2336 max -= x;
2337 continue;
2339 if(shs & n_SHEXP_STATE_ERR_MASK){
2340 n_err(_("Invalid completion pattern: %.*s\n"),
2341 (int)exp.l, exp.s);
2342 f |= a_TTY_VF_BELL;
2343 goto jnope;
2346 /* All WS? Trailing WS that has been "jumped over"? */
2347 if(exp.l == 0 || (shs & n_SHEXP_STATE_WS_TRAIL))
2348 break;
2350 n_shexp_parse_token((n_SHEXP_PARSE_TRIM_SPACE |
2351 n_SHEXP_PARSE_IGNORE_EMPTY | n_SHEXP_PARSE_QUOTE_AUTO_CLOSE),
2352 shoup, &exp, NULL);
2353 break;
2356 sub.s = n_string_cp(shoup);
2357 sub.l = shoup->s_len;
2361 /* Leave room for "implicit asterisk" expansion, as below */
2362 if(sub.l == 0){
2363 sub.s = n_UNCONST(n_star);
2364 sub.l = sizeof(n_star) -1;
2367 preexp.s = n_UNCONST(n_empty);
2368 preexp.l = sizeof(n_empty) -1;
2369 wedid = FAL0;
2370 jredo:
2371 /* TODO Super-Heavy-Metal: block all sigs, avoid leaks on jump */
2372 hold_all_sigs();
2373 exp.s = fexpand(sub.s, a_TTY_TAB_FEXP_FL);
2374 rele_all_sigs();
2376 if(exp.s == NULL || (exp.l = strlen(exp.s)) == 0){
2377 if(wedid < FAL0)
2378 goto jnope;
2379 /* No. But maybe the users' desire was to complete only a part of the
2380 * shell token of interest! TODO This can be improved, we would need to
2381 * TODO have shexp_parse to create a DOM structure of parsed snippets, so
2382 * TODO that we can tell for each snippet which quote is active and
2383 * TODO whether we may cross its boundary and/or apply expansion for it!
2384 * TODO Only like that we would be able to properly requote user input
2385 * TODO like "'['a-z]<TAB>" to e.g. "\[a-z]" for glob purposes! */
2386 if(wedid == TRU1){
2387 size_t i, li;
2389 wedid = TRUM1;
2390 for(li = UIZ_MAX, i = sub.l; i-- > 0;){
2391 char c;
2393 if((c = sub.s[i]) == '/' || c == '+' /* *folder*! */)
2394 li = i;
2395 /* Do stop once some "magic" characters are seen XXX magic set */
2396 else if(c == '<' || c == '>' || c == '=' || c == ':')
2397 break;
2399 if(li != UIZ_MAX){
2400 preexp = sub;
2401 preexp.l = li;
2402 sub.l -= li;
2403 sub.s += li;
2404 goto jredo;
2408 /* A different case is that the user input includes for example character
2409 * classes: here fexpand() will go over glob, and that will not find any
2410 * match, thus returning NULL; try to wildcard expand this pattern! */
2411 jaster_check:
2412 if(sub.s[sub.l - 1] != '*'){
2413 wedid = TRU1;
2414 shoup = n_string_push_c(shoup, '*');
2415 sub.s = n_string_cp(shoup);
2416 sub.l = shoup->s_len;
2417 goto jredo;
2419 goto jnope;
2422 if(wedid == TRUM1 && preexp.l > 0)
2423 preexp.s = savestrbuf(preexp.s, preexp.l);
2425 /* May be multi-return! */
2426 if(n_pstate & n_PS_EXPAND_MULTIRESULT)
2427 goto jmulti;
2429 /* xxx That is not really true since the limit counts characters not bytes */
2430 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
2431 if(exp.l >= a_TTY_LINE_MAX - 1 || a_TTY_LINE_MAX - 1 - exp.l < preexp.l){
2432 n_err(_("Tabulator expansion would extend beyond line size limit\n"));
2433 f |= a_TTY_VF_BELL;
2434 goto jnope;
2437 /* If the expansion equals the original string, assume the user wants what
2438 * is usually known as tab completion, append `*' and restart */
2439 if(!wedid && exp.l == sub.l && !memcmp(exp.s, sub.s, exp.l))
2440 goto jaster_check;
2442 if(exp.s[exp.l - 1] != '/'){
2443 if(!stat(exp.s, &sb) && S_ISDIR(sb.st_mode)){
2444 shoup = n_string_assign_buf(shoup, exp.s, exp.l);
2445 shoup = n_string_push_c(shoup, '/');
2446 exp.s = n_string_cp(shoup);
2447 goto jset;
2450 exp.s[exp.l] = '\0';
2452 jset:
2453 exp.l = strlen(exp.s = n_shexp_quote_cp(exp.s, tlp->tl_quote_rndtrip));
2454 tlp->tl_defc_cursor_byte = bot.l + preexp.l + exp.l -1;
2456 orig.l = bot.l + preexp.l + exp.l + topp.l;
2457 orig.s = n_autorec_alloc_from_pool(mempool_persist, orig.l + 5 +1);
2458 if((rv = (ui32_t)bot.l) > 0)
2459 memcpy(orig.s, bot.s, rv);
2460 if(preexp.l > 0){
2461 memcpy(&orig.s[rv], preexp.s, preexp.l);
2462 rv += preexp.l;
2464 memcpy(&orig.s[rv], exp.s, exp.l);
2465 rv += exp.l;
2466 if(topp.l > 0){
2467 memcpy(&orig.s[rv], topp.s, topp.l);
2468 rv += topp.l;
2470 orig.s[rv] = '\0';
2472 tlp->tl_defc = orig;
2473 tlp->tl_count = tlp->tl_cursor = 0;
2474 f |= a_TTY_VF_MOD_DIRTY;
2475 jleave:
2476 n_memory_pool_pop(mempool);
2477 n_lofi_free(mempool);
2478 tlp->tl_vi_flags |= f;
2479 NYD2_LEAVE;
2480 return rv;
2482 jmulti:{
2483 struct n_visual_info_ctx vic;
2484 struct str input;
2485 wc_t c2, c1;
2486 bool_t isfirst;
2487 char const *lococp;
2488 size_t locolen, scrwid, lnlen, lncnt, prefixlen;
2489 FILE *fp;
2491 if((fp = Ftmp(NULL, "tabex", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
2492 n_perr(_("tmpfile"), 0);
2493 fp = n_tty_fp;
2496 /* How long is the result string for real? Search the NUL NUL
2497 * terminator. While here, detect the longest entry to perform an
2498 * initial allocation of our accumulator string */
2499 locolen = preexp.l;
2501 size_t i;
2503 i = strlen(&exp.s[++exp.l]);
2504 locolen = n_MAX(locolen, i);
2505 exp.l += i;
2506 }while(exp.s[exp.l + 1] != '\0');
2508 shoup = n_string_reserve(n_string_trunc(shoup, 0),
2509 locolen + (locolen >> 1));
2511 /* Iterate (once again) over all results */
2512 scrwid = n_SCRNWIDTH_FOR_LISTS;
2513 lnlen = lncnt = 0;
2514 n_UNINIT(prefixlen, 0);
2515 n_UNINIT(lococp, NULL);
2516 n_UNINIT(c1, '\0');
2517 for(isfirst = TRU1; exp.l > 0; isfirst = FAL0, c1 = c2){
2518 size_t i;
2519 char const *fullpath;
2521 /* Next result */
2522 sub = exp;
2523 sub.l = i = strlen(sub.s);
2524 assert(exp.l >= i);
2525 if((exp.l -= i) > 0)
2526 --exp.l;
2527 exp.s += ++i;
2529 /* Separate dirname and basename */
2530 fullpath = sub.s;
2531 if(isfirst){
2532 char const *cp;
2534 if((cp = strrchr(fullpath, '/')) != NULL)
2535 prefixlen = PTR2SIZE(++cp - fullpath);
2536 else
2537 prefixlen = 0;
2539 if(prefixlen > 0 && prefixlen < sub.l){
2540 sub.l -= prefixlen;
2541 sub.s += prefixlen;
2544 /* We want case-insensitive sort-order */
2545 memset(&vic, 0, sizeof vic);
2546 vic.vic_indat = sub.s;
2547 vic.vic_inlen = sub.l;
2548 c2 = n_visual_info(&vic, n_VISUAL_INFO_ONE_CHAR) ? vic.vic_waccu
2549 : (ui8_t)*sub.s;
2550 #ifdef HAVE_C90AMEND1
2551 c2 = towlower(c2);
2552 #else
2553 c2 = lowerconv(c2);
2554 #endif
2556 /* Query longest common prefix along the way */
2557 if(isfirst){
2558 c1 = c2;
2559 lococp = sub.s;
2560 locolen = sub.l;
2561 }else if(locolen > 0){
2562 for(i = 0; i < locolen; ++i)
2563 if(lococp[i] != sub.s[i]){
2564 i = field_detect_clip(i, lococp, i);
2565 locolen = i;
2566 break;
2570 /* Prepare display */
2571 input = sub;
2572 shoup = n_shexp_quote(n_string_trunc(shoup, 0), &input,
2573 tlp->tl_quote_rndtrip);
2574 memset(&vic, 0, sizeof vic);
2575 vic.vic_indat = shoup->s_dat;
2576 vic.vic_inlen = shoup->s_len;
2577 if(!n_visual_info(&vic,
2578 n_VISUAL_INFO_SKIP_ERRORS | n_VISUAL_INFO_WIDTH_QUERY))
2579 vic.vic_vi_width = shoup->s_len;
2581 /* Put on screen. Indent follow lines of same sort slot.
2582 * Leave enough room for filename tagging */
2583 if((c1 = (c1 != c2))){
2584 #ifdef HAVE_C90AMEND1
2585 c1 = (iswalnum(c2) != 0);
2586 #else
2587 c1 = (alnumchar(c2) != 0);
2588 #endif
2590 if(isfirst || c1 ||
2591 scrwid < lnlen || scrwid - lnlen <= vic.vic_vi_width + 2){
2592 putc('\n', fp);
2593 if(scrwid < lnlen)
2594 ++lncnt;
2595 ++lncnt, lnlen = 0;
2596 if(!isfirst && !c1)
2597 goto jsep;
2598 }else if(lnlen > 0){
2599 jsep:
2600 fputs(" ", fp);
2601 lnlen += 2;
2603 fputs(n_string_cp(shoup), fp);
2604 lnlen += vic.vic_vi_width;
2606 /* Support the known filename tagging
2607 * XXX *line-editor-completion-filetype* or so */
2608 if(!lstat(fullpath, &sb)){
2609 char c = '\0';
2611 if(S_ISDIR(sb.st_mode))
2612 c = '/';
2613 else if(S_ISLNK(sb.st_mode))
2614 c = '@';
2615 # ifdef S_ISFIFO
2616 else if(S_ISFIFO(sb.st_mode))
2617 c = '|';
2618 # endif
2619 # ifdef S_ISSOCK
2620 else if(S_ISSOCK(sb.st_mode))
2621 c = '=';
2622 # endif
2623 # ifdef S_ISCHR
2624 else if(S_ISCHR(sb.st_mode))
2625 c = '%';
2626 # endif
2627 # ifdef S_ISBLK
2628 else if(S_ISBLK(sb.st_mode))
2629 c = '#';
2630 # endif
2632 if(c != '\0'){
2633 putc(c, fp);
2634 ++lnlen;
2638 putc('\n', fp);
2639 ++lncnt;
2641 page_or_print(fp, lncnt);
2642 if(fp != n_tty_fp)
2643 Fclose(fp);
2645 n_string_gut(shoup);
2647 /* A common prefix of 0 means we cannot provide the user any auto
2648 * completed characters for the multiple possible results.
2649 * Otherwise we can, so extend the visual line content by the common
2650 * prefix (in a reversible way) */
2651 f |= a_TTY_VF_BELL; /* XXX -> *line-editor-completion-bell*? or so */
2652 if(locolen > 0){
2653 (exp.s = n_UNCONST(lococp))[locolen] = '\0';
2654 exp.s -= prefixlen;
2655 exp.l = (locolen += prefixlen);
2656 goto jset;
2660 jnope:
2661 /* If we've provided a default content, but failed to expand, there is
2662 * nothing we can "revert to": drop that default again */
2663 if(set_savec){
2664 tlp->tl_savec.s = NULL;
2665 tlp->tl_savec.l = 0;
2667 f &= a_TTY_VF_BELL; /* XXX -> *line-editor-completion-bell*? or so */
2668 rv = 0;
2669 goto jleave;
2672 # ifdef HAVE_HISTORY
2673 static ui32_t
2674 a_tty__khist_shared(struct a_tty_line *tlp, struct a_tty_hist *thp){
2675 ui32_t f, rv;
2676 NYD2_ENTER;
2678 if(n_LIKELY((tlp->tl_hist = thp) != NULL)){
2679 char *cp;
2680 size_t i;
2682 i = thp->th_len;
2683 if(tlp->tl_goinflags & n_GO_INPUT_CTX_COMPOSE){
2684 ++i;
2685 if(!(thp->th_flags & a_TTY_HIST_CTX_COMPOSE))
2686 ++i;
2688 tlp->tl_defc.s = cp = n_autorec_alloc(i +1);
2689 if(tlp->tl_goinflags & n_GO_INPUT_CTX_COMPOSE){
2690 if((*cp = ok_vlook(escape)[0]) == '\0')
2691 *cp = n_ESCAPE[0];
2692 ++cp;
2693 if(!(thp->th_flags & a_TTY_HIST_CTX_COMPOSE))
2694 *cp++ = ':';
2696 memcpy(cp, thp->th_dat, thp->th_len +1);
2697 rv = tlp->tl_defc.l = i;
2699 f = (tlp->tl_count > 0) ? a_TTY_VF_MOD_DIRTY : a_TTY_VF_NONE;
2700 tlp->tl_count = tlp->tl_cursor = 0;
2701 }else{
2702 f = a_TTY_VF_BELL;
2703 rv = UI32_MAX;
2706 tlp->tl_vi_flags |= f;
2707 NYD2_LEAVE;
2708 return rv;
2711 static ui32_t
2712 a_tty_khist(struct a_tty_line *tlp, bool_t fwd){
2713 struct a_tty_hist *thp;
2714 ui32_t rv;
2715 NYD2_ENTER;
2717 /* If we're not in history mode yet, save line content */
2718 if((thp = tlp->tl_hist) == NULL){
2719 a_tty_cell2save(tlp);
2720 if((thp = a_tty.tg_hist) == NULL)
2721 goto jleave;
2722 if(fwd)
2723 while(thp->th_older != NULL)
2724 thp = thp->th_older;
2725 goto jleave;
2728 while((thp = fwd ? thp->th_younger : thp->th_older) != NULL){
2729 /* Applicable to input context? Compose mode swallows anything */
2730 if((tlp->tl_goinflags & n__GO_INPUT_CTX_MASK) == n_GO_INPUT_CTX_COMPOSE)
2731 break;
2732 if((thp->th_flags & a_TTY_HIST_CTX_MASK) != a_TTY_HIST_CTX_COMPOSE)
2733 break;
2735 jleave:
2736 rv = a_tty__khist_shared(tlp, thp);
2737 NYD2_LEAVE;
2738 return rv;
2741 static ui32_t
2742 a_tty_khist_search(struct a_tty_line *tlp, bool_t fwd){
2743 struct str orig_savec;
2744 ui32_t xoff, rv;
2745 struct a_tty_hist *thp;
2746 NYD2_ENTER;
2748 thp = NULL;
2750 /* We cannot complete an empty line */
2751 if(n_UNLIKELY(tlp->tl_count == 0)){
2752 /* XXX The upcoming hard reset would restore a set savec buffer,
2753 * XXX so forcefully reset that. A cleaner solution would be to
2754 * XXX reset it whenever a restore is no longer desired */
2755 tlp->tl_savec.s = NULL;
2756 tlp->tl_savec.l = 0;
2757 goto jleave;
2760 /* xxx It is a bit of a hack, but let's just hard-code the knowledge that
2761 * xxx in compose mode the first character is *escape* and must be skipped
2762 * xxx when searching the history. Alternatively we would need to have
2763 * xxx context-specific history search hooks which would do the search,
2764 * xxx which is overkill for our sole special case compose mode */
2765 if((tlp->tl_goinflags & n__GO_INPUT_CTX_MASK) == n_GO_INPUT_CTX_COMPOSE)
2766 xoff = 1;
2767 else
2768 xoff = 0;
2770 if((thp = tlp->tl_hist) == NULL){
2771 a_tty_cell2save(tlp);
2772 if((thp = a_tty.tg_hist) == NULL) /* TODO Should end "doing nothing"! */
2773 goto jleave;
2774 if(fwd)
2775 while(thp->th_older != NULL)
2776 thp = thp->th_older;
2777 orig_savec.s = NULL;
2778 orig_savec.l = 0; /* silence CC */
2779 }else{
2780 while((thp = fwd ? thp->th_younger : thp->th_older) != NULL){
2781 /* Applicable to input context? Compose mode swallows anything */
2782 if(xoff != 0)
2783 break;
2784 if((thp->th_flags & a_TTY_HIST_CTX_MASK) != a_TTY_HIST_CTX_COMPOSE)
2785 break;
2787 if(thp == NULL)
2788 goto jleave;
2790 orig_savec = tlp->tl_savec;
2793 if(xoff >= tlp->tl_savec.l){
2794 thp = NULL;
2795 goto jleave;
2798 if(orig_savec.s == NULL)
2799 a_tty_cell2save(tlp);
2801 for(; thp != NULL; thp = fwd ? thp->th_younger : thp->th_older){
2802 /* Applicable to input context? Compose mode swallows anything */
2803 if(xoff != 1 && (thp->th_flags & a_TTY_HIST_CTX_MASK) ==
2804 a_TTY_HIST_CTX_COMPOSE)
2805 continue;
2806 if(is_prefix(&tlp->tl_savec.s[xoff], thp->th_dat))
2807 break;
2810 if(orig_savec.s != NULL)
2811 tlp->tl_savec = orig_savec;
2812 jleave:
2813 rv = a_tty__khist_shared(tlp, thp);
2814 NYD2_LEAVE;
2815 return rv;
2817 # endif /* HAVE_HISTORY */
2819 static enum a_tty_fun_status
2820 a_tty_fun(struct a_tty_line *tlp, enum a_tty_bind_flags tbf, size_t *len){
2821 enum a_tty_fun_status rv;
2822 NYD2_ENTER;
2824 rv = a_TTY_FUN_STATUS_OK;
2825 # undef a_X
2826 # define a_X(N) a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## N)
2827 switch(a_TTY_BIND_FUN_REDUCE(tbf)){
2828 case a_X(BELL):
2829 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2830 break;
2831 case a_X(GO_BWD):
2832 a_tty_kleft(tlp);
2833 break;
2834 case a_X(GO_FWD):
2835 a_tty_kright(tlp);
2836 break;
2837 case a_X(GO_WORD_BWD):
2838 a_tty_kgow(tlp, -1);
2839 break;
2840 case a_X(GO_WORD_FWD):
2841 a_tty_kgow(tlp, +1);
2842 break;
2843 case a_X(GO_SCREEN_BWD):
2844 a_tty_kgoscr(tlp, -1);
2845 break;
2846 case a_X(GO_SCREEN_FWD):
2847 a_tty_kgoscr(tlp, +1);
2848 break;
2849 case a_X(GO_HOME):
2850 a_tty_khome(tlp, TRU1);
2851 break;
2852 case a_X(GO_END):
2853 a_tty_kend(tlp);
2854 break;
2855 case a_X(DEL_BWD):
2856 a_tty_kbs(tlp);
2857 break;
2858 case a_X(DEL_FWD):
2859 if(a_tty_kdel(tlp) < 0)
2860 rv = a_TTY_FUN_STATUS_END;
2861 break;
2862 case a_X(SNARF_WORD_BWD):
2863 a_tty_ksnarfw(tlp, FAL0);
2864 break;
2865 case a_X(SNARF_WORD_FWD):
2866 a_tty_ksnarfw(tlp, TRU1);
2867 break;
2868 case a_X(SNARF_END):
2869 a_tty_ksnarf(tlp, FAL0, TRU1);
2870 break;
2871 case a_X(SNARF_LINE):
2872 a_tty_ksnarf(tlp, TRU1, (tlp->tl_count == 0));
2873 break;
2875 case a_X(HIST_FWD):{
2876 # ifdef HAVE_HISTORY
2877 bool_t isfwd = TRU1;
2879 if(0){
2880 # endif
2881 /* FALLTHRU */
2882 case a_X(HIST_BWD):
2883 # ifdef HAVE_HISTORY
2884 isfwd = FAL0;
2886 if((*len = a_tty_khist(tlp, isfwd)) != UI32_MAX){
2887 rv = a_TTY_FUN_STATUS_RESTART;
2888 break;
2890 goto jreset;
2891 # endif
2893 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2894 break;
2896 case a_X(HIST_SRCH_FWD):{
2897 # ifdef HAVE_HISTORY
2898 bool_t isfwd = TRU1;
2900 if(0){
2901 # endif
2902 /* FALLTHRU */
2903 case a_X(HIST_SRCH_BWD):
2904 # ifdef HAVE_HISTORY
2905 isfwd = FAL0;
2907 if((*len = a_tty_khist_search(tlp, isfwd)) != UI32_MAX){
2908 rv = a_TTY_FUN_STATUS_RESTART;
2909 break;
2911 goto jreset;
2912 # else
2913 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2914 # endif
2915 }break;
2917 case a_X(REPAINT):
2918 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2919 break;
2920 case a_X(QUOTE_RNDTRIP):
2921 tlp->tl_quote_rndtrip = !tlp->tl_quote_rndtrip;
2922 break;
2923 case a_X(PROMPT_CHAR):{
2924 wchar_t wc;
2926 if((wc = a_tty_vinuni(tlp)) > 0)
2927 a_tty_kother(tlp, wc);
2928 }break;
2929 case a_X(COMPLETE):
2930 if((*len = a_tty_kht(tlp)) > 0)
2931 rv = a_TTY_FUN_STATUS_RESTART;
2932 break;
2934 case a_X(PASTE):
2935 if(tlp->tl_pastebuf.l > 0)
2936 *len = (tlp->tl_defc = tlp->tl_pastebuf).l;
2937 else
2938 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2939 break;
2941 case a_X(CLEAR_SCREEN):
2942 tlp->tl_vi_flags |= (n_termcap_cmdx(n_TERMCAP_CMD_cl) == TRU1)
2943 ? a_TTY_VF_MOD_DIRTY : a_TTY_VF_BELL;
2944 break;
2946 case a_X(CANCEL):
2947 /* Normally this just causes a restart and thus resets the state
2948 * machine */
2949 if(tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2951 # ifdef HAVE_KEY_BINDINGS
2952 tlp->tl_bind_takeover = '\0';
2953 # endif
2954 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2955 rv = a_TTY_FUN_STATUS_RESTART;
2956 break;
2958 case a_X(RESET):
2959 if(tlp->tl_count == 0 && tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2960 # ifdef HAVE_KEY_BINDINGS
2961 tlp->tl_bind_takeover = '\0';
2962 # endif
2963 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY | a_TTY_VF_BELL;
2964 break;
2965 }else if(0){
2966 case a_X(FULLRESET):
2967 tlp->tl_savec.s = tlp->tl_defc.s = NULL;
2968 tlp->tl_savec.l = tlp->tl_defc.l = 0;
2969 tlp->tl_defc_cursor_byte = 0;
2970 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2972 jreset:
2973 # ifdef HAVE_KEY_BINDINGS
2974 tlp->tl_bind_takeover = '\0';
2975 # endif
2976 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2977 tlp->tl_cursor = tlp->tl_count = 0;
2978 # ifdef HAVE_HISTORY
2979 tlp->tl_hist = NULL;
2980 # endif
2981 if((*len = tlp->tl_savec.l) != 0){
2982 tlp->tl_defc = tlp->tl_savec;
2983 tlp->tl_savec.s = NULL;
2984 tlp->tl_savec.l = 0;
2985 }else
2986 *len = tlp->tl_defc.l;
2987 rv = a_TTY_FUN_STATUS_RESTART;
2988 break;
2990 default:
2991 case a_X(COMMIT):
2992 rv = a_TTY_FUN_STATUS_COMMIT;
2993 break;
2995 # undef a_X
2997 NYD2_LEAVE;
2998 return rv;
3001 static ssize_t
3002 a_tty_readline(struct a_tty_line *tlp, size_t len, bool_t *histok_or_null
3003 n_MEMORY_DEBUG_ARGS){
3004 /* We want to save code, yet we may have to incorporate a lines'
3005 * default content and / or default input to switch back to after some
3006 * history movement; let "len > 0" mean "have to display some data
3007 * buffer" -> a_BUFMODE, and only otherwise read(2) it */
3008 mbstate_t ps[2];
3009 char cbuf_base[MB_LEN_MAX * 2], *cbuf, *cbufp;
3010 ssize_t rv;
3011 struct a_tty_bind_tree *tbtp;
3012 wchar_t wc;
3013 enum a_tty_bind_flags tbf;
3014 enum {a_NONE, a_WAS_HERE = 1<<0, a_BUFMODE = 1<<1, a_MAYBEFUN = 1<<2,
3015 a_TIMEOUT = 1<<3, a_TIMEOUT_EXPIRED = 1<<4,
3016 a_TIMEOUT_MASK = a_TIMEOUT | a_TIMEOUT_EXPIRED,
3017 a_READ_LOOP_MASK = ~(a_WAS_HERE | a_MAYBEFUN | a_TIMEOUT_MASK)
3018 } flags;
3019 NYD_ENTER;
3021 n_UNINIT(rv, 0);
3022 # ifdef HAVE_KEY_BINDINGS
3023 assert(tlp->tl_bind_takeover == '\0');
3024 # endif
3025 jrestart:
3026 memset(ps, 0, sizeof ps);
3027 flags = a_NONE;
3028 tlp->tl_vi_flags |= a_TTY_VF_REFRESH | a_TTY_VF_SYNC;
3030 jinput_loop:
3031 for(;;){
3032 if(len != 0)
3033 flags |= a_BUFMODE;
3035 /* Ensure we have valid pointers, and room for grow */
3036 a_tty_check_grow(tlp, ((flags & a_BUFMODE) ? (ui32_t)len : 1)
3037 n_MEMORY_DEBUG_ARGSCALL);
3039 /* Handle visual state flags, except in buffer mode */
3040 if(!(flags & a_BUFMODE) && (tlp->tl_vi_flags & a_TTY_VF_ALL_MASK))
3041 if(!a_tty_vi_refresh(tlp)){
3042 rv = -1;
3043 goto jleave;
3046 /* Ready for messing around.
3047 * Normal read(2)? Else buffer mode: speed this one up */
3048 if(!(flags & a_BUFMODE)){
3049 cbufp =
3050 cbuf = cbuf_base;
3051 }else{
3052 assert(tlp->tl_defc.l > 0 && tlp->tl_defc.s != NULL);
3053 assert(tlp->tl_defc.l >= len);
3054 cbufp =
3055 cbuf = tlp->tl_defc.s + (tlp->tl_defc.l - len);
3056 cbufp += len;
3059 /* Read in the next complete multibyte character */
3060 /* C99 */{
3061 # ifdef HAVE_KEY_BINDINGS
3062 struct a_tty_bind_tree *xtbtp;
3063 struct inseq{
3064 struct inseq *last;
3065 struct inseq *next;
3066 struct a_tty_bind_tree *tbtp;
3067 } *isp_head, *isp;
3069 isp_head = isp = NULL;
3070 # endif
3072 for(flags &= a_READ_LOOP_MASK;;){
3073 # ifdef HAVE_KEY_BINDINGS
3074 if(!(flags & a_BUFMODE) && tlp->tl_bind_takeover != '\0'){
3075 wc = tlp->tl_bind_takeover;
3076 tlp->tl_bind_takeover = '\0';
3077 }else
3078 # endif
3080 if(!(flags & a_BUFMODE)){
3081 /* Let me at least once dream of iomon(itor), timer with
3082 * one-shot, enwrapped with key_event and key_sequence_event,
3083 * all driven by an event_loop */
3084 /* TODO v15 Until we have SysV signal handling all through we
3085 * TODO need to temporarily adjust our BSD signal handler with
3086 * TODO a SysV one, here */
3087 n_sighdl_t otstp, ottin, ottou;
3089 otstp = n_signal(SIGTSTP, &a_tty_signal);
3090 ottin = n_signal(SIGTTIN, &a_tty_signal);
3091 ottou = n_signal(SIGTTOU, &a_tty_signal);
3092 # ifdef HAVE_KEY_BINDINGS
3093 flags &= ~a_TIMEOUT_MASK;
3094 if(isp != NULL && (tbtp = isp->tbtp)->tbt_isseq &&
3095 !tbtp->tbt_isseq_trail){
3096 a_tty_term_rawmode_timeout(tlp, TRU1);
3097 flags |= a_TIMEOUT;
3099 # endif
3101 while((rv = read(STDIN_FILENO, cbufp, 1)) < 1){
3102 if(rv == -1){
3103 if(n_err_no == n_ERR_INTR){
3104 if((tlp->tl_vi_flags & a_TTY_VF_MOD_DIRTY) &&
3105 !a_tty_vi_refresh(tlp))
3106 break;
3107 continue;
3109 break;
3112 # ifdef HAVE_KEY_BINDINGS
3113 /* Timeout expiration */
3114 if(rv == 0){
3115 assert(flags & a_TIMEOUT);
3116 assert(isp != NULL);
3117 a_tty_term_rawmode_timeout(tlp, FAL0);
3119 /* Something "atomic" broke. Maybe the current one can
3120 * also be terminated already, by itself? xxx really? */
3121 if((tbtp = isp->tbtp)->tbt_bind != NULL){
3122 tlp->tl_bind_takeover = wc;
3123 goto jhave_bind;
3126 /* Or, maybe there is a second path without a timeout;
3127 * this should be covered by .tbt_isseq_trail, but then
3128 * again a single-layer implementation cannot "know" */
3129 for(xtbtp = tbtp; (xtbtp = xtbtp->tbt_sibling) != NULL;)
3130 if(xtbtp->tbt_char == tbtp->tbt_char){
3131 assert(!xtbtp->tbt_isseq);
3132 break;
3134 /* Lay down on read(2)? */
3135 if(xtbtp != NULL)
3136 continue;
3137 goto jtake_over;
3139 # endif /* HAVE_KEY_BINDINGS */
3142 # ifdef HAVE_KEY_BINDINGS
3143 if(flags & a_TIMEOUT)
3144 a_tty_term_rawmode_timeout(tlp, FAL0);
3145 # endif
3146 safe_signal(SIGTSTP, otstp);
3147 safe_signal(SIGTTIN, ottin);
3148 safe_signal(SIGTTOU, ottou);
3149 if(rv < 0)
3150 goto jleave;
3152 ++cbufp;
3155 rv = (ssize_t)mbrtowc(&wc, cbuf, PTR2SIZE(cbufp - cbuf), &ps[0]);
3156 if(rv <= 0){
3157 /* Any error during buffer mode can only result in a hard
3158 * reset; Otherwise, if it's a hard error, or if too many
3159 * redundant shift sequences overflow our buffer: perform
3160 * hard reset */
3161 if((flags & a_BUFMODE) || rv == -1 ||
3162 sizeof cbuf_base == PTR2SIZE(cbufp - cbuf)){
3163 a_tty_fun(tlp, a_TTY_BIND_FUN_FULLRESET, &len);
3164 goto jrestart;
3166 /* Otherwise, due to the way we deal with the buffer, we need
3167 * to restore the mbstate_t from before this conversion */
3168 ps[0] = ps[1];
3169 continue;
3171 cbufp = cbuf;
3172 ps[1] = ps[0];
3175 /* Normal read(2)ing is subject to detection of key-bindings */
3176 # ifdef HAVE_KEY_BINDINGS
3177 if(!(flags & a_BUFMODE)){
3178 /* Check for special bypass functions before we try to embed
3179 * this character into the tree */
3180 if(n_uasciichar(wc)){
3181 char c;
3182 char const *cp;
3184 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_prompt_char)[0];
3185 *cp != '\0'; ++cp){
3186 if(c == *cp){
3187 wc = a_tty_vinuni(tlp);
3188 break;
3191 if(wc == '\0'){
3192 tlp->tl_vi_flags |= a_TTY_VF_BELL;
3193 goto jinput_loop;
3196 if(n_uasciichar(wc))
3197 flags |= a_MAYBEFUN;
3198 else
3199 flags &= ~a_MAYBEFUN;
3201 /* Search for this character in the bind tree */
3202 tbtp = (isp != NULL) ? isp->tbtp->tbt_childs
3203 : (*tlp->tl_bind_tree_hmap)[wc % HSHSIZE];
3204 for(; tbtp != NULL; tbtp = tbtp->tbt_sibling){
3205 if(tbtp->tbt_char == wc){
3206 struct inseq *nisp;
3208 /* If this one cannot continue we're likely finished! */
3209 if(tbtp->tbt_childs == NULL){
3210 assert(tbtp->tbt_bind != NULL);
3211 tbf = tbtp->tbt_bind->tbc_flags;
3212 goto jmle_fun;
3215 /* This needs to read more characters */
3216 nisp = n_autorec_alloc(sizeof *nisp);
3217 if((nisp->last = isp) == NULL)
3218 isp_head = nisp;
3219 else
3220 isp->next = nisp;
3221 nisp->next = NULL;
3222 nisp->tbtp = tbtp;
3223 isp = nisp;
3224 flags &= ~a_WAS_HERE;
3225 break;
3228 if(tbtp != NULL)
3229 continue;
3231 /* Was there a binding active, but couldn't be continued? */
3232 if(isp != NULL){
3233 /* A binding had a timeout, it didn't expire, but we saw
3234 * something non-expected. Something "atomic" broke.
3235 * Maybe there is a second path without a timeout, that
3236 * continues like we've seen it. I.e., it may just have been
3237 * the user, typing too fast. We definitely want to allow
3238 * bindings like \e,d etc. to succeed: users are so used to
3239 * them that a timeout cannot be the mechanism to catch up!
3240 * A single-layer implementation cannot "know" */
3241 if((tbtp = isp->tbtp)->tbt_isseq && (isp->last == NULL ||
3242 !(xtbtp = isp->last->tbtp)->tbt_isseq ||
3243 xtbtp->tbt_isseq_trail)){
3244 for(xtbtp = (tbtp = isp->tbtp);
3245 (xtbtp = xtbtp->tbt_sibling) != NULL;)
3246 if(xtbtp->tbt_char == tbtp->tbt_char){
3247 assert(!xtbtp->tbt_isseq);
3248 break;
3250 if(xtbtp != NULL){
3251 isp->tbtp = xtbtp;
3252 tlp->tl_bind_takeover = wc;
3253 continue;
3257 /* Check for CANCEL shortcut now */
3258 if(flags & a_MAYBEFUN){
3259 char c;
3260 char const *cp;
3262 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_cancel)[0];
3263 *cp != '\0'; ++cp)
3264 if(c == *cp){
3265 tbf = a_TTY_BIND_FUN_INTERNAL |a_TTY_BIND_FUN_CANCEL;
3266 goto jmle_fun;
3270 /* So: maybe the current sequence can be terminated here? */
3271 if((tbtp = isp->tbtp)->tbt_bind != NULL){
3272 jhave_bind:
3273 tbf = tbtp->tbt_bind->tbc_flags;
3274 jmle_fun:
3275 if(tbf & a_TTY_BIND_FUN_INTERNAL){
3276 switch(a_tty_fun(tlp, tbf, &len)){
3277 case a_TTY_FUN_STATUS_OK:
3278 goto jinput_loop;
3279 case a_TTY_FUN_STATUS_COMMIT:
3280 goto jdone;
3281 case a_TTY_FUN_STATUS_RESTART:
3282 goto jrestart;
3283 case a_TTY_FUN_STATUS_END:
3284 rv = -1;
3285 goto jleave;
3287 assert(0);
3288 }else if(tbtp->tbt_bind->tbc_flags & a_TTY_BIND_NOCOMMIT){
3289 struct a_tty_bind_ctx *tbcp;
3291 tbcp = tbtp->tbt_bind;
3292 memcpy(tlp->tl_defc.s = n_autorec_alloc(
3293 (tlp->tl_defc.l = len = tbcp->tbc_exp_len) +1),
3294 tbcp->tbc_exp, tbcp->tbc_exp_len +1);
3295 goto jrestart;
3296 }else{
3297 cbufp = tbtp->tbt_bind->tbc_exp;
3298 goto jinject_input;
3303 /* Otherwise take over all chars "as is" */
3304 jtake_over:
3305 for(; isp_head != NULL; isp_head = isp_head->next)
3306 if(a_tty_kother(tlp, isp_head->tbtp->tbt_char)){
3307 /* FIXME */
3309 /* And the current one too */
3310 goto jkother;
3312 # endif /* HAVE_KEY_BINDINGS */
3314 if((flags & a_BUFMODE) && (len -= (size_t)rv) == 0){
3315 /* Buffer mode completed */
3316 tlp->tl_defc.s = NULL;
3317 tlp->tl_defc.l = 0;
3318 flags &= ~a_BUFMODE;
3320 break;
3323 # ifndef HAVE_KEY_BINDINGS
3324 /* Don't interpret control bytes during buffer mode.
3325 * Otherwise, if it's a control byte check whether it is a MLE
3326 * function. Remarks: initially a complete duplicate to be able to
3327 * switch(), later converted to simply iterate over (an #ifdef'd
3328 * subset of) the MLE base_tuple table in order to have "a SPOF" */
3329 if(cbuf == cbuf_base && n_uasciichar(wc) && cntrlchar((char)wc)){
3330 struct a_tty_bind_builtin_tuple const *tbbtp, *tbbtp_max;
3331 char c;
3333 c = (char)wc ^ 0x40;
3334 tbbtp = a_tty_bind_base_tuples;
3335 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_base_tuples)];
3336 jbuiltin_redo:
3337 for(; tbbtp < tbbtp_max; ++tbbtp){
3338 /* Assert default_tuple table is properly subset'ed */
3339 assert(tbbtp->tbdt_iskey);
3340 if(tbbtp->tbbt_ckey == c){
3341 if(tbbtp->tbbt_exp[0] == '\0'){
3342 tbf = a_TTY_BIND_FUN_EXPAND((ui8_t)tbbtp->tbbt_exp[1]);
3343 switch(a_tty_fun(tlp, tbf, &len)){
3344 case a_TTY_FUN_STATUS_OK:
3345 goto jinput_loop;
3346 case a_TTY_FUN_STATUS_COMMIT:
3347 goto jdone;
3348 case a_TTY_FUN_STATUS_RESTART:
3349 goto jrestart;
3350 case a_TTY_FUN_STATUS_END:
3351 rv = -1;
3352 goto jleave;
3354 assert(0);
3355 }else{
3356 cbufp = tbbtp->tbbt_exp;
3357 goto jinject_input;
3361 if(tbbtp ==
3362 &a_tty_bind_base_tuples[n_NELEM(a_tty_bind_base_tuples)]){
3363 tbbtp = a_tty_bind_default_tuples;
3364 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_default_tuples)];
3365 goto jbuiltin_redo;
3368 # endif /* !HAVE_KEY_BINDINGS */
3370 # ifdef HAVE_KEY_BINDINGS
3371 jkother:
3372 # endif
3373 if(a_tty_kother(tlp, wc)){
3374 /* Don't clear the history during buffer mode.. */
3375 # ifdef HAVE_HISTORY
3376 if(!(flags & a_BUFMODE) && cbuf == cbuf_base)
3377 tlp->tl_hist = NULL;
3378 # endif
3383 /* We have a completed input line, convert the struct cell data to its
3384 * plain character equivalent */
3385 jdone:
3386 rv = a_tty_cell2dat(tlp);
3387 jleave:
3388 putc('\n', n_tty_fp);
3389 fflush(n_tty_fp);
3390 NYD_LEAVE;
3391 return rv;
3393 jinject_input:{
3394 size_t i;
3396 hold_all_sigs(); /* XXX v15 drop */
3397 i = a_tty_cell2dat(tlp);
3398 n_go_input_inject(n_GO_INPUT_INJECT_NONE, tlp->tl_line.cbuf, i);
3399 i = strlen(cbufp) +1;
3400 if(i >= *tlp->tl_x_bufsize){
3401 *tlp->tl_x_buf = (n_realloc)(*tlp->tl_x_buf, i n_MEMORY_DEBUG_ARGSCALL);
3402 *tlp->tl_x_bufsize = i;
3404 memcpy(*tlp->tl_x_buf, cbufp, i);
3405 rele_all_sigs(); /* XXX v15 drop */
3406 if(histok_or_null != NULL)
3407 *histok_or_null = FAL0;
3408 rv = (ssize_t)--i;
3410 goto jleave;
3413 # ifdef HAVE_KEY_BINDINGS
3414 static enum n_go_input_flags
3415 a_tty_bind_ctx_find(char const *name){
3416 enum n_go_input_flags rv;
3417 struct a_tty_bind_ctx_map const *tbcmp;
3418 NYD2_ENTER;
3420 tbcmp = a_tty_bind_ctx_maps;
3421 do if(!asccasecmp(tbcmp->tbcm_name, name)){
3422 rv = tbcmp->tbcm_ctx;
3423 goto jleave;
3424 }while(PTRCMP(++tbcmp, <,
3425 &a_tty_bind_ctx_maps[n_NELEM(a_tty_bind_ctx_maps)]));
3427 rv = (enum n_go_input_flags)-1;
3428 jleave:
3429 NYD2_LEAVE;
3430 return rv;
3433 static bool_t
3434 a_tty_bind_create(struct a_tty_bind_parse_ctx *tbpcp, bool_t replace){
3435 struct a_tty_bind_ctx *tbcp;
3436 bool_t rv;
3437 NYD2_ENTER;
3439 rv = FAL0;
3441 if(!a_tty_bind_parse(TRU1, tbpcp))
3442 goto jleave;
3444 /* Since we use a single buffer for it all, need to replace as such */
3445 if(tbpcp->tbpc_tbcp != NULL){
3446 if(!replace)
3447 goto jleave;
3448 a_tty_bind_del(tbpcp);
3449 }else if(a_tty.tg_bind_cnt == UI32_MAX){
3450 n_err(_("`bind': maximum number of bindings already established\n"));
3451 goto jleave;
3454 /* C99 */{
3455 size_t i, j;
3457 tbcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_tty_bind_ctx, tbc__buf) +
3458 tbpcp->tbpc_seq_len + tbpcp->tbpc_exp.l +
3459 n_MAX(sizeof(si32_t), sizeof(wc_t)) + tbpcp->tbpc_cnv_len +3);
3460 if(tbpcp->tbpc_ltbcp != NULL){
3461 tbcp->tbc_next = tbpcp->tbpc_ltbcp->tbc_next;
3462 tbpcp->tbpc_ltbcp->tbc_next = tbcp;
3463 }else{
3464 enum n_go_input_flags gif;
3466 gif = tbpcp->tbpc_flags & n__GO_INPUT_CTX_MASK;
3467 tbcp->tbc_next = a_tty.tg_bind[gif];
3468 a_tty.tg_bind[gif] = tbcp;
3470 memcpy(tbcp->tbc_seq = &tbcp->tbc__buf[0],
3471 tbpcp->tbpc_seq, i = (tbcp->tbc_seq_len = tbpcp->tbpc_seq_len) +1);
3472 memcpy(tbcp->tbc_exp = &tbcp->tbc__buf[i],
3473 tbpcp->tbpc_exp.s, j = (tbcp->tbc_exp_len = tbpcp->tbpc_exp.l) +1);
3474 i += j;
3475 i = (i + tbpcp->tbpc_cnv_align_mask) & ~tbpcp->tbpc_cnv_align_mask;
3476 memcpy(tbcp->tbc_cnv = &tbcp->tbc__buf[i],
3477 tbpcp->tbpc_cnv, (tbcp->tbc_cnv_len = tbpcp->tbpc_cnv_len) +1);
3478 tbcp->tbc_flags = tbpcp->tbpc_flags;
3481 /* Directly resolve any termcap(5) symbol if we are already setup */
3482 if((n_psonce & n_PSO_STARTED) &&
3483 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
3484 a_TTY_BIND_RESOLVE)
3485 a_tty_bind_resolve(tbcp);
3487 ++a_tty.tg_bind_cnt;
3488 /* If this binding is usable invalidate the key input lookup trees */
3489 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3490 a_tty.tg_bind_isdirty = TRU1;
3491 rv = TRU1;
3492 jleave:
3493 NYD2_LEAVE;
3494 return rv;
3497 static bool_t
3498 a_tty_bind_parse(bool_t isbindcmd, struct a_tty_bind_parse_ctx *tbpcp){
3499 enum{a_TRUE_RV = a_TTY__BIND_LAST<<1};
3501 struct n_visual_info_ctx vic;
3502 struct str shin_save, shin;
3503 struct n_string shou, *shoup;
3504 size_t i;
3505 struct kse{
3506 struct kse *next;
3507 char *seq_dat;
3508 wc_t *cnv_dat;
3509 ui32_t seq_len;
3510 ui32_t cnv_len; /* High bit set if a termap to be resolved */
3511 ui32_t calc_cnv_len; /* Ditto, but aligned etc. */
3512 ui8_t kse__dummy[4];
3513 } *head, *tail;
3514 ui32_t f;
3515 NYD2_ENTER;
3516 n_LCTA(UICMP(64, a_TRUE_RV, <, UI32_MAX),
3517 "Flag bits excess storage datatype");
3519 f = n_GO_INPUT_NONE;
3520 shoup = n_string_creat_auto(&shou);
3521 head = tail = NULL;
3523 /* Parse the key-sequence */
3524 for(shin.s = n_UNCONST(tbpcp->tbpc_in_seq), shin.l = UIZ_MAX;;){
3525 struct kse *ep;
3526 enum n_shexp_state shs;
3528 shin_save = shin;
3529 shs = n_shexp_parse_token((n_SHEXP_PARSE_TRUNC |
3530 n_SHEXP_PARSE_TRIM_SPACE | n_SHEXP_PARSE_IGNORE_EMPTY |
3531 n_SHEXP_PARSE_IFS_IS_COMMA), shoup, &shin, NULL);
3532 if(shs & n_SHEXP_STATE_ERR_UNICODE){
3533 f |= a_TTY_BIND_DEFUNCT;
3534 if(isbindcmd && (n_poption & n_PO_D_V))
3535 n_err(_("`%s': \\uNICODE not available in locale: %s\n"),
3536 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3538 if((shs & n_SHEXP_STATE_ERR_MASK) & ~n_SHEXP_STATE_ERR_UNICODE){
3539 n_err(_("`%s': failed to parse key-sequence: %s\n"),
3540 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3541 goto jleave;
3543 if((shs & (n_SHEXP_STATE_OUTPUT | n_SHEXP_STATE_STOP)) ==
3544 n_SHEXP_STATE_STOP)
3545 break;
3547 ep = n_autorec_alloc(sizeof *ep);
3548 if(head == NULL)
3549 head = ep;
3550 else
3551 tail->next = ep;
3552 tail = ep;
3553 ep->next = NULL;
3554 if(!(shs & n_SHEXP_STATE_ERR_UNICODE)){
3555 i = strlen(ep->seq_dat = n_shexp_quote_cp(n_string_cp(shoup), TRU1));
3556 if(i >= SI32_MAX - 1)
3557 goto jelen;
3558 ep->seq_len = (ui32_t)i;
3559 }else{
3560 /* Otherwise use the original buffer, _we_ can only quote it the wrong
3561 * way (e.g., an initial $'\u3a' becomes '\u3a'), _then_ */
3562 if((i = shin_save.l - shin.l) >= SI32_MAX - 1)
3563 goto jelen;
3564 ep->seq_len = (ui32_t)i;
3565 ep->seq_dat = savestrbuf(shin_save.s, i);
3568 memset(&vic, 0, sizeof vic);
3569 vic.vic_inlen = shoup->s_len;
3570 vic.vic_indat = shoup->s_dat;
3571 if(!n_visual_info(&vic,
3572 n_VISUAL_INFO_WOUT_CREATE | n_VISUAL_INFO_WOUT_SALLOC)){
3573 n_err(_("`%s': key-sequence seems to contain invalid "
3574 "characters: %s: %s\n"),
3575 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
3576 f |= a_TTY_BIND_DEFUNCT;
3577 goto jleave;
3578 }else if(vic.vic_woulen == 0 ||
3579 vic.vic_woulen >= (SI32_MAX - 2) / sizeof(wc_t)){
3580 jelen:
3581 n_err(_("`%s': length of key-sequence unsupported: %s: %s\n"),
3582 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
3583 f |= a_TTY_BIND_DEFUNCT;
3584 goto jleave;
3586 ep->cnv_dat = vic.vic_woudat;
3587 ep->cnv_len = (ui32_t)vic.vic_woulen;
3589 /* A termcap(5)/terminfo(5) identifier? */
3590 if(ep->cnv_len > 1 && ep->cnv_dat[0] == ':'){
3591 i = --ep->cnv_len, ++ep->cnv_dat;
3592 # if 0 /* ndef HAVE_TERMCAP xxx User can, via *termcap*! */
3593 if(n_poption & n_PO_D_V)
3594 n_err(_("`%s': no termcap(5)/terminfo(5) support: %s: %s\n"),
3595 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3596 f |= a_TTY_BIND_DEFUNCT;
3597 # endif
3598 if(i > a_TTY_BIND_CAPNAME_MAX){
3599 n_err(_("`%s': termcap(5)/terminfo(5) name too long: %s: %s\n"),
3600 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3601 f |= a_TTY_BIND_DEFUNCT;
3603 while(i > 0)
3604 /* (We store it as char[]) */
3605 if((ui32_t)ep->cnv_dat[--i] & ~0x7Fu){
3606 n_err(_("`%s': invalid termcap(5)/terminfo(5) name content: "
3607 "%s: %s\n"),
3608 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3609 f |= a_TTY_BIND_DEFUNCT;
3610 break;
3612 ep->cnv_len |= SI32_MIN; /* Needs resolve */
3613 f |= a_TTY_BIND_RESOLVE;
3616 if(shs & n_SHEXP_STATE_STOP)
3617 break;
3620 if(head == NULL){
3621 jeempty:
3622 n_err(_("`%s': effectively empty key-sequence: %s\n"),
3623 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3624 goto jleave;
3627 if(isbindcmd) /* (Or always, just "1st time init") */
3628 tbpcp->tbpc_cnv_align_mask = n_MAX(sizeof(si32_t), sizeof(wc_t)) - 1;
3630 /* C99 */{
3631 struct a_tty_bind_ctx *ltbcp, *tbcp;
3632 char *cpbase, *cp, *cnv;
3633 size_t sl, cl;
3635 /* Unite the parsed sequence(s) into single string representations */
3636 for(sl = cl = 0, tail = head; tail != NULL; tail = tail->next){
3637 sl += tail->seq_len + 1;
3639 if(!isbindcmd)
3640 continue;
3642 /* Preserve room for terminal capabilities to be resolved.
3643 * Above we have ensured the buffer will fit in these calculations */
3644 if((i = tail->cnv_len) & SI32_MIN){
3645 /* For now
3646 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[]+NUL;}
3647 * later
3648 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3649 n_LCTAV(n_ISPOW2(a_TTY_BIND_CAPEXP_ROUNDUP));
3650 n_LCTA(a_TTY_BIND_CAPEXP_ROUNDUP >= sizeof(wc_t),
3651 "Aligning on this constant does not properly align wc_t");
3652 i &= SI32_MAX;
3653 i *= sizeof(wc_t);
3654 i += sizeof(si32_t);
3655 if(i < a_TTY_BIND_CAPEXP_ROUNDUP)
3656 i = (i + (a_TTY_BIND_CAPEXP_ROUNDUP - 1)) &
3657 ~(a_TTY_BIND_CAPEXP_ROUNDUP - 1);
3658 }else
3659 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3660 i *= sizeof(wc_t);
3661 i += sizeof(si32_t) + sizeof(wc_t); /* (buf_len_iscap, NUL) */
3662 cl += i;
3663 if(tail->cnv_len & SI32_MIN){
3664 tail->cnv_len &= SI32_MAX;
3665 i |= SI32_MIN;
3667 tail->calc_cnv_len = (ui32_t)i;
3669 --sl;
3671 tbpcp->tbpc_seq_len = sl;
3672 tbpcp->tbpc_cnv_len = cl;
3673 /* C99 */{
3674 size_t j;
3676 j = i = sl + 1; /* Room for comma separator */
3677 if(isbindcmd){
3678 i = (i + tbpcp->tbpc_cnv_align_mask) & ~tbpcp->tbpc_cnv_align_mask;
3679 j = i;
3680 i += cl;
3682 tbpcp->tbpc_seq = cp = cpbase = n_autorec_alloc(i);
3683 tbpcp->tbpc_cnv = cnv = &cpbase[j];
3686 for(tail = head; tail != NULL; tail = tail->next){
3687 memcpy(cp, tail->seq_dat, tail->seq_len);
3688 cp += tail->seq_len;
3689 *cp++ = ',';
3691 if(isbindcmd){
3692 char * const save_cnv = cnv;
3694 n_UNALIGN(si32_t*,cnv)[0] = (si32_t)(i = tail->calc_cnv_len);
3695 cnv += sizeof(si32_t);
3696 if(i & SI32_MIN){
3697 /* For now
3698 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];}
3699 * later
3700 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[];} */
3701 n_UNALIGN(si32_t*,cnv)[0] = tail->cnv_len;
3702 cnv += sizeof(si32_t);
3704 i = tail->cnv_len * sizeof(wc_t);
3705 memcpy(cnv, tail->cnv_dat, i);
3706 cnv += i;
3707 *n_UNALIGN(wc_t*,cnv) = '\0';
3709 cnv = save_cnv + (tail->calc_cnv_len & SI32_MAX);
3712 *--cp = '\0';
3714 /* Search for a yet existing identical mapping */
3715 /* C99 */{
3716 enum n_go_input_flags gif;
3718 gif = tbpcp->tbpc_flags & n__GO_INPUT_CTX_MASK;
3720 for(ltbcp = NULL, tbcp = a_tty.tg_bind[gif]; tbcp != NULL;
3721 ltbcp = tbcp, tbcp = tbcp->tbc_next)
3722 if(tbcp->tbc_seq_len == sl && !memcmp(tbcp->tbc_seq, cpbase, sl)){
3723 tbpcp->tbpc_tbcp = tbcp;
3724 break;
3727 tbpcp->tbpc_ltbcp = ltbcp;
3728 tbpcp->tbpc_flags |= (f & a_TTY__BIND_MASK);
3731 /* Create single string expansion if so desired */
3732 if(isbindcmd){
3733 char *exp;
3735 exp = tbpcp->tbpc_exp.s;
3737 i = tbpcp->tbpc_exp.l;
3738 if(i > 0 && exp[i - 1] == '@'){
3739 while(--i > 0){
3740 if(!blankspacechar(exp[i - 1]))
3741 break;
3743 if(i == 0)
3744 goto jeempty;
3746 exp[tbpcp->tbpc_exp.l = i] = '\0';
3747 tbpcp->tbpc_flags |= a_TTY_BIND_NOCOMMIT;
3750 /* Reverse solidus cannot be placed last in expansion to avoid (at the
3751 * time of this writing) possible problems with newline escaping.
3752 * Don't care about (un)even number thereof */
3753 if(i > 0 && exp[i - 1] == '\\'){
3754 n_err(_("`%s': reverse solidus cannot be last in expansion: %s\n"),
3755 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3756 goto jleave;
3759 /* It may map to an internal MLE command! */
3760 for(i = 0; i < n_NELEM(a_tty_bind_fun_names); ++i)
3761 if(!asccasecmp(exp, a_tty_bind_fun_names[i])){
3762 tbpcp->tbpc_flags |= a_TTY_BIND_FUN_EXPAND(i) |
3763 a_TTY_BIND_FUN_INTERNAL |
3764 (head->next == NULL ? a_TTY_BIND_MLE1CNTRL : 0);
3765 if((n_poption & n_PO_D_V) &&
3766 (tbpcp->tbpc_flags & a_TTY_BIND_NOCOMMIT))
3767 n_err(_("`%s': MLE commands can't be made editable via @: %s\n"),
3768 tbpcp->tbpc_cmd, exp);
3769 tbpcp->tbpc_flags &= ~a_TTY_BIND_NOCOMMIT;
3770 break;
3774 f |= a_TRUE_RV; /* TODO because we only now true and false; DEFUNCT.. */
3775 jleave:
3776 n_string_gut(shoup);
3777 NYD2_LEAVE;
3778 return (f & a_TRUE_RV) != 0;
3781 static void
3782 a_tty_bind_resolve(struct a_tty_bind_ctx *tbcp){
3783 char capname[a_TTY_BIND_CAPNAME_MAX +1];
3784 struct n_termcap_value tv;
3785 size_t len;
3786 bool_t isfirst; /* TODO For now: first char must be control! */
3787 char *cp, *next;
3788 NYD2_ENTER;
3790 n_UNINIT(next, NULL);
3791 for(cp = tbcp->tbc_cnv, isfirst = TRU1, len = tbcp->tbc_cnv_len;
3792 len > 0; isfirst = FAL0, cp = next){
3793 /* C99 */{
3794 si32_t i, j;
3796 i = n_UNALIGN(si32_t*,cp)[0];
3797 j = i & SI32_MAX;
3798 next = &cp[j];
3799 len -= j;
3800 if(i == j)
3801 continue;
3803 /* struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];} */
3804 cp += sizeof(si32_t);
3805 i = n_UNALIGN(si32_t*,cp)[0];
3806 cp += sizeof(si32_t);
3807 for(j = 0; j < i; ++j)
3808 capname[j] = n_UNALIGN(wc_t*,cp)[j];
3809 capname[j] = '\0';
3812 /* Use generic lookup mechanism if not a known query */
3813 /* C99 */{
3814 si32_t tq;
3816 tq = n_termcap_query_for_name(capname, n_TERMCAP_CAPTYPE_STRING);
3817 if(tq == -1){
3818 tv.tv_data.tvd_string = capname;
3819 tq = n__TERMCAP_QUERY_MAX1;
3822 if(tq < 0 || !n_termcap_query(tq, &tv)){
3823 if(n_poption & n_PO_D_V)
3824 n_err(_("`bind': unknown or unsupported capability: %s: %s\n"),
3825 capname, tbcp->tbc_seq);
3826 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3827 break;
3831 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3832 /* C99 */{
3833 size_t i;
3835 i = strlen(tv.tv_data.tvd_string);
3836 if(/*i > SI32_MAX ||*/ i >= PTR2SIZE(next - cp)){
3837 if(n_poption & n_PO_D_V)
3838 n_err(_("`bind': capability expansion too long: %s: %s\n"),
3839 capname, tbcp->tbc_seq);
3840 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3841 break;
3842 }else if(i == 0){
3843 if(n_poption & n_PO_D_V)
3844 n_err(_("`bind': empty capability expansion: %s: %s\n"),
3845 capname, tbcp->tbc_seq);
3846 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3847 break;
3848 }else if(isfirst && !cntrlchar(*tv.tv_data.tvd_string)){
3849 if(n_poption & n_PO_D_V)
3850 n_err(_("`bind': capability expansion does not start with "
3851 "control: %s: %s\n"), capname, tbcp->tbc_seq);
3852 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3853 break;
3855 n_UNALIGN(si32_t*,cp)[-1] = (si32_t)i;
3856 memcpy(cp, tv.tv_data.tvd_string, i);
3857 cp[i] = '\0';
3860 NYD2_LEAVE;
3863 static void
3864 a_tty_bind_del(struct a_tty_bind_parse_ctx *tbpcp){
3865 struct a_tty_bind_ctx *ltbcp, *tbcp;
3866 NYD2_ENTER;
3868 tbcp = tbpcp->tbpc_tbcp;
3870 if((ltbcp = tbpcp->tbpc_ltbcp) != NULL)
3871 ltbcp->tbc_next = tbcp->tbc_next;
3872 else
3873 a_tty.tg_bind[tbpcp->tbpc_flags & n__GO_INPUT_CTX_MASK] = tbcp->tbc_next;
3874 n_free(tbcp);
3876 --a_tty.tg_bind_cnt;
3877 a_tty.tg_bind_isdirty = TRU1;
3878 NYD2_LEAVE;
3881 static void
3882 a_tty_bind_tree_build(void){
3883 size_t i;
3884 NYD2_ENTER;
3886 for(i = 0; i < n__GO_INPUT_CTX_MAX1; ++i){
3887 struct a_tty_bind_ctx *tbcp;
3888 n_LCTAV(n_GO_INPUT_CTX_BASE == 0);
3890 /* Somewhat wasteful, but easier to handle: simply clone the entire
3891 * primary key onto the secondary one, then only modify it */
3892 for(tbcp = a_tty.tg_bind[n_GO_INPUT_CTX_BASE]; tbcp != NULL;
3893 tbcp = tbcp->tbc_next)
3894 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3895 a_tty__bind_tree_add(n_GO_INPUT_CTX_BASE, &a_tty.tg_bind_tree[i][0],
3896 tbcp);
3898 if(i != n_GO_INPUT_CTX_BASE)
3899 for(tbcp = a_tty.tg_bind[i]; tbcp != NULL; tbcp = tbcp->tbc_next)
3900 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3901 a_tty__bind_tree_add(i, &a_tty.tg_bind_tree[i][0], tbcp);
3904 a_tty.tg_bind_isbuild = TRU1;
3905 NYD2_LEAVE;
3908 static void
3909 a_tty_bind_tree_teardown(void){
3910 size_t i, j;
3911 NYD2_ENTER;
3913 memset(&a_tty.tg_bind_shcut_cancel[0], 0,
3914 sizeof(a_tty.tg_bind_shcut_cancel));
3915 memset(&a_tty.tg_bind_shcut_prompt_char[0], 0,
3916 sizeof(a_tty.tg_bind_shcut_prompt_char));
3918 for(i = 0; i < n__GO_INPUT_CTX_MAX1; ++i)
3919 for(j = 0; j < HSHSIZE; ++j)
3920 a_tty__bind_tree_free(a_tty.tg_bind_tree[i][j]);
3921 memset(&a_tty.tg_bind_tree[0], 0, sizeof(a_tty.tg_bind_tree));
3923 a_tty.tg_bind_isdirty = a_tty.tg_bind_isbuild = FAL0;
3924 NYD2_LEAVE;
3927 static void
3928 a_tty__bind_tree_add(ui32_t hmap_idx, struct a_tty_bind_tree *store[HSHSIZE],
3929 struct a_tty_bind_ctx *tbcp){
3930 ui32_t cnvlen;
3931 char const *cnvdat;
3932 struct a_tty_bind_tree *ntbtp;
3933 NYD2_ENTER;
3934 n_UNUSED(hmap_idx);
3936 ntbtp = NULL;
3938 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len; cnvlen > 0;){
3939 union {wchar_t const *wp; char const *cp;} u;
3940 si32_t entlen;
3942 /* {si32_t buf_len_iscap;} */
3943 entlen = *n_UNALIGN(si32_t const*,cnvdat);
3945 if(entlen & SI32_MIN){
3946 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;}
3947 * Note that empty capabilities result in DEFUNCT */
3948 for(u.cp = (char const*)&n_UNALIGN(si32_t const*,cnvdat)[2];
3949 *u.cp != '\0'; ++u.cp)
3950 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.cp, TRU1);
3951 assert(ntbtp != NULL);
3952 ntbtp->tbt_isseq_trail = TRU1;
3953 entlen &= SI32_MAX;
3954 }else{
3955 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3956 bool_t isseq;
3958 u.wp = (wchar_t const*)&n_UNALIGN(si32_t const*,cnvdat)[1];
3960 /* May be a special shortcut function? */
3961 if(ntbtp == NULL && (tbcp->tbc_flags & a_TTY_BIND_MLE1CNTRL)){
3962 char *cp;
3963 ui32_t ctx, fun;
3965 ctx = tbcp->tbc_flags & n__GO_INPUT_CTX_MASK;
3966 fun = tbcp->tbc_flags & a_TTY__BIND_FUN_MASK;
3968 if(fun == a_TTY_BIND_FUN_CANCEL){
3969 for(cp = &a_tty.tg_bind_shcut_cancel[ctx][0];
3970 PTRCMP(cp, <, &a_tty.tg_bind_shcut_cancel[ctx]
3971 [n_NELEM(a_tty.tg_bind_shcut_cancel[ctx]) - 1]); ++cp)
3972 if(*cp == '\0'){
3973 *cp = (char)*u.wp;
3974 break;
3976 }else if(fun == a_TTY_BIND_FUN_PROMPT_CHAR){
3977 for(cp = &a_tty.tg_bind_shcut_prompt_char[ctx][0];
3978 PTRCMP(cp, <, &a_tty.tg_bind_shcut_prompt_char[ctx]
3979 [n_NELEM(a_tty.tg_bind_shcut_prompt_char[ctx]) - 1]);
3980 ++cp)
3981 if(*cp == '\0'){
3982 *cp = (char)*u.wp;
3983 break;
3988 isseq = (u.wp[1] != '\0');
3989 for(; *u.wp != '\0'; ++u.wp)
3990 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.wp, isseq);
3991 if(isseq){
3992 assert(ntbtp != NULL);
3993 ntbtp->tbt_isseq_trail = TRU1;
3997 cnvlen -= entlen;
3998 cnvdat += entlen;
4001 /* Should have been rendered defunctional at first instead */
4002 assert(ntbtp != NULL);
4003 ntbtp->tbt_bind = tbcp;
4004 NYD2_LEAVE;
4007 static struct a_tty_bind_tree *
4008 a_tty__bind_tree_add_wc(struct a_tty_bind_tree **treep,
4009 struct a_tty_bind_tree *parentp, wchar_t wc, bool_t isseq){
4010 struct a_tty_bind_tree *tbtp, *xtbtp;
4011 NYD2_ENTER;
4013 if(parentp == NULL){
4014 treep += wc % HSHSIZE;
4016 /* Having no parent also means that the tree slot is possibly empty */
4017 for(tbtp = *treep; tbtp != NULL;
4018 parentp = tbtp, tbtp = tbtp->tbt_sibling){
4019 if(tbtp->tbt_char != wc)
4020 continue;
4021 if(tbtp->tbt_isseq == isseq)
4022 goto jleave;
4023 /* isseq MUST be linked before !isseq, so record this "parent"
4024 * sibling, but continue searching for now.
4025 * Otherwise it is impossible that we'll find what we look for */
4026 if(isseq){
4027 #ifdef HAVE_DEBUG
4028 while((tbtp = tbtp->tbt_sibling) != NULL)
4029 assert(tbtp->tbt_char != wc);
4030 #endif
4031 break;
4035 tbtp = n_alloc(sizeof *tbtp);
4036 memset(tbtp, 0, sizeof *tbtp);
4037 tbtp->tbt_char = wc;
4038 tbtp->tbt_isseq = isseq;
4040 if(parentp == NULL){
4041 tbtp->tbt_sibling = *treep;
4042 *treep = tbtp;
4043 }else{
4044 tbtp->tbt_sibling = parentp->tbt_sibling;
4045 parentp->tbt_sibling = tbtp;
4047 }else{
4048 if((tbtp = *(treep = &parentp->tbt_childs)) != NULL){
4049 for(;; tbtp = xtbtp){
4050 if(tbtp->tbt_char == wc){
4051 if(tbtp->tbt_isseq == isseq)
4052 goto jleave;
4053 /* isseq MUST be linked before, so it is impossible that we'll
4054 * find what we look for */
4055 if(isseq){
4056 #ifdef HAVE_DEBUG
4057 while((tbtp = tbtp->tbt_sibling) != NULL)
4058 assert(tbtp->tbt_char != wc);
4059 #endif
4060 tbtp = NULL;
4061 break;
4065 if((xtbtp = tbtp->tbt_sibling) == NULL){
4066 treep = &tbtp->tbt_sibling;
4067 break;
4072 xtbtp = n_alloc(sizeof *xtbtp);
4073 memset(xtbtp, 0, sizeof *xtbtp);
4074 xtbtp->tbt_parent = parentp;
4075 xtbtp->tbt_char = wc;
4076 xtbtp->tbt_isseq = isseq;
4077 tbtp = xtbtp;
4078 *treep = tbtp;
4080 jleave:
4081 NYD2_LEAVE;
4082 return tbtp;
4085 static void
4086 a_tty__bind_tree_free(struct a_tty_bind_tree *tbtp){
4087 NYD2_ENTER;
4088 while(tbtp != NULL){
4089 struct a_tty_bind_tree *tmp;
4091 if((tmp = tbtp->tbt_childs) != NULL)
4092 a_tty__bind_tree_free(tmp);
4094 tmp = tbtp->tbt_sibling;
4095 n_free(tbtp);
4096 tbtp = tmp;
4098 NYD2_LEAVE;
4100 # endif /* HAVE_KEY_BINDINGS */
4102 FL void
4103 n_tty_init(void){
4104 NYD_ENTER;
4106 if(ok_blook(line_editor_disable))
4107 goto jleave;
4109 /* Load the history file */
4110 # ifdef HAVE_HISTORY
4111 a_tty_hist_load();
4112 # endif
4114 /* Force immediate resolve for anything which follows */
4115 n_psonce |= n_PSO_LINE_EDITOR_INIT;
4117 # ifdef HAVE_KEY_BINDINGS
4118 /* `bind's (and `unbind's) done from within resource files couldn't be
4119 * performed for real since our termcap driver wasn't yet loaded, and we
4120 * can't perform automatic init since the user may have disallowed so */
4121 /* C99 */{ /* TODO outsource into own file */
4122 struct a_tty_bind_ctx *tbcp;
4123 enum n_go_input_flags gif;
4125 for(gif = 0; gif < n__GO_INPUT_CTX_MAX1; ++gif)
4126 for(tbcp = a_tty.tg_bind[gif]; tbcp != NULL; tbcp = tbcp->tbc_next)
4127 if((tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
4128 a_TTY_BIND_RESOLVE)
4129 a_tty_bind_resolve(tbcp);
4132 /* And we want to (try to) install some default key bindings */
4133 if(!ok_blook(line_editor_no_defaults)){
4134 char buf[8];
4135 struct a_tty_bind_parse_ctx tbpc;
4136 struct a_tty_bind_builtin_tuple const *tbbtp, *tbbtp_max;
4137 ui32_t flags;
4139 buf[0] = '$', buf[1] = '\'', buf[2] = '\\', buf[3] = 'c',
4140 buf[5] = '\'', buf[6] = '\0';
4142 tbbtp = a_tty_bind_base_tuples;
4143 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_base_tuples)];
4144 flags = n_GO_INPUT_CTX_BASE;
4145 jbuiltin_redo:
4146 for(; tbbtp < tbbtp_max; ++tbbtp){
4147 memset(&tbpc, 0, sizeof tbpc);
4148 tbpc.tbpc_cmd = "bind";
4149 if(tbbtp->tbbt_iskey){
4150 buf[4] = tbbtp->tbbt_ckey;
4151 tbpc.tbpc_in_seq = buf;
4152 }else
4153 tbpc.tbpc_in_seq = savecatsep(":", '\0',
4154 n_termcap_name_of_query(tbbtp->tbbt_query));
4155 tbpc.tbpc_exp.s = n_UNCONST(tbbtp->tbbt_exp[0] == '\0'
4156 ? a_tty_bind_fun_names[(ui8_t)tbbtp->tbbt_exp[1]]
4157 : tbbtp->tbbt_exp);
4158 tbpc.tbpc_exp.l = strlen(tbpc.tbpc_exp.s);
4159 tbpc.tbpc_flags = flags;
4160 /* ..but don't want to overwrite any user settings */
4161 a_tty_bind_create(&tbpc, FAL0);
4163 if(flags == n_GO_INPUT_CTX_BASE){
4164 tbbtp = a_tty_bind_default_tuples;
4165 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_default_tuples)];
4166 flags = n_GO_INPUT_CTX_DEFAULT;
4167 goto jbuiltin_redo;
4170 # endif /* HAVE_KEY_BINDINGS */
4172 jleave:
4173 NYD_LEAVE;
4176 FL void
4177 n_tty_destroy(bool_t xit_fastpath){
4178 NYD_ENTER;
4180 if(!(n_psonce & n_PSO_LINE_EDITOR_INIT))
4181 goto jleave;
4183 /* Write the history file */
4184 # ifdef HAVE_HISTORY
4185 if(!xit_fastpath)
4186 a_tty_hist_save();
4187 # endif
4189 # if defined HAVE_KEY_BINDINGS && defined HAVE_DEBUG
4190 n_go_command(n_GO_INPUT_NONE, "unbind * *");
4191 # endif
4193 # ifdef HAVE_DEBUG
4194 memset(&a_tty, 0, sizeof a_tty);
4196 n_psonce &= ~n_PSO_LINE_EDITOR_INIT;
4197 # endif
4198 jleave:
4199 NYD_LEAVE;
4202 FL int
4203 (n_tty_readline)(enum n_go_input_flags gif, char const *prompt,
4204 char **linebuf, size_t *linesize, size_t n, bool_t *histok_or_null
4205 n_MEMORY_DEBUG_ARGS){
4206 struct a_tty_line tl;
4207 struct n_string xprompt;
4208 # ifdef HAVE_COLOUR
4209 char *posbuf, *pos;
4210 # endif
4211 ssize_t nn;
4212 NYD_ENTER;
4214 assert(!ok_blook(line_editor_disable));
4215 if(!(n_psonce & n_PSO_LINE_EDITOR_INIT))
4216 n_tty_init();
4217 assert(n_psonce & n_PSO_LINE_EDITOR_INIT);
4219 # ifdef HAVE_COLOUR
4220 n_colour_env_create(n_COLOUR_CTX_MLE, n_tty_fp, FAL0);
4222 /* .tl_pos_buf is a hack */
4223 posbuf = pos = NULL;
4225 if(n_COLOUR_IS_ACTIVE()){
4226 char const *ccol;
4227 struct n_colour_pen *ccp;
4228 struct str const *sp;
4230 if((ccp = n_colour_pen_create(n_COLOUR_ID_MLE_POSITION, NULL)) != NULL &&
4231 (sp = n_colour_pen_to_str(ccp)) != NULL){
4232 ccol = sp->s;
4233 if((sp = n_colour_reset_to_str()) != NULL){
4234 size_t l1, l2;
4236 l1 = strlen(ccol);
4237 l2 = strlen(sp->s);
4238 posbuf = n_autorec_alloc(l1 + 4 + l2 +1);
4239 memcpy(posbuf, ccol, l1);
4240 pos = &posbuf[l1];
4241 memcpy(&pos[4], sp->s, ++l2);
4246 if(posbuf == NULL){
4247 posbuf = pos = n_autorec_alloc(4 +1);
4248 pos[4] = '\0';
4250 # endif /* HAVE_COLOUR */
4252 memset(&tl, 0, sizeof tl);
4253 tl.tl_goinflags = gif;
4255 # ifdef HAVE_KEY_BINDINGS
4256 /* C99 */{
4257 char const *cp;
4259 if((cp = ok_vlook(bind_timeout)) != NULL){
4260 ui64_t uib;
4262 n_idec_ui64_cp(&uib, cp, 0, NULL);
4264 if(uib > 0 &&
4265 /* Convert to tenths of a second, unfortunately */
4266 (uib = (uib + 99) / 100) <= a_TTY_BIND_TIMEOUT_MAX)
4267 tl.tl_bind_timeout = (ui8_t)uib;
4268 else if(n_poption & n_PO_D_V)
4269 n_err(_("Ignoring invalid *bind-timeout*: %s\n"), cp);
4273 if(a_tty.tg_bind_isdirty)
4274 a_tty_bind_tree_teardown();
4275 if(a_tty.tg_bind_cnt > 0 && !a_tty.tg_bind_isbuild)
4276 a_tty_bind_tree_build();
4277 tl.tl_bind_tree_hmap = &a_tty.tg_bind_tree[gif & n__GO_INPUT_CTX_MASK];
4278 tl.tl_bind_shcut_cancel =
4279 &a_tty.tg_bind_shcut_cancel[gif & n__GO_INPUT_CTX_MASK];
4280 tl.tl_bind_shcut_prompt_char =
4281 &a_tty.tg_bind_shcut_prompt_char[gif & n__GO_INPUT_CTX_MASK];
4282 # endif /* HAVE_KEY_BINDINGS */
4284 # ifdef HAVE_COLOUR
4285 tl.tl_pos_buf = posbuf;
4286 tl.tl_pos = pos;
4287 # endif
4289 if(!(gif & n_GO_INPUT_PROMPT_NONE)){
4290 n_string_creat_auto(&xprompt);
4292 if((tl.tl_prompt_width = n_tty_create_prompt(&xprompt, prompt, gif)
4293 ) > 0){
4294 tl.tl_prompt = n_string_cp_const(&xprompt);
4295 tl.tl_prompt_length = (ui32_t)xprompt.s_len;
4299 tl.tl_line.cbuf = *linebuf;
4300 if(n != 0){
4301 tl.tl_defc.s = savestrbuf(*linebuf, n);
4302 tl.tl_defc.l = n;
4304 tl.tl_x_buf = linebuf;
4305 tl.tl_x_bufsize = linesize;
4307 a_tty.tg_line = &tl;
4308 a_tty_sigs_up();
4309 n_TERMCAP_RESUME(FAL0);
4310 a_tty_term_mode(TRU1);
4311 nn = a_tty_readline(&tl, n, histok_or_null n_MEMORY_DEBUG_ARGSCALL);
4312 n_COLOUR( n_colour_env_gut(); )
4313 a_tty_term_mode(FAL0);
4314 n_TERMCAP_SUSPEND(FAL0);
4315 a_tty_sigs_down();
4316 a_tty.tg_line = NULL;
4318 NYD_LEAVE;
4319 return (int)nn;
4322 FL void
4323 n_tty_addhist(char const *s, enum n_go_input_flags gif){
4324 NYD_ENTER;
4325 n_UNUSED(s);
4326 n_UNUSED(gif);
4328 # ifdef HAVE_HISTORY
4329 if(*s != '\0' && (n_psonce & n_PSO_LINE_EDITOR_INIT) &&
4330 a_tty.tg_hist_size_max > 0 &&
4331 (!(gif & n_GO_INPUT_HIST_GABBY) || ok_blook(history_gabby)) &&
4332 !ok_blook(line_editor_disable)){
4333 hold_all_sigs();
4334 a_tty_hist_add(s, gif);
4335 rele_all_sigs();
4337 # endif
4338 NYD_LEAVE;
4341 # ifdef HAVE_HISTORY
4342 FL int
4343 c_history(void *v){
4344 siz_t entry;
4345 struct a_tty_hist *thp;
4346 char **argv;
4347 NYD_ENTER;
4349 if(ok_blook(line_editor_disable)){
4350 n_err(_("history: *line-editor-disable* is set\n"));
4351 goto jerr;
4354 if(!(n_psonce & n_PSO_LINE_EDITOR_INIT)){
4355 n_tty_init();
4356 assert(n_psonce & n_PSO_LINE_EDITOR_INIT);
4359 if(*(argv = v) == NULL)
4360 goto jlist;
4361 if(argv[1] != NULL)
4362 goto jerr;
4363 if(!asccasecmp(*argv, "show"))
4364 goto jlist;
4365 if(!asccasecmp(*argv, "clear"))
4366 goto jclear;
4368 if(!asccasecmp(*argv, "load")){
4369 if(!a_tty_hist_load())
4370 v = NULL;
4371 goto jleave;
4373 if(!asccasecmp(*argv, "save")){
4374 if(!a_tty_hist_save())
4375 v = NULL;
4376 goto jleave;
4379 if((n_idec_siz_cp(&entry, *argv, 10, NULL
4380 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
4381 ) == n_IDEC_STATE_CONSUMED)
4382 goto jentry;
4383 jerr:
4384 n_err(_("Synopsis: history: %s\n"),
4385 /* Same string as in cmd-tab.h, still hoping...) */
4386 _("<show (default)|load|save|clear> or select history <NO>"));
4387 v = NULL;
4388 jleave:
4389 NYD_LEAVE;
4390 return (v == NULL ? !STOP : !OKAY); /* xxx 1:bad 0:good -- do some */
4392 jlist:{
4393 size_t no, l, b;
4394 FILE *fp;
4396 if(a_tty.tg_hist == NULL)
4397 goto jleave;
4399 if((fp = Ftmp(NULL, "hist", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
4400 n_perr(_("tmpfile"), 0);
4401 v = NULL;
4402 goto jleave;
4405 no = a_tty.tg_hist_size;
4406 l = b = 0;
4408 for(thp = a_tty.tg_hist; thp != NULL;
4409 --no, ++l, thp = thp->th_older){
4410 char c1, c2;
4412 b += thp->th_len;
4414 switch(thp->th_flags & a_TTY_HIST_CTX_MASK){
4415 default:
4416 case a_TTY_HIST_CTX_DEFAULT:
4417 c1 = 'd';
4418 break;
4419 case a_TTY_HIST_CTX_COMPOSE:
4420 c1 = 'c';
4421 break;
4423 c2 = (thp->th_flags & a_TTY_HIST_GABBY) ? '*' : ' ';
4425 if(n_poption & n_PO_D_V)
4426 fprintf(fp, "# Length +%" PRIu32 ", total %" PRIuZ "\n",
4427 thp->th_len, b);
4428 fprintf(fp, "%c%c%4" PRIuZ "\t%s\n", c1, c2, no, thp->th_dat);
4431 page_or_print(fp, l);
4432 Fclose(fp);
4434 goto jleave;
4436 jclear:
4437 while((thp = a_tty.tg_hist) != NULL){
4438 a_tty.tg_hist = thp->th_older;
4439 n_free(thp);
4441 a_tty.tg_hist_tail = NULL;
4442 a_tty.tg_hist_size = 0;
4443 goto jleave;
4445 jentry:{
4446 siz_t ep;
4448 ep = (entry < 0) ? -entry : entry;
4450 if(ep != 0 && UICMP(z, ep, <=, a_tty.tg_hist_size)){
4451 if(ep != entry)
4452 --ep;
4453 else
4454 ep = (siz_t)a_tty.tg_hist_size - ep;
4455 for(thp = a_tty.tg_hist;; thp = thp->th_older){
4456 assert(thp != NULL);
4457 if(ep-- == 0){
4458 n_go_input_inject((n_GO_INPUT_INJECT_COMMIT |
4459 n_GO_INPUT_INJECT_HISTORY), v = thp->th_dat, thp->th_len);
4460 break;
4463 }else{
4464 n_err(_("`history': no such entry: %" PRIdZ "\n"), entry);
4465 v = NULL;
4468 goto jleave;
4470 # endif /* HAVE_HISTORY */
4472 # ifdef HAVE_KEY_BINDINGS
4473 FL int
4474 c_bind(void *v){
4475 struct a_tty_bind_ctx *tbcp;
4476 enum n_go_input_flags gif;
4477 bool_t aster, show;
4478 union {char const *cp; char *p; char c;} c;
4479 struct n_cmd_arg_ctx *cacp;
4480 NYD_ENTER;
4482 cacp = v;
4484 c.cp = cacp->cac_arg->ca_arg.ca_str.s;
4485 if(cacp->cac_no == 1)
4486 show = TRU1;
4487 else
4488 show = !asccasecmp(cacp->cac_arg->ca_next->ca_arg.ca_str.s, "show");
4489 aster = FAL0;
4491 if((gif = a_tty_bind_ctx_find(c.cp)) == (enum n_go_input_flags)-1){
4492 if(!(aster = n_is_all_or_aster(c.cp)) || !show){
4493 n_err(_("`bind': invalid context: %s\n"), c.cp);
4494 v = NULL;
4495 goto jleave;
4497 gif = 0;
4500 if(show){
4501 ui32_t lns;
4502 FILE *fp;
4504 if((fp = Ftmp(NULL, "bind", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
4505 n_perr(_("tmpfile"), 0);
4506 v = NULL;
4507 goto jleave;
4510 lns = 0;
4511 for(;;){
4512 for(tbcp = a_tty.tg_bind[gif]; tbcp != NULL;
4513 ++lns, tbcp = tbcp->tbc_next){
4514 /* Print the bytes of resolved terminal capabilities, then */
4515 if((n_poption & n_PO_D_V) &&
4516 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)
4517 ) == a_TTY_BIND_RESOLVE){
4518 char cbuf[8];
4519 union {wchar_t const *wp; char const *cp;} u;
4520 si32_t entlen;
4521 ui32_t cnvlen;
4522 char const *cnvdat, *bsep, *cbufp;
4524 putc('#', fp);
4525 putc(' ', fp);
4527 cbuf[0] = '=', cbuf[2] = '\0';
4528 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len;
4529 cnvlen > 0;){
4530 if(cnvdat != tbcp->tbc_cnv)
4531 putc(',', fp);
4533 /* {si32_t buf_len_iscap;} */
4534 entlen = *n_UNALIGN(si32_t const*,cnvdat);
4535 if(entlen & SI32_MIN){
4536 /* struct{si32_t buf_len_iscap; si32_t cap_len;
4537 * char buf[]+NUL;} */
4538 for(bsep = n_empty,
4539 u.cp = (char const*)
4540 &n_UNALIGN(si32_t const*,cnvdat)[2];
4541 (c.c = *u.cp) != '\0'; ++u.cp){
4542 if(asciichar(c.c) && !cntrlchar(c.c))
4543 cbuf[1] = c.c, cbufp = cbuf;
4544 else
4545 cbufp = n_empty;
4546 fprintf(fp, "%s\\x%02X%s",
4547 bsep, (ui32_t)(ui8_t)c.c, cbufp);
4548 bsep = " ";
4550 entlen &= SI32_MAX;
4551 }else
4552 putc('-', fp);
4554 cnvlen -= entlen;
4555 cnvdat += entlen;
4558 fputs("\n ", fp);
4559 ++lns;
4562 fprintf(fp, "%sbind %s %s %s%s%s\n",
4563 ((tbcp->tbc_flags & a_TTY_BIND_DEFUNCT)
4564 /* I18N: `bind' sequence not working, either because it is
4565 * I18N: using Unicode and that is not available in the locale,
4566 * I18N: or a termcap(5)/terminfo(5) sequence won't work out */
4567 ? _("# <Defunctional> ") : n_empty),
4568 a_tty_bind_ctx_maps[gif].tbcm_name, tbcp->tbc_seq,
4569 n_shexp_quote_cp(tbcp->tbc_exp, TRU1),
4570 (tbcp->tbc_flags & a_TTY_BIND_NOCOMMIT ? n_at : n_empty),
4571 (!(n_poption & n_PO_D_VV) ? n_empty
4572 : (tbcp->tbc_flags & a_TTY_BIND_FUN_INTERNAL
4573 ? _(" # MLE internal") : n_empty))
4576 if(!aster || ++gif >= n__GO_INPUT_CTX_MAX1)
4577 break;
4579 page_or_print(fp, lns);
4581 Fclose(fp);
4582 }else{
4583 struct a_tty_bind_parse_ctx tbpc;
4584 struct n_cmd_arg *cap;
4586 memset(&tbpc, 0, sizeof tbpc);
4587 tbpc.tbpc_cmd = cacp->cac_desc->cad_name;
4588 tbpc.tbpc_in_seq = (cap = cacp->cac_arg->ca_next)->ca_arg.ca_str.s;
4589 if((cap = cap->ca_next) != NULL){
4590 tbpc.tbpc_exp.s = cap->ca_arg.ca_str.s;
4591 tbpc.tbpc_exp.l = cap->ca_arg.ca_str.l;
4593 tbpc.tbpc_flags = gif;
4594 if(!a_tty_bind_create(&tbpc, TRU1))
4595 v = NULL;
4597 jleave:
4598 NYD_LEAVE;
4599 return (v != NULL) ? n_EXIT_OK : n_EXIT_ERR;
4602 FL int
4603 c_unbind(void *v){
4604 struct a_tty_bind_parse_ctx tbpc;
4605 struct a_tty_bind_ctx *tbcp;
4606 enum n_go_input_flags gif;
4607 bool_t aster;
4608 union {char const *cp; char *p;} c;
4609 struct n_cmd_arg_ctx *cacp;
4610 NYD_ENTER;
4612 cacp = v;
4613 c.cp = cacp->cac_arg->ca_arg.ca_str.s;
4614 aster = FAL0;
4616 if((gif = a_tty_bind_ctx_find(c.cp)) == (enum n_go_input_flags)-1){
4617 if(!(aster = n_is_all_or_aster(c.cp))){
4618 n_err(_("`unbind': invalid context: %s\n"), c.cp);
4619 v = NULL;
4620 goto jleave;
4622 gif = 0;
4625 c.cp = cacp->cac_arg->ca_next->ca_arg.ca_str.s;
4626 jredo:
4627 if(n_is_all_or_aster(c.cp)){
4628 while((tbcp = a_tty.tg_bind[gif]) != NULL){
4629 memset(&tbpc, 0, sizeof tbpc);
4630 tbpc.tbpc_tbcp = tbcp;
4631 tbpc.tbpc_flags = gif;
4632 a_tty_bind_del(&tbpc);
4634 }else{
4635 memset(&tbpc, 0, sizeof tbpc);
4636 tbpc.tbpc_cmd = cacp->cac_desc->cad_name;
4637 tbpc.tbpc_in_seq = c.cp;
4638 tbpc.tbpc_flags = gif;
4640 if(n_UNLIKELY(!a_tty_bind_parse(FAL0, &tbpc)))
4641 v = NULL;
4642 else if(n_UNLIKELY((tbcp = tbpc.tbpc_tbcp) == NULL)){
4643 n_err(_("`unbind': no such `bind'ing: %s %s\n"),
4644 a_tty_bind_ctx_maps[gif].tbcm_name, c.cp);
4645 v = NULL;
4646 }else
4647 a_tty_bind_del(&tbpc);
4650 if(aster && ++gif < n__GO_INPUT_CTX_MAX1)
4651 goto jredo;
4652 jleave:
4653 NYD_LEAVE;
4654 return (v != NULL) ? n_EXIT_OK : n_EXIT_ERR;
4656 # endif /* HAVE_KEY_BINDINGS */
4658 #else /* HAVE_MLE */
4660 * The really-nothing-at-all implementation
4663 static void
4664 a_tty_signal(int sig){
4665 /* Prototype at top */
4666 # ifdef HAVE_TERMCAP
4667 sigset_t nset, oset;
4668 # endif
4669 NYD_X; /* Signal handler */
4670 n_UNUSED(sig);
4672 # ifdef HAVE_TERMCAP
4673 n_TERMCAP_SUSPEND(TRU1);
4674 a_tty_sigs_down();
4676 sigemptyset(&nset);
4677 sigaddset(&nset, sig);
4678 sigprocmask(SIG_UNBLOCK, &nset, &oset);
4679 n_raise(sig);
4680 /* When we come here we'll continue editing, so reestablish */
4681 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
4683 a_tty_sigs_up();
4684 n_TERMCAP_RESUME(TRU1);
4685 # endif /* HAVE_TERMCAP */
4688 # if 0
4689 FL void
4690 n_tty_init(void){
4691 NYD_ENTER;
4692 NYD_LEAVE;
4695 FL void
4696 n_tty_destroy(bool_t xit_fastpath){
4697 NYD_ENTER;
4698 n_UNUSED(xit_fastpath);
4699 NYD_LEAVE;
4701 # endif /* 0 */
4703 FL int
4704 (n_tty_readline)(enum n_go_input_flags gif, char const *prompt,
4705 char **linebuf, size_t *linesize, size_t n, bool_t *histok_or_null
4706 n_MEMORY_DEBUG_ARGS){
4707 struct n_string xprompt;
4708 int rv;
4709 NYD_ENTER;
4710 n_UNUSED(histok_or_null);
4712 if(!(gif & n_GO_INPUT_PROMPT_NONE)){
4713 if(n_tty_create_prompt(n_string_creat_auto(&xprompt), prompt, gif) > 0){
4714 fwrite(xprompt.s_dat, 1, xprompt.s_len, n_tty_fp);
4715 fflush(n_tty_fp);
4719 # ifdef HAVE_TERMCAP
4720 a_tty_sigs_up();
4721 n_TERMCAP_RESUME(FAL0);
4722 # endif
4723 rv = (readline_restart)(n_stdin, linebuf, linesize, n
4724 n_MEMORY_DEBUG_ARGSCALL);
4725 # ifdef HAVE_TERMCAP
4726 n_TERMCAP_SUSPEND(FAL0);
4727 a_tty_sigs_down();
4728 # endif
4729 NYD_LEAVE;
4730 return rv;
4733 FL void
4734 n_tty_addhist(char const *s, enum n_go_input_flags gif){
4735 NYD_ENTER;
4736 n_UNUSED(s);
4737 n_UNUSED(gif);
4738 NYD_LEAVE;
4740 #endif /* nothing at all */
4742 #undef a_TTY_SIGNALS
4743 /* s-it-mode */