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