aboutsummaryrefslogtreecommitdiff
path: root/src/inlines.c
blob: 599be8437fcc753b02d98b9259ad9e90aa5246b7 (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 (is_email)
  520. gh_buf_puts(&buf, "mailto:");
  521. if (url->data[0] == '<' && url->data[url->len - 1] == '>') {
  522. gh_buf_put(&buf, url->data + 1, url->len - 2);
  523. } else {
  524. gh_buf_put(&buf, url->data, url->len);
  525. }
  526. unescape_buffer(&buf);
  527. return gh_buf_detach(&buf);
  528. }
  529. // Clean a title: remove surrounding quotes and remove \ that escape punctuation.
  530. static unsigned char *clean_title(chunk *title)
  531. {
  532. gh_buf buf = GH_BUF_INIT;
  533. unsigned char first, last;
  534. if (title->len == 0)
  535. return NULL;
  536. first = title->data[0];
  537. last = title->data[title->len - 1];
  538. // remove surrounding quotes if any:
  539. if ((first == '\'' && last == '\'') ||
  540. (first == '(' && last == ')') ||
  541. (first == '"' && last == '"')) {
  542. gh_buf_set(&buf, title->data + 1, title->len - 2);
  543. } else {
  544. gh_buf_set(&buf, title->data, title->len);
  545. }
  546. unescape_buffer(&buf);
  547. return gh_buf_detach(&buf);
  548. }
  549. // Parse an autolink or HTML tag.
  550. // Assumes the subject has a '<' character at the current position.
  551. static inl* handle_pointy_brace(subject* subj)
  552. {
  553. int matchlen = 0;
  554. chunk contents;
  555. advance(subj); // advance past first <
  556. // first try to match a URL autolink
  557. matchlen = scan_autolink_uri(&subj->input, subj->pos);
  558. if (matchlen > 0) {
  559. contents = chunk_dup(&subj->input, subj->pos, matchlen - 1);
  560. subj->pos += matchlen;
  561. return make_link(
  562. make_str_with_entities(&contents),
  563. contents,
  564. chunk_literal(""),
  565. 0
  566. );
  567. }
  568. // next try to match an email autolink
  569. matchlen = scan_autolink_email(&subj->input, subj->pos);
  570. if (matchlen > 0) {
  571. contents = chunk_dup(&subj->input, subj->pos, matchlen - 1);
  572. subj->pos += matchlen;
  573. return make_link(
  574. make_str_with_entities(&contents),
  575. contents,
  576. chunk_literal(""),
  577. 1
  578. );
  579. }
  580. // finally, try to match an html tag
  581. matchlen = scan_html_tag(&subj->input, subj->pos);
  582. if (matchlen > 0) {
  583. contents = chunk_dup(&subj->input, subj->pos - 1, matchlen + 1);
  584. subj->pos += matchlen;
  585. return make_raw_html(contents);
  586. }
  587. // if nothing matches, just return the opening <:
  588. return make_str(chunk_literal("<"));
  589. }
  590. // Parse a link label. Returns 1 if successful.
  591. // Unless raw_label is null, it is set to point to the raw contents of the [].
  592. // Assumes the subject has a '[' character at the current position.
  593. // Returns 0 and does not advance if no matching ] is found.
  594. // Note the precedence: code backticks have precedence over label bracket
  595. // markers, which have precedence over *, _, and other inline formatting
  596. // markers. So, 2 below contains a link while 1 does not:
  597. // 1. [a link `with a ](/url)` character
  598. // 2. [a link *with emphasized ](/url) text*
  599. static int link_label(subject* subj, chunk *raw_label)
  600. {
  601. int nestlevel = 0;
  602. inl* tmp = NULL;
  603. int startpos = subj->pos;
  604. if (subj->label_nestlevel) {
  605. // if we've already checked to the end of the subject
  606. // for a label, even with a different starting [, we
  607. // know we won't find one here and we can just return.
  608. // Note: nestlevel 1 would be: [foo [bar]
  609. // nestlevel 2 would be: [foo [bar [baz]
  610. subj->label_nestlevel--;
  611. return 0;
  612. }
  613. advance(subj); // advance past [
  614. char c;
  615. while ((c = peek_char(subj)) && (c != ']' || nestlevel > 0)) {
  616. switch (c) {
  617. case '`':
  618. tmp = handle_backticks(subj);
  619. free_inlines(tmp);
  620. break;
  621. case '<':
  622. tmp = handle_pointy_brace(subj);
  623. free_inlines(tmp);
  624. break;
  625. case '[': // nested []
  626. nestlevel++;
  627. advance(subj);
  628. break;
  629. case ']': // nested []
  630. nestlevel--;
  631. advance(subj);
  632. break;
  633. case '\\':
  634. advance(subj);
  635. if (ispunct(peek_char(subj))) {
  636. advance(subj);
  637. }
  638. break;
  639. default:
  640. advance(subj);
  641. }
  642. }
  643. if (c == ']') {
  644. *raw_label = chunk_dup(&subj->input, startpos + 1, subj->pos - (startpos + 1));
  645. subj->label_nestlevel = 0;
  646. advance(subj); // advance past ]
  647. return 1;
  648. } else {
  649. if (c == 0) {
  650. subj->label_nestlevel = nestlevel;
  651. }
  652. subj->pos = startpos; // rewind
  653. return 0;
  654. }
  655. }
  656. // Parse a link or the link portion of an image, or return a fallback.
  657. static inl* handle_left_bracket(subject* subj)
  658. {
  659. inl *lab = NULL;
  660. inl *result = NULL;
  661. reference *ref;
  662. int n;
  663. int sps;
  664. int found_label;
  665. int endlabel, starturl, endurl, starttitle, endtitle, endall;
  666. chunk rawlabel;
  667. chunk url, title;
  668. found_label = link_label(subj, &rawlabel);
  669. endlabel = subj->pos;
  670. if (found_label) {
  671. if (peek_char(subj) == '(' &&
  672. ((sps = scan_spacechars(&subj->input, subj->pos + 1)) > -1) &&
  673. ((n = scan_link_url(&subj->input, subj->pos + 1 + sps)) > -1)) {
  674. // try to parse an explicit link:
  675. starturl = subj->pos + 1 + sps; // after (
  676. endurl = starturl + n;
  677. starttitle = endurl + scan_spacechars(&subj->input, endurl);
  678. // ensure there are spaces btw url and title
  679. endtitle = (starttitle == endurl) ? starttitle :
  680. starttitle + scan_link_title(&subj->input, starttitle);
  681. endall = endtitle + scan_spacechars(&subj->input, endtitle);
  682. if (peek_at(subj, endall) == ')') {
  683. subj->pos = endall + 1;
  684. url = chunk_dup(&subj->input, starturl, endurl - starturl);
  685. title = chunk_dup(&subj->input, starttitle, endtitle - starttitle);
  686. lab = parse_chunk_inlines(&rawlabel, NULL);
  687. return make_link(lab, url, title, 0);
  688. } else {
  689. // if we get here, we matched a label but didn't get further:
  690. subj->pos = endlabel;
  691. lab = parse_chunk_inlines(&rawlabel, subj->reference_map);
  692. result = append_inlines(make_str(chunk_literal("[")),
  693. append_inlines(lab,
  694. make_str(chunk_literal("]"))));
  695. return result;
  696. }
  697. } else {
  698. chunk rawlabel_tmp;
  699. chunk reflabel;
  700. // Check for reference link.
  701. // First, see if there's another label:
  702. subj->pos = subj->pos + scan_spacechars(&subj->input, endlabel);
  703. reflabel = rawlabel;
  704. // if followed by a nonempty link label, we change reflabel to it:
  705. if (peek_char(subj) == '[' && link_label(subj, &rawlabel_tmp)) {
  706. if (rawlabel_tmp.len > 0)
  707. reflabel = rawlabel_tmp;
  708. } else {
  709. subj->pos = endlabel;
  710. }
  711. // lookup rawlabel in subject->reference_map:
  712. ref = lookup_reference(subj->reference_map, &reflabel);
  713. if (ref != NULL) { // found
  714. lab = parse_chunk_inlines(&rawlabel, NULL);
  715. result = make_link_from_reference(lab, ref);
  716. } else {
  717. subj->pos = endlabel;
  718. lab = parse_chunk_inlines(&rawlabel, subj->reference_map);
  719. result = append_inlines(make_str(chunk_literal("[")),
  720. append_inlines(lab, make_str(chunk_literal("]"))));
  721. }
  722. return result;
  723. }
  724. }
  725. // If we fall through to here, it means we didn't match a link:
  726. advance(subj); // advance past [
  727. return make_str(chunk_literal("["));
  728. }
  729. // Parse a hard or soft linebreak, returning an inline.
  730. // Assumes the subject has a newline at the current position.
  731. static inl* handle_newline(subject *subj)
  732. {
  733. int nlpos = subj->pos;
  734. // skip over newline
  735. advance(subj);
  736. // skip spaces at beginning of line
  737. while (peek_char(subj) == ' ') {
  738. advance(subj);
  739. }
  740. if (nlpos > 1 &&
  741. peek_at(subj, nlpos - 1) == ' ' &&
  742. peek_at(subj, nlpos - 2) == ' ') {
  743. return make_linebreak();
  744. } else {
  745. return make_softbreak();
  746. }
  747. }
  748. inline static int not_eof(subject* subj)
  749. {
  750. return !is_eof(subj);
  751. }
  752. // Parse inlines while a predicate is satisfied. Return inlines.
  753. extern inl* parse_inlines_while(subject* subj, int (*f)(subject*))
  754. {
  755. inl* result = NULL;
  756. inl** last = &result;
  757. while ((*f)(subj) && parse_inline(subj, last)) {
  758. }
  759. return result;
  760. }
  761. inl *parse_chunk_inlines(chunk *chunk, reference** refmap)
  762. {
  763. subject subj;
  764. subject_from_chunk(&subj, chunk, refmap);
  765. return parse_inlines_while(&subj, not_eof);
  766. }
  767. static int subject_find_special_char(subject *subj)
  768. {
  769. int n = subj->pos + 1;
  770. while (n < subj->input.len) {
  771. if (strchr("\n\\`&_*[]<!", subj->input.data[n]))
  772. return n;
  773. n++;
  774. }
  775. return subj->input.len;
  776. }
  777. // Parse an inline, advancing subject, and add it to last element.
  778. // Adjust tail to point to new last element of list.
  779. // Return 0 if no inline can be parsed, 1 otherwise.
  780. static int parse_inline(subject* subj, inl ** last)
  781. {
  782. inl* new = NULL;
  783. chunk contents;
  784. unsigned char c;
  785. int endpos;
  786. c = peek_char(subj);
  787. if (c == 0) {
  788. return 0;
  789. }
  790. switch(c){
  791. case '\n':
  792. new = handle_newline(subj);
  793. break;
  794. case '`':
  795. new = handle_backticks(subj);
  796. break;
  797. case '\\':
  798. new = handle_backslash(subj);
  799. break;
  800. case '&':
  801. new = handle_entity(subj);
  802. break;
  803. case '<':
  804. new = handle_pointy_brace(subj);
  805. break;
  806. case '_':
  807. if (subj->pos > 0) {
  808. unsigned char prev = peek_at(subj, subj->pos - 1);
  809. if (isalnum(prev) || prev == '_') {
  810. new = make_str(chunk_literal("_"));
  811. advance(subj);
  812. break;
  813. }
  814. }
  815. new = handle_strong_emph(subj, '_');
  816. break;
  817. case '*':
  818. new = handle_strong_emph(subj, '*');
  819. break;
  820. case '[':
  821. new = handle_left_bracket(subj);
  822. break;
  823. case '!':
  824. advance(subj);
  825. if (peek_char(subj) == '[') {
  826. new = handle_left_bracket(subj);
  827. if (new != NULL && new->tag == INL_LINK) {
  828. new->tag = INL_IMAGE;
  829. } else {
  830. new = append_inlines(make_str(chunk_literal("!")), new);
  831. }
  832. } else {
  833. new = make_str(chunk_literal("!"));
  834. }
  835. break;
  836. default:
  837. endpos = subject_find_special_char(subj);
  838. contents = chunk_dup(&subj->input, subj->pos, endpos - subj->pos);
  839. subj->pos = endpos;
  840. // if we're at a newline, strip trailing spaces.
  841. if (peek_char(subj) == '\n') {
  842. chunk_rtrim(&contents);
  843. }
  844. new = make_str(contents);
  845. }
  846. if (*last == NULL) {
  847. *last = new;
  848. } else {
  849. append_inlines(*last, new);
  850. }
  851. return 1;
  852. }
  853. extern inl* parse_inlines(gh_buf *input, reference** refmap)
  854. {
  855. subject subj;
  856. subject_from_buf(&subj, input, refmap);
  857. return parse_inlines_while(&subj, not_eof);
  858. }
  859. // Parse zero or more space characters, including at most one newline.
  860. void spnl(subject* subj)
  861. {
  862. bool seen_newline = false;
  863. while (peek_char(subj) == ' ' ||
  864. (!seen_newline &&
  865. (seen_newline = peek_char(subj) == '\n'))) {
  866. advance(subj);
  867. }
  868. }
  869. // Parse reference. Assumes string begins with '[' character.
  870. // Modify refmap if a reference is encountered.
  871. // Return 0 if no reference found, otherwise position of subject
  872. // after reference is parsed.
  873. extern int parse_reference(gh_buf *input, reference** refmap)
  874. {
  875. subject subj;
  876. chunk lab;
  877. chunk url;
  878. chunk title;
  879. int matchlen = 0;
  880. int beforetitle;
  881. reference *new = NULL;
  882. subject_from_buf(&subj, input, NULL);
  883. // parse label:
  884. if (!link_label(&subj, &lab))
  885. return 0;
  886. // colon:
  887. if (peek_char(&subj) == ':') {
  888. advance(&subj);
  889. } else {
  890. return 0;
  891. }
  892. // parse link url:
  893. spnl(&subj);
  894. matchlen = scan_link_url(&subj.input, subj.pos);
  895. if (matchlen) {
  896. url = chunk_dup(&subj.input, subj.pos, matchlen);
  897. subj.pos += matchlen;
  898. } else {
  899. return 0;
  900. }
  901. // parse optional link_title
  902. beforetitle = subj.pos;
  903. spnl(&subj);
  904. matchlen = scan_link_title(&subj.input, subj.pos);
  905. if (matchlen) {
  906. title = chunk_dup(&subj.input, subj.pos, matchlen);
  907. subj.pos += matchlen;
  908. } else {
  909. subj.pos = beforetitle;
  910. title = chunk_literal("");
  911. }
  912. // parse final spaces and newline:
  913. while (peek_char(&subj) == ' ') {
  914. advance(&subj);
  915. }
  916. if (peek_char(&subj) == '\n') {
  917. advance(&subj);
  918. } else if (peek_char(&subj) != 0) {
  919. return 0;
  920. }
  921. // insert reference into refmap
  922. new = make_reference(&lab, &url, &title);
  923. add_reference(refmap, new);
  924. return subj.pos;
  925. }