12

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?

thisisrandy
  • 2,660
  • 2
  • 12
  • 25

4 Answers4

16

old question, but I couldn't find the answer, so...
here it is; :lua print(vim.fn.getcwd())

ps; if you're using lsp, you may want to put it on on_attach; vim.api.nvim_set_current_dir(client.config.root_dir)

Rafael Quintela
  • 1,908
  • 2
  • 12
  • 14
1

:help cwd yields

uv.cwd()                                                              *uv.cwd()*

                Returns the current working directory.

                Returns: `string` or `fail`

whereby uv is vim.loop from the UV Library https://docs.libuv.org/

therefore:

:lua print(vim.loop.cwd())

Works in NVIM v0.8.3

Jonathan Komar
  • 2,678
  • 4
  • 32
  • 43
0

There is a function in the regular Vim API that can be used for this:

getcwd()
  • Unfortunately this won't work. Per the link in my question, the API is a way to talk to neovim from plugins or external processes. I am attempting to query the nvim cwd from an external process, so I need a way to ask its API for that information. – thisisrandy Dec 16 '19 at 20:46
0

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.

thisisrandy
  • 2,660
  • 2
  • 12
  • 25