Neovim 终极设置指南:lazy.nvim 插件管理器
大家好!本文将向大家展示如何使用 lazy.vim 从头配置 neovim 编辑器。
💤 Lazy.nvim
Neovim 的现代插件管理器
-
突出特点:
- 📦使用强大的用户界面管理所有 Neovim 插件
- 🚀 得益于 Lua 模块的自动缓存和字节码编译,启动时间更快
- 🔌 自动延迟加载 Lua 模块以及延迟加载事件、命令、文件类型和键映射
- ⏳ 在启动 Neovim 之前自动安装缺少的插件,让您可以立即开始使用
- 🛠️无需手动编译插件
- 🧪 依赖项的正确排序
- 📁 可在多个文件中配置
- 🔎 自动检查更新
📚 GitHub 仓库
所有代码都在我的 Github 个人资料slydragonn/dotfiles repo 中。
⚙ 要求
- Neovim >= v0.10.0
- 书呆子字体
- NodeJS 与 npm
- 懒惰的vim
- 路径中的 AC 编译器和已安装的 libstdc++:Windows 支持
- Git
✨ 特点
- folke/lazy.nvim:Neovim 的现代插件管理器
- nvim-neo-tree/neo-tree:Neovim 插件用于管理文件系统和其他树状结构。
- tiagovla/tokyodark.nvim:用 lua 为 neovim 编写的干净的黑暗主题。
- nvim-tree/nvim-web-devicons:neovim 的 vim-web-devicons 的 lua 分支。
- nvim-lualine/lualine.nvim:一个用纯 lua 编写的超快且易于配置的 neovim 状态行插件。
- nvim-treesitter/nvim-treesitter:Nvim Treesitter 配置和抽象层。
- windwp/nvim-ts-autotag:使用 treesitter 自动关闭和自动重命名 html 标签。
- stevearc/conform.nvim:轻量级但功能强大的 Neovim 格式化插件。
- nvim-telescope/telescope.nvim:高度可扩展的列表模糊查找器。
- neovim/nvim-lspconfig:Nvim LSP 的快速启动配置
- hrsh7th/nvim-cmp:用 Lua 编码的 neovim 完成插件。
- williamboman/mason.nvim:Neovim 的便携式包管理器,可在 Neovim 运行的任何地方运行。
- norcalli/nvim-colorizer.lua:彩色荧光笔。
- akinsho/toggleterm.nvim:一个 neovim lua 插件,可帮助轻松管理多个终端窗口。
- lewis6991/gitsigns.nvim:缓冲区的 Git 集成。
- windwp/nvim-autopairs:由 lua 编写的 neovim 自动配对。
- onsails/lspkind.nvim:用于 neovim lsp 完成项目的类似 vscode 的象形图。
- L3MON4D3/LuaSnip:用 Lua 编写的 Neovim 代码片段引擎。
- hrsh7th/cmp-nvim-lsp: neovim 内置 LSP 客户端的 nvim-cmp 源
- hrsh7th/cmp-path: nvim-cmp 路径源
- hrsh7th/cmp-buffer: nvim-cmp 缓冲字源
- williamboman/mason-lspconfig.nvim: mason.nvim 的扩展,使 lspconfig 和 mason.nvim 更容易使用。
- WhoIsSethDaniel/mason-tool-installer.nvim:自动安装和升级第三方工具。
📚 项目结构
📂 nvim/
├── 📂 lua/📂 slydragonn/
│ └── 📂 plugins/
│ └── 📂 lsp/
│ └── ...pluginconfigfiles
│ └── 🌑 settings.lua
│ └── 🌑 maps.lua
│ └── 🌑 lazy.lua
└── 🌑 init.lua
如果你没有某些要求
- Nerd 字体:https://www.nerdfonts.com/
- Neovim:https://github.com/neovim/neovim/releases/
- 节点:https://nodejs.org/en/download/package-manager
- C 编译器:https://github.com/nvim-treesitter/nvim-treesitter/wiki/Windows-support
- Git:https://git-scm.com/downloads
保存设置
配置文件存储在特定位置,因此您应该根据您的操作系统在以下路径中创建 nvim/ 文件夹:
-
视窗:
C:\Users\%YOUR_USERNAME%\AppData\Local\nvim
-
Linux:
~/.configs/nvim/
并在 nvim/ 文件夹中 使用以下代码创建init.lua
文件:
- 注意:slydragonn 是我的个人文件夹,但您可以随意重命名它:)
-- ~/nvim/init.lua
require("slydragonn.settings")
编辑器设置
然后为我们的配置和插件创建一个 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
添加 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")
然后在 init.lua 文件中我们导入惰性配置:
-- ~/nvim/init.lua
require("slydragonn.settings")
require("slydragonn.lazy")
并创建 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,
}
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,
}
自动配对.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,
}
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,
}
着色器.lua
norcalli/nvim-colorizer.lua:彩色荧光笔。
-- ~/nvim/lua/slydragonn/plugins/colorizer.lua
return {
"norcalli/nvim-colorizer.lua",
config = function()
require("colorizer").setup({ "*" })
end,
}
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,
}
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,
}
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,
}
格式化程序.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,
}
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,
}
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
},
}
望远镜.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,
}
切换终端.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,
}
当所有插件都添加完成后,我们写入命令:Lazy
,然后按shift
+L
进行安装或shift
按 +S
进行同步。
编辑器按键绑定
init.lua 内部需要地图文件。
-- ~/nvim/init.lua
require("slydragonn.settings")
require("slydragonn.lazy")
require("slydragonn.maps") -- key bindings
地图.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>-")
就是这样,通过此设置,您应该拥有一个出色的 neovim 编辑器。
📚 资源
- 我的 neovim 设置与 lazy.vim:https://github.com/slydragonn/nvim-lazy
- Youtube 视频:
- Lazy.vim:https://github.com/folke/lazy.nvim
- Neovim 资源:https://neovim.io/doc/user/lua.html#lua-intro
- Lua 资源:https://www.lua.org/manual/5.4/
感谢您的阅读,回头见!
文章来源:https://dev.to/slydragonn/ultimate-neovim-setup-guide-lazynvim-plugin-manager-23b7