4 #include "include/cstring.h"
5 #include "include/markdown.h"
7 document_t *markdown_load(FILE *input) {
9 int c = 0, i = 0, bits = 0;
19 text = cstring_init();
21 while ((c = fgetc(input)) != EOF) {
25 bits = markdown_analyse(text);
27 // if text is markdown hr
28 if(CHECK_BIT(bits, IS_HR)) {
33 page = next_page(page);
47 line = next_line(line);
58 line->offset = next_nonblank(text, 0);
61 text = cstring_init();
64 } else if(c == '\t') {
66 // expand tab to spaces
67 for (i = 0; i <= 4; i++)
68 (text->expand)(text, ' ');
70 } else if(isprint(c) || isspace(c) || is_utf8(c)) {
73 (text->expand)(text, c);
78 line = doc->page->line;
79 if(line && line->text->size > 0 && line->text->text[0] == '%') {
81 // assign header to document
84 // find first non-header line
85 while(line->text->size > 0 && line->text->text[0] == '%') {
90 line->prev->next = (void*)0;
91 line->prev = (void*)0;
93 // remove header lines from page
94 doc->page->line = line;
100 int markdown_analyse(cstring_t *text) {
103 equals = 0, hashes = 0, stars = 0, minus = 0, plus = 0,
104 spaces = 0, other = 0;
106 // count leading spaces
107 offset = next_nonblank(text, 0);
111 SET_BIT(bits, IS_CODE);
115 // strip trailing spaces
116 for(eol = text->size; eol > offset && isspace(text->text[eol - 1]); eol--);
118 for(i = offset; i < eol; i++) {
120 switch(text->text[i]) {
121 case '=': equals++; break;
122 case '#': hashes++; break;
123 case '*': stars++; break;
124 case '-': minus++; break;
125 case '+': plus++; break;
126 case ' ': spaces++; break;
127 default: other++; break;
132 if((minus >= 3 && equals + hashes + stars + plus == 0) ||
133 (stars >= 3 && equals + hashes + minus + plus == 0)) {
135 SET_BIT(bits, IS_HR);
139 //TODO all the other markdown tags
144 int is_utf8(char ch) {
148 int next_nonblank(cstring_t *text, int i) {
149 while ((i < text->size) && isspace((text->text)[i]))
154 int next_blank(cstring_t *text, int i) {
155 while ((i < text->size) && !isspace((text->text)[i]))