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