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