Search code examples
neovim

How to query neovim API for the current working directory?


The neovim API provides nvim_set_current_dir(), but apparently does not expose a way to query cwd. How can I go about doing this?


Solution

  • It turns out that user12542635's answer is kind of correct, but it doesn't put the answer in the proper context of a python plugin, so I'll do so here. I suspect Rafael Quintela's answer is also correct, but I don't have a lua test environment set up, so I'll leave that to others to assess.

    In the context of an nvim python remote plugin, the following code will execute pwd in the nvim process, gather its result, and return it to the plugin process, where we can then instruct the nvim process to echo it:

    import pynvim
    from pynvim.api.nvim import Nvim
    from typing import List
    
    @pynvim.plugin
    class CwdPrinter:
        def __init__(self, vim: Nvim) -> None:
            self.vim = vim
    
        @pynvim.function("PrintCwd")
        def print_cwd(self, args: List) -> None:
            cwd = self.vim.command_output("pwd")
            self.vim.command(f"echo 'cwd: {cwd}'")
    

    PrintCwd could then be called from nvim as :call PrintCwd(). This is obviously contrived; if one needed to print the current working directory, one should of course simply type :pwd, but it illustrates generally how to invoke remote vim commands in a plugin.