Neovim 终极设置指南:lazy.nvim 插件管理器

2025-05-26

Neovim 终极设置指南:lazy.nvim 插件管理器

大家好!本文将向大家展示如何使用 lazy.vim 从头配置 neovim 编辑器。

💤 Lazy.nvim

Neovim 的现代插件管理器

  • 仓库:folke/lazy.nvim

  • 突出特点:

    • 📦使用强大的用户界面管理所有 Neovim 插件
    • 🚀 得益于 Lua 模块的自动缓存和字节码编译,启动时间更快
    • 🔌 自动延迟加载 Lua 模块以及延迟加载事件、命令、文件类型和键映射
    • ⏳ 在启动 Neovim 之前自动安装缺少的插件,让您可以立即开始使用
    • 🛠️无需手动编译插件
    • 🧪 依赖项的正确排序
    • 📁 可在多个文件中配置
    • 🔎 自动检查更新

📚 GitHub 仓库

所有代码都在我的 Github 个人资料slydragonn/dotfiles repo 中。

⚙ 要求

✨ 特点

📚 项目结构

📂 nvim/
├── 📂 lua/📂 slydragonn/
│  └── 📂 plugins/
│        └── 📂 lsp/
│        └── ...pluginconfigfiles
│  └── 🌑 settings.lua
│  └── 🌑 maps.lua
│    └── 🌑 lazy.lua
└── 🌑 init.lua
Enter fullscreen mode Exit fullscreen mode

如果你没有某些要求

保存设置

配置文件存储在特定位置,因此您应该根据您的操作系统在以下路径中创建 nvim/ 文件夹:

  • 视窗:C:\Users\%YOUR_USERNAME%\AppData\Local\nvim

  • Linux:~/.configs/nvim/

并在 nvim/ 文件夹中 使用以下代码创建init.lua文件:

  • 注意:slydragonn 是我的个人文件夹,但您可以随意重命名它:)
-- ~/nvim/init.lua

require("slydragonn.settings")
Enter fullscreen mode Exit fullscreen mode

编辑器设置

然后为我们的配置和插件创建一个 lua 文件夹。

-- ~/nvim/lua/slydragonn/settings.lua

local global = vim.g
local o = vim.opt

-- Editor options

o.number = true -- Print the line number in front of each line
o.relativenumber = true -- Show the line number relative to the line with the cursor in front of each line.
o.clipboard = "unnamedplus" -- uses the clipboard register for all operations except yank.
o.syntax = "on" -- When this option is set, the syntax with this name is loaded.
o.autoindent = true -- Copy indent from current line when starting a new line.
o.cursorline = true -- Highlight the screen line of the cursor with CursorLine.
o.expandtab = true -- In Insert mode: Use the appropriate number of spaces to insert a <Tab>.
o.shiftwidth = 2 -- Number of spaces to use for each step of (auto)indent.
o.tabstop = 2 -- Number of spaces that a <Tab> in the file counts for.
o.encoding = "UTF-8" -- Sets the character encoding used inside Vim.
o.ruler = true -- Show the line and column number of the cursor position, separated by a comma.
o.mouse = "a" -- Enable the use of the mouse. "a" you can use on all modes
o.title = true -- When on, the title of the window will be set to the value of 'titlestring'
o.hidden = true -- When on a buffer becomes hidden when it is |abandon|ed
o.ttimeoutlen = 0 -- The time in milliseconds that is waited for a key code or mapped key sequence to complete.
o.wildmenu = true -- When 'wildmenu' is on, command-line completion operates in an enhanced mode.
o.showcmd = true -- Show (partial) command in the last line of the screen. Set this option off if your terminal is slow.
o.showmatch = true -- When a bracket is inserted, briefly jump to the matching one.
o.inccommand = "split" -- When nonempty, shows the effects of :substitute, :smagic, :snomagic and user commands with the :command-preview flag as you type.
o.splitright = true
o.splitbelow = true -- When on, splitting a window will put the new window below the current one
o.termguicolors = true
Enter fullscreen mode Exit fullscreen mode

添加 Lazy.vim

安装 Lazy 非常简单,你只需要从folke/lazy.nvim复制此代码并将其粘贴到~/nvim/lua/slydragonn/lazy.lua

-- ~/nvim/lua/slydragonn/lazy.lua

local lazypath = vim.fn.stdpath("data") .. "/lazy/lazy.nvim"
if not (vim.uv or vim.loop).fs_stat(lazypath) then
  vim.fn.system({
    "git",
    "clone",
    "--filter=blob:none",
    "https://github.com/folke/lazy.nvim.git",
    "--branch=stable", -- latest stable release
    lazypath,
  })
end
vim.opt.rtp:prepend(lazypath)

require("lazy").setup("slydragonn.plugins")
Enter fullscreen mode Exit fullscreen mode

然后在 init.lua 文件中我们导入惰性配置:

-- ~/nvim/init.lua

require("slydragonn.settings")
require("slydragonn.lazy")
Enter fullscreen mode Exit fullscreen mode

并创建 plugins/ 文件夹,在其中添加插件配置文件:~/nvim/lua/plugins/

Lazy 会读取插件文件夹中的所有文件,因为这是我们设置的,并且 Lazy 会自动安装它们,或者我们可以使用命令:Lazy来查看 UI。

惰性命令

  • 打开用户界面::Lazy
  • 安装:shift+L
  • 同步:shift+S
  • 更新:shift+U
  • 清除:shift+X
  • 检查:shift+C
  • 日志:shift+L
  • 恢复:shift+R
  • 个人资料:shift+P
  • 调试:shift+D
  • 帮助:shift+?

ℹ️建议:checkhealth lazy安装后运行。

插件配置:

树保姆.lua

nvim-treesitter/nvim-treesitter: Nvim Treesitter 配置和抽象层。

--- ~/nvim/lua/slydragonn/plugins/treesiter.lua

return {
    "nvim-treesitter/nvim-treesitter",
    event = { "BufReadPre", "BufNewFile" },
    build = ":TSUpdate",
    dependencies = {
        "windwp/nvim-ts-autotag",
    },
    config = function()
        local treesitter = require("nvim-treesitter.configs")

        treesitter.setup({
            highlight = {
                enable = true,
                additional_vim_regex_highlighting = false,
            },
            indent = { enable = true },
            autotag = {
                enable = true,
            },
            ensure_installed = {
                "json",
                "javascript",
                "typescript",
                "tsx",
                "yaml",
                "html",
                "css",
                "markdown",
                "markdown_inline",
                "bash",
                "lua",
                "vim",
                "dockerfile",
                "gitignore",
                "c",
                "rust",
            },
            incremental_selection = {
                enable = true,
                keymaps = {
                    init_selection = "<C-space>",
                    node_incremental = "<C-space>",
                    scope_incremental = false,
                    node_decremental = "<bs>",
                },
            },
            rainbow = {
                enable = true,
                disable = { "html" },
                extended_mode = false,
                max_file_lines = nil,
            },
            context_commentstring = {
                enable = true,
                enable_autocmd = false,
            },
        })
    end,
}
Enter fullscreen mode Exit fullscreen mode

colorscheme.lua

tiagovla/tokyodark.nvim:用 lua 为 neovim 编写的干净的黑暗主题。

-- ~/nvim/lua/slydragonn/plugins/colorscheme.lua

return {
    "tiagovla/tokyodark.nvim",
    lazy = false,
    priority = 1000,
    config = function()
        vim.cmd("colorscheme tokyodark")
    end,
}
Enter fullscreen mode Exit fullscreen mode

自动配对.lua

windwp/nvim-autopairs:由 lua 编写的 neovim 自动配对。

-- ~/nvim/lua/slydragonn/plugins/autopairs.lua

return {
    "windwp/nvim-autopairs",
    event = "InsertEnter",
    config = function()
        require("nvim-autopairs").setup({
            disable_filetype = { "TelescopePrompt", "vim" },
        })
    end,
}
Enter fullscreen mode Exit fullscreen mode

cmp.lua

hrsh7th/nvim-cmp:用 Lua 编码的 neovim 完成插件。

-- ~/nvim/lua/slydragonn/plugins/cmp.lua

return {
    "hrsh7th/nvim-cmp",
    event = "InsertEnter",
    dependencies = {
        "hrsh7th/cmp-buffer", -- source for text in buffer
        "hrsh7th/cmp-path", -- source for file system paths
        {
            "L3MON4D3/LuaSnip",
            version = "v2.*",
            -- install jsregexp (optional!).
            build = "make install_jsregexp",
        },
        "rafamadriz/friendly-snippets",
        "onsails/lspkind.nvim", -- vs-code like pictograms
    },
    config = function()
        local cmp = require("cmp")
        local lspkind = require("lspkind")
        local luasnip = require("luasnip")

        require("luasnip.loaders.from_vscode").lazy_load()

        cmp.setup({
            snippet = {
                expand = function(args)
                    luasnip.lsp_expand(args.body)
                end,
            },
            mapping = cmp.mapping.preset.insert({
                ["<C-d>"] = cmp.mapping.scroll_docs(-4),
                ["<C-f>"] = cmp.mapping.scroll_docs(4),
                ["<C-Space>"] = cmp.mapping.complete(),
                ["<C-e>"] = cmp.mapping.close(),
                ["<CR>"] = cmp.mapping.confirm({
                    behavior = cmp.ConfirmBehavior.Replace,
                    select = true,
                }),
            }),
            sources = cmp.config.sources({
                { name = "nvim_lsp" },
                { name = "luasnip" },
                { name = "buffer" },
                { name = "path" },
            }),
        })

        vim.cmd([[
      set completeopt=menuone,noinsert,noselect
      highlight! default link CmpItemKind CmpItemMenuDefault
    ]])
    end,
}
Enter fullscreen mode Exit fullscreen mode

着色器.lua

norcalli/nvim-colorizer.lua:彩色荧光笔。

-- ~/nvim/lua/slydragonn/plugins/colorizer.lua

return {
    "norcalli/nvim-colorizer.lua",
    config = function()
        require("colorizer").setup({ "*" })
    end,
}
Enter fullscreen mode Exit fullscreen mode

lualine.lua

nvim-lualine/lualine.nvim:一个用纯 lua 编写的超快且易于配置的 neovim 状态行插件。

-- ~/nvim/lua/slydragonn/plugins/lualine.lua

return {
    "nvim-lualine/lualine.nvim",
    dependencies = { "nvim-tree/nvim-web-devicons" },
    config = function()
        require("lualine").setup()
    end,
}
Enter fullscreen mode Exit fullscreen mode

mason.lua

williamboman/mason.nvim: Neovim 的便携式包管理器,可在 Neovim 运行的任何地方运行。

-- ~/nvim/lua/slydragonn/plugins/mason.lua

return {
    "williamboman/mason.nvim",
    dependencies = {
        "williamboman/mason-lspconfig.nvim",
        "WhoIsSethDaniel/mason-tool-installer.nvim",
    },
    config = function()
        require("mason").setup()

        require("mason-lspconfig").setup({
            automatic_installation = true,
            ensure_installed = {
                "cssls",
                "eslint",
                "html",
                "jsonls",
                "tsserver",
                "pyright",
                "tailwindcss",
            },
        })

        require("mason-tool-installer").setup({
            ensure_installed = {
                "prettier",
                "stylua", -- lua formatter
                "isort", -- python formatter
                "black", -- python formatter
                "pylint",
                "eslint_d",
            },
        })
    end,
}
Enter fullscreen mode Exit fullscreen mode

lsp配置文件

williamboman/mason-lspconfig.nvim: mason.nvim 的扩展,使 lspconfig 和 mason.nvim 更容易使用。

-- ~/nvim/lua/slydragonn/plugins/lspconfig.lua

return {
    "neovim/nvim-lspconfig",
    event = { "BufReadPre", "BufNewFile" },
    dependencies = {
        "hrsh7th/cmp-nvim-lsp",
        { "folke/neodev.nvim", opts = {} },
    },
    config = function()
        local nvim_lsp = require("lspconfig")
        local mason_lspconfig = require("mason-lspconfig")

        local protocol = require("vim.lsp.protocol")

        local on_attach = function(client, bufnr)
            -- format on save
            if client.server_capabilities.documentFormattingProvider then
                vim.api.nvim_create_autocmd("BufWritePre", {
                    group = vim.api.nvim_create_augroup("Format", { clear = true }),
                    buffer = bufnr,
                    callback = function()
                        vim.lsp.buf.format()
                    end,
                })
            end
        end

        local capabilities = require("cmp_nvim_lsp").default_capabilities()

        mason_lspconfig.setup_handlers({
            function(server)
                nvim_lsp[server].setup({
                    capabilities = capabilities,
                })
            end,
            ["tsserver"] = function()
                nvim_lsp["tsserver"].setup({
                    on_attach = on_attach,
                    capabilities = capabilities,
                })
            end,
            ["cssls"] = function()
                nvim_lsp["cssls"].setup({
                    on_attach = on_attach,
                    capabilities = capabilities,
                })
            end,
            ["tailwindcss"] = function()
                nvim_lsp["tailwindcss"].setup({
                    on_attach = on_attach,
                    capabilities = capabilities,
                })
            end,
            ["html"] = function()
                nvim_lsp["html"].setup({
                    on_attach = on_attach,
                    capabilities = capabilities,
                })
            end,
            ["jsonls"] = function()
                nvim_lsp["jsonls"].setup({
                    on_attach = on_attach,
                    capabilities = capabilities,
                })
            end,
            ["eslint"] = function()
                nvim_lsp["eslint"].setup({
                    on_attach = on_attach,
                    capabilities = capabilities,
                })
            end,
            ["pyright"] = function()
                nvim_lsp["pyright"].setup({
                    on_attach = on_attach,
                    capabilities = capabilities,
                })
            end,
        })
    end,
}
Enter fullscreen mode Exit fullscreen mode

格式化程序.lua

stevearc/conform.nvim:轻量级但功能强大的 Neovim 格式化插件。

-- ~/nvim/lua/slydragonn/plugins/formatter.lua

return {
    "stevearc/conform.nvim",
    event = { "BufReadPre", "BufNewFile" },
    config = function()
        local conform = require("conform")

        conform.setup({
            formatters_by_ft = {
                javascript = { "prettier" },
                typescript = { "prettier" },
                javascriptreact = { "prettier" },
                typescriptreact = { "prettier" },
                css = { "prettier" },
                html = { "prettier" },
                json = { "prettier" },
                yaml = { "prettier" },
                markdown = { "prettier" },
                lua = { "stylua" },
                python = { "isort", "black" },
            },
            format_on_save = {
                lsp_fallback = true,
                async = false,
                timeout_ms = 1000,
            },
        })

        vim.keymap.set({ "n", "v" }, "<leader>f", function()
            conform.format({
                lsp_fallback = true,
                async = false,
                timeout_ms = 1000,
            })
        end, { desc = "Format file or range (in visual mode)" })
    end,
}
Enter fullscreen mode Exit fullscreen mode

gitsigns.lua

lewis6991/gitsigns.nvim:缓冲区的 Git 集成。

-- ~/nvim/lua/slydragonn/plugins/gitsigns.lua

return {
    "lewis6991/gitsigns.nvim",
    config = function()
        local gitsigns = require("gitsigns")
        gitsigns.setup({
            signs = {
                add = { text = "│" },
                change = { text = "│" },
                delete = { text = "_" },
                topdelete = { text = "‾" },
                changedelete = { text = "~" },
                untracked = { text = "┆" },
            },
            signcolumn = true, -- Toggle with `:Gitsigns toggle_signs`
            numhl = false, -- Toggle with `:Gitsigns toggle_numhl`
            linehl = false, -- Toggle with `:Gitsigns toggle_linehl`
            word_diff = false, -- Toggle with `:Gitsigns toggle_word_diff`
            watch_gitdir = {
                interval = 1000,
                follow_files = true,
            },
            attach_to_untracked = true,
            current_line_blame = false, -- Toggle with `:Gitsigns toggle_current_line_blame`
            current_line_blame_opts = {
                virt_text = true,
                virt_text_pos = "eol", -- 'eol' | 'overlay' | 'right_align'
                delay = 1000,
                ignore_whitespace = false,
            },
            current_line_blame_formatter = "<author>, <author_time:%Y-%m-%d> - <summary>",
            sign_priority = 6,
            update_debounce = 100,
            status_formatter = nil, -- Use default
            max_file_length = 40000, -- Disable if file is longer than this (in lines)
            preview_config = {
                -- Options passed to nvim_open_win
                border = "single",
                style = "minimal",
                relative = "cursor",
                row = 0,
                col = 1,
            },
            yadm = {
                enable = false,
            },
        })
    end,
}
Enter fullscreen mode Exit fullscreen mode

neotree.lua

nvim-neo-tree/neo-tree: Neovim 插件用于管理文件系统和其他树状结构。

-- ~/nvim/lua/slydragonn/plugins/neotree.lua

return {
    "nvim-neo-tree/neo-tree.nvim",
    branch = "v3.x",
    dependencies = {
        "nvim-lua/plenary.nvim",
        "nvim-tree/nvim-web-devicons",
        "MunifTanjim/nui.nvim",
        -- "3rd/image.nvim", -- Optional image support in preview window: See `# Preview Mode` for more information
    },
}
Enter fullscreen mode Exit fullscreen mode

望远镜.lua

nvim-telescope/telescope.nvim:高度可扩展的列表模糊查找器。

-- ~/nvim/lua/slydragonn/plugins/telescope.lua

return {
    "nvim-telescope/telescope.nvim",
    tag = "0.1.6",
    dependencies = { "nvim-lua/plenary.nvim" },
    config = function()
        require("telescope").setup()

        -- set keymaps
        local keymap = vim.keymap

        keymap.set("n", "<leader>ff", "<cmd>Telescope find_files<cr>", { desc = "Fuzzy find files in cwd" })
        keymap.set("n", "<leader>fg", "<cmd>Telescope live_grep<cr>", { desc = "Fuzzy find recent files" })
        keymap.set("n", "<leader>fb", "<cmd>Telescope buffers<cr>", { desc = "Find string in cwd" })
        keymap.set("n", "<leader>fs", "<cmd>Telescope git_status<cr>", { desc = "Find string under cursor in cwd" })
        keymap.set("n", "<leader>fc", "<cmd>Telescope git commits<cr>", { desc = "Find todos" })
    end,
}
Enter fullscreen mode Exit fullscreen mode

切换终端.lua

akinsho/toggleterm.nvim:一个 neovim lua 插件,可帮助轻松管理多个终端窗口。

-- ~/nvim/lua/slydragonn/plugins/toggleterm.lua

return {
  'akinsho/toggleterm.nvim',
  version = "*",
  config = function()
    require("toggleterm").setup({
        size = 10,
        open_mapping = [[<F7>]],
        shading_factor = 2,
        direction = "float",
        float_opts = {
            border = "curved",
            highlights = {
                border = "Normal",
                background = "Normal",
            },
        },
    }) 

  end,
}
Enter fullscreen mode Exit fullscreen mode

当所有插件都添加完成后,我们写入命令:Lazy,然后按shift+L进行安装或shift按 +S进行同步。

编辑器按键绑定

init.lua 内部需要地图文件。

-- ~/nvim/init.lua
require("slydragonn.settings")
require("slydragonn.lazy")
require("slydragonn.maps") -- key bindings
Enter fullscreen mode Exit fullscreen mode

地图.lua

-- ~/nvim/lua/slydragonn/maps.lua

vim.g.mapleader = " "

local function map(mode, lhs, rhs)
    vim.keymap.set(mode, lhs, rhs, { silent = true })
end


-- Save
map("n", "<leader>w", "<CMD>update<CR>")

-- Quit
map("n", "<leader>q", "<CMD>q<CR>")

-- Exit insert mode
map("i", "jk", "<ESC>")

-- NeoTree
map("n", "<leader>e", "<CMD>Neotree toggle<CR>")
map("n", "<leader>r", "<CMD>Neotree focus<CR>")

-- New Windows
map("n", "<leader>o", "<CMD>vsplit<CR>")
map("n", "<leader>p", "<CMD>split<CR>")

-- Window Navigation
map("n", "<C-h>", "<C-w>h")
map("n", "<C-l>", "<C-w>l")
map("n", "<C-k>", "<C-w>k")
map("n", "<C-j>", "<C-w>j")

-- Resize Windows
map("n", "<C-Left>", "<C-w><")
map("n", "<C-Right>", "<C-w>>")
map("n", "<C-Up>", "<C-w>+")
map("n", "<C-Down>", "<C-w>-")
Enter fullscreen mode Exit fullscreen mode

就是这样,通过此设置,您应该拥有一个出色的 neovim 编辑器。

📚 资源

感谢您的阅读,回头见!

文章来源:https://dev.to/slydragonn/ultimate-neovim-setup-guide-lazynvim-plugin-manager-23b7
PREV
React 初学者的 10 个 JavaScript 概念
NEXT
使用 SST 在 AWS 上免费部署 NEXT.js 应用程序