-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathinit.lua
More file actions
517 lines (450 loc) · 15.6 KB
/
init.lua
File metadata and controls
517 lines (450 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
-- lua/markdown_preview/init.lua
local ts = require("markdown_preview.ts")
local util = require("markdown_preview.util")
local ls_server = require("live_server.server")
local M = {}
M.config = {
port = 0, -- 0 = auto; effective port depends on instance_mode
open_browser = true,
-- "takeover" = shared workspace + fixed port, one browser tab across instances
-- "multi" = per-instance server + browser tab (port 0 recommended)
instance_mode = "takeover",
content_name = "content.md",
index_name = "index.html",
-- nil = per-buffer workspace (recommended); set a path to override
workspace_dir = nil,
overwrite_index_on_start = true,
auto_refresh = true,
auto_refresh_events = { "InsertLeave", "TextChanged", "TextChangedI", "BufWritePost" },
debounce_ms = 300,
notify_on_refresh = false,
-- "js" = browser-side mermaid.js (default, zero deps)
-- "rust" = pre-render via mermaid-rs-renderer (mmdr) CLI (~400x faster)
mermaid_renderer = "js",
scroll_sync = true, -- sync browser scroll to cursor position
-- Fraction (0–1): vertical position of the final line when scrolled to end.
-- 0.5 = middle of viewport (default), 1.0 = bottom edge (no extra space)
bottom_padding = 0.5,
}
function M.setup(opts)
M.config = vim.tbl_deep_extend("force", M.config, opts or {})
M.config.bottom_padding = math.max(0, math.min(1, M.config.bottom_padding))
M._mmdr_available = nil -- reset so next check re-probes
end
-- Internal state
M._augroup = nil
M._active_bufnr = nil
M._last_text_by_buf = {}
M._server_instance = nil
M._debounce_seq = 0
M._workspace_dir = nil
M._mmdr_available = nil -- nil = unchecked, true/false after probe
M._last_scroll_line = nil
M._is_primary = nil -- true/false/nil (takeover mode)
M._takeover_port = nil -- port of primary server (secondary uses for HTTP events)
local function effective_port()
if M.config.port ~= 0 then return M.config.port end
if M.config.instance_mode == "takeover" then return 8421 end
return 0
end
---------------------------------------------------------------------------
-- Workspace
---------------------------------------------------------------------------
local function resolve_workspace(bufnr)
if M.config.workspace_dir then
return M.config.workspace_dir
end
return util.workspace_for_buffer(bufnr)
end
local function ensure_workspace(bufnr)
local dir = resolve_workspace(bufnr)
util.mkdirp(dir)
return dir
end
---------------------------------------------------------------------------
-- Index HTML
---------------------------------------------------------------------------
local function write_index(dir)
local dst = vim.fs.joinpath(dir, M.config.index_name)
local src = util.resolve_asset("assets/index.html")
if not src then
error("Could not locate assets/index.html in runtimepath. Make sure the plugin ships it.")
end
local content = util.read_text(src)
content = content:gsub("__BOTTOM_PADDING__", tostring(M.config.bottom_padding))
util.write_text(dst, content)
return dst
end
local function write_index_if_needed(dir)
if M.config.overwrite_index_on_start then
return write_index(dir)
end
local dst = vim.fs.joinpath(dir, M.config.index_name)
if not util.file_exists(dst) then
return write_index(dir)
end
return dst
end
---------------------------------------------------------------------------
-- Content writing (unified: markdown or mermaid)
---------------------------------------------------------------------------
local function extract_mermaid_under_cursor_strict(bufnr)
local ok, text = pcall(ts.extract_under_cursor, bufnr)
if ok and text and #text > 0 then
return text
end
return nil
end
local function extract_mermaid_under_cursor(bufnr)
local text = extract_mermaid_under_cursor_strict(bufnr)
if text and #text > 0 then
return text
end
local fallback = ts.fallback_scan(bufnr)
if not fallback or #fallback == 0 then
error("No ```mermaid fenced code block found under (or above) the cursor")
end
return fallback
end
---------------------------------------------------------------------------
-- mermaid-rs-renderer (mmdr) integration
---------------------------------------------------------------------------
---Check if mmdr CLI is available; caches result after first probe.
---@return boolean
local function is_mmdr_available()
if M._mmdr_available ~= nil then
return M._mmdr_available
end
M._mmdr_available = vim.fn.executable("mmdr") == 1
if not M._mmdr_available then
vim.notify(
"Markdown Preview: mermaid_renderer='rust' but `mmdr` not found in PATH.\n"
.. "Install: cargo install mermaid-rs-renderer\n"
.. "Falling back to browser-side mermaid.js.",
vim.log.levels.WARN
)
end
return M._mmdr_available
end
---Render a single mermaid diagram source via mmdr CLI.
---@param source string Raw mermaid diagram text
---@return string|nil svg SVG string on success
---@return string|nil err Error message on failure
local function render_mermaid_via_mmdr(source)
local result = vim.fn.system({ "mmdr", "-e", "svg" }, source)
if vim.v.shell_error ~= 0 then
return nil, result
end
return result, nil
end
-- Expand button SVG used in pre-rendered blocks (matches browser-side fence renderer)
local EXPAND_BTN_SVG = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none">'
.. '<path d="M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>'
.. "</svg>"
---Pre-render ```mermaid fences via mmdr, replacing them with HTML blocks.
---Failed renders leave the original fence untouched for browser-side fallback.
---@param text string Full markdown text
---@return string text Markdown with pre-rendered mermaid blocks
local function prerender_mermaid_blocks(text)
local rust_idx = 0
local out = {}
local pos = 1
while true do
-- Find opening ```mermaid fence
local fence_start, fence_end = text:find("\n```mermaid%s*\n", pos)
if not fence_start then
-- Also check at the very start of the document
if pos == 1 then
fence_start, fence_end = text:find("^```mermaid%s*\n")
end
if not fence_start then
break
end
end
-- Find closing ```
local close_start, close_end = text:find("\n```%s*\n", fence_end)
if not close_start then
-- Try closing at end of file
close_start, close_end = text:find("\n```%s*$", fence_end)
if not close_start then
break
end
end
-- Extract mermaid source between fences
local source = text:sub(fence_end + 1, close_start - 1)
if source and #source > 0 then
local svg, _err = render_mermaid_via_mmdr(source)
if svg then
rust_idx = rust_idx + 1
local block_id = "mmd-rust-" .. rust_idx
local encoded = vim.uri_encode(source, "rfc2396")
local html_block = '<div class="mermaid-block mermaid-rendered" id="'
.. block_id
.. '" data-mermaid-source="'
.. encoded
.. '" data-graph="mermaid" data-prerendered="true">'
.. '<button class="mermaid-expand-btn" title="Expand diagram" data-expand="'
.. block_id
.. '">'
.. EXPAND_BTN_SVG
.. "</button>"
.. '<div class="mermaid-svg-wrap">'
.. svg
.. "</div>"
.. "</div>"
-- Append text before fence + the HTML block
out[#out + 1] = text:sub(pos, fence_start - 1)
out[#out + 1] = "\n" .. html_block .. "\n"
pos = close_end + 1
else
-- mmdr failed for this block — leave fence untouched for JS fallback
out[#out + 1] = text:sub(pos, close_end)
pos = close_end + 1
end
else
out[#out + 1] = text:sub(pos, close_end)
pos = close_end + 1
end
end
-- Append remaining text
out[#out + 1] = text:sub(pos)
return table.concat(out)
end
---------------------------------------------------------------------------
-- Content writing (unified: markdown or mermaid)
---------------------------------------------------------------------------
---Get the content to write based on filetype.
---Markdown buffers: entire buffer.
---Mermaid files (.mmd, .mermaid): entire buffer wrapped in mermaid fence.
---Others: mermaid block under cursor wrapped in fence.
---@param bufnr integer
---@return string
local function get_content(bufnr)
local text
local ft = vim.bo[bufnr].filetype
if ft == "markdown" then
local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)
text = table.concat(lines, "\n")
elseif vim.api.nvim_buf_get_name(bufnr):match("%.mmd$")
or vim.api.nvim_buf_get_name(bufnr):match("%.mermaid$") then
-- .mmd / .mermaid files: treat entire buffer as mermaid
local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)
text = "```mermaid\n" .. table.concat(lines, "\n") .. "\n```\n"
else
-- Other filetypes: extract mermaid block under cursor, wrap in code fence
local mermaid_text = extract_mermaid_under_cursor(bufnr)
text = "```mermaid\n" .. mermaid_text .. "\n```\n"
end
-- Pre-render mermaid blocks via mmdr if configured
if M.config.mermaid_renderer == "rust" and is_mmdr_available() then
text = prerender_mermaid_blocks(text)
end
return text
end
---Same as get_content but never errors (returns nil on failure).
---@param bufnr integer
---@return string|nil
local function get_content_safe(bufnr)
local ok, text = pcall(get_content, bufnr)
if ok and text and #text > 0 then
return text
end
return nil
end
local function write_content(dir, text)
local path = vim.fs.joinpath(dir, M.config.content_name)
util.write_text(path, text)
return path
end
---------------------------------------------------------------------------
-- Refresh logic
---------------------------------------------------------------------------
local function maybe_refresh(bufnr, silent)
bufnr = bufnr or vim.api.nvim_get_current_buf()
local text = get_content_safe(bufnr)
if not text then
return false
end
if M._last_text_by_buf[bufnr] == text then
return false
end
local dir = M._workspace_dir or ensure_workspace(bufnr)
write_content(dir, text)
M._last_text_by_buf[bufnr] = text
-- Notify live-server of the content change for immediate SSE push
-- In secondary takeover mode, M._server_instance is nil — fs_watch handles reload
if M._server_instance then
pcall(ls_server.reload, M._server_instance, M.config.content_name)
end
if not silent and M.config.notify_on_refresh then
vim.notify("Markdown preview updated", vim.log.levels.INFO)
end
return true
end
local function debounced_refresh(bufnr)
M._debounce_seq = M._debounce_seq + 1
local this_call = M._debounce_seq
vim.defer_fn(function()
if this_call ~= M._debounce_seq then
return
end
pcall(maybe_refresh, bufnr, true)
end, M.config.debounce_ms)
end
---------------------------------------------------------------------------
-- Scroll sync (line-based)
---------------------------------------------------------------------------
--- Send cursor line to browser for scroll sync.
local function send_scroll_sync(bufnr)
if not M.config.scroll_sync then return end
local cursor_line = vim.api.nvim_win_get_cursor(0)[1] -- 1-based
if cursor_line == M._last_scroll_line then return end
M._last_scroll_line = cursor_line
local total = vim.api.nvim_buf_line_count(bufnr)
local payload = vim.json.encode({ line = cursor_line - 1, total = total })
if M._server_instance then
pcall(ls_server.send_event, M._server_instance, "scroll", payload)
elseif M._takeover_port then
require("markdown_preview.remote").send_event(M._takeover_port, "scroll", payload)
end
end
---------------------------------------------------------------------------
-- Autocmds
---------------------------------------------------------------------------
local function set_autocmds_for_buffer(bufnr)
if M._augroup then
pcall(vim.api.nvim_del_augroup_by_id, M._augroup)
end
M._augroup = vim.api.nvim_create_augroup("MarkdownPreviewAuto", { clear = true })
if M.config.auto_refresh then
for _, ev in ipairs(M.config.auto_refresh_events) do
vim.api.nvim_create_autocmd(ev, {
group = M._augroup,
buffer = bufnr,
callback = function()
debounced_refresh(bufnr)
end,
desc = "Markdown Preview auto-refresh (debounced)",
})
end
end
for _, ev in ipairs({ "CursorMoved", "CursorMovedI" }) do
vim.api.nvim_create_autocmd(ev, {
group = M._augroup,
buffer = bufnr,
callback = function() send_scroll_sync(bufnr) end,
desc = "Markdown Preview scroll sync",
})
end
end
---------------------------------------------------------------------------
-- Public API
---------------------------------------------------------------------------
function M.start()
local bufnr = vim.api.nvim_get_current_buf()
M._active_bufnr = bufnr
local ok_content, text = pcall(get_content, bufnr)
if not ok_content then
vim.notify("Markdown Preview: " .. tostring(text), vim.log.levels.ERROR)
return
end
-- Resolve workspace: shared (takeover) or per-buffer (multi)
local dir
if M.config.instance_mode == "takeover" then
dir = util.shared_workspace()
else
dir = ensure_workspace(bufnr)
end
util.mkdirp(dir)
M._workspace_dir = dir
write_index_if_needed(dir)
write_content(dir, text)
M._last_text_by_buf[bufnr] = text
set_autocmds_for_buffer(bufnr)
-- In takeover mode, check if another instance already owns the server
if M.config.instance_mode == "takeover" and not M._server_instance then
local lock = require("markdown_preview.lock")
local lock_data = lock.read()
if lock_data and lock.is_server_alive(lock_data.port) then
-- Secondary mode: server already running in another Neovim instance
M._is_primary = false
M._takeover_port = lock_data.port
return
end
-- Stale lock or no lock — we become primary
lock.remove()
end
-- Start live-server if not already running
if not M._server_instance then
local port = effective_port()
local index_path = vim.fs.joinpath(dir, M.config.index_name)
local ok, inst = pcall(ls_server.start, {
port = port,
root = dir,
default_index = index_path,
headers = { ["Cache-Control"] = "no-cache" },
cors = true,
live = {
enabled = true,
inject_script = false,
debounce = 100,
},
features = { dirlist = { enabled = false } },
})
if not ok then
vim.notify(
("Markdown Preview: failed to start server (port %s) — %s"):format(tostring(port), tostring(inst)),
vim.log.levels.ERROR
)
return
end
M._server_instance = inst
M._is_primary = true
M._takeover_port = nil
-- Write lock file in takeover mode
if M.config.instance_mode == "takeover" then
require("markdown_preview.lock").write(inst.port, dir)
end
if M.config.open_browser then
vim.defer_fn(function()
util.open_in_browser(("http://127.0.0.1:%d/"):format(inst.port))
end, 200)
end
else
-- Server already running — retarget to this buffer's workspace
local index_path = vim.fs.joinpath(dir, M.config.index_name)
pcall(ls_server.update_target, M._server_instance, dir, index_path)
pcall(ls_server.reload, M._server_instance, M.config.content_name)
-- No browser tab connected (user closed it)? Re-open.
if M.config.open_browser and ls_server.connected_client_count(M._server_instance) == 0 then
vim.defer_fn(function()
util.open_in_browser(("http://127.0.0.1:%d/"):format(M._server_instance.port))
end, 200)
end
end
end
function M.refresh()
local bufnr = vim.api.nvim_get_current_buf()
local changed = maybe_refresh(bufnr, false)
if not changed and M.config.notify_on_refresh then
vim.notify("Markdown Preview: no changes detected", vim.log.levels.INFO)
end
end
function M.stop()
if M._augroup then
pcall(vim.api.nvim_del_augroup_by_id, M._augroup)
M._augroup = nil
end
if M._server_instance then
pcall(ls_server.stop, M._server_instance)
M._server_instance = nil
end
if M._is_primary then
require("markdown_preview.lock").remove()
end
M._workspace_dir = nil
M._last_scroll_line = nil
M._is_primary = nil
M._takeover_port = nil
end
return M