@podlite/schema 0.0.80 → 0.0.81

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/CHANGELOG.podlite +44 -0
  2. package/esm/ast-helpers.d.ts +8 -1
  3. package/esm/ast-helpers.js +172 -47
  4. package/esm/ast-helpers.js.map +1 -1
  5. package/esm/exportAny.d.ts +1 -0
  6. package/esm/exportAny.js +11 -0
  7. package/esm/exportAny.js.map +1 -1
  8. package/esm/exportHtml.js +58 -1
  9. package/esm/exportHtml.js.map +1 -1
  10. package/esm/exportMarkdown.js +604 -137
  11. package/esm/exportMarkdown.js.map +1 -1
  12. package/esm/helpers/code-config.d.ts +1 -0
  13. package/esm/helpers/code-config.js +4 -0
  14. package/esm/helpers/code-config.js.map +1 -0
  15. package/esm/helpers/corePlugins.js +4 -0
  16. package/esm/helpers/corePlugins.js.map +1 -1
  17. package/esm/helpers/handlers.js +8 -4
  18. package/esm/helpers/handlers.js.map +1 -1
  19. package/esm/index.d.ts +2 -0
  20. package/esm/index.js +1 -0
  21. package/esm/index.js.map +1 -1
  22. package/esm/markdown-heading-text.d.ts +3 -0
  23. package/esm/markdown-heading-text.js +36 -0
  24. package/esm/markdown-heading-text.js.map +1 -0
  25. package/esm/plugin-formatting-codes.js +1 -3
  26. package/esm/plugin-formatting-codes.js.map +1 -1
  27. package/esm/plugin-tables.d.ts +4 -1
  28. package/esm/plugin-tables.js +99 -26
  29. package/esm/plugin-tables.js.map +1 -1
  30. package/esm/test-display.js +8 -1
  31. package/esm/test-display.js.map +1 -1
  32. package/esm/title.d.ts +13 -0
  33. package/esm/title.js +22 -0
  34. package/esm/title.js.map +1 -0
  35. package/esm/types.d.ts +9 -4
  36. package/esm/version.d.ts +1 -1
  37. package/esm/version.js +1 -1
  38. package/esm/writerMarkdown.d.ts +9 -0
  39. package/esm/writerMarkdown.js +103 -1
  40. package/esm/writerMarkdown.js.map +1 -1
  41. package/lib/ast-helpers.d.ts +8 -1
  42. package/lib/ast-helpers.js +176 -48
  43. package/lib/exportAny.d.ts +1 -0
  44. package/lib/exportAny.js +11 -0
  45. package/lib/exportHtml.js +58 -1
  46. package/lib/exportMarkdown.js +607 -140
  47. package/lib/helpers/code-config.d.ts +1 -0
  48. package/lib/helpers/code-config.js +8 -0
  49. package/lib/helpers/corePlugins.js +4 -0
  50. package/lib/helpers/handlers.js +8 -4
  51. package/lib/index.d.ts +2 -0
  52. package/lib/index.js +5 -2
  53. package/lib/markdown-heading-text.d.ts +3 -0
  54. package/lib/markdown-heading-text.js +40 -0
  55. package/lib/plugin-formatting-codes.js +2 -4
  56. package/lib/plugin-tables.d.ts +4 -1
  57. package/lib/plugin-tables.js +99 -26
  58. package/lib/test-display.js +8 -1
  59. package/lib/title.d.ts +13 -0
  60. package/lib/title.js +27 -0
  61. package/lib/types.d.ts +9 -4
  62. package/lib/version.d.ts +1 -1
  63. package/lib/version.js +1 -1
  64. package/lib/writerMarkdown.d.ts +9 -0
  65. package/lib/writerMarkdown.js +103 -1
  66. package/package.json +3 -2
  67. package/schema/AstTree.json +246 -0
  68. package/schema/PodliteDocument.json +246 -0
@@ -49,27 +49,52 @@ const ast_helpers_1 = require("./ast-helpers");
49
49
  const html_attr_1 = require("./helpers/html-attr");
50
50
  const link_config_1 = require("./helpers/link-config");
51
51
  const test_display_1 = require("./test-display");
52
+ const title_1 = require("./title");
53
+ const markdown_heading_text_1 = require("./markdown-heading-text");
52
54
  // A markdown reader builds the anchor out of the heading itself, by its own rules,
53
55
  // so a link written here has to match what that reader will produce.
54
56
  // Built once per document and mode: a hidden block renders with a copy of the context,
55
57
  // and a cache kept on the context itself would be rebuilt for every one of them.
56
58
  const readerAnchorsCache = new WeakMap();
59
+ // The walk that learns the lines notes each heading where the page has it, and fills in
60
+ // its line when it is written; a title holds blocks written before its own line.
61
+ const noteHeading = (ctx, node) => {
62
+ const lines = ctx?.__headingLines;
63
+ if (!lines)
64
+ return () => { };
65
+ const at = lines.push({ node, line: null }) - 1;
66
+ return line => {
67
+ lines[at].line = line;
68
+ };
69
+ };
70
+ // With the texts of the headings read from the lines the output wrote, the addresses are
71
+ // the reader's own; the walk that learns those lines builds them from the tree.
57
72
  const markdownAnchors = ctx => {
58
73
  const index = ctx?.__anchors;
59
74
  if (!index)
60
75
  return undefined;
61
76
  const mode = ctx.renderMode === 'draft' ? 'draft' : 'production';
62
- let byMode = readerAnchorsCache.get(index);
77
+ const key = ctx.__readerTexts || index;
78
+ let byMode = readerAnchorsCache.get(key);
63
79
  if (!byMode)
64
- readerAnchorsCache.set(index, (byMode = new Map()));
80
+ readerAnchorsCache.set(key, (byMode = new Map()));
65
81
  if (!byMode.has(mode))
66
- byMode.set(mode, (0, ast_helpers_1.readerAnchors)(index, mode));
82
+ byMode.set(mode, (0, ast_helpers_1.readerAnchors)(index, mode, ctx.__readerTexts, ctx.__codeLinkHeadings));
67
83
  return byMode.get(mode);
68
84
  };
85
+ // a reader takes `©` in an address, a title or the alternative text of a picture for
86
+ // the sign; `&` keeps it as written for every reader, where some do not take off a backslash
87
+ const characterReference = /&(?=#?[A-Za-z0-9]+;)/g;
88
+ const keepReferences = (text) => text.replace(characterReference, '&');
89
+ // the title of a link or a picture, after its address in quotes
90
+ const quotedTitle = (title, inCode = false) => {
91
+ const text = inCode ? title : keepReferences(title.replace(/\\/g, '\\\\'));
92
+ return ` "${text.replace(/"/g, '\\"')}"`;
93
+ };
69
94
  // a title written on a link inside hidden content is hidden with it
70
- const linkTitle = (config, conceal = text => text) => {
95
+ const linkTitle = (config, conceal = text => text, inCode = false) => {
71
96
  const { title } = (0, link_config_1.readLinkConfig)(config);
72
- return title === undefined ? '' : ` "${conceal(title).replace(/"/g, '\\"')}"`;
97
+ return title === undefined ? '' : quotedTitle(conceal(title), inCode);
73
98
  };
74
99
  // Markdown has no form for a link whose target the author never wrote — an empty
75
100
  // address there claims the current document — so the text is written on its own.
@@ -78,18 +103,29 @@ const linkTitle = (config, conceal = text => text) => {
78
103
  // markdown keeps for exactly that. An angle of its own is percent-encoded rather
79
104
  // than dropped, so the address survives the round trip — no source text reaches
80
105
  // here holding one today, since the parser ends the code on it.
81
- const markdownAddress = (address) => /[()\s]/.test(address) ? `<${address.replace(/</g, '%3C').replace(/>/g, '%3E')}>` : address;
82
- const linkWrap = (node, ctx) => {
106
+ // Inside code a reader shows a backslash, so there the address stays as it is.
107
+ const markdownAddress = (address, inCode = false) => {
108
+ const kept = inCode ? address : keepReferences(address.replace(/\\/g, '\\\\'));
109
+ return /[()\s]/.test(kept) ? `<${kept.replace(/</g, '%3C').replace(/>/g, '%3E')}>` : kept;
110
+ };
111
+ const linkWrap = (node, ctx, inCode = false) => {
83
112
  const target = (0, ast_helpers_1.linkTarget)(node);
84
113
  if (target === undefined)
85
114
  return (0, handlers_1.wrapContent)('', '');
86
115
  const resolved = (0, ast_helpers_1.sameDocTarget)(target, ctx, markdownAnchors(ctx), node);
116
+ // a link to this document in the code of a heading line is read as text: the heading
117
+ // and the target of the link take named anchors, so the text stays as it is
118
+ if (inCode && ctx.__codeLinks && ctx.__headingNode && typeof target === 'string' && target.startsWith('#')) {
119
+ const bound = ctx.__bindings ? (0, ast_helpers_1.bindTarget)(target.slice(1), ctx.__bindings) : undefined;
120
+ if (bound?.found)
121
+ ctx.__codeLinks.add(bound.node).add(ctx.__headingNode);
122
+ }
87
123
  // Markdown has no anchor without an address either, so a refused link keeps its
88
124
  // text and loses the brackets.
89
125
  if (resolved === undefined)
90
126
  return (0, handlers_1.wrapContent)('', '');
91
127
  const address = String(resolved);
92
- return (0, handlers_1.wrapContent)(`[`, `](${markdownAddress(address)}${linkTitle((0, config_1.codeConfigWithDefaults)(node, ctx), text => covered(node, ctx, text))})`);
128
+ return (0, handlers_1.wrapContent)(`[`, `](${markdownAddress(address, inCode)}${linkTitle((0, config_1.codeConfigWithDefaults)(node, ctx), text => covered(node, ctx, text), inCode)})`);
93
129
  };
94
130
  // A cell's own text is written whole. Trimming each fragment on its own eats the
95
131
  // spaces that sit between them — between a word and a markup code, or around a
@@ -116,7 +152,7 @@ const writeSourceBlock = (writer, node, ctx) => {
116
152
  const text = (0, handlers_1.collectText)(node.content);
117
153
  const fence = '`'.repeat(Math.max(3, (0, test_display_1.longestBacktickRun)(text) + 1));
118
154
  writer.writeRaw(`${fence}podlite\n`);
119
- writer.writeRaw((0, guard_1.isCovered)(node, ctx) ? (0, handlers_1.maskText)(text) : text);
155
+ writeSource(writer, (0, guard_1.isCovered)(node, ctx) ? (0, handlers_1.maskText)(text) : text);
120
156
  if (!text.endsWith('\n'))
121
157
  writer.writeRaw('\n');
122
158
  writer.writeRaw(`${fence}\n`);
@@ -125,12 +161,269 @@ const writeSourceBlock = (writer, node, ctx) => {
125
161
  const covered = (node, ctx, text) => ((0, guard_1.isCovered)(node, ctx) ? (0, handlers_1.maskText)(text) : text);
126
162
  const inlineCode = (text) => {
127
163
  const ticks = '`'.repeat((0, test_display_1.longestBacktickRun)(text) + 1);
128
- const pad = text.startsWith('`') || text.endsWith('`') ? ' ' : '';
164
+ // a reader takes one space off each side of code that has a space at both ends, a line
165
+ // break counted as a space, so such code, as code at a backtick, gets one more on each side
166
+ const spaced = /^[ \n]/.test(text) && /[ \n]$/.test(text) && /[^ \n]/.test(text);
167
+ const pad = text.startsWith('`') || text.endsWith('`') || spaced ? ' ' : '';
129
168
  return `${ticks}${pad}${text}${pad}${ticks}`;
130
169
  };
131
- const implicitPara = (0, handlers_1.handleNested)((writer, processor) => (node, ctx, interator) => {
132
- if (node.content)
133
- interator(node.content, ctx);
170
+ // Inside code a reader takes < and & as written; a cell of a table written as HTML
171
+ // stands inside a frame, and a fence must not hold across a cell folded onto a line.
172
+ const within = (writer, depth, write) => {
173
+ writer[depth] = (writer[depth] || 0) + 1;
174
+ try {
175
+ write();
176
+ }
177
+ finally {
178
+ writer[depth]--;
179
+ }
180
+ };
181
+ // What `write` writes is kept aside and returned. The line the writer stands on is not
182
+ // touched: the caller writes the result as one piece, and the writer counts its line
183
+ // from that piece.
184
+ const writeAside = (writer, write) => {
185
+ const original = writer.output;
186
+ const { lastWritten, lineText, paraStart, trailingBreaks, pendingBreak } = writer;
187
+ const parts = [];
188
+ writer.output = (str) => parts.push(str);
189
+ // a blank line owed to the content outside is not written into the piece aside
190
+ if (pendingBreak)
191
+ writer.pendingBreak = false;
192
+ try {
193
+ write();
194
+ }
195
+ finally {
196
+ writer.output = original;
197
+ writer.lastWritten = lastWritten;
198
+ writer.lineText = lineText;
199
+ writer.paraStart = paraStart;
200
+ writer.trailingBreaks = trailingBreaks;
201
+ writer.pendingBreak = pendingBreak;
202
+ }
203
+ return parts.join('');
204
+ };
205
+ // The markdown writer keeps the text of its line, so the lines of a quote and of an
206
+ // item can be written aside and given their prefix when they are done.
207
+ const ownsLines = writer => typeof writer.lineText === 'string' && typeof writer.output === 'function';
208
+ // the content of a quote or an item starts on a line of its own
209
+ const startLine = writer => {
210
+ writer.lineText = '';
211
+ writer.lastWritten = '';
212
+ writer.paraStart = false;
213
+ writer.trailingBreaks = null;
214
+ writer.pendingBreak = false;
215
+ };
216
+ // A quote is written aside, then every line of it gets the sign of each level, a blank
217
+ // one too, so a fence, a list or a second paragraph stays inside. A quote opened in the
218
+ // middle of a line, after the term of a definition, starts a line of its own. One blank
219
+ // line outside the quote ends it.
220
+ const quote = (writer, levels, write) => {
221
+ if (writer.lineText !== '')
222
+ writer.writeRaw('\n');
223
+ const body = writeAside(writer, () => {
224
+ startLine(writer);
225
+ write();
226
+ });
227
+ const sign = '> '.repeat(levels);
228
+ const lines = body.replace(/\n+$/, '').split('\n');
229
+ writer.writeRaw(lines.map(line => (line === '' ? sign.trimEnd() : sign + line)).join('\n') + '\n\n');
230
+ };
231
+ // :nested(n) of a block: a quote of n levels around what the block writes
232
+ const handleNested = (handler, implicitLevel) => (writer, processor) => {
233
+ const plain = (0, handlers_1.handleNested)(handler, implicitLevel)(writer, processor);
234
+ const own = handler(writer, processor);
235
+ return (node, ctx, interator) => {
236
+ if (!ownsLines(writer))
237
+ return plain(node, ctx, interator);
238
+ const levels = Number((0, config_1.default)(node, ctx).getFirstValue('nested') || implicitLevel || 0);
239
+ if (!(levels > 0))
240
+ return own(node, ctx, interator);
241
+ quote(writer, levels, () => own(node, ctx, interator));
242
+ };
243
+ };
244
+ // a writer given by the caller may be a plain one, without a source of its own
245
+ const writeSource = (writer, text) => typeof writer.writeSource === 'function' ? writer.writeSource(text) : writer.writeRaw(text);
246
+ // Code in a line is written aside first: its fence is one backtick longer than any run
247
+ // inside, so a backtick of the text does not end the code early.
248
+ // A cell of a pipe table is divided at every bar, before code is read, unless an odd run of
249
+ // backslashes stands before the bar; the reader then takes one backslash off. So a bar of
250
+ // code gets a backslash of its own after an even run, and one more after an odd run: the
251
+ // reader shows the code as written after an even run and one backslash more after an odd one.
252
+ // The whole code is taken at once, as a backslash may come from another piece of it.
253
+ const keepBarsInCell = (code) => code.replace(/(\\*)\|/g, (match, run) => `${run}${run.length % 2 ? '\\' : ''}\\|`);
254
+ const codeSpan = (writer, processor) => (node, ctx, interator) => {
255
+ const code = writeAside(writer, () => within(writer, 'codeDepth', () => node.content && interator(node.content, ctx)));
256
+ writer.writeRaw(inlineCode(writer.cellDepth > 0 ? keepBarsInCell(code) : code));
257
+ };
258
+ const htmlText = (text) => text.replace(/&/g, '&amp;').replace(/</g, '&lt;');
259
+ // A cell of a table written as HTML holds Markdown: a blank line ends the block of
260
+ // HTML before it and another one before the closing tag, so a reader takes what
261
+ // lies between as Markdown. A cell with nothing to show closes on its own line.
262
+ const writeIsland = (writer, open, close, write) => {
263
+ if (typeof writer.output !== 'function') {
264
+ writer.writeRaw(`${open}\n\n`);
265
+ write();
266
+ writer.writeRaw(`\n\n${close}\n`);
267
+ return;
268
+ }
269
+ // the content of a cell starts anew: a block at its start needs no blank line before it
270
+ const body = writeAside(writer, () => {
271
+ writer.trailingBreaks = null;
272
+ write();
273
+ }).replace(/\n+$/, '');
274
+ writer.writeRaw(body.trim() === '' ? `${open}${close}\n` : `${open}\n\n${body}\n\n${close}\n`);
275
+ };
276
+ // a fence longer than any run of backticks in the body, opened at the start of a line
277
+ const writeFenced = (writer, info, write) => {
278
+ if (typeof writer.output !== 'function') {
279
+ writer.writeRaw('```' + info + '\n');
280
+ within(writer, 'codeDepth', write);
281
+ if (!writer.lastWritten.endsWith('\n'))
282
+ writer.writeRaw('\n');
283
+ writer.writeRaw('```\n');
284
+ return;
285
+ }
286
+ const atLineStart = /^$|\n$/.test(writer.lastWritten);
287
+ const body = writeAside(writer, () => within(writer, 'codeDepth', write));
288
+ const fence = '`'.repeat(Math.max(3, (0, test_display_1.longestBacktickRun)(body) + 1));
289
+ writer.writeRaw(`${atLineStart ? '' : '\n'}${fence}${info}\n`);
290
+ if (body !== '')
291
+ writer.writeRaw(body.endsWith('\n') ? body : `${body}\n`);
292
+ writer.writeRaw(`${fence}\n`);
293
+ };
294
+ // A body shown as written goes into a fence a reader keeps as written. A fence holds only
295
+ // on a line of its own and outside a cell folded onto a line; there the body is written
296
+ // as text, so its words stay in sight. Says whether a fence was written.
297
+ const isBodyText = child => typeof child === 'string' || child.type === 'text' || child.type === 'verbatim';
298
+ const bodyValue = child => (typeof child === 'string' ? child : child.value);
299
+ const writeBodyAsWritten = (writer, node, ctx, interator, language = '') => {
300
+ const children = node.content || [];
301
+ if (writer.cellDepth > 0) {
302
+ children.forEach(child => isBodyText(child)
303
+ ? writeText(writer, typeof child === 'string' ? node : child, ctx, bodyValue(child))
304
+ : interator([child], ctx));
305
+ if (!writer.lastWritten.endsWith('\n'))
306
+ writer.writeRaw('\n');
307
+ writer.writeRaw('\n');
308
+ return false;
309
+ }
310
+ const masked = (0, guard_1.isCovered)(node, ctx);
311
+ writeFenced(writer, language, () => children.forEach(child => isBodyText(child)
312
+ ? writeSource(writer, masked ? (0, handlers_1.maskText)(bodyValue(child)) : bodyValue(child))
313
+ : interator([child], ctx)));
314
+ return true;
315
+ };
316
+ // What a block writes, ended by one blank line, so the paragraph after it stands
317
+ // on its own
318
+ const writeWithBoundary = (writer, write) => {
319
+ if (typeof writer.output !== 'function') {
320
+ write();
321
+ writer.writeRaw('\n');
322
+ return;
323
+ }
324
+ const text = writeAside(writer, write);
325
+ if (text === '')
326
+ return;
327
+ writer.writeRaw(text.endsWith('\n\n') ? text : text.endsWith('\n') ? `${text}\n` : `${text}\n\n`);
328
+ };
329
+ // A block no rule knows holds a body nobody has read: text only. Its names never come
330
+ // from a rule, a semantic block or an =include, which is a directive.
331
+ const isBareBody = node => {
332
+ const name = node.name || '';
333
+ if (node.type !== 'block' || name === name.toUpperCase())
334
+ return false;
335
+ if (['root', 'caption', 'Html', 'include'].includes(name))
336
+ return false;
337
+ const children = node.content;
338
+ return Array.isArray(children) && children.length > 0 && children.every(isBodyText);
339
+ };
340
+ // the names the plugins give a picture and a block of Markdown, as an author may write them
341
+ const isPluginPicture = node => (node.name === 'picture' || node.name === 'Image') &&
342
+ node.sourceFormat !== 'markdown' &&
343
+ Array.isArray(node.content) &&
344
+ node.content[0]?.type === 'image';
345
+ const isPluginMarkdown = node => (node.name === 'markdown' || node.name === 'Markdown') &&
346
+ node.sourceFormat !== 'markdown' &&
347
+ node.content &&
348
+ !Array.isArray(node.content) &&
349
+ node.content.name === 'root';
350
+ // A block without a rule of its own is shown as written: a fence without a language,
351
+ // the body as the source has it, a diagram marked mermaid unless it is hidden. A
352
+ // picture from its plugin stands as a picture with its caption a paragraph after it;
353
+ // a block of Markdown read by its plugin keeps its own structure. Each ends with a
354
+ // blank line, so the paragraph after it does not join it.
355
+ const blockWithoutRule = (writer, node, ctx, interator) => {
356
+ if (isBareBody(node)) {
357
+ const body = node.content.map(bodyValue).join('');
358
+ if (body.trim() === '')
359
+ return true;
360
+ const diagram = (node.name === 'Mermaid' || node.name === 'Diagram') && !(0, guard_1.isCovered)(node, ctx);
361
+ if (writeBodyAsWritten(writer, node, ctx, interator, diagram ? 'mermaid' : ''))
362
+ writer.writeRaw('\n');
363
+ return true;
364
+ }
365
+ if (isPluginPicture(node)) {
366
+ const [image, ...rest] = node.content;
367
+ writeWithBoundary(writer, () => {
368
+ interator([image], ctx);
369
+ writer.writeRaw('\n');
370
+ });
371
+ rest.forEach(part => part?.type === 'block' && part.name === 'caption'
372
+ ? writeWithBoundary(writer, () => paragraph(writer, ctx, () => interator(part.content, ctx)))
373
+ : interator([part], ctx));
374
+ return true;
375
+ }
376
+ if (isPluginMarkdown(node)) {
377
+ writeWithBoundary(writer, () => interator(node.content, ctx));
378
+ return true;
379
+ }
380
+ return false;
381
+ };
382
+ // Input and output are written as code a reader keeps as written.
383
+ const sampleBlock = (writer, processor) => (node, ctx, interator) => {
384
+ writeBodyAsWritten(writer, node, ctx, interator);
385
+ };
386
+ // HTML the reader of Markdown made stays as written. An author's =Html is shown, not run:
387
+ // raw, a style could hide what follows it and an open comment could take the rest.
388
+ const htmlBlock = (writer, processor) => (node, ctx, interator) => {
389
+ if (node.sourceFormat === 'markdown')
390
+ return markdownHtml(writer, node, ctx, interator);
391
+ const body = (node.content || []).map(child => (isBodyText(child) ? bodyValue(child) : ' ')).join('');
392
+ if (body.trim() === '')
393
+ return;
394
+ if (writeBodyAsWritten(writer, node, ctx, interator))
395
+ writer.writeRaw('\n');
396
+ };
397
+ // HTML of Markdown that stands for a block needs a blank line before it, or a reader
398
+ // takes it into the paragraph above, and one before what follows it in the same
399
+ // content, or a reader takes that into the HTML. Nothing is added at the start of
400
+ // the content or at its end.
401
+ const markdownHtml = (writer, node, ctx, interator) => {
402
+ if (node.markdownHtml !== 'block' || !ownsLines(writer) || writer.cellDepth > 0)
403
+ return interator(node.content, ctx);
404
+ const missing = writer.trailingBreaks === null ? 0 : 2 - writer.trailingBreaks;
405
+ if (missing > 0)
406
+ writer.writeRaw('\n'.repeat(missing));
407
+ interator(node.content, ctx);
408
+ if (writer.trailingBreaks === 0)
409
+ writer.writeRaw('\n');
410
+ writer.pendingBreak = true;
411
+ };
412
+ // The first visible line of a paragraph is written without its indent. Inside an item
413
+ // the indent of a later paragraph is what keeps it in the item, so it stays there.
414
+ const paragraph = (writer, ctx, write) => {
415
+ if (ctx.inItem || typeof writer.paraStart !== 'boolean')
416
+ return write();
417
+ writer.paraStart = true;
418
+ try {
419
+ write();
420
+ }
421
+ finally {
422
+ writer.paraStart = false;
423
+ }
424
+ };
425
+ const implicitPara = handleNested((writer, processor) => (node, ctx, interator) => {
426
+ paragraph(writer, ctx, () => node.content && interator(node.content, ctx));
134
427
  writer.writeRaw('\n');
135
428
  });
136
429
  const termPara = (writer, processor) => (node, ctx, interator) => {
@@ -145,19 +438,115 @@ const writtenCode = (writer, node, ctx, interator) => {
145
438
  interator(node.content, ctx);
146
439
  writer.write(close);
147
440
  };
148
- const rules = {
149
- ':text': (writer, processor) => (node, ctx, interator) => {
150
- if (node.value && ctx.keepSpaces) {
151
- // inside S<>: every space stays and does not break, a line break stays a line break
152
- const text = writer.escape((0, handlers_1.expandTabs)((0, guard_1.isCovered)(node, ctx) ? (0, handlers_1.maskText)(node.value) : node.value, ctx.keepSpaces));
153
- writer.writeRaw(text.replace(/ /g, '&nbsp;').replace(/\n/g, ' \n'));
441
+ // text of the document, hidden or not by the node it comes from
442
+ const writeText = (writer, node, ctx, value) => {
443
+ if (ctx.keepSpaces) {
444
+ // inside S<>: every space stays and does not break, a line break stays a line break
445
+ const text = writer.escape((0, handlers_1.expandTabs)((0, guard_1.isCovered)(node, ctx) ? (0, handlers_1.maskText)(value) : value, ctx.keepSpaces));
446
+ writer.writeRaw(text.replace(/ /g, '&nbsp;').replace(/\n/g, keptBreak(writer, ctx)));
447
+ }
448
+ else {
449
+ const text = (0, guard_1.isCovered)(node, ctx) ? (0, handlers_1.maskText)(value) : value;
450
+ const shown = writer.paraStart && !(writer.codeDepth > 0) ? text.replace(/^[ \t\n]+/, '') : text;
451
+ writer.write(ctx.headingLine && writer.codeDepth > 0 ? shown.replace(/\n/g, ' ') : shown);
452
+ }
453
+ };
454
+ // A line break S<> keeps: two spaces before the break, and in the line of a heading,
455
+ // which holds no break, the tag of one; inside code there it is a space, as code in
456
+ // a line has no break of its own.
457
+ const keptBreak = (writer, ctx) => (!ctx.headingLine ? ' \n' : writer.codeDepth > 0 ? ' ' : '<br>');
458
+ // The line of a heading is written aside and given back as one line: a break of code
459
+ // or of S<> was settled when it was written, and every other break, with the spaces
460
+ // around it, becomes one space. The break that ends the paragraph goes, and the
461
+ // spaces before it stay, so a heading on one line is written as before.
462
+ const headingLine = (writer, write) => {
463
+ const line = writeAside(writer, write);
464
+ const ended = line.endsWith('\n');
465
+ return (ended ? line.slice(0, -1) : line).replace(/[ \t]*\n[ \t]*/g, ' ') + (ended ? '\n' : '');
466
+ };
467
+ // a paragraph a title takes apart keeps its own mask for the text it gives the title
468
+ const maskedOwner = (owner, ctx) => {
469
+ if (ctx?.maskMode || ctx?.renderMode === 'draft')
470
+ return false;
471
+ if (owner.guarded)
472
+ return true;
473
+ const conf = (0, config_1.default)(owner, ctx || {});
474
+ return Boolean(conf.exists('masked') && conf.getFirstValue('masked'));
475
+ };
476
+ // =TITLE shows its content as the title of the document, as HTML and to-jsx do: its
477
+ // paragraphs in one heading of the first level, other blocks after it, a directive
478
+ // acting from where it stands. A title with nothing to show writes no heading, and
479
+ // an anchor only when the author named it.
480
+ const titleBlock = (writer, node, ctx, interator) => {
481
+ const note = noteHeading(ctx, node);
482
+ const heading = [];
483
+ const rest = [];
484
+ (0, title_1.titleParts)(node).forEach(entry => {
485
+ if (entry.kind === 'rest') {
486
+ rest.push(writeAside(writer, () => interator([entry.node], ctx)));
487
+ return;
154
488
  }
155
- else if (node.value) {
156
- writer.write((0, guard_1.isCovered)(node, ctx) ? (0, handlers_1.maskText)(node.value) : node.value);
489
+ const masked = entry.owners.some(owner => maskedOwner(owner, ctx));
490
+ const partCtx = { ...ctx, headingLine: true, __headingNode: node, ...(masked ? { maskMode: true } : {}) };
491
+ // the line breaks and spaces at the edges of a paragraph go; a no-break space stays
492
+ const part = headingLine(writer, () => interator(entry.content, partCtx)).replace(/^[ \t\n]+|[ \t\n]+$/g, '');
493
+ if (/\S/.test(part))
494
+ heading.push(part);
495
+ });
496
+ // a link reaches a title by the name its author gave it, shaped as for a reader and kept
497
+ // off the addresses the reader builds for the headings
498
+ const written = (0, ast_helpers_1.getExplicitNodeId)(node, ctx);
499
+ const anchors = markdownAnchors(ctx);
500
+ const own = written === null
501
+ ? ''
502
+ : anchors?.byNode.has(node)
503
+ ? anchors.named?.has(node)
504
+ ? anchors.byNode.get(node)
505
+ : ''
506
+ : (0, ast_helpers_1.toMarkdownFragment)(written).toLowerCase();
507
+ if (own)
508
+ writer.writeRaw(`<a name="${(0, html_attr_1.quoteAttribute)(own)}"></a>\n\n`);
509
+ note(heading.length ? heading.join(' ') : null);
510
+ if (heading.length)
511
+ writer.writeRaw(`# ${heading.join(' ')}\n\n`);
512
+ rest.forEach(text => writer.writeRaw(text));
513
+ };
514
+ // HTML the markdown plugin finds inside a line comes as an Html block of one line
515
+ const inlineHtml = node => node.name === 'Html' &&
516
+ (node.content || []).every(part => part.type === 'verbatim' && !String(part.value).includes('\n'));
517
+ // A cell holds a block when it holds more than one paragraph or anything but a paragraph
518
+ // and text; a comment, data and a directive show nothing and count for nothing.
519
+ const holdsBlock = cell => {
520
+ let paragraphs = 0;
521
+ let inline = false;
522
+ let block = false;
523
+ const visit = nodes => (nodes || []).forEach(node => {
524
+ if (typeof node === 'string' || node.type === 'text') {
525
+ if (String(typeof node === 'string' ? node : node.value || '').trim() !== '')
526
+ inline = true;
157
527
  }
158
- else {
528
+ else if (node.type === 'fcode' || (node.type === 'block' && inlineHtml(node)))
529
+ inline = true;
530
+ else if (node.type === 'para')
531
+ paragraphs++;
532
+ else if (node.type === 'block' && node.name === 'para')
533
+ visit(node.content);
534
+ else if (node.type === 'blankline' || node.type === 'config' || node.type === 'alias')
535
+ return;
536
+ else if (node.type === 'block' && (node.name === 'comment' || node.name === 'data'))
537
+ return;
538
+ else
539
+ block = true;
540
+ });
541
+ visit(cell.content);
542
+ return block || paragraphs + (inline ? 1 : 0) > 1;
543
+ };
544
+ const rules = {
545
+ ':text': (writer, processor) => (node, ctx, interator) => {
546
+ if (node.value)
547
+ writeText(writer, node, ctx, node.value);
548
+ else
159
549
  interator(node.content, ctx);
160
- }
161
550
  },
162
551
  // Formatting codes
163
552
  'A<>': (writer, processor) => (node, ctx, interator) => {
@@ -174,11 +563,19 @@ const rules = {
174
563
  else {
175
564
  interator(tree, ctx);
176
565
  }
177
- }, message => console.warn(`[podlite] ${message}`)).expanded;
566
+ },
567
+ // the walk that learns the lines of the headings stays quiet: the walk after it speaks
568
+ message => ctx.__headingLines || console.warn(`[podlite] ${message}`)).expanded;
178
569
  if (!expanded)
179
- writer.writeRaw(`A<${covered(node, ctx, term)}>`);
570
+ writer.write(`A<${covered(node, ctx, term)}>`);
571
+ },
572
+ 'C<>': codeSpan,
573
+ // the characters of an entity are text like any other in the same place
574
+ 'E<>': (writer, processor) => (node, ctx, interator) => {
575
+ const text = (0, ast_helpers_1.decodeEntities)(node.content);
576
+ if (text)
577
+ writeText(writer, node, ctx, text);
180
578
  },
181
- 'C<>': (0, handlers_1.wrapContent)('`', '`'),
182
579
  'D<>': (writer, processor) => (node, ctx, interator) => {
183
580
  if (!writer.hasOwnProperty('DEFINITIONS')) {
184
581
  writer.DEFINITIONS = [];
@@ -191,7 +588,7 @@ const rules = {
191
588
  'B<>': (0, handlers_1.wrapContent)('**', '**'),
192
589
  'I<>': (0, handlers_1.wrapContent)('*', '*'),
193
590
  'R<>': (0, handlers_1.wrapContent)('*', '*'),
194
- 'K<>': (0, handlers_1.wrapContent)('`', '`'),
591
+ 'K<>': codeSpan,
195
592
  'O<>': (0, handlers_1.wrapContent)('~~', '~~'),
196
593
  'G<>': (writer, processor) => (node, ctx, interator) => {
197
594
  if (ctx.renderMode === 'draft') {
@@ -201,14 +598,17 @@ const rules = {
201
598
  const masked = (0, handlers_1.maskText)((0, handlers_1.collectText)(node.content));
202
599
  // inside S<> the spaces of the hidden phrase stay and do not break, as all its text
203
600
  if (ctx.keepSpaces)
204
- writer.writeRaw(writer.escape((0, handlers_1.expandTabs)(masked, ctx.keepSpaces)).replace(/ /g, '&nbsp;').replace(/\n/g, ' \n'));
601
+ writer.writeRaw(writer
602
+ .escape((0, handlers_1.expandTabs)(masked, ctx.keepSpaces))
603
+ .replace(/ /g, '&nbsp;')
604
+ .replace(/\n/g, keptBreak(writer, ctx)));
205
605
  else
206
- writer.write(masked);
606
+ writer.write(ctx.headingLine && writer.codeDepth > 0 ? masked.replace(/\n/g, ' ') : masked);
207
607
  },
208
608
  'H<>': (0, handlers_1.wrapContent)('<sup>', '</sup>'),
209
609
  'J<>': (0, handlers_1.wrapContent)('<sub>', '</sub>'),
210
- 'L<>': (0, handlers_1.setFn)((node, ctx) => linkWrap(node, ctx)),
211
- 'W<>': (0, handlers_1.setFn)((node, ctx) => linkWrap(node, ctx)),
610
+ 'L<>': (writer, processor) => (node, ctx, interator) => linkWrap(node, ctx, writer.codeDepth > 0)(writer, processor)(node, ctx, interator),
611
+ 'W<>': (writer, processor) => (node, ctx, interator) => linkWrap(node, ctx, writer.codeDepth > 0)(writer, processor)(node, ctx, interator),
212
612
  'N<>': (writer, processor) => {
213
613
  writer.addListener('end', () => {
214
614
  if (!writer.hasOwnProperty('FOOTNOTES')) {
@@ -241,8 +641,9 @@ const rules = {
241
641
  gid,
242
642
  fnRefId: `fnref:${gid}`,
243
643
  fnId: `fn:${gid}`,
644
+ // the note is written at the end of the document, not in the line it is called from
244
645
  make: () => {
245
- interator(node.content, ctx);
646
+ interator(node.content, ctx.headingLine ? { ...ctx, headingLine: false } : ctx);
246
647
  },
247
648
  });
248
649
  };
@@ -259,7 +660,7 @@ const rules = {
259
660
  // a reserved code is shown as written: its letter and brackets around what it holds
260
661
  'Q<>': (writer, processor) => (node, ctx, interator) => writtenCode(writer, node, ctx, interator),
261
662
  'Y<>': (writer, processor) => (node, ctx, interator) => writtenCode(writer, node, ctx, interator),
262
- 'T<>': (0, handlers_1.wrapContent)('`', '`'),
663
+ 'T<>': codeSpan,
263
664
  'U<>': (0, handlers_1.wrapContent)('', ''),
264
665
  'V<>': handlers_1.content,
265
666
  'X<>': (writer, processor) => (node, ctx, interator) => {
@@ -279,55 +680,47 @@ const rules = {
279
680
  },
280
681
  'Z<>': handlers_1.emptyContent,
281
682
  pod: handlers_1.content,
282
- ':code': (0, handlers_1.handleNested)((writer, processor) => (node, ctx, interator) => {
683
+ ':code': handleNested((writer, processor) => (node, ctx, interator) => {
283
684
  const conf = (0, config_1.default)(node, ctx);
284
685
  const lang = conf.exists('lang') ? conf.getFirstValue('lang') : '';
285
- writer.writeRaw('```' + lang + '\n');
286
686
  const masked = (0, guard_1.isCovered)(node, ctx);
287
- if (node.content) {
288
- node.content.forEach(child => {
289
- if (typeof child === 'string') {
290
- writer.writeRaw(masked ? (0, handlers_1.maskText)(child) : child);
291
- }
292
- else if (child.type === 'verbatim') {
293
- writer.writeRaw(masked ? (0, handlers_1.maskText)(child.value) : child.value);
294
- }
295
- else {
296
- interator([child], ctx);
297
- }
298
- });
299
- }
300
- // code at the end of input may lack its final line break
301
- if (!writer.lastWritten.endsWith('\n'))
302
- writer.writeRaw('\n');
303
- writer.writeRaw('```\n');
687
+ writeFenced(writer, lang, () => (node.content || []).forEach(child => {
688
+ if (typeof child === 'string') {
689
+ writeSource(writer, masked ? (0, handlers_1.maskText)(child) : child);
690
+ }
691
+ else if (child.type === 'verbatim') {
692
+ writeSource(writer, masked ? (0, handlers_1.maskText)(child.value) : child.value);
693
+ }
694
+ else {
695
+ interator([child], ctx);
696
+ }
697
+ }));
304
698
  }),
305
- code: (0, handlers_1.handleNested)((writer, processor) => (node, ctx, interator) => {
699
+ code: handleNested((writer, processor) => (node, ctx, interator) => {
306
700
  const conf = (0, config_1.default)(node, ctx);
307
701
  const lang = conf.exists('lang') ? conf.getFirstValue('lang') : '';
308
- writer.writeRaw('```' + lang + '\n');
309
702
  const masked = (0, guard_1.isCovered)(node, ctx);
310
- if (node.content) {
311
- node.content.forEach(child => {
312
- if (typeof child === 'string') {
313
- writer.writeRaw(masked ? (0, handlers_1.maskText)(child) : child);
314
- }
315
- else if (child.type === 'verbatim') {
316
- writer.writeRaw(masked ? (0, handlers_1.maskText)(child.value) : child.value);
317
- }
318
- else {
319
- interator([child], ctx);
320
- }
321
- });
322
- }
323
- writer.writeRaw('```\n');
703
+ writeFenced(writer, lang, () => (node.content || []).forEach(child => {
704
+ if (typeof child === 'string') {
705
+ writeSource(writer, masked ? (0, handlers_1.maskText)(child) : child);
706
+ }
707
+ else if (child.type === 'verbatim') {
708
+ writeSource(writer, masked ? (0, handlers_1.maskText)(child.value) : child.value);
709
+ }
710
+ else {
711
+ interator([child], ctx);
712
+ }
713
+ }));
324
714
  }),
325
715
  data: handlers_1.emptyContent,
716
+ Html: htmlBlock,
326
717
  ':verbatim': (writer, processor) => (node, ctx, interator) => {
327
718
  if (node.error) {
328
719
  writer.emit('errors', node.location);
329
720
  }
330
- writer.writeRaw((0, guard_1.isCovered)(node, ctx) ? (0, handlers_1.maskText)(node.value) : node.value);
721
+ const text = (0, guard_1.isCovered)(node, ctx) ? (0, handlers_1.maskText)(node.value) : node.value;
722
+ // inside a frame of HTML a raw </table> would close the frame and drop the cells after it
723
+ writeSource(writer, writer.htmlDepth > 0 ? htmlText(text) : text);
331
724
  },
332
725
  ':blankline': handlers_1.emptyContent,
333
726
  ':ambient': handlers_1.emptyContent,
@@ -345,7 +738,7 @@ const rules = {
345
738
  return handlers_1.emptyContent;
346
739
  }),
347
740
  // block =para
348
- para: (0, handlers_1.handleNested)(handlers_1.content),
741
+ para: handleNested((writer, processor) => (node, ctx, interator) => paragraph(writer, ctx, () => node.content && interator(node.content, ctx))),
349
742
  ':para': implicitPara,
350
743
  'head:block': (0, handlers_1.subUse)({
351
744
  ':para': handlers_1.content,
@@ -362,26 +755,52 @@ const rules = {
362
755
  writer.writeRaw(prefix);
363
756
  if (numberPrefix)
364
757
  writer.writeRaw(numberPrefix);
365
- if (node.content)
366
- interator(node.content, ctx);
758
+ const note = noteHeading(ctx, node);
759
+ const line = headingLine(writer, () => node.content && interator(node.content, { ...ctx, headingLine: true, __headingNode: node }));
760
+ // a reader of Markdown has six levels of headings; a line of more signs is a paragraph
761
+ note(level <= 6 ? numberPrefix + line.replace(/\n$/, '') : null);
762
+ writer.writeRaw(line);
367
763
  writer.writeRaw('\n');
368
764
  };
369
765
  })),
370
- ':list': (0, handlers_1.setFn)((node, ctx) => {
371
- return (writer, processor) => (node, ctx, interator) => {
372
- // pass list type through context
373
- const newCtx = {
374
- ...ctx,
375
- listType: node.list,
376
- listCounter: { value: 1 },
377
- listDepth: (ctx.listDepth || 0) + 1,
378
- };
379
- if (node.content)
380
- interator(node.content, newCtx);
766
+ // A list deeper than an item right after it belongs to that item: it is written inside
767
+ // the item, with the context of its own list, so a mask of the item does not reach it.
768
+ ':list': (writer, processor) => (node, ctx, interator) => {
769
+ // pass list type through context
770
+ const newCtx = {
771
+ ...ctx,
772
+ itemTail: undefined,
773
+ listType: node.list,
774
+ listCounter: { value: 1 },
775
+ listDepth: (ctx.listDepth || 0) + 1,
381
776
  };
382
- }),
777
+ if (!node.content)
778
+ return;
779
+ if (!ownsLines(writer))
780
+ return interator(node.content, newCtx);
781
+ const children = node.content;
782
+ for (let at = 0; at < children.length; at++) {
783
+ const child = children[at];
784
+ if (child?.type !== 'block' || child.name !== 'item') {
785
+ interator([child], newCtx);
786
+ continue;
787
+ }
788
+ let last = at;
789
+ for (let next = at + 1; next < children.length; next++) {
790
+ const after = children[next];
791
+ if (after?.type === 'list' && Number(after.level) > Number(child.level))
792
+ last = next;
793
+ else if (after?.type !== 'blankline')
794
+ break;
795
+ }
796
+ const tail = children.slice(at + 1, last + 1);
797
+ interator([child], tail.length > 0 ? { ...newCtx, itemTail: { nodes: tail, ctx: newCtx } } : newCtx);
798
+ at = last;
799
+ }
800
+ },
801
+ // The marker of an item stands on the first line of what the item writes; the lines
802
+ // after it are indented by the width of the marker, so they stay in the item.
383
803
  'item:block': (writer, processor) => (node, ctx, interator) => {
384
- const indent = ' '.repeat(Math.max(0, (ctx.listDepth || 1) - 1));
385
804
  const listType = ctx.listType || 'unordered';
386
805
  let prefix;
387
806
  if (listType === 'ordered') {
@@ -389,18 +808,32 @@ const rules = {
389
808
  prefix = `${counter.value}. `;
390
809
  counter.value++;
391
810
  }
392
- else if (listType === 'variable') {
393
- prefix = '- ';
394
- }
395
811
  else {
396
812
  prefix = '- ';
397
813
  }
398
- if (node.checked !== undefined) {
399
- prefix += node.checked ? '[x] ' : '[ ] ';
814
+ const box = node.checked === undefined ? '' : node.checked ? '[x] ' : '[ ] ';
815
+ if (!ownsLines(writer)) {
816
+ writer.writeRaw(' '.repeat(Math.max(0, (ctx.listDepth || 1) - 1)) + prefix + box);
817
+ if (node.content)
818
+ interator(node.content, { ...ctx, inItem: true });
819
+ return;
400
820
  }
401
- writer.writeRaw(indent + prefix);
402
- if (node.content)
403
- interator(node.content, ctx);
821
+ const tail = ctx.itemTail;
822
+ const body = writeAside(writer, () => {
823
+ startLine(writer);
824
+ if (box)
825
+ writer.writeRaw(box);
826
+ if (node.content)
827
+ interator(node.content, { ...ctx, itemTail: undefined });
828
+ if (tail)
829
+ interator(tail.nodes, tail.ctx);
830
+ });
831
+ const indent = ' '.repeat(prefix.length);
832
+ const lines = body.replace(/\n+$/, '').split('\n');
833
+ // an item ends as its content does: a blank line after it keeps a loose list loose,
834
+ // and a tight list of markdown stays tight
835
+ const end = /\n\n$/.test(body) ? '\n\n' : '\n';
836
+ writer.writeRaw(lines.map((line, i) => (i === 0 ? prefix + line : line === '' ? '' : indent + line)).join('\n') + end);
404
837
  },
405
838
  'comment:block': handlers_1.emptyContent,
406
839
  'test:block': (writer, processor) => (node, ctx, interator) => {
@@ -415,7 +848,9 @@ const rules = {
415
848
  const conf = (0, config_1.default)(node, ctx);
416
849
  const absent = conf.exists('absent') && Boolean(conf.getFirstValue('absent'));
417
850
  const selector = (0, handlers_1.collectText)(node.content).trim();
418
- writer.writeRaw(`- ${inlineCode((0, guard_1.isCovered)(node, ctx) ? (0, handlers_1.maskText)(selector) : selector)} `);
851
+ writer.writeRaw('- ');
852
+ writeSource(writer, inlineCode((0, guard_1.isCovered)(node, ctx) ? (0, handlers_1.maskText)(selector) : selector));
853
+ writer.writeRaw(' ');
419
854
  writer.writeRaw(absent ? 'must find no block' : 'must find a block');
420
855
  if (conf.exists('caption')) {
421
856
  writer.writeRaw(': ');
@@ -426,8 +861,10 @@ const rules = {
426
861
  'resource:block': (writer, processor) => (node, ctx, interator) => {
427
862
  const conf = (0, config_1.default)(node, ctx);
428
863
  writer.writeRaw('\nResource');
429
- if (conf.exists('name'))
430
- writer.writeRaw(` ${inlineCode(covered(node, ctx, String(conf.getFirstValue('name'))))}`);
864
+ if (conf.exists('name')) {
865
+ writer.writeRaw(' ');
866
+ writeSource(writer, inlineCode(covered(node, ctx, String(conf.getFirstValue('name')))));
867
+ }
431
868
  writer.writeRaw(':\n\n');
432
869
  writeSourceBlock(writer, node, ctx);
433
870
  },
@@ -453,26 +890,16 @@ const rules = {
453
890
  writer.writeRaw('\n');
454
891
  }),
455
892
  'term:para': termPara,
456
- nested: (0, handlers_1.handleNested)(handlers_1.content, 1),
457
- output: (0, handlers_1.handleNested)((writer, processor) => (node, ctx, interator) => {
458
- writer.writeRaw('```\n');
459
- if (node.content)
460
- interator(node.content, ctx);
461
- writer.writeRaw('```\n');
462
- }, 1),
463
- input: (0, handlers_1.handleNested)((writer, processor) => (node, ctx, interator) => {
464
- writer.writeRaw('```\n');
465
- if (node.content)
466
- interator(node.content, ctx);
467
- writer.writeRaw('```\n');
468
- }, 1),
893
+ nested: handleNested(handlers_1.content, 1),
894
+ output: handleNested(sampleBlock),
895
+ input: handleNested(sampleBlock),
469
896
  // table section
470
- 'table:block': (0, handlers_1.handleNested)((writer, processor) => (node, ctx, interator) => {
897
+ 'table:block': handleNested((writer, processor) => (node, ctx, interator) => {
471
898
  const conf = (0, config_1.default)(node, ctx);
472
899
  // a caption with codes of its own stands as a paragraph: bold around it would
473
900
  // hide the bold inside and break on an emphasis that touches a word
474
901
  if (node.caption) {
475
- interator(node.caption.content, ctx);
902
+ paragraph(writer, ctx, () => interator(node.caption.content, ctx));
476
903
  writer.writeRaw('\n\n');
477
904
  }
478
905
  else if (conf.exists('caption')) {
@@ -494,14 +921,15 @@ const rules = {
494
921
  const n = Number(entry.value);
495
922
  return Number.isFinite(n) && n > 1 ? n : 0;
496
923
  };
497
- // GFM pipe-tables don't support colspan/rowspan — fall back to inline HTML
498
- const hasSpans = rows.some(row => (row.content || []).some(c => c.name === 'cell' && (cellSpan(c, 'colspan') || cellSpan(c, 'rowspan'))));
924
+ // GFM pipe-tables hold neither a merged cell nor a block in a cell: such a table is
925
+ // written as a frame of HTML whose cells hold Markdown
926
+ const hasSpans = rows.some(row => (row.content || []).some(c => c.name === 'cell' && (cellSpan(c, 'colspan') || cellSpan(c, 'rowspan') || holdsBlock(c))));
499
927
  const hasHeader = isRowHeader(rows[0]);
500
928
  if (hasSpans) {
501
929
  writer.writeRaw('<table>\n');
502
- rows.forEach(row => {
930
+ within(writer, 'htmlDepth', () => rows.forEach(row => {
503
931
  const tag = isRowHeader(row) ? 'th' : 'td';
504
- writer.writeRaw('<tr>');
932
+ writer.writeRaw('<tr>\n');
505
933
  const cells = (row.content || []).filter(c => c.name === 'cell');
506
934
  cells.forEach(cell => {
507
935
  const colspan = cellSpan(cell, 'colspan');
@@ -511,32 +939,21 @@ const rules = {
511
939
  attrs += ` colspan="${colspan}"`;
512
940
  if (rowspan)
513
941
  attrs += ` rowspan="${rowspan}"`;
514
- writer.writeRaw(`<${tag}${attrs}>`);
515
- writeCellParts(cell, writer, interator, ctx);
516
- writer.writeRaw(`</${tag}>`);
942
+ writeIsland(writer, `<${tag}${attrs}>`, `</${tag}>`, () => writeCellParts(cell, writer, interator, ctx));
517
943
  });
518
944
  writer.writeRaw('</tr>\n');
519
- });
520
- writer.writeRaw('</table>\n');
945
+ }));
946
+ // a blank line ends the block of HTML, or the text after it is read as HTML too
947
+ writer.writeRaw('</table>\n\n');
521
948
  return;
522
949
  }
523
950
  // A cell holds a paragraph when the table is written as blocks, and a
524
951
  // paragraph prints line breaks that would tear the row apart. The cell is
525
952
  // rendered aside and folded onto one line.
526
953
  const renderCell = cell => {
527
- const parts = [];
528
- const original = writer.output;
529
- if (typeof original !== 'function')
954
+ if (typeof writer.output !== 'function')
530
955
  return null;
531
- writer.output = (str) => parts.push(str);
532
- try {
533
- writeCellParts(cell, writer, interator, ctx);
534
- }
535
- finally {
536
- writer.output = original;
537
- }
538
- return parts
539
- .join('')
956
+ return writeAside(writer, () => within(writer, 'cellDepth', () => writeCellParts(cell, writer, interator, ctx)))
540
957
  .replace(/\s*\n+\s*/g, ' ')
541
958
  .trim();
542
959
  };
@@ -548,7 +965,7 @@ const rules = {
548
965
  writer.writeRaw(' ');
549
966
  const folded = renderCell(cell);
550
967
  if (folded === null) {
551
- writeCellParts(cell, writer, interator, ctx);
968
+ within(writer, 'cellDepth', () => writeCellParts(cell, writer, interator, ctx));
552
969
  }
553
970
  else {
554
971
  writer.writeRaw(folded);
@@ -585,13 +1002,56 @@ const rules = {
585
1002
  ':image': (writer, processor) => (node, ctx, interator) => {
586
1003
  // the alternative text sits between square brackets, where a `]` of its own
587
1004
  // would end it, and the address between round ones — the same shape a link has
588
- const alt = covered(node, ctx, (0, ast_helpers_1.writtenValue)(node.alt) ?? '').replace(/([[\]\\])/g, '\\$1');
589
- const src = markdownAddress(String((0, image_base_1.applyImageBase)(node.src, ctx?.base) ?? ''));
590
- writer.writeRaw(`![${alt}](${src})`);
1005
+ const inCode = writer.codeDepth > 0;
1006
+ const bracketed = covered(node, ctx, (0, ast_helpers_1.writtenValue)(node.alt) ?? '').replace(/([[\]\\])/g, '\\$1');
1007
+ const alt = inCode ? bracketed : keepReferences(bracketed);
1008
+ const src = markdownAddress(String((0, image_base_1.applyImageBase)(node.src, ctx?.base) ?? ''), inCode);
1009
+ const title = typeof node.title === 'string' ? quotedTitle(covered(node, ctx, node.title), inCode) : '';
1010
+ writer.writeRaw(`![${alt}](${src}${title})`);
591
1011
  },
592
1012
  };
1013
+ // The output walks the document aside to learn the line it writes for each heading, and
1014
+ // builds the addresses of its links from the text a reader shows for those lines. When a
1015
+ // heading line holds a link to this document in code, the line depends on the addresses:
1016
+ // the heading and its target are named, and the walk is repeated until the texts stay.
1017
+ // The walk aside writes as the writer of the walk does when that writer writes Markdown.
1018
+ const asideWriter = writer => (writer instanceof writerMarkdown_1.default ? writer.constructor : writerMarkdown_1.default);
1019
+ const prepare = (tree, context, walk) => {
1020
+ const named = (0, ast_helpers_1.headingsWithCodeLinks)(tree, context.__bindings);
1021
+ const ofTree = (0, ast_helpers_1.nodesOfTree)(tree);
1022
+ let written;
1023
+ let stable = false;
1024
+ // Each walk settles one more link of a chain of such headings, and a chain is no longer
1025
+ // than the headings the first walk wrote: the number of walks is fixed by then.
1026
+ for (let read = 1, limit = 2; read <= limit; read++) {
1027
+ const lines = [];
1028
+ const codeLinks = new Set();
1029
+ walk({ ...context, __headingLines: lines, __codeLinks: codeLinks, __codeLinkHeadings: named, __readerTexts: written }, asideWriter);
1030
+ if (read === 1)
1031
+ limit = lines.length + 2;
1032
+ const next = lines.map(({ node, line }) => ({ node, text: line === null ? null : (0, markdown_heading_text_1.headingTextOf)(line) }));
1033
+ const before = named.size;
1034
+ // a heading an alias brings is a new node on every walk: it cannot be named, and its
1035
+ // text is compared, not the node
1036
+ codeLinks.forEach(node => ofTree.has(node) && named.add(node));
1037
+ const same = written !== undefined &&
1038
+ written.length === next.length &&
1039
+ written.every((entry, at) => entry.text === next[at].text);
1040
+ written = next;
1041
+ // without links in code, no line depends on an address and one walk is enough
1042
+ if (codeLinks.size === 0 || (same && named.size === before)) {
1043
+ stable = true;
1044
+ break;
1045
+ }
1046
+ }
1047
+ if (!stable)
1048
+ console.warn('[podlite] the addresses of the markdown headings do not settle; a link may lead to the wrong one');
1049
+ context.__codeLinkHeadings = named;
1050
+ context.__readerTexts = written;
1051
+ };
593
1052
  const toMarkdown = opt => (0, exportAny_1.default)({
594
1053
  writer: writerMarkdown_1.default,
1054
+ prepare,
595
1055
  ...opt,
596
1056
  context: { renderMode: opt?.renderMode || 'production', base: opt?.base, ...(opt?.context || {}) },
597
1057
  })
@@ -602,11 +1062,18 @@ const toMarkdown = opt => (0, exportAny_1.default)({
602
1062
  const isTypeBlock = (node.type || '') === 'block';
603
1063
  return isTypeBlock && name === name.toUpperCase();
604
1064
  };
1065
+ if (blockWithoutRule(writer, node, ctx, interator))
1066
+ return;
1067
+ if ((0, title_1.isTitleBlock)(node))
1068
+ return titleBlock(writer, node, ctx, interator);
605
1069
  if (isSemanticBlock(node)) {
606
- const name = node.name;
607
- writer.writeRaw('# ');
608
- writer.write(covered(node, ctx, String(name)));
609
- writer.writeRaw('\n\n');
1070
+ const name = writeAside(writer, () => writer.write(covered(node, ctx, String(node.name))));
1071
+ noteHeading(ctx, node)(name);
1072
+ const anchors = markdownAnchors(ctx);
1073
+ const own = anchors?.named?.has(node) ? anchors.byNode.get(node) : undefined;
1074
+ if (own)
1075
+ writer.writeRaw(`<a name="${(0, html_attr_1.quoteAttribute)(own)}"></a>\n\n`);
1076
+ writer.writeRaw(`# ${name}\n\n`);
610
1077
  }
611
1078
  if (node.hasOwnProperty('content')) {
612
1079
  interator(node.content, ctx);