]>
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-2018 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 COUNT_OF(obj, type) (sizeof (obj) / sizeof (type))
78 #define SKIP_LINE_ENDINGS(flags) ((flags) == (CR|LF) ? 2 : 1)
80 #define VALID_FILE_TYPE(mode) (S_ISREG (mode) || S_ISLNK (mode) || S_ISFIFO (mode))
82 #define STACK_VAR(ptr) do { \
83 stack_var (&vars_list, &stacked_vars, stacked_vars, ptr); \
86 #define RELEASE_VAR(ptr) do { \
87 release_var (vars_list, stacked_vars, (void **)&ptr); \
91 # define MEM_ALLOC_FAIL() do { \
92 fprintf (stderr, "%s: memory allocation failure\n", program_name); \
93 exit (EXIT_FAILURE); \
96 # define MEM_ALLOC_FAIL_DEBUG(file, line) do { \
97 fprintf (stderr, "Memory allocation failure in source file %s, line %u\n", file, line); \
98 exit (EXIT_FAILURE); \
102 #define ABORT_TRACE() \
103 fprintf (stderr, "Aborting in source file %s, line %u\n", __FILE__, __LINE__); \
106 #define CHECK_COLORS_RANDOM(color1, color2) \
107 streq (color_names[color1]->name, "random") \
108 && (streq (color_names[color2]->name, "none") \
109 || streq (color_names[color2]->name, "default"))
111 #define ALLOC_COMPLETE_PART_LINE 8
113 #if defined(COLOR_SEP_CHAR_COLON)
114 # define COLOR_SEP_CHAR ':'
115 #elif defined(COLOR_SEP_CHAR_SLASH)
116 # define COLOR_SEP_CHAR '/'
118 # define COLOR_SEP_CHAR '/'
122 # define DEBUG_FILE "debug.txt"
125 #define MAX_ATTRIBUTE_CHARS (6 * 2)
127 #define PROGRAM_NAME "colorize"
129 #define VERSION "0.64"
131 typedef enum { false, true } bool;
143 static const struct color fg_colors
[] = {
150 { "magenta", "35m" },
153 { "default", "39m" },
155 static const struct color bg_colors
[] = {
162 { "magenta", "45m" },
165 { "default", "49m" },
183 static const char *formats
[] = {
185 "%s '%s'", /* string */
186 "%s `%s' %s", /* quote */
187 "%s color '%s' %s", /* color */
188 "%s color '%s' %s '%s'", /* random */
189 "less than %lu bytes %s", /* error */
191 "%s: %s: %s", /* type */
194 enum { GENERIC
, FOREGROUND
= 0, BACKGROUND
};
196 static const struct {
197 const struct color
*entries
;
201 { fg_colors
, COUNT_OF (fg_colors
, struct color
), "foreground" },
202 { bg_colors
, COUNT_OF (bg_colors
, struct color
), "background" },
210 OPT_OMIT_COLOR_EMPTY
,
215 static const struct option long_opts
[] = {
216 { "attr", required_argument
, &opt_type
, OPT_ATTR
},
217 { "clean", no_argument
, &opt_type
, OPT_CLEAN
},
218 { "clean-all", no_argument
, &opt_type
, OPT_CLEAN_ALL
},
219 { "exclude-random", required_argument
, &opt_type
, OPT_EXCLUDE_RANDOM
},
220 { "omit-color-empty", no_argument
, &opt_type
, OPT_OMIT_COLOR_EMPTY
},
221 { "help", no_argument
, &opt_type
, OPT_HELP
},
222 { "version", no_argument
, &opt_type
, OPT_VERSION
},
223 { NULL
, 0, NULL
, 0 },
228 ATTR_UNDERSCORE
= 0x02,
231 ATTR_CONCEALED
= 0x10
244 static unsigned int stacked_vars
;
245 static void **vars_list
;
248 static bool clean_all
;
249 static bool omit_color_empty
;
251 static char attr
[MAX_ATTRIBUTE_CHARS
+ 1];
252 static char *exclude
;
254 static const char *program_name
;
256 static void process_opts (int, char **);
257 static void process_opt_attr (const char *);
258 static void write_attr (const struct attr
*, unsigned int *);
259 static void print_hint (void);
260 static void print_help (void);
261 static void print_version (void);
262 static void cleanup (void);
263 static void free_color_names (struct color_name
**);
264 static void process_args (unsigned int, char **, char *, const struct color
**, const char **, FILE **);
265 static void process_file_arg (const char *, const char **, FILE **);
266 static void skip_path_colors (const char *, const char *, const struct stat
*);
267 static void gather_color_names (const char *, char *, struct color_name
**);
268 static void read_print_stream (const char *, const struct color
**, const char *, FILE *);
269 static void merge_print_line (const char *, const char *, FILE *);
270 static void complete_part_line (const char *, char **, FILE *);
271 static bool get_next_char (char *, const char **, FILE *, bool *);
272 static void save_char (char, char **, size_t *, size_t *);
273 static void find_color_entries (struct color_name
**, const struct color
**);
274 static void find_color_entry (const struct color_name
*, unsigned int, const struct color
**);
275 static void print_line (const char *, const struct color
**, const char * const, unsigned int, bool);
276 static void print_clean (const char *);
277 static bool is_esc (const char *);
278 static const char *get_end_of_esc (const char *);
279 static const char *get_end_of_text (const char *);
280 static void print_text (const char *, size_t);
281 static bool gather_esc_offsets (const char *, const char **, const char **);
282 static bool validate_esc_clean_all (const char **);
283 static bool validate_esc_clean (int, unsigned int, unsigned int *, const char **, bool *);
284 static bool is_reset (int, unsigned int, const char **);
285 static bool is_attr (int, unsigned int, unsigned int, const char **);
286 static bool is_fg_color (int, const char **);
287 static bool is_bg_color (int, unsigned int, const char **);
289 static void *malloc_wrap (size_t);
290 static void *calloc_wrap (size_t, size_t);
291 static void *realloc_wrap (void *, size_t);
293 static void *malloc_wrap_debug (size_t, const char *, unsigned int);
294 static void *calloc_wrap_debug (size_t, size_t, const char *, unsigned int);
295 static void *realloc_wrap_debug (void *, size_t, const char *, unsigned int);
297 static void free_wrap (void **);
298 static char *strdup_wrap (const char *, const char *, unsigned int);
299 static char *str_concat_wrap (const char *, const char *, const char *, unsigned int);
300 static bool get_bytes_size (unsigned long, struct bytes_size
*);
301 static char *get_file_type (mode_t
);
302 static bool has_color_name (const char *, const char *);
303 static FILE *open_file (const char *, const char *);
304 static void vfprintf_diag (const char *, ...);
305 static void vfprintf_fail (const char *, ...);
306 static void stack_var (void ***, unsigned int *, unsigned int, void *);
307 static void release_var (void **, unsigned int, void **);
312 main (int argc
, char **argv
)
314 unsigned int arg_cnt
;
316 const struct color
*colors
[2] = {
317 NULL
, /* foreground */
318 NULL
, /* background */
321 const char *file
= NULL
;
323 program_name
= argv
[0];
326 setvbuf (stdout
, NULL
, _IOLBF
, 0);
329 log
= open_file (DEBUG_FILE
, "w");
334 process_opts (argc
, argv
);
336 arg_cnt
= argc
- optind
;
338 if (clean
|| clean_all
)
340 if (clean
&& clean_all
)
341 vfprintf_fail (formats
[FMT_GENERIC
], "--clean and --clean-all switch are mutually exclusive");
344 const char *const format
= "%s %s";
345 const char *const message
= "switch cannot be used with more than one file";
347 vfprintf_fail (format
, "--clean", message
);
349 vfprintf_fail (format
, "--clean-all", message
);
354 if (arg_cnt
== 0 || arg_cnt
> 2)
356 vfprintf_diag ("%u arguments provided, expected 1-2 arguments or clean option", arg_cnt
);
362 if (clean
|| clean_all
)
363 process_file_arg (argv
[optind
], &file
, &stream
);
365 process_args (arg_cnt
, &argv
[optind
], &attr
[0], colors
, &file
, &stream
);
366 read_print_stream (&attr
[0], colors
, file
, stream
);
368 RELEASE_VAR (exclude
);
373 #define PRINT_HELP_EXIT() \
377 #define PRINT_VERSION_EXIT() \
384 process_opts (int argc
, char **argv
)
387 while ((opt
= getopt_long (argc
, argv
, "hV", long_opts
, NULL
)) != -1)
391 case 0: /* long opts */
395 process_opt_attr (optarg
);
403 case OPT_EXCLUDE_RANDOM
: {
406 exclude
= xstrdup (optarg
);
408 for (i
= 1; i
< tables
[GENERIC
].count
- 1; i
++) /* skip color none and default */
410 const struct color
*entry
= &tables
[GENERIC
].entries
[i
];
411 if (streq (exclude
, entry
->name
))
418 vfprintf_fail (formats
[FMT_GENERIC
], "--exclude-random switch must be provided a plain color");
421 case OPT_OMIT_COLOR_EMPTY
:
422 omit_color_empty
= true;
427 PRINT_VERSION_EXIT ();
428 default: /* never reached */
435 PRINT_VERSION_EXIT ();
439 default: /* never reached */
446 process_opt_attr (const char *p
)
448 /* If attributes are added to this "list", also increase MAX_ATTRIBUTE_CHARS! */
449 const struct attr attrs
[] = {
450 { "bold", 1, ATTR_BOLD
},
451 { "underscore", 4, ATTR_UNDERSCORE
},
452 { "blink", 5, ATTR_BLINK
},
453 { "reverse", 7, ATTR_REVERSE
},
454 { "concealed", 8, ATTR_CONCEALED
},
456 unsigned int attr_types
= 0;
462 vfprintf_fail (formats
[FMT_GENERIC
], "--attr switch must be provided a string");
466 if (*p
!= '\0' && *p
!= ',')
467 vfprintf_fail (formats
[FMT_GENERIC
], "--attr switch must have strings separated by ,");
470 bool valid_attr
= false;
472 for (i
= 0; i
< COUNT_OF (attrs
, struct attr
); i
++)
474 const size_t name_len
= strlen (attrs
[i
].name
);
475 if ((size_t)(p
- s
) == name_len
&& strneq (s
, attrs
[i
].name
, name_len
))
477 write_attr (&attrs
[i
], &attr_types
);
484 char *attr_invalid
= xmalloc ((p
- s
) + 1);
485 STACK_VAR (attr_invalid
);
486 strncpy (attr_invalid
, s
, p
- s
);
487 attr_invalid
[p
- s
] = '\0';
488 vfprintf_fail ("--attr switch attribute '%s' is not valid", attr_invalid
);
489 RELEASE_VAR (attr_invalid
); /* never reached */
498 write_attr (const struct attr
*attr_i
, unsigned int *attr_types
)
500 const unsigned int val
= attr_i
->val
;
501 const enum attr_type attr_type
= attr_i
->type
;
502 const char *attr_name
= attr_i
->name
;
504 if (*attr_types
& attr_type
)
505 vfprintf_fail ("--attr switch has attribute '%s' twice or more", attr_name
);
506 snprintf (attr
+ strlen (attr
), 3, "%u;", val
);
507 *attr_types
|= attr_type
;
513 fprintf (stderr
, "Type `%s --help' for help screen.\n", program_name
);
521 const char *short_opt
;
524 const struct opt_data opts_data
[] = {
525 { "attr", NULL
, "=ATTR1,ATTR2,..." },
526 { "exclude-random", NULL
, "=COLOR" },
527 { "help", "h", NULL
},
528 { "version", "V", NULL
},
530 const struct option
*opt
= long_opts
;
533 printf ("Usage: %s (foreground) OR (foreground)%c(background) OR --clean[-all] [-|file]\n\n", program_name
, COLOR_SEP_CHAR
);
534 printf ("\tColors (foreground) (background)\n");
535 for (i
= 0; i
< tables
[FOREGROUND
].count
; i
++)
537 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
538 const char *name
= entry
->name
;
539 const char *code
= entry
->code
;
541 printf ("\t\t{\033[%s#\033[0m} [%c%c]%s%*s%s\n",
542 code
, toupper (*name
), *name
, name
+ 1, 10 - (int)strlen (name
), " ", name
);
544 printf ("\t\t{-} %s%*s%s\n", name
, 13 - (int)strlen (name
), " ", name
);
546 printf ("\t\t{*} [Rr]%s%*s%s [--exclude-random=<foreground color>]\n", "andom", 10 - (int)strlen ("random"), " ", "random");
548 printf ("\n\tFirst character of color name in upper case denotes increased intensity,\n");
549 printf ("\twhereas for lower case colors will be of normal intensity.\n");
551 printf ("\n\tOptions\n");
552 for (; opt
->name
; opt
++)
554 const struct opt_data
*opt_data
= NULL
;
556 for (i
= 0; i
< COUNT_OF (opts_data
, struct opt_data
); i
++)
557 if (streq (opt
->name
, opts_data
[i
].name
))
559 opt_data
= &opts_data
[i
];
564 if (opt_data
->short_opt
)
565 printf ("\t\t-%s, --%s\n", opt_data
->short_opt
, opt
->name
);
567 printf ("\t\t --%s%s\n", opt
->name
, opt_data
->arg
);
570 printf ("\t\t --%s\n", opt
->name
);
579 # include "version.h"
581 const char *const version
= NULL
;
583 const char *version_prefix
, *version_string
;
584 const char *c_flags
, *ld_flags
, *cpp_flags
;
585 const char *const desc_flags_unknown
= "unknown";
586 struct bytes_size bytes_size
;
589 c_flags
= to_str (CFLAGS
);
591 c_flags
= desc_flags_unknown
;
594 ld_flags
= to_str (LDFLAGS
);
596 ld_flags
= desc_flags_unknown
;
599 cpp_flags
= to_str (CPPFLAGS
);
601 cpp_flags
= desc_flags_unknown
;
608 version_prefix
= version
? "" : "v";
609 version_string
= version
? version
: VERSION
;
610 printf ("%s %s%s (compiled at %s, %s)\n", PROGRAM_NAME
, version_prefix
, version_string
, __DATE__
, __TIME__
);
612 printf ("Compiler flags: %s\n", c_flags
);
613 printf ("Linker flags: %s\n", ld_flags
);
614 printf ("Preprocessor flags: %s\n", cpp_flags
);
615 if (get_bytes_size (BUF_SIZE
, &bytes_size
))
617 if (BUF_SIZE
% 1024 == 0)
618 printf ("Buffer size: %u%c\n", bytes_size
.size
, bytes_size
.unit
);
620 printf ("Buffer size: %u%c, %u byte%s\n", bytes_size
.size
, bytes_size
.unit
,
621 BUF_SIZE
% 1024, BUF_SIZE
% 1024 > 1 ? "s" : "");
624 printf ("Buffer size: %lu byte%s\n", (unsigned long)BUF_SIZE
, BUF_SIZE
> 1 ? "s" : "");
625 printf ("Color separator: '%c'\n", COLOR_SEP_CHAR
);
626 printf ("Debugging: %s\n", debug
? "yes" : "no");
632 if (stream
&& fileno (stream
) != STDIN_FILENO
)
642 for (i
= 0; i
< stacked_vars
; i
++)
644 free_null (vars_list
);
649 free_color_names (struct color_name
**color_names
)
652 for (i
= 0; color_names
[i
]; i
++)
654 RELEASE_VAR (color_names
[i
]->name
);
655 RELEASE_VAR (color_names
[i
]->orig
);
656 RELEASE_VAR (color_names
[i
]);
661 process_args (unsigned int arg_cnt
, char **arg_strings
, char *attr
, const struct color
**colors
, const char **file
, FILE **stream
)
666 struct color_name
*color_names
[3] = {
667 NULL
, /* foreground */
668 NULL
, /* background */
669 NULL
, /* sentinel value */
672 const char *color_string
= arg_cnt
>= 1 ? arg_strings
[0] : NULL
;
673 const char *file_string
= arg_cnt
== 2 ? arg_strings
[1] : NULL
;
675 assert (color_string
!= NULL
);
677 if (streq (color_string
, "-"))
680 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen cannot be used as color string");
682 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen must be preceded by color string");
685 ret
= lstat (color_string
, &sb
);
687 /* Ensure that we don't fail if there's a file with one or more
688 color names in its path. */
689 if (ret
== 0) /* success */
690 skip_path_colors (color_string
, file_string
, &sb
);
692 if ((p
= strchr (color_string
, COLOR_SEP_CHAR
)))
694 if (p
== color_string
)
695 vfprintf_fail (formats
[FMT_STRING
], "foreground color missing in string", color_string
);
696 else if (p
== color_string
+ strlen (color_string
) - 1)
697 vfprintf_fail (formats
[FMT_STRING
], "background color missing in string", color_string
);
698 else if (strchr (++p
, COLOR_SEP_CHAR
))
699 vfprintf_fail (formats
[FMT_STRING
], "one color pair allowed only for string", color_string
);
702 gather_color_names (color_string
, attr
, color_names
);
704 assert (color_names
[FOREGROUND
] != NULL
);
706 if (color_names
[BACKGROUND
])
709 const unsigned int color_sets
[2][2] = { { FOREGROUND
, BACKGROUND
}, { BACKGROUND
, FOREGROUND
} };
710 for (i
= 0; i
< 2; i
++)
712 const unsigned int color1
= color_sets
[i
][0];
713 const unsigned int color2
= color_sets
[i
][1];
714 if (CHECK_COLORS_RANDOM (color1
, color2
))
715 vfprintf_fail (formats
[FMT_RANDOM
], tables
[color1
].desc
, color_names
[color1
]->orig
, "cannot be combined with", color_names
[color2
]->orig
);
719 find_color_entries (color_names
, colors
);
720 assert (colors
[FOREGROUND
] != NULL
);
721 free_color_names (color_names
);
723 if (!colors
[FOREGROUND
]->code
&& colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
725 struct color_name color_name
;
726 color_name
.name
= color_name
.orig
= "default";
728 find_color_entry (&color_name
, FOREGROUND
, colors
);
729 assert (colors
[FOREGROUND
]->code
!= NULL
);
732 process_file_arg (file_string
, file
, stream
);
736 process_file_arg (const char *file_string
, const char **file
, FILE **stream
)
740 if (streq (file_string
, "-"))
744 const char *file
= file_string
;
749 ret
= stat (file
, &sb
);
752 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
754 if (!VALID_FILE_TYPE (sb
.st_mode
))
755 vfprintf_fail (formats
[FMT_TYPE
], file
, "unrecognized type", get_file_type (sb
.st_mode
));
757 *stream
= open_file (file
, "r");
767 assert (*stream
!= NULL
);
768 assert (*file
!= NULL
);
772 skip_path_colors (const char *color_string
, const char *file_string
, const struct stat
*sb
)
776 const char *color
= color_string
;
777 const mode_t mode
= sb
->st_mode
;
779 for (c
= 1; c
<= 2 && *color
; c
++)
781 bool matched
= false;
783 for (i
= 0; i
< tables
[GENERIC
].count
; i
++)
785 const struct color
*entry
= &tables
[GENERIC
].entries
[i
];
786 if (has_color_name (color
, entry
->name
))
788 color
+= strlen (entry
->name
);
793 if (!matched
&& has_color_name (color
, "random"))
795 color
+= strlen ("random");
798 if (matched
&& *color
== COLOR_SEP_CHAR
&& *(color
+ 1))
804 have_file
= (*color
!= '\0');
808 const char *file_existing
= color_string
;
810 vfprintf_fail (formats
[FMT_QUOTE
], get_file_type (mode
), file_existing
, "cannot be used as color string");
813 if (VALID_FILE_TYPE (mode
))
814 vfprintf_fail (formats
[FMT_QUOTE
], get_file_type (mode
), file_existing
, "must be preceded by color string");
816 vfprintf_fail (formats
[FMT_QUOTE
], get_file_type (mode
), file_existing
, "is not a valid file type");
822 gather_color_names (const char *color_string
, char *attr
, struct color_name
**color_names
)
825 char *color
, *p
, *str
;
827 str
= xstrdup (color_string
);
830 for (index
= 0, color
= str
; *color
; index
++, color
= p
)
835 if ((sep
= strchr (color
, COLOR_SEP_CHAR
)))
841 p
= color
+ strlen (color
);
844 for (ch
= color
; *ch
; ch
++)
846 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be made of non-alphabetic characters");
848 for (ch
= color
+ 1; *ch
; ch
++)
850 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be in mixed lower/upper case");
852 if (streq (color
, "None"))
853 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be bold");
855 if (isupper (*color
))
860 snprintf (attr
+ strlen (attr
), 3, "1;");
863 vfprintf_fail (formats
[FMT_COLOR
], tables
[BACKGROUND
].desc
, color
, "cannot be bold");
864 default: /* never reached */
869 color_names
[index
] = xcalloc (1, sizeof (struct color_name
));
870 STACK_VAR (color_names
[index
]);
872 color_names
[index
]->orig
= xstrdup (color
);
873 STACK_VAR (color_names
[index
]->orig
);
875 for (ch
= color
; *ch
; ch
++)
878 color_names
[index
]->name
= xstrdup (color
);
879 STACK_VAR (color_names
[index
]->name
);
886 read_print_stream (const char *attr
, const struct color
**colors
, const char *file
, FILE *stream
)
888 char buf
[BUF_SIZE
+ 1];
889 unsigned int flags
= 0;
891 while (!feof (stream
))
896 bytes_read
= fread (buf
, 1, BUF_SIZE
, stream
);
897 if (bytes_read
!= BUF_SIZE
&& ferror (stream
))
898 vfprintf_fail (formats
[FMT_ERROR
], BUF_SIZE
, "read");
899 buf
[bytes_read
] = '\0';
901 while ((eol
= strpbrk (line
, "\n\r")))
903 const bool has_text
= (eol
> line
);
909 if (*(eol
+ 1) == '\n')
912 else if (*eol
== '\n')
914 else /* never reached */
915 vfprintf_fail (formats
[FMT_FILE
], file
, "unrecognized line ending");
916 p
= eol
+ SKIP_LINE_ENDINGS (flags
);
918 print_line (attr
, colors
, line
, flags
,
919 omit_color_empty
? has_text
: true);
925 print_line (attr
, colors
, line
, 0, true);
927 else if (*line
!= '\0')
930 if ((clean
|| clean_all
) && (p
= strrchr (line
, '\033')))
931 merge_print_line (line
, p
, stream
);
933 print_line (attr
, colors
, line
, 0, true);
939 merge_print_line (const char *line
, const char *p
, FILE *stream
)
942 char *merged_esc
= NULL
;
943 const char *esc
= "";
944 const char char_restore
= *p
;
946 complete_part_line (p
+ 1, &buf
, stream
);
950 /* form escape sequence */
951 esc
= merged_esc
= str_concat (p
, buf
);
952 /* shorten partial line accordingly */
957 #ifdef TEST_MERGE_PART_LINE
958 printf ("%s%s", line
, esc
);
960 _exit (EXIT_SUCCESS
);
963 *(char *)p
= char_restore
;
970 complete_part_line (const char *p
, char **buf
, FILE *stream
)
972 bool got_next_char
= false, read_from_stream
;
976 if (get_next_char (&ch
, &p
, stream
, &read_from_stream
))
980 if (read_from_stream
)
981 save_char (ch
, buf
, &i
, &size
);
985 if (read_from_stream
)
986 ungetc ((int)ch
, stream
);
993 while (get_next_char (&ch
, &p
, stream
, &read_from_stream
))
995 if (isdigit (ch
) || ch
== ';')
997 if (read_from_stream
)
998 save_char (ch
, buf
, &i
, &size
);
1000 else /* got next character */
1002 got_next_char
= true;
1011 if (read_from_stream
)
1012 save_char (ch
, buf
, &i
, &size
);
1016 if (read_from_stream
)
1017 ungetc ((int)ch
, stream
);
1018 return; /* cancel */
1022 return; /* cancel */
1026 get_next_char (char *ch
, const char **p
, FILE *stream
, bool *read_from_stream
)
1031 if ((c
= fgetc (stream
)) != EOF
)
1034 *read_from_stream
= true;
1039 *read_from_stream
= false;
1047 *read_from_stream
= false;
1053 save_char (char ch
, char **buf
, size_t *i
, size_t *size
)
1057 *size
= ALLOC_COMPLETE_PART_LINE
;
1058 *buf
= xmalloc (*size
);
1060 /* +1: effective occupied size of buffer */
1061 else if ((*i
+ 1) == *size
)
1064 *buf
= xrealloc (*buf
, *size
);
1067 (*buf
)[*i
+ 1] = '\0';
1072 find_color_entries (struct color_name
**color_names
, const struct color
**colors
)
1078 gettimeofday (&tv
, NULL
);
1079 srand (tv
.tv_usec
* tv
.tv_sec
);
1081 for (index
= 0; color_names
[index
]; index
++)
1083 const char *color_name
= color_names
[index
]->name
;
1085 const unsigned int count
= tables
[index
].count
;
1086 const struct color
*const color_entries
= tables
[index
].entries
;
1088 if (streq (color_name
, "random"))
1094 i
= rand() % (count
- 2) + 1; /* omit color none and default */
1098 /* --exclude-random */
1099 if (exclude
&& streq (exclude
, color_entries
[i
].name
))
1101 else if (color_names
[BACKGROUND
] && streq (color_names
[BACKGROUND
]->name
, color_entries
[i
].name
))
1105 if (streq (colors
[FOREGROUND
]->name
, color_entries
[i
].name
))
1108 default: /* never reached */
1111 } while (excludable
);
1112 colors
[index
] = (struct color
*)&color_entries
[i
];
1115 find_color_entry (color_names
[index
], index
, colors
);
1120 find_color_entry (const struct color_name
*color_name
, unsigned int index
, const struct color
**colors
)
1125 const unsigned int count
= tables
[index
].count
;
1126 const struct color
*const color_entries
= tables
[index
].entries
;
1128 for (i
= 0; i
< count
; i
++)
1129 if (streq (color_name
->name
, color_entries
[i
].name
))
1131 colors
[index
] = (struct color
*)&color_entries
[i
];
1136 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color_name
->orig
, "not recognized");
1140 print_line (const char *attr
, const struct color
**colors
, const char *const line
, unsigned int flags
, bool emit_colors
)
1143 if (clean
|| clean_all
)
1145 /* skip for --omit-color-empty? */
1146 else if (emit_colors
)
1148 /* Foreground color code is guaranteed to be set when background color code is present. */
1149 if (colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
1150 printf ("\033[%s", colors
[BACKGROUND
]->code
);
1151 if (colors
[FOREGROUND
]->code
)
1152 printf ("\033[%s%s%s\033[0m", attr
, colors
[FOREGROUND
]->code
, line
);
1154 printf (formats
[FMT_GENERIC
], line
);
1163 print_clean (const char *line
)
1165 const char *p
= line
;
1168 p
= get_end_of_esc (p
);
1172 const char *text_start
= p
;
1173 const char *text_end
= get_end_of_text (p
);
1174 print_text (text_start
, text_end
- text_start
);
1175 p
= get_end_of_esc (text_end
);
1180 is_esc (const char *p
)
1182 return gather_esc_offsets (p
, NULL
, NULL
);
1186 get_end_of_esc (const char *p
)
1189 const char *end
= NULL
;
1190 while ((esc
= strchr (p
, '\033')))
1192 if (gather_esc_offsets (esc
, NULL
, &end
))
1196 return end
? end
+ 1 : p
+ strlen (p
);
1200 get_end_of_text (const char *p
)
1203 const char *start
= NULL
;
1204 while ((esc
= strchr (p
, '\033')))
1206 if (gather_esc_offsets (esc
, &start
, NULL
))
1210 return start
? start
: p
+ strlen (p
);
1214 print_text (const char *p
, size_t len
)
1216 size_t bytes_written
;
1217 bytes_written
= fwrite (p
, 1, len
, stdout
);
1218 if (bytes_written
!= len
)
1219 vfprintf_fail (formats
[FMT_ERROR
], (unsigned long)len
, "written");
1223 gather_esc_offsets (const char *p
, const char **start
, const char **end
)
1226 if (*p
== 27 && *(p
+ 1) == '[')
1229 const char *const begin
= p
;
1232 valid
= validate_esc_clean_all (&p
);
1236 unsigned int prev_iter
, iter
;
1238 prev_iter
= iter
= 0;
1240 check_values
= false;
1245 while (isdigit (*p
))
1249 else /* check range */
1254 const unsigned int digits
= p
- digit
;
1255 for (i
= 0; i
< digits
; i
++)
1259 valid
= validate_esc_clean (value
, iter
, &prev_iter
, &p
, &check_values
);
1261 } while (check_values
);
1276 validate_esc_clean_all (const char **p
)
1278 while (isdigit (**p
) || **p
== ';')
1280 return (**p
== 'm');
1284 validate_esc_clean (int value
, unsigned int iter
, unsigned int *prev_iter
, const char **p
, bool *check_values
)
1286 if (is_reset (value
, iter
, p
))
1288 else if (is_attr (value
, iter
, *prev_iter
, p
))
1291 *check_values
= true;
1293 return false; /* partial escape sequence, need another valid value */
1295 else if (is_fg_color (value
, p
))
1297 else if (is_bg_color (value
, iter
, p
))
1304 is_reset (int value
, unsigned int iter
, const char **p
)
1306 return (value
== 0 && iter
== 1 && **p
== 'm');
1310 is_attr (int value
, unsigned int iter
, unsigned int prev_iter
, const char **p
)
1312 return ((value
> 0 && value
< 10) && (iter
- prev_iter
== 1) && **p
== ';');
1316 is_fg_color (int value
, const char **p
)
1318 return (((value
>= 30 && value
<= 37) || value
== 39) && **p
== 'm');
1322 is_bg_color (int value
, unsigned int iter
, const char **p
)
1324 return (((value
>= 40 && value
<= 47) || value
== 49) && iter
== 1 && **p
== 'm');
1329 malloc_wrap (size_t size
)
1331 void *p
= malloc (size
);
1338 calloc_wrap (size_t nmemb
, size_t size
)
1340 void *p
= calloc (nmemb
, size
);
1347 realloc_wrap (void *ptr
, size_t size
)
1349 void *p
= realloc (ptr
, size
);
1356 malloc_wrap_debug (size_t size
, const char *file
, unsigned int line
)
1358 void *p
= malloc (size
);
1360 MEM_ALLOC_FAIL_DEBUG (file
, line
);
1361 fprintf (log
, "%s: malloc'ed %lu bytes [source file %s, line %u]\n", program_name
, (unsigned long)size
, file
, line
);
1366 calloc_wrap_debug (size_t nmemb
, size_t size
, const char *file
, unsigned int line
)
1368 void *p
= calloc (nmemb
, size
);
1370 MEM_ALLOC_FAIL_DEBUG (file
, line
);
1371 fprintf (log
, "%s: calloc'ed %lu bytes [source file %s, line %u]\n", program_name
, (unsigned long)(nmemb
* size
), file
, line
);
1376 realloc_wrap_debug (void *ptr
, size_t size
, const char *file
, unsigned int line
)
1378 void *p
= realloc (ptr
, size
);
1380 MEM_ALLOC_FAIL_DEBUG (file
, line
);
1381 fprintf (log
, "%s: realloc'ed %lu bytes [source file %s, line %u]\n", program_name
, (unsigned long)size
, file
, line
);
1387 free_wrap (void **ptr
)
1394 # define do_malloc(len, file, line) malloc_wrap(len)
1396 # define do_malloc(len, file, line) malloc_wrap_debug(len, file, line)
1400 strdup_wrap (const char *str
, const char *file
, unsigned int line
)
1402 const size_t len
= strlen (str
) + 1;
1403 char *p
= do_malloc (len
, file
, line
);
1404 strncpy (p
, str
, len
);
1409 str_concat_wrap (const char *str1
, const char *str2
, const char *file
, unsigned int line
)
1411 const size_t len
= strlen (str1
) + strlen (str2
) + 1;
1414 p
= str
= do_malloc (len
, file
, line
);
1415 strncpy (p
, str1
, strlen (str1
));
1417 strncpy (p
, str2
, strlen (str2
));
1425 get_bytes_size (unsigned long bytes
, struct bytes_size
*bytes_size
)
1427 const char *unit
, units
[] = { '0', 'K', 'M', 'G', '\0' };
1428 unsigned long size
= bytes
;
1432 while (size
>= 1024 && *(unit
+ 1))
1437 bytes_size
->size
= (unsigned int)size
;
1438 bytes_size
->unit
= *unit
;
1443 get_file_type (mode_t mode
)
1447 else if (S_ISDIR (mode
))
1449 else if (S_ISCHR (mode
))
1450 return "character device";
1451 else if (S_ISBLK (mode
))
1452 return "block device";
1453 else if (S_ISFIFO (mode
))
1454 return "named pipe";
1455 else if (S_ISLNK (mode
))
1456 return "symbolic link";
1457 else if (S_ISSOCK (mode
))
1464 has_color_name (const char *str
, const char *name
)
1468 assert (strlen (str
) > 0);
1469 assert (strlen (name
) > 0);
1471 if (!(*str
== *name
|| *str
== toupper (*name
)))
1473 else if (*(name
+ 1) != '\0'
1474 && !((p
= strstr (str
+ 1, name
+ 1)) && p
== str
+ 1))
1481 open_file (const char *file
, const char *mode
)
1486 stream
= fopen (file
, mode
);
1488 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
1493 #define DO_VFPRINTF(fmt) \
1495 fprintf (stderr, "%s: ", program_name); \
1496 va_start (ap, fmt); \
1497 vfprintf (stderr, fmt, ap); \
1499 fprintf (stderr, "\n");
1502 vfprintf_diag (const char *fmt
, ...)
1508 vfprintf_fail (const char *fmt
, ...)
1511 exit (EXIT_FAILURE
);
1515 stack_var (void ***list
, unsigned int *stacked
, unsigned int index
, void *ptr
)
1517 /* nothing to stack */
1521 *list
= xmalloc (sizeof (void *));
1525 for (i
= 0; i
< *stacked
; i
++)
1529 return; /* reused */
1531 *list
= xrealloc (*list
, (*stacked
+ 1) * sizeof (void *));
1533 (*list
)[index
] = ptr
;
1538 release_var (void **list
, unsigned int stacked
, void **ptr
)
1541 /* nothing to release */
1544 for (i
= 0; i
< stacked
; i
++)
1545 if (list
[i
] == *ptr
)