]> git.refcnt.org Git - colorize.git/blob - colorize.c
Merge declarations of boolean type
[colorize.git] / colorize.c
1 /*
2 * colorize - Read text from standard input stream or file and print
3 * it colorized through use of ANSI escape sequences
4 *
5 * Copyright (c) 2011-2013 Steven Schubiger
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 *
20 */
21
22 #define _POSIX_C_SOURCE 200809L
23 #include <assert.h>
24 #include <ctype.h>
25 #include <errno.h>
26 #include <getopt.h>
27 #include <stdarg.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/time.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <time.h>
35 #include <unistd.h>
36
37 #ifndef DEBUG
38 # define DEBUG 0
39 #endif
40
41 #define str(arg) #arg
42 #define to_str(arg) str(arg)
43
44 #define streq(s1, s2) (strcmp (s1, s2) == 0)
45
46 #if DEBUG
47 # define xmalloc(size) malloc_wrap_debug(size, __FILE__, __LINE__)
48 # define xcalloc(nmemb, size) calloc_wrap_debug(nmemb, size, __FILE__, __LINE__)
49 # define xrealloc(ptr, size) realloc_wrap_debug(ptr, size, __FILE__, __LINE__)
50 #else
51 # define xmalloc(size) malloc_wrap(size)
52 # define xcalloc(nmemb, size) calloc_wrap(nmemb, size)
53 # define xrealloc(ptr, size) realloc_wrap(ptr, size)
54 #endif
55
56 #define free_null(ptr) free_wrap((void **)&ptr)
57 #define xstrdup(str) strdup_wrap(str)
58
59 #if BUF_SIZE <= 0
60 # undef BUF_SIZE
61 #endif
62 #ifndef BUF_SIZE
63 # define BUF_SIZE 4096
64 #endif
65
66 #define LF 0x01
67 #define CR 0x02
68
69 #define SKIP_LINE_ENDINGS(flags) (((flags) & CR) && ((flags) & LF) ? 2 : 1)
70
71 #define STACK_VAR(ptr) do { \
72 stack_var (&vars_list, &stacked_vars, stacked_vars, ptr); \
73 } while (false)
74
75 #define RELEASE_VAR(ptr) do { \
76 release_var (vars_list, stacked_vars, (void **)&ptr); \
77 } while (false)
78
79 #define MEM_ALLOC_FAIL_DEBUG(file, line) do { \
80 fprintf (stderr, "Memory allocation failure in source file %s, line %u\n", file, line); \
81 exit (2); \
82 } while (false)
83 #define MEM_ALLOC_FAIL() do { \
84 fprintf (stderr, "%s: memory allocation failure\n", program_name); \
85 exit (2); \
86 } while (false)
87
88 #define ABORT_TRACE() \
89 fprintf (stderr, "Aborting in source file %s, line %u\n", __FILE__, __LINE__); \
90 abort (); \
91
92 #define CHECK_COLORS_RANDOM(color1, color2) \
93 streq (color_names[color1]->name, "random") \
94 && (streq (color_names[color2]->name, "none") \
95 || streq (color_names[color2]->name, "default")) \
96
97 #define COLOR_SEP_CHAR '/'
98
99 #define VERSION "0.52"
100
101 typedef enum { false, true } bool;
102
103 struct color_name {
104 char *name;
105 char *orig;
106 };
107
108 static struct color_name *color_names[3] = { NULL, NULL, NULL };
109
110 struct color {
111 const char *name;
112 const char *code;
113 };
114
115 static const struct color fg_colors[] = {
116 { "none", NULL },
117 { "black", "30m" },
118 { "red", "31m" },
119 { "green", "32m" },
120 { "yellow", "33m" },
121 { "blue", "34m" },
122 { "magenta", "35m" },
123 { "cyan", "36m" },
124 { "white", "37m" },
125 { "default", "39m" },
126 };
127 static const struct color bg_colors[] = {
128 { "none", NULL },
129 { "black", "40m" },
130 { "red", "41m" },
131 { "green", "42m" },
132 { "yellow", "43m" },
133 { "blue", "44m" },
134 { "magenta", "45m" },
135 { "cyan", "46m" },
136 { "white", "47m" },
137 { "default", "49m" },
138 };
139
140 enum fmts {
141 FMT_GENERIC,
142 FMT_COLOR,
143 FMT_RANDOM,
144 FMT_ERROR,
145 FMT_FILE
146 };
147 static const char *formats[] = {
148 "%s", /* generic */
149 "%s color '%s' %s", /* color */
150 "%s color '%s' %s '%s'", /* random */
151 "less than %u bytes %s", /* error */
152 "%s: %s", /* file */
153 };
154
155 enum { FOREGROUND, BACKGROUND };
156
157 static const struct {
158 struct color const *entries;
159 unsigned int count;
160 const char *desc;
161 } tables[] = {
162 { fg_colors, sizeof (fg_colors) / sizeof (struct color), "foreground" },
163 { bg_colors, sizeof (bg_colors) / sizeof (struct color), "background" },
164 };
165
166 static FILE *stream = NULL;
167
168 static unsigned int stacked_vars = 0;
169 static void **vars_list = NULL;
170
171 static bool clean = false;
172 static bool clean_all = false;
173
174 static char *exclude = NULL;
175
176 static const char *program_name;
177
178 static void print_help (void);
179 static void print_version (void);
180 static void cleanup (void);
181 static void free_color_names (struct color_name **);
182 static void process_args (unsigned int, char **, bool *, const struct color **, const char **, FILE **);
183 static void process_file_arg (const char *, const char **, FILE **);
184 static void read_print_stream (bool, const struct color **, const char *, FILE *);
185 static void find_color_entries (struct color_name **, const struct color **);
186 static void find_color_entry (const struct color_name *, unsigned int, const struct color **);
187 static void print_line (bool, const struct color **, const char * const, unsigned int);
188 static void print_clean (const char *);
189 static void print_free_offsets (const char *, char ***, unsigned int);
190 static void *malloc_wrap (size_t);
191 static void *calloc_wrap (size_t, size_t);
192 static void *realloc_wrap (void *, size_t);
193 static void *malloc_wrap_debug (size_t, const char *, unsigned int);
194 static void *calloc_wrap_debug (size_t, size_t, const char *, unsigned int);
195 static void *realloc_wrap_debug (void *, size_t, const char *, unsigned int);
196 static void free_wrap (void **);
197 static char *strdup_wrap (const char *);
198 static char *str_concat (const char *, const char *);
199 static bool has_color_name (const char *, const char *);
200 static void vfprintf_diag (const char *, ...);
201 static void vfprintf_fail (const char *, ...);
202 static void stack_var (void ***, unsigned int *, unsigned int, void *);
203 static void release_var (void **, unsigned int, void **);
204
205 #define SET_OPT_TYPE(type) \
206 opt_type = type; \
207 opt = 0; \
208 goto PARSE_OPT; \
209
210 extern char *optarg;
211 extern int optind;
212
213 int
214 main (int argc, char **argv)
215 {
216 unsigned int arg_cnt = 0;
217
218 enum {
219 OPT_CLEAN = 1,
220 OPT_CLEAN_ALL,
221 OPT_EXCLUDE_RANDOM,
222 OPT_HELP,
223 OPT_VERSION
224 };
225
226 int opt, opt_type = 0;
227 struct option long_opts[] = {
228 { "clean", no_argument, &opt_type, OPT_CLEAN },
229 { "clean-all", no_argument, &opt_type, OPT_CLEAN_ALL },
230 { "exclude-random", required_argument, &opt_type, OPT_EXCLUDE_RANDOM },
231 { "help", no_argument, &opt_type, OPT_HELP },
232 { "version", no_argument, &opt_type, OPT_VERSION },
233 { NULL, 0, NULL, 0 },
234 };
235
236 bool bold = false;
237
238 const struct color *colors[2] = {
239 NULL, /* foreground */
240 NULL, /* background */
241 };
242
243 const char *file = NULL;
244
245 program_name = argv[0];
246 atexit (cleanup);
247
248 setvbuf (stdout, NULL, _IOLBF, 0);
249
250 while ((opt = getopt_long (argc, argv, "hv", long_opts, NULL)) != -1)
251 {
252 PARSE_OPT:
253 switch (opt)
254 {
255 case 0: /* long opts */
256 switch (opt_type)
257 {
258 case OPT_CLEAN:
259 clean = true;
260 break;
261 case OPT_CLEAN_ALL:
262 clean_all = true;
263 break;
264 case OPT_EXCLUDE_RANDOM: {
265 bool valid = false;
266 unsigned int i;
267 exclude = xstrdup (optarg);
268 STACK_VAR (exclude);
269 for (i = 1; i < tables[FOREGROUND].count - 1; i++) /* skip color none and default */
270 {
271 const struct color *entry = &tables[FOREGROUND].entries[i];
272 if (streq (exclude, entry->name))
273 {
274 valid = true;
275 break;
276 }
277 }
278 if (!valid)
279 vfprintf_fail (formats[FMT_GENERIC], "--exclude-random switch must be provided a plain color");
280 break;
281 }
282 case OPT_HELP:
283 print_help ();
284 exit (EXIT_SUCCESS);
285 case OPT_VERSION:
286 print_version ();
287 exit (EXIT_SUCCESS);
288 default: /* never reached */
289 ABORT_TRACE ();
290 }
291 break;
292 case 'h':
293 SET_OPT_TYPE (OPT_HELP);
294 case 'v':
295 SET_OPT_TYPE (OPT_VERSION);
296 case '?':
297 print_help ();
298 exit (EXIT_FAILURE);
299 default: /* never reached */
300 ABORT_TRACE ();
301 }
302 }
303
304 arg_cnt = argc - optind;
305
306 if (clean || clean_all)
307 {
308 if (clean && clean_all)
309 vfprintf_fail (formats[FMT_GENERIC], "--clean and --clean-all switch are mutually exclusive");
310 if (arg_cnt > 1)
311 {
312 const char *format = "%s %s";
313 const char *message = "switch cannot be used with more than one file";
314 if (clean)
315 vfprintf_fail (format, "--clean", message);
316 else if (clean_all)
317 vfprintf_fail (format, "--clean-all", message);
318 }
319 }
320 else
321 {
322 if (arg_cnt == 0 || arg_cnt > 2)
323 {
324 vfprintf_diag ("%u arguments provided, expected 1-2 arguments or option", arg_cnt);
325 print_help ();
326 exit (EXIT_FAILURE);
327 }
328 }
329
330 if (clean || clean_all)
331 process_file_arg (argv[optind], &file, &stream);
332 else
333 process_args (arg_cnt, &argv[optind], &bold, colors, &file, &stream);
334 read_print_stream (bold, colors, file, stream);
335
336 RELEASE_VAR (exclude);
337
338 exit (EXIT_SUCCESS);
339 }
340
341 static void
342 print_help (void)
343 {
344 unsigned int i;
345
346 printf ("Usage: %s (foreground) OR (foreground)%c(background) OR --clean[-all] [-|file]\n\n", program_name, COLOR_SEP_CHAR);
347 printf ("\tColors (foreground) (background)\n");
348 for (i = 0; i < tables[FOREGROUND].count; i++)
349 {
350 const struct color *entry = &tables[FOREGROUND].entries[i];
351 const char *name = entry->name;
352 const char *code = entry->code;
353 if (code)
354 printf ("\t\t{\033[%s#\033[0m} [%c%c]%s%*s%s\n",
355 code, toupper (*name), *name, name + 1, 10 - (int)strlen (name), " ", name);
356 else
357 printf ("\t\t{-} %s%*s%s\n", name, 13 - (int)strlen (name), " ", name);
358 }
359 printf ("\t\t{*} [Rr]%s%*s%s [--exclude-random=<foreground color>]\n", "andom", 10 - (int)strlen ("random"), " ", "random");
360
361 printf ("\n\tFirst character of color name in upper case denotes increased intensity,\n");
362 printf ("\twhereas for lower case colors will be of normal intensity.\n");
363
364 printf ("\n\tOptions\n");
365 printf ("\t\t --clean\n");
366 printf ("\t\t --clean-all\n");
367 printf ("\t\t --exclude-random\n");
368 printf ("\t\t-h, --help\n");
369 printf ("\t\t-v, --version\n\n");
370 }
371
372 static void
373 print_version (void)
374 {
375 const char *c_flags;
376 bool debug;
377 #ifdef CFLAGS
378 c_flags = to_str (CFLAGS);
379 #else
380 c_flags = "unknown";
381 #endif
382 #if DEBUG
383 debug = true;
384 #else
385 debug = false;
386 #endif
387 printf ("%s v%s (compiled at %s, %s)\n", "colorize", VERSION, __DATE__, __TIME__);
388 printf ("Compiler flags: %s\n", c_flags);
389 printf ("Buffer size: %u bytes\n", BUF_SIZE);
390 printf ("Debugging: %s\n", debug ? "yes" : "no");
391 }
392
393 static void
394 cleanup (void)
395 {
396 free_color_names (color_names);
397
398 if (stream && fileno (stream) != STDIN_FILENO)
399 fclose (stream);
400
401 if (vars_list)
402 {
403 unsigned int i;
404 for (i = 0; i < stacked_vars; i++)
405 if (vars_list[i])
406 free_null (vars_list[i]);
407
408 free_null (vars_list);
409 }
410 }
411
412 static void
413 free_color_names (struct color_name **color_names)
414 {
415 unsigned int i;
416 for (i = 0; color_names[i]; i++)
417 {
418 free_null (color_names[i]->name);
419 free_null (color_names[i]->orig);
420 free_null (color_names[i]);
421 }
422 }
423
424 static void
425 process_args (unsigned int arg_cnt, char **arg_strings, bool *bold, const struct color **colors, const char **file, FILE **stream)
426 {
427 int ret;
428 unsigned int index;
429 char *color, *p, *str;
430 struct stat sb;
431
432 const char *color_string = arg_cnt >= 1 ? arg_strings[0] : NULL;
433 const char *file_string = arg_cnt == 2 ? arg_strings[1] : NULL;
434
435 assert (color_string);
436
437 if (streq (color_string, "-"))
438 {
439 if (file_string)
440 vfprintf_fail (formats[FMT_GENERIC], "hyphen cannot be used as color string");
441 else
442 vfprintf_fail (formats[FMT_GENERIC], "hyphen must be preceeded by color string");
443 }
444
445 ret = stat (color_string, &sb);
446
447 /* Ensure that we don't fail if there's a file with one or more
448 color names in its path. */
449 if (ret != -1)
450 {
451 bool have_file;
452 unsigned int c;
453 const char *color = color_string;
454
455 for (c = 1; c <= 2 && *color; c++)
456 {
457 bool matched = false;
458 unsigned int i;
459 for (i = 0; i < tables[FOREGROUND].count; i++)
460 {
461 const struct color *entry = &tables[FOREGROUND].entries[i];
462 if (has_color_name (color, entry->name))
463 {
464 color += strlen (entry->name);
465 matched = true;
466 break;
467 }
468 }
469 if (!matched && has_color_name (color, "random"))
470 {
471 color += strlen ("random");
472 matched = true;
473 }
474 if (matched && *color == COLOR_SEP_CHAR && *(color + 1))
475 color++;
476 else
477 break;
478 }
479
480 have_file = (*color != '\0');
481
482 if (have_file)
483 {
484 if (file_string)
485 vfprintf_fail (formats[FMT_GENERIC], "file cannot be used as color string");
486 else
487 vfprintf_fail (formats[FMT_GENERIC], "file must be preceeded by color string");
488 }
489 }
490
491 if ((p = strchr (color_string, COLOR_SEP_CHAR)))
492 {
493 if (p == color_string)
494 vfprintf_fail (formats[FMT_GENERIC], "foreground color missing");
495 else if (p == color_string + strlen (color_string) - 1)
496 vfprintf_fail (formats[FMT_GENERIC], "background color missing");
497 else if (strchr (++p, COLOR_SEP_CHAR))
498 vfprintf_fail (formats[FMT_GENERIC], "one color pair allowed only");
499 }
500
501 str = xstrdup (color_string);
502 STACK_VAR (str);
503
504 for (index = 0, color = str; *color; index++, color = p)
505 {
506 char *ch, *sep;
507
508 p = NULL;
509 if ((sep = strchr (color, COLOR_SEP_CHAR)))
510 {
511 *sep = '\0';
512 p = sep + 1;
513 }
514 else
515 p = color + strlen (color);
516 assert (p);
517
518 for (ch = color; *ch; ch++)
519 if (!isalpha (*ch))
520 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be made of non-alphabetic characters");
521
522 for (ch = color + 1; *ch; ch++)
523 if (!islower (*ch))
524 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be in mixed lower/upper case");
525
526 if (streq (color, "None"))
527 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be bold");
528
529 if (isupper (*color))
530 {
531 switch (index)
532 {
533 case FOREGROUND:
534 *bold = true;
535 break;
536 case BACKGROUND:
537 vfprintf_fail (formats[FMT_COLOR], tables[BACKGROUND].desc, color, "cannot be bold");
538 break;
539 default: /* never reached */
540 ABORT_TRACE ();
541 }
542 }
543
544 color_names[index] = xcalloc (1, sizeof (struct color_name));
545
546 color_names[index]->orig = xstrdup (color);
547
548 for (ch = color; *ch; ch++)
549 *ch = tolower (*ch);
550
551 color_names[index]->name = xstrdup (color);
552 }
553
554 RELEASE_VAR (str);
555
556 assert (color_names[FOREGROUND]);
557
558 if (color_names[BACKGROUND])
559 {
560 unsigned int i;
561 unsigned int color_sets[2][2] = { { FOREGROUND, BACKGROUND }, { BACKGROUND, FOREGROUND } };
562 for (i = 0; i < 2; i++)
563 {
564 unsigned int color1 = color_sets[i][0];
565 unsigned int color2 = color_sets[i][1];
566 if (CHECK_COLORS_RANDOM (color1, color2))
567 vfprintf_fail (formats[FMT_RANDOM], tables[color1].desc, color_names[color1]->orig, "cannot be combined with", color_names[color2]->orig);
568 }
569 }
570
571 find_color_entries (color_names, colors);
572 free_color_names (color_names);
573
574 if (!colors[FOREGROUND]->code && colors[BACKGROUND] && colors[BACKGROUND]->code)
575 {
576 struct color_name color_name;
577 color_name.name = color_name.orig = "default";
578
579 find_color_entry (&color_name, FOREGROUND, colors);
580 }
581
582 process_file_arg (file_string, file, stream);
583 }
584
585 static void
586 process_file_arg (const char *file_string, const char **file, FILE **stream)
587 {
588 if (file_string)
589 {
590 if (streq (file_string, "-"))
591 *stream = stdin;
592 else
593 {
594 FILE *s;
595 const char *file = file_string;
596 struct stat sb;
597 int errno, ret;
598
599 errno = 0;
600 ret = stat (file, &sb);
601
602 if (ret == -1)
603 vfprintf_fail (formats[FMT_FILE], file, strerror (errno));
604
605 if (!(S_ISREG (sb.st_mode) || S_ISLNK (sb.st_mode) || S_ISFIFO (sb.st_mode)))
606 vfprintf_fail (formats[FMT_FILE], file, "unrecognized file type");
607
608 errno = 0;
609
610 s = fopen (file, "r");
611 if (!s)
612 vfprintf_fail (formats[FMT_FILE], file, strerror (errno));
613 *stream = s;
614 }
615 *file = file_string;
616 }
617 else
618 {
619 *stream = stdin;
620 *file = "stdin";
621 }
622
623 assert (*stream);
624 assert (*file);
625 }
626
627 #define MERGE_PRINT_LINE(part_line, line, flags, check_eof) do { \
628 char *current_line, *merged_line = NULL; \
629 if (part_line) \
630 { \
631 merged_line = str_concat (part_line, line); \
632 free_null (part_line); \
633 } \
634 current_line = merged_line ? merged_line : (char *)line; \
635 if (!check_eof || *current_line != '\0') \
636 print_line (bold, colors, current_line, flags); \
637 free (merged_line); \
638 } while (false)
639
640 static void
641 read_print_stream (bool bold, const struct color **colors, const char *file, FILE *stream)
642 {
643 char buf[BUF_SIZE + 1], *part_line = NULL;
644 unsigned int flags = 0;
645
646 while (!feof (stream))
647 {
648 size_t bytes_read;
649 char *eol;
650 const char *line;
651 memset (buf, '\0', BUF_SIZE + 1);
652 bytes_read = fread (buf, 1, BUF_SIZE, stream);
653 if (bytes_read != BUF_SIZE && ferror (stream))
654 vfprintf_fail (formats[FMT_ERROR], BUF_SIZE, "read");
655 line = buf;
656 while ((eol = strpbrk (line, "\n\r")))
657 {
658 char *p;
659 flags &= ~(CR|LF);
660 if (*eol == '\r')
661 {
662 flags |= CR;
663 if (*(eol + 1) == '\n')
664 flags |= LF;
665 }
666 else if (*eol == '\n')
667 flags |= LF;
668 else
669 vfprintf_fail (formats[FMT_FILE], file, "unrecognized line ending");
670 p = eol + SKIP_LINE_ENDINGS (flags);
671 *eol = '\0';
672 MERGE_PRINT_LINE (part_line, line, flags, false);
673 line = p;
674 }
675 if (feof (stream)) {
676 MERGE_PRINT_LINE (part_line, line, 0, true);
677 }
678 else if (*line != '\0')
679 {
680 if (!clean && !clean_all) /* efficiency */
681 print_line (bold, colors, line, 0);
682 else if (!part_line)
683 part_line = xstrdup (line);
684 else
685 {
686 char *merged_line = str_concat (part_line, line);
687 free (part_line);
688 part_line = merged_line;
689 }
690 }
691 }
692 }
693
694 static void
695 find_color_entries (struct color_name **color_names, const struct color **colors)
696 {
697 struct timeval tv;
698 unsigned int index;
699
700 /* randomness */
701 gettimeofday (&tv, NULL);
702 srand (tv.tv_usec * tv.tv_sec);
703
704 for (index = 0; color_names[index]; index++)
705 {
706 const char *color_name = color_names[index]->name;
707
708 const unsigned int count = tables[index].count;
709 const struct color *const color_entries = tables[index].entries;
710
711 if (streq (color_name, "random"))
712 {
713 bool excludable;
714 unsigned int i;
715 do {
716 excludable = false;
717 i = rand() % (count - 2) + 1; /* omit color none and default */
718 switch (index)
719 {
720 case FOREGROUND:
721 /* --exclude-random */
722 if (exclude && streq (exclude, color_entries[i].name))
723 excludable = true;
724 else if (color_names[BACKGROUND] && streq (color_names[BACKGROUND]->name, color_entries[i].name))
725 excludable = true;
726 break;
727 case BACKGROUND:
728 if (streq (colors[FOREGROUND]->name, color_entries[i].name))
729 excludable = true;
730 break;
731 default: /* never reached */
732 ABORT_TRACE ();
733 }
734 } while (excludable);
735 colors[index] = (struct color *)&color_entries[i];
736 }
737 else
738 find_color_entry (color_names[index], index, colors);
739 }
740 }
741
742 static void
743 find_color_entry (const struct color_name *color_name, unsigned int index, const struct color **colors)
744 {
745 bool found = false;
746 unsigned int i;
747
748 const unsigned int count = tables[index].count;
749 const struct color *const color_entries = tables[index].entries;
750
751 for (i = 0; i < count; i++)
752 if (streq (color_name->name, color_entries[i].name))
753 {
754 colors[index] = (struct color *)&color_entries[i];
755 found = true;
756 break;
757 }
758 if (!found)
759 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color_name->orig, "not recognized");
760 }
761
762 static void
763 print_line (bool bold, const struct color **colors, const char *const line, unsigned int flags)
764 {
765 /* --clean[-all] */
766 if (clean || clean_all)
767 print_clean (line);
768 else
769 {
770 /* Foreground color code is guaranteed to be set when background color code is present. */
771 if (colors[BACKGROUND] && colors[BACKGROUND]->code)
772 printf ("\033[%s", colors[BACKGROUND]->code);
773 if (colors[FOREGROUND]->code)
774 printf ("\033[%s%s%s\033[0m", bold ? "1;" : "", colors[FOREGROUND]->code, line);
775 else
776 printf (formats[FMT_GENERIC], line);
777 }
778 if (flags & CR)
779 putchar ('\r');
780 if (flags & LF)
781 putchar ('\n');
782 }
783
784 static void
785 print_clean (const char *line)
786 {
787 const char *p;
788 char ***offsets = NULL;
789 unsigned int count = 0, i = 0;
790
791 for (p = line; *p;)
792 {
793 /* ESC[ */
794 if (*p == 27 && *(p + 1) == '[')
795 {
796 const char *begin = p;
797 p += 2;
798 if (clean_all)
799 {
800 while (isdigit (*p) || *p == ';')
801 p++;
802 }
803 else if (clean)
804 {
805 bool check_values;
806 unsigned int iter = 0;
807 const char *digit;
808 do {
809 check_values = false;
810 iter++;
811 if (!isdigit (*p))
812 goto DISCARD;
813 digit = p;
814 while (isdigit (*p))
815 p++;
816 if (p - digit > 2)
817 goto DISCARD;
818 else /* check range */
819 {
820 char val[3];
821 int value;
822 unsigned int i;
823 const unsigned int digits = p - digit;
824 for (i = 0; i < digits; i++)
825 val[i] = *digit++;
826 val[i] = '\0';
827 value = atoi (val);
828 if (value == 0) /* reset */
829 {
830 if (iter > 1)
831 goto DISCARD;
832 goto END;
833 }
834 else if (value == 1) /* bold */
835 {
836 bool discard = false;
837 if (iter > 1)
838 discard = true;
839 else if (*p != ';')
840 discard = true;
841 if (discard)
842 goto DISCARD;
843 p++;
844 check_values = true;
845 }
846 else if ((value >= 30 && value <= 37) || value == 39) /* foreground colors */
847 goto END;
848 else if ((value >= 40 && value <= 47) || value == 49) /* background colors */
849 {
850 if (iter > 1)
851 goto DISCARD;
852 goto END;
853 }
854 else
855 goto DISCARD;
856 }
857 } while (iter == 1 && check_values);
858 }
859 END: if (*p == 'm')
860 {
861 const char *end = p++;
862 if (!offsets)
863 offsets = xmalloc (++count * sizeof (char **));
864 else
865 offsets = xrealloc (offsets, ++count * sizeof (char **));
866 offsets[i] = xmalloc (2 * sizeof (char *));
867 offsets[i][0] = (char *)begin; /* ESC */
868 offsets[i][1] = (char *)end; /* m */
869 i++;
870 continue;
871 }
872 DISCARD:
873 continue;
874 }
875 p++;
876 }
877
878 if (offsets)
879 print_free_offsets (line, offsets, count);
880 else
881 printf (formats[FMT_GENERIC], line);
882 }
883
884 #define SET_CHAR(offset, new, old) \
885 *old = *offset; \
886 *offset = new; \
887
888 #define RESTORE_CHAR(offset, old) \
889 *offset = old; \
890
891 static void
892 print_free_offsets (const char *line, char ***offsets, unsigned int count)
893 {
894 char ch;
895 unsigned int i;
896
897 SET_CHAR (offsets[0][0], '\0', &ch);
898 printf (formats[FMT_GENERIC], line);
899 RESTORE_CHAR (offsets[0][0], ch);
900
901 for (i = 0; i < count; i++)
902 {
903 char ch;
904 bool next_offset = false;
905 if (i + 1 < count)
906 {
907 SET_CHAR (offsets[i + 1][0], '\0', &ch);
908 next_offset = true;
909 }
910 printf (formats[FMT_GENERIC], offsets[i][1] + 1);
911 if (next_offset)
912 RESTORE_CHAR (offsets[i + 1][0], ch);
913 }
914 for (i = 0; i < count; i++)
915 free_null (offsets[i]);
916 free_null (offsets);
917 }
918
919 static void *
920 malloc_wrap (size_t size)
921 {
922 void *p = malloc (size);
923 if (!p)
924 MEM_ALLOC_FAIL ();
925 return p;
926 }
927
928 static void *
929 calloc_wrap (size_t nmemb, size_t size)
930 {
931 void *p = calloc (nmemb, size);
932 if (!p)
933 MEM_ALLOC_FAIL ();
934 return p;
935 }
936
937 static void *
938 realloc_wrap (void *ptr, size_t size)
939 {
940 void *p = realloc (ptr, size);
941 if (!p)
942 MEM_ALLOC_FAIL ();
943 return p;
944 }
945
946 static void *
947 malloc_wrap_debug (size_t size, const char *file, unsigned int line)
948 {
949 void *p = malloc (size);
950 if (!p)
951 MEM_ALLOC_FAIL_DEBUG (file, line);
952 return p;
953 }
954
955 static void *
956 calloc_wrap_debug (size_t nmemb, size_t size, const char *file, unsigned int line)
957 {
958 void *p = calloc (nmemb, size);
959 if (!p)
960 MEM_ALLOC_FAIL_DEBUG (file, line);
961 return p;
962 }
963
964 static void *
965 realloc_wrap_debug (void *ptr, size_t size, const char *file, unsigned int line)
966 {
967 void *p = realloc (ptr, size);
968 if (!p)
969 MEM_ALLOC_FAIL_DEBUG (file, line);
970 return p;
971 }
972
973 static void
974 free_wrap (void **ptr)
975 {
976 free (*ptr);
977 *ptr = NULL;
978 }
979
980 static char *
981 strdup_wrap (const char *str)
982 {
983 const size_t len = strlen (str) + 1;
984 char *p = xmalloc (len);
985 strncpy (p, str, len);
986 return p;
987 }
988
989 static char *
990 str_concat (const char *str1, const char *str2)
991 {
992 const size_t len = strlen (str1) + strlen (str2) + 1;
993 char *p, *str;
994
995 p = str = xmalloc (len);
996 strncpy (p, str1, strlen (str1));
997 p += strlen (str1);
998 strncpy (p, str2, strlen (str2));
999 p += strlen (str2);
1000 *p = '\0';
1001
1002 return str;
1003 }
1004
1005 static bool
1006 has_color_name (const char *str, const char *name)
1007 {
1008 char *p;
1009
1010 assert (strlen (str));
1011 assert (strlen (name));
1012
1013 if (!(*str == *name || *str == toupper (*name)))
1014 return false;
1015 else if (*(name + 1) != '\0'
1016 && !((p = strstr (str + 1, name + 1)) && p == str + 1))
1017 return false;
1018
1019 return true;
1020 }
1021
1022 #define DO_VFPRINTF(fmt) \
1023 va_list ap; \
1024 fprintf (stderr, "%s: ", program_name); \
1025 va_start (ap, fmt); \
1026 vfprintf (stderr, fmt, ap); \
1027 va_end (ap); \
1028 fprintf (stderr, "\n"); \
1029
1030 static void
1031 vfprintf_diag (const char *fmt, ...)
1032 {
1033 DO_VFPRINTF (fmt);
1034 }
1035
1036 static void
1037 vfprintf_fail (const char *fmt, ...)
1038 {
1039 DO_VFPRINTF (fmt);
1040 exit (EXIT_FAILURE);
1041 }
1042
1043 static void
1044 stack_var (void ***list, unsigned int *stacked, unsigned int index, void *ptr)
1045 {
1046 /* nothing to stack */
1047 if (ptr == NULL)
1048 return;
1049 if (!*list)
1050 *list = xmalloc (sizeof (void *));
1051 else
1052 {
1053 unsigned int i;
1054 for (i = 0; i < *stacked; i++)
1055 if (!(*list)[i])
1056 {
1057 (*list)[i] = ptr;
1058 return; /* reused */
1059 }
1060 *list = xrealloc (*list, (*stacked + 1) * sizeof (void *));
1061 }
1062 (*list)[index] = ptr;
1063 (*stacked)++;
1064 }
1065
1066 static void
1067 release_var (void **list, unsigned int stacked, void **ptr)
1068 {
1069 unsigned int i;
1070 /* nothing to release */
1071 if (*ptr == NULL)
1072 return;
1073 for (i = 0; i < stacked; i++)
1074 if (list[i] == *ptr)
1075 {
1076 free (*ptr);
1077 *ptr = NULL;
1078 list[i] = NULL;
1079 return;
1080 }
1081 }