diff --git a/.config/nvim-astro/lua/plugins/grapple.lua b/.config/nvim-astro/lua/plugins/grapple.lua index d138a6a..8f647e0 100644 --- a/.config/nvim-astro/lua/plugins/grapple.lua +++ b/.config/nvim-astro/lua/plugins/grapple.lua @@ -14,6 +14,7 @@ return { }, keys = { { "A", "Grapple toggle", desc = "Tag a file" }, + { "`", "Grapple toggle", desc = "Tag a file" }, { "", "Grapple toggle", desc = "Tag a file" }, { "", "Grapple toggle_tags", desc = "Toggle tags menu" }, diff --git a/.config/nvim-astro/lua/plugins/mini/operators.lua b/.config/nvim-astro/lua/plugins/mini/operators.lua index 7453beb..15e23a1 100644 --- a/.config/nvim-astro/lua/plugins/mini/operators.lua +++ b/.config/nvim-astro/lua/plugins/mini/operators.lua @@ -9,6 +9,7 @@ return { { "gm", mode = { "n", "x" }, desc = "Duplicate" }, { "x", mode = { "n", "x" }, desc = "Replace with register" }, { "gs", mode = { "n", "x" }, desc = "Sort" }, + "X", }, opts = { -- Exchange text regions diff --git a/.config/nvim-astro/lua/plugins/tpope.lua b/.config/nvim-astro/lua/plugins/tpope.lua new file mode 100644 index 0000000..3a3cb3d --- /dev/null +++ b/.config/nvim-astro/lua/plugins/tpope.lua @@ -0,0 +1,13 @@ +---@type LazySpec +return { + { 'tpope/vim-repeat', event = 'VeryLazy' }, + { + 'tpope/vim-abolish', + keys = { 'cr' }, + cmd = { 'Abolish', 'Subvert', 'S' }, + }, + { + 'tpope/vim-dispatch', + cmd = { 'Dispatch', 'Make', 'Focus', 'Start', 'FocusDispatch', 'Spawn', 'Copen', 'AbortDispatch' }, + }, +} diff --git a/.config/nvim-lazy/lua/plugins/mini/operators.lua b/.config/nvim-lazy/lua/plugins/mini/operators.lua index 7453beb..15e23a1 100644 --- a/.config/nvim-lazy/lua/plugins/mini/operators.lua +++ b/.config/nvim-lazy/lua/plugins/mini/operators.lua @@ -9,6 +9,7 @@ return { { "gm", mode = { "n", "x" }, desc = "Duplicate" }, { "x", mode = { "n", "x" }, desc = "Replace with register" }, { "gs", mode = { "n", "x" }, desc = "Sort" }, + "X", }, opts = { -- Exchange text regions diff --git a/.config/nvim-lazy/lua/plugins/tpope.lua b/.config/nvim-lazy/lua/plugins/tpope.lua new file mode 100644 index 0000000..3a3cb3d --- /dev/null +++ b/.config/nvim-lazy/lua/plugins/tpope.lua @@ -0,0 +1,13 @@ +---@type LazySpec +return { + { 'tpope/vim-repeat', event = 'VeryLazy' }, + { + 'tpope/vim-abolish', + keys = { 'cr' }, + cmd = { 'Abolish', 'Subvert', 'S' }, + }, + { + 'tpope/vim-dispatch', + cmd = { 'Dispatch', 'Make', 'Focus', 'Start', 'FocusDispatch', 'Spawn', 'Copen', 'AbortDispatch' }, + }, +} diff --git a/.config/nvim-vscode/after/plugin/flash.lua b/.config/nvim-vscode/after/plugin/flash.lua index a0ea619..d149ae8 100644 --- a/.config/nvim-vscode/after/plugin/flash.lua +++ b/.config/nvim-vscode/after/plugin/flash.lua @@ -4,6 +4,7 @@ if ok_flash then modes = { char = { enabled = false, autohide = false } }, }) vim.keymap.set({ "n", "x" }, "s", flash.jump, { desc = "Flash" }) + vim.keymap.set({ "n", "o" }, "S", flash.treesitter, { desc = "Flash" }) vim.keymap.set("o", "r", flash.remote, { desc = "Remote Flash" }) vim.keymap.set("c", "", flash.toggle, { desc = "Toggle Flash Search" }) end diff --git a/.config/nvim-vscode/after/plugin/mini-nvim.lua b/.config/nvim-vscode/after/plugin/mini-nvim.lua new file mode 100644 index 0000000..e48b509 --- /dev/null +++ b/.config/nvim-vscode/after/plugin/mini-nvim.lua @@ -0,0 +1,27 @@ +local ok, operators = pcall(require, "mini.operators") +if not ok then + return +end + +require("mini.align").setup({}) +require("mini.move").setup({ + -- Move current line in Visual mode + mappings = { + left = "<", + right = ">", + down = "J", + up = "K", + + -- Move current line in Normal mode + line_left = "", + line_right = "", + line_down = "", + line_up = "", + }, +}) + +operators.setup({ + exchange = { prefix = "ge" }, + replace = { prefix = "x" }, +}) +vim.keymap.set("n", "X", "x$", { desc = "Replace to end of line", remap = true }) diff --git a/.config/nvim-vscode/after/plugin/theme.lua b/.config/nvim-vscode/after/plugin/theme.lua index a5abb6d..fdeb48d 100644 --- a/.config/nvim-vscode/after/plugin/theme.lua +++ b/.config/nvim-vscode/after/plugin/theme.lua @@ -11,7 +11,37 @@ if vim.g.vscode == nil then }) vim.cmd.colorscheme "tokyodark" end - if vim.fn.isdirectory(vim.fn.stdpath('data') .. '/plugged/mono-jade') == 1 then - vim.cmd("colo mono-jade") + if vim.fn.isdirectory(vim.fn.stdpath "data" .. "/plugged/mono-jade") == 1 then + vim.cmd.colorscheme "mono-jade" + end + if vim.fn.isdirectory(vim.fn.stdpath "data" .. "/plugged/mellow.nvim") == 1 then + vim.cmd.colorscheme "mellow" + end + local ok_nordic, nordic = pcall(require, "nordic") + if ok_nordic then + nordic.setup({ + transparent = { bg = true }, + }) + require("nordic").load() + end + local ok_gruber_darker, gruber_darker = pcall(require, "gruber-darker") + if ok_gruber_darker then + ---@diagnostic disable-next-line: missing-fields + gruber_darker.setup({}) + vim.cmd.colorscheme "gruber-darker" + local c = require "gruber-darker.palette" + vim.api.nvim_set_hl(0, "MatchParenCur", { bold = true }) + vim.api.nvim_set_hl(0, "@lsp.type.keyword.lua", { fg = c["brown"]:to_string(), bold = false }) + vim.api.nvim_set_hl(0, "@lsp.type.event.lua", { link = "GruberDarkerYellowBold" }) + vim.api.nvim_set_hl( + 0, + "QuickScopePrimary", + { fg = c["yellow"]:to_string(), bg = c["bg+1"]:to_string(), underline = true, bold = true } + ) + vim.api.nvim_set_hl( + 0, + "QuickScopeSecondary", + { fg = c["brown"]:to_string(), bg = c["bg+1"]:to_string(), underline = true, bold = true } + ) end end diff --git a/.config/nvim-vscode/init.vim b/.config/nvim-vscode/init.vim index 317fe4c..d1bedbf 100644 --- a/.config/nvim-vscode/init.vim +++ b/.config/nvim-vscode/init.vim @@ -3,18 +3,26 @@ function! Cond(Cond, ...) return a:Cond ? opts : extend(opts, { 'on': [], 'for': [] }) endfunction +let g:qs_highlight_on_keys = ['f', 'F', 't', 'T'] +let g:qs_lazy_highlight = 1 + call plug#begin(stdpath('data') . '/plugged') -Plug 'junegunn/vim-easy-align' +" Plug 'junegunn/vim-easy-align' Plug 'tpope/vim-repeat' Plug 'tpope/vim-commentary' Plug 'tpope/vim-surround' +Plug 'tpope/vim-abolish' Plug 'unblevable/quick-scope' -Plug 'svermeulen/vim-subversive' +" Plug 'svermeulen/vim-subversive' +Plug 'machakann/vim-swap' Plug 'folke/flash.nvim' Plug 'monaqa/dial.nvim' -Plug 'tpope/vim-abolish' +Plug 'echasnovski/mini.nvim' if !exists('g:vscode') - Plug 'masar3141/mono-jade' + " Plug 'masar3141/mono-jade' + " Plug 'AlexvZyl/nordic.nvim', { 'branch': 'main' } + " Plug 'mellow-theme/mellow.nvim', { 'branch': 'main' } + Plug 'blazkowolf/gruber-darker.nvim', { 'branch': 'main' } Plug 'windwp/nvim-autopairs' endif @@ -30,7 +38,6 @@ set autoindent set smartindent set mouse=a set iskeyword+=- -set clipboard+=unnamedplus if !exists('g:vscode') " filetype plugin indent on " syntax on @@ -56,13 +63,10 @@ set ignorecase set smartcase if executable('rg') set grepprg=rg\ --vimgrep\ --no-heading\ --smart-case - set grepformat+=%f:%l:%c:%m + " set grepformat+=%f:%l:%c:%m endif let g:mapleader = " " -let g:qs_highlight_on_keys = ['f', 'F', 't', 'T'] -let g:qs_lazy_highlight = 1 - if exists('g:vscode') map ze call VSCodeNotify('scrollLineDown') map zy call VSCodeNotify('scrollLineUp') @@ -162,12 +166,11 @@ else nnoremap ,W noautocmd w! nnoremap zp vaBo^ endif + +" for quick-scope plugin highlight QuickScopePrimary guifg='#afff5f' gui=underline ctermfg=155 cterm=underline highlight QuickScopeSecondary guifg='#5fffff' gui=underline ctermfg=81 cterm=underline -nmap x (SubversiveSubstitute) -nmap xx (SubversiveSubstituteLine) -nmap X (SubversiveSubstituteToEndOfLine) nmap 0 ^ nnoremap nohl @@ -178,21 +181,24 @@ nnoremap dl "_dl nnoremap ,s :let @/='\<'.expand('').'\>'cgn vnoremap ,s "sy:let @/=@scgn vnoremap p 'pgv"'.v:register.'y' -vnoremap J :m '>+1gv=gv -vnoremap K :m '<-2gv=gv -vnoremap > >gv -vnoremap < (EasyAlign) -nmap ga (EasyAlign) onoremap ie :exec "normal! ggVG" onoremap iv :exec "normal! HVL" +" from vim-swap plugin +omap i, (swap-textobject-i) +xmap i, (swap-textobject-i) +omap a, (swap-textobject-a) +xmap a, (swap-textobject-a) augroup highlight_yank autocmd! autocmd TextYankPost * silent! lua vim.highlight.on_yank { higroup="IncSearch", timeout=100 } augroup END +" set clipboard+=unnamedplus lua << EOF +vim.schedule(function() + vim.opt.clipboard:append(vim.env.SSH_TTY and '' or 'unnamedplus') -- Sync with system clipboard +end) if vim.g.vscode == nil then local o = vim.opt o.undodir = { vim.fn.stdpath 'state' .. '/undodir//' } diff --git a/.config/nvim/init.lua b/.config/nvim/init.lua index a77383d..bc414d7 100644 --- a/.config/nvim/init.lua +++ b/.config/nvim/init.lua @@ -4,42 +4,4 @@ vim.g.base46_cache = vim.fn.stdpath 'data' .. '/base46_cache/' vim.t['bufs'] = vim.t.bufs and vim.t.bufs or vim.api.nvim_list_bufs() -- initialize buffers for the current tab -local lazypath = vim.fn.stdpath 'data' .. '/lazy/lazy.nvim' -if not vim.loop.fs_stat(lazypath) then - vim.fn.system({ - 'git', - 'clone', - '--filter=blob:none', - 'https://github.com/folke/lazy.nvim.git', - '--branch=stable', -- latest stable release - lazypath, - }) -end -vim.opt.rtp:prepend(lazypath) - -require('lazy').setup({ - { import = 'plugins' }, - { import = 'plugins.mini' }, - { import = 'plugins.cmp' }, - { import = 'plugins.lsp' }, -}, { - change_detection = { - enabled = true, - notify = false, - }, - lockfile = vim.fn.stdpath 'state' .. '/lazy-lock.json', -- lockfile generated after running update. - performance = { - rtp = { - ---@type string[] list any plugins you want to disable here - disabled_plugins = { - 'gzip', - 'matchit', - 'netrwPlugin', - 'tarPlugin', - 'tohtml', - 'tutor', - 'zipPlugin', - }, - }, - }, -}) +require 'lazy_init' diff --git a/.config/nvim/lua/lazy_init.lua b/.config/nvim/lua/lazy_init.lua new file mode 100644 index 0000000..8a2b46c --- /dev/null +++ b/.config/nvim/lua/lazy_init.lua @@ -0,0 +1,38 @@ +local lazypath = vim.fn.stdpath 'data' .. '/lazy/lazy.nvim' +if not vim.loop.fs_stat(lazypath) then + vim.fn.system({ + 'git', + 'clone', + '--filter=blob:none', + 'https://github.com/folke/lazy.nvim.git', + '--branch=stable', -- latest stable release + lazypath, + }) +end +vim.opt.rtp:prepend(lazypath) + +require('lazy').setup({ + { import = 'plugins' }, + { import = 'plugins.mini' }, + { import = 'plugins.lsp' }, +}, { + change_detection = { + enabled = true, + notify = false, + }, + lockfile = vim.fn.stdpath 'state' .. '/lazy-lock.json', -- lockfile generated after running update. + performance = { + rtp = { + ---@type string[] list any plugins you want to disable here + disabled_plugins = { + 'gzip', + 'matchit', + 'netrwPlugin', + 'tarPlugin', + 'tohtml', + 'tutor', + 'zipPlugin', + }, + }, + }, +}) diff --git a/.config/nvim/lua/plugins/align.lua b/.config/nvim/lua/plugins/align.lua deleted file mode 100644 index 6683df9..0000000 --- a/.config/nvim/lua/plugins/align.lua +++ /dev/null @@ -1,6 +0,0 @@ -return { - 'junegunn/vim-easy-align', - keys = { - { 'ga', '(EasyAlign)', noremap = false, mode = { 'n', 'v' }, desc = 'EasyAlign' }, - }, -} diff --git a/.config/nvim/lua/plugins/autopairs.lua b/.config/nvim/lua/plugins/autopairs.lua index a184973..e2a9790 100644 --- a/.config/nvim/lua/plugins/autopairs.lua +++ b/.config/nvim/lua/plugins/autopairs.lua @@ -1,7 +1,167 @@ +local function rule_add_spaces_between_paren() + local npairs = require 'nvim-autopairs' + local Rule = require 'nvim-autopairs.rule' + local cond = require 'nvim-autopairs.conds' + + local brackets = { { '(', ')' }, { '[', ']' }, { '{', '}' } } + npairs.add_rules({ + -- Rule for a pair with left-side ' ' and right side ' ' + Rule(' ', ' ') + -- Pair will only occur if the conditional function returns true + :with_pair(function(opts) + -- We are checking if we are inserting a space in (), [], or {} + local pair = opts.line:sub(opts.col - 1, opts.col) + return vim.tbl_contains({ + brackets[1][1] .. brackets[1][2], + brackets[2][1] .. brackets[2][2], + brackets[3][1] .. brackets[3][2], + }, pair) + end) + :with_move(cond.none()) + :with_cr(cond.none()) + -- We only want to delete the pair of spaces when the cursor is as such: ( | ) + :with_del(function(opts) + local col = vim.api.nvim_win_get_cursor(0)[2] + local context = opts.line:sub(col - 1, col + 2) + return vim.tbl_contains({ + brackets[1][1] .. ' ' .. brackets[1][2], + brackets[2][1] .. ' ' .. brackets[2][2], + brackets[3][1] .. ' ' .. brackets[3][2], + }, context) + end), + }) + -- For each pair of brackets we will add another rule + for _, bracket in pairs(brackets) do + npairs.add_rules({ + -- Each of these rules is for a pair with left-side '( ' and right-side ' )' for each bracket type + Rule(bracket[1] .. ' ', ' ' .. bracket[2]) + :with_pair(cond.none()) + :with_move(function(opts) + return opts.char == bracket[2] + end) + :with_del(cond.none()) + :use_key(bracket[2]) + -- Removes the trailing whitespace that can occur without this + :replace_map_cr(function(_) + return '2xiO' + end), + }) + end +end + +local function rule_add_space_on_equal() + local Rule = require 'nvim-autopairs.rule' + local cond = require 'nvim-autopairs.conds' + Rule('=', '') + :with_pair(cond.not_inside_quote()) + :with_pair(function(opts) + local last_char = opts.line:sub(opts.col - 1, opts.col - 1) + if last_char:match '[%w%=%s]' then + return true + end + return false + end) + :replace_endpair(function(opts) + local prev_2char = opts.line:sub(opts.col - 2, opts.col - 1) + local next_char = opts.line:sub(opts.col, opts.col) + next_char = next_char == ' ' and '' or ' ' + if prev_2char:match '%w$' then + return ' =' .. next_char + end + if prev_2char:match '%=$' then + return next_char + end + if prev_2char:match '=' then + return '=' .. next_char + end + return '' + end) + :set_end_pair_length(0) + :with_move(cond.none()) + :with_del(cond.none()) +end +-- https://github.com/rstacruz/vim-closer/blob/master/autoload/closer.vim +local get_closing_for_line = function(line) + local i = -1 + local clo = '' + + while true do + i, _ = string.find(line, '[%(%)%{%}%[%]]', i + 1) + if i == nil then + break + end + local ch = string.sub(line, i, i) + local st = string.sub(clo, 1, 1) + + if ch == '{' then + clo = '}' .. clo + elseif ch == '}' then + if st ~= '}' then + return '' + end + clo = string.sub(clo, 2) + elseif ch == '(' then + clo = ')' .. clo + elseif ch == ')' then + if st ~= ')' then + return '' + end + clo = string.sub(clo, 2) + elseif ch == '[' then + clo = ']' .. clo + elseif ch == ']' then + if st ~= ']' then + return '' + end + clo = string.sub(clo, 2) + end + end + + return clo +end + +local function rule_expand_multiple_on_enter(autopairs) + local Rule = require 'nvim-autopairs.rule' + + autopairs.remove_rule '(' + autopairs.remove_rule '{' + autopairs.remove_rule '[' + + autopairs.add_rule(Rule('[%(%{%[]', '') + :use_regex(true) + :replace_endpair(function(opts) + return get_closing_for_line(opts.line) + end) + :end_wise(function(opts) + -- Do not endwise if there is no closing + return get_closing_for_line(opts.line) ~= '' + end)) +end + ---@type LazySpec return { 'windwp/nvim-autopairs', event = 'InsertEnter', enabled = true, - config = require('plugins.config.autopairs').config, + config = function(_, opts) + local options = vim.tbl_deep_extend('force', { + disable_filetype = { 'TelescopePrompt' }, + ignored_next_char = '[%w%.]', + check_ts = false, + map_c_w = true, + fast_wrap = {}, + }, opts) + local npairs = require 'nvim-autopairs' + npairs.setup(options) + + rule_add_spaces_between_paren() + rule_add_space_on_equal() + -- rule_expand_multiple_on_enter(npairs) + + local ok, cmp = pcall(require, 'cmp') + if ok then + local cmp_autopairs = require 'nvim-autopairs.completion.cmp' + cmp.event:on('confirm_done', cmp_autopairs.on_confirm_done()) + end + end, } diff --git a/.config/nvim/lua/plugins/avante.lua b/.config/nvim/lua/plugins/avante.lua index 0b94b14..8e80c70 100644 --- a/.config/nvim/lua/plugins/avante.lua +++ b/.config/nvim/lua/plugins/avante.lua @@ -1,12 +1,3 @@ -local function get_age_credentials(secret_file) - if not vim.fn.filereadable '$HOME/.config/age/identity.txt' then - return nil - end - local identity = vim.fn.expand '$HOME/.config/age/identity.txt' - local secret = vim.fn.expand('$HOME/.config/age/' .. secret_file) - return require('age').get(secret, identity) -end - ---@type LazySpec return { { @@ -15,7 +6,7 @@ return { version = false, build = 'make', opts = function() - vim.env.GEMINI_API_KEY = get_age_credentials 'gemini_api.age' + vim.env.GEMINI_API_KEY = require('plugins.config.util').get_age_credentials 'gemini_api.age' local ollama_setup = { -- add any opts here ---@type Provider @@ -53,6 +44,9 @@ return { return { ---@type Provider provider = 'gemini', + gemini = { + model = 'gemini-2.0-flash-exp', + }, } end, dependencies = { @@ -146,7 +140,7 @@ return { env = { url = 'https://glhf.chat', api_key = function() - return get_age_credentials 'glhf.age' + return require('plugins.config.util').get_age_credentials 'glhf.age' end, chat_url = '/api/openai/v1/chat/completions', }, diff --git a/.config/nvim/lua/plugins/blink-cmp.lua b/.config/nvim/lua/plugins/blink-cmp.lua index d4c23d0..5bea415 100644 --- a/.config/nvim/lua/plugins/blink-cmp.lua +++ b/.config/nvim/lua/plugins/blink-cmp.lua @@ -2,73 +2,95 @@ return { 'Saghen/blink.cmp', enabled = false, - lazy = false, -- lazy loading handled internally + -- use a release tag to download pre-built binaries + version = '*', -- optional: provides snippets for the snippet source dependencies = { 'rafamadriz/friendly-snippets', + 'mikavilpas/blink-ripgrep.nvim', { 'folke/lazydev.nvim', ft = 'lua', -- only load on lua files opts = { library = { 'lazy.nvim', - { path = 'luvit-meta/library', words = { 'vim%.uv' } }, + -- See the configuration section for more details + -- Load luvit types when the `vim.uv` word is found + { path = '${3rd}/luv/library', words = { 'vim%.uv' } }, }, }, }, { 'Bilal2453/luvit-meta', lazy = true }, }, - - -- use a release tag to download pre-built binaries - version = 'v0.*', - -- OR build from source, requires nightly: https://rust-lang.github.io/rustup/concepts/channels.html#working-with-nightly-rust - -- build = 'cargo build --release', - + ---@module 'blink.cmp' + ---@type blink.cmp.Config opts = { keymap = { - hide = '', - accept = '', + preset = 'enter', + [''] = { 'select_and_accept', 'fallback' }, + [''] = { 'select_prev', 'fallback' }, + [''] = { 'select_next', 'fallback' }, + [''] = { 'select_next', 'snippet_forward', 'fallback' }, + [''] = { 'select_prev', 'snippet_backward', 'fallback' }, + cmdline = { + preset = 'enter', + [''] = {}, + [''] = {}, + [''] = { 'select_prev', 'fallback' }, + [''] = { 'select_next', 'fallback' }, + [''] = { 'select_next', 'fallback' }, + [''] = { 'select_prev', 'fallback' }, + }, + }, + completion = { + ghost_text = { enabled = false }, + menu = { border = 'rounded' }, + documentation = { window = { border = 'rounded' } }, + list = { + selection = function(ctx) + return ctx.mode == 'cmdline' and 'auto_insert' or 'preselect' + end, + }, }, - highlight = { use_nvim_cmp_as_default = true }, - -- set to 'mono' for 'Nerd Font Mono' or 'normal' for 'Nerd Font' - -- adjusts spacing to ensure icons are aligned - nerd_font_variant = 'mono', - -- experimental auto-brackets support - accept = { auto_brackets = { enabled = true } }, - -- experimental signature help support - trigger = { signature_help = { enabled = true } }, sources = { + default = { + 'lazydev', + 'lsp', + 'path', + 'snippets', + 'buffer', + 'ripgrep', + }, providers = { - { 'blink.cmp.sources.lsp', name = 'LSP', score_offset = 1 }, - { - 'blink.cmp.sources.snippets', - name = 'Snippets', - -- keyword_length = 1, -- not supported yet - }, - { - 'blink.cmp.sources.path', - name = 'Path', - score_offset = 3, - opts = { get_cwd = vim.uv.cwd }, + ripgrep = { + module = 'blink-ripgrep', + name = 'Ripgrep', + ---@module "blink-ripgrep" + ---@type blink-ripgrep.Options + opts = { + prefix_min_len = 4, + score_offset = 10, -- should be lower priority + max_filesize = '300K', + search_casing = '--smart-case', + }, }, - { - 'blink.cmp.sources.buffer', - name = 'Buffer', - keyword_length = 3, - score_offset = -1, - fallback_for = { 'Path' }, -- PENDING https://github.com/Saghen/blink.cmp/issues/122 + lazydev = { + name = 'LazyDev', + module = 'lazydev.integrations.blink', + -- make lazydev completions top priority (see `:h blink.cmp`) + score_offset = 100, }, }, - }, - windows = { - documentation = { - min_width = 15, - max_width = 50, - max_height = 15, - border = 'single', - auto_show = true, - auto_show_delay_ms = 200, - }, + cmdline = function() + local type = vim.fn.getcmdtype() + if type == ':' then + return { 'path', 'cmdline' } + end + if type == '/' or type == '?' then + return { 'buffer' } + end + return {} + end, }, }, } diff --git a/.config/nvim/lua/plugins/cmp/init.lua b/.config/nvim/lua/plugins/cmp/init.lua deleted file mode 100644 index 67f34c5..0000000 --- a/.config/nvim/lua/plugins/cmp/init.lua +++ /dev/null @@ -1,66 +0,0 @@ ----@type LazySpec -return { - 'iguanacucumber/magazine.nvim', - name = 'nvim-cmp', -- Otherwise highlighting gets messed up - enabled = true, - event = 'BufReadPre', - dependencies = { - 'hrsh7th/cmp-nvim-lsp', - 'hrsh7th/cmp-buffer', - -- 'hrsh7th/cmp-path', - 'https://codeberg.org/FelipeLema/cmp-async-path', - 'hrsh7th/cmp-cmdline', - 'lukas-reineke/cmp-rg', - -- 'lukas-reineke/cmp-under-comparator', - 'octaltree/cmp-look', - 'saadparwaiz1/cmp_luasnip', - { - 'L3MON4D3/LuaSnip', - build = 'make install_jsregexp', - dependencies = { 'rafamadriz/friendly-snippets' }, - event = 'User BaseFile', - opts = { history = true, delete_check_events = 'TextChanged', region_check_events = 'CursorMoved' }, - config = function(_, opts) - if opts then - require('luasnip').config.setup(opts) - end - - vim.tbl_map(function(type) - require('luasnip.loaders.from_' .. type).lazy_load() - end, { 'vscode', 'snipmate', 'lua' }) - - local extends = { - typescript = { 'tsdoc' }, - javascript = { 'jsdoc' }, - lua = { 'luadoc' }, - python = { 'pydoc' }, - rust = { 'rustdoc' }, - cs = { 'csharpdoc' }, - java = { 'javadoc' }, - c = { 'cdoc' }, - cpp = { 'cppdoc' }, - php = { 'phpdoc' }, - kotlin = { 'kdoc' }, - ruby = { 'rdoc' }, - sh = { 'shelldoc' }, - } - -- friendly-snippets - enable standardized comments snippets - for ft, snips in pairs(extends) do - require('luasnip').filetype_extend(ft, snips) - end - end, - }, - 'onsails/lspkind.nvim', - { - 'folke/lazydev.nvim', - ft = 'lua', -- only load on lua files - opts = { - library = { 'lazy.nvim', { path = 'luvit-meta/library', words = { 'vim%.uv' } } }, - }, - }, - { 'Bilal2453/luvit-meta', lazy = true }, - }, - config = function() - require 'plugins.config.cmp' - end, -} diff --git a/.config/nvim/lua/plugins/config/astrolsp.lua b/.config/nvim/lua/plugins/config/astrolsp.lua deleted file mode 100644 index aa12c7f..0000000 --- a/.config/nvim/lua/plugins/config/astrolsp.lua +++ /dev/null @@ -1,353 +0,0 @@ -local M = {} - -M.opts = { - -- Configuration table of features provided by AstroLSP - features = { - autoformat = true, -- enable or disable auto formatting on start - codelens = true, -- enable/disable codelens refresh on start - inlay_hints = false, -- enable/disable inlay hints on start - semantic_tokens = true, -- enable/disable semantic token highlighting - }, - -- Configure buffer local auto commands to add when attaching a language server - autocmds = { - -- first key is the `augroup` (:h augroup) - lsp_document_highlight = { - cond = 'textDocument/documentHighlight', - -- list of auto commands to set - { - -- events to trigger - event = { 'CursorHold', 'CursorHoldI' }, - -- the rest of the autocmd options (:h nvim_create_autocmd) - desc = 'Document Highlighting', - callback = vim.lsp.buf.document_highlight, - }, - { - event = { 'CursorMoved', 'CursorMovedI', 'BufLeave' }, - desc = 'Document Highlighting Clear', - callback = vim.lsp.buf.clear_references, - }, - }, - }, - commands = { - Format = { - function() - vim.lsp.buf.format({ async = true }) - end, - cond = 'textDocument/formatting', - desc = 'Format file with LSP', - }, - ImportsOrganize = { - function() - vim.lsp.buf.code_action({ - context = { only = { 'source.organizeImports' } }, - apply = true, - }) - end, - cond = 'textDocument/codeAction', - desc = 'Organize Imports', - }, - ImportsRemove = { - function() - vim.lsp.buf.code_action({ - context = { only = { 'source.removeUnused' } }, - apply = true, - }) - end, - cond = 'textDocument/codeAction', - desc = 'Remove Unused Imports', - }, - FixAll = { - function() - vim.lsp.buf.code_action({ - context = { only = { 'source.fixAll' } }, - apply = true, - }) - end, - cond = 'textDocument/codeAction', - desc = 'Fix All fixable diagnostics', - }, - }, - capabilities = { - textDocument = { foldingRange = { dynamicRegistration = false, lineFoldingOnly = true } }, - workspace = { - didChangeWatchedFiles = vim.fn.has 'nvim-0.10' == 0 and { dynamicRegistration = true }, - }, - }, - config = { - bashls = { - settings = { bashIde = { highlightParsingErrors = true } }, - }, - }, - mappings = { - n = { - K = { vim.lsp.buf.hover, desc = 'Hover', cond = 'textDocument/hover' }, - gl = { vim.diagnostic.open_float, desc = 'Hover diagnostics' }, - ['le'] = { vim.diagnostic.open_float, desc = 'Hover diagnostics' }, - ['ld'] = { - function() - local ok, fzf = pcall(require, 'fzf-lua') - if not ok then - vim.lsp.buf.definition() - else - fzf.lsp_definitions({ - jump_to_single_result = true, - winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, - }) - end - end, - desc = 'Goto definition', - cond = 'textDocument/definition', - }, - gd = { - function() - local ok, fzf = pcall(require, 'fzf-lua') - if not ok then - vim.lsp.buf.definition() - else - fzf.lsp_definitions({ - jump_to_single_result = true, - winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, - }) - end - end, - desc = 'Goto definition', - cond = 'textDocument/definition', - }, - ['lf'] = { - function() - vim.lsp.buf.code_action({ - context = { only = { 'source.fixAll' } }, - apply = true, - }) - end, - desc = 'Fix All', - cond = 'textDocument/codeAction', - }, - ['lo'] = { - function() - vim.lsp.buf.code_action({ - context = { only = { 'source.organizeImports' } }, - apply = true, - }) - vim.lsp.buf.code_action({ context = { only = { 'source.removeUnused' } }, apply = true }) - end, - desc = 'Oraganize imports', - cond = 'textDocument/codeAction', - }, - ['li'] = { - function() - local ok, fzf = pcall(require, 'fzf-lua') - if not ok then - vim.lsp.buf.implementation() - else - fzf.lsp_implementations() - end - end, - desc = 'Goto implementation', - cond = 'textDocument/implementation', - }, - -- condition for only server with declaration capabilities - ['lD'] = { - function() - local ok, fzf = pcall(require, 'fzf-lua') - if not ok then - vim.lsp.buf.declaration() - else - fzf.lsp_declarations({ - jump_to_single_result = true, - winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, - }) - end - end, - desc = 'Goto Declaration', - cond = 'textDocument/declaration', - }, - ['lt'] = { - function() - local ok, fzf = pcall(require, 'fzf-lua') - if not ok then - vim.lsp.buf.type_definition() - else - fzf.lsp_typedefs() - end - end, - desc = 'Type definition', - cond = 'textDocument/typeDefinition', - }, - ['F'] = { - function() - vim.cmd [[EslintFixAll]] - end, - cond = function(client) - return client.name == 'eslint' - end, - }, - gr = { - function() - local ok, fzf = pcall(require, 'fzf-lua') - if not ok then - vim.lsp.buf.references() - else - fzf.lsp_references({ - jump_to_single_result = true, - winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, - }) - end - end, - desc = 'Goto references', - cond = 'textDocument/references', - }, - ['lR'] = { - function() - local ok, fzf = pcall(require, 'fzf-lua') - if not ok then - vim.lsp.buf.references() - else - fzf.lsp_references({ - jump_to_single_result = true, - winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, - }) - end - end, - desc = 'Goto references', - cond = 'textDocument/references', - }, - [']e'] = { - function() - vim.diagnostic.goto_next({ severity = vim.diagnostic.severity.ERROR }) - end, - desc = 'Goto Next Error', - }, - ['[e'] = { - function() - vim.diagnostic.goto_prev({ severity = vim.diagnostic.severity.ERROR }) - end, - desc = 'Goto Next Error', - }, - [']d'] = { - vim.diagnostic.goto_next, - desc = 'Goto Next diagnostic', - }, - ['[d'] = { - vim.diagnostic.goto_prev, - desc = 'Goto Next diagnostic', - }, - ['lw'] = { - function() - local ok, fzf = pcall(require, 'fzf-lua') - if not ok then - vim.lsp.buf.document_symbol() - else - fzf.lsp_document_symbols() - end - end, - desc = 'Document symbols', - cond = 'textDocument/documentSymbol', - }, - ['lW'] = { - function() - local ok, fzf = pcall(require, 'fzf-lua') - if not ok then - vim.lsp.buf.workspace_symbol() - else - fzf.lsp_workspace_symbols() - end - end, - desc = 'Workspace symbols', - cond = 'workspace/symbol', - }, - [''] = { - vim.lsp.buf.rename, - desc = 'Rename', - cond = 'textDocument/rename', - }, - ['lr'] = { - vim.lsp.buf.rename, - desc = 'Rename', - cond = 'textDocument/rename', - }, - ['la'] = { - function() - local ok, fzf = pcall(require, 'fzf-lua') - if not ok then - vim.lsp.buf.code_action() - else - fzf.lsp_code_actions() - end - end, - desc = 'Code actions', - cond = 'textDocument/codeAction', - }, - ['lI'] = { - function() - vim.cmd 'LspInfo' - end, - desc = 'LspInfo', - }, - -- condition with a full function with `client` and `bufnr` - ['uY'] = { - function() - require('astrolsp.toggles').buffer_semantic_tokens() - end, - desc = 'Toggle LSP semantic highlight (buffer)', - cond = function(client) - return client.server_capabilities.semanticTokensProvider and vim.lsp.semantic_tokens - end, - }, - ['uI'] = { - function() - require('astrolsp.toggles').buffer_inlay_hints() - end, - desc = 'Toggle LSP inlay highlight (buffer)', - cond = function(client) - return client.server_capabilities.inlayHintProvider and vim.lsp.inlay_hint - end, - }, - }, - i = { - [''] = { - vim.lsp.buf.signature_help, - desc = 'Signature help', - cond = 'textDocument/signatureHelp', - }, - }, - x = { - ['la'] = { - function() - local ok, fzf = pcall(require, 'fzf-lua') - if not ok then - vim.lsp.buf.code_action() - else - fzf.lsp_code_actions() - end - end, - desc = 'Code actions', - cond = 'textDocument/codeAction', - }, - }, - }, - handlers = { - function(server, opts) - local ok, cmp_nvim_lsp = pcall(require, 'cmp_nvim_lsp') - if ok then - opts.capabilities = cmp_nvim_lsp.default_capabilities(opts.capabilities) - end - require('lspconfig')[server].setup(opts) - end, - efm = false, - }, - -- A list like table of servers that should be setup, useful for enabling language servers not installed with Mason. - servers = { - 'gleam', - 'zls', - 'roc_ls', - 'nim_langserver' --[[, 'rust_analyzer' ]], - }, - on_attach = function(client, bufnr) - if client.supports_method 'textDocument/documentSymbol' then - require('nvim-navic').attach(client, bufnr) - end - end, -} - -return M diff --git a/.config/nvim/lua/plugins/config/autopairs.lua b/.config/nvim/lua/plugins/config/autopairs.lua deleted file mode 100644 index 1bbc1ca..0000000 --- a/.config/nvim/lua/plugins/config/autopairs.lua +++ /dev/null @@ -1,165 +0,0 @@ -local M = {} - -local function rule_add_spaces_between_paren() - local npairs = require 'nvim-autopairs' - local Rule = require 'nvim-autopairs.rule' - local cond = require 'nvim-autopairs.conds' - - local brackets = { { '(', ')' }, { '[', ']' }, { '{', '}' } } - npairs.add_rules({ - -- Rule for a pair with left-side ' ' and right side ' ' - Rule(' ', ' ') - -- Pair will only occur if the conditional function returns true - :with_pair(function(opts) - -- We are checking if we are inserting a space in (), [], or {} - local pair = opts.line:sub(opts.col - 1, opts.col) - return vim.tbl_contains({ - brackets[1][1] .. brackets[1][2], - brackets[2][1] .. brackets[2][2], - brackets[3][1] .. brackets[3][2], - }, pair) - end) - :with_move(cond.none()) - :with_cr(cond.none()) - -- We only want to delete the pair of spaces when the cursor is as such: ( | ) - :with_del(function(opts) - local col = vim.api.nvim_win_get_cursor(0)[2] - local context = opts.line:sub(col - 1, col + 2) - return vim.tbl_contains({ - brackets[1][1] .. ' ' .. brackets[1][2], - brackets[2][1] .. ' ' .. brackets[2][2], - brackets[3][1] .. ' ' .. brackets[3][2], - }, context) - end), - }) - -- For each pair of brackets we will add another rule - for _, bracket in pairs(brackets) do - npairs.add_rules({ - -- Each of these rules is for a pair with left-side '( ' and right-side ' )' for each bracket type - Rule(bracket[1] .. ' ', ' ' .. bracket[2]) - :with_pair(cond.none()) - :with_move(function(opts) - return opts.char == bracket[2] - end) - :with_del(cond.none()) - :use_key(bracket[2]) - -- Removes the trailing whitespace that can occur without this - :replace_map_cr(function(_) - return '2xiO' - end), - }) - end -end - -local function rule_add_space_on_equal() - local Rule = require 'nvim-autopairs.rule' - local cond = require 'nvim-autopairs.conds' - Rule('=', '') - :with_pair(cond.not_inside_quote()) - :with_pair(function(opts) - local last_char = opts.line:sub(opts.col - 1, opts.col - 1) - if last_char:match '[%w%=%s]' then - return true - end - return false - end) - :replace_endpair(function(opts) - local prev_2char = opts.line:sub(opts.col - 2, opts.col - 1) - local next_char = opts.line:sub(opts.col, opts.col) - next_char = next_char == ' ' and '' or ' ' - if prev_2char:match '%w$' then - return ' =' .. next_char - end - if prev_2char:match '%=$' then - return next_char - end - if prev_2char:match '=' then - return '=' .. next_char - end - return '' - end) - :set_end_pair_length(0) - :with_move(cond.none()) - :with_del(cond.none()) -end --- https://github.com/rstacruz/vim-closer/blob/master/autoload/closer.vim -local get_closing_for_line = function(line) - local i = -1 - local clo = '' - - while true do - i, _ = string.find(line, '[%(%)%{%}%[%]]', i + 1) - if i == nil then - break - end - local ch = string.sub(line, i, i) - local st = string.sub(clo, 1, 1) - - if ch == '{' then - clo = '}' .. clo - elseif ch == '}' then - if st ~= '}' then - return '' - end - clo = string.sub(clo, 2) - elseif ch == '(' then - clo = ')' .. clo - elseif ch == ')' then - if st ~= ')' then - return '' - end - clo = string.sub(clo, 2) - elseif ch == '[' then - clo = ']' .. clo - elseif ch == ']' then - if st ~= ']' then - return '' - end - clo = string.sub(clo, 2) - end - end - - return clo -end - -local function rule_expand_multiple_on_enter(autopairs) - local Rule = require 'nvim-autopairs.rule' - - autopairs.remove_rule '(' - autopairs.remove_rule '{' - autopairs.remove_rule '[' - - autopairs.add_rule(Rule('[%(%{%[]', '') - :use_regex(true) - :replace_endpair(function(opts) - return get_closing_for_line(opts.line) - end) - :end_wise(function(opts) - -- Do not endwise if there is no closing - return get_closing_for_line(opts.line) ~= '' - end)) -end - -function M.config(_, opts) - local options = vim.tbl_deep_extend('force', { - disable_filetype = { 'TelescopePrompt' }, - ignored_next_char = '[%w%.]', - check_ts = false, - map_c_w = true, - fast_wrap = {}, - }, opts) - local npairs = require 'nvim-autopairs' - npairs.setup(options) - - rule_add_spaces_between_paren() - rule_add_space_on_equal() - -- rule_expand_multiple_on_enter(npairs) - - local ok, cmp = pcall(require, 'cmp') - if ok then - local cmp_autopairs = require 'nvim-autopairs.completion.cmp' - cmp.event:on('confirm_done', cmp_autopairs.on_confirm_done()) - end -end - -return M diff --git a/.config/nvim/lua/plugins/config/cmp.lua b/.config/nvim/lua/plugins/config/cmp.lua deleted file mode 100644 index fe52b06..0000000 --- a/.config/nvim/lua/plugins/config/cmp.lua +++ /dev/null @@ -1,268 +0,0 @@ -local cmp = require 'cmp' -local types = require 'cmp.types' -local sources = require 'cmp.config.sources' -local compare = require 'cmp.config.compare' -local lspkind = require 'lspkind' -local snippet = 'luasnip' -local luasnip = require 'luasnip' - -local function feedkey(key, mode) - vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(key, true, true, true), mode, true) -end -local function has_words_before() - unpack = unpack or table.unpack - local line, col = unpack(vim.api.nvim_win_get_cursor(0)) - return col ~= 0 and vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]:sub(col, col):match '%s' == nil -end - -local function deprio(kind) - return function(e1, e2) - if e1:get_kind() == kind then - return false - end - if e2:get_kind() == kind then - return true - end - end -end - ---- detect if the current completion item is an emmet completion item ---- @param entry cmp.Entry ---- @return boolean -local function isEmmet(entry) - return ( - entry:get_kind() == require('cmp.types').lsp.CompletionItemKind.Text - or entry:get_kind() == require('cmp.types').lsp.CompletionItemKind.Snippet - ) - and ( - entry.source:get_debug_name() == 'nvim_lsp:emmet_language_server' - or entry.source:get_debug_name() == 'nvim_lsp:emmet_ls' - ) -end - -cmp.setup({ - snippet = { - expand = function(args) - luasnip.lsp_expand(args.body) - end, - }, - experimental = { ghost_text = false, native_menu = false }, - window = { completion = cmp.config.window.bordered(), documentation = cmp.config.window.bordered() }, - duplicates = { - nvim_lsp = 1, - lazydev = 1, - [snippet] = 1, - cmp_tabnine = 1, - buffer = 1, - path = 1, - }, - - mapping = { - [''] = cmp.mapping({ i = cmp.mapping.scroll_docs(-4) }), - [''] = cmp.mapping({ i = cmp.mapping.scroll_docs(4) }), - [''] = cmp.mapping.complete(), - [''] = cmp.mapping.close(), - [''] = cmp.mapping({ - i = cmp.mapping.confirm({ behavior = cmp.ConfirmBehavior.Replace, select = true }), - c = cmp.mapping.confirm({ behavior = cmp.ConfirmBehavior.Replace, select = false }), - }), - [''] = cmp.mapping({ - i = cmp.mapping.confirm({ behavior = cmp.ConfirmBehavior.Replace, select = true }), - c = cmp.mapping.confirm({ behavior = cmp.ConfirmBehavior.Replace, select = false }), - }), - [''] = cmp.mapping({ - i = function(fallback) - if cmp.visible() then - cmp.select_next_item({ behavior = cmp.SelectBehavior.Select }) - else - fallback() - end - end, - }), - [''] = cmp.mapping({ - i = function(fallback) - if cmp.visible() then - cmp.select_prev_item({ behavior = cmp.SelectBehavior.Select }) - else - fallback() - end - end, - }), - [''] = cmp.mapping({ - c = function() - if cmp.visible() then - cmp.select_next_item({ behavior = cmp.SelectBehavior.Select }) - else - feedkey('', 'n') - end - end, - i = function(fallback) - if cmp.visible() then - cmp.select_next_item({ behavior = cmp.SelectBehavior.Select }) - else - fallback() - end - end, - }), - [''] = cmp.mapping({ - c = function() - if cmp.visible() then - cmp.select_prev_item({ behavior = cmp.SelectBehavior.Select }) - else - feedkey('', 'n') - end - end, - i = function(fallback) - if cmp.visible() then - cmp.select_prev_item({ behavior = cmp.SelectBehavior.Select }) - else - fallback() - end - end, - }), - [''] = cmp.mapping.complete({ - config = { sources = { { name = snippet } } }, - }), - [''] = cmp.mapping.complete({ - config = { - sources = { - { - name = 'nvim_lsp', - entry_filter = function(entry) - return isEmmet(entry) - end, - }, - }, - }, - }), - [''] = cmp.mapping(function(fallback) - if cmp.visible() then - cmp.select_next_item() - -- elseif vim.snippet.active({ direction = 1 }) then - -- return 'lua vim.snippet.jump(1)' - -- vim.snippet.jump(1) - -- elseif vim.fn['vsnip#available'](1) == 1 then - -- feedkey('(vsnip-expand-or-jump)', '') - elseif luasnip.expand_or_jumpable() then - luasnip.expand_or_jump() - elseif has_words_before() then - cmp.complete() - else - fallback() - end - end, { 'i', 's' }), - - [''] = cmp.mapping(function() - if cmp.visible() then - cmp.select_prev_item() - elseif luasnip.jumpable(-1) then - luasnip.jump(-1) - -- elseif vim.snippet.active({ direction = -1 }) then - -- return 'lua vim.snippet.jump(-1)' - -- vim.snippet.jump(-1) - -- elseif vim.fn['vsnip#jumpable'](-1) == 1 then - -- feedkey('(vsnip-jump-prev)', '') - end - end, { 'i', 's' }), - }, - sources = sources({ - { - name = 'nvim_lsp', - priority = 100, - max_item_count = 20, - entry_filter = function(entry) - return not isEmmet(entry) - end, - }, - { name = 'lazydev', priority = 95 }, - { name = snippet, priority = 90 }, - { - name = 'buffer', - max_item_count = 10, - option = { - keyword_length = 2, - -- get_bufnrs = function() - -- local bufIsSmall = function(bufnr) - -- return vim.api.nvim_buf_line_count(bufnr) < 2000 - -- end - -- return vim.tbl_filter(bufIsSmall, vim.api.nvim_list_bufs()) - -- end, - }, - priority = 40, - }, - { - name = 'rg', - keyword_length = 3, - max_item_count = 10, - priority_weight = 50, - option = { - additional_arguments = '--smart-case --hidden', - set_filetype = true, - marker = ' ❰❰❰', - }, - -- entry_filter = function(entry) - -- return not entry.exact - -- end, - }, - -- { name = 'path', priority = 50 }, - { name = 'async_path', priority = 50, option = { trailing_slash = false } }, - { - name = 'look', - keyword_length = 5, - priority = 30, - option = { - convert_case = true, - loud = true, - --dict = '/usr/share/dict/words' - }, - }, - }), - sorting = { - priority_weight = 100, - comparators = { - deprio(types.lsp.CompletionItemKind.Text), - compare.exact, - compare.offset, - compare.score, - compare.length, - compare.recently_used, - compare.kind, - compare.locality, - compare.order, - }, - }, - ---@diagnostic disable-next-line: missing-fields - formatting = { - fields = { 'kind', 'abbr', 'menu' }, - format = lspkind.cmp_format({ - mode = 'symbol', - maxwidth = 50, - ellipsis_char = '...', - symbol_map = { Copilot = '' }, - }), - }, -}) -cmp.setup.cmdline(':', { - sources = sources({ - { - name = 'cmdline', - option = { - ignore_cmds = { 'Man', '!', 'find', 'fin' }, - }, - }, - { name = 'path' }, - }), - matching = { disallow_symbol_nonprefix_matching = false }, - mapping = cmp.mapping.preset.cmdline(), - formatting = { fields = { 'abbr' } }, - window = { completion = cmp.config.window.bordered({ col_offset = 0 }) }, -}) - -cmp.setup.cmdline({ '/', '?' }, { - sources = sources({ - { name = 'buffer' }, - }), - mapping = cmp.mapping.preset.cmdline(), - formatting = { fields = { 'abbr' } }, - window = { completion = cmp.config.window.bordered({ col_offset = 0 }) }, -}) diff --git a/.config/nvim/lua/plugins/config/conform.lua b/.config/nvim/lua/plugins/config/conform.lua deleted file mode 100644 index 19ff5fa..0000000 --- a/.config/nvim/lua/plugins/config/conform.lua +++ /dev/null @@ -1,104 +0,0 @@ -local prettier = { 'prettierd', 'prettier', stop_after_first = true } -local slow_format_filetypes = {} - ----@param bufnr integer ----@param ... string ----@return string -local function first(bufnr, ...) - local conform = require 'conform' - for i = 1, select('#', ...) do - local formatter = select(i, ...) - if conform.get_formatter_info(formatter, bufnr).available then - return formatter - end - end - return select(1, ...) -end - -local function prettier_eslint(bufnr) - return { first(bufnr, 'prettierd', 'prettier'), 'eslint_d' } -end - -require('conform').setup({ - -- Define your formatters - formatters_by_ft = { - sh = { 'shfmt' }, - lua = { 'stylua' }, - bash = { 'shfmt' }, - c = { 'clang-format' }, - cpp = { 'clang-format' }, - go = function(bufnr) - return { 'goimports', first(bufnr, 'gofumpt', 'gofmt') } - end, - fish = { 'fish_indent' }, - css = prettier, - html = prettier, - jsonc = prettier, - json = prettier, - json5 = prettier, - less = prettier, - markdown = prettier, - sass = prettier, - scss = prettier, - astro = prettier_eslint, - javascript = prettier_eslint, - javascriptreact = prettier_eslint, - typescript = prettier_eslint, - typescriptreact = prettier_eslint, - svelte = prettier_eslint, - vue = prettier_eslint, - nim = { 'nimpretty' }, - zig = { 'zigfmt' }, - php = function(bufnr) - return { first(bufnr, 'pint', 'php-cs-fixer', 'phpcbf') } - end, - blade = { 'blade-formatter' }, - gleam = { 'gleam' }, - -- You can use a function here to determine the formatters dynamically - python = function(bufnr) - if require('conform').get_formatter_info('ruff_format', bufnr).available then - return { 'ruff_format', 'ruff_fix', 'ruff_organize_imports' } - else - return { 'isort', 'black' } - end - end, - -- Use the "_" filetype to run formatters on filetypes that don't - -- have other formatters configured. - ['_'] = { 'trim_whitespace', 'trim_newlines' }, - }, - default_format_opts = { - lsp_format = 'fallback', - }, - -- Set up format-on-save - -- format_on_save = { timeout_ms = 500, lsp_fallback = true }, - format_on_save = function(bufnr) - -- Disable autoformat for files in a certain path - local bufname = vim.api.nvim_buf_get_name(bufnr) - if bufname:match '/node_modules/' then - return - end - if slow_format_filetypes[vim.bo[bufnr].filetype] then - return - end - local function on_format(err) - if err and err:match 'timeout$' then - slow_format_filetypes[vim.bo[bufnr].filetype] = true - end - end - - return { timeout_ms = 200, lsp_fallback = true }, on_format - end, - - format_after_save = function(bufnr) - if not slow_format_filetypes[vim.bo[bufnr].filetype] then - return - end - return { lsp_fallback = true } - end, - -- Customize formatters - formatters = { - shfmt = { - prepend_args = { '-i', '2' }, - }, - }, -}) diff --git a/.config/nvim/lua/plugins/config/dap.lua b/.config/nvim/lua/plugins/config/dap.lua deleted file mode 100644 index 8c3a006..0000000 --- a/.config/nvim/lua/plugins/config/dap.lua +++ /dev/null @@ -1,149 +0,0 @@ -local dap, dapui = require 'dap', require 'dapui' -local dap_icons = { - Stopped = { '󰁕 ', 'DiagnosticWarn', 'DapStoppedLine' }, - Breakpoint = ' ', - BreakpointCondition = ' ', - BreakpointRejected = { ' ', 'DiagnosticError' }, - LogPoint = '.>', -} -vim.api.nvim_set_hl(0, 'DapStoppedLine', { default = true, link = 'Visual' }) - -for name, sign in pairs(dap_icons) do - sign = type(sign) == 'table' and sign or { sign } - vim.fn.sign_define( - 'Dap' .. name, - { text = sign[1], texthl = sign[2] or 'DiagnosticInfo', linehl = sign[3], numhl = sign[3] } - ) -end -require('persistent-breakpoints').setup({ - load_breakpoints_event = { 'BufReadPost' }, -}) ----@diagnostic disable-next-line: missing-fields --- require('dap-vscode-js').setup({ --- debugger_path = vim.fn.stdpath 'data' .. '/lazy/vscode-js-debug', --- adapters = { 'pwa-node', 'pwa-chrome', 'pwa-msedge', 'node-terminal', 'pwa-extensionHost' }, -- which adapters to register in nvim-dap --- }) -dap.adapters.bashdb = { - type = 'executable', - command = vim.fn.stdpath 'data' .. '/mason/packages/bash-debug-adapter/bash-debug-adapter', - name = 'bashdb', -} -dap.adapters.mix_task = { - type = 'executable', - command = require('mason-registry').get_package('elixir-ls'):get_install_path() .. '/debug_adapter.sh', -- debugger.bat for windows - args = {}, -} --- setup dap config by VsCode launch.json file -local vscode = require 'dap.ext.vscode' -local json = require 'plenary.json' -vscode.json_decode = function(str) - return vim.json.decode(json.json_strip_comments(str, { whitespace = true })) -end -if not dap.adapters['pwa-node'] then - require('dap').adapters['pwa-node'] = { - type = 'server', - host = 'localhost', - port = '${port}', - executable = { - command = require('mason-registry').get_package('js-debug-adapter'):get_install_path() .. '/js-debug-adapter', - args = { - -- require('mason-registry').get_package('js-debug-adapter'):get_install_path() - -- .. '/js-debug/src/dapDebugServer.js', - '${port}', - }, - }, - } -end -if not dap.adapters['node'] then - dap.adapters['node'] = function(cb, config) - if config.type == 'node' then - config.type = 'pwa-node' - end - local nativeAdapter = dap.adapters['pwa-node'] - if type(nativeAdapter) == 'function' then - nativeAdapter(cb, config) - else - cb(nativeAdapter) - end - end -end - -local js_filetypes = { 'typescript', 'javascript', 'typescriptreact', 'javascriptreact' } - -vscode.type_to_filetypes['node'] = js_filetypes -vscode.type_to_filetypes['pwa-node'] = js_filetypes - -for _, language in ipairs(js_filetypes) do - if not dap.configurations[language] then - dap.configurations[language] = { - { - type = 'pwa-node', - request = 'launch', - name = 'Launch file', - program = '${file}', - cwd = '${workspaceFolder}', - }, - { - type = 'pwa-node', - request = 'attach', - name = 'Attach', - processId = require('dap.utils').pick_process, - cwd = '${workspaceFolder}', - }, - } - end -end - -dap.adapters.php = { - type = 'executable', - command = require('mason-registry').get_package('php-debug-adapter'):get_install_path() .. 'php-debug-adapter', - -- command = 'node', - -- args = { require('mason-registry').get_package('php-debug-adapter'):get_install_path() .. '/out/phpDebug.js' } -} - -dap.configurations.php = { - { - type = 'php', - request = 'launch', - name = 'Listen for Xdebug', - port = 9000, - }, -} - -dap.configurations.elixir = { - { - type = 'mix_task', - name = 'mix (Default task)', - request = 'launch', - projectDir = '${workspaceRoot}', - }, - { - type = 'mix_task', - name = 'mix test', - task = 'test', - taskArgs = { '--trace' }, - request = 'launch', - startApps = true, -- for Phoenix projects - projectDir = '${workspaceFolder}', - requireFiles = { - 'test/**/test_helper.exs', - 'test/**/*_test.exs', - }, - }, -} -require('dap-go').setup() -dapui.setup() -require('nvim-dap-virtual-text').setup({}) - -dap.listeners.before.attach.dapui_config = function() - dapui.open() -end -dap.listeners.before.launch.dapui_config = function() - dapui.open() -end -dap.listeners.before.event_terminated.dapui_config = function() - dapui.close() -end -dap.listeners.before.event_exited.dapui_config = function() - dapui.close() -end diff --git a/.config/nvim/lua/plugins/config/dial.lua b/.config/nvim/lua/plugins/config/dial.lua deleted file mode 100644 index b7438a3..0000000 --- a/.config/nvim/lua/plugins/config/dial.lua +++ /dev/null @@ -1,205 +0,0 @@ -local M = {} ----@type table> -M.dials_by_ft = {} - ----@param increment boolean ----@param g? boolean -function M.dial(increment, g) - local mode = vim.fn.mode(true) - -- Use visual commands for VISUAL 'v', VISUAL LINE 'V' and VISUAL BLOCK '\22' - local is_visual = mode == 'v' or mode == 'V' or mode == '\22' - local func = (increment and 'inc' or 'dec') .. (g and '_g' or '_') .. (is_visual and 'visual' or 'normal') - local group = M.dials_by_ft[vim.bo.filetype] or 'default' - return require('dial.map')[func](group) -end - -M.keys = { - { - '', - function() - return M.dial(true) - end, - expr = true, - desc = 'Increment', - mode = { 'n', 'v' }, - }, - { - '', - function() - return M.dial(false) - end, - expr = true, - desc = 'Decrement', - mode = { 'n', 'v' }, - }, - { - 'g', - function() - return M.dial(true, true) - end, - expr = true, - desc = 'Increment', - mode = { 'n', 'v' }, - }, - { - 'g', - function() - return M.dial(false, true) - end, - expr = true, - desc = 'Decrement', - mode = { 'n', 'v' }, - }, -} - -function M.config() - local augend = require 'dial.augend' - - local logical_alias = augend.constant.new({ - elements = { '&&', '||' }, - word = false, - cyclic = true, - }) - - local ordinal_numbers = augend.constant.new({ - -- elements through which we cycle. When we increment, we go down - -- On decrement we go up - elements = { - 'first', - 'second', - 'third', - 'fourth', - 'fifth', - 'sixth', - 'seventh', - 'eighth', - 'ninth', - 'tenth', - }, - -- if true, it only matches strings with word boundary. firstDate wouldn't work for example - word = false, - -- do we cycle back and forth (tenth to first on increment, first to tenth on decrement). - -- Otherwise nothing will happen when there are no further values - cyclic = true, - }) - - local weekdays = augend.constant.new({ - elements = { - 'Monday', - 'Tuesday', - 'Wednesday', - 'Thursday', - 'Friday', - 'Saturday', - 'Sunday', - }, - word = true, - cyclic = true, - }) - - local months = augend.constant.new({ - elements = { - 'January', - 'February', - 'March', - 'April', - 'May', - 'June', - 'July', - 'August', - 'September', - 'October', - 'November', - 'December', - }, - word = true, - cyclic = true, - }) - - local capitalized_boolean = augend.constant.new({ - elements = { - 'True', - 'False', - }, - word = true, - cyclic = true, - }) - - local opts = { - dials_by_ft = { - lua = 'lua', - json = 'json', - jsonc = 'json', - json5 = 'json', - markdown = 'markdown', - python = 'python', - css = 'css', - sass = 'css', - scss = 'css', - javascript = 'typescript', - javascriptreact = 'typescript', - typescript = 'typescript', - typescriptreact = 'typescript', - }, - groups = { - default = { - augend.integer.alias.decimal, -- nonnegative decimal number (0, 1, 2, 3, ...) - augend.integer.alias.hex, -- nonnegative hex number (0x01, 0x1a1f, etc.) - augend.date.alias['%Y/%m/%d'], -- date (2022/02/19, etc.) - }, - typescript = { - augend.integer.alias.decimal, -- nonnegative and negative decimal number - augend.constant.alias.bool, -- boolean value (true <-> false) - logical_alias, - augend.constant.new({ elements = { 'let', 'const' } }), - ordinal_numbers, - weekdays, - months, - }, - css = { - augend.integer.alias.decimal, -- nonnegative and negative decimal number - augend.hexcolor.new({ - case = 'lower', - }), - augend.hexcolor.new({ - case = 'upper', - }), - }, - markdown = { - augend.misc.alias.markdown_header, - ordinal_numbers, - weekdays, - months, - }, - json = { - augend.integer.alias.decimal, -- nonnegative and negative decimal number - augend.constant.alias.bool, -- boolean value (true <-> false) - augend.semver.alias.semver, -- versioning (v1.1.2) - }, - lua = { - augend.integer.alias.decimal, -- nonnegative and negative decimal number - augend.constant.alias.bool, -- boolean value (true <-> false) - augend.constant.new({ - elements = { 'and', 'or' }, - word = true, -- if false, "sand" is incremented into "sor", "doctor" into "doctand", etc. - cyclic = true, -- "or" is incremented into "and". - }), - ordinal_numbers, - weekdays, - months, - }, - python = { - augend.integer.alias.decimal, -- nonnegative and negative decimal number - capitalized_boolean, - logical_alias, - ordinal_numbers, - weekdays, - months, - }, - }, - } - require('dial.config').augends:register_group(opts.groups) - M.dials_by_ft = opts.dials_by_ft -end - -return M diff --git a/.config/nvim/lua/plugins/config/fzf.lua b/.config/nvim/lua/plugins/config/fzf.lua deleted file mode 100644 index a150dcb..0000000 --- a/.config/nvim/lua/plugins/config/fzf.lua +++ /dev/null @@ -1,376 +0,0 @@ -local fzf = require 'fzf-lua' -local actions = require 'fzf-lua.actions' -local utils = require 'fzf-lua.utils' - -local function hl_validate(hl) - return not utils.is_hl_cleared(hl) and hl or nil -end - -local rg_cmd = - 'rg --files -l ".*" --follow --color=never --sortr=modified -g "!.git/" -g "!*.png" -g "!node_modules/" -g "!*.jpeg" -g "!*.jpg" -g "!*.ico" -g "!*.exe" -g "!*.out"' - -local m_keys = { - ['alt-enter'] = actions.file_tabedit, - ['ctrl-t'] = actions.file_tabedit, - ['ctrl-x'] = actions.file_split, - -- ['ctrl-q'] = actions.file_edit_or_qf, -} --- calling `setup` is optional for customization -fzf.setup({ - defaults = { formatter = { 'path.filename_first', 2 } }, - fzf_opts = { - ['--layout'] = 'reverse', - ['--info'] = 'inline-right', - -- ['--tiebreak'] = 'end', - }, - winopts = { preview = { default = 'bat' } }, - hls = { - normal = hl_validate 'TelescopeNormal', - border = hl_validate 'TelescopeBorder', - title = hl_validate 'TelescopePromptTitle', - help_normal = hl_validate 'TelescopeNormal', - help_border = hl_validate 'TelescopeBorder', - preview_normal = hl_validate 'TelescopeNormal', - preview_border = hl_validate 'TelescopeBorder', - preview_title = hl_validate 'TelescopePreviewTitle', - -- builtin preview only - cursor = hl_validate 'Cursor', - cursorline = hl_validate 'TelescopeSelection', - cursorlinenr = hl_validate 'TelescopeSelection', - search = hl_validate 'IncSearch', - }, - keymap = { - builtin = { - true, - [''] = 'hide', - }, - fzf = { - ['ctrl-j'] = 'down', - ['ctrl-k'] = 'up', - ['ctrl-f'] = 'half-page-down', - ['ctrl-b'] = 'half-page-up', - ['alt-a'] = 'toggle-all', - ['alt-p'] = 'toggle-preview', - ['pgdn'] = 'preview-page-down', - ['pgup'] = 'preview-page-up', - ['alt-j'] = 'preview-down', - ['alt-k'] = 'preview-up', - ['shift-down'] = 'preview-page-down', - ['shift-up'] = 'preview-page-up', - ['ctrl-q'] = 'select-all+accept', - }, - }, - icons = { - ['?'] = { icon = '?', color = 'magenta' }, - ['M'] = { icon = '★', color = 'red' }, - ['D'] = { icon = '✗', color = 'red' }, - ['A'] = { icon = '+', color = 'green' }, - }, - files = { - fzf_opts = { - ['--layout'] = 'reverse', - -- ['--tiebreak'] = 'end', - ['--tiebreak'] = 'length', - }, - winopts = { - height = 0.55, - width = 0.65, - row = 0.52, - col = 0.47, - preview = { - ---@type 'wrap'|'nowrap' - wrap = 'nowrap', - ---@type 'hidden'|'nohidden' - hidden = 'hidden', - }, - }, - actions = m_keys, - }, - git = { - files = { - cmd = 'git ls-files --exclude-standard --cached --others', -- '--others' is used to show untracked files - actions = m_keys, - winopts = { - height = 0.55, - width = 0.65, - row = 0.52, - col = 0.47, - }, - previewer = false, - }, - status = { - actions = m_keys, - prompt = ' ❯ ', - }, - bcommits = { - actions = m_keys, - winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, - }, - commits = { - actions = m_keys, - winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, - }, - branches = { - winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, - cmd = "git branch --all --color | sed 's#remotes/origin/##g'", - cmd_add = { 'git', 'checkout', '-b' }, - }, - }, - buffers = { - ignore_current_buffer = true, - winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, - actions = vim.tbl_extend('force', m_keys, { - ['ctrl-d'] = actions.buf_delete, - ['ctrl-x'] = actions.buf_split, - ['ctrl-v'] = actions.buf_vsplit, - ['ctrl-q'] = actions.buf_edit_or_qf, - }), - }, - keymaps = { winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } } }, - helptags = { winopts = { height = 0.55, width = 1.0, row = 1.0, preview = { horizontal = 'left:40%' } } }, - grep = { - winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, - actions = m_keys, - rg_glob = true, - glob_flah = '--glob', - glob_separator = '%s%-%-', - }, - blines = { - actions = m_keys, - no_term_buffers = false, - winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, - }, - lsp = { - definitions = { - jump_to_single_result = true, - actions = m_keys, - }, - declarations = { - jump_to_single_result = true, - actions = m_keys, - }, - references = { - ignore_current_line = true, - actions = m_keys, - }, - symbols = { - actions = m_keys, - winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, - }, - finder = { - actions = m_keys, - winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, - }, - code_actions = { - actions = m_keys, - winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, - }, - }, - diagnostics = { - actions = m_keys, - winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, - }, - lines = { actions = m_keys }, -}) -local ok_dressing, _ = pcall(require, 'dressing') -if not ok_dressing then - fzf.register_ui_select() -end - -local function fzf_create_file() - local fzf = require 'fzf-lua' - local path = require 'fzf-lua.path' - local uv = vim.uv or vim.loop - local cmd = 'fd -t d . ' .. uv.cwd() - local function get_full_path(selected) - if #selected < 1 then - return - end - local entry = path.entry_to_file(selected[1], { cwd = uv.cwd() }) - if entry.path == '' then - return - end - - local fullpath = entry.path or entry.uri and entry.uri:match '^%a+://(.*)' - if not path.is_absolute(fullpath) then - fullpath = path.join({ uv.cwd(), fullpath }) - end - return fullpath - end - - --- This will create a file in the selected directory - ---@param split_dir ?"e" | "vs" | "sp" | "tabe" Default is "e" - ---@return function - local function perform_action(split_dir) - split_dir = split_dir or 'e' - return function(selected) - local fullpath = get_full_path(selected) - vim.ui.input({ prompt = 'File Name: ' }, function(name) - if name == nil then - return - end - vim.cmd(string.format('%s %s%s', split_dir, fullpath, name)) - vim.cmd 'w ++p' - end) - end - end - - fzf.fzf_exec(cmd, { - defaults = {}, - prompt = 'Create> ', - cwd = uv.cwd(), - cwd_prompt_shorten_len = 32, - cwd_prompt_shorten_val = 1, - fzf_opts = { - ['--tiebreak'] = 'end', - ['--preview-window'] = 'nohidden,50%', - ['--preview'] = { - type = 'cmd', - fn = function(selected) - local fullpath = get_full_path(selected) - local ls_cmd = 'command ls --color -hsv1F --group-directories-first' - local eza_cmd = - 'eza -al --color=always --icons=always --group-directories-first --no-user --no-permissions --no-time' - return string.format('%s %s', vim.fn.executable 'eza' == 1 and eza_cmd or ls_cmd, fullpath) - end, - }, - }, - fn_transform = function(x) - return fzf.make_entry.file(x, { file_icons = true, color_icons = true, cwd = uv.cwd() }) - end, - actions = { - ['default'] = perform_action(), - ['ctrl-x'] = perform_action 'sp', - ['ctrl-v'] = perform_action 'vs', - ['ctrl-t'] = perform_action 'tabe', - }, - }) -end - -local function project_files(default_opts) - local opts = vim.tbl_extend('force', { - fzf_opts = { - ['--layout'] = 'reverse', - ['--info'] = 'inline-right', - ['--tiebreak'] = 'index', - }, - }, default_opts or {}) - local fzf = require 'fzf-lua' - if vim.b.gitsigns_head then - -- Either use one of the following .local/bin/myscripts/sort_file.rs or .local/bin/myscripts/sorting_filev3.cpp - -- compile and then add to `PATH` - --`sort_files` is a program that sorts files based on modified time, recently modified files will be shown first - if vim.fn.executable 'sort_files' == 1 then - opts.cmd = 'git ls-files --exclude-standard --cached --others | sort_files' -- '--others' is used to show untracked files - else - vim.cmd 'echohl WarningMsg | echo "`sort_files` not found in `PATH`. Please compile the program" | echohl None' - end - fzf.git_files(opts) - else - opts.cmd = rg_cmd - fzf.files(opts) - end -end - -local keys = { - [''] = { project_files, { desc = 'Git [F]iles' } }, - ['ff'] = { - function() - fzf.files({ - cmd = rg_cmd, - fzf_opts = { - ['--layout'] = 'reverse', - ['--info'] = 'inline-right', - ['--tiebreak'] = 'index', - }, - }) - end, - { desc = '[F]iles' }, - }, - ['fr'] = { fzf.resume, { desc = '[R]esume' } }, - ['fs'] = { fzf.live_grep_native, { desc = '[S]earch(Project)' } }, - ['fc'] = { fzf_create_file, { desc = 'Create File' } }, - ['fS'] = { - function() - fzf.grep_curbuf({ winopts = { preview = { layout = 'vertical', { vertical = 'up:60%' } } } }) - end, - { desc = '[S]earch Current Buffer' }, - }, - ['fw'] = { fzf.grep_cword, { desc = '[W]ord under cursor' } }, - ['fW'] = { fzf.grep_cWORD, { desc = '[W]ord under cursor' } }, - ['fo'] = { - function() - fzf.oldfiles({ path_shorten = true }) - end, - { desc = '[O]ld Files' }, - }, - ['f/'] = { - function() - fzf.lgrep_curbuf({ - prompt = 'Buffer❫ ', - }) - end, - { desc = 'Grep buffer' }, - }, - ['*'] = { - function() - fzf.grep_curbuf({ - prompt = 'Buffer❫ ', - search = vim.fn.expand '', - }) - end, - { desc = 'Grep buffer with cword' }, - }, - ['fb'] = { fzf.buffers, { desc = '[B]uffers' } }, - ['fz'] = { fzf.spell_suggest, { desc = '[S]pelling' } }, - ['fk'] = { fzf.keymaps, { desc = '[K]eymaps' } }, - ['fh'] = { fzf.help_tags, { desc = '[H]elp Tags' } }, - ['fD'] = { fzf.diagnostics_document, { desc = '[D]iagnostics' } }, - ['fd'] = { - function() - fzf.files({ - cwd = vim.fn.expand '~/Documents/dotfiles', - cmd = rg_cmd .. ' --hidden', - fzf_opts = { - ['--layout'] = 'reverse', - ['--info'] = 'inline-right', - ['--tiebreak'] = 'index', - }, - }) - end, - { desc = '[D]otfiles' }, - }, - ['fn'] = { - function() - fzf.files({ - cwd = vim.fn.stdpath 'config', - cmd = rg_cmd, - fzf_opts = { - ['--layout'] = 'reverse', - ['--info'] = 'inline-right', - ['--tiebreak'] = 'index', - }, - }) - end, - { desc = '[N]eovim Config' }, - }, - ['fg'] = { fzf.git_status, { desc = '[S]tatus' } }, - ['gt'] = { fzf.git_status, { desc = '[S]tatus' } }, - ['gS'] = { fzf.git_stash, { desc = 'Stash' } }, - ['gb'] = { fzf.git_branches, { desc = '[B]ranches' } }, - ['gc'] = { fzf.git_commits, { desc = '[C]ommits' } }, - ['gC'] = { fzf.git_bcommits, { desc = '[B]ranch Commits' } }, -} - -vim.keymap.set('v', 'fw', fzf.grep_visual, { desc = 'Selection' }) -vim.keymap.set('i', '', fzf.complete_bline, { desc = 'Complete bline', silent = true, noremap = true }) -vim.keymap.set('i', '', fzf.complete_line, { desc = 'Complete line', silent = true, noremap = true }) -vim.keymap.set('i', '', fzf.complete_path, { desc = 'Complete path', silent = true, noremap = true }) -for key, value in pairs(keys) do - if value[1] == nil then - vim.print(key .. ' is nil') - goto continue - end - vim.keymap.set('n', key, value[1], vim.tbl_extend('force', { noremap = true, silent = true }, value[2] or {})) - ::continue:: -end diff --git a/.config/nvim/lua/plugins/config/heirline.lua b/.config/nvim/lua/plugins/config/heirline.lua deleted file mode 100644 index 2af74d9..0000000 --- a/.config/nvim/lua/plugins/config/heirline.lua +++ /dev/null @@ -1,174 +0,0 @@ ----@diagnostic disable: missing-fields -local heirline = require 'heirline' -local lib = require 'heirline-components.all' -local hl = require 'heirline-components.core.hl' -local utils = require 'heirline.utils' -local conditions = require 'heirline.conditions' - -local FileNameBlock = { - -- let's first set up some attributes needed by this component and its children - init = function(self) - self.filename = vim.api.nvim_buf_get_name(0) - end, -} --- We can now define some children separately and add them later - -local FileIcon = { - init = function(self) - local filename = self.filename - local extension = vim.fn.fnamemodify(filename, ':e') - self.icon, self.icon_color = require('nvim-web-devicons').get_icon_color(filename, extension, { default = true }) - end, - provider = function(self) - return self.icon and (self.icon .. ' ') - end, - hl = function(self) - return { fg = self.icon_color } - end, -} - -local FileName = { - provider = function(self) - -- first, trim the pattern relative to the current directory. For other - -- options, see :h filename-modifers - local filename = vim.fn.fnamemodify(self.filename, ':.') - if filename == '' then - return '[No Name]' - end - -- now, if the filename would occupy more than 1/4th of the available - -- space, we trim the file path to its initials - -- See Flexible Components section below for dynamic truncation - if not conditions.width_percent_below(#filename, 0.25) then - filename = vim.fn.pathshorten(filename) - end - return filename - end, - hl = { fg = utils.get_highlight('Directory').fg }, -} - -local FileFlags = { - { - condition = function() - return vim.bo.modified - end, - provider = '[+]', - hl = { fg = '#73d936' }, - }, - { - condition = function() - return not vim.bo.modifiable or vim.bo.readonly - end, - provider = '', - hl = { fg = '#cc8c3c' }, - }, -} - --- Now, let's say that we want the filename color to change if the buffer is --- modified. Of course, we could do that directly using the FileName.hl field, --- but we'll see how easy it is to alter existing components using a "modifier" --- component - -local FileNameModifer = { - hl = function() - if vim.bo.modified then - -- use `force` because we need to override the child's hl foreground - return { fg = 'cyan', bold = true, force = true } - end - end, -} - --- let's add the children to our FileNameBlock component -FileNameBlock = utils.insert( - FileNameBlock, - -- FileIcon, - utils.insert(FileNameModifer, FileName), -- a new table where FileName is a child of FileNameModifier - FileFlags, - { provider = '%<' } -- this means that the statusline is cut here when there's not enough space -) --- Setup -vim.opt.laststatus = 3 -lib.init.subscribe_to_events() -heirline.load_colors(lib.hl.get_colors()) -heirline.setup({ - opts = { - disable_winbar_cb = function(args) -- We do this to avoid showing it on the greeter. - local is_disabled = not require('heirline-components.buffer').is_valid(args.buf) - or lib.condition.buffer_matches({ - buftype = { 'terminal', 'prompt', 'nofile', 'help', 'quickfix' }, - filetype = { 'NvimTree', 'neo%-tree', 'dashboard', 'Outline', 'aerial' }, - }, args.buf) - return is_disabled - end, - }, - tabline = { -- UI upper bar - lib.component.tabline_conditional_padding(), - lib.component.tabline_buffers({ - hl = function(self) - local tab_type = self.tab_type - if self._show_picker and self.tab_type ~= 'buffer_active' then - tab_type = 'buffer_visible' - end - if tab_type == 'buffer_active' then - -- tokyonight - -- local fg = '#7ca1f2' - -- local bg = '#393d56' - -- rose-pine - local fg = '#f2e9e1' - local bg = '#214655' - -- gruber-darker - -- local fg = '#f2e9e1' - -- local bg = '#806a4d' - return vim.tbl_extend('force', hl.get_attributes(tab_type), { fg = fg, bg = bg }) - else - return hl.get_attributes(tab_type) - end - end, - }), - lib.component.fill(), - lib.component.tabline_tabpages({}), - }, - winbar = { -- UI breadcrumbs bar - init = function(self) - self.bufnr = vim.api.nvim_get_current_buf() - end, - -- Regular winbar - -- lib.component.neotree(), - -- lib.component.compiler_play(), - -- lib.component.fill(), - { - hl = hl.get_attributes('winbar', true), - condition = function() - return require('nvim-navic').is_available() - end, - provider = function() - return require('nvim-navic').get_location({ highlight = true }) - end, - update = 'CursorMoved', - }, - -- lib.component.fill(), - -- lib.component.compiler_redo(), - -- lib.component.aerial(), - }, - -- statuscolumn = { -- UI left column - -- init = function(self) - -- self.bufnr = vim.api.nvim_get_current_buf() - -- end, - -- lib.component.foldcolumn(), - -- lib.component.numbercolumn(), - -- lib.component.signcolumn(), - -- } or nil, - statusline = { -- UI statusbar - hl = { fg = 'fg', bg = 'bg' }, - lib.component.mode(), - lib.component.git_branch(), - FileNameBlock, - lib.component.file_info(), - lib.component.git_diff(), - lib.component.diagnostics(), - lib.component.fill(), - lib.component.fill(), - lib.component.lsp(), - lib.component.nav(), - lib.component.mode({ surround = { separator = 'right' } }), - }, -}) diff --git a/.config/nvim/lua/plugins/config/lualine.lua b/.config/nvim/lua/plugins/config/lualine.lua deleted file mode 100644 index d962854..0000000 --- a/.config/nvim/lua/plugins/config/lualine.lua +++ /dev/null @@ -1,192 +0,0 @@ -local conditions = { - buffer_not_empty = function() - if vim.opt.filetype._value == 'toggleterm' then - return false - end - return vim.fn.empty(vim.fn.expand '%:t') ~= 1 - end, - hide_in_width = function() - return vim.fn.winwidth(0) > 80 - end, - lsp_active = function() - return vim.fn.winwidth(0) > 80 and next(vim.lsp.get_clients({ bufnr = 0 })) ~= nil - end, -} -local function servers_attached() - local msg = 'None' - local clients = vim - .iter(vim.lsp.get_clients({ bufnr = 0 })) - :map(function(client) - return client.name - end) - :flatten() - :join ',' - return clients == '' and msg or clients -end - -local navic = require 'nvim-navic' -local config = { - options = { - globalstatus = true, - component_separators = '', - section_separators = '', - theme = { - normal = { c = { bg = '#181818', fg = '#303540', blend = 100 } }, - inactive = { c = { bg = '#101010', fg = '#303540' } }, - }, - }, - sections = { - lualine_a = {}, - lualine_b = {}, - lualine_y = {}, - lualine_z = {}, - lualine_c = {}, - lualine_x = {}, - }, - inactive_sections = { - lualine_a = {}, - lualine_v = {}, - lualine_y = {}, - lualine_z = {}, - lualine_c = {}, - lualine_x = {}, - }, - tabline = { - lualine_a = {}, - lualine_v = {}, - lualine_y = {}, - lualine_z = {}, - lualine_c = {}, - lualine_x = {}, - }, - - winbar = { - lualine_c = { - { - 'navic', - ---@type "static"| "dynamic"| nil - color_correction = nil, - navic_opts = nil, - }, - }, - }, - inactive_winbar = { - lualine_c = { - { - 'filename', - path = 1, - condition = conditions.buffer_not_empty, - color = { fg = '#96a6c8', bg = '#181818', gui = 'bold,italic' }, - }, - }, - }, - extensions = { 'lazy', 'neo-tree', 'quickfix', 'toggleterm', 'man' }, -} -local function ins_left(component) - table.insert(config.sections.lualine_c, component) -end -local function ins_right(component) - table.insert(config.sections.lualine_x, component) -end -local function ins_left_tab(component) - table.insert(config.tabline.lualine_c, component) -end -local function ins_right_tab(component) - table.insert(config.tabline.lualine_x, component) -end -ins_left_tab({ - 'buffers', - buffers_color = { - -- Same values as the general color option can be used here. - active = { fg = '#96a6c8', bg = '#303540' }, -- Color for active tab. - inactive = { fg = '#52494e', bg = '#181818' }, -- Color for inactive tab. - }, -}) -ins_left_tab '%=' -ins_right_tab({ - 'tabs', - tabs_color = { - -- Same values as the general color option can be used here. - active = { fg = '#96a6c8', bg = '#303540' }, -- Color for active tab. - inactive = { fg = '#52494e', bg = '#181818' }, -- Color for inactive tab. - }, -}) -ins_left({ - 'filetype', - icon_only = true, - condition = conditions.buffer_not_empty, - left_padding = 0, -}) -ins_left({ - 'filename', - path = 1, - -- shorting_target = 40, - condition = conditions.buffer_not_empty, - color = { fg = '#96a6c8' }, -}) -ins_left({ - 'branch', - icon = '', - color = { fg = '#A3BE8C' }, -}) -ins_left({ - 'diff', - colored = true, - symbols = { added = ' ', modified = '󰇊 ', removed = ' ' }, - -- symbols = { added = ' ', modified = ' ', removed = ' ' }, - cond = conditions.hide_in_width, -}) -ins_left({ - 'diagnostics', - sources = { 'nvim_lsp' }, -}) - --- ins_left({ --- 'navic', --- ---@type "static"| "dynamic"| nil --- color_correction = nil, --- navic_opts = nil, --- }) -ins_right({ - servers_attached, - icon = ' LSPs:', - color = { fg = '#8992a7', gui = 'bold' }, - cond = conditions.lsp_active, -}) -ins_right({ 'progress', color = { fg = '#957FB8' } }) -ins_right({ 'location', color = { fg = '#6CAF95' } }) -ins_right({ - 'searchcount', - icon = '', - -- color = { fg = '#DCA561' }, - color = { fg = '#cc8c3c' }, -}) -ins_right({ - function() - if vim.fn.mode():find '[vV]' then - local ln_beg = vim.fn.line 'v' - local ln_end = vim.fn.line '.' - - local lines = ln_beg <= ln_end and ln_end - ln_beg + 1 or ln_beg - ln_end + 1 - - return 'sel: ' .. tostring(vim.fn.wordcount().visual_chars) .. ' | ' .. tostring(lines) - else - return '' - end - end, - color = { fg = '#c5c9c5' }, -}) - -require('lualine.components.buffers').buffers = function(self) - local buffers = {} - self.bufpos2nr = {} - for _, b in ipairs(vim.t['bufs']) do - if vim.fn.buflisted(b) ~= 0 and vim.api.nvim_buf_get_option(b, 'buftype') ~= 'quickfix' then - buffers[#buffers + 1] = self:new_buffer(b, #buffers + 1) - self.bufpos2nr[#buffers] = b - end - end - - return buffers -end -require('lualine').setup(config) diff --git a/.config/nvim/lua/plugins/config/neotree.lua b/.config/nvim/lua/plugins/config/neotree.lua deleted file mode 100644 index b105f11..0000000 --- a/.config/nvim/lua/plugins/config/neotree.lua +++ /dev/null @@ -1,67 +0,0 @@ -local M = {} - -M.config = function(_, opts) - local cmd = 'trash' - if vim.fn.executable 'trash-put' == 1 then - cmd = 'trash-put' - end - - local options = vim.tbl_deep_extend('force', { - window = { - mappings = { - l = 'open', - ['?'] = 'show_help', - ['<'] = 'prev_source', - ['>'] = 'next_source', - }, - }, - filesystem = { - use_libuv_file_watcher = true, - window = { - -- mappings = { }, - fuzzy_finder_mappings = { - [''] = 'move_cursor_down', - [''] = 'move_cursor_up', - [''] = 'move_cursor_down', - [''] = 'move_cursor_up', - }, - }, - - commands = { - -- Override delete to use trash instead of rm - delete = function(state) - local inputs = require 'neo-tree.ui.inputs' - local path = state.tree:get_node().path - local msg = 'Trash ' .. path .. ' ?' - inputs.confirm(msg, function(confirmed) - if not confirmed then - return - end - - vim.fn.system({ cmd, vim.fn.fnameescape(path) }) - require('neo-tree.sources.manager').refresh(state.name) - end) - end, - -- over write default 'delete_visual' command to 'trash' x n. - delete_visual = function(state, selected_nodes) - local inputs = require 'neo-tree.ui.inputs' - local count = #selected_nodes - local msg = 'Trash ' .. count .. ' files ?' - inputs.confirm(msg, function(confirmed) - if not confirmed then - return - end - for _, node in ipairs(selected_nodes) do - vim.fn.system({ cmd, vim.fn.fnameescape(node.path) }) - end - require('neo-tree.sources.manager').refresh(state.name) - end) - end, - }, - }, - }, opts) - - require('neo-tree').setup(options) - require('lsp-file-operations').setup({}) -end -return M diff --git a/.config/nvim/lua/plugins/config/nvim-lint.lua b/.config/nvim/lua/plugins/config/nvim-lint.lua deleted file mode 100644 index bf95486..0000000 --- a/.config/nvim/lua/plugins/config/nvim-lint.lua +++ /dev/null @@ -1,108 +0,0 @@ -local M = {} -M.au_group = vim.api.nvim_create_augroup('sp_nvim_lint', {}) -M.languages = { - sh = { 'shellcheck', 'cspell' }, - bash = { 'shellcheck', 'cspell' }, - fish = { 'fish' }, - zsh = { 'shellcheck', 'zsh', 'cspell' }, - -- c = { 'clangtidy' }, - -- cpp = { 'clangtidy' }, - go = { 'golangcilint', 'cspell' }, - -- markdown = { 'vale' }, - html = { 'htmlhint', 'cspell' }, - css = { 'stylelint', 'cspell' }, - scss = { 'stylelint', 'cspell' }, - sass = { 'stylelint', 'cspell' }, - less = { 'stylelint', 'cspell' }, - python = { 'ruff', 'cspell' }, - astro = { 'eslint_d', 'cspell' }, - svelte = { 'eslint_d', 'cspell' }, - javascript = { 'eslint_d', 'cspell' }, - javascriptreact = { 'eslint_d', 'cspell' }, - typescript = { 'eslint_d', 'cspell' }, - typescriptreact = { 'eslint_d', 'cspell' }, - vue = { 'eslint_d', 'cspell' }, - yaml = { 'yamllint', 'cspell' }, - php = { 'php', 'phpstan', 'phpcs', 'cspell' }, -} -function M.debounce(ms, fn) - local timer = vim.uv.new_timer() - return function(...) - local argv = { ... } - timer:start(ms, 0, function() - timer:stop() - vim.schedule_wrap(fn)(unpack(argv)) - end) - end -end -M.linters = { - eslint_d = { - condition = function(ctx) - return vim.fs.find({ - 'eslint.config.js', - 'eslint.config.mjs', - 'eslint.config.cjs', - '.eslintrc.json', - '.eslintrc', - '.eslintrc.js', - '.eslintrc.yaml', - '.eslintrc.yml', - }, { path = ctx.filename, upward = true })[1] - end, - }, -} - -function M.config(_, opts) - local lint = require 'lint' - M.languages = vim.tbl_deep_extend('force', M.languages, opts.languages or {}) - M.linters = vim.tbl_deep_extend('force', M.linters, opts.linters or {}) - - lint.linters_by_ft = M.languages - - local function run() - -- Use nvim-lint's logic first: - -- * checks if linters exist for the full filetype first - -- * otherwise will split filetype by "." and add all those linters - -- * this differs from conform.nvim which only uses the first filetype that has a formatter - local names = lint._resolve_linter_by_ft(vim.bo.filetype) - - -- Create a copy of the names table to avoid modifying the original. - names = vim.list_extend({}, names) - - -- Add fallback linters. - if #names == 0 then - vim.list_extend(names, lint.linters_by_ft['_'] or {}) - end - - -- Add global linters. - vim.list_extend(names, lint.linters_by_ft['*'] or {}) - - -- Filter out linters that don't exist or don't match the condition. - local ctx = { filename = vim.api.nvim_buf_get_name(0) } - ctx.dirname = vim.fn.fnamemodify(ctx.filename, ':h') - names = vim.tbl_filter(function(name) - local linter = lint.linters[name] - return linter and not (type(linter) == 'table' and linter.condition and not linter.condition(ctx)) - end, names) - - -- Run linters. - if #names > 0 then - lint.try_lint(names) - end - end - for name, linter in pairs(M.linters) do - if type(linter) == 'table' and type(lint.linters[name]) == 'table' then - lint.linters[name] = vim.tbl_deep_extend('force', lint.linters[name], linter) - else - lint.linters[name] = linter - end - end - vim.api.nvim_create_autocmd({ 'BufWritePost', 'BufRead', 'InsertLeave', 'FocusGained' }, { - group = M.au_group, - desc = 'Lint on save', - pattern = '*', - callback = M.debounce(100, run), - }) -end - -return M diff --git a/.config/nvim/lua/plugins/config/nvim-tree.lua b/.config/nvim/lua/plugins/config/nvim-tree.lua deleted file mode 100644 index 2f54ed5..0000000 --- a/.config/nvim/lua/plugins/config/nvim-tree.lua +++ /dev/null @@ -1,58 +0,0 @@ -local au_group = vim.api.nvim_create_augroup('sp_nvim_tree', { clear = true }) - -vim.api.nvim_create_autocmd('BufEnter', { - group = au_group, - desc = "Close nvim-tree if it's the only window", - pattern = 'NvimTree_*', - callback = function() - local layout = vim.api.nvim_call_function('winlayout', {}) - if - layout[1] == 'leaf' - and vim.api.nvim_get_option_value('filetype', { buf = vim.api.nvim_win_get_buf(layout[2]) }) == 'NvimTree' - and layout[3] == nil - then - vim.cmd 'confirm quit' - end - end, -}) - -local function my_on_attach(bufnr) - local api = require 'nvim-tree.api' - - local function opts(desc) - return { desc = 'nvim-tree: ' .. desc, buffer = bufnr, noremap = true, silent = true, nowait = true } - end - - -- default mappings - api.config.mappings.default_on_attach(bufnr) - - -- custom mappings - - vim.keymap.del('n', 'U', { buffer = bufnr }) - vim.keymap.del('n', 'L', { buffer = bufnr }) - vim.keymap.del('n', 'M', { buffer = bufnr }) - vim.keymap.set('n', 'H', api.node.navigate.parent, opts 'Goto parent') - vim.keymap.set('n', 'l', api.node.open.edit, opts 'Open') - vim.keymap.set('n', 'L', api.node.open.no_windown_picker, opts 'Open(no window select)') - vim.keymap.set('n', '?', api.tree.toggle_help, opts 'Help') - vim.keymap.set('n', 'D', api.fs.remove, opts 'Delete') - vim.keymap.set('n', 'd', api.fs.trash, opts 'Trash') - - vim.keymap.set('n', 'tl', api.node.open.toggle_group_empty, opts 'Toggle Group Empty') - vim.keymap.set('n', 'tm', api.tree.toggle_no_bookmark_filter, opts 'Toggle Filter: No Bookmark') - vim.keymap.set('n', 'td', api.tree.toggle_hidden_filter, opts 'Toggle Dotfiles') - vim.keymap.set('n', 'tg', api.tree.toggle_gitignore_filter, opts 'Toggle Gitignore') - vim.keymap.set('n', 'tc', api.tree.toggle_custom_filter, opts 'Toggle Custom filters') -end - -require('nvim-tree').setup({ - view = { width = 40 }, - ui = { - confirm = { - remove = true, - trash = false, - }, - }, - on_attach = my_on_attach, -}) -require('lsp-file-operations').setup() diff --git a/.config/nvim/lua/plugins/config/telescope.lua b/.config/nvim/lua/plugins/config/telescope.lua deleted file mode 100644 index 2a4e918..0000000 --- a/.config/nvim/lua/plugins/config/telescope.lua +++ /dev/null @@ -1,372 +0,0 @@ -local M = {} -local au_telescope = vim.api.nvim_create_augroup('au_telescope', { clear = true }) - -local function getVisualSelection() - vim.cmd 'noau normal! "vy"' - local text = vim.fn.getreg 'v' - vim.fn.setreg('v', {}) - - text = string.gsub(text, '\n', '') - if #text > 0 then - return text - else - return '' - end -end - -local function filename_first(_, path) - local tail = vim.fs.basename(path) - local parent = vim.fs.dirname(path) - if parent == '.' then - return tail - end - return string.format('%s\t\t%s', tail, parent) -end - -local function telescope_create_file() - require('telescope.builtin').find_files({ - prompt_title = 'Create File', - find_command = { 'fd', '--type', 'd', '.', vim.fn.getcwd() }, - attach_mappings = function(_, map) - local state = require 'telescope.actions.state' - local actions = require 'telescope.actions' - map('i', '', function(prompt_bufnr) - local content = state.get_selected_entry() - actions.close(prompt_bufnr) - -- vim.print('content : ' .. content.cwd .. '/' .. content.value) - local dir = content.value - local name = vim.fn.input 'File Name: ' - vim.cmd('e ' .. dir .. name) - vim.cmd 'w ++p' - end) - return true - end, - }) -end - -local function project_files() - local opts = { - path_display = filename_first, - previewer = false, - } -- define here if you want to define something - - if vim.b.gitsigns_head then - opts.show_untracked = true - require('telescope.builtin').git_files(opts) - else - require('telescope.builtin').find_files(opts) - end -end - -M.keys = function() - local builtin = require 'telescope.builtin' - return { - { - '', - project_files, - desc = 'Git/Files', - }, - { - 'ff', - function() - builtin.find_files({ path_display = filename_first }) - end, - desc = 'Files', - }, - { - 'fF', - function() - builtin.git_files({ show_untracked = true, use_file_path = true, path_display = filename_first }) - end, - desc = 'Git Files(use_file_path)', - }, - { 'fp', telescope_create_file, desc = 'CreateFile' }, - { 'fc', telescope_create_file, desc = 'CreateFile' }, - { 'fk', builtin.keymaps, desc = 'keymaps' }, - { 'fS', builtin.current_buffer_fuzzy_find, desc = 'Search(Buffer)' }, - -- { 'fs', builtin.live_grep, desc = 'Search(Project)' }, - { 'fs', 'Telescope egrepify', desc = 'Search(Project)' }, - { 'fw', builtin.grep_string, desc = 'Search Current Word', mode = { 'n', 'x' } }, - { 'fb', builtin.buffers, desc = 'Buffers' }, - { 'fh', builtin.help_tags, desc = 'Help' }, - { 'fR', builtin.oldfiles, desc = 'Old Files' }, - { 'fr', builtin.resume, desc = 'Resume' }, - { - 'fs', - function() - local text = getVisualSelection() - builtin.live_grep({ default_text = text }) - end, - mode = 'v', - desc = '[S]earch [S]election', - }, - { - 'fS', - function() - local text = getVisualSelection() - builtin.current_buffer_fuzzy_find({ default_text = text }) - end, - mode = 'v', - desc = '[S]earch [S]election(Buffer)', - }, - { - 'fn', - function() - builtin.find_files({ - cwd = vim.fn.stdpath 'config', - path_display = filename_first, - }) - end, - desc = 'Neovim Config', - }, - { - 'fd', - function() - builtin.git_files({ - cwd = vim.fn.expand '$HOME/Documents/dotfiles', - path_display = filename_first, - show_untracked = true, - }) - end, - desc = 'Dotfiles', - }, - { 'gb', builtin.git_branches, desc = 'Git Branches' }, - { 'fg', builtin.git_status, desc = 'Git Status' }, - { 'gS', builtin.git_stash, desc = 'Git Stash' }, - { 'gc', builtin.git_commits, desc = 'Git Commits' }, - { 'gC', builtin.git_bcommits, desc = 'Git Buffer Commits' }, - } -end - -M.config = function() - vim.api.nvim_create_autocmd('FileType', { - pattern = 'TelescopeResults', - group = au_telescope, - callback = function(ctx) - vim.api.nvim_buf_call(ctx.buf, function() - vim.fn.matchadd('TelescopeParent', '\t\t.*$') - vim.api.nvim_set_hl(0, 'TelescopeParent', { link = 'Comment' }) - end) - end, - }) - local actions = require 'telescope.actions' - local action_layout = require 'telescope.actions.layout' - local builtin = require 'telescope.builtin' - - local dropdown = { - layout_strategy = 'vertical', - layout_config = { width = 0.6, preview_cutoff = 1, prompt_position = 'top' }, - } - require('telescope').setup({ - defaults = { - -- path_display = { "truncate" }, - sorting_strategy = 'ascending', - set_env = { ['COLORTERM'] = 'truecolor' }, - layout_config = { - horizontal = { prompt_position = 'top', preview_width = 0.40 }, - vertical = { mirror = false }, - width = 0.87, - height = 0.80, - preview_cutoff = 120, - }, - mappings = { - i = { - [''] = actions.move_selection_next, - [''] = actions.move_selection_previous, - [''] = actions.cycle_history_next, - [''] = actions.cycle_history_prev, - [''] = actions.close, - [''] = action_layout.toggle_preview, - - [''] = actions.toggle_selection + actions.move_selection_next, - [''] = actions.toggle_selection + actions.move_selection_previous, - [''] = actions.smart_send_to_qflist + actions.open_qflist, - }, - n = { - q = actions.close, - [''] = action_layout.toggle_preview, - [''] = actions.toggle_selection, - }, - }, - vimgrep_arguments = { - 'rg', - '--color=never', - '--no-heading', - '--with-filename', - '--line-number', - '--column', - '--smart-case', - '--hidden', - '--trim', -- add this value - '--glob=!.git/', - '--glob=!node_modules/', - '--glob=!.venv/', - '--glob=!venv/', - }, - }, - - pickers = { - buffers = { - ignore_current_buffer = true, - sort_lastused = true, - mappings = { - i = { [''] = 'delete_buffer' }, - n = { d = 'delete_buffer' }, - }, - prompt_title = 'Buffers', - results_title = 'Command History', - prompt_prefix = ' ', - sorting_strategy = 'ascending', - layout_strategy = 'bottom_pane', - layout_config = { - prompt_position = 'top', - }, - border = true, - borderchars = { - prompt = { ' ', ' ', '─', ' ', ' ', ' ', '─', '─' }, - results = { '─', ' ', ' ', ' ', '─', '─', ' ', ' ' }, - preview = { '─', ' ', '─', '│', '┬', '─', '─', '╰' }, - }, - }, - help_tags = { - prompt_title = 'Help', - results_title = 'Help Tags', - prompt_prefix = ' ', - sorting_strategy = 'ascending', - layout_strategy = 'bottom_pane', - layout_config = { - prompt_position = 'top', - height = 25, - }, - border = true, - borderchars = { - prompt = { ' ', ' ', '─', ' ', ' ', ' ', '─', '─' }, - results = { '─', ' ', ' ', ' ', '─', '─', ' ', ' ' }, - preview = { '─', ' ', '─', '│', '┬', '─', '─', '╰' }, - }, - }, - keymaps = { - prompt_title = 'keymaps', - results_title = 'keymaps', - prompt_prefix = ' ', - sorting_strategy = 'ascending', - layout_strategy = 'bottom_pane', - layout_config = { - prompt_position = 'top', - height = 25, - }, - border = true, - borderchars = { - prompt = { ' ', ' ', '─', ' ', ' ', ' ', '─', '─' }, - results = { '─', ' ', ' ', ' ', '─', '─', ' ', ' ' }, - preview = { '─', ' ', '─', '│', '┬', '─', '─', '╰' }, - }, - }, - command_history = { - prompt_title = '', - results_title = 'Command History', - - --            - --  卑 喝   - prompt_prefix = ' ', - -- prompt_prefix = " ", - -- prompt_prefix = " ", - -- prompt_prefix = " ", - - sorting_strategy = 'ascending', - layout_strategy = 'bottom_pane', - layout_config = { - prompt_position = 'top', - height = 25, - }, - border = true, - borderchars = { - prompt = { ' ', ' ', '─', ' ', ' ', ' ', '─', '─' }, - results = { '─', ' ', ' ', ' ', '─', '─', ' ', ' ' }, - preview = { '─', ' ', '─', '│', '┬', '─', '─', '╰' }, - }, - mappings = { - i = { [''] = actions.edit_command_line }, - n = { [''] = actions.edit_command_line }, - }, - }, - lsp_references = dropdown, - lsp_definitions = dropdown, - git_branches = dropdown, - git_commits = dropdown, - git_bcommits = dropdown, - lsp_document_symbols = dropdown, - lsp_workspace_symbols = dropdown, - grep_string = vim.tbl_extend('force', dropdown, { - path_display = { 'truncate' }, - }), - }, - extensions = { - ['zf-native'] = { - -- options for sorting file-like items - file = { - -- override default telescope file sorter - enable = true, - -- highlight matching text in results - highlight_results = true, - -- enable zf filename match priority - match_filename = true, - -- optional function to define a sort order when the query is empty - initial_sort = nil, - }, - - -- options for sorting all other items - generic = { - -- override default telescope generic item sorter - enable = true, - -- highlight matching text in results - highlight_results = true, - -- disable zf filename match priority - match_filename = false, - -- optional function to define a sort order when the query is empty - initial_sort = nil, - }, - }, - ['ui-select'] = require('telescope.themes').get_dropdown({}), - egrepify = { - prefixes = { - ['>'] = { - flag = 'type', - cb = function(input) - -- check if the input has any commas - if string.find(input, ',') then - return string.format([[{%s}]], input) - end - return string.format([[%s]], input) - end, - }, - ['<'] = { - flag = 'type-not', - cb = function(input) - -- check if the input has any commas - if string.find(input, ',') then - return string.format([[{%s}]], input) - end - return string.format([[%s]], input) - end, - }, - }, - }, - }, - }) - require('telescope').load_extension 'zf-native' - require('telescope').load_extension 'ui-select' - require('telescope').load_extension 'egrepify' - - vim.lsp.handlers['textDocument/definition'] = builtin.lsp_definitions - vim.lsp.handlers['textDocument/typeDefinition'] = builtin.lsp_type_definitions - vim.lsp.handlers['textDocument/implementation'] = builtin.lsp_implementations - vim.lsp.handlers['textDocument/references'] = builtin.lsp_references - vim.lsp.handlers['textDocument/documentSymbol'] = builtin.lsp_document_symbols - vim.lsp.handlers['workspace/symbol'] = builtin.lsp_workspace_symbols - vim.lsp.handlers['callHierarchy/incomingCalls'] = builtin.lsp_incoming_calls - vim.lsp.handlers['callHierarchy/outgoingCalls'] = builtin.lsp_outgoing_calls -end --- M.config() - -return M diff --git a/.config/nvim/lua/plugins/config/toggleterm.lua b/.config/nvim/lua/plugins/config/toggleterm.lua deleted file mode 100644 index 4fa7326..0000000 --- a/.config/nvim/lua/plugins/config/toggleterm.lua +++ /dev/null @@ -1,34 +0,0 @@ -local Terminal = require('toggleterm.terminal').Terminal -local toggleterm = require 'toggleterm' -local lazygit = Terminal:new({ - cmd = 'lazygit', - dir = 'git_dir', - direction = 'float', - -- shell = vim.o.shell == '/bin/fish' and '/bin/zsh' or vim.o.shell, - float_opts = { border = 'curved' }, -}) - -local function lazygit_toggle() - lazygit:toggle() -end - -toggleterm.setup({ - shell = vim.o.shell == '/bin/fish' and '/bin/zsh' or vim.o.shell, - direction = 'float', - open_mapping = [[]], - highlights = { - FloatBorder = { link = 'FloatBorder' }, - }, - float_opts = { - border = 'single', - }, - -- highlights = { - -- Normal = { - -- guibg = '#080818', - -- }, - -- NormalFloat = { - -- guibg = '#080818', - -- }, - -- }, -}) -vim.keymap.set('n', 'tl', lazygit_toggle, { desc = '[T]erminal [L]azygit' }) diff --git a/.config/nvim/lua/plugins/config/tree-sitter.lua b/.config/nvim/lua/plugins/config/tree-sitter.lua deleted file mode 100644 index d5dbebc..0000000 --- a/.config/nvim/lua/plugins/config/tree-sitter.lua +++ /dev/null @@ -1,137 +0,0 @@ -local configs = require 'nvim-treesitter.configs' ----@diagnostic disable-next-line: missing-fields -configs.setup({ - highlight = { - enable = true, - -- additional_vim_regex_highlighting = { 'markdown', 'xml' }, - disable = function(_, bufnr) - local line_count = vim.api.nvim_buf_line_count(bufnr) - if line_count > 2500 then - return true - end - end, - }, - indent = { enable = false }, - matchup = { enable = true }, - ensure_installed = { - 'bash', - 'dockerfile', - 'fish', - 'query', - 'regex', - 'rasi', - 'sxhkdrc', - 'vim', - 'vimdoc', - 'diff', - 'git_config', - 'git_rebase', - 'gitattributes', - 'gitcommit', - 'gitignore', - 'hyprlang', - 'ini', - 'sql', - 'ssh_config', - 'tmux', - 'toml', - 'xml', - 'zathurarc', - }, - incremental_selection = { - enable = true, - keymaps = { - init_selection = '', - node_incremental = '', - scope_incremental = false, - node_decremental = '', - }, - }, - textobjects = { - -- select = { - -- enable = true, - -- lookahead = true, - -- keymaps = { - -- ['af'] = '@function.outer', - -- ['if'] = '@function.inner', - -- ['ac'] = '@class.outer', - -- ['ic'] = { query = '@class.inner', desc = 'Select inner part of a class region' }, - -- ['al'] = { query = '@scope', query_group = 'locals', desc = 'Select language scope' }, - -- ['a/'] = { query = '@comment.outer', desc = 'Select outer comment' }, - -- ['i/'] = { query = '@comment.inner', desc = 'Select inner comment' }, - -- }, - -- selection_modes = { - -- ['@parameter.outer'] = 'v', -- charwise - -- ['@function.outer'] = 'V', -- linewise - -- ['@class.outer'] = '', -- blockwise - -- }, - -- include_surrounding_whitespace = true, - -- }, - move = { - enable = true, - set_jumps = true, -- whether to set jumps in the jumplist - goto_next_start = { - [']m'] = '@function.outer', - [']C'] = { query = '@class.outer', desc = 'Next class start' }, - [']l'] = '@loop.*', - -- ["]o"] = { query = { "@loop.inner", "@loop.outer" } } - [']s'] = { query = '@scope', query_group = 'locals', desc = 'Next scope' }, - [']z'] = { query = '@fold', query_group = 'folds', desc = 'Next fold' }, - }, - goto_next_end = { - [']M'] = '@function.outer', - [']['] = '@class.outer', - }, - goto_previous_start = { - ['[m'] = '@function.outer', - ['[C'] = '@class.outer', - }, - goto_previous_end = { - ['[M'] = '@function.outer', - ['[]'] = '@class.outer', - }, - goto_next = { - [']i'] = '@conditional.outer', - }, - goto_previous = { - ['[i'] = '@conditional.outer', - }, - }, - swap = { - enable = true, - swap_next = { - ['k'] = { query = '@block.outer', desc = 'Swap next block' }, - ['f'] = { query = '@function.outer', desc = 'Swap next function' }, - ['a'] = { query = '@parameter.inner', desc = 'Swap next argument' }, - }, - swap_previous = { - ['K'] = { query = '@block.outer', desc = 'Swap previous block' }, - ['F'] = { query = '@function.outer', desc = 'Swap previous function' }, - ['A'] = { query = '@parameter.inner', desc = 'Swap previous argument' }, - }, - }, - }, -}) - -require('nvim-ts-autotag').setup({ - -- Defaults - opts = { - enable_close = true, -- Auto close tags - enable_rename = true, -- Auto rename pairs of tags - enable_close_on_slash = false, -- Auto close on trailing c', function() - require('treesitter-context').go_to_context(vim.v.count1) -end, { silent = true, desc = 'Goto Context' }) -vim.keymap.set('n', '', function() - require('treesitter-context').go_to_context(vim.v.count1) -end, { silent = true, desc = 'Goto Context' }) - --- for _, v in ipairs(vim.fn.readdir(vim.g.base46_cache)) do --- dofile(vim.g.base46_cache .. v) --- end diff --git a/.config/nvim/lua/plugins/config/util.lua b/.config/nvim/lua/plugins/config/util.lua index 5dcdc5f..c698531 100644 --- a/.config/nvim/lua/plugins/config/util.lua +++ b/.config/nvim/lua/plugins/config/util.lua @@ -14,4 +14,18 @@ M.unique_append_table = function(list, values) return vim.list_extend(l, appendValues) end +--- A wrapper around `age.nvim` to get the credentials from the identity file. +---@param secret_file string The secret file to read the credentials from(`secret_file` should be in location `$HOME/.config/age/`). +---@return string|nil secret The credentials from the identity file. +M.get_age_credentials = function(secret_file) + local identity_file = vim.fn.expand '$HOME/.config/age/identity.txt' + + if 0 == vim.fn.filereadable(identity_file) then + return nil + end + + local secret = vim.fn.expand('$HOME/.config/age/' .. secret_file) + return require('age').get(secret, identity_file) +end + return M diff --git a/.config/nvim/lua/plugins/conform.lua b/.config/nvim/lua/plugins/conform.lua index 23337c0..c5622e5 100644 --- a/.config/nvim/lua/plugins/conform.lua +++ b/.config/nvim/lua/plugins/conform.lua @@ -18,6 +18,109 @@ return { vim.o.formatexpr = "v:lua.require'conform'.formatexpr()" end, config = function() - require 'plugins.config.conform' + local prettier = { 'prettierd', 'prettier', stop_after_first = true } + local slow_format_filetypes = {} + + ---@param bufnr integer + ---@param ... string + ---@return string + local function first(bufnr, ...) + local conform = require 'conform' + for i = 1, select('#', ...) do + local formatter = select(i, ...) + if conform.get_formatter_info(formatter, bufnr).available then + return formatter + end + end + return select(1, ...) + end + + local function prettier_eslint(bufnr) + return { first(bufnr, 'prettierd', 'prettier'), 'eslint_d' } + end + + require('conform').setup({ + -- Define your formatters + formatters_by_ft = { + sh = { 'shfmt' }, + lua = { 'stylua' }, + bash = { 'shfmt' }, + c = { 'clang-format' }, + cpp = { 'clang-format' }, + go = function(bufnr) + return { 'goimports', first(bufnr, 'gofumpt', 'gofmt') } + end, + fish = { 'fish_indent' }, + css = prettier, + html = prettier, + jsonc = prettier, + json = prettier, + json5 = prettier, + less = prettier, + markdown = prettier, + sass = prettier, + scss = prettier, + astro = prettier_eslint, + javascript = prettier_eslint, + javascriptreact = prettier_eslint, + typescript = prettier_eslint, + typescriptreact = prettier_eslint, + svelte = prettier_eslint, + vue = prettier_eslint, + nim = { 'nimpretty' }, + zig = { 'zigfmt' }, + php = function(bufnr) + return { first(bufnr, 'pint', 'php-cs-fixer', 'phpcbf') } + end, + blade = { 'blade-formatter' }, + gleam = { 'gleam' }, + -- You can use a function here to determine the formatters dynamically + python = function(bufnr) + if require('conform').get_formatter_info('ruff_format', bufnr).available then + return { 'ruff_format', 'ruff_fix', 'ruff_organize_imports' } + else + return { 'isort', 'black' } + end + end, + -- Use the "_" filetype to run formatters on filetypes that don't + -- have other formatters configured. + ['_'] = { 'trim_whitespace', 'trim_newlines' }, + }, + default_format_opts = { + lsp_format = 'fallback', + }, + -- Set up format-on-save + -- format_on_save = { timeout_ms = 500, lsp_fallback = true }, + format_on_save = function(bufnr) + -- Disable autoformat for files in a certain path + local bufname = vim.api.nvim_buf_get_name(bufnr) + if bufname:match '/node_modules/' then + return + end + if slow_format_filetypes[vim.bo[bufnr].filetype] then + return + end + local function on_format(err) + if err and err:match 'timeout$' then + slow_format_filetypes[vim.bo[bufnr].filetype] = true + end + end + + return { timeout_ms = 200, lsp_fallback = true }, on_format + end, + + format_after_save = function(bufnr) + if not slow_format_filetypes[vim.bo[bufnr].filetype] then + return + end + return { lsp_fallback = true } + end, + -- Customize formatters + formatters = { + shfmt = { + prepend_args = { '-i', '2' }, + }, + }, + }) end, } diff --git a/.config/nvim/lua/plugins/dap.lua b/.config/nvim/lua/plugins/dap.lua index 9c190c7..190370c 100644 --- a/.config/nvim/lua/plugins/dap.lua +++ b/.config/nvim/lua/plugins/dap.lua @@ -57,6 +57,154 @@ return { } end, config = function() - require 'plugins.config.dap' + local dap, dapui = require 'dap', require 'dapui' + local dap_icons = { + Stopped = { '󰁕 ', 'DiagnosticWarn', 'DapStoppedLine' }, + Breakpoint = ' ', + BreakpointCondition = ' ', + BreakpointRejected = { ' ', 'DiagnosticError' }, + LogPoint = '.>', + } + vim.api.nvim_set_hl(0, 'DapStoppedLine', { default = true, link = 'Visual' }) + + for name, sign in pairs(dap_icons) do + sign = type(sign) == 'table' and sign or { sign } + vim.fn.sign_define( + 'Dap' .. name, + { text = sign[1], texthl = sign[2] or 'DiagnosticInfo', linehl = sign[3], numhl = sign[3] } + ) + end + require('persistent-breakpoints').setup({ + load_breakpoints_event = { 'BufReadPost' }, + }) + ---@diagnostic disable-next-line: missing-fields + -- require('dap-vscode-js').setup({ + -- debugger_path = vim.fn.stdpath 'data' .. '/lazy/vscode-js-debug', + -- adapters = { 'pwa-node', 'pwa-chrome', 'pwa-msedge', 'node-terminal', 'pwa-extensionHost' }, -- which adapters to register in nvim-dap + -- }) + dap.adapters.bashdb = { + type = 'executable', + command = vim.fn.stdpath 'data' .. '/mason/packages/bash-debug-adapter/bash-debug-adapter', + name = 'bashdb', + } + dap.adapters.mix_task = { + type = 'executable', + command = require('mason-registry').get_package('elixir-ls'):get_install_path() .. '/debug_adapter.sh', -- debugger.bat for windows + args = {}, + } + -- setup dap config by VsCode launch.json file + local vscode = require 'dap.ext.vscode' + local json = require 'plenary.json' + vscode.json_decode = function(str) + return vim.json.decode(json.json_strip_comments(str, { whitespace = true })) + end + if not dap.adapters['pwa-node'] then + require('dap').adapters['pwa-node'] = { + type = 'server', + host = 'localhost', + port = '${port}', + executable = { + command = require('mason-registry').get_package('js-debug-adapter'):get_install_path() .. '/js-debug-adapter', + args = { + -- require('mason-registry').get_package('js-debug-adapter'):get_install_path() + -- .. '/js-debug/src/dapDebugServer.js', + '${port}', + }, + }, + } + end + if not dap.adapters['node'] then + dap.adapters['node'] = function(cb, config) + if config.type == 'node' then + config.type = 'pwa-node' + end + local nativeAdapter = dap.adapters['pwa-node'] + if type(nativeAdapter) == 'function' then + nativeAdapter(cb, config) + else + cb(nativeAdapter) + end + end + end + + local js_filetypes = { 'typescript', 'javascript', 'typescriptreact', 'javascriptreact' } + + vscode.type_to_filetypes['node'] = js_filetypes + vscode.type_to_filetypes['pwa-node'] = js_filetypes + + for _, language in ipairs(js_filetypes) do + if not dap.configurations[language] then + dap.configurations[language] = { + { + type = 'pwa-node', + request = 'launch', + name = 'Launch file', + program = '${file}', + cwd = '${workspaceFolder}', + }, + { + type = 'pwa-node', + request = 'attach', + name = 'Attach', + processId = require('dap.utils').pick_process, + cwd = '${workspaceFolder}', + }, + } + end + end + + dap.adapters.php = { + type = 'executable', + command = require('mason-registry').get_package('php-debug-adapter'):get_install_path() .. 'php-debug-adapter', + -- command = 'node', + -- args = { require('mason-registry').get_package('php-debug-adapter'):get_install_path() .. '/out/phpDebug.js' } + } + + dap.configurations.php = { + { + type = 'php', + request = 'launch', + name = 'Listen for Xdebug', + port = 9000, + }, + } + + dap.configurations.elixir = { + { + type = 'mix_task', + name = 'mix (Default task)', + request = 'launch', + projectDir = '${workspaceRoot}', + }, + { + type = 'mix_task', + name = 'mix test', + task = 'test', + taskArgs = { '--trace' }, + request = 'launch', + startApps = true, -- for Phoenix projects + projectDir = '${workspaceFolder}', + requireFiles = { + 'test/**/test_helper.exs', + 'test/**/*_test.exs', + }, + }, + } + require('dap-go').setup() + dapui.setup() + require('nvim-dap-virtual-text').setup({}) + + dap.listeners.before.attach.dapui_config = function() + dapui.open() + end + dap.listeners.before.launch.dapui_config = function() + dapui.open() + end + dap.listeners.before.event_terminated.dapui_config = function() + dapui.close() + end + dap.listeners.before.event_exited.dapui_config = function() + dapui.close() + end end, } diff --git a/.config/nvim/lua/plugins/dial.lua b/.config/nvim/lua/plugins/dial.lua index 17844ea..ec1e00f 100644 --- a/.config/nvim/lua/plugins/dial.lua +++ b/.config/nvim/lua/plugins/dial.lua @@ -1,6 +1,206 @@ +---@type table> +local dials_by_ft = {} + +---@param increment boolean +---@param g? boolean +local function dial(increment, g) + local mode = vim.fn.mode(true) + -- Use visual commands for VISUAL 'v', VISUAL LINE 'V' and VISUAL BLOCK '\22' + local is_visual = mode == 'v' or mode == 'V' or mode == '\22' + local func = (increment and 'inc' or 'dec') .. (g and '_g' or '_') .. (is_visual and 'visual' or 'normal') + local group = dials_by_ft[vim.bo.filetype] or 'default' + return require('dial.map')[func](group) +end + +---@type LazySpec return { 'monaqa/dial.nvim', version = '0.4.*', - keys = require('plugins.config.dial').keys, - config = require('plugins.config.dial').config, + keys = { + { + '', + function() + return dial(true) + end, + expr = true, + desc = 'Increment', + mode = { 'n', 'v' }, + }, + { + '', + function() + return dial(false) + end, + expr = true, + desc = 'Decrement', + mode = { 'n', 'v' }, + }, + { + 'g', + function() + return dial(true, true) + end, + expr = true, + desc = 'Increment', + mode = { 'n', 'v' }, + }, + { + 'g', + function() + return dial(false, true) + end, + expr = true, + desc = 'Decrement', + mode = { 'n', 'v' }, + }, + }, + config = function() + local augend = require 'dial.augend' + + local logical_alias = augend.constant.new({ + elements = { '&&', '||' }, + word = false, + cyclic = true, + }) + + local ordinal_numbers = augend.constant.new({ + -- elements through which we cycle. When we increment, we go down + -- On decrement we go up + elements = { + 'first', + 'second', + 'third', + 'fourth', + 'fifth', + 'sixth', + 'seventh', + 'eighth', + 'ninth', + 'tenth', + }, + -- if true, it only matches strings with word boundary. firstDate wouldn't work for example + word = false, + -- do we cycle back and forth (tenth to first on increment, first to tenth on decrement). + -- Otherwise nothing will happen when there are no further values + cyclic = true, + }) + + local weekdays = augend.constant.new({ + elements = { + 'Monday', + 'Tuesday', + 'Wednesday', + 'Thursday', + 'Friday', + 'Saturday', + 'Sunday', + }, + word = true, + cyclic = true, + }) + + local months = augend.constant.new({ + elements = { + 'January', + 'February', + 'March', + 'April', + 'May', + 'June', + 'July', + 'August', + 'September', + 'October', + 'November', + 'December', + }, + word = true, + cyclic = true, + }) + + local capitalized_boolean = augend.constant.new({ + elements = { + 'True', + 'False', + }, + word = true, + cyclic = true, + }) + + local opts = { + dials_by_ft = { + lua = 'lua', + json = 'json', + jsonc = 'json', + json5 = 'json', + markdown = 'markdown', + python = 'python', + css = 'css', + sass = 'css', + scss = 'css', + javascript = 'typescript', + javascriptreact = 'typescript', + typescript = 'typescript', + typescriptreact = 'typescript', + }, + groups = { + default = { + augend.integer.alias.decimal, -- nonnegative decimal number (0, 1, 2, 3, ...) + augend.integer.alias.hex, -- nonnegative hex number (0x01, 0x1a1f, etc.) + augend.date.alias['%Y/%m/%d'], -- date (2022/02/19, etc.) + }, + typescript = { + augend.integer.alias.decimal, -- nonnegative and negative decimal number + augend.constant.alias.bool, -- boolean value (true <-> false) + logical_alias, + augend.constant.new({ elements = { 'let', 'const' } }), + ordinal_numbers, + weekdays, + months, + }, + css = { + augend.integer.alias.decimal, -- nonnegative and negative decimal number + augend.hexcolor.new({ + case = 'lower', + }), + augend.hexcolor.new({ + case = 'upper', + }), + }, + markdown = { + augend.misc.alias.markdown_header, + ordinal_numbers, + weekdays, + months, + }, + json = { + augend.integer.alias.decimal, -- nonnegative and negative decimal number + augend.constant.alias.bool, -- boolean value (true <-> false) + augend.semver.alias.semver, -- versioning (v1.1.2) + }, + lua = { + augend.integer.alias.decimal, -- nonnegative and negative decimal number + augend.constant.alias.bool, -- boolean value (true <-> false) + augend.constant.new({ + elements = { 'and', 'or' }, + word = true, -- if false, "sand" is incremented into "sor", "doctor" into "doctand", etc. + cyclic = true, -- "or" is incremented into "and". + }), + ordinal_numbers, + weekdays, + months, + }, + python = { + augend.integer.alias.decimal, -- nonnegative and negative decimal number + capitalized_boolean, + logical_alias, + ordinal_numbers, + weekdays, + months, + }, + }, + } + require('dial.config').augends:register_group(opts.groups) + dials_by_ft = opts.dials_by_ft + end, } diff --git a/.config/nvim/lua/plugins/fzf-lua.lua b/.config/nvim/lua/plugins/fzf-lua.lua index 61510cf..5c1c7b0 100644 --- a/.config/nvim/lua/plugins/fzf-lua.lua +++ b/.config/nvim/lua/plugins/fzf-lua.lua @@ -3,9 +3,6 @@ return { dependencies = { 'nvim-tree/nvim-web-devicons' }, cmd = 'FzfLua', enabled = true, - config = function() - require 'plugins.config.fzf' - end, keys = { '', 'ff', @@ -37,4 +34,382 @@ return { { '', mode = 'i', desc = 'Complete line' }, { '', mode = 'i', desc = 'Complete path' }, }, + config = function() + local fzf = require 'fzf-lua' + local actions = require 'fzf-lua.actions' + local utils = require 'fzf-lua.utils' + + local function hl_validate(hl) + return not utils.is_hl_cleared(hl) and hl or nil + end + + local rg_cmd = + 'rg --files -l ".*" --follow --color=never --sortr=modified -g "!.git/" -g "!*.png" -g "!node_modules/" -g "!*.jpeg" -g "!*.jpg" -g "!*.ico" -g "!*.exe" -g "!*.out"' + + local m_keys = { + ['alt-enter'] = actions.file_tabedit, + ['ctrl-t'] = actions.file_tabedit, + ['ctrl-x'] = actions.file_split, + -- ['ctrl-q'] = actions.file_edit_or_qf, + } + -- calling `setup` is optional for customization + fzf.setup({ + defaults = { formatter = { 'path.filename_first', 2 } }, + fzf_opts = { + ['--layout'] = 'reverse', + ['--info'] = 'inline-right', + -- ['--tiebreak'] = 'end', + }, + winopts = { preview = { default = 'bat' } }, + hls = { + normal = hl_validate 'TelescopeNormal', + border = hl_validate 'TelescopeBorder', + title = hl_validate 'TelescopePromptTitle', + help_normal = hl_validate 'TelescopeNormal', + help_border = hl_validate 'TelescopeBorder', + preview_normal = hl_validate 'TelescopeNormal', + preview_border = hl_validate 'TelescopeBorder', + preview_title = hl_validate 'TelescopePreviewTitle', + -- builtin preview only + cursor = hl_validate 'Cursor', + cursorline = hl_validate 'TelescopeSelection', + cursorlinenr = hl_validate 'TelescopeSelection', + search = hl_validate 'IncSearch', + }, + keymap = { + builtin = { + true, + [''] = 'hide', + }, + fzf = { + ['ctrl-j'] = 'down', + ['ctrl-k'] = 'up', + ['ctrl-f'] = 'half-page-down', + ['ctrl-b'] = 'half-page-up', + ['alt-a'] = 'toggle-all', + ['alt-p'] = 'toggle-preview', + ['pgdn'] = 'preview-page-down', + ['pgup'] = 'preview-page-up', + ['alt-j'] = 'preview-down', + ['alt-k'] = 'preview-up', + ['shift-down'] = 'preview-page-down', + ['shift-up'] = 'preview-page-up', + ['ctrl-q'] = 'select-all+accept', + }, + }, + icons = { + ['?'] = { icon = '?', color = 'magenta' }, + ['M'] = { icon = '★', color = 'red' }, + ['D'] = { icon = '✗', color = 'red' }, + ['A'] = { icon = '+', color = 'green' }, + }, + files = { + fzf_opts = { + ['--layout'] = 'reverse', + -- ['--tiebreak'] = 'end', + ['--tiebreak'] = 'length', + }, + winopts = { + height = 0.55, + width = 0.65, + row = 0.52, + col = 0.47, + preview = { + ---@type 'wrap'|'nowrap' + wrap = 'nowrap', + ---@type 'hidden'|'nohidden' + hidden = 'hidden', + }, + }, + actions = m_keys, + }, + git = { + files = { + cmd = 'git ls-files --exclude-standard --cached --others', -- '--others' is used to show untracked files + actions = m_keys, + winopts = { + height = 0.55, + width = 0.65, + row = 0.52, + col = 0.47, + }, + previewer = false, + }, + status = { + actions = m_keys, + prompt = ' ❯ ', + }, + bcommits = { + actions = m_keys, + winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, + }, + commits = { + actions = m_keys, + winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, + }, + branches = { + winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, + cmd = "git branch --all --color | sed 's#remotes/origin/##g'", + cmd_add = { 'git', 'checkout', '-b' }, + }, + }, + buffers = { + ignore_current_buffer = true, + winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, + actions = vim.tbl_extend('force', m_keys, { + ['ctrl-d'] = actions.buf_delete, + ['ctrl-x'] = actions.buf_split, + ['ctrl-v'] = actions.buf_vsplit, + ['ctrl-q'] = actions.buf_edit_or_qf, + }), + }, + keymaps = { winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } } }, + helptags = { winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } } }, + grep = { + winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, + actions = m_keys, + rg_glob = true, + glob_flah = '--glob', + glob_separator = '%s%-%-', + }, + blines = { + actions = m_keys, + no_term_buffers = false, + winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, + }, + lsp = { + definitions = { + jump_to_single_result = true, + actions = m_keys, + }, + declarations = { + jump_to_single_result = true, + actions = m_keys, + }, + references = { + ignore_current_line = true, + actions = m_keys, + }, + symbols = { + actions = m_keys, + winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, + }, + finder = { + actions = m_keys, + winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, + }, + code_actions = { + actions = m_keys, + winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, + }, + }, + diagnostics = { + actions = m_keys, + winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, + }, + lines = { actions = m_keys }, + }) + local ok_dressing, _ = pcall(require, 'dressing') + if not ok_dressing then + fzf.register_ui_select() + end + + local function fzf_create_file() + local fzf = require 'fzf-lua' + local path = require 'fzf-lua.path' + local uv = vim.uv or vim.loop + local cmd = 'fd -t d . ' .. uv.cwd() + local function get_full_path(selected) + if #selected < 1 then + return + end + local entry = path.entry_to_file(selected[1], { cwd = uv.cwd() }) + if entry.path == '' then + return + end + + local fullpath = entry.path or entry.uri and entry.uri:match '^%a+://(.*)' + if not path.is_absolute(fullpath) then + fullpath = path.join({ uv.cwd(), fullpath }) + end + return fullpath + end + + --- This will create a file in the selected directory + ---@param split_dir ?"e" | "vs" | "sp" | "tabe" Default is "e" + ---@return function + local function perform_action(split_dir) + split_dir = split_dir or 'e' + return function(selected) + local fullpath = get_full_path(selected) + vim.ui.input({ prompt = 'File Name: ' }, function(name) + if name == nil then + return + end + vim.cmd(string.format('%s %s%s', split_dir, fullpath, name)) + vim.cmd 'w ++p' + end) + end + end + + fzf.fzf_exec(cmd, { + defaults = {}, + prompt = 'Create> ', + cwd = uv.cwd(), + cwd_prompt_shorten_len = 32, + cwd_prompt_shorten_val = 1, + fzf_opts = { + ['--tiebreak'] = 'end', + ['--preview-window'] = 'nohidden,50%', + ['--preview'] = { + type = 'cmd', + fn = function(selected) + local fullpath = get_full_path(selected) + local ls_cmd = 'command ls --color -hsv1F --group-directories-first' + local eza_cmd = + 'eza -al --color=always --icons=always --group-directories-first --no-user --no-permissions --no-time' + return string.format('%s %s', vim.fn.executable 'eza' == 1 and eza_cmd or ls_cmd, fullpath) + end, + }, + }, + fn_transform = function(x) + return fzf.make_entry.file(x, { file_icons = true, color_icons = true, cwd = uv.cwd() }) + end, + actions = { + ['default'] = perform_action(), + ['ctrl-x'] = perform_action 'sp', + ['ctrl-v'] = perform_action 'vs', + ['ctrl-t'] = perform_action 'tabe', + }, + }) + end + + local function project_files(default_opts) + local opts = vim.tbl_extend('force', { + fzf_opts = { + ['--layout'] = 'reverse', + ['--info'] = 'inline-right', + ['--tiebreak'] = 'index', + }, + }, default_opts or {}) + local fzf = require 'fzf-lua' + if vim.b.gitsigns_head then + -- Either use one of the following .local/bin/myscripts/sort_file.rs or .local/bin/myscripts/sorting_filev3.cpp + -- compile and then add to `PATH` + --`sort_files` is a program that sorts files based on modified time, recently modified files will be shown first + if vim.fn.executable 'sort_files' == 1 then + opts.cmd = 'git ls-files --exclude-standard --cached --others | sort_files' -- '--others' is used to show untracked files + else + vim.cmd 'echohl WarningMsg | echo "`sort_files` not found in `PATH`. Please compile the program" | echohl None' + end + fzf.git_files(opts) + else + opts.cmd = rg_cmd + fzf.files(opts) + end + end + + local keys = { + [''] = { project_files, { desc = 'Git [F]iles' } }, + ['ff'] = { + function() + fzf.files({ + cmd = rg_cmd, + fzf_opts = { + ['--layout'] = 'reverse', + ['--info'] = 'inline-right', + ['--tiebreak'] = 'index', + }, + }) + end, + { desc = '[F]iles' }, + }, + ['fr'] = { fzf.resume, { desc = '[R]esume' } }, + ['fs'] = { fzf.live_grep_native, { desc = '[S]earch(Project)' } }, + ['fc'] = { fzf_create_file, { desc = 'Create File' } }, + ['fS'] = { + function() + fzf.grep_curbuf({ winopts = { preview = { layout = 'vertical', { vertical = 'up:60%' } } } }) + end, + { desc = '[S]earch Current Buffer' }, + }, + ['fw'] = { fzf.grep_cword, { desc = '[W]ord under cursor' } }, + ['fW'] = { fzf.grep_cWORD, { desc = '[W]ord under cursor' } }, + ['fo'] = { + function() + fzf.oldfiles({ path_shorten = true }) + end, + { desc = '[O]ld Files' }, + }, + ['f/'] = { + function() + fzf.lgrep_curbuf({ + prompt = 'Buffer❫ ', + }) + end, + { desc = 'Grep buffer' }, + }, + ['*'] = { + function() + fzf.grep_curbuf({ + prompt = 'Buffer❫ ', + search = vim.fn.expand '', + }) + end, + { desc = 'Grep buffer with cword' }, + }, + ['fb'] = { fzf.buffers, { desc = '[B]uffers' } }, + ['fz'] = { fzf.spell_suggest, { desc = '[S]pelling' } }, + ['fk'] = { fzf.keymaps, { desc = '[K]eymaps' } }, + ['fh'] = { fzf.help_tags, { desc = '[H]elp Tags' } }, + ['fD'] = { fzf.diagnostics_document, { desc = '[D]iagnostics' } }, + ['fd'] = { + function() + fzf.files({ + cwd = vim.fn.expand '~/Documents/dotfiles', + cmd = rg_cmd .. ' --hidden', + fzf_opts = { + ['--layout'] = 'reverse', + ['--info'] = 'inline-right', + ['--tiebreak'] = 'index', + }, + }) + end, + { desc = '[D]otfiles' }, + }, + ['fn'] = { + function() + fzf.files({ + cwd = vim.fn.stdpath 'config', + cmd = rg_cmd, + fzf_opts = { + ['--layout'] = 'reverse', + ['--info'] = 'inline-right', + ['--tiebreak'] = 'index', + }, + }) + end, + { desc = '[N]eovim Config' }, + }, + ['fg'] = { fzf.git_status, { desc = '[S]tatus' } }, + ['gt'] = { fzf.git_status, { desc = '[S]tatus' } }, + ['gS'] = { fzf.git_stash, { desc = 'Stash' } }, + ['gb'] = { fzf.git_branches, { desc = '[B]ranches' } }, + ['gc'] = { fzf.git_commits, { desc = '[C]ommits' } }, + ['gC'] = { fzf.git_bcommits, { desc = '[B]ranch Commits' } }, + } + + vim.keymap.set('v', 'fw', fzf.grep_visual, { desc = 'Selection' }) + vim.keymap.set('i', '', fzf.complete_bline, { desc = 'Complete bline', silent = true, noremap = true }) + vim.keymap.set('i', '', fzf.complete_line, { desc = 'Complete line', silent = true, noremap = true }) + vim.keymap.set('i', '', fzf.complete_path, { desc = 'Complete path', silent = true, noremap = true }) + for key, value in pairs(keys) do + if value[1] == nil then + vim.print(key .. ' is nil') + goto continue + end + vim.keymap.set('n', key, value[1], vim.tbl_extend('force', { noremap = true, silent = true }, value[2] or {})) + ::continue:: + end + end, } diff --git a/.config/nvim/lua/plugins/heirline.lua b/.config/nvim/lua/plugins/heirline.lua index 8f2f4c7..12effc3 100644 --- a/.config/nvim/lua/plugins/heirline.lua +++ b/.config/nvim/lua/plugins/heirline.lua @@ -1,3 +1,4 @@ +---@diagnostic disable: missing-fields ---@type LazySpec return { 'rebelot/heirline.nvim', @@ -5,6 +6,179 @@ return { event = 'VeryLazy', dependencies = { 'nvim-tree/nvim-web-devicons', 'Zeioth/heirline-components.nvim' }, config = function() - require 'plugins.config.heirline' + local heirline = require 'heirline' + local lib = require 'heirline-components.all' + local hl = require 'heirline-components.core.hl' + local utils = require 'heirline.utils' + local conditions = require 'heirline.conditions' + + local FileNameBlock = { + -- let's first set up some attributes needed by this component and its children + init = function(self) + self.filename = vim.api.nvim_buf_get_name(0) + end, + } + -- We can now define some children separately and add them later + + local FileIcon = { + init = function(self) + local filename = self.filename + local extension = vim.fn.fnamemodify(filename, ':e') + self.icon, self.icon_color = + require('nvim-web-devicons').get_icon_color(filename, extension, { default = true }) + end, + provider = function(self) + return self.icon and (self.icon .. ' ') + end, + hl = function(self) + return { fg = self.icon_color } + end, + } + + local FileName = { + provider = function(self) + -- first, trim the pattern relative to the current directory. For other + -- options, see :h filename-modifers + local filename = vim.fn.fnamemodify(self.filename, ':.') + if filename == '' then + return '[No Name]' + end + -- now, if the filename would occupy more than 1/4th of the available + -- space, we trim the file path to its initials + -- See Flexible Components section below for dynamic truncation + if not conditions.width_percent_below(#filename, 0.25) then + filename = vim.fn.pathshorten(filename) + end + return filename + end, + hl = { fg = utils.get_highlight('Directory').fg }, + } + + local FileFlags = { + { + condition = function() + return vim.bo.modified + end, + provider = '[+]', + hl = { fg = '#73d936' }, + }, + { + condition = function() + return not vim.bo.modifiable or vim.bo.readonly + end, + provider = '', + hl = { fg = '#cc8c3c' }, + }, + } + + -- Now, let's say that we want the filename color to change if the buffer is + -- modified. Of course, we could do that directly using the FileName.hl field, + -- but we'll see how easy it is to alter existing components using a "modifier" + -- component + + local FileNameModifer = { + hl = function() + if vim.bo.modified then + -- use `force` because we need to override the child's hl foreground + return { fg = 'cyan', bold = true, force = true } + end + end, + } + + -- let's add the children to our FileNameBlock component + FileNameBlock = utils.insert( + FileNameBlock, + -- FileIcon, + utils.insert(FileNameModifer, FileName), -- a new table where FileName is a child of FileNameModifier + FileFlags, + { provider = '%<' } -- this means that the statusline is cut here when there's not enough space + ) + -- Setup + vim.opt.laststatus = 3 + lib.init.subscribe_to_events() + heirline.load_colors(lib.hl.get_colors()) + heirline.setup({ + opts = { + disable_winbar_cb = function(args) -- We do this to avoid showing it on the greeter. + local is_disabled = not require('heirline-components.buffer').is_valid(args.buf) + or lib.condition.buffer_matches({ + buftype = { 'terminal', 'prompt', 'nofile', 'help', 'quickfix' }, + filetype = { 'NvimTree', 'neo%-tree', 'dashboard', 'Outline', 'aerial' }, + }, args.buf) + return is_disabled + end, + }, + tabline = { -- UI upper bar + lib.component.tabline_conditional_padding(), + lib.component.tabline_buffers({ + hl = function(self) + local tab_type = self.tab_type + if self._show_picker and self.tab_type ~= 'buffer_active' then + tab_type = 'buffer_visible' + end + if tab_type == 'buffer_active' then + -- tokyonight + -- local fg = '#7ca1f2' + -- local bg = '#393d56' + -- rose-pine + local fg = '#f2e9e1' + local bg = '#214655' + -- gruber-darker + -- local fg = '#f2e9e1' + -- local bg = '#806a4d' + return vim.tbl_extend('force', hl.get_attributes(tab_type), { fg = fg, bg = bg }) + else + return hl.get_attributes(tab_type) + end + end, + }), + lib.component.fill(), + lib.component.tabline_tabpages({}), + }, + winbar = { -- UI breadcrumbs bar + init = function(self) + self.bufnr = vim.api.nvim_get_current_buf() + end, + -- Regular winbar + -- lib.component.neotree(), + -- lib.component.compiler_play(), + -- lib.component.fill(), + { + hl = hl.get_attributes('winbar', true), + condition = function() + return require('nvim-navic').is_available() + end, + provider = function() + return require('nvim-navic').get_location({ highlight = true }) + end, + update = 'CursorMoved', + }, + -- lib.component.fill(), + -- lib.component.compiler_redo(), + -- lib.component.aerial(), + }, + -- statuscolumn = { -- UI left column + -- init = function(self) + -- self.bufnr = vim.api.nvim_get_current_buf() + -- end, + -- lib.component.foldcolumn(), + -- lib.component.numbercolumn(), + -- lib.component.signcolumn(), + -- } or nil, + statusline = { -- UI statusbar + hl = { fg = 'fg', bg = 'bg' }, + lib.component.mode(), + lib.component.git_branch(), + FileNameBlock, + lib.component.file_info(), + lib.component.git_diff(), + lib.component.diagnostics(), + lib.component.fill(), + lib.component.fill(), + lib.component.lsp(), + lib.component.nav(), + lib.component.mode({ surround = { separator = 'right' } }), + }, + }) end, } diff --git a/.config/nvim/lua/plugins/init.lua b/.config/nvim/lua/plugins/init.lua new file mode 100644 index 0000000..019eb09 --- /dev/null +++ b/.config/nvim/lua/plugins/init.lua @@ -0,0 +1,333 @@ +---@type LazySpec +return { + 'iguanacucumber/magazine.nvim', + name = 'nvim-cmp', -- Otherwise highlighting gets messed up + enabled = true, + event = 'BufReadPre', + dependencies = { + 'hrsh7th/cmp-nvim-lsp', + 'hrsh7th/cmp-buffer', + -- 'hrsh7th/cmp-path', + 'https://codeberg.org/FelipeLema/cmp-async-path', + 'hrsh7th/cmp-cmdline', + 'lukas-reineke/cmp-rg', + -- 'lukas-reineke/cmp-under-comparator', + 'octaltree/cmp-look', + 'saadparwaiz1/cmp_luasnip', + { + 'L3MON4D3/LuaSnip', + build = 'make install_jsregexp', + dependencies = { 'rafamadriz/friendly-snippets' }, + event = 'User BaseFile', + opts = { history = true, delete_check_events = 'TextChanged', region_check_events = 'CursorMoved' }, + config = function(_, opts) + if opts then + require('luasnip').config.setup(opts) + end + + vim.tbl_map(function(type) + require('luasnip.loaders.from_' .. type).lazy_load() + end, { 'vscode', 'snipmate', 'lua' }) + + local extends = { + typescript = { 'tsdoc' }, + javascript = { 'jsdoc' }, + lua = { 'luadoc' }, + python = { 'pydoc' }, + rust = { 'rustdoc' }, + cs = { 'csharpdoc' }, + java = { 'javadoc' }, + c = { 'cdoc' }, + cpp = { 'cppdoc' }, + php = { 'phpdoc' }, + kotlin = { 'kdoc' }, + ruby = { 'rdoc' }, + sh = { 'shelldoc' }, + } + -- friendly-snippets - enable standardized comments snippets + for ft, snips in pairs(extends) do + require('luasnip').filetype_extend(ft, snips) + end + end, + }, + 'onsails/lspkind.nvim', + { + 'folke/lazydev.nvim', + ft = 'lua', -- only load on lua files + opts = { + library = { 'lazy.nvim', { path = 'luvit-meta/library', words = { 'vim%.uv' } } }, + }, + }, + { 'Bilal2453/luvit-meta', lazy = true }, + }, + config = function() + local cmp = require 'cmp' + local types = require 'cmp.types' + local sources = require 'cmp.config.sources' + local compare = require 'cmp.config.compare' + local lspkind = require 'lspkind' + local snippet = 'luasnip' + local luasnip = require 'luasnip' + + local function feedkey(key, mode) + vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(key, true, true, true), mode, true) + end + local function has_words_before() + unpack = unpack or table.unpack + local line, col = unpack(vim.api.nvim_win_get_cursor(0)) + return col ~= 0 and vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]:sub(col, col):match '%s' == nil + end + + local function deprio(kind) + return function(e1, e2) + if e1:get_kind() == kind then + return false + end + if e2:get_kind() == kind then + return true + end + end + end + + --- detect if the current completion item is an emmet completion item + --- @param entry cmp.Entry + --- @return boolean + local function isEmmet(entry) + return ( + entry:get_kind() == require('cmp.types').lsp.CompletionItemKind.Text + or entry:get_kind() == require('cmp.types').lsp.CompletionItemKind.Snippet + ) + and ( + entry.source:get_debug_name() == 'nvim_lsp:emmet_language_server' + or entry.source:get_debug_name() == 'nvim_lsp:emmet_ls' + ) + end + + cmp.setup({ + snippet = { + expand = function(args) + luasnip.lsp_expand(args.body) + end, + }, + experimental = { ghost_text = false, native_menu = false }, + window = { completion = cmp.config.window.bordered(), documentation = cmp.config.window.bordered() }, + duplicates = { + nvim_lsp = 1, + lazydev = 1, + [snippet] = 1, + cmp_tabnine = 1, + buffer = 1, + path = 1, + }, + + mapping = { + [''] = cmp.mapping({ i = cmp.mapping.scroll_docs(-4) }), + [''] = cmp.mapping({ i = cmp.mapping.scroll_docs(4) }), + [''] = cmp.mapping.complete(), + [''] = cmp.mapping.close(), + [''] = cmp.mapping({ + i = cmp.mapping.confirm({ behavior = cmp.ConfirmBehavior.Replace, select = true }), + c = cmp.mapping.confirm({ behavior = cmp.ConfirmBehavior.Replace, select = false }), + }), + [''] = cmp.mapping({ + i = cmp.mapping.confirm({ behavior = cmp.ConfirmBehavior.Replace, select = true }), + c = cmp.mapping.confirm({ behavior = cmp.ConfirmBehavior.Replace, select = false }), + }), + [''] = cmp.mapping({ + i = function(fallback) + if cmp.visible() then + cmp.select_next_item({ behavior = cmp.SelectBehavior.Select }) + else + fallback() + end + end, + }), + [''] = cmp.mapping({ + i = function(fallback) + if cmp.visible() then + cmp.select_prev_item({ behavior = cmp.SelectBehavior.Select }) + else + fallback() + end + end, + }), + [''] = cmp.mapping({ + c = function() + if cmp.visible() then + cmp.select_next_item({ behavior = cmp.SelectBehavior.Select }) + else + feedkey('', 'n') + end + end, + i = function(fallback) + if cmp.visible() then + cmp.select_next_item({ behavior = cmp.SelectBehavior.Select }) + else + fallback() + end + end, + }), + [''] = cmp.mapping({ + c = function() + if cmp.visible() then + cmp.select_prev_item({ behavior = cmp.SelectBehavior.Select }) + else + feedkey('', 'n') + end + end, + i = function(fallback) + if cmp.visible() then + cmp.select_prev_item({ behavior = cmp.SelectBehavior.Select }) + else + fallback() + end + end, + }), + [''] = cmp.mapping.complete({ + config = { sources = { { name = snippet } } }, + }), + [''] = cmp.mapping.complete({ + config = { + sources = { + { + name = 'nvim_lsp', + entry_filter = function(entry) + return isEmmet(entry) + end, + }, + }, + }, + }), + [''] = cmp.mapping(function(fallback) + if cmp.visible() then + cmp.select_next_item() + -- elseif vim.snippet.active({ direction = 1 }) then + -- return 'lua vim.snippet.jump(1)' + -- vim.snippet.jump(1) + -- elseif vim.fn['vsnip#available'](1) == 1 then + -- feedkey('(vsnip-expand-or-jump)', '') + elseif luasnip.expand_or_jumpable() then + luasnip.expand_or_jump() + elseif has_words_before() then + cmp.complete() + else + fallback() + end + end, { 'i', 's' }), + + [''] = cmp.mapping(function() + if cmp.visible() then + cmp.select_prev_item() + elseif luasnip.jumpable(-1) then + luasnip.jump(-1) + -- elseif vim.snippet.active({ direction = -1 }) then + -- return 'lua vim.snippet.jump(-1)' + -- vim.snippet.jump(-1) + -- elseif vim.fn['vsnip#jumpable'](-1) == 1 then + -- feedkey('(vsnip-jump-prev)', '') + end + end, { 'i', 's' }), + }, + sources = sources({ + { + name = 'nvim_lsp', + priority = 100, + max_item_count = 20, + entry_filter = function(entry) + return not isEmmet(entry) + end, + }, + { name = 'lazydev', priority = 95 }, + { name = snippet, priority = 90 }, + { + name = 'buffer', + max_item_count = 10, + option = { + keyword_length = 2, + -- get_bufnrs = function() + -- local bufIsSmall = function(bufnr) + -- return vim.api.nvim_buf_line_count(bufnr) < 2000 + -- end + -- return vim.tbl_filter(bufIsSmall, vim.api.nvim_list_bufs()) + -- end, + }, + priority = 40, + }, + { + name = 'rg', + keyword_length = 3, + max_item_count = 10, + priority_weight = 50, + option = { + additional_arguments = '--smart-case --hidden', + set_filetype = true, + marker = ' ❰❰❰', + }, + -- entry_filter = function(entry) + -- return not entry.exact + -- end, + }, + -- { name = 'path', priority = 50 }, + { name = 'async_path', priority = 50, option = { trailing_slash = false } }, + { + name = 'look', + keyword_length = 5, + priority = 30, + option = { + convert_case = true, + loud = true, + --dict = '/usr/share/dict/words' + }, + }, + }), + sorting = { + priority_weight = 100, + comparators = { + deprio(types.lsp.CompletionItemKind.Text), + compare.exact, + compare.offset, + compare.score, + compare.length, + compare.recently_used, + compare.kind, + compare.locality, + compare.order, + }, + }, + ---@diagnostic disable-next-line: missing-fields + formatting = { + fields = { 'kind', 'abbr', 'menu' }, + format = lspkind.cmp_format({ + mode = 'symbol', + maxwidth = 50, + ellipsis_char = '...', + symbol_map = { Copilot = '' }, + }), + }, + }) + cmp.setup.cmdline(':', { + sources = sources({ + { + name = 'cmdline', + option = { + ignore_cmds = { 'Man', '!', 'find', 'fin' }, + }, + }, + { name = 'path' }, + }), + matching = { disallow_symbol_nonprefix_matching = false }, + mapping = cmp.mapping.preset.cmdline(), + formatting = { fields = { 'abbr' } }, + window = { completion = cmp.config.window.bordered({ col_offset = 0 }) }, + }) + + cmp.setup.cmdline({ '/', '?' }, { + sources = sources({ + { name = 'buffer' }, + }), + mapping = cmp.mapping.preset.cmdline(), + formatting = { fields = { 'abbr' } }, + window = { completion = cmp.config.window.bordered({ col_offset = 0 }) }, + }) + end, +} diff --git a/.config/nvim/lua/plugins/lsp/astrolsp.lua b/.config/nvim/lua/plugins/lsp/astrolsp.lua index 9129fea..4b30f3e 100644 --- a/.config/nvim/lua/plugins/lsp/astrolsp.lua +++ b/.config/nvim/lua/plugins/lsp/astrolsp.lua @@ -22,6 +22,353 @@ return { name = 'nvim-cmp', -- Otherwise highlighting gets messed up }, }, - opts = require('plugins.config.astrolsp').opts, - -- config = require('plugins.config.astrolsp').config, + opts = { + -- Configuration table of features provided by AstroLSP + features = { + autoformat = true, -- enable or disable auto formatting on start + codelens = true, -- enable/disable codelens refresh on start + inlay_hints = false, -- enable/disable inlay hints on start + semantic_tokens = true, -- enable/disable semantic token highlighting + }, + -- Configure buffer local auto commands to add when attaching a language server + autocmds = { + -- first key is the `augroup` (:h augroup) + lsp_document_highlight = { + cond = 'textDocument/documentHighlight', + -- list of auto commands to set + { + -- events to trigger + event = { 'CursorHold', 'CursorHoldI' }, + -- the rest of the autocmd options (:h nvim_create_autocmd) + desc = 'Document Highlighting', + callback = vim.lsp.buf.document_highlight, + }, + { + event = { 'CursorMoved', 'CursorMovedI', 'BufLeave' }, + desc = 'Document Highlighting Clear', + callback = vim.lsp.buf.clear_references, + }, + }, + }, + commands = { + Format = { + function() + vim.lsp.buf.format({ async = true }) + end, + cond = 'textDocument/formatting', + desc = 'Format file with LSP', + }, + ImportsOrganize = { + function() + vim.lsp.buf.code_action({ + context = { only = { 'source.organizeImports' } }, + apply = true, + }) + end, + cond = 'textDocument/codeAction', + desc = 'Organize Imports', + }, + ImportsRemove = { + function() + vim.lsp.buf.code_action({ + context = { only = { 'source.removeUnused' } }, + apply = true, + }) + end, + cond = 'textDocument/codeAction', + desc = 'Remove Unused Imports', + }, + FixAll = { + function() + vim.lsp.buf.code_action({ + context = { only = { 'source.fixAll' } }, + apply = true, + }) + end, + cond = 'textDocument/codeAction', + desc = 'Fix All fixable diagnostics', + }, + }, + capabilities = { + textDocument = { foldingRange = { dynamicRegistration = false, lineFoldingOnly = true } }, + workspace = { + didChangeWatchedFiles = vim.fn.has 'nvim-0.10' == 0 and { dynamicRegistration = true }, + }, + }, + config = { + bashls = { + settings = { bashIde = { highlightParsingErrors = true } }, + }, + }, + mappings = { + n = { + K = { vim.lsp.buf.hover, desc = 'Hover', cond = 'textDocument/hover' }, + gl = { vim.diagnostic.open_float, desc = 'Hover diagnostics' }, + ['le'] = { vim.diagnostic.open_float, desc = 'Hover diagnostics' }, + ['ld'] = { + function() + local ok, fzf = pcall(require, 'fzf-lua') + if not ok then + vim.lsp.buf.definition() + else + fzf.lsp_definitions({ + jump_to_single_result = true, + winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, + }) + end + end, + desc = 'Goto definition', + cond = 'textDocument/definition', + }, + gd = { + function() + local ok, fzf = pcall(require, 'fzf-lua') + if not ok then + vim.lsp.buf.definition() + else + fzf.lsp_definitions({ + jump_to_single_result = true, + winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, + }) + end + end, + desc = 'Goto definition', + cond = 'textDocument/definition', + }, + ['lf'] = { + function() + vim.lsp.buf.code_action({ + context = { only = { 'source.fixAll' } }, + apply = true, + }) + end, + desc = 'Fix All', + cond = 'textDocument/codeAction', + }, + ['lo'] = { + function() + vim.lsp.buf.code_action({ + context = { only = { 'source.organizeImports' } }, + apply = true, + }) + vim.lsp.buf.code_action({ context = { only = { 'source.removeUnused' } }, apply = true }) + end, + desc = 'Oraganize imports', + cond = 'textDocument/codeAction', + }, + ['li'] = { + function() + local ok, fzf = pcall(require, 'fzf-lua') + if not ok then + vim.lsp.buf.implementation() + else + fzf.lsp_implementations() + end + end, + desc = 'Goto implementation', + cond = 'textDocument/implementation', + }, + -- condition for only server with declaration capabilities + ['lD'] = { + function() + local ok, fzf = pcall(require, 'fzf-lua') + if not ok then + vim.lsp.buf.declaration() + else + fzf.lsp_declarations({ + jump_to_single_result = true, + winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, + }) + end + end, + desc = 'Goto Declaration', + cond = 'textDocument/declaration', + }, + ['lt'] = { + function() + local ok, fzf = pcall(require, 'fzf-lua') + if not ok then + vim.lsp.buf.type_definition() + else + fzf.lsp_typedefs() + end + end, + desc = 'Type definition', + cond = 'textDocument/typeDefinition', + }, + ['F'] = { + function() + vim.cmd [[EslintFixAll]] + end, + cond = function(client) + return client.name == 'eslint' + end, + }, + gr = { + function() + local ok, fzf = pcall(require, 'fzf-lua') + if not ok then + vim.lsp.buf.references() + else + fzf.lsp_references({ + jump_to_single_result = true, + winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, + }) + end + end, + desc = 'Goto references', + cond = 'textDocument/references', + }, + ['lR'] = { + function() + local ok, fzf = pcall(require, 'fzf-lua') + if not ok then + vim.lsp.buf.references() + else + fzf.lsp_references({ + jump_to_single_result = true, + winopts = { preview = { layout = 'vertical', vertical = 'up:60%' } }, + }) + end + end, + desc = 'Goto references', + cond = 'textDocument/references', + }, + [']e'] = { + function() + vim.diagnostic.goto_next({ severity = vim.diagnostic.severity.ERROR }) + end, + desc = 'Goto Next Error', + }, + ['[e'] = { + function() + vim.diagnostic.goto_prev({ severity = vim.diagnostic.severity.ERROR }) + end, + desc = 'Goto Next Error', + }, + [']d'] = { + vim.diagnostic.goto_next, + desc = 'Goto Next diagnostic', + }, + ['[d'] = { + vim.diagnostic.goto_prev, + desc = 'Goto Next diagnostic', + }, + ['lw'] = { + function() + local ok, fzf = pcall(require, 'fzf-lua') + if not ok then + vim.lsp.buf.document_symbol() + else + fzf.lsp_document_symbols() + end + end, + desc = 'Document symbols', + cond = 'textDocument/documentSymbol', + }, + ['lW'] = { + function() + local ok, fzf = pcall(require, 'fzf-lua') + if not ok then + vim.lsp.buf.workspace_symbol() + else + fzf.lsp_workspace_symbols() + end + end, + desc = 'Workspace symbols', + cond = 'workspace/symbol', + }, + [''] = { + vim.lsp.buf.rename, + desc = 'Rename', + cond = 'textDocument/rename', + }, + ['lr'] = { + vim.lsp.buf.rename, + desc = 'Rename', + cond = 'textDocument/rename', + }, + ['la'] = { + function() + local ok, fzf = pcall(require, 'fzf-lua') + if not ok then + vim.lsp.buf.code_action() + else + fzf.lsp_code_actions() + end + end, + desc = 'Code actions', + cond = 'textDocument/codeAction', + }, + ['lI'] = { + function() + vim.cmd 'LspInfo' + end, + desc = 'LspInfo', + }, + -- condition with a full function with `client` and `bufnr` + ['uY'] = { + function() + require('astrolsp.toggles').buffer_semantic_tokens() + end, + desc = 'Toggle LSP semantic highlight (buffer)', + cond = function(client) + return client.server_capabilities.semanticTokensProvider and vim.lsp.semantic_tokens + end, + }, + ['uI'] = { + function() + require('astrolsp.toggles').buffer_inlay_hints() + end, + desc = 'Toggle LSP inlay highlight (buffer)', + cond = function(client) + return client.server_capabilities.inlayHintProvider and vim.lsp.inlay_hint + end, + }, + }, + i = { + [''] = { + vim.lsp.buf.signature_help, + desc = 'Signature help', + cond = 'textDocument/signatureHelp', + }, + }, + x = { + ['la'] = { + function() + local ok, fzf = pcall(require, 'fzf-lua') + if not ok then + vim.lsp.buf.code_action() + else + fzf.lsp_code_actions() + end + end, + desc = 'Code actions', + cond = 'textDocument/codeAction', + }, + }, + }, + handlers = { + function(server, opts) + local ok, cmp_nvim_lsp = pcall(require, 'cmp_nvim_lsp') + if ok then + opts.capabilities = cmp_nvim_lsp.default_capabilities(opts.capabilities) + end + require('lspconfig')[server].setup(opts) + end, + efm = false, + }, + -- A list like table of servers that should be setup, useful for enabling language servers not installed with Mason. + servers = { + 'gleam', + 'zls', + 'roc_ls', + 'nim_langserver' --[[, 'rust_analyzer' ]], + }, + on_attach = function(client, bufnr) + if client.supports_method 'textDocument/documentSymbol' then + require('nvim-navic').attach(client, bufnr) + end + end, + }, } diff --git a/.config/nvim/lua/plugins/lsp/elixir.lua b/.config/nvim/lua/plugins/lsp/elixir.lua index e7fb659..ce0c642 100644 --- a/.config/nvim/lua/plugins/lsp/elixir.lua +++ b/.config/nvim/lua/plugins/lsp/elixir.lua @@ -48,9 +48,9 @@ return { }), on_attach = function(client, bufnr) opts.on_attach(client, bufnr) - vim.keymap.set('n', 'lp', ':ElixirFromPipe', { buffer = true, noremap = true }) - vim.keymap.set('n', 'lP', ':ElixirToPipe', { buffer = true, noremap = true }) - vim.keymap.set('v', 'lm', ':ElixirExpandMacro', { buffer = true, noremap = true }) + vim.keymap.set('n', 'lp', ':ElixirFromPipe', { buffer = bufnr, noremap = true }) + vim.keymap.set('n', 'lP', ':ElixirToPipe', { buffer = bufnr, noremap = true }) + vim.keymap.set('v', 'lm', ':ElixirExpandMacro', { buffer = bufnr, noremap = true }) end, }, }) diff --git a/.config/nvim/lua/plugins/lsp/lsp.lua b/.config/nvim/lua/plugins/lsp/lsp.lua deleted file mode 100644 index 1aed007..0000000 --- a/.config/nvim/lua/plugins/lsp/lsp.lua +++ /dev/null @@ -1,653 +0,0 @@ -if true then - ---@type LazySpec - return {} -end ----@type LazySpec -return { - 'neovim/nvim-lspconfig', - event = 'BufReadPre', - dependencies = { - { - 'AstroNvim/astrolsp', - dependencies = { - { 'b0o/schemastore.nvim', ft = { 'json', 'jsonc', 'json5', 'yaml' }, version = false }, - { - 'pmizio/typescript-tools.nvim', - dependencies = 'nvim-lua/plenary.nvim', - ft = { 'javascript', 'typescript', 'javascriptreact', 'typescriptreact' }, - enabled = false, - }, - { - 'yioneko/nvim-vtsls', - lazy = true, - opts = {}, - config = function(_, opts) - require('vtsls').config(opts) - end, - }, - { - 'mrcjkb/rustaceanvim', - enabled = false, - version = '^4', -- Recommended - lazy = false, -- This plugin is already lazy - }, - { - 'SmiteshP/nvim-navic', - init = function() - vim.g.navic_silence = true - end, - opts = { - highlight = true, - depth_limit = 5, - lazy_update_context = true, - }, - }, - { - 'elixir-tools/elixir-tools.nvim', - version = '*', - event = { 'BufReadPre', 'BufNewFile' }, - dependencies = { - 'nvim-lua/plenary.nvim', - }, - }, - }, - ---@type AstroLSPConfig - opts = { - -- Configuration table of features provided by AstroLSP - features = { - autoformat = true, -- enable or disable auto formatting on start - codelens = true, -- enable/disable codelens refresh on start - inlay_hints = false, -- enable/disable inlay hints on start - semantic_tokens = true, -- enable/disable semantic token highlighting - }, - -- Configure buffer local auto commands to add when attaching a language server - autocmds = { - -- first key is the `augroup` (:h augroup) - lsp_document_highlight = { - cond = 'textDocument/documentHighlight', - -- list of auto commands to set - { - -- events to trigger - event = { 'CursorHold', 'CursorHoldI' }, - -- the rest of the autocmd options (:h nvim_create_autocmd) - desc = 'Document Highlighting', - callback = vim.lsp.buf.document_highlight, - }, - { - event = { 'CursorMoved', 'CursorMovedI', 'BufLeave' }, - desc = 'Document Highlighting Clear', - callback = vim.lsp.buf.clear_references, - }, - }, - svelte_auto_format = { - cond = function(client) - return client.name == 'svelte' - end, - { - event = 'BufWritePost', - pattern = { '*.js', '*.ts' }, - desc = 'Svelte auto format', - callback = function(ctx) - -- get the current lsp client - -- and notify the server that the file has been changed - vim.lsp.buf_notify(0, '$/onDidChangeTsOrJsFile', { uri = ctx.file }) - -- client.notify("$/onDidChangeTsOrJsFile", { uri = ctx.file }) - end, - }, - }, - }, - -- Configure buffer local user commands to add when attaching a language server - commands = { - Format = { - function() - vim.lsp.buf.format({ async = true }) - end, - cond = 'textDocument/formatting', - desc = 'Format file with LSP', - }, - }, - -- Configure default capabilities for language servers (`:h vim.lsp.protocol.make_client.capabilities()`) - capabilities = { - textDocument = { foldingRange = { dynamicRegistration = false, lineFoldingOnly = true } }, - }, - -- Configure language servers for `lspconfig` (`:h lspconfig-setup`) - config = { - lua_ls = { - settings = { - Lua = { - diagnostics = { - enable = true, - globals = { 'vim', 'describe' }, - disable = { 'lowercase-global' }, - }, - workspace = { - checkThirdParty = false, - library = { - vim.env.VIMRUNTIME, - }, - }, - runtime = { version = 'LuaJIT' }, - telemetry = { enable = false }, - completion = { callSnippet = 'Replace' }, - hint = { enable = true, arrayIndex = 'Disable' }, - }, - }, - }, - clangd = { - capabilities = { - offsetEncoding = { 'utf-16' }, - clangdInlayHintsProvider = true, - }, - setting = { - InlayHints = { - Enabled = true, - ParameterNames = true, - DeducedTypes = true, - }, - }, - cmd = { - -- 'clangd', - -- '--background-index', - -- '--clang-tidy', - -- '--suggest-missing-includes', - -- '--header-insertion=iwyu', - -- '--completion-style=detailed', - -- '--function-arg-placeholders', - -- '--pch-storage=memory', - -- '--fallback-style=llvm', - 'clangd', - '--background-index', - '--clang-tidy', - '--suggest-missing-includes', - '--header-insertion-decorators', - '--all-scopes-completion', - '--cross-file-rename', - '--log=info', - '--completion-style=detailed', - -- "--enable-config", -- clangd 11+ supports reading from .clangd configuration file - '--offset-encoding=utf-16', - '--header-insertion=never', - }, - }, - gopls = { - settings = { - gopls = { - experimentalPostfixCompletions = true, - analyses = { unusedparams = true, shadow = true, nilness = true, unusedwrite = true }, - hints = { - assignVariableTypes = true, - compositeLiteralFields = true, - compositeLiteralTypes = true, - constantValues = true, - functionTypeParameters = true, - parameterNames = true, - rangeVariableTypes = true, - }, - staticcheck = true, - ui = { - completion = { - usePlaceholders = true, - }, - }, - codelenses = { - usePlaceholders = true, - }, - }, - }, - }, - svelte = { - settings = { - svelte = { - ['enable-ts-plugin'] = true, - plugin = { svelte = { defaultScriptLanguage = 'typescript' } }, - }, - }, - }, - pyright = { - settings = { - python = { - analysis = { - autoImportCompletions = true, - -- typeCheckingMode = 'basic', - }, - exclude = { '**/node_modules', '**/__pycache__' }, - }, - }, - }, - nim_langserver = { - settings = { - nim = { - nimsuggestPath = vim.fn.expand '~/.local/share/nim-2.0.4/bin/nimsuggest', - }, - }, - }, - bashls = { - settings = { bashIde = { highlightParsingErrors = true } }, - }, - cssls = { - settings = { - css = { - validate = true, - completion = { - triggerPropertyValueCompletion = true, - completePropertyWithSemicolon = true, - }, - lint = { - compatibleVendorPrefixes = 'warn', - duplicateProperties = 'warn', - boxModel = 'warn', - unknownVendorSpecificProperties = 'warn', - float = 'error', - }, - }, - scss = { - validate = true, - completion = { - triggerPropertyValueCompletion = true, - completePropertyWithSemicolon = true, - }, - lint = { - compatibleVendorPrefixes = 'warn', - duplicateProperties = 'warn', - boxModel = 'warn', - unknownVendorSpecificProperties = 'warn', - float = 'error', - }, - }, - }, - }, - rust_analyzer = { - settings = { - ['rust-analyzer'] = { - imports = { - granularity = { - group = 'module', - }, - prefix = 'self', - }, - cargo = { - buildScripts = { - enable = true, - }, - }, - procMacro = { - enable = true, - }, - }, - }, - }, - }, - -- Configuration of mappings added when attaching a language server during the core `on_attach` function - -- The first key into the table is the vim map mode (`:h map-modes`), and the value is a table of entries to be passed to `vim.keymap.set` (`:h vim.keymap.set`): - -- - The key is the first parameter or the vim mode (only a single mode supported) and the value is a table of keymaps within that mode: - -- - The first element with no key in the table is the action (the 2nd parameter) and the rest of the keys/value pairs are options for the third parameter. - -- There is also a special `cond` key which can either be a string of a language server capability or a function with `client` and `bufnr` parameters that returns a boolean of whether or not the mapping is added. - mappings = { - -- map mode (:h map-modes) - n = { - K = { vim.lsp.buf.hover, desc = 'Hover', cond = 'textDocument/hover' }, - gl = { vim.diagnostic.open_float, desc = 'Hover diagnostics' }, - gd = { - vim.lsp.buf.definition, - desc = 'Goto definition', - cond = 'textDocument/definition', - }, - gs = { - function() - vim.lsp.buf.code_action({ - context = { only = { 'source.organizeImports' } }, - apply = true, - }) - vim.lsp.buf.code_action({ context = { only = { 'source.removeUnused' } }, apply = true }) - end, - desc = 'Oraganize imports', - cond = 'textDocument/codeAction', - }, - gi = { - vim.lsp.buf.implementation, - desc = 'Goto implementation', - cond = 'textDocument/implementation', - }, - -- condition for only server with declaration capabilities - gD = { vim.lsp.buf.declaration, desc = 'Goto Declaration', cond = 'textDocument/declaration' }, - gt = { - vim.lsp.buf.type_definition, - desc = 'Type definition', - cond = 'textDocument/typeDefinition', - }, - ['g='] = { - function() - vim.cmd [[EslintFixAll]] - end, - cond = function(client) - return client.name == 'eslint' - end, - }, - gr = { - vim.lsp.buf.references, - desc = 'Goto references', - cond = 'textDocument/references', - }, - [']e'] = { - function() - vim.diagnostic.goto_next({ severity = vim.diagnostic.severity.ERROR }) - end, - desc = 'Goto Next Error', - }, - ['[e'] = { - function() - vim.diagnostic.goto_prev({ severity = vim.diagnostic.severity.ERROR }) - end, - desc = 'Goto Next Error', - }, - [']d'] = { - vim.diagnostic.goto_next, - desc = 'Goto Next diagnostic', - }, - ['[d'] = { - vim.diagnostic.goto_prev, - desc = 'Goto Next diagnostic', - }, - gw = { - vim.lsp.buf.document_symbol, - desc = 'Document symbols', - cond = 'textDocument/documentSymbol', - }, - gW = { - vim.lsp.buf.workspace_symbol, - desc = 'Workspace symbols', - cond = 'workspace/symbol', - }, - [''] = { - vim.lsp.buf.rename, - desc = 'Rename', - cond = 'textDocument/rename', - }, - ['lr'] = { - vim.lsp.buf.rename, - desc = 'Rename', - cond = 'textDocument/rename', - }, - ['la'] = { - vim.lsp.buf.code_action, - desc = 'Code actions', - cond = 'textDocument/codeAction', - }, - ['lI'] = { - function() - vim.cmd 'LspInfo' - end, - desc = 'LspInfo', - }, - -- condition with a full function with `client` and `bufnr` - ['uY'] = { - function() - require('astrolsp.toggles').buffer_semantic_tokens() - end, - desc = 'Toggle LSP semantic highlight (buffer)', - cond = function(client) - return client.server_capabilities.semanticTokensProvider and vim.lsp.semantic_tokens - end, - }, - ['uI'] = { - function() - require('astrolsp.toggles').buffer_inlay_hints() - end, - desc = 'Toggle LSP semantic highlight (buffer)', - -- cond = function(client) - -- return client.server_capabilities.semanticTokensProvider and vim.lsp.semantic_tokens - -- end, - }, - }, - i = { - [''] = { - vim.lsp.buf.signature_help, - desc = 'Signature help', - cond = 'textDocument/signatureHelp', - }, - }, - }, - - handlers = { - function(server, opts) - opts.capabilities = require('cmp_nvim_lsp').default_capabilities(opts.capabilities) - require('lspconfig')[server].setup(opts) - end, - tsserver = false, - vtsls = function(server, opts) - local default_attach = opts.on_attach - opts.settings = { - complete_function_calls = true, - vtsls = { - enableMoveToFileCodeAction = true, - autoUseWorkspaceTsdk = true, - experimental = { - completion = { - enableServerSideFuzzyMatch = true, - }, - }, - }, - typescript = { - updateImportsOnFileMove = { enabled = 'always' }, - suggest = { - completeFunctionCalls = true, - }, - inlayHints = { - enumMemberValues = { enabled = true }, - functionLikeReturnTypes = { enabled = true }, - parameterNames = { enabled = 'literals' }, - parameterTypes = { enabled = true }, - propertyDeclarationTypes = { enabled = true }, - variableTypes = { enabled = false }, - }, - }, - } - opts.settings.javascript = vim.tbl_deep_extend('force', {}, opts.settings.typescript, {}) - - opts.on_attach = function(client, buffer) - local map = function(lhs, rhs, opts) - ---@diagnostic disable-next-line: redefined-local - local o = { - buffer = buffer, - noremap = true, - desc = opts, - } - vim.keymap.set('n', lhs, rhs, o) - end - - map('gD', function() - require('vtsls').commands.goto_source_definition(buffer) - end, 'Goto Source Definition') - - map('gR', function() - require('vtsls').commands.file_references(buffer) - end, 'File References') - map('lo', function() - require('vtsls').commands.organize_imports(buffer) - require('vtsls').commands.add_missing_imports(buffer) - require('vtsls').commands.remove_unused_imports(buffer) - end, 'Organize Imports') - map('lF', function() - require('vtsls').commands.fix_all(buffer) - end, 'Fix All') - map('lv', function() - require('vtsls').commands.select_ts_version(buffer) - end, 'Select Version') - map('lR', function() - require('vtsls').commands.rename_file(buffer) - end, 'Rename File') - default_attach(client, buffer) - end - require('lspconfig')[server].setup(opts) - end, - jsonls = function(server, opts) - opts.capabilities = require('cmp_nvim_lsp').default_capabilities(opts.capabilities) - opts.on_new_config = function(new_config) - new_config.settings.json.schemas = new_config.settings.json.schemas or {} - vim.list_extend(new_config.settings.json.schemas, require('schemastore').json.schemas()) - end - opts.settings = { - json = { - -- schemas = require('schemastore').json.schemas({}), - validate = { enable = true }, - format = { enable = false }, - }, - } - require('lspconfig')[server].setup(opts) - end, - yamlls = function(server, opts) - local capabilities = vim.lsp.protocol.make_client_capabilities() - capabilities.textDocument.foldingRange = { - dynamicRegistration = false, - lineFoldingOnly = true, - } - opts.capabilities = capabilities - opts.on_new_config = function(new_config) - new_config.settings.yaml.schemas = vim.tbl_deep_extend( - 'force', - new_config.settings.yaml.schemas or {}, - require('schemastore').yaml.schemas() - ) - end - opts.settings = { - redhat = { telemetry = { enabled = false } }, - yaml = { - keyOrdering = false, - format = { - enable = true, - }, - validate = true, - schemaStore = { enable = false, url = '' }, - }, - } - require('lspconfig')[server].setup(opts) - end, - tailwindcss = function(server, opts) - opts.capabilities = require('cmp_nvim_lsp').default_capabilities(opts.capabilities) - - opts.root_dir = require('lspconfig.util').root_pattern( - 'tailwind.config.js', - 'tailwind.config.cjs', - 'tailwind.config.mjs', - 'tailwind.config.ts', - 'postcss.config.js', - 'postcss.config.cjs', - 'postcss.config.mjs', - 'postcss.config.ts' - ) - opts.settings = { - tailwindCSS = { - emmetCompletions = true, - validate = 'error', - }, - } - opts.single_file_support = false - require('lspconfig')[server].setup(opts) - end, - elixir_ls = function(_, opts) - local elixir = require 'elixir' - local elixirls = require 'elixir.elixirls' - - elixir.setup({ - nextls = { enable = false }, - credo = { enable = true }, - elixirls = { - enable = true, - capabilities = opts.capabilities, - settings = elixirls.settings({ - dialyzerEnabled = true, - enableTestLenses = true, - }), - on_attach = function(client, bufnr) - opts.on_attach(client, bufnr) - vim.keymap.set('n', 'lp', ':ElixirFromPipe', { buffer = true, noremap = true }) - vim.keymap.set('n', 'lP', ':ElixirToPipe', { buffer = true, noremap = true }) - vim.keymap.set('v', 'lm', ':ElixirExpandMacro', { buffer = true, noremap = true }) - end, - }, - }) - end, - -- eslint = false, - efm = false, - zk = false, - }, - -- A list like table of servers that should be setup, useful for enabling language servers not installed with Mason. - servers = { - 'gleam', - 'zls', - 'roc_ls', - 'nim_langserver' --[[, 'rust_analyzer' ]], - }, - on_attach = function(client, bufnr) - if client.supports_method 'textDocument/documentSymbol' then - require('nvim-navic').attach(client, bufnr) - end - end, - }, - }, - { - 'williamboman/mason-lspconfig.nvim', -- MUST be set up before `nvim-lspconfig` - dependencies = { - { - 'williamboman/mason.nvim', - opts = { - ---@type '"prepend"' | '"append"' | '"skip"' - PATH = 'append', - - ui = { - icons = { - package_installed = '✓', - package_uninstalled = '✗', - package_pending = '⟳', - }, - }, - }, - }, - }, - opts = function() - return { - ensure_installed = { - 'astro', - 'bashls', - 'clangd', - 'cssls', - 'docker_compose_language_service', - 'dockerls', - 'emmet_language_server', - 'gopls', - 'html', - 'lua_ls', - 'prismals', - 'pyright', - 'svelte', - 'tailwindcss', - 'tsserver', - 'volar', - }, - -- use AstroLSP setup for mason-lspconfig - handlers = { - function(server) - require('astrolsp').lsp_setup(server) - end, - }, - } - end, - }, - }, - config = function() - local diags = { Error = '', Warn = '', Info = '', Hint = '' } - for sign, icon in pairs(diags) do - vim.fn.sign_define('DiagnosticSign' .. sign, { text = icon, texthl = 'DiagnosticSign' .. sign }) - end - -- set up servers configured with AstroLSP - vim.tbl_map(require('astrolsp').lsp_setup, require('astrolsp').config.servers) - vim.g.rustaceanvim = { - server = { - on_attach = function(client, bufnr) - -- you can also put keymaps in here - require('astrolsp').on_attach(client, bufnr) - end, - }, - } - end, -} diff --git a/.config/nvim/lua/plugins/lsp/init.lua b/.config/nvim/lua/plugins/lsp/lspconfig.lua similarity index 100% rename from .config/nvim/lua/plugins/lsp/init.lua rename to .config/nvim/lua/plugins/lsp/lspconfig.lua diff --git a/.config/nvim/lua/plugins/lualine.lua b/.config/nvim/lua/plugins/lualine.lua index 679059d..0ea04f1 100644 --- a/.config/nvim/lua/plugins/lualine.lua +++ b/.config/nvim/lua/plugins/lualine.lua @@ -5,6 +5,197 @@ return { event = 'VeryLazy', dependencies = { 'nvim-tree/nvim-web-devicons' }, config = function() - require 'plugins.config.lualine' + local conditions = { + buffer_not_empty = function() + if vim.opt.filetype._value == 'toggleterm' then + return false + end + return vim.fn.empty(vim.fn.expand '%:t') ~= 1 + end, + hide_in_width = function() + return vim.fn.winwidth(0) > 80 + end, + lsp_active = function() + return vim.fn.winwidth(0) > 80 and next(vim.lsp.get_clients({ bufnr = 0 })) ~= nil + end, + } + local function servers_attached() + local msg = 'None' + local clients = vim + .iter(vim.lsp.get_clients({ bufnr = 0 })) + :map(function(client) + return client.name + end) + :flatten() + :join ',' + return clients == '' and msg or clients + end + + local navic = require 'nvim-navic' + local config = { + options = { + globalstatus = true, + component_separators = '', + section_separators = '', + theme = { + normal = { c = { bg = '#181818', fg = '#303540', blend = 100 } }, + inactive = { c = { bg = '#101010', fg = '#303540' } }, + }, + }, + sections = { + lualine_a = {}, + lualine_b = {}, + lualine_y = {}, + lualine_z = {}, + lualine_c = {}, + lualine_x = {}, + }, + inactive_sections = { + lualine_a = {}, + lualine_v = {}, + lualine_y = {}, + lualine_z = {}, + lualine_c = {}, + lualine_x = {}, + }, + tabline = { + lualine_a = {}, + lualine_v = {}, + lualine_y = {}, + lualine_z = {}, + lualine_c = {}, + lualine_x = {}, + }, + + winbar = { + lualine_c = { + { + 'navic', + ---@type "static"| "dynamic"| nil + color_correction = nil, + navic_opts = nil, + }, + }, + }, + inactive_winbar = { + lualine_c = { + { + 'filename', + path = 1, + condition = conditions.buffer_not_empty, + color = { fg = '#96a6c8', bg = '#181818', gui = 'bold,italic' }, + }, + }, + }, + extensions = { 'lazy', 'neo-tree', 'quickfix', 'toggleterm', 'man' }, + } + local function ins_left(component) + table.insert(config.sections.lualine_c, component) + end + local function ins_right(component) + table.insert(config.sections.lualine_x, component) + end + local function ins_left_tab(component) + table.insert(config.tabline.lualine_c, component) + end + local function ins_right_tab(component) + table.insert(config.tabline.lualine_x, component) + end + ins_left_tab({ + 'buffers', + buffers_color = { + -- Same values as the general color option can be used here. + active = { fg = '#96a6c8', bg = '#303540' }, -- Color for active tab. + inactive = { fg = '#52494e', bg = '#181818' }, -- Color for inactive tab. + }, + }) + ins_left_tab '%=' + ins_right_tab({ + 'tabs', + tabs_color = { + -- Same values as the general color option can be used here. + active = { fg = '#96a6c8', bg = '#303540' }, -- Color for active tab. + inactive = { fg = '#52494e', bg = '#181818' }, -- Color for inactive tab. + }, + }) + ins_left({ + 'filetype', + icon_only = true, + condition = conditions.buffer_not_empty, + left_padding = 0, + }) + ins_left({ + 'filename', + path = 1, + -- shorting_target = 40, + condition = conditions.buffer_not_empty, + color = { fg = '#96a6c8' }, + }) + ins_left({ + 'branch', + icon = '', + color = { fg = '#A3BE8C' }, + }) + ins_left({ + 'diff', + colored = true, + symbols = { added = ' ', modified = '󰇊 ', removed = ' ' }, + -- symbols = { added = ' ', modified = ' ', removed = ' ' }, + cond = conditions.hide_in_width, + }) + ins_left({ + 'diagnostics', + sources = { 'nvim_lsp' }, + }) + + -- ins_left({ + -- 'navic', + -- ---@type "static"| "dynamic"| nil + -- color_correction = nil, + -- navic_opts = nil, + -- }) + ins_right({ + servers_attached, + icon = ' LSPs:', + color = { fg = '#8992a7', gui = 'bold' }, + cond = conditions.lsp_active, + }) + ins_right({ 'progress', color = { fg = '#957FB8' } }) + ins_right({ 'location', color = { fg = '#6CAF95' } }) + ins_right({ + 'searchcount', + icon = '', + -- color = { fg = '#DCA561' }, + color = { fg = '#cc8c3c' }, + }) + ins_right({ + function() + if vim.fn.mode():find '[vV]' then + local ln_beg = vim.fn.line 'v' + local ln_end = vim.fn.line '.' + + local lines = ln_beg <= ln_end and ln_end - ln_beg + 1 or ln_beg - ln_end + 1 + + return 'sel: ' .. tostring(vim.fn.wordcount().visual_chars) .. ' | ' .. tostring(lines) + else + return '' + end + end, + color = { fg = '#c5c9c5' }, + }) + + require('lualine.components.buffers').buffers = function(self) + local buffers = {} + self.bufpos2nr = {} + for _, b in ipairs(vim.t['bufs']) do + if vim.fn.buflisted(b) ~= 0 and vim.api.nvim_buf_get_option(b, 'buftype') ~= 'quickfix' then + buffers[#buffers + 1] = self:new_buffer(b, #buffers + 1) + self.bufpos2nr[#buffers] = b + end + end + + return buffers + end + require('lualine').setup(config) end, } diff --git a/.config/nvim/lua/plugins/mini/align.lua b/.config/nvim/lua/plugins/mini/align.lua new file mode 100644 index 0000000..6e72beb --- /dev/null +++ b/.config/nvim/lua/plugins/mini/align.lua @@ -0,0 +1,9 @@ +---@type LazySpec +return { + 'echasnovski/mini.align', + version = '*', + keys = { 'ga', 'gA' }, + config = function() + require('mini.align').setup({}) + end, +} diff --git a/.config/nvim/lua/plugins/mini/operators.lua b/.config/nvim/lua/plugins/mini/operators.lua index 72bc909..09a962e 100644 --- a/.config/nvim/lua/plugins/mini/operators.lua +++ b/.config/nvim/lua/plugins/mini/operators.lua @@ -8,12 +8,14 @@ return { { 'ge', mode = { 'n', 'x' }, desc = 'Exchange' }, { 'gm', mode = { 'n', 'x' }, desc = 'Duplicate' }, { 'x', mode = { 'n', 'x' }, desc = 'Replace with register' }, - { 'gs', mode = { 'n', 'x' }, desc = 'Sort' }, + { 'gS', mode = { 'n', 'x' }, desc = 'Sort' }, + 'X', }, opts = { -- Exchange text regions exchange = { prefix = 'ge' }, replace = { prefix = 'x' }, + sort = { prefix = 'gS' }, }, config = function(_, opts) require('mini.operators').setup(opts) diff --git a/.config/nvim/lua/plugins/mini/surround.lua b/.config/nvim/lua/plugins/mini/surround.lua index 50bf03d..8fedbb9 100644 --- a/.config/nvim/lua/plugins/mini/surround.lua +++ b/.config/nvim/lua/plugins/mini/surround.lua @@ -12,7 +12,7 @@ return { { 'gzh', mode = { 'n' }, desc = 'Surround highlight' }, }, opts = { - search_method = 'cover_or_prev', + search_method = 'cover_or_next', n_lines = 500, mappings = { add = 'ys', -- Add surrounding in Normal and Visual modes diff --git a/.config/nvim/lua/plugins/neotree.lua b/.config/nvim/lua/plugins/neotree.lua index 8b2f864..8b8760f 100644 --- a/.config/nvim/lua/plugins/neotree.lua +++ b/.config/nvim/lua/plugins/neotree.lua @@ -9,6 +9,11 @@ local function better_toggle_neotree() vim.cmd 'Neotree reveal focus' end end +local cmd = 'trash' +if vim.fn.executable 'trash-put' == 1 then + cmd = 'trash-put' +end + ---@type LazySpec return { 'nvim-neo-tree/neo-tree.nvim', @@ -53,5 +58,62 @@ return { init = function() vim.g.neo_tree_remove_legacy_commands = 1 end, - config = require('plugins.config.neotree').config, + opts = { + window = { + mappings = { + l = 'open', + ['?'] = 'show_help', + ['<'] = 'prev_source', + ['>'] = 'next_source', + }, + }, + filesystem = { + use_libuv_file_watcher = true, + window = { + -- mappings = { }, + fuzzy_finder_mappings = { + [''] = 'move_cursor_down', + [''] = 'move_cursor_up', + [''] = 'move_cursor_down', + [''] = 'move_cursor_up', + }, + }, + + commands = { + -- Override delete to use trash instead of rm + delete = function(state) + local inputs = require 'neo-tree.ui.inputs' + local path = state.tree:get_node().path + local msg = 'Trash ' .. path .. ' ?' + inputs.confirm(msg, function(confirmed) + if not confirmed then + return + end + + vim.fn.system({ cmd, vim.fn.fnameescape(path) }) + require('neo-tree.sources.manager').refresh(state.name) + end) + end, + -- over write default 'delete_visual' command to 'trash' x n. + delete_visual = function(state, selected_nodes) + local inputs = require 'neo-tree.ui.inputs' + local count = #selected_nodes + local msg = 'Trash ' .. count .. ' files ?' + inputs.confirm(msg, function(confirmed) + if not confirmed then + return + end + for _, node in ipairs(selected_nodes) do + vim.fn.system({ cmd, vim.fn.fnameescape(node.path) }) + end + require('neo-tree.sources.manager').refresh(state.name) + end) + end, + }, + }, + }, + config = function(_, opts) + require('neo-tree').setup(opts) + require('lsp-file-operations').setup({}) + end, } diff --git a/.config/nvim/lua/plugins/nvim-cmp.lua b/.config/nvim/lua/plugins/nvim-cmp.lua new file mode 100644 index 0000000..089f171 --- /dev/null +++ b/.config/nvim/lua/plugins/nvim-cmp.lua @@ -0,0 +1,334 @@ +local function feedkey(key, mode) + vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(key, true, true, true), mode, true) +end +local function has_words_before() + unpack = unpack or table.unpack + local line, col = unpack(vim.api.nvim_win_get_cursor(0)) + return col ~= 0 and vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]:sub(col, col):match '%s' == nil +end + +local function deprio(kind) + return function(e1, e2) + if e1:get_kind() == kind then + return false + end + if e2:get_kind() == kind then + return true + end + end +end + +--- detect if the current completion item is an emmet completion item +--- @param entry cmp.Entry +--- @return boolean +local function isEmmet(entry) + return ( + entry:get_kind() == require('cmp.types').lsp.CompletionItemKind.Text + or entry:get_kind() == require('cmp.types').lsp.CompletionItemKind.Snippet + ) + and ( + entry.source:get_debug_name() == 'nvim_lsp:emmet_language_server' + or entry.source:get_debug_name() == 'nvim_lsp:emmet_ls' + ) +end + +---@type LazySpec +return { + 'iguanacucumber/magazine.nvim', + name = 'nvim-cmp', -- Otherwise highlighting gets messed up + enabled = true, + event = 'BufReadPre', + dependencies = { + 'hrsh7th/cmp-nvim-lsp', + 'hrsh7th/cmp-buffer', + -- 'hrsh7th/cmp-path', + 'https://codeberg.org/FelipeLema/cmp-async-path', + 'hrsh7th/cmp-cmdline', + 'lukas-reineke/cmp-rg', + -- 'lukas-reineke/cmp-under-comparator', + 'octaltree/cmp-look', + 'saadparwaiz1/cmp_luasnip', + { + 'L3MON4D3/LuaSnip', + build = 'make install_jsregexp', + dependencies = { 'rafamadriz/friendly-snippets' }, + event = 'User BaseFile', + opts = { history = true, delete_check_events = 'TextChanged', region_check_events = 'CursorMoved' }, + config = function(_, opts) + if opts then + require('luasnip').config.setup(opts) + end + + vim.tbl_map(function(type) + require('luasnip.loaders.from_' .. type).lazy_load() + end, { 'vscode', 'snipmate', 'lua' }) + + local extends = { + typescript = { 'tsdoc' }, + javascript = { 'jsdoc' }, + lua = { 'luadoc' }, + python = { 'pydoc' }, + rust = { 'rustdoc' }, + cs = { 'csharpdoc' }, + java = { 'javadoc' }, + c = { 'cdoc' }, + cpp = { 'cppdoc' }, + php = { 'phpdoc' }, + kotlin = { 'kdoc' }, + ruby = { 'rdoc' }, + sh = { 'shelldoc' }, + } + -- friendly-snippets - enable standardized comments snippets + for ft, snips in pairs(extends) do + require('luasnip').filetype_extend(ft, snips) + end + end, + }, + 'onsails/lspkind.nvim', + { + 'folke/lazydev.nvim', + ft = 'lua', -- only load on lua files + opts = { + library = { 'lazy.nvim', { path = 'luvit-meta/library', words = { 'vim%.uv' } } }, + }, + }, + { 'Bilal2453/luvit-meta', lazy = true }, + }, + config = function() + local cmp = require 'cmp' + local types = require 'cmp.types' + local sources = require 'cmp.config.sources' + local compare = require 'cmp.config.compare' + local lspkind = require 'lspkind' + local snippet = 'luasnip' + local luasnip = require 'luasnip' + + cmp.setup({ + snippet = { + expand = function(args) + luasnip.lsp_expand(args.body) + end, + }, + experimental = { ghost_text = false, native_menu = false }, + window = { completion = cmp.config.window.bordered(), documentation = cmp.config.window.bordered() }, + duplicates = { + nvim_lsp = 1, + lazydev = 1, + [snippet] = 1, + cmp_tabnine = 1, + buffer = 1, + path = 1, + }, + + mapping = { + [''] = cmp.mapping({ i = cmp.mapping.scroll_docs(-4) }), + [''] = cmp.mapping({ i = cmp.mapping.scroll_docs(4) }), + [''] = cmp.mapping.complete(), + [''] = cmp.mapping.close(), + [''] = cmp.mapping({ + i = cmp.mapping.confirm({ behavior = cmp.ConfirmBehavior.Replace, select = true }), + c = cmp.mapping.confirm({ behavior = cmp.ConfirmBehavior.Replace, select = false }), + }), + [''] = cmp.mapping({ + i = cmp.mapping.confirm({ behavior = cmp.ConfirmBehavior.Replace, select = true }), + c = cmp.mapping.confirm({ behavior = cmp.ConfirmBehavior.Replace, select = false }), + }), + [''] = cmp.mapping({ + i = function(fallback) + if cmp.visible() then + cmp.select_next_item({ behavior = cmp.SelectBehavior.Select }) + else + fallback() + end + end, + }), + [''] = cmp.mapping({ + i = function(fallback) + if cmp.visible() then + cmp.select_prev_item({ behavior = cmp.SelectBehavior.Select }) + else + fallback() + end + end, + }), + [''] = cmp.mapping({ + c = function() + if cmp.visible() then + cmp.select_next_item({ behavior = cmp.SelectBehavior.Select }) + else + feedkey('', 'n') + end + end, + i = function(fallback) + if cmp.visible() then + cmp.select_next_item({ behavior = cmp.SelectBehavior.Select }) + else + fallback() + end + end, + }), + [''] = cmp.mapping({ + c = function() + if cmp.visible() then + cmp.select_prev_item({ behavior = cmp.SelectBehavior.Select }) + else + feedkey('', 'n') + end + end, + i = function(fallback) + if cmp.visible() then + cmp.select_prev_item({ behavior = cmp.SelectBehavior.Select }) + else + fallback() + end + end, + }), + [''] = cmp.mapping.complete({ + config = { sources = { { name = snippet } } }, + }), + [''] = cmp.mapping.complete({ + config = { + sources = { + { + name = 'nvim_lsp', + entry_filter = function(entry) + return isEmmet(entry) + end, + }, + }, + }, + }), + [''] = cmp.mapping(function(fallback) + if cmp.visible() then + cmp.select_next_item() + -- elseif vim.snippet.active({ direction = 1 }) then + -- return 'lua vim.snippet.jump(1)' + -- vim.snippet.jump(1) + -- elseif vim.fn['vsnip#available'](1) == 1 then + -- feedkey('(vsnip-expand-or-jump)', '') + elseif luasnip.expand_or_jumpable() then + luasnip.expand_or_jump() + elseif has_words_before() then + cmp.complete() + else + fallback() + end + end, { 'i', 's' }), + + [''] = cmp.mapping(function() + if cmp.visible() then + cmp.select_prev_item() + elseif luasnip.jumpable(-1) then + luasnip.jump(-1) + -- elseif vim.snippet.active({ direction = -1 }) then + -- return 'lua vim.snippet.jump(-1)' + -- vim.snippet.jump(-1) + -- elseif vim.fn['vsnip#jumpable'](-1) == 1 then + -- feedkey('(vsnip-jump-prev)', '') + end + end, { 'i', 's' }), + }, + sources = sources({ + { + name = 'nvim_lsp', + priority = 100, + max_item_count = 20, + entry_filter = function(entry) + return not isEmmet(entry) + end, + }, + { name = 'lazydev', priority = 95 }, + { name = snippet, priority = 90 }, + { + name = 'buffer', + max_item_count = 10, + option = { + keyword_length = 2, + -- get_bufnrs = function() + -- local bufIsSmall = function(bufnr) + -- return vim.api.nvim_buf_line_count(bufnr) < 2000 + -- end + -- return vim.tbl_filter(bufIsSmall, vim.api.nvim_list_bufs()) + -- end, + }, + priority = 40, + }, + { + name = 'rg', + keyword_length = 3, + max_item_count = 10, + priority_weight = 50, + option = { + additional_arguments = '--smart-case --hidden', + set_filetype = true, + marker = ' ❰❰❰', + }, + -- entry_filter = function(entry) + -- return not entry.exact + -- end, + }, + -- { name = 'path', priority = 50 }, + { name = 'async_path', priority = 50, option = { trailing_slash = false } }, + { + name = 'look', + keyword_length = 5, + priority = 30, + option = { + convert_case = true, + loud = true, + --dict = '/usr/share/dict/words' + }, + }, + }), + sorting = { + priority_weight = 100, + comparators = { + deprio(types.lsp.CompletionItemKind.Text), + compare.exact, + compare.offset, + compare.recently_used, + compare.score, + compare.kind, + compare.length, + compare.locality, + compare.order, + compare.sort_text, + }, + }, + ---@diagnostic disable-next-line: missing-fields + formatting = { + fields = { 'kind', 'abbr', 'menu' }, + format = lspkind.cmp_format({ + mode = 'symbol', + maxwidth = 50, + ellipsis_char = '...', + symbol_map = { Copilot = '' }, + }), + }, + }) + cmp.setup.cmdline(':', { + sources = sources({ + { + name = 'cmdline', + option = { + ignore_cmds = { 'Man', '!', 'find', 'fin' }, + }, + }, + { name = 'path' }, + }), + matching = { disallow_symbol_nonprefix_matching = false }, + mapping = cmp.mapping.preset.cmdline(), + formatting = { fields = { 'abbr' } }, + window = { completion = cmp.config.window.bordered({ col_offset = 0 }) }, + }) + + cmp.setup.cmdline({ '/', '?' }, { + sources = sources({ + { name = 'buffer' }, + }), + mapping = cmp.mapping.preset.cmdline(), + formatting = { fields = { 'abbr' } }, + window = { completion = cmp.config.window.bordered({ col_offset = 0 }) }, + }) + end, +} diff --git a/.config/nvim/lua/plugins/nvim-lint.lua b/.config/nvim/lua/plugins/nvim-lint.lua index 126853c..2712229 100644 --- a/.config/nvim/lua/plugins/nvim-lint.lua +++ b/.config/nvim/lua/plugins/nvim-lint.lua @@ -1,6 +1,112 @@ +local au_group = vim.api.nvim_create_augroup('sp_nvim_lint', {}) +local languages = { + sh = { 'shellcheck', 'cspell' }, + bash = { 'shellcheck', 'cspell' }, + fish = { 'fish' }, + zsh = { 'shellcheck', 'zsh', 'cspell' }, + -- c = { 'clangtidy' }, + -- cpp = { 'clangtidy' }, + go = { 'golangcilint', 'cspell' }, + -- markdown = { 'vale' }, + html = { 'htmlhint', 'cspell' }, + css = { 'stylelint', 'cspell' }, + scss = { 'stylelint', 'cspell' }, + sass = { 'stylelint', 'cspell' }, + less = { 'stylelint', 'cspell' }, + python = { 'ruff', 'cspell' }, + astro = { 'eslint_d', 'cspell' }, + svelte = { 'eslint_d', 'cspell' }, + javascript = { 'eslint_d', 'cspell' }, + javascriptreact = { 'eslint_d', 'cspell' }, + typescript = { 'eslint_d', 'cspell' }, + typescriptreact = { 'eslint_d', 'cspell' }, + vue = { 'eslint_d', 'cspell' }, + yaml = { 'yamllint', 'cspell' }, + php = { 'php', 'phpstan', 'phpcs', 'cspell' }, +} +local linters = { + eslint_d = { + condition = function(ctx) + return vim.fs.find({ + 'eslint.config.js', + 'eslint.config.mjs', + 'eslint.config.cjs', + '.eslintrc.json', + '.eslintrc', + '.eslintrc.js', + '.eslintrc.yaml', + '.eslintrc.yml', + }, { path = ctx.filename, upward = true })[1] + end, + }, +} + +local function debounce(ms, fn) + local timer = vim.uv.new_timer() + return function(...) + local argv = { ... } + timer:start(ms, 0, function() + timer:stop() + vim.schedule_wrap(fn)(unpack(argv)) + end) + end +end + +---@type LazySpec return { 'mfussenegger/nvim-lint', enabled = true, - ft = require('plugins.config.nvim-lint').languages, - config = require('plugins.config.nvim-lint').config, + ft = vim.tbl_keys(languages), + config = function(_, opts) + local lint = require 'lint' + languages = vim.tbl_deep_extend('force', languages, opts.languages or {}) + linters = vim.tbl_deep_extend('force', linters, opts.linters or {}) + + lint.linters_by_ft = languages + + local function run() + -- Use nvim-lint's logic first: + -- * checks if linters exist for the full filetype first + -- * otherwise will split filetype by "." and add all those linters + -- * this differs from conform.nvim which only uses the first filetype that has a formatter + local names = lint._resolve_linter_by_ft(vim.bo.filetype) + + -- Create a copy of the names table to avoid modifying the original. + names = vim.list_extend({}, names) + + -- Add fallback linters. + if #names == 0 then + vim.list_extend(names, lint.linters_by_ft['_'] or {}) + end + + -- Add global linters. + vim.list_extend(names, lint.linters_by_ft['*'] or {}) + + -- Filter out linters that don't exist or don't match the condition. + local ctx = { filename = vim.api.nvim_buf_get_name(0) } + ctx.dirname = vim.fn.fnamemodify(ctx.filename, ':h') + names = vim.tbl_filter(function(name) + local linter = lint.linters[name] + return linter and not (type(linter) == 'table' and linter.condition and not linter.condition(ctx)) + end, names) + + -- Run linters. + if #names > 0 then + lint.try_lint(names) + end + end + for name, linter in pairs(linters) do + if type(linter) == 'table' and type(lint.linters[name]) == 'table' then + lint.linters[name] = vim.tbl_deep_extend('force', lint.linters[name], linter) + else + lint.linters[name] = linter + end + end + vim.api.nvim_create_autocmd({ 'BufWritePost', 'BufRead', 'InsertLeave', 'FocusGained' }, { + group = au_group, + desc = 'Lint on save', + pattern = '*', + callback = debounce(100, run), + }) + end, } diff --git a/.config/nvim/lua/plugins/nvim-tree.lua b/.config/nvim/lua/plugins/nvim-tree.lua index 14024ef..eb5d337 100644 --- a/.config/nvim/lua/plugins/nvim-tree.lua +++ b/.config/nvim/lua/plugins/nvim-tree.lua @@ -1,3 +1,5 @@ +local au_group = vim.api.nvim_create_augroup('sp_nvim_tree', { clear = true }) + ---Description: NvimTree configuration ---Use single hotkeys to toggle/focus nvim-tree ---If nvim-tree is focused - close it, otherwise focus it @@ -14,6 +16,35 @@ local nvimTreeFocusOrToggle = function(isFind) end end +local function my_on_attach(bufnr) + local api = require 'nvim-tree.api' + + local function opts(desc) + return { desc = 'nvim-tree: ' .. desc, buffer = bufnr, noremap = true, silent = true, nowait = true } + end + + -- default mappings + api.config.mappings.default_on_attach(bufnr) + + -- custom mappings + + vim.keymap.del('n', 'U', { buffer = bufnr }) + vim.keymap.del('n', 'L', { buffer = bufnr }) + vim.keymap.del('n', 'M', { buffer = bufnr }) + vim.keymap.set('n', 'H', api.node.navigate.parent, opts 'Goto parent') + vim.keymap.set('n', 'l', api.node.open.edit, opts 'Open') + vim.keymap.set('n', 'L', api.node.open.no_windown_picker, opts 'Open(no window select)') + vim.keymap.set('n', '?', api.tree.toggle_help, opts 'Help') + vim.keymap.set('n', 'D', api.fs.remove, opts 'Delete') + vim.keymap.set('n', 'd', api.fs.trash, opts 'Trash') + + vim.keymap.set('n', 'tl', api.node.open.toggle_group_empty, opts 'Toggle Group Empty') + vim.keymap.set('n', 'tm', api.tree.toggle_no_bookmark_filter, opts 'Toggle Filter: No Bookmark') + vim.keymap.set('n', 'td', api.tree.toggle_hidden_filter, opts 'Toggle Dotfiles') + vim.keymap.set('n', 'tg', api.tree.toggle_gitignore_filter, opts 'Toggle Gitignore') + vim.keymap.set('n', 'tc', api.tree.toggle_custom_filter, opts 'Toggle Custom filters') +end + ---@type LazySpec return { 'nvim-tree/nvim-tree.lua', @@ -34,8 +65,34 @@ return { -- disable netrw at the very start of your init.lua vim.g.loaded_netrw = 1 vim.g.loaded_netrwPlugin = 1 + + vim.api.nvim_create_autocmd('BufEnter', { + group = au_group, + desc = "Close nvim-tree if it's the only window", + pattern = 'NvimTree_*', + callback = function() + local layout = vim.api.nvim_call_function('winlayout', {}) + if + layout[1] == 'leaf' + and vim.api.nvim_get_option_value('filetype', { buf = vim.api.nvim_win_get_buf(layout[2]) }) == 'NvimTree' + and layout[3] == nil + then + vim.cmd 'confirm quit' + end + end, + }) end, config = function() - require 'plugins.config.nvim-tree' + require('nvim-tree').setup({ + view = { width = 40 }, + ui = { + confirm = { + remove = true, + trash = false, + }, + }, + on_attach = my_on_attach, + }) + require('lsp-file-operations').setup() end, } diff --git a/.config/nvim/lua/plugins/telescope.lua b/.config/nvim/lua/plugins/telescope.lua index 099044e..a371ac2 100644 --- a/.config/nvim/lua/plugins/telescope.lua +++ b/.config/nvim/lua/plugins/telescope.lua @@ -1,3 +1,63 @@ +local au_telescope = vim.api.nvim_create_augroup('au_telescope', { clear = true }) + +local function getVisualSelection() + vim.cmd 'noau normal! "vy"' + local text = vim.fn.getreg 'v' + vim.fn.setreg('v', {}) + + text = string.gsub(text, '\n', '') + if #text > 0 then + return text + else + return '' + end +end + +local function filename_first(_, path) + local tail = vim.fs.basename(path) + local parent = vim.fs.dirname(path) + if parent == '.' then + return tail + end + return string.format('%s\t\t%s', tail, parent) +end + +local function telescope_create_file() + require('telescope.builtin').find_files({ + prompt_title = 'Create File', + find_command = { 'fd', '--type', 'd', '.', vim.fn.getcwd() }, + attach_mappings = function(_, map) + local state = require 'telescope.actions.state' + local actions = require 'telescope.actions' + map('i', '', function(prompt_bufnr) + local content = state.get_selected_entry() + actions.close(prompt_bufnr) + -- vim.print('content : ' .. content.cwd .. '/' .. content.value) + local dir = content.value + local name = vim.fn.input 'File Name: ' + vim.cmd('e ' .. dir .. name) + vim.cmd 'w ++p' + end) + return true + end, + }) +end + +local function project_files() + local opts = { + path_display = filename_first, + previewer = false, + } -- define here if you want to define something + + if vim.b.gitsigns_head then + opts.show_untracked = true + require('telescope.builtin').git_files(opts) + else + require('telescope.builtin').find_files(opts) + end +end + +---@type LazySpec return { 'nvim-telescope/telescope.nvim', cmd = 'Telescope', @@ -9,6 +69,312 @@ return { 'nvim-telescope/telescope-ui-select.nvim', { 'fdschmidt93/telescope-egrepify.nvim', dependencies = 'nvim-lua/plenary.nvim' }, }, - keys = require('plugins.config.telescope').keys, - config = require('plugins.config.telescope').config, + keys = function() + local builtin = require 'telescope.builtin' + return { + { + '', + project_files, + desc = 'Git/Files', + }, + { + 'ff', + function() + builtin.find_files({ path_display = filename_first }) + end, + desc = 'Files', + }, + { + 'fF', + function() + builtin.git_files({ show_untracked = true, use_file_path = true, path_display = filename_first }) + end, + desc = 'Git Files(use_file_path)', + }, + { 'fp', telescope_create_file, desc = 'CreateFile' }, + { 'fc', telescope_create_file, desc = 'CreateFile' }, + { 'fk', builtin.keymaps, desc = 'keymaps' }, + { 'fS', builtin.current_buffer_fuzzy_find, desc = 'Search(Buffer)' }, + -- { 'fs', builtin.live_grep, desc = 'Search(Project)' }, + { 'fs', 'Telescope egrepify', desc = 'Search(Project)' }, + { 'fw', builtin.grep_string, desc = 'Search Current Word', mode = { 'n', 'x' } }, + { 'fb', builtin.buffers, desc = 'Buffers' }, + { 'fh', builtin.help_tags, desc = 'Help' }, + { 'fR', builtin.oldfiles, desc = 'Old Files' }, + { 'fr', builtin.resume, desc = 'Resume' }, + { + 'fs', + function() + local text = getVisualSelection() + builtin.live_grep({ default_text = text }) + end, + mode = 'v', + desc = '[S]earch [S]election', + }, + { + 'fS', + function() + local text = getVisualSelection() + builtin.current_buffer_fuzzy_find({ default_text = text }) + end, + mode = 'v', + desc = '[S]earch [S]election(Buffer)', + }, + { + 'fn', + function() + builtin.find_files({ + cwd = vim.fn.stdpath 'config', + path_display = filename_first, + }) + end, + desc = 'Neovim Config', + }, + { + 'fd', + function() + builtin.git_files({ + cwd = vim.fn.expand '$HOME/Documents/dotfiles', + path_display = filename_first, + show_untracked = true, + }) + end, + desc = 'Dotfiles', + }, + { 'gb', builtin.git_branches, desc = 'Git Branches' }, + { 'fg', builtin.git_status, desc = 'Git Status' }, + { 'gS', builtin.git_stash, desc = 'Git Stash' }, + { 'gc', builtin.git_commits, desc = 'Git Commits' }, + { 'gC', builtin.git_bcommits, desc = 'Git Buffer Commits' }, + } + end, + config = function() + vim.api.nvim_create_autocmd('FileType', { + pattern = 'TelescopeResults', + group = au_telescope, + callback = function(ctx) + vim.api.nvim_buf_call(ctx.buf, function() + vim.fn.matchadd('TelescopeParent', '\t\t.*$') + vim.api.nvim_set_hl(0, 'TelescopeParent', { link = 'Comment' }) + end) + end, + }) + local actions = require 'telescope.actions' + local action_layout = require 'telescope.actions.layout' + local builtin = require 'telescope.builtin' + + local dropdown = { + layout_strategy = 'vertical', + layout_config = { width = 0.6, preview_cutoff = 1, prompt_position = 'top' }, + } + require('telescope').setup({ + defaults = { + -- path_display = { "truncate" }, + sorting_strategy = 'ascending', + set_env = { ['COLORTERM'] = 'truecolor' }, + layout_config = { + horizontal = { prompt_position = 'top', preview_width = 0.40 }, + vertical = { mirror = false }, + width = 0.87, + height = 0.80, + preview_cutoff = 120, + }, + mappings = { + i = { + [''] = actions.move_selection_next, + [''] = actions.move_selection_previous, + [''] = actions.cycle_history_next, + [''] = actions.cycle_history_prev, + [''] = actions.close, + [''] = action_layout.toggle_preview, + + [''] = actions.toggle_selection + actions.move_selection_next, + [''] = actions.toggle_selection + actions.move_selection_previous, + [''] = actions.smart_send_to_qflist + actions.open_qflist, + }, + n = { + q = actions.close, + [''] = action_layout.toggle_preview, + [''] = actions.toggle_selection, + }, + }, + vimgrep_arguments = { + 'rg', + '--color=never', + '--no-heading', + '--with-filename', + '--line-number', + '--column', + '--smart-case', + '--hidden', + '--trim', -- add this value + '--glob=!.git/', + '--glob=!node_modules/', + '--glob=!.venv/', + '--glob=!venv/', + }, + }, + + pickers = { + buffers = { + ignore_current_buffer = true, + sort_lastused = true, + mappings = { + i = { [''] = 'delete_buffer' }, + n = { d = 'delete_buffer' }, + }, + prompt_title = 'Buffers', + results_title = 'Command History', + prompt_prefix = ' ', + sorting_strategy = 'ascending', + layout_strategy = 'bottom_pane', + layout_config = { + prompt_position = 'top', + }, + border = true, + borderchars = { + prompt = { ' ', ' ', '─', ' ', ' ', ' ', '─', '─' }, + results = { '─', ' ', ' ', ' ', '─', '─', ' ', ' ' }, + preview = { '─', ' ', '─', '│', '┬', '─', '─', '╰' }, + }, + }, + help_tags = { + prompt_title = 'Help', + results_title = 'Help Tags', + prompt_prefix = ' ', + sorting_strategy = 'ascending', + layout_strategy = 'bottom_pane', + layout_config = { + prompt_position = 'top', + height = 25, + }, + border = true, + borderchars = { + prompt = { ' ', ' ', '─', ' ', ' ', ' ', '─', '─' }, + results = { '─', ' ', ' ', ' ', '─', '─', ' ', ' ' }, + preview = { '─', ' ', '─', '│', '┬', '─', '─', '╰' }, + }, + }, + keymaps = { + prompt_title = 'keymaps', + results_title = 'keymaps', + prompt_prefix = ' ', + sorting_strategy = 'ascending', + layout_strategy = 'bottom_pane', + layout_config = { + prompt_position = 'top', + height = 25, + }, + border = true, + borderchars = { + prompt = { ' ', ' ', '─', ' ', ' ', ' ', '─', '─' }, + results = { '─', ' ', ' ', ' ', '─', '─', ' ', ' ' }, + preview = { '─', ' ', '─', '│', '┬', '─', '─', '╰' }, + }, + }, + command_history = { + prompt_title = '', + results_title = 'Command History', + + --            + --  卑 喝   + prompt_prefix = ' ', + -- prompt_prefix = " ", + -- prompt_prefix = " ", + -- prompt_prefix = " ", + + sorting_strategy = 'ascending', + layout_strategy = 'bottom_pane', + layout_config = { + prompt_position = 'top', + height = 25, + }, + border = true, + borderchars = { + prompt = { ' ', ' ', '─', ' ', ' ', ' ', '─', '─' }, + results = { '─', ' ', ' ', ' ', '─', '─', ' ', ' ' }, + preview = { '─', ' ', '─', '│', '┬', '─', '─', '╰' }, + }, + mappings = { + i = { [''] = actions.edit_command_line }, + n = { [''] = actions.edit_command_line }, + }, + }, + lsp_references = dropdown, + lsp_definitions = dropdown, + git_branches = dropdown, + git_commits = dropdown, + git_bcommits = dropdown, + lsp_document_symbols = dropdown, + lsp_workspace_symbols = dropdown, + grep_string = vim.tbl_extend('force', dropdown, { + path_display = { 'truncate' }, + }), + }, + extensions = { + ['zf-native'] = { + -- options for sorting file-like items + file = { + -- override default telescope file sorter + enable = true, + -- highlight matching text in results + highlight_results = true, + -- enable zf filename match priority + match_filename = true, + -- optional function to define a sort order when the query is empty + initial_sort = nil, + }, + + -- options for sorting all other items + generic = { + -- override default telescope generic item sorter + enable = true, + -- highlight matching text in results + highlight_results = true, + -- disable zf filename match priority + match_filename = false, + -- optional function to define a sort order when the query is empty + initial_sort = nil, + }, + }, + ['ui-select'] = require('telescope.themes').get_dropdown({}), + egrepify = { + prefixes = { + ['>'] = { + flag = 'type', + cb = function(input) + -- check if the input has any commas + if string.find(input, ',') then + return string.format([[{%s}]], input) + end + return string.format([[%s]], input) + end, + }, + ['<'] = { + flag = 'type-not', + cb = function(input) + -- check if the input has any commas + if string.find(input, ',') then + return string.format([[{%s}]], input) + end + return string.format([[%s]], input) + end, + }, + }, + }, + }, + }) + require('telescope').load_extension 'zf-native' + require('telescope').load_extension 'ui-select' + require('telescope').load_extension 'egrepify' + + vim.lsp.handlers['textDocument/definition'] = builtin.lsp_definitions + vim.lsp.handlers['textDocument/typeDefinition'] = builtin.lsp_type_definitions + vim.lsp.handlers['textDocument/implementation'] = builtin.lsp_implementations + vim.lsp.handlers['textDocument/references'] = builtin.lsp_references + vim.lsp.handlers['textDocument/documentSymbol'] = builtin.lsp_document_symbols + vim.lsp.handlers['workspace/symbol'] = builtin.lsp_workspace_symbols + vim.lsp.handlers['callHierarchy/incomingCalls'] = builtin.lsp_incoming_calls + vim.lsp.handlers['callHierarchy/outgoingCalls'] = builtin.lsp_outgoing_calls + end, } diff --git a/.config/nvim/lua/plugins/toggleterm.lua b/.config/nvim/lua/plugins/toggleterm.lua index aa11ad1..fea0ef7 100644 --- a/.config/nvim/lua/plugins/toggleterm.lua +++ b/.config/nvim/lua/plugins/toggleterm.lua @@ -3,6 +3,39 @@ return { version = '*', keys = { 'tl', '' }, config = function() - require 'plugins.config.toggleterm' + local Terminal = require('toggleterm.terminal').Terminal + local toggleterm = require 'toggleterm' + local lazygit = Terminal:new({ + cmd = 'lazygit', + dir = 'git_dir', + direction = 'float', + -- shell = vim.o.shell == '/bin/fish' and '/bin/zsh' or vim.o.shell, + float_opts = { border = 'curved' }, + }) + + local function lazygit_toggle() + lazygit:toggle() + end + + toggleterm.setup({ + shell = vim.o.shell == '/bin/fish' and '/bin/zsh' or vim.o.shell, + direction = 'float', + open_mapping = [[]], + highlights = { + FloatBorder = { link = 'FloatBorder' }, + }, + float_opts = { + border = 'single', + }, + -- highlights = { + -- Normal = { + -- guibg = '#080818', + -- }, + -- NormalFloat = { + -- guibg = '#080818', + -- }, + -- }, + }) + vim.keymap.set('n', 'tl', lazygit_toggle, { desc = '[T]erminal [L]azygit' }) end, } diff --git a/.config/nvim/lua/plugins/tree-sitter.lua b/.config/nvim/lua/plugins/tree-sitter.lua index cd768b6..2e71a4f 100644 --- a/.config/nvim/lua/plugins/tree-sitter.lua +++ b/.config/nvim/lua/plugins/tree-sitter.lua @@ -23,7 +23,143 @@ return { }, }, config = function() - require 'plugins.config.tree-sitter' + local configs = require 'nvim-treesitter.configs' + ---@diagnostic disable-next-line: missing-fields + configs.setup({ + highlight = { + enable = true, + -- additional_vim_regex_highlighting = { 'markdown', 'xml' }, + disable = function(_, bufnr) + local line_count = vim.api.nvim_buf_line_count(bufnr) + if line_count > 2500 then + return true + end + end, + }, + indent = { enable = false }, + matchup = { enable = true }, + ensure_installed = { + 'bash', + 'dockerfile', + 'fish', + 'query', + 'regex', + 'rasi', + 'sxhkdrc', + 'vim', + 'vimdoc', + 'diff', + 'git_config', + 'git_rebase', + 'gitattributes', + 'gitcommit', + 'gitignore', + 'hyprlang', + 'ini', + 'sql', + 'ssh_config', + 'tmux', + 'toml', + 'xml', + 'zathurarc', + }, + incremental_selection = { + enable = true, + keymaps = { + init_selection = '', + node_incremental = '', + scope_incremental = false, + node_decremental = '', + }, + }, + textobjects = { + -- select = { + -- enable = true, + -- lookahead = true, + -- keymaps = { + -- ['af'] = '@function.outer', + -- ['if'] = '@function.inner', + -- ['ac'] = '@class.outer', + -- ['ic'] = { query = '@class.inner', desc = 'Select inner part of a class region' }, + -- ['al'] = { query = '@scope', query_group = 'locals', desc = 'Select language scope' }, + -- ['a/'] = { query = '@comment.outer', desc = 'Select outer comment' }, + -- ['i/'] = { query = '@comment.inner', desc = 'Select inner comment' }, + -- }, + -- selection_modes = { + -- ['@parameter.outer'] = 'v', -- charwise + -- ['@function.outer'] = 'V', -- linewise + -- ['@class.outer'] = '', -- blockwise + -- }, + -- include_surrounding_whitespace = true, + -- }, + move = { + enable = true, + set_jumps = true, -- whether to set jumps in the jumplist + goto_next_start = { + [']m'] = '@function.outer', + [']C'] = { query = '@class.outer', desc = 'Next class start' }, + [']l'] = '@loop.*', + -- ["]o"] = { query = { "@loop.inner", "@loop.outer" } } + [']s'] = { query = '@scope', query_group = 'locals', desc = 'Next scope' }, + [']z'] = { query = '@fold', query_group = 'folds', desc = 'Next fold' }, + }, + goto_next_end = { + [']M'] = '@function.outer', + [']['] = '@class.outer', + }, + goto_previous_start = { + ['[m'] = '@function.outer', + ['[C'] = '@class.outer', + }, + goto_previous_end = { + ['[M'] = '@function.outer', + ['[]'] = '@class.outer', + }, + goto_next = { + [']i'] = '@conditional.outer', + }, + goto_previous = { + ['[i'] = '@conditional.outer', + }, + }, + swap = { + enable = true, + swap_next = { + ['k'] = { query = '@block.outer', desc = 'Swap next block' }, + ['f'] = { query = '@function.outer', desc = 'Swap next function' }, + ['a'] = { query = '@parameter.inner', desc = 'Swap next argument' }, + }, + swap_previous = { + ['K'] = { query = '@block.outer', desc = 'Swap previous block' }, + ['F'] = { query = '@function.outer', desc = 'Swap previous function' }, + ['A'] = { query = '@parameter.inner', desc = 'Swap previous argument' }, + }, + }, + }, + }) + + require('nvim-ts-autotag').setup({ + -- Defaults + opts = { + enable_close = true, -- Auto close tags + enable_rename = true, -- Auto rename pairs of tags + enable_close_on_slash = false, -- Auto close on trailing c', function() + require('treesitter-context').go_to_context(vim.v.count1) + end, { silent = true, desc = 'Goto Context' }) + vim.keymap.set('n', '', function() + require('treesitter-context').go_to_context(vim.v.count1) + end, { silent = true, desc = 'Goto Context' }) + + -- for _, v in ipairs(vim.fn.readdir(vim.g.base46_cache)) do + -- dofile(vim.g.base46_cache .. v) + -- end end, }, { diff --git a/.config/nvim/lua/plugins/vim-swap.lua b/.config/nvim/lua/plugins/vim-swap.lua new file mode 100644 index 0000000..482e18a --- /dev/null +++ b/.config/nvim/lua/plugins/vim-swap.lua @@ -0,0 +1,5 @@ +---@type LazySpec +return { + 'machakann/vim-swap', + keys = { 'g>', 'g<' }, +} diff --git a/.config/nvim/lua/sp/old-plugins/editorconfig.lua b/.config/nvim/lua/sp/old-plugins/editorconfig.lua deleted file mode 100644 index 6a19b1b..0000000 --- a/.config/nvim/lua/sp/old-plugins/editorconfig.lua +++ /dev/null @@ -1,5 +0,0 @@ -return { - 'gpanders/editorconfig.nvim', - enabled = false, - event = 'BufRead', -} diff --git a/.config/nvim/lua/sp/old-plugins/lsp.lua b/.config/nvim/lua/sp/old-plugins/lsp.lua deleted file mode 100644 index c4f56ae..0000000 --- a/.config/nvim/lua/sp/old-plugins/lsp.lua +++ /dev/null @@ -1,719 +0,0 @@ -local sp = require 'sp.util' -return { - { - 'neovim/nvim-lspconfig', - enabled = false, - dependencies = { - 'williamboman/mason.nvim', - 'williamboman/mason-lspconfig.nvim', - 'b0o/schemastore.nvim', - { - 'lvimuser/lsp-inlayhints.nvim', - config = function() - require('lsp-inlayhints').setup() - vim.api.nvim_create_autocmd('LspAttach', { - group = sp.au_lsp, - callback = function(args) - if not (args.data and args.data.client_id) then - return - end - - local bufnr = args.buf - local client = vim.lsp.get_client_by_id(args.data.client_id) - require('lsp-inlayhints').on_attach(client, bufnr) - end, - }) - end, - }, - { - 'folke/neodev.nvim', - opts = {}, - }, - { - 'creativenull/efmls-configs-nvim', - version = 'v1.x.x', - }, - -- 'simrat39/rust-tools.nvim' - }, - config = function() - local lspconfig = require 'lspconfig' - require('lspconfig.ui.windows').default_options.border = 'rounded' - local util = lspconfig.util - vim.diagnostic.config({ - --- {{{ - underline = true, - update_in_insert = false, - virtual_text = { - spacing = 4, - source = 'always', - -- severity = 'error' - -- prefix = '👾', - }, - signs = true, - severity_sort = true, - float = { show_header = true, source = 'always' }, - }) - vim.fn.sign_define( - 'DiagnosticSignError', - { text = require('sp.icons').diagnostics.BoldError, texthl = 'DiagnosticSignError' } - ) - vim.fn.sign_define( - 'DiagnosticSignWarn', - { text = require('sp.icons').diagnostics.BoldWarning, texthl = 'DiagnosticSignWarn' } - ) - vim.fn.sign_define( - 'DiagnosticSignInfo', - { text = require('sp.icons').diagnostics.BoldInformation, texthl = 'DiagnosticSignInfo' } - ) - vim.fn.sign_define( - 'DiagnosticSignHint', - { text = require('sp.icons').diagnostics.BoldHint, texthl = 'DiagnosticSignHint' } - ) - local cmp_capabilities = vim.lsp.protocol.make_client_capabilities() - cmp_capabilities.textDocument.completion.completionItem.snippetSupport = true - cmp_capabilities.textDocument.completion.completionItem.resolveSupport = { - properties = { 'documentation', 'detail', 'additionalTextEdits' }, - } - cmp_capabilities = require('cmp_nvim_lsp').default_capabilities(cmp_capabilities) - cmp_capabilities.textDocument.foldingRange = { - dynamicRegistration = false, - lineFoldingOnly = true, - } - - local mason_lspconfig = require 'mason-lspconfig' - require('mason').setup({ - ---@type '"prepend"' | '"append"' | '"skip"' - PATH = 'append', - ui = { - icons = { - package_installed = '✓', - package_uninstalled = '✗', - package_pending = '⟳', - }, - }, - }) - mason_lspconfig.setup({ - ensure_installed = { - 'lua_ls', - 'efm', - 'astro', - 'bashls', - 'clangd', - 'cssls', - 'docker_compose_language_service', - 'dockerls', - 'efm', - 'emmet_language_server', - 'eslint', - 'gopls', - 'html', - 'jsonls', - 'prismals', - 'svelte', - 'tailwindcss', - 'tsserver', - 'vimls', - 'volar', - 'yamlls', - 'zk', - }, - }) - local opts = {} - opts.capabilities = cmp_capabilities - opts.on_attach = sp.on_attach - -- opts.flags = { debounce_text_changes = 150, } - mason_lspconfig.setup_handlers({ - emmet_ls = function() - lspconfig['emmet_ls'].setup(opts) - end, - clangd = function() - local opt = vim.deepcopy(opts) - opt.capabilities.offsetEncoding = 'utf-8' - opt.cmd = { - 'clangd', - '--background-index', - '--clang-tidy', - '--suggest-missing-includes', - '--header-insertion=iwyu', - '--completion-style=detailed', - '--function-arg-placeholders', - '--pch-storage=memory', - '--fallback-style=llvm', - } - opt.init_options = { - usePlaceholders = true, - completeUnimported = true, - clangdFileStatus = true, - } - lspconfig.clangd.setup(opt) - end, - efm = function() - -- local eslint = require 'efmls-configs.linters.eslint_d' - local prettier = require 'efmls-configs.formatters.prettier_d' - local stylua = require 'efmls-configs.formatters.stylua' - local shfmt = require 'efmls-configs.formatters.shfmt' - local shellcheck = require 'efmls-configs.linters.shellcheck' - local go = { - require 'efmls-configs.linters.golangci_lint', - require 'efmls-configs.formatters.gofumpt', - } - local c = { - require 'efmls-configs.formatters.clang_format', - require 'efmls-configs.linters.clang_tidy', - } - - local languages = { - c = c, - cpp = c, - go = go, - typescript = { prettier }, - typescriptreact = { prettier }, - javascript = { prettier }, - javascriptreact = { prettier }, - html = { prettier }, - css = { prettier }, - scss = { prettier }, - less = { prettier }, - graphql = { prettier }, - json = { prettier }, - jsonc = { prettier }, - json5 = { prettier }, - vue = { prettier }, - svelte = { prettier }, - markdown = { prettier }, - lua = { stylua }, - bash = { shfmt, shellcheck }, - sh = { shfmt, shellcheck }, - zsh = { shfmt, shellcheck }, - } - lspconfig.efm.setup({ - init_options = { - documentFormatting = true, - documentRangeFormatting = true, - }, - filetypes = vim.tbl_keys(languages), - settings = { - rootMarkers = { '.git/' }, - languages = languages, - }, - -- cmd = { - -- 'efm-langserver', - -- -- '-c', - -- -- vim.fn.expand '~/.config/efm-langserver/config.yaml', - -- '-logfile', - -- '/tmp/efm-langserver-logs.log', - -- }, - on_attach = function(_, buf) - vim.keymap.set({ 'n', 'v' }, '=', function() - vim.lsp.buf.format({ - async = true, - filter = function(client) - return client.name == 'efm' - end, - }) - end, { buffer = buf, desc = 'Efm Fix' }) - end, - }) - end, - rust_analyzer = function() - local opt = vim.deepcopy(opts) - local function handler(err) - if err then - error(tostring(err)) - end - vim.notify 'Cargo workspace reloaded' - end - local function fly_check() - local params = vim.lsp.util.make_text_document_params() - vim.lsp.buf_notify(0, 'rust-analyzer/runFlyCheck', params) - end - local function reload_workspace() - vim.notify 'Reloading Cargo Workspace' - vim.lsp.buf_request(0, 'rust-analyzer/reloadWorkspace', nil, handler) - end - opt.on_attach = function(client, bufnr) - sp.on_attach(client, bufnr) - vim.keymap.set('n', '=', vim.lsp.buf.format, { buffer = bufnr, desc = 'Format Buffer(LSP)' }) - end - opt.settings = { - ['rust-analyzer'] = { - diagnostics = { - enable = true, - }, - check = { features = 'all' }, - inlayHints = { - closureCaptureHints = { - enable = true, - }, - }, - lens = { - references = { - adt = { enable = true }, - enumVariant = { enable = true }, - method = { enable = true }, - trait = { enable = true }, - }, - }, - typing = { autoClosingAngleBrackets = { enable = true } }, - }, - } - opt.checkOnSave = { - allFeatures = true, - overrideCommand = { - 'cargo', - 'clippy', - '--workspace', - '--message-format=json', - '--all-targets', - '--all-features', - }, - } - opt.commands = { - RustFlyCheck = { fly_check }, - RustReloadWorkspace = { reload_workspace }, - } - lspconfig['rust_analyzer'].setup(opt) - end, - gopls = function() - local opt = vim.deepcopy(opts) - opt.settings = { - gopls = { - experimentalPostfixCompletions = true, - analyses = { unusedparams = true, shadow = true, nilness = true, unusedwrite = true }, - hints = { - assignVariableTypes = true, - compositeLiteralFields = true, - compositeLiteralTypes = true, - constantValues = true, - functionTypeParameters = true, - parameterNames = true, - rangeVariableTypes = true, - }, - staticcheck = true, - codelenses = { - usePlaceholders = true, - }, - }, - } - lspconfig['gopls'].setup(opt) - end, - bashls = function() - local opt = vim.deepcopy(opts) - opt.cmd = { sp.bun_path() .. '/bash-language-server', 'start' } - opt.settings = { bashIde = { highlightParsingErrors = true } } - lspconfig['bashls'].setup(opt) - end, - html = function() - local opt = vim.deepcopy(opts) - opt.cmd = { sp.bun_path() .. '/vscode-html-language-server', '--stdio' } - lspconfig['html'].setup(opt) - end, - cssls = function() - local opt = vim.deepcopy(opts) - opt.cmd = { sp.bun_path() .. '/vscode-css-language-server', '--stdio' } - opt.settings = { - css = { - validate = true, - completion = { - triggerPropertyValueCompletion = true, - completePropertyWithSemicolon = true, - }, - lint = { - compatibleVendorPrefixes = 'warn', - duplicateProperties = 'warn', - boxModel = 'warn', - unknownVendorSpecificProperties = 'warn', - float = 'error', - }, - }, - scss = { - validate = true, - completion = { - triggerPropertyValueCompletion = true, - completePropertyWithSemicolon = true, - }, - lint = { - compatibleVendorPrefixes = 'warn', - duplicateProperties = 'warn', - boxModel = 'warn', - unknownVendorSpecificProperties = 'warn', - float = 'error', - }, - }, - } - lspconfig['cssls'].setup(opt) - end, - eslint = function() - lspconfig['eslint'].setup({ - cmd = { sp.bun_path() .. '/vscode-eslint-language-server', '--stdio' }, - on_attach = function(_, bufnr) - -- vim.api.nvim_create_autocmd('BufWritePre', { - -- buffer = bufnr, - -- command = 'EslintFixAll', - -- }) - vim.keymap.set('n', 'g=', 'EslintFixAll', { buffer = bufnr, desc = 'Eslint Fix' }) - end, - }) - end, - pylyzer = function() - local opt = vim.deepcopy(opts) - lspconfig['pylyzer'].setup(opt) - end, - pylsp = function() - local opt = vim.deepcopy(opts) - opt.settings = { - pylsp = { - plugins = { - -- formatter options - black = { enabled = true }, - autopep8 = { enabled = false }, - yapf = { enabled = false }, - flake8 = { enabled = true }, - pycodestyle = { enabled = false }, - -- type checker - pylsp_mypy = { enabled = true }, - -- auto-completion options - jedi_completion = { fuzzy = true }, - -- import sorting - pyls_isort = { enabled = true }, - -- rope_autoimport = { enabled = true, memory = true }, - -- rope_completion = { enabled = true }, - }, - }, - } - opt.flags = { - debounce_text_changes = 200, - } - lspconfig['pylsp'].setup(opt) - end, - pyright = function() - local opt = vim.deepcopy(opts) - -- opt.cmd = { sp.bun_path() .. '/pyright-langserver', '--stdio' } - opt.settings = { - python = { - analysis = { - autoImportCompletions = true, - typeCheckingMode = 'basic', - }, - exclude = { '**/node_modules', '**/__pycache__' }, - }, - } - lspconfig['pyright'].setup(opt) - end, - jsonls = function() - local opt = vim.deepcopy(opts) - opt.cmd = { sp.bun_path() .. '/vscode-json-language-server', '--stdio' } - opt.settings = { - json = { - schemas = vim.list_extend({ - { - name = 'Vsnip snippets', - description = 'Extend vs code snippet completion for vsnip', - fileMatch = { string.format('%s/vsnip/*.json', vim.fn.stdpath 'config') }, - url = 'https://raw.githubusercontent.com/Yash-Singh1/vscode-snippets-json-schema/main/schema.json', - }, - }, require('schemastore').json.schemas()), - validate = { enable = true }, - format = { enable = false }, - }, - } - lspconfig['jsonls'].setup(opt) - end, - yamlls = function() - local opt = vim.deepcopy(opts) - opt.cmd = { sp.bun_path() .. '/yaml-language-server', '--stdio' } - opt.settings = { - redhat = { telemetry = { enabled = false } }, - yaml = { - schemas = require('schemastore').yaml.schemas({}), - }, - } - lspconfig['yamlls'].setup(opt) - end, - ['lua_ls'] = function() - -- IMPORTANT: make sure to setup neodev BEFORE lspconfig - require('neodev').setup({ - -- add any options here, or leave empty to use the default settings - }) - local opt = vim.deepcopy(opts) - -- local runtime_path = vim.split(package.path, ';') - -- table.insert(runtime_path, 'lua/?.lua') - -- table.insert(runtime_path, 'lua/?/init.lua') - -- table.insert(runtime_path, '/usr/share/awesome/lib/?.lua') - -- table.insert(runtime_path, '/usr/share/awesome/lib/?/?.lua') - -- table.insert(runtime_path, '/usr/share/awesome/themes/?/?.lua') - -- table.insert(runtime_path, '/usr/share/awesome/lib/awful/?.lua') - -- table.insert(runtime_path, '/usr/share/awesome/lib/wibox/?.lua') - opt.settings = { - Lua = { - diagnostics = { - enable = true, - globals = { 'vim', 'describe' }, - disable = { 'lowercase-global' }, - }, - workspace = { checkThirdParty = false }, - -- runtime = { version = 'LuaJIT', path = runtime_path }, - runtime = { version = 'LuaJIT' }, - telemetry = { enable = false }, - hint = { - enable = true, - setType = true, - semicolon = 'SameLine', - paramType = true, - await = true, - arrayIndex = 'Enable', - }, - }, - } - lspconfig.lua_ls.setup(opt) - end, - tailwindcss = function() - local opt = vim.deepcopy(opts) - opt.cmd = { sp.bun_path() .. '/tailwindcss-language-server', '--stdio' } - opt.root_dir = util.root_pattern( - 'tailwind.config.js', - 'tailwind.config.cjs', - 'tailwind.config.mjs', - 'tailwind.config.ts', - 'postcss.config.js', - 'postcss.config.cjs', - 'postcss.config.mjs', - 'postcss.config.ts' - ) - opt.settings = { - tailwindCSS = { - emmetCompletions = true, - validate = 'error', - }, - } - opt.single_file_support = false - lspconfig['tailwindcss'].setup(opt) - end, - tsserver = function() - -- local opt = vim.deepcopy(opts) - -- opt.cmd = { sp.bun_path() .. '/typescript-language-server', '--stdio' } - -- opt.filetypes = { 'javascriptreact', 'typescriptreact', 'javascript.jsx', 'typescript.tsx' } - -- opt.root_dir = util.root_pattern('package.json', 'tsconfig.json', 'jsconfig.json') - -- opt.init_options = { - -- hostInfo = 'neovim', - -- plugins = { - -- -- for TypeScript v4.9+ - -- -- '@styled/typescript-styled-plugin', - -- -- or for older TypeScript versions - -- 'typescript-styled-plugin', - -- }, - -- } - -- opt.settings = { - -- javascript = { - -- inlayHints = { - -- includeInlayEnumMemberValueHints = true, - -- includeInlayFunctionLikeReturnTypeHints = true, - -- includeInlayFunctionParameterTypeHints = true, - -- includeInlayParameterNameHints = 'all', -- 'none' | 'literals' | 'all'; - -- includeInlayParameterNameHintsWhenArgumentMatchesName = true, - -- includeInlayPropertyDeclarationTypeHints = true, - -- includeInlayVariableTypeHints = true, - -- }, - -- }, - -- typescript = { - -- inlayHints = { - -- includeInlayEnumMemberValueHints = true, - -- includeInlayFunctionLikeReturnTypeHints = true, - -- includeInlayFunctionParameterTypeHints = true, - -- includeInlayParameterNameHints = 'all', -- 'none' | 'literals' | 'all'; - -- includeInlayParameterNameHintsWhenArgumentMatchesName = true, - -- includeInlayPropertyDeclarationTypeHints = true, - -- includeInlayVariableTypeHints = true, - -- }, - -- }, - -- } - -- require('lspconfig').tsserver.setup(opt) - end, - denols = function() - local opt = vim.deepcopy(opts) - opt.root_dir = util.root_pattern('deno.json', 'deno.jsonc') - opt.settings = { - deno = { - enable = true, - lint = true, - codeLens = { - references = true, - test = true, - implementations = true, - referencesAllFunctions = false, - }, - inlayHints = { - enumMemberValues = { enabled = true }, - variableTypes = { enabled = true, suppressWhenArgumentMatchesName = true }, - parameterNames = { enabled = 'all', suppressWhenArgumentMatchesName = true }, - parameterTypes = { enabled = true }, - functionLikeReturnTypes = { enabled = true }, - propertyDeclarationTypes = { enabled = true }, - }, - suggest = { - completeFunctionCalls = true, - autoImports = true, - imports = { - hosts = { - ['https://crux.land'] = true, - ['https://deno.land'] = true, - ['https://x.nest.land'] = true, - }, - }, - }, - }, - } - - lspconfig['denols'].setup(opt) - end, - volar = function() - local function get_typescript_server_path(root_dir) - -- local global_ts = vim.fn.stdpath 'data' .. '/mason/packages/vue-language-server/node_modules/typescript/lib' - local global_ts = string.format('%s/install/global/node_modules/typescript/lib', os.getenv 'BUN_INSTALL') - local found_ts = '' - local function check_dir(path) - found_ts = util.path.join(path, 'node_modules', 'typescript', 'lib') - if util.path.exists(found_ts) then - return path - end - end - if util.search_ancestors(root_dir, check_dir) then - return found_ts - else - return global_ts - end - end - local opt = vim.deepcopy(opts) - opt.cmd = { sp.bun_path() .. '/vue-language-server', '--stdio' } - -- opt.filetypes = { 'typescript', 'javascript', 'vue' } - opt.filetypes = { 'vue' } - opt.on_new_config = function(new_config, new_root_dir) - new_config.init_options.typescript.tsdk = get_typescript_server_path(new_root_dir) - end - lspconfig['volar'].setup(opt) - end, - svelte = function() - local opt = vim.deepcopy(opts) - opt.cmd = { sp.bun_path() .. '/svelteserver', '--stdio' } - opt.settings = { - svelte = { - ['enable-ts-plugin'] = true, - plugin = { svelte = { defaultScriptLanguage = 'typescript' } }, - }, - } - lspconfig['svelte'].setup(opt) - end, - function(server_name) - if server_name ~= 'zk' then - lspconfig[server_name].setup(opts) - end - end, - }) - lspconfig['pylsp'].setup({ - capabilities = cmp_capabilities, - on_attach = sp.on_attach, - settings = { - pylsp = { - plugins = { - -- formatter options - black = { enabled = true }, - autopep8 = { enabled = false }, - yapf = { enabled = false }, - flake8 = { enabled = true }, - pycodestyle = { enabled = false }, - -- type checker - pylsp_mypy = { enabled = true }, - -- auto-completion options - jedi_completion = { fuzzy = true }, - -- import sorting - pyls_isort = { enabled = true }, - -- rope_autoimport = { enabled = true, memory = true }, - -- rope_completion = { enabled = true }, - }, - }, - }, - flags = { - debounce_text_changes = 200, - }, - }) - - lspconfig['ocamllsp'].setup({ - on_attach = function(client, bufnr) - sp.on_attach(client, bufnr) - vim.keymap.set( - 'n', - '=', - 'lua vim.lsp.buf.format{async=true}', - { buffer = bufnr, desc = 'LspFormat' } - ) - end, - capabilities = cmp_capabilities, - }) - end, - }, - { - 'pmizio/typescript-tools.nvim', - dependencies = { 'nvim-lua/plenary.nvim', 'neovim/nvim-lspconfig' }, - opts = { - on_attach = function(client, buffer) - sp.on_attach(client, buffer) - vim.keymap.set('n', 'go', 'TSToolsOrganizeImports', { buffer = buffer }) - vim.keymap.set('n', 'gD', 'TSToolsGoToSourceDefinition', { buffer = buffer }) - vim.keymap.set('n', 'gR', 'TSToolsFileReferences', { buffer = buffer }) - vim.keymap.set('n', '', 'TSToolsRenameFile', { buffer = buffer, silent = false }) - end, - settings = { - tsserver_file_preferences = { - includeInlayParameterNameHints = 'literals', - includeCompletionsForModuleExports = true, - includeCompletionsForImportStatements = true, - includeAutomaticOptionalChainCompletions = true, - includeCompletionsWithClassMemberSnippets = true, - allowIncompleteCompletions = true, - includeInlayFunctionParameterTypeHints = true, - includeInlayParameterNameHintsWhenArgumentMatchesName = false, - includeInlayVariableTypeHints = true, - includeInlayVariableTypeHintsWhenTypeMatchesName = false, - includeInlayPropertyDeclarationTypeHints = true, - includeInlayFunctionLikeReturnTypeHints = true, - includeCompletionsWithSnippetText = true, - }, - tsserver_plugins = { - '@styled/typescript-styled-plugin', - }, - tsserver_max_memory = '3072', - }, - }, - ft = { 'javascriptreact', 'typescriptreact', 'javascript.jsx', 'typescript.tsx', 'javascript', 'typescript' }, - config = function() - require('typescript-tools').setup({ - on_attach = function(client, bufnr) - sp.on_attach(client, bufnr) - vim.keymap.set('n', 'go', 'TSToolsOrganizeImports', { buffer = bufnr }) - vim.keymap.set('n', 'gD', 'TSToolsGoToSourceDefinition', { buffer = bufnr }) - vim.keymap.set('n', 'gR', 'TSToolsFileReferences', { buffer = bufnr }) - vim.keymap.set('n', '', 'TSToolsRenameFile', { buffer = bufnr, silent = false }) - end, - settings = { - tsserver_file_preferences = { - includeInlayParameterNameHints = 'all', - includeCompletionsForModuleExports = true, - includeInlayParameterNameHintsWhenArgumentMatchesName = false, - includeInlayFunctionParameterTypeHints = true, - includeInlayVariableTypeHints = true, - includeInlayVariableTypeHintsWhenTypeMatchesName = false, - includeInlayPropertyDeclarationTypeHints = true, - includeInlayFunctionLikeReturnTypeHints = true, - includeInlayEnumMemberValueHints = true, - }, - tsserver_plugins = { - -- for TypeScript v4.9+ - '@styled/typescript-styled-plugin', - -- or for older TypeScript versions - -- "typescript-styled-plugin", - }, - }, - }) - end, - }, -} diff --git a/.config/nvim/lua/sp/old-plugins/rust.lua b/.config/nvim/lua/sp/old-plugins/rust.lua deleted file mode 100644 index 2058a58..0000000 --- a/.config/nvim/lua/sp/old-plugins/rust.lua +++ /dev/null @@ -1,50 +0,0 @@ -return { - 'mrcjkb/rustaceanvim', - version = '^3', -- Recommended - enabled = false, - ft = { 'rust' }, - init = function() - vim.g.rustaceanvim = { - -- Plugin configuration - -- tools = {}, - -- LSP configuration - server = { - on_attach = function(client, bufnr) - require('sp.util').on_attach(client, bufnr) - vim.keymap.set('n', '=', vim.lsp.buf.format, { buffer = bufnr, desc = 'Format Buffer(Rust)' }) - vim.keymap.set('n', 'J', 'RustLsp joinLines', { buffer = bufnr, desc = 'Rust JoinLines' }) - vim.keymap.set('n', 'gL', 'RustLsp explainError', { buffer = bufnr, desc = 'Explain errors' }) - end, - settings = { - -- rust-analyzer language server configuration - ['rust-analyzer'] = { - diagnostics = { enable = true }, - check = { features = 'all' }, - inlayHints = { closureCaptureHints = { enable = true } }, - lens = { - references = { - adt = { enable = true }, - enumVariant = { enable = true }, - method = { enable = true }, - trait = { enable = true }, - }, - }, - checkOnSave = { - command = { - 'cargo', - 'clippy', - '--workspace', - '--message-format=json', - '--all-targets', - '--all-features', - }, - }, - typing = { autoClosingAngleBrackets = { enable = true } }, - }, - }, - }, - -- DAP configuration - -- dap = {}, - } - end, -} diff --git a/.config/nvim/lua/sp/snippets/cpp.json b/.config/nvim/lua/sp/snippets/cpp.json deleted file mode 100644 index 1ee7692..0000000 --- a/.config/nvim/lua/sp/snippets/cpp.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "using_namespace": { - "prefix": ["usd", "uns"], - "body": ["using namespace ${1:std};", "$0"], - "description": "using namespace std" - }, - "cpp": { - "prefix": "cpp", - "body": [ - "#include ", - "", - "using namespace std;", - "", - "int main() {", - "\t$1", - "\treturn 0;", - "}" - ], - "description": "C++ quick start" - } -} diff --git a/.config/nvim/lua/sp/snippets/go.json b/.config/nvim/lua/sp/snippets/go.json deleted file mode 100644 index e6aa6ff..0000000 --- a/.config/nvim/lua/sp/snippets/go.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "var": { - "prefix": ["v", "var"], - "body": "${1:name} := $2", - "description": "Create a variable and assign value to it" - } -} diff --git a/.config/nvim/lua/sp/snippets/javascript.json b/.config/nvim/lua/sp/snippets/javascript.json deleted file mode 100644 index a4bb2aa..0000000 --- a/.config/nvim/lua/sp/snippets/javascript.json +++ /dev/null @@ -1,372 +0,0 @@ -{ - "require module": { - "prefix": "req", - "body": "const $1 = require('$1');" - }, - "beforeAll Async": { - "prefix": "bfa", - "body": "beforeAll(async () => { $0 })" - }, - "regex-test-digits": { - "prefix": "node-regex-test-digits", - "body": [ - "const isMatch = /\\d+/.test('abc123')" - ], - "description": "test if string contains digits, returns true/false" - }, - "regex-test-word": { - "prefix": "node-regex-test-word", - "body": [ - "const isMatch = /\\w+/.test('abc123')" - ], - "description": "test if string contains a word boundary, returns true/false" - }, - "regex-test-match": { - "prefix": "node-regex-match", - "body": [ - "const [, extension] = 'file.txt'.match(/\\.(\\w+)/)" - ], - "description": "matches a file extension" - }, - "regex-test-match-named-group": { - "prefix": "node-regex-match-named-group", - "body": [ - "const { groups: { extension } } = 'file.txt'.match(/\\.(?\\w+)/)" - ], - "description": "matches a file extension, " - }, - "express server": { - "prefix": "node-express", - "body": [ - "const express = require('express')", - "const app = express()", - "const port = 3000", - "", - "app.get('/', (req, res) => res.send('Hello World!'))", - "app.listen(port, () => console.log(`Example app listening on port \\${port\\}!`))" - ], - "description": "Creates an express server" - }, - "express GET": { - "prefix": "node-express-get", - "body": [ - "app.get('/', (req, res) => {", - " res.send('GET request to the homepage')", - "})" - ], - "description": "Creates a GET route" - }, - "express GET params": { - "prefix": "node-express-get-params", - "body": [ - "app.get('/books/:bookId', (req, res) => {", - " res.send(req.params.bookId)", - "})" - ], - "description": "Creates a GET route and shows how to access params" - }, - "express POST": { - "prefix": "node-express-post", - "body": [ - "app.post('/', function (req, res) {", - " res.send('POST request to the homepage')", - "})" - ], - "description": "Creates a POST route" - }, - "express POST params": { - "prefix": "node-express-post-params", - "body": [ - "var bodyParser = require('body-parser');", - "app.use(bodyParser.json());", - "", - "app.post('/update', function(req, res) {", - " const { name, description } = req.body;", - " res.send(`Name \\${name\\}, desc \\${description\\}`);", - "});" - ], - "description": "Creates a POST route that can read from the body" - }, - "express PUT params": { - "prefix": "node-express-put-params", - "body": [ - "var bodyParser = require('body-parser');", - "app.use(bodyParser.json());", - "", - "app.put('/products', function(req, res) {", - " const { id, name, description } = req.body;", - " res.send(`Name \\${id\\} \\${name\\}, desc \\${description\\}`);", - "});" - ], - "description": "Creates a POST route that can read from the body" - }, - "express DELETE params": { - "prefix": "node-express-delete-params", - "body": [ - "var bodyParser = require('body-parser');", - "app.use(bodyParser.json());", - "", - "app.delete('/products/:id', function(req, res) {", - " const { id } = req.params;", - " res.send(`Delete record with id \\${id\\}`);", - "});" - ], - "description": "Creates a POST route that can read from the body" - }, - "express QUERY params": { - "prefix": "node-express-query-params", - "body": [ - "var bodyParser = require('body-parser');", - "app.use(bodyParser.json());", - "", - "// for routes looking like this `/products?page=1&pageSize=50`", - "app.get('/products', function(req, res) {", - " const page = req.query.page;", - " const pageSize = req.query.pageSize;", - " res.send(`Filter with parameters \\${page\\} and \\${pageSize\\});`", - "});" - ], - "description": "Creates a POST route that can read from the body" - }, - "express POST params version >=4.16": { - "prefix": "node-express-post-params-alt", - "body": [ - "app.use(express.json())", - "app.listen(8080)", - "", - "app.post('/test', (req, res) => {", - " res.json({ body: req.body })", - "});" - ], - "description": "Creates a POST route that can read from the body, works for 4.16 version of express and above" - }, - "express middleware": { - "prefix": "node-express-middleware-logger", - "body": [ - "const logger = function (req, res, next) {", - " console.log('logging')", - " next()", - "}", - "", - "app.use(logger)", - "", - "app.get('/', (req, res) => {", - " res.send('Hello World!')", - "})" - ], - "description": "Creates a middleware" - }, - "express middleware error": { - "prefix": "node-express-middleware-error", - "body": [ - "app.use(function (err, req, res, next) {", - " console.error(err.stack)", - " res.status(500).send('Something broke!')", - "});" - ], - "description": "Creates a error middleware" - }, - "event emitter": { - "prefix": "node-event-emitter", - "body": [ - "var events = require('events');", - "var eventEmitter = new events.EventEmitter();", - "eventEmitter.emit('my_event');", - "eventEmitter.on('my_event', () => {", - " console.log('data received successfully.');", - "});" - ], - "description": "Event emitter, shows emitting event and subscribing to it" - }, - "Promise creation": { - "prefix": "node-promise-create", - "body": [ - "new Promise((resolve, reject) => {", - " let condition = false;", - " if(condition) {", - " resolve('data')", - " } else {", - " reject('error')", - "}", - "})" - ], - "description": "creates a Promise by instantiating it" - }, - "Promise shorthand": { - "prefix": "node-promise-shorthand", - "body": [ - "const promiseThatWillResolve = Promise.resolve('data');", - "const promiseThatWillReject = Promise.reject('error');" - ], - "description": "uses the static resolve/reject, good for unit tests" - }, - "Promise all": { - "prefix": "node-promise-all", - "body": [ - "const getData = () => Promise.resolve('data');", - "const getMoreData = () => Promise.resolve('more data');", - "", - "Promise.all(", - " getData(),", - " getMoreData()", - ").then(result => {", - " const [data, moreData] = result;", - "})" - ], - "description": "uses the static all(), allows us to have a list of Promises finish at the same time" - }, - "Async/await": { - "prefix": "node-async-await", - "body": [ - "async function getData() {", - " return Promise.resolve('data');", - "}", - "", - "async function getMoreData(data) {", - " return Promise.resolve(data + 'more data');", - "}", - "", - "async function getAll() {", - " const data = await getData();", - " const moreData = await getMoreData(data);", - " return `All the data: \\${data\\}, \\${moreData\\}`;", - "}", - "", - "getAll().then((all) => {", - " console.log('all the data')", - "})" - ], - "description": "demonstrates async/await" - }, - "Joi schema validation": { - "prefix": "node-express-schema-validation", - "body": [ - "const Joi = require('joi');", - "const loginSchema = Joi.object().keys({", - " username: Joi.string()", - " .min(3),", - " .max(10),", - " .required(),", - " password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/)", - "});", - "", - "app.post('/login', function(req, res) {", - " const valid = Joi.validate(req.body, loginSchema).error === null;", - " if (!valid) {", - " res.status(422).json({", - " status: 'error'", - " message: 'Invalid request data'", - " data: req.body", - " });", - " } else {", - " // happy days - login user", - " res.send(`ok`);", - " }", - "});" - ], - "description": "showcases the lib Joi and how you can use it to validate incoming requests" - }, - "supertest-init": { - "prefix": "node-supertest-init", - "body": [ - "const supertest = require('supertest')", - "const app = require('../app');", - "const server = app.listen(3000, () => {", - " console.log('listening at port 3000')", - "})", - "let request;" - ], - "description": "Sets up supertest by importing supertest and the app you mean to test. Additionally starts the app" - }, - "supertest-beforeall": { - "prefix": "node-supertest-beforeall", - "body": [ - "beforeAll(() => {", - " request = supertest(app)", - "})" - ], - "description": "Configures supertest to use the app, this is needed" - }, - "supertest-afterall": { - "prefix": "node-supertest-aftereall", - "body": [ - "afterAll(async(close) => {", - " server.close(() => {", - " close()", - " console.log('server closed');", - " })", - "})" - ], - "description": "Ensures the web app closes down after the test run, this is needed" - }, - "supertest-testGET": { - "prefix": "node-supertest-testget", - "body": [ - "test('testing a GET route', async () => {", - " let products = [", - " {", - " id: 1,", - " name: 'book'", - " },", - " {", - " id: 2,", - " name: 'book2'", - " }", - " ];", - "", - " const res = await request.get('/products');", - " expect(res.status).toBe(200);", - " expect(res.body).toEqual(products);", - "})" - ], - "description": "An example of supertest testing a GET route" - }, - "supertest-testGETWithParam": { - "prefix": "node-supertest-testgetwithparam", - "body": [ - "test('testing a GET route with router param', async () => {", - " let product = {", - " id: 1,", - " name: 'book'", - " };", - " const res = await request.get('/products/1');", - " expect(res.status).toBe(200);", - " expect(res.body).toEqual(product);", - "});" - ], - "description": "An example of supertest testing a GET route with a route parameter" - }, - "supertest-testPOSTWithParam": { - "prefix": "node-supertest-testpost", - "body": [ - "test('testing a POST route with a payload', async () => {", - " let product = {", - " name: 'book3'", - " };", - " const res = await request", - " .post('/products')", - " .send(product);", - " expect(res.status).toBe(200);", - " expect(res.body).toEqual({ id: 3, ...product});", - "", - " const newRes = await request.get('/products');", - " let products = [", - " {", - " id: 1,", - " name: 'book'", - " },", - " {", - " id: 2,", - " name: 'book2'", - " },", - " {", - " id: 3,", - " name: 'book3',", - " }", - " ];", - " expect(newRes.body).toEqual(products);", - "});" - ], - "description": "An example of supertest testing a POST route with a payload" - } -} diff --git a/.config/nvim/lua/sp/snippets/lua.json b/.config/nvim/lua/sp/snippets/lua.json deleted file mode 100644 index 1898f33..0000000 --- a/.config/nvim/lua/sp/snippets/lua.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "preq": { - "prefix": "preq", - "body": [ - "local ok,${1:module_name} = pcall(require,'${1}')", - "if not ok then return end", - "\n$0" - ], - "description": "Import module but exit if its not installed" - }, - "Lua module": { - "prefix": "luam", - "body": "local M = {}\n\nfunction M.config()\n\t$1\nend\n\nreturn M", - "description": "Create a module for lua which could be called in packer config" - } -} diff --git a/.config/nvim/lua/sp/snippets/markdown.json b/.config/nvim/lua/sp/snippets/markdown.json deleted file mode 100644 index 5138281..0000000 --- a/.config/nvim/lua/sp/snippets/markdown.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "link": { - "prefix": ["li", "ln", "link"], - "body": ["[${1:name}](https://${2:url}) $0"], - "description": "Insert link" - }, - "image": { - "prefix": ["img", "image"], - "body": ["![${1:caption}](https://${2:url}) $0"], - "description": "Insert image link" - }, - "Insert fenced code block": { - "prefix": "code", - "body": ["```${1:language}", "${TM_SELECTED_TEXT}$0", "```"], - "description": "Insert fenced code block" - } -} diff --git a/.config/nvim/lua/sp/snippets/package.json b/.config/nvim/lua/sp/snippets/package.json deleted file mode 100644 index 5d60810..0000000 --- a/.config/nvim/lua/sp/snippets/package.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "name": "user snippets", - "engines": { - "vscode": "^1.11.0" - }, - "contributes": { - "snippets": [ - { - "language": "vue", - "path": "./vue.json" - }, - { - "language": "typescript", - "path": "./typescript.json" - }, - { - "language": "typescriptreact", - "path": "./typescriptreact.json" - }, - { - "language": "go", - "path": "./go.json" - }, - { - "language": "cpp", - "path": "./cpp.json" - }, - { - "language": "lua", - "path": "./lua.json" - }, - { - "language": "markdown", - "path": "./markdown.json" - }, - { - "language": "svelte", - "path": "./svelte.json" - }, - { - "language": "javascript", - "path": "./javascript.json" - } - ] - } -} diff --git a/.config/nvim/lua/sp/snippets/sh.json b/.config/nvim/lua/sp/snippets/sh.json deleted file mode 100644 index fe55e41..0000000 --- a/.config/nvim/lua/sp/snippets/sh.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "sh": { - "prefix": ["sh", "bash", "bang"], - "body": ["#!/usr/bin/env ${1:sh}", "$0"], - "description": "Inserts shell bang" - }, - "die": { - "prefix": ["die"], - "body": ["die() {", "\techo $1", "\texit ${2:1}", "}", "$0"], - "description": "Creates a die function" - } -} diff --git a/.config/nvim/lua/sp/snippets/svelte.json b/.config/nvim/lua/sp/snippets/svelte.json deleted file mode 100644 index 2667d69..0000000 --- a/.config/nvim/lua/sp/snippets/svelte.json +++ /dev/null @@ -1,616 +0,0 @@ -{ - "svelte-component-format": { - "prefix": "s-component-format", - "body": [ - "", - "", - "", - "", - "${3:}" - ], - "description": "add a script to your svelte file" - }, - "svelte-script-tag": { - "prefix": "s-script", - "body": [""], - "description": "add a script to your svelte file" - }, - "svelte-script-context": { - "prefix": "s-script-context", - "body": [ - "" - ], - "description": "add a script with context=\"module\" to your svelte file" - }, - "svelte-style-tag": { - "prefix": "s-style", - "body": [""], - "description": "add styles to your svelte file" - }, - "svelte-expression": { - "prefix": "s-expression", - "body": ["{${1:expression}}"], - "description": "basic expression" - }, - "svelte-expression-html": { - "prefix": "s-expression-html", - "body": ["{@html ${1:expression}}"], - "description": "html content expression" - }, - "svelte-expression-debug": { - "prefix": "s-expression-debug", - "body": ["{@debug ${1:var1}${2:,var2}}"], - "description": "html content expression" - }, - "svelte-if-block": { - "prefix": "s-if-block", - "body": ["{#if ${1:condition}}", "\t${2: }", "{/if}"], - "description": "if block" - }, - "svelte-if-else-block": { - "prefix": "s-if-else-block", - "body": [ - "{#if ${1:condition}}", - "\t${2: }", - "{:else}", - "\t${3: }", - "{/if}" - ], - "description": "if else block" - }, - "svelte-else-block": { - "prefix": "s-else-block", - "body": ["{:else}", "\t${1: }"], - "description": "else block" - }, - "svelte-if-else-if-block": { - "prefix": "s-if-else-if-block", - "body": [ - "{#if ${1:condition}}", - "\t${2: }", - "{:else if ${3: otherCondition}}", - "\t${4: }", - "{:else}", - "\t${5: }", - "{/if}" - ], - "description": "if else if block" - }, - "svelte-else-if-block": { - "prefix": "s-else-if-block", - "body": [ - "{:else if ${1: otherCondition}}", - "\t${2: }" - ], - "description": "else if block" - }, - "svelte-each-block": { - "prefix": "s-each-block", - "body": [ - "{#each ${1:items} as ${2:item}}", - "\t${3: }", - "{/each}" - ], - "description": "each block" - }, - "svelte-each-else-block": { - "prefix": "s-each-else-block", - "body": [ - "{#each ${1:items} as ${2:item}}", - "\t${3: }", - "{:else}", - "\t${4: }", - "{/each}" - ], - "description": "each else block" - }, - "svelte-each-index-block": { - "prefix": "s-each-index-block", - "body": [ - "{#each ${1:items} as ${2:item},${3:i}}", - "\t${4: }", - "{/each}" - ], - "description": "each index block" - }, - "svelte-each-key-block": { - "prefix": "s-each-key-block", - "body": [ - "{#each ${1:items} as ${2:item},(${3:key})}", - "\t${4: }", - "{/each}" - ], - "description": "each index block" - }, - "svelte-each-index-key-block": { - "prefix": "s-each-index-key-block", - "body": [ - "{#each ${1:items} as ${2:item},i (${3:key})}", - "\t${4: }", - "{/each}" - ], - "description": "each index key block" - }, - "svelte-await-then-block": { - "prefix": "s-await-then-block", - "body": [ - "{#await ${1:promise}}", - "\t", - "{:then ${2:value}}", - "\t", - "{/await}" - ], - "description": "await then block" - }, - "svelte-then-block": { - "prefix": "s-then-block", - "body": ["{:then ${1:value}}", "\t"], - "description": "then block" - }, - "svelte-await-short-block": { - "prefix": "s-await-short-block", - "body": [ - "{#await ${1:promise} then ${2:value}}", - "\t", - "{/await}" - ], - "description": "await short block" - }, - "svelte-await-catch-block": { - "prefix": "s-await-catch-block", - "body": [ - "{#await ${1:promise}}", - "\t", - "{:then ${value}}", - "\t", - "{:catch error}", - "\t", - "{/await}" - ], - "description": "await catch block" - }, - "svelte-catch-block": { - "prefix": "s-catch-block", - "body": ["{:catch error}", "\t"], - "description": "catch block" - }, - "svelte-on-event": { - "prefix": "s-on-event", - "body": ["on:${1:eventname}={${2:handler}}"], - "description": "on event" - }, - "svelte-on-event-forward": { - "prefix": "s-on-event-foward", - "body": ["on:${1:eventname}"], - "description": "on event foward" - }, - "svelte-on-event-modifiers": { - "prefix": "s-on-event-modifiers", - "body": [ - "on:${1:eventname}|${2|preventDefault,stopPropagation,passive,capture,once|}={${3:handler}}" - ], - "description": "on event w/ modifiers" - }, - "svelte-on-event-inline": { - "prefix": "s-on-event-inline", - "body": ["on:${1:click}=\"{() => ${2:count += 1}}\""], - "description": "on event inline" - }, - "svelte-modifiers": { - "prefix": "s-modifier", - "body": ["|${1|preventDefault,stopPropagation,passive,capture,once|}"], - "description": "modifier" - }, - "svelte-bind": { - "prefix": "s-bind", - "body": ["bind:${1:property}"], - "description": "bind property" - }, - "svelte-bind-property": { - "prefix": "s-bind-property", - "body": ["bind:${1:property}={${2:variable}}"], - "description": "bind property" - }, - "svelte-bind-video": { - "prefix": "s-bind-video", - "body": [ - "" - ], - "description": "bind property" - }, - "svelte-bind-audio": { - "prefix": "s-bind-audio", - "body": [ - "" - ], - "description": "bind property" - }, - "svelte-bind-media-elements": { - "prefix": "s-bind-media-elements", - "body": [ - "bind:${1|duration,buffered,played,seekable,seeking,ended,currentTime,playbackRate,paused,volume,muted,videoWidth,videoHeight|}" - ], - "description": "bind property" - }, - "svelte-bind-block-level": { - "prefix": "s-bind-block-level", - "body": [ - "bind:${1|clientWidth,clientHeight,offsetWidth,offsetHeight|}={${2:variable}}" - ], - "description": "bind property" - }, - "svelte-bind-group": { - "prefix": "s-bind-group", - "body": ["bind:group={${1:variable}}"], - "description": "bind group" - }, - "svelte-bind-this": { - "prefix": "s-bind-this", - "body": ["bind:this={${1:dom_node}}"], - "description": "bind this" - }, - "svelte-class": { - "prefix": "s-class", - "body": ["class:${1:name}={${2:condition}}"], - "description": "class" - }, - "svelte-class-short": { - "prefix": "s-class-short", - "body": ["class:${1:name}}"], - "description": "class shorthand" - }, - "svelte-use": { - "prefix": "s-use", - "body": ["use:action"], - "description": "use action" - }, - "svelte-use-parameters": { - "prefix": "s-use-parameters", - "body": ["use:action={${1:parameters}}"], - "description": "use action w/ parameters" - }, - "svelte-transition": { - "prefix": "s-transition", - "body": ["${1|transition,in,out|}:${2:name}"], - "description": "transition" - }, - "svelte-transition-params": { - "prefix": "s-transition-params", - "body": ["${1|transition,in,out|}:${2:name}={${3:params}}"], - "description": "transition-params" - }, - "svelte-transition-events": { - "prefix": "s-transition-events", - "body": [ - "on:${1|introstart,introend,outrostart,outroend|}=\"{() => status = '${1|introstart,introend,outrostart,outroend|}'}\"" - ], - "description": "transition-events" - }, - "svelte-transition-local": { - "prefix": "s-transition-local", - "body": ["${1|transition,in,out|}:${2:name}|${3:local}"], - "description": "transition local" - }, - "svelte-transition-all": { - "prefix": "s-transition-all", - "body": ["${1|transition,in,out|}:${2:name}|${3:local}={${4:params}}"], - "description": "transition" - }, - "svelte-animate": { - "prefix": "s-animate", - "body": ["animate:${1:name}={${2:params}}"], - "description": "animate" - }, - "svelte-slot": { - "prefix": "s-slot", - "body": ["${1:}"], - "description": "slot" - }, - "svelte-slot-name": { - "prefix": "s-slot-name", - "body": ["${2:}"], - "description": "slot w/ name" - }, - "svelte-slot-prop": { - "prefix": "s-slot-prop", - "body": [ - "${3:}" - ], - "description": "slot w/ prop" - }, - "svelte-self": { - "prefix": "s-self", - "body": [""], - "description": "svelte:self" - }, - "svelte-self-prop": { - "prefix": "s-self-prop", - "body": [""], - "description": "svelte:self" - }, - "svelte-component": { - "prefix": "s-component", - "body": [""], - "description": "svelte:component" - }, - "svelte-window": { - "prefix": "s-window", - "body": [""], - "description": "svelte:window" - }, - "svelte-window-bind": { - "prefix": "s-window-bind", - "body": [ - "bind:${1|innerWidth,innerHeight,outerWidth,outerHeight,scrollX,scrollY,online|}={${2:variable}}" - ], - "description": "svelte:window bind properties" - }, - "svelte-body": { - "prefix": "s-body", - "body": [""], - "description": "svelte:body" - }, - "svelte-head": { - "prefix": "s-head", - "body": ["", "\t${1:}", ""], - "description": "svelte:head" - }, - "svelte-options": { - "prefix": "s-options", - "body": [ - "" - ], - "description": "svelte:options" - }, - "svelte-create-component": { - "prefix": "s-create-component", - "body": [ - "const component = new ${1:App}({", - "\ttarget: ${2|target,document.body|},", - "\tprops: ${3:props},", - "\tanchor: ${4:anchor},", - "\thydrate: ${5|false,true|},", - "\tintro: ${5|false,true|}", - "})" - ], - "description": "svelte create component" - }, - "svelte-reactive-statement": { - "prefix": "s-reactive-statement", - "body": ["$: ${1:variable} = ${2:prop}"], - "description": "reactive statement" - }, - "svelte-reactive-block": { - "prefix": "s-reactive-block", - "body": ["$: { ${1:console.log(${2:prop});}}"], - "description": "reactive block" - }, - "svelte-action": { - "prefix": "s-action", - "body": [ - "function ${1:foo}(node) {", - "\t// the node has been mounted in the DOM", - "\treturn {", - "\t\tdestroy() {", - "\t\t\t// the node has been removed from the DOM", - "\t\t}", - "\t};", - "}" - ], - "description": "action function" - }, - "svelte-action-parameters": { - "prefix": "s-action-parameters", - "body": [ - "function ${1:foo}(node, ${2:parameters}) {", - "\t// the node has been mounted in the DOM", - "\treturn {", - "\t\tdestroy() {", - "\t\t\t// the node has been removed from the DOM", - "\t\t}", - "\t};", - "}" - ], - "description": "action function" - }, - "svelte-action-update": { - "prefix": "s-action-update", - "body": [ - "function ${1:foo}(node, ${2:parameters}) {", - "\t// the node has been mounted in the DOM", - "\treturn {", - "\t\tupdate(${2:parameters}) {", - "\t\t\t// the value of `${2:parameters}` has changed", - "\t\t}", - "\t\tdestroy() {", - "\t\t\t// the node has been removed from the DOM", - "\t\t}", - "\t};", - "}" - ], - "description": "action w/ update function" - }, - "svelte-on-mount": { - "prefix": "s-lifecycle-mount", - "body": ["onMount(() => {", "\t${1:// content here}", "});"], - "description": "onMount lifecycle function" - }, - "svelte-before-update": { - "prefix": "s-lifecycle-before-update", - "body": ["beforeUpdate(() => {", "\t${1:// content here}", "});"], - "description": "beforeUpdate lifecycle function" - }, - "svelte-after-update": { - "prefix": "s-lifecycle-after-update", - "body": ["afterUpdate(() => {", "\t${1:// content here}", "});"], - "description": "afterUpdate lifecycle function" - }, - "svelte-on-destroy": { - "prefix": "s-lifecycle-destroy", - "body": ["onDestroy(() => {", "\t${1:// content here}", "});"], - "description": "onDestroy lifecycle function" - }, - "svelte-tick": { - "prefix": "s-tick", - "body": ["await tick()"], - "description": "svelte tick function" - }, - "svelte-set-context": { - "prefix": "s-set-content", - "body": ["setContext(${1:key}, ${2:context})"], - "description": "svelte setContext" - }, - "svelte-get-context": { - "prefix": "s-get-content", - "body": ["getContext(${1:key})"], - "description": "svelte getContext" - }, - "svelte-dispatch": { - "prefix": "s-dispatch", - "body": ["const dispatch = createEventDispatcher();"], - "description": "svelte dispatch" - }, - "svelte-dispatch-event": { - "prefix": "s-dispatch-event", - "body": ["dispatch(${1:key},${2:data})"], - "description": "svelte dispatch event" - }, - "svelte-writeable": { - "prefix": "s-writeable", - "body": ["const ${1:store} = writable(${2:initialValue});"], - "description": "svelte writeable" - }, - "svelte-writeable-set": { - "prefix": "s-writeable-set", - "body": [ - "const ${1:store} = writable(${2:initialValue}, () => {", - "\t${3:console.log('got a subscriber');}", - "\treturn () => ${4:console.log('no more subscribers');}", - "});" - ], - "description": "svelte writeable w/ set function" - }, - "svelte-readable": { - "prefix": "s-readable", - "body": [ - "const ${1:store} = readable(${2:initialValue}, () => {", - "\t${3:console.log('got a subscriber');}", - "\treturn () => ${4:console.log('no more subscribers');}", - "});" - ], - "description": "svelte readable (set function required)" - }, - "svelte-derived": { - "prefix": "s-derived", - "body": [ - "const ${1:derivedStore} = derived(${2:storeA}, $${2:storeA} => $${2:storeA} * 2);" - ], - "description": "svelte derived store" - }, - "svelte-derived-multiple": { - "prefix": "s-derived-multiple", - "body": [ - "const ${1:derivedStore} = derived([${2:storeA}, ${3:storeB}], ([$${2:storeA}, $${3:storeB}]) => $${2:storeA} + $${3:storeB});" - ], - "description": "svelte derived store" - }, - "svelte-derived-set": { - "prefix": "s-derived-set", - "body": [ - "const ${1:derivedStore} = derived(${2:storeA}, ($${2:storeA}, set) => {", - "\tsetTimeout(() => set($${2:storeA}), 1000);", - "}, 'one moment...');" - ], - "description": "svelte derived store" - }, - "svelte-derived-multiple-set": { - "prefix": "s-derived-multiple-set", - "body": [ - "const ${1:derivedStore} = derived([${2:storeA}, ${3:storeB}], ([$${2:storeA}, $${3:storeB}], set) => {", - "\tsetTimeout(() => set($${2:storeA} + $${3:storeB}), 1000);", - "}, 'one moment...');" - ], - "description": "svelte derived store" - }, - "svelte-store-get": { - "prefix": "s-store-get-value", - "body": ["const ${1:value} = get(${2:store});"], - "description": "svelte get value from store" - }, - "svelte-component-set": { - "prefix": "s-component-set", - "body": ["${1:component}.$set(${2: params});"], - "description": "svelte component api $set" - }, - "svelte-component-on": { - "prefix": "s-component-on", - "body": ["${1:component}.$on(${2:eventname}, ${3:handler});"], - "description": "svelte component api $on" - }, - "svelte-component-destroy": { - "prefix": "s-component-destroy", - "body": ["${1:component}.$destroy();"], - "description": "svelte component api $destroy" - }, - "svelte-render-component": { - "prefix": "s-render-component", - "body": [ - "const { head, html, css } = ${1:App}.render({", - "\tprops: ${3:props},", - "})" - ], - "description": "svelte render component" - }, - "svelte-tweened": { - "prefix": "s-tweened", - "body": ["const ${1:store} = tweened(${2:value}, ${3:options});"], - "description": "svelte create tweened store" - }, - "svelte-spring": { - "prefix": "s-spring", - "body": ["const ${1:store} = spring(${2:value}, ${3:options});"], - "description": "svelte create spring store" - }, - "svelte-register": { - "prefix": "s-register", - "body": [ - "require('svelte/register');", - "const ${1:App} = require('${2:./App.svelte}').default;" - ], - "description": "svelte register" - } -} diff --git a/.config/nvim/lua/sp/snippets/typescript.json b/.config/nvim/lua/sp/snippets/typescript.json deleted file mode 100644 index 57662cd..0000000 --- a/.config/nvim/lua/sp/snippets/typescript.json +++ /dev/null @@ -1,390 +0,0 @@ -{ - "Callback function": { - "prefix": "cb", - "body": "(req,res)=>{\n\t$0\n}" - }, - "beforeAll Async": { - "prefix": "bfa", - "body": "beforeAll(async () => { $0 })" - }, - "Log to console": { - "prefix": "cl", - "body": "console.log($1)$0" - }, - "Error to console": { - "prefix": "ce", - "body": "console.error($1)$0" - }, - "Arrow function": { - "prefix": "fun", - "body": "const $1 = ($2) => {\n\t$0\n}" - }, - "jest-expect": { - "prefix": "node-jest-expect", - "body": [ - " expect(1).toBe(2)" - ] - }, - "regex-test-digits": { - "prefix": "node-regex-test-digits", - "body": [ - "const isMatch = /\\d+/.test('abc123')" - ], - "description": "test if string contains digits, returns true/false" - }, - "regex-test-word": { - "prefix": "node-regex-test-word", - "body": [ - "const isMatch = /\\w+/.test('abc123')" - ], - "description": "test if string contains a word boundary, returns true/false" - }, - "regex-test-match": { - "prefix": "node-regex-match", - "body": [ - "const [, extension] = 'file.txt'.match(/\\.(\\w+)/)" - ], - "description": "matches a file extension" - }, - "regex-test-match-named-group": { - "prefix": "node-regex-match-named-group", - "body": [ - "const { groups: { extension } } = 'file.txt'.match(/\\.(?\\w+)/)" - ], - "description": "matches a file extension, " - }, - "express server": { - "prefix": "node-express", - "body": [ - "const express = require('express')", - "const app = express()", - "const port = 3000", - "", - "app.get('/', (req, res) => res.send('Hello World!'))", - "app.listen(port, () => console.log(`Example app listening on port \\${port\\}!`))" - ], - "description": "Creates an express server" - }, - "express GET": { - "prefix": "node-express-get", - "body": [ - "app.get('/', (req, res) => {", - " res.send('GET request to the homepage')", - "})" - ], - "description": "Creates a GET route" - }, - "express GET params": { - "prefix": "node-express-get-params", - "body": [ - "app.get('/books/:bookId', (req, res) => {", - " res.send(req.params.bookId)", - "})" - ], - "description": "Creates a GET route and shows how to access params" - }, - "express POST": { - "prefix": "node-express-post", - "body": [ - "app.post('/', function (req, res) {", - " res.send('POST request to the homepage')", - "})" - ], - "description": "Creates a POST route" - }, - "express POST params": { - "prefix": "node-express-post-params", - "body": [ - "var bodyParser = require('body-parser');", - "app.use(bodyParser.json());", - "", - "app.post('/update', function(req, res) {", - " const { name, description } = req.body;", - " res.send(`Name \\${name\\}, desc \\${description\\}`);", - "});" - ], - "description": "Creates a POST route that can read from the body" - }, - "express PUT params": { - "prefix": "node-express-put-params", - "body": [ - "var bodyParser = require('body-parser');", - "app.use(bodyParser.json());", - "", - "app.put('/products', function(req, res) {", - " const { id, name, description } = req.body;", - " res.send(`Name \\${id\\} \\${name\\}, desc \\${description\\}`);", - "});" - ], - "description": "Creates a POST route that can read from the body" - }, - "express DELETE params": { - "prefix": "node-express-delete-params", - "body": [ - "var bodyParser = require('body-parser');", - "app.use(bodyParser.json());", - "", - "app.delete('/products/:id', function(req, res) {", - " const { id } = req.params;", - " res.send(`Delete record with id \\${id\\}`);", - "});" - ], - "description": "Creates a POST route that can read from the body" - }, - "express QUERY params": { - "prefix": "node-express-query-params", - "body": [ - "var bodyParser = require('body-parser');", - "app.use(bodyParser.json());", - "", - "// for routes looking like this `/products?page=1&pageSize=50`", - "app.get('/products', function(req, res) {", - " const page = req.query.page;", - " const pageSize = req.query.pageSize;", - " res.send(`Filter with parameters \\${page\\} and \\${pageSize\\});`", - "});" - ], - "description": "Creates a POST route that can read from the body" - }, - "express POST params version >=4.16": { - "prefix": "node-express-post-params-alt", - "body": [ - "app.use(express.json())", - "app.listen(8080)", - "", - "app.post('/test', (req, res) => {", - " res.json({ body: req.body })", - "});" - ], - "description": "Creates a POST route that can read from the body, works for 4.16 version of express and above" - }, - "express middleware": { - "prefix": "node-express-middleware-logger", - "body": [ - "const logger = function (req, res, next) {", - " console.log('logging')", - " next()", - "}", - "", - "app.use(logger)", - "", - "app.get('/', (req, res) => {", - " res.send('Hello World!')", - "})" - ], - "description": "Creates a middleware" - }, - "express middleware error": { - "prefix": "node-express-middleware-error", - "body": [ - "app.use(function (err, req, res, next) {", - " console.error(err.stack)", - " res.status(500).send('Something broke!')", - "});" - ], - "description": "Creates a error middleware" - }, - "event emitter": { - "prefix": "node-event-emitter", - "body": [ - "var events = require('events');", - "var eventEmitter = new events.EventEmitter();", - "eventEmitter.emit('my_event');", - "eventEmitter.on('my_event', () => {", - " console.log('data received successfully.');", - "});" - ], - "description": "Event emitter, shows emitting event and subscribing to it" - }, - "Promise creation": { - "prefix": "node-promise-create", - "body": [ - "new Promise((resolve, reject) => {", - " let condition = false;", - " if(condition) {", - " resolve('data')", - " } else {", - " reject('error')", - "}", - "})" - ], - "description": "creates a Promise by instantiating it" - }, - "Promise shorthand": { - "prefix": "node-promise-shorthand", - "body": [ - "const promiseThatWillResolve = Promise.resolve('data');", - "const promiseThatWillReject = Promise.reject('error');" - ], - "description": "uses the static resolve/reject, good for unit tests" - }, - "Promise all": { - "prefix": "node-promise-all", - "body": [ - "const getData = () => Promise.resolve('data');", - "const getMoreData = () => Promise.resolve('more data');", - "", - "Promise.all(", - " getData(),", - " getMoreData()", - ").then(result => {", - " const [data, moreData] = result;", - "})" - ], - "description": "uses the static all(), allows us to have a list of Promises finish at the same time" - }, - "Async/await": { - "prefix": "node-async-await", - "body": [ - "async function getData() {", - " return Promise.resolve('data');", - "}", - "", - "async function getMoreData(data) {", - " return Promise.resolve(data + 'more data');", - "}", - "", - "async function getAll() {", - " const data = await getData();", - " const moreData = await getMoreData(data);", - " return `All the data: \\${data\\}, \\${moreData\\}`;", - "}", - "", - "getAll().then((all) => {", - " console.log('all the data')", - "})" - ], - "description": "demonstrates async/await" - }, - "Joi schema validation": { - "prefix": "node-express-schema-validation", - "body": [ - "const Joi = require('joi');", - "const loginSchema = Joi.object().keys({", - " username: Joi.string()", - " .min(3),", - " .max(10),", - " .required(),", - " password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/)", - "});", - "", - "app.post('/login', function(req, res) {", - " const valid = Joi.validate(req.body, loginSchema).error === null;", - " if (!valid) {", - " res.status(422).json({", - " status: 'error'", - " message: 'Invalid request data'", - " data: req.body", - " });", - " } else {", - " // happy days - login user", - " res.send(`ok`);", - " }", - "});" - ], - "description": "showcases the lib Joi and how you can use it to validate incoming requests" - }, - "supertest-init": { - "prefix": "node-supertest-init", - "body": [ - "const supertest = require('supertest')", - "const app = require('../app');", - "const server = app.listen(3000, () => {", - " console.log('listening at port 3000')", - "})", - "let request;" - ], - "description": "Sets up supertest by importing supertest and the app you mean to test. Additionally starts the app" - }, - "supertest-beforeall": { - "prefix": "node-supertest-beforeall", - "body": [ - "beforeAll(() => {", - " request = supertest(app)", - "})" - ], - "description": "Configures supertest to use the app, this is needed" - }, - "supertest-afterall": { - "prefix": "node-supertest-aftereall", - "body": [ - "afterAll(async(close) => {", - " server.close(() => {", - " close()", - " console.log('server closed');", - " })", - "})" - ], - "description": "Ensures the web app closes down after the test run, this is needed" - }, - "supertest-testGET": { - "prefix": "node-supertest-testget", - "body": [ - "test('testing a GET route', async () => {", - " let products = [", - " {", - " id: 1,", - " name: 'book'", - " },", - " {", - " id: 2,", - " name: 'book2'", - " }", - " ];", - "", - " const res = await request.get('/products');", - " expect(res.status).toBe(200);", - " expect(res.body).toEqual(products);", - "})" - ], - "description": "An example of supertest testing a GET route" - }, - "supertest-testGETWithParam": { - "prefix": "node-supertest-testgetwithparam", - "body": [ - "test('testing a GET route with router param', async () => {", - " let product = {", - " id: 1,", - " name: 'book'", - " };", - " const res = await request.get('/products/1');", - " expect(res.status).toBe(200);", - " expect(res.body).toEqual(product);", - "});" - ], - "description": "An example of supertest testing a GET route with a route parameter" - }, - "supertest-testPOSTWithParam": { - "prefix": "node-supertest-testpost", - "body": [ - "test('testing a POST route with a payload', async () => {", - " let product = {", - " name: 'book3'", - " };", - " const res = await request", - " .post('/products')", - " .send(product);", - " expect(res.status).toBe(200);", - " expect(res.body).toEqual({ id: 3, ...product});", - "", - " const newRes = await request.get('/products');", - " let products = [", - " {", - " id: 1,", - " name: 'book'", - " },", - " {", - " id: 2,", - " name: 'book2'", - " },", - " {", - " id: 3,", - " name: 'book3',", - " }", - " ];", - " expect(newRes.body).toEqual(products);", - "});" - ], - "description": "An example of supertest testing a POST route with a payload" - } -} diff --git a/.config/nvim/lua/sp/snippets/typescriptreact.json b/.config/nvim/lua/sp/snippets/typescriptreact.json deleted file mode 100644 index c5dae19..0000000 --- a/.config/nvim/lua/sp/snippets/typescriptreact.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "React Functional component": { - "prefix": "rf", - "body": [ - "import { ReactElement } from 'react'", - "\n\nconst ${TM_FILENAME_BASE} = ():ReactElement => {\n\t return (
$0
);\n};", - "\nexport default ${TM_FILENAME_BASE};" - ] - }, - "React Functional component(with props)": { - "prefix": "rf_", - "body": [ - "import { ReactElement } from 'react'", - "\ninterface Props {}", - "\nconst ${TM_FILENAME_BASE} = ({}:Props):ReactElement => {\n\t return (
$0
);\n};", - "\nexport default ${TM_FILENAME_BASE};" - ] - } -} diff --git a/.config/nvim/lua/sp/snippets/vue.json b/.config/nvim/lua/sp/snippets/vue.json deleted file mode 100644 index 291f3c2..0000000 --- a/.config/nvim/lua/sp/snippets/vue.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "vbase": { - "prefix": "vbase", - "body": [ - "", - "\n", - "\n" - ], - "description": "Basic vue 2 setup with template,script and style scoped" - }, - "vbase-3": { - "prefix": "vbase-3", - "body": [ - "", - "\n", - "\n" - ], - "description": "Basic vue 3 setup with template,script and style scoped" - }, - "vbase-3-ts": { - "prefix": "vbase-3-ts", - "body": [ - "", - "\n", - "\n" - ], - "description": "Basic vue 3 setup with template,script and style scoped" - } -}