-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinit.vim
1007 lines (902 loc) · 33.5 KB
/
init.vim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"================ Vim Plug =====================
"Auto install Vim Plug
if empty(glob('~/.vim/autoload/plug.vim'))
silent !curl -fLo ~/.vim/autoload/plug.vim --create-dirs
\ https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
autocmd VimEnter * PlugInstal.l:project_pathl | source $MYVIMRC
endif
call plug#begin('~/.vim/plugged')
" Essential
Plug 'junegunn/fzf', { 'do': { -> fzf#install() } }
Plug 'junegunn/fzf.vim'
Plug 'lambdalisue/fern.vim'
" "--------- Language syntax
Plug 'nvim-treesitter/nvim-treesitter', {'do': ':TSUpdate'}
" Color schema
Plug 'EdenEast/nightfox.nvim' " Vim-Plug
" Theme + Style
"Plug 'norcalli/nvim-colorizer.lua'
Plug 'ryanoasis/vim-devicons'
Plug 'lambdalisue/fern-renderer-devicons.vim'
" Show indent line
Plug 'lukas-reineke/indent-blankline.nvim'
" Register list
Plug 'junegunn/vim-peekaboo'
" Support to jump to text
Plug 'smoka7/hop.nvim'
Plug 'ntpeters/vim-better-whitespace'
"{
let g:better_whitespace_filetypes_blacklist=['log', 'fugitive', 'quickfix', 'git']
"}
Plug 'tpope/vim-surround'
Plug 'tpope/vim-repeat'
Plug 'mg979/vim-visual-multi'
Plug 'alvan/vim-closetag'
" Extend matching for html tag
Plug 'andymass/vim-matchup'
" Enhance matching tag for xml, html document
Plug 'Valloric/MatchTagAlways'
Plug 'dhruvasagar/vim-table-mode'
" Note taking
" Git
Plug 'tpope/vim-fugitive'
Plug 'junkblocker/git-time-lapse'
" --- Integrate github to git
Plug 'tpope/vim-rhubarb'
" Align text
Plug 'junegunn/vim-easy-align'
" Auto add pairing
Plug 'windwp/nvim-autopairs'
" Better end in ruby,lua
Plug 'RRethy/nvim-treesitter-endwise'
" More shortcut/keybinding
Plug 'tpope/vim-unimpaired'
" Split/Join code
Plug 'AndrewRadev/splitjoin.vim'
" Send command to tmux
Plug 'christoomey/vim-tmux-runner'
" Navigate between tmux and vim
Plug 'christoomey/vim-tmux-navigator'
" Snippet
Plug 'honza/vim-snippets'
Plug 'mlaursen/vim-react-snippets'
" Indent object, fit for yml,python file
Plug 'michaeljsmith/vim-indent-object'
" CamelCaseMotion
Plug 'bkad/CamelCaseMotion'
"---{
let g:camelcasemotion_key = ','
"---}
" NarrowText in temp buffer
Plug 'chrisbra/NrrwRgn'
" Support raw search for ag and rg from fzf
Plug 'jesseleite/vim-agriculture'
" Markdown and folding
Plug 'plasticboy/vim-markdown'
" Asynchonous call
Plug 'tpope/vim-dispatch'
" manage projection and alternate file
Plug 'tpope/vim-projectionist'
" Completion plugins
Plug 'hrsh7th/nvim-cmp' " Autocompletion plugin
Plug 'hrsh7th/cmp-nvim-lsp' " LSP source for nvim-cmp
Plug 'hrsh7th/cmp-buffer'
Plug 'hrsh7th/cmp-path'
" Completion list for yank
Plug 'gbprod/yanky.nvim'
Plug 'chrisgrieser/cmp_yanky'
"
" LSP Config for Neovim
Plug 'neovim/nvim-lspconfig'
" Mason for managing LSP servers, linters, formatters
Plug 'williamboman/mason.nvim'
Plug 'williamboman/mason-lspconfig.nvim'
" Formatter
Plug 'stevearc/conform.nvim'
" Snippet engine (required for nvim-cmp)
Plug 'L3MON4D3/LuaSnip' " Snippet engine
Plug 'saadparwaiz1/cmp_luasnip' " Snippet completions
" Statusline with LSP progress
Plug 'nvim-lualine/lualine.nvim'
" Icons for better UI (optional but recommended)
Plug 'kyazdani42/nvim-web-devicons'
" LSP status indicator
Plug 'j-hui/fidget.nvim'
" Symbol postion
Plug 'SmiteshP/nvim-navic'
call plug#end()
"{
lua << LUA
require("hop").setup()
require("ibl").setup()
vim.api.nvim_set_keymap('', 'f', "<cmd>lua require'hop'.hint_char1({ direction = require'hop.hint'.HintDirection.AFTER_CURSOR, current_line_only = true })<cr>", {})
vim.api.nvim_set_keymap('', 'F', "<cmd>lua require'hop'.hint_char1({ direction = require'hop.hint'.HintDirection.BEFORE_CURSOR, current_line_only = true })<cr>", {})
vim.api.nvim_set_keymap('', 't', "<cmd>lua require'hop'.hint_char1({ direction = require'hop.hint'.HintDirection.AFTER_CURSOR, current_line_only = true, hint_offset = -1 })<cr>", {})
vim.api.nvim_set_keymap('', 'T', "<cmd>lua require'hop'.hint_char1({ direction = require'hop.hint'.HintDirection.BEFORE_CURSOR, current_line_only = true, hint_offset = 1 })<cr>", {})
require("nvim-autopairs").setup {}
-- Load custom treesitter grammar for org filetype
require'nvim-treesitter.configs'.setup {
ensure_installed = "all", -- one of "all", "maintained" (parsers with maintainers), or a list of languages
ignore_install = { "haskell", "phpdoc" },
endwise = {
enable = true,
},
highlight = {
enable = true, -- false will disable the whole extension
disable = function(lang, bufnr)
end,
},
incremental_selection = {
enable = false,
keymaps = {
init_selection = "gnn",
node_incremental = "grn",
scope_incremental = "grc",
node_decremental = "grm",
},
},
}
require("yanky").setup({
highlight = {
on_put = false,
on_yank = false,
},
})
-- Initialize Mason
require('mason').setup()
-- Ensure that Mason installs the LSPs we need
require('mason-lspconfig').setup({
ensure_installed = { 'pyright', 'lua_ls' }, -- Add your desired language servers here
automatic_installation = true,
})
-- Setup LSP configurations
local lspconfig = require('lspconfig')
-- Format on save function
local format_on_save = function(client, bufnr)
if client.server_capabilities.documentFormattingProvider then
vim.api.nvim_create_autocmd("BufWritePre", {
buffer = bufnr,
callback = function()
vim.lsp.buf.format({ async = false })
end
})
end
end
require("conform").setup({
formatters_by_ft = {
lua = { "stylua" },
-- Conform will run multiple formatters sequentially
python = { "isort", "black" },
ruby = {"standardrb" },
-- You can customize some of the format options for the filetype (:help conform.format)
rust = { "rustfmt", lsp_format = "fallback" },
-- Conform will run the first available formatter
javascript = { "oxc", "prettierd" },
typescript = { "oxc", "prettierd" },
typescriptreact = { "oxc", "prettierd" },
javascripttreact = { "oxc", "prettierd" },
json = { "fixjson"}
},
format_on_save = {
-- These options will be passed to conform.format()
timeout_ms = 5000,
lsp_format = "fallback",
},
})
local navic = require('nvim-navic')
navic.setup({
depth_limit = 1,
})
-- Function to attach keybindings and format on save
local on_attach = function(client, bufnr)
local opts = { noremap=true, silent=true }
vim.api.nvim_buf_set_keymap(bufnr, 'n', 'gd', '<Cmd>lua vim.lsp.buf.definition()<CR>', opts)
vim.api.nvim_buf_set_keymap(bufnr, 'n', 'K', '<Cmd>lua vim.lsp.buf.hover()<CR>', opts)
vim.api.nvim_buf_set_keymap(bufnr, 'n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', opts)
vim.api.nvim_buf_set_keymap(bufnr, 'n', 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', opts)
vim.api.nvim_buf_set_keymap(bufnr, 'n', 'rn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts)
vim.api.nvim_buf_set_keymap(bufnr, 'n', 'ca', '<cmd>lua vim.lsp.buf.code_action()<CR>', opts)
vim.api.nvim_buf_set_keymap(bufnr, 'x', 'ca', '<cmd>lua vim.lsp.buf.code_action()<CR>', opts)
vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with(
vim.lsp.diagnostic.on_publish_diagnostics, {
signs = {
min = "Error",
},
virtual_text = {
min = "Error",
},
}
)
-- Check if the LSP supports document symbols, then attach nvim-navic
if client.server_capabilities.documentSymbolProvider then
navic.attach(client, bufnr)
end
end
require('lspconfig').eslint.setup{
settings = {
format = { enable = false },
}
}
-- Setup LSP for servers managed by Mason
require('mason-lspconfig').setup_handlers({
function(server_name)
lspconfig[server_name].setup({
on_attach = on_attach,
})
end
})
-- Setup for LSP autocompletion using nvim-cmp
local cmp = require'cmp'
cmp.setup({
snippet = {
expand = function(args)
require('luasnip').lsp_expand(args.body) -- For `luasnip` users
end,
},
mapping = {
['<C-N>'] = cmp.mapping.select_next_item(),
['<C-P>'] = cmp.mapping.select_prev_item(),
['<C-X>'] = cmp.mapping.confirm({ select = true }),
['<C-Space>'] = cmp.mapping.complete(),
},
sources = cmp.config.sources({
{ name = 'nvim_lsp' },
{ name = 'vsnip' }, -- For vsnip users.
{ name = 'luasnip' }, -- For luasnip users.
-- { name = 'ultisnips' }, -- For ultisnips users.
-- { name = 'snippy' }, -- For snippy users.
}, {
{ name = 'buffer' },
})
})
-- Setup LSP completion capabilities
local capabilities = require('cmp_nvim_lsp').default_capabilities()
-- Attach capabilities to LSP configurations
require('mason-lspconfig').setup_handlers({
function(server_name)
lspconfig[server_name].setup({
on_attach = on_attach,
capabilities = capabilities,
})
end
})
-- Lualine setup with LSP status
require('lualine').setup{
options = {
theme = 'auto',
icons_enabled = true,
},
sections = {
lualine_b = {},
lualine_c = {
function()
local mode = vim.api.nvim_get_mode().mode
if mode == "t" then
return ""
end
local filepath = vim.fn.fnamemodify(vim.fn.expand('%:p'), ':~:.')
return vim.fn.pathshorten(filepath) -- Shorten it using pathshorten
end,
{'lsp_progress'}, -- LSP status
},
lualine_y = {},
lualine_x = {
-- Treesitter context (current symbol)
{
function()
return navic.get_location() -- Get current symbol location
end,
cond = function()
return navic.is_available() -- Only show if navic data is available
end,
}
},
},
}
-- Fidget setup for LSP progress
require('fidget').setup{}
LUA
"}
set laststatus=2
function! RipgrepFzf(query, fullscreen)
let command_fmt = 'rg --column --line-number --no-heading --color=always --smart-case %s '
let initial_command = printf(command_fmt, a:query)
let reload_command = printf(command_fmt, '{q}')
let spec = {'options': ['--phony', '--query', a:query, '--bind', 'change:reload:'.reload_command]}
call fzf#vim#grep(initial_command, 1, fzf#vim#with_preview(spec), a:fullscreen)
endfunction
command! -nargs=* -bang RG call RipgrepFzf(<q-args>, <bang>0)
" Ignore that because it leads to start in replace mode
nnoremap <Esc><Esc> :noh<CR><Esc>
" Move to bottom after select paragraph
vnoremap y y']
" nmap gx :silent execute "!open " . shellescape("<cWORD>")<CR><CR>
" Select inside the tick
function! Ticks(inner)
normal! gv
call searchpos('`', 'bW')
if a:inner | exe "normal! 1\<space>" | endif
normal! o
call searchpos('`', 'W')
if a:inner | exe "normal! \<bs>" | endif
endfunction
vnoremap <silent> a` :<c-u>call Ticks(0)<cr>
vnoremap <silent> i` :<c-u>call Ticks(1)<cr>
onoremap <silent> a` :<c-u>normal va`<cr>
onoremap <silent> i` :<c-u>normal vi`<cr>
" Map Emacs like movement in Insert mode
inoremap <C-n> <Down>
inoremap <C-p> <Up>
inoremap <C-f> <Right>
inoremap <C-b> <Left>
inoremap <C-e> <C-o>$
inoremap <C-a> <C-o>^
cnoremap <C-A> <Home>
cnoremap <C-B> <Left>
cnoremap <C-D> <Del>
cnoremap <C-E> <End>
cnoremap <C-F> <Right>
cnoremap <C-N> <Down>
cnoremap <C-P> <Up>
cnoremap <M-b> <S-Left>
cnoremap <M-f> <S-Right>
" These mappings will make it so that going to the next one in a search will
" center on the line it's found in.
nnoremap n nzzzv
nnoremap N Nzzzv
" https://vim.fandom.com/wiki/Selecting_your_pasted_text
nnoremap gp `[v`]
" "========================================================
" " leader config
" "========================================================
let mapleader=" "
noremap <silent> <leader>m :Fern . -drawer -toggle<CR>
noremap <silent> <leader>r :execute GoToProjDir() <bar> Fern . -reveal=% -drawer<CR>
" TmuxRunner
"{
let g:vtr_filetype_runner_overrides = {
\ 'ruby': 'ruby -w {file}',
\ 'javascript': 'node {file}',
\ 'sql': 'usql postgres://postgres@localhost:5432/flexlane?sslmode=disable -G -f {file}',
\ 'haskell': 'runhaskell {file}'
\ }
nnoremap <leader>v- :VtrOpenRunner { "orientation": "v", "percentage": 30 }<cr>
nnoremap <leader>v\ :VtrOpenRunner { "orientation": "h", "percentage": 30 }<cr>
nnoremap <leader>vk :VtrKillRunner<cr>
nnoremap <leader>vd :VtrSendCtrlD<cr>
nnoremap <leader>vc :VtrSendCtrlC<cr>
nnoremap <leader>vp :VtrSendKeysRaw Up Enter<cr>
nnoremap <leader>va :VtrAttachToPane<cr>
nnoremap <leader>vq :VtrSendKeysRaw q<cr>
nnoremap <leader>vz :VtrFocusRunner<cr>
nnoremap <leader>v0 :VtrAttachToPane 0<cr>:call system("tmux clock-mode -t 0 && sleep 0.1 && tmux send-keys -t 0 q")<cr>
nnoremap <leader>v1 :VtrAttachToPane 1<cr>:call system("tmux clock-mode -t 1 && sleep 0.1 && tmux send-keys -t 1 q")<cr>
nnoremap <leader>v2 :VtrAttachToPane 2<cr>:call system("tmux clock-mode -t 2 && sleep 0.1 && tmux send-keys -t 2 q")<cr>
nnoremap <leader>v3 :VtrAttachToPane 3<cr>:call system("tmux clock-mode -t 3 && sleep 0.1 && tmux send-keys -t 3 q")<cr>
nnoremap <leader>v4 :VtrAttachToPane 4<cr>:call system("tmux clock-mode -t 4 && sleep 0.1 && tmux send-keys -t 4 q")<cr>
nnoremap <leader>v5 :VtrAttachToPane 5<cr>:call system("tmux clock-mode -t 5 && sleep 0.1 && tmux send-keys -t 5 q")<cr>
nnoremap <leader>vf :VtrSendFile<cr>
nnoremap <C-c><C-c> :VtrSendLinesToRunner<cr>
" Work in ruby with escape chracter. Will list down other cases
vnoremap <C-c><C-c> y:VtrSendCommandToRunner <C-R>" <cr>
function! GoToProjDir()
let path = expand('%:p')
let path_parts = split(path, '/')
let project_part_idx = 0
for part in path_parts
if part == "projects"
if stridx(path, "hashback") >=0
let project_part_idx += 1
endif
break
endif
let project_part_idx += 1
endfor
let project_path = "/".join(path_parts[0:project_part_idx + 1], "/")
execute 'cd '.l:project_path
endfunction
" Mapping tmux-navigator control
let g:fern#mapping#mappings= ['drawer', 'filter', 'mark', 'node', 'open', 'wait', 'yank']
autocmd FileType fern nnoremap <buffer> <c-l> :wincmd l<cr>
autocmd FileType fern nmap <buffer><nowait> z <Plug>(fern-action-zoom:half)
autocmd FileType fern nnoremap <buffer> <c-j> :TmuxNavigateDown<cr>
autocmd FileType fern hi CursorLine ctermbg=20 guibg=#2c323c gui=bold
" Searching
noremap <leader>f :FZF<CR>
vnoremap <leader>f y:call fzf#vim#files('.', {'options': ['--query', '<C-R>=@"<CR>']})<CR>
noremap <leader>b :Buffers<CR>
noremap <silent> <leader>h :call fzf#vim#history({ 'options': ['--header-lines', 0, '--header', getcwd()]})<CR>
noremap <leader>d :Cd <CR>
" Search for the word under cursor
nnoremap <silent> <leader>ag :call histadd("cmd", 'Ag <C-R><C-W>') <bar> Ag <C-R><C-W><CR>
vnoremap <silent> <leader>ag y:call histadd("cmd", 'Ag <C-R>=@"<CR>') <bar> Ag <C-R>=@"<CR><CR>
nnoremap <silent> <leader>rg :call histadd("cmd", 'Rg <C-R><C-W>') <bar> Rg <C-R><C-W><CR>
vnoremap <silent> <leader>rg y:call histadd("cmd", 'Rg <C-R>=@"<CR>') <bar> Rg <C-R>=@"<CR><CR>
" Add handle in fern, move to new active buffer
function! SearchFern(input, function_name)
wincmd l
let l:ascii_name = substitute(split(a:input)[1], "\\..*$", "", 'g')
let l:ascii_name = substitute(l:ascii_name, "/", "", 'g')
call histadd('cmd', a:function_name.' '.l:ascii_name)
execute a:function_name.' '.l:ascii_name
endfunction
autocmd FileType fern nmap <silent> <buffer> <leader>ag :call SearchFern('<C-R><C-L>', 'Ag')<CR>
autocmd FileType fern nmap <silent> <buffer> <leader>rg :call SearchFern('<C-R><C-L>', 'Rg')<CR>
nnoremap <silent> <leader>/ :BLines<CR>
nnoremap <silent> <leader>8 :Lines<CR>
" Search for the visually selected text
vnoremap // y/\V<C-R>=escape(@",'/\')<CR><CR>
" Start interactive EasyAlign in visual mode (e.g. vipga)
xmap ga <Plug>(EasyAlign)
" Start interactive EasyAlign for a motion/text object (e.g. gaip)
nmap ga <Plug>(EasyAlign)
" Open sh in current folder
noremap <leader>z :split <bar> term<cr>
tnoremap <leader>z <c-\><c-n><c-o><esc><esc>
tnoremap <leader>q <c-\><c-n>
" Quick saving / edit
noremap <leader>w :w<cr>
noremap <leader>e :e!<cr>
noremap <leader>q :q<cr>
" only tab
noremap <leader>to :tabonly<cr>
" Split screen
noremap <leader>s :vsplit<cr>
" Change to avoid conflict with vimtmux
noremap <leader>vv :split<cr>
" Copy and Comment Lines
nmap gy yygccp
" Copy current file / folder path
nnoremap <silent> cP :let @+ = expand("%") <bar> echo @+<CR>
nnoremap <silent> cp :let @+ = expand("%:p") <bar> echo @+<CR>
nnoremap <silent> cl :let @+ = expand("%").":".line(".") <bar> echo @+<CR>
nnoremap <silent> cL :let @+ = expand("%:p").":".line(".") <bar> echo @+<CR>
" Git
noremap <leader>gl :execute 'Git pull origin '.FugitiveHead()<cr>
noremap <leader>gL :Git stash <bar> execute 'Git pull origin '.FugitiveHead() <bar> Git stash apply <bar> echo "Pull success"<cr>
noremap <leader>gp :Git push origin HEAD <bar>echo "Pushed success" <cr>
noremap <leader>gP :Git push origin HEAD --force <bar>echo "Pushed success" <cr>
noremap <leader>gb :Git blame<cr>
noremap <leader>gc :BranchList<cr>
noremap <leader>gC :BranchList!<cr>
noremap <leader>gm :echo 'Merging origin/'.GetMergeBranchByProj() <bar> execute 'Git fetch origin '.GetMergeBranchByProj() <bar> execute 'Git rebase origin/'.GetMergeBranchByProj() <cr>
noremap <leader>gd :execute 'Git diff '.GInitCommitWhenBranching().'..HEAD'<cr>
noremap <leader>gD :execute 'Git diff --name-status '.GInitCommitWhenBranching().'..HEAD'<cr>
noremap <leader>g1 :Git cherry-pick HEAD@{1}<cr>
noremap <leader>g0 :Git cherry-pick HEAD@{2}<Left>
" reload current file in source code
noremap <leader>gr :execute 'edit +'.line('.').' '.substitute(expand('%'), 'fugitive://\\|.git//\x*/', '', 'g')<cr>
function! GInitCommitWhenBranching()
let merge_branch = GetMergeBranchByProj()
let commit = system('git merge-base '.FugitiveHead().' origin/'.l:merge_branch)
return commit[:-2]
endfunction
function! GNewBranch()
let branch_name = input('Enter your branch ('.pathshorten(getcwd()).'):')
if len(l:branch_name) == 0
return
endif
let merge_branch = GetMergeBranchByProj()
execute '!git fetch origin '.l:merge_branch
execute '!git checkout -b '.l:branch_name.' origin/'.l:merge_branch
endfunction
function! GetMergeBranchByProj()
let merge_branch = 'master'
if stridx(getcwd(), "employment-hero") >=0
\ || stridx(getcwd(), "smartmatch-hub") >= 0
let merge_branch = "development"
elseif stridx(getcwd(), "time-tracking") >=0
let merge_branch = "dev"
elseif stridx(getcwd(), "frontend-script") >= 0
\ || stridx(getcwd(), "shabu-town") >= 0
\ || stridx(getcwd(), "gold-diggers") >= 0
let merge_branch = "main"
endif
return merge_branch
endfunction
noremap <silent> <leader>gn :call GNewBranch()<CR>
" Git status in new tab
noremap <leader>gs :Gtabedit :<cr>
noremap <leader>gS :Git<cr>
nnoremap <leader>gh :GBrowse!<cr>
vnoremap <leader>gh :GBrowse!<cr>
nnoremap <leader>gH :GBrowse<cr>
vnoremap <leader>gH :GBrowse<cr>
function! OpenFilePath(fugitive_path)
let file_path_with_hash = split(split(a:fugitive_path, '//')[-1])[-1]
let file_path_index = 0
if stridx(file_path_with_hash, "a/") >= 0 || stridx(file_path_with_hash, "b/") >= 0
let file_path_index = 1
endif
let file_path = join(split(file_path_with_hash, '/')[file_path_index:], '/')
execute 'edit '.file_path
endfunction
augroup fugitive_ext
autocmd!
" Browse to the commit under my cursor
autocmd FileType fugitiveblame,git,qf nnoremap <buffer> <leader>gh :execute ":GBrowse " . expand("<cword>")<cr>
autocmd FileType fugitive nnoremap <buffer> <leader>gb :GBrowse head<cr>
autocmd FileType fugitive nnoremap <buffer> <leader>gB :GBrowse! head<cr>
autocmd FileType fugitive nnoremap <buffer> D :!rm -rf <c-r><c-f><cr>
"autocmd FileType fugitive setlocal synmaxcol=500
" Unmap q so that we can use macro to multiple remove
" autocmd FileType fugitive nunmap <buffer> q
autocmd FileType git nnoremap <buffer> q q
autocmd FileType fugitive,help DisableWhitespace
autocmd FileType git nnoremap <buffer> go Vy:call OpenFilePath('<C-R>=@"<CR>')<CR>
augroup END
" Github PR
function! s:pr_cmd_by_proj()
if stridx(getcwd(), "shabu-town") >= 0 ||
\ stridx(getcwd(), "coop-game") >= 0
execute "Git hub-pr"
else
execute "Git hub-pr -d"
endif
endfunction
nnoremap <leader>pr :call <SID>pr_cmd_by_proj()<cr>
" Github PR list
function! s:pr_checkout(selected)
let l:pr_number = split(a:selected[1])[0]
if a:selected[0] == 'ctrl-o'
execute '!hub pr show '.l:pr_number
else
execute '!hub pr checkout '.l:pr_number
endif
endfunction
command! -nargs=* -complete=dir -bang PrList call
\ fzf#run(fzf#wrap(
\ {
\ 'source': "hub pr list -f '%I %t-%au %cr %n'".(<bang>0 == 0 ? '' : ' -s all -L 200'),
\ 'sink*': function('s:pr_checkout'),
\ 'options': [
\ '--tiebreak', 'index',
\ '--prompt', "Pull request>",
\ '--expect=ctrl-o'
\ ]
\ } , 0))
nnoremap <leader>pl :PrList<cr>
nnoremap <leader>pL :PrList!<cr>
" Open github PR at current branch
function! Open_Pr_In_Branch()
if has('mac')
execute "!open $(hub pr list --format='\\%H \\%U \\%n' | grep $(git rev-parse --abbrev-ref HEAD) | awk '{print $2}')"
elseif has("unix")
execute "!xdg-open $(hub pr list --format='\\%H \\%U \\%n' | grep $(git rev-parse --abbrev-ref HEAD) | awk '{print $2}')"
endif
endfunction
nnoremap <silent> <leader>po :call Open_Pr_In_Branch()<cr><cr>
" Checkout list branch
function! s:git_checkout(selected)
let l:branch = split(a:selected[1])[0]
if a:selected[0] == 'ctrl-d'
for delete_selected in a:selected[1:]
let l:delete_branch = split(delete_selected)[0]
execute '!git branch -D '.l:delete_branch
endfor
echo 'Deleted branch successfully'
else
execute 'Git checkout '.l:branch
endif
endfunction
command! -nargs=* -complete=dir -bang BranchList call
\ fzf#run(fzf#wrap(
\ {
\ 'source': "git for-each-ref --sort=-committerdate refs/heads/ --format=".shellescape(
\ '%(HEAD) %(refname:short) - %(contents:subject) - %(authorname) (%(committerdate:relative))'
\ )
\ .(<bang>0 == 0 ? '' : ' --all'),
\ 'sink*': function('s:git_checkout'),
\ 'options': [
\ '--tiebreak', 'index',
\ '--multi' ,
\ '--prompt', "Branches>",
\ '--expect=ctrl-d'
\ ]
\ },0))
" Choose window config
nmap <leader>- <Plug>(choosewin)
" Equal window width
function! EqualWindow()
let window_counter = 0
windo let window_counter = window_counter + 1
let size = &columns/l:window_counter
execute 'windo vertical resize '.l:size
endfunction
nmap <leader>= :call EqualWindow()<cr>
" Easy jump
map <leader>jk :HopChar1<CR>
map <leader>jw :HopChar1MW<CR>
xmap <leader>jk <cmd>lua require'hop'.hint_char1()<CR>
let g:fern#renderer = "devicons"
let g:fern_renderer_devicons_disable_warning = 1
if !exists('g:WebDevIconsUnicodeDecorateFileNodesExtensionSymbols')
let g:WebDevIconsUnicodeDecorateFileNodesExtensionSymbols = {}
endif
" Custom airline
" let g:airline_theme='bubblegum'
" let g:airline_section_c=airline#section#create(["%{pathshorten(fnamemodify(expand('%'), ':~:.'))}"])
" let g:airline_section_b=airline#section#create(["%{FugitiveHead()[:20]}"])
" let g:airline#extensions#default#layout = [
" \ [ 'a', 'b', 'c' ],
" \ [ 'x', 'error', 'warning' ]
" \ ]
"
" Custom closetag
let g:closetag_filenames = '*.js,*.jsx,*.html, *.xml'
" yank/copy-paste policy
if has('win32') || has('win64') || has('mac')
set clipboard=unnamed
else
set clipboard=unnamed,unnamedplus
endif
set autoindent " Copy indent from current line when starting a new line
set smarttab
set tabstop=2 " Number of space og a <Tab> character
set softtabstop=2
set shiftwidth=2 " Number of spaces use by autoindent
" set lazyredraw
set synmaxcol=120 " avoid slow rendering for long lines
" set redrawtime=5000
set regexpengine=1
set expandtab
set noshowmode
set conceallevel=2
set fileencodings=utf-8
" Searching
set hlsearch
set incsearch
set ignorecase
set smartcase
if has('nvim')
set inccommand=split " enables interactive search and replace
endif
set foldmethod=expr
set foldexpr=nvim_treesitter#foldexpr()
set foldnestmax=10
set nofoldenable
set foldlevel=2
set nobackup
set nowritebackup
set noswapfile
set nonumber
set nornu
set showcmd
" enable splitright
set splitright
setlocal nobackup
setlocal nowritebackup
set nowritebackup
" You will have bad experience for diagnostic messages when it's default 4000.
set updatetime=300
" don't give |ins-completion-menu| messages.
set shortmess+=c
" always show signcolumns
set signcolumn=yes
" Use `[g` and `]g` to navigate diagnostics
" nmap <silent> [g <Plug>(coc-diagnostic-prev)
" nmap <silent> ]g <Plug>(coc-diagnostic-next)
" " Remap keys for gotos
" nmap <silent> gd <Plug>(coc-definition)
" nmap <silent> gs :call CocAction('jumpDefinition', 'vne')<CR>
" nmap <silent> gi <Plug>(coc-implementation)
" nmap <silent> gr <Plug>(coc-references)
" nmap <silent> <space>co :CocList outline<CR>
" nmap <silent> <space>cu :CocList output<CR>
" nmap <silent> <space>cd :CocList diagnostics<CR>
" nmap <silent> <space>cD :CocList --normal diagnostics<CR>
" Use <c-space> to trigger completion.
" if has('nvim')
" inoremap <silent><expr> <c-space> coc#refresh()
" else
" inoremap <silent><expr> <c-@> coc#refresh()
" endif
" inoremap <silent><expr> <C-n>
" \ coc#pum#visible() ? coc#pum#next(1) :
" \ CheckBackspace() ? "\<C-n>" :
" \ coc#refresh()
" inoremap <silent><expr> <C-j>
" \ coc#pum#visible() ? coc#pum#next(1) :
" \ CheckBackspace() ? "\<C-j>" :
" \ coc#refresh()
" inoremap <expr><C-k> coc#pum#visible() ? coc#pum#prev(1) : "\<C-k>"
" inoremap <expr><C-p> coc#pum#visible() ? coc#pum#prev(1) : "\<C-p>"
"
" " Make <CR> to accept selected completion item or notify coc.nvim to format
" " <C-g>u breaks current undo, please make your own choice.
" inoremap <silent><expr> <C-x> coc#pum#visible() ? coc#pum#confirm()
" \: "\<C-g>u\<CR>\<c-r>=coc#on_enter()\<CR>"
" " Show full message.ce mean coc-expand
" nmap <silent> <space>ce :call CocAction("diagnosticInfo")<cr>
" " List of yank
" nmap <silent> <space>cy :<C-u>CocList -N yank<cr>
" nmap <silent> <space>cY :<C-u>CocList --normal yank<cr>:set filetype=vim<cr>
" " quick fix
" nmap <silent> <space>cq <Plug>(coc-codeaction)
" vmap <silent> <space>cq <Plug>(coc-codeaction-selected)
" nmap <silent> <space>cf <Plug>(coc-format)
" vmap <silent> <space>cf <Plug>(coc-format-selected)
" " Add text object
" xmap if <Plug>(coc-funcobj-i)
" omap if <Plug>(coc-funcobj-i)
" xmap af <Plug>(coc-funcobj-a)
" omap af <Plug>(coc-funcobj-a)
"format json need jq command in system
" autocmd FileType json nnoremap <buffer> <leader>cf :%!jq '.'<cr>
" Symbol renaming.
" nmap <silent> <space>cn <Plug>(coc-rename)
" function! s:reload_coc_extension()
" if(&filetype == 'javascript')
" let l:result = CocAction('reloadExtension', 'coc-eslint')
" echo 'Reload coc-eslint with result='.l:result
" elseif(&filetype == 'typescript' || &filetype == 'typescriptreact')
" let l:result = CocAction('reloadExtension', 'coc-tsserver')
" echo 'Reload coc-typescript with result='.l:result
" elseif(&filetype == 'reason')
" let l:result = CocAction('reloadExtension', 'coc-reason')
" echo 'Reload coc-reason with result='.l:result
" elseif(&filetype == 'ruby')
" let l:result = CocAction('reloadExtension', 'coc-solargraph')
" echo 'Reload coc-solargraph with result='.l:result
" elseif(&filetype == 'java')
" call coc#rpc#notify('runCommand', ['java.clean.workspace'])
" let l:result = CocAction('reloadExtension', 'coc-java')
" echo 'Reload coc-java with result='.l:result
" else
" CocRestart
" endif
" endfunction
" nmap <silent> <space>cl :call <SID>reload_coc_extension()<CR>
" " Use K to show documentation in preview window
" nnoremap <silent> K :call <SID>show_documentation()<CR>
" function! s:show_documentation()
" if (index(['vim','help'], &filetype) >= 0)
" execute 'h '.expand('<cword>')
" else
" call CocAction('doHover')
" endif
" endfunction
" " Use <C-l> for trigger snippet expand.
" imap <C-l> <Plug>(coc-snippets-expand)
" " Use <C-j> for select text for visual placeholder of snippet.
" vmap <C-j> <Plug>(coc-snippets-select)
" " Use <C-j> for jump to next placeholder, it's default of coc.nvim
" let g:coc_snippet_next = '<c-j>'
" " Use <C-k> for jump to previous placeholder, it's default of coc.nvim
" let g:coc_snippet_prev = '<c-k>'
" " Use <C-j> for both expand and jump (make expand higher priority.)
" " imap <C-j> <Plug>(coc-snippets-expand-jump)
" === END COC config
" Auto format
" command! -nargs=0 Prettier :CocCommand prettier.forceFormatDocument
" autocmd VimEnter * if stridx(getcwd(), "peeba") >= 0 | let g:workspace='/peeba' | elseif stridx(getcwd(), "sourcecode") >= 0 | let g:workspace='/sourcecode' | else | let g:workspace='' | endif
" autocmd BufWritePre *.js,*.jsx,*.css,*.scss,*.less,*.ts,*.tsx if stridx(expand("%:p"), "node_modules") < 0 && stridx(expand("%:p"), "translations") < 0 && stridx(expand("%:p"), "taffi") < 0 | call CocAction('format') | endif
" autocmd BufWritePost *.js,*.jsx,*.css,*.scss,*.less,*.ts,*.tsx if stridx(expand("%:p"), "taffi") >= 0 | execute ':silent !yarn eslint --fix ' . expand('%') | endif
" autocmd BufWritePre *.re,*.res call CocAction('format')
" Quick escape
inoremap jk <ESC>
inoremap jj <ESC>
" Custom FZF for default search file
let $FZF_DEFAULT_COMMAND = 'rg --files --no-ignore-vcs --hidden'.
\' --glob !.git'.
\' --glob !node_modules'.
\' --glob !dist'.
\' --glob !target'.
\' --glob !bin'.
\' --glob !build'.
\' --glob "!*.cm*"'.
\' --glob "!*.reast"'.
\' --glob "!*.d"'.
\' --glob "!.cache"'.
\' --glob "!*.snap"'.
\' --glob "!*.class"'.
\' --glob "!*.bs.js"'.
\' --glob "!*.ast"'.
\' '
" If using macos please check with shortcut key. By default, ctr-space is
" switch between input source in mac
let $FZF_DEFAULT_OPTS='--bind '.
\ 'ctrl-space:toggle-out,'.
\ 'shift-tab:toggle-in,'.
\ 'ctrl-alt-j:preview-down,'.
\ 'ctrl-alt-k:preview-up,'.
\ 'alt-a:select-all,'.
\ 'alt-d:deselect-all'
let g:fzf_preview_window = &columns > 120 ? 'right:40%:wrap' : ''
autocmd VimResized * let g:fzf_preview_window = &columns > 120 ? 'right:40%:wrap' : ''
" Border style (rounded / sharp / horizontal)
let g:fzf_layout = { 'down': '40%' }
function! s:build_quickfix_list(lines)
call setqflist(map(copy(a:lines), '{ "filename": v:val }'))
copen
cc
endfunction
let g:fzf_action = {
\ 'ctrl-q': function('s:build_quickfix_list'),
\ 'ctrl-h': 'tab split',
\ 'ctrl-x': 'split',
\ 'ctrl-v': 'vsplit',
\ }
" Custom matching tag
let g:mta_use_matchparen_group = 1
"----- Add redirect output of command
" Ref: https://gist.github.com/romainl/eae0a260ab9c135390c30cd370c20cd7
function! Redir(cmd, rng, start, end)
for win in range(1, winnr('$'))
if getwinvar(win, 'scratch')
execute win . 'windo close'
endif
endfor
if a:cmd =~ '^!'
let cmd = a:cmd =~' %'
\ ? matchstr(substitute(a:cmd, ' %', ' ' . expand('%:p'), ''), '^!\zs.*')
\ : matchstr(a:cmd, '^!\zs.*')
if a:rng == 0
let output = systemlist(cmd)
else
let joined_lines = join(getline(a:start, a:end), '\n')
let cleaned_lines = substitute(shellescape(joined_lines), "'\\\\''", "\\\\'", 'g')
let output = systemlist(cmd . " <<< $" . cleaned_lines)
endif
else
redir => output
execute a:cmd
redir END
let output = split(output, "\n")
endif
vnew
let w:scratch = 1
setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile
call setline(1, output)
endfunction
command! -nargs=1 -complete=command -bar -range Redir silent call Redir(<q-args>, <range>, <line1>, <line2>)
"End custom redirect output
au FileType gitcommit set textwidth=0
au FileType markdown setl conceallevel=0
" Set background and colorscheme
set termguicolors
" Show menu and force user to select
set completeopt=menu,menuone,noselect
" set concellevel to make json looking right. Ref: https://www.reddit.com/r/neovim/comments/12l1zs0/why_are_quotes_only_showing_up_on_current_line_in/
set conceallevel=0
" choose color which from nvcode-color-schemes
colorscheme nightfox
" hi CocErrorSign cterm=bold,reverse ctermfg=160 ctermbg=230 guifg=White guibg=Red
" hi CocUnderlineError cterm=underline ctermfg=61 gui=undercurl guisp=Red
" hi link CocErrorHighlight CocUnderlineError
" hi MatchTag term=reverse cterm=reverse ctermfg=136 ctermbg=236 guibg=Yellow
" hi MatchParen ctermfg=yellow
" hi Search ctermfg=234 ctermbg=180 guifg=#1e1e1e guibg=#e5c07b
" hi Cursor ctermfg=234 ctermbg=white guifg=#1e1e1e guibg=#e5c07b
" hi CocMenuSel ctermbg=white guifg=#1e1e1e guibg=#e5c07b
hi Visual guibg=#445c80
" Fern color
hi link FernRootSymbol Title
hi link FernRootText Title
" Required for operations modifying multiple buffers like rename.
set hidden
" Save file as root
command! -nargs=0 Sw w !sudo tee % > /dev/null
" Multiple path for example: find ~/projects ~/Downloads -maxdepth 1 -type d
" Detect hightlight at cursor http://www.drchip.org/astronaut/vim/index.html#Maps
" customize function put to the end of the file to make sure treesitter work
let g:workspace = get(g:, 'workspace', '')
command! -nargs=* -complete=dir -bang Cd call
\ fzf#run(fzf#wrap(
\ {
\ 'source': join(['find ~/projects'.g:workspace, '-maxdepth 1 ','-type d'], ' '),
\ 'sink': 'cd',
\ 'options': [
\ '-q', len(<q-args>) > 0 ?(<q-args>): '',
\ '-1',
\ '--prompt', getcwd().">"]
\ } , <bang>0))
command! -nargs=* -complete=dir -bang TmuxLogs call
\ fzf#run(fzf#wrap(