]>
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 xcalloc(nmemb, size) calloc_wrap_debug(nmemb, size, __FILE__, __LINE__)
47 # define xrealloc(ptr, size) realloc_wrap_debug(ptr, size, __FILE__, __LINE__)
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)
54 #define free_null(ptr) free_wrap((void **)&ptr)
55 #define xstrdup(str) strdup_wrap(str)
57 #if !defined BUF_SIZE || BUF_SIZE <= 0
59 # define BUF_SIZE 4096 + 1
65 #define SKIP_LINE_ENDINGS(flags) (((flags) & CR) && ((flags) & LF) ? 2 : 1)
67 #define STACK_VAR(ptr) do { \
68 stack_var (&vars_list, &stacked_vars, stacked_vars, ptr); \
71 #define RELEASE_VAR(ptr) do { \
72 release_var (vars_list, stacked_vars, (void **)&ptr); \
75 #define MEM_ALLOC_FAIL_DEBUG(file, line) do { \
76 fprintf (stderr, "Memory allocation failure in source file %s, line %u\n", file, line); \
79 #define MEM_ALLOC_FAIL() do { \
80 fprintf (stderr, "%s: memory allocation failure\n", program_name); \
84 #define ABORT_TRACE() \
85 fprintf (stderr, "Aborting in source file %s, line %u\n", __FILE__, __LINE__); \
88 #define CHECK_COLORS_RANDOM(color1, color2) \
89 streq (color_names[color1]->name, "random") \
90 && (streq (color_names[color2]->name, "none") \
91 || streq (color_names[color2]->name, "default")) \
93 #define COLOR_SEP_CHAR '/'
95 #define VERSION "0.50"
97 typedef unsigned short bool;
106 static struct color_name
*color_names
[3] = { NULL
, NULL
, NULL
};
113 static const struct color fg_colors
[] = {
121 { "magenta", "36m" },
123 { "default", "39m" },
125 static const struct color bg_colors
[] = {
133 { "magenta", "46m" },
135 { "default", "49m" },
145 static const char *formats
[] = {
147 "%s color '%s' %s", /* color */
148 "%s color '%s' %s '%s'", /* random */
149 "less than %u bytes %s", /* error */
153 enum { FOREGROUND
, BACKGROUND
};
155 static const struct {
156 struct color
const *entries
;
160 { fg_colors
, sizeof (fg_colors
) / sizeof (struct color
), "foreground" },
161 { bg_colors
, sizeof (bg_colors
) / sizeof (struct color
), "background" },
164 enum stream_mode
{ SCAN_FIRST
= 1, SCAN_ALWAYS
};
168 const char newline
[3];
171 static const struct ending endings
[] = {
177 static FILE *stream
= NULL
;
179 static unsigned int stacked_vars
= 0;
180 static void **vars_list
= NULL
;
182 static bool clean
= false;
183 static bool clean_all
= false;
185 static char *exclude
= NULL
;
187 static const char *program_name
;
189 static void print_help (void);
190 static void print_version (void);
191 static void cleanup (void);
192 static void free_color_names (struct color_name
**);
193 static void process_options (unsigned int, char **, bool *, const struct color
**, const char **, FILE **);
194 static void process_file_option (const char *, const char **, FILE **);
195 static void read_print_stream (bool, const struct color
**, const char *, FILE *, enum stream_mode
);
196 static void find_color_entries (struct color_name
**, const struct color
**);
197 static void find_color_entry (const char *const, unsigned int, const struct color
**);
198 static void print_line (const struct color
**, bool, const char * const, unsigned int);
199 static void print_clean (const char *);
200 static void print_free_offsets (const char *, char ***, unsigned int);
201 static void *malloc_wrap (size_t);
202 static void *calloc_wrap (size_t, size_t);
203 static void *realloc_wrap (void *, size_t);
204 static void *malloc_wrap_debug (size_t, const char *, unsigned int);
205 static void *calloc_wrap_debug (size_t, size_t, const char *, unsigned int);
206 static void *realloc_wrap_debug (void *, size_t, const char *, unsigned int);
207 static void free_wrap (void **);
208 static char *strdup_wrap (const char *);
209 static char *str_concat (const char *, const char *);
210 static void vfprintf_fail (const char *, ...);
211 static void stack_var (void ***, unsigned int *, unsigned int, void *);
212 static void release_var (void **, unsigned int, void **);
214 #define SET_OPT_TYPE(type) \
223 main (int argc
, char **argv
)
225 unsigned int arg_cnt
= 0;
235 int opt
, opt_type
= 0;
236 struct option long_opts
[] = {
237 { "clean", no_argument
, &opt_type
, OPT_CLEAN
},
238 { "clean-all", no_argument
, &opt_type
, OPT_CLEAN_ALL
},
239 { "exclude-random", required_argument
, &opt_type
, OPT_EXCLUDE_RANDOM
},
240 { "help", no_argument
, &opt_type
, OPT_HELP
},
241 { "version", no_argument
, &opt_type
, OPT_VERSION
},
247 const struct color
*colors
[2] = {
248 NULL
, /* foreground */
249 NULL
, /* background */
254 enum stream_mode mode
= SCAN_FIRST
;
256 program_name
= argv
[0];
259 setvbuf (stdout
, NULL
, _IOLBF
, 0);
261 while ((opt
= getopt_long (argc
, argv
, "hv", long_opts
, NULL
)) != -1)
266 case 0: /* long opts */
275 case OPT_EXCLUDE_RANDOM
: {
277 exclude
= xstrdup (optarg
);
279 for (p
= exclude
; *p
; p
++)
281 if (streq (exclude
, "random"))
282 vfprintf_fail (formats
[FMT_GENERIC
], "--exclude-random switch must be provided a color");
291 default: /* never reached */
296 SET_OPT_TYPE (OPT_HELP
);
298 SET_OPT_TYPE (OPT_VERSION
);
302 default: /* never reached */
307 arg_cnt
= argc
- optind
;
309 if (clean
|| clean_all
)
313 const char *format
= "%s %s";
314 const char *message
= "switch cannot be used with more than one file";
316 vfprintf_fail (format
, "--clean", message
);
318 vfprintf_fail (format
, "--clean-all", message
);
323 if (arg_cnt
== 0 || arg_cnt
> 2)
330 if (clean
|| clean_all
)
331 process_file_option (argv
[optind
], &file
, &stream
);
333 process_options (arg_cnt
, &argv
[optind
], &bold
, colors
, &file
, &stream
);
334 read_print_stream (bold
, colors
, file
, stream
, mode
);
336 RELEASE_VAR (exclude
);
346 printf ("Usage: %s (foreground) OR (foreground)%c(background) OR --clean[-all] [-|file]\n\n", program_name
, COLOR_SEP_CHAR
);
347 printf ("\tColors (foreground) (background)\n");
348 for (i
= 0; i
< tables
[FOREGROUND
].count
; i
++)
350 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
351 const char *name
= entry
->name
;
352 const char *code
= entry
->code
;
354 printf ("\t\t{\033[%s#\033[0m} [%c%c]%s%*s%s\n",
355 code
, toupper (*name
), *name
, name
+ 1, 10 - (int)strlen (name
), " ", name
);
357 printf ("\t\t{-} %s%*s%s\n", name
, 13 - (int)strlen (name
), " ", name
);
359 printf ("\t\t{*} [Rr]%s%*s%s [--exclude-random=<foreground color>]\n", "andom", 10 - (int)strlen ("random"), " ", "random");
361 printf ("\n\tFirst character of color name in upper case denotes increased intensity,\n");
362 printf ("\twhereas for lower case colors will be of normal intensity.\n");
364 printf ("\n\tOptions\n");
365 printf ("\t\t --clean\n");
366 printf ("\t\t --clean-all\n");
367 printf ("\t\t --exclude-random\n");
368 printf ("\t\t-h, --help\n");
369 printf ("\t\t-v, --version\n\n");
376 printf ("%s v%s (compiled at %s, %s)\n", "colorize", VERSION
, __DATE__
, __TIME__
);
378 c_flags
= to_str (CFLAGS
);
382 printf ("Compiler flags: %s\n", c_flags
);
383 printf ("Buffer size: %u bytes\n", BUF_SIZE
- 1);
389 free_color_names (color_names
);
391 if (stream
&& fileno (stream
) != STDIN_FILENO
)
397 for (i
= 0; i
< stacked_vars
; i
++)
399 free_null (vars_list
[i
]);
401 free_null (vars_list
);
406 free_color_names (struct color_name
**color_names
)
409 for (i
= 0; color_names
[i
]; i
++)
411 free_null (color_names
[i
]->name
);
412 free_null (color_names
[i
]->orig
);
413 free_null (color_names
[i
]);
418 process_options (unsigned int arg_cnt
, char **option_strings
, bool *bold
, const struct color
**colors
, const char **file
, FILE **stream
)
422 char *color
, *p
, *str
;
425 const char *color_string
= arg_cnt
>= 1 ? option_strings
[0] : NULL
;
426 const char *file_string
= arg_cnt
== 2 ? option_strings
[1] : NULL
;
428 assert (color_string
);
430 if (streq (color_string
, "-"))
433 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen cannot be used as color string");
435 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen must be preceeded by color string");
438 ret
= stat (color_string
, &sb
);
440 /* Ensure that we don't fail if there's a file with one or more
441 color names in its path. */
446 const char *color
= color_string
;
448 for (c
= 1; c
<= 2 && *color
; c
++)
450 bool matched
= false;
452 for (i
= 0; i
< tables
[FOREGROUND
].count
; i
++)
454 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
456 if ((p
= strstr (color
, entry
->name
)) && p
== color
)
458 color
= p
+ strlen (entry
->name
);
463 if (matched
&& *color
== COLOR_SEP_CHAR
&& *(color
+ 1))
469 have_file
= (*color
!= '\0');
474 vfprintf_fail (formats
[FMT_GENERIC
], "file cannot be used as color string");
476 vfprintf_fail (formats
[FMT_GENERIC
], "file must be preceeded by color string");
480 if ((p
= strchr (color_string
, COLOR_SEP_CHAR
)))
482 if (p
== color_string
)
483 vfprintf_fail (formats
[FMT_GENERIC
], "foreground color missing");
484 else if (p
== color_string
+ strlen (color_string
) - 1)
485 vfprintf_fail (formats
[FMT_GENERIC
], "background color missing");
486 else if (strchr (++p
, COLOR_SEP_CHAR
))
487 vfprintf_fail (formats
[FMT_GENERIC
], "one color pair allowed only");
490 str
= xstrdup (color_string
);
493 for (index
= 0, color
= str
; *color
; index
++, color
= p
)
496 if ((sep
= strchr (color
, COLOR_SEP_CHAR
)))
502 p
= color
+ strlen (color
);
504 for (ch
= color
; *ch
; ch
++)
506 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be made of non-alphabetic characters");
508 for (ch
= color
+ 1; *ch
; ch
++)
510 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be in mixed lower/upper case");
512 if (streq (color
, "None"))
513 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be bold");
515 if (isupper (*color
))
523 vfprintf_fail (formats
[FMT_COLOR
], tables
[BACKGROUND
].desc
, color
, "cannot be bold");
525 default: /* never reached */
530 color_names
[index
] = xcalloc (1, sizeof (struct color_name
));
532 color_names
[index
]->orig
= xstrdup (color
);
534 for (ch
= color
; *ch
; ch
++)
537 color_names
[index
]->name
= xstrdup (color
);
542 assert (color_names
[FOREGROUND
]);
544 if (color_names
[BACKGROUND
])
547 unsigned int color_sets
[2][2] = { { FOREGROUND
, BACKGROUND
}, { BACKGROUND
, FOREGROUND
} };
548 for (i
= 0; i
< 2; i
++)
550 unsigned int color1
= color_sets
[i
][0];
551 unsigned int color2
= color_sets
[i
][1];
552 if (CHECK_COLORS_RANDOM (color1
, color2
))
553 vfprintf_fail (formats
[FMT_RANDOM
], tables
[color1
].desc
, color_names
[color1
]->orig
, "cannot be combined with", color_names
[color2
]->orig
);
557 find_color_entries (color_names
, colors
);
558 free_color_names (color_names
);
560 if (!colors
[FOREGROUND
]->code
&& colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
561 find_color_entry ("default", FOREGROUND
, colors
);
563 process_file_option (file_string
, file
, stream
);
567 process_file_option (const char *file_string
, const char **file
, FILE **stream
)
571 if (streq (file_string
, "-"))
576 const char *file
= file_string
;
581 ret
= stat (file
, &sb
);
584 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
586 if (!(S_ISREG (sb
.st_mode
) || S_ISLNK (sb
.st_mode
) || S_ISFIFO (sb
.st_mode
)))
587 vfprintf_fail (formats
[FMT_FILE
], file
, "unrecognized file type");
591 s
= fopen (file
, "r");
593 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
607 #define MERGE_PRINT_LINE(part_line, line, flags, check_eof) do { \
608 char *current_line, *merged_line = NULL; \
611 merged_line = str_concat (part_line, line); \
612 free_null (part_line); \
614 current_line = merged_line ? merged_line : (char *)line; \
615 if (!check_eof || *current_line != '\0') \
616 print_line (colors, bold, current_line, flags); \
617 free (merged_line); \
621 read_print_stream (bool bold
, const struct color
**colors
, const char *file
, FILE *stream
, enum stream_mode mode
)
623 char buf
[BUF_SIZE
], *part_line
= NULL
;
624 unsigned int flags
= 0;
625 bool first
= false, always
= false;
635 default: /* never reached */
639 while (!feof (stream
))
644 memset (buf
, '\0', BUF_SIZE
);
645 bytes_read
= fread (buf
, 1, BUF_SIZE
- 1, stream
);
646 if (bytes_read
!= (BUF_SIZE
- 1) && ferror (stream
))
647 vfprintf_fail (formats
[FMT_ERROR
], BUF_SIZE
- 1, "read");
649 LOOP
: while ((eol
= strpbrk (line
, "\n\r")))
659 if (*(eol
+ 1) == '\n')
662 else if (*eol
== '\n')
665 vfprintf_fail (formats
[FMT_FILE
], file
, "unrecognized line ending");
668 p
= eol
+ SKIP_LINE_ENDINGS (flags
);
672 unsigned int count
= sizeof (endings
) / sizeof (struct ending
);
673 for (i
= 0; i
< count
; i
++)
675 if (flags
& endings
[i
].flags
)
678 if ((p
= strstr (eol
, endings
[i
].newline
)) && p
== eol
)
687 p
= eol
+ SKIP_LINE_ENDINGS (flags
);
690 MERGE_PRINT_LINE (part_line
, line
, flags
, false);
694 MERGE_PRINT_LINE (part_line
, line
, 0, true);
698 if (!clean
&& !clean_all
) /* efficiency */
699 print_line (colors
, bold
, line
, 0);
701 part_line
= xstrdup (line
);
704 char *merged_line
= str_concat (part_line
, line
);
706 part_line
= merged_line
;
713 find_color_entries (struct color_name
**color_names
, const struct color
**colors
)
719 gettimeofday (&tv
, NULL
);
720 srand (tv
.tv_usec
* tv
.tv_sec
);
722 for (index
= 0; color_names
[index
]; index
++)
724 const char *color_name
= color_names
[index
]->name
;
726 const unsigned int count
= tables
[index
].count
;
727 const struct color
*const color_entries
= tables
[index
].entries
;
729 if (streq (color_name
, "random"))
735 i
= rand() % (count
- 2) + 1; /* omit color none and default */
739 /* --exclude-random */
740 if (exclude
&& streq (exclude
, color_entries
[i
].name
))
742 else if (color_names
[BACKGROUND
] && streq (color_names
[BACKGROUND
]->name
, color_entries
[i
].name
))
746 if (streq (colors
[FOREGROUND
]->name
, color_entries
[i
].name
))
749 default: /* never reached */
752 } while (excludable
);
753 colors
[index
] = (struct color
*)&color_entries
[i
];
756 find_color_entry (color_name
, index
, colors
);
761 find_color_entry (const char *const color_name
, unsigned int index
, const struct color
**colors
)
766 const unsigned int count
= tables
[index
].count
;
767 const struct color
*const color_entries
= tables
[index
].entries
;
769 for (i
= 0; i
< count
; i
++)
770 if (streq (color_name
, color_entries
[i
].name
))
772 colors
[index
] = (struct color
*)&color_entries
[i
];
777 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color_name
, "not recognized");
781 print_line (const struct color
**colors
, bool bold
, const char *const line
, unsigned int flags
)
784 if (clean
|| clean_all
)
788 if (colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
789 printf ("\033[%s", colors
[BACKGROUND
]->code
);
790 if (colors
[FOREGROUND
]->code
)
791 printf ("\033[%s%s%s\033[0m", bold
? "1;" : "", colors
[FOREGROUND
]->code
, line
);
793 printf (formats
[FMT_GENERIC
], line
);
802 print_clean (const char *line
)
805 char ***offsets
= NULL
;
806 unsigned int count
= 0, i
= 0;
811 if (*p
== 27 && *(p
+ 1) == '[')
813 const char *begin
= p
;
817 while (isdigit (*p
) || *p
== ';')
822 bool check_values
, first
= true;
827 check_values
= false;
828 if (!first
&& !isdigit (*p
))
835 else /* check range */
840 const unsigned int digits
= p
- digit
;
841 for (i
= 0; i
< digits
; i
++)
845 if (!((value
== 0 || value
== 1) /* attributes */
846 || (value
>= 30 && value
<= 37) /* foreground colors */
847 || (value
>= 40 && value
<= 47) /* background colors */
848 || (value
== 39 || value
== 49))) /* default colors */
857 } while (check_values
);
861 const char *end
= p
++;
863 offsets
= xmalloc (++count
* sizeof (char **));
865 offsets
= xrealloc (offsets
, ++count
* sizeof (char **));
866 offsets
[i
] = xmalloc (2 * sizeof (char *));
867 offsets
[i
][0] = (char *)begin
; /* ESC */
868 offsets
[i
][1] = (char *)end
; /* m */
879 print_free_offsets (line
, offsets
, count
);
881 printf (formats
[FMT_GENERIC
], line
);
884 #define SET_CHAR(offset, new, old) \
888 #define RESTORE_CHAR(offset, old) \
892 print_free_offsets (const char *line
, char ***offsets
, unsigned int count
)
897 SET_CHAR (offsets
[0][0], '\0', &ch
);
898 printf (formats
[FMT_GENERIC
], line
);
899 RESTORE_CHAR (offsets
[0][0], ch
);
901 for (i
= 0; i
< count
; i
++)
904 bool next_offset
= false;
907 SET_CHAR (offsets
[i
+ 1][0], '\0', &ch
);
910 printf (formats
[FMT_GENERIC
], offsets
[i
][1] + 1);
912 RESTORE_CHAR (offsets
[i
+ 1][0], ch
);
914 for (i
= 0; i
< count
; i
++)
915 free_null (offsets
[i
]);
920 malloc_wrap (size_t size
)
922 void *p
= malloc (size
);
929 calloc_wrap (size_t nmemb
, size_t size
)
931 void *p
= calloc (nmemb
, size
);
938 realloc_wrap (void *ptr
, size_t size
)
940 void *p
= realloc (ptr
, size
);
947 malloc_wrap_debug (size_t size
, const char *file
, unsigned int line
)
949 void *p
= malloc (size
);
951 MEM_ALLOC_FAIL_DEBUG (file
, line
);
956 calloc_wrap_debug (size_t nmemb
, size_t size
, const char *file
, unsigned int line
)
958 void *p
= calloc (nmemb
, size
);
960 MEM_ALLOC_FAIL_DEBUG (file
, line
);
965 realloc_wrap_debug (void *ptr
, size_t size
, const char *file
, unsigned int line
)
967 void *p
= realloc (ptr
, size
);
969 MEM_ALLOC_FAIL_DEBUG (file
, line
);
974 free_wrap (void **ptr
)
981 strdup_wrap (const char *str
)
983 const size_t len
= strlen (str
) + 1;
984 char *p
= xmalloc (len
);
985 strncpy (p
, str
, len
);
990 str_concat (const char *str1
, const char *str2
)
992 const size_t len
= strlen (str1
) + strlen (str2
) + 1;
995 p
= str
= xmalloc (len
);
996 strncpy (p
, str1
, strlen (str1
));
998 strncpy (p
, str2
, strlen (str2
));
1006 vfprintf_fail (const char *fmt
, ...)
1009 fprintf (stderr
, "%s: ", program_name
);
1011 vfprintf (stderr
, fmt
, ap
);
1013 fprintf (stderr
, "\n");
1014 exit (EXIT_FAILURE
);
1018 stack_var (void ***list
, unsigned int *stacked
, unsigned int index
, void *ptr
)
1020 /* nothing to stack */
1024 *list
= xmalloc (sizeof (void *));
1028 for (i
= 0; i
< *stacked
; i
++)
1032 return; /* reused */
1034 *list
= xrealloc (*list
, (*stacked
+ 1) * sizeof (void *));
1036 (*list
)[index
] = ptr
;
1041 release_var (void **list
, unsigned int stacked
, void **ptr
)
1044 /* nothing to release */
1047 for (i
= 0; i
< stacked
; i
++)
1048 if (list
[i
] == *ptr
)