Bump S-nail v14.9.4.ar ("(5th anniversary) Marsh tit"), 2017-09-18
[s-mailx.git] / tty.c
blob994c19a190535da5b9f2094898f94e322c3e2a48
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 siglongjmp(a_tty__actjmp, s);
90 FL bool_t
91 getapproval(char const * volatile prompt, bool_t noninteract_default)
93 sighandler_type volatile oint, ohup;
94 bool_t volatile rv;
95 int volatile sig;
96 NYD_ENTER;
98 if(!(n_psonce & n_PSO_INTERACTIVE) || (n_pstate & n_PS_ROBOT)){
99 sig = 0;
100 rv = noninteract_default;
101 goto jleave;
103 rv = FAL0;
105 /* C99 */{
106 char const *quest = noninteract_default
107 ? _("[yes]/no? ") : _("[no]/yes? ");
109 if (prompt == NULL)
110 prompt = _("Continue");
111 prompt = savecatsep(prompt, ' ', quest);
114 oint = safe_signal(SIGINT, SIG_IGN);
115 ohup = safe_signal(SIGHUP, SIG_IGN);
116 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
117 goto jrestore;
118 safe_signal(SIGINT, &a_tty__acthdl);
119 safe_signal(SIGHUP, &a_tty__acthdl);
121 if (n_go_input(n_GO_INPUT_CTX_DEFAULT | n_GO_INPUT_NL_ESC, prompt,
122 &termios_state.ts_linebuf, &termios_state.ts_linesize, NULL,NULL) >= 0)
123 rv = (boolify(termios_state.ts_linebuf, UIZ_MAX,
124 noninteract_default) > 0);
125 jrestore:
126 safe_signal(SIGHUP, ohup);
127 safe_signal(SIGINT, oint);
128 jleave:
129 NYD_LEAVE;
130 if (sig != 0)
131 n_raise(sig);
132 return rv;
135 #ifdef HAVE_SOCKETS
136 FL char *
137 getuser(char const * volatile query) /* TODO v15-compat obsolete */
139 sighandler_type volatile oint, ohup;
140 char * volatile user = NULL;
141 int volatile sig;
142 NYD_ENTER;
144 if (query == NULL)
145 query = _("User: ");
147 oint = safe_signal(SIGINT, SIG_IGN);
148 ohup = safe_signal(SIGHUP, SIG_IGN);
149 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
150 goto jrestore;
151 safe_signal(SIGINT, &a_tty__acthdl);
152 safe_signal(SIGHUP, &a_tty__acthdl);
154 if (n_go_input(n_GO_INPUT_CTX_DEFAULT | n_GO_INPUT_NL_ESC, query,
155 &termios_state.ts_linebuf, &termios_state.ts_linesize, NULL,NULL) >= 0)
156 user = termios_state.ts_linebuf;
158 jrestore:
159 safe_signal(SIGHUP, ohup);
160 safe_signal(SIGINT, oint);
162 NYD_LEAVE;
163 if (sig != 0)
164 n_raise(sig);
165 return user;
168 FL char *
169 getpassword(char const *query)/* TODO v15: use _only_ n_tty_fp! */
171 sighandler_type volatile oint, ohup;
172 struct termios tios;
173 char * volatile pass;
174 int volatile sig;
175 NYD_ENTER;
177 pass = NULL;
178 if(!(n_psonce & n_PSO_TTYIN))
179 goto j_leave;
181 if (query == NULL)
182 query = _("Password: ");
183 fputs(query, n_tty_fp);
184 fflush(n_tty_fp);
186 /* FIXME everywhere: tcsetattr() generates SIGTTOU when we're not in
187 * FIXME foreground pgrp, and can fail with EINTR!! also affects
188 * FIXME termios_state_reset() */
189 tcgetattr(STDIN_FILENO, &termios_state.ts_tios);
190 memcpy(&tios, &termios_state.ts_tios, sizeof tios);
191 termios_state.ts_needs_reset = TRU1;
192 tios.c_iflag &= ~(ISTRIP);
193 tios.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
195 oint = safe_signal(SIGINT, SIG_IGN);
196 ohup = safe_signal(SIGHUP, SIG_IGN);
197 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
198 goto jrestore;
199 safe_signal(SIGINT, &a_tty__acthdl);
200 safe_signal(SIGHUP, &a_tty__acthdl);
202 tcsetattr(STDIN_FILENO, TCSAFLUSH, &tios);
203 if (readline_restart(n_stdin, &termios_state.ts_linebuf,
204 &termios_state.ts_linesize, 0) >= 0)
205 pass = termios_state.ts_linebuf;
206 jrestore:
207 termios_state_reset();
208 putc('\n', n_tty_fp);
210 safe_signal(SIGHUP, ohup);
211 safe_signal(SIGINT, oint);
212 NYD_LEAVE;
213 if (sig != 0)
214 n_raise(sig);
215 j_leave:
216 return pass;
218 #endif /* HAVE_SOCKETS */
220 FL ui32_t
221 n_tty_create_prompt(struct n_string *store, char const *xprompt,
222 enum n_go_input_flags gif){
223 struct n_visual_info_ctx vic;
224 struct str in, out;
225 ui32_t pwidth;
226 char const *cp;
227 NYD2_ENTER;
229 /* Prompt creation indicates that prompt printing is directly ahead, so take
230 * this opportunity of UI-in-a-known-state and advertise the error ring */
231 #ifdef HAVE_ERRORS
232 if((n_psonce & (n_PSO_INTERACTIVE | n_PSO_ERRORS_NOTED)
233 ) == n_PSO_INTERACTIVE && (n_pstate & n_PS_ERRORS_PROMPT)){
234 n_psonce |= n_PSO_ERRORS_NOTED;
235 fprintf(n_stdout, _("There are new messages in the error message ring "
236 "(denoted by %s)\n"
237 " The `errors' command manages this message ring\n"),
238 V_(n_error));
240 #endif
242 jredo:
243 n_string_trunc(store, 0);
245 if(gif & n_GO_INPUT_PROMPT_NONE){
246 pwidth = 0;
247 goto jleave;
249 #ifdef HAVE_ERRORS
250 if(n_pstate & n_PS_ERRORS_PROMPT){
251 n_pstate &= ~n_PS_ERRORS_PROMPT;
252 store = n_string_push_cp(store, V_(n_error));
253 store = n_string_push_c(store, '#');
254 store = n_string_push_c(store, ' ');
256 #endif
258 cp = (gif & n_GO_INPUT_PROMPT_EVAL)
259 ? (gif & n_GO_INPUT_NL_FOLLOW ? ok_vlook(prompt2) : ok_vlook(prompt))
260 : xprompt;
261 if(cp != NULL && *cp != '\0'){
262 enum n_shexp_state shs;
264 store = n_string_push_cp(store, cp);
265 in.s = n_string_cp(store);
266 in.l = store->s_len;
267 out = in;
268 store = n_string_drop_ownership(store);
270 shs = n_shexp_parse_token((n_SHEXP_PARSE_LOG |
271 n_SHEXP_PARSE_IGNORE_EMPTY | n_SHEXP_PARSE_QUOTE_AUTO_FIXED |
272 n_SHEXP_PARSE_QUOTE_AUTO_DSQ), store, &in, NULL);
273 if((shs & n_SHEXP_STATE_ERR_MASK) || !(shs & n_SHEXP_STATE_STOP)){
274 store = n_string_clear(store);
275 store = n_string_take_ownership(store, out.s, out.l +1, out.l);
276 jeeval:
277 n_err(_("*prompt2?* evaluation failed, actively unsetting it\n"));
278 if(gif & n_GO_INPUT_NL_FOLLOW)
279 ok_vclear(prompt2);
280 else
281 ok_vclear(prompt);
282 goto jredo;
285 if(!store->s_auto)
286 free(out.s);
289 /* Make all printable TODO not know, we want to pass through ESC/CSI! */
290 #if 0
291 in.s = n_string_cp(store);
292 in.l = store->s_len;
293 makeprint(&in, &out);
294 store = n_string_assign_buf(store, out.s, out.l);
295 free(out.s);
296 #endif
298 /* We need the visual width.. */
299 memset(&vic, 0, sizeof vic);
300 vic.vic_indat = n_string_cp(store);
301 vic.vic_inlen = store->s_len;
302 for(pwidth = 0; vic.vic_inlen > 0;){
303 /* but \[ .. \] is not taken into account */
304 if(vic.vic_indat[0] == '\\' && vic.vic_inlen > 1 &&
305 vic.vic_indat[1] == '['){
306 size_t i;
308 i = PTR2SIZE(vic.vic_indat - store->s_dat);
309 store = n_string_cut(store, i, 2);
310 cp = &n_string_cp(store)[i];
311 i = store->s_len - i;
312 for(;; ++cp, --i){
313 if(i < 2){
314 n_err(_("Open \\[ sequence not closed in *prompt2?*\n"));
315 goto jeeval;
317 if(cp[0] == '\\' && cp[1] == ']')
318 break;
320 i = PTR2SIZE(cp - store->s_dat);
321 store = n_string_cut(store, i, 2);
322 vic.vic_indat = &n_string_cp(store)[i];
323 vic.vic_inlen = store->s_len - i;
324 }else if(!n_visual_info(&vic, n_VISUAL_INFO_WIDTH_QUERY |
325 n_VISUAL_INFO_ONE_CHAR)){
326 n_err(_("Character set error in evaluation of *prompt2?*\n"));
327 goto jeeval;
328 }else{
329 pwidth += (ui32_t)vic.vic_vi_width;
330 vic.vic_indat = vic.vic_oudat;
331 vic.vic_inlen = vic.vic_oulen;
335 /* And there may be colour support, too */
336 #ifdef HAVE_COLOUR
337 if(n_COLOUR_IS_ACTIVE()){
338 struct str const *psp, *rsp;
339 struct n_colour_pen *ccp;
341 if((ccp = n_colour_pen_create(n_COLOUR_ID_MLE_PROMPT, NULL)) != NULL &&
342 (psp = n_colour_pen_to_str(ccp)) != NULL &&
343 (rsp = n_colour_reset_to_str()) != NULL){
344 store = n_string_unshift_buf(store, psp->s, psp->l);
345 /*store =*/ n_string_push_buf(store, rsp->s, rsp->l);
348 #endif /* HAVE_COLOUR */
350 jleave:
351 NYD2_LEAVE;
352 return pwidth;
356 * MLE: the Mailx-Line-Editor, our homebrew editor
357 * (inspired from NetBSDs sh(1) and dash(1)s hetio.c).
359 * Only used in interactive mode.
360 * TODO . This code should be splitted in funs/raw input/bind modules.
361 * TODO . We work with wide characters, but not for buffer takeovers and
362 * TODO cell2save()ings. This should be changed. For the former the buffer
363 * TODO thus needs to be converted to wide first, and then simply be fed in.
364 * TODO . We repaint too much. To overcome this use the same approach that my
365 * TODO terminal library uses, add a true "virtual screen line" that stores
366 * TODO the actually visible content, keep a notion of "first modified slot"
367 * TODO and "last modified slot" (including "unknown" and "any" specials),
368 * TODO update that virtual instead, then synchronize what has truly changed.
369 * TODO I.e., add an indirection layer.
370 * TODO . No BIDI support.
371 * TODO . `bind': we currently use only one lookup tree.
372 * TODO For absolute graceful behaviour in conjunction (with HAVE_TERMCAP) we
373 * TODO need a lower level tree, which possibly combines bytes into "symbolic
374 * TODO wchar_t values", into "keys" that is, as applicable, and an upper
375 * TODO layer which only works on "keys" in order to possibly combine them
376 * TODO into key sequences. We can reuse existent tree code for that.
377 * TODO We need an additional hashmap which maps termcap/terminfo names to
378 * TODO (their byte representations and) a dynamically assigned unique
379 * TODO "symbolic wchar_t value". This implies we may have incompatibilities
380 * TODO when __STDC_ISO_10646__ is not defined. Also we do need takeover-
381 * TODO bytes storage, but it can be a string_creat_auto in the line struct.
382 * TODO Until then we can run into ambiguities; in rare occasions.
384 #ifdef HAVE_MLE
385 /* To avoid memory leaks etc. with the current codebase that simply longjmp(3)s
386 * we're forced to use the very same buffer--the one that is passed through to
387 * us from the outside--to store anything we need, i.e., a "struct cell[]", and
388 * convert that on-the-fly back to the plain char* result once we're done.
389 * To simplify our live, use savestr() buffers for all other needed memory */
391 # ifdef HAVE_KEY_BINDINGS
392 /* Default *bind-timeout* key-sequence continuation timeout, in tenths of
393 * a second. Must fit in 8-bit! Update the manual upon change! */
394 # define a_TTY_BIND_TIMEOUT 2
395 # define a_TTY_BIND_TIMEOUT_MAX SI8_MAX
397 n_CTAV(a_TTY_BIND_TIMEOUT_MAX <= UI8_MAX);
399 /* We have a chicken-and-egg problem with `bind' and our termcap layer,
400 * because we may not initialize the latter automatically to allow users to
401 * specify *termcap-disable* and let it mean exactly that.
402 * On the other hand users can be expected to use `bind' in resource file(s).
403 * Therefore bindings which involve termcap/terminfo sequences, and which are
404 * defined before n_PSO_STARTED signals usability of termcap/terminfo, will be
405 * (partially) delayed until tty_init() is called.
406 * And we preallocate space for the expansion of the resolved capability */
407 # define a_TTY_BIND_CAPNAME_MAX 15
408 # define a_TTY_BIND_CAPEXP_ROUNDUP 16
410 n_CTAV(n_ISPOW2(a_TTY_BIND_CAPEXP_ROUNDUP));
411 n_CTA(a_TTY_BIND_CAPEXP_ROUNDUP <= SI8_MAX / 2, "Variable must fit in 6-bit");
412 n_CTA(a_TTY_BIND_CAPEXP_ROUNDUP >= 8, "Variable too small");
413 # endif /* HAVE_KEY_BINDINGS */
415 /* The maximum size (of a_tty_cell's) in a line */
416 # define a_TTY_LINE_MAX SI32_MAX
418 /* (Some more CTAs around) */
419 n_CTA(a_TTY_LINE_MAX <= SI32_MAX,
420 "a_TTY_LINE_MAX larger than SI32_MAX, but the MLE uses 32-bit arithmetic");
422 /* When shall the visual screen be scrolled, in % of usable screen width */
423 # define a_TTY_SCROLL_MARGIN_LEFT 15
424 # define a_TTY_SCROLL_MARGIN_RIGHT 10
426 /* fexpand() flags for expand-on-tab */
427 # define a_TTY_TAB_FEXP_FL \
428 (FEXP_NOPROTO | FEXP_FULL | FEXP_SILENT | FEXP_MULTIOK)
430 /* Columns to ripoff: outermost may not be touched, plus position indicator.
431 * Must thus be at least 1, but should be >= 1+4 to dig the position indicator
432 * that we place (if there is sufficient space) */
433 # define a_TTY_WIDTH_RIPOFF 5
435 /* The implementation of the MLE functions always exists, and is based upon
436 * the a_TTY_BIND_FUN_* constants, so most of this enum is always necessary */
437 enum a_tty_bind_flags{
438 # ifdef HAVE_KEY_BINDINGS
439 a_TTY_BIND_RESOLVE = 1u<<8, /* Term cap. yet needs to be resolved */
440 a_TTY_BIND_DEFUNCT = 1u<<9, /* Unicode/term cap. used but not avail. */
441 a_TTY__BIND_MASK = a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT,
442 /* MLE fun assigned to a one-byte-sequence: this may be used for special
443 * key-sequence bypass processing */
444 a_TTY_BIND_MLE1CNTRL = 1u<<10,
445 a_TTY_BIND_NOCOMMIT = 1u<<11, /* Expansion shall be editable */
446 # endif
448 /* MLE internal commands */
449 a_TTY_BIND_FUN_INTERNAL = 1u<<15,
450 a_TTY__BIND_FUN_SHIFT = 16u,
451 a_TTY__BIND_FUN_SHIFTMAX = 24u,
452 a_TTY__BIND_FUN_MASK = ((1u << a_TTY__BIND_FUN_SHIFTMAX) - 1) &
453 ~((1u << a_TTY__BIND_FUN_SHIFT) - 1),
454 # define a_TTY_BIND_FUN_REDUCE(X) \
455 (((ui32_t)(X) & a_TTY__BIND_FUN_MASK) >> a_TTY__BIND_FUN_SHIFT)
456 # define a_TTY_BIND_FUN_EXPAND(X) \
457 (((ui32_t)(X) & (a_TTY__BIND_FUN_MASK >> a_TTY__BIND_FUN_SHIFT)) << \
458 a_TTY__BIND_FUN_SHIFT)
459 # undef a_X
460 # define a_X(N,I)\
461 a_TTY_BIND_FUN_ ## N = a_TTY_BIND_FUN_EXPAND(I),
463 a_X(BELL, 0)
464 a_X(GO_BWD, 1) a_X(GO_FWD, 2)
465 a_X(GO_WORD_BWD, 3) a_X(GO_WORD_FWD, 4)
466 a_X(GO_HOME, 5) a_X(GO_END, 6)
467 a_X(DEL_BWD, 7) a_X(DEL_FWD, 8)
468 a_X(SNARF_WORD_BWD, 9) a_X(SNARF_WORD_FWD, 10)
469 a_X(SNARF_END, 11) a_X(SNARF_LINE, 12)
470 a_X(HIST_BWD, 13) a_X(HIST_FWD, 14)
471 a_X(HIST_SRCH_BWD, 15) a_X(HIST_SRCH_FWD, 16)
472 a_X(REPAINT, 17)
473 a_X(QUOTE_RNDTRIP, 18)
474 a_X(PROMPT_CHAR, 19)
475 a_X(COMPLETE, 20)
476 a_X(PASTE, 21)
478 a_X(CANCEL, 22)
479 a_X(RESET, 23)
480 a_X(FULLRESET, 24)
481 a_X(COMMIT, 25) /* Must be last one! */
482 # undef a_X
484 a_TTY__BIND_LAST = 1<<25
486 # ifdef HAVE_KEY_BINDINGS
487 n_CTA((ui32_t)a_TTY_BIND_RESOLVE >= (ui32_t)n__GO_INPUT_CTX_MAX1,
488 "Bit carrier lower boundary must be raised to avoid value sharing");
489 # endif
490 n_CTA(a_TTY_BIND_FUN_EXPAND(a_TTY_BIND_FUN_COMMIT) <
491 (1 << a_TTY__BIND_FUN_SHIFTMAX),
492 "Bit carrier range must be expanded to represent necessary bits");
493 n_CTA(a_TTY__BIND_LAST >= (1u << a_TTY__BIND_FUN_SHIFTMAX),
494 "Bit carrier upper boundary must be raised to avoid value sharing");
495 n_CTA(UICMP(64, a_TTY__BIND_LAST, <=, SI32_MAX),
496 "Flag bits excess storage datatype" /* And we need one bit free */);
498 enum a_tty_fun_status{
499 a_TTY_FUN_STATUS_OK, /* Worked, next character */
500 a_TTY_FUN_STATUS_COMMIT, /* Line done */
501 a_TTY_FUN_STATUS_RESTART, /* Complete restart, reset multibyte etc. */
502 a_TTY_FUN_STATUS_END /* End, return EOF */
505 enum a_tty_visual_flags{
506 a_TTY_VF_NONE,
507 a_TTY_VF_MOD_CURSOR = 1u<<0, /* Cursor moved */
508 a_TTY_VF_MOD_CONTENT = 1u<<1, /* Content modified */
509 a_TTY_VF_MOD_DIRTY = 1u<<2, /* Needs complete repaint */
510 a_TTY_VF_MOD_SINGLE = 1u<<3, /* TODO Drop when indirection as above comes */
511 a_TTY_VF_REFRESH = a_TTY_VF_MOD_DIRTY | a_TTY_VF_MOD_CURSOR |
512 a_TTY_VF_MOD_CONTENT | a_TTY_VF_MOD_SINGLE,
513 a_TTY_VF_BELL = 1u<<8, /* Ring the bell */
514 a_TTY_VF_SYNC = 1u<<9, /* Flush/Sync I/O channel */
516 a_TTY_VF_ALL_MASK = a_TTY_VF_REFRESH | a_TTY_VF_BELL | a_TTY_VF_SYNC,
517 a_TTY__VF_LAST = a_TTY_VF_SYNC
520 # ifdef HAVE_KEY_BINDINGS
521 struct a_tty_bind_ctx{
522 struct a_tty_bind_ctx *tbc_next;
523 char *tbc_seq; /* quence as given (poss. re-quoted), in .tb__buf */
524 char *tbc_exp; /* ansion, in .tb__buf */
525 /* The .tbc_seq'uence with any terminal capabilities resolved; in fact an
526 * array of structures, the first entry of which is {si32_t buf_len_iscap;}
527 * where the signed bit indicates whether the buffer is a resolved terminal
528 * capability instead of a (possibly multibyte) character. In .tbc__buf */
529 char *tbc_cnv;
530 ui32_t tbc_seq_len;
531 ui32_t tbc_exp_len;
532 ui32_t tbc_cnv_len;
533 ui32_t tbc_flags;
534 char tbc__buf[n_VFIELD_SIZE(0)];
537 struct a_tty_bind_ctx_map{
538 enum n_go_input_flags tbcm_ctx;
539 char const tbcm_name[12]; /* Name of `bind' context */
541 # endif /* HAVE_KEY_BINDINGS */
543 struct a_tty_bind_builtin_tuple{
544 bool_t tbbt_iskey; /* Whether this is a control key; else termcap query */
545 char tbbt_ckey; /* Control code */
546 ui16_t tbbt_query; /* enum n_termcap_query (instead) */
547 char tbbt_exp[12]; /* String or [0]=NUL/[1]=BIND_FUN_REDUCE() */
549 n_CTA(n__TERMCAP_QUERY_MAX1 <= UI16_MAX,
550 "Enumeration cannot be stored in datatype");
552 # ifdef HAVE_KEY_BINDINGS
553 struct a_tty_bind_parse_ctx{
554 char const *tbpc_cmd; /* Command which parses */
555 char const *tbpc_in_seq; /* In: key sequence */
556 struct str tbpc_exp; /* In/Out: expansion (or NULL) */
557 struct a_tty_bind_ctx *tbpc_tbcp; /* Out: if yet existent */
558 struct a_tty_bind_ctx *tbpc_ltbcp; /* Out: the one before .tbpc_tbcp */
559 char *tbpc_seq; /* Out: normalized sequence */
560 char *tbpc_cnv; /* Out: sequence when read(2)ing it */
561 ui32_t tbpc_seq_len;
562 ui32_t tbpc_cnv_len;
563 ui32_t tbpc_cnv_align_mask; /* For creating a_tty_bind_ctx.tbc_cnv */
564 ui32_t tbpc_flags; /* n_go_input_flags | a_tty_bind_flags */
567 /* Input character tree */
568 struct a_tty_bind_tree{
569 struct a_tty_bind_tree *tbt_sibling; /* s at same level */
570 struct a_tty_bind_tree *tbt_childs; /* Sequence continues.. here */
571 struct a_tty_bind_tree *tbt_parent;
572 struct a_tty_bind_ctx *tbt_bind; /* NULL for intermediates */
573 wchar_t tbt_char; /* acter this level represents */
574 bool_t tbt_isseq; /* Belongs to multibyte sequence */
575 bool_t tbt_isseq_trail; /* ..is trailing byte of it */
576 ui8_t tbt__dummy[2];
578 # endif /* HAVE_KEY_BINDINGS */
580 struct a_tty_cell{
581 wchar_t tc_wc;
582 ui16_t tc_count; /* ..of bytes */
583 ui8_t tc_width; /* Visual width; TAB==UI8_MAX! */
584 bool_t tc_novis; /* Don't display visually as such (control character) */
585 char tc_cbuf[MB_LEN_MAX * 2]; /* .. plus reset shift sequence */
588 struct a_tty_global{
589 struct a_tty_line *tg_line; /* To be able to access it from signal hdl */
590 # ifdef HAVE_HISTORY
591 struct a_tty_hist *tg_hist;
592 struct a_tty_hist *tg_hist_tail;
593 size_t tg_hist_size;
594 size_t tg_hist_size_max;
595 # endif
596 # ifdef HAVE_KEY_BINDINGS
597 ui32_t tg_bind_cnt; /* Overall number of bindings */
598 bool_t tg_bind_isdirty;
599 bool_t tg_bind_isbuild;
600 # define a_TTY_SHCUT_MAX (3 +1) /* Note: update manual on change! */
601 ui8_t tg_bind__dummy[2];
602 char tg_bind_shcut_cancel[n__GO_INPUT_CTX_MAX1][a_TTY_SHCUT_MAX];
603 char tg_bind_shcut_prompt_char[n__GO_INPUT_CTX_MAX1][a_TTY_SHCUT_MAX];
604 struct a_tty_bind_ctx *tg_bind[n__GO_INPUT_CTX_MAX1];
605 struct a_tty_bind_tree *tg_bind_tree[n__GO_INPUT_CTX_MAX1][HSHSIZE];
606 # endif
607 struct termios tg_tios_old;
608 struct termios tg_tios_new;
610 # ifdef HAVE_KEY_BINDINGS
611 n_CTA(n__GO_INPUT_CTX_MAX1 == 3 && a_TTY_SHCUT_MAX == 4 &&
612 n_SIZEOF_FIELD(struct a_tty_global, tg_bind__dummy) == 2,
613 "Value results in array sizes that results in bad structure layout");
614 n_CTA(a_TTY_SHCUT_MAX > 1,
615 "Users need at least one shortcut, plus NUL terminator");
616 # endif
618 # ifdef HAVE_HISTORY
619 struct a_tty_hist{
620 struct a_tty_hist *th_older;
621 struct a_tty_hist *th_younger;
622 ui32_t th_isgabby : 1;
623 ui32_t th_len : 31;
624 char th_dat[n_VFIELD_SIZE(sizeof(ui32_t))];
626 # endif
628 struct a_tty_line{
629 /* Caller pointers */
630 char **tl_x_buf;
631 size_t *tl_x_bufsize;
632 /* Input processing */
633 # ifdef HAVE_KEY_BINDINGS
634 wchar_t tl_bind_takeover; /* Leftover byte to consume next */
635 ui8_t tl_bind_timeout; /* In-seq. inter-byte-timer, in 1/10th secs */
636 ui8_t tl__bind_dummy[3];
637 char (*tl_bind_shcut_cancel)[a_TTY_SHCUT_MAX]; /* Special _CANCEL control */
638 char (*tl_bind_shcut_prompt_char)[a_TTY_SHCUT_MAX]; /* ..for _PROMPT_CHAR */
639 struct a_tty_bind_tree *(*tl_bind_tree_hmap)[HSHSIZE]; /* Bind lookup tree */
640 struct a_tty_bind_tree *tl_bind_tree;
641 # endif
642 /* Line data / content handling */
643 ui32_t tl_count; /* ..of a_tty_cell's (<= a_TTY_LINE_MAX) */
644 ui32_t tl_cursor; /* Current a_tty_cell insertion point */
645 union{
646 char *cbuf; /* *.tl_x_buf */
647 struct a_tty_cell *cells;
648 } tl_line;
649 struct str tl_defc; /* Current default content */
650 size_t tl_defc_cursor_byte; /* Desired position of cursor after takeover */
651 struct str tl_savec; /* Saved default content */
652 struct str tl_pastebuf; /* Last snarfed data */
653 # ifdef HAVE_HISTORY
654 struct a_tty_hist *tl_hist; /* History cursor */
655 # endif
656 ui32_t tl_count_max; /* ..before buffer needs to grow */
657 /* Visual data representation handling */
658 ui32_t tl_vi_flags; /* enum a_tty_visual_flags */
659 ui32_t tl_lst_count; /* .tl_count after last sync */
660 ui32_t tl_lst_cursor; /* .tl_cursor after last sync */
661 /* TODO Add another indirection layer by adding a tl_phy_line of
662 * TODO a_tty_cell objects, incorporate changes in visual layer,
663 * TODO then check what _really_ has changed, sync those changes only */
664 struct a_tty_cell const *tl_phy_start; /* First visible cell, left border */
665 ui32_t tl_phy_cursor; /* Physical cursor position */
666 bool_t tl_quote_rndtrip; /* For _kht() expansion */
667 ui8_t tl__dummy2[3];
668 ui32_t tl_prompt_length; /* Preclassified (TODO needed as a_tty_cell) */
669 ui32_t tl_prompt_width;
670 char const *tl_prompt; /* Preformatted prompt (including colours) */
671 /* .tl_pos_buf is a hack */
672 # ifdef HAVE_COLOUR
673 char *tl_pos_buf; /* mle-position colour-on, [4], reset seq. */
674 char *tl_pos; /* Address of the [4] */
675 # endif
678 # ifdef HAVE_KEY_BINDINGS
679 /* C99: use [INDEX]={} */
680 n_CTAV(n_GO_INPUT_CTX_BASE == 0);
681 n_CTAV(n_GO_INPUT_CTX_DEFAULT == 1);
682 n_CTAV(n_GO_INPUT_CTX_COMPOSE == 2);
683 static struct a_tty_bind_ctx_map const
684 a_tty_bind_ctx_maps[n__GO_INPUT_CTX_MAX1] = {
685 {n_GO_INPUT_CTX_BASE, "base"},
686 {n_GO_INPUT_CTX_DEFAULT, "default"},
687 {n_GO_INPUT_CTX_COMPOSE, "compose"}
690 /* Special functions which our MLE provides internally.
691 * Update the manual upon change! */
692 static char const a_tty_bind_fun_names[][24] = {
693 # undef a_X
694 # define a_X(I,N) \
695 n_FIELD_INITI(a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## I)) "mle-" N "\0",
697 a_X(BELL, "bell")
698 a_X(GO_BWD, "go-bwd") a_X(GO_FWD, "go-fwd")
699 a_X(GO_WORD_BWD, "go-word-bwd") a_X(GO_WORD_FWD, "go-word-fwd")
700 a_X(GO_HOME, "go-home") a_X(GO_END, "go-end")
701 a_X(DEL_BWD, "del-bwd") a_X(DEL_FWD, "del-fwd")
702 a_X(SNARF_WORD_BWD, "snarf-word-bwd") a_X(SNARF_WORD_FWD, "snarf-word-fwd")
703 a_X(SNARF_END, "snarf-end") a_X(SNARF_LINE, "snarf-line")
704 a_X(HIST_BWD, "hist-bwd") a_X(HIST_FWD, "hist-fwd")
705 a_X(HIST_SRCH_BWD, "hist-srch-bwd") a_X(HIST_SRCH_FWD, "hist-srch-fwd")
706 a_X(REPAINT, "repaint")
707 a_X(QUOTE_RNDTRIP, "quote-rndtrip")
708 a_X(PROMPT_CHAR, "prompt-char")
709 a_X(COMPLETE, "complete")
710 a_X(PASTE, "paste")
712 a_X(CANCEL, "cancel")
713 a_X(RESET, "reset")
714 a_X(FULLRESET, "fullreset")
715 a_X(COMMIT, "commit")
717 # undef a_X
719 # endif /* HAVE_KEY_BINDINGS */
721 /* The default key bindings (unless disallowed). Update manual upon change!
722 * A logical subset of this table is also used if !HAVE_KEY_BINDINGS (more
723 * expensive than a switch() on control codes directly, but less redundant).
724 * The table for the "base" context */
725 static struct a_tty_bind_builtin_tuple const a_tty_bind_base_tuples[] = {
726 # undef a_X
727 # define a_X(K,S) \
728 {TRU1, K, 0, {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
730 a_X('A', GO_HOME)
731 a_X('B', GO_BWD)
732 /* C: SIGINT */
733 a_X('D', DEL_FWD)
734 a_X('E', GO_END)
735 a_X('F', GO_FWD)
736 a_X('G', RESET)
737 a_X('H', DEL_BWD)
738 a_X('I', COMPLETE)
739 a_X('J', COMMIT)
740 a_X('K', SNARF_END)
741 a_X('L', REPAINT)
742 /* M: same as J */
743 a_X('N', HIST_FWD)
744 /* O: below */
745 a_X('P', HIST_BWD)
746 a_X('Q', QUOTE_RNDTRIP)
747 a_X('R', HIST_SRCH_BWD)
748 a_X('S', HIST_SRCH_FWD)
749 a_X('T', PASTE)
750 a_X('U', SNARF_LINE)
751 a_X('V', PROMPT_CHAR)
752 a_X('W', SNARF_WORD_BWD)
753 a_X('X', GO_WORD_FWD)
754 a_X('Y', GO_WORD_BWD)
755 /* Z: SIGTSTP */
757 a_X('[', CANCEL)
758 /* \: below */
759 /* ]: below */
760 /* ^: below */
761 a_X('_', SNARF_WORD_FWD)
763 a_X('?', DEL_BWD)
765 # undef a_X
766 # define a_X(K,S) {TRU1, K, 0, {S}},
768 /* The remains only if we have `bind' functionality available */
769 # ifdef HAVE_KEY_BINDINGS
770 # undef a_X
771 # define a_X(Q,S) \
772 {FAL0, '\0', n_TERMCAP_QUERY_ ## Q,\
773 {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
775 a_X(key_backspace, DEL_BWD) a_X(key_dc, DEL_FWD)
776 a_X(key_eol, SNARF_END)
777 a_X(key_home, GO_HOME) a_X(key_end, GO_END)
778 a_X(key_left, GO_BWD) a_X(key_right, GO_FWD)
779 a_X(key_sleft, GO_HOME) a_X(key_sright, GO_END)
780 a_X(key_up, HIST_BWD) a_X(key_down, HIST_FWD)
781 # endif /* HAVE_KEY_BINDINGS */
784 /* The table for the "default" context */
785 static struct a_tty_bind_builtin_tuple const a_tty_bind_default_tuples[] = {
786 # undef a_X
787 # define a_X(K,S) \
788 {TRU1, K, 0, {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
790 # undef a_X
791 # define a_X(K,S) {TRU1, K, 0, {S}},
793 a_X('O', "dt")
795 a_X('\\', "z+")
796 a_X(']', "z$")
797 a_X('^', "z0")
799 /* The remains only if we have `bind' functionality available */
800 # ifdef HAVE_KEY_BINDINGS
801 # undef a_X
802 # define a_X(Q,S) {FAL0, '\0', n_TERMCAP_QUERY_ ## Q, {S}},
804 a_X(key_shome, "z0") a_X(key_send, "z$")
805 a_X(xkey_sup, "z0") a_X(xkey_sdown, "z$")
806 a_X(key_ppage, "z-") a_X(key_npage, "z+")
807 a_X(xkey_cup, "dotmove-") a_X(xkey_cdown, "dotmove+")
808 # endif /* HAVE_KEY_BINDINGS */
810 # undef a_X
812 static struct a_tty_global a_tty;
814 /* Change from canonical to raw, non-canonical mode, and way back */
815 static void a_tty_term_mode(bool_t raw);
817 /* Initialize .tg_hist_size_max and return desired history file, or NULL */
818 # ifdef HAVE_HISTORY
819 static char const *a_tty_hist_query_config(void);
820 # endif
822 /* Adjust an active raw mode to use / not use a timeout */
823 # ifdef HAVE_KEY_BINDINGS
824 static void a_tty_term_rawmode_timeout(struct a_tty_line *tlp, bool_t enable);
825 # endif
827 /* 0-X (2), UI8_MAX == \t / TAB */
828 static ui8_t a_tty_wcwidth(wchar_t wc);
830 /* Memory / cell / word generics */
831 static void a_tty_check_grow(struct a_tty_line *tlp, ui32_t no
832 n_MEMORY_DEBUG_ARGS);
833 static ssize_t a_tty_cell2dat(struct a_tty_line *tlp);
834 static void a_tty_cell2save(struct a_tty_line *tlp);
836 /* Save away data bytes of given range (max = non-inclusive) */
837 static void a_tty_copy2paste(struct a_tty_line *tlp, struct a_tty_cell *tcpmin,
838 struct a_tty_cell *tcpmax);
840 /* Ask user for hexadecimal number, interpret as UTF-32 */
841 static wchar_t a_tty_vinuni(struct a_tty_line *tlp);
843 /* Visual screen synchronization */
844 static bool_t a_tty_vi_refresh(struct a_tty_line *tlp);
846 static bool_t a_tty_vi__paint(struct a_tty_line *tlp);
848 /* Search for word boundary, starting at tl_cursor, in "dir"ection (<> 0).
849 * Return <0 when moving is impossible (backward direction but in position 0,
850 * forward direction but in outermost column), and relative distance to
851 * tl_cursor otherwise */
852 static si32_t a_tty_wboundary(struct a_tty_line *tlp, si32_t dir);
854 /* Most function implementations */
855 static void a_tty_khome(struct a_tty_line *tlp, bool_t dobell);
856 static void a_tty_kend(struct a_tty_line *tlp);
857 static void a_tty_kbs(struct a_tty_line *tlp);
858 static void a_tty_ksnarf(struct a_tty_line *tlp, bool_t cplline, bool_t dobell);
859 static si32_t a_tty_kdel(struct a_tty_line *tlp);
860 static void a_tty_kleft(struct a_tty_line *tlp);
861 static void a_tty_kright(struct a_tty_line *tlp);
862 static void a_tty_ksnarfw(struct a_tty_line *tlp, bool_t fwd);
863 static void a_tty_kgow(struct a_tty_line *tlp, si32_t dir);
864 static bool_t a_tty_kother(struct a_tty_line *tlp, wchar_t wc);
865 static ui32_t a_tty_kht(struct a_tty_line *tlp);
867 # ifdef HAVE_HISTORY
868 /* Return UI32_MAX on "exhaustion" */
869 static ui32_t a_tty_khist(struct a_tty_line *tlp, bool_t fwd);
870 static ui32_t a_tty_khist_search(struct a_tty_line *tlp, bool_t fwd);
872 static ui32_t a_tty__khist_shared(struct a_tty_line *tlp,
873 struct a_tty_hist *thp);
874 # endif
876 /* Handle a function */
877 static enum a_tty_fun_status a_tty_fun(struct a_tty_line *tlp,
878 enum a_tty_bind_flags tbf, size_t *len);
880 /* Readline core */
881 static ssize_t a_tty_readline(struct a_tty_line *tlp, size_t len,
882 bool_t *histok_or_null n_MEMORY_DEBUG_ARGS);
884 # ifdef HAVE_KEY_BINDINGS
885 /* Find context or -1 */
886 static enum n_go_input_flags a_tty_bind_ctx_find(char const *name);
888 /* Create (or replace, if allowed) a binding */
889 static bool_t a_tty_bind_create(struct a_tty_bind_parse_ctx *tbpcp,
890 bool_t replace);
892 /* Shared implementation to parse `bind' and `unbind' "key-sequence" and
893 * "expansion" command line arguments into something that we can work with */
894 static bool_t a_tty_bind_parse(bool_t isbindcmd,
895 struct a_tty_bind_parse_ctx *tbpcp);
897 /* Lazy resolve a termcap(5)/terminfo(5) (or *termcap*!) capability */
898 static void a_tty_bind_resolve(struct a_tty_bind_ctx *tbcp);
900 /* Delete an existing binding */
901 static void a_tty_bind_del(struct a_tty_bind_parse_ctx *tbpcp);
903 /* Life cycle of all input node trees */
904 static void a_tty_bind_tree_build(void);
905 static void a_tty_bind_tree_teardown(void);
907 static void a_tty__bind_tree_add(ui32_t hmap_idx,
908 struct a_tty_bind_tree *store[HSHSIZE],
909 struct a_tty_bind_ctx *tbcp);
910 static struct a_tty_bind_tree *a_tty__bind_tree_add_wc(
911 struct a_tty_bind_tree **treep, struct a_tty_bind_tree *parentp,
912 wchar_t wc, bool_t isseq);
913 static void a_tty__bind_tree_free(struct a_tty_bind_tree *tbtp);
914 # endif /* HAVE_KEY_BINDINGS */
916 static void
917 a_tty_term_mode(bool_t raw){
918 struct termios *tiosp;
919 NYD2_ENTER;
921 tiosp = &a_tty.tg_tios_old;
922 if(!raw)
923 goto jleave;
925 /* Always requery the attributes, in case we've been moved from background
926 * to foreground or however else in between sessions */
927 /* XXX Always enforce ECHO and ICANON in the OLD attributes - do so as long
928 * XXX as we don't properly deal with TTIN and TTOU etc. */
929 tcgetattr(STDIN_FILENO, tiosp); /* TODO v15: use _only_ n_tty_fp! */
930 tiosp->c_lflag |= ECHO | ICANON;
932 memcpy(&a_tty.tg_tios_new, tiosp, sizeof *tiosp);
933 tiosp = &a_tty.tg_tios_new;
934 tiosp->c_cc[VMIN] = 1;
935 tiosp->c_cc[VTIME] = 0;
936 /* Enable ^\, ^Q and ^S to be used for key bindings */
937 tiosp->c_cc[VQUIT] = tiosp->c_cc[VSTART] = tiosp->c_cc[VSTOP] = '\0';
938 tiosp->c_iflag &= ~(ISTRIP | IGNCR);
939 tiosp->c_lflag &= ~(ECHO /*| ECHOE | ECHONL */| ICANON | IEXTEN);
940 jleave:
941 tcsetattr(STDIN_FILENO, TCSADRAIN, tiosp);
942 NYD2_LEAVE;
945 # ifdef HAVE_HISTORY
946 static char const *
947 a_tty_hist_query_config(void){
948 char const *rv, *cp;
949 NYD2_ENTER;
951 if((cp = ok_vlook(NAIL_HISTSIZE)) != NULL)
952 n_OBSOLETE(_("please use *history-size* instead of *NAIL_HISTSIZE*"));
953 if((rv = ok_vlook(history_size)) == NULL)
954 rv = cp;
955 if(rv == NULL)
956 a_tty.tg_hist_size_max = UIZ_MAX;
957 else
958 (void)n_idec_uiz_cp(&a_tty.tg_hist_size_max, rv, 10, NULL);
960 if((cp = ok_vlook(NAIL_HISTFILE)) != NULL)
961 n_OBSOLETE(_("please use *history-file* instead of *NAIL_HISTFILE*"));
962 if((rv = ok_vlook(history_file)) == NULL)
963 rv = cp;
964 if(rv != NULL)
965 rv = fexpand(rv, FEXP_LOCAL | FEXP_NSHELL);
966 NYD2_LEAVE;
967 return rv;
969 # endif /* HAVE_HISTORY */
971 # ifdef HAVE_KEY_BINDINGS
972 static void
973 a_tty_term_rawmode_timeout(struct a_tty_line *tlp, bool_t enable){
974 NYD2_ENTER;
975 if(enable){
976 ui8_t bt;
978 a_tty.tg_tios_new.c_cc[VMIN] = 0;
979 if((bt = tlp->tl_bind_timeout) == 0)
980 bt = a_TTY_BIND_TIMEOUT;
981 a_tty.tg_tios_new.c_cc[VTIME] = bt;
982 }else{
983 a_tty.tg_tios_new.c_cc[VMIN] = 1;
984 a_tty.tg_tios_new.c_cc[VTIME] = 0;
986 tcsetattr(STDIN_FILENO, TCSANOW, &a_tty.tg_tios_new);
987 NYD2_LEAVE;
989 # endif /* HAVE_KEY_BINDINGS */
991 static ui8_t
992 a_tty_wcwidth(wchar_t wc){
993 ui8_t rv;
994 NYD2_ENTER;
996 /* Special case the reverse solidus at first */
997 if(wc == '\t')
998 rv = UI8_MAX;
999 else{
1000 int i;
1002 # ifdef HAVE_WCWIDTH
1003 rv = ((i = wcwidth(wc)) > 0) ? (ui8_t)i : 0;
1004 # else
1005 rv = iswprint(wc) ? 1 + (wc >= 0x1100u) : 0; /* TODO use S-CText */
1006 # endif
1008 NYD2_LEAVE;
1009 return rv;
1012 static void
1013 a_tty_check_grow(struct a_tty_line *tlp, ui32_t no n_MEMORY_DEBUG_ARGS){
1014 ui32_t cmax;
1015 NYD2_ENTER;
1017 if(n_UNLIKELY((cmax = tlp->tl_count + no) > tlp->tl_count_max)){
1018 size_t i;
1020 i = cmax * sizeof(struct a_tty_cell) + 2 * sizeof(struct a_tty_cell);
1021 if(n_LIKELY(i >= *tlp->tl_x_bufsize)){
1022 hold_all_sigs(); /* XXX v15 drop */
1023 i <<= 1;
1024 tlp->tl_line.cbuf =
1025 *tlp->tl_x_buf = (n_realloc)(*tlp->tl_x_buf, i
1026 n_MEMORY_DEBUG_ARGSCALL);
1027 rele_all_sigs(); /* XXX v15 drop */
1029 tlp->tl_count_max = cmax;
1030 *tlp->tl_x_bufsize = i;
1032 NYD2_LEAVE;
1035 static ssize_t
1036 a_tty_cell2dat(struct a_tty_line *tlp){
1037 size_t len, i;
1038 NYD2_ENTER;
1040 len = 0;
1042 if(n_LIKELY((i = tlp->tl_count) > 0)){
1043 struct a_tty_cell const *tcap;
1045 tcap = tlp->tl_line.cells;
1047 memcpy(tlp->tl_line.cbuf + len, tcap->tc_cbuf, tcap->tc_count);
1048 len += tcap->tc_count;
1049 }while(++tcap, --i > 0);
1052 tlp->tl_line.cbuf[len] = '\0';
1053 NYD2_LEAVE;
1054 return (ssize_t)len;
1057 static void
1058 a_tty_cell2save(struct a_tty_line *tlp){
1059 size_t len, i;
1060 struct a_tty_cell *tcap;
1061 NYD2_ENTER;
1063 tlp->tl_savec.s = NULL;
1064 tlp->tl_savec.l = 0;
1066 if(n_UNLIKELY(tlp->tl_count == 0))
1067 goto jleave;
1069 for(tcap = tlp->tl_line.cells, len = 0, i = tlp->tl_count; i > 0;
1070 ++tcap, --i)
1071 len += tcap->tc_count;
1073 tlp->tl_savec.s = salloc((tlp->tl_savec.l = len) +1);
1075 for(tcap = tlp->tl_line.cells, len = 0, i = tlp->tl_count; i > 0;
1076 ++tcap, --i){
1077 memcpy(tlp->tl_savec.s + len, tcap->tc_cbuf, tcap->tc_count);
1078 len += tcap->tc_count;
1080 tlp->tl_savec.s[len] = '\0';
1081 jleave:
1082 NYD2_LEAVE;
1085 static void
1086 a_tty_copy2paste(struct a_tty_line *tlp, struct a_tty_cell *tcpmin,
1087 struct a_tty_cell *tcpmax){
1088 char *cp;
1089 struct a_tty_cell *tcp;
1090 size_t l;
1091 NYD2_ENTER;
1093 l = 0;
1094 for(tcp = tcpmin; tcp < tcpmax; ++tcp)
1095 l += tcp->tc_count;
1097 tlp->tl_pastebuf.s = cp = salloc((tlp->tl_pastebuf.l = l) +1);
1099 for(tcp = tcpmin; tcp < tcpmax; cp += l, ++tcp)
1100 memcpy(cp, tcp->tc_cbuf, l = tcp->tc_count);
1101 *cp = '\0';
1102 NYD2_LEAVE;
1105 static wchar_t
1106 a_tty_vinuni(struct a_tty_line *tlp){
1107 char buf[16];
1108 uiz_t i;
1109 wchar_t wc;
1110 NYD2_ENTER;
1112 wc = '\0';
1114 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr) ||
1115 !n_termcap_cmd(n_TERMCAP_CMD_ce, 0, -1))
1116 goto jleave;
1118 /* C99 */{
1119 struct str const *cpre, *csuf;
1121 cpre = csuf = NULL;
1122 #ifdef HAVE_COLOUR
1123 if(n_COLOUR_IS_ACTIVE()){
1124 struct n_colour_pen *cpen;
1126 cpen = n_colour_pen_create(n_COLOUR_ID_MLE_PROMPT, NULL);
1127 if((cpre = n_colour_pen_to_str(cpen)) != NULL)
1128 csuf = n_colour_reset_to_str();
1130 #endif
1131 fprintf(n_tty_fp, _("%sPlease enter Unicode code point:%s "),
1132 (cpre != NULL ? cpre->s : n_empty),
1133 (csuf != NULL ? csuf->s : n_empty));
1135 fflush(n_tty_fp);
1137 buf[sizeof(buf) -1] = '\0';
1138 for(i = 0;;){
1139 if(read(STDIN_FILENO, &buf[i], 1) != 1){
1140 if(n_err_no == n_ERR_INTR) /* xxx #if !SA_RESTART ? */
1141 continue;
1142 goto jleave;
1144 if(buf[i] == '\n')
1145 break;
1146 if(!hexchar(buf[i])){
1147 char const emsg[] = "[0-9a-fA-F]";
1149 n_LCTA(sizeof emsg <= sizeof(buf), "Preallocated buffer too small");
1150 memcpy(buf, emsg, sizeof emsg);
1151 goto jerr;
1154 putc(buf[i], n_tty_fp);
1155 fflush(n_tty_fp);
1156 if(++i == sizeof buf)
1157 goto jerr;
1159 buf[i] = '\0';
1161 if((n_idec_uiz_cp(&i, buf, 16, NULL
1162 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
1163 ) != n_IDEC_STATE_CONSUMED || i > 0x10FFFF/* XXX magic; CText */){
1164 jerr:
1165 n_err(_("\nInvalid input: %s\n"), buf);
1166 goto jleave;
1169 wc = (wchar_t)i;
1170 jleave:
1171 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY | (wc == '\0' ? a_TTY_VF_BELL : 0);
1172 NYD2_LEAVE;
1173 return wc;
1176 static bool_t
1177 a_tty_vi_refresh(struct a_tty_line *tlp){
1178 bool_t rv;
1179 NYD2_ENTER;
1181 if(tlp->tl_vi_flags & a_TTY_VF_BELL){
1182 tlp->tl_vi_flags |= a_TTY_VF_SYNC;
1183 if(putc('\a', n_tty_fp) == EOF)
1184 goto jerr;
1187 if(tlp->tl_vi_flags & a_TTY_VF_REFRESH){
1188 /* kht may want to restore a cursor position after inserting some
1189 * data somewhere */
1190 if(tlp->tl_defc_cursor_byte > 0){
1191 size_t i, j;
1192 ssize_t k;
1194 a_tty_khome(tlp, FAL0);
1196 i = tlp->tl_defc_cursor_byte;
1197 tlp->tl_defc_cursor_byte = 0;
1198 for(j = 0; tlp->tl_cursor < tlp->tl_count; ++j){
1199 a_tty_kright(tlp);
1200 if((k = tlp->tl_line.cells[j].tc_count) > i)
1201 break;
1202 i -= k;
1206 if(!a_tty_vi__paint(tlp))
1207 goto jerr;
1210 if(tlp->tl_vi_flags & a_TTY_VF_SYNC){
1211 tlp->tl_vi_flags &= ~a_TTY_VF_SYNC;
1212 if(fflush(n_tty_fp))
1213 goto jerr;
1216 rv = TRU1;
1217 jleave:
1218 tlp->tl_vi_flags &= ~a_TTY_VF_ALL_MASK;
1219 NYD2_LEAVE;
1220 return rv;
1222 jerr:
1223 clearerr(n_tty_fp); /* xxx I/O layer rewrite */
1224 n_err(_("Visual refresh failed! Is $TERM set correctly?\n"
1225 " Setting *line-editor-disable* to get us through!\n"));
1226 ok_bset(line_editor_disable);
1227 rv = FAL0;
1228 goto jleave;
1231 static bool_t
1232 a_tty_vi__paint(struct a_tty_line *tlp){
1233 enum{
1234 a_TRUE_RV = a_TTY__VF_LAST<<1, /* Return value bit */
1235 a_HAVE_PROMPT = a_TTY__VF_LAST<<2, /* Have a prompt */
1236 a_SHOW_PROMPT = a_TTY__VF_LAST<<3, /* Shall print the prompt */
1237 a_MOVE_CURSOR = a_TTY__VF_LAST<<4, /* Move visual cursor for user! */
1238 a_LEFT_MIN = a_TTY__VF_LAST<<5, /* On left boundary */
1239 a_RIGHT_MAX = a_TTY__VF_LAST<<6,
1240 a_HAVE_POSITION = a_TTY__VF_LAST<<7, /* Print the position indicator */
1242 /* We carry some flags over invocations (not worth a specific field) */
1243 a_VISIBLE_PROMPT = a_TTY__VF_LAST<<8, /* The prompt is on the screen */
1244 a_PERSIST_MASK = a_VISIBLE_PROMPT,
1245 a__LAST = a_PERSIST_MASK
1248 ui32_t f, w, phy_wid_base, phy_wid, phy_base, phy_cur, cnt,
1249 DBG(lstcur COMMA) cur,
1250 vi_left, /*vi_right,*/ phy_nxtcur;
1251 struct a_tty_cell const *tccp, *tcp_left, *tcp_right, *tcxp;
1252 NYD2_ENTER;
1253 n_LCTA(UICMP(64, a__LAST, <, UI32_MAX), "Flag bits excess storage datatype");
1255 f = tlp->tl_vi_flags;
1256 tlp->tl_vi_flags = (f & ~(a_TTY_VF_REFRESH | a_PERSIST_MASK)) |
1257 a_TTY_VF_SYNC;
1258 f |= a_TRUE_RV;
1259 if((w = tlp->tl_prompt_width) > 0)
1260 f |= a_HAVE_PROMPT;
1261 f |= a_HAVE_POSITION;
1263 /* XXX We don't have a OnTerminalResize event (see main.c) yet, so we need
1264 * XXX to reevaluate our circumstances over and over again */
1265 /* Don't display prompt or position indicator on very small screens */
1266 if((phy_wid_base = (ui32_t)n_scrnwidth) <= a_TTY_WIDTH_RIPOFF)
1267 f &= ~(a_HAVE_PROMPT | a_HAVE_POSITION);
1268 else{
1269 phy_wid_base -= a_TTY_WIDTH_RIPOFF;
1271 /* Disable the prompt if the screen is too small; due to lack of some
1272 * indicator simply add a second ripoff */
1273 if((f & a_HAVE_PROMPT) && w + a_TTY_WIDTH_RIPOFF >= phy_wid_base)
1274 f &= ~a_HAVE_PROMPT;
1277 phy_wid = phy_wid_base;
1278 phy_base = 0;
1279 phy_cur = tlp->tl_phy_cursor;
1280 cnt = tlp->tl_count;
1281 DBG( lstcur = tlp->tl_lst_cursor; )
1283 /* XXX Assume dirty screen if shrunk */
1284 if(cnt < tlp->tl_lst_count)
1285 f |= a_TTY_VF_MOD_DIRTY;
1287 /* TODO Without HAVE_TERMCAP, it would likely be much cheaper to simply
1288 * TODO always "cr + paint + ce + ch", since ce is simulated via spaces.. */
1290 /* Quickshot: if the line is empty, possibly print prompt and out */
1291 if(cnt == 0){
1292 /* In that special case dirty anything if it seems better */
1293 if((f & a_TTY_VF_MOD_CONTENT) || tlp->tl_lst_count > 0)
1294 f |= a_TTY_VF_MOD_DIRTY;
1296 if((f & a_TTY_VF_MOD_DIRTY) && phy_cur != 0){
1297 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
1298 goto jerr;
1299 phy_cur = 0;
1302 if((f & (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)) ==
1303 (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)){
1304 if(fputs(tlp->tl_prompt, n_tty_fp) == EOF)
1305 goto jerr;
1306 phy_cur = tlp->tl_prompt_width + 1;
1309 /* May need to clear former line content */
1310 if((f & a_TTY_VF_MOD_DIRTY) &&
1311 !n_termcap_cmd(n_TERMCAP_CMD_ce, phy_cur, -1))
1312 goto jerr;
1314 tlp->tl_phy_start = tlp->tl_line.cells;
1315 goto jleave;
1318 /* Try to get an idea of the visual window */
1320 /* Find the left visual boundary */
1321 phy_wid = (phy_wid >> 1) + (phy_wid >> 2);
1322 if((cur = tlp->tl_cursor) == cnt)
1323 --cur;
1325 w = (tcp_left = tccp = tlp->tl_line.cells + cur)->tc_width;
1326 if(w == UI8_MAX) /* TODO yet TAB == SPC */
1327 w = 1;
1328 while(tcp_left > tlp->tl_line.cells){
1329 ui16_t cw = tcp_left[-1].tc_width;
1331 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1332 cw = 1;
1333 if(w + cw >= phy_wid)
1334 break;
1335 w += cw;
1336 --tcp_left;
1338 vi_left = w;
1340 /* If the left hand side of our visual viewpoint consumes less than half
1341 * of the screen width, show the prompt */
1342 if(tcp_left == tlp->tl_line.cells)
1343 f |= a_LEFT_MIN;
1345 if((f & (a_LEFT_MIN | a_HAVE_PROMPT)) == (a_LEFT_MIN | a_HAVE_PROMPT) &&
1346 w + tlp->tl_prompt_width < phy_wid){
1347 phy_base = tlp->tl_prompt_width;
1348 f |= a_SHOW_PROMPT;
1351 /* Then search for right boundary. We always leave the rightmost column
1352 * empty because some terminals [cw]ould wrap the line if we write into
1353 * that. XXX terminfo(5)/termcap(5) have the semi_auto_right_margin/sam/YE
1354 * XXX capability to indicate this, but we don't look at that */
1355 phy_wid = phy_wid_base - phy_base;
1356 tcp_right = tlp->tl_line.cells + cnt;
1358 while(&tccp[1] < tcp_right){
1359 ui16_t cw = tccp[1].tc_width;
1360 ui32_t i;
1362 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1363 cw = 1;
1364 i = w + cw;
1365 if(i > phy_wid)
1366 break;
1367 w = i;
1368 ++tccp;
1370 /*vi_right = w - vi_left;*/
1372 /* If the complete line including prompt fits on the screen, show prompt */
1373 if(--tcp_right == tccp){
1374 f |= a_RIGHT_MAX;
1376 /* Since we did brute-force walk also for the left boundary we may end up
1377 * in a situation were anything effectively fits on the screen, including
1378 * the prompt that is, but were we don't recognize this since we
1379 * restricted the search to fit in some visual viewpoint. Therefore try
1380 * again to extend the left boundary to overcome that */
1381 if(!(f & a_LEFT_MIN)){
1382 struct a_tty_cell const *tc1p = tlp->tl_line.cells;
1383 ui32_t vil1 = vi_left;
1385 assert(!(f & a_SHOW_PROMPT));
1386 w += tlp->tl_prompt_width;
1387 for(tcxp = tcp_left;;){
1388 ui32_t i = tcxp[-1].tc_width;
1390 if(i == UI8_MAX) /* TODO yet TAB == SPC */
1391 i = 1;
1392 vil1 += i;
1393 i += w;
1394 if(i > phy_wid)
1395 break;
1396 w = i;
1397 if(--tcxp == tc1p){
1398 tcp_left = tc1p;
1399 /*vi_left = vil1;*/
1400 f |= a_LEFT_MIN;
1401 break;
1404 /*w -= tlp->tl_prompt_width;*/
1407 tcp_right = tccp;
1408 tccp = tlp->tl_line.cells + cur;
1410 if((f & (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT | a_SHOW_PROMPT)) ==
1411 (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT) &&
1412 w + tlp->tl_prompt_width <= phy_wid){
1413 phy_wid -= (phy_base = tlp->tl_prompt_width);
1414 f |= a_SHOW_PROMPT;
1417 /* Try to avoid repainting the complete line - this is possible if the
1418 * cursor "did not leave the screen" and the prompt status hasn't changed.
1419 * I.e., after clamping virtual viewpoint, compare relation to physical */
1420 if((f & (a_TTY_VF_MOD_SINGLE/*FIXME*/ |
1421 a_TTY_VF_MOD_CONTENT/* xxx */ | a_TTY_VF_MOD_DIRTY)) ||
1422 (tcxp = tlp->tl_phy_start) == NULL ||
1423 tcxp > tccp || tcxp <= tcp_right)
1424 f |= a_TTY_VF_MOD_DIRTY;
1425 else{
1426 f |= a_TTY_VF_MOD_DIRTY;
1427 #if 0
1428 struct a_tty_cell const *tcyp;
1429 si32_t cur_displace;
1430 ui32_t phy_lmargin, phy_rmargin, fx, phy_displace;
1432 phy_lmargin = (fx = phy_wid) / 100;
1433 phy_rmargin = fx - (phy_lmargin * a_TTY_SCROLL_MARGIN_RIGHT);
1434 phy_lmargin *= a_TTY_SCROLL_MARGIN_LEFT;
1435 fx = (f & (a_SHOW_PROMPT | a_VISIBLE_PROMPT));
1437 if(fx == 0 || fx == (a_SHOW_PROMPT | a_VISIBLE_PROMPT)){
1439 #endif
1441 goto jpaint;
1443 /* We know what we have to paint, start synchronizing */
1444 jpaint:
1445 assert(phy_cur == tlp->tl_phy_cursor);
1446 assert(phy_wid == phy_wid_base - phy_base);
1447 assert(cnt == tlp->tl_count);
1448 assert(cnt > 0);
1449 assert(lstcur == tlp->tl_lst_cursor);
1450 assert(tccp == tlp->tl_line.cells + cur);
1452 phy_nxtcur = phy_base; /* FIXME only if repaint cpl. */
1454 /* Quickshot: is it only cursor movement within the visible screen? */
1455 if((f & a_TTY_VF_REFRESH) == a_TTY_VF_MOD_CURSOR){
1456 f |= a_MOVE_CURSOR;
1457 goto jcursor;
1460 /* To be able to apply some quick jump offs, clear line if possible */
1461 if(f & a_TTY_VF_MOD_DIRTY){
1462 /* Force complete clearance and cursor reinitialization */
1463 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr) ||
1464 !n_termcap_cmd(n_TERMCAP_CMD_ce, 0, -1))
1465 goto jerr;
1466 tlp->tl_phy_start = tcp_left;
1467 phy_cur = 0;
1470 if((f & (a_TTY_VF_MOD_DIRTY | a_SHOW_PROMPT)) && phy_cur != 0){
1471 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
1472 goto jerr;
1473 phy_cur = 0;
1476 if(f & a_SHOW_PROMPT){
1477 assert(phy_base == tlp->tl_prompt_width);
1478 if(fputs(tlp->tl_prompt, n_tty_fp) == EOF)
1479 goto jerr;
1480 phy_cur = phy_nxtcur;
1481 f |= a_VISIBLE_PROMPT;
1482 }else
1483 f &= ~a_VISIBLE_PROMPT;
1485 /* FIXME reposition cursor for paint */
1486 for(w = phy_nxtcur; tcp_left <= tcp_right; ++tcp_left){
1487 ui16_t cw;
1489 cw = tcp_left->tc_width;
1491 if(n_LIKELY(!tcp_left->tc_novis)){
1492 if(fwrite(tcp_left->tc_cbuf, sizeof *tcp_left->tc_cbuf,
1493 tcp_left->tc_count, n_tty_fp) != tcp_left->tc_count)
1494 goto jerr;
1495 }else{ /* XXX Shouldn't be here <-> CText, ui_str.c */
1496 char wbuf[8]; /* XXX magic */
1498 if(n_psonce & n_PSO_UNICODE){
1499 ui32_t wc;
1501 wc = (ui32_t)tcp_left->tc_wc;
1502 if((wc & ~0x1Fu) == 0)
1503 wc |= 0x2400;
1504 else if(wc == 0x7F)
1505 wc = 0x2421;
1506 else
1507 wc = 0x2426;
1508 n_utf32_to_utf8(wc, wbuf);
1509 }else
1510 wbuf[0] = '?', wbuf[1] = '\0';
1512 if(fputs(wbuf, n_tty_fp) == EOF)
1513 goto jerr;
1514 cw = 1;
1517 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1518 cw = 1;
1519 w += cw;
1520 if(tcp_left == tccp)
1521 phy_nxtcur = w;
1522 phy_cur += cw;
1525 /* Write something position marker alike if it does not fit on screen */
1526 if((f & a_HAVE_POSITION) &&
1527 ((f & (a_LEFT_MIN | a_RIGHT_MAX)) != (a_LEFT_MIN | a_RIGHT_MAX) ||
1528 ((f & a_HAVE_PROMPT) && !(f & a_SHOW_PROMPT)))){
1529 # ifdef HAVE_COLOUR
1530 char *posbuf = tlp->tl_pos_buf, *pos = tlp->tl_pos;
1531 # else
1532 char posbuf[5], *pos = posbuf;
1534 pos[4] = '\0';
1535 # endif
1537 if(phy_cur != (w = phy_wid_base) &&
1538 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = w, 0))
1539 goto jerr;
1541 *pos++ = '|';
1542 if((f & a_LEFT_MIN) && (!(f & a_HAVE_PROMPT) || (f & a_SHOW_PROMPT)))
1543 memcpy(pos, "^.+", 3);
1544 else if(f & a_RIGHT_MAX)
1545 memcpy(pos, ".+$", 3);
1546 else{
1547 /* Theoretical line length limit a_TTY_LINE_MAX, choose next power of
1548 * ten (10 ** 10) to represent 100 percent, since we don't have a macro
1549 * that generates a constant, and i don't trust the standard "u type
1550 * suffix automatically scales" calculate the large number */
1551 static char const itoa[] = "0123456789";
1553 ui64_t const fact100 = (ui64_t)0x3B9ACA00u * 10u, fact = fact100 / 100;
1554 ui32_t i = (ui32_t)(((fact100 / cnt) * tlp->tl_cursor) / fact);
1555 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1557 if(i < 10)
1558 pos[0] = ' ', pos[1] = itoa[i];
1559 else
1560 pos[1] = itoa[i % 10], pos[0] = itoa[i / 10];
1561 pos[2] = '%';
1564 if(fputs(posbuf, n_tty_fp) == EOF)
1565 goto jerr;
1566 phy_cur += 4;
1569 /* Users are used to see the cursor right of the point of interest, so we
1570 * need some further adjustments unless in special conditions. Be aware
1571 * that we may have adjusted cur at the beginning, too */
1572 if((cur = tlp->tl_cursor) == 0)
1573 phy_nxtcur = phy_base;
1574 else if(cur != cnt){
1575 ui16_t cw = tccp->tc_width;
1577 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1578 cw = 1;
1579 phy_nxtcur -= cw;
1582 jcursor:
1583 if(((f & a_MOVE_CURSOR) || phy_nxtcur != phy_cur) &&
1584 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = phy_nxtcur, 0))
1585 goto jerr;
1587 jleave:
1588 tlp->tl_vi_flags |= (f & a_PERSIST_MASK);
1589 tlp->tl_lst_count = tlp->tl_count;
1590 tlp->tl_lst_cursor = tlp->tl_cursor;
1591 tlp->tl_phy_cursor = phy_cur;
1593 NYD2_LEAVE;
1594 return ((f & a_TRUE_RV) != 0);
1595 jerr:
1596 f &= ~a_TRUE_RV;
1597 goto jleave;
1600 static si32_t
1601 a_tty_wboundary(struct a_tty_line *tlp, si32_t dir){/* TODO shell token-wise */
1602 bool_t anynon;
1603 struct a_tty_cell *tcap;
1604 ui32_t cur, cnt;
1605 si32_t rv;
1606 NYD2_ENTER;
1608 assert(dir == 1 || dir == -1);
1610 rv = -1;
1611 cnt = tlp->tl_count;
1612 cur = tlp->tl_cursor;
1614 if(dir < 0){
1615 if(cur == 0)
1616 goto jleave;
1617 }else if(cur + 1 >= cnt)
1618 goto jleave;
1619 else
1620 --cnt, --cur; /* xxx Unsigned wrapping may occur (twice), then */
1622 for(rv = 0, tcap = tlp->tl_line.cells, anynon = FAL0;;){
1623 wchar_t wc;
1625 wc = tcap[cur += (ui32_t)dir].tc_wc;
1626 if(/*TODO not everywhere iswblank(wc)*/ wc == L' ' || wc == L'\t' ||
1627 iswpunct(wc)){
1628 if(anynon)
1629 break;
1630 }else
1631 anynon = TRU1;
1633 ++rv;
1635 if(dir < 0){
1636 if(cur == 0)
1637 break;
1638 }else if(cur + 1 >= cnt){
1639 ++rv;
1640 break;
1643 jleave:
1644 NYD2_LEAVE;
1645 return rv;
1648 static void
1649 a_tty_khome(struct a_tty_line *tlp, bool_t dobell){
1650 ui32_t f;
1651 NYD2_ENTER;
1653 if(n_LIKELY(tlp->tl_cursor > 0)){
1654 tlp->tl_cursor = 0;
1655 f = a_TTY_VF_MOD_CURSOR;
1656 }else if(dobell)
1657 f = a_TTY_VF_BELL;
1658 else
1659 f = a_TTY_VF_NONE;
1661 tlp->tl_vi_flags |= f;
1662 NYD2_LEAVE;
1665 static void
1666 a_tty_kend(struct a_tty_line *tlp){
1667 ui32_t f;
1668 NYD2_ENTER;
1670 if(n_LIKELY(tlp->tl_cursor < tlp->tl_count)){
1671 tlp->tl_cursor = tlp->tl_count;
1672 f = a_TTY_VF_MOD_CURSOR;
1673 }else
1674 f = a_TTY_VF_BELL;
1676 tlp->tl_vi_flags |= f;
1677 NYD2_LEAVE;
1680 static void
1681 a_tty_kbs(struct a_tty_line *tlp){
1682 ui32_t f, cur, cnt;
1683 NYD2_ENTER;
1685 cur = tlp->tl_cursor;
1686 cnt = tlp->tl_count;
1688 if(n_LIKELY(cur > 0)){
1689 tlp->tl_cursor = --cur;
1690 tlp->tl_count = --cnt;
1692 if((cnt -= cur) > 0){
1693 struct a_tty_cell *tcap;
1695 tcap = tlp->tl_line.cells + cur;
1696 memmove(tcap, &tcap[1], cnt *= sizeof(*tcap));
1698 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
1699 }else
1700 f = a_TTY_VF_BELL;
1702 tlp->tl_vi_flags |= f;
1703 NYD2_LEAVE;
1706 static void
1707 a_tty_ksnarf(struct a_tty_line *tlp, bool_t cplline, bool_t dobell){
1708 ui32_t i, f;
1709 NYD2_ENTER;
1711 f = a_TTY_VF_NONE;
1712 i = tlp->tl_cursor;
1714 if(cplline && i > 0){
1715 tlp->tl_cursor = i = 0;
1716 f = a_TTY_VF_MOD_CURSOR;
1719 if(n_LIKELY(i < tlp->tl_count)){
1720 struct a_tty_cell *tcap;
1722 tcap = &tlp->tl_line.cells[0];
1723 a_tty_copy2paste(tlp, &tcap[i], &tcap[tlp->tl_count]);
1724 tlp->tl_count = i;
1725 f = a_TTY_VF_MOD_CONTENT;
1726 }else if(dobell)
1727 f |= a_TTY_VF_BELL;
1729 tlp->tl_vi_flags |= f;
1730 NYD2_LEAVE;
1733 static si32_t
1734 a_tty_kdel(struct a_tty_line *tlp){
1735 ui32_t cur, cnt, f;
1736 si32_t i;
1737 NYD2_ENTER;
1739 cur = tlp->tl_cursor;
1740 cnt = tlp->tl_count;
1741 i = (si32_t)(cnt - cur);
1743 if(n_LIKELY(i > 0)){
1744 tlp->tl_count = --cnt;
1746 if(n_LIKELY(--i > 0)){
1747 struct a_tty_cell *tcap;
1749 tcap = &tlp->tl_line.cells[cur];
1750 memmove(tcap, &tcap[1], (ui32_t)i * sizeof(*tcap));
1752 f = a_TTY_VF_MOD_CONTENT;
1753 }else if(cnt == 0 && !ok_blook(ignoreeof)){
1754 putc('^', n_tty_fp);
1755 putc('D', n_tty_fp);
1756 i = -1;
1757 f = a_TTY_VF_NONE;
1758 }else{
1759 i = 0;
1760 f = a_TTY_VF_BELL;
1763 tlp->tl_vi_flags |= f;
1764 NYD2_LEAVE;
1765 return i;
1768 static void
1769 a_tty_kleft(struct a_tty_line *tlp){
1770 ui32_t f;
1771 NYD2_ENTER;
1773 if(n_LIKELY(tlp->tl_cursor > 0)){
1774 --tlp->tl_cursor;
1775 f = a_TTY_VF_MOD_CURSOR;
1776 }else
1777 f = a_TTY_VF_BELL;
1779 tlp->tl_vi_flags |= f;
1780 NYD2_LEAVE;
1783 static void
1784 a_tty_kright(struct a_tty_line *tlp){
1785 ui32_t i;
1786 NYD2_ENTER;
1788 if(n_LIKELY((i = tlp->tl_cursor + 1) <= tlp->tl_count)){
1789 tlp->tl_cursor = i;
1790 i = a_TTY_VF_MOD_CURSOR;
1791 }else
1792 i = a_TTY_VF_BELL;
1794 tlp->tl_vi_flags |= i;
1795 NYD2_LEAVE;
1798 static void
1799 a_tty_ksnarfw(struct a_tty_line *tlp, bool_t fwd){
1800 struct a_tty_cell *tcap;
1801 ui32_t cnt, cur, f;
1802 si32_t i;
1803 NYD2_ENTER;
1805 if(n_UNLIKELY((i = a_tty_wboundary(tlp, (fwd ? +1 : -1))) <= 0)){
1806 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
1807 goto jleave;
1810 cnt = tlp->tl_count - (ui32_t)i;
1811 cur = tlp->tl_cursor;
1812 if(!fwd)
1813 cur -= (ui32_t)i;
1814 tcap = &tlp->tl_line.cells[cur];
1816 a_tty_copy2paste(tlp, &tcap[0], &tcap[i]);
1818 if((tlp->tl_count = cnt) != (tlp->tl_cursor = cur)){
1819 cnt -= cur;
1820 memmove(&tcap[0], &tcap[i], cnt * sizeof(*tcap)); /* FIXME*/
1823 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
1824 jleave:
1825 tlp->tl_vi_flags |= f;
1826 NYD2_LEAVE;
1829 static void
1830 a_tty_kgow(struct a_tty_line *tlp, si32_t dir){
1831 ui32_t f;
1832 si32_t i;
1833 NYD2_ENTER;
1835 if(n_UNLIKELY((i = a_tty_wboundary(tlp, dir)) <= 0))
1836 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
1837 else{
1838 if(dir < 0)
1839 i = -i;
1840 tlp->tl_cursor += (ui32_t)i;
1841 f = a_TTY_VF_MOD_CURSOR;
1844 tlp->tl_vi_flags |= f;
1845 NYD2_LEAVE;
1848 static bool_t
1849 a_tty_kother(struct a_tty_line *tlp, wchar_t wc){
1850 /* Append if at EOL, insert otherwise;
1851 * since we may move around character-wise, always use a fresh ps */
1852 mbstate_t ps;
1853 struct a_tty_cell tc, *tcap;
1854 ui32_t f, cur, cnt;
1855 bool_t rv;
1856 NYD2_ENTER;
1858 rv = FAL0;
1859 f = a_TTY_VF_NONE;
1861 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1862 if(tlp->tl_count + 1 >= a_TTY_LINE_MAX){
1863 n_err(_("Stop here, we can't extend line beyond size limit\n"));
1864 goto jleave;
1867 /* First init a cell and see whether we'll really handle this wc */
1868 memset(&ps, 0, sizeof ps);
1869 /* C99 */{
1870 size_t l;
1872 l = wcrtomb(tc.tc_cbuf, tc.tc_wc = wc, &ps);
1873 if(n_UNLIKELY(l > MB_LEN_MAX)){
1874 jemb:
1875 n_err(_("wcrtomb(3) error: too many multibyte character bytes\n"));
1876 goto jleave;
1878 tc.tc_count = (ui16_t)l;
1880 if(n_UNLIKELY((n_psonce & n_PSO_ENC_MBSTATE) != 0)){
1881 l = wcrtomb(&tc.tc_cbuf[l], L'\0', &ps);
1882 if(n_LIKELY(l == 1))
1883 /* Only NUL terminator */;
1884 else if(n_LIKELY(--l < MB_LEN_MAX))
1885 tc.tc_count += (ui16_t)l;
1886 else
1887 goto jemb;
1891 /* Yes, we will! Place it in the array */
1892 tc.tc_novis = (iswprint(wc) == 0);
1893 tc.tc_width = a_tty_wcwidth(wc);
1894 /* TODO if(tc.tc_novis && tc.tc_width > 0) */
1896 cur = tlp->tl_cursor++;
1897 cnt = tlp->tl_count++ - cur;
1898 tcap = &tlp->tl_line.cells[cur];
1899 if(cnt >= 1){
1900 memmove(&tcap[1], tcap, cnt * sizeof(*tcap));
1901 f = a_TTY_VF_MOD_CONTENT;
1902 }else
1903 f = a_TTY_VF_MOD_SINGLE;
1904 memcpy(tcap, &tc, sizeof *tcap);
1906 f |= a_TTY_VF_MOD_CURSOR;
1907 rv = TRU1;
1908 jleave:
1909 if(!rv)
1910 f |= a_TTY_VF_BELL;
1911 tlp->tl_vi_flags |= f;
1912 NYD2_LEAVE;
1913 return rv;
1916 static ui32_t
1917 a_tty_kht(struct a_tty_line *tlp){
1918 ui8_t (*mempool)[n_MEMORY_POOL_TYPE_SIZEOF], *mempool_persist;
1919 struct stat sb;
1920 struct str orig, bot, topp, sub, exp, preexp;
1921 struct n_string shou, *shoup;
1922 struct a_tty_cell *ctop, *cx;
1923 bool_t wedid, set_savec;
1924 ui32_t rv, f;
1925 NYD2_ENTER;
1927 /* Get plain line data; if this is the first expansion/xy, update the
1928 * very original content so that ^G gets the origin back */
1929 orig = tlp->tl_savec;
1930 a_tty_cell2save(tlp);
1931 exp = tlp->tl_savec;
1932 if(orig.s != NULL){
1933 /*tlp->tl_savec = orig;*/
1934 set_savec = FAL0;
1935 }else
1936 set_savec = TRU1;
1937 orig = exp;
1939 mempool_persist = n_go_data->gdc_mempool;
1940 n_memory_pool_push(mempool = n_lofi_alloc(sizeof *mempool));
1942 shoup = n_string_creat_auto(&shou);
1943 f = a_TTY_VF_NONE;
1945 /* C99 */{
1946 size_t max;
1947 struct a_tty_cell *cword;
1949 /* Find the word to be expanded */
1950 cword = tlp->tl_line.cells;
1951 ctop = &cword[tlp->tl_cursor];
1952 cx = &cword[tlp->tl_count];
1954 /* topp: separate data right of cursor */
1955 if(cx > ctop){
1956 for(rv = 0; ctop < cx; ++ctop)
1957 rv += ctop->tc_count;
1958 topp.l = rv;
1959 topp.s = orig.s + orig.l - rv;
1960 ctop = cword + tlp->tl_cursor;
1961 }else
1962 topp.s = NULL, topp.l = 0;
1964 /* Find the shell token that corresponds to the cursor position */
1965 max = 0;
1966 if(ctop > cword){
1967 for(; cword < ctop; ++cword)
1968 max += cword->tc_count;
1970 bot = sub = orig;
1971 bot.l = 0;
1972 sub.l = max;
1974 if(max > 0){
1975 for(;;){
1976 enum n_shexp_state shs;
1978 exp = sub;
1979 shs = n_shexp_parse_token((n_SHEXP_PARSE_DRYRUN |
1980 n_SHEXP_PARSE_TRIM_SPACE | n_SHEXP_PARSE_IGNORE_EMPTY |
1981 n_SHEXP_PARSE_QUOTE_AUTO_CLOSE), NULL, &sub, NULL);
1982 if(sub.l != 0){
1983 size_t x;
1985 assert(max >= sub.l);
1986 x = max - sub.l;
1987 bot.l += x;
1988 max -= x;
1989 continue;
1991 if(shs & n_SHEXP_STATE_ERR_MASK){
1992 n_err(_("Invalid completion pattern: %.*s\n"),
1993 (int)exp.l, exp.s);
1994 f |= a_TTY_VF_BELL;
1995 goto jnope;
1998 /* All WS? Trailing WS that has been "jumped over"? */
1999 if(exp.l == 0 || (shs & n_SHEXP_STATE_WS_TRAIL))
2000 break;
2002 n_shexp_parse_token((n_SHEXP_PARSE_TRIM_SPACE |
2003 n_SHEXP_PARSE_IGNORE_EMPTY | n_SHEXP_PARSE_QUOTE_AUTO_CLOSE),
2004 shoup, &exp, NULL);
2005 break;
2008 sub.s = n_string_cp(shoup);
2009 sub.l = shoup->s_len;
2013 /* Leave room for "implicit asterisk" expansion, as below */
2014 if(sub.l == 0){
2015 sub.s = n_UNCONST(n_star);
2016 sub.l = sizeof(n_star) -1;
2019 preexp.s = n_UNCONST(n_empty);
2020 preexp.l = sizeof(n_empty) -1;
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 f |= a_TTY_VF_BELL;
2070 goto jnope;
2073 /* If the expansion equals the original string, assume the user wants what
2074 * is usually known as tab completion, append `*' and restart */
2075 if(!wedid && exp.l == sub.l && !memcmp(exp.s, sub.s, exp.l)){
2076 if(sub.s[sub.l - 1] == '*')
2077 goto jnope;
2079 wedid = TRU1;
2080 shoup = n_string_push_c(shoup, '*');
2081 sub.s = n_string_cp(shoup);
2082 sub.l = shoup->s_len;
2083 goto jredo;
2086 if(exp.s[exp.l - 1] != '/'){
2087 if(!stat(exp.s, &sb) && S_ISDIR(sb.st_mode)){
2088 shoup = n_string_assign_buf(shoup, exp.s, exp.l);
2089 shoup = n_string_push_c(shoup, '/');
2090 exp.s = n_string_cp(shoup);
2091 goto jset;
2094 exp.s[exp.l] = '\0';
2096 jset:
2097 exp.l = strlen(exp.s = n_shexp_quote_cp(exp.s, tlp->tl_quote_rndtrip));
2098 tlp->tl_defc_cursor_byte = bot.l + preexp.l + exp.l -1;
2100 orig.l = bot.l + preexp.l + exp.l + topp.l;
2101 orig.s = n_autorec_alloc_from_pool(mempool_persist, orig.l + 5 +1);
2102 if((rv = (ui32_t)bot.l) > 0)
2103 memcpy(orig.s, bot.s, rv);
2104 if(preexp.l > 0){
2105 memcpy(&orig.s[rv], preexp.s, preexp.l);
2106 rv += preexp.l;
2108 memcpy(&orig.s[rv], exp.s, exp.l);
2109 rv += exp.l;
2110 if(topp.l > 0){
2111 memcpy(&orig.s[rv], topp.s, topp.l);
2112 rv += topp.l;
2114 orig.s[rv] = '\0';
2116 tlp->tl_defc = orig;
2117 tlp->tl_count = tlp->tl_cursor = 0;
2118 f |= a_TTY_VF_MOD_DIRTY;
2119 jleave:
2120 n_memory_pool_pop(mempool);
2121 n_lofi_free(mempool);
2122 tlp->tl_vi_flags |= f;
2123 NYD2_LEAVE;
2124 return rv;
2126 jmulti:{
2127 struct n_visual_info_ctx vic;
2128 struct str input;
2129 wc_t c2, c1;
2130 bool_t isfirst;
2131 char const *lococp;
2132 size_t locolen, scrwid, lnlen, lncnt, prefixlen;
2133 FILE *fp;
2135 if((fp = Ftmp(NULL, "tabex", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
2136 n_perr(_("tmpfile"), 0);
2137 fp = n_tty_fp;
2140 /* How long is the result string for real? Search the NUL NUL
2141 * terminator. While here, detect the longest entry to perform an
2142 * initial allocation of our accumulator string */
2143 locolen = preexp.l;
2145 size_t i;
2147 i = strlen(&exp.s[++exp.l]);
2148 locolen = n_MAX(locolen, i);
2149 exp.l += i;
2150 }while(exp.s[exp.l + 1] != '\0');
2152 shoup = n_string_reserve(n_string_trunc(shoup, 0),
2153 locolen + (locolen >> 1));
2155 /* Iterate (once again) over all results */
2156 scrwid = n_SCRNWIDTH_FOR_LISTS;
2157 lnlen = lncnt = 0;
2158 n_UNINIT(prefixlen, 0);
2159 n_UNINIT(lococp, NULL);
2160 n_UNINIT(c1, '\0');
2161 for(isfirst = TRU1; exp.l > 0; isfirst = FAL0, c1 = c2){
2162 size_t i;
2163 char const *fullpath;
2165 /* Next result */
2166 sub = exp;
2167 sub.l = i = strlen(sub.s);
2168 assert(exp.l >= i);
2169 if((exp.l -= i) > 0)
2170 --exp.l;
2171 exp.s += ++i;
2173 /* Separate dirname and basename */
2174 fullpath = sub.s;
2175 if(isfirst){
2176 char const *cp;
2178 if((cp = strrchr(fullpath, '/')) != NULL)
2179 prefixlen = PTR2SIZE(++cp - fullpath);
2180 else
2181 prefixlen = 0;
2183 if(prefixlen > 0 && prefixlen < sub.l){
2184 sub.l -= prefixlen;
2185 sub.s += prefixlen;
2188 /* We want case-insensitive sort-order */
2189 memset(&vic, 0, sizeof vic);
2190 vic.vic_indat = sub.s;
2191 vic.vic_inlen = sub.l;
2192 c2 = n_visual_info(&vic, n_VISUAL_INFO_ONE_CHAR) ? vic.vic_waccu
2193 : (ui8_t)*sub.s;
2194 #ifdef HAVE_C90AMEND1
2195 c2 = towlower(c2);
2196 #else
2197 c2 = lowerconv(c2);
2198 #endif
2200 /* Query longest common prefix along the way */
2201 if(isfirst){
2202 c1 = c2;
2203 lococp = sub.s;
2204 locolen = sub.l;
2205 }else if(locolen > 0){
2206 for(i = 0; i < locolen; ++i)
2207 if(lococp[i] != sub.s[i]){
2208 i = field_detect_clip(i, lococp, i);
2209 locolen = i;
2210 break;
2214 /* Prepare display */
2215 input = sub;
2216 shoup = n_shexp_quote(n_string_trunc(shoup, 0), &input,
2217 tlp->tl_quote_rndtrip);
2218 memset(&vic, 0, sizeof vic);
2219 vic.vic_indat = shoup->s_dat;
2220 vic.vic_inlen = shoup->s_len;
2221 if(!n_visual_info(&vic,
2222 n_VISUAL_INFO_SKIP_ERRORS | n_VISUAL_INFO_WIDTH_QUERY))
2223 vic.vic_vi_width = shoup->s_len;
2225 /* Put on screen. Indent follow lines of same sort slot.
2226 * Leave enough room for filename tagging */
2227 if((c1 = (c1 != c2))){
2228 #ifdef HAVE_C90AMEND1
2229 c1 = (iswalnum(c2) != 0);
2230 #else
2231 c1 = (alnumchar(c2) != 0);
2232 #endif
2234 if(isfirst || c1 ||
2235 scrwid < lnlen || scrwid - lnlen <= vic.vic_vi_width + 2){
2236 putc('\n', fp);
2237 if(scrwid < lnlen)
2238 ++lncnt;
2239 ++lncnt, lnlen = 0;
2240 if(!isfirst && !c1)
2241 goto jsep;
2242 }else if(lnlen > 0){
2243 jsep:
2244 fputs(" ", fp);
2245 lnlen += 2;
2247 fputs(n_string_cp(shoup), fp);
2248 lnlen += vic.vic_vi_width;
2250 /* Support the known filename tagging
2251 * XXX *line-editor-completion-filetype* or so */
2252 if(!lstat(fullpath, &sb)){
2253 char c = '\0';
2255 if(S_ISDIR(sb.st_mode))
2256 c = '/';
2257 else if(S_ISLNK(sb.st_mode))
2258 c = '@';
2259 # ifdef S_ISFIFO
2260 else if(S_ISFIFO(sb.st_mode))
2261 c = '|';
2262 # endif
2263 # ifdef S_ISSOCK
2264 else if(S_ISSOCK(sb.st_mode))
2265 c = '=';
2266 # endif
2267 # ifdef S_ISCHR
2268 else if(S_ISCHR(sb.st_mode))
2269 c = '%';
2270 # endif
2271 # ifdef S_ISBLK
2272 else if(S_ISBLK(sb.st_mode))
2273 c = '#';
2274 # endif
2276 if(c != '\0'){
2277 putc(c, fp);
2278 ++lnlen;
2282 putc('\n', fp);
2283 ++lncnt;
2285 page_or_print(fp, lncnt);
2286 if(fp != n_tty_fp)
2287 Fclose(fp);
2289 n_string_gut(shoup);
2291 /* A common prefix of 0 means we cannot provide the user any auto
2292 * completed characters for the multiple possible results.
2293 * Otherwise we can, so extend the visual line content by the common
2294 * prefix (in a reversible way) */
2295 f |= a_TTY_VF_BELL; /* XXX -> *line-editor-completion-bell*? or so */
2296 if(locolen > 0){
2297 (exp.s = n_UNCONST(lococp))[locolen] = '\0';
2298 exp.s -= prefixlen;
2299 exp.l = (locolen += prefixlen);
2300 goto jset;
2304 jnope:
2305 /* If we've provided a default content, but failed to expand, there is
2306 * nothing we can "revert to": drop that default again */
2307 if(set_savec){
2308 tlp->tl_savec.s = NULL;
2309 tlp->tl_savec.l = 0;
2311 f &= a_TTY_VF_BELL; /* XXX -> *line-editor-completion-bell*? or so */
2312 rv = 0;
2313 goto jleave;
2316 # ifdef HAVE_HISTORY
2317 static ui32_t
2318 a_tty__khist_shared(struct a_tty_line *tlp, struct a_tty_hist *thp){
2319 ui32_t f, rv;
2320 NYD2_ENTER;
2322 if(n_LIKELY((tlp->tl_hist = thp) != NULL)){
2323 tlp->tl_defc.s = savestrbuf(thp->th_dat, thp->th_len);
2324 rv = tlp->tl_defc.l = thp->th_len;
2325 f = (tlp->tl_count > 0) ? a_TTY_VF_MOD_DIRTY : a_TTY_VF_NONE;
2326 tlp->tl_count = tlp->tl_cursor = 0;
2327 }else{
2328 f = a_TTY_VF_BELL;
2329 rv = UI32_MAX;
2332 tlp->tl_vi_flags |= f;
2333 NYD2_LEAVE;
2334 return rv;
2337 static ui32_t
2338 a_tty_khist(struct a_tty_line *tlp, bool_t fwd){
2339 struct a_tty_hist *thp;
2340 ui32_t rv;
2341 NYD2_ENTER;
2343 /* If we're not in history mode yet, save line content */
2344 if((thp = tlp->tl_hist) == NULL){
2345 a_tty_cell2save(tlp);
2346 if((thp = a_tty.tg_hist) == NULL)
2347 goto jleave;
2348 if(fwd)
2349 while(thp->th_older != NULL)
2350 thp = thp->th_older;
2351 goto jleave;
2354 thp = fwd ? thp->th_younger : thp->th_older;
2355 jleave:
2356 rv = a_tty__khist_shared(tlp, thp);
2357 NYD2_LEAVE;
2358 return rv;
2361 static ui32_t
2362 a_tty_khist_search(struct a_tty_line *tlp, bool_t fwd){
2363 struct str orig_savec;
2364 struct a_tty_hist *thp;
2365 ui32_t rv;
2366 NYD2_ENTER;
2368 thp = NULL;
2370 /* We cannot complete an empty line */
2371 if(n_UNLIKELY(tlp->tl_count == 0)){
2372 /* XXX The upcoming hard reset would restore a set savec buffer,
2373 * XXX so forcefully reset that. A cleaner solution would be to
2374 * XXX reset it whenever a restore is no longer desired */
2375 tlp->tl_savec.s = NULL;
2376 tlp->tl_savec.l = 0;
2377 goto jleave;
2380 if((thp = tlp->tl_hist) == NULL){
2381 a_tty_cell2save(tlp);
2382 if((thp = a_tty.tg_hist) == NULL) /* TODO Should end "doing nothing"! */
2383 goto jleave;
2384 if(fwd)
2385 while(thp->th_older != NULL)
2386 thp = thp->th_older;
2387 orig_savec.s = NULL;
2388 orig_savec.l = 0; /* silence CC */
2389 }else if((thp = (fwd ? thp->th_younger : thp->th_older)) == NULL)
2390 goto jleave;
2391 else
2392 orig_savec = tlp->tl_savec;
2394 if(orig_savec.s == NULL)
2395 a_tty_cell2save(tlp);
2397 for(; thp != NULL; thp = (fwd ? thp->th_younger : thp->th_older))
2398 if(is_prefix(tlp->tl_savec.s, thp->th_dat))
2399 break;
2401 if(orig_savec.s != NULL)
2402 tlp->tl_savec = orig_savec;
2403 jleave:
2404 rv = a_tty__khist_shared(tlp, thp);
2405 NYD2_LEAVE;
2406 return rv;
2408 # endif /* HAVE_HISTORY */
2410 static enum a_tty_fun_status
2411 a_tty_fun(struct a_tty_line *tlp, enum a_tty_bind_flags tbf, size_t *len){
2412 enum a_tty_fun_status rv;
2413 NYD2_ENTER;
2415 rv = a_TTY_FUN_STATUS_OK;
2416 # undef a_X
2417 # define a_X(N) a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## N)
2418 switch(a_TTY_BIND_FUN_REDUCE(tbf)){
2419 case a_X(BELL):
2420 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2421 break;
2422 case a_X(GO_BWD):
2423 a_tty_kleft(tlp);
2424 break;
2425 case a_X(GO_FWD):
2426 a_tty_kright(tlp);
2427 break;
2428 case a_X(GO_WORD_BWD):
2429 a_tty_kgow(tlp, -1);
2430 break;
2431 case a_X(GO_WORD_FWD):
2432 a_tty_kgow(tlp, +1);
2433 break;
2434 case a_X(GO_HOME):
2435 a_tty_khome(tlp, TRU1);
2436 break;
2437 case a_X(GO_END):
2438 a_tty_kend(tlp);
2439 break;
2440 case a_X(DEL_BWD):
2441 a_tty_kbs(tlp);
2442 break;
2443 case a_X(DEL_FWD):
2444 if(a_tty_kdel(tlp) < 0)
2445 rv = a_TTY_FUN_STATUS_END;
2446 break;
2447 case a_X(SNARF_WORD_BWD):
2448 a_tty_ksnarfw(tlp, FAL0);
2449 break;
2450 case a_X(SNARF_WORD_FWD):
2451 a_tty_ksnarfw(tlp, TRU1);
2452 break;
2453 case a_X(SNARF_END):
2454 a_tty_ksnarf(tlp, FAL0, TRU1);
2455 break;
2456 case a_X(SNARF_LINE):
2457 a_tty_ksnarf(tlp, TRU1, (tlp->tl_count == 0));
2458 break;
2460 case a_X(HIST_FWD):{
2461 # ifdef HAVE_HISTORY
2462 bool_t isfwd = TRU1;
2464 if(0){
2465 # endif
2466 /* FALLTHRU */
2467 case a_X(HIST_BWD):
2468 # ifdef HAVE_HISTORY
2469 isfwd = FAL0;
2471 if((*len = a_tty_khist(tlp, isfwd)) != UI32_MAX){
2472 rv = a_TTY_FUN_STATUS_RESTART;
2473 break;
2475 goto jreset;
2476 # endif
2478 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2479 break;
2481 case a_X(HIST_SRCH_FWD):{
2482 # ifdef HAVE_HISTORY
2483 bool_t isfwd = TRU1;
2485 if(0){
2486 # endif
2487 /* FALLTHRU */
2488 case a_X(HIST_SRCH_BWD):
2489 # ifdef HAVE_HISTORY
2490 isfwd = FAL0;
2492 if((*len = a_tty_khist_search(tlp, isfwd)) != UI32_MAX){
2493 rv = a_TTY_FUN_STATUS_RESTART;
2494 break;
2496 goto jreset;
2497 # else
2498 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2499 # endif
2500 } break;
2502 case a_X(REPAINT):
2503 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2504 break;
2505 case a_X(QUOTE_RNDTRIP):
2506 tlp->tl_quote_rndtrip = !tlp->tl_quote_rndtrip;
2507 break;
2508 case a_X(PROMPT_CHAR):{
2509 wchar_t wc;
2511 if((wc = a_tty_vinuni(tlp)) > 0)
2512 a_tty_kother(tlp, wc);
2513 } break;
2514 case a_X(COMPLETE):
2515 if((*len = a_tty_kht(tlp)) > 0)
2516 rv = a_TTY_FUN_STATUS_RESTART;
2517 break;
2519 case a_X(PASTE):
2520 if(tlp->tl_pastebuf.l > 0)
2521 *len = (tlp->tl_defc = tlp->tl_pastebuf).l;
2522 else
2523 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2524 break;
2527 case a_X(CANCEL):
2528 /* Normally this just causes a restart and thus resets the state
2529 * machine */
2530 if(tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2532 # ifdef HAVE_KEY_BINDINGS
2533 tlp->tl_bind_takeover = '\0';
2534 # endif
2535 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2536 rv = a_TTY_FUN_STATUS_RESTART;
2537 break;
2539 case a_X(RESET):
2540 if(tlp->tl_count == 0 && tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2541 # ifdef HAVE_KEY_BINDINGS
2542 tlp->tl_bind_takeover = '\0';
2543 # endif
2544 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY | a_TTY_VF_BELL;
2545 break;
2546 }else if(0){
2547 case a_X(FULLRESET):
2548 tlp->tl_savec.s = tlp->tl_defc.s = NULL;
2549 tlp->tl_savec.l = tlp->tl_defc.l = 0;
2550 tlp->tl_defc_cursor_byte = 0;
2551 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2553 jreset:
2554 # ifdef HAVE_KEY_BINDINGS
2555 tlp->tl_bind_takeover = '\0';
2556 # endif
2557 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2558 tlp->tl_cursor = tlp->tl_count = 0;
2559 # ifdef HAVE_HISTORY
2560 tlp->tl_hist = NULL;
2561 # endif
2562 if((*len = tlp->tl_savec.l) != 0){
2563 tlp->tl_defc = tlp->tl_savec;
2564 tlp->tl_savec.s = NULL;
2565 tlp->tl_savec.l = 0;
2566 }else
2567 *len = tlp->tl_defc.l;
2568 rv = a_TTY_FUN_STATUS_RESTART;
2569 break;
2571 default:
2572 case a_X(COMMIT):
2573 rv = a_TTY_FUN_STATUS_COMMIT;
2574 break;
2576 # undef a_X
2578 NYD2_LEAVE;
2579 return rv;
2582 static ssize_t
2583 a_tty_readline(struct a_tty_line *tlp, size_t len, bool_t *histok_or_null
2584 n_MEMORY_DEBUG_ARGS){
2585 /* We want to save code, yet we may have to incorporate a lines'
2586 * default content and / or default input to switch back to after some
2587 * history movement; let "len > 0" mean "have to display some data
2588 * buffer" -> a_BUFMODE, and only otherwise read(2) it */
2589 mbstate_t ps[2];
2590 char cbuf_base[MB_LEN_MAX * 2], *cbuf, *cbufp;
2591 ssize_t rv;
2592 struct a_tty_bind_tree *tbtp;
2593 wchar_t wc;
2594 enum a_tty_bind_flags tbf;
2595 enum {a_NONE, a_WAS_HERE = 1<<0, a_BUFMODE = 1<<1, a_MAYBEFUN = 1<<2,
2596 a_TIMEOUT = 1<<3, a_TIMEOUT_EXPIRED = 1<<4,
2597 a_TIMEOUT_MASK = a_TIMEOUT | a_TIMEOUT_EXPIRED,
2598 a_READ_LOOP_MASK = ~(a_WAS_HERE | a_MAYBEFUN | a_TIMEOUT_MASK)
2599 } flags;
2600 NYD_ENTER;
2602 n_UNINIT(rv, 0);
2603 # ifdef HAVE_KEY_BINDINGS
2604 assert(tlp->tl_bind_takeover == '\0');
2605 # endif
2606 jrestart:
2607 memset(ps, 0, sizeof ps);
2608 flags = a_NONE;
2609 tlp->tl_vi_flags |= a_TTY_VF_REFRESH | a_TTY_VF_SYNC;
2611 jinput_loop:
2612 for(;;){
2613 if(len != 0)
2614 flags |= a_BUFMODE;
2616 /* Ensure we have valid pointers, and room for grow */
2617 a_tty_check_grow(tlp, ((flags & a_BUFMODE) ? (ui32_t)len : 1)
2618 n_MEMORY_DEBUG_ARGSCALL);
2620 /* Handle visual state flags, except in buffer mode */
2621 if(!(flags & a_BUFMODE) && (tlp->tl_vi_flags & a_TTY_VF_ALL_MASK))
2622 if(!a_tty_vi_refresh(tlp)){
2623 rv = -1;
2624 goto jleave;
2627 /* Ready for messing around.
2628 * Normal read(2)? Else buffer mode: speed this one up */
2629 if(!(flags & a_BUFMODE)){
2630 cbufp =
2631 cbuf = cbuf_base;
2632 }else{
2633 assert(tlp->tl_defc.l > 0 && tlp->tl_defc.s != NULL);
2634 assert(tlp->tl_defc.l >= len);
2635 cbufp =
2636 cbuf = tlp->tl_defc.s + (tlp->tl_defc.l - len);
2637 cbufp += len;
2640 /* Read in the next complete multibyte character */
2641 /* C99 */{
2642 # ifdef HAVE_KEY_BINDINGS
2643 struct a_tty_bind_tree *xtbtp;
2644 struct inseq{
2645 struct inseq *last;
2646 struct inseq *next;
2647 struct a_tty_bind_tree *tbtp;
2648 } *isp_head, *isp;
2650 isp_head = isp = NULL;
2651 # endif
2653 for(flags &= a_READ_LOOP_MASK;;){
2654 # ifdef HAVE_KEY_BINDINGS
2655 if(!(flags & a_BUFMODE) && tlp->tl_bind_takeover != '\0'){
2656 wc = tlp->tl_bind_takeover;
2657 tlp->tl_bind_takeover = '\0';
2658 }else
2659 # endif
2661 if(!(flags & a_BUFMODE)){
2662 /* Let me at least once dream of iomon(itor), timer with
2663 * one-shot, enwrapped with key_event and key_sequence_event,
2664 * all driven by an event_loop */
2665 /* TODO v15 Until we have SysV signal handling all through we
2666 * TODO need to temporarily adjust our BSD signal handler with
2667 * TODO a SysV one, here */
2668 n_sighdl_t otstp, ottin, ottou;
2670 otstp = n_signal(SIGTSTP, &n_tty_signal);
2671 ottin = n_signal(SIGTTIN, &n_tty_signal);
2672 ottou = n_signal(SIGTTOU, &n_tty_signal);
2673 # ifdef HAVE_KEY_BINDINGS
2674 flags &= ~a_TIMEOUT_MASK;
2675 if(isp != NULL && (tbtp = isp->tbtp)->tbt_isseq &&
2676 !tbtp->tbt_isseq_trail){
2677 a_tty_term_rawmode_timeout(tlp, TRU1);
2678 flags |= a_TIMEOUT;
2680 # endif
2682 while((rv = read(STDIN_FILENO, cbufp, 1)) < 1){
2683 if(rv == -1){
2684 if(n_err_no == n_ERR_INTR){
2685 if((tlp->tl_vi_flags & a_TTY_VF_MOD_DIRTY) &&
2686 !a_tty_vi_refresh(tlp))
2687 break;
2688 continue;
2690 break;
2693 # ifdef HAVE_KEY_BINDINGS
2694 /* Timeout expiration */
2695 if(rv == 0){
2696 assert(flags & a_TIMEOUT);
2697 assert(isp != NULL);
2698 a_tty_term_rawmode_timeout(tlp, FAL0);
2700 /* Something "atomic" broke. Maybe the current one can
2701 * also be terminated already, by itself? xxx really? */
2702 if((tbtp = isp->tbtp)->tbt_bind != NULL){
2703 tlp->tl_bind_takeover = wc;
2704 goto jhave_bind;
2707 /* Or, maybe there is a second path without a timeout;
2708 * this should be covered by .tbt_isseq_trail, but then
2709 * again a single-layer implementation cannot "know" */
2710 for(xtbtp = tbtp; (xtbtp = xtbtp->tbt_sibling) != NULL;)
2711 if(xtbtp->tbt_char == tbtp->tbt_char){
2712 assert(!xtbtp->tbt_isseq);
2713 break;
2715 /* Lay down on read(2)? */
2716 if(xtbtp != NULL)
2717 continue;
2718 goto jtake_over;
2720 # endif /* HAVE_KEY_BINDINGS */
2723 # ifdef HAVE_KEY_BINDINGS
2724 if(flags & a_TIMEOUT)
2725 a_tty_term_rawmode_timeout(tlp, FAL0);
2726 # endif
2727 safe_signal(SIGTSTP, otstp);
2728 safe_signal(SIGTTIN, ottin);
2729 safe_signal(SIGTTOU, ottou);
2730 if(rv < 0)
2731 goto jleave;
2733 ++cbufp;
2736 rv = (ssize_t)mbrtowc(&wc, cbuf, PTR2SIZE(cbufp - cbuf), &ps[0]);
2737 if(rv <= 0){
2738 /* Any error during buffer mode can only result in a hard
2739 * reset; Otherwise, if it's a hard error, or if too many
2740 * redundant shift sequences overflow our buffer: perform
2741 * hard reset */
2742 if((flags & a_BUFMODE) || rv == -1 ||
2743 sizeof cbuf_base == PTR2SIZE(cbufp - cbuf)){
2744 a_tty_fun(tlp, a_TTY_BIND_FUN_FULLRESET, &len);
2745 goto jrestart;
2747 /* Otherwise, due to the way we deal with the buffer, we need
2748 * to restore the mbstate_t from before this conversion */
2749 ps[0] = ps[1];
2750 continue;
2752 cbufp = cbuf;
2753 ps[1] = ps[0];
2756 /* Normal read(2)ing is subject to detection of key-bindings */
2757 # ifdef HAVE_KEY_BINDINGS
2758 if(!(flags & a_BUFMODE)){
2759 /* Check for special bypass functions before we try to embed
2760 * this character into the tree */
2761 if(n_uasciichar(wc)){
2762 char c;
2763 char const *cp;
2765 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_prompt_char)[0];
2766 *cp != '\0'; ++cp){
2767 if(c == *cp){
2768 wc = a_tty_vinuni(tlp);
2769 break;
2772 if(wc == '\0'){
2773 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2774 goto jinput_loop;
2777 if(n_uasciichar(wc))
2778 flags |= a_MAYBEFUN;
2779 else
2780 flags &= ~a_MAYBEFUN;
2782 /* Search for this character in the bind tree */
2783 tbtp = (isp != NULL) ? isp->tbtp->tbt_childs
2784 : (*tlp->tl_bind_tree_hmap)[wc % HSHSIZE];
2785 for(; tbtp != NULL; tbtp = tbtp->tbt_sibling){
2786 if(tbtp->tbt_char == wc){
2787 struct inseq *nisp;
2789 /* If this one cannot continue we're likely finished! */
2790 if(tbtp->tbt_childs == NULL){
2791 assert(tbtp->tbt_bind != NULL);
2792 tbf = tbtp->tbt_bind->tbc_flags;
2793 goto jmle_fun;
2796 /* This needs to read more characters */
2797 nisp = salloc(sizeof *nisp);
2798 if((nisp->last = isp) == NULL)
2799 isp_head = nisp;
2800 else
2801 isp->next = nisp;
2802 nisp->next = NULL;
2803 nisp->tbtp = tbtp;
2804 isp = nisp;
2805 flags &= ~a_WAS_HERE;
2806 break;
2809 if(tbtp != NULL)
2810 continue;
2812 /* Was there a binding active, but couldn't be continued? */
2813 if(isp != NULL){
2814 /* A binding had a timeout, it didn't expire, but we saw
2815 * something non-expected. Something "atomic" broke.
2816 * Maybe there is a second path without a timeout, that
2817 * continues like we've seen it. I.e., it may just have been
2818 * the user, typing too fast. We definitely want to allow
2819 * bindings like \e,d etc. to succeed: users are so used to
2820 * them that a timeout cannot be the mechanism to catch up!
2821 * A single-layer implementation cannot "know" */
2822 if((tbtp = isp->tbtp)->tbt_isseq && (isp->last == NULL ||
2823 !(xtbtp = isp->last->tbtp)->tbt_isseq ||
2824 xtbtp->tbt_isseq_trail)){
2825 for(xtbtp = (tbtp = isp->tbtp);
2826 (xtbtp = xtbtp->tbt_sibling) != NULL;)
2827 if(xtbtp->tbt_char == tbtp->tbt_char){
2828 assert(!xtbtp->tbt_isseq);
2829 break;
2831 if(xtbtp != NULL){
2832 isp->tbtp = xtbtp;
2833 tlp->tl_bind_takeover = wc;
2834 continue;
2838 /* Check for CANCEL shortcut now */
2839 if(flags & a_MAYBEFUN){
2840 char c;
2841 char const *cp;
2843 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_cancel)[0];
2844 *cp != '\0'; ++cp)
2845 if(c == *cp){
2846 tbf = a_TTY_BIND_FUN_INTERNAL |a_TTY_BIND_FUN_CANCEL;
2847 goto jmle_fun;
2851 /* So: maybe the current sequence can be terminated here? */
2852 if((tbtp = isp->tbtp)->tbt_bind != NULL){
2853 jhave_bind:
2854 tbf = tbtp->tbt_bind->tbc_flags;
2855 jmle_fun:
2856 if(tbf & a_TTY_BIND_FUN_INTERNAL){
2857 switch(a_tty_fun(tlp, tbf, &len)){
2858 case a_TTY_FUN_STATUS_OK:
2859 goto jinput_loop;
2860 case a_TTY_FUN_STATUS_COMMIT:
2861 goto jdone;
2862 case a_TTY_FUN_STATUS_RESTART:
2863 goto jrestart;
2864 case a_TTY_FUN_STATUS_END:
2865 rv = -1;
2866 goto jleave;
2868 assert(0);
2869 }else if(tbtp->tbt_bind->tbc_flags & a_TTY_BIND_NOCOMMIT){
2870 struct a_tty_bind_ctx *tbcp;
2872 tbcp = tbtp->tbt_bind;
2873 memcpy(tlp->tl_defc.s = salloc(
2874 (tlp->tl_defc.l = len = tbcp->tbc_exp_len) +1),
2875 tbcp->tbc_exp, tbcp->tbc_exp_len +1);
2876 goto jrestart;
2877 }else{
2878 cbufp = tbtp->tbt_bind->tbc_exp;
2879 goto jinject_input;
2884 /* Otherwise take over all chars "as is" */
2885 jtake_over:
2886 for(; isp_head != NULL; isp_head = isp_head->next)
2887 if(a_tty_kother(tlp, isp_head->tbtp->tbt_char)){
2888 /* FIXME */
2890 /* And the current one too */
2891 goto jkother;
2893 # endif /* HAVE_KEY_BINDINGS */
2895 if((flags & a_BUFMODE) && (len -= (size_t)rv) == 0){
2896 /* Buffer mode completed */
2897 tlp->tl_defc.s = NULL;
2898 tlp->tl_defc.l = 0;
2899 flags &= ~a_BUFMODE;
2901 break;
2904 # ifndef HAVE_KEY_BINDINGS
2905 /* Don't interpret control bytes during buffer mode.
2906 * Otherwise, if it's a control byte check whether it is a MLE
2907 * function. Remarks: initially a complete duplicate to be able to
2908 * switch(), later converted to simply iterate over (an #ifdef'd
2909 * subset of) the MLE base_tuple table in order to have "a SPOF" */
2910 if(cbuf == cbuf_base && n_uasciichar(wc) && cntrlchar((char)wc)){
2911 struct a_tty_bind_builtin_tuple const *tbbtp, *tbbtp_max;
2912 char c;
2914 c = (char)wc ^ 0x40;
2915 tbbtp = a_tty_bind_base_tuples;
2916 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_base_tuples)];
2917 jbuiltin_redo:
2918 for(; tbbtp < tbbtp_max; ++tbbtp){
2919 /* Assert default_tuple table is properly subset'ed */
2920 assert(tbbtp->tbdt_iskey);
2921 if(tbbtp->tbbt_ckey == c){
2922 if(tbbtp->tbbt_exp[0] == '\0'){
2923 tbf = a_TTY_BIND_FUN_EXPAND((ui8_t)tbbtp->tbbt_exp[1]);
2924 switch(a_tty_fun(tlp, tbf, &len)){
2925 case a_TTY_FUN_STATUS_OK:
2926 goto jinput_loop;
2927 case a_TTY_FUN_STATUS_COMMIT:
2928 goto jdone;
2929 case a_TTY_FUN_STATUS_RESTART:
2930 goto jrestart;
2931 case a_TTY_FUN_STATUS_END:
2932 rv = -1;
2933 goto jleave;
2935 assert(0);
2936 }else{
2937 cbufp = tbbtp->tbbt_exp;
2938 goto jinject_input;
2942 if(tbbtp ==
2943 &a_tty_bind_base_tuples[n_NELEM(a_tty_bind_base_tuples)]){
2944 tbbtp = a_tty_bind_default_tuples;
2945 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_default_tuples)];
2946 goto jbuiltin_redo;
2949 # endif /* !HAVE_KEY_BINDINGS */
2951 # ifdef HAVE_KEY_BINDINGS
2952 jkother:
2953 # endif
2954 if(a_tty_kother(tlp, wc)){
2955 /* Don't clear the history during buffer mode.. */
2956 # ifdef HAVE_HISTORY
2957 if(!(flags & a_BUFMODE) && cbuf == cbuf_base)
2958 tlp->tl_hist = NULL;
2959 # endif
2964 /* We have a completed input line, convert the struct cell data to its
2965 * plain character equivalent */
2966 jdone:
2967 rv = a_tty_cell2dat(tlp);
2968 jleave:
2969 putc('\n', n_tty_fp);
2970 fflush(n_tty_fp);
2971 NYD_LEAVE;
2972 return rv;
2974 jinject_input:{
2975 size_t i;
2977 hold_all_sigs(); /* XXX v15 drop */
2978 i = a_tty_cell2dat(tlp);
2979 n_go_input_inject(n_GO_INPUT_INJECT_NONE, tlp->tl_line.cbuf, i);
2980 i = strlen(cbufp) +1;
2981 if(i >= *tlp->tl_x_bufsize){
2982 *tlp->tl_x_buf = (n_realloc)(*tlp->tl_x_buf, i n_MEMORY_DEBUG_ARGSCALL);
2983 *tlp->tl_x_bufsize = i;
2985 memcpy(*tlp->tl_x_buf, cbufp, i);
2986 rele_all_sigs(); /* XXX v15 drop */
2987 if(histok_or_null != NULL)
2988 *histok_or_null = FAL0;
2989 rv = (ssize_t)--i;
2991 goto jleave;
2994 # ifdef HAVE_KEY_BINDINGS
2995 static enum n_go_input_flags
2996 a_tty_bind_ctx_find(char const *name){
2997 enum n_go_input_flags rv;
2998 struct a_tty_bind_ctx_map const *tbcmp;
2999 NYD2_ENTER;
3001 tbcmp = a_tty_bind_ctx_maps;
3002 do if(!asccasecmp(tbcmp->tbcm_name, name)){
3003 rv = tbcmp->tbcm_ctx;
3004 goto jleave;
3005 }while(PTRCMP(++tbcmp, <,
3006 &a_tty_bind_ctx_maps[n_NELEM(a_tty_bind_ctx_maps)]));
3008 rv = (enum n_go_input_flags)-1;
3009 jleave:
3010 NYD2_LEAVE;
3011 return rv;
3014 static bool_t
3015 a_tty_bind_create(struct a_tty_bind_parse_ctx *tbpcp, bool_t replace){
3016 struct a_tty_bind_ctx *tbcp;
3017 bool_t rv;
3018 NYD2_ENTER;
3020 rv = FAL0;
3022 if(!a_tty_bind_parse(TRU1, tbpcp))
3023 goto jleave;
3025 /* Since we use a single buffer for it all, need to replace as such */
3026 if(tbpcp->tbpc_tbcp != NULL){
3027 if(!replace)
3028 goto jleave;
3029 a_tty_bind_del(tbpcp);
3030 }else if(a_tty.tg_bind_cnt == UI32_MAX){
3031 n_err(_("`bind': maximum number of bindings already established\n"));
3032 goto jleave;
3035 /* C99 */{
3036 size_t i, j;
3038 tbcp = smalloc(n_VSTRUCT_SIZEOF(struct a_tty_bind_ctx, tbc__buf) +
3039 tbpcp->tbpc_seq_len + tbpcp->tbpc_exp.l +
3040 n_MAX(sizeof(si32_t), sizeof(wc_t)) + tbpcp->tbpc_cnv_len +3);
3041 if(tbpcp->tbpc_ltbcp != NULL){
3042 tbcp->tbc_next = tbpcp->tbpc_ltbcp->tbc_next;
3043 tbpcp->tbpc_ltbcp->tbc_next = tbcp;
3044 }else{
3045 enum n_go_input_flags gif;
3047 gif = tbpcp->tbpc_flags & n__GO_INPUT_CTX_MASK;
3048 tbcp->tbc_next = a_tty.tg_bind[gif];
3049 a_tty.tg_bind[gif] = tbcp;
3051 memcpy(tbcp->tbc_seq = &tbcp->tbc__buf[0],
3052 tbpcp->tbpc_seq, i = (tbcp->tbc_seq_len = tbpcp->tbpc_seq_len) +1);
3053 memcpy(tbcp->tbc_exp = &tbcp->tbc__buf[i],
3054 tbpcp->tbpc_exp.s, j = (tbcp->tbc_exp_len = tbpcp->tbpc_exp.l) +1);
3055 i += j;
3056 i = (i + tbpcp->tbpc_cnv_align_mask) & ~tbpcp->tbpc_cnv_align_mask;
3057 memcpy(tbcp->tbc_cnv = &tbcp->tbc__buf[i],
3058 tbpcp->tbpc_cnv, (tbcp->tbc_cnv_len = tbpcp->tbpc_cnv_len) +1);
3059 tbcp->tbc_flags = tbpcp->tbpc_flags;
3062 /* Directly resolve any termcap(5) symbol if we are already setup */
3063 if((n_psonce & n_PSO_STARTED) &&
3064 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
3065 a_TTY_BIND_RESOLVE)
3066 a_tty_bind_resolve(tbcp);
3068 ++a_tty.tg_bind_cnt;
3069 /* If this binding is usable invalidate the key input lookup trees */
3070 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3071 a_tty.tg_bind_isdirty = TRU1;
3072 rv = TRU1;
3073 jleave:
3074 NYD2_LEAVE;
3075 return rv;
3078 static bool_t
3079 a_tty_bind_parse(bool_t isbindcmd, struct a_tty_bind_parse_ctx *tbpcp){
3080 enum{a_TRUE_RV = a_TTY__BIND_LAST<<1};
3082 struct n_visual_info_ctx vic;
3083 struct str shin_save, shin;
3084 struct n_string shou, *shoup;
3085 size_t i;
3086 struct kse{
3087 struct kse *next;
3088 char *seq_dat;
3089 wc_t *cnv_dat;
3090 ui32_t seq_len;
3091 ui32_t cnv_len; /* High bit set if a termap to be resolved */
3092 ui32_t calc_cnv_len; /* Ditto, but aligned etc. */
3093 ui8_t kse__dummy[4];
3094 } *head, *tail;
3095 ui32_t f;
3096 NYD2_ENTER;
3097 n_LCTA(UICMP(64, a_TRUE_RV, <, UI32_MAX),
3098 "Flag bits excess storage datatype");
3100 f = n_GO_INPUT_NONE;
3101 shoup = n_string_creat_auto(&shou);
3102 head = tail = NULL;
3104 /* Parse the key-sequence */
3105 for(shin.s = n_UNCONST(tbpcp->tbpc_in_seq), shin.l = UIZ_MAX;;){
3106 struct kse *ep;
3107 enum n_shexp_state shs;
3109 shin_save = shin;
3110 shs = n_shexp_parse_token((n_SHEXP_PARSE_TRUNC |
3111 n_SHEXP_PARSE_TRIM_SPACE | n_SHEXP_PARSE_IGNORE_EMPTY |
3112 n_SHEXP_PARSE_IFS_IS_COMMA), shoup, &shin, NULL);
3113 if(shs & n_SHEXP_STATE_ERR_UNICODE){
3114 f |= a_TTY_BIND_DEFUNCT;
3115 if(isbindcmd && (n_poption & n_PO_D_V))
3116 n_err(_("`%s': \\uNICODE not available in locale: %s\n"),
3117 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3119 if((shs & n_SHEXP_STATE_ERR_MASK) & ~n_SHEXP_STATE_ERR_UNICODE){
3120 n_err(_("`%s': failed to parse key-sequence: %s\n"),
3121 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3122 goto jleave;
3124 if((shs & (n_SHEXP_STATE_OUTPUT | n_SHEXP_STATE_STOP)) ==
3125 n_SHEXP_STATE_STOP)
3126 break;
3128 ep = salloc(sizeof *ep);
3129 if(head == NULL)
3130 head = ep;
3131 else
3132 tail->next = ep;
3133 tail = ep;
3134 ep->next = NULL;
3135 if(!(shs & n_SHEXP_STATE_ERR_UNICODE)){
3136 i = strlen(ep->seq_dat = n_shexp_quote_cp(n_string_cp(shoup), TRU1));
3137 if(i >= SI32_MAX - 1)
3138 goto jelen;
3139 ep->seq_len = (ui32_t)i;
3140 }else{
3141 /* Otherwise use the original buffer, _we_ can only quote it the wrong
3142 * way (e.g., an initial $'\u3a' becomes '\u3a'), _then_ */
3143 if((i = shin_save.l - shin.l) >= SI32_MAX - 1)
3144 goto jelen;
3145 ep->seq_len = (ui32_t)i;
3146 ep->seq_dat = savestrbuf(shin_save.s, i);
3149 memset(&vic, 0, sizeof vic);
3150 vic.vic_inlen = shoup->s_len;
3151 vic.vic_indat = shoup->s_dat;
3152 if(!n_visual_info(&vic,
3153 n_VISUAL_INFO_WOUT_CREATE | n_VISUAL_INFO_WOUT_SALLOC)){
3154 n_err(_("`%s': key-sequence seems to contain invalid "
3155 "characters: %s: %s\n"),
3156 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
3157 f |= a_TTY_BIND_DEFUNCT;
3158 goto jleave;
3159 }else if(vic.vic_woulen == 0 ||
3160 vic.vic_woulen >= (SI32_MAX - 2) / sizeof(wc_t)){
3161 jelen:
3162 n_err(_("`%s': length of key-sequence unsupported: %s: %s\n"),
3163 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
3164 f |= a_TTY_BIND_DEFUNCT;
3165 goto jleave;
3167 ep->cnv_dat = vic.vic_woudat;
3168 ep->cnv_len = (ui32_t)vic.vic_woulen;
3170 /* A termcap(5)/terminfo(5) identifier? */
3171 if(ep->cnv_len > 1 && ep->cnv_dat[0] == ':'){
3172 i = --ep->cnv_len, ++ep->cnv_dat;
3173 # if 0 /* ndef HAVE_TERMCAP xxx User can, via *termcap*! */
3174 if(n_poption & n_PO_D_V)
3175 n_err(_("`%s': no termcap(5)/terminfo(5) support: %s: %s\n"),
3176 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3177 f |= a_TTY_BIND_DEFUNCT;
3178 # endif
3179 if(i > a_TTY_BIND_CAPNAME_MAX){
3180 n_err(_("`%s': termcap(5)/terminfo(5) name too long: %s: %s\n"),
3181 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3182 f |= a_TTY_BIND_DEFUNCT;
3184 while(i > 0)
3185 /* (We store it as char[]) */
3186 if((ui32_t)ep->cnv_dat[--i] & ~0x7Fu){
3187 n_err(_("`%s': invalid termcap(5)/terminfo(5) name content: "
3188 "%s: %s\n"),
3189 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3190 f |= a_TTY_BIND_DEFUNCT;
3191 break;
3193 ep->cnv_len |= SI32_MIN; /* Needs resolve */
3194 f |= a_TTY_BIND_RESOLVE;
3197 if(shs & n_SHEXP_STATE_STOP)
3198 break;
3201 if(head == NULL){
3202 jeempty:
3203 n_err(_("`%s': effectively empty key-sequence: %s\n"),
3204 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3205 goto jleave;
3208 if(isbindcmd) /* (Or always, just "1st time init") */
3209 tbpcp->tbpc_cnv_align_mask = n_MAX(sizeof(si32_t), sizeof(wc_t)) - 1;
3211 /* C99 */{
3212 struct a_tty_bind_ctx *ltbcp, *tbcp;
3213 char *cpbase, *cp, *cnv;
3214 size_t sl, cl;
3216 /* Unite the parsed sequence(s) into single string representations */
3217 for(sl = cl = 0, tail = head; tail != NULL; tail = tail->next){
3218 sl += tail->seq_len + 1;
3220 if(!isbindcmd)
3221 continue;
3223 /* Preserve room for terminal capabilities to be resolved.
3224 * Above we have ensured the buffer will fit in these calculations */
3225 if((i = tail->cnv_len) & SI32_MIN){
3226 /* For now
3227 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[]+NUL;}
3228 * later
3229 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3230 n_LCTAV(n_ISPOW2(a_TTY_BIND_CAPEXP_ROUNDUP));
3231 n_LCTA(a_TTY_BIND_CAPEXP_ROUNDUP >= sizeof(wc_t),
3232 "Aligning on this constant does not properly align wc_t");
3233 i &= SI32_MAX;
3234 i *= sizeof(wc_t);
3235 i += sizeof(si32_t);
3236 if(i < a_TTY_BIND_CAPEXP_ROUNDUP)
3237 i = (i + (a_TTY_BIND_CAPEXP_ROUNDUP - 1)) &
3238 ~(a_TTY_BIND_CAPEXP_ROUNDUP - 1);
3239 }else
3240 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3241 i *= sizeof(wc_t);
3242 i += sizeof(si32_t) + sizeof(wc_t); /* (buf_len_iscap, NUL) */
3243 cl += i;
3244 if(tail->cnv_len & SI32_MIN){
3245 tail->cnv_len &= SI32_MAX;
3246 i |= SI32_MIN;
3248 tail->calc_cnv_len = (ui32_t)i;
3250 --sl;
3252 tbpcp->tbpc_seq_len = sl;
3253 tbpcp->tbpc_cnv_len = cl;
3254 /* C99 */{
3255 size_t j;
3257 j = i = sl + 1; /* Room for comma separator */
3258 if(isbindcmd){
3259 i = (i + tbpcp->tbpc_cnv_align_mask) & ~tbpcp->tbpc_cnv_align_mask;
3260 j = i;
3261 i += cl;
3263 tbpcp->tbpc_seq = cp = cpbase = salloc(i);
3264 tbpcp->tbpc_cnv = cnv = &cpbase[j];
3267 for(tail = head; tail != NULL; tail = tail->next){
3268 memcpy(cp, tail->seq_dat, tail->seq_len);
3269 cp += tail->seq_len;
3270 *cp++ = ',';
3272 if(isbindcmd){
3273 char * const save_cnv = cnv;
3275 n_UNALIGN(si32_t*,cnv)[0] = (si32_t)(i = tail->calc_cnv_len);
3276 cnv += sizeof(si32_t);
3277 if(i & SI32_MIN){
3278 /* For now
3279 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];}
3280 * later
3281 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[];} */
3282 n_UNALIGN(si32_t*,cnv)[0] = tail->cnv_len;
3283 cnv += sizeof(si32_t);
3285 i = tail->cnv_len * sizeof(wc_t);
3286 memcpy(cnv, tail->cnv_dat, i);
3287 cnv += i;
3288 *n_UNALIGN(wc_t*,cnv) = '\0';
3290 cnv = save_cnv + (tail->calc_cnv_len & SI32_MAX);
3293 *--cp = '\0';
3295 /* Search for a yet existing identical mapping */
3296 /* C99 */{
3297 enum n_go_input_flags gif;
3299 gif = tbpcp->tbpc_flags & n__GO_INPUT_CTX_MASK;
3301 for(ltbcp = NULL, tbcp = a_tty.tg_bind[gif]; tbcp != NULL;
3302 ltbcp = tbcp, tbcp = tbcp->tbc_next)
3303 if(tbcp->tbc_seq_len == sl && !memcmp(tbcp->tbc_seq, cpbase, sl)){
3304 tbpcp->tbpc_tbcp = tbcp;
3305 break;
3308 tbpcp->tbpc_ltbcp = ltbcp;
3309 tbpcp->tbpc_flags |= (f & a_TTY__BIND_MASK);
3312 /* Create single string expansion if so desired */
3313 if(isbindcmd){
3314 char *exp;
3316 exp = tbpcp->tbpc_exp.s;
3318 i = tbpcp->tbpc_exp.l;
3319 if(i > 0 && exp[i - 1] == '@'){
3320 while(--i > 0){
3321 if(!blankspacechar(exp[i - 1]))
3322 break;
3324 if(i == 0)
3325 goto jeempty;
3327 exp[tbpcp->tbpc_exp.l = i] = '\0';
3328 tbpcp->tbpc_flags |= a_TTY_BIND_NOCOMMIT;
3331 /* Reverse solidus cannot be placed last in expansion to avoid (at the
3332 * time of this writing) possible problems with newline escaping.
3333 * Don't care about (un)even number thereof */
3334 if(i > 0 && exp[i - 1] == '\\'){
3335 n_err(_("`%s': reverse solidus cannot be last in expansion: %s\n"),
3336 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3337 goto jleave;
3340 /* It may map to an internal MLE command! */
3341 for(i = 0; i < n_NELEM(a_tty_bind_fun_names); ++i)
3342 if(!asccasecmp(exp, a_tty_bind_fun_names[i])){
3343 tbpcp->tbpc_flags |= a_TTY_BIND_FUN_EXPAND(i) |
3344 a_TTY_BIND_FUN_INTERNAL |
3345 (head->next == NULL ? a_TTY_BIND_MLE1CNTRL : 0);
3346 if((n_poption & n_PO_D_V) &&
3347 (tbpcp->tbpc_flags & a_TTY_BIND_NOCOMMIT))
3348 n_err(_("`%s': MLE commands can't be made editable via @: %s\n"),
3349 tbpcp->tbpc_cmd, exp);
3350 tbpcp->tbpc_flags &= ~a_TTY_BIND_NOCOMMIT;
3351 break;
3355 f |= a_TRUE_RV; /* TODO because we only now true and false; DEFUNCT.. */
3356 jleave:
3357 n_string_gut(shoup);
3358 NYD2_LEAVE;
3359 return (f & a_TRUE_RV) != 0;
3362 static void
3363 a_tty_bind_resolve(struct a_tty_bind_ctx *tbcp){
3364 char capname[a_TTY_BIND_CAPNAME_MAX +1];
3365 struct n_termcap_value tv;
3366 size_t len;
3367 bool_t isfirst; /* TODO For now: first char must be control! */
3368 char *cp, *next;
3369 NYD2_ENTER;
3371 n_UNINIT(next, NULL);
3372 for(cp = tbcp->tbc_cnv, isfirst = TRU1, len = tbcp->tbc_cnv_len;
3373 len > 0; isfirst = FAL0, cp = next){
3374 /* C99 */{
3375 si32_t i, j;
3377 i = n_UNALIGN(si32_t*,cp)[0];
3378 j = i & SI32_MAX;
3379 next = &cp[j];
3380 len -= j;
3381 if(i == j)
3382 continue;
3384 /* struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];} */
3385 cp += sizeof(si32_t);
3386 i = n_UNALIGN(si32_t*,cp)[0];
3387 cp += sizeof(si32_t);
3388 for(j = 0; j < i; ++j)
3389 capname[j] = n_UNALIGN(wc_t*,cp)[j];
3390 capname[j] = '\0';
3393 /* Use generic lookup mechanism if not a known query */
3394 /* C99 */{
3395 si32_t tq;
3397 tq = n_termcap_query_for_name(capname, n_TERMCAP_CAPTYPE_STRING);
3398 if(tq == -1){
3399 tv.tv_data.tvd_string = capname;
3400 tq = n__TERMCAP_QUERY_MAX1;
3403 if(tq < 0 || !n_termcap_query(tq, &tv)){
3404 if(n_poption & n_PO_D_V)
3405 n_err(_("`bind': unknown or unsupported capability: %s: %s\n"),
3406 capname, tbcp->tbc_seq);
3407 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3408 break;
3412 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3413 /* C99 */{
3414 size_t i;
3416 i = strlen(tv.tv_data.tvd_string);
3417 if(/*i > SI32_MAX ||*/ i >= PTR2SIZE(next - cp)){
3418 if(n_poption & n_PO_D_V)
3419 n_err(_("`bind': capability expansion too long: %s: %s\n"),
3420 capname, tbcp->tbc_seq);
3421 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3422 break;
3423 }else if(i == 0){
3424 if(n_poption & n_PO_D_V)
3425 n_err(_("`bind': empty capability expansion: %s: %s\n"),
3426 capname, tbcp->tbc_seq);
3427 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3428 break;
3429 }else if(isfirst && !cntrlchar(*tv.tv_data.tvd_string)){
3430 if(n_poption & n_PO_D_V)
3431 n_err(_("`bind': capability expansion does not start with "
3432 "control: %s: %s\n"), capname, tbcp->tbc_seq);
3433 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3434 break;
3436 n_UNALIGN(si32_t*,cp)[-1] = (si32_t)i;
3437 memcpy(cp, tv.tv_data.tvd_string, i);
3438 cp[i] = '\0';
3441 NYD2_LEAVE;
3444 static void
3445 a_tty_bind_del(struct a_tty_bind_parse_ctx *tbpcp){
3446 struct a_tty_bind_ctx *ltbcp, *tbcp;
3447 NYD2_ENTER;
3449 tbcp = tbpcp->tbpc_tbcp;
3451 if((ltbcp = tbpcp->tbpc_ltbcp) != NULL)
3452 ltbcp->tbc_next = tbcp->tbc_next;
3453 else
3454 a_tty.tg_bind[tbpcp->tbpc_flags & n__GO_INPUT_CTX_MASK] = tbcp->tbc_next;
3455 free(tbcp);
3457 --a_tty.tg_bind_cnt;
3458 a_tty.tg_bind_isdirty = TRU1;
3459 NYD2_LEAVE;
3462 static void
3463 a_tty_bind_tree_build(void){
3464 size_t i;
3465 NYD2_ENTER;
3467 for(i = 0; i < n__GO_INPUT_CTX_MAX1; ++i){
3468 struct a_tty_bind_ctx *tbcp;
3469 n_LCTAV(n_GO_INPUT_CTX_BASE == 0);
3471 /* Somewhat wasteful, but easier to handle: simply clone the entire
3472 * primary key onto the secondary one, then only modify it */
3473 for(tbcp = a_tty.tg_bind[n_GO_INPUT_CTX_BASE]; tbcp != NULL;
3474 tbcp = tbcp->tbc_next)
3475 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3476 a_tty__bind_tree_add(n_GO_INPUT_CTX_BASE, &a_tty.tg_bind_tree[i][0],
3477 tbcp);
3479 if(i != n_GO_INPUT_CTX_BASE)
3480 for(tbcp = a_tty.tg_bind[i]; tbcp != NULL; tbcp = tbcp->tbc_next)
3481 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3482 a_tty__bind_tree_add(i, &a_tty.tg_bind_tree[i][0], tbcp);
3485 a_tty.tg_bind_isbuild = TRU1;
3486 NYD2_LEAVE;
3489 static void
3490 a_tty_bind_tree_teardown(void){
3491 size_t i, j;
3492 NYD2_ENTER;
3494 memset(&a_tty.tg_bind_shcut_cancel[0], 0,
3495 sizeof(a_tty.tg_bind_shcut_cancel));
3496 memset(&a_tty.tg_bind_shcut_prompt_char[0], 0,
3497 sizeof(a_tty.tg_bind_shcut_prompt_char));
3499 for(i = 0; i < n__GO_INPUT_CTX_MAX1; ++i)
3500 for(j = 0; j < HSHSIZE; ++j)
3501 a_tty__bind_tree_free(a_tty.tg_bind_tree[i][j]);
3502 memset(&a_tty.tg_bind_tree[0], 0, sizeof(a_tty.tg_bind_tree));
3504 a_tty.tg_bind_isdirty = a_tty.tg_bind_isbuild = FAL0;
3505 NYD2_LEAVE;
3508 static void
3509 a_tty__bind_tree_add(ui32_t hmap_idx, struct a_tty_bind_tree *store[HSHSIZE],
3510 struct a_tty_bind_ctx *tbcp){
3511 ui32_t cnvlen;
3512 char const *cnvdat;
3513 struct a_tty_bind_tree *ntbtp;
3514 NYD2_ENTER;
3515 n_UNUSED(hmap_idx);
3517 ntbtp = NULL;
3519 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len; cnvlen > 0;){
3520 union {wchar_t const *wp; char const *cp;} u;
3521 si32_t entlen;
3523 /* {si32_t buf_len_iscap;} */
3524 entlen = *n_UNALIGN(si32_t const*,cnvdat);
3526 if(entlen & SI32_MIN){
3527 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;}
3528 * Note that empty capabilities result in DEFUNCT */
3529 for(u.cp = (char const*)&n_UNALIGN(si32_t const*,cnvdat)[2];
3530 *u.cp != '\0'; ++u.cp)
3531 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.cp, TRU1);
3532 assert(ntbtp != NULL);
3533 ntbtp->tbt_isseq_trail = TRU1;
3534 entlen &= SI32_MAX;
3535 }else{
3536 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3537 bool_t isseq;
3539 u.wp = (wchar_t const*)&n_UNALIGN(si32_t const*,cnvdat)[1];
3541 /* May be a special shortcut function? */
3542 if(ntbtp == NULL && (tbcp->tbc_flags & a_TTY_BIND_MLE1CNTRL)){
3543 char *cp;
3544 ui32_t ctx, fun;
3546 ctx = tbcp->tbc_flags & n__GO_INPUT_CTX_MASK;
3547 fun = tbcp->tbc_flags & a_TTY__BIND_FUN_MASK;
3549 if(fun == a_TTY_BIND_FUN_CANCEL){
3550 for(cp = &a_tty.tg_bind_shcut_cancel[ctx][0];
3551 PTRCMP(cp, <, &a_tty.tg_bind_shcut_cancel[ctx]
3552 [n_NELEM(a_tty.tg_bind_shcut_cancel[ctx]) - 1]); ++cp)
3553 if(*cp == '\0'){
3554 *cp = (char)*u.wp;
3555 break;
3557 }else if(fun == a_TTY_BIND_FUN_PROMPT_CHAR){
3558 for(cp = &a_tty.tg_bind_shcut_prompt_char[ctx][0];
3559 PTRCMP(cp, <, &a_tty.tg_bind_shcut_prompt_char[ctx]
3560 [n_NELEM(a_tty.tg_bind_shcut_prompt_char[ctx]) - 1]);
3561 ++cp)
3562 if(*cp == '\0'){
3563 *cp = (char)*u.wp;
3564 break;
3569 isseq = (u.wp[1] != '\0');
3570 for(; *u.wp != '\0'; ++u.wp)
3571 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.wp, isseq);
3572 if(isseq){
3573 assert(ntbtp != NULL);
3574 ntbtp->tbt_isseq_trail = TRU1;
3578 cnvlen -= entlen;
3579 cnvdat += entlen;
3582 /* Should have been rendered defunctional at first instead */
3583 assert(ntbtp != NULL);
3584 ntbtp->tbt_bind = tbcp;
3585 NYD2_LEAVE;
3588 static struct a_tty_bind_tree *
3589 a_tty__bind_tree_add_wc(struct a_tty_bind_tree **treep,
3590 struct a_tty_bind_tree *parentp, wchar_t wc, bool_t isseq){
3591 struct a_tty_bind_tree *tbtp, *xtbtp;
3592 NYD2_ENTER;
3594 if(parentp == NULL){
3595 treep += wc % HSHSIZE;
3597 /* Having no parent also means that the tree slot is possibly empty */
3598 for(tbtp = *treep; tbtp != NULL;
3599 parentp = tbtp, tbtp = tbtp->tbt_sibling){
3600 if(tbtp->tbt_char != wc)
3601 continue;
3602 if(tbtp->tbt_isseq == isseq)
3603 goto jleave;
3604 /* isseq MUST be linked before !isseq, so record this "parent"
3605 * sibling, but continue searching for now.
3606 * Otherwise it is impossible that we'll find what we look for */
3607 if(isseq){
3608 #ifdef HAVE_DEBUG
3609 while((tbtp = tbtp->tbt_sibling) != NULL)
3610 assert(tbtp->tbt_char != wc);
3611 #endif
3612 break;
3616 tbtp = smalloc(sizeof *tbtp);
3617 memset(tbtp, 0, sizeof *tbtp);
3618 tbtp->tbt_char = wc;
3619 tbtp->tbt_isseq = isseq;
3621 if(parentp == NULL){
3622 tbtp->tbt_sibling = *treep;
3623 *treep = tbtp;
3624 }else{
3625 tbtp->tbt_sibling = parentp->tbt_sibling;
3626 parentp->tbt_sibling = tbtp;
3628 }else{
3629 if((tbtp = *(treep = &parentp->tbt_childs)) != NULL){
3630 for(;; tbtp = xtbtp){
3631 if(tbtp->tbt_char == wc){
3632 if(tbtp->tbt_isseq == isseq)
3633 goto jleave;
3634 /* isseq MUST be linked before, so it is impossible that we'll
3635 * find what we look for */
3636 if(isseq){
3637 #ifdef HAVE_DEBUG
3638 while((tbtp = tbtp->tbt_sibling) != NULL)
3639 assert(tbtp->tbt_char != wc);
3640 #endif
3641 tbtp = NULL;
3642 break;
3646 if((xtbtp = tbtp->tbt_sibling) == NULL){
3647 treep = &tbtp->tbt_sibling;
3648 break;
3653 xtbtp = smalloc(sizeof *xtbtp);
3654 memset(xtbtp, 0, sizeof *xtbtp);
3655 xtbtp->tbt_parent = parentp;
3656 xtbtp->tbt_char = wc;
3657 xtbtp->tbt_isseq = isseq;
3658 tbtp = xtbtp;
3659 *treep = tbtp;
3661 jleave:
3662 NYD2_LEAVE;
3663 return tbtp;
3666 static void
3667 a_tty__bind_tree_free(struct a_tty_bind_tree *tbtp){
3668 NYD2_ENTER;
3669 while(tbtp != NULL){
3670 struct a_tty_bind_tree *tmp;
3672 if((tmp = tbtp->tbt_childs) != NULL)
3673 a_tty__bind_tree_free(tmp);
3675 tmp = tbtp->tbt_sibling;
3676 free(tbtp);
3677 tbtp = tmp;
3679 NYD2_LEAVE;
3681 # endif /* HAVE_KEY_BINDINGS */
3683 FL void
3684 n_tty_init(void){
3685 NYD_ENTER;
3687 if(ok_blook(line_editor_disable))
3688 goto jleave;
3690 /* Load the history file */
3691 # ifdef HAVE_HISTORY
3692 do/* for break */{
3693 char const *v;
3694 char *lbuf;
3695 FILE *f;
3696 size_t lsize, cnt, llen;
3698 if((v = a_tty_hist_query_config()) == NULL ||
3699 a_tty.tg_hist_size_max == 0)
3700 break;
3702 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
3703 f = fopen(v, "r"); /* TODO HISTFILE LOAD: use linebuf pool */
3704 if(f == NULL)
3705 goto jhist_done;
3706 (void)n_file_lock(fileno(f), FLT_READ, 0,0, UIZ_MAX);
3708 assert(!(n_pstate & n_PS_ROOT));
3709 n_pstate |= n_PS_ROOT; /* Allow calling addhist() */
3710 lbuf = NULL;
3711 lsize = 0;
3712 cnt = (size_t)fsize(f);
3713 while(fgetline(&lbuf, &lsize, &cnt, &llen, f, FAL0) != NULL){
3714 if(llen > 0 && lbuf[llen - 1] == '\n')
3715 lbuf[--llen] = '\0';
3716 if(llen == 0 || lbuf[0] == '#') /* xxx comments? noone! */
3717 continue;
3718 else{
3719 bool_t isgabby;
3721 isgabby = (lbuf[0] == '*');
3722 n_tty_addhist(lbuf + isgabby, isgabby);
3725 if(lbuf != NULL)
3726 free(lbuf);
3727 n_pstate &= ~n_PS_ROOT;
3729 fclose(f);
3730 jhist_done:
3731 rele_all_sigs(); /* XXX remove jumps */
3732 }while(0);
3733 # endif /* HAVE_HISTORY */
3735 /* Force immediate resolve for anything which follows */
3736 n_psonce |= n_PSO_LINE_EDITOR_INIT;
3738 # ifdef HAVE_KEY_BINDINGS
3739 /* `bind's (and `unbind's) done from within resource files couldn't be
3740 * performed for real since our termcap driver wasn't yet loaded, and we
3741 * can't perform automatic init since the user may have disallowed so */
3742 /* C99 */{
3743 struct a_tty_bind_ctx *tbcp;
3744 enum n_go_input_flags gif;
3746 for(gif = 0; gif < n__GO_INPUT_CTX_MAX1; ++gif)
3747 for(tbcp = a_tty.tg_bind[gif]; tbcp != NULL; tbcp = tbcp->tbc_next)
3748 if((tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
3749 a_TTY_BIND_RESOLVE)
3750 a_tty_bind_resolve(tbcp);
3753 /* And we want to (try to) install some default key bindings */
3754 if(!ok_blook(line_editor_no_defaults)){
3755 char buf[8];
3756 struct a_tty_bind_parse_ctx tbpc;
3757 struct a_tty_bind_builtin_tuple const *tbbtp, *tbbtp_max;
3758 ui32_t flags;
3760 buf[0] = '$', buf[1] = '\'', buf[2] = '\\', buf[3] = 'c',
3761 buf[5] = '\'', buf[6] = '\0';
3763 tbbtp = a_tty_bind_base_tuples;
3764 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_base_tuples)];
3765 flags = n_GO_INPUT_CTX_BASE;
3766 jbuiltin_redo:
3767 for(; tbbtp < tbbtp_max; ++tbbtp){
3768 memset(&tbpc, 0, sizeof tbpc);
3769 tbpc.tbpc_cmd = "bind";
3770 if(tbbtp->tbbt_iskey){
3771 buf[4] = tbbtp->tbbt_ckey;
3772 tbpc.tbpc_in_seq = buf;
3773 }else
3774 tbpc.tbpc_in_seq = savecatsep(":", '\0',
3775 n_termcap_name_of_query(tbbtp->tbbt_query));
3776 tbpc.tbpc_exp.s = n_UNCONST(tbbtp->tbbt_exp[0] == '\0'
3777 ? a_tty_bind_fun_names[(ui8_t)tbbtp->tbbt_exp[1]]
3778 : tbbtp->tbbt_exp);
3779 tbpc.tbpc_exp.l = strlen(tbpc.tbpc_exp.s);
3780 tbpc.tbpc_flags = flags;
3781 /* ..but don't want to overwrite any user settings */
3782 a_tty_bind_create(&tbpc, FAL0);
3784 if(flags == n_GO_INPUT_CTX_BASE){
3785 tbbtp = a_tty_bind_default_tuples;
3786 tbbtp_max = &tbbtp[n_NELEM(a_tty_bind_default_tuples)];
3787 flags = n_GO_INPUT_CTX_DEFAULT;
3788 goto jbuiltin_redo;
3791 # endif /* HAVE_KEY_BINDINGS */
3793 jleave:
3794 NYD_LEAVE;
3797 FL void
3798 n_tty_destroy(bool_t xit_fastpath){
3799 NYD_ENTER;
3801 if(!(n_psonce & n_PSO_LINE_EDITOR_INIT))
3802 goto jleave;
3804 # ifdef HAVE_HISTORY
3805 if(!xit_fastpath) do/* for break */{
3806 size_t i;
3807 char const *v;
3808 struct a_tty_hist *thp;
3809 bool_t dogabby;
3810 FILE *f;
3812 if((v = a_tty_hist_query_config()) == NULL ||
3813 a_tty.tg_hist_size_max == 0)
3814 break;
3816 dogabby = ok_blook(history_gabby_persist);
3818 if((thp = a_tty.tg_hist) != NULL)
3819 for(i = a_tty.tg_hist_size_max; thp->th_older != NULL;
3820 thp = thp->th_older)
3821 if((dogabby || !thp->th_isgabby) && --i == 0)
3822 break;
3824 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
3825 f = fopen(v, "w"); /* TODO temporary + rename?! */
3826 if(f == NULL)
3827 goto jhist_done;
3828 (void)n_file_lock(fileno(f), FLT_WRITE, 0,0, UIZ_MAX);
3830 for(; thp != NULL; thp = thp->th_younger){
3831 if(dogabby || !thp->th_isgabby){
3832 if(thp->th_isgabby)
3833 putc('*', f);
3834 fwrite(thp->th_dat, sizeof *thp->th_dat, thp->th_len, f);
3835 putc('\n', f);
3838 fclose(f);
3839 jhist_done:
3840 rele_all_sigs(); /* XXX remove jumps */
3841 }while(0);
3842 # endif /* HAVE_HISTORY */
3844 # if defined HAVE_KEY_BINDINGS && defined HAVE_DEBUG
3845 n_go_command(n_GO_INPUT_NONE, "unbind * *");
3846 # endif
3848 # ifdef HAVE_DEBUG
3849 memset(&a_tty, 0, sizeof a_tty);
3851 n_psonce &= ~n_PSO_LINE_EDITOR_INIT;
3852 # endif
3853 jleave:
3854 NYD_LEAVE;
3857 FL void
3858 n_tty_signal(int sig){
3859 sigset_t nset, oset;
3860 NYD_X; /* Signal handler */
3862 switch(sig){
3863 # ifdef SIGWINCH
3864 case SIGWINCH:
3865 /* We don't deal with SIGWINCH, yet get called from main.c.
3866 * Note this case might get called even if !n_PO_LINE_EDITOR_INIT */
3867 break;
3868 # endif
3869 default:
3870 n_COLOUR( n_colour_env_gut(); ) /* TODO NO SIMPLE SUSPENSION POSSIBLE.. */
3871 a_tty_term_mode(FAL0);
3872 n_TERMCAP_SUSPEND(TRU1);
3873 a_tty_sigs_down();
3875 sigemptyset(&nset);
3876 sigaddset(&nset, sig);
3877 sigprocmask(SIG_UNBLOCK, &nset, &oset);
3878 n_raise(sig);
3879 /* When we come here we'll continue editing, so reestablish */
3880 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
3882 /* TODO THEREFORE NEED TO _GUT() .. _CREATE() ENTIRE ENVS!! */
3883 n_COLOUR( n_colour_env_create(n_COLOUR_CTX_MLE, n_tty_fp, FAL0); )
3884 a_tty_sigs_up();
3885 n_TERMCAP_RESUME(TRU1);
3886 a_tty_term_mode(TRU1);
3887 a_tty.tg_line->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
3888 break;
3892 FL int
3893 (n_tty_readline)(enum n_go_input_flags gif, char const *prompt,
3894 char **linebuf, size_t *linesize, size_t n, bool_t *histok_or_null
3895 n_MEMORY_DEBUG_ARGS){
3896 struct a_tty_line tl;
3897 struct n_string xprompt;
3898 # ifdef HAVE_COLOUR
3899 char *posbuf, *pos;
3900 # endif
3901 ssize_t nn;
3902 NYD_ENTER;
3903 n_UNUSED(gif);
3905 assert(!ok_blook(line_editor_disable));
3906 if(!(n_psonce & n_PSO_LINE_EDITOR_INIT))
3907 n_tty_init();
3908 assert(n_psonce & n_PSO_LINE_EDITOR_INIT);
3910 # ifdef HAVE_COLOUR
3911 n_colour_env_create(n_COLOUR_CTX_MLE, n_tty_fp, FAL0);
3913 /* .tl_pos_buf is a hack */
3914 posbuf = pos = NULL;
3916 if(n_COLOUR_IS_ACTIVE()){
3917 char const *ccol;
3918 struct n_colour_pen *ccp;
3919 struct str const *sp;
3921 if((ccp = n_colour_pen_create(n_COLOUR_ID_MLE_POSITION, NULL)) != NULL &&
3922 (sp = n_colour_pen_to_str(ccp)) != NULL){
3923 ccol = sp->s;
3924 if((sp = n_colour_reset_to_str()) != NULL){
3925 size_t l1, l2;
3927 l1 = strlen(ccol);
3928 l2 = strlen(sp->s);
3929 posbuf = salloc(l1 + 4 + l2 +1);
3930 memcpy(posbuf, ccol, l1);
3931 pos = &posbuf[l1];
3932 memcpy(&pos[4], sp->s, ++l2);
3937 if(posbuf == NULL){
3938 posbuf = pos = salloc(4 +1);
3939 pos[4] = '\0';
3941 # endif /* HAVE_COLOUR */
3943 memset(&tl, 0, sizeof tl);
3945 # ifdef HAVE_KEY_BINDINGS
3946 /* C99 */{
3947 char const *cp;
3949 if((cp = ok_vlook(bind_timeout)) != NULL){
3950 ui64_t uib;
3952 n_idec_ui64_cp(&uib, cp, 0, NULL);
3954 if(uib > 0 &&
3955 /* Convert to tenths of a second, unfortunately */
3956 (uib = (uib + 99) / 100) <= a_TTY_BIND_TIMEOUT_MAX)
3957 tl.tl_bind_timeout = (ui8_t)uib;
3958 else if(n_poption & n_PO_D_V)
3959 n_err(_("Ignoring invalid *bind-timeout*: %s\n"), cp);
3963 if(a_tty.tg_bind_isdirty)
3964 a_tty_bind_tree_teardown();
3965 if(a_tty.tg_bind_cnt > 0 && !a_tty.tg_bind_isbuild)
3966 a_tty_bind_tree_build();
3967 tl.tl_bind_tree_hmap = &a_tty.tg_bind_tree[gif & n__GO_INPUT_CTX_MASK];
3968 tl.tl_bind_shcut_cancel =
3969 &a_tty.tg_bind_shcut_cancel[gif & n__GO_INPUT_CTX_MASK];
3970 tl.tl_bind_shcut_prompt_char =
3971 &a_tty.tg_bind_shcut_prompt_char[gif & n__GO_INPUT_CTX_MASK];
3972 # endif /* HAVE_KEY_BINDINGS */
3974 # ifdef HAVE_COLOUR
3975 tl.tl_pos_buf = posbuf;
3976 tl.tl_pos = pos;
3977 # endif
3979 if(!(gif & n_GO_INPUT_PROMPT_NONE)){
3980 n_string_creat_auto(&xprompt);
3982 if((tl.tl_prompt_width = n_tty_create_prompt(&xprompt, prompt, gif)
3983 ) > 0){
3984 tl.tl_prompt = n_string_cp_const(&xprompt);
3985 tl.tl_prompt_length = (ui32_t)xprompt.s_len;
3989 tl.tl_line.cbuf = *linebuf;
3990 if(n != 0){
3991 tl.tl_defc.s = savestrbuf(*linebuf, n);
3992 tl.tl_defc.l = n;
3994 tl.tl_x_buf = linebuf;
3995 tl.tl_x_bufsize = linesize;
3997 a_tty.tg_line = &tl;
3998 a_tty_sigs_up();
3999 n_TERMCAP_RESUME(FAL0);
4000 a_tty_term_mode(TRU1);
4001 nn = a_tty_readline(&tl, n, histok_or_null n_MEMORY_DEBUG_ARGSCALL);
4002 n_COLOUR( n_colour_env_gut(); )
4003 a_tty_term_mode(FAL0);
4004 n_TERMCAP_SUSPEND(FAL0);
4005 a_tty_sigs_down();
4006 a_tty.tg_line = NULL;
4008 NYD_LEAVE;
4009 return (int)nn;
4012 FL void
4013 n_tty_addhist(char const *s, bool_t isgabby){
4014 # ifdef HAVE_HISTORY
4015 /* Super-Heavy-Metal: block all sigs, avoid leaks+ on jump */
4016 ui32_t l;
4017 struct a_tty_hist *thp, *othp, *ythp;
4018 # endif
4019 NYD_ENTER;
4020 n_UNUSED(s);
4021 n_UNUSED(isgabby);
4023 # ifdef HAVE_HISTORY
4024 if(*s == '\0' ||
4025 (!(n_psonce & n_PSO_LINE_EDITOR_INIT) && !(n_pstate & n_PS_ROOT)) ||
4026 a_tty.tg_hist_size_max == 0 ||
4027 ok_blook(line_editor_disable) ||
4028 (isgabby && !ok_blook(history_gabby)))
4029 goto j_leave;
4031 l = (ui32_t)strlen(s);
4033 /* Eliminating duplicates is expensive, but simply inacceptable so
4034 * during the load of a potentially large history file! */
4035 if(n_psonce & n_PSO_LINE_EDITOR_INIT)
4036 for(thp = a_tty.tg_hist; thp != NULL; thp = thp->th_older)
4037 if(thp->th_len == l && !strcmp(thp->th_dat, s)){
4038 hold_all_sigs(); /* TODO */
4039 if(thp->th_isgabby)
4040 thp->th_isgabby = !!isgabby;
4041 othp = thp->th_older;
4042 ythp = thp->th_younger;
4043 if(othp != NULL)
4044 othp->th_younger = ythp;
4045 else
4046 a_tty.tg_hist_tail = ythp;
4047 if(ythp != NULL)
4048 ythp->th_older = othp;
4049 else
4050 a_tty.tg_hist = othp;
4051 goto jleave;
4053 hold_all_sigs();
4055 ++a_tty.tg_hist_size;
4056 if((n_psonce & n_PSO_LINE_EDITOR_INIT) &&
4057 a_tty.tg_hist_size > a_tty.tg_hist_size_max){
4058 --a_tty.tg_hist_size;
4059 if((thp = a_tty.tg_hist_tail) != NULL){
4060 if((a_tty.tg_hist_tail = thp->th_younger) == NULL)
4061 a_tty.tg_hist = NULL;
4062 else
4063 a_tty.tg_hist_tail->th_older = NULL;
4064 free(thp);
4068 thp = smalloc(n_VSTRUCT_SIZEOF(struct a_tty_hist, th_dat) + l +1);
4069 thp->th_isgabby = !!isgabby;
4070 thp->th_len = l;
4071 memcpy(thp->th_dat, s, l +1);
4072 jleave:
4073 if((thp->th_older = a_tty.tg_hist) != NULL)
4074 a_tty.tg_hist->th_younger = thp;
4075 else
4076 a_tty.tg_hist_tail = thp;
4077 thp->th_younger = NULL;
4078 a_tty.tg_hist = thp;
4080 rele_all_sigs();
4081 j_leave:
4082 # endif /* HAVE_HISTORY */
4083 NYD_LEAVE;
4086 # ifdef HAVE_HISTORY
4087 FL int
4088 c_history(void *v){
4089 siz_t entry;
4090 struct a_tty_hist *thp;
4091 char **argv;
4092 NYD_ENTER;
4094 if(ok_blook(line_editor_disable)){
4095 n_err(_("history: *line-editor-disable* is set\n"));
4096 goto jerr;
4099 if(!(n_psonce & n_PSO_LINE_EDITOR_INIT)){
4100 n_tty_init();
4101 assert(n_psonce & n_PSO_LINE_EDITOR_INIT);
4104 if(*(argv = v) == NULL)
4105 goto jlist;
4106 if(argv[1] != NULL)
4107 goto jerr;
4108 if(!asccasecmp(*argv, "show"))
4109 goto jlist;
4110 if(!asccasecmp(*argv, "clear"))
4111 goto jclear;
4112 if((n_idec_siz_cp(&entry, *argv, 10, NULL
4113 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
4114 ) == n_IDEC_STATE_CONSUMED)
4115 goto jentry;
4116 jerr:
4117 n_err(_("Synopsis: history: %s\n"),
4118 /* Same string as in cmd-tab.h, still hoping...) */
4119 _("<show> (default), <clear> or select <NO> from editor history"));
4120 v = NULL;
4121 jleave:
4122 NYD_LEAVE;
4123 return (v == NULL ? !STOP : !OKAY); /* xxx 1:bad 0:good -- do some */
4125 jlist:{
4126 size_t i, b;
4127 FILE *fp;
4129 if(a_tty.tg_hist == NULL)
4130 goto jleave;
4132 if((fp = Ftmp(NULL, "hist", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
4133 n_perr(_("tmpfile"), 0);
4134 v = NULL;
4135 goto jleave;
4138 i = a_tty.tg_hist_size;
4139 b = 0;
4140 for(thp = a_tty.tg_hist; thp != NULL;
4141 --i, b += thp->th_len, thp = thp->th_older){
4142 fprintf(fp, "%c%" PRIuZ, (thp->th_isgabby ? '*' : ' '), i);
4143 if(n_poption & n_PO_D_V)
4144 fprintf(fp, " (%" PRIuZ "+%" PRIu32 ")", b, thp->th_len);
4145 putc('\t', fp);
4146 fputs(thp->th_dat, fp);
4147 putc('\n', fp);
4150 page_or_print(fp, i);
4151 Fclose(fp);
4153 goto jleave;
4155 jclear:
4156 while((thp = a_tty.tg_hist) != NULL){
4157 a_tty.tg_hist = thp->th_older;
4158 free(thp);
4160 a_tty.tg_hist_tail = NULL;
4161 a_tty.tg_hist_size = 0;
4162 goto jleave;
4164 jentry:{
4165 siz_t ep;
4167 ep = (entry < 0) ? -entry : entry;
4169 if(ep != 0 && UICMP(z, ep, <=, a_tty.tg_hist_size)){
4170 if(ep != entry)
4171 --ep;
4172 else
4173 ep = (siz_t)a_tty.tg_hist_size - ep;
4174 for(thp = a_tty.tg_hist;; thp = thp->th_older){
4175 assert(thp != NULL);
4176 if(ep-- == 0){
4177 n_go_input_inject((n_GO_INPUT_INJECT_COMMIT |
4178 n_GO_INPUT_INJECT_HISTORY), v = thp->th_dat, thp->th_len);
4179 break;
4182 }else{
4183 n_err(_("`history': no such entry: %" PRIdZ "\n"), entry);
4184 v = NULL;
4187 goto jleave;
4189 # endif /* HAVE_HISTORY */
4191 # ifdef HAVE_KEY_BINDINGS
4192 FL int
4193 c_bind(void *v){
4194 struct a_tty_bind_ctx *tbcp;
4195 enum n_go_input_flags gif;
4196 bool_t aster, show;
4197 union {char const *cp; char *p; char c;} c;
4198 struct n_cmd_arg_ctx *cacp;
4199 NYD_ENTER;
4201 cacp = v;
4203 c.cp = cacp->cac_arg->ca_arg.ca_str.s;
4204 if(cacp->cac_no == 1)
4205 show = TRU1;
4206 else
4207 show = !asccasecmp(cacp->cac_arg->ca_next->ca_arg.ca_str.s, "show");
4208 aster = FAL0;
4210 if((gif = a_tty_bind_ctx_find(c.cp)) == (enum n_go_input_flags)-1){
4211 if(!(aster = n_is_all_or_aster(c.cp)) || !show){
4212 n_err(_("`bind': invalid context: %s\n"), c.cp);
4213 v = NULL;
4214 goto jleave;
4216 gif = 0;
4219 if(show){
4220 ui32_t lns;
4221 FILE *fp;
4223 if((fp = Ftmp(NULL, "bind", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
4224 n_perr(_("tmpfile"), 0);
4225 v = NULL;
4226 goto jleave;
4229 lns = 0;
4230 for(;;){
4231 for(tbcp = a_tty.tg_bind[gif]; tbcp != NULL;
4232 ++lns, tbcp = tbcp->tbc_next){
4233 /* Print the bytes of resolved terminal capabilities, then */
4234 if((n_poption & n_PO_D_V) &&
4235 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)
4236 ) == a_TTY_BIND_RESOLVE){
4237 char cbuf[8];
4238 union {wchar_t const *wp; char const *cp;} u;
4239 si32_t entlen;
4240 ui32_t cnvlen;
4241 char const *cnvdat, *bsep, *cbufp;
4243 putc('#', fp);
4244 putc(' ', fp);
4246 cbuf[0] = '=', cbuf[2] = '\0';
4247 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len;
4248 cnvlen > 0;){
4249 if(cnvdat != tbcp->tbc_cnv)
4250 putc(',', fp);
4252 /* {si32_t buf_len_iscap;} */
4253 entlen = *n_UNALIGN(si32_t const*,cnvdat);
4254 if(entlen & SI32_MIN){
4255 /* struct{si32_t buf_len_iscap; si32_t cap_len;
4256 * char buf[]+NUL;} */
4257 for(bsep = n_empty,
4258 u.cp = (char const*)
4259 &n_UNALIGN(si32_t const*,cnvdat)[2];
4260 (c.c = *u.cp) != '\0'; ++u.cp){
4261 if(asciichar(c.c) && !cntrlchar(c.c))
4262 cbuf[1] = c.c, cbufp = cbuf;
4263 else
4264 cbufp = n_empty;
4265 fprintf(fp, "%s%02X%s",
4266 bsep, (ui32_t)(ui8_t)c.c, cbufp);
4267 bsep = " ";
4269 entlen &= SI32_MAX;
4270 }else
4271 putc('-', fp);
4273 cnvlen -= entlen;
4274 cnvdat += entlen;
4277 fputs("\n ", fp);
4278 ++lns;
4281 fprintf(fp, "%sbind %s %s %s%s%s\n",
4282 ((tbcp->tbc_flags & a_TTY_BIND_DEFUNCT)
4283 /* I18N: `bind' sequence not working, either because it is
4284 * I18N: using Unicode and that is not available in the locale,
4285 * I18N: or a termcap(5)/terminfo(5) sequence won't work out */
4286 ? _("# <Defunctional> ") : n_empty),
4287 a_tty_bind_ctx_maps[gif].tbcm_name, tbcp->tbc_seq,
4288 n_shexp_quote_cp(tbcp->tbc_exp, TRU1),
4289 (tbcp->tbc_flags & a_TTY_BIND_NOCOMMIT ? n_at : n_empty),
4290 (!(n_poption & n_PO_D_VV) ? n_empty
4291 : (tbcp->tbc_flags & a_TTY_BIND_FUN_INTERNAL
4292 ? _(" # MLE internal") : n_empty))
4295 if(!aster || ++gif >= n__GO_INPUT_CTX_MAX1)
4296 break;
4298 page_or_print(fp, lns);
4300 Fclose(fp);
4301 }else{
4302 struct a_tty_bind_parse_ctx tbpc;
4303 struct n_cmd_arg *cap;
4305 memset(&tbpc, 0, sizeof tbpc);
4306 tbpc.tbpc_cmd = cacp->cac_desc->cad_name;
4307 tbpc.tbpc_in_seq = (cap = cacp->cac_arg->ca_next)->ca_arg.ca_str.s;
4308 if((cap = cap->ca_next) != NULL){
4309 tbpc.tbpc_exp.s = cap->ca_arg.ca_str.s;
4310 tbpc.tbpc_exp.l = cap->ca_arg.ca_str.l;
4312 tbpc.tbpc_flags = gif;
4313 if(!a_tty_bind_create(&tbpc, TRU1))
4314 v = NULL;
4316 jleave:
4317 NYD_LEAVE;
4318 return (v != NULL) ? n_EXIT_OK : n_EXIT_ERR;
4321 FL int
4322 c_unbind(void *v){
4323 struct a_tty_bind_parse_ctx tbpc;
4324 struct a_tty_bind_ctx *tbcp;
4325 enum n_go_input_flags gif;
4326 bool_t aster;
4327 union {char const *cp; char *p;} c;
4328 struct n_cmd_arg_ctx *cacp;
4329 NYD_ENTER;
4331 cacp = v;
4332 c.cp = cacp->cac_arg->ca_arg.ca_str.s;
4333 aster = FAL0;
4335 if((gif = a_tty_bind_ctx_find(c.cp)) == (enum n_go_input_flags)-1){
4336 if(!(aster = n_is_all_or_aster(c.cp))){
4337 n_err(_("`unbind': invalid context: %s\n"), c.cp);
4338 v = NULL;
4339 goto jleave;
4341 gif = 0;
4344 c.cp = cacp->cac_arg->ca_next->ca_arg.ca_str.s;
4345 jredo:
4346 if(n_is_all_or_aster(c.cp)){
4347 while((tbcp = a_tty.tg_bind[gif]) != NULL){
4348 memset(&tbpc, 0, sizeof tbpc);
4349 tbpc.tbpc_tbcp = tbcp;
4350 tbpc.tbpc_flags = gif;
4351 a_tty_bind_del(&tbpc);
4353 }else{
4354 memset(&tbpc, 0, sizeof tbpc);
4355 tbpc.tbpc_cmd = cacp->cac_desc->cad_name;
4356 tbpc.tbpc_in_seq = c.cp;
4357 tbpc.tbpc_flags = gif;
4359 if(n_UNLIKELY(!a_tty_bind_parse(FAL0, &tbpc)))
4360 v = NULL;
4361 else if(n_UNLIKELY((tbcp = tbpc.tbpc_tbcp) == NULL)){
4362 n_err(_("`unbind': no such `bind'ing: %s %s\n"),
4363 a_tty_bind_ctx_maps[gif].tbcm_name, c.cp);
4364 v = NULL;
4365 }else
4366 a_tty_bind_del(&tbpc);
4369 if(aster && ++gif < n__GO_INPUT_CTX_MAX1)
4370 goto jredo;
4371 jleave:
4372 NYD_LEAVE;
4373 return (v != NULL) ? n_EXIT_OK : n_EXIT_ERR;
4375 # endif /* HAVE_KEY_BINDINGS */
4377 #else /* HAVE_MLE */
4379 * The really-nothing-at-all implementation
4382 # if 0
4383 FL void
4384 n_tty_init(void){
4385 NYD_ENTER;
4386 NYD_LEAVE;
4389 FL void
4390 n_tty_destroy(bool_t xit_fastpath){
4391 NYD_ENTER;
4392 n_UNUSED(xit_fastpath);
4393 NYD_LEAVE;
4395 # endif /* 0 */
4397 FL void
4398 n_tty_signal(int sig){
4399 NYD_X; /* Signal handler */
4400 n_UNUSED(sig);
4402 # ifdef HAVE_TERMCAP
4403 switch(sig){
4404 default:{
4405 sigset_t nset, oset;
4407 n_TERMCAP_SUSPEND(TRU1);
4408 a_tty_sigs_down();
4410 sigemptyset(&nset);
4411 sigaddset(&nset, sig);
4412 sigprocmask(SIG_UNBLOCK, &nset, &oset);
4413 n_raise(sig);
4414 /* When we come here we'll continue editing, so reestablish */
4415 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
4417 a_tty_sigs_up();
4418 n_TERMCAP_RESUME(TRU1);
4419 break;
4422 # endif /* HAVE_TERMCAP */
4425 FL int
4426 (n_tty_readline)(enum n_go_input_flags gif, char const *prompt,
4427 char **linebuf, size_t *linesize, size_t n, bool_t *histok_or_null
4428 n_MEMORY_DEBUG_ARGS){
4429 struct n_string xprompt;
4430 int rv;
4431 NYD_ENTER;
4432 n_UNUSED(histok_or_null);
4434 if(!(gif & n_GO_INPUT_PROMPT_NONE)){
4435 if(n_tty_create_prompt(n_string_creat_auto(&xprompt), prompt, gif) > 0){
4436 fwrite(xprompt.s_dat, 1, xprompt.s_len, n_tty_fp);
4437 fflush(n_tty_fp);
4441 # ifdef HAVE_TERMCAP
4442 a_tty_sigs_up();
4443 n_TERMCAP_RESUME(FAL0);
4444 # endif
4445 rv = (readline_restart)(n_stdin, linebuf, linesize,n n_MEMORY_DEBUG_ARGSCALL);
4446 # ifdef HAVE_TERMCAP
4447 n_TERMCAP_SUSPEND(FAL0);
4448 a_tty_sigs_down();
4449 # endif
4450 NYD_LEAVE;
4451 return rv;
4454 FL void
4455 n_tty_addhist(char const *s, bool_t isgabby){
4456 NYD_ENTER;
4457 n_UNUSED(s);
4458 n_UNUSED(isgabby);
4459 NYD_LEAVE;
4461 #endif /* nothing at all */
4463 #undef a_TTY_SIGNALS
4464 /* s-it-mode */