ShabbyX / libpandoc

C bindings to Pandoc, a markup converter library written in Haskell.
88 stars 16 forks source link

Empty lines at the end of the output #8

Closed Phyks closed 7 years ago

Phyks commented 7 years ago

Hi,

I have a minimal C file using libpandoc like this:

#include <stdlib.h>
#include <string.h>

#include <pandoc.h>

int done = 0;
const char test[] = "$\\textit{K}$ -trivial, $\\textit{K}$ -low and ${{\\mathrm{\\textit{MLR}}}}$ -low Sequences: A Tutorial";
const int BUFFER_LENGTH = 1024;

int reader(char *buf, void *user_data) {
    if (done) {
        return 0;
    }
    strncpy(buf, test, BUFFER_LENGTH);
    done = 1;
    return strlen(test);
}

void writer(const char *buf, int len, void *user_data) {
    printf("%s\n", buf);
}

int main() {
    pandoc_init();
    pandoc(BUFFER_LENGTH, "markdown", "plain", NULL, &reader, &writer, NULL);
    pandoc_exit();
}

I would expect the output to be

K -trivial, K -low and MLR -low Sequences: A Tutorial

as given by Pandoc.

However the output ends with a lot of empty newlines, I am not sure why:

K -trivial, K -low and MLR -low Sequences: A Tutorial

Thanks!

P.S.: It would be really useful to have an example code making use of libpandoc in the repo. I can submit a PR addressing this, if you want.

ShabbyX commented 7 years ago

The buf sent to writer() is not necessarily NUL-terminated. In fact, most of the time it isn't because the output could be given to writer() in chunks. That's also why there's a len argument.

Try fwrite(buf, 1, len, stdout); instead of printf and see if you get the correct output. In case pandoc() doesn't add a newline at the end of output (never tested this, so not sure), you may want to add a printf("\n"); right after your pandoc() call.

So something like this:

#include <stdlib.h>
#include <string.h>

#include <pandoc.h>

int done = 0;
const char test[] = "$\\textit{K}$ -trivial, $\\textit{K}$ -low and ${{\\mathrm{\\textit{MLR}}}}$ -low Sequences: A Tutorial";
const int BUFFER_LENGTH = 1024;

int reader(char *buf, void *user_data) {
    if (done) {
        return 0;
    }
    strncpy(buf, test, BUFFER_LENGTH);
    done = 1;
    return strlen(test);
}

void writer(const char *buf, int len, void *user_data) {
    fwrite(buf, 1, len, stdout);
}

int main() {
    pandoc_init();
    pandoc(BUFFER_LENGTH, "markdown", "plain", NULL, &reader, &writer, NULL);
    printf("\n");      /* if desired */
    pandoc_exit();
}
Phyks commented 7 years ago

Thanks for the explanations!