]>
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-2019 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
36 #include <sys/types.h>
47 #define to_str(arg) str(arg)
49 #define streq(s1, s2) (strcmp (s1, s2) == 0)
50 #define strneq(s1, s2, n) (strncmp (s1, s2, n) == 0)
53 # define xmalloc(size) malloc_wrap(size)
54 # define xcalloc(nmemb, size) calloc_wrap(nmemb, size)
55 # define xrealloc(ptr, size) realloc_wrap(ptr, size)
56 # define xstrdup(str) strdup_wrap(str, NULL, 0)
57 # define str_concat(str1, str2) str_concat_wrap(str1, str2, NULL, 0)
59 # define xmalloc(size) malloc_wrap_debug(size, __FILE__, __LINE__)
60 # define xcalloc(nmemb, size) calloc_wrap_debug(nmemb, size, __FILE__, __LINE__)
61 # define xrealloc(ptr, size) realloc_wrap_debug(ptr, size, __FILE__, __LINE__)
62 # define xstrdup(str) strdup_wrap(str, __FILE__, __LINE__)
63 # define str_concat(str1, str2) str_concat_wrap(str1, str2, __FILE__, __LINE__)
66 #define free_null(ptr) free_wrap((void **)&ptr)
68 #if defined(BUF_SIZE) && (BUF_SIZE <= 0 || BUF_SIZE > 65536)
72 # define BUF_SIZE 4096
78 #define COUNT_OF(obj, type) (sizeof (obj) / sizeof (type))
80 #define SKIP_LINE_ENDINGS(flags) ((flags) == (CR|LF) ? 2 : 1)
82 #define VALID_FILE_TYPE(mode) (S_ISREG (mode) || S_ISLNK (mode) || S_ISFIFO (mode))
84 #define STACK_VAR(ptr) do { \
85 stack_var (&vars_list, &stacked_vars, stacked_vars, ptr); \
88 #define RELEASE_VAR(ptr) do { \
89 release_var (vars_list, stacked_vars, (void **)&ptr); \
93 # define MEM_ALLOC_FAIL() do { \
94 fprintf (stderr, "%s: memory allocation failure\n", program_name); \
95 exit (EXIT_FAILURE); \
98 # define MEM_ALLOC_FAIL_DEBUG(file, line) do { \
99 fprintf (stderr, "Memory allocation failure in source file %s, line %u\n", file, line); \
100 exit (EXIT_FAILURE); \
104 #define ABORT_TRACE() \
105 fprintf (stderr, "Aborting in source file %s, line %u\n", __FILE__, __LINE__); \
108 #define CHECK_COLORS_RANDOM(color1, color2) \
109 streq (color_names[color1]->name, "random") \
110 && (streq (color_names[color2]->name, "none") \
111 || streq (color_names[color2]->name, "default"))
113 #define ALLOC_COMPLETE_PART_LINE 8
115 #if defined(COLOR_SEP_CHAR_COLON)
116 # define COLOR_SEP_CHAR ':'
117 #elif defined(COLOR_SEP_CHAR_SLASH)
118 # define COLOR_SEP_CHAR '/'
120 # define COLOR_SEP_CHAR '/'
123 #define CONF_FILE ".colorize.conf"
126 # define DEBUG_FILE "debug.txt"
129 #define MAX_ATTRIBUTE_CHARS (6 * 2)
131 #define PROGRAM_NAME "colorize"
133 #define VERSION "0.65"
135 typedef enum { false, true } bool;
140 char *exclude_random
;
141 char *omit_color_empty
;
144 enum { DESC_OPTION
, DESC_CONF
};
156 static const struct color fg_colors
[] = {
163 { "magenta", "35m" },
166 { "default", "39m" },
168 static const struct color bg_colors
[] = {
175 { "magenta", "45m" },
178 { "default", "49m" },
197 static const char *formats
[] = {
199 "%s '%s'", /* string */
200 "%s `%s' %s", /* quote */
201 "%s color '%s' %s", /* color */
202 "%s color '%s' %s '%s'", /* random */
203 "less than %lu bytes %s", /* error */
205 "%s: %s: %s", /* type */
206 "%s: option '%s' %s" /* conf */
209 enum { GENERIC
, FOREGROUND
= 0, BACKGROUND
};
211 static const struct {
212 const struct color
*entries
;
216 { fg_colors
, COUNT_OF (fg_colors
, struct color
), "foreground" },
217 { bg_colors
, COUNT_OF (bg_colors
, struct color
), "background" },
220 static unsigned int opts_set
;
223 OPT_EXCLUDE_RANDOM_SET
= 0x02,
224 OPT_OMIT_COLOR_EMPTY_SET
= 0x04
228 char *exclude_random
;
229 } opts_arg
= { NULL
, NULL
};
237 OPT_OMIT_COLOR_EMPTY
,
242 static const struct option long_opts
[] = {
243 { "attr", required_argument
, &opt_type
, OPT_ATTR
},
244 { "clean", no_argument
, &opt_type
, OPT_CLEAN
},
245 { "clean-all", no_argument
, &opt_type
, OPT_CLEAN_ALL
},
246 { "config", required_argument
, &opt_type
, OPT_CONFIG
},
247 { "exclude-random", required_argument
, &opt_type
, OPT_EXCLUDE_RANDOM
},
248 { "omit-color-empty", no_argument
, &opt_type
, OPT_OMIT_COLOR_EMPTY
},
249 { "help", no_argument
, &opt_type
, OPT_HELP
},
250 { "version", no_argument
, &opt_type
, OPT_VERSION
},
251 { NULL
, 0, NULL
, 0 },
256 ATTR_UNDERSCORE
= 0x02,
259 ATTR_CONCEALED
= 0x10
272 static unsigned int stacked_vars
;
273 static void **vars_list
;
276 static bool clean_all
;
277 static bool omit_color_empty
;
279 static char attr
[MAX_ATTRIBUTE_CHARS
+ 1];
280 static char *exclude
;
282 static const char *program_name
;
285 static void print_tstamp (FILE *);
287 static void process_opts (int, char **, char **);
288 static void process_opt_attr (const char *, const bool);
289 static void write_attr (const struct attr
*, unsigned int *, const bool);
290 static void process_opt_exclude_random (const char *, const bool);
291 static void parse_conf (const char *, struct conf
*);
292 static void assign_conf (const char *, struct conf
*, const char *, char *);
293 static void init_conf_vars (const struct conf
*);
294 static void init_opts_vars (void);
295 static void print_hint (void);
296 static void print_help (void);
297 static void print_version (void);
298 static void cleanup (void);
299 static void free_color_names (struct color_name
**);
300 static void free_conf (struct conf
*);
301 static void process_args (unsigned int, char **, char *, const struct color
**, const char **, FILE **, struct conf
*);
302 static void process_file_arg (const char *, const char **, FILE **);
303 static bool skip_path_colors (const char *, const char *, const struct stat
*, const bool);
304 static void gather_color_names (const char *, char *, struct color_name
**);
305 static void read_print_stream (const char *, const struct color
**, const char *, FILE *);
306 static void merge_print_line (const char *, const char *, FILE *);
307 static void complete_part_line (const char *, char **, FILE *);
308 static bool get_next_char (char *, const char **, FILE *, bool *);
309 static void save_char (char, char **, size_t *, size_t *);
310 static void find_color_entries (struct color_name
**, const struct color
**);
311 static void find_color_entry (const struct color_name
*, unsigned int, const struct color
**);
312 static void print_line (const char *, const struct color
**, const char * const, unsigned int, bool);
313 static void print_clean (const char *);
314 static bool is_esc (const char *);
315 static const char *get_end_of_esc (const char *);
316 static const char *get_end_of_text (const char *);
317 static void print_text (const char *, size_t);
318 static bool gather_esc_offsets (const char *, const char **, const char **);
319 static bool validate_esc_clean_all (const char **);
320 static bool validate_esc_clean (int, unsigned int, unsigned int *, const char **, bool *);
321 static bool is_reset (int, unsigned int, const char **);
322 static bool is_attr (int, unsigned int, unsigned int, const char **);
323 static bool is_fg_color (int, const char **);
324 static bool is_bg_color (int, unsigned int, const char **);
326 static void *malloc_wrap (size_t);
327 static void *calloc_wrap (size_t, size_t);
328 static void *realloc_wrap (void *, size_t);
330 static void *malloc_wrap_debug (size_t, const char *, unsigned int);
331 static void *calloc_wrap_debug (size_t, size_t, const char *, unsigned int);
332 static void *realloc_wrap_debug (void *, size_t, const char *, unsigned int);
334 static void free_wrap (void **);
335 static char *strdup_wrap (const char *, const char *, unsigned int);
336 static char *str_concat_wrap (const char *, const char *, const char *, unsigned int);
337 static char *expand_string (const char *);
338 static bool get_bytes_size (unsigned long, struct bytes_size
*);
339 static char *get_file_type (mode_t
);
340 static bool has_color_name (const char *, const char *);
341 static FILE *open_file (const char *, const char *);
342 static void vfprintf_diag (const char *, ...);
343 static void vfprintf_fail (const char *, ...);
344 static void stack_var (void ***, unsigned int *, unsigned int, void *);
345 static void release_var (void **, unsigned int, void **);
350 main (int argc
, char **argv
)
352 unsigned int arg_cnt
;
354 const struct color
*colors
[2] = {
355 NULL
, /* foreground */
356 NULL
, /* background */
359 const char *file
= NULL
;
361 char *conf_file
= NULL
;
362 struct conf config
= { NULL
, NULL
, NULL
, NULL
};
364 program_name
= argv
[0];
367 setvbuf (stdout
, NULL
, _IOLBF
, 0);
370 log
= open_file (DEBUG_FILE
, "w");
376 process_opts (argc
, argv
, &conf_file
);
378 #ifdef CONF_FILE_TEST
379 conf_file
= to_str (CONF_FILE_TEST
);
381 if (conf_file
== NULL
)
384 struct passwd
*passwd
;
389 if ((passwd
= getpwuid (uid
)) == NULL
)
392 vfprintf_diag ("password file entry for uid %lu not found", (unsigned long)uid
);
397 size
= strlen (passwd
->pw_dir
) + 1 + strlen (CONF_FILE
) + 1;
398 conf_file
= xmalloc (size
);
399 snprintf (conf_file
, size
, "%s/%s", passwd
->pw_dir
, CONF_FILE
);
404 if ((s
= expand_string (conf_file
)))
410 if (access (conf_file
, F_OK
) == -1)
411 vfprintf_fail (formats
[FMT_FILE
], conf_file
, strerror (errno
));
414 #if defined(CONF_FILE_TEST) || !defined(TEST)
415 if (access (conf_file
, F_OK
) != -1)
416 parse_conf (conf_file
, &config
);
418 #if !defined(CONF_FILE_TEST) && !defined(TEST)
421 init_conf_vars (&config
);
425 arg_cnt
= argc
- optind
;
427 if (clean
|| clean_all
)
429 if (clean
&& clean_all
)
430 vfprintf_fail (formats
[FMT_GENERIC
], "--clean and --clean-all switch are mutually exclusive");
433 const char *const format
= "%s %s";
434 const char *const message
= "switch cannot be used with more than one file";
436 vfprintf_fail (format
, "--clean", message
);
438 vfprintf_fail (format
, "--clean-all", message
);
443 if (arg_cnt
== 0 || arg_cnt
> 2)
445 vfprintf_diag ("%u arguments provided, expected 1-2 arguments or clean option", arg_cnt
);
451 if (clean
|| clean_all
)
452 process_file_arg (argv
[optind
], &file
, &stream
);
454 process_args (arg_cnt
, &argv
[optind
], &attr
[0], colors
, &file
, &stream
, &config
);
455 read_print_stream (&attr
[0], colors
, file
, stream
);
459 RELEASE_VAR (exclude
);
466 print_tstamp (FILE *log
)
477 perror ("localtime");
480 written
= strftime (str
, sizeof (str
), "%Y-%m-%d %H:%M:%S %Z", tm
);
482 vfprintf_fail (formats
[FMT_GENERIC
], "strftime: 0 returned");
484 fprintf (log
, "%s\n", str
);
491 #define DUP_CONFIG() \
492 *conf_file = xstrdup (optarg); \
495 #define PRINT_HELP_EXIT() \
499 #define PRINT_VERSION_EXIT() \
506 process_opts (int argc
, char **argv
, char **conf_file
)
509 while ((opt
= getopt_long (argc
, argv
, "c:hV", long_opts
, NULL
)) != -1)
513 case 0: /* long opts */
517 opts_set
|= OPT_ATTR_SET
;
518 opts_arg
.attr
= xstrdup (optarg
);
528 case OPT_EXCLUDE_RANDOM
:
529 opts_set
|= OPT_EXCLUDE_RANDOM_SET
;
530 opts_arg
.exclude_random
= xstrdup (optarg
);
532 case OPT_OMIT_COLOR_EMPTY
:
533 opts_set
|= OPT_OMIT_COLOR_EMPTY_SET
;
538 PRINT_VERSION_EXIT ();
539 default: /* never reached */
548 PRINT_VERSION_EXIT ();
552 default: /* never reached */
559 process_opt_attr (const char *p
, const bool is_opt
)
561 /* If attributes are added to this "list", also increase MAX_ATTRIBUTE_CHARS! */
562 const struct attr attrs
[] = {
563 { "bold", 1, ATTR_BOLD
},
564 { "underscore", 4, ATTR_UNDERSCORE
},
565 { "blink", 5, ATTR_BLINK
},
566 { "reverse", 7, ATTR_REVERSE
},
567 { "concealed", 8, ATTR_CONCEALED
},
569 unsigned int attr_types
= 0;
570 const char *desc_type
[2] = { "--attr switch", "attr conf option" };
571 const unsigned int DESC_TYPE
= is_opt
? DESC_OPTION
: DESC_CONF
;
577 vfprintf_fail ("%s must be provided a string", desc_type
[DESC_TYPE
]);
581 if (*p
!= '\0' && *p
!= ',')
582 vfprintf_fail ("%s must have strings separated by ,", desc_type
[DESC_TYPE
]);
585 bool valid_attr
= false;
587 for (i
= 0; i
< COUNT_OF (attrs
, struct attr
); i
++)
589 const size_t name_len
= strlen (attrs
[i
].name
);
590 if ((size_t)(p
- s
) == name_len
&& strneq (s
, attrs
[i
].name
, name_len
))
592 write_attr (&attrs
[i
], &attr_types
, is_opt
);
599 char *attr_invalid
= xmalloc ((p
- s
) + 1);
600 STACK_VAR (attr_invalid
);
601 strncpy (attr_invalid
, s
, p
- s
);
602 attr_invalid
[p
- s
] = '\0';
603 vfprintf_fail ("%s attribute '%s' is not valid", desc_type
[DESC_TYPE
], attr_invalid
);
604 RELEASE_VAR (attr_invalid
); /* never reached */
613 write_attr (const struct attr
*attr_i
, unsigned int *attr_types
, const bool is_opt
)
615 const unsigned int val
= attr_i
->val
;
616 const enum attr_type attr_type
= attr_i
->type
;
617 const char *attr_name
= attr_i
->name
;
619 if (*attr_types
& attr_type
)
620 vfprintf_fail ("%s has attribute '%s' twice or more",
621 is_opt
? "--attr switch" : "attr conf option", attr_name
);
622 snprintf (attr
+ strlen (attr
), 3, "%u;", val
);
623 *attr_types
|= attr_type
;
627 process_opt_exclude_random (const char *s
, const bool is_opt
)
631 RELEASE_VAR (exclude
);
632 exclude
= xstrdup (s
);
634 for (i
= 1; i
< tables
[GENERIC
].count
- 1; i
++) /* skip color none and default */
636 const struct color
*entry
= &tables
[GENERIC
].entries
[i
];
637 if (streq (exclude
, entry
->name
))
644 vfprintf_fail ("%s must be provided a plain color",
645 is_opt
? "--exclude-random switch" : "exclude-random conf option");
649 init_opts_vars (void)
651 if (opts_set
& OPT_ATTR_SET
)
653 attr
[0] = '\0'; /* Clear attr string to discard values from the config file. */
654 process_opt_attr (opts_arg
.attr
, true);
656 if (opts_set
& OPT_EXCLUDE_RANDOM_SET
)
657 process_opt_exclude_random (opts_arg
.exclude_random
, true);
658 if (opts_set
& OPT_OMIT_COLOR_EMPTY_SET
)
659 omit_color_empty
= true;
661 free (opts_arg
.attr
);
662 free (opts_arg
.exclude_random
);
665 #define IS_SPACE(c) ((c) == ' ' || (c) == '\t')
668 parse_conf (const char *conf_file
, struct conf
*config
)
670 unsigned int cnt
= 0;
674 conf
= open_file (conf_file
, "r");
676 while (fgets (line
, sizeof (line
), conf
))
679 char *assign
, *comment
, *opt
, *value
;
683 if ((p
= strchr (line
, '\r')) && *(p
+ 1) != '\n')
684 vfprintf_fail ("%s: CR ending of line %u is not supported, switch to CRLF/LF instead", conf_file
, cnt
);
685 if (strlen (line
) > (sizeof (line
) - 2))
686 vfprintf_fail ("%s: line %u exceeds maximum of %u characters", conf_file
, cnt
, (unsigned int)(sizeof (line
) - 2));
687 if ((p
= strpbrk (line
, "\n\r")))
689 /* NAME PARSING (start) */
691 /* skip leading spaces and tabs for name */
692 while (IS_SPACE (*p
))
694 /* skip line if a) string end, b) comment, [cd]) newline */
695 if (*p
== '\0' || *p
== '#' || *p
== '\n' || *p
== '\r')
698 if (!(assign
= strchr (opt
, '='))) /* check for = */
701 if ((s
= strpbrk (opt
, "# ")))
703 vfprintf_fail (formats
[FMT_CONF
], conf_file
, opt
, "not followed by =");
706 /* skip trailing spaces and tabs for name */
707 while (IS_SPACE (*(p
- 1)))
710 /* NAME PARSING (end) */
711 /* NAME VALIDATION (start) */
712 for (p
= opt
; *p
; p
++)
713 if (!isalnum (*p
) && *p
!= '-')
714 vfprintf_fail (formats
[FMT_CONF
], conf_file
, opt
, "cannot be made of non-option characters");
715 /* NAME VALIDATION (end) */
716 /* VALUE PARSING (start) */
718 /* skip leading spaces and tabs for value */
719 while (IS_SPACE (*p
))
721 /* skip line if comment */
725 if ((comment
= strchr (p
, '#')))
729 /* skip trailing spaces and tabs for value */
730 while (IS_SPACE (*(p
- 1)))
733 /* VALUE PARSING (end) */
735 /* save option name */
737 /* save option value (allow empty ones) */
738 val
= strlen (value
) ? xstrdup (value
) : NULL
;
740 assign_conf (conf_file
, config
, cfg
, val
);
747 #define ASSIGN_CONF(str,val) do { \
753 assign_conf (const char *conf_file
, struct conf
*config
, const char *cfg
, char *val
)
755 if (streq (cfg
, "attr"))
756 ASSIGN_CONF (config
->attr
, val
);
757 else if (streq (cfg
, "color"))
758 ASSIGN_CONF (config
->color
, val
);
759 else if (streq (cfg
, "exclude-random"))
760 ASSIGN_CONF (config
->exclude_random
, val
);
761 else if (streq (cfg
, "omit-color-empty"))
762 ASSIGN_CONF (config
->omit_color_empty
, val
);
764 vfprintf_fail (formats
[FMT_CONF
], conf_file
, cfg
, "not recognized");
768 init_conf_vars (const struct conf
*config
)
771 process_opt_attr (config
->attr
, false);
772 if (config
->exclude_random
)
773 process_opt_exclude_random (config
->exclude_random
, false);
774 if (config
->omit_color_empty
)
776 if (streq (config
->omit_color_empty
, "yes"))
777 omit_color_empty
= true;
778 else if (streq (config
->omit_color_empty
, "no"))
779 omit_color_empty
= false;
781 vfprintf_fail (formats
[FMT_GENERIC
], "omit-color-empty conf option is not valid");
788 fprintf (stderr
, "Type `%s --help' for help screen.\n", program_name
);
796 const char *short_opt
;
799 const struct opt_data opts_data
[] = {
800 { "attr", NULL
, "=ATTR1,ATTR2,..." },
801 { "config", "c", "=PATH" },
802 { "exclude-random", NULL
, "=COLOR" },
803 { "help", "h", NULL
},
804 { "version", "V", NULL
},
806 const struct option
*opt
= long_opts
;
809 printf ("Usage: %s (foreground) OR (foreground)%c(background) OR --clean[-all] [-|file]\n\n", program_name
, COLOR_SEP_CHAR
);
810 printf ("\tColors (foreground) (background)\n");
811 for (i
= 0; i
< tables
[FOREGROUND
].count
; i
++)
813 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
814 const char *name
= entry
->name
;
815 const char *code
= entry
->code
;
817 printf ("\t\t{\033[%s#\033[0m} [%c%c]%s%*s%s\n",
818 code
, toupper (*name
), *name
, name
+ 1, 10 - (int)strlen (name
), " ", name
);
820 printf ("\t\t{-} %s%*s%s\n", name
, 13 - (int)strlen (name
), " ", name
);
822 printf ("\t\t{*} [Rr]%s%*s%s [--exclude-random=<foreground color>]\n", "andom", 10 - (int)strlen ("random"), " ", "random");
824 printf ("\n\tFirst character of color name in upper case denotes increased intensity,\n");
825 printf ("\twhereas for lower case colors will be of normal intensity.\n");
827 printf ("\n\tOptions\n");
828 for (; opt
->name
; opt
++)
830 const struct opt_data
*opt_data
= NULL
;
832 for (i
= 0; i
< COUNT_OF (opts_data
, struct opt_data
); i
++)
833 if (streq (opt
->name
, opts_data
[i
].name
))
835 opt_data
= &opts_data
[i
];
840 if (opt_data
->short_opt
)
841 printf ("\t\t-%s, --%s", opt_data
->short_opt
, opt
->name
);
843 printf ("\t\t --%s", opt
->name
);
845 printf ("%s", opt_data
->arg
);
849 printf ("\t\t --%s\n", opt
->name
);
858 # include "version.h"
860 const char *const version
= NULL
;
862 const char *version_prefix
, *version_string
;
863 const char *c_flags
, *ld_flags
, *cpp_flags
;
864 const char *const desc_flags_unknown
= "unknown";
865 struct bytes_size bytes_size
;
868 c_flags
= to_str (CFLAGS
);
870 c_flags
= desc_flags_unknown
;
873 ld_flags
= to_str (LDFLAGS
);
875 ld_flags
= desc_flags_unknown
;
878 cpp_flags
= to_str (CPPFLAGS
);
880 cpp_flags
= desc_flags_unknown
;
887 version_prefix
= version
? "" : "v";
888 version_string
= version
? version
: VERSION
;
889 printf ("%s %s%s (compiled at %s, %s)\n", PROGRAM_NAME
, version_prefix
, version_string
, __DATE__
, __TIME__
);
891 printf ("Compiler flags: %s\n", c_flags
);
892 printf ("Linker flags: %s\n", ld_flags
);
893 printf ("Preprocessor flags: %s\n", cpp_flags
);
894 if (get_bytes_size (BUF_SIZE
, &bytes_size
))
896 if (BUF_SIZE
% 1024 == 0)
897 printf ("Buffer size: %u%c\n", bytes_size
.size
, bytes_size
.unit
);
899 printf ("Buffer size: %u%c, %u byte%s\n", bytes_size
.size
, bytes_size
.unit
,
900 BUF_SIZE
% 1024, BUF_SIZE
% 1024 > 1 ? "s" : "");
903 printf ("Buffer size: %lu byte%s\n", (unsigned long)BUF_SIZE
, BUF_SIZE
> 1 ? "s" : "");
904 printf ("Color separator: '%c'\n", COLOR_SEP_CHAR
);
905 printf ("Debugging: %s\n", debug
? "yes" : "no");
911 if (stream
&& fileno (stream
) != STDIN_FILENO
)
921 for (i
= 0; i
< stacked_vars
; i
++)
923 free_null (vars_list
);
928 free_color_names (struct color_name
**color_names
)
931 for (i
= 0; color_names
[i
]; i
++)
933 RELEASE_VAR (color_names
[i
]->name
);
934 RELEASE_VAR (color_names
[i
]->orig
);
935 RELEASE_VAR (color_names
[i
]);
940 free_conf (struct conf
*config
)
943 free (config
->color
);
944 free (config
->exclude_random
);
945 free (config
->omit_color_empty
);
949 process_args (unsigned int arg_cnt
, char **arg_strings
, char *attr
, const struct color
**colors
, const char **file
, FILE **stream
, struct conf
*config
)
951 bool has_hyphen
, use_conf_color
;
955 struct color_name
*color_names
[3] = {
956 NULL
, /* foreground */
957 NULL
, /* background */
958 NULL
, /* sentinel value */
961 const char *color_string
= arg_cnt
>= 1 ? arg_strings
[0] : NULL
;
962 const char *file_string
= arg_cnt
== 2 ? arg_strings
[1] : NULL
;
964 assert (color_string
!= NULL
);
966 has_hyphen
= streq (color_string
, "-");
971 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen cannot be used as color string");
972 else if (!config
->color
)
973 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen must be preceded by color string");
976 if (!has_hyphen
&& (ret
= lstat (color_string
, &sb
)) == 0) /* exists */
977 /* Ensure that we don't fail if there's a file with one or more
978 color names in its path. */
979 use_conf_color
= skip_path_colors (color_string
, file_string
, &sb
, !!config
->color
);
981 use_conf_color
= true;
983 use_conf_color
= false;
985 /* Use color from config file. */
986 if (arg_cnt
== 1 && use_conf_color
)
988 file_string
= color_string
;
989 color_string
= config
->color
;
992 if ((p
= strchr (color_string
, COLOR_SEP_CHAR
)))
994 if (p
== color_string
)
995 vfprintf_fail (formats
[FMT_STRING
], "foreground color missing in string", color_string
);
996 else if (p
== color_string
+ strlen (color_string
) - 1)
997 vfprintf_fail (formats
[FMT_STRING
], "background color missing in string", color_string
);
998 else if (strchr (++p
, COLOR_SEP_CHAR
))
999 vfprintf_fail (formats
[FMT_STRING
], "one color pair allowed only for string", color_string
);
1002 gather_color_names (color_string
, attr
, color_names
);
1004 assert (color_names
[FOREGROUND
] != NULL
);
1006 if (color_names
[BACKGROUND
])
1009 const unsigned int color_sets
[2][2] = { { FOREGROUND
, BACKGROUND
}, { BACKGROUND
, FOREGROUND
} };
1010 for (i
= 0; i
< 2; i
++)
1012 const unsigned int color1
= color_sets
[i
][0];
1013 const unsigned int color2
= color_sets
[i
][1];
1014 if (CHECK_COLORS_RANDOM (color1
, color2
))
1015 vfprintf_fail (formats
[FMT_RANDOM
], tables
[color1
].desc
, color_names
[color1
]->orig
, "cannot be combined with", color_names
[color2
]->orig
);
1019 find_color_entries (color_names
, colors
);
1020 assert (colors
[FOREGROUND
] != NULL
);
1021 free_color_names (color_names
);
1023 if (!colors
[FOREGROUND
]->code
&& colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
1025 struct color_name color_name
;
1026 color_name
.name
= color_name
.orig
= "default";
1028 find_color_entry (&color_name
, FOREGROUND
, colors
);
1029 assert (colors
[FOREGROUND
]->code
!= NULL
);
1032 process_file_arg (file_string
, file
, stream
);
1036 process_file_arg (const char *file_string
, const char **file
, FILE **stream
)
1040 if (streq (file_string
, "-"))
1044 const char *file
= file_string
;
1049 ret
= stat (file
, &sb
);
1052 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
1054 if (!VALID_FILE_TYPE (sb
.st_mode
))
1055 vfprintf_fail (formats
[FMT_TYPE
], file
, "unrecognized type", get_file_type (sb
.st_mode
));
1057 *stream
= open_file (file
, "r");
1059 *file
= file_string
;
1067 assert (*stream
!= NULL
);
1068 assert (*file
!= NULL
);
1072 skip_path_colors (const char *color_string
, const char *file_string
, const struct stat
*sb
, const bool has_conf
)
1076 const char *color
= color_string
;
1077 const mode_t mode
= sb
->st_mode
;
1079 for (c
= 1; c
<= 2 && *color
; c
++)
1081 bool matched
= false;
1083 for (i
= 0; i
< tables
[GENERIC
].count
; i
++)
1085 const struct color
*entry
= &tables
[GENERIC
].entries
[i
];
1086 if (has_color_name (color
, entry
->name
))
1088 color
+= strlen (entry
->name
);
1093 if (!matched
&& has_color_name (color
, "random"))
1095 color
+= strlen ("random");
1098 if (matched
&& *color
== COLOR_SEP_CHAR
&& *(color
+ 1))
1104 have_file
= (*color
!= '\0');
1108 const char *file_existing
= color_string
;
1110 vfprintf_fail (formats
[FMT_QUOTE
], get_file_type (mode
), file_existing
, "cannot be used as color string");
1113 if (VALID_FILE_TYPE (mode
))
1117 vfprintf_fail (formats
[FMT_QUOTE
], get_file_type (mode
), file_existing
, "must be preceded by color string");
1120 vfprintf_fail (formats
[FMT_QUOTE
], get_file_type (mode
), file_existing
, "is not a valid file type");
1127 gather_color_names (const char *color_string
, char *attr
, struct color_name
**color_names
)
1130 char *color
, *p
, *str
;
1132 str
= xstrdup (color_string
);
1135 for (index
= 0, color
= str
; *color
; index
++, color
= p
)
1140 if ((sep
= strchr (color
, COLOR_SEP_CHAR
)))
1146 p
= color
+ strlen (color
);
1149 for (ch
= color
; *ch
; ch
++)
1151 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be made of non-alphabetic characters");
1153 for (ch
= color
+ 1; *ch
; ch
++)
1155 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be in mixed lower/upper case");
1157 if (streq (color
, "None"))
1158 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be bold");
1160 if (isupper (*color
))
1165 snprintf (attr
+ strlen (attr
), 3, "1;");
1168 vfprintf_fail (formats
[FMT_COLOR
], tables
[BACKGROUND
].desc
, color
, "cannot be bold");
1170 default: /* never reached */
1175 color_names
[index
] = xcalloc (1, sizeof (struct color_name
));
1176 STACK_VAR (color_names
[index
]);
1178 color_names
[index
]->orig
= xstrdup (color
);
1179 STACK_VAR (color_names
[index
]->orig
);
1181 for (ch
= color
; *ch
; ch
++)
1182 *ch
= tolower (*ch
);
1184 color_names
[index
]->name
= xstrdup (color
);
1185 STACK_VAR (color_names
[index
]->name
);
1192 read_print_stream (const char *attr
, const struct color
**colors
, const char *file
, FILE *stream
)
1194 char buf
[BUF_SIZE
+ 1];
1195 unsigned int flags
= 0;
1197 while (!feof (stream
))
1202 bytes_read
= fread (buf
, 1, BUF_SIZE
, stream
);
1203 if (bytes_read
!= BUF_SIZE
&& ferror (stream
))
1204 vfprintf_fail (formats
[FMT_ERROR
], BUF_SIZE
, "read");
1205 buf
[bytes_read
] = '\0';
1207 while ((eol
= strpbrk (line
, "\n\r")))
1209 const bool has_text
= (eol
> line
);
1215 if (*(eol
+ 1) == '\n')
1218 else if (*eol
== '\n')
1220 else /* never reached */
1221 vfprintf_fail (formats
[FMT_FILE
], file
, "unrecognized line ending");
1222 p
= eol
+ SKIP_LINE_ENDINGS (flags
);
1224 print_line (attr
, colors
, line
, flags
,
1225 omit_color_empty
? has_text
: true);
1231 print_line (attr
, colors
, line
, 0, true);
1233 else if (*line
!= '\0')
1236 if ((clean
|| clean_all
) && (p
= strrchr (line
, '\033')))
1237 merge_print_line (line
, p
, stream
);
1239 print_line (attr
, colors
, line
, 0, true);
1245 merge_print_line (const char *line
, const char *p
, FILE *stream
)
1248 char *merged_esc
= NULL
;
1249 const char *esc
= "";
1250 const char char_restore
= *p
;
1252 complete_part_line (p
+ 1, &buf
, stream
);
1256 /* form escape sequence */
1257 esc
= merged_esc
= str_concat (p
, buf
);
1258 /* shorten partial line accordingly */
1263 #ifdef TEST_MERGE_PART_LINE
1264 printf ("%s%s", line
, esc
);
1266 _exit (EXIT_SUCCESS
);
1269 *(char *)p
= char_restore
;
1276 complete_part_line (const char *p
, char **buf
, FILE *stream
)
1278 bool got_next_char
= false, read_from_stream
;
1282 if (get_next_char (&ch
, &p
, stream
, &read_from_stream
))
1286 if (read_from_stream
)
1287 save_char (ch
, buf
, &i
, &size
);
1291 if (read_from_stream
)
1292 ungetc ((int)ch
, stream
);
1293 return; /* cancel */
1297 return; /* cancel */
1299 while (get_next_char (&ch
, &p
, stream
, &read_from_stream
))
1301 if (isdigit (ch
) || ch
== ';')
1303 if (read_from_stream
)
1304 save_char (ch
, buf
, &i
, &size
);
1306 else /* got next character */
1308 got_next_char
= true;
1317 if (read_from_stream
)
1318 save_char (ch
, buf
, &i
, &size
);
1322 if (read_from_stream
)
1323 ungetc ((int)ch
, stream
);
1324 return; /* cancel */
1328 return; /* cancel */
1332 get_next_char (char *ch
, const char **p
, FILE *stream
, bool *read_from_stream
)
1337 if ((c
= fgetc (stream
)) != EOF
)
1340 *read_from_stream
= true;
1345 *read_from_stream
= false;
1353 *read_from_stream
= false;
1359 save_char (char ch
, char **buf
, size_t *i
, size_t *size
)
1363 *size
= ALLOC_COMPLETE_PART_LINE
;
1364 *buf
= xmalloc (*size
);
1366 /* +1: effective occupied size of buffer */
1367 else if ((*i
+ 1) == *size
)
1370 *buf
= xrealloc (*buf
, *size
);
1373 (*buf
)[*i
+ 1] = '\0';
1378 find_color_entries (struct color_name
**color_names
, const struct color
**colors
)
1384 gettimeofday (&tv
, NULL
);
1385 srand (tv
.tv_usec
* tv
.tv_sec
);
1387 for (index
= 0; color_names
[index
]; index
++)
1389 const char *color_name
= color_names
[index
]->name
;
1391 const unsigned int count
= tables
[index
].count
;
1392 const struct color
*const color_entries
= tables
[index
].entries
;
1394 if (streq (color_name
, "random"))
1400 i
= rand() % (count
- 2) + 1; /* omit color none and default */
1404 /* --exclude-random */
1405 if (exclude
&& streq (exclude
, color_entries
[i
].name
))
1407 else if (color_names
[BACKGROUND
] && streq (color_names
[BACKGROUND
]->name
, color_entries
[i
].name
))
1411 if (streq (colors
[FOREGROUND
]->name
, color_entries
[i
].name
))
1414 default: /* never reached */
1417 } while (excludable
);
1418 colors
[index
] = (struct color
*)&color_entries
[i
];
1421 find_color_entry (color_names
[index
], index
, colors
);
1426 find_color_entry (const struct color_name
*color_name
, unsigned int index
, const struct color
**colors
)
1431 const unsigned int count
= tables
[index
].count
;
1432 const struct color
*const color_entries
= tables
[index
].entries
;
1434 for (i
= 0; i
< count
; i
++)
1435 if (streq (color_name
->name
, color_entries
[i
].name
))
1437 colors
[index
] = (struct color
*)&color_entries
[i
];
1442 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color_name
->orig
, "not recognized");
1446 print_line (const char *attr
, const struct color
**colors
, const char *const line
, unsigned int flags
, bool emit_colors
)
1449 if (clean
|| clean_all
)
1451 /* skip for --omit-color-empty? */
1452 else if (emit_colors
)
1454 /* Foreground color code is guaranteed to be set when background color code is present. */
1455 if (colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
1456 printf ("\033[%s", colors
[BACKGROUND
]->code
);
1457 if (colors
[FOREGROUND
]->code
)
1458 printf ("\033[%s%s%s\033[0m", attr
, colors
[FOREGROUND
]->code
, line
);
1460 printf (formats
[FMT_GENERIC
], line
);
1469 print_clean (const char *line
)
1471 const char *p
= line
;
1474 p
= get_end_of_esc (p
);
1478 const char *text_start
= p
;
1479 const char *text_end
= get_end_of_text (p
);
1480 print_text (text_start
, text_end
- text_start
);
1481 p
= get_end_of_esc (text_end
);
1486 is_esc (const char *p
)
1488 return gather_esc_offsets (p
, NULL
, NULL
);
1492 get_end_of_esc (const char *p
)
1495 const char *end
= NULL
;
1496 while ((esc
= strchr (p
, '\033')))
1498 if (gather_esc_offsets (esc
, NULL
, &end
))
1502 return end
? end
+ 1 : p
+ strlen (p
);
1506 get_end_of_text (const char *p
)
1509 const char *start
= NULL
;
1510 while ((esc
= strchr (p
, '\033')))
1512 if (gather_esc_offsets (esc
, &start
, NULL
))
1516 return start
? start
: p
+ strlen (p
);
1520 print_text (const char *p
, size_t len
)
1522 size_t bytes_written
;
1523 bytes_written
= fwrite (p
, 1, len
, stdout
);
1524 if (bytes_written
!= len
)
1525 vfprintf_fail (formats
[FMT_ERROR
], (unsigned long)len
, "written");
1529 gather_esc_offsets (const char *p
, const char **start
, const char **end
)
1532 if (*p
== 27 && *(p
+ 1) == '[')
1535 const char *const begin
= p
;
1538 valid
= validate_esc_clean_all (&p
);
1542 unsigned int prev_iter
, iter
;
1544 prev_iter
= iter
= 0;
1546 check_values
= false;
1551 while (isdigit (*p
))
1555 else /* check range */
1560 const unsigned int digits
= p
- digit
;
1561 for (i
= 0; i
< digits
; i
++)
1565 valid
= validate_esc_clean (value
, iter
, &prev_iter
, &p
, &check_values
);
1567 } while (check_values
);
1582 validate_esc_clean_all (const char **p
)
1584 while (isdigit (**p
) || **p
== ';')
1586 return (**p
== 'm');
1590 validate_esc_clean (int value
, unsigned int iter
, unsigned int *prev_iter
, const char **p
, bool *check_values
)
1592 if (is_reset (value
, iter
, p
))
1594 else if (is_attr (value
, iter
, *prev_iter
, p
))
1597 *check_values
= true;
1599 return false; /* partial escape sequence, need another valid value */
1601 else if (is_fg_color (value
, p
))
1603 else if (is_bg_color (value
, iter
, p
))
1610 is_reset (int value
, unsigned int iter
, const char **p
)
1612 return (value
== 0 && iter
== 1 && **p
== 'm');
1616 is_attr (int value
, unsigned int iter
, unsigned int prev_iter
, const char **p
)
1618 return ((value
> 0 && value
< 10) && (iter
- prev_iter
== 1) && **p
== ';');
1622 is_fg_color (int value
, const char **p
)
1624 return (((value
>= 30 && value
<= 37) || value
== 39) && **p
== 'm');
1628 is_bg_color (int value
, unsigned int iter
, const char **p
)
1630 return (((value
>= 40 && value
<= 47) || value
== 49) && iter
== 1 && **p
== 'm');
1635 malloc_wrap (size_t size
)
1637 void *p
= malloc (size
);
1644 calloc_wrap (size_t nmemb
, size_t size
)
1646 void *p
= calloc (nmemb
, size
);
1653 realloc_wrap (void *ptr
, size_t size
)
1655 void *p
= realloc (ptr
, size
);
1661 static const char *const format_debug
= "%s: %10s %7lu bytes [source file %s, line %5u]\n";
1663 malloc_wrap_debug (size_t size
, const char *file
, unsigned int line
)
1665 void *p
= malloc (size
);
1667 MEM_ALLOC_FAIL_DEBUG (file
, line
);
1668 fprintf (log
, format_debug
, program_name
, "malloc'ed", (unsigned long)size
, file
, line
);
1673 calloc_wrap_debug (size_t nmemb
, size_t size
, const char *file
, unsigned int line
)
1675 void *p
= calloc (nmemb
, size
);
1677 MEM_ALLOC_FAIL_DEBUG (file
, line
);
1678 fprintf (log
, format_debug
, program_name
, "calloc'ed", (unsigned long)(nmemb
* size
), file
, line
);
1683 realloc_wrap_debug (void *ptr
, size_t size
, const char *file
, unsigned int line
)
1685 void *p
= realloc (ptr
, size
);
1687 MEM_ALLOC_FAIL_DEBUG (file
, line
);
1688 fprintf (log
, format_debug
, program_name
, "realloc'ed", (unsigned long)size
, file
, line
);
1694 free_wrap (void **ptr
)
1701 # define do_malloc(len, file, line) malloc_wrap(len)
1703 # define do_malloc(len, file, line) malloc_wrap_debug(len, file, line)
1707 strdup_wrap (const char *str
, const char *file
, unsigned int line
)
1709 const size_t len
= strlen (str
) + 1;
1710 char *p
= do_malloc (len
, file
, line
);
1711 strncpy (p
, str
, len
);
1716 str_concat_wrap (const char *str1
, const char *str2
, const char *file
, unsigned int line
)
1718 const size_t len
= strlen (str1
) + strlen (str2
) + 1;
1721 p
= str
= do_malloc (len
, file
, line
);
1722 strncpy (p
, str1
, strlen (str1
));
1724 strncpy (p
, str2
, strlen (str2
));
1732 expand_string (const char *str
)
1737 wordexp (str
, &p
, 0);
1738 if (p
.we_wordc
>= 1)
1739 s
= xstrdup (p
.we_wordv
[0]);
1746 get_bytes_size (unsigned long bytes
, struct bytes_size
*bytes_size
)
1748 const char *unit
, units
[] = { '0', 'K', 'M', 'G', '\0' };
1749 unsigned long size
= bytes
;
1753 while (size
>= 1024 && *(unit
+ 1))
1758 bytes_size
->size
= (unsigned int)size
;
1759 bytes_size
->unit
= *unit
;
1764 get_file_type (mode_t mode
)
1768 else if (S_ISDIR (mode
))
1770 else if (S_ISCHR (mode
))
1771 return "character device";
1772 else if (S_ISBLK (mode
))
1773 return "block device";
1774 else if (S_ISFIFO (mode
))
1775 return "named pipe";
1776 else if (S_ISLNK (mode
))
1777 return "symbolic link";
1778 else if (S_ISSOCK (mode
))
1785 has_color_name (const char *str
, const char *name
)
1789 assert (strlen (str
) > 0);
1790 assert (strlen (name
) > 0);
1792 if (!(*str
== *name
|| *str
== toupper (*name
)))
1794 else if (*(name
+ 1) != '\0'
1795 && !((p
= strstr (str
+ 1, name
+ 1)) && p
== str
+ 1))
1802 open_file (const char *file
, const char *mode
)
1807 stream
= fopen (file
, mode
);
1809 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
1814 #define DO_VFPRINTF(fmt) \
1816 fprintf (stderr, "%s: ", program_name); \
1817 va_start (ap, fmt); \
1818 vfprintf (stderr, fmt, ap); \
1820 fprintf (stderr, "\n");
1823 vfprintf_diag (const char *fmt
, ...)
1829 vfprintf_fail (const char *fmt
, ...)
1832 exit (EXIT_FAILURE
);
1836 stack_var (void ***list
, unsigned int *stacked
, unsigned int index
, void *ptr
)
1838 /* nothing to stack */
1842 *list
= xmalloc (sizeof (void *));
1846 for (i
= 0; i
< *stacked
; i
++)
1850 return; /* reused */
1852 *list
= xrealloc (*list
, (*stacked
+ 1) * sizeof (void *));
1854 (*list
)[index
] = ptr
;
1859 release_var (void **list
, unsigned int stacked
, void **ptr
)
1862 /* nothing to release */
1865 for (i
= 0; i
< stacked
; i
++)
1866 if (list
[i
] == *ptr
)