-
Notifications
You must be signed in to change notification settings - Fork 0
/
colr.h
3302 lines (2834 loc) · 108 KB
/
colr.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*! \file colr.h
Declarations for ColrC functions, enums, structs, etc.
\internal
\author Christopher Welborn
\date 06-22-2019
\details
To use ColrC in your project, you will need to include colr.h
and compile colr.c with the rest of your files.
\examplecodefor{colr_h,.c}
#include "colr.h"
// Use ColrC functions/macros/etc.
int main(void) {
char* colorized = colr_cat(
"This is ",
Colr("ColrC", fore(BLUE), style(BRIGHT)),
" and it tries to make things ",
Colr("easy", fore("green"), style("underline")),
"."
);
printf("%s\n", colorized);
free(colorized);
}
\endexamplecode
<em>Don't forget to compile with `colr.c` and `-lm`</em>.
\code{.sh}
gcc -std=c11 -c your_program.c colr.c -lm
\endcode
*/
#ifndef COLR_H
#define COLR_H
//! Current version for ColrC.
#define COLR_VERSION "0.3.7"
/* Tell gcc to ignore clang pragmas, for linting. */
#pragma GCC diagnostic ignored "-Wunknown-pragmas"
#ifndef DOXYGEN_SKIP
/*! \def IS_C11
Pragmas to check for _Generic support.
\details
There's a reason for jumping through all of these hoops.
See: https://mort.coffee/home/c-compiler-quirks/
*/
#if (__STDC_VERSION__ >= 201112L)
#if defined(__GNUC__) && !defined(__clang__)
#if (__GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 9))
#define IS_C11
#endif
#else
#define IS_C11
#endif
#endif
#endif // DOXYGEN_SKIP
// Without _Generic, ColrC is useless.
#ifndef IS_C11
#error "ColrC cannot compile without C11+ generic selections (_Generic)."
#endif
// ColrC uses GNU extensions.
#if defined(__GNUC__)
#if !defined(_GNU_SOURCE)
/*
This enables gnu extensions.
ColrC will not compile at all without this.
Current GNU dependencies:
Optional:
Statement-Expressions in fore_str_static/back_str_static
register_printf_specifier from printf.h.
Required:
stdio.h: asprintf()
locale.h: uselocale(), LC_GLOBAL_LOCALE
string.h: strndup(), strdup(), strcmp(), strcasecmp(), strnlen()
math.h: sin(), M_PI
*/
#define _GNU_SOURCE
#elif _GNU_SOURCE < 1
// This is for testing. If _GNU_SOURCE=0 is set, it will be undefined,
// and I can watch all of the warnings and errors that pop up.
#undef _GNU_SOURCE
#pragma GCC warning "Trying to compile without _GNU_SOURCE, this will not work."
#endif
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wmacro-redefined"
/*! \def COLR_GNU
Defined when `__GNUC__` is available, to enable
<a href='https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html'>
statement-expressions
</a>
and
<a href='https://www.gnu.org/software/libc/manual/html_node/Customizing-Printf.html'>
register_printf_specifier
</a>.
\details
There isn't a lot of information available for `register_printf_specifier`
right now. There are a couple of
<a href='https://lib.void.so/define-your-own-custom-conversion-specifiers-for-printf-example/'>
tutorials
</a> out there. No
<a href='https://www.kernel.org/doc/man-pages/missing_pages.html'>
man pages
</a> though.
It
<a href='https://fossies.org/diffs/glibc/2.26_vs_2.27/stdio-common/reg-printf.c-diff.html'>
looks like
</a> it was introduced in `glibc-2.27`.
\sa back_str_static
\sa fore_str_static
\sa colr_asprintf
\sa colr_printf
\sa colr_printf_handler
\sa colr_printf_info
\sa colr_printf_macro
\sa colr_printf_register
\sa colr_sprintf
\sa colr_snprintf
*/
#define COLR_GNU
#pragma clang diagnostic pop // -Wmacro-redefined
#else
#pragma GCC warning "ColrC uses GNU extensions that your system doesn't support."
#if defined(COLR_GNU)
#pragma GCC warning "ColrC GNU extensions are enabled (COLR_GNU) for a non-GNU system."
#else
#pragma GCC warning "No glibc and COLR_GNU=0, some features will be disabled."
#endif
#endif
#include <assert.h>
// assert() uses a statement-expression when compiling with __GNUC__ defined.
// This is here to silence clang linters.
#pragma clang diagnostic ignored "-Wgnu-statement-expression"
#include <ctype.h> // islower, iscntrl, isdigit, etc.
/* Must include `-lm` in compiler args or Makefile LIBS!
This is for the `sin()` function used in `rainbow_step()`.
*/
#include <math.h>
#include <limits.h> // Used for asprintf return checking.
#include <locale.h> // Not used in colr.c, but necessary for users of rainbow stuff.
#ifdef COLR_GNU
#include <printf.h> // For register_printf_specifier.
#endif
#include <regex.h> // For colr_str_replace_re and friends.
#include <stdarg.h> // Variadic functions and `va_list`.
#include <stdbool.h>
#include <stdint.h> // marker integers for colr structs
#include <stdio.h> // snprintf, fileno, etc.
#include <stdlib.h> // calloc, free, malloc, etc.
#include <string.h> // strcat
#include <sys/ioctl.h> // For `struct winsize` and the `ioctl()` call to use it.
#include <unistd.h> // isatty
#include <wchar.h>
/* This is only enabled for development. */
#if defined(DEBUG) && defined(COLR_DEBUG)
#include "dbug.h"
#endif
/* Tell gcc to ignore unused macros. */
#pragma GCC diagnostic ignored "-Wunused-macros"
//! Convenience definition, because this is used a lot.
#define CODE_RESET_ALL "\x1b[0m"
//! Convenience definition for resetting the back color.
#define CODE_RESET_BACK "\x1b[49m"
//! Convenience definition for resetting the fore color.
#define CODE_RESET_FORE "\x1b[39m"
//! Convenience definition for resetting the back color.
#define WCODE_RESET_BACK L"\x1b[49m"
//! Convenience definition for resetting the fore color.
#define WCODE_RESET_FORE L"\x1b[39m"
//! Convenience definition for wide chars.
#define WCODE_RESET_ALL L"\x1b[0m"
//! Short-hand for CODE_RESET_ALL, stands for "No Color".
#define NC CODE_RESET_ALL
//! Short-hand for `CODE_RESET_ALL "\n"`, stands for "No Color, New Line".
#define NCNL CODE_RESET_ALL "\n"
//! Short-hand for WCODE_RESET_ALL, stands for "Wide No Color".
#define WNC WCODE_RESET_ALL
//! Short-hand for `WCODE_RESET_ALL "\n"`, stands for "Wide No Color, New Line".
#define WNCNL WCODE_RESET_ALL L"\n"
//! Length of CODE_RESET_ALL, including `'\0'`.
#define CODE_RESET_LEN 5
/*! Minimum length for the shortest basic fore/back escape code, including `'\0'`.
\details
Use CODE_LEN for allocation.
*/
#define CODE_LEN_MIN 5
/*! Maximum length for a basic fore/back escape code, including `'\0'`.
Keep in mind that BasicValue actually has some "light" colors (104).
*/
#define CODE_LEN 14
/*! Minimum length for the shortest extended fore/back escape code, including `'\0'`.
\details
Use CODEX_LEN for allocation.
*/
#define CODEX_LEN_MIN 10
//! Maximum length for an extended fore/back escape code, including `'\0'`.
#define CODEX_LEN 12
/*! Minimum length for the shortest style escape code, including `'\0'`.
\details
Use STYLE_LEN for allocation.
*/
#define STYLE_LEN_MIN 5
//! Maximum length for a style escape code, including `'\0'`.
#define STYLE_LEN 6
/*! Maximum length in chars for any combination of basic/extended escape codes
for one complete style (one of each: fore, back, style).
Should be `(CODEX_LEN * 2) + STYLE_LEN`.
Allocating for a string that will be colorized must account for this.
*/
#define COLOR_LEN 30
/*! Minimum length for the shortest RGB fore/back escape code, including `'\0'`.
\details
Use CODE_RGB_LEN for allocation.
*/
#define CODE_RGB_LEN_MIN 14
//! Maximum length in chars for an RGB fore/back escape code, including `'\0'`.
#define CODE_RGB_LEN 20
/*! Maximum length in chars added to a rgb colorized string.
Should be `CODE_RGB_LEN + STYLE_LEN`
Allocating for a string that will be colorized with rgb values must account
for this.
*/
#define COLOR_RGB_LEN 26
/*! Maximum length in chars for any possible escape code mixture for one complete
style (one of each: fore, back, and style).
(basically `(CODE_RGB_LEN * 2) + STYLE_LEN` since rgb codes are the longest).
*/
#define CODE_ANY_LEN 46
/*! \internal
The following markers are not %100 safe. It is possible to compare equal
with an arbitrary non-ColrC struct if they happen to have the same/similar
first member type/value (values must match, types can be close enough).
See `colr_check_marker()`, but an example of an arbitrary struct that
matches would be:
\examplecodefor{colr_marker_mismatch, .c}
//
// Better viewed with: ./tools/snippet.py -L colr_marker_mismatch
// Run this with: ./tools/snippet.py -x colr_marker_mismatch
typedef struct Thing {
uint32_t marker;
} Thing;
Thing* mything = malloc(sizeof(Thing));
// Setting the marker value to ColorArg's marker value.
mything->marker = COLORARG_MARKER;
assert(colr_check_marker(COLORARG_MARKER, mything));
assert(ColorArg_is_ptr(mything));
fprintf(stderr, "Uh oh, ColrC believes this thing is a ColorArg!\n");
fprintf(stderr, "I hope this thing has a usable .type/.value member!\n");
free(mything);
\endexamplecode
When using certain ColrC macros/functions, the ColrC structs are void
pointers, interpreted as a series of bytes (to determine which ColrC
type was passed into the function).
When comparing memory like this, types are thrown out of the window.
This opens the door for all kinds of trouble if you don't know what
types you had to begin with. Passing a non-ColrC (or an uninitialized, or
incorrectly initialized) struct pointer into these functions will break
things.
It's one of the risks that ColrC takes to be dynamic (argument order
doesn't matter, certain types can be mixed in function arguments).
This is also why every function/macro/global is documented in ColrC,
private/internal functions are marked (they start with '_'), and great
care is taken to always use properly initialized ColrC objects with the
correct type.
** The Colr markers are considered private/internal, and are subject to
change/disappear.
\endinternal
*/
/*! Marker for the ColorArg struct, for identifying a void pointer as a
ColorArg.
*/
#define COLORARG_MARKER UINT32_MAX
/*! Marker for the _ColrLastArg_s struct, for identifying a void pointer as a
_ColrLastArg_s.
*/
#define COLORLASTARG_MARKER (UINT32_MAX - 20)
/*! Marker for the ColorJustify struct, for identifying a void pointer as a
ColorJustify.
*/
#define COLORJUSTIFY_MARKER (UINT32_MAX - 30)
/*! Marker for the ColorResult struct, for identifying a void pointer as a
ColorResult.
*/
#define COLORRESULT_MARKER (UINT32_MAX - 40)
/*! Marker for the ColorText struct, for identifying a void pointer as a
ColorText.
*/
#define COLORTEXT_MARKER (UINT32_MAX - 50)
/*! Possible error return value for BasicValue_from_str(), ExtendedValue_from_str(),
and colorname_to_rgb().
*/
#define COLOR_INVALID (-2)
//! Possible error return value for RGB_from_str().
#define COLOR_INVALID_RANGE (-3)
//! Seed value for colr_str_hash().
#define COLR_HASH_SEED 5381
/*! Format character string suitable for use in the printf-family of functions.
This can be defined to any single-char string before including colr.h if
you don't want to use the default value.
*/
#ifndef COLR_FMT
#define COLR_FMT "R"
#endif
#pragma info "Set COLR_FMT=" COLR_FMT
//! Character used in printf format strings for Colr objects.
#define COLR_FMT_CHAR COLR_FMT[0]
//! Modifier for Colr printf character to produce escaped output.
#define COLR_FMT_MOD_ESC "/"
//! Modifier for Colr printf character to produce escaped output, in char form.
#define COLR_FMT_MOD_ESC_CHAR COLR_FMT_MOD_ESC[0]
/*! Integer to test for the presence of the "escaped output modifier" in
colr_printf_handler. This is set in colr_printf_register.
*/
extern int colr_printf_esc_mod;
/*! Alias for COLOR_INVALID.
\details
All color values share an _INVALID member with the same value, so:
\code
COLOR_INVALID == BASIC_INVALID == EXT_INVALID == STYLE_INVALID
\endcode
*/
#define EXT_INVALID COLOR_INVALID
/*! Possible error return value for ExtendedValue_from_str() or ExtendedValue_from_esc().
\details
This is just an alias for COLOR_INVALID_RANGE.
\code
COLOR_INVALID_RANGE == BASIC_INVALID_RANGE == EXT_INVALID_RANGE == STYLE_INVALID_RANGE
\endcode
*/
#define EXT_INVALID_RANGE COLOR_INVALID_RANGE
/*! \def alloc_basic
Allocate enough for a basic code.
\return \parblock
Pointer to the allocated string, or NULL on error.
\mustfree
\endparblock
*/
#define alloc_basic() calloc(CODE_LEN, sizeof(char))
/*! \def alloc_extended
Allocate enough for an extended code.
\return \parblock
Pointer to the allocated string, or NULL on error.
\mustfree
\endparblock
*/
#define alloc_extended() calloc(CODEX_LEN, sizeof(char))
/*! \def alloc_rgb
Allocate enough for an rgb code.
\return \parblock
Pointer to the allocated string, or NULL on error.
\mustfree
\endparblock
*/
#define alloc_rgb() calloc(CODE_RGB_LEN, sizeof(char))
/*! \def alloc_style
Allocate enough for a style code.
\return \parblock
Pointer to the allocated string, or NULL on error.
\mustfree
\endparblock
*/
#define alloc_style() calloc(STYLE_LEN, sizeof(char))
/*! \def asprintf_or_return
Convenience macro for bailing out of a function when asprintf fails.
\pi retval Value to return if the asprintf fails.
\pi ... Arguments for asprintf.
*/
#define asprintf_or_return(retval, ...) if_not_asprintf(__VA_ARGS__) return retval
/*! \def back
Create a back color suitable for use with the \colrmacros.
\details
Technically, this macro accepts BasicValues, ExtendedValues, or RGB structs.
However, for some of these you should be using the
macros that create those things.
\details
BasicValues can be used by their names (RED, YELLOW, etc.).
\details
ExtendedValues can be created on the fly with ext().
\details
RGB structs can be easily created with rgb().
\details
Color names (`char* `) can be passed to generate the appropriate color value.
\pi x A BasicValue, ExtendedValue, or RGB struct to use for the color value.
\return \parblock
A pointer to a heap-allocated ColorArg struct.\n
\colrmightfree
\endparblock
\sa back_arg
\sa back_str
\sa colr
\sa Colr
\example back_example.c
*/
#define back(x) ColorArg_to_ptr(back_arg(x))
/*! \def back_arg
Uses ColorArg_from_<type> to build a ColorArg with the appropriate color
type, based on the type of it's argument.
\details
Uses `_Generic` (C11 standard) to dynamically create a ColorArg.
This is used by the back() macro.
\pi x `BasicValue`, `Extended` (`unsigned char`), `RGB` struct,
or string (color name) for back color.
\return \parblock
A ColorArg with the BACK type set, and it's `.value.type` set
for the appropriate color type/value.\n
For invalid values the `.value.type` may be set to TYPE_INVALID.\n
\mustfree
\endparblock
\sa back
\sa back_str
*/
#define back_arg(x) \
_Generic( \
(x), \
char* : ColorArg_from_str, \
RGB: ColorArg_from_RGB, \
BasicValue: ColorArg_from_BasicValue, \
ExtendedValue: ColorArg_from_ExtendedValue, \
StyleValue: ColorArg_from_StyleValue \
)(BACK, x)
/*! \def back_str
Return just the escape code string for a back color.
\pi x A BasicValue, ExtendedValue, or RGB struct.
\return \parblock
An allocated string.
\mustfree
\endparblock
\sa back
\sa back_arg
*/
#define back_str(x) ColorArg_to_esc(back_arg(x))
#ifdef COLR_GNU
/*! \def back_str_static
Creates a stack-allocated escape code \string for a back color.
\details
These are not constant strings, but they are stored on the stack.
A \statementexpr is used to build a string of the correct length
and content using ColorArg_to_esc_s().
\gnuonly
\warn_alloca_statementexpr
\details
You can also create stack-allocated escape code strings using format_bg(),
format_bgx(), format_bg_RGB(), and format_bg_RGB_term().
\pi x A BasicValue, ExtendedValue, or RGB value.
\return A stack-allocated escape code string.
\sa back_str_static
\sa style_str_static
\sa format_fg
\sa format_bg
\examplecodefor{back_str_static,.c}
// This results in a call to sprintf(), to format an extended escape code.
// The string is stored on the stack.
char* backwhite = back_str_static(WHITE);
char* foreblue = fore_str_static(BLUE);
printf("%s%sBlue on White." NCNL, backwhite, foreblue);
RGB rgbval = rgb(255, 34, 0);
printf("%sA reddish." NCNL, back_str_static(rgbval));
printf("%sAquaMarine." NCNL, back_str_static("aquamarine"));
\endexamplecode
*/
#define back_str_static(x) \
__extension__ ({ \
__typeof(x) _bss_val = x; \
ColorArg _bss_carg = back_arg(_bss_val); \
size_t _bss_len = ColorArg_length(_bss_carg); \
char* _bss_codes = alloca(_bss_len); \
ColorArg_to_esc_s(_bss_codes, _bss_carg); \
_bss_codes; \
})
/* A Variable Length Array will not work here.
The space for `_bss_codes` would be deallocated before this statement
expression returns. Using `alloca` ensures that it will live at least
as long as the calling function.
See:
https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html#index-_002a_005f_005fbuiltin_005falloca
*/
#endif // COLR_GNU
/*! \def basic
Casts to BasicValue.
\pi x Value to case to `BasicValue`.
\return A BasicValue.
\sa fore
\sa back
\sa colr
\sa Colr
*/
#define basic(x) ((BasicValue)(x))
/*! \def bool_colr_enum
Returns the "truthiness" of the enums used in ColrC
(BasicValue, ExtendedValue function-returns, StyleValue, ColorType, ArgType).
\details
Any value less than `0` is considered false.
\pi x An enum to convert to boolean.
\retval true if the value is considered valid, or non-empty.
\retval false if the value is considered invalid, or empty.
*/
#define bool_colr_enum(x) (x < 0 ? false: true)
/*! \def color_arg
Builds a correct ColorArg struct according to the type of it's second
argument.
\details
Uses `_Generic` (C11 standard) to dynamically create a ColorArg.
\pi type `ArgType` (`FORE`, `BACK`, `STYLE`) to build the ColorArg.
\pi x `BasicValue`, `Extended` (`unsigned char`). or `RGB` value.
\return ColorArg_from_value(type, [appropriate type], x)
*/
#define color_arg(type, x) \
_Generic( \
(x), \
char*: ColorArg_from_str(type, x), \
BasicValue: ColorArg_from_value(type, TYPE_BASIC, &x), \
ExtendedValue: ColorArg_from_value(type, TYPE_EXTENDED, &x), \
StyleValue: ColorArg_from_value(type, TYPE_STYLE, &x), \
RGB: ColorArg_from_value(type, TYPE_RGB, &x) \
)
/*! \def color_name_is_invalid
Convenience macro for checking if a color name is invalid.
\pi x \string to check (a name, hex-string, rgb-string, or integer-string).
\return `true` if the name is an invalid color name, otherwise `false`.
\sa color_name_is_valid
\examplecodefor{color_name_is_invalid,.c}
char* names[] = {
// Valid names:
"red",
"lightblue",
"127",
"123,54,67",
"#ff0000",
"#fff",
"aliceblue",
// Invalid names:
"NOTACOLOR",
// Invalid range (not 0-255):
"345",
// Bad RGB strings:
"1;",
"1;2;",
// Bad RGB ranges:
"345;345;345",
"-1;0;0",
"0;0;256",
};
size_t names_len = sizeof(names) / sizeof(names[0]);
for (size_t i = 0; i < names_len; i++) {
if (color_name_is_invalid(names[i])) {
printf("Invalid name: %s\n", names[i]);
} else {
printf(" Valid name: %s\n", names[i]);
}
}
\endexamplecode
*/
#define color_name_is_invalid(x) ColorType_is_invalid(ColorType_from_str(x))
/*! \def color_name_is_valid
Convenience macro for checking if a color name is valid.
\pi x \string to check (a name, hex-string, rgb-string, or integer-string).
\return `true` if the name is a valid color name, otherwise `false`.
\sa color_name_is_invalid
\examplecodefor{color_name_is_valid,.c}
char* names[] = {
// Valid names:
"red",
"lightblue",
"127",
"123,54,67",
"#ff0000",
"#fff",
"aliceblue",
// Invalid names:
"NOTACOLOR",
// Invalid range (not 0-255):
"345",
// Bad RGB strings:
"1;",
"1;2;",
// Bad RGB ranges:
"345;345;345",
"-1;0;0",
"0;0;256",
};
size_t names_len = sizeof(names) / sizeof(names[0]);
for (size_t i = 0; i < names_len; i++) {
if (color_name_is_valid(names[i])) {
printf(" Valid name: %s\n", names[i]);
} else {
printf("Invalid name: %s\n", names[i]);
}
}
\endexamplecode
*/
#define color_name_is_valid(x) ColorType_is_valid(ColorType_from_str(x))
/*! \def color_val
Builds a correct ColorValue struct according to the type of it's first
argument.
\details
Uses `_Generic` (C11 standard) to dynamically create a ColorValue.
\pi x `BasicValue`, `Extended` (`unsigned char`). or `RGB` value.
\return ColorValue_from_value([appropriate type], x)
*/
#define color_val(x) \
_Generic( \
(x), \
BasicValue: ColorValue_from_value(TYPE_BASIC, &x), \
ExtendedValue: ColorValue_from_value(TYPE_EXTENDED, &x), \
StyleValue: ColorValue_from_value(TYPE_STYLE, &x), \
RGB: ColorValue_from_value(TYPE_RGB, &x) \
)
/*! Call the current ColorValue_has_\<type\> function for the given value.
\details
Given the correct type of value, this will check to see if a ColorValue
has the correct `.type` set for the value, and the values match.
\pi cval The ColorValue to check.
\pi val A BasicValue, ExtendedValue, StyleValue, or RGB value.
\return `true` if the ColorValue has the correct `.type` and it's value
matches `val`, otherwise `false`.
\sa ColorValue
\sa ColorValue_has_BasicValue
\sa ColorValue_has_ExtendedValue
\sa ColorValue_has_StyleValue
\sa ColorValue_has_RGB
*/
#define ColorValue_has(cval, val) \
_Generic( \
(val), \
BasicValue: ColorValue_has_BasicValue, \
ExtendedValue: ColorValue_has_ExtendedValue, \
StyleValue: ColorValue_has_StyleValue, \
RGB: ColorValue_has_RGB \
)(cval, val)
/*! \def Colr
Returns a heap-allocated ColorText struct that can be used by itself,
or with the \colrusingmacros.
\details
You must `free()` the resulting ColorText struct using ColorText_free(),
unless you pass it to colr_cat(), which will `free()` it for you.
\pi text String to colorize/style.
\pi ... One to three ColorArg pointers for fore, back, and style in any order.
\return \parblock
An allocated ColorText.
\colrmightfree
\endparblock
\sa Colra
\example Colr_example.c
*/
#define Colr(text, ...) ColorText_to_ptr(ColorText_from_values(text, __VA_ARGS__, _ColrLastArg))
/*! \def Colra
Returns an initialized stack-allocated ColorText.
\details
If this ColorText is manually stored on the heap, and then sent through
the colr macros, it's ColorArgs will be free'd. You cannot use the same
ColorText twice inside the colr macros/functions.
\nocolrmacros
\pi text String to colorize/style.
\pi ... No more than 3 ColorArg pointers for fore, back, and style in any order.
\return An initialized ColorText.
\sa Colr
\examplecodefor{Colra,.c}
// This ColorText is stack-allocated, but it's ColorArgs are not.
ColorText ctext = Colra("This.", fore(RED), back(WHITE));
// You cannot use this in the colr macros.
char* mystring = ColorText_to_str(ctext);
printf("%s\n", mystring);
free(mystring);
// And you are responsible for cleaning up the ColorArgs.
ColorText_free_args(&ctext);
ColorText singleuse = Colra("That.", fore(BLUE));
ColorText* manualalloc = ColorText_to_ptr(singleuse);
assert(singleuse.fore == manualalloc->fore);
colr_printf("Used up: %R\n", manualalloc);
// The ColorArgs associated with `singleuse` were just free'd
// because they were linked with the heap-allocated ColorText.
\endexamplecode
*/
#define Colra(text, ...) ColorText_from_values(text, __VA_ARGS__, _ColrLastArg)
/*! \def Colr_cat
Like colr_cat(), but returns an allocated ColorResult that the \colrmacros
will automatically `free()`.
\pi ... \parblock
Arguments for colr_cat(), to concatenate.
\colrwillfree
\endparblock
\return \parblock
An allocated ColorResult with all arguments joined together.
\mustfree
\maybenullalloc
\colrmightfree
\endparblock
*/
#define Colr_cat(...) ColorResult_to_ptr(ColorResult_new(colr_cat(__VA_ARGS__)))
/*! \def Colr_center
Sets the JustifyMethod for a ColorText while allocating it.
\details
This is like Colr_center_char(), except is uses space as the default character.
\pi text Text to colorize.
\pi justwidth Width for justification.
\pi ... Fore, back, or style ColorArgs for Colr().
\return \parblock
An allocated ColorText.
\colrmightfree
\endparblock
\examplecodefor{Colr_center,.c}
char* justified = colr_cat(Colr_center("This.", 9, fore(RED), back(WHITE)));
assert(justified);
// The string still has codes, but only 4 spaces were added.
assert(colr_str_starts_with(justified, " "));
assert(colr_str_ends_with(justified, " "));
// It was "justified" to 9 characters long, but it is well over that.
assert(strlen(justified) > 9);
printf("'%s'\n", justified);
free(justified);
\endexamplecode
*/
#define Colr_center(text, justwidth, ...) ColorText_set_just( \
Colr(text, __VA_ARGS__), \
(ColorJustify){.method=JUST_CENTER, .width=justwidth, .padchar=' '} \
)
/*! \def Colr_center_char
Sets the JustifyMethod for a ColorText while allocating it.
\pi text Text to colorize.
\pi justwidth Width for justification.
\pi c The character to pad with.
\pi ... Fore, back, or style ColorArgs for Colr().
\return \parblock
An allocated ColorText.
\colrmightfree
\endparblock
\sa Colr_center
\examplecodefor{Colr_center_char,.c}
char* justified = colr_cat(Colr_center_char("This.", 8, ' ', fore(RED), back(WHITE)));
assert(justified);
// The string still has codes, but only 2 spaces were prepended, and 1 appended.
assert(colr_str_starts_with(justified, " "));
assert(colr_str_ends_with(justified, " "));
// It was "justified" to 8 characters long, but it is well over that.
assert(strlen(justified) > 8);
printf("'%s'\n", justified);
free(justified);
\endexamplecode
*/
#define Colr_center_char(text, justwidth, c, ...) ColorText_set_just( \
Colr(text, __VA_ARGS__), \
(ColorJustify){.method=JUST_CENTER, .width=justwidth, .padchar=c} \
)
/*! \def Colr_fmt
Format and colorize a value like the `printf`-family.
\details
Unlike `printf`, this only accepts a <strong>single value</strong> to format.
The other arguments are for coloring/styling the value.
\pi fmt The format string.
\pi value The value to format.
\pi ... At least one of fore(), back(), or style() arguments in any order.
\return \parblock
An allocated ColorResult.
\maybenullalloc
\colrmightfree
\endparblock
\examplecodefor{Colr_fmt,.c}
// Format a number:
for (int i = 1; i < 4; i++) {
colr_puts("Printing line ", Colr_fmt("%d", i, fore(BLUE)));
}
// Format a string:
char* s = "test";
// The coloring/styling applies to the final string value, "[test]".
colr_puts(Colr_fmt("[%s]", s, fore(RED)));
// If you don't want that, use the _join or _cat functions:
colr_puts(Colr_join(Colr(s, fore(RED)), "[", "]"));
\endexamplecode
*/
#define Colr_fmt(fmt, value, ...) \
ColorResult_Colr( \
Colr_fmt_str(fmt, value), \
__VA_ARGS__, \
_ColrLastArg \
)
/*! \def Colr_join
Joins Colr objects and strings, exactly like colr_join(), but returns
an allocated ColorResult that the \colrmacros will automatically `free()`
for you.
\pi joiner What to put between the other arguments.
ColorArg pointer, ColorResult pointer, ColorText pointer, or
\string.
\pi ... \parblock
Other arguments to join, with \p joiner between them.
ColorArg pointers, ColorResult pointers, ColorText pointers,
or strings, in any order.
\colrwillfree
\endparblock
\return \parblock
An allocated ColorResult.
\mustfree
\maybenullalloc
\colrmightfree
\endparblock
\sa ColorResult
\sa colr_join
\sa colr
\sa Colr
\example ColorResult_example.c
*/
#define Colr_join(joiner, ...) ColrResult(colr_join(joiner, __VA_ARGS__))
/*! \def Colr_ljust
Sets the JustifyMethod for a ColorText while allocating it.
\details
This is like Colr_ljust_char(), except is uses space as the default character.
\pi text Text to colorize.
\pi justwidth Width for justification.
\pi ... Fore, back, or style ColorArgs for Colr().
\return \parblock
An allocated ColorText.
\colrmightfree
\endparblock
\examplecodefor{Colr_ljust,.c}
char* justified = colr_cat(Colr_ljust("This.", 8, fore(RED), back(WHITE)));
assert(justified);
// The string still has codes, but only 3 spaces were added.
assert(colr_str_ends_with(justified, " "));
// It was "justified" to 8 characters long, but it is well over that.
assert(strlen(justified) > 8);
printf("'%s'\n", justified);
free(justified);
\endexamplecode
*/
#define Colr_ljust(text, justwidth, ...) ColorText_set_just( \
Colr(text, __VA_ARGS__), \
(ColorJustify){.method=JUST_LEFT, .width=justwidth, .padchar=' '} \
)
/*! \def Colr_ljust_char
Sets the JustifyMethod for a ColorText while allocating it.
\pi text Text to colorize.
\pi justwidth Width for justification.
\pi c The character to pad with.
\pi ... Fore, back, or style ColorArgs for Colr().
\return \parblock
An allocated ColorText.
\colrmightfree
\endparblock
\sa Colr_ljust
\examplecodefor{Colr_ljust_char,.c}
char* justified = colr_cat(Colr_ljust_char("This.", 8, ' ', fore(RED), back(WHITE)));
assert(justified);
// The string still has codes, but only 3 spaces were added.
assert(colr_str_ends_with(justified, " "));
// It was "justified" to 8 characters long, but it is well over that.
assert(strlen(justified) > 8);
printf("'%s'\n", justified);
free(justified);
\endexamplecode
*/
#define Colr_ljust_char(text, justwidth, c, ...) ColorText_set_just( \
Colr(text, __VA_ARGS__), \
(ColorJustify){.method=JUST_LEFT, .width=justwidth, .padchar=c} \
)
/*! \def Colr_rjust