robin/maivi

a tiny cute lua web framework

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

robinlua: add md4c modulefdcf906

push-srxvuswpkqxx
1.5 KiB59 linesraw
1const std = @import("std");
2
3const fern = @import("fern");
4const md4c = @import("md4c");
5const zlua = @import("zlua");
6const Lua = zlua.Lua;
7
8const maivi = @import("../root.zig");
9
10pub fn lua_openmd4c(l: *Lua) !i32 {
11    l.createTable(0, 1);
12
13    l.pushFunction(zlua.wrap(tohtml));
14    l.setField(-2, "tohtml");
15
16    return 1;
17}
18
19const FLAGS: c_int = 0 |
20    // md4c.MD_FLAG_HIGHLIGHT |
21    // md4c.MD_FLAG_INSERT |
22    md4c.MD_FLAG_NOINDENTEDCODEBLOCKS |
23    // md4c.MD_FLAG_SPOILERS |
24    md4c.MD_FLAG_STRIKETHROUGH |
25    // md4c.MD_FLAG_SUBSCRIPTS |
26    // md4c.MD_FLAG_SUPERSCRIPTS |
27    md4c.MD_FLAG_TABLES |
28    md4c.MD_FLAG_TASKLISTS;
29
30pub fn tohtml(l: *Lua) !i32 {
31    l.argCheck(l.isString(1), 1, "string");
32
33    const Output = struct {
34        var buf: std.ArrayList(u8) = .empty;
35
36        pub fn process_output(chunk: [*c]const md4c.MD_CHAR, len: md4c.MD_SIZE, _: ?*anyopaque) callconv(.c) void {
37            buf.appendSlice(maivi.allocator, chunk[0..len]) catch |err| fern.err().err(err).log();
38        }
39    };
40    Output.buf = try .initCapacity(maivi.allocator, 0x400);
41    defer Output.buf.deinit(maivi.allocator);
42
43    const input = try l.toString(1);
44    const ret = md4c.md_html(
45        input,
46        @intCast(input.len),
47        &Output.process_output,
48        null,
49        FLAGS,
50        0,
51    );
52    if (ret == -1) l.raiseErrorStr("error while parsing markdown input", .{});
53
54    const buf = try Output.buf.toOwnedSlice(maivi.allocator);
55    defer maivi.allocator.free(buf);
56    _ = l.pushString(buf);
57
58    return 1;
59}