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