aboutsummaryrefslogtreecommitdiff
path: root/src/inlines.c
blob: 4628e328f21aa9fed29e5ee4c494aaa0fbe0a0cd (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 OpenerStack {
  13. struct OpenerStack *previous;
  14. node_inl *first_inline;
  15. int delim_count;
  16. unsigned char delim_char;
  17. int position;
  18. } opener_stack;
  19. typedef struct Subject {
  20. chunk input;
  21. int pos;
  22. reference_map *refmap;
  23. opener_stack *openers;
  24. } subject;
  25. static node_inl *parse_chunk_inlines(chunk *chunk, reference_map *refmap);
  26. static node_inl *parse_inlines_from_subject(subject* subj);
  27. static int parse_inline(subject* subj, node_inl ** last);
  28. static void subject_from_chunk(subject *e, chunk *chunk, reference_map *refmap);
  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_ref_link(node_inl* label, reference *ref)
  56. {
  57. return make_link_(label, bufdup(ref->url), bufdup(ref->title));
  58. }
  59. inline static node_inl* make_autolink(node_inl* label, chunk url, int is_email)
  60. {
  61. return make_link_(label, clean_autolink(&url, is_email), NULL);
  62. }
  63. inline static node_inl* make_inlines(int t, node_inl* contents)
  64. {
  65. node_inl * e = calloc(1, sizeof(*e));
  66. if(e != NULL) {
  67. e->tag = t;
  68. e->content.inlines = contents;
  69. e->next = NULL;
  70. }
  71. return e;
  72. }
  73. // Create an inline with a literal string value.
  74. inline static node_inl* make_literal(int t, chunk s)
  75. {
  76. node_inl * e = calloc(1, sizeof(*e));
  77. if(e != NULL) {
  78. e->tag = t;
  79. e->content.literal = s;
  80. e->next = NULL;
  81. }
  82. return e;
  83. }
  84. // Create an inline with no value.
  85. inline static node_inl* make_simple(int t)
  86. {
  87. node_inl* e = calloc(1, sizeof(*e));
  88. if(e != NULL) {
  89. e->tag = t;
  90. e->next = NULL;
  91. }
  92. return e;
  93. }
  94. // Macros for creating various kinds of inlines.
  95. #define make_str(s) make_literal(INL_STRING, s)
  96. #define make_code(s) make_literal(INL_CODE, s)
  97. #define make_raw_html(s) make_literal(INL_RAW_HTML, s)
  98. #define make_linebreak() make_simple(INL_LINEBREAK)
  99. #define make_softbreak() make_simple(INL_SOFTBREAK)
  100. #define make_emph(contents) make_inlines(INL_EMPH, contents)
  101. #define make_strong(contents) make_inlines(INL_STRONG, contents)
  102. // Utility function used by free_inlines
  103. void splice_into_list(node_inl* e, node_inl* children) {
  104. node_inl * tmp;
  105. if (children) {
  106. tmp = children;
  107. // Find last child
  108. while (tmp->next) {
  109. tmp = tmp->next;
  110. }
  111. // Splice children into list
  112. tmp->next = e->next;
  113. e->next = children;
  114. }
  115. return ;
  116. }
  117. // Free an inline list. Avoid recursion to prevent stack overflows
  118. // on deeply nested structures.
  119. extern void free_inlines(node_inl* e)
  120. {
  121. node_inl * next;
  122. while (e != NULL) {
  123. switch (e->tag){
  124. case INL_STRING:
  125. case INL_RAW_HTML:
  126. case INL_CODE:
  127. chunk_free(&e->content.literal);
  128. break;
  129. case INL_LINEBREAK:
  130. case INL_SOFTBREAK:
  131. break;
  132. case INL_LINK:
  133. case INL_IMAGE:
  134. free(e->content.linkable.url);
  135. free(e->content.linkable.title);
  136. splice_into_list(e, e->content.linkable.label);
  137. break;
  138. case INL_EMPH:
  139. case INL_STRONG:
  140. splice_into_list(e, e->content.inlines);
  141. break;
  142. default:
  143. log_warn("Unknown inline tag %d", e->tag);
  144. break;
  145. }
  146. next = e->next;
  147. free(e);
  148. e = next;
  149. }
  150. }
  151. // Append inline list b to the end of inline list a.
  152. // Return pointer to head of new list.
  153. inline static node_inl* append_inlines(node_inl* a, node_inl* b)
  154. {
  155. if (a == NULL) { // NULL acts like an empty list
  156. return b;
  157. }
  158. node_inl* cur = a;
  159. while (cur->next) {
  160. cur = cur->next;
  161. }
  162. cur->next = b;
  163. return a;
  164. }
  165. static void subject_from_buf(subject *e, strbuf *buffer, reference_map *refmap)
  166. {
  167. e->input.data = buffer->ptr;
  168. e->input.len = buffer->size;
  169. e->input.alloc = 0;
  170. e->pos = 0;
  171. e->refmap = refmap;
  172. e->openers = NULL;
  173. chunk_rtrim(&e->input);
  174. }
  175. static void subject_from_chunk(subject *e, chunk *chunk, reference_map *refmap)
  176. {
  177. e->input.data = chunk->data;
  178. e->input.len = chunk->len;
  179. e->input.alloc = 0;
  180. e->pos = 0;
  181. e->refmap = refmap;
  182. e->openers = NULL;
  183. chunk_rtrim(&e->input);
  184. }
  185. inline static int isbacktick(int c)
  186. {
  187. return (c == '`');
  188. }
  189. static inline unsigned char peek_char(subject *subj)
  190. {
  191. return (subj->pos < subj->input.len) ? subj->input.data[subj->pos] : 0;
  192. }
  193. static inline unsigned char peek_at(subject *subj, int pos)
  194. {
  195. return subj->input.data[pos];
  196. }
  197. // Return true if there are more characters in the subject.
  198. inline static int is_eof(subject* subj)
  199. {
  200. return (subj->pos >= subj->input.len);
  201. }
  202. // Advance the subject. Doesn't check for eof.
  203. #define advance(subj) (subj)->pos += 1
  204. // Take characters while a predicate holds, and return a string.
  205. inline static chunk take_while(subject* subj, int (*f)(int))
  206. {
  207. unsigned char c;
  208. int startpos = subj->pos;
  209. int len = 0;
  210. while ((c = peek_char(subj)) && (*f)(c)) {
  211. advance(subj);
  212. len++;
  213. }
  214. return chunk_dup(&subj->input, startpos, len);
  215. }
  216. // Try to process a backtick code span that began with a
  217. // span of ticks of length openticklength length (already
  218. // parsed). Return 0 if you don't find matching closing
  219. // backticks, otherwise return the position in the subject
  220. // after the closing backticks.
  221. static int scan_to_closing_backticks(subject* subj, int openticklength)
  222. {
  223. // read non backticks
  224. unsigned char c;
  225. while ((c = peek_char(subj)) && c != '`') {
  226. advance(subj);
  227. }
  228. if (is_eof(subj)) {
  229. return 0; // did not find closing ticks, return 0
  230. }
  231. int numticks = 0;
  232. while (peek_char(subj) == '`') {
  233. advance(subj);
  234. numticks++;
  235. }
  236. if (numticks != openticklength){
  237. return(scan_to_closing_backticks(subj, openticklength));
  238. }
  239. return (subj->pos);
  240. }
  241. // Parse backtick code section or raw backticks, return an inline.
  242. // Assumes that the subject has a backtick at the current position.
  243. static node_inl* handle_backticks(subject *subj)
  244. {
  245. chunk openticks = take_while(subj, isbacktick);
  246. int startpos = subj->pos;
  247. int endpos = scan_to_closing_backticks(subj, openticks.len);
  248. if (endpos == 0) { // not found
  249. subj->pos = startpos; // rewind
  250. return make_str(openticks);
  251. } else {
  252. strbuf buf = GH_BUF_INIT;
  253. strbuf_set(&buf, subj->input.data + startpos, endpos - startpos - openticks.len);
  254. strbuf_trim(&buf);
  255. strbuf_normalize_whitespace(&buf);
  256. return make_code(chunk_buf_detach(&buf));
  257. }
  258. }
  259. // Scan ***, **, or * and return number scanned, or 0.
  260. // Advances position.
  261. static int scan_delims(subject* subj, unsigned char c, bool * can_open, bool * can_close)
  262. {
  263. int numdelims = 0;
  264. unsigned char char_before, char_after;
  265. char_before = subj->pos == 0 ? '\n' : peek_at(subj, subj->pos - 1);
  266. while (peek_char(subj) == c) {
  267. numdelims++;
  268. advance(subj);
  269. }
  270. char_after = peek_char(subj);
  271. *can_open = numdelims > 0 && !isspace(char_after);
  272. *can_close = numdelims > 0 && !isspace(char_before);
  273. if (c == '_') {
  274. *can_open = *can_open && !isalnum(char_before);
  275. *can_close = *can_close && !isalnum(char_after);
  276. }
  277. return numdelims;
  278. }
  279. static void free_openers(subject* subj, opener_stack* istack)
  280. {
  281. opener_stack * tempstack;
  282. while (subj->openers != istack) {
  283. tempstack = subj->openers;
  284. subj->openers = subj->openers->previous;
  285. free(tempstack);
  286. }
  287. }
  288. static opener_stack * push_opener(subject *subj,
  289. int numdelims,
  290. unsigned char c,
  291. node_inl *inl_text)
  292. {
  293. opener_stack *istack =
  294. (opener_stack*)malloc(sizeof(opener_stack));
  295. if (istack == NULL) {
  296. return NULL;
  297. }
  298. istack->delim_count = numdelims;
  299. istack->delim_char = c;
  300. istack->first_inline = inl_text;
  301. istack->previous = subj->openers;
  302. istack->position = subj->pos;
  303. return istack;
  304. }
  305. // Parse strong/emph or a fallback.
  306. // Assumes the subject has '_' or '*' at the current position.
  307. static node_inl* handle_strong_emph(subject* subj, unsigned char c, node_inl **last)
  308. {
  309. bool can_open, can_close;
  310. int numdelims;
  311. int useDelims;
  312. int openerDelims;
  313. opener_stack * istack;
  314. node_inl * inl;
  315. node_inl * emph;
  316. node_inl * inl_text;
  317. numdelims = scan_delims(subj, c, &can_open, &can_close);
  318. if (can_close)
  319. {
  320. // walk the stack and find a matching opener, if there is one
  321. istack = subj->openers;
  322. while (true)
  323. {
  324. if (istack == NULL)
  325. goto cannotClose;
  326. if (istack->delim_char == c)
  327. break;
  328. istack = istack->previous;
  329. }
  330. // calculate the actual number of delimeters used from this closer
  331. openerDelims = istack->delim_count;
  332. if (numdelims < 3 || openerDelims < 3) {
  333. useDelims = numdelims <= openerDelims ? numdelims : openerDelims;
  334. } else { // (numdelims >= 3 && openerDelims >= 3)
  335. useDelims = numdelims % 2 == 0 ? 2 : 1;
  336. }
  337. if (istack->delim_count == useDelims)
  338. {
  339. // the opener is completely used up - remove the stack entry and reuse the inline element
  340. inl = istack->first_inline;
  341. inl->tag = useDelims == 1 ? INL_EMPH : INL_STRONG;
  342. chunk_free(&inl->content.literal);
  343. inl->content.inlines = inl->next;
  344. inl->next = NULL;
  345. // remove this opener and all later ones from stack:
  346. free_openers(subj, istack->previous);
  347. *last = inl;
  348. }
  349. else
  350. {
  351. // the opener will only partially be used - stack entry remains (truncated) and a new inline is added.
  352. inl = istack->first_inline;
  353. istack->delim_count -= useDelims;
  354. inl->content.literal.len = istack->delim_count;
  355. emph = useDelims == 1 ? make_emph(inl->next) : make_strong(inl->next);
  356. inl->next = emph;
  357. // remove all later openers from stack:
  358. free_openers(subj, istack);
  359. *last = emph;
  360. }
  361. // if the closer was not fully used, move back a char or two and try again.
  362. if (useDelims < numdelims)
  363. {
  364. subj->pos = subj->pos - numdelims + useDelims;
  365. return NULL;
  366. }
  367. return NULL; // make_str(chunk_literal(""));
  368. }
  369. cannotClose:
  370. inl_text = make_str(chunk_dup(&subj->input, subj->pos - numdelims, numdelims));
  371. if (can_open)
  372. {
  373. subj->openers = push_opener(subj,
  374. numdelims,
  375. c,
  376. inl_text);
  377. }
  378. return inl_text;
  379. }
  380. // Parse backslash-escape or just a backslash, returning an inline.
  381. static node_inl* handle_backslash(subject *subj)
  382. {
  383. advance(subj);
  384. unsigned char nextchar = peek_char(subj);
  385. if (ispunct(nextchar)) { // only ascii symbols and newline can be escaped
  386. advance(subj);
  387. return make_str(chunk_dup(&subj->input, subj->pos - 1, 1));
  388. } else if (nextchar == '\n') {
  389. advance(subj);
  390. return make_linebreak();
  391. } else {
  392. return make_str(chunk_literal("\\"));
  393. }
  394. }
  395. // Parse an entity or a regular "&" string.
  396. // Assumes the subject has an '&' character at the current position.
  397. static node_inl* handle_entity(subject* subj)
  398. {
  399. strbuf ent = GH_BUF_INIT;
  400. size_t len;
  401. advance(subj);
  402. len = houdini_unescape_ent(&ent,
  403. subj->input.data + subj->pos,
  404. subj->input.len - subj->pos
  405. );
  406. if (len == 0)
  407. return make_str(chunk_literal("&"));
  408. subj->pos += len;
  409. return make_str(chunk_buf_detach(&ent));
  410. }
  411. // Like make_str, but parses entities.
  412. // Returns an inline sequence consisting of str and entity elements.
  413. static node_inl *make_str_with_entities(chunk *content)
  414. {
  415. strbuf unescaped = GH_BUF_INIT;
  416. if (houdini_unescape_html(&unescaped, content->data, (size_t)content->len)) {
  417. return make_str(chunk_buf_detach(&unescaped));
  418. } else {
  419. return make_str(*content);
  420. }
  421. }
  422. // Clean a URL: remove surrounding whitespace and surrounding <>,
  423. // and remove \ that escape punctuation.
  424. unsigned char *clean_url(chunk *url)
  425. {
  426. strbuf buf = GH_BUF_INIT;
  427. chunk_trim(url);
  428. if (url->len == 0)
  429. return NULL;
  430. if (url->data[0] == '<' && url->data[url->len - 1] == '>') {
  431. houdini_unescape_html_f(&buf, url->data + 1, url->len - 2);
  432. } else {
  433. houdini_unescape_html_f(&buf, url->data, url->len);
  434. }
  435. strbuf_unescape(&buf);
  436. return strbuf_detach(&buf);
  437. }
  438. unsigned char *clean_autolink(chunk *url, int is_email)
  439. {
  440. strbuf buf = GH_BUF_INIT;
  441. chunk_trim(url);
  442. if (url->len == 0)
  443. return NULL;
  444. if (is_email)
  445. strbuf_puts(&buf, "mailto:");
  446. houdini_unescape_html_f(&buf, url->data, url->len);
  447. return strbuf_detach(&buf);
  448. }
  449. // Clean a title: remove surrounding quotes and remove \ that escape punctuation.
  450. unsigned char *clean_title(chunk *title)
  451. {
  452. strbuf buf = GH_BUF_INIT;
  453. unsigned char first, last;
  454. if (title->len == 0)
  455. return NULL;
  456. first = title->data[0];
  457. last = title->data[title->len - 1];
  458. // remove surrounding quotes if any:
  459. if ((first == '\'' && last == '\'') ||
  460. (first == '(' && last == ')') ||
  461. (first == '"' && last == '"')) {
  462. houdini_unescape_html_f(&buf, title->data + 1, title->len - 2);
  463. } else {
  464. houdini_unescape_html_f(&buf, title->data, title->len);
  465. }
  466. strbuf_unescape(&buf);
  467. return strbuf_detach(&buf);
  468. }
  469. // Parse an autolink or HTML tag.
  470. // Assumes the subject has a '<' character at the current position.
  471. static node_inl* handle_pointy_brace(subject* subj)
  472. {
  473. int matchlen = 0;
  474. chunk contents;
  475. advance(subj); // advance past first <
  476. // first try to match a URL autolink
  477. matchlen = scan_autolink_uri(&subj->input, subj->pos);
  478. if (matchlen > 0) {
  479. contents = chunk_dup(&subj->input, subj->pos, matchlen - 1);
  480. subj->pos += matchlen;
  481. return make_autolink(
  482. make_str_with_entities(&contents),
  483. contents, 0
  484. );
  485. }
  486. // next try to match an email autolink
  487. matchlen = scan_autolink_email(&subj->input, subj->pos);
  488. if (matchlen > 0) {
  489. contents = chunk_dup(&subj->input, subj->pos, matchlen - 1);
  490. subj->pos += matchlen;
  491. return make_autolink(
  492. make_str_with_entities(&contents),
  493. contents, 1
  494. );
  495. }
  496. // finally, try to match an html tag
  497. matchlen = scan_html_tag(&subj->input, subj->pos);
  498. if (matchlen > 0) {
  499. contents = chunk_dup(&subj->input, subj->pos - 1, matchlen + 1);
  500. subj->pos += matchlen;
  501. return make_raw_html(contents);
  502. }
  503. // if nothing matches, just return the opening <:
  504. return make_str(chunk_literal("<"));
  505. }
  506. // Parse a link label. Returns 1 if successful.
  507. // Note: unescaped brackets are not allowed in labels.
  508. // The label begins with `[` and ends with the first `]` character
  509. // encountered. Backticks in labels do not start code spans.
  510. static int link_label(subject* subj, chunk *raw_label)
  511. {
  512. int startpos = subj->pos;
  513. advance(subj); // advance past [
  514. unsigned char c;
  515. while ((c = peek_char(subj)) && c != '[' && c != ']') {
  516. if (c == '\\') {
  517. advance(subj);
  518. if (ispunct(peek_char(subj))) {
  519. advance(subj);
  520. }
  521. } else {
  522. advance(subj);
  523. }
  524. }
  525. if (c == ']') { // match found
  526. *raw_label = chunk_dup(&subj->input, startpos + 1, subj->pos - (startpos + 1));
  527. advance(subj); // advance past ]
  528. return 1;
  529. } else {
  530. subj->pos = startpos; // rewind
  531. return 0;
  532. }
  533. }
  534. // Return a link, an image, or a literal close bracket.
  535. static node_inl* handle_close_bracket(subject* subj, node_inl **last)
  536. {
  537. int initial_pos;
  538. int starturl, endurl, starttitle, endtitle, endall;
  539. int n;
  540. int sps;
  541. reference *ref;
  542. bool is_image = false;
  543. chunk urlchunk, titlechunk;
  544. unsigned char *url, *title;
  545. opener_stack *ostack = subj->openers;
  546. node_inl *link_text;
  547. node_inl *inl;
  548. chunk raw_label;
  549. advance(subj); // advance past ]
  550. initial_pos = subj->pos;
  551. // look through stack of openers for a [ or !
  552. while (ostack) {
  553. if (ostack->delim_char == '[' || ostack->delim_char == '!') {
  554. break;
  555. }
  556. ostack = ostack->previous;
  557. }
  558. if (ostack == NULL) {
  559. return make_str(chunk_literal("]"));
  560. }
  561. // If we got here, we matched a potential link/image text.
  562. is_image = ostack->delim_char == '!';
  563. link_text = ostack->first_inline->next;
  564. // Now we check to see if it's a link/image.
  565. // First, look for an inline link.
  566. if (peek_char(subj) == '(' &&
  567. ((sps = scan_spacechars(&subj->input, subj->pos + 1)) > -1) &&
  568. ((n = scan_link_url(&subj->input, subj->pos + 1 + sps)) > -1)) {
  569. // try to parse an explicit link:
  570. starturl = subj->pos + 1 + sps; // after (
  571. endurl = starturl + n;
  572. starttitle = endurl + scan_spacechars(&subj->input, endurl);
  573. // ensure there are spaces btw url and title
  574. endtitle = (starttitle == endurl) ? starttitle :
  575. starttitle + scan_link_title(&subj->input, starttitle);
  576. endall = endtitle + scan_spacechars(&subj->input, endtitle);
  577. if (peek_at(subj, endall) == ')') {
  578. subj->pos = endall + 1;
  579. urlchunk = chunk_dup(&subj->input, starturl, endurl - starturl);
  580. titlechunk = chunk_dup(&subj->input, starttitle, endtitle - starttitle);
  581. url = clean_url(&urlchunk);
  582. title = clean_title(&titlechunk);
  583. chunk_free(&urlchunk);
  584. chunk_free(&titlechunk);
  585. goto match;
  586. } else {
  587. goto noMatch;
  588. }
  589. }
  590. // Next, look for a following [link label] that matches in refmap.
  591. // skip spaces
  592. subj->pos = subj->pos + scan_spacechars(&subj->input, subj->pos);
  593. raw_label = chunk_literal("");
  594. if (!link_label(subj, &raw_label) || raw_label.len == 0) {
  595. // chunk_free(&raw_label);
  596. raw_label = chunk_dup(&subj->input, ostack->position, initial_pos - ostack->position - 1);
  597. }
  598. // TODO - document this hard length limit in READE; also impose for creation of refs
  599. if (raw_label.len < 1000) {
  600. ref = reference_lookup(subj->refmap, &raw_label);
  601. } else {
  602. ref = NULL;
  603. }
  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. subj->pos = initial_pos;
  615. return make_str(chunk_literal("]"));
  616. match:
  617. inl = ostack->first_inline;
  618. inl->tag = is_image ? INL_IMAGE : INL_LINK;
  619. chunk_free(&inl->content.literal);
  620. inl->content.linkable.label = link_text;
  621. inl->content.linkable.url = url;
  622. inl->content.linkable.title = title;
  623. inl->next = NULL;
  624. *last = inl;
  625. // remove this opener and all later ones from stack:
  626. free_openers(subj, ostack->previous);
  627. return NULL;
  628. }
  629. // Parse a hard or soft linebreak, returning an inline.
  630. // Assumes the subject has a newline at the current position.
  631. static node_inl* handle_newline(subject *subj)
  632. {
  633. int nlpos = subj->pos;
  634. // skip over newline
  635. advance(subj);
  636. // skip spaces at beginning of line
  637. while (peek_char(subj) == ' ') {
  638. advance(subj);
  639. }
  640. if (nlpos > 1 &&
  641. peek_at(subj, nlpos - 1) == ' ' &&
  642. peek_at(subj, nlpos - 2) == ' ') {
  643. return make_linebreak();
  644. } else {
  645. return make_softbreak();
  646. }
  647. }
  648. // Parse inlines til end of subject, returning inlines.
  649. extern node_inl* parse_inlines_from_subject(subject* subj)
  650. {
  651. node_inl* result = NULL;
  652. node_inl** last = &result;
  653. node_inl* first = NULL;
  654. while (!is_eof(subj) && parse_inline(subj, last)) {
  655. if (!first) {
  656. first = *last;
  657. }
  658. }
  659. opener_stack* istack = subj->openers;
  660. opener_stack* temp;
  661. while (istack != NULL) {
  662. temp = istack->previous;
  663. free(istack);
  664. istack = temp;
  665. }
  666. return first;
  667. }
  668. node_inl *parse_chunk_inlines(chunk *chunk, reference_map *refmap)
  669. {
  670. subject subj;
  671. subject_from_chunk(&subj, chunk, refmap);
  672. return parse_inlines_from_subject(&subj);
  673. }
  674. static int subject_find_special_char(subject *subj)
  675. {
  676. // "\n\\`&_*[]<!"
  677. static const int8_t SPECIAL_CHARS[256] = {
  678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
  679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  680. 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0,
  681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
  682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1,
  684. 1, 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, 0, 0, 0, 0, 0,
  686. 0, 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. int n = subj->pos + 1;
  695. while (n < subj->input.len) {
  696. if (SPECIAL_CHARS[subj->input.data[n]])
  697. return n;
  698. n++;
  699. }
  700. return subj->input.len;
  701. }
  702. // Parse an inline, advancing subject, and add it to last element.
  703. // Adjust tail to point to new last element of list.
  704. // Return 0 if no inline can be parsed, 1 otherwise.
  705. static int parse_inline(subject* subj, node_inl ** last)
  706. {
  707. node_inl* new = NULL;
  708. chunk contents;
  709. unsigned char c;
  710. int endpos;
  711. c = peek_char(subj);
  712. if (c == 0) {
  713. return 0;
  714. }
  715. switch(c){
  716. case '\n':
  717. new = handle_newline(subj);
  718. break;
  719. case '`':
  720. new = handle_backticks(subj);
  721. break;
  722. case '\\':
  723. new = handle_backslash(subj);
  724. break;
  725. case '&':
  726. new = handle_entity(subj);
  727. break;
  728. case '<':
  729. new = handle_pointy_brace(subj);
  730. break;
  731. case '_':
  732. new = handle_strong_emph(subj, '_', last);
  733. break;
  734. case '*':
  735. new = handle_strong_emph(subj, '*', last);
  736. break;
  737. case '[':
  738. advance(subj);
  739. new = make_str(chunk_literal("["));
  740. subj->openers = push_opener(subj, 1, '[', new);
  741. break;
  742. case ']':
  743. new = handle_close_bracket(subj, last);
  744. break;
  745. case '!':
  746. advance(subj);
  747. if (peek_char(subj) == '[') {
  748. advance(subj);
  749. new = make_str(chunk_literal("!["));
  750. subj->openers = push_opener(subj, 1, '!', new);
  751. } else {
  752. new = 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 = make_str(contents);
  764. }
  765. if (*last == NULL) {
  766. *last = new;
  767. } else if (new) {
  768. append_inlines(*last, new);
  769. *last = new;
  770. }
  771. return 1;
  772. }
  773. extern node_inl* 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. 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. }