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