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