Skip to content
4 changes: 2 additions & 2 deletions lua/claudecode/tools/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ Sources: [tools/init.lua:M.register_all], [tools/close_tab.lua:schema], [tools/o
- `openDiff` raises `-32602` when a required parameter is missing. Outside a non-main coroutine it raises `-32000` with `message = "Internal server error"` and `data = "openDiff must run in coroutine context"` [tools/open_diff.lua:handler]
- `openDiff` calls `diff.open_diff_blocking(old, new, contents, tab_name, client.id)`. Structured errors pass through. Other errors become `-32000` "Error opening blocking diff" [tools/open_diff.lua:handler]
- `openFile`, `checkDocumentDirty`, and `saveDocument` raise `-32602` when `filePath` is missing [tools/open_file.lua:handler]
- `openFile` raises `-32602` before it opens the file when `startLine` or `endLine` is not an integer, `startLine` is below 1 or past the last line, or `endLine` is below `startLine`. The last line comes from the file's loaded buffer when one exists, else from the file on disk. An `endLine` past the last line selects through the last line, and the answer names the lines it selected [tools/open_file.lua:handler]
- `openFile` raises `-32602` before it opens the file when `startLine` or `endLine` is given but is not an integer (`false` included), `startLine` is below 1 or past the last line, or `endLine` is below `startLine`. The last line comes from the loaded buffer that `:edit` would reuse, which `bufexists()` and `bufadd()` find by name or by the inode Neovim cached for it, so a symlink or hard link finds it. Without one it comes from the file on disk. An `endLine` past the last line selects through the last line, and the answer names the lines it selected [tools/open_file.lua:handler]
- `openFile` raises `-32000` with `message = "File operation error"` and `data = "File not found: <path>"` when the file is not readable. Its defaults are `preview=false`, `makeFrontmost=true`, and `selectToEndOfLine=false` [tools/open_file.lua:handler]
- `checkDocumentDirty` and `saveDocument` return a `success=false` JSON result (not an error) when the file has no open buffer [tools/save_document.lua:handler]
- `getDiagnostics` raises `-32000` when `vim.lsp`, `vim.diagnostic`, or `vim.diagnostic.get` is missing. It raises `-32001` "File not open" when no buffer exists for `uri` (`vim.fn.bufnr(path) == -1`). An unloaded buffer does not raise [tools/get_diagnostics.lua:handler]
Expand All @@ -54,7 +54,7 @@ Sources: [tools/init.lua:M.register_all], [tools/close_tab.lua:schema], [tools/o

## Side Effects

- `openFile` runs `edit` (or `pedit` for preview) in the main editor window. It can split or move windows when no suitable window exists, and it sets visual marks and the cursor for line or text ranges [tools/open_file.lua:handler]
- `openFile` runs `edit` (or `pedit` for preview) in the main editor window. It can split or move windows when no suitable window exists, and it sets visual marks and the cursor for line or text ranges. With 'selection' set to inclusive, a range that ends on an empty line also covers that line's line break. When `endText` is not found, it only places the cursor on the `startText` match [tools/open_file.lua:handler]
- `openDiff` opens a blocking diff through `claudecode.diff`. The response stays deferred until the user accepts or rejects the diff [tools/open_diff.lua:handler]. A diff that resolves before `openDiff` yields, for example from a `ClaudeCodeDiffOpened` handler, is answered at once [diff.lua:M.open_diff_blocking]
- `saveDocument` runs `write` in the matching buffer with `nvim_buf_call` [tools/save_document.lua:handler]
- `closeAllDiffTabs` calls `diff.close_all_diffs` and returns `CLOSED_<n>_DIFF_TABS` [tools/close_all_diff_tabs.lua:handler]
Expand Down
36 changes: 23 additions & 13 deletions lua/claudecode/tools/open_file.lua
Original file line number Diff line number Diff line change
Expand Up @@ -127,13 +127,16 @@ end

---Returns how many lines `file_path` will show once opened, counting at most `max` lines of the file on disk.
---A loaded buffer for the file can hold unsaved lines, and `:edit` shows that buffer, so its count wins.
---bufexists() and bufadd() find that buffer the way `:edit` does, by name or by the inode Neovim cached for it,
---so a symlink, a symlinked directory, or a hard link finds it. bufexists() comes first because bufadd()
---creates a buffer when none exists.
---@param file_path string Path of the file to open
---@param max integer Lines to read from disk at most
---@return integer count
local function line_count_before_open(file_path, max)
local full_path = vim.fn.fnamemodify(file_path, ":p")
for _, buf in ipairs(vim.api.nvim_list_bufs()) do
if vim.api.nvim_buf_is_loaded(buf) and vim.api.nvim_buf_get_name(buf) == full_path then
if vim.fn.bufexists(file_path) == 1 then
local buf = vim.fn.bufadd(file_path)
if vim.api.nvim_buf_is_loaded(buf) then
return vim.api.nvim_buf_line_count(buf)
end
end
Expand All @@ -151,9 +154,9 @@ local function handler(params)
end

local start_line, end_line
if params.startLine or params.endLine then
start_line = params.startLine or 1
end_line = params.endLine or start_line
if params.startLine ~= nil or params.endLine ~= nil then
start_line = params.startLine == nil and 1 or params.startLine
end_line = params.endLine == nil and start_line or params.endLine
local valid = type(start_line) == "number"
and type(end_line) == "number"
and start_line % 1 == 0
Expand Down Expand Up @@ -255,10 +258,13 @@ local function handler(params)
-- Handle text selection by line numbers
if start_line then
run_in_target_window(function()
-- endLine can run past the last line. The buffer can also be shorter than the count checked before
-- opening, when :edit reuses a buffer under another name for the same file, such as a symlink.
-- endLine can run past the last line. start_line is clamped too, so a buffer that ends up shorter
-- than the count checked before opening still gets a selection.
end_line = math.min(end_line, vim.api.nvim_buf_line_count(0))
start_line = math.min(start_line, end_line)
-- With 'selection' inclusive, a charwise selection that ends on an empty line also covers that line's
-- line break: gv selects the character under '>, and on an empty line that is the line break. Ending
-- on the line above instead would move '> and the selection Claude receives off endLine.
local end_line_text = vim.api.nvim_buf_get_lines(0, end_line - 1, end_line, false)[1]
select_range(start_line, 0, end_line, math.max(#end_line_text - 1, 0))

Expand Down Expand Up @@ -306,9 +312,6 @@ local function handler(params)
if end_line_idx then
message = 'Opened file and selected text from "' .. start_text .. '" to "' .. end_text .. '"'
else
-- End text not found, select only start text
end_line_idx = start_line_idx
end_col_idx = start_col_idx + string.len(start_text) - 1
message = 'Opened file and positioned at "' .. start_text .. '" (end text "' .. end_text .. '" not found)'
end
else
Expand All @@ -318,9 +321,16 @@ local function handler(params)
message = 'Opened file and selected text "' .. start_text .. '"'
end

-- Apply the selection
-- A line range earlier in this call can leave Visual or Select mode on. Moving the cursor in it would
-- stretch that selection, and keys typed in Select mode replace the selected text.
if vim.api.nvim_get_mode().mode:match("^[vVsS\22\19]") then
vim.cmd("normal! \27")
end
vim.api.nvim_win_set_cursor(0, { start_line_idx, start_col_idx })
select_range(start_line_idx, start_col_idx, end_line_idx, end_col_idx)
-- When endText is not found, only the cursor moves, as in the VS Code extension.
if end_line_idx then
select_range(start_line_idx, start_col_idx, end_line_idx, end_col_idx)
end
vim.cmd("normal! zz") -- Center the selection in the window
else
message = 'Opened file, but text "' .. start_text .. '" not found'
Expand Down
82 changes: 68 additions & 14 deletions tests/unit/tools/open_file_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@ describe("Tool: open_file", function()
local buffer_lines
local marks
local coladds
local loaded_bufs
local original_list_bufs
local original_buf_is_loaded
local edit_buffers
local cursor
local editor_mode
local gv_mode
local original_get_mode

before_each(function()
-- Reset mocks and require the module under test
Expand All @@ -31,8 +34,20 @@ describe("Tool: open_file", function()
_G.vim.fn.fnameescape = spy.new(function(path)
return path -- Simple pass-through
end)
-- Like Neovim, gv enters Visual mode (Select mode when 'selectmode' has "cmd"), and :edit or <Esc> ends it.
editor_mode = "n"
gv_mode = "v"
_G.vim.cmd = spy.new(function(command)
table.insert(_G.vim.cmd_history, command)
if command == "normal! gv" then
editor_mode = gv_mode
elseif command == "normal! \27" or command:match("^p?edit ") then
editor_mode = "n"
end
end)
original_get_mode = _G.vim.api.nvim_get_mode
_G.vim.api.nvim_get_mode = spy.new(function()
return { mode = editor_mode, blocking = false }
end)

-- Mock vim.json.encode
Expand Down Expand Up @@ -101,15 +116,18 @@ describe("Tool: open_file", function()
coladds[expr:sub(2)] = pos[4]
return 0
end)
loaded_bufs = {}
original_list_bufs = _G.vim.api.nvim_list_bufs
original_buf_is_loaded = _G.vim.api.nvim_buf_is_loaded
_G.vim.api.nvim_list_bufs = spy.new(function()
return loaded_bufs
end)
_G.vim.api.nvim_buf_is_loaded = spy.new(function(buf)
return true
end)
-- bufexists() and bufadd() find the buffer that :edit would reuse for a path, by name or cached inode.
edit_buffers = {}
_G.vim.fn.bufexists = spy.new(function(path)
return edit_buffers[path] and 1 or 0
end)
_G.vim.fn.bufadd = spy.new(function(path)
return assert(edit_buffers[path], "bufadd would create a buffer for " .. path)
end)
_G.vim.fn.readfile = spy.new(function(path, flags, max)
local read = {}
for line_nr = 1, math.min(max or #buffer_lines, #buffer_lines) do
Expand All @@ -127,10 +145,12 @@ describe("Tool: open_file", function()
end
return slice
end)
cursor = nil
_G.vim.api.nvim_win_set_cursor = spy.new(function(win, pos)
if pos[1] < 1 or pos[1] > #buffer_lines then
error("Invalid cursor line: out of range")
end
cursor = { pos[1], pos[2] }
end)
_G.vim.o = _G.vim.o or {}
_G.vim.o.selection = "inclusive"
Expand All @@ -145,8 +165,10 @@ describe("Tool: open_file", function()
_G.vim.cmd_history = nil
_G.vim.fn.setpos = nil
_G.vim.fn.readfile = nil
_G.vim.api.nvim_list_bufs = original_list_bufs
_G.vim.fn.bufexists = nil
_G.vim.fn.bufadd = nil
_G.vim.api.nvim_buf_is_loaded = original_buf_is_loaded
_G.vim.api.nvim_get_mode = original_get_mode
_G.vim.o.selection = nil
end)

Expand Down Expand Up @@ -378,8 +400,11 @@ describe("Tool: open_file", function()
expect(_G.vim.cmd_history[#_G.vim.cmd_history]).to_be("normal! gv")
end)

it("rejects a line below 1, a fractional line, or endLine below startLine before opening the file", function()
it("rejects a line below 1, a fractional or false line, or endLine below startLine before opening", function()
for _, lines in ipairs({
{ startLine = false },
{ startLine = false, endLine = 3 },
{ startLine = 2, endLine = false },
{ startLine = 0 },
{ startLine = 2, endLine = 0 },
{ startLine = 1.5 },
Expand Down Expand Up @@ -409,13 +434,29 @@ describe("Tool: open_file", function()
end)

it("accepts a startLine that exists only in the unsaved lines of the loaded buffer", function()
loaded_bufs = { 1 }
edit_buffers["test.txt"] = 1
_G.vim.fn.readfile = spy.new(function(path, flags, max)
return { "one", "two" }
end)
expect(open({ startLine = 4, endLine = 5 })).to_be("Opened file and selected lines 4 to 5")
end)

it("uses the file on disk when :edit would not reuse a loaded buffer", function()
-- For example a buffer loaded through a symlink that was retargeted since: Neovim keeps the old inode.
_G.vim.fn.readfile = spy.new(function(path, flags, max)
return { "one", "two" }
end)
local success, err = pcall(open_file_handler, { filePath = "test.txt", startLine = 4 })
expect(success).to_be_false()
expect(err.code).to_be(-32602)
end)

it("keeps the end mark on an empty endLine", function()
buffer_lines = { "abc", "", "xyz" }
expect(open({ startLine = 1, endLine = 2 })).to_be("Opened file and selected lines 1 to 2")
assert.are.same({ 2, 0 }, marks[">"])
end)

it("sets both marks with no column offset on every path", function()
for _, params in ipairs({
{ startLine = 3, endLine = 4 },
Expand Down Expand Up @@ -475,16 +516,29 @@ describe("Tool: open_file", function()
assert.are.same({ 3, 5 }, marks[">"])
end)

it("only places the cursor when one call selects lines and then misses endText", function()
for _, mode in ipairs({ "v", "s" }) do
gv_mode = mode
local text = open({ startLine = 3, endLine = 4, startText = "two", endText = "zzz" })
assert_contains(text, 'Opened file and positioned at "two"')
expect(editor_mode).to_be("n")
assert.are.same({ 2, 0 }, cursor)
end
end)

it("selects only the startText match when there is no endText", function()
expect(open({ startText = "three" })).to_be('Opened file and selected text "three"')
assert.are.same({ 3, 0 }, marks["<"])
assert.are.same({ 3, 4 }, marks[">"])
end)

it("selects the startText match when endText is not found", function()
assert_contains(open({ startText = "two", endText = "zzz" }), 'end text "zzz" not found')
assert.are.same({ 2, 0 }, marks["<"])
assert.are.same({ 2, 2 }, marks[">"])
it("puts the cursor on the startText match without a selection when endText is not found", function()
assert_contains(open({ startText = "two", endText = "zzz" }), 'Opened file and positioned at "two"')
assert.are.same({ 2, 0 }, cursor)
assert.are.same({}, marks)
for _, command in ipairs(_G.vim.cmd_history) do
expect(command == "normal! gv").to_be_false()
end
end)
end)

Expand Down
Loading