fixed duplicated reference in header-only files, #66, #67
[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     (text->delete)(text);
165
166     slide->lines = lc;
167     deck->slides = sc;
168
169     // detect header
170     line = deck->slide->line;
171     if(line && line->text->size > 0 && line->text->text[0] == '%') {
172
173         // assign header to deck
174         deck->header = line;
175
176         // find first non-header line
177         while(line && line->text->size > 0 && line->text->text[0] == '%') {
178             hc++;
179             line = line->next;
180         }
181
182         // only split header if any non-header line is found
183         if(line) {
184
185             // split linked list
186             line->prev->next = NULL;
187             line->prev = NULL;
188
189             // remove header lines from slide
190             deck->slide->line = line;
191
192             // adjust counts
193             deck->headers += hc;
194             deck->slide->lines -= hc;
195         } else {
196
197             // remove header from deck
198             deck->header = NULL;
199         }
200     }
201
202     slide = deck->slide;
203     while(slide) {
204         line = slide->line;
205         while(line) {
206             // combine underlined H1/H2 in single line
207             if((CHECK_BIT(line->bits, IS_H1) ||
208                 CHECK_BIT(line->bits, IS_H2)) &&
209                CHECK_BIT(line->bits, IS_EMPTY) &&
210                line->prev &&
211                !CHECK_BIT(line->prev->bits, IS_EMPTY)) {
212
213
214                 // remove line from linked list
215                 line->prev->next = line->next;
216                 if(line->next)
217                     line->next->prev = line->prev;
218
219                 // set bits on previous line
220                 if(CHECK_BIT(line->bits, IS_H1)) {
221                     SET_BIT(line->prev->bits, IS_H1);
222                 } else {
223                     SET_BIT(line->prev->bits, IS_H2);
224                 }
225
226                 // adjust line count
227                 slide->lines -= 1;
228
229                 // maintain loop condition
230                 tmp = line;
231                 line = line->prev;
232
233                 // delete line
234                 (tmp->text->delete)(tmp->text);
235                 free(tmp);
236
237             // pass enclosing flag IS_UNORDERED_LIST_3
238             // to nested levels for unordered lists
239             } else if(CHECK_BIT(line->bits, IS_UNORDERED_LIST_3)) {
240                 tmp = line->next;
241                 line_t *list_last_level_3 = line;
242
243                 while(tmp &&
244                       CHECK_BIT(tmp->bits, IS_UNORDERED_LIST_3)) {
245                     if(CHECK_BIT(tmp->bits, IS_UNORDERED_LIST_3)) {
246                         list_last_level_3 = tmp;
247                     }
248                     tmp = tmp->next;
249                 }
250
251                 for(tmp = line; tmp != list_last_level_3; tmp = tmp->next) {
252                     SET_BIT(tmp->bits, IS_UNORDERED_LIST_3);
253                 }
254
255             // pass enclosing flag IS_UNORDERED_LIST_2
256             // to nested levels for unordered lists
257             } else if(CHECK_BIT(line->bits, IS_UNORDERED_LIST_2)) {
258                 tmp = line->next;
259                 line_t *list_last_level_2 = line;
260
261                 while(tmp &&
262                       (CHECK_BIT(tmp->bits, IS_UNORDERED_LIST_2) ||
263                        CHECK_BIT(tmp->bits, IS_UNORDERED_LIST_3))) {
264                     if(CHECK_BIT(tmp->bits, IS_UNORDERED_LIST_2)) {
265                         list_last_level_2 = tmp;
266                     }
267                     tmp = tmp->next;
268                 }
269
270                 for(tmp = line; tmp != list_last_level_2; tmp = tmp->next) {
271                     SET_BIT(tmp->bits, IS_UNORDERED_LIST_2);
272                 }
273
274             // pass enclosing flag IS_UNORDERED_LIST_1
275             // to nested levels for unordered lists
276             } else if(CHECK_BIT(line->bits, IS_UNORDERED_LIST_1)) {
277                 tmp = line->next;
278                 line_t *list_last_level_1 = line;
279
280                 while(tmp &&
281                       (CHECK_BIT(tmp->bits, IS_UNORDERED_LIST_1) ||
282                        CHECK_BIT(tmp->bits, IS_UNORDERED_LIST_2) ||
283                        CHECK_BIT(tmp->bits, IS_UNORDERED_LIST_3))) {
284                     if(CHECK_BIT(tmp->bits, IS_UNORDERED_LIST_1)) {
285                         list_last_level_1 = tmp;
286                     }
287                     tmp = tmp->next;
288                 }
289
290                 for(tmp = line; tmp != list_last_level_1; tmp = tmp->next) {
291                     SET_BIT(tmp->bits, IS_UNORDERED_LIST_1);
292                 }
293             }
294
295             line = line->next;
296         }
297         slide = slide->next;
298     }
299
300     return deck;
301 }
302
303 int markdown_analyse(cstring_t *text, int prev) {
304
305     // static variables can not be redeclaired, but changed outside of a declaration
306     // the program remembers their value on every function calls
307     static int unordered_list_level = 0;
308     static int unordered_list_level_offset[] = {-1, -1, -1, -1};
309
310     int i = 0;      // increment
311     int bits = 0;   // markdown bits
312     int offset = 0; // text offset
313     int eol    = 0; // end of line
314
315     int equals = 0, hashes = 0,
316         stars  = 0, minus  = 0,
317         spaces = 0, other  = 0; // special character counts
318
319     const int unordered_list_offset = unordered_list_level_offset[unordered_list_level];
320
321     // return IS_EMPTY on null pointers
322     if(!text || !text->text) {
323         SET_BIT(bits, IS_EMPTY);
324         return bits;
325     }
326
327     // count leading spaces
328     offset = next_nonblank(text, 0);
329
330     // strip trailing spaces
331     for(eol = text->size; eol > offset && isspace((unsigned char) text->text[eol - 1]); eol--);
332
333     // IS_UNORDERED_LIST_#
334     if(text->size >= offset + 2 &&
335        (text->text[offset] == '*' || text->text[offset] == '-') &&
336        text->text[offset + 1] == ' ') {
337
338         // if different from last lines offset
339         if(offset != unordered_list_offset) {
340
341             // test if offset matches a lower indent level
342             for(i = unordered_list_level; i >= 0; i--) {
343                 if(unordered_list_level_offset[i] == offset) {
344                     unordered_list_level = i;
345                     break;
346                 }
347             }
348             // if offset doesn't match any previously stored indent level
349             if(i != unordered_list_level) {
350                 unordered_list_level = MIN(unordered_list_level + 1, UNORDERED_LIST_MAX_LEVEL);
351                 // memorize the offset as next bigger indent level
352                 unordered_list_level_offset[unordered_list_level] = offset;
353             }
354         }
355
356         // if no previous indent level matches, this must be the first line of the list
357         if(unordered_list_level == 0) {
358             unordered_list_level = 1;
359             unordered_list_level_offset[1] = offset;
360         }
361
362         switch(unordered_list_level) {
363             case 1: SET_BIT(bits, IS_UNORDERED_LIST_1); break;
364             case 2: SET_BIT(bits, IS_UNORDERED_LIST_2); break;
365             case 3: SET_BIT(bits, IS_UNORDERED_LIST_3); break;
366             default: break;
367         }
368     }
369
370     if(!CHECK_BIT(bits, IS_UNORDERED_LIST_1) &&
371        !CHECK_BIT(bits, IS_UNORDERED_LIST_2) &&
372        !CHECK_BIT(bits, IS_UNORDERED_LIST_3)) {
373
374         // continue list if indent level is still the same as in previous line
375         if ((CHECK_BIT(prev, IS_UNORDERED_LIST_1) ||
376              CHECK_BIT(prev, IS_UNORDERED_LIST_2) ||
377              CHECK_BIT(prev, IS_UNORDERED_LIST_3)) &&
378             offset >= unordered_list_offset) {
379
380             switch(unordered_list_level) {
381                 case 1: SET_BIT(bits, IS_UNORDERED_LIST_1); break;
382                 case 2: SET_BIT(bits, IS_UNORDERED_LIST_2); break;
383                 case 3: SET_BIT(bits, IS_UNORDERED_LIST_3); break;
384                 default: break;
385             }
386
387             // this line extends the previous list item
388             SET_BIT(bits, IS_UNORDERED_LIST_EXT);
389
390         // or reset indent level
391         } else {
392             unordered_list_level = 0;
393         }
394     }
395
396     if(!CHECK_BIT(bits, IS_UNORDERED_LIST_1) &&
397        !CHECK_BIT(bits, IS_UNORDERED_LIST_2) &&
398        !CHECK_BIT(bits, IS_UNORDERED_LIST_3)) {
399
400         // IS_CODE
401         if(offset >= CODE_INDENT &&
402            (CHECK_BIT(prev, IS_EMPTY) ||
403             CHECK_BIT(prev, IS_CODE))) {
404             SET_BIT(bits, IS_CODE);
405
406         } else {
407
408             // IS_QUOTE
409             if(text->text[offset] == '>') {
410                 SET_BIT(bits, IS_QUOTE);
411             }
412
413             // IS_CENTER
414             if(text->size >= offset + 3 &&
415                text->text[offset] == '-' &&
416                text->text[offset + 1] == '>' &&
417                text->text[offset + 2] == ' ') {
418                 SET_BIT(bits, IS_CENTER);
419
420                 // remove start tag
421                 (text->strip)(text, offset, 3);
422                 eol -= 3;
423
424                 if(text->size >= offset + 3 &&
425                    text->text[eol - 1] == '-' &&
426                    text->text[eol - 2] == '<' &&
427                    text->text[eol - 3] == ' ') {
428
429                     // remove end tags
430                     (text->strip)(text, eol - 3, 3);
431
432                     // adjust end of line
433                     for(eol = text->size; eol > offset && isspace((unsigned char) text->text[eol - 1]); eol--);
434
435                 }
436             }
437
438             for(i = offset; i < eol; i++) {
439
440                 if(text->text[i] == ' ') {
441                     spaces++;
442
443                 } else {
444                     switch(text->text[i]) {
445                         case '=': equals++;  break;
446                         case '#': hashes++;  break;
447                         case '*': stars++;   break;
448                         case '-': minus++;   break;
449                         case '\\': other++; i++; break;
450                         default:  other++;   break;
451                     }
452                 }
453             }
454
455             // IS_H1
456             if(equals > 0 &&
457                 hashes + stars + minus + spaces + other == 0) {
458                 SET_BIT(bits, IS_H1);
459             }
460             if(text->text[offset] == '#' &&
461                 text->text[offset+1] == ' ') {
462                 SET_BIT(bits, IS_H1);
463                 SET_BIT(bits, IS_H1_ATX);
464             }
465
466             // IS_H2
467             if(minus > 0 &&
468                 equals + hashes + stars + spaces + other == 0) {
469                 SET_BIT(bits, IS_H2);
470             }
471             if(text->text[offset] == '#' &&
472                 text->text[offset+1] == '#' &&
473                 text->text[offset+2] == ' ') {
474                 SET_BIT(bits, IS_H2);
475                 SET_BIT(bits, IS_H2_ATX);
476             }
477
478             // IS_HR
479             if((minus >= 3 && equals + hashes + stars + other == 0) ||
480                (stars >= 3 && equals + hashes + minus + other == 0)) {
481
482                 SET_BIT(bits, IS_HR);
483             }
484
485             // IS_EMPTY
486             if(other == 0) {
487                 SET_BIT(bits, IS_EMPTY);
488             }
489         }
490     }
491
492     return bits;
493 }
494
495 void markdown_debug(deck_t *deck, int debug) {
496
497     int sc = 0; // slide count
498     int lc = 0; // line count
499
500     int offset;
501     line_t *header;
502
503     if(debug == 1) {
504         fprintf(stderr, "headers: %i\nslides: %i\n", deck->headers, deck->slides);
505
506     } else if(debug > 1) {
507
508         // print header to STDERR
509         if(deck->header) {
510             header = deck->header;
511             while(header &&
512                 header->length > 0 &&
513                 header->text->text[0] == '%') {
514
515                 // skip descriptor word (e.g. %title:)
516                 offset = next_blank(header->text, 0) + 1;
517
518                 fprintf(stderr, "header: %s\n", &header->text->text[offset]);
519                 header = header->next;
520             }
521         }
522     }
523
524     slide_t *slide = deck->slide;
525     line_t *line;
526
527     // print slide/line count to STDERR
528     while(slide) {
529         sc++;
530
531         if(debug == 1) {
532             fprintf(stderr, "  slide %i: %i lines\n", sc, slide->lines);
533
534         } else if(debug > 1) {
535
536             // also print bits and line length
537             fprintf(stderr, "  slide %i:\n", sc);
538             line = slide->line;
539             lc = 0;
540             while(line) {
541                 lc++;
542                 fprintf(stderr, "    line %i: bits = %i, length = %i\n", lc, line->bits, line->length);
543                 line = line->next;
544             }
545         }
546
547         slide = slide->next;
548     }
549 }
550
551 void adjust_line_length(line_t *line) {
552     int l = 0;
553     const static char *special = "\\*_`"; // list of interpreted chars
554     const char *c = &line->text->text[line->offset];
555     cstack_t *stack = cstack_init();
556
557     // for each char in line
558     for(; *c; c++) {
559         // if char is in special char list
560         if(strchr(special, *c)) {
561
562             // closing special char (or second backslash)
563             if((stack->top)(stack, *c)) {
564                 if(*c == '\\') l++;
565                 (stack->pop)(stack);
566
567             // treat special as regular char
568             } else if((stack->top)(stack, '\\')) {
569                 l++;
570                 (stack->pop)(stack);
571
572             // opening special char
573             } else {
574                 (stack->push)(stack, *c);
575             }
576
577         } else {
578             // remove backslash from stack
579             if((stack->top)(stack, '\\'))
580                 (stack->pop)(stack);
581             l++;
582         }
583     }
584
585     if(CHECK_BIT(line->bits, IS_H1_ATX))
586         l -= 2;
587     if(CHECK_BIT(line->bits, IS_H2_ATX))
588         l -= 3;
589
590     line->length = l;
591
592     (stack->delete)(stack);
593 }
594
595 bool is_utf8(char ch) {
596     return (ch & 0x80) != 0x00;
597 }
598
599 int length_utf8(char ch) {
600
601     int i = 0; // increment
602
603     while(is_utf8(ch)) {
604         i++;
605         ch <<= 1;
606     }
607
608     return i;
609 }
610
611 int next_nonblank(cstring_t *text, int i) {
612     while ((i < text->size) && isspace((unsigned char) (text->text)[i]))
613         i++;
614
615     return i;
616 }
617
618 int prev_blank(cstring_t *text, int i) {
619     while ((i > 0) && !isspace((unsigned char) (text->text)[i]))
620         i--;
621
622     return i;
623 }
624
625 int next_blank(cstring_t *text, int i) {
626     while ((i < text->size) && !isspace((unsigned char) (text->text)[i]))
627         i++;
628
629     return i;
630 }
631
632 int next_word(cstring_t *text, int i) {
633     return next_nonblank(text, next_blank(text, i));
634 }