]>
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-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 #if defined(COLOR_SEP_CHAR_COLON)
110 # define COLOR_SEP_CHAR ':'
111 #elif defined(COLOR_SEP_CHAR_SLASH)
112 # define COLOR_SEP_CHAR '/'
114 # define COLOR_SEP_CHAR '/'
117 #define DEBUG_FILE "debug.txt"
119 #define VERSION "0.57"
121 typedef enum { false, true } bool;
128 static struct color_name
*color_names
[3] = { NULL
, NULL
, NULL
};
135 static const struct color fg_colors
[] = {
142 { "magenta", "35m" },
145 { "default", "39m" },
147 static const struct color bg_colors
[] = {
154 { "magenta", "45m" },
157 { "default", "49m" },
175 static const char *formats
[] = {
177 "%s '%s'", /* string */
178 "%s `%s' %s", /* quote */
179 "%s color '%s' %s", /* color */
180 "%s color '%s' %s '%s'", /* random */
181 "less than %lu bytes %s", /* error */
183 "%s: %s: %s", /* type */
186 enum { FOREGROUND
, BACKGROUND
};
188 static const struct {
189 struct color
const *entries
;
193 { fg_colors
, sizeof (fg_colors
) / sizeof (struct color
), "foreground" },
194 { bg_colors
, sizeof (bg_colors
) / sizeof (struct color
), "background" },
202 static unsigned int stacked_vars
;
203 static void **vars_list
;
206 static bool clean_all
;
208 static char *exclude
;
210 static const char *program_name
;
212 static void process_opts (int, char **);
213 static void print_hint (void);
214 static void print_help (void);
215 static void print_version (void);
216 static void cleanup (void);
217 static void free_color_names (struct color_name
**);
218 static void process_args (unsigned int, char **, bool *, const struct color
**, const char **, FILE **);
219 static void process_file_arg (const char *, const char **, FILE **);
220 static void skip_path_colors (const char *, const char *, const struct stat
*);
221 static void gather_color_names (const char *, bool *, struct color_name
**);
222 static void read_print_stream (bool, const struct color
**, const char *, FILE *);
223 static void merge_print_line (const char *, const char *, FILE *);
224 static void complete_part_line (const char *, char **, FILE *);
225 static bool get_next_char (char *, const char **, FILE *, bool *);
226 static void save_char (char, char **, size_t *, size_t *);
227 static void find_color_entries (struct color_name
**, const struct color
**);
228 static void find_color_entry (const struct color_name
*, unsigned int, const struct color
**);
229 static void print_line (bool, const struct color
**, const char * const, unsigned int);
230 static void print_clean (const char *);
231 static bool is_esc (const char *);
232 static const char *get_end_of_esc (const char *);
233 static const char *get_end_of_text (const char *);
234 static void print_text (const char *, size_t);
235 static bool gather_esc_offsets (const char *, const char **, const char **);
236 static bool validate_esc_clean_all (const char **);
237 static bool validate_esc_clean (int, unsigned int, const char **, bool *);
238 static bool is_reset (int, unsigned int, const char **);
239 static bool is_bold (int, unsigned int, const char **);
240 static bool is_fg_color (int, const char **);
241 static bool is_bg_color (int, unsigned int, const char **);
243 static void *malloc_wrap (size_t);
244 static void *calloc_wrap (size_t, size_t);
245 static void *realloc_wrap (void *, size_t);
247 static void *malloc_wrap_debug (size_t, const char *, unsigned int);
248 static void *calloc_wrap_debug (size_t, size_t, const char *, unsigned int);
249 static void *realloc_wrap_debug (void *, size_t, const char *, unsigned int);
251 static void free_wrap (void **);
252 static char *strdup_wrap (const char *, const char *, unsigned int);
253 static char *str_concat_wrap (const char *, const char *, const char *, unsigned int);
254 static bool get_bytes_size (unsigned long, struct bytes_size
*);
255 static char *get_file_type (mode_t
);
256 static bool has_color_name (const char *, const char *);
257 static FILE *open_file (const char *, const char *);
258 static void vfprintf_diag (const char *, ...);
259 static void vfprintf_fail (const char *, ...);
260 static void stack_var (void ***, unsigned int *, unsigned int, void *);
261 static void release_var (void **, unsigned int, void **);
266 main (int argc
, char **argv
)
268 unsigned int arg_cnt
;
272 const struct color
*colors
[2] = {
273 NULL
, /* foreground */
274 NULL
, /* background */
277 const char *file
= NULL
;
279 program_name
= argv
[0];
282 setvbuf (stdout
, NULL
, _IOLBF
, 0);
285 log
= open_file (DEBUG_FILE
, "w");
288 process_opts (argc
, argv
);
290 arg_cnt
= argc
- optind
;
292 if (clean
|| clean_all
)
294 if (clean
&& clean_all
)
295 vfprintf_fail (formats
[FMT_GENERIC
], "--clean and --clean-all switch are mutually exclusive");
298 const char *format
= "%s %s";
299 const char *message
= "switch cannot be used with more than one file";
301 vfprintf_fail (format
, "--clean", message
);
303 vfprintf_fail (format
, "--clean-all", message
);
308 if (arg_cnt
== 0 || arg_cnt
> 2)
310 vfprintf_diag ("%u arguments provided, expected 1-2 arguments or clean option", arg_cnt
);
316 if (clean
|| clean_all
)
317 process_file_arg (argv
[optind
], &file
, &stream
);
319 process_args (arg_cnt
, &argv
[optind
], &bold
, colors
, &file
, &stream
);
320 read_print_stream (bold
, colors
, file
, stream
);
322 RELEASE_VAR (exclude
);
327 #define SET_OPT_TYPE(type) \
336 process_opts (int argc
, char **argv
)
347 struct option long_opts
[] = {
348 { "clean", no_argument
, &opt_type
, OPT_CLEAN
},
349 { "clean-all", no_argument
, &opt_type
, OPT_CLEAN_ALL
},
350 { "exclude-random", required_argument
, &opt_type
, OPT_EXCLUDE_RANDOM
},
351 { "help", no_argument
, &opt_type
, OPT_HELP
},
352 { "version", no_argument
, &opt_type
, OPT_VERSION
},
353 { NULL
, 0, NULL
, 0 },
356 while ((opt
= getopt_long (argc
, argv
, "hV", long_opts
, NULL
)) != -1)
361 case 0: /* long opts */
370 case OPT_EXCLUDE_RANDOM
: {
373 exclude
= xstrdup (optarg
);
375 for (i
= 1; i
< tables
[FOREGROUND
].count
- 1; i
++) /* skip color none and default */
377 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
378 if (streq (exclude
, entry
->name
))
385 vfprintf_fail (formats
[FMT_GENERIC
], "--exclude-random switch must be provided a plain color");
394 default: /* never reached */
399 SET_OPT_TYPE (OPT_HELP
);
401 SET_OPT_TYPE (OPT_VERSION
);
405 default: /* never reached */
414 fprintf (stderr
, "Type `%s --help' for help screen.\n", program_name
);
422 printf ("Usage: %s (foreground) OR (foreground)%c(background) OR --clean[-all] [-|file]\n\n", program_name
, COLOR_SEP_CHAR
);
423 printf ("\tColors (foreground) (background)\n");
424 for (i
= 0; i
< tables
[FOREGROUND
].count
; i
++)
426 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
427 const char *name
= entry
->name
;
428 const char *code
= entry
->code
;
430 printf ("\t\t{\033[%s#\033[0m} [%c%c]%s%*s%s\n",
431 code
, toupper (*name
), *name
, name
+ 1, 10 - (int)strlen (name
), " ", name
);
433 printf ("\t\t{-} %s%*s%s\n", name
, 13 - (int)strlen (name
), " ", name
);
435 printf ("\t\t{*} [Rr]%s%*s%s [--exclude-random=<foreground color>]\n", "andom", 10 - (int)strlen ("random"), " ", "random");
437 printf ("\n\tFirst character of color name in upper case denotes increased intensity,\n");
438 printf ("\twhereas for lower case colors will be of normal intensity.\n");
440 printf ("\n\tOptions\n");
441 printf ("\t\t --clean\n");
442 printf ("\t\t --clean-all\n");
443 printf ("\t\t --exclude-random\n");
444 printf ("\t\t-h, --help\n");
445 printf ("\t\t-V, --version\n\n");
452 # include "version.h"
454 const char *version
= NULL
;
456 const char *version_prefix
, *version_string
;
458 struct bytes_size bytes_size
;
461 c_flags
= to_str (CFLAGS
);
470 version_prefix
= version
? "" : "v";
471 version_string
= version
? version
: VERSION
;
472 printf ("colorize %s%s (compiled at %s, %s)\n", version_prefix
, version_string
, __DATE__
, __TIME__
);
474 printf ("Compiler flags: %s\n", c_flags
);
475 if (get_bytes_size (BUF_SIZE
, &bytes_size
))
477 if (BUF_SIZE
% 1024 == 0)
478 printf ("Buffer size: %u%c\n", bytes_size
.size
, bytes_size
.unit
);
480 printf ("Buffer size: %u%c, %u byte%s\n", bytes_size
.size
, bytes_size
.unit
,
481 BUF_SIZE
% 1024, BUF_SIZE
% 1024 > 1 ? "s" : "");
484 printf ("Buffer size: %lu byte%s\n", (unsigned long)BUF_SIZE
, BUF_SIZE
> 1 ? "s" : "");
485 printf ("Debugging: %s\n", debug
? "yes" : "no");
491 free_color_names (color_names
);
493 if (stream
&& fileno (stream
) != STDIN_FILENO
)
503 for (i
= 0; i
< stacked_vars
; i
++)
505 free_null (vars_list
);
510 free_color_names (struct color_name
**color_names
)
513 for (i
= 0; color_names
[i
]; i
++)
515 free (color_names
[i
]->name
);
516 free (color_names
[i
]->orig
);
517 free_null (color_names
[i
]);
522 process_args (unsigned int arg_cnt
, char **arg_strings
, bool *bold
, const struct color
**colors
, const char **file
, FILE **stream
)
528 const char *color_string
= arg_cnt
>= 1 ? arg_strings
[0] : NULL
;
529 const char *file_string
= arg_cnt
== 2 ? arg_strings
[1] : NULL
;
531 assert (color_string
);
533 if (streq (color_string
, "-"))
536 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen cannot be used as color string");
538 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen must be preceeded by color string");
541 ret
= lstat (color_string
, &sb
);
543 /* Ensure that we don't fail if there's a file with one or more
544 color names in its path. */
545 if (ret
== 0) /* success */
546 skip_path_colors (color_string
, file_string
, &sb
);
548 if ((p
= strchr (color_string
, COLOR_SEP_CHAR
)))
550 if (p
== color_string
)
551 vfprintf_fail (formats
[FMT_STRING
], "foreground color missing in string", color_string
);
552 else if (p
== color_string
+ strlen (color_string
) - 1)
553 vfprintf_fail (formats
[FMT_STRING
], "background color missing in string", color_string
);
554 else if (strchr (++p
, COLOR_SEP_CHAR
))
555 vfprintf_fail (formats
[FMT_STRING
], "one color pair allowed only for string", color_string
);
558 gather_color_names (color_string
, bold
, color_names
);
560 assert (color_names
[FOREGROUND
]);
562 if (color_names
[BACKGROUND
])
565 const unsigned int color_sets
[2][2] = { { FOREGROUND
, BACKGROUND
}, { BACKGROUND
, FOREGROUND
} };
566 for (i
= 0; i
< 2; i
++)
568 const unsigned int color1
= color_sets
[i
][0];
569 const unsigned int color2
= color_sets
[i
][1];
570 if (CHECK_COLORS_RANDOM (color1
, color2
))
571 vfprintf_fail (formats
[FMT_RANDOM
], tables
[color1
].desc
, color_names
[color1
]->orig
, "cannot be combined with", color_names
[color2
]->orig
);
575 find_color_entries (color_names
, colors
);
576 free_color_names (color_names
);
578 if (!colors
[FOREGROUND
]->code
&& colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
580 struct color_name color_name
;
581 color_name
.name
= color_name
.orig
= "default";
583 find_color_entry (&color_name
, FOREGROUND
, colors
);
586 process_file_arg (file_string
, file
, stream
);
590 process_file_arg (const char *file_string
, const char **file
, FILE **stream
)
594 if (streq (file_string
, "-"))
598 const char *file
= file_string
;
603 ret
= stat (file
, &sb
);
606 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
608 if (!VALID_FILE_TYPE (sb
.st_mode
))
609 vfprintf_fail (formats
[FMT_TYPE
], file
, "unrecognized type", get_file_type (sb
.st_mode
));
611 *stream
= open_file (file
, "r");
626 skip_path_colors (const char *color_string
, const char *file_string
, const struct stat
*sb
)
630 const char *color
= color_string
;
631 const mode_t mode
= sb
->st_mode
;
633 for (c
= 1; c
<= 2 && *color
; c
++)
635 bool matched
= false;
637 for (i
= 0; i
< tables
[FOREGROUND
].count
; i
++)
639 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
640 if (has_color_name (color
, entry
->name
))
642 color
+= strlen (entry
->name
);
647 if (!matched
&& has_color_name (color
, "random"))
649 color
+= strlen ("random");
652 if (matched
&& *color
== COLOR_SEP_CHAR
&& *(color
+ 1))
658 have_file
= (*color
!= '\0');
662 const char *file_exists
= color_string
;
664 vfprintf_fail (formats
[FMT_QUOTE
], get_file_type (mode
), file_exists
, "cannot be used as color string");
667 if (VALID_FILE_TYPE (mode
))
668 vfprintf_fail (formats
[FMT_QUOTE
], get_file_type (mode
), file_exists
, "must be preceeded by color string");
670 vfprintf_fail (formats
[FMT_QUOTE
], get_file_type (mode
), file_exists
, "is not a valid file type");
676 gather_color_names (const char *color_string
, bool *bold
, struct color_name
**color_names
)
679 char *color
, *p
, *str
;
681 str
= xstrdup (color_string
);
684 for (index
= 0, color
= str
; *color
; index
++, color
= p
)
689 if ((sep
= strchr (color
, COLOR_SEP_CHAR
)))
695 p
= color
+ strlen (color
);
698 for (ch
= color
; *ch
; ch
++)
700 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be made of non-alphabetic characters");
702 for (ch
= color
+ 1; *ch
; ch
++)
704 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be in mixed lower/upper case");
706 if (streq (color
, "None"))
707 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be bold");
709 if (isupper (*color
))
717 vfprintf_fail (formats
[FMT_COLOR
], tables
[BACKGROUND
].desc
, color
, "cannot be bold");
718 default: /* never reached */
723 color_names
[index
] = xcalloc (1, sizeof (struct color_name
));
725 color_names
[index
]->orig
= xstrdup (color
);
727 for (ch
= color
; *ch
; ch
++)
730 color_names
[index
]->name
= xstrdup (color
);
737 read_print_stream (bool bold
, const struct color
**colors
, const char *file
, FILE *stream
)
739 char buf
[BUF_SIZE
+ 1];
740 unsigned int flags
= 0;
742 while (!feof (stream
))
747 memset (buf
, '\0', BUF_SIZE
+ 1);
748 bytes_read
= fread (buf
, 1, BUF_SIZE
, stream
);
749 if (bytes_read
!= BUF_SIZE
&& ferror (stream
))
750 vfprintf_fail (formats
[FMT_ERROR
], BUF_SIZE
, "read");
752 while ((eol
= strpbrk (line
, "\n\r")))
759 if (*(eol
+ 1) == '\n')
762 else if (*eol
== '\n')
765 vfprintf_fail (formats
[FMT_FILE
], file
, "unrecognized line ending");
766 p
= eol
+ SKIP_LINE_ENDINGS (flags
);
768 print_line (bold
, colors
, line
, flags
);
774 print_line (bold
, colors
, line
, 0);
776 else if (*line
!= '\0')
779 if ((clean
|| clean_all
) && (p
= strrchr (line
, '\033')))
780 merge_print_line (line
, p
, stream
);
782 print_line (bold
, colors
, line
, 0);
788 merge_print_line (const char *line
, const char *p
, FILE *stream
)
791 char *merged_esc
= NULL
;
792 const char *esc
= "";
793 const char char_restore
= *p
;
795 complete_part_line (p
+ 1, &buf
, stream
);
799 /* form escape sequence */
800 esc
= merged_esc
= str_concat (p
, buf
);
801 /* shorten partial line accordingly */
806 #ifdef TEST_MERGE_PART_LINE
807 printf ("%s%s", line
, esc
);
809 _exit (EXIT_SUCCESS
);
812 *(char *)p
= char_restore
;
819 complete_part_line (const char *p
, char **buf
, FILE *stream
)
821 bool got_next_char
= false, read_from_stream
;
825 if (get_next_char (&ch
, &p
, stream
, &read_from_stream
))
829 if (read_from_stream
)
830 save_char (ch
, buf
, &i
, &size
);
834 if (read_from_stream
)
835 ungetc ((int)ch
, stream
);
842 while (get_next_char (&ch
, &p
, stream
, &read_from_stream
))
844 if (isdigit (ch
) || ch
== ';')
846 if (read_from_stream
)
847 save_char (ch
, buf
, &i
, &size
);
849 else /* read next character */
851 got_next_char
= true;
860 if (read_from_stream
)
861 save_char (ch
, buf
, &i
, &size
);
865 if (read_from_stream
)
866 ungetc ((int)ch
, stream
);
875 get_next_char (char *ch
, const char **p
, FILE *stream
, bool *read_from_stream
)
880 if ((c
= fgetc (stream
)) != EOF
)
883 *read_from_stream
= true;
888 *read_from_stream
= false;
896 *read_from_stream
= false;
902 save_char (char ch
, char **buf
, size_t *i
, size_t *size
)
906 *size
= ALLOC_COMPLETE_PART_LINE
;
907 *buf
= xmalloc (*size
);
909 /* +1: effective occupied size of buffer */
910 else if ((*i
+ 1) == *size
)
913 *buf
= xrealloc (*buf
, *size
);
916 (*buf
)[*i
+ 1] = '\0';
921 find_color_entries (struct color_name
**color_names
, const struct color
**colors
)
927 gettimeofday (&tv
, NULL
);
928 srand (tv
.tv_usec
* tv
.tv_sec
);
930 for (index
= 0; color_names
[index
]; index
++)
932 const char *color_name
= color_names
[index
]->name
;
934 const unsigned int count
= tables
[index
].count
;
935 const struct color
*const color_entries
= tables
[index
].entries
;
937 if (streq (color_name
, "random"))
943 i
= rand() % (count
- 2) + 1; /* omit color none and default */
947 /* --exclude-random */
948 if (exclude
&& streq (exclude
, color_entries
[i
].name
))
950 else if (color_names
[BACKGROUND
] && streq (color_names
[BACKGROUND
]->name
, color_entries
[i
].name
))
954 if (streq (colors
[FOREGROUND
]->name
, color_entries
[i
].name
))
957 default: /* never reached */
960 } while (excludable
);
961 colors
[index
] = (struct color
*)&color_entries
[i
];
964 find_color_entry (color_names
[index
], index
, colors
);
969 find_color_entry (const struct color_name
*color_name
, unsigned int index
, const struct color
**colors
)
974 const unsigned int count
= tables
[index
].count
;
975 const struct color
*const color_entries
= tables
[index
].entries
;
977 for (i
= 0; i
< count
; i
++)
978 if (streq (color_name
->name
, color_entries
[i
].name
))
980 colors
[index
] = (struct color
*)&color_entries
[i
];
985 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color_name
->orig
, "not recognized");
989 print_line (bool bold
, const struct color
**colors
, const char *const line
, unsigned int flags
)
992 if (clean
|| clean_all
)
996 /* Foreground color code is guaranteed to be set when background color code is present. */
997 if (colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
998 printf ("\033[%s", colors
[BACKGROUND
]->code
);
999 if (colors
[FOREGROUND
]->code
)
1000 printf ("\033[%s%s%s\033[0m", bold
? "1;" : "", colors
[FOREGROUND
]->code
, line
);
1002 printf (formats
[FMT_GENERIC
], line
);
1011 print_clean (const char *line
)
1013 const char *p
= line
;
1016 p
= get_end_of_esc (p
);
1020 const char *text_start
= p
;
1021 const char *text_end
= get_end_of_text (p
);
1022 print_text (text_start
, text_end
- text_start
);
1023 p
= get_end_of_esc (text_end
);
1028 is_esc (const char *p
)
1030 return gather_esc_offsets (p
, NULL
, NULL
);
1034 get_end_of_esc (const char *p
)
1037 const char *end
= NULL
;
1038 while ((esc
= strchr (p
, '\033')))
1040 if (gather_esc_offsets (esc
, NULL
, &end
))
1044 return end
? end
+ 1 : p
+ strlen (p
);
1048 get_end_of_text (const char *p
)
1051 const char *start
= NULL
;
1052 while ((esc
= strchr (p
, '\033')))
1054 if (gather_esc_offsets (esc
, &start
, NULL
))
1058 return start
? start
: p
+ strlen (p
);
1062 print_text (const char *p
, size_t len
)
1064 size_t bytes_written
;
1065 bytes_written
= fwrite (p
, 1, len
, stdout
);
1066 if (bytes_written
!= len
)
1067 vfprintf_fail (formats
[FMT_ERROR
], (unsigned long)len
, "written");
1071 gather_esc_offsets (const char *p
, const char **start
, const char **end
)
1074 if (*p
== 27 && *(p
+ 1) == '[')
1077 const char *begin
= p
;
1080 valid
= validate_esc_clean_all (&p
);
1084 unsigned int iter
= 0;
1087 check_values
= false;
1092 while (isdigit (*p
))
1096 else /* check range */
1101 const unsigned int digits
= p
- digit
;
1102 for (i
= 0; i
< digits
; i
++)
1106 valid
= validate_esc_clean (value
, iter
, &p
, &check_values
);
1108 } while (check_values
);
1123 validate_esc_clean_all (const char **p
)
1125 while (isdigit (**p
) || **p
== ';')
1127 return (**p
== 'm');
1131 validate_esc_clean (int value
, unsigned int iter
, const char **p
, bool *check_values
)
1133 if (is_reset (value
, iter
, p
))
1135 else if (is_bold (value
, iter
, p
))
1138 *check_values
= true;
1139 return false; /* partial escape sequence, need another valid value */
1141 else if (is_fg_color (value
, p
))
1143 else if (is_bg_color (value
, iter
, p
))
1150 is_reset (int value
, unsigned int iter
, const char **p
)
1152 return (value
== 0 && iter
== 1 && **p
== 'm');
1156 is_bold (int value
, unsigned int iter
, const char **p
)
1158 return (value
== 1 && iter
== 1 && **p
== ';');
1162 is_fg_color (int value
, const char **p
)
1164 return (((value
>= 30 && value
<= 37) || value
== 39) && **p
== 'm');
1168 is_bg_color (int value
, unsigned int iter
, const char **p
)
1170 return (((value
>= 40 && value
<= 47) || value
== 49) && iter
== 1 && **p
== 'm');
1175 malloc_wrap (size_t size
)
1177 void *p
= malloc (size
);
1184 calloc_wrap (size_t nmemb
, size_t size
)
1186 void *p
= calloc (nmemb
, size
);
1193 realloc_wrap (void *ptr
, size_t size
)
1195 void *p
= realloc (ptr
, size
);
1202 malloc_wrap_debug (size_t size
, const char *file
, unsigned int line
)
1204 void *p
= malloc (size
);
1206 MEM_ALLOC_FAIL_DEBUG (file
, line
);
1207 fprintf (log
, "%s: malloc'ed %lu bytes [source file %s, line %u]\n", program_name
, (unsigned long)size
, file
, line
);
1212 calloc_wrap_debug (size_t nmemb
, size_t size
, const char *file
, unsigned int line
)
1214 void *p
= calloc (nmemb
, size
);
1216 MEM_ALLOC_FAIL_DEBUG (file
, line
);
1217 fprintf (log
, "%s: calloc'ed %lu bytes [source file %s, line %u]\n", program_name
, (unsigned long)(nmemb
* size
), file
, line
);
1222 realloc_wrap_debug (void *ptr
, size_t size
, const char *file
, unsigned int line
)
1224 void *p
= realloc (ptr
, size
);
1226 MEM_ALLOC_FAIL_DEBUG (file
, line
);
1227 fprintf (log
, "%s: realloc'ed %lu bytes [source file %s, line %u]\n", program_name
, (unsigned long)size
, file
, line
);
1233 free_wrap (void **ptr
)
1240 # define do_malloc(len, file, line) malloc_wrap(len)
1242 # define do_malloc(len, file, line) malloc_wrap_debug(len, file, line)
1246 strdup_wrap (const char *str
, const char *file
, unsigned int line
)
1248 const size_t len
= strlen (str
) + 1;
1249 char *p
= do_malloc (len
, file
, line
);
1250 strncpy (p
, str
, len
);
1255 str_concat_wrap (const char *str1
, const char *str2
, const char *file
, unsigned int line
)
1257 const size_t len
= strlen (str1
) + strlen (str2
) + 1;
1260 p
= str
= do_malloc (len
, file
, line
);
1261 strncpy (p
, str1
, strlen (str1
));
1263 strncpy (p
, str2
, strlen (str2
));
1271 get_bytes_size (unsigned long bytes
, struct bytes_size
*bytes_size
)
1273 const char *unit
, units
[] = { '0', 'K', 'M', 'G', '\0' };
1274 unsigned long size
= bytes
;
1278 while (size
>= 1024 && *(unit
+ 1))
1283 bytes_size
->size
= (unsigned int)size
;
1284 bytes_size
->unit
= *unit
;
1289 get_file_type (mode_t mode
)
1293 else if (S_ISDIR (mode
))
1295 else if (S_ISCHR (mode
))
1296 return "character device";
1297 else if (S_ISBLK (mode
))
1298 return "block device";
1299 else if (S_ISFIFO (mode
))
1300 return "named pipe";
1301 else if (S_ISLNK (mode
))
1302 return "symbolic link";
1303 else if (S_ISSOCK (mode
))
1310 has_color_name (const char *str
, const char *name
)
1314 assert (strlen (str
));
1315 assert (strlen (name
));
1317 if (!(*str
== *name
|| *str
== toupper (*name
)))
1319 else if (*(name
+ 1) != '\0'
1320 && !((p
= strstr (str
+ 1, name
+ 1)) && p
== str
+ 1))
1327 open_file (const char *file
, const char *mode
)
1332 stream
= fopen (file
, mode
);
1334 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
1339 #define DO_VFPRINTF(fmt) \
1341 fprintf (stderr, "%s: ", program_name); \
1342 va_start (ap, fmt); \
1343 vfprintf (stderr, fmt, ap); \
1345 fprintf (stderr, "\n"); \
1348 vfprintf_diag (const char *fmt
, ...)
1354 vfprintf_fail (const char *fmt
, ...)
1357 exit (EXIT_FAILURE
);
1361 stack_var (void ***list
, unsigned int *stacked
, unsigned int index
, void *ptr
)
1363 /* nothing to stack */
1367 *list
= xmalloc (sizeof (void *));
1371 for (i
= 0; i
< *stacked
; i
++)
1375 return; /* reused */
1377 *list
= xrealloc (*list
, (*stacked
+ 1) * sizeof (void *));
1379 (*list
)[index
] = ptr
;
1384 release_var (void **list
, unsigned int stacked
, void **ptr
)
1387 /* nothing to release */
1390 for (i
= 0; i
< stacked
; i
++)
1391 if (list
[i
] == *ptr
)