Skip to content

02. Configs

Biser Stoilov edited this page Nov 15, 2021 · 4 revisions

Configs

1. Default configs

1.1. Base configs

Vim
-- lua/configs/global/init.lua

local lvim = require("configs.global.lvim")

configs["vim_global"] = function()
    lvim.global()
    lvim.set()
end

-- lua/configs/global/lvim.lua

local global = require("core.global")
local funcs = require("core.funcs")

local M = {}

M.global = function()
    local global_opt = {
        background = "dark",
        termguicolors = true,
        mouse = "nv",
        errorbells = true,
        visualbell = true,
        hidden = true,
        fileformats = "unix,mac,dos",
        magic = true,
        virtualedit = "block",
        encoding = "utf-8",
        viewoptions = "folds,cursor,curdir,slash,unix",
        sessionoptions = "curdir,help,tabpages,winsize",
        clipboard = "unnamedplus",
        wildignorecase = true,
        wildignore = ".git,.hg,.svn,*.pyc,*.o,*.out,*.jpg,*.jpeg,*.png,*.gif,*.zip," ..
            "**/tmp/**,*.DS_Store,**/node_modules/**,**/bower_modules/**",
        backup = false,
        writebackup = false,
        undofile = true,
        swapfile = false,
        directory = global.cache_path .. "swag/",
        undodir = global.cache_path .. "undo/",
        backupdir = global.cache_path .. "backup/",
        viewdir = global.cache_path .. "view/",
        spellfile = global.cache_path .. "spell/en.uft-8.add",
        history = 2000,
        shada = "!,'300,<50,@100,s10,h",
        backupskip = "/tmp/*,$TMPDIR/*,$TMP/*,$TEMP/*,*/shm/*,/private/var/*,.vault.vim",
        smarttab = true,
        shiftround = true,
        timeout = true,
        ttimeout = true,
        timeoutlen = 500,
        ttimeoutlen = 10,
        updatetime = 100,
        redrawtime = 1500,
        ignorecase = true,
        smartcase = true,
        infercase = true,
        incsearch = true,
        wrapscan = true,
        complete = ".,w,b,k",
        inccommand = "nosplit",
        grepformat = "%f:%l:%c:%m",
        grepprg = "rg --hidden --vimgrep --smart-case --",
        breakat = [[\ \	;:,!?]],
        startofline = false,
        whichwrap = "h,l,<,>,[,],~",
        splitbelow = true,
        splitright = true,
        switchbuf = "useopen",
        backspace = "indent,eol,start",
        diffopt = "filler,iwhite,internal,algorithm:patience",
        completeopt = "menuone,noselect",
        jumpoptions = "stack",
        showmode = false,
        shortmess = "aoOTIcF",
        scrolloff = 2,
        sidescrolloff = 5,
        foldlevelstart = 99,
        ruler = true,
        list = true,
        showtabline = 0,
        winwidth = 30,
        winminwidth = 10,
        pumheight = 15,
        helpheight = 12,
        previewheight = 12,
        showcmd = false,
        cmdheight = 2,
        cmdwinheight = 5,
        equalalways = false,
        laststatus = 2,
        display = "lastline",
        foldmethod = "indent",
        cursorline = true,
        cursorcolumn = true,
        showbreak = "",
        listchars = "tab:»·,nbsp:+,trail:·,extends:→,precedes:←",
        pumblend = 10,
        winblend = 10
    }
    funcs.options_global(global_opt)
end

M.set = function()
    local set_opt = {
        number = true,
        relativenumber = true,
        nocompatible = true,
        wrap = true,
        cmdheight = 1,
        synmaxcol = 2500,
        formatoptions = "1jcroql",
        textwidth = 80,
        expandtab = true,
        autoindent = true,
        signcolumn = "yes",
        tabstop = 4,
        shiftwidth = 4,
        softtabstop = -1,
        breakindentopt = "shift:2,min:20",
        linebreak = true,
        colorcolumn = "80",
        foldenable = true,
        conceallevel = 2,
        concealcursor = "niv"
    }
    funcs.options_set(set_opt)
end

return M
Events
-- lua/configs/global/init.lua

configs["events_global"] = function()
    funcs.augroups(
        {
            bufs = {
                {
                    "BufWinEnter",
                    "*",
                    "setlocal formatoptions-=c formatoptions-=r formatoptions-=o "
                },
                {
                    "BufRead",
                    "*",
                    "setlocal formatoptions-=c formatoptions-=r formatoptions-=o "
                },
                {
                    "BufNewFile",
                    "*",
                    "setlocal formatoptions-=c formatoptions-=r formatoptions-=o "
                },
                {"BufNewFile,BufRead", "*.ex", "set filetype=elixir"},
                {"BufNewFile,BufRead", "*.exs", "set filetype=elixir"},
                {"BufNewFile,BufRead", "*.graphql", "set filetype=graphql"},
                {"BufWinEnter", "NvimTree", "setlocal colorcolumn=0 nocursorcolumn"}
            },
            yank = {
                {
                    "TextYankPost",
                    [[* silent! lua vim.highlight.on_yank({higroup='IncSearch', timeout=400})]]
                }
            },
            ft = {
                {"FileType", "dart", "setlocal ts=2 sw=2"},
                {"FileType", "ruby", "setlocal ts=2 sw=2"},
                {"FileType", "yaml", "setlocal ts=2 sw=2"},
                {"FileType", "c", "setlocal ts=2 sw=2"},
                {"FileType", "cpp", "setlocal ts=2 sw=2"},
                {"FileType", "objc", "setlocal ts=2 sw=2"},
                {"FileType", "objcpp", "setlocal ts=2 sw=2"},
                {"FileType", "help", "setlocal colorcolumn=0 nocursorcolumn"},
                {"FileType", "dashboard", "setlocal nowrap"},
                {"FileType", "Trouble", "setlocal colorcolumn=0 nocursorcolumn"},
                {"FileType", "Outline", "setlocal colorcolumn=0 nocursorcolumn"},
                {"FileType", "VimspectorPrompt", "setlocal colorcolumn=0 nocursorcolumn"},
                {"FileType", "git", "setlocal colorcolumn=0 nocursorcolumn"},
                {"FileType", "packer", "setlocal colorcolumn=0 nocursorcolumn"},
                {"FileType", "dapui_scopes", "setlocal colorcolumn=0 nocursorcolumn"},
                {
                    "FileType",
                    "dapui_breakpoints",
                    "set colorcolumn=0 nocursorcolumn"
                },
                {"FileType", "dapui_stacks", "setlocal colorcolumn=0 nocursorcolumn"},
                {"FileType", "dapui_watches", "setlocal colorcolumn=0 nocursorcolumn"},
                {"FileType", "NeogitStatus", "setlocal colorcolumn=0 nocursorcolumn"}
            }
        }
    )
end
Languages

LVIM has defined settings for the most commonly used programming languages.

LVIM supports personal language settings for each project.


IMPORTANT: For more information, see page 03. Languages




-- lua/configs/global/init.lua

configs["languages_global"] = function()
    funcs.augroups(
        {
            languages_setup = {
                {"BufWinEnter", "*", 'lua require("languages.global").setup()'}
            }
        }
    )
end

-- lua/languages/global/init.lua

local global = require("core.global")
local funcs = require("core.funcs")
local M = {}

M.filetypes = {
    ["angular"] = {
        "typescript",
        "html",
        "typescriptreact",
        "typescript.tsx"
    },
    ["cpp"] = {
        "c",
        "cpp",
        "objc",
        "objcpp"
    },
    ["css"] = {
        "css",
        "scss",
        "less"
    },
    ["dart"] = {"dart"},
    ["go"] = {"go", "gomod"},
    ["graphql"] = {"graphql"},
    ["html"] = {"html"},
    ["java"] = {"java"},
    ["json"] = {"json"},
    ["jsts"] = {
        "javascript",
        "typescript",
        "javascriptreact",
        "typescriptreact"
    },
    ["lua"] = {"lua"},
    ["php"] = {"php"},
    ["python"] = {"python"},
    ["ruby"] = {"ruby"},
    ["rust"] = {"rust"},
    ["shell"] = {"sh"},
    ["vim"] = {"vim"},
    ["vue"] = {"vue"},
    ["yaml"] = {"yaml"}
}

M.setup = function()
    local filetype = vim.bo.filetype
    local project_root_path = vim.fn.getcwd()
    for language, v in pairs(M.filetypes) do
        for _, v2 in pairs(v) do
            if v2 == filetype then
                if global["languages"][language] ~= nil then
                    if global["languages"][language]["project_root_path"] == project_root_path then
                        -- nothing
                    else
                        if funcs.file_exists(project_root_path .. "/lvim/" .. language .. ".lua") then
                            M.kill_server(language)
                            M.pre_init_language(language, project_root_path, "custom")
                            M.init_language(language, project_root_path)
                        elseif global["languages"][language]["lsp_type"] == "global" then
                            -- nothing
                        else
                            M.kill_server(language)
                            M.pre_init_language(language, project_root_path, "global")
                            M.init_language(language, project_root_path)
                        end
                    end
                else
                    M.pre_init_language(language, project_root_path, "global")
                    M.init_language(language, project_root_path)
                end
            end
        end
    end
end

M.pre_init_language = function(language, project_root_path, lsp_type)
    global.current_pwd = project_root_path
    global["languages"][language] = {}
    global["languages"][language]["project_root_path"] = project_root_path
    global["languages"][language]["pid"] = {}
    global["languages"][language]["lsp_type"] = lsp_type
end

M.kill_server = function(language)
    if next(global["languages"][language]["pid"]) ~= nil then
        for _, pid in pairs(global["languages"][language]["pid"]) do
            os.execute("kill -9 " .. pid .. " > /dev/null 2>&1")
        end
    end
end

M.init_language = function(language, project_root_path)
    local language_configs_global = dofile(global.languages_path .. language .. ".lua")
    local language_configs
    if funcs.file_exists(project_root_path .. "/lvim/" .. language .. ".lua") then
        local language_configs_custom = dofile(project_root_path .. "/lvim/" .. language .. ".lua")
        language_configs = funcs.merge(language_configs_global, language_configs_custom)
    else
        language_configs = language_configs_global
    end
    for _, func in pairs(language_configs) do
        func()
    end
end

return M
Commands
-- lua/configs/global/init.lua

configs["commands_global"] = function()
    vim.cmd('command! SetGlobalPath lua require("core.funcs").set_global_path()')
    vim.cmd('command! SetWindowPath lua require("core.funcs").set_window_path()')
end

-- lua/core/funcs.lua

M.set_global_path = function()
    local path = M.change_path()
    vim.api.nvim_command("silent :cd " .. path)
end

M.set_window_path = function()
    local path = M.change_path()
    vim.api.nvim_command("silent :lcd " .. path)
end
Keymaps
-- lua/configs/global/init.lua

local funcs = require("core.funcs")
local keymaps = require("configs.global.keymaps")

configs["keymaps_global"] = function()
    funcs.keymaps("n", {noremap = false, silent = true}, keymaps.normal)
    funcs.keymaps("x", {noremap = false, silent = true}, keymaps.visual)
end

-- lua/configs/global/keymaps.lua

local keymaps = {}

keymaps["normal"] = {
    {"<F1>", ":TTOne<CR>"}, -- Toggleterm one open
    {"<F2>", ":TTTwo<CR>"}, -- Toggleterm two open
    {"<F3>", ":TTThree<CR>"}, -- Toggleterm three open
    {"<F4>", ":TTFloat<CR>"}, -- Toggleterm float open
    {"<F5>", ":UndotreeToggle<CR>"}, -- UndoTree toggle
    {"<F11>", ":LvimHelper<CR>"}, -- LvimHelper
    {"<C-space>", ":CtrlSpace<CR>"}, -- CtrlSpace
    {"<Esc>", "<Esc>:noh<CR>"}, -- Remove highlight after search
    {"<C-c>n", ":e %:h/filename<CR>"}, -- Create new file in current directory
    {"<C-s>", ":w<CR>"}, -- Save
    {"<C-c>a", ":wa<CR>"}, -- Save all
    {"<C-c>e", ":qa!<CR>"}, -- Close all, exit nvim
    {"<C-c>x", "<C-w>c"}, -- Close current window
    {"<C-c>o", "<C-w>o"}, -- Close other windows
    {"<C-c>d", ":bdelete<CR>"}, -- BDelete
    {"<C-c>b", ":GitBlameToggle<CR>"}, -- Git blame toggle
    {"<C-h>", "<C-w>h"}, -- Move to window left
    {"<C-l>", "<C-w>l"}, -- Move to window right
    {"<C-j>", "<C-w>j"}, -- Move to window down
    {"<C-k>", "<C-w>k"}, -- Move to window up
    {"<C-Left>", ":vertical resize -2<CR>"}, -- Resize width -
    {"<C-Right>", ":vertical resize +2<CR>"}, -- Resize width +
    {"<C-Up>", ":resize -2<CR>"}, -- Resize height -
    {"<C-Down>", ":resize +2<CR>"}, -- Resize height +
    {"<S-x>", ":NvimTreeToggle<CR>"}, -- Nvim tree explorer
    {"<S-m>", ":MarkdownPreviewToggle<CR>"}, -- Markdown preview toggle
    {"<S-n>", ":GitSignsNextHunk<CR>"}, -- Git signs next hunk
    {"<S-p>", ":GitSignsPrevHunk<CR>"}, -- Git signs prev hunk
    {"<S-u>", ":GitSignsPreviewHunk<CR>"}, -- Git signs preview hunk
    {"<A-,>", ":Telescope find_files<CR>"}, -- Search files with Telescope
    {"<A-.>", ":Telescope live_grep<CR>"}, -- Search word with Telescope
    {"<A-j>", ":AnyJump<CR>"}, -- Any jump
    {"<A-v>", ":SymbolsOutline<CR>"}, -- Symbols outline
    {"<A-[>", ":foldopen<CR>"}, -- Fold open
    {"<A-]>", ":foldclose<CR>"}, -- Fold close
    {"<A-/>", ":CommentToggle<CR>"}, -- Comment toggle
    {"<A-f>", ":LspFormatting<CR>"}, -- Lsp format code
    {"<A-t>", ":LspCodeAction<CR>"}, -- Lsp action
    {"<A-s>", ":Spectre<CR>"}, -- Replace in multiple files
    {"<A-g>", ":LspReferences<CR>"}, -- Lsp references
    {"<A-d>", ":LspDefinition<CR>"}, -- Lsp definition
    {"<A-c>", ":LspDeclaration<CR>"}, -- Lsp declaration
    {"<A-h>", ":LspHover<CR>"}, -- Lsp hover
    {"<A-r>", ":LspRename<CR>"}, -- Lsp rename
    {"<A-n>", ":LspGoToNext<CR>"}, -- Lsp go to next
    {"<A-p>", ":LspGoToPrev<CR>"}, -- Lsp go to prev
    {"<A-e>", ":LspTroubleToggle<CR>"}, -- Lsp trouble toggle
    {"<A-/>", ":CommentToggle<CR>"}, -- Comment toggle
    {"<A-*>", ":LspVirtualTextToggle<CR>"}, -- Lsp virtual text toggle
    {"<A-1>", "<Cmd>DapToggleBreakpoint<CR>"}, -- Toggle breakpoint
    {"<A-2>", "<Cmd>DapStartContinue<CR>"}, -- Start / continue
    {"<A-3>", "<Cmd>DapStepInto<CR>"}, -- Step into
    {"<A-4>", "<Cmd>DapStepOver<CR>"}, -- Step over
    {"<A-5>", "<Cmd>DapStepOut<CR>"}, -- Step out
    {"<A-6>", "<Cmd>DapUp<CR>"}, -- Up
    {"<A-7>", "<Cmd>DapDown<CR>"}, -- Down
    {"<A-8>", "<Cmd>DapUIClose<CR>"}, -- UI close
    {"<A-9>", "<Cmd>DapRestart<CR>"}, -- Restart
    {"<A-0>", "<Cmd>DapToggleRepl<CR>"} -- Toggle Repl
}

keymaps["visual"] = {
    {"<", "<gv"}, -- Tab left
    {">", ">gv"}, -- Tab right
    {"*", "<Esc>/\\%V"}, -- Visual search /
    {"#", "<Esc>?\\%V"}, -- Visual search ?
    {"K", ":move '<-2<CR>gv-gv"}, -- Move up
    {"J", ":move '>+1<CR>gv-gv"}, -- Move down
    {"<A-j>", ":AnyJumpVisual<CR>"}, -- Any jump visual
    {"<A-/>", ":CommentToggle<CR>"} -- Comment toggle
}

return keymaps
indent char
-- lua/configs/global/init.lua

configs["indent_char_global"] = function()
    vim.g.indent_blankline_char = ""
    vim.g.indentLine_char = ""
end
Vim-CtrlSpace
-- lua/configs/global/init.lua

configs["ctrlspace_pre_config_global"] = function()
    vim.g.ctrlspace_use_tablineend = 1
    vim.g.CtrlSpaceLoadLastWorkspaceOnStart = 1
    vim.g.CtrlSpaceSaveWorkspaceOnSwitch = 1
    vim.g.CtrlSpaceSaveWorkspaceOnExit = 1
    vim.g.CtrlSpaceUseTabline = 0
    vim.g.CtrlSpaceUseArrowsInTerm = 1
    vim.g.CtrlSpaceUseMouseAndArrowsInTerm = 1
    vim.g.CtrlSpaceGlobCommand = "rg --files --follow --hidden -g '!{.git/*,node_modules/*,target/*,vendor/*}'"
    vim.g.CtrlSpaceIgnoredFiles = "\v(tmp|temp)[\\/]"
    vim.g.CtrlSpaceSymbols = {
        CS = "",
        Sin = "",
        All = "",
        Vis = "",
        File = "",
        Tabs = "",
        CTab = "",
        NTM = "",
        WLoad = "",
        WSave = "",
        Zoom = "",
        SLeft = "",
        SRight = "",
        BM = "",
        Help = "",
        IV = "",
        IA = "",
        IM = "",
        Dots = ""
    }
end

1.2. Functions

Code
-- lua/core/funcs.lua

local M = {}

M.augroups = function(definitions)
    for group_name, definition in pairs(definitions) do
        vim.api.nvim_command("augroup " .. group_name)
        vim.api.nvim_command("autocmd!")
        for _, def in ipairs(definition) do
            local command = table.concat(vim.tbl_flatten {"autocmd", def}, " ")
            vim.api.nvim_command(command)
        end
        vim.api.nvim_command("augroup END")
    end
end

M.commands = function(commands)
    for name, c in pairs(commands) do
        local command
        if c.buffer then
            command = "command!-buffer"
        else
            command = "command!"
        end
        vim.cmd(command .. " -nargs=" .. c.nargs .. " " .. name .. " " .. c.cmd)
    end
end

M.merge = function(a, b)
    if type(a) == "table" and type(b) == "table" then
        for k, v in pairs(b) do
            if type(v) == "table" and type(a[k] or false) == "table" then
                M.merge(a[k], v)
            else
                a[k] = v
            end
        end
    end
    return a
end

M.options_global = function(options)
    for name, value in pairs(options) do
        vim.o[name] = value
    end
end

M.options_set = function(options)
    for k, v in pairs(options) do
        if v == true or v == false then
            vim.cmd("set " .. k)
        else
            vim.cmd("set " .. k .. "=" .. v)
        end
    end
end

M.keymaps = function(mode, opts, keymaps)
    for _, keymap in ipairs(keymaps) do
        vim.api.nvim_set_keymap(mode, keymap[1], keymap[2], opts)
    end
end

M.configs = function()
    local global_configs = require "configs.global"
    local custom_configs = require "configs.custom"
    local configs = M.merge(global_configs, custom_configs)
    for _, func in pairs(configs) do
        if type(func) == "function" then
            func()
        end
    end
end

M.file_exists = function(name)
    local f = io.open(name, "r")
    return f ~= nil and io.close(f)
end

M.dir_exists = function(path)
    return M.file_exists(path)
end

M.change_path = function()
    return vim.fn.input("Path: ", vim.fn.getcwd() .. "/", "file")
end

M.set_global_path = function()
    local path = M.change_path()
    vim.api.nvim_command("silent :cd " .. path)
end

M.set_window_path = function()
    local path = M.change_path()
    vim.api.nvim_command("silent :lcd " .. path)
end

return M

2. Disable of default configs

You can disable of any default config

Example
-- lua/configs/custom/init.lua

configs["keymaps_global"] = false

3. Rewrite of settings of default config

You can rewrite of settings of any of default config

Example
-- lua/configs/custom/init.lua

configs["events_global"] = function()
    funcs.augroups(
        {
            bufs = {
                {
                    "BufWinEnter",
                    "*",
                    "setlocal formatoptions-=c formatoptions-=r formatoptions-=o "
                },
                {
                    "BufRead",
                    "*",
                    "setlocal formatoptions-=c formatoptions-=r formatoptions-=o "
                },
                {
                    "BufNewFile",
                    "*",
                    "setlocal formatoptions-=c formatoptions-=r formatoptions-=o "
                },
            },
            ft = {
                {"FileType", "dart", "setlocal ts=2 sw=2"},
                {"FileType", "ruby", "setlocal ts=2 sw=2"},
                {"FileType", "yaml", "setlocal ts=2 sw=2"},
                {"FileType", "c", "setlocal ts=2 sw=2"},
                {"FileType", "cpp", "setlocal ts=2 sw=2"},
                {"FileType", "objc", "setlocal ts=2 sw=2"},
                {"FileType", "objcpp", "setlocal ts=2 sw=2"},
            }
        }
    )
end

4. Add new config

You can add new config

Example
-- lua/configs/custom/init.lua

-- :)
configs["sleep_loading_custom"] = function()
    vim.api.nvim_exec(
        [[
            sleep 1000m
        ]],
        true
    )
end
Clone this wiki locally