aboutsummaryrefslogtreecommitdiff
path: root/src/blocks.c
blob: 5b381166a61035cb57e5f4477677945a82d42d82 (plain)
  1. #include <stdlib.h>
  2. #include <assert.h>
  3. #include <stdio.h>
  4. #include <stdbool.h>
  5. #include <ctype.h>
  6. #include "stmd.h"
  7. #include "utf8.h"
  8. #include "scanners.h"
  9. #include "inlines.h"
  10. #include "html/houdini.h"
  11. #define peek_at(i, n) (i)->data[n]
  12. static void incorporate_line(strbuf *ln, int line_number, node_block** curptr);
  13. static void finalize(node_block* b, int line_number);
  14. static node_block* make_block(int tag, int start_line, int start_column)
  15. {
  16. node_block* e;
  17. e = malloc(sizeof(node_block));
  18. memset(e, 0x0, sizeof(*e));
  19. e->tag = tag;
  20. e->open = true;
  21. e->start_line = start_line;
  22. e->start_column = start_column;
  23. e->end_line = start_line;
  24. strbuf_init(&e->string_content, 32);
  25. return e;
  26. }
  27. // Create a root document node_block.
  28. extern node_block* make_document()
  29. {
  30. node_block *e = make_block(BLOCK_DOCUMENT, 1, 1);
  31. e->as.document.refmap = reference_map_new();
  32. e->top = e;
  33. return e;
  34. }
  35. // Returns true if line has only space characters, else false.
  36. bool is_blank(strbuf *s, int offset)
  37. {
  38. while (offset < s->size) {
  39. switch (s->ptr[offset]) {
  40. case '\n':
  41. return true;
  42. case ' ':
  43. offset++;
  44. break;
  45. default:
  46. return false;
  47. }
  48. }
  49. return true;
  50. }
  51. static inline bool can_contain(int parent_type, int child_type)
  52. {
  53. return ( parent_type == BLOCK_DOCUMENT ||
  54. parent_type == BLOCK_BQUOTE ||
  55. parent_type == BLOCK_LIST_ITEM ||
  56. (parent_type == BLOCK_LIST && child_type == BLOCK_LIST_ITEM) );
  57. }
  58. static inline bool accepts_lines(int block_type)
  59. {
  60. return (block_type == BLOCK_PARAGRAPH ||
  61. block_type == BLOCK_ATX_HEADER ||
  62. block_type == BLOCK_INDENTED_CODE ||
  63. block_type == BLOCK_FENCED_CODE);
  64. }
  65. static void add_line(node_block* node_block, chunk *ch, int offset)
  66. {
  67. assert(node_block->open);
  68. strbuf_put(&node_block->string_content, ch->data + offset, ch->len - offset);
  69. }
  70. static void remove_trailing_blank_lines(strbuf *ln)
  71. {
  72. int i;
  73. for (i = ln->size - 1; i >= 0; --i) {
  74. char c = ln->ptr[i];
  75. if (c != ' ' && c != '\t' && c != '\r' && c != '\n')
  76. break;
  77. }
  78. if (i < 0) {
  79. strbuf_clear(ln);
  80. return;
  81. }
  82. i = strbuf_strchr(ln, '\n', i);
  83. if (i >= 0)
  84. strbuf_truncate(ln, i);
  85. }
  86. // Check to see if a node_block ends with a blank line, descending
  87. // if needed into lists and sublists.
  88. static bool ends_with_blank_line(node_block* node_block)
  89. {
  90. if (node_block->last_line_blank) {
  91. return true;
  92. }
  93. if ((node_block->tag == BLOCK_LIST || node_block->tag == BLOCK_LIST_ITEM) && node_block->last_child) {
  94. return ends_with_blank_line(node_block->last_child);
  95. } else {
  96. return false;
  97. }
  98. }
  99. // Break out of all containing lists
  100. static int break_out_of_lists(node_block ** bptr, int line_number)
  101. {
  102. node_block *container = *bptr;
  103. node_block *b = container->top;
  104. // find first containing BLOCK_LIST:
  105. while (b && b->tag != BLOCK_LIST) {
  106. b = b->last_child;
  107. }
  108. if (b) {
  109. while (container && container != b) {
  110. finalize(container, line_number);
  111. container = container->parent;
  112. }
  113. finalize(b, line_number);
  114. *bptr = b->parent;
  115. }
  116. return 0;
  117. }
  118. static void finalize(node_block* b, int line_number)
  119. {
  120. int firstlinelen;
  121. int pos;
  122. node_block* item;
  123. node_block* subitem;
  124. if (!b->open)
  125. return; // don't do anything if the node_block is already closed
  126. b->open = false;
  127. if (line_number > b->start_line) {
  128. b->end_line = line_number - 1;
  129. } else {
  130. b->end_line = line_number;
  131. }
  132. switch (b->tag) {
  133. case BLOCK_PARAGRAPH:
  134. pos = 0;
  135. while (strbuf_at(&b->string_content, 0) == '[' &&
  136. (pos = parse_reference_inline(&b->string_content, b->top->as.document.refmap))) {
  137. strbuf_drop(&b->string_content, pos);
  138. }
  139. if (is_blank(&b->string_content, 0)) {
  140. b->tag = BLOCK_REFERENCE_DEF;
  141. }
  142. break;
  143. case BLOCK_INDENTED_CODE:
  144. remove_trailing_blank_lines(&b->string_content);
  145. strbuf_putc(&b->string_content, '\n');
  146. break;
  147. case BLOCK_FENCED_CODE:
  148. // first line of contents becomes info
  149. firstlinelen = strbuf_strchr(&b->string_content, '\n', 0);
  150. strbuf_init(&b->as.code.info, 0);
  151. houdini_unescape_html_f(
  152. &b->as.code.info,
  153. b->string_content.ptr,
  154. firstlinelen
  155. );
  156. strbuf_drop(&b->string_content, firstlinelen + 1);
  157. strbuf_trim(&b->as.code.info);
  158. strbuf_unescape(&b->as.code.info);
  159. break;
  160. case BLOCK_LIST: // determine tight/loose status
  161. b->as.list.tight = true; // tight by default
  162. item = b->children;
  163. while (item) {
  164. // check for non-final non-empty list item ending with blank line:
  165. if (item->last_line_blank && item->next) {
  166. b->as.list.tight = false;
  167. break;
  168. }
  169. // recurse into children of list item, to see if there are
  170. // spaces between them:
  171. subitem = item->children;
  172. while (subitem) {
  173. if (ends_with_blank_line(subitem) &&
  174. (item->next || subitem->next)) {
  175. b->as.list.tight = false;
  176. break;
  177. }
  178. subitem = subitem->next;
  179. }
  180. if (!(b->as.list.tight)) {
  181. break;
  182. }
  183. item = item->next;
  184. }
  185. break;
  186. default:
  187. break;
  188. }
  189. }
  190. // Add a node_block as child of another. Return pointer to child.
  191. static node_block* add_child(node_block* parent,
  192. int block_type, int start_line, int start_column)
  193. {
  194. assert(parent);
  195. // if 'parent' isn't the kind of node_block that can accept this child,
  196. // then back up til we hit a node_block that can.
  197. while (!can_contain(parent->tag, block_type)) {
  198. finalize(parent, start_line);
  199. parent = parent->parent;
  200. }
  201. node_block* child = make_block(block_type, start_line, start_column);
  202. child->parent = parent;
  203. child->top = parent->top;
  204. if (parent->last_child) {
  205. parent->last_child->next = child;
  206. child->prev = parent->last_child;
  207. } else {
  208. parent->children = child;
  209. child->prev = NULL;
  210. }
  211. parent->last_child = child;
  212. return child;
  213. }
  214. // Free a node_block list and any children.
  215. void stmd_free_nodes(node_block *e)
  216. {
  217. node_block * next;
  218. while (e != NULL) {
  219. next = e->next;
  220. free_inlines(e->inline_content);
  221. strbuf_free(&e->string_content);
  222. if (e->tag == BLOCK_FENCED_CODE) {
  223. strbuf_free(&e->as.code.info);
  224. } else if (e->tag == BLOCK_DOCUMENT) {
  225. reference_map_free(e->as.document.refmap);
  226. }
  227. stmd_free_nodes(e->children);
  228. free(e);
  229. e = next;
  230. }
  231. }
  232. // Walk through node_block and all children, recursively, parsing
  233. // string content into inline content where appropriate.
  234. void process_inlines(node_block* cur, reference_map *refmap)
  235. {
  236. switch (cur->tag) {
  237. case BLOCK_PARAGRAPH:
  238. case BLOCK_ATX_HEADER:
  239. case BLOCK_SETEXT_HEADER:
  240. cur->inline_content = parse_inlines(&cur->string_content, refmap);
  241. break;
  242. default:
  243. break;
  244. }
  245. node_block *child = cur->children;
  246. while (child != NULL) {
  247. process_inlines(child, refmap);
  248. child = child->next;
  249. }
  250. }
  251. // Attempts to parse a list item marker (bullet or enumerated).
  252. // On success, returns length of the marker, and populates
  253. // data with the details. On failure, returns 0.
  254. static int parse_list_marker(chunk *input, int pos, struct ListData ** dataptr)
  255. {
  256. unsigned char c;
  257. int startpos;
  258. struct ListData * data;
  259. startpos = pos;
  260. c = peek_at(input, pos);
  261. if ((c == '*' || c == '-' || c == '+') && !scan_hrule(input, pos)) {
  262. pos++;
  263. if (!isspace(peek_at(input, pos))) {
  264. return 0;
  265. }
  266. data = malloc(sizeof(struct ListData));
  267. data->marker_offset = 0; // will be adjusted later
  268. data->list_type = bullet;
  269. data->bullet_char = c;
  270. data->start = 1;
  271. data->delimiter = period;
  272. data->tight = false;
  273. } else if (isdigit(c)) {
  274. int start = 0;
  275. do {
  276. start = (10 * start) + (peek_at(input, pos) - '0');
  277. pos++;
  278. } while (isdigit(peek_at(input, pos)));
  279. c = peek_at(input, pos);
  280. if (c == '.' || c == ')') {
  281. pos++;
  282. if (!isspace(peek_at(input, pos))) {
  283. return 0;
  284. }
  285. data = malloc(sizeof(struct ListData));
  286. data->marker_offset = 0; // will be adjusted later
  287. data->list_type = ordered;
  288. data->bullet_char = 0;
  289. data->start = start;
  290. data->delimiter = (c == '.' ? period : parens);
  291. data->tight = false;
  292. } else {
  293. return 0;
  294. }
  295. } else {
  296. return 0;
  297. }
  298. *dataptr = data;
  299. return (pos - startpos);
  300. }
  301. // Return 1 if list item belongs in list, else 0.
  302. static int lists_match(struct ListData *list_data, struct ListData *item_data)
  303. {
  304. return (list_data->list_type == item_data->list_type &&
  305. list_data->delimiter == item_data->delimiter &&
  306. // list_data->marker_offset == item_data.marker_offset &&
  307. list_data->bullet_char == item_data->bullet_char);
  308. }
  309. static node_block *finalize_document(node_block *document, int linenum)
  310. {
  311. while (document != document->top) {
  312. finalize(document, linenum);
  313. document = document->parent;
  314. }
  315. finalize(document, linenum);
  316. process_inlines(document, document->as.document.refmap);
  317. return document;
  318. }
  319. extern node_block *stmd_parse_file(FILE *f)
  320. {
  321. strbuf line = GH_BUF_INIT;
  322. unsigned char buffer[4096];
  323. int linenum = 1;
  324. node_block *document = make_document();
  325. while (fgets((char *)buffer, sizeof(buffer), f)) {
  326. utf8proc_detab(&line, buffer, strlen((char *)buffer));
  327. incorporate_line(&line, linenum, &document);
  328. strbuf_clear(&line);
  329. linenum++;
  330. }
  331. strbuf_free(&line);
  332. return finalize_document(document, linenum);
  333. }
  334. extern node_block *stmd_parse_document(const unsigned char *buffer, size_t len)
  335. {
  336. strbuf line = GH_BUF_INIT;
  337. int linenum = 1;
  338. const unsigned char *end = buffer + len;
  339. node_block *document = make_document();
  340. while (buffer < end) {
  341. const unsigned char *eol = memchr(buffer, '\n', end - buffer);
  342. if (!eol) {
  343. utf8proc_detab(&line, buffer, end - buffer);
  344. buffer = end;
  345. } else {
  346. utf8proc_detab(&line, buffer, (eol - buffer) + 1);
  347. buffer += (eol - buffer) + 1;
  348. }
  349. incorporate_line(&line, linenum, &document);
  350. strbuf_clear(&line);
  351. linenum++;
  352. }
  353. strbuf_free(&line);
  354. return finalize_document(document, linenum);
  355. }
  356. static void chop_trailing_hashtags(chunk *ch)
  357. {
  358. int n, orig_n;
  359. chunk_rtrim(ch);
  360. orig_n = n = ch->len - 1;
  361. // if string ends in #s, remove these:
  362. while (n >= 0 && peek_at(ch, n) == '#')
  363. n--;
  364. // the last # was escaped, so we include it.
  365. if (n != orig_n && n >= 0 && peek_at(ch, n) == '\\')
  366. n++;
  367. ch->len = n + 1;
  368. }
  369. // Process one line at a time, modifying a node_block.
  370. static void incorporate_line(strbuf *line, int line_number, node_block** curptr)
  371. {
  372. node_block* last_matched_container;
  373. int offset = 0;
  374. int matched = 0;
  375. int lev = 0;
  376. int i;
  377. struct ListData * data = NULL;
  378. bool all_matched = true;
  379. node_block* container;
  380. node_block* cur = *curptr;
  381. bool blank = false;
  382. int first_nonspace;
  383. int indent;
  384. chunk input;
  385. input.data = line->ptr;
  386. input.len = line->size;
  387. // container starts at the document root.
  388. container = cur->top;
  389. // for each containing node_block, try to parse the associated line start.
  390. // bail out on failure: container will point to the last matching node_block.
  391. while (container->last_child && container->last_child->open) {
  392. container = container->last_child;
  393. first_nonspace = offset;
  394. while (peek_at(&input, first_nonspace) == ' ') {
  395. first_nonspace++;
  396. }
  397. indent = first_nonspace - offset;
  398. blank = peek_at(&input, first_nonspace) == '\n';
  399. if (container->tag == BLOCK_BQUOTE) {
  400. matched = indent <= 3 && peek_at(&input, first_nonspace) == '>';
  401. if (matched) {
  402. offset = first_nonspace + 1;
  403. if (peek_at(&input, offset) == ' ')
  404. offset++;
  405. } else {
  406. all_matched = false;
  407. }
  408. } else if (container->tag == BLOCK_LIST_ITEM) {
  409. if (indent >= container->as.list.marker_offset +
  410. container->as.list.padding) {
  411. offset += container->as.list.marker_offset +
  412. container->as.list.padding;
  413. } else if (blank) {
  414. offset = first_nonspace;
  415. } else {
  416. all_matched = false;
  417. }
  418. } else if (container->tag == BLOCK_INDENTED_CODE) {
  419. if (indent >= CODE_INDENT) {
  420. offset += CODE_INDENT;
  421. } else if (blank) {
  422. offset = first_nonspace;
  423. } else {
  424. all_matched = false;
  425. }
  426. } else if (container->tag == BLOCK_ATX_HEADER ||
  427. container->tag == BLOCK_SETEXT_HEADER) {
  428. // a header can never contain more than one line
  429. all_matched = false;
  430. } else if (container->tag == BLOCK_FENCED_CODE) {
  431. // skip optional spaces of fence offset
  432. i = container->as.code.fence_offset;
  433. while (i > 0 && peek_at(&input, offset) == ' ') {
  434. offset++;
  435. i--;
  436. }
  437. } else if (container->tag == BLOCK_HTML) {
  438. if (blank) {
  439. all_matched = false;
  440. }
  441. } else if (container->tag == BLOCK_PARAGRAPH) {
  442. if (blank) {
  443. container->last_line_blank = true;
  444. all_matched = false;
  445. }
  446. }
  447. if (!all_matched) {
  448. container = container->parent; // back up to last matching node_block
  449. break;
  450. }
  451. }
  452. last_matched_container = container;
  453. // check to see if we've hit 2nd blank line, break out of list:
  454. if (blank && container->last_line_blank) {
  455. break_out_of_lists(&container, line_number);
  456. }
  457. // unless last matched container is code node_block, try new container starts:
  458. while (container->tag != BLOCK_FENCED_CODE && container->tag != BLOCK_INDENTED_CODE &&
  459. container->tag != BLOCK_HTML) {
  460. first_nonspace = offset;
  461. while (peek_at(&input, first_nonspace) == ' ')
  462. first_nonspace++;
  463. indent = first_nonspace - offset;
  464. blank = peek_at(&input, first_nonspace) == '\n';
  465. if (indent >= CODE_INDENT) {
  466. if (cur->tag != BLOCK_PARAGRAPH && !blank) {
  467. offset += CODE_INDENT;
  468. container = add_child(container, BLOCK_INDENTED_CODE, line_number, offset + 1);
  469. } else { // indent > 4 in lazy line
  470. break;
  471. }
  472. } else if (peek_at(&input, first_nonspace) == '>') {
  473. offset = first_nonspace + 1;
  474. // optional following character
  475. if (peek_at(&input, offset) == ' ')
  476. offset++;
  477. container = add_child(container, BLOCK_BQUOTE, line_number, offset + 1);
  478. } else if ((matched = scan_atx_header_start(&input, first_nonspace))) {
  479. offset = first_nonspace + matched;
  480. container = add_child(container, BLOCK_ATX_HEADER, line_number, offset + 1);
  481. int hashpos = chunk_strchr(&input, '#', first_nonspace);
  482. int level = 0;
  483. while (peek_at(&input, hashpos) == '#') {
  484. level++;
  485. hashpos++;
  486. }
  487. container->as.header.level = level;
  488. } else if ((matched = scan_open_code_fence(&input, first_nonspace))) {
  489. container = add_child(container, BLOCK_FENCED_CODE, line_number, first_nonspace + 1);
  490. container->as.code.fence_char = peek_at(&input, first_nonspace);
  491. container->as.code.fence_length = matched;
  492. container->as.code.fence_offset = first_nonspace - offset;
  493. offset = first_nonspace + matched;
  494. } else if ((matched = scan_html_block_tag(&input, first_nonspace))) {
  495. container = add_child(container, BLOCK_HTML, line_number, first_nonspace + 1);
  496. // note, we don't adjust offset because the tag is part of the text
  497. } else if (container->tag == BLOCK_PARAGRAPH &&
  498. (lev = scan_setext_header_line(&input, first_nonspace)) &&
  499. // check that there is only one line in the paragraph:
  500. strbuf_strrchr(&container->string_content, '\n',
  501. strbuf_len(&container->string_content) - 2) < 0) {
  502. container->tag = BLOCK_SETEXT_HEADER;
  503. container->as.header.level = lev;
  504. offset = input.len - 1;
  505. } else if (!(container->tag == BLOCK_PARAGRAPH && !all_matched) &&
  506. (matched = scan_hrule(&input, first_nonspace))) {
  507. // it's only now that we know the line is not part of a setext header:
  508. container = add_child(container, BLOCK_HRULE, line_number, first_nonspace + 1);
  509. finalize(container, line_number);
  510. container = container->parent;
  511. offset = input.len - 1;
  512. } else if ((matched = parse_list_marker(&input, first_nonspace, &data))) {
  513. // compute padding:
  514. offset = first_nonspace + matched;
  515. i = 0;
  516. while (i <= 5 && peek_at(&input, offset + i) == ' ') {
  517. i++;
  518. }
  519. // i = number of spaces after marker, up to 5
  520. if (i >= 5 || i < 1 || peek_at(&input, offset) == '\n') {
  521. data->padding = matched + 1;
  522. if (i > 0) {
  523. offset += 1;
  524. }
  525. } else {
  526. data->padding = matched + i;
  527. offset += i;
  528. }
  529. // check container; if it's a list, see if this list item
  530. // can continue the list; otherwise, create a list container.
  531. data->marker_offset = indent;
  532. if (container->tag != BLOCK_LIST ||
  533. !lists_match(&container->as.list, data)) {
  534. container = add_child(container, BLOCK_LIST, line_number,
  535. first_nonspace + 1);
  536. memcpy(&container->as.list, data, sizeof(*data));
  537. }
  538. // add the list item
  539. container = add_child(container, BLOCK_LIST_ITEM, line_number,
  540. first_nonspace + 1);
  541. /* TODO: static */
  542. memcpy(&container->as.list, data, sizeof(*data));
  543. free(data);
  544. } else {
  545. break;
  546. }
  547. if (accepts_lines(container->tag)) {
  548. // if it's a line container, it can't contain other containers
  549. break;
  550. }
  551. }
  552. // what remains at offset is a text line. add the text to the
  553. // appropriate container.
  554. first_nonspace = offset;
  555. while (peek_at(&input, first_nonspace) == ' ')
  556. first_nonspace++;
  557. indent = first_nonspace - offset;
  558. blank = peek_at(&input, first_nonspace) == '\n';
  559. // node_block quote lines are never blank as they start with >
  560. // and we don't count blanks in fenced code for purposes of tight/loose
  561. // lists or breaking out of lists. we also don't set last_line_blank
  562. // on an empty list item.
  563. container->last_line_blank = (blank &&
  564. container->tag != BLOCK_BQUOTE &&
  565. container->tag != BLOCK_FENCED_CODE &&
  566. !(container->tag == BLOCK_LIST_ITEM &&
  567. container->children == NULL &&
  568. container->start_line == line_number));
  569. node_block *cont = container;
  570. while (cont->parent) {
  571. cont->parent->last_line_blank = false;
  572. cont = cont->parent;
  573. }
  574. if (cur != last_matched_container &&
  575. container == last_matched_container &&
  576. !blank &&
  577. cur->tag == BLOCK_PARAGRAPH &&
  578. strbuf_len(&cur->string_content) > 0) {
  579. add_line(cur, &input, offset);
  580. } else { // not a lazy continuation
  581. // finalize any blocks that were not matched and set cur to container:
  582. while (cur != last_matched_container) {
  583. finalize(cur, line_number);
  584. cur = cur->parent;
  585. assert(cur != NULL);
  586. }
  587. if (container->tag == BLOCK_INDENTED_CODE) {
  588. add_line(container, &input, offset);
  589. } else if (container->tag == BLOCK_FENCED_CODE) {
  590. matched = 0;
  591. if (indent <= 3 &&
  592. peek_at(&input, first_nonspace) == container->as.code.fence_char) {
  593. int fence_len = scan_close_code_fence(&input, first_nonspace);
  594. if (fence_len > container->as.code.fence_length)
  595. matched = 1;
  596. }
  597. if (matched) {
  598. // if closing fence, don't add line to container; instead, close it:
  599. finalize(container, line_number);
  600. container = container->parent; // back up to parent
  601. } else {
  602. add_line(container, &input, offset);
  603. }
  604. } else if (container->tag == BLOCK_HTML) {
  605. add_line(container, &input, offset);
  606. } else if (blank) {
  607. // ??? do nothing
  608. } else if (container->tag == BLOCK_ATX_HEADER) {
  609. chop_trailing_hashtags(&input);
  610. add_line(container, &input, first_nonspace);
  611. finalize(container, line_number);
  612. container = container->parent;
  613. } else if (accepts_lines(container->tag)) {
  614. add_line(container, &input, first_nonspace);
  615. } else if (container->tag != BLOCK_HRULE && container->tag != BLOCK_SETEXT_HEADER) {
  616. // create paragraph container for line
  617. container = add_child(container, BLOCK_PARAGRAPH, line_number, first_nonspace + 1);
  618. add_line(container, &input, first_nonspace);
  619. } else {
  620. assert(false);
  621. }
  622. *curptr = container;
  623. }
  624. }