aboutsummaryrefslogtreecommitdiff
path: root/src/inlines.c
blob: e08b757504b3c2e3c0cf507a46abaa9db4fab1af (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. while (tmp->next != NULL && tmp->next != closer->first_inline) {
  381. tmp->parent = emph;
  382. tmp = tmp->next;
  383. }
  384. tmp->parent = emph;
  385. if (tmp->next) {
  386. tmp->next->prev = emph;
  387. }
  388. tmp->next = NULL;
  389. emph->last_child = tmp;
  390. // if closer has 0 delims, remove it and its associated inline
  391. if (closer->delim_count == 0) {
  392. // remove empty closer inline
  393. tmp = closer->first_inline;
  394. emph->next = tmp->next;
  395. if (tmp->next) {
  396. tmp->next->prev = emph;
  397. }
  398. cmark_node_free(tmp);
  399. // remove closer from stack
  400. tempstack = closer->next;
  401. remove_delimiter(subj, closer);
  402. closer = tempstack;
  403. }
  404. } else {
  405. closer = closer->next;
  406. }
  407. } else {
  408. closer = closer->next;
  409. }
  410. }
  411. // free all delimiters in stack down to stack_bottom:
  412. while (subj->delimiters != stack_bottom) {
  413. remove_delimiter(subj, subj->delimiters);
  414. }
  415. }
  416. // Parse backslash-escape or just a backslash, returning an inline.
  417. static cmark_node* handle_backslash(subject *subj)
  418. {
  419. advance(subj);
  420. unsigned char nextchar = peek_char(subj);
  421. if (ispunct(nextchar)) { // only ascii symbols and newline can be escaped
  422. advance(subj);
  423. return make_str(chunk_dup(&subj->input, subj->pos - 1, 1));
  424. } else if (nextchar == '\n') {
  425. advance(subj);
  426. return make_linebreak();
  427. } else {
  428. return make_str(chunk_literal("\\"));
  429. }
  430. }
  431. // Parse an entity or a regular "&" string.
  432. // Assumes the subject has an '&' character at the current position.
  433. static cmark_node* handle_entity(subject* subj)
  434. {
  435. strbuf ent = GH_BUF_INIT;
  436. size_t len;
  437. advance(subj);
  438. len = houdini_unescape_ent(&ent,
  439. subj->input.data + subj->pos,
  440. subj->input.len - subj->pos
  441. );
  442. if (len == 0)
  443. return make_str(chunk_literal("&"));
  444. subj->pos += len;
  445. return make_str(chunk_buf_detach(&ent));
  446. }
  447. // Like make_str, but parses entities.
  448. // Returns an inline sequence consisting of str and entity elements.
  449. static cmark_node *make_str_with_entities(chunk *content)
  450. {
  451. strbuf unescaped = GH_BUF_INIT;
  452. if (houdini_unescape_html(&unescaped, content->data, (size_t)content->len)) {
  453. return make_str(chunk_buf_detach(&unescaped));
  454. } else {
  455. return make_str(*content);
  456. }
  457. }
  458. // Clean a URL: remove surrounding whitespace and surrounding <>,
  459. // and remove \ that escape punctuation.
  460. unsigned char *cmark_clean_url(chunk *url)
  461. {
  462. strbuf buf = GH_BUF_INIT;
  463. chunk_trim(url);
  464. if (url->len == 0)
  465. return NULL;
  466. if (url->data[0] == '<' && url->data[url->len - 1] == '>') {
  467. houdini_unescape_html_f(&buf, url->data + 1, url->len - 2);
  468. } else {
  469. houdini_unescape_html_f(&buf, url->data, url->len);
  470. }
  471. strbuf_unescape(&buf);
  472. return strbuf_detach(&buf);
  473. }
  474. unsigned char *cmark_clean_title(chunk *title)
  475. {
  476. strbuf buf = GH_BUF_INIT;
  477. unsigned char first, last;
  478. if (title->len == 0)
  479. return NULL;
  480. first = title->data[0];
  481. last = title->data[title->len - 1];
  482. // remove surrounding quotes if any:
  483. if ((first == '\'' && last == '\'') ||
  484. (first == '(' && last == ')') ||
  485. (first == '"' && last == '"')) {
  486. houdini_unescape_html_f(&buf, title->data + 1, title->len - 2);
  487. } else {
  488. houdini_unescape_html_f(&buf, title->data, title->len);
  489. }
  490. strbuf_unescape(&buf);
  491. return strbuf_detach(&buf);
  492. }
  493. // Parse an autolink or HTML tag.
  494. // Assumes the subject has a '<' character at the current position.
  495. static cmark_node* handle_pointy_brace(subject* subj)
  496. {
  497. int matchlen = 0;
  498. chunk contents;
  499. advance(subj); // advance past first <
  500. // first try to match a URL autolink
  501. matchlen = scan_autolink_uri(&subj->input, subj->pos);
  502. if (matchlen > 0) {
  503. contents = chunk_dup(&subj->input, subj->pos, matchlen - 1);
  504. subj->pos += matchlen;
  505. return make_autolink(
  506. make_str_with_entities(&contents),
  507. contents, 0
  508. );
  509. }
  510. // next try to match an email autolink
  511. matchlen = scan_autolink_email(&subj->input, subj->pos);
  512. if (matchlen > 0) {
  513. contents = chunk_dup(&subj->input, subj->pos, matchlen - 1);
  514. subj->pos += matchlen;
  515. return make_autolink(
  516. make_str_with_entities(&contents),
  517. contents, 1
  518. );
  519. }
  520. // finally, try to match an html tag
  521. matchlen = scan_html_tag(&subj->input, subj->pos);
  522. if (matchlen > 0) {
  523. contents = chunk_dup(&subj->input, subj->pos - 1, matchlen + 1);
  524. subj->pos += matchlen;
  525. return make_raw_html(contents);
  526. }
  527. // if nothing matches, just return the opening <:
  528. return make_str(chunk_literal("<"));
  529. }
  530. // Parse a link label. Returns 1 if successful.
  531. // Note: unescaped brackets are not allowed in labels.
  532. // The label begins with `[` and ends with the first `]` character
  533. // encountered. Backticks in labels do not start code spans.
  534. static int link_label(subject* subj, chunk *raw_label)
  535. {
  536. int startpos = subj->pos;
  537. int length = 0;
  538. advance(subj); // advance past [
  539. unsigned char c;
  540. while ((c = peek_char(subj)) && c != '[' && c != ']') {
  541. if (c == '\\') {
  542. advance(subj);
  543. length++;
  544. if (ispunct(peek_char(subj))) {
  545. advance(subj);
  546. length++;
  547. }
  548. } else {
  549. advance(subj);
  550. length++;
  551. }
  552. if (length > MAX_LINK_LABEL_LENGTH) {
  553. goto noMatch;
  554. }
  555. }
  556. if (c == ']') { // match found
  557. *raw_label = chunk_dup(&subj->input, startpos + 1, subj->pos - (startpos + 1));
  558. advance(subj); // advance past ]
  559. return 1;
  560. }
  561. noMatch:
  562. subj->pos = startpos; // rewind
  563. return 0;
  564. }
  565. // Return a link, an image, or a literal close bracket.
  566. static cmark_node* handle_close_bracket(subject* subj, cmark_node *parent)
  567. {
  568. int initial_pos;
  569. int starturl, endurl, starttitle, endtitle, endall;
  570. int n;
  571. int sps;
  572. cmark_reference *ref;
  573. bool is_image = false;
  574. chunk urlchunk, titlechunk;
  575. unsigned char *url, *title;
  576. delimiter_stack *opener;
  577. delimiter_stack *tempstack;
  578. cmark_node *link_text;
  579. cmark_node *inl;
  580. chunk raw_label;
  581. int found_label;
  582. advance(subj); // advance past ]
  583. initial_pos = subj->pos;
  584. // look through stack of delimiters for a [ or !
  585. opener = subj->delimiters;
  586. while (opener) {
  587. if (opener->delim_char == '[' || opener->delim_char == '!') {
  588. break;
  589. }
  590. opener = opener->previous;
  591. }
  592. if (opener == NULL) {
  593. return make_str(chunk_literal("]"));
  594. }
  595. // If we got here, we matched a potential link/image text.
  596. is_image = opener->delim_char == '!';
  597. link_text = opener->first_inline->next;
  598. // Now we check to see if it's a link/image.
  599. // First, look for an inline link.
  600. if (peek_char(subj) == '(' &&
  601. ((sps = scan_spacechars(&subj->input, subj->pos + 1)) > -1) &&
  602. ((n = scan_link_url(&subj->input, subj->pos + 1 + sps)) > -1)) {
  603. // try to parse an explicit link:
  604. starturl = subj->pos + 1 + sps; // after (
  605. endurl = starturl + n;
  606. starttitle = endurl + scan_spacechars(&subj->input, endurl);
  607. // ensure there are spaces btw url and title
  608. endtitle = (starttitle == endurl) ? starttitle :
  609. starttitle + scan_link_title(&subj->input, starttitle);
  610. endall = endtitle + scan_spacechars(&subj->input, endtitle);
  611. if (peek_at(subj, endall) == ')') {
  612. subj->pos = endall + 1;
  613. urlchunk = chunk_dup(&subj->input, starturl, endurl - starturl);
  614. titlechunk = chunk_dup(&subj->input, starttitle, endtitle - starttitle);
  615. url = cmark_clean_url(&urlchunk);
  616. title = cmark_clean_title(&titlechunk);
  617. chunk_free(&urlchunk);
  618. chunk_free(&titlechunk);
  619. goto match;
  620. } else {
  621. goto noMatch;
  622. }
  623. }
  624. // Next, look for a following [link label] that matches in refmap.
  625. // skip spaces
  626. subj->pos = subj->pos + scan_spacechars(&subj->input, subj->pos);
  627. raw_label = chunk_literal("");
  628. found_label = link_label(subj, &raw_label);
  629. if (!found_label || raw_label.len == 0) {
  630. chunk_free(&raw_label);
  631. raw_label = chunk_dup(&subj->input, opener->position,
  632. initial_pos - opener->position - 1);
  633. }
  634. if (!found_label) {
  635. // If we have a shortcut reference link, back up
  636. // to before the spacse we skipped.
  637. subj->pos = initial_pos;
  638. }
  639. ref = cmark_reference_lookup(subj->refmap, &raw_label);
  640. chunk_free(&raw_label);
  641. if (ref != NULL) { // found
  642. url = bufdup(ref->url);
  643. title = bufdup(ref->title);
  644. goto match;
  645. } else {
  646. goto noMatch;
  647. }
  648. noMatch:
  649. // If we fall through to here, it means we didn't match a link:
  650. remove_delimiter(subj, opener); // remove this opener from delimiter stack
  651. subj->pos = initial_pos;
  652. return make_str(chunk_literal("]"));
  653. match:
  654. inl = opener->first_inline;
  655. inl->type = is_image ? NODE_IMAGE : NODE_LINK;
  656. chunk_free(&inl->as.literal);
  657. inl->first_child = link_text;
  658. process_emphasis(subj, opener->previous);
  659. inl->as.link.url = url;
  660. inl->as.link.title = title;
  661. inl->next = NULL;
  662. if (link_text) {
  663. cmark_node *tmp;
  664. link_text->prev = NULL;
  665. for (tmp = link_text; tmp->next != NULL; tmp = tmp->next) {
  666. tmp->parent = inl;
  667. }
  668. tmp->parent = inl;
  669. inl->last_child = tmp;
  670. }
  671. parent->last_child = inl;
  672. // process_emphasis will remove this delimiter and all later ones.
  673. // Now, if we have a link, we also want to remove earlier link
  674. // delimiters. (This code can be removed if we decide to allow links
  675. // inside links.)
  676. if (!is_image) {
  677. opener = subj->delimiters;
  678. while (opener != NULL) {
  679. tempstack = opener->previous;
  680. if (opener->delim_char == '[') {
  681. remove_delimiter(subj, opener);
  682. }
  683. opener = tempstack;
  684. }
  685. }
  686. return NULL;
  687. }
  688. // Parse a hard or soft linebreak, returning an inline.
  689. // Assumes the subject has a newline at the current position.
  690. static cmark_node* handle_newline(subject *subj)
  691. {
  692. int nlpos = subj->pos;
  693. // skip over newline
  694. advance(subj);
  695. // skip spaces at beginning of line
  696. while (peek_char(subj) == ' ') {
  697. advance(subj);
  698. }
  699. if (nlpos > 1 &&
  700. peek_at(subj, nlpos - 1) == ' ' &&
  701. peek_at(subj, nlpos - 2) == ' ') {
  702. return make_linebreak();
  703. } else {
  704. return make_softbreak();
  705. }
  706. }
  707. static int subject_find_special_char(subject *subj)
  708. {
  709. // "\n\\`&_*[]<!"
  710. static const int8_t SPECIAL_CHARS[256] = {
  711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
  712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  713. 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0,
  714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
  715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1,
  717. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  718. 0, 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. int n = subj->pos + 1;
  728. while (n < subj->input.len) {
  729. if (SPECIAL_CHARS[subj->input.data[n]])
  730. return n;
  731. n++;
  732. }
  733. return subj->input.len;
  734. }
  735. // Parse an inline, advancing subject, and add it as a child of parent.
  736. // Return 0 if no inline can be parsed, 1 otherwise.
  737. static int parse_inline(subject* subj, cmark_node * parent)
  738. {
  739. cmark_node* new_inl = NULL;
  740. chunk contents;
  741. unsigned char c;
  742. int endpos;
  743. c = peek_char(subj);
  744. if (c == 0) {
  745. return 0;
  746. }
  747. switch(c){
  748. case '\n':
  749. new_inl = handle_newline(subj);
  750. break;
  751. case '`':
  752. new_inl = handle_backticks(subj);
  753. break;
  754. case '\\':
  755. new_inl = handle_backslash(subj);
  756. break;
  757. case '&':
  758. new_inl = handle_entity(subj);
  759. break;
  760. case '<':
  761. new_inl = handle_pointy_brace(subj);
  762. break;
  763. case '*':
  764. case '_':
  765. new_inl = handle_strong_emph(subj, c);
  766. break;
  767. case '[':
  768. advance(subj);
  769. new_inl = make_str(chunk_literal("["));
  770. subj->delimiters = push_delimiter(subj, 1, '[', true, false, new_inl);
  771. break;
  772. case ']':
  773. new_inl = handle_close_bracket(subj, parent);
  774. break;
  775. case '!':
  776. advance(subj);
  777. if (peek_char(subj) == '[') {
  778. advance(subj);
  779. new_inl = make_str(chunk_literal("!["));
  780. subj->delimiters = push_delimiter(subj, 1, '!', false, true, new_inl);
  781. } else {
  782. new_inl = make_str(chunk_literal("!"));
  783. }
  784. break;
  785. default:
  786. endpos = subject_find_special_char(subj);
  787. contents = chunk_dup(&subj->input, subj->pos, endpos - subj->pos);
  788. subj->pos = endpos;
  789. // if we're at a newline, strip trailing spaces.
  790. if (peek_char(subj) == '\n') {
  791. chunk_rtrim(&contents);
  792. }
  793. new_inl = make_str(contents);
  794. }
  795. if (new_inl != NULL) {
  796. cmark_node_append_child(parent, new_inl);
  797. }
  798. return 1;
  799. }
  800. // Parse inlines from parent's string_content, adding as children of parent.
  801. extern void cmark_parse_inlines(cmark_node* parent, cmark_reference_map *refmap)
  802. {
  803. subject subj;
  804. subject_from_buf(&subj, &parent->string_content, refmap);
  805. while (!is_eof(&subj) && parse_inline(&subj, parent)) ;
  806. process_emphasis(&subj, NULL);
  807. }
  808. // Parse zero or more space characters, including at most one newline.
  809. static void spnl(subject* subj)
  810. {
  811. bool seen_newline = false;
  812. while (peek_char(subj) == ' ' ||
  813. (!seen_newline &&
  814. (seen_newline = peek_char(subj) == '\n'))) {
  815. advance(subj);
  816. }
  817. }
  818. // Parse reference. Assumes string begins with '[' character.
  819. // Modify refmap if a reference is encountered.
  820. // Return 0 if no reference found, otherwise position of subject
  821. // after reference is parsed.
  822. int cmark_parse_reference_inline(strbuf *input, cmark_reference_map *refmap)
  823. {
  824. subject subj;
  825. chunk lab;
  826. chunk url;
  827. chunk title;
  828. int matchlen = 0;
  829. int beforetitle;
  830. subject_from_buf(&subj, input, NULL);
  831. // parse label:
  832. if (!link_label(&subj, &lab))
  833. return 0;
  834. // colon:
  835. if (peek_char(&subj) == ':') {
  836. advance(&subj);
  837. } else {
  838. return 0;
  839. }
  840. // parse link url:
  841. spnl(&subj);
  842. matchlen = scan_link_url(&subj.input, subj.pos);
  843. if (matchlen) {
  844. url = chunk_dup(&subj.input, subj.pos, matchlen);
  845. subj.pos += matchlen;
  846. } else {
  847. return 0;
  848. }
  849. // parse optional link_title
  850. beforetitle = subj.pos;
  851. spnl(&subj);
  852. matchlen = scan_link_title(&subj.input, subj.pos);
  853. if (matchlen) {
  854. title = chunk_dup(&subj.input, subj.pos, matchlen);
  855. subj.pos += matchlen;
  856. } else {
  857. subj.pos = beforetitle;
  858. title = chunk_literal("");
  859. }
  860. // parse final spaces and newline:
  861. while (peek_char(&subj) == ' ') {
  862. advance(&subj);
  863. }
  864. if (peek_char(&subj) == '\n') {
  865. advance(&subj);
  866. } else if (peek_char(&subj) != 0) {
  867. return 0;
  868. }
  869. // insert reference into refmap
  870. cmark_reference_create(refmap, &lab, &url, &title);
  871. return subj.pos;
  872. }