More or less completely rewrite memory.c..
[s-mailx.git] / tty.c
blob16e18b7fef596d819ae2e5fd1e51f3c452192ff2
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_BASE | 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_BASE | 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 char tg_bind_shcut_cancel[n__LEXINPUT_CTX_MAX][5];
541 char tg_bind_shcut_prompt_char[n__LEXINPUT_CTX_MAX][5];
542 struct a_tty_bind_ctx *tg_bind[n__LEXINPUT_CTX_MAX];
543 struct a_tty_bind_tree *tg_bind_tree[n__LEXINPUT_CTX_MAX][HSHSIZE];
544 # endif
545 struct termios tg_tios_old;
546 struct termios tg_tios_new;
548 n_CTA(n__LEXINPUT_CTX_MAX == 2,
549 "Value results in array sizes that results in bad structure layout");
551 # ifdef HAVE_HISTORY
552 struct a_tty_hist{
553 struct a_tty_hist *th_older;
554 struct a_tty_hist *th_younger;
555 # ifdef HAVE_BYTE_ORDER_LITTLE
556 ui32_t th_isgabby : 1;
557 # endif
558 ui32_t th_len : 31;
559 # ifndef HAVE_BYTE_ORDER_LITTLE
560 ui32_t th_isgabby : 1;
561 # endif
562 char th_dat[n_VFIELD_SIZE(sizeof(ui32_t))];
564 # endif
566 struct a_tty_line{
567 /* Caller pointers */
568 char **tl_x_buf;
569 size_t *tl_x_bufsize;
570 /* Input processing */
571 # ifdef HAVE_KEY_BINDINGS
572 wchar_t tl_bind_takeover; /* Leftover byte to consume next */
573 ui8_t tl_bind_timeout; /* In-seq. inter-byte-timer, in 1/10th secs */
574 ui8_t tl__bind_dummy[3];
575 char (*tl_bind_shcut_cancel)[5]; /* Special _CANCEL shortcut control */
576 char (*tl_bind_shcut_prompt_char)[5]; /* ..for _PROMPT_CHAR */
577 struct a_tty_bind_tree *(*tl_bind_tree_hmap)[HSHSIZE]; /* Bind lookup tree */
578 struct a_tty_bind_tree *tl_bind_tree;
579 # endif
580 char const *tl_reenter_after_cmd; /* `bind' cmd to exec, then re-readline */
581 /* Line data / content handling */
582 ui32_t tl_count; /* ..of a_tty_cell's (<= a_TTY_LINE_MAX) */
583 ui32_t tl_cursor; /* Current a_tty_cell insertion point */
584 union{
585 char *cbuf; /* *.tl_x_buf */
586 struct a_tty_cell *cells;
587 } tl_line;
588 struct str tl_defc; /* Current default content */
589 size_t tl_defc_cursor_byte; /* Desired position of cursor after takeover */
590 struct str tl_savec; /* Saved default content */
591 struct str tl_pastebuf; /* Last snarfed data */
592 # ifdef HAVE_HISTORY
593 struct a_tty_hist *tl_hist; /* History cursor */
594 # endif
595 ui32_t tl_count_max; /* ..before buffer needs to grow */
596 /* Visual data representation handling */
597 ui32_t tl_vi_flags; /* enum a_tty_visual_flags */
598 ui32_t tl_lst_count; /* .tl_count after last sync */
599 ui32_t tl_lst_cursor; /* .tl_cursor after last sync */
600 /* TODO Add another indirection layer by adding a tl_phy_line of
601 * TODO a_tty_cell objects, incorporate changes in visual layer,
602 * TODO then check what _really_ has changed, sync those changes only */
603 struct a_tty_cell const *tl_phy_start; /* First visible cell, left border */
604 ui32_t tl_phy_cursor; /* Physical cursor position */
605 bool_t tl_quote_rndtrip; /* For _kht() expansion */
606 ui8_t tl__dummy2[3];
607 ui32_t tl_prompt_length; /* Preclassified (TODO needed as a_tty_cell) */
608 ui32_t tl_prompt_width;
609 char const *tl_prompt; /* Preformatted prompt (including colours) */
610 /* .tl_pos_buf is a hack */
611 # ifdef HAVE_COLOUR
612 char *tl_pos_buf; /* mle-position colour-on, [4], reset seq. */
613 char *tl_pos; /* Address of the [4] */
614 # endif
617 # ifdef HAVE_KEY_BINDINGS
618 /* C99: use [INDEX]={} */
619 n_CTAV(n_LEXINPUT_CTX_BASE == 0);
620 n_CTAV(n_LEXINPUT_CTX_COMPOSE == 1);
621 static struct a_tty_bind_ctx_map const
622 a_tty_bind_ctx_maps[n__LEXINPUT_CTX_MAX] = {
623 {n_LEXINPUT_CTX_BASE, "base"},
624 {n_LEXINPUT_CTX_COMPOSE, "compose"}
627 /* Special functions which our MLE provides internally.
628 * Update the manual upon change! */
629 static char const a_tty_bind_fun_names[][24] = {
630 # undef a_X
631 # define a_X(I,N) \
632 n_FIELD_INITI(a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## I)) "mle-" N "\0",
634 a_X(BELL, "bell")
635 a_X(GO_BWD, "go-bwd") a_X(GO_FWD, "go-fwd")
636 a_X(GO_WORD_BWD, "go-word-bwd") a_X(GO_WORD_FWD, "go-word-fwd")
637 a_X(GO_HOME, "go-home") a_X(GO_END, "go-end")
638 a_X(DEL_BWD, "del-bwd") a_X(DEL_FWD, "del-fwd")
639 a_X(SNARF_WORD_BWD, "snarf-word-bwd") a_X(SNARF_WORD_FWD, "snarf-word-fwd")
640 a_X(SNARF_END, "snarf-end") a_X(SNARF_LINE, "snarf-line")
641 a_X(HIST_BWD, "hist-bwd") a_X(HIST_FWD, "hist-fwd")
642 a_X(HIST_SRCH_BWD, "hist-srch-bwd") a_X(HIST_SRCH_FWD, "hist-srch-fwd")
643 a_X(REPAINT, "repaint")
644 a_X(QUOTE_RNDTRIP, "quote-rndtrip")
645 a_X(PROMPT_CHAR, "prompt-char")
646 a_X(COMPLETE, "complete")
647 a_X(PASTE, "paste")
649 a_X(CANCEL, "cancel")
650 a_X(RESET, "reset")
651 a_X(FULLRESET, "fullreset")
652 a_X(COMMIT, "commit")
654 # undef a_X
656 # endif /* HAVE_KEY_BINDINGS */
658 /* The default key bindings (unless disallowed). Update manual upon change!
659 * A logical subset of this table is also used if !HAVE_KEY_BINDINGS (more
660 * expensive than a switch() on control codes directly, but less redundant) */
661 static struct a_tty_bind_default_tuple const a_tty_bind_default_tuples[] = {
662 # undef a_X
663 # define a_X(K,S) \
664 {TRU1, K, 0, {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
666 a_X('A', GO_HOME)
667 a_X('B', GO_BWD)
668 /* C: SIGINT */
669 a_X('D', DEL_FWD)
670 a_X('E', GO_END)
671 a_X('F', GO_FWD)
672 a_X('G', RESET)
673 a_X('H', DEL_BWD)
674 a_X('I', COMPLETE)
675 a_X('J', COMMIT)
676 a_X('K', SNARF_END)
677 a_X('L', REPAINT)
678 /* M: same as J */
679 a_X('N', HIST_FWD)
680 /* O: below */
681 a_X('P', HIST_BWD)
682 a_X('Q', QUOTE_RNDTRIP)
683 a_X('R', HIST_SRCH_BWD)
684 a_X('S', HIST_SRCH_FWD)
685 a_X('T', PASTE)
686 a_X('U', SNARF_LINE)
687 a_X('V', PROMPT_CHAR)
688 a_X('W', SNARF_WORD_BWD)
689 a_X('X', GO_WORD_FWD)
690 a_X('Y', GO_WORD_BWD)
691 /* Z: SIGTSTP */
693 a_X('[', CANCEL)
694 /* \: below */
695 /* ]: below */
696 /* ^: below */
697 a_X('_', SNARF_WORD_FWD)
699 a_X('?', DEL_BWD)
701 # undef a_X
702 # define a_X(K,S) {TRU1, K, 0, {S}},
704 a_X('O', "dt")
705 a_X('\\', "z+")
706 a_X(']', "z$")
707 a_X('^', "z0")
709 # ifdef HAVE_KEY_BINDINGS
710 # undef a_X
711 # define a_X(Q,S) \
712 {FAL0, '\0', n_TERMCAP_QUERY_ ## Q,\
713 {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
715 a_X(key_backspace, DEL_BWD) a_X(key_dc, DEL_FWD)
716 a_X(key_eol, SNARF_END)
717 a_X(key_home, GO_HOME) a_X(key_end, GO_END)
718 a_X(key_left, GO_BWD) a_X(key_right, GO_FWD)
719 a_X(key_sleft, GO_HOME) a_X(key_sright, GO_END)
720 a_X(key_up, HIST_BWD) a_X(key_down, HIST_FWD)
722 # undef a_X
723 # define a_X(Q,S) {FAL0, '\0', n_TERMCAP_QUERY_ ## Q, {S}},
725 a_X(key_shome, "z0") a_X(key_send, "z$")
726 a_X(xkey_sup, "z0") a_X(xkey_sdown, "z$")
727 a_X(key_ppage, "z-") a_X(key_npage, "z+")
728 a_X(xkey_cup, "dotmove-") a_X(xkey_cdown, "dotmove+")
730 # endif /* HAVE_KEY_BINDINGS */
731 # undef a_X
734 static struct a_tty_global a_tty;
736 /* Change from canonical to raw, non-canonical mode, and way back */
737 static void a_tty_term_mode(bool_t raw);
739 /* Adjust an active raw mode to use / not use a timeout */
740 # ifdef HAVE_KEY_BINDINGS
741 static void a_tty_term_rawmode_timeout(struct a_tty_line *tlp, bool_t enable);
742 # endif
744 /* 0-X (2), UI8_MAX == \t / TAB */
745 static ui8_t a_tty_wcwidth(wchar_t wc);
747 /* Memory / cell / word generics */
748 static void a_tty_check_grow(struct a_tty_line *tlp, ui32_t no
749 n_MEMORY_DEBUG_ARGS);
750 static ssize_t a_tty_cell2dat(struct a_tty_line *tlp);
751 static void a_tty_cell2save(struct a_tty_line *tlp);
753 /* Save away data bytes of given range (max = non-inclusive) */
754 static void a_tty_copy2paste(struct a_tty_line *tlp, struct a_tty_cell *tcpmin,
755 struct a_tty_cell *tcpmax);
757 /* Ask user for hexadecimal number, interpret as UTF-32 */
758 static wchar_t a_tty_vinuni(struct a_tty_line *tlp);
760 /* Visual screen synchronization */
761 static bool_t a_tty_vi_refresh(struct a_tty_line *tlp);
763 static bool_t a_tty_vi__paint(struct a_tty_line *tlp);
765 /* Search for word boundary, starting at tl_cursor, in "dir"ection (<> 0).
766 * Return <0 when moving is impossible (backward direction but in position 0,
767 * forward direction but in outermost column), and relative distance to
768 * tl_cursor otherwise */
769 static si32_t a_tty_wboundary(struct a_tty_line *tlp, si32_t dir);
771 /* Most function implementations */
772 static void a_tty_khome(struct a_tty_line *tlp, bool_t dobell);
773 static void a_tty_kend(struct a_tty_line *tlp);
774 static void a_tty_kbs(struct a_tty_line *tlp);
775 static void a_tty_ksnarf(struct a_tty_line *tlp, bool_t cplline, bool_t dobell);
776 static si32_t a_tty_kdel(struct a_tty_line *tlp);
777 static void a_tty_kleft(struct a_tty_line *tlp);
778 static void a_tty_kright(struct a_tty_line *tlp);
779 static void a_tty_ksnarfw(struct a_tty_line *tlp, bool_t fwd);
780 static void a_tty_kgow(struct a_tty_line *tlp, si32_t dir);
781 static bool_t a_tty_kother(struct a_tty_line *tlp, wchar_t wc);
782 static ui32_t a_tty_kht(struct a_tty_line *tlp);
784 # ifdef HAVE_HISTORY
785 /* Return UI32_MAX on "exhaustion" */
786 static ui32_t a_tty_khist(struct a_tty_line *tlp, bool_t fwd);
787 static ui32_t a_tty_khist_search(struct a_tty_line *tlp, bool_t fwd);
789 static ui32_t a_tty__khist_shared(struct a_tty_line *tlp,
790 struct a_tty_hist *thp);
791 # endif
793 /* Handle a function */
794 static enum a_tty_fun_status a_tty_fun(struct a_tty_line *tlp,
795 enum a_tty_bind_flags tbf, size_t *len);
797 /* Readline core */
798 static ssize_t a_tty_readline(struct a_tty_line *tlp, size_t len
799 n_MEMORY_DEBUG_ARGS);
801 # ifdef HAVE_KEY_BINDINGS
802 /* Find context or -1 */
803 static enum n_lexinput_flags a_tty_bind_ctx_find(char const *name);
805 /* Create (or replace, if allowed) a binding */
806 static bool_t a_tty_bind_create(struct a_tty_bind_parse_ctx *tbpcp,
807 bool_t replace);
809 /* Shared implementation to parse `bind' and `unbind' "key-sequence" and
810 * "expansion" command line arguments into something that we can work with */
811 static bool_t a_tty_bind_parse(bool_t isbindcmd,
812 struct a_tty_bind_parse_ctx *tbpcp);
814 /* Lazy resolve a termcap(5)/terminfo(5) (or *termcap*!) capability */
815 static void a_tty_bind_resolve(struct a_tty_bind_ctx *tbcp);
817 /* Delete an existing binding */
818 static void a_tty_bind_del(struct a_tty_bind_parse_ctx *tbpcp);
820 /* Life cycle of all input node trees */
821 static void a_tty_bind_tree_build(void);
822 static void a_tty_bind_tree_teardown(void);
824 static void a_tty__bind_tree_add(ui32_t hmap_idx,
825 struct a_tty_bind_tree *store[HSHSIZE],
826 struct a_tty_bind_ctx *tbcp);
827 static struct a_tty_bind_tree *a_tty__bind_tree_add_wc(
828 struct a_tty_bind_tree **treep, struct a_tty_bind_tree *parentp,
829 wchar_t wc, bool_t isseq);
830 static void a_tty__bind_tree_free(struct a_tty_bind_tree *tbtp);
831 # endif /* HAVE_KEY_BINDINGS */
833 static void
834 a_tty_term_mode(bool_t raw){
835 struct termios *tiosp;
836 NYD2_ENTER;
838 tiosp = &a_tty.tg_tios_old;
839 if(!raw)
840 goto jleave;
842 /* Always requery the attributes, in case we've been moved from background
843 * to foreground or however else in between sessions */
844 /* XXX Always enforce ECHO and ICANON in the OLD attributes - do so as long
845 * XXX as we don't properly deal with TTIN and TTOU etc. */
846 tcgetattr(STDIN_FILENO, tiosp);
847 tiosp->c_lflag |= ECHO | ICANON;
849 memcpy(&a_tty.tg_tios_new, tiosp, sizeof *tiosp);
850 tiosp = &a_tty.tg_tios_new;
851 tiosp->c_cc[VMIN] = 1;
852 tiosp->c_cc[VTIME] = 0;
853 /* Enable ^\, ^Q and ^S to be used for key bindings */
854 tiosp->c_cc[VQUIT] = tiosp->c_cc[VSTART] = tiosp->c_cc[VSTOP] = '\0';
855 tiosp->c_iflag &= ~(ISTRIP | IGNCR);
856 tiosp->c_lflag &= ~(ECHO /*| ECHOE | ECHONL */| ICANON | IEXTEN);
857 jleave:
858 tcsetattr(STDIN_FILENO, TCSADRAIN, tiosp);
859 NYD2_LEAVE;
862 # ifdef HAVE_KEY_BINDINGS
863 static void
864 a_tty_term_rawmode_timeout(struct a_tty_line *tlp, bool_t enable){
865 NYD2_ENTER;
866 if(enable){
867 ui8_t bt;
869 a_tty.tg_tios_new.c_cc[VMIN] = 0;
870 if((bt = tlp->tl_bind_timeout) == 0)
871 bt = a_TTY_BIND_TIMEOUT;
872 a_tty.tg_tios_new.c_cc[VTIME] = bt;
873 }else{
874 a_tty.tg_tios_new.c_cc[VMIN] = 1;
875 a_tty.tg_tios_new.c_cc[VTIME] = 0;
877 tcsetattr(STDIN_FILENO, TCSANOW, &a_tty.tg_tios_new);
878 NYD2_LEAVE;
880 # endif /* HAVE_KEY_BINDINGS */
882 static ui8_t
883 a_tty_wcwidth(wchar_t wc){
884 ui8_t rv;
885 NYD2_ENTER;
887 /* Special case the backslash at first */
888 if(wc == '\t')
889 rv = UI8_MAX;
890 else{
891 int i;
893 # ifdef HAVE_WCWIDTH
894 rv = ((i = wcwidth(wc)) > 0) ? (ui8_t)i : 0;
895 # else
896 rv = iswprint(wc) ? 1 + (wc >= 0x1100u) : 0; /* TODO use S-CText */
897 # endif
899 NYD2_LEAVE;
900 return rv;
903 static void
904 a_tty_check_grow(struct a_tty_line *tlp, ui32_t no n_MEMORY_DEBUG_ARGS){
905 ui32_t cmax;
906 NYD2_ENTER;
908 if(n_UNLIKELY((cmax = tlp->tl_count + no) > tlp->tl_count_max)){
909 size_t i;
911 i = cmax * sizeof(struct a_tty_cell) + 2 * sizeof(struct a_tty_cell);
912 if(n_LIKELY(i >= *tlp->tl_x_bufsize)){
913 hold_all_sigs(); /* XXX v15 drop */
914 i <<= 1;
915 tlp->tl_line.cbuf =
916 *tlp->tl_x_buf = (n_realloc)(*tlp->tl_x_buf, i
917 n_MEMORY_DEBUG_ARGSCALL);
918 rele_all_sigs(); /* XXX v15 drop */
920 tlp->tl_count_max = cmax;
921 *tlp->tl_x_bufsize = i;
923 NYD2_LEAVE;
926 static ssize_t
927 a_tty_cell2dat(struct a_tty_line *tlp){
928 size_t len, i;
929 NYD2_ENTER;
931 len = 0;
933 if(n_LIKELY((i = tlp->tl_count) > 0)){
934 struct a_tty_cell const *tcap;
936 tcap = tlp->tl_line.cells;
938 memcpy(tlp->tl_line.cbuf + len, tcap->tc_cbuf, tcap->tc_count);
939 len += tcap->tc_count;
940 }while(++tcap, --i > 0);
943 tlp->tl_line.cbuf[len] = '\0';
944 NYD2_LEAVE;
945 return (ssize_t)len;
948 static void
949 a_tty_cell2save(struct a_tty_line *tlp){
950 size_t len, i;
951 struct a_tty_cell *tcap;
952 NYD2_ENTER;
954 tlp->tl_savec.s = NULL;
955 tlp->tl_savec.l = 0;
957 if(n_UNLIKELY(tlp->tl_count == 0))
958 goto jleave;
960 for(tcap = tlp->tl_line.cells, len = 0, i = tlp->tl_count; i > 0;
961 ++tcap, --i)
962 len += tcap->tc_count;
964 tlp->tl_savec.s = salloc((tlp->tl_savec.l = len) +1);
966 for(tcap = tlp->tl_line.cells, len = 0, i = tlp->tl_count; i > 0;
967 ++tcap, --i){
968 memcpy(tlp->tl_savec.s + len, tcap->tc_cbuf, tcap->tc_count);
969 len += tcap->tc_count;
971 tlp->tl_savec.s[len] = '\0';
972 jleave:
973 NYD2_LEAVE;
976 static void
977 a_tty_copy2paste(struct a_tty_line *tlp, struct a_tty_cell *tcpmin,
978 struct a_tty_cell *tcpmax){
979 char *cp;
980 struct a_tty_cell *tcp;
981 size_t l;
982 NYD2_ENTER;
984 l = 0;
985 for(tcp = tcpmin; tcp < tcpmax; ++tcp)
986 l += tcp->tc_count;
988 tlp->tl_pastebuf.s = cp = salloc((tlp->tl_pastebuf.l = l) +1);
990 l = 0;
991 for(tcp = tcpmin; tcp < tcpmax; cp += l, ++tcp)
992 memcpy(cp, tcp->tc_cbuf, l = tcp->tc_count);
993 *cp = '\0';
994 NYD2_LEAVE;
997 static wchar_t
998 a_tty_vinuni(struct a_tty_line *tlp){
999 char buf[16], *eptr;
1000 union {size_t i; long l;} u;
1001 wchar_t wc;
1002 NYD2_ENTER;
1004 wc = '\0';
1006 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr) ||
1007 !n_termcap_cmd(n_TERMCAP_CMD_ce, 0, -1))
1008 goto jleave;
1010 /* C99 */{
1011 struct str const *cpre, *csuf;
1012 #ifdef HAVE_COLOUR
1013 struct n_colour_pen *cpen;
1015 cpen = n_colour_pen_create(n_COLOUR_ID_MLE_PROMPT, NULL);
1016 if((cpre = n_colour_pen_to_str(cpen)) != NULL)
1017 csuf = n_colour_reset_to_str();
1018 else
1019 csuf = NULL;
1020 #else
1021 cpre = csuf = NULL;
1022 #endif
1023 printf(_("%sPlease enter Unicode code point:%s "),
1024 (cpre != NULL ? cpre->s : ""), (csuf != NULL ? csuf->s : ""));
1026 fflush(stdout);
1028 buf[sizeof(buf) -1] = '\0';
1029 for(u.i = 0;;){
1030 if(read(STDIN_FILENO, &buf[u.i], 1) != 1){
1031 if(errno == EINTR) /* xxx #if !SA_RESTART ? */
1032 continue;
1033 goto jleave;
1035 if(buf[u.i] == '\n')
1036 break;
1037 if(!hexchar(buf[u.i])){
1038 char const emsg[] = "[0-9a-fA-F]";
1040 n_LCTA(sizeof emsg <= sizeof(buf), "Preallocated buffer too small");
1041 memcpy(buf, emsg, sizeof emsg);
1042 goto jerr;
1045 putc(buf[u.i], stdout);
1046 fflush(stdout);
1047 if(++u.i == sizeof buf)
1048 goto jerr;
1050 buf[u.i] = '\0';
1052 u.l = strtol(buf, &eptr, 16);
1053 if(u.l <= 0 || u.l >= 0x10FFFF/* XXX magic; CText */ || *eptr != '\0'){
1054 jerr:
1055 n_err(_("\nInvalid input: %s\n"), buf);
1056 goto jleave;
1059 wc = (wchar_t)u.l;
1060 jleave:
1061 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY | (wc == '\0' ? a_TTY_VF_BELL : 0);
1062 NYD2_LEAVE;
1063 return wc;
1066 static bool_t
1067 a_tty_vi_refresh(struct a_tty_line *tlp){
1068 bool_t rv;
1069 NYD2_ENTER;
1071 if(tlp->tl_vi_flags & a_TTY_VF_BELL){
1072 tlp->tl_vi_flags |= a_TTY_VF_SYNC;
1073 if(putchar('\a') == EOF)
1074 goto jerr;
1077 if(tlp->tl_vi_flags & a_TTY_VF_REFRESH){
1078 /* kht may want to restore a cursor position after inserting some
1079 * data somewhere */
1080 if(tlp->tl_defc_cursor_byte > 0){
1081 size_t i, j;
1082 ssize_t k;
1084 a_tty_khome(tlp, FAL0);
1086 i = tlp->tl_defc_cursor_byte;
1087 tlp->tl_defc_cursor_byte = 0;
1088 for(j = 0; tlp->tl_cursor < tlp->tl_count; ++j){
1089 a_tty_kright(tlp);
1090 if((k = tlp->tl_line.cells[j].tc_count) > i)
1091 break;
1092 i -= k;
1096 if(!a_tty_vi__paint(tlp))
1097 goto jerr;
1100 if(tlp->tl_vi_flags & a_TTY_VF_SYNC){
1101 tlp->tl_vi_flags &= ~a_TTY_VF_SYNC;
1102 if(fflush(stdout))
1103 goto jerr;
1106 rv = TRU1;
1107 jleave:
1108 tlp->tl_vi_flags &= ~a_TTY_VF_ALL_MASK;
1109 NYD2_LEAVE;
1110 return rv;
1112 jerr:
1113 clearerr(stdout); /* xxx I/O layer rewrite */
1114 n_err(_("Visual refresh failed! Is $TERM set correctly?\n"
1115 " Setting *line-editor-disable* to get us through!\n"));
1116 ok_bset(line_editor_disable);
1117 rv = FAL0;
1118 goto jleave;
1121 static bool_t
1122 a_tty_vi__paint(struct a_tty_line *tlp){
1123 enum{
1124 a_TRUE_RV = a_TTY__VF_LAST<<1, /* Return value bit */
1125 a_HAVE_PROMPT = a_TTY__VF_LAST<<2, /* Have a prompt */
1126 a_SHOW_PROMPT = a_TTY__VF_LAST<<3, /* Shall print the prompt */
1127 a_MOVE_CURSOR = a_TTY__VF_LAST<<4, /* Move visual cursor for user! */
1128 a_LEFT_MIN = a_TTY__VF_LAST<<5, /* On left boundary */
1129 a_RIGHT_MAX = a_TTY__VF_LAST<<6,
1130 a_HAVE_POSITION = a_TTY__VF_LAST<<7, /* Print the position indicator */
1132 /* We carry some flags over invocations (not worth a specific field) */
1133 a_VISIBLE_PROMPT = a_TTY__VF_LAST<<8, /* The prompt is on the screen */
1134 a_PERSIST_MASK = a_VISIBLE_PROMPT,
1135 a__LAST = a_PERSIST_MASK
1138 ui32_t f, w, phy_wid_base, phy_wid, phy_base, phy_cur, cnt, lstcur, cur,
1139 vi_left, vi_right, phy_nxtcur;
1140 struct a_tty_cell const *tccp, *tcp_left, *tcp_right, *tcxp;
1141 NYD2_ENTER;
1142 n_LCTA(UICMP(64, a__LAST, <, UI32_MAX), "Flag bits excess storage datatype");
1144 f = tlp->tl_vi_flags;
1145 tlp->tl_vi_flags = (f & ~(a_TTY_VF_REFRESH | a_PERSIST_MASK)) |
1146 a_TTY_VF_SYNC;
1147 f |= a_TRUE_RV;
1148 if((w = tlp->tl_prompt_length) > 0)
1149 f |= a_HAVE_PROMPT;
1150 f |= a_HAVE_POSITION;
1152 /* XXX We don't have a OnTerminalResize event (see main.c) yet, so we need
1153 * XXX to reevaluate our circumstances over and over again */
1154 /* Don't display prompt or position indicator on very small screens */
1155 if((phy_wid_base = (ui32_t)scrnwidth) <= a_TTY_WIDTH_RIPOFF)
1156 f &= ~(a_HAVE_PROMPT | a_HAVE_POSITION);
1157 else{
1158 phy_wid_base -= a_TTY_WIDTH_RIPOFF;
1160 /* Disable the prompt if the screen is too small; due to lack of some
1161 * indicator simply add a second ripoff */
1162 if((f & a_HAVE_PROMPT) && w + a_TTY_WIDTH_RIPOFF >= phy_wid_base)
1163 f &= ~a_HAVE_PROMPT;
1166 phy_wid = phy_wid_base;
1167 phy_base = 0;
1168 phy_cur = tlp->tl_phy_cursor;
1169 cnt = tlp->tl_count;
1170 lstcur = tlp->tl_lst_cursor;
1172 /* XXX Assume dirty screen if shrunk */
1173 if(cnt < tlp->tl_lst_count)
1174 f |= a_TTY_VF_MOD_DIRTY;
1176 /* TODO Without HAVE_TERMCAP, it would likely be much cheaper to simply
1177 * TODO always "cr + paint + ce + ch", since ce is simulated via spaces.. */
1179 /* Quickshot: if the line is empty, possibly print prompt and out */
1180 if(cnt == 0){
1181 /* In that special case dirty anything if it seems better */
1182 if((f & a_TTY_VF_MOD_CONTENT) || tlp->tl_lst_count > 0)
1183 f |= a_TTY_VF_MOD_DIRTY;
1185 if((f & a_TTY_VF_MOD_DIRTY) && phy_cur != 0){
1186 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
1187 goto jerr;
1188 phy_cur = 0;
1191 if((f & (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)) ==
1192 (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)){
1193 if(fputs(tlp->tl_prompt, stdout) == EOF)
1194 goto jerr;
1195 phy_cur = tlp->tl_prompt_width + 1;
1198 /* May need to clear former line content */
1199 if((f & a_TTY_VF_MOD_DIRTY) &&
1200 !n_termcap_cmd(n_TERMCAP_CMD_ce, phy_cur, -1))
1201 goto jerr;
1203 tlp->tl_phy_start = tlp->tl_line.cells;
1204 goto jleave;
1207 /* Try to get an idea of the visual window */
1209 /* Find the left visual boundary */
1210 phy_wid = (phy_wid >> 1) + (phy_wid >> 2);
1211 if((cur = tlp->tl_cursor) == cnt)
1212 --cur;
1214 w = (tcp_left = tccp = tlp->tl_line.cells + cur)->tc_width;
1215 if(w == UI8_MAX) /* TODO yet TAB == SPC */
1216 w = 1;
1217 while(tcp_left > tlp->tl_line.cells){
1218 ui16_t cw = tcp_left[-1].tc_width;
1220 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1221 cw = 1;
1222 if(w + cw >= phy_wid)
1223 break;
1224 w += cw;
1225 --tcp_left;
1227 vi_left = w;
1229 /* If the left hand side of our visual viewpoint consumes less than half
1230 * of the screen width, show the prompt */
1231 if(tcp_left == tlp->tl_line.cells)
1232 f |= a_LEFT_MIN;
1234 if((f & (a_LEFT_MIN | a_HAVE_PROMPT)) == (a_LEFT_MIN | a_HAVE_PROMPT) &&
1235 w + tlp->tl_prompt_width < phy_wid){
1236 phy_base = tlp->tl_prompt_width;
1237 f |= a_SHOW_PROMPT;
1240 /* Then search for right boundary. We always leave the rightmost column
1241 * empty because some terminals [cw]ould wrap the line if we write into
1242 * that. XXX terminfo(5)/termcap(5) have the semi_auto_right_margin/sam/YE
1243 * XXX capability to indicate this, but we don't look at that */
1244 phy_wid = phy_wid_base - phy_base;
1245 tcp_right = tlp->tl_line.cells + cnt;
1247 while(&tccp[1] < tcp_right){
1248 ui16_t cw = tccp[1].tc_width;
1249 ui32_t i;
1251 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1252 cw = 1;
1253 i = w + cw;
1254 if(i > phy_wid)
1255 break;
1256 w = i;
1257 ++tccp;
1259 vi_right = w - vi_left;
1261 /* If the complete line including prompt fits on the screen, show prompt */
1262 if(--tcp_right == tccp){
1263 f |= a_RIGHT_MAX;
1265 /* Since we did brute-force walk also for the left boundary we may end up
1266 * in a situation were anything effectively fits on the screen, including
1267 * the prompt that is, but were we don't recognize this since we
1268 * restricted the search to fit in some visual viewpoint. Therefore try
1269 * again to extend the left boundary to overcome that */
1270 if(!(f & a_LEFT_MIN)){
1271 struct a_tty_cell const *tc1p = tlp->tl_line.cells;
1272 ui32_t vil1 = vi_left;
1274 assert(!(f & a_SHOW_PROMPT));
1275 w += tlp->tl_prompt_width;
1276 for(tcxp = tcp_left;;){
1277 ui32_t i = tcxp[-1].tc_width;
1279 if(i == UI8_MAX) /* TODO yet TAB == SPC */
1280 i = 1;
1281 vil1 += i;
1282 i += w;
1283 if(i > phy_wid)
1284 break;
1285 w = i;
1286 if(--tcxp == tc1p){
1287 tcp_left = tc1p;
1288 vi_left = vil1;
1289 f |= a_LEFT_MIN;
1290 break;
1293 /*w -= tlp->tl_prompt_width;*/
1296 tcp_right = tccp;
1297 tccp = tlp->tl_line.cells + cur;
1299 if((f & (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT | a_SHOW_PROMPT)) ==
1300 (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT) &&
1301 w + tlp->tl_prompt_width <= phy_wid){
1302 phy_wid -= (phy_base = tlp->tl_prompt_width);
1303 f |= a_SHOW_PROMPT;
1306 /* Try to avoid repainting the complete line - this is possible if the
1307 * cursor "did not leave the screen" and the prompt status hasn't changed.
1308 * I.e., after clamping virtual viewpoint, compare relation to physical */
1309 if((f & (a_TTY_VF_MOD_SINGLE/*FIXME*/ |
1310 a_TTY_VF_MOD_CONTENT/* xxx */ | a_TTY_VF_MOD_DIRTY)) ||
1311 (tcxp = tlp->tl_phy_start) == NULL ||
1312 tcxp > tccp || tcxp <= tcp_right)
1313 f |= a_TTY_VF_MOD_DIRTY;
1314 else{
1315 f |= a_TTY_VF_MOD_DIRTY;
1316 #if 0
1317 struct a_tty_cell const *tcyp;
1318 si32_t cur_displace;
1319 ui32_t phy_lmargin, phy_rmargin, fx, phy_displace;
1321 phy_lmargin = (fx = phy_wid) / 100;
1322 phy_rmargin = fx - (phy_lmargin * a_TTY_SCROLL_MARGIN_RIGHT);
1323 phy_lmargin *= a_TTY_SCROLL_MARGIN_LEFT;
1324 fx = (f & (a_SHOW_PROMPT | a_VISIBLE_PROMPT));
1326 if(fx == 0 || fx == (a_SHOW_PROMPT | a_VISIBLE_PROMPT)){
1328 #endif
1330 goto jpaint;
1332 /* We know what we have to paint, start synchronizing */
1333 jpaint:
1334 assert(phy_cur == tlp->tl_phy_cursor);
1335 assert(phy_wid == phy_wid_base - phy_base);
1336 assert(cnt == tlp->tl_count);
1337 assert(cnt > 0);
1338 assert(lstcur == tlp->tl_lst_cursor);
1339 assert(tccp == tlp->tl_line.cells + cur);
1341 phy_nxtcur = phy_base; /* FIXME only if repaint cpl. */
1343 /* Quickshot: is it only cursor movement within the visible screen? */
1344 if((f & a_TTY_VF_REFRESH) == a_TTY_VF_MOD_CURSOR){
1345 f |= a_MOVE_CURSOR;
1346 goto jcursor;
1349 /* To be able to apply some quick jump offs, clear line if possible */
1350 if(f & a_TTY_VF_MOD_DIRTY){
1351 /* Force complete clearance and cursor reinitialization */
1352 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr) ||
1353 !n_termcap_cmd(n_TERMCAP_CMD_ce, 0, -1))
1354 goto jerr;
1355 tlp->tl_phy_start = tcp_left;
1356 phy_cur = 0;
1359 if((f & (a_TTY_VF_MOD_DIRTY | a_SHOW_PROMPT)) && phy_cur != 0){
1360 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
1361 goto jerr;
1362 phy_cur = 0;
1365 if(f & a_SHOW_PROMPT){
1366 assert(phy_base == tlp->tl_prompt_width);
1367 if(fputs(tlp->tl_prompt, stdout) == EOF)
1368 goto jerr;
1369 phy_cur = phy_nxtcur;
1370 f |= a_VISIBLE_PROMPT;
1371 }else
1372 f &= ~a_VISIBLE_PROMPT;
1374 /* FIXME reposition cursor for paint */
1375 for(w = phy_nxtcur; tcp_left <= tcp_right; ++tcp_left){
1376 ui16_t cw;
1378 cw = tcp_left->tc_width;
1380 if(n_LIKELY(!tcp_left->tc_novis)){
1381 if(fwrite(tcp_left->tc_cbuf, sizeof *tcp_left->tc_cbuf,
1382 tcp_left->tc_count, stdout) != tcp_left->tc_count)
1383 goto jerr;
1384 }else{ /* XXX Shouldn't be here <-> CText, ui_str.c */
1385 char wbuf[8]; /* XXX magic */
1387 if(options & OPT_UNICODE){
1388 ui32_t wc;
1390 wc = (ui32_t)tcp_left->tc_wc;
1391 if((wc & ~0x1Fu) == 0)
1392 wc |= 0x2400;
1393 else if(wc == 0x7F)
1394 wc = 0x2421;
1395 else
1396 wc = 0x2426;
1397 n_utf32_to_utf8(wc, wbuf);
1398 }else
1399 wbuf[0] = '?', wbuf[1] = '\0';
1401 if(fputs(wbuf, stdout) == EOF)
1402 goto jerr;
1403 cw = 1;
1406 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1407 cw = 1;
1408 w += cw;
1409 if(tcp_left == tccp)
1410 phy_nxtcur = w;
1411 phy_cur += cw;
1414 /* Write something position marker alike if it doesn't fit on screen */
1415 if((f & a_HAVE_POSITION) &&
1416 ((f & (a_LEFT_MIN | a_RIGHT_MAX)) != (a_LEFT_MIN | a_RIGHT_MAX) ||
1417 ((f & a_HAVE_PROMPT) && !(f & a_SHOW_PROMPT)))){
1418 # ifdef HAVE_COLOUR
1419 char *posbuf = tlp->tl_pos_buf, *pos = tlp->tl_pos;
1420 # else
1421 char posbuf[5], *pos = posbuf;
1423 pos[4] = '\0';
1424 # endif
1426 if(phy_cur != (w = phy_wid_base) &&
1427 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = w, 0))
1428 goto jerr;
1430 *pos++ = '|';
1431 if((f & a_LEFT_MIN) && (!(f & a_HAVE_PROMPT) || (f & a_SHOW_PROMPT)))
1432 memcpy(pos, "^.+", 3);
1433 else if(f & a_RIGHT_MAX)
1434 memcpy(pos, ".+$", 3);
1435 else{
1436 /* Theoretical line length limit a_TTY_LINE_MAX, choose next power of
1437 * ten (10 ** 10) to represent 100 percent, since we don't have a macro
1438 * that generates a constant, and i don't trust the standard "u type
1439 * suffix automatically scales" calculate the large number */
1440 static char const itoa[] = "0123456789";
1442 ui64_t const fact100 = (ui64_t)0x3B9ACA00u * 10u, fact = fact100 / 100;
1443 ui32_t i = (ui32_t)(((fact100 / cnt) * tlp->tl_cursor) / fact);
1444 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1446 if(i < 10)
1447 pos[0] = ' ', pos[1] = itoa[i];
1448 else
1449 pos[1] = itoa[i % 10], pos[0] = itoa[i / 10];
1450 pos[2] = '%';
1453 if(fputs(posbuf, stdout) == EOF)
1454 goto jerr;
1455 phy_cur += 4;
1458 /* Users are used to see the cursor right of the point of interest, so we
1459 * need some further adjustments unless in special conditions. Be aware
1460 * that we may have adjusted cur at the beginning, too */
1461 if((cur = tlp->tl_cursor) == 0)
1462 phy_nxtcur = phy_base;
1463 else if(cur != cnt){
1464 ui16_t cw = tccp->tc_width;
1466 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1467 cw = 1;
1468 phy_nxtcur -= cw;
1471 jcursor:
1472 if(((f & a_MOVE_CURSOR) || phy_nxtcur != phy_cur) &&
1473 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = phy_nxtcur, 0))
1474 goto jerr;
1476 jleave:
1477 tlp->tl_vi_flags |= (f & a_PERSIST_MASK);
1478 tlp->tl_lst_count = tlp->tl_count;
1479 tlp->tl_lst_cursor = tlp->tl_cursor;
1480 tlp->tl_phy_cursor = phy_cur;
1482 NYD2_LEAVE;
1483 return ((f & a_TRUE_RV) != 0);
1484 jerr:
1485 f &= ~a_TRUE_RV;
1486 goto jleave;
1489 static si32_t
1490 a_tty_wboundary(struct a_tty_line *tlp, si32_t dir){/* TODO shell token-wise */
1491 bool_t anynon;
1492 struct a_tty_cell *tcap;
1493 ui32_t cur, cnt;
1494 si32_t rv;
1495 NYD2_ENTER;
1497 assert(dir == 1 || dir == -1);
1499 rv = -1;
1500 cnt = tlp->tl_count;
1501 cur = tlp->tl_cursor;
1503 if(dir < 0){
1504 if(cur == 0)
1505 goto jleave;
1506 }else if(cur + 1 >= cnt)
1507 goto jleave;
1508 else
1509 --cnt, --cur; /* xxx Unsigned wrapping may occur (twice), then */
1511 for(rv = 0, tcap = tlp->tl_line.cells, anynon = FAL0;;){
1512 wchar_t wc;
1514 wc = tcap[cur += (ui32_t)dir].tc_wc;
1515 if(iswblank(wc) || iswpunct(wc)){
1516 if(anynon)
1517 break;
1518 }else
1519 anynon = TRU1;
1521 ++rv;
1523 if(dir < 0){
1524 if(cur == 0)
1525 break;
1526 }else if(cur + 1 >= cnt){
1527 ++rv;
1528 break;
1531 jleave:
1532 NYD2_LEAVE;
1533 return rv;
1536 static void
1537 a_tty_khome(struct a_tty_line *tlp, bool_t dobell){
1538 ui32_t f;
1539 NYD2_ENTER;
1541 if(n_LIKELY(tlp->tl_cursor > 0)){
1542 tlp->tl_cursor = 0;
1543 f = a_TTY_VF_MOD_CURSOR;
1544 }else if(dobell)
1545 f = a_TTY_VF_BELL;
1546 else
1547 f = a_TTY_VF_NONE;
1549 tlp->tl_vi_flags |= f;
1550 NYD2_LEAVE;
1553 static void
1554 a_tty_kend(struct a_tty_line *tlp){
1555 ui32_t f;
1556 NYD2_ENTER;
1558 if(n_LIKELY(tlp->tl_cursor < tlp->tl_count)){
1559 tlp->tl_cursor = tlp->tl_count;
1560 f = a_TTY_VF_MOD_CURSOR;
1561 }else
1562 f = a_TTY_VF_BELL;
1564 tlp->tl_vi_flags |= f;
1565 NYD2_LEAVE;
1568 static void
1569 a_tty_kbs(struct a_tty_line *tlp){
1570 ui32_t f, cur, cnt;
1571 NYD2_ENTER;
1573 cur = tlp->tl_cursor;
1574 cnt = tlp->tl_count;
1576 if(n_LIKELY(cur > 0)){
1577 tlp->tl_cursor = --cur;
1578 tlp->tl_count = --cnt;
1580 if((cnt -= cur) > 0){
1581 struct a_tty_cell *tcap;
1583 tcap = tlp->tl_line.cells + cur;
1584 memmove(tcap, &tcap[1], cnt *= sizeof(*tcap));
1586 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
1587 }else
1588 f = a_TTY_VF_BELL;
1590 tlp->tl_vi_flags |= f;
1591 NYD2_LEAVE;
1594 static void
1595 a_tty_ksnarf(struct a_tty_line *tlp, bool_t cplline, bool_t dobell){
1596 ui32_t i, f;
1597 NYD2_ENTER;
1599 f = a_TTY_VF_NONE;
1600 i = tlp->tl_cursor;
1602 if(cplline && i > 0){
1603 tlp->tl_cursor = i = 0;
1604 f = a_TTY_VF_MOD_CURSOR;
1607 if(n_LIKELY(i < tlp->tl_count)){
1608 struct a_tty_cell *tcap;
1610 tcap = &tlp->tl_line.cells[0];
1611 a_tty_copy2paste(tlp, &tcap[i], &tcap[tlp->tl_count]);
1612 tlp->tl_count = i;
1613 f = a_TTY_VF_MOD_CONTENT;
1614 }else if(dobell)
1615 f |= a_TTY_VF_BELL;
1617 tlp->tl_vi_flags |= f;
1618 NYD2_LEAVE;
1621 static si32_t
1622 a_tty_kdel(struct a_tty_line *tlp){
1623 ui32_t cur, cnt, f;
1624 si32_t i;
1625 NYD2_ENTER;
1627 cur = tlp->tl_cursor;
1628 cnt = tlp->tl_count;
1629 i = (si32_t)(cnt - cur);
1631 if(n_LIKELY(i > 0)){
1632 tlp->tl_count = --cnt;
1634 if(n_LIKELY(--i > 0)){
1635 struct a_tty_cell *tcap;
1637 tcap = &tlp->tl_line.cells[cur];
1638 memmove(tcap, &tcap[1], (ui32_t)i * sizeof(*tcap));
1640 f = a_TTY_VF_MOD_CONTENT;
1641 }else if(cnt == 0 && !ok_blook(ignoreeof)){
1642 putchar('^');
1643 putchar('D');
1644 i = -1;
1645 f = a_TTY_VF_NONE;
1646 }else{
1647 i = 0;
1648 f = a_TTY_VF_BELL;
1651 tlp->tl_vi_flags |= f;
1652 NYD2_LEAVE;
1653 return i;
1656 static void
1657 a_tty_kleft(struct a_tty_line *tlp){
1658 ui32_t f;
1659 NYD2_ENTER;
1661 if(n_LIKELY(tlp->tl_cursor > 0)){
1662 --tlp->tl_cursor;
1663 f = a_TTY_VF_MOD_CURSOR;
1664 }else
1665 f = a_TTY_VF_BELL;
1667 tlp->tl_vi_flags |= f;
1668 NYD2_LEAVE;
1671 static void
1672 a_tty_kright(struct a_tty_line *tlp){
1673 ui32_t i;
1674 NYD2_ENTER;
1676 if(n_LIKELY((i = tlp->tl_cursor + 1) <= tlp->tl_count)){
1677 tlp->tl_cursor = i;
1678 i = a_TTY_VF_MOD_CURSOR;
1679 }else
1680 i = a_TTY_VF_BELL;
1682 tlp->tl_vi_flags |= i;
1683 NYD2_LEAVE;
1686 static void
1687 a_tty_ksnarfw(struct a_tty_line *tlp, bool_t fwd){
1688 struct a_tty_cell *tcap;
1689 ui32_t cnt, cur, f;
1690 si32_t i;
1691 NYD2_ENTER;
1693 if(n_UNLIKELY((i = a_tty_wboundary(tlp, (fwd ? +1 : -1))) <= 0)){
1694 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
1695 goto jleave;
1698 cnt = tlp->tl_count - (ui32_t)i;
1699 cur = tlp->tl_cursor;
1700 if(!fwd)
1701 cur -= (ui32_t)i;
1702 tcap = &tlp->tl_line.cells[cur];
1704 a_tty_copy2paste(tlp, &tcap[0], &tcap[i]);
1706 if((tlp->tl_count = cnt) != (tlp->tl_cursor = cur)){
1707 cnt -= cur;
1708 memmove(&tcap[0], &tcap[i], cnt * sizeof(*tcap)); /* FIXME*/
1711 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
1712 jleave:
1713 tlp->tl_vi_flags |= f;
1714 NYD2_LEAVE;
1717 static void
1718 a_tty_kgow(struct a_tty_line *tlp, si32_t dir){
1719 ui32_t f;
1720 si32_t i;
1721 NYD2_ENTER;
1723 if(n_UNLIKELY((i = a_tty_wboundary(tlp, dir)) <= 0))
1724 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
1725 else{
1726 if(dir < 0)
1727 i = -i;
1728 tlp->tl_cursor += (ui32_t)i;
1729 f = a_TTY_VF_MOD_CURSOR;
1732 tlp->tl_vi_flags |= f;
1733 NYD2_LEAVE;
1736 static bool_t
1737 a_tty_kother(struct a_tty_line *tlp, wchar_t wc){
1738 /* Append if at EOL, insert otherwise;
1739 * since we may move around character-wise, always use a fresh ps */
1740 mbstate_t ps;
1741 struct a_tty_cell tc, *tcap;
1742 ui32_t f, cur, cnt;
1743 bool_t rv;
1744 NYD2_ENTER;
1746 rv = FAL0;
1747 f = a_TTY_VF_NONE;
1749 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1750 if(tlp->tl_count + 1 >= a_TTY_LINE_MAX){
1751 n_err(_("Stop here, we can't extend line beyond size limit\n"));
1752 goto jleave;
1755 /* First init a cell and see whether we'll really handle this wc */
1756 memset(&ps, 0, sizeof ps);
1757 /* C99 */{
1758 size_t l;
1760 l = wcrtomb(tc.tc_cbuf, tc.tc_wc = wc, &ps);
1761 if(n_UNLIKELY(l > MB_LEN_MAX)){
1762 jemb:
1763 n_err(_("wcrtomb(3) error: too many multibyte character bytes\n"));
1764 goto jleave;
1766 tc.tc_count = (ui16_t)l;
1768 if(n_UNLIKELY((options & OPT_ENC_MBSTATE) != 0)){
1769 l = wcrtomb(&tc.tc_cbuf[l], L'\0', &ps);
1770 if(n_LIKELY(l == 1))
1771 /* Only NUL terminator */;
1772 else if(n_LIKELY(--l < MB_LEN_MAX))
1773 tc.tc_count += (ui16_t)l;
1774 else
1775 goto jemb;
1779 /* Yes, we will! Place it in the array */
1780 tc.tc_novis = (iswprint(wc) == 0);
1781 tc.tc_width = a_tty_wcwidth(wc);
1782 /* TODO if(tc.tc_novis && tc.tc_width > 0) */
1784 cur = tlp->tl_cursor++;
1785 cnt = tlp->tl_count++ - cur;
1786 tcap = &tlp->tl_line.cells[cur];
1787 if(cnt >= 1){
1788 memmove(&tcap[1], tcap, cnt * sizeof(*tcap));
1789 f = a_TTY_VF_MOD_CONTENT;
1790 }else
1791 f = a_TTY_VF_MOD_SINGLE;
1792 memcpy(tcap, &tc, sizeof *tcap);
1794 f |= a_TTY_VF_MOD_CURSOR;
1795 rv = TRU1;
1796 jleave:
1797 if(!rv)
1798 f |= a_TTY_VF_BELL;
1799 tlp->tl_vi_flags |= f;
1800 NYD2_LEAVE;
1801 return rv;
1804 static ui32_t
1805 a_tty_kht(struct a_tty_line *tlp){
1806 struct stat sb;
1807 struct str orig, bot, topp, sub, exp;
1808 struct n_string shou, *shoup;
1809 struct a_tty_cell *cword, *ctop, *cx;
1810 bool_t wedid, set_savec;
1811 ui32_t rv, f;
1812 NYD2_ENTER;
1814 f = a_TTY_VF_NONE;
1815 shoup = n_string_creat_auto(&shou);
1817 /* Get plain line data; if this is the first expansion/xy, update the
1818 * very original content so that ^G gets the origin back */
1819 orig = tlp->tl_savec;
1820 a_tty_cell2save(tlp);
1821 exp = tlp->tl_savec;
1822 if(orig.s != NULL){
1823 /*tlp->tl_savec = orig;*/
1824 set_savec = FAL0;
1825 }else
1826 set_savec = TRU1;
1827 orig = exp;
1829 /* Find the word to be expanded */
1831 cword = tlp->tl_line.cells;
1832 ctop = cword + tlp->tl_cursor;
1833 cx = cword + tlp->tl_count;
1835 /* topp: separate data right of cursor */
1836 if(cx > ctop){
1837 for(rv = 0; ctop < cx; ++ctop)
1838 rv += ctop->tc_count;
1839 topp.l = rv;
1840 topp.s = orig.s + orig.l - rv;
1841 ctop = cword + tlp->tl_cursor;
1842 }else
1843 topp.s = NULL, topp.l = 0;
1845 /* Find the shell token that corresponds to the cursor position */
1846 /* C99 */{
1847 size_t max;
1849 max = 0;
1850 if(ctop > cword){
1851 for(; cword < ctop; ++cword)
1852 max += cword->tc_count;
1853 cword = tlp->tl_line.cells;
1855 bot = sub = orig;
1856 bot.l = 0;
1857 sub.l = max;
1859 if(max > 0){
1860 for(;;){
1861 enum n_shexp_state shs;
1863 exp = sub;
1864 shs = n_shexp_parse_token(NULL, &sub, n_SHEXP_PARSE_DRYRUN |
1865 n_SHEXP_PARSE_TRIMSPACE | n_SHEXP_PARSE_IGNORE_EMPTY |
1866 n_SHEXP_PARSE_QUOTE_AUTOCLOSE);
1867 if(sub.l != 0){
1868 size_t x;
1870 assert(max >= sub.l);
1871 x = max - sub.l;
1872 bot.l += x;
1873 max -= x;
1874 continue;
1876 if(shs & n_SHEXP_STATE_ERR_MASK){
1877 n_err(_("Invalid completion pattern: %.*s\n"),
1878 (int)exp.l, exp.s);
1879 goto jnope;
1881 n_shexp_parse_token(shoup, &exp,
1882 n_SHEXP_PARSE_TRIMSPACE | n_SHEXP_PARSE_IGNORE_EMPTY |
1883 n_SHEXP_PARSE_QUOTE_AUTOCLOSE);
1884 break;
1887 sub.s = n_string_cp(shoup);
1888 sub.l = shoup->s_len;
1892 /* Leave room for "implicit asterisk" expansion, as below */
1893 if(sub.l == 0){
1894 wedid = TRU1;
1895 sub.s = n_UNCONST("*");
1896 sub.l = 1;
1899 wedid = FAL0;
1900 jredo:
1901 /* TODO Super-Heavy-Metal: block all sigs, avoid leaks on jump */
1902 hold_all_sigs();
1903 exp.s = fexpand(sub.s, a_TTY_TAB_FEXP_FL);
1904 rele_all_sigs();
1906 if(exp.s == NULL || (exp.l = strlen(exp.s)) == 0)
1907 goto jnope;
1909 /* May be multi-return! */
1910 if(pstate & PS_EXPAND_MULTIRESULT)
1911 goto jmulti;
1913 /* xxx That is not really true since the limit counts characters not bytes */
1914 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1915 if(exp.l + 1 >= a_TTY_LINE_MAX){
1916 n_err(_("Tabulator expansion would extend beyond line size limit\n"));
1917 goto jnope;
1920 /* If the expansion equals the original string, assume the user wants what
1921 * is usually known as tab completion, append `*' and restart */
1922 if(!wedid && exp.l == sub.l && !memcmp(exp.s, sub.s, exp.l)){
1923 if(sub.s[sub.l - 1] == '*')
1924 goto jnope;
1926 wedid = TRU1;
1927 sub.s[sub.l++] = '*';
1928 sub.s[sub.l] = '\0';
1929 goto jredo;
1931 /* If it is a directory, and there is not yet a / appended, then we want the
1932 * user to confirm that he wants to dive in -- with only a HT */
1933 else if(wedid && exp.l == --sub.l && !memcmp(exp.s, sub.s, exp.l) &&
1934 exp.s[exp.l - 1] != '/'){
1935 if(stat(exp.s, &sb) || !S_ISDIR(sb.st_mode))
1936 goto jnope;
1937 sub.s = salloc(exp.l + 1 +1);
1938 memcpy(sub.s, exp.s, exp.l);
1939 sub.s[exp.l++] = '/';
1940 sub.s[exp.l] = '\0';
1941 exp.s = sub.s;
1942 wedid = FAL0;
1943 goto jset;
1944 }else{
1945 if(wedid && (wedid = (exp.s[exp.l - 1] == '*')))
1946 --exp.l;
1947 exp.s[exp.l] = '\0';
1948 jset:
1949 exp.l = strlen(exp.s = n_shexp_quote_cp(exp.s, tlp->tl_quote_rndtrip));
1950 tlp->tl_defc_cursor_byte = bot.l + exp.l -1;
1951 if(wedid)
1952 goto jnope;
1955 orig.l = bot.l + exp.l + topp.l;
1956 orig.s = salloc(orig.l + 5 +1);
1957 if((rv = (ui32_t)bot.l) > 0)
1958 memcpy(orig.s, bot.s, rv);
1959 memcpy(orig.s + rv, exp.s, exp.l);
1960 rv += exp.l;
1961 if(topp.l > 0){
1962 memcpy(orig.s + rv, topp.s, topp.l);
1963 rv += topp.l;
1965 orig.s[rv] = '\0';
1967 tlp->tl_defc = orig;
1968 tlp->tl_count = tlp->tl_cursor = 0;
1969 f |= a_TTY_VF_MOD_DIRTY;
1970 jleave:
1971 n_string_gut(shoup);
1972 tlp->tl_vi_flags |= f;
1973 NYD2_LEAVE;
1974 return rv;
1976 jmulti:{
1977 struct n_visual_info_ctx vic;
1978 struct str input;
1979 wc_t c2, c1;
1980 bool_t isfirst;
1981 char const *lococp;
1982 size_t locolen, scrwid, lnlen, lncnt, prefixlen;
1983 FILE *fp;
1985 if((fp = Ftmp(NULL, "tabex", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
1986 n_perr(_("tmpfile"), 0);
1987 fp = stdout;
1990 /* How long is the result string for real? Search the NUL NUL
1991 * terminator. While here, detect the longest entry to perform an
1992 * initial allocation of our accumulator string */
1993 locolen = 0;
1995 size_t i;
1997 i = strlen(&exp.s[++exp.l]);
1998 locolen = n_MAX(locolen, i);
1999 exp.l += i;
2000 }while(exp.s[exp.l + 1] != '\0');
2002 shoup = n_string_reserve(n_string_trunc(shoup, 0),
2003 locolen + (locolen >> 1));
2005 /* Iterate (once again) over all results */
2006 scrwid = (size_t)scrnwidth - ((size_t)scrnwidth >> 3);
2007 lnlen = lncnt = 0;
2008 n_UNINIT(prefixlen, 0);
2009 n_UNINIT(lococp, NULL);
2010 n_UNINIT(c1, '\0');
2011 for(isfirst = TRU1; exp.l > 0; isfirst = FAL0, c1 = c2){
2012 size_t i;
2013 char const *fullpath;
2015 /* Next result */
2016 sub = exp;
2017 sub.l = i = strlen(sub.s);
2018 assert(exp.l >= i);
2019 if((exp.l -= i) > 0)
2020 --exp.l;
2021 exp.s += ++i;
2023 /* Separate dirname and basename */
2024 fullpath = sub.s;
2025 if(isfirst){
2026 char const *cp;
2028 if((cp = strrchr(fullpath, '/')) != NULL)
2029 prefixlen = PTR2SIZE(++cp - fullpath);
2030 else
2031 prefixlen = 0;
2033 if(prefixlen > 0 && prefixlen < sub.l){
2034 sub.l -= prefixlen;
2035 sub.s += prefixlen;
2038 /* We want case-insensitive sort-order */
2039 memset(&vic, 0, sizeof vic);
2040 vic.vic_indat = sub.s;
2041 vic.vic_inlen = sub.l;
2042 c2 = n_visual_info(&vic, n_VISUAL_INFO_ONE_CHAR) ? vic.vic_waccu
2043 : (ui8_t)*sub.s;
2044 #ifdef HAVE_C90AMEND1
2045 c2 = towlower(c2);
2046 #else
2047 c2 = lowerconv(c2);
2048 #endif
2050 /* Query longest common prefix along the way */
2051 if(isfirst){
2052 c1 = c2;
2053 lococp = sub.s;
2054 locolen = sub.l;
2055 }else if(locolen > 0){
2056 for(i = 0; i < locolen; ++i)
2057 if(lococp[i] != sub.s[i]){
2058 i = field_detect_clip(i, lococp, i);
2059 locolen = i;
2060 break;
2064 /* Prepare display */
2065 input = sub;
2066 shoup = n_shexp_quote(n_string_trunc(shoup, 0), &input,
2067 tlp->tl_quote_rndtrip);
2068 memset(&vic, 0, sizeof vic);
2069 vic.vic_indat = shoup->s_dat;
2070 vic.vic_inlen = shoup->s_len;
2071 if(!n_visual_info(&vic,
2072 n_VISUAL_INFO_SKIP_ERRORS | n_VISUAL_INFO_WIDTH_QUERY))
2073 vic.vic_vi_width = shoup->s_len;
2075 /* Put on screen. Indent follow lines of same sort slot */
2076 c1 = (c1 != c2);
2077 if(isfirst || c1 ||
2078 scrwid < lnlen || scrwid - lnlen <= vic.vic_vi_width + 2){
2079 putc('\n', fp);
2080 if(scrwid < lnlen)
2081 ++lncnt;
2082 ++lncnt, lnlen = 0;
2083 if(!isfirst && !c1)
2084 goto jsep;
2085 }else if(lnlen > 0){
2086 jsep:
2087 fputs(" ", fp);
2088 lnlen += 2;
2090 fputs(n_string_cp(shoup), fp);
2091 lnlen += vic.vic_vi_width;
2093 /* Support the known file name tagging
2094 * XXX *line-editor-completion-filetype* or so */
2095 if(!lstat(fullpath, &sb)){
2096 char c = '\0';
2098 if(S_ISDIR(sb.st_mode))
2099 c = '/';
2100 else if(S_ISLNK(sb.st_mode))
2101 c = '@';
2102 # ifdef S_ISFIFO
2103 else if(S_ISFIFO(sb.st_mode))
2104 c = '|';
2105 # endif
2106 # ifdef S_ISSOCK
2107 else if(S_ISSOCK(sb.st_mode))
2108 c = '=';
2109 # endif
2110 # ifdef S_ISCHR
2111 else if(S_ISCHR(sb.st_mode))
2112 c = '%';
2113 # endif
2114 # ifdef S_ISBLK
2115 else if(S_ISBLK(sb.st_mode))
2116 c = '#';
2117 # endif
2119 if(c != '\0'){
2120 putc(c, fp);
2121 ++lnlen;
2125 putc('\n', fp);
2126 ++lncnt;
2128 page_or_print(fp, lncnt);
2129 if(fp != stdout)
2130 Fclose(fp);
2132 n_string_gut(shoup);
2134 /* A common prefix of 0 means we cannot provide the user any auto
2135 * completed characters */
2136 if(locolen == 0)
2137 goto jnope;
2139 /* Otherwise we can, so extend the visual line content by the common
2140 * prefix (in a reversible way) */
2141 (exp.s = n_UNCONST(lococp))[locolen] = '\0';
2142 exp.s -= prefixlen;
2143 exp.l = (locolen += prefixlen);
2145 /* XXX Indicate that there is multiple choice */
2146 /* XXX f |= a_TTY_VF_BELL; -> *line-editor-completion-bell*? or so */
2147 wedid = FAL0;
2148 goto jset;
2151 jnope:
2152 /* If we've provided a default content, but failed to expand, there is
2153 * nothing we can "revert to": drop that default again */
2154 if(set_savec){
2155 tlp->tl_savec.s = NULL;
2156 tlp->tl_savec.l = 0;
2158 f = a_TTY_VF_NONE;
2159 rv = 0;
2160 goto jleave;
2163 # ifdef HAVE_HISTORY
2164 static ui32_t
2165 a_tty__khist_shared(struct a_tty_line *tlp, struct a_tty_hist *thp){
2166 ui32_t f, rv;
2167 NYD2_ENTER;
2169 if(n_LIKELY((tlp->tl_hist = thp) != NULL)){
2170 tlp->tl_defc.s = savestrbuf(thp->th_dat, thp->th_len);
2171 rv = tlp->tl_defc.l = thp->th_len;
2172 f = (tlp->tl_count > 0) ? a_TTY_VF_MOD_DIRTY : a_TTY_VF_NONE;
2173 tlp->tl_count = tlp->tl_cursor = 0;
2174 }else{
2175 f = a_TTY_VF_BELL;
2176 rv = UI32_MAX;
2179 tlp->tl_vi_flags |= f;
2180 NYD2_LEAVE;
2181 return rv;
2184 static ui32_t
2185 a_tty_khist(struct a_tty_line *tlp, bool_t fwd){
2186 struct a_tty_hist *thp;
2187 ui32_t rv;
2188 NYD2_ENTER;
2190 /* If we're not in history mode yet, save line content;
2191 * also, disallow forward search, then, and, of course, bail unless we
2192 * do have any history at all */
2193 if((thp = tlp->tl_hist) == NULL){
2194 if(fwd)
2195 goto jleave;
2196 if((thp = a_tty.tg_hist) == NULL)
2197 goto jleave;
2198 a_tty_cell2save(tlp);
2199 goto jleave;
2202 thp = fwd ? thp->th_younger : thp->th_older;
2203 jleave:
2204 rv = a_tty__khist_shared(tlp, thp);
2205 NYD2_LEAVE;
2206 return rv;
2209 static ui32_t
2210 a_tty_khist_search(struct a_tty_line *tlp, bool_t fwd){
2211 struct str orig_savec;
2212 struct a_tty_hist *thp;
2213 ui32_t rv;
2214 NYD2_ENTER;
2216 thp = NULL;
2218 /* We cannot complete an empty line */
2219 if(n_UNLIKELY(tlp->tl_count == 0)){
2220 /* XXX The upcoming hard reset would restore a set savec buffer,
2221 * XXX so forcefully reset that. A cleaner solution would be to
2222 * XXX reset it whenever a restore is no longer desired */
2223 tlp->tl_savec.s = NULL;
2224 tlp->tl_savec.l = 0;
2225 goto jleave;
2228 if((thp = tlp->tl_hist) == NULL){
2229 if((thp = a_tty.tg_hist) == NULL)
2230 goto jleave;
2231 /* We don't support wraparound, searching forward must always step */
2232 if(fwd)
2233 thp = thp->th_younger;
2234 orig_savec.s = NULL;
2235 orig_savec.l = 0; /* silence CC */
2236 }else if((thp = (fwd ? thp->th_younger : thp->th_older)) == NULL)
2237 goto jleave;
2238 else
2239 orig_savec = tlp->tl_savec;
2241 if(orig_savec.s == NULL)
2242 a_tty_cell2save(tlp);
2244 for(; thp != NULL; thp = (fwd ? thp->th_younger : thp->th_older))
2245 if(is_prefix(tlp->tl_savec.s, thp->th_dat))
2246 break;
2248 if(orig_savec.s != NULL)
2249 tlp->tl_savec = orig_savec;
2250 jleave:
2251 rv = a_tty__khist_shared(tlp, thp);
2252 NYD2_LEAVE;
2253 return rv;
2255 # endif /* HAVE_HISTORY */
2257 static enum a_tty_fun_status
2258 a_tty_fun(struct a_tty_line *tlp, enum a_tty_bind_flags tbf, size_t *len){
2259 enum a_tty_fun_status rv;
2260 NYD2_ENTER;
2262 rv = a_TTY_FUN_STATUS_OK;
2263 # undef a_X
2264 # define a_X(N) a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## N)
2265 switch(a_TTY_BIND_FUN_REDUCE(tbf)){
2266 case a_X(BELL):
2267 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2268 break;
2269 case a_X(GO_BWD):
2270 a_tty_kleft(tlp);
2271 break;
2272 case a_X(GO_FWD):
2273 a_tty_kright(tlp);
2274 break;
2275 case a_X(GO_WORD_BWD):
2276 a_tty_kgow(tlp, -1);
2277 break;
2278 case a_X(GO_WORD_FWD):
2279 a_tty_kgow(tlp, +1);
2280 break;
2281 case a_X(GO_HOME):
2282 a_tty_khome(tlp, TRU1);
2283 break;
2284 case a_X(GO_END):
2285 a_tty_kend(tlp);
2286 break;
2287 case a_X(DEL_BWD):
2288 a_tty_kbs(tlp);
2289 break;
2290 case a_X(DEL_FWD):
2291 if(a_tty_kdel(tlp) < 0)
2292 rv = a_TTY_FUN_STATUS_END;
2293 break;
2294 case a_X(SNARF_WORD_BWD):
2295 a_tty_ksnarfw(tlp, FAL0);
2296 break;
2297 case a_X(SNARF_WORD_FWD):
2298 a_tty_ksnarfw(tlp, TRU1);
2299 break;
2300 case a_X(SNARF_END):
2301 a_tty_ksnarf(tlp, FAL0, TRU1);
2302 break;
2303 case a_X(SNARF_LINE):
2304 a_tty_ksnarf(tlp, TRU1, (tlp->tl_count == 0));
2305 break;
2307 case a_X(HIST_FWD):
2308 # ifdef HAVE_HISTORY
2309 if(tlp->tl_hist != NULL){
2310 bool_t isfwd = TRU1;
2312 if(0){
2313 # endif
2314 /* FALLTHRU */
2315 case a_X(HIST_BWD):
2316 # ifdef HAVE_HISTORY
2317 isfwd = FAL0;
2319 if((*len = a_tty_khist(tlp, isfwd)) != UI32_MAX){
2320 rv = a_TTY_FUN_STATUS_RESTART;
2321 break;
2323 goto jreset;
2324 # endif
2326 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2327 break;
2329 case a_X(HIST_SRCH_FWD):{
2330 # ifdef HAVE_HISTORY
2331 bool_t isfwd = TRU1;
2333 if(0){
2334 # endif
2335 /* FALLTHRU */
2336 case a_X(HIST_SRCH_BWD):
2337 # ifdef HAVE_HISTORY
2338 isfwd = FAL0;
2340 if((*len = a_tty_khist_search(tlp, isfwd)) != UI32_MAX){
2341 rv = a_TTY_FUN_STATUS_RESTART;
2342 break;
2344 goto jreset;
2345 # else
2346 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2347 # endif
2348 } break;
2350 case a_X(REPAINT):
2351 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2352 break;
2353 case a_X(QUOTE_RNDTRIP):
2354 tlp->tl_quote_rndtrip = !tlp->tl_quote_rndtrip;
2355 break;
2356 case a_X(PROMPT_CHAR):{
2357 wchar_t wc;
2359 if((wc = a_tty_vinuni(tlp)) > 0)
2360 a_tty_kother(tlp, wc);
2361 } break;
2362 case a_X(COMPLETE):
2363 if((*len = a_tty_kht(tlp)) > 0)
2364 rv = a_TTY_FUN_STATUS_RESTART;
2365 break;
2367 case a_X(PASTE):
2368 if(tlp->tl_pastebuf.l > 0)
2369 *len = (tlp->tl_defc = tlp->tl_pastebuf).l;
2370 else
2371 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2372 break;
2375 case a_X(CANCEL):
2376 /* Normally this just causes a restart and thus resets the state
2377 * machine */
2378 if(tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2380 # ifdef HAVE_KEY_BINDINGS
2381 tlp->tl_bind_takeover = '\0';
2382 # endif
2383 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2384 rv = a_TTY_FUN_STATUS_RESTART;
2385 break;
2387 case a_X(RESET):
2388 if(tlp->tl_count == 0 && tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2389 # ifdef HAVE_KEY_BINDINGS
2390 tlp->tl_bind_takeover = '\0';
2391 # endif
2392 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY | a_TTY_VF_BELL;
2393 break;
2394 }else if(0){
2395 case a_X(FULLRESET):
2396 tlp->tl_savec.s = tlp->tl_defc.s = NULL;
2397 tlp->tl_savec.l = tlp->tl_defc.l = 0;
2398 tlp->tl_defc_cursor_byte = 0;
2399 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2401 jreset:
2402 # ifdef HAVE_KEY_BINDINGS
2403 tlp->tl_bind_takeover = '\0';
2404 # endif
2405 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2406 tlp->tl_cursor = tlp->tl_count = 0;
2407 # ifdef HAVE_HISTORY
2408 tlp->tl_hist = NULL;
2409 # endif
2410 if((*len = tlp->tl_savec.l) != 0){
2411 tlp->tl_defc = tlp->tl_savec;
2412 tlp->tl_savec.s = NULL;
2413 tlp->tl_savec.l = 0;
2414 }else
2415 *len = tlp->tl_defc.l;
2416 rv = a_TTY_FUN_STATUS_RESTART;
2417 break;
2419 default:
2420 case a_X(COMMIT):
2421 rv = a_TTY_FUN_STATUS_COMMIT;
2422 break;
2424 # undef a_X
2426 NYD2_LEAVE;
2427 return rv;
2430 static ssize_t
2431 a_tty_readline(struct a_tty_line *tlp, size_t len n_MEMORY_DEBUG_ARGS){
2432 /* We want to save code, yet we may have to incorporate a lines'
2433 * default content and / or default input to switch back to after some
2434 * history movement; let "len > 0" mean "have to display some data
2435 * buffer" -> a_BUFMODE, and only otherwise read(2) it */
2436 mbstate_t ps[2];
2437 char cbuf_base[MB_LEN_MAX * 2], *cbuf, *cbufp;
2438 ssize_t rv;
2439 struct a_tty_bind_tree *tbtp;
2440 wchar_t wc;
2441 enum a_tty_bind_flags tbf;
2442 enum {a_NONE, a_WAS_HERE = 1<<0, a_BUFMODE = 1<<1, a_MAYBEFUN = 1<<2,
2443 a_TIMEOUT = 1<<3, a_TIMEOUT_EXPIRED = 1<<4,
2444 a_TIMEOUT_MASK = a_TIMEOUT | a_TIMEOUT_EXPIRED,
2445 a_READ_LOOP_MASK = ~(a_WAS_HERE | a_MAYBEFUN | a_TIMEOUT_MASK)
2446 } flags;
2447 NYD_ENTER;
2449 n_UNINIT(rv, 0);
2450 # ifdef HAVE_KEY_BINDINGS
2451 assert(tlp->tl_bind_takeover == '\0');
2452 # endif
2453 jrestart:
2454 memset(ps, 0, sizeof ps);
2455 flags = a_NONE;
2456 tbf = 0;
2457 tlp->tl_vi_flags |= a_TTY_VF_REFRESH | a_TTY_VF_SYNC;
2459 jinput_loop:
2460 for(;;){
2461 if(len != 0)
2462 flags |= a_BUFMODE;
2464 /* Ensure we have valid pointers, and room for grow */
2465 a_tty_check_grow(tlp, ((flags & a_BUFMODE) ? (ui32_t)len : 1)
2466 n_MEMORY_DEBUG_ARGSCALL);
2468 /* Handle visual state flags, except in buffer mode */
2469 if(!(flags & a_BUFMODE) && (tlp->tl_vi_flags & a_TTY_VF_ALL_MASK))
2470 if(!a_tty_vi_refresh(tlp)){
2471 rv = -1;
2472 goto jleave;
2475 /* Ready for messing around.
2476 * Normal read(2)? Else buffer mode: speed this one up */
2477 if(!(flags & a_BUFMODE)){
2478 cbufp =
2479 cbuf = cbuf_base;
2480 }else{
2481 assert(tlp->tl_defc.l > 0 && tlp->tl_defc.s != NULL);
2482 assert(tlp->tl_defc.l >= len);
2483 cbufp =
2484 cbuf = tlp->tl_defc.s + (tlp->tl_defc.l - len);
2485 cbufp += len;
2488 /* Read in the next complete multibyte character */
2489 /* C99 */{
2490 # ifdef HAVE_KEY_BINDINGS
2491 struct a_tty_bind_tree *xtbtp;
2492 struct inseq{
2493 struct inseq *last;
2494 struct inseq *next;
2495 struct a_tty_bind_tree *tbtp;
2496 } *isp_head, *isp;
2498 isp_head = isp = NULL;
2499 # endif
2501 for(flags &= a_READ_LOOP_MASK;;){
2502 # ifdef HAVE_KEY_BINDINGS
2503 if(!(flags & a_BUFMODE) && tlp->tl_bind_takeover != '\0'){
2504 wc = tlp->tl_bind_takeover;
2505 tlp->tl_bind_takeover = '\0';
2506 }else
2507 # endif
2509 if(!(flags & a_BUFMODE)){
2510 /* Let me at least once dream of iomon(itor), timer with
2511 * one-shot, enwrapped with key_event and key_sequence_event,
2512 * all driven by an event_loop */
2513 /* TODO v15 Until we have SysV signal handling all through we
2514 * TODO need to temporarily adjust our BSD signal handler with
2515 * TODO a SysV one, here */
2516 n_sighdl_t otstp, ottin, ottou;
2518 otstp = n_signal(SIGTSTP, &n_tty_signal);
2519 ottin = n_signal(SIGTTIN, &n_tty_signal);
2520 ottou = n_signal(SIGTTOU, &n_tty_signal);
2521 # ifdef HAVE_KEY_BINDINGS
2522 flags &= ~a_TIMEOUT_MASK;
2523 if(isp != NULL && (tbtp = isp->tbtp)->tbt_isseq &&
2524 !tbtp->tbt_isseq_trail){
2525 a_tty_term_rawmode_timeout(tlp, TRU1);
2526 flags |= a_TIMEOUT;
2528 # endif
2530 while((rv = read(STDIN_FILENO, cbufp, 1)) < 1){
2531 if(rv == -1){
2532 if(errno == EINTR){
2533 if((tlp->tl_vi_flags & a_TTY_VF_MOD_DIRTY) &&
2534 !a_tty_vi_refresh(tlp))
2535 break;
2536 continue;
2538 break;
2541 # ifdef HAVE_KEY_BINDINGS
2542 /* Timeout expiration */
2543 if(rv == 0){
2544 assert(flags & a_TIMEOUT);
2545 assert(isp != NULL);
2546 a_tty_term_rawmode_timeout(tlp, FAL0);
2548 /* Something "atomic" broke. Maybe the current one can
2549 * also be terminated already, by itself? xxx really? */
2550 if((tbtp = isp->tbtp)->tbt_bind != NULL){
2551 tlp->tl_bind_takeover = wc;
2552 goto jhave_bind;
2555 /* Or, maybe there is a second path without a timeout;
2556 * this should be covered by .tbt_isseq_trail, but then
2557 * again a single-layer implementation cannot "know" */
2558 for(xtbtp = tbtp; (xtbtp = xtbtp->tbt_sibling) != NULL;)
2559 if(xtbtp->tbt_char == tbtp->tbt_char){
2560 assert(!xtbtp->tbt_isseq);
2561 break;
2563 /* Lay down on read(2)? */
2564 if(xtbtp != NULL)
2565 continue;
2566 goto jtake_over;
2568 # endif /* HAVE_KEY_BINDINGS */
2571 # ifdef HAVE_KEY_BINDINGS
2572 if(flags & a_TIMEOUT)
2573 a_tty_term_rawmode_timeout(tlp, FAL0);
2574 # endif
2575 safe_signal(SIGTSTP, otstp);
2576 safe_signal(SIGTTIN, ottin);
2577 safe_signal(SIGTTOU, ottou);
2578 if(rv < 0)
2579 goto jleave;
2581 ++cbufp;
2584 rv = (ssize_t)mbrtowc(&wc, cbuf, PTR2SIZE(cbufp - cbuf), &ps[0]);
2585 if(rv <= 0){
2586 /* Any error during buffer mode can only result in a hard
2587 * reset; Otherwise, if it's a hard error, or if too many
2588 * redundant shift sequences overflow our buffer: perform
2589 * hard reset */
2590 if((flags & a_BUFMODE) || rv == -1 ||
2591 sizeof cbuf_base == PTR2SIZE(cbufp - cbuf)){
2592 a_tty_fun(tlp, a_TTY_BIND_FUN_FULLRESET, &len);
2593 goto jrestart;
2595 /* Otherwise, due to the way we deal with the buffer, we need
2596 * to restore the mbstate_t from before this conversion */
2597 ps[0] = ps[1];
2598 continue;
2600 cbufp = cbuf;
2601 ps[1] = ps[0];
2604 /* Normal read(2)ing is subject to detection of key-bindings */
2605 # ifdef HAVE_KEY_BINDINGS
2606 if(!(flags & a_BUFMODE)){
2607 /* Check for special bypass functions before we try to embed
2608 * this character into the tree */
2609 if(n_uasciichar(wc)){
2610 char c;
2611 char const *cp;
2613 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_prompt_char)[0];
2614 *cp != '\0'; ++cp){
2615 if(c == *cp){
2616 wc = a_tty_vinuni(tlp);
2617 break;
2620 if(wc == '\0'){
2621 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2622 goto jinput_loop;
2625 if(n_uasciichar(wc))
2626 flags |= a_MAYBEFUN;
2627 else
2628 flags &= ~a_MAYBEFUN;
2630 /* Search for this character in the bind tree */
2631 tbtp = (isp != NULL) ? isp->tbtp->tbt_childs
2632 : (*tlp->tl_bind_tree_hmap)[wc % HSHSIZE];
2633 for(; tbtp != NULL; tbtp = tbtp->tbt_sibling){
2634 if(tbtp->tbt_char == wc){
2635 struct inseq *nisp;
2637 /* If this one cannot continue we're likely finished! */
2638 if(tbtp->tbt_childs == NULL){
2639 assert(tbtp->tbt_bind != NULL);
2640 tbf = tbtp->tbt_bind->tbc_flags;
2641 goto jmle_fun;
2644 /* This needs to read more characters */
2645 nisp = salloc(sizeof *nisp);
2646 if((nisp->last = isp) == NULL)
2647 isp_head = nisp;
2648 else
2649 isp->next = nisp;
2650 nisp->next = NULL;
2651 nisp->tbtp = tbtp;
2652 isp = nisp;
2653 flags &= ~a_WAS_HERE;
2654 break;
2657 if(tbtp != NULL)
2658 continue;
2660 /* Was there a binding active, but couldn't be continued? */
2661 if(isp != NULL){
2662 /* A binding had a timeout, it didn't expire, but we saw
2663 * something non-expected. Something "atomic" broke.
2664 * Maybe there is a second path without a timeout, that
2665 * continues like we've seen it. I.e., it may just have been
2666 * the user, typing two fast. We definitely want to allow
2667 * bindings like \e,d etc. to succeed: users are so used to
2668 * them that a timeout cannot be the mechanism to catch up!
2669 * A single-layer implementation cannot "know" */
2670 if((tbtp = isp->tbtp)->tbt_isseq && (isp->last == NULL ||
2671 !(xtbtp = isp->last->tbtp)->tbt_isseq ||
2672 xtbtp->tbt_isseq_trail)){
2673 for(xtbtp = (tbtp = isp->tbtp);
2674 (xtbtp = xtbtp->tbt_sibling) != NULL;)
2675 if(xtbtp->tbt_char == tbtp->tbt_char){
2676 assert(!xtbtp->tbt_isseq);
2677 break;
2679 if(xtbtp != NULL){
2680 isp->tbtp = xtbtp;
2681 tlp->tl_bind_takeover = wc;
2682 continue;
2686 /* Check for CANCEL shortcut now */
2687 if(flags & a_MAYBEFUN){
2688 char c;
2689 char const *cp;
2691 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_cancel)[0];
2692 *cp != '\0'; ++cp)
2693 if(c == *cp){
2694 tbf = a_TTY_BIND_FUN_INTERNAL |a_TTY_BIND_FUN_CANCEL;
2695 goto jmle_fun;
2699 /* So: maybe the current sequence can be terminated here? */
2700 if((tbtp = isp->tbtp)->tbt_bind != NULL){
2701 jhave_bind:
2702 tbf = tbtp->tbt_bind->tbc_flags;
2703 jmle_fun:
2704 if(tbf & a_TTY_BIND_FUN_INTERNAL){
2705 switch(a_tty_fun(tlp, tbf, &len)){
2706 case a_TTY_FUN_STATUS_OK:
2707 goto jinput_loop;
2708 case a_TTY_FUN_STATUS_COMMIT:
2709 goto jdone;
2710 case a_TTY_FUN_STATUS_RESTART:
2711 goto jrestart;
2712 case a_TTY_FUN_STATUS_END:
2713 goto jleave;
2715 assert(0);
2716 }else if(tbtp->tbt_bind->tbc_flags & a_TTY_BIND_NOCOMMIT){
2717 struct a_tty_bind_ctx *tbcp;
2719 tbcp = tbtp->tbt_bind;
2720 memcpy(tlp->tl_defc.s = salloc(
2721 (tlp->tl_defc.l = len = tbcp->tbc_exp_len) +1),
2722 tbcp->tbc_exp, tbcp->tbc_exp_len +1);
2723 goto jrestart;
2724 }else{
2725 tlp->tl_reenter_after_cmd = tbtp->tbt_bind->tbc_exp;
2726 goto jdone;
2731 /* Otherwise take over all chars "as is" */
2732 jtake_over:
2733 for(; isp_head != NULL; isp_head = isp_head->next)
2734 if(a_tty_kother(tlp, isp_head->tbtp->tbt_char)){
2735 /* FIXME */
2737 /* And the current one too */
2738 goto jkother;
2740 # endif /* HAVE_KEY_BINDINGS */
2742 if((flags & a_BUFMODE) && (len -= (size_t)rv) == 0){
2743 /* Buffer mode completed */
2744 tlp->tl_defc.s = NULL;
2745 tlp->tl_defc.l = 0;
2746 flags &= ~a_BUFMODE;
2748 break;
2751 # ifndef HAVE_KEY_BINDINGS
2752 /* Don't interpret control bytes during buffer mode.
2753 * Otherwise, if it's a control byte check whether it is a MLE
2754 * function. Remarks: initially a complete duplicate to be able to
2755 * switch(), later converted to simply iterate over (an #ifdef'd
2756 * subset of) the MLE default_tuple table in order to have "a SPOF" */
2757 if(cbuf == cbuf_base && n_uasciichar(wc) && cntrlchar((char)wc)){
2758 struct a_tty_bind_default_tuple const *tbdtp;
2759 char c;
2761 for(c = (char)wc ^ 0x40, tbdtp = a_tty_bind_default_tuples;
2762 PTRCMP(tbdtp, <, &a_tty_bind_default_tuples[
2763 n_NELEM(a_tty_bind_default_tuples)]);
2764 ++tbdtp){
2765 /* Assert default_tuple table is properly subset'ed */
2766 assert(tbdtp->tbdt_iskey);
2767 if(tbdtp->tbdt_ckey == c){
2768 if(tbdtp->tbdt_exp[0] == '\0'){
2769 enum a_tty_bind_flags tbf;
2771 tbf = a_TTY_BIND_FUN_EXPAND((ui8_t)tbdtp->tbdt_exp[1]);
2772 switch(a_tty_fun(tlp, tbf, &len)){
2773 case a_TTY_FUN_STATUS_OK:
2774 goto jinput_loop;
2775 case a_TTY_FUN_STATUS_COMMIT:
2776 goto jdone;
2777 case a_TTY_FUN_STATUS_RESTART:
2778 goto jrestart;
2779 case a_TTY_FUN_STATUS_END:
2780 goto jleave;
2782 assert(0);
2783 }else{
2784 tlp->tl_reenter_after_cmd = tbdtp->tbdt_exp;
2785 goto jdone;
2790 # endif /* !HAVE_KEY_BINDINGS */
2792 # ifdef HAVE_KEY_BINDINGS
2793 jkother:
2794 # endif
2795 if(a_tty_kother(tlp, wc)){
2796 /* Don't clear the history during buffer mode.. */
2797 # ifdef HAVE_HISTORY
2798 if(!(flags & a_BUFMODE) && cbuf == cbuf_base)
2799 tlp->tl_hist = NULL;
2800 # endif
2805 /* We have a completed input line, convert the struct cell data to its
2806 * plain character equivalent */
2807 jdone:
2808 rv = a_tty_cell2dat(tlp);
2809 jleave:
2810 putchar('\n');
2811 fflush(stdout);
2812 NYD_LEAVE;
2813 return rv;
2816 # ifdef HAVE_KEY_BINDINGS
2817 static enum n_lexinput_flags
2818 a_tty_bind_ctx_find(char const *name){
2819 enum n_lexinput_flags rv;
2820 struct a_tty_bind_ctx_map const *tbcmp;
2821 NYD2_ENTER;
2823 tbcmp = a_tty_bind_ctx_maps;
2824 do if(!asccasecmp(tbcmp->tbcm_name, name)){
2825 rv = tbcmp->tbcm_ctx;
2826 goto jleave;
2827 }while(PTRCMP(++tbcmp, <,
2828 &a_tty_bind_ctx_maps[n_NELEM(a_tty_bind_ctx_maps)]));
2830 rv = (enum n_lexinput_flags)-1;
2831 jleave:
2832 NYD2_LEAVE;
2833 return rv;
2836 static bool_t
2837 a_tty_bind_create(struct a_tty_bind_parse_ctx *tbpcp, bool_t replace){
2838 struct a_tty_bind_ctx *tbcp;
2839 bool_t rv;
2840 NYD2_ENTER;
2842 rv = FAL0;
2844 if(!a_tty_bind_parse(TRU1, tbpcp))
2845 goto jleave;
2847 /* Since we use a single buffer for it all, need to replace as such */
2848 if(tbpcp->tbpc_tbcp != NULL){
2849 if(!replace)
2850 goto jleave;
2851 a_tty_bind_del(tbpcp);
2852 }else if(a_tty.tg_bind_cnt == UI32_MAX){
2853 n_err(_("`bind': maximum number of bindings already established\n"));
2854 goto jleave;
2857 /* C99 */{
2858 size_t i, j;
2860 tbcp = smalloc(sizeof(*tbcp) -
2861 n_VFIELD_SIZEOF(struct a_tty_bind_ctx, tbc__buf) +
2862 tbpcp->tbpc_seq_len + tbpcp->tbpc_exp.l +
2863 n_MAX(sizeof(si32_t), sizeof(wc_t)) + tbpcp->tbpc_cnv_len +3);
2864 if(tbpcp->tbpc_ltbcp != NULL){
2865 tbcp->tbc_next = tbpcp->tbpc_ltbcp->tbc_next;
2866 tbpcp->tbpc_ltbcp->tbc_next = tbcp;
2867 }else{
2868 enum n_lexinput_flags lif = tbpcp->tbpc_flags & n__LEXINPUT_CTX_MASK;
2870 tbcp->tbc_next = a_tty.tg_bind[lif];
2871 a_tty.tg_bind[lif] = tbcp;
2873 memcpy(tbcp->tbc_seq = &tbcp->tbc__buf[0],
2874 tbpcp->tbpc_seq, i = (tbcp->tbc_seq_len = tbpcp->tbpc_seq_len) +1);
2875 memcpy(tbcp->tbc_exp = &tbcp->tbc__buf[i],
2876 tbpcp->tbpc_exp.s, j = (tbcp->tbc_exp_len = tbpcp->tbpc_exp.l) +1);
2877 i += j;
2878 i = (i + tbpcp->tbpc_cnv_align_mask) & ~tbpcp->tbpc_cnv_align_mask;
2879 memcpy(tbcp->tbc_cnv = &tbcp->tbc__buf[i],
2880 tbpcp->tbpc_cnv, (tbcp->tbc_cnv_len = tbpcp->tbpc_cnv_len) +1);
2881 tbcp->tbc_flags = tbpcp->tbpc_flags;
2884 /* Directly resolve any termcap(5) symbol if we are already setup */
2885 if((pstate & PS_STARTED) &&
2886 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
2887 a_TTY_BIND_RESOLVE)
2888 a_tty_bind_resolve(tbcp);
2890 ++a_tty.tg_bind_cnt;
2891 /* If this binding is usable invalidate the key input lookup trees */
2892 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
2893 a_tty.tg_bind_isdirty = TRU1;
2894 rv = TRU1;
2895 jleave:
2896 NYD2_LEAVE;
2897 return rv;
2900 static bool_t
2901 a_tty_bind_parse(bool_t isbindcmd, struct a_tty_bind_parse_ctx *tbpcp){
2902 enum{a_TRUE_RV = a_TTY__BIND_LAST<<1};
2904 struct n_visual_info_ctx vic;
2905 struct str shin_save, shin;
2906 struct n_string shou, *shoup;
2907 size_t i;
2908 struct kse{
2909 struct kse *next;
2910 char *seq_dat;
2911 wc_t *cnv_dat;
2912 ui32_t seq_len;
2913 ui32_t cnv_len; /* High bit set if a termap to be resolved */
2914 ui32_t calc_cnv_len; /* Ditto, but aligned etc. */
2915 ui8_t kse__dummy[4];
2916 } *head, *tail;
2917 ui32_t f;
2918 NYD2_ENTER;
2919 n_LCTA(UICMP(64, a_TRUE_RV, <, UI32_MAX),
2920 "Flag bits excess storage datatype");
2922 f = n_LEXINPUT_NONE;
2923 shoup = n_string_creat_auto(&shou);
2924 head = tail = NULL;
2926 /* Parse the key-sequence */
2927 for(shin.s = n_UNCONST(tbpcp->tbpc_in_seq), shin.l = UIZ_MAX;;){
2928 struct kse *ep;
2929 enum n_shexp_state shs;
2931 shin_save = shin;
2932 shs = n_shexp_parse_token(shoup, &shin,
2933 n_SHEXP_PARSE_TRUNC | n_SHEXP_PARSE_TRIMSPACE |
2934 n_SHEXP_PARSE_IGNORE_EMPTY | n_SHEXP_PARSE_IFS_IS_COMMA);
2935 if(shs & n_SHEXP_STATE_ERR_UNICODE){
2936 f |= a_TTY_BIND_DEFUNCT;
2937 if(isbindcmd && (options & OPT_D_V))
2938 n_err(_("`%s': \\uNICODE not available in locale: %s\n"),
2939 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
2941 if((shs & n_SHEXP_STATE_ERR_MASK) & ~n_SHEXP_STATE_ERR_UNICODE){
2942 n_err(_("`%s': failed to parse key-sequence: %s\n"),
2943 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
2944 goto jleave;
2946 if((shs & (n_SHEXP_STATE_OUTPUT | n_SHEXP_STATE_STOP)) ==
2947 n_SHEXP_STATE_STOP)
2948 break;
2950 ep = salloc(sizeof *ep);
2951 if(head == NULL)
2952 head = ep;
2953 else
2954 tail->next = ep;
2955 tail = ep;
2956 ep->next = NULL;
2957 if(!(shs & n_SHEXP_STATE_ERR_UNICODE)){
2958 i = strlen(ep->seq_dat = n_shexp_quote_cp(n_string_cp(shoup), TRU1));
2959 if(i >= SI32_MAX - 1)
2960 goto jelen;
2961 ep->seq_len = (ui32_t)i;
2962 }else{
2963 /* Otherwise use the original buffer, _we_ can only quote it the wrong
2964 * way (e.g., an initial $'\u3a' becomes '\u3a'), _then_ */
2965 if((i = shin_save.l - shin.l) >= SI32_MAX - 1)
2966 goto jelen;
2967 ep->seq_len = (ui32_t)i;
2968 ep->seq_dat = savestrbuf(shin_save.s, i);
2971 memset(&vic, 0, sizeof vic);
2972 vic.vic_inlen = shoup->s_len;
2973 vic.vic_indat = shoup->s_dat;
2974 if(!n_visual_info(&vic,
2975 n_VISUAL_INFO_WOUT_CREATE | n_VISUAL_INFO_WOUT_SALLOC)){
2976 n_err(_("`%s': key-sequence seems to contain invalid "
2977 "characters: %s: %s\n"),
2978 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
2979 f |= a_TTY_BIND_DEFUNCT;
2980 goto jleave;
2981 }else if(vic.vic_woulen == 0 ||
2982 vic.vic_woulen >= (SI32_MAX - 2) / sizeof(wc_t)){
2983 jelen:
2984 n_err(_("`%s': length of key-sequence unsupported: %s: %s\n"),
2985 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
2986 f |= a_TTY_BIND_DEFUNCT;
2987 goto jleave;
2989 ep->cnv_dat = vic.vic_woudat;
2990 ep->cnv_len = (ui32_t)vic.vic_woulen;
2992 /* A termcap(5)/terminfo(5) identifier? */
2993 if(ep->cnv_len > 1 && ep->cnv_dat[0] == ':'){
2994 i = --ep->cnv_len, ++ep->cnv_dat;
2995 # ifndef HAVE_TERMCAP
2996 if(options & OPT_D_V)
2997 n_err(_("`%s': no termcap(5)/terminfo(5) support: %s: %s\n"),
2998 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
2999 f |= a_TTY_BIND_DEFUNCT;
3000 # endif
3001 if(i > a_TTY_BIND_CAPNAME_MAX){
3002 n_err(_("`%s': termcap(5)/terminfo(5) name too long: %s: %s\n"),
3003 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3004 f |= a_TTY_BIND_DEFUNCT;
3006 while(i > 0)
3007 /* (We store it as char[]) */
3008 if((ui32_t)ep->cnv_dat[--i] & ~0x7Fu){
3009 n_err(_("`%s': invalid termcap(5)/terminfo(5) name content: "
3010 "%s: %s\n"),
3011 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3012 f |= a_TTY_BIND_DEFUNCT;
3013 break;
3015 ep->cnv_len |= SI32_MIN; /* Needs resolve */
3016 f |= a_TTY_BIND_RESOLVE;
3019 if(shs & n_SHEXP_STATE_STOP)
3020 break;
3023 if(head == NULL){
3024 jeempty:
3025 n_err(_("`%s': effectively empty key-sequence: %s\n"),
3026 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3027 goto jleave;
3030 if(isbindcmd) /* (Or always, just "1st time init") */
3031 tbpcp->tbpc_cnv_align_mask = n_MAX(sizeof(si32_t), sizeof(wc_t)) - 1;
3033 /* C99 */{
3034 struct a_tty_bind_ctx *ltbcp, *tbcp;
3035 char *cpbase, *cp, *cnv;
3036 size_t sl, cl;
3038 /* Unite the parsed sequence(s) into single string representations */
3039 for(sl = cl = 0, tail = head; tail != NULL; tail = tail->next){
3040 sl += tail->seq_len + 1;
3042 if(!isbindcmd)
3043 continue;
3045 /* Preserve room for terminal capabilities to be resolved.
3046 * Above we have ensured the buffer will fit in these calculations */
3047 if((i = tail->cnv_len) & SI32_MIN){
3048 /* For now
3049 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[]+NUL;}
3050 * later
3051 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3052 n_LCTAV(n_ISPOW2(a_TTY_BIND_CAPEXP_ROUNDUP));
3053 n_LCTA(a_TTY_BIND_CAPEXP_ROUNDUP >= sizeof(wc_t),
3054 "Aligning on this constant doesn't properly align wc_t");
3055 i &= SI32_MAX;
3056 i *= sizeof(wc_t);
3057 i += sizeof(si32_t);
3058 if(i < a_TTY_BIND_CAPEXP_ROUNDUP)
3059 i = (i + (a_TTY_BIND_CAPEXP_ROUNDUP - 1)) &
3060 ~(a_TTY_BIND_CAPEXP_ROUNDUP - 1);
3061 }else
3062 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3063 i *= sizeof(wc_t);
3064 i += sizeof(si32_t) + sizeof(wc_t); /* (buf_len_iscap, NUL) */
3065 cl += i;
3066 if(tail->cnv_len & SI32_MIN){
3067 tail->cnv_len &= SI32_MAX;
3068 i |= SI32_MIN;
3070 tail->calc_cnv_len = (ui32_t)i;
3072 --sl;
3074 tbpcp->tbpc_seq_len = sl;
3075 tbpcp->tbpc_cnv_len = cl;
3076 /* C99 */{
3077 size_t j;
3079 j = i = sl + 1; /* Room for comma separator */
3080 if(isbindcmd){
3081 i = (i + tbpcp->tbpc_cnv_align_mask) & ~tbpcp->tbpc_cnv_align_mask;
3082 j = i;
3083 i += cl;
3085 tbpcp->tbpc_seq = cp = cpbase = salloc(i);
3086 tbpcp->tbpc_cnv = cnv = &cpbase[j];
3089 for(tail = head; tail != NULL; tail = tail->next){
3090 memcpy(cp, tail->seq_dat, tail->seq_len);
3091 cp += tail->seq_len;
3092 *cp++ = ',';
3094 if(isbindcmd){
3095 char * const save_cnv = cnv;
3097 n_UNALIGN(si32_t*,cnv)[0] = (si32_t)(i = tail->calc_cnv_len);
3098 cnv += sizeof(si32_t);
3099 if(i & SI32_MIN){
3100 /* For now
3101 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];}
3102 * later
3103 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[];} */
3104 n_UNALIGN(si32_t*,cnv)[0] = tail->cnv_len;
3105 cnv += sizeof(si32_t);
3107 i = tail->cnv_len * sizeof(wc_t);
3108 memcpy(cnv, tail->cnv_dat, i);
3109 cnv += i;
3110 *n_UNALIGN(wc_t*,cnv) = '\0';
3112 cnv = save_cnv + (tail->calc_cnv_len & SI32_MAX);
3115 *--cp = '\0';
3117 /* Search for a yet existing identical mapping */
3118 for(ltbcp = NULL, tbcp = a_tty.tg_bind[tbpcp->tbpc_flags]; tbcp != NULL;
3119 ltbcp = tbcp, tbcp = tbcp->tbc_next)
3120 if(tbcp->tbc_seq_len == sl && !memcmp(tbcp->tbc_seq, cpbase, sl)){
3121 tbpcp->tbpc_tbcp = tbcp;
3122 break;
3124 tbpcp->tbpc_ltbcp = ltbcp;
3125 tbpcp->tbpc_flags |= (f & a_TTY__BIND_MASK);
3128 /* Create single string expansion if so desired */
3129 if(isbindcmd){
3130 char *exp;
3132 exp = tbpcp->tbpc_exp.s;
3134 i = tbpcp->tbpc_exp.l;
3135 if(i > 0 && exp[i - 1] == '@'){
3136 while(--i > 0){
3137 if(!blankspacechar(exp[i - 1]))
3138 break;
3140 if(i == 0)
3141 goto jeempty;
3143 exp[tbpcp->tbpc_exp.l = i] = '\0';
3144 tbpcp->tbpc_flags |= a_TTY_BIND_NOCOMMIT;
3147 /* It may map to an internal MLE command! */
3148 for(i = 0; i < n_NELEM(a_tty_bind_fun_names); ++i)
3149 if(!asccasecmp(exp, a_tty_bind_fun_names[i])){
3150 tbpcp->tbpc_flags |= a_TTY_BIND_FUN_EXPAND(i) |
3151 a_TTY_BIND_FUN_INTERNAL |
3152 (head->next == NULL ? a_TTY_BIND_MLE1CNTRL : 0);
3153 if((options & OPT_D_V) && (tbpcp->tbpc_flags & a_TTY_BIND_NOCOMMIT))
3154 n_err(_("`%s': MLE commands can't be made editable via @: %s\n"),
3155 tbpcp->tbpc_cmd, exp);
3156 tbpcp->tbpc_flags &= ~a_TTY_BIND_NOCOMMIT;
3157 break;
3161 f |= a_TRUE_RV; /* TODO because we only now true and false; DEFUNCT.. */
3162 jleave:
3163 n_string_gut(shoup);
3164 NYD2_LEAVE;
3165 return (f & a_TRUE_RV) != 0;
3168 static void
3169 a_tty_bind_resolve(struct a_tty_bind_ctx *tbcp){
3170 char capname[a_TTY_BIND_CAPNAME_MAX +1];
3171 struct n_termcap_value tv;
3172 size_t len;
3173 bool_t isfirst; /* TODO For now: first char must be control! */
3174 char *cp, *next;
3175 NYD2_ENTER;
3177 n_UNINIT(next, NULL);
3178 for(cp = tbcp->tbc_cnv, isfirst = TRU1, len = tbcp->tbc_cnv_len;
3179 len > 0; isfirst = FAL0, cp = next){
3180 /* C99 */{
3181 si32_t i, j;
3183 i = n_UNALIGN(si32_t*,cp)[0];
3184 j = i & SI32_MAX;
3185 next = &cp[j];
3186 len -= j;
3187 if(i == j)
3188 continue;
3190 /* struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];} */
3191 cp += sizeof(si32_t);
3192 i = n_UNALIGN(si32_t*,cp)[0];
3193 cp += sizeof(si32_t);
3194 for(j = 0; j < i; ++j)
3195 capname[j] = n_UNALIGN(wc_t*,cp)[j];
3196 capname[j] = '\0';
3199 /* Use generic lookup mechanism if not a known query */
3200 /* C99 */{
3201 si32_t tq;
3203 tq = n_termcap_query_for_name(capname, n_TERMCAP_CAPTYPE_STRING);
3204 if(tq == -1){
3205 tv.tv_data.tvd_string = capname;
3206 tq = n__TERMCAP_QUERY_MAX;
3209 if(tq < 0 || !n_termcap_query(tq, &tv)){
3210 if(options & OPT_D_V)
3211 n_err(_("`bind': unknown or unsupported capability: %s: %s\n"),
3212 capname, tbcp->tbc_seq);
3213 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3214 break;
3218 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3219 /* C99 */{
3220 size_t i;
3222 i = strlen(tv.tv_data.tvd_string);
3223 if(/*i > SI32_MAX ||*/ i >= PTR2SIZE(next - cp)){
3224 if(options & OPT_D_V)
3225 n_err(_("`bind': capability expansion too long: %s: %s\n"),
3226 capname, tbcp->tbc_seq);
3227 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3228 break;
3229 }else if(i == 0){
3230 if(options & OPT_D_V)
3231 n_err(_("`bind': empty capability expansion: %s: %s\n"),
3232 capname, tbcp->tbc_seq);
3233 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3234 break;
3235 }else if(isfirst && !cntrlchar(*tv.tv_data.tvd_string)){
3236 if(options & OPT_D_V)
3237 n_err(_("`bind': capability expansion doesn't start with "
3238 "control: %s: %s\n"), capname, tbcp->tbc_seq);
3239 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3240 break;
3242 n_UNALIGN(si32_t*,cp)[-1] = (si32_t)i;
3243 memcpy(cp, tv.tv_data.tvd_string, i);
3244 cp[i] = '\0';
3247 NYD2_LEAVE;
3250 static void
3251 a_tty_bind_del(struct a_tty_bind_parse_ctx *tbpcp){
3252 struct a_tty_bind_ctx *ltbcp, *tbcp;
3253 NYD2_ENTER;
3255 tbcp = tbpcp->tbpc_tbcp;
3257 if((ltbcp = tbpcp->tbpc_ltbcp) != NULL)
3258 ltbcp->tbc_next = tbcp->tbc_next;
3259 else
3260 a_tty.tg_bind[tbpcp->tbpc_flags] = tbcp->tbc_next;
3261 free(tbcp);
3263 --a_tty.tg_bind_cnt;
3264 a_tty.tg_bind_isdirty = TRU1;
3265 NYD2_LEAVE;
3268 static void
3269 a_tty_bind_tree_build(void){
3270 size_t i;
3271 NYD2_ENTER;
3273 for(i = 0; i < n__LEXINPUT_CTX_MAX; ++i){
3274 struct a_tty_bind_ctx *tbcp;
3275 n_LCTAV(n_LEXINPUT_CTX_BASE == 0);
3277 /* Somewhat wasteful, but easier to handle: simply clone the entire
3278 * primary key onto the secondary one, then only modify it */
3279 for(tbcp = a_tty.tg_bind[n_LEXINPUT_CTX_BASE]; tbcp != NULL;
3280 tbcp = tbcp->tbc_next)
3281 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3282 a_tty__bind_tree_add(n_LEXINPUT_CTX_BASE, &a_tty.tg_bind_tree[i][0],
3283 tbcp);
3285 if(i != n_LEXINPUT_CTX_BASE)
3286 for(tbcp = a_tty.tg_bind[i]; tbcp != NULL; tbcp = tbcp->tbc_next)
3287 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3288 a_tty__bind_tree_add(i, &a_tty.tg_bind_tree[i][0], tbcp);
3291 a_tty.tg_bind_isbuild = TRU1;
3292 NYD2_LEAVE;
3295 static void
3296 a_tty_bind_tree_teardown(void){
3297 size_t i, j;
3298 NYD2_ENTER;
3300 memset(&a_tty.tg_bind_shcut_cancel[0], 0,
3301 sizeof(a_tty.tg_bind_shcut_cancel));
3302 memset(&a_tty.tg_bind_shcut_prompt_char[0], 0,
3303 sizeof(a_tty.tg_bind_shcut_prompt_char));
3305 for(i = 0; i < n__LEXINPUT_CTX_MAX; ++i)
3306 for(j = 0; j < HSHSIZE; ++j)
3307 a_tty__bind_tree_free(a_tty.tg_bind_tree[i][j]);
3308 memset(&a_tty.tg_bind_tree[0], 0, sizeof(a_tty.tg_bind_tree));
3310 a_tty.tg_bind_isdirty = a_tty.tg_bind_isbuild = FAL0;
3311 NYD2_LEAVE;
3314 static void
3315 a_tty__bind_tree_add(ui32_t hmap_idx, struct a_tty_bind_tree *store[HSHSIZE],
3316 struct a_tty_bind_ctx *tbcp){
3317 ui32_t cnvlen;
3318 char const *cnvdat;
3319 struct a_tty_bind_tree *ntbtp;
3320 NYD2_ENTER;
3321 n_UNUSED(hmap_idx);
3323 ntbtp = NULL;
3325 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len; cnvlen > 0;){
3326 union {wchar_t const *wp; char const *cp;} u;
3327 si32_t entlen;
3329 /* {si32_t buf_len_iscap;} */
3330 entlen = *n_UNALIGN(si32_t const*,cnvdat);
3332 if(entlen & SI32_MIN){
3333 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;}
3334 * Note that empty capabilities result in DEFUNCT */
3335 for(u.cp = (char const*)&n_UNALIGN(si32_t const*,cnvdat)[2];
3336 *u.cp != '\0'; ++u.cp)
3337 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.cp, TRU1);
3338 assert(ntbtp != NULL);
3339 ntbtp->tbt_isseq_trail = TRU1;
3340 entlen &= SI32_MAX;
3341 }else{
3342 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3343 bool_t isseq;
3345 u.wp = (wchar_t const*)&n_UNALIGN(si32_t const*,cnvdat)[1];
3347 /* May be a special shortcut function? */
3348 if(ntbtp == NULL && (tbcp->tbc_flags & a_TTY_BIND_MLE1CNTRL)){
3349 char *cp;
3350 ui32_t ctx, fun;
3352 ctx = tbcp->tbc_flags & n__LEXINPUT_CTX_MAX;
3353 fun = tbcp->tbc_flags & a_TTY__BIND_FUN_MASK;
3355 if(fun == a_TTY_BIND_FUN_CANCEL){
3356 for(cp = &a_tty.tg_bind_shcut_cancel[ctx][0];
3357 PTRCMP(cp, <, &a_tty.tg_bind_shcut_cancel[ctx]
3358 [n_NELEM(a_tty.tg_bind_shcut_cancel[ctx]) - 1]); ++cp)
3359 if(*cp == '\0'){
3360 *cp = (char)*u.wp;
3361 break;
3363 }else if(fun == a_TTY_BIND_FUN_PROMPT_CHAR){
3364 for(cp = &a_tty.tg_bind_shcut_prompt_char[ctx][0];
3365 PTRCMP(cp, <, &a_tty.tg_bind_shcut_prompt_char[ctx]
3366 [n_NELEM(a_tty.tg_bind_shcut_prompt_char[ctx]) - 1]);
3367 ++cp)
3368 if(*cp == '\0'){
3369 *cp = (char)*u.wp;
3370 break;
3375 isseq = (u.wp[1] != '\0');
3376 for(; *u.wp != '\0'; ++u.wp)
3377 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.wp, isseq);
3378 if(isseq)
3379 ntbtp->tbt_isseq_trail = TRU1;
3382 cnvlen -= entlen;
3383 cnvdat += entlen;
3386 /* Should have been rendered defunctional at first instead */
3387 assert(ntbtp != NULL);
3388 ntbtp->tbt_bind = tbcp;
3389 NYD2_LEAVE;
3392 static struct a_tty_bind_tree *
3393 a_tty__bind_tree_add_wc(struct a_tty_bind_tree **treep,
3394 struct a_tty_bind_tree *parentp, wchar_t wc, bool_t isseq){
3395 struct a_tty_bind_tree *tbtp, *xtbtp;
3396 NYD2_ENTER;
3398 if(parentp == NULL){
3399 treep += wc % HSHSIZE;
3401 /* Having no parent also means that the tree slot is possibly empty */
3402 for(tbtp = *treep; tbtp != NULL;
3403 parentp = tbtp, tbtp = tbtp->tbt_sibling){
3404 if(tbtp->tbt_char != wc)
3405 continue;
3406 if(tbtp->tbt_isseq == isseq)
3407 goto jleave;
3408 /* isseq MUST be linked before !isseq, so record this "parent"
3409 * sibling, but continue searching for now */
3410 if(!isseq)
3411 parentp = tbtp;
3412 /* Otherwise it is impossible that we'll find what we look for */
3413 else{
3414 #ifdef HAVE_DEBUG
3415 while((tbtp = tbtp->tbt_sibling) != NULL)
3416 assert(tbtp->tbt_char != wc);
3417 #endif
3418 break;
3422 tbtp = smalloc(sizeof *tbtp);
3423 memset(tbtp, 0, sizeof *tbtp);
3424 tbtp->tbt_char = wc;
3425 tbtp->tbt_isseq = isseq;
3427 if(parentp == NULL){
3428 tbtp->tbt_sibling = *treep;
3429 *treep = tbtp;
3430 }else{
3431 tbtp->tbt_sibling = parentp->tbt_sibling;
3432 parentp->tbt_sibling = tbtp;
3434 }else{
3435 if((tbtp = *(treep = &parentp->tbt_childs)) != NULL){
3436 for(;; tbtp = xtbtp){
3437 if(tbtp->tbt_char == wc){
3438 if(tbtp->tbt_isseq == isseq)
3439 goto jleave;
3440 /* isseq MUST be linked before, so it is impossible that we'll
3441 * find what we look for */
3442 if(isseq){
3443 #ifdef HAVE_DEBUG
3444 while((tbtp = tbtp->tbt_sibling) != NULL)
3445 assert(tbtp->tbt_char != wc);
3446 #endif
3447 tbtp = NULL;
3448 break;
3452 if((xtbtp = tbtp->tbt_sibling) == NULL){
3453 treep = &tbtp->tbt_sibling;
3454 break;
3459 xtbtp = smalloc(sizeof *xtbtp);
3460 memset(xtbtp, 0, sizeof *xtbtp);
3461 xtbtp->tbt_parent = parentp;
3462 xtbtp->tbt_char = wc;
3463 xtbtp->tbt_isseq = isseq;
3464 tbtp = xtbtp;
3465 *treep = tbtp;
3467 jleave:
3468 NYD2_LEAVE;
3469 return tbtp;
3472 static void
3473 a_tty__bind_tree_free(struct a_tty_bind_tree *tbtp){
3474 NYD2_ENTER;
3475 while(tbtp != NULL){
3476 struct a_tty_bind_tree *tmp;
3478 if((tmp = tbtp->tbt_childs) != NULL)
3479 a_tty__bind_tree_free(tmp);
3481 tmp = tbtp->tbt_sibling;
3482 free(tbtp);
3483 tbtp = tmp;
3485 NYD2_LEAVE;
3487 # endif /* HAVE_KEY_BINDINGS */
3489 FL void
3490 n_tty_init(void){
3491 NYD_ENTER;
3493 if(ok_blook(line_editor_disable))
3494 goto jleave;
3496 /* Load the history file */
3497 # ifdef HAVE_HISTORY
3498 do/* for break */{
3499 long hs;
3500 char const *v;
3501 char *lbuf;
3502 FILE *f;
3503 size_t lsize, cnt, llen;
3505 a_TTY_HISTSIZE(hs);
3506 a_tty.tg_hist_size = 0;
3507 a_tty.tg_hist_size_max = (size_t)hs;
3508 if(hs == 0)
3509 break;
3511 a_TTY_HISTFILE(v);
3512 if(v == NULL)
3513 break;
3515 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
3516 f = fopen(v, "r"); /* TODO HISTFILE LOAD: use linebuf pool */
3517 if(f == NULL)
3518 goto jhist_done;
3519 (void)n_file_lock(fileno(f), FLT_READ, 0,0, UIZ_MAX);
3521 assert(!(pstate & PS_ROOT));
3522 pstate |= PS_ROOT; /* Allow calling addhist() */
3523 lbuf = NULL;
3524 lsize = 0;
3525 cnt = (size_t)fsize(f);
3526 while(fgetline(&lbuf, &lsize, &cnt, &llen, f, FAL0) != NULL){
3527 if(llen > 0 && lbuf[llen - 1] == '\n')
3528 lbuf[--llen] = '\0';
3529 if(llen == 0 || lbuf[0] == '#') /* xxx comments? noone! */
3530 continue;
3531 else{
3532 bool_t isgabby;
3534 isgabby = (lbuf[0] == '*');
3535 n_tty_addhist(lbuf + isgabby, isgabby);
3538 if(lbuf != NULL)
3539 free(lbuf);
3540 pstate &= ~PS_ROOT;
3542 fclose(f);
3543 jhist_done:
3544 rele_all_sigs(); /* XXX remove jumps */
3545 }while(0);
3546 # endif /* HAVE_HISTORY */
3548 /* Force immediate resolve for anything which follows */
3549 pstate |= PS_LINE_EDITOR_INIT;
3551 # ifdef HAVE_KEY_BINDINGS
3552 /* `bind's (and `unbind's) done from within resource files couldn't be
3553 * performed for real since our termcap driver wasn't yet loaded, and we
3554 * can't perform automatic init since the user may have disallowed so */
3555 /* C99 */{
3556 struct a_tty_bind_ctx *tbcp;
3557 enum n_lexinput_flags lif;
3559 for(lif = 0; lif < n__LEXINPUT_CTX_MAX; ++lif)
3560 for(tbcp = a_tty.tg_bind[lif]; tbcp != NULL; tbcp = tbcp->tbc_next)
3561 if((tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
3562 a_TTY_BIND_RESOLVE)
3563 a_tty_bind_resolve(tbcp);
3566 /* And we want to (try to) install some default key bindings */
3567 if(!ok_blook(line_editor_no_defaults)){
3568 char buf[8];
3569 struct a_tty_bind_parse_ctx tbpc;
3570 struct a_tty_bind_default_tuple const *tbdtp;
3572 buf[0] = '$', buf[1] = '\'', buf[2] = '\\', buf[3] = 'c',
3573 buf[5] = '\'', buf[6] = '\0';
3574 for(tbdtp = a_tty_bind_default_tuples;
3575 PTRCMP(tbdtp, <,
3576 &a_tty_bind_default_tuples[n_NELEM(a_tty_bind_default_tuples)]);
3577 ++tbdtp){
3578 memset(&tbpc, 0, sizeof tbpc);
3579 tbpc.tbpc_cmd = "bind";
3580 if(tbdtp->tbdt_iskey){
3581 buf[4] = tbdtp->tbdt_ckey;
3582 tbpc.tbpc_in_seq = buf;
3583 }else
3584 tbpc.tbpc_in_seq = savecatsep(":", '\0',
3585 n_termcap_name_of_query(tbdtp->tbdt_query));
3586 tbpc.tbpc_exp.s = n_UNCONST(tbdtp->tbdt_exp[0] == '\0'
3587 ? a_tty_bind_fun_names[(ui8_t)tbdtp->tbdt_exp[1]]
3588 : tbdtp->tbdt_exp);
3589 tbpc.tbpc_exp.l = strlen(tbpc.tbpc_exp.s);
3590 tbpc.tbpc_flags = n_LEXINPUT_CTX_BASE;
3591 /* ..but don't want to overwrite any user settings */
3592 a_tty_bind_create(&tbpc, FAL0);
3595 # endif /* HAVE_KEY_BINDINGS */
3597 jleave:
3598 NYD_LEAVE;
3601 FL void
3602 n_tty_destroy(void){
3603 NYD_ENTER;
3605 if(!(pstate & PS_LINE_EDITOR_INIT))
3606 goto jleave;
3608 # ifdef HAVE_HISTORY
3609 do/* for break */{
3610 long hs;
3611 char const *v;
3612 struct a_tty_hist *thp;
3613 bool_t dogabby;
3614 FILE *f;
3616 a_TTY_HISTSIZE(hs);
3617 if(hs == 0)
3618 break;
3620 a_TTY_HISTFILE(v);
3621 if(v == NULL)
3622 break;
3624 dogabby = ok_blook(history_gabby_persist);
3626 if((thp = a_tty.tg_hist) != NULL)
3627 for(; thp->th_older != NULL; thp = thp->th_older)
3628 if((dogabby || !thp->th_isgabby) && --hs == 0)
3629 break;
3631 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
3632 f = fopen(v, "w"); /* TODO temporary + rename?! */
3633 if(f == NULL)
3634 goto jhist_done;
3635 (void)n_file_lock(fileno(f), FLT_WRITE, 0,0, UIZ_MAX);
3637 for(; thp != NULL; thp = thp->th_younger){
3638 if(dogabby || !thp->th_isgabby){
3639 if(thp->th_isgabby)
3640 putc('*', f);
3641 fwrite(thp->th_dat, sizeof *thp->th_dat, thp->th_len, f);
3642 putc('\n', f);
3645 fclose(f);
3646 jhist_done:
3647 rele_all_sigs(); /* XXX remove jumps */
3648 }while(0);
3649 # endif /* HAVE_HISTORY */
3651 # if defined HAVE_KEY_BINDINGS && defined HAVE_DEBUG
3652 c_unbind(n_UNCONST("* *"));
3653 # endif
3655 # ifdef HAVE_DEBUG
3656 memset(&a_tty, 0, sizeof a_tty);
3657 # endif
3658 DBG( pstate &= ~PS_LINE_EDITOR_INIT; )
3659 jleave:
3660 NYD_LEAVE;
3663 FL void
3664 n_tty_signal(int sig){
3665 sigset_t nset, oset;
3666 NYD_X; /* Signal handler */
3668 switch(sig){
3669 # ifdef SIGWINCH
3670 case SIGWINCH:
3671 /* We don't deal with SIGWINCH, yet get called from main.c.
3672 * Note this case might get called even if !PS_LINE_EDITOR_INIT */
3673 break;
3674 # endif
3675 default:
3676 a_tty_term_mode(FAL0);
3677 n_TERMCAP_SUSPEND(TRU1);
3678 a_tty_sigs_down();
3680 sigemptyset(&nset);
3681 sigaddset(&nset, sig);
3682 sigprocmask(SIG_UNBLOCK, &nset, &oset);
3683 n_raise(sig);
3684 /* When we come here we'll continue editing, so reestablish */
3685 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
3687 a_tty_sigs_up();
3688 n_TERMCAP_RESUME(TRU1);
3689 a_tty_term_mode(TRU1);
3690 a_tty.tg_line->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
3691 break;
3695 FL int
3696 (n_tty_readline)(enum n_lexinput_flags lif, char const *prompt,
3697 char **linebuf, size_t *linesize, size_t n n_MEMORY_DEBUG_ARGS){
3698 struct a_tty_line tl;
3699 # ifdef HAVE_COLOUR
3700 char *posbuf, *pos;
3701 # endif
3702 ui32_t plen, pwidth;
3703 ssize_t nn;
3704 char const *orig_prompt;
3705 NYD_ENTER;
3706 n_UNUSED(lif);
3708 assert(!ok_blook(line_editor_disable));
3709 if(!(pstate & PS_LINE_EDITOR_INIT))
3710 n_tty_init();
3711 assert(pstate & PS_LINE_EDITOR_INIT);
3713 orig_prompt = prompt;
3714 /* xxx Likely overkill: avoid "bind base a,b,c set-line-editor-disable"
3715 * xxx not being honoured at once: call n_lex_input() instead of goto */
3716 # ifndef HAVE_KEY_BINDINGS
3717 jredo:
3718 prompt = orig_prompt;
3719 # endif
3721 # ifdef HAVE_COLOUR
3722 n_colour_env_create(n_COLOUR_CTX_MLE, FAL0);
3723 # endif
3725 /* Classify prompt */
3726 n_UNINIT(plen, 0);
3727 n_UNINIT(pwidth, 0);
3728 if(prompt != NULL){
3729 size_t i = strlen(prompt);
3731 if(i == 0 || i >= UI32_MAX)
3732 prompt = NULL;
3733 else{
3734 /* TODO *prompt* is in multibyte and not in a_tty_cell, therefore
3735 * TODO we cannot handle it in parts, it's all or nothing.
3736 * TODO Later (S-CText, SysV signals) the prompt should be some global
3737 * TODO carrier thing, fully evaluated and passed around as UI-enabled
3738 * TODO string, then we can print it character by character */
3739 struct n_visual_info_ctx vic;
3741 memset(&vic, 0, sizeof vic);
3742 vic.vic_indat = prompt;
3743 vic.vic_inlen = i;
3744 if(n_visual_info(&vic, n_VISUAL_INFO_WIDTH_QUERY)){
3745 pwidth = (ui32_t)vic.vic_vi_width;
3746 plen = (ui32_t)i;
3747 }else{
3748 n_err(_("Character set error in evaluation of prompt\n"));
3749 prompt = NULL;
3754 # ifdef HAVE_COLOUR
3755 /* C99 */{
3756 struct n_colour_pen *ccp;
3757 struct str const *sp;
3759 if(prompt != NULL &&
3760 (ccp = n_colour_pen_create(n_COLOUR_ID_MLE_PROMPT, NULL)) != NULL &&
3761 (sp = n_colour_pen_to_str(ccp)) != NULL){
3762 char const *ccol = sp->s;
3764 if((sp = n_colour_reset_to_str()) != NULL){
3765 size_t l1 = strlen(ccol), l2 = strlen(sp->s);
3766 ui32_t nplen = (ui32_t)(l1 + plen + l2);
3767 char *nprompt = salloc(nplen +1);
3769 memcpy(nprompt, ccol, l1);
3770 memcpy(&nprompt[l1], prompt, plen);
3771 memcpy(&nprompt[l1 += plen], sp->s, ++l2);
3773 prompt = nprompt;
3774 plen = nplen;
3778 /* .tl_pos_buf is a hack */
3779 posbuf = pos = NULL;
3780 if((ccp = n_colour_pen_create(n_COLOUR_ID_MLE_POSITION, NULL)) != NULL &&
3781 (sp = n_colour_pen_to_str(ccp)) != NULL){
3782 char const *ccol = sp->s;
3784 if((sp = n_colour_reset_to_str()) != NULL){
3785 size_t l1 = strlen(ccol), l2 = strlen(sp->s);
3787 posbuf = salloc(l1 + 4 + l2 +1);
3788 memcpy(posbuf, ccol, l1);
3789 pos = &posbuf[l1];
3790 memcpy(&pos[4], sp->s, ++l2);
3793 if(posbuf == NULL){
3794 posbuf = pos = salloc(4 +1);
3795 pos[4] = '\0';
3798 # endif /* HAVE_COLOUR */
3800 memset(&tl, 0, sizeof tl);
3802 # ifdef HAVE_KEY_BINDINGS
3803 /* C99 */{
3804 char const *cp = ok_vlook(bind_timeout);
3806 if(cp != NULL){
3807 ul_i ul;
3809 if((ul = strtoul(cp, NULL, 0)) > 0 &&
3810 /* Convert to tenths of a second, unfortunately */
3811 (ul = (ul + 99) / 100) <= a_TTY_BIND_TIMEOUT_MAX)
3812 tl.tl_bind_timeout = (ui8_t)ul;
3813 else if(options & OPT_D_V)
3814 n_err(_("Ignoring invalid *bind-timeout*: %s\n"), cp);
3818 if(a_tty.tg_bind_isdirty)
3819 a_tty_bind_tree_teardown();
3820 if(a_tty.tg_bind_cnt > 0 && !a_tty.tg_bind_isbuild)
3821 a_tty_bind_tree_build();
3822 tl.tl_bind_tree_hmap = &a_tty.tg_bind_tree[lif & n__LEXINPUT_CTX_MASK];
3823 tl.tl_bind_shcut_cancel =
3824 &a_tty.tg_bind_shcut_cancel[lif & n__LEXINPUT_CTX_MASK];
3825 tl.tl_bind_shcut_prompt_char =
3826 &a_tty.tg_bind_shcut_prompt_char[lif & n__LEXINPUT_CTX_MASK];
3827 # endif /* HAVE_KEY_BINDINGS */
3829 if((tl.tl_prompt = prompt) != NULL){ /* XXX not re-evaluated */
3830 tl.tl_prompt_length = plen;
3831 tl.tl_prompt_width = pwidth;
3833 # ifdef HAVE_COLOUR
3834 tl.tl_pos_buf = posbuf;
3835 tl.tl_pos = pos;
3836 # endif
3838 tl.tl_line.cbuf = *linebuf;
3839 if(n != 0){
3840 tl.tl_defc.s = savestrbuf(*linebuf, n);
3841 tl.tl_defc.l = n;
3843 tl.tl_x_buf = linebuf;
3844 tl.tl_x_bufsize = linesize;
3846 a_tty.tg_line = &tl;
3847 a_tty_sigs_up();
3848 n_TERMCAP_RESUME(FAL0);
3849 a_tty_term_mode(TRU1);
3850 nn = a_tty_readline(&tl, n n_MEMORY_DEBUG_ARGSCALL);
3851 a_tty_term_mode(FAL0);
3852 n_TERMCAP_SUSPEND(FAL0);
3853 a_tty_sigs_down();
3854 a_tty.tg_line = NULL;
3856 # ifdef HAVE_COLOUR
3857 n_colour_env_gut(stdout);
3858 # endif
3860 if(tl.tl_reenter_after_cmd != NULL){
3861 n_source_command(lif, tl.tl_reenter_after_cmd);
3862 /* TODO because of recursion we cannot use srelax()ation: would be good */
3863 /* See above for why not simply using goto */
3864 n = (nn <= 0) ? 0 : nn;
3865 # ifdef HAVE_KEY_BINDINGS
3866 nn = (n_lex_input)(lif, orig_prompt, linebuf, linesize,
3867 (n == 0 ? "" : savestrbuf(*linebuf, n)) n_MEMORY_DEBUG_ARGSCALL);
3868 # else
3869 goto jredo;
3870 # endif
3872 NYD_LEAVE;
3873 return (int)nn;
3876 FL void
3877 n_tty_addhist(char const *s, bool_t isgabby){
3878 # ifdef HAVE_HISTORY
3879 /* Super-Heavy-Metal: block all sigs, avoid leaks+ on jump */
3880 ui32_t l;
3881 struct a_tty_hist *thp, *othp, *ythp;
3882 # endif
3883 NYD_ENTER;
3884 n_UNUSED(s);
3885 n_UNUSED(isgabby);
3887 # ifdef HAVE_HISTORY
3888 a_TTY_CHECK_ADDHIST(s, isgabby, goto j_leave);
3889 if(a_tty.tg_hist_size_max == 0)
3890 goto j_leave;
3892 l = (ui32_t)strlen(s);
3894 /* Eliminating duplicates is expensive, but simply inacceptable so
3895 * during the load of a potentially large history file! */
3896 if(pstate & PS_LINE_EDITOR_INIT)
3897 for(thp = a_tty.tg_hist; thp != NULL; thp = thp->th_older)
3898 if(thp->th_len == l && !strcmp(thp->th_dat, s)){
3899 hold_all_sigs(); /* TODO */
3900 if(thp->th_isgabby)
3901 thp->th_isgabby = !!isgabby;
3902 othp = thp->th_older;
3903 ythp = thp->th_younger;
3904 if(othp != NULL)
3905 othp->th_younger = ythp;
3906 else
3907 a_tty.tg_hist_tail = ythp;
3908 if(ythp != NULL)
3909 ythp->th_older = othp;
3910 else
3911 a_tty.tg_hist = othp;
3912 goto jleave;
3914 hold_all_sigs();
3916 ++a_tty.tg_hist_size;
3917 if((pstate & PS_LINE_EDITOR_INIT) &&
3918 a_tty.tg_hist_size > a_tty.tg_hist_size_max){
3919 --a_tty.tg_hist_size;
3920 if((thp = a_tty.tg_hist_tail) != NULL){
3921 if((a_tty.tg_hist_tail = thp->th_younger) == NULL)
3922 a_tty.tg_hist = NULL;
3923 else
3924 a_tty.tg_hist_tail->th_older = NULL;
3925 free(thp);
3929 thp = smalloc((sizeof(struct a_tty_hist) -
3930 n_VFIELD_SIZEOF(struct a_tty_hist, th_dat)) + l +1);
3931 thp->th_isgabby = !!isgabby;
3932 thp->th_len = l;
3933 memcpy(thp->th_dat, s, l +1);
3934 jleave:
3935 if((thp->th_older = a_tty.tg_hist) != NULL)
3936 a_tty.tg_hist->th_younger = thp;
3937 else
3938 a_tty.tg_hist_tail = thp;
3939 thp->th_younger = NULL;
3940 a_tty.tg_hist = thp;
3942 rele_all_sigs();
3943 j_leave:
3944 # endif
3945 NYD_LEAVE;
3948 # ifdef HAVE_HISTORY
3949 FL int
3950 c_history(void *v){
3951 C_HISTORY_SHARED;
3953 jlist:{
3954 FILE *fp;
3955 size_t i, b;
3956 struct a_tty_hist *thp;
3958 if(a_tty.tg_hist == NULL)
3959 goto jleave;
3961 if((fp = Ftmp(NULL, "hist", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
3962 n_perr(_("tmpfile"), 0);
3963 v = NULL;
3964 goto jleave;
3967 i = a_tty.tg_hist_size;
3968 b = 0;
3969 for(thp = a_tty.tg_hist; thp != NULL;
3970 --i, b += thp->th_len, thp = thp->th_older)
3971 fprintf(fp,
3972 "%c%4" PRIuZ ". %-50.50s (%4" PRIuZ "+%2" PRIu32 " B)\n",
3973 (thp->th_isgabby ? '*' : ' '), i, thp->th_dat, b, thp->th_len);
3975 page_or_print(fp, i);
3976 Fclose(fp);
3978 goto jleave;
3980 jclear:{
3981 struct a_tty_hist *thp;
3983 while((thp = a_tty.tg_hist) != NULL){
3984 a_tty.tg_hist = thp->th_older;
3985 free(thp);
3987 a_tty.tg_hist_tail = NULL;
3988 a_tty.tg_hist_size = 0;
3990 goto jleave;
3992 jentry:{
3993 struct a_tty_hist *thp;
3995 if(UICMP(z, entry, <=, a_tty.tg_hist_size)){
3996 entry = (long)a_tty.tg_hist_size - entry;
3997 for(thp = a_tty.tg_hist;; thp = thp->th_older)
3998 if(thp == NULL)
3999 break;
4000 else if(entry-- != 0)
4001 continue;
4002 else{
4003 v = temporary_arg_v_store = thp->th_dat;
4004 goto jleave;
4007 v = NULL;
4009 goto jleave;
4011 # endif /* HAVE_HISTORY */
4013 # ifdef HAVE_KEY_BINDINGS
4014 FL int
4015 c_bind(void *v){
4016 n_CMD_ARG_DESC_SUBCLASS_DEF(bind, 3, a_tty_bind_cad) { /* TODO cmd_tab.h */
4017 {n_CMD_ARG_DESC_STRING, 0},
4018 {n_CMD_ARG_DESC_WYSH | n_CMD_ARG_DESC_OPTION |
4019 n_CMD_ARG_DESC_HONOUR_STOP,
4020 n_SHEXP_PARSE_DRYRUN | n_SHEXP_PARSE_LOG},
4021 {n_CMD_ARG_DESC_WYSH | n_CMD_ARG_DESC_OPTION | n_CMD_ARG_DESC_GREEDY |
4022 n_CMD_ARG_DESC_HONOUR_STOP,
4023 n_SHEXP_PARSE_IGNORE_EMPTY}
4024 } n_CMD_ARG_DESC_SUBCLASS_DEF_END;
4025 struct n_cmd_arg_ctx cac;
4026 struct a_tty_bind_ctx *tbcp;
4027 enum n_lexinput_flags lif;
4028 bool_t aster, show;
4029 union {char const *cp; char *p; char c;} c;
4030 NYD_ENTER;
4032 cac.cac_desc = n_CMD_ARG_DESC_SUBCLASS_CAST(&a_tty_bind_cad);
4033 cac.cac_indat = v;
4034 cac.cac_inlen = UIZ_MAX;
4035 if(!n_cmd_arg_parse(&cac)){
4036 v = NULL;
4037 goto jleave;
4040 c.cp = cac.cac_arg->ca_arg.ca_str.s;
4041 if(cac.cac_no == 1)
4042 show = TRU1;
4043 else
4044 show = !asccasecmp(cac.cac_arg->ca_next->ca_arg.ca_str.s, "show");
4045 aster = FAL0;
4047 if((lif = a_tty_bind_ctx_find(c.cp)) == (enum n_lexinput_flags)-1){
4048 if(!(aster = n_is_all_or_aster(c.cp)) || !show){
4049 n_err(_("`bind': invalid context: %s\n"), c.cp);
4050 v = NULL;
4051 goto jleave;
4053 lif = 0;
4056 if(show){
4057 ui32_t lns;
4058 FILE *fp;
4060 if((fp = Ftmp(NULL, "bind", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
4061 n_perr(_("tmpfile"), 0);
4062 v = NULL;
4063 goto jleave;
4066 lns = 0;
4067 for(;;){
4068 for(tbcp = a_tty.tg_bind[lif]; tbcp != NULL;
4069 ++lns, tbcp = tbcp->tbc_next){
4070 /* Print the bytes of resolved terminal capabilities, then */
4071 if((options & OPT_D_V) &&
4072 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)
4073 ) == a_TTY_BIND_RESOLVE){
4074 char cbuf[8];
4075 union {wchar_t const *wp; char const *cp;} u;
4076 si32_t entlen;
4077 ui32_t cnvlen;
4078 char const *cnvdat, *bsep, *cbufp;
4080 putc('#', fp);
4081 putc(' ', fp);
4083 cbuf[0] = '=', cbuf[2] = '\0';
4084 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len;
4085 cnvlen > 0;){
4086 if(cnvdat != tbcp->tbc_cnv)
4087 putc(',', fp);
4089 /* {si32_t buf_len_iscap;} */
4090 entlen = *n_UNALIGN(si32_t const*,cnvdat);
4091 if(entlen & SI32_MIN){
4092 /* struct{si32_t buf_len_iscap; si32_t cap_len;
4093 * char buf[]+NUL;} */
4094 for(bsep = "",
4095 u.cp = (char const*)
4096 &n_UNALIGN(si32_t const*,cnvdat)[2];
4097 (c.c = *u.cp) != '\0'; ++u.cp){
4098 if(asciichar(c.c) && !cntrlchar(c.c))
4099 cbuf[1] = c.c, cbufp = cbuf;
4100 else
4101 cbufp = "";
4102 fprintf(fp, "%s%02X%s",
4103 bsep, (ui32_t)(ui8_t)c.c, cbufp);
4104 bsep = " ";
4106 entlen &= SI32_MAX;
4107 }else
4108 putc('-', fp);
4110 cnvlen -= entlen;
4111 cnvdat += entlen;
4114 fputs("\n ", fp);
4115 ++lns;
4118 fprintf(fp, "%sbind %s %s %s%s%s\n",
4119 ((tbcp->tbc_flags & a_TTY_BIND_DEFUNCT)
4120 /* I18N: `bind' sequence not working, either because it is
4121 * I18N: using Unicode and that is not available in the locale,
4122 * I18N: or a termcap(5)/terminfo(5) sequence won't work out */
4123 ? _("# <Defunctional> ") : ""),
4124 a_tty_bind_ctx_maps[lif].tbcm_name, tbcp->tbc_seq,
4125 n_shexp_quote_cp(tbcp->tbc_exp, TRU1),
4126 (tbcp->tbc_flags & a_TTY_BIND_NOCOMMIT ? "@" : ""),
4127 (!(options & OPT_D_VV) ? ""
4128 : (tbcp->tbc_flags & a_TTY_BIND_FUN_INTERNAL
4129 ? _(" # MLE internal") : ""))
4132 if(!aster || ++lif >= n__LEXINPUT_CTX_MAX)
4133 break;
4135 page_or_print(fp, lns);
4137 Fclose(fp);
4138 }else{
4139 struct a_tty_bind_parse_ctx tbpc;
4140 struct n_string store;
4142 memset(&tbpc, 0, sizeof tbpc);
4143 tbpc.tbpc_cmd = a_tty_bind_cad.cad_name;
4144 tbpc.tbpc_in_seq = cac.cac_arg->ca_next->ca_arg.ca_str.s;
4145 tbpc.tbpc_exp.s = n_string_cp(n_cmd_arg_join_greedy(&cac,
4146 n_string_creat_auto(&store)));
4147 tbpc.tbpc_exp.l = store.s_len;
4148 tbpc.tbpc_flags = lif;
4149 if(!a_tty_bind_create(&tbpc, TRU1))
4150 v = NULL;
4151 n_string_gut(&store);
4153 jleave:
4154 NYD_LEAVE;
4155 return (v != NULL) ? EXIT_OK : EXIT_ERR;
4158 FL int
4159 c_unbind(void *v){
4160 n_CMD_ARG_DESC_SUBCLASS_DEF(unbind, 2, a_tty_unbind_cad) {/* TODO cmd_tab.h*/
4161 {n_CMD_ARG_DESC_STRING, 0},
4162 {n_CMD_ARG_DESC_WYSH | n_CMD_ARG_DESC_HONOUR_STOP,
4163 n_SHEXP_PARSE_DRYRUN | n_SHEXP_PARSE_LOG}
4164 } n_CMD_ARG_DESC_SUBCLASS_DEF_END;
4165 struct a_tty_bind_parse_ctx tbpc;
4166 struct n_cmd_arg_ctx cac;
4167 struct a_tty_bind_ctx *tbcp;
4168 enum n_lexinput_flags lif;
4169 bool_t aster;
4170 union {char const *cp; char *p;} c;
4171 NYD_ENTER;
4173 cac.cac_desc = n_CMD_ARG_DESC_SUBCLASS_CAST(&a_tty_unbind_cad);
4174 cac.cac_indat = v;
4175 cac.cac_inlen = UIZ_MAX;
4176 if(!n_cmd_arg_parse(&cac)){
4177 v = NULL;
4178 goto jleave;
4181 c.cp = cac.cac_arg->ca_arg.ca_str.s;
4182 aster = FAL0;
4184 if((lif = a_tty_bind_ctx_find(c.cp)) == (enum n_lexinput_flags)-1){
4185 if(!(aster = n_is_all_or_aster(c.cp))){
4186 n_err(_("`unbind': invalid context: %s\n"), c.cp);
4187 v = NULL;
4188 goto jleave;
4190 lif = 0;
4193 c.cp = cac.cac_arg->ca_next->ca_arg.ca_str.s;
4194 jredo:
4195 if(n_is_all_or_aster(c.cp)){
4196 while((tbcp = a_tty.tg_bind[lif]) != NULL){
4197 memset(&tbpc, 0, sizeof tbpc);
4198 tbpc.tbpc_tbcp = tbcp;
4199 tbpc.tbpc_flags = lif;
4200 a_tty_bind_del(&tbpc);
4202 }else{
4203 memset(&tbpc, 0, sizeof tbpc);
4204 tbpc.tbpc_cmd = a_tty_unbind_cad.cad_name;
4205 tbpc.tbpc_in_seq = c.cp;
4206 tbpc.tbpc_flags = lif;
4208 if(n_UNLIKELY(!a_tty_bind_parse(FAL0, &tbpc)))
4209 v = NULL;
4210 else if(n_UNLIKELY((tbcp = tbpc.tbpc_tbcp) == NULL)){
4211 n_err(_("`unbind': no such `bind'ing: %s %s\n"),
4212 a_tty_bind_ctx_maps[lif].tbcm_name, c.cp);
4213 v = NULL;
4214 }else
4215 a_tty_bind_del(&tbpc);
4218 if(aster && ++lif < n__LEXINPUT_CTX_MAX)
4219 goto jredo;
4220 jleave:
4221 NYD_LEAVE;
4222 return (v != NULL) ? EXIT_OK : EXIT_ERR;
4224 # endif /* HAVE_KEY_BINDINGS */
4226 #else /* HAVE_MLE */
4228 * The really-nothing-at-all implementation
4231 FL void
4232 n_tty_init(void){
4233 NYD_ENTER;
4234 NYD_LEAVE;
4237 FL void
4238 n_tty_destroy(void){
4239 NYD_ENTER;
4240 NYD_LEAVE;
4243 FL void
4244 n_tty_signal(int sig){
4245 NYD_X; /* Signal handler */
4246 n_UNUSED(sig);
4248 # ifdef HAVE_TERMCAP
4249 switch(sig){
4250 default:{
4251 sigset_t nset, oset;
4253 n_TERMCAP_SUSPEND(TRU1);
4254 a_tty_sigs_down();
4256 sigemptyset(&nset);
4257 sigaddset(&nset, sig);
4258 sigprocmask(SIG_UNBLOCK, &nset, &oset);
4259 n_raise(sig);
4260 /* When we come here we'll continue editing, so reestablish */
4261 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
4263 a_tty_sigs_up();
4264 n_TERMCAP_RESUME(TRU1);
4265 break;
4268 # endif /* HAVE_TERMCAP */
4271 FL int
4272 (n_tty_readline)(enum n_lexinput_flags lif, char const *prompt,
4273 char **linebuf, size_t *linesize, size_t n n_MEMORY_DEBUG_ARGS){
4274 int rv;
4275 NYD_ENTER;
4277 if(prompt != NULL){
4278 if(*prompt != '\0')
4279 fputs(prompt, stdout);
4280 fflush(stdout);
4282 # ifdef HAVE_TERMCAP
4283 a_tty_sigs_up();
4284 n_TERMCAP_RESUME(FAL0);
4285 # endif
4286 rv = (readline_restart)(stdin, linebuf, linesize,n n_MEMORY_DEBUG_ARGSCALL);
4287 # ifdef HAVE_TERMCAP
4288 n_TERMCAP_SUSPEND(FAL0);
4289 a_tty_sigs_down();
4290 # endif
4291 NYD_LEAVE;
4292 return rv;
4295 FL void
4296 n_tty_addhist(char const *s, bool_t isgabby){
4297 NYD_ENTER;
4298 n_UNUSED(s);
4299 n_UNUSED(isgabby);
4300 NYD_LEAVE;
4302 #endif /* nothing at all */
4304 #undef a_TTY_SIGNALS
4305 /* s-it-mode */