xref: /freebsd/contrib/ncurses/progs/tabs.c (revision 21817992b3314c908ab50f0bb88d2ee750b9c4ac)
1 /****************************************************************************
2  * Copyright 2020-2022,2023 Thomas E. Dickey                                *
3  * Copyright 2008-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: Thomas E. Dickey                        2008                    *
32  ****************************************************************************/
33 
34 /*
35  * tabs.c --  set terminal hard-tabstops
36  */
37 
38 #define USE_LIBTINFO
39 #include <progs.priv.h>
40 #include <tty_settings.h>
41 
42 MODULE_ID("$Id: tabs.c,v 1.53 2023/11/04 20:46:09 tom Exp $")
43 
44 static GCC_NORETURN void usage(void);
45 
46 const char *_nc_progname;
47 static int max_cols;
48 
49 static void
failed(const char * s)50 failed(const char *s)
51 {
52     perror(s);
53     ExitProgram(EXIT_FAILURE);
54 }
55 
56 static int
putch(int c)57 putch(int c)
58 {
59     return putchar(c);
60 }
61 
62 static char *
skip_csi(char * value)63 skip_csi(char *value)
64 {
65     if (UChar(*value) == 0x9b)
66 	++value;
67     else if (!strncmp(value, "\033[", 2))
68 	value += 2;
69     return value;
70 }
71 
72 /*
73  * If the terminal uses ANSI clear_all_tabs, then it is not necessary to first
74  * move to the left margin before clearing tabs.
75  */
76 static bool
ansi_clear_tabs(void)77 ansi_clear_tabs(void)
78 {
79     bool result = FALSE;
80     if (VALID_STRING(clear_all_tabs)) {
81 	char *param = skip_csi(clear_all_tabs);
82 	if (!strcmp(param, "3g"))
83 	    result = TRUE;
84     }
85     return result;
86 }
87 
88 static void
do_tabs(int * tab_list)89 do_tabs(int *tab_list)
90 {
91     int last = 1;
92     int stop;
93     bool first = TRUE;
94 
95     while ((stop = *tab_list++) > 0) {
96 	if (first) {
97 	    first = FALSE;
98 	    putchar('\r');
99 	}
100 	if (last < stop) {
101 	    while (last++ < stop) {
102 		if (last > max_cols)
103 		    break;
104 		putchar(' ');
105 	    }
106 	}
107 	if (stop <= max_cols) {
108 	    tputs(set_tab, 1, putch);
109 	    last = stop;
110 	} else {
111 	    break;
112 	}
113     }
114     putchar('\r');
115 }
116 
117 /*
118  * Decode a list of tab-stops from a string, returning an array of integers.
119  * If the margin is positive (because the terminal does not support margins),
120  * work around this by adding the margin to the decoded values.
121  */
122 static int *
decode_tabs(const char * tab_list,int margin)123 decode_tabs(const char *tab_list, int margin)
124 {
125     int *result = typeCalloc(int, strlen(tab_list) + (unsigned) max_cols);
126     int n = 0;
127     int value = 0;
128     int prior = 0;
129     int ch;
130 
131     if (result == NULL)
132 	failed("decode_tabs");
133 
134     if (margin < 0)
135 	margin = 0;
136 
137     while ((ch = *tab_list++) != '\0') {
138 	if (isdigit(UChar(ch))) {
139 	    value *= 10;
140 	    value += (ch - '0');
141 	    if (value > max_cols)
142 		value = max_cols;
143 	} else if (ch == ',') {
144 	    result[n] = value + prior + margin;
145 	    if (n > 0 && result[n] <= result[n - 1]) {
146 		fprintf(stderr,
147 			"%s: tab-stops are not in increasing order: %d %d\n",
148 			_nc_progname, value, result[n - 1]);
149 		free(result);
150 		result = 0;
151 		break;
152 	    }
153 	    ++n;
154 	    value = 0;
155 	    prior = 0;
156 	} else if (ch == '+') {
157 	    if (n)
158 		prior = result[n - 1];
159 	}
160     }
161 
162     if (result != 0) {
163 	/*
164 	 * If there is only one value, then it is an option such as "-8".
165 	 */
166 	if ((n == 0) && (value > 0)) {
167 	    int step = value;
168 	    value = 1;
169 	    while (n < max_cols - 1) {
170 		result[n++] = value + margin;
171 		value += step;
172 	    }
173 	}
174 
175 	/*
176 	 * Add the last value, if any.
177 	 */
178 	result[n++] = value + prior + margin;
179 	result[n] = 0;
180     }
181 
182     return result;
183 }
184 
185 static void
print_ruler(const int * const tab_list,const char * new_line)186 print_ruler(const int *const tab_list, const char *new_line)
187 {
188     int last = 0;
189     int n;
190 
191     /* first print a readable ruler */
192     for (n = 0; n < max_cols; n += 10) {
193 	int ch = 1 + (n / 10);
194 	char buffer[20];
195 	_nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
196 		    "----+----%c",
197 		    ((ch < 10)
198 		     ? (ch + '0')
199 		     : (ch + 'A' - 10)));
200 	printf("%.*s", ((max_cols - n) > 10) ? 10 : (max_cols - n), buffer);
201     }
202     printf("%s", new_line);
203 
204     /* now, print '*' for each stop */
205     for (n = 0, last = 0; (tab_list[n] > 0) && (last < max_cols); ++n) {
206 	int stop = tab_list[n];
207 
208 	while (++last < stop) {
209 	    if (last <= max_cols) {
210 		putchar('-');
211 	    } else {
212 		break;
213 	    }
214 	}
215 	if (last <= max_cols) {
216 	    putchar('*');
217 	    last = stop;
218 	} else {
219 	    break;
220 	}
221     }
222     while (++last <= max_cols)
223 	putchar('-');
224     printf("%s", new_line);
225 }
226 
227 /*
228  * Write an '*' on each tabstop, to demonstrate whether it lines up with the
229  * ruler.
230  */
231 static void
write_tabs(int * tab_list,const char * new_line)232 write_tabs(int *tab_list, const char *new_line)
233 {
234     int stop;
235 
236     while ((stop = *tab_list++) > 0 && stop <= max_cols) {
237 	fputs((stop == 1) ? "*" : "\t*", stdout);
238     };
239     /* also show a tab _past_ the stops */
240     if (stop < max_cols)
241 	fputs("\t+", stdout);
242     fputs(new_line, stdout);
243 }
244 
245 /*
246  * Trim leading/trailing blanks, as well as blanks after a comma.
247  * Convert embedded blanks to commas.
248  */
249 static char *
trimmed_tab_list(const char * source)250 trimmed_tab_list(const char *source)
251 {
252     char *result = strdup(source);
253     if (result != 0) {
254 	int j, k, last;
255 
256 	for (j = k = last = 0; result[j] != 0; ++j) {
257 	    int ch = UChar(result[j]);
258 	    if (isspace(ch)) {
259 		if (last == '\0') {
260 		    continue;
261 		} else if (isdigit(last) || last == ',') {
262 		    ch = ',';
263 		}
264 	    } else if (ch == ',') {
265 		;
266 	    } else {
267 		if (last == ',')
268 		    result[k++] = (char) last;
269 		result[k++] = (char) ch;
270 	    }
271 	    last = ch;
272 	}
273 	result[k] = '\0';
274     }
275     return result;
276 }
277 
278 static bool
comma_is_needed(const char * source)279 comma_is_needed(const char *source)
280 {
281     bool result = FALSE;
282 
283     if (source != 0) {
284 	size_t len = strlen(source);
285 	if (len != 0)
286 	    result = (source[len - 1] != ',');
287     } else {
288 	result = FALSE;
289     }
290     return result;
291 }
292 
293 /*
294  * Add a command-line parameter to the tab-list.  It can be blank- or comma-
295  * separated (or a mixture).  For simplicity, empty tabs are ignored, e.g.,
296  *	tabs 1,,6,11
297  *	tabs 1,6,11
298  * are treated the same.
299  */
300 static const char *
add_to_tab_list(char ** append,const char * value)301 add_to_tab_list(char **append, const char *value)
302 {
303     char *result = *append;
304     char *copied = trimmed_tab_list(value);
305 
306     if (copied != 0 && *copied != '\0') {
307 	const char *comma = ",";
308 	size_t need = 1 + strlen(copied);
309 
310 	if (*copied == ',')
311 	    comma = "";
312 	else if (!comma_is_needed(*append))
313 	    comma = "";
314 
315 	need += strlen(comma);
316 	if (*append != 0)
317 	    need += strlen(*append);
318 
319 	result = malloc(need);
320 	if (result == 0)
321 	    failed("add_to_tab_list");
322 
323 	*result = '\0';
324 	if (*append != 0) {
325 	    _nc_STRCPY(result, *append, need);
326 	    free(*append);
327 	}
328 	_nc_STRCAT(result, comma, need);
329 	_nc_STRCAT(result, copied, need);
330 
331 	*append = result;
332     }
333     free(copied);
334     return result;
335 }
336 
337 /*
338  * If the terminal supports it, (re)set the left margin and return true.
339  * Otherwise, return false.
340  */
341 static bool
do_set_margin(int margin,bool no_op)342 do_set_margin(int margin, bool no_op)
343 {
344     bool result = FALSE;
345 
346     if (margin == 0) {		/* 0 is special case for resetting */
347 	if (VALID_STRING(clear_margins)) {
348 	    result = TRUE;
349 	    if (!no_op)
350 		tputs(clear_margins, 1, putch);
351 	}
352     } else if (margin-- < 0) {	/* margin will be 0-based from here on */
353 	result = TRUE;
354     } else if (VALID_STRING(set_left_margin)) {
355 	result = TRUE;
356 	if (!no_op) {
357 	    /*
358 	     * assuming we're on the first column of the line, move the cursor
359 	     * to the column at which we will set a margin.
360 	     */
361 	    if (VALID_STRING(column_address)) {
362 		tputs(TIPARM_1(column_address, margin), 1, putch);
363 	    } else if (margin >= 1) {
364 		if (VALID_STRING(parm_right_cursor)) {
365 		    tputs(TIPARM_1(parm_right_cursor, margin), 1, putch);
366 		} else {
367 		    while (margin-- > 0)
368 			putch(' ');
369 		}
370 	    }
371 	    tputs(set_left_margin, 1, putch);
372 	}
373     }
374 #if defined(set_left_margin_parm) && defined(set_right_margin_parm)
375     else if (VALID_STRING(set_left_margin_parm)) {
376 	result = TRUE;
377 	if (!no_op) {
378 	    if (VALID_STRING(set_right_margin_parm)) {
379 		tputs(TIPARM_1(set_left_margin_parm, margin), 1, putch);
380 	    } else {
381 		tputs(TIPARM_2(set_left_margin_parm, margin, max_cols), 1, putch);
382 	    }
383 	}
384     }
385 #endif
386 #if defined(set_lr_margin)
387     else if (VALID_STRING(set_lr_margin)) {
388 	result = TRUE;
389 	if (!no_op) {
390 	    tputs(TIPARM_2(set_lr_margin, margin, max_cols), 1, putch);
391 	}
392     }
393 #endif
394     return result;
395 }
396 
397 /*
398  * Check for illegal characters in the tab-list.
399  */
400 static bool
legal_tab_list(const char * tab_list)401 legal_tab_list(const char *tab_list)
402 {
403     bool result = TRUE;
404 
405     if (tab_list != 0 && *tab_list != '\0') {
406 	if (comma_is_needed(tab_list)) {
407 	    int n;
408 
409 	    for (n = 0; tab_list[n] != '\0'; ++n) {
410 		int ch = UChar(tab_list[n]);
411 
412 		if (!(isdigit(ch) || ch == ',' || ch == '+')) {
413 		    fprintf(stderr,
414 			    "%s: unexpected character found '%c'\n",
415 			    _nc_progname, ch);
416 		    result = FALSE;
417 		    break;
418 		}
419 	    }
420 	} else {
421 	    fprintf(stderr, "%s: trailing comma found '%s'\n", _nc_progname, tab_list);
422 	    result = FALSE;
423 	}
424     } else {
425 	/* if no list given, default to "tabs -8" */
426     }
427     return result;
428 }
429 
430 static char *
skip_list(char * value)431 skip_list(char *value)
432 {
433     while (*value != '\0' &&
434 	   (isdigit(UChar(*value)) ||
435 	    isspace(UChar(*value)) ||
436 	    strchr("+,", UChar(*value)) != 0)) {
437 	++value;
438     }
439     return value;
440 }
441 
442 static void
usage(void)443 usage(void)
444 {
445 #define DATA(s) s "\n"
446     static const char msg[] =
447     {
448 	DATA("Usage: tabs [options] [tabstop-list]")
449 	DATA("")
450 	DATA("Options:")
451 	DATA("  -0       reset tabs")
452 	DATA("  -8       set tabs to standard interval")
453 	DATA("  -a       Assembler, IBM S/370, first format")
454 	DATA("  -a2      Assembler, IBM S/370, second format")
455 	DATA("  -c       COBOL, normal format")
456 	DATA("  -c2      COBOL compact format")
457 	DATA("  -c3      COBOL compact format extended")
458 	DATA("  -d       debug (show ruler with expected/actual tab positions)")
459 	DATA("  -f       FORTRAN")
460 	DATA("  -n       no-op (do not modify terminal settings)")
461 	DATA("  -p       PL/I")
462 	DATA("  -s       SNOBOL")
463 	DATA("  -u       UNIVAC 1100 Assembler")
464 	DATA("  -T name  use terminal type 'name'")
465 	DATA("  -V       print version")
466 	DATA("")
467 	DATA("A tabstop-list is an ordered list of column numbers, e.g., 1,11,21")
468 	DATA("or 1,+10,+10 which is the same.")
469     };
470 #undef DATA
471 
472     fflush(stdout);
473     fputs(msg, stderr);
474     ExitProgram(EXIT_FAILURE);
475 }
476 
477 int
main(int argc,char * argv[])478 main(int argc, char *argv[])
479 {
480     int rc = EXIT_FAILURE;
481     bool debug = FALSE;
482     bool no_op = FALSE;
483     bool change_tty = FALSE;
484     int n, ch;
485     NCURSES_CONST char *term_name = 0;
486     char *append = 0;
487     const char *tab_list = 0;
488     const char *new_line = "\n";
489     int margin = -1;
490     TTY tty_settings;
491     int fd;
492 
493     _nc_progname = _nc_rootname(argv[0]);
494 
495     if ((term_name = getenv("TERM")) == 0)
496 	term_name = "ansi+tabs";
497 
498     /* cannot use getopt, since some options are two-character */
499     for (n = 1; n < argc; ++n) {
500 	char *option = argv[n];
501 	switch (option[0]) {
502 	case '-':
503 	    while ((ch = *++option) != '\0') {
504 		switch (ch) {
505 		case 'a':
506 		    switch (*++option) {
507 		    default:
508 		    case '\0':
509 			tab_list = "1,10,16,36,72";
510 			option--;
511 			/* Assembler, IBM S/370, first format */
512 			break;
513 		    case '2':
514 			tab_list = "1,10,16,40,72";
515 			/* Assembler, IBM S/370, second format */
516 			break;
517 		    }
518 		    break;
519 		case 'c':
520 		    switch (*++option) {
521 		    default:
522 		    case '\0':
523 			tab_list = "1,8,12,16,20,55";
524 			option--;
525 			/* COBOL, normal format */
526 			break;
527 		    case '2':
528 			tab_list = "1,6,10,14,49";
529 			/* COBOL compact format */
530 			break;
531 		    case '3':
532 			tab_list = "1,6,10,14,18,22,26,30,34,38,42,46,50,54,58,62,67";
533 			/* COBOL compact format extended */
534 			break;
535 		    }
536 		    break;
537 		case 'd':	/* ncurses extension */
538 		    debug = TRUE;
539 		    break;
540 		case 'f':
541 		    tab_list = "1,7,11,15,19,23";
542 		    /* FORTRAN */
543 		    break;
544 		case 'n':	/* ncurses extension */
545 		    no_op = TRUE;
546 		    break;
547 		case 'p':
548 		    tab_list = "1,5,9,13,17,21,25,29,33,37,41,45,49,53,57,61";
549 		    /* PL/I */
550 		    break;
551 		case 's':
552 		    tab_list = "1,10,55";
553 		    /* SNOBOL */
554 		    break;
555 		case 'u':
556 		    tab_list = "1,12,20,44";
557 		    /* UNIVAC 1100 Assembler */
558 		    break;
559 		case 'T':
560 		    ++n;
561 		    if (*++option != '\0') {
562 			term_name = option;
563 		    } else {
564 			term_name = argv[n];
565 			option--;
566 		    }
567 		    option += ((int) strlen(option)) - 1;
568 		    continue;
569 		case 'V':
570 		    puts(curses_version());
571 		    ExitProgram(EXIT_SUCCESS);
572 		default:
573 		    if (isdigit(UChar(*option))) {
574 			char *copy = strdup(option);
575 			*skip_list(copy) = '\0';
576 			tab_list = copy;
577 			option = skip_list(option) - 1;
578 		    } else {
579 			usage();
580 		    }
581 		    break;
582 		}
583 	    }
584 	    break;
585 	case '+':
586 	    if ((ch = *++option) != '\0') {
587 		int digits = 0;
588 		int number = 0;
589 
590 		switch (ch) {
591 		case 'm':
592 		    /*
593 		     * The "+mXXX" option is unimplemented because only the long-obsolete
594 		     * att510d implements smgl, which is needed to support
595 		     * this option.
596 		     */
597 		    while ((ch = *++option) != '\0') {
598 			if (isdigit(UChar(ch))) {
599 			    ++digits;
600 			    number = number * 10 + (ch - '0');
601 			} else {
602 			    usage();
603 			}
604 		    }
605 		    if (digits == 0)
606 			number = 10;
607 		    margin = number;
608 		    break;
609 		default:
610 		    /* special case of relative stops separated by spaces? */
611 		    if (option == argv[n] + 1) {
612 			tab_list = add_to_tab_list(&append, argv[n]);
613 		    }
614 		    break;
615 		}
616 	    }
617 	    break;
618 	default:
619 	    if (append != 0) {
620 		if (tab_list != (const char *) append) {
621 		    /* one of the predefined options was used */
622 		    free(append);
623 		    append = 0;
624 		}
625 	    }
626 	    tab_list = add_to_tab_list(&append, option);
627 	    break;
628 	}
629     }
630 
631     fd = save_tty_settings(&tty_settings, FALSE);
632 
633     setupterm(term_name, fd, (int *) 0);
634 
635     max_cols = (columns > 0) ? columns : 80;
636     if (margin > 0)
637 	max_cols -= margin;
638 
639     if (!VALID_STRING(clear_all_tabs)) {
640 	fprintf(stderr,
641 		"%s: terminal type '%s' cannot reset tabs\n",
642 		_nc_progname, term_name);
643     } else if (!VALID_STRING(set_tab)) {
644 	fprintf(stderr,
645 		"%s: terminal type '%s' cannot set tabs\n",
646 		_nc_progname, term_name);
647     } else if (legal_tab_list(tab_list)) {
648 	int *list;
649 
650 	if (tab_list == NULL)
651 	    tab_list = add_to_tab_list(&append, "8");
652 
653 	if (!no_op) {
654 #if defined(TERMIOS) && defined(OCRNL)
655 	    /* set tty modes to -ocrnl to allow \r */
656 	    if (isatty(STDOUT_FILENO)) {
657 		TTY new_settings = tty_settings;
658 		new_settings.c_oflag &= (unsigned) ~OCRNL;
659 		update_tty_settings(&tty_settings, &new_settings);
660 		change_tty = TRUE;
661 		new_line = "\r\n";
662 	    }
663 #endif
664 
665 	    if (!ansi_clear_tabs())
666 		putch('\r');
667 	    tputs(clear_all_tabs, 1, putch);
668 	}
669 
670 	if (margin >= 0) {
671 	    putch('\r');
672 	    if (margin > 0) {
673 		/* reset existing margin before setting margin, to reduce
674 		 * problems moving left of the current margin.
675 		 */
676 		if (do_set_margin(0, no_op))
677 		    putch('\r');
678 	    }
679 	    if (do_set_margin(margin, no_op))
680 		margin = -1;
681 	}
682 
683 	list = decode_tabs(tab_list, margin);
684 
685 	if (list != 0) {
686 	    if (!no_op)
687 		do_tabs(list);
688 	    if (debug) {
689 		fflush(stderr);
690 		printf("tabs %s%s", tab_list, new_line);
691 		print_ruler(list, new_line);
692 		write_tabs(list, new_line);
693 	    }
694 	    free(list);
695 	} else if (debug) {
696 	    fflush(stderr);
697 	    printf("tabs %s%s", tab_list, new_line);
698 	}
699 	if (!no_op) {
700 	    if (change_tty) {
701 		restore_tty_settings();
702 	    }
703 	}
704 	rc = EXIT_SUCCESS;
705     }
706     if (append != 0)
707 	free(append);
708     ExitProgram(rc);
709 }
710