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