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