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