]>
git.refcnt.org Git - colorize.git/blob - colorize.c
0cfbaad0862809baf37a7e3a0037748e557d87f8
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.60"
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 },
223 static unsigned int stacked_vars
;
224 static void **vars_list
;
227 static bool clean_all
;
229 static char attr
[MAX_ATTRIBUTE_CHARS
+ 1];
230 static char *exclude
;
232 static const char *program_name
;
234 static void process_opts (int, char **);
235 static void process_opt_attr (const char *);
236 static void write_attr (unsigned int);
237 static void print_hint (void);
238 static void print_help (void);
239 static void print_version (void);
240 static void cleanup (void);
241 static void free_color_names (struct color_name
**);
242 static void process_args (unsigned int, char **, char *, const struct color
**, const char **, FILE **);
243 static void process_file_arg (const char *, const char **, FILE **);
244 static void skip_path_colors (const char *, const char *, const struct stat
*);
245 static void gather_color_names (const char *, char *, struct color_name
**);
246 static void read_print_stream (const char *, const struct color
**, const char *, FILE *);
247 static void merge_print_line (const char *, const char *, FILE *);
248 static void complete_part_line (const char *, char **, FILE *);
249 static bool get_next_char (char *, const char **, FILE *, bool *);
250 static void save_char (char, char **, size_t *, size_t *);
251 static void find_color_entries (struct color_name
**, const struct color
**);
252 static void find_color_entry (const struct color_name
*, unsigned int, const struct color
**);
253 static void print_line (const char *, const struct color
**, const char * const, unsigned int);
254 static void print_clean (const char *);
255 static bool is_esc (const char *);
256 static const char *get_end_of_esc (const char *);
257 static const char *get_end_of_text (const char *);
258 static void print_text (const char *, size_t);
259 static bool gather_esc_offsets (const char *, const char **, const char **);
260 static bool validate_esc_clean_all (const char **);
261 static bool validate_esc_clean (int, unsigned int, unsigned int *, const char **, bool *);
262 static bool is_reset (int, unsigned int, const char **);
263 static bool is_attr (int, unsigned int, unsigned int, const char **);
264 static bool is_fg_color (int, const char **);
265 static bool is_bg_color (int, unsigned int, const char **);
267 static void *malloc_wrap (size_t);
268 static void *calloc_wrap (size_t, size_t);
269 static void *realloc_wrap (void *, size_t);
271 static void *malloc_wrap_debug (size_t, const char *, unsigned int);
272 static void *calloc_wrap_debug (size_t, size_t, const char *, unsigned int);
273 static void *realloc_wrap_debug (void *, size_t, const char *, unsigned int);
275 static void free_wrap (void **);
276 static char *strdup_wrap (const char *, const char *, unsigned int);
277 static char *str_concat_wrap (const char *, const char *, const char *, unsigned int);
278 static bool get_bytes_size (unsigned long, struct bytes_size
*);
279 static char *get_file_type (mode_t
);
280 static bool has_color_name (const char *, const char *);
281 static FILE *open_file (const char *, const char *);
282 static void vfprintf_diag (const char *, ...);
283 static void vfprintf_fail (const char *, ...);
284 static void stack_var (void ***, unsigned int *, unsigned int, void *);
285 static void release_var (void **, unsigned int, void **);
290 main (int argc
, char **argv
)
292 unsigned int arg_cnt
;
294 const struct color
*colors
[2] = {
295 NULL
, /* foreground */
296 NULL
, /* background */
299 const char *file
= NULL
;
301 program_name
= argv
[0];
304 setvbuf (stdout
, NULL
, _IOLBF
, 0);
307 log
= open_file (DEBUG_FILE
, "w");
312 process_opts (argc
, argv
);
314 arg_cnt
= argc
- optind
;
316 if (clean
|| clean_all
)
318 if (clean
&& clean_all
)
319 vfprintf_fail (formats
[FMT_GENERIC
], "--clean and --clean-all switch are mutually exclusive");
322 const char *format
= "%s %s";
323 const char *message
= "switch cannot be used with more than one file";
325 vfprintf_fail (format
, "--clean", message
);
327 vfprintf_fail (format
, "--clean-all", message
);
332 if (arg_cnt
== 0 || arg_cnt
> 2)
334 vfprintf_diag ("%u arguments provided, expected 1-2 arguments or clean option", arg_cnt
);
340 if (clean
|| clean_all
)
341 process_file_arg (argv
[optind
], &file
, &stream
);
343 process_args (arg_cnt
, &argv
[optind
], &attr
[0], colors
, &file
, &stream
);
344 read_print_stream (&attr
[0], colors
, file
, stream
);
346 RELEASE_VAR (exclude
);
351 #define PRINT_HELP_EXIT() \
353 exit (EXIT_SUCCESS); \
355 #define PRINT_VERSION_EXIT() \
357 exit (EXIT_SUCCESS); \
362 process_opts (int argc
, char **argv
)
365 while ((opt
= getopt_long (argc
, argv
, "hV", long_opts
, NULL
)) != -1)
369 case 0: /* long opts */
374 opt
= xstrdup (optarg
);
375 process_opt_attr (opt
);
385 case OPT_EXCLUDE_RANDOM
: {
388 exclude
= xstrdup (optarg
);
390 for (i
= 1; i
< tables
[GENERIC
].count
- 1; i
++) /* skip color none and default */
392 const struct color
*entry
= &tables
[GENERIC
].entries
[i
];
393 if (streq (exclude
, entry
->name
))
400 vfprintf_fail (formats
[FMT_GENERIC
], "--exclude-random switch must be provided a plain color");
406 PRINT_VERSION_EXIT ();
407 default: /* never reached */
414 PRINT_VERSION_EXIT ();
418 default: /* never reached */
425 process_opt_attr (const char *p
)
431 vfprintf_fail (formats
[FMT_GENERIC
], "--attr switch must be provided a string");
435 if (*p
!= '\0' && *p
!= ',')
436 vfprintf_fail (formats
[FMT_GENERIC
], "--attr switch must have strings separated by ,");
439 /* If attributes are added to this "list", also increase MAX_ATTRIBUTE_CHARS! */
440 if (p
- s
== 4 && strneq (s
, "bold", 4))
442 else if (p
- s
== 10 && strneq (s
, "underscore", 10))
444 else if (p
- s
== 5 && strneq (s
, "blink", 5))
446 else if (p
- s
== 7 && strneq (s
, "reverse", 7))
448 else if (p
- s
== 9 && strneq (s
, "concealed", 9))
451 vfprintf_fail (formats
[FMT_GENERIC
], "--attr switch must be provided valid attribute names");
459 write_attr (unsigned int val
)
461 snprintf (attr
+ strlen (attr
), 3, "%u;", val
);
467 fprintf (stderr
, "Type `%s --help' for help screen.\n", program_name
);
475 const char *short_opt
;
477 const struct short_opt short_opts
[] = {
481 const struct option
*opt
= long_opts
;
484 printf ("Usage: %s (foreground) OR (foreground)%c(background) OR --clean[-all] [-|file]\n\n", program_name
, COLOR_SEP_CHAR
);
485 printf ("\tColors (foreground) (background)\n");
486 for (i
= 0; i
< tables
[FOREGROUND
].count
; i
++)
488 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
489 const char *name
= entry
->name
;
490 const char *code
= entry
->code
;
492 printf ("\t\t{\033[%s#\033[0m} [%c%c]%s%*s%s\n",
493 code
, toupper (*name
), *name
, name
+ 1, 10 - (int)strlen (name
), " ", name
);
495 printf ("\t\t{-} %s%*s%s\n", name
, 13 - (int)strlen (name
), " ", name
);
497 printf ("\t\t{*} [Rr]%s%*s%s [--exclude-random=<foreground color>]\n", "andom", 10 - (int)strlen ("random"), " ", "random");
499 printf ("\n\tFirst character of color name in upper case denotes increased intensity,\n");
500 printf ("\twhereas for lower case colors will be of normal intensity.\n");
502 printf ("\n\tOptions\n");
503 for (; opt
->name
; opt
++)
505 const char *short_opt
= NULL
;
507 for (i
= 0; i
< sizeof (short_opts
) / sizeof (struct short_opt
); i
++)
509 if (streq (opt
->name
, short_opts
[i
].name
))
511 short_opt
= short_opts
[i
].short_opt
;
516 printf ("\t\t-%s, --%s\n", short_opt
, opt
->name
);
518 printf ("\t\t --%s\n", opt
->name
);
527 # include "version.h"
529 const char *version
= NULL
;
531 const char *version_prefix
, *version_string
;
532 const char *c_flags
, *ld_flags
, *cpp_flags
;
533 struct bytes_size bytes_size
;
536 c_flags
= to_str (CFLAGS
);
541 ld_flags
= to_str (LDFLAGS
);
543 ld_flags
= "unknown";
546 cpp_flags
= to_str (CPPFLAGS
);
548 cpp_flags
= "unknown";
555 version_prefix
= version
? "" : "v";
556 version_string
= version
? version
: VERSION
;
557 printf ("colorize %s%s (compiled at %s, %s)\n", version_prefix
, version_string
, __DATE__
, __TIME__
);
559 printf ("Compiler flags: %s\n", c_flags
);
560 printf ("Linker flags: %s\n", ld_flags
);
561 printf ("Preprocessor flags: %s\n", cpp_flags
);
562 if (get_bytes_size (BUF_SIZE
, &bytes_size
))
564 if (BUF_SIZE
% 1024 == 0)
565 printf ("Buffer size: %u%c\n", bytes_size
.size
, bytes_size
.unit
);
567 printf ("Buffer size: %u%c, %u byte%s\n", bytes_size
.size
, bytes_size
.unit
,
568 BUF_SIZE
% 1024, BUF_SIZE
% 1024 > 1 ? "s" : "");
571 printf ("Buffer size: %lu byte%s\n", (unsigned long)BUF_SIZE
, BUF_SIZE
> 1 ? "s" : "");
572 printf ("Color separator: '%c'\n", COLOR_SEP_CHAR
);
573 printf ("Debugging: %s\n", debug
? "yes" : "no");
579 if (stream
&& fileno (stream
) != STDIN_FILENO
)
589 for (i
= 0; i
< stacked_vars
; i
++)
591 free_null (vars_list
);
596 free_color_names (struct color_name
**color_names
)
599 for (i
= 0; color_names
[i
]; i
++)
601 RELEASE_VAR (color_names
[i
]->name
);
602 RELEASE_VAR (color_names
[i
]->orig
);
603 RELEASE_VAR (color_names
[i
]);
608 process_args (unsigned int arg_cnt
, char **arg_strings
, char *attr
, const struct color
**colors
, const char **file
, FILE **stream
)
613 struct color_name
*color_names
[3] = { NULL
, NULL
, NULL
};
615 const char *color_string
= arg_cnt
>= 1 ? arg_strings
[0] : NULL
;
616 const char *file_string
= arg_cnt
== 2 ? arg_strings
[1] : NULL
;
618 assert (color_string
);
620 if (streq (color_string
, "-"))
623 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen cannot be used as color string");
625 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen must be preceded by color string");
628 ret
= lstat (color_string
, &sb
);
630 /* Ensure that we don't fail if there's a file with one or more
631 color names in its path. */
632 if (ret
== 0) /* success */
633 skip_path_colors (color_string
, file_string
, &sb
);
635 if ((p
= strchr (color_string
, COLOR_SEP_CHAR
)))
637 if (p
== color_string
)
638 vfprintf_fail (formats
[FMT_STRING
], "foreground color missing in string", color_string
);
639 else if (p
== color_string
+ strlen (color_string
) - 1)
640 vfprintf_fail (formats
[FMT_STRING
], "background color missing in string", color_string
);
641 else if (strchr (++p
, COLOR_SEP_CHAR
))
642 vfprintf_fail (formats
[FMT_STRING
], "one color pair allowed only for string", color_string
);
645 gather_color_names (color_string
, attr
, color_names
);
647 assert (color_names
[FOREGROUND
]);
649 if (color_names
[BACKGROUND
])
652 const unsigned int color_sets
[2][2] = { { FOREGROUND
, BACKGROUND
}, { BACKGROUND
, FOREGROUND
} };
653 for (i
= 0; i
< 2; i
++)
655 const unsigned int color1
= color_sets
[i
][0];
656 const unsigned int color2
= color_sets
[i
][1];
657 if (CHECK_COLORS_RANDOM (color1
, color2
))
658 vfprintf_fail (formats
[FMT_RANDOM
], tables
[color1
].desc
, color_names
[color1
]->orig
, "cannot be combined with", color_names
[color2
]->orig
);
662 find_color_entries (color_names
, colors
);
663 free_color_names (color_names
);
665 if (!colors
[FOREGROUND
]->code
&& colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
667 struct color_name color_name
;
668 color_name
.name
= color_name
.orig
= "default";
670 find_color_entry (&color_name
, FOREGROUND
, colors
);
673 process_file_arg (file_string
, file
, stream
);
677 process_file_arg (const char *file_string
, const char **file
, FILE **stream
)
681 if (streq (file_string
, "-"))
685 const char *file
= file_string
;
690 ret
= stat (file
, &sb
);
693 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
695 if (!VALID_FILE_TYPE (sb
.st_mode
))
696 vfprintf_fail (formats
[FMT_TYPE
], file
, "unrecognized type", get_file_type (sb
.st_mode
));
698 *stream
= open_file (file
, "r");
713 skip_path_colors (const char *color_string
, const char *file_string
, const struct stat
*sb
)
717 const char *color
= color_string
;
718 const mode_t mode
= sb
->st_mode
;
720 for (c
= 1; c
<= 2 && *color
; c
++)
722 bool matched
= false;
724 for (i
= 0; i
< tables
[GENERIC
].count
; i
++)
726 const struct color
*entry
= &tables
[GENERIC
].entries
[i
];
727 if (has_color_name (color
, entry
->name
))
729 color
+= strlen (entry
->name
);
734 if (!matched
&& has_color_name (color
, "random"))
736 color
+= strlen ("random");
739 if (matched
&& *color
== COLOR_SEP_CHAR
&& *(color
+ 1))
745 have_file
= (*color
!= '\0');
749 const char *file_exists
= color_string
;
751 vfprintf_fail (formats
[FMT_QUOTE
], get_file_type (mode
), file_exists
, "cannot be used as color string");
754 if (VALID_FILE_TYPE (mode
))
755 vfprintf_fail (formats
[FMT_QUOTE
], get_file_type (mode
), file_exists
, "must be preceded by color string");
757 vfprintf_fail (formats
[FMT_QUOTE
], get_file_type (mode
), file_exists
, "is not a valid file type");
763 gather_color_names (const char *color_string
, char *attr
, struct color_name
**color_names
)
766 char *color
, *p
, *str
;
768 str
= xstrdup (color_string
);
771 for (index
= 0, color
= str
; *color
; index
++, color
= p
)
776 if ((sep
= strchr (color
, COLOR_SEP_CHAR
)))
782 p
= color
+ strlen (color
);
785 for (ch
= color
; *ch
; ch
++)
787 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be made of non-alphabetic characters");
789 for (ch
= color
+ 1; *ch
; ch
++)
791 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be in mixed lower/upper case");
793 if (streq (color
, "None"))
794 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be bold");
796 if (isupper (*color
))
801 snprintf (attr
+ strlen (attr
), 3, "1;");
804 vfprintf_fail (formats
[FMT_COLOR
], tables
[BACKGROUND
].desc
, color
, "cannot be bold");
805 default: /* never reached */
810 color_names
[index
] = xcalloc (1, sizeof (struct color_name
));
811 STACK_VAR (color_names
[index
]);
813 color_names
[index
]->orig
= xstrdup (color
);
814 STACK_VAR (color_names
[index
]->orig
);
816 for (ch
= color
; *ch
; ch
++)
819 color_names
[index
]->name
= xstrdup (color
);
820 STACK_VAR (color_names
[index
]->name
);
827 read_print_stream (const char *attr
, const struct color
**colors
, const char *file
, FILE *stream
)
829 char buf
[BUF_SIZE
+ 1];
830 unsigned int flags
= 0;
832 while (!feof (stream
))
837 bytes_read
= fread (buf
, 1, BUF_SIZE
, stream
);
838 if (bytes_read
!= BUF_SIZE
&& ferror (stream
))
839 vfprintf_fail (formats
[FMT_ERROR
], BUF_SIZE
, "read");
840 buf
[bytes_read
] = '\0';
842 while ((eol
= strpbrk (line
, "\n\r")))
849 if (*(eol
+ 1) == '\n')
852 else if (*eol
== '\n')
855 vfprintf_fail (formats
[FMT_FILE
], file
, "unrecognized line ending");
856 p
= eol
+ SKIP_LINE_ENDINGS (flags
);
858 print_line (attr
, colors
, line
, flags
);
864 print_line (attr
, colors
, line
, 0);
866 else if (*line
!= '\0')
869 if ((clean
|| clean_all
) && (p
= strrchr (line
, '\033')))
870 merge_print_line (line
, p
, stream
);
872 print_line (attr
, colors
, line
, 0);
878 merge_print_line (const char *line
, const char *p
, FILE *stream
)
881 char *merged_esc
= NULL
;
882 const char *esc
= "";
883 const char char_restore
= *p
;
885 complete_part_line (p
+ 1, &buf
, stream
);
889 /* form escape sequence */
890 esc
= merged_esc
= str_concat (p
, buf
);
891 /* shorten partial line accordingly */
896 #ifdef TEST_MERGE_PART_LINE
897 printf ("%s%s", line
, esc
);
899 _exit (EXIT_SUCCESS
);
902 *(char *)p
= char_restore
;
909 complete_part_line (const char *p
, char **buf
, FILE *stream
)
911 bool got_next_char
= false, read_from_stream
;
915 if (get_next_char (&ch
, &p
, stream
, &read_from_stream
))
919 if (read_from_stream
)
920 save_char (ch
, buf
, &i
, &size
);
924 if (read_from_stream
)
925 ungetc ((int)ch
, stream
);
932 while (get_next_char (&ch
, &p
, stream
, &read_from_stream
))
934 if (isdigit (ch
) || ch
== ';')
936 if (read_from_stream
)
937 save_char (ch
, buf
, &i
, &size
);
939 else /* read next character */
941 got_next_char
= true;
950 if (read_from_stream
)
951 save_char (ch
, buf
, &i
, &size
);
955 if (read_from_stream
)
956 ungetc ((int)ch
, stream
);
965 get_next_char (char *ch
, const char **p
, FILE *stream
, bool *read_from_stream
)
970 if ((c
= fgetc (stream
)) != EOF
)
973 *read_from_stream
= true;
978 *read_from_stream
= false;
986 *read_from_stream
= false;
992 save_char (char ch
, char **buf
, size_t *i
, size_t *size
)
996 *size
= ALLOC_COMPLETE_PART_LINE
;
997 *buf
= xmalloc (*size
);
999 /* +1: effective occupied size of buffer */
1000 else if ((*i
+ 1) == *size
)
1003 *buf
= xrealloc (*buf
, *size
);
1006 (*buf
)[*i
+ 1] = '\0';
1011 find_color_entries (struct color_name
**color_names
, const struct color
**colors
)
1017 gettimeofday (&tv
, NULL
);
1018 srand (tv
.tv_usec
* tv
.tv_sec
);
1020 for (index
= 0; color_names
[index
]; index
++)
1022 const char *color_name
= color_names
[index
]->name
;
1024 const unsigned int count
= tables
[index
].count
;
1025 const struct color
*const color_entries
= tables
[index
].entries
;
1027 if (streq (color_name
, "random"))
1033 i
= rand() % (count
- 2) + 1; /* omit color none and default */
1037 /* --exclude-random */
1038 if (exclude
&& streq (exclude
, color_entries
[i
].name
))
1040 else if (color_names
[BACKGROUND
] && streq (color_names
[BACKGROUND
]->name
, color_entries
[i
].name
))
1044 if (streq (colors
[FOREGROUND
]->name
, color_entries
[i
].name
))
1047 default: /* never reached */
1050 } while (excludable
);
1051 colors
[index
] = (struct color
*)&color_entries
[i
];
1054 find_color_entry (color_names
[index
], index
, colors
);
1059 find_color_entry (const struct color_name
*color_name
, unsigned int index
, const struct color
**colors
)
1064 const unsigned int count
= tables
[index
].count
;
1065 const struct color
*const color_entries
= tables
[index
].entries
;
1067 for (i
= 0; i
< count
; i
++)
1068 if (streq (color_name
->name
, color_entries
[i
].name
))
1070 colors
[index
] = (struct color
*)&color_entries
[i
];
1075 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color_name
->orig
, "not recognized");
1079 print_line (const char *attr
, const struct color
**colors
, const char *const line
, unsigned int flags
)
1082 if (clean
|| clean_all
)
1086 /* Foreground color code is guaranteed to be set when background color code is present. */
1087 if (colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
1088 printf ("\033[%s", colors
[BACKGROUND
]->code
);
1089 if (colors
[FOREGROUND
]->code
)
1090 printf ("\033[%s%s%s\033[0m", attr
, colors
[FOREGROUND
]->code
, line
);
1092 printf (formats
[FMT_GENERIC
], line
);
1101 print_clean (const char *line
)
1103 const char *p
= line
;
1106 p
= get_end_of_esc (p
);
1110 const char *text_start
= p
;
1111 const char *text_end
= get_end_of_text (p
);
1112 print_text (text_start
, text_end
- text_start
);
1113 p
= get_end_of_esc (text_end
);
1118 is_esc (const char *p
)
1120 return gather_esc_offsets (p
, NULL
, NULL
);
1124 get_end_of_esc (const char *p
)
1127 const char *end
= NULL
;
1128 while ((esc
= strchr (p
, '\033')))
1130 if (gather_esc_offsets (esc
, NULL
, &end
))
1134 return end
? end
+ 1 : p
+ strlen (p
);
1138 get_end_of_text (const char *p
)
1141 const char *start
= NULL
;
1142 while ((esc
= strchr (p
, '\033')))
1144 if (gather_esc_offsets (esc
, &start
, NULL
))
1148 return start
? start
: p
+ strlen (p
);
1152 print_text (const char *p
, size_t len
)
1154 size_t bytes_written
;
1155 bytes_written
= fwrite (p
, 1, len
, stdout
);
1156 if (bytes_written
!= len
)
1157 vfprintf_fail (formats
[FMT_ERROR
], (unsigned long)len
, "written");
1161 gather_esc_offsets (const char *p
, const char **start
, const char **end
)
1164 if (*p
== 27 && *(p
+ 1) == '[')
1167 const char *const begin
= p
;
1170 valid
= validate_esc_clean_all (&p
);
1174 unsigned int prev_iter
, iter
;
1176 prev_iter
= iter
= 0;
1178 check_values
= false;
1183 while (isdigit (*p
))
1187 else /* check range */
1192 const unsigned int digits
= p
- digit
;
1193 for (i
= 0; i
< digits
; i
++)
1197 valid
= validate_esc_clean (value
, iter
, &prev_iter
, &p
, &check_values
);
1199 } while (check_values
);
1214 validate_esc_clean_all (const char **p
)
1216 while (isdigit (**p
) || **p
== ';')
1218 return (**p
== 'm');
1222 validate_esc_clean (int value
, unsigned int iter
, unsigned int *prev_iter
, const char **p
, bool *check_values
)
1224 if (is_reset (value
, iter
, p
))
1226 else if (is_attr (value
, iter
, *prev_iter
, p
))
1229 *check_values
= true;
1231 return false; /* partial escape sequence, need another valid value */
1233 else if (is_fg_color (value
, p
))
1235 else if (is_bg_color (value
, iter
, p
))
1242 is_reset (int value
, unsigned int iter
, const char **p
)
1244 return (value
== 0 && iter
== 1 && **p
== 'm');
1248 is_attr (int value
, unsigned int iter
, unsigned int prev_iter
, const char **p
)
1250 return ((value
> 0 && value
< 10) && (iter
- prev_iter
== 1) && **p
== ';');
1254 is_fg_color (int value
, const char **p
)
1256 return (((value
>= 30 && value
<= 37) || value
== 39) && **p
== 'm');
1260 is_bg_color (int value
, unsigned int iter
, const char **p
)
1262 return (((value
>= 40 && value
<= 47) || value
== 49) && iter
== 1 && **p
== 'm');
1267 malloc_wrap (size_t size
)
1269 void *p
= malloc (size
);
1276 calloc_wrap (size_t nmemb
, size_t size
)
1278 void *p
= calloc (nmemb
, size
);
1285 realloc_wrap (void *ptr
, size_t size
)
1287 void *p
= realloc (ptr
, size
);
1294 malloc_wrap_debug (size_t size
, const char *file
, unsigned int line
)
1296 void *p
= malloc (size
);
1298 MEM_ALLOC_FAIL_DEBUG (file
, line
);
1299 fprintf (log
, "%s: malloc'ed %lu bytes [source file %s, line %u]\n", program_name
, (unsigned long)size
, file
, line
);
1304 calloc_wrap_debug (size_t nmemb
, size_t size
, const char *file
, unsigned int line
)
1306 void *p
= calloc (nmemb
, size
);
1308 MEM_ALLOC_FAIL_DEBUG (file
, line
);
1309 fprintf (log
, "%s: calloc'ed %lu bytes [source file %s, line %u]\n", program_name
, (unsigned long)(nmemb
* size
), file
, line
);
1314 realloc_wrap_debug (void *ptr
, size_t size
, const char *file
, unsigned int line
)
1316 void *p
= realloc (ptr
, size
);
1318 MEM_ALLOC_FAIL_DEBUG (file
, line
);
1319 fprintf (log
, "%s: realloc'ed %lu bytes [source file %s, line %u]\n", program_name
, (unsigned long)size
, file
, line
);
1325 free_wrap (void **ptr
)
1332 # define do_malloc(len, file, line) malloc_wrap(len)
1334 # define do_malloc(len, file, line) malloc_wrap_debug(len, file, line)
1338 strdup_wrap (const char *str
, const char *file
, unsigned int line
)
1340 const size_t len
= strlen (str
) + 1;
1341 char *p
= do_malloc (len
, file
, line
);
1342 strncpy (p
, str
, len
);
1347 str_concat_wrap (const char *str1
, const char *str2
, const char *file
, unsigned int line
)
1349 const size_t len
= strlen (str1
) + strlen (str2
) + 1;
1352 p
= str
= do_malloc (len
, file
, line
);
1353 strncpy (p
, str1
, strlen (str1
));
1355 strncpy (p
, str2
, strlen (str2
));
1363 get_bytes_size (unsigned long bytes
, struct bytes_size
*bytes_size
)
1365 const char *unit
, units
[] = { '0', 'K', 'M', 'G', '\0' };
1366 unsigned long size
= bytes
;
1370 while (size
>= 1024 && *(unit
+ 1))
1375 bytes_size
->size
= (unsigned int)size
;
1376 bytes_size
->unit
= *unit
;
1381 get_file_type (mode_t mode
)
1385 else if (S_ISDIR (mode
))
1387 else if (S_ISCHR (mode
))
1388 return "character device";
1389 else if (S_ISBLK (mode
))
1390 return "block device";
1391 else if (S_ISFIFO (mode
))
1392 return "named pipe";
1393 else if (S_ISLNK (mode
))
1394 return "symbolic link";
1395 else if (S_ISSOCK (mode
))
1402 has_color_name (const char *str
, const char *name
)
1406 assert (strlen (str
));
1407 assert (strlen (name
));
1409 if (!(*str
== *name
|| *str
== toupper (*name
)))
1411 else if (*(name
+ 1) != '\0'
1412 && !((p
= strstr (str
+ 1, name
+ 1)) && p
== str
+ 1))
1419 open_file (const char *file
, const char *mode
)
1424 stream
= fopen (file
, mode
);
1426 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
1431 #define DO_VFPRINTF(fmt) \
1433 fprintf (stderr, "%s: ", program_name); \
1434 va_start (ap, fmt); \
1435 vfprintf (stderr, fmt, ap); \
1437 fprintf (stderr, "\n"); \
1440 vfprintf_diag (const char *fmt
, ...)
1446 vfprintf_fail (const char *fmt
, ...)
1449 exit (EXIT_FAILURE
);
1453 stack_var (void ***list
, unsigned int *stacked
, unsigned int index
, void *ptr
)
1455 /* nothing to stack */
1459 *list
= xmalloc (sizeof (void *));
1463 for (i
= 0; i
< *stacked
; i
++)
1467 return; /* reused */
1469 *list
= xrealloc (*list
, (*stacked
+ 1) * sizeof (void *));
1471 (*list
)[index
] = ptr
;
1476 release_var (void **list
, unsigned int stacked
, void **ptr
)
1479 /* nothing to release */
1482 for (i
= 0; i
< stacked
; i
++)
1483 if (list
[i
] == *ptr
)