-- Disable banner
vim.g.netrw_banner = 0

-- 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')))

  -- Move the cursor to the line matching file
  local netrw_liststyle = vim.api.nvim_buf_get_var(
      vim.api.nvim_get_current_buf(), 'netrw_liststyle')
  local pattern = nil
  -- TODO: Replace this with something simpler, perhaps a loop over the netrw
  -- buffer lines to get the line number containing the filename string.
  if netrw_liststyle and netrw_liststyle == 2 then
    -- tpope's magic pattern for list style with multiple files in columns
    pattern = '\\%(^\\|\\s\\+\\)\zs'
      .. vim.fn.escape(filename .. '.*[]~\\')
      .. '[/*|@=]\\=\\%($\\|\\s\\+\\)'
  else
    -- tpope's magic pattern for all other list styles
    pattern = '^\\%(| \\)*'
      .. vim.fn.escape(filename, '.*[]~\\')
      .. '[/*|@=]\\=\\%($\\|\\t\\)'
  end
  vim.fn.search(pattern, 'wc')
end)