various improvements
[smdp.git] / src / parser.c
1 /*
2  * Functions necessary to parse a file and transform its content into
3  * a deck of slides containing lines. All based on markdown formating
4  * rules.
5  * Copyright (C) 2014 Michael Goehler
6  *
7  * This file is part of mdp.
8  *
9  * This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program. If not, see <http://www.gnu.org/licenses/>.
21  *
22  */
23
24 #include <ctype.h>
25 #include <errno.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29
30 #include "parser.h"
31
32 deck_t *markdown_load(FILE *input) {
33
34     int c = 0;    // char
35     int i = 0;    // increment
36     int hc = 0;   // header count
37     int lc = 0;   // line count
38     int sc = 1;   // slide count
39     int bits = 0; // markdown bits
40     int prev = 0; // markdown bits of previous line
41
42     deck_t *deck = new_deck();
43     slide_t *slide = deck->slide;
44     line_t *line = NULL;
45     line_t *tmp = NULL;
46     cstring_t *text = cstring_init();
47
48     // initialize bits as empty line
49     SET_BIT(bits, IS_EMPTY);
50
51     while ((c = fgetc(input)) != EOF) {
52         if (ferror(input)) {
53             fprintf(stderr, "markdown_load() failed to read input: %s\n", strerror(errno));
54             exit(EXIT_FAILURE);
55         }
56
57         if(c == '\n') {
58
59             // markdown analyse
60             prev = bits;
61             bits = markdown_analyse(text, prev);
62
63             // if first line in file is markdown hr
64             if(!line && CHECK_BIT(bits, IS_HR)) {
65
66                 // clear text
67                 (text->reset)(text);
68
69             // if text is markdown hr
70             } else if(CHECK_BIT(bits, IS_HR) &&
71                       CHECK_BIT(line->bits, IS_EMPTY)) {
72
73                 slide->lines = lc;
74
75                 // clear text
76                 (text->reset)(text);
77
78                 // create next slide
79                 slide = next_slide(slide);
80                 sc++;
81
82             } else {
83
84                 // if slide ! has line
85                 if(!slide->line) {
86
87                     // create new line
88                     line = new_line();
89                     slide->line = line;
90                     lc = 1;
91
92                 } else {
93
94                     // create next line
95                     line = next_line(line);
96                     lc++;
97
98                 }
99
100                 // add text to line
101                 line->text = text;
102
103                 // add bits to line
104                 line->bits = bits;
105
106                 // calc offset
107                 line->offset = next_nonblank(text, 0);
108
109                 // adjust line length dynamicaly - excluding markup
110                 if(line->text->text)
111                     adjust_line_length(line);
112
113                 // new text
114                 text = cstring_init();
115             }
116
117         } else if(c == '\t') {
118
119             // expand tab to spaces
120             for (i = 0;  i < EXPAND_TABS;  i++) {
121                 (text->expand)(text, ' ');
122             }
123
124         } else if(c == '\\') {
125
126             // add char to line
127             (text->expand)(text, c);
128
129             // if !IS_CODE add next char to line
130             // and do not increase line count
131             if(next_nonblank(text, 0) < CODE_INDENT) {
132
133                 c = fgetc(input);
134                 (text->expand)(text, c);
135
136                 if(is_utf8(c)) {
137
138                     // if utf-8 char > 1 byte add remaing to line
139                     for(i = 0; i < length_utf8(c) - 1; i++) {
140                         c = fgetc(input);
141                         (text->expand)(text, c);
142                     }
143                 }
144
145             }
146
147         } else if(isprint(c) || isspace((unsigned char) c)) {
148
149             // add char to line
150             (text->expand)(text, c);
151
152         } else if(is_utf8(c)) {
153
154             // add char to line
155             (text->expand)(text, c);
156
157             // if utf-8 char > 1 byte add remaing to line
158             for(i = 0; i < length_utf8(c) - 1; i++) {
159                 c = fgetc(input);
160                 (text->expand)(text, c);
161             }
162         }
163     }
164
165     slide->lines = lc;
166     deck->slides = sc;
167
168     // detect header
169     line = deck->slide->line;
170     if(line && line->text->size > 0 && line->text->text[0] == '%') {
171
172         // assign header to deck
173         deck->header = line;
174
175         // find first non-header line
176         while(line->text->size > 0 && line->text->text[0] == '%') {
177             hc++;
178             line = line->next;
179         }
180
181         // split linked list
182         line->prev->next = NULL;
183         line->prev = NULL;
184
185         // remove header lines from slide
186         deck->slide->line = line;
187
188         // adjust counts
189         deck->headers += hc;
190         deck->slide->lines -= hc;
191     }
192
193     slide = deck->slide;
194     while(slide) {
195         line = slide->line;
196         while(line) {
197             // combine underlined H1/H2 in single line
198             if((CHECK_BIT(line->bits, IS_H1) ||
199                 CHECK_BIT(line->bits, IS_H2)) &&
200                CHECK_BIT(line->bits, IS_EMPTY) &&
201                line->prev &&
202                !CHECK_BIT(line->prev->bits, IS_EMPTY)) {
203
204
205                 // remove line from linked list
206                 line->prev->next = line->next;
207                 if(line->next)
208                     line->next->prev = line->prev;
209
210                 // set bits on previous line
211                 if(CHECK_BIT(line->bits, IS_H1)) {
212                     SET_BIT(line->prev->bits, IS_H1);
213                 } else {
214                     SET_BIT(line->prev->bits, IS_H2);
215                 }
216
217                 // adjust line count
218                 slide->lines -= 1;
219
220                 // maintain loop condition
221                 tmp = line;
222                 line = line->prev;
223
224                 // delete line
225                 (tmp->text->delete)(tmp->text);
226                 free(tmp);
227
228             // pass enclosing flag IS_UNORDERED_LIST_3
229             // to nested levels for unordered lists
230             } else if(CHECK_BIT(line->bits, IS_UNORDERED_LIST_3)) {
231                 tmp = line->next;
232                 line_t *list_last_level_3 = line;
233
234                 while(tmp &&
235                       CHECK_BIT(tmp->bits, IS_UNORDERED_LIST_3)) {
236                     if(CHECK_BIT(tmp->bits, IS_UNORDERED_LIST_3)) {
237                         list_last_level_3 = tmp;
238                     }
239                     tmp = tmp->next;
240                 }
241
242                 for(tmp = line; tmp != list_last_level_3; tmp = tmp->next) {
243                     SET_BIT(tmp->bits, IS_UNORDERED_LIST_3);
244                 }
245
246             // pass enclosing flag IS_UNORDERED_LIST_2
247             // to nested levels for unordered lists
248             } else if(CHECK_BIT(line->bits, IS_UNORDERED_LIST_2)) {
249                 tmp = line->next;
250                 line_t *list_last_level_2 = line;
251
252                 while(tmp &&
253                       (CHECK_BIT(tmp->bits, IS_UNORDERED_LIST_2) ||
254                        CHECK_BIT(tmp->bits, IS_UNORDERED_LIST_3))) {
255                     if(CHECK_BIT(tmp->bits, IS_UNORDERED_LIST_2)) {
256                         list_last_level_2 = tmp;
257                     }
258                     tmp = tmp->next;
259                 }
260
261                 for(tmp = line; tmp != list_last_level_2; tmp = tmp->next) {
262                     SET_BIT(tmp->bits, IS_UNORDERED_LIST_2);
263                 }
264
265             // pass enclosing flag IS_UNORDERED_LIST_1
266             // to nested levels for unordered lists
267             } else if(CHECK_BIT(line->bits, IS_UNORDERED_LIST_1)) {
268                 tmp = line->next;
269                 line_t *list_last_level_1 = line;
270
271                 while(tmp &&
272                       (CHECK_BIT(tmp->bits, IS_UNORDERED_LIST_1) ||
273                        CHECK_BIT(tmp->bits, IS_UNORDERED_LIST_2) ||
274                        CHECK_BIT(tmp->bits, IS_UNORDERED_LIST_3))) {
275                     if(CHECK_BIT(tmp->bits, IS_UNORDERED_LIST_1)) {
276                         list_last_level_1 = tmp;
277                     }
278                     tmp = tmp->next;
279                 }
280
281                 for(tmp = line; tmp != list_last_level_1; tmp = tmp->next) {
282                     SET_BIT(tmp->bits, IS_UNORDERED_LIST_1);
283                 }
284             }
285
286             line = line->next;
287         }
288         slide = slide->next;
289     }
290
291     return deck;
292 }
293
294 int markdown_analyse(cstring_t *text, int prev) {
295
296     // static variables can not be redeclaired, but changed outside of a declaration
297     // the program remembers their value on every function calls
298     static int unordered_list_level = 0;
299     static int unordered_list_level_offset[] = {-1, -1, -1, -1};
300
301     int i = 0;      // increment
302     int bits = 0;   // markdown bits
303     int offset = 0; // text offset
304     int eol    = 0; // end of line
305
306     int equals = 0, hashes = 0,
307         stars  = 0, minus  = 0,
308         spaces = 0, other  = 0; // special character counts
309
310     const int unordered_list_offset = unordered_list_level_offset[unordered_list_level];
311
312     // return IS_EMPTY on null pointers
313     if(!text || !text->text) {
314         SET_BIT(bits, IS_EMPTY);
315         return bits;
316     }
317
318     // count leading spaces
319     offset = next_nonblank(text, 0);
320
321     // strip trailing spaces
322     for(eol = text->size; eol > offset && isspace((unsigned char) text->text[eol - 1]); eol--);
323
324     // IS_UNORDERED_LIST_#
325     if(text->size >= offset + 2 &&
326        (text->text[offset] == '*' || text->text[offset] == '-') &&
327        text->text[offset + 1] == ' ') {
328
329         // if different from last lines offset
330         if(offset != unordered_list_offset) {
331
332             // test if offset matches a lower indent level
333             for(i = unordered_list_level; i >= 0; i--) {
334                 if(unordered_list_level_offset[i] == offset) {
335                     unordered_list_level = i;
336                     break;
337                 }
338             }
339             // if offset doesn't match any previously stored indent level
340             if(i != unordered_list_level) {
341                 unordered_list_level = MIN(unordered_list_level + 1, UNORDERED_LIST_MAX_LEVEL);
342                 // memorize the offset as next bigger indent level
343                 unordered_list_level_offset[unordered_list_level] = offset;
344             }
345         }
346
347         // if no previous indent level matches, this must be the first line of the list
348         if(unordered_list_level == 0) {
349             unordered_list_level = 1;
350             unordered_list_level_offset[1] = offset;
351         }
352
353         switch(unordered_list_level) {
354             case 1: SET_BIT(bits, IS_UNORDERED_LIST_1); break;
355             case 2: SET_BIT(bits, IS_UNORDERED_LIST_2); break;
356             case 3: SET_BIT(bits, IS_UNORDERED_LIST_3); break;
357             default: break;
358         }
359     }
360
361     if(!CHECK_BIT(bits, IS_UNORDERED_LIST_1) &&
362        !CHECK_BIT(bits, IS_UNORDERED_LIST_2) &&
363        !CHECK_BIT(bits, IS_UNORDERED_LIST_3)) {
364
365         // continue list if indent level is still the same as in previous line
366         if ((CHECK_BIT(prev, IS_UNORDERED_LIST_1) ||
367              CHECK_BIT(prev, IS_UNORDERED_LIST_2) ||
368              CHECK_BIT(prev, IS_UNORDERED_LIST_3)) &&
369             offset >= unordered_list_offset) {
370
371             switch(unordered_list_level) {
372                 case 1: SET_BIT(bits, IS_UNORDERED_LIST_1); break;
373                 case 2: SET_BIT(bits, IS_UNORDERED_LIST_2); break;
374                 case 3: SET_BIT(bits, IS_UNORDERED_LIST_3); break;
375                 default: break;
376             }
377
378             // this line extends the previous list item
379             SET_BIT(bits, IS_UNORDERED_LIST_EXT);
380
381         // or reset indent level
382         } else {
383             unordered_list_level = 0;
384         }
385     }
386
387     if(!CHECK_BIT(bits, IS_UNORDERED_LIST_1) &&
388        !CHECK_BIT(bits, IS_UNORDERED_LIST_2) &&
389        !CHECK_BIT(bits, IS_UNORDERED_LIST_3)) {
390
391         // IS_CODE
392         if(offset >= CODE_INDENT &&
393            (CHECK_BIT(prev, IS_EMPTY) ||
394             CHECK_BIT(prev, IS_CODE))) {
395             SET_BIT(bits, IS_CODE);
396
397         } else {
398
399             // IS_QUOTE
400             if(text->text[offset] == '>') {
401                 SET_BIT(bits, IS_QUOTE);
402             }
403
404             // IS_CENTER
405             if(text->size >= offset + 3 &&
406                text->text[offset] == '-' &&
407                text->text[offset + 1] == '>' &&
408                text->text[offset + 2] == ' ') {
409                 SET_BIT(bits, IS_CENTER);
410
411                 // remove start tag
412                 (text->strip)(text, offset, 3);
413                 eol -= 3;
414
415                 if(text->size >= offset + 3 &&
416                    text->text[eol - 1] == '-' &&
417                    text->text[eol - 2] == '<' &&
418                    text->text[eol - 3] == ' ') {
419
420                     // remove end tags
421                     (text->strip)(text, eol - 3, 3);
422
423                     // adjust end of line
424                     for(eol = text->size; eol > offset && isspace((unsigned char) text->text[eol - 1]); eol--);
425
426                 }
427             }
428
429             for(i = offset; i < eol; i++) {
430
431                 if(text->text[i] == ' ') {
432                     spaces++;
433
434                 } else {
435                     switch(text->text[i]) {
436                         case '=': equals++;  break;
437                         case '#': hashes++;  break;
438                         case '*': stars++;   break;
439                         case '-': minus++;   break;
440                         case '\\': other++; i++; break;
441                         default:  other++;   break;
442                     }
443                 }
444             }
445
446             // IS_H1
447             if(equals > 0 &&
448                 hashes + stars + minus + spaces + other == 0) {
449                 SET_BIT(bits, IS_H1);
450             }
451             if(text->text[offset] == '#' &&
452                 text->text[offset+1] == ' ') {
453                 SET_BIT(bits, IS_H1);
454                 SET_BIT(bits, IS_H1_ATX);
455             }
456
457             // IS_H2
458             if(minus > 0 &&
459                 equals + hashes + stars + spaces + other == 0) {
460                 SET_BIT(bits, IS_H2);
461             }
462             if(text->text[offset] == '#' &&
463                 text->text[offset+1] == '#' &&
464                 text->text[offset+2] == ' ') {
465                 SET_BIT(bits, IS_H2);
466                 SET_BIT(bits, IS_H2_ATX);
467             }
468
469             // IS_HR
470             if((minus >= 3 && equals + hashes + stars + other == 0) ||
471                (stars >= 3 && equals + hashes + minus + other == 0)) {
472
473                 SET_BIT(bits, IS_HR);
474             }
475
476             // IS_EMPTY
477             if(other == 0) {
478                 SET_BIT(bits, IS_EMPTY);
479             }
480         }
481     }
482
483     return bits;
484 }
485
486 void markdown_debug(deck_t *deck, int debug) {
487
488     int sc = 0; // slide count
489     int lc = 0; // line count
490
491     int offset;
492     line_t *header;
493
494     if(debug == 1) {
495         fprintf(stderr, "headers: %i\nslides: %i\n", deck->headers, deck->slides);
496
497     } else if(debug > 1) {
498
499         // print header to STDERR
500         if(deck->header) {
501             header = deck->header;
502             while(header &&
503                 header->length > 0 &&
504                 header->text->text[0] == '%') {
505
506                 // skip descriptor word (e.g. %title:)
507                 offset = next_blank(header->text, 0) + 1;
508
509                 fprintf(stderr, "header: %s\n", &header->text->text[offset]);
510                 header = header->next;
511             }
512         }
513     }
514
515     slide_t *slide = deck->slide;
516     line_t *line;
517
518     // print slide/line count to STDERR
519     while(slide) {
520         sc++;
521
522         if(debug == 1) {
523             fprintf(stderr, "  slide %i: %i lines\n", sc, slide->lines);
524
525         } else if(debug > 1) {
526
527             // also print bits and line length
528             fprintf(stderr, "  slide %i:\n", sc);
529             line = slide->line;
530             lc = 0;
531             while(line) {
532                 lc++;
533                 fprintf(stderr, "    line %i: bits = %i, length = %i\n", lc, line->bits, line->length);
534                 line = line->next;
535             }
536         }
537
538         slide = slide->next;
539     }
540 }
541
542 void adjust_line_length(line_t *line) {
543     int l = 0;
544     const static char *special = "\\*_`"; // list of interpreted chars
545     const char *c = &line->text->text[line->offset];
546     cstack_t *stack = cstack_init();
547
548     // for each char in line
549     for(; *c; c++) {
550         // if char is in special char list
551         if(strchr(special, *c)) {
552
553             // closing special char (or second backslash)
554             if((stack->top)(stack, *c)) {
555                 if(*c == '\\') l++;
556                 (stack->pop)(stack);
557
558             // treat special as regular char
559             } else if((stack->top)(stack, '\\')) {
560                 l++;
561                 (stack->pop)(stack);
562
563             // opening special char
564             } else {
565                 (stack->push)(stack, *c);
566             }
567
568         } else {
569             // remove backslash from stack
570             if((stack->top)(stack, '\\'))
571                 (stack->pop)(stack);
572             l++;
573         }
574     }
575
576     if(CHECK_BIT(line->bits, IS_H1_ATX))
577         l -= 2;
578     if(CHECK_BIT(line->bits, IS_H2_ATX))
579         l -= 3;
580
581     line->length = l;
582
583     (stack->delete)(stack);
584 }
585
586 bool is_utf8(char ch) {
587     return (ch & 0x80) != 0x00;
588 }
589
590 int length_utf8(char ch) {
591
592     int i = 0; // increment
593
594     while(is_utf8(ch)) {
595         i++;
596         ch <<= 1;
597     }
598
599     return i;
600 }
601
602 int next_nonblank(cstring_t *text, int i) {
603     while ((i < text->size) && isspace((unsigned char) (text->text)[i]))
604         i++;
605
606     return i;
607 }
608
609 int prev_blank(cstring_t *text, int i) {
610     while ((i > 0) && !isspace((unsigned char) (text->text)[i]))
611         i--;
612
613     return i;
614 }
615
616 int next_blank(cstring_t *text, int i) {
617     while ((i < text->size) && !isspace((unsigned char) (text->text)[i]))
618         i++;
619
620     return i;
621 }
622
623 int next_word(cstring_t *text, int i) {
624     return next_nonblank(text, next_blank(text, i));
625 }