]>
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
;
257 static void print_tstamp (FILE *);
259 static void process_opts (int, char **);
260 static void process_opt_attr (const char *);
261 static void write_attr (const struct attr
*, unsigned int *);
262 static void print_hint (void);
263 static void print_help (void);
264 static void print_version (void);
265 static void cleanup (void);
266 static void free_color_names (struct color_name
**);
267 static void process_args (unsigned int, char **, char *, const struct color
**, const char **, FILE **);
268 static void process_file_arg (const char *, const char **, FILE **);
269 static void skip_path_colors (const char *, const char *, const struct stat
*);
270 static void gather_color_names (const char *, char *, struct color_name
**);
271 static void read_print_stream (const char *, const struct color
**, const char *, FILE *);
272 static void merge_print_line (const char *, const char *, FILE *);
273 static void complete_part_line (const char *, char **, FILE *);
274 static bool get_next_char (char *, const char **, FILE *, bool *);
275 static void save_char (char, char **, size_t *, size_t *);
276 static void find_color_entries (struct color_name
**, const struct color
**);
277 static void find_color_entry (const struct color_name
*, unsigned int, const struct color
**);
278 static void print_line (const char *, const struct color
**, const char * const, unsigned int, bool);
279 static void print_clean (const char *);
280 static bool is_esc (const char *);
281 static const char *get_end_of_esc (const char *);
282 static const char *get_end_of_text (const char *);
283 static void print_text (const char *, size_t);
284 static bool gather_esc_offsets (const char *, const char **, const char **);
285 static bool validate_esc_clean_all (const char **);
286 static bool validate_esc_clean (int, unsigned int, unsigned int *, const char **, bool *);
287 static bool is_reset (int, unsigned int, const char **);
288 static bool is_attr (int, unsigned int, unsigned int, const char **);
289 static bool is_fg_color (int, const char **);
290 static bool is_bg_color (int, unsigned int, const char **);
292 static void *malloc_wrap (size_t);
293 static void *calloc_wrap (size_t, size_t);
294 static void *realloc_wrap (void *, size_t);
296 static void *malloc_wrap_debug (size_t, const char *, unsigned int);
297 static void *calloc_wrap_debug (size_t, size_t, const char *, unsigned int);
298 static void *realloc_wrap_debug (void *, size_t, const char *, unsigned int);
300 static void free_wrap (void **);
301 static char *strdup_wrap (const char *, const char *, unsigned int);
302 static char *str_concat_wrap (const char *, const char *, const char *, unsigned int);
303 static bool get_bytes_size (unsigned long, struct bytes_size
*);
304 static char *get_file_type (mode_t
);
305 static bool has_color_name (const char *, const char *);
306 static FILE *open_file (const char *, const char *);
307 static void vfprintf_diag (const char *, ...);
308 static void vfprintf_fail (const char *, ...);
309 static void stack_var (void ***, unsigned int *, unsigned int, void *);
310 static void release_var (void **, unsigned int, void **);
315 main (int argc
, char **argv
)
317 unsigned int arg_cnt
;
319 const struct color
*colors
[2] = {
320 NULL
, /* foreground */
321 NULL
, /* background */
324 const char *file
= NULL
;
326 program_name
= argv
[0];
329 setvbuf (stdout
, NULL
, _IOLBF
, 0);
332 log
= open_file (DEBUG_FILE
, "w");
338 process_opts (argc
, argv
);
340 arg_cnt
= argc
- optind
;
342 if (clean
|| clean_all
)
344 if (clean
&& clean_all
)
345 vfprintf_fail (formats
[FMT_GENERIC
], "--clean and --clean-all switch are mutually exclusive");
348 const char *const format
= "%s %s";
349 const char *const message
= "switch cannot be used with more than one file";
351 vfprintf_fail (format
, "--clean", message
);
353 vfprintf_fail (format
, "--clean-all", message
);
358 if (arg_cnt
== 0 || arg_cnt
> 2)
360 vfprintf_diag ("%u arguments provided, expected 1-2 arguments or clean option", arg_cnt
);
366 if (clean
|| clean_all
)
367 process_file_arg (argv
[optind
], &file
, &stream
);
369 process_args (arg_cnt
, &argv
[optind
], &attr
[0], colors
, &file
, &stream
);
370 read_print_stream (&attr
[0], colors
, file
, stream
);
372 RELEASE_VAR (exclude
);
379 print_tstamp (FILE *log
)
390 perror ("localtime");
393 written
= strftime (str
, sizeof (str
), "%Y-%m-%d %H:%M:%S %Z", tm
);
395 vfprintf_fail (formats
[FMT_GENERIC
], "strftime: 0 returned");
397 fprintf (log
, "%s\n", str
);
404 #define PRINT_HELP_EXIT() \
408 #define PRINT_VERSION_EXIT() \
415 process_opts (int argc
, char **argv
)
418 while ((opt
= getopt_long (argc
, argv
, "hV", long_opts
, NULL
)) != -1)
422 case 0: /* long opts */
426 process_opt_attr (optarg
);
434 case OPT_EXCLUDE_RANDOM
: {
437 exclude
= xstrdup (optarg
);
439 for (i
= 1; i
< tables
[GENERIC
].count
- 1; i
++) /* skip color none and default */
441 const struct color
*entry
= &tables
[GENERIC
].entries
[i
];
442 if (streq (exclude
, entry
->name
))
449 vfprintf_fail (formats
[FMT_GENERIC
], "--exclude-random switch must be provided a plain color");
452 case OPT_OMIT_COLOR_EMPTY
:
453 omit_color_empty
= true;
458 PRINT_VERSION_EXIT ();
459 default: /* never reached */
466 PRINT_VERSION_EXIT ();
470 default: /* never reached */
477 process_opt_attr (const char *p
)
479 /* If attributes are added to this "list", also increase MAX_ATTRIBUTE_CHARS! */
480 const struct attr attrs
[] = {
481 { "bold", 1, ATTR_BOLD
},
482 { "underscore", 4, ATTR_UNDERSCORE
},
483 { "blink", 5, ATTR_BLINK
},
484 { "reverse", 7, ATTR_REVERSE
},
485 { "concealed", 8, ATTR_CONCEALED
},
487 unsigned int attr_types
= 0;
493 vfprintf_fail (formats
[FMT_GENERIC
], "--attr switch must be provided a string");
497 if (*p
!= '\0' && *p
!= ',')
498 vfprintf_fail (formats
[FMT_GENERIC
], "--attr switch must have strings separated by ,");
501 bool valid_attr
= false;
503 for (i
= 0; i
< COUNT_OF (attrs
, struct attr
); i
++)
505 const size_t name_len
= strlen (attrs
[i
].name
);
506 if ((size_t)(p
- s
) == name_len
&& strneq (s
, attrs
[i
].name
, name_len
))
508 write_attr (&attrs
[i
], &attr_types
);
515 char *attr_invalid
= xmalloc ((p
- s
) + 1);
516 STACK_VAR (attr_invalid
);
517 strncpy (attr_invalid
, s
, p
- s
);
518 attr_invalid
[p
- s
] = '\0';
519 vfprintf_fail ("--attr switch attribute '%s' is not valid", attr_invalid
);
520 RELEASE_VAR (attr_invalid
); /* never reached */
529 write_attr (const struct attr
*attr_i
, unsigned int *attr_types
)
531 const unsigned int val
= attr_i
->val
;
532 const enum attr_type attr_type
= attr_i
->type
;
533 const char *attr_name
= attr_i
->name
;
535 if (*attr_types
& attr_type
)
536 vfprintf_fail ("--attr switch has attribute '%s' twice or more", attr_name
);
537 snprintf (attr
+ strlen (attr
), 3, "%u;", val
);
538 *attr_types
|= attr_type
;
544 fprintf (stderr
, "Type `%s --help' for help screen.\n", program_name
);
552 const char *short_opt
;
555 const struct opt_data opts_data
[] = {
556 { "attr", NULL
, "=ATTR1,ATTR2,..." },
557 { "exclude-random", NULL
, "=COLOR" },
558 { "help", "h", NULL
},
559 { "version", "V", NULL
},
561 const struct option
*opt
= long_opts
;
564 printf ("Usage: %s (foreground) OR (foreground)%c(background) OR --clean[-all] [-|file]\n\n", program_name
, COLOR_SEP_CHAR
);
565 printf ("\tColors (foreground) (background)\n");
566 for (i
= 0; i
< tables
[FOREGROUND
].count
; i
++)
568 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
569 const char *name
= entry
->name
;
570 const char *code
= entry
->code
;
572 printf ("\t\t{\033[%s#\033[0m} [%c%c]%s%*s%s\n",
573 code
, toupper (*name
), *name
, name
+ 1, 10 - (int)strlen (name
), " ", name
);
575 printf ("\t\t{-} %s%*s%s\n", name
, 13 - (int)strlen (name
), " ", name
);
577 printf ("\t\t{*} [Rr]%s%*s%s [--exclude-random=<foreground color>]\n", "andom", 10 - (int)strlen ("random"), " ", "random");
579 printf ("\n\tFirst character of color name in upper case denotes increased intensity,\n");
580 printf ("\twhereas for lower case colors will be of normal intensity.\n");
582 printf ("\n\tOptions\n");
583 for (; opt
->name
; opt
++)
585 const struct opt_data
*opt_data
= NULL
;
587 for (i
= 0; i
< COUNT_OF (opts_data
, struct opt_data
); i
++)
588 if (streq (opt
->name
, opts_data
[i
].name
))
590 opt_data
= &opts_data
[i
];
595 if (opt_data
->short_opt
)
596 printf ("\t\t-%s, --%s\n", opt_data
->short_opt
, opt
->name
);
598 printf ("\t\t --%s%s\n", opt
->name
, opt_data
->arg
);
601 printf ("\t\t --%s\n", opt
->name
);
610 # include "version.h"
612 const char *const version
= NULL
;
614 const char *version_prefix
, *version_string
;
615 const char *c_flags
, *ld_flags
, *cpp_flags
;
616 const char *const desc_flags_unknown
= "unknown";
617 struct bytes_size bytes_size
;
620 c_flags
= to_str (CFLAGS
);
622 c_flags
= desc_flags_unknown
;
625 ld_flags
= to_str (LDFLAGS
);
627 ld_flags
= desc_flags_unknown
;
630 cpp_flags
= to_str (CPPFLAGS
);
632 cpp_flags
= desc_flags_unknown
;
639 version_prefix
= version
? "" : "v";
640 version_string
= version
? version
: VERSION
;
641 printf ("%s %s%s (compiled at %s, %s)\n", PROGRAM_NAME
, version_prefix
, version_string
, __DATE__
, __TIME__
);
643 printf ("Compiler flags: %s\n", c_flags
);
644 printf ("Linker flags: %s\n", ld_flags
);
645 printf ("Preprocessor flags: %s\n", cpp_flags
);
646 if (get_bytes_size (BUF_SIZE
, &bytes_size
))
648 if (BUF_SIZE
% 1024 == 0)
649 printf ("Buffer size: %u%c\n", bytes_size
.size
, bytes_size
.unit
);
651 printf ("Buffer size: %u%c, %u byte%s\n", bytes_size
.size
, bytes_size
.unit
,
652 BUF_SIZE
% 1024, BUF_SIZE
% 1024 > 1 ? "s" : "");
655 printf ("Buffer size: %lu byte%s\n", (unsigned long)BUF_SIZE
, BUF_SIZE
> 1 ? "s" : "");
656 printf ("Color separator: '%c'\n", COLOR_SEP_CHAR
);
657 printf ("Debugging: %s\n", debug
? "yes" : "no");
663 if (stream
&& fileno (stream
) != STDIN_FILENO
)
673 for (i
= 0; i
< stacked_vars
; i
++)
675 free_null (vars_list
);
680 free_color_names (struct color_name
**color_names
)
683 for (i
= 0; color_names
[i
]; i
++)
685 RELEASE_VAR (color_names
[i
]->name
);
686 RELEASE_VAR (color_names
[i
]->orig
);
687 RELEASE_VAR (color_names
[i
]);
692 process_args (unsigned int arg_cnt
, char **arg_strings
, char *attr
, const struct color
**colors
, const char **file
, FILE **stream
)
697 struct color_name
*color_names
[3] = {
698 NULL
, /* foreground */
699 NULL
, /* background */
700 NULL
, /* sentinel value */
703 const char *color_string
= arg_cnt
>= 1 ? arg_strings
[0] : NULL
;
704 const char *file_string
= arg_cnt
== 2 ? arg_strings
[1] : NULL
;
706 assert (color_string
!= NULL
);
708 if (streq (color_string
, "-"))
711 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen cannot be used as color string");
713 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen must be preceded by color string");
716 ret
= lstat (color_string
, &sb
);
718 /* Ensure that we don't fail if there's a file with one or more
719 color names in its path. */
720 if (ret
== 0) /* success */
721 skip_path_colors (color_string
, file_string
, &sb
);
723 if ((p
= strchr (color_string
, COLOR_SEP_CHAR
)))
725 if (p
== color_string
)
726 vfprintf_fail (formats
[FMT_STRING
], "foreground color missing in string", color_string
);
727 else if (p
== color_string
+ strlen (color_string
) - 1)
728 vfprintf_fail (formats
[FMT_STRING
], "background color missing in string", color_string
);
729 else if (strchr (++p
, COLOR_SEP_CHAR
))
730 vfprintf_fail (formats
[FMT_STRING
], "one color pair allowed only for string", color_string
);
733 gather_color_names (color_string
, attr
, color_names
);
735 assert (color_names
[FOREGROUND
] != NULL
);
737 if (color_names
[BACKGROUND
])
740 const unsigned int color_sets
[2][2] = { { FOREGROUND
, BACKGROUND
}, { BACKGROUND
, FOREGROUND
} };
741 for (i
= 0; i
< 2; i
++)
743 const unsigned int color1
= color_sets
[i
][0];
744 const unsigned int color2
= color_sets
[i
][1];
745 if (CHECK_COLORS_RANDOM (color1
, color2
))
746 vfprintf_fail (formats
[FMT_RANDOM
], tables
[color1
].desc
, color_names
[color1
]->orig
, "cannot be combined with", color_names
[color2
]->orig
);
750 find_color_entries (color_names
, colors
);
751 assert (colors
[FOREGROUND
] != NULL
);
752 free_color_names (color_names
);
754 if (!colors
[FOREGROUND
]->code
&& colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
756 struct color_name color_name
;
757 color_name
.name
= color_name
.orig
= "default";
759 find_color_entry (&color_name
, FOREGROUND
, colors
);
760 assert (colors
[FOREGROUND
]->code
!= NULL
);
763 process_file_arg (file_string
, file
, stream
);
767 process_file_arg (const char *file_string
, const char **file
, FILE **stream
)
771 if (streq (file_string
, "-"))
775 const char *file
= file_string
;
780 ret
= stat (file
, &sb
);
783 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
785 if (!VALID_FILE_TYPE (sb
.st_mode
))
786 vfprintf_fail (formats
[FMT_TYPE
], file
, "unrecognized type", get_file_type (sb
.st_mode
));
788 *stream
= open_file (file
, "r");
798 assert (*stream
!= NULL
);
799 assert (*file
!= NULL
);
803 skip_path_colors (const char *color_string
, const char *file_string
, const struct stat
*sb
)
807 const char *color
= color_string
;
808 const mode_t mode
= sb
->st_mode
;
810 for (c
= 1; c
<= 2 && *color
; c
++)
812 bool matched
= false;
814 for (i
= 0; i
< tables
[GENERIC
].count
; i
++)
816 const struct color
*entry
= &tables
[GENERIC
].entries
[i
];
817 if (has_color_name (color
, entry
->name
))
819 color
+= strlen (entry
->name
);
824 if (!matched
&& has_color_name (color
, "random"))
826 color
+= strlen ("random");
829 if (matched
&& *color
== COLOR_SEP_CHAR
&& *(color
+ 1))
835 have_file
= (*color
!= '\0');
839 const char *file_existing
= color_string
;
841 vfprintf_fail (formats
[FMT_QUOTE
], get_file_type (mode
), file_existing
, "cannot be used as color string");
844 if (VALID_FILE_TYPE (mode
))
845 vfprintf_fail (formats
[FMT_QUOTE
], get_file_type (mode
), file_existing
, "must be preceded by color string");
847 vfprintf_fail (formats
[FMT_QUOTE
], get_file_type (mode
), file_existing
, "is not a valid file type");
853 gather_color_names (const char *color_string
, char *attr
, struct color_name
**color_names
)
856 char *color
, *p
, *str
;
858 str
= xstrdup (color_string
);
861 for (index
= 0, color
= str
; *color
; index
++, color
= p
)
866 if ((sep
= strchr (color
, COLOR_SEP_CHAR
)))
872 p
= color
+ strlen (color
);
875 for (ch
= color
; *ch
; ch
++)
877 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be made of non-alphabetic characters");
879 for (ch
= color
+ 1; *ch
; ch
++)
881 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be in mixed lower/upper case");
883 if (streq (color
, "None"))
884 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be bold");
886 if (isupper (*color
))
891 snprintf (attr
+ strlen (attr
), 3, "1;");
894 vfprintf_fail (formats
[FMT_COLOR
], tables
[BACKGROUND
].desc
, color
, "cannot be bold");
895 default: /* never reached */
900 color_names
[index
] = xcalloc (1, sizeof (struct color_name
));
901 STACK_VAR (color_names
[index
]);
903 color_names
[index
]->orig
= xstrdup (color
);
904 STACK_VAR (color_names
[index
]->orig
);
906 for (ch
= color
; *ch
; ch
++)
909 color_names
[index
]->name
= xstrdup (color
);
910 STACK_VAR (color_names
[index
]->name
);
917 read_print_stream (const char *attr
, const struct color
**colors
, const char *file
, FILE *stream
)
919 char buf
[BUF_SIZE
+ 1];
920 unsigned int flags
= 0;
922 while (!feof (stream
))
927 bytes_read
= fread (buf
, 1, BUF_SIZE
, stream
);
928 if (bytes_read
!= BUF_SIZE
&& ferror (stream
))
929 vfprintf_fail (formats
[FMT_ERROR
], BUF_SIZE
, "read");
930 buf
[bytes_read
] = '\0';
932 while ((eol
= strpbrk (line
, "\n\r")))
934 const bool has_text
= (eol
> line
);
940 if (*(eol
+ 1) == '\n')
943 else if (*eol
== '\n')
945 else /* never reached */
946 vfprintf_fail (formats
[FMT_FILE
], file
, "unrecognized line ending");
947 p
= eol
+ SKIP_LINE_ENDINGS (flags
);
949 print_line (attr
, colors
, line
, flags
,
950 omit_color_empty
? has_text
: true);
956 print_line (attr
, colors
, line
, 0, true);
958 else if (*line
!= '\0')
961 if ((clean
|| clean_all
) && (p
= strrchr (line
, '\033')))
962 merge_print_line (line
, p
, stream
);
964 print_line (attr
, colors
, line
, 0, true);
970 merge_print_line (const char *line
, const char *p
, FILE *stream
)
973 char *merged_esc
= NULL
;
974 const char *esc
= "";
975 const char char_restore
= *p
;
977 complete_part_line (p
+ 1, &buf
, stream
);
981 /* form escape sequence */
982 esc
= merged_esc
= str_concat (p
, buf
);
983 /* shorten partial line accordingly */
988 #ifdef TEST_MERGE_PART_LINE
989 printf ("%s%s", line
, esc
);
991 _exit (EXIT_SUCCESS
);
994 *(char *)p
= char_restore
;
1001 complete_part_line (const char *p
, char **buf
, FILE *stream
)
1003 bool got_next_char
= false, read_from_stream
;
1007 if (get_next_char (&ch
, &p
, stream
, &read_from_stream
))
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 */
1024 while (get_next_char (&ch
, &p
, stream
, &read_from_stream
))
1026 if (isdigit (ch
) || ch
== ';')
1028 if (read_from_stream
)
1029 save_char (ch
, buf
, &i
, &size
);
1031 else /* got next character */
1033 got_next_char
= true;
1042 if (read_from_stream
)
1043 save_char (ch
, buf
, &i
, &size
);
1047 if (read_from_stream
)
1048 ungetc ((int)ch
, stream
);
1049 return; /* cancel */
1053 return; /* cancel */
1057 get_next_char (char *ch
, const char **p
, FILE *stream
, bool *read_from_stream
)
1062 if ((c
= fgetc (stream
)) != EOF
)
1065 *read_from_stream
= true;
1070 *read_from_stream
= false;
1078 *read_from_stream
= false;
1084 save_char (char ch
, char **buf
, size_t *i
, size_t *size
)
1088 *size
= ALLOC_COMPLETE_PART_LINE
;
1089 *buf
= xmalloc (*size
);
1091 /* +1: effective occupied size of buffer */
1092 else if ((*i
+ 1) == *size
)
1095 *buf
= xrealloc (*buf
, *size
);
1098 (*buf
)[*i
+ 1] = '\0';
1103 find_color_entries (struct color_name
**color_names
, const struct color
**colors
)
1109 gettimeofday (&tv
, NULL
);
1110 srand (tv
.tv_usec
* tv
.tv_sec
);
1112 for (index
= 0; color_names
[index
]; index
++)
1114 const char *color_name
= color_names
[index
]->name
;
1116 const unsigned int count
= tables
[index
].count
;
1117 const struct color
*const color_entries
= tables
[index
].entries
;
1119 if (streq (color_name
, "random"))
1125 i
= rand() % (count
- 2) + 1; /* omit color none and default */
1129 /* --exclude-random */
1130 if (exclude
&& streq (exclude
, color_entries
[i
].name
))
1132 else if (color_names
[BACKGROUND
] && streq (color_names
[BACKGROUND
]->name
, color_entries
[i
].name
))
1136 if (streq (colors
[FOREGROUND
]->name
, color_entries
[i
].name
))
1139 default: /* never reached */
1142 } while (excludable
);
1143 colors
[index
] = (struct color
*)&color_entries
[i
];
1146 find_color_entry (color_names
[index
], index
, colors
);
1151 find_color_entry (const struct color_name
*color_name
, unsigned int index
, const struct color
**colors
)
1156 const unsigned int count
= tables
[index
].count
;
1157 const struct color
*const color_entries
= tables
[index
].entries
;
1159 for (i
= 0; i
< count
; i
++)
1160 if (streq (color_name
->name
, color_entries
[i
].name
))
1162 colors
[index
] = (struct color
*)&color_entries
[i
];
1167 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color_name
->orig
, "not recognized");
1171 print_line (const char *attr
, const struct color
**colors
, const char *const line
, unsigned int flags
, bool emit_colors
)
1174 if (clean
|| clean_all
)
1176 /* skip for --omit-color-empty? */
1177 else if (emit_colors
)
1179 /* Foreground color code is guaranteed to be set when background color code is present. */
1180 if (colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
1181 printf ("\033[%s", colors
[BACKGROUND
]->code
);
1182 if (colors
[FOREGROUND
]->code
)
1183 printf ("\033[%s%s%s\033[0m", attr
, colors
[FOREGROUND
]->code
, line
);
1185 printf (formats
[FMT_GENERIC
], line
);
1194 print_clean (const char *line
)
1196 const char *p
= line
;
1199 p
= get_end_of_esc (p
);
1203 const char *text_start
= p
;
1204 const char *text_end
= get_end_of_text (p
);
1205 print_text (text_start
, text_end
- text_start
);
1206 p
= get_end_of_esc (text_end
);
1211 is_esc (const char *p
)
1213 return gather_esc_offsets (p
, NULL
, NULL
);
1217 get_end_of_esc (const char *p
)
1220 const char *end
= NULL
;
1221 while ((esc
= strchr (p
, '\033')))
1223 if (gather_esc_offsets (esc
, NULL
, &end
))
1227 return end
? end
+ 1 : p
+ strlen (p
);
1231 get_end_of_text (const char *p
)
1234 const char *start
= NULL
;
1235 while ((esc
= strchr (p
, '\033')))
1237 if (gather_esc_offsets (esc
, &start
, NULL
))
1241 return start
? start
: p
+ strlen (p
);
1245 print_text (const char *p
, size_t len
)
1247 size_t bytes_written
;
1248 bytes_written
= fwrite (p
, 1, len
, stdout
);
1249 if (bytes_written
!= len
)
1250 vfprintf_fail (formats
[FMT_ERROR
], (unsigned long)len
, "written");
1254 gather_esc_offsets (const char *p
, const char **start
, const char **end
)
1257 if (*p
== 27 && *(p
+ 1) == '[')
1260 const char *const begin
= p
;
1263 valid
= validate_esc_clean_all (&p
);
1267 unsigned int prev_iter
, iter
;
1269 prev_iter
= iter
= 0;
1271 check_values
= false;
1276 while (isdigit (*p
))
1280 else /* check range */
1285 const unsigned int digits
= p
- digit
;
1286 for (i
= 0; i
< digits
; i
++)
1290 valid
= validate_esc_clean (value
, iter
, &prev_iter
, &p
, &check_values
);
1292 } while (check_values
);
1307 validate_esc_clean_all (const char **p
)
1309 while (isdigit (**p
) || **p
== ';')
1311 return (**p
== 'm');
1315 validate_esc_clean (int value
, unsigned int iter
, unsigned int *prev_iter
, const char **p
, bool *check_values
)
1317 if (is_reset (value
, iter
, p
))
1319 else if (is_attr (value
, iter
, *prev_iter
, p
))
1322 *check_values
= true;
1324 return false; /* partial escape sequence, need another valid value */
1326 else if (is_fg_color (value
, p
))
1328 else if (is_bg_color (value
, iter
, p
))
1335 is_reset (int value
, unsigned int iter
, const char **p
)
1337 return (value
== 0 && iter
== 1 && **p
== 'm');
1341 is_attr (int value
, unsigned int iter
, unsigned int prev_iter
, const char **p
)
1343 return ((value
> 0 && value
< 10) && (iter
- prev_iter
== 1) && **p
== ';');
1347 is_fg_color (int value
, const char **p
)
1349 return (((value
>= 30 && value
<= 37) || value
== 39) && **p
== 'm');
1353 is_bg_color (int value
, unsigned int iter
, const char **p
)
1355 return (((value
>= 40 && value
<= 47) || value
== 49) && iter
== 1 && **p
== 'm');
1360 malloc_wrap (size_t size
)
1362 void *p
= malloc (size
);
1369 calloc_wrap (size_t nmemb
, size_t size
)
1371 void *p
= calloc (nmemb
, size
);
1378 realloc_wrap (void *ptr
, size_t size
)
1380 void *p
= realloc (ptr
, size
);
1386 static const char *const format_debug
= "%s: %10s %7lu bytes [source file %s, line %5u]\n";
1388 malloc_wrap_debug (size_t size
, const char *file
, unsigned int line
)
1390 void *p
= malloc (size
);
1392 MEM_ALLOC_FAIL_DEBUG (file
, line
);
1393 fprintf (log
, format_debug
, program_name
, "malloc'ed", (unsigned long)size
, file
, line
);
1398 calloc_wrap_debug (size_t nmemb
, size_t size
, const char *file
, unsigned int line
)
1400 void *p
= calloc (nmemb
, size
);
1402 MEM_ALLOC_FAIL_DEBUG (file
, line
);
1403 fprintf (log
, format_debug
, program_name
, "calloc'ed", (unsigned long)(nmemb
* size
), file
, line
);
1408 realloc_wrap_debug (void *ptr
, size_t size
, const char *file
, unsigned int line
)
1410 void *p
= realloc (ptr
, size
);
1412 MEM_ALLOC_FAIL_DEBUG (file
, line
);
1413 fprintf (log
, format_debug
, program_name
, "realloc'ed", (unsigned long)size
, file
, line
);
1419 free_wrap (void **ptr
)
1426 # define do_malloc(len, file, line) malloc_wrap(len)
1428 # define do_malloc(len, file, line) malloc_wrap_debug(len, file, line)
1432 strdup_wrap (const char *str
, const char *file
, unsigned int line
)
1434 const size_t len
= strlen (str
) + 1;
1435 char *p
= do_malloc (len
, file
, line
);
1436 strncpy (p
, str
, len
);
1441 str_concat_wrap (const char *str1
, const char *str2
, const char *file
, unsigned int line
)
1443 const size_t len
= strlen (str1
) + strlen (str2
) + 1;
1446 p
= str
= do_malloc (len
, file
, line
);
1447 strncpy (p
, str1
, strlen (str1
));
1449 strncpy (p
, str2
, strlen (str2
));
1457 get_bytes_size (unsigned long bytes
, struct bytes_size
*bytes_size
)
1459 const char *unit
, units
[] = { '0', 'K', 'M', 'G', '\0' };
1460 unsigned long size
= bytes
;
1464 while (size
>= 1024 && *(unit
+ 1))
1469 bytes_size
->size
= (unsigned int)size
;
1470 bytes_size
->unit
= *unit
;
1475 get_file_type (mode_t mode
)
1479 else if (S_ISDIR (mode
))
1481 else if (S_ISCHR (mode
))
1482 return "character device";
1483 else if (S_ISBLK (mode
))
1484 return "block device";
1485 else if (S_ISFIFO (mode
))
1486 return "named pipe";
1487 else if (S_ISLNK (mode
))
1488 return "symbolic link";
1489 else if (S_ISSOCK (mode
))
1496 has_color_name (const char *str
, const char *name
)
1500 assert (strlen (str
) > 0);
1501 assert (strlen (name
) > 0);
1503 if (!(*str
== *name
|| *str
== toupper (*name
)))
1505 else if (*(name
+ 1) != '\0'
1506 && !((p
= strstr (str
+ 1, name
+ 1)) && p
== str
+ 1))
1513 open_file (const char *file
, const char *mode
)
1518 stream
= fopen (file
, mode
);
1520 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
1525 #define DO_VFPRINTF(fmt) \
1527 fprintf (stderr, "%s: ", program_name); \
1528 va_start (ap, fmt); \
1529 vfprintf (stderr, fmt, ap); \
1531 fprintf (stderr, "\n");
1534 vfprintf_diag (const char *fmt
, ...)
1540 vfprintf_fail (const char *fmt
, ...)
1543 exit (EXIT_FAILURE
);
1547 stack_var (void ***list
, unsigned int *stacked
, unsigned int index
, void *ptr
)
1549 /* nothing to stack */
1553 *list
= xmalloc (sizeof (void *));
1557 for (i
= 0; i
< *stacked
; i
++)
1561 return; /* reused */
1563 *list
= xrealloc (*list
, (*stacked
+ 1) * sizeof (void *));
1565 (*list
)[index
] = ptr
;
1570 release_var (void **list
, unsigned int stacked
, void **ptr
)
1573 /* nothing to release */
1576 for (i
= 0; i
< stacked
; i
++)
1577 if (list
[i
] == *ptr
)