aboutsummaryrefslogtreecommitdiff
path: root/src/blocks.c
blob: e8c9e94af1f4fa219f5da57eb5cc1cb281ff7ff6 (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. extern 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. 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. // Free a node_block list and any children.
  216. void cmark_free_nodes(node_block *e)
  217. {
  218. node_block * next;
  219. node_block * tmp;
  220. while (e != NULL) {
  221. free_inlines(e->inline_content);
  222. strbuf_free(&e->string_content);
  223. if (e->tag == BLOCK_FENCED_CODE) {
  224. strbuf_free(&e->as.code.info);
  225. } else if (e->tag == BLOCK_DOCUMENT) {
  226. reference_map_free(e->as.document.refmap);
  227. }
  228. tmp = e->children;
  229. if (tmp) {
  230. // Find last child
  231. while (tmp->next) {
  232. tmp = tmp->next;
  233. }
  234. // Splice children into list
  235. tmp->next = e->next;
  236. e->next = e->children;
  237. }
  238. next = e->next;
  239. free(e);
  240. e = next;
  241. }
  242. }
  243. // Walk through node_block and all children, recursively, parsing
  244. // string content into inline content where appropriate.
  245. void process_inlines(node_block* cur, reference_map *refmap)
  246. {
  247. switch (cur->tag) {
  248. case BLOCK_PARAGRAPH:
  249. case BLOCK_ATX_HEADER:
  250. case BLOCK_SETEXT_HEADER:
  251. cur->inline_content = parse_inlines(&cur->string_content, refmap);
  252. break;
  253. default:
  254. break;
  255. }
  256. node_block *child = cur->children;
  257. while (child != NULL) {
  258. process_inlines(child, refmap);
  259. child = child->next;
  260. }
  261. }
  262. // Attempts to parse a list item marker (bullet or enumerated).
  263. // On success, returns length of the marker, and populates
  264. // data with the details. On failure, returns 0.
  265. static int parse_list_marker(chunk *input, int pos, struct ListData ** dataptr)
  266. {
  267. unsigned char c;
  268. int startpos;
  269. struct ListData * data;
  270. startpos = pos;
  271. c = peek_at(input, pos);
  272. if ((c == '*' || c == '-' || c == '+') && !scan_hrule(input, pos)) {
  273. pos++;
  274. if (!isspace(peek_at(input, pos))) {
  275. return 0;
  276. }
  277. data = calloc(1, sizeof(*data));
  278. if(data == NULL) {
  279. return 0;
  280. } else {
  281. data->marker_offset = 0; // will be adjusted later
  282. data->list_type = bullet;
  283. data->bullet_char = c;
  284. data->start = 1;
  285. data->delimiter = period;
  286. data->tight = false;
  287. }
  288. } else if (isdigit(c)) {
  289. int start = 0;
  290. do {
  291. start = (10 * start) + (peek_at(input, pos) - '0');
  292. pos++;
  293. } while (isdigit(peek_at(input, pos)));
  294. c = peek_at(input, pos);
  295. if (c == '.' || c == ')') {
  296. pos++;
  297. if (!isspace(peek_at(input, pos))) {
  298. return 0;
  299. }
  300. data = calloc(1, sizeof(*data));
  301. if(data == NULL) {
  302. return 0;
  303. } else {
  304. data->marker_offset = 0; // will be adjusted later
  305. data->list_type = ordered;
  306. data->bullet_char = 0;
  307. data->start = start;
  308. data->delimiter = (c == '.' ? period : parens);
  309. data->tight = false;
  310. }
  311. } else {
  312. return 0;
  313. }
  314. } else {
  315. return 0;
  316. }
  317. *dataptr = data;
  318. return (pos - startpos);
  319. }
  320. // Return 1 if list item belongs in list, else 0.
  321. static int lists_match(struct ListData *list_data, struct ListData *item_data)
  322. {
  323. return (list_data->list_type == item_data->list_type &&
  324. list_data->delimiter == item_data->delimiter &&
  325. // list_data->marker_offset == item_data.marker_offset &&
  326. list_data->bullet_char == item_data->bullet_char);
  327. }
  328. static node_block *finalize_document(node_block *document, int linenum)
  329. {
  330. while (document != document->top) {
  331. finalize(document, linenum);
  332. document = document->parent;
  333. }
  334. finalize(document, linenum);
  335. process_inlines(document, document->as.document.refmap);
  336. return document;
  337. }
  338. extern node_block *cmark_parse_file(FILE *f)
  339. {
  340. strbuf line = GH_BUF_INIT;
  341. unsigned char buffer[4096];
  342. int linenum = 1;
  343. node_block *document = make_document();
  344. while (fgets((char *)buffer, sizeof(buffer), f)) {
  345. utf8proc_detab(&line, buffer, strlen((char *)buffer));
  346. incorporate_line(&line, linenum, &document);
  347. strbuf_clear(&line);
  348. linenum++;
  349. }
  350. strbuf_free(&line);
  351. return finalize_document(document, linenum);
  352. }
  353. extern node_block *cmark_parse_document(const unsigned char *buffer, size_t len)
  354. {
  355. strbuf line = GH_BUF_INIT;
  356. int linenum = 1;
  357. const unsigned char *end = buffer + len;
  358. node_block *document = make_document();
  359. while (buffer < end) {
  360. const unsigned char *eol = memchr(buffer, '\n', end - buffer);
  361. if (!eol) {
  362. utf8proc_detab(&line, buffer, end - buffer);
  363. buffer = end;
  364. } else {
  365. utf8proc_detab(&line, buffer, (eol - buffer) + 1);
  366. buffer += (eol - buffer) + 1;
  367. }
  368. incorporate_line(&line, linenum, &document);
  369. strbuf_clear(&line);
  370. linenum++;
  371. }
  372. strbuf_free(&line);
  373. return finalize_document(document, linenum);
  374. }
  375. static void chop_trailing_hashtags(chunk *ch)
  376. {
  377. int n, orig_n;
  378. chunk_rtrim(ch);
  379. orig_n = n = ch->len - 1;
  380. // if string ends in space followed by #s, remove these:
  381. while (n >= 0 && peek_at(ch, n) == '#')
  382. n--;
  383. // Check for a be a space before the final #s:
  384. if (n != orig_n && n >= 0 && peek_at(ch, n) == ' ') {
  385. ch->len = n;
  386. chunk_rtrim(ch);
  387. }
  388. }
  389. // Process one line at a time, modifying a node_block.
  390. static void incorporate_line(strbuf *line, int line_number, node_block** curptr)
  391. {
  392. node_block* last_matched_container;
  393. int offset = 0;
  394. int matched = 0;
  395. int lev = 0;
  396. int i;
  397. struct ListData * data = NULL;
  398. bool all_matched = true;
  399. node_block* container;
  400. node_block* cur = *curptr;
  401. bool blank = false;
  402. int first_nonspace;
  403. int indent;
  404. chunk input;
  405. // Add a newline to the end if not present:
  406. if (line->ptr[line->size - 1] != '\n') {
  407. strbuf_putc(line, '\n');
  408. }
  409. input.data = line->ptr;
  410. input.len = line->size;
  411. // container starts at the document root.
  412. container = cur->top;
  413. // for each containing node_block, try to parse the associated line start.
  414. // bail out on failure: container will point to the last matching node_block.
  415. while (container->last_child && container->last_child->open) {
  416. container = container->last_child;
  417. first_nonspace = offset;
  418. while (peek_at(&input, first_nonspace) == ' ') {
  419. first_nonspace++;
  420. }
  421. indent = first_nonspace - offset;
  422. blank = peek_at(&input, first_nonspace) == '\n';
  423. if (container->tag == BLOCK_BQUOTE) {
  424. matched = indent <= 3 && peek_at(&input, first_nonspace) == '>';
  425. if (matched) {
  426. offset = first_nonspace + 1;
  427. if (peek_at(&input, offset) == ' ')
  428. offset++;
  429. } else {
  430. all_matched = false;
  431. }
  432. } else if (container->tag == BLOCK_LIST_ITEM) {
  433. if (indent >= container->as.list.marker_offset +
  434. container->as.list.padding) {
  435. offset += container->as.list.marker_offset +
  436. container->as.list.padding;
  437. } else if (blank) {
  438. offset = first_nonspace;
  439. } else {
  440. all_matched = false;
  441. }
  442. } else if (container->tag == BLOCK_INDENTED_CODE) {
  443. if (indent >= CODE_INDENT) {
  444. offset += CODE_INDENT;
  445. } else if (blank) {
  446. offset = first_nonspace;
  447. } else {
  448. all_matched = false;
  449. }
  450. } else if (container->tag == BLOCK_ATX_HEADER ||
  451. container->tag == BLOCK_SETEXT_HEADER) {
  452. // a header can never contain more than one line
  453. all_matched = false;
  454. } else if (container->tag == BLOCK_FENCED_CODE) {
  455. // skip optional spaces of fence offset
  456. i = container->as.code.fence_offset;
  457. while (i > 0 && peek_at(&input, offset) == ' ') {
  458. offset++;
  459. i--;
  460. }
  461. } else if (container->tag == BLOCK_HTML) {
  462. if (blank) {
  463. all_matched = false;
  464. }
  465. } else if (container->tag == BLOCK_PARAGRAPH) {
  466. if (blank) {
  467. container->last_line_blank = true;
  468. all_matched = false;
  469. }
  470. }
  471. if (!all_matched) {
  472. container = container->parent; // back up to last matching node_block
  473. break;
  474. }
  475. }
  476. last_matched_container = container;
  477. // check to see if we've hit 2nd blank line, break out of list:
  478. if (blank && container->last_line_blank) {
  479. break_out_of_lists(&container, line_number);
  480. }
  481. // unless last matched container is code node_block, try new container starts:
  482. while (container->tag != BLOCK_FENCED_CODE && container->tag != BLOCK_INDENTED_CODE &&
  483. container->tag != BLOCK_HTML) {
  484. first_nonspace = offset;
  485. while (peek_at(&input, first_nonspace) == ' ')
  486. first_nonspace++;
  487. indent = first_nonspace - offset;
  488. blank = peek_at(&input, first_nonspace) == '\n';
  489. if (indent >= CODE_INDENT) {
  490. if (cur->tag != BLOCK_PARAGRAPH && !blank) {
  491. offset += CODE_INDENT;
  492. container = add_child(container, BLOCK_INDENTED_CODE, line_number, offset + 1);
  493. } else { // indent > 4 in lazy line
  494. break;
  495. }
  496. } else if (peek_at(&input, first_nonspace) == '>') {
  497. offset = first_nonspace + 1;
  498. // optional following character
  499. if (peek_at(&input, offset) == ' ')
  500. offset++;
  501. container = add_child(container, BLOCK_BQUOTE, line_number, offset + 1);
  502. } else if ((matched = scan_atx_header_start(&input, first_nonspace))) {
  503. offset = first_nonspace + matched;
  504. container = add_child(container, BLOCK_ATX_HEADER, line_number, offset + 1);
  505. int hashpos = chunk_strchr(&input, '#', first_nonspace);
  506. int level = 0;
  507. while (peek_at(&input, hashpos) == '#') {
  508. level++;
  509. hashpos++;
  510. }
  511. container->as.header.level = level;
  512. } else if ((matched = scan_open_code_fence(&input, first_nonspace))) {
  513. container = add_child(container, BLOCK_FENCED_CODE, line_number, first_nonspace + 1);
  514. container->as.code.fence_char = peek_at(&input, first_nonspace);
  515. container->as.code.fence_length = matched;
  516. container->as.code.fence_offset = first_nonspace - offset;
  517. offset = first_nonspace + matched;
  518. } else if ((matched = scan_html_block_tag(&input, first_nonspace))) {
  519. container = add_child(container, BLOCK_HTML, line_number, first_nonspace + 1);
  520. // note, we don't adjust offset because the tag is part of the text
  521. } else if (container->tag == BLOCK_PARAGRAPH &&
  522. (lev = scan_setext_header_line(&input, first_nonspace)) &&
  523. // check that there is only one line in the paragraph:
  524. strbuf_strrchr(&container->string_content, '\n',
  525. strbuf_len(&container->string_content) - 2) < 0) {
  526. container->tag = BLOCK_SETEXT_HEADER;
  527. container->as.header.level = lev;
  528. offset = input.len - 1;
  529. } else if (!(container->tag == BLOCK_PARAGRAPH && !all_matched) &&
  530. (matched = scan_hrule(&input, first_nonspace))) {
  531. // it's only now that we know the line is not part of a setext header:
  532. container = add_child(container, BLOCK_HRULE, line_number, first_nonspace + 1);
  533. finalize(container, line_number);
  534. container = container->parent;
  535. offset = input.len - 1;
  536. } else if ((matched = parse_list_marker(&input, first_nonspace, &data))) {
  537. // compute padding:
  538. offset = first_nonspace + matched;
  539. i = 0;
  540. while (i <= 5 && peek_at(&input, offset + i) == ' ') {
  541. i++;
  542. }
  543. // i = number of spaces after marker, up to 5
  544. if (i >= 5 || i < 1 || peek_at(&input, offset) == '\n') {
  545. data->padding = matched + 1;
  546. if (i > 0) {
  547. offset += 1;
  548. }
  549. } else {
  550. data->padding = matched + i;
  551. offset += i;
  552. }
  553. // check container; if it's a list, see if this list item
  554. // can continue the list; otherwise, create a list container.
  555. data->marker_offset = indent;
  556. if (container->tag != BLOCK_LIST ||
  557. !lists_match(&container->as.list, data)) {
  558. container = add_child(container, BLOCK_LIST, line_number,
  559. first_nonspace + 1);
  560. memcpy(&container->as.list, data, sizeof(*data));
  561. }
  562. // add the list item
  563. container = add_child(container, BLOCK_LIST_ITEM, line_number,
  564. first_nonspace + 1);
  565. /* TODO: static */
  566. memcpy(&container->as.list, data, sizeof(*data));
  567. free(data);
  568. } else {
  569. break;
  570. }
  571. if (accepts_lines(container->tag)) {
  572. // if it's a line container, it can't contain other containers
  573. break;
  574. }
  575. }
  576. // what remains at offset is a text line. add the text to the
  577. // appropriate container.
  578. first_nonspace = offset;
  579. while (peek_at(&input, first_nonspace) == ' ')
  580. first_nonspace++;
  581. indent = first_nonspace - offset;
  582. blank = peek_at(&input, first_nonspace) == '\n';
  583. // node_block quote lines are never blank as they start with >
  584. // and we don't count blanks in fenced code for purposes of tight/loose
  585. // lists or breaking out of lists. we also don't set last_line_blank
  586. // on an empty list item.
  587. container->last_line_blank = (blank &&
  588. container->tag != BLOCK_BQUOTE &&
  589. container->tag != BLOCK_FENCED_CODE &&
  590. !(container->tag == BLOCK_LIST_ITEM &&
  591. container->children == NULL &&
  592. container->start_line == line_number));
  593. node_block *cont = container;
  594. while (cont->parent) {
  595. cont->parent->last_line_blank = false;
  596. cont = cont->parent;
  597. }
  598. if (cur != last_matched_container &&
  599. container == last_matched_container &&
  600. !blank &&
  601. cur->tag == BLOCK_PARAGRAPH &&
  602. strbuf_len(&cur->string_content) > 0) {
  603. add_line(cur, &input, offset);
  604. } else { // not a lazy continuation
  605. // finalize any blocks that were not matched and set cur to container:
  606. while (cur != last_matched_container) {
  607. finalize(cur, line_number);
  608. cur = cur->parent;
  609. assert(cur != NULL);
  610. }
  611. if (container->tag == BLOCK_INDENTED_CODE) {
  612. add_line(container, &input, offset);
  613. } else if (container->tag == BLOCK_FENCED_CODE) {
  614. matched = 0;
  615. if (indent <= 3 &&
  616. peek_at(&input, first_nonspace) == container->as.code.fence_char) {
  617. int fence_len = scan_close_code_fence(&input, first_nonspace);
  618. if (fence_len > container->as.code.fence_length)
  619. matched = 1;
  620. }
  621. if (matched) {
  622. // if closing fence, don't add line to container; instead, close it:
  623. finalize(container, line_number);
  624. container = container->parent; // back up to parent
  625. } else {
  626. add_line(container, &input, offset);
  627. }
  628. } else if (container->tag == BLOCK_HTML) {
  629. add_line(container, &input, offset);
  630. } else if (blank) {
  631. // ??? do nothing
  632. } else if (container->tag == BLOCK_ATX_HEADER) {
  633. chop_trailing_hashtags(&input);
  634. add_line(container, &input, first_nonspace);
  635. finalize(container, line_number);
  636. container = container->parent;
  637. } else if (accepts_lines(container->tag)) {
  638. add_line(container, &input, first_nonspace);
  639. } else if (container->tag != BLOCK_HRULE && container->tag != BLOCK_SETEXT_HEADER) {
  640. // create paragraph container for line
  641. container = add_child(container, BLOCK_PARAGRAPH, line_number, first_nonspace + 1);
  642. add_line(container, &input, first_nonspace);
  643. } else {
  644. assert(false);
  645. }
  646. *curptr = container;
  647. }
  648. }