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