~gpanders/wk

ref: cecdf4253b507cef4f1595078ac7e0b41b738fb1 wk/src/cmd/show.zig -rw-r--r-- 1.4 KiB
cecdf425 — Gregory Anders Highlight triple dots as closing front matter fence 2 months ago
                                                                                
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
const std = @import("std");
const ChildProcess = std.ChildProcess;
const fs = std.fs;
const mem = std.mem;

const ColorWriter = @import("../tty.zig").ColorWriter;
const Command = @import("../cmd.zig").Command;
const Page = @import("../core.zig").Page;
const getPages = @import("../core.zig").getPages;

pub const cmd = Command{
    .name = "show",
    .aliases = &[_][]const u8{ "s", "sh" },
    .usage = "s|show <PATTERN> [PATTERN ...]",
    .desc = "Display contents of notes containing PATTERN.",
    .run = run,
};

pub fn run(allocator: *mem.Allocator, args: ?[]const []const u8) Command.Error!void {
    if (args) |patterns| {
        const writer = ColorWriter.new(std.io.getStdOut());
        const pages = try getPages(allocator);
        for (pages) |page| {
            if (!page.match(patterns)) continue;

            writer.setColor(.Blue).print("{}\n", .{page.fname});

            var it = mem.split(page.contents, "\n");

            // Print front matter fences in yellow
            writer.setColor(.Yellow).print("{}\n", .{it.next()});

            while (it.next()) |line| {
                const fence = mem.eql(u8, line, "---") or mem.eql(u8, line, "...");
                writer.setColor(if (fence) .Yellow else null).print("{}\n", .{line});
                if (fence) break;
            }

            writer.print("{}\n", .{it.rest()});
        }
    } else {
        return error.MissingRequiredArgument;
    }
}