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