Compare commits

..

No commits in common. "b2ccc50b4d2632777cdc1f47ca7886cb944b6f49" and "d919afda5dd18f324325a783e2709e7b03166809" have entirely different histories.

19 changed files with 1348 additions and 1777 deletions

892
.vimrc
View file

@ -1,892 +0,0 @@
" ============================================================================
" Vim Configuration - The Ultimate vimrc
" Inspired by the best practices from the Vim community
" ============================================================================
" ============================================================================
" => General Settings
" ============================================================================
" Disable compatibility with vi which can cause unexpected issues
set nocompatible
" Detect terminal type and capabilities (must be early for conditional configs)
let g:is_tty = ($TERM =~ 'linux' || $TERM =~ 'screen' || &term =~ 'builtin')
let g:has_true_color = ($COLORTERM == 'truecolor' || $COLORTERM == '24bit')
" Enable type file detection. Vim will be able to try to detect the type of file in use
filetype on
" Enable plugins and load plugin for the detected file type
filetype plugin on
" Load an indent file for the detected file type
filetype indent on
" Turn syntax highlighting on
syntax on
" Add numbers to each line on the left-hand side
set number
" Show relative line numbers
set relativenumber
" Highlight cursor line (disabled in TTY for performance)
if !g:is_tty
set cursorline
endif
" Set shift width to 4 spaces
set shiftwidth=4
" Set tab width to 4 columns
set tabstop=4
" Use space characters instead of tabs
set expandtab
" Do not save backup files
set nobackup
" Do not let cursor scroll below or above N number of lines when scrolling
set scrolloff=10
" Do not wrap lines. Allow long lines to extend as far as the line goes
set nowrap
" While searching though a file incrementally highlight matching characters as you type
set incsearch
" Ignore capital letters during search
set ignorecase
" Override the ignorecase option if searching for capital letters
set smartcase
" Show partial command you type in the last line of the screen
set showcmd
" Show the mode you are on the last line
set showmode
" Show matching words during a search
set showmatch
" Use highlighting when doing a search
set hlsearch
" Set the commands to save in history default number is 20
set history=1000
" Enable auto completion menu after pressing TAB
set wildmenu
" Make wildmenu behave like similar to Bash completion
set wildmode=list:longest
" There are certain files that we would never want to edit with Vim
" Wildmenu will ignore files with these extensions
set wildignore=*.docx,*.jpg,*.png,*.gif,*.pdf,*.pyc,*.exe,*.flv,*.img,*.xlsx
" Enable mouse support
set mouse=a
" Set encoding
set encoding=utf-8
" Enable folding
set foldmethod=indent
set foldlevel=99
" Split window settings
set splitbelow
set splitright
" Better backspace behavior
set backspace=indent,eol,start
" Auto read when file is changed from outside
set autoread
" Height of the command bar
set cmdheight=1
" A buffer becomes hidden when it is abandoned
set hid
" Configure backspace so it acts as it should act (enhanced from earlier basic setting)
set whichwrap+=<,>,h,l
" Don't redraw while executing macros (good performance config)
set lazyredraw
" For regular expressions turn magic on
set magic
" Show matching brackets when text indicator is over them
set showmatch
" How many tenths of a second to blink when matching brackets
set mat=2
" No annoying sound on errors
set noerrorbells
set novisualbell
set t_vb=
set tm=500
" Enable 256 colors palette in Gnome Terminal
if $COLORTERM == 'gnome-terminal'
set t_Co=256
endif
" Set extra options when running in GUI mode
if has("gui_running")
set guioptions-=T
set guioptions-=e
set t_Co=256
set guitablabel=%M\ %t
endif
" Use Unix as the standard file type
set ffs=unix,dos,mac
" Turn backup off, since most stuff is in SVN, git etc. anyway
set nobackup
set nowb
set noswapfile
" ============================================================================
" => Vim-Plug Plugin Manager
" ============================================================================
" Auto-install vim-plug
let data_dir = has('nvim') ? stdpath('data') . '/site' : '~/.vim'
if empty(glob(data_dir . '/autoload/plug.vim'))
silent execute '!curl -fLo '.data_dir.'/autoload/plug.vim --create-dirs https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim'
autocmd VimEnter * PlugInstall --sync | source $MYVIMRC
endif
" Plugin list
call plug#begin('~/.vim/plugged')
" ===== File Navigation & Search =====
Plug 'preservim/nerdtree' " File explorer
Plug 'junegunn/fzf', { 'do': { -> fzf#install() } }
Plug 'junegunn/fzf.vim' " Fuzzy finder
Plug 'ctrlpvim/ctrlp.vim' " Fuzzy file finder
" ===== Git Integration =====
Plug 'tpope/vim-fugitive' " Git wrapper
Plug 'airblade/vim-gitgutter' " Show git diff in gutter
" ===== Status Line & UI =====
Plug 'vim-airline/vim-airline' " Status bar
Plug 'vim-airline/vim-airline-themes' " Airline themes
" ===== Code Editing & Completion =====
Plug 'tpope/vim-surround' " Surround text objects
Plug 'tpope/vim-commentary' " Comment stuff out
Plug 'tpope/vim-repeat' " Repeat plugin maps
Plug 'jiangmiao/auto-pairs' " Auto close brackets
Plug 'dense-analysis/ale' " Async linting engine
" ===== Language Support =====
Plug 'sheerun/vim-polyglot' " Language pack
Plug 'fatih/vim-go', { 'do': ':GoUpdateBinaries' } " Go support
" ===== Color Schemes =====
Plug 'morhetz/gruvbox' " Gruvbox theme
Plug 'dracula/vim', { 'as': 'dracula' } " Dracula theme
Plug 'altercation/vim-colors-solarized' " Solarized theme
Plug 'joshdick/onedark.vim' " One Dark theme
" ===== Productivity =====
Plug 'mbbill/undotree' " Undo history visualizer
Plug 'preservim/tagbar' " Tag browser
Plug 'easymotion/vim-easymotion' " Easy motion
" ===== Code Intelligence =====
if has('vim9') || has('nvim')
Plug 'neoclide/coc.nvim', {'branch': 'release'} " LSP & Completion
endif
" ===== Session Management =====
Plug 'tpope/vim-obsession' " Continuous session save
Plug 'dhruvasagar/vim-prosession' " Better session management
" ===== Additional Utilities =====
Plug 'tpope/vim-unimpaired' " Handy bracket mappings
Plug 'wellle/targets.vim' " Additional text objects
Plug 'honza/vim-snippets' " Snippet collection
call plug#end()
" ============================================================================
" => Colors and Fonts
" ============================================================================
" Enable true colors support only if terminal supports it
if g:has_true_color && has('termguicolors') && !g:is_tty
set termguicolors
endif
" Set colorscheme with proper fallbacks
if &t_Co >= 256 && !g:is_tty
" 256-color terminals
try
colorscheme gruvbox
set background=dark
catch
try
colorscheme desert
catch
colorscheme default
endtry
endtry
else
" Basic 16-color terminals (TTY, console)
colorscheme default
set background=dark
endif
" Set font for GUI
if has("gui_running")
if has("gui_gtk2") || has("gui_gtk3")
set guifont=Hack\ 12,Source\ Code\ Pro\ 12,Monospace\ 12
elseif has("gui_win32")
set guifont=Consolas:h11:cANSI
endif
endif
" ============================================================================
" => Text, Tab and Indent Related
" ============================================================================
" Use spaces instead of tabs
set expandtab
" Be smart when using tabs
set smarttab
" 1 tab == 4 spaces
set shiftwidth=4
set tabstop=4
" Linebreak on 500 characters
set lbr
set tw=500
set ai "Auto indent
set si "Smart indent
set wrap "Wrap lines
" ============================================================================
" => Key Mappings
" ============================================================================
" Set leader key to comma
let mapleader = ","
" Fast saving
nmap <leader>w :w!<cr>
" Fast quitting
nmap <leader>q :q<cr>
" Fast save and quit
nmap <leader>x :x<cr>
" Disable highlight when <leader><cr> is pressed
map <silent> <leader><cr> :noh<cr>
" Smart way to move between windows
map <C-j> <C-W>j
map <C-k> <C-W>k
map <C-h> <C-W>h
map <C-l> <C-W>l
" Close the current buffer
map <leader>bd :Bclose<cr>:tabclose<cr>gT
" Close all the buffers
map <leader>ba :bufdo bd<cr>
" Next buffer
map <leader>l :bnext<cr>
" Previous buffer
map <leader>h :bprevious<cr>
" Useful mappings for managing tabs
map <leader>tn :tabnew<cr>
map <leader>to :tabonly<cr>
map <leader>tc :tabclose<cr>
map <leader>tm :tabmove
map <leader>t<leader> :tabnext<cr>
" Let 'tl' toggle between this and the last accessed tab
let g:lasttab = 1
nmap <Leader>tl :exe "tabn ".g:lasttab<CR>
au TabLeave * let g:lasttab = tabpagenr()
" Opens a new tab with the current buffer's path
map <leader>te :tabedit <C-r>=expand("%:p:h")<cr>/
" Switch CWD to the directory of the open buffer
map <leader>cd :cd %:p:h<cr>:pwd<cr>
" Remap VIM 0 to first non-blank character
map 0 ^
" Move a line of text using ALT+[jk] or Command+[jk] on mac
nmap <M-j> mz:m+<cr>`z
nmap <M-k> mz:m-2<cr>`z
vmap <M-j> :m'>+<cr>`<my`>mzgv`yo`z
vmap <M-k> :m'<-2<cr>`>my`<mzgv`yo`z
" Pressing ,ss will toggle and untoggle spell checking
map <leader>ss :setlocal spell!<cr>
" Shortcuts using <leader>
map <leader>sn ]s
map <leader>sp [s
map <leader>sa zg
map <leader>s? z=
" Remove trailing whitespace
nnoremap <leader>w :let _s=@/<Bar>:%s/\s\+$//e<Bar>:let @/=_s<Bar><CR>
" Toggle paste mode
set pastetoggle=<F2>
" Toggle line numbers
nnoremap <F3> :set invnumber<CR>
" Toggle relative line numbers
nnoremap <F4> :set invrelativenumber<CR>
" Enable folding with the spacebar
nnoremap <space> za
" ============================================================================
" => Plugin Settings
" ============================================================================
" --- NERDTree ---
map <C-n> :NERDTreeToggle<CR>
map <leader>n :NERDTreeFind<CR>
" Close vim if the only window left open is a NERDTree
autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTree") && b:NERDTree.isTabTree()) | q | endif
" Show hidden files
let NERDTreeShowHidden=1
" Ignore files in NERDTree
let NERDTreeIgnore=['\.pyc$', '\~$', '\.swp$', '\.git$', '\.DS_Store', 'node_modules', '__pycache__', '\.egg-info$']
" NERDTree window size
let NERDTreeWinSize=35
" Automatically open NERDTree when vim starts on a directory
" Disabled in TTY for faster startup
if !g:is_tty
autocmd StdinReadPre * let s:std_in=1
autocmd VimEnter * if argc() == 1 && isdirectory(argv()[0]) && !exists("s:std_in") | exe 'NERDTree' argv()[0] | wincmd p | ene | exe 'cd '.argv()[0] | endif
endif
" --- FZF ---
map <C-p> :Files<CR>
map <leader>b :Buffers<CR>
map <leader>rg :Rg<CR>
map <leader>t :Tags<CR>
" FZF customization for better project search
let g:fzf_layout = { 'down': '40%' }
" Disable preview in TTY for better performance
if g:is_tty
let g:fzf_preview_window = []
else
let g:fzf_preview_window = ['right:50%', 'ctrl-/']
endif
" Advanced FZF commands
" Conditionally enable preview based on terminal type
if g:is_tty
command! -bang -nargs=* Rg
\ call fzf#vim#grep(
\ 'rg --column --line-number --no-heading --color=always --smart-case -- '.shellescape(<q-args>), 1,
\ <bang>0)
command! -bang GFiles call fzf#vim#gitfiles('', <bang>0)
else
command! -bang -nargs=* Rg
\ call fzf#vim#grep(
\ 'rg --column --line-number --no-heading --color=always --smart-case -- '.shellescape(<q-args>), 1,
\ fzf#vim#with_preview(), <bang>0)
command! -bang GFiles call fzf#vim#gitfiles('', fzf#vim#with_preview(), <bang>0)
endif
" --- CtrlP ---
let g:ctrlp_working_path_mode = 'ra'
let g:ctrlp_show_hidden = 1
let g:ctrlp_custom_ignore = {
\ 'dir': '\v[\/]\.(git|hg|svn)$',
\ 'file': '\v\.(exe|so|dll|pyc)$',
\ }
" --- Airline ---
" Disable powerline fonts in TTY for compatibility
if g:is_tty
let g:airline_powerline_fonts = 0
let g:airline_left_sep = ''
let g:airline_right_sep = ''
let g:airline#extensions#tabline#left_sep = ' '
let g:airline#extensions#tabline#left_alt_sep = '|'
else
let g:airline_powerline_fonts = 1
endif
let g:airline#extensions#tabline#enabled = 1
let g:airline#extensions#tabline#formatter = 'unique_tail'
" Set theme based on terminal capabilities
if &t_Co >= 256 && !g:is_tty
let g:airline_theme='gruvbox'
else
let g:airline_theme='dark'
endif
" --- GitGutter ---
let g:gitgutter_sign_added = '+'
let g:gitgutter_sign_modified = '~'
let g:gitgutter_sign_removed = '-'
let g:gitgutter_sign_removed_first_line = '^'
let g:gitgutter_sign_modified_removed = '~'
" --- ALE (Asynchronous Lint Engine) ---
let g:ale_linters = {
\ 'python': ['flake8', 'pylint'],
\ 'javascript': ['eslint'],
\ 'typescript': ['eslint', 'tsserver'],
\ 'go': ['gopls', 'golint'],
\ 'rust': ['cargo'],
\ 'sh': ['shellcheck'],
\ 'yaml': ['yamllint'],
\ 'dockerfile': ['hadolint'],
\}
let g:ale_fixers = {
\ '*': ['remove_trailing_lines', 'trim_whitespace'],
\ 'python': ['black', 'isort'],
\ 'javascript': ['prettier', 'eslint'],
\ 'typescript': ['prettier', 'eslint'],
\ 'go': ['gofmt', 'goimports'],
\ 'rust': ['rustfmt'],
\ 'json': ['prettier'],
\ 'yaml': ['prettier'],
\ 'html': ['prettier'],
\ 'css': ['prettier'],
\ 'markdown': ['prettier'],
\}
let g:ale_fix_on_save = 1
let g:ale_sign_error = 'X'
let g:ale_sign_warning = '!'
let g:ale_lint_on_text_changed = 'never'
let g:ale_lint_on_insert_leave = 0
let g:ale_lint_on_enter = 0
" Navigate between errors
nmap <silent> <leader>aj :ALENext<cr>
nmap <silent> <leader>ak :ALEPrevious<cr>
nmap <silent> <leader>ad :ALEDetail<cr>
" --- Tagbar ---
nmap <F8> :TagbarToggle<CR>
" --- UndoTree ---
nnoremap <F5> :UndotreeToggle<CR>
" --- EasyMotion ---
let g:EasyMotion_do_mapping = 0 " Disable default mappings
" Jump to anywhere you want with minimal keystrokes
nmap s <Plug>(easymotion-overwin-f2)
" Turn on case-insensitive feature
let g:EasyMotion_smartcase = 1
" JK motions: Line motions
map <Leader>j <Plug>(easymotion-j)
map <Leader>k <Plug>(easymotion-k)
" --- CoC (Conquer of Completion) ---
if exists('g:plugs["coc.nvim"]')
" Use tab for trigger completion with characters ahead and navigate
inoremap <silent><expr> <TAB>
\ coc#pum#visible() ? coc#pum#next(1) :
\ CheckBackspace() ? "\<Tab>" :
\ coc#refresh()
inoremap <expr><S-TAB> coc#pum#visible() ? coc#pum#prev(1) : "\<C-h>"
" Make <CR> to accept selected completion item
inoremap <silent><expr> <CR> coc#pum#visible() ? coc#pum#confirm()
\: "\<C-g>u\<CR>\<c-r>=coc#on_enter()\<CR>"
function! CheckBackspace() abort
let col = col('.') - 1
return !col || getline('.')[col - 1] =~# '\s'
endfunction
" Use <c-space> to trigger completion
inoremap <silent><expr> <c-space> coc#refresh()
" Use `[g` and `]g` to navigate diagnostics
nmap <silent> [g <Plug>(coc-diagnostic-prev)
nmap <silent> ]g <Plug>(coc-diagnostic-next)
" GoTo code navigation
nmap <silent> gd <Plug>(coc-definition)
nmap <silent> gy <Plug>(coc-type-definition)
nmap <silent> gi <Plug>(coc-implementation)
nmap <silent> gr <Plug>(coc-references)
" Use K to show documentation in preview window
nnoremap <silent> K :call ShowDocumentation()<CR>
function! ShowDocumentation()
if CocAction('hasProvider', 'hover')
call CocActionAsync('doHover')
else
call feedkeys('K', 'in')
endif
endfunction
" Highlight the symbol and its references when holding the cursor
autocmd CursorHold * silent call CocActionAsync('highlight')
" Symbol renaming
nmap <leader>rn <Plug>(coc-rename)
" Formatting selected code
xmap <leader>f <Plug>(coc-format-selected)
nmap <leader>f <Plug>(coc-format-selected)
endif
" ============================================================================
" => Helper Functions
" ============================================================================
" Returns true if paste mode is enabled
function! HasPaste()
if &paste
return 'PASTE MODE '
endif
return ''
endfunction
" Don't close window, when deleting a buffer
command! Bclose call <SID>BufcloseCloseIt()
function! <SID>BufcloseCloseIt()
let l:currentBufNum = bufnr("%")
let l:alternateBufNum = bufnr("#")
if buflisted(l:alternateBufNum)
buffer #
else
bnext
endif
if bufnr("%") == l:currentBufNum
new
endif
if buflisted(l:currentBufNum)
execute("bdelete! ".l:currentBufNum)
endif
endfunction
" Delete trailing white space on save
fun! CleanExtraSpaces()
let save_cursor = getpos(".")
let old_query = getreg('/')
silent! %s/\s\+$//e
call setpos('.', save_cursor)
call setreg('/', old_query)
endfun
if has("autocmd")
autocmd BufWritePre *.txt,*.js,*.py,*.wiki,*.sh,*.coffee :call CleanExtraSpaces()
endif
" ============================================================================
" => Auto Commands
" ============================================================================
" Return to last edit position when opening files
autocmd BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif
" Set specific file types
autocmd BufNewFile,BufRead *.json setlocal filetype=json
autocmd BufNewFile,BufRead *.md setlocal filetype=markdown
autocmd BufNewFile,BufRead *.jsx setlocal filetype=javascript.jsx
autocmd BufNewFile,BufRead *.tsx setlocal filetype=typescript.tsx
" Python specific settings
autocmd FileType python setlocal expandtab shiftwidth=4 tabstop=4 colorcolumn=88
" JavaScript specific settings
autocmd FileType javascript,typescript setlocal expandtab shiftwidth=2 tabstop=2
" Go specific settings
autocmd FileType go setlocal noexpandtab shiftwidth=4 tabstop=4
" HTML/CSS specific settings
autocmd FileType html,css setlocal expandtab shiftwidth=2 tabstop=2
" YAML specific settings
autocmd FileType yaml setlocal expandtab shiftwidth=2 tabstop=2
" Markdown specific settings
autocmd FileType markdown setlocal wrap linebreak spell
" Shell script settings
autocmd FileType sh setlocal expandtab shiftwidth=2 tabstop=2
" Makefile settings (must use tabs)
autocmd FileType make setlocal noexpandtab shiftwidth=8 tabstop=8
" JSON specific settings
autocmd FileType json setlocal expandtab shiftwidth=2 tabstop=2
" Docker specific settings
autocmd BufNewFile,BufRead Dockerfile* setlocal filetype=dockerfile
autocmd FileType dockerfile setlocal expandtab shiftwidth=2 tabstop=2
" ============================================================================
" => Status Line
" ============================================================================
" Always show the status line
set laststatus=2
" Format the status line (if not using airline)
" set statusline=\ %{HasPaste()}%F%m%r%h\ %w\ \ CWD:\ %r%{getcwd()}%h\ \ \ Line:\ %l\ \ Column:\ %c
" ============================================================================
" => Misc
" ============================================================================
" Quickly open a buffer for scribble
map <leader>q :e ~/buffer<cr>
" Quickly open a markdown buffer for scribble
map <leader>m :e ~/buffer.md<cr>
" Toggle between number and relativenumber
function! ToggleNumber()
if(&relativenumber == 1)
set norelativenumber
set number
else
set relativenumber
endif
endfunc
" Toggle paste mode
map <leader>pp :setlocal paste!<cr>
" ============================================================================
" => Performance Optimization
" ============================================================================
" Optimize for large files
set synmaxcol=200
set ttyfast
" Reduce updatetime for better user experience
set updatetime=300
" Don't pass messages to |ins-completion-menu|
set shortmess+=c
" Always show the signcolumn (simplified for TTY)
if g:is_tty
" In TTY, only show signcolumn when there are signs
set signcolumn=auto
else
if has("patch-8.1.1564")
set signcolumn=number
else
set signcolumn=yes
endif
endif
" ============================================================================
" => Project-Specific Settings
" ============================================================================
" Load project-specific vimrc if it exists
" This allows per-project customization
set exrc
set secure
" ============================================================================
" => Additional Engineering Utilities
" ============================================================================
" Quick format entire file
nnoremap <leader>F gg=G``
" Toggle between source and header files (for C/C++)
nnoremap <leader>a :A<CR>
" Quick save all buffers
nnoremap <leader>wa :wa<CR>
" Easier window resizing
nnoremap <silent> <Leader>= :exe "resize " . (winheight(0) * 3/2)<CR>
nnoremap <silent> <Leader>- :exe "resize " . (winheight(0) * 2/3)<CR>
nnoremap <silent> <Leader>+ :exe "vertical resize " . (winwidth(0) * 3/2)<CR>
nnoremap <silent> <Leader>_ :exe "vertical resize " . (winwidth(0) * 2/3)<CR>
" Quick switch between last two files
nnoremap <leader><leader> <c-^>
" Clear whitespace on empty lines
nnoremap <leader>W :%s/\s\+$//<CR>:let @/=''<CR>
" Source current file
nnoremap <leader>so :source %<CR>
" Edit vimrc quickly
nnoremap <leader>ev :edit $MYVIMRC<CR>
" Reload vimrc
nnoremap <leader>sv :source $MYVIMRC<CR>
" Search and replace word under cursor
nnoremap <leader>* :%s/\<<C-r><C-w>\>//g<Left><Left>
" Copy file path to clipboard
nnoremap <leader>cp :let @+ = expand("%:p")<CR>:echo "Copied path: " . expand("%:p")<CR>
nnoremap <leader>cf :let @+ = expand("%:t")<CR>:echo "Copied filename: " . expand("%:t")<CR>
" Create parent directories on save if they don't exist
function! s:MkNonExDir(file, buf)
if empty(getbufvar(a:buf, '&buftype')) && a:file!~#'\v^\w+\:\/'
let dir=fnamemodify(a:file, ':h')
if !isdirectory(dir)
call mkdir(dir, 'p')
endif
endif
endfunction
augroup BWCCreateDir
autocmd!
autocmd BufWritePre * :call s:MkNonExDir(expand('<afile>'), +expand('<abuf>'))
augroup END
" ============================================================================
" => Debugging Helpers
" ============================================================================
" Show syntax highlighting groups for word under cursor
nmap <leader>sp :call <SID>SynStack()<CR>
function! <SID>SynStack()
if !exists("*synstack")
return
endif
echo map(synstack(line('.'), col('.')), 'synIDattr(v:val, "name")')
endfunc
" ============================================================================
" => Git Workflow Enhancements
" ============================================================================
" Git shortcuts
nnoremap <leader>gs :Git status<CR>
nnoremap <leader>gc :Git commit<CR>
nnoremap <leader>gp :Git push<CR>
nnoremap <leader>gl :Git pull<CR>
nnoremap <leader>gd :Gdiff<CR>
nnoremap <leader>gb :Git blame<CR>
" ============================================================================
" => Terminal Integration
" ============================================================================
" Better terminal navigation
if has('terminal')
" Open terminal in split
nnoremap <leader>tv :terminal<CR>
nnoremap <leader>th :terminal ++rows=10<CR>
" Terminal mode mappings
tnoremap <Esc> <C-\><C-n>
tnoremap <C-h> <C-\><C-n><C-w>h
tnoremap <C-j> <C-\><C-n><C-w>j
tnoremap <C-k> <C-\><C-n><C-w>k
tnoremap <C-l> <C-\><C-n><C-w>l
endif
" ============================================================================
" => Large File Handling
" ============================================================================
" Disable syntax highlighting and other features for large files (>10MB)
let g:LargeFile = 1024 * 1024 * 10
augroup LargeFile
autocmd!
autocmd BufReadPre * let f=getfsize(expand("<afile>")) | if f > g:LargeFile || f == -2 | call LargeFileSettings() | endif
augroup END
function! LargeFileSettings()
setlocal bufhidden=unload
setlocal undolevels=-1
setlocal eventignore+=FileType
setlocal noswapfile
setlocal buftype=nowrite
echo "Large file detected. Some features disabled for performance."
endfunction
" ============================================================================
" => TTY and Basic Terminal Optimizations
" ============================================================================
" Additional optimizations for TTY/basic terminals
if g:is_tty
" Disable syntax highlighting for very large files in TTY
autocmd BufReadPre * if getfsize(expand("<afile>")) > 512000 | setlocal syntax=OFF | endif
" Simpler status line for TTY
set statusline=%f\ %h%w%m%r\ %=%(%l,%c%V\ %=\ %P%)
" Disable some visual effects
set novisualbell
set noerrorbells
" Faster redraw
set lazyredraw
set ttyfast
" Reduce syntax highlighting complexity
set synmaxcol=120
endif
" Provide helpful message on first run in TTY
if g:is_tty && !exists("g:tty_message_shown")
augroup TTYMessage
autocmd!
autocmd VimEnter * echom "Running in TTY mode - some features disabled for performance"
augroup END
let g:tty_message_shown = 1
endif
" ============================================================================
" End of Configuration
" ============================================================================

View file

@ -1,274 +0,0 @@
# Quick Start Guide
Get up and running with this Vim configuration in 5 minutes!
## Installation
### One-Line Install
```bash
git clone https://github.com/m1ngsama/chopsticks.git ~/.vim && cd ~/.vim && ./install.sh
```
**IMPORTANT:** Always run the install script from the `~/.vim` directory (where you cloned the repository). The script validates this to ensure correct symlink creation.
That's it! The script will:
- Verify it's being run from the correct directory
- Backup your existing .vimrc
- Create and validate symlink to the new configuration
- Install vim-plug
- Install all plugins automatically
### Manual Install
```bash
# 1. Clone the repository
git clone https://github.com/m1ngsama/chopsticks.git ~/.vim
# 2. Create symlink
ln -sf ~/.vim/.vimrc ~/.vimrc
# 3. Install vim-plug
curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
# 4. Open Vim and install plugins
vim +PlugInstall +qall
```
## Essential Key Mappings
### File Operations
| Key | Action |
|-----|--------|
| `,w` | Quick save |
| `,q` | Quick quit |
| `,x` | Save and quit |
### Navigation
| Key | Action |
|-----|--------|
| `Ctrl+n` | Toggle file explorer (NERDTree) |
| `Ctrl+p` | Fuzzy file search (FZF) |
| `Ctrl+h/j/k/l` | Navigate between windows |
| `,b` | Search open buffers |
### Code Intelligence
| Key | Action |
|-----|--------|
| `gd` | Go to definition |
| `gr` | Find references |
| `K` | Show documentation |
| `Tab` | Autocomplete (when popup is visible) |
### Editing
| Key | Action |
|-----|--------|
| `gc` | Comment/uncomment (in visual mode) |
| `Space` | Toggle fold |
| `,,+Enter` | Clear search highlight |
## Common Workflows
### Opening a Project
```bash
# Navigate to your project directory
cd ~/my-project
# Open Vim
vim
# Press Ctrl+n to open file explorer
# Press Ctrl+p to fuzzy search files
```
### Editing Code
1. Open a file with `Ctrl+p` or through NERDTree
2. Use `gd` to jump to definitions
3. Use `K` to view documentation
4. Use `Tab` for autocomplete while typing
5. Save with `,w`
### Working with Git
| Command | Action |
|---------|--------|
| `:Git status` | View git status |
| `:Git diff` | View changes |
| `:Git commit` | Commit changes |
| `:Git push` | Push to remote |
| `,gb` | Open git blame window |
### Search and Replace
```vim
" Search in current file
/searchterm
" Search across project (with FZF)
,rg
" Replace in file
:%s/old/new/g
" Replace with confirmation
:%s/old/new/gc
```
## Language-Specific Features
### Python
- Auto-formatting with Black (on save)
- Linting with flake8/pylint
- 4-space indentation
- 88-character line limit
**Setup:**
```bash
pip install black flake8 pylint
vim -c "CocInstall coc-pyright" -c "q"
```
### JavaScript/TypeScript
- Prettier formatting (on save)
- ESLint integration
- 2-space indentation
**Setup:**
```bash
npm install -g prettier eslint
vim -c "CocInstall coc-tsserver coc-prettier coc-eslint" -c "q"
```
### Go
- Auto-formatting with gofmt
- Auto-imports with goimports
- Tab indentation
**Setup:**
```bash
go install golang.org/x/tools/gopls@latest
vim -c "CocInstall coc-go" -c "q"
```
## Troubleshooting
### Plugins not working?
```vim
:PlugInstall
:PlugUpdate
```
### Autocomplete not working?
Make sure Node.js is installed:
```bash
node --version # Should be >= 14.14
```
Then install CoC language servers:
```vim
:CocInstall coc-json coc-tsserver coc-pyright
```
### FZF not finding files?
Install FZF and ripgrep:
```bash
# Ubuntu/Debian
sudo apt install fzf ripgrep
# macOS
brew install fzf ripgrep
```
### Colors look weird?
Add to your `~/.bashrc` or `~/.zshrc`:
```bash
export TERM=xterm-256color
```
## Customization
The `.vimrc` file is well-organized into sections:
1. **General Settings** (lines 1-150) - Basic Vim behavior
2. **Plugin Management** (lines 151-230) - Plugin list
3. **Key Mappings** (lines 300-400) - Custom shortcuts
4. **Plugin Settings** (lines 400-600) - Plugin configurations
To customize:
1. Open `~/.vim/.vimrc`
2. Find the section you want to modify
3. Make your changes
4. Reload with `:source ~/.vimrc` or restart Vim
### Common Customizations
**Change colorscheme:**
```vim
" In .vimrc, find the colorscheme line and change to:
colorscheme dracula
" or: solarized, onedark, gruvbox
```
**Change leader key:**
```vim
" Default is comma (,), change to space:
let mapleader = " "
```
**Disable relative line numbers:**
```vim
set norelativenumber
```
## Next Steps
1. Read the full [README.md](README.md) for complete documentation
2. Check out `:help` in Vim for built-in documentation
3. Customize the configuration to your needs
4. Share your improvements!
## Quick Reference Card
Print this for your desk:
```
┌─────────────────────────────────────────────┐
│ Vim Quick Reference │
├─────────────────────────────────────────────┤
│ FILES │
│ Ctrl+n File explorer │
│ Ctrl+p Fuzzy find files │
│ ,w Save │
│ ,q Quit │
├─────────────────────────────────────────────┤
│ NAVIGATION │
│ gd Go to definition │
│ gr Find references │
│ K Show docs │
│ Ctrl+o Jump back │
│ Ctrl+i Jump forward │
├─────────────────────────────────────────────┤
│ EDITING │
│ gc Comment (visual mode) │
│ Tab Autocomplete │
│ Space Toggle fold │
├─────────────────────────────────────────────┤
│ SEARCH │
│ /text Search forward │
│ ?text Search backward │
│ ,rg Project-wide search │
│ ,,Enter Clear highlight │
└─────────────────────────────────────────────┘
```
Happy Vimming!

472
README.md
View file

@ -1,472 +1,2 @@
# The Ultimate Vim Configuration m1ngsama's neovim config
A comprehensive, modern Vim configuration optimized for engineering workflows. This configuration transforms vanilla Vim into a powerful, feature-rich development environment with enterprise-grade tooling.
**NEW: Quick installation script and enhanced engineering features!**
## Quick Start
```bash
git clone https://github.com/m1ngsama/chopsticks.git ~/.vim && cd ~/.vim && ./install.sh
```
**Note:** The installation script must be run from the cloned `~/.vim` directory. See [QUICKSTART.md](QUICKSTART.md) for detailed getting started guide.
## Features
### Core Enhancements
- **Smart Line Numbers**: Hybrid line numbers (absolute + relative) for efficient navigation
- **Modern UI**: Gruvbox color scheme with airline status bar
- **Plugin Management**: vim-plug for easy plugin installation and updates
- **Auto-completion**: CoC (Conquer of Completion) for intelligent code completion
- **Syntax Checking**: ALE (Asynchronous Lint Engine) for real-time linting
### File Navigation
- **NERDTree**: Visual file explorer (`Ctrl+n`)
- **FZF**: Blazing fast fuzzy finder (`Ctrl+p`)
- **CtrlP**: Alternative fuzzy file finder
- **Easy Motion**: Jump to any location with minimal keystrokes
### Git Integration
- **Fugitive**: Complete Git wrapper for Vim
- **GitGutter**: Show git diff in the sign column
### Code Editing
- **Auto-pairs**: Automatic bracket/quote pairing
- **Surround**: Easily change surrounding quotes, brackets, tags
- **Commentary**: Quick code commenting (`gc`)
- **Multi-language Support**: vim-polyglot for 100+ languages
### Productivity Tools
- **UndoTree**: Visualize and navigate undo history (`F5`)
- **Tagbar**: Code structure browser (`F8`)
- **Smart Window Management**: Easy navigation with `Ctrl+hjkl`
- **Session Management**: Auto-save sessions with vim-obsession
- **Project-Specific Settings**: Per-project .vimrc support
- **Large File Optimization**: Automatic performance tuning for files >10MB
- **TTY/Basic Terminal Support**: Automatic optimization for console environments
## Installation
### Automatic Installation (Recommended)
```bash
git clone https://github.com/m1ngsama/chopsticks.git ~/.vim
cd ~/.vim
./install.sh
```
**IMPORTANT:** You must run the install script from the `~/.vim` directory (the cloned repository directory). Do not copy the script to another location and run it from there.
The installation script will:
- Verify it's being run from the correct directory
- Backup your existing configuration
- Create necessary symlinks
- Validate symlink creation
- Install vim-plug automatically
- Install all plugins
- Offer to install CoC language servers
### Manual Installation
```bash
# 1. Clone this repository
git clone https://github.com/m1ngsama/chopsticks.git ~/.vim
cd ~/.vim
# 2. Create symlink to .vimrc
ln -s ~/.vim/.vimrc ~/.vimrc
# 3. Install vim-plug
curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
# 4. Open Vim and install plugins
vim +PlugInstall +qall
```
### 4. (Optional) Install recommended dependencies
For the best experience, install these optional dependencies:
```bash
# FZF (fuzzy finder)
git clone --depth 1 https://github.com/junegunn/fzf.git ~/.fzf
~/.fzf/install
# ripgrep (better grep)
# On Ubuntu/Debian
sudo apt install ripgrep
# On macOS
brew install ripgrep
# Node.js (for CoC)
# Required for code completion
curl -sL install-node.now.sh/lts | bash
# Universal Ctags (for Tagbar)
# On Ubuntu/Debian
sudo apt install universal-ctags
# On macOS
brew install universal-ctags
```
### 5. Install CoC language servers
For intelligent code completion, install language servers:
```vim
" Python
:CocInstall coc-pyright
" JavaScript/TypeScript
:CocInstall coc-tsserver
" Go
:CocInstall coc-go
" JSON
:CocInstall coc-json
" HTML/CSS
:CocInstall coc-html coc-css
" See more: https://github.com/neoclide/coc.nvim/wiki/Using-coc-extensions
```
## Key Mappings
### General
| Key | Action |
|-----|--------|
| `,w` | Quick save |
| `,q` | Quick quit |
| `,x` | Save and quit |
| `,,` + Enter | Clear search highlight |
### Window Navigation
| Key | Action |
|-----|--------|
| `Ctrl+h` | Move to left window |
| `Ctrl+j` | Move to bottom window |
| `Ctrl+k` | Move to top window |
| `Ctrl+l` | Move to right window |
### Buffer Management
| Key | Action |
|-----|--------|
| `,l` | Next buffer |
| `,h` | Previous buffer |
| `,bd` | Close current buffer |
| `,ba` | Close all buffers |
### Tab Management
| Key | Action |
|-----|--------|
| `,tn` | New tab |
| `,tc` | Close tab |
| `,tl` | Toggle to last tab |
### File Navigation
| Key | Action |
|-----|--------|
| `Ctrl+n` | Toggle NERDTree |
| `,n` | Find current file in NERDTree |
| `Ctrl+p` | FZF file search |
| `,b` | FZF buffer search |
| `,rg` | Ripgrep search |
### Code Navigation (CoC)
| Key | Action |
|-----|--------|
| `gd` | Go to definition |
| `gy` | Go to type definition |
| `gi` | Go to implementation |
| `gr` | Go to references |
| `K` | Show documentation |
| `[g` | Previous diagnostic |
| `]g` | Next diagnostic |
| `,rn` | Rename symbol |
### Linting (ALE)
| Key | Action |
|-----|--------|
| `,aj` | Next error/warning |
| `,ak` | Previous error/warning |
| `,ad` | Show error details |
### Git Workflow
| Key | Action |
|-----|--------|
| `,gs` | Git status |
| `,gc` | Git commit |
| `,gp` | Git push |
| `,gl` | Git pull |
| `,gd` | Git diff |
| `,gb` | Git blame |
### Engineering Utilities
| Key | Action |
|-----|--------|
| `,ev` | Edit .vimrc |
| `,sv` | Reload .vimrc |
| `,F` | Format entire file |
| `,wa` | Save all buffers |
| `,cp` | Copy file path |
| `,cf` | Copy filename |
| `,*` | Search & replace word under cursor |
| `,<leader>` | Switch to last file |
### Other Utilities
| Key | Action |
|-----|--------|
| `F2` | Toggle paste mode |
| `F3` | Toggle line numbers |
| `F4` | Toggle relative numbers |
| `F5` | Toggle UndoTree |
| `F8` | Toggle Tagbar |
| `Space` | Toggle fold |
| `s` + 2 chars | EasyMotion jump |
## Plugin List
### File Navigation & Search
- **NERDTree**: File system explorer
- **FZF**: Fuzzy file finder
- **CtrlP**: Alternative fuzzy finder
### Git
- **vim-fugitive**: Git integration
- **vim-gitgutter**: Git diff in sign column
### UI
- **vim-airline**: Enhanced status line
- **gruvbox**: Color scheme
### Code Editing
- **vim-surround**: Manage surroundings
- **vim-commentary**: Code commenting
- **auto-pairs**: Auto close brackets
- **ALE**: Asynchronous linting
### Language Support
- **vim-polyglot**: Language pack for 100+ languages
- **vim-go**: Go development
### Productivity
- **UndoTree**: Undo history visualizer
- **Tagbar**: Code structure browser
- **EasyMotion**: Fast cursor movement
- **CoC**: Code completion and LSP
- **vim-obsession**: Session management
- **vim-prosession**: Project sessions
- **vim-unimpaired**: Handy bracket mappings
- **targets.vim**: Additional text objects
## Color Schemes
Available color schemes (change in .vimrc):
- **gruvbox** (default) - Warm, retro groove colors
- **dracula** - Dark theme with vivid colors
- **solarized** - Precision colors for machines and people
- **onedark** - Atom's iconic One Dark theme
To change:
```vim
colorscheme dracula
```
## Engineering Features
### Project-Specific Configuration
Create a `.vimrc` file in your project root for project-specific settings:
```vim
" .vimrc in project root
set shiftwidth=2
let g:ale_python_black_options = '--line-length=100'
```
The configuration automatically loads project-specific settings while maintaining security.
### Session Management
Sessions are automatically saved with vim-obsession:
```vim
" Start session tracking
:Obsess
" Stop session tracking
:Obsess!
" Sessions are saved to ~/.vim/sessions/
```
### Large File Handling
Files larger than 10MB automatically disable heavy features for better performance:
- Syntax highlighting optimized
- Undo levels reduced
- Swap files disabled
### Terminal Integration
Open integrated terminal:
- `,tv` - Vertical terminal split
- `,th` - Horizontal terminal split (10 rows)
Navigate out of terminal with `Esc` then normal window navigation.
### TTY and Basic Terminal Support
The configuration automatically detects and optimizes for basic terminal environments (TTY, Linux console):
**Automatic Optimizations:**
- Disables true color mode for compatibility
- Uses simple ASCII separators instead of powerline fonts
- Falls back to default colorscheme
- Disables cursorline for better performance
- Simplifies signcolumn behavior
- Disables FZF preview windows
- Skips auto-opening NERDTree
- Uses simpler status line
- Reduces syntax highlighting complexity
- Faster startup and redraw
**Detected Terminals:**
- Linux console (TERM=linux)
- Screen sessions (TERM=screen)
- Basic built-in terminals
The configuration provides a message on first run in TTY mode to inform about the optimizations.
## Customization
The configuration is organized into sections:
1. **General Settings**: Basic Vim behavior
2. **Plugin Management**: vim-plug configuration
3. **Colors & Fonts**: Visual appearance
4. **Key Mappings**: Custom keybindings
5. **Plugin Settings**: Individual plugin configurations
6. **Auto Commands**: File-type specific settings
7. **Helper Functions**: Utility functions
8. **Engineering Utilities**: Project workflow tools
9. **Git Workflow**: Git integration shortcuts
Feel free to modify any section to suit your needs!
### Quick Customization
Edit configuration:
```vim
,ev " Opens .vimrc in Vim
```
Reload configuration:
```vim
,sv " Sources .vimrc without restart
```
## Language-Specific Settings
### Python
- 4 spaces indentation
- 88 character line limit (Black formatter)
- Auto-formatting with Black + isort on save
- Linting with flake8 and pylint
### JavaScript/TypeScript
- 2 spaces indentation
- Prettier formatting on save
- ESLint integration
- TypeScript server support
### Go
- Tab indentation
- Auto-formatting with gofmt
- Auto-import with goimports
- gopls language server
### Rust
- Auto-formatting with rustfmt
- Cargo integration
### Shell Scripts
- 2 spaces indentation
- shellcheck linting
### Docker
- Dockerfile syntax highlighting
- hadolint linting
### YAML
- 2 spaces indentation
- yamllint integration
### HTML/CSS
- 2 spaces indentation
- Prettier formatting
### Markdown
- Line wrapping enabled
- Spell checking enabled
- Prettier formatting
## Troubleshooting
### Plugins not working
```vim
:PlugInstall
:PlugUpdate
```
### CoC not working
Make sure Node.js is installed:
```bash
node --version # Should be >= 14.14
```
### Colors look wrong
Enable true colors in your terminal emulator and add to your shell rc:
```bash
export TERM=xterm-256color
```
## References
This configuration is inspired by:
- [amix/vimrc](https://github.com/amix/vimrc) - The ultimate vimrc
- [vim-plug](https://github.com/junegunn/vim-plug) - Minimalist plugin manager
- [Top 50 Vim Configuration Options](https://www.shortcutfoo.com/blog/top-50-vim-configuration-options)
- [Modern Vim Development Setup 2025](https://swedishembedded.com/developers/vim-in-minutes)
## License
MIT License - Feel free to use and modify!
## Contributing
Suggestions and improvements are welcome! Feel free to open an issue or submit a pull request.

10
init.lua Normal file
View file

@ -0,0 +1,10 @@
if vim.loader then
vim.loader.enable()
end
_G.dd = function(...)
require("util.debug").dump(...)
end
vim.print = _G.dd
require("config.lazy")

View file

@ -1,140 +0,0 @@
#!/usr/bin/env bash
# ============================================================================
# Vim Configuration - Quick Installation Script
# ============================================================================
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BOLD='\033[1m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color
# Function to print status messages
print_status() {
echo -e "${GREEN}==>${NC} ${BOLD}$1${NC}"
}
print_warning() {
echo -e "${YELLOW}Warning:${NC} $1"
}
print_error() {
echo -e "${RED}Error:${NC} $1"
}
echo -e "${BOLD}========================================${NC}"
echo -e "${BOLD}Vim Configuration Installer${NC}"
echo -e "${BOLD}========================================${NC}\n"
# Verify .vimrc exists in script directory
if [ ! -f "$SCRIPT_DIR/.vimrc" ]; then
print_error "Cannot find .vimrc in $SCRIPT_DIR"
echo "Please run this script from the chopsticks directory:"
echo " cd ~/.vim && ./install.sh"
exit 1
fi
# Check if vim is installed
if ! command -v vim &> /dev/null; then
print_error "Vim is not installed. Please install Vim first."
echo " Ubuntu/Debian: sudo apt install vim"
echo " macOS: brew install vim"
echo " Fedora: sudo dnf install vim"
exit 1
fi
print_status "Vim version: $(vim --version | head -n1)"
# Backup existing .vimrc if it exists
if [ -f "$HOME/.vimrc" ] && [ ! -L "$HOME/.vimrc" ]; then
BACKUP_FILE="$HOME/.vimrc.backup.$(date +%Y%m%d_%H%M%S)"
print_warning "Backing up existing .vimrc to $BACKUP_FILE"
mv "$HOME/.vimrc" "$BACKUP_FILE"
fi
# Create symlink to .vimrc
print_status "Creating symlink: $HOME/.vimrc -> $SCRIPT_DIR/.vimrc"
ln -sf "$SCRIPT_DIR/.vimrc" "$HOME/.vimrc"
# Verify symlink was created correctly
if [ -L "$HOME/.vimrc" ]; then
LINK_TARGET=$(readlink "$HOME/.vimrc")
if [ "$LINK_TARGET" = "$SCRIPT_DIR/.vimrc" ]; then
echo -e "${GREEN}[OK]${NC} Symlink created successfully"
else
print_warning "Symlink points to unexpected target: $LINK_TARGET"
fi
else
print_error "Failed to create symlink"
exit 1
fi
# Install vim-plug if not already installed
VIM_PLUG_PATH="$HOME/.vim/autoload/plug.vim"
if [ ! -f "$VIM_PLUG_PATH" ]; then
print_status "Installing vim-plug..."
curl -fLo "$VIM_PLUG_PATH" --create-dirs \
https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
echo -e "${GREEN}[OK]${NC} vim-plug installed successfully"
else
echo -e "${GREEN}[OK]${NC} vim-plug already installed"
fi
# Install plugins
print_status "Installing Vim plugins..."
vim +PlugInstall +qall
echo -e "\n${GREEN}[OK]${NC} ${BOLD}Installation complete!${NC}\n"
# Print optional dependencies
echo -e "${BOLD}Optional Dependencies (Recommended):${NC}"
echo ""
echo -e "${BOLD}1. FZF (Fuzzy Finder):${NC}"
echo " Ubuntu/Debian: sudo apt install fzf ripgrep"
echo " macOS: brew install fzf ripgrep"
echo ""
echo -e "${BOLD}2. Node.js (for CoC completion):${NC}"
echo " Ubuntu/Debian: curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash - && sudo apt install -y nodejs"
echo " macOS: brew install node"
echo ""
echo -e "${BOLD}3. Universal Ctags (for code navigation):${NC}"
echo " Ubuntu/Debian: sudo apt install universal-ctags"
echo " macOS: brew install universal-ctags"
echo ""
echo -e "${BOLD}4. Language-specific tools:${NC}"
echo " Python: pip install black flake8 pylint"
echo " JavaScript: npm install -g prettier eslint"
echo " Go: go install golang.org/x/tools/gopls@latest"
echo ""
# Ask to install CoC language servers
read -p "Do you want to install CoC language servers now? (y/N) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
print_status "Installing CoC language servers..."
# Check if node is installed
if ! command -v node &> /dev/null; then
print_error "Node.js is not installed. Please install Node.js first."
else
vim +'CocInstall -sync coc-json coc-tsserver coc-pyright coc-sh coc-html coc-css coc-yaml' +qall
echo -e "${GREEN}[OK]${NC} CoC language servers installed"
fi
fi
echo ""
echo -e "${BOLD}========================================${NC}"
echo -e "${GREEN}All done!${NC} Open Vim and start coding!"
echo -e "${BOLD}========================================${NC}"
echo ""
echo -e "Quick tips:"
echo " - Press ${BOLD}Ctrl+n${NC} to toggle file explorer (NERDTree)"
echo " - Press ${BOLD}Ctrl+p${NC} to fuzzy search files (FZF)"
echo " - Press ${BOLD},w${NC} to quick save"
echo " - Press ${BOLD}K${NC} on a function to see documentation"
echo " - See README.md for complete key mappings"
echo ""

14
lua/config/autocmds.lua Normal file
View file

@ -0,0 +1,14 @@
-- Turn off paste mode when leaving insert
vim.api.nvim_create_autocmd("InsertLeave", {
pattern = "*",
command = "set nopaste",
})
-- Disable the concealing in some file formats
-- The default conceallevel is 3 in LazyVim
vim.api.nvim_create_autocmd("FileType", {
pattern = { "json", "jsonc", "markdown" },
callback = function()
vim.opt.conceallevel = 0
end,
})

72
lua/config/keymaps.lua Normal file
View file

@ -0,0 +1,72 @@
local discipline = require("m1ngsama.discipline")
-- discipline.cowboy()
local keymap = vim.keymap
local opts = { noremap = true, silent = true }
-- Do things without affecting the registers
keymap.set("n", "x", '"_x')
keymap.set("n", "<Leader>p", '"0p')
keymap.set("n", "<Leader>P", '"0P')
keymap.set("v", "<Leader>p", '"0p')
keymap.set("n", "<Leader>c", '"_c')
keymap.set("n", "<Leader>C", '"_C')
keymap.set("v", "<Leader>c", '"_c')
keymap.set("v", "<Leader>C", '"_C')
keymap.set("n", "<Leader>d", '"_d')
keymap.set("n", "<Leader>D", '"_D')
keymap.set("v", "<Leader>d", '"_d')
keymap.set("v", "<Leader>D", '"_D')
-- Increment/decrement
keymap.set("n", "+", "<C-a>")
keymap.set("n", "-", "<C-x>")
-- Delete a word backwards
keymap.set("n", "dw", 'vb"_d')
-- Select all
keymap.set("n", "<C-a>", "gg<S-v>G")
-- Save with root permission (not working for now)
--vim.api.nvim_create_user_command('W', 'w !sudo tee > /dev/null %', {})
-- Disable continuations
keymap.set("n", "<Leader>o", "o<Esc>^Da", opts)
keymap.set("n", "<Leader>O", "O<Esc>^Da", opts)
-- Jumplist
keymap.set("n", "<C-m>", "<C-i>", opts)
-- New tab
keymap.set("n", "te", ":tabedit")
keymap.set("n", "<tab>", ":tabnext<Return>", opts)
keymap.set("n", "<s-tab>", ":tabprev<Return>", opts)
-- Split window
keymap.set("n", "ss", ":split<Return>", opts)
keymap.set("n", "sv", ":vsplit<Return>", opts)
-- Move window
keymap.set("n", "sh", "<C-w>h")
keymap.set("n", "sk", "<C-w>k")
keymap.set("n", "sj", "<C-w>j")
keymap.set("n", "sl", "<C-w>l")
-- Resize window
keymap.set("n", "<C-w><left>", "<C-w><")
keymap.set("n", "<C-w><right>", "<C-w>>")
keymap.set("n", "<C-w><up>", "<C-w>+")
keymap.set("n", "<C-w><down>", "<C-w>-")
-- Diagnostics
keymap.set("n", "<C-j>", function()
vim.diagnostic.goto_next()
end, opts)
keymap.set("n", "<leader>r", function()
require("m1ngsama.hsl").replaceHexWithHSL()
end)
keymap.set("n", "<leader>i", function()
require("m1ngsama.lsp").toggleInlayHints()
end)

87
lua/config/lazy.lua Normal file
View file

@ -0,0 +1,87 @@
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({
spec = {
-- add LazyVim and import its plugins
{
"LazyVim/LazyVim",
import = "lazyvim.plugins",
opts = {
colorscheme = "solarized-osaka",
news = {
lazyvim = true,
neovim = true,
},
},
},
-- import any extras modules here
{ import = "lazyvim.plugins.extras.linting.eslint" },
{ import = "lazyvim.plugins.extras.formatting.prettier" },
{ import = "lazyvim.plugins.extras.lang.typescript" },
{ import = "lazyvim.plugins.extras.lang.json" },
-- { import = "lazyvim.plugins.extras.lang.markdown" },
{ import = "lazyvim.plugins.extras.lang.rust" },
{ import = "lazyvim.plugins.extras.lang.tailwind" },
-- { import = "lazyvim.plugins.extras.ai.copilot" },
-- { import = "lazyvim.plugins.extras.dap.core" },
-- { import = "lazyvim.plugins.extras.vscode" },
{ import = "lazyvim.plugins.extras.util.mini-hipatterns" },
-- { import = "lazyvim.plugins.extras.test.core" },
-- { import = "lazyvim.plugins.extras.coding.yanky" },
-- { import = "lazyvim.plugins.extras.editor.mini-files" },
-- { import = "lazyvim.plugins.extras.util.project" },
{ import = "plugins" },
},
defaults = {
-- By default, only LazyVim plugins will be lazy-loaded. Your custom plugins will load during startup.
-- If you know what you're doing, you can set this to `true` to have all your custom plugins lazy-loaded by default.
lazy = false,
-- It's recommended to leave version=false for now, since a lot the plugin that support versioning,
-- have outdated releases, which may break your Neovim install.
version = false, -- always use the latest git commit
-- version = "*", -- try installing the latest stable version for plugins that support semver
},
dev = {
path = "~/.ghq/github.com",
},
checker = { enabled = true }, -- automatically check for plugin updates
performance = {
cache = {
enabled = true,
-- disable_events = {},
},
rtp = {
-- disable some rtp plugins
disabled_plugins = {
"gzip",
-- "matchit",
-- "matchparen",
"netrwPlugin",
"rplugin",
"tarPlugin",
"tohtml",
"tutor",
"zipPlugin",
},
},
},
ui = {
custom_keys = {
["<localleader>d"] = function(plugin)
dd(plugin)
end,
},
},
debug = false,
})

47
lua/config/options.lua Normal file
View file

@ -0,0 +1,47 @@
vim.g.mapleader = " "
vim.opt.encoding = "utf-8"
vim.opt.fileencoding = "utf-8"
vim.opt.number = true
vim.opt.title = true
vim.opt.autoindent = true
vim.opt.smartindent = true
vim.opt.hlsearch = true
vim.opt.backup = false
vim.opt.showcmd = true
vim.opt.cmdheight = 1
vim.opt.laststatus = 3
vim.opt.expandtab = true
vim.opt.scrolloff = 10
vim.opt.shell = "fish"
vim.opt.backupskip = { "/tmp/*", "/private/tmp/*" }
vim.opt.inccommand = "split"
vim.opt.ignorecase = true -- Case insensitive searching UNLESS /C or capital in search
vim.opt.smarttab = true
vim.opt.breakindent = true
vim.opt.shiftwidth = 2
vim.opt.tabstop = 2
vim.opt.wrap = false -- No Wrap lines
vim.opt.backspace = { "start", "eol", "indent" }
vim.opt.path:append({ "**" }) -- Finding files - Search down into subfolders
vim.opt.wildignore:append({ "*/node_modules/*" })
vim.opt.splitbelow = true -- Put new windows below current
vim.opt.splitright = true -- Put new windows right of current
vim.opt.splitkeep = "cursor"
vim.opt.mouse = ""
-- Undercurl
vim.cmd([[let &t_Cs = "\e[4:3m"]])
vim.cmd([[let &t_Ce = "\e[4:0m"]])
-- Add asterisks in block comments
vim.opt.formatoptions:append({ "r" })
vim.cmd([[au BufNewFile,BufRead *.astro setf astro]])
vim.cmd([[au BufNewFile,BufRead Podfile setf ruby]])
if vim.fn.has("nvim-0.8") == 1 then
vim.opt.cmdheight = 0
end

View file

@ -0,0 +1,36 @@
local M = {}
function M.cowboy()
---@type table?
local ok = true
for _, key in ipairs({ "h", "j", "k", "l", "+", "-" }) do
local count = 0
local timer = assert(vim.uv.new_timer())
local map = key
vim.keymap.set("n", key, function()
if vim.v.count > 0 then
count = 0
end
if count >= 10 and vim.bo.buftype ~= "nofile" then
ok = pcall(vim.notify, "Hold it Cowboy!", vim.log.levels.WARN, {
icon = "🤠",
id = "cowboy",
keep = function()
return count >= 10
end,
})
if not ok then
return map
end
else
count = count + 1
timer:start(2000, 0, function()
count = 0
end)
return map
end
end, { expr = true, silent = true })
end
end
return M

154
lua/m1ngsama/hsl.lua Normal file
View file

@ -0,0 +1,154 @@
-- https://github.com/EmmanuelOga/columns/blob/master/utils/color.lua
local M = {}
local hexChars = "0123456789abcdef"
function M.hex_to_rgb(hex)
hex = string.lower(hex)
local ret = {}
for i = 0, 2 do
local char1 = string.sub(hex, i * 2 + 2, i * 2 + 2)
local char2 = string.sub(hex, i * 2 + 3, i * 2 + 3)
local digit1 = string.find(hexChars, char1) - 1
local digit2 = string.find(hexChars, char2) - 1
ret[i + 1] = (digit1 * 16 + digit2) / 255.0
end
return ret
end
--[[
* Converts an RGB color value to HSL. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes r, g, and b are contained in the set [0, 255] and
* returns h, s, and l in the set [0, 1].
*
* @param Number r The red color value
* @param Number g The green color value
* @param Number b The blue color value
* @return Array The HSL representation
]]
function M.rgbToHsl(r, g, b)
local max, min = math.max(r, g, b), math.min(r, g, b)
local h = 0
local s = 0
local l = 0
l = (max + min) / 2
if max == min then
h, s = 0, 0 -- achromatic
else
local d = max - min
if l > 0.5 then
s = d / (2 - max - min)
else
s = d / (max + min)
end
if max == r then
h = (g - b) / d
if g < b then
h = h + 6
end
elseif max == g then
h = (b - r) / d + 2
elseif max == b then
h = (r - g) / d + 4
end
h = h / 6
end
return h * 360, s * 100, l * 100
end
--[[
* Converts an HSL color value to RGB. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes h, s, and l are contained in the set [0, 1] and
* returns r, g, and b in the set [0, 255].
*
* @param Number h The hue
* @param Number s The saturation
* @param Number l The lightness
* @return Array The RGB representation
]]
function M.hslToRgb(h, s, l)
local r, g, b
if s == 0 then
r, g, b = l, l, l -- achromatic
else
function hue2rgb(p, q, t)
if t < 0 then
t = t + 1
end
if t > 1 then
t = t - 1
end
if t < 1 / 6 then
return p + (q - p) * 6 * t
end
if t < 1 / 2 then
return q
end
if t < 2 / 3 then
return p + (q - p) * (2 / 3 - t) * 6
end
return p
end
local q
if l < 0.5 then
q = l * (1 + s)
else
q = l + s - l * s
end
local p = 2 * l - q
r = hue2rgb(p, q, h + 1 / 3)
g = hue2rgb(p, q, h)
b = hue2rgb(p, q, h - 1 / 3)
end
return r * 255, g * 255, b * 255
end
function M.hexToHSL(hex)
local hsluv = require("solarized-osaka.hsluv")
local rgb = M.hex_to_rgb(hex)
local h, s, l = M.rgbToHsl(rgb[1], rgb[2], rgb[3])
return string.format("hsl(%d, %d, %d)", math.floor(h + 0.5), math.floor(s + 0.5), math.floor(l + 0.5))
end
--[[
* Converts an HSL color value to RGB in Hex representation.
* @param Number h The hue
* @param Number s The saturation
* @param Number l The lightness
* @return String The hex representation
]]
function M.hslToHex(h, s, l)
local r, g, b = M.hslToRgb(h / 360, s / 100, l / 100)
return string.format("#%02x%02x%02x", r, g, b)
end
function M.replaceHexWithHSL()
-- Get the current line number
local line_number = vim.api.nvim_win_get_cursor(0)[1]
-- Get the line content
local line_content = vim.api.nvim_buf_get_lines(0, line_number - 1, line_number, false)[1]
-- Find hex code patterns and replace them
for hex in line_content:gmatch("#[0-9a-fA-F]+") do
local hsl = M.hexToHSL(hex)
line_content = line_content:gsub(hex, hsl)
end
-- Set the line content back
vim.api.nvim_buf_set_lines(0, line_number - 1, line_number, false, { line_content })
end
return M

7
lua/m1ngsama/lsp.lua Normal file
View file

@ -0,0 +1,7 @@
local M = {}
function M.toggleInlayHints()
vim.lsp.inlay_hint.enable(0, not vim.lsp.inlay_hint.is_enabled())
end
return M

97
lua/plugins/coding.lua Normal file
View file

@ -0,0 +1,97 @@
return {
-- Create annotations with one keybind, and jump your cursor in the inserted annotation
{
"danymat/neogen",
keys = {
{
"<leader>cc",
function()
require("neogen").generate({})
end,
desc = "Neogen Comment",
},
},
opts = { snippet_engine = "luasnip" },
},
-- Incremental rename
{
"smjonas/inc-rename.nvim",
cmd = "IncRename",
config = true,
},
-- Refactoring tool
{
"ThePrimeagen/refactoring.nvim",
keys = {
{
"<leader>r",
function()
require("refactoring").select_refactor()
end,
mode = "v",
noremap = true,
silent = true,
expr = false,
},
},
opts = {},
},
-- Go forward/backward with square brackets
{
"echasnovski/mini.bracketed",
event = "BufReadPost",
config = function()
local bracketed = require("mini.bracketed")
bracketed.setup({
file = { suffix = "" },
window = { suffix = "" },
quickfix = { suffix = "" },
yank = { suffix = "" },
treesitter = { suffix = "n" },
})
end,
},
-- Better increase/descrease
{
"monaqa/dial.nvim",
-- stylua: ignore
keys = {
{ "<C-a>", function() return require("dial.map").inc_normal() end, expr = true, desc = "Increment" },
{ "<C-x>", function() return require("dial.map").dec_normal() end, expr = true, desc = "Decrement" },
},
config = function()
local augend = require("dial.augend")
require("dial.config").augends:register_group({
default = {
augend.integer.alias.decimal,
augend.integer.alias.hex,
augend.date.alias["%Y/%m/%d"],
augend.constant.alias.bool,
augend.semver.alias.semver,
augend.constant.new({ elements = { "let", "const" } }),
},
})
end,
},
{
"simrat39/symbols-outline.nvim",
keys = { { "<leader>cs", "<cmd>SymbolsOutline<cr>", desc = "Symbols Outline" } },
cmd = "SymbolsOutline",
opts = {
position = "right",
},
},
{
"nvim-cmp",
dependencies = { "hrsh7th/cmp-emoji" },
opts = function(_, opts)
table.insert(opts.sources, { name = "emoji" })
end,
},
}

View file

@ -0,0 +1,12 @@
return {
{
"craftzdog/solarized-osaka.nvim",
lazy = true,
priority = 1000,
opts = function()
return {
transparent = true,
}
end,
},
}

237
lua/plugins/editor.lua Normal file
View file

@ -0,0 +1,237 @@
return {
{
enabled = false,
"folke/flash.nvim",
---@type Flash.Config
opts = {
search = {
forward = true,
multi_window = false,
wrap = false,
incremental = true,
},
},
},
{
"echasnovski/mini.hipatterns",
event = "BufReadPre",
opts = {
highlighters = {
hsl_color = {
pattern = "hsl%(%d+,? %d+%%?,? %d+%%?%)",
group = function(_, match)
local utils = require("solarized-osaka.hsl")
--- @type string, string, string
local nh, ns, nl = match:match("hsl%((%d+),? (%d+)%%?,? (%d+)%%?%)")
--- @type number?, number?, number?
local h, s, l = tonumber(nh), tonumber(ns), tonumber(nl)
--- @type string
local hex_color = utils.hslToHex(h, s, l)
return MiniHipatterns.compute_hex_color_group(hex_color, "bg")
end,
},
},
},
},
{
"dinhhuy258/git.nvim",
event = "BufReadPre",
opts = {
keymaps = {
-- Open blame window
blame = "<Leader>gb",
-- Open file/folder in git repository
browse = "<Leader>go",
},
},
},
{
"nvim-telescope/telescope.nvim",
dependencies = {
{
"nvim-telescope/telescope-fzf-native.nvim",
build = "make",
},
"nvim-telescope/telescope-file-browser.nvim",
},
keys = {
{
"<leader>fP",
function()
require("telescope.builtin").find_files({
cwd = require("lazy.core.config").options.root,
})
end,
desc = "Find Plugin File",
},
{
";f",
function()
local builtin = require("telescope.builtin")
builtin.find_files({
no_ignore = false,
hidden = true,
})
end,
desc = "Lists files in your current working directory, respects .gitignore",
},
{
";r",
function()
local builtin = require("telescope.builtin")
builtin.live_grep({
additional_args = { "--hidden" },
})
end,
desc = "Search for a string in your current working directory and get results live as you type, respects .gitignore",
},
{
"\\\\",
function()
local builtin = require("telescope.builtin")
builtin.buffers()
end,
desc = "Lists open buffers",
},
{
";t",
function()
local builtin = require("telescope.builtin")
builtin.help_tags()
end,
desc = "Lists available help tags and opens a new window with the relevant help info on <cr>",
},
{
";;",
function()
local builtin = require("telescope.builtin")
builtin.resume()
end,
desc = "Resume the previous telescope picker",
},
{
";e",
function()
local builtin = require("telescope.builtin")
builtin.diagnostics()
end,
desc = "Lists Diagnostics for all open buffers or a specific buffer",
},
{
";s",
function()
local builtin = require("telescope.builtin")
builtin.treesitter()
end,
desc = "Lists Function names, variables, from Treesitter",
},
{
"sf",
function()
local telescope = require("telescope")
local function telescope_buffer_dir()
return vim.fn.expand("%:p:h")
end
telescope.extensions.file_browser.file_browser({
path = "%:p:h",
cwd = telescope_buffer_dir(),
respect_gitignore = false,
hidden = true,
grouped = true,
previewer = false,
initial_mode = "normal",
layout_config = { height = 40 },
})
end,
desc = "Open File Browser with the path of the current buffer",
},
},
config = function(_, opts)
local telescope = require("telescope")
local actions = require("telescope.actions")
local fb_actions = require("telescope").extensions.file_browser.actions
opts.defaults = vim.tbl_deep_extend("force", opts.defaults, {
wrap_results = true,
layout_strategy = "horizontal",
layout_config = { prompt_position = "top" },
sorting_strategy = "ascending",
winblend = 0,
mappings = {
n = {},
},
})
opts.pickers = {
diagnostics = {
theme = "ivy",
initial_mode = "normal",
layout_config = {
preview_cutoff = 9999,
},
},
}
opts.extensions = {
file_browser = {
theme = "dropdown",
-- disables netrw and use telescope-file-browser in its place
hijack_netrw = true,
mappings = {
-- your custom insert mode mappings
["n"] = {
-- your custom normal mode mappings
["N"] = fb_actions.create,
["h"] = fb_actions.goto_parent_dir,
["/"] = function()
vim.cmd("startinsert")
end,
["<C-u>"] = function(prompt_bufnr)
for i = 1, 10 do
actions.move_selection_previous(prompt_bufnr)
end
end,
["<C-d>"] = function(prompt_bufnr)
for i = 1, 10 do
actions.move_selection_next(prompt_bufnr)
end
end,
["<PageUp>"] = actions.preview_scrolling_up,
["<PageDown>"] = actions.preview_scrolling_down,
},
},
},
}
telescope.setup(opts)
require("telescope").load_extension("fzf")
require("telescope").load_extension("file_browser")
end,
},
{
"saghen/blink.cmp",
opts = {
completion = {
menu = {
winblend = vim.o.pumblend,
},
},
signature = {
window = {
winblend = vim.o.pumblend,
},
},
},
},
{
"3rd/image.nvim",
build = false, -- so that it doesn't build the rock https://github.com/3rd/image.nvim/issues/91#issuecomment-2453430239
opts = {
processor = "magick_cli",
},
},
}

179
lua/plugins/lsp.lua Normal file
View file

@ -0,0 +1,179 @@
return {
-- tools
{
"williamboman/mason.nvim",
opts = function(_, opts)
vim.list_extend(opts.ensure_installed, {
"stylua",
"selene",
"luacheck",
"shellcheck",
"shfmt",
"tailwindcss-language-server",
"typescript-language-server",
"css-lsp",
"clangd",
})
end,
},
-- lsp servers
{
"neovim/nvim-lspconfig",
opts = {
inlay_hints = { enabled = false },
---@type lspconfig.options
servers = {
cssls = {},
tailwindcss = {
root_dir = function(...)
return require("lspconfig.util").root_pattern(".git")(...)
end,
},
tsserver = {
root_dir = function(...)
return require("lspconfig.util").root_pattern(".git")(...)
end,
single_file_support = false,
settings = {
typescript = {
inlayHints = {
includeInlayParameterNameHints = "literal",
includeInlayParameterNameHintsWhenArgumentMatchesName = false,
includeInlayFunctionParameterTypeHints = true,
includeInlayVariableTypeHints = false,
includeInlayPropertyDeclarationTypeHints = true,
includeInlayFunctionLikeReturnTypeHints = true,
includeInlayEnumMemberValueHints = true,
},
},
javascript = {
inlayHints = {
includeInlayParameterNameHints = "all",
includeInlayParameterNameHintsWhenArgumentMatchesName = false,
includeInlayFunctionParameterTypeHints = true,
includeInlayVariableTypeHints = true,
includeInlayPropertyDeclarationTypeHints = true,
includeInlayFunctionLikeReturnTypeHints = true,
includeInlayEnumMemberValueHints = true,
},
},
},
},
html = {},
yamlls = {
settings = {
yaml = {
keyOrdering = false,
},
},
},
lua_ls = {
-- enabled = false,
single_file_support = true,
settings = {
Lua = {
workspace = {
checkThirdParty = false,
},
completion = {
workspaceWord = true,
callSnippet = "Both",
},
misc = {
parameters = {
-- "--log-level=trace",
},
},
hint = {
enable = true,
setType = false,
paramType = true,
paramName = "Disable",
semicolon = "Disable",
arrayIndex = "Disable",
},
doc = {
privateName = { "^_" },
},
type = {
castNumberToInteger = true,
},
diagnostics = {
disable = { "incomplete-signature-doc", "trailing-space" },
-- enable = false,
groupSeverity = {
strong = "Warning",
strict = "Warning",
},
groupFileStatus = {
["ambiguity"] = "Opened",
["await"] = "Opened",
["codestyle"] = "None",
["duplicate"] = "Opened",
["global"] = "Opened",
["luadoc"] = "Opened",
["redefined"] = "Opened",
["strict"] = "Opened",
["strong"] = "Opened",
["type-check"] = "Opened",
["unbalanced"] = "Opened",
["unused"] = "Opened",
},
unusedLocalExclude = { "_*" },
},
format = {
enable = false,
defaultConfig = {
indent_style = "space",
indent_size = "2",
continuation_indent_size = "2",
},
},
},
},
},
gopls = {
settings = {
gopls = {
analyses = {
unusedparams = true,
shadow = true,
},
staticcheck = true,
},
},
},
clangd = {
cmd = { "clangd", "--background-index" },
filetypes = { "c", "cpp", "objc", "objcpp" },
root_dir = function(...)
return require("lspconfig.util").root_pattern(
"compile_commands.json",
"compile_flags.txt",
".git"
)(...)
end,
},
},
setup = {},
},
},
{
"neovim/nvim-lspconfig",
opts = function()
local keys = require("lazyvim.plugins.lsp.keymaps").get()
vim.list_extend(keys, {
{
"gd",
function()
-- DO NOT RESUSE WINDOW
require("telescope.builtin").lsp_definitions({ reuse_win = false })
end,
desc = "Goto Definition",
has = "definition",
},
})
end,
},
}

View file

@ -0,0 +1,67 @@
return {
{ "nvim-treesitter/playground", cmd = "TSPlaygroundToggle" },
{
"nvim-treesitter/nvim-treesitter",
opts = {
ensure_installed = {
"astro",
"cmake",
"cpp",
"css",
"fish",
"gitignore",
"go",
"graphql",
"http",
"java",
"php",
"rust",
"scss",
"sql",
"svelte",
},
-- matchup = {
-- enable = true,
-- },
-- https://github.com/nvim-treesitter/playground#query-linter
query_linter = {
enable = true,
use_virtual_text = true,
lint_events = { "BufWrite", "CursorHold" },
},
playground = {
enable = true,
disable = {},
updatetime = 25, -- Debounced time for highlighting nodes in the playground from source code
persist_queries = true, -- Whether the query persists across vim sessions
keybindings = {
toggle_query_editor = "o",
toggle_hl_groups = "i",
toggle_injected_languages = "t",
toggle_anonymous_nodes = "a",
toggle_language_display = "I",
focus_language = "f",
unfocus_language = "F",
update = "R",
goto_node = "<cr>",
show_help = "?",
},
},
},
config = function(_, opts)
require("nvim-treesitter.configs").setup(opts)
-- MDX
vim.filetype.add({
extension = {
mdx = "mdx",
},
})
vim.treesitter.language.register("markdown", "mdx")
end,
},
}

170
lua/plugins/ui.lua Normal file
View file

@ -0,0 +1,170 @@
return {
-- messages, cmdline and the popupmenu
{
"folke/noice.nvim",
opts = function(_, opts)
table.insert(opts.routes, {
filter = {
event = "notify",
find = "No information available",
},
opts = { skip = true },
})
local focused = true
vim.api.nvim_create_autocmd("FocusGained", {
callback = function()
focused = true
end,
})
vim.api.nvim_create_autocmd("FocusLost", {
callback = function()
focused = false
end,
})
table.insert(opts.routes, 1, {
filter = {
cond = function()
return not focused
end,
},
view = "notify_send",
opts = { stop = false },
})
opts.commands = {
all = {
-- options for the message history that you get with `:Noice`
view = "split",
opts = { enter = true, format = "details" },
filter = {},
},
}
vim.api.nvim_create_autocmd("FileType", {
pattern = "markdown",
callback = function(event)
vim.schedule(function()
require("noice.text.markdown").keys(event.buf)
end)
end,
})
opts.presets.lsp_doc_border = true
end,
},
{
"rcarriga/nvim-notify",
opts = {
timeout = 5000,
},
},
{
"snacks.nvim",
opts = {
scroll = { enabled = false },
},
keys = {},
},
-- buffer line
{
"akinsho/bufferline.nvim",
event = "VeryLazy",
keys = {
{ "<Tab>", "<Cmd>BufferLineCycleNext<CR>", desc = "Next tab" },
{ "<S-Tab>", "<Cmd>BufferLineCyclePrev<CR>", desc = "Prev tab" },
},
opts = {
options = {
mode = "tabs",
-- separator_style = "slant",
show_buffer_close_icons = false,
show_close_icon = false,
},
},
},
-- filename
{
"b0o/incline.nvim",
dependencies = { "craftzdog/solarized-osaka.nvim" },
event = "BufReadPre",
priority = 1200,
config = function()
local colors = require("solarized-osaka.colors").setup()
require("incline").setup({
highlight = {
groups = {
InclineNormal = { guibg = colors.magenta500, guifg = colors.base04 },
InclineNormalNC = { guifg = colors.violet500, guibg = colors.base03 },
},
},
window = { margin = { vertical = 0, horizontal = 1 } },
hide = {
cursorline = true,
},
render = function(props)
local filename = vim.fn.fnamemodify(vim.api.nvim_buf_get_name(props.buf), ":t")
if vim.bo[props.buf].modified then
filename = "[+] " .. filename
end
local icon, color = require("nvim-web-devicons").get_icon_color(filename)
return { { icon, guifg = color }, { " " }, { filename } }
end,
})
end,
},
-- statusline
{
"nvim-lualine/lualine.nvim",
opts = function(_, opts)
local LazyVim = require("lazyvim.util")
opts.sections.lualine_c[4] = {
LazyVim.lualine.pretty_path({
length = 0,
relative = "cwd",
modified_hl = "MatchParen",
directory_hl = "",
filename_hl = "Bold",
modified_sign = "",
readonly_icon = " 󰌾 ",
}),
}
end,
},
{
"folke/zen-mode.nvim",
cmd = "ZenMode",
opts = {
plugins = {
gitsigns = true,
tmux = true,
kitty = { enabled = false, font = "+2" },
},
},
keys = { { "<leader>z", "<cmd>ZenMode<cr>", desc = "Zen Mode" } },
},
{
"folke/snacks.nvim",
opts = {
dashboard = {
preset = {
header = [[
]],
},
},
},
},
}

158
lua/util/debug.lua Normal file
View file

@ -0,0 +1,158 @@
-- selene: allow(global_usage)
local M = {}
function M.get_loc()
local me = debug.getinfo(1, "S")
local level = 2
local info = debug.getinfo(level, "S")
while info and (info.source == me.source or info.source == "@" .. vim.env.MYVIMRC or info.what ~= "Lua") do
level = level + 1
info = debug.getinfo(level, "S")
end
info = info or me
local source = info.source:sub(2)
source = vim.loop.fs_realpath(source) or source
return source .. ":" .. info.linedefined
end
---@param value any
---@param opts? {loc:string}
function M._dump(value, opts)
opts = opts or {}
opts.loc = opts.loc or M.get_loc()
if vim.in_fast_event() then
return vim.schedule(function()
M._dump(value, opts)
end)
end
opts.loc = vim.fn.fnamemodify(opts.loc, ":~:.")
local msg = vim.inspect(value)
vim.notify(msg, vim.log.levels.INFO, {
title = "Debug: " .. opts.loc,
on_open = function(win)
vim.wo[win].conceallevel = 3
vim.wo[win].concealcursor = ""
vim.wo[win].spell = false
local buf = vim.api.nvim_win_get_buf(win)
if not pcall(vim.treesitter.start, buf, "lua") then
vim.bo[buf].filetype = "lua"
end
end,
})
end
function M.dump(...)
local value = { ... }
if vim.tbl_isempty(value) then
value = nil
else
value = vim.tbl_islist(value) and vim.tbl_count(value) <= 1 and value[1] or value
end
M._dump(value)
end
function M.extmark_leaks()
local nsn = vim.api.nvim_get_namespaces()
local counts = {}
for name, ns in pairs(nsn) do
for _, buf in ipairs(vim.api.nvim_list_bufs()) do
local count = #vim.api.nvim_buf_get_extmarks(buf, ns, 0, -1, {})
if count > 0 then
counts[#counts + 1] = {
name = name,
buf = buf,
count = count,
ft = vim.bo[buf].ft,
}
end
end
end
table.sort(counts, function(a, b)
return a.count > b.count
end)
dd(counts)
end
function estimateSize(value, visited)
if value == nil then
return 0
end
local bytes = 0
-- initialize the visited table if not already done
--- @type table<any, true>
visited = visited or {}
-- handle already-visited value to avoid infinite recursion
if visited[value] then
return 0
else
visited[value] = true
end
if type(value) == "boolean" or value == nil then
bytes = 4
elseif type(value) == "number" then
bytes = 8
elseif type(value) == "string" then
bytes = string.len(value) + 24
elseif type(value) == "function" then
bytes = 32 -- base size for a function
-- add size of upvalues
local i = 1
while true do
local name, val = debug.getupvalue(value, i)
if not name then
break
end
bytes = bytes + estimateSize(val, visited)
i = i + 1
end
elseif type(value) == "table" then
bytes = 40 -- base size for a table entry
for k, v in pairs(value) do
bytes = bytes + estimateSize(k, visited) + estimateSize(v, visited)
end
local mt = debug.getmetatable(value)
if mt then
bytes = bytes + estimateSize(mt, visited)
end
end
return bytes
end
function M.module_leaks(filter)
local sizes = {}
for modname, mod in pairs(package.loaded) do
if not filter or modname:match(filter) then
local root = modname:match("^([^%.]+)%..*$") or modname
-- root = modname
sizes[root] = sizes[root] or { mod = root, size = 0 }
sizes[root].size = sizes[root].size + estimateSize(mod) / 1024 / 1024
end
end
sizes = vim.tbl_values(sizes)
table.sort(sizes, function(a, b)
return a.size > b.size
end)
dd(sizes)
end
function M.get_upvalue(func, name)
local i = 1
while true do
local n, v = debug.getupvalue(func, i)
if not n then
break
end
if n == name then
return v
end
i = i + 1
end
end
return M