accmacvar.c: "use %reg not (mem)" to access flag carrier
[s-mailx.git] / tty.c
blobb30108f9d0327fe180df29f8bf3eafb3413dba08
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)
494 a_X(CANCEL, 24)
495 a_X(RESET, 25)
496 a_X(FULLRESET, 26)
497 a_X(COMMIT, 27) /* Must be last one! */
498 # undef a_X
500 a_TTY__BIND_LAST = 1<<27
502 # ifdef HAVE_KEY_BINDINGS
503 n_CTA((ui32_t)a_TTY_BIND_RESOLVE >= (ui32_t)n__GO_INPUT_CTX_MAX1,
504 "Bit carrier lower boundary must be raised to avoid value sharing");
505 # endif
506 n_CTA(a_TTY_BIND_FUN_EXPAND(a_TTY_BIND_FUN_COMMIT) <
507 (1 << a_TTY__BIND_FUN_SHIFTMAX),
508 "Bit carrier range must be expanded to represent necessary bits");
509 n_CTA(a_TTY__BIND_LAST >= (1u << a_TTY__BIND_FUN_SHIFTMAX),
510 "Bit carrier upper boundary must be raised to avoid value sharing");
511 n_CTA(UICMP(64, a_TTY__BIND_LAST, <=, SI32_MAX),
512 "Flag bits excess storage datatype" /* And we need one bit free */);
514 enum a_tty_fun_status{
515 a_TTY_FUN_STATUS_OK, /* Worked, next character */
516 a_TTY_FUN_STATUS_COMMIT, /* Line done */
517 a_TTY_FUN_STATUS_RESTART, /* Complete restart, reset multibyte etc. */
518 a_TTY_FUN_STATUS_END /* End, return EOF */
521 # ifdef HAVE_HISTORY
522 enum a_tty_hist_flags{
523 a_TTY_HIST_CTX_DEFAULT = n_GO_INPUT_CTX_DEFAULT,
524 a_TTY_HIST_CTX_COMPOSE = n_GO_INPUT_CTX_COMPOSE,
525 a_TTY_HIST_CTX_MASK = n__GO_INPUT_CTX_MASK,
526 /* Cannot use enum n_go_input_flags for the rest, need to stay in 8-bit */
527 a_TTY_HIST_GABBY = 1u<<7,
528 a_TTY_HIST__MAX = a_TTY_HIST_GABBY
530 n_CTA(a_TTY_HIST_CTX_MASK < a_TTY_HIST_GABBY, "Enumeration value overlap");
531 # endif
533 enum a_tty_visual_flags{
534 a_TTY_VF_NONE,
535 a_TTY_VF_MOD_CURSOR = 1u<<0, /* Cursor moved */
536 a_TTY_VF_MOD_CONTENT = 1u<<1, /* Content modified */
537 a_TTY_VF_MOD_DIRTY = 1u<<2, /* Needs complete repaint */
538 a_TTY_VF_MOD_SINGLE = 1u<<3, /* TODO Drop when indirection as above comes */
539 a_TTY_VF_REFRESH = a_TTY_VF_MOD_DIRTY | a_TTY_VF_MOD_CURSOR |
540 a_TTY_VF_MOD_CONTENT | a_TTY_VF_MOD_SINGLE,
541 a_TTY_VF_BELL = 1u<<8, /* Ring the bell */
542 a_TTY_VF_SYNC = 1u<<9, /* Flush/Sync I/O channel */
544 a_TTY_VF_ALL_MASK = a_TTY_VF_REFRESH | a_TTY_VF_BELL | a_TTY_VF_SYNC,
545 a_TTY__VF_LAST = a_TTY_VF_SYNC
548 # ifdef HAVE_KEY_BINDINGS
549 struct a_tty_bind_ctx{
550 struct a_tty_bind_ctx *tbc_next;
551 char *tbc_seq; /* quence as given (poss. re-quoted), in .tb__buf */
552 char *tbc_exp; /* ansion, in .tb__buf */
553 /* The .tbc_seq'uence with any terminal capabilities resolved; in fact an
554 * array of structures, the first entry of which is {si32_t buf_len_iscap;}
555 * where the signed bit indicates whether the buffer is a resolved terminal
556 * capability instead of a (possibly multibyte) character. In .tbc__buf */
557 char *tbc_cnv;
558 ui32_t tbc_seq_len;
559 ui32_t tbc_exp_len;
560 ui32_t tbc_cnv_len;
561 ui32_t tbc_flags;
562 char tbc__buf[n_VFIELD_SIZE(0)];
565 struct a_tty_bind_ctx_map{
566 enum n_go_input_flags tbcm_ctx;
567 char const tbcm_name[12]; /* Name of `bind' context */
569 # endif /* HAVE_KEY_BINDINGS */
571 struct a_tty_bind_builtin_tuple{
572 bool_t tbbt_iskey; /* Whether this is a control key; else termcap query */
573 char tbbt_ckey; /* Control code */
574 ui16_t tbbt_query; /* enum n_termcap_query (instead) */
575 char tbbt_exp[12]; /* String or [0]=NUL/[1]=BIND_FUN_REDUCE() */
577 n_CTA(n__TERMCAP_QUERY_MAX1 <= UI16_MAX,
578 "Enumeration cannot be stored in datatype");
580 # ifdef HAVE_KEY_BINDINGS
581 struct a_tty_bind_parse_ctx{
582 char const *tbpc_cmd; /* Command which parses */
583 char const *tbpc_in_seq; /* In: key sequence */
584 struct str tbpc_exp; /* In/Out: expansion (or NULL) */
585 struct a_tty_bind_ctx *tbpc_tbcp; /* Out: if yet existent */
586 struct a_tty_bind_ctx *tbpc_ltbcp; /* Out: the one before .tbpc_tbcp */
587 char *tbpc_seq; /* Out: normalized sequence */
588 char *tbpc_cnv; /* Out: sequence when read(2)ing it */
589 ui32_t tbpc_seq_len;
590 ui32_t tbpc_cnv_len;
591 ui32_t tbpc_cnv_align_mask; /* For creating a_tty_bind_ctx.tbc_cnv */
592 ui32_t tbpc_flags; /* n_go_input_flags | a_tty_bind_flags */
595 /* Input character tree */
596 struct a_tty_bind_tree{
597 struct a_tty_bind_tree *tbt_sibling; /* s at same level */
598 struct a_tty_bind_tree *tbt_childs; /* Sequence continues.. here */
599 struct a_tty_bind_tree *tbt_parent;
600 struct a_tty_bind_ctx *tbt_bind; /* NULL for intermediates */
601 wchar_t tbt_char; /* acter this level represents */
602 bool_t tbt_isseq; /* Belongs to multibyte sequence */
603 bool_t tbt_isseq_trail; /* ..is trailing byte of it */
604 ui8_t tbt__dummy[2];
606 # endif /* HAVE_KEY_BINDINGS */
608 struct a_tty_cell{
609 wchar_t tc_wc;
610 ui16_t tc_count; /* ..of bytes */
611 ui8_t tc_width; /* Visual width; TAB==UI8_MAX! */
612 bool_t tc_novis; /* Don't display visually as such (control character) */
613 char tc_cbuf[MB_LEN_MAX * 2]; /* .. plus reset shift sequence */
616 struct a_tty_global{
617 struct a_tty_line *tg_line; /* To be able to access it from signal hdl */
618 # ifdef HAVE_HISTORY
619 struct a_tty_hist *tg_hist;
620 struct a_tty_hist *tg_hist_tail;
621 size_t tg_hist_size;
622 size_t tg_hist_size_max;
623 # endif
624 # ifdef HAVE_KEY_BINDINGS
625 ui32_t tg_bind_cnt; /* Overall number of bindings */
626 bool_t tg_bind_isdirty;
627 bool_t tg_bind_isbuild;
628 # define a_TTY_SHCUT_MAX (3 +1) /* Note: update manual on change! */
629 ui8_t tg_bind__dummy[2];
630 char tg_bind_shcut_cancel[n__GO_INPUT_CTX_MAX1][a_TTY_SHCUT_MAX];
631 char tg_bind_shcut_prompt_char[n__GO_INPUT_CTX_MAX1][a_TTY_SHCUT_MAX];
632 struct a_tty_bind_ctx *tg_bind[n__GO_INPUT_CTX_MAX1];
633 struct a_tty_bind_tree *tg_bind_tree[n__GO_INPUT_CTX_MAX1][HSHSIZE];
634 # endif
635 struct termios tg_tios_old;
636 struct termios tg_tios_new;
638 # ifdef HAVE_KEY_BINDINGS
639 n_CTA(n__GO_INPUT_CTX_MAX1 == 3 && a_TTY_SHCUT_MAX == 4 &&
640 n_SIZEOF_FIELD(struct a_tty_global, tg_bind__dummy) == 2,
641 "Value results in array sizes that results in bad structure layout");
642 n_CTA(a_TTY_SHCUT_MAX > 1,
643 "Users need at least one shortcut, plus NUL terminator");
644 # endif
646 # ifdef HAVE_HISTORY
647 struct a_tty_hist{
648 struct a_tty_hist *th_older;
649 struct a_tty_hist *th_younger;
650 ui32_t th_len;
651 ui8_t th_flags; /* enum a_tty_hist_flags */
652 char th_dat[n_VFIELD_SIZE(3)];
654 n_CTA(UI8_MAX >= a_TTY_HIST__MAX, "Value exceeds datatype storage");
655 # endif
657 struct a_tty_line{
658 /* Caller pointers */
659 char **tl_x_buf;
660 size_t *tl_x_bufsize;
661 /* Input processing */
662 # ifdef HAVE_KEY_BINDINGS
663 wchar_t tl_bind_takeover; /* Leftover byte to consume next */
664 ui8_t tl_bind_timeout; /* In-seq. inter-byte-timer, in 1/10th secs */
665 ui8_t tl__bind_dummy[3];
666 char (*tl_bind_shcut_cancel)[a_TTY_SHCUT_MAX]; /* Special _CANCEL control */
667 char (*tl_bind_shcut_prompt_char)[a_TTY_SHCUT_MAX]; /* ..for _PROMPT_CHAR */
668 struct a_tty_bind_tree *(*tl_bind_tree_hmap)[HSHSIZE]; /* Bind lookup tree */
669 struct a_tty_bind_tree *tl_bind_tree;
670 # endif
671 /* Line data / content handling */
672 ui32_t tl_count; /* ..of a_tty_cell's (<= a_TTY_LINE_MAX) */
673 ui32_t tl_cursor; /* Current a_tty_cell insertion point */
674 union{
675 char *cbuf; /* *.tl_x_buf */
676 struct a_tty_cell *cells;
677 } tl_line;
678 struct str tl_defc; /* Current default content */
679 size_t tl_defc_cursor_byte; /* Desired position of cursor after takeover */
680 struct str tl_savec; /* Saved default content */
681 struct str tl_pastebuf; /* Last snarfed data */
682 # ifdef HAVE_HISTORY
683 struct a_tty_hist *tl_hist; /* History cursor */
684 # endif
685 ui32_t tl_count_max; /* ..before buffer needs to grow */
686 /* Visual data representation handling */
687 ui32_t tl_vi_flags; /* enum a_tty_visual_flags */
688 ui32_t tl_lst_count; /* .tl_count after last sync */
689 ui32_t tl_lst_cursor; /* .tl_cursor after last sync */
690 /* TODO Add another indirection layer by adding a tl_phy_line of
691 * TODO a_tty_cell objects, incorporate changes in visual layer,
692 * TODO then check what _really_ has changed, sync those changes only */
693 struct a_tty_cell const *tl_phy_start; /* First visible cell, left border */
694 ui32_t tl_phy_cursor; /* Physical cursor position */
695 bool_t tl_quote_rndtrip; /* For _kht() expansion */
696 ui8_t tl__dummy2[3 + 4];
697 ui32_t tl_goinflags; /* enum n_go_input_flags */
698 ui32_t tl_prompt_length; /* Preclassified (TODO needed as a_tty_cell) */
699 ui32_t tl_prompt_width;
700 char const *tl_prompt; /* Preformatted prompt (including colours) */
701 /* .tl_pos_buf is a hack */
702 # ifdef HAVE_COLOUR
703 char *tl_pos_buf; /* mle-position colour-on, [4], reset seq. */
704 char *tl_pos; /* Address of the [4] */
705 # endif
708 # ifdef HAVE_KEY_BINDINGS
709 /* C99: use [INDEX]={} */
710 n_CTAV(n_GO_INPUT_CTX_BASE == 0);
711 n_CTAV(n_GO_INPUT_CTX_DEFAULT == 1);
712 n_CTAV(n_GO_INPUT_CTX_COMPOSE == 2);
713 static struct a_tty_bind_ctx_map const
714 a_tty_bind_ctx_maps[n__GO_INPUT_CTX_MAX1] = {
715 {n_GO_INPUT_CTX_BASE, "base"},
716 {n_GO_INPUT_CTX_DEFAULT, "default"},
717 {n_GO_INPUT_CTX_COMPOSE, "compose"}
720 /* Special functions which our MLE provides internally.
721 * Update the manual upon change! */
722 static char const a_tty_bind_fun_names[][24] = {
723 # undef a_X
724 # define a_X(I,N) \
725 n_FIELD_INITI(a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## I)) "mle-" N "\0",
727 a_X(BELL, "bell")
728 a_X(GO_BWD, "go-bwd") a_X(GO_FWD, "go-fwd")
729 a_X(GO_WORD_BWD, "go-word-bwd") a_X(GO_WORD_FWD, "go-word-fwd")
730 a_X(GO_SCREEN_BWD, "go-screen-bwd") a_X(GO_SCREEN_FWD, "go-screen-fwd")
731 a_X(GO_HOME, "go-home") a_X(GO_END, "go-end")
732 a_X(DEL_BWD, "del-bwd") a_X(DEL_FWD, "del-fwd")
733 a_X(SNARF_WORD_BWD, "snarf-word-bwd") a_X(SNARF_WORD_FWD, "snarf-word-fwd")
734 a_X(SNARF_END, "snarf-end") a_X(SNARF_LINE, "snarf-line")
735 a_X(HIST_BWD, "hist-bwd") a_X(HIST_FWD, "hist-fwd")
736 a_X(HIST_SRCH_BWD, "hist-srch-bwd") a_X(HIST_SRCH_FWD, "hist-srch-fwd")
737 a_X(REPAINT, "repaint")
738 a_X(QUOTE_RNDTRIP, "quote-rndtrip")
739 a_X(PROMPT_CHAR, "prompt-char")
740 a_X(COMPLETE, "complete")
741 a_X(PASTE, "paste")
743 a_X(CANCEL, "cancel")
744 a_X(RESET, "reset")
745 a_X(FULLRESET, "fullreset")
746 a_X(COMMIT, "commit")
748 # undef a_X
750 # endif /* HAVE_KEY_BINDINGS */
752 /* The default key bindings (unless disallowed). Update manual upon change!
753 * A logical subset of this table is also used if !HAVE_KEY_BINDINGS (more
754 * expensive than a switch() on control codes directly, but less redundant).
755 * The table for the "base" context */
756 static struct a_tty_bind_builtin_tuple const a_tty_bind_base_tuples[] = {
757 # undef a_X
758 # define a_X(K,S) \
759 {TRU1, K, 0, {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
761 a_X('A', GO_HOME)
762 a_X('B', GO_BWD)
763 /* C: SIGINT */
764 a_X('D', DEL_FWD)
765 a_X('E', GO_END)
766 a_X('F', GO_FWD)
767 a_X('G', RESET)
768 a_X('H', DEL_BWD)
769 a_X('I', COMPLETE)
770 a_X('J', COMMIT)
771 a_X('K', SNARF_END)
772 a_X('L', REPAINT)
773 /* M: same as J */
774 a_X('N', HIST_FWD)
775 /* O: below */
776 a_X('P', HIST_BWD)
777 a_X('Q', QUOTE_RNDTRIP)
778 a_X('R', HIST_SRCH_BWD)
779 a_X('S', HIST_SRCH_FWD)
780 a_X('T', PASTE)
781 a_X('U', SNARF_LINE)
782 a_X('V', PROMPT_CHAR)
783 a_X('W', SNARF_WORD_BWD)
784 a_X('X', GO_WORD_FWD)
785 a_X('Y', GO_WORD_BWD)
786 /* Z: SIGTSTP */
788 a_X('[', CANCEL)
789 /* \: below */
790 /* ]: below */
791 /* ^: below */
792 a_X('_', SNARF_WORD_FWD)
794 a_X('?', DEL_BWD)
796 # undef a_X
797 # define a_X(K,S) {TRU1, K, 0, {S}},
799 /* The remains only if we have `bind' functionality available */
800 # ifdef HAVE_KEY_BINDINGS
801 # undef a_X
802 # define a_X(Q,S) \
803 {FAL0, '\0', n_TERMCAP_QUERY_ ## Q,\
804 {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
806 a_X(key_backspace, DEL_BWD) a_X(key_dc, DEL_FWD)
807 a_X(key_eol, SNARF_END)
808 a_X(key_home, GO_HOME) a_X(key_end, GO_END)
809 a_X(key_left, GO_BWD) a_X(key_right, GO_FWD)
810 a_X(xkey_aleft, GO_WORD_BWD) a_X(xkey_aright, GO_WORD_FWD)
811 a_X(xkey_cleft, GO_SCREEN_BWD) a_X(xkey_cright, GO_SCREEN_FWD)
812 a_X(key_sleft, GO_HOME) a_X(key_sright, GO_END)
813 a_X(key_up, HIST_BWD) a_X(key_down, HIST_FWD)
814 # endif /* HAVE_KEY_BINDINGS */
817 /* The table for the "default" context */
818 static struct a_tty_bind_builtin_tuple const a_tty_bind_default_tuples[] = {
819 # undef a_X
820 # define a_X(K,S) \
821 {TRU1, K, 0, {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
823 # undef a_X
824 # define a_X(K,S) {TRU1, K, 0, {S}},
826 a_X('O', "dt")
828 a_X('\\', "z+")
829 a_X(']', "z$")
830 a_X('^', "z0")
832 /* The remains only if we have `bind' functionality available */
833 # ifdef HAVE_KEY_BINDINGS
834 # undef a_X
835 # define a_X(Q,S) {FAL0, '\0', n_TERMCAP_QUERY_ ## Q, {S}},
837 a_X(key_shome, "z0") a_X(key_send, "z$")
838 a_X(xkey_sup, "z0") a_X(xkey_sdown, "z$")
839 a_X(key_ppage, "z-") a_X(key_npage, "z+")
840 a_X(xkey_cup, "dotmove-") a_X(xkey_cdown, "dotmove+")
841 # endif /* HAVE_KEY_BINDINGS */
843 # undef a_X
845 static struct a_tty_global a_tty;
847 /* Change from canonical to raw, non-canonical mode, and way back */
848 static void a_tty_term_mode(bool_t raw);
850 # ifdef HAVE_HISTORY
851 /* Load and save the history file, respectively */
852 static bool_t a_tty_hist_load(void);
853 static bool_t a_tty_hist_save(void);
855 /* Initialize .tg_hist_size_max and return desired history file, or NULL */
856 static char const *a_tty_hist__query_config(void);
857 # endif
859 /* Adjust an active raw mode to use / not use a timeout */
860 # ifdef HAVE_KEY_BINDINGS
861 static void a_tty_term_rawmode_timeout(struct a_tty_line *tlp, bool_t enable);
862 # endif
864 /* 0-X (2), UI8_MAX == \t / HT */
865 static ui8_t a_tty_wcwidth(wchar_t wc);
867 /* Memory / cell / word generics */
868 static void a_tty_check_grow(struct a_tty_line *tlp, ui32_t no
869 n_MEMORY_DEBUG_ARGS);
870 static ssize_t a_tty_cell2dat(struct a_tty_line *tlp);
871 static void a_tty_cell2save(struct a_tty_line *tlp);
873 /* Save away data bytes of given range (max = non-inclusive) */
874 static void a_tty_copy2paste(struct a_tty_line *tlp, struct a_tty_cell *tcpmin,
875 struct a_tty_cell *tcpmax);
877 /* Ask user for hexadecimal number, interpret as UTF-32 */
878 static wchar_t a_tty_vinuni(struct a_tty_line *tlp);
880 /* Visual screen synchronization */
881 static bool_t a_tty_vi_refresh(struct a_tty_line *tlp);
883 static bool_t a_tty_vi__paint(struct a_tty_line *tlp);
885 /* Search for word boundary, starting at tl_cursor, in "dir"ection (<> 0).
886 * Return <0 when moving is impossible (backward direction but in position 0,
887 * forward direction but in outermost column), and relative distance to
888 * tl_cursor otherwise */
889 static si32_t a_tty_wboundary(struct a_tty_line *tlp, si32_t dir);
891 /* Most function implementations */
892 static void a_tty_khome(struct a_tty_line *tlp, bool_t dobell);
893 static void a_tty_kend(struct a_tty_line *tlp);
894 static void a_tty_kbs(struct a_tty_line *tlp);
895 static void a_tty_ksnarf(struct a_tty_line *tlp, bool_t cplline, bool_t dobell);
896 static si32_t a_tty_kdel(struct a_tty_line *tlp);
897 static void a_tty_kleft(struct a_tty_line *tlp);
898 static void a_tty_kright(struct a_tty_line *tlp);
899 static void a_tty_ksnarfw(struct a_tty_line *tlp, bool_t fwd);
900 static void a_tty_kgow(struct a_tty_line *tlp, si32_t dir);
901 static void a_tty_kgoscr(struct a_tty_line *tlp, si32_t dir);
902 static bool_t a_tty_kother(struct a_tty_line *tlp, wchar_t wc);
903 static ui32_t a_tty_kht(struct a_tty_line *tlp);
905 # ifdef HAVE_HISTORY
906 /* Return UI32_MAX on "exhaustion" */
907 static ui32_t a_tty_khist(struct a_tty_line *tlp, bool_t fwd);
908 static ui32_t a_tty_khist_search(struct a_tty_line *tlp, bool_t fwd);
910 static ui32_t a_tty__khist_shared(struct a_tty_line *tlp,
911 struct a_tty_hist *thp);
912 # endif
914 /* Handle a function */
915 static enum a_tty_fun_status a_tty_fun(struct a_tty_line *tlp,
916 enum a_tty_bind_flags tbf, size_t *len);
918 /* Readline core */
919 static ssize_t a_tty_readline(struct a_tty_line *tlp, size_t len,
920 bool_t *histok_or_null n_MEMORY_DEBUG_ARGS);
922 # ifdef HAVE_KEY_BINDINGS
923 /* Find context or -1 */
924 static enum n_go_input_flags a_tty_bind_ctx_find(char const *name);
926 /* Create (or replace, if allowed) a binding */
927 static bool_t a_tty_bind_create(struct a_tty_bind_parse_ctx *tbpcp,
928 bool_t replace);
930 /* Shared implementation to parse `bind' and `unbind' "key-sequence" and
931 * "expansion" command line arguments into something that we can work with */
932 static bool_t a_tty_bind_parse(bool_t isbindcmd,
933 struct a_tty_bind_parse_ctx *tbpcp);
935 /* Lazy resolve a termcap(5)/terminfo(5) (or *termcap*!) capability */
936 static void a_tty_bind_resolve(struct a_tty_bind_ctx *tbcp);
938 /* Delete an existing binding */
939 static void a_tty_bind_del(struct a_tty_bind_parse_ctx *tbpcp);
941 /* Life cycle of all input node trees */
942 static void a_tty_bind_tree_build(void);
943 static void a_tty_bind_tree_teardown(void);
945 static void a_tty__bind_tree_add(ui32_t hmap_idx,
946 struct a_tty_bind_tree *store[HSHSIZE],
947 struct a_tty_bind_ctx *tbcp);
948 static struct a_tty_bind_tree *a_tty__bind_tree_add_wc(
949 struct a_tty_bind_tree **treep, struct a_tty_bind_tree *parentp,
950 wchar_t wc, bool_t isseq);
951 static void a_tty__bind_tree_free(struct a_tty_bind_tree *tbtp);
952 # endif /* HAVE_KEY_BINDINGS */
954 static void
955 a_tty_signal(int sig){
956 /* Prototype at top */
957 sigset_t nset, oset;
958 NYD_X; /* Signal handler */
960 n_COLOUR( n_colour_env_gut(); ) /* TODO NO SIMPLE SUSPENSION POSSIBLE.. */
961 a_tty_term_mode(FAL0);
962 n_TERMCAP_SUSPEND(TRU1);
963 a_tty_sigs_down();
965 sigemptyset(&nset);
966 sigaddset(&nset, sig);
967 sigprocmask(SIG_UNBLOCK, &nset, &oset);
968 n_raise(sig);
969 /* When we come here we'll continue editing, so reestablish */
970 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
972 /* TODO THEREFORE NEED TO _GUT() .. _CREATE() ENTIRE ENVS!! */
973 n_COLOUR( n_colour_env_create(n_COLOUR_CTX_MLE, n_tty_fp, FAL0); )
974 a_tty_sigs_up();
975 n_TERMCAP_RESUME(TRU1);
976 a_tty_term_mode(TRU1);
977 a_tty.tg_line->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
980 static void
981 a_tty_term_mode(bool_t raw){
982 struct termios *tiosp;
983 NYD2_ENTER;
985 tiosp = &a_tty.tg_tios_old;
986 if(!raw)
987 goto jleave;
989 /* Always requery the attributes, in case we've been moved from background
990 * to foreground or however else in between sessions */
991 /* XXX Always enforce ECHO and ICANON in the OLD attributes - do so as long
992 * XXX as we don't properly deal with TTIN and TTOU etc. */
993 tcgetattr(STDIN_FILENO, tiosp); /* TODO v15: use _only_ n_tty_fp! */
994 tiosp->c_lflag |= ECHO | ICANON;
996 memcpy(&a_tty.tg_tios_new, tiosp, sizeof *tiosp);
997 tiosp = &a_tty.tg_tios_new;
998 tiosp->c_cc[VMIN] = 1;
999 tiosp->c_cc[VTIME] = 0;
1000 /* Enable ^\, ^Q and ^S to be used for key bindings */
1001 tiosp->c_cc[VQUIT] = tiosp->c_cc[VSTART] = tiosp->c_cc[VSTOP] = '\0';
1002 tiosp->c_iflag &= ~(ISTRIP | IGNCR);
1003 tiosp->c_lflag &= ~(ECHO /*| ECHOE | ECHONL */| ICANON | IEXTEN);
1004 jleave:
1005 tcsetattr(STDIN_FILENO, TCSADRAIN, tiosp);
1006 NYD2_LEAVE;
1009 # ifdef HAVE_HISTORY
1010 static bool_t
1011 a_tty_hist_load(void){
1012 ui8_t version;
1013 size_t lsize, cnt, llen;
1014 char *lbuf, *cp;
1015 FILE *f;
1016 char const *v;
1017 bool_t rv;
1018 NYD_ENTER;
1020 rv = TRU1;
1022 if((v = a_tty_hist__query_config()) == NULL ||
1023 a_tty.tg_hist_size_max == 0)
1024 goto jleave;
1026 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
1027 f = fopen(v, "r"); /* TODO HISTFILE LOAD: use linebuf pool */
1028 if(f == NULL){
1029 int e;
1031 e = errno;
1032 n_err(_("Cannot read *history-file*=%s: %s\n"),
1033 n_shexp_quote_cp(v, FAL0), n_err_to_doc(e));
1034 rv = FAL0;
1035 goto jrele;
1037 (void)n_file_lock(fileno(f), FLT_READ, 0,0, UIZ_MAX);
1039 /* Clear old history */
1040 /* C99 */{
1041 struct a_tty_hist *thp;
1043 while((thp = a_tty.tg_hist) != NULL){
1044 a_tty.tg_hist = thp->th_older;
1045 n_free(thp);
1047 a_tty.tg_hist_tail = NULL;
1048 a_tty.tg_hist_size = 0;
1051 assert(!(n_pstate & n_PS_ROOT));
1052 n_pstate |= n_PS_ROOT; /* Allow calling addhist() */
1053 lbuf = NULL;
1054 lsize = 0;
1055 cnt = (size_t)fsize(f);
1056 version = 0;
1058 while(fgetline(&lbuf, &lsize, &cnt, &llen, f, FAL0) != NULL){
1059 cp = lbuf;
1060 /* Hand-edited history files may have this, probably */
1061 while(llen > 0 && spacechar(cp[0])){
1062 ++cp;
1063 --llen;
1065 if(llen > 0 && cp[llen - 1] == '\n')
1066 cp[--llen] = '\0';
1068 /* Skip empty and comment lines */
1069 if(llen == 0 || cp[0] == '#')
1070 continue;
1072 if(n_UNLIKELY(version == 0) &&
1073 (version = strcmp(cp, a_TTY_HIST_MARKER) ? 1 : 2) != 1)
1074 continue;
1076 /* C99 */{
1077 enum n_go_input_flags gif;
1079 if(version == 2){
1080 if(llen <= 2){
1081 /* XXX n_err(_("Skipped invalid *history-file* entry: %s\n"),
1082 * XXX n_shexp_quote_cp(cp));*/
1083 continue;
1085 switch(*cp++){
1086 default:
1087 case 'd':
1088 gif = n_GO_INPUT_CTX_DEFAULT; /* == a_TTY_HIST_CTX_DEFAULT */
1089 break;
1090 case 'c':
1091 gif = n_GO_INPUT_CTX_COMPOSE; /* == a_TTY_HIST_CTX_COMPOSE */
1092 break;
1095 if(*cp++ == '*')
1096 gif |= n_GO_INPUT_HIST_GABBY;
1098 while(*cp == ' ')
1099 ++cp;
1100 }else{
1101 gif = n_GO_INPUT_CTX_DEFAULT;
1102 if(cp[0] == '*'){
1103 ++cp;
1104 gif |= n_GO_INPUT_HIST_GABBY;
1108 n_tty_addhist(cp, gif);
1112 if(lbuf != NULL)
1113 n_free(lbuf);
1114 n_pstate &= ~n_PS_ROOT;
1116 fclose(f);
1117 jrele:
1118 rele_all_sigs(); /* XXX remove jumps */
1119 jleave:
1120 NYD_LEAVE;
1121 return rv;
1124 static bool_t
1125 a_tty_hist_save(void){
1126 size_t i;
1127 struct a_tty_hist *thp;
1128 FILE *f;
1129 char const *v;
1130 bool_t rv, dogabby;
1131 NYD_ENTER;
1133 rv = TRU1;
1135 if((v = a_tty_hist__query_config()) == NULL ||
1136 a_tty.tg_hist_size_max == 0)
1137 goto jleave;
1139 dogabby = ok_blook(history_gabby_persist);
1141 if((thp = a_tty.tg_hist) != NULL)
1142 for(i = a_tty.tg_hist_size_max; thp->th_older != NULL;
1143 thp = thp->th_older)
1144 if((dogabby || !(thp->th_flags & a_TTY_HIST_GABBY)) && --i == 0)
1145 break;
1147 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
1148 if((f = fopen(v, "w")) == NULL){ /* TODO temporary + rename?! */
1149 int e;
1151 e = errno;
1152 n_err(_("Cannot write *history-file*=%s: %s\n"),
1153 n_shexp_quote_cp(v, FAL0), n_err_to_doc(e));
1154 rv = FAL0;
1155 goto jrele;
1157 (void)n_file_lock(fileno(f), FLT_WRITE, 0,0, UIZ_MAX);
1159 if(fwrite(a_TTY_HIST_MARKER "\n", sizeof *a_TTY_HIST_MARKER,
1160 sizeof(a_TTY_HIST_MARKER "\n") -1, f) !=
1161 sizeof(a_TTY_HIST_MARKER "\n") -1)
1162 goto jioerr;
1163 else for(; thp != NULL; thp = thp->th_younger){
1164 if(dogabby || !(thp->th_flags & a_TTY_HIST_GABBY)){
1165 char c;
1167 switch(thp->th_flags & a_TTY_HIST_CTX_MASK){
1168 default:
1169 case a_TTY_HIST_CTX_DEFAULT:
1170 c = 'd';
1171 break;
1172 case a_TTY_HIST_CTX_COMPOSE:
1173 c = 'c';
1174 break;
1176 if(putc(c, f) == EOF)
1177 goto jioerr;
1179 if((thp->th_flags & a_TTY_HIST_GABBY) && putc('*', f) == EOF)
1180 goto jioerr;
1182 if(putc(' ', f) == EOF ||
1183 fwrite(thp->th_dat, sizeof *thp->th_dat, thp->th_len, f) !=
1184 sizeof(*thp->th_dat) * thp->th_len ||
1185 putc('\n', f) == EOF){
1186 jioerr:
1187 n_err(_("I/O error while writing *history-file* %s\n"),
1188 n_shexp_quote_cp(v, FAL0));
1189 rv = FAL0;
1190 break;
1195 fclose(f);
1196 jrele:
1197 rele_all_sigs(); /* XXX remove jumps */
1198 jleave:
1199 NYD_LEAVE;
1200 return rv;
1203 static char const *
1204 a_tty_hist__query_config(void){
1205 char const *rv, *cp;
1206 NYD2_ENTER;
1208 if((cp = ok_vlook(NAIL_HISTSIZE)) != NULL)
1209 n_OBSOLETE(_("please use *history-size* instead of *NAIL_HISTSIZE*"));
1210 if((rv = ok_vlook(history_size)) == NULL)
1211 rv = cp;
1212 if(rv == NULL)
1213 a_tty.tg_hist_size_max = UIZ_MAX;
1214 else
1215 (void)n_idec_uiz_cp(&a_tty.tg_hist_size_max, rv, 10, NULL);
1217 if((cp = ok_vlook(NAIL_HISTFILE)) != NULL)
1218 n_OBSOLETE(_("please use *history-file* instead of *NAIL_HISTFILE*"));
1219 if((rv = ok_vlook(history_file)) == NULL)
1220 rv = cp;
1221 if(rv != NULL)
1222 rv = fexpand(rv, FEXP_LOCAL | FEXP_NSHELL);
1223 NYD2_LEAVE;
1224 return rv;
1226 # endif /* HAVE_HISTORY */
1228 # ifdef HAVE_KEY_BINDINGS
1229 static void
1230 a_tty_term_rawmode_timeout(struct a_tty_line *tlp, bool_t enable){
1231 NYD2_ENTER;
1232 if(enable){
1233 ui8_t bt;
1235 a_tty.tg_tios_new.c_cc[VMIN] = 0;
1236 if((bt = tlp->tl_bind_timeout) == 0)
1237 bt = a_TTY_BIND_TIMEOUT;
1238 a_tty.tg_tios_new.c_cc[VTIME] = bt;
1239 }else{
1240 a_tty.tg_tios_new.c_cc[VMIN] = 1;
1241 a_tty.tg_tios_new.c_cc[VTIME] = 0;
1243 tcsetattr(STDIN_FILENO, TCSANOW, &a_tty.tg_tios_new);
1244 NYD2_LEAVE;
1246 # endif /* HAVE_KEY_BINDINGS */
1248 static ui8_t
1249 a_tty_wcwidth(wchar_t wc){
1250 ui8_t rv;
1251 NYD2_ENTER;
1253 /* Special case the reverse solidus at first */
1254 if(wc == '\t')
1255 rv = UI8_MAX;
1256 else{
1257 int i;
1259 # ifdef HAVE_WCWIDTH
1260 rv = ((i = wcwidth(wc)) > 0) ? (ui8_t)i : 0;
1261 # else
1262 rv = iswprint(wc) ? 1 + (wc >= 0x1100u) : 0; /* TODO use S-CText */
1263 # endif
1265 NYD2_LEAVE;
1266 return rv;
1269 static void
1270 a_tty_check_grow(struct a_tty_line *tlp, ui32_t no n_MEMORY_DEBUG_ARGS){
1271 ui32_t cmax;
1272 NYD2_ENTER;
1274 if(n_UNLIKELY((cmax = tlp->tl_count + no) > tlp->tl_count_max)){
1275 size_t i;
1277 i = cmax * sizeof(struct a_tty_cell) + 2 * sizeof(struct a_tty_cell);
1278 if(n_LIKELY(i >= *tlp->tl_x_bufsize)){
1279 hold_all_sigs(); /* XXX v15 drop */
1280 i <<= 1;
1281 tlp->tl_line.cbuf =
1282 *tlp->tl_x_buf = (n_realloc)(*tlp->tl_x_buf, i
1283 n_MEMORY_DEBUG_ARGSCALL);
1284 rele_all_sigs(); /* XXX v15 drop */
1286 tlp->tl_count_max = cmax;
1287 *tlp->tl_x_bufsize = i;
1289 NYD2_LEAVE;
1292 static ssize_t
1293 a_tty_cell2dat(struct a_tty_line *tlp){
1294 size_t len, i;
1295 NYD2_ENTER;
1297 len = 0;
1299 if(n_LIKELY((i = tlp->tl_count) > 0)){
1300 struct a_tty_cell const *tcap;
1302 tcap = tlp->tl_line.cells;
1304 memcpy(tlp->tl_line.cbuf + len, tcap->tc_cbuf, tcap->tc_count);
1305 len += tcap->tc_count;
1306 }while(++tcap, --i > 0);
1309 tlp->tl_line.cbuf[len] = '\0';
1310 NYD2_LEAVE;
1311 return (ssize_t)len;
1314 static void
1315 a_tty_cell2save(struct a_tty_line *tlp){
1316 size_t len, i;
1317 struct a_tty_cell *tcap;
1318 NYD2_ENTER;
1320 tlp->tl_savec.s = NULL;
1321 tlp->tl_savec.l = 0;
1323 if(n_UNLIKELY(tlp->tl_count == 0))
1324 goto jleave;
1326 for(tcap = tlp->tl_line.cells, len = 0, i = tlp->tl_count; i > 0;
1327 ++tcap, --i)
1328 len += tcap->tc_count;
1330 tlp->tl_savec.s = n_autorec_alloc((tlp->tl_savec.l = len) +1);
1332 for(tcap = tlp->tl_line.cells, len = 0, i = tlp->tl_count; i > 0;
1333 ++tcap, --i){
1334 memcpy(tlp->tl_savec.s + len, tcap->tc_cbuf, tcap->tc_count);
1335 len += tcap->tc_count;
1337 tlp->tl_savec.s[len] = '\0';
1338 jleave:
1339 NYD2_LEAVE;
1342 static void
1343 a_tty_copy2paste(struct a_tty_line *tlp, struct a_tty_cell *tcpmin,
1344 struct a_tty_cell *tcpmax){
1345 char *cp;
1346 struct a_tty_cell *tcp;
1347 size_t l;
1348 NYD2_ENTER;
1350 l = 0;
1351 for(tcp = tcpmin; tcp < tcpmax; ++tcp)
1352 l += tcp->tc_count;
1354 tlp->tl_pastebuf.s = cp = n_autorec_alloc((tlp->tl_pastebuf.l = l) +1);
1356 for(tcp = tcpmin; tcp < tcpmax; cp += l, ++tcp)
1357 memcpy(cp, tcp->tc_cbuf, l = tcp->tc_count);
1358 *cp = '\0';
1359 NYD2_LEAVE;
1362 static wchar_t
1363 a_tty_vinuni(struct a_tty_line *tlp){
1364 char buf[16];
1365 uiz_t i;
1366 wchar_t wc;
1367 NYD2_ENTER;
1369 wc = '\0';
1371 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr) ||
1372 !n_termcap_cmd(n_TERMCAP_CMD_ce, 0, -1))
1373 goto jleave;
1375 /* C99 */{
1376 struct str const *cpre, *csuf;
1378 cpre = csuf = NULL;
1379 #ifdef HAVE_COLOUR
1380 if(n_COLOUR_IS_ACTIVE()){
1381 struct n_colour_pen *cpen;
1383 cpen = n_colour_pen_create(n_COLOUR_ID_MLE_PROMPT, NULL);
1384 if((cpre = n_colour_pen_to_str(cpen)) != NULL)
1385 csuf = n_colour_reset_to_str();
1387 #endif
1388 fprintf(n_tty_fp, _("%sPlease enter Unicode code point:%s "),
1389 (cpre != NULL ? cpre->s : n_empty),
1390 (csuf != NULL ? csuf->s : n_empty));
1392 fflush(n_tty_fp);
1394 buf[sizeof(buf) -1] = '\0';
1395 for(i = 0;;){
1396 if(read(STDIN_FILENO, &buf[i], 1) != 1){
1397 if(n_err_no == n_ERR_INTR) /* xxx #if !SA_RESTART ? */
1398 continue;
1399 goto jleave;
1401 if(buf[i] == '\n')
1402 break;
1403 if(!hexchar(buf[i])){
1404 char const emsg[] = "[0-9a-fA-F]";
1406 n_LCTA(sizeof emsg <= sizeof(buf), "Preallocated buffer too small");
1407 memcpy(buf, emsg, sizeof emsg);
1408 goto jerr;
1411 putc(buf[i], n_tty_fp);
1412 fflush(n_tty_fp);
1413 if(++i == sizeof buf)
1414 goto jerr;
1416 buf[i] = '\0';
1418 if((n_idec_uiz_cp(&i, buf, 16, NULL
1419 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
1420 ) != n_IDEC_STATE_CONSUMED || i > 0x10FFFF/* XXX magic; CText */){
1421 jerr:
1422 n_err(_("\nInvalid input: %s\n"), buf);
1423 goto jleave;
1426 wc = (wchar_t)i;
1427 jleave:
1428 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY | (wc == '\0' ? a_TTY_VF_BELL : 0);
1429 NYD2_LEAVE;
1430 return wc;
1433 static bool_t
1434 a_tty_vi_refresh(struct a_tty_line *tlp){
1435 bool_t rv;
1436 NYD2_ENTER;
1438 if(tlp->tl_vi_flags & a_TTY_VF_BELL){
1439 tlp->tl_vi_flags |= a_TTY_VF_SYNC;
1440 if(putc('\a', n_tty_fp) == EOF)
1441 goto jerr;
1444 if(tlp->tl_vi_flags & a_TTY_VF_REFRESH){
1445 /* kht may want to restore a cursor position after inserting some
1446 * data somewhere */
1447 if(tlp->tl_defc_cursor_byte > 0){
1448 size_t i, j;
1449 ssize_t k;
1451 a_tty_khome(tlp, FAL0);
1453 i = tlp->tl_defc_cursor_byte;
1454 tlp->tl_defc_cursor_byte = 0;
1455 for(j = 0; tlp->tl_cursor < tlp->tl_count; ++j){
1456 a_tty_kright(tlp);
1457 if((k = tlp->tl_line.cells[j].tc_count) > i)
1458 break;
1459 i -= k;
1463 if(!a_tty_vi__paint(tlp))
1464 goto jerr;
1467 if(tlp->tl_vi_flags & a_TTY_VF_SYNC){
1468 tlp->tl_vi_flags &= ~a_TTY_VF_SYNC;
1469 if(fflush(n_tty_fp))
1470 goto jerr;
1473 rv = TRU1;
1474 jleave:
1475 tlp->tl_vi_flags &= ~a_TTY_VF_ALL_MASK;
1476 NYD2_LEAVE;
1477 return rv;
1479 jerr:
1480 clearerr(n_tty_fp); /* xxx I/O layer rewrite */
1481 n_err(_("Visual refresh failed! Is $TERM set correctly?\n"
1482 " Setting *line-editor-disable* to get us through!\n"));
1483 ok_bset(line_editor_disable);
1484 rv = FAL0;
1485 goto jleave;
1488 static bool_t
1489 a_tty_vi__paint(struct a_tty_line *tlp){
1490 enum{
1491 a_TRUE_RV = a_TTY__VF_LAST<<1, /* Return value bit */
1492 a_HAVE_PROMPT = a_TTY__VF_LAST<<2, /* Have a prompt */
1493 a_SHOW_PROMPT = a_TTY__VF_LAST<<3, /* Shall print the prompt */
1494 a_MOVE_CURSOR = a_TTY__VF_LAST<<4, /* Move visual cursor for user! */
1495 a_LEFT_MIN = a_TTY__VF_LAST<<5, /* On left boundary */
1496 a_RIGHT_MAX = a_TTY__VF_LAST<<6,
1497 a_HAVE_POSITION = a_TTY__VF_LAST<<7, /* Print the position indicator */
1499 /* We carry some flags over invocations (not worth a specific field) */
1500 a_VISIBLE_PROMPT = a_TTY__VF_LAST<<8, /* The prompt is on the screen */
1501 a_PERSIST_MASK = a_VISIBLE_PROMPT,
1502 a__LAST = a_PERSIST_MASK
1505 ui32_t f, w, phy_wid_base, phy_wid, phy_base, phy_cur, cnt,
1506 DBG(lstcur COMMA) cur,
1507 vi_left, /*vi_right,*/ phy_nxtcur;
1508 struct a_tty_cell const *tccp, *tcp_left, *tcp_right, *tcxp;
1509 NYD2_ENTER;
1510 n_LCTA(UICMP(64, a__LAST, <, UI32_MAX), "Flag bits excess storage datatype");
1512 f = tlp->tl_vi_flags;
1513 tlp->tl_vi_flags = (f & ~(a_TTY_VF_REFRESH | a_PERSIST_MASK)) |
1514 a_TTY_VF_SYNC;
1515 f |= a_TRUE_RV;
1516 if((w = tlp->tl_prompt_width) > 0)
1517 f |= a_HAVE_PROMPT;
1518 f |= a_HAVE_POSITION;
1520 /* XXX We don't have a OnTerminalResize event (see main.c) yet, so we need
1521 * XXX to reevaluate our circumstances over and over again */
1522 /* Don't display prompt or position indicator on very small screens */
1523 if((phy_wid_base = (ui32_t)n_scrnwidth) <= a_TTY_WIDTH_RIPOFF)
1524 f &= ~(a_HAVE_PROMPT | a_HAVE_POSITION);
1525 else{
1526 phy_wid_base -= a_TTY_WIDTH_RIPOFF;
1528 /* Disable the prompt if the screen is too small; due to lack of some
1529 * indicator simply add a second ripoff */
1530 if((f & a_HAVE_PROMPT) && w + a_TTY_WIDTH_RIPOFF >= phy_wid_base)
1531 f &= ~a_HAVE_PROMPT;
1534 phy_wid = phy_wid_base;
1535 phy_base = 0;
1536 phy_cur = tlp->tl_phy_cursor;
1537 cnt = tlp->tl_count;
1538 DBG( lstcur = tlp->tl_lst_cursor; )
1540 /* XXX Assume dirty screen if shrunk */
1541 if(cnt < tlp->tl_lst_count)
1542 f |= a_TTY_VF_MOD_DIRTY;
1544 /* TODO Without HAVE_TERMCAP, it would likely be much cheaper to simply
1545 * TODO always "cr + paint + ce + ch", since ce is simulated via spaces.. */
1547 /* Quickshot: if the line is empty, possibly print prompt and out */
1548 if(cnt == 0){
1549 /* In that special case dirty anything if it seems better */
1550 if((f & a_TTY_VF_MOD_CONTENT) || tlp->tl_lst_count > 0)
1551 f |= a_TTY_VF_MOD_DIRTY;
1553 if((f & a_TTY_VF_MOD_DIRTY) && phy_cur != 0){
1554 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
1555 goto jerr;
1556 phy_cur = 0;
1559 if((f & (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)) ==
1560 (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)){
1561 if(fputs(tlp->tl_prompt, n_tty_fp) == EOF)
1562 goto jerr;
1563 phy_cur = tlp->tl_prompt_width + 1;
1566 /* May need to clear former line content */
1567 if((f & a_TTY_VF_MOD_DIRTY) &&
1568 !n_termcap_cmd(n_TERMCAP_CMD_ce, phy_cur, -1))
1569 goto jerr;
1571 tlp->tl_phy_start = tlp->tl_line.cells;
1572 goto jleave;
1575 /* Try to get an idea of the visual window */
1577 /* Find the left visual boundary */
1578 phy_wid = (phy_wid >> 1) + (phy_wid >> 2);
1579 if((cur = tlp->tl_cursor) == cnt)
1580 --cur;
1582 w = (tcp_left = tccp = tlp->tl_line.cells + cur)->tc_width;
1583 if(w == UI8_MAX) /* TODO yet HT == SPACE */
1584 w = 1;
1585 while(tcp_left > tlp->tl_line.cells){
1586 ui16_t cw = tcp_left[-1].tc_width;
1588 if(cw == UI8_MAX) /* TODO yet HT == SPACE */
1589 cw = 1;
1590 if(w + cw >= phy_wid)
1591 break;
1592 w += cw;
1593 --tcp_left;
1595 vi_left = w;
1597 /* If the left hand side of our visual viewpoint consumes less than half
1598 * of the screen width, show the prompt */
1599 if(tcp_left == tlp->tl_line.cells)
1600 f |= a_LEFT_MIN;
1602 if((f & (a_LEFT_MIN | a_HAVE_PROMPT)) == (a_LEFT_MIN | a_HAVE_PROMPT) &&
1603 w + tlp->tl_prompt_width < phy_wid){
1604 phy_base = tlp->tl_prompt_width;
1605 f |= a_SHOW_PROMPT;
1608 /* Then search for right boundary. We always leave the rightmost column
1609 * empty because some terminals [cw]ould wrap the line if we write into
1610 * that. XXX terminfo(5)/termcap(5) have the semi_auto_right_margin/sam/YE
1611 * XXX capability to indicate this, but we don't look at that */
1612 phy_wid = phy_wid_base - phy_base;
1613 tcp_right = tlp->tl_line.cells + cnt;
1615 while(&tccp[1] < tcp_right){
1616 ui16_t cw = tccp[1].tc_width;
1617 ui32_t i;
1619 if(cw == UI8_MAX) /* TODO yet HT == SPACE */
1620 cw = 1;
1621 i = w + cw;
1622 if(i > phy_wid)
1623 break;
1624 w = i;
1625 ++tccp;
1627 /*vi_right = w - vi_left;*/
1629 /* If the complete line including prompt fits on the screen, show prompt */
1630 if(--tcp_right == tccp){
1631 f |= a_RIGHT_MAX;
1633 /* Since we did brute-force walk also for the left boundary we may end up
1634 * in a situation were anything effectively fits on the screen, including
1635 * the prompt that is, but were we don't recognize this since we
1636 * restricted the search to fit in some visual viewpoint. Therefore try
1637 * again to extend the left boundary to overcome that */
1638 if(!(f & a_LEFT_MIN)){
1639 struct a_tty_cell const *tc1p = tlp->tl_line.cells;
1640 ui32_t vil1 = vi_left;
1642 assert(!(f & a_SHOW_PROMPT));
1643 w += tlp->tl_prompt_width;
1644 for(tcxp = tcp_left;;){
1645 ui32_t i = tcxp[-1].tc_width;
1647 if(i == UI8_MAX) /* TODO yet HT == SPACE */
1648 i = 1;
1649 vil1 += i;
1650 i += w;
1651 if(i > phy_wid)
1652 break;
1653 w = i;
1654 if(--tcxp == tc1p){
1655 tcp_left = tc1p;
1656 /*vi_left = vil1;*/
1657 f |= a_LEFT_MIN;
1658 break;
1661 /*w -= tlp->tl_prompt_width;*/
1664 tcp_right = tccp;
1665 tccp = tlp->tl_line.cells + cur;
1667 if((f & (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT | a_SHOW_PROMPT)) ==
1668 (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT) &&
1669 w + tlp->tl_prompt_width <= phy_wid){
1670 phy_wid -= (phy_base = tlp->tl_prompt_width);
1671 f |= a_SHOW_PROMPT;
1674 /* Try to avoid repainting the complete line - this is possible if the
1675 * cursor "did not leave the screen" and the prompt status hasn't changed.
1676 * I.e., after clamping virtual viewpoint, compare relation to physical */
1677 if((f & (a_TTY_VF_MOD_SINGLE/*FIXME*/ |
1678 a_TTY_VF_MOD_CONTENT/* xxx */ | a_TTY_VF_MOD_DIRTY)) ||
1679 (tcxp = tlp->tl_phy_start) == NULL ||
1680 tcxp > tccp || tcxp <= tcp_right)
1681 f |= a_TTY_VF_MOD_DIRTY;
1682 else{
1683 f |= a_TTY_VF_MOD_DIRTY;
1684 #if 0
1685 struct a_tty_cell const *tcyp;
1686 si32_t cur_displace;
1687 ui32_t phy_lmargin, phy_rmargin, fx, phy_displace;
1689 phy_lmargin = (fx = phy_wid) / 100;
1690 phy_rmargin = fx - (phy_lmargin * a_TTY_SCROLL_MARGIN_RIGHT);
1691 phy_lmargin *= a_TTY_SCROLL_MARGIN_LEFT;
1692 fx = (f & (a_SHOW_PROMPT | a_VISIBLE_PROMPT));
1694 if(fx == 0 || fx == (a_SHOW_PROMPT | a_VISIBLE_PROMPT)){
1696 #endif
1698 goto jpaint;
1700 /* We know what we have to paint, start synchronizing */
1701 jpaint:
1702 assert(phy_cur == tlp->tl_phy_cursor);
1703 assert(phy_wid == phy_wid_base - phy_base);
1704 assert(cnt == tlp->tl_count);
1705 assert(cnt > 0);
1706 assert(lstcur == tlp->tl_lst_cursor);
1707 assert(tccp == tlp->tl_line.cells + cur);
1709 phy_nxtcur = phy_base; /* FIXME only if repaint cpl. */
1711 /* Quickshot: is it only cursor movement within the visible screen? */
1712 if((f & a_TTY_VF_REFRESH) == a_TTY_VF_MOD_CURSOR){
1713 f |= a_MOVE_CURSOR;
1714 goto jcursor;
1717 /* To be able to apply some quick jump offs, clear line if possible */
1718 if(f & a_TTY_VF_MOD_DIRTY){
1719 /* Force complete clearance and cursor reinitialization */
1720 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr) ||
1721 !n_termcap_cmd(n_TERMCAP_CMD_ce, 0, -1))
1722 goto jerr;
1723 tlp->tl_phy_start = tcp_left;
1724 phy_cur = 0;
1727 if((f & (a_TTY_VF_MOD_DIRTY | a_SHOW_PROMPT)) && phy_cur != 0){
1728 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
1729 goto jerr;
1730 phy_cur = 0;
1733 if(f & a_SHOW_PROMPT){
1734 assert(phy_base == tlp->tl_prompt_width);
1735 if(fputs(tlp->tl_prompt, n_tty_fp) == EOF)
1736 goto jerr;
1737 phy_cur = phy_nxtcur;
1738 f |= a_VISIBLE_PROMPT;
1739 }else
1740 f &= ~a_VISIBLE_PROMPT;
1742 /* FIXME reposition cursor for paint */
1743 for(w = phy_nxtcur; tcp_left <= tcp_right; ++tcp_left){
1744 ui16_t cw;
1746 cw = tcp_left->tc_width;
1748 if(n_LIKELY(!tcp_left->tc_novis)){
1749 if(fwrite(tcp_left->tc_cbuf, sizeof *tcp_left->tc_cbuf,
1750 tcp_left->tc_count, n_tty_fp) != tcp_left->tc_count)
1751 goto jerr;
1752 }else{ /* XXX Shouldn't be here <-> CText, ui_str.c */
1753 char wbuf[8]; /* XXX magic */
1755 if(n_psonce & n_PSO_UNICODE){
1756 ui32_t wc;
1758 wc = (ui32_t)tcp_left->tc_wc;
1759 if((wc & ~0x1Fu) == 0)
1760 wc |= 0x2400;
1761 else if(wc == 0x7F)
1762 wc = 0x2421;
1763 else
1764 wc = 0x2426;
1765 n_utf32_to_utf8(wc, wbuf);
1766 }else
1767 wbuf[0] = '?', wbuf[1] = '\0';
1769 if(fputs(wbuf, n_tty_fp) == EOF)
1770 goto jerr;
1771 cw = 1;
1774 if(cw == UI8_MAX) /* TODO yet HT == SPACE */
1775 cw = 1;
1776 w += cw;
1777 if(tcp_left == tccp)
1778 phy_nxtcur = w;
1779 phy_cur += cw;
1782 /* Write something position marker alike if it does not fit on screen */
1783 if((f & a_HAVE_POSITION) &&
1784 ((f & (a_LEFT_MIN | a_RIGHT_MAX)) != (a_LEFT_MIN | a_RIGHT_MAX) ||
1785 ((f & a_HAVE_PROMPT) && !(f & a_SHOW_PROMPT)))){
1786 # ifdef HAVE_COLOUR
1787 char *posbuf = tlp->tl_pos_buf, *pos = tlp->tl_pos;
1788 # else
1789 char posbuf[5], *pos = posbuf;
1791 pos[4] = '\0';
1792 # endif
1794 if(phy_cur != (w = phy_wid_base) &&
1795 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = w, 0))
1796 goto jerr;
1798 *pos++ = '|';
1799 if((f & a_LEFT_MIN) && (!(f & a_HAVE_PROMPT) || (f & a_SHOW_PROMPT)))
1800 memcpy(pos, "^.+", 3);
1801 else if(f & a_RIGHT_MAX)
1802 memcpy(pos, ".+$", 3);
1803 else{
1804 /* Theoretical line length limit a_TTY_LINE_MAX, choose next power of
1805 * ten (10 ** 10) to represent 100 percent, since we don't have a macro
1806 * that generates a constant, and i don't trust the standard "u type
1807 * suffix automatically scales" calculate the large number */
1808 static char const itoa[] = "0123456789";
1810 ui64_t const fact100 = (ui64_t)0x3B9ACA00u * 10u, fact = fact100 / 100;
1811 ui32_t i = (ui32_t)(((fact100 / cnt) * tlp->tl_cursor) / fact);
1812 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1814 if(i < 10)
1815 pos[0] = ' ', pos[1] = itoa[i];
1816 else
1817 pos[1] = itoa[i % 10], pos[0] = itoa[i / 10];
1818 pos[2] = '%';
1821 if(fputs(posbuf, n_tty_fp) == EOF)
1822 goto jerr;
1823 phy_cur += 4;
1826 /* Users are used to see the cursor right of the point of interest, so we
1827 * need some further adjustments unless in special conditions. Be aware
1828 * that we may have adjusted cur at the beginning, too */
1829 if((cur = tlp->tl_cursor) == 0)
1830 phy_nxtcur = phy_base;
1831 else if(cur != cnt){
1832 ui16_t cw = tccp->tc_width;
1834 if(cw == UI8_MAX) /* TODO yet HT == SPACE */
1835 cw = 1;
1836 phy_nxtcur -= cw;
1839 jcursor:
1840 if(((f & a_MOVE_CURSOR) || phy_nxtcur != phy_cur) &&
1841 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = phy_nxtcur, 0))
1842 goto jerr;
1844 jleave:
1845 tlp->tl_vi_flags |= (f & a_PERSIST_MASK);
1846 tlp->tl_lst_count = tlp->tl_count;
1847 tlp->tl_lst_cursor = tlp->tl_cursor;
1848 tlp->tl_phy_cursor = phy_cur;
1850 NYD2_LEAVE;
1851 return ((f & a_TRUE_RV) != 0);
1852 jerr:
1853 f &= ~a_TRUE_RV;
1854 goto jleave;
1857 static si32_t
1858 a_tty_wboundary(struct a_tty_line *tlp, si32_t dir){/* TODO shell token-wise */
1859 bool_t anynon;
1860 struct a_tty_cell *tcap;
1861 ui32_t cur, cnt;
1862 si32_t rv;
1863 NYD2_ENTER;
1865 assert(dir == 1 || dir == -1);
1867 rv = -1;
1868 cnt = tlp->tl_count;
1869 cur = tlp->tl_cursor;
1871 if(dir < 0){
1872 if(cur == 0)
1873 goto jleave;
1874 }else if(cur + 1 >= cnt)
1875 goto jleave;
1876 else
1877 --cnt, --cur; /* xxx Unsigned wrapping may occur (twice), then */
1879 for(rv = 0, tcap = tlp->tl_line.cells, anynon = FAL0;;){
1880 wchar_t wc;
1882 wc = tcap[cur += (ui32_t)dir].tc_wc;
1883 if(/*TODO not everywhere iswblank(wc)*/ wc == L' ' || wc == L'\t' ||
1884 iswpunct(wc)){
1885 if(anynon)
1886 break;
1887 }else
1888 anynon = TRU1;
1890 ++rv;
1892 if(dir < 0){
1893 if(cur == 0)
1894 break;
1895 }else if(cur + 1 >= cnt){
1896 ++rv;
1897 break;
1900 jleave:
1901 NYD2_LEAVE;
1902 return rv;
1905 static void
1906 a_tty_khome(struct a_tty_line *tlp, bool_t dobell){
1907 ui32_t f;
1908 NYD2_ENTER;
1910 if(n_LIKELY(tlp->tl_cursor > 0)){
1911 tlp->tl_cursor = 0;
1912 f = a_TTY_VF_MOD_CURSOR;
1913 }else if(dobell)
1914 f = a_TTY_VF_BELL;
1915 else
1916 f = a_TTY_VF_NONE;
1918 tlp->tl_vi_flags |= f;
1919 NYD2_LEAVE;
1922 static void
1923 a_tty_kend(struct a_tty_line *tlp){
1924 ui32_t f;
1925 NYD2_ENTER;
1927 if(n_LIKELY(tlp->tl_cursor < tlp->tl_count)){
1928 tlp->tl_cursor = tlp->tl_count;
1929 f = a_TTY_VF_MOD_CURSOR;
1930 }else
1931 f = a_TTY_VF_BELL;
1933 tlp->tl_vi_flags |= f;
1934 NYD2_LEAVE;
1937 static void
1938 a_tty_kbs(struct a_tty_line *tlp){
1939 ui32_t f, cur, cnt;
1940 NYD2_ENTER;
1942 cur = tlp->tl_cursor;
1943 cnt = tlp->tl_count;
1945 if(n_LIKELY(cur > 0)){
1946 tlp->tl_cursor = --cur;
1947 tlp->tl_count = --cnt;
1949 if((cnt -= cur) > 0){
1950 struct a_tty_cell *tcap;
1952 tcap = tlp->tl_line.cells + cur;
1953 memmove(tcap, &tcap[1], cnt *= sizeof(*tcap));
1955 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
1956 }else
1957 f = a_TTY_VF_BELL;
1959 tlp->tl_vi_flags |= f;
1960 NYD2_LEAVE;
1963 static void
1964 a_tty_ksnarf(struct a_tty_line *tlp, bool_t cplline, bool_t dobell){
1965 ui32_t i, f;
1966 NYD2_ENTER;
1968 f = a_TTY_VF_NONE;
1969 i = tlp->tl_cursor;
1971 if(cplline && i > 0){
1972 tlp->tl_cursor = i = 0;
1973 f = a_TTY_VF_MOD_CURSOR;
1976 if(n_LIKELY(i < tlp->tl_count)){
1977 struct a_tty_cell *tcap;
1979 tcap = &tlp->tl_line.cells[0];
1980 a_tty_copy2paste(tlp, &tcap[i], &tcap[tlp->tl_count]);
1981 tlp->tl_count = i;
1982 f = a_TTY_VF_MOD_CONTENT;
1983 }else if(dobell)
1984 f |= a_TTY_VF_BELL;
1986 tlp->tl_vi_flags |= f;
1987 NYD2_LEAVE;
1990 static si32_t
1991 a_tty_kdel(struct a_tty_line *tlp){
1992 ui32_t cur, cnt, f;
1993 si32_t i;
1994 NYD2_ENTER;
1996 cur = tlp->tl_cursor;
1997 cnt = tlp->tl_count;
1998 i = (si32_t)(cnt - cur);
2000 if(n_LIKELY(i > 0)){
2001 tlp->tl_count = --cnt;
2003 if(n_LIKELY(--i > 0)){
2004 struct a_tty_cell *tcap;
2006 tcap = &tlp->tl_line.cells[cur];
2007 memmove(tcap, &tcap[1], (ui32_t)i * sizeof(*tcap));
2009 f = a_TTY_VF_MOD_CONTENT;
2010 }else if(cnt == 0 && !ok_blook(ignoreeof)){
2011 putc('^', n_tty_fp);
2012 putc('D', n_tty_fp);
2013 i = -1;
2014 f = a_TTY_VF_NONE;
2015 }else{
2016 i = 0;
2017 f = a_TTY_VF_BELL;
2020 tlp->tl_vi_flags |= f;
2021 NYD2_LEAVE;
2022 return i;
2025 static void
2026 a_tty_kleft(struct a_tty_line *tlp){
2027 ui32_t f;
2028 NYD2_ENTER;
2030 if(n_LIKELY(tlp->tl_cursor > 0)){
2031 --tlp->tl_cursor;
2032 f = a_TTY_VF_MOD_CURSOR;
2033 }else
2034 f = a_TTY_VF_BELL;
2036 tlp->tl_vi_flags |= f;
2037 NYD2_LEAVE;
2040 static void
2041 a_tty_kright(struct a_tty_line *tlp){
2042 ui32_t i;
2043 NYD2_ENTER;
2045 if(n_LIKELY((i = tlp->tl_cursor + 1) <= tlp->tl_count)){
2046 tlp->tl_cursor = i;
2047 i = a_TTY_VF_MOD_CURSOR;
2048 }else
2049 i = a_TTY_VF_BELL;
2051 tlp->tl_vi_flags |= i;
2052 NYD2_LEAVE;
2055 static void
2056 a_tty_ksnarfw(struct a_tty_line *tlp, bool_t fwd){
2057 struct a_tty_cell *tcap;
2058 ui32_t cnt, cur, f;
2059 si32_t i;
2060 NYD2_ENTER;
2062 if(n_UNLIKELY((i = a_tty_wboundary(tlp, (fwd ? +1 : -1))) <= 0)){
2063 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
2064 goto jleave;
2067 cnt = tlp->tl_count - (ui32_t)i;
2068 cur = tlp->tl_cursor;
2069 if(!fwd)
2070 cur -= (ui32_t)i;
2071 tcap = &tlp->tl_line.cells[cur];
2073 a_tty_copy2paste(tlp, &tcap[0], &tcap[i]);
2075 if((tlp->tl_count = cnt) != (tlp->tl_cursor = cur)){
2076 cnt -= cur;
2077 memmove(&tcap[0], &tcap[i], cnt * sizeof(*tcap)); /* FIXME*/
2080 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
2081 jleave:
2082 tlp->tl_vi_flags |= f;
2083 NYD2_LEAVE;
2086 static void
2087 a_tty_kgow(struct a_tty_line *tlp, si32_t dir){
2088 ui32_t f;
2089 si32_t i;
2090 NYD2_ENTER;
2092 if(n_UNLIKELY((i = a_tty_wboundary(tlp, dir)) <= 0))
2093 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
2094 else{
2095 if(dir < 0)
2096 i = -i;
2097 tlp->tl_cursor += (ui32_t)i;
2098 f = a_TTY_VF_MOD_CURSOR;
2101 tlp->tl_vi_flags |= f;
2102 NYD2_LEAVE;
2105 static void
2106 a_tty_kgoscr(struct a_tty_line *tlp, si32_t dir){
2107 ui32_t sw, i, cur, f, cnt;
2108 NYD2_ENTER;
2110 sw = (ui32_t)n_scrnwidth - 2;
2111 if(sw > (i = tlp->tl_prompt_width))
2112 sw -= i;
2113 cur = tlp->tl_cursor;
2114 f = a_TTY_VF_BELL;
2116 if(dir > 0){
2117 for(cnt = tlp->tl_count; cur < cnt && sw > 0; ++cur){
2118 i = tlp->tl_line.cells[cur].tc_width;
2119 i = n_MIN(sw, i);
2120 sw -= i;
2122 }else{
2123 while(cur > 0 && sw > 0){
2124 i = tlp->tl_line.cells[--cur].tc_width;
2125 i = n_MIN(sw, i);
2126 sw -= i;
2129 if(cur != tlp->tl_cursor){
2130 tlp->tl_cursor = cur;
2131 f = a_TTY_VF_MOD_CURSOR;
2134 tlp->tl_vi_flags |= f;
2135 NYD2_LEAVE;
2138 static bool_t
2139 a_tty_kother(struct a_tty_line *tlp, wchar_t wc){
2140 /* Append if at EOL, insert otherwise;
2141 * since we may move around character-wise, always use a fresh ps */
2142 mbstate_t ps;
2143 struct a_tty_cell tc, *tcap;
2144 ui32_t f, cur, cnt;
2145 bool_t rv;
2146 NYD2_ENTER;
2148 rv = FAL0;
2149 f = a_TTY_VF_NONE;
2151 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
2152 if(tlp->tl_count + 1 >= a_TTY_LINE_MAX){
2153 n_err(_("Stop here, we can't extend line beyond size limit\n"));
2154 goto jleave;
2157 /* First init a cell and see whether we'll really handle this wc */
2158 memset(&ps, 0, sizeof ps);
2159 /* C99 */{
2160 size_t l;
2162 l = wcrtomb(tc.tc_cbuf, tc.tc_wc = wc, &ps);
2163 if(n_UNLIKELY(l > MB_LEN_MAX)){
2164 jemb:
2165 n_err(_("wcrtomb(3) error: too many multibyte character bytes\n"));
2166 goto jleave;
2168 tc.tc_count = (ui16_t)l;
2170 if(n_UNLIKELY((n_psonce & n_PSO_ENC_MBSTATE) != 0)){
2171 l = wcrtomb(&tc.tc_cbuf[l], L'\0', &ps);
2172 if(n_LIKELY(l == 1))
2173 /* Only NUL terminator */;
2174 else if(n_LIKELY(--l < MB_LEN_MAX))
2175 tc.tc_count += (ui16_t)l;
2176 else
2177 goto jemb;
2181 /* Yes, we will! Place it in the array */
2182 tc.tc_novis = (iswprint(wc) == 0);
2183 tc.tc_width = a_tty_wcwidth(wc);
2184 /* TODO if(tc.tc_novis && tc.tc_width > 0) */
2186 cur = tlp->tl_cursor++;
2187 cnt = tlp->tl_count++ - cur;
2188 tcap = &tlp->tl_line.cells[cur];
2189 if(cnt >= 1){
2190 memmove(&tcap[1], tcap, cnt * sizeof(*tcap));
2191 f = a_TTY_VF_MOD_CONTENT;
2192 }else
2193 f = a_TTY_VF_MOD_SINGLE;
2194 memcpy(tcap, &tc, sizeof *tcap);
2196 f |= a_TTY_VF_MOD_CURSOR;
2197 rv = TRU1;
2198 jleave:
2199 if(!rv)
2200 f |= a_TTY_VF_BELL;
2201 tlp->tl_vi_flags |= f;
2202 NYD2_LEAVE;
2203 return rv;
2206 static ui32_t
2207 a_tty_kht(struct a_tty_line *tlp){
2208 ui8_t (*mempool)[n_MEMORY_POOL_TYPE_SIZEOF], *mempool_persist;
2209 struct stat sb;
2210 struct str orig, bot, topp, sub, exp, preexp;
2211 struct n_string shou, *shoup;
2212 struct a_tty_cell *ctop, *cx;
2213 bool_t wedid, set_savec;
2214 ui32_t rv, f;
2215 NYD2_ENTER;
2217 /* Get plain line data; if this is the first expansion/xy, update the
2218 * very original content so that ^G gets the origin back */
2219 orig = tlp->tl_savec;
2220 a_tty_cell2save(tlp);
2221 exp = tlp->tl_savec;
2222 if(orig.s != NULL){
2223 /*tlp->tl_savec = orig;*/
2224 set_savec = FAL0;
2225 }else
2226 set_savec = TRU1;
2227 orig = exp;
2229 mempool_persist = n_go_data->gdc_mempool;
2230 n_memory_pool_push(mempool = n_lofi_alloc(sizeof *mempool));
2232 shoup = n_string_creat_auto(&shou);
2233 f = a_TTY_VF_NONE;
2235 /* C99 */{
2236 size_t max;
2237 struct a_tty_cell *cword;
2239 /* Find the word to be expanded */
2240 cword = tlp->tl_line.cells;
2241 ctop = &cword[tlp->tl_cursor];
2242 cx = &cword[tlp->tl_count];
2244 /* topp: separate data right of cursor */
2245 if(cx > ctop){
2246 for(rv = 0; ctop < cx; ++ctop)
2247 rv += ctop->tc_count;
2248 topp.l = rv;
2249 topp.s = orig.s + orig.l - rv;
2250 ctop = cword + tlp->tl_cursor;
2251 }else
2252 topp.s = NULL, topp.l = 0;
2254 /* Find the shell token that corresponds to the cursor position */
2255 max = 0;
2256 if(ctop > cword){
2257 for(; cword < ctop; ++cword)
2258 max += cword->tc_count;
2260 bot = sub = orig;
2261 bot.l = 0;
2262 sub.l = max;
2264 if(max > 0){
2265 for(;;){
2266 enum n_shexp_state shs;
2268 exp = sub;
2269 shs = n_shexp_parse_token((n_SHEXP_PARSE_DRYRUN |
2270 n_SHEXP_PARSE_TRIM_SPACE | n_SHEXP_PARSE_IGNORE_EMPTY |
2271 n_SHEXP_PARSE_QUOTE_AUTO_CLOSE), NULL, &sub, NULL);
2272 if(sub.l != 0){
2273 size_t x;
2275 assert(max >= sub.l);
2276 x = max - sub.l;
2277 bot.l += x;
2278 max -= x;
2279 continue;
2281 if(shs & n_SHEXP_STATE_ERR_MASK){
2282 n_err(_("Invalid completion pattern: %.*s\n"),
2283 (int)exp.l, exp.s);
2284 f |= a_TTY_VF_BELL;
2285 goto jnope;
2288 /* All WS? Trailing WS that has been "jumped over"? */
2289 if(exp.l == 0 || (shs & n_SHEXP_STATE_WS_TRAIL))
2290 break;
2292 n_shexp_parse_token((n_SHEXP_PARSE_TRIM_SPACE |
2293 n_SHEXP_PARSE_IGNORE_EMPTY | n_SHEXP_PARSE_QUOTE_AUTO_CLOSE),
2294 shoup, &exp, NULL);
2295 break;
2298 sub.s = n_string_cp(shoup);
2299 sub.l = shoup->s_len;
2303 /* Leave room for "implicit asterisk" expansion, as below */
2304 if(sub.l == 0){
2305 sub.s = n_UNCONST(n_star);
2306 sub.l = sizeof(n_star) -1;
2309 preexp.s = n_UNCONST(n_empty);
2310 preexp.l = sizeof(n_empty) -1;
2311 wedid = FAL0;
2312 jredo:
2313 /* TODO Super-Heavy-Metal: block all sigs, avoid leaks on jump */
2314 hold_all_sigs();
2315 exp.s = fexpand(sub.s, a_TTY_TAB_FEXP_FL);
2316 rele_all_sigs();
2318 if(exp.s == NULL || (exp.l = strlen(exp.s)) == 0){
2319 if(wedid < FAL0)
2320 goto jnope;
2321 /* No. But maybe the users' desire was to complete only a part of the
2322 * shell token of interest! TODO This can be improved, we would need to
2323 * TODO have shexp_parse to create a DOM structure of parsed snippets, so
2324 * TODO that we can tell for each snippet which quote is active and
2325 * TODO whether we may cross its boundary and/or apply expansion for it!
2326 * TODO Only like that we would be able to properly requote user input
2327 * TODO like "'['a-z]<TAB>" to e.g. "\[a-z]" for glob purposes! */
2328 if(wedid == TRU1){
2329 size_t i, li;
2331 wedid = TRUM1;
2332 for(li = UIZ_MAX, i = sub.l; i-- > 0;){
2333 char c;
2335 if((c = sub.s[i]) == '/' || c == '+' /* *folder*! */)
2336 li = i;
2337 /* Do stop once some "magic" characters are seen XXX magic set */
2338 else if(c == '<' || c == '>' || c == '=' || c == ':')
2339 break;
2341 if(li != UIZ_MAX){
2342 preexp = sub;
2343 preexp.l = li;
2344 sub.l -= li;
2345 sub.s += li;
2346 goto jredo;
2350 /* A different case is that the user input includes for example character
2351 * classes: here fexpand() will go over glob, and that will not find any
2352 * match, thus returning NULL; try to wildcard expand this pattern! */
2353 jaster_check:
2354 if(sub.s[sub.l - 1] != '*'){
2355 wedid = TRU1;
2356 shoup = n_string_push_c(shoup, '*');
2357 sub.s = n_string_cp(shoup);
2358 sub.l = shoup->s_len;
2359 goto jredo;
2361 goto jnope;
2364 if(wedid == TRUM1 && preexp.l > 0)
2365 preexp.s = savestrbuf(preexp.s, preexp.l);
2367 /* May be multi-return! */
2368 if(n_pstate & n_PS_EXPAND_MULTIRESULT)
2369 goto jmulti;
2371 /* xxx That is not really true since the limit counts characters not bytes */
2372 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
2373 if(exp.l >= a_TTY_LINE_MAX - 1 || a_TTY_LINE_MAX - 1 - exp.l < preexp.l){
2374 n_err(_("Tabulator expansion would extend beyond line size limit\n"));
2375 f |= a_TTY_VF_BELL;
2376 goto jnope;
2379 /* If the expansion equals the original string, assume the user wants what
2380 * is usually known as tab completion, append `*' and restart */
2381 if(!wedid && exp.l == sub.l && !memcmp(exp.s, sub.s, exp.l))
2382 goto jaster_check;
2384 if(exp.s[exp.l - 1] != '/'){
2385 if(!stat(exp.s, &sb) && S_ISDIR(sb.st_mode)){
2386 shoup = n_string_assign_buf(shoup, exp.s, exp.l);
2387 shoup = n_string_push_c(shoup, '/');
2388 exp.s = n_string_cp(shoup);
2389 goto jset;
2392 exp.s[exp.l] = '\0';
2394 jset:
2395 exp.l = strlen(exp.s = n_shexp_quote_cp(exp.s, tlp->tl_quote_rndtrip));
2396 tlp->tl_defc_cursor_byte = bot.l + preexp.l + exp.l -1;
2398 orig.l = bot.l + preexp.l + exp.l + topp.l;
2399 orig.s = n_autorec_alloc_from_pool(mempool_persist, orig.l + 5 +1);
2400 if((rv = (ui32_t)bot.l) > 0)
2401 memcpy(orig.s, bot.s, rv);
2402 if(preexp.l > 0){
2403 memcpy(&orig.s[rv], preexp.s, preexp.l);
2404 rv += preexp.l;
2406 memcpy(&orig.s[rv], exp.s, exp.l);
2407 rv += exp.l;
2408 if(topp.l > 0){
2409 memcpy(&orig.s[rv], topp.s, topp.l);
2410 rv += topp.l;
2412 orig.s[rv] = '\0';
2414 tlp->tl_defc = orig;
2415 tlp->tl_count = tlp->tl_cursor = 0;
2416 f |= a_TTY_VF_MOD_DIRTY;
2417 jleave:
2418 n_memory_pool_pop(mempool);
2419 n_lofi_free(mempool);
2420 tlp->tl_vi_flags |= f;
2421 NYD2_LEAVE;
2422 return rv;
2424 jmulti:{
2425 struct n_visual_info_ctx vic;
2426 struct str input;
2427 wc_t c2, c1;
2428 bool_t isfirst;
2429 char const *lococp;
2430 size_t locolen, scrwid, lnlen, lncnt, prefixlen;
2431 FILE *fp;
2433 if((fp = Ftmp(NULL, "tabex", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
2434 n_perr(_("tmpfile"), 0);
2435 fp = n_tty_fp;
2438 /* How long is the result string for real? Search the NUL NUL
2439 * terminator. While here, detect the longest entry to perform an
2440 * initial allocation of our accumulator string */
2441 locolen = preexp.l;
2443 size_t i;
2445 i = strlen(&exp.s[++exp.l]);
2446 locolen = n_MAX(locolen, i);
2447 exp.l += i;
2448 }while(exp.s[exp.l + 1] != '\0');
2450 shoup = n_string_reserve(n_string_trunc(shoup, 0),
2451 locolen + (locolen >> 1));
2453 /* Iterate (once again) over all results */
2454 scrwid = n_SCRNWIDTH_FOR_LISTS;
2455 lnlen = lncnt = 0;
2456 n_UNINIT(prefixlen, 0);
2457 n_UNINIT(lococp, NULL);
2458 n_UNINIT(c1, '\0');
2459 for(isfirst = TRU1; exp.l > 0; isfirst = FAL0, c1 = c2){
2460 size_t i;
2461 char const *fullpath;
2463 /* Next result */
2464 sub = exp;
2465 sub.l = i = strlen(sub.s);
2466 assert(exp.l >= i);
2467 if((exp.l -= i) > 0)
2468 --exp.l;
2469 exp.s += ++i;
2471 /* Separate dirname and basename */
2472 fullpath = sub.s;
2473 if(isfirst){
2474 char const *cp;
2476 if((cp = strrchr(fullpath, '/')) != NULL)
2477 prefixlen = PTR2SIZE(++cp - fullpath);
2478 else
2479 prefixlen = 0;
2481 if(prefixlen > 0 && prefixlen < sub.l){
2482 sub.l -= prefixlen;
2483 sub.s += prefixlen;
2486 /* We want case-insensitive sort-order */
2487 memset(&vic, 0, sizeof vic);
2488 vic.vic_indat = sub.s;
2489 vic.vic_inlen = sub.l;
2490 c2 = n_visual_info(&vic, n_VISUAL_INFO_ONE_CHAR) ? vic.vic_waccu
2491 : (ui8_t)*sub.s;
2492 #ifdef HAVE_C90AMEND1
2493 c2 = towlower(c2);
2494 #else
2495 c2 = lowerconv(c2);
2496 #endif
2498 /* Query longest common prefix along the way */
2499 if(isfirst){
2500 c1 = c2;
2501 lococp = sub.s;
2502 locolen = sub.l;
2503 }else if(locolen > 0){
2504 for(i = 0; i < locolen; ++i)
2505 if(lococp[i] != sub.s[i]){
2506 i = field_detect_clip(i, lococp, i);
2507 locolen = i;
2508 break;
2512 /* Prepare display */
2513 input = sub;
2514 shoup = n_shexp_quote(n_string_trunc(shoup, 0), &input,
2515 tlp->tl_quote_rndtrip);
2516 memset(&vic, 0, sizeof vic);
2517 vic.vic_indat = shoup->s_dat;
2518 vic.vic_inlen = shoup->s_len;
2519 if(!n_visual_info(&vic,
2520 n_VISUAL_INFO_SKIP_ERRORS | n_VISUAL_INFO_WIDTH_QUERY))
2521 vic.vic_vi_width = shoup->s_len;
2523 /* Put on screen. Indent follow lines of same sort slot.
2524 * Leave enough room for filename tagging */
2525 if((c1 = (c1 != c2))){
2526 #ifdef HAVE_C90AMEND1
2527 c1 = (iswalnum(c2) != 0);
2528 #else
2529 c1 = (alnumchar(c2) != 0);
2530 #endif
2532 if(isfirst || c1 ||
2533 scrwid < lnlen || scrwid - lnlen <= vic.vic_vi_width + 2){
2534 putc('\n', fp);
2535 if(scrwid < lnlen)
2536 ++lncnt;
2537 ++lncnt, lnlen = 0;
2538 if(!isfirst && !c1)
2539 goto jsep;
2540 }else if(lnlen > 0){
2541 jsep:
2542 fputs(" ", fp);
2543 lnlen += 2;
2545 fputs(n_string_cp(shoup), fp);
2546 lnlen += vic.vic_vi_width;
2548 /* Support the known filename tagging
2549 * XXX *line-editor-completion-filetype* or so */
2550 if(!lstat(fullpath, &sb)){
2551 char c = '\0';
2553 if(S_ISDIR(sb.st_mode))
2554 c = '/';
2555 else if(S_ISLNK(sb.st_mode))
2556 c = '@';
2557 # ifdef S_ISFIFO
2558 else if(S_ISFIFO(sb.st_mode))
2559 c = '|';
2560 # endif
2561 # ifdef S_ISSOCK
2562 else if(S_ISSOCK(sb.st_mode))
2563 c = '=';
2564 # endif
2565 # ifdef S_ISCHR
2566 else if(S_ISCHR(sb.st_mode))
2567 c = '%';
2568 # endif
2569 # ifdef S_ISBLK
2570 else if(S_ISBLK(sb.st_mode))
2571 c = '#';
2572 # endif
2574 if(c != '\0'){
2575 putc(c, fp);
2576 ++lnlen;
2580 putc('\n', fp);
2581 ++lncnt;
2583 page_or_print(fp, lncnt);
2584 if(fp != n_tty_fp)
2585 Fclose(fp);
2587 n_string_gut(shoup);
2589 /* A common prefix of 0 means we cannot provide the user any auto
2590 * completed characters for the multiple possible results.
2591 * Otherwise we can, so extend the visual line content by the common
2592 * prefix (in a reversible way) */
2593 f |= a_TTY_VF_BELL; /* XXX -> *line-editor-completion-bell*? or so */
2594 if(locolen > 0){
2595 (exp.s = n_UNCONST(lococp))[locolen] = '\0';
2596 exp.s -= prefixlen;
2597 exp.l = (locolen += prefixlen);
2598 goto jset;
2602 jnope:
2603 /* If we've provided a default content, but failed to expand, there is
2604 * nothing we can "revert to": drop that default again */
2605 if(set_savec){
2606 tlp->tl_savec.s = NULL;
2607 tlp->tl_savec.l = 0;
2609 f &= a_TTY_VF_BELL; /* XXX -> *line-editor-completion-bell*? or so */
2610 rv = 0;
2611 goto jleave;
2614 # ifdef HAVE_HISTORY
2615 static ui32_t
2616 a_tty__khist_shared(struct a_tty_line *tlp, struct a_tty_hist *thp){
2617 ui32_t f, rv;
2618 NYD2_ENTER;
2620 if(n_LIKELY((tlp->tl_hist = thp) != NULL)){
2621 char *cp;
2622 size_t i;
2624 i = thp->th_len;
2625 if(tlp->tl_goinflags & n_GO_INPUT_CTX_COMPOSE){
2626 ++i;
2627 if(!(thp->th_flags & a_TTY_HIST_CTX_COMPOSE))
2628 ++i;
2630 tlp->tl_defc.s = cp = n_autorec_alloc(i +1);
2631 if(tlp->tl_goinflags & n_GO_INPUT_CTX_COMPOSE){
2632 if((*cp = ok_vlook(escape)[0]) == '\0')
2633 *cp = n_ESCAPE[0];
2634 ++cp;
2635 if(!(thp->th_flags & a_TTY_HIST_CTX_COMPOSE))
2636 *cp++ = ':';
2638 memcpy(cp, thp->th_dat, thp->th_len +1);
2639 rv = tlp->tl_defc.l = i;
2641 f = (tlp->tl_count > 0) ? a_TTY_VF_MOD_DIRTY : a_TTY_VF_NONE;
2642 tlp->tl_count = tlp->tl_cursor = 0;
2643 }else{
2644 f = a_TTY_VF_BELL;
2645 rv = UI32_MAX;
2648 tlp->tl_vi_flags |= f;
2649 NYD2_LEAVE;
2650 return rv;
2653 static ui32_t
2654 a_tty_khist(struct a_tty_line *tlp, bool_t fwd){
2655 struct a_tty_hist *thp;
2656 ui32_t rv;
2657 NYD2_ENTER;
2659 /* If we're not in history mode yet, save line content */
2660 if((thp = tlp->tl_hist) == NULL){
2661 a_tty_cell2save(tlp);
2662 if((thp = a_tty.tg_hist) == NULL)
2663 goto jleave;
2664 if(fwd)
2665 while(thp->th_older != NULL)
2666 thp = thp->th_older;
2667 goto jleave;
2670 while((thp = fwd ? thp->th_younger : thp->th_older) != NULL){
2671 /* Applicable to input context? Compose mode swallows anything */
2672 if((tlp->tl_goinflags & n__GO_INPUT_CTX_MASK) == n_GO_INPUT_CTX_COMPOSE)
2673 break;
2674 if((thp->th_flags & a_TTY_HIST_CTX_MASK) != a_TTY_HIST_CTX_COMPOSE)
2675 break;
2677 jleave:
2678 rv = a_tty__khist_shared(tlp, thp);
2679 NYD2_LEAVE;
2680 return rv;
2683 static ui32_t
2684 a_tty_khist_search(struct a_tty_line *tlp, bool_t fwd){
2685 struct str orig_savec;
2686 ui32_t xoff, rv;
2687 struct a_tty_hist *thp;
2688 NYD2_ENTER;
2690 thp = NULL;
2692 /* We cannot complete an empty line */
2693 if(n_UNLIKELY(tlp->tl_count == 0)){
2694 /* XXX The upcoming hard reset would restore a set savec buffer,
2695 * XXX so forcefully reset that. A cleaner solution would be to
2696 * XXX reset it whenever a restore is no longer desired */
2697 tlp->tl_savec.s = NULL;
2698 tlp->tl_savec.l = 0;
2699 goto jleave;
2702 /* xxx It is a bit of a hack, but let's just hard-code the knowledge that
2703 * xxx in compose mode the first character is *escape* and must be skipped
2704 * xxx when searching the history. Alternatively we would need to have
2705 * xxx context-specific history search hooks which would do the search,
2706 * xxx which is overkill for our sole special case compose mode */
2707 if((tlp->tl_goinflags & n__GO_INPUT_CTX_MASK) == n_GO_INPUT_CTX_COMPOSE)
2708 xoff = 1;
2709 else
2710 xoff = 0;
2712 if((thp = tlp->tl_hist) == NULL){
2713 a_tty_cell2save(tlp);
2714 if((thp = a_tty.tg_hist) == NULL) /* TODO Should end "doing nothing"! */
2715 goto jleave;
2716 if(fwd)
2717 while(thp->th_older != NULL)
2718 thp = thp->th_older;
2719 orig_savec.s = NULL;
2720 orig_savec.l = 0; /* silence CC */
2721 }else{
2722 while((thp = fwd ? thp->th_younger : thp->th_older) != NULL){
2723 /* Applicable to input context? Compose mode swallows anything */
2724 if(xoff != 0)
2725 break;
2726 if((thp->th_flags & a_TTY_HIST_CTX_MASK) != a_TTY_HIST_CTX_COMPOSE)
2727 break;
2729 if(thp == NULL)
2730 goto jleave;
2732 orig_savec = tlp->tl_savec;
2735 if(xoff >= tlp->tl_savec.l){
2736 thp = NULL;
2737 goto jleave;
2740 if(orig_savec.s == NULL)
2741 a_tty_cell2save(tlp);
2743 for(; thp != NULL; thp = fwd ? thp->th_younger : thp->th_older){
2744 /* Applicable to input context? Compose mode swallows anything */
2745 if(xoff != 1 && (thp->th_flags & a_TTY_HIST_CTX_MASK) ==
2746 a_TTY_HIST_CTX_COMPOSE)
2747 continue;
2748 if(is_prefix(&tlp->tl_savec.s[xoff], thp->th_dat))
2749 break;
2752 if(orig_savec.s != NULL)
2753 tlp->tl_savec = orig_savec;
2754 jleave:
2755 rv = a_tty__khist_shared(tlp, thp);
2756 NYD2_LEAVE;
2757 return rv;
2759 # endif /* HAVE_HISTORY */
2761 static enum a_tty_fun_status
2762 a_tty_fun(struct a_tty_line *tlp, enum a_tty_bind_flags tbf, size_t *len){
2763 enum a_tty_fun_status rv;
2764 NYD2_ENTER;
2766 rv = a_TTY_FUN_STATUS_OK;
2767 # undef a_X
2768 # define a_X(N) a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## N)
2769 switch(a_TTY_BIND_FUN_REDUCE(tbf)){
2770 case a_X(BELL):
2771 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2772 break;
2773 case a_X(GO_BWD):
2774 a_tty_kleft(tlp);
2775 break;
2776 case a_X(GO_FWD):
2777 a_tty_kright(tlp);
2778 break;
2779 case a_X(GO_WORD_BWD):
2780 a_tty_kgow(tlp, -1);
2781 break;
2782 case a_X(GO_WORD_FWD):
2783 a_tty_kgow(tlp, +1);
2784 break;
2785 case a_X(GO_SCREEN_BWD):
2786 a_tty_kgoscr(tlp, -1);
2787 break;
2788 case a_X(GO_SCREEN_FWD):
2789 a_tty_kgoscr(tlp, +1);
2790 break;
2791 case a_X(GO_HOME):
2792 a_tty_khome(tlp, TRU1);
2793 break;
2794 case a_X(GO_END):
2795 a_tty_kend(tlp);
2796 break;
2797 case a_X(DEL_BWD):
2798 a_tty_kbs(tlp);
2799 break;
2800 case a_X(DEL_FWD):
2801 if(a_tty_kdel(tlp) < 0)
2802 rv = a_TTY_FUN_STATUS_END;
2803 break;
2804 case a_X(SNARF_WORD_BWD):
2805 a_tty_ksnarfw(tlp, FAL0);
2806 break;
2807 case a_X(SNARF_WORD_FWD):
2808 a_tty_ksnarfw(tlp, TRU1);
2809 break;
2810 case a_X(SNARF_END):
2811 a_tty_ksnarf(tlp, FAL0, TRU1);
2812 break;
2813 case a_X(SNARF_LINE):
2814 a_tty_ksnarf(tlp, TRU1, (tlp->tl_count == 0));
2815 break;
2817 case a_X(HIST_FWD):{
2818 # ifdef HAVE_HISTORY
2819 bool_t isfwd = TRU1;
2821 if(0){
2822 # endif
2823 /* FALLTHRU */
2824 case a_X(HIST_BWD):
2825 # ifdef HAVE_HISTORY
2826 isfwd = FAL0;
2828 if((*len = a_tty_khist(tlp, isfwd)) != UI32_MAX){
2829 rv = a_TTY_FUN_STATUS_RESTART;
2830 break;
2832 goto jreset;
2833 # endif
2835 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2836 break;
2838 case a_X(HIST_SRCH_FWD):{
2839 # ifdef HAVE_HISTORY
2840 bool_t isfwd = TRU1;
2842 if(0){
2843 # endif
2844 /* FALLTHRU */
2845 case a_X(HIST_SRCH_BWD):
2846 # ifdef HAVE_HISTORY
2847 isfwd = FAL0;
2849 if((*len = a_tty_khist_search(tlp, isfwd)) != UI32_MAX){
2850 rv = a_TTY_FUN_STATUS_RESTART;
2851 break;
2853 goto jreset;
2854 # else
2855 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2856 # endif
2857 }break;
2859 case a_X(REPAINT):
2860 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2861 break;
2862 case a_X(QUOTE_RNDTRIP):
2863 tlp->tl_quote_rndtrip = !tlp->tl_quote_rndtrip;
2864 break;
2865 case a_X(PROMPT_CHAR):{
2866 wchar_t wc;
2868 if((wc = a_tty_vinuni(tlp)) > 0)
2869 a_tty_kother(tlp, wc);
2870 }break;
2871 case a_X(COMPLETE):
2872 if((*len = a_tty_kht(tlp)) > 0)
2873 rv = a_TTY_FUN_STATUS_RESTART;
2874 break;
2876 case a_X(PASTE):
2877 if(tlp->tl_pastebuf.l > 0)
2878 *len = (tlp->tl_defc = tlp->tl_pastebuf).l;
2879 else
2880 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2881 break;
2884 case a_X(CANCEL):
2885 /* Normally this just causes a restart and thus resets the state
2886 * machine */
2887 if(tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2889 # ifdef HAVE_KEY_BINDINGS
2890 tlp->tl_bind_takeover = '\0';
2891 # endif
2892 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2893 rv = a_TTY_FUN_STATUS_RESTART;
2894 break;
2896 case a_X(RESET):
2897 if(tlp->tl_count == 0 && tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2898 # ifdef HAVE_KEY_BINDINGS
2899 tlp->tl_bind_takeover = '\0';
2900 # endif
2901 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY | a_TTY_VF_BELL;
2902 break;
2903 }else if(0){
2904 case a_X(FULLRESET):
2905 tlp->tl_savec.s = tlp->tl_defc.s = NULL;
2906 tlp->tl_savec.l = tlp->tl_defc.l = 0;
2907 tlp->tl_defc_cursor_byte = 0;
2908 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2910 jreset:
2911 # ifdef HAVE_KEY_BINDINGS
2912 tlp->tl_bind_takeover = '\0';
2913 # endif
2914 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2915 tlp->tl_cursor = tlp->tl_count = 0;
2916 # ifdef HAVE_HISTORY
2917 tlp->tl_hist = NULL;
2918 # endif
2919 if((*len = tlp->tl_savec.l) != 0){
2920 tlp->tl_defc = tlp->tl_savec;
2921 tlp->tl_savec.s = NULL;
2922 tlp->tl_savec.l = 0;
2923 }else
2924 *len = tlp->tl_defc.l;
2925 rv = a_TTY_FUN_STATUS_RESTART;
2926 break;
2928 default:
2929 case a_X(COMMIT):
2930 rv = a_TTY_FUN_STATUS_COMMIT;
2931 break;
2933 # undef a_X
2935 NYD2_LEAVE;
2936 return rv;
2939 static ssize_t
2940 a_tty_readline(struct a_tty_line *tlp, size_t len, bool_t *histok_or_null
2941 n_MEMORY_DEBUG_ARGS){
2942 /* We want to save code, yet we may have to incorporate a lines'
2943 * default content and / or default input to switch back to after some
2944 * history movement; let "len > 0" mean "have to display some data
2945 * buffer" -> a_BUFMODE, and only otherwise read(2) it */
2946 mbstate_t ps[2];
2947 char cbuf_base[MB_LEN_MAX * 2], *cbuf, *cbufp;
2948 ssize_t rv;
2949 struct a_tty_bind_tree *tbtp;
2950 wchar_t wc;
2951 enum a_tty_bind_flags tbf;
2952 enum {a_NONE, a_WAS_HERE = 1<<0, a_BUFMODE = 1<<1, a_MAYBEFUN = 1<<2,
2953 a_TIMEOUT = 1<<3, a_TIMEOUT_EXPIRED = 1<<4,
2954 a_TIMEOUT_MASK = a_TIMEOUT | a_TIMEOUT_EXPIRED,
2955 a_READ_LOOP_MASK = ~(a_WAS_HERE | a_MAYBEFUN | a_TIMEOUT_MASK)
2956 } flags;
2957 NYD_ENTER;
2959 n_UNINIT(rv, 0);
2960 # ifdef HAVE_KEY_BINDINGS
2961 assert(tlp->tl_bind_takeover == '\0');
2962 # endif
2963 jrestart:
2964 memset(ps, 0, sizeof ps);
2965 flags = a_NONE;
2966 tlp->tl_vi_flags |= a_TTY_VF_REFRESH | a_TTY_VF_SYNC;
2968 jinput_loop:
2969 for(;;){
2970 if(len != 0)
2971 flags |= a_BUFMODE;
2973 /* Ensure we have valid pointers, and room for grow */
2974 a_tty_check_grow(tlp, ((flags & a_BUFMODE) ? (ui32_t)len : 1)
2975 n_MEMORY_DEBUG_ARGSCALL);
2977 /* Handle visual state flags, except in buffer mode */
2978 if(!(flags & a_BUFMODE) && (tlp->tl_vi_flags & a_TTY_VF_ALL_MASK))
2979 if(!a_tty_vi_refresh(tlp)){
2980 rv = -1;
2981 goto jleave;
2984 /* Ready for messing around.
2985 * Normal read(2)? Else buffer mode: speed this one up */
2986 if(!(flags & a_BUFMODE)){
2987 cbufp =
2988 cbuf = cbuf_base;
2989 }else{
2990 assert(tlp->tl_defc.l > 0 && tlp->tl_defc.s != NULL);
2991 assert(tlp->tl_defc.l >= len);
2992 cbufp =
2993 cbuf = tlp->tl_defc.s + (tlp->tl_defc.l - len);
2994 cbufp += len;
2997 /* Read in the next complete multibyte character */
2998 /* C99 */{
2999 # ifdef HAVE_KEY_BINDINGS
3000 struct a_tty_bind_tree *xtbtp;
3001 struct inseq{
3002 struct inseq *last;
3003 struct inseq *next;
3004 struct a_tty_bind_tree *tbtp;
3005 } *isp_head, *isp;
3007 isp_head = isp = NULL;
3008 # endif
3010 for(flags &= a_READ_LOOP_MASK;;){
3011 # ifdef HAVE_KEY_BINDINGS
3012 if(!(flags & a_BUFMODE) && tlp->tl_bind_takeover != '\0'){
3013 wc = tlp->tl_bind_takeover;
3014 tlp->tl_bind_takeover = '\0';
3015 }else
3016 # endif
3018 if(!(flags & a_BUFMODE)){
3019 /* Let me at least once dream of iomon(itor), timer with
3020 * one-shot, enwrapped with key_event and key_sequence_event,
3021 * all driven by an event_loop */
3022 /* TODO v15 Until we have SysV signal handling all through we
3023 * TODO need to temporarily adjust our BSD signal handler with
3024 * TODO a SysV one, here */
3025 n_sighdl_t otstp, ottin, ottou;
3027 otstp = n_signal(SIGTSTP, &a_tty_signal);
3028 ottin = n_signal(SIGTTIN, &a_tty_signal);
3029 ottou = n_signal(SIGTTOU, &a_tty_signal);
3030 # ifdef HAVE_KEY_BINDINGS
3031 flags &= ~a_TIMEOUT_MASK;
3032 if(isp != NULL && (tbtp = isp->tbtp)->tbt_isseq &&
3033 !tbtp->tbt_isseq_trail){
3034 a_tty_term_rawmode_timeout(tlp, TRU1);
3035 flags |= a_TIMEOUT;
3037 # endif
3039 while((rv = read(STDIN_FILENO, cbufp, 1)) < 1){
3040 if(rv == -1){
3041 if(n_err_no == n_ERR_INTR){
3042 if((tlp->tl_vi_flags & a_TTY_VF_MOD_DIRTY) &&
3043 !a_tty_vi_refresh(tlp))
3044 break;
3045 continue;
3047 break;
3050 # ifdef HAVE_KEY_BINDINGS
3051 /* Timeout expiration */
3052 if(rv == 0){
3053 assert(flags & a_TIMEOUT);
3054 assert(isp != NULL);
3055 a_tty_term_rawmode_timeout(tlp, FAL0);
3057 /* Something "atomic" broke. Maybe the current one can
3058 * also be terminated already, by itself? xxx really? */
3059 if((tbtp = isp->tbtp)->tbt_bind != NULL){
3060 tlp->tl_bind_takeover = wc;
3061 goto jhave_bind;
3064 /* Or, maybe there is a second path without a timeout;
3065 * this should be covered by .tbt_isseq_trail, but then
3066 * again a single-layer implementation cannot "know" */
3067 for(xtbtp = tbtp; (xtbtp = xtbtp->tbt_sibling) != NULL;)
3068 if(xtbtp->tbt_char == tbtp->tbt_char){
3069 assert(!xtbtp->tbt_isseq);
3070 break;
3072 /* Lay down on read(2)? */
3073 if(xtbtp != NULL)
3074 continue;
3075 goto jtake_over;
3077 # endif /* HAVE_KEY_BINDINGS */
3080 # ifdef HAVE_KEY_BINDINGS
3081 if(flags & a_TIMEOUT)
3082 a_tty_term_rawmode_timeout(tlp, FAL0);
3083 # endif
3084 safe_signal(SIGTSTP, otstp);
3085 safe_signal(SIGTTIN, ottin);
3086 safe_signal(SIGTTOU, ottou);
3087 if(rv < 0)
3088 goto jleave;
3090 ++cbufp;
3093 rv = (ssize_t)mbrtowc(&wc, cbuf, PTR2SIZE(cbufp - cbuf), &ps[0]);
3094 if(rv <= 0){
3095 /* Any error during buffer mode can only result in a hard
3096 * reset; Otherwise, if it's a hard error, or if too many
3097 * redundant shift sequences overflow our buffer: perform
3098 * hard reset */
3099 if((flags & a_BUFMODE) || rv == -1 ||
3100 sizeof cbuf_base == PTR2SIZE(cbufp - cbuf)){
3101 a_tty_fun(tlp, a_TTY_BIND_FUN_FULLRESET, &len);
3102 goto jrestart;
3104 /* Otherwise, due to the way we deal with the buffer, we need
3105 * to restore the mbstate_t from before this conversion */
3106 ps[0] = ps[1];
3107 continue;
3109 cbufp = cbuf;
3110 ps[1] = ps[0];
3113 /* Normal read(2)ing is subject to detection of key-bindings */
3114 # ifdef HAVE_KEY_BINDINGS
3115 if(!(flags & a_BUFMODE)){
3116 /* Check for special bypass functions before we try to embed
3117 * this character into the tree */
3118 if(n_uasciichar(wc)){
3119 char c;
3120 char const *cp;
3122 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_prompt_char)[0];
3123 *cp != '\0'; ++cp){
3124 if(c == *cp){
3125 wc = a_tty_vinuni(tlp);
3126 break;
3129 if(wc == '\0'){
3130 tlp->tl_vi_flags |= a_TTY_VF_BELL;
3131 goto jinput_loop;
3134 if(n_uasciichar(wc))
3135 flags |= a_MAYBEFUN;
3136 else
3137 flags &= ~a_MAYBEFUN;
3139 /* Search for this character in the bind tree */
3140 tbtp = (isp != NULL) ? isp->tbtp->tbt_childs
3141 : (*tlp->tl_bind_tree_hmap)[wc % HSHSIZE];
3142 for(; tbtp != NULL; tbtp = tbtp->tbt_sibling){
3143 if(tbtp->tbt_char == wc){
3144 struct inseq *nisp;
3146 /* If this one cannot continue we're likely finished! */
3147 if(tbtp->tbt_childs == NULL){
3148 assert(tbtp->tbt_bind != NULL);
3149 tbf = tbtp->tbt_bind->tbc_flags;
3150 goto jmle_fun;
3153 /* This needs to read more characters */
3154 nisp = n_autorec_alloc(sizeof *nisp);
3155 if((nisp->last = isp) == NULL)
3156 isp_head = nisp;
3157 else
3158 isp->next = nisp;
3159 nisp->next = NULL;
3160 nisp->tbtp = tbtp;
3161 isp = nisp;
3162 flags &= ~a_WAS_HERE;
3163 break;
3166 if(tbtp != NULL)
3167 continue;
3169 /* Was there a binding active, but couldn't be continued? */
3170 if(isp != NULL){
3171 /* A binding had a timeout, it didn't expire, but we saw
3172 * something non-expected. Something "atomic" broke.
3173 * Maybe there is a second path without a timeout, that
3174 * continues like we've seen it. I.e., it may just have been
3175 * the user, typing too fast. We definitely want to allow
3176 * bindings like \e,d etc. to succeed: users are so used to
3177 * them that a timeout cannot be the mechanism to catch up!
3178 * A single-layer implementation cannot "know" */
3179 if((tbtp = isp->tbtp)->tbt_isseq && (isp->last == NULL ||
3180 !(xtbtp = isp->last->tbtp)->tbt_isseq ||
3181 xtbtp->tbt_isseq_trail)){
3182 for(xtbtp = (tbtp = isp->tbtp);
3183 (xtbtp = xtbtp->tbt_sibling) != NULL;)
3184 if(xtbtp->tbt_char == tbtp->tbt_char){
3185 assert(!xtbtp->tbt_isseq);
3186 break;
3188 if(xtbtp != NULL){
3189 isp->tbtp = xtbtp;
3190 tlp->tl_bind_takeover = wc;
3191 continue;
3195 /* Check for CANCEL shortcut now */
3196 if(flags & a_MAYBEFUN){
3197 char c;
3198 char const *cp;
3200 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_cancel)[0];
3201 *cp != '\0'; ++cp)
3202 if(c == *cp){
3203 tbf = a_TTY_BIND_FUN_INTERNAL |a_TTY_BIND_FUN_CANCEL;
3204 goto jmle_fun;
3208 /* So: maybe the current sequence can be terminated here? */
3209 if((tbtp = isp->tbtp)->tbt_bind != NULL){
3210 jhave_bind:
3211 tbf = tbtp->tbt_bind->tbc_flags;
3212 jmle_fun:
3213 if(tbf & a_TTY_BIND_FUN_INTERNAL){
3214 switch(a_tty_fun(tlp, tbf, &len)){
3215 case a_TTY_FUN_STATUS_OK:
3216 goto jinput_loop;
3217 case a_TTY_FUN_STATUS_COMMIT:
3218 goto jdone;
3219 case a_TTY_FUN_STATUS_RESTART:
3220 goto jrestart;
3221 case a_TTY_FUN_STATUS_END:
3222 rv = -1;
3223 goto jleave;
3225 assert(0);
3226 }else if(tbtp->tbt_bind->tbc_flags & a_TTY_BIND_NOCOMMIT){
3227 struct a_tty_bind_ctx *tbcp;
3229 tbcp = tbtp->tbt_bind;
3230 memcpy(tlp->tl_defc.s = n_autorec_alloc(
3231 (tlp->tl_defc.l = len = tbcp->tbc_exp_len) +1),
3232 tbcp->tbc_exp, tbcp->tbc_exp_len +1);
3233 goto jrestart;
3234 }else{
3235 cbufp = tbtp->tbt_bind->tbc_exp;
3236 goto jinject_input;
3241 /* Otherwise take over all chars "as is" */
3242 jtake_over:
3243 for(; isp_head != NULL; isp_head = isp_head->next)
3244 if(a_tty_kother(tlp, isp_head->tbtp->tbt_char)){
3245 /* FIXME */
3247 /* And the current one too */
3248 goto jkother;
3250 # endif /* HAVE_KEY_BINDINGS */
3252 if((flags & a_BUFMODE) && (len -= (size_t)rv) == 0){
3253 /* Buffer mode completed */
3254 tlp->tl_defc.s = NULL;
3255 tlp->tl_defc.l = 0;
3256 flags &= ~a_BUFMODE;
3258 break;
3261 # ifndef HAVE_KEY_BINDINGS
3262 /* Don't interpret control bytes during buffer mode.
3263 * Otherwise, if it's a control byte check whether it is a MLE
3264 * function. Remarks: initially a complete duplicate to be able to
3265 * switch(), later converted to simply iterate over (an #ifdef'd
3266 * subset of) the MLE base_tuple table in order to have "a SPOF" */
3267 if(cbuf == cbuf_base && n_uasciichar(wc) && cntrlchar((char)wc)){
3268 struct a_tty_bind_builtin_tuple const *tbbtp, *tbbtp_max;
3269 char c;
3271 c = (char)wc ^ 0x40;
3272 tbbtp = a_tty_bind_base_tuples;
3273 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_base_tuples)];
3274 jbuiltin_redo:
3275 for(; tbbtp < tbbtp_max; ++tbbtp){
3276 /* Assert default_tuple table is properly subset'ed */
3277 assert(tbbtp->tbdt_iskey);
3278 if(tbbtp->tbbt_ckey == c){
3279 if(tbbtp->tbbt_exp[0] == '\0'){
3280 tbf = a_TTY_BIND_FUN_EXPAND((ui8_t)tbbtp->tbbt_exp[1]);
3281 switch(a_tty_fun(tlp, tbf, &len)){
3282 case a_TTY_FUN_STATUS_OK:
3283 goto jinput_loop;
3284 case a_TTY_FUN_STATUS_COMMIT:
3285 goto jdone;
3286 case a_TTY_FUN_STATUS_RESTART:
3287 goto jrestart;
3288 case a_TTY_FUN_STATUS_END:
3289 rv = -1;
3290 goto jleave;
3292 assert(0);
3293 }else{
3294 cbufp = tbbtp->tbbt_exp;
3295 goto jinject_input;
3299 if(tbbtp ==
3300 &a_tty_bind_base_tuples[n_NELEM(a_tty_bind_base_tuples)]){
3301 tbbtp = a_tty_bind_default_tuples;
3302 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_default_tuples)];
3303 goto jbuiltin_redo;
3306 # endif /* !HAVE_KEY_BINDINGS */
3308 # ifdef HAVE_KEY_BINDINGS
3309 jkother:
3310 # endif
3311 if(a_tty_kother(tlp, wc)){
3312 /* Don't clear the history during buffer mode.. */
3313 # ifdef HAVE_HISTORY
3314 if(!(flags & a_BUFMODE) && cbuf == cbuf_base)
3315 tlp->tl_hist = NULL;
3316 # endif
3321 /* We have a completed input line, convert the struct cell data to its
3322 * plain character equivalent */
3323 jdone:
3324 rv = a_tty_cell2dat(tlp);
3325 jleave:
3326 putc('\n', n_tty_fp);
3327 fflush(n_tty_fp);
3328 NYD_LEAVE;
3329 return rv;
3331 jinject_input:{
3332 size_t i;
3334 hold_all_sigs(); /* XXX v15 drop */
3335 i = a_tty_cell2dat(tlp);
3336 n_go_input_inject(n_GO_INPUT_INJECT_NONE, tlp->tl_line.cbuf, i);
3337 i = strlen(cbufp) +1;
3338 if(i >= *tlp->tl_x_bufsize){
3339 *tlp->tl_x_buf = (n_realloc)(*tlp->tl_x_buf, i n_MEMORY_DEBUG_ARGSCALL);
3340 *tlp->tl_x_bufsize = i;
3342 memcpy(*tlp->tl_x_buf, cbufp, i);
3343 rele_all_sigs(); /* XXX v15 drop */
3344 if(histok_or_null != NULL)
3345 *histok_or_null = FAL0;
3346 rv = (ssize_t)--i;
3348 goto jleave;
3351 # ifdef HAVE_KEY_BINDINGS
3352 static enum n_go_input_flags
3353 a_tty_bind_ctx_find(char const *name){
3354 enum n_go_input_flags rv;
3355 struct a_tty_bind_ctx_map const *tbcmp;
3356 NYD2_ENTER;
3358 tbcmp = a_tty_bind_ctx_maps;
3359 do if(!asccasecmp(tbcmp->tbcm_name, name)){
3360 rv = tbcmp->tbcm_ctx;
3361 goto jleave;
3362 }while(PTRCMP(++tbcmp, <,
3363 &a_tty_bind_ctx_maps[n_NELEM(a_tty_bind_ctx_maps)]));
3365 rv = (enum n_go_input_flags)-1;
3366 jleave:
3367 NYD2_LEAVE;
3368 return rv;
3371 static bool_t
3372 a_tty_bind_create(struct a_tty_bind_parse_ctx *tbpcp, bool_t replace){
3373 struct a_tty_bind_ctx *tbcp;
3374 bool_t rv;
3375 NYD2_ENTER;
3377 rv = FAL0;
3379 if(!a_tty_bind_parse(TRU1, tbpcp))
3380 goto jleave;
3382 /* Since we use a single buffer for it all, need to replace as such */
3383 if(tbpcp->tbpc_tbcp != NULL){
3384 if(!replace)
3385 goto jleave;
3386 a_tty_bind_del(tbpcp);
3387 }else if(a_tty.tg_bind_cnt == UI32_MAX){
3388 n_err(_("`bind': maximum number of bindings already established\n"));
3389 goto jleave;
3392 /* C99 */{
3393 size_t i, j;
3395 tbcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_tty_bind_ctx, tbc__buf) +
3396 tbpcp->tbpc_seq_len + tbpcp->tbpc_exp.l +
3397 n_MAX(sizeof(si32_t), sizeof(wc_t)) + tbpcp->tbpc_cnv_len +3);
3398 if(tbpcp->tbpc_ltbcp != NULL){
3399 tbcp->tbc_next = tbpcp->tbpc_ltbcp->tbc_next;
3400 tbpcp->tbpc_ltbcp->tbc_next = tbcp;
3401 }else{
3402 enum n_go_input_flags gif;
3404 gif = tbpcp->tbpc_flags & n__GO_INPUT_CTX_MASK;
3405 tbcp->tbc_next = a_tty.tg_bind[gif];
3406 a_tty.tg_bind[gif] = tbcp;
3408 memcpy(tbcp->tbc_seq = &tbcp->tbc__buf[0],
3409 tbpcp->tbpc_seq, i = (tbcp->tbc_seq_len = tbpcp->tbpc_seq_len) +1);
3410 memcpy(tbcp->tbc_exp = &tbcp->tbc__buf[i],
3411 tbpcp->tbpc_exp.s, j = (tbcp->tbc_exp_len = tbpcp->tbpc_exp.l) +1);
3412 i += j;
3413 i = (i + tbpcp->tbpc_cnv_align_mask) & ~tbpcp->tbpc_cnv_align_mask;
3414 memcpy(tbcp->tbc_cnv = &tbcp->tbc__buf[i],
3415 tbpcp->tbpc_cnv, (tbcp->tbc_cnv_len = tbpcp->tbpc_cnv_len) +1);
3416 tbcp->tbc_flags = tbpcp->tbpc_flags;
3419 /* Directly resolve any termcap(5) symbol if we are already setup */
3420 if((n_psonce & n_PSO_STARTED) &&
3421 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
3422 a_TTY_BIND_RESOLVE)
3423 a_tty_bind_resolve(tbcp);
3425 ++a_tty.tg_bind_cnt;
3426 /* If this binding is usable invalidate the key input lookup trees */
3427 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3428 a_tty.tg_bind_isdirty = TRU1;
3429 rv = TRU1;
3430 jleave:
3431 NYD2_LEAVE;
3432 return rv;
3435 static bool_t
3436 a_tty_bind_parse(bool_t isbindcmd, struct a_tty_bind_parse_ctx *tbpcp){
3437 enum{a_TRUE_RV = a_TTY__BIND_LAST<<1};
3439 struct n_visual_info_ctx vic;
3440 struct str shin_save, shin;
3441 struct n_string shou, *shoup;
3442 size_t i;
3443 struct kse{
3444 struct kse *next;
3445 char *seq_dat;
3446 wc_t *cnv_dat;
3447 ui32_t seq_len;
3448 ui32_t cnv_len; /* High bit set if a termap to be resolved */
3449 ui32_t calc_cnv_len; /* Ditto, but aligned etc. */
3450 ui8_t kse__dummy[4];
3451 } *head, *tail;
3452 ui32_t f;
3453 NYD2_ENTER;
3454 n_LCTA(UICMP(64, a_TRUE_RV, <, UI32_MAX),
3455 "Flag bits excess storage datatype");
3457 f = n_GO_INPUT_NONE;
3458 shoup = n_string_creat_auto(&shou);
3459 head = tail = NULL;
3461 /* Parse the key-sequence */
3462 for(shin.s = n_UNCONST(tbpcp->tbpc_in_seq), shin.l = UIZ_MAX;;){
3463 struct kse *ep;
3464 enum n_shexp_state shs;
3466 shin_save = shin;
3467 shs = n_shexp_parse_token((n_SHEXP_PARSE_TRUNC |
3468 n_SHEXP_PARSE_TRIM_SPACE | n_SHEXP_PARSE_IGNORE_EMPTY |
3469 n_SHEXP_PARSE_IFS_IS_COMMA), shoup, &shin, NULL);
3470 if(shs & n_SHEXP_STATE_ERR_UNICODE){
3471 f |= a_TTY_BIND_DEFUNCT;
3472 if(isbindcmd && (n_poption & n_PO_D_V))
3473 n_err(_("`%s': \\uNICODE not available in locale: %s\n"),
3474 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3476 if((shs & n_SHEXP_STATE_ERR_MASK) & ~n_SHEXP_STATE_ERR_UNICODE){
3477 n_err(_("`%s': failed to parse key-sequence: %s\n"),
3478 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3479 goto jleave;
3481 if((shs & (n_SHEXP_STATE_OUTPUT | n_SHEXP_STATE_STOP)) ==
3482 n_SHEXP_STATE_STOP)
3483 break;
3485 ep = n_autorec_alloc(sizeof *ep);
3486 if(head == NULL)
3487 head = ep;
3488 else
3489 tail->next = ep;
3490 tail = ep;
3491 ep->next = NULL;
3492 if(!(shs & n_SHEXP_STATE_ERR_UNICODE)){
3493 i = strlen(ep->seq_dat = n_shexp_quote_cp(n_string_cp(shoup), TRU1));
3494 if(i >= SI32_MAX - 1)
3495 goto jelen;
3496 ep->seq_len = (ui32_t)i;
3497 }else{
3498 /* Otherwise use the original buffer, _we_ can only quote it the wrong
3499 * way (e.g., an initial $'\u3a' becomes '\u3a'), _then_ */
3500 if((i = shin_save.l - shin.l) >= SI32_MAX - 1)
3501 goto jelen;
3502 ep->seq_len = (ui32_t)i;
3503 ep->seq_dat = savestrbuf(shin_save.s, i);
3506 memset(&vic, 0, sizeof vic);
3507 vic.vic_inlen = shoup->s_len;
3508 vic.vic_indat = shoup->s_dat;
3509 if(!n_visual_info(&vic,
3510 n_VISUAL_INFO_WOUT_CREATE | n_VISUAL_INFO_WOUT_SALLOC)){
3511 n_err(_("`%s': key-sequence seems to contain invalid "
3512 "characters: %s: %s\n"),
3513 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
3514 f |= a_TTY_BIND_DEFUNCT;
3515 goto jleave;
3516 }else if(vic.vic_woulen == 0 ||
3517 vic.vic_woulen >= (SI32_MAX - 2) / sizeof(wc_t)){
3518 jelen:
3519 n_err(_("`%s': length of key-sequence unsupported: %s: %s\n"),
3520 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
3521 f |= a_TTY_BIND_DEFUNCT;
3522 goto jleave;
3524 ep->cnv_dat = vic.vic_woudat;
3525 ep->cnv_len = (ui32_t)vic.vic_woulen;
3527 /* A termcap(5)/terminfo(5) identifier? */
3528 if(ep->cnv_len > 1 && ep->cnv_dat[0] == ':'){
3529 i = --ep->cnv_len, ++ep->cnv_dat;
3530 # if 0 /* ndef HAVE_TERMCAP xxx User can, via *termcap*! */
3531 if(n_poption & n_PO_D_V)
3532 n_err(_("`%s': no termcap(5)/terminfo(5) support: %s: %s\n"),
3533 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3534 f |= a_TTY_BIND_DEFUNCT;
3535 # endif
3536 if(i > a_TTY_BIND_CAPNAME_MAX){
3537 n_err(_("`%s': termcap(5)/terminfo(5) name too long: %s: %s\n"),
3538 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3539 f |= a_TTY_BIND_DEFUNCT;
3541 while(i > 0)
3542 /* (We store it as char[]) */
3543 if((ui32_t)ep->cnv_dat[--i] & ~0x7Fu){
3544 n_err(_("`%s': invalid termcap(5)/terminfo(5) name content: "
3545 "%s: %s\n"),
3546 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3547 f |= a_TTY_BIND_DEFUNCT;
3548 break;
3550 ep->cnv_len |= SI32_MIN; /* Needs resolve */
3551 f |= a_TTY_BIND_RESOLVE;
3554 if(shs & n_SHEXP_STATE_STOP)
3555 break;
3558 if(head == NULL){
3559 jeempty:
3560 n_err(_("`%s': effectively empty key-sequence: %s\n"),
3561 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3562 goto jleave;
3565 if(isbindcmd) /* (Or always, just "1st time init") */
3566 tbpcp->tbpc_cnv_align_mask = n_MAX(sizeof(si32_t), sizeof(wc_t)) - 1;
3568 /* C99 */{
3569 struct a_tty_bind_ctx *ltbcp, *tbcp;
3570 char *cpbase, *cp, *cnv;
3571 size_t sl, cl;
3573 /* Unite the parsed sequence(s) into single string representations */
3574 for(sl = cl = 0, tail = head; tail != NULL; tail = tail->next){
3575 sl += tail->seq_len + 1;
3577 if(!isbindcmd)
3578 continue;
3580 /* Preserve room for terminal capabilities to be resolved.
3581 * Above we have ensured the buffer will fit in these calculations */
3582 if((i = tail->cnv_len) & SI32_MIN){
3583 /* For now
3584 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[]+NUL;}
3585 * later
3586 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3587 n_LCTAV(n_ISPOW2(a_TTY_BIND_CAPEXP_ROUNDUP));
3588 n_LCTA(a_TTY_BIND_CAPEXP_ROUNDUP >= sizeof(wc_t),
3589 "Aligning on this constant does not properly align wc_t");
3590 i &= SI32_MAX;
3591 i *= sizeof(wc_t);
3592 i += sizeof(si32_t);
3593 if(i < a_TTY_BIND_CAPEXP_ROUNDUP)
3594 i = (i + (a_TTY_BIND_CAPEXP_ROUNDUP - 1)) &
3595 ~(a_TTY_BIND_CAPEXP_ROUNDUP - 1);
3596 }else
3597 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3598 i *= sizeof(wc_t);
3599 i += sizeof(si32_t) + sizeof(wc_t); /* (buf_len_iscap, NUL) */
3600 cl += i;
3601 if(tail->cnv_len & SI32_MIN){
3602 tail->cnv_len &= SI32_MAX;
3603 i |= SI32_MIN;
3605 tail->calc_cnv_len = (ui32_t)i;
3607 --sl;
3609 tbpcp->tbpc_seq_len = sl;
3610 tbpcp->tbpc_cnv_len = cl;
3611 /* C99 */{
3612 size_t j;
3614 j = i = sl + 1; /* Room for comma separator */
3615 if(isbindcmd){
3616 i = (i + tbpcp->tbpc_cnv_align_mask) & ~tbpcp->tbpc_cnv_align_mask;
3617 j = i;
3618 i += cl;
3620 tbpcp->tbpc_seq = cp = cpbase = n_autorec_alloc(i);
3621 tbpcp->tbpc_cnv = cnv = &cpbase[j];
3624 for(tail = head; tail != NULL; tail = tail->next){
3625 memcpy(cp, tail->seq_dat, tail->seq_len);
3626 cp += tail->seq_len;
3627 *cp++ = ',';
3629 if(isbindcmd){
3630 char * const save_cnv = cnv;
3632 n_UNALIGN(si32_t*,cnv)[0] = (si32_t)(i = tail->calc_cnv_len);
3633 cnv += sizeof(si32_t);
3634 if(i & SI32_MIN){
3635 /* For now
3636 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];}
3637 * later
3638 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[];} */
3639 n_UNALIGN(si32_t*,cnv)[0] = tail->cnv_len;
3640 cnv += sizeof(si32_t);
3642 i = tail->cnv_len * sizeof(wc_t);
3643 memcpy(cnv, tail->cnv_dat, i);
3644 cnv += i;
3645 *n_UNALIGN(wc_t*,cnv) = '\0';
3647 cnv = save_cnv + (tail->calc_cnv_len & SI32_MAX);
3650 *--cp = '\0';
3652 /* Search for a yet existing identical mapping */
3653 /* C99 */{
3654 enum n_go_input_flags gif;
3656 gif = tbpcp->tbpc_flags & n__GO_INPUT_CTX_MASK;
3658 for(ltbcp = NULL, tbcp = a_tty.tg_bind[gif]; tbcp != NULL;
3659 ltbcp = tbcp, tbcp = tbcp->tbc_next)
3660 if(tbcp->tbc_seq_len == sl && !memcmp(tbcp->tbc_seq, cpbase, sl)){
3661 tbpcp->tbpc_tbcp = tbcp;
3662 break;
3665 tbpcp->tbpc_ltbcp = ltbcp;
3666 tbpcp->tbpc_flags |= (f & a_TTY__BIND_MASK);
3669 /* Create single string expansion if so desired */
3670 if(isbindcmd){
3671 char *exp;
3673 exp = tbpcp->tbpc_exp.s;
3675 i = tbpcp->tbpc_exp.l;
3676 if(i > 0 && exp[i - 1] == '@'){
3677 while(--i > 0){
3678 if(!blankspacechar(exp[i - 1]))
3679 break;
3681 if(i == 0)
3682 goto jeempty;
3684 exp[tbpcp->tbpc_exp.l = i] = '\0';
3685 tbpcp->tbpc_flags |= a_TTY_BIND_NOCOMMIT;
3688 /* Reverse solidus cannot be placed last in expansion to avoid (at the
3689 * time of this writing) possible problems with newline escaping.
3690 * Don't care about (un)even number thereof */
3691 if(i > 0 && exp[i - 1] == '\\'){
3692 n_err(_("`%s': reverse solidus cannot be last in expansion: %s\n"),
3693 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3694 goto jleave;
3697 /* It may map to an internal MLE command! */
3698 for(i = 0; i < n_NELEM(a_tty_bind_fun_names); ++i)
3699 if(!asccasecmp(exp, a_tty_bind_fun_names[i])){
3700 tbpcp->tbpc_flags |= a_TTY_BIND_FUN_EXPAND(i) |
3701 a_TTY_BIND_FUN_INTERNAL |
3702 (head->next == NULL ? a_TTY_BIND_MLE1CNTRL : 0);
3703 if((n_poption & n_PO_D_V) &&
3704 (tbpcp->tbpc_flags & a_TTY_BIND_NOCOMMIT))
3705 n_err(_("`%s': MLE commands can't be made editable via @: %s\n"),
3706 tbpcp->tbpc_cmd, exp);
3707 tbpcp->tbpc_flags &= ~a_TTY_BIND_NOCOMMIT;
3708 break;
3712 f |= a_TRUE_RV; /* TODO because we only now true and false; DEFUNCT.. */
3713 jleave:
3714 n_string_gut(shoup);
3715 NYD2_LEAVE;
3716 return (f & a_TRUE_RV) != 0;
3719 static void
3720 a_tty_bind_resolve(struct a_tty_bind_ctx *tbcp){
3721 char capname[a_TTY_BIND_CAPNAME_MAX +1];
3722 struct n_termcap_value tv;
3723 size_t len;
3724 bool_t isfirst; /* TODO For now: first char must be control! */
3725 char *cp, *next;
3726 NYD2_ENTER;
3728 n_UNINIT(next, NULL);
3729 for(cp = tbcp->tbc_cnv, isfirst = TRU1, len = tbcp->tbc_cnv_len;
3730 len > 0; isfirst = FAL0, cp = next){
3731 /* C99 */{
3732 si32_t i, j;
3734 i = n_UNALIGN(si32_t*,cp)[0];
3735 j = i & SI32_MAX;
3736 next = &cp[j];
3737 len -= j;
3738 if(i == j)
3739 continue;
3741 /* struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];} */
3742 cp += sizeof(si32_t);
3743 i = n_UNALIGN(si32_t*,cp)[0];
3744 cp += sizeof(si32_t);
3745 for(j = 0; j < i; ++j)
3746 capname[j] = n_UNALIGN(wc_t*,cp)[j];
3747 capname[j] = '\0';
3750 /* Use generic lookup mechanism if not a known query */
3751 /* C99 */{
3752 si32_t tq;
3754 tq = n_termcap_query_for_name(capname, n_TERMCAP_CAPTYPE_STRING);
3755 if(tq == -1){
3756 tv.tv_data.tvd_string = capname;
3757 tq = n__TERMCAP_QUERY_MAX1;
3760 if(tq < 0 || !n_termcap_query(tq, &tv)){
3761 if(n_poption & n_PO_D_V)
3762 n_err(_("`bind': unknown or unsupported capability: %s: %s\n"),
3763 capname, tbcp->tbc_seq);
3764 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3765 break;
3769 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3770 /* C99 */{
3771 size_t i;
3773 i = strlen(tv.tv_data.tvd_string);
3774 if(/*i > SI32_MAX ||*/ i >= PTR2SIZE(next - cp)){
3775 if(n_poption & n_PO_D_V)
3776 n_err(_("`bind': capability expansion too long: %s: %s\n"),
3777 capname, tbcp->tbc_seq);
3778 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3779 break;
3780 }else if(i == 0){
3781 if(n_poption & n_PO_D_V)
3782 n_err(_("`bind': empty capability expansion: %s: %s\n"),
3783 capname, tbcp->tbc_seq);
3784 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3785 break;
3786 }else if(isfirst && !cntrlchar(*tv.tv_data.tvd_string)){
3787 if(n_poption & n_PO_D_V)
3788 n_err(_("`bind': capability expansion does not start with "
3789 "control: %s: %s\n"), capname, tbcp->tbc_seq);
3790 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3791 break;
3793 n_UNALIGN(si32_t*,cp)[-1] = (si32_t)i;
3794 memcpy(cp, tv.tv_data.tvd_string, i);
3795 cp[i] = '\0';
3798 NYD2_LEAVE;
3801 static void
3802 a_tty_bind_del(struct a_tty_bind_parse_ctx *tbpcp){
3803 struct a_tty_bind_ctx *ltbcp, *tbcp;
3804 NYD2_ENTER;
3806 tbcp = tbpcp->tbpc_tbcp;
3808 if((ltbcp = tbpcp->tbpc_ltbcp) != NULL)
3809 ltbcp->tbc_next = tbcp->tbc_next;
3810 else
3811 a_tty.tg_bind[tbpcp->tbpc_flags & n__GO_INPUT_CTX_MASK] = tbcp->tbc_next;
3812 n_free(tbcp);
3814 --a_tty.tg_bind_cnt;
3815 a_tty.tg_bind_isdirty = TRU1;
3816 NYD2_LEAVE;
3819 static void
3820 a_tty_bind_tree_build(void){
3821 size_t i;
3822 NYD2_ENTER;
3824 for(i = 0; i < n__GO_INPUT_CTX_MAX1; ++i){
3825 struct a_tty_bind_ctx *tbcp;
3826 n_LCTAV(n_GO_INPUT_CTX_BASE == 0);
3828 /* Somewhat wasteful, but easier to handle: simply clone the entire
3829 * primary key onto the secondary one, then only modify it */
3830 for(tbcp = a_tty.tg_bind[n_GO_INPUT_CTX_BASE]; tbcp != NULL;
3831 tbcp = tbcp->tbc_next)
3832 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3833 a_tty__bind_tree_add(n_GO_INPUT_CTX_BASE, &a_tty.tg_bind_tree[i][0],
3834 tbcp);
3836 if(i != n_GO_INPUT_CTX_BASE)
3837 for(tbcp = a_tty.tg_bind[i]; tbcp != NULL; tbcp = tbcp->tbc_next)
3838 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3839 a_tty__bind_tree_add(i, &a_tty.tg_bind_tree[i][0], tbcp);
3842 a_tty.tg_bind_isbuild = TRU1;
3843 NYD2_LEAVE;
3846 static void
3847 a_tty_bind_tree_teardown(void){
3848 size_t i, j;
3849 NYD2_ENTER;
3851 memset(&a_tty.tg_bind_shcut_cancel[0], 0,
3852 sizeof(a_tty.tg_bind_shcut_cancel));
3853 memset(&a_tty.tg_bind_shcut_prompt_char[0], 0,
3854 sizeof(a_tty.tg_bind_shcut_prompt_char));
3856 for(i = 0; i < n__GO_INPUT_CTX_MAX1; ++i)
3857 for(j = 0; j < HSHSIZE; ++j)
3858 a_tty__bind_tree_free(a_tty.tg_bind_tree[i][j]);
3859 memset(&a_tty.tg_bind_tree[0], 0, sizeof(a_tty.tg_bind_tree));
3861 a_tty.tg_bind_isdirty = a_tty.tg_bind_isbuild = FAL0;
3862 NYD2_LEAVE;
3865 static void
3866 a_tty__bind_tree_add(ui32_t hmap_idx, struct a_tty_bind_tree *store[HSHSIZE],
3867 struct a_tty_bind_ctx *tbcp){
3868 ui32_t cnvlen;
3869 char const *cnvdat;
3870 struct a_tty_bind_tree *ntbtp;
3871 NYD2_ENTER;
3872 n_UNUSED(hmap_idx);
3874 ntbtp = NULL;
3876 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len; cnvlen > 0;){
3877 union {wchar_t const *wp; char const *cp;} u;
3878 si32_t entlen;
3880 /* {si32_t buf_len_iscap;} */
3881 entlen = *n_UNALIGN(si32_t const*,cnvdat);
3883 if(entlen & SI32_MIN){
3884 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;}
3885 * Note that empty capabilities result in DEFUNCT */
3886 for(u.cp = (char const*)&n_UNALIGN(si32_t const*,cnvdat)[2];
3887 *u.cp != '\0'; ++u.cp)
3888 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.cp, TRU1);
3889 assert(ntbtp != NULL);
3890 ntbtp->tbt_isseq_trail = TRU1;
3891 entlen &= SI32_MAX;
3892 }else{
3893 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3894 bool_t isseq;
3896 u.wp = (wchar_t const*)&n_UNALIGN(si32_t const*,cnvdat)[1];
3898 /* May be a special shortcut function? */
3899 if(ntbtp == NULL && (tbcp->tbc_flags & a_TTY_BIND_MLE1CNTRL)){
3900 char *cp;
3901 ui32_t ctx, fun;
3903 ctx = tbcp->tbc_flags & n__GO_INPUT_CTX_MASK;
3904 fun = tbcp->tbc_flags & a_TTY__BIND_FUN_MASK;
3906 if(fun == a_TTY_BIND_FUN_CANCEL){
3907 for(cp = &a_tty.tg_bind_shcut_cancel[ctx][0];
3908 PTRCMP(cp, <, &a_tty.tg_bind_shcut_cancel[ctx]
3909 [n_NELEM(a_tty.tg_bind_shcut_cancel[ctx]) - 1]); ++cp)
3910 if(*cp == '\0'){
3911 *cp = (char)*u.wp;
3912 break;
3914 }else if(fun == a_TTY_BIND_FUN_PROMPT_CHAR){
3915 for(cp = &a_tty.tg_bind_shcut_prompt_char[ctx][0];
3916 PTRCMP(cp, <, &a_tty.tg_bind_shcut_prompt_char[ctx]
3917 [n_NELEM(a_tty.tg_bind_shcut_prompt_char[ctx]) - 1]);
3918 ++cp)
3919 if(*cp == '\0'){
3920 *cp = (char)*u.wp;
3921 break;
3926 isseq = (u.wp[1] != '\0');
3927 for(; *u.wp != '\0'; ++u.wp)
3928 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.wp, isseq);
3929 if(isseq){
3930 assert(ntbtp != NULL);
3931 ntbtp->tbt_isseq_trail = TRU1;
3935 cnvlen -= entlen;
3936 cnvdat += entlen;
3939 /* Should have been rendered defunctional at first instead */
3940 assert(ntbtp != NULL);
3941 ntbtp->tbt_bind = tbcp;
3942 NYD2_LEAVE;
3945 static struct a_tty_bind_tree *
3946 a_tty__bind_tree_add_wc(struct a_tty_bind_tree **treep,
3947 struct a_tty_bind_tree *parentp, wchar_t wc, bool_t isseq){
3948 struct a_tty_bind_tree *tbtp, *xtbtp;
3949 NYD2_ENTER;
3951 if(parentp == NULL){
3952 treep += wc % HSHSIZE;
3954 /* Having no parent also means that the tree slot is possibly empty */
3955 for(tbtp = *treep; tbtp != NULL;
3956 parentp = tbtp, tbtp = tbtp->tbt_sibling){
3957 if(tbtp->tbt_char != wc)
3958 continue;
3959 if(tbtp->tbt_isseq == isseq)
3960 goto jleave;
3961 /* isseq MUST be linked before !isseq, so record this "parent"
3962 * sibling, but continue searching for now.
3963 * Otherwise it is impossible that we'll find what we look for */
3964 if(isseq){
3965 #ifdef HAVE_DEBUG
3966 while((tbtp = tbtp->tbt_sibling) != NULL)
3967 assert(tbtp->tbt_char != wc);
3968 #endif
3969 break;
3973 tbtp = n_alloc(sizeof *tbtp);
3974 memset(tbtp, 0, sizeof *tbtp);
3975 tbtp->tbt_char = wc;
3976 tbtp->tbt_isseq = isseq;
3978 if(parentp == NULL){
3979 tbtp->tbt_sibling = *treep;
3980 *treep = tbtp;
3981 }else{
3982 tbtp->tbt_sibling = parentp->tbt_sibling;
3983 parentp->tbt_sibling = tbtp;
3985 }else{
3986 if((tbtp = *(treep = &parentp->tbt_childs)) != NULL){
3987 for(;; tbtp = xtbtp){
3988 if(tbtp->tbt_char == wc){
3989 if(tbtp->tbt_isseq == isseq)
3990 goto jleave;
3991 /* isseq MUST be linked before, so it is impossible that we'll
3992 * find what we look for */
3993 if(isseq){
3994 #ifdef HAVE_DEBUG
3995 while((tbtp = tbtp->tbt_sibling) != NULL)
3996 assert(tbtp->tbt_char != wc);
3997 #endif
3998 tbtp = NULL;
3999 break;
4003 if((xtbtp = tbtp->tbt_sibling) == NULL){
4004 treep = &tbtp->tbt_sibling;
4005 break;
4010 xtbtp = n_alloc(sizeof *xtbtp);
4011 memset(xtbtp, 0, sizeof *xtbtp);
4012 xtbtp->tbt_parent = parentp;
4013 xtbtp->tbt_char = wc;
4014 xtbtp->tbt_isseq = isseq;
4015 tbtp = xtbtp;
4016 *treep = tbtp;
4018 jleave:
4019 NYD2_LEAVE;
4020 return tbtp;
4023 static void
4024 a_tty__bind_tree_free(struct a_tty_bind_tree *tbtp){
4025 NYD2_ENTER;
4026 while(tbtp != NULL){
4027 struct a_tty_bind_tree *tmp;
4029 if((tmp = tbtp->tbt_childs) != NULL)
4030 a_tty__bind_tree_free(tmp);
4032 tmp = tbtp->tbt_sibling;
4033 n_free(tbtp);
4034 tbtp = tmp;
4036 NYD2_LEAVE;
4038 # endif /* HAVE_KEY_BINDINGS */
4040 FL void
4041 n_tty_init(void){
4042 NYD_ENTER;
4044 if(ok_blook(line_editor_disable))
4045 goto jleave;
4047 /* Load the history file */
4048 # ifdef HAVE_HISTORY
4049 a_tty_hist_load();
4050 # endif
4052 /* Force immediate resolve for anything which follows */
4053 n_psonce |= n_PSO_LINE_EDITOR_INIT;
4055 # ifdef HAVE_KEY_BINDINGS
4056 /* `bind's (and `unbind's) done from within resource files couldn't be
4057 * performed for real since our termcap driver wasn't yet loaded, and we
4058 * can't perform automatic init since the user may have disallowed so */
4059 /* C99 */{ /* TODO outsource into own file */
4060 struct a_tty_bind_ctx *tbcp;
4061 enum n_go_input_flags gif;
4063 for(gif = 0; gif < n__GO_INPUT_CTX_MAX1; ++gif)
4064 for(tbcp = a_tty.tg_bind[gif]; tbcp != NULL; tbcp = tbcp->tbc_next)
4065 if((tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
4066 a_TTY_BIND_RESOLVE)
4067 a_tty_bind_resolve(tbcp);
4070 /* And we want to (try to) install some default key bindings */
4071 if(!ok_blook(line_editor_no_defaults)){
4072 char buf[8];
4073 struct a_tty_bind_parse_ctx tbpc;
4074 struct a_tty_bind_builtin_tuple const *tbbtp, *tbbtp_max;
4075 ui32_t flags;
4077 buf[0] = '$', buf[1] = '\'', buf[2] = '\\', buf[3] = 'c',
4078 buf[5] = '\'', buf[6] = '\0';
4080 tbbtp = a_tty_bind_base_tuples;
4081 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_base_tuples)];
4082 flags = n_GO_INPUT_CTX_BASE;
4083 jbuiltin_redo:
4084 for(; tbbtp < tbbtp_max; ++tbbtp){
4085 memset(&tbpc, 0, sizeof tbpc);
4086 tbpc.tbpc_cmd = "bind";
4087 if(tbbtp->tbbt_iskey){
4088 buf[4] = tbbtp->tbbt_ckey;
4089 tbpc.tbpc_in_seq = buf;
4090 }else
4091 tbpc.tbpc_in_seq = savecatsep(":", '\0',
4092 n_termcap_name_of_query(tbbtp->tbbt_query));
4093 tbpc.tbpc_exp.s = n_UNCONST(tbbtp->tbbt_exp[0] == '\0'
4094 ? a_tty_bind_fun_names[(ui8_t)tbbtp->tbbt_exp[1]]
4095 : tbbtp->tbbt_exp);
4096 tbpc.tbpc_exp.l = strlen(tbpc.tbpc_exp.s);
4097 tbpc.tbpc_flags = flags;
4098 /* ..but don't want to overwrite any user settings */
4099 a_tty_bind_create(&tbpc, FAL0);
4101 if(flags == n_GO_INPUT_CTX_BASE){
4102 tbbtp = a_tty_bind_default_tuples;
4103 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_default_tuples)];
4104 flags = n_GO_INPUT_CTX_DEFAULT;
4105 goto jbuiltin_redo;
4108 # endif /* HAVE_KEY_BINDINGS */
4110 jleave:
4111 NYD_LEAVE;
4114 FL void
4115 n_tty_destroy(bool_t xit_fastpath){
4116 NYD_ENTER;
4118 if(!(n_psonce & n_PSO_LINE_EDITOR_INIT))
4119 goto jleave;
4121 /* Write the history file */
4122 # ifdef HAVE_HISTORY
4123 if(!xit_fastpath)
4124 a_tty_hist_save();
4125 # endif
4127 # if defined HAVE_KEY_BINDINGS && defined HAVE_DEBUG
4128 n_go_command(n_GO_INPUT_NONE, "unbind * *");
4129 # endif
4131 # ifdef HAVE_DEBUG
4132 memset(&a_tty, 0, sizeof a_tty);
4134 n_psonce &= ~n_PSO_LINE_EDITOR_INIT;
4135 # endif
4136 jleave:
4137 NYD_LEAVE;
4140 FL int
4141 (n_tty_readline)(enum n_go_input_flags gif, char const *prompt,
4142 char **linebuf, size_t *linesize, size_t n, bool_t *histok_or_null
4143 n_MEMORY_DEBUG_ARGS){
4144 struct a_tty_line tl;
4145 struct n_string xprompt;
4146 # ifdef HAVE_COLOUR
4147 char *posbuf, *pos;
4148 # endif
4149 ssize_t nn;
4150 NYD_ENTER;
4152 assert(!ok_blook(line_editor_disable));
4153 if(!(n_psonce & n_PSO_LINE_EDITOR_INIT))
4154 n_tty_init();
4155 assert(n_psonce & n_PSO_LINE_EDITOR_INIT);
4157 # ifdef HAVE_COLOUR
4158 n_colour_env_create(n_COLOUR_CTX_MLE, n_tty_fp, FAL0);
4160 /* .tl_pos_buf is a hack */
4161 posbuf = pos = NULL;
4163 if(n_COLOUR_IS_ACTIVE()){
4164 char const *ccol;
4165 struct n_colour_pen *ccp;
4166 struct str const *sp;
4168 if((ccp = n_colour_pen_create(n_COLOUR_ID_MLE_POSITION, NULL)) != NULL &&
4169 (sp = n_colour_pen_to_str(ccp)) != NULL){
4170 ccol = sp->s;
4171 if((sp = n_colour_reset_to_str()) != NULL){
4172 size_t l1, l2;
4174 l1 = strlen(ccol);
4175 l2 = strlen(sp->s);
4176 posbuf = n_autorec_alloc(l1 + 4 + l2 +1);
4177 memcpy(posbuf, ccol, l1);
4178 pos = &posbuf[l1];
4179 memcpy(&pos[4], sp->s, ++l2);
4184 if(posbuf == NULL){
4185 posbuf = pos = n_autorec_alloc(4 +1);
4186 pos[4] = '\0';
4188 # endif /* HAVE_COLOUR */
4190 memset(&tl, 0, sizeof tl);
4191 tl.tl_goinflags = gif;
4193 # ifdef HAVE_KEY_BINDINGS
4194 /* C99 */{
4195 char const *cp;
4197 if((cp = ok_vlook(bind_timeout)) != NULL){
4198 ui64_t uib;
4200 n_idec_ui64_cp(&uib, cp, 0, NULL);
4202 if(uib > 0 &&
4203 /* Convert to tenths of a second, unfortunately */
4204 (uib = (uib + 99) / 100) <= a_TTY_BIND_TIMEOUT_MAX)
4205 tl.tl_bind_timeout = (ui8_t)uib;
4206 else if(n_poption & n_PO_D_V)
4207 n_err(_("Ignoring invalid *bind-timeout*: %s\n"), cp);
4211 if(a_tty.tg_bind_isdirty)
4212 a_tty_bind_tree_teardown();
4213 if(a_tty.tg_bind_cnt > 0 && !a_tty.tg_bind_isbuild)
4214 a_tty_bind_tree_build();
4215 tl.tl_bind_tree_hmap = &a_tty.tg_bind_tree[gif & n__GO_INPUT_CTX_MASK];
4216 tl.tl_bind_shcut_cancel =
4217 &a_tty.tg_bind_shcut_cancel[gif & n__GO_INPUT_CTX_MASK];
4218 tl.tl_bind_shcut_prompt_char =
4219 &a_tty.tg_bind_shcut_prompt_char[gif & n__GO_INPUT_CTX_MASK];
4220 # endif /* HAVE_KEY_BINDINGS */
4222 # ifdef HAVE_COLOUR
4223 tl.tl_pos_buf = posbuf;
4224 tl.tl_pos = pos;
4225 # endif
4227 if(!(gif & n_GO_INPUT_PROMPT_NONE)){
4228 n_string_creat_auto(&xprompt);
4230 if((tl.tl_prompt_width = n_tty_create_prompt(&xprompt, prompt, gif)
4231 ) > 0){
4232 tl.tl_prompt = n_string_cp_const(&xprompt);
4233 tl.tl_prompt_length = (ui32_t)xprompt.s_len;
4237 tl.tl_line.cbuf = *linebuf;
4238 if(n != 0){
4239 tl.tl_defc.s = savestrbuf(*linebuf, n);
4240 tl.tl_defc.l = n;
4242 tl.tl_x_buf = linebuf;
4243 tl.tl_x_bufsize = linesize;
4245 a_tty.tg_line = &tl;
4246 a_tty_sigs_up();
4247 n_TERMCAP_RESUME(FAL0);
4248 a_tty_term_mode(TRU1);
4249 nn = a_tty_readline(&tl, n, histok_or_null n_MEMORY_DEBUG_ARGSCALL);
4250 n_COLOUR( n_colour_env_gut(); )
4251 a_tty_term_mode(FAL0);
4252 n_TERMCAP_SUSPEND(FAL0);
4253 a_tty_sigs_down();
4254 a_tty.tg_line = NULL;
4256 NYD_LEAVE;
4257 return (int)nn;
4260 FL void
4261 n_tty_addhist(char const *s, enum n_go_input_flags gif){
4262 # ifdef HAVE_HISTORY
4263 /* Super-Heavy-Metal: block all sigs, avoid leaks+ on jump */
4264 ui32_t l;
4265 struct a_tty_hist *thp, *othp, *ythp;
4266 # endif
4267 NYD_ENTER;
4268 n_UNUSED(s);
4269 n_UNUSED(gif);
4271 # ifdef HAVE_HISTORY
4272 if(*s == '\0' ||
4273 (!(n_psonce & n_PSO_LINE_EDITOR_INIT) && !(n_pstate & n_PS_ROOT)) ||
4274 a_tty.tg_hist_size_max == 0 ||
4275 ok_blook(line_editor_disable) ||
4276 ((gif & n_GO_INPUT_HIST_GABBY) && !ok_blook(history_gabby)))
4277 goto j_leave;
4279 l = (ui32_t)strlen(s);
4281 /* Eliminating duplicates is expensive, but simply inacceptable so
4282 * during the load of a potentially large history file! */
4283 if(n_psonce & n_PSO_LINE_EDITOR_INIT)
4284 for(thp = a_tty.tg_hist; thp != NULL; thp = thp->th_older)
4285 if(thp->th_len == l && !strcmp(thp->th_dat, s)){
4286 hold_all_sigs(); /* TODO */
4287 thp->th_flags = (gif & a_TTY_HIST_CTX_MASK) |
4288 (gif & n_GO_INPUT_HIST_GABBY ? a_TTY_HIST_GABBY : 0);
4289 othp = thp->th_older;
4290 ythp = thp->th_younger;
4291 if(othp != NULL)
4292 othp->th_younger = ythp;
4293 else
4294 a_tty.tg_hist_tail = ythp;
4295 if(ythp != NULL)
4296 ythp->th_older = othp;
4297 else
4298 a_tty.tg_hist = othp;
4299 goto jleave;
4301 hold_all_sigs();
4303 ++a_tty.tg_hist_size;
4304 if((n_psonce & n_PSO_LINE_EDITOR_INIT) &&
4305 a_tty.tg_hist_size > a_tty.tg_hist_size_max){
4306 --a_tty.tg_hist_size;
4307 if((thp = a_tty.tg_hist_tail) != NULL){
4308 if((a_tty.tg_hist_tail = thp->th_younger) == NULL)
4309 a_tty.tg_hist = NULL;
4310 else
4311 a_tty.tg_hist_tail->th_older = NULL;
4312 n_free(thp);
4316 thp = n_alloc(n_VSTRUCT_SIZEOF(struct a_tty_hist, th_dat) + l +1);
4317 thp->th_len = l;
4318 thp->th_flags = (gif & a_TTY_HIST_CTX_MASK) |
4319 (gif & n_GO_INPUT_HIST_GABBY ? a_TTY_HIST_GABBY : 0);
4320 memcpy(thp->th_dat, s, l +1);
4321 jleave:
4322 if((thp->th_older = a_tty.tg_hist) != NULL)
4323 a_tty.tg_hist->th_younger = thp;
4324 else
4325 a_tty.tg_hist_tail = thp;
4326 thp->th_younger = NULL;
4327 a_tty.tg_hist = thp;
4329 rele_all_sigs();
4330 j_leave:
4331 # endif /* HAVE_HISTORY */
4332 NYD_LEAVE;
4335 # ifdef HAVE_HISTORY
4336 FL int
4337 c_history(void *v){
4338 siz_t entry;
4339 struct a_tty_hist *thp;
4340 char **argv;
4341 NYD_ENTER;
4343 if(ok_blook(line_editor_disable)){
4344 n_err(_("history: *line-editor-disable* is set\n"));
4345 goto jerr;
4348 if(!(n_psonce & n_PSO_LINE_EDITOR_INIT)){
4349 n_tty_init();
4350 assert(n_psonce & n_PSO_LINE_EDITOR_INIT);
4353 if(*(argv = v) == NULL)
4354 goto jlist;
4355 if(argv[1] != NULL)
4356 goto jerr;
4357 if(!asccasecmp(*argv, "show"))
4358 goto jlist;
4359 if(!asccasecmp(*argv, "clear"))
4360 goto jclear;
4362 if(!asccasecmp(*argv, "load")){
4363 if(!a_tty_hist_load())
4364 v = NULL;
4365 goto jleave;
4367 if(!asccasecmp(*argv, "save")){
4368 if(!a_tty_hist_save())
4369 v = NULL;
4370 goto jleave;
4373 if((n_idec_siz_cp(&entry, *argv, 10, NULL
4374 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
4375 ) == n_IDEC_STATE_CONSUMED)
4376 goto jentry;
4377 jerr:
4378 n_err(_("Synopsis: history: %s\n"),
4379 /* Same string as in cmd-tab.h, still hoping...) */
4380 _("<show (default)|load|save|clear> or select history <NO>"));
4381 v = NULL;
4382 jleave:
4383 NYD_LEAVE;
4384 return (v == NULL ? !STOP : !OKAY); /* xxx 1:bad 0:good -- do some */
4386 jlist:{
4387 size_t no, l, b;
4388 FILE *fp;
4390 if(a_tty.tg_hist == NULL)
4391 goto jleave;
4393 if((fp = Ftmp(NULL, "hist", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
4394 n_perr(_("tmpfile"), 0);
4395 v = NULL;
4396 goto jleave;
4399 no = a_tty.tg_hist_size;
4400 l = b = 0;
4402 for(thp = a_tty.tg_hist; thp != NULL;
4403 --no, ++l, thp = thp->th_older){
4404 char c1, c2;
4406 b += thp->th_len;
4408 switch(thp->th_flags & a_TTY_HIST_CTX_MASK){
4409 default:
4410 case a_TTY_HIST_CTX_DEFAULT:
4411 c1 = 'd';
4412 break;
4413 case a_TTY_HIST_CTX_COMPOSE:
4414 c1 = 'c';
4415 break;
4417 c2 = (thp->th_flags & a_TTY_HIST_GABBY) ? '*' : ' ';
4419 if(n_poption & n_PO_D_V)
4420 fprintf(fp, "# Length +%" PRIu32 ", total %" PRIuZ "\n",
4421 thp->th_len, b);
4422 fprintf(fp, "%c%c%4" PRIuZ "\t%s\n", c1, c2, no, thp->th_dat);
4425 page_or_print(fp, l);
4426 Fclose(fp);
4428 goto jleave;
4430 jclear:
4431 while((thp = a_tty.tg_hist) != NULL){
4432 a_tty.tg_hist = thp->th_older;
4433 n_free(thp);
4435 a_tty.tg_hist_tail = NULL;
4436 a_tty.tg_hist_size = 0;
4437 goto jleave;
4439 jentry:{
4440 siz_t ep;
4442 ep = (entry < 0) ? -entry : entry;
4444 if(ep != 0 && UICMP(z, ep, <=, a_tty.tg_hist_size)){
4445 if(ep != entry)
4446 --ep;
4447 else
4448 ep = (siz_t)a_tty.tg_hist_size - ep;
4449 for(thp = a_tty.tg_hist;; thp = thp->th_older){
4450 assert(thp != NULL);
4451 if(ep-- == 0){
4452 n_go_input_inject((n_GO_INPUT_INJECT_COMMIT |
4453 n_GO_INPUT_INJECT_HISTORY), v = thp->th_dat, thp->th_len);
4454 break;
4457 }else{
4458 n_err(_("`history': no such entry: %" PRIdZ "\n"), entry);
4459 v = NULL;
4462 goto jleave;
4464 # endif /* HAVE_HISTORY */
4466 # ifdef HAVE_KEY_BINDINGS
4467 FL int
4468 c_bind(void *v){
4469 struct a_tty_bind_ctx *tbcp;
4470 enum n_go_input_flags gif;
4471 bool_t aster, show;
4472 union {char const *cp; char *p; char c;} c;
4473 struct n_cmd_arg_ctx *cacp;
4474 NYD_ENTER;
4476 cacp = v;
4478 c.cp = cacp->cac_arg->ca_arg.ca_str.s;
4479 if(cacp->cac_no == 1)
4480 show = TRU1;
4481 else
4482 show = !asccasecmp(cacp->cac_arg->ca_next->ca_arg.ca_str.s, "show");
4483 aster = FAL0;
4485 if((gif = a_tty_bind_ctx_find(c.cp)) == (enum n_go_input_flags)-1){
4486 if(!(aster = n_is_all_or_aster(c.cp)) || !show){
4487 n_err(_("`bind': invalid context: %s\n"), c.cp);
4488 v = NULL;
4489 goto jleave;
4491 gif = 0;
4494 if(show){
4495 ui32_t lns;
4496 FILE *fp;
4498 if((fp = Ftmp(NULL, "bind", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
4499 n_perr(_("tmpfile"), 0);
4500 v = NULL;
4501 goto jleave;
4504 lns = 0;
4505 for(;;){
4506 for(tbcp = a_tty.tg_bind[gif]; tbcp != NULL;
4507 ++lns, tbcp = tbcp->tbc_next){
4508 /* Print the bytes of resolved terminal capabilities, then */
4509 if((n_poption & n_PO_D_V) &&
4510 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)
4511 ) == a_TTY_BIND_RESOLVE){
4512 char cbuf[8];
4513 union {wchar_t const *wp; char const *cp;} u;
4514 si32_t entlen;
4515 ui32_t cnvlen;
4516 char const *cnvdat, *bsep, *cbufp;
4518 putc('#', fp);
4519 putc(' ', fp);
4521 cbuf[0] = '=', cbuf[2] = '\0';
4522 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len;
4523 cnvlen > 0;){
4524 if(cnvdat != tbcp->tbc_cnv)
4525 putc(',', fp);
4527 /* {si32_t buf_len_iscap;} */
4528 entlen = *n_UNALIGN(si32_t const*,cnvdat);
4529 if(entlen & SI32_MIN){
4530 /* struct{si32_t buf_len_iscap; si32_t cap_len;
4531 * char buf[]+NUL;} */
4532 for(bsep = n_empty,
4533 u.cp = (char const*)
4534 &n_UNALIGN(si32_t const*,cnvdat)[2];
4535 (c.c = *u.cp) != '\0'; ++u.cp){
4536 if(asciichar(c.c) && !cntrlchar(c.c))
4537 cbuf[1] = c.c, cbufp = cbuf;
4538 else
4539 cbufp = n_empty;
4540 fprintf(fp, "%s\\x%02X%s",
4541 bsep, (ui32_t)(ui8_t)c.c, cbufp);
4542 bsep = " ";
4544 entlen &= SI32_MAX;
4545 }else
4546 putc('-', fp);
4548 cnvlen -= entlen;
4549 cnvdat += entlen;
4552 fputs("\n ", fp);
4553 ++lns;
4556 fprintf(fp, "%sbind %s %s %s%s%s\n",
4557 ((tbcp->tbc_flags & a_TTY_BIND_DEFUNCT)
4558 /* I18N: `bind' sequence not working, either because it is
4559 * I18N: using Unicode and that is not available in the locale,
4560 * I18N: or a termcap(5)/terminfo(5) sequence won't work out */
4561 ? _("# <Defunctional> ") : n_empty),
4562 a_tty_bind_ctx_maps[gif].tbcm_name, tbcp->tbc_seq,
4563 n_shexp_quote_cp(tbcp->tbc_exp, TRU1),
4564 (tbcp->tbc_flags & a_TTY_BIND_NOCOMMIT ? n_at : n_empty),
4565 (!(n_poption & n_PO_D_VV) ? n_empty
4566 : (tbcp->tbc_flags & a_TTY_BIND_FUN_INTERNAL
4567 ? _(" # MLE internal") : n_empty))
4570 if(!aster || ++gif >= n__GO_INPUT_CTX_MAX1)
4571 break;
4573 page_or_print(fp, lns);
4575 Fclose(fp);
4576 }else{
4577 struct a_tty_bind_parse_ctx tbpc;
4578 struct n_cmd_arg *cap;
4580 memset(&tbpc, 0, sizeof tbpc);
4581 tbpc.tbpc_cmd = cacp->cac_desc->cad_name;
4582 tbpc.tbpc_in_seq = (cap = cacp->cac_arg->ca_next)->ca_arg.ca_str.s;
4583 if((cap = cap->ca_next) != NULL){
4584 tbpc.tbpc_exp.s = cap->ca_arg.ca_str.s;
4585 tbpc.tbpc_exp.l = cap->ca_arg.ca_str.l;
4587 tbpc.tbpc_flags = gif;
4588 if(!a_tty_bind_create(&tbpc, TRU1))
4589 v = NULL;
4591 jleave:
4592 NYD_LEAVE;
4593 return (v != NULL) ? n_EXIT_OK : n_EXIT_ERR;
4596 FL int
4597 c_unbind(void *v){
4598 struct a_tty_bind_parse_ctx tbpc;
4599 struct a_tty_bind_ctx *tbcp;
4600 enum n_go_input_flags gif;
4601 bool_t aster;
4602 union {char const *cp; char *p;} c;
4603 struct n_cmd_arg_ctx *cacp;
4604 NYD_ENTER;
4606 cacp = v;
4607 c.cp = cacp->cac_arg->ca_arg.ca_str.s;
4608 aster = FAL0;
4610 if((gif = a_tty_bind_ctx_find(c.cp)) == (enum n_go_input_flags)-1){
4611 if(!(aster = n_is_all_or_aster(c.cp))){
4612 n_err(_("`unbind': invalid context: %s\n"), c.cp);
4613 v = NULL;
4614 goto jleave;
4616 gif = 0;
4619 c.cp = cacp->cac_arg->ca_next->ca_arg.ca_str.s;
4620 jredo:
4621 if(n_is_all_or_aster(c.cp)){
4622 while((tbcp = a_tty.tg_bind[gif]) != NULL){
4623 memset(&tbpc, 0, sizeof tbpc);
4624 tbpc.tbpc_tbcp = tbcp;
4625 tbpc.tbpc_flags = gif;
4626 a_tty_bind_del(&tbpc);
4628 }else{
4629 memset(&tbpc, 0, sizeof tbpc);
4630 tbpc.tbpc_cmd = cacp->cac_desc->cad_name;
4631 tbpc.tbpc_in_seq = c.cp;
4632 tbpc.tbpc_flags = gif;
4634 if(n_UNLIKELY(!a_tty_bind_parse(FAL0, &tbpc)))
4635 v = NULL;
4636 else if(n_UNLIKELY((tbcp = tbpc.tbpc_tbcp) == NULL)){
4637 n_err(_("`unbind': no such `bind'ing: %s %s\n"),
4638 a_tty_bind_ctx_maps[gif].tbcm_name, c.cp);
4639 v = NULL;
4640 }else
4641 a_tty_bind_del(&tbpc);
4644 if(aster && ++gif < n__GO_INPUT_CTX_MAX1)
4645 goto jredo;
4646 jleave:
4647 NYD_LEAVE;
4648 return (v != NULL) ? n_EXIT_OK : n_EXIT_ERR;
4650 # endif /* HAVE_KEY_BINDINGS */
4652 #else /* HAVE_MLE */
4654 * The really-nothing-at-all implementation
4657 static void
4658 a_tty_signal(int sig){
4659 /* Prototype at top */
4660 # ifdef HAVE_TERMCAP
4661 sigset_t nset, oset;
4662 # endif
4663 NYD_X; /* Signal handler */
4664 n_UNUSED(sig);
4666 # ifdef HAVE_TERMCAP
4667 n_TERMCAP_SUSPEND(TRU1);
4668 a_tty_sigs_down();
4670 sigemptyset(&nset);
4671 sigaddset(&nset, sig);
4672 sigprocmask(SIG_UNBLOCK, &nset, &oset);
4673 n_raise(sig);
4674 /* When we come here we'll continue editing, so reestablish */
4675 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
4677 a_tty_sigs_up();
4678 n_TERMCAP_RESUME(TRU1);
4679 # endif /* HAVE_TERMCAP */
4682 # if 0
4683 FL void
4684 n_tty_init(void){
4685 NYD_ENTER;
4686 NYD_LEAVE;
4689 FL void
4690 n_tty_destroy(bool_t xit_fastpath){
4691 NYD_ENTER;
4692 n_UNUSED(xit_fastpath);
4693 NYD_LEAVE;
4695 # endif /* 0 */
4697 FL int
4698 (n_tty_readline)(enum n_go_input_flags gif, char const *prompt,
4699 char **linebuf, size_t *linesize, size_t n, bool_t *histok_or_null
4700 n_MEMORY_DEBUG_ARGS){
4701 struct n_string xprompt;
4702 int rv;
4703 NYD_ENTER;
4704 n_UNUSED(histok_or_null);
4706 if(!(gif & n_GO_INPUT_PROMPT_NONE)){
4707 if(n_tty_create_prompt(n_string_creat_auto(&xprompt), prompt, gif) > 0){
4708 fwrite(xprompt.s_dat, 1, xprompt.s_len, n_tty_fp);
4709 fflush(n_tty_fp);
4713 # ifdef HAVE_TERMCAP
4714 a_tty_sigs_up();
4715 n_TERMCAP_RESUME(FAL0);
4716 # endif
4717 rv = (readline_restart)(n_stdin, linebuf, linesize, n
4718 n_MEMORY_DEBUG_ARGSCALL);
4719 # ifdef HAVE_TERMCAP
4720 n_TERMCAP_SUSPEND(FAL0);
4721 a_tty_sigs_down();
4722 # endif
4723 NYD_LEAVE;
4724 return rv;
4727 FL void
4728 n_tty_addhist(char const *s, enum n_go_input_flags gif){
4729 NYD_ENTER;
4730 n_UNUSED(s);
4731 n_UNUSED(gif);
4732 NYD_LEAVE;
4734 #endif /* nothing at all */
4736 #undef a_TTY_SIGNALS
4737 /* s-it-mode */