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