]>
git.refcnt.org Git - colorize.git/blob - colorize.c
c0baf60f01571d94eda0343392a85cb75da12c98
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-2015 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/>.
23 #define _XOPEN_SOURCE 700
24 #define _FILE_OFFSET_BITS 64
34 #include <sys/types.h>
44 #define to_str(arg) str(arg)
46 #define streq(s1, s2) (strcmp (s1, s2) == 0)
49 # define xmalloc(size) malloc_wrap(size)
50 # define xcalloc(nmemb, size) calloc_wrap(nmemb, size)
51 # define xrealloc(ptr, size) realloc_wrap(ptr, size)
52 # define xstrdup(str) strdup_wrap(str, NULL, 0)
53 # define str_concat(str1, str2) str_concat_wrap(str1, str2, NULL, 0)
55 # define xmalloc(size) malloc_wrap_debug(size, __FILE__, __LINE__)
56 # define xcalloc(nmemb, size) calloc_wrap_debug(nmemb, size, __FILE__, __LINE__)
57 # define xrealloc(ptr, size) realloc_wrap_debug(ptr, size, __FILE__, __LINE__)
58 # define xstrdup(str) strdup_wrap(str, __FILE__, __LINE__)
59 # define str_concat(str1, str2) str_concat_wrap(str1, str2, __FILE__, __LINE__)
62 #define free_null(ptr) free_wrap((void **)&ptr)
64 #if defined(BUF_SIZE) && (BUF_SIZE <= 0 || BUF_SIZE > 65536)
68 # define BUF_SIZE 4096
74 #define SKIP_LINE_ENDINGS(flags) (((flags) & CR) && ((flags) & LF) ? 2 : 1)
76 #define VALID_FILE_TYPE(mode) (S_ISREG (mode) || S_ISLNK (mode) || S_ISFIFO (mode))
78 #define STACK_VAR(ptr) do { \
79 stack_var (&vars_list, &stacked_vars, stacked_vars, ptr); \
82 #define RELEASE_VAR(ptr) do { \
83 release_var (vars_list, stacked_vars, (void **)&ptr); \
87 # define MEM_ALLOC_FAIL() do { \
88 fprintf (stderr, "%s: memory allocation failure\n", program_name); \
89 exit (EXIT_FAILURE); \
92 # define MEM_ALLOC_FAIL_DEBUG(file, line) do { \
93 fprintf (stderr, "Memory allocation failure in source file %s, line %u\n", file, line); \
94 exit (EXIT_FAILURE); \
98 #define ABORT_TRACE() \
99 fprintf (stderr, "Aborting in source file %s, line %u\n", __FILE__, __LINE__); \
102 #define CHECK_COLORS_RANDOM(color1, color2) \
103 streq (color_names[color1]->name, "random") \
104 && (streq (color_names[color2]->name, "none") \
105 || streq (color_names[color2]->name, "default")) \
107 #define ALLOC_COMPLETE_PART_LINE 8
109 #define COLOR_SEP_CHAR '/'
111 #define DEBUG_FILE "debug.txt"
113 #define VERSION "0.57"
115 typedef enum { false, true } bool;
122 static struct color_name
*color_names
[3] = { NULL
, NULL
, NULL
};
129 static const struct color fg_colors
[] = {
136 { "magenta", "35m" },
139 { "default", "39m" },
141 static const struct color bg_colors
[] = {
148 { "magenta", "45m" },
151 { "default", "49m" },
169 static const char *formats
[] = {
171 "%s '%s'", /* string */
172 "%s `%s' %s", /* quote */
173 "%s color '%s' %s", /* color */
174 "%s color '%s' %s '%s'", /* random */
175 "less than %lu bytes %s", /* error */
177 "%s: %s: %s", /* type */
180 enum { FOREGROUND
, BACKGROUND
};
182 static const struct {
183 struct color
const *entries
;
187 { fg_colors
, sizeof (fg_colors
) / sizeof (struct color
), "foreground" },
188 { bg_colors
, sizeof (bg_colors
) / sizeof (struct color
), "background" },
196 static unsigned int stacked_vars
;
197 static void **vars_list
;
200 static bool clean_all
;
202 static char *exclude
;
204 static const char *program_name
;
206 static void process_opts (int, char **);
207 static void print_hint (void);
208 static void print_help (void);
209 static void print_version (void);
210 static void cleanup (void);
211 static void free_color_names (struct color_name
**);
212 static void process_args (unsigned int, char **, bool *, const struct color
**, const char **, FILE **);
213 static void process_file_arg (const char *, const char **, FILE **);
214 static void skip_path_colors (const char *, const char *, const struct stat
*);
215 static void gather_color_names (const char *, bool *, struct color_name
**);
216 static void read_print_stream (bool, const struct color
**, const char *, FILE *);
217 static void merge_print_line (bool, const struct color
**, const char *, const char *, FILE *);
218 static void complete_part_line (const char *, char **, FILE *);
219 static bool get_next_char (char *, const char **, FILE *, bool *);
220 static void save_char (char, char **, unsigned long *, size_t *);
221 static void find_color_entries (struct color_name
**, const struct color
**);
222 static void find_color_entry (const struct color_name
*, unsigned int, const struct color
**);
223 static void print_line (bool, const struct color
**, const char * const, unsigned int);
224 static void print_clean (const char *);
225 static bool is_esc (const char *);
226 static const char *get_end_of_esc (const char *);
227 static const char *get_end_of_text (const char *);
228 static void print_text (const char *, size_t);
229 static bool gather_esc_offsets (const char *, const char **, const char **);
230 static bool validate_esc_clean_all (const char **);
231 static bool validate_esc_clean (int, unsigned int, const char **, bool *);
232 static bool is_reset (int, unsigned int, const char **);
233 static bool is_bold (int, unsigned int, const char **);
234 static bool is_fg_color (int, const char **);
235 static bool is_bg_color (int, unsigned int, const char **);
237 static void *malloc_wrap (size_t);
238 static void *calloc_wrap (size_t, size_t);
239 static void *realloc_wrap (void *, size_t);
241 static void *malloc_wrap_debug (size_t, const char *, unsigned int);
242 static void *calloc_wrap_debug (size_t, size_t, const char *, unsigned int);
243 static void *realloc_wrap_debug (void *, size_t, const char *, unsigned int);
245 static void free_wrap (void **);
246 static char *strdup_wrap (const char *, const char *, unsigned int);
247 static char *str_concat_wrap (const char *, const char *, const char *, unsigned int);
248 static bool get_bytes_size (unsigned long, struct bytes_size
*);
249 static char *get_file_type (mode_t
);
250 static bool has_color_name (const char *, const char *);
251 static FILE *open_file (const char *, const char *);
252 static void vfprintf_diag (const char *, ...);
253 static void vfprintf_fail (const char *, ...);
254 static void stack_var (void ***, unsigned int *, unsigned int, void *);
255 static void release_var (void **, unsigned int, void **);
260 main (int argc
, char **argv
)
262 unsigned int arg_cnt
;
266 const struct color
*colors
[2] = {
267 NULL
, /* foreground */
268 NULL
, /* background */
271 const char *file
= NULL
;
273 program_name
= argv
[0];
276 setvbuf (stdout
, NULL
, _IOLBF
, 0);
279 log
= open_file (DEBUG_FILE
, "w");
282 process_opts (argc
, argv
);
284 arg_cnt
= argc
- optind
;
286 if (clean
|| clean_all
)
288 if (clean
&& clean_all
)
289 vfprintf_fail (formats
[FMT_GENERIC
], "--clean and --clean-all switch are mutually exclusive");
292 const char *format
= "%s %s";
293 const char *message
= "switch cannot be used with more than one file";
295 vfprintf_fail (format
, "--clean", message
);
297 vfprintf_fail (format
, "--clean-all", message
);
302 if (arg_cnt
== 0 || arg_cnt
> 2)
304 vfprintf_diag ("%u arguments provided, expected 1-2 arguments or clean option", arg_cnt
);
310 if (clean
|| clean_all
)
311 process_file_arg (argv
[optind
], &file
, &stream
);
313 process_args (arg_cnt
, &argv
[optind
], &bold
, colors
, &file
, &stream
);
314 read_print_stream (bold
, colors
, file
, stream
);
316 RELEASE_VAR (exclude
);
321 #define SET_OPT_TYPE(type) \
330 process_opts (int argc
, char **argv
)
341 struct option long_opts
[] = {
342 { "clean", no_argument
, &opt_type
, OPT_CLEAN
},
343 { "clean-all", no_argument
, &opt_type
, OPT_CLEAN_ALL
},
344 { "exclude-random", required_argument
, &opt_type
, OPT_EXCLUDE_RANDOM
},
345 { "help", no_argument
, &opt_type
, OPT_HELP
},
346 { "version", no_argument
, &opt_type
, OPT_VERSION
},
347 { NULL
, 0, NULL
, 0 },
350 while ((opt
= getopt_long (argc
, argv
, "hV", long_opts
, NULL
)) != -1)
355 case 0: /* long opts */
364 case OPT_EXCLUDE_RANDOM
: {
367 exclude
= xstrdup (optarg
);
369 for (i
= 1; i
< tables
[FOREGROUND
].count
- 1; i
++) /* skip color none and default */
371 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
372 if (streq (exclude
, entry
->name
))
379 vfprintf_fail (formats
[FMT_GENERIC
], "--exclude-random switch must be provided a plain color");
388 default: /* never reached */
393 SET_OPT_TYPE (OPT_HELP
);
395 SET_OPT_TYPE (OPT_VERSION
);
399 default: /* never reached */
408 fprintf (stderr
, "Type `%s --help' for help screen.\n", program_name
);
416 printf ("Usage: %s (foreground) OR (foreground)%c(background) OR --clean[-all] [-|file]\n\n", program_name
, COLOR_SEP_CHAR
);
417 printf ("\tColors (foreground) (background)\n");
418 for (i
= 0; i
< tables
[FOREGROUND
].count
; i
++)
420 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
421 const char *name
= entry
->name
;
422 const char *code
= entry
->code
;
424 printf ("\t\t{\033[%s#\033[0m} [%c%c]%s%*s%s\n",
425 code
, toupper (*name
), *name
, name
+ 1, 10 - (int)strlen (name
), " ", name
);
427 printf ("\t\t{-} %s%*s%s\n", name
, 13 - (int)strlen (name
), " ", name
);
429 printf ("\t\t{*} [Rr]%s%*s%s [--exclude-random=<foreground color>]\n", "andom", 10 - (int)strlen ("random"), " ", "random");
431 printf ("\n\tFirst character of color name in upper case denotes increased intensity,\n");
432 printf ("\twhereas for lower case colors will be of normal intensity.\n");
434 printf ("\n\tOptions\n");
435 printf ("\t\t --clean\n");
436 printf ("\t\t --clean-all\n");
437 printf ("\t\t --exclude-random\n");
438 printf ("\t\t-h, --help\n");
439 printf ("\t\t-V, --version\n\n");
446 # include "version.h"
448 const char *version
= NULL
;
450 const char *version_prefix
, *version_string
;
452 struct bytes_size bytes_size
;
455 c_flags
= to_str (CFLAGS
);
464 version_prefix
= version
? "" : "v";
465 version_string
= version
? version
: VERSION
;
466 printf ("colorize %s%s (compiled at %s, %s)\n", version_prefix
, version_string
, __DATE__
, __TIME__
);
468 printf ("Compiler flags: %s\n", c_flags
);
469 if (get_bytes_size (BUF_SIZE
, &bytes_size
))
471 if (BUF_SIZE
% 1024 == 0)
472 printf ("Buffer size: %u%c\n", bytes_size
.size
, bytes_size
.unit
);
474 printf ("Buffer size: %u%c, %u byte%s\n", bytes_size
.size
, bytes_size
.unit
,
475 BUF_SIZE
% 1024, BUF_SIZE
% 1024 > 1 ? "s" : "");
478 printf ("Buffer size: %lu byte%s\n", (unsigned long)BUF_SIZE
, BUF_SIZE
> 1 ? "s" : "");
479 printf ("Debugging: %s\n", debug
? "yes" : "no");
485 free_color_names (color_names
);
487 if (stream
&& fileno (stream
) != STDIN_FILENO
)
497 for (i
= 0; i
< stacked_vars
; i
++)
499 free_null (vars_list
);
504 free_color_names (struct color_name
**color_names
)
507 for (i
= 0; color_names
[i
]; i
++)
509 free (color_names
[i
]->name
);
510 free (color_names
[i
]->orig
);
511 free_null (color_names
[i
]);
516 process_args (unsigned int arg_cnt
, char **arg_strings
, bool *bold
, const struct color
**colors
, const char **file
, FILE **stream
)
522 const char *color_string
= arg_cnt
>= 1 ? arg_strings
[0] : NULL
;
523 const char *file_string
= arg_cnt
== 2 ? arg_strings
[1] : NULL
;
525 assert (color_string
);
527 if (streq (color_string
, "-"))
530 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen cannot be used as color string");
532 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen must be preceeded by color string");
535 ret
= lstat (color_string
, &sb
);
537 /* Ensure that we don't fail if there's a file with one or more
538 color names in its path. */
539 if (ret
== 0) /* success */
540 skip_path_colors (color_string
, file_string
, &sb
);
542 if ((p
= strchr (color_string
, COLOR_SEP_CHAR
)))
544 if (p
== color_string
)
545 vfprintf_fail (formats
[FMT_STRING
], "foreground color missing in string", color_string
);
546 else if (p
== color_string
+ strlen (color_string
) - 1)
547 vfprintf_fail (formats
[FMT_STRING
], "background color missing in string", color_string
);
548 else if (strchr (++p
, COLOR_SEP_CHAR
))
549 vfprintf_fail (formats
[FMT_STRING
], "one color pair allowed only for string", color_string
);
552 gather_color_names (color_string
, bold
, color_names
);
554 assert (color_names
[FOREGROUND
]);
556 if (color_names
[BACKGROUND
])
559 const unsigned int color_sets
[2][2] = { { FOREGROUND
, BACKGROUND
}, { BACKGROUND
, FOREGROUND
} };
560 for (i
= 0; i
< 2; i
++)
562 const unsigned int color1
= color_sets
[i
][0];
563 const unsigned int color2
= color_sets
[i
][1];
564 if (CHECK_COLORS_RANDOM (color1
, color2
))
565 vfprintf_fail (formats
[FMT_RANDOM
], tables
[color1
].desc
, color_names
[color1
]->orig
, "cannot be combined with", color_names
[color2
]->orig
);
569 find_color_entries (color_names
, colors
);
570 free_color_names (color_names
);
572 if (!colors
[FOREGROUND
]->code
&& colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
574 struct color_name color_name
;
575 color_name
.name
= color_name
.orig
= "default";
577 find_color_entry (&color_name
, FOREGROUND
, colors
);
580 process_file_arg (file_string
, file
, stream
);
584 process_file_arg (const char *file_string
, const char **file
, FILE **stream
)
588 if (streq (file_string
, "-"))
592 const char *file
= file_string
;
597 ret
= stat (file
, &sb
);
600 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
602 if (!VALID_FILE_TYPE (sb
.st_mode
))
603 vfprintf_fail (formats
[FMT_TYPE
], file
, "unrecognized type", get_file_type (sb
.st_mode
));
605 *stream
= open_file (file
, "r");
620 skip_path_colors (const char *color_string
, const char *file_string
, const struct stat
*sb
)
624 const char *color
= color_string
;
625 const mode_t mode
= sb
->st_mode
;
627 for (c
= 1; c
<= 2 && *color
; c
++)
629 bool matched
= false;
631 for (i
= 0; i
< tables
[FOREGROUND
].count
; i
++)
633 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
634 if (has_color_name (color
, entry
->name
))
636 color
+= strlen (entry
->name
);
641 if (!matched
&& has_color_name (color
, "random"))
643 color
+= strlen ("random");
646 if (matched
&& *color
== COLOR_SEP_CHAR
&& *(color
+ 1))
652 have_file
= (*color
!= '\0');
656 const char *file_exists
= color_string
;
658 vfprintf_fail (formats
[FMT_QUOTE
], get_file_type (mode
), file_exists
, "cannot be used as color string");
661 if (VALID_FILE_TYPE (mode
))
662 vfprintf_fail (formats
[FMT_QUOTE
], get_file_type (mode
), file_exists
, "must be preceeded by color string");
664 vfprintf_fail (formats
[FMT_QUOTE
], get_file_type (mode
), file_exists
, "is not a valid file type");
670 gather_color_names (const char *color_string
, bool *bold
, struct color_name
**color_names
)
673 char *color
, *p
, *str
;
675 str
= xstrdup (color_string
);
678 for (index
= 0, color
= str
; *color
; index
++, color
= p
)
683 if ((sep
= strchr (color
, COLOR_SEP_CHAR
)))
689 p
= color
+ strlen (color
);
692 for (ch
= color
; *ch
; ch
++)
694 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be made of non-alphabetic characters");
696 for (ch
= color
+ 1; *ch
; ch
++)
698 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be in mixed lower/upper case");
700 if (streq (color
, "None"))
701 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be bold");
703 if (isupper (*color
))
711 vfprintf_fail (formats
[FMT_COLOR
], tables
[BACKGROUND
].desc
, color
, "cannot be bold");
712 default: /* never reached */
717 color_names
[index
] = xcalloc (1, sizeof (struct color_name
));
719 color_names
[index
]->orig
= xstrdup (color
);
721 for (ch
= color
; *ch
; ch
++)
724 color_names
[index
]->name
= xstrdup (color
);
731 read_print_stream (bool bold
, const struct color
**colors
, const char *file
, FILE *stream
)
733 char buf
[BUF_SIZE
+ 1];
734 unsigned int flags
= 0;
736 while (!feof (stream
))
741 memset (buf
, '\0', BUF_SIZE
+ 1);
742 bytes_read
= fread (buf
, 1, BUF_SIZE
, stream
);
743 if (bytes_read
!= BUF_SIZE
&& ferror (stream
))
744 vfprintf_fail (formats
[FMT_ERROR
], BUF_SIZE
, "read");
746 while ((eol
= strpbrk (line
, "\n\r")))
753 if (*(eol
+ 1) == '\n')
756 else if (*eol
== '\n')
759 vfprintf_fail (formats
[FMT_FILE
], file
, "unrecognized line ending");
760 p
= eol
+ SKIP_LINE_ENDINGS (flags
);
762 print_line (bold
, colors
, line
, flags
);
768 print_line (bold
, colors
, line
, 0);
770 else if (*line
!= '\0')
773 if ((clean
|| clean_all
) && (p
= strrchr (line
, '\033')))
774 merge_print_line (bold
, colors
, line
, p
, stream
);
776 print_line (bold
, colors
, line
, 0);
782 merge_print_line (bool bold
, const struct color
**colors
, const char *line
, const char *p
, FILE *stream
)
785 char *merged_part_line
= NULL
;
786 const char *part_line
;
788 complete_part_line (p
+ 1, &buf
, stream
);
791 part_line
= merged_part_line
= str_concat (line
, buf
);
796 #ifdef TEST_MERGE_PART_LINE
797 printf ("%s", part_line
);
798 free (merged_part_line
);
801 print_line (bold
, colors
, part_line
, 0);
802 free (merged_part_line
);
807 complete_part_line (const char *p
, char **buf
, FILE *stream
)
809 bool got_next_char
= false, read_from_stream
;
814 if (get_next_char (&ch
, &p
, stream
, &read_from_stream
))
818 if (read_from_stream
)
819 save_char (ch
, buf
, &i
, &size
);
823 if (read_from_stream
)
824 ungetc ((int)ch
, stream
);
831 while (get_next_char (&ch
, &p
, stream
, &read_from_stream
))
833 if (isdigit (ch
) || ch
== ';')
835 if (read_from_stream
)
836 save_char (ch
, buf
, &i
, &size
);
838 else /* read next character */
840 got_next_char
= true;
849 if (read_from_stream
)
850 save_char (ch
, buf
, &i
, &size
);
854 if (read_from_stream
)
855 ungetc ((int)ch
, stream
);
864 get_next_char (char *ch
, const char **p
, FILE *stream
, bool *read_from_stream
)
869 if ((c
= fgetc (stream
)) != EOF
)
872 *read_from_stream
= true;
877 *read_from_stream
= false;
885 *read_from_stream
= false;
891 save_char (char ch
, char **buf
, unsigned long *i
, size_t *size
)
895 *size
= ALLOC_COMPLETE_PART_LINE
;
896 *buf
= xmalloc (*size
);
898 /* +1: effective occupied size of buffer */
899 else if ((*i
+ 1) == *size
)
902 *buf
= xrealloc (*buf
, *size
);
905 (*buf
)[*i
+ 1] = '\0';
910 find_color_entries (struct color_name
**color_names
, const struct color
**colors
)
916 gettimeofday (&tv
, NULL
);
917 srand (tv
.tv_usec
* tv
.tv_sec
);
919 for (index
= 0; color_names
[index
]; index
++)
921 const char *color_name
= color_names
[index
]->name
;
923 const unsigned int count
= tables
[index
].count
;
924 const struct color
*const color_entries
= tables
[index
].entries
;
926 if (streq (color_name
, "random"))
932 i
= rand() % (count
- 2) + 1; /* omit color none and default */
936 /* --exclude-random */
937 if (exclude
&& streq (exclude
, color_entries
[i
].name
))
939 else if (color_names
[BACKGROUND
] && streq (color_names
[BACKGROUND
]->name
, color_entries
[i
].name
))
943 if (streq (colors
[FOREGROUND
]->name
, color_entries
[i
].name
))
946 default: /* never reached */
949 } while (excludable
);
950 colors
[index
] = (struct color
*)&color_entries
[i
];
953 find_color_entry (color_names
[index
], index
, colors
);
958 find_color_entry (const struct color_name
*color_name
, unsigned int index
, const struct color
**colors
)
963 const unsigned int count
= tables
[index
].count
;
964 const struct color
*const color_entries
= tables
[index
].entries
;
966 for (i
= 0; i
< count
; i
++)
967 if (streq (color_name
->name
, color_entries
[i
].name
))
969 colors
[index
] = (struct color
*)&color_entries
[i
];
974 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color_name
->orig
, "not recognized");
978 print_line (bool bold
, const struct color
**colors
, const char *const line
, unsigned int flags
)
981 if (clean
|| clean_all
)
985 /* Foreground color code is guaranteed to be set when background color code is present. */
986 if (colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
987 printf ("\033[%s", colors
[BACKGROUND
]->code
);
988 if (colors
[FOREGROUND
]->code
)
989 printf ("\033[%s%s%s\033[0m", bold
? "1;" : "", colors
[FOREGROUND
]->code
, line
);
991 printf (formats
[FMT_GENERIC
], line
);
1000 print_clean (const char *line
)
1002 const char *p
= line
;
1005 p
= get_end_of_esc (p
);
1009 const char *text_start
= p
;
1010 const char *text_end
= get_end_of_text (p
);
1011 print_text (text_start
, text_end
- text_start
);
1012 p
= get_end_of_esc (text_end
);
1017 is_esc (const char *p
)
1019 return gather_esc_offsets (p
, NULL
, NULL
);
1023 get_end_of_esc (const char *p
)
1026 const char *end
= NULL
;
1027 while ((esc
= strchr (p
, '\033')))
1029 if (gather_esc_offsets (esc
, NULL
, &end
))
1033 return end
? end
+ 1 : p
+ strlen (p
);
1037 get_end_of_text (const char *p
)
1040 const char *start
= NULL
;
1041 while ((esc
= strchr (p
, '\033')))
1043 if (gather_esc_offsets (esc
, &start
, NULL
))
1047 return start
? start
: p
+ strlen (p
);
1051 print_text (const char *p
, size_t len
)
1053 size_t bytes_written
;
1054 bytes_written
= fwrite (p
, 1, len
, stdout
);
1055 if (bytes_written
!= len
)
1056 vfprintf_fail (formats
[FMT_ERROR
], (unsigned long)len
, "written");
1060 gather_esc_offsets (const char *p
, const char **start
, const char **end
)
1063 if (*p
== 27 && *(p
+ 1) == '[')
1066 const char *begin
= p
;
1069 valid
= validate_esc_clean_all (&p
);
1073 unsigned int iter
= 0;
1076 check_values
= false;
1081 while (isdigit (*p
))
1085 else /* check range */
1090 const unsigned int digits
= p
- digit
;
1091 for (i
= 0; i
< digits
; i
++)
1095 valid
= validate_esc_clean (value
, iter
, &p
, &check_values
);
1097 } while (check_values
);
1112 validate_esc_clean_all (const char **p
)
1114 while (isdigit (**p
) || **p
== ';')
1116 return (**p
== 'm');
1120 validate_esc_clean (int value
, unsigned int iter
, const char **p
, bool *check_values
)
1122 if (is_reset (value
, iter
, p
))
1124 else if (is_bold (value
, iter
, p
))
1127 *check_values
= true;
1128 return false; /* partial escape sequence, need another valid value */
1130 else if (is_fg_color (value
, p
))
1132 else if (is_bg_color (value
, iter
, p
))
1139 is_reset (int value
, unsigned int iter
, const char **p
)
1141 return (value
== 0 && iter
== 1 && **p
== 'm');
1145 is_bold (int value
, unsigned int iter
, const char **p
)
1147 return (value
== 1 && iter
== 1 && **p
== ';');
1151 is_fg_color (int value
, const char **p
)
1153 return (((value
>= 30 && value
<= 37) || value
== 39) && **p
== 'm');
1157 is_bg_color (int value
, unsigned int iter
, const char **p
)
1159 return (((value
>= 40 && value
<= 47) || value
== 49) && iter
== 1 && **p
== 'm');
1164 malloc_wrap (size_t size
)
1166 void *p
= malloc (size
);
1173 calloc_wrap (size_t nmemb
, size_t size
)
1175 void *p
= calloc (nmemb
, size
);
1182 realloc_wrap (void *ptr
, size_t size
)
1184 void *p
= realloc (ptr
, size
);
1191 malloc_wrap_debug (size_t size
, const char *file
, unsigned int line
)
1193 void *p
= malloc (size
);
1195 MEM_ALLOC_FAIL_DEBUG (file
, line
);
1196 fprintf (log
, "%s: malloc'ed %lu bytes [source file %s, line %u]\n", program_name
, (unsigned long)size
, file
, line
);
1201 calloc_wrap_debug (size_t nmemb
, size_t size
, const char *file
, unsigned int line
)
1203 void *p
= calloc (nmemb
, size
);
1205 MEM_ALLOC_FAIL_DEBUG (file
, line
);
1206 fprintf (log
, "%s: calloc'ed %lu bytes [source file %s, line %u]\n", program_name
, (unsigned long)(nmemb
* size
), file
, line
);
1211 realloc_wrap_debug (void *ptr
, size_t size
, const char *file
, unsigned int line
)
1213 void *p
= realloc (ptr
, size
);
1215 MEM_ALLOC_FAIL_DEBUG (file
, line
);
1216 fprintf (log
, "%s: realloc'ed %lu bytes [source file %s, line %u]\n", program_name
, (unsigned long)size
, file
, line
);
1222 free_wrap (void **ptr
)
1229 # define do_malloc(len, file, line) malloc_wrap(len)
1231 # define do_malloc(len, file, line) malloc_wrap_debug(len, file, line)
1235 strdup_wrap (const char *str
, const char *file
, unsigned int line
)
1237 const size_t len
= strlen (str
) + 1;
1238 char *p
= do_malloc (len
, file
, line
);
1239 strncpy (p
, str
, len
);
1244 str_concat_wrap (const char *str1
, const char *str2
, const char *file
, unsigned int line
)
1246 const size_t len
= strlen (str1
) + strlen (str2
) + 1;
1249 p
= str
= do_malloc (len
, file
, line
);
1250 strncpy (p
, str1
, strlen (str1
));
1252 strncpy (p
, str2
, strlen (str2
));
1260 get_bytes_size (unsigned long bytes
, struct bytes_size
*bytes_size
)
1262 const char *unit
, units
[] = { '0', 'K', 'M', 'G', '\0' };
1263 unsigned long size
= bytes
;
1267 while (size
>= 1024 && *(unit
+ 1))
1272 bytes_size
->size
= (unsigned int)size
;
1273 bytes_size
->unit
= *unit
;
1278 get_file_type (mode_t mode
)
1282 else if (S_ISDIR (mode
))
1284 else if (S_ISCHR (mode
))
1285 return "character device";
1286 else if (S_ISBLK (mode
))
1287 return "block device";
1288 else if (S_ISFIFO (mode
))
1289 return "named pipe";
1290 else if (S_ISLNK (mode
))
1291 return "symbolic link";
1292 else if (S_ISSOCK (mode
))
1299 has_color_name (const char *str
, const char *name
)
1303 assert (strlen (str
));
1304 assert (strlen (name
));
1306 if (!(*str
== *name
|| *str
== toupper (*name
)))
1308 else if (*(name
+ 1) != '\0'
1309 && !((p
= strstr (str
+ 1, name
+ 1)) && p
== str
+ 1))
1316 open_file (const char *file
, const char *mode
)
1321 stream
= fopen (file
, mode
);
1323 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
1328 #define DO_VFPRINTF(fmt) \
1330 fprintf (stderr, "%s: ", program_name); \
1331 va_start (ap, fmt); \
1332 vfprintf (stderr, fmt, ap); \
1334 fprintf (stderr, "\n"); \
1337 vfprintf_diag (const char *fmt
, ...)
1343 vfprintf_fail (const char *fmt
, ...)
1346 exit (EXIT_FAILURE
);
1350 stack_var (void ***list
, unsigned int *stacked
, unsigned int index
, void *ptr
)
1352 /* nothing to stack */
1356 *list
= xmalloc (sizeof (void *));
1360 for (i
= 0; i
< *stacked
; i
++)
1364 return; /* reused */
1366 *list
= xrealloc (*list
, (*stacked
+ 1) * sizeof (void *));
1368 (*list
)[index
] = ptr
;
1373 release_var (void **list
, unsigned int stacked
, void **ptr
)
1376 /* nothing to release */
1379 for (i
= 0; i
< stacked
; i
++)
1380 if (list
[i
] == *ptr
)