我有以下用于在 neovim 中映射键的 lua 函数
local M = {}
function M.map(mode, lhs, rhs, opts)
-- default options
local options = { noremap = true }
if opts then
options = vim.tbl_extend("force", options, opts)
end
vim.api.nvim_set_keymap(mode, lhs, rhs, options)
end
return M
并像这样将其用于键映射:
map("", "<Leader>f", ":CocCommand prettier.forceFormatDocument<CR>")
map("", "<Leader>f", ":RustFmt<CR>")
我只想对
:RustFmt
文件使用.rs
,对所有其他文件使用:CocCommand prettier.forceFormatDocument
。
这可能与
vim.api.nvim_set_keymap
有关吗?如果可以,我该怎么做?
感谢@DoktorOSwaldo 和@UnrealApex,我能够使用
ftplugin
解决问题。
步骤:
ftplugin
.内创建
~/.config/nvim
ftplugin
目录中创建一个文件rust.lua
.rust.lua
导入map
实用程序并定义键映射。local map = require("utils").map
-- Format document
map("", "<Leader>f", ":RustFmt<CR>")
对于 Rust 以外的语言,使用以下命令获取可能文件名的完整列表(
.vim
可以切换为 .lua
):
:exe 'Lexplore ' . expand('$VIMRUNTIME') . '/syntax'
您可以在
format
配置文件中创建一个utils.lua
函数:
function M.format()
if vim.bo.filetype == 'rust' then
vim.cmd('RustFmt')
else
vim.cmd('CocCommand prettier.forceFormatDocument')
end
并像这样定义您的键映射:
map("", "<Leader>f", "<cmd>:lua require('utils').format<CR>")