-
Notifications
You must be signed in to change notification settings - Fork 194
Expand file tree
/
Copy pathinit.lua
More file actions
449 lines (382 loc) · 15.1 KB
/
init.lua
File metadata and controls
449 lines (382 loc) · 15.1 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
---@brief [[
--- Claude Code Neovim Integration
--- This plugin integrates Claude Code CLI with Neovim, enabling
--- seamless AI-assisted coding experiences directly in Neovim.
---@brief ]]
--- @module 'claudecode'
local M = {}
--- @class ClaudeCode.Version
--- @field major integer Major version number
--- @field minor integer Minor version number
--- @field patch integer Patch version number
--- @field prerelease string|nil Prerelease identifier (e.g., "alpha", "beta")
--- @field string fun(self: ClaudeCode.Version):string Returns the formatted version string
--- The current version of the plugin.
--- @type ClaudeCode.Version
M.version = {
major = 0,
minor = 1,
patch = 0,
prerelease = "alpha",
string = function(self)
local version = string.format("%d.%d.%d", self.major, self.minor, self.patch)
if self.prerelease then
version = version .. "-" .. self.prerelease
end
return version
end,
}
--- @class ClaudeCode.Config
--- @field port_range {min: integer, max: integer} Port range for WebSocket server.
--- @field auto_start boolean Auto-start WebSocket server on Neovim startup.
--- @field terminal_cmd string|nil Custom terminal command to use when launching Claude.
--- @field log_level "trace"|"debug"|"info"|"warn"|"error" Log level.
--- @field track_selection boolean Enable sending selection updates to Claude.
--- @field visual_demotion_delay_ms number Milliseconds to wait before demoting a visual selection.
--- @field diff_opts { auto_close_on_accept: boolean, show_diff_stats: boolean, vertical_split: boolean, open_in_current_tab: boolean } Options for the diff provider.
--- @type ClaudeCode.Config
local default_config = {
port_range = { min = 10000, max = 65535 },
auto_start = true,
terminal_cmd = nil,
log_level = "info",
track_selection = true,
visual_demotion_delay_ms = 200,
diff_opts = {
auto_close_on_accept = true,
show_diff_stats = true,
vertical_split = true,
open_in_current_tab = false,
},
}
--- @class ClaudeCode.State
--- @field config ClaudeCode.Config The current plugin configuration.
--- @field server table|nil The WebSocket server instance.
--- @field port number|nil The port the server is running on.
--- @field initialized boolean Whether the plugin has been initialized.
--- @type ClaudeCode.State
M.state = {
config = vim.deepcopy(default_config),
server = nil,
port = nil,
initialized = false,
}
---@alias ClaudeCode.TerminalOpts { \
--- split_side?: "left"|"right", \
--- split_width_percentage?: number, \
--- provider?: "snacks"|"native", \
--- show_native_term_exit_tip?: boolean }
---
---@alias ClaudeCode.SetupOpts { \
--- terminal?: ClaudeCode.TerminalOpts }
---
--- Set up the plugin with user configuration
---@param opts ClaudeCode.SetupOpts|nil Optional configuration table to override defaults.
---@return table The plugin module
function M.setup(opts)
opts = opts or {}
local terminal_opts = nil
if opts.terminal then
terminal_opts = opts.terminal
opts.terminal = nil -- Remove from main opts to avoid polluting M.state.config
end
local config = require("claudecode.config")
M.state.config = config.apply(opts)
-- vim.g.claudecode_user_config is no longer needed as config values are passed directly.
local logger = require("claudecode.logger")
logger.setup(M.state.config)
-- Setup terminal module: always try to call setup to pass terminal_cmd,
-- even if terminal_opts (for split_side etc.) are not provided.
local terminal_setup_ok, terminal_module = pcall(require, "claudecode.terminal")
if terminal_setup_ok then
-- terminal_opts might be nil if user only configured top-level terminal_cmd
-- and not specific terminal appearance options.
-- The terminal.setup function handles nil for its first argument.
terminal_module.setup(terminal_opts, M.state.config.terminal_cmd)
else
logger.error("init", "Failed to load claudecode.terminal module for setup.")
end
local diff = require("claudecode.diff")
diff.setup(M.state.config)
if M.state.config.auto_start then
M.start(false) -- Suppress notification on auto-start
end
M._create_commands()
vim.api.nvim_create_autocmd("VimLeavePre", {
group = vim.api.nvim_create_augroup("ClaudeCodeShutdown", { clear = true }),
callback = function()
if M.state.server then
M.stop()
end
end,
desc = "Automatically stop Claude Code integration when exiting Neovim",
})
M.state.initialized = true
return M
end
--- Start the Claude Code integration
---@param show_startup_notification? boolean Whether to show a notification upon successful startup (defaults to true)
---@return boolean success Whether the operation was successful
---@return number|string port_or_error The WebSocket port if successful, or error message if failed
function M.start(show_startup_notification)
if show_startup_notification == nil then
show_startup_notification = true
end
if M.state.server then
local msg = "Claude Code integration is already running on port " .. tostring(M.state.port)
vim.notify(msg, vim.log.levels.WARN)
return false, "Already running"
end
local server = require("claudecode.server.init")
local success, result = server.start(M.state.config)
if not success then
vim.notify("Failed to start Claude Code integration: " .. result, vim.log.levels.ERROR)
return false, result
end
M.state.server = server
M.state.port = tonumber(result)
local lockfile = require("claudecode.lockfile")
local lock_success, lock_result = lockfile.create(M.state.port)
if not lock_success then
server.stop()
M.state.server = nil
M.state.port = nil
vim.notify("Failed to create lock file: " .. lock_result, vim.log.levels.ERROR)
return false, lock_result
end
if M.state.config.track_selection then
local selection = require("claudecode.selection")
selection.enable(M.state.server, M.state.config.visual_demotion_delay_ms)
end
if show_startup_notification then
vim.notify("Claude Code integration started on port " .. tostring(M.state.port), vim.log.levels.INFO)
end
return true, M.state.port
end
--- Stop the Claude Code integration
---@return boolean success Whether the operation was successful
---@return string? error Error message if operation failed
function M.stop()
if not M.state.server then
vim.notify("Claude Code integration is not running", vim.log.levels.WARN)
return false, "Not running"
end
local lockfile = require("claudecode.lockfile")
local lock_success, lock_error = lockfile.remove(M.state.port)
if not lock_success then
vim.notify("Failed to remove lock file: " .. lock_error, vim.log.levels.WARN)
-- Continue with shutdown even if lock file removal fails
end
if M.state.config.track_selection then
local selection = require("claudecode.selection")
selection.disable()
end
local success, error = M.state.server.stop()
if not success then
vim.notify("Failed to stop Claude Code integration: " .. error, vim.log.levels.ERROR)
return false, error
end
M.state.server = nil
M.state.port = nil
vim.notify("Claude Code integration stopped", vim.log.levels.INFO)
return true
end
--- Set up user commands
---@private
function M._create_commands()
local logger = require("claudecode.logger")
vim.api.nvim_create_user_command("ClaudeCodeStart", function()
M.start()
end, {
desc = "Start Claude Code integration",
})
vim.api.nvim_create_user_command("ClaudeCodeStop", function()
M.stop()
end, {
desc = "Stop Claude Code integration",
})
vim.api.nvim_create_user_command("ClaudeCodeStatus", function()
if M.state.server and M.state.port then
vim.notify("Claude Code integration is running on port " .. tostring(M.state.port), vim.log.levels.INFO)
else
vim.notify("Claude Code integration is not running", vim.log.levels.INFO)
end
end, {
desc = "Show Claude Code integration status",
})
vim.api.nvim_create_user_command("ClaudeCodeSend", function(opts)
if not M.state.server then
logger.error("command", "ClaudeCodeSend: Claude Code integration is not running.")
vim.notify("Claude Code integration is not running", vim.log.levels.ERROR)
return
end
-- Check if we're in a tree buffer - if so, delegate to tree integration
local current_ft = vim.bo.filetype
local current_bufname = vim.api.nvim_buf_get_name(0)
logger.debug(
"command",
"ClaudeCodeSend: Buffer detection - filetype: '" .. current_ft .. "', bufname: '" .. current_bufname .. "'"
)
-- Check both filetype and buffer name for tree detection
local is_tree_buffer = current_ft == "NvimTree"
or current_ft == "neo-tree"
or string.match(current_bufname, "neo%-tree")
or string.match(current_bufname, "NvimTree")
if is_tree_buffer then
logger.debug("command", "ClaudeCodeSend: Detected tree buffer, delegating to tree integration")
local integrations = require("claudecode.integrations")
local files, error = integrations.get_selected_files_from_tree()
if error then
logger.warn("command", "ClaudeCodeSend->TreeAdd: " .. error)
return
end
if not files or #files == 0 then
logger.warn("command", "ClaudeCodeSend->TreeAdd: No files selected")
return
end
-- Send each file as an at_mention (full file, no line numbers)
local success_count = 0
for _, file_path in ipairs(files) do
local params = {
filePath = file_path,
lineStart = nil, -- No line numbers for full file
lineEnd = nil, -- No line numbers for full file
}
local broadcast_success = M.state.server.broadcast("at_mentioned", params)
if broadcast_success then
success_count = success_count + 1
logger.debug("command", "ClaudeCodeSend->TreeAdd: Added file " .. file_path)
else
logger.error("command", "ClaudeCodeSend->TreeAdd: Failed to add file " .. file_path)
end
end
if success_count > 0 then
local message = success_count == 1 and "Added 1 file to Claude context"
or string.format("Added %d files to Claude context", success_count)
logger.debug("command", message) -- Use debug level to avoid popup
else
logger.error("command", "ClaudeCodeSend->TreeAdd: Failed to add any files")
end
-- Exit visual mode if we were in it
vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("<Esc>", true, false, true), "n", false)
return
end
logger.debug(
"command",
"ClaudeCodeSend (new logic) invoked. Mode: "
.. vim.fn.mode(true)
.. ", Neovim's reported range: "
.. tostring(opts and opts.range)
)
-- We now ignore opts.range and rely on the selection module's state,
-- as opts.range was found to be 0 even when in visual mode for <cmd> mappings.
if not M.state.server then
logger.error("command", "ClaudeCodeSend: Claude Code integration is not running.")
return
end
local selection_module_ok, selection_module = pcall(require, "claudecode.selection")
if selection_module_ok then
local sent_successfully = selection_module.send_at_mention_for_visual_selection()
if sent_successfully then
vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("<Esc>", true, false, true), "n", false)
logger.debug("command", "ClaudeCodeSend: Exited visual mode after successful send.")
-- Focus the Claude Code terminal after sending selection
local terminal_ok, terminal = pcall(require, "claudecode.terminal")
if terminal_ok then
terminal.open({}) -- Open/focus the terminal
logger.debug("command", "ClaudeCodeSend: Focused Claude Code terminal after selection send.")
else
logger.warn("command", "ClaudeCodeSend: Failed to load terminal module for focusing.")
end
end
else
logger.error("command", "ClaudeCodeSend: Failed to load selection module.")
vim.notify("Failed to send selection: selection module not loaded.", vim.log.levels.ERROR)
end
end, {
desc = "Send current visual selection as an at_mention to Claude Code",
range = true, -- Important: This makes the command expect a range (visual selection)
})
vim.api.nvim_create_user_command("ClaudeCodeTreeAdd", function()
if not M.state.server then
logger.error("command", "ClaudeCodeTreeAdd: Claude Code integration is not running.")
return
end
local integrations = require("claudecode.integrations")
local files, error = integrations.get_selected_files_from_tree()
if error then
logger.warn("command", "ClaudeCodeTreeAdd: " .. error)
return
end
if not files or #files == 0 then
logger.warn("command", "ClaudeCodeTreeAdd: No files selected")
return
end
-- Send each file as an at_mention (full file, no line numbers)
local success_count = 0
for _, file_path in ipairs(files) do
local params = {
filePath = file_path,
lineStart = nil, -- No line numbers for full file
lineEnd = nil, -- No line numbers for full file
}
local broadcast_success = M.state.server.broadcast("at_mentioned", params)
if broadcast_success then
success_count = success_count + 1
logger.debug("command", "ClaudeCodeTreeAdd: Added file " .. file_path)
else
logger.error("command", "ClaudeCodeTreeAdd: Failed to add file " .. file_path)
end
end
if success_count > 0 then
local message = success_count == 1 and "Added 1 file to Claude context"
or string.format("Added %d files to Claude context", success_count)
logger.debug("command", message)
else
logger.error("command", "ClaudeCodeTreeAdd: Failed to add any files")
end
end, {
desc = "Add selected file(s) from tree explorer to Claude Code context",
})
local terminal_ok, terminal = pcall(require, "claudecode.terminal")
if terminal_ok then
vim.api.nvim_create_user_command("ClaudeCode", function(_opts)
local current_mode = vim.fn.mode()
if current_mode == "v" or current_mode == "V" or current_mode == "\22" then -- \22 is CTRL-V (blockwise visual mode)
vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("<Esc>", true, false, true), "n", false)
end
terminal.toggle({}) -- `opts.fargs` can be used for future enhancements.
end, {
nargs = "?",
desc = "Toggle the Claude Code terminal window",
})
vim.api.nvim_create_user_command("ClaudeCodeOpen", function(_opts)
terminal.open({})
end, {
nargs = "?",
desc = "Open the Claude Code terminal window",
})
vim.api.nvim_create_user_command("ClaudeCodeClose", function()
terminal.close()
end, {
desc = "Close the Claude Code terminal window",
})
else
logger.error(
"init",
"Terminal module not found. Terminal commands (ClaudeCode, ClaudeCodeOpen, ClaudeCodeClose) not registered."
)
end
end
--- Get version information
---@return table Version information
function M.get_version()
return {
version = M.version:string(),
major = M.version.major,
minor = M.version.minor,
patch = M.version.patch,
prerelease = M.version.prerelease,
}
end
return M