send.c:_print_part_info(): use field_detect_clip()
[s-mailx.git] / tty.c
blobbd789089bdeb0895d905cd80ce5a366432c7d6e9
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ TTY interaction.
4 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
5 * Copyright (c) 2012 - 2014 Steffen (Daode) Nurpmeso <sdaoden@users.sf.net>.
6 */
7 /* The NCL version is
9 * Copyright (c) 2013 - 2014 Steffen (Daode) Nurpmeso <sdaoden@users.sf.net>.
11 * Permission to use, copy, modify, and/or distribute this software for any
12 * purpose with or without fee is hereby granted, provided that the above
13 * copyright notice and this permission notice appear in all copies.
15 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
16 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
17 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
18 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
20 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
21 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
24 * Copyright (c) 1980, 1993
25 * The Regents of the University of California. All rights reserved.
27 * Redistribution and use in source and binary forms, with or without
28 * modification, are permitted provided that the following conditions
29 * are met:
30 * 1. Redistributions of source code must retain the above copyright
31 * notice, this list of conditions and the following disclaimer.
32 * 2. Redistributions in binary form must reproduce the above copyright
33 * notice, this list of conditions and the following disclaimer in the
34 * documentation and/or other materials provided with the distribution.
35 * 3. All advertising materials mentioning features or use of this software
36 * must display the following acknowledgement:
37 * This product includes software developed by the University of
38 * California, Berkeley and its contributors.
39 * 4. Neither the name of the University nor the names of its contributors
40 * may be used to endorse or promote products derived from this software
41 * without specific prior written permission.
43 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
44 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
45 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
46 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
47 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
48 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
49 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
51 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
52 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53 * SUCH DAMAGE.
56 #ifndef HAVE_AMALGAMATION
57 # include "nail.h"
58 #endif
60 #ifdef HAVE_READLINE
61 # include <readline/readline.h>
62 # ifdef HAVE_HISTORY
63 # include <readline/history.h>
64 # endif
65 #elif defined HAVE_EDITLINE
66 # include <histedit.h>
67 #endif
69 /* Shared history support macros */
70 #ifdef HAVE_HISTORY
71 # define _CL_HISTFILE(S) \
72 do {\
73 S = ok_vlook(NAIL_HISTFILE);\
74 if ((S) != NULL)\
75 S = fexpand(S, FEXP_LOCAL);\
76 } while (0)
78 # define _CL_HISTSIZE(V) \
79 do {\
80 char const *__sv = ok_vlook(NAIL_HISTSIZE);\
81 long __rv;\
82 if (__sv == NULL || *__sv == '\0' || (__rv = strtol(__sv, NULL, 10)) == 0)\
83 (V) = HIST_SIZE;\
84 else if (__rv < 0)\
85 (V) = 0;\
86 else\
87 (V) = __rv;\
88 } while (0)
90 # define _CL_CHECK_ADDHIST(S,NOACT) \
91 do {\
92 switch (*(S)) {\
93 case '\0':\
94 case ' ':\
95 NOACT;\
96 default:\
97 break;\
99 } while (0)
101 # define C_HISTORY_SHARED \
102 char **argv = v;\
103 long entry;\
104 NYD_ENTER;\
106 if (*argv == NULL)\
107 goto jlist;\
108 if (argv[1] != NULL)\
109 goto jerr;\
110 if (!asccasecmp(*argv, "show"))\
111 goto jlist;\
112 if (!asccasecmp(*argv, "clear"))\
113 goto jclear;\
114 if ((entry = strtol(*argv, argv, 10)) > 0 && **argv == '\0')\
115 goto jentry;\
116 jerr:\
117 fprintf(stderr, "Synopsis: history: %s\n", tr(431,\
118 "<show> (default), <clear> or select <NO> from editor history"));\
119 v = NULL;\
120 jleave:\
121 NYD_LEAVE;\
122 return (v == NULL ? !STOP : !OKAY); /* xxx 1:bad 0:good -- do some */
123 #endif /* HAVE_HISTORY */
125 /* fexpand() flags for expand-on-tab */
126 #define _CL_TAB_FEXP_FL (FEXP_FULL | FEXP_SILENT | FEXP_MULTIOK)
129 * Because we have multiple identical implementations, change file layout a bit
130 * and place the implementations one after the other below the other externals
133 static sigjmp_buf __tty_actjmp; /* TODO someday, we won't need it no more */
134 static void
135 __tty_acthdl(int s) /* TODO someday, we won't need it no more */
137 NYD_X; /* Signal handler */
138 termios_state_reset();
139 siglongjmp(__tty_actjmp, s);
142 FL bool_t
143 getapproval(char const * volatile prompt, bool_t noninteract_default)
145 sighandler_type volatile ohdl;
146 bool_t volatile hadsig = FAL0, rv;
147 NYD_ENTER;
149 if (!(options & OPT_INTERACTIVE)) {
150 rv = noninteract_default;
151 goto jleave;
153 rv = FAL0;
155 if (prompt == NULL)
156 prompt = tr(264, "Continue (y/n)? ");
158 ohdl = safe_signal(SIGINT, SIG_IGN);
159 if (sigsetjmp(__tty_actjmp, 1) != 0) {
160 hadsig = TRU1;
161 goto jrestore;
163 safe_signal(SIGINT, &__tty_acthdl);
165 if (readline_input(prompt, FAL0, &termios_state.ts_linebuf,
166 &termios_state.ts_linesize, NULL) >= 0)
167 switch (termios_state.ts_linebuf[0]) {
168 case 'N': case 'n': rv = FAL0; break ;
169 default: rv = TRU1; break;
171 jrestore:
172 termios_state_reset();
173 safe_signal(SIGINT, ohdl);
174 jleave:
175 NYD_LEAVE;
176 if (hadsig && ohdl != SIG_IGN)
177 kill(0, SIGINT);
178 return rv;
181 FL char *
182 getuser(char const * volatile query) /* TODO v15-compat obsolete */
184 sighandler_type volatile ohdl;
185 char * volatile user = NULL;
186 bool_t volatile hadsig = FAL0;
187 NYD_ENTER;
189 if (query == NULL)
190 query = tr(509, "User: ");
192 ohdl = safe_signal(SIGINT, SIG_IGN);
193 if (sigsetjmp(__tty_actjmp, 1) != 0) {
194 hadsig = TRU1;
195 goto jrestore;
197 safe_signal(SIGINT, &__tty_acthdl);
199 if (readline_input(query, FAL0, &termios_state.ts_linebuf,
200 &termios_state.ts_linesize, NULL) >= 0)
201 user = termios_state.ts_linebuf;
202 jrestore:
203 termios_state_reset();
204 safe_signal(SIGINT, ohdl);
205 NYD_LEAVE;
206 if (hadsig && ohdl != SIG_IGN)
207 kill(0, SIGINT);
208 return user;
211 FL char *
212 getpassword(char const *query)
214 sighandler_type volatile ohdl;
215 struct termios tios;
216 char * volatile pass = NULL;
217 #if 0
218 bool_t hadsig = FAL0; /* TODO getpassword() no longer reraises SIGINT */
219 #endif
220 NYD_ENTER;
222 if (query == NULL)
223 query = tr(510, "Password: ");
224 fputs(query, stdout);
225 fflush(stdout);
227 /* FIXME everywhere: tcsetattr() generates SIGTTOU when we're not in
228 * FIXME foreground pgrp, and can fail with EINTR!! also affects
229 * FIXME termios_state_reset() */
230 if (options & OPT_TTYIN) {
231 tcgetattr(STDIN_FILENO, &termios_state.ts_tios);
232 memcpy(&tios, &termios_state.ts_tios, sizeof tios);
233 termios_state.ts_needs_reset = TRU1;
234 tios.c_iflag &= ~(ISTRIP);
235 tios.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
236 tcsetattr(STDIN_FILENO, TCSAFLUSH, &tios);
239 ohdl = safe_signal(SIGINT, SIG_IGN);
240 if (sigsetjmp(__tty_actjmp, 1) != 0) {
241 #if 0
242 hadsig = TRU1;
243 #endif
244 goto jrestore;
246 safe_signal(SIGINT, &__tty_acthdl);
248 if (readline_restart(stdin, &termios_state.ts_linebuf,
249 &termios_state.ts_linesize, 0) >= 0)
250 pass = termios_state.ts_linebuf;
251 jrestore:
252 termios_state_reset();
253 safe_signal(SIGINT, ohdl);
254 if (options & OPT_TTYIN)
255 fputc('\n', stdout);
256 NYD_LEAVE;
257 #if 0
258 if (hadsig && ohdl != SIG_IGN)
259 kill(0, SIGINT);
260 #endif
261 return pass;
265 * readline(3)
268 #ifdef HAVE_READLINE
269 static sighandler_type _rl_shup;
270 static char * _rl_buf; /* pre_input() hook: initial line */
271 static int _rl_buflen; /* content, and its length */
273 static int _rl_pre_input(void);
275 static int
276 _rl_pre_input(void)
278 NYD_ENTER;
279 /* Handle leftover data from \ escaped former line */
280 rl_extend_line_buffer(_rl_buflen + 10);
281 memcpy(rl_line_buffer, _rl_buf, _rl_buflen + 1);
282 rl_point = rl_end = _rl_buflen;
283 rl_pre_input_hook = (rl_hook_func_t*)NULL;
284 rl_redisplay();
285 NYD_LEAVE;
286 return 0;
289 FL void
290 tty_init(void)
292 # ifdef HAVE_HISTORY
293 long hs;
294 char *v;
295 # endif
296 NYD_ENTER;
298 rl_readline_name = UNCONST(uagent);
299 # ifdef HAVE_HISTORY
300 _CL_HISTSIZE(hs);
301 using_history();
302 stifle_history((int)hs);
303 # endif
304 rl_read_init_file(NULL);
306 /* Because rl_read_init_file() may have introduced yet a different
307 * history size limit, simply load and incorporate the history, leave
308 * it up to readline(3) to do the rest */
309 # ifdef HAVE_HISTORY
310 _CL_HISTFILE(v);
311 if (v != NULL)
312 read_history(v);
313 # endif
314 NYD_LEAVE;
317 FL void
318 tty_destroy(void)
320 # ifdef HAVE_HISTORY
321 char *v;
322 # endif
323 NYD_ENTER;
325 # ifdef HAVE_HISTORY
326 _CL_HISTFILE(v);
327 if (v != NULL)
328 write_history(v);
329 # endif
330 NYD_LEAVE;
333 FL void
334 tty_signal(int sig)
336 sigset_t nset, oset;
337 NYD_X; /* Signal handler */
339 switch (sig) {
340 # ifdef SIGWINCH
341 case SIGWINCH:
342 break;
343 # endif
344 case SIGHUP:
345 /* readline(3) doesn't catch it :( */
346 rl_free_line_state();
347 rl_cleanup_after_signal();
348 safe_signal(SIGHUP, _rl_shup);
349 sigemptyset(&nset);
350 sigaddset(&nset, sig);
351 sigprocmask(SIG_UNBLOCK, &nset, &oset);
352 kill(0, sig);
353 /* XXX When we come here we'll continue editing, so reestablish
354 * XXX cannot happen */
355 sigprocmask(SIG_BLOCK, &oset, NULL);
356 _rl_shup = safe_signal(SIGHUP, &tty_signal);
357 rl_reset_after_signal();
358 break;
359 default:
360 break;
364 FL int
365 (tty_readline)(char const *prompt, char **linebuf, size_t *linesize, size_t n
366 SMALLOC_DEBUG_ARGS)
368 int nn;
369 char *line;
370 NYD_ENTER;
372 if (n > 0) {
373 _rl_buf = *linebuf;
374 _rl_buflen = (int)n;
375 rl_pre_input_hook = &_rl_pre_input;
378 _rl_shup = safe_signal(SIGHUP, &tty_signal);
379 line = readline(prompt != NULL ? prompt : "");
380 safe_signal(SIGHUP, _rl_shup);
382 if (line == NULL) {
383 nn = -1;
384 goto jleave;
386 n = strlen(line);
388 if (n >= *linesize) {
389 *linesize = LINESIZE + n +1;
390 *linebuf = (srealloc)(*linebuf, *linesize SMALLOC_DEBUG_ARGSCALL);
392 memcpy(*linebuf, line, n);
393 (free)(line);
394 (*linebuf)[n] = '\0';
395 nn = (int)n;
396 jleave:
397 NYD_LEAVE;
398 return nn;
401 FL void
402 tty_addhist(char const *s)
404 NYD_ENTER;
405 UNUSED(s);
406 # ifdef HAVE_HISTORY
407 _CL_CHECK_ADDHIST(s, goto jleave);
408 hold_all_sigs(); /* XXX too heavy */
409 add_history(s); /* XXX yet we jump away! */
410 rele_all_sigs(); /* XXX remove jumps */
411 jleave:
412 # endif
413 NYD_LEAVE;
416 # ifdef HAVE_HISTORY
417 FL int
418 c_history(void *v)
420 C_HISTORY_SHARED;
422 jlist: {
423 FILE *fp;
424 HISTORY_STATE *hs;
425 HIST_ENTRY **hl;
426 ul_it i, b;
428 if ((fp = Ftmp(NULL, "hist", OF_RDWR | OF_UNLINK | OF_REGISTER, 0600)) ==
429 NULL) {
430 perror("tmpfile");
431 v = NULL;
432 goto jleave;
435 hs = history_get_history_state();
437 for (i = (ul_it)hs->length, hl = hs->entries + i, b = 0; i > 0; --i) {
438 char *cp = (*--hl)->line;
439 size_t sl = strlen(cp);
440 fprintf(fp, "%4lu. %-50.50s (%4lu+%2lu bytes)\n", i, cp, b, sl);
441 b += sl;
444 page_or_print(fp, (size_t)hs->length);
445 Fclose(fp);
447 goto jleave;
449 jclear:
450 clear_history();
451 goto jleave;
453 jentry: {
454 HISTORY_STATE *hs = history_get_history_state();
456 if (UICMP(z, entry, <=, hs->length))
457 v = temporary_arg_v_store = hs->entries[entry - 1]->line;
458 else
459 v = NULL;
461 goto jleave;
463 # endif /* HAVE_HISTORY */
464 #endif /* HAVE_READLINE */
467 * BSD editline(3)
470 #ifdef HAVE_EDITLINE
471 static EditLine * _el_el; /* editline(3) handle */
472 static char const * _el_prompt; /* Current prompt */
473 # ifdef HAVE_HISTORY
474 static History * _el_hcom; /* History handle for commline */
475 # endif
477 static char const * _el_getprompt(void);
479 static char const *
480 _el_getprompt(void)
482 return _el_prompt;
485 FL void
486 tty_init(void)
488 # ifdef HAVE_HISTORY
489 HistEvent he;
490 long hs;
491 char *v;
492 # endif
493 NYD_ENTER;
495 # ifdef HAVE_HISTORY
496 _CL_HISTSIZE(hs);
497 _el_hcom = history_init();
498 history(_el_hcom, &he, H_SETSIZE, (int)hs);
499 /* We unroll our own one history(_el_hcom, &he, H_SETUNIQUE, 1);*/
500 # endif
502 _el_el = el_init(uagent, stdin, stdout, stderr);
503 el_set(_el_el, EL_SIGNAL, 1);
504 el_set(_el_el, EL_TERMINAL, NULL);
505 /* Need to set HIST before EDITOR, otherwise it won't work automatic */
506 # ifdef HAVE_HISTORY
507 el_set(_el_el, EL_HIST, &history, _el_hcom);
508 # endif
509 el_set(_el_el, EL_EDITOR, "emacs");
510 # ifdef EL_PROMPT_ESC
511 el_set(_el_el, EL_PROMPT_ESC, &_el_getprompt, '\1');
512 # else
513 el_set(_el_el, EL_PROMPT, &_el_getprompt);
514 # endif
515 # if 0
516 el_set(_el_el, EL_ADDFN, "tab_complete",
517 "editline(3) internal completion function", &_el_file_cpl);
518 el_set(_el_el, EL_BIND, "^I", "tab_complete", NULL);
519 # endif
520 # ifdef HAVE_HISTORY
521 el_set(_el_el, EL_BIND, "^R", "ed-search-prev-history", NULL);
522 # endif
523 el_source(_el_el, NULL); /* Source ~/.editrc */
525 /* Because el_source() may have introduced yet a different history size
526 * limit, simply load and incorporate the history, leave it up to
527 * editline(3) to do the rest */
528 # ifdef HAVE_HISTORY
529 _CL_HISTFILE(v);
530 if (v != NULL)
531 history(_el_hcom, &he, H_LOAD, v);
532 # endif
533 NYD_LEAVE;
536 FL void
537 tty_destroy(void)
539 # ifdef HAVE_HISTORY
540 HistEvent he;
541 char *v;
542 # endif
543 NYD_ENTER;
545 el_end(_el_el);
547 # ifdef HAVE_HISTORY
548 _CL_HISTFILE(v);
549 if (v != NULL)
550 history(_el_hcom, &he, H_SAVE, v);
551 history_end(_el_hcom);
552 # endif
553 NYD_LEAVE;
556 FL void
557 tty_signal(int sig)
559 NYD_X; /* Signal handler */
560 switch (sig) {
561 # ifdef SIGWINCH
562 case SIGWINCH:
563 el_resize(_el_el);
564 break;
565 # endif
566 default:
567 break;
571 FL int
572 (tty_readline)(char const *prompt, char **linebuf, size_t *linesize, size_t n
573 SMALLOC_DEBUG_ARGS)
575 int nn;
576 char const *line;
577 NYD_ENTER;
579 _el_prompt = (prompt != NULL) ? prompt : "";
580 if (n > 0)
581 el_push(_el_el, *linebuf);
582 line = el_gets(_el_el, &nn);
584 if (line == NULL) {
585 nn = -1;
586 goto jleave;
588 assert(nn >= 0);
589 n = (size_t)nn;
590 if (n > 0 && line[n - 1] == '\n')
591 nn = (int)--n;
593 if (n >= *linesize) {
594 *linesize = LINESIZE + n + 1;
595 *linebuf = (srealloc)(*linebuf, *linesize SMALLOC_DEBUG_ARGSCALL);
597 memcpy(*linebuf, line, n);
598 (*linebuf)[n] = '\0';
599 jleave:
600 NYD_LEAVE;
601 return nn;
604 FL void
605 tty_addhist(char const *s)
607 # ifdef HAVE_HISTORY
608 /* Enlarge meaning of unique .. to something that rocks;
609 * xxx unfortunately this is expensive to do with editline(3)
610 * xxx maybe it would be better to hook the ptfs instead? */
611 HistEvent he;
612 int i;
613 # endif
614 NYD_ENTER;
615 UNUSED(s);
617 # ifdef HAVE_HISTORY
618 _CL_CHECK_ADDHIST(s, goto jleave);
620 hold_all_sigs(); /* XXX too heavy, yet we jump away! */
621 for (i = history(_el_hcom, &he, H_FIRST); i >= 0;
622 i = history(_el_hcom, &he, H_NEXT))
623 if (!strcmp(he.str, s)) {
624 history(_el_hcom, &he, H_DEL, he.num);
625 break;
627 history(_el_hcom, &he, H_ENTER, s);
628 rele_all_sigs(); /* XXX remove jumps */
629 jleave:
630 # endif
631 NYD_LEAVE;
634 # ifdef HAVE_HISTORY
635 FL int
636 c_history(void *v)
638 C_HISTORY_SHARED;
640 jlist: {
641 HistEvent he;
642 FILE *fp;
643 size_t i, b;
644 int x;
646 if ((fp = Ftmp(NULL, "hist", OF_RDWR | OF_UNLINK | OF_REGISTER, 0600)) ==
647 NULL) {
648 perror("tmpfile");
649 v = NULL;
650 goto jleave;
653 i = (size_t)((history(_el_hcom, &he, H_GETSIZE) >= 0) ? he.num : 0);
654 b = 0;
655 for (x = history(_el_hcom, &he, H_FIRST); x >= 0;
656 x = history(_el_hcom, &he, H_NEXT)) {
657 size_t sl = strlen(he.str);
658 fprintf(fp, "%4lu. %-50.50s (%4lu+%2lu bytes)\n",
659 (ul_it)i, he.str, (ul_it)b, (ul_it)sl);
660 --i;
661 b += sl;
664 page_or_print(fp, i);
665 Fclose(fp);
667 goto jleave;
669 jclear: {
670 HistEvent he;
671 history(_el_hcom, &he, H_CLEAR);
673 goto jleave;
675 jentry: {
676 HistEvent he;
677 size_t i;
678 int x;
680 i = (size_t)((history(_el_hcom, &he, H_GETSIZE) >= 0) ? he.num : 0);
681 if (UICMP(z, entry, <=, i)) {
682 entry = (long)i - entry;
683 for (x = history(_el_hcom, &he, H_FIRST); x >= 0;
684 x = history(_el_hcom, &he, H_NEXT))
685 if (entry-- == 0) {
686 v = temporary_arg_v_store = UNCONST(he.str);
687 goto jleave;
690 v = NULL;
692 goto jleave;
694 # endif /* HAVE_HISTORY */
695 #endif /* HAVE_EDITLINE */
698 * NCL: our homebrew version (inspired from NetBSD sh(1) / dash(1)s hetio.c).
700 * Only used in interactive mode, simply use STDIN_FILENO as point of interest.
701 * We do not handle character widths because the terminal must deal with that
702 * anyway on the one hand, and also wcwidth(3) doesn't support zero-width
703 * characters by definition on the other. We're addicted.
705 * To avoid memory leaks etc. with the current codebase that simply longjmp(3)s
706 * we're forced to use the very same buffer--the one that is passed through to
707 * us from the outside--to store anything we need, i.e., a `struct cell[]', and
708 * convert that on-the-fly back to the plain char* result once we're done.
709 * To simplify our live, use savestr() buffers for all other needed memory
713 * TODO NCL: don't use that stupid .sint=-1 stuff, but simply block all signals
714 * TODO NCL: during handler de-/installation handling.
717 #ifdef HAVE_NCL
718 # ifndef MAX_INPUT
719 # define MAX_INPUT 255 /* (_POSIX_MAX_INPUT = 255 as of Issue 7 TC1) */
720 # endif
722 /* Since we simply fputs(3) the prompt, assume each character requires two
723 * visual cells -- and we need to restrict the maximum prompt size because
724 * of MAX_INPUT and our desire to have room for some error message left */
725 # define _PROMPT_VLEN(P) (strlen(P) * 2)
726 # define _PROMPT_MAX ((MAX_INPUT / 2) + (MAX_INPUT / 4))
728 union xsighdl {
729 sighandler_type shdl; /* Try avoid races by setting */
730 sl_it sint; /* .sint=-1 when inactive */
732 CTA(sizeof(sl_it) >= sizeof(sighandler_type));
734 struct xtios {
735 struct termios told;
736 struct termios tnew;
739 struct cell {
740 wchar_t wc;
741 ui32_t count;
742 char cbuf[MB_LEN_MAX * 2]; /* .. plus reset shift sequence */
745 struct line {
746 size_t cursor; /* Current cursor position */
747 size_t topins; /* Outermost cursor col set */
748 union {
749 char * cbuf; /* *x_buf */
750 struct cell * cells;
751 } line;
752 struct str defc; /* Current default content */
753 struct str savec; /* Saved default content */
754 # ifdef HAVE_HISTORY
755 struct hist * hist; /* History cursor */
756 # endif
757 char const * prompt;
758 char const * nd; /* Cursor right */
759 char ** x_buf; /* Caller pointers */
760 size_t * x_bufsize;
763 # ifdef HAVE_HISTORY
764 struct hist {
765 struct hist * older;
766 struct hist * younger;
767 size_t len;
768 char dat[VFIELD_SIZE(sizeof(size_t))];
770 # endif
772 static union xsighdl _ncl_oint;
773 static union xsighdl _ncl_oquit;
774 static union xsighdl _ncl_oterm;
775 static union xsighdl _ncl_ohup;
776 static union xsighdl _ncl_otstp;
777 static union xsighdl _ncl_ottin;
778 static union xsighdl _ncl_ottou;
779 static struct xtios _ncl_tios;
780 # ifdef HAVE_HISTORY
781 static struct hist * _ncl_hist;
782 static struct hist * _ncl_hist_tail;
783 static size_t _ncl_hist_size;
784 static size_t _ncl_hist_size_max;
785 static bool_t _ncl_hist_load;
786 # endif
788 static void _ncl_sigs_up(void);
789 static void _ncl_sigs_down(void);
791 static void _ncl_term_mode(bool_t raw);
793 static void _ncl_check_grow(struct line *l, size_t no SMALLOC_DEBUG_ARGS);
794 static void _ncl_bs_eof_dvup(struct cell *cap, size_t i);
795 static ssize_t _ncl_wboundary(struct line *l, ssize_t dir);
796 static ssize_t _ncl_cell2dat(struct line *l);
797 # if defined HAVE_HISTORY || defined HAVE_TABEXPAND
798 static void _ncl_cell2save(struct line *l);
799 # endif
801 static void _ncl_khome(struct line *l, bool_t dobell);
802 static void _ncl_kend(struct line *l);
803 static void _ncl_kbs(struct line *l);
804 static void _ncl_kkill(struct line *l, bool_t dobell);
805 static ssize_t _ncl_keof(struct line *l);
806 static void _ncl_kleft(struct line *l);
807 static void _ncl_kright(struct line *l);
808 static void _ncl_krefresh(struct line *l);
809 static void _ncl_kbwddelw(struct line *l);
810 static void _ncl_kgow(struct line *l, ssize_t dir);
811 static void _ncl_kother(struct line *l, wchar_t wc);
812 # ifdef HAVE_HISTORY
813 static size_t __ncl_khist_shared(struct line *l, struct hist *hp);
814 static size_t _ncl_khist(struct line *l, bool_t backwd);
815 static size_t _ncl_krhist(struct line *l);
816 # endif
817 # ifdef HAVE_TABEXPAND
818 static size_t _ncl_kht(struct line *l);
819 # endif
820 static ssize_t _ncl_readline(char const *prompt, char **buf, size_t *bufsize,
821 size_t len SMALLOC_DEBUG_ARGS);
823 static void
824 _ncl_sigs_up(void)
826 NYD_ENTER;
827 if (_ncl_oint.sint == -1)
828 _ncl_oint.shdl = safe_signal(SIGINT, &tty_signal);
829 if (_ncl_oquit.sint == -1)
830 _ncl_oquit.shdl = safe_signal(SIGQUIT, &tty_signal);
831 if (_ncl_oterm.sint == -1)
832 _ncl_oterm.shdl = safe_signal(SIGTERM, &tty_signal);
833 if (_ncl_ohup.sint == -1)
834 _ncl_ohup.shdl = safe_signal(SIGHUP, &tty_signal);
835 if (_ncl_otstp.sint == -1)
836 _ncl_otstp.shdl = safe_signal(SIGTSTP, &tty_signal);
837 if (_ncl_ottin.sint == -1)
838 _ncl_ottin.shdl = safe_signal(SIGTTIN, &tty_signal);
839 if (_ncl_ottou.sint == -1)
840 _ncl_ottou.shdl = safe_signal(SIGTTOU, &tty_signal);
841 NYD_LEAVE;
844 static void
845 _ncl_sigs_down(void)
847 /* aaah.. atomic cas would be nice (but isn't it all redundant?) */
848 sighandler_type st;
849 NYD_ENTER;
851 if (_ncl_ottou.sint != -1) {
852 st = _ncl_ottou.shdl, _ncl_ottou.sint = -1;
853 safe_signal(SIGTTOU, st);
855 if (_ncl_ottin.sint != -1) {
856 st = _ncl_ottin.shdl, _ncl_ottin.sint = -1;
857 safe_signal(SIGTTIN, st);
859 if (_ncl_otstp.sint != -1) {
860 st = _ncl_otstp.shdl, _ncl_otstp.sint = -1;
861 safe_signal(SIGTSTP, st);
863 if (_ncl_ohup.sint != -1) {
864 st = _ncl_ohup.shdl, _ncl_ohup.sint = -1;
865 safe_signal(SIGHUP, st);
867 if (_ncl_oterm.sint != -1) {
868 st = _ncl_oterm.shdl, _ncl_oterm.sint = -1;
869 safe_signal(SIGTERM, st);
871 if (_ncl_oquit.sint != -1) {
872 st = _ncl_oquit.shdl, _ncl_oquit.sint = -1;
873 safe_signal(SIGQUIT, st);
875 if (_ncl_oint.sint != -1) {
876 st = _ncl_oint.shdl, _ncl_oint.sint = -1;
877 safe_signal(SIGINT, st);
879 NYD_LEAVE;
882 static void
883 _ncl_term_mode(bool_t raw)
885 struct termios *tiosp;
886 NYD_ENTER;
888 tiosp = &_ncl_tios.told;
889 if (!raw)
890 goto jleave;
892 /* Always requery the attributes, in case we've been moved from background
893 * to foreground or however else in between sessions */
894 tcgetattr(STDIN_FILENO, tiosp);
895 memcpy(&_ncl_tios.tnew, tiosp, sizeof *tiosp);
896 tiosp = &_ncl_tios.tnew;
897 tiosp->c_cc[VMIN] = 1;
898 tiosp->c_cc[VTIME] = 0;
899 tiosp->c_iflag &= ~(ISTRIP);
900 tiosp->c_lflag &= ~(ECHO /*| ECHOE | ECHONL */| ICANON | IEXTEN);
901 jleave:
902 tcsetattr(STDIN_FILENO, TCSADRAIN, tiosp);
903 NYD_LEAVE;
906 static void
907 _ncl_check_grow(struct line *l, size_t no SMALLOC_DEBUG_ARGS)
909 size_t i;
910 NYD_ENTER;
912 i = (l->topins + no) * sizeof(struct cell) + 2 * sizeof(struct cell);
913 if (i > *l->x_bufsize) {
914 i <<= 1;
915 *l->x_bufsize = i;
916 l->line.cbuf =
917 *l->x_buf = (srealloc)(*l->x_buf, i SMALLOC_DEBUG_ARGSCALL);
919 NYD_LEAVE;
922 static void
923 _ncl_bs_eof_dvup(struct cell *cap, size_t i)
925 size_t j;
926 NYD_ENTER;
928 if (i > 0)
929 memmove(cap, cap + 1, i * sizeof(*cap));
931 /* And.. the (rest of the) visual update */
932 for (j = 0; j < i; ++j)
933 fwrite(cap[j].cbuf, sizeof *cap->cbuf, cap[j].count, stdout);
934 fputs(" \b", stdout);
935 for (j = 0; j < i; ++j)
936 putchar('\b');
937 NYD_LEAVE;
940 static ssize_t
941 _ncl_wboundary(struct line *l, ssize_t dir)
943 size_t c, t, i;
944 struct cell *cap;
945 bool_t anynon;
946 NYD_ENTER;
948 c = l->cursor;
949 t = l->topins;
950 i = (size_t)-1;
952 if (dir < 0) {
953 if (c == 0)
954 goto jleave;
955 } else if (c == t)
956 goto jleave;
957 else
958 --t, --c; /* Unsigned wrapping may occur (twice), then */
960 for (i = 0, cap = l->line.cells, anynon = FAL0;;) {
961 wchar_t wc = cap[c + dir].wc;
962 if (iswblank(wc) || iswpunct(wc)) {
963 if (anynon)
964 break;
965 } else
966 anynon = TRU1;
967 ++i;
968 c += dir;
969 if (dir < 0) {
970 if (c == 0)
971 break;
972 } else if (c == t)
973 break;
975 jleave:
976 NYD_LEAVE;
977 return (ssize_t)i;
980 static ssize_t
981 _ncl_cell2dat(struct line *l)
983 size_t len = 0, i;
984 NYD_ENTER;
986 if (l->topins > 0)
987 for (i = 0; i < l->topins; ++i) {
988 struct cell *cap = l->line.cells + i;
989 memcpy(l->line.cbuf + len, cap->cbuf, cap->count);
990 len += cap->count;
992 l->line.cbuf[len] = '\0';
993 NYD_LEAVE;
994 return (ssize_t)len;
997 # if defined HAVE_HISTORY || defined HAVE_TABEXPAND
998 static void
999 _ncl_cell2save(struct line *l)
1001 size_t len, i;
1002 struct cell *cap;
1003 NYD_ENTER;
1005 l->savec.s = NULL, l->savec.l = 0;
1006 if (l->topins == 0)
1007 goto jleave;
1009 for (cap = l->line.cells, len = i = 0; i < l->topins; ++cap, ++i)
1010 len += cap->count;
1012 l->savec.l = len;
1013 l->savec.s = salloc(len + 1);
1015 for (cap = l->line.cells, len = i = 0; i < l->topins; ++cap, ++i) {
1016 memcpy(l->savec.s + len, cap->cbuf, cap->count);
1017 len += cap->count;
1019 l->savec.s[len] = '\0';
1020 jleave:
1021 NYD_LEAVE;
1023 # endif
1025 static void
1026 _ncl_khome(struct line *l, bool_t dobell)
1028 size_t c;
1029 NYD_ENTER;
1031 c = l->cursor;
1032 if (c > 0) {
1033 l->cursor = 0;
1034 while (c-- != 0)
1035 putchar('\b');
1036 } else if (dobell)
1037 putchar('\a');
1038 NYD_LEAVE;
1041 static void
1042 _ncl_kend(struct line *l)
1044 ssize_t i;
1045 NYD_ENTER;
1047 i = (ssize_t)(l->topins - l->cursor);
1049 if (i > 0) {
1050 l->cursor = l->topins;
1051 while (i-- != 0)
1052 fputs(l->nd, stdout);
1053 } else
1054 putchar('\a');
1055 NYD_LEAVE;
1058 static void
1059 _ncl_kbs(struct line *l)
1061 ssize_t c, t;
1062 NYD_ENTER;
1064 c = l->cursor;
1065 t = l->topins;
1067 if (c > 0) {
1068 putchar('\b');
1069 l->cursor = --c;
1070 l->topins = --t;
1071 t -= c;
1072 _ncl_bs_eof_dvup(l->line.cells + c, t);
1073 } else
1074 putchar('\a');
1075 NYD_LEAVE;
1078 static void
1079 _ncl_kkill(struct line *l, bool_t dobell)
1081 size_t j, c, i;
1082 NYD_ENTER;
1084 c = l->cursor;
1085 i = (size_t)(l->topins - c);
1087 if (i > 0) {
1088 l->topins = c;
1089 for (j = i; j != 0; --j)
1090 putchar(' ');
1091 for (j = i; j != 0; --j)
1092 putchar('\b');
1093 } else if (dobell)
1094 putchar('\a');
1095 NYD_LEAVE;
1098 static ssize_t
1099 _ncl_keof(struct line *l)
1101 size_t c, t;
1102 ssize_t i;
1103 NYD_ENTER;
1105 c = l->cursor;
1106 t = l->topins;
1107 i = (ssize_t)(t - c);
1109 if (i > 0) {
1110 l->topins = --t;
1111 _ncl_bs_eof_dvup(l->line.cells + c, --i);
1112 } else if (t == 0 && !ok_blook(ignoreeof)) {
1113 fputs("^D", stdout);
1114 fflush(stdout);
1115 i = -1;
1116 } else {
1117 putchar('\a');
1118 i = 0;
1120 NYD_LEAVE;
1121 return i;
1124 static void
1125 _ncl_kleft(struct line *l)
1127 NYD_ENTER;
1128 if (l->cursor > 0) {
1129 --l->cursor;
1130 putchar('\b');
1131 } else
1132 putchar('\a');
1133 NYD_LEAVE;
1136 static void
1137 _ncl_kright(struct line *l)
1139 NYD_ENTER;
1140 if (l->cursor < l->topins) {
1141 ++l->cursor;
1142 fputs(l->nd, stdout);
1143 } else
1144 putchar('\a');
1145 NYD_LEAVE;
1148 static void
1149 _ncl_krefresh(struct line *l)
1151 struct cell *cap;
1152 size_t i;
1153 NYD_ENTER;
1155 putchar('\r');
1156 if (l->prompt != NULL && *l->prompt != '\0')
1157 fputs(l->prompt, stdout);
1158 for (cap = l->line.cells, i = l->topins; i > 0; ++cap, --i)
1159 fwrite(cap->cbuf, sizeof *cap->cbuf, cap->count, stdout);
1160 for (i = l->topins - l->cursor; i > 0; --i)
1161 putchar('\b');
1162 NYD_LEAVE;
1165 static void
1166 _ncl_kbwddelw(struct line *l)
1168 ssize_t i;
1169 size_t c, t, j;
1170 struct cell *cap;
1171 NYD_ENTER;
1173 i = _ncl_wboundary(l, -1);
1174 if (i <= 0) {
1175 if (i < 0)
1176 putchar('\a');
1177 goto jleave;
1180 c = l->cursor - i;
1181 t = l->topins;
1182 l->topins = t - i;
1183 l->cursor = c;
1184 cap = l->line.cells + c;
1186 if (t != l->cursor) {
1187 j = t - c + i;
1188 memmove(cap, cap + i, j * sizeof(*cap));
1191 for (j = i; j > 0; --j)
1192 putchar('\b');
1193 for (j = l->topins - c; j > 0; ++cap, --j)
1194 fwrite(cap[0].cbuf, sizeof *cap->cbuf, cap[0].count, stdout);
1195 for (j = i; j > 0; --j)
1196 putchar(' ');
1197 for (j = t - c; j > 0; --j)
1198 putchar('\b');
1199 jleave:
1200 NYD_LEAVE;
1203 static void
1204 _ncl_kgow(struct line *l, ssize_t dir)
1206 ssize_t i;
1207 NYD_ENTER;
1209 i = _ncl_wboundary(l, dir);
1210 if (i <= 0) {
1211 if (i < 0)
1212 putchar('\a');
1213 goto jleave;
1216 if (dir < 0) {
1217 l->cursor -= i;
1218 while (i-- > 0)
1219 putchar('\b');
1220 } else {
1221 l->cursor += i;
1222 while (i-- > 0)
1223 fputs(l->nd, stdout);
1225 jleave:
1226 NYD_LEAVE;
1229 static void
1230 _ncl_kother(struct line *l, wchar_t wc)
1232 /* Append if at EOL, insert otherwise;
1233 * since we may move around character-wise, always use a fresh ps */
1234 mbstate_t ps;
1235 struct cell cell, *cap;
1236 size_t i, c;
1237 NYD_ENTER;
1239 /* First init a cell and see wether we'll really handle this wc */
1240 cell.wc = wc;
1241 memset(&ps, 0, sizeof ps);
1242 i = wcrtomb(cell.cbuf, wc, &ps);
1243 if (i > MB_LEN_MAX)
1244 goto jleave;
1245 cell.count = (ui_it)i;
1246 if (enc_has_state) {
1247 i = wcrtomb(cell.cbuf + i, L'\0', &ps);
1248 if (i == 1)
1250 else if (--i < MB_LEN_MAX)
1251 cell.count += (ui_it)i;
1252 else
1253 goto jleave;
1256 /* Yes, we will! Place it in the array */
1257 c = l->cursor++;
1258 i = l->topins++ - c;
1259 cap = l->line.cells + c;
1260 if (i > 0)
1261 memmove(cap + 1, cap, i * sizeof(cell));
1262 memcpy(cap, &cell, sizeof cell);
1264 /* And update visual */
1265 c = i;
1267 fwrite(cap->cbuf, sizeof *cap->cbuf, cap->count, stdout);
1268 while ((++cap, i-- != 0));
1269 while (c-- != 0)
1270 putchar('\b');
1271 jleave:
1272 NYD_LEAVE;
1275 # ifdef HAVE_HISTORY
1276 static size_t
1277 __ncl_khist_shared(struct line *l, struct hist *hp)
1279 size_t rv;
1280 NYD_ENTER;
1282 if ((l->hist = hp) != NULL) {
1283 l->defc.s = savestrbuf(hp->dat, hp->len);
1284 rv =
1285 l->defc.l = hp->len;
1286 if (l->topins > 0) {
1287 _ncl_khome(l, FAL0);
1288 _ncl_kkill(l, FAL0);
1290 } else {
1291 putchar('\a');
1292 rv = 0;
1294 NYD_LEAVE;
1295 return rv;
1298 static size_t
1299 _ncl_khist(struct line *l, bool_t backwd)
1301 struct hist *hp;
1302 size_t rv;
1303 NYD_ENTER;
1305 /* If we're not in history mode yet, save line content;
1306 * also, disallow forward search, then, and, of course, bail unless we
1307 * do have any history at all */
1308 if ((hp = l->hist) == NULL) {
1309 if (!backwd)
1310 goto jleave;
1311 if ((hp = _ncl_hist) == NULL)
1312 goto jleave;
1313 _ncl_cell2save(l);
1314 goto jleave;
1317 hp = backwd ? hp->older : hp->younger;
1318 jleave:
1319 rv = __ncl_khist_shared(l, hp);
1320 NYD_LEAVE;
1321 return rv;
1324 static size_t
1325 _ncl_krhist(struct line *l)
1327 struct str orig_savec;
1328 struct hist *hp = NULL;
1329 size_t rv;
1330 NYD_ENTER;
1332 /* We cannot complete an empty line */
1333 if (l->topins == 0) {
1334 /* XXX The upcoming hard reset would restore a set savec buffer,
1335 * XXX so forcefully reset that. A cleaner solution would be to
1336 * XXX reset it whenever a restore is no longer desired */
1337 l->savec.s = NULL, l->savec.l = 0;
1338 goto jleave;
1340 if ((hp = l->hist) == NULL) {
1341 if ((hp = _ncl_hist) == NULL)
1342 goto jleave;
1343 orig_savec.s = NULL;
1344 orig_savec.l = 0; /* silence CC */
1345 } else if ((hp = hp->older) == NULL)
1346 goto jleave;
1347 else
1348 orig_savec = l->savec;
1350 if (orig_savec.s == NULL)
1351 _ncl_cell2save(l);
1352 for (; hp != NULL; hp = hp->older)
1353 if (is_prefix(l->savec.s, hp->dat))
1354 break;
1355 if (orig_savec.s != NULL)
1356 l->savec = orig_savec;
1357 jleave:
1358 rv = __ncl_khist_shared(l, hp);
1359 NYD_LEAVE;
1360 return rv;
1362 # endif
1364 # ifdef HAVE_TABEXPAND
1365 static size_t
1366 _ncl_kht(struct line *l)
1368 struct str orig, bot, topp, sub, exp;
1369 struct cell *cword, *ctop, *cx;
1370 bool_t set_savec = FAL0;
1371 size_t rv = 0;
1372 NYD_ENTER;
1374 /* We cannot expand an empty line */
1375 if (l->topins == 0)
1376 goto jleave;
1378 /* Get plain line data; if this is the first expansion/xy, update the
1379 * very original content so that ^G gets the origin back */
1380 orig = l->savec;
1381 _ncl_cell2save(l);
1382 exp = l->savec;
1383 if (orig.s != NULL)
1384 l->savec = orig;
1385 else
1386 set_savec = TRU1;
1387 orig = exp;
1389 cword = l->line.cells;
1390 ctop = cword + l->cursor;
1392 /* topp: separate data right of cursor */
1393 if ((cx = cword + l->topins) != ctop) {
1394 for (rv = 0; cx > ctop; --cx)
1395 rv += cx->count;
1396 topp.l = rv;
1397 topp.s = orig.s + orig.l - rv;
1398 } else
1399 topp.s = NULL, topp.l = 0;
1401 /* bot, sub: we cannot expand the entire data left of cursor, but only
1402 * the last "word", so separate them */
1403 while (cx > cword && !iswspace(cx[-1].wc))
1404 --cx;
1405 for (rv = 0; cword < cx; ++cword)
1406 rv += cword->count;
1407 sub =
1408 bot = orig;
1409 bot.l = rv;
1410 sub.s += rv;
1411 sub.l -= rv;
1412 sub.l -= topp.l;
1414 /* Leave room for "implicit asterisk" expansion, as below */
1415 if (sub.l == 0) {
1416 sub.s = UNCONST("*");
1417 sub.l = 1;
1418 } else {
1419 exp.s = salloc(sub.l + 1 +1);
1420 memcpy(exp.s, sub.s, sub.l);
1421 exp.s[sub.l] = '\0';
1422 sub.s = exp.s;
1425 /* TODO there is a TODO note upon fexpand() with multi-return;
1426 * TODO if that will change, the if() below can be simplified */
1427 /* Super-Heavy-Metal: block all sigs, avoid leaks on jump */
1428 jredo:
1429 hold_all_sigs();
1430 exp.s = fexpand(sub.s, _CL_TAB_FEXP_FL);
1431 rele_all_sigs();
1433 if (exp.s == NULL || (exp.l = strlen(exp.s)) == 0)
1434 goto jnope;
1435 /* If the expansion equals the original string, assume the user wants what
1436 * is usually known as tab completion, append `*' and restart */
1437 if (exp.l == sub.l && !strcmp(exp.s, sub.s)) {
1438 if (sub.s[sub.l - 1] == '*')
1439 goto jnope;
1440 sub.s[sub.l++] = '*';
1441 sub.s[sub.l] = '\0';
1442 goto jredo;
1445 /* Cramp expansion length to MAX_INPUT, or 255 if not defined.
1446 * Take care to take *prompt* into account, since we don't know
1447 * anything about it's visual length (fputs(3) is used), simply
1448 * assume each character requires two columns */
1449 /* TODO the problem is that we loose control otherwise; in the best
1450 * TODO case the user can control via ^A and ^K etc., but be safe;
1451 * TODO we cannot simply adjust fexpand() because we don't know how
1452 * TODO that is implemented... The real solution would be to check
1453 * TODO wether we fit on a line, and start a pager if not.
1454 * TODO However, that should be part of a real tab-COMPLETION, then,
1455 * TODO i.e., don't EXPAND, but SHOW COMPLETIONS, page-wise if needed.
1456 * TODO And: MAX_INPUT is dynamic: pathconf(2), _SC_MAX_INPUT */
1457 rv = (l->prompt != NULL) ? _PROMPT_VLEN(l->prompt) : 0;
1458 if (rv + bot.l + exp.l + topp.l >= MAX_INPUT) {
1459 char const e1[] = "[ERR_TOO_LONG]";
1460 exp.s = UNCONST(e1);
1461 exp.l = sizeof(e1) - 1;
1462 topp.l = 0;
1463 if (rv + bot.l + exp.l >= MAX_INPUT)
1464 bot.l = 0;
1465 if (rv + exp.l >= MAX_INPUT) {
1466 char const e2[] = "[ERR]";
1467 exp.s = UNCONST(e2);
1468 exp.l = sizeof(e2) - 1;
1472 orig.l = bot.l + exp.l + topp.l;
1473 orig.s = salloc(orig.l + 5 +1);
1474 if ((rv = bot.l) > 0)
1475 memcpy(orig.s, bot.s, rv);
1476 memcpy(orig.s + rv, exp.s, exp.l);
1477 rv += exp.l;
1478 if (topp.l > 0) {
1479 memcpy(orig.s + rv, topp.s, topp.l);
1480 rv += topp.l;
1482 orig.s[rv] = '\0';
1484 l->defc = orig;
1485 _ncl_khome(l, FAL0);
1486 _ncl_kkill(l, FAL0);
1487 jleave:
1488 NYD_LEAVE;
1489 return rv;
1490 jnope:
1491 /* If we've provided a default content, but failed to expand, there is
1492 * nothing we can "revert to": drop that default again */
1493 if (set_savec)
1494 l->savec.s = NULL, l->savec.l = 0;
1495 rv = 0;
1496 goto jleave;
1498 # endif /* HAVE_TABEXPAND */
1500 static ssize_t
1501 _ncl_readline(char const *prompt, char **buf, size_t *bufsize, size_t len
1502 SMALLOC_DEBUG_ARGS)
1504 /* We want to save code, yet we may have to incorporate a lines'
1505 * default content and / or default input to switch back to after some
1506 * history movement; let "len > 0" mean "have to display some data
1507 * buffer", and only otherwise read(2) it */
1508 mbstate_t ps[2];
1509 struct line l;
1510 char cbuf_base[MB_LEN_MAX * 2], *cbuf, *cbufp, cursor_maybe, cursor_store;
1511 wchar_t wc;
1512 ssize_t rv;
1513 NYD_ENTER;
1515 memset(&l, 0, sizeof l);
1516 l.line.cbuf = *buf;
1517 if (len != 0) {
1518 l.defc.s = savestrbuf(*buf, len);
1519 l.defc.l = len;
1521 if ((l.prompt = prompt) != NULL && _PROMPT_VLEN(prompt) > _PROMPT_MAX)
1522 l.prompt = prompt = "?ERR?";
1523 /* TODO *l.nd=='\0' : instead adjust acmava.c to disallow empty vals */
1524 if ((l.nd = ok_vlook(line_editor_cursor_right)) == NULL || *l.nd == '\0')
1525 l.nd = "\033[C"; /* XXX no "magic" constant */
1526 l.x_buf = buf;
1527 l.x_bufsize = bufsize;
1529 if (prompt != NULL && *prompt != '\0') {
1530 fputs(prompt, stdout);
1531 fflush(stdout);
1533 jrestart:
1534 memset(ps, 0, sizeof ps);
1535 cursor_maybe = cursor_store = 0;
1536 /* TODO: NCL: we should output the reset sequence when we jrestart:
1537 * TODO: NCL: if we are using a stateful encoding? !
1538 * TODO: NCL: in short: this is not yet well understood */
1539 for (;;) {
1540 _ncl_check_grow(&l, len SMALLOC_DEBUG_ARGSCALL);
1542 /* Normal read(2)? Else buffer-takeover: speed this one up */
1543 if (len == 0)
1544 cbufp =
1545 cbuf = cbuf_base;
1546 else {
1547 assert(l.defc.l > 0 && l.defc.s != NULL);
1548 cbufp =
1549 cbuf = l.defc.s + (l.defc.l - len);
1550 cbufp += len;
1553 /* Read in the next complete multibyte character */
1554 for (;;) {
1555 if (len == 0) {
1556 if ((rv = read(STDIN_FILENO, cbufp, 1)) < 1) {
1557 if (errno == EINTR) /* xxx #if !SA_RESTART ? */
1558 continue;
1559 goto jleave;
1561 ++cbufp;
1564 /* Ach! the ISO C multibyte handling!
1565 * Encodings with locking shift states cannot really be helped, since
1566 * it is impossible to only query the shift state, as opposed to the
1567 * entire shift state + character pair (via ISO C functions) */
1568 rv = (ssize_t)mbrtowc(&wc, cbuf, PTR2SIZE(cbufp - cbuf), ps + 0);
1569 if (rv <= 0) {
1570 /* Any error during take-over can only result in a hard reset;
1571 * Otherwise, if it's a hard error, or if too many redundant shift
1572 * sequences overflow our buffer, also perform a hard reset */
1573 if (len != 0 || rv == -1 ||
1574 sizeof cbuf_base == PTR2SIZE(cbufp - cbuf)) {
1575 l.savec.s = l.defc.s = NULL,
1576 l.savec.l = l.defc.l = len = 0;
1577 putchar('\a');
1578 wc = 'G';
1579 goto jreset;
1581 /* Otherwise, due to the way we deal with the buffer, we need to
1582 * restore the mbstate_t from before this conversion */
1583 ps[0] = ps[1];
1584 continue;
1587 if (len != 0 && (len -= (size_t)rv) == 0)
1588 l.defc.s = NULL, l.defc.l = 0;
1589 ps[1] = ps[0];
1590 break;
1593 /* Don't interpret control bytes during buffer take-over */
1594 if (cbuf != cbuf_base)
1595 goto jprint;
1596 switch (wc) {
1597 case 'A' ^ 0x40: /* cursor home */
1598 _ncl_khome(&l, TRU1);
1599 break;
1600 case 'B' ^ 0x40: /* backward character */
1601 j_b:
1602 _ncl_kleft(&l);
1603 break;
1604 /* 'C': interrupt (CTRL-C) */
1605 case 'D' ^ 0x40: /* delete char forward if any, else EOF */
1606 if ((rv = _ncl_keof(&l)) < 0)
1607 goto jleave;
1608 break;
1609 case 'E' ^ 0x40: /* end of line */
1610 _ncl_kend(&l);
1611 break;
1612 case 'F' ^ 0x40: /* forward character */
1613 j_f:
1614 _ncl_kright(&l);
1615 break;
1616 /* 'G' below */
1617 case 'H' ^ 0x40: /* backspace */
1618 case '\177':
1619 _ncl_kbs(&l);
1620 break;
1621 case 'I' ^ 0x40: /* horizontal tab */
1622 # ifdef HAVE_TABEXPAND
1623 if ((len = _ncl_kht(&l)) > 0)
1624 goto jrestart;
1625 # endif
1626 goto jbell;
1627 case 'J' ^ 0x40: /* NL (\n) */
1628 goto jdone;
1629 case 'G' ^ 0x40: /* full reset */
1630 jreset:
1631 /* FALLTHRU */
1632 case 'U' ^ 0x40: /* ^U: ^A + ^K */
1633 _ncl_khome(&l, FAL0);
1634 /* FALLTHRU */
1635 case 'K' ^ 0x40: /* kill from cursor to end of line */
1636 _ncl_kkill(&l, (wc == ('K' ^ 0x40) || l.topins == 0));
1637 /* (Handle full reset?) */
1638 if (wc == ('G' ^ 0x40)) {
1639 # ifdef HAVE_HISTORY
1640 l.hist = NULL;
1641 # endif
1642 if ((len = l.savec.l) != 0) {
1643 l.defc = l.savec;
1644 l.savec.s = NULL, l.savec.l = 0;
1645 } else
1646 len = l.defc.l;
1648 fflush(stdout);
1649 goto jrestart;
1650 case 'L' ^ 0x40: /* repaint line */
1651 j_l:
1652 _ncl_krefresh(&l);
1653 break;
1654 /* 'M': CR (\r) */
1655 case 'N' ^ 0x40: /* history next */
1656 j_n:
1657 # ifdef HAVE_HISTORY
1658 if (l.hist == NULL)
1659 goto jbell;
1660 if ((len = _ncl_khist(&l, FAL0)) > 0)
1661 goto jrestart;
1662 wc = 'G' ^ 0x40;
1663 goto jreset;
1664 # else
1665 goto jbell;
1666 # endif
1667 /* 'O' */
1668 case 'O' ^ 0x40: /* `dp' */
1669 putchar('\n');
1670 cbuf_base[0] = 'd';
1671 cbuf_base[1] = 'p';
1672 cbuf_base[2] = '\0';
1673 inhook = 0;
1674 execute(cbuf_base, TRU1, 2);
1675 goto j_l;
1676 case 'P' ^ 0x40: /* history previous */
1677 j_p:
1678 # ifdef HAVE_HISTORY
1679 if ((len = _ncl_khist(&l, TRU1)) > 0)
1680 goto jrestart;
1681 wc = 'G' ^ 0x40;
1682 goto jreset;
1683 # else
1684 goto jbell;
1685 # endif
1686 /* 'Q': no code */
1687 case 'R' ^ 0x40: /* reverse history search */
1688 # ifdef HAVE_HISTORY
1689 if ((len = _ncl_krhist(&l)) > 0)
1690 goto jrestart;
1691 wc = 'G' ^ 0x40;
1692 goto jreset;
1693 # else
1694 goto jbell;
1695 # endif
1696 /* 'S': no code */
1697 /* 'U' above */
1698 /*case 'V' ^ 0x40: TODO*/ /* forward delete "word" */
1699 case 'W' ^ 0x40: /* backward delete "word" */
1700 _ncl_kbwddelw(&l);
1701 break;
1702 case 'X' ^ 0x40: /* move cursor forward "word" */
1703 _ncl_kgow(&l, +1);
1704 break;
1705 case 'Y' ^ 0x40: /* move cursor backward "word" */
1706 _ncl_kgow(&l, -1);
1707 break;
1708 /* 'Z': suspend (CTRL-Z) */
1709 case 0x1B:
1710 if (cursor_maybe++ != 0)
1711 goto jreset;
1712 continue;
1713 default:
1714 /* XXX Handle usual ^[[[ABCD1456] cursor keys: UGLY,"MAGIC",INFLEX */
1715 if (cursor_maybe > 0) {
1716 if (++cursor_maybe == 2) {
1717 if (wc == L'[')
1718 continue;
1719 cursor_maybe = 0;
1720 } else if (cursor_maybe == 3) {
1721 cursor_maybe = 0;
1722 switch (wc) {
1723 default: break;
1724 case L'A': goto j_p;
1725 case L'B': goto j_n;
1726 case L'C': goto j_f;
1727 case L'D': goto j_b;
1728 case L'1':
1729 case L'4':
1730 case L'5':
1731 case L'6':
1732 cursor_store = ((wc == L'1') ? '0' :
1733 (wc == L'4' ? '$' : (wc == L'5' ? '-' : '+')));
1734 cursor_maybe = 3;
1735 continue;
1737 _ncl_kother(&l, L'[');
1738 } else {
1739 cursor_maybe = 0;
1740 if (wc == L'~') {
1741 char x[2];
1742 x[0] = cursor_store;
1743 x[1] = '\0';
1744 putchar('\n');
1745 c_scroll(x);
1746 cursor_store = 0;
1747 goto j_l;
1749 _ncl_kother(&l, L'[');
1750 _ncl_kother(&l, (wchar_t)cursor_store);
1751 cursor_store = 0;
1754 jprint:
1755 if (iswprint(wc)) {
1756 _ncl_kother(&l, wc);
1757 /* Don't clear the history during takeover..
1758 * ..and also avoid fflush()ing unless we've worked entire buffer */
1759 if (len > 0)
1760 continue;
1761 # ifdef HAVE_HISTORY
1762 if (cbuf == cbuf_base)
1763 l.hist = NULL;
1764 # endif
1765 } else {
1766 jbell:
1767 putchar('\a');
1769 break;
1771 fflush(stdout);
1774 /* We have a completed input line, convert the struct cell data to its
1775 * plain character equivalent */
1776 jdone:
1777 putchar('\n');
1778 fflush(stdout);
1779 len = _ncl_cell2dat(&l);
1780 rv = (ssize_t)len;
1781 jleave:
1782 NYD_LEAVE;
1783 return rv;
1786 FL void
1787 tty_init(void)
1789 # ifdef HAVE_HISTORY
1790 long hs;
1791 char *v, *lbuf;
1792 FILE *f;
1793 size_t lsize, cnt, llen;
1794 # endif
1795 NYD_ENTER;
1797 _ncl_oint.sint = _ncl_oquit.sint = _ncl_oterm.sint =
1798 _ncl_ohup.sint = _ncl_otstp.sint = _ncl_ottin.sint =
1799 _ncl_ottou.sint = -1;
1801 # ifdef HAVE_HISTORY
1802 _CL_HISTSIZE(hs);
1803 _ncl_hist_size = 0;
1804 _ncl_hist_size_max = hs;
1805 if (hs == 0)
1806 goto jleave;
1808 _CL_HISTFILE(v);
1809 if (v == NULL)
1810 goto jleave;
1812 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
1813 f = fopen(v, "r"); /* TODO HISTFILE LOAD: use linebuf pool */
1814 if (f == NULL)
1815 goto jdone;
1816 fcntl_lock(fileno(f), FLOCK_READ); /* TODO ouch, retval check, etc. */
1818 lbuf = NULL;
1819 lsize = 0;
1820 cnt = fsize(f);
1821 while (fgetline(&lbuf, &lsize, &cnt, &llen, f, FAL0) != NULL) {
1822 if (llen > 0 && lbuf[llen - 1] == '\n')
1823 lbuf[--llen] = '\0';
1824 if (llen == 0 || lbuf[0] == '#') /* xxx comments? noone! */
1825 continue;
1826 _ncl_hist_load = TRU1;
1827 tty_addhist(lbuf);
1828 _ncl_hist_load = FAL0;
1830 if (lbuf != NULL)
1831 free(lbuf);
1833 fclose(f);
1834 jdone:
1835 rele_all_sigs(); /* XXX remove jumps */
1836 jleave:
1837 # endif /* HAVE_HISTORY */
1838 NYD_LEAVE;
1841 FL void
1842 tty_destroy(void)
1844 # ifdef HAVE_HISTORY
1845 long hs;
1846 char *v;
1847 struct hist *hp;
1848 FILE *f;
1849 # endif
1850 NYD_ENTER;
1852 # ifdef HAVE_HISTORY
1853 _CL_HISTSIZE(hs);
1854 if (hs == 0)
1855 goto jleave;
1857 _CL_HISTFILE(v);
1858 if (v == NULL)
1859 goto jleave;
1861 if ((hp = _ncl_hist) != NULL)
1862 while (hp->older != NULL && hs-- != 0)
1863 hp = hp->older;
1865 hold_all_sigs(); /* TODO too heavy, yet we may jump even here!? */
1866 f = fopen(v, "w"); /* TODO temporary + rename?! */
1867 if (f == NULL)
1868 goto jdone;
1869 fcntl_lock(fileno(f), FLOCK_WRITE); /* TODO ouch, retval check, etc. */
1870 if (fchmod(fileno(f), S_IRUSR | S_IWUSR) != 0)
1871 goto jclose;
1873 for (; hp != NULL; hp = hp->younger) {
1874 fwrite(hp->dat, sizeof *hp->dat, hp->len, f);
1875 putc('\n', f);
1877 jclose:
1878 fclose(f);
1879 jdone:
1880 rele_all_sigs(); /* XXX remove jumps */
1881 jleave:
1882 # endif /* HAVE_HISTORY */
1883 NYD_LEAVE;
1886 FL void
1887 tty_signal(int sig)
1889 sigset_t nset, oset;
1890 NYD_X; /* Signal handler */
1892 switch (sig) {
1893 case SIGWINCH:
1894 /* We don't deal with SIGWINCH, yet get called from main.c */
1895 break;
1896 default:
1897 _ncl_term_mode(FAL0);
1898 _ncl_sigs_down();
1899 sigemptyset(&nset);
1900 sigaddset(&nset, sig);
1901 sigprocmask(SIG_UNBLOCK, &nset, &oset);
1902 kill(0, sig);
1903 /* When we come here we'll continue editing, so reestablish */
1904 sigprocmask(SIG_BLOCK, &oset, (sigset_t*)NULL);
1905 _ncl_sigs_up();
1906 _ncl_term_mode(TRU1);
1907 break;
1911 FL int
1912 (tty_readline)(char const *prompt, char **linebuf, size_t *linesize, size_t n
1913 SMALLOC_DEBUG_ARGS)
1915 ssize_t nn;
1916 NYD_ENTER;
1918 /* Of course we have races here, but they cannot be avoided on POSIX
1919 * (except by even *more* actions) */
1920 _ncl_sigs_up();
1921 _ncl_term_mode(TRU1);
1922 nn = _ncl_readline(prompt, linebuf, linesize, n SMALLOC_DEBUG_ARGSCALL);
1923 _ncl_term_mode(FAL0);
1924 _ncl_sigs_down();
1925 NYD_LEAVE;
1926 return (int)nn;
1929 FL void
1930 tty_addhist(char const *s)
1932 # ifdef HAVE_HISTORY
1933 /* Super-Heavy-Metal: block all sigs, avoid leaks+ on jump */
1934 size_t l;
1935 struct hist *h, *o, *y;
1936 # endif
1937 NYD_ENTER;
1938 UNUSED(s);
1940 # ifdef HAVE_HISTORY
1941 l = strlen(s);
1943 if (_ncl_hist_size_max == 0)
1944 goto j_leave;
1945 _CL_CHECK_ADDHIST(s, goto j_leave);
1947 /* Eliminating duplicates is expensive, but simply inacceptable so
1948 * during the load of a potentially large history file! */
1949 if (!_ncl_hist_load)
1950 for (h = _ncl_hist; h != NULL; h = h->older)
1951 if (h->len == l && !strcmp(h->dat, s)) {
1952 hold_all_sigs(); /* TODO */
1953 o = h->older;
1954 y = h->younger;
1955 if (o != NULL)
1956 o->younger = y;
1957 else
1958 _ncl_hist_tail = y;
1959 if (y != NULL)
1960 y->older = o;
1961 else
1962 _ncl_hist = o;
1963 goto jleave;
1965 hold_all_sigs();
1967 ++_ncl_hist_size;
1968 if (!_ncl_hist_load && _ncl_hist_size > _ncl_hist_size_max) {
1969 --_ncl_hist_size;
1970 if ((h = _ncl_hist_tail) != NULL) {
1971 if ((_ncl_hist_tail = h->younger) == NULL)
1972 _ncl_hist = NULL;
1973 else
1974 _ncl_hist_tail->older = NULL;
1975 free(h);
1979 h = smalloc((sizeof(struct hist) - VFIELD_SIZEOF(struct hist, dat)) + l +1);
1980 h->len = l;
1981 memcpy(h->dat, s, l +1);
1982 jleave:
1983 if ((h->older = _ncl_hist) != NULL)
1984 _ncl_hist->younger = h;
1985 else
1986 _ncl_hist_tail = h;
1987 h->younger = NULL;
1988 _ncl_hist = h;
1990 rele_all_sigs();
1991 j_leave:
1992 # endif
1993 NYD_LEAVE;
1996 # ifdef HAVE_HISTORY
1997 FL int
1998 c_history(void *v)
2000 C_HISTORY_SHARED;
2002 jlist: {
2003 FILE *fp;
2004 size_t i, b;
2005 struct hist *h;
2007 if (_ncl_hist == NULL)
2008 goto jleave;
2010 if ((fp = Ftmp(NULL, "hist", OF_RDWR | OF_UNLINK | OF_REGISTER, 0600)) ==
2011 NULL) {
2012 perror("tmpfile");
2013 v = NULL;
2014 goto jleave;
2017 i = _ncl_hist_size;
2018 b = 0;
2019 for (h = _ncl_hist; h != NULL; --i, b += h->len, h = h->older)
2020 fprintf(fp, "%4lu. %-50.50s (%4lu+%2lu bytes)\n",
2021 (ul_it)i, h->dat, (ul_it)b, (ul_it)h->len);
2023 page_or_print(fp, i);
2024 Fclose(fp);
2026 goto jleave;
2028 jclear: {
2029 struct hist *h;
2030 while ((h = _ncl_hist) != NULL) {
2031 _ncl_hist = h->older;
2032 free(h);
2034 _ncl_hist_tail = NULL;
2035 _ncl_hist_size = 0;
2037 goto jleave;
2039 jentry: {
2040 struct hist *h = _ncl_hist;
2041 if (UICMP(z, entry, <=, _ncl_hist_size)) {
2042 entry = (long)_ncl_hist_size - entry;
2043 for (h = _ncl_hist;; h = h->older)
2044 if (h == NULL)
2045 break;
2046 else if (entry-- != 0)
2047 continue;
2048 else {
2049 v = temporary_arg_v_store = h->dat;
2050 goto jleave;
2053 v = NULL;
2055 goto jleave;
2057 # endif /* HAVE_HISTORY */
2058 #endif /* HAVE_NCL */
2061 * The really-nothing-at-all implementation
2064 #if !defined HAVE_READLINE && !defined HAVE_EDITLINE && !defined HAVE_NCL
2065 FL void
2066 tty_init(void)
2068 NYD_ENTER;
2069 NYD_LEAVE;
2072 FL void
2073 tty_destroy(void)
2075 NYD_ENTER;
2076 NYD_LEAVE;
2079 FL void
2080 tty_signal(int sig)
2082 NYD_X; /* Signal handler */
2083 UNUSED(sig);
2086 FL int
2087 (tty_readline)(char const *prompt, char **linebuf, size_t *linesize, size_t n
2088 SMALLOC_DEBUG_ARGS)
2090 /* TODO The nothing-at-all tty layer even forces re-entering all the
2091 * TODO original data when re-editing a field */
2092 bool_t doffl = FAL0;
2093 int rv;
2094 NYD_ENTER;
2096 if (prompt != NULL && *prompt != '\0') {
2097 fputs(prompt, stdout);
2098 doffl = TRU1;
2100 if (n > 0) {
2101 fprintf(stdout, tr(511, "{former content: %.*s} "), (int)n, *linebuf);
2102 n = 0;
2103 doffl = TRU1;
2105 if (doffl)
2106 fflush(stdout);
2107 rv = (readline_restart)(stdin, linebuf, linesize,n SMALLOC_DEBUG_ARGSCALL);
2108 NYD_LEAVE;
2109 return rv;
2112 FL void
2113 tty_addhist(char const *s)
2115 NYD_ENTER;
2116 UNUSED(s);
2117 NYD_LEAVE;
2119 #endif /* nothing at all */
2121 /* vim:set fenc=utf-8:s-it-mode */