(BWDIC!) Rewrite variable handling..
[s-mailx.git] / tty.c
blob37261b076bf82ff2a388340baa4c60f5f2a790b8
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 #ifdef HAVE_READLINE
29 # include <readline/readline.h>
30 # ifdef HAVE_HISTORY
31 # include <readline/history.h>
32 # endif
33 #endif
35 #if defined HAVE_READLINE || defined HAVE_MLE || defined HAVE_TERMCAP
36 # define a_TTY_SIGNALS
37 #endif
39 /* Shared history support macros */
40 #ifdef HAVE_HISTORY
41 # define a_TTY_HISTFILE(S) \
42 do{\
43 char const *__hist_obsolete = ok_vlook(NAIL_HISTFILE);\
44 if(__hist_obsolete != NULL)\
45 OBSOLETE(_("please use *history-file* instead of *NAIL_HISTFILE*"));\
46 S = ok_vlook(history_file);\
47 if((S) == NULL)\
48 (S) = __hist_obsolete;\
49 if((S) != NULL)\
50 S = fexpand(S, FEXP_LOCAL | FEXP_NSHELL);\
51 }while(0)
53 # define a_TTY_HISTSIZE(V) \
54 do{\
55 char const *__hist_obsolete = ok_vlook(NAIL_HISTSIZE);\
56 char const *__sv = ok_vlook(history_size);\
57 long __rv;\
58 if(__hist_obsolete != NULL)\
59 OBSOLETE(_("please use *history-size* instead of *NAIL_HISTSIZE*"));\
60 if(__sv == NULL)\
61 __sv = __hist_obsolete;\
62 if(__sv == NULL || *__sv == '\0' || (__rv = strtol(__sv, NULL, 10)) == 0)\
63 (V) = HIST_SIZE;\
64 else if(__rv < 0)\
65 (V) = 0;\
66 else\
67 (V) = __rv;\
68 }while(0)
70 # define a_TTY_CHECK_ADDHIST(S,NOACT) \
71 do{\
72 switch(*(S)){\
73 case '\0':\
74 case ' ':\
75 case '\t':\
76 NOACT;\
77 default:\
78 break;\
80 }while(0)
82 # define C_HISTORY_SHARED \
83 char **argv = v;\
84 long entry;\
85 NYD_ENTER;\
87 if(*argv == NULL)\
88 goto jlist;\
89 if(argv[1] != NULL)\
90 goto jerr;\
91 if(!asccasecmp(*argv, "show"))\
92 goto jlist;\
93 if(!asccasecmp(*argv, "clear"))\
94 goto jclear;\
95 if((entry = strtol(*argv, argv, 10)) > 0 && **argv == '\0')\
96 goto jentry;\
97 jerr:\
98 n_err(_("Synopsis: history: %s\n" \
99 "<show> (default), <clear> or select <NO> from editor history"));\
100 v = NULL;\
101 jleave:\
102 NYD_LEAVE;\
103 return (v == NULL ? !STOP : !OKAY); /* xxx 1:bad 0:good -- do some */
104 #endif /* HAVE_HISTORY */
106 /* fexpand() flags for expand-on-tab */
107 #define a_TTY_TAB_FEXP_FL (FEXP_FULL | FEXP_SILENT | FEXP_MULTIOK)
109 #ifdef a_TTY_SIGNALS
110 static sighandler_type a_tty_oint, a_tty_oquit, a_tty_oterm,
111 a_tty_ohup,
112 a_tty_otstp, a_tty_ottin, a_tty_ottou;
113 #endif
115 #ifdef a_TTY_SIGNALS
116 static void a_tty_sigs_up(void), a_tty_sigs_down(void);
117 #endif
119 #ifdef a_TTY_SIGNALS
120 static void
121 a_tty_sigs_up(void){
122 sigset_t nset, oset;
123 NYD2_ENTER;
125 sigfillset(&nset);
127 sigprocmask(SIG_BLOCK, &nset, &oset);
128 a_tty_oint = safe_signal(SIGINT, &n_tty_signal);
129 a_tty_oquit = safe_signal(SIGQUIT, &n_tty_signal);
130 a_tty_oterm = safe_signal(SIGTERM, &n_tty_signal);
131 a_tty_ohup = safe_signal(SIGHUP, &n_tty_signal);
132 a_tty_otstp = safe_signal(SIGTSTP, &n_tty_signal);
133 a_tty_ottin = safe_signal(SIGTTIN, &n_tty_signal);
134 a_tty_ottou = safe_signal(SIGTTOU, &n_tty_signal);
135 sigprocmask(SIG_SETMASK, &oset, NULL);
136 NYD2_LEAVE;
139 static void
140 a_tty_sigs_down(void){
141 sigset_t nset, oset;
142 NYD2_ENTER;
144 sigfillset(&nset);
146 sigprocmask(SIG_BLOCK, &nset, &oset);
147 safe_signal(SIGINT, a_tty_oint);
148 safe_signal(SIGQUIT, a_tty_oquit);
149 safe_signal(SIGTERM, a_tty_oterm);
150 safe_signal(SIGHUP, a_tty_ohup);
151 safe_signal(SIGTSTP, a_tty_otstp);
152 safe_signal(SIGTTIN, a_tty_ottin);
153 safe_signal(SIGTTOU, a_tty_ottou);
154 sigprocmask(SIG_SETMASK, &oset, NULL);
155 NYD2_LEAVE;
157 #endif /* a_TTY_SIGNALS */
159 static sigjmp_buf a_tty__actjmp; /* TODO someday, we won't need it no more */
160 static void
161 a_tty__acthdl(int s) /* TODO someday, we won't need it no more */
163 NYD_X; /* Signal handler */
164 termios_state_reset();
165 siglongjmp(a_tty__actjmp, s);
168 FL bool_t
169 getapproval(char const * volatile prompt, bool_t noninteract_default)
171 sighandler_type volatile oint, ohup;
172 bool_t volatile rv;
173 int volatile sig;
174 NYD_ENTER;
176 if (!(options & OPT_INTERACTIVE)) {
177 sig = 0;
178 rv = noninteract_default;
179 goto jleave;
181 rv = FAL0;
183 /* C99 */{
184 char const *quest = noninteract_default
185 ? _("[yes]/no? ") : _("[no]/yes? ");
187 if (prompt == NULL)
188 prompt = _("Continue");
189 prompt = savecatsep(prompt, ' ', quest);
192 oint = safe_signal(SIGINT, SIG_IGN);
193 ohup = safe_signal(SIGHUP, SIG_IGN);
194 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
195 goto jrestore;
196 safe_signal(SIGINT, &a_tty__acthdl);
197 safe_signal(SIGHUP, &a_tty__acthdl);
199 if (n_lex_input(prompt, TRU1, &termios_state.ts_linebuf,
200 &termios_state.ts_linesize, NULL) >= 0)
201 rv = (boolify(termios_state.ts_linebuf, UIZ_MAX,
202 noninteract_default) > 0);
203 jrestore:
204 termios_state_reset();
206 safe_signal(SIGHUP, ohup);
207 safe_signal(SIGINT, oint);
208 jleave:
209 NYD_LEAVE;
210 if (sig != 0)
211 n_raise(sig);
212 return rv;
215 #ifdef HAVE_SOCKETS
216 FL char *
217 getuser(char const * volatile query) /* TODO v15-compat obsolete */
219 sighandler_type volatile oint, ohup;
220 char * volatile user = NULL;
221 int volatile sig;
222 NYD_ENTER;
224 if (query == NULL)
225 query = _("User: ");
227 oint = safe_signal(SIGINT, SIG_IGN);
228 ohup = safe_signal(SIGHUP, SIG_IGN);
229 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
230 goto jrestore;
231 safe_signal(SIGINT, &a_tty__acthdl);
232 safe_signal(SIGHUP, &a_tty__acthdl);
234 if (n_lex_input(query, TRU1, &termios_state.ts_linebuf,
235 &termios_state.ts_linesize, NULL) >= 0)
236 user = termios_state.ts_linebuf;
237 jrestore:
238 termios_state_reset();
240 safe_signal(SIGHUP, ohup);
241 safe_signal(SIGINT, oint);
242 NYD_LEAVE;
243 if (sig != 0)
244 n_raise(sig);
245 return user;
248 FL char *
249 getpassword(char const *query)
251 sighandler_type volatile oint, ohup;
252 struct termios tios;
253 char * volatile pass = NULL;
254 int volatile sig;
255 NYD_ENTER;
257 if (query == NULL)
258 query = _("Password: ");
259 fputs(query, stdout);
260 fflush(stdout);
262 /* FIXME everywhere: tcsetattr() generates SIGTTOU when we're not in
263 * FIXME foreground pgrp, and can fail with EINTR!! also affects
264 * FIXME termios_state_reset() */
265 if (options & OPT_TTYIN) {
266 tcgetattr(STDIN_FILENO, &termios_state.ts_tios);
267 memcpy(&tios, &termios_state.ts_tios, sizeof tios);
268 termios_state.ts_needs_reset = TRU1;
269 tios.c_iflag &= ~(ISTRIP);
270 tios.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
273 oint = safe_signal(SIGINT, SIG_IGN);
274 ohup = safe_signal(SIGHUP, SIG_IGN);
275 if ((sig = sigsetjmp(a_tty__actjmp, 1)) != 0)
276 goto jrestore;
277 safe_signal(SIGINT, &a_tty__acthdl);
278 safe_signal(SIGHUP, &a_tty__acthdl);
280 if (options & OPT_TTYIN)
281 tcsetattr(STDIN_FILENO, TCSAFLUSH, &tios);
283 if (readline_restart(stdin, &termios_state.ts_linebuf,
284 &termios_state.ts_linesize, 0) >= 0)
285 pass = termios_state.ts_linebuf;
286 jrestore:
287 termios_state_reset();
288 if (options & OPT_TTYIN)
289 putc('\n', stdout);
291 safe_signal(SIGHUP, ohup);
292 safe_signal(SIGINT, oint);
293 NYD_LEAVE;
294 if (sig != 0)
295 n_raise(sig);
296 return pass;
298 #endif /* HAVE_SOCKETS */
301 * readline(3)
303 #ifdef HAVE_READLINE
305 static char *a_tty_rl_buf; /* pre_input() hook: initial line */
306 static int a_tty_rl_buflen; /* content, and its length */
308 /* Our rl_pre_input_hook */
309 static int a_tty_rl_pre_input(void);
311 static int
312 a_tty_rl_pre_input(void){
313 NYD2_ENTER;
314 /* Handle leftover data from \ escaped former line */
315 rl_extend_line_buffer(a_tty_rl_buflen + 10);
316 memcpy(rl_line_buffer, a_tty_rl_buf, a_tty_rl_buflen +1);
317 rl_point = rl_end = a_tty_rl_buflen;
318 rl_pre_input_hook = (rl_hook_func_t*)NULL;
319 rl_redisplay();
320 NYD2_LEAVE;
321 return 0;
324 FL void
325 n_tty_init(void){
326 # ifdef HAVE_HISTORY
327 long hs;
328 char const *v;
329 # endif
330 NYD_ENTER;
332 rl_readline_name = UNCONST(uagent);
333 # ifdef HAVE_HISTORY
334 a_TTY_HISTSIZE(hs);
335 using_history();
336 stifle_history((int)hs);
337 # endif
338 rl_read_init_file(NULL);
340 /* Because rl_read_init_file() may have introduced yet a different
341 * history size limit, simply load and incorporate the history, leave
342 * it up to readline(3) to do the rest */
343 # ifdef HAVE_HISTORY
344 a_TTY_HISTFILE(v);
345 if(v != NULL)
346 read_history(v);
347 # endif
348 NYD_LEAVE;
351 FL void
352 n_tty_destroy(void){
353 # ifdef HAVE_HISTORY
354 char const *v;
355 # endif
356 NYD_ENTER;
358 # ifdef HAVE_HISTORY
359 a_TTY_HISTFILE(v);
360 if(v != NULL)
361 write_history(v);
362 # endif
363 NYD_LEAVE;
366 FL void
367 n_tty_signal(int sig){
368 NYD_X; /* Signal handler */
370 /* WINCH comes from main.c */
371 switch(sig){
372 # ifdef SIGWINCH
373 case SIGWINCH:
374 break;
375 # endif
376 default:{
377 sigset_t nset, oset;
379 /* readline(3) doesn't catch SIGHUP :( */
380 if(sig == SIGHUP){
381 rl_free_line_state();
382 rl_cleanup_after_signal();
384 n_TERMCAP_SUSPEND(TRU1);
385 a_tty_sigs_down();
387 sigemptyset(&nset);
388 sigaddset(&nset, sig);
389 sigprocmask(SIG_UNBLOCK, &nset, &oset);
390 n_raise(sig);
391 /* When we come here we'll continue editing, so reestablish */
392 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
394 a_tty_sigs_up();
395 n_TERMCAP_RESUME(TRU1);
396 if(sig == SIGHUP)
397 rl_reset_after_signal();
398 break;
403 FL int
404 (n_tty_readline)(char const *prompt, char **linebuf, size_t *linesize, size_t n
405 SMALLOC_DEBUG_ARGS){
406 int nn;
407 char *line;
408 NYD_ENTER;
410 if(n > 0){
411 a_tty_rl_buf = *linebuf;
412 a_tty_rl_buflen = (int)n;
413 rl_pre_input_hook = &a_tty_rl_pre_input;
416 a_tty_sigs_up();
417 n_TERMCAP_SUSPEND(FAL0);
418 line = readline(prompt != NULL ? prompt : "");
419 n_TERMCAP_RESUME(FAL0);
420 a_tty_sigs_down();
422 if(line == NULL){
423 nn = -1;
424 goto jleave;
426 n = strlen(line);
428 if(n >= *linesize){
429 *linesize = LINESIZE + n +1;
430 *linebuf = (srealloc)(*linebuf, *linesize SMALLOC_DEBUG_ARGSCALL);
432 memcpy(*linebuf, line, n);
433 (free)(line);
434 (*linebuf)[n] = '\0';
435 nn = (int)n;
436 jleave:
437 NYD_LEAVE;
438 return nn;
441 FL void
442 n_tty_addhist(char const *s, bool_t isgabby){
443 NYD_ENTER;
444 UNUSED(s);
445 UNUSED(isgabby);
447 # ifdef HAVE_HISTORY
448 if(isgabby && !ok_blook(history_gabby))
449 goto jleave;
450 a_TTY_CHECK_ADDHIST(s, goto jleave);
451 hold_all_sigs(); /* XXX too heavy */
452 add_history(s); /* XXX yet we jump away! */
453 rele_all_sigs(); /* XXX remove jumps */
454 jleave:
455 # endif
456 NYD_LEAVE;
459 # ifdef HAVE_HISTORY
460 FL int
461 c_history(void *v){
462 C_HISTORY_SHARED;
464 jlist:{
465 FILE *fp;
466 HISTORY_STATE *hs;
467 HIST_ENTRY **hl;
468 ul_i i, b;
470 if((fp = Ftmp(NULL, "hist", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
471 n_perr(_("tmpfile"), 0);
472 v = NULL;
473 goto jleave;
476 hs = history_get_history_state();
478 for(i = (ul_i)hs->length, hl = hs->entries + i, b = 0; i > 0; --i){
479 char *cp = (*--hl)->line;
480 size_t sl = strlen(cp);
482 fprintf(fp, "%4lu. %-50.50s (%4lu+%2lu B)\n", i, cp, b, sl);
483 b += sl;
486 page_or_print(fp, (size_t)hs->length);
487 Fclose(fp);
489 goto jleave;
491 jclear:
492 clear_history();
493 goto jleave;
495 jentry:{
496 HISTORY_STATE *hs = history_get_history_state();
498 if(UICMP(z, entry, <=, hs->length))
499 v = temporary_arg_v_store = hs->entries[entry - 1]->line;
500 else
501 v = NULL;
503 goto jleave;
505 # endif /* HAVE_HISTORY */
506 #endif /* HAVE_READLINE */
509 * MLE: the Mailx-Line-Editor, our homebrew editor
510 * (inspired from NetBSD sh(1) / dash(1)s hetio.c).
512 * Only used in interactive mode, simply use STDIN_FILENO as point of interest.
513 * TODO . After I/O layer rewrite, also "output to STDIN_FILENO".
514 * TODO . We work with wide characters, but not for buffer takeovers and
515 * TODO cell2save()ings. This should be changed. For the former the buffer
516 * TODO thus needs to be converted to wide first, and then simply be fed in.
517 * TODO . No BIDI support.
518 * TODO . We repaint too much. To overcome this use the same approach that my
519 * TODO terminal library uses, add a true "virtual screen line" that stores
520 * TODO the actually visible content, keep a notion of "first modified slot"
521 * TODO and "last modified slot" (including "unknown" and "any" specials),
522 * TODO update that virtual instead, then synchronize what has truly changed.
523 * TODO I.e., add an indirection layer.
525 #ifdef HAVE_MLE
526 /* To avoid memory leaks etc. with the current codebase that simply longjmp(3)s
527 * we're forced to use the very same buffer--the one that is passed through to
528 * us from the outside--to store anything we need, i.e., a "struct cell[]", and
529 * convert that on-the-fly back to the plain char* result once we're done.
530 * To simplify our live, use savestr() buffers for all other needed memory */
532 /* Columns to ripoff: outermost may not be touched, plus position indicator.
533 * Must thus be at least 1, but should be >= 1+4 to dig the position indicator
534 * that we place (if there is sufficient space) */
535 # define a_TTY_WIDTH_RIPOFF 5
537 /* When shall the visual screen be scrolled, in % of usable screen width */
538 # define a_TTY_SCROLL_MARGIN_LEFT 15
539 # define a_TTY_SCROLL_MARGIN_RIGHT 10
541 /* The maximum size (of a_tty_cell's) in a line */
542 # define a_TTY_LINE_MAX SI32_MAX
544 /* (Some more CTAs around) */
545 n_CTA(a_TTY_LINE_MAX <= SI32_MAX,
546 "a_TTY_LINE_MAX larger than SI32_MAX, but the MLE uses 32-bit arithmetic");
548 enum a_tty_visual_flags{
549 a_TTY_VF_NONE,
550 a_TTY_VF_MOD_CURSOR = 1<<0, /* Cursor moved */
551 a_TTY_VF_MOD_CONTENT = 1<<1, /* Content modified */
552 a_TTY_VF_MOD_DIRTY = 1<<2, /* Needs complete repaint */
553 a_TTY_VF_MOD_SINGLE = 1<<3, /* TODO Drop when indirection as above comes */
554 a_TTY_VF_REFRESH = a_TTY_VF_MOD_DIRTY | a_TTY_VF_MOD_CURSOR |
555 a_TTY_VF_MOD_CONTENT | a_TTY_VF_MOD_SINGLE,
556 a_TTY_VF_BELL = 1<<8, /* Ring the bell */
557 a_TTY_VF_SYNC = 1<<9, /* Flush/Sync I/O channel */
559 a_TTY_VF_ALL_MASK = a_TTY_VF_REFRESH | a_TTY_VF_BELL | a_TTY_VF_SYNC,
560 a_TTY__VF_LAST = a_TTY_VF_SYNC
563 struct a_tty_global{
564 # ifdef HAVE_HISTORY
565 struct a_tty_hist *tg_hist;
566 struct a_tty_hist *tg_hist_tail;
567 size_t tg_hist_size;
568 size_t tg_hist_size_max;
569 # endif
570 struct termios tg_tios_old;
571 struct termios tg_tios_new;
574 struct a_tty_cell{
575 wchar_t tc_wc;
576 ui16_t tc_count; /* ..of bytes */
577 ui8_t tc_width; /* Visual width; TAB==UI8_MAX! */
578 bool_t tc_novis; /* Don't display visually as such (control character) */
579 char tc_cbuf[MB_LEN_MAX * 2]; /* .. plus reset shift sequence */
582 struct a_tty_line{
583 /* Caller pointers */
584 char **tl_x_buf;
585 size_t *tl_x_bufsize;
586 /* Input processing */
587 char const *tl_reenter_after_cmd; /* `bind' cmd to exec, then re-readline */
588 /* Line data / content handling */
589 ui32_t tl_count; /* ..of a_tty_cell's (<= a_TTY_LINE_MAX) */
590 ui32_t tl_cursor; /* Current a_tty_cell insertion point */
591 union{
592 char *cbuf; /* *.tl_x_buf */
593 struct a_tty_cell *cells;
594 } tl_line;
595 struct str tl_defc; /* Current default content */
596 struct str tl_savec; /* Saved default content */
597 struct str tl_yankbuf; /* Last yanked data */
598 # ifdef HAVE_HISTORY
599 struct a_tty_hist *tl_hist; /* History cursor */
600 # endif
601 ui32_t tl_count_max; /* ..before buffer needs to grow */
602 /* Visual data representation handling */
603 ui32_t tl_vi_flags; /* enum a_tty_visual_flags */
604 ui32_t tl_lst_count; /* .tl_count after last sync */
605 ui32_t tl_lst_cursor; /* .tl_cursor after last sync */
606 /* TODO Add another indirection layer by adding a tl_phy_line of
607 * TODO a_tty_cell objects, incorporate changes in visual layer,
608 * TODO then check what _really_ has changed, sync those changes only */
609 struct a_tty_cell const *tl_phy_start; /* First visible cell, left border */
610 ui32_t tl_phy_cursor; /* Physical cursor position */
611 ui32_t tl_prompt_length; /* Preclassified (TODO needed as a_tty_cell) */
612 ui32_t tl_prompt_width;
613 ui8_t tl__dummy[4];
614 char const *tl_prompt; /* Preformatted prompt (including colours) */
615 /* .tl_pos_buf is a hack */
616 # ifdef HAVE_COLOUR
617 char *tl_pos_buf; /* mle-position colour-on, [4], reset seq. */
618 char *tl_pos; /* Address of the [4] */
619 # endif
622 # ifdef HAVE_HISTORY
623 struct a_tty_hist{
624 struct a_tty_hist *th_older;
625 struct a_tty_hist *th_younger;
626 ui32_t th_isgabby : 1;
627 ui32_t th_len : 31;
628 char th_dat[VFIELD_SIZE(sizeof(ui32_t))];
630 # endif
632 static struct a_tty_global a_tty;
634 /**/
635 static void a_tty_term_mode(bool_t raw);
637 /* 0-X (2), UI8_MAX == \t / TAB */
638 static ui8_t a_tty_wcwidth(wchar_t wc);
640 /* Memory / cell / word generics */
641 static void a_tty_check_grow(struct a_tty_line *tlp, ui32_t no
642 SMALLOC_DEBUG_ARGS);
643 static ssize_t a_tty_cell2dat(struct a_tty_line *tlp);
644 static void a_tty_cell2save(struct a_tty_line *tlp);
646 /* Save away data bytes of given range (max = non-inclusive) */
647 static void a_tty_yank(struct a_tty_line *tlp, struct a_tty_cell *tcpmin,
648 struct a_tty_cell *tcpmax);
650 /* Ask user for hexadecimal number, interpret as UTF-32 */
651 static wchar_t a_tty_vinuni(struct a_tty_line *tlp);
653 /* Visual screen synchronization */
654 static bool_t a_tty_vi_refresh(struct a_tty_line *tlp);
656 /* Search for word boundary, starting at tl_cursor, in "dir"ection (<> 0).
657 * Return <0 when moving is impossible (backward direction but in position 0,
658 * forward direction but in outermost column), and relative distance to
659 * tl_cursor otherwise */
660 static si32_t a_tty_wboundary(struct a_tty_line *tlp, si32_t dir);
662 /* Key actions */
663 static void a_tty_khome(struct a_tty_line *tlp, bool_t dobell);
664 static void a_tty_kend(struct a_tty_line *tlp);
665 static void a_tty_kbs(struct a_tty_line *tlp);
666 static void a_tty_kkill(struct a_tty_line *tlp, bool_t dobell);
667 static si32_t a_tty_kdel(struct a_tty_line *tlp);
668 static void a_tty_kleft(struct a_tty_line *tlp);
669 static void a_tty_kright(struct a_tty_line *tlp);
670 static void a_tty_kbwddelw(struct a_tty_line *tlp);
671 static void a_tty_kgow(struct a_tty_line *tlp, si32_t dir);
672 static void a_tty_kother(struct a_tty_line *tlp, wchar_t wc);
673 static ui32_t a_tty_kht(struct a_tty_line *tlp);
674 # ifdef HAVE_HISTORY
675 static ui32_t a_tty__khist_shared(struct a_tty_line *tlp,
676 struct a_tty_hist *thp);
677 static ui32_t a_tty_khist(struct a_tty_line *tlp, bool_t backwd);
678 static ui32_t a_tty_krhist(struct a_tty_line *tlp);
679 # endif
681 /* Readline core */
682 static ssize_t a_tty_readline(struct a_tty_line *tlp, size_t len
683 SMALLOC_DEBUG_ARGS);
685 static void
686 a_tty_term_mode(bool_t raw){
687 struct termios *tiosp;
688 NYD2_ENTER;
690 tiosp = &a_tty.tg_tios_old;
691 if(!raw)
692 goto jleave;
694 /* Always requery the attributes, in case we've been moved from background
695 * to foreground or however else in between sessions */
696 /* XXX Always enforce ECHO and ICANON in the OLD attributes - do so as long
697 * XXX as we don't properly deal with TTIN and TTOU etc. */
698 tcgetattr(STDIN_FILENO, tiosp);
699 tiosp->c_lflag |= ECHO | ICANON;
701 memcpy(&a_tty.tg_tios_new, tiosp, sizeof *tiosp);
702 tiosp = &a_tty.tg_tios_new;
703 tiosp->c_cc[VMIN] = 1;
704 tiosp->c_cc[VTIME] = 0;
705 tiosp->c_iflag &= ~(ISTRIP);
706 tiosp->c_lflag &= ~(ECHO /*| ECHOE | ECHONL */| ICANON | IEXTEN);
707 jleave:
708 tcsetattr(STDIN_FILENO, TCSADRAIN, tiosp);
709 NYD2_LEAVE;
712 static ui8_t
713 a_tty_wcwidth(wchar_t wc){
714 ui8_t rv;
715 NYD2_ENTER;
717 /* Special case the backslash at first */
718 if(wc == '\t')
719 rv = UI8_MAX;
720 else{
721 int i;
723 # ifdef HAVE_WCWIDTH
724 rv = ((i = wcwidth(wc)) > 0) ? (ui8_t)i : 0;
725 # else
726 rv = iswprint(wc) ? 1 + (wc >= 0x1100u) : 0; /* TODO use S-CText */
727 # endif
729 NYD2_LEAVE;
730 return rv;
733 static void
734 a_tty_check_grow(struct a_tty_line *tlp, ui32_t no SMALLOC_DEBUG_ARGS){
735 ui32_t cmax;
736 NYD2_ENTER;
738 if(UNLIKELY((cmax = tlp->tl_count + no) > tlp->tl_count_max)){
739 size_t i;
741 i = cmax * sizeof(struct a_tty_cell) + 2 * sizeof(struct a_tty_cell);
742 if(LIKELY(i >= *tlp->tl_x_bufsize)){
743 hold_all_sigs(); /* XXX v15 drop */
744 i <<= 1;
745 tlp->tl_line.cbuf =
746 *tlp->tl_x_buf = (srealloc)(*tlp->tl_x_buf, i SMALLOC_DEBUG_ARGSCALL);
747 rele_all_sigs(); /* XXX v15 drop */
749 tlp->tl_count_max = cmax;
750 *tlp->tl_x_bufsize = i;
752 NYD2_LEAVE;
755 static ssize_t
756 a_tty_cell2dat(struct a_tty_line *tlp){
757 size_t len, i;
758 NYD2_ENTER;
760 len = 0;
762 if(LIKELY((i = tlp->tl_count) > 0)){
763 struct a_tty_cell const *tcap;
765 tcap = tlp->tl_line.cells;
767 memcpy(tlp->tl_line.cbuf + len, tcap->tc_cbuf, tcap->tc_count);
768 len += tcap->tc_count;
769 }while(++tcap, --i > 0);
772 tlp->tl_line.cbuf[len] = '\0';
773 NYD2_LEAVE;
774 return (ssize_t)len;
777 static void
778 a_tty_cell2save(struct a_tty_line *tlp){
779 size_t len, i;
780 struct a_tty_cell *tcap;
781 NYD2_ENTER;
783 tlp->tl_savec.s = NULL;
784 tlp->tl_savec.l = 0;
786 if(UNLIKELY(tlp->tl_count == 0))
787 goto jleave;
789 for(tcap = tlp->tl_line.cells, len = 0, i = tlp->tl_count; i > 0;
790 ++tcap, --i)
791 len += tcap->tc_count;
793 tlp->tl_savec.s = salloc((tlp->tl_savec.l = len) +1);
795 for(tcap = tlp->tl_line.cells, len = 0, i = tlp->tl_count; i > 0;
796 ++tcap, --i){
797 memcpy(tlp->tl_savec.s + len, tcap->tc_cbuf, tcap->tc_count);
798 len += tcap->tc_count;
800 tlp->tl_savec.s[len] = '\0';
801 jleave:
802 NYD2_LEAVE;
805 static void
806 a_tty_yank(struct a_tty_line *tlp, struct a_tty_cell *tcpmin,
807 struct a_tty_cell *tcpmax){
808 char *cp;
809 struct a_tty_cell *tcp;
810 size_t l;
811 NYD2_ENTER;
813 l = 0;
814 for(tcp = tcpmin; tcp < tcpmax; ++tcp)
815 l += tcp->tc_count;
817 tlp->tl_yankbuf.s = cp = salloc((tlp->tl_yankbuf.l = l) +1);
819 l = 0;
820 for(tcp = tcpmin; tcp < tcpmax; cp += l, ++tcp)
821 memcpy(cp, tcp->tc_cbuf, l = tcp->tc_count);
822 *cp = '\0';
823 NYD2_LEAVE;
826 static wchar_t
827 a_tty_vinuni(struct a_tty_line *tlp){
828 char buf[16], *eptr;
829 union {size_t i; long l;} u;
830 wchar_t wc;
831 NYD2_ENTER;
833 wc = 0;
835 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
836 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr) ||
837 !n_termcap_cmd(n_TERMCAP_CMD_ce, 0, -1))
838 goto jleave;
840 /* C99 */{
841 struct str const *cpre, *csuf;
842 #ifdef HAVE_COLOUR
843 struct n_colour_pen *cpen;
845 cpen = n_colour_pen_create(n_COLOUR_ID_MLE_PROMPT, NULL);
846 if((cpre = n_colour_pen_to_str(cpen)) != NULL)
847 csuf = n_colour_reset_to_str();
848 else
849 csuf = NULL;
850 #else
851 cpre = csuf = NULL;
852 #endif
853 printf(_("%sPlease enter Unicode code point:%s "),
854 (cpre != NULL ? cpre->s : ""), (csuf != NULL ? csuf->s : ""));
856 fflush(stdout);
858 buf[sizeof(buf) -1] = '\0';
859 for(u.i = 0;;){
860 if(read(STDIN_FILENO, &buf[u.i], 1) != 1){
861 if(errno == EINTR) /* xxx #if !SA_RESTART ? */
862 continue;
863 goto jleave;
865 if(buf[u.i] == '\n')
866 break;
867 if(!hexchar(buf[u.i])){
868 char const emsg[] = "[0-9a-fA-F]";
870 LCTA(sizeof emsg <= sizeof(buf));
871 memcpy(buf, emsg, sizeof emsg);
872 goto jerr;
875 putc(buf[u.i], stdout);
876 fflush(stdout);
877 if(++u.i == sizeof buf)
878 goto jerr;
880 buf[u.i] = '\0';
882 u.l = strtol(buf, &eptr, 16);
883 if(u.l <= 0 || u.l >= 0x10FFFF/* XXX magic; CText */ || *eptr != '\0'){
884 jerr:
885 n_err(_("\nInvalid input: %s\n"), buf);
886 goto jleave;
889 wc = (wchar_t)u.l;
890 jleave:
891 NYD2_LEAVE;
892 return wc;
895 static bool_t
896 a_tty_vi_refresh(struct a_tty_line *tlp){
897 enum{
898 a_TRUE_RV = a_TTY__VF_LAST<<1, /* Return value bit */
899 a_HAVE_PROMPT = a_TTY__VF_LAST<<2, /* Have a prompt */
900 a_SHOW_PROMPT = a_TTY__VF_LAST<<3, /* Shall print the prompt */
901 a_MOVE_CURSOR = a_TTY__VF_LAST<<4, /* Move visual cursor for user! */
902 a_LEFT_MIN = a_TTY__VF_LAST<<5, /* On left boundary */
903 a_RIGHT_MAX = a_TTY__VF_LAST<<6,
904 a_HAVE_POSITION = a_TTY__VF_LAST<<7, /* Print the position indicator */
906 /* We carry some flags over invocations (not worth a specific field) */
907 a_VISIBLE_PROMPT = a_TTY__VF_LAST<<8, /* The prompt is on the screen */
908 a_PERSIST_MASK = a_VISIBLE_PROMPT,
909 a__LAST = a_PERSIST_MASK
912 ui32_t f, w, phy_wid_base, phy_wid, phy_base, phy_cur, cnt, lstcur, cur,
913 vi_left, vi_right, phy_nxtcur;
914 struct a_tty_cell const *tccp, *tcp_left, *tcp_right, *tcxp;
915 NYD2_ENTER;
916 n_LCTA(UICMP(64, a__LAST, <, UI32_MAX), "Flag bits excess storage datatype");
918 f = tlp->tl_vi_flags;
919 tlp->tl_vi_flags = (f & ~(a_TTY_VF_REFRESH | a_PERSIST_MASK)) |
920 a_TTY_VF_SYNC;
921 f |= a_TRUE_RV;
922 if((w = tlp->tl_prompt_length) > 0)
923 f |= a_HAVE_PROMPT;
924 f |= a_HAVE_POSITION;
926 /* XXX We don't have a OnTerminalResize event (see main.c) yet, so we need
927 * XXX to reevaluate our circumstances over and over again */
928 /* Don't display prompt or position indicator on very small screens */
929 if((phy_wid_base = (ui32_t)scrnwidth) <= a_TTY_WIDTH_RIPOFF)
930 f &= ~(a_HAVE_PROMPT | a_HAVE_POSITION);
931 else{
932 phy_wid_base -= a_TTY_WIDTH_RIPOFF;
934 /* Disable the prompt if the screen is too small; due to lack of some
935 * indicator simply add a second ripoff */
936 if((f & a_HAVE_PROMPT) && w + a_TTY_WIDTH_RIPOFF >= phy_wid_base)
937 f &= ~a_HAVE_PROMPT;
940 phy_wid = phy_wid_base;
941 phy_base = 0;
942 phy_cur = tlp->tl_phy_cursor;
943 cnt = tlp->tl_count;
944 lstcur = tlp->tl_lst_cursor;
946 /* XXX Assume dirty screen if shrunk */
947 if(cnt < tlp->tl_lst_count)
948 f |= a_TTY_VF_MOD_DIRTY;
950 /* TODO Without HAVE_TERMCAP, it would likely be much cheaper to simply
951 * TODO always "cr + paint + ce + ch", since ce is simulated via spaces.. */
953 /* Quickshot: if the line is empty, possibly print prompt and out */
954 if(cnt == 0){
955 /* In that special case dirty anything if it seems better */
956 if((f & a_TTY_VF_MOD_CONTENT) || tlp->tl_lst_count > 0)
957 f |= a_TTY_VF_MOD_DIRTY;
959 if((f & a_TTY_VF_MOD_DIRTY) && phy_cur != 0){
960 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
961 goto jerr;
962 phy_cur = 0;
965 if((f & (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)) ==
966 (a_TTY_VF_MOD_DIRTY | a_HAVE_PROMPT)){
967 if(fputs(tlp->tl_prompt, stdout) == EOF)
968 goto jerr;
969 phy_cur = tlp->tl_prompt_width + 1;
972 /* May need to clear former line content */
973 if((f & a_TTY_VF_MOD_DIRTY) &&
974 !n_termcap_cmd(n_TERMCAP_CMD_ce, phy_cur, -1))
975 goto jerr;
977 tlp->tl_phy_start = tlp->tl_line.cells;
978 goto jleave;
981 /* Try to get an idea of the visual window */
983 /* Find the left visual boundary */
984 phy_wid = (phy_wid >> 1) + (phy_wid >> 2);
985 if((cur = tlp->tl_cursor) == cnt)
986 --cur;
988 w = (tcp_left = tccp = tlp->tl_line.cells + cur)->tc_width;
989 if(w == UI8_MAX) /* TODO yet TAB == SPC */
990 w = 1;
991 while(tcp_left > tlp->tl_line.cells){
992 ui16_t cw = tcp_left[-1].tc_width;
994 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
995 cw = 1;
996 if(w + cw >= phy_wid)
997 break;
998 w += cw;
999 --tcp_left;
1001 vi_left = w;
1003 /* If the left hand side of our visual viewpoint consumes less than half
1004 * of the screen width, show the prompt */
1005 if(tcp_left == tlp->tl_line.cells)
1006 f |= a_LEFT_MIN;
1008 if((f & (a_LEFT_MIN | a_HAVE_PROMPT)) == (a_LEFT_MIN | a_HAVE_PROMPT) &&
1009 w + tlp->tl_prompt_width < phy_wid){
1010 phy_base = tlp->tl_prompt_width;
1011 f |= a_SHOW_PROMPT;
1014 /* Then search for right boundary. We always leave the rightmost column
1015 * empty because some terminals [cw]ould wrap the line if we write into
1016 * that. XXX terminfo(5)/termcap(5) have the semi_auto_right_margin/sam/YE
1017 * XXX capability to indicate this, but we don't look at that */
1018 phy_wid = phy_wid_base - phy_base;
1019 tcp_right = tlp->tl_line.cells + cnt;
1021 while(&tccp[1] < tcp_right){
1022 ui16_t cw = tccp[1].tc_width;
1023 ui32_t i;
1025 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1026 cw = 1;
1027 i = w + cw;
1028 if(i > phy_wid)
1029 break;
1030 w = i;
1031 ++tccp;
1033 vi_right = w - vi_left;
1035 /* If the complete line including prompt fits on the screen, show prompt */
1036 if(--tcp_right == tccp){
1037 f |= a_RIGHT_MAX;
1039 /* Since we did brute-force walk also for the left boundary we may end up
1040 * in a situation were anything effectively fits on the screen, including
1041 * the prompt that is, but were we don't recognize this since we
1042 * restricted the search to fit in some visual viewpoint. Therefore try
1043 * again to extend the left boundary to overcome that */
1044 if(!(f & a_LEFT_MIN)){
1045 struct a_tty_cell const *tc1p = tlp->tl_line.cells;
1046 ui32_t vil1 = vi_left;
1048 assert(!(f & a_SHOW_PROMPT));
1049 w += tlp->tl_prompt_width;
1050 for(tcxp = tcp_left;;){
1051 ui32_t i = tcxp[-1].tc_width;
1053 if(i == UI8_MAX) /* TODO yet TAB == SPC */
1054 i = 1;
1055 vil1 += i;
1056 i += w;
1057 if(i > phy_wid)
1058 break;
1059 w = i;
1060 if(--tcxp == tc1p){
1061 tcp_left = tc1p;
1062 vi_left = vil1;
1063 f |= a_LEFT_MIN;
1064 break;
1067 /*w -= tlp->tl_prompt_width;*/
1070 tcp_right = tccp;
1071 tccp = tlp->tl_line.cells + cur;
1073 if((f & (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT | a_SHOW_PROMPT)) ==
1074 (a_LEFT_MIN | a_RIGHT_MAX | a_HAVE_PROMPT) &&
1075 w + tlp->tl_prompt_width <= phy_wid){
1076 phy_wid -= (phy_base = tlp->tl_prompt_width);
1077 f |= a_SHOW_PROMPT;
1080 /* Try to avoid repainting the complete line - this is possible if the
1081 * cursor "did not leave the screen" and the prompt status hasn't changed.
1082 * I.e., after clamping virtual viewpoint, compare relation to physical */
1083 if((f & (a_TTY_VF_MOD_SINGLE/*FIXME*/ |
1084 a_TTY_VF_MOD_CONTENT/* xxx */ | a_TTY_VF_MOD_DIRTY)) ||
1085 (tcxp = tlp->tl_phy_start) == NULL ||
1086 tcxp > tccp || tcxp <= tcp_right)
1087 f |= a_TTY_VF_MOD_DIRTY;
1088 else{
1089 f |= a_TTY_VF_MOD_DIRTY;
1090 #if 0
1091 struct a_tty_cell const *tcyp;
1092 si32_t cur_displace;
1093 ui32_t phy_lmargin, phy_rmargin, fx, phy_displace;
1095 phy_lmargin = (fx = phy_wid) / 100;
1096 phy_rmargin = fx - (phy_lmargin * a_TTY_SCROLL_MARGIN_RIGHT);
1097 phy_lmargin *= a_TTY_SCROLL_MARGIN_LEFT;
1098 fx = (f & (a_SHOW_PROMPT | a_VISIBLE_PROMPT));
1100 if(fx == 0 || fx == (a_SHOW_PROMPT | a_VISIBLE_PROMPT)){
1102 #endif
1104 goto jpaint;
1106 /* We know what we have to paint, start synchronizing */
1107 jpaint:
1108 assert(phy_cur == tlp->tl_phy_cursor);
1109 assert(phy_wid == phy_wid_base - phy_base);
1110 assert(cnt == tlp->tl_count);
1111 assert(cnt > 0);
1112 assert(lstcur == tlp->tl_lst_cursor);
1113 assert(tccp == tlp->tl_line.cells + cur);
1115 phy_nxtcur = phy_base; /* FIXME only if repaint cpl. */
1117 /* Quickshot: is it only cursor movement within the visible screen? */
1118 if((f & a_TTY_VF_REFRESH) == a_TTY_VF_MOD_CURSOR){
1119 f |= a_MOVE_CURSOR;
1120 goto jcursor;
1123 /* To be able to apply some quick jump offs, clear line if possible */
1124 if(f & a_TTY_VF_MOD_DIRTY){
1125 /* Force complete clearance and cursor reinitialization */
1126 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr) ||
1127 !n_termcap_cmd(n_TERMCAP_CMD_ce, 0, -1))
1128 goto jerr;
1129 tlp->tl_phy_start = tcp_left;
1130 phy_cur = 0;
1133 if((f & (a_TTY_VF_MOD_DIRTY | a_SHOW_PROMPT)) && phy_cur != 0){
1134 if(!n_termcap_cmdx(n_TERMCAP_CMD_cr))
1135 goto jerr;
1136 phy_cur = 0;
1139 if(f & a_SHOW_PROMPT){
1140 assert(phy_base == tlp->tl_prompt_width);
1141 if(fputs(tlp->tl_prompt, stdout) == EOF)
1142 goto jerr;
1143 phy_cur = phy_nxtcur;
1144 f |= a_VISIBLE_PROMPT;
1145 }else
1146 f &= ~a_VISIBLE_PROMPT;
1148 /* FIXME reposition cursor for paint */
1149 for(w = phy_nxtcur; tcp_left <= tcp_right; ++tcp_left){
1150 ui16_t cw;
1152 cw = tcp_left->tc_width;
1154 if(LIKELY(!tcp_left->tc_novis)){
1155 if(fwrite(tcp_left->tc_cbuf, sizeof *tcp_left->tc_cbuf,
1156 tcp_left->tc_count, stdout) != tcp_left->tc_count)
1157 goto jerr;
1158 }else{ /* XXX Shouldn't be here <-> CText, ui_str.c */
1159 char wbuf[8]; /* XXX magic */
1161 if(options & OPT_UNICODE){
1162 ui32_t wc;
1164 wc = (ui32_t)tcp_left->tc_wc;
1165 if((wc & ~0x1Fu) == 0)
1166 wc |= 0x2400;
1167 else if(wc == 0x7F)
1168 wc = 0x2421;
1169 else
1170 wc = 0x2426;
1171 n_utf32_to_utf8(wc, wbuf);
1172 }else
1173 wbuf[0] = '?', wbuf[1] = '\0';
1175 if(fputs(wbuf, stdout) == EOF)
1176 goto jerr;
1177 cw = 1;
1180 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1181 cw = 1;
1182 w += cw;
1183 if(tcp_left == tccp)
1184 phy_nxtcur = w;
1185 phy_cur += cw;
1188 /* Write something position marker alike if it doesn't fit on screen */
1189 if((f & a_HAVE_POSITION) &&
1190 ((f & (a_LEFT_MIN | a_RIGHT_MAX)) != (a_LEFT_MIN | a_RIGHT_MAX) ||
1191 ((f & a_HAVE_PROMPT) && !(f & a_SHOW_PROMPT)))){
1192 # ifdef HAVE_COLOUR
1193 char *posbuf = tlp->tl_pos_buf, *pos = tlp->tl_pos;
1194 # else
1195 char posbuf[5], *pos = posbuf;
1197 pos[4] = '\0';
1198 # endif
1200 if(phy_cur != (w = phy_wid_base) &&
1201 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = w, 0))
1202 goto jerr;
1204 *pos++ = '|';
1205 if((f & a_LEFT_MIN) && (!(f & a_HAVE_PROMPT) || (f & a_SHOW_PROMPT)))
1206 memcpy(pos, "^.+", 3);
1207 else if(f & a_RIGHT_MAX)
1208 memcpy(pos, ".+$", 3);
1209 else{
1210 /* Theoretical line length limit a_TTY_LINE_MAX, choose next power of
1211 * ten (10 ** 10) to represent 100 percent, since we don't have a macro
1212 * that generates a constant, and i don't trust the standard "u type
1213 * suffix automatically scales" calculate the large number */
1214 static char const itoa[] = "0123456789";
1216 ui64_t const fact100 = (ui64_t)0x3B9ACA00u * 10u, fact = fact100 / 100;
1217 ui32_t i = (ui32_t)(((fact100 / cnt) * tlp->tl_cursor) / fact);
1218 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1220 if(i < 10)
1221 pos[0] = ' ', pos[1] = itoa[i];
1222 else
1223 pos[1] = itoa[i % 10], pos[0] = itoa[i / 10];
1224 pos[2] = '%';
1227 if(fputs(posbuf, stdout) == EOF)
1228 goto jerr;
1229 phy_cur += 4;
1232 /* Users are used to see the cursor right of the point of interest, so we
1233 * need some further adjustments unless in special conditions. Be aware
1234 * that we may have adjusted cur at the beginning, too */
1235 if((cur = tlp->tl_cursor) == 0)
1236 phy_nxtcur = phy_base;
1237 else if(cur != cnt){
1238 ui16_t cw = tccp->tc_width;
1240 if(cw == UI8_MAX) /* TODO yet TAB == SPC */
1241 cw = 1;
1242 phy_nxtcur -= cw;
1245 jcursor:
1246 if(((f & a_MOVE_CURSOR) || phy_nxtcur != phy_cur) &&
1247 !n_termcap_cmd(n_TERMCAP_CMD_ch, phy_cur = phy_nxtcur, 0))
1248 goto jerr;
1250 jleave:
1251 tlp->tl_vi_flags |= (f & a_PERSIST_MASK);
1252 tlp->tl_lst_count = tlp->tl_count;
1253 tlp->tl_lst_cursor = tlp->tl_cursor;
1254 tlp->tl_phy_cursor = phy_cur;
1256 NYD2_LEAVE;
1257 return ((f & a_TRUE_RV) != 0);
1258 jerr:
1259 f &= ~a_TRUE_RV;
1260 goto jleave;
1263 static si32_t
1264 a_tty_wboundary(struct a_tty_line *tlp, si32_t dir){
1265 bool_t anynon;
1266 struct a_tty_cell *tcap;
1267 ui32_t cur, cnt;
1268 si32_t rv;
1269 NYD2_ENTER;
1271 assert(dir == 1 || dir == -1);
1273 rv = -1;
1274 cnt = tlp->tl_count;
1275 cur = tlp->tl_cursor;
1277 if(dir < 0){
1278 if(cur == 0)
1279 goto jleave;
1280 }else if(cur + 1 >= cnt)
1281 goto jleave;
1282 else
1283 --cnt, --cur; /* xxx Unsigned wrapping may occur (twice), then */
1285 for(rv = 0, tcap = tlp->tl_line.cells, anynon = FAL0;;){
1286 wchar_t wc;
1288 wc = tcap[cur += (ui32_t)dir].tc_wc;
1289 if(iswblank(wc) || iswpunct(wc)){
1290 if(anynon)
1291 break;
1292 }else
1293 anynon = TRU1;
1295 ++rv;
1297 if(dir < 0){
1298 if(cur == 0)
1299 break;
1300 }else if(cur + 1 >= cnt){
1301 ++rv;
1302 break;
1305 jleave:
1306 NYD2_LEAVE;
1307 return rv;
1310 static void
1311 a_tty_khome(struct a_tty_line *tlp, bool_t dobell){
1312 ui32_t f;
1313 NYD2_ENTER;
1315 if(LIKELY(tlp->tl_cursor > 0)){
1316 tlp->tl_cursor = 0;
1317 f = a_TTY_VF_MOD_CURSOR;
1318 }else if(dobell)
1319 f = a_TTY_VF_BELL;
1320 else
1321 f = a_TTY_VF_NONE;
1323 tlp->tl_vi_flags |= f;
1324 NYD2_LEAVE;
1327 static void
1328 a_tty_kend(struct a_tty_line *tlp){
1329 ui32_t f;
1330 NYD2_ENTER;
1332 if(LIKELY(tlp->tl_cursor < tlp->tl_count)){
1333 tlp->tl_cursor = tlp->tl_count;
1334 f = a_TTY_VF_MOD_CURSOR;
1335 }else
1336 f = a_TTY_VF_BELL;
1338 tlp->tl_vi_flags |= f;
1339 NYD2_LEAVE;
1342 static void
1343 a_tty_kbs(struct a_tty_line *tlp){
1344 ui32_t f, cur, cnt;
1345 NYD2_ENTER;
1347 cur = tlp->tl_cursor;
1348 cnt = tlp->tl_count;
1350 if(LIKELY(cur > 0)){
1351 tlp->tl_cursor = --cur;
1352 tlp->tl_count = --cnt;
1354 if((cnt -= cur) > 0){
1355 struct a_tty_cell *tcap;
1357 tcap = tlp->tl_line.cells + cur;
1358 memmove(tcap, &tcap[1], cnt *= sizeof(*tcap));
1360 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
1361 }else
1362 f = a_TTY_VF_BELL;
1364 tlp->tl_vi_flags |= f;
1365 NYD2_LEAVE;
1368 static void
1369 a_tty_kkill(struct a_tty_line *tlp, bool_t dobell){
1370 ui32_t i;
1371 NYD2_ENTER;
1373 if(LIKELY((i = tlp->tl_cursor) < tlp->tl_count)){
1374 struct a_tty_cell *tcap;
1376 tcap = &tlp->tl_line.cells[0];
1377 a_tty_yank(tlp, &tcap[i], &tcap[tlp->tl_count]);
1378 tlp->tl_count = i;
1379 i = a_TTY_VF_MOD_CONTENT;
1380 }else if(dobell)
1381 i = a_TTY_VF_BELL;
1382 else
1383 i = a_TTY_VF_NONE;
1385 tlp->tl_vi_flags |= i;
1386 NYD2_LEAVE;
1389 static si32_t
1390 a_tty_kdel(struct a_tty_line *tlp){
1391 ui32_t cur, cnt, f;
1392 si32_t i;
1393 NYD2_ENTER;
1395 cur = tlp->tl_cursor;
1396 cnt = tlp->tl_count;
1397 i = (si32_t)(cnt - cur);
1399 if(LIKELY(i > 0)){
1400 tlp->tl_count = --cnt;
1402 if(LIKELY(--i > 0)){
1403 struct a_tty_cell *tcap;
1405 tcap = &tlp->tl_line.cells[cur];
1406 memmove(tcap, &tcap[1], (ui32_t)i * sizeof(*tcap));
1408 f = a_TTY_VF_MOD_CONTENT;
1409 }else if(cnt == 0 && !ok_blook(ignoreeof)){
1410 putchar('^');
1411 putchar('D');
1412 i = -1;
1413 f = a_TTY_VF_NONE;
1414 }else{
1415 i = 0;
1416 f = a_TTY_VF_BELL;
1419 tlp->tl_vi_flags |= f;
1420 NYD2_LEAVE;
1421 return i;
1424 static void
1425 a_tty_kleft(struct a_tty_line *tlp){
1426 ui32_t f;
1427 NYD2_ENTER;
1429 if(LIKELY(tlp->tl_cursor > 0)){
1430 --tlp->tl_cursor;
1431 f = a_TTY_VF_MOD_CURSOR;
1432 }else
1433 f = a_TTY_VF_BELL;
1435 tlp->tl_vi_flags |= f;
1436 NYD2_LEAVE;
1439 static void
1440 a_tty_kright(struct a_tty_line *tlp){
1441 ui32_t i;
1442 NYD2_ENTER;
1444 if(LIKELY((i = tlp->tl_cursor + 1) <= tlp->tl_count)){
1445 tlp->tl_cursor = i;
1446 i = a_TTY_VF_MOD_CURSOR;
1447 }else
1448 i = a_TTY_VF_BELL;
1450 tlp->tl_vi_flags |= i;
1451 NYD2_LEAVE;
1454 static void
1455 a_tty_kbwddelw(struct a_tty_line *tlp){
1456 struct a_tty_cell *tcap;
1457 ui32_t cnt, cur, f;
1458 si32_t i;
1459 NYD2_ENTER;
1461 if(UNLIKELY((i = a_tty_wboundary(tlp, -1)) <= 0)){
1462 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
1463 goto jleave;
1466 cnt = tlp->tl_count - (ui32_t)i;
1467 cur = tlp->tl_cursor - (ui32_t)i;
1468 tcap = &tlp->tl_line.cells[cur];
1470 a_tty_yank(tlp, &tcap[0], &tcap[i]);
1472 if((tlp->tl_count = cnt) != (tlp->tl_cursor = cur)){
1473 cnt -= cur;
1474 memmove(&tcap[0], &tcap[i], cnt * sizeof(*tcap)); /* FIXME*/
1477 f = a_TTY_VF_MOD_CURSOR | a_TTY_VF_MOD_CONTENT;
1478 jleave:
1479 tlp->tl_vi_flags |= f;
1480 NYD2_LEAVE;
1483 static void
1484 a_tty_kgow(struct a_tty_line *tlp, si32_t dir){
1485 ui32_t f;
1486 si32_t i;
1487 NYD2_ENTER;
1489 if(UNLIKELY((i = a_tty_wboundary(tlp, dir)) <= 0))
1490 f = (i < 0) ? a_TTY_VF_BELL : a_TTY_VF_NONE;
1491 else{
1492 if(dir < 0)
1493 i = -i;
1494 tlp->tl_cursor += (ui32_t)i;
1495 f = a_TTY_VF_MOD_CURSOR;
1498 tlp->tl_vi_flags |= f;
1499 NYD2_LEAVE;
1502 static void
1503 a_tty_kother(struct a_tty_line *tlp, wchar_t wc){
1504 /* Append if at EOL, insert otherwise;
1505 * since we may move around character-wise, always use a fresh ps */
1506 mbstate_t ps;
1507 struct a_tty_cell tc, *tcap;
1508 ui32_t f, cur, cnt;
1509 NYD2_ENTER;
1511 f = a_TTY_VF_NONE;
1513 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1514 if(tlp->tl_count + 1 >= a_TTY_LINE_MAX){
1515 n_err(_("Stop here, we can't extend line beyond size limit\n"));
1516 goto jleave;
1519 /* First init a cell and see wether we'll really handle this wc */
1520 memset(&ps, 0, sizeof ps);
1521 /* C99 */{
1522 size_t l;
1524 l = wcrtomb(tc.tc_cbuf, tc.tc_wc = wc, &ps);
1525 if(UNLIKELY(l > MB_LEN_MAX)){
1526 jemb:
1527 n_err(_("wcrtomb(3) error: too many multibyte character bytes\n"));
1528 goto jleave;
1530 tc.tc_count = (ui16_t)l;
1532 if(UNLIKELY((options & OPT_ENC_MBSTATE) != 0)){
1533 l = wcrtomb(&tc.tc_cbuf[l], L'\0', &ps);
1534 if(LIKELY(l == 1))
1535 /* Only NUL terminator */;
1536 else if(LIKELY(--l < MB_LEN_MAX))
1537 tc.tc_count += (ui16_t)l;
1538 else
1539 goto jemb;
1543 /* Yes, we will! Place it in the array */
1544 tc.tc_novis = (iswprint(wc) == 0);
1545 tc.tc_width = a_tty_wcwidth(wc);
1546 /* TODO if(tc.tc_novis && tc.tc_width > 0) */
1548 cur = tlp->tl_cursor++;
1549 cnt = tlp->tl_count++ - cur;
1550 tcap = &tlp->tl_line.cells[cur];
1551 if(cnt >= 1){
1552 memmove(&tcap[1], tcap, cnt * sizeof(*tcap));
1553 f = a_TTY_VF_MOD_CONTENT;
1554 }else
1555 f = a_TTY_VF_MOD_SINGLE;
1556 memcpy(tcap, &tc, sizeof *tcap);
1558 f |= a_TTY_VF_MOD_CURSOR;
1559 jleave:
1560 tlp->tl_vi_flags |= f;
1561 NYD2_LEAVE;
1564 static ui32_t
1565 a_tty_kht(struct a_tty_line *tlp){
1566 struct str orig, bot, topp, sub, exp;
1567 struct a_tty_cell *cword, *ctop, *cx;
1568 bool_t set_savec = FAL0;
1569 ui32_t f, rv;
1570 NYD2_ENTER;
1572 /* We cannot expand an empty line */
1573 if(UNLIKELY(tlp->tl_count == 0)){
1574 rv = 0;
1575 f = a_TTY_VF_BELL; /* xxx really bell if no expansion is possible? */
1576 goto jleave;
1579 /* Get plain line data; if this is the first expansion/xy, update the
1580 * very original content so that ^G gets the origin back */
1581 orig = tlp->tl_savec;
1582 a_tty_cell2save(tlp);
1583 exp = tlp->tl_savec;
1584 if(orig.s != NULL)
1585 tlp->tl_savec = orig;
1586 else
1587 set_savec = TRU1;
1588 orig = exp;
1590 /* Find the word to be expanded */
1592 cword = tlp->tl_line.cells;
1593 ctop = cword + tlp->tl_cursor;
1594 cx = cword + tlp->tl_count;
1596 /* topp: separate data right of cursor */
1597 if(cx > ctop){
1598 for(rv = 0; --cx > ctop; --cx)
1599 rv += cx->tc_count;
1600 topp.l = rv;
1601 topp.s = orig.s + orig.l - rv;
1602 }else
1603 topp.s = NULL, topp.l = 0;
1605 /* bot, sub: we cannot expand the entire data left of cursor, but only
1606 * the last "word", so separate them */
1607 /* TODO Context-sensitive completion: stop for | too, try expand shell?
1608 * TODO Ditto, "cx==cword(+space)": try mail command expansion? */
1609 while(cx > cword && !iswspace(cx[-1].tc_wc))
1610 --cx;
1611 for(rv = 0; cword < cx; ++cword)
1612 rv += cword->tc_count;
1613 sub =
1614 bot = orig;
1615 bot.l = rv;
1616 sub.s += rv;
1617 sub.l -= rv;
1618 sub.l -= topp.l;
1620 /* Leave room for "implicit asterisk" expansion, as below */
1621 if(sub.l == 0){
1622 sub.s = UNCONST("*");
1623 sub.l = 1;
1624 }else{
1625 exp.s = salloc(sub.l + 1 +1);
1626 memcpy(exp.s, sub.s, sub.l);
1627 exp.s[sub.l] = '\0';
1628 sub.s = exp.s;
1631 /* TODO there is a TODO note upon fexpand() with multi-return;
1632 * TODO if that will change, the if() below can be simplified.
1633 * TODO Also: iff multireturn, offer a numbered list of possible
1634 * TODO expansions, 0 meaning "none" and * (?) meaning "all",
1635 * TODO go over the pager as necesary (use *crt*, generalized) */
1636 /* Super-Heavy-Metal: block all sigs, avoid leaks on jump */
1637 jredo:
1638 hold_all_sigs();
1639 exp.s = fexpand(sub.s, a_TTY_TAB_FEXP_FL);
1640 rele_all_sigs();
1642 if(exp.s == NULL || (exp.l = strlen(exp.s)) == 0)
1643 goto jnope;
1644 /* xxx That is not really true since the limit counts characters not bytes */
1645 n_LCTA(a_TTY_LINE_MAX <= SI32_MAX, "a_TTY_LINE_MAX too large");
1646 if(exp.l + 1 >= a_TTY_LINE_MAX){
1647 n_err(_("Tabulator expansion would extend beyond line size limit\n"));
1648 goto jnope;
1651 /* If the expansion equals the original string, assume the user wants what
1652 * is usually known as tab completion, append `*' and restart */
1653 if(exp.l == sub.l && !strcmp(exp.s, sub.s)){
1654 if(sub.s[sub.l - 1] == '*')
1655 goto jnope;
1656 sub.s[sub.l++] = '*';
1657 sub.s[sub.l] = '\0';
1658 goto jredo;
1661 orig.l = bot.l + exp.l + topp.l;
1662 orig.s = salloc(orig.l + 5 +1);
1663 if((rv = (ui32_t)bot.l) > 0)
1664 memcpy(orig.s, bot.s, rv);
1665 memcpy(orig.s + rv, exp.s, exp.l);
1666 rv += exp.l;
1667 if(topp.l > 0){
1668 memcpy(orig.s + rv, topp.s, topp.l);
1669 rv += topp.l;
1671 orig.s[rv] = '\0';
1673 tlp->tl_defc = orig;
1674 tlp->tl_count = tlp->tl_cursor = 0;
1675 f = a_TTY_VF_MOD_DIRTY;
1676 jleave:
1677 tlp->tl_vi_flags |= f;
1678 NYD2_LEAVE;
1679 return rv;
1681 jnope:
1682 /* If we've provided a default content, but failed to expand, there is
1683 * nothing we can "revert to": drop that default again */
1684 if(set_savec){
1685 tlp->tl_savec.s = NULL;
1686 tlp->tl_savec.l = 0;
1688 rv = 0;
1689 f = a_TTY_VF_NONE;
1690 goto jleave;
1693 # ifdef HAVE_HISTORY
1694 static ui32_t
1695 a_tty__khist_shared(struct a_tty_line *tlp, struct a_tty_hist *thp){
1696 ui32_t f, rv;
1697 NYD2_ENTER;
1699 if(LIKELY((tlp->tl_hist = thp) != NULL)){
1700 tlp->tl_defc.s = savestrbuf(thp->th_dat, thp->th_len);
1701 rv = tlp->tl_defc.l = thp->th_len;
1702 f = (tlp->tl_count > 0) ? a_TTY_VF_MOD_DIRTY : a_TTY_VF_NONE;
1703 tlp->tl_count = tlp->tl_cursor = 0;
1704 }else{
1705 f = a_TTY_VF_BELL;
1706 rv = 0;
1709 tlp->tl_vi_flags |= f;
1710 NYD2_LEAVE;
1711 return rv;
1714 static ui32_t
1715 a_tty_khist(struct a_tty_line *tlp, bool_t backwd){
1716 struct a_tty_hist *thp;
1717 ui32_t rv;
1718 NYD2_ENTER;
1720 /* If we're not in history mode yet, save line content;
1721 * also, disallow forward search, then, and, of course, bail unless we
1722 * do have any history at all */
1723 if((thp = tlp->tl_hist) == NULL){
1724 if(!backwd)
1725 goto jleave;
1726 if((thp = a_tty.tg_hist) == NULL)
1727 goto jleave;
1728 a_tty_cell2save(tlp);
1729 goto jleave;
1732 thp = backwd ? thp->th_older : thp->th_younger;
1733 jleave:
1734 rv = a_tty__khist_shared(tlp, thp);
1735 NYD2_LEAVE;
1736 return rv;
1739 static ui32_t
1740 a_tty_krhist(struct a_tty_line *tlp){
1741 struct str orig_savec;
1742 struct a_tty_hist *thp;
1743 ui32_t rv;
1744 NYD2_ENTER;
1746 thp = NULL;
1748 /* We cannot complete an empty line */
1749 if(UNLIKELY(tlp->tl_count == 0)){
1750 /* XXX The upcoming hard reset would restore a set savec buffer,
1751 * XXX so forcefully reset that. A cleaner solution would be to
1752 * XXX reset it whenever a restore is no longer desired */
1753 tlp->tl_savec.s = NULL;
1754 tlp->tl_savec.l = 0;
1755 goto jleave;
1758 if((thp = tlp->tl_hist) == NULL){
1759 if((thp = a_tty.tg_hist) == NULL)
1760 goto jleave;
1761 orig_savec.s = NULL;
1762 orig_savec.l = 0; /* silence CC */
1763 }else if((thp = thp->th_older) == NULL)
1764 goto jleave;
1765 else
1766 orig_savec = tlp->tl_savec;
1768 if(orig_savec.s == NULL)
1769 a_tty_cell2save(tlp);
1771 for(; thp != NULL; thp = thp->th_older)
1772 if(is_prefix(tlp->tl_savec.s, thp->th_dat))
1773 break;
1775 if(orig_savec.s != NULL)
1776 tlp->tl_savec = orig_savec;
1777 jleave:
1778 rv = a_tty__khist_shared(tlp, thp);
1779 NYD2_LEAVE;
1780 return rv;
1782 # endif /* HAVE_HISTORY */
1784 static ssize_t
1785 a_tty_readline(struct a_tty_line *tlp, size_t len SMALLOC_DEBUG_ARGS){
1786 /* We want to save code, yet we may have to incorporate a lines'
1787 * default content and / or default input to switch back to after some
1788 * history movement; let "len > 0" mean "have to display some data
1789 * buffer", and only otherwise read(2) it */
1790 mbstate_t ps[2];
1791 char cbuf_base[MB_LEN_MAX * 2], *cbuf, *cbufp, cursor_maybe, cursor_store;
1792 wchar_t wc;
1793 ssize_t rv;
1794 NYD_ENTER;
1796 jrestart:
1797 memset(ps, 0, sizeof ps);
1798 tlp->tl_vi_flags |= a_TTY_VF_REFRESH | a_TTY_VF_SYNC;
1800 for(cursor_maybe = cursor_store = 0;;){
1801 /* Ensure we have valid pointers, and room for grow */
1802 a_tty_check_grow(tlp, (len == 0 ? 1 : (ui32_t)len)
1803 SMALLOC_DEBUG_ARGSCALL);
1805 /* Handle visual state flags, except in buffer take-over mode */
1806 if(len == 0){
1807 if(tlp->tl_vi_flags & a_TTY_VF_BELL){
1808 tlp->tl_vi_flags |= a_TTY_VF_SYNC;
1809 putchar('\a');
1812 if(tlp->tl_vi_flags & a_TTY_VF_REFRESH){
1813 if(!a_tty_vi_refresh(tlp)){
1814 clearerr(stdout); /* xxx I/O layer rewrite */
1815 n_err(_("Visual refresh failed! Is $TERM set correctly?\n"
1816 " Setting *line-editor-disable* to get us through!\n"));
1817 ok_bset(line_editor_disable, TRU1);
1818 rv = -1;
1819 goto jleave;
1823 if(tlp->tl_vi_flags & a_TTY_VF_SYNC){
1824 tlp->tl_vi_flags &= ~a_TTY_VF_SYNC;
1825 fflush(stdout);
1828 tlp->tl_vi_flags &= ~a_TTY_VF_ALL_MASK;
1831 /* Ready for messing around.
1832 * Normal read(2)? Else buffer-takeover: speed this one up */
1833 if(len == 0){
1834 cbufp =
1835 cbuf = cbuf_base;
1836 }else{
1837 assert(tlp->tl_defc.l > 0 && tlp->tl_defc.s != NULL);
1838 cbufp =
1839 cbuf = tlp->tl_defc.s + (tlp->tl_defc.l - len);
1840 cbufp += len;
1843 /* Read in the next complete multibyte character */
1844 for(;;){
1845 if(len == 0){
1846 /* Let me at least once dream of iomon(itor), timer with one-shot,
1847 * enwrapped with key_event and key_sequence_event, all driven by
1848 * an event_loop */
1849 if((rv = read(STDIN_FILENO, cbufp, 1)) < 1){
1850 if(errno == EINTR) /* xxx #if !SA_RESTART ? */
1851 continue;
1852 goto jleave;
1854 ++cbufp;
1857 rv = (ssize_t)mbrtowc(&wc, cbuf, PTR2SIZE(cbufp - cbuf), &ps[0]);
1858 if(rv <= 0){
1859 /* Any error during take-over can only result in a hard reset;
1860 * Otherwise, if it's a hard error, or if too many redundant shift
1861 * sequences overflow our buffer, also perform a hard reset */
1862 if(len != 0 || rv == -1 ||
1863 sizeof cbuf_base == PTR2SIZE(cbufp - cbuf)){
1864 tlp->tl_savec.s = tlp->tl_defc.s = NULL;
1865 tlp->tl_savec.l = tlp->tl_defc.l = len = 0;
1866 tlp->tl_vi_flags |= a_TTY_VF_BELL;
1867 goto jreset;
1869 /* Otherwise, due to the way we deal with the buffer, we need to
1870 * restore the mbstate_t from before this conversion */
1871 ps[0] = ps[1];
1872 continue;
1875 /* Buffer takeover completed? */
1876 if(len != 0 && (len -= (size_t)rv) == 0){
1877 tlp->tl_defc.s = NULL;
1878 tlp->tl_defc.l = 0;
1880 ps[1] = ps[0];
1881 break;
1884 /* Don't interpret control bytes during buffer take-over */
1885 if(cbuf != cbuf_base)
1886 goto jprint;
1887 switch(wc){
1888 case 'A' ^ 0x40: /* cursor home */
1889 a_tty_khome(tlp, TRU1);
1890 break;
1891 case 'B' ^ 0x40: /* backward character */
1892 j_b:
1893 a_tty_kleft(tlp);
1894 break;
1895 /* 'C': interrupt (CTRL-C) */
1896 case 'D' ^ 0x40: /* delete char forward if any, else EOF */
1897 if((rv = a_tty_kdel(tlp)) < 0)
1898 goto jleave;
1899 break;
1900 case 'E' ^ 0x40: /* end of line */
1901 a_tty_kend(tlp);
1902 break;
1903 case 'F' ^ 0x40: /* forward character */
1904 j_f:
1905 a_tty_kright(tlp);
1906 break;
1907 /* 'G' below */
1908 case 'H' ^ 0x40: /* backspace */
1909 case '\177':
1910 a_tty_kbs(tlp);
1911 break;
1912 case 'I' ^ 0x40: /* horizontal tab */
1913 if((len = a_tty_kht(tlp)) > 0)
1914 goto jrestart;
1915 goto jbell;
1916 case 'J' ^ 0x40: /* NL (\n) */
1917 goto jdone;
1918 case 'G' ^ 0x40: /* full reset */
1919 jreset:
1920 /* FALLTHRU */
1921 case 'U' ^ 0x40: /* ^U: ^A + ^K */
1922 a_tty_khome(tlp, FAL0);
1923 /* FALLTHRU */
1924 case 'K' ^ 0x40: /* kill from cursor to end of line */
1925 a_tty_kkill(tlp, (wc == ('K' ^ 0x40) || tlp->tl_count == 0));
1926 /* (Handle full reset?) */
1927 if(wc == ('G' ^ 0x40)) {
1928 # ifdef HAVE_HISTORY
1929 tlp->tl_hist = NULL;
1930 # endif
1931 if((len = tlp->tl_savec.l) != 0){
1932 tlp->tl_defc = tlp->tl_savec;
1933 tlp->tl_savec.s = NULL;
1934 tlp->tl_savec.l = 0;
1935 }else
1936 len = tlp->tl_defc.l;
1938 goto jrestart;
1939 case 'L' ^ 0x40: /* repaint line */
1940 tlp->tl_vi_flags |= a_TTY_VF_MOD_DIRTY;
1941 break;
1942 /* 'M': CR (\r) */
1943 case 'N' ^ 0x40: /* history next */
1944 j_n:
1945 # ifdef HAVE_HISTORY
1946 if(tlp->tl_hist == NULL)
1947 goto jbell;
1948 if((len = a_tty_khist(tlp, FAL0)) > 0)
1949 goto jrestart;
1950 wc = 'G' ^ 0x40;
1951 goto jreset;
1952 # else
1953 goto jbell;
1954 # endif
1955 case 'O' ^ 0x40:
1956 tlp->tl_reenter_after_cmd = "dp";
1957 goto jdone;
1958 case 'P' ^ 0x40: /* history previous */
1959 j_p:
1960 # ifdef HAVE_HISTORY
1961 if((len = a_tty_khist(tlp, TRU1)) > 0)
1962 goto jrestart;
1963 wc = 'G' ^ 0x40;
1964 goto jreset;
1965 # else
1966 goto jbell;
1967 # endif
1968 /* 'Q': no code */
1969 case 'R' ^ 0x40: /* reverse history search */
1970 # ifdef HAVE_HISTORY
1971 if((len = a_tty_krhist(tlp)) > 0)
1972 goto jrestart;
1973 wc = 'G' ^ 0x40;
1974 goto jreset;
1975 # else
1976 goto jbell;
1977 # endif
1978 /* 'S': no code */
1979 /* 'U' above */
1980 case 'V' ^ 0x40: /* insert (Unicode) character */
1981 if((wc = a_tty_vinuni(tlp)) > 0)
1982 goto jprint;
1983 goto jbell;
1984 case 'W' ^ 0x40: /* backward delete "word" */
1985 a_tty_kbwddelw(tlp);
1986 break;
1987 case 'X' ^ 0x40: /* move cursor forward "word" */
1988 a_tty_kgow(tlp, +1);
1989 break;
1990 case 'Y' ^ 0x40: /* move cursor backward "word" */
1991 a_tty_kgow(tlp, -1);
1992 break;
1993 /* 'Z': suspend (CTRL-Z) */
1994 case 0x1B:
1995 if(cursor_maybe++ != 0)
1996 goto jreset;
1997 continue;
1998 default:
1999 /* XXX Handle usual ^[[[ABCD1456] cursor keys: UGLY,"MAGIC",INFLEX */
2000 if(cursor_maybe > 0){
2001 if(++cursor_maybe == 2){
2002 if(wc == L'[')
2003 continue;
2004 cursor_maybe = 0;
2005 }else if(cursor_maybe == 3){
2006 cursor_maybe = 0;
2007 switch(wc){
2008 default: break;
2009 case L'A': goto j_p;
2010 case L'B': goto j_n;
2011 case L'C': goto j_f;
2012 case L'D': goto j_b;
2013 case L'H':
2014 cursor_store = '0';
2015 goto J_xterm_noapp;
2016 case L'F':
2017 cursor_store = '$';
2018 goto J_xterm_noapp;
2019 case L'1':
2020 case L'4':
2021 case L'5':
2022 case L'6':
2023 cursor_store = ((wc == L'1') ? '0' :
2024 (wc == L'4' ? '$' : (wc == L'5' ? '-' : '+')));
2025 cursor_maybe = 3;
2026 continue;
2028 a_tty_kother(tlp, L'[');
2029 }else{
2030 cursor_maybe = 0;
2031 if(wc == L'~') J_xterm_noapp:{
2032 char *cp = salloc(3);
2034 cp[0] = 'z';
2035 cp[1] = cursor_store;
2036 cp[2] = '\0';
2037 tlp->tl_reenter_after_cmd = cp;
2038 goto jdone;
2039 }else if(cursor_store == '-' && (wc == L'A' || wc == L'B')){
2040 char const cmd[] = "dotmove";
2041 char *cp = salloc(sizeof(cmd) -1 + 1 +1);
2043 memcpy(cp, cmd, sizeof(cmd) -1);
2044 cp[sizeof(cmd) -1] = (wc != L'A') ? '+' : cursor_store;
2045 cp[sizeof(cmd)] = '\0';
2046 tlp->tl_reenter_after_cmd = cp;
2047 goto jdone;
2049 a_tty_kother(tlp, L'[');
2050 a_tty_kother(tlp, (wchar_t)cursor_store);
2051 cursor_store = 0;
2054 jprint:
2055 if(iswprint(wc)){
2056 a_tty_kother(tlp, wc);
2057 /* Don't clear the history during takeover..
2058 * ..and also avoid fflush()ing unless we've worked entire buffer */
2059 if(len > 0)
2060 continue;
2061 # ifdef HAVE_HISTORY
2062 if(cbuf == cbuf_base)
2063 tlp->tl_hist = NULL;
2064 # endif
2065 }else{
2066 jbell:
2067 tlp->tl_vi_flags |= a_TTY_VF_BELL;
2069 break;
2071 tlp->tl_vi_flags |= a_TTY_VF_SYNC;
2074 /* We have a completed input line, convert the struct cell data to its
2075 * plain character equivalent */
2076 jdone:
2077 rv = a_tty_cell2dat(tlp);
2078 jleave:
2079 putchar('\n');
2080 fflush(stdout);
2081 NYD_LEAVE;
2082 return rv;
2085 FL void
2086 n_tty_init(void){
2087 # ifdef HAVE_HISTORY
2088 long hs;
2089 char const *v;
2090 char *lbuf;
2091 FILE *f;
2092 size_t lsize, cnt, llen;
2093 # endif
2094 NYD_ENTER;
2096 /* Load the history file */
2097 # ifdef HAVE_HISTORY
2098 a_TTY_HISTSIZE(hs);
2099 a_tty.tg_hist_size = 0;
2100 a_tty.tg_hist_size_max = (size_t)hs;
2101 if(hs == 0)
2102 goto jleave;
2104 a_TTY_HISTFILE(v);
2105 if(v == NULL)
2106 goto jleave;
2108 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
2109 f = fopen(v, "r"); /* TODO HISTFILE LOAD: use linebuf pool */
2110 if(f == NULL)
2111 goto jdone;
2112 (void)n_file_lock(fileno(f), FLT_READ, 0,0, 500);
2114 lbuf = NULL;
2115 lsize = 0;
2116 cnt = (size_t)fsize(f);
2117 while(fgetline(&lbuf, &lsize, &cnt, &llen, f, FAL0) != NULL){
2118 if(llen > 0 && lbuf[llen - 1] == '\n')
2119 lbuf[--llen] = '\0';
2120 if(llen == 0 || lbuf[0] == '#') /* xxx comments? noone! */
2121 continue;
2122 else{
2123 bool_t isgabby = (lbuf[0] == '*');
2125 n_tty_addhist(lbuf + isgabby, isgabby);
2128 if(lbuf != NULL)
2129 free(lbuf);
2131 fclose(f);
2132 jdone:
2133 rele_all_sigs(); /* XXX remove jumps */
2134 jleave:
2135 # endif /* HAVE_HISTORY */
2136 pstate |= PS_HISTORY_LOADED;
2137 NYD_LEAVE;
2140 FL void
2141 n_tty_destroy(void){
2142 # ifdef HAVE_HISTORY
2143 long hs;
2144 char const *v;
2145 struct a_tty_hist *thp;
2146 bool_t dogabby;
2147 FILE *f;
2148 # endif
2149 NYD_ENTER;
2151 # ifdef HAVE_HISTORY
2152 a_TTY_HISTSIZE(hs);
2153 if(hs == 0)
2154 goto jleave;
2156 a_TTY_HISTFILE(v);
2157 if(v == NULL)
2158 goto jleave;
2160 dogabby = ok_blook(history_gabby_persist);
2162 if((thp = a_tty.tg_hist) != NULL)
2163 for(; thp->th_older != NULL; thp = thp->th_older)
2164 if((dogabby || !thp->th_isgabby) && --hs == 0)
2165 break;
2167 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
2168 f = fopen(v, "w"); /* TODO temporary + rename?! */
2169 if(f == NULL)
2170 goto jdone;
2171 (void)n_file_lock(fileno(f), FLT_WRITE, 0,0, 500);
2172 if (fchmod(fileno(f), S_IRUSR | S_IWUSR) != 0)
2173 goto jclose;
2175 for(; thp != NULL; thp = thp->th_younger){
2176 if(dogabby || !thp->th_isgabby){
2177 if(thp->th_isgabby)
2178 putc('*', f);
2179 fwrite(thp->th_dat, sizeof *thp->th_dat, thp->th_len, f);
2180 putc('\n', f);
2183 jclose:
2184 fclose(f);
2185 jdone:
2186 rele_all_sigs(); /* XXX remove jumps */
2187 jleave:
2188 # endif /* HAVE_HISTORY */
2189 NYD_LEAVE;
2192 FL void
2193 n_tty_signal(int sig){
2194 sigset_t nset, oset;
2195 NYD_X; /* Signal handler */
2197 switch(sig){
2198 case SIGWINCH:
2199 /* We don't deal with SIGWINCH, yet get called from main.c */
2200 break;
2201 default:
2202 a_tty_term_mode(FAL0);
2203 n_TERMCAP_SUSPEND(TRU1);
2204 a_tty_sigs_down();
2206 sigemptyset(&nset);
2207 sigaddset(&nset, sig);
2208 sigprocmask(SIG_UNBLOCK, &nset, &oset);
2209 n_raise(sig);
2210 /* When we come here we'll continue editing, so reestablish */
2211 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
2213 a_tty_sigs_up();
2214 n_TERMCAP_RESUME(TRU1);
2215 a_tty_term_mode(TRU1);
2216 break;
2220 FL int
2221 (n_tty_readline)(char const *prompt, char **linebuf, size_t *linesize, size_t n
2222 SMALLOC_DEBUG_ARGS){
2223 struct a_tty_line tl;
2224 # ifdef HAVE_COLOUR
2225 char *posbuf, *pos;
2226 # endif
2227 ui32_t plen, pwidth;
2228 ssize_t nn;
2229 NYD_ENTER;
2231 # ifdef HAVE_COLOUR
2232 n_colour_env_create(n_COLOUR_CTX_MLE, FAL0);
2233 # endif
2235 /* Classify prompt */
2236 UNINIT(plen, 0);
2237 UNINIT(pwidth, 0);
2238 if(prompt != NULL){
2239 size_t i = strlen(prompt);
2241 if(i == 0 || i >= UI32_MAX)
2242 prompt = NULL;
2243 else{
2244 plen = (ui32_t)i;
2245 /* TODO *prompt* is in multibyte and not in a_tty_cell, therefore
2246 * TODO we cannot handle it in parts, it's all or nothing.
2247 * TODO Later (S-CText, SysV signals) the prompt should be some global
2248 * TODO carrier thing, fully evaluated and passed around as UI-enabled
2249 * TODO string, then we can print it character by character */
2250 if((i = field_detect_width(prompt, i)) != (size_t)-1)
2251 pwidth = (ui32_t)i;
2252 else{
2253 n_err(_("Character set error in evaluation of prompt\n"));
2254 prompt = NULL;
2259 # ifdef HAVE_COLOUR
2260 /* C99 */{
2261 struct n_colour_pen *ccp;
2262 struct str const *sp;
2264 if(prompt != NULL &&
2265 (ccp = n_colour_pen_create(n_COLOUR_ID_MLE_PROMPT, NULL)) != NULL &&
2266 (sp = n_colour_pen_to_str(ccp)) != NULL){
2267 char const *ccol = sp->s;
2269 if((sp = n_colour_reset_to_str()) != NULL){
2270 size_t l1 = strlen(ccol), l2 = strlen(sp->s);
2271 ui32_t nplen = (ui32_t)(l1 + plen + l2);
2272 char *nprompt = salloc(nplen +1);
2274 memcpy(nprompt, ccol, l1);
2275 memcpy(&nprompt[l1], prompt, plen);
2276 memcpy(&nprompt[l1 += plen], sp->s, ++l2);
2278 prompt = nprompt;
2279 plen = nplen;
2283 /* .tl_pos_buf is a hack */
2284 posbuf = pos = NULL;
2285 if((ccp = n_colour_pen_create(n_COLOUR_ID_MLE_POSITION, NULL)) != NULL &&
2286 (sp = n_colour_pen_to_str(ccp)) != NULL){
2287 char const *ccol = sp->s;
2289 if((sp = n_colour_reset_to_str()) != NULL){
2290 size_t l1 = strlen(ccol), l2 = strlen(sp->s);
2292 posbuf = salloc(l1 + 4 + l2 +1);
2293 memcpy(posbuf, ccol, l1);
2294 pos = &posbuf[l1];
2295 memcpy(&pos[4], sp->s, ++l2);
2298 if(posbuf == NULL){
2299 posbuf = pos = salloc(4 +1);
2300 pos[4] = '\0';
2303 # endif /* HAVE_COLOUR */
2305 jredo:
2306 memset(&tl, 0, sizeof tl);
2308 if((tl.tl_prompt = prompt) != NULL){ /* XXX not re-evaluated */
2309 tl.tl_prompt_length = plen;
2310 tl.tl_prompt_width = pwidth;
2312 # ifdef HAVE_COLOUR
2313 tl.tl_pos_buf = posbuf;
2314 tl.tl_pos = pos;
2315 # endif
2317 tl.tl_line.cbuf = *linebuf;
2318 if(n != 0){
2319 tl.tl_defc.s = savestrbuf(*linebuf, n);
2320 tl.tl_defc.l = n;
2322 tl.tl_x_buf = linebuf;
2323 tl.tl_x_bufsize = linesize;
2325 a_tty_sigs_up();
2326 a_tty_term_mode(TRU1);
2327 nn = a_tty_readline(&tl, n SMALLOC_DEBUG_ARGSCALL);
2328 a_tty_term_mode(FAL0);
2329 a_tty_sigs_down();
2331 if(tl.tl_reenter_after_cmd != NULL){
2332 n = 0;
2333 n_source_command(tl.tl_reenter_after_cmd);
2334 goto jredo;
2337 # ifdef HAVE_COLOUR
2338 n_colour_env_gut(stdout);
2339 # endif
2340 NYD_LEAVE;
2341 return (int)nn;
2344 FL void
2345 n_tty_addhist(char const *s, bool_t isgabby){
2346 # ifdef HAVE_HISTORY
2347 /* Super-Heavy-Metal: block all sigs, avoid leaks+ on jump */
2348 ui32_t l;
2349 struct a_tty_hist *thp, *othp, *ythp;
2350 # endif
2351 NYD_ENTER;
2352 UNUSED(s);
2353 UNUSED(isgabby);
2355 # ifdef HAVE_HISTORY
2356 if(isgabby && !ok_blook(history_gabby))
2357 goto j_leave;
2359 if(a_tty.tg_hist_size_max == 0)
2360 goto j_leave;
2361 a_TTY_CHECK_ADDHIST(s, goto j_leave);
2363 l = (ui32_t)strlen(s);
2365 /* Eliminating duplicates is expensive, but simply inacceptable so
2366 * during the load of a potentially large history file! */
2367 if(pstate & PS_HISTORY_LOADED)
2368 for(thp = a_tty.tg_hist; thp != NULL; thp = thp->th_older)
2369 if(thp->th_len == l && !strcmp(thp->th_dat, s)){
2370 hold_all_sigs(); /* TODO */
2371 if(thp->th_isgabby)
2372 thp->th_isgabby = !!isgabby;
2373 othp = thp->th_older;
2374 ythp = thp->th_younger;
2375 if(othp != NULL)
2376 othp->th_younger = ythp;
2377 else
2378 a_tty.tg_hist_tail = ythp;
2379 if(ythp != NULL)
2380 ythp->th_older = othp;
2381 else
2382 a_tty.tg_hist = othp;
2383 goto jleave;
2385 hold_all_sigs();
2387 ++a_tty.tg_hist_size;
2388 if((pstate & PS_HISTORY_LOADED) &&
2389 a_tty.tg_hist_size > a_tty.tg_hist_size_max){
2390 --a_tty.tg_hist_size;
2391 if((thp = a_tty.tg_hist_tail) != NULL){
2392 if((a_tty.tg_hist_tail = thp->th_younger) == NULL)
2393 a_tty.tg_hist = NULL;
2394 else
2395 a_tty.tg_hist_tail->th_older = NULL;
2396 free(thp);
2400 thp = smalloc((sizeof(struct a_tty_hist) -
2401 VFIELD_SIZEOF(struct a_tty_hist, th_dat)) + l +1);
2402 thp->th_isgabby = !!isgabby;
2403 thp->th_len = l;
2404 memcpy(thp->th_dat, s, l +1);
2405 jleave:
2406 if((thp->th_older = a_tty.tg_hist) != NULL)
2407 a_tty.tg_hist->th_younger = thp;
2408 else
2409 a_tty.tg_hist_tail = thp;
2410 thp->th_younger = NULL;
2411 a_tty.tg_hist = thp;
2413 rele_all_sigs();
2414 j_leave:
2415 # endif
2416 NYD_LEAVE;
2419 # ifdef HAVE_HISTORY
2420 FL int
2421 c_history(void *v){
2422 C_HISTORY_SHARED;
2424 jlist:{
2425 FILE *fp;
2426 size_t i, b;
2427 struct a_tty_hist *thp;
2429 if(a_tty.tg_hist == NULL)
2430 goto jleave;
2432 if((fp = Ftmp(NULL, "hist", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
2433 n_perr(_("tmpfile"), 0);
2434 v = NULL;
2435 goto jleave;
2438 i = a_tty.tg_hist_size;
2439 b = 0;
2440 for(thp = a_tty.tg_hist; thp != NULL;
2441 --i, b += thp->th_len, thp = thp->th_older)
2442 fprintf(fp,
2443 "%c%4" PRIuZ ". %-50.50s (%4" PRIuZ "+%2" PRIu32 " B)\n",
2444 (thp->th_isgabby ? '*' : ' '), i, thp->th_dat, b, thp->th_len);
2446 page_or_print(fp, i);
2447 Fclose(fp);
2449 goto jleave;
2451 jclear:{
2452 struct a_tty_hist *thp;
2454 while((thp = a_tty.tg_hist) != NULL){
2455 a_tty.tg_hist = thp->th_older;
2456 free(thp);
2458 a_tty.tg_hist_tail = NULL;
2459 a_tty.tg_hist_size = 0;
2461 goto jleave;
2463 jentry:{
2464 struct a_tty_hist *thp;
2466 if(UICMP(z, entry, <=, a_tty.tg_hist_size)){
2467 entry = (long)a_tty.tg_hist_size - entry;
2468 for(thp = a_tty.tg_hist;; thp = thp->th_older)
2469 if(thp == NULL)
2470 break;
2471 else if(entry-- != 0)
2472 continue;
2473 else{
2474 v = temporary_arg_v_store = thp->th_dat;
2475 goto jleave;
2478 v = NULL;
2480 goto jleave;
2482 # endif /* HAVE_HISTORY */
2483 #endif /* HAVE_MLE */
2486 * The really-nothing-at-all implementation
2488 #if !defined HAVE_READLINE && !defined HAVE_MLE
2490 FL void
2491 n_tty_init(void){
2492 NYD_ENTER;
2493 NYD_LEAVE;
2496 FL void
2497 n_tty_destroy(void){
2498 NYD_ENTER;
2499 NYD_LEAVE;
2502 FL void
2503 n_tty_signal(int sig){
2504 NYD_X; /* Signal handler */
2505 UNUSED(sig);
2507 # ifdef HAVE_TERMCAP
2508 switch(sig){
2509 default:{
2510 sigset_t nset, oset;
2512 n_TERMCAP_SUSPEND(TRU1);
2513 a_tty_sigs_down();
2515 sigemptyset(&nset);
2516 sigaddset(&nset, sig);
2517 sigprocmask(SIG_UNBLOCK, &nset, &oset);
2518 n_raise(sig);
2519 /* When we come here we'll continue editing, so reestablish */
2520 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
2522 a_tty_sigs_up();
2523 n_TERMCAP_RESUME(TRU1);
2524 break;
2527 # endif /* HAVE_TERMCAP */
2530 FL int
2531 (n_tty_readline)(char const *prompt, char **linebuf, size_t *linesize, size_t n
2532 SMALLOC_DEBUG_ARGS){
2533 int rv;
2534 NYD_ENTER;
2536 if(prompt != NULL){
2537 if(*prompt != '\0')
2538 fputs(prompt, stdout);
2539 fflush(stdout);
2541 # ifdef HAVE_TERMCAP
2542 a_tty_sigs_up();
2543 # endif
2544 rv = (readline_restart)(stdin, linebuf, linesize,n SMALLOC_DEBUG_ARGSCALL);
2545 # ifdef HAVE_TERMCAP
2546 a_tty_sigs_down();
2547 # endif
2548 NYD_LEAVE;
2549 return rv;
2552 FL void
2553 n_tty_addhist(char const *s, bool_t isgabby){
2554 NYD_ENTER;
2555 UNUSED(s);
2556 UNUSED(isgabby);
2557 NYD_LEAVE;
2559 #endif /* nothing at all */
2561 #undef a_TTY_SIGNALS
2562 /* s-it-mode */