aboutsummaryrefslogtreecommitdiff
path: root/src/inlines.c
blob: e747dfde763eee495561a2eded2469bad354f92a (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 && !isspace(char_after);
  264. *can_close = numdelims > 0 && !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. int openerDelims;
  289. inline_stack * istack;
  290. node_inl * inl;
  291. node_inl * emph;
  292. node_inl * inl_text;
  293. numdelims = scan_delims(subj, c, &can_open, &can_close);
  294. if (can_close)
  295. {
  296. // walk the stack and find a matching opener, if there is one
  297. istack = subj->emphasis_openers;
  298. while (true)
  299. {
  300. if (istack == NULL)
  301. goto cannotClose;
  302. if (istack->delim_char == c)
  303. break;
  304. istack = istack->previous;
  305. }
  306. // calculate the actual number of delimeters used from this closer
  307. openerDelims = istack->delim_count;
  308. if (numdelims < 3 || openerDelims < 3) {
  309. useDelims = numdelims <= openerDelims ? numdelims : openerDelims;
  310. } else { // (numdelims >= 3 && openerDelims >= 3)
  311. useDelims = numdelims % 2 == 0 ? 2 : 1;
  312. }
  313. if (istack->delim_count == useDelims)
  314. {
  315. // the opener is completely used up - remove the stack entry and reuse the inline element
  316. inl = istack->first_inline;
  317. inl->tag = useDelims == 1 ? INL_EMPH : INL_STRONG;
  318. chunk_free(&inl->content.literal);
  319. inl->content.inlines = inl->next;
  320. inl->next = NULL;
  321. // remove this opener and all later ones from stack:
  322. free_openers(subj, istack->previous);
  323. *last = inl;
  324. }
  325. else
  326. {
  327. // the opener will only partially be used - stack entry remains (truncated) and a new inline is added.
  328. inl = istack->first_inline;
  329. istack->delim_count -= useDelims;
  330. inl->content.literal.len = istack->delim_count;
  331. emph = useDelims == 1 ? make_emph(inl->next) : make_strong(inl->next);
  332. inl->next = emph;
  333. // remove all later openers from stack:
  334. free_openers(subj, istack);
  335. *last = emph;
  336. }
  337. // if the closer was not fully used, move back a char or two and try again.
  338. if (useDelims < numdelims)
  339. {
  340. subj->pos = subj->pos - numdelims + useDelims;
  341. return handle_strong_emph(subj, c, last);
  342. }
  343. return NULL; // make_str(chunk_literal(""));
  344. }
  345. cannotClose:
  346. inl_text = make_str(chunk_dup(&subj->input, subj->pos - numdelims, numdelims));
  347. if (can_open && subj->emphasis_nestlevel < STACK_LIMIT)
  348. {
  349. istack = (inline_stack*)malloc(sizeof(inline_stack));
  350. if (istack == NULL) {
  351. return NULL;
  352. }
  353. istack->delim_count = numdelims;
  354. istack->delim_char = c;
  355. istack->first_inline = inl_text;
  356. istack->previous = subj->emphasis_openers;
  357. subj->emphasis_openers = istack;
  358. subj->emphasis_nestlevel++;
  359. }
  360. return inl_text;
  361. }
  362. // Parse backslash-escape or just a backslash, returning an inline.
  363. static node_inl* handle_backslash(subject *subj)
  364. {
  365. advance(subj);
  366. unsigned char nextchar = peek_char(subj);
  367. if (ispunct(nextchar)) { // only ascii symbols and newline can be escaped
  368. advance(subj);
  369. return make_str(chunk_dup(&subj->input, subj->pos - 1, 1));
  370. } else if (nextchar == '\n') {
  371. advance(subj);
  372. return make_linebreak();
  373. } else {
  374. return make_str(chunk_literal("\\"));
  375. }
  376. }
  377. // Parse an entity or a regular "&" string.
  378. // Assumes the subject has an '&' character at the current position.
  379. static node_inl* handle_entity(subject* subj)
  380. {
  381. strbuf ent = GH_BUF_INIT;
  382. size_t len;
  383. advance(subj);
  384. len = houdini_unescape_ent(&ent,
  385. subj->input.data + subj->pos,
  386. subj->input.len - subj->pos
  387. );
  388. if (len == 0)
  389. return make_str(chunk_literal("&"));
  390. subj->pos += len;
  391. return make_str(chunk_buf_detach(&ent));
  392. }
  393. // Like make_str, but parses entities.
  394. // Returns an inline sequence consisting of str and entity elements.
  395. static node_inl *make_str_with_entities(chunk *content)
  396. {
  397. strbuf unescaped = GH_BUF_INIT;
  398. if (houdini_unescape_html(&unescaped, content->data, (size_t)content->len)) {
  399. return make_str(chunk_buf_detach(&unescaped));
  400. } else {
  401. return make_str(*content);
  402. }
  403. }
  404. // Clean a URL: remove surrounding whitespace and surrounding <>,
  405. // and remove \ that escape punctuation.
  406. unsigned char *clean_url(chunk *url)
  407. {
  408. strbuf buf = GH_BUF_INIT;
  409. chunk_trim(url);
  410. if (url->len == 0)
  411. return NULL;
  412. if (url->data[0] == '<' && url->data[url->len - 1] == '>') {
  413. houdini_unescape_html_f(&buf, url->data + 1, url->len - 2);
  414. } else {
  415. houdini_unescape_html_f(&buf, url->data, url->len);
  416. }
  417. strbuf_unescape(&buf);
  418. return strbuf_detach(&buf);
  419. }
  420. unsigned char *clean_autolink(chunk *url, int is_email)
  421. {
  422. strbuf buf = GH_BUF_INIT;
  423. chunk_trim(url);
  424. if (url->len == 0)
  425. return NULL;
  426. if (is_email)
  427. strbuf_puts(&buf, "mailto:");
  428. houdini_unescape_html_f(&buf, url->data, url->len);
  429. return strbuf_detach(&buf);
  430. }
  431. // Clean a title: remove surrounding quotes and remove \ that escape punctuation.
  432. unsigned char *clean_title(chunk *title)
  433. {
  434. strbuf buf = GH_BUF_INIT;
  435. unsigned char first, last;
  436. if (title->len == 0)
  437. return NULL;
  438. first = title->data[0];
  439. last = title->data[title->len - 1];
  440. // remove surrounding quotes if any:
  441. if ((first == '\'' && last == '\'') ||
  442. (first == '(' && last == ')') ||
  443. (first == '"' && last == '"')) {
  444. houdini_unescape_html_f(&buf, title->data + 1, title->len - 2);
  445. } else {
  446. houdini_unescape_html_f(&buf, title->data, title->len);
  447. }
  448. strbuf_unescape(&buf);
  449. return strbuf_detach(&buf);
  450. }
  451. // Parse an autolink or HTML tag.
  452. // Assumes the subject has a '<' character at the current position.
  453. static node_inl* handle_pointy_brace(subject* subj)
  454. {
  455. int matchlen = 0;
  456. chunk contents;
  457. advance(subj); // advance past first <
  458. // first try to match a URL autolink
  459. matchlen = scan_autolink_uri(&subj->input, subj->pos);
  460. if (matchlen > 0) {
  461. contents = chunk_dup(&subj->input, subj->pos, matchlen - 1);
  462. subj->pos += matchlen;
  463. return make_autolink(
  464. make_str_with_entities(&contents),
  465. contents, 0
  466. );
  467. }
  468. // next try to match an email autolink
  469. matchlen = scan_autolink_email(&subj->input, subj->pos);
  470. if (matchlen > 0) {
  471. contents = chunk_dup(&subj->input, subj->pos, matchlen - 1);
  472. subj->pos += matchlen;
  473. return make_autolink(
  474. make_str_with_entities(&contents),
  475. contents, 1
  476. );
  477. }
  478. // finally, try to match an html tag
  479. matchlen = scan_html_tag(&subj->input, subj->pos);
  480. if (matchlen > 0) {
  481. contents = chunk_dup(&subj->input, subj->pos - 1, matchlen + 1);
  482. subj->pos += matchlen;
  483. return make_raw_html(contents);
  484. }
  485. // if nothing matches, just return the opening <:
  486. return make_str(chunk_literal("<"));
  487. }
  488. // Parse a link label. Returns 1 if successful.
  489. // Unless raw_label is null, it is set to point to the raw contents of the [].
  490. // Assumes the subject has a '[' character at the current position.
  491. // Returns 0 and does not advance if no matching ] is found.
  492. // Note the precedence: code backticks have precedence over label bracket
  493. // markers, which have precedence over *, _, and other inline formatting
  494. // markers. So, 2 below contains a link while 1 does not:
  495. // 1. [a link `with a ](/url)` character
  496. // 2. [a link *with emphasized ](/url) text*
  497. static int link_label(subject* subj, chunk *raw_label)
  498. {
  499. int nestlevel = 0;
  500. node_inl* tmp = NULL;
  501. int startpos = subj->pos;
  502. if (subj->label_nestlevel) {
  503. // if we've already checked to the end of the subject
  504. // for a label, even with a different starting [, we
  505. // know we won't find one here and we can just return.
  506. // Note: nestlevel 1 would be: [foo [bar]
  507. // nestlevel 2 would be: [foo [bar [baz]
  508. subj->label_nestlevel--;
  509. return 0;
  510. }
  511. advance(subj); // advance past [
  512. unsigned char c;
  513. while ((c = peek_char(subj)) &&
  514. (c != ']' || (nestlevel > 0 && nestlevel < STACK_LIMIT))) {
  515. switch (c) {
  516. case '`':
  517. tmp = handle_backticks(subj);
  518. free_inlines(tmp);
  519. break;
  520. case '<':
  521. tmp = handle_pointy_brace(subj);
  522. free_inlines(tmp);
  523. break;
  524. case '[': // nested []
  525. nestlevel++;
  526. advance(subj);
  527. break;
  528. case ']': // nested []
  529. nestlevel--;
  530. advance(subj);
  531. break;
  532. case '\\':
  533. advance(subj);
  534. if (ispunct(peek_char(subj))) {
  535. advance(subj);
  536. }
  537. break;
  538. default:
  539. advance(subj);
  540. }
  541. }
  542. if (nestlevel == 0 && c == ']') {
  543. *raw_label = chunk_dup(&subj->input, startpos + 1, subj->pos - (startpos + 1));
  544. subj->label_nestlevel = 0;
  545. advance(subj); // advance past ]
  546. return 1;
  547. } else {
  548. if (c == 0) {
  549. subj->label_nestlevel = nestlevel;
  550. }
  551. subj->pos = startpos; // rewind
  552. return 0;
  553. }
  554. }
  555. // Parse a link or the link portion of an image, or return a fallback.
  556. static node_inl* handle_left_bracket(subject* subj)
  557. {
  558. node_inl *lab = NULL;
  559. node_inl *result = NULL;
  560. reference *ref;
  561. int n;
  562. int sps;
  563. int found_label;
  564. int endlabel, starturl, endurl, starttitle, endtitle, endall;
  565. chunk rawlabel;
  566. chunk url, title;
  567. found_label = link_label(subj, &rawlabel);
  568. endlabel = subj->pos;
  569. if (found_label) {
  570. if (peek_char(subj) == '(' &&
  571. ((sps = scan_spacechars(&subj->input, subj->pos + 1)) > -1) &&
  572. ((n = scan_link_url(&subj->input, subj->pos + 1 + sps)) > -1)) {
  573. // try to parse an explicit link:
  574. starturl = subj->pos + 1 + sps; // after (
  575. endurl = starturl + n;
  576. starttitle = endurl + scan_spacechars(&subj->input, endurl);
  577. // ensure there are spaces btw url and title
  578. endtitle = (starttitle == endurl) ? starttitle :
  579. starttitle + scan_link_title(&subj->input, starttitle);
  580. endall = endtitle + scan_spacechars(&subj->input, endtitle);
  581. if (peek_at(subj, endall) == ')') {
  582. subj->pos = endall + 1;
  583. url = chunk_dup(&subj->input, starturl, endurl - starturl);
  584. title = chunk_dup(&subj->input, starttitle, endtitle - starttitle);
  585. lab = parse_chunk_inlines(&rawlabel, NULL);
  586. return make_link(lab, url, title);
  587. } else {
  588. // if we get here, we matched a label but didn't get further:
  589. subj->pos = endlabel;
  590. lab = parse_chunk_inlines(&rawlabel, subj->refmap);
  591. result = append_inlines(make_str(chunk_literal("[")),
  592. append_inlines(lab,
  593. make_str(chunk_literal("]"))));
  594. return result;
  595. }
  596. } else {
  597. chunk rawlabel_tmp;
  598. chunk reflabel;
  599. // Check for reference link.
  600. // First, see if there's another label:
  601. subj->pos = subj->pos + scan_spacechars(&subj->input, endlabel);
  602. reflabel = rawlabel;
  603. // if followed by a nonempty link label, we change reflabel to it:
  604. if (peek_char(subj) == '[' && link_label(subj, &rawlabel_tmp)) {
  605. if (rawlabel_tmp.len > 0)
  606. reflabel = rawlabel_tmp;
  607. } else {
  608. subj->pos = endlabel;
  609. }
  610. // lookup rawlabel in subject->reference_map:
  611. ref = reference_lookup(subj->refmap, &reflabel);
  612. if (ref != NULL) { // found
  613. lab = parse_chunk_inlines(&rawlabel, NULL);
  614. result = make_ref_link(lab, ref);
  615. } else {
  616. subj->pos = endlabel;
  617. lab = parse_chunk_inlines(&rawlabel, subj->refmap);
  618. result = append_inlines(make_str(chunk_literal("[")),
  619. append_inlines(lab, make_str(chunk_literal("]"))));
  620. }
  621. return result;
  622. }
  623. }
  624. // If we fall through to here, it means we didn't match a link:
  625. advance(subj); // advance past [
  626. return make_str(chunk_literal("["));
  627. }
  628. // Parse a hard or soft linebreak, returning an inline.
  629. // Assumes the subject has a newline at the current position.
  630. static node_inl* handle_newline(subject *subj)
  631. {
  632. int nlpos = subj->pos;
  633. // skip over newline
  634. advance(subj);
  635. // skip spaces at beginning of line
  636. while (peek_char(subj) == ' ') {
  637. advance(subj);
  638. }
  639. if (nlpos > 1 &&
  640. peek_at(subj, nlpos - 1) == ' ' &&
  641. peek_at(subj, nlpos - 2) == ' ') {
  642. return make_linebreak();
  643. } else {
  644. return make_softbreak();
  645. }
  646. }
  647. inline static int not_eof(subject* subj)
  648. {
  649. return !is_eof(subj);
  650. }
  651. // Parse inlines while a predicate is satisfied. Return inlines.
  652. extern node_inl* parse_inlines_while(subject* subj, int (*f)(subject*))
  653. {
  654. node_inl* result = NULL;
  655. node_inl** last = &result;
  656. node_inl* first = NULL;
  657. while ((*f)(subj) && parse_inline(subj, last)) {
  658. if (!first) {
  659. first = *last;
  660. }
  661. }
  662. inline_stack* istack = subj->emphasis_openers;
  663. inline_stack* temp;
  664. while (istack != NULL) {
  665. temp = istack->previous;
  666. free(istack);
  667. istack = temp;
  668. }
  669. return first;
  670. }
  671. node_inl *parse_chunk_inlines(chunk *chunk, reference_map *refmap)
  672. {
  673. subject subj;
  674. subject_from_chunk(&subj, chunk, refmap);
  675. return parse_inlines_while(&subj, not_eof);
  676. }
  677. static int subject_find_special_char(subject *subj)
  678. {
  679. // "\n\\`&_*[]<!"
  680. static const int8_t SPECIAL_CHARS[256] = {
  681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
  682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  683. 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0,
  684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 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, 1, 1, 1, 0, 1,
  687. 1, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0 };
  697. int n = subj->pos + 1;
  698. while (n < subj->input.len) {
  699. if (SPECIAL_CHARS[subj->input.data[n]])
  700. return n;
  701. n++;
  702. }
  703. return subj->input.len;
  704. }
  705. // Parse an inline, advancing subject, and add it to last element.
  706. // Adjust tail to point to new last element of list.
  707. // Return 0 if no inline can be parsed, 1 otherwise.
  708. static int parse_inline(subject* subj, node_inl ** last)
  709. {
  710. node_inl* new = NULL;
  711. chunk contents;
  712. unsigned char c;
  713. int endpos;
  714. c = peek_char(subj);
  715. if (c == 0) {
  716. return 0;
  717. }
  718. switch(c){
  719. case '\n':
  720. new = handle_newline(subj);
  721. break;
  722. case '`':
  723. new = handle_backticks(subj);
  724. break;
  725. case '\\':
  726. new = handle_backslash(subj);
  727. break;
  728. case '&':
  729. new = handle_entity(subj);
  730. break;
  731. case '<':
  732. new = handle_pointy_brace(subj);
  733. break;
  734. case '_':
  735. new = handle_strong_emph(subj, '_', last);
  736. break;
  737. case '*':
  738. new = handle_strong_emph(subj, '*', last);
  739. break;
  740. case '[':
  741. new = handle_left_bracket(subj);
  742. break;
  743. case '!':
  744. advance(subj);
  745. if (peek_char(subj) == '[') {
  746. new = handle_left_bracket(subj);
  747. if (new != NULL && new->tag == INL_LINK) {
  748. new->tag = INL_IMAGE;
  749. } else {
  750. new = append_inlines(make_str(chunk_literal("!")), new);
  751. }
  752. } else {
  753. new = make_str(chunk_literal("!"));
  754. }
  755. break;
  756. default:
  757. endpos = subject_find_special_char(subj);
  758. contents = chunk_dup(&subj->input, subj->pos, endpos - subj->pos);
  759. subj->pos = endpos;
  760. // if we're at a newline, strip trailing spaces.
  761. if (peek_char(subj) == '\n') {
  762. chunk_rtrim(&contents);
  763. }
  764. new = make_str(contents);
  765. }
  766. if (*last == NULL) {
  767. *last = new;
  768. } else if (new) {
  769. append_inlines(*last, new);
  770. *last = new;
  771. }
  772. return 1;
  773. }
  774. extern node_inl* parse_inlines(strbuf *input, reference_map *refmap)
  775. {
  776. subject subj;
  777. subject_from_buf(&subj, input, refmap);
  778. return parse_inlines_while(&subj, not_eof);
  779. }
  780. // Parse zero or more space characters, including at most one newline.
  781. void spnl(subject* subj)
  782. {
  783. bool seen_newline = false;
  784. while (peek_char(subj) == ' ' ||
  785. (!seen_newline &&
  786. (seen_newline = peek_char(subj) == '\n'))) {
  787. advance(subj);
  788. }
  789. }
  790. // Parse reference. Assumes string begins with '[' character.
  791. // Modify refmap if a reference is encountered.
  792. // Return 0 if no reference found, otherwise position of subject
  793. // after reference is parsed.
  794. int parse_reference_inline(strbuf *input, reference_map *refmap)
  795. {
  796. subject subj;
  797. chunk lab;
  798. chunk url;
  799. chunk title;
  800. int matchlen = 0;
  801. int beforetitle;
  802. subject_from_buf(&subj, input, NULL);
  803. // parse label:
  804. if (!link_label(&subj, &lab))
  805. return 0;
  806. // colon:
  807. if (peek_char(&subj) == ':') {
  808. advance(&subj);
  809. } else {
  810. return 0;
  811. }
  812. // parse link url:
  813. spnl(&subj);
  814. matchlen = scan_link_url(&subj.input, subj.pos);
  815. if (matchlen) {
  816. url = chunk_dup(&subj.input, subj.pos, matchlen);
  817. subj.pos += matchlen;
  818. } else {
  819. return 0;
  820. }
  821. // parse optional link_title
  822. beforetitle = subj.pos;
  823. spnl(&subj);
  824. matchlen = scan_link_title(&subj.input, subj.pos);
  825. if (matchlen) {
  826. title = chunk_dup(&subj.input, subj.pos, matchlen);
  827. subj.pos += matchlen;
  828. } else {
  829. subj.pos = beforetitle;
  830. title = chunk_literal("");
  831. }
  832. // parse final spaces and newline:
  833. while (peek_char(&subj) == ' ') {
  834. advance(&subj);
  835. }
  836. if (peek_char(&subj) == '\n') {
  837. advance(&subj);
  838. } else if (peek_char(&subj) != 0) {
  839. return 0;
  840. }
  841. // insert reference into refmap
  842. reference_create(refmap, &lab, &url, &title);
  843. return subj.pos;
  844. }