1 /****************************************************************************
2 * Copyright 2018-2020,2021 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.134 2021/08/21 21:52:08 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) tps->var
121 #define popcount _nc_popcount /* workaround for NetBSD 6.0 defect */
123 #define get_tparm_state(term) \
125 ? &(term->tparm_state) \
126 : &(_nc_prescreen.tparm_state))
128 #define isUPPER(c) ((c) >= 'A' && (c) <= 'Z')
129 #define isLOWER(c) ((c) >= 'a' && (c) <= 'z')
130 #define tc_BUMP() if (level < 0 && number < 2) number++
133 const char *format; /* format-string can be used as cache-key */
134 int tparm_type; /* bit-set for each string-parameter */
138 TPARM_ARG param[NUM_PARM];
139 char *p_is_s[NUM_PARM];
143 #define MyCache _nc_globals.cached_tparm
144 #define MyCount _nc_globals.count_tparm
146 static int which_tparm;
147 static TPARM_DATA **delete_tparm;
149 #endif /* HAVE_TSEARCH */
151 static char dummy[] = ""; /* avoid const-cast */
155 cmp_format(const void *p, const void *q)
157 const char *a = *(char *const *) p;
158 const char *b = *(char *const *) q;
166 visit_nodes(const void *nodep, const VISIT which, const int depth)
169 if (which == preorder || which == leaf) {
170 delete_tparm[which_tparm] = *(TPARM_DATA **) nodep;
179 TPARM_STATE *tps = get_tparm_state(cur_term); /* FIXME */
182 delete_tparm = typeCalloc(TPARM_DATA *, MyCount);
184 twalk(MyCache, visit_nodes);
185 for (which_tparm = 0; which_tparm < MyCount; ++which_tparm) {
186 TPARM_DATA *ptr = delete_tparm[which_tparm];
188 tdelete(ptr, &MyCache, cmp_format);
189 free((char *) ptr->format);
194 twalk(MyCache, visit_nodes);
195 FreeAndNull(delete_tparm);
200 FreeAndNull(TPS(out_buff));
204 FreeAndNull(TPS(fmt_buff));
210 tparm_error(TPARM_STATE *tps, const char *message)
212 DEBUG(2, ("%s: %s", message, _nc_visbuf(TPS(tparam_base))));
213 return ++_nc_tparm_err;
216 #define get_space(tps, need) \
218 size_t need2get = need + TPS(out_used); \
219 if (need2get > TPS(out_size)) { \
220 TPS(out_size) = need2get * 2; \
221 TYPE_REALLOC(char, TPS(out_size), TPS(out_buff)); \
226 static NCURSES_INLINE void
227 (get_space) (TPARM_STATE *tps, size_t need) {
228 get_space(tps, need);
234 #define save_text(tps, fmt, s, len) \
236 size_t s_len = (size_t) len + strlen(s) + strlen(fmt); \
237 get_space(tps, s_len + 1); \
238 _nc_SPRINTF(TPS(out_buff) + TPS(out_used), \
239 _nc_SLIMIT(TPS(out_size) - TPS(out_used)) \
241 TPS(out_used) += strlen(TPS(out_buff) + TPS(out_used)); \
245 static NCURSES_INLINE void
246 (save_text) (TPARM_STATE *tps, const char *fmt, const char *s, int len) {
247 save_text(tps, fmt, s, len);
253 #define save_number(tps, fmt, number, len) \
255 size_t s_len = (size_t) len + 30 + strlen(fmt); \
256 get_space(tps, s_len + 1); \
257 _nc_SPRINTF(TPS(out_buff) + TPS(out_used), \
258 _nc_SLIMIT(TPS(out_size) - TPS(out_used)) \
260 TPS(out_used) += strlen(TPS(out_buff) + TPS(out_used)); \
264 static NCURSES_INLINE void
265 (save_number) (TPARM_STATE *tps, const char *fmt, int number, int len) {
266 save_number(tps, fmt, number, len);
272 #define save_char(tps, c) \
274 get_space(tps, (size_t) 1); \
275 TPS(out_buff)[TPS(out_used)++] = (char) ((c == 0) ? 0200 : c); \
279 static NCURSES_INLINE void
280 (save_char) (TPARM_STATE *tps, int c) {
287 #define npush(tps, x) \
289 if (TPS(stack_ptr) < STACKSIZE) { \
290 TPS(stack)[TPS(stack_ptr)].num_type = TRUE; \
291 TPS(stack)[TPS(stack_ptr)].data.num = x; \
294 (void) tparm_error(tps, "npush: stack overflow"); \
299 static NCURSES_INLINE void
300 (npush) (TPARM_STATE *tps, int x) {
307 #define spush(tps, x) \
309 if (TPS(stack_ptr) < STACKSIZE) { \
310 TPS(stack)[TPS(stack_ptr)].num_type = FALSE; \
311 TPS(stack)[TPS(stack_ptr)].data.str = x; \
314 (void) tparm_error(tps, "spush: stack overflow"); \
319 static NCURSES_INLINE void
320 (spush) (TPARM_STATE *tps, char *x) {
328 ((TPS(stack_ptr)-- > 0) \
329 ? ((TPS(stack)[TPS(stack_ptr)].num_type) \
330 ? TPS(stack)[TPS(stack_ptr)].data.num \
332 : (tparm_error(tps, "npop: stack underflow"), \
336 static NCURSES_INLINE int
337 (npop) (TPARM_STATE *tps) {
344 ((TPS(stack_ptr)-- > 0) \
345 ? ((!TPS(stack)[TPS(stack_ptr)].num_type \
346 && TPS(stack)[TPS(stack_ptr)].data.str != 0) \
347 ? TPS(stack)[TPS(stack_ptr)].data.str \
349 : (tparm_error(tps, "spop: stack underflow"), \
353 static NCURSES_INLINE char *
354 (spop) (TPARM_STATE *tps) {
360 static NCURSES_INLINE const char *
361 parse_format(const char *s, char *format, int *len)
366 bool allowminus = FALSE;
376 while (*s != '\0' && !done) {
378 case 'c': /* FALLTHRU */
379 case 'd': /* FALLTHRU */
380 case 'o': /* FALLTHRU */
381 case 'x': /* FALLTHRU */
382 case 'X': /* FALLTHRU */
384 #ifdef EXP_XTERM_1005
394 } else { /* value before '.' is the width */
418 if (isdigit(UChar(*s))) {
419 value = (value * 10) + (*s - '0');
430 * If we found an error, ignore (and remove) the flags.
433 my_width = my_prec = value = 0;
440 * Any value after '.' is the precision. If we did not see '.', then
441 * the value is the width.
449 /* return maximum string length in print */
450 *len = (my_width > my_prec) ? my_width : my_prec;
456 * Analyze the string to see how many parameters we need from the varargs list,
457 * and what their types are. We will only accept string parameters if they
458 * appear as a %l or %s format following an explicit parameter reference (e.g.,
459 * %p2%s). All other parameters are numbers.
461 * 'number' counts coarsely the number of pop's we see in the string, and
462 * 'popcount' shows the highest parameter number in the string. We would like
463 * to simply use the latter count, but if we are reading termcap strings, there
464 * may be cases that we cannot see the explicit parameter numbers.
467 _nc_tparm_analyze(TERMINAL *term, const char *string, char **p_is_s, int *popcount)
469 TPARM_STATE *tps = get_tparm_state(term);
476 const char *cp = string;
481 if ((len2 = strlen(cp)) + 2 > TPS(fmt_size)) {
482 TPS(fmt_size) += len2 + 2;
483 TPS(fmt_buff) = typeRealloc(char, TPS(fmt_size), TPS(fmt_buff));
484 if (TPS(fmt_buff) == 0)
488 memset(p_is_s, 0, sizeof(p_is_s[0]) * NUM_PARM);
491 while ((cp - string) < (int) len2) {
494 cp = parse_format(cp, TPS(fmt_buff), &len);
499 case 'd': /* FALLTHRU */
500 case 'o': /* FALLTHRU */
501 case 'x': /* FALLTHRU */
502 case 'X': /* FALLTHRU */
503 case 'c': /* FALLTHRU */
504 #ifdef EXP_XTERM_1005
518 p_is_s[lastpop - 1] = dummy;
525 i = (UChar(*cp) - '0');
526 if (i >= 0 && i <= NUM_PARM) {
529 if (lastpop > *popcount)
552 while (isdigit(UChar(*cp))) {
571 level -= 1; /* pop 2, operate, push 1 */
582 /* will add 1 to first (usually two) parameters */
590 if (number > NUM_PARM)
596 * Analyze the capability string, finding the number of parameters and their
599 * TODO: cache the result so that this is done once per capability per term.
602 tparm_setup(TERMINAL *term, const char *string, TPARM_DATA *result)
604 TPARM_STATE *tps = get_tparm_state(term);
608 memset(result, 0, sizeof(*result));
610 if (string == NULL) {
611 TR(TRACE_CALLS, ("%s: format is null", TPS(tname)));
618 result->format = string;
619 if ((ft = tfind(result, &MyCache, cmp_format)) != 0) {
621 fs = *(TPARM_DATA **) ft;
623 if ((len2 = strlen(string)) + 2 > TPS(fmt_size)) {
624 TPS(fmt_size) += len2 + 2;
625 TPS(fmt_buff) = typeRealloc(char, TPS(fmt_size), TPS(fmt_buff));
626 if (TPS(fmt_buff) == 0)
633 * Find the highest parameter-number referred to in the format
634 * string. Use this value to limit the number of arguments copied
635 * from the variable-length argument list.
637 result->num_parsed = _nc_tparm_analyze(term, string,
639 &(result->num_popped));
640 if (TPS(fmt_buff) == 0) {
641 TR(TRACE_CALLS, ("%s: error in analysis", TPS(tname)));
646 if (result->num_parsed > NUM_PARM)
647 result->num_parsed = NUM_PARM;
648 if (result->num_popped > NUM_PARM)
649 result->num_popped = NUM_PARM;
650 result->num_actual = max(result->num_popped, result->num_parsed);
652 for (n = 0; n < result->num_actual; ++n) {
653 if (result->p_is_s[n])
654 result->tparm_type |= (1 << n);
657 if ((fs = typeCalloc(TPARM_DATA, 1)) != 0) {
659 if ((fs->format = strdup(string)) != 0) {
660 if (tsearch(fs, &MyCache, cmp_format) != 0) {
682 * A few caps (such as plab_norm) have string-valued parms. We'll have to
683 * assume that the caller knows the difference, since a char* and an int may
684 * not be the same size on the stack. The normal prototype for tparm uses 9
685 * long's, which is consistent with our va_arg() usage.
688 tparm_copy_valist(TPARM_DATA *data, int use_TPARM_ARG, va_list ap)
692 for (i = 0; i < data->num_actual; i++) {
693 if (data->p_is_s[i] != 0) {
694 char *value = va_arg(ap, char *);
697 data->p_is_s[i] = value;
699 } else if (use_TPARM_ARG) {
700 data->param[i] = va_arg(ap, TPARM_ARG);
702 data->param[i] = (TPARM_ARG) va_arg(ap, int);
708 * This is a termcap compatibility hack. If there are no explicit pop
709 * operations in the string, load the stack in such a way that successive pops
710 * will grab successive parameters. That will make the expansion of (for
711 * example) \E[%d;%dH work correctly in termcap style, which means tparam()
712 * will expand termcap strings OK.
715 tparm_tc_compat(TPARM_STATE *tps, TPARM_DATA *data)
717 bool termcap_hack = FALSE;
721 if (data->num_popped == 0) {
725 for (i = data->num_parsed - 1; i >= 0; i--) {
726 if (data->p_is_s[i]) {
727 spush(tps, data->p_is_s[i]);
729 npush(tps, (int) data->param[i]);
738 tparm_trace_call(TPARM_STATE *tps, const char *string, TPARM_DATA *data)
740 if (USE_TRACEF(TRACE_CALLS)) {
742 for (i = 0; i < data->num_actual; i++) {
743 if (data->p_is_s[i] != 0) {
744 save_text(tps, ", %s", _nc_visbuf(data->p_is_s[i]), 0);
745 } else if ((long) data->param[i] > MAX_OF_TYPE(NCURSES_INT2) ||
746 (long) data->param[i] < 0) {
747 _tracef("BUG: problem with tparm parameter #%d of %d",
748 i + 1, data->num_actual);
751 save_number(tps, ", %d", (int) data->param[i], 0);
754 _tracef(T_CALLED("%s(%s%s)"), TPS(tname), _nc_visbuf(string), TPS(out_buff));
756 _nc_unlock_global(tracef);
761 #define tparm_trace_call(tps, string, data) /* nothing */
764 #define init_vars(name) \
765 if (!name##_used) { \
766 name##_used = TRUE; \
767 memset(name##_vars, 0, sizeof(name##_vars)); \
770 static NCURSES_INLINE char *
771 tparam_internal(TPARM_STATE *tps, const char *string, TPARM_DATA *data)
779 const char *cp = string;
780 size_t len2 = strlen(cp);
781 bool incremented_two = FALSE;
782 bool termcap_hack = tparm_tc_compat(tps, data);
784 * SVr4 curses stores variables 'A' to 'Z' in the TERMINAL structure (so
785 * they are initialized once to zero), and variables 'a' to 'z' on the
786 * stack in tparm, referring to the former as "static" and the latter as
787 * "dynamic". However, it makes no check to ensure that the "dynamic"
788 * variables are initialized.
790 * Solaris xpg4 curses makes no distinction between the upper/lower, and
791 * stores the common set of 26 variables on the stack, without initializing
794 * In ncurses, both sets of variables are initialized on the first use.
796 bool dynamic_used = FALSE;
797 int dynamic_vars[NUM_VARS];
799 tparm_trace_call(tps, string, data);
801 while ((cp - string) < (int) len2) {
803 save_char(tps, UChar(*cp));
805 TPS(tparam_base) = cp++;
806 cp = parse_format(cp, TPS(fmt_buff), &len);
814 case 'd': /* FALLTHRU */
815 case 'o': /* FALLTHRU */
816 case 'x': /* FALLTHRU */
817 case 'X': /* FALLTHRU */
819 save_number(tps, TPS(fmt_buff), x, len);
822 case 'c': /* FALLTHRU */
827 #ifdef EXP_XTERM_1005
830 unsigned char target[10];
831 unsigned source = (unsigned) npop(tps);
832 int rc = _nc_conv_to_utf8(target, source, (unsigned)
835 for (n = 0; n < rc; ++n) {
836 save_char(tps, target[n]);
843 npush(tps, (int) strlen(s));
848 save_text(tps, TPS(fmt_buff), s, len);
853 i = (UChar(*cp) - '1');
854 if (i >= 0 && i < NUM_PARM) {
855 if (data->p_is_s[i]) {
856 spush(tps, data->p_is_s[i]);
858 npush(tps, (int) data->param[i]);
866 i = (UChar(*cp) - 'A');
867 TPS(static_vars)[i] = npop(tps);
868 } else if (isLOWER(*cp)) {
869 i = (UChar(*cp) - 'a');
871 dynamic_vars[i] = npop(tps);
878 i = (UChar(*cp) - 'A');
879 npush(tps, TPS(static_vars)[i]);
880 } else if (isLOWER(*cp)) {
881 i = (UChar(*cp) - 'a');
883 npush(tps, dynamic_vars[i]);
889 npush(tps, UChar(*cp));
896 while (isdigit(UChar(*cp))) {
897 number = (number * 10) + (UChar(*cp) - '0');
924 npush(tps, y ? (x / y) : 0);
930 npush(tps, y ? (x % y) : 0);
993 * Increment the first two parameters -- if they are numbers
994 * rather than strings. As a side effect, assign into the
995 * stack; if this is termcap, then the stack was populated
996 * using the termcap hack above rather than via the terminfo
999 if (!incremented_two) {
1000 incremented_two = TRUE;
1001 if (data->p_is_s[0] == 0) {
1004 TPS(stack)[0].data.num = (int) data->param[0];
1006 if (data->p_is_s[1] == 0) {
1009 TPS(stack)[1].data.num = (int) data->param[1];
1020 /* scan forward for %e or %; at level zero */
1028 else if (*cp == ';') {
1033 } else if (*cp == 'e' && level == 0)
1044 /* scan forward for a %; at level zero */
1052 else if (*cp == ';') {
1068 } /* endswitch (*cp) */
1069 } /* endelse (*cp == '%') */
1075 } /* endwhile (*cp) */
1077 get_space(tps, (size_t) 1);
1078 TPS(out_buff)[TPS(out_used)] = '\0';
1080 if (TPS(stack_ptr) && !_nc_tparm_err) {
1081 DEBUG(2, ("tparm: stack has %d item%s on return",
1083 TPS(stack_ptr) == 1 ? "" : "s"));
1087 T((T_RETURN("%s"), _nc_visbuf(TPS(out_buff))));
1088 return (TPS(out_buff));
1091 #if NCURSES_TPARM_VARARGS
1093 NCURSES_EXPORT(char *)
1094 tparm(const char *string, ...)
1096 TPARM_STATE *tps = get_tparm_state(cur_term);
1098 char *result = NULL;
1102 tps->tname = "tparm";
1105 if (tparm_setup(cur_term, string, &myData) == OK) {
1108 va_start(ap, string);
1109 tparm_copy_valist(&myData, TRUE, ap);
1112 result = tparam_internal(tps, string, &myData);
1117 #else /* !NCURSES_TPARM_VARARGS */
1119 NCURSES_EXPORT(char *)
1120 tparm(const char *string,
1131 TPARM_STATE *tps = get_tparm_state(cur_term);
1133 char *result = NULL;
1137 tps->tname = "tparm";
1140 if (tparm_setup(cur_term, string, &myData) == OK) {
1142 myData.param[0] = a1;
1143 myData.param[1] = a2;
1144 myData.param[2] = a3;
1145 myData.param[3] = a4;
1146 myData.param[4] = a5;
1147 myData.param[5] = a6;
1148 myData.param[6] = a7;
1149 myData.param[7] = a8;
1150 myData.param[8] = a9;
1152 result = tparam_internal(tps, string, &myData);
1157 #endif /* NCURSES_TPARM_VARARGS */
1159 NCURSES_EXPORT(char *)
1160 tiparm(const char *string, ...)
1162 TPARM_STATE *tps = get_tparm_state(cur_term);
1164 char *result = NULL;
1168 tps->tname = "tiparm";
1171 if (tparm_setup(cur_term, string, &myData) == OK) {
1174 va_start(ap, string);
1175 tparm_copy_valist(&myData, FALSE, ap);
1178 result = tparam_internal(tps, string, &myData);
1184 * The internal-use flavor ensures that the parameters are numbers, not strings
1186 NCURSES_EXPORT(char *)
1187 _nc_tiparm(int expected, const char *string, ...)
1189 TPARM_STATE *tps = get_tparm_state(cur_term);
1191 char *result = NULL;
1195 tps->tname = "_nc_tiparm";
1198 if (tparm_setup(cur_term, string, &myData) == OK
1199 && myData.num_actual <= expected
1200 && myData.tparm_type == 0) {
1203 va_start(ap, string);
1204 tparm_copy_valist(&myData, FALSE, ap);
1207 result = tparam_internal(tps, string, &myData);
1213 * Improve tic's checks by resetting the terminfo "static variables" before
1214 * calling functions which may update them.
1216 NCURSES_EXPORT(void)
1217 _nc_reset_tparm(TERMINAL *term)
1219 TPARM_STATE *tps = get_tparm_state(term);
1220 memset(TPS(static_vars), 0, sizeof(TPS(static_vars)));