markdown-pdf-export 2.0.3 → 2.1.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/cli.mjs CHANGED
@@ -40,8 +40,17 @@ import {
40
40
  userSettingsPath,
41
41
  } from "./lib/settings-loader.mjs";
42
42
  import { formatDoctor } from "./lib/doctor-report.mjs";
43
+ import { makeStyle } from "./lib/term-style.mjs";
43
44
  import { LOOKS, FONTS, applyPresets } from "./lib/looks.mjs";
44
- import { EDITOR_IDS, applySetupItem, buildEditorSetup, launchSpec } from "./lib/editor-setup.mjs";
45
+ import {
46
+ EDITOR_IDS,
47
+ ITEM_LABELS,
48
+ applySetupItem,
49
+ buildEditorSetup,
50
+ editorStatus,
51
+ launchSpec,
52
+ pendingItems,
53
+ } from "./lib/editor-setup.mjs";
45
54
 
46
55
  const BIN = "markdown-pdf-export";
47
56
  const CLI_PATH = fileURLToPath(import.meta.url);
@@ -275,12 +284,15 @@ async function main(argv) {
275
284
  if (fromArg) setSettings(fromArg.data, fromArg.file);
276
285
 
277
286
  if (isDoctor) {
278
- const report = await doctorMarkdownPdf({ input_path: positional[0] });
287
+ const report = {
288
+ ...(await doctorMarkdownPdf({ input_path: positional[0] })),
289
+ editors: editorStatus(),
290
+ };
279
291
  if (asJson) {
280
292
  process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
281
293
  return report.browser.available ? 0 : 1;
282
294
  }
283
- const { text, ok } = formatDoctor(report, { bin: BIN });
295
+ const { text, ok } = formatDoctor(report, { bin: BIN, style: makeStyle() });
284
296
  process.stdout.write(text);
285
297
  return ok ? 0 : 1;
286
298
  }
@@ -322,7 +334,8 @@ async function runMenu() {
322
334
  if (pick === "1") return runSetup([]);
323
335
  if (pick === "2") return runStudio([]);
324
336
  if (pick === "3") {
325
- const { text, ok } = formatDoctor(await doctorMarkdownPdf({}), { bin: BIN });
337
+ const report = { ...(await doctorMarkdownPdf({})), editors: editorStatus() };
338
+ const { text, ok } = formatDoctor(report, { bin: BIN, style: makeStyle() });
326
339
  process.stdout.write(text);
327
340
  return ok ? 0 : 1;
328
341
  }
@@ -661,14 +674,90 @@ async function runInit(argv) {
661
674
 
662
675
  // ── setup ────────────────────────────────────────────────────────────────────
663
676
 
677
+ /**
678
+ * Ask editor by editor; skip what is already set up. Returns an exit code
679
+ * (130 when the person aborts with Ctrl+C / Ctrl+D).
680
+ */
681
+ async function setupInteractive(setups, c) {
682
+ const out = process.stdout;
683
+ const status = Object.fromEntries(editorStatus().map((e) => [e.id, e]));
684
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
685
+ let aborted = false;
686
+ rl.on("SIGINT", () => {
687
+ aborted = true;
688
+ rl.close();
689
+ });
690
+ const ask = async (question) => {
691
+ try {
692
+ const answer = (await rl.question(question)).trim().toLowerCase();
693
+ return answer === "" || answer === "y" || answer === "yes" || answer === "o" || answer === "oui";
694
+ } catch {
695
+ aborted = true; // input closed
696
+ return false;
697
+ }
698
+ };
699
+
700
+ out.write(`\n${c.bold(`Set up ${BIN} ${SERVER_VERSION}`)}\n`);
701
+ out.write(c.dim(`Found: ${setups.map((s) => s.name).join(", ")}`) + "\n\n");
702
+ try {
703
+ for (const setup of setups) {
704
+ const todo = pendingItems(setup, status[setup.id]);
705
+ if (todo.length === 0) {
706
+ out.write(`${c.green("✓")} ${c.bold(setup.name)}: already set up\n`);
707
+ continue;
708
+ }
709
+ const what = todo.map((i) => ITEM_LABELS[i.kind]).join(" + ");
710
+ const yes = await ask(`${c.cyan("?")} Set up ${c.bold(setup.name)} (${what})? ${c.dim("[Y/n]")} `);
711
+ if (aborted) {
712
+ out.write(`\n${c.yellow("Setup stopped.")}\n`);
713
+ return 130;
714
+ }
715
+ if (!yes) {
716
+ out.write(` ${c.dim("· skipped")}\n`);
717
+ continue;
718
+ }
719
+ for (const item of todo) {
720
+ const label = ITEM_LABELS[item.kind];
721
+ if (item.write === "print") {
722
+ out.write(
723
+ ` ${c.yellow("→")} ${label}: add this to ${item.file}` +
724
+ `${fs.existsSync(item.file) ? " (merge with what is there)" : ""}:\n` +
725
+ `${item.snippet.replace(/^/gm, " ")}\n`,
726
+ );
727
+ continue;
728
+ }
729
+ const { done, message } = applySetupItem(item, { stdio: "pipe" });
730
+ if (done) {
731
+ out.write(` ${c.green("✓")} ${label}: ${c.green(message)}\n`);
732
+ } else {
733
+ out.write(
734
+ ` ${c.red("✗")} ${label}: ${message}\n` +
735
+ `${item.snippet.replace(/^/gm, " ")}\n`,
736
+ );
737
+ }
738
+ }
739
+ }
740
+ } finally {
741
+ rl.close();
742
+ }
743
+ const others = EDITOR_IDS.filter((id) => !setups.some((s) => s.id === id));
744
+ if (others.length) {
745
+ out.write(c.dim(`\nOther editors: ${BIN} setup <${others.join("|")}>`) + "\n");
746
+ }
747
+ return 0;
748
+ }
749
+
664
750
  async function runSetup(argv) {
665
- const flags = parseSubArgs(argv, { write: "boolean" });
751
+ const flags = parseSubArgs(argv, { write: "boolean", print: "boolean" });
666
752
  if (flags.help) {
667
753
  process.stdout.write(
668
- `Usage: ${BIN} setup [${EDITOR_IDS.join("|")}|all] [--write]\n\n` +
669
- "Prints the task and MCP snippets for your editors (detected ones by default).\n" +
670
- "--write creates config files that do not exist yet and runs editor CLIs;\n" +
671
- "existing files are never modified.\n",
754
+ `Usage: ${BIN} setup [${EDITOR_IDS.join("|")}|all] [--write|--print]\n\n` +
755
+ "Sets up the export task and AI tools in your editors (the ones found by default).\n" +
756
+ "In a terminal it asks editor by editor and skips what is already set up.\n" +
757
+ "--write set up everything without asking (scripts)\n" +
758
+ "--print only show what to add\n" +
759
+ "Files that do not exist yet are created and editor CLIs are run;\n" +
760
+ "existing files are never modified: you get the snippet to paste.\n",
672
761
  );
673
762
  return 0;
674
763
  }
@@ -688,28 +777,47 @@ async function runSetup(argv) {
688
777
  }
689
778
 
690
779
  const out = process.stdout;
691
- for (const setup of setups) {
692
- out.write(`\n━━ ${setup.name}${setup.detected ? "" : " (not detected)"} ━━\n`);
780
+ const c = makeStyle();
781
+ const interactive =
782
+ !flags.write && !flags.print && process.stdin.isTTY && process.stdout.isTTY;
783
+ if (interactive) {
784
+ const code = await setupInteractive(setups, c);
785
+ if (code !== 0) return code;
786
+ }
787
+ const status = flags.write ? Object.fromEntries(editorStatus().map((e) => [e.id, e])) : {};
788
+ for (const setup of interactive ? [] : setups) {
789
+ const todo = flags.write ? new Set(pendingItems(setup, status[setup.id])) : null;
790
+ out.write(
791
+ `\n${c.bold(`━━ ${setup.name} ━━`)}${setup.detected ? "" : c.dim(" (not detected)")}\n`,
792
+ );
693
793
  for (const item of setup.items) {
694
- out.write(`\n▸ ${item.label}\n`);
695
- if (item.file) out.write(` file: ${item.file}\n`);
794
+ out.write(`\n${c.cyan(`▸ ${item.label}`)}\n`);
795
+ if (item.file) out.write(c.dim(` file: ${item.file}`) + "\n");
696
796
  out.write(`${item.snippet}\n`);
697
797
  if (!flags.write) continue;
798
+ if (!todo.has(item)) {
799
+ const set = status[setup.id]?.[item.kind] === true;
800
+ out.write(` ${set ? c.green("✓") : c.dim("·")} ${set ? "already set up" : "not needed here"}\n`);
801
+ continue;
802
+ }
698
803
 
699
804
  const { done, message } = applySetupItem(item);
700
- out.write(` ${done ? "✓" : item.write === "print" ? "→" : "✗"} ${message}\n`);
805
+ const mark = done ? c.green("✓") : item.write === "print" ? c.yellow("→") : c.red("✗");
806
+ out.write(` ${mark} ${done ? c.green(message) : message}\n`);
701
807
  }
702
808
  }
703
809
 
810
+ const settingsFile = userSettingsPath();
704
811
  out.write(
705
- `\nSettings file: ${userSettingsPath()}` +
706
- `${fs.existsSync(userSettingsPath()) ? "" : ` (missing — create it with: ${BIN} init)`}\n`,
812
+ fs.existsSync(settingsFile)
813
+ ? `\n${c.green("✓")} Settings file: ${settingsFile}\n`
814
+ : `\n${c.yellow("·")} No settings file yet (built-in look is used). Design your pages: ${c.cyan(`${BIN} studio`)}\n`,
707
815
  );
708
816
  const report = await doctorMarkdownPdf({});
709
817
  out.write(
710
818
  report.browser.available
711
- ? `Browser: ${report.browser.version} ✓\n`
712
- : `Browser: not found — ${report.browser.hint}\n`,
819
+ ? `${c.green("✓")} Browser: ${report.browser.version}\n`
820
+ : `${c.red("✗")} Browser: not found — ${report.browser.hint}\n`,
713
821
  );
714
822
  return report.browser.available ? 0 : 1;
715
823
  }
package/export.mjs CHANGED
@@ -874,6 +874,7 @@ export async function doctorMarkdownPdf(args) {
874
874
  );
875
875
 
876
876
  return {
877
+ version: SERVER_VERSION,
877
878
  browser: browserInfo,
878
879
  settings_sources: doc.sources,
879
880
  settings: {
@@ -3,25 +3,35 @@
3
3
  * where every problem comes with the one command that fixes it.
4
4
  */
5
5
 
6
+ import { plain } from "./term-style.mjs";
7
+
6
8
  /**
7
9
  * @param {object} report result of doctorMarkdownPdf()
8
- * @param {{bin?: string, nodeVersion?: string}} [opts]
10
+ * @param {{bin?: string, nodeVersion?: string, style?: typeof plain}} [opts]
9
11
  * @returns {{text: string, ok: boolean}}
10
12
  */
11
- export function formatDoctor(report, { bin = "markdown-pdf-export", nodeVersion = process.versions.node } = {}) {
13
+ export function formatDoctor(
14
+ report,
15
+ { bin = "markdown-pdf-export", nodeVersion = process.versions.node, style = plain } = {},
16
+ ) {
17
+ const c = style;
12
18
  const lines = [];
13
19
  let ok = true;
14
- const good = (msg) => lines.push(` ✓ ${msg}`);
20
+ const good = (msg) => lines.push(` ${c.green("✓")} ${msg}`);
15
21
  const bad = (msg, fix) => {
16
22
  ok = false;
17
- lines.push(` ✗ ${msg}`);
18
- if (fix) lines.push(` fix: ${fix}`);
23
+ lines.push(` ${c.red("✗")} ${msg}`);
24
+ if (fix) lines.push(` fix: ${c.cyan(fix)}`);
19
25
  };
20
26
  const info = (msg, hint) => {
21
- lines.push(` · ${msg}`);
22
- if (hint) lines.push(` ${hint}`);
27
+ lines.push(` ${c.dim("·")} ${msg}`);
28
+ if (hint) lines.push(` ${c.cyan(hint)}`);
23
29
  };
24
30
 
31
+ if (report.version) {
32
+ good(`${c.bold(`${bin} ${report.version}`)}` + (report.server_dir ? c.dim(` (${report.server_dir})`) : ""));
33
+ }
34
+
25
35
  const major = Number.parseInt(nodeVersion, 10);
26
36
  if (major >= 20) good(`Node ${nodeVersion}`);
27
37
  else bad(`Node ${nodeVersion} is too old (needs 20 or newer)`, "install Node 20+ from nodejs.org");
@@ -47,6 +57,43 @@ export function formatDoctor(report, { bin = "markdown-pdf-export", nodeVersion
47
57
  (st.font_family ? " · custom font" : ""),
48
58
  );
49
59
 
50
- const head = ok ? "Everything is ready." : "Something needs attention:";
51
- return { text: `${head}\n\n${lines.join("\n")}\n`, ok };
60
+ const head = ok
61
+ ? c.green(c.bold("✨ Everything is ready."))
62
+ : c.red(c.bold("Something needs attention:"));
63
+ const editors = report.editors ? `\n${formatEditors(report.editors, bin, c)}` : "";
64
+ return { text: `${head}\n\n${lines.join("\n")}\n${editors}`, ok };
65
+ }
66
+
67
+ const PARTS = { task: "export task", mcp: "AI tools" };
68
+
69
+ /**
70
+ * Editors section: what is set up where. Never fails the check — a missing
71
+ * editor is a choice, not an error.
72
+ * @param {ReturnType<typeof import("./editor-setup.mjs").editorStatus>} editors
73
+ * @param {string} bin
74
+ */
75
+ export function formatEditors(editors, bin = "markdown-pdf-export", style = plain) {
76
+ const c = style;
77
+ const lines = [c.bold("Editors:")];
78
+ for (const e of editors.filter((x) => x.detected)) {
79
+ const parts = Object.keys(PARTS).filter((k) => e[k] !== undefined);
80
+ const done = parts.filter((k) => e[k] === true);
81
+ const missing = parts.filter((k) => e[k] !== true);
82
+ const label = (ks) => ks.map((k) => PARTS[k]).join(", ");
83
+ if (missing.length === 0) {
84
+ lines.push(` ${c.green("✓")} ${c.bold(e.name)}: ${label(done)}`);
85
+ } else {
86
+ const note = e.mcp === "project" ? " (only in some project folders)" : "";
87
+ lines.push(
88
+ ` ${c.yellow("·")} ${c.bold(e.name)}: ${done.length ? `${label(done)} ${c.green("✓")}, ` : ""}` +
89
+ c.yellow(`${label(missing)} not set up${note}`),
90
+ ` add: ${c.cyan(`${bin} setup ${e.id} --write`)}`,
91
+ );
92
+ }
93
+ for (const w of e.warnings ?? []) lines.push(` ${c.yellow("!")} ${c.yellow(w)}`);
94
+ }
95
+ const absent = editors.filter((x) => !x.detected).map((x) => x.name);
96
+ // Not installed is a choice, not a problem: neutral grey, never red.
97
+ if (absent.length) lines.push(c.dim(` · Not found: ${absent.join(", ")}`));
98
+ return `${lines.join("\n")}\n`;
52
99
  }
@@ -16,6 +16,8 @@ export const SERVER_NAME = "markdown-pdf-export";
16
16
  export const MCP_KEY = "markdown-pdf";
17
17
  export const TASK_LABEL = "Markdown: Export to PDF";
18
18
  export const EDITOR_IDS = ["zed", "vscode", "cursor", "claude-code", "claude-desktop", "copilot-cli"];
19
+ /** Short names people type for an editor id. */
20
+ export const EDITOR_ALIASES = { claude: "claude-code", code: "vscode", copilot: "copilot-cli" };
19
21
 
20
22
  /**
21
23
  * Version managers install node under a version-specific directory; editors
@@ -98,7 +100,8 @@ function roots({ home, platform, env }) {
98
100
  * @property {string|null} file target file (null for CLI-only)
99
101
  * @property {string} snippet text to show / write
100
102
  * @property {"create"|"print"|"command"} write safe-write strategy
101
- * @property {{cmd: string, args: string[]}} [run] CLI to run for "command"
103
+ * @property {{cmd: string, args: string[], fallbacks?: string[]}} [run]
104
+ * CLI to run for "command"; `fallbacks` are full paths tried when `cmd` is not on PATH
102
105
  */
103
106
 
104
107
  /**
@@ -108,6 +111,7 @@ function roots({ home, platform, env }) {
108
111
  * @returns {{id: string, name: string, detected: boolean, items: SetupItem[]}}
109
112
  */
110
113
  export function buildEditorSetup(editor, launch, ctx = {}) {
114
+ editor = EDITOR_ALIASES[editor] ?? editor;
111
115
  const home = ctx.home ?? os.homedir();
112
116
  const platform = ctx.platform ?? process.platform;
113
117
  const env = ctx.env ?? process.env;
@@ -128,7 +132,8 @@ export function buildEditorSetup(editor, launch, ctx = {}) {
128
132
  kind: "task",
129
133
  label: "Zed task (add to tasks.json)",
130
134
  file: path.join(dir, "tasks.json"),
131
- write: "print",
135
+ // Zed files are JSONC: create a missing one, never edit an existing one.
136
+ write: exists(path.join(dir, "tasks.json")) ? "print" : "create",
132
137
  snippet: json([
133
138
  {
134
139
  label: TASK_LABEL,
@@ -155,14 +160,15 @@ export function buildEditorSetup(editor, launch, ctx = {}) {
155
160
  const isCursor = editor === "cursor";
156
161
  const userDir = path.join(r.userData, isCursor ? "Cursor" : "Code", "User");
157
162
  const mcpFile = path.join(home, ".cursor", "mcp.json");
163
+ const taskFile = path.join(userDir, "tasks.json");
158
164
  const addMcp = JSON.stringify({ name: MCP_KEY, ...server });
159
165
  /** @type {SetupItem[]} */
160
166
  const items = [
161
167
  {
162
168
  kind: "task",
163
169
  label: `${isCursor ? "Cursor" : "VS Code"} task (add to tasks.json)`,
164
- file: path.join(userDir, "tasks.json"),
165
- write: "print",
170
+ file: taskFile,
171
+ write: exists(taskFile) ? "print" : "create",
166
172
  snippet: json({
167
173
  version: "2.0.0",
168
174
  tasks: [
@@ -190,7 +196,18 @@ export function buildEditorSetup(editor, launch, ctx = {}) {
190
196
  label: "VS Code MCP server",
191
197
  file: null,
192
198
  write: "command",
193
- run: { cmd: "code", args: ["--add-mcp", addMcp] },
199
+ run: {
200
+ cmd: "code",
201
+ args: ["--add-mcp", addMcp],
202
+ // macOS: `code` is only on PATH after "Install 'code' command in PATH".
203
+ fallbacks:
204
+ platform === "darwin"
205
+ ? [
206
+ "/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code",
207
+ path.join(home, "Applications", "Visual Studio Code.app", "Contents", "Resources", "app", "bin", "code"),
208
+ ]
209
+ : [],
210
+ },
194
211
  snippet: shellJoin(["code", "--add-mcp", addMcp], platform),
195
212
  },
196
213
  ];
@@ -215,10 +232,10 @@ export function buildEditorSetup(editor, launch, ctx = {}) {
215
232
  write: "command",
216
233
  run: {
217
234
  cmd: "claude",
218
- args: ["mcp", "add", MCP_KEY, "--", server.command, ...server.args],
235
+ args: ["mcp", "add", "--scope", "user", MCP_KEY, "--", server.command, ...server.args],
219
236
  },
220
237
  snippet: shellJoin(
221
- ["claude", "mcp", "add", MCP_KEY, "--", server.command, ...server.args],
238
+ ["claude", "mcp", "add", "--scope", "user", MCP_KEY, "--", server.command, ...server.args],
222
239
  platform,
223
240
  ),
224
241
  },
@@ -289,13 +306,122 @@ export function applySetupItem(item, { stdio = "inherit" } = {}) {
289
306
  if (item.write === "command") {
290
307
  // Windows: code/claude are .cmd shims, which need the shell; pass one
291
308
  // pre-quoted command line so JSON arguments survive cmd.exe.
292
- const result =
309
+ let result =
293
310
  process.platform === "win32"
294
311
  ? spawnSync(item.snippet, { stdio, shell: true })
295
312
  : spawnSync(item.run.cmd, item.run.args, { stdio });
313
+ for (const cmd of item.run.fallbacks ?? []) {
314
+ if (result.error?.code !== "ENOENT") break;
315
+ if (fs.existsSync(cmd)) result = spawnSync(cmd, item.run.args, { stdio });
316
+ }
296
317
  return result.status === 0
297
318
  ? { done: true, message: `ran: ${item.snippet}` }
298
319
  : { done: false, message: `could not run "${item.run.cmd}" — run the command yourself` };
299
320
  }
300
321
  return { done: false, message: "existing file: paste the snippet yourself" };
301
322
  }
323
+
324
+ // ── Status (doctor) ──────────────────────────────────────────────────────────
325
+
326
+ const readText = (file) => {
327
+ try {
328
+ return fs.readFileSync(file, "utf8");
329
+ } catch {
330
+ return null;
331
+ }
332
+ };
333
+
334
+ /** Task file: names our package. Settings/MCP file: has a "markdown-pdf" entry. */
335
+ const hasTask = (text) => text !== null && text.includes(SERVER_NAME);
336
+ const hasMcpKey = (text) => text !== null && text.includes(`"${MCP_KEY}"`);
337
+
338
+ /**
339
+ * Claude Code keeps user-scope servers at the top of ~/.claude.json and
340
+ * local-scope ones per project. "project" = only set up for some folders.
341
+ * @returns {boolean|"project"}
342
+ */
343
+ function claudeCodeMcp(file) {
344
+ const text = readText(file);
345
+ if (text === null) return false;
346
+ try {
347
+ const data = JSON.parse(text);
348
+ if (data?.mcpServers?.[MCP_KEY]) return true;
349
+ const inProject = Object.values(data?.projects ?? {}).some((p) => p?.mcpServers?.[MCP_KEY]);
350
+ return inProject ? "project" : false;
351
+ } catch {
352
+ return hasMcpKey(text);
353
+ }
354
+ }
355
+
356
+ /**
357
+ * What is set up in each editor: read-only, for `doctor`.
358
+ * `task` / `mcp` are undefined when the editor has no such thing.
359
+ * `warnings` flags configs known to cause trouble (an old settings override).
360
+ * @param {{home?: string, platform?: string, env?: NodeJS.ProcessEnv}} [ctx]
361
+ * @returns {{id: string, name: string, detected: boolean, task?: boolean, mcp?: boolean|"project", warnings: string[]}[]}
362
+ */
363
+ export function editorStatus(ctx = {}) {
364
+ const home = ctx.home ?? os.homedir();
365
+ const platform = ctx.platform ?? process.platform;
366
+ const env = ctx.env ?? process.env;
367
+ const r = roots({ home, platform, env });
368
+
369
+ return EDITOR_IDS.map((id) => {
370
+ const { name, detected } = buildEditorSetup(id, { command: "npx", args: [] }, { home, platform, env });
371
+ const out = { id, name, detected, warnings: [] };
372
+ let taskFile = null;
373
+ switch (id) {
374
+ case "zed":
375
+ taskFile = path.join(r.zed, "tasks.json");
376
+ out.mcp = hasMcpKey(readText(path.join(r.zed, "settings.json")));
377
+ break;
378
+ case "vscode":
379
+ case "cursor": {
380
+ const userDir = path.join(r.userData, id === "cursor" ? "Cursor" : "Code", "User");
381
+ // ~/.cursor alone = Cursor Agent CLI without the app: no task to offer.
382
+ if (id === "vscode" || fs.existsSync(userDir)) taskFile = path.join(userDir, "tasks.json");
383
+ out.mcp = hasMcpKey(
384
+ readText(id === "cursor" ? path.join(home, ".cursor", "mcp.json") : path.join(userDir, "mcp.json")),
385
+ );
386
+ break;
387
+ }
388
+ case "claude-code":
389
+ out.mcp = claudeCodeMcp(path.join(home, ".claude.json"));
390
+ break;
391
+ case "claude-desktop":
392
+ out.mcp = hasMcpKey(readText(path.join(r.appData, "Claude", "claude_desktop_config.json")));
393
+ break;
394
+ case "copilot-cli":
395
+ out.mcp = hasMcpKey(readText(path.join(home, ".copilot", "mcp-config.json")));
396
+ break;
397
+ }
398
+ if (taskFile) {
399
+ const text = readText(taskFile);
400
+ out.task = hasTask(text);
401
+ if (out.task && text.includes("MARKDOWN_PDF_SETTINGS")) {
402
+ out.warnings.push(
403
+ `${taskFile} sets MARKDOWN_PDF_SETTINGS, which replaces your settings file`,
404
+ );
405
+ }
406
+ }
407
+ if (out.task || out.mcp) out.detected = true; // set up, even if its folder moved
408
+ return out;
409
+ });
410
+ }
411
+
412
+ /** What a setup item adds, in words. */
413
+ export const ITEM_LABELS = { task: "export task", mcp: "AI tools" };
414
+
415
+ /**
416
+ * Items of one editor that are not set up yet, given its editorStatus() entry.
417
+ * Claude Code set up only for some folders ("project") still counts as to do;
418
+ * a kind the status does not list is skipped (it does not apply here).
419
+ * @param {{items: SetupItem[]}} setup
420
+ * @param {{task?: boolean, mcp?: boolean|"project"}|undefined} status
421
+ * @returns {SetupItem[]}
422
+ */
423
+ export function pendingItems(setup, status) {
424
+ if (!status) return [...setup.items];
425
+ // A kind missing from the status does not apply here (Cursor CLI without the app).
426
+ return setup.items.filter((item) => item.kind in status && status[item.kind] !== true);
427
+ }
@@ -36,7 +36,14 @@ import {
36
36
  readSettingsFile,
37
37
  userSettingsPath,
38
38
  } from "./settings-loader.mjs";
39
- import { EDITOR_IDS, applySetupItem, buildEditorSetup, launchSpec } from "./editor-setup.mjs";
39
+ import {
40
+ EDITOR_IDS,
41
+ applySetupItem,
42
+ buildEditorSetup,
43
+ editorStatus,
44
+ launchSpec,
45
+ pendingItems,
46
+ } from "./editor-setup.mjs";
40
47
  import { IMAGE_FORMATS } from "./types.mjs";
41
48
 
42
49
  const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
@@ -393,15 +400,27 @@ export async function startStudio(opts = {}) {
393
400
 
394
401
  if (req.method === "GET" && route === "/api/state") return send(res, 200, state());
395
402
  if (req.method === "GET" && route === "/api/editors") {
403
+ const status = Object.fromEntries(editorStatus().map((e) => [e.id, e]));
396
404
  return send(
397
405
  res,
398
406
  200,
399
- editors().map((e) => ({
400
- id: e.id,
401
- name: e.name,
402
- detected: e.detected,
403
- items: e.items.map((i) => ({ label: i.label, file: i.file ?? null, snippet: i.snippet, write: i.write })),
404
- })),
407
+ editors().map((e) => {
408
+ const todo = new Set(pendingItems(e, status[e.id]));
409
+ return {
410
+ id: e.id,
411
+ name: e.name,
412
+ detected: e.detected || Boolean(status[e.id]?.detected),
413
+ items: e.items.map((i) => ({
414
+ kind: i.kind,
415
+ label: i.label,
416
+ file: i.file ?? null,
417
+ snippet: i.snippet,
418
+ write: i.write,
419
+ // not set up yet, and applies on this computer
420
+ pending: todo.has(i),
421
+ })),
422
+ };
423
+ }),
405
424
  );
406
425
  }
407
426
  if (req.method === "GET" && route === "/api/check") {
@@ -0,0 +1,27 @@
1
+ /**
2
+ * @fileoverview Tiny terminal colours, no dependency. On only for a TTY;
3
+ * NO_COLOR turns it off, FORCE_COLOR (≠ "0") turns it on. See no-color.org.
4
+ */
5
+
6
+ /**
7
+ * @param {{stream?: {isTTY?: boolean}, env?: NodeJS.ProcessEnv}} [opts]
8
+ */
9
+ export function makeStyle({ stream = process.stdout, env = process.env } = {}) {
10
+ const enabled = env.FORCE_COLOR
11
+ ? env.FORCE_COLOR !== "0"
12
+ : !env.NO_COLOR && Boolean(stream.isTTY) && env.TERM !== "dumb";
13
+ const wrap = (open, close) => (text) =>
14
+ enabled ? `\x1b[${open}m${text}\x1b[${close}m` : String(text);
15
+ return {
16
+ enabled,
17
+ bold: wrap(1, 22),
18
+ dim: wrap(2, 22),
19
+ red: wrap(31, 39),
20
+ green: wrap(32, 39),
21
+ yellow: wrap(33, 39),
22
+ cyan: wrap(36, 39),
23
+ };
24
+ }
25
+
26
+ /** No colours: for tests, JSON, logs. */
27
+ export const plain = makeStyle({ stream: {}, env: { NO_COLOR: "1" } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "markdown-pdf-export",
3
- "version": "2.0.3",
3
+ "version": "2.1.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",
@@ -83,7 +83,11 @@
83
83
  "documentation",
84
84
  "report"
85
85
  ],
86
- "author": "Mat <mat@matinfo.ch>",
86
+ "author": {
87
+ "name": "Matinfo",
88
+ "email": "dev@matinfo.tech",
89
+ "url": "https://matinfo.tech"
90
+ },
87
91
  "license": "MIT",
88
92
  "repository": {
89
93
  "type": "git",
@@ -91,7 +95,8 @@
91
95
  },
92
96
  "homepage": "https://markdown-pdf.matinfo.tech/",
93
97
  "bugs": {
94
- "url": "https://github.com/matinfo-tech/markdown-pdf-export/issues"
98
+ "url": "https://github.com/matinfo-tech/markdown-pdf-export/issues",
99
+ "email": "dev@matinfo.tech"
95
100
  },
96
101
  "packageManager": "npm@11.12.1",
97
102
  "devDependencies": {
package/studio/app.mjs CHANGED
@@ -492,7 +492,7 @@ async function openEditors() {
492
492
  const dialog = $("editors");
493
493
  const list = $("editors-list");
494
494
  list.replaceChildren(el("p", { class: "hint", text: "Looking for your editors…" }));
495
- dialog.showModal();
495
+ if (!dialog.open) dialog.showModal();
496
496
  let editors;
497
497
  try {
498
498
  editors = await api("/api/editors");
@@ -509,16 +509,7 @@ async function openEditors() {
509
509
  EDITOR_NOTES[editor.id] ? el("p", { class: "editor-note", text: EDITOR_NOTES[editor.id] }) : null,
510
510
  ...editor.items.map((item, index) => {
511
511
  const result = el("div", { class: "result", role: "status" });
512
- const copy = el("button", {
513
- type: "button",
514
- class: "btn small",
515
- text: "Copy",
516
- onclick: async () => {
517
- await navigator.clipboard.writeText(item.snippet);
518
- copy.textContent = "Copied";
519
- setTimeout(() => (copy.textContent = "Copy"), 1500);
520
- },
521
- });
512
+ const copy = copyButton(item.snippet);
522
513
  const auto =
523
514
  item.write === "print"
524
515
  ? null
@@ -596,10 +587,127 @@ async function openEditors() {
596
587
  tabs.append(button);
597
588
  });
598
589
 
599
- list.replaceChildren(tabs, panel);
590
+ const found = sorted.filter((e) => e.detected);
591
+ const manual = el(
592
+ "details",
593
+ { class: "manual", open: found.length === 0 },
594
+ el("summary", { text: found.length ? "All editors and manual steps" : "Pick your editor" }),
595
+ tabs,
596
+ panel,
597
+ );
598
+ list.replaceChildren(quickSetup(found), manual);
600
599
  select(current);
601
600
  }
602
601
 
602
+ function copyButton(text) {
603
+ const button = el("button", {
604
+ type: "button",
605
+ class: "btn small",
606
+ text: "Copy",
607
+ onclick: async () => {
608
+ await navigator.clipboard.writeText(text);
609
+ button.textContent = "Copied";
610
+ setTimeout(() => (button.textContent = "Copy"), 1500);
611
+ },
612
+ });
613
+ return button;
614
+ }
615
+
616
+ const KIND_LABEL = { task: "export task", mcp: "AI tools" };
617
+
618
+ /**
619
+ * Editors found on this computer, one switch each (on by default). Already
620
+ * set-up parts are skipped; files that exist are never edited — the person
621
+ * gets the snippet to paste instead.
622
+ */
623
+ function quickSetup(found) {
624
+ const box = el("section", { class: "quick", "aria-label": "Editors found on this computer" });
625
+ if (found.length === 0) {
626
+ box.append(el("p", { class: "hint", text: "No editor found on this computer. Pick yours below." }));
627
+ return box;
628
+ }
629
+ box.append(el("h3", { text: "Found on this computer" }));
630
+
631
+ const rows = found.map((editor) => {
632
+ const todo = editor.items.map((item, index) => ({ item, index })).filter((x) => x.item.pending);
633
+ const result = el("div", { class: "quick-result", role: "status" });
634
+ if (todo.length === 0) {
635
+ const row = el(
636
+ "div",
637
+ { class: "quick-row done" },
638
+ el("span", { class: "tick", "aria-hidden": "true", text: "✓" }),
639
+ el("span", { class: "quick-name", text: editor.name }),
640
+ el("span", { class: "quick-what", text: "Already set up" }),
641
+ );
642
+ return { row, toggle: null };
643
+ }
644
+ const id = `quick-${editor.id}`;
645
+ const toggle = el("input", { type: "checkbox", role: "switch", class: "switch", id, checked: true });
646
+ const what = [...new Set(todo.map((x) => KIND_LABEL[x.item.kind]))].join(" + ");
647
+ const row = el(
648
+ "div",
649
+ { class: "quick-row" },
650
+ toggle,
651
+ el("label", { for: id, class: "quick-name", text: editor.name }),
652
+ el("span", { class: "quick-what", text: what }),
653
+ result,
654
+ );
655
+ return { row, toggle, editor, todo, result };
656
+ });
657
+
658
+ const pending = rows.filter((r) => r.toggle);
659
+ box.append(...rows.map((r) => r.row));
660
+ if (pending.length === 0) {
661
+ box.append(el("p", { class: "hint", text: "Everything found here is set up." }));
662
+ return box;
663
+ }
664
+
665
+ const go = el("button", { type: "button", class: "btn primary" });
666
+ const selected = () => pending.filter((r) => r.toggle.checked && !r.toggle.disabled);
667
+ const refresh = () => {
668
+ const n = selected().length;
669
+ go.textContent = n ? `Set up ${n} editor${n > 1 ? "s" : ""}` : "Nothing selected";
670
+ go.disabled = n === 0;
671
+ };
672
+ for (const r of pending) r.toggle.addEventListener("change", refresh);
673
+
674
+ const line = (ok, text, title) => el("p", { class: ok ? "ok" : "bad", text: `${ok ? "✓" : "✗"} ${text}`, title });
675
+ const paste = (item, why) =>
676
+ el(
677
+ "div",
678
+ { class: "paste" },
679
+ el("div", { class: "step-head" }, el("span", { text: why }), copyButton(item.snippet)),
680
+ el("pre", { text: item.snippet }),
681
+ );
682
+
683
+ go.addEventListener("click", async () => {
684
+ go.disabled = true;
685
+ for (const r of selected()) {
686
+ r.toggle.disabled = true;
687
+ r.result.replaceChildren();
688
+ for (const { item, index } of r.todo) {
689
+ const label = KIND_LABEL[item.kind];
690
+ if (item.write === "print") {
691
+ r.result.append(paste(item, `${label}: paste this into ${item.file}`));
692
+ continue;
693
+ }
694
+ try {
695
+ const { done, message } = await api("/api/editors/apply", { method: "POST", json: { id: r.editor.id, index } });
696
+ r.result.append(line(done, done ? `${label} added` : `${label}: ${message}`, message));
697
+ if (!done) r.result.append(paste(item, "Run or add this yourself:"));
698
+ } catch (error) {
699
+ r.result.append(line(false, `${label}: ${error.message}`), paste(item, "Run or add this yourself:"));
700
+ }
701
+ }
702
+ }
703
+ refresh();
704
+ if (selected().length === 0) go.textContent = "Done";
705
+ });
706
+ refresh();
707
+ box.append(el("div", { class: "quick-foot" }, go));
708
+ return box;
709
+ }
710
+
603
711
  // ── start ───────────────────────────────────────────────────────────────────
604
712
  async function start() {
605
713
  try {
package/studio/style.css CHANGED
@@ -481,7 +481,8 @@ dialog .hint { margin: 0 0 6px; }
481
481
  .step { margin-bottom: 12px; }
482
482
  .step-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 10px; }
483
483
  .step-file { font: 11.5px var(--mono); color: var(--quiet); overflow-wrap: anywhere; margin: 2px 0 5px; }
484
- .step pre {
484
+ .step pre,
485
+ .quick-result pre {
485
486
  margin: 0;
486
487
  max-height: 150px;
487
488
  overflow: auto;
@@ -492,6 +493,48 @@ dialog .hint { margin: 0 0 6px; }
492
493
  font: 12px/1.45 var(--mono);
493
494
  }
494
495
  .step .result { margin-top: 5px; color: var(--ok); }
496
+
497
+ /* quick setup: editors found here, one switch each */
498
+ .quick { margin: 14px 0 4px; }
499
+ .quick h3 { margin: 0 0 8px; font: 600 12px var(--ui); letter-spacing: 0.06em; text-transform: uppercase; color: var(--quiet); }
500
+ .quick-row {
501
+ display: grid; grid-template-columns: 40px auto 1fr; align-items: center; gap: 4px 12px;
502
+ padding: 10px 12px; margin-bottom: 8px;
503
+ background: var(--surface); border: 1px solid var(--rule); border-radius: 8px;
504
+ }
505
+ .quick-name { font-weight: 600; cursor: pointer; }
506
+ .quick-row.done .quick-name { cursor: default; }
507
+ .quick-what { color: var(--quiet); font-size: 13px; text-align: right; }
508
+ .quick-row.done .quick-what { color: var(--ok); }
509
+ .quick-row .tick { color: var(--ok); font-weight: 700; text-align: center; }
510
+ .quick-result { grid-column: 2 / -1; }
511
+ .quick-result:empty { display: none; }
512
+ .quick-result p { margin: 4px 0 0; font-size: 13px; }
513
+ .quick-result .ok { color: var(--ok); }
514
+ .quick-result .bad { color: var(--error); }
515
+ .quick-result .paste { margin-top: 8px; }
516
+ .quick-result .step-head { margin-bottom: 6px; font-size: 13px; color: var(--quiet); overflow-wrap: anywhere; }
517
+ .quick-foot { display: flex; justify-content: flex-end; margin-top: 4px; }
518
+
519
+ .switch {
520
+ appearance: none; position: relative; margin: 0;
521
+ width: 34px; height: 20px; border-radius: 999px; cursor: pointer;
522
+ background: var(--rule); transition: background 0.15s;
523
+ }
524
+ .switch::before {
525
+ content: ""; position: absolute; top: 3px; left: 3px;
526
+ width: 14px; height: 14px; border-radius: 50%;
527
+ background: var(--text); transition: transform 0.15s;
528
+ }
529
+ .switch:checked { background: var(--ok); }
530
+ .switch:checked::before { transform: translateX(14px); background: var(--accent-ink); }
531
+ .switch:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
532
+ .switch:disabled { opacity: 0.5; cursor: default; }
533
+
534
+ details.manual { margin-top: 18px; border-top: 1px solid var(--rule); padding-top: 12px; }
535
+ details.manual > summary { cursor: pointer; font-weight: 600; color: var(--quiet); }
536
+ details.manual > summary:hover { color: var(--text); }
537
+ details.manual[open] > summary { margin-bottom: 4px; }
495
538
  .step .result.bad { color: var(--error); }
496
539
 
497
540
  /* ── small screens: form first, preview below ───────────────────────────── */
@@ -506,4 +549,5 @@ dialog .hint { margin: 0 0 6px; }
506
549
 
507
550
  @media (prefers-reduced-motion: reduce) {
508
551
  .status.busy::before { animation: none; }
552
+ .switch, .switch::before { transition: none; }
509
553
  }