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