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