使用 Nvim 远程 coding
有时我们需要修改远程机器上的文件。然而目标机器可能没有配置好的编辑工具,甚至连 Vim 都没有安装。这种情况下,如果可以直接用本地配置好的 Nvim 来远程修改文件,将得心应手。
安装 distant | 也可通过 nvim 插件安装(下文提及)
curl -L https://sh.distant.dev | sh
安装路径为 ~/.local/bin,为方便使用,建议将其添加到环境变量中。
远程服务器
使用和本地相同的命令或者使用以下命令
curl -L https://sh.distant.dev | sh -s -- --run-as-admin
使用 distant 管理连接 | 终端使用
distant connect ssh://root@192.168.123.6 1 ↵
Passphrase to decrypt /Users/guo/.ssh/id_rsa for root@192.168.123.6:
>
Password for root@192.168.123.6:
3869755296
distant manager list
+----------+------------+--------+---------------+------+
| selected | id | scheme | host | port |
+----------+------------+--------+---------------+------+
| true | 3869755296 | ssh | 192.168.123.6 | |
+----------+------------+--------+---------------+------+
成功连接后,通过 distant shell
即可打开连接。
安装 nvim 插件 以及 distant
-- Lazy.nvim 安装
{
'chipsenkbeil/distant.nvim',
branch = 'v0.3',
config = function()
require('distant'):setup()
end
}
-- AstroNvim 安装
{ import = "astrocommunity.remote-development.distant-nvim" },
astrocommunity 使用的是 distant-nvim v0.2 branch,通过这个方式安装似乎暂时不能用
安装好插件后,通过 :DistantInstall
命令安装 distant 软件,或者指定已安装的 distant 路径
软件本体安装好后,通过 :DistantClientVersion
查看成功与否。
使用
连接主机 :DistantConnect ssh://<user>@<remote ip>


打开目录并编辑文件 :DistantOpen </path/to/file.txt>



distant-nvim 会新建一个 buffer 用以显示远程主机目录,并在进入子目录后继续新建 buffer 展示子目录。通过提供的快捷键可以自由地在目录中 navigate 。
快捷键如下 👇
配置快捷键
最后,将常用的命令设为快捷键方便使用。 🎉 🎉 🎉
{
"AstroNvim/astrocore",
---@type AstroCoreOpts
opts = {
mappings = {
n = {
["<leader>D"] = { desc = " Distant" },
["<leader>Dc"] = { ":DistantConnect ssh://", desc = "Connects to a remote server" },
["<leader>Do"] = { ":DistantOpen ", desc = "Open a file or directory on the remote machine" },
["<leader>Ds"] = { ":DistantShell<CR>", desc = "Spawns a remote shell for the current connection" },
["<leader>Dm"] = { ":DistantMkdir ", desc = "Creates a new directory on the remote machine" },
["<leader>Dv"] = { ":DistantClientVersion<CR>", desc = "Prints out the version of distant CLI" }
}
}
}
}
References
使用 Nvim 远程 coding
http://guoguo.host/blog/p/268ef2b8.html