xref: /freebsd/contrib/ncurses/ncurses/tinfo/captoinfo.c (revision 10ff414c14eef433d8157f0c17904d740693933b)
1 /****************************************************************************
2  * Copyright 2018-2019,2020 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.100 2020/07/08 21:39:54 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 *
124 init_string(void)
125 /* initialize 'my_string', 'my_length' */
126 {
127     if (my_string == 0)
128 	TYPE_MALLOC(char, my_length = 256, my_string);
129 
130     *my_string = '\0';
131     return my_string;
132 }
133 
134 static char *
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 == 0)
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 *
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
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
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
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
250 getparm(int parm, int n)
251 /* push n copies of param on the terminfo stack if not already there */
252 {
253     int nn;
254 
255     if (seenr) {
256 	if (parm == 1)
257 	    parm = 2;
258 	else if (parm == 2)
259 	    parm = 1;
260     }
261 
262     for (nn = 0; nn < n; ++nn) {
263 	dp = save_string(dp, "%p");
264 	dp = save_char(dp, '0' + parm);
265     }
266 
267     if (onstack == parm) {
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 = parm;
281 
282     if (seenn && parm < 3) {
283 	dp = save_string(dp, "%{96}%^");
284     }
285 
286     if (seenm && parm < 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 *)
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 = 0;
317     if (s == 0)
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 		getparm(param, 1);
357 		dp = save_string(dp, "%{10}%/%{16}%*");
358 		getparm(param, 1);
359 		dp = save_string(dp, "%{10}%m%+");
360 		break;
361 	    case '8':
362 	    case 'D':
363 		getparm(param, 2);
364 		dp = save_string(dp, "%{2}%*%-");
365 		break;
366 	    case '>':
367 		/* %?%{x}%>%t%{y}%+%; */
368 		if (s[0] && s[1]) {
369 		    getparm(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 			getparm(param, 1);
389 		    if (s[1] == 'p') {
390 			getparm(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 		getparm(param, 1);
427 		s += cvtchar(s);
428 		dp = save_string(dp, "%+");
429 		break;
430 	    case '+':
431 		getparm(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 		getparm(param, 1);
440 		dp = save_string(dp, "%-");
441 #else
442 		getparm(param, 1);
443 		dp = save_string(dp, "%s");
444 		pop();
445 #endif /* WATERLOO */
446 		break;
447 	    case '-':
448 		s += cvtchar(s);
449 		getparm(param, 1);
450 		dp = save_string(dp, "%-%c");
451 		pop();
452 		break;
453 	    case '.':
454 		getparm(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 		getparm(param, 1);
471 		dp = save_string(dp, "%2d");
472 		pop();
473 		break;
474 	    case '3':
475 	      see03:
476 		getparm(param, 1);
477 		dp = save_string(dp, "%3d");
478 		pop();
479 		break;
480 	    case 'd':
481 		getparm(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
536 bcd_expression(const char *str)
537 {
538     /* leave this non-const for HPUX */
539     static char fmt[] = "%%p%c%%{10}%%/%%{16}%%*%%p%c%%{10}%%m%%+";
540     int len = 0;
541     char ch1, ch2;
542 
543     if (sscanf(str, fmt, &ch1, &ch2) == 2
544 	&& isdigit(UChar(ch1))
545 	&& isdigit(UChar(ch2))
546 	&& (ch1 == ch2)) {
547 	len = 28;
548 #ifndef NDEBUG
549 	{
550 	    char buffer[80];
551 	    int tst;
552 	    _nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer)) fmt, ch1, ch2);
553 	    tst = strlen(buffer) - 1;
554 	    assert(len == tst);
555 	}
556 #endif
557     }
558     return len;
559 }
560 
561 static char *
562 save_tc_char(char *bufptr, int c1)
563 {
564     if (is7bits(c1) && isprint(c1)) {
565 	if (c1 == ':' || c1 == '\\')
566 	    bufptr = save_char(bufptr, '\\');
567 	bufptr = save_char(bufptr, c1);
568     } else {
569 	char temp[80];
570 
571 	if (c1 == (c1 & 0x1f)) {	/* iscntrl() returns T on 255 */
572 	    _nc_SPRINTF(temp, _nc_SLIMIT(sizeof(temp))
573 			"%.20s", unctrl((chtype) c1));
574 	} else {
575 	    _nc_SPRINTF(temp, _nc_SLIMIT(sizeof(temp))
576 			"\\%03o", c1);
577 	}
578 	bufptr = save_string(bufptr, temp);
579     }
580     return bufptr;
581 }
582 
583 static char *
584 save_tc_inequality(char *bufptr, int c1, int c2)
585 {
586     bufptr = save_string(bufptr, "%>");
587     bufptr = save_tc_char(bufptr, c1);
588     bufptr = save_tc_char(bufptr, c2);
589     return bufptr;
590 }
591 
592 /*
593  * info-to-cap --- conversion between terminfo and termcap formats
594  *
595  * Here are the capabilities infotocap assumes it can translate to:
596  *
597  *     %%       output `%'
598  *     %d       output value as in printf %d
599  *     %2       output value as in printf %2d
600  *     %3       output value as in printf %3d
601  *     %.       output value as in printf %c
602  *     %+c      add character c to value, then do %.
603  *     %>xy     if value > x then add y, no output
604  *     %r       reverse order of two parameters, no output
605  *     %i       increment by one, no output
606  *     %n       exclusive-or all parameters with 0140 (Datamedia 2500)
607  *     %B       BCD (16*(value/10)) + (value%10), no output
608  *     %D       Reverse coding (value - 2*(value%16)), no output (Delta Data).
609  *     %m       exclusive-or all parameters with 0177 (not in 4.4BSD)
610  */
611 
612 #define octal_fixup(n, c) fixups[n].ch = ((fixups[n].ch << 3) | ((c) - '0'))
613 
614 /*
615  * Convert a terminfo string to termcap format.  Parameters are as in
616  * _nc_captoinfo().
617  */
618 NCURSES_EXPORT(char *)
619 _nc_infotocap(const char *cap GCC_UNUSED, const char *str, int const parameterized)
620 {
621     int seenone = 0, seentwo = 0, saw_m = 0, saw_n = 0;
622     const char *padding;
623     const char *trimmed = 0;
624     int in0, in1, in2;
625     char ch1 = 0, ch2 = 0;
626     char *bufptr = init_string();
627     char octal[4];
628     int len;
629     int digits;
630     bool syntax_error = FALSE;
631     int myfix = 0;
632     struct {
633 	int ch;
634 	int offset;
635     } fixups[MAX_TC_FIXUPS];
636 
637     DEBUG_THIS(("_nc_infotocap params %d, %s", parameterized, str));
638 
639     /* we may have to move some trailing mandatory padding up front */
640     padding = str + strlen(str) - 1;
641     if (padding > str && *padding == '>') {
642 	if (padding > (str + 1) && *--padding == '/')
643 	    --padding;
644 	while (isdigit(UChar(*padding)) || *padding == '.' || *padding == '*')
645 	    padding--;
646 	if (padding > str && *padding == '<' && *--padding == '$')
647 	    trimmed = padding;
648 	padding += 2;
649 
650 	while (isdigit(UChar(*padding)) || *padding == '.' || *padding == '*')
651 	    bufptr = save_char(bufptr, *padding++);
652     }
653 
654     for (; !syntax_error &&
655 	 *str &&
656 	 ((trimmed == 0) || (str < trimmed)); str++) {
657 	int c1, c2;
658 	char *cp = 0;
659 
660 	if (str[0] == '^') {
661 	    if (str[1] == '\0' || (str + 1) == trimmed) {
662 		bufptr = save_string(bufptr, "\\136");
663 		++str;
664 	    } else if (str[1] == '?') {
665 		/*
666 		 * Although the 4.3BSD termcap file has an instance of "kb=^?",
667 		 * that appears to be just cut/paste since neither 4.3BSD nor
668 		 * 4.4BSD termcap interprets "^?" as DEL.
669 		 */
670 		bufptr = save_string(bufptr, "\\177");
671 		++str;
672 	    } else {
673 		bufptr = save_char(bufptr, *str++);
674 		bufptr = save_char(bufptr, *str);
675 	    }
676 	} else if (str[0] == '\\') {
677 	    if (str[1] == '\0' || (str + 1) == trimmed) {
678 		bufptr = save_string(bufptr, "\\134");
679 		++str;
680 	    } else if (str[1] == '^') {
681 		bufptr = save_string(bufptr, "\\136");
682 		++str;
683 	    } else if (str[1] == ',') {
684 		bufptr = save_char(bufptr, *++str);
685 	    } else {
686 		int xx1;
687 
688 		bufptr = save_char(bufptr, *str++);
689 		xx1 = *str;
690 		if (_nc_strict_bsd) {
691 
692 		    if (isoctal(UChar(xx1))) {
693 			int pad = 0;
694 			int xx2;
695 			int fix = 0;
696 
697 			if (!isoctal(UChar(str[1])))
698 			    pad = 2;
699 			else if (str[1] && !isoctal(UChar(str[2])))
700 			    pad = 1;
701 
702 			/*
703 			 * Test for "\0", "\00" or "\000" and transform those
704 			 * into "\200".
705 			 */
706 			if (xx1 == '0'
707 			    && ((pad == 2) || (str[1] == '0'))
708 			    && ((pad >= 1) || (str[2] == '0'))) {
709 			    xx2 = '2';
710 			} else {
711 			    xx2 = '0';
712 			    pad = 0;	/* FIXME - optionally pad to 3 digits */
713 			}
714 			if (myfix < MAX_TC_FIXUPS) {
715 			    fix = 3 - pad;
716 			    fixups[myfix].ch = 0;
717 			    fixups[myfix].offset = (int) (bufptr
718 							  - my_string
719 							  - 1);
720 			}
721 			while (pad-- > 0) {
722 			    bufptr = save_char(bufptr, xx2);
723 			    if (myfix < MAX_TC_FIXUPS) {
724 				fixups[myfix].ch <<= 3;
725 				fixups[myfix].ch |= (xx2 - '0');
726 			    }
727 			    xx2 = '0';
728 			}
729 			if (myfix < MAX_TC_FIXUPS) {
730 			    int n;
731 			    for (n = 0; n < fix; ++n) {
732 				fixups[myfix].ch <<= 3;
733 				fixups[myfix].ch |= (str[n] - '0');
734 			    }
735 			    if (fixups[myfix].ch < 32) {
736 				++myfix;
737 			    }
738 			}
739 		    } else if (strchr("E\\nrtbf", xx1) == 0) {
740 			switch (xx1) {
741 			case 'e':
742 			    xx1 = 'E';
743 			    break;
744 			case 'l':
745 			    xx1 = 'n';
746 			    break;
747 			case 's':
748 			    bufptr = save_char(bufptr, '0');
749 			    bufptr = save_char(bufptr, '4');
750 			    xx1 = '0';
751 			    break;
752 			case ':':
753 			    /*
754 			     * Note: termcap documentation claims that ":"
755 			     * must be escaped as "\072", however the
756 			     * documentation is incorrect - read the code.
757 			     * The replacement does not work reliably,
758 			     * so the advice is not helpful.
759 			     */
760 			    bufptr = save_char(bufptr, '0');
761 			    bufptr = save_char(bufptr, '7');
762 			    xx1 = '2';
763 			    break;
764 			default:
765 			    /* should not happen, but handle this anyway */
766 			    _nc_SPRINTF(octal, _nc_SLIMIT(sizeof(octal))
767 					"%03o", UChar(xx1));
768 			    bufptr = save_char(bufptr, octal[0]);
769 			    bufptr = save_char(bufptr, octal[1]);
770 			    xx1 = octal[2];
771 			    break;
772 			}
773 		    }
774 		} else {
775 		    if (myfix < MAX_TC_FIXUPS && isoctal(UChar(xx1))) {
776 			bool will_fix = TRUE;
777 			int n;
778 
779 			fixups[myfix].ch = 0;
780 			fixups[myfix].offset = (int) (bufptr - my_string - 1);
781 			for (n = 0; n < 3; ++n) {
782 			    if (isoctal(str[n])) {
783 				octal_fixup(myfix, str[n]);
784 			    } else {
785 				will_fix = FALSE;
786 				break;
787 			    }
788 			}
789 			if (will_fix && (fixups[myfix].ch < 32))
790 			    ++myfix;
791 		    }
792 		}
793 		bufptr = save_char(bufptr, xx1);
794 	    }
795 	} else if (str[0] == '$' && str[1] == '<') {	/* discard padding */
796 	    str += 2;
797 	    while (isdigit(UChar(*str))
798 		   || *str == '.'
799 		   || *str == '*'
800 		   || *str == '/'
801 		   || *str == '>')
802 		str++;
803 	    --str;
804 	} else if (sscanf(str,
805 			  "[%%?%%p1%%{8}%%<%%t%d%%p1%%d%%e%%p1%%{16}%%<%%t%d%%p1%%{8}%%-%%d%%e%d;5;%%p1%%d%%;m",
806 			  &in0, &in1, &in2) == 3
807 		   && ((in0 == 4 && in1 == 10 && in2 == 48)
808 		       || (in0 == 3 && in1 == 9 && in2 == 38))) {
809 	    /* dumb-down an optimized case from xterm-256color for termcap */
810 	    if ((str = strstr(str, ";m")) == 0)
811 		break;		/* cannot happen */
812 	    ++str;
813 	    if (in2 == 48) {
814 		bufptr = save_string(bufptr, "[48;5;%dm");
815 	    } else {
816 		bufptr = save_string(bufptr, "[38;5;%dm");
817 	    }
818 	} else if (str[0] == '%' && str[1] == '%') {	/* escaped '%' */
819 	    bufptr = save_string(bufptr, "%%");
820 	    ++str;
821 	} else if (*str != '%' || (parameterized < 1)) {
822 	    bufptr = save_char(bufptr, *str);
823 	} else if (sscanf(str, "%%?%%{%d}%%>%%t%%{%d}%%+%%;", &c1, &c2) == 2) {
824 	    str = strchr(str, ';');
825 	    bufptr = save_tc_inequality(bufptr, c1, c2);
826 	} else if (sscanf(str, "%%?%%{%d}%%>%%t%%'%c'%%+%%;", &c1, &ch2) == 2) {
827 	    str = strchr(str, ';');
828 	    bufptr = save_tc_inequality(bufptr, c1, ch2);
829 	} else if (sscanf(str, "%%?%%'%c'%%>%%t%%{%d}%%+%%;", &ch1, &c2) == 2) {
830 	    str = strchr(str, ';');
831 	    bufptr = save_tc_inequality(bufptr, ch1, c2);
832 	} else if (sscanf(str, "%%?%%'%c'%%>%%t%%'%c'%%+%%;", &ch1, &ch2) == 2) {
833 	    str = strchr(str, ';');
834 	    bufptr = save_tc_inequality(bufptr, ch1, ch2);
835 	} else if ((len = bcd_expression(str)) != 0) {
836 	    str += len;
837 	    bufptr = save_string(bufptr, "%B");
838 	} else if ((sscanf(str, "%%{%d}%%+%%%c", &c1, &ch2) == 2
839 		    || sscanf(str, "%%'%c'%%+%%%c", &ch1, &ch2) == 2)
840 		   && ch2 == 'c'
841 		   && (cp = strchr(str, '+'))) {
842 	    str = cp + 2;
843 	    bufptr = save_string(bufptr, "%+");
844 
845 	    if (ch1)
846 		c1 = ch1;
847 	    bufptr = save_tc_char(bufptr, c1);
848 	}
849 	/* FIXME: this "works" for 'delta' */
850 	else if (strncmp(str, "%{2}%*%-", (size_t) 8) == 0) {
851 	    str += 7;
852 	    bufptr = save_string(bufptr, "%D");
853 	} else if (strncmp(str, "%{96}%^", (size_t) 7) == 0) {
854 	    str += 6;
855 	    if (saw_m++ == 0) {
856 		bufptr = save_string(bufptr, "%n");
857 	    }
858 	} else if (strncmp(str, "%{127}%^", (size_t) 8) == 0) {
859 	    str += 7;
860 	    if (saw_n++ == 0) {
861 		bufptr = save_string(bufptr, "%m");
862 	    }
863 	} else {		/* cm-style format element */
864 	    str++;
865 	    switch (*str) {
866 	    case '%':
867 		bufptr = save_char(bufptr, '%');
868 		break;
869 
870 	    case '0':
871 	    case '1':
872 	    case '2':
873 	    case '3':
874 	    case '4':
875 	    case '5':
876 	    case '6':
877 	    case '7':
878 	    case '8':
879 	    case '9':
880 		bufptr = save_char(bufptr, '%');
881 		ch1 = 0;
882 		ch2 = 0;
883 		digits = 0;
884 		while (isdigit(UChar(*str))) {
885 		    if (++digits > 2) {
886 			syntax_error = TRUE;
887 			break;
888 		    }
889 		    ch2 = ch1;
890 		    ch1 = *str++;
891 		    if (digits == 2 && ch2 != '0') {
892 			syntax_error = TRUE;
893 			break;
894 		    } else if (_nc_strict_bsd) {
895 			if (ch1 > '3') {
896 			    syntax_error = TRUE;
897 			    break;
898 			}
899 		    } else {
900 			bufptr = save_char(bufptr, ch1);
901 		    }
902 		}
903 		if (syntax_error)
904 		    break;
905 		/*
906 		 * Convert %02 to %2 and %03 to %3
907 		 */
908 		if (ch2 == '0' && !_nc_strict_bsd) {
909 		    ch2 = 0;
910 		    bufptr[-2] = bufptr[-1];
911 		    *--bufptr = 0;
912 		}
913 		if (_nc_strict_bsd) {
914 		    if (ch2 != 0 && ch2 != '0') {
915 			syntax_error = TRUE;
916 		    } else if (ch1 < '2') {
917 			ch1 = 'd';
918 		    }
919 		    bufptr = save_char(bufptr, ch1);
920 		}
921 		if (strchr("oxX.", *str)) {
922 		    syntax_error = TRUE;	/* termcap doesn't have octal, hex */
923 		}
924 		break;
925 
926 	    case 'd':
927 		bufptr = save_string(bufptr, "%d");
928 		break;
929 
930 	    case 'c':
931 		bufptr = save_string(bufptr, "%.");
932 		break;
933 
934 		/*
935 		 * %s isn't in termcap, but it's convenient to pass it through
936 		 * so we can represent things like terminfo pfkey strings in
937 		 * termcap notation.
938 		 */
939 	    case 's':
940 		if (_nc_strict_bsd) {
941 		    syntax_error = TRUE;
942 		} else {
943 		    bufptr = save_string(bufptr, "%s");
944 		}
945 		break;
946 
947 	    case 'p':
948 		str++;
949 		if (*str == '1')
950 		    seenone = 1;
951 		else if (*str == '2') {
952 		    if (!seenone && !seentwo) {
953 			bufptr = save_string(bufptr, "%r");
954 			seentwo++;
955 		    }
956 		} else if (*str >= '3') {
957 		    syntax_error = TRUE;
958 		}
959 		break;
960 
961 	    case 'i':
962 		bufptr = save_string(bufptr, "%i");
963 		break;
964 
965 	    default:
966 		bufptr = save_char(bufptr, *str);
967 		syntax_error = TRUE;
968 		break;
969 	    }			/* endswitch (*str) */
970 	}			/* endelse (*str == '%') */
971 
972 	/*
973 	 * 'str' always points to the end of what was scanned in this step,
974 	 * but that may not be the end of the string.
975 	 */
976 	assert(str != 0);
977 	if (str == 0 || *str == '\0')
978 	    break;
979 
980     }				/* endwhile (*str) */
981 
982     if (!syntax_error &&
983 	myfix > 0 &&
984 	((int) strlen(my_string) - (4 * myfix)) < MIN_TC_FIXUPS) {
985 	while (--myfix >= 0) {
986 	    char *p = fixups[myfix].offset + my_string;
987 	    *p++ = '^';
988 	    *p++ = (char) (fixups[myfix].ch | '@');
989 	    while ((p[0] = p[2]) != '\0') {
990 		++p;
991 	    }
992 	}
993     }
994 
995     DEBUG_THIS(("... _nc_infotocap %s",
996 		syntax_error
997 		? "<ERR>"
998 		: _nc_visbuf(my_string)));
999 
1000     return (syntax_error ? NULL : my_string);
1001 }
1002 
1003 #ifdef MAIN
1004 
1005 int curr_line;
1006 
1007 int
1008 main(int argc, char *argv[])
1009 {
1010     int c, tc = FALSE;
1011 
1012     while ((c = getopt(argc, argv, "c")) != EOF)
1013 	switch (c) {
1014 	case 'c':
1015 	    tc = TRUE;
1016 	    break;
1017 	}
1018 
1019     curr_line = 0;
1020     for (;;) {
1021 	char buf[BUFSIZ];
1022 
1023 	++curr_line;
1024 	if (fgets(buf, sizeof(buf), stdin) == 0)
1025 	    break;
1026 	buf[strlen(buf) - 1] = '\0';
1027 	_nc_set_source(buf);
1028 
1029 	if (tc) {
1030 	    char *cp = _nc_infotocap("to termcap", buf, 1);
1031 
1032 	    if (cp)
1033 		(void) fputs(cp, stdout);
1034 	} else
1035 	    (void) fputs(_nc_captoinfo("to terminfo", buf, 1), stdout);
1036 	(void) putchar('\n');
1037     }
1038     return (0);
1039 }
1040 #endif /* MAIN */
1041 
1042 #if NO_LEAKS
1043 NCURSES_EXPORT(void)
1044 _nc_captoinfo_leaks(void)
1045 {
1046     if (my_string != 0) {
1047 	FreeAndNull(my_string);
1048     }
1049     my_length = 0;
1050 }
1051 #endif
1052