0

I use Neotree on Neovim, and have mapped a key to open the file browser which is supposed to:

  • open the file browser pointing to the current file
  • if there is no filename, open the file browser at the current working dir.

It works well except in the case that the buffer has a filename, but that file does not exist, e.g. if you start nvim with the name of a file you intend to create but have not yet saved.

Here's my existing code:

local d = vim.fn.getreg('%')                                 
if (d == '') then d = vim.fn.getcwd(); end                                                          
vim.cmd("Neotree reveal_force_cwd " .. vim.fn.fnameescape(d))

In the failing case the % reg is not empty, but it has no file associated with it.

Is there a vim built-in that knows this? or a way to check for the existence of the file?

1
  • I think the Vim function is filereadable()
    – D. Ben Knoble
    Commented Sep 29, 2023 at 13:16

1 Answer 1

0

This seems to work

local d = vim.fn.getreg('%')                                 
if (d == '') then                                            
  d = vim.fn.getcwd();                                       
else                                                         
  local f = io.open(d, "r") -- Attempt to open the file
  if (f) then     
    f.close(f)              -- Close file if we opened it ok
  else
    d = vim.fn.getcwd()     -- Could not open file, use cwd
  end                                                        
end                                                          
vim.cmd("Neotree reveal_force_cwd " .. vim.fn.fnameescape(d))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.