-
-
Notifications
You must be signed in to change notification settings - Fork 406
Expand file tree
/
Copy pathinit.lua
More file actions
295 lines (263 loc) · 7.91 KB
/
init.lua
File metadata and controls
295 lines (263 loc) · 7.91 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
local api = vim.api
local M = {}
---Fire an event
---@param event string
---@param opts? table
function M.fire(event, opts)
opts = opts or {}
api.nvim_exec_autocmds("User", { pattern = "CodeCompanion" .. event, data = opts })
end
---Notify the user
---@param msg string
---@param level? number|string
---@return nil
function M.notify(msg, level)
level = level or vim.log.levels.INFO
return vim.notify(msg, level, {
title = "CodeCompanion",
})
end
---Make the first letter uppercase
---@param str string
---@return string
M.capitalize = function(str)
local result = str:gsub("^%l", string.upper)
return result
end
---Check if a table is an array
---@param t table
---@return boolean
M.is_array = function(t)
if type(t) ~= "table" then
return false
end
if vim.islist then
return vim.islist(t)
end
return vim.tbl_islist(t)
end
---@param table table
---@param value string
---@return boolean
M.contains = function(table, value)
for _, v in pairs(table) do
if v == value then
return true
end
end
return false
end
M._noop = function() end
---@param name string
---@return nil
M.set_dot_repeat = function(name)
vim.go.operatorfunc = "v:lua.require'codecompanion.utils'._noop"
vim.cmd.normal({ args = { "g@l" }, bang = true })
vim.go.operatorfunc = string.format("v:lua.require'codecompanion'.%s", name)
end
---Extract placeholder names from a string
---@param str string The string to search for placeholders
---@return table List of unique placeholder names found (e.g. {"diff", "selection"})
function M.extract_placeholders(str)
local placeholders = {}
local seen = {}
for placeholder in str:gmatch("%${([^}]+)}") do
if not seen[placeholder] then
seen[placeholder] = true
table.insert(placeholders, placeholder)
end
end
return placeholders
end
---Extract all placeholders from a prompts structure (recursively)
---@param prompts table|string The prompts structure to search
---@return table List of unique placeholder names found
function M.extract_all_placeholders(prompts)
local all_placeholders = {}
local seen = {}
local function extract_recursive(value)
if type(value) == "string" then
local found = M.extract_placeholders(value)
for _, placeholder in ipairs(found) do
if not seen[placeholder] then
seen[placeholder] = true
table.insert(all_placeholders, placeholder)
end
end
elseif type(value) == "table" then
for _, v in pairs(value) do
extract_recursive(v)
end
end
end
extract_recursive(prompts)
return all_placeholders
end
---Escape percent signs in a string for use as a gsub replacement value.
---In Lua's gsub, the replacement string treats %0-%9 as capture references
---and %% as a literal percent. This function doubles all percent signs so
---that the replacement is inserted verbatim.
---@param str string
---@return string
local function escape_gsub_replacement(str)
return (str:gsub("%%", "%%%%"))
end
---Replace any placeholders (e.g. ${placeholder}) in a string or table
---@param t table|string The content to process
---@param replacements table<string, string> Map of placeholder names to replacement values
---@return string|nil The replaced string if input was string, or nil if input was table (modified in place)
function M.replace_placeholders(t, replacements)
if type(t) == "string" then
for placeholder, replacement in pairs(replacements) do
t = t:gsub("%${" .. vim.pesc(placeholder) .. "}", escape_gsub_replacement(replacement))
end
return t
else
for key, value in pairs(t) do
if type(value) == "table" then
M.replace_placeholders(value, replacements)
elseif type(value) == "string" then
for placeholder, replacement in pairs(replacements) do
value = value:gsub("%${" .. vim.pesc(placeholder) .. "}", escape_gsub_replacement(replacement))
end
t[key] = value
end
end
end
end
---@param msg string
---@param vars table
---@param mapping table
---@return string
function M.replace_vars(msg, vars, mapping)
local replacements = {}
for _, var_name in ipairs(vars) do
-- Check if the variable exists in the mapping
if mapping[var_name] then
table.insert(replacements, mapping[var_name])
else
error("Variable '" .. var_name .. "' not found in the mapping.")
end
end
return string.format(msg, unpack(replacements))
end
---Safely get the filetype
---@param filetype string
---@return string
function M.safe_filetype(filetype)
if filetype == "C++" then
return "cpp"
end
return filetype
end
---Set an option in Neovim
---@param bufnr number
---@param opt string
---@param value any
function M.set_option(bufnr, opt, value)
if api.nvim_set_option_value then
return api.nvim_set_option_value(opt, value, {
buf = bufnr,
})
end
if api.nvim_buf_set_option then
return api.nvim_buf_set_option(bufnr, opt, value)
end
end
---Parse an ISO 8601 timestamp to a Unix timestamp
---@param iso string ISO 8601 timestamp (e.g. "2026-03-18T22:29:29.993Z")
---@return number|nil
function M.parse_iso8601(iso)
local pattern = "(%d+)-(%d+)-(%d+)T(%d+):(%d+):(%d+)"
local year, month, day, hour, min, sec = iso:match(pattern)
if not year then
return nil
end
local date = {
year = tonumber(year), --[[@as number]]
month = tonumber(month), --[[@as number]]
day = tonumber(day), --[[@as number]]
hour = tonumber(hour), --[[@as number]]
min = tonumber(min), --[[@as number]]
sec = tonumber(sec), --[[@as number]]
}
return os.time(date)
end
---Make a timestamp relative
---@param timestamp number Unix timestamp
---@return string Relative time string (e.g. "5m", "2h")
function M.make_relative(timestamp)
local now = os.time()
local diff = now - timestamp
if diff < 60 then
return diff .. "s"
elseif diff < 3600 then
return math.floor(diff / 60) .. "m"
elseif diff < 86400 then
return math.floor(diff / 3600) .. "h"
else
return math.floor(diff / 86400) .. "d"
end
end
---Add a callback to a set of callbacks
---@param callbacks table|nil The existing callbacks
---@param event string The event to add the callback to
---@param fn function The callback function
function M.callbacks_extend(callbacks, event, fn)
callbacks = callbacks or {}
local existing = callbacks[event]
if not existing then
callbacks[event] = fn
elseif type(existing) == "function" then
callbacks[event] = { existing, fn }
else
table.insert(existing, fn)
end
return callbacks
end
---Resolve a nested table value using a dot-separated path string
---@param tbl table The table to traverse
---@param path string The dot-separated path (e.g. "interactions.chat.tools.memory")
---@return any|nil The resolved value, or nil if the path doesn't exist
function M.resolve_nested_value(tbl, path)
local parts = vim.split(path, ".", { plain = true })
local resolved = tbl
for _, part in ipairs(parts) do
resolved = resolved[part]
if not resolved then
return nil
end
end
return resolved
end
---Convert a word to singular or plural form based on count
---@param count number The count to determine singular or plural
---@param word string The base word (singular form)
---@return string The word with "s" appended if count ~= 1, or the original word if inputs are invalid
function M.pluralize(count, word)
if type(count) ~= "number" or type(word) ~= "string" then
return word or "item"
end
return count == 1 and word or word .. "s"
end
---Deep copy a table, truncating any string values
---@param tbl table
---@param max_len? number
---@return table
function M.truncate(tbl, max_len)
if not max_len then
max_len = 255
end
local output = {}
for k, v in pairs(tbl) do
if type(v) == "table" then
output[k] = M.truncate(v, max_len)
elseif type(v) == "string" and #v > max_len then
output[k] = v:sub(1, max_len) .. "...[truncated]"
else
output[k] = v
end
end
return output
end
return M