commit e29380b0b0628f64e58bdf3ddc247de3f1c5b9ce
parent 832036ba5f77907079a6bccaf30dd1e6324da260
Author: Remy Noulin <loader2x@gmail.com>
Date: Sat, 2 Jun 2018 14:17:50 +0200
print RGB colors with printf %k and %K
README.md | 7 +++++++
main.c | 9 +++++++++
make.sh | 3 +++
printfRGB.c | 44 ++++++++++++++++++++++++++++++++++++++++++++
printfRGB.h | 4 ++++
5 files changed, 67 insertions(+)
Diffstat:
5 files changed, 67 insertions(+), 0 deletions(-)
diff --git a/README.md b/README.md
@@ -1,2 +1,9 @@
# printfRGB
add %k and %K type specifier to GNU printf for RBG colors
+
+- %k foreground hex color (uint32_t) 0x00RRGGBB
+- %K background hex color
+
+```
+ printf("%k%KRGB color" RST, 0x99EEFF, 0x666666);
+```
diff --git a/main.c b/main.c
@@ -0,0 +1,9 @@
+#include <stdio.h>
+#include "printfRGB.h"
+
+int main(int ARGC, char** ARGV) {
+
+ initPrintfRBG();
+
+ printf("%k%KRGB color" RST, 0x99EEFF, 0x666666);
+}
diff --git a/make.sh b/make.sh
@@ -0,0 +1,3 @@
+gcc -c -std=gnu99 printfRGB.c
+gcc -std=gnu99 main.c printfRGB.o
+echo Compiled to a.out
diff --git a/printfRGB.c b/printfRGB.c
@@ -0,0 +1,44 @@
+#include <inttypes.h>
+#include <stdio.h>
+#include <printf.h>
+
+#define TERMRGB "\x1b[38;2;"
+#define BGTERMRGB "\x1b[48;2;"
+
+int print_k(FILE *stream, const struct printf_info *info, const void *const *args) {
+ uint32_t rgbColor = *((uint32_t*) args[0]);
+ char b[20];
+ size_t len;
+
+ snprintf(b, sizeof(b), TERMRGB "%d;%d;%dm", rgbColor>>16, (rgbColor&0xFF00)>>8, rgbColor&0xFF);
+
+ /* Pad to the minimum field width and print to the stream. */
+ len = fprintf(stream, "%*s", (info->left ? -info->width : info->width), b);
+ return len;
+}
+
+int print_K(FILE *stream, const struct printf_info *info, const void *const *args) {
+ uint32_t rgbColor = *((uint32_t*) args[0]);
+ char b[20];
+ size_t len;
+
+ snprintf(b, sizeof(b), BGTERMRGB "%d;%d;%dm", rgbColor>>16, (rgbColor&0xFF00)>>8, rgbColor&0xFF);
+
+ /* Pad to the minimum field width and print to the stream. */
+ len = fprintf(stream, "%*s", (info->left ? -info->width : info->width), b);
+ return len;
+}
+
+
+int print_k_arginfo(const struct printf_info *info, size_t n, int *argtypes, int* size) {
+ if (n > 0) {
+ argtypes[0] = PA_POINTER;
+ size[0] = sizeof(uint32_t);
+ }
+ return 1;
+}
+
+void initPrintfRBG(void) {
+ register_printf_specifier('k', print_k, print_k_arginfo);
+ register_printf_specifier('K', print_K, print_k_arginfo);
+}
diff --git a/printfRGB.h b/printfRGB.h
@@ -0,0 +1,4 @@
+
+#define RST "\x1B[0m"
+
+void initPrintfRBG(void);