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