aboutsummaryrefslogtreecommitdiff
path: root/src/inlines.c
blob: 810230cedfd338d34caffd15422988727699f2cd (plain)
  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include <stdio.h>
  4. #include <stdbool.h>
  5. #include <ctype.h>
  6. #include "cmark.h"
  7. #include "html/houdini.h"
  8. #include "utf8.h"
  9. #include "scanners.h"
  10. #include "inlines.h"
  11. #include "debug.h"
  12. typedef struct InlineStack {
  13. struct InlineStack *previous;
  14. node_inl *first_inline;
  15. int delim_count;
  16. unsigned char delim_char;
  17. } inline_stack;
  18. typedef struct Subject {
  19. chunk input;
  20. int pos;
  21. int label_nestlevel;
  22. reference_map *refmap;
  23. inline_stack *emphasis_openers;
  24. int emphasis_nestlevel;
  25. } subject;
  26. static node_inl *parse_chunk_inlines(chunk *chunk, reference_map *refmap);
  27. static node_inl *parse_inlines_while(subject* subj, int (*f)(subject*));
  28. static int parse_inline(subject* subj, node_inl ** last);
  29. static void subject_from_chunk(subject *e, chunk *chunk, reference_map *refmap);
  30. static void subject_from_buf(subject *e, strbuf *buffer, reference_map *refmap);
  31. static int subject_find_special_char(subject *subj);
  32. static unsigned char *bufdup(const unsigned char *buf)
  33. {
  34. unsigned char *new = NULL;
  35. if (buf) {
  36. int len = strlen((char *)buf);
  37. new = calloc(len + 1, sizeof(*new));
  38. if(new != NULL) {
  39. memcpy(new, buf, len + 1);
  40. }
  41. }
  42. return new;
  43. }
  44. static inline node_inl *make_link_(node_inl *label, unsigned char *url, unsigned char *title)
  45. {
  46. node_inl* e = calloc(1, sizeof(*e));
  47. if(e != NULL) {
  48. e->tag = INL_LINK;
  49. e->content.linkable.label = label;
  50. e->content.linkable.url = url;
  51. e->content.linkable.title = title;
  52. e->next = NULL;
  53. }
  54. return e;
  55. }
  56. inline static node_inl* make_ref_link(node_inl* label, reference *ref)
  57. {
  58. return make_link_(label, bufdup(ref->url), bufdup(ref->title));
  59. }
  60. inline static node_inl* make_autolink(node_inl* label, chunk url, int is_email)
  61. {
  62. return make_link_(label, clean_autolink(&url, is_email), NULL);
  63. }
  64. // Create an inline with a linkable string value.
  65. inline static node_inl* make_link(node_inl* label, chunk url, chunk title)
  66. {
  67. return make_link_(label, clean_url(&url), clean_title(&title));
  68. }
  69. inline static node_inl* make_inlines(int t, node_inl* contents)
  70. {
  71. node_inl * e = calloc(1, sizeof(*e));
  72. if(e != NULL) {
  73. e->tag = t;
  74. e->content.inlines = contents;
  75. e->next = NULL;
  76. }
  77. return e;
  78. }
  79. // Create an inline with a literal string value.
  80. inline static node_inl* make_literal(int t, chunk s)
  81. {
  82. node_inl * e = calloc(1, sizeof(*e));
  83. if(e != NULL) {
  84. e->tag = t;
  85. e->content.literal = s;
  86. e->next = NULL;
  87. }
  88. return e;
  89. }
  90. // Create an inline with no value.
  91. inline static node_inl* make_simple(int t)
  92. {
  93. node_inl* e = calloc(1, sizeof(*e));
  94. if(e != NULL) {
  95. e->tag = t;
  96. e->next = NULL;
  97. }
  98. return e;
  99. }
  100. // Macros for creating various kinds of inlines.
  101. #define make_str(s) make_literal(INL_STRING, s)
  102. #define make_code(s) make_literal(INL_CODE, s)
  103. #define make_raw_html(s) make_literal(INL_RAW_HTML, s)
  104. #define make_linebreak() make_simple(INL_LINEBREAK)
  105. #define make_softbreak() make_simple(INL_SOFTBREAK)
  106. #define make_emph(contents) make_inlines(INL_EMPH, contents)
  107. #define make_strong(contents) make_inlines(INL_STRONG, contents)
  108. // Utility function used by free_inlines
  109. void splice_into_list(node_inl* e, node_inl* children) {
  110. node_inl * tmp;
  111. if (children) {
  112. tmp = children;
  113. // Find last child
  114. while (tmp->next) {
  115. tmp = tmp->next;
  116. }
  117. // Splice children into list
  118. tmp->next = e->next;
  119. e->next = children;
  120. }
  121. return ;
  122. }
  123. // Free an inline list. Avoid recursion to prevent stack overflows
  124. // on deeply nested structures.
  125. extern void free_inlines(node_inl* e)
  126. {
  127. node_inl * next;
  128. while (e != NULL) {
  129. switch (e->tag){
  130. case INL_STRING:
  131. case INL_RAW_HTML:
  132. case INL_CODE:
  133. chunk_free(&e->content.literal);
  134. break;
  135. case INL_LINEBREAK:
  136. case INL_SOFTBREAK:
  137. break;
  138. case INL_LINK:
  139. case INL_IMAGE:
  140. free(e->content.linkable.url);
  141. free(e->content.linkable.title);
  142. splice_into_list(e, e->content.linkable.label);
  143. break;
  144. case INL_EMPH:
  145. case INL_STRONG:
  146. splice_into_list(e, e->content.inlines);
  147. break;
  148. default:
  149. log_warn("Unknown inline tag %d", e->tag);
  150. break;
  151. }
  152. next = e->next;
  153. free(e);
  154. e = next;
  155. }
  156. }
  157. // Append inline list b to the end of inline list a.
  158. // Return pointer to head of new list.
  159. inline static node_inl* append_inlines(node_inl* a, node_inl* b)
  160. {
  161. if (a == NULL) { // NULL acts like an empty list
  162. return b;
  163. }
  164. node_inl* cur = a;
  165. while (cur->next) {
  166. cur = cur->next;
  167. }
  168. cur->next = b;
  169. return a;
  170. }
  171. static void subject_from_buf(subject *e, strbuf *buffer, reference_map *refmap)
  172. {
  173. e->input.data = buffer->ptr;
  174. e->input.len = buffer->size;
  175. e->input.alloc = 0;
  176. e->pos = 0;
  177. e->label_nestlevel = 0;
  178. e->refmap = refmap;
  179. e->emphasis_openers = NULL;
  180. e->emphasis_nestlevel = 0;
  181. chunk_rtrim(&e->input);
  182. }
  183. static void subject_from_chunk(subject *e, chunk *chunk, reference_map *refmap)
  184. {
  185. e->input.data = chunk->data;
  186. e->input.len = chunk->len;
  187. e->input.alloc = 0;
  188. e->pos = 0;
  189. e->label_nestlevel = 0;
  190. e->refmap = refmap;
  191. e->emphasis_openers = NULL;
  192. e->emphasis_nestlevel = 0;
  193. chunk_rtrim(&e->input);
  194. }
  195. inline static int isbacktick(int c)
  196. {
  197. return (c == '`');
  198. }
  199. static inline unsigned char peek_char(subject *subj)
  200. {
  201. return (subj->pos < subj->input.len) ? subj->input.data[subj->pos] : 0;
  202. }
  203. static inline unsigned char peek_at(subject *subj, int pos)
  204. {
  205. return subj->input.data[pos];
  206. }
  207. // Return true if there are more characters in the subject.
  208. inline static int is_eof(subject* subj)
  209. {
  210. return (subj->pos >= subj->input.len);
  211. }
  212. // Advance the subject. Doesn't check for eof.
  213. #define advance(subj) (subj)->pos += 1
  214. // Take characters while a predicate holds, and return a string.
  215. inline static chunk take_while(subject* subj, int (*f)(int))
  216. {
  217. unsigned char c;
  218. int startpos = subj->pos;
  219. int len = 0;
  220. while ((c = peek_char(subj)) && (*f)(c)) {
  221. advance(subj);
  222. len++;
  223. }
  224. return chunk_dup(&subj->input, startpos, len);
  225. }
  226. // Try to process a backtick code span that began with a
  227. // span of ticks of length openticklength length (already
  228. // parsed). Return 0 if you don't find matching closing
  229. // backticks, otherwise return the position in the subject
  230. // after the closing backticks.
  231. static int scan_to_closing_backticks(subject* subj, int openticklength)
  232. {
  233. // read non backticks
  234. unsigned char c;
  235. while ((c = peek_char(subj)) && c != '`') {
  236. advance(subj);
  237. }
  238. if (is_eof(subj)) {
  239. return 0; // did not find closing ticks, return 0
  240. }
  241. int numticks = 0;
  242. while (peek_char(subj) == '`') {
  243. advance(subj);
  244. numticks++;
  245. }
  246. if (numticks != openticklength){
  247. return(scan_to_closing_backticks(subj, openticklength));
  248. }
  249. return (subj->pos);
  250. }
  251. // Parse backtick code section or raw backticks, return an inline.
  252. // Assumes that the subject has a backtick at the current position.
  253. static node_inl* handle_backticks(subject *subj)
  254. {
  255. chunk openticks = take_while(subj, isbacktick);
  256. int startpos = subj->pos;
  257. int endpos = scan_to_closing_backticks(subj, openticks.len);
  258. if (endpos == 0) { // not found
  259. subj->pos = startpos; // rewind
  260. return make_str(openticks);
  261. } else {
  262. strbuf buf = GH_BUF_INIT;
  263. strbuf_set(&buf, subj->input.data + startpos, endpos - startpos - openticks.len);
  264. strbuf_trim(&buf);
  265. strbuf_normalize_whitespace(&buf);
  266. return make_code(chunk_buf_detach(&buf));
  267. }
  268. }
  269. // Scan ***, **, or * and return number scanned, or 0.
  270. // Advances position.
  271. static int scan_delims(subject* subj, unsigned char c, bool * can_open, bool * can_close)
  272. {
  273. int numdelims = 0;
  274. unsigned char char_before, char_after;
  275. char_before = subj->pos == 0 ? '\n' : peek_at(subj, subj->pos - 1);
  276. while (peek_char(subj) == c) {
  277. numdelims++;
  278. advance(subj);
  279. }
  280. char_after = peek_char(subj);
  281. *can_open = numdelims > 0 && !isspace(char_after);
  282. *can_close = numdelims > 0 && !isspace(char_before);
  283. if (c == '_') {
  284. *can_open = *can_open && !isalnum(char_before);
  285. *can_close = *can_close && !isalnum(char_after);
  286. }
  287. return numdelims;
  288. }
  289. static void free_openers(subject* subj, inline_stack* istack)
  290. {
  291. inline_stack * tempstack;
  292. while (subj->emphasis_openers != istack) {
  293. tempstack = subj->emphasis_openers;
  294. subj->emphasis_openers = subj->emphasis_openers->previous;
  295. subj->emphasis_nestlevel--;
  296. free(tempstack);
  297. }
  298. }
  299. // Parse strong/emph or a fallback.
  300. // Assumes the subject has '_' or '*' at the current position.
  301. static node_inl* handle_strong_emph(subject* subj, unsigned char c, node_inl **last)
  302. {
  303. bool can_open, can_close;
  304. int numdelims;
  305. int useDelims;
  306. int openerDelims;
  307. inline_stack * istack;
  308. node_inl * inl;
  309. node_inl * emph;
  310. node_inl * inl_text;
  311. numdelims = scan_delims(subj, c, &can_open, &can_close);
  312. if (can_close)
  313. {
  314. // walk the stack and find a matching opener, if there is one
  315. istack = subj->emphasis_openers;
  316. while (true)
  317. {
  318. if (istack == NULL)
  319. goto cannotClose;
  320. if (istack->delim_char == c)
  321. break;
  322. istack = istack->previous;
  323. }
  324. // calculate the actual number of delimeters used from this closer
  325. openerDelims = istack->delim_count;
  326. if (numdelims < 3 || openerDelims < 3) {
  327. useDelims = numdelims <= openerDelims ? numdelims : openerDelims;
  328. } else { // (numdelims >= 3 && openerDelims >= 3)
  329. useDelims = numdelims % 2 == 0 ? 2 : 1;
  330. }
  331. if (istack->delim_count == useDelims)
  332. {
  333. // the opener is completely used up - remove the stack entry and reuse the inline element
  334. inl = istack->first_inline;
  335. inl->tag = useDelims == 1 ? INL_EMPH : INL_STRONG;
  336. chunk_free(&inl->content.literal);
  337. inl->content.inlines = inl->next;
  338. inl->next = NULL;
  339. // remove this opener and all later ones from stack:
  340. free_openers(subj, istack->previous);
  341. *last = inl;
  342. }
  343. else
  344. {
  345. // the opener will only partially be used - stack entry remains (truncated) and a new inline is added.
  346. inl = istack->first_inline;
  347. istack->delim_count -= useDelims;
  348. inl->content.literal.len = istack->delim_count;
  349. emph = useDelims == 1 ? make_emph(inl->next) : make_strong(inl->next);
  350. inl->next = emph;
  351. // remove all later openers from stack:
  352. free_openers(subj, istack);
  353. *last = emph;
  354. }
  355. // if the closer was not fully used, move back a char or two and try again.
  356. if (useDelims < numdelims)
  357. {
  358. subj->pos = subj->pos - numdelims + useDelims;
  359. return NULL;
  360. }
  361. return NULL; // make_str(chunk_literal(""));
  362. }
  363. cannotClose:
  364. inl_text = make_str(chunk_dup(&subj->input, subj->pos - numdelims, numdelims));
  365. if (can_open)
  366. {
  367. istack = (inline_stack*)malloc(sizeof(inline_stack));
  368. if (istack == NULL) {
  369. return NULL;
  370. }
  371. istack->delim_count = numdelims;
  372. istack->delim_char = c;
  373. istack->first_inline = inl_text;
  374. istack->previous = subj->emphasis_openers;
  375. subj->emphasis_openers = istack;
  376. subj->emphasis_nestlevel++;
  377. }
  378. return inl_text;
  379. }
  380. // Parse backslash-escape or just a backslash, returning an inline.
  381. static node_inl* handle_backslash(subject *subj)
  382. {
  383. advance(subj);
  384. unsigned char nextchar = peek_char(subj);
  385. if (ispunct(nextchar)) { // only ascii symbols and newline can be escaped
  386. advance(subj);
  387. return make_str(chunk_dup(&subj->input, subj->pos - 1, 1));
  388. } else if (nextchar == '\n') {
  389. advance(subj);
  390. return make_linebreak();
  391. } else {
  392. return make_str(chunk_literal("\\"));
  393. }
  394. }
  395. // Parse an entity or a regular "&" string.
  396. // Assumes the subject has an '&' character at the current position.
  397. static node_inl* handle_entity(subject* subj)
  398. {
  399. strbuf ent = GH_BUF_INIT;
  400. size_t len;
  401. advance(subj);
  402. len = houdini_unescape_ent(&ent,
  403. subj->input.data + subj->pos,
  404. subj->input.len - subj->pos
  405. );
  406. if (len == 0)
  407. return make_str(chunk_literal("&"));
  408. subj->pos += len;
  409. return make_str(chunk_buf_detach(&ent));
  410. }
  411. // Like make_str, but parses entities.
  412. // Returns an inline sequence consisting of str and entity elements.
  413. static node_inl *make_str_with_entities(chunk *content)
  414. {
  415. strbuf unescaped = GH_BUF_INIT;
  416. if (houdini_unescape_html(&unescaped, content->data, (size_t)content->len)) {
  417. return make_str(chunk_buf_detach(&unescaped));
  418. } else {
  419. return make_str(*content);
  420. }
  421. }
  422. // Clean a URL: remove surrounding whitespace and surrounding <>,
  423. // and remove \ that escape punctuation.
  424. unsigned char *clean_url(chunk *url)
  425. {
  426. strbuf buf = GH_BUF_INIT;
  427. chunk_trim(url);
  428. if (url->len == 0)
  429. return NULL;
  430. if (url->data[0] == '<' && url->data[url->len - 1] == '>') {
  431. houdini_unescape_html_f(&buf, url->data + 1, url->len - 2);
  432. } else {
  433. houdini_unescape_html_f(&buf, url->data, url->len);
  434. }
  435. strbuf_unescape(&buf);
  436. return strbuf_detach(&buf);
  437. }
  438. unsigned char *clean_autolink(chunk *url, int is_email)
  439. {
  440. strbuf buf = GH_BUF_INIT;
  441. chunk_trim(url);
  442. if (url->len == 0)
  443. return NULL;
  444. if (is_email)
  445. strbuf_puts(&buf, "mailto:");
  446. houdini_unescape_html_f(&buf, url->data, url->len);
  447. return strbuf_detach(&buf);
  448. }
  449. // Clean a title: remove surrounding quotes and remove \ that escape punctuation.
  450. unsigned char *clean_title(chunk *title)
  451. {
  452. strbuf buf = GH_BUF_INIT;
  453. unsigned char first, last;
  454. if (title->len == 0)
  455. return NULL;
  456. first = title->data[0];
  457. last = title->data[title->len - 1];
  458. // remove surrounding quotes if any:
  459. if ((first == '\'' && last == '\'') ||
  460. (first == '(' && last == ')') ||
  461. (first == '"' && last == '"')) {
  462. houdini_unescape_html_f(&buf, title->data + 1, title->len - 2);
  463. } else {
  464. houdini_unescape_html_f(&buf, title->data, title->len);
  465. }
  466. strbuf_unescape(&buf);
  467. return strbuf_detach(&buf);
  468. }
  469. // Parse an autolink or HTML tag.
  470. // Assumes the subject has a '<' character at the current position.
  471. static node_inl* handle_pointy_brace(subject* subj)
  472. {
  473. int matchlen = 0;
  474. chunk contents;
  475. advance(subj); // advance past first <
  476. // first try to match a URL autolink
  477. matchlen = scan_autolink_uri(&subj->input, subj->pos);
  478. if (matchlen > 0) {
  479. contents = chunk_dup(&subj->input, subj->pos, matchlen - 1);
  480. subj->pos += matchlen;
  481. return make_autolink(
  482. make_str_with_entities(&contents),
  483. contents, 0
  484. );
  485. }
  486. // next try to match an email autolink
  487. matchlen = scan_autolink_email(&subj->input, subj->pos);
  488. if (matchlen > 0) {
  489. contents = chunk_dup(&subj->input, subj->pos, matchlen - 1);
  490. subj->pos += matchlen;
  491. return make_autolink(
  492. make_str_with_entities(&contents),
  493. contents, 1
  494. );
  495. }
  496. // finally, try to match an html tag
  497. matchlen = scan_html_tag(&subj->input, subj->pos);
  498. if (matchlen > 0) {
  499. contents = chunk_dup(&subj->input, subj->pos - 1, matchlen + 1);
  500. subj->pos += matchlen;
  501. return make_raw_html(contents);
  502. }
  503. // if nothing matches, just return the opening <:
  504. return make_str(chunk_literal("<"));
  505. }
  506. // Parse a link label. Returns 1 if successful.
  507. // Unless raw_label is null, it is set to point to the raw contents of the [].
  508. // Assumes the subject has a '[' character at the current position.
  509. // Returns 0 and does not advance if no matching ] is found.
  510. // Note the precedence: code backticks have precedence over label bracket
  511. // markers, which have precedence over *, _, and other inline formatting
  512. // markers. So, 2 below contains a link while 1 does not:
  513. // 1. [a link `with a ](/url)` character
  514. // 2. [a link *with emphasized ](/url) text*
  515. static int link_label(subject* subj, chunk *raw_label)
  516. {
  517. int nestlevel = 0;
  518. node_inl* tmp = NULL;
  519. int startpos = subj->pos;
  520. if (subj->label_nestlevel) {
  521. // if we've already checked to the end of the subject
  522. // for a label, even with a different starting [, we
  523. // know we won't find one here and we can just return.
  524. // Note: nestlevel 1 would be: [foo [bar]
  525. // nestlevel 2 would be: [foo [bar [baz]
  526. subj->label_nestlevel--;
  527. return 0;
  528. }
  529. advance(subj); // advance past [
  530. unsigned char c;
  531. while ((c = peek_char(subj)) && (c != ']' || nestlevel > 0)) {
  532. switch (c) {
  533. case '`':
  534. tmp = handle_backticks(subj);
  535. free_inlines(tmp);
  536. break;
  537. case '<':
  538. tmp = handle_pointy_brace(subj);
  539. free_inlines(tmp);
  540. break;
  541. case '[': // nested []
  542. nestlevel++;
  543. advance(subj);
  544. break;
  545. case ']': // nested []
  546. nestlevel--;
  547. advance(subj);
  548. break;
  549. case '\\':
  550. advance(subj);
  551. if (ispunct(peek_char(subj))) {
  552. advance(subj);
  553. }
  554. break;
  555. default:
  556. advance(subj);
  557. }
  558. }
  559. if (nestlevel == 0 && c == ']') {
  560. *raw_label = chunk_dup(&subj->input, startpos + 1, subj->pos - (startpos + 1));
  561. subj->label_nestlevel = 0;
  562. advance(subj); // advance past ]
  563. return 1;
  564. } else {
  565. if (c == 0) {
  566. subj->label_nestlevel = nestlevel;
  567. }
  568. subj->pos = startpos; // rewind
  569. return 0;
  570. }
  571. }
  572. // Parse a link or the link portion of an image, or return a fallback.
  573. static node_inl* handle_left_bracket(subject* subj)
  574. {
  575. node_inl *lab = NULL;
  576. node_inl *result = NULL;
  577. reference *ref;
  578. int n;
  579. int sps;
  580. int found_label;
  581. int endlabel, startpos, starturl, endurl, starttitle, endtitle, endall;
  582. chunk rawlabel;
  583. chunk url, title;
  584. startpos = subj->pos;
  585. found_label = link_label(subj, &rawlabel);
  586. endlabel = subj->pos;
  587. if (found_label) {
  588. if (peek_char(subj) == '(' &&
  589. ((sps = scan_spacechars(&subj->input, subj->pos + 1)) > -1) &&
  590. ((n = scan_link_url(&subj->input, subj->pos + 1 + sps)) > -1)) {
  591. // try to parse an explicit link:
  592. starturl = subj->pos + 1 + sps; // after (
  593. endurl = starturl + n;
  594. starttitle = endurl + scan_spacechars(&subj->input, endurl);
  595. // ensure there are spaces btw url and title
  596. endtitle = (starttitle == endurl) ? starttitle :
  597. starttitle + scan_link_title(&subj->input, starttitle);
  598. endall = endtitle + scan_spacechars(&subj->input, endtitle);
  599. if (peek_at(subj, endall) == ')') {
  600. subj->pos = endall + 1;
  601. url = chunk_dup(&subj->input, starturl, endurl - starturl);
  602. title = chunk_dup(&subj->input, starttitle, endtitle - starttitle);
  603. lab = parse_chunk_inlines(&rawlabel, NULL);
  604. return make_link(lab, url, title);
  605. } else {
  606. goto noMatch;
  607. }
  608. } else {
  609. chunk rawlabel_tmp;
  610. chunk reflabel;
  611. // Check for reference link.
  612. // First, see if there's another label:
  613. subj->pos = subj->pos + scan_spacechars(&subj->input, endlabel);
  614. reflabel = rawlabel;
  615. // if followed by a nonempty link label, we change reflabel to it:
  616. if (peek_char(subj) == '[' && link_label(subj, &rawlabel_tmp)) {
  617. if (rawlabel_tmp.len > 0)
  618. reflabel = rawlabel_tmp;
  619. } else {
  620. subj->pos = endlabel;
  621. }
  622. // lookup rawlabel in subject->reference_map:
  623. ref = reference_lookup(subj->refmap, &reflabel);
  624. if (ref != NULL) { // found
  625. lab = parse_chunk_inlines(&rawlabel, NULL);
  626. result = make_ref_link(lab, ref);
  627. } else {
  628. goto noMatch;
  629. }
  630. return result;
  631. }
  632. }
  633. noMatch:
  634. // If we fall through to here, it means we didn't match a link:
  635. subj->pos = startpos + 1; // advance past [
  636. return make_str(chunk_literal("["));
  637. }
  638. // Parse a hard or soft linebreak, returning an inline.
  639. // Assumes the subject has a newline at the current position.
  640. static node_inl* handle_newline(subject *subj)
  641. {
  642. int nlpos = subj->pos;
  643. // skip over newline
  644. advance(subj);
  645. // skip spaces at beginning of line
  646. while (peek_char(subj) == ' ') {
  647. advance(subj);
  648. }
  649. if (nlpos > 1 &&
  650. peek_at(subj, nlpos - 1) == ' ' &&
  651. peek_at(subj, nlpos - 2) == ' ') {
  652. return make_linebreak();
  653. } else {
  654. return make_softbreak();
  655. }
  656. }
  657. inline static int not_eof(subject* subj)
  658. {
  659. return !is_eof(subj);
  660. }
  661. // Parse inlines while a predicate is satisfied. Return inlines.
  662. extern node_inl* parse_inlines_while(subject* subj, int (*f)(subject*))
  663. {
  664. node_inl* result = NULL;
  665. node_inl** last = &result;
  666. node_inl* first = NULL;
  667. while ((*f)(subj) && parse_inline(subj, last)) {
  668. if (!first) {
  669. first = *last;
  670. }
  671. }
  672. inline_stack* istack = subj->emphasis_openers;
  673. inline_stack* temp;
  674. while (istack != NULL) {
  675. temp = istack->previous;
  676. free(istack);
  677. istack = temp;
  678. }
  679. return first;
  680. }
  681. node_inl *parse_chunk_inlines(chunk *chunk, reference_map *refmap)
  682. {
  683. subject subj;
  684. subject_from_chunk(&subj, chunk, refmap);
  685. return parse_inlines_while(&subj, not_eof);
  686. }
  687. static int subject_find_special_char(subject *subj)
  688. {
  689. // "\n\\`&_*[]<!"
  690. static const int8_t SPECIAL_CHARS[256] = {
  691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
  692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  693. 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0,
  694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
  695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1,
  697. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
  707. int n = subj->pos + 1;
  708. while (n < subj->input.len) {
  709. if (SPECIAL_CHARS[subj->input.data[n]])
  710. return n;
  711. n++;
  712. }
  713. return subj->input.len;
  714. }
  715. // Parse an inline, advancing subject, and add it to last element.
  716. // Adjust tail to point to new last element of list.
  717. // Return 0 if no inline can be parsed, 1 otherwise.
  718. static int parse_inline(subject* subj, node_inl ** last)
  719. {
  720. node_inl* new = NULL;
  721. chunk contents;
  722. unsigned char c;
  723. int endpos;
  724. c = peek_char(subj);
  725. if (c == 0) {
  726. return 0;
  727. }
  728. switch(c){
  729. case '\n':
  730. new = handle_newline(subj);
  731. break;
  732. case '`':
  733. new = handle_backticks(subj);
  734. break;
  735. case '\\':
  736. new = handle_backslash(subj);
  737. break;
  738. case '&':
  739. new = handle_entity(subj);
  740. break;
  741. case '<':
  742. new = handle_pointy_brace(subj);
  743. break;
  744. case '_':
  745. new = handle_strong_emph(subj, '_', last);
  746. break;
  747. case '*':
  748. new = handle_strong_emph(subj, '*', last);
  749. break;
  750. case '[':
  751. new = handle_left_bracket(subj);
  752. break;
  753. case '!':
  754. advance(subj);
  755. if (peek_char(subj) == '[') {
  756. new = handle_left_bracket(subj);
  757. if (new != NULL && new->tag == INL_LINK) {
  758. new->tag = INL_IMAGE;
  759. } else {
  760. new = append_inlines(make_str(chunk_literal("!")), new);
  761. }
  762. } else {
  763. new = make_str(chunk_literal("!"));
  764. }
  765. break;
  766. default:
  767. endpos = subject_find_special_char(subj);
  768. contents = chunk_dup(&subj->input, subj->pos, endpos - subj->pos);
  769. subj->pos = endpos;
  770. // if we're at a newline, strip trailing spaces.
  771. if (peek_char(subj) == '\n') {
  772. chunk_rtrim(&contents);
  773. }
  774. new = make_str(contents);
  775. }
  776. if (*last == NULL) {
  777. *last = new;
  778. } else if (new) {
  779. append_inlines(*last, new);
  780. *last = new;
  781. }
  782. return 1;
  783. }
  784. extern node_inl* parse_inlines(strbuf *input, reference_map *refmap)
  785. {
  786. subject subj;
  787. subject_from_buf(&subj, input, refmap);
  788. return parse_inlines_while(&subj, not_eof);
  789. }
  790. // Parse zero or more space characters, including at most one newline.
  791. void spnl(subject* subj)
  792. {
  793. bool seen_newline = false;
  794. while (peek_char(subj) == ' ' ||
  795. (!seen_newline &&
  796. (seen_newline = peek_char(subj) == '\n'))) {
  797. advance(subj);
  798. }
  799. }
  800. // Parse reference. Assumes string begins with '[' character.
  801. // Modify refmap if a reference is encountered.
  802. // Return 0 if no reference found, otherwise position of subject
  803. // after reference is parsed.
  804. int parse_reference_inline(strbuf *input, reference_map *refmap)
  805. {
  806. subject subj;
  807. chunk lab;
  808. chunk url;
  809. chunk title;
  810. int matchlen = 0;
  811. int beforetitle;
  812. subject_from_buf(&subj, input, NULL);
  813. // parse label:
  814. if (!link_label(&subj, &lab))
  815. return 0;
  816. // colon:
  817. if (peek_char(&subj) == ':') {
  818. advance(&subj);
  819. } else {
  820. return 0;
  821. }
  822. // parse link url:
  823. spnl(&subj);
  824. matchlen = scan_link_url(&subj.input, subj.pos);
  825. if (matchlen) {
  826. url = chunk_dup(&subj.input, subj.pos, matchlen);
  827. subj.pos += matchlen;
  828. } else {
  829. return 0;
  830. }
  831. // parse optional link_title
  832. beforetitle = subj.pos;
  833. spnl(&subj);
  834. matchlen = scan_link_title(&subj.input, subj.pos);
  835. if (matchlen) {
  836. title = chunk_dup(&subj.input, subj.pos, matchlen);
  837. subj.pos += matchlen;
  838. } else {
  839. subj.pos = beforetitle;
  840. title = chunk_literal("");
  841. }
  842. // parse final spaces and newline:
  843. while (peek_char(&subj) == ' ') {
  844. advance(&subj);
  845. }
  846. if (peek_char(&subj) == '\n') {
  847. advance(&subj);
  848. } else if (peek_char(&subj) != 0) {
  849. return 0;
  850. }
  851. // insert reference into refmap
  852. reference_create(refmap, &lab, &url, &title);
  853. return subj.pos;
  854. }