]> ncurses.scripts.mit.edu Git - ncurses.git/blob - lib_tparm.c
d11fcf80cfbfd66f2dde42f6a7dfbc7396ded591
[ncurses.git] / lib_tparm.c
1 /****************************************************************************
2  * Copyright (c) 1998-2006,2007 Free Software Foundation, Inc.              *
3  *                                                                          *
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:                 *
11  *                                                                          *
12  * The above copyright notice and this permission notice shall be included  *
13  * in all copies or substantial portions of the Software.                   *
14  *                                                                          *
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.                               *
22  *                                                                          *
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       *
26  * authorization.                                                           *
27  ****************************************************************************/
28
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  ****************************************************************************/
34
35 /*
36  *      tparm.c
37  *
38  */
39
40 #include <curses.priv.h>
41
42 #include <ctype.h>
43 #include <term.h>
44 #include <tic.h>
45
46 MODULE_ID("$Id: lib_tparm.c,v 1.74 2007/09/29 20:37:13 tom Exp $")
47
48 /*
49  *      char *
50  *      tparm(string, ...)
51  *
52  *      Substitute the given parameters into the given string by the following
53  *      rules (taken from terminfo(5)):
54  *
55  *           Cursor addressing and other strings  requiring  parame-
56  *      ters in the terminal are described by a parameterized string
57  *      capability, with like escapes %x in  it.   For  example,  to
58  *      address  the  cursor, the cup capability is given, using two
59  *      parameters: the row and column to  address  to.   (Rows  and
60  *      columns  are  numbered  from  zero and refer to the physical
61  *      screen visible to the user, not to any  unseen  memory.)  If
62  *      the terminal has memory relative cursor addressing, that can
63  *      be indicated by
64  *
65  *           The parameter mechanism uses  a  stack  and  special  %
66  *      codes  to manipulate it.  Typically a sequence will push one
67  *      of the parameters onto the stack and then print it  in  some
68  *      format.  Often more complex operations are necessary.
69  *
70  *           The % encodings have the following meanings:
71  *
72  *           %%        outputs `%'
73  *           %c        print pop() like %c in printf()
74  *           %s        print pop() like %s in printf()
75  *           %[[:]flags][width[.precision]][doxXs]
76  *                     as in printf, flags are [-+#] and space
77  *                     The ':' is used to avoid making %+ or %-
78  *                     patterns (see below).
79  *
80  *           %p[1-9]   push ith parm
81  *           %P[a-z]   set dynamic variable [a-z] to pop()
82  *           %g[a-z]   get dynamic variable [a-z] and push it
83  *           %P[A-Z]   set static variable [A-Z] to pop()
84  *           %g[A-Z]   get static variable [A-Z] and push it
85  *           %l        push strlen(pop)
86  *           %'c'      push char constant c
87  *           %{nn}     push integer constant nn
88  *
89  *           %+ %- %* %/ %m
90  *                     arithmetic (%m is mod): push(pop() op pop())
91  *           %& %| %^  bit operations: push(pop() op pop())
92  *           %= %> %<  logical operations: push(pop() op pop())
93  *           %A %O     logical and & or operations for conditionals
94  *           %! %~     unary operations push(op pop())
95  *           %i        add 1 to first two parms (for ANSI terminals)
96  *
97  *           %? expr %t thenpart %e elsepart %;
98  *                     if-then-else, %e elsepart is optional.
99  *                     else-if's are possible ala Algol 68:
100  *                     %? c1 %t b1 %e c2 %t b2 %e c3 %t b3 %e c4 %t b4 %e b5 %;
101  *
102  *      For those of the above operators which are binary and not commutative,
103  *      the stack works in the usual way, with
104  *                      %gx %gy %m
105  *      resulting in x mod y, not the reverse.
106  */
107
108 NCURSES_EXPORT_VAR(int) _nc_tparm_err = 0;
109
110 #define TPS(var) _nc_prescreen.tparm_state.var
111
112 #if NO_LEAKS
113 NCURSES_EXPORT(void)
114 _nc_free_tparm(void)
115 {
116     if (TPS(out_buff) != 0) {
117         FreeAndNull(TPS(out_buff));
118         TPS(out_size) = 0;
119         TPS(out_used) = 0;
120         FreeAndNull(TPS(fmt_buff));
121         TPS(fmt_size) = 0;
122     }
123 }
124 #endif
125
126 static NCURSES_INLINE void
127 get_space(size_t need)
128 {
129     need += TPS(out_used);
130     if (need > TPS(out_size)) {
131         TPS(out_size) = need * 2;
132         TPS(out_buff) = typeRealloc(char, TPS(out_size), TPS(out_buff));
133         if (TPS(out_buff) == 0)
134             _nc_err_abort(MSG_NO_MEMORY);
135     }
136 }
137
138 static NCURSES_INLINE void
139 save_text(const char *fmt, const char *s, int len)
140 {
141     size_t s_len = strlen(s);
142     if (len > (int) s_len)
143         s_len = len;
144
145     get_space(s_len + 1);
146
147     (void) sprintf(TPS(out_buff) + TPS(out_used), fmt, s);
148     TPS(out_used) += strlen(TPS(out_buff) + TPS(out_used));
149 }
150
151 static NCURSES_INLINE void
152 save_number(const char *fmt, int number, int len)
153 {
154     if (len < 30)
155         len = 30;               /* actually log10(MAX_INT)+1 */
156
157     get_space((unsigned) len + 1);
158
159     (void) sprintf(TPS(out_buff) + TPS(out_used), fmt, number);
160     TPS(out_used) += strlen(TPS(out_buff) + TPS(out_used));
161 }
162
163 static NCURSES_INLINE void
164 save_char(int c)
165 {
166     if (c == 0)
167         c = 0200;
168     get_space(1);
169     TPS(out_buff)[TPS(out_used)++] = c;
170 }
171
172 static NCURSES_INLINE void
173 npush(int x)
174 {
175     if (TPS(stack_ptr) < STACKSIZE) {
176         TPS(stack)[TPS(stack_ptr)].num_type = TRUE;
177         TPS(stack)[TPS(stack_ptr)].data.num = x;
178         TPS(stack_ptr)++;
179     } else {
180         DEBUG(2, ("npush: stack overflow: %s", _nc_visbuf(TPS(tparam_base))));
181         _nc_tparm_err++;
182     }
183 }
184
185 static NCURSES_INLINE int
186 npop(void)
187 {
188     int result = 0;
189     if (TPS(stack_ptr) > 0) {
190         TPS(stack_ptr)--;
191         if (TPS(stack)[TPS(stack_ptr)].num_type)
192             result = TPS(stack)[TPS(stack_ptr)].data.num;
193     } else {
194         DEBUG(2, ("npop: stack underflow: %s", _nc_visbuf(TPS(tparam_base))));
195         _nc_tparm_err++;
196     }
197     return result;
198 }
199
200 static NCURSES_INLINE void
201 spush(char *x)
202 {
203     if (TPS(stack_ptr) < STACKSIZE) {
204         TPS(stack)[TPS(stack_ptr)].num_type = FALSE;
205         TPS(stack)[TPS(stack_ptr)].data.str = x;
206         TPS(stack_ptr)++;
207     } else {
208         DEBUG(2, ("spush: stack overflow: %s", _nc_visbuf(TPS(tparam_base))));
209         _nc_tparm_err++;
210     }
211 }
212
213 static NCURSES_INLINE char *
214 spop(void)
215 {
216     static char dummy[] = "";   /* avoid const-cast */
217     char *result = dummy;
218     if (TPS(stack_ptr) > 0) {
219         TPS(stack_ptr)--;
220         if (!TPS(stack)[TPS(stack_ptr)].num_type
221             && TPS(stack)[TPS(stack_ptr)].data.str != 0)
222             result = TPS(stack)[TPS(stack_ptr)].data.str;
223     } else {
224         DEBUG(2, ("spop: stack underflow: %s", _nc_visbuf(TPS(tparam_base))));
225         _nc_tparm_err++;
226     }
227     return result;
228 }
229
230 static NCURSES_INLINE const char *
231 parse_format(const char *s, char *format, int *len)
232 {
233     *len = 0;
234     if (format != 0) {
235         bool done = FALSE;
236         bool allowminus = FALSE;
237         bool dot = FALSE;
238         bool err = FALSE;
239         char *fmt = format;
240         int my_width = 0;
241         int my_prec = 0;
242         int value = 0;
243
244         *len = 0;
245         *format++ = '%';
246         while (*s != '\0' && !done) {
247             switch (*s) {
248             case 'c':           /* FALLTHRU */
249             case 'd':           /* FALLTHRU */
250             case 'o':           /* FALLTHRU */
251             case 'x':           /* FALLTHRU */
252             case 'X':           /* FALLTHRU */
253             case 's':
254                 *format++ = *s;
255                 done = TRUE;
256                 break;
257             case '.':
258                 *format++ = *s++;
259                 if (dot) {
260                     err = TRUE;
261                 } else {        /* value before '.' is the width */
262                     dot = TRUE;
263                     my_width = value;
264                 }
265                 value = 0;
266                 break;
267             case '#':
268                 *format++ = *s++;
269                 break;
270             case ' ':
271                 *format++ = *s++;
272                 break;
273             case ':':
274                 s++;
275                 allowminus = TRUE;
276                 break;
277             case '-':
278                 if (allowminus) {
279                     *format++ = *s++;
280                 } else {
281                     done = TRUE;
282                 }
283                 break;
284             default:
285                 if (isdigit(UChar(*s))) {
286                     value = (value * 10) + (*s - '0');
287                     if (value > 10000)
288                         err = TRUE;
289                     *format++ = *s++;
290                 } else {
291                     done = TRUE;
292                 }
293             }
294         }
295
296         /*
297          * If we found an error, ignore (and remove) the flags.
298          */
299         if (err) {
300             my_width = my_prec = value = 0;
301             format = fmt;
302             *format++ = '%';
303             *format++ = *s;
304         }
305
306         /*
307          * Any value after '.' is the precision.  If we did not see '.', then
308          * the value is the width.
309          */
310         if (dot)
311             my_prec = value;
312         else
313             my_width = value;
314
315         *format = '\0';
316         /* return maximum string length in print */
317         *len = (my_width > my_prec) ? my_width : my_prec;
318     }
319     return s;
320 }
321
322 #define isUPPER(c) ((c) >= 'A' && (c) <= 'Z')
323 #define isLOWER(c) ((c) >= 'a' && (c) <= 'z')
324
325 /*
326  * Analyze the string to see how many parameters we need from the varargs list,
327  * and what their types are.  We will only accept string parameters if they
328  * appear as a %l or %s format following an explicit parameter reference (e.g.,
329  * %p2%s).  All other parameters are numbers.
330  *
331  * 'number' counts coarsely the number of pop's we see in the string, and
332  * 'popcount' shows the highest parameter number in the string.  We would like
333  * to simply use the latter count, but if we are reading termcap strings, there
334  * may be cases that we cannot see the explicit parameter numbers.
335  */
336 NCURSES_EXPORT(int)
337 _nc_tparm_analyze(const char *string, char *p_is_s[NUM_PARM], int *popcount)
338 {
339     size_t len2;
340     int i;
341     int lastpop = -1;
342     int len;
343     int number = 0;
344     const char *cp = string;
345     static char dummy[] = "";
346
347     if (cp == 0)
348         return 0;
349
350     if ((len2 = strlen(cp)) > TPS(fmt_size)) {
351         TPS(fmt_size) = len2 + TPS(fmt_size) + 2;
352         TPS(fmt_buff) = typeRealloc(char, TPS(fmt_size), TPS(fmt_buff));
353         if (TPS(fmt_buff) == 0)
354             return 0;
355     }
356
357     memset(p_is_s, 0, sizeof(p_is_s[0]) * NUM_PARM);
358     *popcount = 0;
359
360     while ((cp - string) < (int) len2) {
361         if (*cp == '%') {
362             cp++;
363             cp = parse_format(cp, TPS(fmt_buff), &len);
364             switch (*cp) {
365             default:
366                 break;
367
368             case 'd':           /* FALLTHRU */
369             case 'o':           /* FALLTHRU */
370             case 'x':           /* FALLTHRU */
371             case 'X':           /* FALLTHRU */
372             case 'c':           /* FALLTHRU */
373                 if (lastpop <= 0)
374                     number++;
375                 lastpop = -1;
376                 break;
377
378             case 'l':
379             case 's':
380                 if (lastpop > 0)
381                     p_is_s[lastpop - 1] = dummy;
382                 ++number;
383                 break;
384
385             case 'p':
386                 cp++;
387                 i = (UChar(*cp) - '0');
388                 if (i >= 0 && i <= NUM_PARM) {
389                     lastpop = i;
390                     if (lastpop > *popcount)
391                         *popcount = lastpop;
392                 }
393                 break;
394
395             case 'P':
396                 ++number;
397                 ++cp;
398                 break;
399
400             case 'g':
401                 cp++;
402                 break;
403
404             case S_QUOTE:
405                 cp += 2;
406                 lastpop = -1;
407                 break;
408
409             case L_BRACE:
410                 cp++;
411                 while (isdigit(UChar(*cp))) {
412                     cp++;
413                 }
414                 break;
415
416             case '+':
417             case '-':
418             case '*':
419             case '/':
420             case 'm':
421             case 'A':
422             case 'O':
423             case '&':
424             case '|':
425             case '^':
426             case '=':
427             case '<':
428             case '>':
429                 lastpop = -1;
430                 number += 2;
431                 break;
432
433             case '!':
434             case '~':
435                 lastpop = -1;
436                 ++number;
437                 break;
438
439             case 'i':
440                 /* will add 1 to first (usually two) parameters */
441                 break;
442             }
443         }
444         if (*cp != '\0')
445             cp++;
446     }
447
448     if (number > NUM_PARM)
449         number = NUM_PARM;
450     return number;
451 }
452
453 static NCURSES_INLINE char *
454 tparam_internal(const char *string, va_list ap)
455 {
456     char *p_is_s[NUM_PARM];
457     TPARM_ARG param[NUM_PARM];
458     int popcount;
459     int number;
460     int len;
461     int level;
462     int x, y;
463     int i;
464     const char *cp = string;
465     size_t len2;
466
467     if (cp == NULL)
468         return NULL;
469
470     TPS(out_used) = 0;
471     len2 = strlen(cp);
472
473     /*
474      * Find the highest parameter-number referred to in the format string.
475      * Use this value to limit the number of arguments copied from the
476      * variable-length argument list.
477      */
478     number = _nc_tparm_analyze(cp, p_is_s, &popcount);
479     if (TPS(fmt_buff) == 0)
480         return NULL;
481
482     for (i = 0; i < max(popcount, number); i++) {
483         /*
484          * A few caps (such as plab_norm) have string-valued parms.
485          * We'll have to assume that the caller knows the difference, since
486          * a char* and an int may not be the same size on the stack.  The
487          * normal prototype for this uses 9 long's, which is consistent with
488          * our va_arg() usage.
489          */
490         if (p_is_s[i] != 0) {
491             p_is_s[i] = va_arg(ap, char *);
492         } else {
493             param[i] = va_arg(ap, TPARM_ARG);
494         }
495     }
496
497     /*
498      * This is a termcap compatibility hack.  If there are no explicit pop
499      * operations in the string, load the stack in such a way that
500      * successive pops will grab successive parameters.  That will make
501      * the expansion of (for example) \E[%d;%dH work correctly in termcap
502      * style, which means tparam() will expand termcap strings OK.
503      */
504     TPS(stack_ptr) = 0;
505     if (popcount == 0) {
506         popcount = number;
507         for (i = number - 1; i >= 0; i--)
508             npush(param[i]);
509     }
510 #ifdef TRACE
511     if (USE_TRACEF(TRACE_CALLS)) {
512         for (i = 0; i < popcount; i++) {
513             if (p_is_s[i] != 0)
514                 save_text(", %s", _nc_visbuf(p_is_s[i]), 0);
515             else
516                 save_number(", %d", param[i], 0);
517         }
518         _tracef(T_CALLED("%s(%s%s)"), TPS(tname), _nc_visbuf(cp), TPS(out_buff));
519         TPS(out_used) = 0;
520         _nc_unlock_global(tracef);
521     }
522 #endif /* TRACE */
523
524     while ((cp - string) < (int) len2) {
525         if (*cp != '%') {
526             save_char(UChar(*cp));
527         } else {
528             TPS(tparam_base) = cp++;
529             cp = parse_format(cp, TPS(fmt_buff), &len);
530             switch (*cp) {
531             default:
532                 break;
533             case '%':
534                 save_char('%');
535                 break;
536
537             case 'd':           /* FALLTHRU */
538             case 'o':           /* FALLTHRU */
539             case 'x':           /* FALLTHRU */
540             case 'X':           /* FALLTHRU */
541                 save_number(TPS(fmt_buff), npop(), len);
542                 break;
543
544             case 'c':           /* FALLTHRU */
545                 save_char(npop());
546                 break;
547
548             case 'l':
549                 save_number("%d", (int) strlen(spop()), 0);
550                 break;
551
552             case 's':
553                 save_text(TPS(fmt_buff), spop(), len);
554                 break;
555
556             case 'p':
557                 cp++;
558                 i = (UChar(*cp) - '1');
559                 if (i >= 0 && i < NUM_PARM) {
560                     if (p_is_s[i])
561                         spush(p_is_s[i]);
562                     else
563                         npush(param[i]);
564                 }
565                 break;
566
567             case 'P':
568                 cp++;
569                 if (isUPPER(*cp)) {
570                     i = (UChar(*cp) - 'A');
571                     TPS(static_vars)[i] = npop();
572                 } else if (isLOWER(*cp)) {
573                     i = (UChar(*cp) - 'a');
574                     TPS(dynamic_var)[i] = npop();
575                 }
576                 break;
577
578             case 'g':
579                 cp++;
580                 if (isUPPER(*cp)) {
581                     i = (UChar(*cp) - 'A');
582                     npush(TPS(static_vars)[i]);
583                 } else if (isLOWER(*cp)) {
584                     i = (UChar(*cp) - 'a');
585                     npush(TPS(dynamic_var)[i]);
586                 }
587                 break;
588
589             case S_QUOTE:
590                 cp++;
591                 npush(UChar(*cp));
592                 cp++;
593                 break;
594
595             case L_BRACE:
596                 number = 0;
597                 cp++;
598                 while (isdigit(UChar(*cp))) {
599                     number = (number * 10) + (UChar(*cp) - '0');
600                     cp++;
601                 }
602                 npush(number);
603                 break;
604
605             case '+':
606                 npush(npop() + npop());
607                 break;
608
609             case '-':
610                 y = npop();
611                 x = npop();
612                 npush(x - y);
613                 break;
614
615             case '*':
616                 npush(npop() * npop());
617                 break;
618
619             case '/':
620                 y = npop();
621                 x = npop();
622                 npush(y ? (x / y) : 0);
623                 break;
624
625             case 'm':
626                 y = npop();
627                 x = npop();
628                 npush(y ? (x % y) : 0);
629                 break;
630
631             case 'A':
632                 npush(npop() && npop());
633                 break;
634
635             case 'O':
636                 npush(npop() || npop());
637                 break;
638
639             case '&':
640                 npush(npop() & npop());
641                 break;
642
643             case '|':
644                 npush(npop() | npop());
645                 break;
646
647             case '^':
648                 npush(npop() ^ npop());
649                 break;
650
651             case '=':
652                 y = npop();
653                 x = npop();
654                 npush(x == y);
655                 break;
656
657             case '<':
658                 y = npop();
659                 x = npop();
660                 npush(x < y);
661                 break;
662
663             case '>':
664                 y = npop();
665                 x = npop();
666                 npush(x > y);
667                 break;
668
669             case '!':
670                 npush(!npop());
671                 break;
672
673             case '~':
674                 npush(~npop());
675                 break;
676
677             case 'i':
678                 if (p_is_s[0] == 0)
679                     param[0]++;
680                 if (p_is_s[1] == 0)
681                     param[1]++;
682                 break;
683
684             case '?':
685                 break;
686
687             case 't':
688                 x = npop();
689                 if (!x) {
690                     /* scan forward for %e or %; at level zero */
691                     cp++;
692                     level = 0;
693                     while (*cp) {
694                         if (*cp == '%') {
695                             cp++;
696                             if (*cp == '?')
697                                 level++;
698                             else if (*cp == ';') {
699                                 if (level > 0)
700                                     level--;
701                                 else
702                                     break;
703                             } else if (*cp == 'e' && level == 0)
704                                 break;
705                         }
706
707                         if (*cp)
708                             cp++;
709                     }
710                 }
711                 break;
712
713             case 'e':
714                 /* scan forward for a %; at level zero */
715                 cp++;
716                 level = 0;
717                 while (*cp) {
718                     if (*cp == '%') {
719                         cp++;
720                         if (*cp == '?')
721                             level++;
722                         else if (*cp == ';') {
723                             if (level > 0)
724                                 level--;
725                             else
726                                 break;
727                         }
728                     }
729
730                     if (*cp)
731                         cp++;
732                 }
733                 break;
734
735             case ';':
736                 break;
737
738             }                   /* endswitch (*cp) */
739         }                       /* endelse (*cp == '%') */
740
741         if (*cp == '\0')
742             break;
743
744         cp++;
745     }                           /* endwhile (*cp) */
746
747     get_space(1);
748     TPS(out_buff)[TPS(out_used)] = '\0';
749
750     T((T_RETURN("%s"), _nc_visbuf(TPS(out_buff))));
751     return (TPS(out_buff));
752 }
753
754 #if NCURSES_TPARM_VARARGS
755 #define tparm_varargs tparm
756 #else
757 #define tparm_proto tparm
758 #endif
759
760 NCURSES_EXPORT(char *)
761 tparm_varargs(NCURSES_CONST char *string,...)
762 {
763     va_list ap;
764     char *result;
765
766     _nc_tparm_err = 0;
767     va_start(ap, string);
768 #ifdef TRACE
769     TPS(tname) = "tparm";
770 #endif /* TRACE */
771     result = tparam_internal(string, ap);
772     va_end(ap);
773     return result;
774 }
775
776 #if !NCURSES_TPARM_VARARGS
777 NCURSES_EXPORT(char *)
778 tparm_proto(NCURSES_CONST char *string,
779             TPARM_ARG a1,
780             TPARM_ARG a2,
781             TPARM_ARG a3,
782             TPARM_ARG a4,
783             TPARM_ARG a5,
784             TPARM_ARG a6,
785             TPARM_ARG a7,
786             TPARM_ARG a8,
787             TPARM_ARG a9)
788 {
789     return tparm_varargs(string, a1, a2, a3, a4, a5, a6, a7, a8, a9);
790 }
791 #endif /* NCURSES_TPARM_VARARGS */