aboutsummaryrefslogtreecommitdiff
path: root/src/inlines.c
blob: bf55a0f631e1cbd05328cd83eac9504e12d0e5c8 (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. #include "debug.h"
  12. typedef struct DelimiterStack {
  13. struct DelimiterStack *previous;
  14. struct DelimiterStack *next;
  15. node_inl *first_inline;
  16. int delim_count;
  17. unsigned char delim_char;
  18. int position;
  19. bool can_open;
  20. bool can_close;
  21. } delimiter_stack;
  22. typedef struct Subject {
  23. chunk input;
  24. int pos;
  25. reference_map *refmap;
  26. delimiter_stack *delimiters;
  27. } subject;
  28. static node_inl *parse_inlines_from_subject(subject* subj);
  29. static int parse_inline(subject* subj, node_inl ** last);
  30. static void subject_from_buf(subject *e, strbuf *buffer, reference_map *refmap);
  31. static int subject_find_special_char(subject *subj);
  32. static unsigned char *bufdup(const unsigned char *buf)
  33. {
  34. unsigned char *new = NULL;
  35. if (buf) {
  36. int len = strlen((char *)buf);
  37. new = calloc(len + 1, sizeof(*new));
  38. if(new != NULL) {
  39. memcpy(new, buf, len + 1);
  40. }
  41. }
  42. return new;
  43. }
  44. static inline node_inl *make_link_(node_inl *label, unsigned char *url, unsigned char *title)
  45. {
  46. node_inl* e = calloc(1, sizeof(*e));
  47. if(e != NULL) {
  48. e->tag = INL_LINK;
  49. e->content.linkable.label = label;
  50. e->content.linkable.url = url;
  51. e->content.linkable.title = title;
  52. e->next = NULL;
  53. }
  54. return e;
  55. }
  56. inline static node_inl* make_autolink(node_inl* label, chunk url, int is_email)
  57. {
  58. return make_link_(label, clean_autolink(&url, is_email), NULL);
  59. }
  60. inline static node_inl* make_inlines(int t, node_inl* contents)
  61. {
  62. node_inl * e = calloc(1, sizeof(*e));
  63. if(e != NULL) {
  64. e->tag = t;
  65. e->content.inlines = contents;
  66. e->next = NULL;
  67. }
  68. return e;
  69. }
  70. // Create an inline with a literal string value.
  71. inline static node_inl* make_literal(int t, chunk s)
  72. {
  73. node_inl * e = calloc(1, sizeof(*e));
  74. if(e != NULL) {
  75. e->tag = t;
  76. e->content.literal = s;
  77. e->next = NULL;
  78. }
  79. return e;
  80. }
  81. // Create an inline with no value.
  82. inline static node_inl* make_simple(int t)
  83. {
  84. node_inl* e = calloc(1, sizeof(*e));
  85. if(e != NULL) {
  86. e->tag = t;
  87. e->next = NULL;
  88. }
  89. return e;
  90. }
  91. // Macros for creating various kinds of inlines.
  92. #define make_str(s) make_literal(INL_STRING, s)
  93. #define make_code(s) make_literal(INL_CODE, s)
  94. #define make_raw_html(s) make_literal(INL_RAW_HTML, s)
  95. #define make_linebreak() make_simple(INL_LINEBREAK)
  96. #define make_softbreak() make_simple(INL_SOFTBREAK)
  97. #define make_emph(contents) make_inlines(INL_EMPH, contents)
  98. #define make_strong(contents) make_inlines(INL_STRONG, contents)
  99. // Utility function used by free_inlines
  100. void splice_into_list(node_inl* e, node_inl* children) {
  101. node_inl * tmp;
  102. if (children) {
  103. tmp = children;
  104. // Find last child
  105. while (tmp->next) {
  106. tmp = tmp->next;
  107. }
  108. // Splice children into list
  109. tmp->next = e->next;
  110. e->next = children;
  111. }
  112. return ;
  113. }
  114. // Free an inline list. Avoid recursion to prevent stack overflows
  115. // on deeply nested structures.
  116. extern void free_inlines(node_inl* e)
  117. {
  118. node_inl * next;
  119. while (e != NULL) {
  120. switch (e->tag){
  121. case INL_STRING:
  122. case INL_RAW_HTML:
  123. case INL_CODE:
  124. chunk_free(&e->content.literal);
  125. break;
  126. case INL_LINEBREAK:
  127. case INL_SOFTBREAK:
  128. break;
  129. case INL_LINK:
  130. case INL_IMAGE:
  131. free(e->content.linkable.url);
  132. free(e->content.linkable.title);
  133. splice_into_list(e, e->content.linkable.label);
  134. break;
  135. case INL_EMPH:
  136. case INL_STRONG:
  137. splice_into_list(e, e->content.inlines);
  138. break;
  139. default:
  140. log_warn("Unknown inline tag %d", 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 *closer_above;
  597. delimiter_stack *tempstack;
  598. node_inl *link_text;
  599. node_inl *inl;
  600. chunk raw_label;
  601. advance(subj); // advance past ]
  602. initial_pos = subj->pos;
  603. // look through stack of delimiters for a [ or !
  604. opener = subj->delimiters;
  605. while (opener) {
  606. if (opener->delim_char == '[' || opener->delim_char == '!') {
  607. break;
  608. }
  609. opener = opener->previous;
  610. }
  611. if (opener == NULL) {
  612. return make_str(chunk_literal("]"));
  613. }
  614. // If we got here, we matched a potential link/image text.
  615. is_image = opener->delim_char == '!';
  616. link_text = opener->first_inline->next;
  617. // Now we check to see if it's a link/image.
  618. // First, look for an inline link.
  619. if (peek_char(subj) == '(' &&
  620. ((sps = scan_spacechars(&subj->input, subj->pos + 1)) > -1) &&
  621. ((n = scan_link_url(&subj->input, subj->pos + 1 + sps)) > -1)) {
  622. // try to parse an explicit link:
  623. starturl = subj->pos + 1 + sps; // after (
  624. endurl = starturl + n;
  625. starttitle = endurl + scan_spacechars(&subj->input, endurl);
  626. // ensure there are spaces btw url and title
  627. endtitle = (starttitle == endurl) ? starttitle :
  628. starttitle + scan_link_title(&subj->input, starttitle);
  629. endall = endtitle + scan_spacechars(&subj->input, endtitle);
  630. if (peek_at(subj, endall) == ')') {
  631. subj->pos = endall + 1;
  632. urlchunk = chunk_dup(&subj->input, starturl, endurl - starturl);
  633. titlechunk = chunk_dup(&subj->input, starttitle, endtitle - starttitle);
  634. url = clean_url(&urlchunk);
  635. title = clean_title(&titlechunk);
  636. chunk_free(&urlchunk);
  637. chunk_free(&titlechunk);
  638. goto match;
  639. } else {
  640. goto noMatch;
  641. }
  642. }
  643. // Next, look for a following [link label] that matches in refmap.
  644. // skip spaces
  645. subj->pos = subj->pos + scan_spacechars(&subj->input, subj->pos);
  646. raw_label = chunk_literal("");
  647. if (!link_label(subj, &raw_label) || raw_label.len == 0) {
  648. chunk_free(&raw_label);
  649. raw_label = chunk_dup(&subj->input, opener->position,
  650. initial_pos - opener->position - 1);
  651. }
  652. ref = reference_lookup(subj->refmap, &raw_label);
  653. chunk_free(&raw_label);
  654. if (ref != NULL) { // found
  655. url = bufdup(ref->url);
  656. title = bufdup(ref->title);
  657. goto match;
  658. } else {
  659. goto noMatch;
  660. }
  661. noMatch:
  662. // If we fall through to here, it means we didn't match a link:
  663. remove_delimiter(subj, opener); // remove this opener from delimiter stack
  664. subj->pos = initial_pos;
  665. return make_str(chunk_literal("]"));
  666. match:
  667. inl = opener->first_inline;
  668. inl->tag = is_image ? INL_IMAGE : INL_LINK;
  669. chunk_free(&inl->content.literal);
  670. inl->content.linkable.label = link_text;
  671. process_emphasis(subj, opener->previous);
  672. inl->content.linkable.url = url;
  673. inl->content.linkable.title = title;
  674. inl->next = NULL;
  675. *last = inl;
  676. // process_emphasis will remove this delimiter and all later ones.
  677. // Now, if we have a link, we also want to remove earlier link
  678. // delimiters. (This code can be removed if we decide to allow links
  679. // inside links.)
  680. if (!is_image) {
  681. opener = subj->delimiters;
  682. closer_above = NULL;
  683. while (opener != NULL) {
  684. tempstack = opener->previous;
  685. if (opener->delim_char == '[') {
  686. free(opener);
  687. if (closer_above) {
  688. closer_above->previous = tempstack;
  689. } else {
  690. subj->delimiters = tempstack;
  691. }
  692. } else {
  693. closer_above = opener;
  694. }
  695. opener = tempstack;
  696. }
  697. }
  698. return NULL;
  699. }
  700. // Parse a hard or soft linebreak, returning an inline.
  701. // Assumes the subject has a newline at the current position.
  702. static node_inl* handle_newline(subject *subj)
  703. {
  704. int nlpos = subj->pos;
  705. // skip over newline
  706. advance(subj);
  707. // skip spaces at beginning of line
  708. while (peek_char(subj) == ' ') {
  709. advance(subj);
  710. }
  711. if (nlpos > 1 &&
  712. peek_at(subj, nlpos - 1) == ' ' &&
  713. peek_at(subj, nlpos - 2) == ' ') {
  714. return make_linebreak();
  715. } else {
  716. return make_softbreak();
  717. }
  718. }
  719. // Parse inlines til end of subject, returning inlines.
  720. extern node_inl* parse_inlines_from_subject(subject* subj)
  721. {
  722. node_inl* result = NULL;
  723. node_inl** last = &result;
  724. node_inl* first = NULL;
  725. while (!is_eof(subj) && parse_inline(subj, last)) {
  726. if (!first) {
  727. first = *last;
  728. }
  729. }
  730. process_emphasis(subj, NULL);
  731. return first;
  732. }
  733. static int subject_find_special_char(subject *subj)
  734. {
  735. // "\n\\`&_*[]<!"
  736. static const int8_t SPECIAL_CHARS[256] = {
  737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
  738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  739. 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0,
  740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 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, 1, 1, 1, 0, 1,
  743. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
  753. int n = subj->pos + 1;
  754. while (n < subj->input.len) {
  755. if (SPECIAL_CHARS[subj->input.data[n]])
  756. return n;
  757. n++;
  758. }
  759. return subj->input.len;
  760. }
  761. // Parse an inline, advancing subject, and add it to last element.
  762. // Adjust tail to point to new last element of list.
  763. // Return 0 if no inline can be parsed, 1 otherwise.
  764. static int parse_inline(subject* subj, node_inl ** last)
  765. {
  766. node_inl* new = NULL;
  767. chunk contents;
  768. unsigned char c;
  769. int endpos;
  770. c = peek_char(subj);
  771. if (c == 0) {
  772. return 0;
  773. }
  774. switch(c){
  775. case '\n':
  776. new = handle_newline(subj);
  777. break;
  778. case '`':
  779. new = handle_backticks(subj);
  780. break;
  781. case '\\':
  782. new = handle_backslash(subj);
  783. break;
  784. case '&':
  785. new = handle_entity(subj);
  786. break;
  787. case '<':
  788. new = handle_pointy_brace(subj);
  789. break;
  790. case '*':
  791. case '_':
  792. new = handle_strong_emph(subj, c, last);
  793. break;
  794. case '[':
  795. advance(subj);
  796. new = make_str(chunk_literal("["));
  797. subj->delimiters = push_delimiter(subj, 1, '[', true, false, new);
  798. break;
  799. case ']':
  800. new = handle_close_bracket(subj, last);
  801. break;
  802. case '!':
  803. advance(subj);
  804. if (peek_char(subj) == '[') {
  805. advance(subj);
  806. new = make_str(chunk_literal("!["));
  807. subj->delimiters = push_delimiter(subj, 1, '!', false, true, new);
  808. } else {
  809. new = make_str(chunk_literal("!"));
  810. }
  811. break;
  812. default:
  813. endpos = subject_find_special_char(subj);
  814. contents = chunk_dup(&subj->input, subj->pos, endpos - subj->pos);
  815. subj->pos = endpos;
  816. // if we're at a newline, strip trailing spaces.
  817. if (peek_char(subj) == '\n') {
  818. chunk_rtrim(&contents);
  819. }
  820. new = make_str(contents);
  821. }
  822. if (*last == NULL) {
  823. *last = new;
  824. } else if (new) {
  825. append_inlines(*last, new);
  826. *last = new;
  827. }
  828. return 1;
  829. }
  830. extern node_inl* parse_inlines(strbuf *input, reference_map *refmap)
  831. {
  832. subject subj;
  833. subject_from_buf(&subj, input, refmap);
  834. return parse_inlines_from_subject(&subj);
  835. }
  836. // Parse zero or more space characters, including at most one newline.
  837. void spnl(subject* subj)
  838. {
  839. bool seen_newline = false;
  840. while (peek_char(subj) == ' ' ||
  841. (!seen_newline &&
  842. (seen_newline = peek_char(subj) == '\n'))) {
  843. advance(subj);
  844. }
  845. }
  846. // Parse reference. Assumes string begins with '[' character.
  847. // Modify refmap if a reference is encountered.
  848. // Return 0 if no reference found, otherwise position of subject
  849. // after reference is parsed.
  850. int parse_reference_inline(strbuf *input, reference_map *refmap)
  851. {
  852. subject subj;
  853. chunk lab;
  854. chunk url;
  855. chunk title;
  856. int matchlen = 0;
  857. int beforetitle;
  858. subject_from_buf(&subj, input, NULL);
  859. // parse label:
  860. if (!link_label(&subj, &lab))
  861. return 0;
  862. // colon:
  863. if (peek_char(&subj) == ':') {
  864. advance(&subj);
  865. } else {
  866. return 0;
  867. }
  868. // parse link url:
  869. spnl(&subj);
  870. matchlen = scan_link_url(&subj.input, subj.pos);
  871. if (matchlen) {
  872. url = chunk_dup(&subj.input, subj.pos, matchlen);
  873. subj.pos += matchlen;
  874. } else {
  875. return 0;
  876. }
  877. // parse optional link_title
  878. beforetitle = subj.pos;
  879. spnl(&subj);
  880. matchlen = scan_link_title(&subj.input, subj.pos);
  881. if (matchlen) {
  882. title = chunk_dup(&subj.input, subj.pos, matchlen);
  883. subj.pos += matchlen;
  884. } else {
  885. subj.pos = beforetitle;
  886. title = chunk_literal("");
  887. }
  888. // parse final spaces and newline:
  889. while (peek_char(&subj) == ' ') {
  890. advance(&subj);
  891. }
  892. if (peek_char(&subj) == '\n') {
  893. advance(&subj);
  894. } else if (peek_char(&subj) != 0) {
  895. return 0;
  896. }
  897. // insert reference into refmap
  898. reference_create(refmap, &lab, &url, &title);
  899. return subj.pos;
  900. }