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