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