vmg / sundown

Standards compliant, fast, secure markdown processing library in C
1.99k stars 385 forks source link

Opened parsing flags to external code #97

Open tomaz opened 12 years ago

tomaz commented 12 years ago

I'm investigating replacement for Discount in my project (appledoc). Sundown seems like a way to go. Although I could use included html renderer out of the box, I need to preprocess Markdown before that (for detecting cross references for example).

For that to work, I need to do processing inside normal_text callback, however I need to work differently whether the text is inside a link or not and the simplest way I found it to work was to open up parsing flags to outside code - basically, I'd assign pointer to sd_markdown to my renderer opaque struct and check the flags in callbacks. One way would be to make whole sd_markdown public, but I didn't like that - so basically I refactored it into public/private interface.

To prevent breaking existing users code, I renamed what was before sd_markdown into sd_markdown_parser - this is used internally. And then I simply updated the public interface sd_markdown to include relevant flags. sd_markdown_parser includes sd_markdown struct as the first var - hence I can look at pointers to both structs either way. At this point the only flag included is in_link_body, but that can be extended in the future should the need be. So my code looks like this:

struct html_renderopt {
    ...
    struct sd_markdown *markdown;
    ...
};
int main() {
    ...
    sdhtml_renderer(&callbacks, &options, extensions);
    markdown = sd_markdown_parser_new(extensions, 16, &callbacks, &options);
    options.markdown = markdown;
    ...
}
static void
rndr_normal_text(struct buf *ob, const struct buf *text, void *opaque)
{
    if (text) {
        struct html_renderopt *options = (struct html_renderopt *)opaque;
        if (options->markdown->in_link_body == 1) { /* do whatever needed if in link */ }
        escape_html(ob, text->data, text->size);
    }
}

Hopefully you'll find additions useful and merge them to main branch - I'd love to be able to use future updates to main branch without the hassle of refactoring above changes every time :) But feel free to close pull request if you find changes not suitable for your audience.