blocks.c 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  1. /**
  2. * Block parsing implementation.
  3. *
  4. * For a high-level overview of the block parsing process,
  5. * see http://spec.commonmark.org/0.24/#phase-1-block-structure
  6. */
  7. #include <stdlib.h>
  8. #include <assert.h>
  9. #include <stdio.h>
  10. #include "cmark_ctype.h"
  11. #include "config.h"
  12. #include "parser.h"
  13. #include "cmark.h"
  14. #include "node.h"
  15. #include "references.h"
  16. #include "utf8.h"
  17. #include "scanners.h"
  18. #include "inlines.h"
  19. #include "houdini.h"
  20. #include "buffer.h"
  21. #define CODE_INDENT 4
  22. #define TAB_STOP 4
  23. #ifndef MIN
  24. #define MIN(x, y) ((x < y) ? x : y)
  25. #endif
  26. #define peek_at(i, n) (i)->data[n]
  27. static bool S_last_line_blank(const cmark_node *node) {
  28. return (node->flags & CMARK_NODE__LAST_LINE_BLANK) != 0;
  29. }
  30. static bool S_last_line_checked(const cmark_node *node) {
  31. return (node->flags & CMARK_NODE__LAST_LINE_CHECKED) != 0;
  32. }
  33. static CMARK_INLINE cmark_node_type S_type(const cmark_node *node) {
  34. return (cmark_node_type)node->type;
  35. }
  36. static void S_set_last_line_blank(cmark_node *node, bool is_blank) {
  37. if (is_blank)
  38. node->flags |= CMARK_NODE__LAST_LINE_BLANK;
  39. else
  40. node->flags &= ~CMARK_NODE__LAST_LINE_BLANK;
  41. }
  42. static void S_set_last_line_checked(cmark_node *node) {
  43. node->flags |= CMARK_NODE__LAST_LINE_CHECKED;
  44. }
  45. static CMARK_INLINE bool S_is_line_end_char(char c) {
  46. return (c == '\n' || c == '\r');
  47. }
  48. static CMARK_INLINE bool S_is_space_or_tab(char c) {
  49. return (c == ' ' || c == '\t');
  50. }
  51. static void S_parser_feed(cmark_parser *parser, const unsigned char *buffer,
  52. size_t len, bool eof);
  53. static void S_process_line(cmark_parser *parser, const unsigned char *buffer,
  54. bufsize_t bytes);
  55. static cmark_node *make_block(cmark_mem *mem, cmark_node_type tag,
  56. int start_line, int start_column) {
  57. cmark_node *e;
  58. e = (cmark_node *)mem->calloc(1, sizeof(*e));
  59. cmark_strbuf_init(mem, &e->content, 32);
  60. e->type = (uint16_t)tag;
  61. e->flags = CMARK_NODE__OPEN;
  62. e->start_line = start_line;
  63. e->start_column = start_column;
  64. e->end_line = start_line;
  65. return e;
  66. }
  67. // Create a root document node.
  68. static cmark_node *make_document(cmark_mem *mem) {
  69. cmark_node *e = make_block(mem, CMARK_NODE_DOCUMENT, 1, 1);
  70. return e;
  71. }
  72. cmark_parser *cmark_parser_new_with_mem(int options, cmark_mem *mem) {
  73. cmark_parser *parser = (cmark_parser *)mem->calloc(1, sizeof(cmark_parser));
  74. parser->mem = mem;
  75. cmark_node *document = make_document(mem);
  76. cmark_strbuf_init(mem, &parser->curline, 256);
  77. cmark_strbuf_init(mem, &parser->linebuf, 0);
  78. parser->refmap = cmark_reference_map_new(mem);
  79. parser->root = document;
  80. parser->current = document;
  81. parser->line_number = 0;
  82. parser->offset = 0;
  83. parser->column = 0;
  84. parser->first_nonspace = 0;
  85. parser->first_nonspace_column = 0;
  86. parser->thematic_break_kill_pos = 0;
  87. parser->indent = 0;
  88. parser->blank = false;
  89. parser->partially_consumed_tab = false;
  90. parser->last_line_length = 0;
  91. parser->options = options;
  92. parser->last_buffer_ended_with_cr = false;
  93. return parser;
  94. }
  95. cmark_parser *cmark_parser_new(int options) {
  96. extern cmark_mem DEFAULT_MEM_ALLOCATOR;
  97. return cmark_parser_new_with_mem(options, &DEFAULT_MEM_ALLOCATOR);
  98. }
  99. void cmark_parser_free(cmark_parser *parser) {
  100. cmark_mem *mem = parser->mem;
  101. cmark_strbuf_free(&parser->curline);
  102. cmark_strbuf_free(&parser->linebuf);
  103. cmark_reference_map_free(parser->refmap);
  104. mem->free(parser);
  105. }
  106. static cmark_node *finalize(cmark_parser *parser, cmark_node *b);
  107. // Returns true if line has only space characters, else false.
  108. static bool is_blank(cmark_strbuf *s, bufsize_t offset) {
  109. while (offset < s->size) {
  110. switch (s->ptr[offset]) {
  111. case '\r':
  112. case '\n':
  113. return true;
  114. case ' ':
  115. offset++;
  116. break;
  117. case '\t':
  118. offset++;
  119. break;
  120. default:
  121. return false;
  122. }
  123. }
  124. return true;
  125. }
  126. static CMARK_INLINE bool can_contain(cmark_node_type parent_type,
  127. cmark_node_type child_type) {
  128. return (parent_type == CMARK_NODE_DOCUMENT ||
  129. parent_type == CMARK_NODE_BLOCK_QUOTE ||
  130. parent_type == CMARK_NODE_ITEM ||
  131. (parent_type == CMARK_NODE_LIST && child_type == CMARK_NODE_ITEM));
  132. }
  133. static CMARK_INLINE bool accepts_lines(cmark_node_type block_type) {
  134. return (block_type == CMARK_NODE_PARAGRAPH ||
  135. block_type == CMARK_NODE_HEADING ||
  136. block_type == CMARK_NODE_CODE_BLOCK);
  137. }
  138. static CMARK_INLINE bool contains_inlines(cmark_node_type block_type) {
  139. return (block_type == CMARK_NODE_PARAGRAPH ||
  140. block_type == CMARK_NODE_HEADING);
  141. }
  142. static void add_line(cmark_node *node, cmark_chunk *ch, cmark_parser *parser) {
  143. int chars_to_tab;
  144. int i;
  145. assert(node->flags & CMARK_NODE__OPEN);
  146. if (parser->partially_consumed_tab) {
  147. parser->offset += 1; // skip over tab
  148. // add space characters:
  149. chars_to_tab = TAB_STOP - (parser->column % TAB_STOP);
  150. for (i = 0; i < chars_to_tab; i++) {
  151. cmark_strbuf_putc(&node->content, ' ');
  152. }
  153. }
  154. cmark_strbuf_put(&node->content, ch->data + parser->offset,
  155. ch->len - parser->offset);
  156. }
  157. static void remove_trailing_blank_lines(cmark_strbuf *ln) {
  158. bufsize_t i;
  159. unsigned char c;
  160. for (i = ln->size - 1; i >= 0; --i) {
  161. c = ln->ptr[i];
  162. if (c != ' ' && c != '\t' && !S_is_line_end_char(c))
  163. break;
  164. }
  165. if (i < 0) {
  166. cmark_strbuf_clear(ln);
  167. return;
  168. }
  169. for (; i < ln->size; ++i) {
  170. c = ln->ptr[i];
  171. if (!S_is_line_end_char(c))
  172. continue;
  173. cmark_strbuf_truncate(ln, i);
  174. break;
  175. }
  176. }
  177. // Check to see if a node ends with a blank line, descending
  178. // if needed into lists and sublists.
  179. static bool S_ends_with_blank_line(cmark_node *node) {
  180. if (S_last_line_checked(node)) {
  181. return(S_last_line_blank(node));
  182. } else if ((S_type(node) == CMARK_NODE_LIST ||
  183. S_type(node) == CMARK_NODE_ITEM) && node->last_child) {
  184. S_set_last_line_checked(node);
  185. return(S_ends_with_blank_line(node->last_child));
  186. } else {
  187. S_set_last_line_checked(node);
  188. return (S_last_line_blank(node));
  189. }
  190. }
  191. // returns true if content remains after link defs are resolved.
  192. static bool resolve_reference_link_definitions(
  193. cmark_parser *parser,
  194. cmark_node *b) {
  195. bufsize_t pos;
  196. cmark_strbuf *node_content = &b->content;
  197. cmark_chunk chunk = {node_content->ptr, node_content->size, 0};
  198. while (chunk.len && chunk.data[0] == '[' &&
  199. (pos = cmark_parse_reference_inline(parser->mem, &chunk,
  200. parser->refmap))) {
  201. chunk.data += pos;
  202. chunk.len -= pos;
  203. }
  204. cmark_strbuf_drop(node_content, (node_content->size - chunk.len));
  205. return !is_blank(&b->content, 0);
  206. }
  207. static cmark_node *finalize(cmark_parser *parser, cmark_node *b) {
  208. bufsize_t pos;
  209. cmark_node *item;
  210. cmark_node *subitem;
  211. cmark_node *parent;
  212. bool has_content;
  213. parent = b->parent;
  214. assert(b->flags &
  215. CMARK_NODE__OPEN); // shouldn't call finalize on closed blocks
  216. b->flags &= ~CMARK_NODE__OPEN;
  217. if (parser->curline.size == 0) {
  218. // end of input - line number has not been incremented
  219. b->end_line = parser->line_number;
  220. b->end_column = parser->last_line_length;
  221. } else if (S_type(b) == CMARK_NODE_DOCUMENT ||
  222. (S_type(b) == CMARK_NODE_CODE_BLOCK && b->as.code.fenced) ||
  223. (S_type(b) == CMARK_NODE_HEADING && b->as.heading.setext)) {
  224. b->end_line = parser->line_number;
  225. b->end_column = parser->curline.size;
  226. if (b->end_column && parser->curline.ptr[b->end_column - 1] == '\n')
  227. b->end_column -= 1;
  228. if (b->end_column && parser->curline.ptr[b->end_column - 1] == '\r')
  229. b->end_column -= 1;
  230. } else {
  231. b->end_line = parser->line_number - 1;
  232. b->end_column = parser->last_line_length;
  233. }
  234. cmark_strbuf *node_content = &b->content;
  235. switch (S_type(b)) {
  236. case CMARK_NODE_PARAGRAPH:
  237. {
  238. has_content = resolve_reference_link_definitions(parser, b);
  239. if (!has_content) {
  240. // remove blank node (former reference def)
  241. cmark_node_free(b);
  242. }
  243. break;
  244. }
  245. case CMARK_NODE_CODE_BLOCK:
  246. if (!b->as.code.fenced) { // indented code
  247. remove_trailing_blank_lines(node_content);
  248. cmark_strbuf_putc(node_content, '\n');
  249. } else {
  250. // first line of contents becomes info
  251. for (pos = 0; pos < node_content->size; ++pos) {
  252. if (S_is_line_end_char(node_content->ptr[pos]))
  253. break;
  254. }
  255. assert(pos < node_content->size);
  256. cmark_strbuf tmp = CMARK_BUF_INIT(parser->mem);
  257. houdini_unescape_html_f(&tmp, node_content->ptr, pos);
  258. cmark_strbuf_trim(&tmp);
  259. cmark_strbuf_unescape(&tmp);
  260. b->as.code.info = cmark_chunk_buf_detach(&tmp);
  261. if (node_content->ptr[pos] == '\r')
  262. pos += 1;
  263. if (node_content->ptr[pos] == '\n')
  264. pos += 1;
  265. cmark_strbuf_drop(node_content, pos);
  266. }
  267. b->as.code.literal = cmark_chunk_buf_detach(node_content);
  268. break;
  269. case CMARK_NODE_HTML_BLOCK:
  270. b->as.literal = cmark_chunk_buf_detach(node_content);
  271. break;
  272. case CMARK_NODE_LIST: // determine tight/loose status
  273. b->as.list.tight = true; // tight by default
  274. item = b->first_child;
  275. while (item) {
  276. // check for non-final non-empty list item ending with blank line:
  277. if (S_last_line_blank(item) && item->next) {
  278. b->as.list.tight = false;
  279. break;
  280. }
  281. // recurse into children of list item, to see if there are
  282. // spaces between them:
  283. subitem = item->first_child;
  284. while (subitem) {
  285. if ((item->next || subitem->next) &&
  286. S_ends_with_blank_line(subitem)) {
  287. b->as.list.tight = false;
  288. break;
  289. }
  290. subitem = subitem->next;
  291. }
  292. if (!(b->as.list.tight)) {
  293. break;
  294. }
  295. item = item->next;
  296. }
  297. break;
  298. default:
  299. break;
  300. }
  301. return parent;
  302. }
  303. // Add a node as child of another. Return pointer to child.
  304. static cmark_node *add_child(cmark_parser *parser, cmark_node *parent,
  305. cmark_node_type block_type, int start_column) {
  306. assert(parent);
  307. // if 'parent' isn't the kind of node that can accept this child,
  308. // then back up til we hit a node that can.
  309. while (!can_contain(S_type(parent), block_type)) {
  310. parent = finalize(parser, parent);
  311. }
  312. cmark_node *child =
  313. make_block(parser->mem, block_type, parser->line_number, start_column);
  314. child->parent = parent;
  315. if (parent->last_child) {
  316. parent->last_child->next = child;
  317. child->prev = parent->last_child;
  318. } else {
  319. parent->first_child = child;
  320. child->prev = NULL;
  321. }
  322. parent->last_child = child;
  323. return child;
  324. }
  325. // Walk through node and all children, recursively, parsing
  326. // string content into inline content where appropriate.
  327. static void process_inlines(cmark_mem *mem, cmark_node *root,
  328. cmark_reference_map *refmap, int options) {
  329. cmark_iter *iter = cmark_iter_new(root);
  330. cmark_node *cur;
  331. cmark_event_type ev_type;
  332. while ((ev_type = cmark_iter_next(iter)) != CMARK_EVENT_DONE) {
  333. cur = cmark_iter_get_node(iter);
  334. if (ev_type == CMARK_EVENT_ENTER) {
  335. if (contains_inlines(S_type(cur))) {
  336. cmark_parse_inlines(mem, cur, refmap, options);
  337. }
  338. }
  339. }
  340. cmark_iter_free(iter);
  341. }
  342. // Attempts to parse a list item marker (bullet or enumerated).
  343. // On success, returns length of the marker, and populates
  344. // data with the details. On failure, returns 0.
  345. static bufsize_t parse_list_marker(cmark_mem *mem, cmark_chunk *input,
  346. bufsize_t pos, bool interrupts_paragraph,
  347. cmark_list **dataptr) {
  348. unsigned char c;
  349. bufsize_t startpos;
  350. cmark_list *data;
  351. bufsize_t i;
  352. startpos = pos;
  353. c = peek_at(input, pos);
  354. if (c == '*' || c == '-' || c == '+') {
  355. pos++;
  356. if (!cmark_isspace(peek_at(input, pos))) {
  357. return 0;
  358. }
  359. if (interrupts_paragraph) {
  360. i = pos;
  361. // require non-blank content after list marker:
  362. while (S_is_space_or_tab(peek_at(input, i))) {
  363. i++;
  364. }
  365. if (peek_at(input, i) == '\n') {
  366. return 0;
  367. }
  368. }
  369. data = (cmark_list *)mem->calloc(1, sizeof(*data));
  370. data->marker_offset = 0; // will be adjusted later
  371. data->list_type = CMARK_BULLET_LIST;
  372. data->bullet_char = c;
  373. data->start = 0;
  374. data->delimiter = CMARK_NO_DELIM;
  375. data->tight = false;
  376. } else if (cmark_isdigit(c)) {
  377. int start = 0;
  378. int digits = 0;
  379. do {
  380. start = (10 * start) + (peek_at(input, pos) - '0');
  381. pos++;
  382. digits++;
  383. // We limit to 9 digits to avoid overflow,
  384. // assuming max int is 2^31 - 1
  385. // This also seems to be the limit for 'start' in some browsers.
  386. } while (digits < 9 && cmark_isdigit(peek_at(input, pos)));
  387. if (interrupts_paragraph && start != 1) {
  388. return 0;
  389. }
  390. c = peek_at(input, pos);
  391. if (c == '.' || c == ')') {
  392. pos++;
  393. if (!cmark_isspace(peek_at(input, pos))) {
  394. return 0;
  395. }
  396. if (interrupts_paragraph) {
  397. // require non-blank content after list marker:
  398. i = pos;
  399. while (S_is_space_or_tab(peek_at(input, i))) {
  400. i++;
  401. }
  402. if (S_is_line_end_char(peek_at(input, i))) {
  403. return 0;
  404. }
  405. }
  406. data = (cmark_list *)mem->calloc(1, sizeof(*data));
  407. data->marker_offset = 0; // will be adjusted later
  408. data->list_type = CMARK_ORDERED_LIST;
  409. data->bullet_char = 0;
  410. data->start = start;
  411. data->delimiter = (c == '.' ? CMARK_PERIOD_DELIM : CMARK_PAREN_DELIM);
  412. data->tight = false;
  413. } else {
  414. return 0;
  415. }
  416. } else {
  417. return 0;
  418. }
  419. *dataptr = data;
  420. return (pos - startpos);
  421. }
  422. // Return 1 if list item belongs in list, else 0.
  423. static int lists_match(cmark_list *list_data, cmark_list *item_data) {
  424. return (list_data->list_type == item_data->list_type &&
  425. list_data->delimiter == item_data->delimiter &&
  426. // list_data->marker_offset == item_data.marker_offset &&
  427. list_data->bullet_char == item_data->bullet_char);
  428. }
  429. static cmark_node *finalize_document(cmark_parser *parser) {
  430. while (parser->current != parser->root) {
  431. parser->current = finalize(parser, parser->current);
  432. }
  433. finalize(parser, parser->root);
  434. process_inlines(parser->mem, parser->root, parser->refmap, parser->options);
  435. return parser->root;
  436. }
  437. cmark_node *cmark_parse_file(FILE *f, int options) {
  438. unsigned char buffer[4096];
  439. cmark_parser *parser = cmark_parser_new(options);
  440. size_t bytes;
  441. cmark_node *document;
  442. while ((bytes = fread(buffer, 1, sizeof(buffer), f)) > 0) {
  443. bool eof = bytes < sizeof(buffer);
  444. S_parser_feed(parser, buffer, bytes, eof);
  445. if (eof) {
  446. break;
  447. }
  448. }
  449. document = cmark_parser_finish(parser);
  450. cmark_parser_free(parser);
  451. return document;
  452. }
  453. cmark_node *cmark_parse_document(const char *buffer, size_t len, int options) {
  454. cmark_parser *parser = cmark_parser_new(options);
  455. cmark_node *document;
  456. S_parser_feed(parser, (const unsigned char *)buffer, len, true);
  457. document = cmark_parser_finish(parser);
  458. cmark_parser_free(parser);
  459. return document;
  460. }
  461. void cmark_parser_feed(cmark_parser *parser, const char *buffer, size_t len) {
  462. S_parser_feed(parser, (const unsigned char *)buffer, len, false);
  463. }
  464. static void S_parser_feed(cmark_parser *parser, const unsigned char *buffer,
  465. size_t len, bool eof) {
  466. const unsigned char *end = buffer + len;
  467. static const uint8_t repl[] = {239, 191, 189};
  468. if (parser->last_buffer_ended_with_cr && *buffer == '\n') {
  469. // skip NL if last buffer ended with CR ; see #117
  470. buffer++;
  471. }
  472. parser->last_buffer_ended_with_cr = false;
  473. while (buffer < end) {
  474. const unsigned char *eol;
  475. bufsize_t chunk_len;
  476. bool process = false;
  477. for (eol = buffer; eol < end; ++eol) {
  478. if (S_is_line_end_char(*eol)) {
  479. process = true;
  480. break;
  481. }
  482. if (*eol == '\0' && eol < end) {
  483. break;
  484. }
  485. }
  486. if (eol >= end && eof) {
  487. process = true;
  488. }
  489. chunk_len = (eol - buffer);
  490. if (process) {
  491. if (parser->linebuf.size > 0) {
  492. cmark_strbuf_put(&parser->linebuf, buffer, chunk_len);
  493. S_process_line(parser, parser->linebuf.ptr, parser->linebuf.size);
  494. cmark_strbuf_clear(&parser->linebuf);
  495. } else {
  496. S_process_line(parser, buffer, chunk_len);
  497. }
  498. } else {
  499. if (eol < end && *eol == '\0') {
  500. // omit NULL byte
  501. cmark_strbuf_put(&parser->linebuf, buffer, chunk_len);
  502. // add replacement character
  503. cmark_strbuf_put(&parser->linebuf, repl, 3);
  504. } else {
  505. cmark_strbuf_put(&parser->linebuf, buffer, chunk_len);
  506. }
  507. }
  508. buffer += chunk_len;
  509. if (buffer < end) {
  510. if (*buffer == '\0') {
  511. // skip over NULL
  512. buffer++;
  513. } else {
  514. // skip over line ending characters
  515. if (*buffer == '\r') {
  516. buffer++;
  517. if (buffer == end)
  518. parser->last_buffer_ended_with_cr = true;
  519. }
  520. if (buffer < end && *buffer == '\n')
  521. buffer++;
  522. }
  523. }
  524. }
  525. }
  526. static void chop_trailing_hashtags(cmark_chunk *ch) {
  527. bufsize_t n, orig_n;
  528. cmark_chunk_rtrim(ch);
  529. orig_n = n = ch->len - 1;
  530. // if string ends in space followed by #s, remove these:
  531. while (n >= 0 && peek_at(ch, n) == '#')
  532. n--;
  533. // Check for a space before the final #s:
  534. if (n != orig_n && n >= 0 && S_is_space_or_tab(peek_at(ch, n))) {
  535. ch->len = n;
  536. cmark_chunk_rtrim(ch);
  537. }
  538. }
  539. // Check for thematic break. On failure, return 0 and update
  540. // thematic_break_kill_pos with the index at which the
  541. // parse fails. On success, return length of match.
  542. // "...three or more hyphens, asterisks,
  543. // or underscores on a line by themselves. If you wish, you may use
  544. // spaces between the hyphens or asterisks."
  545. static int S_scan_thematic_break(cmark_parser *parser, cmark_chunk *input,
  546. bufsize_t offset) {
  547. bufsize_t i;
  548. char c;
  549. char nextc = '\0';
  550. int count;
  551. i = offset;
  552. c = peek_at(input, i);
  553. if (!(c == '*' || c == '_' || c == '-')) {
  554. parser->thematic_break_kill_pos = i;
  555. return 0;
  556. }
  557. count = 1;
  558. while ((nextc = peek_at(input, ++i))) {
  559. if (nextc == c) {
  560. count++;
  561. } else if (nextc != ' ' && nextc != '\t') {
  562. break;
  563. }
  564. }
  565. if (count >= 3 && (nextc == '\r' || nextc == '\n')) {
  566. return (i - offset) + 1;
  567. } else {
  568. parser->thematic_break_kill_pos = i;
  569. return 0;
  570. }
  571. }
  572. // Find first nonspace character from current offset, setting
  573. // parser->first_nonspace, parser->first_nonspace_column,
  574. // parser->indent, and parser->blank. Does not advance parser->offset.
  575. static void S_find_first_nonspace(cmark_parser *parser, cmark_chunk *input) {
  576. char c;
  577. int chars_to_tab = TAB_STOP - (parser->column % TAB_STOP);
  578. if (parser->first_nonspace <= parser->offset) {
  579. parser->first_nonspace = parser->offset;
  580. parser->first_nonspace_column = parser->column;
  581. while ((c = peek_at(input, parser->first_nonspace))) {
  582. if (c == ' ') {
  583. parser->first_nonspace += 1;
  584. parser->first_nonspace_column += 1;
  585. chars_to_tab = chars_to_tab - 1;
  586. if (chars_to_tab == 0) {
  587. chars_to_tab = TAB_STOP;
  588. }
  589. } else if (c == '\t') {
  590. parser->first_nonspace += 1;
  591. parser->first_nonspace_column += chars_to_tab;
  592. chars_to_tab = TAB_STOP;
  593. } else {
  594. break;
  595. }
  596. }
  597. }
  598. parser->indent = parser->first_nonspace_column - parser->column;
  599. parser->blank = S_is_line_end_char(peek_at(input, parser->first_nonspace));
  600. }
  601. // Advance parser->offset and parser->column. parser->offset is the
  602. // byte position in input; parser->column is a virtual column number
  603. // that takes into account tabs. (Multibyte characters are not taken
  604. // into account, because the Markdown line prefixes we are interested in
  605. // analyzing are entirely ASCII.) The count parameter indicates
  606. // how far to advance the offset. If columns is true, then count
  607. // indicates a number of columns; otherwise, a number of bytes.
  608. // If advancing a certain number of columns partially consumes
  609. // a tab character, parser->partially_consumed_tab is set to true.
  610. static void S_advance_offset(cmark_parser *parser, cmark_chunk *input,
  611. bufsize_t count, bool columns) {
  612. char c;
  613. int chars_to_tab;
  614. int chars_to_advance;
  615. while (count > 0 && (c = peek_at(input, parser->offset))) {
  616. if (c == '\t') {
  617. chars_to_tab = TAB_STOP - (parser->column % TAB_STOP);
  618. if (columns) {
  619. parser->partially_consumed_tab = chars_to_tab > count;
  620. chars_to_advance = MIN(count, chars_to_tab);
  621. parser->column += chars_to_advance;
  622. parser->offset += (parser->partially_consumed_tab ? 0 : 1);
  623. count -= chars_to_advance;
  624. } else {
  625. parser->partially_consumed_tab = false;
  626. parser->column += chars_to_tab;
  627. parser->offset += 1;
  628. count -= 1;
  629. }
  630. } else {
  631. parser->partially_consumed_tab = false;
  632. parser->offset += 1;
  633. parser->column += 1; // assume ascii; block starts are ascii
  634. count -= 1;
  635. }
  636. }
  637. }
  638. static bool S_last_child_is_open(cmark_node *container) {
  639. return container->last_child &&
  640. (container->last_child->flags & CMARK_NODE__OPEN);
  641. }
  642. static bool parse_block_quote_prefix(cmark_parser *parser, cmark_chunk *input) {
  643. bool res = false;
  644. bufsize_t matched = 0;
  645. matched =
  646. parser->indent <= 3 && peek_at(input, parser->first_nonspace) == '>';
  647. if (matched) {
  648. S_advance_offset(parser, input, parser->indent + 1, true);
  649. if (S_is_space_or_tab(peek_at(input, parser->offset))) {
  650. S_advance_offset(parser, input, 1, true);
  651. }
  652. res = true;
  653. }
  654. return res;
  655. }
  656. static bool parse_node_item_prefix(cmark_parser *parser, cmark_chunk *input,
  657. cmark_node *container) {
  658. bool res = false;
  659. if (parser->indent >=
  660. container->as.list.marker_offset + container->as.list.padding) {
  661. S_advance_offset(parser, input, container->as.list.marker_offset +
  662. container->as.list.padding,
  663. true);
  664. res = true;
  665. } else if (parser->blank && container->first_child != NULL) {
  666. // if container->first_child is NULL, then the opening line
  667. // of the list item was blank after the list marker; in this
  668. // case, we are done with the list item.
  669. S_advance_offset(parser, input, parser->first_nonspace - parser->offset,
  670. false);
  671. res = true;
  672. }
  673. return res;
  674. }
  675. static bool parse_code_block_prefix(cmark_parser *parser, cmark_chunk *input,
  676. cmark_node *container,
  677. bool *should_continue) {
  678. bool res = false;
  679. if (!container->as.code.fenced) { // indented
  680. if (parser->indent >= CODE_INDENT) {
  681. S_advance_offset(parser, input, CODE_INDENT, true);
  682. res = true;
  683. } else if (parser->blank) {
  684. S_advance_offset(parser, input, parser->first_nonspace - parser->offset,
  685. false);
  686. res = true;
  687. }
  688. } else { // fenced
  689. bufsize_t matched = 0;
  690. if (parser->indent <= 3 && (peek_at(input, parser->first_nonspace) ==
  691. container->as.code.fence_char)) {
  692. matched = scan_close_code_fence(input, parser->first_nonspace);
  693. }
  694. if (matched >= container->as.code.fence_length) {
  695. // closing fence - and since we're at
  696. // the end of a line, we can stop processing it:
  697. *should_continue = false;
  698. S_advance_offset(parser, input, matched, false);
  699. parser->current = finalize(parser, container);
  700. } else {
  701. // skip opt. spaces of fence parser->offset
  702. int i = container->as.code.fence_offset;
  703. while (i > 0 && S_is_space_or_tab(peek_at(input, parser->offset))) {
  704. S_advance_offset(parser, input, 1, true);
  705. i--;
  706. }
  707. res = true;
  708. }
  709. }
  710. return res;
  711. }
  712. static bool parse_html_block_prefix(cmark_parser *parser,
  713. cmark_node *container) {
  714. bool res = false;
  715. int html_block_type = container->as.html_block_type;
  716. assert(html_block_type >= 1 && html_block_type <= 7);
  717. switch (html_block_type) {
  718. case 1:
  719. case 2:
  720. case 3:
  721. case 4:
  722. case 5:
  723. // these types of blocks can accept blanks
  724. res = true;
  725. break;
  726. case 6:
  727. case 7:
  728. res = !parser->blank;
  729. break;
  730. }
  731. return res;
  732. }
  733. /**
  734. * For each containing node, try to parse the associated line start.
  735. *
  736. * Will not close unmatched blocks, as we may have a lazy continuation
  737. * line -> http://spec.commonmark.org/0.24/#lazy-continuation-line
  738. *
  739. * Returns: The last matching node, or NULL
  740. */
  741. static cmark_node *check_open_blocks(cmark_parser *parser, cmark_chunk *input,
  742. bool *all_matched) {
  743. bool should_continue = true;
  744. *all_matched = false;
  745. cmark_node *container = parser->root;
  746. cmark_node_type cont_type;
  747. while (S_last_child_is_open(container)) {
  748. container = container->last_child;
  749. cont_type = S_type(container);
  750. S_find_first_nonspace(parser, input);
  751. switch (cont_type) {
  752. case CMARK_NODE_BLOCK_QUOTE:
  753. if (!parse_block_quote_prefix(parser, input))
  754. goto done;
  755. break;
  756. case CMARK_NODE_ITEM:
  757. if (!parse_node_item_prefix(parser, input, container))
  758. goto done;
  759. break;
  760. case CMARK_NODE_CODE_BLOCK:
  761. if (!parse_code_block_prefix(parser, input, container, &should_continue))
  762. goto done;
  763. break;
  764. case CMARK_NODE_HEADING:
  765. // a heading can never contain more than one line
  766. goto done;
  767. case CMARK_NODE_HTML_BLOCK:
  768. if (!parse_html_block_prefix(parser, container))
  769. goto done;
  770. break;
  771. case CMARK_NODE_PARAGRAPH:
  772. if (parser->blank)
  773. goto done;
  774. break;
  775. default:
  776. break;
  777. }
  778. }
  779. *all_matched = true;
  780. done:
  781. if (!*all_matched) {
  782. container = container->parent; // back up to last matching node
  783. }
  784. if (!should_continue) {
  785. container = NULL;
  786. }
  787. return container;
  788. }
  789. static void open_new_blocks(cmark_parser *parser, cmark_node **container,
  790. cmark_chunk *input, bool all_matched) {
  791. bool indented;
  792. cmark_list *data = NULL;
  793. bool maybe_lazy = S_type(parser->current) == CMARK_NODE_PARAGRAPH;
  794. cmark_node_type cont_type = S_type(*container);
  795. bufsize_t matched = 0;
  796. int lev = 0;
  797. bool save_partially_consumed_tab;
  798. bool has_content;
  799. int save_offset;
  800. int save_column;
  801. while (cont_type != CMARK_NODE_CODE_BLOCK &&
  802. cont_type != CMARK_NODE_HTML_BLOCK) {
  803. S_find_first_nonspace(parser, input);
  804. indented = parser->indent >= CODE_INDENT;
  805. if (!indented && peek_at(input, parser->first_nonspace) == '>') {
  806. bufsize_t blockquote_startpos = parser->first_nonspace;
  807. S_advance_offset(parser, input,
  808. parser->first_nonspace + 1 - parser->offset, false);
  809. // optional following character
  810. if (S_is_space_or_tab(peek_at(input, parser->offset))) {
  811. S_advance_offset(parser, input, 1, true);
  812. }
  813. *container = add_child(parser, *container, CMARK_NODE_BLOCK_QUOTE,
  814. blockquote_startpos + 1);
  815. } else if (!indented && (matched = scan_atx_heading_start(
  816. input, parser->first_nonspace))) {
  817. bufsize_t hashpos;
  818. int level = 0;
  819. bufsize_t heading_startpos = parser->first_nonspace;
  820. S_advance_offset(parser, input,
  821. parser->first_nonspace + matched - parser->offset,
  822. false);
  823. *container = add_child(parser, *container, CMARK_NODE_HEADING,
  824. heading_startpos + 1);
  825. hashpos = cmark_chunk_strchr(input, '#', parser->first_nonspace);
  826. while (peek_at(input, hashpos) == '#') {
  827. level++;
  828. hashpos++;
  829. }
  830. (*container)->as.heading.level = level;
  831. (*container)->as.heading.setext = false;
  832. (*container)->internal_offset = matched;
  833. } else if (!indented && (matched = scan_open_code_fence(
  834. input, parser->first_nonspace))) {
  835. *container = add_child(parser, *container, CMARK_NODE_CODE_BLOCK,
  836. parser->first_nonspace + 1);
  837. (*container)->as.code.fenced = true;
  838. (*container)->as.code.fence_char = peek_at(input, parser->first_nonspace);
  839. (*container)->as.code.fence_length = (matched > 255) ? 255 : matched;
  840. (*container)->as.code.fence_offset =
  841. (int8_t)(parser->first_nonspace - parser->offset);
  842. (*container)->as.code.info = cmark_chunk_literal("");
  843. S_advance_offset(parser, input,
  844. parser->first_nonspace + matched - parser->offset,
  845. false);
  846. } else if (!indented && ((matched = scan_html_block_start(
  847. input, parser->first_nonspace)) ||
  848. (cont_type != CMARK_NODE_PARAGRAPH &&
  849. (matched = scan_html_block_start_7(
  850. input, parser->first_nonspace))))) {
  851. *container = add_child(parser, *container, CMARK_NODE_HTML_BLOCK,
  852. parser->first_nonspace + 1);
  853. (*container)->as.html_block_type = matched;
  854. // note, we don't adjust parser->offset because the tag is part of the
  855. // text
  856. } else if (!indented && cont_type == CMARK_NODE_PARAGRAPH &&
  857. (lev =
  858. scan_setext_heading_line(input, parser->first_nonspace))) {
  859. // finalize paragraph, resolving reference links
  860. has_content = resolve_reference_link_definitions(parser, *container);
  861. if (has_content) {
  862. (*container)->type = (uint16_t)CMARK_NODE_HEADING;
  863. (*container)->as.heading.level = lev;
  864. (*container)->as.heading.setext = true;
  865. S_advance_offset(parser, input, input->len - 1 - parser->offset, false);
  866. }
  867. } else if (!indented &&
  868. !(cont_type == CMARK_NODE_PARAGRAPH && !all_matched) &&
  869. (parser->thematic_break_kill_pos <= parser->first_nonspace) &&
  870. (matched = S_scan_thematic_break(parser, input, parser->first_nonspace))) {
  871. // it's only now that we know the line is not part of a setext heading:
  872. *container = add_child(parser, *container, CMARK_NODE_THEMATIC_BREAK,
  873. parser->first_nonspace + 1);
  874. S_advance_offset(parser, input, input->len - 1 - parser->offset, false);
  875. } else if ((!indented || cont_type == CMARK_NODE_LIST) &&
  876. parser->indent < 4 &&
  877. (matched = parse_list_marker(
  878. parser->mem, input, parser->first_nonspace,
  879. (*container)->type == CMARK_NODE_PARAGRAPH, &data))) {
  880. // Note that we can have new list items starting with >= 4
  881. // spaces indent, as long as the list container is still open.
  882. int i = 0;
  883. // compute padding:
  884. S_advance_offset(parser, input,
  885. parser->first_nonspace + matched - parser->offset,
  886. false);
  887. save_partially_consumed_tab = parser->partially_consumed_tab;
  888. save_offset = parser->offset;
  889. save_column = parser->column;
  890. while (parser->column - save_column <= 5 &&
  891. S_is_space_or_tab(peek_at(input, parser->offset))) {
  892. S_advance_offset(parser, input, 1, true);
  893. }
  894. i = parser->column - save_column;
  895. if (i >= 5 || i < 1 ||
  896. // only spaces after list marker:
  897. S_is_line_end_char(peek_at(input, parser->offset))) {
  898. data->padding = matched + 1;
  899. parser->offset = save_offset;
  900. parser->column = save_column;
  901. parser->partially_consumed_tab = save_partially_consumed_tab;
  902. if (i > 0) {
  903. S_advance_offset(parser, input, 1, true);
  904. }
  905. } else {
  906. data->padding = matched + i;
  907. }
  908. // check container; if it's a list, see if this list item
  909. // can continue the list; otherwise, create a list container.
  910. data->marker_offset = parser->indent;
  911. if (cont_type != CMARK_NODE_LIST ||
  912. !lists_match(&((*container)->as.list), data)) {
  913. *container = add_child(parser, *container, CMARK_NODE_LIST,
  914. parser->first_nonspace + 1);
  915. memcpy(&((*container)->as.list), data, sizeof(*data));
  916. }
  917. // add the list item
  918. *container = add_child(parser, *container, CMARK_NODE_ITEM,
  919. parser->first_nonspace + 1);
  920. /* TODO: static */
  921. memcpy(&((*container)->as.list), data, sizeof(*data));
  922. parser->mem->free(data);
  923. } else if (indented && !maybe_lazy && !parser->blank) {
  924. S_advance_offset(parser, input, CODE_INDENT, true);
  925. *container = add_child(parser, *container, CMARK_NODE_CODE_BLOCK,
  926. parser->offset + 1);
  927. (*container)->as.code.fenced = false;
  928. (*container)->as.code.fence_char = 0;
  929. (*container)->as.code.fence_length = 0;
  930. (*container)->as.code.fence_offset = 0;
  931. (*container)->as.code.info = cmark_chunk_literal("");
  932. } else {
  933. break;
  934. }
  935. if (accepts_lines(S_type(*container))) {
  936. // if it's a line container, it can't contain other containers
  937. break;
  938. }
  939. cont_type = S_type(*container);
  940. maybe_lazy = false;
  941. }
  942. }
  943. static void add_text_to_container(cmark_parser *parser, cmark_node *container,
  944. cmark_node *last_matched_container,
  945. cmark_chunk *input) {
  946. cmark_node *tmp;
  947. // what remains at parser->offset is a text line. add the text to the
  948. // appropriate container.
  949. S_find_first_nonspace(parser, input);
  950. if (parser->blank && container->last_child)
  951. S_set_last_line_blank(container->last_child, true);
  952. // block quote lines are never blank as they start with >
  953. // and we don't count blanks in fenced code for purposes of tight/loose
  954. // lists or breaking out of lists. we also don't set last_line_blank
  955. // on an empty list item.
  956. const cmark_node_type ctype = S_type(container);
  957. const bool last_line_blank =
  958. (parser->blank && ctype != CMARK_NODE_BLOCK_QUOTE &&
  959. ctype != CMARK_NODE_HEADING && ctype != CMARK_NODE_THEMATIC_BREAK &&
  960. !(ctype == CMARK_NODE_CODE_BLOCK && container->as.code.fenced) &&
  961. !(ctype == CMARK_NODE_ITEM && container->first_child == NULL &&
  962. container->start_line == parser->line_number));
  963. S_set_last_line_blank(container, last_line_blank);
  964. tmp = container;
  965. while (tmp->parent) {
  966. S_set_last_line_blank(tmp->parent, false);
  967. tmp = tmp->parent;
  968. }
  969. // If the last line processed belonged to a paragraph node,
  970. // and we didn't match all of the line prefixes for the open containers,
  971. // and we didn't start any new containers,
  972. // and the line isn't blank,
  973. // then treat this as a "lazy continuation line" and add it to
  974. // the open paragraph.
  975. if (parser->current != last_matched_container &&
  976. container == last_matched_container && !parser->blank &&
  977. S_type(parser->current) == CMARK_NODE_PARAGRAPH) {
  978. add_line(parser->current, input, parser);
  979. } else { // not a lazy continuation
  980. // Finalize any blocks that were not matched and set cur to container:
  981. while (parser->current != last_matched_container) {
  982. parser->current = finalize(parser, parser->current);
  983. assert(parser->current != NULL);
  984. }
  985. if (S_type(container) == CMARK_NODE_CODE_BLOCK) {
  986. add_line(container, input, parser);
  987. } else if (S_type(container) == CMARK_NODE_HTML_BLOCK) {
  988. add_line(container, input, parser);
  989. int matches_end_condition;
  990. switch (container->as.html_block_type) {
  991. case 1:
  992. // </script>, </style>, </pre>
  993. matches_end_condition =
  994. scan_html_block_end_1(input, parser->first_nonspace);
  995. break;
  996. case 2:
  997. // -->
  998. matches_end_condition =
  999. scan_html_block_end_2(input, parser->first_nonspace);
  1000. break;
  1001. case 3:
  1002. // ?>
  1003. matches_end_condition =
  1004. scan_html_block_end_3(input, parser->first_nonspace);
  1005. break;
  1006. case 4:
  1007. // >
  1008. matches_end_condition =
  1009. scan_html_block_end_4(input, parser->first_nonspace);
  1010. break;
  1011. case 5:
  1012. // ]]>
  1013. matches_end_condition =
  1014. scan_html_block_end_5(input, parser->first_nonspace);
  1015. break;
  1016. default:
  1017. matches_end_condition = 0;
  1018. break;
  1019. }
  1020. if (matches_end_condition) {
  1021. container = finalize(parser, container);
  1022. assert(parser->current != NULL);
  1023. }
  1024. } else if (parser->blank) {
  1025. // ??? do nothing
  1026. } else if (accepts_lines(S_type(container))) {
  1027. if (S_type(container) == CMARK_NODE_HEADING &&
  1028. container->as.heading.setext == false) {
  1029. chop_trailing_hashtags(input);
  1030. }
  1031. S_advance_offset(parser, input, parser->first_nonspace - parser->offset,
  1032. false);
  1033. add_line(container, input, parser);
  1034. } else {
  1035. // create paragraph container for line
  1036. container = add_child(parser, container, CMARK_NODE_PARAGRAPH,
  1037. parser->first_nonspace + 1);
  1038. S_advance_offset(parser, input, parser->first_nonspace - parser->offset,
  1039. false);
  1040. add_line(container, input, parser);
  1041. }
  1042. parser->current = container;
  1043. }
  1044. }
  1045. /* See http://spec.commonmark.org/0.24/#phase-1-block-structure */
  1046. static void S_process_line(cmark_parser *parser, const unsigned char *buffer,
  1047. bufsize_t bytes) {
  1048. cmark_node *last_matched_container;
  1049. bool all_matched = true;
  1050. cmark_node *container;
  1051. cmark_chunk input;
  1052. if (parser->options & CMARK_OPT_VALIDATE_UTF8)
  1053. cmark_utf8proc_check(&parser->curline, buffer, bytes);
  1054. else
  1055. cmark_strbuf_put(&parser->curline, buffer, bytes);
  1056. bytes = parser->curline.size;
  1057. // ensure line ends with a newline:
  1058. if (bytes == 0 || !S_is_line_end_char(parser->curline.ptr[bytes - 1]))
  1059. cmark_strbuf_putc(&parser->curline, '\n');
  1060. parser->offset = 0;
  1061. parser->column = 0;
  1062. parser->first_nonspace = 0;
  1063. parser->first_nonspace_column = 0;
  1064. parser->thematic_break_kill_pos = 0;
  1065. parser->indent = 0;
  1066. parser->blank = false;
  1067. parser->partially_consumed_tab = false;
  1068. input.data = parser->curline.ptr;
  1069. input.len = parser->curline.size;
  1070. input.alloc = 0;
  1071. parser->line_number++;
  1072. last_matched_container = check_open_blocks(parser, &input, &all_matched);
  1073. if (!last_matched_container)
  1074. goto finished;
  1075. container = last_matched_container;
  1076. open_new_blocks(parser, &container, &input, all_matched);
  1077. add_text_to_container(parser, container, last_matched_container, &input);
  1078. finished:
  1079. parser->last_line_length = input.len;
  1080. if (parser->last_line_length &&
  1081. input.data[parser->last_line_length - 1] == '\n')
  1082. parser->last_line_length -= 1;
  1083. if (parser->last_line_length &&
  1084. input.data[parser->last_line_length - 1] == '\r')
  1085. parser->last_line_length -= 1;
  1086. cmark_strbuf_clear(&parser->curline);
  1087. }
  1088. cmark_node *cmark_parser_finish(cmark_parser *parser) {
  1089. if (parser->linebuf.size) {
  1090. S_process_line(parser, parser->linebuf.ptr, parser->linebuf.size);
  1091. cmark_strbuf_clear(&parser->linebuf);
  1092. }
  1093. finalize_document(parser);
  1094. cmark_consolidate_text_nodes(parser->root);
  1095. cmark_strbuf_free(&parser->curline);
  1096. #if CMARK_DEBUG_NODES
  1097. if (cmark_node_check(parser->root, stderr)) {
  1098. abort();
  1099. }
  1100. #endif
  1101. return parser->root;
  1102. }