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