aboutsummaryrefslogtreecommitdiff
path: root/src/inlines.c
blob: 37ad768bc0fbbacf6bf703b1dfed36490b756639 (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_STRING, 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. 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 = clean_url(&urlchunk);
  608. title = 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. if (!link_label(subj, &raw_label) || raw_label.len == 0) {
  621. chunk_free(&raw_label);
  622. raw_label = chunk_dup(&subj->input, opener->position,
  623. initial_pos - opener->position - 1);
  624. }
  625. ref = reference_lookup(subj->refmap, &raw_label);
  626. chunk_free(&raw_label);
  627. if (ref != NULL) { // found
  628. url = bufdup(ref->url);
  629. title = bufdup(ref->title);
  630. goto match;
  631. } else {
  632. goto noMatch;
  633. }
  634. noMatch:
  635. // If we fall through to here, it means we didn't match a link:
  636. remove_delimiter(subj, opener); // remove this opener from delimiter stack
  637. subj->pos = initial_pos;
  638. return make_str(chunk_literal("]"));
  639. match:
  640. inl = opener->first_inline;
  641. inl->type = is_image ? NODE_IMAGE : NODE_LINK;
  642. chunk_free(&inl->as.literal);
  643. inl->first_child = link_text;
  644. process_emphasis(subj, opener->previous);
  645. inl->as.link.url = url;
  646. inl->as.link.title = title;
  647. inl->next = NULL;
  648. if (link_text) {
  649. cmark_node *tmp;
  650. link_text->prev = NULL;
  651. for (tmp = link_text; tmp->next != NULL; tmp = tmp->next) {
  652. tmp->parent = inl;
  653. }
  654. tmp->parent = inl;
  655. inl->last_child = tmp;
  656. }
  657. parent->last_child = inl;
  658. // process_emphasis will remove this delimiter and all later ones.
  659. // Now, if we have a link, we also want to remove earlier link
  660. // delimiters. (This code can be removed if we decide to allow links
  661. // inside links.)
  662. if (!is_image) {
  663. opener = subj->delimiters;
  664. while (opener != NULL) {
  665. tempstack = opener->previous;
  666. if (opener->delim_char == '[') {
  667. remove_delimiter(subj, opener);
  668. }
  669. opener = tempstack;
  670. }
  671. }
  672. return NULL;
  673. }
  674. // Parse a hard or soft linebreak, returning an inline.
  675. // Assumes the subject has a newline at the current position.
  676. static cmark_node* handle_newline(subject *subj)
  677. {
  678. int nlpos = subj->pos;
  679. // skip over newline
  680. advance(subj);
  681. // skip spaces at beginning of line
  682. while (peek_char(subj) == ' ') {
  683. advance(subj);
  684. }
  685. if (nlpos > 1 &&
  686. peek_at(subj, nlpos - 1) == ' ' &&
  687. peek_at(subj, nlpos - 2) == ' ') {
  688. return make_linebreak();
  689. } else {
  690. return make_softbreak();
  691. }
  692. }
  693. static int subject_find_special_char(subject *subj)
  694. {
  695. // "\n\\`&_*[]<!"
  696. static const int8_t SPECIAL_CHARS[256] = {
  697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
  698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  699. 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0,
  700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
  701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1,
  703. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  709. 0, 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. int n = subj->pos + 1;
  714. while (n < subj->input.len) {
  715. if (SPECIAL_CHARS[subj->input.data[n]])
  716. return n;
  717. n++;
  718. }
  719. return subj->input.len;
  720. }
  721. // Parse an inline, advancing subject, and add it as a child of parent.
  722. // Return 0 if no inline can be parsed, 1 otherwise.
  723. static int parse_inline(subject* subj, cmark_node * parent)
  724. {
  725. cmark_node* new_inl = NULL;
  726. chunk contents;
  727. unsigned char c;
  728. int endpos;
  729. c = peek_char(subj);
  730. if (c == 0) {
  731. return 0;
  732. }
  733. switch(c){
  734. case '\n':
  735. new_inl = handle_newline(subj);
  736. break;
  737. case '`':
  738. new_inl = handle_backticks(subj);
  739. break;
  740. case '\\':
  741. new_inl = handle_backslash(subj);
  742. break;
  743. case '&':
  744. new_inl = handle_entity(subj);
  745. break;
  746. case '<':
  747. new_inl = handle_pointy_brace(subj);
  748. break;
  749. case '*':
  750. case '_':
  751. new_inl = handle_strong_emph(subj, c);
  752. break;
  753. case '[':
  754. advance(subj);
  755. new_inl = make_str(chunk_literal("["));
  756. subj->delimiters = push_delimiter(subj, 1, '[', true, false, new_inl);
  757. break;
  758. case ']':
  759. new_inl = handle_close_bracket(subj, parent);
  760. break;
  761. case '!':
  762. advance(subj);
  763. if (peek_char(subj) == '[') {
  764. advance(subj);
  765. new_inl = make_str(chunk_literal("!["));
  766. subj->delimiters = push_delimiter(subj, 1, '!', false, true, new_inl);
  767. } else {
  768. new_inl = make_str(chunk_literal("!"));
  769. }
  770. break;
  771. default:
  772. endpos = subject_find_special_char(subj);
  773. contents = chunk_dup(&subj->input, subj->pos, endpos - subj->pos);
  774. subj->pos = endpos;
  775. // if we're at a newline, strip trailing spaces.
  776. if (peek_char(subj) == '\n') {
  777. chunk_rtrim(&contents);
  778. }
  779. new_inl = make_str(contents);
  780. }
  781. if (new_inl != NULL) {
  782. cmark_node_append_child(parent, new_inl);
  783. }
  784. return 1;
  785. }
  786. // Parse inlines from parent's string_content, adding as children of parent.
  787. extern void cmark_parse_inlines(cmark_node* parent, cmark_reference_map *refmap)
  788. {
  789. subject subj;
  790. subject_from_buf(&subj, &parent->string_content, refmap);
  791. while (!is_eof(&subj) && parse_inline(&subj, parent)) ;
  792. process_emphasis(&subj, NULL);
  793. }
  794. // Parse zero or more space characters, including at most one newline.
  795. static void spnl(subject* subj)
  796. {
  797. bool seen_newline = false;
  798. while (peek_char(subj) == ' ' ||
  799. (!seen_newline &&
  800. (seen_newline = peek_char(subj) == '\n'))) {
  801. advance(subj);
  802. }
  803. }
  804. // Parse reference. Assumes string begins with '[' character.
  805. // Modify refmap if a reference is encountered.
  806. // Return 0 if no reference found, otherwise position of subject
  807. // after reference is parsed.
  808. int parse_reference_inline(strbuf *input, reference_map *refmap)
  809. {
  810. subject subj;
  811. chunk lab;
  812. chunk url;
  813. chunk title;
  814. int matchlen = 0;
  815. int beforetitle;
  816. subject_from_buf(&subj, input, NULL);
  817. // parse label:
  818. if (!link_label(&subj, &lab))
  819. return 0;
  820. // colon:
  821. if (peek_char(&subj) == ':') {
  822. advance(&subj);
  823. } else {
  824. return 0;
  825. }
  826. // parse link url:
  827. spnl(&subj);
  828. matchlen = scan_link_url(&subj.input, subj.pos);
  829. if (matchlen) {
  830. url = chunk_dup(&subj.input, subj.pos, matchlen);
  831. subj.pos += matchlen;
  832. } else {
  833. return 0;
  834. }
  835. // parse optional link_title
  836. beforetitle = subj.pos;
  837. spnl(&subj);
  838. matchlen = scan_link_title(&subj.input, subj.pos);
  839. if (matchlen) {
  840. title = chunk_dup(&subj.input, subj.pos, matchlen);
  841. subj.pos += matchlen;
  842. } else {
  843. subj.pos = beforetitle;
  844. title = chunk_literal("");
  845. }
  846. // parse final spaces and newline:
  847. while (peek_char(&subj) == ' ') {
  848. advance(&subj);
  849. }
  850. if (peek_char(&subj) == '\n') {
  851. advance(&subj);
  852. } else if (peek_char(&subj) != 0) {
  853. return 0;
  854. }
  855. // insert reference into refmap
  856. reference_create(refmap, &lab, &url, &title);
  857. return subj.pos;
  858. }