Restructure config | Move some to a packer plugin | Lot of cleanup

* move teleacope files, updater and related utils to
  https://github.com/NvChad/core

* restructure config file and directory structure

* expose mappings for better escape

* allow multiple mappings for some

* improve merge table function for the same

* move autocommands to a seperate file

* rearrange everything alphabetically where sanely possible

* rearrange packer plugin list on the basis of trigerred state

config structure now

 .
├──  init.lua
├──  LICENSE
├──  lua
│  ├──  chadrc.lua
│  ├──  colors
│  │  ├──  highlights.lua
│  │  ├──  init.lua
│  │  └──  themes
│  │     ├──  chadracula.lua
│  │     ├──  everforest.lua
│  │     ├──  gruvchad.lua
│  │     ├──  javacafe.lua
│  │     ├──  mountain.lua
│  │     ├──  norchad.lua
│  │     ├──  one-light.lua
│  │     ├──  onedark.lua
│  │     ├──  tokyonight.lua
│  │     └──  tomorrow-night.lua
│  ├──  core
│  │  ├──  autocmds.lua
│  │  ├──  init.lua
│  │  ├──  mappings.lua
│  │  ├──  options.lua
│  │  └──  utils.lua
│  ├──  default_config.lua
│  └──  plugins
│     ├──  configs
│     │  ├──  autopairs.lua
│     │  ├──  autosave.lua
│     │  ├──  bufferline.lua
│     │  ├──  chadsheet.lua
│     │  ├──  compe.lua
│     │  ├──  dashboard.lua
│     │  ├──  gitsigns.lua
│     │  ├──  icons.lua
│     │  ├──  lspconfig.lua
│     │  ├──  luasnip.lua
│     │  ├──  nvimtree.lua
│     │  ├──  others.lua
│     │  ├──  statusline.lua
│     │  ├──  telescope.lua
│     │  ├──  treesitter.lua
│     │  └──  zenmode.lua
│     ├──  init.lua
│     └──  packerInit.lua
└──  README.md
This commit is contained in:
Akianonymus 2021-08-22 13:19:15 +05:30 committed by siduck76
parent 44ae0178f4
commit 9ffddb6b52
44 changed files with 1383 additions and 1789 deletions

17
lua/core/autocmds.lua Normal file
View file

@ -0,0 +1,17 @@
-- uncomment this if you want to open nvim with a dir
-- vim.cmd [[ autocmd BufEnter * if &buftype != "terminal" | lcd %:p:h | endif ]]
-- Use relative & absolute line numbers in 'n' & 'i' modes respectively
-- vim.cmd[[ au InsertEnter * set norelativenumber ]]
-- vim.cmd[[ au InsertLeave * set relativenumber ]]
-- Don't show any numbers inside terminals
vim.cmd [[ au TermOpen term://* setlocal nonumber norelativenumber | setfiletype terminal ]]
-- Don't show status line on certain windows
vim.cmd [[ autocmd BufEnter,BufWinEnter,WinEnter,CmdwinEnter,TermEnter * lua require("core.utils").hide_statusline() ]]
-- Open a file from its last left off position
-- vim.cmd [[ au BufReadPost * if expand('%:p') !~# '\m/\.git/' && line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif ]]
-- File extension specific tabbing
-- vim.cmd [[ autocmd Filetype python setlocal expandtab tabstop=4 shiftwidth=4 softtabstop=4 ]]

15
lua/core/init.lua Normal file
View file

@ -0,0 +1,15 @@
local core_modules = {
"core.options",
"core.autocmds",
"core.mappings",
}
for _, module in ipairs(core_modules) do
local ok, err = pcall(require, module)
if not ok then
error("Error loading " .. module .. "\n\n" .. err)
end
end
-- set all the non plugin mappings
require("core.mappings").misc()

202
lua/core/mappings.lua Normal file
View file

@ -0,0 +1,202 @@
local config = require("core.utils").load_config()
local maps = config.mappings
local plugin_maps = maps.plugin
local cmd = vim.cmd
local function map(mode, lhs, rhs, opts)
local options = { noremap = true, silent = true }
if opts then
options = vim.tbl_extend("force", options, opts)
end
-- if list of keys provided then run set for all of them
if type(lhs) == "table" then
for _, key in ipairs(lhs) do
vim.api.nvim_set_keymap(mode, key, rhs, options)
end
else
vim.api.nvim_set_keymap(mode, lhs, rhs, options)
end
end
local opt, M = {}, {}
-- these mappings will only be called during initialization
M.misc = function()
local function non_config_mappings()
-- dont copy any deleted text , this is disabled by default so uncomment the below mappings if you want them
-- map("n", "dd", [=[ "_dd ]=], opt)
-- map("v", "dd", [=[ "_dd ]=], opt)
-- map("v", "x", [=[ "_x ]=], opt)
-- todo: this should be configurable via chadrc
-- Don't copy the replaced text after pasting in visual mode
map("v", "p", '"_dP', opt)
-- Allow moving the cursor through wrapped lines with j, k, <Up> and <Down>
-- http://www.reddit.com/r/vim/comments/2k4cbr/problem_with_gj_and_gk/
-- empty mode is same as using :map
map("", "j", 'v:count ? "j" : "gj"', { expr = true })
map("", "k", 'v:count ? "k" : "gk"', { expr = true })
map("", "<Down>", 'v:count ? "j" : "gj"', { expr = true })
map("", "<Up>", 'v:count ? "k" : "gk"', { expr = true })
-- use ESC to turn off search highlighting
map("n", "<Esc>", ":noh <CR>", opt)
end
local function optional_mappings()
-- navigation within insert mode
if config.options.insert_nav then
local inav = maps.insert_nav
map("i", inav.backward, "<Left>", opt)
map("i", inav.end_of_line, "<End>", opt)
map("i", inav.forward, "<Right>", opt)
map("i", inav.next_line, "<Up>", opt)
map("i", inav.prev_line, "<Down>", opt)
map("i", inav.top_of_line, "<ESC>^i", opt)
end
-- check the theme toggler
if config.ui.theme_toggler then
map(
"n",
maps.theme_toggler,
":lua require('nvchad').toggle_theme(require('core.utils').load_config().ui.theme_toggler.fav_themes) <CR>",
opt
)
end
end
local function required_mappings()
map("n", maps.close_buffer, ":lua require('core.utils').close_buffer() <CR>", opt) -- close buffer
map("n", maps.copy_whole_file, ":%y+ <CR>", opt) -- copy whole file content
map("n", maps.new_buffer, ":enew <CR>", opt) -- new buffer
map("n", maps.new_tab, ":tabnew <CR>", opt) -- new tabs
map("n", maps.line_number_toggle, ":set nu! <CR>", opt) -- toggle numbers
map("n", maps.save_file, ":w <CR>", opt) -- ctrl + s to save file
-- terminal mappings --
local term_maps = maps.terminal
-- get out of terminal mode
map("t", term_maps.esc_termmode, "<C-\\><C-n>", opt)
-- hide a term from within terminal mode
map("t", term_maps.esc_hide_termmode, "<C-\\><C-n> :lua require('core.utils').close_buffer() <CR>", opt)
-- pick a hidden term
map("n", term_maps.pick_term, ":Telescope terms <CR>", opt)
-- Open terminals
-- TODO this opens on top of an existing vert/hori term, fixme
map(
"n",
term_maps.new_horizontal,
":execute 15 .. 'new +terminal' | let b:term_type = 'hori' | startinsert <CR>",
opt
)
map("n", term_maps.new_vertical, ":execute 'vnew +terminal' | let b:term_type = 'vert' | startinsert <CR>", opt)
map("n", term_maps.new_window, ":execute 'terminal' | let b:term_type = 'wind' | startinsert <CR>", opt)
-- terminal mappings end --
-- Add Packer commands because we are not loading it at startup
cmd "silent! command PackerCompile lua require 'plugins' require('packer').compile()"
cmd "silent! command PackerInstall lua require 'plugins' require('packer').install()"
cmd "silent! command PackerStatus lua require 'plugins' require('packer').status()"
cmd "silent! command PackerSync lua require 'plugins' require('packer').sync()"
cmd "silent! command PackerUpdate lua require 'plugins' require('packer').update()"
-- add NvChadUpdate command and mapping
cmd "silent! command! NvChadUpdate lua require('nvchad').update_nvchad()"
map("n", maps.update_nvchad, ":NvChadUpdate <CR>", opt)
end
non_config_mappings()
optional_mappings()
required_mappings()
end
-- below are all plugin related mappinsg
M.better_escape = function()
vim.g.better_escape_shortcut = plugin_maps.better_escape.esc_insertmode or { "" }
end
M.bufferline = function()
local m = plugin_maps.bufferline
map("n", m.next_buffer, ":BufferLineCycleNext <CR>", opt)
map("n", m.prev_buffer, ":BufferLineCyclePrev <CR>", opt)
end
M.chadsheet = function()
local m = plugin_maps.chadsheet
map("n", m.default_keys, ":lua require('cheatsheet').show_cheatsheet_telescope() <CR>", opt)
map(
"n",
m.user_keys,
":lua require('cheatsheet').show_cheatsheet_telescope{bundled_cheatsheets = false, bundled_plugin_cheatsheets = false } <CR>",
opt
)
end
M.comment = function()
local m = plugin_maps.comment.toggle
map("n", m, ":CommentToggle <CR>", opt)
map("v", m, ":CommentToggle <CR>", opt)
end
M.dashboard = function()
local m = plugin_maps.dashboard
map("n", m.bookmarks, ":DashboardJumpMarks <CR>", opt)
map("n", m.new_file, ":DashboardNewFile <CR>", opt)
map("n", m.open, ":Dashboard <CR>", opt)
map("n", m.session_load, ":SessionLoad <CR>", opt)
map("n", m.session_save, ":SessionSave <CR>", opt)
end
M.nvimtree = function()
map("n", plugin_maps.nvimtree.toggle, ":NvimTreeToggle <CR>", opt)
end
M.neoformat = function()
map("n", plugin_maps.neoformat.format, ":Neoformat <CR>", opt)
end
M.telescope = function()
local m = plugin_maps.telescope
map("n", m.buffers, ":Telescope buffers <CR>", opt)
map("n", m.find_files, ":Telescope find_files <CR>", opt)
map("n", m.git_commits, ":Telescope git_commits <CR>", opt)
map("n", m.git_status, ":Telescope git_status <CR>", opt)
map("n", m.help_tags, ":Telescope help_tags <CR>", opt)
map("n", m.live_grep, ":Telescope live_grep <CR>", opt)
map("n", m.oldfiles, ":Telescope oldfiles <CR>", opt)
map("n", m.themes, ":Telescope themes <CR>", opt)
end
M.telescope_media = function()
local m = plugin_maps.telescope_media
map("n", m.media_files, ":Telescope media_files <CR>", opt)
end
M.truezen = function()
local m = plugin_maps.truezen
map("n", m.ataraxis_mode, ":TZAtaraxis <CR>", opt)
map("n", m.focus_mode, ":TZFocus <CR>", opt)
map("n", m.minimalistic_mode, ":TZMinimalist <CR>", opt)
end
M.vim_fugitive = function()
local m = plugin_maps.vim_fugitive
map("n", m.git, ":Git <CR>", opt)
map("n", m.git_blame, ":Git blame <CR>", opt)
map("n", m.diff_get_2, ":diffget //2 <CR>", opt)
map("n", m.diff_get_3, ":diffget //3 <CR>", opt)
end
return M

74
lua/core/options.lua Normal file
View file

@ -0,0 +1,74 @@
local opt = vim.opt
local g = vim.g
-- export user config as a global varibale
g.nvchad_user_config = "chadrc"
local options = require("core.utils").load_config().options
opt.clipboard = options.clipboard
opt.cmdheight = options.cmdheight
opt.completeopt = { "menuone", "noselect" }
opt.cul = true -- cursor line
-- Indentline
opt.expandtab = options.expandtab
opt.shiftwidth = options.shiftwidth
opt.smartindent = options.smartindent
-- disable tilde on end of buffer: https://github.com/ neovim/neovim/pull/8546#issuecomment-643643758
opt.fillchars = { eob = " " }
opt.hidden = options.hidden
opt.ignorecase = options.ignorecase
opt.mouse = options.mouse
-- Numbers
opt.number = options.number
opt.numberwidth = options.numberwidth
opt.relativenumber = options.relativenumber
opt.ruler = options.ruler
-- disable nvim intro
opt.shortmess:append "sI"
opt.signcolumn = "yes"
opt.splitbelow = true
opt.splitright = true
opt.termguicolors = true
opt.timeoutlen = options.timeoutlen
opt.undofile = options.permanent_undo
-- interval for writing swap file to disk, also used by gitsigns
opt.updatetime = options.updatetime
-- go to previous/next line with h,l,left arrow and right arrow
-- when cursor reaches end/beginning of line
opt.whichwrap:append "<>hl"
g.mapleader = options.mapleader
-- disable some builtin vim plugins
local disabled_built_ins = {
"2html_plugin",
"getscript",
"getscriptPlugin",
"gzip",
"logipat",
"netrw",
"netrwPlugin",
"netrwSettings",
"netrwFileHandlers",
"matchit",
"tar",
"tarPlugin",
"rrhelper",
"spellfile_plugin",
"vimball",
"vimballPlugin",
"zip",
"zipPlugin",
}
for _, plugin in pairs(disabled_built_ins) do
g["loaded_" .. plugin] = 1
end

265
lua/core/utils.lua Normal file
View file

@ -0,0 +1,265 @@
local M = {}
M.close_buffer = function(bufexpr, force)
-- This is a modification of a NeoVim plugin from
-- Author: ojroques - Olivier Roques
-- Src: https://github.com/ojroques/nvim-bufdel
-- (Author has okayed copy-paste)
-- Options
local opts = {
next = "cycle", -- how to retrieve the next buffer
quit = false, -- exit when last buffer is deleted
--TODO make this a chadrc flag/option
}
-- ----------------
-- Helper functions
-- ----------------
-- Switch to buffer 'buf' on each window from list 'windows'
local function switch_buffer(windows, buf)
local cur_win = vim.fn.winnr()
for _, winid in ipairs(windows) do
vim.cmd(string.format("%d wincmd w", vim.fn.win_id2win(winid)))
vim.cmd(string.format("buffer %d", buf))
end
vim.cmd(string.format("%d wincmd w", cur_win)) -- return to original window
end
-- Select the first buffer with a number greater than given buffer
local function get_next_buf(buf)
local next = vim.fn.bufnr "#"
if opts.next == "alternate" and vim.fn.buflisted(next) == 1 then
return next
end
for i = 0, vim.fn.bufnr "$" - 1 do
next = (buf + i) % vim.fn.bufnr "$" + 1 -- will loop back to 1
if vim.fn.buflisted(next) == 1 then
return next
end
end
end
-- ----------------
-- End helper functions
-- ----------------
local buf = vim.fn.bufnr()
if vim.fn.buflisted(buf) == 0 then -- exit if buffer number is invalid
vim.cmd "close"
return
end
if #vim.fn.getbufinfo { buflisted = 1 } < 2 then
if opts.quit then
-- exit when there is only one buffer left
if force then
vim.cmd "qall!"
else
vim.cmd "confirm qall"
end
return
end
local chad_term, type = pcall(function()
return vim.api.nvim_buf_get_var(buf, "term_type")
end)
if chad_term then
-- Must be a window type
vim.cmd(string.format("setlocal nobl", buf))
vim.cmd "enew"
return
end
-- don't exit and create a new empty buffer
vim.cmd "enew"
vim.cmd "bp"
end
local next_buf = get_next_buf(buf)
local windows = vim.fn.getbufinfo(buf)[1].windows
-- force deletion of terminal buffers to avoid the prompt
if force or vim.fn.getbufvar(buf, "&buftype") == "terminal" then
local chad_term, type = pcall(function()
return vim.api.nvim_buf_get_var(buf, "term_type")
end)
-- TODO this scope is error prone, make resilient
if chad_term then
if type == "wind" then
-- hide from bufferline
vim.cmd(string.format("%d bufdo setlocal nobl", buf))
-- swtich to another buff
-- TODO switch to next bufffer, this works too
vim.cmd "BufferLineCycleNext"
else
local cur_win = vim.fn.winnr()
-- we can close this window
vim.cmd(string.format("%d wincmd c", cur_win))
return
end
else
switch_buffer(windows, next_buf)
vim.cmd(string.format("bd! %d", buf))
end
else
switch_buffer(windows, next_buf)
vim.cmd(string.format("silent! confirm bd %d", buf))
end
-- revert buffer switches if user has canceled deletion
if vim.fn.buflisted(buf) == 1 then
switch_buffer(windows, buf)
end
end
-- hide statusline
-- tables fetched from load_config function
M.hide_statusline = function()
local hidden = require("core.utils").load_config().ui.plugin.statusline.hidden
local shown = require("core.utils").load_config().ui.plugin.statusline.shown
local api = vim.api
local buftype = api.nvim_buf_get_option("%", "ft")
-- shown table from config has the highest priority
if vim.tbl_contains(shown, buftype) then
api.nvim_set_option("laststatus", 2)
return
end
if vim.tbl_contains(hidden, buftype) then
api.nvim_set_option("laststatus", 0)
return
else
api.nvim_set_option("laststatus", 2)
end
end
-- Base code: https://gist.github.com/revolucas/184aec7998a6be5d2f61b984fac1d7f7
-- Changes over it: preserving table 1 contents and also update with table b, without duplicating
-- 1st arg - base table
-- 2nd arg - table to merge
-- 3rg arg - list of nodes as a table, if the node is found replace the from table2 to result, rather than adding the value
-- e.g: merge_table(t1, t2, { ['plugin']['truezen']['mappings'] })
M.merge_table = function(into, from, nodes_to_replace)
-- make sure both are table
if type(into) ~= "table" or type(from) ~= "table" then
return into
end
local stack, seen = {}, {}
local table1, table2 = into, from
if type(nodes_to_replace) == "table" then
-- function that will be executed with loadstring
local base_fn = [[
return function(table1, table2)
local t1, t2 = table1_node or false , table2_node or false
if t1 and t2 then
table1_node = table2_node
end
return table1
end]]
for _, node in ipairs(nodes_to_replace) do
-- replace the _node in base_fn to actual given node value
local fn = base_fn:gsub("_node", node)
-- if the node if found, it is replaced, otherwise table 1 is returned
table1 = loadstring(fn)()(table1, table2)
end
end
while true do
for k, v in pairs(table2) do
if type(v) == "table" and type(table1[k]) == "table" then
table.insert(stack, { table1[k], table2[k] })
else
local present = seen[v] or false
if not present then
if type(k) == "number" then
-- add the value to seen table until value is found
-- only do when key is number we just want to append to subtables
-- todo: maybe improve this
for _, value in pairs(table1) do
if value == v then
present = true
break
end
end
seen[v] = true
if not present then
table1[#table1 + 1] = v
end
else
table1[k] = v
end
end
end
end
if #stack > 0 then
local t = stack[#stack]
table1, table2 = t[1], t[2]
stack[#stack] = nil
else
break
end
end
return into
end
-- load config
-- 1st arg = boolean - whether to force reload
-- Modifies _G._NVCHAD_CONFIG global variable
M.load_config = function(reload)
-- only do the stuff below one time, otherwise just return the set config
if _G._NVCHAD_CONFIG_CONTENTS ~= nil and not (reload or false) then
return _G._NVCHAD_CONFIG_CONTENTS
end
-- these are the table value which will be always prioritiezed to take user config value
local to_replace = {
"['mappings']['plugin']['esc_insertmode']",
"['mappings']['terminal']['esc_termmode']",
"['mappings']['terminal']['esc_hide_termmode']",
}
local default_config = "default_config"
local config_name = vim.g.nvchad_user_config or "chadrc"
local config_file = vim.fn.stdpath "config" .. "/lua/" .. config_name .. ".lua"
-- unload the modules if force reload
if reload then
package.loaded[default_config or false] = nil
package.loaded[config_name or false] = nil
end
-- don't enclose in pcall, it better break when default config is faulty
_G._NVCHAD_CONFIG_CONTENTS = require(default_config)
-- user config is not required to run nvchad but a optional
-- Make sure the config doesn't break the whole system if user config is not present or in bad state or not a table
-- print warning texts if user config file is present
-- check if the user config is present
if vim.fn.empty(vim.fn.glob(config_file)) < 1 then
local present, config = pcall(require, config_name)
if present then
-- make sure the returned value is table
if type(config) == "table" then
-- data = require(config_name)
_G._NVCHAD_CONFIG_CONTENTS = require("core.utils").merge_table(
_G._NVCHAD_CONFIG_CONTENTS,
config,
to_replace
)
else
print("Warning: " .. config_name .. " sourced successfully but did not return a lua table.")
end
else
print("Warning: " .. config_file .. " is present but sourcing failed.")
end
end
return _G._NVCHAD_CONFIG_CONTENTS
end
return M