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.135 2021/11/15 23:31:31 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)
214 DEBUG(2, ("%s: %s", message, _nc_visbuf(TPS(tparam_base))));
215 return ++_nc_tparm_err;
218 #define get_space(tps, need) \
220 size_t need2get = need + TPS(out_used); \
221 if (need2get > TPS(out_size)) { \
222 TPS(out_size) = need2get * 2; \
223 TYPE_REALLOC(char, TPS(out_size), TPS(out_buff)); \
228 static NCURSES_INLINE void
229 (get_space) (TPARM_STATE *tps, size_t need) {
230 get_space(tps, need);
236 #define save_text(tps, fmt, s, len) \
238 size_t s_len = (size_t) len + strlen(s) + strlen(fmt); \
239 get_space(tps, s_len + 1); \
240 _nc_SPRINTF(TPS(out_buff) + TPS(out_used), \
241 _nc_SLIMIT(TPS(out_size) - TPS(out_used)) \
243 TPS(out_used) += strlen(TPS(out_buff) + TPS(out_used)); \
247 static NCURSES_INLINE void
248 (save_text) (TPARM_STATE *tps, const char *fmt, const char *s, int len) {
249 save_text(tps, fmt, s, len);
255 #define save_number(tps, fmt, number, len) \
257 size_t s_len = (size_t) len + 30 + strlen(fmt); \
258 get_space(tps, s_len + 1); \
259 _nc_SPRINTF(TPS(out_buff) + TPS(out_used), \
260 _nc_SLIMIT(TPS(out_size) - TPS(out_used)) \
262 TPS(out_used) += strlen(TPS(out_buff) + TPS(out_used)); \
266 static NCURSES_INLINE void
267 (save_number) (TPARM_STATE *tps, const char *fmt, int number, int len) {
268 save_number(tps, fmt, number, len);
274 #define save_char(tps, c) \
276 get_space(tps, (size_t) 1); \
277 TPS(out_buff)[TPS(out_used)++] = (char) ((c == 0) ? 0200 : c); \
281 static NCURSES_INLINE void
282 (save_char) (TPARM_STATE *tps, int c) {
289 #define npush(tps, x) \
291 if (TPS(stack_ptr) < STACKSIZE) { \
292 TPS(stack)[TPS(stack_ptr)].num_type = TRUE; \
293 TPS(stack)[TPS(stack_ptr)].data.num = x; \
296 (void) tparm_error(tps, "npush: stack overflow"); \
301 static NCURSES_INLINE void
302 (npush) (TPARM_STATE *tps, int x) {
309 #define spush(tps, x) \
311 if (TPS(stack_ptr) < STACKSIZE) { \
312 TPS(stack)[TPS(stack_ptr)].num_type = FALSE; \
313 TPS(stack)[TPS(stack_ptr)].data.str = x; \
316 (void) tparm_error(tps, "spush: stack overflow"); \
321 static NCURSES_INLINE void
322 (spush) (TPARM_STATE *tps, char *x) {
330 ((TPS(stack_ptr)-- > 0) \
331 ? ((TPS(stack)[TPS(stack_ptr)].num_type) \
332 ? TPS(stack)[TPS(stack_ptr)].data.num \
334 : (tparm_error(tps, "npop: stack underflow"), \
338 static NCURSES_INLINE int
339 (npop) (TPARM_STATE *tps) {
346 ((TPS(stack_ptr)-- > 0) \
347 ? ((!TPS(stack)[TPS(stack_ptr)].num_type \
348 && TPS(stack)[TPS(stack_ptr)].data.str != 0) \
349 ? TPS(stack)[TPS(stack_ptr)].data.str \
351 : (tparm_error(tps, "spop: stack underflow"), \
355 static NCURSES_INLINE char *
356 (spop) (TPARM_STATE *tps) {
362 static NCURSES_INLINE const char *
363 parse_format(const char *s, char *format, int *len)
368 bool allowminus = FALSE;
378 while (*s != '\0' && !done) {
380 case 'c': /* FALLTHRU */
381 case 'd': /* FALLTHRU */
382 case 'o': /* FALLTHRU */
383 case 'x': /* FALLTHRU */
384 case 'X': /* FALLTHRU */
386 #ifdef EXP_XTERM_1005
396 } else { /* value before '.' is the width */
420 if (isdigit(UChar(*s))) {
421 value = (value * 10) + (*s - '0');
432 * If we found an error, ignore (and remove) the flags.
435 my_width = my_prec = value = 0;
442 * Any value after '.' is the precision. If we did not see '.', then
443 * the value is the width.
451 /* return maximum string length in print */
452 *len = (my_width > my_prec) ? my_width : my_prec;
458 * Analyze the string to see how many parameters we need from the varargs list,
459 * and what their types are. We will only accept string parameters if they
460 * appear as a %l or %s format following an explicit parameter reference (e.g.,
461 * %p2%s). All other parameters are numbers.
463 * 'number' counts coarsely the number of pop's we see in the string, and
464 * 'popcount' shows the highest parameter number in the string. We would like
465 * to simply use the latter count, but if we are reading termcap strings, there
466 * may be cases that we cannot see the explicit parameter numbers.
469 _nc_tparm_analyze(TERMINAL *term, const char *string, char **p_is_s, int *popcount)
471 TPARM_STATE *tps = get_tparm_state(term);
478 const char *cp = string;
483 if ((len2 = strlen(cp)) + 2 > TPS(fmt_size)) {
484 TPS(fmt_size) += len2 + 2;
485 TPS(fmt_buff) = typeRealloc(char, TPS(fmt_size), TPS(fmt_buff));
486 if (TPS(fmt_buff) == 0)
490 memset(p_is_s, 0, sizeof(p_is_s[0]) * NUM_PARM);
493 while ((cp - string) < (int) len2) {
496 cp = parse_format(cp, TPS(fmt_buff), &len);
501 case 'd': /* FALLTHRU */
502 case 'o': /* FALLTHRU */
503 case 'x': /* FALLTHRU */
504 case 'X': /* FALLTHRU */
505 case 'c': /* FALLTHRU */
506 #ifdef EXP_XTERM_1005
520 p_is_s[lastpop - 1] = dummy;
527 i = (UChar(*cp) - '0');
528 if (i >= 0 && i <= NUM_PARM) {
531 if (lastpop > *popcount)
554 while (isdigit(UChar(*cp))) {
573 level -= 1; /* pop 2, operate, push 1 */
584 /* will add 1 to first (usually two) parameters */
592 if (number > NUM_PARM)
598 * Analyze the capability string, finding the number of parameters and their
601 * TODO: cache the result so that this is done once per capability per term.
604 tparm_setup(TERMINAL *term, const char *string, TPARM_DATA *result)
606 TPARM_STATE *tps = get_tparm_state(term);
610 memset(result, 0, sizeof(*result));
612 if (string == NULL) {
613 TR(TRACE_CALLS, ("%s: format is null", TPS(tname)));
620 result->format = string;
621 if ((ft = tfind(result, &MyCache, cmp_format)) != 0) {
623 fs = *(TPARM_DATA **) ft;
625 if ((len2 = strlen(string)) + 2 > TPS(fmt_size)) {
626 TPS(fmt_size) += len2 + 2;
627 TPS(fmt_buff) = typeRealloc(char, TPS(fmt_size), TPS(fmt_buff));
628 if (TPS(fmt_buff) == 0)
635 * Find the highest parameter-number referred to in the format
636 * string. Use this value to limit the number of arguments copied
637 * from the variable-length argument list.
639 result->num_parsed = _nc_tparm_analyze(term, string,
641 &(result->num_popped));
642 if (TPS(fmt_buff) == 0) {
643 TR(TRACE_CALLS, ("%s: error in analysis", TPS(tname)));
648 if (result->num_parsed > NUM_PARM)
649 result->num_parsed = NUM_PARM;
650 if (result->num_popped > NUM_PARM)
651 result->num_popped = NUM_PARM;
652 result->num_actual = max(result->num_popped, result->num_parsed);
654 for (n = 0; n < result->num_actual; ++n) {
655 if (result->p_is_s[n])
656 result->tparm_type |= (1 << n);
659 if ((fs = typeCalloc(TPARM_DATA, 1)) != 0) {
661 if ((fs->format = strdup(string)) != 0) {
662 if (tsearch(fs, &MyCache, cmp_format) != 0) {
684 * A few caps (such as plab_norm) have string-valued parms. We'll have to
685 * assume that the caller knows the difference, since a char* and an int may
686 * not be the same size on the stack. The normal prototype for tparm uses 9
687 * long's, which is consistent with our va_arg() usage.
690 tparm_copy_valist(TPARM_DATA *data, int use_TPARM_ARG, va_list ap)
694 for (i = 0; i < data->num_actual; i++) {
695 if (data->p_is_s[i] != 0) {
696 char *value = va_arg(ap, char *);
699 data->p_is_s[i] = value;
701 } else if (use_TPARM_ARG) {
702 data->param[i] = va_arg(ap, TPARM_ARG);
704 data->param[i] = (TPARM_ARG) va_arg(ap, int);
710 * This is a termcap compatibility hack. If there are no explicit pop
711 * operations in the string, load the stack in such a way that successive pops
712 * will grab successive parameters. That will make the expansion of (for
713 * example) \E[%d;%dH work correctly in termcap style, which means tparam()
714 * will expand termcap strings OK.
717 tparm_tc_compat(TPARM_STATE *tps, TPARM_DATA *data)
719 bool termcap_hack = FALSE;
723 if (data->num_popped == 0) {
727 for (i = data->num_parsed - 1; i >= 0; i--) {
728 if (data->p_is_s[i]) {
729 spush(tps, data->p_is_s[i]);
731 npush(tps, (int) data->param[i]);
740 tparm_trace_call(TPARM_STATE *tps, const char *string, TPARM_DATA *data)
742 if (USE_TRACEF(TRACE_CALLS)) {
744 for (i = 0; i < data->num_actual; i++) {
745 if (data->p_is_s[i] != 0) {
746 save_text(tps, ", %s", _nc_visbuf(data->p_is_s[i]), 0);
747 } else if ((long) data->param[i] > MAX_OF_TYPE(NCURSES_INT2) ||
748 (long) data->param[i] < 0) {
749 _tracef("BUG: problem with tparm parameter #%d of %d",
750 i + 1, data->num_actual);
753 save_number(tps, ", %d", (int) data->param[i], 0);
756 _tracef(T_CALLED("%s(%s%s)"), TPS(tname), _nc_visbuf(string), TPS(out_buff));
758 _nc_unlock_global(tracef);
763 #define tparm_trace_call(tps, string, data) /* nothing */
766 #define init_vars(name) \
767 if (!name##_used) { \
768 name##_used = TRUE; \
769 memset(name##_vars, 0, sizeof(name##_vars)); \
772 static NCURSES_INLINE char *
773 tparam_internal(TPARM_STATE *tps, const char *string, TPARM_DATA *data)
781 const char *cp = string;
782 size_t len2 = strlen(cp);
783 bool incremented_two = FALSE;
784 bool termcap_hack = tparm_tc_compat(tps, data);
786 * SVr4 curses stores variables 'A' to 'Z' in the TERMINAL structure (so
787 * they are initialized once to zero), and variables 'a' to 'z' on the
788 * stack in tparm, referring to the former as "static" and the latter as
789 * "dynamic". However, it makes no check to ensure that the "dynamic"
790 * variables are initialized.
792 * Solaris xpg4 curses makes no distinction between the upper/lower, and
793 * stores the common set of 26 variables on the stack, without initializing
796 * In ncurses, both sets of variables are initialized on the first use.
798 bool dynamic_used = FALSE;
799 int dynamic_vars[NUM_VARS];
801 tparm_trace_call(tps, string, data);
803 while ((cp - string) < (int) len2) {
805 save_char(tps, UChar(*cp));
807 TPS(tparam_base) = cp++;
808 cp = parse_format(cp, TPS(fmt_buff), &len);
816 case 'd': /* FALLTHRU */
817 case 'o': /* FALLTHRU */
818 case 'x': /* FALLTHRU */
819 case 'X': /* FALLTHRU */
821 save_number(tps, TPS(fmt_buff), x, len);
824 case 'c': /* FALLTHRU */
829 #ifdef EXP_XTERM_1005
832 unsigned char target[10];
833 unsigned source = (unsigned) npop(tps);
834 int rc = _nc_conv_to_utf8(target, source, (unsigned)
837 for (n = 0; n < rc; ++n) {
838 save_char(tps, target[n]);
845 npush(tps, (int) strlen(s));
850 save_text(tps, TPS(fmt_buff), s, len);
855 i = (UChar(*cp) - '1');
856 if (i >= 0 && i < NUM_PARM) {
857 if (data->p_is_s[i]) {
858 spush(tps, data->p_is_s[i]);
860 npush(tps, (int) data->param[i]);
868 i = (UChar(*cp) - 'A');
869 TPS(static_vars)[i] = npop(tps);
870 } else if (isLOWER(*cp)) {
871 i = (UChar(*cp) - 'a');
873 dynamic_vars[i] = npop(tps);
880 i = (UChar(*cp) - 'A');
881 npush(tps, TPS(static_vars)[i]);
882 } else if (isLOWER(*cp)) {
883 i = (UChar(*cp) - 'a');
885 npush(tps, dynamic_vars[i]);
891 npush(tps, UChar(*cp));
898 while (isdigit(UChar(*cp))) {
899 number = (number * 10) + (UChar(*cp) - '0');
926 npush(tps, y ? (x / y) : 0);
932 npush(tps, y ? (x % y) : 0);
995 * Increment the first two parameters -- if they are numbers
996 * rather than strings. As a side effect, assign into the
997 * stack; if this is termcap, then the stack was populated
998 * using the termcap hack above rather than via the terminfo
1001 if (!incremented_two) {
1002 incremented_two = TRUE;
1003 if (data->p_is_s[0] == 0) {
1006 TPS(stack)[0].data.num = (int) data->param[0];
1008 if (data->p_is_s[1] == 0) {
1011 TPS(stack)[1].data.num = (int) data->param[1];
1022 /* scan forward for %e or %; at level zero */
1030 else if (*cp == ';') {
1035 } else if (*cp == 'e' && level == 0)
1046 /* scan forward for a %; at level zero */
1054 else if (*cp == ';') {
1070 } /* endswitch (*cp) */
1071 } /* endelse (*cp == '%') */
1077 } /* endwhile (*cp) */
1079 get_space(tps, (size_t) 1);
1080 TPS(out_buff)[TPS(out_used)] = '\0';
1082 if (TPS(stack_ptr) && !_nc_tparm_err) {
1083 DEBUG(2, ("tparm: stack has %d item%s on return",
1085 TPS(stack_ptr) == 1 ? "" : "s"));
1089 T((T_RETURN("%s"), _nc_visbuf(TPS(out_buff))));
1090 return (TPS(out_buff));
1093 #if NCURSES_TPARM_VARARGS
1095 NCURSES_EXPORT(char *)
1096 tparm(const char *string, ...)
1098 TPARM_STATE *tps = get_tparm_state(cur_term);
1100 char *result = NULL;
1104 tps->tname = "tparm";
1107 if (tparm_setup(cur_term, string, &myData) == OK) {
1110 va_start(ap, string);
1111 tparm_copy_valist(&myData, TRUE, ap);
1114 result = tparam_internal(tps, string, &myData);
1119 #else /* !NCURSES_TPARM_VARARGS */
1121 NCURSES_EXPORT(char *)
1122 tparm(const char *string,
1133 TPARM_STATE *tps = get_tparm_state(cur_term);
1135 char *result = NULL;
1139 tps->tname = "tparm";
1142 if (tparm_setup(cur_term, string, &myData) == OK) {
1144 myData.param[0] = a1;
1145 myData.param[1] = a2;
1146 myData.param[2] = a3;
1147 myData.param[3] = a4;
1148 myData.param[4] = a5;
1149 myData.param[5] = a6;
1150 myData.param[6] = a7;
1151 myData.param[7] = a8;
1152 myData.param[8] = a9;
1154 result = tparam_internal(tps, string, &myData);
1159 #endif /* NCURSES_TPARM_VARARGS */
1161 NCURSES_EXPORT(char *)
1162 tiparm(const char *string, ...)
1164 TPARM_STATE *tps = get_tparm_state(cur_term);
1166 char *result = NULL;
1170 tps->tname = "tiparm";
1173 if (tparm_setup(cur_term, string, &myData) == OK) {
1176 va_start(ap, string);
1177 tparm_copy_valist(&myData, FALSE, ap);
1180 result = tparam_internal(tps, string, &myData);
1186 * The internal-use flavor ensures that the parameters are numbers, not strings
1188 NCURSES_EXPORT(char *)
1189 _nc_tiparm(int expected, const char *string, ...)
1191 TPARM_STATE *tps = get_tparm_state(cur_term);
1193 char *result = NULL;
1197 tps->tname = "_nc_tiparm";
1200 if (tparm_setup(cur_term, string, &myData) == OK
1201 && myData.num_actual <= expected
1202 && myData.tparm_type == 0) {
1205 va_start(ap, string);
1206 tparm_copy_valist(&myData, FALSE, ap);
1209 result = tparam_internal(tps, string, &myData);
1215 * Improve tic's checks by resetting the terminfo "static variables" before
1216 * calling functions which may update them.
1218 NCURSES_EXPORT(void)
1219 _nc_reset_tparm(TERMINAL *term)
1221 TPARM_STATE *tps = get_tparm_state(term);
1222 memset(TPS(static_vars), 0, sizeof(TPS(static_vars)));