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