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