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