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