]> ncurses.scripts.mit.edu Git - ncurses.git/blob - progs/tabs.c
7378d116f70c8f48c90df1357a6aa49f036bd771
[ncurses.git] / progs / tabs.c
1 /****************************************************************************
2  * Copyright 2020-2021,2022 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.51 2022/02/26 22:44:44 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
50 failed(const char *s)
51 {
52     perror(s);
53     ExitProgram(EXIT_FAILURE);
54 }
55
56 static int
57 putch(int c)
58 {
59     return putchar(c);
60 }
61
62 static char *
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
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
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 *
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
186 print_ruler(int *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
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 *
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
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 *
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
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     } else if (VALID_STRING(set_left_margin_parm)) {
374         result = TRUE;
375         if (!no_op) {
376             if (VALID_STRING(set_right_margin_parm)) {
377                 tputs(TIPARM_1(set_left_margin_parm, margin), 1, putch);
378             } else {
379                 tputs(TIPARM_2(set_left_margin_parm, margin, max_cols), 1, putch);
380             }
381         }
382     } else if (VALID_STRING(set_lr_margin)) {
383         result = TRUE;
384         if (!no_op) {
385             tputs(TIPARM_2(set_lr_margin, margin, max_cols), 1, putch);
386         }
387     }
388     return result;
389 }
390
391 /*
392  * Check for illegal characters in the tab-list.
393  */
394 static bool
395 legal_tab_list(const char *tab_list)
396 {
397     bool result = TRUE;
398
399     if (tab_list != 0 && *tab_list != '\0') {
400         if (comma_is_needed(tab_list)) {
401             int n;
402
403             for (n = 0; tab_list[n] != '\0'; ++n) {
404                 int ch = UChar(tab_list[n]);
405
406                 if (!(isdigit(ch) || ch == ',' || ch == '+')) {
407                     fprintf(stderr,
408                             "%s: unexpected character found '%c'\n",
409                             _nc_progname, ch);
410                     result = FALSE;
411                     break;
412                 }
413             }
414         } else {
415             fprintf(stderr, "%s: trailing comma found '%s'\n", _nc_progname, tab_list);
416             result = FALSE;
417         }
418     } else {
419         /* if no list given, default to "tabs -8" */
420     }
421     return result;
422 }
423
424 static char *
425 skip_list(char *value)
426 {
427     while (*value != '\0' &&
428            (isdigit(UChar(*value)) ||
429             isspace(UChar(*value)) ||
430             strchr("+,", UChar(*value)) != 0)) {
431         ++value;
432     }
433     return value;
434 }
435
436 static void
437 usage(void)
438 {
439 #define DATA(s) s "\n"
440     static const char msg[] =
441     {
442         DATA("Usage: tabs [options] [tabstop-list]")
443         DATA("")
444         DATA("Options:")
445         DATA("  -0       reset tabs")
446         DATA("  -8       set tabs to standard interval")
447         DATA("  -a       Assembler, IBM S/370, first format")
448         DATA("  -a2      Assembler, IBM S/370, second format")
449         DATA("  -c       COBOL, normal format")
450         DATA("  -c2      COBOL compact format")
451         DATA("  -c3      COBOL compact format extended")
452         DATA("  -d       debug (show ruler with expected/actual tab positions)")
453         DATA("  -f       FORTRAN")
454         DATA("  -n       no-op (do not modify terminal settings)")
455         DATA("  -p       PL/I")
456         DATA("  -s       SNOBOL")
457         DATA("  -u       UNIVAC 1100 Assembler")
458         DATA("  -T name  use terminal type 'name'")
459         DATA("  -V       print version")
460         DATA("")
461         DATA("A tabstop-list is an ordered list of column numbers, e.g., 1,11,21")
462         DATA("or 1,+10,+10 which is the same.")
463     };
464 #undef DATA
465
466     fflush(stdout);
467     fputs(msg, stderr);
468     ExitProgram(EXIT_FAILURE);
469 }
470
471 int
472 main(int argc, char *argv[])
473 {
474     int rc = EXIT_FAILURE;
475     bool debug = FALSE;
476     bool no_op = FALSE;
477     bool change_tty = FALSE;
478     int n, ch;
479     NCURSES_CONST char *term_name = 0;
480     char *append = 0;
481     const char *tab_list = 0;
482     const char *new_line = "\n";
483     int margin = -1;
484     TTY tty_settings;
485     int fd;
486
487     _nc_progname = _nc_rootname(argv[0]);
488
489     if ((term_name = getenv("TERM")) == 0)
490         term_name = "ansi+tabs";
491
492     /* cannot use getopt, since some options are two-character */
493     for (n = 1; n < argc; ++n) {
494         char *option = argv[n];
495         switch (option[0]) {
496         case '-':
497             while ((ch = *++option) != '\0') {
498                 switch (ch) {
499                 case 'a':
500                     switch (*++option) {
501                     default:
502                     case '\0':
503                         tab_list = "1,10,16,36,72";
504                         option--;
505                         /* Assembler, IBM S/370, first format */
506                         break;
507                     case '2':
508                         tab_list = "1,10,16,40,72";
509                         /* Assembler, IBM S/370, second format */
510                         break;
511                     }
512                     break;
513                 case 'c':
514                     switch (*++option) {
515                     default:
516                     case '\0':
517                         tab_list = "1,8,12,16,20,55";
518                         option--;
519                         /* COBOL, normal format */
520                         break;
521                     case '2':
522                         tab_list = "1,6,10,14,49";
523                         /* COBOL compact format */
524                         break;
525                     case '3':
526                         tab_list = "1,6,10,14,18,22,26,30,34,38,42,46,50,54,58,62,67";
527                         /* COBOL compact format extended */
528                         break;
529                     }
530                     break;
531                 case 'd':       /* ncurses extension */
532                     debug = TRUE;
533                     break;
534                 case 'f':
535                     tab_list = "1,7,11,15,19,23";
536                     /* FORTRAN */
537                     break;
538                 case 'n':       /* ncurses extension */
539                     no_op = TRUE;
540                     break;
541                 case 'p':
542                     tab_list = "1,5,9,13,17,21,25,29,33,37,41,45,49,53,57,61";
543                     /* PL/I */
544                     break;
545                 case 's':
546                     tab_list = "1,10,55";
547                     /* SNOBOL */
548                     break;
549                 case 'u':
550                     tab_list = "1,12,20,44";
551                     /* UNIVAC 1100 Assembler */
552                     break;
553                 case 'T':
554                     ++n;
555                     if (*++option != '\0') {
556                         term_name = option;
557                     } else {
558                         term_name = argv[n];
559                         option--;
560                     }
561                     option += ((int) strlen(option)) - 1;
562                     continue;
563                 case 'V':
564                     puts(curses_version());
565                     ExitProgram(EXIT_SUCCESS);
566                 default:
567                     if (isdigit(UChar(*option))) {
568                         char *copy = strdup(option);
569                         *skip_list(copy) = '\0';
570                         tab_list = copy;
571                         option = skip_list(option) - 1;
572                     } else {
573                         usage();
574                     }
575                     break;
576                 }
577             }
578             break;
579         case '+':
580             if ((ch = *++option) != '\0') {
581                 int digits = 0;
582                 int number = 0;
583
584                 switch (ch) {
585                 case 'm':
586                     /*
587                      * The "+mXXX" option is unimplemented because only the long-obsolete
588                      * att510d implements smgl, which is needed to support
589                      * this option.
590                      */
591                     while ((ch = *++option) != '\0') {
592                         if (isdigit(UChar(ch))) {
593                             ++digits;
594                             number = number * 10 + (ch - '0');
595                         } else {
596                             usage();
597                         }
598                     }
599                     if (digits == 0)
600                         number = 10;
601                     margin = number;
602                     break;
603                 default:
604                     /* special case of relative stops separated by spaces? */
605                     if (option == argv[n] + 1) {
606                         tab_list = add_to_tab_list(&append, argv[n]);
607                     }
608                     break;
609                 }
610             }
611             break;
612         default:
613             if (append != 0) {
614                 if (tab_list != (const char *) append) {
615                     /* one of the predefined options was used */
616                     free(append);
617                     append = 0;
618                 }
619             }
620             tab_list = add_to_tab_list(&append, option);
621             break;
622         }
623     }
624
625     fd = save_tty_settings(&tty_settings, FALSE);
626
627     setupterm(term_name, fd, (int *) 0);
628
629     max_cols = (columns > 0) ? columns : 80;
630     if (margin > 0)
631         max_cols -= margin;
632
633     if (!VALID_STRING(clear_all_tabs)) {
634         fprintf(stderr,
635                 "%s: terminal type '%s' cannot reset tabs\n",
636                 _nc_progname, term_name);
637     } else if (!VALID_STRING(set_tab)) {
638         fprintf(stderr,
639                 "%s: terminal type '%s' cannot set tabs\n",
640                 _nc_progname, term_name);
641     } else if (legal_tab_list(tab_list)) {
642         int *list;
643
644         if (tab_list == NULL)
645             tab_list = add_to_tab_list(&append, "8");
646
647         if (!no_op) {
648 #if defined(TERMIOS) && defined(OCRNL)
649             /* set tty modes to -ocrnl to allow \r */
650             if (isatty(STDOUT_FILENO)) {
651                 TTY new_settings = tty_settings;
652                 new_settings.c_oflag &= (unsigned)~OCRNL;
653                 update_tty_settings(&tty_settings, &new_settings);
654                 change_tty = TRUE;
655                 new_line = "\r\n";
656             }
657 #endif
658
659             if (!ansi_clear_tabs())
660                 putch('\r');
661             tputs(clear_all_tabs, 1, putch);
662         }
663
664         if (margin >= 0) {
665             putch('\r');
666             if (margin > 0) {
667                 /* reset existing margin before setting margin, to reduce
668                  * problems moving left of the current margin.
669                  */
670                 if (do_set_margin(0, no_op))
671                     putch('\r');
672             }
673             if (do_set_margin(margin, no_op))
674                 margin = -1;
675         }
676
677         list = decode_tabs(tab_list, margin);
678
679         if (list != 0) {
680             if (!no_op)
681                 do_tabs(list);
682             if (debug) {
683                 fflush(stderr);
684                 printf("tabs %s%s", tab_list, new_line);
685                 print_ruler(list, new_line);
686                 write_tabs(list, new_line);
687             }
688             free(list);
689         } else if (debug) {
690             fflush(stderr);
691             printf("tabs %s%s", tab_list, new_line);
692         }
693         if (!no_op) {
694             if (change_tty) {
695                 restore_tty_settings();
696             }
697         }
698         rc = EXIT_SUCCESS;
699     }
700     if (append != 0)
701         free(append);
702     ExitProgram(rc);
703 }