@galacticquasar/mdview 0.0.0-stage → 0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 GalacticQuasar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,152 @@
1
- # Temporary Holding Version
1
+ # mdview
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **A Markdown viewer you launch from the terminal.** `mdview README.md` opens the file, rendered the
4
+ way GitHub renders it, in its own minimal window. You navigate with vim keys, and the window reloads
5
+ whenever you save. It uses the Chrome or Edge you already have, so there's no Electron and nothing
6
+ heavy to install.
7
+
8
+ <!-- TODO: demo GIF -->
9
+
10
+ ```sh
11
+ npm install -g @galacticquasar/mdview
12
+ mdview README.md
13
+ ```
14
+
15
+ ## Why
16
+
17
+ Most Markdown previewers either open a tab in your normal browser (grip, markserv), only work from
18
+ inside an editor (markdown-preview.nvim, VS Code), or render in the terminal (glow), with no real
19
+ typography, images or math. mdview gives you a dedicated window that feels like a native viewer:
20
+
21
+ - **Vim navigation** that's pleasant to use: smooth scrolling, holding `j` glides at a constant
22
+ speed, `gg`/`G`, `]]`/`[[` to jump between headings, `/` to search, jump history with `Ctrl-O`/`Ctrl-I`,
23
+ and `q` to close.
24
+ - **Rendered like GitHub:** GitHub-flavored Markdown, syntax highlighting, alerts (`> [!NOTE]`),
25
+ math, and light and dark themes that follow your system.
26
+ - **Live reload** on save, keeping your scroll position. It works with editors that save by
27
+ renaming the file, like Neovim.
28
+ - **Works well on WSL.** The server runs in Linux and the window is a native Windows Edge or Chrome
29
+ window. It also works around the WSL localhost relay delay, so the window doesn't flash a
30
+ connection error.
31
+ - **Takes pipes:** `git show HEAD~3:README.md | mdview -`.
32
+ - **Claude Code plugin:** `/mdview` opens Claude's last response in a window ([details below](#claude-code-plugin)).
33
+
34
+ ## Features
35
+
36
+ - GitHub-flavored Markdown: tables, task lists, alerts (`> [!NOTE]`), heading anchors, inline HTML
37
+ - Syntax highlighting for code blocks
38
+ - Math (KaTeX) with GitHub's syntax: `$inline$`, `` $`inline`$ ``, `$$` blocks and ` ```math ` blocks
39
+ - YAML frontmatter (as in `SKILL.md` files) shown as a highlighted block at the top
40
+ - Follows links to other `.md` files and shows relative images; web links open in your default browser
41
+ - Other text files (`.txt`, logs, `LICENSE`, ...) are shown as-is, with the same keys and live reload
42
+ - A thin progress bar on the right edge shows how far down the file you are
43
+ - The mouse cursor hides while you scroll with the keyboard
44
+
45
+ ## Requirements
46
+
47
+ - Node.js 20 or later
48
+ - A Chromium-based browser:
49
+ - **WSL:** Edge or Chrome installed on Windows
50
+ - **macOS:** Chrome, Edge, Chromium or Brave in `/Applications` or `~/Applications`
51
+ - **Linux:** Chrome, Chromium or Edge in `/usr/bin`
52
+
53
+ Set `MDVIEW_BROWSER` to the path of any other Chromium-based browser.
54
+
55
+ mdview runs the browser with its own profile, so it never touches your normal browser session.
56
+
57
+ ## Usage
58
+
59
+ ```sh
60
+ mdview <file | -> [--size WxH] [--pos X,Y] [--no-open]
61
+ ```
62
+
63
+ ```sh
64
+ mdview README.md # open a file
65
+ mdview notes.txt # non-Markdown text files are shown verbatim
66
+ git show HEAD~3:README.md | mdview - # read Markdown from stdin
67
+ mdview README.md --size 900x1000 --pos 400,0
68
+ ```
69
+
70
+ | Option | Meaning |
71
+ |---|---|
72
+ | `-` | Read Markdown from stdin. Relative links and images resolve from the current directory. There's no live reload. |
73
+ | `--size WxH` | Window size |
74
+ | `--pos X,Y` | Window position |
75
+ | `--no-open` | Just start the server and print the URL |
76
+ | `--version`, `--help` | |
77
+
78
+ Files ending in `.md`, `.markdown`, `.mdown` or `.mkd` are rendered as Markdown. Any other text
79
+ file is shown verbatim, and binary files are refused. mdview exits when you close the window.
80
+
81
+ ### Default window size
82
+
83
+ Sizes and positions are in scaled pixels, not physical screen pixels. With display scaling, divide
84
+ your screen's pixel numbers by the scale factor: a 1400×1460 window at 150% scaling is
85
+ `--size 933x973`. To make every window open the same way, wrap mdview in a function in your shell's
86
+ startup file (`~/.bashrc`, `~/.zshrc`):
87
+
88
+ ```sh
89
+ mdview() { command mdview --size 933x973 --pos 387,0 "$@"; }
90
+ ```
91
+
92
+ ## Keys
93
+
94
+ | Key | Action |
95
+ |---|---|
96
+ | `j` / `k`, `Ctrl-E` / `Ctrl-Y` | scroll line down / up (hold to glide) |
97
+ | `Ctrl-D` / `Ctrl-U` (or `d` / `u`) | half page down / up |
98
+ | `Ctrl-F` / `Ctrl-B`, `Space` | full page down / up |
99
+ | `gg` / `G` | top / bottom |
100
+ | `]]` / `[[` | next / previous heading |
101
+ | `/`, `n` / `N` | search, next / previous match |
102
+ | `H` / `L`, `Ctrl-O` / `Ctrl-I` | back / forward between linked files |
103
+ | `r` | re-render |
104
+ | `q` | quit |
105
+
106
+ ## Claude Code plugin
107
+
108
+ The repo includes a [Claude Code](https://claude.com/claude-code) plugin that adds a `/mdview`
109
+ command. It opens Claude's last response in mdview, which is handy for reading long answers,
110
+ tables and math. It runs without calling the model, so it costs no tokens.
111
+
112
+ Install mdview first (see above), then in Claude Code:
113
+
114
+ ```
115
+ /plugin marketplace add GalacticQuasar/mdview
116
+ /plugin install mdview@mdview
117
+ ```
118
+
119
+ On Claude Code 2.1.275 or later, one step works too:
120
+ `/plugin install mdview --marketplace GalacticQuasar/mdview`.
121
+
122
+ To pass a window size or position, set the plugin's `args` option in `/config`, or in
123
+ `~/.claude/settings.json`:
124
+
125
+ ```json
126
+ { "pluginConfigs": { "mdview": { "options": { "args": "--size 933x1013 --pos 387,0" } } } }
127
+ ```
128
+
129
+ ## How it works
130
+
131
+ `mdview` renders the file to HTML in a small local Node server and opens it in a Chromium `--app`
132
+ window, which has no tabs or address bar. The server only serves files inside the file's git
133
+ repository (or its folder, outside a repo), and it pushes reloads to the page over server-sent
134
+ events.
135
+
136
+ ## Development
137
+
138
+ ```sh
139
+ git clone https://github.com/GalacticQuasar/mdview
140
+ cd mdview
141
+ npm install
142
+ npm link # puts this checkout on your PATH as `mdview`
143
+ npm test
144
+ ```
145
+
146
+ Rendering lives in `render.mjs`, the server and launcher in `mdview.mjs`, and the in-page code in
147
+ `page.js` and `page.css`. To work on the Claude Code plugin, load it from the checkout with
148
+ `claude --plugin-dir ./claude-plugin`.
149
+
150
+ ## License
151
+
152
+ MIT
package/icon.svg ADDED
@@ -0,0 +1,11 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
2
+ <!-- Lucide "view" icon, ISC License, Copyright (c) Lucide Contributors (https://lucide.dev) -->
3
+ <style>
4
+ svg { stroke: #ffffff; }
5
+ @media (prefers-color-scheme: light) { svg { stroke: #1f2328; } }
6
+ </style>
7
+ <path d="M21 17v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2"/>
8
+ <path d="M21 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2"/>
9
+ <circle cx="12" cy="12" r="1"/>
10
+ <path d="M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0"/>
11
+ </svg>
package/mdview.mjs ADDED
@@ -0,0 +1,322 @@
1
+ #!/usr/bin/env node
2
+ // mdview: render a Markdown or text file and show it in a chromeless browser window
3
+ // with vim-style navigation and live reload.
4
+
5
+ import http from 'node:http';
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import os from 'node:os';
9
+ import { spawn, execFileSync } from 'node:child_process';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { createRequire } from 'node:module';
12
+ import { render, isMarkdown, escapeHtml } from './render.mjs';
13
+
14
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
15
+ // Vendored files are found through Node's resolution, not HERE/node_modules, since a
16
+ // package manager may hoist dependencies out of mdview's own folder.
17
+ const vendored = createRequire(import.meta.url).resolve;
18
+ const readVendored = (f) => fs.readFileSync(vendored(f), 'utf8');
19
+
20
+ // ---------- args ----------
21
+
22
+ // Same heuristic as git: a NUL byte near the start means binary.
23
+ const isBinary = (p) => {
24
+ const buf = Buffer.alloc(8192);
25
+ const fd = fs.openSync(p, 'r');
26
+ const n = fs.readSync(fd, buf);
27
+ fs.closeSync(fd);
28
+ return buf.subarray(0, n).includes(0);
29
+ };
30
+
31
+ const USAGE = `usage: mdview <file | -> [--size WxH] [--pos X,Y] [--no-open] [--version]`;
32
+ const opts = { size: null, pos: null, open: true, file: null };
33
+ const argv = process.argv.slice(2);
34
+ for (let i = 0; i < argv.length; i++) {
35
+ const a = argv[i];
36
+ if (a === '--size') opts.size = argv[++i];
37
+ else if (a === '--pos') opts.pos = argv[++i];
38
+ else if (a === '--no-open') opts.open = false;
39
+ else if (a === '-h' || a === '--help') { console.log(USAGE); process.exit(0); }
40
+ else if (a === '-v' || a === '--version') {
41
+ console.log(JSON.parse(fs.readFileSync(path.join(HERE, 'package.json'), 'utf8')).version);
42
+ process.exit(0);
43
+ }
44
+ else if (!opts.file) opts.file = a;
45
+ else { console.error(USAGE); process.exit(1); }
46
+ }
47
+ if (!opts.file) { console.error(USAGE); process.exit(1); }
48
+
49
+ // "-" reads Markdown from stdin. It's served as a virtual stdin.md in the current
50
+ // directory, so relative links and images resolve from there; there's no live reload.
51
+ const stdin = opts.file === '-' ? readStdin() : null;
52
+ const file = stdin === null ? path.resolve(opts.file) : path.resolve('stdin.md');
53
+ const isStdin = (p) => stdin !== null && p === file;
54
+
55
+ function readStdin() {
56
+ if (process.stdin.isTTY) { console.error('mdview: nothing piped to stdin'); process.exit(1); }
57
+ return fs.readFileSync(0, 'utf8');
58
+ }
59
+
60
+ if (stdin === null) {
61
+ if (!fs.existsSync(file)) { console.error(`mdview: no such file: ${opts.file}`); process.exit(1); }
62
+ if (!fs.statSync(file).isFile()) { console.error(`mdview: not a file: ${opts.file}`); process.exit(1); }
63
+ if (!isMarkdown(file) && isBinary(file)) { console.error(`mdview: not a text file: ${opts.file}`); process.exit(1); }
64
+ }
65
+
66
+ // Serve from the git root (so ../images work inside a repo), else the file's directory.
67
+ let root = path.dirname(file);
68
+ try {
69
+ root = execFileSync('git', ['-C', root, 'rev-parse', '--show-toplevel'], { stdio: ['ignore', 'pipe', 'ignore'] })
70
+ .toString().trim() || root;
71
+ } catch {}
72
+
73
+ // ---------- markdown ----------
74
+
75
+ const renderFile = (p) => render(isStdin(p) ? stdin : fs.readFileSync(p, 'utf8'), isMarkdown(p));
76
+
77
+ // ---------- page ----------
78
+
79
+ const KATEX = path.dirname(vendored('katex/dist/katex.min.css'));
80
+ const css = [
81
+ 'github-markdown-css/github-markdown.css',
82
+ 'markdown-it-github-alerts/styles/github-base.css',
83
+ 'markdown-it-github-alerts/styles/github-colors-light.css',
84
+ 'markdown-it-github-alerts/styles/github-colors-dark-media.css',
85
+ ].map(readVendored).join('\n')
86
+ + `\n@media (prefers-color-scheme: light) {${readVendored('highlight.js/styles/github.css')}}`
87
+ + `\n@media (prefers-color-scheme: dark) {${readVendored('highlight.js/styles/github-dark.css')}}`
88
+ // The stylesheet is inlined, so point its relative font URLs at the /__katex/ route.
89
+ + '\n' + fs.readFileSync(path.join(KATEX, 'katex.min.css'), 'utf8').replaceAll('url(fonts/', 'url(/__katex/fonts/')
90
+ + '\n' + fs.readFileSync(path.join(HERE, 'page.css'), 'utf8');
91
+ const js = fs.readFileSync(path.join(HERE, 'page.js'), 'utf8');
92
+ const icon = 'data:image/svg+xml,' + encodeURIComponent(fs.readFileSync(path.join(HERE, 'icon.svg'), 'utf8'));
93
+
94
+ const page = (p) => `<!doctype html>
95
+ <html><head><meta charset="utf-8">
96
+ <title>${escapeHtml(path.basename(p))}</title>
97
+ <link rel="icon" type="image/svg+xml" href="${icon}">
98
+ <style>${css}</style>
99
+ </head><body class="markdown-body">
100
+ <article id="content">${renderFile(p)}</article>
101
+ <div id="mdview-bar" hidden><span>/</span><input id="mdview-search" spellcheck="false"></div>
102
+ <div id="mdview-status" hidden></div>
103
+ <div id="mdview-progress"></div>
104
+ <script>${js}</script>
105
+ </body></html>`;
106
+
107
+ // ---------- server ----------
108
+
109
+ const MIME = {
110
+ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif',
111
+ '.svg': 'image/svg+xml', '.webp': 'image/webp', '.ico': 'image/x-icon', '.pdf': 'application/pdf',
112
+ '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'text/javascript',
113
+ '.json': 'application/json', '.txt': 'text/plain; charset=utf-8',
114
+ '.woff2': 'font/woff2', '.woff': 'font/woff', '.ttf': 'font/ttf',
115
+ };
116
+ // The absolute path for a request path, or null when it falls outside the serve root.
117
+ const inRoot = (p) => {
118
+ const abs = path.join(root, p);
119
+ return abs === root || abs.startsWith(root + path.sep) ? abs : null;
120
+ };
121
+ const urlFor = (p) => '/' + path.relative(root, p).split(path.sep).map(encodeURIComponent).join('/');
122
+
123
+ // Exit once the window is closed: no live event streams for a short grace period.
124
+ let clients = 0;
125
+ let exitTimer = setTimeout(() => process.exit(0), 30_000); // window never connected
126
+ const clientGone = () => {
127
+ if (--clients === 0) exitTimer = setTimeout(() => process.exit(0), 1500);
128
+ };
129
+
130
+ const server = http.createServer((req, res) => {
131
+ const url = new URL(req.url, 'http://x');
132
+
133
+ if (url.pathname === '/') {
134
+ res.writeHead(302, { Location: urlFor(file) });
135
+ return res.end();
136
+ }
137
+ if (url.pathname === '/__quit') {
138
+ res.end();
139
+ return setTimeout(() => process.exit(0), 50);
140
+ }
141
+ if (url.pathname.startsWith('/__katex/fonts/')) {
142
+ const font = path.join(KATEX, 'fonts', path.basename(url.pathname));
143
+ return fs.readFile(font, (err, data) => {
144
+ res.writeHead(err ? 404 : 200, { 'Content-Type': MIME[path.extname(font)] ?? 'application/octet-stream' });
145
+ res.end(err ? undefined : data);
146
+ });
147
+ }
148
+ if (url.pathname === '/__open' && req.method === 'POST') {
149
+ if (req.headers.origin !== `http://${req.headers.host}`) { // only our own pages
150
+ res.writeHead(403);
151
+ return res.end();
152
+ }
153
+ let body = '';
154
+ req.on('data', (c) => { body += c; });
155
+ req.on('end', () => {
156
+ res.writeHead(openExternal(body) ? 204 : 400);
157
+ res.end();
158
+ });
159
+ return;
160
+ }
161
+
162
+ let target;
163
+ try { target = inRoot(decodeURIComponent(url.pathname)); } catch { // malformed %-escape
164
+ res.writeHead(400);
165
+ return res.end();
166
+ }
167
+ // searchParams.get has already decoded `path`, so it isn't decoded again.
168
+ const watched = url.pathname === '/__events' ? inRoot(url.searchParams.get('path') ?? '') : undefined;
169
+ if (!target || watched === null) {
170
+ res.writeHead(403);
171
+ return res.end();
172
+ }
173
+
174
+ if (watched) {
175
+ res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' });
176
+ res.write(': hi\n\n');
177
+ clients++;
178
+ clearTimeout(exitTimer);
179
+ if (isStdin(watched)) return req.on('close', clientGone);
180
+ // Watch the directory, not the file: editors like Neovim save by rename.
181
+ // A missing or deleted directory just means no reloads; the stream stays open for the lifecycle.
182
+ let debounce, watcher;
183
+ try {
184
+ watcher = fs.watch(path.dirname(watched), (_, name) => {
185
+ if (name !== path.basename(watched)) return;
186
+ clearTimeout(debounce);
187
+ debounce = setTimeout(() => res.write('data: reload\n\n'), 50);
188
+ }).on('error', () => {});
189
+ } catch {}
190
+ req.on('close', () => { watcher?.close(); clientGone(); });
191
+ return;
192
+ }
193
+
194
+ fs.stat(target, (err, st) => {
195
+ if (!isStdin(target) && (err || !st.isFile())) {
196
+ res.writeHead(404, { 'Content-Type': 'text/plain' });
197
+ return res.end('not found');
198
+ }
199
+ try {
200
+ if (isMarkdown(target) || target === file) {
201
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' });
202
+ return res.end(url.searchParams.has('fragment') ? renderFile(target) : page(target));
203
+ }
204
+ } catch (e) {
205
+ res.writeHead(500, { 'Content-Type': 'text/plain' });
206
+ return res.end(String(e));
207
+ }
208
+ res.writeHead(200, { 'Content-Type': MIME[path.extname(target).toLowerCase()] ?? 'application/octet-stream' });
209
+ fs.createReadStream(target).pipe(res);
210
+ });
211
+ });
212
+
213
+ // ---------- window ----------
214
+
215
+ const isWSL = fs.existsSync('/proc/version') && /microsoft/i.test(fs.readFileSync('/proc/version', 'utf8'));
216
+
217
+ function findBrowser() {
218
+ if (process.env.MDVIEW_BROWSER) return process.env.MDVIEW_BROWSER;
219
+ const macApps = ['Google Chrome.app/Contents/MacOS/Google Chrome',
220
+ 'Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
221
+ 'Chromium.app/Contents/MacOS/Chromium',
222
+ 'Brave Browser.app/Contents/MacOS/Brave Browser'];
223
+ const candidates = isWSL
224
+ ? ['/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',
225
+ '/mnt/c/Program Files/Microsoft/Edge/Application/msedge.exe',
226
+ '/mnt/c/Program Files/Google/Chrome/Application/chrome.exe']
227
+ : process.platform === 'darwin'
228
+ ? ['/Applications', path.join(os.homedir(), 'Applications')].flatMap((dir) => macApps.map((app) => path.join(dir, app)))
229
+ : ['/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser', '/usr/bin/microsoft-edge'];
230
+ return candidates.find((c) => fs.existsSync(c));
231
+ }
232
+
233
+ // e.g. "chrome", "msedge", "google-chrome", "microsoft-edge"
234
+ const browserName = (browser) =>
235
+ path.basename(browser).replace(/\.exe$/i, '').toLowerCase().replace(/[^a-z0-9]+/g, '-');
236
+
237
+ // Separate profile so mdview windows don't attach to your normal browser session
238
+ // (which would ignore --window-size/--window-position). One per browser, since
239
+ // browsers can't safely share a user-data-dir.
240
+ function profileDir(browser) {
241
+ const name = browserName(browser);
242
+ if (process.platform === 'darwin') return path.join(os.homedir(), 'Library', 'Caches', 'mdview', name);
243
+ if (!isWSL) return path.join(process.env.XDG_CACHE_HOME ?? path.join(os.homedir(), '.cache'), 'mdview', name);
244
+ // Asking cmd.exe is slow, so the answer is cached. Not in mdview's own folder, which
245
+ // is read-only after a global npm install.
246
+ const cache = path.join(process.env.XDG_CACHE_HOME ?? path.join(os.homedir(), '.cache'), 'mdview', 'localappdata');
247
+ let local;
248
+ try { local = fs.readFileSync(cache, 'utf8').trim(); } catch {}
249
+ if (!local) {
250
+ local = execFileSync('cmd.exe', ['/c', 'echo %LOCALAPPDATA%'], { cwd: '/mnt/c', stdio: ['ignore', 'pipe', 'ignore'] })
251
+ .toString().trim();
252
+ try {
253
+ fs.mkdirSync(path.dirname(cache), { recursive: true });
254
+ fs.writeFileSync(cache, local);
255
+ } catch {}
256
+ }
257
+ return `${local}\\mdview\\${name}`;
258
+ }
259
+
260
+ // Open a link in the user's default browser (links never navigate the viewer window away).
261
+ function openExternal(link) {
262
+ let url;
263
+ try { url = new URL(link); } catch { return false; }
264
+ if (!['http:', 'https:', 'mailto:'].includes(url.protocol)) return false;
265
+ const [cmd, args] = isWSL ? ['rundll32.exe', ['url.dll,FileProtocolHandler', url.href]]
266
+ : process.platform === 'darwin' ? ['open', [url.href]]
267
+ : ['xdg-open', [url.href]];
268
+ spawn(cmd, args, { detached: true, stdio: 'ignore', cwd: isWSL ? '/mnt/c' : undefined })
269
+ .on('error', () => {}).unref();
270
+ return true;
271
+ }
272
+
273
+ // Turn off Edge's "mini menu" (the popup toolbar over selected text). Pages can't suppress it,
274
+ // so set the profile pref directly.
275
+ function disableMiniMenu(profile) {
276
+ const dir = path.join(isWSL ? execFileSync('wslpath', ['-u', profile]).toString().trim() : profile, 'Default');
277
+ const file = path.join(dir, 'Preferences');
278
+ let prefs = {};
279
+ try { prefs = JSON.parse(fs.readFileSync(file, 'utf8')); } catch {}
280
+ if (prefs.edge_quick_search?.show_mini_menu === false) return;
281
+ prefs.edge_quick_search = { ...prefs.edge_quick_search, show_mini_menu: false };
282
+ fs.mkdirSync(dir, { recursive: true });
283
+ fs.writeFileSync(file, JSON.stringify(prefs));
284
+ }
285
+
286
+ function openWindow(url) {
287
+ const browser = findBrowser();
288
+ if (!browser) {
289
+ console.error(`mdview: no Chromium-based browser found; set MDVIEW_BROWSER. Open ${url} manually.`);
290
+ return;
291
+ }
292
+ const profile = profileDir(browser);
293
+ if (/edge/.test(browserName(browser))) {
294
+ try { disableMiniMenu(profile); } catch {}
295
+ }
296
+ const args = [`--app=${url}`, `--user-data-dir=${profile}`, '--no-first-run', '--no-default-browser-check'];
297
+ if (opts.size) args.push(`--window-size=${opts.size.replace('x', ',')}`);
298
+ if (opts.pos) args.push(`--window-position=${opts.pos}`);
299
+ spawn(browser, args, { detached: true, stdio: 'ignore', cwd: isWSL ? '/mnt/c' : undefined }).unref();
300
+ }
301
+
302
+ // In WSL's NAT mode, Windows reaches WSL's localhost through a relay that takes up to
303
+ // ~1.5s to pick up a new port, so the window often loads before it's reachable.
304
+ // The VM's own address is reachable from Windows immediately (and only from the host).
305
+ // Not used in mirrored mode, where that address is the machine's LAN IP.
306
+ function listenHost() {
307
+ if (!isWSL) return '127.0.0.1';
308
+ try {
309
+ if (execFileSync('wslinfo', ['--networking-mode'], { stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim() !== 'nat') {
310
+ return '127.0.0.1';
311
+ }
312
+ } catch { return '127.0.0.1'; }
313
+ const vnic = os.networkInterfaces().eth0?.find((a) => a.family === 'IPv4');
314
+ return vnic?.address ?? '127.0.0.1';
315
+ }
316
+
317
+ const host = listenHost();
318
+ server.listen(0, host, () => {
319
+ const url = `http://${host === '127.0.0.1' ? 'localhost' : host}:${server.address().port}${urlFor(file)}`;
320
+ if (opts.open) openWindow(url);
321
+ else console.log(url);
322
+ });
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "@galacticquasar/mdview",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Markdown viewer with vim keybindings and live reload, in a chromeless Chrome/Edge window",
5
+ "keywords": [
6
+ "markdown",
7
+ "viewer",
8
+ "preview",
9
+ "vim",
10
+ "live-reload",
11
+ "cli",
12
+ "wsl",
13
+ "katex",
14
+ "github-flavored-markdown"
15
+ ],
16
+ "homepage": "https://github.com/GalacticQuasar/mdview#readme",
17
+ "bugs": {
18
+ "url": "https://github.com/GalacticQuasar/mdview/issues"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/GalacticQuasar/mdview.git"
23
+ },
24
+ "author": "GalacticQuasar",
25
+ "license": "MIT",
26
+ "type": "module",
27
+ "bin": {
28
+ "mdview": "mdview.mjs"
29
+ },
30
+ "files": [
31
+ "mdview.mjs",
32
+ "render.mjs",
33
+ "page.js",
34
+ "page.css",
35
+ "icon.svg"
36
+ ],
37
+ "engines": {
38
+ "node": ">=20"
39
+ },
40
+ "scripts": {
41
+ "test": "node --test"
42
+ },
43
+ "dependencies": {
44
+ "github-markdown-css": "^5.9.0",
45
+ "highlight.js": "^11.12.0",
46
+ "katex": "^0.19.0",
47
+ "markdown-it": "^15.0.3",
48
+ "markdown-it-github-alerts": "^1.0.1"
49
+ }
50
+ }
package/page.css ADDED
@@ -0,0 +1,58 @@
1
+ :root { color-scheme: light dark; scrollbar-width: none; }
2
+ ::-webkit-scrollbar { display: none; }
3
+ .hide-cursor, .hide-cursor * { cursor: none !important; }
4
+ /* body carries .markdown-body so its theme colors cover the whole window */
5
+ body { margin: 0; min-height: 100vh; }
6
+ /* github-markdown-css already pads/colors <pre>; drop highlight.js's duplicate */
7
+ .markdown-body pre code.hljs { padding: 0; background: transparent; }
8
+ /* non-Markdown files: the text is the whole page, so no code-block card, and wrap long lines */
9
+ .markdown-body pre.plain-text {
10
+ padding: 0;
11
+ background: transparent;
12
+ white-space: pre-wrap;
13
+ overflow-wrap: anywhere;
14
+ }
15
+ #content {
16
+ box-sizing: border-box;
17
+ padding: 32px 40px 50vh;
18
+ }
19
+
20
+ #mdview-bar, #mdview-status {
21
+ position: fixed;
22
+ left: 0;
23
+ right: 0;
24
+ bottom: 0;
25
+ display: flex;
26
+ gap: 6px;
27
+ padding: 4px 10px;
28
+ font: 14px/1.4 ui-monospace, SFMono-Regular, Consolas, monospace;
29
+ background: var(--bgColor-muted, #f6f8fa);
30
+ border-top: 1px solid var(--borderColor-default, #d0d7de);
31
+ color: var(--fgColor-default, inherit);
32
+ }
33
+ /* scroll progress, scaled from the top by page.js */
34
+ #mdview-progress {
35
+ position: fixed;
36
+ top: 0;
37
+ right: 0;
38
+ width: 3px;
39
+ height: 100vh;
40
+ background: var(--borderColor-default, #d1d9e0);
41
+ transform: scaleY(0);
42
+ transform-origin: top;
43
+ pointer-events: none;
44
+ }
45
+ #mdview-progress[hidden] { display: none; }
46
+ #mdview-bar[hidden], #mdview-status[hidden] { display: none; }
47
+ #mdview-search {
48
+ flex: 1;
49
+ border: 0;
50
+ outline: 0;
51
+ background: transparent;
52
+ color: inherit;
53
+ font: inherit;
54
+ }
55
+ /* like GitHub: an img's height attribute is a cap, so max-width shrinking it keeps its aspect ratio */
56
+ .markdown-body img[height] { height: auto; max-height: attr(height px); }
57
+ /* wide display math scrolls sideways instead of overflowing the page */
58
+ .katex-display { overflow-x: auto; overflow-y: hidden; padding: 2px 0; }
package/page.js ADDED
@@ -0,0 +1,308 @@
1
+ // Vim-style navigation + live reload, injected into every rendered page.
2
+ (() => {
3
+ const content = document.getElementById('content');
4
+ const bar = document.getElementById('mdview-bar');
5
+ const input = document.getElementById('mdview-search');
6
+ const status = document.getElementById('mdview-status');
7
+
8
+ const LINE = 60;
9
+ const half = () => window.innerHeight / 2;
10
+ const full = () => window.innerHeight - LINE;
11
+
12
+ // Smooth scrolling: ease toward a target each frame. Quick repeated presses (e.g. d d)
13
+ // push the target further instead of restarting the animation.
14
+ let target = null;
15
+ let last = 0; // where we last put the page, to notice wheel/scrollbar taking over
16
+ let lastTime = 0;
17
+ let velocity = 0; // px/ms of the eased animation, so a hold can pick up where it left off
18
+ // Fraction of the remaining distance covered per 60Hz frame.
19
+ const EASE = 0.25;
20
+ const EASE_HALF_PAGE = 0.16; // gentler for Ctrl-D/Ctrl-U, which travel much further
21
+ let ease = EASE;
22
+ const maxY = () => document.documentElement.scrollHeight - window.innerHeight;
23
+ const step = (now) => {
24
+ if (target === null) return;
25
+ if (Math.abs(window.scrollY - last) > 2) { target = null; velocity = 0; return; }
26
+ const d = target - window.scrollY;
27
+ if (Math.abs(d) <= 1) { window.scrollTo(0, target); target = null; velocity = 0; return; }
28
+ // Frame-rate independent ease-out, at least 1px so pixel snapping can't stall it
29
+ // just short of the target.
30
+ const dt = Math.min(now - lastTime, 100);
31
+ const k = 1 - Math.pow(1 - ease, dt / 16.7);
32
+ lastTime = now;
33
+ const from = window.scrollY;
34
+ window.scrollTo(0, from + Math.sign(d) * Math.max(1, Math.abs(d) * k));
35
+ last = window.scrollY;
36
+ if (dt > 0) velocity = (last - from) / dt;
37
+ requestAnimationFrame(step);
38
+ };
39
+ const scrollTo = (y, rate = EASE) => {
40
+ glide = null;
41
+ ease = rate;
42
+ const animating = target !== null;
43
+ target = Math.round(Math.max(0, Math.min(maxY(), y)));
44
+ if (!animating) {
45
+ last = window.scrollY;
46
+ lastTime = performance.now();
47
+ requestAnimationFrame(step);
48
+ }
49
+ };
50
+ const scroll = (dy, rate) => scrollTo((target ?? window.scrollY) + dy, rate);
51
+ const halfPage = (dir) => scroll(dir * half(), EASE_HALF_PAGE);
52
+
53
+ // Holding a line key: from the first auto-repeat on, scroll at a constant speed every frame.
54
+ // Easing toward a target that each repeat bumps 60px makes the speed pulse at the repeat rate.
55
+ const HOLD_SPEED = 1.8; // px/ms: LINE per repeat at Windows' default ~30/s repeat rate
56
+ const HOLD_EASE = 70; // ms time constant for speeding up and slowing down
57
+ let glide = null; // { key, dir, held, v, y, last, time }
58
+ const holdLine = (key, dir) => {
59
+ hideCursor();
60
+ if (glide) { Object.assign(glide, { key, dir, held: true }); return; }
61
+ const g = glide = {
62
+ key, dir, held: true, v: velocity,
63
+ y: window.scrollY, last: window.scrollY, time: performance.now(),
64
+ };
65
+ target = null; // take over from the eased tap
66
+ const frame = (now) => {
67
+ if (glide !== g) return;
68
+ if (Math.abs(window.scrollY - g.last) > 2) { glide = null; return; } // wheel/scrollbar took over
69
+ const dt = Math.min(now - g.time, 100);
70
+ g.time = now;
71
+ g.v += ((g.held ? g.dir * HOLD_SPEED : 0) - g.v) * (1 - Math.exp(-dt / HOLD_EASE));
72
+ g.y = Math.max(0, Math.min(maxY(), g.y + g.v * dt)); // keep the fraction; scrollY snaps to pixels
73
+ window.scrollTo(0, g.y);
74
+ g.last = window.scrollY;
75
+ if (!g.held && (Math.abs(g.v) < 0.05 || g.y === 0 || g.y === maxY())) { glide = null; return; }
76
+ requestAnimationFrame(frame);
77
+ };
78
+ requestAnimationFrame(frame);
79
+ };
80
+ const line = (e, dir) => (e.repeat ? holdLine(e.key.toLowerCase(), dir) : scroll(dir * LINE));
81
+ const release = () => { if (glide) glide.held = false; };
82
+ document.addEventListener('keyup', (e) => {
83
+ if (glide && (e.key.toLowerCase() === glide.key || e.key === 'Control')) release();
84
+ });
85
+ window.addEventListener('blur', release);
86
+
87
+ // Hide the mouse cursor while scrolling with the keyboard; moving the mouse brings it back.
88
+ // Compare positions because Chromium can fire mousemove when content scrolls under a still cursor.
89
+ let mouseX = -1;
90
+ let mouseY = -1;
91
+ function hideCursor() { document.documentElement.classList.add('hide-cursor'); }
92
+ document.addEventListener('mousemove', (e) => {
93
+ if (e.screenX === mouseX && e.screenY === mouseY) return;
94
+ mouseX = e.screenX;
95
+ mouseY = e.screenY;
96
+ document.documentElement.classList.remove('hide-cursor');
97
+ });
98
+
99
+ // Progress bar on the right edge: how far down the page we are.
100
+ const progress = document.getElementById('mdview-progress');
101
+ const updateProgress = () => {
102
+ const max = maxY();
103
+ progress.hidden = max <= 0;
104
+ progress.style.transform = `scaleY(${max > 0 ? Math.min(1, window.scrollY / max) : 0})`;
105
+ };
106
+ window.addEventListener('scroll', updateProgress, { passive: true });
107
+ window.addEventListener('resize', updateProgress);
108
+ new ResizeObserver(updateProgress).observe(content); // live reload, images loading
109
+ updateProgress();
110
+
111
+ let statusTimer;
112
+ const flash = (msg) => {
113
+ status.textContent = msg;
114
+ status.hidden = false;
115
+ clearTimeout(statusTimer);
116
+ statusTimer = setTimeout(() => { status.hidden = true; }, 1200);
117
+ };
118
+
119
+ const headings = () => [...content.querySelectorAll('h1, h2, h3, h4, h5, h6')];
120
+ const jumpHeading = (dir) => {
121
+ const y = window.scrollY + 1;
122
+ const hs = headings().map((h) => h.getBoundingClientRect().top + window.scrollY - 16);
123
+ const next = dir > 0 ? hs.find((t) => t > y + 4) : hs.reverse().find((t) => t < y - 4);
124
+ if (next !== undefined) scrollTo(next);
125
+ };
126
+
127
+ // Search via window.find (non-standard but supported by Chromium).
128
+ let query = '';
129
+ const find = (backwards) => {
130
+ if (!query) return;
131
+ if (!window.find(query, false, backwards, true)) return flash(`not found: ${query}`);
132
+ const rect = window.getSelection().getRangeAt(0).getBoundingClientRect();
133
+ if (rect.top < 0 || rect.bottom > window.innerHeight) {
134
+ scrollTo(window.scrollY + rect.top - window.innerHeight / 3);
135
+ }
136
+ };
137
+
138
+ // Multi-key sequences: gg, ]], [[
139
+ let pending = '';
140
+ let pendingTimer;
141
+ const sequences = {
142
+ gg: () => scrollTo(0),
143
+ ']]': () => jumpHeading(1),
144
+ '[[': () => jumpHeading(-1),
145
+ };
146
+
147
+ const ctrlKeys = {
148
+ d: () => halfPage(1),
149
+ u: () => halfPage(-1),
150
+ f: () => scroll(full()),
151
+ b: () => scroll(-full()),
152
+ e: (e) => line(e, 1),
153
+ y: (e) => line(e, -1),
154
+ o: () => goBack(),
155
+ i: () => goForward(),
156
+ };
157
+
158
+ const keys = {
159
+ j: (e) => line(e, 1),
160
+ k: (e) => line(e, -1),
161
+ d: () => halfPage(1),
162
+ u: () => halfPage(-1),
163
+ ' ': () => scroll(full()),
164
+ G: () => scrollTo(maxY()),
165
+ H: () => goBack(),
166
+ L: () => goForward(),
167
+ '/': () => { bar.hidden = false; input.value = query; input.select(); input.focus(); },
168
+ n: () => find(false),
169
+ N: () => find(true),
170
+ r: () => reload(),
171
+ q: () => quit(),
172
+ };
173
+
174
+ document.addEventListener('keydown', (e) => {
175
+ if (e.target === input || e.altKey || e.metaKey) return;
176
+ if (e.ctrlKey) {
177
+ const fn = ctrlKeys[e.key.toLowerCase()];
178
+ if (fn) { e.preventDefault(); hideCursor(); fn(e); }
179
+ return;
180
+ }
181
+ if (e.key === 'Escape') { pending = ''; window.getSelection().removeAllRanges(); return; }
182
+
183
+ pending += e.key;
184
+ clearTimeout(pendingTimer);
185
+ if (sequences[pending]) { e.preventDefault(); hideCursor(); sequences[pending](); pending = ''; return; }
186
+ if (Object.keys(sequences).some((s) => s.startsWith(pending))) {
187
+ e.preventDefault();
188
+ pendingTimer = setTimeout(() => { pending = ''; }, 800);
189
+ return;
190
+ }
191
+ pending = '';
192
+ const fn = keys[e.key];
193
+ if (fn) { e.preventDefault(); hideCursor(); fn(e); }
194
+ });
195
+
196
+ input.addEventListener('keydown', (e) => {
197
+ if (e.key === 'Enter') {
198
+ query = input.value;
199
+ bar.hidden = true;
200
+ input.blur();
201
+ window.getSelection().removeAllRanges();
202
+ find(false);
203
+ } else if (e.key === 'Escape') {
204
+ bar.hidden = true;
205
+ input.blur();
206
+ }
207
+ e.stopPropagation();
208
+ });
209
+
210
+ // No browser context menu: it's a viewer, not a browser.
211
+ document.addEventListener('contextmenu', (e) => e.preventDefault());
212
+
213
+ // ---------- links and back/forward ----------
214
+ // The window must keep a single history entry: browsers only let a page close its own
215
+ // window (q) when there's nothing to go back to. So links never add entries: #anchors
216
+ // scroll in place, other .md files replace the page (with our own back/forward stacks in
217
+ // sessionStorage), and everything else opens in the default browser.
218
+
219
+ const load = (key, fallback) => {
220
+ try { return JSON.parse(sessionStorage.getItem(key)) ?? fallback; } catch { return fallback; }
221
+ };
222
+ const save = (key, value) => {
223
+ try { sessionStorage.setItem(key, JSON.stringify(value)); } catch {}
224
+ };
225
+ let leaving = false;
226
+ const leave = (url, y) => {
227
+ if (y !== undefined) {
228
+ save('mdview.restoreY', y);
229
+ url = url.split('#')[0]; // else the browser jumps to the anchor after we restore
230
+ }
231
+ leaving = true;
232
+ location.replace(url);
233
+ };
234
+ const here = () => ({ url: location.href, y: window.scrollY });
235
+
236
+ const openPage = (url) => {
237
+ save('mdview.back', [...load('mdview.back', []), here()]);
238
+ save('mdview.forward', []);
239
+ leave(url);
240
+ };
241
+ const travel = (from, to, label) => {
242
+ const stack = load(from, []);
243
+ const entry = stack.pop();
244
+ if (!entry) return flash(`no ${label} page`);
245
+ save(from, stack);
246
+ save(to, [...load(to, []), here()]);
247
+ leave(entry.url, entry.y);
248
+ };
249
+ function goBack() { travel('mdview.back', 'mdview.forward', 'previous'); }
250
+ function goForward() { travel('mdview.forward', 'mdview.back', 'next'); }
251
+
252
+ const restoreY = load('mdview.restoreY', null);
253
+ if (restoreY !== null) {
254
+ try { sessionStorage.removeItem('mdview.restoreY'); } catch {}
255
+ window.scrollTo({ top: restoreY, behavior: 'instant' });
256
+ }
257
+
258
+ document.addEventListener('click', (e) => {
259
+ const a = e.target.closest('a[href]');
260
+ if (!a) return;
261
+ e.preventDefault();
262
+ const url = new URL(a.href, location.href);
263
+ const local = url.origin === location.origin;
264
+ if (local && url.pathname === location.pathname) {
265
+ const el = url.hash && document.getElementById(decodeURIComponent(url.hash.slice(1)));
266
+ scrollTo(el ? el.getBoundingClientRect().top + window.scrollY - 16 : 0);
267
+ history.replaceState(null, '', url.hash || location.pathname);
268
+ } else if (local && /\.(md|markdown|mdown|mkd)$/i.test(url.pathname)) {
269
+ openPage(url.href);
270
+ } else {
271
+ fetch('/__open', { method: 'POST', body: url.href }).catch(() => flash('could not open link'));
272
+ }
273
+ });
274
+ // Middle-click would open a new browser window.
275
+ document.addEventListener('auxclick', (e) => { if (e.target.closest('a[href]')) e.preventDefault(); });
276
+
277
+ // ---------- live reload (keeps scroll position) ----------
278
+
279
+ async function reload() {
280
+ const res = await fetch(location.pathname + '?fragment', { cache: 'no-store' });
281
+ if (!res.ok) return flash(`reload failed: ${res.status}`);
282
+ const y = window.scrollY;
283
+ content.innerHTML = await res.text();
284
+ window.scrollTo({ top: y, behavior: 'instant' });
285
+ }
286
+
287
+ const events = new EventSource('/__events?path=' + encodeURIComponent(decodeURIComponent(location.pathname)));
288
+ events.onmessage = (e) => { if (e.data === 'reload') reload(); };
289
+
290
+ // Server gone (q, Ctrl-C in the terminal): say so instead of leaving a dead window.
291
+ const stopped = () => {
292
+ clearTimeout(statusTimer);
293
+ status.textContent = 'mdview has stopped. You can close this window.';
294
+ status.hidden = false;
295
+ };
296
+ events.onerror = () => {
297
+ if (leaving) return;
298
+ events.close();
299
+ stopped();
300
+ };
301
+
302
+ async function quit() {
303
+ events.close();
304
+ try { await fetch('/__quit'); } catch {}
305
+ window.close();
306
+ setTimeout(stopped, 300); // only runs if the window refused to close
307
+ }
308
+ })();
package/render.mjs ADDED
@@ -0,0 +1,122 @@
1
+ // Markdown rendering for mdview: markdown-it with GitHub-style heading ids, alerts,
2
+ // KaTeX math and YAML frontmatter.
3
+
4
+ import MarkdownIt from 'markdown-it';
5
+ import githubAlerts from 'markdown-it-github-alerts';
6
+ import hljs from 'highlight.js';
7
+ import katex from 'katex';
8
+
9
+ export const isMarkdown = (p) => /\.(md|markdown|mdown|mkd)$/i.test(p);
10
+
11
+ export const escapeHtml = (s) => s.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
12
+
13
+ const md = new MarkdownIt({
14
+ html: true,
15
+ linkify: true,
16
+ typographer: true,
17
+ highlight(code, lang) {
18
+ if (lang && hljs.getLanguage(lang)) {
19
+ return `<pre><code class="hljs language-${lang}">${hljs.highlight(code, { language: lang, ignoreIllegals: true }).value}</code></pre>`;
20
+ }
21
+ return '';
22
+ },
23
+ }).use(githubAlerts);
24
+
25
+ // GitHub-style heading ids so #anchor links work.
26
+ md.core.ruler.push('heading_ids', (state) => {
27
+ const seen = new Map();
28
+ state.tokens.forEach((tok, i) => {
29
+ if (tok.type !== 'heading_open') return;
30
+ const text = state.tokens[i + 1].children.map((c) => c.content).join('');
31
+ let slug = text.toLowerCase().trim().replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s/g, '-');
32
+ const n = seen.get(slug) ?? 0;
33
+ seen.set(slug, n + 1);
34
+ if (n) slug += `-${n}`;
35
+ tok.attrSet('id', slug);
36
+ });
37
+ });
38
+
39
+ // GitHub-style math, rendered with KaTeX: $inline$, $`inline`$, $$display$$ and ```math blocks.
40
+ const tex = (src, displayMode) => katex.renderToString(src, { displayMode, throwOnError: false });
41
+
42
+ const isSpace = (c) => c === ' ' || c === '\t' || c === '\n';
43
+
44
+ md.inline.ruler.before('escape', 'math_inline', (state, silent) => {
45
+ const src = state.src, start = state.pos;
46
+ if (src[start] !== '$') return false;
47
+ let open = '$', close = '$';
48
+ if (src[start + 1] === '`') { open = '$`'; close = '`$'; }
49
+ else if (src[start + 1] === '$') { open = close = '$$'; }
50
+ const from = start + open.length;
51
+ if (open === '$' && (from >= state.posMax || isSpace(src[from]))) return false;
52
+ let end = from;
53
+ for (;;) {
54
+ end = src.indexOf(close, end);
55
+ if (end < 0 || end + close.length > state.posMax) return false;
56
+ if (open !== '$') break;
57
+ if (src[end - 1] === '\\') { end++; continue; } // \$ inside math
58
+ // A lone $ must close at the next $, after a non-space and before a non-digit,
59
+ // so "$5-$10" stays text.
60
+ if (isSpace(src[end - 1]) || /\d/.test(src[end + 1] ?? '')) return false;
61
+ break;
62
+ }
63
+ if (end === from) return false;
64
+ if (!silent) {
65
+ const tok = state.push('math_inline', 'math', 0);
66
+ tok.content = src.slice(from, end);
67
+ tok.markup = open;
68
+ }
69
+ state.pos = end + close.length;
70
+ return true;
71
+ });
72
+
73
+ // $$ on its own line(s): "$$ x $$", or "$$" ... "$$" across lines.
74
+ md.block.ruler.before('fence', 'math_block', (state, startLine, endLine, silent) => {
75
+ if (state.sCount[startLine] - state.blkIndent >= 4) return false;
76
+ const line = (n) => state.src.slice(state.bMarks[n] + state.tShift[n], state.eMarks[n]).trimEnd();
77
+ const first = line(startLine);
78
+ if (!first.startsWith('$$')) return false;
79
+ let content, last = startLine;
80
+ const rest = first.slice(2);
81
+ if (rest.includes('$$')) {
82
+ if (!rest.endsWith('$$') || rest.length < 3) return false; // "$$x$$ more text" is inline math
83
+ content = rest.slice(0, -2);
84
+ } else {
85
+ const lines = [rest];
86
+ for (;;) {
87
+ if (++last >= endLine) return false;
88
+ const l = line(last);
89
+ if (l.endsWith('$$')) { lines.push(l.slice(0, -2)); break; }
90
+ lines.push(l);
91
+ }
92
+ content = lines.join('\n');
93
+ }
94
+ if (silent) return true;
95
+ state.line = last + 1;
96
+ const tok = state.push('math_block', 'math', 0);
97
+ tok.block = true;
98
+ tok.content = content;
99
+ tok.map = [startLine, state.line];
100
+ return true;
101
+ }, { alt: ['paragraph', 'reference', 'blockquote', 'list'] });
102
+
103
+ md.renderer.rules.math_inline = (tokens, idx) => tex(tokens[idx].content, tokens[idx].markup === '$$');
104
+ md.renderer.rules.math_block = (tokens, idx) => tex(tokens[idx].content, true) + '\n';
105
+ const fence = md.renderer.rules.fence;
106
+ md.renderer.rules.fence = (tokens, idx, ...rest) =>
107
+ tokens[idx].info.trim() === 'math' ? tex(tokens[idx].content, true) + '\n' : fence(tokens, idx, ...rest);
108
+
109
+ // YAML frontmatter (e.g. SKILL.md) is shown as a highlighted block instead of
110
+ // being parsed as Markdown, where it turned into an <hr> plus a setext heading.
111
+ const FRONTMATTER = /^?---\r?\n([\s\S]*?\r?\n)?---[ \t]*(?:\r?\n|$)/;
112
+
113
+ // Markdown source to HTML; with markdown false, the text is shown verbatim.
114
+ export const render = (src, markdown = true) => {
115
+ if (!markdown) return `<pre class="plain-text">${escapeHtml(src.replace(/^\uFEFF/, ''))}</pre>`;
116
+ const m = src.match(FRONTMATTER);
117
+ if (!m) return md.render(src);
118
+ const body = md.render(src.slice(m[0].length));
119
+ if (!m[1]?.trim()) return body;
120
+ const yaml = hljs.highlight(m[1], { language: 'yaml', ignoreIllegals: true }).value;
121
+ return `<pre class="frontmatter"><code class="hljs language-yaml">${yaml}</code></pre>\n${body}`;
122
+ };