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