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