-
Notifications
You must be signed in to change notification settings - Fork 250
/
Copy pathrenderer.lua
1346 lines (1248 loc) · 42.8 KB
/
renderer.lua
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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
local vim = vim
local NuiLine = require("nui.line")
local NuiTree = require("nui.tree")
local NuiSplit = require("nui.split")
local NuiPopup = require("nui.popup")
local utils = require("neo-tree.utils")
local highlights = require("neo-tree.ui.highlights")
local popups = require("neo-tree.ui.popups")
local events = require("neo-tree.events")
local keymap = require("nui.utils.keymap")
local autocmd = require("nui.utils.autocmd")
local log = require("neo-tree.log")
local windows = require("neo-tree.ui.windows")
local M = { resize_timer_interval = 50 }
local ESC_KEY = vim.api.nvim_replace_termcodes("<ESC>", true, false, true)
local default_popup_size = { width = 60, height = "80%" }
local draw, create_tree, render_tree
local floating_windows = {}
local update_floating_windows = function()
local valid_windows = {}
for _, win in ipairs(floating_windows) do
if M.is_window_valid(win.winid) then
table.insert(valid_windows, win)
end
end
floating_windows = valid_windows
end
local tabid_to_tabnr = function(tabid)
return vim.api.nvim_tabpage_is_valid(tabid) and vim.api.nvim_tabpage_get_number(tabid)
end
local buffer_is_usable = function(bufnr)
return vim.api.nvim_buf_is_valid(bufnr) and vim.api.nvim_buf_is_loaded(bufnr)
end
local cleaned_up = false
---Clean up invalid neotree buffers (e.g after a session restore)
---@param force boolean if true, force cleanup. Otherwise only cleanup once
M.clean_invalid_neotree_buffers = function(force)
if cleaned_up and not force then
return
end
for _, buf in ipairs(vim.api.nvim_list_bufs()) do
local bufname = vim.fn.bufname(buf)
local is_neotree_buffer = string.match(bufname, "neo%-tree [^ ]+ %[%d+]")
local is_valid_neotree, _ = pcall(vim.api.nvim_buf_get_var, buf, "neo_tree_source")
if is_neotree_buffer and not is_valid_neotree then
vim.api.nvim_buf_delete(buf, { force = true })
end
end
cleaned_up = true
end
local resize_monitor_timer = nil
local start_resize_monitor = function()
local interval = M.resize_timer_interval or -1
if interval < 0 then
return
end
if type(interval) ~= "number" then
log.warn("Invalid resize_timer_interval:", interval)
return
end
if resize_monitor_timer then
return
end
local manager = require("neo-tree.sources.manager")
local check_window_size
local speed_up_loops = 0
check_window_size = function()
local windows_exist = false
local success, err = pcall(manager._for_each_state, nil, function(state)
if state.win_width and M.tree_is_visible(state) then
windows_exist = true
local current_size = utils.get_inner_win_width(state.winid)
if current_size ~= state.win_width then
log.trace("Window size changed, redrawing tree")
state.win_width = current_size
render_tree(state)
speed_up_loops = 21 -- move to fast timer for the next 1000 ms
end
end
end)
speed_up_loops = speed_up_loops - 1
if success then
if windows_exist then
local this_interval = interval
if speed_up_loops > 0 then
this_interval = 50
else
speed_up_loops = 0
end
vim.defer_fn(check_window_size, this_interval)
else
log.trace("No windows exist, stopping resize monitor")
end
else
log.debug("Error checking window size: ", err)
vim.defer_fn(check_window_size, math.max(interval * 5, 1000))
end
end
vim.defer_fn(check_window_size, interval)
end
---Safely closes the window and deletes the buffer associated with the state
---@param state table State of the source to close
---@param focus_prior_window boolean | nil if true or nil, focus the window that was previously focused
M.close = function(state, focus_prior_window)
log.debug("Closing window, but saving position first.")
M.position.save(state)
if focus_prior_window == nil then
focus_prior_window = true
end
local window_existed = false
if state and state.winid then
if M.window_exists(state) then
local bufnr = vim.api.nvim_win_get_buf(state.winid)
-- if bufnr is different then we expect, then it was taken over by
-- another buffer, so we can't delete it now
if bufnr == state.bufnr then
window_existed = true
if state.current_position == "current" then
-- we are going to hide the buffer instead of closing the window
M.position.save(state)
local new_buf = vim.fn.bufnr("#")
if new_buf < 1 then
new_buf = vim.api.nvim_create_buf(true, false)
end
vim.api.nvim_win_set_buf(state.winid, new_buf)
else
events.fire_event(events.NEO_TREE_WINDOW_BEFORE_CLOSE, args)
local win_list = vim.api.nvim_tabpage_list_wins(0)
if focus_prior_window and #win_list > 1 then
local args = {
position = state.current_position,
source = state.name,
winid = state.winid,
tabnr = tabid_to_tabnr(state.tabid), -- for compatibility
tabid = state.tabid,
}
-- focus the prior used window if we are closing the currently focused window
local current_winid = vim.api.nvim_get_current_win()
if current_winid == state.winid then
local pwin = require("neo-tree").get_prior_window()
if type(pwin) == "number" and pwin > 0 then
pcall(vim.api.nvim_set_current_win, pwin)
end
end
end
-- if the window was a float, changing the current win would have closed it already
pcall(vim.api.nvim_win_close, state.winid, true)
events.fire_event(events.NEO_TREE_WINDOW_AFTER_CLOSE, args)
end
end
end
state.winid = nil
end
local bufnr = utils.get_value(state, "bufnr", 0, true)
if bufnr > 0 and vim.api.nvim_buf_is_valid(bufnr) then
state.bufnr = nil
local success, err = pcall(vim.api.nvim_buf_delete, bufnr, { force = true })
if not success and err:match("E523") then
vim.schedule_wrap(function()
vim.api.nvim_buf_delete(bufnr, { force = true })
end)()
end
end
return window_existed
end
M.close_floating_window = function(source_name)
local found_windows = {}
for _, win in ipairs(floating_windows) do
if win.source_name == source_name then
table.insert(found_windows, win)
end
end
local valid_window_was_closed = false
for _, win in ipairs(found_windows) do
if not valid_window_was_closed then
valid_window_was_closed = M.is_window_valid(win.winid)
end
-- regardless of whether the window is valid or not, nui will cleanup
win:unmount()
end
return valid_window_was_closed
end
M.close_all_floating_windows = function()
while #floating_windows > 0 do
local win = table.remove(floating_windows)
win:unmount()
end
end
M.get_nui_popup = function(winid)
for _, win in ipairs(floating_windows) do
if win.winid == winid then
return win
end
end
end
local remove_filtered = function(source_items, filtered_items)
local visible = {}
local hidden = {}
for _, child in ipairs(source_items) do
local fby = child.filtered_by
if type(fby) == "table" and not child.is_reveal_target then
if not fby.never_show then
if filtered_items.visible or child.is_nested or fby.always_show then
table.insert(visible, child)
elseif fby.name or fby.pattern or fby.dotfiles or fby.hidden then
table.insert(hidden, child)
elseif fby.show_gitignored and fby.gitignored then
table.insert(visible, child)
else
table.insert(hidden, child)
end
end
else
table.insert(visible, child)
end
end
return visible, hidden
end
local create_nodes
---Transforms a list of items into a collection of TreeNodes.
---@param source_items table The list of items to transform. The expected
--interface for these items depends on the component renderers configured for
--the given source, but they must contain at least an id field.
---@param state table The current state of the plugin.
---@param level integer Optional. The current level of the tree, defaults to 0.
---@return table A collection of TreeNodes.
create_nodes = function(source_items, state, level)
level = level or 0
local nodes = {}
local filtered_items = state.filtered_items or {}
local visible, hidden = remove_filtered(source_items, filtered_items)
if #visible == 0 and level <= 1 and filtered_items.force_visible_in_empty_folder then
source_items = hidden
else
source_items = visible
end
local show_indent_marker_for_message
local msg = state.renderers.message or {}
if msg[1] and msg[1][1] == "indent" then
show_indent_marker_for_message = msg[1].with_markers
end
for i, item in ipairs(source_items) do
local is_last_child = i == #source_items
local nodeData = {
id = item.id,
name = item.name,
type = item.type,
loaded = item.loaded,
filtered_by = item.filtered_by,
extra = item.extra,
is_nested = item.is_nested,
skip_node = item.skip_node,
is_empty_with_hidden_root = item.is_empty_with_hidden_root,
stat = item.stat,
stat_provider = item.stat_provider,
-- TODO: The below properties are not universal and should not be here.
-- Maybe they should be moved to the "extra" field?
is_link = item.is_link,
link_to = item.link_to,
path = item.path,
ext = item.ext,
search_pattern = item.search_pattern,
level = level,
is_last_child = is_last_child,
}
local indent = (state.renderers[item.type] or {}).indent_size or 4
local node_children = nil
if item.children ~= nil then
node_children = create_nodes(item.children, state, level + 1)
end
local node = NuiTree.Node(nodeData, node_children)
if item._is_expanded then
node:expand()
end
table.insert(nodes, node)
end
if #hidden > 0 then
if source_items == hidden then
local nodeData = {
id = hidden[#hidden].id .. "_hidden_message",
name = "(forced to show "
.. #hidden
.. " hidden "
.. (#hidden > 1 and "items" or "item")
.. ")",
type = "message",
level = level,
is_last_child = show_indent_marker_for_message,
}
local node = NuiTree.Node(nodeData)
table.insert(nodes, node)
elseif filtered_items.show_hidden_count or (#visible == 0 and level <= 1) then
local nodeData = {
id = hidden[#hidden].id .. "_hidden_message",
name = "(" .. #hidden .. " hidden " .. (#hidden > 1 and "items" or "item") .. ")",
type = "message",
level = level,
is_last_child = show_indent_marker_for_message,
}
if #nodes > 0 then
nodes[#nodes].is_last_child = not show_indent_marker_for_message
end
local node = NuiTree.Node(nodeData)
table.insert(nodes, node)
end
end
return nodes
end
local one_line = function(text)
if type(text) == "string" then
return text:gsub("\n", " ")
else
return text
end
end
M.render_component = function(component, item, state, remaining_width)
local component_func = state.components[component[1]]
if component_func then
local success, component_data, wanted_width =
pcall(component_func, component, item, state, remaining_width)
if success then
if component_data == nil then
return { {} }
end
if component_data.text then
-- everything else is easier if we make sure this is always the same shape
-- which is an array of { text, highlight } tables
component_data = { component_data }
end
for _, data in ipairs(component_data) do
data.text = one_line(data.text)
end
return component_data, wanted_width
else
local name = component[1] or "[missing_name]"
local msg = string.format("Error rendering component %s: %s", name, component_data)
log.warn(msg)
return { { text = msg, highlight = highlights.NORMAL } }
end
else
local name = component[1] or "[missing_name]"
local msg = "Neo-tree: Component " .. name .. " not found."
log.warn(msg)
return { { text = msg, highlight = highlights.NORMAL } }
end
end
local prepare_node = function(item, state)
if item.skip_node then
if item.is_empty_with_hidden_root then
local line = NuiLine()
line:append("(empty folder)", highlights.MESSAGE)
return line
else
return nil
end
end
-- pre_render is used to calculate the longest node width
-- without actually rendering the node.
-- We'll try to reuse that work if possible.
local pre_render = state._in_pre_render
if item.line and not pre_render then
local line = item.line
-- Only use it once, we don't want to accidentally use stale data
item.line = nil
if
line
and item.wanted_width
and state.longest_node
and item.wanted_width <= state.longest_node
then
return line
end
end
local line = NuiLine()
local renderer = state.renderers[item.type]
if not renderer then
line:append(item.type .. ": ", "Comment")
line:append(item.name)
return line
end
local remaining_cols = state.win_width
if remaining_cols == nil then
if state.winid then
remaining_cols = vim.api.nvim_win_get_width(state.winid)
else
local default_width = utils.resolve_config_option(state, "window.width", 40)
remaining_cols = default_width
end
end
local wanted_width = 0
if state.current_position == "current" then
local longest = state.longest_node or 0
remaining_cols = math.min(remaining_cols, longest + 4)
end
local should_pad = false
for _, component in ipairs(renderer) do
if component.enabled == false then
goto continue
end
local component_data, component_wanted_width =
M.render_component(component, item, state, remaining_cols - (should_pad and 1 or 0))
local actual_width = 0
if component_data then
for _, data in ipairs(component_data) do
if data.text then
local padding = ""
if should_pad and #data.text and data.text:sub(1, 1) ~= " " and not data.no_padding then
padding = " "
end
data.text = padding .. data.text
should_pad = data.text:sub(#data.text) ~= " " and not data.no_next_padding
actual_width = actual_width + vim.api.nvim_strwidth(data.text)
line:append(data.text, data.highlight)
remaining_cols = remaining_cols - vim.fn.strchars(data.text)
end
end
end
component_wanted_width = component_wanted_width or actual_width
wanted_width = wanted_width + component_wanted_width
::continue::
end
line.wanted_width = wanted_width
if pre_render then
item.line = line
state.longest_node = math.max(state.longest_node, line.wanted_width)
else
item.line = nil
end
return line
end
---Sets the cursor at the specified node.
---@param state table The current state of the source.
---@param id string? The id of the node to set the cursor at.
---@return boolean boolean True if the node was found and focused, false
---otherwise.
M.focus_node = function(state, id, do_not_focus_window, relative_movement, bottom_scroll_padding)
if not id and not relative_movement then
log.debug("focus_node called with no id and no relative movement")
return false
end
relative_movement = relative_movement or 0
bottom_scroll_padding = bottom_scroll_padding or 0
local tree = state.tree
if not tree then
log.debug("focus_node called with no tree")
return false
end
local node, linenr = tree:get_node(id)
if not node then
log.debug("focus_node cannot find node with id ", id)
return false
end
id = node:get_id() -- in case nil was passed in for id, meaning current node
local bufnr = utils.get_value(state, "bufnr", 0, true)
if bufnr == 0 then
log.debug("focus_node: state has no bufnr ", state.bufnr, " / ", state.winid)
return false
end
if not vim.api.nvim_buf_is_valid(bufnr) then
log.debug("focus_node: bufnr is not valid")
return false
end
if M.window_exists(state) then
if not linenr then
M.expand_to_node(state, node)
node, linenr = tree:get_node(id)
if not linenr then
log.debug("focus_node cannot get linenr for node with id ", id)
return false
end
end
local focus_window = not do_not_focus_window
if focus_window then
vim.api.nvim_set_current_win(state.winid)
end
-- focus the correct line
linenr = linenr + relative_movement
local col = 0
if node.indent then
col = string.len(node.indent)
end
local success, err = pcall(vim.api.nvim_win_set_cursor, state.winid, { linenr, col })
if success then
-- forget about cursor position as it is overwritten
M.position.clear(state)
-- now ensure that the window is scrolled correctly
local execute_win_command = function(cmd)
if vim.api.nvim_get_current_win() == state.winid then
vim.cmd(cmd)
else
vim.cmd("call win_execute(" .. state.winid .. [[, "]] .. cmd .. [[")]])
end
end
-- make sure we are not scrolled down if it can all fit on the screen
local lines = vim.api.nvim_buf_line_count(state.bufnr)
local win_height = vim.api.nvim_win_get_height(state.winid)
local expected_bottom_line = math.min(lines, linenr + 5) + bottom_scroll_padding
if expected_bottom_line > win_height then
execute_win_command("normal! zb")
local top = vim.fn.line("w0", state.winid)
local bottom = vim.fn.line("w$", state.winid)
local offset_top = top + (expected_bottom_line - bottom)
execute_win_command("normal! " .. offset_top .. "zt")
pcall(vim.api.nvim_win_set_cursor, state.winid, { linenr, col })
elseif win_height > linenr then
execute_win_command("normal! zb")
elseif linenr < (win_height / 2) then
execute_win_command("normal! zz")
end
else
log.debug("Failed to set cursor: " .. err)
end
return success
else
log.debug("focus_node: window does not exist")
return false
end
return false
end
M.get_all_visible_nodes = function(tree)
local nodes = {}
local function process(node)
table.insert(nodes, node)
if node:is_expanded() then
if node:has_children() then
for _, child in ipairs(tree:get_nodes(node:get_id())) do
process(child)
end
end
end
end
for _, node in ipairs(tree:get_nodes()) do
process(node)
end
return nodes
end
M.get_expanded_nodes = function(tree, root_node_id)
local node_ids = {}
local function process(node)
local id = node:get_id()
if node:is_expanded() then
table.insert(node_ids, id)
end
if node:has_children() then
for _, child in ipairs(tree:get_nodes(id)) do
process(child)
end
end
end
if root_node_id then
local root_node = tree:get_node(root_node_id)
if root_node then
process(root_node)
end
else
for _, node in ipairs(tree:get_nodes()) do
process(node)
end
end
return node_ids
end
M.collapse_all_nodes = function(tree, root_node_id)
local expanded = M.get_expanded_nodes(tree, root_node_id)
for _, id in ipairs(expanded) do
local node = tree:get_node(id)
if utils.is_expandable(node) then
node:collapse(id)
end
end
-- but make sure the root is expanded
local root = tree:get_nodes()[1]
if root then
root:expand()
end
end
M.expand_to_node = function(state, node)
if not M.tree_is_visible(state) then
return
end
local tree = state.tree
if type(node) == "string" then
node = tree:get_node(node)
end
local parentId = node:get_parent_id()
while parentId do
local parent = tree:get_node(parentId)
parent:expand()
parentId = parent:get_parent_id()
end
render_tree(state)
end
---Functions to save and restore the focused node.
M.position = {
save = function(state)
if state.position.topline and state.position.lnum then
log.debug("There's already a position saved to be restored. Cannot save another.")
return
end
if state.tree and M.window_exists(state) then
local win_state = vim.api.nvim_win_call(state.winid, vim.fn.winsaveview)
state.position.topline = win_state.topline
state.position.lnum = win_state.lnum
log.debug("Saved cursor position with lnum: " .. state.position.lnum)
log.debug("Saved window position with topline: " .. state.position.topline)
end
end,
set = function(state, node_id)
if not type(node_id) == "string" and node_id > "" then
return
end
state.position.node_id = node_id
end,
clear = function (state)
log.debug("Forget about cursor position.")
-- Clear saved position, so that we can save another position later.
state.position.topline = nil
state.position.lnum = nil
-- After focusing a node, we clear it so that subsequent renderer.position.restore don't
-- focus on it anymore
state.position.node_id = nil
end,
restore = function(state)
if state.position.topline and state.position.lnum then
log.debug("Restoring window position to topline: " .. state.position.topline)
log.debug("Restoring cursor position to lnum: " .. state.position.lnum)
vim.api.nvim_win_call(state.winid, function()
vim.fn.winrestview({ topline = state.position.topline, lnum = state.position.lnum })
end)
end
if state.position.node_id then
log.debug("Focusing on node_id: " .. state.position.node_id)
M.focus_node(state, state.position.node_id, true)
end
M.position.clear(state)
end,
}
---Redraw the tree without relaoding from the source.
---@param state table State of the tree.
M.redraw = function(state)
if state.tree and M.tree_is_visible(state) then
log.trace("Redrawing tree", state.name, state.id)
-- every now and then this will fail because the window was closed in
-- betweeen the start of an async refresh and the redraw call.
-- This is not a problem, so we just ignore the error.
local success = pcall(render_tree, state)
if success then
log.trace(" Redrawing tree done", state.name, state.id)
else
log.trace(" Redrawing tree failed, maybe it was closed?", state.name, state.id)
end
end
end
---Visit all nodes ina tree recursively and reduce to a single value.
---@param tree table NuiTree
---@param memo any Value that is passed to the accumulator function
---@param func function Accumulator function that is called for each node
---@return any any The final memo value.
M.reduce_nodes = function(tree, memo, func)
if type(func) ~= "function" then
error("func must be a function")
end
local visit
visit = function(node)
func(node, memo)
if node:has_children() then
for _, child in ipairs(tree:get_nodes(node:get_id())) do
visit(child)
end
end
end
for _, node in ipairs(tree:get_nodes()) do
visit(node)
end
return memo
end
---Visits all nodes in the tree and returns a list of all nodes that match the
---given predicate.
---@param tree table The NuiTree to search.
---@param selector_func function The predicate function, should return true for
---nodes that should be included in the result.
---@return table table A list of nodes that match the predicate.
M.select_nodes = function(tree, selector_func, limit)
if type(selector_func) ~= "function" then
error("selector_func must be a function")
end
local found_nodes = {}
local visit
visit = function(node)
if selector_func(node) then
table.insert(found_nodes, node)
if limit and #found_nodes >= limit then
return
end
end
if node:has_children() then
for _, child in ipairs(tree:get_nodes(node:get_id())) do
visit(child)
end
end
end
for _, node in ipairs(tree:get_nodes()) do
visit(node)
if limit and #found_nodes >= limit then
break
end
end
return found_nodes
end
M.set_expanded_nodes = function(tree, expanded_nodes)
M.collapse_all_nodes(tree)
log.debug("Setting expanded nodes")
for _, id in ipairs(expanded_nodes or {}) do
local node = tree:get_node(id)
if node ~= nil then
node:expand()
end
end
end
create_tree = function(state)
if state.tree and state.tree.bufnr == state.bufnr then
if buffer_is_usable(state.tree.bufnr) then
log.debug("Tree already exists and buffer is valid, skipping creation", state.name, state.id)
state.tree.winid = state.winid
return
end
end
state.tree = NuiTree({
ns_id = highlights.ns_id,
winid = state.winid,
get_node_id = function(node)
return node.id
end,
prepare_node = function(data)
return prepare_node(data, state)
end,
})
end
local get_selected_nodes = function(state)
if state.winid ~= vim.api.nvim_get_current_win() then
return nil
end
local start_pos = vim.fn.getpos("'<")[2]
local end_pos = vim.fn.getpos("'>")[2]
if end_pos < start_pos then
-- I'm not sure if this could actually happen, but just in case
start_pos, end_pos = end_pos, start_pos
end
local selected_nodes = {}
while start_pos <= end_pos do
local node = state.tree:get_node(start_pos)
if node then
table.insert(selected_nodes, node)
end
start_pos = start_pos + 1
end
return selected_nodes
end
local set_buffer_mappings = function(state)
local resolved_mappings = {}
local skip_this_mapping = {
["none"] = true,
["nop"] = true,
["noop"] = true,
}
local mappings = utils.get_value(state, "window.mappings", {}, true)
local mapping_options = utils.get_value(state, "window.mapping_options", { noremap = true }, true)
for cmd, func in pairs(mappings) do
local vfunc
local config = {}
if utils.truthy(func) then
if skip_this_mapping[func] then
log.trace("Skipping mapping for %s", cmd)
else
local map_options = vim.deepcopy(mapping_options)
local desc
if type(func) == "table" then
for key, value in pairs(func) do
if key ~= "command" and key ~= 1 and key ~= "config" then
map_options[key] = value
end
end
desc = func.desc
config = func.config or {}
func = func.command or func[1]
end
if type(func) == "string" then
resolved_mappings[cmd] = { text = func }
map_options.desc = map_options.desc or func
vfunc = state.commands[func .. "_visual"]
func = state.commands[func]
elseif type(func) == "function" then
resolved_mappings[cmd] = { text = desc or "<function>" }
end
if type(func) == "function" then
resolved_mappings[cmd].handler = function()
state.config = config
return func(state)
end
keymap.set(state.bufnr, "n", cmd, resolved_mappings[cmd].handler, map_options)
if type(vfunc) == "function" then
keymap.set(state.bufnr, "v", cmd, function()
vim.api.nvim_feedkeys(ESC_KEY, "i", true)
vim.schedule(function()
local selected_nodes = get_selected_nodes(state)
if utils.truthy(selected_nodes) then
state.config = config
vfunc(state, selected_nodes)
end
end)
end, map_options)
end
else
log.warn("Invalid mapping for ", cmd, ": ", func)
resolved_mappings[cmd] = "<invalid>"
end
end
end
end
state.resolved_mappings = resolved_mappings
end
local function create_floating_window(state, win_options, bufname)
local win
state.force_float = nil
-- First get the default options for floating windows.
local sourceTitle = state.name:gsub("^%l", string.upper)
win_options = popups.popup_options("Neo-tree " .. sourceTitle, 40, win_options)
win_options.win_options = nil
win_options.zindex = 40
-- Then override with source specific options.
local b = win_options.border
win_options.size = utils.resolve_config_option(state, "window.popup.size", default_popup_size)
win_options.position = utils.resolve_config_option(state, "window.popup.position", "50%")
win_options.border = utils.resolve_config_option(state, "window.popup.border", b)
win = NuiPopup(win_options)
win:mount()
win.source_name = state.name
win.original_options = state.window
table.insert(floating_windows, win)
win:on({ "BufHidden" }, function()
vim.schedule(function()
win:unmount()
end)
end, { once = true })
state.winid = win.winid
state.bufnr = win.bufnr
log.debug("Created floating window with winid: ", win.winid, " and bufnr: ", win.bufnr)
vim.api.nvim_buf_set_name(state.bufnr, bufname)
-- why is this necessary?
vim.api.nvim_set_current_win(win.winid)
return win
end
local get_buffer = function(bufname, state)
local bufnr = vim.fn.bufnr(bufname)
if bufnr > 0 then
if vim.api.nvim_buf_is_valid(bufnr) and vim.api.nvim_buf_is_loaded(bufnr) then
return bufnr
else
pcall(vim.api.nvim_buf_delete, bufnr, { force = true })
bufnr = 0
end
end
if bufnr < 1 then
bufnr = vim.api.nvim_create_buf(false, false)
vim.api.nvim_buf_set_name(bufnr, bufname)
vim.api.nvim_buf_set_option(bufnr, "buftype", "nofile")
vim.api.nvim_buf_set_option(bufnr, "swapfile", false)
vim.api.nvim_buf_set_option(bufnr, "filetype", "neo-tree")
vim.api.nvim_buf_set_option(bufnr, "modifiable", false)
vim.api.nvim_buf_set_option(bufnr, "undolevels", -1)
autocmd.buf.define(bufnr, "BufDelete", function()
M.position.save(state)
end)
end
return bufnr
end
M.acquire_window = function(state)
if M.window_exists(state) then
return state.winid
end
-- used by tests to determine if the tree is ready for testing
state._ready = false
local default_position = utils.resolve_config_option(state, "window.position", "left")
local relative = utils.resolve_config_option(state, "window.relative", "editor")
state.current_position = state.current_position or default_position
local bufname = string.format("neo-tree %s [%s]", state.name, state.id)
local size_opt, default_size
if state.current_position == "top" or state.current_position == "bottom" then
size_opt, default_size = "window.height", "15"
else
size_opt, default_size = "window.width", "40"
end
local win_options = {
ns_id = highlights.ns_id,
size = utils.resolve_config_option(state, size_opt, default_size),
position = state.current_position,
relative = relative,
buf_options = {
buftype = "nofile",
modifiable = false,
swapfile = false,
filetype = "neo-tree",
undolevels = -1,
},
win_options = {
colorcolumn = "",
signcolumn = "no",
},
}
local event_args = {
position = state.current_position,
source = state.name,
tabnr = tabid_to_tabnr(state.tabid), -- for compatibility
tabid = state.tabid,
}
events.fire_event(events.NEO_TREE_WINDOW_BEFORE_OPEN, event_args)
local win
if state.current_position == "float" then
M.close_all_floating_windows()
M.close(state)
win = create_floating_window(state, win_options, bufname)
elseif state.current_position == "current" then
-- state.id is always the window id or tabnr that this state was created for
-- in the case of a position = current state object, it will be the window id
local winid = state.id
if not vim.api.nvim_win_is_valid(winid) then
log.warn("Window ", winid, " is no longer valid!")
return
end
state.winid = winid