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