aboutsummaryrefslogtreecommitdiff
path: root/src/inlines.c
blob: aa0e13e5e650f582846b59bb1b0860d2fea3397a (plain)
  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include <stdio.h>
  4. #include <stdbool.h>
  5. #include <ctype.h>
  6. #include "stmd.h"
  7. #include "html/houdini.h"
  8. #include "utf8.h"
  9. #include "uthash.h"
  10. #include "scanners.h"
  11. typedef struct Subject {
  12. chunk input;
  13. int pos;
  14. int label_nestlevel;
  15. reference** reference_map;
  16. } subject;
  17. reference* lookup_reference(reference** refmap, chunk *label);
  18. reference* make_reference(chunk *label, chunk *url, chunk *title);
  19. static unsigned char *clean_url(chunk *url);
  20. static unsigned char *clean_title(chunk *title);
  21. static unsigned char *clean_autolink(chunk *url, int is_email);
  22. inline static void chunk_free(chunk *c);
  23. inline static void chunk_trim(chunk *c);
  24. inline static chunk chunk_literal(const char *data);
  25. inline static chunk chunk_buf_detach(strbuf *buf);
  26. inline static chunk chunk_dup(const chunk *ch, int pos, int len);
  27. static node_inl *parse_chunk_inlines(chunk *chunk, reference** refmap);
  28. static node_inl *parse_inlines_while(subject* subj, int (*f)(subject*));
  29. static int parse_inline(subject* subj, node_inl ** last);
  30. static void subject_from_chunk(subject *e, chunk *chunk, reference** refmap);
  31. static void subject_from_buf(subject *e, strbuf *buffer, reference** refmap);
  32. static int subject_find_special_char(subject *subj);
  33. static void normalize_whitespace(strbuf *s);
  34. extern void free_reference(reference *ref) {
  35. free(ref->label);
  36. free(ref->url);
  37. free(ref->title);
  38. free(ref);
  39. }
  40. extern void free_reference_map(reference **refmap) {
  41. /* free the hash table contents */
  42. reference *s;
  43. reference *tmp;
  44. if (refmap != NULL) {
  45. HASH_ITER(hh, *refmap, s, tmp) {
  46. HASH_DEL(*refmap, s);
  47. free_reference(s);
  48. }
  49. free(refmap);
  50. }
  51. }
  52. // normalize reference: collapse internal whitespace to single space,
  53. // remove leading/trailing whitespace, case fold
  54. static unsigned char *normalize_reference(chunk *ref)
  55. {
  56. strbuf normalized = GH_BUF_INIT;
  57. utf8proc_case_fold(&normalized, ref->data, ref->len);
  58. strbuf_trim(&normalized);
  59. normalize_whitespace(&normalized);
  60. return strbuf_detach(&normalized);
  61. }
  62. // Returns reference if refmap contains a reference with matching
  63. // label, otherwise NULL.
  64. extern reference* lookup_reference(reference** refmap, chunk *label)
  65. {
  66. reference *ref = NULL;
  67. unsigned char *norm = normalize_reference(label);
  68. if (refmap != NULL) {
  69. HASH_FIND_STR(*refmap, (char*)norm, ref);
  70. }
  71. free(norm);
  72. return ref;
  73. }
  74. extern reference* make_reference(chunk *label, chunk *url, chunk *title)
  75. {
  76. reference *ref;
  77. ref = malloc(sizeof(reference));
  78. ref->label = normalize_reference(label);
  79. ref->url = clean_url(url);
  80. ref->title = clean_title(title);
  81. return ref;
  82. }
  83. extern void add_reference(reference** refmap, reference* ref)
  84. {
  85. reference * t = NULL;
  86. const char *label = (const char *)ref->label;
  87. HASH_FIND(hh, *refmap, label, strlen(label), t);
  88. if (t == NULL) {
  89. HASH_ADD_KEYPTR(hh, *refmap, label, strlen(label), ref);
  90. } else {
  91. free_reference(ref); // we free this now since it won't be in the refmap
  92. }
  93. }
  94. static unsigned char *bufdup(const unsigned char *buf)
  95. {
  96. unsigned char *new = NULL;
  97. if (buf) {
  98. int len = strlen((char *)buf);
  99. new = malloc(len + 1);
  100. memcpy(new, buf, len + 1);
  101. }
  102. return new;
  103. }
  104. static inline node_inl *make_link_(node_inl *label, unsigned char *url, unsigned char *title)
  105. {
  106. node_inl* e = (node_inl*) malloc(sizeof(node_inl));
  107. e->tag = INL_LINK;
  108. e->content.linkable.label = label;
  109. e->content.linkable.url = url;
  110. e->content.linkable.title = title;
  111. e->next = NULL;
  112. return e;
  113. }
  114. inline static node_inl* make_ref_link(node_inl* label, reference *ref)
  115. {
  116. return make_link_(label, bufdup(ref->url), bufdup(ref->title));
  117. }
  118. inline static node_inl* make_autolink(node_inl* label, chunk url, int is_email)
  119. {
  120. return make_link_(label, clean_autolink(&url, is_email), NULL);
  121. }
  122. // Create an inline with a linkable string value.
  123. inline static node_inl* make_link(node_inl* label, chunk url, chunk title)
  124. {
  125. return make_link_(label, clean_url(&url), clean_title(&title));
  126. }
  127. inline static node_inl* make_inlines(int t, node_inl* contents)
  128. {
  129. node_inl* e = (node_inl*) malloc(sizeof(node_inl));
  130. e->tag = t;
  131. e->content.inlines = contents;
  132. e->next = NULL;
  133. return e;
  134. }
  135. // Create an inline with a literal string value.
  136. inline static node_inl* make_literal(int t, chunk s)
  137. {
  138. node_inl* e = (node_inl*) malloc(sizeof(node_inl));
  139. e->tag = t;
  140. e->content.literal = s;
  141. e->next = NULL;
  142. return e;
  143. }
  144. // Create an inline with no value.
  145. inline static node_inl* make_simple(int t)
  146. {
  147. node_inl* e = (node_inl*) malloc(sizeof(node_inl));
  148. e->tag = t;
  149. e->next = NULL;
  150. return e;
  151. }
  152. // Macros for creating various kinds of inlines.
  153. #define make_str(s) make_literal(INL_STRING, s)
  154. #define make_code(s) make_literal(INL_CODE, s)
  155. #define make_raw_html(s) make_literal(INL_RAW_HTML, s)
  156. #define make_linebreak() make_simple(INL_LINEBREAK)
  157. #define make_softbreak() make_simple(INL_SOFTBREAK)
  158. #define make_emph(contents) make_inlines(INL_EMPH, contents)
  159. #define make_strong(contents) make_inlines(INL_STRONG, contents)
  160. // Free an inline list.
  161. extern void free_inlines(node_inl* e)
  162. {
  163. node_inl * next;
  164. while (e != NULL) {
  165. switch (e->tag){
  166. case INL_STRING:
  167. case INL_RAW_HTML:
  168. case INL_CODE:
  169. chunk_free(&e->content.literal);
  170. break;
  171. case INL_LINEBREAK:
  172. case INL_SOFTBREAK:
  173. break;
  174. case INL_LINK:
  175. case INL_IMAGE:
  176. free(e->content.linkable.url);
  177. free(e->content.linkable.title);
  178. free_inlines(e->content.linkable.label);
  179. break;
  180. case INL_EMPH:
  181. case INL_STRONG:
  182. free_inlines(e->content.inlines);
  183. break;
  184. default:
  185. break;
  186. }
  187. next = e->next;
  188. free(e);
  189. e = next;
  190. }
  191. }
  192. // Append inline list b to the end of inline list a.
  193. // Return pointer to head of new list.
  194. inline static node_inl* append_inlines(node_inl* a, node_inl* b)
  195. {
  196. if (a == NULL) { // NULL acts like an empty list
  197. return b;
  198. }
  199. node_inl* cur = a;
  200. while (cur->next) {
  201. cur = cur->next;
  202. }
  203. cur->next = b;
  204. return a;
  205. }
  206. static void subject_from_buf(subject *e, strbuf *buffer, reference** refmap)
  207. {
  208. e->input.data = buffer->ptr;
  209. e->input.len = buffer->size;
  210. e->input.alloc = 0;
  211. e->pos = 0;
  212. e->label_nestlevel = 0;
  213. e->reference_map = refmap;
  214. chunk_rtrim(&e->input);
  215. }
  216. static void subject_from_chunk(subject *e, chunk *chunk, reference** refmap)
  217. {
  218. e->input.data = chunk->data;
  219. e->input.len = chunk->len;
  220. e->input.alloc = 0;
  221. e->pos = 0;
  222. e->label_nestlevel = 0;
  223. e->reference_map = refmap;
  224. chunk_rtrim(&e->input);
  225. }
  226. inline static int isbacktick(int c)
  227. {
  228. return (c == '`');
  229. }
  230. static inline unsigned char peek_char(subject *subj)
  231. {
  232. return (subj->pos < subj->input.len) ? subj->input.data[subj->pos] : 0;
  233. }
  234. static inline unsigned char peek_at(subject *subj, int pos)
  235. {
  236. return subj->input.data[pos];
  237. }
  238. // Return true if there are more characters in the subject.
  239. inline static int is_eof(subject* subj)
  240. {
  241. return (subj->pos >= subj->input.len);
  242. }
  243. // Advance the subject. Doesn't check for eof.
  244. #define advance(subj) (subj)->pos += 1
  245. // Take characters while a predicate holds, and return a string.
  246. inline static chunk take_while(subject* subj, int (*f)(int))
  247. {
  248. unsigned char c;
  249. int startpos = subj->pos;
  250. int len = 0;
  251. while ((c = peek_char(subj)) && (*f)(c)) {
  252. advance(subj);
  253. len++;
  254. }
  255. return chunk_dup(&subj->input, startpos, len);
  256. }
  257. // Try to process a backtick code span that began with a
  258. // span of ticks of length openticklength length (already
  259. // parsed). Return 0 if you don't find matching closing
  260. // backticks, otherwise return the position in the subject
  261. // after the closing backticks.
  262. static int scan_to_closing_backticks(subject* subj, int openticklength)
  263. {
  264. // read non backticks
  265. char c;
  266. while ((c = peek_char(subj)) && c != '`') {
  267. advance(subj);
  268. }
  269. if (is_eof(subj)) {
  270. return 0; // did not find closing ticks, return 0
  271. }
  272. int numticks = 0;
  273. while (peek_char(subj) == '`') {
  274. advance(subj);
  275. numticks++;
  276. }
  277. if (numticks != openticklength){
  278. return(scan_to_closing_backticks(subj, openticklength));
  279. }
  280. return (subj->pos);
  281. }
  282. // Destructively modify string, collapsing consecutive
  283. // space and newline characters into a single space.
  284. static void normalize_whitespace(strbuf *s)
  285. {
  286. bool last_char_was_space = false;
  287. int r, w;
  288. for (r = 0, w = 0; r < s->size; ++r) {
  289. switch (s->ptr[r]) {
  290. case ' ':
  291. case '\n':
  292. if (last_char_was_space)
  293. break;
  294. s->ptr[w++] = ' ';
  295. last_char_was_space = true;
  296. break;
  297. default:
  298. s->ptr[w++] = s->ptr[r];
  299. last_char_was_space = false;
  300. }
  301. }
  302. strbuf_truncate(s, w);
  303. }
  304. // Parse backtick code section or raw backticks, return an inline.
  305. // Assumes that the subject has a backtick at the current position.
  306. static node_inl* handle_backticks(subject *subj)
  307. {
  308. chunk openticks = take_while(subj, isbacktick);
  309. int startpos = subj->pos;
  310. int endpos = scan_to_closing_backticks(subj, openticks.len);
  311. if (endpos == 0) { // not found
  312. subj->pos = startpos; // rewind
  313. return make_str(openticks);
  314. } else {
  315. strbuf buf = GH_BUF_INIT;
  316. strbuf_set(&buf, subj->input.data + startpos, endpos - startpos - openticks.len);
  317. strbuf_trim(&buf);
  318. normalize_whitespace(&buf);
  319. return make_code(chunk_buf_detach(&buf));
  320. }
  321. }
  322. // Scan ***, **, or * and return number scanned, or 0.
  323. // Don't advance position.
  324. static int scan_delims(subject* subj, char c, bool * can_open, bool * can_close)
  325. {
  326. int numdelims = 0;
  327. char char_before, char_after;
  328. int startpos = subj->pos;
  329. char_before = subj->pos == 0 ? '\n' : peek_at(subj, subj->pos - 1);
  330. while (peek_char(subj) == c) {
  331. numdelims++;
  332. advance(subj);
  333. }
  334. char_after = peek_char(subj);
  335. *can_open = numdelims > 0 && numdelims <= 3 && !isspace(char_after);
  336. *can_close = numdelims > 0 && numdelims <= 3 && !isspace(char_before);
  337. if (c == '_') {
  338. *can_open = *can_open && !isalnum(char_before);
  339. *can_close = *can_close && !isalnum(char_after);
  340. }
  341. subj->pos = startpos;
  342. return numdelims;
  343. }
  344. // Parse strong/emph or a fallback.
  345. // Assumes the subject has '_' or '*' at the current position.
  346. static node_inl* handle_strong_emph(subject* subj, char c)
  347. {
  348. bool can_open, can_close;
  349. node_inl * result = NULL;
  350. node_inl ** last = malloc(sizeof(node_inl *));
  351. node_inl * new;
  352. node_inl * il;
  353. node_inl * first_head = NULL;
  354. node_inl * first_close = NULL;
  355. int first_close_delims = 0;
  356. int numdelims;
  357. *last = NULL;
  358. numdelims = scan_delims(subj, c, &can_open, &can_close);
  359. subj->pos += numdelims;
  360. new = make_str(chunk_dup(&subj->input, subj->pos - numdelims, numdelims));
  361. *last = new;
  362. first_head = new;
  363. result = new;
  364. if (!can_open || numdelims == 0) {
  365. goto done;
  366. }
  367. switch (numdelims) {
  368. case 1:
  369. while (true) {
  370. numdelims = scan_delims(subj, c, &can_open, &can_close);
  371. if (numdelims >= 1 && can_close) {
  372. subj->pos += 1;
  373. first_head->tag = INL_EMPH;
  374. chunk_free(&first_head->content.literal);
  375. first_head->content.inlines = first_head->next;
  376. first_head->next = NULL;
  377. goto done;
  378. } else {
  379. if (!parse_inline(subj, last)) {
  380. goto done;
  381. }
  382. }
  383. }
  384. break;
  385. case 2:
  386. while (true) {
  387. numdelims = scan_delims(subj, c, &can_open, &can_close);
  388. if (numdelims >= 2 && can_close) {
  389. subj->pos += 2;
  390. first_head->tag = INL_STRONG;
  391. chunk_free(&first_head->content.literal);
  392. first_head->content.inlines = first_head->next;
  393. first_head->next = NULL;
  394. goto done;
  395. } else {
  396. if (!parse_inline(subj, last)) {
  397. goto done;
  398. }
  399. }
  400. }
  401. break;
  402. case 3:
  403. while (true) {
  404. numdelims = scan_delims(subj, c, &can_open, &can_close);
  405. if (can_close && numdelims >= 1 && numdelims <= 3 &&
  406. numdelims != first_close_delims) {
  407. new = make_str(chunk_dup(&subj->input, subj->pos, numdelims));
  408. append_inlines(*last, new);
  409. *last = new;
  410. if (first_close_delims == 1 && numdelims > 2) {
  411. numdelims = 2;
  412. } else if (first_close_delims == 2) {
  413. numdelims = 1;
  414. } else if (numdelims == 3) {
  415. // If we opened with ***, we interpret it as ** followed by *
  416. // giving us <strong><em>
  417. numdelims = 1;
  418. }
  419. subj->pos += numdelims;
  420. if (first_close) {
  421. first_head->tag = first_close_delims == 1 ? INL_STRONG : INL_EMPH;
  422. chunk_free(&first_head->content.literal);
  423. first_head->content.inlines =
  424. make_inlines(first_close_delims == 1 ? INL_EMPH : INL_STRONG,
  425. first_head->next);
  426. il = first_head->next;
  427. while (il->next && il->next != first_close) {
  428. il = il->next;
  429. }
  430. il->next = NULL;
  431. first_head->content.inlines->next = first_close->next;
  432. il = first_head->content.inlines;
  433. while (il->next && il->next != *last) {
  434. il = il->next;
  435. }
  436. il->next = NULL;
  437. free_inlines(*last);
  438. first_close->next = NULL;
  439. free_inlines(first_close);
  440. first_head->next = NULL;
  441. goto done;
  442. } else {
  443. first_close = *last;
  444. first_close_delims = numdelims;
  445. }
  446. } else {
  447. if (!parse_inline(subj, last)) {
  448. goto done;
  449. }
  450. }
  451. }
  452. break;
  453. default:
  454. goto done;
  455. }
  456. done:
  457. free(last);
  458. return result;
  459. }
  460. // Parse backslash-escape or just a backslash, returning an inline.
  461. static node_inl* handle_backslash(subject *subj)
  462. {
  463. advance(subj);
  464. unsigned char nextchar = peek_char(subj);
  465. if (ispunct(nextchar)) { // only ascii symbols and newline can be escaped
  466. advance(subj);
  467. return make_str(chunk_dup(&subj->input, subj->pos - 1, 1));
  468. } else if (nextchar == '\n') {
  469. advance(subj);
  470. return make_linebreak();
  471. } else {
  472. return make_str(chunk_literal("\\"));
  473. }
  474. }
  475. // Parse an entity or a regular "&" string.
  476. // Assumes the subject has an '&' character at the current position.
  477. static node_inl* handle_entity(subject* subj)
  478. {
  479. strbuf ent = GH_BUF_INIT;
  480. size_t len;
  481. advance(subj);
  482. len = houdini_unescape_ent(&ent,
  483. subj->input.data + subj->pos,
  484. subj->input.len - subj->pos
  485. );
  486. if (len == 0)
  487. return make_str(chunk_literal("&"));
  488. subj->pos += len;
  489. return make_str(chunk_buf_detach(&ent));
  490. }
  491. // Like make_str, but parses entities.
  492. // Returns an inline sequence consisting of str and entity elements.
  493. static node_inl *make_str_with_entities(chunk *content)
  494. {
  495. strbuf unescaped = GH_BUF_INIT;
  496. if (houdini_unescape_html(&unescaped, content->data, (size_t)content->len)) {
  497. return make_str(chunk_buf_detach(&unescaped));
  498. } else {
  499. return make_str(*content);
  500. }
  501. }
  502. // Destructively unescape a string: remove backslashes before punctuation chars.
  503. extern void unescape_buffer(strbuf *buf)
  504. {
  505. int r, w;
  506. for (r = 0, w = 0; r < buf->size; ++r) {
  507. if (buf->ptr[r] == '\\' && ispunct(buf->ptr[r + 1]))
  508. continue;
  509. buf->ptr[w++] = buf->ptr[r];
  510. }
  511. strbuf_truncate(buf, w);
  512. }
  513. // Clean a URL: remove surrounding whitespace and surrounding <>,
  514. // and remove \ that escape punctuation.
  515. static unsigned char *clean_url(chunk *url)
  516. {
  517. strbuf buf = GH_BUF_INIT;
  518. chunk_trim(url);
  519. if (url->len == 0)
  520. return NULL;
  521. if (url->data[0] == '<' && url->data[url->len - 1] == '>') {
  522. houdini_unescape_html_f(&buf, url->data + 1, url->len - 2);
  523. } else {
  524. houdini_unescape_html_f(&buf, url->data, url->len);
  525. }
  526. unescape_buffer(&buf);
  527. return strbuf_detach(&buf);
  528. }
  529. static unsigned char *clean_autolink(chunk *url, int is_email)
  530. {
  531. strbuf buf = GH_BUF_INIT;
  532. chunk_trim(url);
  533. if (url->len == 0)
  534. return NULL;
  535. if (is_email)
  536. strbuf_puts(&buf, "mailto:");
  537. houdini_unescape_html_f(&buf, url->data, url->len);
  538. return strbuf_detach(&buf);
  539. }
  540. // Clean a title: remove surrounding quotes and remove \ that escape punctuation.
  541. static unsigned char *clean_title(chunk *title)
  542. {
  543. strbuf buf = GH_BUF_INIT;
  544. unsigned char first, last;
  545. if (title->len == 0)
  546. return NULL;
  547. first = title->data[0];
  548. last = title->data[title->len - 1];
  549. // remove surrounding quotes if any:
  550. if ((first == '\'' && last == '\'') ||
  551. (first == '(' && last == ')') ||
  552. (first == '"' && last == '"')) {
  553. houdini_unescape_html_f(&buf, title->data + 1, title->len - 2);
  554. } else {
  555. houdini_unescape_html_f(&buf, title->data, title->len);
  556. }
  557. unescape_buffer(&buf);
  558. return strbuf_detach(&buf);
  559. }
  560. // Parse an autolink or HTML tag.
  561. // Assumes the subject has a '<' character at the current position.
  562. static node_inl* handle_pointy_brace(subject* subj)
  563. {
  564. int matchlen = 0;
  565. chunk contents;
  566. advance(subj); // advance past first <
  567. // first try to match a URL autolink
  568. matchlen = scan_autolink_uri(&subj->input, subj->pos);
  569. if (matchlen > 0) {
  570. contents = chunk_dup(&subj->input, subj->pos, matchlen - 1);
  571. subj->pos += matchlen;
  572. return make_autolink(
  573. make_str_with_entities(&contents),
  574. contents, 0
  575. );
  576. }
  577. // next try to match an email autolink
  578. matchlen = scan_autolink_email(&subj->input, subj->pos);
  579. if (matchlen > 0) {
  580. contents = chunk_dup(&subj->input, subj->pos, matchlen - 1);
  581. subj->pos += matchlen;
  582. return make_autolink(
  583. make_str_with_entities(&contents),
  584. contents, 1
  585. );
  586. }
  587. // finally, try to match an html tag
  588. matchlen = scan_html_tag(&subj->input, subj->pos);
  589. if (matchlen > 0) {
  590. contents = chunk_dup(&subj->input, subj->pos - 1, matchlen + 1);
  591. subj->pos += matchlen;
  592. return make_raw_html(contents);
  593. }
  594. // if nothing matches, just return the opening <:
  595. return make_str(chunk_literal("<"));
  596. }
  597. // Parse a link label. Returns 1 if successful.
  598. // Unless raw_label is null, it is set to point to the raw contents of the [].
  599. // Assumes the subject has a '[' character at the current position.
  600. // Returns 0 and does not advance if no matching ] is found.
  601. // Note the precedence: code backticks have precedence over label bracket
  602. // markers, which have precedence over *, _, and other inline formatting
  603. // markers. So, 2 below contains a link while 1 does not:
  604. // 1. [a link `with a ](/url)` character
  605. // 2. [a link *with emphasized ](/url) text*
  606. static int link_label(subject* subj, chunk *raw_label)
  607. {
  608. int nestlevel = 0;
  609. node_inl* tmp = NULL;
  610. int startpos = subj->pos;
  611. if (subj->label_nestlevel) {
  612. // if we've already checked to the end of the subject
  613. // for a label, even with a different starting [, we
  614. // know we won't find one here and we can just return.
  615. // Note: nestlevel 1 would be: [foo [bar]
  616. // nestlevel 2 would be: [foo [bar [baz]
  617. subj->label_nestlevel--;
  618. return 0;
  619. }
  620. advance(subj); // advance past [
  621. char c;
  622. while ((c = peek_char(subj)) && (c != ']' || nestlevel > 0)) {
  623. switch (c) {
  624. case '`':
  625. tmp = handle_backticks(subj);
  626. free_inlines(tmp);
  627. break;
  628. case '<':
  629. tmp = handle_pointy_brace(subj);
  630. free_inlines(tmp);
  631. break;
  632. case '[': // nested []
  633. nestlevel++;
  634. advance(subj);
  635. break;
  636. case ']': // nested []
  637. nestlevel--;
  638. advance(subj);
  639. break;
  640. case '\\':
  641. advance(subj);
  642. if (ispunct(peek_char(subj))) {
  643. advance(subj);
  644. }
  645. break;
  646. default:
  647. advance(subj);
  648. }
  649. }
  650. if (c == ']') {
  651. *raw_label = chunk_dup(&subj->input, startpos + 1, subj->pos - (startpos + 1));
  652. subj->label_nestlevel = 0;
  653. advance(subj); // advance past ]
  654. return 1;
  655. } else {
  656. if (c == 0) {
  657. subj->label_nestlevel = nestlevel;
  658. }
  659. subj->pos = startpos; // rewind
  660. return 0;
  661. }
  662. }
  663. // Parse a link or the link portion of an image, or return a fallback.
  664. static node_inl* handle_left_bracket(subject* subj)
  665. {
  666. node_inl *lab = NULL;
  667. node_inl *result = NULL;
  668. reference *ref;
  669. int n;
  670. int sps;
  671. int found_label;
  672. int endlabel, starturl, endurl, starttitle, endtitle, endall;
  673. chunk rawlabel;
  674. chunk url, title;
  675. found_label = link_label(subj, &rawlabel);
  676. endlabel = subj->pos;
  677. if (found_label) {
  678. if (peek_char(subj) == '(' &&
  679. ((sps = scan_spacechars(&subj->input, subj->pos + 1)) > -1) &&
  680. ((n = scan_link_url(&subj->input, subj->pos + 1 + sps)) > -1)) {
  681. // try to parse an explicit link:
  682. starturl = subj->pos + 1 + sps; // after (
  683. endurl = starturl + n;
  684. starttitle = endurl + scan_spacechars(&subj->input, endurl);
  685. // ensure there are spaces btw url and title
  686. endtitle = (starttitle == endurl) ? starttitle :
  687. starttitle + scan_link_title(&subj->input, starttitle);
  688. endall = endtitle + scan_spacechars(&subj->input, endtitle);
  689. if (peek_at(subj, endall) == ')') {
  690. subj->pos = endall + 1;
  691. url = chunk_dup(&subj->input, starturl, endurl - starturl);
  692. title = chunk_dup(&subj->input, starttitle, endtitle - starttitle);
  693. lab = parse_chunk_inlines(&rawlabel, NULL);
  694. return make_link(lab, url, title);
  695. } else {
  696. // if we get here, we matched a label but didn't get further:
  697. subj->pos = endlabel;
  698. lab = parse_chunk_inlines(&rawlabel, subj->reference_map);
  699. result = append_inlines(make_str(chunk_literal("[")),
  700. append_inlines(lab,
  701. make_str(chunk_literal("]"))));
  702. return result;
  703. }
  704. } else {
  705. chunk rawlabel_tmp;
  706. chunk reflabel;
  707. // Check for reference link.
  708. // First, see if there's another label:
  709. subj->pos = subj->pos + scan_spacechars(&subj->input, endlabel);
  710. reflabel = rawlabel;
  711. // if followed by a nonempty link label, we change reflabel to it:
  712. if (peek_char(subj) == '[' && link_label(subj, &rawlabel_tmp)) {
  713. if (rawlabel_tmp.len > 0)
  714. reflabel = rawlabel_tmp;
  715. } else {
  716. subj->pos = endlabel;
  717. }
  718. // lookup rawlabel in subject->reference_map:
  719. ref = lookup_reference(subj->reference_map, &reflabel);
  720. if (ref != NULL) { // found
  721. lab = parse_chunk_inlines(&rawlabel, NULL);
  722. result = make_ref_link(lab, ref);
  723. } else {
  724. subj->pos = endlabel;
  725. lab = parse_chunk_inlines(&rawlabel, subj->reference_map);
  726. result = append_inlines(make_str(chunk_literal("[")),
  727. append_inlines(lab, make_str(chunk_literal("]"))));
  728. }
  729. return result;
  730. }
  731. }
  732. // If we fall through to here, it means we didn't match a link:
  733. advance(subj); // advance past [
  734. return make_str(chunk_literal("["));
  735. }
  736. // Parse a hard or soft linebreak, returning an inline.
  737. // Assumes the subject has a newline at the current position.
  738. static node_inl* handle_newline(subject *subj)
  739. {
  740. int nlpos = subj->pos;
  741. // skip over newline
  742. advance(subj);
  743. // skip spaces at beginning of line
  744. while (peek_char(subj) == ' ') {
  745. advance(subj);
  746. }
  747. if (nlpos > 1 &&
  748. peek_at(subj, nlpos - 1) == ' ' &&
  749. peek_at(subj, nlpos - 2) == ' ') {
  750. return make_linebreak();
  751. } else {
  752. return make_softbreak();
  753. }
  754. }
  755. inline static int not_eof(subject* subj)
  756. {
  757. return !is_eof(subj);
  758. }
  759. // Parse inlines while a predicate is satisfied. Return inlines.
  760. extern node_inl* parse_inlines_while(subject* subj, int (*f)(subject*))
  761. {
  762. node_inl* result = NULL;
  763. node_inl** last = &result;
  764. while ((*f)(subj) && parse_inline(subj, last)) {
  765. }
  766. return result;
  767. }
  768. node_inl *parse_chunk_inlines(chunk *chunk, reference** refmap)
  769. {
  770. subject subj;
  771. subject_from_chunk(&subj, chunk, refmap);
  772. return parse_inlines_while(&subj, not_eof);
  773. }
  774. static int subject_find_special_char(subject *subj)
  775. {
  776. int n = subj->pos + 1;
  777. while (n < subj->input.len) {
  778. if (strchr("\n\\`&_*[]<!", subj->input.data[n]))
  779. return n;
  780. n++;
  781. }
  782. return subj->input.len;
  783. }
  784. // Parse an inline, advancing subject, and add it to last element.
  785. // Adjust tail to point to new last element of list.
  786. // Return 0 if no inline can be parsed, 1 otherwise.
  787. static int parse_inline(subject* subj, node_inl ** last)
  788. {
  789. node_inl* new = NULL;
  790. chunk contents;
  791. unsigned char c;
  792. int endpos;
  793. c = peek_char(subj);
  794. if (c == 0) {
  795. return 0;
  796. }
  797. switch(c){
  798. case '\n':
  799. new = handle_newline(subj);
  800. break;
  801. case '`':
  802. new = handle_backticks(subj);
  803. break;
  804. case '\\':
  805. new = handle_backslash(subj);
  806. break;
  807. case '&':
  808. new = handle_entity(subj);
  809. break;
  810. case '<':
  811. new = handle_pointy_brace(subj);
  812. break;
  813. case '_':
  814. if (subj->pos > 0) {
  815. unsigned char prev = peek_at(subj, subj->pos - 1);
  816. if (isalnum(prev) || prev == '_') {
  817. new = make_str(chunk_literal("_"));
  818. advance(subj);
  819. break;
  820. }
  821. }
  822. new = handle_strong_emph(subj, '_');
  823. break;
  824. case '*':
  825. new = handle_strong_emph(subj, '*');
  826. break;
  827. case '[':
  828. new = handle_left_bracket(subj);
  829. break;
  830. case '!':
  831. advance(subj);
  832. if (peek_char(subj) == '[') {
  833. new = handle_left_bracket(subj);
  834. if (new != NULL && new->tag == INL_LINK) {
  835. new->tag = INL_IMAGE;
  836. } else {
  837. new = append_inlines(make_str(chunk_literal("!")), new);
  838. }
  839. } else {
  840. new = make_str(chunk_literal("!"));
  841. }
  842. break;
  843. default:
  844. endpos = subject_find_special_char(subj);
  845. contents = chunk_dup(&subj->input, subj->pos, endpos - subj->pos);
  846. subj->pos = endpos;
  847. // if we're at a newline, strip trailing spaces.
  848. if (peek_char(subj) == '\n') {
  849. chunk_rtrim(&contents);
  850. }
  851. new = make_str(contents);
  852. }
  853. if (*last == NULL) {
  854. *last = new;
  855. } else {
  856. append_inlines(*last, new);
  857. }
  858. return 1;
  859. }
  860. extern node_inl* parse_inlines(strbuf *input, reference** refmap)
  861. {
  862. subject subj;
  863. subject_from_buf(&subj, input, refmap);
  864. return parse_inlines_while(&subj, not_eof);
  865. }
  866. // Parse zero or more space characters, including at most one newline.
  867. void spnl(subject* subj)
  868. {
  869. bool seen_newline = false;
  870. while (peek_char(subj) == ' ' ||
  871. (!seen_newline &&
  872. (seen_newline = peek_char(subj) == '\n'))) {
  873. advance(subj);
  874. }
  875. }
  876. // Parse reference. Assumes string begins with '[' character.
  877. // Modify refmap if a reference is encountered.
  878. // Return 0 if no reference found, otherwise position of subject
  879. // after reference is parsed.
  880. extern int parse_reference(strbuf *input, reference** refmap)
  881. {
  882. subject subj;
  883. chunk lab;
  884. chunk url;
  885. chunk title;
  886. int matchlen = 0;
  887. int beforetitle;
  888. reference *new = NULL;
  889. subject_from_buf(&subj, input, NULL);
  890. // parse label:
  891. if (!link_label(&subj, &lab))
  892. return 0;
  893. // colon:
  894. if (peek_char(&subj) == ':') {
  895. advance(&subj);
  896. } else {
  897. return 0;
  898. }
  899. // parse link url:
  900. spnl(&subj);
  901. matchlen = scan_link_url(&subj.input, subj.pos);
  902. if (matchlen) {
  903. url = chunk_dup(&subj.input, subj.pos, matchlen);
  904. subj.pos += matchlen;
  905. } else {
  906. return 0;
  907. }
  908. // parse optional link_title
  909. beforetitle = subj.pos;
  910. spnl(&subj);
  911. matchlen = scan_link_title(&subj.input, subj.pos);
  912. if (matchlen) {
  913. title = chunk_dup(&subj.input, subj.pos, matchlen);
  914. subj.pos += matchlen;
  915. } else {
  916. subj.pos = beforetitle;
  917. title = chunk_literal("");
  918. }
  919. // parse final spaces and newline:
  920. while (peek_char(&subj) == ' ') {
  921. advance(&subj);
  922. }
  923. if (peek_char(&subj) == '\n') {
  924. advance(&subj);
  925. } else if (peek_char(&subj) != 0) {
  926. return 0;
  927. }
  928. // insert reference into refmap
  929. new = make_reference(&lab, &url, &title);
  930. add_reference(refmap, new);
  931. return subj.pos;
  932. }