]>
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)
44 #define xmalloc(size) malloc_wrap(size, __FILE__, __LINE__)
45 #define xrealloc(ptr, size) realloc_wrap(ptr, size, __FILE__, __LINE__)
46 #define xstrdup(str) strdup_wrap(str, __FILE__, __LINE__)
48 #if !defined BUF_SIZE || BUF_SIZE <= 0
50 # define BUF_SIZE 4096 + 1
56 #define SKIP_LINE_ENDINGS(flags) (((flags) & CR) && ((flags) & LF) ? 2 : 1)
58 #define STACK_VAR(ptr) do { \
59 stack_var (&vars_list, &stacked_vars, stacked_vars, ptr); \
62 #define RELEASE_VAR(ptr) do { \
63 release_var (vars_list, stacked_vars, (void **)&ptr); \
67 # define MEM_ALLOC_FAIL(file, line) do { \
68 fprintf (stderr, "Memory allocation failure in source file %s, line %d\n", file, line); \
72 # define MEM_ALLOC_FAIL(file, line) do { \
73 fprintf (stderr, "%s: memory allocation failure\n", program_name); \
78 #define ABORT_TRACE() \
79 fprintf (stderr, "Aborting in source file %s, line %d\n", __FILE__, __LINE__); \
82 #define CHECK_COLORS_RANDOM(color1, color2) \
83 streq (color_names[color1]->name, "random") \
84 && (streq (color_names[color2]->name, "none") \
85 || streq (color_names[color2]->name, "default")) \
87 #define VERSION "0.48"
89 typedef unsigned short bool;
98 static struct color_name
*color_names
[3] = { NULL
, NULL
, NULL
};
105 static const struct color fg_colors
[] = {
113 { "magenta", "36m" },
115 { "default", "39m" },
117 static const struct color bg_colors
[] = {
125 { "magenta", "46m" },
127 { "default", "49m" },
137 static const char *formats
[] = {
139 "%s color '%s' %s", /* color */
140 "%s color '%s' %s '%s'", /* random */
141 "less than %d bytes %s", /* error */
145 enum { FOREGROUND
, BACKGROUND
};
147 static const struct {
148 struct color
const *entries
;
152 { fg_colors
, sizeof (fg_colors
) / sizeof (struct color
), "foreground" },
153 { bg_colors
, sizeof (bg_colors
) / sizeof (struct color
), "background" },
156 enum stream_mode
{ SCAN_FIRST
= 1, SCAN_ALWAYS
};
160 const char newline
[3];
163 static const struct ending endings
[] = {
169 static FILE *stream
= NULL
;
171 static unsigned int stacked_vars
= 0;
172 static void **vars_list
= NULL
;
174 static char *exclude
= NULL
;
176 static const char *program_name
;
178 static void print_help (void);
179 static void print_version (void);
180 static void cleanup (void);
181 static void free_color_names (struct color_name
**);
182 static void process_options (unsigned int, char **, bool *, const struct color
**, const char **, FILE **);
183 static void read_print_stream (bool, const struct color
**, const char *, FILE *, enum stream_mode
);
184 static void find_color_entries (struct color_name
**, const struct color
**);
185 static void find_color_entry (const char *const, unsigned int, const struct color
**);
186 static void print_line (const struct color
**, bool, const char * const, unsigned int);
187 static void *malloc_wrap (size_t, const char *, unsigned int);
188 static void *realloc_wrap (void *, size_t, const char *, unsigned int);
189 static char *strdup_wrap (const char *, const char *, unsigned int);
190 static void vfprintf_fail (const char *, ...);
191 static void stack_var (void ***, unsigned int *, unsigned int, void *);
192 static void release_var (void **, unsigned int, void **);
198 main (int argc
, char **argv
)
200 unsigned int arg_cnt
= 0;
202 bool invalid_opt
= false;
205 struct option long_opts
[] = {
206 { "exclude-random", required_argument
, NULL
, 'e' },
207 { "help", no_argument
, NULL
, 'h' },
208 { "version", no_argument
, NULL
, 'v' },
214 const struct color
*colors
[2] = {
215 NULL
, /* foreground */
216 NULL
, /* background */
221 enum stream_mode mode
= SCAN_FIRST
;
223 program_name
= argv
[0];
226 setvbuf (stdout
, NULL
, _IOLBF
, 0);
228 while ((opt
= getopt_long (argc
, argv
, "hv", long_opts
, NULL
)) != -1)
234 exclude
= xstrdup (optarg
);
236 for (p
= exclude
; *p
; p
++)
238 if (streq (exclude
, "random"))
239 vfprintf_fail (formats
[FMT_GENERIC
], "--exclude-random switch must be provided a color");
251 default: /* never reached */
256 arg_cnt
= argc
- optind
;
258 if (arg_cnt
== 0 || arg_cnt
> 2 || invalid_opt
)
264 process_options (arg_cnt
, &argv
[optind
], &bold
, colors
, &file
, &stream
);
265 read_print_stream (bold
, colors
, file
, stream
, mode
);
267 RELEASE_VAR (exclude
);
277 printf ("Usage: %s (foreground) OR (foreground)/(background) [-|file]\n\n", program_name
);
278 printf ("\tColors (foreground) (background)\n");
279 for (i
= 0; i
< tables
[FOREGROUND
].count
; i
++)
281 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
282 const char *name
= entry
->name
;
283 const char *code
= entry
->code
;
285 printf ("\t\t{\033[%s#\033[0m} [%c%c]%s%*s%s\n",
286 code
, toupper (*name
), *name
, name
+ 1, 10 - (int)strlen (name
), " ", name
);
288 printf ("\t\t{-} %s%*s%s\n", name
, 13 - (int)strlen (name
), " ", name
);
290 printf ("\t\t{*} [Rr]%s%*s%s [--exclude-random=<foreground color>]\n", "andom", 10 - (int)strlen ("random"), " ", "random");
292 printf ("\n\tFirst character of color name in upper case denotes increased intensity,\n");
293 printf ("\twhereas for lower case colors will be of normal intensity.\n");
295 printf ("\n\tOptions\n");
296 printf ("\t\t-h, --help\n");
297 printf ("\t\t-v, --version\n\n");
304 printf ("%s v%s (compiled at %s, %s)\n", "colorize", VERSION
, __DATE__
, __TIME__
);
306 c_flags
= to_str (CFLAGS
);
310 printf ("Compiler flags: %s\n", c_flags
);
311 printf ("Buffer size: %d bytes\n", BUF_SIZE
- 1);
317 free_color_names (color_names
);
319 if (stream
&& fileno (stream
) != STDIN_FILENO
)
325 for (i
= 0; i
< stacked_vars
; i
++)
337 free_color_names (struct color_name
**color_names
)
340 for (i
= 0; color_names
[i
]; i
++)
342 free (color_names
[i
]->name
);
343 color_names
[i
]->name
= NULL
;
344 free (color_names
[i
]->orig
);
345 color_names
[i
]->orig
= NULL
;
346 free (color_names
[i
]);
347 color_names
[i
] = NULL
;
352 process_options (unsigned int arg_cnt
, char **option_strings
, bool *bold
, const struct color
**colors
, const char **file
, FILE **stream
)
356 char *color
, *p
, *str
;
359 const char *color_string
= arg_cnt
>= 1 ? option_strings
[0] : NULL
;
360 const char *file_string
= arg_cnt
== 2 ? option_strings
[1] : NULL
;
362 assert (color_string
);
364 if (streq (color_string
, "-"))
367 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen cannot be used as color string");
369 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen must be preceeded by color string");
372 ret
= stat (color_string
, &sb
);
374 /* Ensure that we don't fail if there's a file with one or more
375 color names in its path. */
380 const char *color
= color_string
;
382 for (c
= 1; c
<= 2 && *color
; c
++)
384 bool matched
= false;
386 for (i
= 0; i
< tables
[FOREGROUND
].count
; i
++)
388 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
390 if ((p
= strstr (color
, entry
->name
)) && p
== color
)
392 color
= p
+ strlen (entry
->name
);
397 if (matched
&& *color
== '/' && *(color
+ 1))
403 have_file
= (*color
!= '\0');
408 vfprintf_fail (formats
[FMT_GENERIC
], "file cannot be used as color string");
410 vfprintf_fail (formats
[FMT_GENERIC
], "file must be preceeded by color string");
414 if ((p
= strchr (color_string
, '/')))
416 if (p
== color_string
)
417 vfprintf_fail (formats
[FMT_GENERIC
], "foreground color missing");
418 else if (p
== color_string
+ strlen (color_string
) - 1)
419 vfprintf_fail (formats
[FMT_GENERIC
], "background color missing");
420 else if (strchr (++p
, '/'))
421 vfprintf_fail (formats
[FMT_GENERIC
], "one color pair allowed only");
424 str
= xstrdup (color_string
);
427 for (index
= 0, color
= str
; *color
; index
++, color
= p
)
430 if ((sep
= strchr (color
, '/')))
436 p
= color
+ strlen (color
);
438 for (ch
= color
; *ch
; ch
++)
440 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be made of non-alphabetic characters");
442 for (ch
= color
+ 1; *ch
; ch
++)
444 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be in mixed lower/upper case");
446 if (streq (color
, "None"))
447 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be bold");
449 if (isupper (*color
))
457 vfprintf_fail (formats
[FMT_COLOR
], tables
[BACKGROUND
].desc
, color
, "cannot be bold");
459 default: /* never reached */
464 color_names
[index
] = xmalloc (sizeof (struct color_name
));
466 color_names
[index
]->orig
= xstrdup (color
);
468 for (ch
= color
; *ch
; ch
++)
471 color_names
[index
]->name
= xstrdup (color
);
476 assert (color_names
[FOREGROUND
]);
478 if (color_names
[BACKGROUND
])
481 unsigned int color_sets
[2][2] = { { FOREGROUND
, BACKGROUND
}, { BACKGROUND
, FOREGROUND
} };
482 for (i
= 0; i
< 2; i
++)
484 unsigned int color1
= color_sets
[i
][0];
485 unsigned int color2
= color_sets
[i
][1];
486 if (CHECK_COLORS_RANDOM (color1
, color2
))
487 vfprintf_fail (formats
[FMT_RANDOM
], tables
[color1
].desc
, color_names
[color1
]->orig
, "cannot be combined with", color_names
[color2
]->orig
);
491 find_color_entries (color_names
, colors
);
492 free_color_names (color_names
);
494 if (!colors
[FOREGROUND
]->code
&& colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
495 find_color_entry ("default", FOREGROUND
, colors
);
499 if (streq (file_string
, "-"))
504 const char *file
= file_string
;
509 ret
= stat (file
, &sb
);
512 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
514 if (!(S_ISREG (sb
.st_mode
) || S_ISLNK (sb
.st_mode
) || S_ISFIFO (sb
.st_mode
)))
515 vfprintf_fail (formats
[FMT_FILE
], file
, "unrecognized file type");
519 s
= fopen (file
, "r");
521 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
536 read_print_stream (bool bold
, const struct color
**colors
, const char *file
, FILE *stream
, enum stream_mode mode
)
539 unsigned int flags
= 0;
540 bool first
= false, always
= false;
550 default: /* never reached */
554 while (!feof (stream
))
559 memset (buf
, '\0', BUF_SIZE
);
560 bytes_read
= fread (buf
, 1, BUF_SIZE
- 1, stream
);
561 if (bytes_read
!= (BUF_SIZE
- 1) && ferror (stream
))
562 vfprintf_fail (formats
[FMT_ERROR
], BUF_SIZE
- 1, "read");
564 LOOP
: while ((eol
= strpbrk (line
, "\n\r")))
574 if (*(eol
+ 1) == '\n')
577 else if (*eol
== '\n')
580 vfprintf_fail (formats
[FMT_FILE
], file
, "unrecognized line ending");
583 p
= eol
+ SKIP_LINE_ENDINGS (flags
);
587 unsigned int count
= sizeof (endings
) / sizeof (struct ending
);
588 for (i
= 0; i
< count
; i
++)
590 if (flags
& endings
[i
].flags
)
593 if ((p
= strstr (eol
, endings
[i
].newline
)) && p
== eol
)
602 p
= eol
+ SKIP_LINE_ENDINGS (flags
);
605 print_line (colors
, bold
, line
, flags
);
608 print_line (colors
, bold
, line
, 0);
613 find_color_entries (struct color_name
**color_names
, const struct color
**colors
)
619 gettimeofday (&tv
, NULL
);
620 srand (tv
.tv_usec
* tv
.tv_sec
);
622 for (index
= 0; color_names
[index
]; index
++)
624 const char *color_name
= color_names
[index
]->name
;
626 const unsigned int count
= tables
[index
].count
;
627 const struct color
*const color_entries
= tables
[index
].entries
;
629 if (streq (color_name
, "random"))
635 i
= rand() % (count
- 2) + 1; /* omit color none and default */
639 /* --exclude-random */
640 if (exclude
&& streq (exclude
, color_entries
[i
].name
))
642 else if (color_names
[BACKGROUND
] && streq (color_names
[BACKGROUND
]->name
, color_entries
[i
].name
))
646 if (streq (colors
[FOREGROUND
]->name
, color_entries
[i
].name
))
649 default: /* never reached */
652 } while (excludable
);
653 colors
[index
] = (struct color
*)&color_entries
[i
];
656 find_color_entry (color_name
, index
, colors
);
661 find_color_entry (const char *const color_name
, unsigned int index
, const struct color
**colors
)
666 const unsigned int count
= tables
[index
].count
;
667 const struct color
*const color_entries
= tables
[index
].entries
;
669 for (i
= 0; i
< count
; i
++)
670 if (streq (color_name
, color_entries
[i
].name
))
672 colors
[index
] = (struct color
*)&color_entries
[i
];
677 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color_name
, "not recognized");
681 print_line (const struct color
**colors
, bool bold
, const char *const line
, unsigned int flags
)
683 if (colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
684 printf ("\033[%s", colors
[BACKGROUND
]->code
);
685 if (colors
[FOREGROUND
]->code
)
686 printf ("\033[%s%s%s\033[0m", bold
? "1;" : "", colors
[FOREGROUND
]->code
, line
);
688 printf (formats
[FMT_GENERIC
], line
);
696 malloc_wrap (size_t size
, const char *file
, unsigned int line
)
698 void *p
= malloc (size
);
700 MEM_ALLOC_FAIL (file
, line
);
705 realloc_wrap (void *ptr
, size_t size
, const char *file
, unsigned int line
)
707 void *p
= realloc (ptr
, size
);
709 MEM_ALLOC_FAIL (file
, line
);
714 strdup_wrap (const char *str
, const char *file
, unsigned int line
)
716 const unsigned int len
= strlen (str
) + 1;
717 char *p
= malloc (len
);
719 MEM_ALLOC_FAIL (file
, line
);
720 strncpy (p
, str
, len
);
725 vfprintf_fail (const char *fmt
, ...)
728 fprintf (stderr
, "%s: ", program_name
);
730 vfprintf (stderr
, fmt
, ap
);
732 fprintf (stderr
, "\n");
737 stack_var (void ***list
, unsigned int *stacked
, unsigned int index
, void *ptr
)
739 /* nothing to stack */
743 *list
= xmalloc (sizeof (void *));
747 for (i
= 0; i
< *stacked
; i
++)
753 *list
= xrealloc (*list
, (*stacked
+ 1) * sizeof (void *));
755 (*list
)[index
] = ptr
;
760 release_var (void **list
, unsigned int stacked
, void **ptr
)
763 /* nothing to release */
766 for (i
= 0; i
< stacked
; i
++)