2020-08-24 16:10:33 +00:00
|
|
|
#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)
|
|
|
|
{
|
2022-05-06 11:14:49 +00:00
|
|
|
int windowWidth = getWindowSize().second;
|
|
|
|
|
2020-08-24 16:10:33 +00:00
|
|
|
struct lowdown_opts opts {
|
|
|
|
.type = LOWDOWN_TERM,
|
|
|
|
.maxdepth = 20,
|
2022-05-06 11:14:49 +00:00
|
|
|
.cols = (size_t) std::max(windowWidth - 5, 60),
|
2020-08-24 16:10:33 +00:00
|
|
|
.hmargin = 0,
|
|
|
|
.vmargin = 0,
|
|
|
|
.feat = LOWDOWN_COMMONMARK | LOWDOWN_FENCED | LOWDOWN_DEFLIST | LOWDOWN_TABLES,
|
2022-08-26 12:03:40 +00:00
|
|
|
.oflags = LOWDOWN_TERM_NOLINK,
|
2020-08-24 16:10:33 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
auto doc = lowdown_doc_new(&opts);
|
|
|
|
if (!doc)
|
|
|
|
throw Error("cannot allocate Markdown document");
|
|
|
|
Finally freeDoc([&]() { lowdown_doc_free(doc); });
|
|
|
|
|
|
|
|
size_t maxn = 0;
|
2021-09-24 13:21:41 +00:00
|
|
|
auto node = lowdown_doc_parse(doc, &maxn, markdown.data(), markdown.size(), nullptr);
|
2020-08-24 16:10:33 +00:00
|
|
|
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); });
|
|
|
|
|
2021-09-24 13:21:41 +00:00
|
|
|
int rndr_res = lowdown_term_rndr(buf, renderer, node);
|
2021-02-06 11:59:11 +00:00
|
|
|
if (!rndr_res)
|
|
|
|
throw Error("allocation error while rendering Markdown");
|
2020-08-24 16:10:33 +00:00
|
|
|
|
2021-09-14 12:57:58 +00:00
|
|
|
return filterANSIEscapes(std::string(buf->data, buf->size), !shouldANSI());
|
2020-08-24 16:10:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|