/
Panteleev
/
nvim-lua-cfg
Обзор
Документация
Войти
/
Panteleev
/
nvim-lua-cfg
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
init.lua
364 строки
12 KB
Panteleev
update init.lua
21 дек 2025, 11:20
21 дек 2025, 11:20
992518c
Код
Авторство
О чём код?
local vim = vim local api = vim.api local opt = vim.opt -- Загрузка lazy.nvim -- local lazypath = vim.fn.stdpath("data") .. "/lazy/lazy.nvim" if not (vim.uv or vim.loop).fs_stat(lazypath) then local lazyrepo = "https://github.com/folke/lazy.nvim.git" local out = vim.fn.system({ "git", "clone", "--filter=blob:none", "--branch=stable", lazyrepo, lazypath }) if vim.v.shell_error ~= 0 then api.nvim_echo({ { "Failed to clone lazy.nvim:\n", "ErrorMsg" }, { out, "WarningMsg" }, { "\nPress any key to exit..." }, }, true, {}) vim.fn.getchar() os.exit(1) end end opt.rtp:prepend(lazypath) -- нужно установить до запуска lazy vim.g.mapleader = " " vim.g.maplocalleader = "\\" -- Плагины -- require("lazy").setup({ "tpope/vim-fugitive", { "f-person/git-blame.nvim", event = "VeryLazy", opts = { enabled = false}, }, { "nvimtools/none-ls.nvim", dependencies = { "nvim-lua/plenary.nvim" }, }, { "nvim-treesitter/nvim-treesitter", lazy = false, build = ':TSUpdate', }, { 'nvim-mini/mini.nvim', version = false, config = function() require('mini.icons').setup() end, }, { 'stevearc/oil.nvim', opts = {}, dependencies = { { "nvim-mini/mini.nvim", opts = {} } }, lazy = false, config = function() require("oil").setup() end, }, "nordtheme/vim", "michaeldyrynda/carbon", { "ellisonleao/gruvbox.nvim", name = "gruvbox", priority = 1000, config = function() require("gruvbox").setup({ terminal_colors = true, -- современная цветовая палитра undercurl = true, underline = true, bold = true, italic = { strings = true, emphasis = true, comments = true, operators = false, folds = true, }, strikethrough = true, invert_selection = false, invert_signs = false, invert_tabline = false, inverse = true, -- инверсия фона при поиска, статуса и прочего contrast = "soft", -- "hard", "soft" или "" palette_overrides = {}, overrides = {}, dim_inactive = true, transparent_mode = false, }) vim.cmd.colorscheme("gruvbox") opt.background = "dark" end, }, }) -- Пользовательские настройки -- opt.number = true -- показывать номер строки opt.relativenumber = true -- показывать относительные номера строк opt.expandtab = true -- заменять табы на пробелы opt.tabstop = 4 -- пробелов на таб opt.shiftwidth = 4 -- автоотступ пробелами opt.softtabstop = 4 -- удалять пробелов за раз opt.ignorecase = true -- игнорировать регистр при поиске opt.smartcase = true -- умный учет регистра при поиске opt.termguicolors = true -- современная цветовая палитра opt.clipboard = 'unnamedplus' -- копирование также в системный буфер mac os opt.encoding = 'UTF-8' -- кодировка -- шрифт(должен быть установлен в системе), размер символов opt.guifont= 'FiraCodeNerdFontMono:h14' -- Перемещение блока кода в визуальном режиме -- vim.keymap.set("v", "<C-j>", ":m '>+1<CR>gv=gv") vim.keymap.set("v", "<C-k>", ":m '<-2<CR>gv=gv") vim.keymap.set("v", "<C-h>", "<gv") vim.keymap.set("v", "<C-l>", ">gv") -- LSP -- local lsp = vim.lsp local lsp_attach = function(ev) opts = { buffer = ev.buf } vim.keymap.set('n', 'K', '<cmd>lua vim.lsp.buf.hover()<cr>', opts) -- показать информацию о выдленном токене vim.keymap.set('n', 'gd', '<cmd>lua vim.lsp.buf.definition()<cr>', opts) -- перейти к реализации vim.keymap.set('n', 'gD', '<cmd>lua vim.lsp.buf.declaration()<cr>', opts) -- перейти к объявлению vim.keymap.set('n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<cr>', opts) -- показать все реализации интерфейса vim.keymap.set('n', 'go', '<cmd>lua vim.lsp.buf.type_definition()<cr>', opts) -- перейти к интерфейсу vim.keymap.set('n', 'gr', '<cmd>lua vim.lsp.buf.references()<cr>', opts) -- показать все зависимости vim.keymap.set('n', 'gs', '<cmd>lua vim.lsp.buf.signature_help()<cr>', opts) -- показать информацию о сигнатуре vim.keymap.set('n', '<F2>', '<cmd>lua vim.lsp.buf.rename()<cr>', opts) -- переименовать токен vim.keymap.set({'n', 'x'}, '<F3>', '<cmd>lua vim.lsp.buf.format({async = true})<cr>', opts) -- форматирование кода vim.keymap.set('n', '<F4>', '<cmd>lua vim.lsp.buf.code_action()<cr>', opts) -- возможные действия над кодом -- автодополнение local client = lsp.get_client_by_id(ev.data.client_id) if client:supports_method('textDocument/completion') then -- local chars = {}; for i = 32, 126 do table.insert(chars, string.char(i)) end -- client.server_capabilities.completionProvider.triggerCharacters = chars lsp.completion.enable(true, client.id, ev.buf, { autotrigger = false }) -- автодополнение работает через комбинацию <C-X><C-O> end end api.nvim_create_autocmd("LspAttach", { callback = lsp_attach, }) -- не выбирать первую подсказку автодополнения автоматически -- vim.cmd("set completeopt+=noselect") -- закругленные углы всплывающего окна vim.o.winborder = "rounded" -- Perl -- lsp.config.perlpls = { cmd = { 'pls' }, filetypes = { 'perl' }, root_markers = { '.git' }, settings = { perl = { inc = { "$ROOT_PATH/lib" }, syntax = { enabled = true }, perlcritic = { enabled = false }, } } } -- PHP -- local get_intelephense_license = function () local f = assert(io.open(os.getenv("HOME") .. "/intelephense/license.txt","rb")) local content = f:read("*a") f:close() return string.gsub(content, "%s+", "") end lsp.config.intelephense = { cmd = { 'intelephense', '--stdio' }, filetypes = { 'php' }, root_markers = { '.git', 'composer.json' }, init_options = { licenceKey = get_intelephense_license() }, settings = { intelephense = { runtime = true, maxMemory = 8192, files = { maxSize = 50000000 }, } } } -- GO -- --- @class go_dir_custom_args --- --- @field envvar_id string --- --- @field custom_subdir string? local mod_cache = nil local std_lib = nil ---@param custom_args go_dir_custom_args ---@param on_complete fun(dir: string | nil) local function identify_go_dir(custom_args, on_complete) local cmd = { 'go', 'env', custom_args.envvar_id } vim.system(cmd, { text = true }, function(output) local res = vim.trim(output.stdout or '') if output.code == 0 and res ~= '' then if custom_args.custom_subdir and custom_args.custom_subdir ~= '' then res = res .. custom_args.custom_subdir end on_complete(res) else vim.schedule(function() vim.notify( ('[gopls] identify ' .. custom_args.envvar_id .. ' dir cmd failed with code %d: %s\n%s'):format( output.code, vim.inspect(cmd), output.stderr ) ) end) on_complete(nil) end end) end ---@return string? local function get_std_lib_dir() if std_lib and std_lib ~= '' then return std_lib end identify_go_dir({ envvar_id = 'GOROOT', custom_subdir = '/src' }, function(dir) if dir then std_lib = dir end end) return std_lib end ---@return string? local function get_mod_cache_dir() if mod_cache and mod_cache ~= '' then return mod_cache end identify_go_dir({ envvar_id = 'GOMODCACHE' }, function(dir) if dir then mod_cache = dir end end) return mod_cache end ---@param fname string ---@return string? local function get_root_dir(fname) if mod_cache and fname:sub(1, #mod_cache) == mod_cache then local clients = lsp.get_clients({ name = 'gopls' }) if #clients > 0 then return clients[#clients].config.root_dir end end if std_lib and fname:sub(1, #std_lib) == std_lib then local clients = lsp.get_clients({ name = 'gopls' }) if #clients > 0 then return clients[#clients].config.root_dir end end return vim.fs.root(fname, 'go.work') or vim.fs.root(fname, 'go.mod') or vim.fs.root(fname, '.git') end lsp.config.gopls = { cmd = { 'gopls' }, filetypes = { 'go', 'gomod', 'gowork', 'gotmpl' }, root_dir = function(bufnr, on_dir) local fname = api.nvim_buf_get_name(bufnr) get_mod_cache_dir() get_std_lib_dir() -- see: https://github.com/neovim/nvim-lspconfig/issues/804 on_dir(get_root_dir(fname)) end, on_attach = function(client, bufnr) --Format on save api.nvim_create_autocmd("BufWritePre", { group = api.nvim_create_augroup("lsp_format_go", { clear = true }), buffer = bufnr, callback = function() lsp.buf.format({ async = false }) end, }) end, settings = { gopls = { buildFlags = {"-tags=integration component"} } } } -- golangci-lint lsp.config.golangci_lint_ls = { cmd = { 'golangci-lint-langserver' }, filetypes = { 'go', 'gomod' }, init_options = { command = { 'golangci-lint', 'run', '--output.json.path=stdout', '--show-stats=false' }, }, root_markers = { '.golangci.yml', '.golangci.yaml', '.golangci.toml', '.golangci.json', 'go.work', 'go.mod', '.git', }, } lsp.enable({ "perlpls", "intelephense", "gopls", "golangci_lint_ls", }) -- диганостические сообщения (от LSP сервера) vim.diagnostic.config({ -- virtual_text = { current_line = true }, -- показывать сообщение только в активной строке -- underline = true, -- подчеркивание ошибок virtual_lines = true, -- виртуальные строки для сообщений }) -- Treesitter -- -- установка нужных парсеров require('nvim-treesitter').install({ 'perl', 'php', 'go' }) -- включаем подсветку vim.api.nvim_create_autocmd('FileType', { pattern = { '<filetype>' }, callback = function() vim.treesitter.start() end, }) -- none-ls -- local none_ls = require("null-ls") -- использует старую сигнатуру none_ls.setup({ sources = { none_ls.builtins.formatting.phpcsfixer.with({ prefer_local = "tools/" }), none_ls.builtins.diagnostics.phpstan.with({ prefer_local = "tools/", }), }, on_attach = function(client, bufnr) if client.supports_method("textDocument/formatting") then api.nvim_create_autocmd("BufWritePre", { group = api.nvim_create_augroup("LspFormatting", {}), buffer = bufnr, callback = function() lsp.buf.format({ async = false }) end, }) end end, })