]>
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-2012 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>
38 #define to_str(arg) str(arg)
40 #define streq(s1, s2) (strcmp (s1, s2) == 0)
42 #if !defined BUF_SIZE || BUF_SIZE <= 0
44 # define BUF_SIZE 4096 + 1
50 #define SKIP_LINE_ENDINGS(flags) (((flags) & CR) && ((flags) & LF) ? 2 : 1)
52 #define STACK_VAR(ptr) do { \
53 stack_var (&vars_list, &stacked_vars, stacked_vars, ptr); \
56 #define RELEASE_VAR(ptr) do { \
57 release_var (vars_list, stacked_vars, (void **)&ptr); \
60 #define ABORT_TRACE() \
61 fprintf (stderr, "aborting in source file %s, line %d\n", __FILE__, __LINE__); \
64 #define CHECK_COLORS_RANDOM(color1, color2) \
65 streq (color_names[color1]->name, "random") \
66 && (streq (color_names[color2]->name, "none") \
67 || streq (color_names[color2]->name, "default")) \
69 #define VERSION "0.47"
71 typedef unsigned short bool;
80 static struct color_name
*color_names
[3] = { NULL
, NULL
, NULL
};
87 static const struct color fg_colors
[] = {
99 static const struct color bg_colors
[] = {
107 { "magenta", "46m" },
109 { "default", "49m" },
119 static const char *formats
[] = {
121 "%s color '%s' %s", /* color */
122 "%s color '%s' %s '%s'", /* random */
123 "less than %d bytes %s", /* error */
127 enum { FOREGROUND
, BACKGROUND
};
129 static const struct {
130 struct color
const *entries
;
134 { fg_colors
, sizeof (fg_colors
) / sizeof (struct color
), "foreground" },
135 { bg_colors
, sizeof (bg_colors
) / sizeof (struct color
), "background" },
138 enum stream_mode
{ SCAN_FIRST
= 1, SCAN_ALWAYS
};
142 const char newline
[3];
145 static const struct ending endings
[] = {
151 static FILE *stream
= NULL
;
153 static unsigned int stacked_vars
= 0;
154 static void **vars_list
= NULL
;
156 static char *exclude
= NULL
;
158 static const char *program_name
;
160 static void print_help (void);
161 static void print_version (void);
162 static void cleanup (void);
163 static void free_color_names (struct color_name
**);
164 static void process_options (unsigned int, char **, bool *, const struct color
**, const char **, FILE **);
165 static void read_print_stream (bool, const struct color
**, const char *, FILE *, enum stream_mode
);
166 static void find_color_entries (struct color_name
**, const struct color
**);
167 static void find_color_entry (const char *const, unsigned int, const struct color
**);
168 static void print_line (const struct color
**, bool, const char * const, unsigned int);
169 static char *xstrdup (const char *);
170 static void vfprintf_fail (const char *, ...);
171 static void stack_var (void ***, unsigned int *, unsigned int, void *);
172 static void release_var (void **, unsigned int, void **);
178 main (int argc
, char **argv
)
180 unsigned int arg_cnt
= 0;
182 bool invalid_opt
= false;
185 struct option long_opts
[] = {
186 { "exclude-random", required_argument
, NULL
, 'e' },
187 { "help", no_argument
, NULL
, 'h' },
188 { "version", no_argument
, NULL
, 'v' },
194 const struct color
*colors
[2] = {
195 NULL
, /* foreground */
196 NULL
, /* background */
201 enum stream_mode mode
= SCAN_FIRST
;
203 program_name
= argv
[0];
206 setvbuf (stdout
, NULL
, _IOLBF
, 0);
208 while ((opt
= getopt_long (argc
, argv
, "hv", long_opts
, NULL
)) != -1)
214 exclude
= xstrdup (optarg
);
216 for (p
= exclude
; *p
; p
++)
218 if (streq (exclude
, "random"))
219 vfprintf_fail (formats
[FMT_GENERIC
], "--exclude-random switch must be provided a color");
231 default: /* never reached */
236 arg_cnt
= argc
- optind
;
238 if (arg_cnt
== 0 || arg_cnt
> 2 || invalid_opt
)
244 process_options (arg_cnt
, &argv
[optind
], &bold
, colors
, &file
, &stream
);
245 read_print_stream (bold
, colors
, file
, stream
, mode
);
247 RELEASE_VAR (exclude
);
257 printf ("Usage: %s (foreground) OR (foreground)/(background) [-|file]\n\n", program_name
);
258 printf ("\tColors (foreground) (background)\n");
259 for (i
= 0; i
< tables
[FOREGROUND
].count
; i
++)
261 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
262 const char *name
= entry
->name
;
263 const char *code
= entry
->code
;
265 printf ("\t\t{\033[%s#\033[0m} [%c%c]%s%*s%s\n",
266 code
, toupper (*name
), *name
, name
+ 1, 10 - (int)strlen (name
), " ", name
);
268 printf ("\t\t{-} %s%*s%s\n", name
, 13 - (int)strlen (name
), " ", name
);
270 printf ("\t\t{*} [Rr]%s%*s%s [--exclude-random=<foreground color>]\n", "andom", 10 - (int)strlen ("random"), " ", "random");
272 printf ("\n\tFirst character of color name in upper case denotes increased intensity,\n");
273 printf ("\twhereas for lower case colors will be of normal intensity.\n");
275 printf ("\n\tOptions\n");
276 printf ("\t\t-h, --help\n");
277 printf ("\t\t-v, --version\n\n");
284 printf ("%s v%s (compiled at %s, %s)\n", "colorize", VERSION
, __DATE__
, __TIME__
);
286 c_flags
= to_str (CFLAGS
);
290 printf ("Compiler flags: %s\n", c_flags
);
291 printf ("Buffer size: %d bytes\n", BUF_SIZE
- 1);
297 free_color_names (color_names
);
299 if (stream
&& fileno (stream
) != STDIN_FILENO
)
305 for (i
= 0; i
< stacked_vars
; i
++)
317 free_color_names (struct color_name
**color_names
)
320 for (i
= 0; color_names
[i
]; i
++)
322 free (color_names
[i
]->name
);
323 color_names
[i
]->name
= NULL
;
324 free (color_names
[i
]->orig
);
325 color_names
[i
]->orig
= NULL
;
326 free (color_names
[i
]);
327 color_names
[i
] = NULL
;
332 process_options (unsigned int arg_cnt
, char **option_strings
, bool *bold
, const struct color
**colors
, const char **file
, FILE **stream
)
336 char *color
, *p
, *str
;
339 const char *color_string
= arg_cnt
>= 1 ? option_strings
[0] : NULL
;
340 const char *file_string
= arg_cnt
== 2 ? option_strings
[1] : NULL
;
342 assert (color_string
);
344 if (streq (color_string
, "-"))
347 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen cannot be used as color string");
349 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen must be preceeded by color string");
352 ret
= stat (color_string
, &sb
);
354 /* Ensure that we don't fail if there's a file with one or more
355 color names in its path. */
360 const char *color
= color_string
;
362 for (c
= 1; c
<= 2 && *color
; c
++)
364 bool matched
= false;
366 for (i
= 0; i
< tables
[FOREGROUND
].count
; i
++)
368 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
370 if ((p
= strstr (color
, entry
->name
)) && p
== color
)
372 color
= p
+ strlen (entry
->name
);
377 if (matched
&& *color
== '/' && *(color
+ 1))
383 have_file
= (*color
!= '\0');
386 vfprintf_fail (formats
[FMT_GENERIC
], "file must be preceeded by color string");
389 if ((p
= strchr (color_string
, '/')))
391 if (p
== color_string
)
392 vfprintf_fail (formats
[FMT_GENERIC
], "foreground color missing");
393 else if (p
== color_string
+ strlen (color_string
) - 1)
394 vfprintf_fail (formats
[FMT_GENERIC
], "background color missing");
395 else if (strchr (++p
, '/'))
396 vfprintf_fail (formats
[FMT_GENERIC
], "one color pair allowed only");
399 str
= xstrdup (color_string
);
402 for (index
= 0, color
= str
; *color
; index
++, color
= p
)
405 if ((sep
= strchr (color
, '/')))
411 p
= color
+ strlen (color
);
413 for (ch
= color
; *ch
; ch
++)
415 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be made of non-alphabetic characters");
417 for (ch
= color
+ 1; *ch
; ch
++)
419 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be in mixed lower/upper case");
421 if (streq (color
, "None"))
422 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be bold");
424 if (isupper (*color
))
432 vfprintf_fail (formats
[FMT_COLOR
], tables
[BACKGROUND
].desc
, color
, "cannot be bold");
434 default: /* never reached */
439 color_names
[index
] = malloc (sizeof (struct color_name
));
441 color_names
[index
]->orig
= xstrdup (color
);
443 for (ch
= color
; *ch
; ch
++)
446 color_names
[index
]->name
= xstrdup (color
);
451 assert (color_names
[FOREGROUND
]);
453 if (color_names
[BACKGROUND
])
456 unsigned int color_sets
[2][2] = { { FOREGROUND
, BACKGROUND
}, { BACKGROUND
, FOREGROUND
} };
457 for (i
= 0; i
< 2; i
++)
459 unsigned int color1
= color_sets
[i
][0];
460 unsigned int color2
= color_sets
[i
][1];
461 if (CHECK_COLORS_RANDOM (color1
, color2
))
462 vfprintf_fail (formats
[FMT_RANDOM
], tables
[color1
].desc
, color_names
[color1
]->orig
, "cannot be combined with", color_names
[color2
]->orig
);
466 find_color_entries (color_names
, colors
);
467 free_color_names (color_names
);
469 if (!colors
[FOREGROUND
]->code
&& colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
470 find_color_entry ("default", FOREGROUND
, colors
);
474 if (streq (file_string
, "-"))
479 const char *file
= file_string
;
484 ret
= stat (file
, &sb
);
487 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
489 if (!(S_ISREG (sb
.st_mode
) || S_ISLNK (sb
.st_mode
) || S_ISFIFO (sb
.st_mode
)))
490 vfprintf_fail (formats
[FMT_FILE
], file
, "unrecognized file type");
494 s
= fopen (file
, "r");
496 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
511 read_print_stream (bool bold
, const struct color
**colors
, const char *file
, FILE *stream
, enum stream_mode mode
)
514 unsigned int flags
= 0;
515 bool first
= false, always
= false;
525 default: /* never reached */
529 while (!feof (stream
))
534 memset (buf
, '\0', BUF_SIZE
);
535 bytes_read
= fread (buf
, 1, BUF_SIZE
- 1, stream
);
536 if (bytes_read
!= (BUF_SIZE
- 1) && ferror (stream
))
537 vfprintf_fail (formats
[FMT_ERROR
], BUF_SIZE
- 1, "read");
539 LOOP
: while ((eol
= strpbrk (line
, "\n\r")))
549 if (*(eol
+ 1) == '\n')
552 else if (*eol
== '\n')
555 vfprintf_fail (formats
[FMT_FILE
], file
, "unrecognized line ending");
558 p
= eol
+ SKIP_LINE_ENDINGS (flags
);
562 unsigned int count
= sizeof (endings
) / sizeof (struct ending
);
563 for (i
= 0; i
< count
; i
++)
565 if (flags
& endings
[i
].flags
)
568 if ((p
= strstr (eol
, endings
[i
].newline
)) && p
== eol
)
577 p
= eol
+ SKIP_LINE_ENDINGS (flags
);
580 print_line (colors
, bold
, line
, flags
);
583 print_line (colors
, bold
, line
, 0);
588 find_color_entries (struct color_name
**color_names
, const struct color
**colors
)
594 gettimeofday (&tv
, NULL
);
595 srand (tv
.tv_usec
* tv
.tv_sec
);
597 for (index
= 0; color_names
[index
]; index
++)
599 const char *color_name
= color_names
[index
]->name
;
601 const unsigned int count
= tables
[index
].count
;
602 const struct color
*const color_entries
= tables
[index
].entries
;
604 if (streq (color_name
, "random"))
610 i
= rand() % (count
- 2) + 1; /* omit color none and default */
614 /* --exclude-random */
615 if (exclude
&& streq (exclude
, color_entries
[i
].name
))
617 else if (color_names
[BACKGROUND
] && streq (color_names
[BACKGROUND
]->name
, color_entries
[i
].name
))
621 if (streq (colors
[FOREGROUND
]->name
, color_entries
[i
].name
))
624 default: /* never reached */
627 } while (excludable
);
628 colors
[index
] = (struct color
*)&color_entries
[i
];
631 find_color_entry (color_name
, index
, colors
);
636 find_color_entry (const char *const color_name
, unsigned int index
, const struct color
**colors
)
641 const unsigned int count
= tables
[index
].count
;
642 const struct color
*const color_entries
= tables
[index
].entries
;
644 for (i
= 0; i
< count
; i
++)
645 if (streq (color_name
, color_entries
[i
].name
))
647 colors
[index
] = (struct color
*)&color_entries
[i
];
652 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color_name
, "not recognized");
656 print_line (const struct color
**colors
, bool bold
, const char *const line
, unsigned int flags
)
658 if (colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
659 printf ("\033[%s", colors
[BACKGROUND
]->code
);
660 if (colors
[FOREGROUND
]->code
)
661 printf ("\033[%s%s%s\033[0m", bold
? "1;" : "", colors
[FOREGROUND
]->code
, line
);
663 printf (formats
[FMT_GENERIC
], line
);
671 xstrdup (const char *str
)
673 const unsigned int len
= strlen (str
) + 1;
674 char *p
= malloc (len
);
676 strncpy (p
, str
, len
);
681 vfprintf_fail (const char *fmt
, ...)
684 fprintf (stderr
, "%s: ", program_name
);
686 vfprintf (stderr
, fmt
, ap
);
688 fprintf (stderr
, "\n");
693 stack_var (void ***list
, unsigned int *stacked
, unsigned int index
, void *ptr
)
695 /* nothing to stack */
699 *list
= malloc (sizeof (void *));
703 for (i
= 0; i
< *stacked
; i
++)
709 *list
= realloc (*list
, (*stacked
+ 1) * sizeof (void *));
711 (*list
)[index
] = ptr
;
716 release_var (void **list
, unsigned int stacked
, void **ptr
)
719 /* nothing to release */
722 for (i
= 0; i
< stacked
; i
++)