This commit is contained in:
root
2025-08-10 20:24:22 +00:00
commit f470e78d1c
75 changed files with 4408 additions and 0 deletions

92
lua/colorschemes.lua Normal file
View File

@@ -0,0 +1,92 @@
local utils = require("utils")
local M = {}
M.colorscheme_conf = {
onedark = function()
require("onedark").setup {
style = "darker",
}
require("onedark").load()
end,
edge = function()
vim.g.edge_style = "default"
vim.g.edge_enable_italic = 1
vim.g.edge_better_performance = 1
vim.cmd([[colorscheme edge]])
end,
sonokai = function()
vim.g.sonokai_enable_italic = 1
vim.g.sonokai_better_performance = 1
vim.cmd([[colorscheme sonokai]])
end,
gruvbox_material = function()
-- foreground option can be material, mix, or original
vim.g.gruvbox_material_foreground = "original"
-- background option can be hard, medium, soft
vim.g.gruvbox_material_background = "hard"
vim.g.gruvbox_material_enable_italic = 1
vim.g.gruvbox_material_better_performance = 1
vim.cmd([[colorscheme gruvbox-material]])
end,
everforest = function()
vim.g.everforest_background = "hard"
vim.g.everforest_enable_italic = 1
vim.g.everforest_better_performance = 1
vim.cmd([[colorscheme everforest]])
end,
nightfox = function()
vim.cmd([[colorscheme carboxfox]])
end,
onedarkpro = function()
vim.cmd("colorscheme onedark_dark")
end,
material = function()
vim.g.material_style = "darker"
vim.cmd("colorscheme material")
end,
arctic = function()
vim.cmd("colorscheme arctic")
end,
kanagawa = function()
vim.cmd("colorscheme kanagawa-dragon")
end,
modus = function()
vim.cmd([[colorscheme modus]])
end,
jellybeans = function()
vim.cmd([[colorscheme jellybeans]])
end,
github = function()
vim.cmd([[colorscheme github_dark_default]])
end,
e_ink = function()
require("e-ink").setup()
vim.cmd.colorscheme("e-ink")
end,
ashen = function()
vim.cmd([[colorscheme ashen]])
end,
melange = function()
vim.cmd([[colorscheme melange]])
end,
makurai = function()
vim.cmd.colorscheme("makurai_warrior")
end,
vague = function()
vim.cmd([[colorscheme vague]])
end,
kanso = function()
vim.cmd([[colorscheme kanso]])
end,
citruszest = function()
vim.cmd([[colorscheme citruszest]])
end,
}
M.rand_colorscheme = function()
local colorscheme = utils.rand_element(vim.tbl_keys(M.colorscheme_conf))
M.colorscheme_conf[colorscheme]()
end
return M

32
lua/config/blink-cmp.lua Normal file
View File

@@ -0,0 +1,32 @@
require("blink.cmp").setup {
keymap = {
preset = "default",
["<Tab>"] = { "select_next", "fallback" },
["<S-Tab>"] = { "select_prev", "fallback" },
["<Enter>"] = { "select_and_accept", "fallback" },
["<C-U>"] = { "scroll_documentation_up", "fallback" },
["<C-D>"] = { "scroll_documentation_down", "fallback" },
},
appearance = {
nerd_font_variant = "mono",
},
completion = {
documentation = {
auto_show = true,
},
},
sources = {
default = { "lsp", "path", "buffer" },
},
fuzzy = { implementation = "prefer_rust_with_warning" },
cmdline = {
completion = {
menu = {
auto_show = true,
},
},
keymap = {
["<Enter>"] = { "select_and_accept", "fallback" },
},
},
}

6
lua/config/bqf.lua Normal file
View File

@@ -0,0 +1,6 @@
require("bqf").setup {
auto_resize_height = false,
preview = {
auto_preview = false,
},
}

42
lua/config/bufferline.lua Normal file
View File

@@ -0,0 +1,42 @@
require("bufferline").setup {
options = {
numbers = "none",
close_command = "bdelete! %d",
right_mouse_command = nil,
left_mouse_command = "buffer %d",
middle_mouse_command = nil,
indicator = {
icon = "▎",
style = "icon",
},
buffer_close_icon = "",
modified_icon = "●",
close_icon = "",
left_trunc_marker = "",
right_trunc_marker = "",
max_name_length = 18,
max_prefix_length = 15,
tab_size = 10,
diagnostics = false,
custom_filter = function(bufnr)
local exclude_ft = { "qf", "fugitive", "git" }
local cur_ft = vim.bo[bufnr].filetype
local should_filter = vim.tbl_contains(exclude_ft, cur_ft)
return not should_filter
end,
show_buffer_icons = false,
show_buffer_close_icons = true,
show_close_icon = true,
show_tab_indicators = true,
persist_buffer_sort = true,
separator_style = "bar",
enforce_regular_tabs = false,
always_show_bufferline = true,
sort_by = "id",
},
}
vim.keymap.set("n", "<space>bp", "<cmd>BufferLinePick<cr>", {
desc = "pick a buffer",
})

View File

@@ -0,0 +1,75 @@
local api = vim.api
local keymap = vim.keymap
local dashboard = require("dashboard")
local conf = {}
conf.header = {
" ",
" ",
" ",
" ███╗ ██╗ ███████╗ ██████╗ ██╗ ██╗ ██╗ ███╗ ███╗",
" ████╗ ██║ ██╔════╝██╔═══██╗ ██║ ██║ ██║ ████╗ ████║",
" ██╔██╗ ██║ █████╗ ██║ ██║ ██║ ██║ ██║ ██╔████╔██║",
" ██║╚██╗██║ ██╔══╝ ██║ ██║ ╚██╗ ██╔╝ ██║ ██║╚██╔╝██║",
" ██║ ╚████║ ███████╗╚██████╔╝ ╚████╔╝ ██║ ██║ ╚═╝ ██║",
" ╚═╝ ╚═══╝ ╚══════╝ ╚═════╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝",
" ",
" ",
" ",
" ",
}
conf.center = {
{
icon = "󰈞 ",
desc = "Find File ",
action = "FzfLua files",
key = "<Leader> f f",
},
{
icon = "󰈢 ",
desc = "Recently opened files ",
action = "FzfLua oldfiles",
key = "<Leader> f r",
},
{
icon = "󰈬 ",
desc = "Project grep ",
action = "FzfLua live_grep",
key = "<Leader> f g",
},
{
icon = "",
desc = "Open Nvim config ",
action = "tabnew $MYVIMRC | tcd %:p:h",
key = "<Leader> e v",
},
{
icon = "",
desc = "New file ",
action = "enew",
key = "e",
},
{
icon = "󰗼 ",
desc = "Quit Nvim ",
-- desc = "Quit Nvim ",
action = "qa",
key = "q",
},
}
dashboard.setup {
theme = "doom",
shortcut_type = "number",
config = conf,
}
api.nvim_create_autocmd("FileType", {
pattern = "dashboard",
group = api.nvim_create_augroup("dashboard_enter", { clear = true }),
callback = function()
keymap.set("n", "q", ":qa<CR>", { buffer = true, silent = true })
keymap.set("n", "e", ":enew<CR>", { buffer = true, silent = true })
end,
})

View File

@@ -0,0 +1 @@
require("fidget").setup {}

24
lua/config/fugitive.lua Normal file
View File

@@ -0,0 +1,24 @@
local keymap = vim.keymap
keymap.set("n", "<leader>gs", "<cmd>Git<cr>", { desc = "Git: show status" })
keymap.set("n", "<leader>gw", "<cmd>Gwrite<cr>", { desc = "Git: add file" })
keymap.set("n", "<leader>gc", "<cmd>Git commit<cr>", { desc = "Git: commit changes" })
keymap.set("n", "<leader>gpl", "<cmd>Git pull<cr>", { desc = "Git: pull changes" })
keymap.set("n", "<leader>gpu", "<cmd>15 split|term git push<cr>", { desc = "Git: push changes" })
keymap.set("v", "<leader>gb", ":Git blame<cr>", { desc = "Git: blame selected line" })
vim.fn["utils#Cabbrev"]("git", "Git")
keymap.set("n", "<leader>gbn", function()
vim.ui.input({ prompt = "Enter a new branch name" }, function(user_input)
if user_input == nil or user_input == "" then
return
end
local cmd_str = string.format("G checkout -b %s", user_input)
vim.cmd(cmd_str)
end)
end, { desc = "Git: create new branch" })
keymap.set("n", "<leader>gf", ":Git fetch ", { desc = "Git: prune branches" })
keymap.set("n", "<leader>gbd", ":Git branch -D ", { desc = "Git: delete branch" })

18
lua/config/fzf-lua.lua Normal file
View File

@@ -0,0 +1,18 @@
require("fzf-lua").setup {
defaults = {
file_icons = "mini",
},
winopts = {
row = 0.5,
height = 0.7,
},
files = {
previewer = false,
},
}
vim.keymap.set("n", "<leader>ff", "<cmd>FzfLua files<cr>", { desc = "Fuzzy find files" })
vim.keymap.set("n", "<leader>fg", "<cmd>FzfLua live_grep<cr>", { desc = "Fuzzy grep files" })
vim.keymap.set("n", "<leader>fh", "<cmd>FzfLua helptags<cr>", { desc = "Fuzzy grep tags in help files" })
vim.keymap.set("n", "<leader>ft", "<cmd>FzfLua btags<cr>", { desc = "Fuzzy search buffer tags" })
vim.keymap.set("n", "<leader>fb", "<cmd>FzfLua buffers<cr>", { desc = "Fuzzy search opened buffers" })

View File

@@ -0,0 +1,9 @@
require("git-conflict").setup {}
vim.api.nvim_create_autocmd("User", {
pattern = "GitConflictResolved",
callback = function()
vim.fn.setqflist({}, "r")
vim.cmd([[silent! GitConflictListQf]])
end,
})

47
lua/config/git-linker.lua Normal file
View File

@@ -0,0 +1,47 @@
local keymap = vim.keymap
local gitlinker = require("gitlinker")
gitlinker.setup {
callbacks = {
["dev.azure.com"] = function(url_data)
vim.print(url_data)
local url = require("gitlinker.hosts").get_base_https_url(url_data)
if url_data.lstart then
if url_data.lend == nil then
url_data.lend = url_data.lstart
end
url = url
.. "?path=/"
.. url_data.file
.. "&version=GC"
.. url_data.rev
.. "&line="
.. url_data.lstart
"&lineEnd="
.. url_data.lend
.. "&lineStartColumn=1"
.. "&lineEndColumn=120"
end
return url
end,
},
mappings = nil,
}
keymap.set({ "n", "v" }, "<leader>gl", function()
local mode = string.lower(vim.fn.mode())
gitlinker.get_buf_range_url(mode)
end, {
silent = true,
desc = "Git: get permlink",
})
keymap.set("n", "<leader>gbr", function()
gitlinker.get_repo_url {
action_callback = gitlinker.actions.open_in_browser,
}
end, {
silent = true,
desc = "Git: browse repo in browser",
})

55
lua/config/gitsigns.lua Normal file
View File

@@ -0,0 +1,55 @@
local gs = require("gitsigns")
gs.setup {
signs = {
add = { text = "+" },
change = { text = "~" },
delete = { text = "_" },
topdelete = { text = "‾" },
changedelete = { text = "|" },
},
word_diff = false,
on_attach = function(bufnr)
local function map(mode, l, r, opts)
opts = opts or {}
opts.buffer = bufnr
vim.keymap.set(mode, l, r, opts)
end
map("n", "]c", function()
if vim.wo.diff then
return "]c"
end
vim.schedule(function()
gs.next_hunk()
end)
return "<Ignore>"
end, { expr = true, desc = "next hunk" })
map("n", "[c", function()
if vim.wo.diff then
return "[c"
end
vim.schedule(function()
gs.prev_hunk()
end)
return "<Ignore>"
end, { expr = true, desc = "previous hunk" })
map("n", "<leader>hp", gs.preview_hunk, { desc = "preview hunk" })
map("n", "<leader>hb", function()
gs.blame_line { full = true }
end, { desc = "blame hunk" })
end,
}
vim.api.nvim_create_autocmd("ColorScheme", {
pattern = "*",
callback = function()
vim.cmd([[
hi GitSignsChangeInline gui=reverse
hi GitSignsAddInline gui=reverse
hi GitSignsDeleteInline gui=reverse
]])
end,
})

12
lua/config/glance.lua Normal file
View File

@@ -0,0 +1,12 @@
local glance = require("glance")
glance.setup {
height = 25,
border = {
enable = true,
},
}
vim.keymap.set("n", "<space>gd", "<cmd>Glance definitions<cr>")
vim.keymap.set("n", "<space>gr", "<cmd>Glance reference<cr>")
vim.keymap.set("n", "<space>gi", "<cmd>Glance implementations<cr>")

75
lua/config/hlslens.lua Normal file
View File

@@ -0,0 +1,75 @@
local api = vim.api
local keymap = vim.keymap
local hlslens = require("hlslens")
hlslens.setup {
calm_down = true,
nearest_only = true,
}
local activate_hlslens = function(direction)
local cmd = string.format("normal! %s%szzzv", vim.v.count1, direction)
local status, msg = pcall(vim.cmd, cmd)
if not status then
local start_idx, _ = string.find(msg, "E486", 1, true)
local msg_part = string.sub(msg, start_idx)
api.nvim_echo({ { msg_part } }, true, { err = true })
return
end
hlslens.start()
end
keymap.set("n", "n", "", {
callback = function()
activate_hlslens("n")
end,
})
keymap.set("n", "N", "", {
callback = function()
activate_hlslens("N")
end,
})
local check_cursor_word = function()
local cursor_word = vim.fn.expand("<cword>")
local result = cursor_word == ""
if result then
local msg = "E348: No string under cursor"
api.nvim_echo({ { msg } }, true, { err = true })
end
return result, cursor_word
end
keymap.set("n", "*", "", {
callback = function()
local cursor_word_empty, cursor_word = check_cursor_word()
if cursor_word_empty then
return
end
local cmd = string.format([[normal! /\v<%s>]], cursor_word)
local escaped_enter = vim.api.nvim_replace_termcodes("<CR>", true, false, true)
local full_cmd = cmd .. escaped_enter .. "N"
vim.fn.execute(full_cmd)
hlslens.start()
end,
})
keymap.set("n", "#", "", {
callback = function()
local cursor_word_empty, cursor_word = check_cursor_word()
if cursor_word_empty then
return
end
local cmd = string.format([[normal! ?\v<%s>]], cursor_word)
local escaped_enter = vim.api.nvim_replace_termcodes("<CR>", true, false, true)
local full_cmd = cmd .. escaped_enter .. "N"
vim.fn.execute(full_cmd)
hlslens.start()
end,
})

7
lua/config/iron.lua Normal file
View File

@@ -0,0 +1,7 @@
local lua = require("iron")
iron.core.set_config {
preferred = {
python = "ipython",
},
repl_open_cmd = "vertical 120 split",
}

18
lua/config/lightbulb.lua Normal file
View File

@@ -0,0 +1,18 @@
---@diagnostic disable: missing-fields
require("nvim-lightbulb").setup {
autocmd = {
enabled = true,
updatetime = -1,
},
---@diagnostic disable-next-line: unused-local
filter = function(client_name, result)
-- Ruff always sends these two actions even if there are no actions to take
-- so it is better to just ignore these to avoid noise
local ignored_kinds = { "source.fixAll.ruff", "source.organizeImports.ruff" }
if vim.tbl_contains(ignored_kinds, result.kind) then
return false
end
return true
end,
}

View File

@@ -0,0 +1,9 @@
require("live-command").setup {
enable_highlighting = true,
inline_highlighting = true,
commands = {
Norm = { cmd = "norm" },
},
}
vim.cmd("cnoreabbrev norm Norm")

127
lua/config/lsp.lua Normal file
View File

@@ -0,0 +1,127 @@
local utils = require("utils")
vim.api.nvim_create_autocmd("LspAttach", {
group = vim.api.nvim_create_augroup("lsp_buf_conf", { clear = true }),
callback = function(event_context)
local client = vim.lsp.get_client_by_id(event_context.data.client_id)
if not client then
return
end
local bufnr = event_context.buf
local map = function(mode, l, r, opts)
opts = opts or {}
opts.silent = true
opts.buffer = bufnr
vim.keymap.set(mode, l, r, opts)
end
map("n", "gd", function()
vim.lsp.buf.definition {
on_list = function(options)
local unique_defs = {}
local def_loc_hash = {}
for _, def_location in pairs(options.items) do
local hash_key = def_location.filename .. def_location.lnum
if not def_loc_hash[hash_key] then
def_loc_hash[hash_key] = true
table.insert(unique_defs, def_location)
end
end
options.items = unique_defs
---@diagnostic disable-next-line: param-type-mismatch
vim.fn.setloclist(0, {}, " ", options)
if #options.items > 1 then
vim.cmd.lopen()
else
vim.cmd([[silent! lfirst]])
end
end,
}
end, { desc = "go to definition" })
map("n", "<c-]>", vim.lsp.buf.definition)
map("n", "K", function()
vim.lsp.buf.hover { border = "single", max_height = 25, max_width = 120 }
end)
map("n", "<c-k>", vim.lsp.buf.signature_help)
map("n", "<space>rn", vim.lsp.buf.rename, { desc = "variable rename" })
map("n", "<space>ca", vim.lsp.buf.code_action, { desc = "LSP code action" })
map("n", "<space>wa", vim.lsp.buf.add_workspace_folder, { desc = "add workspace folder" })
map("n", "<space>wr", vim.lsp.buf.remove_workspace_folder, { desc = "remove workspace folder" })
map("n", "<space>wl", function()
vim.print(vim.lsp.buf.list_workspace_folders())
end, { desc = "list workspace folder" })
if client.name == "ruff" then
client.server_capabilities.hoverProvider = false
end
vim.lsp.inlay_hint.enable(true, { buffer = bufnr })
if client.server_capabilities.documentHighlightProvider then
local gid = vim.api.nvim_create_augroup("lsp_document_highlight", { clear = true })
vim.api.nvim_create_autocmd("CursorHold", {
group = gid,
buffer = bufnr,
callback = function()
vim.lsp.buf.document_highlight()
end,
})
vim.api.nvim_create_autocmd("CursorMoved", {
group = gid,
buffer = bufnr,
callback = function()
vim.lsp.buf.clear_references()
end,
})
vim.api.nvim_create_autocmd("CursorMoved", {
group = gid,
buffer = bufnr,
callback = function()
vim.lsp.buf.clear_references()
end,
})
end
end,
nested = true,
desc = "configure buffer keymap and behavior based on LSP",
})
local capabilities = require("lsp_utils").get_default_capabilities()
vim.lsp.config("*", {
capabilities = capabilities,
flags = {
debounce_text_changes = 500,
},
})
local enabled_lsp_servers = {
pyright = "delance-langserver",
ruff = "ruff",
lua_ls = "lua-language-server",
vimls = "vim-language-server",
bashls = "bash-language-server",
yamlls = "yaml-language-server",
}
for server_name, lsp_executable in pairs(enabled_lsp_servers) do
if utils.executable(lsp_executable) then
vim.lsp.enable(server_name)
else
local msg = string.format(
"Executable '%s' for server '%s' not found! Server will not be enabled",
lsp_executable,
server_name
)
vim.notify(msg, vim.log.levels.WARN, { title = "nvim-config" })
end
end

310
lua/config/lualine.lua Normal file
View File

@@ -0,0 +1,310 @@
local fn = vim.fn
local git_status_cache = {}
local on_exit_fetch = function(result)
if result.code == 0 then
git_status_cache.fetch_success = true
end
end
local function handle_numeric_result(cache_key)
return function(result)
if result.code == 0 then
git_status_cache[cache_key] = tonumber(result.stdout:match("(%d+)")) or 0
end
end
end
local async_cmd = function(cmd_str, on_exit)
local cmd = vim.tbl_filter(function(element)
return element ~= ""
end, vim.split(cmd_str, " "))
vim.system(cmd, { text = true }, on_exit)
end
local async_git_status_update = function()
-- Fetch the latest changes from the remote repository (replace 'origin' if needed)
async_cmd("git fetch origin", on_exit_fetch)
if not git_status_cache.fetch_success then
return
end
-- Get the number of commits behind
-- the @{upstream} notation is inspired by post: https://www.reddit.com/r/neovim/comments/t48x5i/git_branch_aheadbehind_info_status_line_component/
-- note that here we should use double dots instead of triple dots
local behind_cmd_str = "git rev-list --count HEAD..@{upstream}"
async_cmd(behind_cmd_str, handle_numeric_result("behind_count"))
-- Get the number of commits ahead
local ahead_cmd_str = "git rev-list --count @{upstream}..HEAD"
async_cmd(ahead_cmd_str, handle_numeric_result("ahead_count"))
end
local function get_git_ahead_behind_info()
async_git_status_update()
local status = git_status_cache
if not status then
return ""
end
local msg = ""
if type(status.ahead_count) == "number" and status.ahead_count > 0 then
local ahead_str = string.format("↑[%d] ", status.ahead_count)
msg = msg .. ahead_str
end
if type(status.behind_count) == "number" and status.behind_count > 0 then
local behind_str = string.format("↓[%d] ", status.behind_count)
msg = msg .. behind_str
end
return msg
end
local function spell()
if vim.o.spell then
return string.format("[SPELL]")
end
return ""
end
--- show indicator for Chinese IME
local function ime_state()
if vim.g.is_mac then
-- ref: https://github.com/vim-airline/vim-airline/blob/master/autoload/airline/extensions/xkblayout.vim#L11
local layout = fn.libcall(vim.g.XkbSwitchLib, "Xkb_Switch_getXkbLayout", "")
-- We can use `xkbswitch -g` on the command line to get current mode.
-- mode for macOS builtin pinyin IME: com.apple.inputmethod.SCIM.ITABC
-- mode for Rime: im.rime.inputmethod.Squirrel.Rime
local res = fn.match(layout, [[\v(Squirrel\.Rime|SCIM.ITABC)]])
if res ~= -1 then
return "[CN]"
end
end
return ""
end
local function trailing_space()
if not vim.o.modifiable then
return ""
end
local line_num = nil
for i = 1, fn.line("$") do
local linetext = fn.getline(i)
-- To prevent invalid escape error, we wrap the regex string with `[[]]`.
local idx = fn.match(linetext, [[\v\s+$]])
if idx ~= -1 then
line_num = i
break
end
end
local msg = ""
if line_num ~= nil then
msg = string.format("[%d]trailing", line_num)
end
return msg
end
local function mixed_indent()
if not vim.o.modifiable then
return ""
end
local space_pat = [[\v^ +]]
local tab_pat = [[\v^\t+]]
local space_indent = fn.search(space_pat, "nwc")
local tab_indent = fn.search(tab_pat, "nwc")
local mixed = (space_indent > 0 and tab_indent > 0)
local mixed_same_line
if not mixed then
mixed_same_line = fn.search([[\v^(\t+ | +\t)]], "nwc")
mixed = mixed_same_line > 0
end
if not mixed then
return ""
end
if mixed_same_line ~= nil and mixed_same_line > 0 then
return "MI:" .. mixed_same_line
end
local space_indent_cnt = fn.searchcount({ pattern = space_pat, max_count = 1e3 }).total
local tab_indent_cnt = fn.searchcount({ pattern = tab_pat, max_count = 1e3 }).total
if space_indent_cnt > tab_indent_cnt then
return "MI:" .. tab_indent
else
return "MI:" .. space_indent
end
end
local diff = function()
local git_status = vim.b.gitsigns_status_dict
if git_status == nil then
return
end
local modify_num = git_status.changed
local remove_num = git_status.removed
local add_num = git_status.added
local info = { added = add_num, modified = modify_num, removed = remove_num }
-- vim.print(info)
return info
end
local virtual_env = function()
-- only show virtual env for Python
if vim.bo.filetype ~= "python" then
return ""
end
local conda_env = os.getenv("CONDA_DEFAULT_ENV")
local venv_path = os.getenv("VIRTUAL_ENV")
if venv_path == nil then
if conda_env == nil then
return ""
else
return string.format(" %s (conda)", conda_env)
end
else
local venv_name = vim.fn.fnamemodify(venv_path, ":t")
return string.format(" %s (venv)", venv_name)
end
end
local get_active_lsp = function()
local msg = "🚫"
local buf_ft = vim.api.nvim_get_option_value("filetype", {})
local clients = vim.lsp.get_clients { bufnr = 0 }
if next(clients) == nil then
return msg
end
for _, client in ipairs(clients) do
---@diagnostic disable-next-line: undefined-field
local filetypes = client.config.filetypes
if filetypes and vim.fn.index(filetypes, buf_ft) ~= -1 then
return client.name
end
end
return msg
end
require("lualine").setup {
options = {
icons_enabled = true,
theme = "auto",
component_separators = { left = "⏐", right = "⏐" },
section_separators = "",
disabled_filetypes = {},
always_divide_middle = true,
refresh = {
statusline = 1000,
},
},
sections = {
lualine_a = {
{
"filename",
symbols = {
readonly = "[🔒]",
},
},
},
lualine_b = {
{
"branch",
fmt = function(name, _)
-- truncate branch name in case the name is too long
return string.sub(name, 1, 20)
end,
color = { gui = "italic,bold" },
},
{
get_git_ahead_behind_info,
color = { fg = "#E0C479" },
},
{
"diff",
source = diff,
},
{
virtual_env,
color = { fg = "black", bg = "#F1CA81" },
},
},
lualine_c = {
{
"%S",
color = { gui = "bold", fg = "cyan" },
},
{
spell,
color = { fg = "black", bg = "#a7c080" },
},
},
lualine_x = {
{
get_active_lsp,
icon = "📡",
},
{
"diagnostics",
sources = { "nvim_diagnostic" },
symbols = { error = "🆇 ", warn = "⚠️ ", info = "ℹ️ ", hint = "" },
},
{
trailing_space,
color = "WarningMsg",
},
{
mixed_indent,
color = "WarningMsg",
},
},
lualine_y = {
{
"encoding",
fmt = string.upper,
},
{
"fileformat",
symbols = {
unix = "unix",
dos = "win",
mac = "mac",
},
},
"filetype",
{
ime_state,
color = { fg = "black", bg = "#f46868" },
},
},
lualine_z = {
"location",
"progress",
},
},
inactive_sections = {
lualine_a = {},
lualine_b = {},
lualine_c = { "filename" },
lualine_x = { "location" },
lualine_y = {},
lualine_z = {},
},
tabline = {},
extensions = { "quickfix", "fugitive", "nvim-tree" },
}

106
lua/config/nvim-cmp.lua Normal file
View File

@@ -0,0 +1,106 @@
local cmp = require("cmp")
require("cmp_nvim_lsp")
require("cmp_path")
require("cmp_buffer")
require("cmp_omni")
require("cmp_nvim_ultisnips")
require("cmp_cmdline")
local MiniIcons = require("mini.icons")
cmp.setup {
snippet = {
expand = function(args)
vim.fn["UltiSnips#Anon"](args.body)
end,
},
mapping = cmp.mapping.preset.insert {
["<Tab>"] = function(fallback)
if cmp.visible() then
cmp.select_next_item()
else
fallback()
end
end,
["<S-Tab>"] = function(fallback)
if cmp.visible() then
cmp.select_prev_item()
else
fallback()
end
end,
["<CR>"] = cmp.mapping.confirm { select = true },
["<C-e>"] = cmp.mapping.abort(),
["<Esc>"] = cmp.mapping.close(),
["<C-d>"] = cmp.mapping.scroll_docs(-4),
["<C-f>"] = cmp.mapping.scroll_docs(4),
},
sources = {
{ name = "nvim_lsp" },
{ name = "ultisnips" },
{ name = "path" },
{ name = "buffer", keyword_length = 2 },
},
completion = {
keyword_length = 1,
completeopt = "menu,noselect",
},
view = {
entries = "custom",
},
formatting = {
format = function(_, vim_item)
local icon, hl = MiniIcons.get("lsp", vim_item.kind)
vim_item.kind = icon .. " " .. vim_item.kind
vim_item.kind_hl_group = hl
return vim_item
end,
},
}
cmp.setup.filetype("tex", {
sources = {
{ name = "omni" },
{ name = "ultisnips" },
{ name = "buffer", keyword_length = 2 },
{ name = "path" },
},
})
cmp.setup.cmdline("/", {
mapping = cmp.mapping.preset.cmdline(),
sources = {
{ name = "buffer" },
},
})
cmp.setup.cmdline(":", {
mapping = cmp.mapping.preset.cmdline(),
sources = cmp.config.sources({
{ name = "path" },
}, {
{ name = "cmdline" },
}),
matching = { disallow_symbol_nonprefix_matching = false },
})
vim.cmd([[
highlight! link CmpItemMenu Comment
" gray
highlight! CmpItemAbbrDeprecated guibg=NONE gui=strikethrough guifg=#808080
" blue
highlight! CmpItemAbbrMatch guibg=NONE guifg=#569CD6
highlight! CmpItemAbbrMatchFuzzy guibg=NONE guifg=#569CD6
" light blue
highlight! CmpItemKindVariable guibg=NONE guifg=#9CDCFE
highlight! CmpItemKindInterface guibg=NONE guifg=#9CDCFE
highlight! CmpItemKindText guibg=NONE guifg=#9CDCFE
" pink
highlight! CmpItemKindFunction guibg=NONE guifg=#C586C0
highlight! CmpItemKindMethod guibg=NONE guifg=#C586C0
" front
highlight! CmpItemKindKeyword guibg=NONE guifg=#D4D4D4
highlight! CmpItemKindProperty guibg=NONE guifg=#D4D4D4
highlight! CmpItemKindUnit guibg=NONE guifg=#D4D4D4
]])

27
lua/config/nvim-hop.lua Normal file
View File

@@ -0,0 +1,27 @@
local keymap = vim.keymap
local hop = require("hop")
hop.setup {
case_insensitive = true,
char2_fallback_key = "<CR>",
quit_key = "<Esc>",
}
keymap.set({ "n", "v", "o" }, "f", "", {
silent = true,
noremap = true,
callback = function()
hop.hint_char2()
end,
desc = "nvim-hop char2",
})
vim.api.nvim_create_autocmd("ColorScheme", {
pattern = "*",
callback = function()
vim.cmd([[
hi HopNextKey cterm=bold ctermfg=176 gui=bold guibg=#ff00ff guifg=#ffffff
hi HopNextKey cterm=bold ctermfg=176 gui=bold guibg=#ff00ff guifg=#ffffff
hi HopNextKey cterm=bold ctermfg=176 gui=bold guibg=#ff00ff guifg=#ffffff
]])
end,
})

View File

@@ -0,0 +1,8 @@
local nvim_notify = require("notify")
nvim_notify.setup {
stages = "fade_in_slide_out",
timeout = 1500,
background_colour = "#2E3440",
}
vim.notify = nvim_notify

View File

@@ -0,0 +1,22 @@
local builtin = require("statuscol.builtin")
local ffi = require("statuscol.ffidef")
local C = ffi.C
local fold_level_limit = 3
local function foldfunc(args)
local foldinfo = C.fold_info(args.wp, args.lnum)
if foldinfo.level > fold_level_limit then
return " "
end
return builtin.foldfunc(args)
end
require("statuscol").setup {
relculright = false,
segments = {
{ text = { "%s" }, click = "v:lua.ScSa" },
{ text = { builtin.lnumfunc, " " }, click = "v:lua.ScLa" },
{ text = { foldfunc, " " }, condition = { true, builtin.not_empty }, click = "v:lua.ScFa" },
},
}

108
lua/config/nvim-tree.lua Normal file
View File

@@ -0,0 +1,108 @@
local keymap = vim.keymap
local nvim_tree = require("nvim-tree")
nvim_tree.setup {
auto_reload_on_write = true,
disable_netrw = false,
hijack_netrw = true,
hijack_cursor = false,
hijack_unnamed_buffer_when_opening = false,
open_on_tab = false,
sort_by = "name",
update_cwd = false,
view = {
width = 30,
side = "left",
preserve_window_proportions = false,
number = false,
relativenumber = false,
signcolumn = "yes",
},
renderer = {
indent_markers = {
enable = false,
icons = {
corner = "└ ",
edge = "| ",
none = " ",
},
},
icons = {
webdev_colors = true,
},
},
hijack_directories = {
enable = true,
auto_open = true,
},
update_focused_file = {
enable = false,
update_cwd = false,
ignore_list = {},
},
system_open = {
cmd = "",
args = {},
},
diagnostics = {
enable = false,
show_on_dirs = false,
icons = {
hint = "",
info = "",
warning = "",
error = "",
},
},
filters = {
dotfiles = false,
custom = {},
exclude = {},
},
git = {
enable = true,
ignore = true,
timeout = 400,
},
actions = {
use_system_clipboard = true,
change_dir = {
enable = true,
global = false,
restrict_above_cwd = false,
},
open_file = {
quit_on_open = false,
resize_window = false,
window_picker = {
enable = true,
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890",
exclude = {
filetype = { "notify", "qf", "diff", "fugitive", "fugitiveblame" },
buftype = { "nofile", "terminal", "help" },
},
},
},
},
trash = {
cmd = "trash",
require_confirm = true,
},
log = {
enable = false,
truncate = false,
types = {
all = false,
config = false,
copy_paste = false,
diagnostics = false,
git = false,
profile = false,
},
},
}
keymap.set("n", "<space>s", require("nvim-tree.api").tree.toggle, {
silent = true,
desc = "toggle nvim-tree",
})

41
lua/config/nvim-ufo.lua Normal file
View File

@@ -0,0 +1,41 @@
local handler = function(virtText, lnum, endLnum, width, truncate)
local newVirtText = {}
local foldedLines = endLnum - lnum
local suffix = (" 󰁂 %d"):format(foldedLines)
local sufWidth = vim.fn.strdisplaywidth(suffix)
local targetWidth = width - sufWidth
local curWidth = 0
for _, chunk in ipairs(virtText) do
local chunkText = chunk[1]
local chunkWidth = vim.fn.strdisplaywidth(chunkText)
if targetWidth > curWidth + chunkWidth then
table.insert(newVirtText, chunk)
else
chunkText = truncate(chunkText, targetWidth - curWidth)
local hlGroup = chunk[2]
table.insert(newVirtText, { chunkText, hlGroup })
chunkWidth = vim.fn.strdisplaywidth(chunkText)
if curWidth + chunkWidth < targetWidth then
suffix = suffix .. (" "):rep(targetWidth - curWidth - chunkWidth)
end
break
end
curWidth = curWidth + chunkWidth
end
local rAlignAppndx = math.max(math.min(vim.opt.textwidth["_value"], width - 1) - curWidth - sufWidth, 0)
suffix = (" "):rep(rAlignAppndx) .. suffix
table.insert(newVirtText, { suffix, "MoreMsg" })
return newVirtText
end
require("ufo").setup {
fold_virt_text_handler = handler,
}
vim.keymap.set("n", "zR", require("ufo").openAllFolds)
vim.keymap.set("n", "zM", require("ufo").closeAllFolds)
vim.keymap.set("n", "zr", require("ufo").openFoldsExceptKinds)
vim.keymap.set("n", "<leader>K", function()
local _ = require("ufo").peekFoldedLinesUnderCursor()
end, { desc = "Preview folded maps" })

View File

@@ -0,0 +1,23 @@
require("nvim-treesitter.configs").setup {
textobjects = {
select = {
enable = true,
lookahead = true,
keymaps = {
["af"] = "@function.outer",
["if"] = "@function.inner",
["ac"] = "@class.outer",
["ic"] = { query = "@class.inner", desc = "select inner part of a class region" },
},
selection_modes = {
["@function.inner"] = "V",
["@function.outer"] = "V",
["@class.outer"] = "V",
["@class.inner"] = "V",
["@parameter.outer"] = "v",
},
include_surrounding_whitespace = false,
},
},
}

View File

@@ -0,0 +1,8 @@
require("nvim-treesitter.configs").setup {
ensure_installed = { "python", "cpp", "lua", "vim", "json", "toml" },
ignore_install = {},
highlight = {
enable = true,
disable = { "help" },
},
}

6
lua/config/which-key.lua Normal file
View File

@@ -0,0 +1,6 @@
require("which-key").setup {
present = "modern",
icons = {
mappings = false,
},
}

15
lua/config/yanky.lua Normal file
View File

@@ -0,0 +1,15 @@
require("yanky").setup {
preserve_cursor_position = {
enabled = false,
},
highlight = {
on_put = true,
on_yank = false,
timer = 300,
},
}
vim.keymap.set({ "n", "x" }, "p", "<Plug>(YankyPutAfter)")
vim.keymap.set({ "n", "x" }, "P", "<Plug>(YankyPutBefore)")
vim.keymap.set("n", "[y", "<Plug>(YankyPreviousEntry)")
vim.keymap.set("n", "]y", "<Plug>(YankyNextEntry)")

217
lua/custom-autocmd.lua Normal file
View File

@@ -0,0 +1,217 @@
local fn = vim.fn
local api = vim.api
local utils = require("utils")
-- Display a message when the current file is not in utf-8 format
api.nvim_create_autocmd({ "BufRead" }, {
pattern = "*",
group = api.nvim_create_augroup("non_utf8_file", { clear = true }),
callback = function()
if vim.bo.fileencoding ~= "utf-8" then
vim.notify("File not in UTF-8 format!", vim.log.levels.WARN, { title = "nvim-config" })
end
end,
})
-- Highlight yanked region
local yank_group = api.nvim_create_augroup("highlight_yank", { clear = true })
api.nvim_create_autocmd({ "TextYankPost" }, {
pattern = "*",
group = yank_group,
callback = function()
vim.hl.on_yank { higroup = "YankColor", timeout = 300 }
end,
})
api.nvim_create_autocmd({ "CursorMoved" }, {
pattern = "*",
group = yank_group,
callback = function()
vim.g.current_cursor_pos = vim.fn.getcurpos()
end,
})
api.nvim_create_autocmd("TextYankPost", {
pattern = "*",
group = yank_group,
---@diagnostic disable-next-line: unused-local
callback = function(ctx)
if vim.v.event.operator == "y" then
vim.fn.setpos(".", vim.g.current_cursor_pos)
end
end,
})
-- Auto-create dir when saving a file in case some intermediate directory does not exist
api.nvim_create_autocmd({ "BufWritePre" }, {
pattern = "*",
group = api.nvim_create_augroup("auto_create_dir", { clear = true }),
callback = function(ctx)
local dir = fn.fnamemodify(ctx.file, ":p:h")
utils.may_create_dir(dir)
end,
})
-- Automatically reload the file if it is changed outside of nvim
-- It seems that `checktime` does not work in command line, so we need to check if we are in
-- command line before executing this command
local auto_read_group = api.nvim_create_augroup("auto_read", { clear = true })
api.nvim_create_autocmd({ "FileChangedShellPost" }, {
pattern = "*",
group = auto_read_group,
callback = function()
vim.notify("File changed on disk. Buffer reloaded!", vim.log.levels.WARN, { title = "nvim-config" })
end,
})
api.nvim_create_autocmd({ "FocusGained", "CursorHold" }, {
pattern = "*",
group = auto_read_group,
callback = function()
if fn.getcmdwintype() == "" then
vim.cmd("checktime")
end
end,
})
-- Resize all windows when we resize the terminal
api.nvim_create_autocmd("VimResized", {
group = api.nvim_create_augroup("win_autoresize", { clear = true }),
command = "wincmd =",
})
local function open_nvim_tree(data)
local is_directory = vim.fn.isdirectory(data.file) == 1
if not directory then
return
end
vim.cmd.enew()
vim.cmd.bw(data.buf)
require("nvim-tree.api").tree.open()
end
api.nvim_create_autocmd({ "VimEnter" }, { callback = open_nvim_tree })
-- Do not use smart case in command line mode
api.nvim_create_augroup("dynamic_smartcase", { clear = true })
api.nvim_create_autocmd("CmdLineEnter", {
group = "dynamic_smartcase",
pattern = ":",
callback = function()
vim.o.smartcase = false
end,
})
api.nvim_create_autocmd("CmdLineLeave", {
group = "dynamic_smartcase",
pattern = ":",
callback = function()
vim.o.smartcase = true
end,
})
api.nvim_create_autocmd("TermOpen", {
group = api.nvim_create_augroup("term_start", { clear = true }),
pattern = "*",
callback = function()
vim.wo.relativenumber = false
vim.wo.number = false
vim.cmd("startinsert")
end,
})
local number_toggle_group = api.nvim_create_augroup("numbertoggle", { clear = true })
api.nvim_create_autocmd({ "BufEnter", "FocusGained", "InsertLeave", "WinEnter" }, {
pattern = "*",
group = number_toggle_group,
callback = function()
if vim.wo.number then
vim.wo.relativenumber = true
end
end,
})
api.nvim_create_autocmd({ "BufLeave", "FocusLost", "InsertEnter", "WinLeave" }, {
group = number_toggle_group,
callback = function()
if vim.wo.number then
vim.wo.relativenumber = false
end
end,
})
api.nvim_create_autocmd("ColorScheme", {
group = api.nvim_create_augroup("custom_highlight", { clear = true }),
pattern = "*",
desc = "Define or override some highlight groups",
callback = function()
vim.api.nvim_set_hl(0, "YankColor", { fg = "#34495E", bg = "#2ECC71", ctermfg = 59, ctermbg = 41 })
vim.api.nvim_set_hl(0, "Cursor", { fg = "black", bg = "#00C918", bold = true })
vim.api.nvim_set_hl(0, "Cursor2", { fg = "red", bg = "red" })
vim.api.nvim_set_hl(0, "FloatBorder", { fg = "LightGreen", bg = "None", bold = true })
local hl = vim.api.nvim_get_hl(0, { name = "NormalFloat" })
vim.api.nvim_set_hl(0, "NormalFloat", { fg = hl.fg, bg = "None" })
vim.api.nvim_set_hl(0, "MatchParen", { bold = true, underline = true })
end,
})
api.nvim_create_autocmd("BufEnter", {
pattern = "*",
group = api.nvim_create_augroup("auto_close_win", { clear = true }),
desc = "Quit nvim if we have only one window and its filetype matches our pattern",
---@diagnostic disable-next-line: unused-local
callback = function(ctx)
local quit_filetypes = { "qf", "vista", "NvimTree" }
local should_quit = true
local tabwins = api.nvim_tabpage_list_wins(0)
for _, win in pairs(tabwins) do
local buf = api.nvim_win_get_buf(win)
local buf_type = vim.api.nvim_get_option_value("filetype", { buf = buf })
if not vim.tbl_contains(quit_filetypes, buf_type) then
should_quit = false
end
end
if should_quit then
vim.cmd("qall")
end
end,
})
api.nvim_create_autocmd({ "VimEnter", "DirChanged" }, {
group = api.nvim_create_augroup("git_repo_check", { clear = true }),
pattern = "*",
desc = "Check if we are inside a git repo",
callback = function()
utils.inside_git_repo()
end,
})
-- ref: https://vi.stackexchange.com/a/169/15292
api.nvim_create_autocmd("BufReadPre", {
group = api.nvim_create_augroup("large_file", { clear = true }),
pattern = "*",
desc = "Optimize for large files",
callback = function(ctx)
local file_size_limit = 524288 -- 0.5MB
local f = ctx.file
if fn.getfsize(f) > file_size_limit or fn.getfsize(f) == -2 then
vim.o.eventignore = "all"
vim.o.ruler = true
vim.wo.relativenumber = false
vim.wo.number = false
vim.bo.swapfile = false
vim.bo.bufhidden = "unload"
vim.bo.undolevels = -1
end
end,
})

62
lua/diagnostic-conf.lua Normal file
View File

@@ -0,0 +1,62 @@
local diagnostic = vim.diagnostic
local api = vim.api
-- Global config for diagnostic
diagnostic.config {
underline = false,
virtual_text = false,
virtual_lines = false,
signs = {
text = {
[diagnostic.severity.ERROR] = "🆇",
[diagnostic.severity.WARN] = "⚠️",
[diagnostic.severity.INFO] = "ℹ️",
[diagnostic.severity.HINT] = "",
},
},
severity_sort = true,
float = {
source = true,
header = "Diagnostics:",
prefix = " ",
border = "single",
},
}
-- Set quickfix list from diagnostics in a certain buffer, not the whole workspace
local set_qflist = function(buf_num, severity)
local diagnostics = nil
diagnostics = diagnostic.get(buf_num, { severity = severity })
local qf_items = diagnostic.toqflist(diagnostics)
vim.fn.setqflist({}, " ", { title = "Diagnostics", items = qf_items })
vim.cmd([[copen]])
end
vim.keymap.set("n", "<space>qw", diagnostic.setqflist, { desc = "Put window diagnostics to qf" })
vim.keymap.set("n", "<space>qb", function()
set_qflist(0)
end, { desc = "Put buffer diagnostics to qf" })
-- Automatically show diagnostic in float win for current line
api.nvim_create_autocmd("CursorHold", {
pattern = "*",
callback = function()
if #vim.diagnostic.get(0) == 0 then
return
end
if not vim.b.diagnostics_pos then
vim.b.diagnostics_pos = { nil, nil }
end
local cursor_pos = api.nvim_win_get_cursor(0)
if not vim.deep_equal(cursor_pos, vim.b.diagnostics_pos) then
diagnostic.open_float { width = 100 }
end
vim.b.diagnostics_pos = cursor_pos
end,
})

58
lua/globals.lua Normal file
View File

@@ -0,0 +1,58 @@
local fn = vim.fn
local api = vim.api
local utils = require("utils")
-- Custom variables
vim.g.is_win = (utils.has("win32") or utils.has("win64")) and true or false
vim.g.is_linux = (utils.has("unix") and (not utils.has("macunix"))) and true or false
vim.g.is_mac = utils.has("macunix") and true or false
vim.g.logging_level = vim.log.levels.INFO
-- Built-in variables
vim.g.loaded_perl_provider = 0
vim.g.loaded_ruby_provider = 0
vim.g.loaded_node_provider = 0
vim.g.did_install_default_menus = 1 -- do not load menu
vim.g.python3_host_prog = "~/.local/share/nvim/venv/bin/python"
vim.g.mapleader = ","
-- Enable highlighting for lua HERE doc inside vim script
vim.g.vimsyn_embed = "l"
-- Use English as main language
vim.cmd([[language en_US.UTF-8]])
-- Disable loading certain plugins
-- Whether to load netrw by default
vim.g.loaded_netrw = 1
vim.g.loaded_netrwPlugin = 1
vim.g.netrw_liststyle = 3
if vim.g.is_win then
vim.g.netrw_http_cmd = "curl --ssl-no-revoke -Lo"
end
-- Don't load tohtml.vim
vim.g.loaded_2html_plugin = 1
-- Don't load zipPlugin.vim, gzip.vim, or tarPlugin.vim
vim.g.loaded_zipPlugin = 1
vim.g.loaded_gzip = 1
vim.g.loaded_tarPlugin = 1
-- Don't load the tutor plugin
vim.g.loaded_tutor_mode_plugin = 1
-- Don't use built-in matchit.vim and matchparen.vim since we use vim-matchup
vim.g.loaded_matchit = 1
vim.g.loaded_matchparen = 1
-- Disable sql omni completion since it's broken
vim.g.loaded_sql_completion = 1
-- Control how to show health check window
vim.g.health = { style = nil }

14
lua/lsp_utils.lua Normal file
View File

@@ -0,0 +1,14 @@
local M = {}
M.get_default_capabilities = function()
local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities.textDocument.foldingRange = {
dynamicRegistration = false,
lineFoldingOnly = true,
}
return capabilities
end
return M

153
lua/mappings.lua Normal file
View File

@@ -0,0 +1,153 @@
local keymap = vim.keymap
local uv = vim.uv
keymap.set({ "n", "x" }, ";", ":", { desc = "enter command mode" })
keymap.set("i", "<c-u>", "<Esc>viwUea", { desc = "make word upper case" })
keymap.set("i", "<c-t>", "<Esc>b~lea", { desc = "make word title case" })
keymap.set("n", "<leader>p", "m`o<ESC>p``", { desc = "paste below current line" })
keymap.set("n", "<leader>P", "m`O<ESC>p``", { desc = "paste above current line" })
keymap.set("n", "<leader>w", "<cmd>update<cr>", { silent = true, desc = "save buffer" })
keymap.set("n", "<leader>q", "<cmd>x<cr>", { silent = true, desc = "quit current window" })
keymap.set("n", "<leader>Q", "<cmd>qa!<cr>", { silent = true, desc = "quit nvim" })
keymap.set("n", [[\x]], "<cmd>windo lclose <bar> cclose <cr>", {
silent = true,
desc = "close qf and location lists",
})
keymap.set("n", [[\d]], "<cmd>bprevious <bar> bdelete #<cr>", {
silent = true,
desc = "delete current buffer",
})
keymap.set("n", [[\D]], function()
local buf_ids = vim.api.nvim_list_bufs()
local cur_buf = vim.api.nvim_win_get_buf(0)
for _, buf_id in pairs(buf_ids) do
if vim.api.nvim_get_option_value("buflisted", { buf = buf_id }) and buf_id ~= cur_buf then
vim.api.nvim_buf_delete(buf_id, { force = true })
end
end
end, { desc = "delete other buffers" })
keymap.set("n", "<space>o", "printf('m`%so<ESC>``', v:count1)", {
expr = true,
desc = "insert line below",
})
keymap.set("n", "<space>O", "printf('m`%sO<ESC>``', v:count1)", {
expr = true,
desc = "insert line above",
})
-- Move the cursor base on physical lines, not the actual lines
keymap.set("n", "j", "v:count == 0 ? 'gj' : 'j'", { expr = true })
keymap.set("n", "k", "v:count == 0 ? 'gk' : 'k'", { expr = true })
keymap.set("n", "^", "g^")
keymap.set("n", "0", "g0")
-- Don't include white space characters when using '$' in visual mode
keymap.set("x", "$", "g_")
-- Go to start and end of line easier
keymap.set({ "n", "x" }, "H", "^")
keymap.set({ "n", "x" }, "L", "g_")
-- Continuous visual shifting
keymap.set("x", "<", "<gv")
keymap.set("x", ">", ">gv")
keymap.set("n", "<leader>ev", "<cmd>tabnew $MYVIMRC <bar> tcd %:h<cr>", {
silent = true,
desc = "open init.lua",
})
keymap.set("n", "<leader>sv", function()
vim.cmd([[
update $MYVIMRC
source $MYVIMRC
]])
vim.notify("Nvim config successfully reloaded!", vim.log.levels.INFO, { title = "nvim-config" })
end, { silent = true, desc = "reload init.lua" })
keymap.set("n", "<leader>v", "printf('`[%s`]', getregtype()[0])", {
expr = true,
desc = "reselect last pasted area",
})
keymap.set("n", "<leader>cd", "<cmd>lcd %:p:h<cr><cmd>pwd<cr>", { desc = "change cwd" })
keymap.set("t", "<Esc>", [[<c-\><c-n>]], { desc = "quit term" })
keymap.set("n", "<F11>", "<cmd>set spell!<cr>", { desc = "toggle spell" })
keymap.set("i", "<F11>", "<c-o><cmd>set spell!<cr>", { desc = "toggle spell" })
-- Change text without putting it into the vim register
keymap.set("n", "c", '"_c')
keymap.set("n", "C", '"_C')
keymap.set("n", "cc", '"_cc')
keymap.set("x", "c", '"_c')
keymap.set("n", "<leader><space>", "<cmd>StripTrailingWhitespace<cr>", { desc = "remove trailing spaces" })
keymap.set("n", "<leader>y", "<cmd>%yank<cr>", { desc = "yank entire buffer" })
keymap.set("n", "<leader>cl", "<cmd>call utils#ToggleCursorCol()<cr>", { desc = "toggle cursor column" })
keymap.set("n", "<A-k>", '<cmd>call utils#SwitchLine(line("."), "up")<cr>', { desc = "move line up" })
keymap.set("n", "<A-j>", '<cmd>call utils#SwitchLine(line("."), "down")<cr>', { desc = "move line down" })
keymap.set("x", "<A-k>", '<cmd>call utils#MoveSelection("up")<cr>', { desc = "move selection up" })
keymap.set("x", "<A-j>", '<cmd>call utils#MoveSelection("down")<cr>', { desc = "move selection down" })
keymap.set("x", "p", '"_c<Esc>p', { desc = "replace visual selection with text in register without contaminating the register" })
keymap.set("n", "gb", '<cmd>call buf_utils#GoToBuffer(v:count, "forward")<cr>', {
desc = "go to buffer (forward)",
})
keymap.set("n", "gB", '<cmd>call buf_utils#GoToBuffer(v:count, "backward")<cr>', {
desc = "go to buffer (backward)",
})
-- Switch windows
keymap.set("n", "<left>", "<c-w>h")
keymap.set("n", "<right>", "<c-w>l")
keymap.set("n", "<up>", "<c-w>k")
keymap.set("n", "<down>", "<c-w>j")
keymap.set({ "x", "o" }, "iu", "<cmd>call text_obj#URL()<cr>", { desc = "URL text object" })
keymap.set({ "x", "o" }, "iB", ":<C-U>call text_obj#Buffer()<cr>", { desc = "buffer text object" })
keymap.set("n", "J", function()
vim.cmd([[
normal! mzJ`z
delmarks z
]])
end, { desc = "join lines without moving cursor" })
keymap.set("n", "gJ", function()
vim.cmd([[
normal! mzgJ`z
delmarks z
]])
end, { desc = "join lines without moving cursor" })
-- Break inserted text into smaller undo units
local undo_ch = { ",", ".", "!", "?", ";", ":" }
for _, ch in ipairs(undo_ch) do
keymap.set("i", ch, ch .. "<c-g>u")
end
keymap.set("i", "<A-;>", "<Esc>miA;<Esc>`ii", { desc = "insert semicolon at end" })
keymap.set("i", "<c-a>", "<HOME>", { desc = "go to beginning of line" })
keymap.set("i", "<c-e>", "<END>", { desc = "go to end of line" })
keymap.set("c", "<c-a>", "<HOME>", { desc = "go to beginning of command" })
keymap.set("i", "<c-d>", "<DEL>", { desc = "delete character to right of cursor" })
keymap.set("n", "<leader>cb", function()
local cnt = 0
local blink_times = 7
local timer = uv.new_timer()
if timer == nil then
return
end
timer:start(
0,
100,
vim.schedule_wrap(function()
vim.cmd([[
set cursorcolumn!
set cursorline!
]])
if cnt == blink_times then
timer:close()
end
cnt = cnt + 1
end)
)
end, { desc = "show cursor" })

405
lua/plugin_specs.lua Normal file
View File

@@ -0,0 +1,405 @@
local utils = require("utils")
local plugin_dir = vim.fn.stdpath("data") .. "/lazy"
local lazypath = plugin_dir .. "/lazy.nvim"
if not vim.uv.fs_stat(lazypath) then
vim.fn.system {
"git",
"clone",
"--filter=blob:none",
"https://github.com/folke/lazy.nvim.git",
"--branch=stable",
lazypath,
}
end
vim.opt.rtp:prepend(lazypath)
local firenvim_not_active = function()
return not vim.g.started_by_firenvim
end
local plugin_specs = {
{ "hrsh7th/cmp-nvim-lsp", lazy = true },
{ "hrsh7th/cmp-path", lazy = true },
{ "hrsh7th/cmp-buffer", lazy = true },
{ "hrsh7th/cmp-omni", lazy = true },
{ "hrsh7th/cmp-cmdline", lazy = true },
{ "quangnguyen30192/cmp-nvim-ultisnips", lazy = true },
{
"hrsh7th/nvim-cmp",
name = "nvim-cmp",
event = "VeryLazy",
config = function()
require("config.nvim-cmp")
end,
},
{
"echasnovski/mini.icons",
version = false,
config = function()
require("mini.icons").mock_nvim_web_devicons()
require("mini.icons").tweak_lsp_kind()
end,
lazy = true,
},
{
"SirVer/ultisnips",
dependencies = {
"honza/vim-snippets",
},
event = "InsertEnter",
},
{
"neovim/nvim-lspconfig",
config = function()
require("config.lsp")
end,
},
{
"dnlhc/glance.nvim",
config = function()
require("config.glance")
end,
event = "VeryLazy",
},
{
"nvim-treesitter/nvim-treesitter",
lazy = true,
build = ":TSUpdate",
config = function()
require("config.treesitter")
end,
},
{
"nvim-treesitter/nvim-treesitter-textobjects",
event = "VeryLazy",
branch = "master",
config = function()
require("config.treesitter-textobjects")
end,
},
{ "machakann/vim-swap", event = "VeryLazy" },
{
"smoka7/hop.nvim",
keys = { "f" },
config = function()
require("config.nvim-hop")
end,
},
{
"kevinhwang91/nvim-hlslens",
branch = "main",
keys = { "*", "#", "n", "N" },
config = function()
require("config.hlslens")
end,
},
{
"nvim-telescope/telescope.nvim",
cmd = "Telescope",
dependencies = {
"nvim-telescope/telescope-symbols.nvim",
},
},
{
"ibhagwan/fzf-lua",
config = function()
require("config.fzf-lua")
end,
event = "VeryLazy",
},
{
"MeanderingProgrammer/markdown.nvim",
main = "render-markdown",
opts = {},
ft = { "markdown" },
},
{ "navarasu/onedark.nvim", lazy = true },
{ "sainnhe/edge", lazy = true },
{ "sainnhe/sonokai", lazy = true },
{ "sainnhe/gruvbox-material", lazy = true },
{ "sainnhe/everforest", lazy = true },
{ "EdenEast/nightfox.nvim", lazy = true },
{ "catppuccin/nvim", name = "catppuccin", lazy = true },
{ "olimorris/onedarkpro.nvim", lazy = true },
{ "marko-cerovac/material.nvim", lazy = true },
{
"rockyzhang24/arctic.nvim",
dependencies = { "rktjmp/lush.nvim" },
name = "arctic",
branch = "v2",
},
{ "rebelot/kanagawa.nvim", lazy = true },
{ "miikanissi/modus-themes.nvim", priority = 1000 },
{ "wtfox/jellybeans.nvim", priority = 1000 },
{ "projekt0n/github-nvim-theme", name = "github-theme" },
{ "e-ink-colorscheme/e-ink.nvim", priority = 1000 },
{ "ficcdaf/ashen.nvim", priority = 1000 },
{ "savq/melange-nvim", priority = 1000 },
{ "Skardyy/makurai-nvim", priority = 1000 },
{ "vague2k/vague.nvim", priority = 1000 },
{ "webhooked/kanso.nvim", priority = 1000 },
{ "zootedb0t/citruszest.nvim", priority = 1000 },
{
"nvim-lualine/lualine.nvim",
event = "BufRead",
cond = firenvim_not_active,
config = function()
require("config.lualine")
end,
},
{
"akinsho/bufferline.nvim",
event = { "BufEnter" },
cond = firenvim_not_active,
config = function()
require("config.bufferline")
end,
},
{
"nvimdev/dashboard-nvim",
cond = firenvim_not_active,
config = function()
require("config.dashboard-nvim")
end,
},
{
"echasnovski/mini.indentscope",
version = false,
config = function()
local mini_indent = require("mini.indentscope")
mini_indent.setup {
draw = {
animation = mini_indent.gen_animation.none(),
},
symbol = "▏",
}
end,
},
{
"luukvbaal/statuscol.nvim",
opts = {},
config = function()
require("config.nvim-statuscol")
end,
},
{
"kevinhwang91/nvim-ufo",
dependencies = "kevinhwang91/promise-async",
event = "VeryLazy",
opts = {},
init = function()
vim.o.foldcolumn = "1"
vim.o.foldlevel = 99
vim.o.foldlevelstart = 99
vim.o.foldenable = true
end,
config = function()
require("config.nvim-ufo")
end,
},
{ "itchyny/vim-highlighturl", event = "BufReadPost" },
{
"rcarriga/nvim-notify",
event = "VeryLazy",
config = function()
require("config.nvim-notify")
end,
},
{"nvim-lua/plenary.nvim", lazy = true },
{
"liuchengxu/vista.vim",
enabled = function()
return utils.executable("ctags")
end,
cmd = "Vista",
},
{
"windwp/nvim-autopairs",
event = "InsertEnter",
config = true,
},
{
"tpope/vim-commentary",
keys = {
{ "gc", mode = "n" },
{ "gc", mode = "v" },
},
},
{ "simnalamburt/vim-mundo", cmd = { "MundoToggle", "MundoShow" } },
{
"gbprod/yanky.nvim",
config = function()
require("config.yanky")
end,
cmd = "YankyRingHistory",
},
{ "tpope/vim-eunuch", cmd = { "Rename", "Delete" } },
{ "tpope/vim-repeat", event = "VeryLazy" },
{ "nvim-zh/better-escape.vim", event = { "InsertEnter" } },
{
"tpope/vim-fugitive",
event = "User InGitRepo",
config = function()
require("config.fugitive")
end,
},
{
"NeogitOrg/neogit",
dependencies = {
"nvim-lua/plenary.nvim",
},
event = "User InGitRepo",
},
{ "rbong/vim-flog", cmd = { "Flog" } },
{
"akinsho/git-conflict.nvim",
version = "*",
event = "VeryLazy",
config = function()
require("config.git-conflict")
end,
},
{
"ruifm/gitlinker.nvim",
event = "User InGitRepo",
config = function()
require("config.git-linker")
end,
},
{
"lewis6991/gitsigns.nvim",
config = function()
require("config.gitsigns")
end,
event = "BufRead",
},
{
"sindrets/diffview.nvim",
cmd = { "DiffViewOpen" },
},
{
"kevinhwang91/nvim-bqf",
ft = "qf",
config = function()
require("config.bqf")
end,
},
{ "vim-pandoc/vim-markdownfootnotes", ft = { "markdown" } },
{ "godlygeek/tabular", ft = { "markdown" } },
{ "chrisbra/unicode.vim", keys = { "ga" }, cmd = { "UnicodeSearch" } },
{ "wellle/targets.vim", event = "VeryLazy" },
{ "machakann/vim-sandwich", event = "VeryLazy" },
{
"tmux-plugins/vim-tmux",
enabled = function()
return utils.executable("tmux")
end,
ft = { "tmux" },
},
{ "andymass/vim-matchup", event = "BufRead" },
{ "tpope/vim-scriptease", cmd = { "Scriptnames", "Messages", "Verbose" } },
{ "skywind3000/asyncrun.vim", lazy = true, cmd = { "AsyncRun" } },
{ "cespare/vim-toml", ft = { "toml" }, branch = "main" },
{
"sakhnik/nvim-gdb",
enabled = function()
return vim.g.is_win or vim.g.is_linux
end,
build = { "bash install.sh" },
lazy = true,
},
{ "tpope/vim-obsession", cmd = "Obsession" },
{
"ojroques/vim-oscyank",
enabled = function()
return vim.g.is_linux
end,
cmd = { "OSCYank", "OSCYankReg" },
},
{
"folke/which-key.nvim",
event = "VeryLazy",
config = function()
require("config.which-key")
end,
},
{
"folke/snacks.nvim",
priority = 1000,
lazy = false,
opts = {
input = {
enabled = true,
win = {
relative = "cursor",
backdrop = true,
},
},
picker = { enabled = true },
image = { enabled = false },
},
},
{ "jdhao/whitespace.nvim", event = "VeryLazy" },
{
"nvim-tree/nvim-tree.lua",
keys = { "<space>s" },
config = function()
require("config.nvim-tree")
end,
},
{
"j-hui/fidget.nvim",
event = "BufRead",
config = function()
require("config.fidget-nvim")
end,
},
{
"folke/lazydev.nvim",
ft = "lua",
opts = {
library = {
{ path = "${3rd}/luv/library", words = { "vim%.uv" } },
},
},
},
{
"smjonas/live-command.nvim",
event = "VeryLazy",
config = function()
require("config.live-command")
end,
},
{
"kosayoda/nvim-lightbulb",
config = function()
require("config.lightbulb")
end,
event = "LspAttach",
},
{
"Bekaboo/dropbar.nvim",
event = "VeryLazy",
},
{
"catgoose/nvim-colorizer.lua",
event = "BufReadPre",
opts = {},
},
}
---@diagnostic disable-next-line: missing-fields
require("lazy").setup {
spec = plugin_specs,
ui = {
border = "rounded",
title = "Plugin Manager",
title_pos = "center",
},
rocks = {
enabled = false,
hererocks = false,
},
}

87
lua/utils.lua Normal file
View File

@@ -0,0 +1,87 @@
local fn = vim.fn
local version = vim.version
local M = {}
--- Check if an executable exists
--- @param name string An executable name/path
--- @return boolean
function M.executable(name)
return fn.executable(name) > 0
end
--- Check whether a feature exists in nvim
--- @param feat string the feature name, like `nvim-0.7` or `unix`
--- @return boolean
M.has = function(feat)
if fn.has(feat) == 1 then
return true
end
return false
end
--- Create a dir if it does not exist
function M.may_create_dir(dir)
local res = fn.isdirectory(dir)
if res == 0 then
fn.mkdir(dir, "p")
end
end
--- Generate random integers in the range [low, high], inclusive,
--- @param low integer the lower value for this range
--- @param high integer the upper value for this range
--- @return integer
function M.rand_int(low, high)
math.randomseed(os.time())
return math.random(low, high)
end
--- Select a random element from a sequence/list
--- @param seq any[] the sequence to choose an element from
function M.rand_element(seq)
local idx = M.rand_int(1, #seq)
return seq[idx]
end
--- Check if the current nvim version is compatible with the allowed version
--- @param expected_version string
--- @return boolean
function M.is_compatible_version(expected_version)
local expect_ver = version.parse(expected_version)
local actual_ver = vim.version()
if expect_ver == nil then
local msg = string.format("Unsupported version string: %s", expected_version)
vim.api.nvim_echo({ { msg } }, true, { err = true })
return false
end
local result = version.cmp(expect_ver, actual_ver)
if result ~= 0 then
local _ver = string.format("%s.%s.%s", actual_ver.major, actual_ver.minor, actual_ver.patch)
local msg = string.format(
"Expect nvim version %s, but your current nvim version is %s. Use at your own risk!",
expected_version,
_ver
)
vim.api.nvim_echo({ { msg } }, true, { err = true })
end
return true
end
--- Check if we are inside a git repo
--- @return boolean
function M.inside_git_repo()
local result = vim.system({ "git", "rev-parse", "--is-inside-work-tree" }, { text = true }):wait()
if result.code ~= 0 then
return false
end
vim.cmd([[doautocmd User InGitRepo]])
return true
end
return M