]> git.refcnt.org Git - colorize.git/blob - colorize.c
colorize 0.52
[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 !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.52"
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 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 char *p;
266 exclude = xstrdup (optarg);
267 STACK_VAR (exclude);
268 for (p = exclude; *p; p++)
269 *p = tolower (*p);
270 if (streq (exclude, "random"))
271 vfprintf_fail (formats[FMT_GENERIC], "--exclude-random switch must be provided a color");
272 break;
273 }
274 case OPT_HELP:
275 print_help ();
276 exit (EXIT_SUCCESS);
277 case OPT_VERSION:
278 print_version ();
279 exit (EXIT_SUCCESS);
280 default: /* never reached */
281 ABORT_TRACE ();
282 }
283 break;
284 case 'h':
285 SET_OPT_TYPE (OPT_HELP);
286 case 'v':
287 SET_OPT_TYPE (OPT_VERSION);
288 case '?':
289 print_help ();
290 exit (EXIT_FAILURE);
291 default: /* never reached */
292 ABORT_TRACE ();
293 }
294 }
295
296 arg_cnt = argc - optind;
297
298 if (clean || clean_all)
299 {
300 if (clean && clean_all)
301 vfprintf_fail (formats[FMT_GENERIC], "--clean and --clean-all switch are mutually exclusive");
302 if (arg_cnt > 1)
303 {
304 const char *format = "%s %s";
305 const char *message = "switch cannot be used with more than one file";
306 if (clean)
307 vfprintf_fail (format, "--clean", message);
308 else if (clean_all)
309 vfprintf_fail (format, "--clean-all", message);
310 }
311 }
312 else
313 {
314 if (arg_cnt == 0 || arg_cnt > 2)
315 {
316 vfprintf_diag ("%u arguments provided, expected 1-2 arguments or option", arg_cnt);
317 print_help ();
318 exit (EXIT_FAILURE);
319 }
320 }
321
322 if (clean || clean_all)
323 process_file_arg (argv[optind], &file, &stream);
324 else
325 process_args (arg_cnt, &argv[optind], &bold, colors, &file, &stream);
326 read_print_stream (bold, colors, file, stream);
327
328 RELEASE_VAR (exclude);
329
330 exit (EXIT_SUCCESS);
331 }
332
333 static void
334 print_help (void)
335 {
336 unsigned int i;
337
338 printf ("Usage: %s (foreground) OR (foreground)%c(background) OR --clean[-all] [-|file]\n\n", program_name, COLOR_SEP_CHAR);
339 printf ("\tColors (foreground) (background)\n");
340 for (i = 0; i < tables[FOREGROUND].count; i++)
341 {
342 const struct color *entry = &tables[FOREGROUND].entries[i];
343 const char *name = entry->name;
344 const char *code = entry->code;
345 if (code)
346 printf ("\t\t{\033[%s#\033[0m} [%c%c]%s%*s%s\n",
347 code, toupper (*name), *name, name + 1, 10 - (int)strlen (name), " ", name);
348 else
349 printf ("\t\t{-} %s%*s%s\n", name, 13 - (int)strlen (name), " ", name);
350 }
351 printf ("\t\t{*} [Rr]%s%*s%s [--exclude-random=<foreground color>]\n", "andom", 10 - (int)strlen ("random"), " ", "random");
352
353 printf ("\n\tFirst character of color name in upper case denotes increased intensity,\n");
354 printf ("\twhereas for lower case colors will be of normal intensity.\n");
355
356 printf ("\n\tOptions\n");
357 printf ("\t\t --clean\n");
358 printf ("\t\t --clean-all\n");
359 printf ("\t\t --exclude-random\n");
360 printf ("\t\t-h, --help\n");
361 printf ("\t\t-v, --version\n\n");
362 }
363
364 static void
365 print_version (void)
366 {
367 const char *c_flags;
368 printf ("%s v%s (compiled at %s, %s)\n", "colorize", VERSION, __DATE__, __TIME__);
369 #ifdef CFLAGS
370 c_flags = to_str (CFLAGS);
371 #else
372 c_flags = "unknown";
373 #endif
374 printf ("Compiler flags: %s\n", c_flags);
375 printf ("Buffer size: %u bytes\n", BUF_SIZE - 1);
376 }
377
378 static void
379 cleanup (void)
380 {
381 free_color_names (color_names);
382
383 if (stream && fileno (stream) != STDIN_FILENO)
384 fclose (stream);
385
386 if (vars_list)
387 {
388 unsigned int i;
389 for (i = 0; i < stacked_vars; i++)
390 if (vars_list[i])
391 free_null (vars_list[i]);
392
393 free_null (vars_list);
394 }
395 }
396
397 static void
398 free_color_names (struct color_name **color_names)
399 {
400 unsigned int i;
401 for (i = 0; color_names[i]; i++)
402 {
403 free_null (color_names[i]->name);
404 free_null (color_names[i]->orig);
405 free_null (color_names[i]);
406 }
407 }
408
409 static void
410 process_args (unsigned int arg_cnt, char **arg_strings, bool *bold, const struct color **colors, const char **file, FILE **stream)
411 {
412 int ret;
413 unsigned int index;
414 char *color, *p, *str;
415 struct stat sb;
416
417 const char *color_string = arg_cnt >= 1 ? arg_strings[0] : NULL;
418 const char *file_string = arg_cnt == 2 ? arg_strings[1] : NULL;
419
420 assert (color_string);
421
422 if (streq (color_string, "-"))
423 {
424 if (file_string)
425 vfprintf_fail (formats[FMT_GENERIC], "hyphen cannot be used as color string");
426 else
427 vfprintf_fail (formats[FMT_GENERIC], "hyphen must be preceeded by color string");
428 }
429
430 ret = stat (color_string, &sb);
431
432 /* Ensure that we don't fail if there's a file with one or more
433 color names in its path. */
434 if (ret != -1)
435 {
436 bool have_file;
437 unsigned int c;
438 const char *color = color_string;
439
440 for (c = 1; c <= 2 && *color; c++)
441 {
442 bool matched = false;
443 unsigned int i;
444 for (i = 0; i < tables[FOREGROUND].count; i++)
445 {
446 const struct color *entry = &tables[FOREGROUND].entries[i];
447 if (has_color_name (color, entry->name))
448 {
449 color += strlen (entry->name);
450 matched = true;
451 break;
452 }
453 }
454 if (!matched && has_color_name (color, "random"))
455 {
456 color += strlen ("random");
457 matched = true;
458 }
459 if (matched && *color == COLOR_SEP_CHAR && *(color + 1))
460 color++;
461 else
462 break;
463 }
464
465 have_file = (*color != '\0');
466
467 if (have_file)
468 {
469 if (file_string)
470 vfprintf_fail (formats[FMT_GENERIC], "file cannot be used as color string");
471 else
472 vfprintf_fail (formats[FMT_GENERIC], "file must be preceeded by color string");
473 }
474 }
475
476 if ((p = strchr (color_string, COLOR_SEP_CHAR)))
477 {
478 if (p == color_string)
479 vfprintf_fail (formats[FMT_GENERIC], "foreground color missing");
480 else if (p == color_string + strlen (color_string) - 1)
481 vfprintf_fail (formats[FMT_GENERIC], "background color missing");
482 else if (strchr (++p, COLOR_SEP_CHAR))
483 vfprintf_fail (formats[FMT_GENERIC], "one color pair allowed only");
484 }
485
486 str = xstrdup (color_string);
487 STACK_VAR (str);
488
489 for (index = 0, color = str; *color; index++, color = p)
490 {
491 char *ch, *sep;
492
493 p = NULL;
494 if ((sep = strchr (color, COLOR_SEP_CHAR)))
495 {
496 *sep = '\0';
497 p = sep + 1;
498 }
499 else
500 p = color + strlen (color);
501 assert (p);
502
503 for (ch = color; *ch; ch++)
504 if (!isalpha (*ch))
505 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be made of non-alphabetic characters");
506
507 for (ch = color + 1; *ch; ch++)
508 if (!islower (*ch))
509 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be in mixed lower/upper case");
510
511 if (streq (color, "None"))
512 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be bold");
513
514 if (isupper (*color))
515 {
516 switch (index)
517 {
518 case FOREGROUND:
519 *bold = true;
520 break;
521 case BACKGROUND:
522 vfprintf_fail (formats[FMT_COLOR], tables[BACKGROUND].desc, color, "cannot be bold");
523 break;
524 default: /* never reached */
525 ABORT_TRACE ();
526 }
527 }
528
529 color_names[index] = xcalloc (1, sizeof (struct color_name));
530
531 color_names[index]->orig = xstrdup (color);
532
533 for (ch = color; *ch; ch++)
534 *ch = tolower (*ch);
535
536 color_names[index]->name = xstrdup (color);
537 }
538
539 RELEASE_VAR (str);
540
541 assert (color_names[FOREGROUND]);
542
543 if (color_names[BACKGROUND])
544 {
545 unsigned int i;
546 unsigned int color_sets[2][2] = { { FOREGROUND, BACKGROUND }, { BACKGROUND, FOREGROUND } };
547 for (i = 0; i < 2; i++)
548 {
549 unsigned int color1 = color_sets[i][0];
550 unsigned int color2 = color_sets[i][1];
551 if (CHECK_COLORS_RANDOM (color1, color2))
552 vfprintf_fail (formats[FMT_RANDOM], tables[color1].desc, color_names[color1]->orig, "cannot be combined with", color_names[color2]->orig);
553 }
554 }
555
556 find_color_entries (color_names, colors);
557 free_color_names (color_names);
558
559 if (!colors[FOREGROUND]->code && colors[BACKGROUND] && colors[BACKGROUND]->code)
560 {
561 struct color_name color_name;
562 color_name.name = color_name.orig = "default";
563
564 find_color_entry (&color_name, FOREGROUND, colors);
565 }
566
567 process_file_arg (file_string, file, stream);
568 }
569
570 static void
571 process_file_arg (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 assert (*file);
610 }
611
612 #define MERGE_PRINT_LINE(part_line, line, flags, check_eof) do { \
613 char *current_line, *merged_line = NULL; \
614 if (part_line) \
615 { \
616 merged_line = str_concat (part_line, line); \
617 free_null (part_line); \
618 } \
619 current_line = merged_line ? merged_line : (char *)line; \
620 if (!check_eof || *current_line != '\0') \
621 print_line (bold, colors, current_line, flags); \
622 free (merged_line); \
623 } while (false);
624
625 static void
626 read_print_stream (bool bold, const struct color **colors, const char *file, FILE *stream)
627 {
628 char buf[BUF_SIZE], *part_line = NULL;
629 unsigned int flags = 0;
630
631 while (!feof (stream))
632 {
633 size_t bytes_read;
634 char *eol;
635 const char *line;
636 memset (buf, '\0', BUF_SIZE);
637 bytes_read = fread (buf, 1, BUF_SIZE - 1, stream);
638 if (bytes_read != (BUF_SIZE - 1) && ferror (stream))
639 vfprintf_fail (formats[FMT_ERROR], BUF_SIZE - 1, "read");
640 line = buf;
641 while ((eol = strpbrk (line, "\n\r")))
642 {
643 char *p;
644 flags &= ~(CR|LF);
645 if (*eol == '\r')
646 {
647 flags |= CR;
648 if (*(eol + 1) == '\n')
649 flags |= LF;
650 }
651 else if (*eol == '\n')
652 flags |= LF;
653 else
654 vfprintf_fail (formats[FMT_FILE], file, "unrecognized line ending");
655 p = eol + SKIP_LINE_ENDINGS (flags);
656 *eol = '\0';
657 MERGE_PRINT_LINE (part_line, line, flags, false);
658 line = p;
659 }
660 if (feof (stream)) {
661 MERGE_PRINT_LINE (part_line, line, 0, true);
662 }
663 else if (*line != '\0')
664 {
665 if (!clean && !clean_all) /* efficiency */
666 print_line (bold, colors, line, 0);
667 else if (!part_line)
668 part_line = xstrdup (line);
669 else
670 {
671 char *merged_line = str_concat (part_line, line);
672 free (part_line);
673 part_line = merged_line;
674 }
675 }
676 }
677 }
678
679 static void
680 find_color_entries (struct color_name **color_names, const struct color **colors)
681 {
682 struct timeval tv;
683 unsigned int index;
684
685 /* randomness */
686 gettimeofday (&tv, NULL);
687 srand (tv.tv_usec * tv.tv_sec);
688
689 for (index = 0; color_names[index]; index++)
690 {
691 const char *color_name = color_names[index]->name;
692
693 const unsigned int count = tables[index].count;
694 const struct color *const color_entries = tables[index].entries;
695
696 if (streq (color_name, "random"))
697 {
698 bool excludable;
699 unsigned int i;
700 do {
701 excludable = false;
702 i = rand() % (count - 2) + 1; /* omit color none and default */
703 switch (index)
704 {
705 case FOREGROUND:
706 /* --exclude-random */
707 if (exclude && streq (exclude, color_entries[i].name))
708 excludable = true;
709 else if (color_names[BACKGROUND] && streq (color_names[BACKGROUND]->name, color_entries[i].name))
710 excludable = true;
711 break;
712 case BACKGROUND:
713 if (streq (colors[FOREGROUND]->name, color_entries[i].name))
714 excludable = true;
715 break;
716 default: /* never reached */
717 ABORT_TRACE ();
718 }
719 } while (excludable);
720 colors[index] = (struct color *)&color_entries[i];
721 }
722 else
723 find_color_entry (color_names[index], index, colors);
724 }
725 }
726
727 static void
728 find_color_entry (const struct color_name *color_name, unsigned int index, const struct color **colors)
729 {
730 bool found = false;
731 unsigned int i;
732
733 const unsigned int count = tables[index].count;
734 const struct color *const color_entries = tables[index].entries;
735
736 for (i = 0; i < count; i++)
737 if (streq (color_name->name, color_entries[i].name))
738 {
739 colors[index] = (struct color *)&color_entries[i];
740 found = true;
741 break;
742 }
743 if (!found)
744 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color_name->orig, "not recognized");
745 }
746
747 static void
748 print_line (bool bold, const struct color **colors, const char *const line, unsigned int flags)
749 {
750 /* --clean[-all] */
751 if (clean || clean_all)
752 print_clean (line);
753 else
754 {
755 /* Foreground color code is guaranteed to be set when background color code is present. */
756 if (colors[BACKGROUND] && colors[BACKGROUND]->code)
757 printf ("\033[%s", colors[BACKGROUND]->code);
758 if (colors[FOREGROUND]->code)
759 printf ("\033[%s%s%s\033[0m", bold ? "1;" : "", colors[FOREGROUND]->code, line);
760 else
761 printf (formats[FMT_GENERIC], line);
762 }
763 if (flags & CR)
764 putchar ('\r');
765 if (flags & LF)
766 putchar ('\n');
767 }
768
769 static void
770 print_clean (const char *line)
771 {
772 const char *p;
773 char ***offsets = NULL;
774 unsigned int count = 0, i = 0;
775
776 for (p = line; *p;)
777 {
778 /* ESC[ */
779 if (*p == 27 && *(p + 1) == '[')
780 {
781 const char *begin = p;
782 p += 2;
783 if (clean_all)
784 {
785 while (isdigit (*p) || *p == ';')
786 p++;
787 }
788 else if (clean)
789 {
790 bool check_values;
791 unsigned int iter = 0;
792 const char *digit;
793 do {
794 check_values = false;
795 iter++;
796 if (!isdigit (*p))
797 goto DISCARD;
798 digit = p;
799 while (isdigit (*p))
800 p++;
801 if (p - digit > 2)
802 goto DISCARD;
803 else /* check range */
804 {
805 char val[3];
806 int value;
807 unsigned int i;
808 const unsigned int digits = p - digit;
809 for (i = 0; i < digits; i++)
810 val[i] = *digit++;
811 val[i] = '\0';
812 value = atoi (val);
813 if (value == 0) /* reset */
814 {
815 if (iter > 1)
816 goto DISCARD;
817 goto END;
818 }
819 else if (value == 1) /* bold */
820 {
821 bool discard = false;
822 if (iter > 1)
823 discard = true;
824 else if (*p != ';')
825 discard = true;
826 if (discard)
827 goto DISCARD;
828 p++;
829 check_values = true;
830 }
831 else if ((value >= 30 && value <= 37) || value == 39) /* foreground colors */
832 goto END;
833 else if ((value >= 40 && value <= 47) || value == 49) /* background colors */
834 {
835 if (iter > 1)
836 goto DISCARD;
837 goto END;
838 }
839 else
840 goto DISCARD;
841 }
842 } while (iter == 1 && check_values);
843 }
844 END: if (*p == 'm')
845 {
846 const char *end = p++;
847 if (!offsets)
848 offsets = xmalloc (++count * sizeof (char **));
849 else
850 offsets = xrealloc (offsets, ++count * sizeof (char **));
851 offsets[i] = xmalloc (2 * sizeof (char *));
852 offsets[i][0] = (char *)begin; /* ESC */
853 offsets[i][1] = (char *)end; /* m */
854 i++;
855 continue;
856 }
857 DISCARD:
858 continue;
859 }
860 p++;
861 }
862
863 if (offsets)
864 print_free_offsets (line, offsets, count);
865 else
866 printf (formats[FMT_GENERIC], line);
867 }
868
869 #define SET_CHAR(offset, new, old) \
870 *old = *offset; \
871 *offset = new; \
872
873 #define RESTORE_CHAR(offset, old) \
874 *offset = old; \
875
876 static void
877 print_free_offsets (const char *line, char ***offsets, unsigned int count)
878 {
879 char ch;
880 unsigned int i;
881
882 SET_CHAR (offsets[0][0], '\0', &ch);
883 printf (formats[FMT_GENERIC], line);
884 RESTORE_CHAR (offsets[0][0], ch);
885
886 for (i = 0; i < count; i++)
887 {
888 char ch;
889 bool next_offset = false;
890 if (i + 1 < count)
891 {
892 SET_CHAR (offsets[i + 1][0], '\0', &ch);
893 next_offset = true;
894 }
895 printf (formats[FMT_GENERIC], offsets[i][1] + 1);
896 if (next_offset)
897 RESTORE_CHAR (offsets[i + 1][0], ch);
898 }
899 for (i = 0; i < count; i++)
900 free_null (offsets[i]);
901 free_null (offsets);
902 }
903
904 static void *
905 malloc_wrap (size_t size)
906 {
907 void *p = malloc (size);
908 if (!p)
909 MEM_ALLOC_FAIL ();
910 return p;
911 }
912
913 static void *
914 calloc_wrap (size_t nmemb, size_t size)
915 {
916 void *p = calloc (nmemb, size);
917 if (!p)
918 MEM_ALLOC_FAIL ();
919 return p;
920 }
921
922 static void *
923 realloc_wrap (void *ptr, size_t size)
924 {
925 void *p = realloc (ptr, size);
926 if (!p)
927 MEM_ALLOC_FAIL ();
928 return p;
929 }
930
931 static void *
932 malloc_wrap_debug (size_t size, const char *file, unsigned int line)
933 {
934 void *p = malloc (size);
935 if (!p)
936 MEM_ALLOC_FAIL_DEBUG (file, line);
937 return p;
938 }
939
940 static void *
941 calloc_wrap_debug (size_t nmemb, size_t size, const char *file, unsigned int line)
942 {
943 void *p = calloc (nmemb, size);
944 if (!p)
945 MEM_ALLOC_FAIL_DEBUG (file, line);
946 return p;
947 }
948
949 static void *
950 realloc_wrap_debug (void *ptr, size_t size, const char *file, unsigned int line)
951 {
952 void *p = realloc (ptr, size);
953 if (!p)
954 MEM_ALLOC_FAIL_DEBUG (file, line);
955 return p;
956 }
957
958 static void
959 free_wrap (void **ptr)
960 {
961 free (*ptr);
962 *ptr = NULL;
963 }
964
965 static char *
966 strdup_wrap (const char *str)
967 {
968 const size_t len = strlen (str) + 1;
969 char *p = xmalloc (len);
970 strncpy (p, str, len);
971 return p;
972 }
973
974 static char *
975 str_concat (const char *str1, const char *str2)
976 {
977 const size_t len = strlen (str1) + strlen (str2) + 1;
978 char *p, *str;
979
980 p = str = xmalloc (len);
981 strncpy (p, str1, strlen (str1));
982 p += strlen (str1);
983 strncpy (p, str2, strlen (str2));
984 p += strlen (str2);
985 *p = '\0';
986
987 return str;
988 }
989
990 static bool
991 has_color_name (const char *str, const char *name)
992 {
993 char *p;
994
995 assert (strlen (str));
996 assert (strlen (name));
997
998 if (!(*str == *name || *str == toupper (*name)))
999 return false;
1000 else if (*(name + 1) != '\0'
1001 && !((p = strstr (str + 1, name + 1)) && p == str + 1))
1002 return false;
1003
1004 return true;
1005 }
1006
1007 #define DO_VFPRINTF(fmt) \
1008 va_list ap; \
1009 fprintf (stderr, "%s: ", program_name); \
1010 va_start (ap, fmt); \
1011 vfprintf (stderr, fmt, ap); \
1012 va_end (ap); \
1013 fprintf (stderr, "\n"); \
1014
1015 static void
1016 vfprintf_diag (const char *fmt, ...)
1017 {
1018 DO_VFPRINTF (fmt);
1019 }
1020
1021 static void
1022 vfprintf_fail (const char *fmt, ...)
1023 {
1024 DO_VFPRINTF (fmt);
1025 exit (EXIT_FAILURE);
1026 }
1027
1028 static void
1029 stack_var (void ***list, unsigned int *stacked, unsigned int index, void *ptr)
1030 {
1031 /* nothing to stack */
1032 if (ptr == NULL)
1033 return;
1034 if (!*list)
1035 *list = xmalloc (sizeof (void *));
1036 else
1037 {
1038 unsigned int i;
1039 for (i = 0; i < *stacked; i++)
1040 if (!(*list)[i])
1041 {
1042 (*list)[i] = ptr;
1043 return; /* reused */
1044 }
1045 *list = xrealloc (*list, (*stacked + 1) * sizeof (void *));
1046 }
1047 (*list)[index] = ptr;
1048 (*stacked)++;
1049 }
1050
1051 static void
1052 release_var (void **list, unsigned int stacked, void **ptr)
1053 {
1054 unsigned int i;
1055 /* nothing to release */
1056 if (*ptr == NULL)
1057 return;
1058 for (i = 0; i < stacked; i++)
1059 if (list[i] == *ptr)
1060 {
1061 free (*ptr);
1062 *ptr = NULL;
1063 list[i] = NULL;
1064 return;
1065 }
1066 }