aboutsummaryrefslogtreecommitdiff
path: root/src/inlines.c
blob: f75c846d43c5aa2ff434b0b72659caf1807f611d (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 (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 ? strong : emph;
  409. bdestroy(first_head->content.literal);
  410. first_head->content.inlines =
  411. make_inlines(first_close_delims == 1 ? emph : 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(bformat("%c", nextchar));
  455. } else if (nextchar == '\n') {
  456. advance(subj);
  457. return make_linebreak();
  458. } else {
  459. return make_str(bfromcstr("\\"));
  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->buffer, subj->pos);
  469. if (match) {
  470. result = make_entity(bmidstr(subj->buffer, subj->pos, match));
  471. subj->pos += match;
  472. } else {
  473. advance(subj);
  474. result = make_str(bfromcstr("&"));
  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(bstring s)
  481. {
  482. inl * result = NULL;
  483. inl * new;
  484. int searchpos;
  485. char c;
  486. subject * subj = make_subject(s, NULL);
  487. while ((c = peek_char(subj))) {
  488. switch (c) {
  489. case '&':
  490. new = handle_entity(subj);
  491. break;
  492. default:
  493. searchpos = bstrchrp(subj->buffer, '&', subj->pos);
  494. if (searchpos == BSTR_ERR) {
  495. searchpos = blength(subj->buffer);
  496. }
  497. new = make_str(bmidstr(subj->buffer, subj->pos, searchpos - subj->pos));
  498. subj->pos = searchpos;
  499. }
  500. result = append_inlines(result, new);
  501. }
  502. free(subj);
  503. return result;
  504. }
  505. // Destructively unescape a string: remove backslashes before punctuation chars.
  506. extern int unescape(bstring url)
  507. {
  508. // remove backslashes before punctuation chars:
  509. int searchpos = 0;
  510. while ((searchpos = bstrchrp(url, '\\', searchpos)) != BSTR_ERR) {
  511. if (ispunct(bchar(url, searchpos + 1))) {
  512. bdelete(url, searchpos, 1);
  513. } else {
  514. searchpos++;
  515. }
  516. }
  517. return 0;
  518. }
  519. // Clean a URL: remove surrounding whitespace and surrounding <>,
  520. // and remove \ that escape punctuation.
  521. static int clean_url(bstring url)
  522. {
  523. // remove surrounding <> if any:
  524. int urllength = blength(url);
  525. btrimws(url);
  526. if (bchar(url, 0) == '<' && bchar(url, urllength - 1) == '>') {
  527. bdelete(url, 0, 1);
  528. bdelete(url, urllength - 2, 1);
  529. }
  530. unescape(url);
  531. return 0;
  532. }
  533. // Clean a title: remove surrounding quotes and remove \ that escape punctuation.
  534. static int clean_title(bstring title)
  535. {
  536. // remove surrounding quotes if any:
  537. int titlelength = blength(title);
  538. if ((bchar(title, 0) == '\'' && bchar(title, titlelength - 1) == '\'') ||
  539. (bchar(title, 0) == '(' && bchar(title, titlelength - 1) == ')') ||
  540. (bchar(title, 0) == '"' && bchar(title, titlelength - 1) == '"')) {
  541. bdelete(title, 0, 1);
  542. bdelete(title, titlelength - 2, 1);
  543. }
  544. unescape(title);
  545. return 0;
  546. }
  547. // Parse an autolink or HTML tag.
  548. // Assumes the subject has a '<' character at the current position.
  549. static inl* handle_pointy_brace(subject* subj)
  550. {
  551. int matchlen = 0;
  552. bstring contents;
  553. inl* result;
  554. advance(subj); // advance past first <
  555. // first try to match a URL autolink
  556. matchlen = scan_autolink_uri(subj->buffer, subj->pos);
  557. if (matchlen > 0) {
  558. contents = bmidstr(subj->buffer, subj->pos, matchlen - 1);
  559. subj->pos += matchlen;
  560. result = make_link(make_str_with_entities(contents),
  561. bstrcpy(contents), bfromcstr(""));
  562. bdestroy(contents);
  563. return result;
  564. }
  565. // next try to match an email autolink
  566. matchlen = scan_autolink_email(subj->buffer, subj->pos);
  567. if (matchlen > 0) {
  568. contents = bmidstr(subj->buffer, subj->pos, matchlen - 1);
  569. subj->pos += matchlen;
  570. result = make_link(make_str_with_entities(contents),
  571. bformat("mailto:%s", contents->data),
  572. bfromcstr(""));
  573. bdestroy(contents);
  574. return result;
  575. }
  576. // finally, try to match an html tag
  577. matchlen = scan_html_tag(subj->buffer, subj->pos);
  578. if (matchlen > 0) {
  579. contents = bmidstr(subj->buffer, subj->pos, matchlen);
  580. binsertch(contents, 0, 1, '<');
  581. subj->pos += matchlen;
  582. return make_raw_html(contents);
  583. } else {// if nothing matches, just return the opening <:
  584. return make_str(bfromcstr("<"));
  585. }
  586. }
  587. // Parse a link label. Returns 1 if successful.
  588. // Unless raw_label is null, it is set to point to the raw contents of the [].
  589. // Assumes the subject has a '[' character at the current position.
  590. // Returns 0 and does not advance if no matching ] is found.
  591. // Note the precedence: code backticks have precedence over label bracket
  592. // markers, which have precedence over *, _, and other inline formatting
  593. // markers. So, 2 below contains a link while 1 does not:
  594. // 1. [a link `with a ](/url)` character
  595. // 2. [a link *with emphasized ](/url) text*
  596. static int link_label(subject* subj, bstring* raw_label)
  597. {
  598. int nestlevel = 0;
  599. inl* tmp = NULL;
  600. bstring raw;
  601. int startpos = subj->pos;
  602. if (subj->label_nestlevel) {
  603. // if we've already checked to the end of the subject
  604. // for a label, even with a different starting [, we
  605. // know we won't find one here and we can just return.
  606. // Note: nestlevel 1 would be: [foo [bar]
  607. // nestlevel 2 would be: [foo [bar [baz]
  608. subj->label_nestlevel--;
  609. return 0;
  610. }
  611. advance(subj); // advance past [
  612. char c;
  613. while ((c = peek_char(subj)) && (c != ']' || nestlevel > 0)) {
  614. switch (c) {
  615. case '`':
  616. tmp = handle_backticks(subj);
  617. free_inlines(tmp);
  618. break;
  619. case '<':
  620. tmp = handle_pointy_brace(subj);
  621. free_inlines(tmp);
  622. break;
  623. case '[': // nested []
  624. nestlevel++;
  625. advance(subj);
  626. break;
  627. case ']': // nested []
  628. nestlevel--;
  629. advance(subj);
  630. break;
  631. case '\\':
  632. advance(subj);
  633. if (ispunct(peek_char(subj))) {
  634. advance(subj);
  635. }
  636. break;
  637. default:
  638. advance(subj);
  639. }
  640. }
  641. if (c == ']') {
  642. if (raw_label != NULL) {
  643. raw = bmidstr(subj->buffer, startpos + 1, subj->pos - (startpos + 1));
  644. *raw_label = raw;
  645. }
  646. subj->label_nestlevel = 0;
  647. advance(subj); // advance past ]
  648. return 1;
  649. } else {
  650. if (c == 0) {
  651. subj->label_nestlevel = nestlevel;
  652. }
  653. subj->pos = startpos; // rewind
  654. return 0;
  655. }
  656. }
  657. // Parse a link or the link portion of an image, or return a fallback.
  658. static inl* handle_left_bracket(subject* subj)
  659. {
  660. inl* lab = NULL;
  661. inl* result = NULL;
  662. reference* ref;
  663. int n;
  664. int sps;
  665. int found_label;
  666. int endlabel, starturl, endurl, starttitle, endtitle, endall;
  667. bstring url, title, rawlabel, reflabel;
  668. bstring rawlabel2 = NULL;
  669. found_label = link_label(subj, &rawlabel);
  670. endlabel = subj->pos;
  671. if (found_label) {
  672. if (peek_char(subj) == '(' &&
  673. ((sps = scan_spacechars(subj->buffer, subj->pos + 1)) > -1) &&
  674. ((n = scan_link_url(subj->buffer, subj->pos + 1 + sps)) > -1)) {
  675. // try to parse an explicit link:
  676. starturl = subj->pos + 1 + sps; // after (
  677. endurl = starturl + n;
  678. starttitle = endurl + scan_spacechars(subj->buffer, endurl);
  679. // ensure there are spaces btw url and title
  680. endtitle = (starttitle == endurl) ? starttitle :
  681. starttitle + scan_link_title(subj->buffer, starttitle);
  682. endall = endtitle + scan_spacechars(subj->buffer, endtitle);
  683. if (bchar(subj->buffer, endall) == ')') {
  684. subj->pos = endall + 1;
  685. url = bmidstr(subj->buffer, starturl, endurl - starturl);
  686. clean_url(url);
  687. title = bmidstr(subj->buffer, starttitle, endtitle - starttitle);
  688. clean_title(title);
  689. lab = parse_inlines(rawlabel, NULL);
  690. bdestroy(rawlabel);
  691. return make_link(lab, url, title);
  692. } else {
  693. // if we get here, we matched a label but didn't get further:
  694. subj->pos = endlabel;
  695. lab = parse_inlines(rawlabel, subj->reference_map);
  696. bdestroy(rawlabel);
  697. result = append_inlines(make_str(bfromcstr("[")),
  698. append_inlines(lab,
  699. make_str(bfromcstr("]"))));
  700. return result;
  701. }
  702. } else {
  703. // Check for reference link.
  704. // First, see if there's another label:
  705. subj->pos = subj->pos + scan_spacechars(subj->buffer, endlabel);
  706. reflabel = rawlabel;
  707. // if followed by a nonempty link label, we change reflabel to it:
  708. if (peek_char(subj) == '[' &&
  709. link_label(subj, &rawlabel2)) {
  710. if (blength(rawlabel2) > 0) {
  711. reflabel = rawlabel2;
  712. }
  713. } else {
  714. subj->pos = endlabel;
  715. }
  716. // lookup rawlabel in subject->reference_map:
  717. ref = lookup_reference(subj->reference_map, reflabel);
  718. if (ref != NULL) { // found
  719. lab = parse_inlines(rawlabel, NULL);
  720. result = make_link(lab, bstrcpy(ref->url), bstrcpy(ref->title));
  721. } else {
  722. subj->pos = endlabel;
  723. lab = parse_inlines(rawlabel, subj->reference_map);
  724. result = append_inlines(make_str(bfromcstr("[")),
  725. append_inlines(lab, make_str(bfromcstr("]"))));
  726. }
  727. bdestroy(rawlabel);
  728. bdestroy(rawlabel2);
  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(bfromcstr("["));
  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. bchar(subj->buffer, nlpos - 1) == ' ' &&
  749. bchar(subj->buffer, 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. // Parse an inline, advancing subject, and add it to last element.
  769. // Adjust tail to point to new last element of list.
  770. // Return 0 if no inline can be parsed, 1 otherwise.
  771. extern int parse_inline(subject* subj, inl ** last)
  772. {
  773. inl* new = NULL;
  774. bstring contents;
  775. bstring special_chars;
  776. unsigned char c;
  777. int endpos;
  778. c = peek_char(subj);
  779. if (c == 0) {
  780. return 0;
  781. }
  782. switch(c){
  783. case '\n':
  784. new = handle_newline(subj);
  785. break;
  786. case '`':
  787. new = handle_backticks(subj);
  788. break;
  789. case '\\':
  790. new = handle_backslash(subj);
  791. break;
  792. case '&':
  793. new = handle_entity(subj);
  794. break;
  795. case '<':
  796. new = handle_pointy_brace(subj);
  797. break;
  798. case '_':
  799. if (subj->pos > 0 && (isalnum(bchar(subj->buffer, subj->pos - 1)) ||
  800. bchar(subj->buffer, subj->pos - 1) == '_')) {
  801. new = make_str(take_one(subj));
  802. } else {
  803. new = handle_strong_emph(subj, '_');
  804. }
  805. break;
  806. case '*':
  807. new = handle_strong_emph(subj, '*');
  808. break;
  809. case '[':
  810. new = handle_left_bracket(subj);
  811. break;
  812. case '!':
  813. advance(subj);
  814. if (peek_char(subj) == '[') {
  815. new = handle_left_bracket(subj);
  816. if (new != NULL && new->tag == link) {
  817. new->tag = image;
  818. } else {
  819. new = append_inlines(make_str(bfromcstr("!")), new);
  820. }
  821. } else {
  822. new = make_str(bfromcstr("!"));
  823. }
  824. break;
  825. default:
  826. // we read until we hit a special character
  827. special_chars = bfromcstr("\n\\`&_*[]<!");
  828. endpos = binchr(subj->buffer, subj->pos, special_chars);
  829. bdestroy(special_chars);
  830. if (endpos == subj->pos) {
  831. // current char is special: read a 1-character str
  832. contents = take_one(subj);
  833. } else if (endpos == BSTR_ERR) {
  834. // special char not found, take whole rest of buffer:
  835. endpos = subj->buffer->slen;
  836. contents = bmidstr(subj->buffer, subj->pos, endpos - subj->pos);
  837. subj->pos = endpos;
  838. } else {
  839. // take buffer from subj->pos to endpos to str.
  840. contents = bmidstr(subj->buffer, subj->pos, endpos - subj->pos);
  841. subj->pos = endpos;
  842. // if we're at a newline, strip trailing spaces.
  843. if (peek_char(subj) == '\n') {
  844. brtrimws(contents);
  845. }
  846. }
  847. new = make_str(contents);
  848. }
  849. if (*last == NULL) {
  850. *last = new;
  851. } else {
  852. append_inlines(*last, new);
  853. }
  854. return 1;
  855. }
  856. extern inl* parse_inlines(bstring input, reference** refmap)
  857. {
  858. subject * subj = make_subject(input, refmap);
  859. inl * result = parse_inlines_while(subj, not_eof);
  860. free(subj);
  861. return result;
  862. }
  863. // Parse zero or more space characters, including at most one newline.
  864. void spnl(subject* subj)
  865. {
  866. bool seen_newline = false;
  867. while (peek_char(subj) == ' ' ||
  868. (!seen_newline &&
  869. (seen_newline = peek_char(subj) == '\n'))) {
  870. advance(subj);
  871. }
  872. }
  873. // Parse reference. Assumes string begins with '[' character.
  874. // Modify refmap if a reference is encountered.
  875. // Return 0 if no reference found, otherwise position of subject
  876. // after reference is parsed.
  877. extern int parse_reference(bstring input, reference** refmap)
  878. {
  879. subject * subj = make_subject(input, NULL);
  880. bstring lab = NULL;
  881. bstring url = NULL;
  882. bstring title = NULL;
  883. int matchlen = 0;
  884. int beforetitle;
  885. reference * new = NULL;
  886. int newpos;
  887. // parse label:
  888. if (!link_label(subj, &lab)) {
  889. free(subj);
  890. return 0;
  891. }
  892. // colon:
  893. if (peek_char(subj) == ':') {
  894. advance(subj);
  895. } else {
  896. free(subj);
  897. bdestroy(lab);
  898. return 0;
  899. }
  900. // parse link url:
  901. spnl(subj);
  902. matchlen = scan_link_url(subj->buffer, subj->pos);
  903. if (matchlen) {
  904. url = bmidstr(subj->buffer, subj->pos, matchlen);
  905. clean_url(url);
  906. subj->pos += matchlen;
  907. } else {
  908. free(subj);
  909. bdestroy(lab);
  910. bdestroy(url);
  911. return 0;
  912. }
  913. // parse optional link_title
  914. beforetitle = subj->pos;
  915. spnl(subj);
  916. matchlen = scan_link_title(subj->buffer, subj->pos);
  917. if (matchlen) {
  918. title = bmidstr(subj->buffer, subj->pos, matchlen);
  919. clean_title(title);
  920. subj->pos += matchlen;
  921. } else {
  922. subj->pos = beforetitle;
  923. title = bfromcstr("");
  924. }
  925. // parse final spaces and newline:
  926. while (peek_char(subj) == ' ') {
  927. advance(subj);
  928. }
  929. if (peek_char(subj) == '\n') {
  930. advance(subj);
  931. } else if (peek_char(subj) != 0) {
  932. free(subj);
  933. bdestroy(lab);
  934. bdestroy(url);
  935. bdestroy(title);
  936. return 0;
  937. }
  938. // insert reference into refmap
  939. new = make_reference(lab, url, title);
  940. add_reference(refmap, new);
  941. newpos = subj->pos;
  942. free(subj);
  943. bdestroy(lab);
  944. bdestroy(url);
  945. bdestroy(title);
  946. return newpos;
  947. }