xref: /src/contrib/ncurses/ncurses/tinfo/captoinfo.c (revision 68ad2b0d7af2a3571c4abac9afa712f9b09b721c)
1 /****************************************************************************
2  * Copyright 2018-2024,2025 Thomas E. Dickey                                *
3  * Copyright 1998-2016,2017 Free Software Foundation, Inc.                  *
4  *                                                                          *
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:                 *
12  *                                                                          *
13  * The above copyright notice and this permission notice shall be included  *
14  * in all copies or substantial portions of the Software.                   *
15  *                                                                          *
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.                               *
23  *                                                                          *
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       *
27  * authorization.                                                           *
28  ****************************************************************************/
29 
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  ****************************************************************************/
35 
36 /*
37  *	captoinfo.c
38  *
39  *	Provide conversion in both directions between termcap and terminfo.
40  *
41  * cap-to-info --- conversion between termcap and terminfo formats
42  *
43  *	The captoinfo() code was swiped from Ross Ridge's mytinfo package,
44  *	adapted to fit ncurses by Eric S. Raymond <esr@snark.thyrsus.com>.
45  *
46  *	It has just one entry point:
47  *
48  *	char *_nc_captoinfo(n, s, parameterized)
49  *
50  *	Convert value s for termcap string capability named n into terminfo
51  *	format.
52  *
53  *	This code recognizes all the standard 4.4BSD %-escapes:
54  *
55  *	%%       output `%'
56  *	%d       output value as in printf %d
57  *	%2       output value as in printf %2d
58  *	%3       output value as in printf %3d
59  *	%.       output value as in printf %c
60  *	%+x      add x to value, then do %.
61  *	%>xy     if value > x then add y, no output
62  *	%r       reverse order of two parameters, no output
63  *	%i       increment by one, no output
64  *	%n       exclusive-or all parameters with 0140 (Datamedia 2500)
65  *	%B       BCD (16*(value/10)) + (value%10), no output
66  *	%D       Reverse coding (value - 2*(value%16)), no output (Delta Data).
67  *
68  *	Also, %02 and %03 are accepted as synonyms for %2 and %3.
69  *
70  *	Besides all the standard termcap escapes, this translator understands
71  *	the following extended escapes:
72  *
73  *	used by GNU Emacs termcap libraries
74  *		%a[+*-/=][cp]x	GNU arithmetic.
75  *		%m		xor the first two parameters by 0177
76  *		%b		backup to previous parameter
77  *		%f		skip this parameter
78  *
79  *	used by the University of Waterloo (MFCF) termcap libraries
80  *		%-x	 subtract parameter FROM char x and output it as a char
81  *		%ax	 add the character x to parameter
82  *
83  *	If #define WATERLOO is on, also enable these translations:
84  *
85  *		%sx	 subtract parameter FROM the character x
86  *
87  *	By default, this Waterloo translations are not compiled in, because
88  *	the Waterloo %s conflicts with the way terminfo uses %s in strings for
89  *	function programming.
90  *
91  *	Note the two definitions of %a: the GNU definition is translated if the
92  *	characters after the 'a' are valid for it, otherwise the UW definition
93  *	is translated.
94  */
95 
96 #include <curses.priv.h>
97 
98 #include <ctype.h>
99 #include <tic.h>
100 
101 MODULE_ID("$Id: captoinfo.c,v 1.109 2025/11/23 20:22:38 tom Exp $")
102 
103 #if 0
104 #define DEBUG_THIS(p) DEBUG(9, p)
105 #else
106 #define DEBUG_THIS(p)		/* nothing */
107 #endif
108 
109 #define MAX_PUSHED	16	/* max # args we can push onto the stack */
110 
111 static int stack[MAX_PUSHED];	/* the stack */
112 static int stackptr;		/* the next empty place on the stack */
113 static int onstack;		/* the top of stack */
114 static int seenm;		/* seen a %m */
115 static int seenn;		/* seen a %n */
116 static int seenr;		/* seen a %r */
117 static int param;		/* current parameter */
118 static char *dp;		/* pointer to end of the converted string */
119 
120 static char *my_string;
121 static size_t my_length;
122 
123 static char *
init_string(void)124 init_string(void)
125 /* initialize 'my_string', 'my_length' */
126 {
127     if (my_string == NULL)
128 	TYPE_MALLOC(char, my_length = 256, my_string);
129 
130     *my_string = '\0';
131     return my_string;
132 }
133 
134 static char *
save_string(char * d,const char * const s)135 save_string(char *d, const char *const s)
136 {
137     size_t have = (size_t) (d - my_string);
138     size_t need = have + strlen(s) + 2;
139     if (need > my_length) {
140 	my_string = (char *) _nc_doalloc(my_string, my_length = (need + need));
141 	if (my_string == NULL)
142 	    _nc_err_abort(MSG_NO_MEMORY);
143 	d = my_string + have;
144     }
145     _nc_STRCPY(d, s, my_length - have);
146     return d + strlen(d);
147 }
148 
149 static NCURSES_INLINE char *
save_char(char * s,int c)150 save_char(char *s, int c)
151 {
152     static char temp[2];
153     temp[0] = (char) c;
154     return save_string(s, temp);
155 }
156 
157 static void
push(void)158 push(void)
159 /* push onstack on to the stack */
160 {
161     if (stackptr >= MAX_PUSHED)
162 	_nc_warning("string too complex to convert");
163     else
164 	stack[stackptr++] = onstack;
165 }
166 
167 static void
pop(void)168 pop(void)
169 /* pop the top of the stack into onstack */
170 {
171     if (stackptr == 0) {
172 	if (onstack == 0)
173 	    _nc_warning("I'm confused");
174 	else
175 	    onstack = 0;
176     } else
177 	onstack = stack[--stackptr];
178     param++;
179 }
180 
181 static int
cvtchar(register const char * sp)182 cvtchar(register const char *sp)
183 /* convert a character to a terminfo push */
184 {
185     unsigned char c = 0;
186     int len;
187 
188     switch (*sp) {
189     case '\\':
190 	switch (*++sp) {
191 	case '\'':
192 	case '$':
193 	case '\\':
194 	case '%':
195 	    c = UChar(*sp);
196 	    len = 2;
197 	    break;
198 	case '\0':
199 	    c = '\\';
200 	    len = 1;
201 	    break;
202 	case '0':
203 	case '1':
204 	case '2':
205 	case '3':
206 	    len = 1;
207 	    while (isdigit(UChar(*sp))) {
208 		c = UChar(8 * c + (*sp++ - '0'));
209 		len++;
210 	    }
211 	    break;
212 	default:
213 	    c = UChar(*sp);
214 	    len = (c != '\0') ? 2 : 1;
215 	    break;
216 	}
217 	break;
218     case '^':
219 	len = 2;
220 	c = UChar(*++sp);
221 	if (c == '?') {
222 	    c = 127;
223 	} else if (c == '\0') {
224 	    len = 1;
225 	} else {
226 	    c &= 0x1f;
227 	}
228 	break;
229     default:
230 	c = UChar(*sp);
231 	len = (c != '\0') ? 1 : 0;
232     }
233     if (isgraph(c) && c != ',' && c != '\'' && c != '\\' && c != ':') {
234 	dp = save_string(dp, "%\'");
235 	dp = save_char(dp, c);
236 	dp = save_char(dp, '\'');
237     } else if (c != '\0') {
238 	dp = save_string(dp, "%{");
239 	if (c > 99)
240 	    dp = save_char(dp, c / 100 + '0');
241 	if (c > 9)
242 	    dp = save_char(dp, ((int) (c / 10)) % 10 + '0');
243 	dp = save_char(dp, c % 10 + '0');
244 	dp = save_char(dp, '}');
245     }
246     return len;
247 }
248 
249 static void
getparam(int parameter,int n)250 getparam(int parameter, int n)
251 /* push n copies of parameter on the terminfo stack if not already there */
252 {
253     int nn;
254 
255     if (seenr) {
256 	if (parameter == 1)
257 	    parameter = 2;
258 	else if (parameter == 2)
259 	    parameter = 1;
260     }
261 
262     for (nn = 0; nn < n; ++nn) {
263 	dp = save_string(dp, "%p");
264 	dp = save_char(dp, '0' + parameter);
265     }
266 
267     if (onstack == parameter) {
268 	if (n > 1) {
269 	    _nc_warning("string may not be optimal");
270 	    dp = save_string(dp, "%Pa");
271 	    while (n-- > 0) {
272 		dp = save_string(dp, "%ga");
273 	    }
274 	}
275 	return;
276     }
277     if (onstack != 0)
278 	push();
279 
280     onstack = parameter;
281 
282     if (seenn && parameter < 3) {
283 	dp = save_string(dp, "%{96}%^");
284     }
285 
286     if (seenm && parameter < 3) {
287 	dp = save_string(dp, "%{127}%^");
288     }
289 }
290 
291 /*
292  * Convert a termcap string to terminfo format.
293  * 'cap' is the relevant terminfo capability index.
294  * 's' is the string value of the capability.
295  * 'parameterized' tells what type of translations to do:
296  *	% translations if 1
297  *	pad translations if >=0
298  */
299 NCURSES_EXPORT(char *)
_nc_captoinfo(const char * cap,const char * s,int const parameterized)300 _nc_captoinfo(const char *cap, const char *s, int const parameterized)
301 {
302     const char *capstart;
303 
304     stackptr = 0;
305     onstack = 0;
306     seenm = 0;
307     seenn = 0;
308     seenr = 0;
309     param = 1;
310 
311     DEBUG_THIS(("_nc_captoinfo params %d, %s", parameterized, s));
312 
313     dp = init_string();
314 
315     /* skip the initial padding (if we haven't been told not to) */
316     capstart = NULL;
317     if (s == NULL)
318 	s = "";
319     if (parameterized >= 0 && isdigit(UChar(*s)))
320 	for (capstart = s; *s != '\0'; s++)
321 	    if (!(isdigit(UChar(*s)) || *s == '*' || *s == '.'))
322 		break;
323 
324     while (*s != '\0') {
325 	switch (*s) {
326 	case '%':
327 	    s++;
328 	    if (parameterized < 1) {
329 		dp = save_char(dp, '%');
330 		break;
331 	    }
332 	    switch (*s++) {
333 	    case '%':
334 		dp = save_string(dp, "%%");
335 		break;
336 	    case 'r':
337 		if (seenr++ == 1) {
338 		    _nc_warning("saw %%r twice in %s", cap);
339 		}
340 		break;
341 	    case 'm':
342 		if (seenm++ == 1) {
343 		    _nc_warning("saw %%m twice in %s", cap);
344 		}
345 		break;
346 	    case 'n':
347 		if (seenn++ == 1) {
348 		    _nc_warning("saw %%n twice in %s", cap);
349 		}
350 		break;
351 	    case 'i':
352 		dp = save_string(dp, "%i");
353 		break;
354 	    case '6':
355 	    case 'B':
356 		getparam(param, 1);
357 		dp = save_string(dp, "%{10}%/%{16}%*");
358 		getparam(param, 1);
359 		dp = save_string(dp, "%{10}%m%+");
360 		break;
361 	    case '8':
362 	    case 'D':
363 		getparam(param, 2);
364 		dp = save_string(dp, "%{2}%*%-");
365 		break;
366 	    case '>':
367 		/* %?%{x}%>%t%{y}%+%; */
368 		if (s[0] && s[1]) {
369 		    getparam(param, 2);
370 		    dp = save_string(dp, "%?");
371 		    s += cvtchar(s);
372 		    dp = save_string(dp, "%>%t");
373 		    s += cvtchar(s);
374 		    dp = save_string(dp, "%+%;");
375 		} else {
376 		    _nc_warning("expected two characters after %%>");
377 		    dp = save_string(dp, "%>");
378 		}
379 		break;
380 	    case 'a':
381 		if ((*s == '=' || *s == '+' || *s == '-'
382 		     || *s == '*' || *s == '/')
383 		    && (s[1] == 'p' || s[1] == 'c')
384 		    && s[2] != '\0') {
385 		    int l;
386 		    l = 2;
387 		    if (*s != '=')
388 			getparam(param, 1);
389 		    if (s[1] == 'p') {
390 			getparam(param + s[2] - '@', 1);
391 			if (param != onstack) {
392 			    pop();
393 			    param--;
394 			}
395 			l++;
396 		    } else
397 			l += cvtchar(s + 2);
398 		    switch (*s) {
399 		    case '+':
400 			dp = save_string(dp, "%+");
401 			break;
402 		    case '-':
403 			dp = save_string(dp, "%-");
404 			break;
405 		    case '*':
406 			dp = save_string(dp, "%*");
407 			break;
408 		    case '/':
409 			dp = save_string(dp, "%/");
410 			break;
411 		    case '=':
412 			if (seenr) {
413 			    if (param == 1)
414 				onstack = 2;
415 			    else if (param == 2)
416 				onstack = 1;
417 			    else
418 				onstack = param;
419 			} else
420 			    onstack = param;
421 			break;
422 		    }
423 		    s += l;
424 		    break;
425 		}
426 		getparam(param, 1);
427 		s += cvtchar(s);
428 		dp = save_string(dp, "%+");
429 		break;
430 	    case '+':
431 		getparam(param, 1);
432 		s += cvtchar(s);
433 		dp = save_string(dp, "%+%c");
434 		pop();
435 		break;
436 	    case 's':
437 #ifdef WATERLOO
438 		s += cvtchar(s);
439 		getparam(param, 1);
440 		dp = save_string(dp, "%-");
441 #else
442 		getparam(param, 1);
443 		dp = save_string(dp, "%s");
444 		pop();
445 #endif /* WATERLOO */
446 		break;
447 	    case '-':
448 		s += cvtchar(s);
449 		getparam(param, 1);
450 		dp = save_string(dp, "%-%c");
451 		pop();
452 		break;
453 	    case '.':
454 		getparam(param, 1);
455 		dp = save_string(dp, "%c");
456 		pop();
457 		break;
458 	    case '0':		/* not clear any of the historical termcaps did this */
459 		if (*s == '3') {
460 		    ++s;
461 		    goto see03;
462 		}
463 		if (*s == '2') {
464 		    ++s;
465 		    goto see02;
466 		}
467 		goto invalid;
468 	    case '2':
469 	      see02:
470 		getparam(param, 1);
471 		dp = save_string(dp, "%2d");
472 		pop();
473 		break;
474 	    case '3':
475 	      see03:
476 		getparam(param, 1);
477 		dp = save_string(dp, "%3d");
478 		pop();
479 		break;
480 	    case 'd':
481 		getparam(param, 1);
482 		dp = save_string(dp, "%d");
483 		pop();
484 		break;
485 	    case 'f':
486 		param++;
487 		break;
488 	    case 'b':
489 		param--;
490 		break;
491 	    case '\\':
492 		dp = save_string(dp, "%\\");
493 		break;
494 	    default:
495 	      invalid:
496 		dp = save_char(dp, '%');
497 		s--;
498 		_nc_warning("unknown %% code %s (%#x) in %s",
499 			    unctrl((chtype) *s), UChar(*s), cap);
500 		break;
501 	    }
502 	    break;
503 	default:
504 	    if (*s != '\0')
505 		dp = save_char(dp, *s++);
506 	    break;
507 	}
508     }
509 
510     /*
511      * Now, if we stripped off some leading padding, add it at the end
512      * of the string as mandatory padding.
513      */
514     if (capstart) {
515 	dp = save_string(dp, "$<");
516 	for (s = capstart; *s != '\0'; s++)
517 	    if (isdigit(UChar(*s)) || *s == '*' || *s == '.')
518 		dp = save_char(dp, *s);
519 	    else
520 		break;
521 	dp = save_string(dp, "/>");
522     }
523 
524     (void) save_char(dp, '\0');
525 
526     DEBUG_THIS(("... _nc_captoinfo %s", NonNull(my_string)));
527 
528     return (my_string);
529 }
530 
531 /*
532  * Check for an expression that corresponds to "%B" (BCD):
533  *	(parameter / 10) * 16 + (parameter % 10)
534  */
535 static int
bcd_expression(const char * str)536 bcd_expression(const char *str)
537 {
538     static const char fmt[] = "%%p%c%%{10}%%/%%{16}%%*%%p%c%%{10}%%m%%+";
539     int len = 0;
540     char ch1, ch2;
541 
542     if (sscanf(str, fmt, &ch1, &ch2) == 2
543 	&& isdigit(UChar(ch1))
544 	&& isdigit(UChar(ch2))
545 	&& (ch1 == ch2)) {
546 	len = 28;
547 #ifndef NDEBUG
548 	{
549 	    char buffer[80];
550 	    int tst;
551 	    _nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer)) fmt, ch1, ch2);
552 	    tst = (int) strlen(buffer) - 1;
553 	    assert(len == tst);
554 	}
555 #endif
556     }
557     return len;
558 }
559 
560 static char *
save_tc_char(char * bufptr,int c1)561 save_tc_char(char *bufptr, int c1)
562 {
563     if (is7bits(c1) && isprint(c1)) {
564 	if (c1 == ':' || c1 == '\\')
565 	    bufptr = save_char(bufptr, '\\');
566 	bufptr = save_char(bufptr, c1);
567     } else {
568 	char temp[80];
569 
570 	if (c1 == (c1 & 0x1f)) {	/* iscntrl() returns T on 255 */
571 	    _nc_SPRINTF(temp, _nc_SLIMIT(sizeof(temp))
572 			"%.20s", unctrl((chtype) c1));
573 	} else {
574 	    _nc_SPRINTF(temp, _nc_SLIMIT(sizeof(temp))
575 			"\\%03o", c1);
576 	}
577 	bufptr = save_string(bufptr, temp);
578     }
579     return bufptr;
580 }
581 
582 static char *
save_tc_inequality(char * bufptr,int c1,int c2)583 save_tc_inequality(char *bufptr, int c1, int c2)
584 {
585     bufptr = save_string(bufptr, "%>");
586     bufptr = save_tc_char(bufptr, c1);
587     bufptr = save_tc_char(bufptr, c2);
588     return bufptr;
589 }
590 
591 /*
592  * info-to-cap --- conversion between terminfo and termcap formats
593  *
594  * Here are the capabilities infotocap assumes it can translate to:
595  *
596  *     %%       output `%'
597  *     %d       output value as in printf %d
598  *     %2       output value as in printf %2d
599  *     %3       output value as in printf %3d
600  *     %.       output value as in printf %c
601  *     %+c      add character c to value, then do %.
602  *     %>xy     if value > x then add y, no output
603  *     %r       reverse order of two parameters, no output
604  *     %i       increment by one, no output
605  *     %n       exclusive-or all parameters with 0140 (Datamedia 2500)
606  *     %B       BCD (16*(value/10)) + (value%10), no output
607  *     %D       Reverse coding (value - 2*(value%16)), no output (Delta Data).
608  *     %m       exclusive-or all parameters with 0177 (not in 4.4BSD)
609  */
610 
611 #define octal_fixup(n, c) fixups[n].ch = ((fixups[n].ch << 3) | ((c) - '0'))
612 
613 /*
614  * Convert a terminfo string to termcap format.  Parameters are as in
615  * _nc_captoinfo().
616  */
617 NCURSES_EXPORT(char *)
_nc_infotocap(const char * cap GCC_UNUSED,const char * str,int const parameterized)618 _nc_infotocap(const char *cap GCC_UNUSED, const char *str, int const parameterized)
619 {
620     int seenone = 0, seentwo = 0, saw_m = 0, saw_n = 0;
621     const char *padding;
622     const char *trimmed = NULL;
623     int in0, in1, in2;
624     char ch1 = 0, ch2 = 0;
625     char *bufptr = init_string();
626     char octal[4];
627     int len;
628     int digits;
629     bool syntax_error = FALSE;
630     int myfix = 0;
631     struct {
632 	int ch;
633 	int offset;
634     } fixups[MAX_TC_FIXUPS];
635 
636     DEBUG_THIS(("_nc_infotocap %s params %d, %s",
637 		_nc_strict_bsd ? "strict" : "loose",
638 		parameterized,
639 		_nc_visbuf(str)));
640 
641     /* we may have to move some trailing mandatory padding up front */
642     padding = str + strlen(str) - 1;
643     if (padding > str && *padding == '>') {
644 	if (padding > (str + 1) && *--padding == '/')
645 	    --padding;
646 	while (isdigit(UChar(*padding)) || *padding == '.' || *padding == '*')
647 	    padding--;
648 	if (padding > str && *padding == '<' && *--padding == '$')
649 	    trimmed = padding;
650 	padding += 2;
651 
652 	while (isdigit(UChar(*padding)) || *padding == '.' || *padding == '*')
653 	    bufptr = save_char(bufptr, *padding++);
654     }
655 
656     for (; !syntax_error &&
657 	 *str &&
658 	 ((trimmed == NULL) || (str < trimmed)); str++) {
659 	int c1, c2;
660 	char *cp = NULL;
661 
662 	if (str[0] == '^') {
663 	    if (str[1] == '\0' || (str + 1) == trimmed) {
664 		bufptr = save_string(bufptr, "\\136");
665 		++str;
666 	    } else if (str[1] == '?') {
667 		/*
668 		 * Although the 4.3BSD termcap file has an instance of "kb=^?",
669 		 * that appears to be just cut/paste since neither 4.3BSD nor
670 		 * 4.4BSD termcap interprets "^?" as DEL.
671 		 */
672 		bufptr = save_string(bufptr, "\\177");
673 		++str;
674 	    } else {
675 		bufptr = save_char(bufptr, *str++);
676 		bufptr = save_char(bufptr, *str);
677 	    }
678 	} else if (str[0] == ':') {
679 	    bufptr = save_char(bufptr, '\\');
680 	    bufptr = save_char(bufptr, '0');
681 	    bufptr = save_char(bufptr, '7');
682 	    bufptr = save_char(bufptr, '2');
683 	} else if (str[0] == '\\') {
684 	    if (str[1] == '\0' || (str + 1) == trimmed) {
685 		bufptr = save_string(bufptr, "\\134");
686 		++str;
687 	    } else if (str[1] == '^') {
688 		bufptr = save_string(bufptr, "\\136");
689 		++str;
690 	    } else if (str[1] == ',') {
691 		bufptr = save_char(bufptr, *++str);
692 	    } else {
693 		int xx1;
694 
695 		bufptr = save_char(bufptr, *str++);
696 		xx1 = *str;
697 		if (_nc_strict_bsd) {
698 
699 		    if (isoctal(UChar(xx1))) {
700 			int pad = 0;
701 			int xx2;
702 			int fix = 0;
703 
704 			if (!isoctal(UChar(str[1])))
705 			    pad = 2;
706 			else if (str[1] && !isoctal(UChar(str[2])))
707 			    pad = 1;
708 
709 			/*
710 			 * Test for "\0", "\00" or "\000" and transform those
711 			 * into "\200".
712 			 */
713 			if (xx1 == '0'
714 			    && ((pad == 2) || (str[1] == '0'))
715 			    && ((pad >= 1) || (str[2] == '0'))) {
716 			    xx2 = '2';
717 			} else {
718 			    xx2 = '0';
719 			    pad = 0;	/* FIXME - optionally pad to 3 digits */
720 			}
721 			if (myfix < MAX_TC_FIXUPS) {
722 			    fix = 3 - pad;
723 			    fixups[myfix].ch = 0;
724 			    fixups[myfix].offset = (int) (bufptr
725 							  - my_string
726 							  - 1);
727 			}
728 			while (pad-- > 0) {
729 			    bufptr = save_char(bufptr, xx2);
730 			    if (myfix < MAX_TC_FIXUPS) {
731 				fixups[myfix].ch <<= 3;
732 				fixups[myfix].ch |= (xx2 - '0');
733 			    }
734 			    xx2 = '0';
735 			}
736 			if (myfix < MAX_TC_FIXUPS) {
737 			    int n;
738 			    for (n = 0; n < fix; ++n) {
739 				fixups[myfix].ch <<= 3;
740 				fixups[myfix].ch |= (str[n] - '0');
741 			    }
742 			    if (fixups[myfix].ch < 32) {
743 				++myfix;
744 			    }
745 			}
746 		    } else if (strchr("E\\nrtbf", xx1) == NULL) {
747 			switch (xx1) {
748 			case 'e':
749 			    xx1 = 'E';
750 			    break;
751 			case 'l':
752 			    xx1 = 'n';
753 			    break;
754 			case 's':
755 			    bufptr = save_char(bufptr, '0');
756 			    bufptr = save_char(bufptr, '4');
757 			    xx1 = '0';
758 			    break;
759 			case ':':
760 			    /*
761 			     * Note: termcap documentation claims that ":"
762 			     * must be escaped as "\072", however the
763 			     * documentation is incorrect - read the code.
764 			     * The replacement does not work reliably,
765 			     * so the advice is not helpful.
766 			     */
767 			    bufptr = save_char(bufptr, '0');
768 			    bufptr = save_char(bufptr, '7');
769 			    xx1 = '2';
770 			    break;
771 			default:
772 			    /* should not happen, but handle this anyway */
773 			    _nc_SPRINTF(octal, _nc_SLIMIT(sizeof(octal))
774 					"%03o", UChar(xx1));
775 			    bufptr = save_char(bufptr, octal[0]);
776 			    bufptr = save_char(bufptr, octal[1]);
777 			    xx1 = octal[2];
778 			    break;
779 			}
780 		    }
781 		} else {
782 		    if (myfix < MAX_TC_FIXUPS && isoctal(UChar(xx1))) {
783 			bool will_fix = TRUE;
784 			int n;
785 
786 			fixups[myfix].ch = 0;
787 			fixups[myfix].offset = (int) (bufptr - my_string - 1);
788 			for (n = 0; n < 3; ++n) {
789 			    if (isoctal(str[n])) {
790 				octal_fixup(myfix, str[n]);
791 			    } else {
792 				will_fix = FALSE;
793 				break;
794 			    }
795 			}
796 			if (will_fix && (fixups[myfix].ch < 32))
797 			    ++myfix;
798 		    }
799 		}
800 		bufptr = save_char(bufptr, xx1);
801 	    }
802 	} else if (str[0] == '$' && str[1] == '<') {	/* discard padding */
803 	    str += 2;
804 	    while (isdigit(UChar(*str))
805 		   || *str == '.'
806 		   || *str == '*'
807 		   || *str == '/'
808 		   || *str == '>')
809 		str++;
810 	    --str;
811 	} else if (sscanf(str,
812 			  "[%%?%%p1%%{8}%%<%%t%d%%p1%%d%%e%%p1%%{16}%%<%%t%d%%p1%%{8}%%-%%d%%e%d;5;%%p1%%d%%;m",
813 			  &in0, &in1, &in2) == 3
814 		   && ((in0 == 4 && in1 == 10 && in2 == 48)
815 		       || (in0 == 3 && in1 == 9 && in2 == 38))) {
816 	    /* dumb-down an optimized case from xterm-256color for termcap */
817 	    if ((str = strstr(str, ";m")) == NULL)
818 		break;		/* cannot happen */
819 	    ++str;
820 	    if (in2 == 48) {
821 		bufptr = save_string(bufptr, "[48;5;%dm");
822 	    } else {
823 		bufptr = save_string(bufptr, "[38;5;%dm");
824 	    }
825 	} else if (str[0] == '%' && str[1] == '%') {	/* escaped '%' */
826 	    bufptr = save_string(bufptr, "%%");
827 	    ++str;
828 	} else if (*str != '%' || (parameterized < 1)) {
829 	    bufptr = save_char(bufptr, *str);
830 	} else if (sscanf(str, "%%?%%{%d}%%>%%t%%{%d}%%+%%;", &c1, &c2) == 2) {
831 	    str = strchr(str, ';');
832 	    bufptr = save_tc_inequality(bufptr, c1, c2);
833 	} else if (sscanf(str, "%%?%%{%d}%%>%%t%%'%c'%%+%%;", &c1, &ch2) == 2) {
834 	    str = strchr(str, ';');
835 	    bufptr = save_tc_inequality(bufptr, c1, ch2);
836 	} else if (sscanf(str, "%%?%%'%c'%%>%%t%%{%d}%%+%%;", &ch1, &c2) == 2) {
837 	    str = strchr(str, ';');
838 	    bufptr = save_tc_inequality(bufptr, ch1, c2);
839 	} else if (sscanf(str, "%%?%%'%c'%%>%%t%%'%c'%%+%%;", &ch1, &ch2) == 2) {
840 	    str = strchr(str, ';');
841 	    bufptr = save_tc_inequality(bufptr, ch1, ch2);
842 	} else if ((len = bcd_expression(str)) != 0) {
843 	    str += len;
844 	    bufptr = save_string(bufptr, "%B");
845 	} else if ((sscanf(str, "%%{%d}%%+%%%c", &c1, &ch2) == 2
846 		    || sscanf(str, "%%'%c'%%+%%%c", &ch1, &ch2) == 2)
847 		   && ch2 == 'c'
848 		   && (cp = strchr(str, '+'))) {
849 	    str = cp + 2;
850 	    bufptr = save_string(bufptr, "%+");
851 
852 	    if (ch1)
853 		c1 = ch1;
854 	    bufptr = save_tc_char(bufptr, c1);
855 	}
856 	/* FIXME: this "works" for 'delta' */
857 	else if (strncmp(str, "%{2}%*%-", (size_t) 8) == 0) {
858 	    str += 7;
859 	    bufptr = save_string(bufptr, "%D");
860 	} else if (strncmp(str, "%{96}%^", (size_t) 7) == 0) {
861 	    str += 6;
862 	    if (saw_m++ == 0) {
863 		bufptr = save_string(bufptr, "%n");
864 	    }
865 	} else if (strncmp(str, "%{127}%^", (size_t) 8) == 0) {
866 	    str += 7;
867 	    if (saw_n++ == 0) {
868 		bufptr = save_string(bufptr, "%m");
869 	    }
870 	} else {		/* cm-style format element */
871 	    str++;
872 	    switch (*str) {
873 	    case '%':
874 		bufptr = save_char(bufptr, '%');
875 		break;
876 
877 	    case '0':
878 	    case '1':
879 	    case '2':
880 	    case '3':
881 	    case '4':
882 	    case '5':
883 	    case '6':
884 	    case '7':
885 	    case '8':
886 	    case '9':
887 		bufptr = save_char(bufptr, '%');
888 		ch1 = 0;
889 		ch2 = 0;
890 		digits = 0;
891 		while (isdigit(UChar(*str))) {
892 		    if (++digits > 2) {
893 			syntax_error = TRUE;
894 			break;
895 		    }
896 		    ch2 = ch1;
897 		    ch1 = *str++;
898 		    if (digits == 2 && ch2 != '0') {
899 			syntax_error = TRUE;
900 			break;
901 		    } else if (_nc_strict_bsd) {
902 			if (ch1 > '3') {
903 			    syntax_error = TRUE;
904 			    break;
905 			}
906 		    } else {
907 			bufptr = save_char(bufptr, ch1);
908 		    }
909 		}
910 		if (syntax_error)
911 		    break;
912 		/*
913 		 * Convert %02 to %2 and %03 to %3
914 		 */
915 		if (ch2 == '0' && !_nc_strict_bsd) {
916 		    ch2 = 0;
917 		    bufptr[-2] = bufptr[-1];
918 		    *--bufptr = 0;
919 		}
920 		if (_nc_strict_bsd) {
921 		    if (ch2 != 0 && ch2 != '0') {
922 			syntax_error = TRUE;
923 		    } else if (ch1 < '2') {
924 			ch1 = 'd';
925 		    }
926 		    bufptr = save_char(bufptr, ch1);
927 		}
928 		if (strchr("oxX.", *str)) {
929 		    syntax_error = TRUE;	/* termcap doesn't have octal, hex */
930 		}
931 		break;
932 
933 	    case 'd':
934 		bufptr = save_string(bufptr, "%d");
935 		break;
936 
937 	    case 'c':
938 		bufptr = save_string(bufptr, "%.");
939 		break;
940 
941 		/*
942 		 * %s isn't in termcap, but it is convenient to pass it through
943 		 * so we can represent things like terminfo pfkey strings in
944 		 * termcap notation.
945 		 */
946 	    case 's':
947 		if (_nc_strict_bsd) {
948 		    syntax_error = TRUE;
949 		} else {
950 		    bufptr = save_string(bufptr, "%s");
951 		}
952 		break;
953 
954 	    case 'p':
955 		str++;
956 		if (*str == '1')
957 		    seenone = 1;
958 		else if (*str == '2') {
959 		    if (!seenone && !seentwo) {
960 			bufptr = save_string(bufptr, "%r");
961 			seentwo++;
962 		    }
963 		} else if (*str >= '3') {
964 		    syntax_error = TRUE;
965 		}
966 		break;
967 
968 	    case 'i':
969 		bufptr = save_string(bufptr, "%i");
970 		break;
971 
972 	    default:
973 		bufptr = save_char(bufptr, *str);
974 		syntax_error = TRUE;
975 		break;
976 	    }			/* endswitch (*str) */
977 	}			/* endelse (*str == '%') */
978 
979 	/*
980 	 * 'str' always points to the end of what was scanned in this step,
981 	 * but that may not be the end of the string.
982 	 */
983 	assert(str != NULL);
984 	if (str == NULL || *str == '\0')
985 	    break;
986 
987     }				/* endwhile (*str) */
988 
989     if (!syntax_error &&
990 	myfix > 0 &&
991 	((int) strlen(my_string) - (4 * myfix)) < MIN_TC_FIXUPS) {
992 	while (--myfix >= 0) {
993 	    char *p = fixups[myfix].offset + my_string;
994 	    *p++ = '^';
995 	    *p++ = (char) (fixups[myfix].ch | '@');
996 	    while ((p[0] = p[2]) != '\0') {
997 		++p;
998 	    }
999 	}
1000     }
1001 
1002     DEBUG_THIS(("... _nc_infotocap %s",
1003 		syntax_error
1004 		? "<ERR>"
1005 		: _nc_visbuf(my_string)));
1006 
1007     return (syntax_error ? NULL : my_string);
1008 }
1009 
1010 #ifdef MAIN
1011 
1012 int curr_line;
1013 
1014 int
main(int argc,char * argv[])1015 main(int argc, char *argv[])
1016 {
1017     int c, tc = FALSE;
1018 
1019     while ((c = getopt(argc, argv, "c")) != EOF)
1020 	switch (c) {
1021 	case 'c':
1022 	    tc = TRUE;
1023 	    break;
1024 	}
1025 
1026     curr_line = 0;
1027     for (;;) {
1028 	char buf[BUFSIZ];
1029 
1030 	++curr_line;
1031 	if (fgets(buf, sizeof(buf), stdin) == NULL)
1032 	    break;
1033 	buf[strlen(buf) - 1] = '\0';
1034 	_nc_set_source(buf);
1035 
1036 	if (tc) {
1037 	    char *cp = _nc_infotocap("to termcap", buf, 1);
1038 
1039 	    if (cp)
1040 		(void) fputs(cp, stdout);
1041 	} else
1042 	    (void) fputs(_nc_captoinfo("to terminfo", buf, 1), stdout);
1043 	(void) putchar('\n');
1044     }
1045     return (0);
1046 }
1047 #endif /* MAIN */
1048 
1049 #if NO_LEAKS
1050 NCURSES_EXPORT(void)
_nc_captoinfo_leaks(void)1051 _nc_captoinfo_leaks(void)
1052 {
1053     if (my_string != NULL) {
1054 	FreeAndNull(my_string);
1055     }
1056     my_length = 0;
1057 }
1058 #endif
1059