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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
#include <stdlib.h>
#include <string.h>
#include <lua.h>
#include "honeysuckle.h"
#include "md4c-html.h"
#include "bindings.h"
#include "logging.h"
struct concat_buffer {
char *buf;
size_t size;
int index;
bool ok;
};
static void md_callback(const MD_CHAR *html, MD_SIZE size, void *data)
{
argent_log(TRACE, "begin md_callback()");
struct concat_buffer *d = data;
if (!d->ok)
return;
if (d->index + size >= d->size) {
char *new_buf = realloc(d->buf, d->size * 2);
if (new_buf == NULL) {
// failed to allocate memory, abort!
argent_log(WARN, "failed to properly allocate memory for html buffer!");
d->ok = false;
return;
}
d->buf = new_buf;
d->size *= 2;
}
memcpy((d->buf) + d->index, html, size);
d->index += size;
argent_log(TRACE, "finish md_callback()");
}
int markdown(lua_State *L)
{
argent_log(DEBUG, "begin markdown parsing");
char *markdown_buffer;
hs_parse_args(L, hs_str(markdown_buffer));
size_t len = strlen(markdown_buffer);
argent_log(TRACE, "markdown input (%ld bytes): %s", len, markdown_buffer);
unsigned int md_flags = MD_FLAG_TABLES | MD_FLAG_STRIKETHROUGH | MD_FLAG_UNDERLINE;
struct concat_buffer data;
data.buf = malloc(128 * sizeof(char));
data.size = 128 * sizeof(char);
data.index = 0;
data.ok = true;
argent_log(TRACE, "call md_html()");
// fill out the buffer
int error = md_html(markdown_buffer, len, md_callback, &data, md_flags, 0);
if (error)
hs_throw_error(L, "markdown parsing failed!");
if (data.ok == false)
hs_throw_error(L, "encountered error (re)allocating html buffer memory!");
data.buf[data.index] = 0;
argent_log(TRACE, "finished HTML buffer (%d bytes, %d chars): %s",
data.size, data.index, data.buf);
lua_pushstring(L, data.buf);
free(data.buf);
argent_log(DEBUG, "finish markdown parsing");
return 1;
}
|