Skip to content

Instantly share code, notes, and snippets.

@apokalyptik
Created March 16, 2023 17:56
Show Gist options
  • Save apokalyptik/1388db585fbaf9caebfe1ea62bc7e5a7 to your computer and use it in GitHub Desktop.
Save apokalyptik/1388db585fbaf9caebfe1ea62bc7e5a7 to your computer and use it in GitHub Desktop.
My NVIM configuration
-- Install packer
local install_path = vim.fn.stdpath 'data' .. '/site/pack/packer/start/packer.nvim'
local is_bootstrap = false
if vim.fn.empty(vim.fn.glob(install_path)) > 0 then
is_bootstrap = true
vim.fn.system { 'git', 'clone', '--depth', '1', 'https://github.com/wbthomason/packer.nvim', install_path }
vim.cmd [[packadd packer.nvim]]
end
require('packer').startup(function(use)
-- Package manager
use 'wbthomason/packer.nvim'
use 'tpope/vim-vividchalk'
use 'aperezdc/vim-elrond'
use 'patstockwell/vim-monokai-tasty'
use( 'nvim-treesitter/nvim-treesitter', { run = ':TSUpdate' } )
use( 'nvim-treesitter/playground' )
use( 'mbbill/undotree' )
use {
'VonHeikemen/lsp-zero.nvim',
branch = 'v1.x',
requires = {
-- LSP Support
{ 'neovim/nvim-lspconfig' }, -- Required
{ 'williamboman/mason.nvim' }, -- Optional
{ 'williamboman/mason-lspconfig.nvim' }, -- Optional
-- Useful status updates for LSP
'j-hui/fidget.nvim',
-- Autocompletion
{ 'hrsh7th/nvim-cmp' }, -- Required
{ 'hrsh7th/cmp-nvim-lsp' }, -- Required
{ 'hrsh7th/cmp-buffer' }, -- Optional
{ 'hrsh7th/cmp-path' }, -- Optional
{ 'hrsh7th/cmp-nvim-lua' }, -- Optional
-- Snippets
--{ 'L3MON4D3/LuaSnip' }, -- Required
--{ 'saadparwaiz1/cmp_luasnip' }, -- Optional for autocompletion
--{ 'rafamadriz/friendly-snippets' }, -- Optional
-- Additional lua configuration, makes nvim stuff amazing
'folke/neodev.nvim',
}
}
use { -- Additional text objects via treesitter
'nvim-treesitter/nvim-treesitter-textobjects',
after = 'nvim-treesitter',
}
-- Git related plugins
use 'tpope/vim-fugitive'
use 'tpope/vim-rhubarb'
use 'lewis6991/gitsigns.nvim'
use 'nvim-lualine/lualine.nvim' -- Fancier statusline
use 'lukas-reineke/indent-blankline.nvim' -- Add indentation guides even on blank lines
use 'numToStr/Comment.nvim' -- "gc" to comment visual regions/lines
use 'tpope/vim-sleuth' -- Detect tabstop and shiftwidth automatically
-- Fuzzy Finder (files, lsp, etc)
use { 'nvim-telescope/telescope.nvim', branch = '0.1.x', requires = { 'nvim-lua/plenary.nvim' } }
-- Fuzzy Finder Algorithm which requires local dependencies to be built. Only load if `make` is available
use { 'nvim-telescope/telescope-fzf-native.nvim', run = 'make', cond = vim.fn.executable 'make' == 1 }
use 'ray-x/go.nvim'
use 'ray-x/guihua.lua' -- recommended if need floating window support
use 'apokalyptik/vim-servers-dot-dat'
use 'nvim-tree/nvim-web-devicons'
use {'romgrk/barbar.nvim', requires = 'nvim-web-devicons'}
use {
'nvim-tree/nvim-tree.lua',
requires = {
'nvim-tree/nvim-web-devicons', -- optional
},
}
-- Add custom plugins to packer from ~/.config/nvim/lua/custom/plugins.lua
local has_plugins, plugins = pcall(require, 'custom.plugins')
if has_plugins then
plugins(use)
end
if is_bootstrap then
require('packer').sync()
end
end)
-- When we are bootstrapping a configuration, it doesn't
-- make sense to execute the rest of the init.lua.
--
-- You'll need to restart nvim, and then it will work.
if is_bootstrap then
print '=================================='
print ' Plugins are being installed'
print ' Wait until Packer completes,'
print ' then restart nvim'
print '=================================='
return
end
-- General [N]VIM setup
-- Set <space> as the leader key See `:help mapleader`
-- NOTE: Must happen before plugins are required (otherwise wrong leader will be used)
vim.g.mapleader = ' '
vim.g.maplocalleader = ' '
-- disable netrw at the very start of your init.lua (strongly advised)
vim.g.loaded_netrw = 1
vim.g.loaded_netrwPlugin = 1
-- set termguicolors to enable highlight groups
vim.opt.termguicolors = true
-- Tabs
vim.opt.autoindent = true
vim.opt.smartindent = true
vim.opt.cindent = true
vim.opt.cinoptions = "l1"
vim.opt.tabstop = 8
vim.opt.shiftwidth = 8
vim.opt.expandtab = true
-- Completion helpers
vim.opt.ignorecase = true
vim.opt.infercase = true
-- Searching and spelling
vim.opt.hlsearch = true
vim.opt.spell = true
vim.opt.spelllang = "en_us"
vim.opt.hlsearch = true
-- Line Numbers
vim.opt.number = true
-- Set colorscheme
vim.o.termguicolors = true
vim.cmd [[
colorscheme vividchalk
set background=dark
syntax on
]]
-- Persistent undo
vim.cmd [[
let vimDir = '$HOME/.nvim'
let &runtimepath.=','.vimDir
if has('persistent_undo')
let myUndoDir = expand(vimDir . '/undodir')
call system('mkdir ' . vimDir)
call system('mkdir ' . myUndoDir)
let &undodir = myUndoDir
set undofile
endif
]]
-- indentation
vim.o.cindent = true
vim.o.cinwords = "if,else,while,do,for,switch,case"
vim.o.autoindent = true
-- better in/outdenting with visual selection
vim.api.nvim_set_keymap('v', '<', '<gv', {noremap = true})
vim.api.nvim_set_keymap('v', '>', '>gv', {noremap = true})
-- Enable break indent
vim.o.breakindent = true
-- Enable mouse mode
vim.o.mouse = 'a'
-- Decrease update time
vim.o.updatetime = 250
vim.wo.signcolumn = 'yes'
-- Set completeopt to have a better completion experience
vim.o.completeopt = 'menuone,noselect'
-- Keymaps for better default experience See `:help vim.keymap.set()`
vim.keymap.set({ 'n', 'v' }, '<Space>', '<Nop>', { silent = true })
-- Remap for dealing with word wrap
vim.keymap.set('n', 'k', "v:count == 0 ? 'gk' : 'k'", { expr = true, silent = true })
vim.keymap.set('n', 'j', "v:count == 0 ? 'gj' : 'j'", { expr = true, silent = true })
-- Automatically source and re-compile packer whenever you save this init.lua
local packer_group = vim.api.nvim_create_augroup('Packer', { clear = true })
vim.api.nvim_create_autocmd('BufWritePost', {
command = 'source <afile> | silent! LspStop | silent! LspStart | PackerCompile',
group = packer_group,
pattern = vim.fn.expand '$MYVIMRC',
})
-- for nvim-tree
require("nvim-tree").setup({
sort_by = "case_sensitive",
renderer = {
group_empty = true,
},
filters = {
dotfiles = true,
},
})
vim.api.nvim_set_keymap('n', '<leader>fs', ':NvimTreeToggle<CR>', {noremap = true, silent = true})
-- [[ Highlight on yank ]] See `:help vim.highlight.on_yank()`
local highlight_group = vim.api.nvim_create_augroup('YankHighlight', { clear = true })
vim.api.nvim_create_autocmd('TextYankPost', {
callback = function()
vim.highlight.on_yank()
end,
group = highlight_group,
pattern = '*',
})
-- Set lualine as statusline See `:help lualine.txt`
require('lualine').setup {
options = {
icons_enabled = false,
theme = 'onedark',
component_separators = '|',
section_separators = '',
disabled_filetypes = { 'serversdat' },
},
}
-- Enable Comment.nvim
require('Comment').setup()
-- Enable `lukas-reineke/indent-blankline.nvim` See `:help indent_blankline.txt`
require('indent_blankline').setup {
char = '┊',
show_trailing_blankline_indent = false,
}
-- Gitsigns
-- See `:help gitsigns.txt`
require('gitsigns').setup {
signs = {
add = { text = '+' },
change = { text = '~' },
delete = { text = '_' },
topdelete = { text = '‾' },
changedelete = { text = '~' },
},
}
-- [[ Configure Telescope ]]
-- See `:help telescope` and `:help telescope.setup()`
require('telescope').setup {
defaults = {
mappings = {
i = {
['<C-u>'] = false,
['<C-d>'] = false,
},
},
},
}
-- Enable telescope fzf native, if installed
pcall( require( 'telescope' ).load_extension, 'fzf' )
-- See `:help telescope.builtin`
vim.keymap.set('n', '<leader>?', require('telescope.builtin').oldfiles, { desc = '[?] Find recently opened files' })
vim.keymap.set('n', '<leader><space>', require('telescope.builtin').buffers, { desc = '[ ] Find existing buffers' })
vim.keymap.set('n', '<leader>/', function()
-- You can pass additional configuration to telescope to change theme, layout, etc.
require('telescope.builtin').current_buffer_fuzzy_find(require('telescope.themes').get_dropdown {
winblend = 10,
previewer = false,
})
end, { desc = '[/] Fuzzily search in current buffer]' })
vim.keymap.set('n', '<leader>sf', require('telescope.builtin').find_files, { desc = '[S]earch [F]iles' })
vim.keymap.set('n', '<leader>sh', require('telescope.builtin').help_tags, { desc = '[S]earch [H]elp' })
vim.keymap.set('n', '<leader>sw', require('telescope.builtin').grep_string, { desc = '[S]earch current [W]ord' })
vim.keymap.set('n', '<leader>sg', require('telescope.builtin').live_grep, { desc = '[S]earch by [G]rep' })
vim.keymap.set('n', '<leader>sd', require('telescope.builtin').diagnostics, { desc = '[S]earch [D]iagnostics' })
-- Treesitter
require 'nvim-treesitter.configs'.setup {
-- A list of parser names, or "all" (the four listed parsers should always be installed)
ensure_installed = { "c", "lua", "vim", "help", "php", "javascript", "typescript", "go", "html", "css", "make", "json", "diff" },
-- Install parsers synchronously (only applied to `ensure_installed`)
sync_install = false,
-- Automatically install missing parsers when entering buffer
-- Recommendation: set to false if you don't have `tree-sitter` CLI installed locally
auto_install = true,
indent = {
enable = true,
},
-- List of parsers to ignore installing (for "all")
-- ignore_install = { "javascript" },
---- 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 = {
-- `false` will disable the whole extension
enable = true,
-- NOTE: these are the names of the parsers and not the filetype. (for example if you want to
-- disable highlighting for the `tex` filetype, you need to include `latex` in this list as this is
-- the name of the parser)
-- list of language that will be disabled
-- disable = { "c", "rust" },
-- Or use a function for more flexibility, e.g. to disable slow treesitter highlight for large files
disable = function(lang, buf)
local max_filesize = 1024 * 1024 -- 1mb
local ok, stats = pcall(vim.loop.fs_stat, vim.api.nvim_buf_get_name(buf))
if ok and stats and stats.size > max_filesize then
return true
end
end,
-- Setting this to true will run `:h syntax` and tree-sitter at the same time.
-- Set this to `true` if you depend on 'syntax' being enabled (like for indentation).
-- Using this option may slow down your editor, and you may see some duplicate highlights.
-- Instead of true it can also be a list of languages
additional_vim_regex_highlighting = { "diff" },
},
}
-- LSP
-- Learn the keybindings, see :help lsp-zero-keybindings
-- Learn to configure LSP servers, see :help lsp-zero-api-showcase
local lsp = require('lsp-zero')
lsp.preset('recommended')
-- (Optional) Configure lua language server for neovim
lsp.nvim_workspace()
lsp.setup()
-- Diagnostic keymaps
vim.keymap.set('n', '[d', vim.diagnostic.goto_prev)
vim.keymap.set('n', ']d', vim.diagnostic.goto_next)
vim.keymap.set('n', '<leader>e', vim.diagnostic.open_float)
vim.keymap.set('n', '<leader>q', vim.diagnostic.setloclist)
-- LSP settings.
-- This function gets run when an LSP connects to a particular buffer.
local on_attach = function(_, bufnr)
-- NOTE: Remember that lua is a real programming language, and as such it is possible
-- to define small helper and utility functions so you don't have to repeat yourself
-- many times.
--
-- In this case, we create a function that lets us more easily define mappings specific
-- for LSP related items. It sets the mode, buffer and description for us each time.
local nmap = function(keys, func, desc)
if desc then
desc = 'LSP: ' .. desc
end
vim.keymap.set('n', keys, func, { buffer = bufnr, desc = desc })
end
nmap('<leader>rn', vim.lsp.buf.rename, '[R]e[n]ame')
nmap('<leader>ca', vim.lsp.buf.code_action, '[C]ode [A]ction')
nmap('gd', vim.lsp.buf.definition, '[G]oto [D]efinition')
nmap('gr', require('telescope.builtin').lsp_references, '[G]oto [R]eferences')
nmap('gI', vim.lsp.buf.implementation, '[G]oto [I]mplementation')
nmap('<leader>D', vim.lsp.buf.type_definition, 'Type [D]efinition')
nmap('<leader>ds', require('telescope.builtin').lsp_document_symbols, '[D]ocument [S]ymbols')
nmap('<leader>ws', require('telescope.builtin').lsp_dynamic_workspace_symbols, '[W]orkspace [S]ymbols')
-- See `:help K` for why this keymap
nmap('K', vim.lsp.buf.hover, 'Hover Documentation')
nmap('<C-k>', vim.lsp.buf.signature_help, 'Signature Documentation')
-- Lesser used LSP functionality
nmap('gD', vim.lsp.buf.declaration, '[G]oto [D]eclaration')
nmap('<leader>wa', vim.lsp.buf.add_workspace_folder, '[W]orkspace [A]dd Folder')
nmap('<leader>wr', vim.lsp.buf.remove_workspace_folder, '[W]orkspace [R]emove Folder')
nmap('<leader>wl', function()
print(vim.inspect(vim.lsp.buf.list_workspace_folders()))
end, '[W]orkspace [L]ist Folders')
-- Create a command `:Format` local to the LSP buffer
vim.api.nvim_buf_create_user_command(bufnr, 'Format', function(_)
vim.lsp.buf.format()
end, { desc = 'Format current buffer with LSP' })
end
-- Enable the following language servers
-- Feel free to add/remove any LSPs that you want here. They will automatically be installed.
--
-- Add any additional override configuration in the following tables. They will be passed to
-- the `settings` field of the server config. You must look up that documentation yourself.
local servers = {
-- clangd = {},
-- gopls = {},
-- pyright = {},
-- rust_analyzer = {},
-- tsserver = {},
intelephense = {
files = {
exclude = {
'**/blogs.dir/**',
"/home/wpcom/public_html/wp-content/blogs.dir/**",
},
},
intelephense = {
files = {
exclude = {
'**/blogs.dir/**',
"/home/wpcom/public_html/wp-content/blogs.dir/**",
},
},
},
},
lua_ls = {
Lua = {
workspace = { checkThirdParty = false },
telemetry = { enable = false },
},
},
}
-- Setup neovim lua configuration
require('neodev').setup()
--
-- nvim-cmp supports additional completion capabilities, so broadcast that to servers
local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities = require('cmp_nvim_lsp').default_capabilities(capabilities)
-- Setup mason so it can manage external tooling
require('mason').setup()
-- Ensure the servers above are installed
local mason_lspconfig = require 'mason-lspconfig'
mason_lspconfig.setup {
ensure_installed = vim.tbl_keys(servers),
}
mason_lspconfig.setup_handlers {
function(server_name)
require('lspconfig')[server_name].setup {
capabilities = capabilities,
on_attach = on_attach,
settings = servers[server_name],
}
end,
}
-- Turn on lsp status information
require('fidget').setup()
-- nvim-cmp setup
local cmp = require 'cmp'
-- local luasnip = require 'luasnip'
cmp.setup {
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()
else
fallback()
end
end, { 'i', 's' }),
['<S-Tab>'] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_prev_item()
else
fallback()
end
end, { 'i', 's' }),
},
sources = {
{ name = 'nvim_lsp' },
},
}
local format_sync_grp = vim.api.nvim_create_augroup("GoFormat", {})
vim.api.nvim_create_autocmd("BufWritePre", {
pattern = "*.go",
callback = function()
require('go.format').goimport()
end,
group = format_sync_grp,
})
require('go').setup()
require('lualine').setup {
options = {
theme = "dracula"
},
extensions = {
'quickfix'
}
}
-- vim.lsp.set_log_level('debug')
-- The line beneath this is called `modeline`. See `:help modeline`
-- vim: ts=2 sts=2 sw=2 et
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment