aboutsummaryrefslogtreecommitdiff
path: root/src/inlines.c
blob: 1ab1b29003b871c76c567f94bbb31db61f345376 (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 && subj->emphasis_nestlevel < STACK_LIMIT)
  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)) &&
  531. (c != ']' || (nestlevel > 0 && nestlevel < STACK_LIMIT))) {
  532. switch (c) {
  533. case '`':
  534. tmp = handle_backticks(subj);
  535. free_inlines(tmp);
  536. break;
  537. case '<':
  538. tmp = handle_pointy_brace(subj);
  539. free_inlines(tmp);
  540. break;
  541. case '[': // nested []
  542. nestlevel++;
  543. advance(subj);
  544. break;
  545. case ']': // nested []
  546. nestlevel--;
  547. advance(subj);
  548. break;
  549. case '\\':
  550. advance(subj);
  551. if (ispunct(peek_char(subj))) {
  552. advance(subj);
  553. }
  554. break;
  555. default:
  556. advance(subj);
  557. }
  558. }
  559. if (nestlevel == 0 && c == ']') {
  560. *raw_label = chunk_dup(&subj->input, startpos + 1, subj->pos - (startpos + 1));
  561. subj->label_nestlevel = 0;
  562. advance(subj); // advance past ]
  563. return 1;
  564. } else {
  565. if (c == 0) {
  566. subj->label_nestlevel = nestlevel;
  567. }
  568. subj->pos = startpos; // rewind
  569. return 0;
  570. }
  571. }
  572. // Parse a link or the link portion of an image, or return a fallback.
  573. static node_inl* handle_left_bracket(subject* subj)
  574. {
  575. node_inl *lab = NULL;
  576. node_inl *result = NULL;
  577. reference *ref;
  578. int n;
  579. int sps;
  580. int found_label;
  581. int endlabel, starturl, endurl, starttitle, endtitle, endall;
  582. chunk rawlabel;
  583. chunk url, title;
  584. found_label = link_label(subj, &rawlabel);
  585. endlabel = subj->pos;
  586. if (found_label) {
  587. if (peek_char(subj) == '(' &&
  588. ((sps = scan_spacechars(&subj->input, subj->pos + 1)) > -1) &&
  589. ((n = scan_link_url(&subj->input, subj->pos + 1 + sps)) > -1)) {
  590. // try to parse an explicit link:
  591. starturl = subj->pos + 1 + sps; // after (
  592. endurl = starturl + n;
  593. starttitle = endurl + scan_spacechars(&subj->input, endurl);
  594. // ensure there are spaces btw url and title
  595. endtitle = (starttitle == endurl) ? starttitle :
  596. starttitle + scan_link_title(&subj->input, starttitle);
  597. endall = endtitle + scan_spacechars(&subj->input, endtitle);
  598. if (peek_at(subj, endall) == ')') {
  599. subj->pos = endall + 1;
  600. url = chunk_dup(&subj->input, starturl, endurl - starturl);
  601. title = chunk_dup(&subj->input, starttitle, endtitle - starttitle);
  602. lab = parse_chunk_inlines(&rawlabel, NULL);
  603. return make_link(lab, url, title);
  604. } else {
  605. // if we get here, we matched a label but didn't get further:
  606. subj->pos = endlabel;
  607. lab = parse_chunk_inlines(&rawlabel, subj->refmap);
  608. result = append_inlines(make_str(chunk_literal("[")),
  609. append_inlines(lab,
  610. make_str(chunk_literal("]"))));
  611. return result;
  612. }
  613. } else {
  614. chunk rawlabel_tmp;
  615. chunk reflabel;
  616. // Check for reference link.
  617. // First, see if there's another label:
  618. subj->pos = subj->pos + scan_spacechars(&subj->input, endlabel);
  619. reflabel = rawlabel;
  620. // if followed by a nonempty link label, we change reflabel to it:
  621. if (peek_char(subj) == '[' && link_label(subj, &rawlabel_tmp)) {
  622. if (rawlabel_tmp.len > 0)
  623. reflabel = rawlabel_tmp;
  624. } else {
  625. subj->pos = endlabel;
  626. }
  627. // lookup rawlabel in subject->reference_map:
  628. ref = reference_lookup(subj->refmap, &reflabel);
  629. if (ref != NULL) { // found
  630. lab = parse_chunk_inlines(&rawlabel, NULL);
  631. result = make_ref_link(lab, ref);
  632. } else {
  633. subj->pos = endlabel;
  634. lab = parse_chunk_inlines(&rawlabel, subj->refmap);
  635. result = append_inlines(make_str(chunk_literal("[")),
  636. append_inlines(lab, make_str(chunk_literal("]"))));
  637. }
  638. return result;
  639. }
  640. }
  641. // If we fall through to here, it means we didn't match a link:
  642. advance(subj); // advance past [
  643. return make_str(chunk_literal("["));
  644. }
  645. // Parse a hard or soft linebreak, returning an inline.
  646. // Assumes the subject has a newline at the current position.
  647. static node_inl* handle_newline(subject *subj)
  648. {
  649. int nlpos = subj->pos;
  650. // skip over newline
  651. advance(subj);
  652. // skip spaces at beginning of line
  653. while (peek_char(subj) == ' ') {
  654. advance(subj);
  655. }
  656. if (nlpos > 1 &&
  657. peek_at(subj, nlpos - 1) == ' ' &&
  658. peek_at(subj, nlpos - 2) == ' ') {
  659. return make_linebreak();
  660. } else {
  661. return make_softbreak();
  662. }
  663. }
  664. inline static int not_eof(subject* subj)
  665. {
  666. return !is_eof(subj);
  667. }
  668. // Parse inlines while a predicate is satisfied. Return inlines.
  669. extern node_inl* parse_inlines_while(subject* subj, int (*f)(subject*))
  670. {
  671. node_inl* result = NULL;
  672. node_inl** last = &result;
  673. node_inl* first = NULL;
  674. while ((*f)(subj) && parse_inline(subj, last)) {
  675. if (!first) {
  676. first = *last;
  677. }
  678. }
  679. inline_stack* istack = subj->emphasis_openers;
  680. inline_stack* temp;
  681. while (istack != NULL) {
  682. temp = istack->previous;
  683. free(istack);
  684. istack = temp;
  685. }
  686. return first;
  687. }
  688. node_inl *parse_chunk_inlines(chunk *chunk, reference_map *refmap)
  689. {
  690. subject subj;
  691. subject_from_chunk(&subj, chunk, refmap);
  692. return parse_inlines_while(&subj, not_eof);
  693. }
  694. static int subject_find_special_char(subject *subj)
  695. {
  696. // "\n\\`&_*[]<!"
  697. static const int8_t SPECIAL_CHARS[256] = {
  698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
  699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  700. 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0,
  701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
  702. 0, 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, 1, 1, 1, 0, 1,
  704. 1, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
  714. int n = subj->pos + 1;
  715. while (n < subj->input.len) {
  716. if (SPECIAL_CHARS[subj->input.data[n]])
  717. return n;
  718. n++;
  719. }
  720. return subj->input.len;
  721. }
  722. // Parse an inline, advancing subject, and add it to last element.
  723. // Adjust tail to point to new last element of list.
  724. // Return 0 if no inline can be parsed, 1 otherwise.
  725. static int parse_inline(subject* subj, node_inl ** last)
  726. {
  727. node_inl* new = NULL;
  728. chunk contents;
  729. unsigned char c;
  730. int endpos;
  731. c = peek_char(subj);
  732. if (c == 0) {
  733. return 0;
  734. }
  735. switch(c){
  736. case '\n':
  737. new = handle_newline(subj);
  738. break;
  739. case '`':
  740. new = handle_backticks(subj);
  741. break;
  742. case '\\':
  743. new = handle_backslash(subj);
  744. break;
  745. case '&':
  746. new = handle_entity(subj);
  747. break;
  748. case '<':
  749. new = handle_pointy_brace(subj);
  750. break;
  751. case '_':
  752. new = handle_strong_emph(subj, '_', last);
  753. break;
  754. case '*':
  755. new = handle_strong_emph(subj, '*', last);
  756. break;
  757. case '[':
  758. new = handle_left_bracket(subj);
  759. break;
  760. case '!':
  761. advance(subj);
  762. if (peek_char(subj) == '[') {
  763. new = handle_left_bracket(subj);
  764. if (new != NULL && new->tag == INL_LINK) {
  765. new->tag = INL_IMAGE;
  766. } else {
  767. new = append_inlines(make_str(chunk_literal("!")), new);
  768. }
  769. } else {
  770. new = make_str(chunk_literal("!"));
  771. }
  772. break;
  773. default:
  774. endpos = subject_find_special_char(subj);
  775. contents = chunk_dup(&subj->input, subj->pos, endpos - subj->pos);
  776. subj->pos = endpos;
  777. // if we're at a newline, strip trailing spaces.
  778. if (peek_char(subj) == '\n') {
  779. chunk_rtrim(&contents);
  780. }
  781. new = make_str(contents);
  782. }
  783. if (*last == NULL) {
  784. *last = new;
  785. } else if (new) {
  786. append_inlines(*last, new);
  787. *last = new;
  788. }
  789. return 1;
  790. }
  791. extern node_inl* parse_inlines(strbuf *input, reference_map *refmap)
  792. {
  793. subject subj;
  794. subject_from_buf(&subj, input, refmap);
  795. return parse_inlines_while(&subj, not_eof);
  796. }
  797. // Parse zero or more space characters, including at most one newline.
  798. void spnl(subject* subj)
  799. {
  800. bool seen_newline = false;
  801. while (peek_char(subj) == ' ' ||
  802. (!seen_newline &&
  803. (seen_newline = peek_char(subj) == '\n'))) {
  804. advance(subj);
  805. }
  806. }
  807. // Parse reference. Assumes string begins with '[' character.
  808. // Modify refmap if a reference is encountered.
  809. // Return 0 if no reference found, otherwise position of subject
  810. // after reference is parsed.
  811. int parse_reference_inline(strbuf *input, reference_map *refmap)
  812. {
  813. subject subj;
  814. chunk lab;
  815. chunk url;
  816. chunk title;
  817. int matchlen = 0;
  818. int beforetitle;
  819. subject_from_buf(&subj, input, NULL);
  820. // parse label:
  821. if (!link_label(&subj, &lab))
  822. return 0;
  823. // colon:
  824. if (peek_char(&subj) == ':') {
  825. advance(&subj);
  826. } else {
  827. return 0;
  828. }
  829. // parse link url:
  830. spnl(&subj);
  831. matchlen = scan_link_url(&subj.input, subj.pos);
  832. if (matchlen) {
  833. url = chunk_dup(&subj.input, subj.pos, matchlen);
  834. subj.pos += matchlen;
  835. } else {
  836. return 0;
  837. }
  838. // parse optional link_title
  839. beforetitle = subj.pos;
  840. spnl(&subj);
  841. matchlen = scan_link_title(&subj.input, subj.pos);
  842. if (matchlen) {
  843. title = chunk_dup(&subj.input, subj.pos, matchlen);
  844. subj.pos += matchlen;
  845. } else {
  846. subj.pos = beforetitle;
  847. title = chunk_literal("");
  848. }
  849. // parse final spaces and newline:
  850. while (peek_char(&subj) == ' ') {
  851. advance(&subj);
  852. }
  853. if (peek_char(&subj) == '\n') {
  854. advance(&subj);
  855. } else if (peek_char(&subj) != 0) {
  856. return 0;
  857. }
  858. // insert reference into refmap
  859. reference_create(refmap, &lab, &url, &title);
  860. return subj.pos;
  861. }