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