1 /****************************************************************************
2 * Copyright (c) 1998-2017,2018 Free Software Foundation, Inc. *
4 * Permission is hereby granted, free of charge, to any person obtaining a *
5 * copy of this software and associated documentation files (the *
6 * "Software"), to deal in the Software without restriction, including *
7 * without limitation the rights to use, copy, modify, merge, publish, *
8 * distribute, distribute with modifications, sublicense, and/or sell *
9 * copies of the Software, and to permit persons to whom the Software is *
10 * furnished to do so, subject to the following conditions: *
12 * The above copyright notice and this permission notice shall be included *
13 * in all copies or substantial portions of the Software. *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS *
16 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. *
18 * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, *
19 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR *
20 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR *
21 * THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
23 * Except as contained in this notice, the name(s) of the above copyright *
24 * holders shall not be used in advertising or otherwise to promote the *
25 * sale, use or other dealings in this Software without prior written *
27 ****************************************************************************/
29 /****************************************************************************
30 * Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995 *
31 * and: Eric S. Raymond <esr@snark.thyrsus.com> *
32 * and: Thomas E. Dickey, 1996 on *
33 ****************************************************************************/
40 #include <curses.priv.h>
45 MODULE_ID("$Id: lib_tparm.c,v 1.106 2018/07/01 15:23:27 tom Exp $")
51 * Substitute the given parameters into the given string by the following
52 * rules (taken from terminfo(5)):
54 * Cursor addressing and other strings requiring parame-
55 * ters in the terminal are described by a parameterized string
56 * capability, with escapes like %x in it. For example, to
57 * address the cursor, the cup capability is given, using two
58 * parameters: the row and column to address to. (Rows and
59 * columns are numbered from zero and refer to the physical
60 * screen visible to the user, not to any unseen memory.) If
61 * the terminal has memory relative cursor addressing, that can
64 * The parameter mechanism uses a stack and special %
65 * codes to manipulate it. Typically a sequence will push one
66 * of the parameters onto the stack and then print it in some
67 * format. Often more complex operations are necessary.
69 * The % encodings have the following meanings:
72 * %c print pop() like %c in printf()
73 * %s print pop() like %s in printf()
74 * %[[:]flags][width[.precision]][doxXs]
75 * as in printf, flags are [-+#] and space
76 * The ':' is used to avoid making %+ or %-
77 * patterns (see below).
79 * %p[1-9] push ith parm
80 * %P[a-z] set dynamic variable [a-z] to pop()
81 * %g[a-z] get dynamic variable [a-z] and push it
82 * %P[A-Z] set static variable [A-Z] to pop()
83 * %g[A-Z] get static variable [A-Z] and push it
85 * %'c' push char constant c
86 * %{nn} push integer constant nn
89 * arithmetic (%m is mod): push(pop() op pop())
90 * %& %| %^ bit operations: push(pop() op pop())
91 * %= %> %< logical operations: push(pop() op pop())
92 * %A %O logical and & or operations for conditionals
93 * %! %~ unary operations push(op pop())
94 * %i add 1 to first two parms (for ANSI terminals)
96 * %? expr %t thenpart %e elsepart %;
97 * if-then-else, %e elsepart is optional.
98 * else-if's are possible ala Algol 68:
99 * %? c1 %t b1 %e c2 %t b2 %e c3 %t b3 %e c4 %t b4 %e b5 %;
101 * For those of the above operators which are binary and not commutative,
102 * the stack works in the usual way, with
104 * resulting in x mod y, not the reverse.
107 NCURSES_EXPORT_VAR(int) _nc_tparm_err = 0;
109 #define TPS(var) _nc_prescreen.tparm_state.var
110 #define popcount _nc_popcount /* workaround for NetBSD 6.0 defect */
116 if (TPS(out_buff) != 0) {
117 FreeAndNull(TPS(out_buff));
120 FreeAndNull(TPS(fmt_buff));
126 static NCURSES_INLINE void
127 get_space(size_t need)
129 need += TPS(out_used);
130 if (need > TPS(out_size)) {
131 TPS(out_size) = need * 2;
132 TYPE_REALLOC(char, TPS(out_size), TPS(out_buff));
136 static NCURSES_INLINE void
137 save_text(const char *fmt, const char *s, int len)
139 size_t s_len = strlen(s);
140 if (len > (int) s_len)
141 s_len = (size_t) len;
143 get_space(s_len + 1);
145 _nc_SPRINTF(TPS(out_buff) + TPS(out_used),
146 _nc_SLIMIT(TPS(out_size) - TPS(out_used))
148 TPS(out_used) += strlen(TPS(out_buff) + TPS(out_used));
151 static NCURSES_INLINE void
152 save_number(const char *fmt, int number, int len)
155 len = 30; /* actually log10(MAX_INT)+1 */
157 get_space((size_t) len + 1);
159 _nc_SPRINTF(TPS(out_buff) + TPS(out_used),
160 _nc_SLIMIT(TPS(out_size) - TPS(out_used))
162 TPS(out_used) += strlen(TPS(out_buff) + TPS(out_used));
165 static NCURSES_INLINE void
170 get_space((size_t) 1);
171 TPS(out_buff)[TPS(out_used)++] = (char) c;
174 static NCURSES_INLINE void
177 if (TPS(stack_ptr) < STACKSIZE) {
178 TPS(stack)[TPS(stack_ptr)].num_type = TRUE;
179 TPS(stack)[TPS(stack_ptr)].data.num = x;
182 DEBUG(2, ("npush: stack overflow: %s", _nc_visbuf(TPS(tparam_base))));
187 static NCURSES_INLINE int
191 if (TPS(stack_ptr) > 0) {
193 if (TPS(stack)[TPS(stack_ptr)].num_type)
194 result = TPS(stack)[TPS(stack_ptr)].data.num;
196 DEBUG(2, ("npop: stack underflow: %s", _nc_visbuf(TPS(tparam_base))));
202 static NCURSES_INLINE void
205 if (TPS(stack_ptr) < STACKSIZE) {
206 TPS(stack)[TPS(stack_ptr)].num_type = FALSE;
207 TPS(stack)[TPS(stack_ptr)].data.str = x;
210 DEBUG(2, ("spush: stack overflow: %s", _nc_visbuf(TPS(tparam_base))));
215 static NCURSES_INLINE char *
218 static char dummy[] = ""; /* avoid const-cast */
219 char *result = dummy;
220 if (TPS(stack_ptr) > 0) {
222 if (!TPS(stack)[TPS(stack_ptr)].num_type
223 && TPS(stack)[TPS(stack_ptr)].data.str != 0)
224 result = TPS(stack)[TPS(stack_ptr)].data.str;
226 DEBUG(2, ("spop: stack underflow: %s", _nc_visbuf(TPS(tparam_base))));
232 static NCURSES_INLINE const char *
233 parse_format(const char *s, char *format, int *len)
238 bool allowminus = FALSE;
248 while (*s != '\0' && !done) {
250 case 'c': /* FALLTHRU */
251 case 'd': /* FALLTHRU */
252 case 'o': /* FALLTHRU */
253 case 'x': /* FALLTHRU */
254 case 'X': /* FALLTHRU */
256 #ifdef EXP_XTERM_1005
266 } else { /* value before '.' is the width */
290 if (isdigit(UChar(*s))) {
291 value = (value * 10) + (*s - '0');
302 * If we found an error, ignore (and remove) the flags.
305 my_width = my_prec = value = 0;
312 * Any value after '.' is the precision. If we did not see '.', then
313 * the value is the width.
321 /* return maximum string length in print */
322 *len = (my_width > my_prec) ? my_width : my_prec;
327 #define isUPPER(c) ((c) >= 'A' && (c) <= 'Z')
328 #define isLOWER(c) ((c) >= 'a' && (c) <= 'z')
329 #define tc_BUMP() if (level < 0 && number < 2) number++
332 * Analyze the string to see how many parameters we need from the varargs list,
333 * and what their types are. We will only accept string parameters if they
334 * appear as a %l or %s format following an explicit parameter reference (e.g.,
335 * %p2%s). All other parameters are numbers.
337 * 'number' counts coarsely the number of pop's we see in the string, and
338 * 'popcount' shows the highest parameter number in the string. We would like
339 * to simply use the latter count, but if we are reading termcap strings, there
340 * may be cases that we cannot see the explicit parameter numbers.
343 _nc_tparm_analyze(const char *string, char *p_is_s[NUM_PARM], int *popcount)
351 const char *cp = string;
352 static char dummy[] = "";
357 if ((len2 = strlen(cp)) + 2 > TPS(fmt_size)) {
358 TPS(fmt_size) += len2 + 2;
359 TPS(fmt_buff) = typeRealloc(char, TPS(fmt_size), TPS(fmt_buff));
360 if (TPS(fmt_buff) == 0)
364 memset(p_is_s, 0, sizeof(p_is_s[0]) * NUM_PARM);
367 while ((cp - string) < (int) len2) {
370 cp = parse_format(cp, TPS(fmt_buff), &len);
375 case 'd': /* FALLTHRU */
376 case 'o': /* FALLTHRU */
377 case 'x': /* FALLTHRU */
378 case 'X': /* FALLTHRU */
379 case 'c': /* FALLTHRU */
380 #ifdef EXP_XTERM_1005
394 p_is_s[lastpop - 1] = dummy;
401 i = (UChar(*cp) - '0');
402 if (i >= 0 && i <= NUM_PARM) {
405 if (lastpop > *popcount)
428 while (isdigit(UChar(*cp))) {
447 level -= 1; /* pop 2, operate, push 1 */
458 /* will add 1 to first (usually two) parameters */
466 if (number > NUM_PARM)
471 static NCURSES_INLINE char *
472 tparam_internal(int use_TPARM_ARG, const char *string, va_list ap)
474 char *p_is_s[NUM_PARM];
475 TPARM_ARG param[NUM_PARM];
483 const char *cp = string;
486 bool incremented_two;
489 TR(TRACE_CALLS, ("%s: format is null", TPS(tname)));
497 * Find the highest parameter-number referred to in the format string.
498 * Use this value to limit the number of arguments copied from the
499 * variable-length argument list.
501 number = _nc_tparm_analyze(cp, p_is_s, &popcount);
502 if (TPS(fmt_buff) == 0) {
503 TR(TRACE_CALLS, ("%s: error in analysis", TPS(tname)));
507 incremented_two = FALSE;
509 if (number > NUM_PARM)
511 if (popcount > NUM_PARM)
513 num_args = max(popcount, number);
515 for (i = 0; i < num_args; i++) {
517 * A few caps (such as plab_norm) have string-valued parms.
518 * We'll have to assume that the caller knows the difference, since
519 * a char* and an int may not be the same size on the stack. The
520 * normal prototype for this uses 9 long's, which is consistent with
521 * our va_arg() usage.
523 if (p_is_s[i] != 0) {
524 p_is_s[i] = va_arg(ap, char *);
526 } else if (use_TPARM_ARG) {
527 param[i] = va_arg(ap, TPARM_ARG);
529 param[i] = (TPARM_ARG) va_arg(ap, int);
534 * This is a termcap compatibility hack. If there are no explicit pop
535 * operations in the string, load the stack in such a way that
536 * successive pops will grab successive parameters. That will make
537 * the expansion of (for example) \E[%d;%dH work correctly in termcap
538 * style, which means tparam() will expand termcap strings OK.
541 termcap_hack = FALSE;
544 for (i = number - 1; i >= 0; i--) {
548 npush((int) param[i]);
552 if (USE_TRACEF(TRACE_CALLS)) {
553 for (i = 0; i < num_args; i++) {
554 if (p_is_s[i] != 0) {
555 save_text(", %s", _nc_visbuf(p_is_s[i]), 0);
556 } else if ((long) param[i] > MAX_OF_TYPE(NCURSES_INT2) ||
557 (long) param[i] < 0) {
558 _tracef("BUG: problem with tparm parameter #%d of %d",
562 save_number(", %d", (int) param[i], 0);
565 _tracef(T_CALLED("%s(%s%s)"), TPS(tname), _nc_visbuf(cp), TPS(out_buff));
567 _nc_unlock_global(tracef);
571 while ((cp - string) < (int) len2) {
573 save_char(UChar(*cp));
575 TPS(tparam_base) = cp++;
576 cp = parse_format(cp, TPS(fmt_buff), &len);
584 case 'd': /* FALLTHRU */
585 case 'o': /* FALLTHRU */
586 case 'x': /* FALLTHRU */
587 case 'X': /* FALLTHRU */
588 save_number(TPS(fmt_buff), npop(), len);
591 case 'c': /* FALLTHRU */
595 #ifdef EXP_XTERM_1005
598 unsigned char target[10];
599 unsigned source = (unsigned) npop();
600 int rc = _nc_conv_to_utf8(target, source, (unsigned)
603 for (n = 0; n < rc; ++n) {
604 save_char(target[n]);
610 npush((int) strlen(spop()));
614 save_text(TPS(fmt_buff), spop(), len);
619 i = (UChar(*cp) - '1');
620 if (i >= 0 && i < NUM_PARM) {
624 npush((int) param[i]);
632 i = (UChar(*cp) - 'A');
633 TPS(static_vars)[i] = npop();
634 } else if (isLOWER(*cp)) {
635 i = (UChar(*cp) - 'a');
636 TPS(dynamic_var)[i] = npop();
643 i = (UChar(*cp) - 'A');
644 npush(TPS(static_vars)[i]);
645 } else if (isLOWER(*cp)) {
646 i = (UChar(*cp) - 'a');
647 npush(TPS(dynamic_var)[i]);
660 while (isdigit(UChar(*cp))) {
661 number = (number * 10) + (UChar(*cp) - '0');
668 npush(npop() + npop());
678 npush(npop() * npop());
684 npush(y ? (x / y) : 0);
690 npush(y ? (x % y) : 0);
706 npush(npop() & npop());
710 npush(npop() | npop());
714 npush(npop() ^ npop());
745 * Increment the first two parameters -- if they are numbers
746 * rather than strings. As a side effect, assign into the
747 * stack; if this is termcap, then the stack was populated
748 * using the termcap hack above rather than via the terminfo
751 if (!incremented_two) {
752 incremented_two = TRUE;
753 if (p_is_s[0] == 0) {
756 TPS(stack)[0].data.num = (int) param[0];
758 if (p_is_s[1] == 0) {
761 TPS(stack)[1].data.num = (int) param[1];
772 /* scan forward for %e or %; at level zero */
780 else if (*cp == ';') {
785 } else if (*cp == 'e' && level == 0)
796 /* scan forward for a %; at level zero */
804 else if (*cp == ';') {
820 } /* endswitch (*cp) */
821 } /* endelse (*cp == '%') */
827 } /* endwhile (*cp) */
829 get_space((size_t) 1);
830 TPS(out_buff)[TPS(out_used)] = '\0';
832 T((T_RETURN("%s"), _nc_visbuf(TPS(out_buff))));
833 return (TPS(out_buff));
836 #if NCURSES_TPARM_VARARGS
837 #define tparm_varargs tparm
839 #define tparm_proto tparm
842 NCURSES_EXPORT(char *)
843 tparm_varargs(const char *string,...)
849 va_start(ap, string);
851 TPS(tname) = "tparm";
853 result = tparam_internal(TRUE, string, ap);
858 #if !NCURSES_TPARM_VARARGS
859 NCURSES_EXPORT(char *)
860 tparm_proto(const char *string,
871 return tparm_varargs(string, a1, a2, a3, a4, a5, a6, a7, a8, a9);
873 #endif /* NCURSES_TPARM_VARARGS */
875 NCURSES_EXPORT(char *)
876 tiparm(const char *string,...)
882 va_start(ap, string);
884 TPS(tname) = "tiparm";
886 result = tparam_internal(FALSE, string, ap);