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