aboutsummaryrefslogtreecommitdiff
path: root/src/inlines.c
blob: 928a3ac33fba957f8deaf406c183516b96ce924d (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 number_of_emphasis_openers;
  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->number_of_emphasis_openers = 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->number_of_emphasis_openers = 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->number_of_emphasis_openers--;
  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->number_of_emphasis_openers < EMPHASIS_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->number_of_emphasis_openers++;
  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)) && (c != ']' || nestlevel > 0)) {
  510. switch (c) {
  511. case '`':
  512. tmp = handle_backticks(subj);
  513. free_inlines(tmp);
  514. break;
  515. case '<':
  516. tmp = handle_pointy_brace(subj);
  517. free_inlines(tmp);
  518. break;
  519. case '[': // nested []
  520. nestlevel++;
  521. advance(subj);
  522. break;
  523. case ']': // nested []
  524. nestlevel--;
  525. advance(subj);
  526. break;
  527. case '\\':
  528. advance(subj);
  529. if (ispunct(peek_char(subj))) {
  530. advance(subj);
  531. }
  532. break;
  533. default:
  534. advance(subj);
  535. }
  536. }
  537. if (c == ']') {
  538. *raw_label = chunk_dup(&subj->input, startpos + 1, subj->pos - (startpos + 1));
  539. subj->label_nestlevel = 0;
  540. advance(subj); // advance past ]
  541. return 1;
  542. } else {
  543. if (c == 0) {
  544. subj->label_nestlevel = nestlevel;
  545. }
  546. subj->pos = startpos; // rewind
  547. return 0;
  548. }
  549. }
  550. // Parse a link or the link portion of an image, or return a fallback.
  551. static node_inl* handle_left_bracket(subject* subj)
  552. {
  553. node_inl *lab = NULL;
  554. node_inl *result = NULL;
  555. reference *ref;
  556. int n;
  557. int sps;
  558. int found_label;
  559. int endlabel, starturl, endurl, starttitle, endtitle, endall;
  560. chunk rawlabel;
  561. chunk url, title;
  562. found_label = link_label(subj, &rawlabel);
  563. endlabel = subj->pos;
  564. if (found_label) {
  565. if (peek_char(subj) == '(' &&
  566. ((sps = scan_spacechars(&subj->input, subj->pos + 1)) > -1) &&
  567. ((n = scan_link_url(&subj->input, subj->pos + 1 + sps)) > -1)) {
  568. // try to parse an explicit link:
  569. starturl = subj->pos + 1 + sps; // after (
  570. endurl = starturl + n;
  571. starttitle = endurl + scan_spacechars(&subj->input, endurl);
  572. // ensure there are spaces btw url and title
  573. endtitle = (starttitle == endurl) ? starttitle :
  574. starttitle + scan_link_title(&subj->input, starttitle);
  575. endall = endtitle + scan_spacechars(&subj->input, endtitle);
  576. if (peek_at(subj, endall) == ')') {
  577. subj->pos = endall + 1;
  578. url = chunk_dup(&subj->input, starturl, endurl - starturl);
  579. title = chunk_dup(&subj->input, starttitle, endtitle - starttitle);
  580. lab = parse_chunk_inlines(&rawlabel, NULL);
  581. return make_link(lab, url, title);
  582. } else {
  583. // if we get here, we matched a label but didn't get further:
  584. subj->pos = endlabel;
  585. lab = parse_chunk_inlines(&rawlabel, subj->refmap);
  586. result = append_inlines(make_str(chunk_literal("[")),
  587. append_inlines(lab,
  588. make_str(chunk_literal("]"))));
  589. return result;
  590. }
  591. } else {
  592. chunk rawlabel_tmp;
  593. chunk reflabel;
  594. // Check for reference link.
  595. // First, see if there's another label:
  596. subj->pos = subj->pos + scan_spacechars(&subj->input, endlabel);
  597. reflabel = rawlabel;
  598. // if followed by a nonempty link label, we change reflabel to it:
  599. if (peek_char(subj) == '[' && link_label(subj, &rawlabel_tmp)) {
  600. if (rawlabel_tmp.len > 0)
  601. reflabel = rawlabel_tmp;
  602. } else {
  603. subj->pos = endlabel;
  604. }
  605. // lookup rawlabel in subject->reference_map:
  606. ref = reference_lookup(subj->refmap, &reflabel);
  607. if (ref != NULL) { // found
  608. lab = parse_chunk_inlines(&rawlabel, NULL);
  609. result = make_ref_link(lab, ref);
  610. } else {
  611. subj->pos = endlabel;
  612. lab = parse_chunk_inlines(&rawlabel, subj->refmap);
  613. result = append_inlines(make_str(chunk_literal("[")),
  614. append_inlines(lab, make_str(chunk_literal("]"))));
  615. }
  616. return result;
  617. }
  618. }
  619. // If we fall through to here, it means we didn't match a link:
  620. advance(subj); // advance past [
  621. return make_str(chunk_literal("["));
  622. }
  623. // Parse a hard or soft linebreak, returning an inline.
  624. // Assumes the subject has a newline at the current position.
  625. static node_inl* handle_newline(subject *subj)
  626. {
  627. int nlpos = subj->pos;
  628. // skip over newline
  629. advance(subj);
  630. // skip spaces at beginning of line
  631. while (peek_char(subj) == ' ') {
  632. advance(subj);
  633. }
  634. if (nlpos > 1 &&
  635. peek_at(subj, nlpos - 1) == ' ' &&
  636. peek_at(subj, nlpos - 2) == ' ') {
  637. return make_linebreak();
  638. } else {
  639. return make_softbreak();
  640. }
  641. }
  642. inline static int not_eof(subject* subj)
  643. {
  644. return !is_eof(subj);
  645. }
  646. // Parse inlines while a predicate is satisfied. Return inlines.
  647. extern node_inl* parse_inlines_while(subject* subj, int (*f)(subject*))
  648. {
  649. node_inl* result = NULL;
  650. node_inl** last = &result;
  651. node_inl* first = NULL;
  652. while ((*f)(subj) && parse_inline(subj, last)) {
  653. if (!first) {
  654. first = *last;
  655. }
  656. }
  657. inline_stack* istack = subj->emphasis_openers;
  658. inline_stack* temp;
  659. while (istack != NULL) {
  660. temp = istack->previous;
  661. free(istack);
  662. istack = temp;
  663. }
  664. return first;
  665. }
  666. node_inl *parse_chunk_inlines(chunk *chunk, reference_map *refmap)
  667. {
  668. subject subj;
  669. subject_from_chunk(&subj, chunk, refmap);
  670. return parse_inlines_while(&subj, not_eof);
  671. }
  672. static int subject_find_special_char(subject *subj)
  673. {
  674. // "\n\\`&_*[]<!"
  675. static const int8_t SPECIAL_CHARS[256] = {
  676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
  677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  678. 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0,
  679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
  680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1,
  682. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  683. 0, 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. int n = subj->pos + 1;
  693. while (n < subj->input.len) {
  694. if (SPECIAL_CHARS[subj->input.data[n]])
  695. return n;
  696. n++;
  697. }
  698. return subj->input.len;
  699. }
  700. // Parse an inline, advancing subject, and add it to last element.
  701. // Adjust tail to point to new last element of list.
  702. // Return 0 if no inline can be parsed, 1 otherwise.
  703. static int parse_inline(subject* subj, node_inl ** last)
  704. {
  705. node_inl* new = NULL;
  706. chunk contents;
  707. unsigned char c;
  708. int endpos;
  709. c = peek_char(subj);
  710. if (c == 0) {
  711. return 0;
  712. }
  713. switch(c){
  714. case '\n':
  715. new = handle_newline(subj);
  716. break;
  717. case '`':
  718. new = handle_backticks(subj);
  719. break;
  720. case '\\':
  721. new = handle_backslash(subj);
  722. break;
  723. case '&':
  724. new = handle_entity(subj);
  725. break;
  726. case '<':
  727. new = handle_pointy_brace(subj);
  728. break;
  729. case '_':
  730. new = handle_strong_emph(subj, '_', last);
  731. break;
  732. case '*':
  733. new = handle_strong_emph(subj, '*', last);
  734. break;
  735. case '[':
  736. new = handle_left_bracket(subj);
  737. break;
  738. case '!':
  739. advance(subj);
  740. if (peek_char(subj) == '[') {
  741. new = handle_left_bracket(subj);
  742. if (new != NULL && new->tag == INL_LINK) {
  743. new->tag = INL_IMAGE;
  744. } else {
  745. new = append_inlines(make_str(chunk_literal("!")), new);
  746. }
  747. } else {
  748. new = make_str(chunk_literal("!"));
  749. }
  750. break;
  751. default:
  752. endpos = subject_find_special_char(subj);
  753. contents = chunk_dup(&subj->input, subj->pos, endpos - subj->pos);
  754. subj->pos = endpos;
  755. // if we're at a newline, strip trailing spaces.
  756. if (peek_char(subj) == '\n') {
  757. chunk_rtrim(&contents);
  758. }
  759. new = make_str(contents);
  760. }
  761. if (*last == NULL) {
  762. *last = new;
  763. } else if (new) {
  764. append_inlines(*last, new);
  765. *last = new;
  766. }
  767. return 1;
  768. }
  769. extern node_inl* parse_inlines(strbuf *input, reference_map *refmap)
  770. {
  771. subject subj;
  772. subject_from_buf(&subj, input, refmap);
  773. return parse_inlines_while(&subj, not_eof);
  774. }
  775. // Parse zero or more space characters, including at most one newline.
  776. void spnl(subject* subj)
  777. {
  778. bool seen_newline = false;
  779. while (peek_char(subj) == ' ' ||
  780. (!seen_newline &&
  781. (seen_newline = peek_char(subj) == '\n'))) {
  782. advance(subj);
  783. }
  784. }
  785. // Parse reference. Assumes string begins with '[' character.
  786. // Modify refmap if a reference is encountered.
  787. // Return 0 if no reference found, otherwise position of subject
  788. // after reference is parsed.
  789. int parse_reference_inline(strbuf *input, reference_map *refmap)
  790. {
  791. subject subj;
  792. chunk lab;
  793. chunk url;
  794. chunk title;
  795. int matchlen = 0;
  796. int beforetitle;
  797. subject_from_buf(&subj, input, NULL);
  798. // parse label:
  799. if (!link_label(&subj, &lab))
  800. return 0;
  801. // colon:
  802. if (peek_char(&subj) == ':') {
  803. advance(&subj);
  804. } else {
  805. return 0;
  806. }
  807. // parse link url:
  808. spnl(&subj);
  809. matchlen = scan_link_url(&subj.input, subj.pos);
  810. if (matchlen) {
  811. url = chunk_dup(&subj.input, subj.pos, matchlen);
  812. subj.pos += matchlen;
  813. } else {
  814. return 0;
  815. }
  816. // parse optional link_title
  817. beforetitle = subj.pos;
  818. spnl(&subj);
  819. matchlen = scan_link_title(&subj.input, subj.pos);
  820. if (matchlen) {
  821. title = chunk_dup(&subj.input, subj.pos, matchlen);
  822. subj.pos += matchlen;
  823. } else {
  824. subj.pos = beforetitle;
  825. title = chunk_literal("");
  826. }
  827. // parse final spaces and newline:
  828. while (peek_char(&subj) == ' ') {
  829. advance(&subj);
  830. }
  831. if (peek_char(&subj) == '\n') {
  832. advance(&subj);
  833. } else if (peek_char(&subj) != 0) {
  834. return 0;
  835. }
  836. // insert reference into refmap
  837. reference_create(refmap, &lab, &url, &title);
  838. return subj.pos;
  839. }