当前位置: 首页 > 工具软件 > neovim-e > 使用案例 >

neovim 配置记录

松高爽
2023-12-01
local use=require('packer').use
require('packer').startup(function()
        use 'wbthomason/packer.nvim'
        use 'neovim/nvim-lspconfig'
        use 'hrsh7th/nvim-cmp' -- Autocompletion plugin
        use 'hrsh7th/cmp-path' -- Autocompletion plugin
        use 'hrsh7th/cmp-buffer' -- Autocompletion plugin
        use 'hrsh7th/cmp-cmdline' -- Autocompletion plugin
        use 'hrsh7th/cmp-nvim-lsp' -- LSP source for nvim-cmp
        use 'saadparwaiz1/cmp_luasnip' -- Snippets source for nvim-cmp
        use 'L3MON4D3/LuaSnip' -- Snippets plugin
        use "windwp/nvim-autopairs"
        use 'shaunsingh/nord.nvim'
        use 'nvim-treesitter/nvim-treesitter'
        use 'glepnir/dashboard-nvim'
        use 'yamatsum/nvim-cursorline'
        use {
                'kyazdani42/nvim-tree.lua',
                requires = 'kyazdani42/nvim-web-devicons'
        }
        use {
                'nvim-lualine/lualine.nvim',
                requires = { 'kyazdani42/nvim-web-devicons', opt = true }
        }
        use {"akinsho/toggleterm.nvim", tag = 'v2.*', config = function()
                require("toggleterm").setup()
        end}
        use 'karb94/neoscroll.nvim'
        use { "rcarriga/nvim-dap-ui", requires = {"mfussenegger/nvim-dap"} }
        use {
                'kdheepak/tabline.nvim',
                config = function()
                        require'tabline'.setup {
                                -- Defaults configuration options
                                enable = true,
                                options = {
                                        -- If lualine is installed tabline will use separators configured in lualine by default.
                                        -- These options can be used to override those settings.
                                        section_separators = {'', ''},
                                        component_separators = {'', ''},
                                        max_bufferline_percent = 66, -- set to nil by default, and it uses vim.o.columns * 2/3
                                        show_tabs_always = false, -- this shows tabs only when there are more than one tab or if the first tab is named
                                        show_devicons = true, -- this shows devicons in buffer section
                                        show_bufnr = false, -- this appends [bufnr] to buffer section,
                                        show_filename_only = false, -- shows base filename only instead of relative path in filename
                                        modified_icon = "+ ", -- change the default modified icon
                                        modified_italic = false, -- set to true by default; this determines whether the filename turns italic if modified
                                        show_tabs_only = false, -- this shows only tabs instead of tabs + buffers
                                }
                        }
                        vim.cmd[[
                        set guioptions-=e " Use showtabline in gui vim
                        set sessionoptions+=tabpages,globals " store tabpages and globals in session
                        ]]
                end,
                requires = { { 'hoob3rt/lualine.nvim', opt=true }, {'kyazdani42/nvim-web-devicons', opt = true} }
        }
end)

local colors = {
        red = '#ca1243',
        grey = '#a0a1a7',
        black = '#383a42',
        white = '#f3f3f3',
        light_green = '#83a598',
        orange = '#fe8019',
        green = '#8ec07c',
}

local theme = {
        normal = {
                a = { fg = colors.white, bg = colors.black },
                b = { fg = colors.white, bg = colors.grey },
                c = { fg = colors.black, bg = colors.white },
                z = { fg = colors.white, bg = colors.black },
        },
        insert = { a = { fg = colors.black, bg = colors.light_green } },
        visual = { a = { fg = colors.black, bg = colors.orange } },
        replace = { a = { fg = colors.black, bg = colors.green } },
}

local empty = require('lualine.component'):extend()
function empty:draw(default_highlight)
        self.status = ''
        self.applied_separator = ''
        self:apply_highlights(default_highlight)
        self:apply_section_separators()
        return self.status
end

-- Put proper separators and gaps between components in sections
local function process_sections(sections)
        for name, section in pairs(sections) do
                local left = name:sub(9, 10) < 'x'
                for pos = 1, name ~= 'lualine_z' and #section or #section - 1 do
                        table.insert(section, pos * 2, { empty, color = { fg = colors.white, bg = colors.white } })
                end
                for id, comp in ipairs(section) do
                        if type(comp) ~= 'table' then
                                comp = { comp }
                                section[id] = comp
                        end
                        comp.separator = left and { right = '' } or { left = '' }
                end
        end
        return sections
end

local function search_result()
        if vim.v.hlsearch == 0 then
                return ''
        end
        local last_search = vim.fn.getreg('/')
        if not last_search or last_search == '' then
                return ''
        end
        local searchcount = vim.fn.searchcount { maxcount = 9999 }
        return last_search .. '(' .. searchcount.current .. '/' .. searchcount.total .. ')'
end

local function modified()
        if vim.bo.modified then
                return '+'
        elseif vim.bo.modifiable == false or vim.bo.readonly == true then
                return '-'
        end
        return ''
end

require('lualine').setup {
        options = {
                theme = theme,
                component_separators = '',
                section_separators = { left = '', right = '' },
        },
        sections = process_sections {
                lualine_a = { 'mode' },
                lualine_b = {
                        'branch',
                        'diff',
                        {
                                'diagnostics',
                                source = { 'nvim' },
                                sections = { 'error' },
                                diagnostics_color = { error = { bg = colors.red, fg = colors.white } },
                        },
                        {
                                'diagnostics',
                                source = { 'nvim' },
                                sections = { 'warn' },
                                diagnostics_color = { warn = { bg = colors.orange, fg = colors.white } },
                        },
                        { 'filename', file_status = false, path = 1 },
                        { modified, color = { bg = colors.red } },
                        {
                                '%w',
                                cond = function()
                                        return vim.wo.previewwindow
                                end,
                        },
                        {
                                '%r',
                                cond = function()
                                        return vim.bo.readonly
                                end,
                        },
                        {
                                '%q',
                                cond = function()
                                        return vim.bo.buftype == 'quickfix'
                                end,
                        },
                },
                lualine_c = {},
                lualine_x = {},
                lualine_y = { search_result, 'filetype' },
                lualine_z = { '%l:%c', '%p%%/%L' },
        },
        inactive_sections = {
                lualine_c = { '%f %y %m' },
                lualine_x = {},
        },
}

require("dapui").setup({
        icons = { expanded = "▾", collapsed = "▸" },
        mappings = {
                -- Use a table to apply multiple mappings
                expand = { "<CR>", "<2-LeftMouse>" },
                open = "o",
                remove = "d",
                edit = "e",
                repl = "r",
                toggle = "t",
        },
        -- Expand lines larger than the window
        -- Requires >= 0.7
        expand_lines = vim.fn.has("nvim-0.7"),
        -- Layouts define sections of the screen to place windows.
        -- The position can be "left", "right", "top" or "bottom".
        -- The size specifies the height/width depending on position. It can be an Int
        -- or a Float. Integer specifies height/width directly (i.e. 20 lines/columns) while
        -- Float value specifies percentage (i.e. 0.3 - 30% of available lines/columns)
        -- Elements are the elements shown in the layout (in order).
        -- Layouts are opened in order so that earlier layouts take priority in window sizing.
        layouts = {
                {
                        elements = {
                                -- Elements can be strings or table with id and size keys.
                                { id = "scopes", size = 0.25 },
                                "breakpoints",
                                "stacks",
                                "watches",
                        },
                        size = 40, -- 40 columns
                        position = "left",
                },
                {
                        elements = {
                                "repl",
                                "console",
                        },
                        size = 0.25, -- 25% of total lines
                        position = "bottom",
                },
        },
        floating = {
                max_height = nil, -- These can be integers or a float between 0 and 1.
                max_width = nil, -- Floats will be treated as percentage of your screen.
                border = "single", -- Border style. Can be "single", "double" or "rounded"
                mappings = {
                        close = { "q", "<Esc>" },
                },
        },
        windows = { indent = 1 },
        render = {
                max_type_length = nil, -- Can be integer or nil.
        }
})

require("toggleterm").setup({
        -- size can be a number or function which is passed the current terminal
        size = function(term)
                if term.direction == "horizontal" then
                        return 15
                elseif term.direction == "vertical" then
                        return vim.o.columns * 0.40
                end
        end,
        on_open = function()
                -- Prevent infinite calls from freezing neovim.
                -- Only set these options specific to this terminal buffer.
                vim.api.nvim_set_option_value("foldmethod", "manual", { scope = "local" })
                vim.api.nvim_set_option_value("foldexpr", "0", { scope = "local" })
        end,
        open_mapping = false, -- [[<c-\>]],
        hide_numbers = true, -- hide the number column in toggleterm buffers
        shade_filetypes = {},
        shade_terminals = false,
        shading_factor = "1", -- the degree by which to darken to terminal colour, default: 1 for dark backgrounds, 3 for light
        start_in_insert = true,
        insert_mappings = true, -- whether or not the open mapping applies in insert mode
        persist_size = true,
        direction = "horizontal",
        close_on_exit = true, -- close the terminal window when the process exits
        shell = vim.o.shell, -- change the default shell
})

require("nvim-autopairs").setup{}

require('neoscroll').setup()

require('lualine').setup {
        options = {
                icons_enabled = true,
                theme = 'auto',
                component_separators = { left = '', right = ''},
                section_separators = { left = '', right = ''},
                disabled_filetypes = {
                        statusline = {},
                        winbar = {},
                },
                ignore_focus = {},
                always_divide_middle = true,
                globalstatus = false,
                refresh = {
                        statusline = 1000,
                        tabline = 1000,
                        winbar = 1000,
                }
        },
        sections = {
                lualine_a = {'mode'},
                lualine_b = {'branch', 'diff', 'diagnostics'},
                lualine_c = {'filename'},
                lualine_x = {'encoding', 'fileformat', 'filetype'},
                lualine_y = {'progress'},
                lualine_z = {'location'}
        },
        inactive_sections = {
                lualine_a = {},
                lualine_b = {},
                lualine_c = {'filename'},
                lualine_x = {'location'},
                lualine_y = {},
                lualine_z = {}
        },
        tabline = {},
        winbar = {},
        inactive_winbar = {},
        extensions = {}
}

local kind_icons = {
        Text = "",
        Method = "m",
        Function = "",
        Constructor = "",
        Field = "",
        Variable = "",
        Class = "",
        Interface = "",
        Module = "",
        Property = "",
        Unit = "",
        Value = "",
        Enum = "",
        Keyword = "",
        Snippet = "",
        Color = "",
        File = "",
        Reference = "",
        Folder = "",
        EnumMember = "",
        Constant = "",
        Struct = "",
        Event = "",
        Operator = "",
        TypeParameter = "",
}

local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities = require('cmp_nvim_lsp').update_capabilities(capabilities)

local lspconfig = require('lspconfig')

-- Enable some language servers with the additional completion capabilities offered by nvim-cmp
local servers = { 'clangd','pyright','bashls','cmake'}
for _, lsp in ipairs(servers) do
        lspconfig[lsp].setup {
                capabilities = capabilities,
        }
end

-- luasnip setup
local luasnip = require 'luasnip'

-- nvim-cmp setup
local cmp = require 'cmp'
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(),
                ['<CR>'] = cmp.mapping.confirm {
                        behavior = cmp.ConfirmBehavior.Replace,
                        select = true,
                },
                ['<Tab>'] = cmp.mapping(function(fallback)
                        if cmp.visible() then
                                cmp.select_next_item()
                        elseif luasnip.expand_or_jumpable() then
                                luasnip.expand_or_jump()
                        else
                                fallback()
                        end
                end, { 'i', 's' }),
                ['<S-Tab>'] = cmp.mapping(function(fallback)
                        if cmp.visible() then
                                cmp.select_prev_item()
                        elseif luasnip.jumpable(-1) then
                                luasnip.jump(-1)
                        else
                                fallback()
                        end
                end, { 'i', 's' }),
        }),

        formatting = {
                fields = { "kind", "abbr", "menu" },
                format = function(entry, vim_item)
                        -- Kind icons
                        vim_item.kind = string.format("%s", kind_icons[vim_item.kind])
                        vim_item.menu = ({
                                nvim_lsp = "[LSP]",
                                ultisnips = "[Snippet]",
                                buffer = "[Buffer]",
                                path = "[Path]",
                        })[entry.source.name]
                        return vim_item
                end,
        },

        sources = {
                { name = 'nvim_lsp' },
                { name = 'luasnip' },
                { name = 'buffer' },
                { name = 'path' },
        },
}

cmp.setup.cmdline('/', {
        completion = { autocomplete = false },
        sources = {
                { name = 'buffer' }
        }
})

cmp.setup.cmdline(':', {
        completion = { autocomplete = false },
        sources = cmp.config.sources({
                { name = 'path' }
        }, {
                { name = 'cmdline' }
        })
})

vim.cmd[[colorscheme nord]]

require'nvim-treesitter.configs'.setup {
        -- A list of parser names, or "all"
        ensure_installed = { "c", "lua", "python","cmake","cpp","make","bash","rust"},

        -- Install parsers synchronously (only applied to `ensure_installed`)
        sync_install = true,

        -- Automatically install missing parsers when entering buffer
        auto_install = false,

        ---- If you need to change the installation directory of the parsers (see -> Advanced Setup)
        -- parser_install_dir = "/some/path/to/store/parsers", -- Remember to run vim.opt.runtimepath:append("/some/path/to/store/parsers")!

        highlight = {
                enable = true,
                additional_vim_regex_highlighting = true,
        },
}

vim.cmd[[set noswapfile]]
vim.cmd[[set expandtab]]
vim.cmd[[set tabstop=4]]
vim.cmd[[set mouse=a]]
vim.cmd[[set selection=exclusive]]
vim.cmd[[set selectmode=mouse,key]]
vim.cmd[[set nu]]

require'nvim-tree'.setup {
        auto_close = false,
}

require('nvim-cursorline').setup {
        cursorline = {
                enable = true,
                timeout = 1000,
                number = false,
        },
        cursorword = {
                enable = true,
                min_length = 3,
                hl = { underline = true },
        }
}

vim.cmd[[map <C-n> :ToggleTerm direction=float<CR>]]

 类似资料: