markdown-pdf-export 2.1.0 → 2.2.0

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.
package/export.mjs CHANGED
@@ -28,7 +28,7 @@ import {
28
28
  readSettingsFile,
29
29
  userSettingsPath,
30
30
  } from "./lib/settings-loader.mjs";
31
- import { applyPresets } from "./lib/looks.mjs";
31
+ import { accentCss, applyPresets, normalizeAccentColor } from "./lib/looks.mjs";
32
32
  import { PAGE_BREAK_CSS, pageBreakComments } from "./lib/page-breaks.mjs";
33
33
  import {
34
34
  createPlaceholderResolver,
@@ -94,6 +94,7 @@ export const DEFAULT_SETTINGS = {
94
94
  // content / rendering
95
95
  font_family: null,
96
96
  heading_font_family: null,
97
+ accent_color: null,
97
98
  include_default_styles: true,
98
99
  highlight: true,
99
100
  highlight_style: "github.css",
@@ -342,6 +343,7 @@ export function normalizeSettings(raw) {
342
343
 
343
344
  font_family: normalizeNonEmptyString(safe.font_family),
344
345
  heading_font_family: normalizeNonEmptyString(safe.heading_font_family),
346
+ accent_color: normalizeAccentColor(safe.accent_color),
345
347
 
346
348
  // Structured header/footer configs – pass through as-is for the
347
349
  // config-merger / html-generator pipeline to consume.
@@ -560,6 +562,7 @@ function buildEffectiveOptions(args = {}, settings) {
560
562
  normalizeNonEmptyString(args.font_family) ?? settings.font_family,
561
563
  heading_font_family:
562
564
  normalizeNonEmptyString(args.heading_font_family) ?? settings.heading_font_family,
565
+ accent_color: normalizeAccentColor(args.accent_color) ?? settings.accent_color,
563
566
  };
564
567
  }
565
568
 
@@ -896,6 +899,7 @@ export async function doctorMarkdownPdf(args) {
896
899
  display_header_footer: doc.settings.display_header_footer,
897
900
  font_family: doc.settings.font_family,
898
901
  heading_font_family: doc.settings.heading_font_family,
902
+ accent_color: doc.settings.accent_color,
899
903
  header: doc.settings.header,
900
904
  footer: doc.settings.footer,
901
905
  },
@@ -969,6 +973,7 @@ export async function exportMarkdownPdf(args) {
969
973
  margin: options.margin,
970
974
  font_family: options.font_family,
971
975
  heading_font_family: options.heading_font_family,
976
+ accent_color: options.accent_color,
972
977
  include_default_styles: options.include_default_styles,
973
978
  highlight: options.highlight,
974
979
  highlight_style: options.highlight_style,
@@ -1002,6 +1007,7 @@ export async function exportMarkdownPdf(args) {
1002
1007
  margin: mergedConfig.margin ?? options.margin,
1003
1008
  font_family: mergedConfig.font_family ?? options.font_family,
1004
1009
  heading_font_family: mergedConfig.heading_font_family ?? options.heading_font_family,
1010
+ accent_color: normalizeAccentColor(mergedConfig.accent_color) ?? options.accent_color,
1005
1011
  include_default_styles:
1006
1012
  mergedConfig.include_default_styles ?? options.include_default_styles,
1007
1013
  highlight: mergedConfig.highlight ?? options.highlight,
@@ -1303,6 +1309,9 @@ async function renderMarkdownToHtmlWithBody(inputPath, body, title, options) {
1303
1309
  if (options.heading_font_family) {
1304
1310
  styleBlocks += `<style>h1, h2, h3, h4, h5, h6 { font-family: ${options.heading_font_family}; }</style>\n `;
1305
1311
  }
1312
+ // Accent colour: only page styles that read --accent change with it.
1313
+ const accent = accentCss(options.accent_color);
1314
+ if (accent) styleBlocks += `<style>${accent}</style>\n `;
1306
1315
 
1307
1316
  const baseHref = `${pathToFileURL(path.dirname(inputPath)).href}/`;
1308
1317
 
package/lib/looks.mjs CHANGED
@@ -14,7 +14,11 @@ import { fileURLToPath } from "node:url";
14
14
 
15
15
  const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
16
16
 
17
- /** @type {Record<string, {description: string, settings: object}>} */
17
+ /**
18
+ * `accent` = the colour of titles, rules and code bars in that style; only the
19
+ * styles that have one let `accent_color` change it.
20
+ * @type {Record<string, {description: string, accent?: string, settings: object}>}
21
+ */
18
22
  export const LOOKS = {
19
23
  clean: {
20
24
  description: "Default. GitHub-style, neutral.",
@@ -22,6 +26,7 @@ export const LOOKS = {
22
26
  },
23
27
  report: {
24
28
  description: "Serif headings, strong title rule. Business reports.",
29
+ accent: "#24292e",
25
30
  settings: { stylesheet: "report.css", highlight_style: "github.css" },
26
31
  },
27
32
  academic: {
@@ -41,6 +46,7 @@ export const LOOKS = {
41
46
  },
42
47
  technical: {
43
48
  description: "For documents with code: framed code blocks, blue accents.",
49
+ accent: "#0969da",
44
50
  settings: { stylesheet: "technical.css", highlight_style: "atom-one-light.css" },
45
51
  },
46
52
  };
@@ -51,6 +57,8 @@ export const FONTS = {
51
57
  book: '"Iowan Old Style", "Palatino Linotype", Palatino, "Book Antiqua", Georgia, serif',
52
58
  humanist: 'Seravek, "Gill Sans Nova", "Gill Sans", Ubuntu, Calibri, "DejaVu Sans", sans-serif',
53
59
  geometric: 'Avenir, "Avenir Next", Montserrat, Corbel, "Century Gothic", "URW Gothic", sans-serif',
60
+ // Microsoft Office's default fonts; Carlito = free, same-width stand-in for Calibri (Linux).
61
+ office: 'Aptos, Calibri, Carlito, "Segoe UI", Arial, sans-serif',
54
62
  mono: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
55
63
  system: "system-ui, sans-serif",
56
64
  };
@@ -62,6 +70,7 @@ export const FONT_LABELS = {
62
70
  book: "Book serif",
63
71
  humanist: "Humanist sans",
64
72
  geometric: "Geometric sans",
73
+ office: "Office",
65
74
  mono: "Mono",
66
75
  system: "System",
67
76
  };
@@ -94,6 +103,20 @@ export function readTemplate(name) {
94
103
  return data;
95
104
  }
96
105
 
106
+ /** A valid `accent_color` (#rgb or #rrggbb), else null. */
107
+ export function normalizeAccentColor(value) {
108
+ if (typeof value !== "string") return null;
109
+ const v = value.trim();
110
+ return /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i.test(v) ? v.toLowerCase() : null;
111
+ }
112
+
113
+ /** CSS that hands an accent colour to the page styles (they read --accent*). */
114
+ export function accentCss(color) {
115
+ const c = normalizeAccentColor(color);
116
+ if (!c) return "";
117
+ return `:root { --accent: ${c}; --accent-strong: color-mix(in srgb, ${c} 80%, black); --accent-soft: color-mix(in srgb, ${c} 8%, white); }`;
118
+ }
119
+
97
120
  const isPlain = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
98
121
 
99
122
  function merge(base, over) {
@@ -0,0 +1,149 @@
1
+ /**
2
+ * @fileoverview Setup helpers behind the MCP tools `install_browser_markdown_pdf`
3
+ * and `open_studio_markdown_pdf`, so an assistant can finish the setup without
4
+ * the user opening a terminal (or having Node installed: the editor's own
5
+ * Node runs the server).
6
+ */
7
+ import { spawn } from "node:child_process";
8
+ import os from "node:os";
9
+ import path from "node:path";
10
+ import process from "node:process";
11
+
12
+ import { PROJECT_SETTINGS_FILENAME, userSettingsPath } from "./settings-loader.mjs";
13
+
14
+ /**
15
+ * Wrap a long browser download so one tool call never blocks for minutes.
16
+ * The download keeps running in the server after `run()` returns
17
+ * "installing"; later calls join the same download.
18
+ *
19
+ * @param {() => Promise<void>} install
20
+ * @param {{ waitMs?: number }} [opts]
21
+ */
22
+ export function createBrowserInstaller(install, { waitMs = 50_000 } = {}) {
23
+ /** @type {Promise<"installed"> | null} */
24
+ let running = null;
25
+ /** @type {string | null} */
26
+ let lastError = null;
27
+
28
+ return {
29
+ /** @returns {"idle"|"installing"|"failed"} */
30
+ status: () => (running ? "installing" : lastError ? "failed" : "idle"),
31
+ lastError: () => lastError,
32
+
33
+ /** @returns {Promise<"installed"|"installing">} rejects if the install fails in time */
34
+ async run() {
35
+ if (!running) {
36
+ lastError = null;
37
+ running = install().then(
38
+ () => {
39
+ running = null;
40
+ return /** @type {const} */ ("installed");
41
+ },
42
+ (error) => {
43
+ running = null;
44
+ lastError = error instanceof Error ? error.message : String(error);
45
+ throw error;
46
+ },
47
+ );
48
+ // A failure after the caller stopped waiting must not crash the server.
49
+ running.catch(() => {});
50
+ }
51
+ let timer;
52
+ const timeout = new Promise((resolve) => {
53
+ timer = setTimeout(() => resolve(/** @type {const} */ ("installing")), waitMs);
54
+ });
55
+ try {
56
+ return await Promise.race([running, timeout]);
57
+ } finally {
58
+ clearTimeout(timer);
59
+ }
60
+ },
61
+ };
62
+ }
63
+
64
+ const STUDIO_URL = /^http:\/\/127\.0\.0\.1:\d+\/#[0-9a-f]+$/;
65
+
66
+ /**
67
+ * Start `cli.mjs studio` in its own process and resolve with its private URL.
68
+ *
69
+ * Studio swaps the exporter's settings while it renders previews, so it must
70
+ * not share a process with the MCP server. The child is detached: it outlives
71
+ * a server restart and stops by itself a few minutes after its page is closed.
72
+ *
73
+ * @param {object} opts
74
+ * @param {string} opts.cliPath path to cli.mjs
75
+ * @param {string} [opts.file] Markdown file to preview
76
+ * @param {string} [opts.projectFolder] edit <folder>/.markdown-pdf.json instead of the user file
77
+ * @param {boolean} [opts.openBrowser] default true
78
+ * @param {number} [opts.timeoutMs] default 15 s
79
+ * @returns {Promise<{ url: string, settingsPath: string, pid: number }>}
80
+ */
81
+ export function launchStudio({
82
+ cliPath,
83
+ file,
84
+ projectFolder,
85
+ openBrowser = true,
86
+ timeoutMs = 15_000,
87
+ }) {
88
+ const args = [cliPath, "studio"];
89
+ if (projectFolder) args.push("--project");
90
+ if (file) args.push("--file", path.resolve(file));
91
+ if (!openBrowser) args.push("--no-open");
92
+ // Same rule as startStudio(); the child inherits this process's environment.
93
+ const settingsPath = projectFolder
94
+ ? path.join(path.resolve(projectFolder), PROJECT_SETTINGS_FILENAME)
95
+ : userSettingsPath();
96
+
97
+ return new Promise((resolve, reject) => {
98
+ const child = spawn(process.execPath, args, {
99
+ cwd: projectFolder ? path.resolve(projectFolder) : os.homedir(),
100
+ stdio: ["ignore", "pipe", "pipe"],
101
+ detached: true,
102
+ windowsHide: true,
103
+ });
104
+
105
+ let stdout = "";
106
+ let stderr = "";
107
+ let settled = false;
108
+ const finish = (fn) => {
109
+ if (settled) return;
110
+ settled = true;
111
+ clearTimeout(timer);
112
+ fn();
113
+ };
114
+
115
+ const timer = setTimeout(
116
+ () =>
117
+ finish(() => {
118
+ child.kill();
119
+ reject(new Error(`Studio did not start within ${timeoutMs / 1000} s.\n${stderr.trim()}`));
120
+ }),
121
+ timeoutMs,
122
+ );
123
+
124
+ child.stderr.on("data", (chunk) => {
125
+ stderr += chunk.toString();
126
+ });
127
+ child.stdout.on("data", (chunk) => {
128
+ stdout += chunk.toString();
129
+ const url = stdout.split(/\r?\n/).map((line) => line.trim()).find((line) => STUDIO_URL.test(line));
130
+ if (!url) return;
131
+ finish(() => {
132
+ // Keep draining the pipes so the child never blocks on a full buffer,
133
+ // but let the server exit without waiting for Studio.
134
+ child.stdout.unref?.();
135
+ child.stderr.unref?.();
136
+ child.unref();
137
+ resolve({ url, settingsPath, pid: child.pid });
138
+ });
139
+ });
140
+ child.on("error", (error) =>
141
+ finish(() => reject(new Error(`Could not start Studio: ${error.message}`))),
142
+ );
143
+ child.on("exit", (code) =>
144
+ finish(() =>
145
+ reject(new Error(`Studio stopped before it was ready (exit ${code}).\n${stderr.trim()}`)),
146
+ ),
147
+ );
148
+ });
149
+ }
@@ -268,6 +268,7 @@ export async function startStudio(opts = {}) {
268
268
  description: def.description,
269
269
  margin: def.settings.margin ?? null,
270
270
  highlight: def.settings.highlight_style ?? null,
271
+ accent: def.accent ?? null,
271
272
  };
272
273
  }
273
274
  return {
package/looks/report.css CHANGED
@@ -1,8 +1,9 @@
1
- /* Look: report — serif headings, restrained rules, roomy paragraphs. */
1
+ /* Look: report — serif headings, restrained rules, roomy paragraphs.
2
+ Accent colours come from accent_color when set (see accentCss in lib/looks.mjs). */
2
3
  :root { line-height: 1.7; }
3
4
  h1, h2, h3 { font-family: Georgia, "Times New Roman", serif; letter-spacing: -0.01em; }
4
- h1 { border-bottom: 2px solid #24292e; }
5
+ h1 { border-bottom: 2px solid var(--accent, #24292e); }
5
6
  h2 { border-bottom: 1px solid #d0d7de; }
6
7
  table { border-collapse: collapse; }
7
8
  th { background: #f6f8fa; }
8
- blockquote { border-left: 4px solid #0969da; color: #57606a; }
9
+ blockquote { border-left: 4px solid var(--accent, #0969da); color: #57606a; }
@@ -1,11 +1,12 @@
1
- /* Look: technical — for documents with code: framed code blocks, blue accents. */
1
+ /* Look: technical — for documents with code: framed code blocks, blue accents.
2
+ Accent colours come from accent_color when set (see accentCss in lib/looks.mjs). */
2
3
  :root { font-size: 13px; }
3
- h1 { border-bottom: 3px solid #0969da; }
4
- h2 { border-bottom: none; color: #0550ae; }
4
+ h1 { border-bottom: 3px solid var(--accent, #0969da); }
5
+ h2 { border-bottom: none; color: var(--accent-strong, #0550ae); }
5
6
  pre.hljs, pre:not(.hljs) {
6
7
  border: 1px solid #d0d7de;
7
- border-left: 3px solid #0969da;
8
+ border-left: 3px solid var(--accent, #0969da);
8
9
  border-radius: 4px;
9
10
  }
10
- :not(pre) > code { color: #0550ae; background: #eef4fb; }
11
- th { background: #eef4fb; }
11
+ :not(pre) > code { color: var(--accent-strong, #0550ae); background: var(--accent-soft, #eef4fb); }
12
+ th { background: var(--accent-soft, #eef4fb); }
package/mcp.mjs CHANGED
@@ -1,11 +1,13 @@
1
1
  /**
2
2
  * Markdown PDF MCP server (stdio).
3
3
  *
4
- * Thin transport around export.mjs: framing, JSON-RPC dispatch, two tools.
4
+ * Thin transport around export.mjs: framing, JSON-RPC dispatch, four tools
5
+ * (export, doctor, and two setup helpers from lib/mcp-setup.mjs).
5
6
  * Settings: user file (~/.config/markdown-pdf-export/settings.json) or the
6
7
  * MARKDOWN_PDF_SETTINGS env var, plus the nearest .markdown-pdf.json — see
7
8
  * lib/settings-loader.mjs.
8
9
  */
10
+ import path from "node:path";
9
11
  import process from "node:process";
10
12
  import { fileURLToPath } from "node:url";
11
13
 
@@ -15,9 +17,20 @@ import {
15
17
  debugLog,
16
18
  exportMarkdownPdf,
17
19
  doctorMarkdownPdf,
20
+ installBrowser,
21
+ launchBrowser,
22
+ reloadSettings,
18
23
  } from "./export.mjs";
24
+ import { createBrowserInstaller, launchStudio } from "./lib/mcp-setup.mjs";
19
25
  import { TOOLS } from "./tool-schemas.mjs";
20
26
 
27
+ const CLI_PATH = path.join(path.dirname(fileURLToPath(import.meta.url)), "cli.mjs");
28
+ const NO_BROWSER = "No usable Chrome/Chromium browser found";
29
+ const MCP_BROWSER_HINT =
30
+ "No Chrome or Edge found. Ask the user, then call install_browser_markdown_pdf " +
31
+ "to download Chromium (about 200 MB).";
32
+ const browserInstaller = createBrowserInstaller(() => installBrowser());
33
+
21
34
  debugLog(`server starting — pid=${process.pid} node=${process.execPath}`);
22
35
  debugLog(`argv=${JSON.stringify(process.argv)}`);
23
36
  debugLog(`cwd=${process.cwd()}`);
@@ -232,21 +245,94 @@ async function callTool(name, args) {
232
245
  try {
233
246
  switch (name) {
234
247
  case "export_markdown_pdf":
248
+ // Pick up edits made in Studio (or by hand) since the server started.
249
+ reloadSettings();
235
250
  return toolResult(await exportMarkdownPdf(args));
236
251
 
237
252
  case "doctor_markdown_pdf":
238
- return toolResult(await doctorMarkdownPdf(args));
253
+ reloadSettings();
254
+ return toolResult(await doctor(args));
255
+
256
+ case "install_browser_markdown_pdf":
257
+ return toolResult(await installBrowserTool(args));
258
+
259
+ case "open_studio_markdown_pdf":
260
+ return toolResult(await openStudioTool(args));
239
261
 
240
262
  default:
241
263
  throw new Error(`Unknown tool: ${name}`);
242
264
  }
243
265
  } catch (error) {
244
- const message = error instanceof Error ? error.message : String(error);
266
+ let message = error instanceof Error ? error.message : String(error);
267
+ if (message.includes(NO_BROWSER)) message += `\n\n${MCP_BROWSER_HINT}`;
245
268
  debugLog(`callTool(${name}) error: ${message}`);
246
269
  return toolError(message);
247
270
  }
248
271
  }
249
272
 
273
+ async function doctor(args) {
274
+ const report = await doctorMarkdownPdf(args);
275
+ if (report.browser && !report.browser.available) {
276
+ report.browser.hint =
277
+ browserInstaller.status() === "installing"
278
+ ? "Chromium is downloading. Check again in a minute."
279
+ : MCP_BROWSER_HINT;
280
+ if (browserInstaller.status() === "failed") {
281
+ report.browser.last_install_error = browserInstaller.lastError();
282
+ }
283
+ }
284
+ return report;
285
+ }
286
+
287
+ async function installBrowserTool(args) {
288
+ if (!args.force && browserInstaller.status() !== "installing") {
289
+ try {
290
+ const browser = await launchBrowser();
291
+ const version = browser.version();
292
+ await browser.close();
293
+ return {
294
+ status: "already_available",
295
+ browser: version,
296
+ message: "A browser already works; nothing was downloaded. Pass force: true to download Chromium anyway.",
297
+ };
298
+ } catch {
299
+ // none found → download below
300
+ }
301
+ }
302
+ const status = await browserInstaller.run();
303
+ return status === "installed"
304
+ ? { status, message: "Chromium is installed. PDFs can be exported now." }
305
+ : {
306
+ status,
307
+ message: "The download is still running (about 200 MB). Call doctor_markdown_pdf in a minute to check.",
308
+ };
309
+ }
310
+
311
+ async function openStudioTool(args) {
312
+ const studio = await launchStudio({
313
+ cliPath: CLI_PATH,
314
+ file: args.file,
315
+ projectFolder: args.project_folder,
316
+ openBrowser: args.open_browser !== false,
317
+ });
318
+ const result = {
319
+ url: studio.url,
320
+ settings_file: studio.settingsPath,
321
+ message:
322
+ (args.open_browser === false
323
+ ? "Studio is running. Give the user this private link."
324
+ : "Studio is open in the browser. If no page appeared, give the user this private link.") +
325
+ " Choices saved in Studio apply to the next export. Studio stops by itself a few minutes after its page is closed.",
326
+ };
327
+ const env = (process.env.MARKDOWN_PDF_SETTINGS ?? "").trim();
328
+ if (env && env !== "{}" && !args.project_folder) {
329
+ result.warning =
330
+ "This server reads its settings from MARKDOWN_PDF_SETTINGS, not from the file Studio edits, " +
331
+ "so Studio changes will not apply to exports until that variable is removed.";
332
+ }
333
+ return result;
334
+ }
335
+
250
336
  function toolResult(data) {
251
337
  return {
252
338
  content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "markdown-pdf-export",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "Markdown to PDF with your header, footer, page numbers and logo. Design pages in Studio, export from VS Code, Zed, Cursor, Claude or any MCP client, or the command line.",
5
5
  "type": "module",
6
6
  "mcpName": "io.github.matinfo-tech/markdown-pdf-export",
@@ -257,6 +257,11 @@
257
257
  "type": "string",
258
258
  "description": "CSS font-family value for headings (h1-h6). Default: same as the body text."
259
259
  },
260
+ "accent_color": {
261
+ "type": "string",
262
+ "pattern": "^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$",
263
+ "description": "Accent colour of the page style, as #rgb or #rrggbb: title rules, coloured titles, code block bars. Used by the report and technical looks; the others have no accent."
264
+ },
260
265
  "look": {
261
266
  "type": "string",
262
267
  "enum": [
@@ -276,6 +281,7 @@
276
281
  "book",
277
282
  "humanist",
278
283
  "geometric",
284
+ "office",
279
285
  "mono",
280
286
  "system"
281
287
  ],
@@ -289,6 +295,7 @@
289
295
  "book",
290
296
  "humanist",
291
297
  "geometric",
298
+ "office",
292
299
  "mono",
293
300
  "system"
294
301
  ],
package/studio/app.mjs CHANGED
@@ -8,6 +8,7 @@ import {
8
8
  ZONES,
9
9
  draftToSettings,
10
10
  emptyDraft,
11
+ lookAccent,
11
12
  lookDefaults,
12
13
  matchLayout,
13
14
  renderText,
@@ -66,6 +67,11 @@ const thumbs = new Map(); // image path → object URL of the file just uploaded
66
67
  const AREA_NAMES = { header: "Top", footer: "Bottom" };
67
68
  const SIZE_LABELS = { s: "Small", m: "Medium", l: "Large" };
68
69
  const MARGIN_LABELS = { narrow: "Narrow", normal: "Normal", wide: "Wide" };
70
+ /** What the theme colour paints, per page style that has one. */
71
+ const ACCENT_HINTS = {
72
+ technical: "Title rule, section titles, code bars.",
73
+ report: "Title rule and quote bars.",
74
+ };
69
75
  const LOOK_LABELS = { clean: "Clean", report: "Report", academic: "Academic", compact: "Compact", technical: "Technical" };
70
76
 
71
77
  const currentSettings = () => draftToSettings(draft, raw, { looks: server.looks });
@@ -120,6 +126,9 @@ function build() {
120
126
  $(id).addEventListener("change", (e) => change(() => (draft[key] = e.target.value)));
121
127
  }
122
128
 
129
+ $("accent").addEventListener("input", (e) => change(() => (draft.accent = e.target.value)));
130
+ $("accent-reset").addEventListener("click", () => change(() => (draft.accent = "")));
131
+
123
132
  $("format").replaceChildren(...server.pageFormats.map((f) => el("option", { value: f, text: f })));
124
133
  $("format").addEventListener("change", (e) => change(() => (draft.page_format = e.target.value)));
125
134
 
@@ -357,6 +366,7 @@ function sync() {
357
366
  $(id).value = draft[key];
358
367
  $(id).style.fontFamily = server.fonts[draft[key]] ?? ""; // the control shows its own choice
359
368
  }
369
+ syncAccent();
360
370
  $("format").value = draft.page_format;
361
371
  $("highlight").value = draft.highlight;
362
372
  // The diagram's side padding follows the margins, so text and rules sit where they will print.
@@ -390,6 +400,18 @@ function sync() {
390
400
  }
391
401
  }
392
402
 
403
+ /** Theme colour: offered only for page styles that have one. */
404
+ function syncAccent() {
405
+ const own = lookAccent(draft.look, server.looks);
406
+ $("accent-box").hidden = !own;
407
+ if (!own) return;
408
+ const value = draft.accent || own;
409
+ $("accent").value = value;
410
+ $("accent-swatch").style.background = value;
411
+ $("accent-hint").textContent = ACCENT_HINTS[draft.look] ?? "";
412
+ $("accent-reset").hidden = !draft.accent || draft.accent.toLowerCase() === own;
413
+ }
414
+
393
415
  // ── preview ─────────────────────────────────────────────────────────────────
394
416
  let previewTimer = null;
395
417
  let previewRun = 0;
package/studio/index.html CHANGED
@@ -32,6 +32,15 @@
32
32
  <label class="label" for="heading-font">Title font</label>
33
33
  <select id="heading-font"></select>
34
34
 
35
+ <details class="more" id="accent-box">
36
+ <summary><span class="swatch" id="accent-swatch"></span>Theme colour</summary>
37
+ <div class="more-body">
38
+ <input type="color" class="color" id="accent" aria-label="Theme colour">
39
+ <span class="hint" id="accent-hint"></span>
40
+ <button type="button" class="btn small quiet" id="accent-reset">Reset</button>
41
+ </div>
42
+ </details>
43
+
35
44
  <label class="label" for="format">Paper</label>
36
45
  <div class="pair">
37
46
  <select id="format"></select>
package/studio/model.mjs CHANGED
@@ -5,7 +5,9 @@
5
5
  *
6
6
  * Draft shape:
7
7
  * { look, font, heading_font, highlight, page_format, orientation, margin,
8
- * header: Area, footer: Area, text_size, color }
8
+ * header: Area, footer: Area, text_size, color, accent }
9
+ * accent = "" (the page style's own colour) or "#rrggbb"; written only for
10
+ * page styles that have an accent
9
11
  * font / heading_font = a preset name, "look" (whatever the page style
10
12
  * brings) or "custom" (a hand-written font_family kept from the file)
11
13
  * Area = { left: Slot, center: Slot, right: Slot, line: boolean, custom: boolean }
@@ -90,6 +92,7 @@ export function emptyDraft() {
90
92
  footer: area(),
91
93
  text_size: "m",
92
94
  color: DEFAULT_COLOR,
95
+ accent: "",
93
96
  };
94
97
  }
95
98
 
@@ -106,6 +109,15 @@ export function lookMargin(look, looks = {}) {
106
109
  return mm(looks[look]?.margin?.left) ?? MARGINS.normal;
107
110
  }
108
111
 
112
+ const HEX = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;
113
+ const longHex = (c) => (c.length === 4 ? `#${[...c.slice(1)].map((x) => x + x).join("")}` : c).toLowerCase();
114
+
115
+ /** Accent colour a look brings, or null when the look has none (no colour to change). */
116
+ export function lookAccent(look, looks = {}) {
117
+ const a = looks[look]?.accent;
118
+ return typeof a === "string" && HEX.test(a) ? longHex(a) : null;
119
+ }
120
+
109
121
  /** What picking a look suggests for the controls it influences. */
110
122
  export function lookDefaults(look, looks = {}) {
111
123
  return {
@@ -170,6 +182,9 @@ export function settingsToDraft(raw, ctx = {}) {
170
182
  if (typeof raw.heading_font === "string") draft.heading_font = raw.heading_font;
171
183
  else if (typeof raw.heading_font_family === "string" && raw.heading_font_family) draft.heading_font = "custom";
172
184
  draft.highlight = typeof raw.highlight_style === "string" ? raw.highlight_style : defaults.highlight;
185
+ if (typeof raw.accent_color === "string" && HEX.test(raw.accent_color.trim())) {
186
+ draft.accent = longHex(raw.accent_color.trim());
187
+ }
173
188
  if (typeof raw.page_format === "string") draft.page_format = raw.page_format;
174
189
  if (raw.orientation === "landscape") draft.orientation = "landscape";
175
190
 
@@ -251,6 +266,17 @@ export function draftToSettings(draft, raw = {}, ctx = {}) {
251
266
  else out[preset] = choice;
252
267
  }
253
268
 
269
+ // Accent: written when the look has one and the choice differs from it. A
270
+ // look without an accent ignores the key, so whatever the file had stays.
271
+ const ownAccent = lookAccent(draft.look, looks);
272
+ const accent = typeof draft.accent === "string" && HEX.test(draft.accent) ? longHex(draft.accent) : "";
273
+ if (ownAccent) {
274
+ const written = typeof raw?.accent_color === "string" ? raw.accent_color.trim() : "";
275
+ const same = HEX.test(written) && longHex(written) === accent; // "#ABC" stays as typed
276
+ if (accent && accent !== ownAccent) out.accent_color = same ? raw.accent_color : accent;
277
+ else delete out.accent_color;
278
+ }
279
+
254
280
  if (draft.highlight === defaults.highlight) delete out.highlight_style;
255
281
  else out.highlight_style = draft.highlight;
256
282
 
package/studio/sample.md CHANGED
@@ -1,6 +1,8 @@
1
1
  ---
2
2
  title: Quarterly report
3
3
  author: Alex Morgan
4
+ pdf:
5
+ math: true
4
6
  ---
5
7
 
6
8
  # Quarterly report
@@ -36,6 +38,16 @@ function total(rows) {
36
38
  }
37
39
  ```
38
40
 
41
+ ## A little maths
42
+
43
+ Growth over the quarter, with $r$ the monthly rate:
44
+
45
+ $$
46
+ \text{growth} = \frac{47\,300 - 41\,200}{41\,200} \approx 14.8\,\%
47
+ \qquad
48
+ r = \sqrt[3]{1.148} - 1 \approx 4.7\,\%
49
+ $$
50
+
39
51
  <div style="page-break-after: always"></div>
40
52
 
41
53
  ## Next quarter
package/studio/style.css CHANGED
@@ -101,6 +101,37 @@ h2 {
101
101
 
102
102
  .label { color: var(--quiet); }
103
103
 
104
+ /* collapsed extra option inside .fields (theme colour) */
105
+ .more { grid-column: 1 / -1; margin-top: -2px; }
106
+ .more[hidden] { display: none; }
107
+ .more > summary {
108
+ display: inline-flex;
109
+ align-items: center;
110
+ gap: 8px;
111
+ color: var(--quiet);
112
+ cursor: pointer;
113
+ list-style: none;
114
+ }
115
+ .more > summary::-webkit-details-marker { display: none; }
116
+ .more > summary::before { content: "▸"; font-size: 0.8em; transition: transform 0.15s; }
117
+ .more[open] > summary::before { transform: rotate(90deg); }
118
+ .more > summary:hover { color: var(--text); }
119
+ .more .swatch {
120
+ width: 12px;
121
+ height: 12px;
122
+ border-radius: 3px;
123
+ box-shadow: 0 0 0 1px var(--rule);
124
+ }
125
+ .more-body {
126
+ display: flex;
127
+ align-items: center;
128
+ gap: 10px;
129
+ margin-top: 8px;
130
+ padding-left: 18px;
131
+ }
132
+ .more-body .hint { margin: 0; flex: 1; }
133
+ .more-body .btn[hidden] { display: none; }
134
+
104
135
  .row {
105
136
  display: flex;
106
137
  flex-wrap: wrap;
package/tool-schemas.mjs CHANGED
@@ -183,6 +183,12 @@ export const EXPORT_INPUT_SCHEMA = {
183
183
  description:
184
184
  "CSS font-family value for headings (h1-h6). Default: same as the body text.",
185
185
  },
186
+ accent_color: {
187
+ type: "string",
188
+ pattern: "^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$",
189
+ description:
190
+ "Accent colour of the page style, as #rgb or #rrggbb: title rules, coloured titles, code block bars. Used by the report and technical looks; the others have no accent.",
191
+ },
186
192
  },
187
193
  };
188
194
 
@@ -197,6 +203,40 @@ export const DOCTOR_INPUT_SCHEMA = {
197
203
  },
198
204
  };
199
205
 
206
+ export const INSTALL_BROWSER_INPUT_SCHEMA = {
207
+ type: "object",
208
+ additionalProperties: false,
209
+ properties: {
210
+ force: {
211
+ type: "boolean",
212
+ description:
213
+ "Download even when a working browser is already found. Default: false.",
214
+ },
215
+ },
216
+ };
217
+
218
+ export const OPEN_STUDIO_INPUT_SCHEMA = {
219
+ type: "object",
220
+ additionalProperties: false,
221
+ properties: {
222
+ file: {
223
+ type: "string",
224
+ description:
225
+ "Markdown file to preview instead of the built-in sample. Use an absolute path.",
226
+ },
227
+ project_folder: {
228
+ type: "string",
229
+ description:
230
+ "Edit the settings of this folder only (its .markdown-pdf.json) instead of the user settings used by every document. Use an absolute path.",
231
+ },
232
+ open_browser: {
233
+ type: "boolean",
234
+ description:
235
+ "Open Studio in the default browser. Default: true. The private link is returned either way.",
236
+ },
237
+ },
238
+ };
239
+
200
240
  export const TOOLS = [
201
241
  {
202
242
  name: "export_markdown_pdf",
@@ -212,4 +252,24 @@ export const TOOLS = [
212
252
  "Inspect browser setup and current settings.",
213
253
  inputSchema: DOCTOR_INPUT_SCHEMA,
214
254
  },
255
+ {
256
+ name: "install_browser_markdown_pdf",
257
+ title: "Install browser for Markdown PDF",
258
+ description:
259
+ "Download Playwright's Chromium (about 200 MB), the browser that draws the PDF. " +
260
+ "Only needed when doctor_markdown_pdf reports no browser (no Chrome or Edge on this computer). " +
261
+ "Ask the user before calling it. Returns status \"installing\" if the download is still running; " +
262
+ "call doctor_markdown_pdf a minute later to check.",
263
+ inputSchema: INSTALL_BROWSER_INPUT_SCHEMA,
264
+ },
265
+ {
266
+ name: "open_studio_markdown_pdf",
267
+ title: "Open Markdown PDF Studio",
268
+ description:
269
+ "Open Studio, a local page with a live PDF preview, to choose the page style, font, " +
270
+ "header, footer and logo. Saved choices apply to every later export. " +
271
+ "Use when the user wants to change how their PDFs look in general; for a one-off change, " +
272
+ "pass arguments to export_markdown_pdf instead.",
273
+ inputSchema: OPEN_STUDIO_INPUT_SCHEMA,
274
+ },
215
275
  ];