Bump S-nail v14.9.0-pre4, 2017-04-13
[s-mailx.git] / tty.c
blob592856cf9c5ede263693326d93df306a6ce71d30
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ TTY (command line) editing interaction.
3 *@ Because we have (had) multiple line-editor implementations, including our
4 *@ own M(ailx) L(ine) E(ditor), change the file layout a bit and place those
5 *@ one after the other below the other externals.
7 * Copyright (c) 2012 - 2017 Steffen (Daode) Nurpmeso <steffen@sdaoden.eu>.
9 * Permission to use, copy, modify, and/or distribute this software for any
10 * purpose with or without fee is hereby granted, provided that the above
11 * copyright notice and this permission notice appear in all copies.
13 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
14 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
15 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
16 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
17 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21 #undef n_FILE
22 #define n_FILE tty
24 #ifndef HAVE_AMALGAMATION
25 # include "nail.h"
26 #endif
28 #if defined HAVE_MLE || defined HAVE_TERMCAP
29 # define a_TTY_SIGNALS
30 #endif
32 #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 #ifdef a_TTY_SIGNALS
43 static void
44 a_tty_sigs_up(void){
45 sigset_t nset, oset;
46 NYD2_ENTER;
48 sigfillset(&nset);
50 sigprocmask(SIG_BLOCK, &nset, &oset);
51 a_tty_oint = safe_signal(SIGINT, &n_tty_signal);
52 a_tty_oquit = safe_signal(SIGQUIT, &n_tty_signal);
53 a_tty_oterm = safe_signal(SIGTERM, &n_tty_signal);
54 a_tty_ohup = safe_signal(SIGHUP, &n_tty_signal);
55 a_tty_otstp = safe_signal(SIGTSTP, &n_tty_signal);
56 a_tty_ottin = safe_signal(SIGTTIN, &n_tty_signal);
57 a_tty_ottou = safe_signal(SIGTTOU, &n_tty_signal);
58 sigprocmask(SIG_SETMASK, &oset, NULL);
59 NYD2_LEAVE;
62 static void
63 a_tty_sigs_down(void){
64 sigset_t nset, oset;
65 NYD2_ENTER;
67 sigfillset(&nset);
69 sigprocmask(SIG_BLOCK, &nset, &oset);
70 safe_signal(SIGINT, a_tty_oint);
71 safe_signal(SIGQUIT, a_tty_oquit);
72 safe_signal(SIGTERM, a_tty_oterm);
73 safe_signal(SIGHUP, a_tty_ohup);
74 safe_signal(SIGTSTP, a_tty_otstp);
75 safe_signal(SIGTTIN, a_tty_ottin);
76 safe_signal(SIGTTOU, a_tty_ottou);
77 sigprocmask(SIG_SETMASK, &oset, NULL);
78 NYD2_LEAVE;
80 #endif /* a_TTY_SIGNALS */
82 static sigjmp_buf a_tty__actjmp; /* TODO someday, we won't need it no more */
83 static void
84 a_tty__acthdl(int s) /* TODO someday, we won't need it no more */
86 NYD_X; /* Signal handler */
87 termios_state_reset();
88 siglongjmp(a_tty__actjmp, s);
91 FL bool_t
92 getapproval(char const * volatile prompt, bool_t noninteract_default)
94 sighandler_type volatile oint, ohup;
95 bool_t volatile rv;
96 int volatile sig;
97 NYD_ENTER;
99 if(!(n_psonce & n_PSO_INTERACTIVE)){
100 sig = 0;
101 rv = noninteract_default;
102 goto jleave;
104 rv = FAL0;
106 /* C99 */{
107 char const *quest = noninteract_default
108 ? _("[yes]/no? ") : _("[no]/yes? ");
110 if (prompt == NULL)
111 prompt = _("Continue");
112 prompt = savecatsep(prompt, ' ', quest);
115 oint = safe_signal(SIGINT, SIG_IGN);
116 ohup = safe_signal(SIGHUP, SIG_IGN);
117 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
118 goto jrestore;
119 safe_signal(SIGINT, &a_tty__acthdl);
120 safe_signal(SIGHUP, &a_tty__acthdl);
122 if (n_go_input(n_GO_INPUT_CTX_DEFAULT | n_GO_INPUT_NL_ESC, prompt,
123 &termios_state.ts_linebuf, &termios_state.ts_linesize, NULL) >= 0)
124 rv = (boolify(termios_state.ts_linebuf, UIZ_MAX,
125 noninteract_default) > 0);
126 jrestore:
127 termios_state_reset();
129 safe_signal(SIGHUP, ohup);
130 safe_signal(SIGINT, oint);
131 jleave:
132 NYD_LEAVE;
133 if (sig != 0)
134 n_raise(sig);
135 return rv;
138 #ifdef HAVE_SOCKETS
139 FL char *
140 getuser(char const * volatile query) /* TODO v15-compat obsolete */
142 sighandler_type volatile oint, ohup;
143 char * volatile user = NULL;
144 int volatile sig;
145 NYD_ENTER;
147 if (query == NULL)
148 query = _("User: ");
150 oint = safe_signal(SIGINT, SIG_IGN);
151 ohup = safe_signal(SIGHUP, SIG_IGN);
152 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
153 goto jrestore;
154 safe_signal(SIGINT, &a_tty__acthdl);
155 safe_signal(SIGHUP, &a_tty__acthdl);
157 if (n_go_input(n_GO_INPUT_CTX_DEFAULT | n_GO_INPUT_NL_ESC, query,
158 &termios_state.ts_linebuf, &termios_state.ts_linesize, NULL) >= 0)
159 user = termios_state.ts_linebuf;
160 jrestore:
161 termios_state_reset();
163 safe_signal(SIGHUP, ohup);
164 safe_signal(SIGINT, oint);
165 NYD_LEAVE;
166 if (sig != 0)
167 n_raise(sig);
168 return user;
171 FL char *
172 getpassword(char const *query)/* TODO v15: use _only_ n_tty_fp! */
174 sighandler_type volatile oint, ohup;
175 struct termios tios;
176 char * volatile pass;
177 int volatile sig;
178 NYD_ENTER;
180 pass = NULL;
181 if(!(n_psonce & n_PSO_TTYIN))
182 goto j_leave;
184 if (query == NULL)
185 query = _("Password: ");
186 fputs(query, n_tty_fp);
187 fflush(n_tty_fp);
189 /* FIXME everywhere: tcsetattr() generates SIGTTOU when we're not in
190 * FIXME foreground pgrp, and can fail with EINTR!! also affects
191 * FIXME termios_state_reset() */
192 tcgetattr(STDIN_FILENO, &termios_state.ts_tios);
193 memcpy(&tios, &termios_state.ts_tios, sizeof tios);
194 termios_state.ts_needs_reset = TRU1;
195 tios.c_iflag &= ~(ISTRIP);
196 tios.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
198 oint = safe_signal(SIGINT, SIG_IGN);
199 ohup = safe_signal(SIGHUP, SIG_IGN);
200 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
201 goto jrestore;
202 safe_signal(SIGINT, &a_tty__acthdl);
203 safe_signal(SIGHUP, &a_tty__acthdl);
205 tcsetattr(STDIN_FILENO, TCSAFLUSH, &tios);
206 if (readline_restart(n_stdin, &termios_state.ts_linebuf,
207 &termios_state.ts_linesize, 0) >= 0)
208 pass = termios_state.ts_linebuf;
209 jrestore:
210 termios_state_reset();
211 putc('\n', n_tty_fp);
213 safe_signal(SIGHUP, ohup);
214 safe_signal(SIGINT, oint);
215 NYD_LEAVE;
216 if (sig != 0)
217 n_raise(sig);
218 j_leave:
219 return pass;
221 #endif /* HAVE_SOCKETS */
223 FL ui32_t
224 n_tty_create_prompt(struct n_string *store, char const *xprompt,
225 enum n_go_input_flags gif){
226 struct n_visual_info_ctx vic;
227 struct str in, out;
228 ui32_t pwidth;
229 char const *cp;
230 NYD2_ENTER;
232 /* Prompt creation indicates that prompt printing is directly ahead, so take
233 * this opportunity of UI-in-a-known-state and advertise the error ring */
234 #ifdef HAVE_ERRORS
235 if((n_psonce & (n_PSO_INTERACTIVE | n_PSO_ERRORS_NOTED)
236 ) == n_PSO_INTERACTIVE && (n_pstate & n_PS_ERRORS_PROMPT)){
237 n_psonce |= n_PSO_ERRORS_NOTED;
238 fprintf(n_stdout, _("There are new messages in the error message ring "
239 "(denoted by %s)\n"
240 " The `errors' command manages this message ring\n"),
241 V_(n_error));
243 #endif
245 jredo:
246 n_string_trunc(store, 0);
248 if(gif & n_GO_INPUT_PROMPT_NONE){
249 pwidth = 0;
250 goto jleave;
252 #ifdef HAVE_ERRORS
253 if(n_pstate & n_PS_ERRORS_PROMPT){
254 n_pstate &= ~n_PS_ERRORS_PROMPT;
255 store = n_string_push_cp(store, V_(n_error));
256 store = n_string_push_c(store, '#');
257 store = n_string_push_c(store, ' ');
259 #endif
261 cp = (gif & n_GO_INPUT_PROMPT_EVAL)
262 ? (gif & n_GO_INPUT_NL_FOLLOW ? ok_vlook(prompt2) : ok_vlook(prompt))
263 : xprompt;
264 if(cp != NULL && *cp != '\0'){
265 enum n_shexp_state shs;
267 store = n_string_push_cp(store, cp);
268 in.s = n_string_cp(store);
269 in.l = store->s_len;
270 out = in;
271 store = n_string_drop_ownership(store);
273 shs = n_shexp_parse_token((n_SHEXP_PARSE_LOG |
274 n_SHEXP_PARSE_IGNORE_EMPTY | n_SHEXP_PARSE_QUOTE_AUTO_FIXED |
275 n_SHEXP_PARSE_QUOTE_AUTO_DSQ), store, &in, NULL);
276 if((shs & n_SHEXP_STATE_ERR_MASK) || !(shs & n_SHEXP_STATE_STOP)){
277 store = n_string_clear(store);
278 store = n_string_take_ownership(store, out.s, out.l +1, out.l);
279 jeeval:
280 n_err(_("*prompt2?* evaluation failed, actively unsetting it\n"));
281 if(gif & n_GO_INPUT_NL_FOLLOW)
282 ok_vclear(prompt2);
283 else
284 ok_vclear(prompt);
285 goto jredo;
288 if(!store->s_auto)
289 free(out.s);
292 /* Make all printable TODO not know, we want to pass through ESC/CSI! */
293 #if 0
294 in.s = n_string_cp(store);
295 in.l = store->s_len;
296 makeprint(&in, &out);
297 store = n_string_assign_buf(store, out.s, out.l);
298 free(out.s);
299 #endif
301 /* We need the visual width.. */
302 memset(&vic, 0, sizeof vic);
303 vic.vic_indat = n_string_cp(store);
304 vic.vic_inlen = store->s_len;
305 for(pwidth = 0; vic.vic_inlen > 0;){
306 /* but \[ .. \] is not taken into account */
307 if(vic.vic_indat[0] == '\\' && vic.vic_inlen > 1 &&
308 vic.vic_indat[1] == '['){
309 size_t i;
311 i = PTR2SIZE(vic.vic_indat - store->s_dat);
312 store = n_string_cut(store, i, 2);
313 cp = &n_string_cp(store)[i];
314 i = store->s_len - i;
315 for(;; ++cp, --i){
316 if(i < 2){
317 n_err(_("Open \\[ sequence not closed in *prompt2?*\n"));
318 goto jeeval;
320 if(cp[0] == '\\' && cp[1] == ']')
321 break;
323 i = PTR2SIZE(cp - store->s_dat);
324 store = n_string_cut(store, i, 2);
325 vic.vic_indat = &n_string_cp(store)[i];
326 vic.vic_inlen = store->s_len - i;
327 }else if(!n_visual_info(&vic, n_VISUAL_INFO_WIDTH_QUERY |
328 n_VISUAL_INFO_ONE_CHAR)){
329 n_err(_("Character set error in evaluation of *prompt2?*\n"));
330 goto jeeval;
331 }else{
332 pwidth += (ui32_t)vic.vic_vi_width;
333 vic.vic_indat = vic.vic_oudat;
334 vic.vic_inlen = vic.vic_oulen;
338 /* And there may be colour support, too */
339 #ifdef HAVE_COLOUR
340 if(n_COLOUR_IS_ACTIVE()){
341 struct str const *psp, *rsp;
342 struct n_colour_pen *ccp;
344 if((ccp = n_colour_pen_create(n_COLOUR_ID_MLE_PROMPT, NULL)) != NULL &&
345 (psp = n_colour_pen_to_str(ccp)) != NULL &&
346 (rsp = n_colour_reset_to_str()) != NULL){
347 store = n_string_unshift_buf(store, psp->s, psp->l);
348 store = n_string_push_buf(store, rsp->s, rsp->l);
351 #endif /* HAVE_COLOUR */
353 jleave:
354 NYD2_LEAVE;
355 return pwidth;
359 * MLE: the Mailx-Line-Editor, our homebrew editor
360 * (inspired from NetBSDs sh(1) and dash(1)s hetio.c).
362 * Only used in interactive mode.
363 * TODO . This code should be splitted in funs/raw input/bind modules.
364 * TODO . We work with wide characters, but not for buffer takeovers and
365 * TODO cell2save()ings. This should be changed. For the former the buffer
366 * TODO thus needs to be converted to wide first, and then simply be fed in.
367 * TODO . We repaint too much. To overcome this use the same approach that my
368 * TODO terminal library uses, add a true "virtual screen line" that stores
369 * TODO the actually visible content, keep a notion of "first modified slot"
370 * TODO and "last modified slot" (including "unknown" and "any" specials),
371 * TODO update that virtual instead, then synchronize what has truly changed.
372 * TODO I.e., add an indirection layer.
373 * TODO . No BIDI support.
374 * TODO . `bind': we currently use only one lookup tree.
375 * TODO For absolute graceful behaviour in conjunction (with HAVE_TERMCAP) we
376 * TODO need a lower level tree, which possibly combines bytes into "symbolic
377 * TODO wchar_t values", into "keys" that is, as applicable, and an upper
378 * TODO layer which only works on "keys" in order to possibly combine them
379 * TODO into key sequences. We can reuse existent tree code for that.
380 * TODO We need an additional hashmap which maps termcap/terminfo names to
381 * TODO (their byte representations and) a dynamically assigned unique
382 * TODO "symbolic wchar_t value". This implies we may have incompatibilities
383 * TODO when __STDC_ISO_10646__ is not defined. Also we do need takeover-
384 * TODO bytes storage, but it can be a string_creat_auto in the line struct.
385 * TODO Until then we can run into ambiguities; in rare occasions.
387 #ifdef HAVE_MLE
388 /* To avoid memory leaks etc. with the current codebase that simply longjmp(3)s
389 * we're forced to use the very same buffer--the one that is passed through to
390 * us from the outside--to store anything we need, i.e., a "struct cell[]", and
391 * convert that on-the-fly back to the plain char* result once we're done.
392 * To simplify our live, use savestr() buffers for all other needed memory */
394 # ifdef HAVE_KEY_BINDINGS
395 /* Default *bind-timeout* key-sequence continuation timeout, in tenths of
396 * a second. Must fit in 8-bit! Update the manual upon change! */
397 # define a_TTY_BIND_TIMEOUT 2
398 # define a_TTY_BIND_TIMEOUT_MAX SI8_MAX
400 n_CTAV(a_TTY_BIND_TIMEOUT_MAX <= UI8_MAX);
402 /* We have a chicken-and-egg problem with `bind' and our termcap layer,
403 * because we may not initialize the latter automatically to allow users to
404 * specify *termcap-disable* and let it mean exactly that.
405 * On the other hand users can be expected to use `bind' in resource file(s).
406 * Therefore bindings which involve termcap/terminfo sequences, and which are
407 * defined before n_PSO_STARTED signals usability of termcap/terminfo, will be
408 * (partially) delayed until tty_init() is called.
409 * And we preallocate space for the expansion of the resolved capability */
410 # define a_TTY_BIND_CAPNAME_MAX 15
411 # define a_TTY_BIND_CAPEXP_ROUNDUP 16
413 n_CTAV(n_ISPOW2(a_TTY_BIND_CAPEXP_ROUNDUP));
414 n_CTA(a_TTY_BIND_CAPEXP_ROUNDUP <= SI8_MAX / 2, "Variable must fit in 6-bit");
415 n_CTA(a_TTY_BIND_CAPEXP_ROUNDUP >= 8, "Variable too small");
416 # endif /* HAVE_KEY_BINDINGS */
418 /* The maximum size (of a_tty_cell's) in a line */
419 # define a_TTY_LINE_MAX SI32_MAX
421 /* (Some more CTAs around) */
422 n_CTA(a_TTY_LINE_MAX <= SI32_MAX,
423 "a_TTY_LINE_MAX larger than SI32_MAX, but the MLE uses 32-bit arithmetic");
425 /* When shall the visual screen be scrolled, in % of usable screen width */
426 # define a_TTY_SCROLL_MARGIN_LEFT 15
427 # define a_TTY_SCROLL_MARGIN_RIGHT 10
429 /* fexpand() flags for expand-on-tab */
430 # define a_TTY_TAB_FEXP_FL \
431 (FEXP_NOPROTO | FEXP_FULL | FEXP_SILENT | FEXP_MULTIOK)
433 /* Columns to ripoff: outermost may not be touched, plus position indicator.
434 * Must thus be at least 1, but should be >= 1+4 to dig the position indicator
435 * that we place (if there is sufficient space) */
436 # define a_TTY_WIDTH_RIPOFF 5
438 /* The implementation of the MLE functions always exists, and is based upon
439 * the a_TTY_BIND_FUN_* constants, so most of this enum is always necessary */
440 enum a_tty_bind_flags{
441 # ifdef HAVE_KEY_BINDINGS
442 a_TTY_BIND_RESOLVE = 1u<<8, /* Term cap. yet needs to be resolved */
443 a_TTY_BIND_DEFUNCT = 1u<<9, /* Unicode/term cap. used but not avail. */
444 a_TTY__BIND_MASK = a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT,
445 /* MLE fun assigned to a one-byte-sequence: this may be used for special
446 * key-sequence bypass processing */
447 a_TTY_BIND_MLE1CNTRL = 1u<<10,
448 a_TTY_BIND_NOCOMMIT = 1u<<11, /* Expansion shall be editable */
449 # endif
451 /* MLE internal commands */
452 a_TTY_BIND_FUN_INTERNAL = 1u<<15,
453 a_TTY__BIND_FUN_SHIFT = 16u,
454 a_TTY__BIND_FUN_SHIFTMAX = 24u,
455 a_TTY__BIND_FUN_MASK = ((1u << a_TTY__BIND_FUN_SHIFTMAX) - 1) &
456 ~((1u << a_TTY__BIND_FUN_SHIFT) - 1),
457 # define a_TTY_BIND_FUN_REDUCE(X) \
458 (((ui32_t)(X) & a_TTY__BIND_FUN_MASK) >> a_TTY__BIND_FUN_SHIFT)
459 # define a_TTY_BIND_FUN_EXPAND(X) \
460 (((ui32_t)(X) & (a_TTY__BIND_FUN_MASK >> a_TTY__BIND_FUN_SHIFT)) << \
461 a_TTY__BIND_FUN_SHIFT)
462 # undef a_X
463 # define a_X(N,I)\
464 a_TTY_BIND_FUN_ ## N = a_TTY_BIND_FUN_EXPAND(I),
466 a_X(BELL, 0)
467 a_X(GO_BWD, 1) a_X(GO_FWD, 2)
468 a_X(GO_WORD_BWD, 3) a_X(GO_WORD_FWD, 4)
469 a_X(GO_HOME, 5) a_X(GO_END, 6)
470 a_X(DEL_BWD, 7) a_X(DEL_FWD, 8)
471 a_X(SNARF_WORD_BWD, 9) a_X(SNARF_WORD_FWD, 10)
472 a_X(SNARF_END, 11) a_X(SNARF_LINE, 12)
473 a_X(HIST_BWD, 13) a_X(HIST_FWD, 14)
474 a_X(HIST_SRCH_BWD, 15) a_X(HIST_SRCH_FWD, 16)
475 a_X(REPAINT, 17)
476 a_X(QUOTE_RNDTRIP, 18)
477 a_X(PROMPT_CHAR, 19)
478 a_X(COMPLETE, 20)
479 a_X(PASTE, 21)
481 a_X(CANCEL, 22)
482 a_X(RESET, 23)
483 a_X(FULLRESET, 24)
484 a_X(COMMIT, 25) /* Must be last one! */
485 # undef a_X
487 a_TTY__BIND_LAST = 1<<25
489 # ifdef HAVE_KEY_BINDINGS
490 n_CTA((ui32_t)a_TTY_BIND_RESOLVE >= (ui32_t)n__GO_INPUT_CTX_MAX1,
491 "Bit carrier lower boundary must be raised to avoid value sharing");
492 # endif
493 n_CTA(a_TTY_BIND_FUN_EXPAND(a_TTY_BIND_FUN_COMMIT) <
494 (1 << a_TTY__BIND_FUN_SHIFTMAX),
495 "Bit carrier range must be expanded to represent necessary bits");
496 n_CTA(a_TTY__BIND_LAST >= (1u << a_TTY__BIND_FUN_SHIFTMAX),
497 "Bit carrier upper boundary must be raised to avoid value sharing");
498 n_CTA(UICMP(64, a_TTY__BIND_LAST, <=, SI32_MAX),
499 "Flag bits excess storage datatype" /* And we need one bit free */);
501 enum a_tty_fun_status{
502 a_TTY_FUN_STATUS_OK, /* Worked, next character */
503 a_TTY_FUN_STATUS_COMMIT, /* Line done */
504 a_TTY_FUN_STATUS_RESTART, /* Complete restart, reset multibyte etc. */
505 a_TTY_FUN_STATUS_END /* End, return EOF */
508 enum a_tty_visual_flags{
509 a_TTY_VF_NONE,
510 a_TTY_VF_MOD_CURSOR = 1u<<0, /* Cursor moved */
511 a_TTY_VF_MOD_CONTENT = 1u<<1, /* Content modified */
512 a_TTY_VF_MOD_DIRTY = 1u<<2, /* Needs complete repaint */
513 a_TTY_VF_MOD_SINGLE = 1u<<3, /* TODO Drop when indirection as above comes */
514 a_TTY_VF_REFRESH = a_TTY_VF_MOD_DIRTY | a_TTY_VF_MOD_CURSOR |
515 a_TTY_VF_MOD_CONTENT | a_TTY_VF_MOD_SINGLE,
516 a_TTY_VF_BELL = 1u<<8, /* Ring the bell */
517 a_TTY_VF_SYNC = 1u<<9, /* Flush/Sync I/O channel */
519 a_TTY_VF_ALL_MASK = a_TTY_VF_REFRESH | a_TTY_VF_BELL | a_TTY_VF_SYNC,
520 a_TTY__VF_LAST = a_TTY_VF_SYNC
523 # ifdef HAVE_KEY_BINDINGS
524 struct a_tty_bind_ctx{
525 struct a_tty_bind_ctx *tbc_next;
526 char *tbc_seq; /* quence as given (poss. re-quoted), in .tb__buf */
527 char *tbc_exp; /* ansion, in .tb__buf */
528 /* The .tbc_seq'uence with any terminal capabilities resolved; in fact an
529 * array of structures, the first entry of which is {si32_t buf_len_iscap;}
530 * where the signed bit indicates whether the buffer is a resolved terminal
531 * capability instead of a (possibly multibyte) character. In .tbc__buf */
532 char *tbc_cnv;
533 ui32_t tbc_seq_len;
534 ui32_t tbc_exp_len;
535 ui32_t tbc_cnv_len;
536 ui32_t tbc_flags;
537 char tbc__buf[n_VFIELD_SIZE(0)];
540 struct a_tty_bind_ctx_map{
541 enum n_go_input_flags tbcm_ctx;
542 char const tbcm_name[12]; /* Name of `bind' context */
544 # endif /* HAVE_KEY_BINDINGS */
546 struct a_tty_bind_builtin_tuple{
547 bool_t tbbt_iskey; /* Whether this is a control key; else termcap query */
548 char tbbt_ckey; /* Control code */
549 ui16_t tbbt_query; /* enum n_termcap_query (instead) */
550 char tbbt_exp[12]; /* String or [0]=NUL/[1]=BIND_FUN_REDUCE() */
552 n_CTA(n__TERMCAP_QUERY_MAX1 <= UI16_MAX,
553 "Enumeration cannot be stored in datatype");
555 # ifdef HAVE_KEY_BINDINGS
556 struct a_tty_bind_parse_ctx{
557 char const *tbpc_cmd; /* Command which parses */
558 char const *tbpc_in_seq; /* In: key sequence */
559 struct str tbpc_exp; /* In/Out: expansion (or NULL) */
560 struct a_tty_bind_ctx *tbpc_tbcp; /* Out: if yet existent */
561 struct a_tty_bind_ctx *tbpc_ltbcp; /* Out: the one before .tbpc_tbcp */
562 char *tbpc_seq; /* Out: normalized sequence */
563 char *tbpc_cnv; /* Out: sequence when read(2)ing it */
564 ui32_t tbpc_seq_len;
565 ui32_t tbpc_cnv_len;
566 ui32_t tbpc_cnv_align_mask; /* For creating a_tty_bind_ctx.tbc_cnv */
567 ui32_t tbpc_flags; /* n_go_input_flags | a_tty_bind_flags */
570 /* Input character tree */
571 struct a_tty_bind_tree{
572 struct a_tty_bind_tree *tbt_sibling; /* s at same level */
573 struct a_tty_bind_tree *tbt_childs; /* Sequence continues.. here */
574 struct a_tty_bind_tree *tbt_parent;
575 struct a_tty_bind_ctx *tbt_bind; /* NULL for intermediates */
576 wchar_t tbt_char; /* acter this level represents */
577 bool_t tbt_isseq; /* Belongs to multibyte sequence */
578 bool_t tbt_isseq_trail; /* ..is trailing byte of it */
579 ui8_t tbt__dummy[2];
581 # endif /* HAVE_KEY_BINDINGS */
583 struct a_tty_cell{
584 wchar_t tc_wc;
585 ui16_t tc_count; /* ..of bytes */
586 ui8_t tc_width; /* Visual width; TAB==UI8_MAX! */
587 bool_t tc_novis; /* Don't display visually as such (control character) */
588 char tc_cbuf[MB_LEN_MAX * 2]; /* .. plus reset shift sequence */
591 struct a_tty_global{
592 struct a_tty_line *tg_line; /* To be able to access it from signal hdl */
593 # ifdef HAVE_HISTORY
594 struct a_tty_hist *tg_hist;
595 struct a_tty_hist *tg_hist_tail;
596 size_t tg_hist_size;
597 size_t tg_hist_size_max;
598 # endif
599 # ifdef HAVE_KEY_BINDINGS
600 ui32_t tg_bind_cnt; /* Overall number of bindings */
601 bool_t tg_bind_isdirty;
602 bool_t tg_bind_isbuild;
603 # define a_TTY_SHCUT_MAX (3 +1) /* Note: update manual on change! */
604 ui8_t tg_bind__dummy[2];
605 char tg_bind_shcut_cancel[n__GO_INPUT_CTX_MAX1][a_TTY_SHCUT_MAX];
606 char tg_bind_shcut_prompt_char[n__GO_INPUT_CTX_MAX1][a_TTY_SHCUT_MAX];
607 struct a_tty_bind_ctx *tg_bind[n__GO_INPUT_CTX_MAX1];
608 struct a_tty_bind_tree *tg_bind_tree[n__GO_INPUT_CTX_MAX1][HSHSIZE];
609 # endif
610 struct termios tg_tios_old;
611 struct termios tg_tios_new;
613 # ifdef HAVE_KEY_BINDINGS
614 n_CTA(n__GO_INPUT_CTX_MAX1 == 3 && a_TTY_SHCUT_MAX == 4 &&
615 n_SIZEOF_FIELD(struct a_tty_global, tg_bind__dummy) == 2,
616 "Value results in array sizes that results in bad structure layout");
617 n_CTA(a_TTY_SHCUT_MAX > 1,
618 "Users need at least one shortcut, plus NUL terminator");
619 # endif
621 # ifdef HAVE_HISTORY
622 struct a_tty_hist{
623 struct a_tty_hist *th_older;
624 struct a_tty_hist *th_younger;
625 ui32_t th_isgabby : 1;
626 ui32_t th_len : 31;
627 char th_dat[n_VFIELD_SIZE(sizeof(ui32_t))];
629 # endif
631 struct a_tty_line{
632 /* Caller pointers */
633 char **tl_x_buf;
634 size_t *tl_x_bufsize;
635 /* Input processing */
636 # ifdef HAVE_KEY_BINDINGS
637 wchar_t tl_bind_takeover; /* Leftover byte to consume next */
638 ui8_t tl_bind_timeout; /* In-seq. inter-byte-timer, in 1/10th secs */
639 ui8_t tl__bind_dummy[3];
640 char (*tl_bind_shcut_cancel)[a_TTY_SHCUT_MAX]; /* Special _CANCEL control */
641 char (*tl_bind_shcut_prompt_char)[a_TTY_SHCUT_MAX]; /* ..for _PROMPT_CHAR */
642 struct a_tty_bind_tree *(*tl_bind_tree_hmap)[HSHSIZE]; /* Bind lookup tree */
643 struct a_tty_bind_tree *tl_bind_tree;
644 # endif
645 /* Line data / content handling */
646 ui32_t tl_count; /* ..of a_tty_cell's (<= a_TTY_LINE_MAX) */
647 ui32_t tl_cursor; /* Current a_tty_cell insertion point */
648 union{
649 char *cbuf; /* *.tl_x_buf */
650 struct a_tty_cell *cells;
651 } tl_line;
652 struct str tl_defc; /* Current default content */
653 size_t tl_defc_cursor_byte; /* Desired position of cursor after takeover */
654 struct str tl_savec; /* Saved default content */
655 struct str tl_pastebuf; /* Last snarfed data */
656 # ifdef HAVE_HISTORY
657 struct a_tty_hist *tl_hist; /* History cursor */
658 # endif
659 ui32_t tl_count_max; /* ..before buffer needs to grow */
660 /* Visual data representation handling */
661 ui32_t tl_vi_flags; /* enum a_tty_visual_flags */
662 ui32_t tl_lst_count; /* .tl_count after last sync */
663 ui32_t tl_lst_cursor; /* .tl_cursor after last sync */
664 /* TODO Add another indirection layer by adding a tl_phy_line of
665 * TODO a_tty_cell objects, incorporate changes in visual layer,
666 * TODO then check what _really_ has changed, sync those changes only */
667 struct a_tty_cell const *tl_phy_start; /* First visible cell, left border */
668 ui32_t tl_phy_cursor; /* Physical cursor position */
669 bool_t tl_quote_rndtrip; /* For _kht() expansion */
670 ui8_t tl__dummy2[3];
671 ui32_t tl_prompt_length; /* Preclassified (TODO needed as a_tty_cell) */
672 ui32_t tl_prompt_width;
673 char const *tl_prompt; /* Preformatted prompt (including colours) */
674 /* .tl_pos_buf is a hack */
675 # ifdef HAVE_COLOUR
676 char *tl_pos_buf; /* mle-position colour-on, [4], reset seq. */
677 char *tl_pos; /* Address of the [4] */
678 # endif
681 # ifdef HAVE_KEY_BINDINGS
682 /* C99: use [INDEX]={} */
683 n_CTAV(n_GO_INPUT_CTX_BASE == 0);
684 n_CTAV(n_GO_INPUT_CTX_DEFAULT == 1);
685 n_CTAV(n_GO_INPUT_CTX_COMPOSE == 2);
686 static struct a_tty_bind_ctx_map const
687 a_tty_bind_ctx_maps[n__GO_INPUT_CTX_MAX1] = {
688 {n_GO_INPUT_CTX_BASE, "base"},
689 {n_GO_INPUT_CTX_DEFAULT, "default"},
690 {n_GO_INPUT_CTX_COMPOSE, "compose"}
693 /* Special functions which our MLE provides internally.
694 * Update the manual upon change! */
695 static char const a_tty_bind_fun_names[][24] = {
696 # undef a_X
697 # define a_X(I,N) \
698 n_FIELD_INITI(a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## I)) "mle-" N "\0",
700 a_X(BELL, "bell")
701 a_X(GO_BWD, "go-bwd") a_X(GO_FWD, "go-fwd")
702 a_X(GO_WORD_BWD, "go-word-bwd") a_X(GO_WORD_FWD, "go-word-fwd")
703 a_X(GO_HOME, "go-home") a_X(GO_END, "go-end")
704 a_X(DEL_BWD, "del-bwd") a_X(DEL_FWD, "del-fwd")
705 a_X(SNARF_WORD_BWD, "snarf-word-bwd") a_X(SNARF_WORD_FWD, "snarf-word-fwd")
706 a_X(SNARF_END, "snarf-end") a_X(SNARF_LINE, "snarf-line")
707 a_X(HIST_BWD, "hist-bwd") a_X(HIST_FWD, "hist-fwd")
708 a_X(HIST_SRCH_BWD, "hist-srch-bwd") a_X(HIST_SRCH_FWD, "hist-srch-fwd")
709 a_X(REPAINT, "repaint")
710 a_X(QUOTE_RNDTRIP, "quote-rndtrip")
711 a_X(PROMPT_CHAR, "prompt-char")
712 a_X(COMPLETE, "complete")
713 a_X(PASTE, "paste")
715 a_X(CANCEL, "cancel")
716 a_X(RESET, "reset")
717 a_X(FULLRESET, "fullreset")
718 a_X(COMMIT, "commit")
720 # undef a_X
722 # endif /* HAVE_KEY_BINDINGS */
724 /* The default key bindings (unless disallowed). Update manual upon change!
725 * A logical subset of this table is also used if !HAVE_KEY_BINDINGS (more
726 * expensive than a switch() on control codes directly, but less redundant).
727 * The table for the "base" context */
728 static struct a_tty_bind_builtin_tuple const a_tty_bind_base_tuples[] = {
729 # undef a_X
730 # define a_X(K,S) \
731 {TRU1, K, 0, {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
733 a_X('A', GO_HOME)
734 a_X('B', GO_BWD)
735 /* C: SIGINT */
736 a_X('D', DEL_FWD)
737 a_X('E', GO_END)
738 a_X('F', GO_FWD)
739 a_X('G', RESET)
740 a_X('H', DEL_BWD)
741 a_X('I', COMPLETE)
742 a_X('J', COMMIT)
743 a_X('K', SNARF_END)
744 a_X('L', REPAINT)
745 /* M: same as J */
746 a_X('N', HIST_FWD)
747 /* O: below */
748 a_X('P', HIST_BWD)
749 a_X('Q', QUOTE_RNDTRIP)
750 a_X('R', HIST_SRCH_BWD)
751 a_X('S', HIST_SRCH_FWD)
752 a_X('T', PASTE)
753 a_X('U', SNARF_LINE)
754 a_X('V', PROMPT_CHAR)
755 a_X('W', SNARF_WORD_BWD)
756 a_X('X', GO_WORD_FWD)
757 a_X('Y', GO_WORD_BWD)
758 /* Z: SIGTSTP */
760 a_X('[', CANCEL)
761 /* \: below */
762 /* ]: below */
763 /* ^: below */
764 a_X('_', SNARF_WORD_FWD)
766 a_X('?', DEL_BWD)
768 # undef a_X
769 # define a_X(K,S) {TRU1, K, 0, {S}},
771 /* The remains only if we have `bind' functionality available */
772 # ifdef HAVE_KEY_BINDINGS
773 # undef a_X
774 # define a_X(Q,S) \
775 {FAL0, '\0', n_TERMCAP_QUERY_ ## Q,\
776 {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
778 a_X(key_backspace, DEL_BWD) a_X(key_dc, DEL_FWD)
779 a_X(key_eol, SNARF_END)
780 a_X(key_home, GO_HOME) a_X(key_end, GO_END)
781 a_X(key_left, GO_BWD) a_X(key_right, GO_FWD)
782 a_X(key_sleft, GO_HOME) a_X(key_sright, GO_END)
783 a_X(key_up, HIST_BWD) a_X(key_down, HIST_FWD)
784 # endif /* HAVE_KEY_BINDINGS */
787 /* The table for the "default" context.
788 * We don't want commands to end up in history, so place an initial space */
789 static struct a_tty_bind_builtin_tuple const a_tty_bind_default_tuples[] = {
790 # undef a_X
791 # define a_X(K,S) \
792 {TRU1, K, 0, {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
794 # undef a_X
795 # define a_X(K,S) {TRU1, K, 0, {" " S}},
797 a_X('O', "dt")
799 a_X('\\', "z+")
800 a_X(']', "z$")
801 a_X('^', "z0")
803 /* The remains only if we have `bind' functionality available */
804 # ifdef HAVE_KEY_BINDINGS
805 # undef a_X
806 # define a_X(Q,S) {FAL0, '\0', n_TERMCAP_QUERY_ ## Q, {" " S}},
808 a_X(key_shome, "z0") a_X(key_send, "z$")
809 a_X(xkey_sup, "z0") a_X(xkey_sdown, "z$")
810 a_X(key_ppage, "z-") a_X(key_npage, "z+")
811 a_X(xkey_cup, "dotmove-") a_X(xkey_cdown, "dotmove+")
812 # endif /* HAVE_KEY_BINDINGS */
814 # undef a_X
816 static struct a_tty_global a_tty;
818 /* Change from canonical to raw, non-canonical mode, and way back */
819 static void a_tty_term_mode(bool_t raw);
821 /* Initialize .tg_hist_size_max and return desired history file, or NULL */
822 # ifdef HAVE_HISTORY
823 static char const *a_tty_hist_query_config(void);
824 # endif
826 /* Adjust an active raw mode to use / not use a timeout */
827 # ifdef HAVE_KEY_BINDINGS
828 static void a_tty_term_rawmode_timeout(struct a_tty_line *tlp, bool_t enable);
829 # endif
831 /* 0-X (2), UI8_MAX == \t / TAB */
832 static ui8_t a_tty_wcwidth(wchar_t wc);
834 /* Memory / cell / word generics */
835 static void a_tty_check_grow(struct a_tty_line *tlp, ui32_t no
836 n_MEMORY_DEBUG_ARGS);
837 static ssize_t a_tty_cell2dat(struct a_tty_line *tlp);
838 static void a_tty_cell2save(struct a_tty_line *tlp);
840 /* Save away data bytes of given range (max = non-inclusive) */
841 static void a_tty_copy2paste(struct a_tty_line *tlp, struct a_tty_cell *tcpmin,
842 struct a_tty_cell *tcpmax);
844 /* Ask user for hexadecimal number, interpret as UTF-32 */
845 static wchar_t a_tty_vinuni(struct a_tty_line *tlp);
847 /* Visual screen synchronization */
848 static bool_t a_tty_vi_refresh(struct a_tty_line *tlp);
850 static bool_t a_tty_vi__paint(struct a_tty_line *tlp);
852 /* Search for word boundary, starting at tl_cursor, in "dir"ection (<> 0).
853 * Return <0 when moving is impossible (backward direction but in position 0,
854 * forward direction but in outermost column), and relative distance to
855 * tl_cursor otherwise */
856 static si32_t a_tty_wboundary(struct a_tty_line *tlp, si32_t dir);
858 /* Most function implementations */
859 static void a_tty_khome(struct a_tty_line *tlp, bool_t dobell);
860 static void a_tty_kend(struct a_tty_line *tlp);
861 static void a_tty_kbs(struct a_tty_line *tlp);
862 static void a_tty_ksnarf(struct a_tty_line *tlp, bool_t cplline, bool_t dobell);
863 static si32_t a_tty_kdel(struct a_tty_line *tlp);
864 static void a_tty_kleft(struct a_tty_line *tlp);
865 static void a_tty_kright(struct a_tty_line *tlp);
866 static void a_tty_ksnarfw(struct a_tty_line *tlp, bool_t fwd);
867 static void a_tty_kgow(struct a_tty_line *tlp, si32_t dir);
868 static bool_t a_tty_kother(struct a_tty_line *tlp, wchar_t wc);
869 static ui32_t a_tty_kht(struct a_tty_line *tlp);
871 # ifdef HAVE_HISTORY
872 /* Return UI32_MAX on "exhaustion" */
873 static ui32_t a_tty_khist(struct a_tty_line *tlp, bool_t fwd);
874 static ui32_t a_tty_khist_search(struct a_tty_line *tlp, bool_t fwd);
876 static ui32_t a_tty__khist_shared(struct a_tty_line *tlp,
877 struct a_tty_hist *thp);
878 # endif
880 /* Handle a function */
881 static enum a_tty_fun_status a_tty_fun(struct a_tty_line *tlp,
882 enum a_tty_bind_flags tbf, size_t *len);
884 /* Readline core */
885 static ssize_t a_tty_readline(struct a_tty_line *tlp, size_t len
886 n_MEMORY_DEBUG_ARGS);
888 # ifdef HAVE_KEY_BINDINGS
889 /* Find context or -1 */
890 static enum n_go_input_flags a_tty_bind_ctx_find(char const *name);
892 /* Create (or replace, if allowed) a binding */
893 static bool_t a_tty_bind_create(struct a_tty_bind_parse_ctx *tbpcp,
894 bool_t replace);
896 /* Shared implementation to parse `bind' and `unbind' "key-sequence" and
897 * "expansion" command line arguments into something that we can work with */
898 static bool_t a_tty_bind_parse(bool_t isbindcmd,
899 struct a_tty_bind_parse_ctx *tbpcp);
901 /* Lazy resolve a termcap(5)/terminfo(5) (or *termcap*!) capability */
902 static void a_tty_bind_resolve(struct a_tty_bind_ctx *tbcp);
904 /* Delete an existing binding */
905 static void a_tty_bind_del(struct a_tty_bind_parse_ctx *tbpcp);
907 /* Life cycle of all input node trees */
908 static void a_tty_bind_tree_build(void);
909 static void a_tty_bind_tree_teardown(void);
911 static void a_tty__bind_tree_add(ui32_t hmap_idx,
912 struct a_tty_bind_tree *store[HSHSIZE],
913 struct a_tty_bind_ctx *tbcp);
914 static struct a_tty_bind_tree *a_tty__bind_tree_add_wc(
915 struct a_tty_bind_tree **treep, struct a_tty_bind_tree *parentp,
916 wchar_t wc, bool_t isseq);
917 static void a_tty__bind_tree_free(struct a_tty_bind_tree *tbtp);
918 # endif /* HAVE_KEY_BINDINGS */
920 static void
921 a_tty_term_mode(bool_t raw){
922 struct termios *tiosp;
923 NYD2_ENTER;
925 tiosp = &a_tty.tg_tios_old;
926 if(!raw)
927 goto jleave;
929 /* Always requery the attributes, in case we've been moved from background
930 * to foreground or however else in between sessions */
931 /* XXX Always enforce ECHO and ICANON in the OLD attributes - do so as long
932 * XXX as we don't properly deal with TTIN and TTOU etc. */
933 tcgetattr(STDIN_FILENO, tiosp); /* TODO v15: use _only_ n_tty_fp! */
934 tiosp->c_lflag |= ECHO | ICANON;
936 memcpy(&a_tty.tg_tios_new, tiosp, sizeof *tiosp);
937 tiosp = &a_tty.tg_tios_new;
938 tiosp->c_cc[VMIN] = 1;
939 tiosp->c_cc[VTIME] = 0;
940 /* Enable ^\, ^Q and ^S to be used for key bindings */
941 tiosp->c_cc[VQUIT] = tiosp->c_cc[VSTART] = tiosp->c_cc[VSTOP] = '\0';
942 tiosp->c_iflag &= ~(ISTRIP | IGNCR);
943 tiosp->c_lflag &= ~(ECHO /*| ECHOE | ECHONL */| ICANON | IEXTEN);
944 jleave:
945 tcsetattr(STDIN_FILENO, TCSADRAIN, tiosp);
946 NYD2_LEAVE;
949 # ifdef HAVE_HISTORY
950 static char const *
951 a_tty_hist_query_config(void){
952 char const *rv, *cp;
953 NYD2_ENTER;
955 if((cp = ok_vlook(NAIL_HISTSIZE)) != NULL)
956 n_OBSOLETE(_("please use *history-size* instead of *NAIL_HISTSIZE*"));
957 if((rv = ok_vlook(history_size)) == NULL)
958 rv = cp;
959 if(rv == NULL)
960 a_tty.tg_hist_size_max = UIZ_MAX;
961 else
962 (void)n_idec_uiz_cp(&a_tty.tg_hist_size_max, rv, 10, NULL);
964 if((cp = ok_vlook(NAIL_HISTFILE)) != NULL)
965 n_OBSOLETE(_("please use *history-file* instead of *NAIL_HISTFILE*"));
966 if((rv = ok_vlook(history_file)) == NULL)
967 rv = cp;
968 if(rv != NULL)
969 rv = fexpand(rv, FEXP_LOCAL | FEXP_NSHELL);
970 NYD2_LEAVE;
971 return rv;
973 # endif /* HAVE_HISTORY */
975 # ifdef HAVE_KEY_BINDINGS
976 static void
977 a_tty_term_rawmode_timeout(struct a_tty_line *tlp, bool_t enable){
978 NYD2_ENTER;
979 if(enable){
980 ui8_t bt;
982 a_tty.tg_tios_new.c_cc[VMIN] = 0;
983 if((bt = tlp->tl_bind_timeout) == 0)
984 bt = a_TTY_BIND_TIMEOUT;
985 a_tty.tg_tios_new.c_cc[VTIME] = bt;
986 }else{
987 a_tty.tg_tios_new.c_cc[VMIN] = 1;
988 a_tty.tg_tios_new.c_cc[VTIME] = 0;
990 tcsetattr(STDIN_FILENO, TCSANOW, &a_tty.tg_tios_new);
991 NYD2_LEAVE;
993 # endif /* HAVE_KEY_BINDINGS */
995 static ui8_t
996 a_tty_wcwidth(wchar_t wc){
997 ui8_t rv;
998 NYD2_ENTER;
1000 /* Special case the reverse solidus at first */
1001 if(wc == '\t')
1002 rv = UI8_MAX;
1003 else{
1004 int i;
1006 # ifdef HAVE_WCWIDTH
1007 rv = ((i = wcwidth(wc)) > 0) ? (ui8_t)i : 0;
1008 # else
1009 rv = iswprint(wc) ? 1 + (wc >= 0x1100u) : 0; /* TODO use S-CText */
1010 # endif
1012 NYD2_LEAVE;
1013 return rv;
1016 static void
1017 a_tty_check_grow(struct a_tty_line *tlp, ui32_t no n_MEMORY_DEBUG_ARGS){
1018 ui32_t cmax;
1019 NYD2_ENTER;
1021 if(n_UNLIKELY((cmax = tlp->tl_count + no) > tlp->tl_count_max)){
1022 size_t i;
1024 i = cmax * sizeof(struct a_tty_cell) + 2 * sizeof(struct a_tty_cell);
1025 if(n_LIKELY(i >= *tlp->tl_x_bufsize)){
1026 hold_all_sigs(); /* XXX v15 drop */
1027 i <<= 1;
1028 tlp->tl_line.cbuf =
1029 *tlp->tl_x_buf = (n_realloc)(*tlp->tl_x_buf, i
1030 n_MEMORY_DEBUG_ARGSCALL);
1031 rele_all_sigs(); /* XXX v15 drop */
1033 tlp->tl_count_max = cmax;
1034 *tlp->tl_x_bufsize = i;
1036 NYD2_LEAVE;
1039 static ssize_t
1040 a_tty_cell2dat(struct a_tty_line *tlp){
1041 size_t len, i;
1042 NYD2_ENTER;
1044 len = 0;
1046 if(n_LIKELY((i = tlp->tl_count) > 0)){
1047 struct a_tty_cell const *tcap;
1049 tcap = tlp->tl_line.cells;
1051 memcpy(tlp->tl_line.cbuf + len, tcap->tc_cbuf, tcap->tc_count);
1052 len += tcap->tc_count;
1053 }while(++tcap, --i > 0);
1056 tlp->tl_line.cbuf[len] = '\0';
1057 NYD2_LEAVE;
1058 return (ssize_t)len;
1061 static void
1062 a_tty_cell2save(struct a_tty_line *tlp){
1063 size_t len, i;
1064 struct a_tty_cell *tcap;
1065 NYD2_ENTER;
1067 tlp->tl_savec.s = NULL;
1068 tlp->tl_savec.l = 0;
1070 if(n_UNLIKELY(tlp->tl_count == 0))
1071 goto jleave;
1073 for(tcap = tlp->tl_line.cells, len = 0, i = tlp->tl_count; i > 0;
1074 ++tcap, --i)
1075 len += tcap->tc_count;
1077 tlp->tl_savec.s = salloc((tlp->tl_savec.l = len) +1);
1079 for(tcap = tlp->tl_line.cells, len = 0, i = tlp->tl_count; i > 0;
1080 ++tcap, --i){
1081 memcpy(tlp->tl_savec.s + len, tcap->tc_cbuf, tcap->tc_count);
1082 len += tcap->tc_count;
1084 tlp->tl_savec.s[len] = '\0';
1085 jleave:
1086 NYD2_LEAVE;
1089 static void
1090 a_tty_copy2paste(struct a_tty_line *tlp, struct a_tty_cell *tcpmin,
1091 struct a_tty_cell *tcpmax){
1092 char *cp;
1093 struct a_tty_cell *tcp;
1094 size_t l;
1095 NYD2_ENTER;
1097 l = 0;
1098 for(tcp = tcpmin; tcp < tcpmax; ++tcp)
1099 l += tcp->tc_count;
1101 tlp->tl_pastebuf.s = cp = salloc((tlp->tl_pastebuf.l = l) +1);
1103 l = 0;
1104 for(tcp = tcpmin; tcp < tcpmax; cp += l, ++tcp)
1105 memcpy(cp, tcp->tc_cbuf, l = tcp->tc_count);
1106 *cp = '\0';
1107 NYD2_LEAVE;
1110 static wchar_t
1111 a_tty_vinuni(struct a_tty_line *tlp){
1112 char buf[16];
1113 uiz_t i;
1114 wchar_t wc;
1115 NYD2_ENTER;
1117 wc = '\0';
1119 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr) ||
1120 !n_termcap_cmd(n_TERMCAP_CMD_ce, 0, -1))
1121 goto jleave;
1123 /* C99 */{
1124 struct str const *cpre, *csuf;
1126 cpre = csuf = NULL;
1127 #ifdef HAVE_COLOUR
1128 if(n_COLOUR_IS_ACTIVE()){
1129 struct n_colour_pen *cpen;
1131 cpen = n_colour_pen_create(n_COLOUR_ID_MLE_PROMPT, NULL);
1132 if((cpre = n_colour_pen_to_str(cpen)) != NULL)
1133 csuf = n_colour_reset_to_str();
1135 #endif
1136 fprintf(n_tty_fp, _("%sPlease enter Unicode code point:%s "),
1137 (cpre != NULL ? cpre->s : n_empty),
1138 (csuf != NULL ? csuf->s : n_empty));
1140 fflush(n_tty_fp);
1142 buf[sizeof(buf) -1] = '\0';
1143 for(i = 0;;){
1144 if(read(STDIN_FILENO, &buf[i], 1) != 1){
1145 if(n_err_no == n_ERR_INTR) /* xxx #if !SA_RESTART ? */
1146 continue;
1147 goto jleave;
1149 if(buf[i] == '\n')
1150 break;
1151 if(!hexchar(buf[i])){
1152 char const emsg[] = "[0-9a-fA-F]";
1154 n_LCTA(sizeof emsg <= sizeof(buf), "Preallocated buffer too small");
1155 memcpy(buf, emsg, sizeof emsg);
1156 goto jerr;
1159 putc(buf[i], n_tty_fp);
1160 fflush(n_tty_fp);
1161 if(++i == sizeof buf)
1162 goto jerr;
1164 buf[i] = '\0';
1166 if((n_idec_uiz_cp(&i, buf, 16, NULL
1167 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
1168 ) != n_IDEC_STATE_CONSUMED || i > 0x10FFFF/* XXX magic; CText */){
1169 jerr:
1170 n_err(_("\nInvalid input: %s\n"), buf);
1171 goto jleave;
1174 wc = (wchar_t)i;
1175 jleave:
1176 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY | (wc == '\0' ? a_TTY_VF_BELL : 0);
1177 NYD2_LEAVE;
1178 return wc;
1181 static bool_t
1182 a_tty_vi_refresh(struct a_tty_line *tlp){
1183 bool_t rv;
1184 NYD2_ENTER;
1186 if(tlp->tl_vi_flags & a_TTY_VF_BELL){
1187 tlp->tl_vi_flags |= a_TTY_VF_SYNC;
1188 if(putc('\a', n_tty_fp) == EOF)
1189 goto jerr;
1192 if(tlp->tl_vi_flags & a_TTY_VF_REFRESH){
1193 /* kht may want to restore a cursor position after inserting some
1194 * data somewhere */
1195 if(tlp->tl_defc_cursor_byte > 0){
1196 size_t i, j;
1197 ssize_t k;
1199 a_tty_khome(tlp, FAL0);
1201 i = tlp->tl_defc_cursor_byte;
1202 tlp->tl_defc_cursor_byte = 0;
1203 for(j = 0; tlp->tl_cursor < tlp->tl_count; ++j){
1204 a_tty_kright(tlp);
1205 if((k = tlp->tl_line.cells[j].tc_count) > i)
1206 break;
1207 i -= k;
1211 if(!a_tty_vi__paint(tlp))
1212 goto jerr;
1215 if(tlp->tl_vi_flags & a_TTY_VF_SYNC){
1216 tlp->tl_vi_flags &= ~a_TTY_VF_SYNC;
1217 if(fflush(n_tty_fp))
1218 goto jerr;
1221 rv = TRU1;
1222 jleave:
1223 tlp->tl_vi_flags &= ~a_TTY_VF_ALL_MASK;
1224 NYD2_LEAVE;
1225 return rv;
1227 jerr:
1228 clearerr(n_tty_fp); /* xxx I/O layer rewrite */
1229 n_err(_("Visual refresh failed! Is $TERM set correctly?\n"
1230 " Setting *line-editor-disable* to get us through!\n"));
1231 ok_bset(line_editor_disable);
1232 rv = FAL0;
1233 goto jleave;
1236 static bool_t
1237 a_tty_vi__paint(struct a_tty_line *tlp){
1238 enum{
1239 a_TRUE_RV = a_TTY__VF_LAST<<1, /* Return value bit */
1240 a_HAVE_PROMPT = a_TTY__VF_LAST<<2, /* Have a prompt */
1241 a_SHOW_PROMPT = a_TTY__VF_LAST<<3, /* Shall print the prompt */
1242 a_MOVE_CURSOR = a_TTY__VF_LAST<<4, /* Move visual cursor for user! */
1243 a_LEFT_MIN = a_TTY__VF_LAST<<5, /* On left boundary */
1244 a_RIGHT_MAX = a_TTY__VF_LAST<<6,
1245 a_HAVE_POSITION = a_TTY__VF_LAST<<7, /* Print the position indicator */
1247 /* We carry some flags over invocations (not worth a specific field) */
1248 a_VISIBLE_PROMPT = a_TTY__VF_LAST<<8, /* The prompt is on the screen */
1249 a_PERSIST_MASK = a_VISIBLE_PROMPT,
1250 a__LAST = a_PERSIST_MASK
1253 ui32_t f, w, phy_wid_base, phy_wid, phy_base, phy_cur, cnt,
1254 DBG(lstcur COMMA) cur,
1255 vi_left, /*vi_right,*/ phy_nxtcur;
1256 struct a_tty_cell const *tccp, *tcp_left, *tcp_right, *tcxp;
1257 NYD2_ENTER;
1258 n_LCTA(UICMP(64, a__LAST, <, UI32_MAX), "Flag bits excess storage datatype");
1260 f = tlp->tl_vi_flags;
1261 tlp->tl_vi_flags = (f & ~(a_TTY_VF_REFRESH | a_PERSIST_MASK)) |
1262 a_TTY_VF_SYNC;
1263 f |= a_TRUE_RV;
1264 if((w = tlp->tl_prompt_width) > 0)
1265 f |= a_HAVE_PROMPT;
1266 f |= a_HAVE_POSITION;
1268 /* XXX We don't have a OnTerminalResize event (see main.c) yet, so we need
1269 * XXX to reevaluate our circumstances over and over again */
1270 /* Don't display prompt or position indicator on very small screens */
1271 if((phy_wid_base = (ui32_t)n_scrnwidth) <= a_TTY_WIDTH_RIPOFF)
1272 f &= ~(a_HAVE_PROMPT | a_HAVE_POSITION);
1273 else{
1274 phy_wid_base -= a_TTY_WIDTH_RIPOFF;
1276 /* Disable the prompt if the screen is too small; due to lack of some
1277 * indicator simply add a second ripoff */
1278 if((f & a_HAVE_PROMPT) && w + a_TTY_WIDTH_RIPOFF >= phy_wid_base)
1279 f &= ~a_HAVE_PROMPT;
1282 phy_wid = phy_wid_base;
1283 phy_base = 0;
1284 phy_cur = tlp->tl_phy_cursor;
1285 cnt = tlp->tl_count;
1286 DBG( lstcur = tlp->tl_lst_cursor; )
1288 /* XXX Assume dirty screen if shrunk */
1289 if(cnt < tlp->tl_lst_count)
1290 f |= a_TTY_VF_MOD_DIRTY;
1292 /* TODO Without HAVE_TERMCAP, it would likely be much cheaper to simply
1293 * TODO always "cr + paint + ce + ch", since ce is simulated via spaces.. */
1295 /* Quickshot: if the line is empty, possibly print prompt and out */
1296 if(cnt == 0){
1297 /* In that special case dirty anything if it seems better */
1298 if((f & a_TTY_VF_MOD_CONTENT) || tlp->tl_lst_count > 0)
1299 f |= a_TTY_VF_MOD_DIRTY;
1301 if((f & a_TTY_VF_MOD_DIRTY) && phy_cur != 0){
1302 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
1303 goto jerr;
1304 phy_cur = 0;
1307 if((f & (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)) ==
1308 (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)){
1309 if(fputs(tlp->tl_prompt, n_tty_fp) == EOF)
1310 goto jerr;
1311 phy_cur = tlp->tl_prompt_width + 1;
1314 /* May need to clear former line content */
1315 if((f & a_TTY_VF_MOD_DIRTY) &&
1316 !n_termcap_cmd(n_TERMCAP_CMD_ce, phy_cur, -1))
1317 goto jerr;
1319 tlp->tl_phy_start = tlp->tl_line.cells;
1320 goto jleave;
1323 /* Try to get an idea of the visual window */
1325 /* Find the left visual boundary */
1326 phy_wid = (phy_wid >> 1) + (phy_wid >> 2);
1327 if((cur = tlp->tl_cursor) == cnt)
1328 --cur;
1330 w = (tcp_left = tccp = tlp->tl_line.cells + cur)->tc_width;
1331 if(w == UI8_MAX) /* TODO yet TAB == SPC */
1332 w = 1;
1333 while(tcp_left > tlp->tl_line.cells){
1334 ui16_t cw = tcp_left[-1].tc_width;
1336 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1337 cw = 1;
1338 if(w + cw >= phy_wid)
1339 break;
1340 w += cw;
1341 --tcp_left;
1343 vi_left = w;
1345 /* If the left hand side of our visual viewpoint consumes less than half
1346 * of the screen width, show the prompt */
1347 if(tcp_left == tlp->tl_line.cells)
1348 f |= a_LEFT_MIN;
1350 if((f & (a_LEFT_MIN | a_HAVE_PROMPT)) == (a_LEFT_MIN | a_HAVE_PROMPT) &&
1351 w + tlp->tl_prompt_width < phy_wid){
1352 phy_base = tlp->tl_prompt_width;
1353 f |= a_SHOW_PROMPT;
1356 /* Then search for right boundary. We always leave the rightmost column
1357 * empty because some terminals [cw]ould wrap the line if we write into
1358 * that. XXX terminfo(5)/termcap(5) have the semi_auto_right_margin/sam/YE
1359 * XXX capability to indicate this, but we don't look at that */
1360 phy_wid = phy_wid_base - phy_base;
1361 tcp_right = tlp->tl_line.cells + cnt;
1363 while(&tccp[1] < tcp_right){
1364 ui16_t cw = tccp[1].tc_width;
1365 ui32_t i;
1367 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1368 cw = 1;
1369 i = w + cw;
1370 if(i > phy_wid)
1371 break;
1372 w = i;
1373 ++tccp;
1375 /*vi_right = w - vi_left;*/
1377 /* If the complete line including prompt fits on the screen, show prompt */
1378 if(--tcp_right == tccp){
1379 f |= a_RIGHT_MAX;
1381 /* Since we did brute-force walk also for the left boundary we may end up
1382 * in a situation were anything effectively fits on the screen, including
1383 * the prompt that is, but were we don't recognize this since we
1384 * restricted the search to fit in some visual viewpoint. Therefore try
1385 * again to extend the left boundary to overcome that */
1386 if(!(f & a_LEFT_MIN)){
1387 struct a_tty_cell const *tc1p = tlp->tl_line.cells;
1388 ui32_t vil1 = vi_left;
1390 assert(!(f & a_SHOW_PROMPT));
1391 w += tlp->tl_prompt_width;
1392 for(tcxp = tcp_left;;){
1393 ui32_t i = tcxp[-1].tc_width;
1395 if(i == UI8_MAX) /* TODO yet TAB == SPC */
1396 i = 1;
1397 vil1 += i;
1398 i += w;
1399 if(i > phy_wid)
1400 break;
1401 w = i;
1402 if(--tcxp == tc1p){
1403 tcp_left = tc1p;
1404 vi_left = vil1;
1405 f |= a_LEFT_MIN;
1406 break;
1409 /*w -= tlp->tl_prompt_width;*/
1412 tcp_right = tccp;
1413 tccp = tlp->tl_line.cells + cur;
1415 if((f & (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT | a_SHOW_PROMPT)) ==
1416 (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT) &&
1417 w + tlp->tl_prompt_width <= phy_wid){
1418 phy_wid -= (phy_base = tlp->tl_prompt_width);
1419 f |= a_SHOW_PROMPT;
1422 /* Try to avoid repainting the complete line - this is possible if the
1423 * cursor "did not leave the screen" and the prompt status hasn't changed.
1424 * I.e., after clamping virtual viewpoint, compare relation to physical */
1425 if((f & (a_TTY_VF_MOD_SINGLE/*FIXME*/ |
1426 a_TTY_VF_MOD_CONTENT/* xxx */ | a_TTY_VF_MOD_DIRTY)) ||
1427 (tcxp = tlp->tl_phy_start) == NULL ||
1428 tcxp > tccp || tcxp <= tcp_right)
1429 f |= a_TTY_VF_MOD_DIRTY;
1430 else{
1431 f |= a_TTY_VF_MOD_DIRTY;
1432 #if 0
1433 struct a_tty_cell const *tcyp;
1434 si32_t cur_displace;
1435 ui32_t phy_lmargin, phy_rmargin, fx, phy_displace;
1437 phy_lmargin = (fx = phy_wid) / 100;
1438 phy_rmargin = fx - (phy_lmargin * a_TTY_SCROLL_MARGIN_RIGHT);
1439 phy_lmargin *= a_TTY_SCROLL_MARGIN_LEFT;
1440 fx = (f & (a_SHOW_PROMPT | a_VISIBLE_PROMPT));
1442 if(fx == 0 || fx == (a_SHOW_PROMPT | a_VISIBLE_PROMPT)){
1444 #endif
1446 goto jpaint;
1448 /* We know what we have to paint, start synchronizing */
1449 jpaint:
1450 assert(phy_cur == tlp->tl_phy_cursor);
1451 assert(phy_wid == phy_wid_base - phy_base);
1452 assert(cnt == tlp->tl_count);
1453 assert(cnt > 0);
1454 assert(lstcur == tlp->tl_lst_cursor);
1455 assert(tccp == tlp->tl_line.cells + cur);
1457 phy_nxtcur = phy_base; /* FIXME only if repaint cpl. */
1459 /* Quickshot: is it only cursor movement within the visible screen? */
1460 if((f & a_TTY_VF_REFRESH) == a_TTY_VF_MOD_CURSOR){
1461 f |= a_MOVE_CURSOR;
1462 goto jcursor;
1465 /* To be able to apply some quick jump offs, clear line if possible */
1466 if(f & a_TTY_VF_MOD_DIRTY){
1467 /* Force complete clearance and cursor reinitialization */
1468 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr) ||
1469 !n_termcap_cmd(n_TERMCAP_CMD_ce, 0, -1))
1470 goto jerr;
1471 tlp->tl_phy_start = tcp_left;
1472 phy_cur = 0;
1475 if((f & (a_TTY_VF_MOD_DIRTY | a_SHOW_PROMPT)) && phy_cur != 0){
1476 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
1477 goto jerr;
1478 phy_cur = 0;
1481 if(f & a_SHOW_PROMPT){
1482 assert(phy_base == tlp->tl_prompt_width);
1483 if(fputs(tlp->tl_prompt, n_tty_fp) == EOF)
1484 goto jerr;
1485 phy_cur = phy_nxtcur;
1486 f |= a_VISIBLE_PROMPT;
1487 }else
1488 f &= ~a_VISIBLE_PROMPT;
1490 /* FIXME reposition cursor for paint */
1491 for(w = phy_nxtcur; tcp_left <= tcp_right; ++tcp_left){
1492 ui16_t cw;
1494 cw = tcp_left->tc_width;
1496 if(n_LIKELY(!tcp_left->tc_novis)){
1497 if(fwrite(tcp_left->tc_cbuf, sizeof *tcp_left->tc_cbuf,
1498 tcp_left->tc_count, n_tty_fp) != tcp_left->tc_count)
1499 goto jerr;
1500 }else{ /* XXX Shouldn't be here <-> CText, ui_str.c */
1501 char wbuf[8]; /* XXX magic */
1503 if(n_psonce & n_PSO_UNICODE){
1504 ui32_t wc;
1506 wc = (ui32_t)tcp_left->tc_wc;
1507 if((wc & ~0x1Fu) == 0)
1508 wc |= 0x2400;
1509 else if(wc == 0x7F)
1510 wc = 0x2421;
1511 else
1512 wc = 0x2426;
1513 n_utf32_to_utf8(wc, wbuf);
1514 }else
1515 wbuf[0] = '?', wbuf[1] = '\0';
1517 if(fputs(wbuf, n_tty_fp) == EOF)
1518 goto jerr;
1519 cw = 1;
1522 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1523 cw = 1;
1524 w += cw;
1525 if(tcp_left == tccp)
1526 phy_nxtcur = w;
1527 phy_cur += cw;
1530 /* Write something position marker alike if it doesn't fit on screen */
1531 if((f & a_HAVE_POSITION) &&
1532 ((f & (a_LEFT_MIN | a_RIGHT_MAX)) != (a_LEFT_MIN | a_RIGHT_MAX) ||
1533 ((f & a_HAVE_PROMPT) && !(f & a_SHOW_PROMPT)))){
1534 # ifdef HAVE_COLOUR
1535 char *posbuf = tlp->tl_pos_buf, *pos = tlp->tl_pos;
1536 # else
1537 char posbuf[5], *pos = posbuf;
1539 pos[4] = '\0';
1540 # endif
1542 if(phy_cur != (w = phy_wid_base) &&
1543 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = w, 0))
1544 goto jerr;
1546 *pos++ = '|';
1547 if((f & a_LEFT_MIN) && (!(f & a_HAVE_PROMPT) || (f & a_SHOW_PROMPT)))
1548 memcpy(pos, "^.+", 3);
1549 else if(f & a_RIGHT_MAX)
1550 memcpy(pos, ".+$", 3);
1551 else{
1552 /* Theoretical line length limit a_TTY_LINE_MAX, choose next power of
1553 * ten (10 ** 10) to represent 100 percent, since we don't have a macro
1554 * that generates a constant, and i don't trust the standard "u type
1555 * suffix automatically scales" calculate the large number */
1556 static char const itoa[] = "0123456789";
1558 ui64_t const fact100 = (ui64_t)0x3B9ACA00u * 10u, fact = fact100 / 100;
1559 ui32_t i = (ui32_t)(((fact100 / cnt) * tlp->tl_cursor) / fact);
1560 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1562 if(i < 10)
1563 pos[0] = ' ', pos[1] = itoa[i];
1564 else
1565 pos[1] = itoa[i % 10], pos[0] = itoa[i / 10];
1566 pos[2] = '%';
1569 if(fputs(posbuf, n_tty_fp) == EOF)
1570 goto jerr;
1571 phy_cur += 4;
1574 /* Users are used to see the cursor right of the point of interest, so we
1575 * need some further adjustments unless in special conditions. Be aware
1576 * that we may have adjusted cur at the beginning, too */
1577 if((cur = tlp->tl_cursor) == 0)
1578 phy_nxtcur = phy_base;
1579 else if(cur != cnt){
1580 ui16_t cw = tccp->tc_width;
1582 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1583 cw = 1;
1584 phy_nxtcur -= cw;
1587 jcursor:
1588 if(((f & a_MOVE_CURSOR) || phy_nxtcur != phy_cur) &&
1589 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = phy_nxtcur, 0))
1590 goto jerr;
1592 jleave:
1593 tlp->tl_vi_flags |= (f & a_PERSIST_MASK);
1594 tlp->tl_lst_count = tlp->tl_count;
1595 tlp->tl_lst_cursor = tlp->tl_cursor;
1596 tlp->tl_phy_cursor = phy_cur;
1598 NYD2_LEAVE;
1599 return ((f & a_TRUE_RV) != 0);
1600 jerr:
1601 f &= ~a_TRUE_RV;
1602 goto jleave;
1605 static si32_t
1606 a_tty_wboundary(struct a_tty_line *tlp, si32_t dir){/* TODO shell token-wise */
1607 bool_t anynon;
1608 struct a_tty_cell *tcap;
1609 ui32_t cur, cnt;
1610 si32_t rv;
1611 NYD2_ENTER;
1613 assert(dir == 1 || dir == -1);
1615 rv = -1;
1616 cnt = tlp->tl_count;
1617 cur = tlp->tl_cursor;
1619 if(dir < 0){
1620 if(cur == 0)
1621 goto jleave;
1622 }else if(cur + 1 >= cnt)
1623 goto jleave;
1624 else
1625 --cnt, --cur; /* xxx Unsigned wrapping may occur (twice), then */
1627 for(rv = 0, tcap = tlp->tl_line.cells, anynon = FAL0;;){
1628 wchar_t wc;
1630 wc = tcap[cur += (ui32_t)dir].tc_wc;
1631 if(iswblank(wc) || iswpunct(wc)){
1632 if(anynon)
1633 break;
1634 }else
1635 anynon = TRU1;
1637 ++rv;
1639 if(dir < 0){
1640 if(cur == 0)
1641 break;
1642 }else if(cur + 1 >= cnt){
1643 ++rv;
1644 break;
1647 jleave:
1648 NYD2_LEAVE;
1649 return rv;
1652 static void
1653 a_tty_khome(struct a_tty_line *tlp, bool_t dobell){
1654 ui32_t f;
1655 NYD2_ENTER;
1657 if(n_LIKELY(tlp->tl_cursor > 0)){
1658 tlp->tl_cursor = 0;
1659 f = a_TTY_VF_MOD_CURSOR;
1660 }else if(dobell)
1661 f = a_TTY_VF_BELL;
1662 else
1663 f = a_TTY_VF_NONE;
1665 tlp->tl_vi_flags |= f;
1666 NYD2_LEAVE;
1669 static void
1670 a_tty_kend(struct a_tty_line *tlp){
1671 ui32_t f;
1672 NYD2_ENTER;
1674 if(n_LIKELY(tlp->tl_cursor < tlp->tl_count)){
1675 tlp->tl_cursor = tlp->tl_count;
1676 f = a_TTY_VF_MOD_CURSOR;
1677 }else
1678 f = a_TTY_VF_BELL;
1680 tlp->tl_vi_flags |= f;
1681 NYD2_LEAVE;
1684 static void
1685 a_tty_kbs(struct a_tty_line *tlp){
1686 ui32_t f, cur, cnt;
1687 NYD2_ENTER;
1689 cur = tlp->tl_cursor;
1690 cnt = tlp->tl_count;
1692 if(n_LIKELY(cur > 0)){
1693 tlp->tl_cursor = --cur;
1694 tlp->tl_count = --cnt;
1696 if((cnt -= cur) > 0){
1697 struct a_tty_cell *tcap;
1699 tcap = tlp->tl_line.cells + cur;
1700 memmove(tcap, &tcap[1], cnt *= sizeof(*tcap));
1702 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
1703 }else
1704 f = a_TTY_VF_BELL;
1706 tlp->tl_vi_flags |= f;
1707 NYD2_LEAVE;
1710 static void
1711 a_tty_ksnarf(struct a_tty_line *tlp, bool_t cplline, bool_t dobell){
1712 ui32_t i, f;
1713 NYD2_ENTER;
1715 f = a_TTY_VF_NONE;
1716 i = tlp->tl_cursor;
1718 if(cplline && i > 0){
1719 tlp->tl_cursor = i = 0;
1720 f = a_TTY_VF_MOD_CURSOR;
1723 if(n_LIKELY(i < tlp->tl_count)){
1724 struct a_tty_cell *tcap;
1726 tcap = &tlp->tl_line.cells[0];
1727 a_tty_copy2paste(tlp, &tcap[i], &tcap[tlp->tl_count]);
1728 tlp->tl_count = i;
1729 f = a_TTY_VF_MOD_CONTENT;
1730 }else if(dobell)
1731 f |= a_TTY_VF_BELL;
1733 tlp->tl_vi_flags |= f;
1734 NYD2_LEAVE;
1737 static si32_t
1738 a_tty_kdel(struct a_tty_line *tlp){
1739 ui32_t cur, cnt, f;
1740 si32_t i;
1741 NYD2_ENTER;
1743 cur = tlp->tl_cursor;
1744 cnt = tlp->tl_count;
1745 i = (si32_t)(cnt - cur);
1747 if(n_LIKELY(i > 0)){
1748 tlp->tl_count = --cnt;
1750 if(n_LIKELY(--i > 0)){
1751 struct a_tty_cell *tcap;
1753 tcap = &tlp->tl_line.cells[cur];
1754 memmove(tcap, &tcap[1], (ui32_t)i * sizeof(*tcap));
1756 f = a_TTY_VF_MOD_CONTENT;
1757 }else if(cnt == 0 && !ok_blook(ignoreeof)){
1758 putc('^', n_tty_fp);
1759 putc('D', n_tty_fp);
1760 i = -1;
1761 f = a_TTY_VF_NONE;
1762 }else{
1763 i = 0;
1764 f = a_TTY_VF_BELL;
1767 tlp->tl_vi_flags |= f;
1768 NYD2_LEAVE;
1769 return i;
1772 static void
1773 a_tty_kleft(struct a_tty_line *tlp){
1774 ui32_t f;
1775 NYD2_ENTER;
1777 if(n_LIKELY(tlp->tl_cursor > 0)){
1778 --tlp->tl_cursor;
1779 f = a_TTY_VF_MOD_CURSOR;
1780 }else
1781 f = a_TTY_VF_BELL;
1783 tlp->tl_vi_flags |= f;
1784 NYD2_LEAVE;
1787 static void
1788 a_tty_kright(struct a_tty_line *tlp){
1789 ui32_t i;
1790 NYD2_ENTER;
1792 if(n_LIKELY((i = tlp->tl_cursor + 1) <= tlp->tl_count)){
1793 tlp->tl_cursor = i;
1794 i = a_TTY_VF_MOD_CURSOR;
1795 }else
1796 i = a_TTY_VF_BELL;
1798 tlp->tl_vi_flags |= i;
1799 NYD2_LEAVE;
1802 static void
1803 a_tty_ksnarfw(struct a_tty_line *tlp, bool_t fwd){
1804 struct a_tty_cell *tcap;
1805 ui32_t cnt, cur, f;
1806 si32_t i;
1807 NYD2_ENTER;
1809 if(n_UNLIKELY((i = a_tty_wboundary(tlp, (fwd ? +1 : -1))) <= 0)){
1810 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
1811 goto jleave;
1814 cnt = tlp->tl_count - (ui32_t)i;
1815 cur = tlp->tl_cursor;
1816 if(!fwd)
1817 cur -= (ui32_t)i;
1818 tcap = &tlp->tl_line.cells[cur];
1820 a_tty_copy2paste(tlp, &tcap[0], &tcap[i]);
1822 if((tlp->tl_count = cnt) != (tlp->tl_cursor = cur)){
1823 cnt -= cur;
1824 memmove(&tcap[0], &tcap[i], cnt * sizeof(*tcap)); /* FIXME*/
1827 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
1828 jleave:
1829 tlp->tl_vi_flags |= f;
1830 NYD2_LEAVE;
1833 static void
1834 a_tty_kgow(struct a_tty_line *tlp, si32_t dir){
1835 ui32_t f;
1836 si32_t i;
1837 NYD2_ENTER;
1839 if(n_UNLIKELY((i = a_tty_wboundary(tlp, dir)) <= 0))
1840 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
1841 else{
1842 if(dir < 0)
1843 i = -i;
1844 tlp->tl_cursor += (ui32_t)i;
1845 f = a_TTY_VF_MOD_CURSOR;
1848 tlp->tl_vi_flags |= f;
1849 NYD2_LEAVE;
1852 static bool_t
1853 a_tty_kother(struct a_tty_line *tlp, wchar_t wc){
1854 /* Append if at EOL, insert otherwise;
1855 * since we may move around character-wise, always use a fresh ps */
1856 mbstate_t ps;
1857 struct a_tty_cell tc, *tcap;
1858 ui32_t f, cur, cnt;
1859 bool_t rv;
1860 NYD2_ENTER;
1862 rv = FAL0;
1863 f = a_TTY_VF_NONE;
1865 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1866 if(tlp->tl_count + 1 >= a_TTY_LINE_MAX){
1867 n_err(_("Stop here, we can't extend line beyond size limit\n"));
1868 goto jleave;
1871 /* First init a cell and see whether we'll really handle this wc */
1872 memset(&ps, 0, sizeof ps);
1873 /* C99 */{
1874 size_t l;
1876 l = wcrtomb(tc.tc_cbuf, tc.tc_wc = wc, &ps);
1877 if(n_UNLIKELY(l > MB_LEN_MAX)){
1878 jemb:
1879 n_err(_("wcrtomb(3) error: too many multibyte character bytes\n"));
1880 goto jleave;
1882 tc.tc_count = (ui16_t)l;
1884 if(n_UNLIKELY((n_psonce & n_PSO_ENC_MBSTATE) != 0)){
1885 l = wcrtomb(&tc.tc_cbuf[l], L'\0', &ps);
1886 if(n_LIKELY(l == 1))
1887 /* Only NUL terminator */;
1888 else if(n_LIKELY(--l < MB_LEN_MAX))
1889 tc.tc_count += (ui16_t)l;
1890 else
1891 goto jemb;
1895 /* Yes, we will! Place it in the array */
1896 tc.tc_novis = (iswprint(wc) == 0);
1897 tc.tc_width = a_tty_wcwidth(wc);
1898 /* TODO if(tc.tc_novis && tc.tc_width > 0) */
1900 cur = tlp->tl_cursor++;
1901 cnt = tlp->tl_count++ - cur;
1902 tcap = &tlp->tl_line.cells[cur];
1903 if(cnt >= 1){
1904 memmove(&tcap[1], tcap, cnt * sizeof(*tcap));
1905 f = a_TTY_VF_MOD_CONTENT;
1906 }else
1907 f = a_TTY_VF_MOD_SINGLE;
1908 memcpy(tcap, &tc, sizeof *tcap);
1910 f |= a_TTY_VF_MOD_CURSOR;
1911 rv = TRU1;
1912 jleave:
1913 if(!rv)
1914 f |= a_TTY_VF_BELL;
1915 tlp->tl_vi_flags |= f;
1916 NYD2_LEAVE;
1917 return rv;
1920 static ui32_t
1921 a_tty_kht(struct a_tty_line *tlp){
1922 ui8_t (*mempool)[n_MEMORY_POOL_TYPE_SIZEOF], *mempool_persist;
1923 struct stat sb;
1924 struct str orig, bot, topp, sub, exp, preexp;
1925 struct n_string shou, *shoup;
1926 struct a_tty_cell *cword, *ctop, *cx;
1927 bool_t wedid, set_savec;
1928 ui32_t rv, f;
1929 NYD2_ENTER;
1931 /* Get plain line data; if this is the first expansion/xy, update the
1932 * very original content so that ^G gets the origin back */
1933 orig = tlp->tl_savec;
1934 a_tty_cell2save(tlp);
1935 exp = tlp->tl_savec;
1936 if(orig.s != NULL){
1937 /*tlp->tl_savec = orig;*/
1938 set_savec = FAL0;
1939 }else
1940 set_savec = TRU1;
1941 orig = exp;
1943 mempool_persist = n_go_data->gdc_mempool;
1944 n_memory_pool_push(mempool = n_lofi_alloc(sizeof *mempool));
1946 shoup = n_string_creat_auto(&shou);
1947 f = a_TTY_VF_NONE;
1949 /* Find the word to be expanded */
1951 cword = tlp->tl_line.cells;
1952 ctop = cword + tlp->tl_cursor;
1953 cx = cword + tlp->tl_count;
1955 /* topp: separate data right of cursor */
1956 if(cx > ctop){
1957 for(rv = 0; ctop < cx; ++ctop)
1958 rv += ctop->tc_count;
1959 topp.l = rv;
1960 topp.s = orig.s + orig.l - rv;
1961 ctop = cword + tlp->tl_cursor;
1962 }else
1963 topp.s = NULL, topp.l = 0;
1965 /* Find the shell token that corresponds to the cursor position */
1966 /* C99 */{
1967 size_t max;
1969 max = 0;
1970 if(ctop > cword){
1971 for(; cword < ctop; ++cword)
1972 max += cword->tc_count;
1973 cword = tlp->tl_line.cells;
1975 bot = sub = orig;
1976 bot.l = 0;
1977 sub.l = max;
1979 if(max > 0){
1980 for(;;){
1981 enum n_shexp_state shs;
1983 exp = sub;
1984 shs = n_shexp_parse_token((n_SHEXP_PARSE_DRYRUN |
1985 n_SHEXP_PARSE_TRIMSPACE | n_SHEXP_PARSE_IGNORE_EMPTY |
1986 n_SHEXP_PARSE_QUOTE_AUTO_CLOSE), NULL, &sub, NULL);
1987 if(sub.l != 0){
1988 size_t x;
1990 assert(max >= sub.l);
1991 x = max - sub.l;
1992 bot.l += x;
1993 max -= x;
1994 continue;
1996 if(shs & n_SHEXP_STATE_ERR_MASK){
1997 n_err(_("Invalid completion pattern: %.*s\n"),
1998 (int)exp.l, exp.s);
1999 goto jnope;
2001 n_shexp_parse_token((n_SHEXP_PARSE_TRIMSPACE |
2002 n_SHEXP_PARSE_IGNORE_EMPTY | n_SHEXP_PARSE_QUOTE_AUTO_CLOSE),
2003 shoup, &exp, NULL);
2004 break;
2007 sub.s = n_string_cp(shoup);
2008 sub.l = shoup->s_len;
2012 /* Leave room for "implicit asterisk" expansion, as below */
2013 if(sub.l == 0){
2014 wedid = TRU1;
2015 sub.s = n_UNCONST(n_star);
2016 sub.l = 1;
2019 preexp.s = n_UNCONST(n_empty);
2020 preexp.l = 0;
2021 wedid = FAL0;
2022 jredo:
2023 /* TODO Super-Heavy-Metal: block all sigs, avoid leaks on jump */
2024 hold_all_sigs();
2025 exp.s = fexpand(sub.s, a_TTY_TAB_FEXP_FL);
2026 rele_all_sigs();
2028 if(exp.s == NULL || (exp.l = strlen(exp.s)) == 0){
2029 /* No. But maybe the users' desire was to complete only a part of the
2030 * shell token of interest! TODO This can be improved, we would need to
2031 * TODO have shexp_parse to create a DOM structure of parsed snippets, so
2032 * TODO that we can tell for each snippet which quote is active and
2033 * TODO whether we may cross its boundary and/or apply expansion for it */
2034 if(wedid == TRU1){
2035 size_t i, li;
2037 wedid = TRUM1;
2038 for(li = UIZ_MAX, i = sub.l; i-- > 0;){
2039 char c;
2041 if((c = sub.s[i]) == '/' || c == '+' /* *folder*! */)
2042 li = i;
2043 /* Do stop once some "magic" characters are seen XXX magic set */
2044 else if(c == '<' || c == '>' || c == '=' || c == ':')
2045 break;
2047 if(li != UIZ_MAX){
2048 preexp = sub;
2049 preexp.l = li;
2050 sub.l -= li;
2051 sub.s += li;
2052 goto jredo;
2055 goto jnope;
2058 if(wedid == TRUM1 && preexp.l > 0)
2059 preexp.s = savestrbuf(preexp.s, preexp.l);
2061 /* May be multi-return! */
2062 if(n_pstate & n_PS_EXPAND_MULTIRESULT)
2063 goto jmulti;
2065 /* xxx That is not really true since the limit counts characters not bytes */
2066 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
2067 if(exp.l >= a_TTY_LINE_MAX - 1 || a_TTY_LINE_MAX - 1 - exp.l < preexp.l){
2068 n_err(_("Tabulator expansion would extend beyond line size limit\n"));
2069 goto jnope;
2072 /* If the expansion equals the original string, assume the user wants what
2073 * is usually known as tab completion, append `*' and restart */
2074 if(!wedid && exp.l == sub.l && !memcmp(exp.s, sub.s, exp.l)){
2075 if(sub.s[sub.l - 1] == '*')
2076 goto jnope;
2078 wedid = TRU1;
2079 shoup = n_string_push_c(shoup, '*');
2080 sub.s = n_string_cp(shoup);
2081 sub.l = shoup->s_len;
2082 goto jredo;
2085 /* If it is a directory, and there is not yet a / appended, then we want the
2086 * user to confirm that he wants to dive in -- with only a HT */
2087 if(wedid && exp.l == --sub.l && !memcmp(exp.s, sub.s, exp.l) &&
2088 exp.s[exp.l - 1] != '/'){
2089 if(stat(exp.s, &sb) || !S_ISDIR(sb.st_mode))
2090 goto jnope;
2091 sub.s = salloc(exp.l + 1 +1);
2092 memcpy(sub.s, exp.s, exp.l);
2093 sub.s[exp.l++] = '/';
2094 sub.s[exp.l] = '\0';
2095 exp.s = sub.s;
2096 wedid = FAL0;
2097 goto jset;
2098 }else{
2099 if(wedid && (wedid = (exp.s[exp.l - 1] == '*')))
2100 --exp.l;
2101 exp.s[exp.l] = '\0';
2102 jset:
2103 exp.l = strlen(exp.s = n_shexp_quote_cp(exp.s, tlp->tl_quote_rndtrip));
2104 tlp->tl_defc_cursor_byte = bot.l + preexp.l + exp.l -1;
2105 if(wedid)
2106 goto jnope;
2109 orig.l = bot.l + preexp.l + exp.l + topp.l;
2110 orig.s = n_autorec_alloc_from_pool(mempool_persist, orig.l + 5 +1);
2111 if((rv = (ui32_t)bot.l) > 0)
2112 memcpy(orig.s, bot.s, rv);
2113 if(preexp.l > 0){
2114 memcpy(&orig.s[rv], preexp.s, preexp.l);
2115 rv += preexp.l;
2117 memcpy(&orig.s[rv], exp.s, exp.l);
2118 rv += exp.l;
2119 if(topp.l > 0){
2120 memcpy(&orig.s[rv], topp.s, topp.l);
2121 rv += topp.l;
2123 orig.s[rv] = '\0';
2125 tlp->tl_defc = orig;
2126 tlp->tl_count = tlp->tl_cursor = 0;
2127 f |= a_TTY_VF_MOD_DIRTY;
2128 jleave:
2129 n_memory_pool_pop(mempool);
2130 n_lofi_free(mempool);
2131 tlp->tl_vi_flags |= f;
2132 NYD2_LEAVE;
2133 return rv;
2135 jmulti:{
2136 struct n_visual_info_ctx vic;
2137 struct str input;
2138 wc_t c2, c1;
2139 bool_t isfirst;
2140 char const *lococp;
2141 size_t locolen, scrwid, lnlen, lncnt, prefixlen;
2142 FILE *fp;
2144 if((fp = Ftmp(NULL, "tabex", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
2145 n_perr(_("tmpfile"), 0);
2146 fp = n_tty_fp;
2149 /* How long is the result string for real? Search the NUL NUL
2150 * terminator. While here, detect the longest entry to perform an
2151 * initial allocation of our accumulator string */
2152 locolen = preexp.l;
2154 size_t i;
2156 i = strlen(&exp.s[++exp.l]);
2157 locolen = n_MAX(locolen, i);
2158 exp.l += i;
2159 }while(exp.s[exp.l + 1] != '\0');
2161 shoup = n_string_reserve(n_string_trunc(shoup, 0),
2162 locolen + (locolen >> 1));
2164 /* Iterate (once again) over all results */
2165 scrwid = n_SCRNWIDTH_FOR_LISTS;
2166 lnlen = lncnt = 0;
2167 n_UNINIT(prefixlen, 0);
2168 n_UNINIT(lococp, NULL);
2169 n_UNINIT(c1, '\0');
2170 for(isfirst = TRU1; exp.l > 0; isfirst = FAL0, c1 = c2){
2171 size_t i;
2172 char const *fullpath;
2174 /* Next result */
2175 sub = exp;
2176 sub.l = i = strlen(sub.s);
2177 assert(exp.l >= i);
2178 if((exp.l -= i) > 0)
2179 --exp.l;
2180 exp.s += ++i;
2182 /* Separate dirname and basename */
2183 fullpath = sub.s;
2184 if(isfirst){
2185 char const *cp;
2187 if((cp = strrchr(fullpath, '/')) != NULL)
2188 prefixlen = PTR2SIZE(++cp - fullpath);
2189 else
2190 prefixlen = 0;
2192 if(prefixlen > 0 && prefixlen < sub.l){
2193 sub.l -= prefixlen;
2194 sub.s += prefixlen;
2197 /* We want case-insensitive sort-order */
2198 memset(&vic, 0, sizeof vic);
2199 vic.vic_indat = sub.s;
2200 vic.vic_inlen = sub.l;
2201 c2 = n_visual_info(&vic, n_VISUAL_INFO_ONE_CHAR) ? vic.vic_waccu
2202 : (ui8_t)*sub.s;
2203 #ifdef HAVE_C90AMEND1
2204 c2 = towlower(c2);
2205 #else
2206 c2 = lowerconv(c2);
2207 #endif
2209 /* Query longest common prefix along the way */
2210 if(isfirst){
2211 c1 = c2;
2212 lococp = sub.s;
2213 locolen = sub.l;
2214 }else if(locolen > 0){
2215 for(i = 0; i < locolen; ++i)
2216 if(lococp[i] != sub.s[i]){
2217 i = field_detect_clip(i, lococp, i);
2218 locolen = i;
2219 break;
2223 /* Prepare display */
2224 input = sub;
2225 shoup = n_shexp_quote(n_string_trunc(shoup, 0), &input,
2226 tlp->tl_quote_rndtrip);
2227 memset(&vic, 0, sizeof vic);
2228 vic.vic_indat = shoup->s_dat;
2229 vic.vic_inlen = shoup->s_len;
2230 if(!n_visual_info(&vic,
2231 n_VISUAL_INFO_SKIP_ERRORS | n_VISUAL_INFO_WIDTH_QUERY))
2232 vic.vic_vi_width = shoup->s_len;
2234 /* Put on screen. Indent follow lines of same sort slot.
2235 * Leave enough room for filename tagging */
2236 if((c1 = (c1 != c2))){
2237 #ifdef HAVE_C90AMEND1
2238 c1 = (iswalnum(c2) != 0);
2239 #else
2240 c1 = (alnumchar(c2) != 0);
2241 #endif
2243 if(isfirst || c1 ||
2244 scrwid < lnlen || scrwid - lnlen <= vic.vic_vi_width + 2){
2245 putc('\n', fp);
2246 if(scrwid < lnlen)
2247 ++lncnt;
2248 ++lncnt, lnlen = 0;
2249 if(!isfirst && !c1)
2250 goto jsep;
2251 }else if(lnlen > 0){
2252 jsep:
2253 fputs(" ", fp);
2254 lnlen += 2;
2256 fputs(n_string_cp(shoup), fp);
2257 lnlen += vic.vic_vi_width;
2259 /* Support the known filename tagging
2260 * XXX *line-editor-completion-filetype* or so */
2261 if(!lstat(fullpath, &sb)){
2262 char c = '\0';
2264 if(S_ISDIR(sb.st_mode))
2265 c = '/';
2266 else if(S_ISLNK(sb.st_mode))
2267 c = '@';
2268 # ifdef S_ISFIFO
2269 else if(S_ISFIFO(sb.st_mode))
2270 c = '|';
2271 # endif
2272 # ifdef S_ISSOCK
2273 else if(S_ISSOCK(sb.st_mode))
2274 c = '=';
2275 # endif
2276 # ifdef S_ISCHR
2277 else if(S_ISCHR(sb.st_mode))
2278 c = '%';
2279 # endif
2280 # ifdef S_ISBLK
2281 else if(S_ISBLK(sb.st_mode))
2282 c = '#';
2283 # endif
2285 if(c != '\0'){
2286 putc(c, fp);
2287 ++lnlen;
2291 putc('\n', fp);
2292 ++lncnt;
2294 page_or_print(fp, lncnt);
2295 if(fp != n_tty_fp)
2296 Fclose(fp);
2298 n_string_gut(shoup);
2300 /* A common prefix of 0 means we cannot provide the user any auto
2301 * completed characters */
2302 if(locolen == 0)
2303 goto jnope;
2305 /* Otherwise we can, so extend the visual line content by the common
2306 * prefix (in a reversible way) */
2307 (exp.s = n_UNCONST(lococp))[locolen] = '\0';
2308 exp.s -= prefixlen;
2309 exp.l = (locolen += prefixlen);
2311 /* XXX Indicate that there is multiple choice */
2312 /* XXX f |= a_TTY_VF_BELL; -> *line-editor-completion-bell*? or so */
2313 wedid = FAL0;
2314 goto jset;
2317 jnope:
2318 /* If we've provided a default content, but failed to expand, there is
2319 * nothing we can "revert to": drop that default again */
2320 if(set_savec){
2321 tlp->tl_savec.s = NULL;
2322 tlp->tl_savec.l = 0;
2324 f = a_TTY_VF_NONE;
2325 rv = 0;
2326 goto jleave;
2329 # ifdef HAVE_HISTORY
2330 static ui32_t
2331 a_tty__khist_shared(struct a_tty_line *tlp, struct a_tty_hist *thp){
2332 ui32_t f, rv;
2333 NYD2_ENTER;
2335 if(n_LIKELY((tlp->tl_hist = thp) != NULL)){
2336 tlp->tl_defc.s = savestrbuf(thp->th_dat, thp->th_len);
2337 rv = tlp->tl_defc.l = thp->th_len;
2338 f = (tlp->tl_count > 0) ? a_TTY_VF_MOD_DIRTY : a_TTY_VF_NONE;
2339 tlp->tl_count = tlp->tl_cursor = 0;
2340 }else{
2341 f = a_TTY_VF_BELL;
2342 rv = UI32_MAX;
2345 tlp->tl_vi_flags |= f;
2346 NYD2_LEAVE;
2347 return rv;
2350 static ui32_t
2351 a_tty_khist(struct a_tty_line *tlp, bool_t fwd){
2352 struct a_tty_hist *thp;
2353 ui32_t rv;
2354 NYD2_ENTER;
2356 /* If we're not in history mode yet, save line content;
2357 * also, disallow forward search, then, and, of course, bail unless we
2358 * do have any history at all */
2359 if((thp = tlp->tl_hist) == NULL){
2360 if(fwd)
2361 goto jleave;
2362 if((thp = a_tty.tg_hist) == NULL)
2363 goto jleave;
2364 a_tty_cell2save(tlp);
2365 goto jleave;
2368 thp = fwd ? thp->th_younger : thp->th_older;
2369 jleave:
2370 rv = a_tty__khist_shared(tlp, thp);
2371 NYD2_LEAVE;
2372 return rv;
2375 static ui32_t
2376 a_tty_khist_search(struct a_tty_line *tlp, bool_t fwd){
2377 struct str orig_savec;
2378 struct a_tty_hist *thp;
2379 ui32_t rv;
2380 NYD2_ENTER;
2382 thp = NULL;
2384 /* We cannot complete an empty line */
2385 if(n_UNLIKELY(tlp->tl_count == 0)){
2386 /* XXX The upcoming hard reset would restore a set savec buffer,
2387 * XXX so forcefully reset that. A cleaner solution would be to
2388 * XXX reset it whenever a restore is no longer desired */
2389 tlp->tl_savec.s = NULL;
2390 tlp->tl_savec.l = 0;
2391 goto jleave;
2394 if((thp = tlp->tl_hist) == NULL){
2395 if((thp = a_tty.tg_hist) == NULL)
2396 goto jleave;
2397 /* We don't support wraparound, searching forward must always step */
2398 if(fwd)
2399 thp = thp->th_younger;
2400 orig_savec.s = NULL;
2401 orig_savec.l = 0; /* silence CC */
2402 }else if((thp = (fwd ? thp->th_younger : thp->th_older)) == NULL)
2403 goto jleave;
2404 else
2405 orig_savec = tlp->tl_savec;
2407 if(orig_savec.s == NULL)
2408 a_tty_cell2save(tlp);
2410 for(; thp != NULL; thp = (fwd ? thp->th_younger : thp->th_older))
2411 if(is_prefix(tlp->tl_savec.s, thp->th_dat))
2412 break;
2414 if(orig_savec.s != NULL)
2415 tlp->tl_savec = orig_savec;
2416 jleave:
2417 rv = a_tty__khist_shared(tlp, thp);
2418 NYD2_LEAVE;
2419 return rv;
2421 # endif /* HAVE_HISTORY */
2423 static enum a_tty_fun_status
2424 a_tty_fun(struct a_tty_line *tlp, enum a_tty_bind_flags tbf, size_t *len){
2425 enum a_tty_fun_status rv;
2426 NYD2_ENTER;
2428 rv = a_TTY_FUN_STATUS_OK;
2429 # undef a_X
2430 # define a_X(N) a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## N)
2431 switch(a_TTY_BIND_FUN_REDUCE(tbf)){
2432 case a_X(BELL):
2433 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2434 break;
2435 case a_X(GO_BWD):
2436 a_tty_kleft(tlp);
2437 break;
2438 case a_X(GO_FWD):
2439 a_tty_kright(tlp);
2440 break;
2441 case a_X(GO_WORD_BWD):
2442 a_tty_kgow(tlp, -1);
2443 break;
2444 case a_X(GO_WORD_FWD):
2445 a_tty_kgow(tlp, +1);
2446 break;
2447 case a_X(GO_HOME):
2448 a_tty_khome(tlp, TRU1);
2449 break;
2450 case a_X(GO_END):
2451 a_tty_kend(tlp);
2452 break;
2453 case a_X(DEL_BWD):
2454 a_tty_kbs(tlp);
2455 break;
2456 case a_X(DEL_FWD):
2457 if(a_tty_kdel(tlp) < 0)
2458 rv = a_TTY_FUN_STATUS_END;
2459 break;
2460 case a_X(SNARF_WORD_BWD):
2461 a_tty_ksnarfw(tlp, FAL0);
2462 break;
2463 case a_X(SNARF_WORD_FWD):
2464 a_tty_ksnarfw(tlp, TRU1);
2465 break;
2466 case a_X(SNARF_END):
2467 a_tty_ksnarf(tlp, FAL0, TRU1);
2468 break;
2469 case a_X(SNARF_LINE):
2470 a_tty_ksnarf(tlp, TRU1, (tlp->tl_count == 0));
2471 break;
2473 case a_X(HIST_FWD):
2474 # ifdef HAVE_HISTORY
2475 if(tlp->tl_hist != NULL){
2476 bool_t isfwd = TRU1;
2478 if(0){
2479 # endif
2480 /* FALLTHRU */
2481 case a_X(HIST_BWD):
2482 # ifdef HAVE_HISTORY
2483 isfwd = FAL0;
2485 if((*len = a_tty_khist(tlp, isfwd)) != UI32_MAX){
2486 rv = a_TTY_FUN_STATUS_RESTART;
2487 break;
2489 goto jreset;
2490 # endif
2492 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2493 break;
2495 case a_X(HIST_SRCH_FWD):{
2496 # ifdef HAVE_HISTORY
2497 bool_t isfwd = TRU1;
2499 if(0){
2500 # endif
2501 /* FALLTHRU */
2502 case a_X(HIST_SRCH_BWD):
2503 # ifdef HAVE_HISTORY
2504 isfwd = FAL0;
2506 if((*len = a_tty_khist_search(tlp, isfwd)) != UI32_MAX){
2507 rv = a_TTY_FUN_STATUS_RESTART;
2508 break;
2510 goto jreset;
2511 # else
2512 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2513 # endif
2514 } break;
2516 case a_X(REPAINT):
2517 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2518 break;
2519 case a_X(QUOTE_RNDTRIP):
2520 tlp->tl_quote_rndtrip = !tlp->tl_quote_rndtrip;
2521 break;
2522 case a_X(PROMPT_CHAR):{
2523 wchar_t wc;
2525 if((wc = a_tty_vinuni(tlp)) > 0)
2526 a_tty_kother(tlp, wc);
2527 } break;
2528 case a_X(COMPLETE):
2529 if((*len = a_tty_kht(tlp)) > 0)
2530 rv = a_TTY_FUN_STATUS_RESTART;
2531 break;
2533 case a_X(PASTE):
2534 if(tlp->tl_pastebuf.l > 0)
2535 *len = (tlp->tl_defc = tlp->tl_pastebuf).l;
2536 else
2537 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2538 break;
2541 case a_X(CANCEL):
2542 /* Normally this just causes a restart and thus resets the state
2543 * machine */
2544 if(tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2546 # ifdef HAVE_KEY_BINDINGS
2547 tlp->tl_bind_takeover = '\0';
2548 # endif
2549 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2550 rv = a_TTY_FUN_STATUS_RESTART;
2551 break;
2553 case a_X(RESET):
2554 if(tlp->tl_count == 0 && tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2555 # ifdef HAVE_KEY_BINDINGS
2556 tlp->tl_bind_takeover = '\0';
2557 # endif
2558 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY | a_TTY_VF_BELL;
2559 break;
2560 }else if(0){
2561 case a_X(FULLRESET):
2562 tlp->tl_savec.s = tlp->tl_defc.s = NULL;
2563 tlp->tl_savec.l = tlp->tl_defc.l = 0;
2564 tlp->tl_defc_cursor_byte = 0;
2565 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2567 jreset:
2568 # ifdef HAVE_KEY_BINDINGS
2569 tlp->tl_bind_takeover = '\0';
2570 # endif
2571 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2572 tlp->tl_cursor = tlp->tl_count = 0;
2573 # ifdef HAVE_HISTORY
2574 tlp->tl_hist = NULL;
2575 # endif
2576 if((*len = tlp->tl_savec.l) != 0){
2577 tlp->tl_defc = tlp->tl_savec;
2578 tlp->tl_savec.s = NULL;
2579 tlp->tl_savec.l = 0;
2580 }else
2581 *len = tlp->tl_defc.l;
2582 rv = a_TTY_FUN_STATUS_RESTART;
2583 break;
2585 default:
2586 case a_X(COMMIT):
2587 rv = a_TTY_FUN_STATUS_COMMIT;
2588 break;
2590 # undef a_X
2592 NYD2_LEAVE;
2593 return rv;
2596 static ssize_t
2597 a_tty_readline(struct a_tty_line *tlp, size_t len n_MEMORY_DEBUG_ARGS){
2598 /* We want to save code, yet we may have to incorporate a lines'
2599 * default content and / or default input to switch back to after some
2600 * history movement; let "len > 0" mean "have to display some data
2601 * buffer" -> a_BUFMODE, and only otherwise read(2) it */
2602 mbstate_t ps[2];
2603 char cbuf_base[MB_LEN_MAX * 2], *cbuf, *cbufp;
2604 ssize_t rv;
2605 struct a_tty_bind_tree *tbtp;
2606 wchar_t wc;
2607 enum a_tty_bind_flags tbf;
2608 enum {a_NONE, a_WAS_HERE = 1<<0, a_BUFMODE = 1<<1, a_MAYBEFUN = 1<<2,
2609 a_TIMEOUT = 1<<3, a_TIMEOUT_EXPIRED = 1<<4,
2610 a_TIMEOUT_MASK = a_TIMEOUT | a_TIMEOUT_EXPIRED,
2611 a_READ_LOOP_MASK = ~(a_WAS_HERE | a_MAYBEFUN | a_TIMEOUT_MASK)
2612 } flags;
2613 NYD_ENTER;
2615 n_UNINIT(rv, 0);
2616 # ifdef HAVE_KEY_BINDINGS
2617 assert(tlp->tl_bind_takeover == '\0');
2618 # endif
2619 jrestart:
2620 memset(ps, 0, sizeof ps);
2621 flags = a_NONE;
2622 tbf = 0;
2623 tlp->tl_vi_flags |= a_TTY_VF_REFRESH | a_TTY_VF_SYNC;
2625 jinput_loop:
2626 for(;;){
2627 if(len != 0)
2628 flags |= a_BUFMODE;
2630 /* Ensure we have valid pointers, and room for grow */
2631 a_tty_check_grow(tlp, ((flags & a_BUFMODE) ? (ui32_t)len : 1)
2632 n_MEMORY_DEBUG_ARGSCALL);
2634 /* Handle visual state flags, except in buffer mode */
2635 if(!(flags & a_BUFMODE) && (tlp->tl_vi_flags & a_TTY_VF_ALL_MASK))
2636 if(!a_tty_vi_refresh(tlp)){
2637 rv = -1;
2638 goto jleave;
2641 /* Ready for messing around.
2642 * Normal read(2)? Else buffer mode: speed this one up */
2643 if(!(flags & a_BUFMODE)){
2644 cbufp =
2645 cbuf = cbuf_base;
2646 }else{
2647 assert(tlp->tl_defc.l > 0 && tlp->tl_defc.s != NULL);
2648 assert(tlp->tl_defc.l >= len);
2649 cbufp =
2650 cbuf = tlp->tl_defc.s + (tlp->tl_defc.l - len);
2651 cbufp += len;
2654 /* Read in the next complete multibyte character */
2655 /* C99 */{
2656 # ifdef HAVE_KEY_BINDINGS
2657 struct a_tty_bind_tree *xtbtp;
2658 struct inseq{
2659 struct inseq *last;
2660 struct inseq *next;
2661 struct a_tty_bind_tree *tbtp;
2662 } *isp_head, *isp;
2664 isp_head = isp = NULL;
2665 # endif
2667 for(flags &= a_READ_LOOP_MASK;;){
2668 # ifdef HAVE_KEY_BINDINGS
2669 if(!(flags & a_BUFMODE) && tlp->tl_bind_takeover != '\0'){
2670 wc = tlp->tl_bind_takeover;
2671 tlp->tl_bind_takeover = '\0';
2672 }else
2673 # endif
2675 if(!(flags & a_BUFMODE)){
2676 /* Let me at least once dream of iomon(itor), timer with
2677 * one-shot, enwrapped with key_event and key_sequence_event,
2678 * all driven by an event_loop */
2679 /* TODO v15 Until we have SysV signal handling all through we
2680 * TODO need to temporarily adjust our BSD signal handler with
2681 * TODO a SysV one, here */
2682 n_sighdl_t otstp, ottin, ottou;
2684 otstp = n_signal(SIGTSTP, &n_tty_signal);
2685 ottin = n_signal(SIGTTIN, &n_tty_signal);
2686 ottou = n_signal(SIGTTOU, &n_tty_signal);
2687 # ifdef HAVE_KEY_BINDINGS
2688 flags &= ~a_TIMEOUT_MASK;
2689 if(isp != NULL && (tbtp = isp->tbtp)->tbt_isseq &&
2690 !tbtp->tbt_isseq_trail){
2691 a_tty_term_rawmode_timeout(tlp, TRU1);
2692 flags |= a_TIMEOUT;
2694 # endif
2696 while((rv = read(STDIN_FILENO, cbufp, 1)) < 1){
2697 if(rv == -1){
2698 if(n_err_no == n_ERR_INTR){
2699 if((tlp->tl_vi_flags & a_TTY_VF_MOD_DIRTY) &&
2700 !a_tty_vi_refresh(tlp))
2701 break;
2702 continue;
2704 break;
2707 # ifdef HAVE_KEY_BINDINGS
2708 /* Timeout expiration */
2709 if(rv == 0){
2710 assert(flags & a_TIMEOUT);
2711 assert(isp != NULL);
2712 a_tty_term_rawmode_timeout(tlp, FAL0);
2714 /* Something "atomic" broke. Maybe the current one can
2715 * also be terminated already, by itself? xxx really? */
2716 if((tbtp = isp->tbtp)->tbt_bind != NULL){
2717 tlp->tl_bind_takeover = wc;
2718 goto jhave_bind;
2721 /* Or, maybe there is a second path without a timeout;
2722 * this should be covered by .tbt_isseq_trail, but then
2723 * again a single-layer implementation cannot "know" */
2724 for(xtbtp = tbtp; (xtbtp = xtbtp->tbt_sibling) != NULL;)
2725 if(xtbtp->tbt_char == tbtp->tbt_char){
2726 assert(!xtbtp->tbt_isseq);
2727 break;
2729 /* Lay down on read(2)? */
2730 if(xtbtp != NULL)
2731 continue;
2732 goto jtake_over;
2734 # endif /* HAVE_KEY_BINDINGS */
2737 # ifdef HAVE_KEY_BINDINGS
2738 if(flags & a_TIMEOUT)
2739 a_tty_term_rawmode_timeout(tlp, FAL0);
2740 # endif
2741 safe_signal(SIGTSTP, otstp);
2742 safe_signal(SIGTTIN, ottin);
2743 safe_signal(SIGTTOU, ottou);
2744 if(rv < 0)
2745 goto jleave;
2747 ++cbufp;
2750 rv = (ssize_t)mbrtowc(&wc, cbuf, PTR2SIZE(cbufp - cbuf), &ps[0]);
2751 if(rv <= 0){
2752 /* Any error during buffer mode can only result in a hard
2753 * reset; Otherwise, if it's a hard error, or if too many
2754 * redundant shift sequences overflow our buffer: perform
2755 * hard reset */
2756 if((flags & a_BUFMODE) || rv == -1 ||
2757 sizeof cbuf_base == PTR2SIZE(cbufp - cbuf)){
2758 a_tty_fun(tlp, a_TTY_BIND_FUN_FULLRESET, &len);
2759 goto jrestart;
2761 /* Otherwise, due to the way we deal with the buffer, we need
2762 * to restore the mbstate_t from before this conversion */
2763 ps[0] = ps[1];
2764 continue;
2766 cbufp = cbuf;
2767 ps[1] = ps[0];
2770 /* Normal read(2)ing is subject to detection of key-bindings */
2771 # ifdef HAVE_KEY_BINDINGS
2772 if(!(flags & a_BUFMODE)){
2773 /* Check for special bypass functions before we try to embed
2774 * this character into the tree */
2775 if(n_uasciichar(wc)){
2776 char c;
2777 char const *cp;
2779 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_prompt_char)[0];
2780 *cp != '\0'; ++cp){
2781 if(c == *cp){
2782 wc = a_tty_vinuni(tlp);
2783 break;
2786 if(wc == '\0'){
2787 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2788 goto jinput_loop;
2791 if(n_uasciichar(wc))
2792 flags |= a_MAYBEFUN;
2793 else
2794 flags &= ~a_MAYBEFUN;
2796 /* Search for this character in the bind tree */
2797 tbtp = (isp != NULL) ? isp->tbtp->tbt_childs
2798 : (*tlp->tl_bind_tree_hmap)[wc % HSHSIZE];
2799 for(; tbtp != NULL; tbtp = tbtp->tbt_sibling){
2800 if(tbtp->tbt_char == wc){
2801 struct inseq *nisp;
2803 /* If this one cannot continue we're likely finished! */
2804 if(tbtp->tbt_childs == NULL){
2805 assert(tbtp->tbt_bind != NULL);
2806 tbf = tbtp->tbt_bind->tbc_flags;
2807 goto jmle_fun;
2810 /* This needs to read more characters */
2811 nisp = salloc(sizeof *nisp);
2812 if((nisp->last = isp) == NULL)
2813 isp_head = nisp;
2814 else
2815 isp->next = nisp;
2816 nisp->next = NULL;
2817 nisp->tbtp = tbtp;
2818 isp = nisp;
2819 flags &= ~a_WAS_HERE;
2820 break;
2823 if(tbtp != NULL)
2824 continue;
2826 /* Was there a binding active, but couldn't be continued? */
2827 if(isp != NULL){
2828 /* A binding had a timeout, it didn't expire, but we saw
2829 * something non-expected. Something "atomic" broke.
2830 * Maybe there is a second path without a timeout, that
2831 * continues like we've seen it. I.e., it may just have been
2832 * the user, typing too fast. We definitely want to allow
2833 * bindings like \e,d etc. to succeed: users are so used to
2834 * them that a timeout cannot be the mechanism to catch up!
2835 * A single-layer implementation cannot "know" */
2836 if((tbtp = isp->tbtp)->tbt_isseq && (isp->last == NULL ||
2837 !(xtbtp = isp->last->tbtp)->tbt_isseq ||
2838 xtbtp->tbt_isseq_trail)){
2839 for(xtbtp = (tbtp = isp->tbtp);
2840 (xtbtp = xtbtp->tbt_sibling) != NULL;)
2841 if(xtbtp->tbt_char == tbtp->tbt_char){
2842 assert(!xtbtp->tbt_isseq);
2843 break;
2845 if(xtbtp != NULL){
2846 isp->tbtp = xtbtp;
2847 tlp->tl_bind_takeover = wc;
2848 continue;
2852 /* Check for CANCEL shortcut now */
2853 if(flags & a_MAYBEFUN){
2854 char c;
2855 char const *cp;
2857 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_cancel)[0];
2858 *cp != '\0'; ++cp)
2859 if(c == *cp){
2860 tbf = a_TTY_BIND_FUN_INTERNAL |a_TTY_BIND_FUN_CANCEL;
2861 goto jmle_fun;
2865 /* So: maybe the current sequence can be terminated here? */
2866 if((tbtp = isp->tbtp)->tbt_bind != NULL){
2867 jhave_bind:
2868 tbf = tbtp->tbt_bind->tbc_flags;
2869 jmle_fun:
2870 if(tbf & a_TTY_BIND_FUN_INTERNAL){
2871 switch(a_tty_fun(tlp, tbf, &len)){
2872 case a_TTY_FUN_STATUS_OK:
2873 goto jinput_loop;
2874 case a_TTY_FUN_STATUS_COMMIT:
2875 goto jdone;
2876 case a_TTY_FUN_STATUS_RESTART:
2877 goto jrestart;
2878 case a_TTY_FUN_STATUS_END:
2879 goto jleave;
2881 assert(0);
2882 }else if(tbtp->tbt_bind->tbc_flags & a_TTY_BIND_NOCOMMIT){
2883 struct a_tty_bind_ctx *tbcp;
2885 tbcp = tbtp->tbt_bind;
2886 memcpy(tlp->tl_defc.s = salloc(
2887 (tlp->tl_defc.l = len = tbcp->tbc_exp_len) +1),
2888 tbcp->tbc_exp, tbcp->tbc_exp_len +1);
2889 goto jrestart;
2890 }else{
2891 cbufp = tbtp->tbt_bind->tbc_exp;
2892 goto jinject_input;
2897 /* Otherwise take over all chars "as is" */
2898 jtake_over:
2899 for(; isp_head != NULL; isp_head = isp_head->next)
2900 if(a_tty_kother(tlp, isp_head->tbtp->tbt_char)){
2901 /* FIXME */
2903 /* And the current one too */
2904 goto jkother;
2906 # endif /* HAVE_KEY_BINDINGS */
2908 if((flags & a_BUFMODE) && (len -= (size_t)rv) == 0){
2909 /* Buffer mode completed */
2910 tlp->tl_defc.s = NULL;
2911 tlp->tl_defc.l = 0;
2912 flags &= ~a_BUFMODE;
2914 break;
2917 # ifndef HAVE_KEY_BINDINGS
2918 /* Don't interpret control bytes during buffer mode.
2919 * Otherwise, if it's a control byte check whether it is a MLE
2920 * function. Remarks: initially a complete duplicate to be able to
2921 * switch(), later converted to simply iterate over (an #ifdef'd
2922 * subset of) the MLE base_tuple table in order to have "a SPOF" */
2923 if(cbuf == cbuf_base && n_uasciichar(wc) && cntrlchar((char)wc)){
2924 struct a_tty_bind_builtin_tuple const *tbbtp, *tbbtp_max;
2925 char c;
2927 c = (char)wc ^ 0x40;
2928 tbbtp = a_tty_bind_base_tuples;
2929 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_base_tuples)];
2930 jbuiltin_redo:
2931 for(; tbbtp < tbbtp_max; ++tbbtp){
2932 /* Assert default_tuple table is properly subset'ed */
2933 assert(tbbtp->tbdt_iskey);
2934 if(tbbtp->tbbt_ckey == c){
2935 if(tbbtp->tbbt_exp[0] == '\0'){
2936 enum a_tty_bind_flags tbf;
2938 tbf = a_TTY_BIND_FUN_EXPAND((ui8_t)tbbtp->tbbt_exp[1]);
2939 switch(a_tty_fun(tlp, tbf, &len)){
2940 case a_TTY_FUN_STATUS_OK:
2941 goto jinput_loop;
2942 case a_TTY_FUN_STATUS_COMMIT:
2943 goto jdone;
2944 case a_TTY_FUN_STATUS_RESTART:
2945 goto jrestart;
2946 case a_TTY_FUN_STATUS_END:
2947 goto jleave;
2949 assert(0);
2950 }else{
2951 cbufp = tbbtp->tbbt_exp;
2952 goto jinject_input;
2956 if(tbbtp ==
2957 &a_tty_bind_base_tuples[n_NELEM(a_tty_bind_base_tuples)]){
2958 tbbtp = a_tty_bind_default_tuples;
2959 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_default_tuples)];
2960 goto jbuiltin_redo;
2963 # endif /* !HAVE_KEY_BINDINGS */
2965 # ifdef HAVE_KEY_BINDINGS
2966 jkother:
2967 # endif
2968 if(a_tty_kother(tlp, wc)){
2969 /* Don't clear the history during buffer mode.. */
2970 # ifdef HAVE_HISTORY
2971 if(!(flags & a_BUFMODE) && cbuf == cbuf_base)
2972 tlp->tl_hist = NULL;
2973 # endif
2978 /* We have a completed input line, convert the struct cell data to its
2979 * plain character equivalent */
2980 jdone:
2981 rv = a_tty_cell2dat(tlp);
2982 jleave:
2983 putc('\n', n_tty_fp);
2984 fflush(n_tty_fp);
2985 NYD_LEAVE;
2986 return rv;
2988 jinject_input:{
2989 size_t i;
2991 hold_all_sigs(); /* XXX v15 drop */
2992 i = a_tty_cell2dat(tlp);
2993 n_go_input_inject(n_GO_INPUT_INJECT_NONE, tlp->tl_line.cbuf, i);
2994 i = strlen(cbufp) +1;
2995 if(i >= *tlp->tl_x_bufsize){
2996 *tlp->tl_x_buf = (n_realloc)(*tlp->tl_x_buf, i n_MEMORY_DEBUG_ARGSCALL);
2997 *tlp->tl_x_bufsize = i;
2999 memcpy(*tlp->tl_x_buf, cbufp, i);
3000 rele_all_sigs(); /* XXX v15 drop */
3001 rv = (ssize_t)i -1;
3003 goto jleave;
3006 # ifdef HAVE_KEY_BINDINGS
3007 static enum n_go_input_flags
3008 a_tty_bind_ctx_find(char const *name){
3009 enum n_go_input_flags rv;
3010 struct a_tty_bind_ctx_map const *tbcmp;
3011 NYD2_ENTER;
3013 tbcmp = a_tty_bind_ctx_maps;
3014 do if(!asccasecmp(tbcmp->tbcm_name, name)){
3015 rv = tbcmp->tbcm_ctx;
3016 goto jleave;
3017 }while(PTRCMP(++tbcmp, <,
3018 &a_tty_bind_ctx_maps[n_NELEM(a_tty_bind_ctx_maps)]));
3020 rv = (enum n_go_input_flags)-1;
3021 jleave:
3022 NYD2_LEAVE;
3023 return rv;
3026 static bool_t
3027 a_tty_bind_create(struct a_tty_bind_parse_ctx *tbpcp, bool_t replace){
3028 struct a_tty_bind_ctx *tbcp;
3029 bool_t rv;
3030 NYD2_ENTER;
3032 rv = FAL0;
3034 if(!a_tty_bind_parse(TRU1, tbpcp))
3035 goto jleave;
3037 /* Since we use a single buffer for it all, need to replace as such */
3038 if(tbpcp->tbpc_tbcp != NULL){
3039 if(!replace)
3040 goto jleave;
3041 a_tty_bind_del(tbpcp);
3042 }else if(a_tty.tg_bind_cnt == UI32_MAX){
3043 n_err(_("`bind': maximum number of bindings already established\n"));
3044 goto jleave;
3047 /* C99 */{
3048 size_t i, j;
3050 tbcp = smalloc(n_VSTRUCT_SIZEOF(struct a_tty_bind_ctx, tbc__buf) +
3051 tbpcp->tbpc_seq_len + tbpcp->tbpc_exp.l +
3052 n_MAX(sizeof(si32_t), sizeof(wc_t)) + tbpcp->tbpc_cnv_len +3);
3053 if(tbpcp->tbpc_ltbcp != NULL){
3054 tbcp->tbc_next = tbpcp->tbpc_ltbcp->tbc_next;
3055 tbpcp->tbpc_ltbcp->tbc_next = tbcp;
3056 }else{
3057 enum n_go_input_flags gif;
3059 gif = tbpcp->tbpc_flags & n__GO_INPUT_CTX_MASK;
3060 tbcp->tbc_next = a_tty.tg_bind[gif];
3061 a_tty.tg_bind[gif] = tbcp;
3063 memcpy(tbcp->tbc_seq = &tbcp->tbc__buf[0],
3064 tbpcp->tbpc_seq, i = (tbcp->tbc_seq_len = tbpcp->tbpc_seq_len) +1);
3065 memcpy(tbcp->tbc_exp = &tbcp->tbc__buf[i],
3066 tbpcp->tbpc_exp.s, j = (tbcp->tbc_exp_len = tbpcp->tbpc_exp.l) +1);
3067 i += j;
3068 i = (i + tbpcp->tbpc_cnv_align_mask) & ~tbpcp->tbpc_cnv_align_mask;
3069 memcpy(tbcp->tbc_cnv = &tbcp->tbc__buf[i],
3070 tbpcp->tbpc_cnv, (tbcp->tbc_cnv_len = tbpcp->tbpc_cnv_len) +1);
3071 tbcp->tbc_flags = tbpcp->tbpc_flags;
3074 /* Directly resolve any termcap(5) symbol if we are already setup */
3075 if((n_psonce & n_PSO_STARTED) &&
3076 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
3077 a_TTY_BIND_RESOLVE)
3078 a_tty_bind_resolve(tbcp);
3080 ++a_tty.tg_bind_cnt;
3081 /* If this binding is usable invalidate the key input lookup trees */
3082 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3083 a_tty.tg_bind_isdirty = TRU1;
3084 rv = TRU1;
3085 jleave:
3086 NYD2_LEAVE;
3087 return rv;
3090 static bool_t
3091 a_tty_bind_parse(bool_t isbindcmd, struct a_tty_bind_parse_ctx *tbpcp){
3092 enum{a_TRUE_RV = a_TTY__BIND_LAST<<1};
3094 struct n_visual_info_ctx vic;
3095 struct str shin_save, shin;
3096 struct n_string shou, *shoup;
3097 size_t i;
3098 struct kse{
3099 struct kse *next;
3100 char *seq_dat;
3101 wc_t *cnv_dat;
3102 ui32_t seq_len;
3103 ui32_t cnv_len; /* High bit set if a termap to be resolved */
3104 ui32_t calc_cnv_len; /* Ditto, but aligned etc. */
3105 ui8_t kse__dummy[4];
3106 } *head, *tail;
3107 ui32_t f;
3108 NYD2_ENTER;
3109 n_LCTA(UICMP(64, a_TRUE_RV, <, UI32_MAX),
3110 "Flag bits excess storage datatype");
3112 f = n_GO_INPUT_NONE;
3113 shoup = n_string_creat_auto(&shou);
3114 head = tail = NULL;
3116 /* Parse the key-sequence */
3117 for(shin.s = n_UNCONST(tbpcp->tbpc_in_seq), shin.l = UIZ_MAX;;){
3118 struct kse *ep;
3119 enum n_shexp_state shs;
3121 shin_save = shin;
3122 shs = n_shexp_parse_token((n_SHEXP_PARSE_TRUNC | n_SHEXP_PARSE_TRIMSPACE |
3123 n_SHEXP_PARSE_IGNORE_EMPTY | n_SHEXP_PARSE_IFS_IS_COMMA),
3124 shoup, &shin, NULL);
3125 if(shs & n_SHEXP_STATE_ERR_UNICODE){
3126 f |= a_TTY_BIND_DEFUNCT;
3127 if(isbindcmd && (n_poption & n_PO_D_V))
3128 n_err(_("`%s': \\uNICODE not available in locale: %s\n"),
3129 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3131 if((shs & n_SHEXP_STATE_ERR_MASK) & ~n_SHEXP_STATE_ERR_UNICODE){
3132 n_err(_("`%s': failed to parse key-sequence: %s\n"),
3133 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3134 goto jleave;
3136 if((shs & (n_SHEXP_STATE_OUTPUT | n_SHEXP_STATE_STOP)) ==
3137 n_SHEXP_STATE_STOP)
3138 break;
3140 ep = salloc(sizeof *ep);
3141 if(head == NULL)
3142 head = ep;
3143 else
3144 tail->next = ep;
3145 tail = ep;
3146 ep->next = NULL;
3147 if(!(shs & n_SHEXP_STATE_ERR_UNICODE)){
3148 i = strlen(ep->seq_dat = n_shexp_quote_cp(n_string_cp(shoup), TRU1));
3149 if(i >= SI32_MAX - 1)
3150 goto jelen;
3151 ep->seq_len = (ui32_t)i;
3152 }else{
3153 /* Otherwise use the original buffer, _we_ can only quote it the wrong
3154 * way (e.g., an initial $'\u3a' becomes '\u3a'), _then_ */
3155 if((i = shin_save.l - shin.l) >= SI32_MAX - 1)
3156 goto jelen;
3157 ep->seq_len = (ui32_t)i;
3158 ep->seq_dat = savestrbuf(shin_save.s, i);
3161 memset(&vic, 0, sizeof vic);
3162 vic.vic_inlen = shoup->s_len;
3163 vic.vic_indat = shoup->s_dat;
3164 if(!n_visual_info(&vic,
3165 n_VISUAL_INFO_WOUT_CREATE | n_VISUAL_INFO_WOUT_SALLOC)){
3166 n_err(_("`%s': key-sequence seems to contain invalid "
3167 "characters: %s: %s\n"),
3168 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
3169 f |= a_TTY_BIND_DEFUNCT;
3170 goto jleave;
3171 }else if(vic.vic_woulen == 0 ||
3172 vic.vic_woulen >= (SI32_MAX - 2) / sizeof(wc_t)){
3173 jelen:
3174 n_err(_("`%s': length of key-sequence unsupported: %s: %s\n"),
3175 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
3176 f |= a_TTY_BIND_DEFUNCT;
3177 goto jleave;
3179 ep->cnv_dat = vic.vic_woudat;
3180 ep->cnv_len = (ui32_t)vic.vic_woulen;
3182 /* A termcap(5)/terminfo(5) identifier? */
3183 if(ep->cnv_len > 1 && ep->cnv_dat[0] == ':'){
3184 i = --ep->cnv_len, ++ep->cnv_dat;
3185 # ifndef HAVE_TERMCAP
3186 if(n_poption & n_PO_D_V)
3187 n_err(_("`%s': no termcap(5)/terminfo(5) support: %s: %s\n"),
3188 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3189 f |= a_TTY_BIND_DEFUNCT;
3190 # endif
3191 if(i > a_TTY_BIND_CAPNAME_MAX){
3192 n_err(_("`%s': termcap(5)/terminfo(5) name too long: %s: %s\n"),
3193 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3194 f |= a_TTY_BIND_DEFUNCT;
3196 while(i > 0)
3197 /* (We store it as char[]) */
3198 if((ui32_t)ep->cnv_dat[--i] & ~0x7Fu){
3199 n_err(_("`%s': invalid termcap(5)/terminfo(5) name content: "
3200 "%s: %s\n"),
3201 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3202 f |= a_TTY_BIND_DEFUNCT;
3203 break;
3205 ep->cnv_len |= SI32_MIN; /* Needs resolve */
3206 f |= a_TTY_BIND_RESOLVE;
3209 if(shs & n_SHEXP_STATE_STOP)
3210 break;
3213 if(head == NULL){
3214 jeempty:
3215 n_err(_("`%s': effectively empty key-sequence: %s\n"),
3216 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3217 goto jleave;
3220 if(isbindcmd) /* (Or always, just "1st time init") */
3221 tbpcp->tbpc_cnv_align_mask = n_MAX(sizeof(si32_t), sizeof(wc_t)) - 1;
3223 /* C99 */{
3224 struct a_tty_bind_ctx *ltbcp, *tbcp;
3225 char *cpbase, *cp, *cnv;
3226 size_t sl, cl;
3228 /* Unite the parsed sequence(s) into single string representations */
3229 for(sl = cl = 0, tail = head; tail != NULL; tail = tail->next){
3230 sl += tail->seq_len + 1;
3232 if(!isbindcmd)
3233 continue;
3235 /* Preserve room for terminal capabilities to be resolved.
3236 * Above we have ensured the buffer will fit in these calculations */
3237 if((i = tail->cnv_len) & SI32_MIN){
3238 /* For now
3239 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[]+NUL;}
3240 * later
3241 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3242 n_LCTAV(n_ISPOW2(a_TTY_BIND_CAPEXP_ROUNDUP));
3243 n_LCTA(a_TTY_BIND_CAPEXP_ROUNDUP >= sizeof(wc_t),
3244 "Aligning on this constant doesn't properly align wc_t");
3245 i &= SI32_MAX;
3246 i *= sizeof(wc_t);
3247 i += sizeof(si32_t);
3248 if(i < a_TTY_BIND_CAPEXP_ROUNDUP)
3249 i = (i + (a_TTY_BIND_CAPEXP_ROUNDUP - 1)) &
3250 ~(a_TTY_BIND_CAPEXP_ROUNDUP - 1);
3251 }else
3252 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3253 i *= sizeof(wc_t);
3254 i += sizeof(si32_t) + sizeof(wc_t); /* (buf_len_iscap, NUL) */
3255 cl += i;
3256 if(tail->cnv_len & SI32_MIN){
3257 tail->cnv_len &= SI32_MAX;
3258 i |= SI32_MIN;
3260 tail->calc_cnv_len = (ui32_t)i;
3262 --sl;
3264 tbpcp->tbpc_seq_len = sl;
3265 tbpcp->tbpc_cnv_len = cl;
3266 /* C99 */{
3267 size_t j;
3269 j = i = sl + 1; /* Room for comma separator */
3270 if(isbindcmd){
3271 i = (i + tbpcp->tbpc_cnv_align_mask) & ~tbpcp->tbpc_cnv_align_mask;
3272 j = i;
3273 i += cl;
3275 tbpcp->tbpc_seq = cp = cpbase = salloc(i);
3276 tbpcp->tbpc_cnv = cnv = &cpbase[j];
3279 for(tail = head; tail != NULL; tail = tail->next){
3280 memcpy(cp, tail->seq_dat, tail->seq_len);
3281 cp += tail->seq_len;
3282 *cp++ = ',';
3284 if(isbindcmd){
3285 char * const save_cnv = cnv;
3287 n_UNALIGN(si32_t*,cnv)[0] = (si32_t)(i = tail->calc_cnv_len);
3288 cnv += sizeof(si32_t);
3289 if(i & SI32_MIN){
3290 /* For now
3291 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];}
3292 * later
3293 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[];} */
3294 n_UNALIGN(si32_t*,cnv)[0] = tail->cnv_len;
3295 cnv += sizeof(si32_t);
3297 i = tail->cnv_len * sizeof(wc_t);
3298 memcpy(cnv, tail->cnv_dat, i);
3299 cnv += i;
3300 *n_UNALIGN(wc_t*,cnv) = '\0';
3302 cnv = save_cnv + (tail->calc_cnv_len & SI32_MAX);
3305 *--cp = '\0';
3307 /* Search for a yet existing identical mapping */
3308 for(ltbcp = NULL, tbcp = a_tty.tg_bind[tbpcp->tbpc_flags]; tbcp != NULL;
3309 ltbcp = tbcp, tbcp = tbcp->tbc_next)
3310 if(tbcp->tbc_seq_len == sl && !memcmp(tbcp->tbc_seq, cpbase, sl)){
3311 tbpcp->tbpc_tbcp = tbcp;
3312 break;
3314 tbpcp->tbpc_ltbcp = ltbcp;
3315 tbpcp->tbpc_flags |= (f & a_TTY__BIND_MASK);
3318 /* Create single string expansion if so desired */
3319 if(isbindcmd){
3320 char *exp;
3322 exp = tbpcp->tbpc_exp.s;
3324 i = tbpcp->tbpc_exp.l;
3325 if(i > 0 && exp[i - 1] == '@'){
3326 while(--i > 0){
3327 if(!blankspacechar(exp[i - 1]))
3328 break;
3330 if(i == 0)
3331 goto jeempty;
3333 exp[tbpcp->tbpc_exp.l = i] = '\0';
3334 tbpcp->tbpc_flags |= a_TTY_BIND_NOCOMMIT;
3337 /* Reverse solidus cannot be placed last in expansion to avoid (at the
3338 * time of this writing) possible problems with newline escaping.
3339 * Don't care about (un)even number thereof */
3340 if(i > 0 && exp[i - 1] == '\\'){
3341 n_err(_("`%s': reverse solidus cannot be last in expansion: %s\n"),
3342 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3343 goto jleave;
3346 /* It may map to an internal MLE command! */
3347 for(i = 0; i < n_NELEM(a_tty_bind_fun_names); ++i)
3348 if(!asccasecmp(exp, a_tty_bind_fun_names[i])){
3349 tbpcp->tbpc_flags |= a_TTY_BIND_FUN_EXPAND(i) |
3350 a_TTY_BIND_FUN_INTERNAL |
3351 (head->next == NULL ? a_TTY_BIND_MLE1CNTRL : 0);
3352 if((n_poption & n_PO_D_V) &&
3353 (tbpcp->tbpc_flags & a_TTY_BIND_NOCOMMIT))
3354 n_err(_("`%s': MLE commands can't be made editable via @: %s\n"),
3355 tbpcp->tbpc_cmd, exp);
3356 tbpcp->tbpc_flags &= ~a_TTY_BIND_NOCOMMIT;
3357 break;
3361 f |= a_TRUE_RV; /* TODO because we only now true and false; DEFUNCT.. */
3362 jleave:
3363 n_string_gut(shoup);
3364 NYD2_LEAVE;
3365 return (f & a_TRUE_RV) != 0;
3368 static void
3369 a_tty_bind_resolve(struct a_tty_bind_ctx *tbcp){
3370 char capname[a_TTY_BIND_CAPNAME_MAX +1];
3371 struct n_termcap_value tv;
3372 size_t len;
3373 bool_t isfirst; /* TODO For now: first char must be control! */
3374 char *cp, *next;
3375 NYD2_ENTER;
3377 n_UNINIT(next, NULL);
3378 for(cp = tbcp->tbc_cnv, isfirst = TRU1, len = tbcp->tbc_cnv_len;
3379 len > 0; isfirst = FAL0, cp = next){
3380 /* C99 */{
3381 si32_t i, j;
3383 i = n_UNALIGN(si32_t*,cp)[0];
3384 j = i & SI32_MAX;
3385 next = &cp[j];
3386 len -= j;
3387 if(i == j)
3388 continue;
3390 /* struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];} */
3391 cp += sizeof(si32_t);
3392 i = n_UNALIGN(si32_t*,cp)[0];
3393 cp += sizeof(si32_t);
3394 for(j = 0; j < i; ++j)
3395 capname[j] = n_UNALIGN(wc_t*,cp)[j];
3396 capname[j] = '\0';
3399 /* Use generic lookup mechanism if not a known query */
3400 /* C99 */{
3401 si32_t tq;
3403 tq = n_termcap_query_for_name(capname, n_TERMCAP_CAPTYPE_STRING);
3404 if(tq == -1){
3405 tv.tv_data.tvd_string = capname;
3406 tq = n__TERMCAP_QUERY_MAX1;
3409 if(tq < 0 || !n_termcap_query(tq, &tv)){
3410 if(n_poption & n_PO_D_V)
3411 n_err(_("`bind': unknown or unsupported capability: %s: %s\n"),
3412 capname, tbcp->tbc_seq);
3413 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3414 break;
3418 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3419 /* C99 */{
3420 size_t i;
3422 i = strlen(tv.tv_data.tvd_string);
3423 if(/*i > SI32_MAX ||*/ i >= PTR2SIZE(next - cp)){
3424 if(n_poption & n_PO_D_V)
3425 n_err(_("`bind': capability expansion too long: %s: %s\n"),
3426 capname, tbcp->tbc_seq);
3427 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3428 break;
3429 }else if(i == 0){
3430 if(n_poption & n_PO_D_V)
3431 n_err(_("`bind': empty capability expansion: %s: %s\n"),
3432 capname, tbcp->tbc_seq);
3433 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3434 break;
3435 }else if(isfirst && !cntrlchar(*tv.tv_data.tvd_string)){
3436 if(n_poption & n_PO_D_V)
3437 n_err(_("`bind': capability expansion doesn't start with "
3438 "control: %s: %s\n"), capname, tbcp->tbc_seq);
3439 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3440 break;
3442 n_UNALIGN(si32_t*,cp)[-1] = (si32_t)i;
3443 memcpy(cp, tv.tv_data.tvd_string, i);
3444 cp[i] = '\0';
3447 NYD2_LEAVE;
3450 static void
3451 a_tty_bind_del(struct a_tty_bind_parse_ctx *tbpcp){
3452 struct a_tty_bind_ctx *ltbcp, *tbcp;
3453 NYD2_ENTER;
3455 tbcp = tbpcp->tbpc_tbcp;
3457 if((ltbcp = tbpcp->tbpc_ltbcp) != NULL)
3458 ltbcp->tbc_next = tbcp->tbc_next;
3459 else
3460 a_tty.tg_bind[tbpcp->tbpc_flags] = tbcp->tbc_next;
3461 free(tbcp);
3463 --a_tty.tg_bind_cnt;
3464 a_tty.tg_bind_isdirty = TRU1;
3465 NYD2_LEAVE;
3468 static void
3469 a_tty_bind_tree_build(void){
3470 size_t i;
3471 NYD2_ENTER;
3473 for(i = 0; i < n__GO_INPUT_CTX_MAX1; ++i){
3474 struct a_tty_bind_ctx *tbcp;
3475 n_LCTAV(n_GO_INPUT_CTX_BASE == 0);
3477 /* Somewhat wasteful, but easier to handle: simply clone the entire
3478 * primary key onto the secondary one, then only modify it */
3479 for(tbcp = a_tty.tg_bind[n_GO_INPUT_CTX_BASE]; tbcp != NULL;
3480 tbcp = tbcp->tbc_next)
3481 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3482 a_tty__bind_tree_add(n_GO_INPUT_CTX_BASE, &a_tty.tg_bind_tree[i][0],
3483 tbcp);
3485 if(i != n_GO_INPUT_CTX_BASE)
3486 for(tbcp = a_tty.tg_bind[i]; tbcp != NULL; tbcp = tbcp->tbc_next)
3487 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3488 a_tty__bind_tree_add(i, &a_tty.tg_bind_tree[i][0], tbcp);
3491 a_tty.tg_bind_isbuild = TRU1;
3492 NYD2_LEAVE;
3495 static void
3496 a_tty_bind_tree_teardown(void){
3497 size_t i, j;
3498 NYD2_ENTER;
3500 memset(&a_tty.tg_bind_shcut_cancel[0], 0,
3501 sizeof(a_tty.tg_bind_shcut_cancel));
3502 memset(&a_tty.tg_bind_shcut_prompt_char[0], 0,
3503 sizeof(a_tty.tg_bind_shcut_prompt_char));
3505 for(i = 0; i < n__GO_INPUT_CTX_MAX1; ++i)
3506 for(j = 0; j < HSHSIZE; ++j)
3507 a_tty__bind_tree_free(a_tty.tg_bind_tree[i][j]);
3508 memset(&a_tty.tg_bind_tree[0], 0, sizeof(a_tty.tg_bind_tree));
3510 a_tty.tg_bind_isdirty = a_tty.tg_bind_isbuild = FAL0;
3511 NYD2_LEAVE;
3514 static void
3515 a_tty__bind_tree_add(ui32_t hmap_idx, struct a_tty_bind_tree *store[HSHSIZE],
3516 struct a_tty_bind_ctx *tbcp){
3517 ui32_t cnvlen;
3518 char const *cnvdat;
3519 struct a_tty_bind_tree *ntbtp;
3520 NYD2_ENTER;
3521 n_UNUSED(hmap_idx);
3523 ntbtp = NULL;
3525 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len; cnvlen > 0;){
3526 union {wchar_t const *wp; char const *cp;} u;
3527 si32_t entlen;
3529 /* {si32_t buf_len_iscap;} */
3530 entlen = *n_UNALIGN(si32_t const*,cnvdat);
3532 if(entlen & SI32_MIN){
3533 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;}
3534 * Note that empty capabilities result in DEFUNCT */
3535 for(u.cp = (char const*)&n_UNALIGN(si32_t const*,cnvdat)[2];
3536 *u.cp != '\0'; ++u.cp)
3537 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.cp, TRU1);
3538 assert(ntbtp != NULL);
3539 ntbtp->tbt_isseq_trail = TRU1;
3540 entlen &= SI32_MAX;
3541 }else{
3542 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3543 bool_t isseq;
3545 u.wp = (wchar_t const*)&n_UNALIGN(si32_t const*,cnvdat)[1];
3547 /* May be a special shortcut function? */
3548 if(ntbtp == NULL && (tbcp->tbc_flags & a_TTY_BIND_MLE1CNTRL)){
3549 char *cp;
3550 ui32_t ctx, fun;
3552 ctx = tbcp->tbc_flags & n__GO_INPUT_CTX_MASK;
3553 fun = tbcp->tbc_flags & a_TTY__BIND_FUN_MASK;
3555 if(fun == a_TTY_BIND_FUN_CANCEL){
3556 for(cp = &a_tty.tg_bind_shcut_cancel[ctx][0];
3557 PTRCMP(cp, <, &a_tty.tg_bind_shcut_cancel[ctx]
3558 [n_NELEM(a_tty.tg_bind_shcut_cancel[ctx]) - 1]); ++cp)
3559 if(*cp == '\0'){
3560 *cp = (char)*u.wp;
3561 break;
3563 }else if(fun == a_TTY_BIND_FUN_PROMPT_CHAR){
3564 for(cp = &a_tty.tg_bind_shcut_prompt_char[ctx][0];
3565 PTRCMP(cp, <, &a_tty.tg_bind_shcut_prompt_char[ctx]
3566 [n_NELEM(a_tty.tg_bind_shcut_prompt_char[ctx]) - 1]);
3567 ++cp)
3568 if(*cp == '\0'){
3569 *cp = (char)*u.wp;
3570 break;
3575 isseq = (u.wp[1] != '\0');
3576 for(; *u.wp != '\0'; ++u.wp)
3577 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.wp, isseq);
3578 if(isseq)
3579 ntbtp->tbt_isseq_trail = TRU1;
3582 cnvlen -= entlen;
3583 cnvdat += entlen;
3586 /* Should have been rendered defunctional at first instead */
3587 assert(ntbtp != NULL);
3588 ntbtp->tbt_bind = tbcp;
3589 NYD2_LEAVE;
3592 static struct a_tty_bind_tree *
3593 a_tty__bind_tree_add_wc(struct a_tty_bind_tree **treep,
3594 struct a_tty_bind_tree *parentp, wchar_t wc, bool_t isseq){
3595 struct a_tty_bind_tree *tbtp, *xtbtp;
3596 NYD2_ENTER;
3598 if(parentp == NULL){
3599 treep += wc % HSHSIZE;
3601 /* Having no parent also means that the tree slot is possibly empty */
3602 for(tbtp = *treep; tbtp != NULL;
3603 parentp = tbtp, tbtp = tbtp->tbt_sibling){
3604 if(tbtp->tbt_char != wc)
3605 continue;
3606 if(tbtp->tbt_isseq == isseq)
3607 goto jleave;
3608 /* isseq MUST be linked before !isseq, so record this "parent"
3609 * sibling, but continue searching for now */
3610 if(!isseq)
3611 parentp = tbtp;
3612 /* Otherwise it is impossible that we'll find what we look for */
3613 else{
3614 #ifdef HAVE_DEBUG
3615 while((tbtp = tbtp->tbt_sibling) != NULL)
3616 assert(tbtp->tbt_char != wc);
3617 #endif
3618 break;
3622 tbtp = smalloc(sizeof *tbtp);
3623 memset(tbtp, 0, sizeof *tbtp);
3624 tbtp->tbt_char = wc;
3625 tbtp->tbt_isseq = isseq;
3627 if(parentp == NULL){
3628 tbtp->tbt_sibling = *treep;
3629 *treep = tbtp;
3630 }else{
3631 tbtp->tbt_sibling = parentp->tbt_sibling;
3632 parentp->tbt_sibling = tbtp;
3634 }else{
3635 if((tbtp = *(treep = &parentp->tbt_childs)) != NULL){
3636 for(;; tbtp = xtbtp){
3637 if(tbtp->tbt_char == wc){
3638 if(tbtp->tbt_isseq == isseq)
3639 goto jleave;
3640 /* isseq MUST be linked before, so it is impossible that we'll
3641 * find what we look for */
3642 if(isseq){
3643 #ifdef HAVE_DEBUG
3644 while((tbtp = tbtp->tbt_sibling) != NULL)
3645 assert(tbtp->tbt_char != wc);
3646 #endif
3647 tbtp = NULL;
3648 break;
3652 if((xtbtp = tbtp->tbt_sibling) == NULL){
3653 treep = &tbtp->tbt_sibling;
3654 break;
3659 xtbtp = smalloc(sizeof *xtbtp);
3660 memset(xtbtp, 0, sizeof *xtbtp);
3661 xtbtp->tbt_parent = parentp;
3662 xtbtp->tbt_char = wc;
3663 xtbtp->tbt_isseq = isseq;
3664 tbtp = xtbtp;
3665 *treep = tbtp;
3667 jleave:
3668 NYD2_LEAVE;
3669 return tbtp;
3672 static void
3673 a_tty__bind_tree_free(struct a_tty_bind_tree *tbtp){
3674 NYD2_ENTER;
3675 while(tbtp != NULL){
3676 struct a_tty_bind_tree *tmp;
3678 if((tmp = tbtp->tbt_childs) != NULL)
3679 a_tty__bind_tree_free(tmp);
3681 tmp = tbtp->tbt_sibling;
3682 free(tbtp);
3683 tbtp = tmp;
3685 NYD2_LEAVE;
3687 # endif /* HAVE_KEY_BINDINGS */
3689 FL void
3690 n_tty_init(void){
3691 NYD_ENTER;
3693 if(ok_blook(line_editor_disable))
3694 goto jleave;
3696 /* Load the history file */
3697 # ifdef HAVE_HISTORY
3698 do/* for break */{
3699 char const *v;
3700 char *lbuf;
3701 FILE *f;
3702 size_t lsize, cnt, llen;
3704 if((v = a_tty_hist_query_config()) == NULL ||
3705 a_tty.tg_hist_size_max == 0)
3706 break;
3708 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
3709 f = fopen(v, "r"); /* TODO HISTFILE LOAD: use linebuf pool */
3710 if(f == NULL)
3711 goto jhist_done;
3712 (void)n_file_lock(fileno(f), FLT_READ, 0,0, UIZ_MAX);
3714 assert(!(n_pstate & n_PS_ROOT));
3715 n_pstate |= n_PS_ROOT; /* Allow calling addhist() */
3716 lbuf = NULL;
3717 lsize = 0;
3718 cnt = (size_t)fsize(f);
3719 while(fgetline(&lbuf, &lsize, &cnt, &llen, f, FAL0) != NULL){
3720 if(llen > 0 && lbuf[llen - 1] == '\n')
3721 lbuf[--llen] = '\0';
3722 if(llen == 0 || lbuf[0] == '#') /* xxx comments? noone! */
3723 continue;
3724 else{
3725 bool_t isgabby;
3727 isgabby = (lbuf[0] == '*');
3728 n_tty_addhist(lbuf + isgabby, isgabby);
3731 if(lbuf != NULL)
3732 free(lbuf);
3733 n_pstate &= ~n_PS_ROOT;
3735 fclose(f);
3736 jhist_done:
3737 rele_all_sigs(); /* XXX remove jumps */
3738 }while(0);
3739 # endif /* HAVE_HISTORY */
3741 /* Force immediate resolve for anything which follows */
3742 n_psonce |= n_PSO_LINE_EDITOR_INIT;
3744 # ifdef HAVE_KEY_BINDINGS
3745 /* `bind's (and `unbind's) done from within resource files couldn't be
3746 * performed for real since our termcap driver wasn't yet loaded, and we
3747 * can't perform automatic init since the user may have disallowed so */
3748 /* C99 */{
3749 struct a_tty_bind_ctx *tbcp;
3750 enum n_go_input_flags gif;
3752 for(gif = 0; gif < n__GO_INPUT_CTX_MAX1; ++gif)
3753 for(tbcp = a_tty.tg_bind[gif]; tbcp != NULL; tbcp = tbcp->tbc_next)
3754 if((tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
3755 a_TTY_BIND_RESOLVE)
3756 a_tty_bind_resolve(tbcp);
3759 /* And we want to (try to) install some default key bindings */
3760 if(!ok_blook(line_editor_no_defaults)){
3761 char buf[8];
3762 struct a_tty_bind_parse_ctx tbpc;
3763 struct a_tty_bind_builtin_tuple const *tbbtp, *tbbtp_max;
3764 ui32_t flags;
3766 buf[0] = '$', buf[1] = '\'', buf[2] = '\\', buf[3] = 'c',
3767 buf[5] = '\'', buf[6] = '\0';
3769 tbbtp = a_tty_bind_base_tuples;
3770 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_base_tuples)];
3771 flags = n_GO_INPUT_CTX_BASE;
3772 jbuiltin_redo:
3773 for(; tbbtp < tbbtp_max; ++tbbtp){
3774 memset(&tbpc, 0, sizeof tbpc);
3775 tbpc.tbpc_cmd = "bind";
3776 if(tbbtp->tbbt_iskey){
3777 buf[4] = tbbtp->tbbt_ckey;
3778 tbpc.tbpc_in_seq = buf;
3779 }else
3780 tbpc.tbpc_in_seq = savecatsep(":", '\0',
3781 n_termcap_name_of_query(tbbtp->tbbt_query));
3782 tbpc.tbpc_exp.s = n_UNCONST(tbbtp->tbbt_exp[0] == '\0'
3783 ? a_tty_bind_fun_names[(ui8_t)tbbtp->tbbt_exp[1]]
3784 : tbbtp->tbbt_exp);
3785 tbpc.tbpc_exp.l = strlen(tbpc.tbpc_exp.s);
3786 tbpc.tbpc_flags = flags;
3787 /* ..but don't want to overwrite any user settings */
3788 a_tty_bind_create(&tbpc, FAL0);
3790 if(flags == n_GO_INPUT_CTX_BASE){
3791 tbbtp = a_tty_bind_default_tuples;
3792 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_default_tuples)];
3793 flags = n_GO_INPUT_CTX_DEFAULT;
3794 goto jbuiltin_redo;
3797 # endif /* HAVE_KEY_BINDINGS */
3799 jleave:
3800 NYD_LEAVE;
3803 FL void
3804 n_tty_destroy(void){
3805 NYD_ENTER;
3807 if(!(n_psonce & n_PSO_LINE_EDITOR_INIT))
3808 goto jleave;
3810 # ifdef HAVE_HISTORY
3811 do/* for break */{
3812 size_t i;
3813 char const *v;
3814 struct a_tty_hist *thp;
3815 bool_t dogabby;
3816 FILE *f;
3818 if((v = a_tty_hist_query_config()) == NULL ||
3819 a_tty.tg_hist_size_max == 0)
3820 break;
3822 dogabby = ok_blook(history_gabby_persist);
3824 if((thp = a_tty.tg_hist) != NULL)
3825 for(i = a_tty.tg_hist_size_max; thp->th_older != NULL;
3826 thp = thp->th_older)
3827 if((dogabby || !thp->th_isgabby) && --i == 0)
3828 break;
3830 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
3831 f = fopen(v, "w"); /* TODO temporary + rename?! */
3832 if(f == NULL)
3833 goto jhist_done;
3834 (void)n_file_lock(fileno(f), FLT_WRITE, 0,0, UIZ_MAX);
3836 for(; thp != NULL; thp = thp->th_younger){
3837 if(dogabby || !thp->th_isgabby){
3838 if(thp->th_isgabby)
3839 putc('*', f);
3840 fwrite(thp->th_dat, sizeof *thp->th_dat, thp->th_len, f);
3841 putc('\n', f);
3844 fclose(f);
3845 jhist_done:
3846 rele_all_sigs(); /* XXX remove jumps */
3847 }while(0);
3848 # endif /* HAVE_HISTORY */
3850 # if defined HAVE_KEY_BINDINGS && defined HAVE_DEBUG
3851 c_unbind(n_UNCONST("* *"));
3852 # endif
3854 # ifdef HAVE_DEBUG
3855 memset(&a_tty, 0, sizeof a_tty);
3856 # endif
3857 DBG( n_psonce &= ~n_PSO_LINE_EDITOR_INIT; )
3858 jleave:
3859 NYD_LEAVE;
3862 FL void
3863 n_tty_signal(int sig){
3864 sigset_t nset, oset;
3865 NYD_X; /* Signal handler */
3867 switch(sig){
3868 # ifdef SIGWINCH
3869 case SIGWINCH:
3870 /* We don't deal with SIGWINCH, yet get called from main.c.
3871 * Note this case might get called even if !n_PO_LINE_EDITOR_INIT */
3872 break;
3873 # endif
3874 default:
3875 a_tty_term_mode(FAL0);
3876 n_TERMCAP_SUSPEND(TRU1);
3877 a_tty_sigs_down();
3879 sigemptyset(&nset);
3880 sigaddset(&nset, sig);
3881 sigprocmask(SIG_UNBLOCK, &nset, &oset);
3882 n_raise(sig);
3883 /* When we come here we'll continue editing, so reestablish */
3884 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
3886 a_tty_sigs_up();
3887 n_TERMCAP_RESUME(TRU1);
3888 a_tty_term_mode(TRU1);
3889 a_tty.tg_line->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
3890 break;
3894 FL int
3895 (n_tty_readline)(enum n_go_input_flags gif, char const *prompt,
3896 char **linebuf, size_t *linesize, size_t n n_MEMORY_DEBUG_ARGS){
3897 struct a_tty_line tl;
3898 struct n_string xprompt;
3899 # ifdef HAVE_COLOUR
3900 char *posbuf, *pos;
3901 # endif
3902 ssize_t nn;
3903 NYD_ENTER;
3904 n_UNUSED(gif);
3906 assert(!ok_blook(line_editor_disable));
3907 if(!(n_psonce & n_PSO_LINE_EDITOR_INIT))
3908 n_tty_init();
3909 assert(n_psonce & n_PSO_LINE_EDITOR_INIT);
3911 # ifdef HAVE_COLOUR
3912 n_colour_env_create(n_COLOUR_CTX_MLE, n_tty_fp, FAL0);
3914 /* .tl_pos_buf is a hack */
3915 posbuf = pos = NULL;
3917 if(n_COLOUR_IS_ACTIVE()){
3918 char const *ccol;
3919 struct n_colour_pen *ccp;
3920 struct str const *sp;
3922 if((ccp = n_colour_pen_create(n_COLOUR_ID_MLE_POSITION, NULL)) != NULL &&
3923 (sp = n_colour_pen_to_str(ccp)) != NULL){
3924 ccol = sp->s;
3925 if((sp = n_colour_reset_to_str()) != NULL){
3926 size_t l1, l2;
3928 l1 = strlen(ccol);
3929 l2 = strlen(sp->s);
3930 posbuf = salloc(l1 + 4 + l2 +1);
3931 memcpy(posbuf, ccol, l1);
3932 pos = &posbuf[l1];
3933 memcpy(&pos[4], sp->s, ++l2);
3938 if(posbuf == NULL){
3939 posbuf = pos = salloc(4 +1);
3940 pos[4] = '\0';
3942 # endif /* HAVE_COLOUR */
3944 memset(&tl, 0, sizeof tl);
3946 # ifdef HAVE_KEY_BINDINGS
3947 /* C99 */{
3948 char const *cp;
3950 if((cp = ok_vlook(bind_timeout)) != NULL){
3951 ui64_t uib;
3953 n_idec_ui64_cp(&uib, cp, 0, NULL);
3955 if(uib > 0 &&
3956 /* Convert to tenths of a second, unfortunately */
3957 (uib = (uib + 99) / 100) <= a_TTY_BIND_TIMEOUT_MAX)
3958 tl.tl_bind_timeout = (ui8_t)uib;
3959 else if(n_poption & n_PO_D_V)
3960 n_err(_("Ignoring invalid *bind-timeout*: %s\n"), cp);
3964 if(a_tty.tg_bind_isdirty)
3965 a_tty_bind_tree_teardown();
3966 if(a_tty.tg_bind_cnt > 0 && !a_tty.tg_bind_isbuild)
3967 a_tty_bind_tree_build();
3968 tl.tl_bind_tree_hmap = &a_tty.tg_bind_tree[gif & n__GO_INPUT_CTX_MASK];
3969 tl.tl_bind_shcut_cancel =
3970 &a_tty.tg_bind_shcut_cancel[gif & n__GO_INPUT_CTX_MASK];
3971 tl.tl_bind_shcut_prompt_char =
3972 &a_tty.tg_bind_shcut_prompt_char[gif & n__GO_INPUT_CTX_MASK];
3973 # endif /* HAVE_KEY_BINDINGS */
3975 # ifdef HAVE_COLOUR
3976 tl.tl_pos_buf = posbuf;
3977 tl.tl_pos = pos;
3978 # endif
3980 if(!(gif & n_GO_INPUT_PROMPT_NONE)){
3981 n_string_creat_auto(&xprompt);
3983 if((tl.tl_prompt_width = n_tty_create_prompt(&xprompt, prompt, gif)
3984 ) > 0){
3985 tl.tl_prompt = n_string_cp_const(&xprompt);
3986 tl.tl_prompt_length = (ui32_t)xprompt.s_len;
3990 tl.tl_line.cbuf = *linebuf;
3991 if(n != 0){
3992 tl.tl_defc.s = savestrbuf(*linebuf, n);
3993 tl.tl_defc.l = n;
3995 tl.tl_x_buf = linebuf;
3996 tl.tl_x_bufsize = linesize;
3998 a_tty.tg_line = &tl;
3999 a_tty_sigs_up();
4000 n_TERMCAP_RESUME(FAL0);
4001 a_tty_term_mode(TRU1);
4002 nn = a_tty_readline(&tl, n n_MEMORY_DEBUG_ARGSCALL);
4003 a_tty_term_mode(FAL0);
4004 n_TERMCAP_SUSPEND(FAL0);
4005 a_tty_sigs_down();
4006 a_tty.tg_line = NULL;
4008 n_COLOUR( n_colour_env_gut(); )
4009 NYD_LEAVE;
4010 return (int)nn;
4013 FL void
4014 n_tty_addhist(char const *s, bool_t isgabby){
4015 # ifdef HAVE_HISTORY
4016 /* Super-Heavy-Metal: block all sigs, avoid leaks+ on jump */
4017 ui32_t l;
4018 struct a_tty_hist *thp, *othp, *ythp;
4019 # endif
4020 NYD_ENTER;
4021 n_UNUSED(s);
4022 n_UNUSED(isgabby);
4024 # ifdef HAVE_HISTORY
4025 if(spacechar(*s) || *s == '\0' ||
4026 (!(n_psonce & n_PSO_LINE_EDITOR_INIT) && !(n_pstate & n_PS_ROOT)) ||
4027 a_tty.tg_hist_size_max == 0 ||
4028 ok_blook(line_editor_disable) ||
4029 (isgabby && !ok_blook(history_gabby)))
4030 goto j_leave;
4032 l = (ui32_t)strlen(s);
4034 /* Eliminating duplicates is expensive, but simply inacceptable so
4035 * during the load of a potentially large history file! */
4036 if(n_psonce & n_PSO_LINE_EDITOR_INIT)
4037 for(thp = a_tty.tg_hist; thp != NULL; thp = thp->th_older)
4038 if(thp->th_len == l && !strcmp(thp->th_dat, s)){
4039 hold_all_sigs(); /* TODO */
4040 if(thp->th_isgabby)
4041 thp->th_isgabby = !!isgabby;
4042 othp = thp->th_older;
4043 ythp = thp->th_younger;
4044 if(othp != NULL)
4045 othp->th_younger = ythp;
4046 else
4047 a_tty.tg_hist_tail = ythp;
4048 if(ythp != NULL)
4049 ythp->th_older = othp;
4050 else
4051 a_tty.tg_hist = othp;
4052 goto jleave;
4054 hold_all_sigs();
4056 ++a_tty.tg_hist_size;
4057 if((n_psonce & n_PSO_LINE_EDITOR_INIT) &&
4058 a_tty.tg_hist_size > a_tty.tg_hist_size_max){
4059 --a_tty.tg_hist_size;
4060 if((thp = a_tty.tg_hist_tail) != NULL){
4061 if((a_tty.tg_hist_tail = thp->th_younger) == NULL)
4062 a_tty.tg_hist = NULL;
4063 else
4064 a_tty.tg_hist_tail->th_older = NULL;
4065 free(thp);
4069 thp = smalloc(n_VSTRUCT_SIZEOF(struct a_tty_hist, th_dat) + l +1);
4070 thp->th_isgabby = !!isgabby;
4071 thp->th_len = l;
4072 memcpy(thp->th_dat, s, l +1);
4073 jleave:
4074 if((thp->th_older = a_tty.tg_hist) != NULL)
4075 a_tty.tg_hist->th_younger = thp;
4076 else
4077 a_tty.tg_hist_tail = thp;
4078 thp->th_younger = NULL;
4079 a_tty.tg_hist = thp;
4081 rele_all_sigs();
4082 j_leave:
4083 # endif /* HAVE_HISTORY */
4084 NYD_LEAVE;
4087 # ifdef HAVE_HISTORY
4088 FL int
4089 c_history(void *v){
4090 siz_t entry;
4091 struct a_tty_hist *thp;
4092 char **argv;
4093 NYD_ENTER;
4095 if(ok_blook(line_editor_disable)){
4096 n_err(_("history: *line-editor-disable* is set\n"));
4097 goto jerr;
4100 if(!(n_psonce & n_PSO_LINE_EDITOR_INIT)){
4101 n_tty_init();
4102 assert(n_psonce & n_PSO_LINE_EDITOR_INIT);
4105 if(*(argv = v) == NULL)
4106 goto jlist;
4107 if(argv[1] != NULL)
4108 goto jerr;
4109 if(!asccasecmp(*argv, "show"))
4110 goto jlist;
4111 if(!asccasecmp(*argv, "clear"))
4112 goto jclear;
4113 if((n_idec_siz_cp(&entry, *argv, 10, NULL
4114 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
4115 ) == n_IDEC_STATE_CONSUMED)
4116 goto jentry;
4117 jerr:
4118 n_err(_("Synopsis: history: %s\n"),
4119 /* Same string as in cmd-tab.h, still hoping...) */
4120 _("<show> (default), <clear> or select <NO> from editor history"));
4121 v = NULL;
4122 jleave:
4123 NYD_LEAVE;
4124 return (v == NULL ? !STOP : !OKAY); /* xxx 1:bad 0:good -- do some */
4126 jlist:{
4127 FILE *fp;
4128 size_t i, b;
4130 if(a_tty.tg_hist == NULL)
4131 goto jleave;
4133 if((fp = Ftmp(NULL, "hist", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
4134 n_perr(_("tmpfile"), 0);
4135 v = NULL;
4136 goto jleave;
4139 i = a_tty.tg_hist_size;
4140 b = 0;
4141 for(thp = a_tty.tg_hist; thp != NULL;
4142 --i, b += thp->th_len, thp = thp->th_older)
4143 fprintf(fp,
4144 "%c%4" PRIuZ ". %-50.50s (%4" PRIuZ "+%2" PRIu32 " B)\n",
4145 (thp->th_isgabby ? '*' : ' '), i, thp->th_dat, b, thp->th_len);
4147 page_or_print(fp, i);
4148 Fclose(fp);
4150 goto jleave;
4152 jclear:
4153 while((thp = a_tty.tg_hist) != NULL){
4154 a_tty.tg_hist = thp->th_older;
4155 free(thp);
4157 a_tty.tg_hist_tail = NULL;
4158 a_tty.tg_hist_size = 0;
4159 goto jleave;
4161 jentry:{
4162 siz_t ep;
4164 ep = (entry < 0) ? -entry : entry;
4166 if(ep != 0 && UICMP(z, ep, <=, a_tty.tg_hist_size)){
4167 if(ep != entry)
4168 --ep;
4169 else
4170 ep = (siz_t)a_tty.tg_hist_size - ep;
4171 for(thp = a_tty.tg_hist;; thp = thp->th_older){
4172 assert(thp != NULL);
4173 if(ep-- == 0){
4174 n_go_input_inject((n_GO_INPUT_INJECT_COMMIT |
4175 n_GO_INPUT_INJECT_HISTORY), v = thp->th_dat, thp->th_len);
4176 break;
4179 }else{
4180 n_err(_("`history': no such entry: %" PRIdZ "\n"), entry);
4181 v = NULL;
4184 goto jleave;
4186 # endif /* HAVE_HISTORY */
4188 # ifdef HAVE_KEY_BINDINGS
4189 FL int
4190 c_bind(void *v){
4191 n_CMD_ARG_DESC_SUBCLASS_DEF(bind, 3, a_tty_bind_cad) { /* TODO cmd-tab.h */
4192 {n_CMD_ARG_DESC_STRING, 0},
4193 {n_CMD_ARG_DESC_WYSH | n_CMD_ARG_DESC_OPTION |
4194 n_CMD_ARG_DESC_HONOUR_STOP,
4195 n_SHEXP_PARSE_DRYRUN | n_SHEXP_PARSE_LOG},
4196 {n_CMD_ARG_DESC_WYSH | n_CMD_ARG_DESC_OPTION | n_CMD_ARG_DESC_GREEDY |
4197 n_CMD_ARG_DESC_HONOUR_STOP,
4198 n_SHEXP_PARSE_IGNORE_EMPTY}
4199 } n_CMD_ARG_DESC_SUBCLASS_DEF_END;
4200 struct n_cmd_arg_ctx cac;
4201 struct a_tty_bind_ctx *tbcp;
4202 enum n_go_input_flags gif;
4203 bool_t aster, show;
4204 union {char const *cp; char *p; char c;} c;
4205 NYD_ENTER;
4207 cac.cac_desc = n_CMD_ARG_DESC_SUBCLASS_CAST(&a_tty_bind_cad);
4208 cac.cac_indat = v;
4209 cac.cac_inlen = UIZ_MAX;
4210 if(!n_cmd_arg_parse(&cac)){
4211 v = NULL;
4212 goto jleave;
4215 c.cp = cac.cac_arg->ca_arg.ca_str.s;
4216 if(cac.cac_no == 1)
4217 show = TRU1;
4218 else
4219 show = !asccasecmp(cac.cac_arg->ca_next->ca_arg.ca_str.s, "show");
4220 aster = FAL0;
4222 if((gif = a_tty_bind_ctx_find(c.cp)) == (enum n_go_input_flags)-1){
4223 if(!(aster = n_is_all_or_aster(c.cp)) || !show){
4224 n_err(_("`bind': invalid context: %s\n"), c.cp);
4225 v = NULL;
4226 goto jleave;
4228 gif = 0;
4231 if(show){
4232 ui32_t lns;
4233 FILE *fp;
4235 if((fp = Ftmp(NULL, "bind", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
4236 n_perr(_("tmpfile"), 0);
4237 v = NULL;
4238 goto jleave;
4241 lns = 0;
4242 for(;;){
4243 for(tbcp = a_tty.tg_bind[gif]; tbcp != NULL;
4244 ++lns, tbcp = tbcp->tbc_next){
4245 /* Print the bytes of resolved terminal capabilities, then */
4246 if((n_poption & n_PO_D_V) &&
4247 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)
4248 ) == a_TTY_BIND_RESOLVE){
4249 char cbuf[8];
4250 union {wchar_t const *wp; char const *cp;} u;
4251 si32_t entlen;
4252 ui32_t cnvlen;
4253 char const *cnvdat, *bsep, *cbufp;
4255 putc('#', fp);
4256 putc(' ', fp);
4258 cbuf[0] = '=', cbuf[2] = '\0';
4259 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len;
4260 cnvlen > 0;){
4261 if(cnvdat != tbcp->tbc_cnv)
4262 putc(',', fp);
4264 /* {si32_t buf_len_iscap;} */
4265 entlen = *n_UNALIGN(si32_t const*,cnvdat);
4266 if(entlen & SI32_MIN){
4267 /* struct{si32_t buf_len_iscap; si32_t cap_len;
4268 * char buf[]+NUL;} */
4269 for(bsep = n_empty,
4270 u.cp = (char const*)
4271 &n_UNALIGN(si32_t const*,cnvdat)[2];
4272 (c.c = *u.cp) != '\0'; ++u.cp){
4273 if(asciichar(c.c) && !cntrlchar(c.c))
4274 cbuf[1] = c.c, cbufp = cbuf;
4275 else
4276 cbufp = n_empty;
4277 fprintf(fp, "%s%02X%s",
4278 bsep, (ui32_t)(ui8_t)c.c, cbufp);
4279 bsep = " ";
4281 entlen &= SI32_MAX;
4282 }else
4283 putc('-', fp);
4285 cnvlen -= entlen;
4286 cnvdat += entlen;
4289 fputs("\n ", fp);
4290 ++lns;
4293 fprintf(fp, "%sbind %s %s %s%s%s\n",
4294 ((tbcp->tbc_flags & a_TTY_BIND_DEFUNCT)
4295 /* I18N: `bind' sequence not working, either because it is
4296 * I18N: using Unicode and that is not available in the locale,
4297 * I18N: or a termcap(5)/terminfo(5) sequence won't work out */
4298 ? _("# <Defunctional> ") : n_empty),
4299 a_tty_bind_ctx_maps[gif].tbcm_name, tbcp->tbc_seq,
4300 n_shexp_quote_cp(tbcp->tbc_exp, TRU1),
4301 (tbcp->tbc_flags & a_TTY_BIND_NOCOMMIT ? n_at : n_empty),
4302 (!(n_poption & n_PO_D_VV) ? n_empty
4303 : (tbcp->tbc_flags & a_TTY_BIND_FUN_INTERNAL
4304 ? _(" # MLE internal") : n_empty))
4307 if(!aster || ++gif >= n__GO_INPUT_CTX_MAX1)
4308 break;
4310 page_or_print(fp, lns);
4312 Fclose(fp);
4313 }else{
4314 struct a_tty_bind_parse_ctx tbpc;
4315 struct n_string store;
4317 memset(&tbpc, 0, sizeof tbpc);
4318 tbpc.tbpc_cmd = a_tty_bind_cad.cad_name;
4319 tbpc.tbpc_in_seq = cac.cac_arg->ca_next->ca_arg.ca_str.s;
4320 tbpc.tbpc_exp.s = n_string_cp(n_cmd_arg_join_greedy(&cac,
4321 n_string_creat_auto(&store)));
4322 tbpc.tbpc_exp.l = store.s_len;
4323 tbpc.tbpc_flags = gif;
4324 if(!a_tty_bind_create(&tbpc, TRU1))
4325 v = NULL;
4326 n_string_gut(&store);
4328 jleave:
4329 NYD_LEAVE;
4330 return (v != NULL) ? n_EXIT_OK : n_EXIT_ERR;
4333 FL int
4334 c_unbind(void *v){
4335 n_CMD_ARG_DESC_SUBCLASS_DEF(unbind, 2, a_tty_unbind_cad) {/* TODO cmd-tab.h*/
4336 {n_CMD_ARG_DESC_STRING, 0},
4337 {n_CMD_ARG_DESC_WYSH | n_CMD_ARG_DESC_HONOUR_STOP,
4338 n_SHEXP_PARSE_DRYRUN | n_SHEXP_PARSE_LOG}
4339 } n_CMD_ARG_DESC_SUBCLASS_DEF_END;
4340 struct a_tty_bind_parse_ctx tbpc;
4341 struct n_cmd_arg_ctx cac;
4342 struct a_tty_bind_ctx *tbcp;
4343 enum n_go_input_flags gif;
4344 bool_t aster;
4345 union {char const *cp; char *p;} c;
4346 NYD_ENTER;
4348 cac.cac_desc = n_CMD_ARG_DESC_SUBCLASS_CAST(&a_tty_unbind_cad);
4349 cac.cac_indat = v;
4350 cac.cac_inlen = UIZ_MAX;
4351 if(!n_cmd_arg_parse(&cac)){
4352 v = NULL;
4353 goto jleave;
4356 c.cp = cac.cac_arg->ca_arg.ca_str.s;
4357 aster = FAL0;
4359 if((gif = a_tty_bind_ctx_find(c.cp)) == (enum n_go_input_flags)-1){
4360 if(!(aster = n_is_all_or_aster(c.cp))){
4361 n_err(_("`unbind': invalid context: %s\n"), c.cp);
4362 v = NULL;
4363 goto jleave;
4365 gif = 0;
4368 c.cp = cac.cac_arg->ca_next->ca_arg.ca_str.s;
4369 jredo:
4370 if(n_is_all_or_aster(c.cp)){
4371 while((tbcp = a_tty.tg_bind[gif]) != NULL){
4372 memset(&tbpc, 0, sizeof tbpc);
4373 tbpc.tbpc_tbcp = tbcp;
4374 tbpc.tbpc_flags = gif;
4375 a_tty_bind_del(&tbpc);
4377 }else{
4378 memset(&tbpc, 0, sizeof tbpc);
4379 tbpc.tbpc_cmd = a_tty_unbind_cad.cad_name;
4380 tbpc.tbpc_in_seq = c.cp;
4381 tbpc.tbpc_flags = gif;
4383 if(n_UNLIKELY(!a_tty_bind_parse(FAL0, &tbpc)))
4384 v = NULL;
4385 else if(n_UNLIKELY((tbcp = tbpc.tbpc_tbcp) == NULL)){
4386 n_err(_("`unbind': no such `bind'ing: %s %s\n"),
4387 a_tty_bind_ctx_maps[gif].tbcm_name, c.cp);
4388 v = NULL;
4389 }else
4390 a_tty_bind_del(&tbpc);
4393 if(aster && ++gif < n__GO_INPUT_CTX_MAX1)
4394 goto jredo;
4395 jleave:
4396 NYD_LEAVE;
4397 return (v != NULL) ? n_EXIT_OK : n_EXIT_ERR;
4399 # endif /* HAVE_KEY_BINDINGS */
4401 #else /* HAVE_MLE */
4403 * The really-nothing-at-all implementation
4406 FL void
4407 n_tty_init(void){
4408 NYD_ENTER;
4409 NYD_LEAVE;
4412 FL void
4413 n_tty_destroy(void){
4414 NYD_ENTER;
4415 NYD_LEAVE;
4418 FL void
4419 n_tty_signal(int sig){
4420 NYD_X; /* Signal handler */
4421 n_UNUSED(sig);
4423 # ifdef HAVE_TERMCAP
4424 switch(sig){
4425 default:{
4426 sigset_t nset, oset;
4428 n_TERMCAP_SUSPEND(TRU1);
4429 a_tty_sigs_down();
4431 sigemptyset(&nset);
4432 sigaddset(&nset, sig);
4433 sigprocmask(SIG_UNBLOCK, &nset, &oset);
4434 n_raise(sig);
4435 /* When we come here we'll continue editing, so reestablish */
4436 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
4438 a_tty_sigs_up();
4439 n_TERMCAP_RESUME(TRU1);
4440 break;
4443 # endif /* HAVE_TERMCAP */
4446 FL int
4447 (n_tty_readline)(enum n_go_input_flags gif, char const *prompt,
4448 char **linebuf, size_t *linesize, size_t n n_MEMORY_DEBUG_ARGS){
4449 struct n_string xprompt;
4450 int rv;
4451 NYD_ENTER;
4453 if(!(gif & n_GO_INPUT_PROMPT_NONE)){
4454 if(n_tty_create_prompt(n_string_creat_auto(&xprompt), prompt, gif) > 0){
4455 fwrite(xprompt.s_dat, 1, xprompt.s_len, n_tty_fp);
4456 fflush(n_tty_fp);
4460 # ifdef HAVE_TERMCAP
4461 a_tty_sigs_up();
4462 n_TERMCAP_RESUME(FAL0);
4463 # endif
4464 rv = (readline_restart)(n_stdin, linebuf, linesize,n n_MEMORY_DEBUG_ARGSCALL);
4465 # ifdef HAVE_TERMCAP
4466 n_TERMCAP_SUSPEND(FAL0);
4467 a_tty_sigs_down();
4468 # endif
4469 NYD_LEAVE;
4470 return rv;
4473 FL void
4474 n_tty_addhist(char const *s, bool_t isgabby){
4475 NYD_ENTER;
4476 n_UNUSED(s);
4477 n_UNUSED(isgabby);
4478 NYD_LEAVE;
4480 #endif /* nothing at all */
4482 #undef a_TTY_SIGNALS
4483 /* s-it-mode */