1 /****************************************************************************
2 * Copyright 2018-2019,2020 Thomas E. Dickey *
3 * Copyright 1998-2016,2017 Free Software Foundation, Inc. *
5 * Permission is hereby granted, free of charge, to any person obtaining a *
6 * copy of this software and associated documentation files (the *
7 * "Software"), to deal in the Software without restriction, including *
8 * without limitation the rights to use, copy, modify, merge, publish, *
9 * distribute, distribute with modifications, sublicense, and/or sell *
10 * copies of the Software, and to permit persons to whom the Software is *
11 * furnished to do so, subject to the following conditions: *
13 * The above copyright notice and this permission notice shall be included *
14 * in all copies or substantial portions of the Software. *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS *
17 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *
18 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. *
19 * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, *
20 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR *
21 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR *
22 * THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
24 * Except as contained in this notice, the name(s) of the above copyright *
25 * holders shall not be used in advertising or otherwise to promote the *
26 * sale, use or other dealings in this Software without prior written *
28 ****************************************************************************/
30 /****************************************************************************
31 * Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995 *
32 * and: Eric S. Raymond <esr@snark.thyrsus.com> *
33 * and: Thomas E. Dickey, 1996 on *
34 ****************************************************************************/
41 #define entry _ncu_entry
42 #define ENTRY _ncu_ENTRY
44 #include <curses.priv.h>
56 MODULE_ID("$Id: lib_tparm.c,v 1.128 2020/10/10 21:18:09 tom Exp $")
62 * Substitute the given parameters into the given string by the following
63 * rules (taken from terminfo(5)):
65 * Cursor addressing and other strings requiring parame-
66 * ters in the terminal are described by a parameterized string
67 * capability, with escapes like %x in it. For example, to
68 * address the cursor, the cup capability is given, using two
69 * parameters: the row and column to address to. (Rows and
70 * columns are numbered from zero and refer to the physical
71 * screen visible to the user, not to any unseen memory.) If
72 * the terminal has memory relative cursor addressing, that can
75 * The parameter mechanism uses a stack and special %
76 * codes to manipulate it. Typically a sequence will push one
77 * of the parameters onto the stack and then print it in some
78 * format. Often more complex operations are necessary.
80 * The % encodings have the following meanings:
83 * %c print pop() like %c in printf()
84 * %s print pop() like %s in printf()
85 * %[[:]flags][width[.precision]][doxXs]
86 * as in printf, flags are [-+#] and space
87 * The ':' is used to avoid making %+ or %-
88 * patterns (see below).
90 * %p[1-9] push ith parm
91 * %P[a-z] set dynamic variable [a-z] to pop()
92 * %g[a-z] get dynamic variable [a-z] and push it
93 * %P[A-Z] set static variable [A-Z] to pop()
94 * %g[A-Z] get static variable [A-Z] and push it
96 * %'c' push char constant c
97 * %{nn} push integer constant nn
100 * arithmetic (%m is mod): push(pop() op pop())
101 * %& %| %^ bit operations: push(pop() op pop())
102 * %= %> %< logical operations: push(pop() op pop())
103 * %A %O logical and & or operations for conditionals
104 * %! %~ unary operations push(op pop())
105 * %i add 1 to first two parms (for ANSI terminals)
107 * %? expr %t thenpart %e elsepart %;
108 * if-then-else, %e elsepart is optional.
109 * else-if's are possible ala Algol 68:
110 * %? c1 %t b1 %e c2 %t b2 %e c3 %t b3 %e c4 %t b4 %e b5 %;
112 * For those of the above operators which are binary and not commutative,
113 * the stack works in the usual way, with
115 * resulting in x mod y, not the reverse.
118 NCURSES_EXPORT_VAR(int) _nc_tparm_err = 0;
120 #define TPS(var) _nc_prescreen.tparm_state.var
121 #define popcount _nc_popcount /* workaround for NetBSD 6.0 defect */
123 #define isUPPER(c) ((c) >= 'A' && (c) <= 'Z')
124 #define isLOWER(c) ((c) >= 'a' && (c) <= 'z')
125 #define tc_BUMP() if (level < 0 && number < 2) number++
128 const char *format; /* format-string can be used as cache-key */
129 int tparm_type; /* bit-set for each string-parameter */
133 TPARM_ARG param[NUM_PARM];
134 char *p_is_s[NUM_PARM];
138 #define MyCache _nc_globals.cached_tparm
139 #define MyCount _nc_globals.count_tparm
141 static int which_tparm;
142 static TPARM_DATA **delete_tparm;
144 #endif /* HAVE_TSEARCH */
146 static char dummy[] = ""; /* avoid const-cast */
150 cmp_format(const void *p, const void *q)
152 const char *a = *(char *const *) p;
153 const char *b = *(char *const *) q;
161 visit_nodes(const void *nodep, const VISIT which, const int depth)
164 if (which == preorder || which == leaf) {
165 delete_tparm[which_tparm] = *(TPARM_DATA **) nodep;
176 delete_tparm = typeMalloc(TPARM_DATA *, MyCount);
178 twalk(MyCache, visit_nodes);
179 for (which_tparm = 0; which_tparm < MyCount; ++which_tparm) {
180 TPARM_DATA *ptr = delete_tparm[which_tparm];
181 tdelete(ptr, &MyCache, cmp_format);
182 free((char *) ptr->format);
186 twalk(MyCache, visit_nodes);
187 FreeAndNull(delete_tparm);
192 FreeAndNull(TPS(out_buff));
196 FreeAndNull(TPS(fmt_buff));
201 static NCURSES_INLINE void
202 get_space(size_t need)
204 need += TPS(out_used);
205 if (need > TPS(out_size)) {
206 TPS(out_size) = need * 2;
207 TYPE_REALLOC(char, TPS(out_size), TPS(out_buff));
211 static NCURSES_INLINE void
212 save_text(const char *fmt, const char *s, int len)
214 size_t s_len = (size_t) len + strlen(s) + strlen(fmt);
215 get_space(s_len + 1);
217 _nc_SPRINTF(TPS(out_buff) + TPS(out_used),
218 _nc_SLIMIT(TPS(out_size) - TPS(out_used))
220 TPS(out_used) += strlen(TPS(out_buff) + TPS(out_used));
223 static NCURSES_INLINE void
224 save_number(const char *fmt, int number, int len)
226 size_t s_len = (size_t) len + 30 + strlen(fmt);
227 get_space(s_len + 1);
229 _nc_SPRINTF(TPS(out_buff) + TPS(out_used),
230 _nc_SLIMIT(TPS(out_size) - TPS(out_used))
232 TPS(out_used) += strlen(TPS(out_buff) + TPS(out_used));
235 static NCURSES_INLINE void
240 get_space((size_t) 1);
241 TPS(out_buff)[TPS(out_used)++] = (char) c;
244 static NCURSES_INLINE void
247 if (TPS(stack_ptr) < STACKSIZE) {
248 TPS(stack)[TPS(stack_ptr)].num_type = TRUE;
249 TPS(stack)[TPS(stack_ptr)].data.num = x;
252 DEBUG(2, ("npush: stack overflow: %s", _nc_visbuf(TPS(tparam_base))));
257 static NCURSES_INLINE int
261 if (TPS(stack_ptr) > 0) {
263 if (TPS(stack)[TPS(stack_ptr)].num_type)
264 result = TPS(stack)[TPS(stack_ptr)].data.num;
266 DEBUG(2, ("npop: stack underflow: %s", _nc_visbuf(TPS(tparam_base))));
272 static NCURSES_INLINE void
275 if (TPS(stack_ptr) < STACKSIZE) {
276 TPS(stack)[TPS(stack_ptr)].num_type = FALSE;
277 TPS(stack)[TPS(stack_ptr)].data.str = x;
280 DEBUG(2, ("spush: stack overflow: %s", _nc_visbuf(TPS(tparam_base))));
285 static NCURSES_INLINE char *
288 char *result = dummy;
289 if (TPS(stack_ptr) > 0) {
291 if (!TPS(stack)[TPS(stack_ptr)].num_type
292 && TPS(stack)[TPS(stack_ptr)].data.str != 0)
293 result = TPS(stack)[TPS(stack_ptr)].data.str;
295 DEBUG(2, ("spop: stack underflow: %s", _nc_visbuf(TPS(tparam_base))));
301 static NCURSES_INLINE const char *
302 parse_format(const char *s, char *format, int *len)
307 bool allowminus = FALSE;
317 while (*s != '\0' && !done) {
319 case 'c': /* FALLTHRU */
320 case 'd': /* FALLTHRU */
321 case 'o': /* FALLTHRU */
322 case 'x': /* FALLTHRU */
323 case 'X': /* FALLTHRU */
325 #ifdef EXP_XTERM_1005
335 } else { /* value before '.' is the width */
359 if (isdigit(UChar(*s))) {
360 value = (value * 10) + (*s - '0');
371 * If we found an error, ignore (and remove) the flags.
374 my_width = my_prec = value = 0;
381 * Any value after '.' is the precision. If we did not see '.', then
382 * the value is the width.
390 /* return maximum string length in print */
391 *len = (my_width > my_prec) ? my_width : my_prec;
397 * Analyze the string to see how many parameters we need from the varargs list,
398 * and what their types are. We will only accept string parameters if they
399 * appear as a %l or %s format following an explicit parameter reference (e.g.,
400 * %p2%s). All other parameters are numbers.
402 * 'number' counts coarsely the number of pop's we see in the string, and
403 * 'popcount' shows the highest parameter number in the string. We would like
404 * to simply use the latter count, but if we are reading termcap strings, there
405 * may be cases that we cannot see the explicit parameter numbers.
408 _nc_tparm_analyze(const char *string, char *p_is_s[NUM_PARM], int *popcount)
416 const char *cp = string;
421 if ((len2 = strlen(cp)) + 2 > TPS(fmt_size)) {
422 TPS(fmt_size) += len2 + 2;
423 TPS(fmt_buff) = typeRealloc(char, TPS(fmt_size), TPS(fmt_buff));
424 if (TPS(fmt_buff) == 0)
428 memset(p_is_s, 0, sizeof(p_is_s[0]) * NUM_PARM);
431 while ((cp - string) < (int) len2) {
434 cp = parse_format(cp, TPS(fmt_buff), &len);
439 case 'd': /* FALLTHRU */
440 case 'o': /* FALLTHRU */
441 case 'x': /* FALLTHRU */
442 case 'X': /* FALLTHRU */
443 case 'c': /* FALLTHRU */
444 #ifdef EXP_XTERM_1005
458 p_is_s[lastpop - 1] = dummy;
465 i = (UChar(*cp) - '0');
466 if (i >= 0 && i <= NUM_PARM) {
469 if (lastpop > *popcount)
492 while (isdigit(UChar(*cp))) {
511 level -= 1; /* pop 2, operate, push 1 */
522 /* will add 1 to first (usually two) parameters */
530 if (number > NUM_PARM)
536 * Analyze the capability string, finding the number of parameters and their
539 * TODO: cache the result so that this is done once per capability per term.
542 tparm_setup(const char *string, TPARM_DATA * result)
547 memset(result, 0, sizeof(*result));
549 if (string == NULL) {
550 TR(TRACE_CALLS, ("%s: format is null", TPS(tname)));
557 result->format = string;
558 if ((ft = tfind(result, &MyCache, cmp_format)) != 0) {
559 fs = *(TPARM_DATA **) ft;
565 * Find the highest parameter-number referred to in the format
566 * string. Use this value to limit the number of arguments copied
567 * from the variable-length argument list.
569 result->num_parsed = _nc_tparm_analyze(string,
571 &(result->num_popped));
572 if (TPS(fmt_buff) == 0) {
573 TR(TRACE_CALLS, ("%s: error in analysis", TPS(tname)));
578 if (result->num_parsed > NUM_PARM)
579 result->num_parsed = NUM_PARM;
580 if (result->num_popped > NUM_PARM)
581 result->num_popped = NUM_PARM;
582 result->num_actual = max(result->num_popped, result->num_parsed);
584 for (n = 0; n < result->num_actual; ++n) {
585 if (result->p_is_s[n])
586 result->tparm_type |= (1 << n);
589 if ((fs = typeCalloc(TPARM_DATA, 1)) != 0) {
591 if ((fs->format = strdup(string)) != 0) {
592 if ((ft = tsearch(fs, &MyCache, cmp_format)) != 0) {
612 * A few caps (such as plab_norm) have string-valued parms. We'll have to
613 * assume that the caller knows the difference, since a char* and an int may
614 * not be the same size on the stack. The normal prototype for tparm uses 9
615 * long's, which is consistent with our va_arg() usage.
618 tparm_copy_valist(TPARM_DATA * data, int use_TPARM_ARG, va_list ap)
622 for (i = 0; i < data->num_actual; i++) {
623 if (data->p_is_s[i] != 0) {
624 char *value = va_arg(ap, char *);
627 data->p_is_s[i] = value;
629 } else if (use_TPARM_ARG) {
630 data->param[i] = va_arg(ap, TPARM_ARG);
632 data->param[i] = (TPARM_ARG) va_arg(ap, int);
638 * This is a termcap compatibility hack. If there are no explicit pop
639 * operations in the string, load the stack in such a way that successive pops
640 * will grab successive parameters. That will make the expansion of (for
641 * example) \E[%d;%dH work correctly in termcap style, which means tparam()
642 * will expand termcap strings OK.
645 tparm_tc_compat(TPARM_DATA * data)
647 bool termcap_hack = FALSE;
651 if (data->num_popped == 0) {
655 for (i = data->num_parsed - 1; i >= 0; i--) {
657 spush(data->p_is_s[i]);
659 npush((int) data->param[i]);
667 tparm_trace_call(const char *string, TPARM_DATA * data)
669 if (USE_TRACEF(TRACE_CALLS)) {
671 for (i = 0; i < data->num_actual; i++) {
672 if (data->p_is_s[i] != 0) {
673 save_text(", %s", _nc_visbuf(data->p_is_s[i]), 0);
674 } else if ((long) data->param[i] > MAX_OF_TYPE(NCURSES_INT2) ||
675 (long) data->param[i] < 0) {
676 _tracef("BUG: problem with tparm parameter #%d of %d",
677 i + 1, data->num_actual);
680 save_number(", %d", (int) data->param[i], 0);
683 _tracef(T_CALLED("%s(%s%s)"), TPS(tname), _nc_visbuf(string), TPS(out_buff));
685 _nc_unlock_global(tracef);
690 #define tparm_trace_call(string, data) /* nothing */
693 static NCURSES_INLINE char *
694 tparam_internal(const char *string, TPARM_DATA * data)
701 const char *cp = string;
702 size_t len2 = strlen(cp);
703 bool incremented_two = FALSE;
704 bool termcap_hack = tparm_tc_compat(data);
706 tparm_trace_call(string, data);
708 while ((cp - string) < (int) len2) {
710 save_char(UChar(*cp));
712 TPS(tparam_base) = cp++;
713 cp = parse_format(cp, TPS(fmt_buff), &len);
721 case 'd': /* FALLTHRU */
722 case 'o': /* FALLTHRU */
723 case 'x': /* FALLTHRU */
724 case 'X': /* FALLTHRU */
725 save_number(TPS(fmt_buff), npop(), len);
728 case 'c': /* FALLTHRU */
732 #ifdef EXP_XTERM_1005
735 unsigned char target[10];
736 unsigned source = (unsigned) npop();
737 int rc = _nc_conv_to_utf8(target, source, (unsigned)
740 for (n = 0; n < rc; ++n) {
741 save_char(target[n]);
747 npush((int) strlen(spop()));
751 save_text(TPS(fmt_buff), spop(), len);
756 i = (UChar(*cp) - '1');
757 if (i >= 0 && i < NUM_PARM) {
758 if (data->p_is_s[i]) {
759 spush(data->p_is_s[i]);
761 npush((int) data->param[i]);
769 i = (UChar(*cp) - 'A');
770 TPS(static_vars)[i] = npop();
771 } else if (isLOWER(*cp)) {
772 i = (UChar(*cp) - 'a');
773 TPS(dynamic_var)[i] = npop();
780 i = (UChar(*cp) - 'A');
781 npush(TPS(static_vars)[i]);
782 } else if (isLOWER(*cp)) {
783 i = (UChar(*cp) - 'a');
784 npush(TPS(dynamic_var)[i]);
797 while (isdigit(UChar(*cp))) {
798 number = (number * 10) + (UChar(*cp) - '0');
805 npush(npop() + npop());
815 npush(npop() * npop());
821 npush(y ? (x / y) : 0);
827 npush(y ? (x % y) : 0);
843 npush(npop() & npop());
847 npush(npop() | npop());
851 npush(npop() ^ npop());
882 * Increment the first two parameters -- if they are numbers
883 * rather than strings. As a side effect, assign into the
884 * stack; if this is termcap, then the stack was populated
885 * using the termcap hack above rather than via the terminfo
888 if (!incremented_two) {
889 incremented_two = TRUE;
890 if (data->p_is_s[0] == 0) {
893 TPS(stack)[0].data.num = (int) data->param[0];
895 if (data->p_is_s[1] == 0) {
898 TPS(stack)[1].data.num = (int) data->param[1];
909 /* scan forward for %e or %; at level zero */
917 else if (*cp == ';') {
922 } else if (*cp == 'e' && level == 0)
933 /* scan forward for a %; at level zero */
941 else if (*cp == ';') {
957 } /* endswitch (*cp) */
958 } /* endelse (*cp == '%') */
964 } /* endwhile (*cp) */
966 get_space((size_t) 1);
967 TPS(out_buff)[TPS(out_used)] = '\0';
969 if (TPS(stack_ptr) && !_nc_tparm_err) {
970 DEBUG(2, ("tparm: stack has %d item%s on return",
972 TPS(stack_ptr) == 1 ? "" : "s"));
976 T((T_RETURN("%s"), _nc_visbuf(TPS(out_buff))));
977 return (TPS(out_buff));
980 #if NCURSES_TPARM_VARARGS
982 NCURSES_EXPORT(char *)
983 tparm(const char *string, ...)
991 TPS(tname) = "tparm";
994 if (tparm_setup(string, &myData) == OK) {
996 va_start(ap, string);
997 tparm_copy_valist(&myData, TRUE, ap);
1000 result = tparam_internal(string, &myData);
1005 #else /* !NCURSES_TPARM_VARARGS */
1007 NCURSES_EXPORT(char *)
1008 tparm(const char *string,
1020 char *result = NULL;
1024 TPS(tname) = "tparm";
1027 if (tparm_setup(string, &myData) == OK) {
1029 myData.param[0] = a1;
1030 myData.param[1] = a2;
1031 myData.param[2] = a3;
1032 myData.param[3] = a4;
1033 myData.param[4] = a5;
1034 myData.param[5] = a6;
1035 myData.param[6] = a7;
1036 myData.param[7] = a8;
1037 myData.param[8] = a9;
1039 result = tparam_internal(string, &myData);
1044 #endif /* NCURSES_TPARM_VARARGS */
1046 NCURSES_EXPORT(char *)
1047 tiparm(const char *string, ...)
1051 char *result = NULL;
1055 TPS(tname) = "tiparm";
1058 if (tparm_setup(string, &myData) == OK) {
1060 va_start(ap, string);
1061 tparm_copy_valist(&myData, FALSE, ap);
1064 result = tparam_internal(string, &myData);
1070 * The internal-use flavor ensures that the parameters are numbers, not strings
1072 NCURSES_EXPORT(char *)
1073 _nc_tiparm(int expected, const char *string, ...)
1077 char *result = NULL;
1081 TPS(tname) = "_nc_tiparm";
1084 if (tparm_setup(string, &myData) == OK
1085 && myData.num_actual <= expected
1086 && myData.tparm_type == 0) {
1088 va_start(ap, string);
1089 tparm_copy_valist(&myData, FALSE, ap);
1092 result = tparam_internal(string, &myData);