aboutsummaryrefslogtreecommitdiff
path: root/src/inlines.c
blob: 7a7ca022d72a9fbaf8d7f7ab0f5e1e02df033098 (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. advance(subj); // advance past [
  498. unsigned char c;
  499. while ((c = peek_char(subj)) && c != '[' && c != ']') {
  500. if (c == '\\') {
  501. advance(subj);
  502. if (ispunct(peek_char(subj))) {
  503. advance(subj);
  504. }
  505. } else {
  506. advance(subj);
  507. }
  508. }
  509. if (c == ']') { // match found
  510. *raw_label = chunk_dup(&subj->input, startpos + 1, subj->pos - (startpos + 1));
  511. advance(subj); // advance past ]
  512. return 1;
  513. } else {
  514. subj->pos = startpos; // rewind
  515. return 0;
  516. }
  517. }
  518. // Return a link, an image, or a literal close bracket.
  519. static node_inl* handle_close_bracket(subject* subj, node_inl **last)
  520. {
  521. int initial_pos;
  522. int starturl, endurl, starttitle, endtitle, endall;
  523. int n;
  524. int sps;
  525. reference *ref;
  526. bool is_image = false;
  527. chunk urlchunk, titlechunk;
  528. unsigned char *url, *title;
  529. opener_stack *ostack = subj->openers;
  530. opener_stack *closer_above;
  531. opener_stack *tempstack;
  532. node_inl *link_text;
  533. node_inl *inl;
  534. chunk raw_label;
  535. advance(subj); // advance past ]
  536. initial_pos = subj->pos;
  537. // look through stack of openers for a [ or !
  538. while (ostack) {
  539. if (ostack->delim_char == '[' || ostack->delim_char == '!') {
  540. break;
  541. }
  542. ostack = ostack->previous;
  543. }
  544. if (ostack == NULL) {
  545. return make_str(chunk_literal("]"));
  546. }
  547. // If we got here, we matched a potential link/image text.
  548. is_image = ostack->delim_char == '!';
  549. link_text = ostack->first_inline->next;
  550. // Now we check to see if it's a link/image.
  551. // First, look for an inline link.
  552. if (peek_char(subj) == '(' &&
  553. ((sps = scan_spacechars(&subj->input, subj->pos + 1)) > -1) &&
  554. ((n = scan_link_url(&subj->input, subj->pos + 1 + sps)) > -1)) {
  555. // try to parse an explicit link:
  556. starturl = subj->pos + 1 + sps; // after (
  557. endurl = starturl + n;
  558. starttitle = endurl + scan_spacechars(&subj->input, endurl);
  559. // ensure there are spaces btw url and title
  560. endtitle = (starttitle == endurl) ? starttitle :
  561. starttitle + scan_link_title(&subj->input, starttitle);
  562. endall = endtitle + scan_spacechars(&subj->input, endtitle);
  563. if (peek_at(subj, endall) == ')') {
  564. subj->pos = endall + 1;
  565. urlchunk = chunk_dup(&subj->input, starturl, endurl - starturl);
  566. titlechunk = chunk_dup(&subj->input, starttitle, endtitle - starttitle);
  567. url = clean_url(&urlchunk);
  568. title = clean_title(&titlechunk);
  569. chunk_free(&urlchunk);
  570. chunk_free(&titlechunk);
  571. goto match;
  572. } else {
  573. goto noMatch;
  574. }
  575. }
  576. // Next, look for a following [link label] that matches in refmap.
  577. // skip spaces
  578. subj->pos = subj->pos + scan_spacechars(&subj->input, subj->pos);
  579. raw_label = chunk_literal("");
  580. if (!link_label(subj, &raw_label) || raw_label.len == 0) {
  581. // chunk_free(&raw_label);
  582. raw_label = chunk_dup(&subj->input, ostack->position, initial_pos - ostack->position - 1);
  583. }
  584. // TODO - document this hard length limit in spec; also impose for creation of refs
  585. if (raw_label.len < 1000) {
  586. ref = reference_lookup(subj->refmap, &raw_label);
  587. } else {
  588. ref = NULL;
  589. }
  590. chunk_free(&raw_label);
  591. if (ref != NULL) { // found
  592. url = bufdup(ref->url);
  593. title = bufdup(ref->title);
  594. goto match;
  595. } else {
  596. goto noMatch;
  597. }
  598. noMatch:
  599. // If we fall through to here, it means we didn't match a link:
  600. subj->pos = initial_pos;
  601. return make_str(chunk_literal("]"));
  602. match:
  603. inl = ostack->first_inline;
  604. inl->tag = is_image ? INL_IMAGE : INL_LINK;
  605. chunk_free(&inl->content.literal);
  606. inl->content.linkable.label = link_text;
  607. inl->content.linkable.url = url;
  608. inl->content.linkable.title = title;
  609. inl->next = NULL;
  610. *last = inl;
  611. // remove this opener and all later ones:
  612. free_openers(subj, ostack->previous);
  613. // remove earlier ones of the same kind
  614. // (so, no links in links, and no images in images):
  615. // (This code can be removed if we decide to allow links
  616. // inside links and images inside images):
  617. ostack = subj->openers;
  618. closer_above = NULL;
  619. while (ostack != NULL) {
  620. tempstack = ostack->previous;
  621. if (ostack->delim_char == (is_image ? '!' : '[')) {
  622. free(ostack);
  623. if (closer_above) {
  624. closer_above->previous = tempstack;
  625. } else {
  626. subj->openers = tempstack;
  627. }
  628. } else {
  629. closer_above = ostack;
  630. }
  631. ostack = tempstack;
  632. }
  633. return NULL;
  634. }
  635. // Parse a hard or soft linebreak, returning an inline.
  636. // Assumes the subject has a newline at the current position.
  637. static node_inl* handle_newline(subject *subj)
  638. {
  639. int nlpos = subj->pos;
  640. // skip over newline
  641. advance(subj);
  642. // skip spaces at beginning of line
  643. while (peek_char(subj) == ' ') {
  644. advance(subj);
  645. }
  646. if (nlpos > 1 &&
  647. peek_at(subj, nlpos - 1) == ' ' &&
  648. peek_at(subj, nlpos - 2) == ' ') {
  649. return make_linebreak();
  650. } else {
  651. return make_softbreak();
  652. }
  653. }
  654. // Parse inlines til end of subject, returning inlines.
  655. extern node_inl* parse_inlines_from_subject(subject* subj)
  656. {
  657. node_inl* result = NULL;
  658. node_inl** last = &result;
  659. node_inl* first = NULL;
  660. while (!is_eof(subj) && parse_inline(subj, last)) {
  661. if (!first) {
  662. first = *last;
  663. }
  664. }
  665. opener_stack* istack = subj->openers;
  666. opener_stack* temp;
  667. while (istack != NULL) {
  668. temp = istack->previous;
  669. free(istack);
  670. istack = temp;
  671. }
  672. return first;
  673. }
  674. static int subject_find_special_char(subject *subj)
  675. {
  676. // "\n\\`&_*[]<!"
  677. static const int8_t SPECIAL_CHARS[256] = {
  678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
  679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  680. 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0,
  681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
  682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1,
  684. 1, 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, 0, 0, 0, 0, 0,
  686. 0, 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. int n = subj->pos + 1;
  695. while (n < subj->input.len) {
  696. if (SPECIAL_CHARS[subj->input.data[n]])
  697. return n;
  698. n++;
  699. }
  700. return subj->input.len;
  701. }
  702. // Parse an inline, advancing subject, and add it to last element.
  703. // Adjust tail to point to new last element of list.
  704. // Return 0 if no inline can be parsed, 1 otherwise.
  705. static int parse_inline(subject* subj, node_inl ** last)
  706. {
  707. node_inl* new = NULL;
  708. chunk contents;
  709. unsigned char c;
  710. int endpos;
  711. c = peek_char(subj);
  712. if (c == 0) {
  713. return 0;
  714. }
  715. switch(c){
  716. case '\n':
  717. new = handle_newline(subj);
  718. break;
  719. case '`':
  720. new = handle_backticks(subj);
  721. break;
  722. case '\\':
  723. new = handle_backslash(subj);
  724. break;
  725. case '&':
  726. new = handle_entity(subj);
  727. break;
  728. case '<':
  729. new = handle_pointy_brace(subj);
  730. break;
  731. case '_':
  732. new = handle_strong_emph(subj, '_', last);
  733. break;
  734. case '*':
  735. new = handle_strong_emph(subj, '*', last);
  736. break;
  737. case '[':
  738. advance(subj);
  739. new = make_str(chunk_literal("["));
  740. subj->openers = push_opener(subj, 1, '[', new);
  741. break;
  742. case ']':
  743. new = handle_close_bracket(subj, last);
  744. break;
  745. case '!':
  746. advance(subj);
  747. if (peek_char(subj) == '[') {
  748. advance(subj);
  749. new = make_str(chunk_literal("!["));
  750. subj->openers = push_opener(subj, 1, '!', new);
  751. } else {
  752. new = make_str(chunk_literal("!"));
  753. }
  754. break;
  755. default:
  756. endpos = subject_find_special_char(subj);
  757. contents = chunk_dup(&subj->input, subj->pos, endpos - subj->pos);
  758. subj->pos = endpos;
  759. // if we're at a newline, strip trailing spaces.
  760. if (peek_char(subj) == '\n') {
  761. chunk_rtrim(&contents);
  762. }
  763. new = make_str(contents);
  764. }
  765. if (*last == NULL) {
  766. *last = new;
  767. } else if (new) {
  768. append_inlines(*last, new);
  769. *last = new;
  770. }
  771. return 1;
  772. }
  773. extern node_inl* parse_inlines(strbuf *input, reference_map *refmap)
  774. {
  775. subject subj;
  776. subject_from_buf(&subj, input, refmap);
  777. return parse_inlines_from_subject(&subj);
  778. }
  779. // Parse zero or more space characters, including at most one newline.
  780. void spnl(subject* subj)
  781. {
  782. bool seen_newline = false;
  783. while (peek_char(subj) == ' ' ||
  784. (!seen_newline &&
  785. (seen_newline = peek_char(subj) == '\n'))) {
  786. advance(subj);
  787. }
  788. }
  789. // Parse reference. Assumes string begins with '[' character.
  790. // Modify refmap if a reference is encountered.
  791. // Return 0 if no reference found, otherwise position of subject
  792. // after reference is parsed.
  793. int parse_reference_inline(strbuf *input, reference_map *refmap)
  794. {
  795. subject subj;
  796. chunk lab;
  797. chunk url;
  798. chunk title;
  799. int matchlen = 0;
  800. int beforetitle;
  801. subject_from_buf(&subj, input, NULL);
  802. // parse label:
  803. if (!link_label(&subj, &lab))
  804. return 0;
  805. // colon:
  806. if (peek_char(&subj) == ':') {
  807. advance(&subj);
  808. } else {
  809. return 0;
  810. }
  811. // parse link url:
  812. spnl(&subj);
  813. matchlen = scan_link_url(&subj.input, subj.pos);
  814. if (matchlen) {
  815. url = chunk_dup(&subj.input, subj.pos, matchlen);
  816. subj.pos += matchlen;
  817. } else {
  818. return 0;
  819. }
  820. // parse optional link_title
  821. beforetitle = subj.pos;
  822. spnl(&subj);
  823. matchlen = scan_link_title(&subj.input, subj.pos);
  824. if (matchlen) {
  825. title = chunk_dup(&subj.input, subj.pos, matchlen);
  826. subj.pos += matchlen;
  827. } else {
  828. subj.pos = beforetitle;
  829. title = chunk_literal("");
  830. }
  831. // parse final spaces and newline:
  832. while (peek_char(&subj) == ' ') {
  833. advance(&subj);
  834. }
  835. if (peek_char(&subj) == '\n') {
  836. advance(&subj);
  837. } else if (peek_char(&subj) != 0) {
  838. return 0;
  839. }
  840. // insert reference into refmap
  841. reference_create(refmap, &lab, &url, &title);
  842. return subj.pos;
  843. }