`bind': new "default" context and changed "base" semantics..
[s-mailx.git] / tty.c
blob4b744533cd1928319199b2b8b616ee823eb03e63
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ TTY (command line) editing interaction.
3 *@ Because we have multiple line-editor implementations, including our own
4 *@ M(ailx) L(ine) E(ditor), change the file layout a bit and place those
5 *@ one after the other below the other externals.
7 * Copyright (c) 2012 - 2016 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 /* History support macros */
33 #ifdef HAVE_HISTORY
34 # define a_TTY_HISTFILE(S) \
35 do{\
36 char const *__hist_obsolete = ok_vlook(NAIL_HISTFILE);\
37 if(__hist_obsolete != NULL)\
38 OBSOLETE(_("please use *history-file* instead of *NAIL_HISTFILE*"));\
39 S = ok_vlook(history_file);\
40 if((S) == NULL)\
41 (S) = __hist_obsolete;\
42 if((S) != NULL)\
43 S = fexpand(S, FEXP_LOCAL | FEXP_NSHELL);\
44 }while(0)
46 # define a_TTY_HISTSIZE(V) \
47 do{\
48 char const *__hist_obsolete = ok_vlook(NAIL_HISTSIZE);\
49 char const *__sv = ok_vlook(history_size);\
50 long __rv;\
51 if(__hist_obsolete != NULL)\
52 OBSOLETE(_("please use *history-size* instead of *NAIL_HISTSIZE*"));\
53 if(__sv == NULL)\
54 __sv = __hist_obsolete;\
55 if(__sv == NULL || (__rv = strtol(__sv, NULL, 10)) == 0)\
56 __rv = HIST_SIZE;\
57 else if(__rv < 0)\
58 __rv = 0;\
59 (V) = __rv;\
60 }while(0)
62 # define a_TTY_CHECK_ADDHIST(S,ISGABBY,NOACT) \
63 do{\
64 if(!(pstate & (PS_ROOT | PS_LINE_EDITOR_INIT)) ||\
65 ok_blook(line_editor_disable) ||\
66 ((ISGABBY) && !ok_blook(history_gabby)) ||\
67 spacechar(*(S)) || *(S) == '\0')\
68 NOACT;\
69 }while(0)
71 # define C_HISTORY_SHARED \
72 char **argv = v;\
73 long entry;\
74 NYD_ENTER;\
76 if(ok_blook(line_editor_disable)){\
77 n_err(_("history: *line-editor-disable* is set\n"));\
78 goto jerr;\
80 if(!(pstate & PS_LINE_EDITOR_INIT)){\
81 n_tty_init();\
82 assert(pstate & PS_LINE_EDITOR_INIT);\
84 if(*argv == NULL)\
85 goto jlist;\
86 if(argv[1] != NULL)\
87 goto jerr;\
88 if(!asccasecmp(*argv, "show"))\
89 goto jlist;\
90 if(!asccasecmp(*argv, "clear"))\
91 goto jclear;\
92 if((entry = strtol(*argv, argv, 10)) > 0 && **argv == '\0')\
93 goto jentry;\
94 jerr:\
95 n_err(_("Synopsis: history: %s\n"),\
96 /* Same string as in cmd_tab.h, still hoping...) */\
97 _("<show> (default), <clear> or select <NO> from editor history"));\
98 v = NULL;\
99 jleave:\
100 NYD_LEAVE;\
101 return (v == NULL ? !STOP : !OKAY); /* xxx 1:bad 0:good -- do some */
102 #endif /* HAVE_HISTORY */
104 #ifdef a_TTY_SIGNALS
105 static sighandler_type a_tty_oint, a_tty_oquit, a_tty_oterm,
106 a_tty_ohup,
107 a_tty_otstp, a_tty_ottin, a_tty_ottou;
108 #endif
110 #ifdef a_TTY_SIGNALS
111 static void a_tty_sigs_up(void), a_tty_sigs_down(void);
112 #endif
114 #ifdef a_TTY_SIGNALS
115 static void
116 a_tty_sigs_up(void){
117 sigset_t nset, oset;
118 NYD2_ENTER;
120 sigfillset(&nset);
122 sigprocmask(SIG_BLOCK, &nset, &oset);
123 a_tty_oint = safe_signal(SIGINT, &n_tty_signal);
124 a_tty_oquit = safe_signal(SIGQUIT, &n_tty_signal);
125 a_tty_oterm = safe_signal(SIGTERM, &n_tty_signal);
126 a_tty_ohup = safe_signal(SIGHUP, &n_tty_signal);
127 a_tty_otstp = safe_signal(SIGTSTP, &n_tty_signal);
128 a_tty_ottin = safe_signal(SIGTTIN, &n_tty_signal);
129 a_tty_ottou = safe_signal(SIGTTOU, &n_tty_signal);
130 sigprocmask(SIG_SETMASK, &oset, NULL);
131 NYD2_LEAVE;
134 static void
135 a_tty_sigs_down(void){
136 sigset_t nset, oset;
137 NYD2_ENTER;
139 sigfillset(&nset);
141 sigprocmask(SIG_BLOCK, &nset, &oset);
142 safe_signal(SIGINT, a_tty_oint);
143 safe_signal(SIGQUIT, a_tty_oquit);
144 safe_signal(SIGTERM, a_tty_oterm);
145 safe_signal(SIGHUP, a_tty_ohup);
146 safe_signal(SIGTSTP, a_tty_otstp);
147 safe_signal(SIGTTIN, a_tty_ottin);
148 safe_signal(SIGTTOU, a_tty_ottou);
149 sigprocmask(SIG_SETMASK, &oset, NULL);
150 NYD2_LEAVE;
152 #endif /* a_TTY_SIGNALS */
154 static sigjmp_buf a_tty__actjmp; /* TODO someday, we won't need it no more */
155 static void
156 a_tty__acthdl(int s) /* TODO someday, we won't need it no more */
158 NYD_X; /* Signal handler */
159 termios_state_reset();
160 siglongjmp(a_tty__actjmp, s);
163 FL bool_t
164 getapproval(char const * volatile prompt, bool_t noninteract_default)
166 sighandler_type volatile oint, ohup;
167 bool_t volatile rv;
168 int volatile sig;
169 NYD_ENTER;
171 if (!(options & OPT_INTERACTIVE)) {
172 sig = 0;
173 rv = noninteract_default;
174 goto jleave;
176 rv = FAL0;
178 /* C99 */{
179 char const *quest = noninteract_default
180 ? _("[yes]/no? ") : _("[no]/yes? ");
182 if (prompt == NULL)
183 prompt = _("Continue");
184 prompt = savecatsep(prompt, ' ', quest);
187 oint = safe_signal(SIGINT, SIG_IGN);
188 ohup = safe_signal(SIGHUP, SIG_IGN);
189 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
190 goto jrestore;
191 safe_signal(SIGINT, &a_tty__acthdl);
192 safe_signal(SIGHUP, &a_tty__acthdl);
194 if (n_lex_input(n_LEXINPUT_CTX_DEFAULT | n_LEXINPUT_NL_ESC, prompt,
195 &termios_state.ts_linebuf, &termios_state.ts_linesize, NULL) >= 0)
196 rv = (boolify(termios_state.ts_linebuf, UIZ_MAX,
197 noninteract_default) > 0);
198 jrestore:
199 termios_state_reset();
201 safe_signal(SIGHUP, ohup);
202 safe_signal(SIGINT, oint);
203 jleave:
204 NYD_LEAVE;
205 if (sig != 0)
206 n_raise(sig);
207 return rv;
210 #ifdef HAVE_SOCKETS
211 FL char *
212 getuser(char const * volatile query) /* TODO v15-compat obsolete */
214 sighandler_type volatile oint, ohup;
215 char * volatile user = NULL;
216 int volatile sig;
217 NYD_ENTER;
219 if (query == NULL)
220 query = _("User: ");
222 oint = safe_signal(SIGINT, SIG_IGN);
223 ohup = safe_signal(SIGHUP, SIG_IGN);
224 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
225 goto jrestore;
226 safe_signal(SIGINT, &a_tty__acthdl);
227 safe_signal(SIGHUP, &a_tty__acthdl);
229 if (n_lex_input(n_LEXINPUT_CTX_DEFAULT | n_LEXINPUT_NL_ESC, query,
230 &termios_state.ts_linebuf, &termios_state.ts_linesize, NULL) >= 0)
231 user = termios_state.ts_linebuf;
232 jrestore:
233 termios_state_reset();
235 safe_signal(SIGHUP, ohup);
236 safe_signal(SIGINT, oint);
237 NYD_LEAVE;
238 if (sig != 0)
239 n_raise(sig);
240 return user;
243 FL char *
244 getpassword(char const *query)
246 sighandler_type volatile oint, ohup;
247 struct termios tios;
248 char * volatile pass = NULL;
249 int volatile sig;
250 NYD_ENTER;
252 if (query == NULL)
253 query = _("Password: ");
254 fputs(query, stdout);
255 fflush(stdout);
257 /* FIXME everywhere: tcsetattr() generates SIGTTOU when we're not in
258 * FIXME foreground pgrp, and can fail with EINTR!! also affects
259 * FIXME termios_state_reset() */
260 if (options & OPT_TTYIN) {
261 tcgetattr(STDIN_FILENO, &termios_state.ts_tios);
262 memcpy(&tios, &termios_state.ts_tios, sizeof tios);
263 termios_state.ts_needs_reset = TRU1;
264 tios.c_iflag &= ~(ISTRIP);
265 tios.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
268 oint = safe_signal(SIGINT, SIG_IGN);
269 ohup = safe_signal(SIGHUP, SIG_IGN);
270 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
271 goto jrestore;
272 safe_signal(SIGINT, &a_tty__acthdl);
273 safe_signal(SIGHUP, &a_tty__acthdl);
275 if (options & OPT_TTYIN)
276 tcsetattr(STDIN_FILENO, TCSAFLUSH, &tios);
278 if (readline_restart(stdin, &termios_state.ts_linebuf,
279 &termios_state.ts_linesize, 0) >= 0)
280 pass = termios_state.ts_linebuf;
281 jrestore:
282 termios_state_reset();
283 if (options & OPT_TTYIN)
284 putc('\n', stdout);
286 safe_signal(SIGHUP, ohup);
287 safe_signal(SIGINT, oint);
288 NYD_LEAVE;
289 if (sig != 0)
290 n_raise(sig);
291 return pass;
293 #endif /* HAVE_SOCKETS */
296 * MLE: the Mailx-Line-Editor, our homebrew editor
297 * (inspired from NetBSDs sh(1) and dash(1)s hetio.c).
299 * Only used in interactive mode, simply use STDIN_FILENO as point of interest.
300 * TODO . This code should be splitted in funs/raw input/bind modules.
301 * TODO . After I/O layer rewrite, also "output to STDIN_FILENO".
302 * TODO . We work with wide characters, but not for buffer takeovers and
303 * TODO cell2save()ings. This should be changed. For the former the buffer
304 * TODO thus needs to be converted to wide first, and then simply be fed in.
305 * TODO . We repaint too much. To overcome this use the same approach that my
306 * TODO terminal library uses, add a true "virtual screen line" that stores
307 * TODO the actually visible content, keep a notion of "first modified slot"
308 * TODO and "last modified slot" (including "unknown" and "any" specials),
309 * TODO update that virtual instead, then synchronize what has truly changed.
310 * TODO I.e., add an indirection layer.
311 * TODO . No BIDI support.
312 * TODO . `bind': we currently use only one lookup tree.
313 * TODO For absolute graceful behaviour in conjunction (with HAVE_TERMCAP) we
314 * TODO need a lower level tree, which possibly combines bytes into "symbolic
315 * TODO wchar_t values", into "keys" that is, as applicable, and an upper
316 * TODO layer which only works on "keys" in order to possibly combine them
317 * TODO into key sequences. We can reuse existent tree code for that.
318 * TODO We need an additional hashmap which maps termcap/terminfo names to
319 * TODO (their byte representations and) a dynamically assigned unique
320 * TODO "symbolic wchar_t value". This implies we may have incompatibilities
321 * TODO when __STDC_ISO_10646__ is not defined. Also we do need takeover-
322 * TODO bytes storage, but it can be a string_creat_auto in the line struct.
323 * TODO Until then we can run into ambiguities; in rare occasions.
325 #ifdef HAVE_MLE
326 /* To avoid memory leaks etc. with the current codebase that simply longjmp(3)s
327 * we're forced to use the very same buffer--the one that is passed through to
328 * us from the outside--to store anything we need, i.e., a "struct cell[]", and
329 * convert that on-the-fly back to the plain char* result once we're done.
330 * To simplify our live, use savestr() buffers for all other needed memory */
332 # ifdef HAVE_KEY_BINDINGS
333 /* Default *bind-timeout* key-sequence continuation timeout, in tenths of
334 * a second. Must fit in 8-bit! Update the manual upon change! */
335 # define a_TTY_BIND_TIMEOUT 2
336 # define a_TTY_BIND_TIMEOUT_MAX SI8_MAX
338 n_CTAV(a_TTY_BIND_TIMEOUT_MAX <= UI8_MAX);
340 /* We have a chicken-and-egg problem with `bind' and our termcap layer,
341 * because we may not initialize the latter automatically to allow users to
342 * specify *termcap-disable* and let it mean exactly that.
343 * On the other hand users can be expected to use `bind' in resource file(s).
344 * Therefore bindings which involve termcap/terminfo sequences, and which are
345 * defined before PS_STARTED signals usability of termcap/terminfo, will be
346 * (partially) delayed until tty_init() is called.
347 * And we preallocate space for the expansion of the resolved capability */
348 # define a_TTY_BIND_CAPNAME_MAX 15
349 # define a_TTY_BIND_CAPEXP_ROUNDUP 16
351 n_CTAV(n_ISPOW2(a_TTY_BIND_CAPEXP_ROUNDUP));
352 n_CTA(a_TTY_BIND_CAPEXP_ROUNDUP <= SI8_MAX / 2, "Variable must fit in 6-bit");
353 n_CTA(a_TTY_BIND_CAPEXP_ROUNDUP >= 8, "Variable too small");
354 # endif /* HAVE_KEY_BINDINGS */
356 /* The maximum size (of a_tty_cell's) in a line */
357 # define a_TTY_LINE_MAX SI32_MAX
359 /* (Some more CTAs around) */
360 n_CTA(a_TTY_LINE_MAX <= SI32_MAX,
361 "a_TTY_LINE_MAX larger than SI32_MAX, but the MLE uses 32-bit arithmetic");
363 /* When shall the visual screen be scrolled, in % of usable screen width */
364 # define a_TTY_SCROLL_MARGIN_LEFT 15
365 # define a_TTY_SCROLL_MARGIN_RIGHT 10
367 /* fexpand() flags for expand-on-tab */
368 # define a_TTY_TAB_FEXP_FL (FEXP_FULL | FEXP_SILENT | FEXP_MULTIOK)
370 /* Columns to ripoff: outermost may not be touched, plus position indicator.
371 * Must thus be at least 1, but should be >= 1+4 to dig the position indicator
372 * that we place (if there is sufficient space) */
373 # define a_TTY_WIDTH_RIPOFF 5
375 /* The implementation of the MLE functions always exists, and is based upon
376 * the a_TTY_BIND_FUN_* constants, so most of this enum is always necessary */
377 enum a_tty_bind_flags{
378 # ifdef HAVE_KEY_BINDINGS
379 a_TTY_BIND_RESOLVE = 1u<<8, /* Term cap. yet needs to be resolved */
380 a_TTY_BIND_DEFUNCT = 1u<<9, /* Unicode/term cap. used but not avail. */
381 a_TTY__BIND_MASK = a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT,
382 /* MLE fun assigned to a one-byte-sequence: this may be used for special
383 * key-sequence bypass processing */
384 a_TTY_BIND_MLE1CNTRL = 1u<<10,
385 a_TTY_BIND_NOCOMMIT = 1u<<11, /* Expansion shall be editable */
386 # endif
388 /* MLE internal commands */
389 a_TTY_BIND_FUN_INTERNAL = 1u<<15,
390 a_TTY__BIND_FUN_SHIFT = 16u,
391 a_TTY__BIND_FUN_SHIFTMAX = 24u,
392 a_TTY__BIND_FUN_MASK = ((1u << a_TTY__BIND_FUN_SHIFTMAX) - 1) &
393 ~((1u << a_TTY__BIND_FUN_SHIFT) - 1),
394 # define a_TTY_BIND_FUN_REDUCE(X) \
395 (((ui32_t)(X) & a_TTY__BIND_FUN_MASK) >> a_TTY__BIND_FUN_SHIFT)
396 # define a_TTY_BIND_FUN_EXPAND(X) \
397 (((ui32_t)(X) & (a_TTY__BIND_FUN_MASK >> a_TTY__BIND_FUN_SHIFT)) << \
398 a_TTY__BIND_FUN_SHIFT)
399 # undef a_X
400 # define a_X(N,I)\
401 a_TTY_BIND_FUN_ ## N = a_TTY_BIND_FUN_EXPAND(I),
403 a_X(BELL, 0)
404 a_X(GO_BWD, 1) a_X(GO_FWD, 2)
405 a_X(GO_WORD_BWD, 3) a_X(GO_WORD_FWD, 4)
406 a_X(GO_HOME, 5) a_X(GO_END, 6)
407 a_X(DEL_BWD, 7) a_X(DEL_FWD, 8)
408 a_X(SNARF_WORD_BWD, 9) a_X(SNARF_WORD_FWD, 10)
409 a_X(SNARF_END, 11) a_X(SNARF_LINE, 12)
410 a_X(HIST_BWD, 13) a_X(HIST_FWD, 14)
411 a_X(HIST_SRCH_BWD, 15) a_X(HIST_SRCH_FWD, 16)
412 a_X(REPAINT, 17)
413 a_X(QUOTE_RNDTRIP, 18)
414 a_X(PROMPT_CHAR, 19)
415 a_X(COMPLETE, 20)
416 a_X(PASTE, 21)
418 a_X(CANCEL, 22)
419 a_X(RESET, 23)
420 a_X(FULLRESET, 24)
421 a_X(COMMIT, 25) /* Must be last one! */
422 # undef a_X
424 a_TTY__BIND_LAST = 1<<25
426 # ifdef HAVE_KEY_BINDINGS
427 n_CTA((ui32_t)a_TTY_BIND_RESOLVE > (ui32_t)n__LEXINPUT_CTX_MAX,
428 "Bit carrier lower boundary must be raised to avoid value sharing");
429 # endif
430 n_CTA(a_TTY_BIND_FUN_EXPAND(a_TTY_BIND_FUN_COMMIT) <
431 (1 << a_TTY__BIND_FUN_SHIFTMAX),
432 "Bit carrier range must be expanded to represent necessary bits");
433 n_CTA(a_TTY__BIND_LAST >= (1u << a_TTY__BIND_FUN_SHIFTMAX),
434 "Bit carrier upper boundary must be raised to avoid value sharing");
435 n_CTA(UICMP(64, a_TTY__BIND_LAST, <=, SI32_MAX),
436 "Flag bits excess storage datatype" /* And we need one bit free */);
438 enum a_tty_fun_status{
439 a_TTY_FUN_STATUS_OK, /* Worked, next character */
440 a_TTY_FUN_STATUS_COMMIT, /* Line done */
441 a_TTY_FUN_STATUS_RESTART, /* Complete restart, reset multibyte etc. */
442 a_TTY_FUN_STATUS_END /* End, return EOF */
445 enum a_tty_visual_flags{
446 a_TTY_VF_NONE,
447 a_TTY_VF_MOD_CURSOR = 1u<<0, /* Cursor moved */
448 a_TTY_VF_MOD_CONTENT = 1u<<1, /* Content modified */
449 a_TTY_VF_MOD_DIRTY = 1u<<2, /* Needs complete repaint */
450 a_TTY_VF_MOD_SINGLE = 1u<<3, /* TODO Drop when indirection as above comes */
451 a_TTY_VF_REFRESH = a_TTY_VF_MOD_DIRTY | a_TTY_VF_MOD_CURSOR |
452 a_TTY_VF_MOD_CONTENT | a_TTY_VF_MOD_SINGLE,
453 a_TTY_VF_BELL = 1u<<8, /* Ring the bell */
454 a_TTY_VF_SYNC = 1u<<9, /* Flush/Sync I/O channel */
456 a_TTY_VF_ALL_MASK = a_TTY_VF_REFRESH | a_TTY_VF_BELL | a_TTY_VF_SYNC,
457 a_TTY__VF_LAST = a_TTY_VF_SYNC
460 # ifdef HAVE_KEY_BINDINGS
461 struct a_tty_bind_ctx{
462 struct a_tty_bind_ctx *tbc_next;
463 char *tbc_seq; /* quence as given (poss. re-quoted), in .tb__buf */
464 char *tbc_exp; /* ansion, in .tb__buf */
465 /* The .tbc_seq'uence with any terminal capabilities resolved; in fact an
466 * array of structures, the first entry of which is {si32_t buf_len_iscap;}
467 * where the signed bit indicates whether the buffer is a resolved terminal
468 * capability instead of a (possibly multibyte) character. In .tbc__buf */
469 char *tbc_cnv;
470 ui32_t tbc_seq_len;
471 ui32_t tbc_exp_len;
472 ui32_t tbc_cnv_len;
473 ui32_t tbc_flags;
474 char tbc__buf[n_VFIELD_SIZE(0)];
477 struct a_tty_bind_ctx_map{
478 enum n_lexinput_flags tbcm_ctx;
479 char const tbcm_name[12]; /* Name of `bind' context */
481 # endif /* HAVE_KEY_BINDINGS */
483 struct a_tty_bind_default_tuple{
484 bool_t tbdt_iskey; /* Whether this is a control key; else termcap query */
485 char tbdt_ckey; /* Control code */
486 ui16_t tbdt_query; /* enum n_termcap_query (instead) */
487 char tbdt_exp[12]; /* String or [0]=NUL/[1]=BIND_FUN_REDUCE() */
489 n_CTA(n__TERMCAP_QUERY_MAX <= UI16_MAX,
490 "Enumeration cannot be stored in datatype");
492 # ifdef HAVE_KEY_BINDINGS
493 struct a_tty_bind_parse_ctx{
494 char const *tbpc_cmd; /* Command which parses */
495 char const *tbpc_in_seq; /* In: key sequence */
496 struct str tbpc_exp; /* In/Out: expansion (or NULL) */
497 struct a_tty_bind_ctx *tbpc_tbcp; /* Out: if yet existent */
498 struct a_tty_bind_ctx *tbpc_ltbcp; /* Out: the one before .tbpc_tbcp */
499 char *tbpc_seq; /* Out: normalized sequence */
500 char *tbpc_cnv; /* Out: sequence when read(2)ing it */
501 ui32_t tbpc_seq_len;
502 ui32_t tbpc_cnv_len;
503 ui32_t tbpc_cnv_align_mask; /* For creating a_tty_bind_ctx.tbc_cnv */
504 ui32_t tbpc_flags; /* n_lexinput_flags | a_tty_bind_flags */
507 /* Input character tree */
508 struct a_tty_bind_tree{
509 struct a_tty_bind_tree *tbt_sibling; /* s at same level */
510 struct a_tty_bind_tree *tbt_childs; /* Sequence continues.. here */
511 struct a_tty_bind_tree *tbt_parent;
512 struct a_tty_bind_ctx *tbt_bind; /* NULL for intermediates */
513 wchar_t tbt_char; /* acter this level represents */
514 bool_t tbt_isseq; /* Belongs to multibyte sequence */
515 bool_t tbt_isseq_trail; /* ..is trailing byte of it */
516 ui8_t tbt__dummy[2];
518 # endif /* HAVE_KEY_BINDINGS */
520 struct a_tty_cell{
521 wchar_t tc_wc;
522 ui16_t tc_count; /* ..of bytes */
523 ui8_t tc_width; /* Visual width; TAB==UI8_MAX! */
524 bool_t tc_novis; /* Don't display visually as such (control character) */
525 char tc_cbuf[MB_LEN_MAX * 2]; /* .. plus reset shift sequence */
528 struct a_tty_global{
529 struct a_tty_line *tg_line; /* To be able to access it from signal hdl */
530 # ifdef HAVE_HISTORY
531 struct a_tty_hist *tg_hist;
532 struct a_tty_hist *tg_hist_tail;
533 size_t tg_hist_size;
534 size_t tg_hist_size_max;
535 # endif
536 # ifdef HAVE_KEY_BINDINGS
537 ui32_t tg_bind_cnt; /* Overall number of bindings */
538 bool_t tg_bind_isdirty;
539 bool_t tg_bind_isbuild;
540 # define a_TTY_SHCUT_MAX (3 +1) /* Note: update manual on change! */
541 ui8_t tg_bind__dummy[2];
542 char tg_bind_shcut_cancel[n__LEXINPUT_CTX_MAX][a_TTY_SHCUT_MAX];
543 char tg_bind_shcut_prompt_char[n__LEXINPUT_CTX_MAX][a_TTY_SHCUT_MAX];
544 struct a_tty_bind_ctx *tg_bind[n__LEXINPUT_CTX_MAX];
545 struct a_tty_bind_tree *tg_bind_tree[n__LEXINPUT_CTX_MAX][HSHSIZE];
546 # endif
547 struct termios tg_tios_old;
548 struct termios tg_tios_new;
550 n_CTA(n__LEXINPUT_CTX_MAX == 3 && a_TTY_SHCUT_MAX == 4 &&
551 n_SIZEOF_FIELD(struct a_tty_global, tg_bind__dummy) == 2,
552 "Value results in array sizes that results in bad structure layout");
553 n_CTA(a_TTY_SHCUT_MAX > 1,
554 "Users need at least one shortcut, plus NUL terminator");
556 # ifdef HAVE_HISTORY
557 struct a_tty_hist{
558 struct a_tty_hist *th_older;
559 struct a_tty_hist *th_younger;
560 # ifdef HAVE_BYTE_ORDER_LITTLE
561 ui32_t th_isgabby : 1;
562 # endif
563 ui32_t th_len : 31;
564 # ifndef HAVE_BYTE_ORDER_LITTLE
565 ui32_t th_isgabby : 1;
566 # endif
567 char th_dat[n_VFIELD_SIZE(sizeof(ui32_t))];
569 # endif
571 struct a_tty_line{
572 /* Caller pointers */
573 char **tl_x_buf;
574 size_t *tl_x_bufsize;
575 /* Input processing */
576 # ifdef HAVE_KEY_BINDINGS
577 wchar_t tl_bind_takeover; /* Leftover byte to consume next */
578 ui8_t tl_bind_timeout; /* In-seq. inter-byte-timer, in 1/10th secs */
579 ui8_t tl__bind_dummy[3];
580 char (*tl_bind_shcut_cancel)[a_TTY_SHCUT_MAX]; /* Special _CANCEL control */
581 char (*tl_bind_shcut_prompt_char)[a_TTY_SHCUT_MAX]; /* ..for _PROMPT_CHAR */
582 struct a_tty_bind_tree *(*tl_bind_tree_hmap)[HSHSIZE]; /* Bind lookup tree */
583 struct a_tty_bind_tree *tl_bind_tree;
584 # endif
585 char const *tl_reenter_after_cmd; /* `bind' cmd to exec, then re-readline */
586 /* Line data / content handling */
587 ui32_t tl_count; /* ..of a_tty_cell's (<= a_TTY_LINE_MAX) */
588 ui32_t tl_cursor; /* Current a_tty_cell insertion point */
589 union{
590 char *cbuf; /* *.tl_x_buf */
591 struct a_tty_cell *cells;
592 } tl_line;
593 struct str tl_defc; /* Current default content */
594 size_t tl_defc_cursor_byte; /* Desired position of cursor after takeover */
595 struct str tl_savec; /* Saved default content */
596 struct str tl_pastebuf; /* Last snarfed data */
597 # ifdef HAVE_HISTORY
598 struct a_tty_hist *tl_hist; /* History cursor */
599 # endif
600 ui32_t tl_count_max; /* ..before buffer needs to grow */
601 /* Visual data representation handling */
602 ui32_t tl_vi_flags; /* enum a_tty_visual_flags */
603 ui32_t tl_lst_count; /* .tl_count after last sync */
604 ui32_t tl_lst_cursor; /* .tl_cursor after last sync */
605 /* TODO Add another indirection layer by adding a tl_phy_line of
606 * TODO a_tty_cell objects, incorporate changes in visual layer,
607 * TODO then check what _really_ has changed, sync those changes only */
608 struct a_tty_cell const *tl_phy_start; /* First visible cell, left border */
609 ui32_t tl_phy_cursor; /* Physical cursor position */
610 bool_t tl_quote_rndtrip; /* For _kht() expansion */
611 ui8_t tl__dummy2[3];
612 ui32_t tl_prompt_length; /* Preclassified (TODO needed as a_tty_cell) */
613 ui32_t tl_prompt_width;
614 char const *tl_prompt; /* Preformatted prompt (including colours) */
615 /* .tl_pos_buf is a hack */
616 # ifdef HAVE_COLOUR
617 char *tl_pos_buf; /* mle-position colour-on, [4], reset seq. */
618 char *tl_pos; /* Address of the [4] */
619 # endif
622 # ifdef HAVE_KEY_BINDINGS
623 /* C99: use [INDEX]={} */
624 n_CTAV(n_LEXINPUT_CTX_BASE == 0);
625 n_CTAV(n_LEXINPUT_CTX_DEFAULT == 1);
626 n_CTAV(n_LEXINPUT_CTX_COMPOSE == 2);
627 static struct a_tty_bind_ctx_map const
628 a_tty_bind_ctx_maps[n__LEXINPUT_CTX_MAX] = {
629 {n_LEXINPUT_CTX_BASE, "base"},
630 {n_LEXINPUT_CTX_DEFAULT, "default"},
631 {n_LEXINPUT_CTX_COMPOSE, "compose"}
634 /* Special functions which our MLE provides internally.
635 * Update the manual upon change! */
636 static char const a_tty_bind_fun_names[][24] = {
637 # undef a_X
638 # define a_X(I,N) \
639 n_FIELD_INITI(a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## I)) "mle-" N "\0",
641 a_X(BELL, "bell")
642 a_X(GO_BWD, "go-bwd") a_X(GO_FWD, "go-fwd")
643 a_X(GO_WORD_BWD, "go-word-bwd") a_X(GO_WORD_FWD, "go-word-fwd")
644 a_X(GO_HOME, "go-home") a_X(GO_END, "go-end")
645 a_X(DEL_BWD, "del-bwd") a_X(DEL_FWD, "del-fwd")
646 a_X(SNARF_WORD_BWD, "snarf-word-bwd") a_X(SNARF_WORD_FWD, "snarf-word-fwd")
647 a_X(SNARF_END, "snarf-end") a_X(SNARF_LINE, "snarf-line")
648 a_X(HIST_BWD, "hist-bwd") a_X(HIST_FWD, "hist-fwd")
649 a_X(HIST_SRCH_BWD, "hist-srch-bwd") a_X(HIST_SRCH_FWD, "hist-srch-fwd")
650 a_X(REPAINT, "repaint")
651 a_X(QUOTE_RNDTRIP, "quote-rndtrip")
652 a_X(PROMPT_CHAR, "prompt-char")
653 a_X(COMPLETE, "complete")
654 a_X(PASTE, "paste")
656 a_X(CANCEL, "cancel")
657 a_X(RESET, "reset")
658 a_X(FULLRESET, "fullreset")
659 a_X(COMMIT, "commit")
661 # undef a_X
663 # endif /* HAVE_KEY_BINDINGS */
665 /* The default key bindings (unless disallowed). Update manual upon change!
666 * A logical subset of this table is also used if !HAVE_KEY_BINDINGS (more
667 * expensive than a switch() on control codes directly, but less redundant) */
668 static struct a_tty_bind_default_tuple const a_tty_bind_default_tuples[] = {
669 # undef a_X
670 # define a_X(K,S) \
671 {TRU1, K, 0, {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
673 a_X('A', GO_HOME)
674 a_X('B', GO_BWD)
675 /* C: SIGINT */
676 a_X('D', DEL_FWD)
677 a_X('E', GO_END)
678 a_X('F', GO_FWD)
679 a_X('G', RESET)
680 a_X('H', DEL_BWD)
681 a_X('I', COMPLETE)
682 a_X('J', COMMIT)
683 a_X('K', SNARF_END)
684 a_X('L', REPAINT)
685 /* M: same as J */
686 a_X('N', HIST_FWD)
687 /* O: below */
688 a_X('P', HIST_BWD)
689 a_X('Q', QUOTE_RNDTRIP)
690 a_X('R', HIST_SRCH_BWD)
691 a_X('S', HIST_SRCH_FWD)
692 a_X('T', PASTE)
693 a_X('U', SNARF_LINE)
694 a_X('V', PROMPT_CHAR)
695 a_X('W', SNARF_WORD_BWD)
696 a_X('X', GO_WORD_FWD)
697 a_X('Y', GO_WORD_BWD)
698 /* Z: SIGTSTP */
700 a_X('[', CANCEL)
701 /* \: below */
702 /* ]: below */
703 /* ^: below */
704 a_X('_', SNARF_WORD_FWD)
706 a_X('?', DEL_BWD)
708 # undef a_X
709 # define a_X(K,S) {TRU1, K, 0, {S}},
711 a_X('O', "dt")
712 a_X('\\', "z+")
713 a_X(']', "z$")
714 a_X('^', "z0")
716 # ifdef HAVE_KEY_BINDINGS
717 # undef a_X
718 # define a_X(Q,S) \
719 {FAL0, '\0', n_TERMCAP_QUERY_ ## Q,\
720 {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
722 a_X(key_backspace, DEL_BWD) a_X(key_dc, DEL_FWD)
723 a_X(key_eol, SNARF_END)
724 a_X(key_home, GO_HOME) a_X(key_end, GO_END)
725 a_X(key_left, GO_BWD) a_X(key_right, GO_FWD)
726 a_X(key_sleft, GO_HOME) a_X(key_sright, GO_END)
727 a_X(key_up, HIST_BWD) a_X(key_down, HIST_FWD)
729 # undef a_X
730 # define a_X(Q,S) {FAL0, '\0', n_TERMCAP_QUERY_ ## Q, {S}},
732 a_X(key_shome, "z0") a_X(key_send, "z$")
733 a_X(xkey_sup, "z0") a_X(xkey_sdown, "z$")
734 a_X(key_ppage, "z-") a_X(key_npage, "z+")
735 a_X(xkey_cup, "dotmove-") a_X(xkey_cdown, "dotmove+")
737 # endif /* HAVE_KEY_BINDINGS */
738 # undef a_X
741 static struct a_tty_global a_tty;
743 /* Change from canonical to raw, non-canonical mode, and way back */
744 static void a_tty_term_mode(bool_t raw);
746 /* Adjust an active raw mode to use / not use a timeout */
747 # ifdef HAVE_KEY_BINDINGS
748 static void a_tty_term_rawmode_timeout(struct a_tty_line *tlp, bool_t enable);
749 # endif
751 /* 0-X (2), UI8_MAX == \t / TAB */
752 static ui8_t a_tty_wcwidth(wchar_t wc);
754 /* Memory / cell / word generics */
755 static void a_tty_check_grow(struct a_tty_line *tlp, ui32_t no
756 n_MEMORY_DEBUG_ARGS);
757 static ssize_t a_tty_cell2dat(struct a_tty_line *tlp);
758 static void a_tty_cell2save(struct a_tty_line *tlp);
760 /* Save away data bytes of given range (max = non-inclusive) */
761 static void a_tty_copy2paste(struct a_tty_line *tlp, struct a_tty_cell *tcpmin,
762 struct a_tty_cell *tcpmax);
764 /* Ask user for hexadecimal number, interpret as UTF-32 */
765 static wchar_t a_tty_vinuni(struct a_tty_line *tlp);
767 /* Visual screen synchronization */
768 static bool_t a_tty_vi_refresh(struct a_tty_line *tlp);
770 static bool_t a_tty_vi__paint(struct a_tty_line *tlp);
772 /* Search for word boundary, starting at tl_cursor, in "dir"ection (<> 0).
773 * Return <0 when moving is impossible (backward direction but in position 0,
774 * forward direction but in outermost column), and relative distance to
775 * tl_cursor otherwise */
776 static si32_t a_tty_wboundary(struct a_tty_line *tlp, si32_t dir);
778 /* Most function implementations */
779 static void a_tty_khome(struct a_tty_line *tlp, bool_t dobell);
780 static void a_tty_kend(struct a_tty_line *tlp);
781 static void a_tty_kbs(struct a_tty_line *tlp);
782 static void a_tty_ksnarf(struct a_tty_line *tlp, bool_t cplline, bool_t dobell);
783 static si32_t a_tty_kdel(struct a_tty_line *tlp);
784 static void a_tty_kleft(struct a_tty_line *tlp);
785 static void a_tty_kright(struct a_tty_line *tlp);
786 static void a_tty_ksnarfw(struct a_tty_line *tlp, bool_t fwd);
787 static void a_tty_kgow(struct a_tty_line *tlp, si32_t dir);
788 static bool_t a_tty_kother(struct a_tty_line *tlp, wchar_t wc);
789 static ui32_t a_tty_kht(struct a_tty_line *tlp);
791 # ifdef HAVE_HISTORY
792 /* Return UI32_MAX on "exhaustion" */
793 static ui32_t a_tty_khist(struct a_tty_line *tlp, bool_t fwd);
794 static ui32_t a_tty_khist_search(struct a_tty_line *tlp, bool_t fwd);
796 static ui32_t a_tty__khist_shared(struct a_tty_line *tlp,
797 struct a_tty_hist *thp);
798 # endif
800 /* Handle a function */
801 static enum a_tty_fun_status a_tty_fun(struct a_tty_line *tlp,
802 enum a_tty_bind_flags tbf, size_t *len);
804 /* Readline core */
805 static ssize_t a_tty_readline(struct a_tty_line *tlp, size_t len
806 n_MEMORY_DEBUG_ARGS);
808 # ifdef HAVE_KEY_BINDINGS
809 /* Find context or -1 */
810 static enum n_lexinput_flags a_tty_bind_ctx_find(char const *name);
812 /* Create (or replace, if allowed) a binding */
813 static bool_t a_tty_bind_create(struct a_tty_bind_parse_ctx *tbpcp,
814 bool_t replace);
816 /* Shared implementation to parse `bind' and `unbind' "key-sequence" and
817 * "expansion" command line arguments into something that we can work with */
818 static bool_t a_tty_bind_parse(bool_t isbindcmd,
819 struct a_tty_bind_parse_ctx *tbpcp);
821 /* Lazy resolve a termcap(5)/terminfo(5) (or *termcap*!) capability */
822 static void a_tty_bind_resolve(struct a_tty_bind_ctx *tbcp);
824 /* Delete an existing binding */
825 static void a_tty_bind_del(struct a_tty_bind_parse_ctx *tbpcp);
827 /* Life cycle of all input node trees */
828 static void a_tty_bind_tree_build(void);
829 static void a_tty_bind_tree_teardown(void);
831 static void a_tty__bind_tree_add(ui32_t hmap_idx,
832 struct a_tty_bind_tree *store[HSHSIZE],
833 struct a_tty_bind_ctx *tbcp);
834 static struct a_tty_bind_tree *a_tty__bind_tree_add_wc(
835 struct a_tty_bind_tree **treep, struct a_tty_bind_tree *parentp,
836 wchar_t wc, bool_t isseq);
837 static void a_tty__bind_tree_free(struct a_tty_bind_tree *tbtp);
838 # endif /* HAVE_KEY_BINDINGS */
840 static void
841 a_tty_term_mode(bool_t raw){
842 struct termios *tiosp;
843 NYD2_ENTER;
845 tiosp = &a_tty.tg_tios_old;
846 if(!raw)
847 goto jleave;
849 /* Always requery the attributes, in case we've been moved from background
850 * to foreground or however else in between sessions */
851 /* XXX Always enforce ECHO and ICANON in the OLD attributes - do so as long
852 * XXX as we don't properly deal with TTIN and TTOU etc. */
853 tcgetattr(STDIN_FILENO, tiosp);
854 tiosp->c_lflag |= ECHO | ICANON;
856 memcpy(&a_tty.tg_tios_new, tiosp, sizeof *tiosp);
857 tiosp = &a_tty.tg_tios_new;
858 tiosp->c_cc[VMIN] = 1;
859 tiosp->c_cc[VTIME] = 0;
860 /* Enable ^\, ^Q and ^S to be used for key bindings */
861 tiosp->c_cc[VQUIT] = tiosp->c_cc[VSTART] = tiosp->c_cc[VSTOP] = '\0';
862 tiosp->c_iflag &= ~(ISTRIP | IGNCR);
863 tiosp->c_lflag &= ~(ECHO /*| ECHOE | ECHONL */| ICANON | IEXTEN);
864 jleave:
865 tcsetattr(STDIN_FILENO, TCSADRAIN, tiosp);
866 NYD2_LEAVE;
869 # ifdef HAVE_KEY_BINDINGS
870 static void
871 a_tty_term_rawmode_timeout(struct a_tty_line *tlp, bool_t enable){
872 NYD2_ENTER;
873 if(enable){
874 ui8_t bt;
876 a_tty.tg_tios_new.c_cc[VMIN] = 0;
877 if((bt = tlp->tl_bind_timeout) == 0)
878 bt = a_TTY_BIND_TIMEOUT;
879 a_tty.tg_tios_new.c_cc[VTIME] = bt;
880 }else{
881 a_tty.tg_tios_new.c_cc[VMIN] = 1;
882 a_tty.tg_tios_new.c_cc[VTIME] = 0;
884 tcsetattr(STDIN_FILENO, TCSANOW, &a_tty.tg_tios_new);
885 NYD2_LEAVE;
887 # endif /* HAVE_KEY_BINDINGS */
889 static ui8_t
890 a_tty_wcwidth(wchar_t wc){
891 ui8_t rv;
892 NYD2_ENTER;
894 /* Special case the backslash at first */
895 if(wc == '\t')
896 rv = UI8_MAX;
897 else{
898 int i;
900 # ifdef HAVE_WCWIDTH
901 rv = ((i = wcwidth(wc)) > 0) ? (ui8_t)i : 0;
902 # else
903 rv = iswprint(wc) ? 1 + (wc >= 0x1100u) : 0; /* TODO use S-CText */
904 # endif
906 NYD2_LEAVE;
907 return rv;
910 static void
911 a_tty_check_grow(struct a_tty_line *tlp, ui32_t no n_MEMORY_DEBUG_ARGS){
912 ui32_t cmax;
913 NYD2_ENTER;
915 if(n_UNLIKELY((cmax = tlp->tl_count + no) > tlp->tl_count_max)){
916 size_t i;
918 i = cmax * sizeof(struct a_tty_cell) + 2 * sizeof(struct a_tty_cell);
919 if(n_LIKELY(i >= *tlp->tl_x_bufsize)){
920 hold_all_sigs(); /* XXX v15 drop */
921 i <<= 1;
922 tlp->tl_line.cbuf =
923 *tlp->tl_x_buf = (n_realloc)(*tlp->tl_x_buf, i
924 n_MEMORY_DEBUG_ARGSCALL);
925 rele_all_sigs(); /* XXX v15 drop */
927 tlp->tl_count_max = cmax;
928 *tlp->tl_x_bufsize = i;
930 NYD2_LEAVE;
933 static ssize_t
934 a_tty_cell2dat(struct a_tty_line *tlp){
935 size_t len, i;
936 NYD2_ENTER;
938 len = 0;
940 if(n_LIKELY((i = tlp->tl_count) > 0)){
941 struct a_tty_cell const *tcap;
943 tcap = tlp->tl_line.cells;
945 memcpy(tlp->tl_line.cbuf + len, tcap->tc_cbuf, tcap->tc_count);
946 len += tcap->tc_count;
947 }while(++tcap, --i > 0);
950 tlp->tl_line.cbuf[len] = '\0';
951 NYD2_LEAVE;
952 return (ssize_t)len;
955 static void
956 a_tty_cell2save(struct a_tty_line *tlp){
957 size_t len, i;
958 struct a_tty_cell *tcap;
959 NYD2_ENTER;
961 tlp->tl_savec.s = NULL;
962 tlp->tl_savec.l = 0;
964 if(n_UNLIKELY(tlp->tl_count == 0))
965 goto jleave;
967 for(tcap = tlp->tl_line.cells, len = 0, i = tlp->tl_count; i > 0;
968 ++tcap, --i)
969 len += tcap->tc_count;
971 tlp->tl_savec.s = salloc((tlp->tl_savec.l = len) +1);
973 for(tcap = tlp->tl_line.cells, len = 0, i = tlp->tl_count; i > 0;
974 ++tcap, --i){
975 memcpy(tlp->tl_savec.s + len, tcap->tc_cbuf, tcap->tc_count);
976 len += tcap->tc_count;
978 tlp->tl_savec.s[len] = '\0';
979 jleave:
980 NYD2_LEAVE;
983 static void
984 a_tty_copy2paste(struct a_tty_line *tlp, struct a_tty_cell *tcpmin,
985 struct a_tty_cell *tcpmax){
986 char *cp;
987 struct a_tty_cell *tcp;
988 size_t l;
989 NYD2_ENTER;
991 l = 0;
992 for(tcp = tcpmin; tcp < tcpmax; ++tcp)
993 l += tcp->tc_count;
995 tlp->tl_pastebuf.s = cp = salloc((tlp->tl_pastebuf.l = l) +1);
997 l = 0;
998 for(tcp = tcpmin; tcp < tcpmax; cp += l, ++tcp)
999 memcpy(cp, tcp->tc_cbuf, l = tcp->tc_count);
1000 *cp = '\0';
1001 NYD2_LEAVE;
1004 static wchar_t
1005 a_tty_vinuni(struct a_tty_line *tlp){
1006 char buf[16], *eptr;
1007 union {size_t i; long l;} u;
1008 wchar_t wc;
1009 NYD2_ENTER;
1011 wc = '\0';
1013 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr) ||
1014 !n_termcap_cmd(n_TERMCAP_CMD_ce, 0, -1))
1015 goto jleave;
1017 /* C99 */{
1018 struct str const *cpre, *csuf;
1019 #ifdef HAVE_COLOUR
1020 struct n_colour_pen *cpen;
1022 cpen = n_colour_pen_create(n_COLOUR_ID_MLE_PROMPT, NULL);
1023 if((cpre = n_colour_pen_to_str(cpen)) != NULL)
1024 csuf = n_colour_reset_to_str();
1025 else
1026 csuf = NULL;
1027 #else
1028 cpre = csuf = NULL;
1029 #endif
1030 printf(_("%sPlease enter Unicode code point:%s "),
1031 (cpre != NULL ? cpre->s : ""), (csuf != NULL ? csuf->s : ""));
1033 fflush(stdout);
1035 buf[sizeof(buf) -1] = '\0';
1036 for(u.i = 0;;){
1037 if(read(STDIN_FILENO, &buf[u.i], 1) != 1){
1038 if(errno == EINTR) /* xxx #if !SA_RESTART ? */
1039 continue;
1040 goto jleave;
1042 if(buf[u.i] == '\n')
1043 break;
1044 if(!hexchar(buf[u.i])){
1045 char const emsg[] = "[0-9a-fA-F]";
1047 n_LCTA(sizeof emsg <= sizeof(buf), "Preallocated buffer too small");
1048 memcpy(buf, emsg, sizeof emsg);
1049 goto jerr;
1052 putc(buf[u.i], stdout);
1053 fflush(stdout);
1054 if(++u.i == sizeof buf)
1055 goto jerr;
1057 buf[u.i] = '\0';
1059 u.l = strtol(buf, &eptr, 16);
1060 if(u.l <= 0 || u.l >= 0x10FFFF/* XXX magic; CText */ || *eptr != '\0'){
1061 jerr:
1062 n_err(_("\nInvalid input: %s\n"), buf);
1063 goto jleave;
1066 wc = (wchar_t)u.l;
1067 jleave:
1068 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY | (wc == '\0' ? a_TTY_VF_BELL : 0);
1069 NYD2_LEAVE;
1070 return wc;
1073 static bool_t
1074 a_tty_vi_refresh(struct a_tty_line *tlp){
1075 bool_t rv;
1076 NYD2_ENTER;
1078 if(tlp->tl_vi_flags & a_TTY_VF_BELL){
1079 tlp->tl_vi_flags |= a_TTY_VF_SYNC;
1080 if(putchar('\a') == EOF)
1081 goto jerr;
1084 if(tlp->tl_vi_flags & a_TTY_VF_REFRESH){
1085 /* kht may want to restore a cursor position after inserting some
1086 * data somewhere */
1087 if(tlp->tl_defc_cursor_byte > 0){
1088 size_t i, j;
1089 ssize_t k;
1091 a_tty_khome(tlp, FAL0);
1093 i = tlp->tl_defc_cursor_byte;
1094 tlp->tl_defc_cursor_byte = 0;
1095 for(j = 0; tlp->tl_cursor < tlp->tl_count; ++j){
1096 a_tty_kright(tlp);
1097 if((k = tlp->tl_line.cells[j].tc_count) > i)
1098 break;
1099 i -= k;
1103 if(!a_tty_vi__paint(tlp))
1104 goto jerr;
1107 if(tlp->tl_vi_flags & a_TTY_VF_SYNC){
1108 tlp->tl_vi_flags &= ~a_TTY_VF_SYNC;
1109 if(fflush(stdout))
1110 goto jerr;
1113 rv = TRU1;
1114 jleave:
1115 tlp->tl_vi_flags &= ~a_TTY_VF_ALL_MASK;
1116 NYD2_LEAVE;
1117 return rv;
1119 jerr:
1120 clearerr(stdout); /* xxx I/O layer rewrite */
1121 n_err(_("Visual refresh failed! Is $TERM set correctly?\n"
1122 " Setting *line-editor-disable* to get us through!\n"));
1123 ok_bset(line_editor_disable);
1124 rv = FAL0;
1125 goto jleave;
1128 static bool_t
1129 a_tty_vi__paint(struct a_tty_line *tlp){
1130 enum{
1131 a_TRUE_RV = a_TTY__VF_LAST<<1, /* Return value bit */
1132 a_HAVE_PROMPT = a_TTY__VF_LAST<<2, /* Have a prompt */
1133 a_SHOW_PROMPT = a_TTY__VF_LAST<<3, /* Shall print the prompt */
1134 a_MOVE_CURSOR = a_TTY__VF_LAST<<4, /* Move visual cursor for user! */
1135 a_LEFT_MIN = a_TTY__VF_LAST<<5, /* On left boundary */
1136 a_RIGHT_MAX = a_TTY__VF_LAST<<6,
1137 a_HAVE_POSITION = a_TTY__VF_LAST<<7, /* Print the position indicator */
1139 /* We carry some flags over invocations (not worth a specific field) */
1140 a_VISIBLE_PROMPT = a_TTY__VF_LAST<<8, /* The prompt is on the screen */
1141 a_PERSIST_MASK = a_VISIBLE_PROMPT,
1142 a__LAST = a_PERSIST_MASK
1145 ui32_t f, w, phy_wid_base, phy_wid, phy_base, phy_cur, cnt, lstcur, cur,
1146 vi_left, vi_right, phy_nxtcur;
1147 struct a_tty_cell const *tccp, *tcp_left, *tcp_right, *tcxp;
1148 NYD2_ENTER;
1149 n_LCTA(UICMP(64, a__LAST, <, UI32_MAX), "Flag bits excess storage datatype");
1151 f = tlp->tl_vi_flags;
1152 tlp->tl_vi_flags = (f & ~(a_TTY_VF_REFRESH | a_PERSIST_MASK)) |
1153 a_TTY_VF_SYNC;
1154 f |= a_TRUE_RV;
1155 if((w = tlp->tl_prompt_length) > 0)
1156 f |= a_HAVE_PROMPT;
1157 f |= a_HAVE_POSITION;
1159 /* XXX We don't have a OnTerminalResize event (see main.c) yet, so we need
1160 * XXX to reevaluate our circumstances over and over again */
1161 /* Don't display prompt or position indicator on very small screens */
1162 if((phy_wid_base = (ui32_t)scrnwidth) <= a_TTY_WIDTH_RIPOFF)
1163 f &= ~(a_HAVE_PROMPT | a_HAVE_POSITION);
1164 else{
1165 phy_wid_base -= a_TTY_WIDTH_RIPOFF;
1167 /* Disable the prompt if the screen is too small; due to lack of some
1168 * indicator simply add a second ripoff */
1169 if((f & a_HAVE_PROMPT) && w + a_TTY_WIDTH_RIPOFF >= phy_wid_base)
1170 f &= ~a_HAVE_PROMPT;
1173 phy_wid = phy_wid_base;
1174 phy_base = 0;
1175 phy_cur = tlp->tl_phy_cursor;
1176 cnt = tlp->tl_count;
1177 lstcur = tlp->tl_lst_cursor;
1179 /* XXX Assume dirty screen if shrunk */
1180 if(cnt < tlp->tl_lst_count)
1181 f |= a_TTY_VF_MOD_DIRTY;
1183 /* TODO Without HAVE_TERMCAP, it would likely be much cheaper to simply
1184 * TODO always "cr + paint + ce + ch", since ce is simulated via spaces.. */
1186 /* Quickshot: if the line is empty, possibly print prompt and out */
1187 if(cnt == 0){
1188 /* In that special case dirty anything if it seems better */
1189 if((f & a_TTY_VF_MOD_CONTENT) || tlp->tl_lst_count > 0)
1190 f |= a_TTY_VF_MOD_DIRTY;
1192 if((f & a_TTY_VF_MOD_DIRTY) && phy_cur != 0){
1193 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
1194 goto jerr;
1195 phy_cur = 0;
1198 if((f & (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)) ==
1199 (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)){
1200 if(fputs(tlp->tl_prompt, stdout) == EOF)
1201 goto jerr;
1202 phy_cur = tlp->tl_prompt_width + 1;
1205 /* May need to clear former line content */
1206 if((f & a_TTY_VF_MOD_DIRTY) &&
1207 !n_termcap_cmd(n_TERMCAP_CMD_ce, phy_cur, -1))
1208 goto jerr;
1210 tlp->tl_phy_start = tlp->tl_line.cells;
1211 goto jleave;
1214 /* Try to get an idea of the visual window */
1216 /* Find the left visual boundary */
1217 phy_wid = (phy_wid >> 1) + (phy_wid >> 2);
1218 if((cur = tlp->tl_cursor) == cnt)
1219 --cur;
1221 w = (tcp_left = tccp = tlp->tl_line.cells + cur)->tc_width;
1222 if(w == UI8_MAX) /* TODO yet TAB == SPC */
1223 w = 1;
1224 while(tcp_left > tlp->tl_line.cells){
1225 ui16_t cw = tcp_left[-1].tc_width;
1227 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1228 cw = 1;
1229 if(w + cw >= phy_wid)
1230 break;
1231 w += cw;
1232 --tcp_left;
1234 vi_left = w;
1236 /* If the left hand side of our visual viewpoint consumes less than half
1237 * of the screen width, show the prompt */
1238 if(tcp_left == tlp->tl_line.cells)
1239 f |= a_LEFT_MIN;
1241 if((f & (a_LEFT_MIN | a_HAVE_PROMPT)) == (a_LEFT_MIN | a_HAVE_PROMPT) &&
1242 w + tlp->tl_prompt_width < phy_wid){
1243 phy_base = tlp->tl_prompt_width;
1244 f |= a_SHOW_PROMPT;
1247 /* Then search for right boundary. We always leave the rightmost column
1248 * empty because some terminals [cw]ould wrap the line if we write into
1249 * that. XXX terminfo(5)/termcap(5) have the semi_auto_right_margin/sam/YE
1250 * XXX capability to indicate this, but we don't look at that */
1251 phy_wid = phy_wid_base - phy_base;
1252 tcp_right = tlp->tl_line.cells + cnt;
1254 while(&tccp[1] < tcp_right){
1255 ui16_t cw = tccp[1].tc_width;
1256 ui32_t i;
1258 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1259 cw = 1;
1260 i = w + cw;
1261 if(i > phy_wid)
1262 break;
1263 w = i;
1264 ++tccp;
1266 vi_right = w - vi_left;
1268 /* If the complete line including prompt fits on the screen, show prompt */
1269 if(--tcp_right == tccp){
1270 f |= a_RIGHT_MAX;
1272 /* Since we did brute-force walk also for the left boundary we may end up
1273 * in a situation were anything effectively fits on the screen, including
1274 * the prompt that is, but were we don't recognize this since we
1275 * restricted the search to fit in some visual viewpoint. Therefore try
1276 * again to extend the left boundary to overcome that */
1277 if(!(f & a_LEFT_MIN)){
1278 struct a_tty_cell const *tc1p = tlp->tl_line.cells;
1279 ui32_t vil1 = vi_left;
1281 assert(!(f & a_SHOW_PROMPT));
1282 w += tlp->tl_prompt_width;
1283 for(tcxp = tcp_left;;){
1284 ui32_t i = tcxp[-1].tc_width;
1286 if(i == UI8_MAX) /* TODO yet TAB == SPC */
1287 i = 1;
1288 vil1 += i;
1289 i += w;
1290 if(i > phy_wid)
1291 break;
1292 w = i;
1293 if(--tcxp == tc1p){
1294 tcp_left = tc1p;
1295 vi_left = vil1;
1296 f |= a_LEFT_MIN;
1297 break;
1300 /*w -= tlp->tl_prompt_width;*/
1303 tcp_right = tccp;
1304 tccp = tlp->tl_line.cells + cur;
1306 if((f & (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT | a_SHOW_PROMPT)) ==
1307 (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT) &&
1308 w + tlp->tl_prompt_width <= phy_wid){
1309 phy_wid -= (phy_base = tlp->tl_prompt_width);
1310 f |= a_SHOW_PROMPT;
1313 /* Try to avoid repainting the complete line - this is possible if the
1314 * cursor "did not leave the screen" and the prompt status hasn't changed.
1315 * I.e., after clamping virtual viewpoint, compare relation to physical */
1316 if((f & (a_TTY_VF_MOD_SINGLE/*FIXME*/ |
1317 a_TTY_VF_MOD_CONTENT/* xxx */ | a_TTY_VF_MOD_DIRTY)) ||
1318 (tcxp = tlp->tl_phy_start) == NULL ||
1319 tcxp > tccp || tcxp <= tcp_right)
1320 f |= a_TTY_VF_MOD_DIRTY;
1321 else{
1322 f |= a_TTY_VF_MOD_DIRTY;
1323 #if 0
1324 struct a_tty_cell const *tcyp;
1325 si32_t cur_displace;
1326 ui32_t phy_lmargin, phy_rmargin, fx, phy_displace;
1328 phy_lmargin = (fx = phy_wid) / 100;
1329 phy_rmargin = fx - (phy_lmargin * a_TTY_SCROLL_MARGIN_RIGHT);
1330 phy_lmargin *= a_TTY_SCROLL_MARGIN_LEFT;
1331 fx = (f & (a_SHOW_PROMPT | a_VISIBLE_PROMPT));
1333 if(fx == 0 || fx == (a_SHOW_PROMPT | a_VISIBLE_PROMPT)){
1335 #endif
1337 goto jpaint;
1339 /* We know what we have to paint, start synchronizing */
1340 jpaint:
1341 assert(phy_cur == tlp->tl_phy_cursor);
1342 assert(phy_wid == phy_wid_base - phy_base);
1343 assert(cnt == tlp->tl_count);
1344 assert(cnt > 0);
1345 assert(lstcur == tlp->tl_lst_cursor);
1346 assert(tccp == tlp->tl_line.cells + cur);
1348 phy_nxtcur = phy_base; /* FIXME only if repaint cpl. */
1350 /* Quickshot: is it only cursor movement within the visible screen? */
1351 if((f & a_TTY_VF_REFRESH) == a_TTY_VF_MOD_CURSOR){
1352 f |= a_MOVE_CURSOR;
1353 goto jcursor;
1356 /* To be able to apply some quick jump offs, clear line if possible */
1357 if(f & a_TTY_VF_MOD_DIRTY){
1358 /* Force complete clearance and cursor reinitialization */
1359 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr) ||
1360 !n_termcap_cmd(n_TERMCAP_CMD_ce, 0, -1))
1361 goto jerr;
1362 tlp->tl_phy_start = tcp_left;
1363 phy_cur = 0;
1366 if((f & (a_TTY_VF_MOD_DIRTY | a_SHOW_PROMPT)) && phy_cur != 0){
1367 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
1368 goto jerr;
1369 phy_cur = 0;
1372 if(f & a_SHOW_PROMPT){
1373 assert(phy_base == tlp->tl_prompt_width);
1374 if(fputs(tlp->tl_prompt, stdout) == EOF)
1375 goto jerr;
1376 phy_cur = phy_nxtcur;
1377 f |= a_VISIBLE_PROMPT;
1378 }else
1379 f &= ~a_VISIBLE_PROMPT;
1381 /* FIXME reposition cursor for paint */
1382 for(w = phy_nxtcur; tcp_left <= tcp_right; ++tcp_left){
1383 ui16_t cw;
1385 cw = tcp_left->tc_width;
1387 if(n_LIKELY(!tcp_left->tc_novis)){
1388 if(fwrite(tcp_left->tc_cbuf, sizeof *tcp_left->tc_cbuf,
1389 tcp_left->tc_count, stdout) != tcp_left->tc_count)
1390 goto jerr;
1391 }else{ /* XXX Shouldn't be here <-> CText, ui_str.c */
1392 char wbuf[8]; /* XXX magic */
1394 if(options & OPT_UNICODE){
1395 ui32_t wc;
1397 wc = (ui32_t)tcp_left->tc_wc;
1398 if((wc & ~0x1Fu) == 0)
1399 wc |= 0x2400;
1400 else if(wc == 0x7F)
1401 wc = 0x2421;
1402 else
1403 wc = 0x2426;
1404 n_utf32_to_utf8(wc, wbuf);
1405 }else
1406 wbuf[0] = '?', wbuf[1] = '\0';
1408 if(fputs(wbuf, stdout) == EOF)
1409 goto jerr;
1410 cw = 1;
1413 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1414 cw = 1;
1415 w += cw;
1416 if(tcp_left == tccp)
1417 phy_nxtcur = w;
1418 phy_cur += cw;
1421 /* Write something position marker alike if it doesn't fit on screen */
1422 if((f & a_HAVE_POSITION) &&
1423 ((f & (a_LEFT_MIN | a_RIGHT_MAX)) != (a_LEFT_MIN | a_RIGHT_MAX) ||
1424 ((f & a_HAVE_PROMPT) && !(f & a_SHOW_PROMPT)))){
1425 # ifdef HAVE_COLOUR
1426 char *posbuf = tlp->tl_pos_buf, *pos = tlp->tl_pos;
1427 # else
1428 char posbuf[5], *pos = posbuf;
1430 pos[4] = '\0';
1431 # endif
1433 if(phy_cur != (w = phy_wid_base) &&
1434 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = w, 0))
1435 goto jerr;
1437 *pos++ = '|';
1438 if((f & a_LEFT_MIN) && (!(f & a_HAVE_PROMPT) || (f & a_SHOW_PROMPT)))
1439 memcpy(pos, "^.+", 3);
1440 else if(f & a_RIGHT_MAX)
1441 memcpy(pos, ".+$", 3);
1442 else{
1443 /* Theoretical line length limit a_TTY_LINE_MAX, choose next power of
1444 * ten (10 ** 10) to represent 100 percent, since we don't have a macro
1445 * that generates a constant, and i don't trust the standard "u type
1446 * suffix automatically scales" calculate the large number */
1447 static char const itoa[] = "0123456789";
1449 ui64_t const fact100 = (ui64_t)0x3B9ACA00u * 10u, fact = fact100 / 100;
1450 ui32_t i = (ui32_t)(((fact100 / cnt) * tlp->tl_cursor) / fact);
1451 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1453 if(i < 10)
1454 pos[0] = ' ', pos[1] = itoa[i];
1455 else
1456 pos[1] = itoa[i % 10], pos[0] = itoa[i / 10];
1457 pos[2] = '%';
1460 if(fputs(posbuf, stdout) == EOF)
1461 goto jerr;
1462 phy_cur += 4;
1465 /* Users are used to see the cursor right of the point of interest, so we
1466 * need some further adjustments unless in special conditions. Be aware
1467 * that we may have adjusted cur at the beginning, too */
1468 if((cur = tlp->tl_cursor) == 0)
1469 phy_nxtcur = phy_base;
1470 else if(cur != cnt){
1471 ui16_t cw = tccp->tc_width;
1473 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1474 cw = 1;
1475 phy_nxtcur -= cw;
1478 jcursor:
1479 if(((f & a_MOVE_CURSOR) || phy_nxtcur != phy_cur) &&
1480 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = phy_nxtcur, 0))
1481 goto jerr;
1483 jleave:
1484 tlp->tl_vi_flags |= (f & a_PERSIST_MASK);
1485 tlp->tl_lst_count = tlp->tl_count;
1486 tlp->tl_lst_cursor = tlp->tl_cursor;
1487 tlp->tl_phy_cursor = phy_cur;
1489 NYD2_LEAVE;
1490 return ((f & a_TRUE_RV) != 0);
1491 jerr:
1492 f &= ~a_TRUE_RV;
1493 goto jleave;
1496 static si32_t
1497 a_tty_wboundary(struct a_tty_line *tlp, si32_t dir){/* TODO shell token-wise */
1498 bool_t anynon;
1499 struct a_tty_cell *tcap;
1500 ui32_t cur, cnt;
1501 si32_t rv;
1502 NYD2_ENTER;
1504 assert(dir == 1 || dir == -1);
1506 rv = -1;
1507 cnt = tlp->tl_count;
1508 cur = tlp->tl_cursor;
1510 if(dir < 0){
1511 if(cur == 0)
1512 goto jleave;
1513 }else if(cur + 1 >= cnt)
1514 goto jleave;
1515 else
1516 --cnt, --cur; /* xxx Unsigned wrapping may occur (twice), then */
1518 for(rv = 0, tcap = tlp->tl_line.cells, anynon = FAL0;;){
1519 wchar_t wc;
1521 wc = tcap[cur += (ui32_t)dir].tc_wc;
1522 if(iswblank(wc) || iswpunct(wc)){
1523 if(anynon)
1524 break;
1525 }else
1526 anynon = TRU1;
1528 ++rv;
1530 if(dir < 0){
1531 if(cur == 0)
1532 break;
1533 }else if(cur + 1 >= cnt){
1534 ++rv;
1535 break;
1538 jleave:
1539 NYD2_LEAVE;
1540 return rv;
1543 static void
1544 a_tty_khome(struct a_tty_line *tlp, bool_t dobell){
1545 ui32_t f;
1546 NYD2_ENTER;
1548 if(n_LIKELY(tlp->tl_cursor > 0)){
1549 tlp->tl_cursor = 0;
1550 f = a_TTY_VF_MOD_CURSOR;
1551 }else if(dobell)
1552 f = a_TTY_VF_BELL;
1553 else
1554 f = a_TTY_VF_NONE;
1556 tlp->tl_vi_flags |= f;
1557 NYD2_LEAVE;
1560 static void
1561 a_tty_kend(struct a_tty_line *tlp){
1562 ui32_t f;
1563 NYD2_ENTER;
1565 if(n_LIKELY(tlp->tl_cursor < tlp->tl_count)){
1566 tlp->tl_cursor = tlp->tl_count;
1567 f = a_TTY_VF_MOD_CURSOR;
1568 }else
1569 f = a_TTY_VF_BELL;
1571 tlp->tl_vi_flags |= f;
1572 NYD2_LEAVE;
1575 static void
1576 a_tty_kbs(struct a_tty_line *tlp){
1577 ui32_t f, cur, cnt;
1578 NYD2_ENTER;
1580 cur = tlp->tl_cursor;
1581 cnt = tlp->tl_count;
1583 if(n_LIKELY(cur > 0)){
1584 tlp->tl_cursor = --cur;
1585 tlp->tl_count = --cnt;
1587 if((cnt -= cur) > 0){
1588 struct a_tty_cell *tcap;
1590 tcap = tlp->tl_line.cells + cur;
1591 memmove(tcap, &tcap[1], cnt *= sizeof(*tcap));
1593 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
1594 }else
1595 f = a_TTY_VF_BELL;
1597 tlp->tl_vi_flags |= f;
1598 NYD2_LEAVE;
1601 static void
1602 a_tty_ksnarf(struct a_tty_line *tlp, bool_t cplline, bool_t dobell){
1603 ui32_t i, f;
1604 NYD2_ENTER;
1606 f = a_TTY_VF_NONE;
1607 i = tlp->tl_cursor;
1609 if(cplline && i > 0){
1610 tlp->tl_cursor = i = 0;
1611 f = a_TTY_VF_MOD_CURSOR;
1614 if(n_LIKELY(i < tlp->tl_count)){
1615 struct a_tty_cell *tcap;
1617 tcap = &tlp->tl_line.cells[0];
1618 a_tty_copy2paste(tlp, &tcap[i], &tcap[tlp->tl_count]);
1619 tlp->tl_count = i;
1620 f = a_TTY_VF_MOD_CONTENT;
1621 }else if(dobell)
1622 f |= a_TTY_VF_BELL;
1624 tlp->tl_vi_flags |= f;
1625 NYD2_LEAVE;
1628 static si32_t
1629 a_tty_kdel(struct a_tty_line *tlp){
1630 ui32_t cur, cnt, f;
1631 si32_t i;
1632 NYD2_ENTER;
1634 cur = tlp->tl_cursor;
1635 cnt = tlp->tl_count;
1636 i = (si32_t)(cnt - cur);
1638 if(n_LIKELY(i > 0)){
1639 tlp->tl_count = --cnt;
1641 if(n_LIKELY(--i > 0)){
1642 struct a_tty_cell *tcap;
1644 tcap = &tlp->tl_line.cells[cur];
1645 memmove(tcap, &tcap[1], (ui32_t)i * sizeof(*tcap));
1647 f = a_TTY_VF_MOD_CONTENT;
1648 }else if(cnt == 0 && !ok_blook(ignoreeof)){
1649 putchar('^');
1650 putchar('D');
1651 i = -1;
1652 f = a_TTY_VF_NONE;
1653 }else{
1654 i = 0;
1655 f = a_TTY_VF_BELL;
1658 tlp->tl_vi_flags |= f;
1659 NYD2_LEAVE;
1660 return i;
1663 static void
1664 a_tty_kleft(struct a_tty_line *tlp){
1665 ui32_t f;
1666 NYD2_ENTER;
1668 if(n_LIKELY(tlp->tl_cursor > 0)){
1669 --tlp->tl_cursor;
1670 f = a_TTY_VF_MOD_CURSOR;
1671 }else
1672 f = a_TTY_VF_BELL;
1674 tlp->tl_vi_flags |= f;
1675 NYD2_LEAVE;
1678 static void
1679 a_tty_kright(struct a_tty_line *tlp){
1680 ui32_t i;
1681 NYD2_ENTER;
1683 if(n_LIKELY((i = tlp->tl_cursor + 1) <= tlp->tl_count)){
1684 tlp->tl_cursor = i;
1685 i = a_TTY_VF_MOD_CURSOR;
1686 }else
1687 i = a_TTY_VF_BELL;
1689 tlp->tl_vi_flags |= i;
1690 NYD2_LEAVE;
1693 static void
1694 a_tty_ksnarfw(struct a_tty_line *tlp, bool_t fwd){
1695 struct a_tty_cell *tcap;
1696 ui32_t cnt, cur, f;
1697 si32_t i;
1698 NYD2_ENTER;
1700 if(n_UNLIKELY((i = a_tty_wboundary(tlp, (fwd ? +1 : -1))) <= 0)){
1701 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
1702 goto jleave;
1705 cnt = tlp->tl_count - (ui32_t)i;
1706 cur = tlp->tl_cursor;
1707 if(!fwd)
1708 cur -= (ui32_t)i;
1709 tcap = &tlp->tl_line.cells[cur];
1711 a_tty_copy2paste(tlp, &tcap[0], &tcap[i]);
1713 if((tlp->tl_count = cnt) != (tlp->tl_cursor = cur)){
1714 cnt -= cur;
1715 memmove(&tcap[0], &tcap[i], cnt * sizeof(*tcap)); /* FIXME*/
1718 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
1719 jleave:
1720 tlp->tl_vi_flags |= f;
1721 NYD2_LEAVE;
1724 static void
1725 a_tty_kgow(struct a_tty_line *tlp, si32_t dir){
1726 ui32_t f;
1727 si32_t i;
1728 NYD2_ENTER;
1730 if(n_UNLIKELY((i = a_tty_wboundary(tlp, dir)) <= 0))
1731 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
1732 else{
1733 if(dir < 0)
1734 i = -i;
1735 tlp->tl_cursor += (ui32_t)i;
1736 f = a_TTY_VF_MOD_CURSOR;
1739 tlp->tl_vi_flags |= f;
1740 NYD2_LEAVE;
1743 static bool_t
1744 a_tty_kother(struct a_tty_line *tlp, wchar_t wc){
1745 /* Append if at EOL, insert otherwise;
1746 * since we may move around character-wise, always use a fresh ps */
1747 mbstate_t ps;
1748 struct a_tty_cell tc, *tcap;
1749 ui32_t f, cur, cnt;
1750 bool_t rv;
1751 NYD2_ENTER;
1753 rv = FAL0;
1754 f = a_TTY_VF_NONE;
1756 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1757 if(tlp->tl_count + 1 >= a_TTY_LINE_MAX){
1758 n_err(_("Stop here, we can't extend line beyond size limit\n"));
1759 goto jleave;
1762 /* First init a cell and see whether we'll really handle this wc */
1763 memset(&ps, 0, sizeof ps);
1764 /* C99 */{
1765 size_t l;
1767 l = wcrtomb(tc.tc_cbuf, tc.tc_wc = wc, &ps);
1768 if(n_UNLIKELY(l > MB_LEN_MAX)){
1769 jemb:
1770 n_err(_("wcrtomb(3) error: too many multibyte character bytes\n"));
1771 goto jleave;
1773 tc.tc_count = (ui16_t)l;
1775 if(n_UNLIKELY((options & OPT_ENC_MBSTATE) != 0)){
1776 l = wcrtomb(&tc.tc_cbuf[l], L'\0', &ps);
1777 if(n_LIKELY(l == 1))
1778 /* Only NUL terminator */;
1779 else if(n_LIKELY(--l < MB_LEN_MAX))
1780 tc.tc_count += (ui16_t)l;
1781 else
1782 goto jemb;
1786 /* Yes, we will! Place it in the array */
1787 tc.tc_novis = (iswprint(wc) == 0);
1788 tc.tc_width = a_tty_wcwidth(wc);
1789 /* TODO if(tc.tc_novis && tc.tc_width > 0) */
1791 cur = tlp->tl_cursor++;
1792 cnt = tlp->tl_count++ - cur;
1793 tcap = &tlp->tl_line.cells[cur];
1794 if(cnt >= 1){
1795 memmove(&tcap[1], tcap, cnt * sizeof(*tcap));
1796 f = a_TTY_VF_MOD_CONTENT;
1797 }else
1798 f = a_TTY_VF_MOD_SINGLE;
1799 memcpy(tcap, &tc, sizeof *tcap);
1801 f |= a_TTY_VF_MOD_CURSOR;
1802 rv = TRU1;
1803 jleave:
1804 if(!rv)
1805 f |= a_TTY_VF_BELL;
1806 tlp->tl_vi_flags |= f;
1807 NYD2_LEAVE;
1808 return rv;
1811 static ui32_t
1812 a_tty_kht(struct a_tty_line *tlp){
1813 struct stat sb;
1814 struct str orig, bot, topp, sub, exp;
1815 struct n_string shou, *shoup;
1816 struct a_tty_cell *cword, *ctop, *cx;
1817 bool_t wedid, set_savec;
1818 ui32_t rv, f;
1819 NYD2_ENTER;
1821 f = a_TTY_VF_NONE;
1822 shoup = n_string_creat_auto(&shou);
1824 /* Get plain line data; if this is the first expansion/xy, update the
1825 * very original content so that ^G gets the origin back */
1826 orig = tlp->tl_savec;
1827 a_tty_cell2save(tlp);
1828 exp = tlp->tl_savec;
1829 if(orig.s != NULL){
1830 /*tlp->tl_savec = orig;*/
1831 set_savec = FAL0;
1832 }else
1833 set_savec = TRU1;
1834 orig = exp;
1836 /* Find the word to be expanded */
1838 cword = tlp->tl_line.cells;
1839 ctop = cword + tlp->tl_cursor;
1840 cx = cword + tlp->tl_count;
1842 /* topp: separate data right of cursor */
1843 if(cx > ctop){
1844 for(rv = 0; ctop < cx; ++ctop)
1845 rv += ctop->tc_count;
1846 topp.l = rv;
1847 topp.s = orig.s + orig.l - rv;
1848 ctop = cword + tlp->tl_cursor;
1849 }else
1850 topp.s = NULL, topp.l = 0;
1852 /* Find the shell token that corresponds to the cursor position */
1853 /* C99 */{
1854 size_t max;
1856 max = 0;
1857 if(ctop > cword){
1858 for(; cword < ctop; ++cword)
1859 max += cword->tc_count;
1860 cword = tlp->tl_line.cells;
1862 bot = sub = orig;
1863 bot.l = 0;
1864 sub.l = max;
1866 if(max > 0){
1867 for(;;){
1868 enum n_shexp_state shs;
1870 exp = sub;
1871 shs = n_shexp_parse_token(NULL, &sub, n_SHEXP_PARSE_DRYRUN |
1872 n_SHEXP_PARSE_TRIMSPACE | n_SHEXP_PARSE_IGNORE_EMPTY |
1873 n_SHEXP_PARSE_QUOTE_AUTOCLOSE);
1874 if(sub.l != 0){
1875 size_t x;
1877 assert(max >= sub.l);
1878 x = max - sub.l;
1879 bot.l += x;
1880 max -= x;
1881 continue;
1883 if(shs & n_SHEXP_STATE_ERR_MASK){
1884 n_err(_("Invalid completion pattern: %.*s\n"),
1885 (int)exp.l, exp.s);
1886 goto jnope;
1888 n_shexp_parse_token(shoup, &exp,
1889 n_SHEXP_PARSE_TRIMSPACE | n_SHEXP_PARSE_IGNORE_EMPTY |
1890 n_SHEXP_PARSE_QUOTE_AUTOCLOSE);
1891 break;
1894 sub.s = n_string_cp(shoup);
1895 sub.l = shoup->s_len;
1899 /* Leave room for "implicit asterisk" expansion, as below */
1900 if(sub.l == 0){
1901 wedid = TRU1;
1902 sub.s = n_UNCONST("*");
1903 sub.l = 1;
1906 wedid = FAL0;
1907 jredo:
1908 /* TODO Super-Heavy-Metal: block all sigs, avoid leaks on jump */
1909 hold_all_sigs();
1910 exp.s = fexpand(sub.s, a_TTY_TAB_FEXP_FL);
1911 rele_all_sigs();
1913 if(exp.s == NULL || (exp.l = strlen(exp.s)) == 0)
1914 goto jnope;
1916 /* May be multi-return! */
1917 if(pstate & PS_EXPAND_MULTIRESULT)
1918 goto jmulti;
1920 /* xxx That is not really true since the limit counts characters not bytes */
1921 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1922 if(exp.l + 1 >= a_TTY_LINE_MAX){
1923 n_err(_("Tabulator expansion would extend beyond line size limit\n"));
1924 goto jnope;
1927 /* If the expansion equals the original string, assume the user wants what
1928 * is usually known as tab completion, append `*' and restart */
1929 if(!wedid && exp.l == sub.l && !memcmp(exp.s, sub.s, exp.l)){
1930 if(sub.s[sub.l - 1] == '*')
1931 goto jnope;
1933 wedid = TRU1;
1934 sub.s[sub.l++] = '*';
1935 sub.s[sub.l] = '\0';
1936 goto jredo;
1938 /* If it is a directory, and there is not yet a / appended, then we want the
1939 * user to confirm that he wants to dive in -- with only a HT */
1940 else if(wedid && exp.l == --sub.l && !memcmp(exp.s, sub.s, exp.l) &&
1941 exp.s[exp.l - 1] != '/'){
1942 if(stat(exp.s, &sb) || !S_ISDIR(sb.st_mode))
1943 goto jnope;
1944 sub.s = salloc(exp.l + 1 +1);
1945 memcpy(sub.s, exp.s, exp.l);
1946 sub.s[exp.l++] = '/';
1947 sub.s[exp.l] = '\0';
1948 exp.s = sub.s;
1949 wedid = FAL0;
1950 goto jset;
1951 }else{
1952 if(wedid && (wedid = (exp.s[exp.l - 1] == '*')))
1953 --exp.l;
1954 exp.s[exp.l] = '\0';
1955 jset:
1956 exp.l = strlen(exp.s = n_shexp_quote_cp(exp.s, tlp->tl_quote_rndtrip));
1957 tlp->tl_defc_cursor_byte = bot.l + exp.l -1;
1958 if(wedid)
1959 goto jnope;
1962 orig.l = bot.l + exp.l + topp.l;
1963 orig.s = salloc(orig.l + 5 +1);
1964 if((rv = (ui32_t)bot.l) > 0)
1965 memcpy(orig.s, bot.s, rv);
1966 memcpy(orig.s + rv, exp.s, exp.l);
1967 rv += exp.l;
1968 if(topp.l > 0){
1969 memcpy(orig.s + rv, topp.s, topp.l);
1970 rv += topp.l;
1972 orig.s[rv] = '\0';
1974 tlp->tl_defc = orig;
1975 tlp->tl_count = tlp->tl_cursor = 0;
1976 f |= a_TTY_VF_MOD_DIRTY;
1977 jleave:
1978 n_string_gut(shoup);
1979 tlp->tl_vi_flags |= f;
1980 NYD2_LEAVE;
1981 return rv;
1983 jmulti:{
1984 struct n_visual_info_ctx vic;
1985 struct str input;
1986 wc_t c2, c1;
1987 bool_t isfirst;
1988 char const *lococp;
1989 size_t locolen, scrwid, lnlen, lncnt, prefixlen;
1990 FILE *fp;
1992 if((fp = Ftmp(NULL, "tabex", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
1993 n_perr(_("tmpfile"), 0);
1994 fp = stdout;
1997 /* How long is the result string for real? Search the NUL NUL
1998 * terminator. While here, detect the longest entry to perform an
1999 * initial allocation of our accumulator string */
2000 locolen = 0;
2002 size_t i;
2004 i = strlen(&exp.s[++exp.l]);
2005 locolen = n_MAX(locolen, i);
2006 exp.l += i;
2007 }while(exp.s[exp.l + 1] != '\0');
2009 shoup = n_string_reserve(n_string_trunc(shoup, 0),
2010 locolen + (locolen >> 1));
2012 /* Iterate (once again) over all results */
2013 scrwid = (size_t)scrnwidth - ((size_t)scrnwidth >> 3);
2014 lnlen = lncnt = 0;
2015 n_UNINIT(prefixlen, 0);
2016 n_UNINIT(lococp, NULL);
2017 n_UNINIT(c1, '\0');
2018 for(isfirst = TRU1; exp.l > 0; isfirst = FAL0, c1 = c2){
2019 size_t i;
2020 char const *fullpath;
2022 /* Next result */
2023 sub = exp;
2024 sub.l = i = strlen(sub.s);
2025 assert(exp.l >= i);
2026 if((exp.l -= i) > 0)
2027 --exp.l;
2028 exp.s += ++i;
2030 /* Separate dirname and basename */
2031 fullpath = sub.s;
2032 if(isfirst){
2033 char const *cp;
2035 if((cp = strrchr(fullpath, '/')) != NULL)
2036 prefixlen = PTR2SIZE(++cp - fullpath);
2037 else
2038 prefixlen = 0;
2040 if(prefixlen > 0 && prefixlen < sub.l){
2041 sub.l -= prefixlen;
2042 sub.s += prefixlen;
2045 /* We want case-insensitive sort-order */
2046 memset(&vic, 0, sizeof vic);
2047 vic.vic_indat = sub.s;
2048 vic.vic_inlen = sub.l;
2049 c2 = n_visual_info(&vic, n_VISUAL_INFO_ONE_CHAR) ? vic.vic_waccu
2050 : (ui8_t)*sub.s;
2051 #ifdef HAVE_C90AMEND1
2052 c2 = towlower(c2);
2053 #else
2054 c2 = lowerconv(c2);
2055 #endif
2057 /* Query longest common prefix along the way */
2058 if(isfirst){
2059 c1 = c2;
2060 lococp = sub.s;
2061 locolen = sub.l;
2062 }else if(locolen > 0){
2063 for(i = 0; i < locolen; ++i)
2064 if(lococp[i] != sub.s[i]){
2065 i = field_detect_clip(i, lococp, i);
2066 locolen = i;
2067 break;
2071 /* Prepare display */
2072 input = sub;
2073 shoup = n_shexp_quote(n_string_trunc(shoup, 0), &input,
2074 tlp->tl_quote_rndtrip);
2075 memset(&vic, 0, sizeof vic);
2076 vic.vic_indat = shoup->s_dat;
2077 vic.vic_inlen = shoup->s_len;
2078 if(!n_visual_info(&vic,
2079 n_VISUAL_INFO_SKIP_ERRORS | n_VISUAL_INFO_WIDTH_QUERY))
2080 vic.vic_vi_width = shoup->s_len;
2082 /* Put on screen. Indent follow lines of same sort slot */
2083 c1 = (c1 != c2);
2084 if(isfirst || c1 ||
2085 scrwid < lnlen || scrwid - lnlen <= vic.vic_vi_width + 2){
2086 putc('\n', fp);
2087 if(scrwid < lnlen)
2088 ++lncnt;
2089 ++lncnt, lnlen = 0;
2090 if(!isfirst && !c1)
2091 goto jsep;
2092 }else if(lnlen > 0){
2093 jsep:
2094 fputs(" ", fp);
2095 lnlen += 2;
2097 fputs(n_string_cp(shoup), fp);
2098 lnlen += vic.vic_vi_width;
2100 /* Support the known file name tagging
2101 * XXX *line-editor-completion-filetype* or so */
2102 if(!lstat(fullpath, &sb)){
2103 char c = '\0';
2105 if(S_ISDIR(sb.st_mode))
2106 c = '/';
2107 else if(S_ISLNK(sb.st_mode))
2108 c = '@';
2109 # ifdef S_ISFIFO
2110 else if(S_ISFIFO(sb.st_mode))
2111 c = '|';
2112 # endif
2113 # ifdef S_ISSOCK
2114 else if(S_ISSOCK(sb.st_mode))
2115 c = '=';
2116 # endif
2117 # ifdef S_ISCHR
2118 else if(S_ISCHR(sb.st_mode))
2119 c = '%';
2120 # endif
2121 # ifdef S_ISBLK
2122 else if(S_ISBLK(sb.st_mode))
2123 c = '#';
2124 # endif
2126 if(c != '\0'){
2127 putc(c, fp);
2128 ++lnlen;
2132 putc('\n', fp);
2133 ++lncnt;
2135 page_or_print(fp, lncnt);
2136 if(fp != stdout)
2137 Fclose(fp);
2139 n_string_gut(shoup);
2141 /* A common prefix of 0 means we cannot provide the user any auto
2142 * completed characters */
2143 if(locolen == 0)
2144 goto jnope;
2146 /* Otherwise we can, so extend the visual line content by the common
2147 * prefix (in a reversible way) */
2148 (exp.s = n_UNCONST(lococp))[locolen] = '\0';
2149 exp.s -= prefixlen;
2150 exp.l = (locolen += prefixlen);
2152 /* XXX Indicate that there is multiple choice */
2153 /* XXX f |= a_TTY_VF_BELL; -> *line-editor-completion-bell*? or so */
2154 wedid = FAL0;
2155 goto jset;
2158 jnope:
2159 /* If we've provided a default content, but failed to expand, there is
2160 * nothing we can "revert to": drop that default again */
2161 if(set_savec){
2162 tlp->tl_savec.s = NULL;
2163 tlp->tl_savec.l = 0;
2165 f = a_TTY_VF_NONE;
2166 rv = 0;
2167 goto jleave;
2170 # ifdef HAVE_HISTORY
2171 static ui32_t
2172 a_tty__khist_shared(struct a_tty_line *tlp, struct a_tty_hist *thp){
2173 ui32_t f, rv;
2174 NYD2_ENTER;
2176 if(n_LIKELY((tlp->tl_hist = thp) != NULL)){
2177 tlp->tl_defc.s = savestrbuf(thp->th_dat, thp->th_len);
2178 rv = tlp->tl_defc.l = thp->th_len;
2179 f = (tlp->tl_count > 0) ? a_TTY_VF_MOD_DIRTY : a_TTY_VF_NONE;
2180 tlp->tl_count = tlp->tl_cursor = 0;
2181 }else{
2182 f = a_TTY_VF_BELL;
2183 rv = UI32_MAX;
2186 tlp->tl_vi_flags |= f;
2187 NYD2_LEAVE;
2188 return rv;
2191 static ui32_t
2192 a_tty_khist(struct a_tty_line *tlp, bool_t fwd){
2193 struct a_tty_hist *thp;
2194 ui32_t rv;
2195 NYD2_ENTER;
2197 /* If we're not in history mode yet, save line content;
2198 * also, disallow forward search, then, and, of course, bail unless we
2199 * do have any history at all */
2200 if((thp = tlp->tl_hist) == NULL){
2201 if(fwd)
2202 goto jleave;
2203 if((thp = a_tty.tg_hist) == NULL)
2204 goto jleave;
2205 a_tty_cell2save(tlp);
2206 goto jleave;
2209 thp = fwd ? thp->th_younger : thp->th_older;
2210 jleave:
2211 rv = a_tty__khist_shared(tlp, thp);
2212 NYD2_LEAVE;
2213 return rv;
2216 static ui32_t
2217 a_tty_khist_search(struct a_tty_line *tlp, bool_t fwd){
2218 struct str orig_savec;
2219 struct a_tty_hist *thp;
2220 ui32_t rv;
2221 NYD2_ENTER;
2223 thp = NULL;
2225 /* We cannot complete an empty line */
2226 if(n_UNLIKELY(tlp->tl_count == 0)){
2227 /* XXX The upcoming hard reset would restore a set savec buffer,
2228 * XXX so forcefully reset that. A cleaner solution would be to
2229 * XXX reset it whenever a restore is no longer desired */
2230 tlp->tl_savec.s = NULL;
2231 tlp->tl_savec.l = 0;
2232 goto jleave;
2235 if((thp = tlp->tl_hist) == NULL){
2236 if((thp = a_tty.tg_hist) == NULL)
2237 goto jleave;
2238 /* We don't support wraparound, searching forward must always step */
2239 if(fwd)
2240 thp = thp->th_younger;
2241 orig_savec.s = NULL;
2242 orig_savec.l = 0; /* silence CC */
2243 }else if((thp = (fwd ? thp->th_younger : thp->th_older)) == NULL)
2244 goto jleave;
2245 else
2246 orig_savec = tlp->tl_savec;
2248 if(orig_savec.s == NULL)
2249 a_tty_cell2save(tlp);
2251 for(; thp != NULL; thp = (fwd ? thp->th_younger : thp->th_older))
2252 if(is_prefix(tlp->tl_savec.s, thp->th_dat))
2253 break;
2255 if(orig_savec.s != NULL)
2256 tlp->tl_savec = orig_savec;
2257 jleave:
2258 rv = a_tty__khist_shared(tlp, thp);
2259 NYD2_LEAVE;
2260 return rv;
2262 # endif /* HAVE_HISTORY */
2264 static enum a_tty_fun_status
2265 a_tty_fun(struct a_tty_line *tlp, enum a_tty_bind_flags tbf, size_t *len){
2266 enum a_tty_fun_status rv;
2267 NYD2_ENTER;
2269 rv = a_TTY_FUN_STATUS_OK;
2270 # undef a_X
2271 # define a_X(N) a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## N)
2272 switch(a_TTY_BIND_FUN_REDUCE(tbf)){
2273 case a_X(BELL):
2274 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2275 break;
2276 case a_X(GO_BWD):
2277 a_tty_kleft(tlp);
2278 break;
2279 case a_X(GO_FWD):
2280 a_tty_kright(tlp);
2281 break;
2282 case a_X(GO_WORD_BWD):
2283 a_tty_kgow(tlp, -1);
2284 break;
2285 case a_X(GO_WORD_FWD):
2286 a_tty_kgow(tlp, +1);
2287 break;
2288 case a_X(GO_HOME):
2289 a_tty_khome(tlp, TRU1);
2290 break;
2291 case a_X(GO_END):
2292 a_tty_kend(tlp);
2293 break;
2294 case a_X(DEL_BWD):
2295 a_tty_kbs(tlp);
2296 break;
2297 case a_X(DEL_FWD):
2298 if(a_tty_kdel(tlp) < 0)
2299 rv = a_TTY_FUN_STATUS_END;
2300 break;
2301 case a_X(SNARF_WORD_BWD):
2302 a_tty_ksnarfw(tlp, FAL0);
2303 break;
2304 case a_X(SNARF_WORD_FWD):
2305 a_tty_ksnarfw(tlp, TRU1);
2306 break;
2307 case a_X(SNARF_END):
2308 a_tty_ksnarf(tlp, FAL0, TRU1);
2309 break;
2310 case a_X(SNARF_LINE):
2311 a_tty_ksnarf(tlp, TRU1, (tlp->tl_count == 0));
2312 break;
2314 case a_X(HIST_FWD):
2315 # ifdef HAVE_HISTORY
2316 if(tlp->tl_hist != NULL){
2317 bool_t isfwd = TRU1;
2319 if(0){
2320 # endif
2321 /* FALLTHRU */
2322 case a_X(HIST_BWD):
2323 # ifdef HAVE_HISTORY
2324 isfwd = FAL0;
2326 if((*len = a_tty_khist(tlp, isfwd)) != UI32_MAX){
2327 rv = a_TTY_FUN_STATUS_RESTART;
2328 break;
2330 goto jreset;
2331 # endif
2333 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2334 break;
2336 case a_X(HIST_SRCH_FWD):{
2337 # ifdef HAVE_HISTORY
2338 bool_t isfwd = TRU1;
2340 if(0){
2341 # endif
2342 /* FALLTHRU */
2343 case a_X(HIST_SRCH_BWD):
2344 # ifdef HAVE_HISTORY
2345 isfwd = FAL0;
2347 if((*len = a_tty_khist_search(tlp, isfwd)) != UI32_MAX){
2348 rv = a_TTY_FUN_STATUS_RESTART;
2349 break;
2351 goto jreset;
2352 # else
2353 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2354 # endif
2355 } break;
2357 case a_X(REPAINT):
2358 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2359 break;
2360 case a_X(QUOTE_RNDTRIP):
2361 tlp->tl_quote_rndtrip = !tlp->tl_quote_rndtrip;
2362 break;
2363 case a_X(PROMPT_CHAR):{
2364 wchar_t wc;
2366 if((wc = a_tty_vinuni(tlp)) > 0)
2367 a_tty_kother(tlp, wc);
2368 } break;
2369 case a_X(COMPLETE):
2370 if((*len = a_tty_kht(tlp)) > 0)
2371 rv = a_TTY_FUN_STATUS_RESTART;
2372 break;
2374 case a_X(PASTE):
2375 if(tlp->tl_pastebuf.l > 0)
2376 *len = (tlp->tl_defc = tlp->tl_pastebuf).l;
2377 else
2378 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2379 break;
2382 case a_X(CANCEL):
2383 /* Normally this just causes a restart and thus resets the state
2384 * machine */
2385 if(tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2387 # ifdef HAVE_KEY_BINDINGS
2388 tlp->tl_bind_takeover = '\0';
2389 # endif
2390 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2391 rv = a_TTY_FUN_STATUS_RESTART;
2392 break;
2394 case a_X(RESET):
2395 if(tlp->tl_count == 0 && tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2396 # ifdef HAVE_KEY_BINDINGS
2397 tlp->tl_bind_takeover = '\0';
2398 # endif
2399 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY | a_TTY_VF_BELL;
2400 break;
2401 }else if(0){
2402 case a_X(FULLRESET):
2403 tlp->tl_savec.s = tlp->tl_defc.s = NULL;
2404 tlp->tl_savec.l = tlp->tl_defc.l = 0;
2405 tlp->tl_defc_cursor_byte = 0;
2406 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2408 jreset:
2409 # ifdef HAVE_KEY_BINDINGS
2410 tlp->tl_bind_takeover = '\0';
2411 # endif
2412 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2413 tlp->tl_cursor = tlp->tl_count = 0;
2414 # ifdef HAVE_HISTORY
2415 tlp->tl_hist = NULL;
2416 # endif
2417 if((*len = tlp->tl_savec.l) != 0){
2418 tlp->tl_defc = tlp->tl_savec;
2419 tlp->tl_savec.s = NULL;
2420 tlp->tl_savec.l = 0;
2421 }else
2422 *len = tlp->tl_defc.l;
2423 rv = a_TTY_FUN_STATUS_RESTART;
2424 break;
2426 default:
2427 case a_X(COMMIT):
2428 rv = a_TTY_FUN_STATUS_COMMIT;
2429 break;
2431 # undef a_X
2433 NYD2_LEAVE;
2434 return rv;
2437 static ssize_t
2438 a_tty_readline(struct a_tty_line *tlp, size_t len n_MEMORY_DEBUG_ARGS){
2439 /* We want to save code, yet we may have to incorporate a lines'
2440 * default content and / or default input to switch back to after some
2441 * history movement; let "len > 0" mean "have to display some data
2442 * buffer" -> a_BUFMODE, and only otherwise read(2) it */
2443 mbstate_t ps[2];
2444 char cbuf_base[MB_LEN_MAX * 2], *cbuf, *cbufp;
2445 ssize_t rv;
2446 struct a_tty_bind_tree *tbtp;
2447 wchar_t wc;
2448 enum a_tty_bind_flags tbf;
2449 enum {a_NONE, a_WAS_HERE = 1<<0, a_BUFMODE = 1<<1, a_MAYBEFUN = 1<<2,
2450 a_TIMEOUT = 1<<3, a_TIMEOUT_EXPIRED = 1<<4,
2451 a_TIMEOUT_MASK = a_TIMEOUT | a_TIMEOUT_EXPIRED,
2452 a_READ_LOOP_MASK = ~(a_WAS_HERE | a_MAYBEFUN | a_TIMEOUT_MASK)
2453 } flags;
2454 NYD_ENTER;
2456 n_UNINIT(rv, 0);
2457 # ifdef HAVE_KEY_BINDINGS
2458 assert(tlp->tl_bind_takeover == '\0');
2459 # endif
2460 jrestart:
2461 memset(ps, 0, sizeof ps);
2462 flags = a_NONE;
2463 tbf = 0;
2464 tlp->tl_vi_flags |= a_TTY_VF_REFRESH | a_TTY_VF_SYNC;
2466 jinput_loop:
2467 for(;;){
2468 if(len != 0)
2469 flags |= a_BUFMODE;
2471 /* Ensure we have valid pointers, and room for grow */
2472 a_tty_check_grow(tlp, ((flags & a_BUFMODE) ? (ui32_t)len : 1)
2473 n_MEMORY_DEBUG_ARGSCALL);
2475 /* Handle visual state flags, except in buffer mode */
2476 if(!(flags & a_BUFMODE) && (tlp->tl_vi_flags & a_TTY_VF_ALL_MASK))
2477 if(!a_tty_vi_refresh(tlp)){
2478 rv = -1;
2479 goto jleave;
2482 /* Ready for messing around.
2483 * Normal read(2)? Else buffer mode: speed this one up */
2484 if(!(flags & a_BUFMODE)){
2485 cbufp =
2486 cbuf = cbuf_base;
2487 }else{
2488 assert(tlp->tl_defc.l > 0 && tlp->tl_defc.s != NULL);
2489 assert(tlp->tl_defc.l >= len);
2490 cbufp =
2491 cbuf = tlp->tl_defc.s + (tlp->tl_defc.l - len);
2492 cbufp += len;
2495 /* Read in the next complete multibyte character */
2496 /* C99 */{
2497 # ifdef HAVE_KEY_BINDINGS
2498 struct a_tty_bind_tree *xtbtp;
2499 struct inseq{
2500 struct inseq *last;
2501 struct inseq *next;
2502 struct a_tty_bind_tree *tbtp;
2503 } *isp_head, *isp;
2505 isp_head = isp = NULL;
2506 # endif
2508 for(flags &= a_READ_LOOP_MASK;;){
2509 # ifdef HAVE_KEY_BINDINGS
2510 if(!(flags & a_BUFMODE) && tlp->tl_bind_takeover != '\0'){
2511 wc = tlp->tl_bind_takeover;
2512 tlp->tl_bind_takeover = '\0';
2513 }else
2514 # endif
2516 if(!(flags & a_BUFMODE)){
2517 /* Let me at least once dream of iomon(itor), timer with
2518 * one-shot, enwrapped with key_event and key_sequence_event,
2519 * all driven by an event_loop */
2520 /* TODO v15 Until we have SysV signal handling all through we
2521 * TODO need to temporarily adjust our BSD signal handler with
2522 * TODO a SysV one, here */
2523 n_sighdl_t otstp, ottin, ottou;
2525 otstp = n_signal(SIGTSTP, &n_tty_signal);
2526 ottin = n_signal(SIGTTIN, &n_tty_signal);
2527 ottou = n_signal(SIGTTOU, &n_tty_signal);
2528 # ifdef HAVE_KEY_BINDINGS
2529 flags &= ~a_TIMEOUT_MASK;
2530 if(isp != NULL && (tbtp = isp->tbtp)->tbt_isseq &&
2531 !tbtp->tbt_isseq_trail){
2532 a_tty_term_rawmode_timeout(tlp, TRU1);
2533 flags |= a_TIMEOUT;
2535 # endif
2537 while((rv = read(STDIN_FILENO, cbufp, 1)) < 1){
2538 if(rv == -1){
2539 if(errno == EINTR){
2540 if((tlp->tl_vi_flags & a_TTY_VF_MOD_DIRTY) &&
2541 !a_tty_vi_refresh(tlp))
2542 break;
2543 continue;
2545 break;
2548 # ifdef HAVE_KEY_BINDINGS
2549 /* Timeout expiration */
2550 if(rv == 0){
2551 assert(flags & a_TIMEOUT);
2552 assert(isp != NULL);
2553 a_tty_term_rawmode_timeout(tlp, FAL0);
2555 /* Something "atomic" broke. Maybe the current one can
2556 * also be terminated already, by itself? xxx really? */
2557 if((tbtp = isp->tbtp)->tbt_bind != NULL){
2558 tlp->tl_bind_takeover = wc;
2559 goto jhave_bind;
2562 /* Or, maybe there is a second path without a timeout;
2563 * this should be covered by .tbt_isseq_trail, but then
2564 * again a single-layer implementation cannot "know" */
2565 for(xtbtp = tbtp; (xtbtp = xtbtp->tbt_sibling) != NULL;)
2566 if(xtbtp->tbt_char == tbtp->tbt_char){
2567 assert(!xtbtp->tbt_isseq);
2568 break;
2570 /* Lay down on read(2)? */
2571 if(xtbtp != NULL)
2572 continue;
2573 goto jtake_over;
2575 # endif /* HAVE_KEY_BINDINGS */
2578 # ifdef HAVE_KEY_BINDINGS
2579 if(flags & a_TIMEOUT)
2580 a_tty_term_rawmode_timeout(tlp, FAL0);
2581 # endif
2582 safe_signal(SIGTSTP, otstp);
2583 safe_signal(SIGTTIN, ottin);
2584 safe_signal(SIGTTOU, ottou);
2585 if(rv < 0)
2586 goto jleave;
2588 ++cbufp;
2591 rv = (ssize_t)mbrtowc(&wc, cbuf, PTR2SIZE(cbufp - cbuf), &ps[0]);
2592 if(rv <= 0){
2593 /* Any error during buffer mode can only result in a hard
2594 * reset; Otherwise, if it's a hard error, or if too many
2595 * redundant shift sequences overflow our buffer: perform
2596 * hard reset */
2597 if((flags & a_BUFMODE) || rv == -1 ||
2598 sizeof cbuf_base == PTR2SIZE(cbufp - cbuf)){
2599 a_tty_fun(tlp, a_TTY_BIND_FUN_FULLRESET, &len);
2600 goto jrestart;
2602 /* Otherwise, due to the way we deal with the buffer, we need
2603 * to restore the mbstate_t from before this conversion */
2604 ps[0] = ps[1];
2605 continue;
2607 cbufp = cbuf;
2608 ps[1] = ps[0];
2611 /* Normal read(2)ing is subject to detection of key-bindings */
2612 # ifdef HAVE_KEY_BINDINGS
2613 if(!(flags & a_BUFMODE)){
2614 /* Check for special bypass functions before we try to embed
2615 * this character into the tree */
2616 if(n_uasciichar(wc)){
2617 char c;
2618 char const *cp;
2620 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_prompt_char)[0];
2621 *cp != '\0'; ++cp){
2622 if(c == *cp){
2623 wc = a_tty_vinuni(tlp);
2624 break;
2627 if(wc == '\0'){
2628 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2629 goto jinput_loop;
2632 if(n_uasciichar(wc))
2633 flags |= a_MAYBEFUN;
2634 else
2635 flags &= ~a_MAYBEFUN;
2637 /* Search for this character in the bind tree */
2638 tbtp = (isp != NULL) ? isp->tbtp->tbt_childs
2639 : (*tlp->tl_bind_tree_hmap)[wc % HSHSIZE];
2640 for(; tbtp != NULL; tbtp = tbtp->tbt_sibling){
2641 if(tbtp->tbt_char == wc){
2642 struct inseq *nisp;
2644 /* If this one cannot continue we're likely finished! */
2645 if(tbtp->tbt_childs == NULL){
2646 assert(tbtp->tbt_bind != NULL);
2647 tbf = tbtp->tbt_bind->tbc_flags;
2648 goto jmle_fun;
2651 /* This needs to read more characters */
2652 nisp = salloc(sizeof *nisp);
2653 if((nisp->last = isp) == NULL)
2654 isp_head = nisp;
2655 else
2656 isp->next = nisp;
2657 nisp->next = NULL;
2658 nisp->tbtp = tbtp;
2659 isp = nisp;
2660 flags &= ~a_WAS_HERE;
2661 break;
2664 if(tbtp != NULL)
2665 continue;
2667 /* Was there a binding active, but couldn't be continued? */
2668 if(isp != NULL){
2669 /* A binding had a timeout, it didn't expire, but we saw
2670 * something non-expected. Something "atomic" broke.
2671 * Maybe there is a second path without a timeout, that
2672 * continues like we've seen it. I.e., it may just have been
2673 * the user, typing two fast. We definitely want to allow
2674 * bindings like \e,d etc. to succeed: users are so used to
2675 * them that a timeout cannot be the mechanism to catch up!
2676 * A single-layer implementation cannot "know" */
2677 if((tbtp = isp->tbtp)->tbt_isseq && (isp->last == NULL ||
2678 !(xtbtp = isp->last->tbtp)->tbt_isseq ||
2679 xtbtp->tbt_isseq_trail)){
2680 for(xtbtp = (tbtp = isp->tbtp);
2681 (xtbtp = xtbtp->tbt_sibling) != NULL;)
2682 if(xtbtp->tbt_char == tbtp->tbt_char){
2683 assert(!xtbtp->tbt_isseq);
2684 break;
2686 if(xtbtp != NULL){
2687 isp->tbtp = xtbtp;
2688 tlp->tl_bind_takeover = wc;
2689 continue;
2693 /* Check for CANCEL shortcut now */
2694 if(flags & a_MAYBEFUN){
2695 char c;
2696 char const *cp;
2698 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_cancel)[0];
2699 *cp != '\0'; ++cp)
2700 if(c == *cp){
2701 tbf = a_TTY_BIND_FUN_INTERNAL |a_TTY_BIND_FUN_CANCEL;
2702 goto jmle_fun;
2706 /* So: maybe the current sequence can be terminated here? */
2707 if((tbtp = isp->tbtp)->tbt_bind != NULL){
2708 jhave_bind:
2709 tbf = tbtp->tbt_bind->tbc_flags;
2710 jmle_fun:
2711 if(tbf & a_TTY_BIND_FUN_INTERNAL){
2712 switch(a_tty_fun(tlp, tbf, &len)){
2713 case a_TTY_FUN_STATUS_OK:
2714 goto jinput_loop;
2715 case a_TTY_FUN_STATUS_COMMIT:
2716 goto jdone;
2717 case a_TTY_FUN_STATUS_RESTART:
2718 goto jrestart;
2719 case a_TTY_FUN_STATUS_END:
2720 goto jleave;
2722 assert(0);
2723 }else if(tbtp->tbt_bind->tbc_flags & a_TTY_BIND_NOCOMMIT){
2724 struct a_tty_bind_ctx *tbcp;
2726 tbcp = tbtp->tbt_bind;
2727 memcpy(tlp->tl_defc.s = salloc(
2728 (tlp->tl_defc.l = len = tbcp->tbc_exp_len) +1),
2729 tbcp->tbc_exp, tbcp->tbc_exp_len +1);
2730 goto jrestart;
2731 }else{
2732 tlp->tl_reenter_after_cmd = tbtp->tbt_bind->tbc_exp;
2733 goto jdone;
2738 /* Otherwise take over all chars "as is" */
2739 jtake_over:
2740 for(; isp_head != NULL; isp_head = isp_head->next)
2741 if(a_tty_kother(tlp, isp_head->tbtp->tbt_char)){
2742 /* FIXME */
2744 /* And the current one too */
2745 goto jkother;
2747 # endif /* HAVE_KEY_BINDINGS */
2749 if((flags & a_BUFMODE) && (len -= (size_t)rv) == 0){
2750 /* Buffer mode completed */
2751 tlp->tl_defc.s = NULL;
2752 tlp->tl_defc.l = 0;
2753 flags &= ~a_BUFMODE;
2755 break;
2758 # ifndef HAVE_KEY_BINDINGS
2759 /* Don't interpret control bytes during buffer mode.
2760 * Otherwise, if it's a control byte check whether it is a MLE
2761 * function. Remarks: initially a complete duplicate to be able to
2762 * switch(), later converted to simply iterate over (an #ifdef'd
2763 * subset of) the MLE default_tuple table in order to have "a SPOF" */
2764 if(cbuf == cbuf_base && n_uasciichar(wc) && cntrlchar((char)wc)){
2765 struct a_tty_bind_default_tuple const *tbdtp;
2766 char c;
2768 for(c = (char)wc ^ 0x40, tbdtp = a_tty_bind_default_tuples;
2769 PTRCMP(tbdtp, <, &a_tty_bind_default_tuples[
2770 n_NELEM(a_tty_bind_default_tuples)]);
2771 ++tbdtp){
2772 /* Assert default_tuple table is properly subset'ed */
2773 assert(tbdtp->tbdt_iskey);
2774 if(tbdtp->tbdt_ckey == c){
2775 if(tbdtp->tbdt_exp[0] == '\0'){
2776 enum a_tty_bind_flags tbf;
2778 tbf = a_TTY_BIND_FUN_EXPAND((ui8_t)tbdtp->tbdt_exp[1]);
2779 switch(a_tty_fun(tlp, tbf, &len)){
2780 case a_TTY_FUN_STATUS_OK:
2781 goto jinput_loop;
2782 case a_TTY_FUN_STATUS_COMMIT:
2783 goto jdone;
2784 case a_TTY_FUN_STATUS_RESTART:
2785 goto jrestart;
2786 case a_TTY_FUN_STATUS_END:
2787 goto jleave;
2789 assert(0);
2790 }else{
2791 tlp->tl_reenter_after_cmd = tbdtp->tbdt_exp;
2792 goto jdone;
2797 # endif /* !HAVE_KEY_BINDINGS */
2799 # ifdef HAVE_KEY_BINDINGS
2800 jkother:
2801 # endif
2802 if(a_tty_kother(tlp, wc)){
2803 /* Don't clear the history during buffer mode.. */
2804 # ifdef HAVE_HISTORY
2805 if(!(flags & a_BUFMODE) && cbuf == cbuf_base)
2806 tlp->tl_hist = NULL;
2807 # endif
2812 /* We have a completed input line, convert the struct cell data to its
2813 * plain character equivalent */
2814 jdone:
2815 rv = a_tty_cell2dat(tlp);
2816 jleave:
2817 putchar('\n');
2818 fflush(stdout);
2819 NYD_LEAVE;
2820 return rv;
2823 # ifdef HAVE_KEY_BINDINGS
2824 static enum n_lexinput_flags
2825 a_tty_bind_ctx_find(char const *name){
2826 enum n_lexinput_flags rv;
2827 struct a_tty_bind_ctx_map const *tbcmp;
2828 NYD2_ENTER;
2830 tbcmp = a_tty_bind_ctx_maps;
2831 do if(!asccasecmp(tbcmp->tbcm_name, name)){
2832 rv = tbcmp->tbcm_ctx;
2833 goto jleave;
2834 }while(PTRCMP(++tbcmp, <,
2835 &a_tty_bind_ctx_maps[n_NELEM(a_tty_bind_ctx_maps)]));
2837 rv = (enum n_lexinput_flags)-1;
2838 jleave:
2839 NYD2_LEAVE;
2840 return rv;
2843 static bool_t
2844 a_tty_bind_create(struct a_tty_bind_parse_ctx *tbpcp, bool_t replace){
2845 struct a_tty_bind_ctx *tbcp;
2846 bool_t rv;
2847 NYD2_ENTER;
2849 rv = FAL0;
2851 if(!a_tty_bind_parse(TRU1, tbpcp))
2852 goto jleave;
2854 /* Since we use a single buffer for it all, need to replace as such */
2855 if(tbpcp->tbpc_tbcp != NULL){
2856 if(!replace)
2857 goto jleave;
2858 a_tty_bind_del(tbpcp);
2859 }else if(a_tty.tg_bind_cnt == UI32_MAX){
2860 n_err(_("`bind': maximum number of bindings already established\n"));
2861 goto jleave;
2864 /* C99 */{
2865 size_t i, j;
2867 tbcp = smalloc(sizeof(*tbcp) -
2868 n_VFIELD_SIZEOF(struct a_tty_bind_ctx, tbc__buf) +
2869 tbpcp->tbpc_seq_len + tbpcp->tbpc_exp.l +
2870 n_MAX(sizeof(si32_t), sizeof(wc_t)) + tbpcp->tbpc_cnv_len +3);
2871 if(tbpcp->tbpc_ltbcp != NULL){
2872 tbcp->tbc_next = tbpcp->tbpc_ltbcp->tbc_next;
2873 tbpcp->tbpc_ltbcp->tbc_next = tbcp;
2874 }else{
2875 enum n_lexinput_flags lif = tbpcp->tbpc_flags & n__LEXINPUT_CTX_MASK;
2877 tbcp->tbc_next = a_tty.tg_bind[lif];
2878 a_tty.tg_bind[lif] = tbcp;
2880 memcpy(tbcp->tbc_seq = &tbcp->tbc__buf[0],
2881 tbpcp->tbpc_seq, i = (tbcp->tbc_seq_len = tbpcp->tbpc_seq_len) +1);
2882 memcpy(tbcp->tbc_exp = &tbcp->tbc__buf[i],
2883 tbpcp->tbpc_exp.s, j = (tbcp->tbc_exp_len = tbpcp->tbpc_exp.l) +1);
2884 i += j;
2885 i = (i + tbpcp->tbpc_cnv_align_mask) & ~tbpcp->tbpc_cnv_align_mask;
2886 memcpy(tbcp->tbc_cnv = &tbcp->tbc__buf[i],
2887 tbpcp->tbpc_cnv, (tbcp->tbc_cnv_len = tbpcp->tbpc_cnv_len) +1);
2888 tbcp->tbc_flags = tbpcp->tbpc_flags;
2891 /* Directly resolve any termcap(5) symbol if we are already setup */
2892 if((pstate & PS_STARTED) &&
2893 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
2894 a_TTY_BIND_RESOLVE)
2895 a_tty_bind_resolve(tbcp);
2897 ++a_tty.tg_bind_cnt;
2898 /* If this binding is usable invalidate the key input lookup trees */
2899 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
2900 a_tty.tg_bind_isdirty = TRU1;
2901 rv = TRU1;
2902 jleave:
2903 NYD2_LEAVE;
2904 return rv;
2907 static bool_t
2908 a_tty_bind_parse(bool_t isbindcmd, struct a_tty_bind_parse_ctx *tbpcp){
2909 enum{a_TRUE_RV = a_TTY__BIND_LAST<<1};
2911 struct n_visual_info_ctx vic;
2912 struct str shin_save, shin;
2913 struct n_string shou, *shoup;
2914 size_t i;
2915 struct kse{
2916 struct kse *next;
2917 char *seq_dat;
2918 wc_t *cnv_dat;
2919 ui32_t seq_len;
2920 ui32_t cnv_len; /* High bit set if a termap to be resolved */
2921 ui32_t calc_cnv_len; /* Ditto, but aligned etc. */
2922 ui8_t kse__dummy[4];
2923 } *head, *tail;
2924 ui32_t f;
2925 NYD2_ENTER;
2926 n_LCTA(UICMP(64, a_TRUE_RV, <, UI32_MAX),
2927 "Flag bits excess storage datatype");
2929 f = n_LEXINPUT_NONE;
2930 shoup = n_string_creat_auto(&shou);
2931 head = tail = NULL;
2933 /* Parse the key-sequence */
2934 for(shin.s = n_UNCONST(tbpcp->tbpc_in_seq), shin.l = UIZ_MAX;;){
2935 struct kse *ep;
2936 enum n_shexp_state shs;
2938 shin_save = shin;
2939 shs = n_shexp_parse_token(shoup, &shin,
2940 n_SHEXP_PARSE_TRUNC | n_SHEXP_PARSE_TRIMSPACE |
2941 n_SHEXP_PARSE_IGNORE_EMPTY | n_SHEXP_PARSE_IFS_IS_COMMA);
2942 if(shs & n_SHEXP_STATE_ERR_UNICODE){
2943 f |= a_TTY_BIND_DEFUNCT;
2944 if(isbindcmd && (options & OPT_D_V))
2945 n_err(_("`%s': \\uNICODE not available in locale: %s\n"),
2946 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
2948 if((shs & n_SHEXP_STATE_ERR_MASK) & ~n_SHEXP_STATE_ERR_UNICODE){
2949 n_err(_("`%s': failed to parse key-sequence: %s\n"),
2950 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
2951 goto jleave;
2953 if((shs & (n_SHEXP_STATE_OUTPUT | n_SHEXP_STATE_STOP)) ==
2954 n_SHEXP_STATE_STOP)
2955 break;
2957 ep = salloc(sizeof *ep);
2958 if(head == NULL)
2959 head = ep;
2960 else
2961 tail->next = ep;
2962 tail = ep;
2963 ep->next = NULL;
2964 if(!(shs & n_SHEXP_STATE_ERR_UNICODE)){
2965 i = strlen(ep->seq_dat = n_shexp_quote_cp(n_string_cp(shoup), TRU1));
2966 if(i >= SI32_MAX - 1)
2967 goto jelen;
2968 ep->seq_len = (ui32_t)i;
2969 }else{
2970 /* Otherwise use the original buffer, _we_ can only quote it the wrong
2971 * way (e.g., an initial $'\u3a' becomes '\u3a'), _then_ */
2972 if((i = shin_save.l - shin.l) >= SI32_MAX - 1)
2973 goto jelen;
2974 ep->seq_len = (ui32_t)i;
2975 ep->seq_dat = savestrbuf(shin_save.s, i);
2978 memset(&vic, 0, sizeof vic);
2979 vic.vic_inlen = shoup->s_len;
2980 vic.vic_indat = shoup->s_dat;
2981 if(!n_visual_info(&vic,
2982 n_VISUAL_INFO_WOUT_CREATE | n_VISUAL_INFO_WOUT_SALLOC)){
2983 n_err(_("`%s': key-sequence seems to contain invalid "
2984 "characters: %s: %s\n"),
2985 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
2986 f |= a_TTY_BIND_DEFUNCT;
2987 goto jleave;
2988 }else if(vic.vic_woulen == 0 ||
2989 vic.vic_woulen >= (SI32_MAX - 2) / sizeof(wc_t)){
2990 jelen:
2991 n_err(_("`%s': length of key-sequence unsupported: %s: %s\n"),
2992 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
2993 f |= a_TTY_BIND_DEFUNCT;
2994 goto jleave;
2996 ep->cnv_dat = vic.vic_woudat;
2997 ep->cnv_len = (ui32_t)vic.vic_woulen;
2999 /* A termcap(5)/terminfo(5) identifier? */
3000 if(ep->cnv_len > 1 && ep->cnv_dat[0] == ':'){
3001 i = --ep->cnv_len, ++ep->cnv_dat;
3002 # ifndef HAVE_TERMCAP
3003 if(options & OPT_D_V)
3004 n_err(_("`%s': no termcap(5)/terminfo(5) support: %s: %s\n"),
3005 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3006 f |= a_TTY_BIND_DEFUNCT;
3007 # endif
3008 if(i > a_TTY_BIND_CAPNAME_MAX){
3009 n_err(_("`%s': termcap(5)/terminfo(5) name too long: %s: %s\n"),
3010 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3011 f |= a_TTY_BIND_DEFUNCT;
3013 while(i > 0)
3014 /* (We store it as char[]) */
3015 if((ui32_t)ep->cnv_dat[--i] & ~0x7Fu){
3016 n_err(_("`%s': invalid termcap(5)/terminfo(5) name content: "
3017 "%s: %s\n"),
3018 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3019 f |= a_TTY_BIND_DEFUNCT;
3020 break;
3022 ep->cnv_len |= SI32_MIN; /* Needs resolve */
3023 f |= a_TTY_BIND_RESOLVE;
3026 if(shs & n_SHEXP_STATE_STOP)
3027 break;
3030 if(head == NULL){
3031 jeempty:
3032 n_err(_("`%s': effectively empty key-sequence: %s\n"),
3033 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3034 goto jleave;
3037 if(isbindcmd) /* (Or always, just "1st time init") */
3038 tbpcp->tbpc_cnv_align_mask = n_MAX(sizeof(si32_t), sizeof(wc_t)) - 1;
3040 /* C99 */{
3041 struct a_tty_bind_ctx *ltbcp, *tbcp;
3042 char *cpbase, *cp, *cnv;
3043 size_t sl, cl;
3045 /* Unite the parsed sequence(s) into single string representations */
3046 for(sl = cl = 0, tail = head; tail != NULL; tail = tail->next){
3047 sl += tail->seq_len + 1;
3049 if(!isbindcmd)
3050 continue;
3052 /* Preserve room for terminal capabilities to be resolved.
3053 * Above we have ensured the buffer will fit in these calculations */
3054 if((i = tail->cnv_len) & SI32_MIN){
3055 /* For now
3056 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[]+NUL;}
3057 * later
3058 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3059 n_LCTAV(n_ISPOW2(a_TTY_BIND_CAPEXP_ROUNDUP));
3060 n_LCTA(a_TTY_BIND_CAPEXP_ROUNDUP >= sizeof(wc_t),
3061 "Aligning on this constant doesn't properly align wc_t");
3062 i &= SI32_MAX;
3063 i *= sizeof(wc_t);
3064 i += sizeof(si32_t);
3065 if(i < a_TTY_BIND_CAPEXP_ROUNDUP)
3066 i = (i + (a_TTY_BIND_CAPEXP_ROUNDUP - 1)) &
3067 ~(a_TTY_BIND_CAPEXP_ROUNDUP - 1);
3068 }else
3069 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3070 i *= sizeof(wc_t);
3071 i += sizeof(si32_t) + sizeof(wc_t); /* (buf_len_iscap, NUL) */
3072 cl += i;
3073 if(tail->cnv_len & SI32_MIN){
3074 tail->cnv_len &= SI32_MAX;
3075 i |= SI32_MIN;
3077 tail->calc_cnv_len = (ui32_t)i;
3079 --sl;
3081 tbpcp->tbpc_seq_len = sl;
3082 tbpcp->tbpc_cnv_len = cl;
3083 /* C99 */{
3084 size_t j;
3086 j = i = sl + 1; /* Room for comma separator */
3087 if(isbindcmd){
3088 i = (i + tbpcp->tbpc_cnv_align_mask) & ~tbpcp->tbpc_cnv_align_mask;
3089 j = i;
3090 i += cl;
3092 tbpcp->tbpc_seq = cp = cpbase = salloc(i);
3093 tbpcp->tbpc_cnv = cnv = &cpbase[j];
3096 for(tail = head; tail != NULL; tail = tail->next){
3097 memcpy(cp, tail->seq_dat, tail->seq_len);
3098 cp += tail->seq_len;
3099 *cp++ = ',';
3101 if(isbindcmd){
3102 char * const save_cnv = cnv;
3104 n_UNALIGN(si32_t*,cnv)[0] = (si32_t)(i = tail->calc_cnv_len);
3105 cnv += sizeof(si32_t);
3106 if(i & SI32_MIN){
3107 /* For now
3108 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];}
3109 * later
3110 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[];} */
3111 n_UNALIGN(si32_t*,cnv)[0] = tail->cnv_len;
3112 cnv += sizeof(si32_t);
3114 i = tail->cnv_len * sizeof(wc_t);
3115 memcpy(cnv, tail->cnv_dat, i);
3116 cnv += i;
3117 *n_UNALIGN(wc_t*,cnv) = '\0';
3119 cnv = save_cnv + (tail->calc_cnv_len & SI32_MAX);
3122 *--cp = '\0';
3124 /* Search for a yet existing identical mapping */
3125 for(ltbcp = NULL, tbcp = a_tty.tg_bind[tbpcp->tbpc_flags]; tbcp != NULL;
3126 ltbcp = tbcp, tbcp = tbcp->tbc_next)
3127 if(tbcp->tbc_seq_len == sl && !memcmp(tbcp->tbc_seq, cpbase, sl)){
3128 tbpcp->tbpc_tbcp = tbcp;
3129 break;
3131 tbpcp->tbpc_ltbcp = ltbcp;
3132 tbpcp->tbpc_flags |= (f & a_TTY__BIND_MASK);
3135 /* Create single string expansion if so desired */
3136 if(isbindcmd){
3137 char *exp;
3139 exp = tbpcp->tbpc_exp.s;
3141 i = tbpcp->tbpc_exp.l;
3142 if(i > 0 && exp[i - 1] == '@'){
3143 while(--i > 0){
3144 if(!blankspacechar(exp[i - 1]))
3145 break;
3147 if(i == 0)
3148 goto jeempty;
3150 exp[tbpcp->tbpc_exp.l = i] = '\0';
3151 tbpcp->tbpc_flags |= a_TTY_BIND_NOCOMMIT;
3154 /* Reverse solidus cannot be placed last in expansion to avoid (at the
3155 * time of this writing) possible problems with newline escaping.
3156 * Don't care about (un)even number thereof */
3157 if(i > 0 && exp[i - 1] == '\\'){
3158 n_err(_("`%s': reverse solidus cannot be last in expansion: %s\n"),
3159 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3160 goto jleave;
3163 /* It may map to an internal MLE command! */
3164 for(i = 0; i < n_NELEM(a_tty_bind_fun_names); ++i)
3165 if(!asccasecmp(exp, a_tty_bind_fun_names[i])){
3166 tbpcp->tbpc_flags |= a_TTY_BIND_FUN_EXPAND(i) |
3167 a_TTY_BIND_FUN_INTERNAL |
3168 (head->next == NULL ? a_TTY_BIND_MLE1CNTRL : 0);
3169 if((options & OPT_D_V) && (tbpcp->tbpc_flags & a_TTY_BIND_NOCOMMIT))
3170 n_err(_("`%s': MLE commands can't be made editable via @: %s\n"),
3171 tbpcp->tbpc_cmd, exp);
3172 tbpcp->tbpc_flags &= ~a_TTY_BIND_NOCOMMIT;
3173 break;
3177 f |= a_TRUE_RV; /* TODO because we only now true and false; DEFUNCT.. */
3178 jleave:
3179 n_string_gut(shoup);
3180 NYD2_LEAVE;
3181 return (f & a_TRUE_RV) != 0;
3184 static void
3185 a_tty_bind_resolve(struct a_tty_bind_ctx *tbcp){
3186 char capname[a_TTY_BIND_CAPNAME_MAX +1];
3187 struct n_termcap_value tv;
3188 size_t len;
3189 bool_t isfirst; /* TODO For now: first char must be control! */
3190 char *cp, *next;
3191 NYD2_ENTER;
3193 n_UNINIT(next, NULL);
3194 for(cp = tbcp->tbc_cnv, isfirst = TRU1, len = tbcp->tbc_cnv_len;
3195 len > 0; isfirst = FAL0, cp = next){
3196 /* C99 */{
3197 si32_t i, j;
3199 i = n_UNALIGN(si32_t*,cp)[0];
3200 j = i & SI32_MAX;
3201 next = &cp[j];
3202 len -= j;
3203 if(i == j)
3204 continue;
3206 /* struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];} */
3207 cp += sizeof(si32_t);
3208 i = n_UNALIGN(si32_t*,cp)[0];
3209 cp += sizeof(si32_t);
3210 for(j = 0; j < i; ++j)
3211 capname[j] = n_UNALIGN(wc_t*,cp)[j];
3212 capname[j] = '\0';
3215 /* Use generic lookup mechanism if not a known query */
3216 /* C99 */{
3217 si32_t tq;
3219 tq = n_termcap_query_for_name(capname, n_TERMCAP_CAPTYPE_STRING);
3220 if(tq == -1){
3221 tv.tv_data.tvd_string = capname;
3222 tq = n__TERMCAP_QUERY_MAX;
3225 if(tq < 0 || !n_termcap_query(tq, &tv)){
3226 if(options & OPT_D_V)
3227 n_err(_("`bind': unknown or unsupported capability: %s: %s\n"),
3228 capname, tbcp->tbc_seq);
3229 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3230 break;
3234 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3235 /* C99 */{
3236 size_t i;
3238 i = strlen(tv.tv_data.tvd_string);
3239 if(/*i > SI32_MAX ||*/ i >= PTR2SIZE(next - cp)){
3240 if(options & OPT_D_V)
3241 n_err(_("`bind': capability expansion too long: %s: %s\n"),
3242 capname, tbcp->tbc_seq);
3243 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3244 break;
3245 }else if(i == 0){
3246 if(options & OPT_D_V)
3247 n_err(_("`bind': empty capability expansion: %s: %s\n"),
3248 capname, tbcp->tbc_seq);
3249 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3250 break;
3251 }else if(isfirst && !cntrlchar(*tv.tv_data.tvd_string)){
3252 if(options & OPT_D_V)
3253 n_err(_("`bind': capability expansion doesn't start with "
3254 "control: %s: %s\n"), capname, tbcp->tbc_seq);
3255 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3256 break;
3258 n_UNALIGN(si32_t*,cp)[-1] = (si32_t)i;
3259 memcpy(cp, tv.tv_data.tvd_string, i);
3260 cp[i] = '\0';
3263 NYD2_LEAVE;
3266 static void
3267 a_tty_bind_del(struct a_tty_bind_parse_ctx *tbpcp){
3268 struct a_tty_bind_ctx *ltbcp, *tbcp;
3269 NYD2_ENTER;
3271 tbcp = tbpcp->tbpc_tbcp;
3273 if((ltbcp = tbpcp->tbpc_ltbcp) != NULL)
3274 ltbcp->tbc_next = tbcp->tbc_next;
3275 else
3276 a_tty.tg_bind[tbpcp->tbpc_flags] = tbcp->tbc_next;
3277 free(tbcp);
3279 --a_tty.tg_bind_cnt;
3280 a_tty.tg_bind_isdirty = TRU1;
3281 NYD2_LEAVE;
3284 static void
3285 a_tty_bind_tree_build(void){
3286 size_t i;
3287 NYD2_ENTER;
3289 for(i = 0; i < n__LEXINPUT_CTX_MAX; ++i){
3290 struct a_tty_bind_ctx *tbcp;
3291 n_LCTAV(n_LEXINPUT_CTX_BASE == 0);
3293 /* Somewhat wasteful, but easier to handle: simply clone the entire
3294 * primary key onto the secondary one, then only modify it */
3295 for(tbcp = a_tty.tg_bind[n_LEXINPUT_CTX_BASE]; tbcp != NULL;
3296 tbcp = tbcp->tbc_next)
3297 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3298 a_tty__bind_tree_add(n_LEXINPUT_CTX_BASE, &a_tty.tg_bind_tree[i][0],
3299 tbcp);
3301 if(i != n_LEXINPUT_CTX_BASE)
3302 for(tbcp = a_tty.tg_bind[i]; tbcp != NULL; tbcp = tbcp->tbc_next)
3303 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3304 a_tty__bind_tree_add(i, &a_tty.tg_bind_tree[i][0], tbcp);
3307 a_tty.tg_bind_isbuild = TRU1;
3308 NYD2_LEAVE;
3311 static void
3312 a_tty_bind_tree_teardown(void){
3313 size_t i, j;
3314 NYD2_ENTER;
3316 memset(&a_tty.tg_bind_shcut_cancel[0], 0,
3317 sizeof(a_tty.tg_bind_shcut_cancel));
3318 memset(&a_tty.tg_bind_shcut_prompt_char[0], 0,
3319 sizeof(a_tty.tg_bind_shcut_prompt_char));
3321 for(i = 0; i < n__LEXINPUT_CTX_MAX; ++i)
3322 for(j = 0; j < HSHSIZE; ++j)
3323 a_tty__bind_tree_free(a_tty.tg_bind_tree[i][j]);
3324 memset(&a_tty.tg_bind_tree[0], 0, sizeof(a_tty.tg_bind_tree));
3326 a_tty.tg_bind_isdirty = a_tty.tg_bind_isbuild = FAL0;
3327 NYD2_LEAVE;
3330 static void
3331 a_tty__bind_tree_add(ui32_t hmap_idx, struct a_tty_bind_tree *store[HSHSIZE],
3332 struct a_tty_bind_ctx *tbcp){
3333 ui32_t cnvlen;
3334 char const *cnvdat;
3335 struct a_tty_bind_tree *ntbtp;
3336 NYD2_ENTER;
3337 n_UNUSED(hmap_idx);
3339 ntbtp = NULL;
3341 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len; cnvlen > 0;){
3342 union {wchar_t const *wp; char const *cp;} u;
3343 si32_t entlen;
3345 /* {si32_t buf_len_iscap;} */
3346 entlen = *n_UNALIGN(si32_t const*,cnvdat);
3348 if(entlen & SI32_MIN){
3349 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;}
3350 * Note that empty capabilities result in DEFUNCT */
3351 for(u.cp = (char const*)&n_UNALIGN(si32_t const*,cnvdat)[2];
3352 *u.cp != '\0'; ++u.cp)
3353 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.cp, TRU1);
3354 assert(ntbtp != NULL);
3355 ntbtp->tbt_isseq_trail = TRU1;
3356 entlen &= SI32_MAX;
3357 }else{
3358 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3359 bool_t isseq;
3361 u.wp = (wchar_t const*)&n_UNALIGN(si32_t const*,cnvdat)[1];
3363 /* May be a special shortcut function? */
3364 if(ntbtp == NULL && (tbcp->tbc_flags & a_TTY_BIND_MLE1CNTRL)){
3365 char *cp;
3366 ui32_t ctx, fun;
3368 ctx = tbcp->tbc_flags & n__LEXINPUT_CTX_MAX;
3369 fun = tbcp->tbc_flags & a_TTY__BIND_FUN_MASK;
3371 if(fun == a_TTY_BIND_FUN_CANCEL){
3372 for(cp = &a_tty.tg_bind_shcut_cancel[ctx][0];
3373 PTRCMP(cp, <, &a_tty.tg_bind_shcut_cancel[ctx]
3374 [n_NELEM(a_tty.tg_bind_shcut_cancel[ctx]) - 1]); ++cp)
3375 if(*cp == '\0'){
3376 *cp = (char)*u.wp;
3377 break;
3379 }else if(fun == a_TTY_BIND_FUN_PROMPT_CHAR){
3380 for(cp = &a_tty.tg_bind_shcut_prompt_char[ctx][0];
3381 PTRCMP(cp, <, &a_tty.tg_bind_shcut_prompt_char[ctx]
3382 [n_NELEM(a_tty.tg_bind_shcut_prompt_char[ctx]) - 1]);
3383 ++cp)
3384 if(*cp == '\0'){
3385 *cp = (char)*u.wp;
3386 break;
3391 isseq = (u.wp[1] != '\0');
3392 for(; *u.wp != '\0'; ++u.wp)
3393 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.wp, isseq);
3394 if(isseq)
3395 ntbtp->tbt_isseq_trail = TRU1;
3398 cnvlen -= entlen;
3399 cnvdat += entlen;
3402 /* Should have been rendered defunctional at first instead */
3403 assert(ntbtp != NULL);
3404 ntbtp->tbt_bind = tbcp;
3405 NYD2_LEAVE;
3408 static struct a_tty_bind_tree *
3409 a_tty__bind_tree_add_wc(struct a_tty_bind_tree **treep,
3410 struct a_tty_bind_tree *parentp, wchar_t wc, bool_t isseq){
3411 struct a_tty_bind_tree *tbtp, *xtbtp;
3412 NYD2_ENTER;
3414 if(parentp == NULL){
3415 treep += wc % HSHSIZE;
3417 /* Having no parent also means that the tree slot is possibly empty */
3418 for(tbtp = *treep; tbtp != NULL;
3419 parentp = tbtp, tbtp = tbtp->tbt_sibling){
3420 if(tbtp->tbt_char != wc)
3421 continue;
3422 if(tbtp->tbt_isseq == isseq)
3423 goto jleave;
3424 /* isseq MUST be linked before !isseq, so record this "parent"
3425 * sibling, but continue searching for now */
3426 if(!isseq)
3427 parentp = tbtp;
3428 /* Otherwise it is impossible that we'll find what we look for */
3429 else{
3430 #ifdef HAVE_DEBUG
3431 while((tbtp = tbtp->tbt_sibling) != NULL)
3432 assert(tbtp->tbt_char != wc);
3433 #endif
3434 break;
3438 tbtp = smalloc(sizeof *tbtp);
3439 memset(tbtp, 0, sizeof *tbtp);
3440 tbtp->tbt_char = wc;
3441 tbtp->tbt_isseq = isseq;
3443 if(parentp == NULL){
3444 tbtp->tbt_sibling = *treep;
3445 *treep = tbtp;
3446 }else{
3447 tbtp->tbt_sibling = parentp->tbt_sibling;
3448 parentp->tbt_sibling = tbtp;
3450 }else{
3451 if((tbtp = *(treep = &parentp->tbt_childs)) != NULL){
3452 for(;; tbtp = xtbtp){
3453 if(tbtp->tbt_char == wc){
3454 if(tbtp->tbt_isseq == isseq)
3455 goto jleave;
3456 /* isseq MUST be linked before, so it is impossible that we'll
3457 * find what we look for */
3458 if(isseq){
3459 #ifdef HAVE_DEBUG
3460 while((tbtp = tbtp->tbt_sibling) != NULL)
3461 assert(tbtp->tbt_char != wc);
3462 #endif
3463 tbtp = NULL;
3464 break;
3468 if((xtbtp = tbtp->tbt_sibling) == NULL){
3469 treep = &tbtp->tbt_sibling;
3470 break;
3475 xtbtp = smalloc(sizeof *xtbtp);
3476 memset(xtbtp, 0, sizeof *xtbtp);
3477 xtbtp->tbt_parent = parentp;
3478 xtbtp->tbt_char = wc;
3479 xtbtp->tbt_isseq = isseq;
3480 tbtp = xtbtp;
3481 *treep = tbtp;
3483 jleave:
3484 NYD2_LEAVE;
3485 return tbtp;
3488 static void
3489 a_tty__bind_tree_free(struct a_tty_bind_tree *tbtp){
3490 NYD2_ENTER;
3491 while(tbtp != NULL){
3492 struct a_tty_bind_tree *tmp;
3494 if((tmp = tbtp->tbt_childs) != NULL)
3495 a_tty__bind_tree_free(tmp);
3497 tmp = tbtp->tbt_sibling;
3498 free(tbtp);
3499 tbtp = tmp;
3501 NYD2_LEAVE;
3503 # endif /* HAVE_KEY_BINDINGS */
3505 FL void
3506 n_tty_init(void){
3507 NYD_ENTER;
3509 if(ok_blook(line_editor_disable))
3510 goto jleave;
3512 /* Load the history file */
3513 # ifdef HAVE_HISTORY
3514 do/* for break */{
3515 long hs;
3516 char const *v;
3517 char *lbuf;
3518 FILE *f;
3519 size_t lsize, cnt, llen;
3521 a_TTY_HISTSIZE(hs);
3522 a_tty.tg_hist_size = 0;
3523 a_tty.tg_hist_size_max = (size_t)hs;
3524 if(hs == 0)
3525 break;
3527 a_TTY_HISTFILE(v);
3528 if(v == NULL)
3529 break;
3531 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
3532 f = fopen(v, "r"); /* TODO HISTFILE LOAD: use linebuf pool */
3533 if(f == NULL)
3534 goto jhist_done;
3535 (void)n_file_lock(fileno(f), FLT_READ, 0,0, UIZ_MAX);
3537 assert(!(pstate & PS_ROOT));
3538 pstate |= PS_ROOT; /* Allow calling addhist() */
3539 lbuf = NULL;
3540 lsize = 0;
3541 cnt = (size_t)fsize(f);
3542 while(fgetline(&lbuf, &lsize, &cnt, &llen, f, FAL0) != NULL){
3543 if(llen > 0 && lbuf[llen - 1] == '\n')
3544 lbuf[--llen] = '\0';
3545 if(llen == 0 || lbuf[0] == '#') /* xxx comments? noone! */
3546 continue;
3547 else{
3548 bool_t isgabby;
3550 isgabby = (lbuf[0] == '*');
3551 n_tty_addhist(lbuf + isgabby, isgabby);
3554 if(lbuf != NULL)
3555 free(lbuf);
3556 pstate &= ~PS_ROOT;
3558 fclose(f);
3559 jhist_done:
3560 rele_all_sigs(); /* XXX remove jumps */
3561 }while(0);
3562 # endif /* HAVE_HISTORY */
3564 /* Force immediate resolve for anything which follows */
3565 pstate |= PS_LINE_EDITOR_INIT;
3567 # ifdef HAVE_KEY_BINDINGS
3568 /* `bind's (and `unbind's) done from within resource files couldn't be
3569 * performed for real since our termcap driver wasn't yet loaded, and we
3570 * can't perform automatic init since the user may have disallowed so */
3571 /* C99 */{
3572 struct a_tty_bind_ctx *tbcp;
3573 enum n_lexinput_flags lif;
3575 for(lif = 0; lif < n__LEXINPUT_CTX_MAX; ++lif)
3576 for(tbcp = a_tty.tg_bind[lif]; tbcp != NULL; tbcp = tbcp->tbc_next)
3577 if((tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
3578 a_TTY_BIND_RESOLVE)
3579 a_tty_bind_resolve(tbcp);
3582 /* And we want to (try to) install some default key bindings */
3583 if(!ok_blook(line_editor_no_defaults)){
3584 char buf[8];
3585 struct a_tty_bind_parse_ctx tbpc;
3586 struct a_tty_bind_default_tuple const *tbdtp;
3588 buf[0] = '$', buf[1] = '\'', buf[2] = '\\', buf[3] = 'c',
3589 buf[5] = '\'', buf[6] = '\0';
3590 for(tbdtp = a_tty_bind_default_tuples;
3591 PTRCMP(tbdtp, <,
3592 &a_tty_bind_default_tuples[n_NELEM(a_tty_bind_default_tuples)]);
3593 ++tbdtp){
3594 memset(&tbpc, 0, sizeof tbpc);
3595 tbpc.tbpc_cmd = "bind";
3596 if(tbdtp->tbdt_iskey){
3597 buf[4] = tbdtp->tbdt_ckey;
3598 tbpc.tbpc_in_seq = buf;
3599 }else
3600 tbpc.tbpc_in_seq = savecatsep(":", '\0',
3601 n_termcap_name_of_query(tbdtp->tbdt_query));
3602 tbpc.tbpc_exp.s = n_UNCONST(tbdtp->tbdt_exp[0] == '\0'
3603 ? a_tty_bind_fun_names[(ui8_t)tbdtp->tbdt_exp[1]]
3604 : tbdtp->tbdt_exp);
3605 tbpc.tbpc_exp.l = strlen(tbpc.tbpc_exp.s);
3606 tbpc.tbpc_flags = n_LEXINPUT_CTX_BASE;
3607 /* ..but don't want to overwrite any user settings */
3608 a_tty_bind_create(&tbpc, FAL0);
3611 # endif /* HAVE_KEY_BINDINGS */
3613 jleave:
3614 NYD_LEAVE;
3617 FL void
3618 n_tty_destroy(void){
3619 NYD_ENTER;
3621 if(!(pstate & PS_LINE_EDITOR_INIT))
3622 goto jleave;
3624 # ifdef HAVE_HISTORY
3625 do/* for break */{
3626 long hs;
3627 char const *v;
3628 struct a_tty_hist *thp;
3629 bool_t dogabby;
3630 FILE *f;
3632 a_TTY_HISTSIZE(hs);
3633 if(hs == 0)
3634 break;
3636 a_TTY_HISTFILE(v);
3637 if(v == NULL)
3638 break;
3640 dogabby = ok_blook(history_gabby_persist);
3642 if((thp = a_tty.tg_hist) != NULL)
3643 for(; thp->th_older != NULL; thp = thp->th_older)
3644 if((dogabby || !thp->th_isgabby) && --hs == 0)
3645 break;
3647 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
3648 f = fopen(v, "w"); /* TODO temporary + rename?! */
3649 if(f == NULL)
3650 goto jhist_done;
3651 (void)n_file_lock(fileno(f), FLT_WRITE, 0,0, UIZ_MAX);
3653 for(; thp != NULL; thp = thp->th_younger){
3654 if(dogabby || !thp->th_isgabby){
3655 if(thp->th_isgabby)
3656 putc('*', f);
3657 fwrite(thp->th_dat, sizeof *thp->th_dat, thp->th_len, f);
3658 putc('\n', f);
3661 fclose(f);
3662 jhist_done:
3663 rele_all_sigs(); /* XXX remove jumps */
3664 }while(0);
3665 # endif /* HAVE_HISTORY */
3667 # if defined HAVE_KEY_BINDINGS && defined HAVE_DEBUG
3668 c_unbind(n_UNCONST("* *"));
3669 # endif
3671 # ifdef HAVE_DEBUG
3672 memset(&a_tty, 0, sizeof a_tty);
3673 # endif
3674 DBG( pstate &= ~PS_LINE_EDITOR_INIT; )
3675 jleave:
3676 NYD_LEAVE;
3679 FL void
3680 n_tty_signal(int sig){
3681 sigset_t nset, oset;
3682 NYD_X; /* Signal handler */
3684 switch(sig){
3685 # ifdef SIGWINCH
3686 case SIGWINCH:
3687 /* We don't deal with SIGWINCH, yet get called from main.c.
3688 * Note this case might get called even if !PS_LINE_EDITOR_INIT */
3689 break;
3690 # endif
3691 default:
3692 a_tty_term_mode(FAL0);
3693 n_TERMCAP_SUSPEND(TRU1);
3694 a_tty_sigs_down();
3696 sigemptyset(&nset);
3697 sigaddset(&nset, sig);
3698 sigprocmask(SIG_UNBLOCK, &nset, &oset);
3699 n_raise(sig);
3700 /* When we come here we'll continue editing, so reestablish */
3701 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
3703 a_tty_sigs_up();
3704 n_TERMCAP_RESUME(TRU1);
3705 a_tty_term_mode(TRU1);
3706 a_tty.tg_line->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
3707 break;
3711 FL int
3712 (n_tty_readline)(enum n_lexinput_flags lif, char const *prompt,
3713 char **linebuf, size_t *linesize, size_t n n_MEMORY_DEBUG_ARGS){
3714 struct a_tty_line tl;
3715 # ifdef HAVE_COLOUR
3716 char *posbuf, *pos;
3717 # endif
3718 ui32_t plen, pwidth;
3719 ssize_t nn;
3720 char const *orig_prompt;
3721 NYD_ENTER;
3722 n_UNUSED(lif);
3724 assert(!ok_blook(line_editor_disable));
3725 if(!(pstate & PS_LINE_EDITOR_INIT))
3726 n_tty_init();
3727 assert(pstate & PS_LINE_EDITOR_INIT);
3729 orig_prompt = prompt;
3730 /* xxx Likely overkill: avoid "bind base a,b,c set-line-editor-disable"
3731 * xxx not being honoured at once: call n_lex_input() instead of goto */
3732 # ifndef HAVE_KEY_BINDINGS
3733 jredo:
3734 prompt = orig_prompt;
3735 # endif
3737 # ifdef HAVE_COLOUR
3738 n_colour_env_create(n_COLOUR_CTX_MLE, FAL0);
3739 # endif
3741 /* Classify prompt */
3742 n_UNINIT(plen, 0);
3743 n_UNINIT(pwidth, 0);
3744 if(prompt != NULL){
3745 size_t i = strlen(prompt);
3747 if(i == 0 || i >= UI32_MAX)
3748 prompt = NULL;
3749 else{
3750 /* TODO *prompt* is in multibyte and not in a_tty_cell, therefore
3751 * TODO we cannot handle it in parts, it's all or nothing.
3752 * TODO Later (S-CText, SysV signals) the prompt should be some global
3753 * TODO carrier thing, fully evaluated and passed around as UI-enabled
3754 * TODO string, then we can print it character by character */
3755 struct n_visual_info_ctx vic;
3757 memset(&vic, 0, sizeof vic);
3758 vic.vic_indat = prompt;
3759 vic.vic_inlen = i;
3760 if(n_visual_info(&vic, n_VISUAL_INFO_WIDTH_QUERY)){
3761 pwidth = (ui32_t)vic.vic_vi_width;
3762 plen = (ui32_t)i;
3763 }else{
3764 n_err(_("Character set error in evaluation of prompt\n"));
3765 prompt = NULL;
3770 # ifdef HAVE_COLOUR
3771 /* C99 */{
3772 struct n_colour_pen *ccp;
3773 struct str const *sp;
3775 if(prompt != NULL &&
3776 (ccp = n_colour_pen_create(n_COLOUR_ID_MLE_PROMPT, NULL)) != NULL &&
3777 (sp = n_colour_pen_to_str(ccp)) != NULL){
3778 char const *ccol = sp->s;
3780 if((sp = n_colour_reset_to_str()) != NULL){
3781 size_t l1 = strlen(ccol), l2 = strlen(sp->s);
3782 ui32_t nplen = (ui32_t)(l1 + plen + l2);
3783 char *nprompt = salloc(nplen +1);
3785 memcpy(nprompt, ccol, l1);
3786 memcpy(&nprompt[l1], prompt, plen);
3787 memcpy(&nprompt[l1 += plen], sp->s, ++l2);
3789 prompt = nprompt;
3790 plen = nplen;
3794 /* .tl_pos_buf is a hack */
3795 posbuf = pos = NULL;
3796 if((ccp = n_colour_pen_create(n_COLOUR_ID_MLE_POSITION, NULL)) != NULL &&
3797 (sp = n_colour_pen_to_str(ccp)) != NULL){
3798 char const *ccol = sp->s;
3800 if((sp = n_colour_reset_to_str()) != NULL){
3801 size_t l1 = strlen(ccol), l2 = strlen(sp->s);
3803 posbuf = salloc(l1 + 4 + l2 +1);
3804 memcpy(posbuf, ccol, l1);
3805 pos = &posbuf[l1];
3806 memcpy(&pos[4], sp->s, ++l2);
3809 if(posbuf == NULL){
3810 posbuf = pos = salloc(4 +1);
3811 pos[4] = '\0';
3814 # endif /* HAVE_COLOUR */
3816 memset(&tl, 0, sizeof tl);
3818 # ifdef HAVE_KEY_BINDINGS
3819 /* C99 */{
3820 char const *cp = ok_vlook(bind_timeout);
3822 if(cp != NULL){
3823 ul_i ul;
3825 if((ul = strtoul(cp, NULL, 0)) > 0 &&
3826 /* Convert to tenths of a second, unfortunately */
3827 (ul = (ul + 99) / 100) <= a_TTY_BIND_TIMEOUT_MAX)
3828 tl.tl_bind_timeout = (ui8_t)ul;
3829 else if(options & OPT_D_V)
3830 n_err(_("Ignoring invalid *bind-timeout*: %s\n"), cp);
3834 if(a_tty.tg_bind_isdirty)
3835 a_tty_bind_tree_teardown();
3836 if(a_tty.tg_bind_cnt > 0 && !a_tty.tg_bind_isbuild)
3837 a_tty_bind_tree_build();
3838 tl.tl_bind_tree_hmap = &a_tty.tg_bind_tree[lif & n__LEXINPUT_CTX_MASK];
3839 tl.tl_bind_shcut_cancel =
3840 &a_tty.tg_bind_shcut_cancel[lif & n__LEXINPUT_CTX_MASK];
3841 tl.tl_bind_shcut_prompt_char =
3842 &a_tty.tg_bind_shcut_prompt_char[lif & n__LEXINPUT_CTX_MASK];
3843 # endif /* HAVE_KEY_BINDINGS */
3845 if((tl.tl_prompt = prompt) != NULL){ /* XXX not re-evaluated */
3846 tl.tl_prompt_length = plen;
3847 tl.tl_prompt_width = pwidth;
3849 # ifdef HAVE_COLOUR
3850 tl.tl_pos_buf = posbuf;
3851 tl.tl_pos = pos;
3852 # endif
3854 tl.tl_line.cbuf = *linebuf;
3855 if(n != 0){
3856 tl.tl_defc.s = savestrbuf(*linebuf, n);
3857 tl.tl_defc.l = n;
3859 tl.tl_x_buf = linebuf;
3860 tl.tl_x_bufsize = linesize;
3862 a_tty.tg_line = &tl;
3863 a_tty_sigs_up();
3864 n_TERMCAP_RESUME(FAL0);
3865 a_tty_term_mode(TRU1);
3866 nn = a_tty_readline(&tl, n n_MEMORY_DEBUG_ARGSCALL);
3867 a_tty_term_mode(FAL0);
3868 n_TERMCAP_SUSPEND(FAL0);
3869 a_tty_sigs_down();
3870 a_tty.tg_line = NULL;
3872 # ifdef HAVE_COLOUR
3873 n_colour_env_gut(stdout);
3874 # endif
3876 if(tl.tl_reenter_after_cmd != NULL){
3877 n_source_command(lif, tl.tl_reenter_after_cmd);
3878 /* TODO because of recursion we cannot use srelax()ation: would be good */
3879 /* See above for why not simply using goto */
3880 n = (nn <= 0) ? 0 : nn;
3881 # ifdef HAVE_KEY_BINDINGS
3882 nn = (n_lex_input)(lif, orig_prompt, linebuf, linesize,
3883 (n == 0 ? "" : savestrbuf(*linebuf, n)) n_MEMORY_DEBUG_ARGSCALL);
3884 # else
3885 goto jredo;
3886 # endif
3888 NYD_LEAVE;
3889 return (int)nn;
3892 FL void
3893 n_tty_addhist(char const *s, bool_t isgabby){
3894 # ifdef HAVE_HISTORY
3895 /* Super-Heavy-Metal: block all sigs, avoid leaks+ on jump */
3896 ui32_t l;
3897 struct a_tty_hist *thp, *othp, *ythp;
3898 # endif
3899 NYD_ENTER;
3900 n_UNUSED(s);
3901 n_UNUSED(isgabby);
3903 # ifdef HAVE_HISTORY
3904 a_TTY_CHECK_ADDHIST(s, isgabby, goto j_leave);
3905 if(a_tty.tg_hist_size_max == 0)
3906 goto j_leave;
3908 l = (ui32_t)strlen(s);
3910 /* Eliminating duplicates is expensive, but simply inacceptable so
3911 * during the load of a potentially large history file! */
3912 if(pstate & PS_LINE_EDITOR_INIT)
3913 for(thp = a_tty.tg_hist; thp != NULL; thp = thp->th_older)
3914 if(thp->th_len == l && !strcmp(thp->th_dat, s)){
3915 hold_all_sigs(); /* TODO */
3916 if(thp->th_isgabby)
3917 thp->th_isgabby = !!isgabby;
3918 othp = thp->th_older;
3919 ythp = thp->th_younger;
3920 if(othp != NULL)
3921 othp->th_younger = ythp;
3922 else
3923 a_tty.tg_hist_tail = ythp;
3924 if(ythp != NULL)
3925 ythp->th_older = othp;
3926 else
3927 a_tty.tg_hist = othp;
3928 goto jleave;
3930 hold_all_sigs();
3932 ++a_tty.tg_hist_size;
3933 if((pstate & PS_LINE_EDITOR_INIT) &&
3934 a_tty.tg_hist_size > a_tty.tg_hist_size_max){
3935 --a_tty.tg_hist_size;
3936 if((thp = a_tty.tg_hist_tail) != NULL){
3937 if((a_tty.tg_hist_tail = thp->th_younger) == NULL)
3938 a_tty.tg_hist = NULL;
3939 else
3940 a_tty.tg_hist_tail->th_older = NULL;
3941 free(thp);
3945 thp = smalloc((sizeof(struct a_tty_hist) -
3946 n_VFIELD_SIZEOF(struct a_tty_hist, th_dat)) + l +1);
3947 thp->th_isgabby = !!isgabby;
3948 thp->th_len = l;
3949 memcpy(thp->th_dat, s, l +1);
3950 jleave:
3951 if((thp->th_older = a_tty.tg_hist) != NULL)
3952 a_tty.tg_hist->th_younger = thp;
3953 else
3954 a_tty.tg_hist_tail = thp;
3955 thp->th_younger = NULL;
3956 a_tty.tg_hist = thp;
3958 rele_all_sigs();
3959 j_leave:
3960 # endif
3961 NYD_LEAVE;
3964 # ifdef HAVE_HISTORY
3965 FL int
3966 c_history(void *v){
3967 C_HISTORY_SHARED;
3969 jlist:{
3970 FILE *fp;
3971 size_t i, b;
3972 struct a_tty_hist *thp;
3974 if(a_tty.tg_hist == NULL)
3975 goto jleave;
3977 if((fp = Ftmp(NULL, "hist", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
3978 n_perr(_("tmpfile"), 0);
3979 v = NULL;
3980 goto jleave;
3983 i = a_tty.tg_hist_size;
3984 b = 0;
3985 for(thp = a_tty.tg_hist; thp != NULL;
3986 --i, b += thp->th_len, thp = thp->th_older)
3987 fprintf(fp,
3988 "%c%4" PRIuZ ". %-50.50s (%4" PRIuZ "+%2" PRIu32 " B)\n",
3989 (thp->th_isgabby ? '*' : ' '), i, thp->th_dat, b, thp->th_len);
3991 page_or_print(fp, i);
3992 Fclose(fp);
3994 goto jleave;
3996 jclear:{
3997 struct a_tty_hist *thp;
3999 while((thp = a_tty.tg_hist) != NULL){
4000 a_tty.tg_hist = thp->th_older;
4001 free(thp);
4003 a_tty.tg_hist_tail = NULL;
4004 a_tty.tg_hist_size = 0;
4006 goto jleave;
4008 jentry:{
4009 struct a_tty_hist *thp;
4011 if(UICMP(z, entry, <=, a_tty.tg_hist_size)){
4012 entry = (long)a_tty.tg_hist_size - entry;
4013 for(thp = a_tty.tg_hist;; thp = thp->th_older)
4014 if(thp == NULL)
4015 break;
4016 else if(entry-- != 0)
4017 continue;
4018 else{
4019 v = temporary_arg_v_store = thp->th_dat;
4020 goto jleave;
4023 v = NULL;
4025 goto jleave;
4027 # endif /* HAVE_HISTORY */
4029 # ifdef HAVE_KEY_BINDINGS
4030 FL int
4031 c_bind(void *v){
4032 n_CMD_ARG_DESC_SUBCLASS_DEF(bind, 3, a_tty_bind_cad) { /* TODO cmd_tab.h */
4033 {n_CMD_ARG_DESC_STRING, 0},
4034 {n_CMD_ARG_DESC_WYSH | n_CMD_ARG_DESC_OPTION |
4035 n_CMD_ARG_DESC_HONOUR_STOP,
4036 n_SHEXP_PARSE_DRYRUN | n_SHEXP_PARSE_LOG},
4037 {n_CMD_ARG_DESC_WYSH | n_CMD_ARG_DESC_OPTION | n_CMD_ARG_DESC_GREEDY |
4038 n_CMD_ARG_DESC_HONOUR_STOP,
4039 n_SHEXP_PARSE_IGNORE_EMPTY}
4040 } n_CMD_ARG_DESC_SUBCLASS_DEF_END;
4041 struct n_cmd_arg_ctx cac;
4042 struct a_tty_bind_ctx *tbcp;
4043 enum n_lexinput_flags lif;
4044 bool_t aster, show;
4045 union {char const *cp; char *p; char c;} c;
4046 NYD_ENTER;
4048 cac.cac_desc = n_CMD_ARG_DESC_SUBCLASS_CAST(&a_tty_bind_cad);
4049 cac.cac_indat = v;
4050 cac.cac_inlen = UIZ_MAX;
4051 if(!n_cmd_arg_parse(&cac)){
4052 v = NULL;
4053 goto jleave;
4056 c.cp = cac.cac_arg->ca_arg.ca_str.s;
4057 if(cac.cac_no == 1)
4058 show = TRU1;
4059 else
4060 show = !asccasecmp(cac.cac_arg->ca_next->ca_arg.ca_str.s, "show");
4061 aster = FAL0;
4063 if((lif = a_tty_bind_ctx_find(c.cp)) == (enum n_lexinput_flags)-1){
4064 if(!(aster = n_is_all_or_aster(c.cp)) || !show){
4065 n_err(_("`bind': invalid context: %s\n"), c.cp);
4066 v = NULL;
4067 goto jleave;
4069 lif = 0;
4072 if(show){
4073 ui32_t lns;
4074 FILE *fp;
4076 if((fp = Ftmp(NULL, "bind", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
4077 n_perr(_("tmpfile"), 0);
4078 v = NULL;
4079 goto jleave;
4082 lns = 0;
4083 for(;;){
4084 for(tbcp = a_tty.tg_bind[lif]; tbcp != NULL;
4085 ++lns, tbcp = tbcp->tbc_next){
4086 /* Print the bytes of resolved terminal capabilities, then */
4087 if((options & OPT_D_V) &&
4088 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)
4089 ) == a_TTY_BIND_RESOLVE){
4090 char cbuf[8];
4091 union {wchar_t const *wp; char const *cp;} u;
4092 si32_t entlen;
4093 ui32_t cnvlen;
4094 char const *cnvdat, *bsep, *cbufp;
4096 putc('#', fp);
4097 putc(' ', fp);
4099 cbuf[0] = '=', cbuf[2] = '\0';
4100 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len;
4101 cnvlen > 0;){
4102 if(cnvdat != tbcp->tbc_cnv)
4103 putc(',', fp);
4105 /* {si32_t buf_len_iscap;} */
4106 entlen = *n_UNALIGN(si32_t const*,cnvdat);
4107 if(entlen & SI32_MIN){
4108 /* struct{si32_t buf_len_iscap; si32_t cap_len;
4109 * char buf[]+NUL;} */
4110 for(bsep = "",
4111 u.cp = (char const*)
4112 &n_UNALIGN(si32_t const*,cnvdat)[2];
4113 (c.c = *u.cp) != '\0'; ++u.cp){
4114 if(asciichar(c.c) && !cntrlchar(c.c))
4115 cbuf[1] = c.c, cbufp = cbuf;
4116 else
4117 cbufp = "";
4118 fprintf(fp, "%s%02X%s",
4119 bsep, (ui32_t)(ui8_t)c.c, cbufp);
4120 bsep = " ";
4122 entlen &= SI32_MAX;
4123 }else
4124 putc('-', fp);
4126 cnvlen -= entlen;
4127 cnvdat += entlen;
4130 fputs("\n ", fp);
4131 ++lns;
4134 fprintf(fp, "%sbind %s %s %s%s%s\n",
4135 ((tbcp->tbc_flags & a_TTY_BIND_DEFUNCT)
4136 /* I18N: `bind' sequence not working, either because it is
4137 * I18N: using Unicode and that is not available in the locale,
4138 * I18N: or a termcap(5)/terminfo(5) sequence won't work out */
4139 ? _("# <Defunctional> ") : ""),
4140 a_tty_bind_ctx_maps[lif].tbcm_name, tbcp->tbc_seq,
4141 n_shexp_quote_cp(tbcp->tbc_exp, TRU1),
4142 (tbcp->tbc_flags & a_TTY_BIND_NOCOMMIT ? "@" : ""),
4143 (!(options & OPT_D_VV) ? ""
4144 : (tbcp->tbc_flags & a_TTY_BIND_FUN_INTERNAL
4145 ? _(" # MLE internal") : ""))
4148 if(!aster || ++lif >= n__LEXINPUT_CTX_MAX)
4149 break;
4151 page_or_print(fp, lns);
4153 Fclose(fp);
4154 }else{
4155 struct a_tty_bind_parse_ctx tbpc;
4156 struct n_string store;
4158 memset(&tbpc, 0, sizeof tbpc);
4159 tbpc.tbpc_cmd = a_tty_bind_cad.cad_name;
4160 tbpc.tbpc_in_seq = cac.cac_arg->ca_next->ca_arg.ca_str.s;
4161 tbpc.tbpc_exp.s = n_string_cp(n_cmd_arg_join_greedy(&cac,
4162 n_string_creat_auto(&store)));
4163 tbpc.tbpc_exp.l = store.s_len;
4164 tbpc.tbpc_flags = lif;
4165 if(!a_tty_bind_create(&tbpc, TRU1))
4166 v = NULL;
4167 n_string_gut(&store);
4169 jleave:
4170 NYD_LEAVE;
4171 return (v != NULL) ? EXIT_OK : EXIT_ERR;
4174 FL int
4175 c_unbind(void *v){
4176 n_CMD_ARG_DESC_SUBCLASS_DEF(unbind, 2, a_tty_unbind_cad) {/* TODO cmd_tab.h*/
4177 {n_CMD_ARG_DESC_STRING, 0},
4178 {n_CMD_ARG_DESC_WYSH | n_CMD_ARG_DESC_HONOUR_STOP,
4179 n_SHEXP_PARSE_DRYRUN | n_SHEXP_PARSE_LOG}
4180 } n_CMD_ARG_DESC_SUBCLASS_DEF_END;
4181 struct a_tty_bind_parse_ctx tbpc;
4182 struct n_cmd_arg_ctx cac;
4183 struct a_tty_bind_ctx *tbcp;
4184 enum n_lexinput_flags lif;
4185 bool_t aster;
4186 union {char const *cp; char *p;} c;
4187 NYD_ENTER;
4189 cac.cac_desc = n_CMD_ARG_DESC_SUBCLASS_CAST(&a_tty_unbind_cad);
4190 cac.cac_indat = v;
4191 cac.cac_inlen = UIZ_MAX;
4192 if(!n_cmd_arg_parse(&cac)){
4193 v = NULL;
4194 goto jleave;
4197 c.cp = cac.cac_arg->ca_arg.ca_str.s;
4198 aster = FAL0;
4200 if((lif = a_tty_bind_ctx_find(c.cp)) == (enum n_lexinput_flags)-1){
4201 if(!(aster = n_is_all_or_aster(c.cp))){
4202 n_err(_("`unbind': invalid context: %s\n"), c.cp);
4203 v = NULL;
4204 goto jleave;
4206 lif = 0;
4209 c.cp = cac.cac_arg->ca_next->ca_arg.ca_str.s;
4210 jredo:
4211 if(n_is_all_or_aster(c.cp)){
4212 while((tbcp = a_tty.tg_bind[lif]) != NULL){
4213 memset(&tbpc, 0, sizeof tbpc);
4214 tbpc.tbpc_tbcp = tbcp;
4215 tbpc.tbpc_flags = lif;
4216 a_tty_bind_del(&tbpc);
4218 }else{
4219 memset(&tbpc, 0, sizeof tbpc);
4220 tbpc.tbpc_cmd = a_tty_unbind_cad.cad_name;
4221 tbpc.tbpc_in_seq = c.cp;
4222 tbpc.tbpc_flags = lif;
4224 if(n_UNLIKELY(!a_tty_bind_parse(FAL0, &tbpc)))
4225 v = NULL;
4226 else if(n_UNLIKELY((tbcp = tbpc.tbpc_tbcp) == NULL)){
4227 n_err(_("`unbind': no such `bind'ing: %s %s\n"),
4228 a_tty_bind_ctx_maps[lif].tbcm_name, c.cp);
4229 v = NULL;
4230 }else
4231 a_tty_bind_del(&tbpc);
4234 if(aster && ++lif < n__LEXINPUT_CTX_MAX)
4235 goto jredo;
4236 jleave:
4237 NYD_LEAVE;
4238 return (v != NULL) ? EXIT_OK : EXIT_ERR;
4240 # endif /* HAVE_KEY_BINDINGS */
4242 #else /* HAVE_MLE */
4244 * The really-nothing-at-all implementation
4247 FL void
4248 n_tty_init(void){
4249 NYD_ENTER;
4250 NYD_LEAVE;
4253 FL void
4254 n_tty_destroy(void){
4255 NYD_ENTER;
4256 NYD_LEAVE;
4259 FL void
4260 n_tty_signal(int sig){
4261 NYD_X; /* Signal handler */
4262 n_UNUSED(sig);
4264 # ifdef HAVE_TERMCAP
4265 switch(sig){
4266 default:{
4267 sigset_t nset, oset;
4269 n_TERMCAP_SUSPEND(TRU1);
4270 a_tty_sigs_down();
4272 sigemptyset(&nset);
4273 sigaddset(&nset, sig);
4274 sigprocmask(SIG_UNBLOCK, &nset, &oset);
4275 n_raise(sig);
4276 /* When we come here we'll continue editing, so reestablish */
4277 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
4279 a_tty_sigs_up();
4280 n_TERMCAP_RESUME(TRU1);
4281 break;
4284 # endif /* HAVE_TERMCAP */
4287 FL int
4288 (n_tty_readline)(enum n_lexinput_flags lif, char const *prompt,
4289 char **linebuf, size_t *linesize, size_t n n_MEMORY_DEBUG_ARGS){
4290 int rv;
4291 NYD_ENTER;
4293 if(prompt != NULL){
4294 if(*prompt != '\0')
4295 fputs(prompt, stdout);
4296 fflush(stdout);
4298 # ifdef HAVE_TERMCAP
4299 a_tty_sigs_up();
4300 n_TERMCAP_RESUME(FAL0);
4301 # endif
4302 rv = (readline_restart)(stdin, linebuf, linesize,n n_MEMORY_DEBUG_ARGSCALL);
4303 # ifdef HAVE_TERMCAP
4304 n_TERMCAP_SUSPEND(FAL0);
4305 a_tty_sigs_down();
4306 # endif
4307 NYD_LEAVE;
4308 return rv;
4311 FL void
4312 n_tty_addhist(char const *s, bool_t isgabby){
4313 NYD_ENTER;
4314 n_UNUSED(s);
4315 n_UNUSED(isgabby);
4316 NYD_LEAVE;
4318 #endif /* nothing at all */
4320 #undef a_TTY_SIGNALS
4321 /* s-it-mode */