-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathinit.lua
More file actions
626 lines (548 loc) · 18.8 KB
/
Copy pathinit.lua
File metadata and controls
626 lines (548 loc) · 18.8 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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
local logger = require("image/utils/logger")
local processors = require("image/processors")
local render_scheduler = require("image/utils/render_scheduler")
local report = require("image/report")
local utils = require("image/utils")
local log = logger.within("core")
---@type table<string, string>
local backend_modules = {
kitty = "image/backends/kitty",
ueberzug = "image/backends/ueberzug",
sixel = "image/backends/sixel",
}
---@type Options
local default_options = {
-- backend = "ueberzug",
backend = "kitty",
processor = "magick_cli",
debug = {
enabled = false,
level = "debug",
file_path = "/tmp/image.nvim.log",
format = "compact",
},
integrations = {
markdown = {
enabled = true,
},
asciidoc = {
enabled = true,
},
typst = {
enabled = true,
},
neorg = {
enabled = true,
},
syslang = {
enabled = true,
},
html = {
enabled = false,
},
css = {
enabled = false,
},
org = {
enabled = false,
},
},
max_width = nil,
max_height = nil,
max_width_window_percentage = 100,
max_height_window_percentage = 50,
scale_factor = 1.0,
kitty_method = "normal",
kitty_direct_chunk_size = 4096,
window_overlap_clear_enabled = false,
window_overlap_clear_ft_ignore = { "cmp_menu", "cmp_docs", "snacks_notif", "scrollview", "scrollview_sign" },
editor_only_render_when_focused = false,
tmux_show_only_in_active_window = false,
ignore_download_error = false,
hijack_file_patterns = { "*.png", "*.jpg", "*.jpeg", "*.gif", "*.webp", "*.avif" },
}
---@type State
local state = {
---@diagnostic disable-next-line: assign-type-mismatch
backend = nil,
---@diagnostic disable-next-line: assign-type-mismatch
processor = nil,
options = default_options,
images = {},
extmarks_namespace = vim.api.nvim_create_namespace("image.nvim"),
remote_cache = {},
tmp_dir = vim.fn.tempname(),
disable_decorator_handling = false,
hijacked_win_buf_images = {},
enabled = true,
}
---@type API
---@diagnostic disable-next-line: missing-fields
local api = {}
---@param name string
local function validate_backend(name)
if not backend_modules[name] then utils.throw("image.nvim: backend not found: " .. tostring(name)) end
end
---@param name string
---@return Backend
local function create_lazy_backend(name)
validate_backend(name)
local backend = nil
local load_backend = function()
if backend then return backend end
backend = require(backend_modules[name])
if type(backend.setup) == "function" then backend.setup(state) end
return backend
end
return setmetatable({}, {
__index = function(_, key)
return load_backend()[key]
end,
__newindex = function(_, key, value)
load_backend()[key] = value
end,
})
end
---@param options Options
api.setup = function(options)
local opts = vim.tbl_deep_extend("force", default_options, options or {})
state.options = opts
-- setup logger with debug configuration
if opts.debug then logger.setup(opts.debug) end
if opts.processor == "magick_rock" then
vim.schedule(function()
require("image/magick").warn_if_magick_rock_missing()
end)
end
state.processor = processors.create_lazy_processor(opts.processor)
state.backend = create_lazy_backend(opts.backend)
render_scheduler.clear()
-- load integrations
for integration_name, integration_options in pairs(opts.integrations) do
if integration_options.enabled then
log.debug("Loading integration: " .. integration_name)
local ok, integration = pcall(require, "image/integrations/" .. integration_name)
if not ok then
log.error("Failed to load integration: " .. integration_name, integration)
elseif type(integration.setup) == "function" then
integration.setup(api, integration_options, state)
log.debug("Setup integration: " .. integration_name)
end
end
end
-- create tmp dir
vim.fn.mkdir(state.tmp_dir, "p")
local render_window_images = function(winid)
if not state.enabled then return end
if not winid or not vim.api.nvim_win_is_valid(winid) then return end
local bufnr = vim.api.nvim_win_get_buf(winid)
for _, current_image in ipairs(api.get_images({ window = winid, buffer = bufnr })) do
current_image:render()
end
end
local schedule_window_render = function(winid)
if not winid then return end
render_scheduler.schedule(("core:window:%d"):format(winid), function()
render_window_images(winid)
end)
end
local schedule_all_window_render = function()
render_scheduler.schedule("core:all-windows", function()
if not state.enabled then return end
local windows_to_render = {}
for _, current_image in ipairs(api.get_images()) do
if current_image.window ~= nil then
state.backend.clear(current_image.id, true)
windows_to_render[current_image.window] = true
end
end
for winid in pairs(windows_to_render) do
render_window_images(winid)
end
end)
end
-- handle folds / scroll extra
---@type table<number, { topline: number, botline: number, bufnr: number, height: number; folded_lines: number }>
local window_history = {}
vim.api.nvim_set_decoration_provider(state.extmarks_namespace, {
on_win = function(_, winid, bufnr, topline, botline)
-- bail if not enabled
if not state.enabled then return false end
-- bail if decorator handling is disabled
if state.disable_decorator_handling then return false end
-- bail if not in normal mode, there's a weird behavior where in visual mode this callback gets called CONTINUOUSLY
if vim.api.nvim_get_mode().mode ~= "n" then return false end
if not vim.api.nvim_win_is_valid(winid) then return false end
if not vim.api.nvim_buf_is_valid(bufnr) then return false end
local prev = window_history[winid]
local buffer_changed = prev ~= nil and prev.bufnr ~= bufnr
if buffer_changed then
for _, curr in ipairs(api.get_images({ window = winid, buffer = prev.bufnr })) do
curr:clear(true)
end
end
-- bail if there are no images
local all_images = api.get_images()
if #all_images == 0 then
window_history[winid] = { topline = topline, botline = botline, bufnr = bufnr }
return false
end
-- toggle images in overlapped windows
if state.options.window_overlap_clear_enabled then
render_scheduler.schedule("core:overlap", function()
local windows = utils.window.get_windows({
normal = true,
floating = true,
with_masks = true,
ignore_masking_filetypes = state.options.window_overlap_clear_ft_ignore,
})
for _, current_window in ipairs(windows) do
local cur_win_images = api.get_images({ window = current_window.id, buffer = current_window.buffer })
if #current_window.masks > 0 then
for _, current_image in ipairs(cur_win_images) do
current_image:clear(true)
end
else
for _, current_image in ipairs(cur_win_images) do
if not current_image.is_rendered then current_image:render() end
end
end
end
end)
end
-- bail if there are no images tied to this window and buffer pair
local images = api.get_images({ window = winid, buffer = bufnr })
if #images == 0 then
window_history[winid] = { topline = topline, botline = botline, bufnr = bufnr }
return false
end
-- get current window
local window = utils.window.get_window(winid)
if not window then return false end
if not prev then
window_history[winid] = { topline = topline, botline = botline, bufnr = bufnr }
return false
end
local height = vim.api.nvim_win_get_height(winid)
local needs_rerender = buffer_changed
-- rerender if height, topline, or botline changed
needs_rerender = needs_rerender or prev.topline ~= topline or prev.botline ~= botline or prev.height ~= height
-- rerender if the amount of folded lines changed
local folded_lines = 0
local i = 1
while i < botline do
local fold_start, fold_end = vim.fn.foldclosed(i), vim.fn.foldclosedend(i)
if fold_start ~= -1 and fold_end ~= -1 then
folded_lines = folded_lines + (fold_end - fold_start)
i = fold_end + 1
else
i = i + 1
end
end
if prev.folded_lines ~= folded_lines then needs_rerender = true end
-- store new state
window_history[winid] =
{ topline = topline, botline = botline, bufnr = bufnr, height = height, folded_lines = folded_lines }
-- execute deferred clear / rerender
log.debug("needs_rerender", { needs_rerender = needs_rerender })
render_scheduler.schedule(("core:decorator:%d"):format(winid), function()
if not needs_rerender then return end
if not vim.api.nvim_win_is_valid(winid) then return end
if vim.api.nvim_win_get_buf(winid) ~= bufnr then return end
render_window_images(winid)
end)
return false
end,
})
-- setup autocommands
local group = vim.api.nvim_create_augroup("image.nvim", { clear = true })
-- auto-clear on buffer / window close
vim.api.nvim_create_autocmd({ "BufLeave", "WinClosed", "TabEnter" }, {
group = group,
callback = function() -- auto-clear images when windows and buffers change
-- bail if not enabled
if not state.enabled then return end
vim.schedule(function()
local images = api.get_images()
local windows_in_current_tab = vim.api.nvim_tabpage_list_wins(0)
local windows_in_current_tab_map = {}
for _, current_window in ipairs(windows_in_current_tab) do
windows_in_current_tab_map[current_window] = true
end
for _, current_image in ipairs(images) do
if current_image.window then
local window_ok, is_valid_window = pcall(vim.api.nvim_win_is_valid, current_image.window)
if not window_ok or not is_valid_window then
current_image:clear()
return
end
local is_window_in_current_tab = windows_in_current_tab_map[current_image.window]
if not is_window_in_current_tab then
current_image:clear()
return
end
if current_image.buffer then
local buf_ok, is_valid_buffer = pcall(vim.api.nvim_buf_is_valid, current_image.buffer)
if not buf_ok or not is_valid_buffer then
current_image:clear()
return
end
local is_buffer_in_window = vim.api.nvim_win_get_buf(current_image.window) == current_image.buffer
if not is_buffer_in_window then current_image:clear() end
end
end
end
end)
end,
})
-- rerender on scroll
vim.api.nvim_create_autocmd({ "WinScrolled" }, {
group = group,
callback = function(au)
if not state.enabled then return end
schedule_window_render(tonumber(au.file))
end,
})
-- force rerender on resize (handles VimResized as well)
vim.api.nvim_create_autocmd({ "WinResized", "WinNew" }, {
group = group,
callback = function()
if not state.enabled then return end
schedule_all_window_render()
end,
})
-- auto-clear on VimSuspend and re-render on VimResume
local image_to_restore_on_resume = {}
vim.api.nvim_create_autocmd({ "VimSuspend" }, {
group = group,
callback = function()
local images = api.get_images()
for _, current_image in ipairs(images) do
current_image:clear()
end
image_to_restore_on_resume = images
end,
})
vim.api.nvim_create_autocmd({ "VimResume" }, {
group = group,
callback = function()
local images = image_to_restore_on_resume
for _, current_image in ipairs(images) do
current_image:render()
end
end,
})
-- auto-toggle on editor focus change
if
state.options.editor_only_render_when_focused
or (state.options.tmux_show_only_in_active_window and utils.tmux.is_tmux)
then
local images_to_restore_on_focus = {}
local initial_tmux_window_id = utils.tmux.get_window_id()
local initial_tmux_session = utils.tmux.get_current_session()
vim.api.nvim_create_autocmd("FocusLost", {
group = group,
callback = function() -- auto-clear images when windows and buffers change
-- bail if not enabled
if not state.enabled then return end
vim.schedule(function()
log.debug("FocusLost")
if
state.options.editor_only_render_when_focused
or (utils.tmux.is_tmux and utils.tmux.get_window_id() ~= initial_tmux_window_id)
or (utils.tmux.is_tmux and utils.tmux.get_current_session() ~= initial_tmux_session)
then
state.disable_decorator_handling = true
local images = api.get_images()
for _, current_image in ipairs(images) do
if current_image.is_rendered then
current_image:clear(true)
table.insert(images_to_restore_on_focus, current_image)
end
end
end
end)
end,
})
vim.api.nvim_create_autocmd("FocusGained", {
group = group,
callback = function() -- auto-clear images when windows and buffers change
-- bail if not enabled
if not state.enabled then return end
log.debug("FocusGained")
state.disable_decorator_handling = false
vim.schedule_wrap(function()
-- force rerender
local images = api.get_images()
for _, current_image in ipairs(images) do
if current_image.is_rendered then
current_image:clear()
current_image:render()
end
end
-- render images cleared on focus loss
for _, current_image in ipairs(images_to_restore_on_focus) do
current_image:render()
end
images_to_restore_on_focus = {}
end)()
end,
})
end
-- hijack image filetypes
if state.options.hijack_file_patterns and #state.options.hijack_file_patterns > 0 then
vim.api.nvim_create_autocmd({
"WinNew",
"BufWinEnter",
"TabEnter",
}, {
group = group,
pattern = state.options.hijack_file_patterns,
callback = function(event)
-- bail if not enabled
if not state.enabled then return end
local buf = event.buf
local win = vim.api.nvim_get_current_win()
local path = vim.api.nvim_buf_get_name(buf)
api.hijack_buffer(path, win, buf)
end,
})
end
-- sync with extmarks
vim.api.nvim_create_autocmd({ "BufWritePost", "TextChanged", "TextChangedI", "InsertEnter" }, {
group = group,
callback = function(event)
-- bail if not enabled
if not state.enabled then return end
local images = api.get_images({ buffer = event.buf })
for _, img in ipairs(images) do
local has_moved, extmark_y, extmark_x = img:has_extmark_moved()
if has_moved and extmark_x and extmark_y then
img.geometry.y = extmark_y
img.geometry.x = extmark_x
img.extmark.col = extmark_x
img.extmark.row = extmark_y
img:render()
end
end
end,
})
-- add :ImageReport
vim.api.nvim_create_user_command("ImageReport", function()
api.create_report()
end, {})
end
local guard_setup = function()
if not state.backend then utils.throw("image.nvim is not setup. Call setup() first.") end
end
---@param path string
---@param win number? if nil or 0, uses current window
---@param buf number? if nil or 0, uses current buffer
---@param options ImageOptions?
---@return Image|nil
api.hijack_buffer = function(path, win, buf, options)
if not win or win == 0 then win = vim.api.nvim_get_current_win() end
if not buf or buf == 0 then buf = vim.api.nvim_get_current_buf() end
vim.bo[buf].modifiable = true
vim.api.nvim_buf_set_lines(buf, 0, -1, true, { "" })
vim.bo[buf].modifiable = false
vim.bo[buf].buftype = "nowrite"
vim.bo[buf].filetype = "image_nvim"
vim.opt_local.colorcolumn = "0"
vim.opt_local.cursorline = false
vim.opt_local.number = false
vim.opt_local.signcolumn = "no"
local key = ("%s:%s"):format(win, buf)
if state.hijacked_win_buf_images[key] then
state.hijacked_win_buf_images[key]:render()
return state.hijacked_win_buf_images[key]
end
local opts = options or {}
opts.window = win
opts.buffer = buf
if not opts.x then opts.x = 0 end
if not opts.y then opts.y = 0 end
local img = api.from_file(path, opts)
if img then
-- wait for vimenter
if vim.v.vim_did_enter == 1 then
img:render()
else
vim.api.nvim_create_autocmd("VimEnter", {
once = true,
callback = function()
img:render()
end,
})
end
state.hijacked_win_buf_images[key] = img
end
return img
end
---@param path string
---@param options? ImageOptions
api.from_file = function(path, options)
guard_setup()
local image = require("image/image")
return image.from_file(path, options, state)
end
---@param url string
---@param options? ImageOptions
---@param callback fun(image: Image|nil)
api.from_url = function(url, options, callback)
guard_setup()
local image = require("image/image")
image.from_url(url, options, callback, state)
end
---@param id? string
api.clear = function(id)
guard_setup()
local target = state.images[id]
if target then
target:clear()
else
state.backend.clear(id)
end
end
---@param opts? { window?: number, buffer?: number, namespace?: string }
---@return Image[]
api.get_images = function(opts)
local images = {}
local namespace = opts and opts.namespace or nil
for _, current_image in pairs(state.images) do
if (namespace and current_image.namespace == namespace) or not namespace then
if
(opts and opts.window and opts.window == current_image.window and not opts.buffer)
or (opts and opts.buffer and opts.buffer == current_image.buffer and not opts.window)
or (opts and opts.window and opts.buffer and opts.window == current_image.window and opts.buffer == current_image.buffer)
or not opts
then
table.insert(images, current_image)
end
end
end
return images
end
api.create_report = function()
guard_setup()
return report.create(state)
end
---@return boolean
api.is_enabled = function()
return state.enabled
end
api.enable = function()
state.enabled = true
local images = api.get_images()
for _, current_image in ipairs(images) do
current_image:render()
end
end
api.disable = function()
state.enabled = false
local images = api.get_images()
for _, current_image in ipairs(images) do
current_image:clear(true)
end
end
return api