Fix netrw - mapping when in a buffer with no name/file

This commit is contained in:
Kenneth Benzie 2024-03-14 23:57:41 +00:00
parent 6c0c906cb2
commit 6533a96ba0

View File

@ -10,18 +10,25 @@ end
vim.keymap.set('n', '-', function() vim.keymap.set('n', '-', function()
-- Get the filename before invoking netrw -- Get the filename before invoking netrw
local filename = vim.fn.expand('%:t') local filename = vim.fn.expand('%:t')
local directory = vim.fn.expand('%:hp')
if directory == '' then
directory = vim.fn.getcwd()
end
-- Invoke netrw on the directory containing the current file -- Invoke netrw on the directory containing the current file
vim.fn.execute(string.format("edit %s", vim.fn.expand('%:hp'))) vim.fn.execute(string.format("edit %s", directory))
-- In the netrw buffer, move the cursor to the first character of filename if filename ~= '' then
local buffer = vim.api.nvim_get_current_buf() -- In the netrw buffer, move the cursor to the first character of filename
local lines = vim.api.nvim_buf_get_lines(buffer, 0, -1, true) local buffer = vim.api.nvim_get_current_buf()
for row, content in ipairs(lines) do local lines = vim.api.nvim_buf_get_lines(buffer, 0, -1, true)
local column = string.find(content, filename) for row, content in ipairs(lines) do
if column then local column = string.find(content, filename)
vim.api.nvim_win_set_cursor(0, { row, column - 1 }) if column then
break vim.api.nvim_win_set_cursor(0, { row, column - 1 })
break
end
end end
end end
end) end)