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