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