]>
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-2013 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/>.
32 #include <sys/types.h>
42 #define to_str(arg) str(arg)
44 #define streq(s1, s2) (strcmp (s1, s2) == 0)
46 #define vfprintf_fail(fmt, ...) vfprintf_name(true, fmt, __VA_ARGS__)
47 #define vfprintf_diag(fmt, ...) vfprintf_name(false, fmt, __VA_ARGS__)
50 # define xmalloc(size) malloc_wrap_debug(size, __FILE__, __LINE__)
51 # define xcalloc(nmemb, size) calloc_wrap_debug(nmemb, size, __FILE__, __LINE__)
52 # define xrealloc(ptr, size) realloc_wrap_debug(ptr, size, __FILE__, __LINE__)
54 # define xmalloc(size) malloc_wrap(size)
55 # define xcalloc(nmemb, size) calloc_wrap(nmemb, size)
56 # define xrealloc(ptr, size) realloc_wrap(ptr, size)
59 #define free_null(ptr) free_wrap((void **)&ptr)
60 #define xstrdup(str) strdup_wrap(str)
62 #if !defined BUF_SIZE || BUF_SIZE <= 0
64 # define BUF_SIZE 4096 + 1
70 #define SKIP_LINE_ENDINGS(flags) (((flags) & CR) && ((flags) & LF) ? 2 : 1)
72 #define STACK_VAR(ptr) do { \
73 stack_var (&vars_list, &stacked_vars, stacked_vars, ptr); \
76 #define RELEASE_VAR(ptr) do { \
77 release_var (vars_list, stacked_vars, (void **)&ptr); \
80 #define MEM_ALLOC_FAIL_DEBUG(file, line) do { \
81 fprintf (stderr, "Memory allocation failure in source file %s, line %u\n", file, line); \
84 #define MEM_ALLOC_FAIL() do { \
85 fprintf (stderr, "%s: memory allocation failure\n", program_name); \
89 #define ABORT_TRACE() \
90 fprintf (stderr, "Aborting in source file %s, line %u\n", __FILE__, __LINE__); \
93 #define CHECK_COLORS_RANDOM(color1, color2) \
94 streq (color_names[color1]->name, "random") \
95 && (streq (color_names[color2]->name, "none") \
96 || streq (color_names[color2]->name, "default")) \
98 #define COLOR_SEP_CHAR '/'
100 #define VERSION "0.50"
102 typedef unsigned short bool;
104 enum { false, true };
111 static struct color_name
*color_names
[3] = { NULL
, NULL
, NULL
};
118 static const struct color fg_colors
[] = {
126 { "magenta", "36m" },
128 { "default", "39m" },
130 static const struct color bg_colors
[] = {
138 { "magenta", "46m" },
140 { "default", "49m" },
150 static const char *formats
[] = {
152 "%s color '%s' %s", /* color */
153 "%s color '%s' %s '%s'", /* random */
154 "less than %u bytes %s", /* error */
158 enum { FOREGROUND
, BACKGROUND
};
160 static const struct {
161 struct color
const *entries
;
165 { fg_colors
, sizeof (fg_colors
) / sizeof (struct color
), "foreground" },
166 { bg_colors
, sizeof (bg_colors
) / sizeof (struct color
), "background" },
169 static FILE *stream
= NULL
;
171 static unsigned int stacked_vars
= 0;
172 static void **vars_list
= NULL
;
174 static bool clean
= false;
175 static bool clean_all
= false;
177 static char *exclude
= NULL
;
179 static const char *program_name
;
181 static void print_help (void);
182 static void print_version (void);
183 static void cleanup (void);
184 static void free_color_names (struct color_name
**);
185 static void process_options (unsigned int, char **, bool *, const struct color
**, const char **, FILE **);
186 static void process_file_option (const char *, const char **, FILE **);
187 static void read_print_stream (bool, const struct color
**, const char *, FILE *);
188 static void find_color_entries (struct color_name
**, const struct color
**);
189 static void find_color_entry (const char *const, unsigned int, const struct color
**);
190 static void print_line (const struct color
**, bool, const char * const, unsigned int);
191 static void print_clean (const char *);
192 static void print_free_offsets (const char *, char ***, unsigned int);
193 static void *malloc_wrap (size_t);
194 static void *calloc_wrap (size_t, size_t);
195 static void *realloc_wrap (void *, size_t);
196 static void *malloc_wrap_debug (size_t, const char *, unsigned int);
197 static void *calloc_wrap_debug (size_t, size_t, const char *, unsigned int);
198 static void *realloc_wrap_debug (void *, size_t, const char *, unsigned int);
199 static void free_wrap (void **);
200 static char *strdup_wrap (const char *);
201 static char *str_concat (const char *, const char *);
202 static void vfprintf_name (bool, const char *, ...);
203 static void stack_var (void ***, unsigned int *, unsigned int, void *);
204 static void release_var (void **, unsigned int, void **);
206 #define SET_OPT_TYPE(type) \
215 main (int argc
, char **argv
)
217 unsigned int arg_cnt
= 0;
227 int opt
, opt_type
= 0;
228 struct option long_opts
[] = {
229 { "clean", no_argument
, &opt_type
, OPT_CLEAN
},
230 { "clean-all", no_argument
, &opt_type
, OPT_CLEAN_ALL
},
231 { "exclude-random", required_argument
, &opt_type
, OPT_EXCLUDE_RANDOM
},
232 { "help", no_argument
, &opt_type
, OPT_HELP
},
233 { "version", no_argument
, &opt_type
, OPT_VERSION
},
239 const struct color
*colors
[2] = {
240 NULL
, /* foreground */
241 NULL
, /* background */
246 program_name
= argv
[0];
249 setvbuf (stdout
, NULL
, _IOLBF
, 0);
251 while ((opt
= getopt_long (argc
, argv
, "hv", long_opts
, NULL
)) != -1)
256 case 0: /* long opts */
265 case OPT_EXCLUDE_RANDOM
: {
267 exclude
= xstrdup (optarg
);
269 for (p
= exclude
; *p
; p
++)
271 if (streq (exclude
, "random"))
272 vfprintf_fail (formats
[FMT_GENERIC
], "--exclude-random switch must be provided a color");
281 default: /* never reached */
286 SET_OPT_TYPE (OPT_HELP
);
288 SET_OPT_TYPE (OPT_VERSION
);
292 default: /* never reached */
297 arg_cnt
= argc
- optind
;
299 if (clean
|| clean_all
)
301 if (clean
&& clean_all
)
302 vfprintf_fail (formats
[FMT_GENERIC
], "--clean and --clean-all switch are mutually exclusive");
305 const char *format
= "%s %s";
306 const char *message
= "switch cannot be used with more than one file";
308 vfprintf_fail (format
, "--clean", message
);
310 vfprintf_fail (format
, "--clean-all", message
);
315 if (arg_cnt
== 0 || arg_cnt
> 2)
322 if (clean
|| clean_all
)
323 process_file_option (argv
[optind
], &file
, &stream
);
325 process_options (arg_cnt
, &argv
[optind
], &bold
, colors
, &file
, &stream
);
326 read_print_stream (bold
, colors
, file
, stream
);
328 RELEASE_VAR (exclude
);
338 printf ("Usage: %s (foreground) OR (foreground)%c(background) OR --clean[-all] [-|file]\n\n", program_name
, COLOR_SEP_CHAR
);
339 printf ("\tColors (foreground) (background)\n");
340 for (i
= 0; i
< tables
[FOREGROUND
].count
; i
++)
342 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
343 const char *name
= entry
->name
;
344 const char *code
= entry
->code
;
346 printf ("\t\t{\033[%s#\033[0m} [%c%c]%s%*s%s\n",
347 code
, toupper (*name
), *name
, name
+ 1, 10 - (int)strlen (name
), " ", name
);
349 printf ("\t\t{-} %s%*s%s\n", name
, 13 - (int)strlen (name
), " ", name
);
351 printf ("\t\t{*} [Rr]%s%*s%s [--exclude-random=<foreground color>]\n", "andom", 10 - (int)strlen ("random"), " ", "random");
353 printf ("\n\tFirst character of color name in upper case denotes increased intensity,\n");
354 printf ("\twhereas for lower case colors will be of normal intensity.\n");
356 printf ("\n\tOptions\n");
357 printf ("\t\t --clean\n");
358 printf ("\t\t --clean-all\n");
359 printf ("\t\t --exclude-random\n");
360 printf ("\t\t-h, --help\n");
361 printf ("\t\t-v, --version\n\n");
368 printf ("%s v%s (compiled at %s, %s)\n", "colorize", VERSION
, __DATE__
, __TIME__
);
370 c_flags
= to_str (CFLAGS
);
374 printf ("Compiler flags: %s\n", c_flags
);
375 printf ("Buffer size: %u bytes\n", BUF_SIZE
- 1);
381 free_color_names (color_names
);
383 if (stream
&& fileno (stream
) != STDIN_FILENO
)
389 for (i
= 0; i
< stacked_vars
; i
++)
391 free_null (vars_list
[i
]);
393 free_null (vars_list
);
398 free_color_names (struct color_name
**color_names
)
401 for (i
= 0; color_names
[i
]; i
++)
403 free_null (color_names
[i
]->name
);
404 free_null (color_names
[i
]->orig
);
405 free_null (color_names
[i
]);
410 process_options (unsigned int arg_cnt
, char **option_strings
, bool *bold
, const struct color
**colors
, const char **file
, FILE **stream
)
414 char *color
, *p
, *str
;
417 const char *color_string
= arg_cnt
>= 1 ? option_strings
[0] : NULL
;
418 const char *file_string
= arg_cnt
== 2 ? option_strings
[1] : NULL
;
420 assert (color_string
);
422 if (streq (color_string
, "-"))
425 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen cannot be used as color string");
427 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen must be preceeded by color string");
430 ret
= stat (color_string
, &sb
);
432 /* Ensure that we don't fail if there's a file with one or more
433 color names in its path. */
438 const char *color
= color_string
;
440 for (c
= 1; c
<= 2 && *color
; c
++)
442 bool matched
= false;
444 for (i
= 0; i
< tables
[FOREGROUND
].count
; i
++)
446 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
448 if ((p
= strstr (color
, entry
->name
)) && p
== color
)
450 color
= p
+ strlen (entry
->name
);
455 if (matched
&& *color
== COLOR_SEP_CHAR
&& *(color
+ 1))
461 have_file
= (*color
!= '\0');
466 vfprintf_fail (formats
[FMT_GENERIC
], "file cannot be used as color string");
468 vfprintf_fail (formats
[FMT_GENERIC
], "file must be preceeded by color string");
472 if ((p
= strchr (color_string
, COLOR_SEP_CHAR
)))
474 if (p
== color_string
)
475 vfprintf_fail (formats
[FMT_GENERIC
], "foreground color missing");
476 else if (p
== color_string
+ strlen (color_string
) - 1)
477 vfprintf_fail (formats
[FMT_GENERIC
], "background color missing");
478 else if (strchr (++p
, COLOR_SEP_CHAR
))
479 vfprintf_fail (formats
[FMT_GENERIC
], "one color pair allowed only");
482 str
= xstrdup (color_string
);
485 for (index
= 0, color
= str
; *color
; index
++, color
= p
)
488 if ((sep
= strchr (color
, COLOR_SEP_CHAR
)))
494 p
= color
+ strlen (color
);
496 for (ch
= color
; *ch
; ch
++)
498 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be made of non-alphabetic characters");
500 for (ch
= color
+ 1; *ch
; ch
++)
502 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be in mixed lower/upper case");
504 if (streq (color
, "None"))
505 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be bold");
507 if (isupper (*color
))
515 vfprintf_fail (formats
[FMT_COLOR
], tables
[BACKGROUND
].desc
, color
, "cannot be bold");
517 default: /* never reached */
522 color_names
[index
] = xcalloc (1, sizeof (struct color_name
));
524 color_names
[index
]->orig
= xstrdup (color
);
526 for (ch
= color
; *ch
; ch
++)
529 color_names
[index
]->name
= xstrdup (color
);
534 assert (color_names
[FOREGROUND
]);
536 if (color_names
[BACKGROUND
])
539 unsigned int color_sets
[2][2] = { { FOREGROUND
, BACKGROUND
}, { BACKGROUND
, FOREGROUND
} };
540 for (i
= 0; i
< 2; i
++)
542 unsigned int color1
= color_sets
[i
][0];
543 unsigned int color2
= color_sets
[i
][1];
544 if (CHECK_COLORS_RANDOM (color1
, color2
))
545 vfprintf_fail (formats
[FMT_RANDOM
], tables
[color1
].desc
, color_names
[color1
]->orig
, "cannot be combined with", color_names
[color2
]->orig
);
549 find_color_entries (color_names
, colors
);
550 free_color_names (color_names
);
552 if (!colors
[FOREGROUND
]->code
&& colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
553 find_color_entry ("default", FOREGROUND
, colors
);
555 process_file_option (file_string
, file
, stream
);
559 process_file_option (const char *file_string
, const char **file
, FILE **stream
)
563 if (streq (file_string
, "-"))
568 const char *file
= file_string
;
573 ret
= stat (file
, &sb
);
576 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
578 if (!(S_ISREG (sb
.st_mode
) || S_ISLNK (sb
.st_mode
) || S_ISFIFO (sb
.st_mode
)))
579 vfprintf_fail (formats
[FMT_FILE
], file
, "unrecognized file type");
583 s
= fopen (file
, "r");
585 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
599 #define MERGE_PRINT_LINE(part_line, line, flags, check_eof) do { \
600 char *current_line, *merged_line = NULL; \
603 merged_line = str_concat (part_line, line); \
604 free_null (part_line); \
606 current_line = merged_line ? merged_line : (char *)line; \
607 if (!check_eof || *current_line != '\0') \
608 print_line (colors, bold, current_line, flags); \
609 free (merged_line); \
613 read_print_stream (bool bold
, const struct color
**colors
, const char *file
, FILE *stream
)
615 char buf
[BUF_SIZE
], *part_line
= NULL
;
616 unsigned int flags
= 0;
618 while (!feof (stream
))
623 memset (buf
, '\0', BUF_SIZE
);
624 bytes_read
= fread (buf
, 1, BUF_SIZE
- 1, stream
);
625 if (bytes_read
!= (BUF_SIZE
- 1) && ferror (stream
))
626 vfprintf_fail (formats
[FMT_ERROR
], BUF_SIZE
- 1, "read");
628 while ((eol
= strpbrk (line
, "\n\r")))
635 if (*(eol
+ 1) == '\n')
638 else if (*eol
== '\n')
641 vfprintf_fail (formats
[FMT_FILE
], file
, "unrecognized line ending");
642 p
= eol
+ SKIP_LINE_ENDINGS (flags
);
644 MERGE_PRINT_LINE (part_line
, line
, flags
, false);
648 MERGE_PRINT_LINE (part_line
, line
, 0, true);
650 else if (*line
!= '\0')
652 if (!clean
&& !clean_all
) /* efficiency */
653 print_line (colors
, bold
, line
, 0);
655 part_line
= xstrdup (line
);
658 char *merged_line
= str_concat (part_line
, line
);
660 part_line
= merged_line
;
667 find_color_entries (struct color_name
**color_names
, const struct color
**colors
)
673 gettimeofday (&tv
, NULL
);
674 srand (tv
.tv_usec
* tv
.tv_sec
);
676 for (index
= 0; color_names
[index
]; index
++)
678 const char *color_name
= color_names
[index
]->name
;
680 const unsigned int count
= tables
[index
].count
;
681 const struct color
*const color_entries
= tables
[index
].entries
;
683 if (streq (color_name
, "random"))
689 i
= rand() % (count
- 2) + 1; /* omit color none and default */
693 /* --exclude-random */
694 if (exclude
&& streq (exclude
, color_entries
[i
].name
))
696 else if (color_names
[BACKGROUND
] && streq (color_names
[BACKGROUND
]->name
, color_entries
[i
].name
))
700 if (streq (colors
[FOREGROUND
]->name
, color_entries
[i
].name
))
703 default: /* never reached */
706 } while (excludable
);
707 colors
[index
] = (struct color
*)&color_entries
[i
];
710 find_color_entry (color_name
, index
, colors
);
715 find_color_entry (const char *const color_name
, unsigned int index
, const struct color
**colors
)
720 const unsigned int count
= tables
[index
].count
;
721 const struct color
*const color_entries
= tables
[index
].entries
;
723 for (i
= 0; i
< count
; i
++)
724 if (streq (color_name
, color_entries
[i
].name
))
726 colors
[index
] = (struct color
*)&color_entries
[i
];
731 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color_name
, "not recognized");
735 print_line (const struct color
**colors
, bool bold
, const char *const line
, unsigned int flags
)
738 if (clean
|| clean_all
)
742 /* Foreground color code is guaranteed to be set when background color code is present. */
743 if (colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
744 printf ("\033[%s", colors
[BACKGROUND
]->code
);
745 if (colors
[FOREGROUND
]->code
)
746 printf ("\033[%s%s%s\033[0m", bold
? "1;" : "", colors
[FOREGROUND
]->code
, line
);
748 printf (formats
[FMT_GENERIC
], line
);
757 print_clean (const char *line
)
760 char ***offsets
= NULL
;
761 unsigned int count
= 0, i
= 0;
766 if (*p
== 27 && *(p
+ 1) == '[')
768 const char *begin
= p
;
772 while (isdigit (*p
) || *p
== ';')
778 unsigned int iter
= 0;
781 check_values
= false;
790 else /* check range */
795 const unsigned int digits
= p
- digit
;
796 for (i
= 0; i
< digits
; i
++)
800 if (value
== 0) /* reset */
806 else if (value
== 1) /* bold */
808 bool discard
= false;
818 else if ((value
>= 30 && value
<= 37) || value
== 39) /* foreground colors */
820 else if ((value
>= 40 && value
<= 47) || value
== 49) /* background colors */
829 } while (iter
== 1 && check_values
);
833 const char *end
= p
++;
835 offsets
= xmalloc (++count
* sizeof (char **));
837 offsets
= xrealloc (offsets
, ++count
* sizeof (char **));
838 offsets
[i
] = xmalloc (2 * sizeof (char *));
839 offsets
[i
][0] = (char *)begin
; /* ESC */
840 offsets
[i
][1] = (char *)end
; /* m */
851 print_free_offsets (line
, offsets
, count
);
853 printf (formats
[FMT_GENERIC
], line
);
856 #define SET_CHAR(offset, new, old) \
860 #define RESTORE_CHAR(offset, old) \
864 print_free_offsets (const char *line
, char ***offsets
, unsigned int count
)
869 SET_CHAR (offsets
[0][0], '\0', &ch
);
870 printf (formats
[FMT_GENERIC
], line
);
871 RESTORE_CHAR (offsets
[0][0], ch
);
873 for (i
= 0; i
< count
; i
++)
876 bool next_offset
= false;
879 SET_CHAR (offsets
[i
+ 1][0], '\0', &ch
);
882 printf (formats
[FMT_GENERIC
], offsets
[i
][1] + 1);
884 RESTORE_CHAR (offsets
[i
+ 1][0], ch
);
886 for (i
= 0; i
< count
; i
++)
887 free_null (offsets
[i
]);
892 malloc_wrap (size_t size
)
894 void *p
= malloc (size
);
901 calloc_wrap (size_t nmemb
, size_t size
)
903 void *p
= calloc (nmemb
, size
);
910 realloc_wrap (void *ptr
, size_t size
)
912 void *p
= realloc (ptr
, size
);
919 malloc_wrap_debug (size_t size
, const char *file
, unsigned int line
)
921 void *p
= malloc (size
);
923 MEM_ALLOC_FAIL_DEBUG (file
, line
);
928 calloc_wrap_debug (size_t nmemb
, size_t size
, const char *file
, unsigned int line
)
930 void *p
= calloc (nmemb
, size
);
932 MEM_ALLOC_FAIL_DEBUG (file
, line
);
937 realloc_wrap_debug (void *ptr
, size_t size
, const char *file
, unsigned int line
)
939 void *p
= realloc (ptr
, size
);
941 MEM_ALLOC_FAIL_DEBUG (file
, line
);
946 free_wrap (void **ptr
)
953 strdup_wrap (const char *str
)
955 const size_t len
= strlen (str
) + 1;
956 char *p
= xmalloc (len
);
957 strncpy (p
, str
, len
);
962 str_concat (const char *str1
, const char *str2
)
964 const size_t len
= strlen (str1
) + strlen (str2
) + 1;
967 p
= str
= xmalloc (len
);
968 strncpy (p
, str1
, strlen (str1
));
970 strncpy (p
, str2
, strlen (str2
));
978 vfprintf_name (bool fatal
, const char *fmt
, ...)
981 fprintf (stderr
, "%s: ", program_name
);
983 vfprintf (stderr
, fmt
, ap
);
985 fprintf (stderr
, "\n");
991 stack_var (void ***list
, unsigned int *stacked
, unsigned int index
, void *ptr
)
993 /* nothing to stack */
997 *list
= xmalloc (sizeof (void *));
1001 for (i
= 0; i
< *stacked
; i
++)
1005 return; /* reused */
1007 *list
= xrealloc (*list
, (*stacked
+ 1) * sizeof (void *));
1009 (*list
)[index
] = ptr
;
1014 release_var (void **list
, unsigned int stacked
, void **ptr
)
1017 /* nothing to release */
1020 for (i
= 0; i
< stacked
; i
++)
1021 if (list
[i
] == *ptr
)