-- Disable banner
vim.g.netrw_banner = 0

-- Fix gx when running inside WSL
if vim.env.WSLENV then
  vim.g.netrw_browsex_viewer = 'cmd.exe /C start'
end

-- Map - key to open netrw in current files parent directory
vim.keymap.set('n', '-', function()
  -- Get the filename before invoking netrw
  local filename = vim.fn.expand('%:t')

  -- Invoke netrw on the directory containing the current file
  vim.fn.execute(string.format("edit %s", vim.fn.expand('%:hp')))

  -- In the netrw buffer, move the cursor to the first character of filename
  local buffer = vim.api.nvim_get_current_buf()
  local lines = vim.api.nvim_buf_get_lines(buffer, 0, -1, true)
  for row, content in ipairs(lines) do
    local column = string.find(content, filename)
    if column then
      vim.api.nvim_win_set_cursor(0, { row, column - 1 })
      break
    end
  end
end)