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