robin/cdl

cute fetch client written in zig

git clone https://git.robinwobin.dev/robin/cdl

robinmeow: styling & formatting92d0b25

main
2.0 KiB99 linesraw
1const std = @import("std");
2
3const W = std.Io.Writer;
4const E = W.Error;
5
6pub const Style = enum(u8) {
7    reset,
8    bold,
9    dim,
10    italic,
11    underline,
12    blink,
13    inverse,
14    invisible,
15    strikethrough,
16
17    pub fn ansi(self: Style) u8 {
18        return @intFromEnum(self);
19    }
20};
21
22pub fn style(w: *W, b: Style) E!void {
23    try base(w, b.ansi());
24}
25
26pub const Color = enum(u8) {
27    black,
28    red,
29    green,
30    yellow,
31    blue,
32    magenta,
33    cyan,
34    white,
35    default,
36
37    pub fn int(n: u8) Color {
38        return @enumFromInt(n);
39    }
40    pub fn foreground(self: Color) u8 {
41        return @intFromEnum(self) + 30;
42    }
43    pub fn background(self: Color) u8 {
44        return @intFromEnum(self) + 40;
45    }
46    pub fn foreground_bright(self: Color) u8 {
47        return @intFromEnum(self) + 90;
48    }
49    pub fn background_bright(self: Color) u8 {
50        return @intFromEnum(self) + 100;
51    }
52};
53
54pub fn fg(w: *W, color: Color) E!void {
55    try base(w, color.foreground());
56}
57pub fn bg(w: *W, color: Color) E!void {
58    try base(w, color.background());
59}
60pub fn fg_bright(w: *W, color: Color) E!void {
61    try base(w, color.foreground_bright());
62}
63pub fn bg_bright(w: *W, color: Color) E!void {
64    try base(w, color.background_bright());
65}
66
67pub fn fg_256(w: *W, color: u8) E!void {
68    try params(w, &[_]u8{ 38, 5, color });
69}
70pub fn bg_256(w: *W, color: u8) E!void {
71    try params(w, &[_]u8{ 48, 5, color });
72}
73
74pub fn fg_rgb(w: *W, red: u8, green: u8, blue: u8) E!void {
75    try params(w, &[_]u8{ 38, 2, red, green, blue });
76}
77pub fn bg_rgb(w: *W, red: u8, green: u8, blue: u8) E!void {
78    try params(w, &[_]u8{ 48, 2, red, green, blue });
79}
80
81fn params(w: *W, p: []const u8) E!void {
82    try csi(w);
83    for (p, 0..) |c, i| {
84        try w.printInt(c, 10, .lower, .{});
85        if (i < p.len - 1) try w.writeByte(';');
86    }
87    try w.writeByte('m');
88}
89
90fn base(w: *W, c: u8) E!void {
91    try csi(w);
92    try w.printInt(c, 10, .lower, .{});
93    try w.writeByte('m');
94}
95
96fn csi(w: *W) E!void {
97    try w.writeByte('\x1B');
98    try w.writeByte('[');
99}