Skip to content

Instantly share code, notes, and snippets.

@rnyrnyrny
Last active July 17, 2024 08:00
Show Gist options
  • Save rnyrnyrny/756f6c7556db5acaab044e16d74618cd to your computer and use it in GitHub Desktop.
Save rnyrnyrny/756f6c7556db5acaab044e16d74618cd to your computer and use it in GitHub Desktop.
my neovim config
" { =============================================== Plugin List =======================================================
call plug#begin(stdpath('data') . '/plugged')
Plug 'scrooloose/nerdcommenter' "easy commenting
Plug 'airblade/vim-gitgutter' "show git diffs
Plug 'will133/vim-dirdiff'
Plug 'fatih/vim-go'
Plug 'flazz/vim-colorschemes'
" If the software manager can install fzf, comment this line
" and use `set rtp+=/usr/bin/fzf` or where your fzf is
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
Plug 'junegunn/fzf.vim'
Plug 'nvim-tree/nvim-tree.lua'
Plug 'majutsushi/tagbar'
"Plug 'scrooloose/syntastic' "syntax checking
Plug 'tpope/vim-fugitive' "git bindings
Plug 'jiangmiao/auto-pairs'
Plug 'davidhalter/jedi-vim'
Plug 'MattesGroeger/vim-bookmarks'
Plug 'tpope/vim-repeat' "dependency of leap.nvim
Plug 'ggandor/leap.nvim'
" auto-completion
Plug 'neoclide/coc.nvim', {'branch': 'release'}
Plug 'antoinemadec/coc-fzf', {'branch': 'release'}
"Plug 'nvim-treesitter/nvim-treesitter', {'do': ':TSUpdate'}
call plug#end()
" =================================================================================================================== }
" { =============================================== General Configs ===================================================
set fileencodings=ucs-bom,utf-8,cp936,gb18030,big5,euc-jp,euc-kr,latin1
set nu
set relativenumber
set splitright
set colorcolumn=120
set mouse=a
" ctrl-o like ctrl-t tag stack
set jumpoptions+=stack
syntax on
" remember cursor position
if has("autocmd")
au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif
endif
" *.eh *.ih *.inc c files
au BufRead,BufNewFile *.eh setfiletype c
au BufRead,BufNewFile *.ih setfiletype c
au BufRead,BufNewFile *.inc setfiletype c
au filetype go set tabstop=4 shiftwidth=4 noet
au filetype java set tabstop=4 shiftwidth=4 noet
au filetype sh set et ts=4 sw=4
au filetype json set et ts=4 sw=4 filetype=json foldmethod=syntax
" The following are done in sensibel.vim or neovim itself
"set wildmenu
"set laststatus=2
"set hlsearch
"set completeopt=menuone,menu,longest,preview
" {------------------------------------------------- Key Bindings -----------------------------------------------------
let mapleader=","
let g:mapleader=","
let maplocalleader=","
" search cursor word and place cursor back
map * *``
map # #``
" hilight cursor word
nnoremap <leader>1 :let m1=matchadd("Search", expand("<cword>"))<CR>
nnoremap <leader>2 :let m2=matchadd("WildMenu", expand("<cword>"))<CR>
nnoremap <leader>= @=clearmatches()<CR>
nnoremap <leader>m1 @=matchdelete(m1)<CR>
nnoremap <leader>m2 @=matchdelete(m2)<CR>
"nnoremap <C-K> :Man<CR>
" quickfix cjk
function! QfMakeConv()
let qflist = getqflist()
for i in qflist
let i.text = iconv(i.text, "cp936", "utf-8")
endfor
call setqflist(qflist)
endfunction
nnoremap <F2> :copen<CR>
nnoremap <F3> :call QfMakeConv()<CR>
nnoremap <C-c> :cclose<CR>
nnoremap <C-n> :cn<CR>
nnoremap <C-p> :cp<CR>
" grep to quickfix
set grepprg=rg\ --vimgrep\ --smart-case\ -u
set grepformat=%f:%l:%c:%m,%f:%l:%m
nnoremap <c-f> :silent grep!<Space>
nnoremap <leader>f :silent grep! <C-r><C-w><CR>:copen<CR>
" autofold preprocessor
function! FoldPreprocessor()
" set foldmarker=#ifdef,#endif
set foldmarker=#if,#endif
set foldmethod=marker
endfunction
set foldlevelstart=99
set foldmarker=\{,\}
set foldmethod=syntax
nnoremap <space> @=((foldclosed(line('.')) < 0) ? 'zc' : 'zo')<CR>
" --------------------------------------------------------------------------------------------------------------------}
" { -------------------------------------------------- Clipboard ------------------------------------------------------
"set clipboard+=unnamed,unnamedplus
vnoremap <leader>x "_x
vnoremap <leader>d "_d
vnoremap <leader>y "*y
vnoremap <leader>p "*P
vnoremap <leader>Y "+y
vnoremap <leader>P "+P
" gui pasting
if has("gui_running")
map <S-Insert> <MiddleMouse>
map! <S-Insert> <MiddleMouse>
endif
" --------------------------------------------------------------------------------------------------------------------}
" { ---------------------------------------------------- UI -----------------------------------------------------------
set background=dark
set t_Co=256
colorscheme gruvbox
" Returns true if paste mode is enabled
function! HasPaste()
if &paste
return 'PASTE MODE '
endif
return ''
endfunction
" status line
set statusline=\ %{HasPaste()}\ %{FugitiveStatusline()}\ %t%m%r%h\ %w\ \ CWD:\ %r%{getcwd()}%h\ \ \ Line:\ %l\ \ Column:\ %c
set list
"set listchars=tab:»\ ,eol:¬,trail:-,extends:>,precedes:<,nbsp:+
set listchars=tab:\|\ ,trail:-,extends:>,precedes:<,nbsp:+
" --------------------------------------------------------------------------------------------------------------------}
" =================================================================================================================== }
" { ================================================= Plugin Config ===================================================
" { -------------------------------------------------- vim-go ---------------------------------------------------------
"let g:go_bin_path = "/data/gotools/"
let g:go_gopls_enabled = 1
let g:go_gopls_options = ['-remote=auto']
let g:go_def_mode='gopls'
let g:go_info_mode='gopls'
let g:go_referrers_mode = 'gopls'
let g:go_autodetect_gopath = 1
" syntax-hilight
let g:go_highlight_functions = 1
let g:go_highlight_methods = 1
let g:go_highlight_fields = 1
let g:go_highlight_types = 1
let g:go_highlight_operators = 1
let g:go_highlight_build_constraints = 1
" avoid lagging when using both vim-go and syntastic
"let g:syntastic_go_checkers = ['golint', 'govet', 'errcheck', 'go', 'gofmt']
"let g:syntastic_mode_map = { 'mode': 'active', 'passive_filetypes': ['go'] }
"let syntastic_aggregate_errors = 1
let g:go_list_type = "quickfix"
let g:go_term_enabled = 1
let g:go_auto_type_info = 0
let g:go_def_reuse_buffer = 1
map <leader>c :SyntasticCheck golint govet errcheck go gofmt<CR>
" for goimports
let g:go_def_mapping_enabled = 0
au FileType go nmap <c-j> <Plug>(go-def)
au FileType go nmap <leader>gi :GoImports<CR>
au FileType go nmap <Leader>ds <Plug>(go-def-split)
au FileType go nmap <Leader>dv <Plug>(go-def-vertical)
au FileType go nmap <Leader>dt <Plug>(go-def-tab)
au FileType go nmap <Leader>gd <Plug>(go-doc)
au FileType go nmap <Leader>gv <Plug>(go-doc-vertical)
au FileType go nmap <Leader>s <Plug>(go-implements)
au FileType go nmap <Leader>i <Plug>(go-info)
au FileType go nmap <leader>e <Plug>(go-rename)
au FileType go nmap <Leader>gr :GoReferrers<CR>
au FileType go nmap <leader>rt <Plug>(go-run-tab)
au FileType go nmap <leader>rs <Plug>(go-run-split)
au FileType go nmap <leader>rv <Plug>(go-run-vertical)
au FileType go nmap <leader>gc :GoCallers<CR>
au FileType go nmap <leader>ch :GoChannelPeers<CR>
" --------------------------------------------------------------------------------------------------------------------}
" { -------------------------------------------------- fzf-vim --------------------------------------------------------
" for fzf installed from software manager
" set rtp+=/usr/sbin/fzf
" This is the default extra key bindings
let g:fzf_action = {
\ 'ctrl-t': 'tab split',
\ 'ctrl-x': 'split',
\ 'ctrl-v': 'vsplit' }
" Default fzf layout
" - down / up / left / right
"let g:fzf_layout = { 'down': '~40%' }
let g:fzf_layout = { 'window': { 'width': 0.9, 'height': 0.8 } }
" Customize fzf colors to match your color scheme
let g:fzf_colors =
\ { 'fg': ['fg', 'Normal'],
\ 'bg': ['bg', 'Normal'],
\ 'hl': ['fg', 'Comment'],
\ 'fg+': ['fg', 'CursorLine', 'CursorColumn', 'Normal'],
\ 'bg+': ['bg', 'CursorLine', 'CursorColumn'],
\ 'hl+': ['fg', 'Statement'],
\ 'info': ['fg', 'PreProc'],
\ 'prompt': ['fg', 'Conditional'],
\ 'pointer': ['fg', 'Exception'],
\ 'marker': ['fg', 'Keyword'],
\ 'spinner': ['fg', 'Label'],
\ 'header': ['fg', 'Comment'] }
" Enable per-command history.
" CTRL-N and CTRL-P will be automatically bound to next-history and
" previous-history instead of down and up. If you don't like the change,
" explicitly bind the keys to down and up in your $FZF_DEFAULT_OPTS.
let g:fzf_history_dir = '~/.local/share/fzf-history'
" Command-local options
" [Files] Extra options for fzf
" e.g. File preview using Highlight
" (http://www.andre-simon.de/doku/highlight/en/highlight.html)
let g:fzf_files_options =
\ ' --preview "(highlight -O ansi {} || cat {}) 2> /dev/null | head -'.&lines.'" --keep-right'
" [Buffers] Jump to the existing window if possible
let g:fzf_buffers_jump = 1
" [[B]Commits] Customize the options used by 'git log':
let g:fzf_commits_log_options = '--graph --color=always --format="%C(auto)%h%d %s %C(black)%C(bold)%cr"'
" [Tags] Command to generate tags file
let g:fzf_tags_command = 'ctags -L .tagfiles -R -h=".h.H.inc.eh.ih" --langmap=c:+.eh.ih.inc'
" [Commands] --expect expression for directly executing the command
let g:fzf_commands_expect = 'alt-enter,ctrl-x'
" configure preview window
let g:fzf_vim = {}
let g:fzf_vim.preview_window = ['hidden,up,50%,<70(up,50%)', 'ctrl-/']
" fzf key-binding
nnoremap <M-t> :<C-u>Tags<cr>
nnoremap <M-f> :<C-u>FZF<cr>
nnoremap <M-c> :<C-u>History<cr>
nnoremap <M-g> :<C-u>GFiles?<cr>
nnoremap <M-b> :<C-u>Buffers<cr>
" --------------------------------------------------------------------------------------------------------------------}
" { ------------------------------------------------ nvim-tree.lua & Tagbar ------------------------------------------------
map <leader>t :TagbarToggle<CR>
let g:tagbar_iconchars = ['+', '-']
" gotags for tagbar
let g:tagbar_type_go = {
\ 'ctagstype' : 'go',
\ 'kinds' : [
\ 'p:package',
\ 'i:imports:1',
\ 'c:constants',
\ 'v:variables',
\ 't:types',
\ 'n:interfaces',
\ 'w:fields',
\ 'e:embedded',
\ 'm:methods',
\ 'r:constructor',
\ 'f:functions'
\ ],
\ 'sro' : '.',
\ 'kind2scope' : {
\ 't' : 'ctype',
\ 'n' : 'ntype'
\ },
\ 'scope2kind' : {
\ 'ctype' : 't',
\ 'ntype' : 'n'
\ }
\ }
map <leader>n :NvimTreeToggle<CR>
map <Leader>B :NvimTreeFindFile<CR>
lua<<EOF
-- disable netrw at the very start of your init.lua
vim.g.loaded_netrw = 1
vim.g.loaded_netrwPlugin = 1
-- optionally enable 24-bit colour
vim.opt.termguicolors = true
-- OR setup with some options
require("nvim-tree").setup({
sort = {
sorter = "case_sensitive",
},
view = {
width = 30,
},
renderer = {
group_empty = true,
},
filters = {
dotfiles = false,
},
})
EOF
" --------------------------------------------------------------------------------------------------------------------}
" { ------------------------------------------------- syntastic -------------------------------------------------------
"set statusline+=%#warningmsg#
"set statusline+=%{SyntasticStatuslineFlag()}
"set statusline+=%*
"let g:syntastic_always_populate_loc_list = 1
"let g:syntastic_auto_loc_list = 1
"let g:syntastic_check_on_open = 1
"let g:syntastic_check_on_wq = 0
" --------------------------------------------------------------------------------------------------------------------}
" { ------------------------------------------------- fugitive --------------------------------------------------------
autocmd QuickFixCmdPost *grep* cwindow
function! s:BlameToggle() abort
let found = 0
for winnr in range(1, winnr('$'))
if getbufvar(winbufnr(winnr), '&filetype') ==# 'fugitiveblame'
exe winnr . 'close'
let found = 1
endif
endfor
if !found
Git blame
endif
endfunction
nmap <silent> <Leader>b :call <SID>BlameToggle()<CR>
" --------------------------------------------------------------------------------------------------------------------}
" { ------------------------------------------------- auto-pairs ------------------------------------------------------
let g:AutoPairsShortcutToggle = ''
let g:AutoPairsCenterLine = 0
" --------------------------------------------------------------------------------------------------------------------}
" { ------------------------------------------------- jedi-vim --------------------------------------------------------
"let g:jedi#auto_initialization = 0
let g:jedi#completions_enabled = 0
"let g:jedi#goto_command = "<leader>d"
"let g:jedi#goto_assignments_command = "<C-]>"
let g:jedi#goto_definitions_command = "<C-j>"
"let g:jedi#documentation_command = "K"
let g:jedi#usages_command = "<F7>"
"let g:jedi#completions_command = "<C-Space>"
let g:jedi#rename_command = "<leader>r"
let g:jedi#force_py_version = 2
" --------------------------------------------------------------------------------------------------------------------}
" { ------------------------------------------------ vim-bookmarks ----------------------------------------------------
let g:bookmark_sign = '*'
let g:bookmark_annotation_sign = '##'
let g:bookmark_save_per_working_dir = 1
"let g:bookmark_highlight_lines = 1
let g:bookmark_center = 1
" Finds the Git super-project directory.
function! g:BMWorkDirFileLocation()
let filename = 'bookmarks'
let location = ''
if isdirectory('.git')
" Current work dir is git's work tree
let location = getcwd().'/.git'
else
" Look upwards (at parents) for a directory named '.git'
let location = finddir('.git', '.;')
endif
if len(location) > 0
return location.'/'.filename
else
return getcwd().'/.'.filename
endif
endfunction
" --------------------------------------------------------------------------------------------------------------------}
" { -------------------------------------------------- coc.nvim -------------------------------------------------------
" Some servers have issues with backup files, see #649
set nobackup
set nowritebackup
let g:coc_global_extensions = ['coc-json', 'coc-git']
inoremap <silent><expr> <TAB>
\ coc#pum#visible() ? coc#pum#next(1):
\ <SID>check_back_space() ? "\<Tab>" :
\ coc#refresh()
inoremap <expr><S-TAB> coc#pum#visible() ? coc#pum#prev(1) : "\<C-h>"
function! s:check_back_space() abort
let col = col('.') - 1
return !col || getline('.')[col - 1] =~# '\s'
endfunction
" 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> <c-j> <Plug>(coc-definition)
nmap <silent> gy <Plug>(coc-type-definition)
nmap <silent> gi <Plug>(coc-implementation)
nmap <silent> gr <Plug>(coc-references)
nmap <silent> <M-r> :<C-u>CocFzfList commands<CR>
nmap <silent> <M-e> :<C-u>CocFzfList diagnostics --current-buf<CR>
nnoremap <silent> <leader><space> :<C-u>CocFzfList<CR>
" 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)
" Applying code actions to the selected code block
" Example: `<leader>aap` for current paragraph
xmap <leader>a <Plug>(coc-codeaction-selected)
nmap <leader>a <Plug>(coc-codeaction-selected)
" Remap keys for applying code actions at the cursor position
nmap <leader>ac <Plug>(coc-codeaction-cursor)
" Remap keys for apply code actions affect whole buffer
nmap <leader>as <Plug>(coc-codeaction-source)
" Apply the most preferred quickfix action to fix diagnostic on the current line
nmap <leader>qf <Plug>(coc-fix-current)
" Remap keys for applying refactor code actions
nmap <silent> <leader>re <Plug>(coc-codeaction-refactor)
xmap <silent> <leader>r <Plug>(coc-codeaction-refactor-selected)
nmap <silent> <leader>r <Plug>(coc-codeaction-refactor-selected)
" Run the Code Lens action on the current line
nmap <leader>cl <Plug>(coc-codelens-action)
" Add `:Format` command to format current buffer
command! -nargs=0 Format :call CocActionAsync('format')
" Add `:Fold` command to fold current buffer
command! -nargs=? Fold :call CocAction('fold', <f-args>)
" Add `:OR` command for organize imports of the current buffer
command! -nargs=0 OR :call CocActionAsync('runCommand', 'editor.action.organizeImport')
" Highlight the symbol and its references when holding the cursor.
autocmd CursorHold * silent call CocActionAsync('highlight')
" show documentation in preview window.
nnoremap <silent> <c-k> :call <SID>show_documentation()<CR>
function! s:show_documentation()
if (index(['vim','help'], &filetype) >= 0)
execute 'h '.expand('<cword>')
elseif (coc#rpc#ready())
call CocActionAsync('doHover')
else
execute '!' . &keywordprg . " " . expand('<cword>')
endif
endfunction
set statusline^=%{coc#status()}%{get(b:,'coc_current_function','')}
" coc-snippets
" Use <leader>x for convert visual selected code to snippet
xmap <leader>x <Plug>(coc-convert-snippet)
"autocmd User CocOpenFloat call nvim_win_set_config(g:coc_last_float_win, {'relative': 'cursor', 'row': -10, 'col': 0})
"autocmd User CocOpenFloat call nvim_win_set_width(g:coc_last_float_win, 9999)
" --------------------------------------------------------------------------------------------------------------------}
" { ------------------------------------------------- treesitter ------------------------------------------------------
lua<<EOF
-- require'nvim-treesitter.configs'.setup {
-- -- One of "all", "maintained" (parsers with maintainers), or a list of languages
-- ensure_installed = "maintained",
--
-- -- Install languages synchronously (only applied to `ensure_installed`)
-- sync_install = false,
--
-- -- List of parsers to ignore installing
-- ignore_install = { "javascript" },
--
-- highlight = {
-- -- `false` will disable the whole extension
-- enable = true,
--
-- -- list of language that will be disabled
-- disable = {},
--
-- -- Setting this to true will run `:h syntax` and tree-sitter at the same time.
-- -- Set this to `true` if you depend on 'syntax' being enabled (like for indentation).
-- -- Using this option may slow down your editor, and you may see some duplicate highlights.
-- -- Instead of true it can also be a list of languages
-- additional_vim_regex_highlighting = false,
-- },
-- }
EOF
" --------------------------------------------------------------------------------------------------------------------}
" { ------------------------------------------------- leap.nvim -------------------------------------------------------
lua<<EOF
-- require('leap').create_default_mappings()
vim.keymap.set('n', 'f', '<Plug>(leap)')
vim.keymap.set('n', 'F', '<Plug>(leap-from-window)')
vim.keymap.set({'x', 'o'}, 'f', '<Plug>(leap-forward)')
vim.keymap.set({'x', 'o'}, 'F', '<Plug>(leap-backward)')
-- Define equivalence classes for brackets and quotes, in addition to
-- the default whitespace group.
require('leap').opts.equivalence_classes = { ' \t\r\n', '([{', ')]}', '\'"`' }
-- Override some old defaults - use backspace instead of tab (see issue #165).
require('leap').opts.special_keys.prev_target = '<backspace>'
require('leap').opts.special_keys.prev_group = '<backspace>'
EOF
" --------------------------------------------------------------------------------------------------------------------}
" ====================================================================================================================}
" vim: set et ts=4 sw=4:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment