]>
git.refcnt.org Git - colorize.git/blob - colorize.c
2 * colorize - Read text from standard input stream or file and print
3 * it colorized through use of ANSI escape sequences
5 * Copyright (c) 2011-2017 Steven Schubiger
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.
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.
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/>.
22 #define _DEFAULT_SOURCE
24 #define _XOPEN_SOURCE 700
25 #define _FILE_OFFSET_BITS 64
35 #include <sys/types.h>
45 #define to_str(arg) str(arg)
47 #define streq(s1, s2) (strcmp (s1, s2) == 0)
48 #define strneq(s1, s2, n) (strncmp (s1, s2, n) == 0)
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 # define xstrdup(str) strdup_wrap(str, NULL, 0)
55 # define str_concat(str1, str2) str_concat_wrap(str1, str2, NULL, 0)
57 # define xmalloc(size) malloc_wrap_debug(size, __FILE__, __LINE__)
58 # define xcalloc(nmemb, size) calloc_wrap_debug(nmemb, size, __FILE__, __LINE__)
59 # define xrealloc(ptr, size) realloc_wrap_debug(ptr, size, __FILE__, __LINE__)
60 # define xstrdup(str) strdup_wrap(str, __FILE__, __LINE__)
61 # define str_concat(str1, str2) str_concat_wrap(str1, str2, __FILE__, __LINE__)
64 #define free_null(ptr) free_wrap((void **)&ptr)
66 #if defined(BUF_SIZE) && (BUF_SIZE <= 0 || BUF_SIZE > 65536)
70 # define BUF_SIZE 4096
76 #define SKIP_LINE_ENDINGS(flags) (((flags) & CR) && ((flags) & LF) ? 2 : 1)
78 #define VALID_FILE_TYPE(mode) (S_ISREG (mode) || S_ISLNK (mode) || S_ISFIFO (mode))
80 #define STACK_VAR(ptr) do { \
81 stack_var (&vars_list, &stacked_vars, stacked_vars, ptr); \
84 #define RELEASE_VAR(ptr) do { \
85 release_var (vars_list, stacked_vars, (void **)&ptr); \
89 # define MEM_ALLOC_FAIL() do { \
90 fprintf (stderr, "%s: memory allocation failure\n", program_name); \
91 exit (EXIT_FAILURE); \
94 # define MEM_ALLOC_FAIL_DEBUG(file, line) do { \
95 fprintf (stderr, "Memory allocation failure in source file %s, line %u\n", file, line); \
96 exit (EXIT_FAILURE); \
100 #define ABORT_TRACE() \
101 fprintf (stderr, "Aborting in source file %s, line %u\n", __FILE__, __LINE__); \
104 #define CHECK_COLORS_RANDOM(color1, color2) \
105 streq (color_names[color1]->name, "random") \
106 && (streq (color_names[color2]->name, "none") \
107 || streq (color_names[color2]->name, "default")) \
109 #define ALLOC_COMPLETE_PART_LINE 8
111 #if defined(COLOR_SEP_CHAR_COLON)
112 # define COLOR_SEP_CHAR ':'
113 #elif defined(COLOR_SEP_CHAR_SLASH)
114 # define COLOR_SEP_CHAR '/'
116 # define COLOR_SEP_CHAR '/'
119 #define DEBUG_FILE "debug.txt"
121 #define MAX_ATTRIBUTE_CHARS (5 * 2)
123 #define VERSION "0.61"
125 typedef enum { false, true } bool;
137 static const struct color fg_colors
[] = {
144 { "magenta", "35m" },
147 { "default", "39m" },
149 static const struct color bg_colors
[] = {
156 { "magenta", "45m" },
159 { "default", "49m" },
177 static const char *formats
[] = {
179 "%s '%s'", /* string */
180 "%s `%s' %s", /* quote */
181 "%s color '%s' %s", /* color */
182 "%s color '%s' %s '%s'", /* random */
183 "less than %lu bytes %s", /* error */
185 "%s: %s: %s", /* type */
188 enum { GENERIC
, FOREGROUND
= 0, BACKGROUND
};
190 static const struct {
191 struct color
const *entries
;
195 { fg_colors
, sizeof (fg_colors
) / sizeof (struct color
), "foreground" },
196 { bg_colors
, sizeof (bg_colors
) / sizeof (struct color
), "background" },
208 static const struct option long_opts
[] = {
209 { "attr", required_argument
, &opt_type
, OPT_ATTR
},
210 { "clean", no_argument
, &opt_type
, OPT_CLEAN
},
211 { "clean-all", no_argument
, &opt_type
, OPT_CLEAN_ALL
},
212 { "exclude-random", required_argument
, &opt_type
, OPT_EXCLUDE_RANDOM
},
213 { "help", no_argument
, &opt_type
, OPT_HELP
},
214 { "version", no_argument
, &opt_type
, OPT_VERSION
},
215 { NULL
, 0, NULL
, 0 },
220 ATTR_UNDERSCORE
= 0x02,
223 ATTR_CONCEALED
= 0x10
236 static unsigned int stacked_vars
;
237 static void **vars_list
;
240 static bool clean_all
;
242 static char attr
[MAX_ATTRIBUTE_CHARS
+ 1];
243 static char *exclude
;
245 static const char *program_name
;
247 static void process_opts (int, char **);
248 static void process_opt_attr (const char *);
249 static void write_attr (const struct attr
*, unsigned int *);
250 static void print_hint (void);
251 static void print_help (void);
252 static void print_version (void);
253 static void cleanup (void);
254 static void free_color_names (struct color_name
**);
255 static void process_args (unsigned int, char **, char *, const struct color
**, const char **, FILE **);
256 static void process_file_arg (const char *, const char **, FILE **);
257 static void skip_path_colors (const char *, const char *, const struct stat
*);
258 static void gather_color_names (const char *, char *, struct color_name
**);
259 static void read_print_stream (const char *, const struct color
**, const char *, FILE *);
260 static void merge_print_line (const char *, const char *, FILE *);
261 static void complete_part_line (const char *, char **, FILE *);
262 static bool get_next_char (char *, const char **, FILE *, bool *);
263 static void save_char (char, char **, size_t *, size_t *);
264 static void find_color_entries (struct color_name
**, const struct color
**);
265 static void find_color_entry (const struct color_name
*, unsigned int, const struct color
**);
266 static void print_line (const char *, const struct color
**, const char * const, unsigned int);
267 static void print_clean (const char *);
268 static bool is_esc (const char *);
269 static const char *get_end_of_esc (const char *);
270 static const char *get_end_of_text (const char *);
271 static void print_text (const char *, size_t);
272 static bool gather_esc_offsets (const char *, const char **, const char **);
273 static bool validate_esc_clean_all (const char **);
274 static bool validate_esc_clean (int, unsigned int, unsigned int *, const char **, bool *);
275 static bool is_reset (int, unsigned int, const char **);
276 static bool is_attr (int, unsigned int, unsigned int, const char **);
277 static bool is_fg_color (int, const char **);
278 static bool is_bg_color (int, unsigned int, const char **);
280 static void *malloc_wrap (size_t);
281 static void *calloc_wrap (size_t, size_t);
282 static void *realloc_wrap (void *, size_t);
284 static void *malloc_wrap_debug (size_t, const char *, unsigned int);
285 static void *calloc_wrap_debug (size_t, size_t, const char *, unsigned int);
286 static void *realloc_wrap_debug (void *, size_t, const char *, unsigned int);
288 static void free_wrap (void **);
289 static char *strdup_wrap (const char *, const char *, unsigned int);
290 static char *str_concat_wrap (const char *, const char *, const char *, unsigned int);
291 static bool get_bytes_size (unsigned long, struct bytes_size
*);
292 static char *get_file_type (mode_t
);
293 static bool has_color_name (const char *, const char *);
294 static FILE *open_file (const char *, const char *);
295 static void vfprintf_diag (const char *, ...);
296 static void vfprintf_fail (const char *, ...);
297 static void stack_var (void ***, unsigned int *, unsigned int, void *);
298 static void release_var (void **, unsigned int, void **);
303 main (int argc
, char **argv
)
305 unsigned int arg_cnt
;
307 const struct color
*colors
[2] = {
308 NULL
, /* foreground */
309 NULL
, /* background */
312 const char *file
= NULL
;
314 program_name
= argv
[0];
317 setvbuf (stdout
, NULL
, _IOLBF
, 0);
320 log
= open_file (DEBUG_FILE
, "w");
325 process_opts (argc
, argv
);
327 arg_cnt
= argc
- optind
;
329 if (clean
|| clean_all
)
331 if (clean
&& clean_all
)
332 vfprintf_fail (formats
[FMT_GENERIC
], "--clean and --clean-all switch are mutually exclusive");
335 const char *format
= "%s %s";
336 const char *message
= "switch cannot be used with more than one file";
338 vfprintf_fail (format
, "--clean", message
);
340 vfprintf_fail (format
, "--clean-all", message
);
345 if (arg_cnt
== 0 || arg_cnt
> 2)
347 vfprintf_diag ("%u arguments provided, expected 1-2 arguments or clean option", arg_cnt
);
353 if (clean
|| clean_all
)
354 process_file_arg (argv
[optind
], &file
, &stream
);
356 process_args (arg_cnt
, &argv
[optind
], &attr
[0], colors
, &file
, &stream
);
357 read_print_stream (&attr
[0], colors
, file
, stream
);
359 RELEASE_VAR (exclude
);
364 #define PRINT_HELP_EXIT() \
366 exit (EXIT_SUCCESS); \
368 #define PRINT_VERSION_EXIT() \
370 exit (EXIT_SUCCESS); \
375 process_opts (int argc
, char **argv
)
378 while ((opt
= getopt_long (argc
, argv
, "hV", long_opts
, NULL
)) != -1)
382 case 0: /* long opts */
386 process_opt_attr (optarg
);
394 case OPT_EXCLUDE_RANDOM
: {
397 exclude
= xstrdup (optarg
);
399 for (i
= 1; i
< tables
[GENERIC
].count
- 1; i
++) /* skip color none and default */
401 const struct color
*entry
= &tables
[GENERIC
].entries
[i
];
402 if (streq (exclude
, entry
->name
))
409 vfprintf_fail (formats
[FMT_GENERIC
], "--exclude-random switch must be provided a plain color");
415 PRINT_VERSION_EXIT ();
416 default: /* never reached */
423 PRINT_VERSION_EXIT ();
427 default: /* never reached */
434 process_opt_attr (const char *p
)
436 /* If attributes are added to this "list", also increase MAX_ATTRIBUTE_CHARS! */
437 const struct attr attrs
[] = {
438 { "bold", 1, ATTR_BOLD
},
439 { "underscore", 4, ATTR_UNDERSCORE
},
440 { "blink", 5, ATTR_BLINK
},
441 { "reverse", 7, ATTR_REVERSE
},
442 { "concealed", 8, ATTR_CONCEALED
},
444 unsigned int attr_types
= 0;
450 vfprintf_fail (formats
[FMT_GENERIC
], "--attr switch must be provided a string");
454 if (*p
!= '\0' && *p
!= ',')
455 vfprintf_fail (formats
[FMT_GENERIC
], "--attr switch must have strings separated by ,");
458 bool valid_attr
= false;
460 for (i
= 0; i
< sizeof (attrs
) / sizeof (struct attr
); i
++)
462 const size_t name_len
= strlen (attrs
[i
].name
);
463 if ((size_t)(p
- s
) == name_len
&& strneq (s
, attrs
[i
].name
, name_len
))
465 write_attr (&attrs
[i
], &attr_types
);
471 vfprintf_fail (formats
[FMT_GENERIC
], "--attr switch must be provided valid attribute names");
479 write_attr (const struct attr
*attr_i
, unsigned int *attr_types
)
481 const unsigned int val
= attr_i
->val
;
482 const enum attr_type attr_type
= attr_i
->type
;
483 const char *attr_name
= attr_i
->name
;
485 if (*attr_types
& attr_type
)
486 vfprintf_fail ("--attr switch has attribute '%s' twice or more", attr_name
);
487 snprintf (attr
+ strlen (attr
), 3, "%u;", val
);
488 *attr_types
|= attr_type
;
494 fprintf (stderr
, "Type `%s --help' for help screen.\n", program_name
);
502 const char *short_opt
;
504 const struct short_opt short_opts
[] = {
508 const struct option
*opt
= long_opts
;
511 printf ("Usage: %s (foreground) OR (foreground)%c(background) OR --clean[-all] [-|file]\n\n", program_name
, COLOR_SEP_CHAR
);
512 printf ("\tColors (foreground) (background)\n");
513 for (i
= 0; i
< tables
[FOREGROUND
].count
; i
++)
515 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
516 const char *name
= entry
->name
;
517 const char *code
= entry
->code
;
519 printf ("\t\t{\033[%s#\033[0m} [%c%c]%s%*s%s\n",
520 code
, toupper (*name
), *name
, name
+ 1, 10 - (int)strlen (name
), " ", name
);
522 printf ("\t\t{-} %s%*s%s\n", name
, 13 - (int)strlen (name
), " ", name
);
524 printf ("\t\t{*} [Rr]%s%*s%s [--exclude-random=<foreground color>]\n", "andom", 10 - (int)strlen ("random"), " ", "random");
526 printf ("\n\tFirst character of color name in upper case denotes increased intensity,\n");
527 printf ("\twhereas for lower case colors will be of normal intensity.\n");
529 printf ("\n\tOptions\n");
530 for (; opt
->name
; opt
++)
532 const char *short_opt
= NULL
;
534 for (i
= 0; i
< sizeof (short_opts
) / sizeof (struct short_opt
); i
++)
536 if (streq (opt
->name
, short_opts
[i
].name
))
538 short_opt
= short_opts
[i
].short_opt
;
543 printf ("\t\t-%s, --%s\n", short_opt
, opt
->name
);
545 printf ("\t\t --%s\n", opt
->name
);
554 # include "version.h"
556 const char *version
= NULL
;
558 const char *version_prefix
, *version_string
;
559 const char *c_flags
, *ld_flags
, *cpp_flags
;
560 const char *const desc_flags_unknown
= "unknown";
561 struct bytes_size bytes_size
;
564 c_flags
= to_str (CFLAGS
);
566 c_flags
= desc_flags_unknown
;
569 ld_flags
= to_str (LDFLAGS
);
571 ld_flags
= desc_flags_unknown
;
574 cpp_flags
= to_str (CPPFLAGS
);
576 cpp_flags
= desc_flags_unknown
;
583 version_prefix
= version
? "" : "v";
584 version_string
= version
? version
: VERSION
;
585 printf ("colorize %s%s (compiled at %s, %s)\n", version_prefix
, version_string
, __DATE__
, __TIME__
);
587 printf ("Compiler flags: %s\n", c_flags
);
588 printf ("Linker flags: %s\n", ld_flags
);
589 printf ("Preprocessor flags: %s\n", cpp_flags
);
590 if (get_bytes_size (BUF_SIZE
, &bytes_size
))
592 if (BUF_SIZE
% 1024 == 0)
593 printf ("Buffer size: %u%c\n", bytes_size
.size
, bytes_size
.unit
);
595 printf ("Buffer size: %u%c, %u byte%s\n", bytes_size
.size
, bytes_size
.unit
,
596 BUF_SIZE
% 1024, BUF_SIZE
% 1024 > 1 ? "s" : "");
599 printf ("Buffer size: %lu byte%s\n", (unsigned long)BUF_SIZE
, BUF_SIZE
> 1 ? "s" : "");
600 printf ("Color separator: '%c'\n", COLOR_SEP_CHAR
);
601 printf ("Debugging: %s\n", debug
? "yes" : "no");
607 if (stream
&& fileno (stream
) != STDIN_FILENO
)
617 for (i
= 0; i
< stacked_vars
; i
++)
619 free_null (vars_list
);
624 free_color_names (struct color_name
**color_names
)
627 for (i
= 0; color_names
[i
]; i
++)
629 RELEASE_VAR (color_names
[i
]->name
);
630 RELEASE_VAR (color_names
[i
]->orig
);
631 RELEASE_VAR (color_names
[i
]);
636 process_args (unsigned int arg_cnt
, char **arg_strings
, char *attr
, const struct color
**colors
, const char **file
, FILE **stream
)
641 struct color_name
*color_names
[3] = { NULL
, NULL
, NULL
};
643 const char *color_string
= arg_cnt
>= 1 ? arg_strings
[0] : NULL
;
644 const char *file_string
= arg_cnt
== 2 ? arg_strings
[1] : NULL
;
646 assert (color_string
);
648 if (streq (color_string
, "-"))
651 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen cannot be used as color string");
653 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen must be preceded by color string");
656 ret
= lstat (color_string
, &sb
);
658 /* Ensure that we don't fail if there's a file with one or more
659 color names in its path. */
660 if (ret
== 0) /* success */
661 skip_path_colors (color_string
, file_string
, &sb
);
663 if ((p
= strchr (color_string
, COLOR_SEP_CHAR
)))
665 if (p
== color_string
)
666 vfprintf_fail (formats
[FMT_STRING
], "foreground color missing in string", color_string
);
667 else if (p
== color_string
+ strlen (color_string
) - 1)
668 vfprintf_fail (formats
[FMT_STRING
], "background color missing in string", color_string
);
669 else if (strchr (++p
, COLOR_SEP_CHAR
))
670 vfprintf_fail (formats
[FMT_STRING
], "one color pair allowed only for string", color_string
);
673 gather_color_names (color_string
, attr
, color_names
);
675 assert (color_names
[FOREGROUND
]);
677 if (color_names
[BACKGROUND
])
680 const unsigned int color_sets
[2][2] = { { FOREGROUND
, BACKGROUND
}, { BACKGROUND
, FOREGROUND
} };
681 for (i
= 0; i
< 2; i
++)
683 const unsigned int color1
= color_sets
[i
][0];
684 const unsigned int color2
= color_sets
[i
][1];
685 if (CHECK_COLORS_RANDOM (color1
, color2
))
686 vfprintf_fail (formats
[FMT_RANDOM
], tables
[color1
].desc
, color_names
[color1
]->orig
, "cannot be combined with", color_names
[color2
]->orig
);
690 find_color_entries (color_names
, colors
);
691 free_color_names (color_names
);
693 if (!colors
[FOREGROUND
]->code
&& colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
695 struct color_name color_name
;
696 color_name
.name
= color_name
.orig
= "default";
698 find_color_entry (&color_name
, FOREGROUND
, colors
);
701 process_file_arg (file_string
, file
, stream
);
705 process_file_arg (const char *file_string
, const char **file
, FILE **stream
)
709 if (streq (file_string
, "-"))
713 const char *file
= file_string
;
718 ret
= stat (file
, &sb
);
721 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
723 if (!VALID_FILE_TYPE (sb
.st_mode
))
724 vfprintf_fail (formats
[FMT_TYPE
], file
, "unrecognized type", get_file_type (sb
.st_mode
));
726 *stream
= open_file (file
, "r");
741 skip_path_colors (const char *color_string
, const char *file_string
, const struct stat
*sb
)
745 const char *color
= color_string
;
746 const mode_t mode
= sb
->st_mode
;
748 for (c
= 1; c
<= 2 && *color
; c
++)
750 bool matched
= false;
752 for (i
= 0; i
< tables
[GENERIC
].count
; i
++)
754 const struct color
*entry
= &tables
[GENERIC
].entries
[i
];
755 if (has_color_name (color
, entry
->name
))
757 color
+= strlen (entry
->name
);
762 if (!matched
&& has_color_name (color
, "random"))
764 color
+= strlen ("random");
767 if (matched
&& *color
== COLOR_SEP_CHAR
&& *(color
+ 1))
773 have_file
= (*color
!= '\0');
777 const char *file_existing
= color_string
;
779 vfprintf_fail (formats
[FMT_QUOTE
], get_file_type (mode
), file_existing
, "cannot be used as color string");
782 if (VALID_FILE_TYPE (mode
))
783 vfprintf_fail (formats
[FMT_QUOTE
], get_file_type (mode
), file_existing
, "must be preceded by color string");
785 vfprintf_fail (formats
[FMT_QUOTE
], get_file_type (mode
), file_existing
, "is not a valid file type");
791 gather_color_names (const char *color_string
, char *attr
, struct color_name
**color_names
)
794 char *color
, *p
, *str
;
796 str
= xstrdup (color_string
);
799 for (index
= 0, color
= str
; *color
; index
++, color
= p
)
804 if ((sep
= strchr (color
, COLOR_SEP_CHAR
)))
810 p
= color
+ strlen (color
);
813 for (ch
= color
; *ch
; ch
++)
815 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be made of non-alphabetic characters");
817 for (ch
= color
+ 1; *ch
; ch
++)
819 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be in mixed lower/upper case");
821 if (streq (color
, "None"))
822 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be bold");
824 if (isupper (*color
))
829 snprintf (attr
+ strlen (attr
), 3, "1;");
832 vfprintf_fail (formats
[FMT_COLOR
], tables
[BACKGROUND
].desc
, color
, "cannot be bold");
833 default: /* never reached */
838 color_names
[index
] = xcalloc (1, sizeof (struct color_name
));
839 STACK_VAR (color_names
[index
]);
841 color_names
[index
]->orig
= xstrdup (color
);
842 STACK_VAR (color_names
[index
]->orig
);
844 for (ch
= color
; *ch
; ch
++)
847 color_names
[index
]->name
= xstrdup (color
);
848 STACK_VAR (color_names
[index
]->name
);
855 read_print_stream (const char *attr
, const struct color
**colors
, const char *file
, FILE *stream
)
857 char buf
[BUF_SIZE
+ 1];
858 unsigned int flags
= 0;
860 while (!feof (stream
))
865 bytes_read
= fread (buf
, 1, BUF_SIZE
, stream
);
866 if (bytes_read
!= BUF_SIZE
&& ferror (stream
))
867 vfprintf_fail (formats
[FMT_ERROR
], BUF_SIZE
, "read");
868 buf
[bytes_read
] = '\0';
870 while ((eol
= strpbrk (line
, "\n\r")))
877 if (*(eol
+ 1) == '\n')
880 else if (*eol
== '\n')
883 vfprintf_fail (formats
[FMT_FILE
], file
, "unrecognized line ending");
884 p
= eol
+ SKIP_LINE_ENDINGS (flags
);
886 print_line (attr
, colors
, line
, flags
);
892 print_line (attr
, colors
, line
, 0);
894 else if (*line
!= '\0')
897 if ((clean
|| clean_all
) && (p
= strrchr (line
, '\033')))
898 merge_print_line (line
, p
, stream
);
900 print_line (attr
, colors
, line
, 0);
906 merge_print_line (const char *line
, const char *p
, FILE *stream
)
909 char *merged_esc
= NULL
;
910 const char *esc
= "";
911 const char char_restore
= *p
;
913 complete_part_line (p
+ 1, &buf
, stream
);
917 /* form escape sequence */
918 esc
= merged_esc
= str_concat (p
, buf
);
919 /* shorten partial line accordingly */
924 #ifdef TEST_MERGE_PART_LINE
925 printf ("%s%s", line
, esc
);
927 _exit (EXIT_SUCCESS
);
930 *(char *)p
= char_restore
;
937 complete_part_line (const char *p
, char **buf
, FILE *stream
)
939 bool got_next_char
= false, read_from_stream
;
943 if (get_next_char (&ch
, &p
, stream
, &read_from_stream
))
947 if (read_from_stream
)
948 save_char (ch
, buf
, &i
, &size
);
952 if (read_from_stream
)
953 ungetc ((int)ch
, stream
);
960 while (get_next_char (&ch
, &p
, stream
, &read_from_stream
))
962 if (isdigit (ch
) || ch
== ';')
964 if (read_from_stream
)
965 save_char (ch
, buf
, &i
, &size
);
967 else /* got next character */
969 got_next_char
= true;
978 if (read_from_stream
)
979 save_char (ch
, buf
, &i
, &size
);
983 if (read_from_stream
)
984 ungetc ((int)ch
, stream
);
993 get_next_char (char *ch
, const char **p
, FILE *stream
, bool *read_from_stream
)
998 if ((c
= fgetc (stream
)) != EOF
)
1001 *read_from_stream
= true;
1006 *read_from_stream
= false;
1014 *read_from_stream
= false;
1020 save_char (char ch
, char **buf
, size_t *i
, size_t *size
)
1024 *size
= ALLOC_COMPLETE_PART_LINE
;
1025 *buf
= xmalloc (*size
);
1027 /* +1: effective occupied size of buffer */
1028 else if ((*i
+ 1) == *size
)
1031 *buf
= xrealloc (*buf
, *size
);
1034 (*buf
)[*i
+ 1] = '\0';
1039 find_color_entries (struct color_name
**color_names
, const struct color
**colors
)
1045 gettimeofday (&tv
, NULL
);
1046 srand (tv
.tv_usec
* tv
.tv_sec
);
1048 for (index
= 0; color_names
[index
]; index
++)
1050 const char *color_name
= color_names
[index
]->name
;
1052 const unsigned int count
= tables
[index
].count
;
1053 const struct color
*const color_entries
= tables
[index
].entries
;
1055 if (streq (color_name
, "random"))
1061 i
= rand() % (count
- 2) + 1; /* omit color none and default */
1065 /* --exclude-random */
1066 if (exclude
&& streq (exclude
, color_entries
[i
].name
))
1068 else if (color_names
[BACKGROUND
] && streq (color_names
[BACKGROUND
]->name
, color_entries
[i
].name
))
1072 if (streq (colors
[FOREGROUND
]->name
, color_entries
[i
].name
))
1075 default: /* never reached */
1078 } while (excludable
);
1079 colors
[index
] = (struct color
*)&color_entries
[i
];
1082 find_color_entry (color_names
[index
], index
, colors
);
1087 find_color_entry (const struct color_name
*color_name
, unsigned int index
, const struct color
**colors
)
1092 const unsigned int count
= tables
[index
].count
;
1093 const struct color
*const color_entries
= tables
[index
].entries
;
1095 for (i
= 0; i
< count
; i
++)
1096 if (streq (color_name
->name
, color_entries
[i
].name
))
1098 colors
[index
] = (struct color
*)&color_entries
[i
];
1103 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color_name
->orig
, "not recognized");
1107 print_line (const char *attr
, const struct color
**colors
, const char *const line
, unsigned int flags
)
1110 if (clean
|| clean_all
)
1114 /* Foreground color code is guaranteed to be set when background color code is present. */
1115 if (colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
1116 printf ("\033[%s", colors
[BACKGROUND
]->code
);
1117 if (colors
[FOREGROUND
]->code
)
1118 printf ("\033[%s%s%s\033[0m", attr
, colors
[FOREGROUND
]->code
, line
);
1120 printf (formats
[FMT_GENERIC
], line
);
1129 print_clean (const char *line
)
1131 const char *p
= line
;
1134 p
= get_end_of_esc (p
);
1138 const char *text_start
= p
;
1139 const char *text_end
= get_end_of_text (p
);
1140 print_text (text_start
, text_end
- text_start
);
1141 p
= get_end_of_esc (text_end
);
1146 is_esc (const char *p
)
1148 return gather_esc_offsets (p
, NULL
, NULL
);
1152 get_end_of_esc (const char *p
)
1155 const char *end
= NULL
;
1156 while ((esc
= strchr (p
, '\033')))
1158 if (gather_esc_offsets (esc
, NULL
, &end
))
1162 return end
? end
+ 1 : p
+ strlen (p
);
1166 get_end_of_text (const char *p
)
1169 const char *start
= NULL
;
1170 while ((esc
= strchr (p
, '\033')))
1172 if (gather_esc_offsets (esc
, &start
, NULL
))
1176 return start
? start
: p
+ strlen (p
);
1180 print_text (const char *p
, size_t len
)
1182 size_t bytes_written
;
1183 bytes_written
= fwrite (p
, 1, len
, stdout
);
1184 if (bytes_written
!= len
)
1185 vfprintf_fail (formats
[FMT_ERROR
], (unsigned long)len
, "written");
1189 gather_esc_offsets (const char *p
, const char **start
, const char **end
)
1192 if (*p
== 27 && *(p
+ 1) == '[')
1195 const char *const begin
= p
;
1198 valid
= validate_esc_clean_all (&p
);
1202 unsigned int prev_iter
, iter
;
1204 prev_iter
= iter
= 0;
1206 check_values
= false;
1211 while (isdigit (*p
))
1215 else /* check range */
1220 const unsigned int digits
= p
- digit
;
1221 for (i
= 0; i
< digits
; i
++)
1225 valid
= validate_esc_clean (value
, iter
, &prev_iter
, &p
, &check_values
);
1227 } while (check_values
);
1242 validate_esc_clean_all (const char **p
)
1244 while (isdigit (**p
) || **p
== ';')
1246 return (**p
== 'm');
1250 validate_esc_clean (int value
, unsigned int iter
, unsigned int *prev_iter
, const char **p
, bool *check_values
)
1252 if (is_reset (value
, iter
, p
))
1254 else if (is_attr (value
, iter
, *prev_iter
, p
))
1257 *check_values
= true;
1259 return false; /* partial escape sequence, need another valid value */
1261 else if (is_fg_color (value
, p
))
1263 else if (is_bg_color (value
, iter
, p
))
1270 is_reset (int value
, unsigned int iter
, const char **p
)
1272 return (value
== 0 && iter
== 1 && **p
== 'm');
1276 is_attr (int value
, unsigned int iter
, unsigned int prev_iter
, const char **p
)
1278 return ((value
> 0 && value
< 10) && (iter
- prev_iter
== 1) && **p
== ';');
1282 is_fg_color (int value
, const char **p
)
1284 return (((value
>= 30 && value
<= 37) || value
== 39) && **p
== 'm');
1288 is_bg_color (int value
, unsigned int iter
, const char **p
)
1290 return (((value
>= 40 && value
<= 47) || value
== 49) && iter
== 1 && **p
== 'm');
1295 malloc_wrap (size_t size
)
1297 void *p
= malloc (size
);
1304 calloc_wrap (size_t nmemb
, size_t size
)
1306 void *p
= calloc (nmemb
, size
);
1313 realloc_wrap (void *ptr
, size_t size
)
1315 void *p
= realloc (ptr
, size
);
1322 malloc_wrap_debug (size_t size
, const char *file
, unsigned int line
)
1324 void *p
= malloc (size
);
1326 MEM_ALLOC_FAIL_DEBUG (file
, line
);
1327 fprintf (log
, "%s: malloc'ed %lu bytes [source file %s, line %u]\n", program_name
, (unsigned long)size
, file
, line
);
1332 calloc_wrap_debug (size_t nmemb
, size_t size
, const char *file
, unsigned int line
)
1334 void *p
= calloc (nmemb
, size
);
1336 MEM_ALLOC_FAIL_DEBUG (file
, line
);
1337 fprintf (log
, "%s: calloc'ed %lu bytes [source file %s, line %u]\n", program_name
, (unsigned long)(nmemb
* size
), file
, line
);
1342 realloc_wrap_debug (void *ptr
, size_t size
, const char *file
, unsigned int line
)
1344 void *p
= realloc (ptr
, size
);
1346 MEM_ALLOC_FAIL_DEBUG (file
, line
);
1347 fprintf (log
, "%s: realloc'ed %lu bytes [source file %s, line %u]\n", program_name
, (unsigned long)size
, file
, line
);
1353 free_wrap (void **ptr
)
1360 # define do_malloc(len, file, line) malloc_wrap(len)
1362 # define do_malloc(len, file, line) malloc_wrap_debug(len, file, line)
1366 strdup_wrap (const char *str
, const char *file
, unsigned int line
)
1368 const size_t len
= strlen (str
) + 1;
1369 char *p
= do_malloc (len
, file
, line
);
1370 strncpy (p
, str
, len
);
1375 str_concat_wrap (const char *str1
, const char *str2
, const char *file
, unsigned int line
)
1377 const size_t len
= strlen (str1
) + strlen (str2
) + 1;
1380 p
= str
= do_malloc (len
, file
, line
);
1381 strncpy (p
, str1
, strlen (str1
));
1383 strncpy (p
, str2
, strlen (str2
));
1391 get_bytes_size (unsigned long bytes
, struct bytes_size
*bytes_size
)
1393 const char *unit
, units
[] = { '0', 'K', 'M', 'G', '\0' };
1394 unsigned long size
= bytes
;
1398 while (size
>= 1024 && *(unit
+ 1))
1403 bytes_size
->size
= (unsigned int)size
;
1404 bytes_size
->unit
= *unit
;
1409 get_file_type (mode_t mode
)
1413 else if (S_ISDIR (mode
))
1415 else if (S_ISCHR (mode
))
1416 return "character device";
1417 else if (S_ISBLK (mode
))
1418 return "block device";
1419 else if (S_ISFIFO (mode
))
1420 return "named pipe";
1421 else if (S_ISLNK (mode
))
1422 return "symbolic link";
1423 else if (S_ISSOCK (mode
))
1430 has_color_name (const char *str
, const char *name
)
1434 assert (strlen (str
));
1435 assert (strlen (name
));
1437 if (!(*str
== *name
|| *str
== toupper (*name
)))
1439 else if (*(name
+ 1) != '\0'
1440 && !((p
= strstr (str
+ 1, name
+ 1)) && p
== str
+ 1))
1447 open_file (const char *file
, const char *mode
)
1452 stream
= fopen (file
, mode
);
1454 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
1459 #define DO_VFPRINTF(fmt) \
1461 fprintf (stderr, "%s: ", program_name); \
1462 va_start (ap, fmt); \
1463 vfprintf (stderr, fmt, ap); \
1465 fprintf (stderr, "\n"); \
1468 vfprintf_diag (const char *fmt
, ...)
1474 vfprintf_fail (const char *fmt
, ...)
1477 exit (EXIT_FAILURE
);
1481 stack_var (void ***list
, unsigned int *stacked
, unsigned int index
, void *ptr
)
1483 /* nothing to stack */
1487 *list
= xmalloc (sizeof (void *));
1491 for (i
= 0; i
< *stacked
; i
++)
1495 return; /* reused */
1497 *list
= xrealloc (*list
, (*stacked
+ 1) * sizeof (void *));
1499 (*list
)[index
] = ptr
;
1504 release_var (void **list
, unsigned int stacked
, void **ptr
)
1507 /* nothing to release */
1510 for (i
= 0; i
< stacked
; i
++)
1511 if (list
[i
] == *ptr
)