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