]>
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>
40 #define to_str(arg) str(arg)
42 #define streq(s1, s2) (strcmp (s1, s2) == 0)
45 # define xmalloc(size) malloc_wrap_debug(size, __FILE__, __LINE__)
46 # define xrealloc(ptr, size) realloc_wrap_debug(ptr, size, __FILE__, __LINE__)
48 # define xmalloc(size) malloc_wrap(size)
49 # define xrealloc(ptr, size) realloc_wrap(ptr, size)
52 #define free_null(ptr) free_wrap((void **)&ptr)
53 #define xstrdup(str) strdup_wrap(str)
55 #if !defined BUF_SIZE || BUF_SIZE <= 0
57 # define BUF_SIZE 4096 + 1
63 #define SKIP_LINE_ENDINGS(flags) (((flags) & CR) && ((flags) & LF) ? 2 : 1)
65 #define STACK_VAR(ptr) do { \
66 stack_var (&vars_list, &stacked_vars, stacked_vars, ptr); \
69 #define RELEASE_VAR(ptr) do { \
70 release_var (vars_list, stacked_vars, (void **)&ptr); \
73 #define MEM_ALLOC_FAIL_DEBUG(file, line) do { \
74 fprintf (stderr, "Memory allocation failure in source file %s, line %u\n", file, line); \
77 #define MEM_ALLOC_FAIL() do { \
78 fprintf (stderr, "%s: memory allocation failure\n", program_name); \
82 #define ABORT_TRACE() \
83 fprintf (stderr, "Aborting in source file %s, line %u\n", __FILE__, __LINE__); \
86 #define CHECK_COLORS_RANDOM(color1, color2) \
87 streq (color_names[color1]->name, "random") \
88 && (streq (color_names[color2]->name, "none") \
89 || streq (color_names[color2]->name, "default")) \
91 #define COLOR_SEP_CHAR '/'
93 #define VERSION "0.49"
95 typedef unsigned short bool;
104 static struct color_name
*color_names
[3] = { NULL
, NULL
, NULL
};
111 static const struct color fg_colors
[] = {
119 { "magenta", "36m" },
121 { "default", "39m" },
123 static const struct color bg_colors
[] = {
131 { "magenta", "46m" },
133 { "default", "49m" },
143 static const char *formats
[] = {
145 "%s color '%s' %s", /* color */
146 "%s color '%s' %s '%s'", /* random */
147 "less than %u bytes %s", /* error */
151 enum { FOREGROUND
, BACKGROUND
};
153 static const struct {
154 struct color
const *entries
;
158 { fg_colors
, sizeof (fg_colors
) / sizeof (struct color
), "foreground" },
159 { bg_colors
, sizeof (bg_colors
) / sizeof (struct color
), "background" },
162 enum stream_mode
{ SCAN_FIRST
= 1, SCAN_ALWAYS
};
166 const char newline
[3];
169 static const struct ending endings
[] = {
175 static FILE *stream
= NULL
;
177 static unsigned int stacked_vars
= 0;
178 static void **vars_list
= NULL
;
180 static bool clean
= false;
181 static char *exclude
= NULL
;
183 static const char *program_name
;
185 static void print_help (void);
186 static void print_version (void);
187 static void cleanup (void);
188 static void free_color_names (struct color_name
**);
189 static void process_options (unsigned int, char **, bool *, const struct color
**, const char **, FILE **);
190 static void process_file_option (const char *, const char **, FILE **);
191 static void read_print_stream (bool, const struct color
**, const char *, FILE *, enum stream_mode
);
192 static void find_color_entries (struct color_name
**, const struct color
**);
193 static void find_color_entry (const char *const, unsigned int, const struct color
**);
194 static void print_line (const struct color
**, bool, const char * const, unsigned int);
195 static void print_clean (const char *);
196 static void print_free_offsets (const char *, char ***, unsigned int);
197 static void *malloc_wrap (size_t);
198 static void *realloc_wrap (void *, size_t);
199 static void *malloc_wrap_debug (size_t, const char *, unsigned int);
200 static void *realloc_wrap_debug (void *, size_t, const char *, unsigned int);
201 static void free_wrap (void **);
202 static char *strdup_wrap (const char *);
203 static char *str_concat (const char *, const char *);
204 static void vfprintf_fail (const char *, ...);
205 static void stack_var (void ***, unsigned int *, unsigned int, void *);
206 static void release_var (void **, unsigned int, void **);
212 main (int argc
, char **argv
)
214 unsigned int arg_cnt
= 0;
217 struct option long_opts
[] = {
218 { "clean", no_argument
, NULL
, 'c' },
219 { "exclude-random", required_argument
, NULL
, 'e' },
220 { "help", no_argument
, NULL
, 'h' },
221 { "version", no_argument
, NULL
, 'v' },
227 const struct color
*colors
[2] = {
228 NULL
, /* foreground */
229 NULL
, /* background */
234 enum stream_mode mode
= SCAN_FIRST
;
236 program_name
= argv
[0];
239 setvbuf (stdout
, NULL
, _IOLBF
, 0);
241 while ((opt
= getopt_long (argc
, argv
, "hv", long_opts
, NULL
)) != -1)
250 exclude
= xstrdup (optarg
);
252 for (p
= exclude
; *p
; p
++)
254 if (streq (exclude
, "random"))
255 vfprintf_fail (formats
[FMT_GENERIC
], "--exclude-random switch must be provided a color");
267 default: /* never reached */
272 arg_cnt
= argc
- optind
;
277 vfprintf_fail (formats
[FMT_GENERIC
], "--clean switch cannot be used with more than one file");
281 if (arg_cnt
== 0 || arg_cnt
> 2)
289 process_file_option (argv
[optind
], &file
, &stream
);
291 process_options (arg_cnt
, &argv
[optind
], &bold
, colors
, &file
, &stream
);
292 read_print_stream (bold
, colors
, file
, stream
, mode
);
294 RELEASE_VAR (exclude
);
304 printf ("Usage: %s (foreground) OR (foreground)%c(background) OR --clean [-|file]\n\n", program_name
, COLOR_SEP_CHAR
);
305 printf ("\tColors (foreground) (background)\n");
306 for (i
= 0; i
< tables
[FOREGROUND
].count
; i
++)
308 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
309 const char *name
= entry
->name
;
310 const char *code
= entry
->code
;
312 printf ("\t\t{\033[%s#\033[0m} [%c%c]%s%*s%s\n",
313 code
, toupper (*name
), *name
, name
+ 1, 10 - (int)strlen (name
), " ", name
);
315 printf ("\t\t{-} %s%*s%s\n", name
, 13 - (int)strlen (name
), " ", name
);
317 printf ("\t\t{*} [Rr]%s%*s%s [--exclude-random=<foreground color>]\n", "andom", 10 - (int)strlen ("random"), " ", "random");
319 printf ("\n\tFirst character of color name in upper case denotes increased intensity,\n");
320 printf ("\twhereas for lower case colors will be of normal intensity.\n");
322 printf ("\n\tOptions\n");
323 printf ("\t\t --clean\n");
324 printf ("\t\t --exclude-random\n");
325 printf ("\t\t-h, --help\n");
326 printf ("\t\t-v, --version\n\n");
333 printf ("%s v%s (compiled at %s, %s)\n", "colorize", VERSION
, __DATE__
, __TIME__
);
335 c_flags
= to_str (CFLAGS
);
339 printf ("Compiler flags: %s\n", c_flags
);
340 printf ("Buffer size: %u bytes\n", BUF_SIZE
- 1);
346 free_color_names (color_names
);
348 if (stream
&& fileno (stream
) != STDIN_FILENO
)
354 for (i
= 0; i
< stacked_vars
; i
++)
356 free_null (vars_list
[i
]);
358 free_null (vars_list
);
363 free_color_names (struct color_name
**color_names
)
366 for (i
= 0; color_names
[i
]; i
++)
368 free_null (color_names
[i
]->name
);
369 free_null (color_names
[i
]->orig
);
370 free_null (color_names
[i
]);
375 process_options (unsigned int arg_cnt
, char **option_strings
, bool *bold
, const struct color
**colors
, const char **file
, FILE **stream
)
379 char *color
, *p
, *str
;
382 const char *color_string
= arg_cnt
>= 1 ? option_strings
[0] : NULL
;
383 const char *file_string
= arg_cnt
== 2 ? option_strings
[1] : NULL
;
385 assert (color_string
);
387 if (streq (color_string
, "-"))
390 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen cannot be used as color string");
392 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen must be preceeded by color string");
395 ret
= stat (color_string
, &sb
);
397 /* Ensure that we don't fail if there's a file with one or more
398 color names in its path. */
403 const char *color
= color_string
;
405 for (c
= 1; c
<= 2 && *color
; c
++)
407 bool matched
= false;
409 for (i
= 0; i
< tables
[FOREGROUND
].count
; i
++)
411 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
413 if ((p
= strstr (color
, entry
->name
)) && p
== color
)
415 color
= p
+ strlen (entry
->name
);
420 if (matched
&& *color
== COLOR_SEP_CHAR
&& *(color
+ 1))
426 have_file
= (*color
!= '\0');
431 vfprintf_fail (formats
[FMT_GENERIC
], "file cannot be used as color string");
433 vfprintf_fail (formats
[FMT_GENERIC
], "file must be preceeded by color string");
437 if ((p
= strchr (color_string
, COLOR_SEP_CHAR
)))
439 if (p
== color_string
)
440 vfprintf_fail (formats
[FMT_GENERIC
], "foreground color missing");
441 else if (p
== color_string
+ strlen (color_string
) - 1)
442 vfprintf_fail (formats
[FMT_GENERIC
], "background color missing");
443 else if (strchr (++p
, COLOR_SEP_CHAR
))
444 vfprintf_fail (formats
[FMT_GENERIC
], "one color pair allowed only");
447 str
= xstrdup (color_string
);
450 for (index
= 0, color
= str
; *color
; index
++, color
= p
)
453 if ((sep
= strchr (color
, COLOR_SEP_CHAR
)))
459 p
= color
+ strlen (color
);
461 for (ch
= color
; *ch
; ch
++)
463 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be made of non-alphabetic characters");
465 for (ch
= color
+ 1; *ch
; ch
++)
467 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be in mixed lower/upper case");
469 if (streq (color
, "None"))
470 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be bold");
472 if (isupper (*color
))
480 vfprintf_fail (formats
[FMT_COLOR
], tables
[BACKGROUND
].desc
, color
, "cannot be bold");
482 default: /* never reached */
487 color_names
[index
] = xmalloc (sizeof (struct color_name
));
489 color_names
[index
]->orig
= xstrdup (color
);
491 for (ch
= color
; *ch
; ch
++)
494 color_names
[index
]->name
= xstrdup (color
);
499 assert (color_names
[FOREGROUND
]);
501 if (color_names
[BACKGROUND
])
504 unsigned int color_sets
[2][2] = { { FOREGROUND
, BACKGROUND
}, { BACKGROUND
, FOREGROUND
} };
505 for (i
= 0; i
< 2; i
++)
507 unsigned int color1
= color_sets
[i
][0];
508 unsigned int color2
= color_sets
[i
][1];
509 if (CHECK_COLORS_RANDOM (color1
, color2
))
510 vfprintf_fail (formats
[FMT_RANDOM
], tables
[color1
].desc
, color_names
[color1
]->orig
, "cannot be combined with", color_names
[color2
]->orig
);
514 find_color_entries (color_names
, colors
);
515 free_color_names (color_names
);
517 if (!colors
[FOREGROUND
]->code
&& colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
518 find_color_entry ("default", FOREGROUND
, colors
);
520 process_file_option (file_string
, file
, stream
);
524 process_file_option (const char *file_string
, const char **file
, FILE **stream
)
528 if (streq (file_string
, "-"))
533 const char *file
= file_string
;
538 ret
= stat (file
, &sb
);
541 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
543 if (!(S_ISREG (sb
.st_mode
) || S_ISLNK (sb
.st_mode
) || S_ISFIFO (sb
.st_mode
)))
544 vfprintf_fail (formats
[FMT_FILE
], file
, "unrecognized file type");
548 s
= fopen (file
, "r");
550 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
564 #define MERGE_PRINT_LINE(part_line, line, flags) do { \
565 char *merged_line = NULL; \
568 merged_line = str_concat (part_line, line); \
569 free_null (part_line); \
571 print_line (colors, bold, merged_line ? merged_line : line, flags); \
572 free (merged_line); \
576 read_print_stream (bool bold
, const struct color
**colors
, const char *file
, FILE *stream
, enum stream_mode mode
)
578 char buf
[BUF_SIZE
], *part_line
= NULL
;
579 unsigned int flags
= 0;
580 bool first
= false, always
= false;
590 default: /* never reached */
594 while (!feof (stream
))
599 memset (buf
, '\0', BUF_SIZE
);
600 bytes_read
= fread (buf
, 1, BUF_SIZE
- 1, stream
);
601 if (bytes_read
!= (BUF_SIZE
- 1) && ferror (stream
))
602 vfprintf_fail (formats
[FMT_ERROR
], BUF_SIZE
- 1, "read");
604 LOOP
: while ((eol
= strpbrk (line
, "\n\r")))
614 if (*(eol
+ 1) == '\n')
617 else if (*eol
== '\n')
620 vfprintf_fail (formats
[FMT_FILE
], file
, "unrecognized line ending");
623 p
= eol
+ SKIP_LINE_ENDINGS (flags
);
627 unsigned int count
= sizeof (endings
) / sizeof (struct ending
);
628 for (i
= 0; i
< count
; i
++)
630 if (flags
& endings
[i
].flags
)
633 if ((p
= strstr (eol
, endings
[i
].newline
)) && p
== eol
)
642 p
= eol
+ SKIP_LINE_ENDINGS (flags
);
645 MERGE_PRINT_LINE (part_line
, line
, flags
);
649 MERGE_PRINT_LINE (part_line
, line
, 0);
653 if (!clean
) /* efficiency */
654 print_line (colors
, bold
, line
, 0);
656 part_line
= xstrdup (line
);
659 char *merged_line
= str_concat (part_line
, line
);
661 part_line
= merged_line
;
668 find_color_entries (struct color_name
**color_names
, const struct color
**colors
)
674 gettimeofday (&tv
, NULL
);
675 srand (tv
.tv_usec
* tv
.tv_sec
);
677 for (index
= 0; color_names
[index
]; index
++)
679 const char *color_name
= color_names
[index
]->name
;
681 const unsigned int count
= tables
[index
].count
;
682 const struct color
*const color_entries
= tables
[index
].entries
;
684 if (streq (color_name
, "random"))
690 i
= rand() % (count
- 2) + 1; /* omit color none and default */
694 /* --exclude-random */
695 if (exclude
&& streq (exclude
, color_entries
[i
].name
))
697 else if (color_names
[BACKGROUND
] && streq (color_names
[BACKGROUND
]->name
, color_entries
[i
].name
))
701 if (streq (colors
[FOREGROUND
]->name
, color_entries
[i
].name
))
704 default: /* never reached */
707 } while (excludable
);
708 colors
[index
] = (struct color
*)&color_entries
[i
];
711 find_color_entry (color_name
, index
, colors
);
716 find_color_entry (const char *const color_name
, unsigned int index
, const struct color
**colors
)
721 const unsigned int count
= tables
[index
].count
;
722 const struct color
*const color_entries
= tables
[index
].entries
;
724 for (i
= 0; i
< count
; i
++)
725 if (streq (color_name
, color_entries
[i
].name
))
727 colors
[index
] = (struct color
*)&color_entries
[i
];
732 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color_name
, "not recognized");
736 print_line (const struct color
**colors
, bool bold
, const char *const line
, unsigned int flags
)
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 bool check_values
, first
= true;
769 const char *begin
= p
;
775 check_values
= false;
776 if (!first
&& !isdigit (*p
))
783 else /* check range */
788 const unsigned int digits
= p
- digit
;
789 for (i
= 0; i
< digits
; i
++)
793 if (!((value
>= 0 && value
<= 8) /* attributes */
794 || (value
>= 30 && value
<= 37) /* foreground colors */
795 || (value
>= 40 && value
<= 47) /* background colors */
796 || (value
== 39 || value
== 49))) /* default colors */
805 } while (check_values
);
808 const char *end
= p
++;
810 offsets
= xmalloc (++count
* sizeof (char **));
812 offsets
= xrealloc (offsets
, ++count
* sizeof (char **));
813 offsets
[i
] = xmalloc (2 * sizeof (char *));
814 offsets
[i
][0] = (char *)begin
; /* ESC */
815 offsets
[i
][1] = (char *)end
; /* m */
826 print_free_offsets (line
, offsets
, count
);
828 printf (formats
[FMT_GENERIC
], line
);
831 #define SET_CHAR(offset, new, old) \
835 #define RESTORE_CHAR(offset, old) \
839 print_free_offsets (const char *line
, char ***offsets
, unsigned int count
)
844 SET_CHAR (offsets
[0][0], '\0', &ch
);
845 printf (formats
[FMT_GENERIC
], line
);
846 RESTORE_CHAR (offsets
[0][0], ch
);
848 for (i
= 0; i
< count
; i
++)
851 bool next_offset
= false;
854 SET_CHAR (offsets
[i
+ 1][0], '\0', &ch
);
857 printf (formats
[FMT_GENERIC
], offsets
[i
][1] + 1);
859 RESTORE_CHAR (offsets
[i
+ 1][0], ch
);
861 for (i
= 0; i
< count
; i
++)
862 free_null (offsets
[i
]);
867 malloc_wrap (size_t size
)
869 void *p
= malloc (size
);
876 realloc_wrap (void *ptr
, size_t size
)
878 void *p
= realloc (ptr
, size
);
885 malloc_wrap_debug (size_t size
, const char *file
, unsigned int line
)
887 void *p
= malloc (size
);
889 MEM_ALLOC_FAIL_DEBUG (file
, line
);
894 realloc_wrap_debug (void *ptr
, size_t size
, const char *file
, unsigned int line
)
896 void *p
= realloc (ptr
, size
);
898 MEM_ALLOC_FAIL_DEBUG (file
, line
);
903 free_wrap (void **ptr
)
910 strdup_wrap (const char *str
)
912 const size_t len
= strlen (str
) + 1;
913 char *p
= xmalloc (len
);
914 strncpy (p
, str
, len
);
919 str_concat (const char *str1
, const char *str2
)
921 const size_t len
= strlen (str1
) + strlen (str2
) + 1;
924 p
= str
= xmalloc (len
);
925 strncpy (p
, str1
, strlen (str1
));
927 strncpy (p
, str2
, strlen (str2
));
935 vfprintf_fail (const char *fmt
, ...)
938 fprintf (stderr
, "%s: ", program_name
);
940 vfprintf (stderr
, fmt
, ap
);
942 fprintf (stderr
, "\n");
947 stack_var (void ***list
, unsigned int *stacked
, unsigned int index
, void *ptr
)
949 /* nothing to stack */
953 *list
= xmalloc (sizeof (void *));
957 for (i
= 0; i
< *stacked
; i
++)
963 *list
= xrealloc (*list
, (*stacked
+ 1) * sizeof (void *));
965 (*list
)[index
] = ptr
;
970 release_var (void **list
, unsigned int stacked
, void **ptr
)
973 /* nothing to release */
976 for (i
= 0; i
< stacked
; i
++)