Method: RDiscount#to_html

Defined in:
ext/rdiscount.c

#to_html(*args) ⇒ Object



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'ext/rdiscount.c', line 73

static VALUE
rb_rdiscount_to_html(int argc, VALUE *argv, VALUE self)
{
    /* grab char pointer to markdown input text */
    char *res;
    int szres;
    VALUE encoding;
    VALUE text = rb_funcall(self, rb_intern("text"), 0);
    VALUE buf = rb_str_buf_new(1024);
    Check_Type(text, T_STRING);

    int flags = rb_rdiscount__get_flags(self);
    
    /* 
     * Force Discount to use ASCII character encoding for isalnum(), isalpha(),
     * and similar functions.
     * 
     * Ruby tends to use UTF-8 encoding, which is ill-defined for these
     * functions since they expect 8-bit codepoints (and UTF-8 has codepoints
     * of at least 21 bits).
     */
    char *old_locale = strdup(setlocale(LC_CTYPE, NULL));
    setlocale(LC_CTYPE, "C");   /* ASCII (and passthru characters > 127) */

    MMIOT *doc = mkd_string(RSTRING_PTR(text), RSTRING_LEN(text), flags);

    if ( mkd_compile(doc, flags) ) {
        szres = mkd_document(doc, &res);

        if ( szres != EOF ) {
            rb_str_cat(buf, res, szres);
            rb_str_cat(buf, "\n", 1);
        }
    }
    mkd_cleanup(doc);

    setlocale(LC_CTYPE, old_locale);
    free(old_locale);

    /* force the input encoding */
    if ( rb_respond_to(text, rb_intern("encoding")) ) {
        encoding = rb_funcall(text, rb_intern("encoding"), 0);
        rb_funcall(buf, rb_intern("force_encoding"), 1, encoding);
    }

    return buf;
}