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.137 2021/11/20 23:29:15 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
145 static int which_tparm;
146 static TPARM_DATA **delete_tparm;
147 #endif /* HAVE_TSEARCH */
149 static char dummy[] = ""; /* avoid const-cast */
153 cmp_format(const void *p, const void *q)
155 const char *a = *(char *const *) p;
156 const char *b = *(char *const *) q;
163 visit_nodes(const void *nodep, VISIT which, int depth)
166 if (which == preorder || which == leaf) {
167 delete_tparm[which_tparm] = *(TPARM_DATA **) nodep;
174 _nc_free_tparm(TERMINAL *termp)
176 TPARM_STATE *tps = get_tparm_state(termp);
179 delete_tparm = typeCalloc(TPARM_DATA *, MyCount);
181 twalk(MyCache, visit_nodes);
182 for (which_tparm = 0; which_tparm < MyCount; ++which_tparm) {
183 TPARM_DATA *ptr = delete_tparm[which_tparm];
185 tdelete(ptr, &MyCache, cmp_format);
186 free((char *) ptr->format);
191 twalk(MyCache, visit_nodes);
192 FreeAndNull(delete_tparm);
197 FreeAndNull(TPS(out_buff));
201 FreeAndNull(TPS(fmt_buff));
206 tparm_error(TPARM_STATE *tps, const char *message)
210 DEBUG(2, ("%s: %s", message, _nc_visbuf(TPS(tparam_base))));
211 return ++_nc_tparm_err;
214 #define get_space(tps, need) \
216 size_t need2get = need + TPS(out_used); \
217 if (need2get > TPS(out_size)) { \
218 TPS(out_size) = need2get * 2; \
219 TYPE_REALLOC(char, TPS(out_size), TPS(out_buff)); \
224 static NCURSES_INLINE void
225 (get_space) (TPARM_STATE *tps, size_t need) {
226 get_space(tps, need);
232 #define save_text(tps, fmt, s, len) \
234 size_t s_len = (size_t) len + strlen(s) + strlen(fmt); \
235 get_space(tps, s_len + 1); \
236 _nc_SPRINTF(TPS(out_buff) + TPS(out_used), \
237 _nc_SLIMIT(TPS(out_size) - TPS(out_used)) \
239 TPS(out_used) += strlen(TPS(out_buff) + TPS(out_used)); \
243 static NCURSES_INLINE void
244 (save_text) (TPARM_STATE *tps, const char *fmt, const char *s, int len) {
245 save_text(tps, fmt, s, len);
251 #define save_number(tps, fmt, number, len) \
253 size_t s_len = (size_t) len + 30 + strlen(fmt); \
254 get_space(tps, s_len + 1); \
255 _nc_SPRINTF(TPS(out_buff) + TPS(out_used), \
256 _nc_SLIMIT(TPS(out_size) - TPS(out_used)) \
258 TPS(out_used) += strlen(TPS(out_buff) + TPS(out_used)); \
262 static NCURSES_INLINE void
263 (save_number) (TPARM_STATE *tps, const char *fmt, int number, int len) {
264 save_number(tps, fmt, number, len);
270 #define save_char(tps, c) \
272 get_space(tps, (size_t) 1); \
273 TPS(out_buff)[TPS(out_used)++] = (char) ((c == 0) ? 0200 : c); \
277 static NCURSES_INLINE void
278 (save_char) (TPARM_STATE *tps, int c) {
285 #define npush(tps, x) \
287 if (TPS(stack_ptr) < STACKSIZE) { \
288 TPS(stack)[TPS(stack_ptr)].num_type = TRUE; \
289 TPS(stack)[TPS(stack_ptr)].data.num = x; \
292 (void) tparm_error(tps, "npush: stack overflow"); \
297 static NCURSES_INLINE void
298 (npush) (TPARM_STATE *tps, int x) {
305 #define spush(tps, x) \
307 if (TPS(stack_ptr) < STACKSIZE) { \
308 TPS(stack)[TPS(stack_ptr)].num_type = FALSE; \
309 TPS(stack)[TPS(stack_ptr)].data.str = x; \
312 (void) tparm_error(tps, "spush: stack overflow"); \
317 static NCURSES_INLINE void
318 (spush) (TPARM_STATE *tps, char *x) {
326 ((TPS(stack_ptr)-- > 0) \
327 ? ((TPS(stack)[TPS(stack_ptr)].num_type) \
328 ? TPS(stack)[TPS(stack_ptr)].data.num \
330 : (tparm_error(tps, "npop: stack underflow"), \
334 static NCURSES_INLINE int
335 (npop) (TPARM_STATE *tps) {
342 ((TPS(stack_ptr)-- > 0) \
343 ? ((!TPS(stack)[TPS(stack_ptr)].num_type \
344 && TPS(stack)[TPS(stack_ptr)].data.str != 0) \
345 ? TPS(stack)[TPS(stack_ptr)].data.str \
347 : (tparm_error(tps, "spop: stack underflow"), \
351 static NCURSES_INLINE char *
352 (spop) (TPARM_STATE *tps) {
358 static NCURSES_INLINE const char *
359 parse_format(const char *s, char *format, int *len)
364 bool allowminus = FALSE;
374 while (*s != '\0' && !done) {
376 case 'c': /* FALLTHRU */
377 case 'd': /* FALLTHRU */
378 case 'o': /* FALLTHRU */
379 case 'x': /* FALLTHRU */
380 case 'X': /* FALLTHRU */
382 #ifdef EXP_XTERM_1005
392 } else { /* value before '.' is the width */
416 if (isdigit(UChar(*s))) {
417 value = (value * 10) + (*s - '0');
428 * If we found an error, ignore (and remove) the flags.
431 my_width = my_prec = value = 0;
438 * Any value after '.' is the precision. If we did not see '.', then
439 * the value is the width.
447 /* return maximum string length in print */
448 *len = (my_width > my_prec) ? my_width : my_prec;
454 * Analyze the string to see how many parameters we need from the varargs list,
455 * and what their types are. We will only accept string parameters if they
456 * appear as a %l or %s format following an explicit parameter reference (e.g.,
457 * %p2%s). All other parameters are numbers.
459 * 'number' counts coarsely the number of pop's we see in the string, and
460 * 'popcount' shows the highest parameter number in the string. We would like
461 * to simply use the latter count, but if we are reading termcap strings, there
462 * may be cases that we cannot see the explicit parameter numbers.
465 _nc_tparm_analyze(TERMINAL *term, const char *string, char **p_is_s, int *popcount)
467 TPARM_STATE *tps = get_tparm_state(term);
474 const char *cp = string;
479 if ((len2 = strlen(cp)) + 2 > TPS(fmt_size)) {
480 TPS(fmt_size) += len2 + 2;
481 TPS(fmt_buff) = typeRealloc(char, TPS(fmt_size), TPS(fmt_buff));
482 if (TPS(fmt_buff) == 0)
486 memset(p_is_s, 0, sizeof(p_is_s[0]) * NUM_PARM);
489 while ((cp - string) < (int) len2) {
492 cp = parse_format(cp, TPS(fmt_buff), &len);
497 case 'd': /* FALLTHRU */
498 case 'o': /* FALLTHRU */
499 case 'x': /* FALLTHRU */
500 case 'X': /* FALLTHRU */
501 case 'c': /* FALLTHRU */
502 #ifdef EXP_XTERM_1005
516 p_is_s[lastpop - 1] = dummy;
523 i = (UChar(*cp) - '0');
524 if (i >= 0 && i <= NUM_PARM) {
527 if (lastpop > *popcount)
550 while (isdigit(UChar(*cp))) {
569 level -= 1; /* pop 2, operate, push 1 */
580 /* will add 1 to first (usually two) parameters */
588 if (number > NUM_PARM)
594 * Analyze the capability string, finding the number of parameters and their
597 * TODO: cache the result so that this is done once per capability per term.
600 tparm_setup(TERMINAL *term, const char *string, TPARM_DATA *result)
602 TPARM_STATE *tps = get_tparm_state(term);
606 memset(result, 0, sizeof(*result));
608 if (string == NULL) {
609 TR(TRACE_CALLS, ("%s: format is null", TPS(tname)));
616 result->format = string;
617 if ((ft = tfind(result, &MyCache, cmp_format)) != 0) {
619 fs = *(TPARM_DATA **) ft;
621 if ((len2 = strlen(string)) + 2 > TPS(fmt_size)) {
622 TPS(fmt_size) += len2 + 2;
623 TPS(fmt_buff) = typeRealloc(char, TPS(fmt_size), TPS(fmt_buff));
624 if (TPS(fmt_buff) == 0)
631 * Find the highest parameter-number referred to in the format
632 * string. Use this value to limit the number of arguments copied
633 * from the variable-length argument list.
635 result->num_parsed = _nc_tparm_analyze(term, string,
637 &(result->num_popped));
638 if (TPS(fmt_buff) == 0) {
639 TR(TRACE_CALLS, ("%s: error in analysis", TPS(tname)));
644 if (result->num_parsed > NUM_PARM)
645 result->num_parsed = NUM_PARM;
646 if (result->num_popped > NUM_PARM)
647 result->num_popped = NUM_PARM;
648 result->num_actual = max(result->num_popped, result->num_parsed);
650 for (n = 0; n < result->num_actual; ++n) {
651 if (result->p_is_s[n])
652 result->tparm_type |= (1 << n);
655 if ((fs = typeCalloc(TPARM_DATA, 1)) != 0) {
657 if ((fs->format = strdup(string)) != 0) {
658 if (tsearch(fs, &MyCache, cmp_format) != 0) {
680 * A few caps (such as plab_norm) have string-valued parms. We'll have to
681 * assume that the caller knows the difference, since a char* and an int may
682 * not be the same size on the stack. The normal prototype for tparm uses 9
683 * long's, which is consistent with our va_arg() usage.
686 tparm_copy_valist(TPARM_DATA *data, int use_TPARM_ARG, va_list ap)
690 for (i = 0; i < data->num_actual; i++) {
691 if (data->p_is_s[i] != 0) {
692 char *value = va_arg(ap, char *);
695 data->p_is_s[i] = value;
697 } else if (use_TPARM_ARG) {
698 data->param[i] = va_arg(ap, TPARM_ARG);
700 data->param[i] = (TPARM_ARG) va_arg(ap, int);
706 * This is a termcap compatibility hack. If there are no explicit pop
707 * operations in the string, load the stack in such a way that successive pops
708 * will grab successive parameters. That will make the expansion of (for
709 * example) \E[%d;%dH work correctly in termcap style, which means tparam()
710 * will expand termcap strings OK.
713 tparm_tc_compat(TPARM_STATE *tps, TPARM_DATA *data)
715 bool termcap_hack = FALSE;
719 if (data->num_popped == 0) {
723 for (i = data->num_parsed - 1; i >= 0; i--) {
724 if (data->p_is_s[i]) {
725 spush(tps, data->p_is_s[i]);
727 npush(tps, (int) data->param[i]);
736 tparm_trace_call(TPARM_STATE *tps, const char *string, TPARM_DATA *data)
738 if (USE_TRACEF(TRACE_CALLS)) {
740 for (i = 0; i < data->num_actual; i++) {
741 if (data->p_is_s[i] != 0) {
742 save_text(tps, ", %s", _nc_visbuf(data->p_is_s[i]), 0);
743 } else if ((long) data->param[i] > MAX_OF_TYPE(NCURSES_INT2) ||
744 (long) data->param[i] < 0) {
745 _tracef("BUG: problem with tparm parameter #%d of %d",
746 i + 1, data->num_actual);
749 save_number(tps, ", %d", (int) data->param[i], 0);
752 _tracef(T_CALLED("%s(%s%s)"), TPS(tname), _nc_visbuf(string), TPS(out_buff));
754 _nc_unlock_global(tracef);
759 #define tparm_trace_call(tps, string, data) /* nothing */
762 #define init_vars(name) \
763 if (!name##_used) { \
764 name##_used = TRUE; \
765 memset(name##_vars, 0, sizeof(name##_vars)); \
768 static NCURSES_INLINE char *
769 tparam_internal(TPARM_STATE *tps, const char *string, TPARM_DATA *data)
777 const char *cp = string;
778 size_t len2 = strlen(cp);
779 bool incremented_two = FALSE;
780 bool termcap_hack = tparm_tc_compat(tps, data);
782 * SVr4 curses stores variables 'A' to 'Z' in the TERMINAL structure (so
783 * they are initialized once to zero), and variables 'a' to 'z' on the
784 * stack in tparm, referring to the former as "static" and the latter as
785 * "dynamic". However, it makes no check to ensure that the "dynamic"
786 * variables are initialized.
788 * Solaris xpg4 curses makes no distinction between the upper/lower, and
789 * stores the common set of 26 variables on the stack, without initializing
792 * In ncurses, both sets of variables are initialized on the first use.
794 bool dynamic_used = FALSE;
795 int dynamic_vars[NUM_VARS];
797 tparm_trace_call(tps, string, data);
799 while ((cp - string) < (int) len2) {
801 save_char(tps, UChar(*cp));
803 TPS(tparam_base) = cp++;
804 cp = parse_format(cp, TPS(fmt_buff), &len);
812 case 'd': /* FALLTHRU */
813 case 'o': /* FALLTHRU */
814 case 'x': /* FALLTHRU */
815 case 'X': /* FALLTHRU */
817 save_number(tps, TPS(fmt_buff), x, len);
820 case 'c': /* FALLTHRU */
825 #ifdef EXP_XTERM_1005
828 unsigned char target[10];
829 unsigned source = (unsigned) npop(tps);
830 int rc = _nc_conv_to_utf8(target, source, (unsigned)
833 for (n = 0; n < rc; ++n) {
834 save_char(tps, target[n]);
841 npush(tps, (int) strlen(s));
846 save_text(tps, TPS(fmt_buff), s, len);
851 i = (UChar(*cp) - '1');
852 if (i >= 0 && i < NUM_PARM) {
853 if (data->p_is_s[i]) {
854 spush(tps, data->p_is_s[i]);
856 npush(tps, (int) data->param[i]);
864 i = (UChar(*cp) - 'A');
865 TPS(static_vars)[i] = npop(tps);
866 } else if (isLOWER(*cp)) {
867 i = (UChar(*cp) - 'a');
869 dynamic_vars[i] = npop(tps);
876 i = (UChar(*cp) - 'A');
877 npush(tps, TPS(static_vars)[i]);
878 } else if (isLOWER(*cp)) {
879 i = (UChar(*cp) - 'a');
881 npush(tps, dynamic_vars[i]);
887 npush(tps, UChar(*cp));
894 while (isdigit(UChar(*cp))) {
895 number = (number * 10) + (UChar(*cp) - '0');
922 npush(tps, y ? (x / y) : 0);
928 npush(tps, y ? (x % y) : 0);
991 * Increment the first two parameters -- if they are numbers
992 * rather than strings. As a side effect, assign into the
993 * stack; if this is termcap, then the stack was populated
994 * using the termcap hack above rather than via the terminfo
997 if (!incremented_two) {
998 incremented_two = TRUE;
999 if (data->p_is_s[0] == 0) {
1002 TPS(stack)[0].data.num = (int) data->param[0];
1004 if (data->p_is_s[1] == 0) {
1007 TPS(stack)[1].data.num = (int) data->param[1];
1018 /* scan forward for %e or %; at level zero */
1026 else if (*cp == ';') {
1031 } else if (*cp == 'e' && level == 0)
1042 /* scan forward for a %; at level zero */
1050 else if (*cp == ';') {
1066 } /* endswitch (*cp) */
1067 } /* endelse (*cp == '%') */
1073 } /* endwhile (*cp) */
1075 get_space(tps, (size_t) 1);
1076 TPS(out_buff)[TPS(out_used)] = '\0';
1078 if (TPS(stack_ptr) && !_nc_tparm_err) {
1079 DEBUG(2, ("tparm: stack has %d item%s on return",
1081 TPS(stack_ptr) == 1 ? "" : "s"));
1085 T((T_RETURN("%s"), _nc_visbuf(TPS(out_buff))));
1086 return (TPS(out_buff));
1089 #if NCURSES_TPARM_VARARGS
1091 NCURSES_EXPORT(char *)
1092 tparm(const char *string, ...)
1094 TPARM_STATE *tps = get_tparm_state(cur_term);
1096 char *result = NULL;
1100 tps->tname = "tparm";
1103 if (tparm_setup(cur_term, string, &myData) == OK) {
1106 va_start(ap, string);
1107 tparm_copy_valist(&myData, TRUE, ap);
1110 result = tparam_internal(tps, string, &myData);
1115 #else /* !NCURSES_TPARM_VARARGS */
1117 NCURSES_EXPORT(char *)
1118 tparm(const char *string,
1129 TPARM_STATE *tps = get_tparm_state(cur_term);
1131 char *result = NULL;
1135 tps->tname = "tparm";
1138 if (tparm_setup(cur_term, string, &myData) == OK) {
1140 myData.param[0] = a1;
1141 myData.param[1] = a2;
1142 myData.param[2] = a3;
1143 myData.param[3] = a4;
1144 myData.param[4] = a5;
1145 myData.param[5] = a6;
1146 myData.param[6] = a7;
1147 myData.param[7] = a8;
1148 myData.param[8] = a9;
1150 result = tparam_internal(tps, string, &myData);
1155 #endif /* NCURSES_TPARM_VARARGS */
1157 NCURSES_EXPORT(char *)
1158 tiparm(const char *string, ...)
1160 TPARM_STATE *tps = get_tparm_state(cur_term);
1162 char *result = NULL;
1166 tps->tname = "tiparm";
1169 if (tparm_setup(cur_term, string, &myData) == OK) {
1172 va_start(ap, string);
1173 tparm_copy_valist(&myData, FALSE, ap);
1176 result = tparam_internal(tps, string, &myData);
1182 * The internal-use flavor ensures that the parameters are numbers, not strings
1184 NCURSES_EXPORT(char *)
1185 _nc_tiparm(int expected, const char *string, ...)
1187 TPARM_STATE *tps = get_tparm_state(cur_term);
1189 char *result = NULL;
1193 tps->tname = "_nc_tiparm";
1196 if (tparm_setup(cur_term, string, &myData) == OK
1197 && myData.num_actual <= expected
1198 && myData.tparm_type == 0) {
1201 va_start(ap, string);
1202 tparm_copy_valist(&myData, FALSE, ap);
1205 result = tparam_internal(tps, string, &myData);
1211 * Improve tic's checks by resetting the terminfo "static variables" before
1212 * calling functions which may update them.
1214 NCURSES_EXPORT(void)
1215 _nc_reset_tparm(TERMINAL *term)
1217 TPARM_STATE *tps = get_tparm_state(term);
1218 memset(TPS(static_vars), 0, sizeof(TPS(static_vars)));