diff options
| author | srdusr <trevorgray@srdusr.com> | 2025-09-24 02:55:49 +0200 |
|---|---|---|
| committer | srdusr <trevorgray@srdusr.com> | 2025-09-24 02:55:49 +0200 |
| commit | 3cf613ec7c90ab4933728b0f19e49b0c955c17bb (patch) | |
| tree | 765e58766936b5228ad473ad77dfbf4353f173e9 /common/nvim/lua/user | |
| parent | ef51a60993197ed3bbd1003522f98f0a898d34c6 (diff) | |
| parent | 966d12ac730c83da90d60ab24eae539b2ea69441 (diff) | |
| download | dotfiles-3cf613ec7c90ab4933728b0f19e49b0c955c17bb.tar.gz dotfiles-3cf613ec7c90ab4933728b0f19e49b0c955c17bb.zip | |
Add 'common/nvim/' from commit '966d12ac730c83da90d60ab24eae539b2ea69441'
git-subtree-dir: common/nvim
git-subtree-mainline: ef51a60993197ed3bbd1003522f98f0a898d34c6
git-subtree-split: 966d12ac730c83da90d60ab24eae539b2ea69441
Diffstat (limited to 'common/nvim/lua/user')
| -rwxr-xr-x | common/nvim/lua/user/keys.lua | 928 | ||||
| -rwxr-xr-x | common/nvim/lua/user/mods.lua | 1427 | ||||
| -rwxr-xr-x | common/nvim/lua/user/opts.lua | 438 | ||||
| -rwxr-xr-x | common/nvim/lua/user/view.lua | 180 |
4 files changed, 2973 insertions, 0 deletions
diff --git a/common/nvim/lua/user/keys.lua b/common/nvim/lua/user/keys.lua new file mode 100755 index 0000000..63b64fa --- /dev/null +++ b/common/nvim/lua/user/keys.lua @@ -0,0 +1,928 @@ +-- ============================================================================ +-- Key Mappings +-- ============================================================================ + +local map = function(mode, l, r, opts) + if r == nil then + vim.notify("Attempted to map key '" .. l .. "' but RHS is nil", vim.log.levels.WARN) + return + end + opts = vim.tbl_extend('force', { + silent = true, + noremap = true + }, opts or {}) + vim.keymap.set(mode, l, r, opts) +end + +-- Leader key +vim.g.mapleader = ";" +vim.g.maplocalleader = "\\" + +-- Tmux/Vim navigation +local function smart_move(direction, tmux_cmd) + local curwin = vim.api.nvim_get_current_win() + vim.cmd('wincmd ' .. direction) + if curwin == vim.api.nvim_get_current_win() then + vim.fn.system('tmux select-pane ' .. tmux_cmd) + end +end + +-- Window Navigation +map('n', '<C-h>', function() smart_move('h', '-L') end) +map('n', '<C-j>', function() smart_move('j', '-D') end) +map('n', '<C-k>', function() smart_move('k', '-U') end) +map('n', '<C-l>', function() smart_move('l', '-R') end) + +-- Buffer Navigation +map('n', '<leader>bn', '<cmd>bnext<CR>') +map('n', '<leader>bp', '<cmd>bprevious<CR>') +--map('n', '<leader>bd', '<cmd>bdelete<CR>') +map('n', '<leader>ba', '<cmd>%bdelete<CR>') + + + +-- Get list of loaded buffers in order +local function get_buffers() + local bufs = {} + for _, buf in ipairs(vim.api.nvim_list_bufs()) do + if vim.api.nvim_buf_is_loaded(buf) then + table.insert(bufs, buf) + end + end + return bufs +end + +-- Swap two buffers by index in the buffer list +local function swap_buffers(idx1, idx2) + local bufs = get_buffers() + local buf1 = bufs[idx1] + local buf2 = bufs[idx2] + if not buf1 or not buf2 then return end + local name1 = vim.api.nvim_buf_get_name(buf1) + local name2 = vim.api.nvim_buf_get_name(buf2) + vim.cmd("b " .. buf1) + vim.cmd("file " .. name2) + vim.cmd("b " .. buf2) + vim.cmd("file " .. name1) +end + +-- Move current buffer left +vim.keymap.set("n", "<leader>bh", function() + local bufs = get_buffers() + local curr = vim.api.nvim_get_current_buf() + local idx + for i, b in ipairs(bufs) do if b == curr then idx = i break end end + if idx and idx > 1 then + swap_buffers(idx, idx-1) + end +end, { noremap = true, silent = true }) + +-- Move current buffer right +vim.keymap.set("n", "<leader>bl", function() + local bufs = get_buffers() + local curr = vim.api.nvim_get_current_buf() + local idx + for i, b in ipairs(bufs) do if b == curr then idx = i break end end + if idx and idx < #bufs then + swap_buffers(idx, idx+1) + end +end, { noremap = true, silent = true }) +-- Save and Quit +map('n', '<leader>w', '<cmd>w<CR>') +map('n', '<leader>q', '<cmd>q<CR>') +map('n', '<leader>wq', '<cmd>wq<CR>') +map('n', '<leader>Q', '<cmd>qa!<CR>') + +-- Resize Windows +map('n', '<M-Up>', '<cmd>resize -2<CR>') +map('n', '<M-Down>', '<cmd>resize +2<CR>') +map('n', '<M-Left>', '<cmd>vertical resize -2<CR>') +map('n', '<M-Right>', '<cmd>vertical resize +2<CR>') + +-- Quickfix and Location List +map('n', ']q', '<cmd>cnext<CR>zz') +map('n', '[q', '<cmd>cprev<CR>zz') +map('n', ']l', '<cmd>lnext<CR>zz') +map('n', '[l', '<cmd>lprev<CR>zz') + +-- Terminal Mode +map('t', '<Esc>', '<C-\\><C-n>') +map('t', '<C-h>', '<C-\\><C-n><C-w>h') +map('t', '<C-j>', '<C-\\><C-n><C-w>j') +map('t', '<C-k>', '<C-\\><C-n><C-w>k') +map('t', '<C-l>', '<C-\\><C-n><C-w>l') + +-- Insert mode escape +map('i', 'jk', '<ESC>') + +-- Tmux/(n)vim navigation +local function smart_move(direction, tmux_cmd) + local curwin = vim.api.nvim_get_current_win() + vim.cmd('wincmd ' .. direction) + if curwin == vim.api.nvim_get_current_win() then + vim.fn.system('tmux select-pane ' .. tmux_cmd) + end +end + +map('n', '<C-h>', function() smart_move('h', '-L') end, {silent = true}) +map('n', '<C-j>', function() smart_move('j', '-D') end, {silent = true}) +map('n', '<C-k>', function() smart_move('k', '-U') end, {silent = true}) +map('n', '<C-l>', function() smart_move('l', '-R') end, {silent = true}) + + +-- Jump to next match on line using `.` instead of `;` NOTE: commented out in favour of "ggandor/flit.nvim" +--map("n", ".", ";") + +-- Repeat last command using `<Space>` instead of `.` NOTE: commented out in favour of "ggandor/flit.nvim" +--map("n", "<Space>", ".") + +-- Reload nvim config +map("n", "<leader><CR>", +"<cmd>luafile ~/.config/nvim/init.lua<CR> | :echom ('Nvim config loading...') | :sl! | echo ('')<CR>") + +vim.keymap.set("t", "<Esc>", "<C-\\><C-n>", { desc = "Exit terminal mode" }) +vim.keymap.set("t", "<C-b>", "<C-\\><C-n>", { desc = "Exit terminal mode" }) + +--------------- Extended Operations --------------- +-- Conditional 'q' to quit on floating/quickfix/help windows otherwise still use it for macros +-- TODO: Have a list of if available on system/packages, example "Zen Mode" to not work on it (quit Zen Mode) +map("n", "q", function() + local config = vim.api.nvim_win_get_config(0) + if config.relative ~= "" then -- is_floating_window? + return ":silent! close!<CR>" + elseif vim.o.buftype == "quickfix" then + return ":quit<CR>" + elseif vim.o.buftype == "help" then + return ":close<CR>" + else + return "q" + end +end, { expr = true, replace_keycodes = true }) + +-- Minimalist Tab Completion +map("i", "<Tab>", function() + local col = vim.fn.col('.') - 1 + local line = vim.fn.getline('.') + local prev_char = line:sub(col, col) + if vim.fn.pumvisible() == 1 or prev_char:match("%w") then + return vim.api.nvim_replace_termcodes("<C-n>", true, true, true) + else + return vim.api.nvim_replace_termcodes("<Tab>", true, true, true) + end +end, { expr = true }) + +-- Shift-Tab for reverse completion +map("i", "<S-Tab>", function() + if vim.fn.pumvisible() == 1 then + return vim.api.nvim_replace_termcodes("<C-p>", true, true, true) + else + return vim.api.nvim_replace_termcodes("<S-Tab>", true, true, true) + end +end, { expr = true }) + + +-- Toggle completion +map("n", "<Leader>tc", ':lua require("user.mods").toggle_completion()<CR>') + +-- Minimalist Auto Completion +map("i", "<CR>", function() + -- Exit this keymap if nvim-cmp is present + local cmp_is_present, _ = pcall(require, "cmp") + if cmp_is_present and require("cmp").visible() then + return vim.api.nvim_replace_termcodes("<C-y>", true, true, true) + elseif cmp_is_present then + return vim.api.nvim_replace_termcodes("<CR>", true, true, true) + end + + -- when cmp is NOT present + if vim.fn.pumvisible() == 1 then + return vim.api.nvim_replace_termcodes("<C-y>", true, true, true) + else + return vim.api.nvim_replace_termcodes("<CR>", true, true, true) + end +end, { expr = true }) + +-- Closing compaction in insert mode +map("i", "[", "[]<Left>") +map("i", "(", "()<Left>") +map("i", "{", "{}<Left>") +map("i", "/*", "/**/<Left><Left>") + +-- Edit new file +map("n", "<leader>e", [[:e <C-R>=expand("%:h")..'/'<CR>]], { noremap = true, silent = true, desc = "New file" }) + +-- Write as sudo +map("c", "W!", "exe 'w !sudo tee >/dev/null %:p:S' | setl nomod", { silent = true, desc = "Write as Sudo" }) + +-- Don't format on save +map("c", "F!", ":noautocmd w<CR>") + +-- Combine buffers list with buffer name +map("n", "<Leader>b", ":buffers<CR>:buffer<Space>") + +-- Buffer confirmation +map("n", "<leader>y", ":BufferPick<CR>") + +-- Map buffer next, prev and delete to <leader>+(n/p/d) respectively and tab/s-tab +map("n", "<leader>n", ":bn<cr>") +map("n", "<leader>p", ":bp<cr>") +map("n", "<leader>d", ":bd<cr>") +map("n", "<TAB>", ":bnext<CR>") +map("n", "<S-TAB>", ":bprevious<CR>") + +-- Close all buffers and reopen last one +map("n", "<leader>D", ":update | %bdelete | edit # | normal `<CR>") + +-- Delete file of current buffer +map("n", "<leader>rm", "<CMD>call delete(expand('%')) | bdelete!<CR>") + +-- List marks +map("n", "<Leader>M", ":marks<CR>") + +-- Messages +map("n", "<Leader>m", ":messages<CR>") + +--- Clear messages or just refresh/redraw the screen +map("n", "<leader>i", function() + local ok, notify = pcall(require, "notify") + if ok then + notify.dismiss() + end +end) + +-- Toggle set number +map("n", "<leader>$", ":NumbersToggle<CR>") +map("n", "<leader>%", ":NumbersOnOff<CR>") + +-- Easier split navigations, just ctrl-j instead of ctrl-w then j +map("t", "<C-[>", "<C-\\><C-N>") +map("t", "<C-h>", "<C-\\><C-N><C-h>") +map("t", "<C-j>", "<C-\\><C-N><C-j>") +map("t", "<C-k>", "<C-\\><C-N><C-k>") +map("t", "<C-l>", "<C-\\><C-N><C-l>") + +-- Split window +map("n", "<leader>-", ":split<CR>") +map("n", "<leader>\\", ":vsplit<CR>") + +-- Close window +--map("n", "<leader>c", "<C-w>c") +map({ "n", "t", "c" }, "<leader>c", function() + local winid = vim.api.nvim_get_current_win() + local config = vim.api.nvim_win_get_config(winid) + + if config.relative ~= "" then + -- This is a floating window + vim.cmd("CloseFloatingWindows") + else + -- Not a float/close window + vim.cmd("close") + end +end, { desc = "Close current float or all floating windows" }) + +-- Resize Panes +map("n", "<Leader><", ":vertical resize +5<CR>") +map("n", "<Leader>>", ":vertical resize -5<CR>") +map("n", "<Leader>=", "<C-w>=") + +-- Mapping for left and right arrow keys in command-line mode +vim.api.nvim_set_keymap("c", "<A-h>", "<Left>", { noremap = true, silent = false }) -- Left Arrow +vim.api.nvim_set_keymap("c", "<A-l>", "<Right>", { noremap = true, silent = false }) -- Right Arrow + +-- Map Alt+(h/j/k/l) in insert(include terminal/command) mode to move directional +map({ "i", "t" }, "<A-h>", "<Left>") +map({ "i", "t" }, "<A-j>", "<Down>") +map({ "i", "t" }, "<A-k>", "<Up>") +map({ "i", "t" }, "<A-l>", "<Right>") + +-- Create tab, edit and move between them +map("n", "<C-T>n", ":tabnew<CR>") +map("n", "<C-T>e", ":tabedit") +map("n", "<leader>[", ":tabprev<CR>") +map("n", "<leader>]", ":tabnext<CR>") + +-- Vim TABs +map("n", "<leader>1", "1gt<CR>") +map("n", "<leader>2", "2gt<CR>") +map("n", "<leader>3", "3gt<CR>") +map("n", "<leader>4", "4gt<CR>") +map("n", "<leader>5", "5gt<CR>") +map("n", "<leader>6", "6gt<CR>") +map("n", "<leader>7", "7gt<CR>") +map("n", "<leader>8", "8gt<CR>") +map("n", "<leader>9", "9gt<CR>") +map("n", "<leader>0", "10gt<CR>") + +-- Hitting ESC when inside a terminal to get into normal mode +--map("t", "<Esc>", [[<C-\><C-N>]]) + +-- Move block (indentation) easily +--map("n", "<", "<<", term_opts) +--map("n", ">", ">>", term_opts) +--map("x", "<", "<gv", term_opts) +--map("x", ">", ">gv", term_opts) +--map("v", "<", "<gv") +--map("v", ">", ">gv") +--map("n", "<", "<S-v><<esc>change mode to normal") +--map("n", ">", "<S-v>><esc>change mode to normal") + +-- Visual mode: Indent and reselect the visual area, like default behavior but explicit +map("v", "<", "<gv", { desc = "Indent left and reselect" }) +map("v", ">", ">gv", { desc = "Indent right and reselect" }) + +-- Normal mode: Indent current line and enter Visual Line mode to repeat easily +map("n", "<", "v<<", { desc = "Indent left and select" }) +map("n", ">", "v>>", { desc = "Indent right and select" }) + +---- Visual mode: Indent and reselect the visual area, like default behavior but explicit +--map("v", "<", "<", { desc = "Indent left" }) +--map("v", ">", ">", { desc = "Indent right" }) +-- +---- Normal mode: Indent current line and enter Visual Line mode to repeat easily +--map("n", "<", "v<<", { desc = "Indent left and select" }) +--map("n", ">", "v>>", { desc = "Indent right and select" }) + +-- Set alt+(j/k) to switch lines of texts or simply move them +map("n", "<A-k>", ':let save_a=@a<Cr><Up>"add"ap<Up>:let @a=save_a<Cr>') +map("n", "<A-j>", ':let save_a=@a<Cr>"add"ap:let @a=save_a<Cr>') + +-- Toggle Diff +map("n", "<leader>df", "<Cmd>call utils#ToggleDiff()<CR>") + +-- Toggle Verbose +map("n", "<leader>uvt", "<Cmd>call utils#VerboseToggle()<CR>") + +-- Jump List +map("n", "<leader>j", "<Cmd>call utils#GotoJump()<CR>") + +-- Rename file +map("n", "<leader>rf", "<Cmd>call utils#RenameFile()<CR>") + +-- Map delete to Ctrl+l +map("i", "<C-l>", "<Del>") + +-- Clear screen +map("n", "<leader><C-l>", "<Cmd>!clear<CR>") + +-- Change file to an executable +map("n", "<Leader>x", +":lua require('user.mods').Toggle_executable()<CR> | :echom ('Toggle executable')<CR> | :sl! | echo ('')<CR>") +-- map("n", "<leader>x", ":!chmod +x %<CR>") + +vim.keymap.set("n", "<leader>cm", function() + vim.cmd("redir @+") + vim.cmd("silent messages") + vim.cmd("redir END") + vim.notify("Copied :messages to clipboard") +end, { desc = "Copy :messages to clipboard" }) + +-- Paste without replace clipboard +map("v", "p", '"_dP') + +map("n", "]p", 'm`o<Esc>"+p``', opts) + +map("n", "[p", 'm`O<Esc>"+p``', opts) + +-- Bind Ctrl-V to paste in insert/normal/command mode +map("i", "<C-v>", "<C-G>u<C-R><C-P>+", opts) +map("n", "<C-v>", '"+p', { noremap = true, silent = true }) +vim.api.nvim_set_keymap("c", "<C-v>", "<C-R>=getreg('+')<CR><BS>", { noremap = true, silent = false }) + +-- Change Working Directory to current project +map("n", "<leader>cd", ":cd %:p:h<CR>:pwd<CR>") + +-- Search and replace +map("v", "<leader>sr", 'y:%s/<C-r><C-r>"//g<Left><Left>c') + +-- Substitute globally and locally in the selected region. +map("n", "<leader>s", ":%s//g<Left><Left>") +map("v", "<leader>s", ":s//g<Left><Left>") + +-- Set line wrap +map("n", "<M-z>", function() + local wrap_status = vim.api.nvim_exec("set wrap ?", true) + + if wrap_status == "nowrap" then + vim.api.nvim_command("set wrap linebreak") + print("Wrap enabled") + else + vim.api.nvim_command("set wrap nowrap") + print("Wrap disabled") + end +end, { silent = true }) + +-- Toggle between folds +map("n", "<Space>", "&foldlevel ? 'zM' : 'zR'", { expr = true }) + +-- Use space to toggle fold +--map("n", "<Space>", "za") + +map("n", "<leader>.b", ":!cp % %.backup<CR>") + +-- Go to next window +map("n", "<leader>wn", "<C-w>w", { desc = "Next window" }) + +-- Go to previous window +map("n", "<leader>wp", "<C-w>W", { desc = "Previous window" }) + +-- Toggle transparency +map("n", "<leader>tb", ":call utils#Toggle_transparent_background()<CR>") + +-- Toggle zoom +map("n", "<leader>z", ":call utils#ZoomToggle()<CR>") +map("n", "<C-w>z", "<C-w>|<C-w>_") + +-- Toggle statusline +map("n", "<leader>sl", ":call utils#ToggleHiddenAll()<CR>") + +-- Open last closed buffer +map("n", "<C-t>", ":call utils#OpenLastClosed()<CR>") + + +-- Automatically set LSP keymaps when LSP attaches to a buffer +--vim.api.nvim_create_autocmd("LspAttach", { +-- callback = function(args) +-- local bufnr = args.buf +-- local opts = { buffer = bufnr } +-- map("n", "K", vim.lsp.buf.hover) +-- map("n", "gd", "<cmd>lua require('goto-preview').goto_preview_definition()<CR>") +-- map("n", "gi", "<cmd>lua require('goto-preview').goto_preview_implementation()<CR>") +-- map("n", "gr", "<cmd>lua require('goto-preview').goto_preview_references()<CR>") +-- map("n", "gD", vim.lsp.buf.declaration) +-- map("n", "<leader>k", vim.lsp.buf.signature_help) +-- map("n", "gt", "<cmd>lua require('goto-preview').goto_preview_type_definition()<CR>") +-- map("n", "gn", vim.lsp.buf.rename) +-- map("n", "ga", vim.lsp.buf.code_action) +-- map("n", "gf", function() vim.lsp.buf.format({ async = true }) end) +-- map("n", "go", vim.diagnostic.open_float) +-- map("n", "<leader>go", ":call utils#ToggleDiagnosticsOpenFloat()<CR> | :echom ('Toggle Diagnostics Float open/close...')<CR> | :sl! | echo ('')<CR>") +-- map("n", "gq", vim.diagnostic.setloclist) +-- map("n", "[d", vim.diagnostic.goto_prev) +-- map("n", "]d", vim.diagnostic.goto_next) +-- map("n", "gs", vim.lsp.buf.document_symbol) +-- map("n", "gw", vim.lsp.buf.workspace_symbol) +-- map("n", "<leader>wa", vim.lsp.buf.add_workspace_folder) +-- map("n", "<leader>wr", vim.lsp.buf.remove_workspace_folder) +-- map("n", "<leader>wl", function() +-- print(vim.inspect(vim.lsp.buf.list_workspace_folders())) +-- end) +-- end, +--}) + +---- LSP Global Keymaps (available in all buffers) +--map("n", "[d", vim.diagnostic.goto_prev, { desc = "LSP: Previous Diagnostic" }) +--map("n", "]d", vim.diagnostic.goto_next, { desc = "LSP: Next Diagnostic" }) +--map("n", "go", vim.diagnostic.open_float, { desc = "LSP: Open Diagnostic Float" }) +-- +---- LSP Buffer-local keymaps function (to be called from LSP on_attach) +--_G.setup_lsp_keymaps = function(bufnr) +-- local bmap = function(mode, l, r, opts) +-- opts = opts or {} +-- opts.silent = true +-- opts.noremap = true +-- opts.buffer = bufnr +-- vim.keymap.set(mode, l, r, opts) +-- end +-- +-- bmap("n", "K", vim.lsp.buf.hover, { desc = "LSP: Hover Documentation" }) +-- bmap("n", "gd", vim.lsp.buf.definition, { desc = "LSP: Go to Definition" }) +-- bmap("n", "gD", vim.lsp.buf.declaration, { desc = "LSP: Go to Declaration" }) +-- bmap("n", "gi", vim.lsp.buf.implementation, { desc = "LSP: Go to Implementation" }) +-- bmap("n", "gt", vim.lsp.buf.type_definition, { desc = "LSP: Go to Type Definition" }) +-- bmap("n", "gr", vim.lsp.buf.references, { desc = "LSP: Go to References" }) +-- bmap("n", "gn", vim.lsp.buf.rename, { desc = "LSP: Rename" }) +-- bmap("n", "ga", vim.lsp.buf.code_action, { desc = "LSP: Code Action" }) +-- bmap("n", "<leader>k", vim.lsp.buf.signature_help, { desc = "LSP: Signature Help" }) +-- bmap("n", "gs", vim.lsp.buf.document_symbol, { desc = "LSP: Document Symbols" }) +--end + +-- LSP Global Keymaps (available in all buffers) +map("n", "[d", vim.diagnostic.goto_prev, { desc = "LSP: Previous Diagnostic" }) +map("n", "]d", vim.diagnostic.goto_next, { desc = "LSP: Next Diagnostic" }) +map("n", "go", vim.diagnostic.open_float, { desc = "LSP: Open Diagnostic Float" }) +map("n", "<leader>go", ":call utils#ToggleDiagnosticsOpenFloat()<CR> | :echom ('Toggle Diagnostics Float open/close...')<CR> | :sl! | echo ('')<CR>") + +-- LSP Buffer-local keymaps function (to be called from LSP on_attach) +_G.setup_lsp_keymaps = function(bufnr) + local bmap = function(mode, l, r, opts) + opts = opts or {} + opts.silent = true + opts.noremap = true + opts.buffer = bufnr + vim.keymap.set(mode, l, r, opts) + end + + -- Your preferred keybindings + bmap("n", "K", function() + vim.lsp.buf.hover { border = "single", max_height = 25, max_width = 120 } + end, { desc = "LSP: Hover Documentation" }) + + bmap("n", "gd", function() + vim.lsp.buf.definition { + on_list = function(options) + -- Custom logic to avoid showing multiple definitions for Lua patterns like: + -- `local M.my_fn_name = function() ... end` + 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 + vim.fn.setloclist(0, {}, " ", options) + + -- Open location list if multiple definitions, otherwise jump directly + if #options.items > 1 then + vim.cmd.lopen() + else + vim.cmd([[silent! lfirst]]) + end + end, + } + end, { desc = "LSP: Go to Definition" }) + + bmap("n", "<C-]>", vim.lsp.buf.definition, { desc = "LSP: Go to Definition (Alt)" }) + bmap("n", "gD", vim.lsp.buf.declaration, { desc = "LSP: Go to Declaration" }) + bmap("n", "gi", vim.lsp.buf.implementation, { desc = "LSP: Go to Implementation" }) + bmap("n", "gt", vim.lsp.buf.type_definition, { desc = "LSP: Go to Type Definition" }) + bmap("n", "gr", vim.lsp.buf.references, { desc = "LSP: Go to References" }) + bmap("n", "gn", vim.lsp.buf.rename, { desc = "LSP: Rename" }) + bmap("n", "<leader>rn", vim.lsp.buf.rename, { desc = "LSP: Rename (Alt)" }) + bmap("n", "ga", vim.lsp.buf.code_action, { desc = "LSP: Code Action" }) + bmap("n", "<leader>ca", vim.lsp.buf.code_action, { desc = "LSP: Code Action (Alt)" }) + bmap("n", "<leader>k", vim.lsp.buf.signature_help, { desc = "LSP: Signature Help" }) + bmap("n", "<C-k>", vim.lsp.buf.signature_help, { desc = "LSP: Signature Help (Alt)" }) + bmap("n", "gs", vim.lsp.buf.document_symbol, { desc = "LSP: Document Symbols" }) + + -- Workspace folder management + bmap("n", "<leader>wa", vim.lsp.buf.add_workspace_folder, { desc = "LSP: Add Workspace Folder" }) + bmap("n", "<leader>wr", vim.lsp.buf.remove_workspace_folder, { desc = "LSP: Remove Workspace Folder" }) + bmap("n", "<leader>wl", function() + vim.print(vim.lsp.buf.list_workspace_folders()) + end, { desc = "LSP: List Workspace Folders" }) +end + +---------------- Plugin Operations ---------------- +-- Packer +map("n", "<leader>Pc", "<cmd>PackerCompile<cr>") +map("n", "<leader>Pi", "<cmd>PackerInstall<cr>") +map("n", "<leader>Ps", "<cmd>PackerSync<cr>") +map("n", "<leader>PS", "<cmd>PackerStatus<cr>") +map("n", "<leader>Pu", "<cmd>PackerUpdate<cr>") + +-- ToggleTerm +map({ "n", "t" }, "<leader>tt", "<cmd>ToggleTerm<CR>") +map({ "n", "t" }, "<leader>th", "<cmd>lua Horizontal_term_toggle()<CR>") +map({ "n", "t" }, "<leader>tv", "<cmd>lua Vertical_term_toggle()<CR>") + +-- LazyGit +map({ "n", "t" }, "<leader>gg", "<cmd>lua Lazygit_toggle()<CR>") + +map("n", "<leader>tg", "<cmd>lua Gh_dash()<CR>") + +-- Fugitive git bindings +map("n", "<leader>gs", vim.cmd.Git) +map("n", "<leader>ga", ":Git add %:p<CR><CR>") +--map("n", "<leader>gs", ":Gstatus<CR>") +--map("n", "<leader>gc", ":Gcommit -v -q<CR>") +map("n", "<leader>gt", ":Gcommit -v -q %:p<CR>") +map("n", "<leader>gd", ":Gdiff<CR>") +map("n", "<leader>ge", ":Gedit<CR>") +--map("n", "<leader>gr", ":Gread<Cj>") +map("n", "<leader>gw", ":Gwrite<CR><CR>") +map("n", "<leader>gl", ":silent! Glog<CR>:bot copen<CR>") +--map("n", "<leader>gp", ":Ggrep<Space>") +--map("n", "<Leader>gp", ":Git push<CR>") +--map("n", "<Leader>gb", ":Gblame<CR>") +map("n", "<leader>gm", ":Gmove<Space>") +--map("n", "<leader>gb", ":Git branch<Space>") +--map("n", "<leader>go", ":Git checkout<Space>") +--map("n", "<leader>gps", ":Dispatch! git push<CR>") +--map("n", "<leader>gpl", ":Dispatch! git pull<CR>") + +-- Telescope +-- Safe load of your custom Telescope module +-- This initial pcall for "plugins.telescope" is fine because it just checks if YOUR module is there. +-- The actual checks for Telescope's core modules happen *inside* your wrapper functions when called. +local telescope_ok, telescope_module = pcall(require, "plugins.telescope") + +if telescope_ok and telescope_module then + + -- Direct function calls from your plugins.telescope module + -- M.safe_find_files handles its own internal `builtin` check + map("n", "<leader>ff", telescope_module.safe_find_files, { desc = "Find files" }) + + -- For `find all files`, use your `safe_telescope_builtin` wrapper + -- You need to wrap it in a function to pass the options correctly. + map("n", "<leader>f.", function() + telescope_module.safe_telescope_builtin("find_files")({ hidden = true, no_ignore = true }) + end, { desc = "Find all files" }) + + + --- + --- Built-in Telescope functions + --- Note: safe_telescope_builtin returns a function, so you map directly to it. + --- + map("n", "<leader>fg", function() telescope_module.safe_telescope_builtin("live_grep")() end, { desc = "Live grep" }) + map("n", "<leader>fb", function() telescope_module.safe_telescope_builtin("buffers")() end, { desc = "Find buffers" }) + map("n", "<leader>fh", function() telescope_module.safe_telescope_builtin("help_tags")() end, { desc = "Help tags" }) + map("n", "<leader>fc", function() telescope_module.safe_telescope_builtin("commands")() end, { desc = "Commands" }) + map("n", "<leader>fd", function() telescope_module.safe_telescope_builtin("diagnostics")() end, { desc = "Diagnostics" }) + map("n", "<leader>fk", function() telescope_module.safe_telescope_builtin("keymaps")() end, { desc = "Keymaps" }) + map("n", "<leader>fr", function() telescope_module.safe_telescope_builtin("registers")() end, { desc = "Registers" }) + map("n", "<leader>ffc", function() telescope_module.safe_telescope_builtin("current_buffer_fuzzy_find")() end, { desc = "Current buffer fuzzy find" }) + -- Corrected the previous `fp` mapping that pointed to `pickers` + map("n", "<leader>fp", function() telescope_module.safe_telescope_builtin("oldfiles")() end, { desc = "Recently opened files" }) + + + --- + --- Telescope Extension functions + --- Note: safe_telescope_extension returns a function, so you map directly to it. + --- + map("n", "<leader>cf", function() telescope_module.safe_telescope_extension("changed_files", "changed_files")() end, { desc = "Changed files" }) + map("n", "<leader>fm", function() telescope_module.safe_telescope_extension("media_files", "media_files")() end, { desc = "Media files" }) + map("n", "<leader>fi", function() telescope_module.safe_telescope_extension("notify", "notify")() end, { desc = "Notifications" }) + map("n", "<Leader>fs", function() telescope_module.safe_telescope_extension("session-lens", "search_session")() end, { desc = "Search sessions" }) + map("n", "<Leader>frf", function() telescope_module.safe_telescope_extension("recent_files", "pick")() end, { desc = "Recent files" }) + map("n", "<Leader>f/", function() telescope_module.safe_telescope_extension("file_browser", "file_browser")() end, { desc = "File browser" }) + + + --- + --- Custom functions defined in plugins.telescope.lua + --- Note: safe_telescope_call returns a function, so you map directly to it. + --- (These were already correct as safe_telescope_call returns a callable function) + --- + map("n", "<leader>ffd", telescope_module.safe_telescope_call("plugins.telescope", "find_dirs"), { desc = "Find directories" }) + map("n", "<leader>ff.", telescope_module.safe_telescope_call("plugins.telescope", "find_configs"), { desc = "Find configs" }) + map("n", "<leader>ffs", telescope_module.safe_telescope_call("plugins.telescope", "find_scripts"), { desc = "Find scripts" }) + map("n", "<leader>ffw", telescope_module.safe_telescope_call("plugins.telescope", "find_projects"), { desc = "Find projects" }) + map("n", "<leader>ffB", telescope_module.safe_telescope_call("plugins.telescope", "find_books"), { desc = "Find books" }) + map("n", "<leader>ffn", telescope_module.safe_telescope_call("plugins.telescope", "find_notes"), { desc = "Find notes" }) + map("n", "<leader>fgn", telescope_module.safe_telescope_call("plugins.telescope", "grep_notes"), { desc = "Grep notes" }) + map("n", "<leader>fpp", telescope_module.safe_telescope_call("plugins.telescope", "find_private"), { desc = "Find private notes" }) + map("n", "<leader>fgc", telescope_module.safe_telescope_call("plugins.telescope", "grep_current_dir"), { desc = "Grep current directory" }) + +end +---- Fallback keymaps when telescope is not available +--map("n", "<leader>ff", function() +-- local file = vim.fn.input("Open file: ", "", "file") +-- if file ~= "" then +-- vim.cmd("edit " .. file) +-- end +--end, { desc = "Find files (fallback)" }) + +---- You can add other basic fallbacks here +--map("n", "<leader>fg", function() +-- vim.notify("Live grep requires telescope plugin", vim.log.levels.WARN) +--end, { desc = "Live grep (unavailable)" }) +----end + + +map("n", "<leader>fF", ":cd %:p:h<CR>:pwd<CR><cmd>lua require('user.mods').findFilesInCwd()<CR>", +{ noremap = true, silent = true, desc = "Find files in cwd" }) + +-- FZF +map("n", "<leader>fz", function() + local ok, fzf_lua = pcall(require, "fzf-lua") + if ok then + fzf_lua.files() -- no config, just open + else + local handle = io.popen("find . -type f | fzf") + if handle then + local result = handle:read("*a") + handle:close() + result = result:gsub("\n", "") + if result ~= "" then + vim.cmd("edit " .. vim.fn.fnameescape(result)) + end + else + vim.notify("fzf not found or failed to run", vim.log.levels.ERROR) + end + end +end, { desc = "FZF file picker (fzf-lua or fallback)" }) + +map("n", "gA", ":FzfLua lsp_code_actions<CR>") + +-- Nvim-tree +local function safe_nvim_tree_toggle() + local ok_tree, tree_api = pcall(require, "nvim-tree.api") + if ok_tree then + pcall(vim.cmd, "Rooter") -- silently run Rooter if available + tree_api.tree.toggle() + else + -- Fallback to netrw + local cur_buf = vim.api.nvim_get_current_buf() + local ft = vim.api.nvim_get_option_value("filetype", { buf = cur_buf }) + + if ft == "netrw" then + vim.cmd("close") + else + vim.cmd("Lexplore") + end + end +end + +map("n", "<leader>f", safe_nvim_tree_toggle, { desc = "Toggle file explorer" }) + +-- Undotree +map("n", "<leader>u", vim.cmd.UndotreeToggle) + +-- Markdown-preview +map("n", "<leader>md", "<Plug>MarkdownPreviewToggle") +map("n", "<leader>mg", "<CMD>Glow<CR>") + +-- Autopairs +map("n", "<leader>ww", "<cmd>lua require('user.mods').Toggle_autopairs()<CR>") + +-- Zen-mode toggle +map("n", "<leader>zm", "<CMD>ZenMode<CR> | :echom ('Zen Mode')<CR> | :sl! | echo ('')<CR>") + +-- Vim-rooter +local function safe_project_root() + if vim.fn.exists(":Rooter") == 2 then + vim.cmd("Rooter") + else + vim.cmd("cd %:p:h") + end +end +vim.keymap.set("n", "<leader>ro", safe_project_root, { desc = "Project root" }) + +-- Trouble (UI to show diagnostics) +local function safe_trouble_toggle(view, opts) + local ok, _ = pcall(require, "trouble") + if ok then + local cmd = "Trouble" + if view then + cmd = cmd .. " " .. view .. " toggle" + if opts then + cmd = cmd .. " " .. opts + end + else + cmd = cmd .. " diagnostics toggle" + end + vim.cmd(cmd) + else + vim.cmd("copen") + end +end + +-- Replace 'map' with 'vim.keymap.set' if not already a global alias +vim.keymap.set("n", "<leader>t", function() + safe_trouble_toggle() +end, { desc = "Diagnostics (Workspace)" }) + +vim.keymap.set("n", "<leader>tw", function() + vim.cmd("cd %:p:h | pwd") + safe_trouble_toggle("diagnostics") +end, { desc = "Diagnostics (Workspace)" }) + +vim.keymap.set("n", "<leader>td", function() + vim.cmd("cd %:p:h | pwd") + safe_trouble_toggle("diagnostics", "filter.buf=0") +end, { desc = "Diagnostics (Buffer)" }) + +vim.keymap.set("n", "<leader>tq", function() + vim.cmd("cd %:p:h | pwd") + safe_trouble_toggle("qflist") +end, { desc = "Quickfix List" }) + +vim.keymap.set("n", "<leader>tl", function() + vim.cmd("cd %:p:h | pwd") + safe_trouble_toggle("loclist") +end, { desc = "Location List" }) + +vim.keymap.set("n", "gR", function() + safe_trouble_toggle("lsp") +end, { desc = "LSP References/Definitions" }) + +-- Null-ls +map("n", "<leader>ls", ':lua require("null-ls").toggle({})<CR>') + + +-- Replacer +map("n", "<Leader>qr", ':lua require("replacer").run()<CR>') + +-- Quickfix +map("n", "<leader>q", function() + if vim.fn.getqflist({ winid = 0 }).winid ~= 0 then + require("plugins.quickfix").close() + else + require("plugins.quickfix").open() + end +end, { desc = "Toggle quickfix window" }) + +-- Move to the next and previous item in the quickfixlist +map("n", "]c", "<Cmd>cnext<CR>") +map("n", "[c", "<Cmd>cprevious<CR>") + +-- Location list +map("n", "<leader>l", '<cmd>lua require("plugins.loclist").loclist_toggle()<CR>') + +-- Dap (debugging) +local dap_ok, dap = pcall(require, "dap") +local dap_ui_ok, ui = pcall(require, "dapui") + +if not (dap_ok and dap_ui_ok) then + --require("notify")("nvim-dap or dap-ui not installed!", "warning") + return +end + +vim.fn.sign_define("DapBreakpoint", { text = "๐" }) + +-- Start debugging session +map("n", "<leader>ds", function() + dap.continue() + ui.toggle({}) + vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("<C-w>=", false, true, true), "n", false) -- Spaces buffers evenly +end) + +-- Set breakpoints, get variable values, step into/out of functions, etc. +map("n", "<leader>dC", dap.continue) +-- map("n", "<leader>dC", dap.close) +-- map("n", "<leader>dt", dap.terminate) +map("n", "<leader>dt", ui.toggle) +map("n", "<leader>dd", function() + dap.disconnect({ terminateDebuggee = true }) +end) +map("n", "<leader>dn", dap.step_over) +map("n", "<leader>di", dap.step_into) +map("n", "<leader>do", dap.step_out) +map("n", "<leader>db", dap.toggle_breakpoint) +map("n", "<leader>dB", function() + dap.clear_breakpoints() + require("notify")("Breakpoints cleared", "warn") +end) +map("n", "<leader>dl", function() + local ok, dap_widgets = pcall(require, "dap.ui.widgets") + if ok then dap_widgets.hover() end +end) +map("n", "<leader>de", function() + require("dapui").float_element() +end, { desc = "Open Element" }) +map("n", "<leader>dq", function() + require("dapui").close() + require("dap").repl.close() + local session = require("dap").session() + if session then + require("dap").terminate() + end + require("nvim-dap-virtual-text").refresh() +end, { desc = "Terminate Debug" }) +map("n", "<leader>dc", function() + require("telescope").extensions.dap.commands() +end, { desc = "DAP-Telescope: Commands" }) +--vim.keymap.set("n", "<leader>B", ":lua require'dap'.set_breakpoint(vim.fn.input('Breakpoint condition: '))<CR>") +--vim.keymap.set("v", "<leader>B", ":lua require'dap'.set_breakpoint(vim.fn.input('Breakpoint condition: '))<CR>") +--vim.keymap.set("n", "<leader>lp", ":lua require'dap'.set_breakpoint(nil, nil, vim.fn.input('Log point message: '))<CR>") +--vim.keymap.set("n", "<leader>dr", ":lua require'dap'.repl.open()<CR>") + +-- Close debugger and clear breakpoints +--map("n", "<leader>de", function() +-- dap.clear_breakpoints() +-- ui.toggle({}) +-- dap.terminate() +-- vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("<C-w>=", false, true, true), "n", false) +-- require("notify")("Debugger session ended", "warn") +--end) + +-- Toggle Dashboard +map("n", "<leader><Space>", '<CMD>lua require("user.mods").toggle_dashboard()<CR>') + +-- Lsp Lines toggle +map("", "<Leader>ll", require("lsp_lines").toggle, { desc = "Toggle lsp_lines" }) + +-- SnipRun +map({ "n", "v" }, "<leader>r", "<Plug>SnipRun<CR>") + +-- Codi +map("n", "<leader>co", '<CMD>lua require("user.mods").toggleCodi()<CR>') + +-- Scratch buffer +map("n", "<leader>ss", '<CMD>lua require("user.mods").Scratch("float")<CR>') +map("n", "<leader>sh", '<CMD>lua require("user.mods").Scratch("horizontal")<CR>') +map("n", "<leader>sv", '<CMD>lua require("user.mods").Scratch("vertical")<CR>') + +-- Hardtime +map("n", "<leader>H", '<CMD>lua require("plugins.hardtime").ToggleHardtime()<CR>') + +-- Code Run +map("n", "<leader>rr", '<CMD>lua require("user.mods").toggleCodeRunner()<CR>') + +-- Run executable file +map("n", "<leader>rx", +":lua require('user.mods').RunCurrentFile()<CR>:echom 'Running executable file...'<CR>:sl!<CR>:echo ''<CR>") + +-- Set Files to current location as dir +map({ "n" }, "<leader>cf", "<CMD>e %:h<CR>") + +-- Vimtex +map("n", "<Leader>lc", ":VimtexCompile<cr>") +map("v", "<Leader>ls", ":VimtexCompileSelected<cr>") +map("n", "<Leader>li", ":VimtexInfo<cr>") +map("n", "<Leader>lt", ":VimtexTocToggle<cr>") +map("n", "<Leader>lv", ":VimtexView<cr>") diff --git a/common/nvim/lua/user/mods.lua b/common/nvim/lua/user/mods.lua new file mode 100755 index 0000000..b4e1579 --- /dev/null +++ b/common/nvim/lua/user/mods.lua @@ -0,0 +1,1427 @@ +-- ============================================================================ +-- Modules/Utility functions +-- ============================================================================ + +local M = {} + +-- Shorten Function Names +local fn = vim.fn +local api = vim.api + +--- Check if an executable exists +---@param name string The name of the executable to check +---@return boolean +function M.executable(name) + return fn.executable(name) > 0 +end + +--- Check if a feature is available in Neovim +---@param feat string The feature to check (e.g., 'nvim-0.7') +---@return boolean +function M.has(feat) + return fn.has(feat) == 1 +end + +--- Setup command aliases +---@param from string The alias +---@param to string The command to alias to +function M.setup_command_alias(from, to) + local cmd = string.format('cnoreabbrev <expr> %s (getcmdtype() == ":" && getcmdline() == "%s") ? "%s" : "%s"', + from, from, to, from) + api.nvim_command(cmd) +end + +--- Preserve cursor position while formatting +---@param cmd string The command to run +function M.preserve_cursor(cmd) + local cursor = api.nvim_win_get_cursor(0) + vim.cmd(cmd) + api.nvim_win_set_cursor(0, cursor) +end + +--- Toggle quickfix window +function M.toggle_quickfix() + local qf_exists = false + for _, win in pairs(fn.getwininfo()) do + if win.quickfix == 1 then + qf_exists = true + break + end + end + if qf_exists then + vim.cmd('cclose') + else + vim.cmd('copen') + end +end + +--- Toggle location list +function M.toggle_location() + local loc_exists = false + for _, win in pairs(fn.getwininfo()) do + if win.loclist == 1 then + loc_exists = true + break + end + end + if loc_exists then + vim.cmd('lclose') + else + vim.cmd('lopen') + end +end + +-- Setup command aliases +M.setup_command_alias('W', 'w') +M.setup_command_alias('Wq', 'wq') +M.setup_command_alias('WQ', 'wq') +M.setup_command_alias('Q', 'q') +M.setup_command_alias('Qa', 'qa') +M.setup_command_alias('QA', 'qa') + +-------------------------------------------------- + +--- Check whether a feature exists in Nvim +--- @feat: string +--- the feature name, like `nvim-0.7` or `unix`. +--- return: bool +M.has = function(feat) + if fn.has(feat) == 1 then + return true + end + + return false +end + +-------------------------------------------------- + +-- Format on save +local format_augroup = vim.api.nvim_create_augroup("LspFormatting", {}) + +local ok, null_ls = pcall(require, "null-ls") +if ok then + null_ls.setup({ + on_attach = function(client, bufnr) + if client.supports_method("textDocument/formatting") then + vim.api.nvim_clear_autocmds({ group = format_augroup, buffer = bufnr }) + vim.api.nvim_create_autocmd("BufWritePre", { + group = format_augroup, + buffer = bufnr, + callback = function() + if vim.lsp.buf.format then + vim.lsp.buf.format({ bufnr = bufnr }) + else + vim.lsp.buf.formatting_seq_sync() + end + end, + }) + end + end, + }) +end + +vim.cmd([[autocmd BufWritePre <buffer> lua vim.lsp.buf.format()]]) + + +-------------------------------------------------- + +---Determine if a value of any type is empty +---@param item any +---@return boolean? + +--- Checks if an item is considered "empty". +-- +-- An item is considered empty if: +-- - It is nil. +-- - It is an empty string. +-- - It is an empty table. +-- - It is a number equal to 0 (you might want to adjust this based on your definition of "empty" for numbers). +-- +-- @param item any The item to check. +-- @return boolean True if the item is empty, false otherwise. +function M.empty(item) + -- Case 1: item is nil + if item == nil then + return true + end + + local item_type = type(item) + + -- Case 2: empty string + if item_type == "string" then + return item == "" + end + + if item_type == "table" then + return vim.tbl_isempty(item) + end + if item_type == "number" then + return item == 0 -- Changed from item <= 0 for a stricter "empty" definition for numbers + end + + if item_type == "boolean" then + return not item -- Returns true if item is false, false if item is 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 + +-------------------------------------------------- + +--- Toggle cmp completion +vim.g.cmp_toggle_flag = false -- initialize +local normal_buftype = function() + return vim.api.nvim_buf_get_option(0, "buftype") ~= "prompt" +end +M.toggle_completion = function() + local ok, cmp = pcall(require, "cmp") + if ok then + local next_cmp_toggle_flag = not vim.g.cmp_toggle_flag + if next_cmp_toggle_flag then + print("completion on") + else + print("completion off") + end + cmp.setup({ + enabled = function() + vim.g.cmp_toggle_flag = next_cmp_toggle_flag + if next_cmp_toggle_flag then + return normal_buftype + else + return next_cmp_toggle_flag + end + end, + }) + else + print("completion not available") + end +end + +-------------------------------------------------- + +--- Make sure using latest neovim version +function M.get_nvim_version() + local actual_ver = vim.version() + + local nvim_ver_str = string.format("%d.%d.%d", actual_ver.major, actual_ver.minor, actual_ver.patch) + return nvim_ver_str +end + +function M.add_pack(name) + local status, error = pcall(vim.cmd, "packadd " .. name) + + return status +end + +-------------------------------------------------- + +-- Define a global function to retrieve LSP clients based on Neovim version +function M.get_lsp_clients(bufnr) + local mods = require("user.mods") + --local expected_ver = '0.10.0' + local nvim_ver = mods.get_nvim_version() + + local version_major, version_minor = string.match(nvim_ver, "(%d+)%.(%d+)") + version_major = tonumber(version_major) + version_minor = tonumber(version_minor) + + if version_major > 0 or (version_major == 0 and version_minor >= 10) then + return vim.lsp.get_clients({ buffer = bufnr }) + else + return vim.lsp.buf_get_clients() + end +end + +-------------------------------------------------- + +--- Toggle autopairs on/off (requires "windwp/nvim-autopairs") +function M.Toggle_autopairs() + local ok, autopairs = pcall(require, "nvim-autopairs") + if ok then + if autopairs.state.disabled then + autopairs.enable() + print("autopairs on") + else + autopairs.disable() + print("autopairs off") + end + else + print("autopairs not available") + end +end + +-------------------------------------------------- + +--- Make vim-rooter message disappear after making it's changes +--vim.cmd([[ +--let timer = timer_start(1000, 'LogTrigger', {}) +--func! LogTrigger(timer) +-- silent! +--endfunc +--]]) +-- +--vim.cmd([[ +--function! ConfigureChDir() +-- echo ('') +--endfunction +--" Call after vim-rooter changes the root dir +--autocmd User RooterChDir :sleep! | call LogTrigger(timer) | call ConfigureChDir() +--]]) + +function M.findFilesInCwd() + vim.cmd("let g:rooter_manual_only = 1") -- Toggle the rooter plugin + require("plugins.telescope").findhere() + vim.defer_fn(function() + vim.cmd("let g:rooter_manual_only = 0") -- Change back to automatic rooter + end, 100) +end + +--function M.findFilesInCwd() +-- vim.cmd("let g:rooter_manual_only = 1") -- Toggle the rooter plugin +-- require("plugins.telescope").findhere() +-- --vim.cmd("let g:rooter_manual_only = 0") -- Change back to automatic rooter +--end + +-------------------------------------------------- + +-- Toggle the executable permission +function M.Toggle_executable() + local current_file = vim.fn.expand("%:p") + local executable = vim.fn.executable(current_file) == 1 + + if executable then + -- File is executable, unset the executable permission + vim.fn.system("chmod -x " .. current_file) + --print(current_file .. ' is no longer executable.') + print("No longer executable") + else + -- File is not executable, set the executable permission + vim.fn.system("chmod +x " .. current_file) + --print(current_file .. ' is now executable.') + print("Now executable") + end +end + +-------------------------------------------------- + +-- Set bare dotfiles repository git environment variables dynamically + +-- Set git enviornment variables +--function M.Set_git_env_vars() +-- local git_dir_job = vim.fn.jobstart({ "git", "rev-parse", "--git-dir" }) +-- local command_status = vim.fn.jobwait({ git_dir_job })[1] +-- if command_status > 0 then +-- vim.env.GIT_DIR = vim.fn.expand("$HOME/.cfg") +-- vim.env.GIT_WORK_TREE = vim.fn.expand("~") +-- else +-- vim.env.GIT_DIR = nil +-- vim.env.GIT_WORK_TREE = nil +-- end +-- -- Launch terminal emulator with Git environment variables set +-- --require("toggleterm").exec(string.format([[%s %s]], os.getenv("SHELL"), "-i")) +--end + +------ + +local prev_cwd = "" + +function M.Set_git_env_vars() + local cwd = vim.fn.getcwd() + if prev_cwd == "" then + -- First buffer being opened, set prev_cwd to cwd + prev_cwd = cwd + elseif cwd ~= prev_cwd then + -- Working directory has changed since last buffer was opened + prev_cwd = cwd + local git_dir_job = vim.fn.jobstart({ "git", "rev-parse", "--git-dir" }) + local command_status = vim.fn.jobwait({ git_dir_job })[1] + if command_status > 0 then + vim.env.GIT_DIR = vim.fn.expand("$HOME/.cfg") + vim.env.GIT_WORK_TREE = vim.fn.expand("~") + else + vim.env.GIT_DIR = nil + vim.env.GIT_WORK_TREE = nil + end + end +end + +vim.cmd([[augroup my_git_env_vars]]) +vim.cmd([[ autocmd!]]) +vim.cmd([[ autocmd BufEnter * lua require('user.mods').Set_git_env_vars()]]) +vim.cmd([[ autocmd VimEnter * lua require('user.mods').Set_git_env_vars()]]) +vim.cmd([[augroup END]]) + +-------------------------------------------------- + +--- Update Tmux Status Vi-mode +function M.update_tmux_status() + -- Check if the current buffer has a man filetype + if vim.bo.filetype == "man" then + return + end + local mode = vim.api.nvim_eval("mode()") + -- Determine the mode name based on the mode value + local mode_name + if mode == "n" then + mode_name = "-- NORMAL --" + elseif mode == "i" or mode == "ic" then + mode_name = "-- INSERT --" + else + mode_name = "-- NORMAL --" --'-- COMMAND --' + end + + -- Write the mode name to the file + local file = io.open(os.getenv("HOME") .. "/.vi-mode", "w") + file:write(mode_name) + file:close() + if nvim_running then + -- Neovim is running, update the mode file and refresh tmux + VI_MODE = "" -- Clear VI_MODE to show Neovim mode + vim.cmd("silent !tmux refresh-client -S") + end + ---- Force tmux to update the status + vim.cmd("silent !tmux refresh-client -S") +end + +vim.cmd([[ + augroup TmuxStatus + autocmd! + autocmd InsertLeave,InsertEnter * lua require("user.mods").update_tmux_status() + autocmd VimEnter * lua require("user.mods").update_tmux_status() + autocmd BufEnter * lua require("user.mods").update_tmux_status() + autocmd ModeChanged * lua require("user.mods").update_tmux_status() + autocmd WinEnter,WinLeave * lua require("user.mods").update_tmux_status() + augroup END +]]) + +-- Add autocmd for <esc> +-- Add autocmd to check when tmux switches panes/windows +--autocmd InsertLeave,InsertEnter * lua require("user.mods").update_tmux_status() +--autocmd BufEnter * lua require("user.mods").update_tmux_status() +--autocmd WinEnter,WinLeave * lua require("user.mods").update_tmux_status() + +--autocmd WinEnter,WinLeave * lua require("user.mods").update_tmux_status() +--autocmd VimResized * lua require("user.mods").update_tmux_status() +--autocmd FocusGained * lua require("user.mods").update_tmux_status() +--autocmd FocusLost * lua require("user.mods").update_tmux_status() +--autocmd CmdwinEnter,CmdwinLeave * lua require("user.mods").update_tmux_status() + +-------------------------------------------------- + +-- function OpenEmulatorList() +-- local emulatorsBuffer = vim.api.nvim_create_buf(false, true) +-- vim.api.nvim_buf_set_lines(emulatorsBuffer, 0, 0, true, {"Some text"}) +-- vim.api.nvim_open_win( +-- emulatorsBuffer, +-- false, +-- { +-- relative='win', row=3, col=3, width=12, height=3 +-- } +-- ) +-- end +-- +-- vim.api.nvim_create_user_command('OpenEmulators', OpenEmulatorList, {}) + +--local api = vim.api +--local fn = vim.fn +--local cmd = vim.cmd +-- +--local function bufremove(opts) +-- local target_buf_id = api.nvim_get_current_buf() +-- +-- -- Do nothing if buffer is in modified state. +-- if not opts.force and api.nvim_buf_get_option(target_buf_id, 'modified') then +-- return false +-- end +-- +-- -- Hide target buffer from all windows. +-- vim.tbl_map(function(win_id) +-- win_id = win_id or 0 +-- +-- local current_buf_id = api.nvim_win_get_buf(win_id) +-- +-- api.nvim_win_call(win_id, function() +-- -- Try using alternate buffer +-- local alt_buf_id = fn.bufnr('#') +-- if alt_buf_id ~= current_buf_id and fn.buflisted(alt_buf_id) == 1 then +-- api.nvim_win_set_buf(win_id, alt_buf_id) +-- return +-- end +-- +-- -- Try using previous buffer +-- cmd('bprevious') +-- if current_buf_id ~= api.nvim_win_get_buf(win_id) then +-- return +-- end +-- +-- -- Create new listed scratch buffer +-- local new_buf = api.nvim_create_buf(true, true) +-- api.nvim_win_set_buf(win_id, new_buf) +-- end) +-- +-- return true +-- end, fn.win_findbuf(target_buf_id)) +-- +-- cmd(string.format('bdelete%s %d', opts.force and '!' or '', target_buf_id)) +--end +-- +---- Assign bufremove to a global variable +--_G.bufremove = bufremove + +--vim.cmd([[ +-- augroup NvimTreeDelete +-- autocmd! +-- autocmd FileType NvimTree lua require('user.mods').enew_on_delete() +-- augroup END +--]]) +-- +--function M.enew_on_delete() +-- if vim.bo.buftype == 'nofile' then +-- vim.cmd('enew') +-- end +--end + +-- Update Neovim +--function M.Update_neovim() +-- -- Run the commands to download and extract the latest version +-- os.execute("curl -L -o nvim-linux64.tar.gz https://github.com/neovim/neovim/releases/latest/download/nvim-linux64.tar.gz") +-- os.execute("tar xzvf nvim-linux64.tar.gz") +-- -- Replace the existing Neovim installation with the new version +-- os.execute("rm -rf $HOME/.local/bin/nvim") +-- os.execute("mv nvim-linux64 $HOME/.local/bin/nvim") +-- +-- -- Clean up the downloaded file +-- os.execute("rm nvim-linux64.tar.gz") +-- +-- -- Print a message to indicate the update is complete +-- print("Neovim has been updated to the latest version.") +--end +-- +---- Bind a keymap to the update_neovim function (optional) +--vim.api.nvim_set_keymap('n', '<leader>u', '<cmd> lua require("user.mods").Update_neovim()<CR>', { noremap = true, silent = true }) + +-- Define a function to create a floating window and run the update process inside it +function M.Update_neovim() + -- Create a new floating window + local bufnr, winid = vim.api.nvim_create_buf(false, true) + vim.api.nvim_open_win(bufnr, true, { + relative = "editor", + width = 80, + height = 20, + row = 2, + col = 2, + style = "minimal", + border = "single", + }) + + -- Function to append a line to the buffer in the floating window + local function append_line(line) + vim.api.nvim_buf_set_option(bufnr, "modifiable", true) + vim.api.nvim_buf_set_lines(bufnr, -1, -1, false, { line }) + vim.api.nvim_buf_set_option(bufnr, "modifiable", false) + end + + -- Download the latest version of Neovim + append_line("Downloading the latest version of Neovim...") + os.execute( + "curl -L -o nvim-linux64.tar.gz https://github.com/neovim/neovim/releases/latest/download/nvim-linux64.tar.gz") + append_line("Download complete.") + + -- Extract the downloaded archive + append_line("Extracting the downloaded archive...") + os.execute("tar xzvf nvim-linux64.tar.gz") + append_line("Extraction complete.") + + -- Replace the existing Neovim installation with the new version + append_line("Replacing the existing Neovim installation...") + os.execute("rm -rf $HOME/nvim") + os.execute("mv nvim-linux64 $HOME/nvim") + append_line("Update complete.") + + -- Clean up the downloaded file + append_line("Cleaning up the downloaded file...") + os.execute("rm nvim-linux64.tar.gz") + append_line("Cleanup complete.") + + -- Close the floating window after a delay + vim.defer_fn(function() + vim.api.nvim_win_close(winid, true) + end, 5000) -- Adjust the delay as needed +end + +-- Bind a keymap to the update_neovim function (optional) +vim.api.nvim_set_keymap("n", "<leader>U", '<cmd> lua require("user.mods").Update_neovim()<CR>', + { noremap = true, silent = true }) + +-------------------------------------------------- + +-- Fix or suppress closing nvim error message (/src/unix/core.c:147: uv_close: Assertion `!uv__is_closing(handle)' failed.) +vim.api.nvim_create_autocmd({ "VimLeave" }, { + callback = function() + vim.fn.jobstart("!notify-send 2>/dev/null &", { detach = true }) + end, +}) + +-------------------------------------------------- + +-- Rooter +--vim.cmd([[autocmd BufEnter * lua vim.cmd('Rooter')]]) + +-------------------------------------------------- + +-- Nvim-tree +local modifiedBufs = function(bufs) -- nvim-tree is also there in modified buffers so this function filter it out + local t = 0 + for k, v in pairs(bufs) do + if v.name:match("NvimTree_", "NvimTree1") == nil then + t = t + 1 + end + end + return t +end + +-- Deleting current file opened behaviour +function M.DeleteCurrentBuffer() + local cbn = vim.api.nvim_get_current_buf() + local buffers = vim.fn.getbufinfo({ buflisted = true }) + local size = #buffers + local idx = 0 + + for n, e in ipairs(buffers) do + if e.bufnr == cbn then + idx = n + break -- Exit loop as soon as we find the buffer + end + end + + if idx == 0 then + return + end + + if idx == size then + vim.cmd("bprevious") + else + vim.cmd("bnext") + end + + vim.cmd("silent! bdelete " .. cbn) + + -- Open a new blank window + vim.cmd("silent! enew") -- Opens a new vertical split + -- OR + -- vim.cmd("new") -- Opens a new horizontal split + -- Delay before opening a new split + --vim.defer_fn(function() + -- vim.cmd("enew") -- Opens a new vertical split + --end, 100) -- Adjust the delay as needed (in milliseconds) + -- Delay before closing the nvim-tree window +end + + +-- On :bd nvim-tree should behave as if it wasn't opened +-- Only run DeleteCurrentBuffer if NvimTree is loaded +vim.api.nvim_create_autocmd("FileType", { + pattern = "NvimTree", + callback = function() + local ok, mods = pcall(require, "user.mods") + if ok and type(mods.DeleteCurrentBuffer) == "function" then + mods.DeleteCurrentBuffer() + end + end, +}) + +-- Handle NvimTree window closure safely +vim.api.nvim_create_autocmd("BufEnter", { + nested = true, + callback = function() + local ok_utils, utils = pcall(require, "nvim-tree.utils") + if not ok_utils then return end + + if #vim.api.nvim_list_wins() == 1 and utils.is_nvim_tree_buf() then + local ok_api, api = pcall(require, "nvim-tree.api") + if not ok_api then return end + + vim.defer_fn(function() + -- Safely toggle tree off and on + pcall(api.tree.toggle, { find_file = true, focus = true }) + pcall(api.tree.toggle, { find_file = true, focus = true }) + vim.cmd("wincmd p") + end, 0) + end + end, +}) + +-- Dismiss notifications when opening nvim-tree window +local function isNvimTreeOpen() + local win = vim.fn.win_findbuf(vim.fn.bufnr("NvimTree")) + return vim.fn.empty(win) == 0 +end + +function M.DisableNotify() + if isNvimTreeOpen() then + require("notify").dismiss() + end +end + +vim.cmd([[ + autocmd! WinEnter,WinLeave * lua require('user.mods').DisableNotify() +]]) + +-------------------------------------------------- + +-- Toggle Dashboard +function M.toggle_dashboard() + if vim.bo.filetype == "dashboard" then + vim.cmd("bdelete") + else + vim.cmd("Dashboard") + end +end + +-------------------------------------------------- + +-- Helper function to suppress errors +local function silent_execute(cmd) + vim.fn["serverlist"]() -- Required to prevent 'Press ENTER' prompt + local result = vim.fn.system(cmd .. " 2>/dev/null") + vim.fn["serverlist"]() + return result +end + +-------------------------------------------------- + +-- Toggle Codi +-- Define a global variable to track Codi's state +local is_codi_open = false + +function M.toggleCodi() + if is_codi_open then + -- Close Codi + vim.cmd("Codi!") + is_codi_open = false + print("Codi off") + else + -- Open Codi + vim.cmd("Codi") + is_codi_open = true + print("Codi on") + end +end + +-------------------------------------------------- + +---- Function to create or toggle a scratch buffer +-- Define global variables to store the scratch buffer and window +local scratch_buf = nil +local scratch_win = nil + +-- Other global variables +local scratch_date = os.date("%Y-%m-%d") +local scratch_dir = vim.fn.expand("~/notes/private") +local scratch_file = "scratch-" .. scratch_date .. ".md" + +-- Function to close and delete a buffer +function CloseAndDeleteBuffer(bufnr) + if bufnr and vim.api.nvim_buf_is_valid(bufnr) then + vim.api.nvim_command("silent! bwipe " .. bufnr) + end +end + +function M.Scratch(Split_direction) + -- Check if the directory exists, and create it if it doesn't + if vim.fn.isdirectory(scratch_dir) == 0 then + vim.fn.mkdir(scratch_dir, "p") + end + + -- Determine the window type based on Split_direction + local current_window_type = "float" + if Split_direction == "float" then + current_window_type = "float" + elseif Split_direction == "vertical" then + current_window_type = "vertical" + elseif Split_direction == "horizontal" then + current_window_type = "horizontal" + end + + local file_path = scratch_dir .. "/" .. scratch_file + + if scratch_win and vim.api.nvim_win_is_valid(scratch_win) then + -- Window exists, save buffer to file and close it + WriteScratchBufferToFile(scratch_buf, file_path) + vim.cmd(":w!") + vim.api.nvim_win_close(scratch_win, true) + CloseAndDeleteBuffer(scratch_buf) + scratch_win = nil + scratch_buf = nil + else + if scratch_buf and vim.api.nvim_buf_is_valid(scratch_buf) then + -- Buffer exists, reuse it and open a new window + OpenScratchWindow(scratch_buf, current_window_type) + else + -- Buffer doesn't exist, create it and load the file if it exists + scratch_buf = OpenScratchBuffer(file_path) + OpenScratchWindow(scratch_buf, current_window_type) + end + end +end + +-- Function to write buffer contents to a file +function WriteScratchBufferToFile(buf, file_path) + if buf and vim.api.nvim_buf_is_valid(buf) then + local lines = vim.api.nvim_buf_get_lines(buf, 0, -1, false) + local content = table.concat(lines, "\n") + local escaped_file_path = vim.fn.fnameescape(file_path) + + -- Write the buffer content to the file + local file = io.open(escaped_file_path, "w") + if file then + file:write(content) + file:close() + end + end +end + +-- Function to create or open the scratch buffer +function OpenScratchBuffer(file_path) + local buf = vim.api.nvim_create_buf(true, false) + + -- Set the file name for the buffer + local escaped_file_path = vim.fn.fnameescape(file_path) + vim.api.nvim_buf_set_name(buf, escaped_file_path) + + -- Check if the file exists and load it if it does + if vim.fn.filereadable(file_path) == 1 then + local file_contents = vim.fn.readfile(file_path) + vim.api.nvim_buf_set_lines(buf, 0, -1, true, file_contents) + else + -- Insert initial content + vim.api.nvim_buf_set_lines(buf, 0, -1, true, { + "# Quick Notes - " .. scratch_date, + "--------------------------", + "", + }) + + -- Save the initial content to the file + vim.cmd(":w") + end + + return buf +end + +-- Function to open the scratch buffer in a window +function OpenScratchWindow(buf, current_window_type) + if buf and vim.api.nvim_buf_is_valid(buf) then + if current_window_type == "float" then + local opts = { + relative = "win", + width = 120, + height = 10, + border = "single", + row = 20, + col = 20, + } + scratch_win = vim.api.nvim_open_win(buf, true, opts) + -- Go to the last line of the buffer + vim.api.nvim_win_set_cursor(scratch_win, { vim.api.nvim_buf_line_count(buf), 1 }) + elseif current_window_type == "vertical" then + vim.cmd("vsplit") + vim.api.nvim_win_set_buf(0, buf) + scratch_win = 0 + elseif current_window_type == "horizontal" then + vim.cmd("split") + vim.api.nvim_win_set_buf(0, buf) + scratch_win = 0 + end + end +end + +-------------------------------------------------- + +---- Intercept file open +--local augroup = vim.api.nvim_create_augroup("user-autocmds", { clear = true }) +--local intercept_file_open = true +--vim.api.nvim_create_user_command("InterceptToggle", function() +-- intercept_file_open = not intercept_file_open +-- local intercept_state = "`Enabled`" +-- if not intercept_file_open then +-- intercept_state = "`Disabled`" +-- end +-- vim.notify("Intercept file open set to " .. intercept_state, vim.log.levels.INFO, { +-- title = "Intercept File Open", +-- ---@param win integer The window handle +-- on_open = function(win) +-- vim.api.nvim_buf_set_option(vim.api.nvim_win_get_buf(win), "filetype", "markdown") +-- end, +-- }) +--end, { desc = "Toggles intercepting BufNew to open files in custom programs" }) + +---- NOTE: Add "BufReadPre" to the autocmd events to also intercept files given on the command line, e.g. +---- `nvim myfile.txt` +--vim.api.nvim_create_autocmd({ "BufNew" }, { +-- group = augroup, +-- callback = function(args) +-- ---@type string +-- local path = args.match +-- ---@type integer +-- local bufnr = args.buf +-- +-- ---@type string? The file extension if detected +-- local extension = vim.fn.fnamemodify(path, ":e") +-- ---@type string? The filename if detected +-- local filename = vim.fn.fnamemodify(path, ":t") +-- +-- ---Open a given file path in a given program and remove the buffer for the file. +-- ---@param buf integer The buffer handle for the opening buffer +-- ---@param fpath string The file path given to the program +-- ---@param fname string The file name used in notifications +-- ---@param prog string The program to execute against the file path +-- local function open_in_prog(buf, fpath, fname, prog) +-- vim.notify(string.format("Opening `%s` in `%s`", fname, prog), vim.log.levels.INFO, { +-- title = "Open File in External Program", +-- ---@param win integer The window handle +-- on_open = function(win) +-- vim.api.nvim_buf_set_option(vim.api.nvim_win_get_buf(win), "filetype", "markdown") +-- end, +-- }) +-- local mods = require("user.mods") +-- local nvim_ver = mods.get_nvim_version() +-- +-- local version_major, version_minor = string.match(nvim_ver, "(%d+)%.(%d+)") +-- version_major = tonumber(version_major) +-- version_minor = tonumber(version_minor) +-- +-- if version_major > 0 or (version_major == 0 and version_minor >= 10) then +-- vim.system({ prog, fpath }, { detach = true }) +-- else +-- vim.fn.jobstart({ prog, fpath }, { detach = true }) +-- end +-- vim.api.nvim_buf_delete(buf, { force = true }) +-- end +-- +-- local extension_callbacks = { +-- ["pdf"] = function(buf, fpath, fname) +-- open_in_prog(buf, fpath, fname, "zathura") +-- end, +-- ["epub"] = function(buf, fpath, fname) +-- open_in_prog(buf, fpath, fname, "zathura") +-- end, +-- ["mobi"] = "pdf", +-- ["png"] = function(buf, fpath, fname) +-- open_in_prog(buf, fpath, fname, "vimiv") +-- end, +-- ["jpg"] = "png", +-- ["mp4"] = function(buf, fpath, fname) +-- open_in_prog(buf, fpath, fname, "vlc") +-- end, +-- ["gif"] = "mp4", +-- } +-- +-- ---Get the extension callback for a given extension. Will do a recursive lookup if an extension callback is actually +-- ---of type string to get the correct extension +-- ---@param ext string A file extension. Example: `png`. +-- ---@return fun(bufnr: integer, path: string, filename: string?) extension_callback The extension callback to invoke, expects a buffer handle, file path, and filename. +-- local function extension_lookup(ext) +-- local callback = extension_callbacks[ext] +-- if type(callback) == "string" then +-- callback = extension_lookup(callback) +-- end +-- return callback +-- end +-- +-- if extension ~= nil and not extension:match("^%s*$") and intercept_file_open then +-- local callback = extension_lookup(extension) +-- if type(callback) == "function" then +-- callback(bufnr, path, filename) +-- end +-- end +-- end, +--}) + +-------------------------------------------------- + +-- Delete [No Name] buffers +vim.api.nvim_create_autocmd("BufHidden", { + desc = "Delete [No Name] buffers", + callback = function(event) + if event.file == "" and vim.bo[event.buf].buftype == "" and not vim.bo[event.buf].modified then + vim.schedule(function() + pcall(vim.api.nvim_buf_delete, event.buf, {}) + end) + end + end, +}) + +-------------------------------------------------- + +local codeRunnerEnabled = false + +function M.toggleCodeRunner() + codeRunnerEnabled = not codeRunnerEnabled + if codeRunnerEnabled then + print("Code Runner enabled") + M.RunCode() -- Execute when enabled + else + print("Code Runner disabled") + -- Close the terminal window when disabled + local buffers = vim.fn.getbufinfo() + + for _, buf in ipairs(buffers) do + local type = vim.api.nvim_buf_get_option(buf.bufnr, "buftype") + if type == "terminal" then + vim.api.nvim_command("silent! bdelete " .. buf.bufnr) + end + end + end +end + +local function substitute(cmd) + cmd = cmd:gsub("%%", vim.fn.expand("%")) + cmd = cmd:gsub("$fileBase", vim.fn.expand("%:r")) + cmd = cmd:gsub("$filePath", vim.fn.expand("%:p")) + cmd = cmd:gsub("$file", vim.fn.expand("%")) + cmd = cmd:gsub("$dir", vim.fn.expand("%:p:h")) + cmd = cmd:gsub("#", vim.fn.expand("#")) + cmd = cmd:gsub("$altFile", vim.fn.expand("#")) + + return cmd +end + +function M.RunCode() + if not codeRunnerEnabled then + print("Code Runner is currently disabled. Toggle it on to execute code.") + return + end + local file_extension = vim.fn.expand("%:e") + local selected_cmd = "" + local supported_filetypes = { + html = { + default = "%", + }, + c = { + default = "gcc % -o $fileBase && ./$fileBase", + debug = "gcc -g % -o $fileBase && ./$fileBase", + }, + cs = { + default = "dotnet run", + }, + cpp = { + default = "g++ % -o $fileBase && ./$fileBase", + debug = "g++ -g % -o ./$fileBase", + competitive = "g++ -std=c++17 -Wall -DAL -O2 % -o $fileBase && $fileBase<input.txt", + }, + py = { + default = "python %", + }, + go = { + default = "go run %", + }, + java = { + default = "java %", + }, + js = { + default = "node %", + debug = "node --inspect %", + }, + lua = { + default = "lua %", + }, + ts = { + default = "tsc % && node $fileBase", + }, + rs = { + default = "rustc % && $fileBase", + }, + php = { + default = "php %", + }, + r = { + default = "Rscript %", + }, + jl = { + default = "julia %", + }, + rb = { + default = "ruby %", + }, + pl = { + default = "perl %", + }, + } + + local term_cmd = "bot 10 new | term " + local choices = {} + + -- Add 'default' as the first option if available + if supported_filetypes[file_extension]["default"] then + table.insert(choices, "default") + end + + -- Add 'debug' as the second option if available + if supported_filetypes[file_extension]["debug"] then + table.insert(choices, "debug") + end + + -- Add other available options + for key, _ in pairs(supported_filetypes[file_extension]) do + if key ~= "default" and key ~= "debug" then + table.insert(choices, key) + end + end + if #choices == 0 then + vim.notify("It doesn't contain any command", vim.log.levels.WARN, { title = "Code Runner" }) + elseif #choices == 1 then + selected_cmd = supported_filetypes[file_extension][choices[1]] + vim.cmd(term_cmd .. substitute(selected_cmd)) + else + vim.ui.select(choices, { + prompt = "Choose a command: ", + layout_config = { + height = 10, + width = 40, + prompt_position = "top", + -- other options as required + }, + }, function(choice) + selected_cmd = supported_filetypes[file_extension][choice] + if selected_cmd then + vim.cmd(term_cmd .. substitute(selected_cmd)) + end + end) + end + + if not supported_filetypes[file_extension] then + vim.notify("The filetype isn't included in the list", vim.log.levels.WARN, { title = "Code Runner" }) + end +end + +-------------------------------------------------- + +-- Run executable file +local interpreters = { + python = "python", + lua = "lua", + bash = "bash", + zsh = "zsh", + perl = "perl", + ruby = "ruby", + node = "node", + rust = "rust", + php = "php", +} + +function M.RunCurrentFile() + local file_path = vim.fn.expand("%:p") + local file = io.open(file_path, "r") + + if not file then + print("Error: Unable to open the file") + return + end + + local shebang = file:read() + file:close() + + local interpreter = shebang:match("#!%s*(.-)$") + if not interpreter then + print("Error: No shebang line found in the file") + return + end + + -- Remove leading spaces and any arguments, extracting the interpreter name + interpreter = interpreter:gsub("^%s*([^%s]+).*", "%1") + + local cmd = interpreters[interpreter] + + if not cmd then + cmd = interpreter -- Set the command to the interpreter directly + end + + -- Run the file using the determined interpreter + vim.fn.jobstart(cmd .. " " .. file_path, { + cwd = vim.fn.expand("%:p:h"), + }) +end + +-------------------------------------------------- + +-- Close all floating windows +vim.api.nvim_create_user_command("CloseFloatingWindows", function(opts) + for _, window_id in ipairs(vim.api.nvim_list_wins()) do + -- If window is floating + if vim.api.nvim_win_get_config(window_id).relative ~= "" then + -- Force close if called with ! + vim.api.nvim_win_close(window_id, opts.bang) + end + end +end, { bang = true, nargs = 0 }) + +-------------------------------------------------- + + +-- Platform detection +local uname = vim.loop.os_uname().sysname +local has = vim.fn.has + +local is_mac = has("mac") == 1 +local is_linux = uname == "Linux" +local is_windows = has("win32") == 1 or uname:find("Windows") +local is_wsl = has("wsl") == 1 or (uname:find("Linux") and (os.getenv("WSL_DISTRO_NAME") ~= nil)) +local is_termux = has("termux") == 1 or (os.getenv("PREFIX") and os.getenv("PREFIX"):find("com.termux")) +local os_name = (is_mac and "mac") or (is_linux and "linux") or (is_windows and "windows") or (is_wsl and "wsl") or (is_termux and "termux") or uname:lower() + +-- Check if a command exists +local function command_exists(cmd) + local handle = io.popen(cmd .. " --version 2>/dev/null") + if handle then + local result = handle:read("*a") + handle:close() + return result ~= "" + end + return false +end + +-- Detect clipboard tool on Linux +local function detect_clipboard_tool() + if command_exists("xclip") then return "xclip" end + if command_exists("xsel") then return "xsel" end + if command_exists("wl-copy") and command_exists("wl-paste") then return "wl-clipboard" end + return nil +end + +-- OSC52 clipboard copy fallback +local function osc52_copy(text) + local encoded = vim.fn.system("base64 | tr -d '\n'", text) + io.write(string.format("\027]52;c;%s\007", encoded)) +end + +---- Set clipboard +--function set_clipboard(text) +-- if not text or text == "" then return end +-- +-- if is_mac then +-- local handle = io.popen("pbcopy", "w") +-- if handle then +-- handle:write(text) +-- handle:close() +-- end +-- elseif is_linux then +-- local tool = detect_clipboard_tool() +-- if tool == "xclip" then +-- local handle = io.popen("xclip -selection clipboard", "w") +-- if handle then handle:write(text) handle:close() end +-- elseif tool == "xsel" then +-- local handle = io.popen("xsel --clipboard --input", "w") +-- if handle then handle:write(text) handle:close() end +-- elseif tool == "wl-clipboard" then +-- local handle = io.popen("wl-copy", "w") +-- if handle then handle:write(text) handle:close() end +-- else +-- osc52_copy(text) +-- vim.notify("Using OSC52 for clipboard (install xclip, xsel, or wl-clipboard for better support)", vim.log.levels.INFO) +-- end +-- elseif is_wsl or is_windows then +-- local handle = io.popen("clip", "w") +-- if handle then handle:write(text) handle:close() end +-- elseif is_termux then +-- local handle = io.popen("termux-clipboard-set", "w") +-- if handle then handle:write(text) handle:close() end +-- else +-- vim.notify("No clipboard support for OS: " .. os_name, vim.log.levels.WARN) +-- end +--end +-- +---- Clipboard sync autocmd setup +--local function setup_clipboard_sync() +-- local ok, Job = pcall(require, "plenary.job") +-- if not ok then +-- -- plenary not available, skip +-- return +-- end +-- +-- vim.api.nvim_create_augroup("clipboard_sync", { clear = true }) +-- vim.api.nvim_create_autocmd("TextYankPost", { +-- group = "clipboard_sync", +-- desc = "Sync yanked text to system clipboard", +-- pattern = "*", +-- callback = function() +-- local text = vim.fn.getreg("\"") +-- if text ~= nil and text ~= "" then +-- set_clipboard(text) +-- end +-- end, +-- }) +--end +--setup_clipboard_sync() +-- +---- Terminal clear function (optional) +--function clear_terminal() +-- vim.opt.scrollback = 1 +-- vim.api.nvim_feedkeys("i", "n", false) +-- vim.api.nvim_feedkeys("clear\r", "n", false) +-- vim.api.nvim_feedkeys("\x1b", "n", false) +-- vim.api.nvim_feedkeys("i", "n", false) +-- vim.defer_fn(function() +-- vim.opt.scrollback = 10000 +-- end, 100) +--end +-- +---- Get clipboard content (optional) +--function GetClipboard() +-- local handle +-- +-- if is_mac then +-- handle = io.popen("pbpaste", "r") +-- elseif is_linux then +-- local tool = detect_clipboard_tool() +-- if tool == "xclip" then +-- handle = io.popen("xclip -selection clipboard -o", "r") +-- elseif tool == "xsel" then +-- handle = io.popen("xsel --clipboard --output", "r") +-- elseif tool == "wl-clipboard" then +-- handle = io.popen("wl-paste", "r") +-- end +-- elseif is_wsl or is_windows then +-- handle = io.popen("powershell.exe Get-Clipboard", "r") +-- elseif is_termux then +-- handle = io.popen("termux-clipboard-get", "r") +-- end +-- +-- if handle then +-- local result = handle:read("*a") +-- handle:close() +-- return result or "" +-- end +-- +-- return "" +--end + +-------------------------------------------------- + +-- Cross-platform file/URL opener +function M.open_file_or_url(path) + local commands = { + mac = string.format('open "%s"', path), + linux = string.format('xdg-open "%s" &', path), + wsl = string.format('wslview "%s" &', path), + windows = string.format('start "" "%s"', path), + termux = string.format('am start -a android.intent.action.VIEW -d "%s"', path), + } + + local cmd = commands[M.os_name] + if cmd then + os.execute(cmd) + else + vim.notify("No supported file opener for this OS: " .. tostring(M.os_name), vim.log.levels.WARN) + end +end + +-------------------------------------------------- + +-- Automcmd to close netrw buffer when file is opened +vim.api.nvim_create_autocmd("FileType", { + pattern = "netrw", + callback = function() + vim.api.nvim_create_autocmd("BufEnter", { + once = true, + callback = function() + if vim.bo.filetype ~= "netrw" then + for _, buf in ipairs(vim.api.nvim_list_bufs()) do + if vim.bo[buf].filetype == "netrw" then + vim.api.nvim_buf_delete(buf, { force = true }) + end + end + end + end, + }) + end, +}) + +-------------------------------------------------- + +-- Autocomplete +vim.api.nvim_create_autocmd("InsertCharPre", { + callback = function() + -- Exit the autocmd if nvim-cmp is present + local cmp_is_present, _ = pcall(require, "cmp") + if cmp_is_present then + return + end + + -- Skip unwanted buffer types (Telescope, NvimTree, etc.) + local ft = vim.bo.filetype + local bt = vim.bo.buftype + local ignore_ft = { + "TelescopePrompt", + "prompt", + "nofile", + "terminal", + "help", + "quickfix", + "lazy", + "neo-tree", + "NvimTree", + "starter", + "packer", + } + + if bt ~= "" or vim.tbl_contains(ignore_ft, ft) then + return + end + + local col = vim.fn.col(".") + local line = vim.fn.getline(".") + local function safe_sub(i) + return line:sub(i, i) + end + + local prev3 = safe_sub(col - 3) + local prev2 = safe_sub(col - 2) + local prev1 = safe_sub(col - 1) + local curr = vim.v.char + + if curr:match("%w") and prev3:match("%W") and prev2:match("%w") and prev1:match("%w") then + vim.api.nvim_feedkeys( + vim.api.nvim_replace_termcodes("<C-n>", true, true, true), + "n", + true + ) + end + end, +}) +-------------------------------------------------- + +M.has_treesitter = function ( bufnr ) + if not bufnr then + bufnr = vim.api.nvim_get_current_buf() + end + + local highlighter = require( "vim.treesitter.highlighter" ) + + if highlighter.active[ bufnr ] then + return true + else + return false + end +end + +M.parse_treesitter = function ( bufnr, range ) + local parser = vim.treesitter.get_parser( bufnr ) + + -- XXX https://neovim.io/doc/user/treesitter.html#LanguageTree%3Aparse() + parser:parse( range ) +end + +-- ... +return M diff --git a/common/nvim/lua/user/opts.lua b/common/nvim/lua/user/opts.lua new file mode 100755 index 0000000..bac80c3 --- /dev/null +++ b/common/nvim/lua/user/opts.lua @@ -0,0 +1,438 @@ +-- ============================================================================ +-- Options +-- ============================================================================ + +local uname = vim.loop.os_uname() +local system = uname.sysname +local shell = nil + +if system == "Windows_NT" then + -- Windows options + if vim.fn.executable("pwsh") == 1 then + shell = "pwsh" + elseif vim.fn.executable("powershell") == 1 then + shell = "powershell" + elseif vim.fn.executable("bash") == 1 then + shell = "bash" + end +else + -- Unix-like systems: use the user's default shell + local env_shell = os.getenv("SHELL") + if env_shell and vim.fn.executable(env_shell) == 1 then + shell = env_shell + else + -- fallback logic + if vim.fn.executable("zsh") == 1 then + shell = vim.fn.exepath("zsh") + elseif vim.fn.executable("bash") == 1 then + shell = vim.fn.exepath("bash") + end + end +end + +-- Finally set the shell if we found one +if shell then + vim.o.shell = shell +end + +-- Core Settings +vim.opt.encoding = 'utf-8' +vim.opt.fileencoding = 'utf-8' +vim.scriptencoding = 'utf-8' +vim.opt.termguicolors = true +vim.opt.mouse = 'a' +vim.opt.clipboard = 'unnamedplus' +vim.opt.hidden = true +vim.opt.updatetime = 300 +vim.opt.timeoutlen = 500 +vim.opt.ttimeoutlen = 10 + +-- Display +vim.opt.number = true +vim.opt.relativenumber = true +vim.opt.cursorline = true +vim.opt.signcolumn = 'yes' +vim.opt.showcmd = true +vim.opt.showmode = true +vim.opt.showmatch = true +vim.opt.laststatus = 2 +vim.opt.cmdheight = 1 +vim.opt.scrolloff = 5 +vim.opt.sidescrolloff = 5 +vim.opt.display = 'lastline' + +-- Indentation +vim.opt.autoindent = true +vim.opt.smartindent = true +vim.opt.expandtab = true +vim.opt.tabstop = 2 +vim.opt.shiftwidth = 2 +vim.opt.softtabstop = 2 +vim.opt.shiftround = true + +-- Search +vim.opt.hlsearch = true +vim.opt.incsearch = true +vim.opt.ignorecase = true +vim.opt.smartcase = true +vim.opt.inccommand = 'split' + +-- Window Management +vim.opt.splitright = true +vim.opt.splitbelow = true +vim.opt.winminwidth = 1 +vim.opt.winwidth = 5 + +-- File Handling +vim.opt.autoread = true +--vim.opt.autowrite = true +vim.opt.backup = true +vim.opt.backupdir = vim.fn.stdpath('cache') .. '/backup//' +vim.opt.directory = vim.fn.stdpath('cache') .. '/swap//' +vim.opt.undofile = true +vim.opt.undodir = vim.fn.stdpath('cache') .. '/undo//' +vim.opt.swapfile = false + +-- Wildmenu +vim.opt.wildmenu = true +vim.opt.wildmode = 'longest:full,full' +vim.opt.wildignorecase = true +vim.opt.wildignore = '*.o,*.obj,.git,*.rbc,*.pyc,__pycache__' + + +vim.scriptencoding = "utf-8" -- +vim.opt.encoding = "utf-8" -- +vim.opt.fileencoding = "utf-8" -- +vim.g.python3_host_prog = "/usr/bin/python3" -- +vim.g.loaded_python3_provider = 1 -- +vim.g.sh_noisk = 1 -- iskeyword word boundaries when editing a 'sh' file +vim.o.autochdir = true +--vim.o.writeany= true + +-- Clipboard +vim.opt.clipboard:append({ "unnamedplus" }) -- Install xclip or this will slowdown startup + +-- Behaviour +vim.opt.backspace = { "start", "eol", "indent" } -- Make backspace work as you would expect. +vim.opt.hidden = true -- Switch between buffers without having to save first. +vim.opt.conceallevel = 2 +vim.opt.splitbelow = true -- make split put the new buffer below the current buffer +vim.opt.splitright = true -- make vsplit put the new buffer on the right of the current buffer +vim.opt.scrolloff = 8 -- +vim.opt.sidescrolloff = 8 -- how many lines to scroll when using the scrollbar +vim.opt.autoread = true -- reload files if changed externally +vim.opt.display = "lastline" -- Show as much as possible of the last line. +vim.opt.inccommand = "split" -- +vim.opt.ttyfast = true -- Faster redrawing. +vim.opt.lazyredraw = false -- Only redraw when necessary +vim.opt.keywordprg = ":help" -- :help options +vim.opt.ruler = true -- +vim.opt.errorbells = false -- +vim.opt.list = true -- Show non-printable characters. +vim.opt.showmatch = true -- +vim.opt.matchtime = 3 -- +vim.opt.showbreak = "โช " -- +vim.opt.linebreak = true -- +vim.opt.exrc = true -- +--vim.opt.autochdir = true -- or use this to use <:e> to create a file in current directory +vim.opt.autoread = true -- if a file is changed outside of vim, automatically reload it without asking +--vim.opt.notimeout = true -- Timeout on keycodes and not mappings +vim.opt.ttimeout = true -- Makes terminal vim work sanely +vim.opt.ttimeoutlen = 10 -- +--vim.opt.timeoutlen = 100 -- time to wait for a mapped sequence to complete (in milliseconds) +--vim.cmd([[set diffopt = vertical = true]]) -- diffs are shown side-by-side not above/below + +-- Indent/tab +vim.opt.breakindent = true -- +vim.opt.autoindent = true -- Indent according to previous line. +vim.opt.copyindent = true -- Copy indent from the previous line +vim.opt.smarttab = false -- +vim.opt.tabstop = 2 -- +vim.opt.expandtab = true -- Indent according to previous line. +--vim.opt.expandtab = true -- Use spaces instead of tabs. +vim.opt.softtabstop = 2 -- Tab key indents by 2 spaces. +vim.opt.shiftwidth = 2 -- >> indents by 2 spaces. +vim.opt.shiftround = true -- >> indents to next multiple of 'shiftwidth'. +vim.opt.smartindent = true -- smart indent + +-- Column/statusline/Cl + +-- Enable number and relativenumber by default +vim.opt.number = true +vim.opt.relativenumber = true + +-- Entering insert mode: disable relativenumber +vim.api.nvim_create_autocmd("InsertEnter", { + callback = function() + vim.opt.relativenumber = false + end, +}) + +-- Leaving insert mode: enable relativenumber +vim.api.nvim_create_autocmd("InsertLeave", { + callback = function() + vim.opt.relativenumber = true + end, +}) + +vim.opt.title = true -- +--vim.opt.colorcolumn = "+1" -- +vim.opt.signcolumn = "yes:1" -- always show the sign column +--vim.opt.signcolumn = "yes:" .. vim.o.numberwidth +--vim.opt.signcolumn = "number" +--vim.opt.signcolumn = "no" -- +vim.opt.laststatus = 3 -- " Always show statusline. +vim.opt.showmode = true -- Show current mode in command-line, example: -- INSERT -- mode +vim.opt.showcmd = true -- Show the command in the status bar +vim.opt.cmdheight = 1 -- +--vim.opt.cmdheight = 0 -- +vim.opt.report = 0 -- Always report changed lines. +--local autocmd = vim.api.nvim_create_autocmd +--autocmd("bufenter", { +-- pattern = "*", +-- callback = function() +-- if vim.bo.ft ~= "terminal" then +-- vim.opt.statusline = "%!v:lua.require'ui.statusline'.run()" +-- else +-- vim.opt.statusline = "%#normal# " +-- end +-- end, +--}) +---- With vertical splits, the statusline would still show up at the +---- bottom of the split. A quick fix is to just set the statusline +---- to empty whitespace (it can't be an empty string because then +---- it'll get replaced by the default stline). +--vim.opt.stl = " " + +-- Backup/undo/swap +local prefix = vim.env.XDG_CONFIG_HOME or vim.fn.expand("~/.config") +--vim.opt.undodir = os.getenv("HOME") .. "/.vim/undodir" +--vim.opt.undodir = { prefix .. "/nvim/tmp/.undo//" } +vim.opt.undodir = os.getenv("HOME") .. "/.vim/undodir" +vim.opt.directory = { prefix .. "/nvim/tmp/.swp//" } +vim.opt.backupdir = { prefix .. "/nvim/tmp/.backup//" } +vim.opt.undofile = true -- +vim.opt.swapfile = true -- +vim.opt.backup = true -- +--vim.opt.backupcopy = +-- Add timestamp as extension for backup files +vim.api.nvim_create_autocmd("BufWritePre", { + group = vim.api.nvim_create_augroup("timestamp_backupext", { clear = true }), + desc = "Add timestamp to backup extension", + pattern = "*", + callback = function() + vim.opt.backupext = "-" .. vim.fn.strftime("%Y%m%d%H%M") + end, +}) + +-- Format +--vim.opt.textwidth = 80 -- +vim.opt.isfname:append("@-@") +vim.cmd([[let &t_Cs = "\e[4:3m"]]) -- Undercurl +vim.cmd([[let &t_Ce = "\e[4:0m"]]) -- +vim.opt.path:append({ "**" }) -- Finding files - Search down into subfolder +vim.cmd("set whichwrap+=<,>,[,],h,l") -- +vim.cmd([[set iskeyword+=-]]) -- +--vim.cmd([[set formatoptions-=cro]]) -- TODO: this doesn't seem to work +vim.opt.formatoptions = vim.opt.formatoptions + - "t" -- wrap with text width + + "c" -- wrap comments + + "r" -- insert comment after enter + - "o" -- insert comment after o/O + - "q" -- allow formatting of comments with gq + - "a" -- format paragraphs + + "n" -- recognized numbered lists + - "2" -- use indent of second line for paragraph + + "l" -- long lines are not broken + + "j" -- remove comment when joining lines +vim.opt.wrapscan = true -- " Searches wrap around end-of-file. +--vim.wo.number = true -- +--vim.opt.wrap = false -- No Wrap lines +--vim.opt.foldmethod = 'manual' -- +--vim.opt.foldmethod = "expr" -- +vim.opt.foldmethod = "manual" +vim.opt.foldlevel = 3 +vim.opt.confirm = false +--vim.opt.shortmess:append("sI") +--vim.opt.shortmess = "a" +--vim.opt.shortmess = "sI" +--vim.o.shortmess = vim.o.shortmess:gsub('s', '') +vim.opt.shortmess = table.concat({ -- Use abbreviations and short messages in command menu line. + "f", -- Use "(3 of 5)" instead of "(file 3 of 5)". + "i", -- Use "[noeol]" instead of "[Incomplete last line]". + "l", -- Use "999L, 888C" instead of "999 lines, 888 characters". + "m", -- Use "[+]" instead of "[Modified]". + "n", -- Use "[New]" instead of "[New File]". + "r", -- Use "[RO]" instead of "[readonly]". + "w", -- Use "[w]", "[a]" instead of "written", "appended". + "x", -- Use "[dos]", "[unix]", "[mac]" instead of "[dos format]", "[unix format]", "[mac format]". + "o", -- Overwrite message for writing a file with subsequent message. + "O", -- Message for reading a file overwrites any previous message. + "s", -- Disable "search hit BOTTOM, continuing at TOP" such messages. + "t", -- Truncate file message at the start if it is too long. + "T", -- Truncate other messages in the middle if they are too long. + "I", -- Don't give the :intro message when starting. + "c", -- Don't give ins-completion-menu messages. + "F", -- Don't give the file info when editing a file. +}) +vim.opt.fillchars = { + horiz = "โ", + horizup = "โด", + horizdown = "โฌ", + vert = "โ", + vertleft = "โค", + vertright = "โ", + verthoriz = "โผ", + foldopen = "๏", + foldsep = "โ", + foldclose = "๏
", + fold = "โ", + eob = " ", + --diff = "โ", + diff = "โ", + msgsep = "โ", + --msgsep = "โพ", +} +vim.opt.listchars = { tab = "โธ ", trail = "ยท" } -- +--vim.opt.fillchars:append({ eob = " " }) -- remove the ~ from end of buffer +vim.opt.modeline = true -- +vim.opt.modelines = 3 -- modelines (comments that set vim options on a per-file basis) +--vim.opt.modelineexpr = true +--vim.opt.nofoldenable = true -- turn folding off +--vim.opt.foldenable = false -- turn folding off +vim.o.showtabline = 2 + +-- Highlights +vim.opt.incsearch = true -- Highlight while searching with / or ?. +vim.opt.hlsearch = true -- Keep matches highlighted. +vim.opt.ignorecase = true -- ignore case in search patterns UNLESS /C or capital in search +vim.opt.smartcase = true -- smart case +vim.opt.synmaxcol = 200 -- Only highlight the first 200 columns. +--vim.opt.winblend = 30 +--vim.opt.winblend = 5 +vim.opt.wildoptions = "pum" -- +--vim.opt.pumblend = 5 -- +vim.opt.pumblend = 12 -- +--vim.opt.pumblend=15 +vim.opt.pumheight = 10 -- pop up menu height + +-- Better Completion +vim.opt.complete = { ".", "w", "b", "u", "t" } -- +--vim.opt.completeopt = { "longest,menuone,preview" } -- +vim.opt.completeopt = { "menu", "menuone", "noselect" } +--vim.opt.completeopt = { "menuone", "noselect" } -- mostly just for cmp +--vim.opt.completeopt = { "menu", "menuone", "noselect" } -- + +-- Spellcheck +vim.opt.spelllang = { "en_gb", "en_us" } -- Set a list of preferred dictionaries +vim.opt.spell = true +--vim.opt.spellfile = "~/.config/nvim/spell/en.utf-8.add" -- Specify a personal dictionary file + +-- Wildmenu completion -- +vim.opt.wildmenu = true -- +vim.opt.wildmode = { "list:longest" } -- +vim.opt.wildignore:append({ ".hg", ".git", ".svn" }) -- Version control +vim.opt.wildignore:append({ "*.aux", "*.out", "*.toc" }) -- LaTeX intermediate files +vim.opt.wildignore:append({ "*.jpg", "*.bmp", "*.gif", "*.png", "*.jpeg" }) -- binary images +vim.opt.wildignore:append({ "*.o", "*.obj", "*.exe", "*.dll", "*.manifest" }) -- compiled object files +vim.opt.wildignore:append({ "*.spl" }) -- compiled spelling word lists +vim.opt.wildignore:append({ "*.sw?" }) -- Vim swap files +vim.opt.wildignore:append({ "*.DS_Store" }) -- OSX bullshit +vim.opt.wildignore:append({ "*.luac" }) -- Lua byte code +vim.opt.wildignore:append({ "migrations" }) -- Django migrations +vim.opt.wildignore:append({ "*.pyc" }) -- Python byte code +vim.opt.wildignore:append({ "*.orig" }) -- Merge resolution files +vim.opt.wildignore:append({ "*/node_modules/*" }) -- + +-- Shada +vim.opt.shada = "!,'1000,f1,<1000,s100,:1000,/1000,h" + +-- Sessions +vim.opt.sessionoptions = "blank,buffers,curdir,folds,help,tabpages,winsize,winpos,terminal" +--vim.opt.sessionoptions = "curdir,folds,help,options,tabpages,winsize,winpos,terminal,globals" -- +--vim.opt.sessionoptions = "buffers,curdir,folds,help,tabpages,winsize,winpos,terminal" +--vim.opt.sessionoptions:remove({ "blank", "buffers", "globals" }) + +-- Netrw file tree +vim.g.netrw_browse_split = 0 +vim.g.netrw_banner = 0 +vim.g.netrw_winsize = 25 + +-- " Load indent files, to automatically do language-dependent indenting. +--vim.cmd([[ +-- "filetype plugin indent on +--]]) +vim.cmd("filetype plugin on") +vim.cmd("filetype indent off") + +--vim.cmd([[ +-- "autocmd BufEnter * :syntax sync fromstart +-- "syntax enable +-- "set nocompatible +-- "autocmd FileType lua set comments=s1:---,m:--,ex:-- +--]]) + + +-- Fast macros without lazyredraw +vim.cmd([[ + set re=0 + nnoremap @ <cmd>execute "noautocmd norm! " . v:count1 . "@" . getcharstr()<cr> + xnoremap @ :<C-U>execute "noautocmd '<,'>norm! " . v:count1 . "@" . getcharstr()<cr> +]]) + +-- Stop annoying auto commenting on new lines +vim.cmd([[ + augroup annoying + au! + au BufEnter * set fo-=c fo-=r fo-=o + augroup end +]]) + +-- Cursorline +vim.cmd([[ " Only show cursorline in the current window and in normal mode + augroup cline + au! + au WinLeave,InsertEnter * set nocursorline + au WinEnter,InsertLeave * set cursorline + augroup END +]]) +vim.opt.cursorline = true -- +vim.opt.guicursor = "i:ver100,r:hor100" -- + +-- Trailing whitespace +vim.cmd([[ " Only show in insert mode + augroup trailing + au! + au InsertEnter * :set listchars-=trail:โด + au InsertLeave * :set listchars+=trail:โด + augroup END +]]) + +-- Line Return +vim.cmd([[ " Return to the same line when we reopen a file + augroup line_return + au! + au BufReadPost * + \ if line("'\"") > 0 && line("'\"") <= line("$") | + \ execute 'normal! g`"zvzz' | + \ endif + augroup END +]]) + +-- Enable mouse scrollback +vim.cmd([[ + set mouse=a + tnoremap <Esc> <C-\><C-n> + tnoremap <c-b> <c-\><c-n> + function! ClearTerminal() + set scrollback=1 + let &g:scrollback=1 + echo &scrollback + call feedkeys("\i") + call feedkeys("clear\<CR>") + call feedkeys("\<C-\>\<C-n>") + call feedkeys("\i") + sleep 100m + let &scrollback=s:scroll_value + endfunction +]]) diff --git a/common/nvim/lua/user/view.lua b/common/nvim/lua/user/view.lua new file mode 100755 index 0000000..f243194 --- /dev/null +++ b/common/nvim/lua/user/view.lua @@ -0,0 +1,180 @@ +-- ============================================================================ +-- View/UI +-- ============================================================================ + +local M = {} + +-- List of available themes (for reference or user selection UI) +M.available_themes = { + "nightfly", "ayu", "onedark", "doom-one", "nvimgelion", "github_dark", "tokyonight", "bamboo", "oxocarbon" +} + +-- Configuration +local default_colorscheme = "tokyonight" +local fallback_colorscheme = "default" + +-- Diagnostic icons +local Signs = { + Error = "โ", + Warn = "๏ฑ", + Hint = "โ", + Info = "๏ ต", +} + +-- Setup Function +function M.setup() + -- Truecolor & syntax + vim.opt.termguicolors = true + vim.cmd("syntax on") + + -- Colorscheme setup with fallback + local ok = pcall(vim.cmd, "colorscheme " .. default_colorscheme) + if not ok then + vim.cmd("colorscheme " .. fallback_colorscheme) + end + + -- Optional: Tokyonight configuration + pcall(function() + require("tokyonight").setup({ + style = "night", + transparent = true, + transparent_sidebar = true, + dim_inactive = false, + styles = { + sidebars = "transparent", + floats = "transparent", + }, + }) + end) + + -- Highlight groups + local highlights = { + -- Core UI + { group = "Normal", options = { bg = "none" } }, + { group = "NormalNC", options = { bg = "none" } }, + { group = "NormalFloat", options = { bg = "none" } }, + { group = "Float", options = { bg = "none" } }, + { group = "FloatBorder", options = { bg = "none", fg = "#7f8493" } }, + { group = "StatusLine", options = { bg = "none" } }, + { group = "TabLine", options = { bg = "#333842", bold = true } }, + { group = "TabLineSel", options = { bg = "#333842", bold = true } }, + { group = "TabLineFill", options = { bg = "none", bold = true } }, + { group = "WinBar", options = { bg = "none", bold = true } }, + { group = "WinBarNC", options = { bg = "none" } }, + { group = "WinSeparator", options = { bg = "none", fg = "#444b62", bold = true } }, + { group = "EndOfBuffer", options = { bg = "none", fg = "#7f8493" } }, + { group = "NonText", options = { bg = "none", fg = "#555b71" } }, + { group = "LineNr", options = { bg = "none", fg = "#555b71" } }, + { group = "SignColumn", options = { bg = "none" } }, + { group = "FoldColumn", options = { bg = "none" } }, + { group = "CursorLine", options = { bg = "#3a3f52" } }, + { group = "CursorLineNr", options = { bg = "#3a3f52", fg = "#cdd6f4" } }, + { group = "CursorLineSign", options = { bg = "none" } }, + { group = "Title", options = { bg = "none", bold = true } }, + { group = "Comment", options = { bg = "none", fg = "#6b7089" } }, + { group = "MsgSeparator", options = { bg = "none" } }, + { group = "WarningMsg", options = { bg = "none", fg = "#e6c384" } }, + { group = "MoreMsg", options = { bg = "none", fg = "#7f8493" } }, + + -- Pop-up / menu + { group = "Pmenu", options = { bg = "none" } }, + { group = "PmenuSel", options = { fg = "black", bg = "white" } }, + { group = "PmenuThumb", options = { bg = "none" } }, + { group = "PmenuSbar", options = { bg = "none" } }, + { group = "PmenuExtra", options = { bg = "none" } }, + { group = "PmenuExtraSel", options = { bg = "none" } }, + { group = "WildMenu", options = { link = "PmenuSel" } }, + + -- Telescope + { group = "TelescopeNormal", options = { bg = "none" } }, + { group = "TelescopePromptNormal", options = { bg = "none" } }, + { group = "TelescopeResultsNormal", options = { bg = "none" } }, + { group = "TelescopePreviewNormal", options = { bg = "none" } }, + { group = "TelescopeBorder", options = { bg = "none", fg = "#7f8493" } }, + { group = "TelescopeMatching", options = { fg = "#cba6f7", bold = true } }, + + -- Blending + { group = "Winblend", options = { bg = "none" } }, + { group = "Pumblend", options = { bg = "none" } }, + + ---- NvimTree + --{ group = "NvimTreeNormal", options = { bg = "none", fg = "NONE" } }, + --{ group = "NvimTreeNormalNC", options = { bg = "none", fg = "NONE" } }, + --{ group = "NvimTreeNormalFloat", options = { bg = "none" } }, + --{ group = "NvimTreeEndOfBuffer", options = { bg = "none" } }, + --{ group = "NvimTreeCursorLine", options = { bg = "#50fa7b", fg = "#000000" } }, + --{ group = "NvimTreeSymlinkFolderName", options = { fg = "#f8f8f2", bg = "none" } }, + --{ group = "NvimTreeFolderName", options = { fg = "#f8f8f2", bg = "none" } }, + --{ group = "NvimTreeRootFolder", options = { fg = "#f8f8f2", bg = "none" } }, + --{ group = "NvimTreeEmptyFolderName", options = { fg = "#f8f8f2", bg = "none" } }, + --{ group = "NvimTreeOpenedFolderName", options = { fg = "#f8f8f2", bg = "none" } }, + --{ group = "NvimTreeOpenedFile", options = { fg = "#50fa7b", bg = "none" } }, + --{ group = "NvimTreeExecFile", options = { fg = "#ff882a", bg = "none" } }, + } + + for _, hl in ipairs(highlights) do + vim.api.nvim_set_hl(0, hl.group, hl.options) + end + + -- Reapply highlights on ColorScheme change + vim.api.nvim_create_autocmd("ColorScheme", { + group = vim.api.nvim_create_augroup("CustomHighlights", { clear = true }), + pattern = "*", + callback = function() + for _, hl in ipairs(highlights) do + vim.api.nvim_set_hl(0, hl.group, hl.options) + end + end, + }) + + -- Optional window separator styling + vim.cmd([[ + augroup CustomWinSeparator + autocmd! + autocmd WinEnter * setlocal winhl=WinSeparator:WinSeparatorA + autocmd WinLeave * setlocal winhl=WinSeparator:WinSeparator + augroup END + ]]) + + -- Diagnostics configuration + local border = "rounded" + vim.diagnostic.config({ + signs = { + text = { + [vim.diagnostic.severity.ERROR] = Signs.Error, + [vim.diagnostic.severity.WARN] = Signs.Warn, + [vim.diagnostic.severity.HINT] = Signs.Hint, + [vim.diagnostic.severity.INFO] = Signs.Info, + }, + }, + underline = true, + virtual_text = false, + virtual_lines = false, + float = { + show_header = true, + source = "always", + border = border, + focusable = true, + }, + update_in_insert = false, + severity_sort = true, + }) + + -- Fallback statusline if heirline is missing + local heirline_ok, _ = pcall(require, "heirline") + if not heirline_ok then + local statusline_path = vim.fn.stdpath("config") .. "/autoload/statusline.vim" + if vim.fn.filereadable(statusline_path) == 1 then + vim.cmd.source(statusline_path) + vim.api.nvim_create_autocmd("VimEnter", { + callback = function() + vim.cmd("call autoload#statusline#ActivateStatusline()") + end, + }) + else + vim.notify("Fallback statusline script not found:\n" .. statusline_path, vim.log.levels.ERROR) + end + end +end + +return M |
