--- INIT.LUA: Personal lua config files for NeoVim. -- Last Changed: 2019-01-27 -- Author: Federico Igne -- License: This file is placed in the public domain. local opt = vim.opt local cmd = vim.cmd local root = vim.env.USER == 'root' local home = vim.env.HOME local datahome = vim.env.XDG_DATA_HOME --- {{{1 General settings -- @section general -- A buffer becomes hidden when it is abandoned. opt.hidden = true -- Do not redraw the screen while executing macros or other (not explicitly -- typed) commands. This speeds up the iteration of macros and avoids -- screen flickering/lag. opt.lazyredraw = true -- If in `updatetime` milliseconds nothing is typed the swap file will -- be written to disk. Also used for the `CursorHold` autocommand event. opt.updatetime = 1000 -- Reduce the time Vim will try to recognize commands consisting of -- a sequence of keys. In particular `timeoutlen` is the timeout for -- mappings, `ttimeoutlen` is the timeout for key codes (like ). opt.timeoutlen = 2000 opt.ttimeoutlen = 100 -- Save (`:write`) current buffer automatically on a bunch of different -- situations (check `:help autowrite`). -- In particular this saves files before a `:make` command. opt.autowrite = true --- {{{1 Colour/Interface -- @section interface -- Leave n lines above/below cursor when scrolling. -- If set to a very large value the cursor line will always be in the -- middle of the window (except at the start or end of the file). opt.scrolloff = 999 -- Highlight the text line of the cursor. opt.cursorline = true -- Leave n chars on the left/right of the cursor when scrolling. opt.sidescrolloff = 20 -- Do not show current mode in status bar (remove the "-- INSERT --" -- status string. opt.showmode = false -- Use 24bit colors. opt.termguicolors = true -- Any modification to the highlights groups needs to be done here, -- before setting the colorsheme. This is because most colorschemes -- clear the highlight groups before setting them... this includes -- groups like User1-9. Setting this hook, it's possible to set custom -- colors everytime a colorscheme is reloaded. cmd([[ function! CustomColors() " Visual highlight clear Visual highlight Visual ctermbg=239 guibg=#504945 " Statusline highlight clear StatusLine highlight StatusLine ctermfg=248 ctermbg=239 guifg=#bdae93 guibg=#504945 highlight User1 ctermfg=246 ctermbg=239 guifg=#a89984 guibg=#504945 highlight User2 cterm=bold gui=bold ctermfg=248 ctermbg=239 guifg=#bdae93 guibg=#504945 highlight User3 cterm=bold gui=bold ctermfg=237 ctermbg=248 guifg=#3c3836 guibg=#bdae93 highlight User4 cterm=bold gui=bold ctermfg=237 ctermbg=3 guifg=#3c3836 guibg=#d79921 highlight User5 cterm=italic gui=italic ctermfg=248 ctermbg=239 guifg=#bdae93 guibg=#504945 " Tabline highlight TabLineSel cterm=bold gui=bold ctermfg=248 ctermbg=223 guifg=#bdae93 guibg=#282828 " Spell highlight clear SpellBad highlight clear SpellCap highlight clear SpellLocal highlight clear SpellRare highlight SpellBad cterm=underline gui=underline ctermbg=235 ctermfg=01 guibg=#282828 guifg=#cc241d highlight SpellCap cterm=underline gui=underline ctermbg=235 ctermfg=03 guibg=#282828 guifg=#d79921 highlight SpellLocal cterm=underline gui=underline ctermbg=235 ctermfg=04 guibg=#282828 guifg=#458588 highlight link SpellRare SpellLocal " LSP Diagnostics highlight clear DiagnosticUnderlineError highlight clear DiagnosticUnderlineWarn highlight clear DiagnosticUnderlineInfo highlight clear DiagnosticUnderlineHint highlight link DiagnosticUnderlineError SpellBad highlight link DiagnosticUnderlineWarn SpellCap highlight link DiagnosticUnderlineInfo SpellLocal highlight link DiagnosticUnderlineHint SpellLocal " Termdebug highlight clear debugPC highlight link debugPC SpellLocal " " Guides " " highlight ColorColumn ctermbg=237 guibg=#3c3836 " highlight LineNr cterm=NONE ctermbg=237 gui=NONE guibg=#3c3836 " " Errors " " Default highlight for errors is `reverse`d which looks terrible. " highlight clear Error " highlight clear ErrorMsg " highlight Error cterm=bold term=bold ctermbg=00 ctermfg=01 guibg=#282828 guifg=#fb4934 " highlight link Errormsg Error endfunction augroup CustomColors autocmd! autocmd ColorScheme * call CustomColors() " Highlight yanked region autocmd TextYankPost * silent! lua vim.highlight.on_yank { higroup='Visual', timeout=200 } augroup END ]]) -- Set colorscheme opt.background = "dark" cmd('colorscheme gruvbox') -- Display whitespaces with flavour opt.list = true opt.listchars = { eol = "¬", tab = "├─", trail = "·", extends = "»", precedes = "«" } -- Add visual indicator for visually wrapped lines opt.showbreak = "+" -- Keep visually wrapped lines indented opt.breakindent = true --- {{{1 Statuslines -- @section statuslines -- Statusline opt.statusline = "%!v:lua.dyamon.statusline.update()" -- Tabline opt.tabline = "%!v:lua.dyamon.tabline()" --- {{{1 Search/Completion -- @section search/completion -- Case-insensitive when searching; case-sensitive only if search string -- includes capital letters. opt.ignorecase = true opt.smartcase = true -- Show incremental effect of substitution command opt.inccommand = "nosplit" -- Don't echo search wrap messages. opt.shortmess = opt.shortmess + "s" -- Enables "fuzzyfind" in command mode. Completion via in command mode -- searches in the whole subtree of the cwd. opt.path = opt.path + "**" -- Hitting will first complete the longest common prefix; hit again -- for a complete list of possible completions (cicle through them with ). opt.wildmode = { "longest:full", "full" } -- File patterns ignored during completion. opt.wildignore = "*.o,*~" -- Java/Scala compilation files opt.wildignore = opt.wildignore + "*.class" -- Options for Insert mode completion: -- - menuone: display popup menu when there is only one match; -- - longest only insert the longest common text of the matches; -- - preview: show extra information about the currently selected -- completion in the preview window. opt.completeopt = { "longest", "menuone", "preview" } --- {{{1 Spell Checking -- @section spell checking -- Defaults to British English opt.spelllang = "en_gb" -- Camel-cased words count as multiple words opt.spelloptions = "camel" -- Use double method to compute suggestions (takes into account both syntax -- errors and words with a similar sound - useful if English is not your first -- language). opt.spellsuggest = { "double" , "15" } --- {{{1 Windows -- @section windows -- When using `:[v]split' (or any command including it) the buffer is opened -- below/right. opt.splitbelow = true opt.splitright = true --- {{{1 Editing -- @section editing -- Turn off soft wrap opt.wrap = false -- Set hard wrap to 72 columns. opt.textwidth = 72 -- Do not insert two spaces after a `.`, `?` or `!` with a join command opt.joinspaces = false -- Turn tabs into spaces but still keep some advantages of tabs opt.expandtab = true opt.smarttab = true -- Set number of spaces a tab counts for, and the number of spaces used per -- (auto)indent step opt.tabstop = 4 opt.shiftwidth = 0 -- fallback to `tabstop` -- Show matching bracket (briefly jumping for 0.n seconds) opt.showmatch = true opt.matchtime = 2 -- Add matching angle bracket opt.matchpairs = opt.matchpairs + "<:>" -- Removes and from the default `whichwrap` list, preventing -- them from moving the cursor to the next/previous line when on the -- first/last character of a line. opt.whichwrap = {} -- Allow visual-block selection to exceed text boundaries opt.virtualedit = { "block" } -- Override default `foldtext` with something like: -- -- »···[42l]···Title··················································· -- opt.foldtext = "v:lua.dyamon.foldtext()" --- {{{1 Pollution -- @section pollution -- Backup files if root then -- This is done to avoid backups for files that might contain sensible -- information. opt.backup = false opt.writebackup = false else -- Move backups out of the way opt.backupdir = datahome .. "/nvim/backup//,." -- Backup file is created *while* writing a file, and deleted -- afterwards. This gives you a backup when something goes wrong -- during a write operation. opt.backup = false opt.writebackup = false -- See this video for a good explaination of the option -- https://invidio.us/watch?v=BKSK1Dsuz_M opt.backupcopy = 'yes' end -- Swap files if root then -- This is done to avoid swap files that might contain sensible -- information. opt.swapfile = false else -- Move swap out of the way opt.directory = datahome .. "/nvim/swap//,." opt.swapfile = true end -- Undo files if not root then -- Persist undo tree in a file and restore it when reading a file. -- Avoiding this for `root` user to prevent sensible information to -- appear in undo files. opt.undodir = datahome .. "/nvim/undo//,." opt.undofile = true end if root then -- `viminfo` is reset for `root` user to avoid storing sensible -- information. opt.shada = "" opt.shadafile = 'NONE' end -- Session files (stored in $NVIM_SESSIONS) -- Note that, if using vim-obsession, it modifies `sessionoption` each call: -blank -options +tabpages -- This can be changed with a `ObsessionPre` autocommand. opt.sessionoptions = opt.sessionoptions - 'blank' --- {{{1 (Auto)commands -- @section auto-commands cmd([[ " Open a new terminal in a split (like in Vim) command -bang Term split | terminal " Delete a buffer without closing the window command -bang Bdelete bnext | bdelete # " Generate/remove ctags file command -bang TagsGenerate call v:lua.dyamon.tags.generate(0) " Create a new zettel command -bang -nargs=* ZNew call v:lua.dyamon.zettel.new(0, '', ) " Open zettelkasten index command ZKasten call v:lua.dyamon.zettel.kasten('') " Search zettelkasten by title command ZSearch call v:lua.dyamon.zettel.find_files() " Search zettelkasten by content command ZGrep call v:lua.dyamon.zettel.live_grep() ]]) cmd([[ " Copy the Markdown link (and line) of current zettel to register z command -buffer -bang -register ZLinkYank call v:lua.dyamon.zettel.link_yank(0, '') ]]) cmd([[ " Terminal autocommands (to make it more Vim-like) augroup dyamon_terminal autocmd TermOpen,BufWinEnter term://* startinsert autocmd TermClose * lua vim.api.nvim_input('') " Termdebug autocommands augroup dyamon_termdebug autocmd User TermdebugStartPre set number autocmd User TermdebugStopPost set nonumber " Zettel autocommands augroup dyamon_zettel autocmd BufEnter $NOTES/\d\\\{12\}.md lcd $NOTES autocmd BufNewFile,BufFilePre,BufRead $NOTES/\d\\\{12\}.md set filetype=markdown.pandoc autocmd BufEnter $NOTES/\d\\\{12\}.md call v:lua.dyamon.zettel.setup() " Reset autogroup augroup END ]]) --- {{{1 Languages -- @section languages -- Set filetype of *.tex files to `tex` by default (instead of `plaintex`) vim.g.tex_flavor = "latex" --- {{{1 LSP -- @section lsp -- Set custom diagnostic message for lTeX LSP -- @note this is used by `vim.diagnostic.open_float()`. vim.diagnostic.config({ float = { focusable = false, format = function(diagnostic) local msg = diagnostic.message if diagnostic.source == "LTeX" then msg = "["..diagnostic.user_data.lsp.code.."] "..msg end return msg end } }) -- Set diagnostics gutter signs local signs = { 'Error', 'Warn', 'Hint', 'Info' } for _,sign in ipairs(signs) do local hl = "DiagnosticSign" .. sign vim.fn.sign_define(hl, { text = "▐", texthl = hl, linehl = '', numhl = '' }) end -- Show diagnostics on hover vim.cmd [[ autocmd CursorHold * lua vim.diagnostic.open_float() ]] --- {{{1 Plugins loading -- @section plugins loading local plugins = { eager = {}, lazy = { 'gitsigns.nvim', 'gruvbox', 'matchit', 'neovim-tasks', 'nnn.nvim', 'nvim-lspconfig', 'nlsp-settings.nvim', 'plenary.nvim', 'telescope-fzf-native.nvim', 'telescope.nvim', 'vim-commentary', 'vim-fugitive', 'vim-obsession', 'vim-pandoc-syntax', 'vim-surround', 'zen-mode.nvim' } } for _, p in ipairs(plugins.lazy) do cmd('packadd! ' .. p) end --- {{{1 Plugins -- @section plugins --- {{{2 GITSIGNS.NVIM -- https://github.com/lewis6991/gitsigns.nvim require('gitsigns').setup { signs = { add = {hl = 'GitSignsAdd' , text = '▐', numhl='GitSignsAddNr' , linehl='GitSignsAddLn'}, change = {hl = 'GitSignsChange', text = '▐', numhl='GitSignsChangeNr', linehl='GitSignsChangeLn'}, delete = {hl = 'GitSignsDelete', text = '▐', numhl='GitSignsDeleteNr', linehl='GitSignsDeleteLn'}, topdelete = {hl = 'GitSignsDelete', text = '▐', numhl='GitSignsDeleteNr', linehl='GitSignsDeleteLn'}, changedelete = {hl = 'GitSignsChange', text = '▐', numhl='GitSignsChangeNr', linehl='GitSignsChangeLn'}, }, signcolumn = false, numhl = false, linehl = false, word_diff = false, keymaps = { }, watch_gitdir = { interval = 1000, follow_files = true }, attach_to_untracked = true, current_line_blame = false, sign_priority = 6, } --- {{{2 GRUVBOX -- https://github.com/gruvbox-community/gruvbox vim.g.gruvbox_italic = true --- {{{2 NEOVIM-TASKS -- https://github.com/Shatur/neovim-tasks local Path = require('plenary.path') require('tasks').setup({ default_params = { cmake = { cmd = 'cmake', build_dir = tostring(Path:new('{cwd}', 'build', '{os}-{build_type}')), build_type = 'Debug', args = { configure = { '-D', 'CMAKE_EXPORT_COMPILE_COMMANDS=1' }, build = { '-j', tonumber(vim.fn.systemlist({ "nproc", "--all" })[1])-1 }, }, }, docker = { cmd = 'docker', args = { up = { "docker-compose.yml" } } }, }, save_before_run = true, params_file = '.tasks.json', quickfix = { pos = 'botright', height = 15, }, }) --- {{{2 NNN.NVIM -- https://github.com/luukvbaal/nnn.nvim.git local nnn = require 'nnn' nnn.setup { picker = { style = { width = 3/4, height = 2/3, xoffset = 1/2, yoffset = 1/2, border = "rounded" } }, replace_netrw = "picker", auto_open = { tabpage = nil, }, mappings = { { "", nnn.builtin.open_in_split }, { "", nnn.builtin.open_in_vsplit }, { "", nnn.builtin.open_in_tab }, }, } --- {{{2 NLSP-SETTINGS.NVIM -- https://github.com/tamago324/nlsp-settings.nvim.git local lspsettings = require("nlspsettings") -- NOTE: call this before setting up lsp-config to get automatic loading on -- JSON config. This is because this call of `lspsettings.setup` injects some -- code into the `lspconfig..setup` via the `on_new_config` callback. lspsettings.setup({ config_home = vim.fn.stdpath('config') .. '/lsp-settings', local_settings_dir = ".lsp-settings", local_settings_root_markers = { '.git' }, append_default_schemas = true, loader = 'json' }) --- {{{2 NVIM-LSPCONFIG -- https://github.com/neovim/nvim-lspconfig.git local lsp = require'dyamon'.lsp local lspconfig = require 'lspconfig' local function lsp_common_config(on_attach) local on_attach = on_attach or lsp.on_attach_common return { on_attach = on_attach, handlers = { ['textDocument/publishDiagnostics'] = vim.lsp.with(vim.lsp.diagnostic.on_publish_diagnostics, { virtual_text = false, signs = true, underline = true, update_in_insert = false, }), ["textDocument/hover"] = vim.lsp.with(vim.lsp.handlers.hover, { border = 'rounded' }), ["textDocument/signatureHelp"] = vim.lsp.with(vim.lsp.handlers.signature_help, { border = 'rounded' }) } } end --- {{{3 METALS -- Setup Scala Metals lspconfig.metals.setup(lsp_common_config()) --- {{{3 RUST ANALYZER -- Setup Rust Analyzer lspconfig.rust_analyzer.setup(lsp_common_config()) --- {{{3 CLANGD -- Setup ClangD lspconfig.clangd.setup( lsp_common_config( lsp.on_attach_clangd)) --- {{{3 LTEX -- Setup lTeX local lsp_ltex = { on_attach = require'dyamon'.lsp.on_attach_ltex, autostart = false, filetypes = { "bib", "markdown", "plaintex", "rst", "tex" }, single_file_support = false, handlers = { ['textDocument/publishDiagnostics'] = vim.lsp.with(vim.lsp.diagnostic.on_publish_diagnostics, { virtual_text = false, signs = true, underline = true, update_in_insert = false, }), }, on_init = function(client) local fn = vim.fn local readfile, writefile = fn.readfile, fn.writefile local json_encode, json_decode = fn.json_encode, fn.json_decode local config = client.config local settings_file = config.root_dir .. "/" .. config.settings.dyamon.localSettings if not fn.filereadable(settings_file) then settings_file = fn.expand(config.settings.dyamon.globalSettings) end function add(rules, field_name) local settings = json_decode(readfile(settings_file)) local field = settings[field_name] if not field then settings[field_name] = rules else for language, rules in pairs(rules) do if not field[language] then field[language] = rules else for _, rule in ipairs(rules) do table.insert(field[language], rule) end end end end settings = vim.fn.split(vim.fn.json_encode(settings), '\n') vim.fn.writefile(settings, settings_file) vim.cmd[[ LspSettings update ltex ]] end client.commands['_ltex.disableRules'] = function(args, ctx) add(args.arguments[1].ruleIds, "ltex.disabledRules") end client.commands['_ltex.hideFalsePositives'] = function(args, ctx) add(args.arguments[1].falsePositives, "ltex.hiddenFalsePositives") end client.commands['_ltex.addToDictionary'] = function(args, ctx) add(args.arguments[1].words, "ltex.dictionary") end end } lspconfig.ltex.setup(lsp_ltex) --- {{{2 TELESCOPE.NVIM -- https://github.com/nvim-telescope/telescope.nvim.git require('telescope').setup { defaults = { mappings = { i = { [""] = "select_horizontal", }, }, layout_strategy = 'flex', --layout_strategy = 'vertical', layout_config = { flex = { flip_columns = 120, horizontal = { preview_width = .55, }, vertical = { preview_height = .60, }, }, }, }, extensions = { fzf = { fuzzy = true, override_generic_sorter = true, override_file_sorter = true, case_mode = "smart_case", } } } -- Load fzf-native extension require('telescope').load_extension('fzf') -- --- {{{2 TERMDEBUG -- builtin plugin -- TODO fix "missing separate debuginfo" error in GDB vim.g.termdebug_map_K = 0 vim.g.termdebug_disasm_window = 15 vim.g.termdebug_useFloatingHover = 0 vim.g.termdebug_wide = 1 --- {{{2 VIM-OBSESSION -- https://github.com/tpope/vim-obsession -- The plugin is not designed to be used with tab-wise sessions, but -- using the custom autocommand `ObsessionPre` and some scripting we are -- able to achieve that (see `lua/dyamon/session.vim`) cmd([[ autocmd User ObsessionPre lua require('dyamon').session.pre() ]]) --- {{{2 VIM-PANDOC-SYNTAX -- https://github.com/vim-pandoc/vim-pandoc-syntax vim.g["pandoc#syntax#conceal#urls"] = true vim.g["pandoc#syntax#codeblocks#embeds#use"] = true vim.g["pandoc#syntax#codeblocks#embeds#langs"] = { "cpp", "bash", "bash=sh", "dockerfile", "yaml" } --- {{{2 VIM-SLIME -- https://github.com/jpalardy/vim-slime vim.g.slime_target = "neovim" vim.g.slime_no_mappings = 1 --- {{{2 VIM-SURROUND -- https://github.com/tpope/vim-surround -- Insert checkpoint at the end of insert-mode vim-surround mappings. vim.g.surround_insert_tail = "<++>" --- {{{2 ZEN-MODE.NVIM -- https://github.com/folke/zen-mode.nvim.git require('zen-mode').setup { window = { width = function() return math.min(vim.o.columns, 90) end, height = function() local rows = vim.o.lines return math.min(rows, math.max(24, math.floor(2*rows/3))) end, } } --- {{{1 End -- vim: foldmethod=marker