aboutsummaryrefslogtreecommitdiff
path: root/src/inlines.c
blob: 872a9c3b8717380c6aca74bc3a4cb2ac1852a889 (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. // walk back to the beginning of the UTF_8 sequence:
  221. while (peek_at(subj, before_char_pos) >> 6 == 2 &&
  222. before_char_pos > 0) {
  223. before_char_pos -= 1;
  224. }
  225. len = utf8proc_iterate(subj->input.data + before_char_pos,
  226. subj->pos - before_char_pos, &before_char);
  227. if (len == 0) {
  228. before_char = 10;
  229. }
  230. }
  231. while (peek_char(subj) == c) {
  232. numdelims++;
  233. advance(subj);
  234. }
  235. len = utf8proc_iterate(subj->input.data + subj->pos,
  236. subj->input.len - subj->pos, &after_char);
  237. if (len == 0) {
  238. after_char = 10;
  239. }
  240. *can_open = numdelims > 0 && !utf8proc_is_space(after_char);
  241. *can_close = numdelims > 0 && !utf8proc_is_space(before_char);
  242. if (c == '_') {
  243. *can_open = *can_open &&
  244. !(before_char < 128 && isalnum((char)before_char));
  245. *can_close = *can_close &&
  246. !(before_char < 128 && isalnum((char)after_char));
  247. }
  248. return numdelims;
  249. }
  250. /*
  251. static void print_delimiters(subject *subj)
  252. {
  253. delimiter *delim;
  254. delim = subj->last_delim;
  255. while (delim != NULL) {
  256. printf("Item at %p: %d %d %d next(%p) prev(%p)\n",
  257. delim, delim->delim_char,
  258. delim->can_open, delim->can_close,
  259. delim->next, delim->previous);
  260. delim = delim->previous;
  261. }
  262. }
  263. */
  264. static void remove_delimiter(subject *subj, delimiter *delim)
  265. {
  266. if (delim == NULL) return;
  267. if (delim->next == NULL) {
  268. // end of list:
  269. assert(delim == subj->last_delim);
  270. subj->last_delim = delim->previous;
  271. } else {
  272. delim->next->previous = delim->previous;
  273. }
  274. if (delim->previous != NULL) {
  275. delim->previous->next = delim->next;
  276. }
  277. free(delim);
  278. }
  279. static void push_delimiter(subject *subj, unsigned char c, bool can_open,
  280. bool can_close, cmark_node *inl_text)
  281. {
  282. delimiter *delim =
  283. (delimiter*)malloc(sizeof(delimiter));
  284. if (delim == NULL) {
  285. return;
  286. }
  287. delim->delim_char = c;
  288. delim->can_open = can_open;
  289. delim->can_close = can_close;
  290. delim->inl_text = inl_text;
  291. delim->previous = subj->last_delim;
  292. delim->next = NULL;
  293. if (delim->previous != NULL) {
  294. delim->previous->next = delim;
  295. }
  296. delim->position = subj->pos;
  297. subj->last_delim = delim;
  298. }
  299. // Parse strong/emph or a fallback.
  300. // Assumes the subject has '_' or '*' at the current position.
  301. static cmark_node* handle_strong_emph(subject* subj, unsigned char c)
  302. {
  303. int numdelims;
  304. cmark_node * inl_text;
  305. bool can_open, can_close;
  306. numdelims = scan_delims(subj, c, &can_open, &can_close);
  307. inl_text = make_str(chunk_dup(&subj->input, subj->pos - numdelims, numdelims));
  308. if (can_open || can_close) {
  309. push_delimiter(subj, c, can_open, can_close, inl_text);
  310. }
  311. return inl_text;
  312. }
  313. static void process_emphasis(subject *subj, delimiter *start_delim)
  314. {
  315. delimiter *closer = subj->last_delim;
  316. delimiter *opener;
  317. // move back to first relevant delim.
  318. while (closer != NULL && closer->previous != start_delim) {
  319. closer = closer->previous;
  320. }
  321. // now move forward, looking for closers, and handling each
  322. while (closer != NULL) {
  323. if (closer->can_close &&
  324. (closer->delim_char == '*' || closer->delim_char == '_')) {
  325. // Now look backwards for first matching opener:
  326. opener = closer->previous;
  327. while (opener != NULL && opener != start_delim) {
  328. if (opener->delim_char == closer->delim_char &&
  329. opener->can_open) {
  330. break;
  331. }
  332. opener = opener->previous;
  333. }
  334. if (opener != NULL && opener != start_delim) {
  335. closer = S_insert_emph(subj, opener, closer);
  336. } else {
  337. closer = closer->next;
  338. }
  339. } else {
  340. closer = closer->next;
  341. }
  342. }
  343. // free all delimiters in list until start_delim:
  344. while (subj->last_delim != start_delim) {
  345. remove_delimiter(subj, subj->last_delim);
  346. }
  347. }
  348. static delimiter*
  349. S_insert_emph(subject *subj, delimiter *opener, delimiter *closer)
  350. {
  351. delimiter *delim, *tmp_delim;
  352. int use_delims;
  353. cmark_node *opener_inl = opener->inl_text;
  354. cmark_node *closer_inl = closer->inl_text;
  355. int opener_num_chars = opener_inl->as.literal.len;
  356. int closer_num_chars = closer_inl->as.literal.len;
  357. cmark_node *tmp, *emph, *first_child, *last_child;
  358. // calculate the actual number of characters used from this closer
  359. if (closer_num_chars < 3 || opener_num_chars < 3) {
  360. use_delims = closer_num_chars <= opener_num_chars ?
  361. closer_num_chars : opener_num_chars;
  362. } else { // closer and opener both have >= 3 characters
  363. use_delims = closer_num_chars % 2 == 0 ? 2 : 1;
  364. }
  365. // remove used characters from associated inlines.
  366. opener_num_chars -= use_delims;
  367. closer_num_chars -= use_delims;
  368. opener_inl->as.literal.len = opener_num_chars;
  369. closer_inl->as.literal.len = closer_num_chars;
  370. // free delimiters between opener and closer
  371. delim = closer->previous;
  372. while (delim != NULL && delim != opener) {
  373. tmp_delim = delim->previous;
  374. remove_delimiter(subj, delim);
  375. delim = tmp_delim;
  376. }
  377. first_child = opener_inl->next;
  378. last_child = closer_inl->prev;
  379. // if opener has 0 characters, remove it and its associated inline
  380. if (opener_num_chars == 0) {
  381. // replace empty opener inline with emph
  382. chunk_free(&(opener_inl->as.literal));
  383. emph = opener_inl;
  384. emph->type = use_delims == 1 ? NODE_EMPH : NODE_STRONG;
  385. // remove opener from list
  386. remove_delimiter(subj, opener);
  387. }
  388. else {
  389. // create new emph or strong, and splice it in to our inlines
  390. // between the opener and closer
  391. emph = use_delims == 1 ? make_emph() : make_strong();
  392. emph->parent = opener_inl->parent;
  393. emph->prev = opener_inl;
  394. opener_inl->next = emph;
  395. }
  396. // push children below emph
  397. emph->next = closer_inl;
  398. closer_inl->prev = emph;
  399. emph->first_child = first_child;
  400. emph->last_child = last_child;
  401. // fix children pointers
  402. first_child->prev = NULL;
  403. last_child->next = NULL;
  404. for (tmp = first_child; tmp != NULL; tmp = tmp->next) {
  405. tmp->parent = emph;
  406. }
  407. // if closer has 0 characters, remove it and its associated inline
  408. if (closer_num_chars == 0) {
  409. // remove empty closer inline
  410. cmark_node_free(closer_inl);
  411. // remove closer from list
  412. tmp_delim = closer->next;
  413. remove_delimiter(subj, closer);
  414. closer = tmp_delim;
  415. }
  416. return closer;
  417. }
  418. // Parse backslash-escape or just a backslash, returning an inline.
  419. static cmark_node* handle_backslash(subject *subj)
  420. {
  421. advance(subj);
  422. unsigned char nextchar = peek_char(subj);
  423. if (ispunct(nextchar)) { // only ascii symbols and newline can be escaped
  424. advance(subj);
  425. return make_str(chunk_dup(&subj->input, subj->pos - 1, 1));
  426. } else if (nextchar == '\n') {
  427. advance(subj);
  428. return make_linebreak();
  429. } else {
  430. return make_str(chunk_literal("\\"));
  431. }
  432. }
  433. // Parse an entity or a regular "&" string.
  434. // Assumes the subject has an '&' character at the current position.
  435. static cmark_node* handle_entity(subject* subj)
  436. {
  437. strbuf ent = GH_BUF_INIT;
  438. size_t len;
  439. advance(subj);
  440. len = houdini_unescape_ent(&ent,
  441. subj->input.data + subj->pos,
  442. subj->input.len - subj->pos
  443. );
  444. if (len == 0)
  445. return make_str(chunk_literal("&"));
  446. subj->pos += len;
  447. return make_str(chunk_buf_detach(&ent));
  448. }
  449. // Like make_str, but parses entities.
  450. // Returns an inline sequence consisting of str and entity elements.
  451. static cmark_node *make_str_with_entities(chunk *content)
  452. {
  453. strbuf unescaped = GH_BUF_INIT;
  454. if (houdini_unescape_html(&unescaped, content->data, (size_t)content->len)) {
  455. return make_str(chunk_buf_detach(&unescaped));
  456. } else {
  457. return make_str(*content);
  458. }
  459. }
  460. // Clean a URL: remove surrounding whitespace and surrounding <>,
  461. // and remove \ that escape punctuation.
  462. unsigned char *cmark_clean_url(chunk *url)
  463. {
  464. strbuf buf = GH_BUF_INIT;
  465. chunk_trim(url);
  466. if (url->len == 0)
  467. return NULL;
  468. if (url->data[0] == '<' && url->data[url->len - 1] == '>') {
  469. houdini_unescape_html_f(&buf, url->data + 1, url->len - 2);
  470. } else {
  471. houdini_unescape_html_f(&buf, url->data, url->len);
  472. }
  473. strbuf_unescape(&buf);
  474. return strbuf_detach(&buf);
  475. }
  476. unsigned char *cmark_clean_title(chunk *title)
  477. {
  478. strbuf buf = GH_BUF_INIT;
  479. unsigned char first, last;
  480. if (title->len == 0)
  481. return NULL;
  482. first = title->data[0];
  483. last = title->data[title->len - 1];
  484. // remove surrounding quotes if any:
  485. if ((first == '\'' && last == '\'') ||
  486. (first == '(' && last == ')') ||
  487. (first == '"' && last == '"')) {
  488. houdini_unescape_html_f(&buf, title->data + 1, title->len - 2);
  489. } else {
  490. houdini_unescape_html_f(&buf, title->data, title->len);
  491. }
  492. strbuf_unescape(&buf);
  493. return strbuf_detach(&buf);
  494. }
  495. // Parse an autolink or HTML tag.
  496. // Assumes the subject has a '<' character at the current position.
  497. static cmark_node* handle_pointy_brace(subject* subj)
  498. {
  499. int matchlen = 0;
  500. chunk contents;
  501. advance(subj); // advance past first <
  502. // first try to match a URL autolink
  503. matchlen = scan_autolink_uri(&subj->input, subj->pos);
  504. if (matchlen > 0) {
  505. contents = chunk_dup(&subj->input, subj->pos, matchlen - 1);
  506. subj->pos += matchlen;
  507. return make_autolink(
  508. make_str_with_entities(&contents),
  509. contents, 0
  510. );
  511. }
  512. // next try to match an email autolink
  513. matchlen = scan_autolink_email(&subj->input, subj->pos);
  514. if (matchlen > 0) {
  515. contents = chunk_dup(&subj->input, subj->pos, matchlen - 1);
  516. subj->pos += matchlen;
  517. return make_autolink(
  518. make_str_with_entities(&contents),
  519. contents, 1
  520. );
  521. }
  522. // finally, try to match an html tag
  523. matchlen = scan_html_tag(&subj->input, subj->pos);
  524. if (matchlen > 0) {
  525. contents = chunk_dup(&subj->input, subj->pos - 1, matchlen + 1);
  526. subj->pos += matchlen;
  527. return make_raw_html(contents);
  528. }
  529. // if nothing matches, just return the opening <:
  530. return make_str(chunk_literal("<"));
  531. }
  532. // Parse a link label. Returns 1 if successful.
  533. // Note: unescaped brackets are not allowed in labels.
  534. // The label begins with `[` and ends with the first `]` character
  535. // encountered. Backticks in labels do not start code spans.
  536. static int link_label(subject* subj, chunk *raw_label)
  537. {
  538. int startpos = subj->pos;
  539. int length = 0;
  540. unsigned char c;
  541. // advance past [
  542. if (peek_char(subj) == '[') {
  543. advance(subj);
  544. } else {
  545. return 0;
  546. }
  547. while ((c = peek_char(subj)) && c != '[' && c != ']') {
  548. if (c == '\\') {
  549. advance(subj);
  550. length++;
  551. if (ispunct(peek_char(subj))) {
  552. advance(subj);
  553. length++;
  554. }
  555. } else {
  556. advance(subj);
  557. length++;
  558. }
  559. if (length > MAX_LINK_LABEL_LENGTH) {
  560. goto noMatch;
  561. }
  562. }
  563. if (c == ']') { // match found
  564. *raw_label = chunk_dup(&subj->input, startpos + 1, subj->pos - (startpos + 1));
  565. advance(subj); // advance past ]
  566. return 1;
  567. }
  568. noMatch:
  569. subj->pos = startpos; // rewind
  570. return 0;
  571. }
  572. // Return a link, an image, or a literal close bracket.
  573. static cmark_node* handle_close_bracket(subject* subj, cmark_node *parent)
  574. {
  575. int initial_pos;
  576. int starturl, endurl, starttitle, endtitle, endall;
  577. int n;
  578. int sps;
  579. cmark_reference *ref;
  580. bool is_image = false;
  581. chunk urlchunk, titlechunk;
  582. unsigned char *url, *title;
  583. delimiter *opener;
  584. delimiter *tmp_delim;
  585. cmark_node *link_text;
  586. cmark_node *inl;
  587. chunk raw_label;
  588. int found_label;
  589. advance(subj); // advance past ]
  590. initial_pos = subj->pos;
  591. // look through list of delimiters for a [ or !
  592. opener = subj->last_delim;
  593. while (opener) {
  594. if (opener->delim_char == '[' || opener->delim_char == '!') {
  595. break;
  596. }
  597. opener = opener->previous;
  598. }
  599. if (opener == NULL) {
  600. return make_str(chunk_literal("]"));
  601. }
  602. // If we got here, we matched a potential link/image text.
  603. is_image = opener->delim_char == '!';
  604. link_text = opener->inl_text->next;
  605. // Now we check to see if it's a link/image.
  606. // First, look for an inline link.
  607. if (peek_char(subj) == '(' &&
  608. ((sps = scan_spacechars(&subj->input, subj->pos + 1)) > -1) &&
  609. ((n = scan_link_url(&subj->input, subj->pos + 1 + sps)) > -1)) {
  610. // try to parse an explicit link:
  611. starturl = subj->pos + 1 + sps; // after (
  612. endurl = starturl + n;
  613. starttitle = endurl + scan_spacechars(&subj->input, endurl);
  614. // ensure there are spaces btw url and title
  615. endtitle = (starttitle == endurl) ? starttitle :
  616. starttitle + scan_link_title(&subj->input, starttitle);
  617. endall = endtitle + scan_spacechars(&subj->input, endtitle);
  618. if (peek_at(subj, endall) == ')') {
  619. subj->pos = endall + 1;
  620. urlchunk = chunk_dup(&subj->input, starturl, endurl - starturl);
  621. titlechunk = chunk_dup(&subj->input, starttitle, endtitle - starttitle);
  622. url = cmark_clean_url(&urlchunk);
  623. title = cmark_clean_title(&titlechunk);
  624. chunk_free(&urlchunk);
  625. chunk_free(&titlechunk);
  626. goto match;
  627. } else {
  628. goto noMatch;
  629. }
  630. }
  631. // Next, look for a following [link label] that matches in refmap.
  632. // skip spaces
  633. subj->pos = subj->pos + scan_spacechars(&subj->input, subj->pos);
  634. raw_label = chunk_literal("");
  635. found_label = link_label(subj, &raw_label);
  636. if (!found_label || raw_label.len == 0) {
  637. chunk_free(&raw_label);
  638. raw_label = chunk_dup(&subj->input, opener->position,
  639. initial_pos - opener->position - 1);
  640. }
  641. if (!found_label) {
  642. // If we have a shortcut reference link, back up
  643. // to before the spacse we skipped.
  644. subj->pos = initial_pos;
  645. }
  646. ref = cmark_reference_lookup(subj->refmap, &raw_label);
  647. chunk_free(&raw_label);
  648. if (ref != NULL) { // found
  649. url = bufdup(ref->url);
  650. title = bufdup(ref->title);
  651. goto match;
  652. } else {
  653. goto noMatch;
  654. }
  655. noMatch:
  656. // If we fall through to here, it means we didn't match a link:
  657. remove_delimiter(subj, opener); // remove this opener from delimiter list
  658. subj->pos = initial_pos;
  659. return make_str(chunk_literal("]"));
  660. match:
  661. inl = opener->inl_text;
  662. inl->type = is_image ? NODE_IMAGE : NODE_LINK;
  663. chunk_free(&inl->as.literal);
  664. inl->first_child = link_text;
  665. process_emphasis(subj, opener->previous);
  666. inl->as.link.url = url;
  667. inl->as.link.title = title;
  668. inl->next = NULL;
  669. if (link_text) {
  670. cmark_node *tmp;
  671. link_text->prev = NULL;
  672. for (tmp = link_text; tmp->next != NULL; tmp = tmp->next) {
  673. tmp->parent = inl;
  674. }
  675. tmp->parent = inl;
  676. inl->last_child = tmp;
  677. }
  678. parent->last_child = inl;
  679. // process_emphasis will remove this delimiter and all later ones.
  680. // Now, if we have a link, we also want to remove earlier link
  681. // delimiters. (This code can be removed if we decide to allow links
  682. // inside links.)
  683. if (!is_image) {
  684. opener = subj->last_delim;
  685. while (opener != NULL) {
  686. tmp_delim = opener->previous;
  687. if (opener->delim_char == '[') {
  688. remove_delimiter(subj, opener);
  689. }
  690. opener = tmp_delim;
  691. }
  692. }
  693. return NULL;
  694. }
  695. // Parse a hard or soft linebreak, returning an inline.
  696. // Assumes the subject has a newline at the current position.
  697. static cmark_node* handle_newline(subject *subj)
  698. {
  699. int nlpos = subj->pos;
  700. // skip over newline
  701. advance(subj);
  702. // skip spaces at beginning of line
  703. while (peek_char(subj) == ' ') {
  704. advance(subj);
  705. }
  706. if (nlpos > 1 &&
  707. peek_at(subj, nlpos - 1) == ' ' &&
  708. peek_at(subj, nlpos - 2) == ' ') {
  709. return make_linebreak();
  710. } else {
  711. return make_softbreak();
  712. }
  713. }
  714. static int subject_find_special_char(subject *subj)
  715. {
  716. // "\n\\`&_*[]<!"
  717. static const int8_t SPECIAL_CHARS[256] = {
  718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
  719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  720. 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0,
  721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
  722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1,
  724. 1, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
  734. int n = subj->pos + 1;
  735. while (n < subj->input.len) {
  736. if (SPECIAL_CHARS[subj->input.data[n]])
  737. return n;
  738. n++;
  739. }
  740. return subj->input.len;
  741. }
  742. // Parse an inline, advancing subject, and add it as a child of parent.
  743. // Return 0 if no inline can be parsed, 1 otherwise.
  744. static int parse_inline(subject* subj, cmark_node * parent)
  745. {
  746. cmark_node* new_inl = NULL;
  747. chunk contents;
  748. unsigned char c;
  749. int endpos;
  750. c = peek_char(subj);
  751. if (c == 0) {
  752. return 0;
  753. }
  754. switch(c){
  755. case '\n':
  756. new_inl = handle_newline(subj);
  757. break;
  758. case '`':
  759. new_inl = handle_backticks(subj);
  760. break;
  761. case '\\':
  762. new_inl = handle_backslash(subj);
  763. break;
  764. case '&':
  765. new_inl = handle_entity(subj);
  766. break;
  767. case '<':
  768. new_inl = handle_pointy_brace(subj);
  769. break;
  770. case '*':
  771. case '_':
  772. new_inl = handle_strong_emph(subj, c);
  773. break;
  774. case '[':
  775. advance(subj);
  776. new_inl = make_str(chunk_literal("["));
  777. push_delimiter(subj, '[', true, false, new_inl);
  778. break;
  779. case ']':
  780. new_inl = handle_close_bracket(subj, parent);
  781. break;
  782. case '!':
  783. advance(subj);
  784. if (peek_char(subj) == '[') {
  785. advance(subj);
  786. new_inl = make_str(chunk_literal("!["));
  787. push_delimiter(subj, '!', false, true, new_inl);
  788. } else {
  789. new_inl = make_str(chunk_literal("!"));
  790. }
  791. break;
  792. default:
  793. endpos = subject_find_special_char(subj);
  794. contents = chunk_dup(&subj->input, subj->pos, endpos - subj->pos);
  795. subj->pos = endpos;
  796. // if we're at a newline, strip trailing spaces.
  797. if (peek_char(subj) == '\n') {
  798. chunk_rtrim(&contents);
  799. }
  800. new_inl = make_str(contents);
  801. }
  802. if (new_inl != NULL) {
  803. cmark_node_append_child(parent, new_inl);
  804. }
  805. return 1;
  806. }
  807. // Parse inlines from parent's string_content, adding as children of parent.
  808. extern void cmark_parse_inlines(cmark_node* parent, cmark_reference_map *refmap)
  809. {
  810. subject subj;
  811. subject_from_buf(&subj, &parent->string_content, refmap);
  812. while (!is_eof(&subj) && parse_inline(&subj, parent)) ;
  813. process_emphasis(&subj, NULL);
  814. }
  815. // Parse zero or more space characters, including at most one newline.
  816. static void spnl(subject* subj)
  817. {
  818. bool seen_newline = false;
  819. while (peek_char(subj) == ' ' ||
  820. (!seen_newline &&
  821. (seen_newline = peek_char(subj) == '\n'))) {
  822. advance(subj);
  823. }
  824. }
  825. // Parse reference. Assumes string begins with '[' character.
  826. // Modify refmap if a reference is encountered.
  827. // Return 0 if no reference found, otherwise position of subject
  828. // after reference is parsed.
  829. int cmark_parse_reference_inline(strbuf *input, cmark_reference_map *refmap)
  830. {
  831. subject subj;
  832. chunk lab;
  833. chunk url;
  834. chunk title;
  835. int matchlen = 0;
  836. int beforetitle;
  837. subject_from_buf(&subj, input, NULL);
  838. // parse label:
  839. if (!link_label(&subj, &lab))
  840. return 0;
  841. // colon:
  842. if (peek_char(&subj) == ':') {
  843. advance(&subj);
  844. } else {
  845. return 0;
  846. }
  847. // parse link url:
  848. spnl(&subj);
  849. matchlen = scan_link_url(&subj.input, subj.pos);
  850. if (matchlen) {
  851. url = chunk_dup(&subj.input, subj.pos, matchlen);
  852. subj.pos += matchlen;
  853. } else {
  854. return 0;
  855. }
  856. // parse optional link_title
  857. beforetitle = subj.pos;
  858. spnl(&subj);
  859. matchlen = scan_link_title(&subj.input, subj.pos);
  860. if (matchlen) {
  861. title = chunk_dup(&subj.input, subj.pos, matchlen);
  862. subj.pos += matchlen;
  863. } else {
  864. subj.pos = beforetitle;
  865. title = chunk_literal("");
  866. }
  867. // parse final spaces and newline:
  868. while (peek_char(&subj) == ' ') {
  869. advance(&subj);
  870. }
  871. if (peek_char(&subj) == '\n') {
  872. advance(&subj);
  873. } else if (peek_char(&subj) != 0) {
  874. return 0;
  875. }
  876. // insert reference into refmap
  877. cmark_reference_create(refmap, &lab, &url, &title);
  878. return subj.pos;
  879. }