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