This repository was archived by the owner on Dec 7, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinit.lua
More file actions
1811 lines (1559 loc) · 47.8 KB
/
init.lua
File metadata and controls
1811 lines (1559 loc) · 47.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
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
-- Strive: Minimalist Plugin Manager for Neovim
-- A lightweight, feature-rich plugin manager with support for lazy loading,
-- dependencies, and asynchronous operations.
local api, uv, fs, joinpath = vim.api, vim.uv, vim.fs, vim.fs.joinpath
-- =====================================================================
-- 1. Configuration and Constants
-- =====================================================================
local M = {}
local plugins = {}
local plugin_map = {}
-- Data paths
local data_dir = vim.fn.stdpath('data')
local START_DIR = joinpath(data_dir, 'site', 'pack', 'strive', 'start')
local OPT_DIR = joinpath(data_dir, 'site', 'pack', 'strive', 'opt')
-- Add to packpath
vim.opt.packpath:prepend(joinpath(data_dir, 'site'))
vim.g.strive_loaded = 0
vim.g.strive_count = 0
local DEFAULT_SETTINGS = {
max_concurrent_tasks = vim.g.strive_max_concurrent_tasks or 10,
auto_install = vim.g.strive_auto_install or true,
log_level = vim.g.strive_log_level or 'warn',
git_timeout = vim.g.strive_git_timeout or 60000,
git_depth = vim.g.strive_git_depth or 1,
install_retry = vim.g.strive_install_with_retry or false,
}
-- Plugin status constants
local STATUS = {
PENDING = 'pending',
LOADING = 'loading',
LOADED = 'loaded',
INSTALLING = 'installing',
INSTALLED = 'installed',
UPDATING = 'updating',
UPDATED = 'updated',
ERROR = 'error',
}
local function isdir(dir)
return (uv.fs_stat(dir) or {}).type == 'directory'
end
-- =====================================================================
-- 2. Async Utilities
-- =====================================================================
local Async = {}
-- Result type to handle errors properly
local Result = {}
local success_meta = { success = true, error = nil }
local failure_meta = { success = false, value = nil }
success_meta.__index = success_meta
failure_meta.__index = failure_meta
function Result.success(value)
return setmetatable({ value = value }, success_meta)
end
function Result.failure(err)
return setmetatable({ error = err }, failure_meta)
end
-- Wrap a function to return a promise
function Async.wrap(func)
return function(...)
local args = { ... }
return function(callback)
local function handle_result(...)
local results = { ... }
if #results == 0 then
-- No results
callback(Result.success(nil))
elseif #results == 1 then
-- Single result
callback(Result.success(results[1]))
else
-- Multiple results
callback(Result.success(results))
end
end
-- Handle any errors in the wrapped function
local status, err = pcall(function()
table.insert(args, handle_result)
func(unpack(args))
end)
if not status then
callback(Result.failure(err))
end
end
end
end
-- Wrap vim.system to provide better error handling and cleaner usage
function Async.system(cmd, opts)
opts = opts or {}
return function(callback)
local progress_data = {}
local error_data = {}
local stderr_callback = opts.stderr
-- Setup options
local system_opts = vim.deepcopy(opts)
-- Capture stderr for progress if requested
if stderr_callback then
system_opts.stderr = function(_, data)
if data then
table.insert(error_data, data)
stderr_callback(_, data)
end
end
end
-- Call vim.system with proper error handling
vim.system(cmd, system_opts, function(obj)
-- Success is 0 exit code
local success = obj.code == 0
if success then
callback(Result.success({
stdout = obj.stdout,
stderr = obj.stderr,
code = obj.code,
signal = obj.signal,
progress = progress_data,
}))
else
callback(Result.failure({
message = 'Command failed with exit code: ' .. obj.code,
stdout = obj.stdout,
stderr = obj.stderr,
code = obj.code,
signal = obj.signal,
progress = progress_data,
}))
end
end)
end
end
-- Await a promise - execution is paused until promise resolves
function Async.await(promise)
local co = coroutine.running()
if not co then
error('Cannot await outside of an async function')
end
promise(function(result)
vim.schedule(function()
local ok = coroutine.resume(co, result)
if not ok then
vim.notify(debug.traceback(co), vim.log.levels.ERROR)
end
end)
end)
local result = coroutine.yield()
-- Propagate errors by throwing them
if not result.success then
error(result.error)
end
return result.value
end
-- Safely await a promise, returning a result instead of throwing
function Async.try_await(promise)
local co = coroutine.running()
if not co then
error('Cannot await outside of an async function')
end
promise(function(result)
vim.schedule(function()
local ok = coroutine.resume(co, result)
if not ok then
vim.notify(debug.traceback(co), vim.log.levels.ERROR)
end
end)
end)
return coroutine.yield()
end
-- Create an async function that can use await
function Async.async(func)
return function(...)
local args = { ... }
local co = coroutine.create(function()
local status, result = pcall(function()
return func(unpack(args))
end)
if not status then
vim.schedule(function()
vim.notify('Async error: ' .. tostring(result), vim.log.levels.ERROR)
end)
end
return status and result or nil
end)
local function step(...)
local ok, err = coroutine.resume(co, ...)
if not ok then
vim.schedule(function()
vim.notify('Coroutine error: ' .. debug.traceback(co, err), vim.log.levels.ERROR)
end)
end
end
step()
end
end
-- Run multiple promises concurrently and wait for all to complete
function Async.all(promises)
return function(callback)
if #promises == 0 then
callback(Result.success({}))
return
end
local results = {}
local completed = 0
local had_errors = false
local first_error = nil
for i, promise in ipairs(promises) do
promise(function(result)
results[i] = result
completed = completed + 1
-- Keep track of first error
if not result.success and not had_errors then
had_errors = true
first_error = result.error
end
if completed == #promises then
if had_errors then
callback(Result.failure(first_error))
else
-- Extract values from results
local values = {}
for j, res in ipairs(results) do
values[j] = res.value
end
callback(Result.success(values))
end
end
end)
end
end
end
-- Simple delay function (sleep)
function Async.delay(ms)
return function(callback)
vim.defer_fn(function()
callback(Result.success(nil))
end, ms)
end
end
-- Retry a promise with exponential backoff
function Async.retry(promise_fn, max_retries, initial_delay)
max_retries = max_retries or 3
initial_delay = initial_delay or 100
return function(callback)
local attempt = 0
local function try()
attempt = attempt + 1
promise_fn()(function(result)
if result.success or attempt >= max_retries then
callback(result)
else
-- Exponential backoff
local delay = initial_delay * (2 ^ (attempt - 1))
vim.defer_fn(try, delay)
end
end)
end
try()
end
end
function Async.scandir(dir)
return function(callback)
uv.fs_scandir(dir, function(err, handle)
callback(err and Result.failure(err) or Result.success(handle))
end)
end
end
function Async.safe_schedule(callback)
if vim.in_fast_event() then
vim.schedule(function()
callback()
end)
else
callback()
end
end
-- =====================================================================
-- 3. Task Queue
-- =====================================================================
local TaskQueue = {}
TaskQueue.__index = TaskQueue
-- Create a new task queue with a maximum number of concurrent tasks
function TaskQueue.new(max_concurrent)
local self = setmetatable({
active_tasks = 0,
max_concurrent = max_concurrent,
queue = {},
on_empty = nil,
}, TaskQueue)
return self
end
-- Process the queue, starting as many tasks as allowed
function TaskQueue:process()
M.log(
'debug',
string.format('TaskQueue status: %d queued, %d active', #self.queue, self.active_tasks)
)
if #self.queue == 0 and self.active_tasks == 0 and self.on_empty then
M.log('debug', 'All tasks completed, calling on_empty callback')
self.on_empty()
return
end
M.log(
'debug',
string.format('Starting new task, active: %d, queued: %d', self.active_tasks, #self.queue)
)
while self.active_tasks < self.max_concurrent and #self.queue > 0 do
local task = table.remove(self.queue, 1)
self.active_tasks = self.active_tasks + 1
task(function()
self.active_tasks = self.active_tasks - 1
self:process()
end)
end
end
-- Add a task to the queue and start processing
function TaskQueue:enqueue(task)
table.insert(self.queue, task)
self:process()
return self
end
-- Set a callback for when the queue becomes empty
function TaskQueue:on_complete(callback)
self.on_empty = callback
-- Check immediately in case the queue is already empty
if #self.queue == 0 and self.active_tasks == 0 and self.on_empty then
self.on_empty()
end
return self
end
-- Get the current queue status
function TaskQueue:status()
return {
queued = #self.queue,
active = self.active_tasks,
total = #self.queue + self.active_tasks,
}
end
-- =====================================================================
-- 4. UI Window
-- =====================================================================
local ProgressWindow = {}
ProgressWindow.__index = ProgressWindow
function ProgressWindow.new()
local self = setmetatable({
bufnr = nil,
winid = nil,
entries = {},
visible = false,
title = 'Strive Plugin Manager',
}, ProgressWindow)
return self
end
-- Create the buffer for the window
function ProgressWindow:create_buffer()
self.bufnr = api.nvim_create_buf(false, true)
-- Set buffer options
vim.bo[self.bufnr].buftype = 'nofile'
vim.bo[self.bufnr].bufhidden = 'wipe'
vim.bo[self.bufnr].swapfile = false
vim.bo[self.bufnr].modifiable = false
-- Set buffer name
api.nvim_buf_set_name(self.bufnr, 'strive-Progress')
-- Set key mappings for the buffer
self:set_keymaps()
return self
end
-- Set key mappings for the window
function ProgressWindow:set_keymaps()
local opts = { buffer = self.bufnr }
local mapset = vim.keymap.set
for _, key in ipairs({ 'q', '<ESC>' }) do
mapset('n', key, function()
self:close()
end, opts)
end
-- Add other useful keymaps
mapset('n', 'r', function()
self:refresh()
end, vim.tbl_extend('force', opts, { desc = 'Refresh display' }))
end
-- Create and open the window
function ProgressWindow:open()
if self.visible and api.nvim_win_is_valid(self.winid) then
api.nvim_set_current_win(self.winid)
return self
end
if not self.bufnr or not api.nvim_buf_is_valid(self.bufnr) then
self:create_buffer()
end
-- Calculate window dimensions (50% of screen)
local width = math.floor(vim.o.columns * 0.8)
local height = math.floor(vim.o.lines * 0.5)
-- Create the window
self.winid = api.nvim_open_win(self.bufnr, true, {
relative = 'editor',
width = width,
height = height,
row = math.floor((vim.o.lines - height) / 2),
col = math.floor((vim.o.columns - width) / 2),
style = 'minimal',
border = 'rounded',
title = self.title,
title_pos = 'center',
})
self.ns = api.nvim_create_namespace('Strive')
-- Set window options
vim.wo[self.winid].wrap = false
vim.wo[self.winid].foldenable = false
vim.wo[self.winid].cursorline = true
self.visible = true
self:refresh()
return self
end
-- Close the window
function ProgressWindow:close()
if self.visible and self.winid and api.nvim_win_is_valid(self.winid) then
api.nvim_win_close(self.winid, true)
self.visible = false
end
return self
end
-- Update entry for a plugin
function ProgressWindow:update_entry(plugin_name, status, message)
self.entries[plugin_name] = {
status = status,
message = message,
time = os.time(),
}
if self.visible then
Async.safe_schedule(function()
self:refresh()
end)
end
return self
end
-- Refresh the window content
function ProgressWindow:refresh()
-- Ensure we're not in a fast event context
if not self.visible then
return self
end
-- Check buffer validity safely
local buf_valid = false
if self.bufnr then
-- This could throw in a fast event context, so we need to handle it safely
local ok, result = pcall(api.nvim_buf_is_valid, self.bufnr)
buf_valid = ok and result
end
if not buf_valid then
return self
end
-- Convert entries to sorted list
local lines = {}
local sorted_plugins = {}
for name, _ in pairs(self.entries) do
table.insert(sorted_plugins, name)
end
table.sort(sorted_plugins)
local width = api.nvim_win_get_width(self.winid)
-- Header
table.insert(lines, string.rep('=', width))
table.insert(lines, string.format('%-40s %-10s %s', 'Plugin', 'Status', 'Message'))
table.insert(lines, string.rep('=', width))
-- Plugin entries
for _, name in ipairs(sorted_plugins) do
local entry = self.entries[name]
table.insert(
lines,
string.format('%-40s %-10s %s', name:sub(1, 40), entry.status, entry.message or '')
)
end
-- Update buffer content
vim.bo[self.bufnr].modifiable = true
api.nvim_buf_set_lines(self.bufnr, 0, -1, false, lines)
vim.bo[self.bufnr].modifiable = false
vim.hl.range(self.bufnr, self.ns, 'Comment', { 0, 0 }, { 2, -1 })
return self
end
-- Clear all entries
function ProgressWindow:clear()
self.entries = {}
if self.visible then
self:refresh()
end
return self
end
-- Create a singleton UI window
local ui = ProgressWindow.new()
-- =====================================================================
-- 5. Plugin Class
-- =====================================================================
local Plugin = {}
Plugin.__index = Plugin
-- Create a new plugin instance
function Plugin.new(spec)
spec = type(spec) == 'string' and { name = spec } or spec
-- Extract plugin name from repo
local name = fs.normalize(spec.name)
if vim.startswith(name, vim.env.HOME) then
spec.is_local = true
end
local parts = vim.split(name, '/', { trimempty = true })
local plugin_name = parts[#parts]:gsub('%.git$', '')
local self = setmetatable({
id = 0,
-- Basic properties
name = name, -- Full repo name (user/repo)
plugin_name = plugin_name, -- Just the repo part (for loading)
is_remote = not name:find(vim.env.HOME), -- Is it a remote or local plugin
is_local = spec.is_local or false, -- Development mode flag
is_lazy = spec.is_lazy or false, -- Whether to lazy load
local_path = nil, -- Local path to load
remote_branch = spec._branch, -- Git branch to use
-- States
status = STATUS.PENDING, -- Current plugin status
loaded = false, -- Is the plugin loaded
-- Loading options
events = {}, -- Events to trigger loading
filetypes = {}, -- Filetypes to trigger loading
commands = {}, -- Commands to trigger loading
mappings = {}, -- Keys to trigger loading
-- Configuration
setup_opts = spec.setup or {}, -- Options for plugin setup()
init_opts = spec.init, -- Options for before load plugin
config_opts = spec.config, -- Config function to run after loading
after_fn = spec.after, -- Function to run after dependencies load
colorscheme = spec.theme, -- Theme to apply if this is a colorscheme
-- Dependencies
dependencies = spec.depends or {}, -- Dependencies
user_commands = {}, -- Created user commands
run_action = spec.build or nil,
need_build = false,
}, Plugin)
return self
end
-- Get the plugin installation path
function Plugin:get_path()
return (not self.is_local and not self.local_path)
and joinpath(self.is_lazy and OPT_DIR or START_DIR, self.plugin_name)
or (joinpath(self.local_path, self.plugin_name) or self.name)
end
-- Check if plugin is installed (async version)
function Plugin:is_installed()
return Async.wrap(function(callback)
uv.fs_stat(self:get_path(), function(err, stat)
callback(not err and stat and stat.type == 'directory')
end)
end)()
end
-- Only string or function can be used for init and config opt
local function load_opts(opt)
return type(opt) == 'string' and vim.cmd(opt) or opt()
end
-- return a Promise
function Plugin:load_scripts()
return function(callback)
local plugin_path = self:get_path()
local plugin_dir = joinpath(plugin_path, 'plugin')
if not isdir(plugin_dir) then
callback(Result.success(false))
return
end
Async.scandir(plugin_dir)(function(result)
if not result.success or not result.value then
M.log('debug', string.format('Plugin directory not found: %s', plugin_dir))
callback(Result.success(false))
return
end
local scripts = {}
while true do
local name, type = uv.fs_scandir_next(result.value)
if not name then
break
end
if type == 'file' and (name:match('%.lua$') or name:match('%.vim$')) then
scripts[#scripts + 1] = joinpath(plugin_dir, name)
end
end
if #scripts > 0 then
Async.safe_schedule(function()
for _, file_path in ipairs(scripts) do
vim.cmd.source(vim.fn.fnameescape(file_path))
end
callback(Result.success(true))
end)
else
callback(Result.success(false))
end
end)
end
end
-- Load a plugin and its dependencies
function Plugin:load(do_action, callback)
if self.loaded then
return true
end
Async.async(function()
local plugin_path = self:get_path()
local stat = uv.fs_stat(plugin_path)
if not stat or stat.type ~= 'directory' then
self.status = STATUS.ERROR
return false
end
if self.init_opts then
load_opts(self.init_opts)
end
if self.is_local then
vim.opt.rtp:append(plugin_path)
local after_path = joinpath(plugin_path, 'after')
if isdir(after_path) then
vim.opt.rtp:append(after_path)
end
local result = Async.try_await(self:load_scripts())
if result.error then
M.log(
'error',
string.format('Failed to load scripts for %s: %s', self.name, tostring(result.error))
)
return
end
elseif self.is_lazy then
vim.cmd.packadd(self.plugin_name)
end
self.loaded = true
vim.g.strive_loaded = vim.g.strive_loaded + 1
self:call_setup()
self.status = STATUS.LOADED
if self.group_ids and #self.group_ids > 0 then
for _, id in ipairs(self.group_ids) do
api.nvim_del_augroup_by_id(id)
end
self.group_ids = {}
end
local deps_to_load = {}
for _, dep in ipairs(self.dependencies) do
if not dep.loaded then
table.insert(deps_to_load, dep)
end
end
if #deps_to_load > 0 then
local promises = {}
for _, dep in ipairs(deps_to_load) do
table.insert(promises, function(cb)
Async.async(function()
dep:load()
cb(Result.success(true))
end)()
end)
end
Async.await(Async.all(promises))
end
if self.config_opts then
load_opts(self.config_opts)
end
if do_action and self.run_action and self.loaded then
if type(self.run_action) == 'string' then
vim.cmd(self.run_action)
else
self.run_action()
end
end
if callback then
callback()
end
return true
end)()
return true
end
-- Set up lazy loading on specific events
function Plugin:on(events)
self.is_lazy = true
self.events = type(events) ~= 'table' and { events } or events
self.group_ids = self.group_id or {}
local id = api.nvim_create_augroup('strive_' .. self.plugin_name, { clear = true })
table.insert(self.group_ids, id)
-- Create autocmds for each event within this group
for _, event in ipairs(self.events) do
event = event == 'StriveDone' and 'User StriveDone' or event
local pattern
if event:find('%s') then
local t = vim.split(event, '%s')
event, pattern = t[1], t[2]
end
api.nvim_create_autocmd(event, {
group = id,
pattern = pattern,
once = true,
callback = function()
if not self.loaded then
self:load()
end
end,
})
end
return self
end
local function _split(s, sep)
local t = {}
for c in vim.gsplit(s, sep, { trimempty = true }) do
if #c > 0 then
table.insert(t, c)
end
end
return t
end
-- Set up lazy loading for specific filetypes
function Plugin:ft(filetypes)
self.is_lazy = true
self.filetypes = type(filetypes) ~= 'table' and { filetypes } or filetypes
self.group_ids = self.group_ids or {}
local id = api.nvim_create_augroup('strive_' .. self.plugin_name, { clear = true })
self.group_ids[#self.group_ids + 1] = id
api.nvim_create_autocmd('FileType', {
group = id,
pattern = self.filetypes,
once = true,
callback = function(args)
if not self.loaded then
return self:load(false, function()
local res = api.nvim_exec2('autocmd FileType', { output = true })
if not res.output then
return
end
res = { unpack(vim.split(res.output, '\n'), 1) }
local group_start = nil
for i, item in ipairs(res) do
if item:find('FileType$') then
group_start = i
end
if item:find(self.plugin_name, 1, true) then
local data = _split(item, '%s')
local g = res[group_start]:match('^(.-)%s+FileType$')
if g and (data[1] == '*' or data[1] == vim.bo[args.buf].filetype) then
api.nvim_exec_autocmds('FileType', {
group = g,
modeline = false,
buffer = args.buf,
data = args.data,
})
break
end
end
end
end)
end
end,
})
return self
end
-- Set up lazy loading for specific commands
function Plugin:cmd(commands)
self.is_lazy = true
self.commands = type(commands) == 'table' and commands or { commands }
-- Helper to execute a given command string
local function execute(name, bang, args)
if vim.fn.exists(':' .. name) ~= 2 then
return
end
local cmd_str = name .. (bang and '!' or '') .. (args or '')
---@diagnostic disable-next-line: param-type-mismatch
local ok, err = pcall(vim.cmd, cmd_str)
if not ok then
vim.notify(string.format('execute %s wrong: %s', name, err), vim.log.levels.ERROR)
end
end
for _, name in ipairs(self.commands) do
api.nvim_create_user_command(name, function(opts)
-- Remove this command to avoid recursion
pcall(api.nvim_del_user_command, name)
local args = opts.args ~= '' and (' ' .. opts.args) or ''
local bang = opts.bang
Async.async(function()
self:load()
if self.is_local then
Async.await(Async.delay(5))
end
Async.safe_schedule(function()
execute(name, bang, args)
end)
end)()
end, {
nargs = '*',
bang = true,
complete = function(_, cmd_line)
if not self.loaded then
self:load()
end
local ok, result = pcall(vim.fn.getcompletion, cmd_line, 'cmdline')
return ok and result or {}
end,
})
table.insert(self.user_commands, name)
end
return self
end
function Plugin:cond(condition)
self.is_lazy = true
if
(type(condition) == 'string' and api.nvim_eval(condition))
or (type(condition) == 'function' and condition())
then
self:load(true)
end
return self
end
-- Set up lazy loading for specific keymaps
function Plugin:keys(mappings)
self.is_lazy = true
self.mappings = type(mappings) ~= 'table' and { mappings } or mappings
for _, mapping in ipairs(self.mappings) do
local mode, lhs, rhs, opts
if type(mapping) == 'table' then
mode = mapping[1] or 'n'
lhs = mapping[2]
rhs = mapping[3]
opts = mapping[4] or {}
else
mode, lhs = 'n', mapping
opts = {}
end
-- Create a keymap that loads the plugin first
vim.keymap.set(mode, lhs, function()
if type(rhs) == 'function' then
self:load(nil, rhs)
elseif type(rhs) == 'string' then
self:load(nil, function()
vim.cmd(rhs)
end)
elseif type(rhs) == 'nil' then
-- If rhs not specified, it should be defined in plugin config
-- In this case, we need to pass a callback
self:load(nil, function()
vim.schedule(function()
vim.fn.feedkeys(lhs)
end)
end)
end
end, opts)
end
return self
end
-- Mark plugin as a development plugin
function Plugin:load_path(path)
path = path or vim.g.strive_dev_path
self.is_local = true
self.local_path = fs.normalize(path)
self.is_remote = false
return self
end
-- Set plugin configuration options
function Plugin:setup(opts)
self.setup_opts = opts
return self
end
function Plugin:init(opts)
self.init_opts = opts
return self
end