How to write a file that is not the active buffer?

My problem is that I have a tree plugin with a rename function, and when I do that rename on the filesystem I am also renaming any open buffers using vim.api.nvim_buf_set_name. When it is renamed in this way, the next time the user tries to write the file they get E13 and have to add ! to force it. I would like to prevent this.

My preferred solution is to just force write the file right after renaming it if it is not currently modified. Unfortunately, I can’t find any way of doing this in lua. Does it exist? If it doesn’t, is there a way to write a file using vim.cmd without it being the currently focused buffer?

Thanks for any insight you can offer.

I finally found the answer myself, which is to use vim.api.nvim_buf_call to execute a vim.cmd in the context of a particular buffer. It feels a little hacky but it works.

I didn’t notice this function at first because it wasn’t included in my LSP completions.

you could get that buffer id and pipe something you’d like to to it.