-
-
Notifications
You must be signed in to change notification settings - Fork 406
Expand file tree
/
Copy pathinit.lua
More file actions
651 lines (563 loc) · 17.5 KB
/
init.lua
File metadata and controls
651 lines (563 loc) · 17.5 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
local async = require("plenary.async")
local completion = require("codecompanion.providers.completion")
local config = require("codecompanion.config")
local ts = require("codecompanion.utils.treesitter")
local ui_utils = require("codecompanion.utils.ui")
local utils = require("codecompanion.utils")
local api = vim.api
local M = {}
-- CHAT MAPPINGS --------------------------------------------------------------
local _cached_options = {}
M.options = {
callback = function()
local float_opts = {
filetype = "codecompanion",
lock = true,
style = "minimal",
title = "Options",
window = config.display.chat.window,
}
if next(_cached_options) ~= nil then
return ui_utils.create_float(_cached_options, float_opts)
end
local lines = {}
local indent = " "
local function max(col, tbl)
local max_length = 0
for key, val in pairs(tbl) do
if val.hide then
goto continue
end
local get_length = (col == "key") and key or val[col]
local length = #get_length
if length > max_length then
max_length = length
end
::continue::
end
return max_length
end
local function pad(str, max_length, offset)
return str .. string.rep(" ", max_length - #str + (offset or 0))
end
--- Cleans and truncates a string to a maximum width.
---@param desc string? The description to clean
---@param max_width number? The maximum width to truncate the description to
---@return string The cleaned and truncated description
local function clean_and_truncate(desc, max_width)
if not desc then
return ""
end
desc = vim.trim(tostring(desc):gsub("\n", " "))
if max_width and #desc > max_width then
return desc:sub(1, max_width - 3) .. "..."
end
return desc
end
local function sorted_pairs(tbl, comp)
local keys = {}
for k in pairs(tbl) do
table.insert(keys, k)
end
table.sort(keys, comp)
local i = 0
return function()
i = i + 1
local key = keys[i]
if key ~= nil then
return key, tbl[key]
end
end
end
-- Filter out private keymaps
local keymaps = {}
for k, v in pairs(config.interactions.chat.keymaps) do
if k:sub(1, 1) ~= "_" then
keymaps[k] = v
end
end
-- Workout the column spacing
local keymaps_max = max("description", keymaps)
local vars = {}
vim.iter(config.interactions.chat.variables):each(function(key, val)
if not val.hide_in_help_window then
vars[key] = val
end
end)
local vars_max = max("key", vars)
local tools = {}
-- Add tools
vim
.iter(config.interactions.chat.tools)
:filter(function(name)
return name ~= "opts" and name ~= "groups"
end)
:each(function(tool)
local tool_conf = config.interactions.chat.tools[tool]
if not tool_conf.hide_in_help_window then
tools[tool] = {
description = tool_conf.description,
}
end
end)
-- Add groups
vim.iter(config.interactions.chat.tools.groups):each(function(tool)
local group_conf = config.interactions.chat.tools.groups[tool]
if not group_conf.hide_in_help_window then
tools[tool] = {
description = group_conf.description,
}
end
end)
local tools_max = max("key", tools)
local max_length = math.max(keymaps_max, vars_max, tools_max)
-- Keymaps
table.insert(lines, "### Keymaps")
local function compare_keymaps(a, b)
return (keymaps[a].description or "") < (keymaps[b].description or "")
end
for _, map in sorted_pairs(keymaps, compare_keymaps) do
if type(map.condition) == "function" and not map.condition() then
goto continue
end
if not map.hide then
local modes = {
n = "Normal",
i = "Insert",
}
local output = {}
for mode, key in pairs(map.modes) do
if type(key) == "table" then
local keys = {}
for _, v in ipairs(key) do
table.insert(keys, "`" .. v .. "`")
end
key = table.concat(key, "|")
table.insert(output, "`" .. key .. "` in " .. modes[mode] .. " mode")
else
table.insert(output, "`" .. key .. "` in " .. modes[mode] .. " mode")
end
end
local output_str = table.concat(output, " and ")
table.insert(lines, indent .. pad("_" .. map.description .. "_", max_length, 4) .. " " .. output_str)
end
::continue::
end
-- Variables
table.insert(lines, "")
table.insert(lines, "### Variables")
for key, val in sorted_pairs(vars) do
local desc = clean_and_truncate(val.description)
table.insert(lines, indent .. pad("#{" .. key .. "}", max_length, 4) .. " " .. desc)
end
-- Tools
table.insert(lines, "")
table.insert(lines, "### Tools")
for key, val in sorted_pairs(tools) do
if key ~= "opts" then
local desc = clean_and_truncate(val.description)
table.insert(lines, indent .. pad("@{" .. key .. "}", max_length, 4) .. " " .. desc)
end
end
_cached_options = lines
ui_utils.create_float(lines, float_opts)
end,
}
-- Native completion
M.completion = {
callback = function(chat)
local function complete_items(callback)
async.run(function()
local slash_cmds = completion.slash_commands()
local tools = completion.tools()
local vars = completion.variables()
local items = {}
if type(slash_cmds[1]) == "table" then
vim.list_extend(items, slash_cmds)
end
if type(tools[1]) == "table" then
vim.list_extend(items, tools)
end
if type(vars[1]) == "table" then
vim.list_extend(items, vars)
end
-- Process each item to match the completion format
for _, item in ipairs(items) do
if item.label then
-- Add bracket wrapping for variables and tools like cmp/blink do
if item.type == "variable" then
item.word = string.format("#{%s}", item.label:sub(2))
elseif item.type == "tool" then
item.word = string.format("@{%s}", item.label:sub(2))
else
item.word = item.label
end
item.abbr = item.label:sub(2)
item.menu = item.description or item.detail
item.icase = 1
item.dup = 0
item.empty = 0
item.user_data = {
command = item.label:sub(2),
label = item.label,
type = item.type,
config = item.config,
from_prompt_library = item.from_prompt_library,
}
end
end
vim.schedule(function()
callback(items)
end)
end)
end
local function trigger_complete()
local line = vim.api.nvim_get_current_line()
local cursor = vim.api.nvim_win_get_cursor(0)
local col = cursor[2]
if col == 0 or #line == 0 then
return
end
local before_cursor = line:sub(1, col)
local find_current_word = string.find(before_cursor, "%s[^%s]*$")
local start = find_current_word or 0
local prefix = line:sub(start + 1, col)
if not prefix then
return
end
complete_items(function(items)
vim.fn.complete(
start + 1,
vim.tbl_filter(function(item)
return vim.startswith(item.label:lower(), prefix:lower())
end, items)
)
end)
end
trigger_complete()
end,
}
M.send = {
callback = function(chat)
chat:submit()
end,
}
M.regenerate = {
callback = function(chat)
chat:regenerate()
end,
}
M.close = {
callback = function(chat)
chat:close()
local chats = require("codecompanion").buf_get_chat()
if vim.tbl_count(chats) == 0 then
return
end
local window_opts = chat.ui.window_opts or { default = true }
chats[1].chat.ui:open({ window_opts = window_opts })
end,
}
M.stop = {
callback = function(chat)
if chat.current_request or chat.tool_orchestrator then
chat:stop()
end
end,
}
M.clear = {
callback = function(chat)
chat:clear()
end,
}
M.codeblock = {
desc = "Insert a codeblock",
callback = function(chat)
local bufnr = api.nvim_get_current_buf()
local cursor_pos = api.nvim_win_get_cursor(0)
local line = cursor_pos[1]
local ft = chat.buffer_context.filetype or ""
local codeblock = {
"````" .. ft,
"",
"````",
}
api.nvim_buf_set_lines(bufnr, line - 1, line, false, codeblock)
api.nvim_win_set_cursor(0, { line + 1, vim.fn.indent(line) })
end,
}
---@param node TSNode to yank text from
local function yank_node(node)
local start_row, start_col, end_row, end_col = node:range()
local cursor_position = vim.fn.getcurpos()
-- Create marks for the node range
local ok, _ = pcall(function()
vim.api.nvim_buf_set_mark(0, "[", start_row + 1, start_col, {})
vim.api.nvim_buf_set_mark(0, "]", end_row + 1, end_col - 1, {})
end)
if not ok then
return utils.notify("Failed to copy code block", vim.log.levels.WARN)
end
-- Yank using marks
vim.cmd(string.format('normal! `["%sy`]', config.interactions.chat.opts.register))
-- Restore position after delay
vim.defer_fn(function()
vim.fn.setpos(".", cursor_position)
end, config.interactions.chat.opts.yank_jump_delay_ms)
end
M.yank_code = {
desc = "Yank focused or the last codeblock",
callback = function(chat)
local node = chat:get_codeblock()
if node ~= nil then
yank_node(node)
end
end,
}
M.buffer_sync_all = {
desc = "Sync the buffer to share all of its content",
callback = function(chat)
local current_line = vim.api.nvim_win_get_cursor(0)[1]
local line = vim.api.nvim_buf_get_lines(chat.bufnr, current_line - 1, current_line, true)[1]
if not vim.startswith(line, "> - ") then
return
end
local icon = config.display.chat.icons.buffer_sync_all
local id = line:gsub("^> %- ", "")
if not chat.context:can_be_synced__all(id) then
return utils.notify("This context type cannot be sync'd", vim.log.levels.WARN)
end
local filename = id
local state = "unsynced"
if line:find(icon) then
state = "synced"
filename = filename:gsub(icon, "")
id = filename
end
-- Update the UI
local new_line = (state == "synced") and string.format("> - %s", filename)
or string.format("> - %s%s", icon, filename)
api.nvim_buf_set_lines(chat.bufnr, current_line - 1, current_line, true, { new_line })
-- Update the context items on the chat buffer
for _, item in ipairs(chat.context_items) do
if item.id == id then
item.opts.synced = not item.opts.synced
break
end
end
end,
}
M.buffer_sync_diff = {
desc = "Sync the buffer to share it's diffs",
callback = function(chat)
local current_line = vim.api.nvim_win_get_cursor(0)[1]
local line = vim.api.nvim_buf_get_lines(chat.bufnr, current_line - 1, current_line, true)[1]
if not vim.startswith(line, "> - ") then
return
end
local id = line:gsub("^> %- ", "")
if not chat.context:can_be_synced__diff(id) then
return utils.notify("This context type cannot be sync'd", vim.log.levels.WARN)
end
-- Find the context and toggle diff state
local icons = config.display.chat.icons
for _, item in ipairs(chat.context_items) do
local clean_id = id:gsub(icons.buffer_sync_all, ""):gsub(icons.buffer_sync_diff, "")
if item.id == clean_id then
if not item.opts then
item.opts = {}
end
item.opts.sync_diff = not item.opts.sync_diff
-- Update the UI for just this line
local new_line
if item.opts.sync_diff then
-- Check if buffer is still valid before syncing
if vim.api.nvim_buf_is_valid(item.bufnr) and vim.api.nvim_buf_is_loaded(item.bufnr) then
chat.buffer_diffs:sync(item.bufnr)
new_line = string.format("> - %s%s", icons.buffer_sync_diff, clean_id)
else
-- Buffer is invalid, can't sync with it
item.opts.sync_diff = false
new_line = string.format("> - %s", clean_id)
utils.notify("Cannot sync - Invalid or unloaded buffer " .. item.id, vim.log.levels.WARN)
end
else
chat.buffer_diffs:unsync(item.bufnr)
new_line = string.format("> - %s", clean_id)
end
-- Update only the current line
vim.api.nvim_buf_set_lines(chat.bufnr, current_line - 1, current_line, true, { new_line })
break
end
end
end,
}
---@param chat CodeCompanion.Chat
---@param direction number
local function move_buffer(chat, direction)
local bufs = _G.codecompanion_buffers
local len = #bufs
local next_buf = vim
.iter(bufs)
:enumerate()
:filter(function(_, v)
return v == chat.bufnr
end)
:map(function(i, _)
return direction > 0 and bufs[(i % len) + 1] or bufs[((i - 2 + len) % len) + 1]
end)
:next()
local codecompanion = require("codecompanion")
local prev_ui = codecompanion.buf_get_chat(chat.bufnr).ui
prev_ui:hide()
local window_opts = prev_ui.window_opts or { default = true }
codecompanion.buf_get_chat(next_buf).ui:open({ window_opts = window_opts })
end
M.next_chat = {
desc = "Move to the next chat",
callback = function(chat)
if vim.tbl_count(_G.codecompanion_buffers) == 1 then
return
end
move_buffer(chat, 1)
end,
}
M.previous_chat = {
desc = "Move to the previous chat",
callback = function(chat)
if vim.tbl_count(_G.codecompanion_buffers) == 1 then
return
end
move_buffer(chat, -1)
end,
}
M.next_header = {
desc = "Go to the next message",
callback = function()
ts.goto_heading("next", 1)
end,
}
M.previous_header = {
desc = "Go to the previous message",
callback = function()
ts.goto_heading("prev", 1)
end,
}
M.change_adapter = {
desc = "Change the adapter",
callback = function(chat)
return require("codecompanion.interactions.chat.keymaps.change_adapter").callback(chat)
end,
}
M.fold_code = {
callback = function(chat)
chat.ui:fold_code()
end,
}
M.debug = {
desc = "Show debug information for the current chat",
callback = function(chat)
local settings, messages = chat:debug()
if not settings and not messages then
return
end
return require("codecompanion.interactions.chat.debug")
.new({
chat = chat,
settings = settings,
})
:render()
end,
}
M.toggle_system_prompt = {
desc = "Toggle the system prompt",
callback = function(chat)
chat:toggle_system_prompt()
end,
}
M.clear_rules = {
desc = "Clear rules",
callback = function(chat)
chat:remove_tagged_message("rules")
chat:refresh_context()
return utils.notify("Cleared the rules", vim.log.levels.INFO)
end,
}
M.clear_approvals = {
desc = "Clear approvals in the current buffer",
callback = function(chat)
local approvals = require("codecompanion.interactions.chat.tools.approvals")
approvals:reset(chat.bufnr)
return utils.notify("Cleared the approvals", vim.log.levels.INFO)
end,
}
M.yolo_mode = {
desc = "Toggle YOLO mode",
callback = function(chat)
local approvals = require("codecompanion.interactions.chat.tools.approvals")
local status = approvals:toggle_yolo_mode(chat.bufnr)
if status then
return utils.notify("YOLO mode enabled!", vim.log.levels.INFO)
end
return utils.notify("YOLO mode disabled!", vim.log.levels.INFO)
end,
}
M.goto_file_under_cursor = {
desc = "Open the file under cursor in a new tab.",
---@param chat CodeCompanion.Chat
callback = function(chat)
local file_name
if vim.fn.mode() == "n" then
file_name = vim.fn.expand("<cfile>")
elseif string.lower(vim.fn.mode()):find("^.?v%a?") then
-- one of the visual selection modes
local start_pos = vim.fn.getpos("v")
local end_pos = vim.fn.getpos(".")
if start_pos[1] > end_pos[1] or (start_pos[1] == end_pos[1] and start_pos[2] > end_pos[2]) then
start_pos, end_pos = end_pos, start_pos
end
local lines =
vim.api.nvim_buf_get_text(chat.bufnr, start_pos[2] - 1, start_pos[3] - 1, end_pos[2] - 1, end_pos[3], {})
if lines then
file_name = table.concat(lines)
end
end
if type(file_name) == "string" then
file_name = vim.fs.normalize(file_name)
else
return
end
local stat = vim.uv.fs_stat(file_name)
if stat == nil or stat.type ~= "file" then
return
end
local action = nil
local user_action = config.interactions.chat.opts.goto_file_action
if type(user_action) == "string" then
action = function(fname)
vim.cmd(user_action .. " " .. fname)
end
elseif type(user_action) == "function" then
action = user_action
else
error(string.format("%s is not a valid jump action!", vim.inspect(user_action)))
end
action(file_name)
end,
}
M.copilot_stats = {
desc = "Show Copilot usage statistics",
callback = function(chat)
if not chat.adapter.show_copilot_stats then
return utils.notify("Stats are only available when using the Copilot adapter", vim.log.levels.WARN)
end
chat.adapter.show_copilot_stats()
end,
}
M.super_diff = {
desc = "Show super diff buffer",
callback = function(chat)
require("codecompanion.interactions.chat.super_diff").show_super_diff(chat)
end,
}
return M