aboutsummaryrefslogtreecommitdiff
path: root/src/libcmd/markdown.cc
diff options
context:
space:
mode:
authorJohn Ericson <John.Ericson@Obsidian.Systems>2021-02-25 20:35:11 +0000
committerJohn Ericson <John.Ericson@Obsidian.Systems>2021-02-25 21:51:05 +0000
commitca0994819d68aee26a2906c37a47ae609ac46c4c (patch)
treec96805c008c22926b1eaadc340a99323d53be532 /src/libcmd/markdown.cc
parent10e81bf871551901ff0383bdede0f79325e93867 (diff)
parentc189031e8be0530d73a817571ad7f81ad5eedce6 (diff)
Merge remote-tracking branch 'upstream/master' into path-info
Diffstat (limited to 'src/libcmd/markdown.cc')
-rw-r--r--src/libcmd/markdown.cc50
1 files changed, 50 insertions, 0 deletions
diff --git a/src/libcmd/markdown.cc b/src/libcmd/markdown.cc
new file mode 100644
index 000000000..d25113d93
--- /dev/null
+++ b/src/libcmd/markdown.cc
@@ -0,0 +1,50 @@
+#include "markdown.hh"
+#include "util.hh"
+#include "finally.hh"
+
+#include <sys/queue.h>
+#include <lowdown.h>
+
+namespace nix {
+
+std::string renderMarkdownToTerminal(std::string_view markdown)
+{
+ struct lowdown_opts opts {
+ .type = LOWDOWN_TERM,
+ .maxdepth = 20,
+ .cols = std::min(getWindowSize().second, (unsigned short) 80),
+ .hmargin = 0,
+ .vmargin = 0,
+ .feat = LOWDOWN_COMMONMARK | LOWDOWN_FENCED | LOWDOWN_DEFLIST | LOWDOWN_TABLES,
+ .oflags = 0,
+ };
+
+ auto doc = lowdown_doc_new(&opts);
+ if (!doc)
+ throw Error("cannot allocate Markdown document");
+ Finally freeDoc([&]() { lowdown_doc_free(doc); });
+
+ size_t maxn = 0;
+ auto node = lowdown_doc_parse(doc, &maxn, markdown.data(), markdown.size());
+ if (!node)
+ throw Error("cannot parse Markdown document");
+ Finally freeNode([&]() { lowdown_node_free(node); });
+
+ auto renderer = lowdown_term_new(&opts);
+ if (!renderer)
+ throw Error("cannot allocate Markdown renderer");
+ Finally freeRenderer([&]() { lowdown_term_free(renderer); });
+
+ auto buf = lowdown_buf_new(16384);
+ if (!buf)
+ throw Error("cannot allocate Markdown output buffer");
+ Finally freeBuffer([&]() { lowdown_buf_free(buf); });
+
+ int rndr_res = lowdown_term_rndr(buf, nullptr, renderer, node);
+ if (!rndr_res)
+ throw Error("allocation error while rendering Markdown");
+
+ return std::string(buf->data, buf->size);
+}
+
+}