Neovim + Lua:如何根据文件类型使用不同的映射?

问题描述 投票:0回答:2

我有以下用于在 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
有关吗?如果可以,我该怎么做?

lua neovim keymapping
2个回答
5
投票

感谢@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'

2
投票

您可以在

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>")
© www.soinside.com 2019 - 2024. All rights reserved.