Drop `features', change `version', adjust make system..
[s-mailx.git] / tty.c
blob01d8899ad3f7ab14bb19d0e988b461fbbd1ff823
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 - 2015 Steffen (Daode) Nurpmeso <sdaoden@users.sf.net>.
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 (V) = HIST_SIZE;\
57 else if(__rv < 0)\
58 __rv = 0;\
59 else\
60 (V) = __rv;\
61 }while(0)
63 # define a_TTY_CHECK_ADDHIST(S,ISGABBY,NOACT) \
64 do{\
65 if(!(pstate & (PS_ROOT | PS_LINE_EDITOR_INIT)) ||\
66 ok_blook(line_editor_disable) ||\
67 ((ISGABBY) && !ok_blook(history_gabby)) ||\
68 spacechar(*(S)) || *(S) == '\0')\
69 NOACT;\
70 }while(0)
72 # define C_HISTORY_SHARED \
73 char **argv = v;\
74 long entry;\
75 NYD_ENTER;\
77 if(ok_blook(line_editor_disable)){\
78 n_err(_("history: *line-editor-disable* is set\n"));\
79 goto jerr;\
81 if(!(pstate & PS_LINE_EDITOR_INIT)){\
82 n_tty_init();\
83 assert(pstate & PS_LINE_EDITOR_INIT);\
85 if(*argv == NULL)\
86 goto jlist;\
87 if(argv[1] != NULL)\
88 goto jerr;\
89 if(!asccasecmp(*argv, "show"))\
90 goto jlist;\
91 if(!asccasecmp(*argv, "clear"))\
92 goto jclear;\
93 if((entry = strtol(*argv, argv, 10)) > 0 && **argv == '\0')\
94 goto jentry;\
95 jerr:\
96 n_err(_("Synopsis: history: %s\n"),\
97 /* Same string as in cmd_tab.h, still hoping...) */\
98 _("<show> (default), <clear> or select <NO> from editor history"));\
99 v = NULL;\
100 jleave:\
101 NYD_LEAVE;\
102 return (v == NULL ? !STOP : !OKAY); /* xxx 1:bad 0:good -- do some */
103 #endif /* HAVE_HISTORY */
105 #ifdef a_TTY_SIGNALS
106 static sighandler_type a_tty_oint, a_tty_oquit, a_tty_oterm,
107 a_tty_ohup,
108 a_tty_otstp, a_tty_ottin, a_tty_ottou;
109 #endif
111 #ifdef a_TTY_SIGNALS
112 static void a_tty_sigs_up(void), a_tty_sigs_down(void);
113 #endif
115 #ifdef a_TTY_SIGNALS
116 static void
117 a_tty_sigs_up(void){
118 sigset_t nset, oset;
119 NYD2_ENTER;
121 sigfillset(&nset);
123 sigprocmask(SIG_BLOCK, &nset, &oset);
124 a_tty_oint = safe_signal(SIGINT, &n_tty_signal);
125 a_tty_oquit = safe_signal(SIGQUIT, &n_tty_signal);
126 a_tty_oterm = safe_signal(SIGTERM, &n_tty_signal);
127 a_tty_ohup = safe_signal(SIGHUP, &n_tty_signal);
128 a_tty_otstp = safe_signal(SIGTSTP, &n_tty_signal);
129 a_tty_ottin = safe_signal(SIGTTIN, &n_tty_signal);
130 a_tty_ottou = safe_signal(SIGTTOU, &n_tty_signal);
131 sigprocmask(SIG_SETMASK, &oset, NULL);
132 NYD2_LEAVE;
135 static void
136 a_tty_sigs_down(void){
137 sigset_t nset, oset;
138 NYD2_ENTER;
140 sigfillset(&nset);
142 sigprocmask(SIG_BLOCK, &nset, &oset);
143 safe_signal(SIGINT, a_tty_oint);
144 safe_signal(SIGQUIT, a_tty_oquit);
145 safe_signal(SIGTERM, a_tty_oterm);
146 safe_signal(SIGHUP, a_tty_ohup);
147 safe_signal(SIGTSTP, a_tty_otstp);
148 safe_signal(SIGTTIN, a_tty_ottin);
149 safe_signal(SIGTTOU, a_tty_ottou);
150 sigprocmask(SIG_SETMASK, &oset, NULL);
151 NYD2_LEAVE;
153 #endif /* a_TTY_SIGNALS */
155 static sigjmp_buf a_tty__actjmp; /* TODO someday, we won't need it no more */
156 static void
157 a_tty__acthdl(int s) /* TODO someday, we won't need it no more */
159 NYD_X; /* Signal handler */
160 termios_state_reset();
161 siglongjmp(a_tty__actjmp, s);
164 FL bool_t
165 getapproval(char const * volatile prompt, bool_t noninteract_default)
167 sighandler_type volatile oint, ohup;
168 bool_t volatile rv;
169 int volatile sig;
170 NYD_ENTER;
172 if (!(options & OPT_INTERACTIVE)) {
173 sig = 0;
174 rv = noninteract_default;
175 goto jleave;
177 rv = FAL0;
179 /* C99 */{
180 char const *quest = noninteract_default
181 ? _("[yes]/no? ") : _("[no]/yes? ");
183 if (prompt == NULL)
184 prompt = _("Continue");
185 prompt = savecatsep(prompt, ' ', quest);
188 oint = safe_signal(SIGINT, SIG_IGN);
189 ohup = safe_signal(SIGHUP, SIG_IGN);
190 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
191 goto jrestore;
192 safe_signal(SIGINT, &a_tty__acthdl);
193 safe_signal(SIGHUP, &a_tty__acthdl);
195 if (n_lex_input(n_LEXINPUT_CTX_BASE | n_LEXINPUT_NL_ESC, prompt,
196 &termios_state.ts_linebuf, &termios_state.ts_linesize, NULL) >= 0)
197 rv = (boolify(termios_state.ts_linebuf, UIZ_MAX,
198 noninteract_default) > 0);
199 jrestore:
200 termios_state_reset();
202 safe_signal(SIGHUP, ohup);
203 safe_signal(SIGINT, oint);
204 jleave:
205 NYD_LEAVE;
206 if (sig != 0)
207 n_raise(sig);
208 return rv;
211 #ifdef HAVE_SOCKETS
212 FL char *
213 getuser(char const * volatile query) /* TODO v15-compat obsolete */
215 sighandler_type volatile oint, ohup;
216 char * volatile user = NULL;
217 int volatile sig;
218 NYD_ENTER;
220 if (query == NULL)
221 query = _("User: ");
223 oint = safe_signal(SIGINT, SIG_IGN);
224 ohup = safe_signal(SIGHUP, SIG_IGN);
225 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
226 goto jrestore;
227 safe_signal(SIGINT, &a_tty__acthdl);
228 safe_signal(SIGHUP, &a_tty__acthdl);
230 if (n_lex_input(n_LEXINPUT_CTX_BASE | n_LEXINPUT_NL_ESC, query,
231 &termios_state.ts_linebuf, &termios_state.ts_linesize, NULL) >= 0)
232 user = termios_state.ts_linebuf;
233 jrestore:
234 termios_state_reset();
236 safe_signal(SIGHUP, ohup);
237 safe_signal(SIGINT, oint);
238 NYD_LEAVE;
239 if (sig != 0)
240 n_raise(sig);
241 return user;
244 FL char *
245 getpassword(char const *query)
247 sighandler_type volatile oint, ohup;
248 struct termios tios;
249 char * volatile pass = NULL;
250 int volatile sig;
251 NYD_ENTER;
253 if (query == NULL)
254 query = _("Password: ");
255 fputs(query, stdout);
256 fflush(stdout);
258 /* FIXME everywhere: tcsetattr() generates SIGTTOU when we're not in
259 * FIXME foreground pgrp, and can fail with EINTR!! also affects
260 * FIXME termios_state_reset() */
261 if (options & OPT_TTYIN) {
262 tcgetattr(STDIN_FILENO, &termios_state.ts_tios);
263 memcpy(&tios, &termios_state.ts_tios, sizeof tios);
264 termios_state.ts_needs_reset = TRU1;
265 tios.c_iflag &= ~(ISTRIP);
266 tios.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
269 oint = safe_signal(SIGINT, SIG_IGN);
270 ohup = safe_signal(SIGHUP, SIG_IGN);
271 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
272 goto jrestore;
273 safe_signal(SIGINT, &a_tty__acthdl);
274 safe_signal(SIGHUP, &a_tty__acthdl);
276 if (options & OPT_TTYIN)
277 tcsetattr(STDIN_FILENO, TCSAFLUSH, &tios);
279 if (readline_restart(stdin, &termios_state.ts_linebuf,
280 &termios_state.ts_linesize, 0) >= 0)
281 pass = termios_state.ts_linebuf;
282 jrestore:
283 termios_state_reset();
284 if (options & OPT_TTYIN)
285 putc('\n', stdout);
287 safe_signal(SIGHUP, ohup);
288 safe_signal(SIGINT, oint);
289 NYD_LEAVE;
290 if (sig != 0)
291 n_raise(sig);
292 return pass;
294 #endif /* HAVE_SOCKETS */
297 * MLE: the Mailx-Line-Editor, our homebrew editor
298 * (inspired from NetBSDs sh(1) and dash(1)s hetio.c).
300 * Only used in interactive mode, simply use STDIN_FILENO as point of interest.
301 * TODO . This code should be splitted in funs/raw input/bind modules.
302 * TODO . After I/O layer rewrite, also "output to STDIN_FILENO".
303 * TODO . We work with wide characters, but not for buffer takeovers and
304 * TODO cell2save()ings. This should be changed. For the former the buffer
305 * TODO thus needs to be converted to wide first, and then simply be fed in.
306 * TODO . We repaint too much. To overcome this use the same approach that my
307 * TODO terminal library uses, add a true "virtual screen line" that stores
308 * TODO the actually visible content, keep a notion of "first modified slot"
309 * TODO and "last modified slot" (including "unknown" and "any" specials),
310 * TODO update that virtual instead, then synchronize what has truly changed.
311 * TODO I.e., add an indirection layer.
312 * TODO . No BIDI support.
313 * TODO . `bind': we currently use only one lookup tree.
314 * TODO For absolute graceful behaviour in conjunction (with HAVE_TERMCAP) we
315 * TODO need a lower level tree, which possibly combines bytes into "symbolic
316 * TODO wchar_t values", into "keys" that is, as applicable, and an upper
317 * TODO layer which only works on "keys" in order to possibly combine them
318 * TODO into key sequences. We can reuse existent tree code for that.
319 * TODO We need an additional hashmap which maps termcap/terminfo names to
320 * TODO (their byte representations and) a dynamically assigned unique
321 * TODO "symbolic wchar_t value". This implies we may have incompatibilities
322 * TODO when __STDC_ISO_10646__ is not defined. Also we do need takeover-
323 * TODO bytes storage, but it can be a string_creat_auto in the line struct.
324 * TODO Until then we can run into ambiguities; in rare occasions.
326 #ifdef HAVE_MLE
327 /* To avoid memory leaks etc. with the current codebase that simply longjmp(3)s
328 * we're forced to use the very same buffer--the one that is passed through to
329 * us from the outside--to store anything we need, i.e., a "struct cell[]", and
330 * convert that on-the-fly back to the plain char* result once we're done.
331 * To simplify our live, use savestr() buffers for all other needed memory */
333 # ifdef HAVE_KEY_BINDINGS
334 /* Default *bind-timeout* key-sequence continuation timeout, in tenths of
335 * a second. Must fit in 8-bit! Update the manual upon change! */
336 # define a_TTY_BIND_TIMEOUT 2
337 # define a_TTY_BIND_TIMEOUT_MAX SI8_MAX
339 n_CTAV(a_TTY_BIND_TIMEOUT_MAX <= UI8_MAX);
341 /* We have a chicken-and-egg problem with `bind' and our termcap layer,
342 * because we may not initialize the latter automatically to allow users to
343 * specify *termcap-disable* and let it mean exactly that.
344 * On the other hand users can be expected to use `bind' in resource file(s).
345 * Therefore bindings which involve termcap/terminfo sequences, and which are
346 * defined before PS_STARTED signals usability of termcap/terminfo, will be
347 * (partially) delayed until tty_init() is called.
348 * And we preallocate space for the expansion of the resolved capability */
349 # define a_TTY_BIND_CAPNAME_MAX 15
350 # define a_TTY_BIND_CAPEXP_ROUNDUP 16
352 n_CTAV(ISPOW2(a_TTY_BIND_CAPEXP_ROUNDUP));
353 n_CTA(a_TTY_BIND_CAPEXP_ROUNDUP <= SI8_MAX / 2, "Variable must fit in 6-bit");
354 n_CTA(a_TTY_BIND_CAPEXP_ROUNDUP >= 8, "Variable too small");
355 # endif /* HAVE_KEY_BINDINGS */
357 /* The maximum size (of a_tty_cell's) in a line */
358 # define a_TTY_LINE_MAX SI32_MAX
360 /* (Some more CTAs around) */
361 n_CTA(a_TTY_LINE_MAX <= SI32_MAX,
362 "a_TTY_LINE_MAX larger than SI32_MAX, but the MLE uses 32-bit arithmetic");
364 /* When shall the visual screen be scrolled, in % of usable screen width */
365 # define a_TTY_SCROLL_MARGIN_LEFT 15
366 # define a_TTY_SCROLL_MARGIN_RIGHT 10
368 /* fexpand() flags for expand-on-tab */
369 # define a_TTY_TAB_FEXP_FL (FEXP_FULL | FEXP_SILENT | FEXP_MULTIOK)
371 /* Columns to ripoff: outermost may not be touched, plus position indicator.
372 * Must thus be at least 1, but should be >= 1+4 to dig the position indicator
373 * that we place (if there is sufficient space) */
374 # define a_TTY_WIDTH_RIPOFF 5
376 /* The implementation of the MLE functions always exists, and is based upon
377 * the a_TTY_BIND_FUN_* constants, so most of this enum is always necessary */
378 enum a_tty_bind_flags{
379 # ifdef HAVE_KEY_BINDINGS
380 a_TTY_BIND_RESOLVE = 1<<8, /* Term cap. yet needs to be resolved */
381 a_TTY_BIND_DEFUNCT = 1<<9, /* Unicode/term cap. used but not avail. */
382 a_TTY__BIND_MASK = a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT,
383 /* MLE fun assigned to a one-byte-sequence: this may be used for special
384 * key-sequence bypass processing */
385 a_TTY_BIND_MLE1CNTRL = 1<<10,
386 a_TTY_BIND_NOCOMMIT = 1<<11, /* Expansion shall be editable */
387 # endif
389 /* MLE internal commands */
390 a_TTY_BIND_FUN_INTERNAL = 1<<15,
391 a_TTY__BIND_FUN_SHIFT = 16,
392 a_TTY__BIND_FUN_SHIFTMAX = 24,
393 a_TTY__BIND_FUN_MASK = ((1 << a_TTY__BIND_FUN_SHIFTMAX) - 1) &
394 ~((1 << a_TTY__BIND_FUN_SHIFT) - 1),
395 # define a_TTY_BIND_FUN_REDUCE(X) \
396 (((ui32_t)(X) & a_TTY__BIND_FUN_MASK) >> a_TTY__BIND_FUN_SHIFT)
397 # define a_TTY_BIND_FUN_EXPAND(X) \
398 (((ui32_t)(X) & (a_TTY__BIND_FUN_MASK >> a_TTY__BIND_FUN_SHIFT)) << \
399 a_TTY__BIND_FUN_SHIFT)
400 # undef a_X
401 # define a_X(N,I)\
402 a_TTY_BIND_FUN_ ## N = a_TTY_BIND_FUN_EXPAND(I),
404 a_X(BELL, 0)
405 a_X(GO_BWD, 1) a_X(GO_FWD, 2)
406 a_X(GO_WORD_BWD, 3) a_X(GO_WORD_FWD, 4)
407 a_X(GO_HOME, 5) a_X(GO_END, 6)
408 a_X(DEL_BWD, 7) a_X(DEL_FWD, 8)
409 a_X(SNARF_WORD_BWD, 9) a_X(SNARF_WORD_FWD, 10)
410 a_X(SNARF_END, 11) a_X(SNARF_LINE, 12)
411 a_X(HIST_BWD, 13) a_X(HIST_FWD, 14)
412 a_X(HIST_SRCH_BWD, 15) a_X(HIST_SRCH_FWD, 16)
413 a_X(REPAINT, 17)
414 a_X(QUOTE_RNDTRIP, 18)
415 a_X(PROMPT_CHAR, 19)
416 a_X(COMPLETE, 20)
417 a_X(PASTE, 21)
419 a_X(CANCEL, 22)
420 a_X(RESET, 23)
421 a_X(FULLRESET, 24)
422 a_X(COMMIT, 25) /* Must be last one! */
423 # undef a_X
425 a_TTY__BIND_LAST = 1<<25
427 # ifdef HAVE_KEY_BINDINGS
428 n_CTA((ui32_t)a_TTY_BIND_RESOLVE > (ui32_t)n__LEXINPUT_CTX_MAX,
429 "Bit carrier lower boundary must be raised to avoid value sharing");
430 # endif
431 n_CTA(a_TTY_BIND_FUN_EXPAND(a_TTY_BIND_FUN_COMMIT) <
432 (1 << a_TTY__BIND_FUN_SHIFTMAX),
433 "Bit carrier range must be expanded to represent necessary bits");
434 n_CTA(a_TTY__BIND_LAST >= (1 << a_TTY__BIND_FUN_SHIFTMAX),
435 "Bit carrier upper boundary must be raised to avoid value sharing");
436 n_CTA(UICMP(64, a_TTY__BIND_LAST, <=, SI32_MAX),
437 "Flag bits excess storage datatype" /* And we need one bit free */);
439 enum a_tty_fun_status{
440 a_TTY_FUN_STATUS_OK, /* Worked, next character */
441 a_TTY_FUN_STATUS_COMMIT, /* Line done */
442 a_TTY_FUN_STATUS_RESTART, /* Complete restart, reset multibyte etc. */
443 a_TTY_FUN_STATUS_END /* End, return EOF */
446 enum a_tty_visual_flags{
447 a_TTY_VF_NONE,
448 a_TTY_VF_MOD_CURSOR = 1<<0, /* Cursor moved */
449 a_TTY_VF_MOD_CONTENT = 1<<1, /* Content modified */
450 a_TTY_VF_MOD_DIRTY = 1<<2, /* Needs complete repaint */
451 a_TTY_VF_MOD_SINGLE = 1<<3, /* TODO Drop when indirection as above comes */
452 a_TTY_VF_REFRESH = a_TTY_VF_MOD_DIRTY | a_TTY_VF_MOD_CURSOR |
453 a_TTY_VF_MOD_CONTENT | a_TTY_VF_MOD_SINGLE,
454 a_TTY_VF_BELL = 1<<8, /* Ring the bell */
455 a_TTY_VF_SYNC = 1<<9, /* Flush/Sync I/O channel */
457 a_TTY_VF_ALL_MASK = a_TTY_VF_REFRESH | a_TTY_VF_BELL | a_TTY_VF_SYNC,
458 a_TTY__VF_LAST = a_TTY_VF_SYNC
461 # ifdef HAVE_KEY_BINDINGS
462 struct a_tty_bind_ctx{
463 struct a_tty_bind_ctx *tbc_next;
464 char *tbc_seq; /* quence as given (poss. re-quoted), in .tb__buf */
465 char *tbc_exp; /* ansion, in .tb__buf */
466 /* The .tbc_seq'uence with any terminal capabilities resolved; in fact an
467 * array of structures, the first entry of which is {si32_t buf_len_iscap;}
468 * where the signed bit indicates whether the buffer is a resolved terminal
469 * capability instead of a (possibly multibyte) character. In .tbc__buf */
470 char *tbc_cnv;
471 ui32_t tbc_seq_len;
472 ui32_t tbc_exp_len;
473 ui32_t tbc_cnv_len;
474 ui32_t tbc_flags;
475 char tbc__buf[VFIELD_SIZE(0)];
478 struct a_tty_bind_ctx_map{
479 enum n_lexinput_flags tbcm_ctx;
480 char const tbcm_name[12]; /* Name of `bind' context */
482 # endif /* HAVE_KEY_BINDINGS */
484 struct a_tty_bind_default_tuple{
485 bool_t tbdt_iskey; /* Whether this is a control key; else termcap query */
486 char tbdt_ckey; /* Control code */
487 ui16_t tbdt_query; /* enum n_termcap_query (instead) */
488 char tbdt_exp[12]; /* String or [0]=NUL/[1]=BIND_FUN_REDUCE() */
490 n_CTA(n__TERMCAP_QUERY_MAX <= UI16_MAX,
491 "Enumeration cannot be stored in datatype");
493 # ifdef HAVE_KEY_BINDINGS
494 struct a_tty_bind_parse_ctx{
495 char const *tbpc_cmd; /* Command which parses */
496 char const *tbpc_in_seq; /* In: key sequence */
497 struct str tbpc_exp; /* In/Out: expansion (or NULL) */
498 struct a_tty_bind_ctx *tbpc_tbcp; /* Out: if yet existent */
499 struct a_tty_bind_ctx *tbpc_ltbcp; /* Out: the one before .tbpc_tbcp */
500 char *tbpc_seq; /* Out: normalized sequence */
501 char *tbpc_cnv; /* Out: sequence when read(2)ing it */
502 ui32_t tbpc_seq_len;
503 ui32_t tbpc_cnv_len;
504 ui32_t tbpc_flags; /* n_lexinput_flags | a_tty_bind_flags */
505 ui8_t tbpc__dummy[4];
508 /* Input character tree */
509 struct a_tty_bind_tree{
510 struct a_tty_bind_tree *tbt_sibling; /* s at same level */
511 struct a_tty_bind_tree *tbt_childs; /* Sequence continues.. here */
512 struct a_tty_bind_tree *tbt_parent;
513 struct a_tty_bind_ctx *tbt_bind; /* NULL for intermediates */
514 wchar_t tbt_char; /* acter this level represents */
515 bool_t tbt_isseq; /* Belongs to multibyte sequence */
516 bool_t tbt_isseq_trail; /* ..is trailing byte of it */
517 ui8_t tbt__dummy[2];
519 # endif /* HAVE_KEY_BINDINGS */
521 struct a_tty_cell{
522 wchar_t tc_wc;
523 ui16_t tc_count; /* ..of bytes */
524 ui8_t tc_width; /* Visual width; TAB==UI8_MAX! */
525 bool_t tc_novis; /* Don't display visually as such (control character) */
526 char tc_cbuf[MB_LEN_MAX * 2]; /* .. plus reset shift sequence */
529 struct a_tty_global{
530 struct a_tty_line *tg_line; /* To be able to access it from signal hdl */
531 # ifdef HAVE_HISTORY
532 struct a_tty_hist *tg_hist;
533 struct a_tty_hist *tg_hist_tail;
534 size_t tg_hist_size;
535 size_t tg_hist_size_max;
536 # endif
537 # ifdef HAVE_KEY_BINDINGS
538 ui32_t tg_bind_cnt; /* Overall number of bindings */
539 bool_t tg_bind_isdirty;
540 bool_t tg_bind_isbuild;
541 char tg_bind_shcut_cancel[n__LEXINPUT_CTX_MAX][5];
542 char tg_bind_shcut_prompt_char[n__LEXINPUT_CTX_MAX][5];
543 struct a_tty_bind_ctx *tg_bind[n__LEXINPUT_CTX_MAX];
544 struct a_tty_bind_tree *tg_bind_tree[n__LEXINPUT_CTX_MAX][HSHSIZE];
545 # endif
546 struct termios tg_tios_old;
547 struct termios tg_tios_new;
549 n_CTA(n__LEXINPUT_CTX_MAX == 2,
550 "Value results in array sizes that results in bad structure layout");
552 # ifdef HAVE_HISTORY
553 struct a_tty_hist{
554 struct a_tty_hist *th_older;
555 struct a_tty_hist *th_younger;
556 # ifdef HAVE_BYTE_ORDER_LITTLE
557 ui32_t th_isgabby : 1;
558 # endif
559 ui32_t th_len : 31;
560 # ifndef HAVE_BYTE_ORDER_LITTLE
561 ui32_t th_isgabby : 1;
562 # endif
563 char th_dat[VFIELD_SIZE(sizeof(ui32_t))];
565 # endif
567 struct a_tty_line{
568 /* Caller pointers */
569 char **tl_x_buf;
570 size_t *tl_x_bufsize;
571 /* Input processing */
572 # ifdef HAVE_KEY_BINDINGS
573 wchar_t tl_bind_takeover; /* Leftover byte to consume next */
574 ui8_t tl_bind_timeout; /* In-seq. inter-byte-timer, in 1/10th secs */
575 ui8_t tl__bind_dummy[3];
576 char (*tl_bind_shcut_cancel)[5]; /* Special _CANCEL shortcut control */
577 char (*tl_bind_shcut_prompt_char)[5]; /* ..for _PROMPT_CHAR */
578 struct a_tty_bind_tree *(*tl_bind_tree_hmap)[HSHSIZE]; /* Bind lookup tree */
579 struct a_tty_bind_tree *tl_bind_tree;
580 # endif
581 char const *tl_reenter_after_cmd; /* `bind' cmd to exec, then re-readline */
582 /* Line data / content handling */
583 ui32_t tl_count; /* ..of a_tty_cell's (<= a_TTY_LINE_MAX) */
584 ui32_t tl_cursor; /* Current a_tty_cell insertion point */
585 union{
586 char *cbuf; /* *.tl_x_buf */
587 struct a_tty_cell *cells;
588 } tl_line;
589 struct str tl_defc; /* Current default content */
590 size_t tl_defc_cursor_byte; /* Desired position of cursor after takeover */
591 struct str tl_savec; /* Saved default content */
592 struct str tl_pastebuf; /* Last snarfed data */
593 # ifdef HAVE_HISTORY
594 struct a_tty_hist *tl_hist; /* History cursor */
595 # endif
596 ui32_t tl_count_max; /* ..before buffer needs to grow */
597 /* Visual data representation handling */
598 ui32_t tl_vi_flags; /* enum a_tty_visual_flags */
599 ui32_t tl_lst_count; /* .tl_count after last sync */
600 ui32_t tl_lst_cursor; /* .tl_cursor after last sync */
601 /* TODO Add another indirection layer by adding a tl_phy_line of
602 * TODO a_tty_cell objects, incorporate changes in visual layer,
603 * TODO then check what _really_ has changed, sync those changes only */
604 struct a_tty_cell const *tl_phy_start; /* First visible cell, left border */
605 ui32_t tl_phy_cursor; /* Physical cursor position */
606 bool_t tl_quote_rndtrip; /* For _kht() expansion */
607 ui8_t tl__dummy2[3];
608 ui32_t tl_prompt_length; /* Preclassified (TODO needed as a_tty_cell) */
609 ui32_t tl_prompt_width;
610 char const *tl_prompt; /* Preformatted prompt (including colours) */
611 /* .tl_pos_buf is a hack */
612 # ifdef HAVE_COLOUR
613 char *tl_pos_buf; /* mle-position colour-on, [4], reset seq. */
614 char *tl_pos; /* Address of the [4] */
615 # endif
618 # ifdef HAVE_KEY_BINDINGS
619 /* C99: use [INDEX]={} */
620 n_CTAV(n_LEXINPUT_CTX_BASE == 0);
621 n_CTAV(n_LEXINPUT_CTX_COMPOSE == 1);
622 static struct a_tty_bind_ctx_map const
623 a_tty_bind_ctx_maps[n__LEXINPUT_CTX_MAX] = {
624 {n_LEXINPUT_CTX_BASE, "base"},
625 {n_LEXINPUT_CTX_COMPOSE, "compose"}
628 /* Special functions which our MLE provides internally.
629 * Update the manual upon change! */
630 static char const a_tty_bind_fun_names[][24] = {
631 # undef a_X
632 # define a_X(I,N) \
633 n_FIELD_INITI(a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## I)) "mle-" N "\0",
635 a_X(BELL, "bell")
636 a_X(GO_BWD, "go-bwd") a_X(GO_FWD, "go-fwd")
637 a_X(GO_WORD_BWD, "go-word-bwd") a_X(GO_WORD_FWD, "go-word-fwd")
638 a_X(GO_HOME, "go-home") a_X(GO_END, "go-end")
639 a_X(DEL_BWD, "del-bwd") a_X(DEL_FWD, "del-fwd")
640 a_X(SNARF_WORD_BWD, "snarf-word-bwd") a_X(SNARF_WORD_FWD, "snarf-word-fwd")
641 a_X(SNARF_END, "snarf-end") a_X(SNARF_LINE, "snarf-line")
642 a_X(HIST_BWD, "hist-bwd") a_X(HIST_FWD, "hist-fwd")
643 a_X(HIST_SRCH_BWD, "hist-srch-bwd") a_X(HIST_SRCH_FWD, "hist-srch-fwd")
644 a_X(REPAINT, "repaint")
645 a_X(QUOTE_RNDTRIP, "quote-rndtrip")
646 a_X(PROMPT_CHAR, "prompt-char")
647 a_X(COMPLETE, "complete")
648 a_X(PASTE, "paste")
650 a_X(CANCEL, "cancel")
651 a_X(RESET, "reset")
652 a_X(FULLRESET, "fullreset")
653 a_X(COMMIT, "commit")
655 # undef a_X
657 # endif /* HAVE_KEY_BINDINGS */
659 /* The default key bindings (unless disallowed). Update manual upon change!
660 * A logical subset of this table is also used if !HAVE_KEY_BINDINGS (more
661 * expensive than a switch() on control codes directly, but less redundant) */
662 static struct a_tty_bind_default_tuple const a_tty_bind_default_tuples[] = {
663 # undef a_X
664 # define a_X(K,S) \
665 {TRU1, K, 0, {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
667 a_X('A', GO_HOME)
668 a_X('B', GO_BWD)
669 /* C: SIGINT */
670 a_X('D', DEL_FWD)
671 a_X('E', GO_END)
672 a_X('F', GO_FWD)
673 a_X('G', RESET)
674 a_X('H', DEL_BWD)
675 a_X('I', COMPLETE)
676 a_X('J', COMMIT)
677 a_X('K', SNARF_END)
678 a_X('L', REPAINT)
679 /* M: same as J */
680 a_X('N', HIST_FWD)
681 /* O: below */
682 a_X('P', HIST_BWD)
683 a_X('Q', QUOTE_RNDTRIP)
684 a_X('R', HIST_SRCH_BWD)
685 a_X('S', HIST_SRCH_FWD)
686 a_X('T', PASTE)
687 a_X('U', SNARF_LINE)
688 a_X('V', PROMPT_CHAR)
689 a_X('W', SNARF_WORD_BWD)
690 a_X('X', GO_WORD_FWD)
691 a_X('Y', GO_WORD_BWD)
692 /* Z: SIGTSTP */
694 a_X('[', CANCEL)
695 /* \: below */
696 /* ]: below */
697 /* ^: below */
698 a_X('_', SNARF_WORD_FWD)
700 a_X('?', DEL_BWD)
702 # undef a_X
703 # define a_X(K,S) {TRU1, K, 0, {S}},
705 a_X('O', "dt")
706 a_X('\\', "z+")
707 a_X(']', "z$")
708 a_X('^', "z0")
710 # ifdef HAVE_KEY_BINDINGS
711 # undef a_X
712 # define a_X(Q,S) \
713 {FAL0, '\0', n_TERMCAP_QUERY_ ## Q,\
714 {'\0', (char)a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## S),}},
716 a_X(key_backspace, DEL_BWD) a_X(key_dc, DEL_FWD)
717 a_X(key_eol, SNARF_END)
718 a_X(key_home, GO_HOME) a_X(key_end, GO_END)
719 a_X(key_left, GO_BWD) a_X(key_right, GO_FWD)
720 a_X(key_sleft, GO_HOME) a_X(key_sright, GO_END)
721 a_X(key_up, HIST_BWD) a_X(key_down, HIST_FWD)
723 # undef a_X
724 # define a_X(Q,S) {FAL0, '\0', n_TERMCAP_QUERY_ ## Q, {S}},
726 a_X(key_shome, "z0") a_X(key_send, "z$")
727 a_X(xkey_sup, "z0") a_X(xkey_sdown, "z$")
728 a_X(key_ppage, "z-") a_X(key_npage, "z+")
729 a_X(xkey_cup, "dotmove-") a_X(xkey_cdown, "dotmove+")
731 # endif /* HAVE_KEY_BINDINGS */
732 # undef a_X
735 static struct a_tty_global a_tty;
737 /* Change from canonical to raw, non-canonical mode, and way back */
738 static void a_tty_term_mode(bool_t raw);
740 /* Adjust an active raw mode to use / not use a timeout */
741 # ifdef HAVE_KEY_BINDINGS
742 static void a_tty_term_rawmode_timeout(struct a_tty_line *tlp, bool_t enable);
743 # endif
745 /* 0-X (2), UI8_MAX == \t / TAB */
746 static ui8_t a_tty_wcwidth(wchar_t wc);
748 /* Memory / cell / word generics */
749 static void a_tty_check_grow(struct a_tty_line *tlp, ui32_t no
750 SMALLOC_DEBUG_ARGS);
751 static ssize_t a_tty_cell2dat(struct a_tty_line *tlp);
752 static void a_tty_cell2save(struct a_tty_line *tlp);
754 /* Save away data bytes of given range (max = non-inclusive) */
755 static void a_tty_copy2paste(struct a_tty_line *tlp, struct a_tty_cell *tcpmin,
756 struct a_tty_cell *tcpmax);
758 /* Ask user for hexadecimal number, interpret as UTF-32 */
759 static wchar_t a_tty_vinuni(struct a_tty_line *tlp);
761 /* Visual screen synchronization */
762 static bool_t a_tty_vi_refresh(struct a_tty_line *tlp);
764 static bool_t a_tty_vi__paint(struct a_tty_line *tlp);
766 /* Search for word boundary, starting at tl_cursor, in "dir"ection (<> 0).
767 * Return <0 when moving is impossible (backward direction but in position 0,
768 * forward direction but in outermost column), and relative distance to
769 * tl_cursor otherwise */
770 static si32_t a_tty_wboundary(struct a_tty_line *tlp, si32_t dir);
772 /* Most function implementations */
773 static void a_tty_khome(struct a_tty_line *tlp, bool_t dobell);
774 static void a_tty_kend(struct a_tty_line *tlp);
775 static void a_tty_kbs(struct a_tty_line *tlp);
776 static void a_tty_ksnarf(struct a_tty_line *tlp, bool_t cplline, bool_t dobell);
777 static si32_t a_tty_kdel(struct a_tty_line *tlp);
778 static void a_tty_kleft(struct a_tty_line *tlp);
779 static void a_tty_kright(struct a_tty_line *tlp);
780 static void a_tty_ksnarfw(struct a_tty_line *tlp, bool_t fwd);
781 static void a_tty_kgow(struct a_tty_line *tlp, si32_t dir);
782 static bool_t a_tty_kother(struct a_tty_line *tlp, wchar_t wc);
783 static ui32_t a_tty_kht(struct a_tty_line *tlp);
785 # ifdef HAVE_HISTORY
786 /* Return UI32_MAX on "exhaustion" */
787 static ui32_t a_tty_khist(struct a_tty_line *tlp, bool_t fwd);
788 static ui32_t a_tty_khist_search(struct a_tty_line *tlp, bool_t fwd);
790 static ui32_t a_tty__khist_shared(struct a_tty_line *tlp,
791 struct a_tty_hist *thp);
792 # endif
794 /* Handle a function */
795 static enum a_tty_fun_status a_tty_fun(struct a_tty_line *tlp,
796 enum a_tty_bind_flags tbf, size_t *len);
798 /* Readline core */
799 static ssize_t a_tty_readline(struct a_tty_line *tlp, size_t len
800 SMALLOC_DEBUG_ARGS);
802 # ifdef HAVE_KEY_BINDINGS
803 /* Find context or -1 */
804 static enum n_lexinput_flags a_tty_bind_ctx_find(char const *name);
806 /* Create (or replace, if allowed) a binding */
807 static bool_t a_tty_bind_create(struct a_tty_bind_parse_ctx *tbpcp,
808 bool_t replace);
810 /* Shared implementation to parse `bind' and `unbind' "key-sequence" and
811 * "expansion" command line arguments into something that we can work with */
812 static bool_t a_tty_bind_parse(bool_t isbindcmd,
813 struct a_tty_bind_parse_ctx *tbpcp);
815 /* Lazy resolve a termcap(5)/terminfo(5) (or *termcap*!) capability */
816 static void a_tty_bind_resolve(struct a_tty_bind_ctx *tbcp);
818 /* Delete an existing binding */
819 static void a_tty_bind_del(struct a_tty_bind_parse_ctx *tbpcp);
821 /* Life cycle of all input node trees */
822 static void a_tty_bind_tree_build(void);
823 static void a_tty_bind_tree_teardown(void);
825 static void a_tty__bind_tree_add(ui32_t hmap_idx,
826 struct a_tty_bind_tree *store[HSHSIZE],
827 struct a_tty_bind_ctx *tbcp);
828 static struct a_tty_bind_tree *a_tty__bind_tree_add_wc(
829 struct a_tty_bind_tree **treep, struct a_tty_bind_tree *parentp,
830 wchar_t wc, bool_t isseq);
831 static void a_tty__bind_tree_free(struct a_tty_bind_tree *tbtp);
832 # endif /* HAVE_KEY_BINDINGS */
834 static void
835 a_tty_term_mode(bool_t raw){
836 struct termios *tiosp;
837 NYD2_ENTER;
839 tiosp = &a_tty.tg_tios_old;
840 if(!raw)
841 goto jleave;
843 /* Always requery the attributes, in case we've been moved from background
844 * to foreground or however else in between sessions */
845 /* XXX Always enforce ECHO and ICANON in the OLD attributes - do so as long
846 * XXX as we don't properly deal with TTIN and TTOU etc. */
847 tcgetattr(STDIN_FILENO, tiosp);
848 tiosp->c_lflag |= ECHO | ICANON;
850 memcpy(&a_tty.tg_tios_new, tiosp, sizeof *tiosp);
851 tiosp = &a_tty.tg_tios_new;
852 tiosp->c_cc[VMIN] = 1;
853 tiosp->c_cc[VTIME] = 0;
854 /* Enable ^\, ^Q and ^S to be used for key bindings */
855 tiosp->c_cc[VQUIT] = tiosp->c_cc[VSTART] = tiosp->c_cc[VSTOP] = '\0';
856 tiosp->c_iflag &= ~(ISTRIP | IGNCR);
857 tiosp->c_lflag &= ~(ECHO /*| ECHOE | ECHONL */| ICANON | IEXTEN);
858 jleave:
859 tcsetattr(STDIN_FILENO, TCSADRAIN, tiosp);
860 NYD2_LEAVE;
863 # ifdef HAVE_KEY_BINDINGS
864 static void
865 a_tty_term_rawmode_timeout(struct a_tty_line *tlp, bool_t enable){
866 NYD2_ENTER;
867 if(enable){
868 ui8_t bt;
870 a_tty.tg_tios_new.c_cc[VMIN] = 0;
871 if((bt = tlp->tl_bind_timeout) == 0)
872 bt = a_TTY_BIND_TIMEOUT;
873 a_tty.tg_tios_new.c_cc[VTIME] = bt;
874 }else{
875 a_tty.tg_tios_new.c_cc[VMIN] = 1;
876 a_tty.tg_tios_new.c_cc[VTIME] = 0;
878 tcsetattr(STDIN_FILENO, TCSANOW, &a_tty.tg_tios_new);
879 NYD2_LEAVE;
881 # endif /* HAVE_KEY_BINDINGS */
883 static ui8_t
884 a_tty_wcwidth(wchar_t wc){
885 ui8_t rv;
886 NYD2_ENTER;
888 /* Special case the backslash at first */
889 if(wc == '\t')
890 rv = UI8_MAX;
891 else{
892 int i;
894 # ifdef HAVE_WCWIDTH
895 rv = ((i = wcwidth(wc)) > 0) ? (ui8_t)i : 0;
896 # else
897 rv = iswprint(wc) ? 1 + (wc >= 0x1100u) : 0; /* TODO use S-CText */
898 # endif
900 NYD2_LEAVE;
901 return rv;
904 static void
905 a_tty_check_grow(struct a_tty_line *tlp, ui32_t no SMALLOC_DEBUG_ARGS){
906 ui32_t cmax;
907 NYD2_ENTER;
909 if(UNLIKELY((cmax = tlp->tl_count + no) > tlp->tl_count_max)){
910 size_t i;
912 i = cmax * sizeof(struct a_tty_cell) + 2 * sizeof(struct a_tty_cell);
913 if(LIKELY(i >= *tlp->tl_x_bufsize)){
914 hold_all_sigs(); /* XXX v15 drop */
915 i <<= 1;
916 tlp->tl_line.cbuf =
917 *tlp->tl_x_buf = (srealloc)(*tlp->tl_x_buf, i SMALLOC_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(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(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 LCTA(sizeof emsg <= sizeof(buf));
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, TRU1);
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(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(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(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(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(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(LIKELY(i > 0)){
1632 tlp->tl_count = --cnt;
1634 if(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(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(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(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(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(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(UNLIKELY((options & OPT_ENC_MBSTATE) != 0)){
1769 l = wcrtomb(&tc.tc_cbuf[l], L'\0', &ps);
1770 if(LIKELY(l == 1))
1771 /* Only NUL terminator */;
1772 else if(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_shell_parse_token(NULL, &sub, n_SHEXP_PARSE_DRYRUN |
1865 n_SHEXP_PARSE_TRIMSPACE | n_SHEXP_PARSE_IGNORE_EMPTY);
1866 if(sub.l != 0){
1867 size_t x;
1869 assert(max >= sub.l);
1870 x = max - sub.l;
1871 bot.l += x;
1872 max -= x;
1873 continue;
1875 if(shs & n_SHEXP_STATE_ERR_MASK){
1876 n_err(_("Invalid completion pattern: %.*s\n"),
1877 (int)exp.l, exp.s);
1878 goto jnope;
1880 n_shell_parse_token(shoup, &exp,
1881 n_SHEXP_PARSE_TRIMSPACE | n_SHEXP_PARSE_IGNORE_EMPTY);
1882 break;
1885 sub.s = n_string_cp(shoup);
1886 sub.l = shoup->s_len;
1890 /* Leave room for "implicit asterisk" expansion, as below */
1891 if(sub.l == 0){
1892 wedid = TRU1;
1893 sub.s = UNCONST("*");
1894 sub.l = 1;
1897 wedid = FAL0;
1898 jredo:
1899 /* TODO Super-Heavy-Metal: block all sigs, avoid leaks on jump */
1900 hold_all_sigs();
1901 exp.s = fexpand(sub.s, a_TTY_TAB_FEXP_FL);
1902 rele_all_sigs();
1904 if(exp.s == NULL || (exp.l = strlen(exp.s)) == 0)
1905 goto jnope;
1907 /* May be multi-return! */
1908 if(pstate & PS_EXPAND_MULTIRESULT)
1909 goto jmulti;
1911 /* xxx That is not really true since the limit counts characters not bytes */
1912 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1913 if(exp.l + 1 >= a_TTY_LINE_MAX){
1914 n_err(_("Tabulator expansion would extend beyond line size limit\n"));
1915 goto jnope;
1918 /* If the expansion equals the original string, assume the user wants what
1919 * is usually known as tab completion, append `*' and restart */
1920 if(!wedid && exp.l == sub.l && !memcmp(exp.s, sub.s, exp.l)){
1921 if(sub.s[sub.l - 1] == '*')
1922 goto jnope;
1924 wedid = TRU1;
1925 sub.s[sub.l++] = '*';
1926 sub.s[sub.l] = '\0';
1927 goto jredo;
1929 /* If it is a directory, and there is not yet a / appended, then we want the
1930 * user to confirm that he wants to dive in -- with only a HT */
1931 else if(wedid && exp.l == --sub.l && !memcmp(exp.s, sub.s, exp.l) &&
1932 exp.s[exp.l - 1] != '/'){
1933 if(stat(exp.s, &sb) || !S_ISDIR(sb.st_mode))
1934 goto jnope;
1935 sub.s = salloc(exp.l + 1 +1);
1936 memcpy(sub.s, exp.s, exp.l);
1937 sub.s[exp.l++] = '/';
1938 sub.s[exp.l] = '\0';
1939 exp.s = sub.s;
1940 wedid = FAL0;
1941 goto jset;
1942 }else{
1943 if(wedid && (wedid = (exp.s[exp.l - 1] == '*')))
1944 --exp.l;
1945 exp.s[exp.l] = '\0';
1946 jset:
1947 exp.l = strlen(exp.s = n_shell_quote_cp(exp.s, tlp->tl_quote_rndtrip));
1948 tlp->tl_defc_cursor_byte = bot.l + exp.l -1;
1949 if(wedid)
1950 goto jnope;
1953 orig.l = bot.l + exp.l + topp.l;
1954 orig.s = salloc(orig.l + 5 +1);
1955 if((rv = (ui32_t)bot.l) > 0)
1956 memcpy(orig.s, bot.s, rv);
1957 memcpy(orig.s + rv, exp.s, exp.l);
1958 rv += exp.l;
1959 if(topp.l > 0){
1960 memcpy(orig.s + rv, topp.s, topp.l);
1961 rv += topp.l;
1963 orig.s[rv] = '\0';
1965 tlp->tl_defc = orig;
1966 tlp->tl_count = tlp->tl_cursor = 0;
1967 f |= a_TTY_VF_MOD_DIRTY;
1968 jleave:
1969 n_string_gut(shoup);
1970 tlp->tl_vi_flags |= f;
1971 NYD2_LEAVE;
1972 return rv;
1974 jmulti:{
1975 struct n_visual_info_ctx vic;
1976 struct str input;
1977 wc_t c2, c1;
1978 bool_t isfirst;
1979 char const *lococp;
1980 size_t locolen, scrwid, lnlen, lncnt, prefixlen;
1981 FILE *fp;
1983 if((fp = Ftmp(NULL, "tabex", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
1984 n_perr(_("tmpfile"), 0);
1985 fp = stdout;
1988 /* How long is the result string for real? Search the NUL NUL
1989 * terminator. While here, detect the longest entry to perform an
1990 * initial allocation of our accumulator string */
1991 locolen = 0;
1993 size_t i;
1995 i = strlen(&exp.s[++exp.l]);
1996 locolen = MAX(locolen, i);
1997 exp.l += i;
1998 }while(exp.s[exp.l + 1] != '\0');
2000 shoup = n_string_reserve(n_string_trunc(shoup, 0),
2001 locolen + (locolen >> 1));
2003 /* Iterate (once again) over all results */
2004 scrwid = (size_t)scrnwidth - ((size_t)scrnwidth >> 3);
2005 lnlen = lncnt = 0;
2006 UNINIT(prefixlen, 0);
2007 UNINIT(lococp, NULL);
2008 UNINIT(c1, '\0');
2009 for(isfirst = TRU1; exp.l > 0; isfirst = FAL0, c1 = c2){
2010 size_t i;
2011 char const *fullpath;
2013 /* Next result */
2014 sub = exp;
2015 sub.l = i = strlen(sub.s);
2016 assert(exp.l >= i);
2017 if((exp.l -= i) > 0)
2018 --exp.l;
2019 exp.s += ++i;
2021 /* Separate dirname and basename */
2022 fullpath = sub.s;
2023 if(isfirst){
2024 char const *cp;
2026 if((cp = strrchr(fullpath, '/')) != NULL)
2027 prefixlen = PTR2SIZE(++cp - fullpath);
2028 else
2029 prefixlen = 0;
2031 if(prefixlen > 0 && prefixlen < sub.l){
2032 sub.l -= prefixlen;
2033 sub.s += prefixlen;
2036 /* We want case-insensitive sort-order */
2037 memset(&vic, 0, sizeof vic);
2038 vic.vic_indat = sub.s;
2039 vic.vic_inlen = sub.l;
2040 c2 = n_visual_info(&vic, n_VISUAL_INFO_ONE_CHAR) ? vic.vic_waccu
2041 : (ui8_t)*sub.s;
2042 #ifdef HAVE_C90AMEND1
2043 c2 = towlower(c2);
2044 #else
2045 c2 = lowerconv(c2);
2046 #endif
2048 /* Query longest common prefix along the way */
2049 if(isfirst){
2050 c1 = c2;
2051 lococp = sub.s;
2052 locolen = sub.l;
2053 }else if(locolen > 0){
2054 for(i = 0; i < locolen; ++i)
2055 if(lococp[i] != sub.s[i]){
2056 i = field_detect_clip(i, lococp, i);
2057 locolen = i;
2058 break;
2062 /* Prepare display */
2063 input = sub;
2064 shoup = n_shell_quote(n_string_trunc(shoup, 0), &input,
2065 tlp->tl_quote_rndtrip);
2066 memset(&vic, 0, sizeof vic);
2067 vic.vic_indat = shoup->s_dat;
2068 vic.vic_inlen = shoup->s_len;
2069 if(!n_visual_info(&vic,
2070 n_VISUAL_INFO_SKIP_ERRORS | n_VISUAL_INFO_WIDTH_QUERY))
2071 vic.vic_vi_width = shoup->s_len;
2073 /* Put on screen. Indent follow lines of same sort slot */
2074 c1 = (c1 != c2);
2075 if(isfirst || c1 ||
2076 scrwid < lnlen || scrwid - lnlen <= vic.vic_vi_width + 2){
2077 putc('\n', fp);
2078 if(scrwid < lnlen)
2079 ++lncnt;
2080 ++lncnt, lnlen = 0;
2081 if(!isfirst && !c1)
2082 goto jsep;
2083 }else if(lnlen > 0){
2084 jsep:
2085 fputs(" ", fp);
2086 lnlen += 2;
2088 fputs(n_string_cp(shoup), fp);
2089 lnlen += vic.vic_vi_width;
2091 /* Support the known file name tagging
2092 * XXX *line-editor-completion-filetype* or so */
2093 if(!lstat(fullpath, &sb)){
2094 char c = '\0';
2096 if(S_ISDIR(sb.st_mode))
2097 c = '/';
2098 else if(S_ISLNK(sb.st_mode))
2099 c = '@';
2100 # ifdef S_ISFIFO
2101 else if(S_ISFIFO(sb.st_mode))
2102 c = '|';
2103 # endif
2104 # ifdef S_ISSOCK
2105 else if(S_ISSOCK(sb.st_mode))
2106 c = '=';
2107 # endif
2108 # ifdef S_ISCHR
2109 else if(S_ISCHR(sb.st_mode))
2110 c = '%';
2111 # endif
2112 # ifdef S_ISBLK
2113 else if(S_ISBLK(sb.st_mode))
2114 c = '#';
2115 # endif
2117 if(c != '\0'){
2118 putc(c, fp);
2119 ++lnlen;
2123 putc('\n', fp);
2124 ++lncnt;
2126 page_or_print(fp, lncnt);
2127 if(fp != stdout)
2128 Fclose(fp);
2130 n_string_gut(shoup);
2132 /* A common prefix of 0 means we cannot provide the user any auto
2133 * completed characters */
2134 if(locolen == 0)
2135 goto jnope;
2137 /* Otherwise we can, so extend the visual line content by the common
2138 * prefix (in a reversible way) */
2139 (exp.s = UNCONST(lococp))[locolen] = '\0';
2140 exp.s -= prefixlen;
2141 exp.l = (locolen += prefixlen);
2143 /* XXX Indicate that there is multiple choice */
2144 /* XXX f |= a_TTY_VF_BELL; -> *line-editor-completion-bell*? or so */
2145 wedid = FAL0;
2146 goto jset;
2149 jnope:
2150 /* If we've provided a default content, but failed to expand, there is
2151 * nothing we can "revert to": drop that default again */
2152 if(set_savec){
2153 tlp->tl_savec.s = NULL;
2154 tlp->tl_savec.l = 0;
2156 f = a_TTY_VF_NONE;
2157 rv = 0;
2158 goto jleave;
2161 # ifdef HAVE_HISTORY
2162 static ui32_t
2163 a_tty__khist_shared(struct a_tty_line *tlp, struct a_tty_hist *thp){
2164 ui32_t f, rv;
2165 NYD2_ENTER;
2167 if(LIKELY((tlp->tl_hist = thp) != NULL)){
2168 tlp->tl_defc.s = savestrbuf(thp->th_dat, thp->th_len);
2169 rv = tlp->tl_defc.l = thp->th_len;
2170 f = (tlp->tl_count > 0) ? a_TTY_VF_MOD_DIRTY : a_TTY_VF_NONE;
2171 tlp->tl_count = tlp->tl_cursor = 0;
2172 }else{
2173 f = a_TTY_VF_BELL;
2174 rv = UI32_MAX;
2177 tlp->tl_vi_flags |= f;
2178 NYD2_LEAVE;
2179 return rv;
2182 static ui32_t
2183 a_tty_khist(struct a_tty_line *tlp, bool_t fwd){
2184 struct a_tty_hist *thp;
2185 ui32_t rv;
2186 NYD2_ENTER;
2188 /* If we're not in history mode yet, save line content;
2189 * also, disallow forward search, then, and, of course, bail unless we
2190 * do have any history at all */
2191 if((thp = tlp->tl_hist) == NULL){
2192 if(fwd)
2193 goto jleave;
2194 if((thp = a_tty.tg_hist) == NULL)
2195 goto jleave;
2196 a_tty_cell2save(tlp);
2197 goto jleave;
2200 thp = fwd ? thp->th_younger : thp->th_older;
2201 jleave:
2202 rv = a_tty__khist_shared(tlp, thp);
2203 NYD2_LEAVE;
2204 return rv;
2207 static ui32_t
2208 a_tty_khist_search(struct a_tty_line *tlp, bool_t fwd){
2209 struct str orig_savec;
2210 struct a_tty_hist *thp;
2211 ui32_t rv;
2212 NYD2_ENTER;
2214 thp = NULL;
2216 /* We cannot complete an empty line */
2217 if(UNLIKELY(tlp->tl_count == 0)){
2218 /* XXX The upcoming hard reset would restore a set savec buffer,
2219 * XXX so forcefully reset that. A cleaner solution would be to
2220 * XXX reset it whenever a restore is no longer desired */
2221 tlp->tl_savec.s = NULL;
2222 tlp->tl_savec.l = 0;
2223 goto jleave;
2226 if((thp = tlp->tl_hist) == NULL){
2227 if((thp = a_tty.tg_hist) == NULL)
2228 goto jleave;
2229 /* We don't support wraparound, searching forward must always step */
2230 if(fwd)
2231 thp = thp->th_younger;
2232 orig_savec.s = NULL;
2233 orig_savec.l = 0; /* silence CC */
2234 }else if((thp = (fwd ? thp->th_younger : thp->th_older)) == NULL)
2235 goto jleave;
2236 else
2237 orig_savec = tlp->tl_savec;
2239 if(orig_savec.s == NULL)
2240 a_tty_cell2save(tlp);
2242 for(; thp != NULL; thp = (fwd ? thp->th_younger : thp->th_older))
2243 if(is_prefix(tlp->tl_savec.s, thp->th_dat))
2244 break;
2246 if(orig_savec.s != NULL)
2247 tlp->tl_savec = orig_savec;
2248 jleave:
2249 rv = a_tty__khist_shared(tlp, thp);
2250 NYD2_LEAVE;
2251 return rv;
2253 # endif /* HAVE_HISTORY */
2255 static enum a_tty_fun_status
2256 a_tty_fun(struct a_tty_line *tlp, enum a_tty_bind_flags tbf, size_t *len){
2257 enum a_tty_fun_status rv;
2258 NYD2_ENTER;
2260 rv = a_TTY_FUN_STATUS_OK;
2261 # undef a_X
2262 # define a_X(N) a_TTY_BIND_FUN_REDUCE(a_TTY_BIND_FUN_ ## N)
2263 switch(a_TTY_BIND_FUN_REDUCE(tbf)){
2264 case a_X(BELL):
2265 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2266 break;
2267 case a_X(GO_BWD):
2268 a_tty_kleft(tlp);
2269 break;
2270 case a_X(GO_FWD):
2271 a_tty_kright(tlp);
2272 break;
2273 case a_X(GO_WORD_BWD):
2274 a_tty_kgow(tlp, -1);
2275 break;
2276 case a_X(GO_WORD_FWD):
2277 a_tty_kgow(tlp, +1);
2278 break;
2279 case a_X(GO_HOME):
2280 a_tty_khome(tlp, TRU1);
2281 break;
2282 case a_X(GO_END):
2283 a_tty_kend(tlp);
2284 break;
2285 case a_X(DEL_BWD):
2286 a_tty_kbs(tlp);
2287 break;
2288 case a_X(DEL_FWD):
2289 if(a_tty_kdel(tlp) < 0)
2290 rv = a_TTY_FUN_STATUS_END;
2291 break;
2292 case a_X(SNARF_WORD_BWD):
2293 a_tty_ksnarfw(tlp, FAL0);
2294 break;
2295 case a_X(SNARF_WORD_FWD):
2296 a_tty_ksnarfw(tlp, TRU1);
2297 break;
2298 case a_X(SNARF_END):
2299 a_tty_ksnarf(tlp, FAL0, TRU1);
2300 break;
2301 case a_X(SNARF_LINE):
2302 a_tty_ksnarf(tlp, TRU1, (tlp->tl_count == 0));
2303 break;
2305 case a_X(HIST_FWD):
2306 # ifdef HAVE_HISTORY
2307 if(tlp->tl_hist != NULL){
2308 bool_t isfwd = TRU1;
2310 if(0){
2311 # endif
2312 /* FALLTHRU */
2313 case a_X(HIST_BWD):
2314 # ifdef HAVE_HISTORY
2315 isfwd = FAL0;
2317 if((*len = a_tty_khist(tlp, isfwd)) != UI32_MAX){
2318 rv = a_TTY_FUN_STATUS_RESTART;
2319 break;
2321 goto jreset;
2322 # endif
2324 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2325 break;
2327 case a_X(HIST_SRCH_FWD):{
2328 # ifdef HAVE_HISTORY
2329 bool_t isfwd = TRU1;
2331 if(0){
2332 # endif
2333 /* FALLTHRU */
2334 case a_X(HIST_SRCH_BWD):
2335 # ifdef HAVE_HISTORY
2336 isfwd = FAL0;
2338 if((*len = a_tty_khist_search(tlp, isfwd)) != UI32_MAX){
2339 rv = a_TTY_FUN_STATUS_RESTART;
2340 break;
2342 goto jreset;
2343 # else
2344 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2345 # endif
2346 } break;
2348 case a_X(REPAINT):
2349 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2350 break;
2351 case a_X(QUOTE_RNDTRIP):
2352 tlp->tl_quote_rndtrip = !tlp->tl_quote_rndtrip;
2353 break;
2354 case a_X(PROMPT_CHAR):{
2355 wchar_t wc;
2357 if((wc = a_tty_vinuni(tlp)) > 0)
2358 a_tty_kother(tlp, wc);
2359 } break;
2360 case a_X(COMPLETE):
2361 if((*len = a_tty_kht(tlp)) > 0)
2362 rv = a_TTY_FUN_STATUS_RESTART;
2363 break;
2365 case a_X(PASTE):
2366 if(tlp->tl_pastebuf.l > 0)
2367 *len = (tlp->tl_defc = tlp->tl_pastebuf).l;
2368 else
2369 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2370 break;
2373 case a_X(CANCEL):
2374 /* Normally this just causes a restart and thus resets the state
2375 * machine */
2376 if(tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2378 # ifdef HAVE_KEY_BINDINGS
2379 tlp->tl_bind_takeover = '\0';
2380 # endif
2381 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2382 rv = a_TTY_FUN_STATUS_RESTART;
2383 break;
2385 case a_X(RESET):
2386 if(tlp->tl_count == 0 && tlp->tl_savec.l == 0 && tlp->tl_defc.l == 0){
2387 # ifdef HAVE_KEY_BINDINGS
2388 tlp->tl_bind_takeover = '\0';
2389 # endif
2390 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY | a_TTY_VF_BELL;
2391 break;
2392 }else if(0){
2393 case a_X(FULLRESET):
2394 tlp->tl_savec.s = tlp->tl_defc.s = NULL;
2395 tlp->tl_savec.l = tlp->tl_defc.l = 0;
2396 tlp->tl_defc_cursor_byte = 0;
2397 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2399 jreset:
2400 # ifdef HAVE_KEY_BINDINGS
2401 tlp->tl_bind_takeover = '\0';
2402 # endif
2403 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
2404 tlp->tl_cursor = tlp->tl_count = 0;
2405 # ifdef HAVE_HISTORY
2406 tlp->tl_hist = NULL;
2407 # endif
2408 if((*len = tlp->tl_savec.l) != 0){
2409 tlp->tl_defc = tlp->tl_savec;
2410 tlp->tl_savec.s = NULL;
2411 tlp->tl_savec.l = 0;
2412 }else
2413 *len = tlp->tl_defc.l;
2414 rv = a_TTY_FUN_STATUS_RESTART;
2415 break;
2417 default:
2418 case a_X(COMMIT):
2419 rv = a_TTY_FUN_STATUS_COMMIT;
2420 break;
2422 # undef a_X
2424 NYD2_LEAVE;
2425 return rv;
2428 static ssize_t
2429 a_tty_readline(struct a_tty_line *tlp, size_t len SMALLOC_DEBUG_ARGS){
2430 /* We want to save code, yet we may have to incorporate a lines'
2431 * default content and / or default input to switch back to after some
2432 * history movement; let "len > 0" mean "have to display some data
2433 * buffer" -> a_BUFMODE, and only otherwise read(2) it */
2434 mbstate_t ps[2];
2435 char cbuf_base[MB_LEN_MAX * 2], *cbuf, *cbufp;
2436 ssize_t rv;
2437 struct a_tty_bind_tree *tbtp;
2438 wchar_t wc;
2439 enum a_tty_bind_flags tbf;
2440 enum {a_NONE, a_WAS_HERE = 1<<0, a_BUFMODE = 1<<1, a_MAYBEFUN = 1<<2,
2441 a_TIMEOUT = 1<<3, a_TIMEOUT_EXPIRED = 1<<4,
2442 a_TIMEOUT_MASK = a_TIMEOUT | a_TIMEOUT_EXPIRED,
2443 a_READ_LOOP_MASK = ~(a_WAS_HERE | a_MAYBEFUN | a_TIMEOUT_MASK)
2444 } flags;
2445 NYD_ENTER;
2447 UNINIT(rv, 0);
2448 # ifdef HAVE_KEY_BINDINGS
2449 assert(tlp->tl_bind_takeover == '\0');
2450 # endif
2451 jrestart:
2452 memset(ps, 0, sizeof ps);
2453 flags = a_NONE;
2454 tbf = 0;
2455 tlp->tl_vi_flags |= a_TTY_VF_REFRESH | a_TTY_VF_SYNC;
2457 jinput_loop:
2458 for(;;){
2459 if(len != 0)
2460 flags |= a_BUFMODE;
2462 /* Ensure we have valid pointers, and room for grow */
2463 a_tty_check_grow(tlp, ((flags & a_BUFMODE) ? (ui32_t)len : 1)
2464 SMALLOC_DEBUG_ARGSCALL);
2466 /* Handle visual state flags, except in buffer mode */
2467 if(!(flags & a_BUFMODE) && (tlp->tl_vi_flags & a_TTY_VF_ALL_MASK))
2468 if(!a_tty_vi_refresh(tlp)){
2469 rv = -1;
2470 goto jleave;
2473 /* Ready for messing around.
2474 * Normal read(2)? Else buffer mode: speed this one up */
2475 if(!(flags & a_BUFMODE)){
2476 cbufp =
2477 cbuf = cbuf_base;
2478 }else{
2479 assert(tlp->tl_defc.l > 0 && tlp->tl_defc.s != NULL);
2480 assert(tlp->tl_defc.l >= len);
2481 cbufp =
2482 cbuf = tlp->tl_defc.s + (tlp->tl_defc.l - len);
2483 cbufp += len;
2486 /* Read in the next complete multibyte character */
2487 /* C99 */{
2488 # ifdef HAVE_KEY_BINDINGS
2489 struct a_tty_bind_tree *xtbtp;
2490 struct inseq{
2491 struct inseq *last;
2492 struct inseq *next;
2493 struct a_tty_bind_tree *tbtp;
2494 } *isp_head, *isp;
2496 isp_head = isp = NULL;
2497 # endif
2499 for(flags &= a_READ_LOOP_MASK;;){
2500 # ifdef HAVE_KEY_BINDINGS
2501 if(!(flags & a_BUFMODE) && tlp->tl_bind_takeover != '\0'){
2502 wc = tlp->tl_bind_takeover;
2503 tlp->tl_bind_takeover = '\0';
2504 }else
2505 # endif
2507 if(!(flags & a_BUFMODE)){
2508 /* Let me at least once dream of iomon(itor), timer with
2509 * one-shot, enwrapped with key_event and key_sequence_event,
2510 * all driven by an event_loop */
2511 /* TODO v15 Until we have SysV signal handling all through we
2512 * TODO need to temporarily adjust our BSD signal handler with
2513 * TODO a SysV one, here */
2514 n_sighdl_t otstp, ottin, ottou;
2516 otstp = n_signal(SIGTSTP, &n_tty_signal);
2517 ottin = n_signal(SIGTTIN, &n_tty_signal);
2518 ottou = n_signal(SIGTTOU, &n_tty_signal);
2519 # ifdef HAVE_KEY_BINDINGS
2520 flags &= ~a_TIMEOUT_MASK;
2521 if(isp != NULL && (tbtp = isp->tbtp)->tbt_isseq &&
2522 !tbtp->tbt_isseq_trail){
2523 a_tty_term_rawmode_timeout(tlp, TRU1);
2524 flags |= a_TIMEOUT;
2526 # endif
2528 while((rv = read(STDIN_FILENO, cbufp, 1)) < 1){
2529 if(rv == -1){
2530 if(errno == EINTR){
2531 if((tlp->tl_vi_flags & a_TTY_VF_MOD_DIRTY) &&
2532 !a_tty_vi_refresh(tlp))
2533 break;
2534 continue;
2536 break;
2539 # ifdef HAVE_KEY_BINDINGS
2540 /* Timeout expiration */
2541 if(rv == 0){
2542 assert(flags & a_TIMEOUT);
2543 assert(isp != NULL);
2544 a_tty_term_rawmode_timeout(tlp, FAL0);
2546 /* Something "atomic" broke. Maybe the current one can
2547 * also be terminated already, by itself? xxx really? */
2548 if((tbtp = isp->tbtp)->tbt_bind != NULL){
2549 tlp->tl_bind_takeover = wc;
2550 goto jhave_bind;
2553 /* Or, maybe there is a second path without a timeout;
2554 * this should be covered by .tbt_isseq_trail, but then
2555 * again a single-layer implementation cannot "know" */
2556 for(xtbtp = tbtp; (xtbtp = xtbtp->tbt_sibling) != NULL;)
2557 if(xtbtp->tbt_char == tbtp->tbt_char){
2558 assert(!xtbtp->tbt_isseq);
2559 break;
2561 /* Lay down on read(2)? */
2562 if(xtbtp != NULL)
2563 continue;
2564 goto jtake_over;
2566 # endif /* HAVE_KEY_BINDINGS */
2569 # ifdef HAVE_KEY_BINDINGS
2570 if(flags & a_TIMEOUT)
2571 a_tty_term_rawmode_timeout(tlp, FAL0);
2572 # endif
2573 safe_signal(SIGTSTP, otstp);
2574 safe_signal(SIGTTIN, ottin);
2575 safe_signal(SIGTTOU, ottou);
2576 if(rv < 0)
2577 goto jleave;
2579 ++cbufp;
2582 rv = (ssize_t)mbrtowc(&wc, cbuf, PTR2SIZE(cbufp - cbuf), &ps[0]);
2583 if(rv <= 0){
2584 /* Any error during buffer mode can only result in a hard
2585 * reset; Otherwise, if it's a hard error, or if too many
2586 * redundant shift sequences overflow our buffer: perform
2587 * hard reset */
2588 if((flags & a_BUFMODE) || rv == -1 ||
2589 sizeof cbuf_base == PTR2SIZE(cbufp - cbuf)){
2590 a_tty_fun(tlp, a_TTY_BIND_FUN_FULLRESET, &len);
2591 goto jrestart;
2593 /* Otherwise, due to the way we deal with the buffer, we need
2594 * to restore the mbstate_t from before this conversion */
2595 ps[0] = ps[1];
2596 continue;
2598 cbufp = cbuf;
2599 ps[1] = ps[0];
2602 /* Normal read(2)ing is subject to detection of key-bindings */
2603 # ifdef HAVE_KEY_BINDINGS
2604 if(!(flags & a_BUFMODE)){
2605 /* Check for special bypass functions before we try to embed
2606 * this character into the tree */
2607 if(n_uasciichar(wc)){
2608 char c;
2609 char const *cp;
2611 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_prompt_char)[0];
2612 *cp != '\0'; ++cp){
2613 if(c == *cp){
2614 wc = a_tty_vinuni(tlp);
2615 break;
2618 if(wc == '\0'){
2619 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2620 goto jinput_loop;
2623 if(n_uasciichar(wc))
2624 flags |= a_MAYBEFUN;
2625 else
2626 flags &= ~a_MAYBEFUN;
2628 /* Search for this character in the bind tree */
2629 tbtp = (isp != NULL) ? isp->tbtp->tbt_childs
2630 : (*tlp->tl_bind_tree_hmap)[wc % HSHSIZE];
2631 for(; tbtp != NULL; tbtp = tbtp->tbt_sibling){
2632 if(tbtp->tbt_char == wc){
2633 struct inseq *nisp;
2635 /* If this one cannot continue we're likely finished! */
2636 if(tbtp->tbt_childs == NULL){
2637 assert(tbtp->tbt_bind != NULL);
2638 tbf = tbtp->tbt_bind->tbc_flags;
2639 goto jmle_fun;
2642 /* This needs to read more characters */
2643 nisp = salloc(sizeof *nisp);
2644 if((nisp->last = isp) == NULL)
2645 isp_head = nisp;
2646 else
2647 isp->next = nisp;
2648 nisp->next = NULL;
2649 nisp->tbtp = tbtp;
2650 isp = nisp;
2651 flags &= ~a_WAS_HERE;
2652 break;
2655 if(tbtp != NULL)
2656 continue;
2658 /* Was there a binding active, but couldn't be continued? */
2659 if(isp != NULL){
2660 /* A binding had a timeout, it didn't expire, but we saw
2661 * something non-expected. Something "atomic" broke.
2662 * Maybe there is a second path without a timeout, that
2663 * continues like we've seen it. I.e., it may just have been
2664 * the user, typing two fast. We definitely want to allow
2665 * bindings like \e,d etc. to succeed: users are so used to
2666 * them that a timeout cannot be the mechanism to catch up!
2667 * A single-layer implementation cannot "know" */
2668 if((tbtp = isp->tbtp)->tbt_isseq && (isp->last == NULL ||
2669 !(xtbtp = isp->last->tbtp)->tbt_isseq ||
2670 xtbtp->tbt_isseq_trail)){
2671 for(xtbtp = (tbtp = isp->tbtp);
2672 (xtbtp = xtbtp->tbt_sibling) != NULL;)
2673 if(xtbtp->tbt_char == tbtp->tbt_char){
2674 assert(!xtbtp->tbt_isseq);
2675 break;
2677 if(xtbtp != NULL){
2678 isp->tbtp = xtbtp;
2679 tlp->tl_bind_takeover = wc;
2680 continue;
2684 /* Check for CANCEL shortcut now */
2685 if(flags & a_MAYBEFUN){
2686 char c;
2687 char const *cp;
2689 for(c = (char)wc, cp = &(*tlp->tl_bind_shcut_cancel)[0];
2690 *cp != '\0'; ++cp)
2691 if(c == *cp){
2692 tbf = a_TTY_BIND_FUN_INTERNAL |a_TTY_BIND_FUN_CANCEL;
2693 goto jmle_fun;
2697 /* So: maybe the current sequence can be terminated here? */
2698 if((tbtp = isp->tbtp)->tbt_bind != NULL){
2699 jhave_bind:
2700 tbf = tbtp->tbt_bind->tbc_flags;
2701 jmle_fun:
2702 if(tbf & a_TTY_BIND_FUN_INTERNAL){
2703 switch(a_tty_fun(tlp, tbf, &len)){
2704 case a_TTY_FUN_STATUS_OK:
2705 goto jinput_loop;
2706 case a_TTY_FUN_STATUS_COMMIT:
2707 goto jdone;
2708 case a_TTY_FUN_STATUS_RESTART:
2709 goto jrestart;
2710 case a_TTY_FUN_STATUS_END:
2711 goto jleave;
2713 assert(0);
2714 }else if(tbtp->tbt_bind->tbc_flags & a_TTY_BIND_NOCOMMIT){
2715 struct a_tty_bind_ctx *tbcp;
2717 tbcp = tbtp->tbt_bind;
2718 memcpy(tlp->tl_defc.s = salloc(
2719 (tlp->tl_defc.l = len = tbcp->tbc_exp_len) +1),
2720 tbcp->tbc_exp, tbcp->tbc_exp_len +1);
2721 goto jrestart;
2722 }else{
2723 tlp->tl_reenter_after_cmd = tbtp->tbt_bind->tbc_exp;
2724 goto jdone;
2729 /* Otherwise take over all chars "as is" */
2730 jtake_over:
2731 for(; isp_head != NULL; isp_head = isp_head->next)
2732 if(a_tty_kother(tlp, isp_head->tbtp->tbt_char)){
2733 /* FIXME */
2735 /* And the current one too */
2736 goto jkother;
2738 # endif /* HAVE_KEY_BINDINGS */
2740 if((flags & a_BUFMODE) && (len -= (size_t)rv) == 0){
2741 /* Buffer mode completed */
2742 tlp->tl_defc.s = NULL;
2743 tlp->tl_defc.l = 0;
2744 flags &= ~a_BUFMODE;
2746 break;
2749 # ifndef HAVE_KEY_BINDINGS
2750 /* Don't interpret control bytes during buffer mode.
2751 * Otherwise, if it's a control byte check whether it is a MLE
2752 * function. Remarks: initially a complete duplicate to be able to
2753 * switch(), later converted to simply iterate over (an #ifdef'd
2754 * subset of) the MLE default_tuple table in order to have "a SPOF" */
2755 if(cbuf == cbuf_base && n_uasciichar(wc) && cntrlchar((char)wc)){
2756 struct a_tty_bind_default_tuple const *tbdtp;
2757 char c;
2759 for(c = (char)wc ^ 0x40, tbdtp = a_tty_bind_default_tuples;
2760 PTRCMP(tbdtp, <, &a_tty_bind_default_tuples[
2761 NELEM(a_tty_bind_default_tuples)]);
2762 ++tbdtp){
2763 /* Assert default_tuple table is properly subset'ed */
2764 assert(tbdtp->tbdt_iskey);
2765 if(tbdtp->tbdt_ckey == c){
2766 if(tbdtp->tbdt_exp[0] == '\0'){
2767 enum a_tty_bind_flags tbf;
2769 tbf = a_TTY_BIND_FUN_EXPAND((ui8_t)tbdtp->tbdt_exp[1]);
2770 switch(a_tty_fun(tlp, tbf, &len)){
2771 case a_TTY_FUN_STATUS_OK:
2772 goto jinput_loop;
2773 case a_TTY_FUN_STATUS_COMMIT:
2774 goto jdone;
2775 case a_TTY_FUN_STATUS_RESTART:
2776 goto jrestart;
2777 case a_TTY_FUN_STATUS_END:
2778 goto jleave;
2780 assert(0);
2781 }else{
2782 tlp->tl_reenter_after_cmd = tbdtp->tbdt_exp;
2783 goto jdone;
2788 # endif /* !HAVE_KEY_BINDINGS */
2790 # ifdef HAVE_KEY_BINDINGS
2791 jkother:
2792 # endif
2793 if(a_tty_kother(tlp, wc)){
2794 /* Don't clear the history during buffer mode.. */
2795 # ifdef HAVE_HISTORY
2796 if(!(flags & a_BUFMODE) && cbuf == cbuf_base)
2797 tlp->tl_hist = NULL;
2798 # endif
2803 /* We have a completed input line, convert the struct cell data to its
2804 * plain character equivalent */
2805 jdone:
2806 rv = a_tty_cell2dat(tlp);
2807 jleave:
2808 putchar('\n');
2809 fflush(stdout);
2810 NYD_LEAVE;
2811 return rv;
2814 # ifdef HAVE_KEY_BINDINGS
2815 static enum n_lexinput_flags
2816 a_tty_bind_ctx_find(char const *name){
2817 enum n_lexinput_flags rv;
2818 struct a_tty_bind_ctx_map const *tbcmp;
2819 NYD2_ENTER;
2821 tbcmp = a_tty_bind_ctx_maps;
2822 do if(!asccasecmp(tbcmp->tbcm_name, name)){
2823 rv = tbcmp->tbcm_ctx;
2824 goto jleave;
2825 }while(PTRCMP(++tbcmp, <, &a_tty_bind_ctx_maps[NELEM(a_tty_bind_ctx_maps)]));
2827 rv = (enum n_lexinput_flags)-1;
2828 jleave:
2829 NYD2_LEAVE;
2830 return rv;
2833 static bool_t
2834 a_tty_bind_create(struct a_tty_bind_parse_ctx *tbpcp, bool_t replace){
2835 struct a_tty_bind_ctx *tbcp;
2836 bool_t rv;
2837 NYD2_ENTER;
2839 rv = FAL0;
2841 if(!a_tty_bind_parse(TRU1, tbpcp))
2842 goto jleave;
2844 /* Since we use a single buffer for it all, need to replace as such */
2845 if(tbpcp->tbpc_tbcp != NULL){
2846 if(!replace)
2847 goto jleave;
2848 a_tty_bind_del(tbpcp);
2849 }else if(a_tty.tg_bind_cnt == UI32_MAX){
2850 n_err(_("`bind': maximum number of bindings already established\n"));
2851 goto jleave;
2854 /* C99 */{
2855 size_t i, j;
2857 tbcp = smalloc(sizeof(*tbcp) -
2858 VFIELD_SIZEOF(struct a_tty_bind_ctx, tbc__buf) +
2859 tbpcp->tbpc_seq_len + tbpcp->tbpc_exp.l + tbpcp->tbpc_cnv_len +3);
2860 if(tbpcp->tbpc_ltbcp != NULL){
2861 tbcp->tbc_next = tbpcp->tbpc_ltbcp->tbc_next;
2862 tbpcp->tbpc_ltbcp->tbc_next = tbcp;
2863 }else{
2864 enum n_lexinput_flags lif = tbpcp->tbpc_flags & n__LEXINPUT_CTX_MASK;
2866 tbcp->tbc_next = a_tty.tg_bind[lif];
2867 a_tty.tg_bind[lif] = tbcp;
2869 memcpy(tbcp->tbc_seq = &tbcp->tbc__buf[0],
2870 tbpcp->tbpc_seq, i = (tbcp->tbc_seq_len = tbpcp->tbpc_seq_len) +1);
2871 memcpy(tbcp->tbc_exp = &tbcp->tbc__buf[i],
2872 tbpcp->tbpc_exp.s, j = (tbcp->tbc_exp_len = tbpcp->tbpc_exp.l) +1);
2873 memcpy(tbcp->tbc_cnv = &tbcp->tbc__buf[i += j],
2874 tbpcp->tbpc_cnv, (tbcp->tbc_cnv_len = tbpcp->tbpc_cnv_len) +1);
2875 tbcp->tbc_flags = tbpcp->tbpc_flags;
2878 /* Directly resolve any termcap(5) symbol if we are already setup */
2879 if((pstate & PS_STARTED) &&
2880 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
2881 a_TTY_BIND_RESOLVE)
2882 a_tty_bind_resolve(tbcp);
2884 ++a_tty.tg_bind_cnt;
2885 /* If this binding is usable invalidate the key input lookup trees */
2886 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
2887 a_tty.tg_bind_isdirty = TRU1;
2888 rv = TRU1;
2889 jleave:
2890 NYD2_LEAVE;
2891 return rv;
2894 static bool_t
2895 a_tty_bind_parse(bool_t isbindcmd, struct a_tty_bind_parse_ctx *tbpcp){
2896 enum{a_TRUE_RV = a_TTY__BIND_LAST<<1};
2898 struct n_visual_info_ctx vic;
2899 struct str shin_save, shin;
2900 struct n_string shou, *shoup;
2901 size_t i;
2902 struct kse{
2903 struct kse *next;
2904 char *seq_dat;
2905 wc_t *cnv_dat;
2906 ui32_t seq_len;
2907 ui32_t cnv_len; /* High bit set if a termap to be resolved */
2908 ui32_t calc_cnv_len; /* Ditto, but aligned etc. */
2909 } *head, *tail;
2910 ui32_t f;
2911 NYD2_ENTER;
2912 n_LCTA(UICMP(64, a_TRUE_RV, <, UI32_MAX),
2913 "Flag bits excess storage datatype");
2915 f = n_LEXINPUT_NONE;
2916 shoup = n_string_creat_auto(&shou);
2917 head = tail = NULL;
2919 /* Parse the key-sequence */
2920 for(shin.s = UNCONST(tbpcp->tbpc_in_seq), shin.l = UIZ_MAX;;){
2921 struct kse *ep;
2922 enum n_shexp_state shs;
2924 shin_save = shin;
2925 shs = n_shell_parse_token(shoup, &shin,
2926 n_SHEXP_PARSE_TRUNC | n_SHEXP_PARSE_TRIMSPACE |
2927 n_SHEXP_PARSE_IGNORE_EMPTY | n_SHEXP_PARSE_IFS_IS_COMMA);
2928 if(shs & n_SHEXP_STATE_ERR_UNICODE){
2929 f |= a_TTY_BIND_DEFUNCT;
2930 if(isbindcmd && (options & OPT_D_V))
2931 n_err(_("`%s': \\uNICODE not available in locale: %s\n"),
2932 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
2934 if((shs & n_SHEXP_STATE_ERR_MASK) & ~n_SHEXP_STATE_ERR_UNICODE){
2935 n_err(_("`%s': failed to parse key-sequence: %s\n"),
2936 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
2937 goto jleave;
2939 if((shs & (n_SHEXP_STATE_OUTPUT | n_SHEXP_STATE_STOP)) ==
2940 n_SHEXP_STATE_STOP)
2941 break;
2943 ep = salloc(sizeof *ep);
2944 if(head == NULL)
2945 head = ep;
2946 else
2947 tail->next = ep;
2948 tail = ep;
2949 ep->next = NULL;
2950 if(!(shs & n_SHEXP_STATE_ERR_UNICODE)){
2951 i = strlen(ep->seq_dat = n_shell_quote_cp(n_string_cp(shoup), TRU1));
2952 if(i >= SI32_MAX - 1)
2953 goto jelen;
2954 ep->seq_len = (ui32_t)i;
2955 }else{
2956 /* Otherwise use the original buffer, _we_ can only quote it the wrong
2957 * way (e.g., an initial $'\u3a' becomes '\u3a'), _then_ */
2958 if((i = shin_save.l - shin.l) >= SI32_MAX - 1)
2959 goto jelen;
2960 ep->seq_len = (ui32_t)i;
2961 ep->seq_dat = savestrbuf(shin_save.s, i);
2964 memset(&vic, 0, sizeof vic);
2965 vic.vic_inlen = shoup->s_len;
2966 vic.vic_indat = shoup->s_dat;
2967 if(!n_visual_info(&vic,
2968 n_VISUAL_INFO_WOUT_CREATE | n_VISUAL_INFO_WOUT_SALLOC)){
2969 n_err(_("`%s': key-sequence seems to contain invalid "
2970 "characters: %s: %s\n"),
2971 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
2972 f |= a_TTY_BIND_DEFUNCT;
2973 goto jleave;
2974 }else if(vic.vic_woulen == 0 ||
2975 vic.vic_woulen >= (SI32_MAX - 2) / sizeof(wc_t)){
2976 jelen:
2977 n_err(_("`%s': length of key-sequence unsupported: %s: %s\n"),
2978 tbpcp->tbpc_cmd, n_string_cp(shoup), tbpcp->tbpc_in_seq);
2979 f |= a_TTY_BIND_DEFUNCT;
2980 goto jleave;
2982 ep->cnv_dat = vic.vic_woudat;
2983 ep->cnv_len = (ui32_t)vic.vic_woulen;
2985 /* A termcap(5)/terminfo(5) identifier? */
2986 if(ep->cnv_len > 1 && ep->cnv_dat[0] == ':'){
2987 i = --ep->cnv_len, ++ep->cnv_dat;
2988 # ifndef HAVE_TERMCAP
2989 if(options & OPT_D_V)
2990 n_err(_("`%s': no termcap(5)/terminfo(5) support: %s: %s\n"),
2991 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
2992 f |= a_TTY_BIND_DEFUNCT;
2993 # endif
2994 if(i > a_TTY_BIND_CAPNAME_MAX){
2995 n_err(_("`%s': termcap(5)/terminfo(5) name too long: %s: %s\n"),
2996 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
2997 f |= a_TTY_BIND_DEFUNCT;
2999 while(i > 0)
3000 /* (We store it as char[]) */
3001 if((ui32_t)ep->cnv_dat[--i] & ~0x7Fu){
3002 n_err(_("`%s': invalid termcap(5)/terminfo(5) name content: "
3003 "%s: %s\n"),
3004 tbpcp->tbpc_cmd, ep->seq_dat, tbpcp->tbpc_in_seq);
3005 f |= a_TTY_BIND_DEFUNCT;
3006 break;
3008 ep->cnv_len |= SI32_MIN; /* Needs resolve */
3009 f |= a_TTY_BIND_RESOLVE;
3012 if(shs & n_SHEXP_STATE_STOP)
3013 break;
3016 if(head == NULL){
3017 jeempty:
3018 n_err(_("`%s': effectively empty key-sequence: %s\n"),
3019 tbpcp->tbpc_cmd, tbpcp->tbpc_in_seq);
3020 goto jleave;
3023 /* C99 */{
3024 struct a_tty_bind_ctx *ltbcp, *tbcp;
3025 char *cpbase, *cp, *cnv;
3026 size_t sl, cl;
3028 /* Unite the parsed sequence(s) into single string representations */
3029 for(sl = cl = 0, tail = head; tail != NULL; tail = tail->next){
3030 sl += tail->seq_len + 1;
3032 if(!isbindcmd)
3033 continue;
3035 /* Preserve room for terminal capabilities to be resolved.
3036 * Above we have ensured the buffer will fit in these calculations */
3037 if((i = tail->cnv_len) & SI32_MIN){
3038 /* For now
3039 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[]+NUL;}
3040 * later
3041 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3042 n_LCTAV(ISPOW2(a_TTY_BIND_CAPEXP_ROUNDUP));
3043 n_LCTA(a_TTY_BIND_CAPEXP_ROUNDUP >= sizeof(wc_t),
3044 "Aligning on this constant doesn't properly align wc_t");
3045 i &= SI32_MAX;
3046 i *= sizeof(wc_t);
3047 i += sizeof(si32_t);
3048 if(i < a_TTY_BIND_CAPEXP_ROUNDUP)
3049 i = (i + (a_TTY_BIND_CAPEXP_ROUNDUP - 1)) &
3050 ~(a_TTY_BIND_CAPEXP_ROUNDUP - 1);
3051 }else
3052 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3053 i *= sizeof(wc_t);
3054 i += sizeof(si32_t) + sizeof(wc_t); /* (buf_len_iscap, NUL) */
3055 cl += i;
3056 if(tail->cnv_len & SI32_MIN){
3057 tail->cnv_len &= SI32_MAX;
3058 i |= SI32_MIN;
3060 tail->calc_cnv_len = (ui32_t)i;
3062 --sl;
3064 tbpcp->tbpc_seq_len = sl;
3065 tbpcp->tbpc_cnv_len = cl;
3066 /* C99 */{
3067 size_t j;
3069 j = i = sl + 1; /* Room for comma separator */
3070 if(isbindcmd){
3071 size_t const al = MAX(sizeof(si32_t), sizeof(wc_t)) - 1;
3073 i = (i + al) & ~al;
3074 j = i;
3075 i += cl;
3077 tbpcp->tbpc_seq = cp = cpbase = salloc(i);
3078 tbpcp->tbpc_cnv = cnv = &cpbase[j];
3081 for(tail = head; tail != NULL; tail = tail->next){
3082 memcpy(cp, tail->seq_dat, tail->seq_len);
3083 cp += tail->seq_len;
3084 *cp++ = ',';
3086 if(isbindcmd){
3087 char * const save_cnv = cnv;
3089 ((si32_t*)cnv)[0] = (si32_t)(i = tail->calc_cnv_len);
3090 cnv += sizeof(si32_t);
3091 if(i & SI32_MIN){
3092 /* For now
3093 * struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];}
3094 * later
3095 * struct{si32_t buf_len_iscap; si32_t cap_len; char buf[];} */
3096 ((si32_t*)cnv)[0] = tail->cnv_len;
3097 cnv += sizeof(si32_t);
3099 i = tail->cnv_len * sizeof(wc_t);
3100 memcpy(cnv, tail->cnv_dat, i);
3101 cnv += i;
3102 *(wc_t*)cnv = '\0';
3104 cnv = save_cnv + (tail->calc_cnv_len & SI32_MAX);
3107 *--cp = '\0';
3109 /* Search for a yet existing identical mapping */
3110 for(ltbcp = NULL, tbcp = a_tty.tg_bind[tbpcp->tbpc_flags]; tbcp != NULL;
3111 ltbcp = tbcp, tbcp = tbcp->tbc_next)
3112 if(tbcp->tbc_seq_len == sl && !memcmp(tbcp->tbc_seq, cpbase, sl)){
3113 tbpcp->tbpc_tbcp = tbcp;
3114 break;
3116 tbpcp->tbpc_ltbcp = ltbcp;
3117 tbpcp->tbpc_flags |= (f & a_TTY__BIND_MASK);
3120 /* Create single string expansion if so desired */
3121 if(isbindcmd){
3122 char *exp;
3124 exp = tbpcp->tbpc_exp.s;
3126 i = tbpcp->tbpc_exp.l;
3127 if(i > 0 && exp[i - 1] == '@'){
3128 while(--i > 0){
3129 if(!blankspacechar(exp[i - 1]))
3130 break;
3132 if(i == 0)
3133 goto jeempty;
3135 exp[tbpcp->tbpc_exp.l = i] = '\0';
3136 tbpcp->tbpc_flags |= a_TTY_BIND_NOCOMMIT;
3139 /* It may map to an internal MLE command! */
3140 for(i = 0; i < NELEM(a_tty_bind_fun_names); ++i)
3141 if(!asccasecmp(exp, a_tty_bind_fun_names[i])){
3142 tbpcp->tbpc_flags |= a_TTY_BIND_FUN_EXPAND(i) |
3143 a_TTY_BIND_FUN_INTERNAL |
3144 (head->next == NULL ? a_TTY_BIND_MLE1CNTRL : 0);
3145 if((options & OPT_D_V) && (tbpcp->tbpc_flags & a_TTY_BIND_NOCOMMIT))
3146 n_err(_("`%s': MLE commands can't be made editable via @: %s\n"),
3147 tbpcp->tbpc_cmd, exp);
3148 tbpcp->tbpc_flags &= ~a_TTY_BIND_NOCOMMIT;
3149 break;
3153 f |= a_TRUE_RV; /* TODO because we only now true and false; DEFUNCT.. */
3154 jleave:
3155 n_string_gut(shoup);
3156 NYD2_LEAVE;
3157 return (f & a_TRUE_RV) != 0;
3160 static void
3161 a_tty_bind_resolve(struct a_tty_bind_ctx *tbcp){
3162 char capname[a_TTY_BIND_CAPNAME_MAX +1];
3163 struct n_termcap_value tv;
3164 size_t len;
3165 bool_t isfirst; /* TODO For now: first char must be control! */
3166 char *cp, *next;
3167 NYD2_ENTER;
3169 UNINIT(next, NULL);
3170 for(cp = tbcp->tbc_cnv, isfirst = TRU1, len = tbcp->tbc_cnv_len;
3171 len > 0; isfirst = FAL0, cp = next){
3172 /* C99 */{
3173 si32_t i, j;
3175 i = ((si32_t*)cp)[0];
3176 j = i & SI32_MAX;
3177 next = &cp[j];
3178 len -= j;
3179 if(i == j)
3180 continue;
3182 /* struct{si32_t buf_len_iscap; si32_t cap_len; wc_t name[];} */
3183 cp += sizeof(si32_t);
3184 i = ((si32_t*)cp)[0];
3185 cp += sizeof(si32_t);
3186 for(j = 0; j < i; ++j)
3187 capname[j] = ((wc_t*)cp)[j];
3188 capname[j] = '\0';
3191 /* Use generic lookup mechanism if not a known query */
3192 /* C99 */{
3193 si32_t tq;
3195 tq = n_termcap_query_for_name(capname, n_TERMCAP_CAPTYPE_STRING);
3196 if(tq == -1){
3197 tv.tv_data.tvd_string = capname;
3198 tq = n__TERMCAP_QUERY_MAX;
3201 if(tq < 0 || !n_termcap_query(tq, &tv)){
3202 if(options & OPT_D_V)
3203 n_err(_("`bind': unknown or unsupported capability: %s: %s\n"),
3204 capname, tbcp->tbc_seq);
3205 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3206 break;
3210 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;} */
3211 /* C99 */{
3212 size_t i;
3214 i = strlen(tv.tv_data.tvd_string);
3215 if(/*i > SI32_MAX ||*/ i >= PTR2SIZE(next - cp)){
3216 if(options & OPT_D_V)
3217 n_err(_("`bind': capability expansion too long: %s: %s\n"),
3218 capname, tbcp->tbc_seq);
3219 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3220 break;
3221 }else if(i == 0){
3222 if(options & OPT_D_V)
3223 n_err(_("`bind': empty capability expansion: %s: %s\n"),
3224 capname, tbcp->tbc_seq);
3225 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3226 break;
3227 }else if(isfirst && !cntrlchar(*tv.tv_data.tvd_string)){
3228 if(options & OPT_D_V)
3229 n_err(_("`bind': capability expansion doesn't start with "
3230 "control: %s: %s\n"), capname, tbcp->tbc_seq);
3231 tbcp->tbc_flags |= a_TTY_BIND_DEFUNCT;
3232 break;
3234 ((si32_t*)cp)[-1] = (si32_t)i;
3235 memcpy(cp, tv.tv_data.tvd_string, i);
3236 cp[i] = '\0';
3239 NYD2_LEAVE;
3242 static void
3243 a_tty_bind_del(struct a_tty_bind_parse_ctx *tbpcp){
3244 struct a_tty_bind_ctx *ltbcp, *tbcp;
3245 NYD2_ENTER;
3247 tbcp = tbpcp->tbpc_tbcp;
3249 if((ltbcp = tbpcp->tbpc_ltbcp) != NULL)
3250 ltbcp->tbc_next = tbcp->tbc_next;
3251 else
3252 a_tty.tg_bind[tbpcp->tbpc_flags] = tbcp->tbc_next;
3253 free(tbcp);
3255 --a_tty.tg_bind_cnt;
3256 a_tty.tg_bind_isdirty = TRU1;
3257 NYD2_LEAVE;
3260 static void
3261 a_tty_bind_tree_build(void){
3262 size_t i;
3263 NYD2_ENTER;
3265 for(i = 0; i < n__LEXINPUT_CTX_MAX; ++i){
3266 struct a_tty_bind_ctx *tbcp;
3267 n_LCTAV(n_LEXINPUT_CTX_BASE == 0);
3269 /* Somewhat wasteful, but easier to handle: simply clone the entire
3270 * primary key onto the secondary one, then only modify it */
3271 for(tbcp = a_tty.tg_bind[n_LEXINPUT_CTX_BASE]; tbcp != NULL;
3272 tbcp = tbcp->tbc_next)
3273 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3274 a_tty__bind_tree_add(n_LEXINPUT_CTX_BASE, &a_tty.tg_bind_tree[i][0],
3275 tbcp);
3277 if(i != n_LEXINPUT_CTX_BASE)
3278 for(tbcp = a_tty.tg_bind[i]; tbcp != NULL; tbcp = tbcp->tbc_next)
3279 if(!(tbcp->tbc_flags & a_TTY_BIND_DEFUNCT))
3280 a_tty__bind_tree_add(i, &a_tty.tg_bind_tree[i][0], tbcp);
3283 a_tty.tg_bind_isbuild = TRU1;
3284 NYD2_LEAVE;
3287 static void
3288 a_tty_bind_tree_teardown(void){
3289 size_t i, j;
3290 NYD2_ENTER;
3292 memset(&a_tty.tg_bind_shcut_cancel[0], 0,
3293 sizeof(a_tty.tg_bind_shcut_cancel));
3294 memset(&a_tty.tg_bind_shcut_prompt_char[0], 0,
3295 sizeof(a_tty.tg_bind_shcut_prompt_char));
3297 for(i = 0; i < n__LEXINPUT_CTX_MAX; ++i)
3298 for(j = 0; j < HSHSIZE; ++j)
3299 a_tty__bind_tree_free(a_tty.tg_bind_tree[i][j]);
3300 memset(&a_tty.tg_bind_tree[0], 0, sizeof(a_tty.tg_bind_tree));
3302 a_tty.tg_bind_isdirty = a_tty.tg_bind_isbuild = FAL0;
3303 NYD2_LEAVE;
3306 static void
3307 a_tty__bind_tree_add(ui32_t hmap_idx, struct a_tty_bind_tree *store[HSHSIZE],
3308 struct a_tty_bind_ctx *tbcp){
3309 ui32_t cnvlen;
3310 char const *cnvdat;
3311 struct a_tty_bind_tree *ntbtp;
3312 NYD2_ENTER;
3313 UNUSED(hmap_idx);
3315 ntbtp = NULL;
3317 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len; cnvlen > 0;){
3318 union {wchar_t const *wp; char const *cp;} u;
3319 si32_t entlen;
3321 /* {si32_t buf_len_iscap;} */
3322 entlen = *(si32_t const*)cnvdat;
3324 if(entlen & SI32_MIN){
3325 /* struct{si32_t buf_len_iscap; si32_t cap_len; char buf[]+NUL;}
3326 * Note that empty capabilities result in DEFUNCT */
3327 for(u.cp = (char const*)&((si32_t const*)cnvdat)[2];
3328 *u.cp != '\0'; ++u.cp)
3329 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.cp, TRU1);
3330 ntbtp->tbt_isseq_trail = TRU1;
3331 entlen &= SI32_MAX;
3332 }else{
3333 /* struct{si32_t buf_len_iscap; wc_t buf[]+NUL;} */
3334 bool_t isseq;
3336 u.wp = (wchar_t const*)&((si32_t const*)cnvdat)[1];
3338 /* May be a special shortcut function? */
3339 if(ntbtp == NULL && (tbcp->tbc_flags & a_TTY_BIND_MLE1CNTRL)){
3340 char *cp;
3341 ui32_t ctx, fun;
3343 ctx = tbcp->tbc_flags & n__LEXINPUT_CTX_MAX;
3344 fun = tbcp->tbc_flags & a_TTY__BIND_FUN_MASK;
3346 if(fun == a_TTY_BIND_FUN_CANCEL){
3347 for(cp = &a_tty.tg_bind_shcut_cancel[ctx][0];
3348 PTRCMP(cp, <, &a_tty.tg_bind_shcut_cancel[ctx]
3349 [NELEM(a_tty.tg_bind_shcut_cancel[ctx]) - 1]); ++cp)
3350 if(*cp == '\0'){
3351 *cp = (char)*u.wp;
3352 break;
3354 }else if(fun == a_TTY_BIND_FUN_PROMPT_CHAR){
3355 for(cp = &a_tty.tg_bind_shcut_prompt_char[ctx][0];
3356 PTRCMP(cp, <, &a_tty.tg_bind_shcut_prompt_char[ctx]
3357 [NELEM(a_tty.tg_bind_shcut_prompt_char[ctx]) - 1]);
3358 ++cp)
3359 if(*cp == '\0'){
3360 *cp = (char)*u.wp;
3361 break;
3366 isseq = (u.wp[1] != '\0');
3367 for(; *u.wp != '\0'; ++u.wp)
3368 ntbtp = a_tty__bind_tree_add_wc(store, ntbtp, *u.wp, isseq);
3369 if(isseq)
3370 ntbtp->tbt_isseq_trail = TRU1;
3373 cnvlen -= entlen;
3374 cnvdat += entlen;
3377 /* Should have been rendered defunctional at first instead */
3378 assert(ntbtp != NULL);
3379 ntbtp->tbt_bind = tbcp;
3380 NYD2_LEAVE;
3383 static struct a_tty_bind_tree *
3384 a_tty__bind_tree_add_wc(struct a_tty_bind_tree **treep,
3385 struct a_tty_bind_tree *parentp, wchar_t wc, bool_t isseq){
3386 struct a_tty_bind_tree *tbtp, *xtbtp;
3387 NYD2_ENTER;
3389 if(parentp == NULL){
3390 treep += wc % HSHSIZE;
3392 /* Having no parent also means that the tree slot is possibly empty */
3393 for(tbtp = *treep; tbtp != NULL;
3394 parentp = tbtp, tbtp = tbtp->tbt_sibling){
3395 if(tbtp->tbt_char != wc)
3396 continue;
3397 if(tbtp->tbt_isseq == isseq)
3398 goto jleave;
3399 /* isseq MUST be linked before !isseq, so record this "parent"
3400 * sibling, but continue searching for now */
3401 if(!isseq)
3402 parentp = tbtp;
3403 /* Otherwise it is impossible that we'll find what we look for */
3404 else{
3405 #ifdef HAVE_DEBUG
3406 while((tbtp = tbtp->tbt_sibling) != NULL)
3407 assert(tbtp->tbt_char != wc);
3408 #endif
3409 break;
3413 tbtp = smalloc(sizeof *tbtp);
3414 memset(tbtp, 0, sizeof *tbtp);
3415 tbtp->tbt_char = wc;
3416 tbtp->tbt_isseq = isseq;
3418 if(parentp == NULL){
3419 tbtp->tbt_sibling = *treep;
3420 *treep = tbtp;
3421 }else{
3422 tbtp->tbt_sibling = parentp->tbt_sibling;
3423 parentp->tbt_sibling = tbtp;
3425 }else{
3426 if((tbtp = *(treep = &parentp->tbt_childs)) != NULL){
3427 for(;; tbtp = xtbtp){
3428 if(tbtp->tbt_char == wc){
3429 if(tbtp->tbt_isseq == isseq)
3430 goto jleave;
3431 /* isseq MUST be linked before, so it is impossible that we'll
3432 * find what we look for */
3433 if(isseq){
3434 #ifdef HAVE_DEBUG
3435 while((tbtp = tbtp->tbt_sibling) != NULL)
3436 assert(tbtp->tbt_char != wc);
3437 #endif
3438 tbtp = NULL;
3439 break;
3443 if((xtbtp = tbtp->tbt_sibling) == NULL){
3444 treep = &tbtp->tbt_sibling;
3445 break;
3450 xtbtp = smalloc(sizeof *xtbtp);
3451 memset(xtbtp, 0, sizeof *xtbtp);
3452 xtbtp->tbt_parent = parentp;
3453 xtbtp->tbt_char = wc;
3454 xtbtp->tbt_isseq = isseq;
3455 tbtp = xtbtp;
3456 *treep = tbtp;
3458 jleave:
3459 NYD2_LEAVE;
3460 return tbtp;
3463 static void
3464 a_tty__bind_tree_free(struct a_tty_bind_tree *tbtp){
3465 NYD2_ENTER;
3466 while(tbtp != NULL){
3467 struct a_tty_bind_tree *tmp;
3469 if((tmp = tbtp->tbt_childs) != NULL)
3470 a_tty__bind_tree_free(tmp);
3472 tmp = tbtp->tbt_sibling;
3473 free(tbtp);
3474 tbtp = tmp;
3476 NYD2_LEAVE;
3478 # endif /* HAVE_KEY_BINDINGS */
3480 FL void
3481 n_tty_init(void){
3482 NYD_ENTER;
3484 if(ok_blook(line_editor_disable))
3485 goto jleave;
3487 /* Load the history file */
3488 # ifdef HAVE_HISTORY
3489 do/* for break */{
3490 long hs;
3491 char const *v;
3492 char *lbuf;
3493 FILE *f;
3494 size_t lsize, cnt, llen;
3496 a_TTY_HISTSIZE(hs);
3497 a_tty.tg_hist_size = 0;
3498 a_tty.tg_hist_size_max = (size_t)hs;
3499 if(hs == 0)
3500 break;
3502 a_TTY_HISTFILE(v);
3503 if(v == NULL)
3504 break;
3506 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
3507 f = fopen(v, "r"); /* TODO HISTFILE LOAD: use linebuf pool */
3508 if(f == NULL)
3509 goto jhist_done;
3510 (void)n_file_lock(fileno(f), FLT_READ, 0,0, UIZ_MAX);
3512 assert(!(pstate & PS_ROOT));
3513 pstate |= PS_ROOT; /* Allow calling addhist() */
3514 lbuf = NULL;
3515 lsize = 0;
3516 cnt = (size_t)fsize(f);
3517 while(fgetline(&lbuf, &lsize, &cnt, &llen, f, FAL0) != NULL){
3518 if(llen > 0 && lbuf[llen - 1] == '\n')
3519 lbuf[--llen] = '\0';
3520 if(llen == 0 || lbuf[0] == '#') /* xxx comments? noone! */
3521 continue;
3522 else{
3523 bool_t isgabby;
3525 isgabby = (lbuf[0] == '*');
3526 n_tty_addhist(lbuf + isgabby, isgabby);
3529 if(lbuf != NULL)
3530 free(lbuf);
3531 pstate &= ~PS_ROOT;
3533 fclose(f);
3534 jhist_done:
3535 rele_all_sigs(); /* XXX remove jumps */
3536 }while(0);
3537 # endif /* HAVE_HISTORY */
3539 /* Force immediate resolve for anything which follows */
3540 pstate |= PS_LINE_EDITOR_INIT;
3542 # ifdef HAVE_KEY_BINDINGS
3543 /* `bind's (and `unbind's) done from within resource files couldn't be
3544 * performed for real since our termcap driver wasn't yet loaded, and we
3545 * can't perform automatic init since the user may have disallowed so */
3546 /* C99 */{
3547 struct a_tty_bind_ctx *tbcp;
3548 enum n_lexinput_flags lif;
3550 for(lif = 0; lif < n__LEXINPUT_CTX_MAX; ++lif)
3551 for(tbcp = a_tty.tg_bind[lif]; tbcp != NULL; tbcp = tbcp->tbc_next)
3552 if((tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)) ==
3553 a_TTY_BIND_RESOLVE)
3554 a_tty_bind_resolve(tbcp);
3557 /* And we want to (try to) install some default key bindings */
3558 if(!ok_blook(line_editor_no_defaults)){
3559 char buf[8];
3560 struct a_tty_bind_parse_ctx tbpc;
3561 struct a_tty_bind_default_tuple const *tbdtp;
3563 buf[0] = '$', buf[1] = '\'', buf[2] = '\\', buf[3] = 'c',
3564 buf[5] = '\'', buf[6] = '\0';
3565 for(tbdtp = a_tty_bind_default_tuples;
3566 PTRCMP(tbdtp, <,
3567 &a_tty_bind_default_tuples[NELEM(a_tty_bind_default_tuples)]);
3568 ++tbdtp){
3569 memset(&tbpc, 0, sizeof tbpc);
3570 tbpc.tbpc_cmd = "bind";
3571 if(tbdtp->tbdt_iskey){
3572 buf[4] = tbdtp->tbdt_ckey;
3573 tbpc.tbpc_in_seq = buf;
3574 }else
3575 tbpc.tbpc_in_seq = savecatsep(":", '\0',
3576 n_termcap_name_of_query(tbdtp->tbdt_query));
3577 tbpc.tbpc_exp.s = UNCONST(tbdtp->tbdt_exp[0] == '\0'
3578 ? a_tty_bind_fun_names[(ui8_t)tbdtp->tbdt_exp[1]]
3579 : tbdtp->tbdt_exp);
3580 tbpc.tbpc_exp.l = strlen(tbpc.tbpc_exp.s);
3581 tbpc.tbpc_flags = n_LEXINPUT_CTX_BASE;
3582 /* ..but don't want to overwrite any user settings */
3583 a_tty_bind_create(&tbpc, FAL0);
3586 # endif /* HAVE_KEY_BINDINGS */
3588 jleave:
3589 NYD_LEAVE;
3592 FL void
3593 n_tty_destroy(void){
3594 NYD_ENTER;
3596 if(!(pstate & PS_LINE_EDITOR_INIT))
3597 goto jleave;
3599 # ifdef HAVE_HISTORY
3600 do/* for break */{
3601 long hs;
3602 char const *v;
3603 struct a_tty_hist *thp;
3604 bool_t dogabby;
3605 FILE *f;
3607 a_TTY_HISTSIZE(hs);
3608 if(hs == 0)
3609 break;
3611 a_TTY_HISTFILE(v);
3612 if(v == NULL)
3613 break;
3615 dogabby = ok_blook(history_gabby_persist);
3617 if((thp = a_tty.tg_hist) != NULL)
3618 for(; thp->th_older != NULL; thp = thp->th_older)
3619 if((dogabby || !thp->th_isgabby) && --hs == 0)
3620 break;
3622 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
3623 f = fopen(v, "w"); /* TODO temporary + rename?! */
3624 if(f == NULL)
3625 goto jhist_done;
3626 (void)n_file_lock(fileno(f), FLT_WRITE, 0,0, UIZ_MAX);
3628 for(; thp != NULL; thp = thp->th_younger){
3629 if(dogabby || !thp->th_isgabby){
3630 if(thp->th_isgabby)
3631 putc('*', f);
3632 fwrite(thp->th_dat, sizeof *thp->th_dat, thp->th_len, f);
3633 putc('\n', f);
3636 fclose(f);
3637 jhist_done:
3638 rele_all_sigs(); /* XXX remove jumps */
3639 }while(0);
3640 # endif /* HAVE_HISTORY */
3642 # if defined HAVE_KEY_BINDINGS && defined HAVE_DEBUG
3643 c_unbind(UNCONST("* *"));
3644 # endif
3646 # ifdef HAVE_DEBUG
3647 memset(&a_tty, 0, sizeof a_tty);
3648 # endif
3649 DBG( pstate &= ~PS_LINE_EDITOR_INIT; )
3650 jleave:
3651 NYD_LEAVE;
3654 FL void
3655 n_tty_signal(int sig){
3656 sigset_t nset, oset;
3657 NYD_X; /* Signal handler */
3659 switch(sig){
3660 # ifdef SIGWINCH
3661 case SIGWINCH:
3662 /* We don't deal with SIGWINCH, yet get called from main.c.
3663 * Note this case might get called even if !PS_LINE_EDITOR_INIT */
3664 break;
3665 # endif
3666 default:
3667 a_tty_term_mode(FAL0);
3668 n_TERMCAP_SUSPEND(TRU1);
3669 a_tty_sigs_down();
3671 sigemptyset(&nset);
3672 sigaddset(&nset, sig);
3673 sigprocmask(SIG_UNBLOCK, &nset, &oset);
3674 n_raise(sig);
3675 /* When we come here we'll continue editing, so reestablish */
3676 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
3678 a_tty_sigs_up();
3679 n_TERMCAP_RESUME(TRU1);
3680 a_tty_term_mode(TRU1);
3681 a_tty.tg_line->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
3682 break;
3686 FL int
3687 (n_tty_readline)(enum n_lexinput_flags lif, char const *prompt,
3688 char **linebuf, size_t *linesize, size_t n SMALLOC_DEBUG_ARGS){
3689 struct a_tty_line tl;
3690 # ifdef HAVE_COLOUR
3691 char *posbuf, *pos;
3692 # endif
3693 ui32_t plen, pwidth;
3694 ssize_t nn;
3695 char const *orig_prompt;
3696 NYD_ENTER;
3697 UNUSED(lif);
3699 assert(!ok_blook(line_editor_disable));
3700 if(!(pstate & PS_LINE_EDITOR_INIT))
3701 n_tty_init();
3702 assert(pstate & PS_LINE_EDITOR_INIT);
3704 orig_prompt = prompt;
3705 /* xxx Likely overkill: avoid "bind base a,b,c set-line-editor-disable"
3706 * xxx not being honoured at once: call n_lex_input() instead of goto */
3707 # ifndef HAVE_KEY_BINDINGS
3708 jredo:
3709 prompt = orig_prompt;
3710 # endif
3712 # ifdef HAVE_COLOUR
3713 n_colour_env_create(n_COLOUR_CTX_MLE, FAL0);
3714 # endif
3716 /* Classify prompt */
3717 UNINIT(plen, 0);
3718 UNINIT(pwidth, 0);
3719 if(prompt != NULL){
3720 size_t i = strlen(prompt);
3722 if(i == 0 || i >= UI32_MAX)
3723 prompt = NULL;
3724 else{
3725 /* TODO *prompt* is in multibyte and not in a_tty_cell, therefore
3726 * TODO we cannot handle it in parts, it's all or nothing.
3727 * TODO Later (S-CText, SysV signals) the prompt should be some global
3728 * TODO carrier thing, fully evaluated and passed around as UI-enabled
3729 * TODO string, then we can print it character by character */
3730 struct n_visual_info_ctx vic;
3732 memset(&vic, 0, sizeof vic);
3733 vic.vic_indat = prompt;
3734 vic.vic_inlen = i;
3735 if(n_visual_info(&vic, n_VISUAL_INFO_WIDTH_QUERY)){
3736 pwidth = (ui32_t)vic.vic_vi_width;
3737 plen = (ui32_t)i;
3738 }else{
3739 n_err(_("Character set error in evaluation of prompt\n"));
3740 prompt = NULL;
3745 # ifdef HAVE_COLOUR
3746 /* C99 */{
3747 struct n_colour_pen *ccp;
3748 struct str const *sp;
3750 if(prompt != NULL &&
3751 (ccp = n_colour_pen_create(n_COLOUR_ID_MLE_PROMPT, NULL)) != NULL &&
3752 (sp = n_colour_pen_to_str(ccp)) != NULL){
3753 char const *ccol = sp->s;
3755 if((sp = n_colour_reset_to_str()) != NULL){
3756 size_t l1 = strlen(ccol), l2 = strlen(sp->s);
3757 ui32_t nplen = (ui32_t)(l1 + plen + l2);
3758 char *nprompt = salloc(nplen +1);
3760 memcpy(nprompt, ccol, l1);
3761 memcpy(&nprompt[l1], prompt, plen);
3762 memcpy(&nprompt[l1 += plen], sp->s, ++l2);
3764 prompt = nprompt;
3765 plen = nplen;
3769 /* .tl_pos_buf is a hack */
3770 posbuf = pos = NULL;
3771 if((ccp = n_colour_pen_create(n_COLOUR_ID_MLE_POSITION, NULL)) != NULL &&
3772 (sp = n_colour_pen_to_str(ccp)) != NULL){
3773 char const *ccol = sp->s;
3775 if((sp = n_colour_reset_to_str()) != NULL){
3776 size_t l1 = strlen(ccol), l2 = strlen(sp->s);
3778 posbuf = salloc(l1 + 4 + l2 +1);
3779 memcpy(posbuf, ccol, l1);
3780 pos = &posbuf[l1];
3781 memcpy(&pos[4], sp->s, ++l2);
3784 if(posbuf == NULL){
3785 posbuf = pos = salloc(4 +1);
3786 pos[4] = '\0';
3789 # endif /* HAVE_COLOUR */
3791 memset(&tl, 0, sizeof tl);
3793 # ifdef HAVE_KEY_BINDINGS
3794 /* C99 */{
3795 char const *cp = ok_vlook(bind_timeout);
3797 if(cp != NULL){
3798 ul_i ul;
3800 if((ul = strtoul(cp, NULL, 0)) > 0 &&
3801 /* Convert to tenths of a second, unfortunately */
3802 (ul = (ul + 99) / 100) <= a_TTY_BIND_TIMEOUT_MAX)
3803 tl.tl_bind_timeout = (ui8_t)ul;
3804 else if(options & OPT_D_V)
3805 n_err(_("Ignoring invalid *bind-timeout*: %s\n"), cp);
3809 if(a_tty.tg_bind_isdirty)
3810 a_tty_bind_tree_teardown();
3811 if(a_tty.tg_bind_cnt > 0 && !a_tty.tg_bind_isbuild)
3812 a_tty_bind_tree_build();
3813 tl.tl_bind_tree_hmap = &a_tty.tg_bind_tree[lif & n__LEXINPUT_CTX_MASK];
3814 tl.tl_bind_shcut_cancel =
3815 &a_tty.tg_bind_shcut_cancel[lif & n__LEXINPUT_CTX_MASK];
3816 tl.tl_bind_shcut_prompt_char =
3817 &a_tty.tg_bind_shcut_prompt_char[lif & n__LEXINPUT_CTX_MASK];
3818 # endif /* HAVE_KEY_BINDINGS */
3820 if((tl.tl_prompt = prompt) != NULL){ /* XXX not re-evaluated */
3821 tl.tl_prompt_length = plen;
3822 tl.tl_prompt_width = pwidth;
3824 # ifdef HAVE_COLOUR
3825 tl.tl_pos_buf = posbuf;
3826 tl.tl_pos = pos;
3827 # endif
3829 tl.tl_line.cbuf = *linebuf;
3830 if(n != 0){
3831 tl.tl_defc.s = savestrbuf(*linebuf, n);
3832 tl.tl_defc.l = n;
3834 tl.tl_x_buf = linebuf;
3835 tl.tl_x_bufsize = linesize;
3837 a_tty.tg_line = &tl;
3838 a_tty_sigs_up();
3839 a_tty_term_mode(TRU1);
3840 nn = a_tty_readline(&tl, n SMALLOC_DEBUG_ARGSCALL);
3841 a_tty_term_mode(FAL0);
3842 a_tty_sigs_down();
3843 a_tty.tg_line = NULL;
3845 # ifdef HAVE_COLOUR
3846 n_colour_env_gut(stdout);
3847 # endif
3849 if(tl.tl_reenter_after_cmd != NULL){
3850 n_source_command(lif, tl.tl_reenter_after_cmd);
3851 /* TODO because of recursion we cannot use srelax()ation: would be good */
3852 /* See above for why not simply using goto */
3853 n = (nn <= 0) ? 0 : nn;
3854 # ifdef HAVE_KEY_BINDINGS
3855 nn = (n_lex_input)(lif, orig_prompt, linebuf, linesize,
3856 (n == 0 ? "" : savestrbuf(*linebuf, n)) SMALLOC_DEBUG_ARGSCALL);
3857 # else
3858 goto jredo;
3859 # endif
3861 NYD_LEAVE;
3862 return (int)nn;
3865 FL void
3866 n_tty_addhist(char const *s, bool_t isgabby){
3867 # ifdef HAVE_HISTORY
3868 /* Super-Heavy-Metal: block all sigs, avoid leaks+ on jump */
3869 ui32_t l;
3870 struct a_tty_hist *thp, *othp, *ythp;
3871 # endif
3872 NYD_ENTER;
3873 UNUSED(s);
3874 UNUSED(isgabby);
3876 # ifdef HAVE_HISTORY
3877 a_TTY_CHECK_ADDHIST(s, isgabby, goto j_leave);
3878 if(a_tty.tg_hist_size_max == 0)
3879 goto j_leave;
3881 l = (ui32_t)strlen(s);
3883 /* Eliminating duplicates is expensive, but simply inacceptable so
3884 * during the load of a potentially large history file! */
3885 if(pstate & PS_LINE_EDITOR_INIT)
3886 for(thp = a_tty.tg_hist; thp != NULL; thp = thp->th_older)
3887 if(thp->th_len == l && !strcmp(thp->th_dat, s)){
3888 hold_all_sigs(); /* TODO */
3889 if(thp->th_isgabby)
3890 thp->th_isgabby = !!isgabby;
3891 othp = thp->th_older;
3892 ythp = thp->th_younger;
3893 if(othp != NULL)
3894 othp->th_younger = ythp;
3895 else
3896 a_tty.tg_hist_tail = ythp;
3897 if(ythp != NULL)
3898 ythp->th_older = othp;
3899 else
3900 a_tty.tg_hist = othp;
3901 goto jleave;
3903 hold_all_sigs();
3905 ++a_tty.tg_hist_size;
3906 if((pstate & PS_LINE_EDITOR_INIT) &&
3907 a_tty.tg_hist_size > a_tty.tg_hist_size_max){
3908 --a_tty.tg_hist_size;
3909 if((thp = a_tty.tg_hist_tail) != NULL){
3910 if((a_tty.tg_hist_tail = thp->th_younger) == NULL)
3911 a_tty.tg_hist = NULL;
3912 else
3913 a_tty.tg_hist_tail->th_older = NULL;
3914 free(thp);
3918 thp = smalloc((sizeof(struct a_tty_hist) -
3919 VFIELD_SIZEOF(struct a_tty_hist, th_dat)) + l +1);
3920 thp->th_isgabby = !!isgabby;
3921 thp->th_len = l;
3922 memcpy(thp->th_dat, s, l +1);
3923 jleave:
3924 if((thp->th_older = a_tty.tg_hist) != NULL)
3925 a_tty.tg_hist->th_younger = thp;
3926 else
3927 a_tty.tg_hist_tail = thp;
3928 thp->th_younger = NULL;
3929 a_tty.tg_hist = thp;
3931 rele_all_sigs();
3932 j_leave:
3933 # endif
3934 NYD_LEAVE;
3937 # ifdef HAVE_HISTORY
3938 FL int
3939 c_history(void *v){
3940 C_HISTORY_SHARED;
3942 jlist:{
3943 FILE *fp;
3944 size_t i, b;
3945 struct a_tty_hist *thp;
3947 if(a_tty.tg_hist == NULL)
3948 goto jleave;
3950 if((fp = Ftmp(NULL, "hist", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
3951 n_perr(_("tmpfile"), 0);
3952 v = NULL;
3953 goto jleave;
3956 i = a_tty.tg_hist_size;
3957 b = 0;
3958 for(thp = a_tty.tg_hist; thp != NULL;
3959 --i, b += thp->th_len, thp = thp->th_older)
3960 fprintf(fp,
3961 "%c%4" PRIuZ ". %-50.50s (%4" PRIuZ "+%2" PRIu32 " B)\n",
3962 (thp->th_isgabby ? '*' : ' '), i, thp->th_dat, b, thp->th_len);
3964 page_or_print(fp, i);
3965 Fclose(fp);
3967 goto jleave;
3969 jclear:{
3970 struct a_tty_hist *thp;
3972 while((thp = a_tty.tg_hist) != NULL){
3973 a_tty.tg_hist = thp->th_older;
3974 free(thp);
3976 a_tty.tg_hist_tail = NULL;
3977 a_tty.tg_hist_size = 0;
3979 goto jleave;
3981 jentry:{
3982 struct a_tty_hist *thp;
3984 if(UICMP(z, entry, <=, a_tty.tg_hist_size)){
3985 entry = (long)a_tty.tg_hist_size - entry;
3986 for(thp = a_tty.tg_hist;; thp = thp->th_older)
3987 if(thp == NULL)
3988 break;
3989 else if(entry-- != 0)
3990 continue;
3991 else{
3992 v = temporary_arg_v_store = thp->th_dat;
3993 goto jleave;
3996 v = NULL;
3998 goto jleave;
4000 # endif /* HAVE_HISTORY */
4002 # ifdef HAVE_KEY_BINDINGS
4003 FL int
4004 c_bind(void *v){
4005 n_CMD_ARG_DESC_SUBCLASS_DEF(bind, 3, a_tty_bind_cad) { /* TODO cmd_tab.h */
4006 {n_CMD_ARG_DESC_STRING, 0},
4007 {n_CMD_ARG_DESC_WYSH | n_CMD_ARG_DESC_OPTION |
4008 n_CMD_ARG_DESC_HONOUR_STOP,
4009 n_SHEXP_PARSE_DRYRUN | n_SHEXP_PARSE_LOG},
4010 {n_CMD_ARG_DESC_WYSH | n_CMD_ARG_DESC_OPTION | n_CMD_ARG_DESC_GREEDY |
4011 n_CMD_ARG_DESC_HONOUR_STOP,
4012 n_SHEXP_PARSE_IGNORE_EMPTY}
4013 } n_CMD_ARG_DESC_SUBCLASS_DEF_END;
4014 struct n_cmd_arg_ctx cac;
4015 struct a_tty_bind_ctx *tbcp;
4016 enum n_lexinput_flags lif;
4017 bool_t aster, show;
4018 union {char const *cp; char *p; char c;} c;
4019 NYD_ENTER;
4021 cac.cac_desc = n_CMD_ARG_DESC_SUBCLASS_CAST(&a_tty_bind_cad);
4022 cac.cac_indat = v;
4023 cac.cac_inlen = UIZ_MAX;
4024 if(!n_cmd_arg_parse(&cac)){
4025 v = NULL;
4026 goto jleave;
4029 c.cp = cac.cac_arg->ca_arg.ca_str.s;
4030 if(cac.cac_no == 1)
4031 show = TRU1;
4032 else
4033 show = !asccasecmp(cac.cac_arg->ca_next->ca_arg.ca_str.s, "show");
4034 aster = FAL0;
4036 if((lif = a_tty_bind_ctx_find(c.cp)) == (enum n_lexinput_flags)-1){
4037 if(!(aster = n_is_all_or_aster(c.cp)) || !show){
4038 n_err(_("`bind': invalid context: %s\n"), c.cp);
4039 v = NULL;
4040 goto jleave;
4042 lif = 0;
4045 if(show){
4046 ui32_t lns;
4047 FILE *fp;
4049 if((fp = Ftmp(NULL, "bind", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
4050 n_perr(_("tmpfile"), 0);
4051 v = NULL;
4052 goto jleave;
4055 lns = 0;
4056 for(;;){
4057 for(tbcp = a_tty.tg_bind[lif]; tbcp != NULL;
4058 ++lns, tbcp = tbcp->tbc_next){
4059 /* Print the bytes of resolved terminal capabilities, then */
4060 if((options & OPT_D_V) &&
4061 (tbcp->tbc_flags & (a_TTY_BIND_RESOLVE | a_TTY_BIND_DEFUNCT)
4062 ) == a_TTY_BIND_RESOLVE){
4063 char cbuf[8];
4064 union {wchar_t const *wp; char const *cp;} u;
4065 si32_t entlen;
4066 ui32_t cnvlen;
4067 char const *cnvdat, *bsep, *cbufp;
4069 putc('#', fp);
4070 putc(' ', fp);
4072 cbuf[0] = '=', cbuf[2] = '\0';
4073 for(cnvdat = tbcp->tbc_cnv, cnvlen = tbcp->tbc_cnv_len;
4074 cnvlen > 0;){
4075 if(cnvdat != tbcp->tbc_cnv)
4076 putc(',', fp);
4078 /* {si32_t buf_len_iscap;} */
4079 entlen = *(si32_t const*)cnvdat;
4080 if(entlen & SI32_MIN){
4081 /* struct{si32_t buf_len_iscap; si32_t cap_len;
4082 * char buf[]+NUL;} */
4083 for(bsep = "",
4084 u.cp = (char const*)&((si32_t const*)cnvdat)[2];
4085 (c.c = *u.cp) != '\0'; ++u.cp){
4086 if(asciichar(c.c) && !cntrlchar(c.c))
4087 cbuf[1] = c.c, cbufp = cbuf;
4088 else
4089 cbufp = "";
4090 fprintf(fp, "%s%02X%s",
4091 bsep, (ui32_t)(ui8_t)c.c, cbufp);
4092 bsep = " ";
4094 entlen &= SI32_MAX;
4095 }else
4096 putc('-', fp);
4098 cnvlen -= entlen;
4099 cnvdat += entlen;
4102 fputs("\n ", fp);
4103 ++lns;
4106 fprintf(fp, "%sbind %s %s %s%s%s\n",
4107 ((tbcp->tbc_flags & a_TTY_BIND_DEFUNCT)
4108 /* I18N: `bind' sequence not working, either because it is
4109 * I18N: using Unicode and that is not available in the locale,
4110 * I18N: or a termcap(5)/terminfo(5) sequence won't work out */
4111 ? _("# <Defunctional> ") : ""),
4112 a_tty_bind_ctx_maps[lif].tbcm_name, tbcp->tbc_seq,
4113 n_shell_quote_cp(tbcp->tbc_exp, TRU1),
4114 (tbcp->tbc_flags & a_TTY_BIND_NOCOMMIT ? "@" : ""),
4115 (!(options & OPT_D_VV) ? ""
4116 : (tbcp->tbc_flags & a_TTY_BIND_FUN_INTERNAL
4117 ? _(" # MLE internal") : ""))
4120 if(!aster || ++lif >= n__LEXINPUT_CTX_MAX)
4121 break;
4123 page_or_print(fp, lns);
4125 Fclose(fp);
4126 }else{
4127 struct a_tty_bind_parse_ctx tbpc;
4128 struct n_string store;
4130 memset(&tbpc, 0, sizeof tbpc);
4131 tbpc.tbpc_cmd = a_tty_bind_cad.cad_name;
4132 tbpc.tbpc_in_seq = cac.cac_arg->ca_next->ca_arg.ca_str.s;
4133 tbpc.tbpc_exp.s = n_string_cp(n_cmd_arg_join_greedy(&cac,
4134 n_string_creat_auto(&store)));
4135 tbpc.tbpc_exp.l = store.s_len;
4136 tbpc.tbpc_flags = lif;
4137 if(!a_tty_bind_create(&tbpc, TRU1))
4138 v = NULL;
4139 n_string_gut(&store);
4141 jleave:
4142 NYD_LEAVE;
4143 return (v != NULL) ? EXIT_OK : EXIT_ERR;
4146 FL int
4147 c_unbind(void *v){
4148 n_CMD_ARG_DESC_SUBCLASS_DEF(unbind, 2, a_tty_unbind_cad) {/* TODO cmd_tab.h*/
4149 {n_CMD_ARG_DESC_STRING, 0},
4150 {n_CMD_ARG_DESC_WYSH | n_CMD_ARG_DESC_HONOUR_STOP,
4151 n_SHEXP_PARSE_DRYRUN | n_SHEXP_PARSE_LOG}
4152 } n_CMD_ARG_DESC_SUBCLASS_DEF_END;
4153 struct a_tty_bind_parse_ctx tbpc;
4154 struct n_cmd_arg_ctx cac;
4155 struct a_tty_bind_ctx *tbcp;
4156 enum n_lexinput_flags lif;
4157 bool_t aster;
4158 union {char const *cp; char *p;} c;
4159 NYD_ENTER;
4161 cac.cac_desc = n_CMD_ARG_DESC_SUBCLASS_CAST(&a_tty_unbind_cad);
4162 cac.cac_indat = v;
4163 cac.cac_inlen = UIZ_MAX;
4164 if(!n_cmd_arg_parse(&cac)){
4165 v = NULL;
4166 goto jleave;
4169 c.cp = cac.cac_arg->ca_arg.ca_str.s;
4170 aster = FAL0;
4172 if((lif = a_tty_bind_ctx_find(c.cp)) == (enum n_lexinput_flags)-1){
4173 if(!(aster = n_is_all_or_aster(c.cp))){
4174 n_err(_("`unbind': invalid context: %s\n"), c.cp);
4175 v = NULL;
4176 goto jleave;
4178 lif = 0;
4181 c.cp = cac.cac_arg->ca_next->ca_arg.ca_str.s;
4182 jredo:
4183 if(n_is_all_or_aster(c.cp)){
4184 while((tbcp = a_tty.tg_bind[lif]) != NULL){
4185 memset(&tbpc, 0, sizeof tbpc);
4186 tbpc.tbpc_tbcp = tbcp;
4187 tbpc.tbpc_flags = lif;
4188 a_tty_bind_del(&tbpc);
4190 }else{
4191 memset(&tbpc, 0, sizeof tbpc);
4192 tbpc.tbpc_cmd = a_tty_unbind_cad.cad_name;
4193 tbpc.tbpc_in_seq = c.cp;
4194 tbpc.tbpc_flags = lif;
4196 if(UNLIKELY(!a_tty_bind_parse(FAL0, &tbpc)))
4197 v = NULL;
4198 else if(UNLIKELY((tbcp = tbpc.tbpc_tbcp) == NULL)){
4199 n_err(_("`unbind': no such `bind'ing: %s %s\n"),
4200 a_tty_bind_ctx_maps[lif].tbcm_name, c.cp);
4201 v = NULL;
4202 }else
4203 a_tty_bind_del(&tbpc);
4206 if(aster && ++lif < n__LEXINPUT_CTX_MAX)
4207 goto jredo;
4208 jleave:
4209 NYD_LEAVE;
4210 return (v != NULL) ? EXIT_OK : EXIT_ERR;
4212 # endif /* HAVE_KEY_BINDINGS */
4214 #else /* HAVE_MLE */
4216 * The really-nothing-at-all implementation
4219 FL void
4220 n_tty_init(void){
4221 NYD_ENTER;
4222 NYD_LEAVE;
4225 FL void
4226 n_tty_destroy(void){
4227 NYD_ENTER;
4228 NYD_LEAVE;
4231 FL void
4232 n_tty_signal(int sig){
4233 NYD_X; /* Signal handler */
4234 UNUSED(sig);
4236 # ifdef HAVE_TERMCAP
4237 switch(sig){
4238 default:{
4239 sigset_t nset, oset;
4241 n_TERMCAP_SUSPEND(TRU1);
4242 a_tty_sigs_down();
4244 sigemptyset(&nset);
4245 sigaddset(&nset, sig);
4246 sigprocmask(SIG_UNBLOCK, &nset, &oset);
4247 n_raise(sig);
4248 /* When we come here we'll continue editing, so reestablish */
4249 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
4251 a_tty_sigs_up();
4252 n_TERMCAP_RESUME(TRU1);
4253 break;
4256 # endif /* HAVE_TERMCAP */
4259 FL int
4260 (n_tty_readline)(char const *prompt, char **linebuf, size_t *linesize, size_t n
4261 SMALLOC_DEBUG_ARGS){
4262 int rv;
4263 NYD_ENTER;
4265 if(prompt != NULL){
4266 if(*prompt != '\0')
4267 fputs(prompt, stdout);
4268 fflush(stdout);
4270 # ifdef HAVE_TERMCAP
4271 a_tty_sigs_up();
4272 # endif
4273 rv = (readline_restart)(stdin, linebuf, linesize,n SMALLOC_DEBUG_ARGSCALL);
4274 # ifdef HAVE_TERMCAP
4275 a_tty_sigs_down();
4276 # endif
4277 NYD_LEAVE;
4278 return rv;
4281 FL void
4282 n_tty_addhist(char const *s, bool_t isgabby){
4283 NYD_ENTER;
4284 UNUSED(s);
4285 UNUSED(isgabby);
4286 NYD_LEAVE;
4288 #endif /* nothing at all */
4290 #undef a_TTY_SIGNALS
4291 /* s-it-mode */