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