fix: proper ft detection with multiple file types in context (#1111)

This commit is contained in:
Fernando Freire 2025-01-21 19:59:38 -08:00 committed by GitHub
parent 15a471b155
commit eaf51492d4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -285,32 +285,27 @@ end
function FileSelector:get_selected_files_contents() function FileSelector:get_selected_files_contents()
local contents = {} local contents = {}
for _, file_path in ipairs(self.selected_filepaths) do for _, file_path in ipairs(self.selected_filepaths) do
--- lookup loaded buffer firstly --- Lookup if the file is loaded in a buffer
local bufnr = vim.fn.bufnr(file_path) local bufnr = vim.fn.bufnr(file_path)
if bufnr ~= -1 then if bufnr ~= -1 and vim.api.nvim_buf_is_loaded(bufnr) then
-- If buffer exists and is loaded, get buffer content
local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false) local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)
local content = table.concat(lines, "\n") local content = table.concat(lines, "\n")
local filetype = vim.api.nvim_get_option_value("filetype", { buf = bufnr }) local filetype = vim.api.nvim_get_option_value("filetype", { buf = bufnr })
table.insert(contents, { path = file_path, content = content, file_type = filetype }) table.insert(contents, { path = file_path, content = content, file_type = filetype })
goto continue else
end -- Fallback: read file from disk
local file, open_err = io.open(file_path, "r") local file, open_err = io.open(file_path, "r")
if open_err then Utils.debug("error reading file:", open_err) end
if file then if file then
local content, read_err = file:read("*all") local content = file:read("*all")
file:close() file:close()
-- Detect the file type using the specific file's content
if read_err then Utils.debug("failed to read:", file_path, read_err) end local filetype = vim.filetype.match({ filename = file_path, contents = { content } }) or "unknown"
-- Detect the file type
local filetype = vim.filetype.match({ filename = file_path, contents = contents }) or "unknown"
table.insert(contents, { path = file_path, content = content, file_type = filetype }) table.insert(contents, { path = file_path, content = content, file_type = filetype })
else
Utils.debug("error reading file:", open_err)
end
end end
::continue::
end end
return contents return contents
end end