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