615cc6e26971c5191123282cb16864f45cf556a6
[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) 2016 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 <wchar.h>
29 #include <wctype.h>
30 #include <string.h>
31
32 #include "parser.h"
33
34 // char entry translation table
35 static struct named_character_entity {
36     wchar_t        ucs;
37     const wchar_t *name;
38 } named_character_entities[] = {
39    { L'\x0022', L"quot" },
40    { L'\x0026', L"amp" },
41    { L'\x0027', L"apos" },
42    { L'\x003C', L"lt" },
43    { L'\x003E', L"gt" },
44    { L'\x00A2', L"cent" },
45    { L'\x00A3', L"pound" },
46    { L'\x00A5', L"yen" },
47    { L'\x00A7', L"sect" },
48    { L'\x00A9', L"copy" },
49    { L'\x00AA', L"laquo" },
50    { L'\x00AE', L"reg" },
51    { L'\x00B0', L"deg" },
52    { L'\x00B1', L"plusmn" },
53    { L'\x00B2', L"sup2" },
54    { L'\x00B3', L"sup3" },
55    { L'\x00B6', L"para" },
56    { L'\x00B9', L"sup1" },
57    { L'\x00BB', L"raquo" },
58    { L'\x00BC', L"frac14" },
59    { L'\x00BD', L"frac12" },
60    { L'\x00BE', L"frac34" },
61    { L'\x00D7', L"times" },
62    { L'\x00F7', L"divide" },
63    { L'\x2018', L"lsquo" },
64    { L'\x2019', L"rsquo" },
65    { L'\x201C', L"ldquo" },
66    { L'\x201D', L"rdquo" },
67    { L'\x2020', L"dagger" },
68    { L'\x2021', L"Dagger" },
69    { L'\x2022', L"bull" },
70    { L'\x2026', L"hellip" },
71    { L'\x2030', L"permil" },
72    { L'\x2032', L"prime" },
73    { L'\x2033', L"Prime" },
74    { L'\x2039', L"lsaquo" },
75    { L'\x203A', L"rsaquo" },
76    { L'\x20AC', L"euro" },
77    { L'\x2122', L"trade" },
78    { L'\x2190', L"larr" },
79    { L'\x2191', L"uarr" },
80    { L'\x2192', L"rarr" },
81    { L'\x2193', L"darr" },
82    { L'\x2194', L"harr" },
83    { L'\x21B5', L"crarr" },
84    { L'\x21D0', L"lArr" },
85    { L'\x21D1', L"uArr" },
86    { L'\x21D2', L"rArr" },
87    { L'\x21D3', L"dArr" },
88    { L'\x21D4', L"hArr" },
89    { L'\x221E', L"infin" },
90    { L'\x2261', L"equiv" },
91    { L'\x2308', L"lceil" },
92    { L'\x2309', L"rceil" },
93    { L'\x230A', L"lfloor" },
94    { L'\x230B', L"rfloor" },
95    { L'\x25CA', L"loz" },
96    { L'\x2660', L"spades" },
97    { L'\x2663', L"clubs" },
98    { L'\x2665', L"hearts" },
99    { L'\x2666', L"diams" },
100    { L'\0', NULL },
101 };
102
103 deck_t *markdown_load(FILE *input, int noexpand) {
104
105     wchar_t c = L'\0';    // char
106     int i = 0;    // increment
107     int hc = 0;   // header count
108     int lc = 0;   // line count
109     int sc = 1;   // slide count
110     int bits = 0; // markdown bits
111     int prev = 0; // markdown bits of previous line
112
113     deck_t *deck = new_deck();
114     slide_t *slide = deck->slide;
115     line_t *line = NULL;
116     line_t *tmp = NULL;
117     cstring_t *text = cstring_init();
118
119     // initialize bits as empty line
120     SET_BIT(bits, IS_EMPTY);
121
122     while ((c = fgetwc(input)) != WEOF) {
123         if (ferror(input)) {
124             fprintf(stderr, "markdown_load() failed to read input: %s\n", strerror(errno));
125             exit(EXIT_FAILURE);
126         }
127
128         if(c == L'\n') {
129
130             // markdown analyse
131             prev = bits;
132             bits = markdown_analyse(text, prev);
133
134             // if first line in file is markdown hr
135             if(!line && CHECK_BIT(bits, IS_HR)) {
136
137                 // clear text
138                 (text->reset)(text);
139
140             } else if(line && CHECK_BIT(bits, IS_STOP)) {
141
142                 // set stop bit on last line
143                 SET_BIT(line->bits, IS_STOP);
144
145                 // clear text
146                 (text->reset)(text);
147
148             // if text is markdown hr
149             } else if(CHECK_BIT(bits, IS_HR) &&
150                       CHECK_BIT(line->bits, IS_EMPTY)) {
151
152                 slide->lines = lc;
153
154                 // clear text
155                 (text->reset)(text);
156
157                 // create next slide
158                 slide = next_slide(slide);
159                 sc++;
160
161             } else if((CHECK_BIT(bits, IS_TILDE_CODE) ||
162                        CHECK_BIT(bits, IS_GFM_CODE)) &&
163                       CHECK_BIT(bits, IS_EMPTY)) {
164                 // remove tilde code markers
165                 (text->reset)(text);
166
167             } else {
168
169                 // if slide ! has line
170                 if(!slide->line || !line) {
171
172                     // create new line
173                     line = new_line();
174                     slide->line = line;
175                     lc = 1;
176
177                 } else {
178
179                     // create next line
180                     line = next_line(line);
181                     lc++;
182
183                 }
184
185                 // add text to line
186                 line->text = text;
187
188                 // add bits to line
189                 line->bits = bits;
190
191                 // calc offset
192                 line->offset = next_nonblank(text, 0);
193
194                 // expand character entities if enabled
195                 if(line->text->value &&
196                    !noexpand &&
197                    !CHECK_BIT(line->bits, IS_CODE))
198                     expand_character_entities(line);
199
200                 // adjust line length dynamicaly - excluding markup
201                 if(line->text->value)
202                     adjust_line_length(line);
203
204                 // new text
205                 text = cstring_init();
206             }
207
208         } else if(c == L'\t') {
209
210             // expand tab to spaces
211             for (i = 0;  i < EXPAND_TABS;  i++) {
212                 (text->expand)(text, L' ');
213             }
214
215         } else if(c == L'\\') {
216
217             // add char to line
218             (text->expand)(text, c);
219
220             // if !IS_CODE add next char to line
221             // and do not increase line count
222             if(next_nonblank(text, 0) < CODE_INDENT) {
223
224                 c = fgetwc(input);
225                 (text->expand)(text, c);
226             }
227
228         } else if(iswprint(c) || iswspace(c)) {
229
230             // add char to line
231             (text->expand)(text, c);
232         }
233     }
234     (text->delete)(text);
235
236     slide->lines = lc;
237     deck->slides = sc;
238
239     // detect header
240     line = deck->slide->line;
241     if(line && line->text->size > 0 && line->text->value[0] == L'%') {
242
243         // assign header to deck
244         deck->header = line;
245
246         // find first non-header line
247         while(line && line->text->size > 0 && line->text->value[0] == L'%') {
248             hc++;
249             line = line->next;
250         }
251
252         // only split header if any non-header line is found
253         if(line) {
254
255             // split linked list
256             line->prev->next = NULL;
257             line->prev = NULL;
258
259             // remove header lines from slide
260             deck->slide->line = line;
261
262             // adjust counts
263             deck->headers += hc;
264             deck->slide->lines -= hc;
265         } else {
266
267             // remove header from deck
268             deck->header = NULL;
269         }
270     }
271
272     slide = deck->slide;
273     while(slide) {
274         line = slide->line;
275
276         // ignore mdpress format attributes
277         if(line &&
278            slide->lines > 1 &&
279            !CHECK_BIT(line->bits, IS_EMPTY) &&
280            line->text->value[line->offset] == L'=' &&
281            line->text->value[line->offset + 1] == L' ') {
282
283             // remove line from linked list
284             slide->line = line->next;
285             line->next->prev = NULL;
286
287             // maintain loop condition
288             tmp = line;
289             line = line->next;
290
291             // adjust line count
292             slide->lines -= 1;
293
294             // delete line
295             (tmp->text->delete)(tmp->text);
296             free(tmp);
297         }
298
299         while(line) {
300             // combine underlined H1/H2 in single line
301             if((CHECK_BIT(line->bits, IS_H1) ||
302                 CHECK_BIT(line->bits, IS_H2)) &&
303                CHECK_BIT(line->bits, IS_EMPTY) &&
304                line->prev &&
305                !CHECK_BIT(line->prev->bits, IS_EMPTY)) {
306
307
308                 // remove line from linked list
309                 line->prev->next = line->next;
310                 if(line->next)
311                     line->next->prev = line->prev;
312
313                 // set bits on previous line
314                 if(CHECK_BIT(line->bits, IS_H1)) {
315                     SET_BIT(line->prev->bits, IS_H1);
316                 } else {
317                     SET_BIT(line->prev->bits, IS_H2);
318                 }
319
320                 // adjust line count
321                 slide->lines -= 1;
322
323                 // maintain loop condition
324                 tmp = line;
325                 line = line->prev;
326
327                 // delete line
328                 (tmp->text->delete)(tmp->text);
329                 free(tmp);
330
331             // pass enclosing flag IS_UNORDERED_LIST_3
332             // to nested levels for unordered lists
333             } else if(CHECK_BIT(line->bits, IS_UNORDERED_LIST_3)) {
334                 tmp = line->next;
335                 line_t *list_last_level_3 = line;
336
337                 while(tmp &&
338                       CHECK_BIT(tmp->bits, IS_UNORDERED_LIST_3)) {
339                     if(CHECK_BIT(tmp->bits, IS_UNORDERED_LIST_3)) {
340                         list_last_level_3 = tmp;
341                     }
342                     tmp = tmp->next;
343                 }
344
345                 for(tmp = line; tmp != list_last_level_3; tmp = tmp->next) {
346                     SET_BIT(tmp->bits, IS_UNORDERED_LIST_3);
347                 }
348
349             // pass enclosing flag IS_UNORDERED_LIST_2
350             // to nested levels for unordered lists
351             } else if(CHECK_BIT(line->bits, IS_UNORDERED_LIST_2)) {
352                 tmp = line->next;
353                 line_t *list_last_level_2 = line;
354
355                 while(tmp &&
356                       (CHECK_BIT(tmp->bits, IS_UNORDERED_LIST_2) ||
357                        CHECK_BIT(tmp->bits, IS_UNORDERED_LIST_3))) {
358                     if(CHECK_BIT(tmp->bits, IS_UNORDERED_LIST_2)) {
359                         list_last_level_2 = tmp;
360                     }
361                     tmp = tmp->next;
362                 }
363
364                 for(tmp = line; tmp != list_last_level_2; tmp = tmp->next) {
365                     SET_BIT(tmp->bits, IS_UNORDERED_LIST_2);
366                 }
367
368             // pass enclosing flag IS_UNORDERED_LIST_1
369             // to nested levels for unordered lists
370             } else if(CHECK_BIT(line->bits, IS_UNORDERED_LIST_1)) {
371                 tmp = line->next;
372                 line_t *list_last_level_1 = line;
373
374                 while(tmp &&
375                       (CHECK_BIT(tmp->bits, IS_UNORDERED_LIST_1) ||
376                        CHECK_BIT(tmp->bits, IS_UNORDERED_LIST_2) ||
377                        CHECK_BIT(tmp->bits, IS_UNORDERED_LIST_3))) {
378                     if(CHECK_BIT(tmp->bits, IS_UNORDERED_LIST_1)) {
379                         list_last_level_1 = tmp;
380                     }
381                     tmp = tmp->next;
382                 }
383
384                 for(tmp = line; tmp != list_last_level_1; tmp = tmp->next) {
385                     SET_BIT(tmp->bits, IS_UNORDERED_LIST_1);
386                 }
387             }
388
389             line = line->next;
390         }
391         slide = slide->next;
392     }
393
394     return deck;
395 }
396
397 int markdown_analyse(cstring_t *text, int prev) {
398
399     // static variables can not be redeclaired, but changed outside of a declaration
400     // the program remembers their value on every function calls
401     static int unordered_list_level = 0;
402     static int unordered_list_level_offset[] = {-1, -1, -1, -1};
403     static int num_tilde_characters = 0;
404     static int num_backticks = 0;
405
406     int i = 0;      // increment
407     int bits = 0;   // markdown bits
408     int offset = 0; // text offset
409     int eol    = 0; // end of line
410
411     int equals = 0, hashes = 0,
412         stars  = 0, minus  = 0,
413         spaces = 0, other  = 0; // special character counts
414
415     const int unordered_list_offset = unordered_list_level_offset[unordered_list_level];
416
417     // return IS_EMPTY on null pointers
418     if(!text || !text->value) {
419         SET_BIT(bits, IS_EMPTY);
420
421         // continue fenced code blocks across empty lines
422         if(num_tilde_characters > 0)
423             SET_BIT(bits, IS_CODE);
424
425         return bits;
426     }
427
428     // count leading spaces
429     offset = next_nonblank(text, 0);
430
431     // IS_TILDE_CODE
432     if (wcsncmp(text->value, L"~~~", 3) == 0) {
433         int tildes_in_line = next_nontilde(text, 0);
434         if (tildes_in_line >= num_tilde_characters) {
435             if (num_tilde_characters > 0) {
436                 num_tilde_characters = 0;
437             } else {
438                 num_tilde_characters = tildes_in_line;
439             }
440             SET_BIT(bits, IS_EMPTY);
441             SET_BIT(bits, IS_TILDE_CODE);
442             return bits;
443         }
444     }
445
446     if (num_tilde_characters > 0) {
447         SET_BIT(bits, IS_CODE);
448         SET_BIT(bits, IS_TILDE_CODE);
449         return bits;
450     }
451
452     // IS_GFM_CODE
453     if (wcsncmp(text->value, L"```", 3) == 0) {
454         int backticks_in_line = next_nonbacktick(text, 0);
455         if (backticks_in_line >= num_backticks) {
456             if (num_backticks > 0) {
457                 num_backticks = 0;
458             } else {
459                 num_backticks = backticks_in_line;
460             }
461             SET_BIT(bits, IS_EMPTY);
462             SET_BIT(bits, IS_GFM_CODE);
463             return bits;
464         }
465     }
466
467     if (num_backticks > 0) {
468         SET_BIT(bits, IS_CODE);
469         SET_BIT(bits, IS_GFM_CODE);
470         return bits;
471     }
472
473     // IS_STOP
474     if((offset < CODE_INDENT || !CHECK_BIT(prev, IS_CODE)) &&
475        (!wcsncmp(&text->value[offset], L"<br>", 4) ||
476         !wcsncmp(&text->value[offset], L"<BR>", 4) ||
477         !wcsncmp(&text->value[offset], L"^", 1))) {
478         SET_BIT(bits, IS_STOP);
479         return bits;
480     }
481
482     // strip trailing spaces
483     for(eol = text->size; eol > offset && iswspace(text->value[eol - 1]); eol--);
484
485     // IS_UNORDERED_LIST_#
486     if(text->size >= offset + 2 &&
487        (text->value[offset] == L'*' || text->value[offset] == L'-') &&
488        iswspace(text->value[offset + 1])) {
489
490         // if different from last lines offset
491         if(offset != unordered_list_offset) {
492
493             // test if offset matches a lower indent level
494             for(i = unordered_list_level; i >= 0; i--) {
495                 if(unordered_list_level_offset[i] == offset) {
496                     unordered_list_level = i;
497                     break;
498                 }
499             }
500             // if offset doesn't match any previously stored indent level
501             if(i != unordered_list_level) {
502                 unordered_list_level = MIN(unordered_list_level + 1, UNORDERED_LIST_MAX_LEVEL);
503                 // memorize the offset as next bigger indent level
504                 unordered_list_level_offset[unordered_list_level] = offset;
505             }
506         }
507
508         // if no previous indent level matches, this must be the first line of the list
509         if(unordered_list_level == 0) {
510             unordered_list_level = 1;
511             unordered_list_level_offset[1] = offset;
512         }
513
514         switch(unordered_list_level) {
515             case 1: SET_BIT(bits, IS_UNORDERED_LIST_1); break;
516             case 2: SET_BIT(bits, IS_UNORDERED_LIST_2); break;
517             case 3: SET_BIT(bits, IS_UNORDERED_LIST_3); break;
518             default: break;
519         }
520     }
521
522     if(!CHECK_BIT(bits, IS_UNORDERED_LIST_1) &&
523        !CHECK_BIT(bits, IS_UNORDERED_LIST_2) &&
524        !CHECK_BIT(bits, IS_UNORDERED_LIST_3)) {
525
526         // continue list if indent level is still the same as in previous line
527         if ((CHECK_BIT(prev, IS_UNORDERED_LIST_1) ||
528              CHECK_BIT(prev, IS_UNORDERED_LIST_2) ||
529              CHECK_BIT(prev, IS_UNORDERED_LIST_3)) &&
530             offset >= unordered_list_offset) {
531
532             switch(unordered_list_level) {
533                 case 1: SET_BIT(bits, IS_UNORDERED_LIST_1); break;
534                 case 2: SET_BIT(bits, IS_UNORDERED_LIST_2); break;
535                 case 3: SET_BIT(bits, IS_UNORDERED_LIST_3); break;
536                 default: break;
537             }
538
539             // this line extends the previous list item
540             SET_BIT(bits, IS_UNORDERED_LIST_EXT);
541
542         // or reset indent level
543         } else {
544             unordered_list_level = 0;
545         }
546     }
547
548     if(!CHECK_BIT(bits, IS_UNORDERED_LIST_1) &&
549        !CHECK_BIT(bits, IS_UNORDERED_LIST_2) &&
550        !CHECK_BIT(bits, IS_UNORDERED_LIST_3)) {
551
552         // IS_CODE
553         if(offset >= CODE_INDENT &&
554            (CHECK_BIT(prev, IS_EMPTY) ||
555             CHECK_BIT(prev, IS_CODE)  ||
556             CHECK_BIT(prev, IS_STOP))) {
557             SET_BIT(bits, IS_CODE);
558
559         } else {
560
561             // IS_QUOTE
562             if(text->value[offset] == L'>') {
563                 SET_BIT(bits, IS_QUOTE);
564             }
565
566             // IS_CENTER
567             if(text->size >= offset + 3 &&
568                text->value[offset] == L'-' &&
569                text->value[offset + 1] == L'>' &&
570                iswspace(text->value[offset + 2])) {
571                 SET_BIT(bits, IS_CENTER);
572
573                 // remove start tag
574                 (text->strip)(text, offset, 3);
575                 eol -= 3;
576
577                 if(text->size >= offset + 3 &&
578                    text->value[eol - 1] == L'-' &&
579                    text->value[eol - 2] == L'<' &&
580                    iswspace(text->value[eol - 3])) {
581
582                     // remove end tags
583                     (text->strip)(text, eol - 3, 3);
584
585                     // adjust end of line
586                     for(eol = text->size; eol > offset && iswspace(text->value[eol - 1]); eol--);
587
588                 }
589             }
590
591             for(i = offset; i < eol; i++) {
592
593                 if(iswspace(text->value[i])) {
594                     spaces++;
595
596                 } else {
597                     switch(text->value[i]) {
598                         case L'=': equals++;  break;
599                         case L'#': hashes++;  break;
600                         case L'*': stars++;   break;
601                         case L'-': minus++;   break;
602                         case L'\\': other++; i++; break;
603                         default:  other++;   break;
604                     }
605                 }
606             }
607
608             // IS_H1
609             if(equals > 0 &&
610                hashes + stars + minus + spaces + other == 0) {
611                 SET_BIT(bits, IS_H1);
612             }
613             if(text->value[offset] == L'#' &&
614                iswspace(text->value[offset+1])) {
615                 SET_BIT(bits, IS_H1);
616                 SET_BIT(bits, IS_H1_ATX);
617             }
618
619             // IS_H2
620             if(minus > 0 &&
621                equals + hashes + stars + spaces + other == 0) {
622                 SET_BIT(bits, IS_H2);
623             }
624             if(text->value[offset] == L'#' &&
625                text->value[offset+1] == L'#' &&
626                iswspace(text->value[offset+2])) {
627                 SET_BIT(bits, IS_H2);
628                 SET_BIT(bits, IS_H2_ATX);
629             }
630
631             // IS_HR
632             if((minus >= 3 && equals + hashes + stars + other == 0) ||
633                (stars >= 3 && equals + hashes + minus + other == 0)) {
634
635                 SET_BIT(bits, IS_HR);
636             }
637
638             // IS_EMPTY
639             if(other == 0) {
640                 SET_BIT(bits, IS_EMPTY);
641             }
642         }
643     }
644
645     return bits;
646 }
647
648 void markdown_debug(deck_t *deck, int debug) {
649
650     int sc = 0; // slide count
651     int lc = 0; // line count
652
653     int offset;
654     line_t *header;
655
656     if(debug == 1) {
657         fwprintf(stderr, L"headers: %i\nslides: %i\n", deck->headers, deck->slides);
658
659     } else if(debug > 1) {
660
661         // print header to STDERR
662         if(deck->header) {
663             header = deck->header;
664             while(header &&
665                 header->length > 0 &&
666                 header->text->value[0] == L'%') {
667
668                 // skip descriptor word (e.g. %title:)
669                 offset = next_blank(header->text, 0) + 1;
670
671                 fwprintf(stderr, L"header: %S\n", &header->text->value[offset]);
672                 header = header->next;
673             }
674         }
675     }
676
677     slide_t *slide = deck->slide;
678     line_t *line;
679
680     // print slide/line count to STDERR
681     while(slide) {
682         sc++;
683
684         if(debug == 1) {
685             fwprintf(stderr, L"  slide %i: %i lines\n", sc, slide->lines);
686
687         } else if(debug > 1) {
688
689             // also print bits and line length
690             fwprintf(stderr, L"  slide %i:\n", sc);
691             line = slide->line;
692             lc = 0;
693             while(line) {
694                 lc++;
695                 fwprintf(stderr, L"    line %i: bits = %i, length = %i\n", lc, line->bits, line->length);
696                 line = line->next;
697             }
698         }
699
700         slide = slide->next;
701     }
702 }
703
704 void expand_character_entities(line_t *line)
705 {
706     wchar_t *ampersand;
707     wchar_t *prev, *curr;
708
709     ampersand = NULL;
710     curr = &line->text->value[0];
711
712     // for each char in line
713     for(prev = NULL; *curr; prev = curr++) {
714         if (*curr == L'&' && (prev == NULL || *prev != L'\\')) {
715             ampersand = curr;
716             continue;
717         }
718         if (ampersand == NULL) {
719             continue;
720         }
721         if (*curr == L'#') {
722             if (prev == ampersand)
723                 continue;
724             ampersand = NULL;
725             continue;
726         }
727         if (iswalpha(*curr) || iswxdigit(*curr)) {
728             continue;
729         }
730         if (*curr == L';') {
731             int cnt;
732             wchar_t ucs = L'\0';
733             if (ampersand + 1 >= curr || ampersand + 16 < curr) { // what is a good limit?
734                 ampersand = NULL;
735                 continue;
736             }
737             if (ampersand[1] == L'#') { // &#nnnn; or &#xhhhh;
738                 if (ampersand + 2 >= curr) {
739                     ampersand = NULL;
740                     continue;
741                 }
742                 if (ampersand[2] != L'x') { // &#nnnn;
743                     cnt = wcsspn(&ampersand[2], L"0123456789");
744                     if (ampersand + 2 + cnt != curr) {
745                         ampersand = NULL;
746                         continue;
747                     }
748                     ucs = wcstoul(&ampersand[2], NULL, 10);
749                 } else { // &#xhhhh;
750                     if (ampersand + 3 >= curr) {
751                         ampersand = NULL;
752                         continue;
753                     }
754                     cnt = wcsspn(&ampersand[3], L"0123456789abcdefABCDEF");
755                     if (ampersand + 3 + cnt != curr) {
756                         ampersand = NULL;
757                         continue;
758                     }
759                     ucs = wcstoul(&ampersand[3], NULL, 16);
760                 }
761             } else { // &name;
762                 for (cnt = 0; cnt < sizeof(named_character_entities)/sizeof(named_character_entities[0]); ++cnt) {
763                     if (wcsncmp(named_character_entities[cnt].name, &ampersand[1], curr - ampersand - 1))
764                         continue;
765                     ucs = named_character_entities[cnt].ucs;
766                     break;
767                 }
768                 if (ucs == L'\0') {
769                     ampersand = NULL;
770                     continue;
771                 }
772             }
773             *ampersand = ucs;
774             cstring_strip(line->text, ampersand + 1 - &line->text->value[0], curr - ampersand);
775             curr = ampersand;
776             ampersand = NULL;
777         }
778     }
779 }
780
781 void adjust_line_length(line_t *line) {
782     int l = 0;
783     const static wchar_t *special = L"\\*_`"; // list of interpreted chars
784     const wchar_t *c = &line->text->value[0];
785     cstack_t *stack = cstack_init();
786
787     // for each char in line
788     for(; *c; c++) {
789         // if char is in special char list
790         if(wcschr(special, *c)) {
791
792             // closing special char (or second backslash)
793             if((stack->top)(stack, *c)) {
794                 if(*c == L'\\') l++;
795                 (stack->pop)(stack);
796
797             // treat special as regular char
798             } else if((stack->top)(stack, L'\\')) {
799                 l++;
800                 (stack->pop)(stack);
801
802             // opening special char
803             } else {
804                 (stack->push)(stack, *c);
805             }
806
807         } else {
808             // remove backslash from stack
809             if((stack->top)(stack, L'\\'))
810                 (stack->pop)(stack);
811             l++;
812         }
813     }
814
815     if(CHECK_BIT(line->bits, IS_H1_ATX))
816         l -= 2;
817     if(CHECK_BIT(line->bits, IS_H2_ATX))
818         l -= 3;
819
820     line->length = l;
821
822     (stack->delete)(stack);
823 }
824
825 int next_nonblank(cstring_t *text, int i) {
826     while ((i < text->size) && iswspace((text->value)[i]))
827         i++;
828
829     return i;
830 }
831
832 int prev_blank(cstring_t *text, int i) {
833     while ((i > 0) && !iswspace((text->value)[i]))
834         i--;
835
836     return i;
837 }
838
839 int next_blank(cstring_t *text, int i) {
840     while ((i < text->size) && !iswspace((text->value)[i]))
841         i++;
842
843     return i;
844 }
845
846 int next_word(cstring_t *text, int i) {
847     return next_nonblank(text, next_blank(text, i));
848 }
849
850 int next_nontilde(cstring_t *text, int i) {
851     while ((i < text->size) && text->value[i] == L'~')
852         i++;
853
854     return i;
855 }
856
857 int next_nonbacktick(cstring_t *text, int i) {
858     while ((i < text->size) && text->value[i] == L'`')
859         i++;
860
861     return i;
862 }
863