]>
git.refcnt.org Git - colorize.git/blob - colorize.c
36d7a0a228baa62400697051b7cd044a9ad98144
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/>.
22 #define _POSIX_C_SOURCE 200809L
32 #include <sys/types.h>
42 #define to_str(arg) str(arg)
44 #define streq(s1, s2) (strcmp (s1, s2) == 0)
47 # define xmalloc(size) malloc_wrap_debug(size, __FILE__, __LINE__)
48 # define xcalloc(nmemb, size) calloc_wrap_debug(nmemb, size, __FILE__, __LINE__)
49 # define xrealloc(ptr, size) realloc_wrap_debug(ptr, size, __FILE__, __LINE__)
51 # define xmalloc(size) malloc_wrap(size)
52 # define xcalloc(nmemb, size) calloc_wrap(nmemb, size)
53 # define xrealloc(ptr, size) realloc_wrap(ptr, size)
56 #define free_null(ptr) free_wrap((void **)&ptr)
57 #define xstrdup(str) strdup_wrap(str)
63 # define BUF_SIZE 4096
69 #define SKIP_LINE_ENDINGS(flags) (((flags) & CR) && ((flags) & LF) ? 2 : 1)
71 #define STACK_VAR(ptr) do { \
72 stack_var (&vars_list, &stacked_vars, stacked_vars, ptr); \
75 #define RELEASE_VAR(ptr) do { \
76 release_var (vars_list, stacked_vars, (void **)&ptr); \
79 #define MEM_ALLOC_FAIL_DEBUG(file, line) do { \
80 fprintf (stderr, "Memory allocation failure in source file %s, line %u\n", file, line); \
83 #define MEM_ALLOC_FAIL() do { \
84 fprintf (stderr, "%s: memory allocation failure\n", program_name); \
88 #define ABORT_TRACE() \
89 fprintf (stderr, "Aborting in source file %s, line %u\n", __FILE__, __LINE__); \
92 #define CHECK_COLORS_RANDOM(color1, color2) \
93 streq (color_names[color1]->name, "random") \
94 && (streq (color_names[color2]->name, "none") \
95 || streq (color_names[color2]->name, "default")) \
97 #define COLOR_SEP_CHAR '/'
99 #define VERSION "0.52"
101 typedef unsigned short bool;
103 enum { false, true };
110 static struct color_name
*color_names
[3] = { NULL
, NULL
, NULL
};
117 static const struct color fg_colors
[] = {
125 { "magenta", "36m" },
127 { "default", "39m" },
129 static const struct color bg_colors
[] = {
137 { "magenta", "46m" },
139 { "default", "49m" },
149 static const char *formats
[] = {
151 "%s color '%s' %s", /* color */
152 "%s color '%s' %s '%s'", /* random */
153 "less than %u bytes %s", /* error */
157 enum { FOREGROUND
, BACKGROUND
};
159 static const struct {
160 struct color
const *entries
;
164 { fg_colors
, sizeof (fg_colors
) / sizeof (struct color
), "foreground" },
165 { bg_colors
, sizeof (bg_colors
) / sizeof (struct color
), "background" },
168 static FILE *stream
= NULL
;
170 static unsigned int stacked_vars
= 0;
171 static void **vars_list
= NULL
;
173 static bool clean
= false;
174 static bool clean_all
= false;
176 static char *exclude
= NULL
;
178 static const char *program_name
;
180 static void print_help (void);
181 static void print_version (void);
182 static void cleanup (void);
183 static void free_color_names (struct color_name
**);
184 static void process_args (unsigned int, char **, bool *, const struct color
**, const char **, FILE **);
185 static void process_file_arg (const char *, const char **, FILE **);
186 static void read_print_stream (bool, const struct color
**, const char *, FILE *);
187 static void find_color_entries (struct color_name
**, const struct color
**);
188 static void find_color_entry (const struct color_name
*, unsigned int, const struct color
**);
189 static void print_line (bool, const struct color
**, const char * const, unsigned int);
190 static void print_clean (const char *);
191 static void print_free_offsets (const char *, char ***, unsigned int);
192 static void *malloc_wrap (size_t);
193 static void *calloc_wrap (size_t, size_t);
194 static void *realloc_wrap (void *, size_t);
195 static void *malloc_wrap_debug (size_t, const char *, unsigned int);
196 static void *calloc_wrap_debug (size_t, size_t, const char *, unsigned int);
197 static void *realloc_wrap_debug (void *, size_t, const char *, unsigned int);
198 static void free_wrap (void **);
199 static char *strdup_wrap (const char *);
200 static char *str_concat (const char *, const char *);
201 static bool has_color_name (const char *, const char *);
202 static void vfprintf_diag (const char *, ...);
203 static void vfprintf_fail (const char *, ...);
204 static void stack_var (void ***, unsigned int *, unsigned int, void *);
205 static void release_var (void **, unsigned int, void **);
207 #define SET_OPT_TYPE(type) \
216 main (int argc
, char **argv
)
218 unsigned int arg_cnt
= 0;
228 int opt
, opt_type
= 0;
229 struct option long_opts
[] = {
230 { "clean", no_argument
, &opt_type
, OPT_CLEAN
},
231 { "clean-all", no_argument
, &opt_type
, OPT_CLEAN_ALL
},
232 { "exclude-random", required_argument
, &opt_type
, OPT_EXCLUDE_RANDOM
},
233 { "help", no_argument
, &opt_type
, OPT_HELP
},
234 { "version", no_argument
, &opt_type
, OPT_VERSION
},
235 { NULL
, 0, NULL
, 0 },
240 const struct color
*colors
[2] = {
241 NULL
, /* foreground */
242 NULL
, /* background */
245 const char *file
= NULL
;
247 program_name
= argv
[0];
250 setvbuf (stdout
, NULL
, _IOLBF
, 0);
252 while ((opt
= getopt_long (argc
, argv
, "hv", long_opts
, NULL
)) != -1)
257 case 0: /* long opts */
266 case OPT_EXCLUDE_RANDOM
: {
269 exclude
= xstrdup (optarg
);
271 for (i
= 1; i
< tables
[FOREGROUND
].count
- 1; i
++) /* skip color none and default */
273 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
274 if (streq (exclude
, entry
->name
))
281 vfprintf_fail (formats
[FMT_GENERIC
], "--exclude-random switch must be provided a plain color");
290 default: /* never reached */
295 SET_OPT_TYPE (OPT_HELP
);
297 SET_OPT_TYPE (OPT_VERSION
);
301 default: /* never reached */
306 arg_cnt
= argc
- optind
;
308 if (clean
|| clean_all
)
310 if (clean
&& clean_all
)
311 vfprintf_fail (formats
[FMT_GENERIC
], "--clean and --clean-all switch are mutually exclusive");
314 const char *format
= "%s %s";
315 const char *message
= "switch cannot be used with more than one file";
317 vfprintf_fail (format
, "--clean", message
);
319 vfprintf_fail (format
, "--clean-all", message
);
324 if (arg_cnt
== 0 || arg_cnt
> 2)
326 vfprintf_diag ("%u arguments provided, expected 1-2 arguments or option", arg_cnt
);
332 if (clean
|| clean_all
)
333 process_file_arg (argv
[optind
], &file
, &stream
);
335 process_args (arg_cnt
, &argv
[optind
], &bold
, colors
, &file
, &stream
);
336 read_print_stream (bold
, colors
, file
, stream
);
338 RELEASE_VAR (exclude
);
348 printf ("Usage: %s (foreground) OR (foreground)%c(background) OR --clean[-all] [-|file]\n\n", program_name
, COLOR_SEP_CHAR
);
349 printf ("\tColors (foreground) (background)\n");
350 for (i
= 0; i
< tables
[FOREGROUND
].count
; i
++)
352 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
353 const char *name
= entry
->name
;
354 const char *code
= entry
->code
;
356 printf ("\t\t{\033[%s#\033[0m} [%c%c]%s%*s%s\n",
357 code
, toupper (*name
), *name
, name
+ 1, 10 - (int)strlen (name
), " ", name
);
359 printf ("\t\t{-} %s%*s%s\n", name
, 13 - (int)strlen (name
), " ", name
);
361 printf ("\t\t{*} [Rr]%s%*s%s [--exclude-random=<foreground color>]\n", "andom", 10 - (int)strlen ("random"), " ", "random");
363 printf ("\n\tFirst character of color name in upper case denotes increased intensity,\n");
364 printf ("\twhereas for lower case colors will be of normal intensity.\n");
366 printf ("\n\tOptions\n");
367 printf ("\t\t --clean\n");
368 printf ("\t\t --clean-all\n");
369 printf ("\t\t --exclude-random\n");
370 printf ("\t\t-h, --help\n");
371 printf ("\t\t-v, --version\n\n");
380 c_flags
= to_str (CFLAGS
);
389 printf ("%s v%s (compiled at %s, %s)\n", "colorize", VERSION
, __DATE__
, __TIME__
);
390 printf ("Compiler flags: %s\n", c_flags
);
391 printf ("Buffer size: %u bytes\n", BUF_SIZE
);
392 printf ("Debugging: %s\n", debug
? "yes" : "no");
398 free_color_names (color_names
);
400 if (stream
&& fileno (stream
) != STDIN_FILENO
)
406 for (i
= 0; i
< stacked_vars
; i
++)
408 free_null (vars_list
[i
]);
410 free_null (vars_list
);
415 free_color_names (struct color_name
**color_names
)
418 for (i
= 0; color_names
[i
]; i
++)
420 free_null (color_names
[i
]->name
);
421 free_null (color_names
[i
]->orig
);
422 free_null (color_names
[i
]);
427 process_args (unsigned int arg_cnt
, char **arg_strings
, bool *bold
, const struct color
**colors
, const char **file
, FILE **stream
)
431 char *color
, *p
, *str
;
434 const char *color_string
= arg_cnt
>= 1 ? arg_strings
[0] : NULL
;
435 const char *file_string
= arg_cnt
== 2 ? arg_strings
[1] : NULL
;
437 assert (color_string
);
439 if (streq (color_string
, "-"))
442 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen cannot be used as color string");
444 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen must be preceeded by color string");
447 ret
= stat (color_string
, &sb
);
449 /* Ensure that we don't fail if there's a file with one or more
450 color names in its path. */
455 const char *color
= color_string
;
457 for (c
= 1; c
<= 2 && *color
; c
++)
459 bool matched
= false;
461 for (i
= 0; i
< tables
[FOREGROUND
].count
; i
++)
463 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
464 if (has_color_name (color
, entry
->name
))
466 color
+= strlen (entry
->name
);
471 if (!matched
&& has_color_name (color
, "random"))
473 color
+= strlen ("random");
476 if (matched
&& *color
== COLOR_SEP_CHAR
&& *(color
+ 1))
482 have_file
= (*color
!= '\0');
487 vfprintf_fail (formats
[FMT_GENERIC
], "file cannot be used as color string");
489 vfprintf_fail (formats
[FMT_GENERIC
], "file must be preceeded by color string");
493 if ((p
= strchr (color_string
, COLOR_SEP_CHAR
)))
495 if (p
== color_string
)
496 vfprintf_fail (formats
[FMT_GENERIC
], "foreground color missing");
497 else if (p
== color_string
+ strlen (color_string
) - 1)
498 vfprintf_fail (formats
[FMT_GENERIC
], "background color missing");
499 else if (strchr (++p
, COLOR_SEP_CHAR
))
500 vfprintf_fail (formats
[FMT_GENERIC
], "one color pair allowed only");
503 str
= xstrdup (color_string
);
506 for (index
= 0, color
= str
; *color
; index
++, color
= p
)
511 if ((sep
= strchr (color
, COLOR_SEP_CHAR
)))
517 p
= color
+ strlen (color
);
520 for (ch
= color
; *ch
; ch
++)
522 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be made of non-alphabetic characters");
524 for (ch
= color
+ 1; *ch
; ch
++)
526 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be in mixed lower/upper case");
528 if (streq (color
, "None"))
529 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be bold");
531 if (isupper (*color
))
539 vfprintf_fail (formats
[FMT_COLOR
], tables
[BACKGROUND
].desc
, color
, "cannot be bold");
541 default: /* never reached */
546 color_names
[index
] = xcalloc (1, sizeof (struct color_name
));
548 color_names
[index
]->orig
= xstrdup (color
);
550 for (ch
= color
; *ch
; ch
++)
553 color_names
[index
]->name
= xstrdup (color
);
558 assert (color_names
[FOREGROUND
]);
560 if (color_names
[BACKGROUND
])
563 unsigned int color_sets
[2][2] = { { FOREGROUND
, BACKGROUND
}, { BACKGROUND
, FOREGROUND
} };
564 for (i
= 0; i
< 2; i
++)
566 unsigned int color1
= color_sets
[i
][0];
567 unsigned int color2
= color_sets
[i
][1];
568 if (CHECK_COLORS_RANDOM (color1
, color2
))
569 vfprintf_fail (formats
[FMT_RANDOM
], tables
[color1
].desc
, color_names
[color1
]->orig
, "cannot be combined with", color_names
[color2
]->orig
);
573 find_color_entries (color_names
, colors
);
574 free_color_names (color_names
);
576 if (!colors
[FOREGROUND
]->code
&& colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
578 struct color_name color_name
;
579 color_name
.name
= color_name
.orig
= "default";
581 find_color_entry (&color_name
, FOREGROUND
, colors
);
584 process_file_arg (file_string
, file
, stream
);
588 process_file_arg (const char *file_string
, const char **file
, FILE **stream
)
592 if (streq (file_string
, "-"))
597 const char *file
= file_string
;
602 ret
= stat (file
, &sb
);
605 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
607 if (!(S_ISREG (sb
.st_mode
) || S_ISLNK (sb
.st_mode
) || S_ISFIFO (sb
.st_mode
)))
608 vfprintf_fail (formats
[FMT_FILE
], file
, "unrecognized file type");
612 s
= fopen (file
, "r");
614 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
629 #define MERGE_PRINT_LINE(part_line, line, flags, check_eof) do { \
630 char *current_line, *merged_line = NULL; \
633 merged_line = str_concat (part_line, line); \
634 free_null (part_line); \
636 current_line = merged_line ? merged_line : (char *)line; \
637 if (!check_eof || *current_line != '\0') \
638 print_line (bold, colors, current_line, flags); \
639 free (merged_line); \
643 read_print_stream (bool bold
, const struct color
**colors
, const char *file
, FILE *stream
)
645 char buf
[BUF_SIZE
+ 1], *part_line
= NULL
;
646 unsigned int flags
= 0;
648 while (!feof (stream
))
653 memset (buf
, '\0', BUF_SIZE
+ 1);
654 bytes_read
= fread (buf
, 1, BUF_SIZE
, stream
);
655 if (bytes_read
!= BUF_SIZE
&& ferror (stream
))
656 vfprintf_fail (formats
[FMT_ERROR
], BUF_SIZE
, "read");
658 while ((eol
= strpbrk (line
, "\n\r")))
665 if (*(eol
+ 1) == '\n')
668 else if (*eol
== '\n')
671 vfprintf_fail (formats
[FMT_FILE
], file
, "unrecognized line ending");
672 p
= eol
+ SKIP_LINE_ENDINGS (flags
);
674 MERGE_PRINT_LINE (part_line
, line
, flags
, false);
678 MERGE_PRINT_LINE (part_line
, line
, 0, true);
680 else if (*line
!= '\0')
682 if (!clean
&& !clean_all
) /* efficiency */
683 print_line (bold
, colors
, line
, 0);
685 part_line
= xstrdup (line
);
688 char *merged_line
= str_concat (part_line
, line
);
690 part_line
= merged_line
;
697 find_color_entries (struct color_name
**color_names
, const struct color
**colors
)
703 gettimeofday (&tv
, NULL
);
704 srand (tv
.tv_usec
* tv
.tv_sec
);
706 for (index
= 0; color_names
[index
]; index
++)
708 const char *color_name
= color_names
[index
]->name
;
710 const unsigned int count
= tables
[index
].count
;
711 const struct color
*const color_entries
= tables
[index
].entries
;
713 if (streq (color_name
, "random"))
719 i
= rand() % (count
- 2) + 1; /* omit color none and default */
723 /* --exclude-random */
724 if (exclude
&& streq (exclude
, color_entries
[i
].name
))
726 else if (color_names
[BACKGROUND
] && streq (color_names
[BACKGROUND
]->name
, color_entries
[i
].name
))
730 if (streq (colors
[FOREGROUND
]->name
, color_entries
[i
].name
))
733 default: /* never reached */
736 } while (excludable
);
737 colors
[index
] = (struct color
*)&color_entries
[i
];
740 find_color_entry (color_names
[index
], index
, colors
);
745 find_color_entry (const struct color_name
*color_name
, unsigned int index
, const struct color
**colors
)
750 const unsigned int count
= tables
[index
].count
;
751 const struct color
*const color_entries
= tables
[index
].entries
;
753 for (i
= 0; i
< count
; i
++)
754 if (streq (color_name
->name
, color_entries
[i
].name
))
756 colors
[index
] = (struct color
*)&color_entries
[i
];
761 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color_name
->orig
, "not recognized");
765 print_line (bool bold
, const struct color
**colors
, const char *const line
, unsigned int flags
)
768 if (clean
|| clean_all
)
772 /* Foreground color code is guaranteed to be set when background color code is present. */
773 if (colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
774 printf ("\033[%s", colors
[BACKGROUND
]->code
);
775 if (colors
[FOREGROUND
]->code
)
776 printf ("\033[%s%s%s\033[0m", bold
? "1;" : "", colors
[FOREGROUND
]->code
, line
);
778 printf (formats
[FMT_GENERIC
], line
);
787 print_clean (const char *line
)
790 char ***offsets
= NULL
;
791 unsigned int count
= 0, i
= 0;
796 if (*p
== 27 && *(p
+ 1) == '[')
798 const char *begin
= p
;
802 while (isdigit (*p
) || *p
== ';')
808 unsigned int iter
= 0;
811 check_values
= false;
820 else /* check range */
825 const unsigned int digits
= p
- digit
;
826 for (i
= 0; i
< digits
; i
++)
830 if (value
== 0) /* reset */
836 else if (value
== 1) /* bold */
838 bool discard
= false;
848 else if ((value
>= 30 && value
<= 37) || value
== 39) /* foreground colors */
850 else if ((value
>= 40 && value
<= 47) || value
== 49) /* background colors */
859 } while (iter
== 1 && check_values
);
863 const char *end
= p
++;
865 offsets
= xmalloc (++count
* sizeof (char **));
867 offsets
= xrealloc (offsets
, ++count
* sizeof (char **));
868 offsets
[i
] = xmalloc (2 * sizeof (char *));
869 offsets
[i
][0] = (char *)begin
; /* ESC */
870 offsets
[i
][1] = (char *)end
; /* m */
881 print_free_offsets (line
, offsets
, count
);
883 printf (formats
[FMT_GENERIC
], line
);
886 #define SET_CHAR(offset, new, old) \
890 #define RESTORE_CHAR(offset, old) \
894 print_free_offsets (const char *line
, char ***offsets
, unsigned int count
)
899 SET_CHAR (offsets
[0][0], '\0', &ch
);
900 printf (formats
[FMT_GENERIC
], line
);
901 RESTORE_CHAR (offsets
[0][0], ch
);
903 for (i
= 0; i
< count
; i
++)
906 bool next_offset
= false;
909 SET_CHAR (offsets
[i
+ 1][0], '\0', &ch
);
912 printf (formats
[FMT_GENERIC
], offsets
[i
][1] + 1);
914 RESTORE_CHAR (offsets
[i
+ 1][0], ch
);
916 for (i
= 0; i
< count
; i
++)
917 free_null (offsets
[i
]);
922 malloc_wrap (size_t size
)
924 void *p
= malloc (size
);
931 calloc_wrap (size_t nmemb
, size_t size
)
933 void *p
= calloc (nmemb
, size
);
940 realloc_wrap (void *ptr
, size_t size
)
942 void *p
= realloc (ptr
, size
);
949 malloc_wrap_debug (size_t size
, const char *file
, unsigned int line
)
951 void *p
= malloc (size
);
953 MEM_ALLOC_FAIL_DEBUG (file
, line
);
958 calloc_wrap_debug (size_t nmemb
, size_t size
, const char *file
, unsigned int line
)
960 void *p
= calloc (nmemb
, size
);
962 MEM_ALLOC_FAIL_DEBUG (file
, line
);
967 realloc_wrap_debug (void *ptr
, size_t size
, const char *file
, unsigned int line
)
969 void *p
= realloc (ptr
, size
);
971 MEM_ALLOC_FAIL_DEBUG (file
, line
);
976 free_wrap (void **ptr
)
983 strdup_wrap (const char *str
)
985 const size_t len
= strlen (str
) + 1;
986 char *p
= xmalloc (len
);
987 strncpy (p
, str
, len
);
992 str_concat (const char *str1
, const char *str2
)
994 const size_t len
= strlen (str1
) + strlen (str2
) + 1;
997 p
= str
= xmalloc (len
);
998 strncpy (p
, str1
, strlen (str1
));
1000 strncpy (p
, str2
, strlen (str2
));
1008 has_color_name (const char *str
, const char *name
)
1012 assert (strlen (str
));
1013 assert (strlen (name
));
1015 if (!(*str
== *name
|| *str
== toupper (*name
)))
1017 else if (*(name
+ 1) != '\0'
1018 && !((p
= strstr (str
+ 1, name
+ 1)) && p
== str
+ 1))
1024 #define DO_VFPRINTF(fmt) \
1026 fprintf (stderr, "%s: ", program_name); \
1027 va_start (ap, fmt); \
1028 vfprintf (stderr, fmt, ap); \
1030 fprintf (stderr, "\n"); \
1033 vfprintf_diag (const char *fmt
, ...)
1039 vfprintf_fail (const char *fmt
, ...)
1042 exit (EXIT_FAILURE
);
1046 stack_var (void ***list
, unsigned int *stacked
, unsigned int index
, void *ptr
)
1048 /* nothing to stack */
1052 *list
= xmalloc (sizeof (void *));
1056 for (i
= 0; i
< *stacked
; i
++)
1060 return; /* reused */
1062 *list
= xrealloc (*list
, (*stacked
+ 1) * sizeof (void *));
1064 (*list
)[index
] = ptr
;
1069 release_var (void **list
, unsigned int stacked
, void **ptr
)
1072 /* nothing to release */
1075 for (i
= 0; i
< stacked
; i
++)
1076 if (list
[i
] == *ptr
)