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