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