-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfigs.vim
More file actions
888 lines (764 loc) · 34.8 KB
/
Copy pathconfigs.vim
File metadata and controls
888 lines (764 loc) · 34.8 KB
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
scriptencoding utf-8
" Chaves de API (Gemini/Claude, usadas por vim-ai-autocomplete e
" minuet-ai.nvim) -- um arquivo dedicado por provedor em ~/.config/<provedor>/
" (dir 0700, arquivo 0600), nao mais export no ~/.zsh_secrets (isso vazava a
" var pra TODO processo aberto naquele shell). `let $VAR = ...` seta a env
" var so no processo deste Vim -- e do Neovim tambem, ja que nvim/init.vim
" da `source ~/.vimrc`, entao um arquivo so cobre os dois lados.
function! s:LoadApiKeyFromConfig(env_var, path) abort
let full_path = expand(a:path)
if !filereadable(full_path)
return
endif
for line in readfile(full_path)
" stridx/slice em vez de split('=') -- split() quebra em TODA ocorrencia
" de '=', nao so a primeira, o que corromperia um valor que contenha
" '=' (ex: alguns tokens base64). Isolar so a primeira ocorrencia
" preserva o resto do valor intacto.
let eq_idx = stridx(line, '=')
if eq_idx ==# -1
continue
endif
let key = line[: eq_idx - 1]
let value = line[eq_idx + 1 :]
if key ==# a:env_var
execute 'let $' . a:env_var . ' = ' . string(value)
endif
endfor
endfunction
call s:LoadApiKeyFromConfig('GEMINI_API_KEY', '~/.config/gemini/vim-ai-autocomplete.env')
call s:LoadApiKeyFromConfig('ANTHROPIC_API_KEY', '~/.config/anthropic/vim-ai-autocomplete.env')
call s:LoadApiKeyFromConfig('DEEPSEEK_API_KEY', '~/.config/deepseek/vim-ai-autocomplete.env')
" Modelos do vim-ai-autocomplete (,pr cicla, :VimAiAutocompleteModel <nome>
" seleciona direto) -- nomes descritivos em vez do default generico
" 'gemini'/'claude'. claude-sonnet-5 e claude-haiku-4-5 confirmados como
" IDs validos via chamada real (2026-07-21 -- erro foi so credito de API
" zerado, nao "modelo desconhecido", que a API acusaria antes do billing).
" deepseek-v4-pro: substituiu o v4-flash em 2026-08-25 depois que o flash
" (sem thinking) se mostrou fraco em FIM nos testes manuais -- indentava
" errado, repetia o BEFORE, resposta de uma linha. O pro custa 3x ($0.66/M
" in, off-peak) e respondeu em 1.4-1.9s com thinking desligado (medido em
" chamada real). Se o pro tambem decepcionar, remover a familia do rodizio.
let g:vim_ai_autocomplete_models = [
\ {'name': 'gemini-flash', 'family': 'gemini', 'model_id': 'gemini-3.1-flash-lite', 'api_key_env': 'GEMINI_API_KEY'},
\ {'name': 'claude-sonnet', 'family': 'anthropic', 'model_id': 'claude-sonnet-5', 'api_key_env': 'ANTHROPIC_API_KEY'},
\ {'name': 'claude-haiku', 'family': 'anthropic', 'model_id': 'claude-haiku-4-5', 'api_key_env': 'ANTHROPIC_API_KEY'},
\ {'name': 'deepseek-pro', 'family': 'deepseek', 'model_id': 'deepseek-v4-pro', 'api_key_env': 'DEEPSEEK_API_KEY'},
\ ]
" Cycle through up to 3 alternative suggestions with <C-g>n / <C-g>p. Each
" alternative is one extra request, fetched only when asked for. The keys are
" deliberately NOT Alt ones: <M-.>/<M-,> used to be the defaults and cost the
" <Esc> itself -- claiming an <M-char> key makes ESC+char one key, and with
" "," being the leader here, <Esc> followed by the leader left Vim in insert
" mode (measured in a real pty on 2026-09-10, Neovim included).
let g:vim_ai_autocomplete_alternatives = 3
" No AI completion while writing prose: in markdown a suggestion is on screen
" almost all the time, which is noise rather than help. ,pt still turns it on
" by hand for the current buffer when a suggestion IS wanted there.
let g:vim_ai_autocomplete_disabled_filetypes = ['markdown']
" Highlight cursor line
set cursorline
" column with 90
highlight ColorColumn ctermbg=235 guibg=#2c2d27
let &colorcolumn="100,".join(range(100,999),",")
" No Neovim, termguicolors (ligado em vimrcs/filetypes.vim quando dentro do
" tmux) renderiza RGB exato — mais vibrante que a paleta 256 cores aproximada
" que o Vim usa. 'soft' suaviza o contraste/dureza do gruvbox pra compensar.
if has('nvim')
let g:gruvbox_contrast_dark = 'soft'
endif
" Default colorscheme
colorscheme gruvbox
set background=dark " Setting dark mode
"
" yank to clipboard
set clipboard=unnamed " copy to the system clipboard
" markdown previewr
nnoremap <leader>mdp :CocCommand markdown-preview-enhanced.openPreview<CR>
nnoremap <leader>mdt :CocCommand markdown-preview-enhanced.insertTable<CR>
nnoremap <leader>mdl :CocList --input=markdown-preview-enhanced. commands<CR>
" glow: preview estilo terminal (requer `glow` instalado).
" Sem -p (pager): o pager é interativo e não rola com os comandos normais do
" Vim (precisa mandar teclas pro próprio glow em modo terminal — confuso).
" Sem -p, o glow só imprime tudo e sai; o resultado fica como texto normal
" no buffer do terminal, rolável com <C-d>/<C-u>/gg/G depois de <C-\><C-n>
" (sair do modo terminal). -w 100: largura de quebra explícita, mesma do
" colorcolumn — evita quebra cedo demais mesmo com a metade da tela do vert.
nnoremap <leader>mg :vert term glow -w 100 %<CR>
" vim-markdown: conceal e frontmatter
let g:vim_markdown_conceal = 1
let g:vim_markdown_conceal_code_blocks = 0
let g:vim_markdown_frontmatter = 1
augroup ft_markdown
autocmd!
autocmd FileType markdown setlocal conceallevel=2
augroup END
" vim-table-mode: prefixo próprio (,M) — o padrão dele é ,tm, que colide com
" ,tm = :tabmove (vimrcs/options.vim). ,Mm liga/desliga o modo (realinha
" colunas sozinho ao digitar |); ,Mr realinha manualmente.
let g:table_mode_map_prefix = '<Leader>M'
"Sets numbers to be always shown
set number
" 1 tab == 2 spaces
set shiftwidth=2
set tabstop=2
set expandtab
set softtabstop=2
set smartindent
" Move vim tabs with ctrl+shift+arrow right or left (normal mode only)
nnoremap <C-S-h> :tabmove -1<cr>
nnoremap <C-S-l> :tabmove +1<cr>
"Git gutter
let g:gitgutter_enabled=1
" Display tabs and trailing spaces visually
set list listchars=tab:\ \ ,trail:·
" Navigate to previous tab
nnoremap gr :tabprev<CR>
" scrolling
set scrolloff=8 "Start scrolling when we're 8 lines away from margins
set sidescrolloff=15
set sidescroll=1
" Search highlight off by default, F3 (ou ,hs, pra teclado sem teclas F) to toggle
set nohlsearch
nnoremap <F3> :set hlsearch!<CR>
nnoremap <leader>hs :set hlsearch!<CR>
" Copy current filename relative to cwd (,cs — com vim-rooter, é relativo à
" raiz do projeto) and full absolute path (,cl) to clipboard
nnoremap <silent> <leader>cs :let @+=expand("%:.")<CR>:echo 'Copied: ' . expand('%:.')<CR>
nnoremap <silent> <leader>cl :let @+=expand("%:p")<CR>:echo 'Copied: ' . expand('%:p')<CR>
" =============================================================================
" Ruby & Rails Configuration
" =============================================================================
let g:ruby_host_prog = 'ruby'
" Vim test for Ruby
let test#ruby#rspec#executable = 'bundle exec rspec'
" =============================================================================
" Node.js, React & Web Configuration
" =============================================================================
" coc-tsserver handles JS/TS/JSX/TSX
" coc-emmet for fast HTML/JSX expansions
" Ensure JSX/TSX filetypes are recognized
augroup JsxTsxFiletypes
autocmd!
autocmd BufNewFile,BufRead *.jsx set filetype=javascriptreact
autocmd BufNewFile,BufRead *.tsx set filetype=typescriptreact
augroup end
" =============================================================================
" Database Configuration (vim-dadbod)
" =============================================================================
" Toggle DB UI explorer
nnoremap <silent> <leader>db :DBUIToggle<CR>
nnoremap <silent> <leader>dba :DBUIAddConnection<CR>
nnoremap <silent> <leader>dbf :DBUIFindBuffer<CR>
nnoremap <silent> <leader>dbr :DBUIRenameBuffer<CR>
" Save queries automatically
let g:db_ui_save_location = '~/.vim_runtime/db_queries'
let g:db_ui_use_nerd_fonts = 1
let g:db_ui_show_database_icon = 1
" dadbod-completion: enable in SQL and dadbod buffers
" (coc#config só existe com coc.nvim ativo — Vim; Neovim usa blink.cmp/lsp.lua)
augroup DadbodCompletion
autocmd!
if !has('nvim')
autocmd FileType sql,mysql,plsql call coc#config('suggest.autoTrigger', 'always')
endif
augroup end
" =============================================================================
" Elixir Configuration
" =============================================================================
" Use coc-elixir for LSP (already in coc_global_extensions)
" Syntax highlighting is handled by vim-elixir
" Configuring vim mix format
let g:mix_format_on_save = 1
nnoremap <Leader>mf :MixFormat<CR>
nnoremap <Leader>md :MixFormatDiff<CR>
" Vim test for Elixir
let test#elixir#exunit#executable = 'mix test'
let test#strategy = "vimux"
" Vimux: Utility mappings
nnoremap <Leader>vp :VimuxPromptCommand<CR>
nnoremap <Leader>vl :VimuxRunLastCommand<CR>
nnoremap <Leader>vq :VimuxCloseRunner<CR>
nnoremap <Leader>vx :VimuxInterruptRunner<CR>
" Elixir: Run Credo for strict linting
nnoremap <Leader>lc :call VimuxRunCommand("mix credo --strict")<CR>
" Elixir: Open IEx REPL in a split
nnoremap <Leader>ie :call VimuxRunCommand("iex -S mix")<CR>
" Elixir: Projectionist configurations (switching between lib and test)
let g:projectionist_heuristics = {
\ "mix.exs": {
\ "lib/*.ex": {"alternate": "test/{}_test.exs", "type": "source"},
\ "test/*_test.exs": {"alternate": "lib/{}.ex", "type": "test"},
\ "lib/*_web/controllers/*_controller.ex": {"alternate": "test/{}_web/controllers/{}_controller_test.exs", "type": "controller"},
\ "lib/*_web/live/*_live.ex": {"alternate": "test/{}_web/live/{}_live_test.exs", "type": "live"}
\ },
\ "Gemfile": {
\ "app/models/*.rb": {"alternate": "spec/models/{}_spec.rb", "type": "model"},
\ "app/controllers/*.rb": {"alternate": "spec/controllers/{}_spec.rb", "type": "controller"},
\ "app/helpers/*.rb": {"alternate": "spec/helpers/{}_spec.rb", "type": "helper"}
\ }}
" Elixir: Surround mappings for 'do ... end'
" Usage: 'ysiw d' to wrap a word in do/end
" =============================================================================
" vim-surround: pares customizados (visual: S<char> | normal: ysiw<char>)
" Chars reservados pelo plugin: b() B{} r[] a<> f/F função t/T tag s p :
" =============================================================================
" d → do/end (Elixir e Ruby — bloco com newlines)
let g:surround_100 = "do\n\r\nend"
" e → fn → end (Elixir — função anônima inline)
let g:surround_101 = "fn -> \r end"
" E → fn → end (Elixir — função anônima multilinha)
let g:surround_69 = "fn ->\n\r\nend"
" n → defmodule/do/end (Elixir — novo módulo)
let g:surround_110 = "defmodule \r do\nend"
" g → begin/end (Ruby — bloco de rescue/error handling)
let g:surround_103 = "begin\n\r\nend"
" = → <%= %> (Rails ERB — tag de output)
let g:surround_61 = "<%= \r %>"
" % → <% %> (Rails ERB — tag silenciosa)
let g:surround_37 = "<% \r %>"
" Auto-format Elixir files on save via mix format
augroup ElixirFormat
autocmd!
autocmd BufWritePre *.ex,*.exs,*.heex silent! call CocAction('format')
augroup end
" =============================================================================
" Test Runner (vim-test)
" =============================================================================
nmap <silent> <leader>tn :TestNearest<CR>
nmap <silent> <leader>tf :TestFile<CR>
nmap <silent> <leader>ts :TestSuite<CR>
nmap <silent> <leader>tl :TestLast<CR>
nmap <silent> <leader>tv :TestVisit<CR>
" Enable folding via CoC (much faster than indent)
set foldmethod=manual
set foldlevel=99
augroup coc_folding
autocmd!
if !has('nvim')
autocmd FileType typescript,json,javascript,python,go,elixir setl formatexpr=CocAction('formatSelected')
endif
augroup end
" =============================================================================
" CoC (Conquer of Completion) Configuration — Vim apenas.
" No Neovim, o LSP nativo (lsp.lua: mason + nvim-lspconfig + blink.cmp) cobre
" completion/gd/gr/K/rename/code action; ver ~/.claude/plans/squishy-crafting-clover.md.
" =============================================================================
if !has('nvim')
" Better performance for CoC
set updatetime=300
set shortmess+=c
set signcolumn=yes
" Tab/Enter for completion selection
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>"
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
" Ctrl+Space to trigger completion manually
inoremap <silent><expr> <c-space> coc#refresh()
" 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.
augroup CocHighlight
autocmd!
autocmd CursorHold * silent call CocActionAsync('highlight')
augroup end
" 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)
" 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')
" CoC float scroll — apenas insert/visual (<C-f>/<C-b> no normal mode vai pro fzf)
if has('patch-8.2.0750')
inoremap <silent><nowait><expr> <C-f> coc#float#has_scroll() ? "\<c-r>=coc#float#scroll(1)\<cr>" : "\<Right>"
inoremap <silent><nowait><expr> <C-b> coc#float#has_scroll() ? "\<c-r>=coc#float#scroll(0)\<cr>" : "\<Left>"
vnoremap <silent><nowait><expr> <C-f> coc#float#has_scroll() ? coc#float#scroll(1) : "\<C-f>"
vnoremap <silent><nowait><expr> <C-b> coc#float#has_scroll() ? coc#float#scroll(0) : "\<C-b>"
endif
" Add (Neo)Vim's native statusline support.
set statusline^=%{coc#status()}%{get(b:,'coc_current_function','')}
" Mappings for CoCList
nnoremap <silent><nowait> <space>a :<C-u>CocList diagnostics<cr>
" CoC references (,gr — gr sozinho mantém tabprev)
nmap <leader>gr <Plug>(coc-references)
" Jump to definition with Ctrl+] (LSP aware)
nmap <silent> <C-]> <Plug>(coc-definition)
" Jump back with Ctrl+t (Reverse jump)
nmap <silent> <C-t> <C-o>
" LSP navigation: gd=definition gy=type gi=implementation
nmap <silent> gd <Plug>(coc-definition)
nmap <silent> gy <Plug>(coc-type-definition)
nmap <silent> gi <Plug>(coc-implementation)
" Code actions: ,a (cursor) e visual ,a (selection)
nmap <leader>a <Plug>(coc-codeaction-cursor)
xmap <leader>a <Plug>(coc-codeaction-selected)
" Navegar entre diagnósticos: [g (anterior) e ]g (próximo)
nmap <silent> [g <Plug>(coc-diagnostic-prev)
nmap <silent> ]g <Plug>(coc-diagnostic-next)
" macOS specific shortcuts (Cmd+] and Cmd+[)
if has("mac") || has("macunix")
nmap <silent> <D-]> <Plug>(coc-definition)
nmap <silent> <D-[> <C-o>
endif
" Manage extensions.
nnoremap <silent><nowait> <space>e :<C-u>CocList extensions<cr>
" Show commands.
nnoremap <silent><nowait> <space>c :<C-u>CocList commands<cr>
" Find symbol of current document.
nnoremap <silent><nowait> <space>o :<C-u>CocList outline<cr>
" Search workspace symbols.
nnoremap <silent><nowait> <space>s :<C-u>CocList -I symbols<cr>
" Do default action for next item.
nnoremap <silent><nowait> <space>j :<C-u>CocNext<CR>
" Do default action for previous item.
nnoremap <silent><nowait> <space>k :<C-u>CocPrev<CR>
" Resume latest coc list.
nnoremap <silent><nowait> <space>p :<C-u>CocListResume<CR>
" coc-snippets: expand and jump
imap <C-j> <Plug>(coc-snippets-expand-jump)
endif " !has('nvim')
" Endwise: disable default mapping (coc handles insert-mode <CR>)
let g:endwise_no_mappings = 1
" Lista de extensions auto-instaladas pelo CoC em máquina nova.
" Sincronizada com ~/.config/coc/extensions/package.json em 2026-04-23,
" excluindo as banidas pela política (test/unit/variables.vader UT-052):
" coc-rome (deprecated), coc-java, coc-texlab, coc-powershell, coc-solargraph.
let g:coc_global_extensions = [
\ 'coc-browser',
\ 'coc-css',
\ 'coc-docker',
\ 'coc-elixir',
\ 'coc-emmet',
\ 'coc-eslint',
\ 'coc-git',
\ 'coc-go',
\ 'coc-html',
\ 'coc-json',
\ 'coc-markdown-preview-enhanced',
\ 'coc-markdownlint',
\ 'coc-prettier',
\ 'coc-pyright',
\ 'coc-sh',
\ 'coc-snippets',
\ 'coc-sql',
\ 'coc-stylelint',
\ 'coc-stylelintplus',
\ 'coc-tailwindcss',
\ 'coc-tsserver',
\ 'coc-webview',
\ 'coc-xml',
\ 'coc-yaml',
\ 'coc-yank'
\ ]
" =============================================================================
" Smart Open Pairs — não fecha quando há \w À DIREITA do cursor
" auto-pairs continua gerenciando: backspace, jump-over, espaço, Alt+e
" Estratégia: sobrescrever só os chars de abertura com <buffer>, disparando
" via InsertEnter DEPOIS do auto-pairs (que registrou o autocmd antes)
" =============================================================================
let g:AutoPairsShortcutToggle = '<C-p>'
" auto-pairs reconstrói o <CR> concatenando texto com o mapping que já
" existia (pra encadear com outros plugins de <CR>) — funciona com CoC (Vim,
" mapping em texto puro) mas quebra com blink.cmp (Neovim, mapping é uma
" referência Lua interna, não texto): a reconstrução vira lixo e insere o
" nome da função literalmente no buffer. No Neovim, blink.cmp já cuida do
" <CR> sozinho (aceita completion, senão quebra linha normal).
if has('nvim')
let g:AutoPairsMapCR = 0
endif
function! s:SmartPair(open, close) abort
let next = getline('.')[col('.')-1]
return next =~# '\w' ? a:open : a:open . a:close . "\<Left>"
endfunction
function! s:SmartQuote(char) abort
let next = getline('.')[col('.')-1]
if next =~# '\w' | return a:char
elseif next ==# a:char | return "\<Right>"
else | return a:char . a:char . "\<Left>"
endif
endfunction
function! s:ApplySmartOpenPairs() abort
inoremap <buffer> <expr> ( <SID>SmartPair('(', ')')
inoremap <buffer> <expr> [ <SID>SmartPair('[', ']')
inoremap <buffer> <expr> { <SID>SmartPair('{', '}')
inoremap <buffer> <expr> " <SID>SmartQuote('"')
inoremap <buffer> <expr> ' <SID>SmartQuote("'")
inoremap <buffer> <expr> ` <SID>SmartQuote('`')
endfunction
augroup SmartOpenPairs
autocmd!
autocmd VimEnter,BufEnter,InsertEnter * call s:ApplySmartOpenPairs()
augroup end
" =============================================================================
" fzf — Busca rápida de arquivos, buffers, texto (substitui CtrlP)
" =============================================================================
" Janela popup centralizada
let g:fzf_layout = { 'window': { 'width': 0.9, 'height': 0.8 } }
let g:fzf_preview_window = ['right:50%', 'ctrl-/']
let g:fzf_history_dir = '~/.local/share/fzf-history'
" ripgrep como backend de listagem de arquivos
if executable('rg')
let $FZF_DEFAULT_COMMAND = 'rg --files --hidden --follow --glob "!.git/*" --glob "!node_modules/*" --glob "!_build/*" --glob "!deps/*" --glob "!.elixir_ls/*"'
endif
nnoremap <C-f> :Files<CR>
nnoremap <C-b> :Buffers<CR>
nnoremap <leader>gf :GFiles<CR>
nnoremap <leader>rg :Rg<space>
nnoremap <leader>bl :BLines<CR>
nnoremap <leader>ht :History<CR>
" =============================================================================
" vim-projectionist — Alternância código<=>teste (:A) em Elixir e outros
" =============================================================================
" (g:projectionist_heuristics já definido na seção Elixir acima)
" =============================================================================
" vim-unimpaired — Navegação rápida de quickfix, location list, buffers
" =============================================================================
" [q / ]q → quickfix anterior/próximo
" [l / ]l → location list anterior/próximo
" [b / ]b → buffer anterior/próximo
" [n / ]n → conflito de merge anterior/próximo
" (sem configuração necessária — o plugin define tudo)
" =============================================================================
" Undotree — Histórico visual de undo
" =============================================================================
nnoremap <leader>u :UndotreeToggle<CR>
let g:undotree_WindowLayout = 2
let g:undotree_SetFocusWhenToggle = 1
" =============================================================================
" vim-obsession — Gerenciamento de sessões
" =============================================================================
" ,os → inicia/para tracking da sessão (salva Session.vim no CWD)
nnoremap <leader>os :Obsession<CR>
" Restaura sessão automaticamente se Session.vim existir no diretório atual
augroup obsession_restore
autocmd!
autocmd VimEnter * nested
\ if !argc() && empty(v:this_session) && filereadable('Session.vim') |
\ source Session.vim |
\ endif
augroup end
" =============================================================================
" vim-rooter — CD automático para a raiz do projeto
" =============================================================================
let g:rooter_patterns = ['.git', 'mix.exs', 'Gemfile', 'package.json',
\ 'pyproject.toml', 'setup.py', '.python-version', 'Cargo.toml']
let g:rooter_silent_chdir = 1
let g:rooter_resolve_links = 1
" =============================================================================
" GV.vim — Browser de git log
" =============================================================================
nnoremap <leader>gv :GV<CR>
nnoremap <leader>gV :GV!<CR>
" =============================================================================
" Git Messenger — popup com commit/autor da linha atual (,gm)
" =============================================================================
function! s:GitMessenger() abort
let l:line = line('.')
let l:file = expand('%')
if empty(l:file) || !filereadable(l:file)
return
endif
let l:blame = system(printf(
\ 'git blame -L %d,%d --porcelain %s 2>/dev/null',
\ l:line, l:line, shellescape(l:file)))
if v:shell_error
echo 'Não é um repositório git'
return
endif
let l:hash = matchstr(l:blame, '^[0-9a-f]\+')
if l:hash =~# '^0\+$'
echo 'Linha ainda não commitada'
return
endif
let l:msg = system(printf(
\ 'git log -1 --format="%%h %%s%%n%%nAuthor: %%an <%%ae>%%nDate: %%ad%%n%%n%%b" %s 2>/dev/null',
\ l:hash))
if has('popupwin')
call popup_atcursor(split(l:msg, "\n"),
\ {'border': [1,1,1,1], 'padding': [0,1,0,1], 'moved': 'any'})
else
echo l:msg
endif
endfunction
nmap <silent> <leader>gm :call <SID>GitMessenger()<CR>
" =============================================================================
" Undodir cleanup — remove arquivos de undo com mais de 90 dias
" =============================================================================
augroup UndoCleanup
autocmd!
autocmd VimEnter * silent! call timer_start(3000, {-> system(
\ 'find ' . expand('~/.vim_runtime/temp_dirs/undodir') . ' ' .
\ expand('~/.vim_runtime/temp_dirs/undodir-nvim') .
\ ' -type f -mtime +90 -delete 2>/dev/null &')})
augroup end
" =============================================================================
" Auto-save e trailing whitespace extra
" =============================================================================
" Salva todos os buffers ao perder o foco (saiu da janela/app)
augroup AutoSave
autocmd!
autocmd FocusLost * silent! wa
augroup end
" Extend trailing whitespace removal para Elixir, Ruby, TS, CSS
augroup ExtraCleanExtraSpaces
autocmd!
autocmd BufWritePre *.ex,*.exs,*.heex,*.rb,*.rake,*.erb,*.ts,*.tsx,*.css,*.scss
\ call CleanExtraSpaces()
augroup end
" =============================================================================
" Auto-reload — detecta mudanças feitas por agentes de IA (Claude Code, etc.)
" Requer tmux: set -g focus-events on (no ~/.tmux.conf)
" =============================================================================
augroup AgentAutoReload
autocmd!
autocmd FocusGained,BufEnter * silent! checktime
autocmd CursorHold * silent! checktime
augroup end
" Terminal sync — evita flickering com TUI apps (Claude Code) no :terminal
if exists('+termsync')
set termsync
endif
" =============================================================================
" vim-claude-code — Claude Code CLI integrado no Vim
" Toggle: Ctrl+\ | Prefix: ,c | Layout: split direito 40%
" =============================================================================
let g:claude_code_position = 'right'
let g:claude_code_split_ratio = 0.4
" Remove C-\ do tmux-navigator (conflita com Claude Code toggle)
nnoremap <silent> <c-\> <Nop>
" =============================================================================
" GitHub Copilot: removed for good (Alberto, 2026-09-02). Neither the native
" github/copilot.vim package nor copilot-chat.vim is part of this setup any
" more -- with copilot.vim merely installed in ~/.vim/pack, every Vim start
" (test runs included) spawned its language server through npx and prompted
" for the keychain. g:loaded_copilot stays as a tripwire: if the package ever
" comes back, it must not load.
let g:loaded_copilot = 1
" =============================================================================
" Startup screen — atalhos úteis ao abrir Vim sem argumentos
" =============================================================================
" Conteúdo puro (sem guard, sem tocar em buffer) — separado de s:StartScreen()
" só pra ser testável direto via function('<SNR>N_StartScreenLines').
function! s:StartScreenLines() abort
if has('nvim')
let lines = [
\ '',
\ ' Neovim ' . luaeval("vim.version().major..'.'..vim.version().minor..'.'..vim.version().patch") . ' — ,e editar configs.vim',
\ '',
\ ' BUSCA LSP (nativo)',
\ ' Ctrl+f Arquivos (fzf) K Documentação',
\ ' Ctrl+b Buffers gd Goto definition',
\ ' ,gf Git files ,rn Renomear símbolo (grn)',
\ ' ,rg Ripgrep (conteúdo) ,ca Code actions (gra)',
\ ' ,bl Linhas do buffer grr Referências',
\ ' ,ht Histórico ,fd Diagnósticos (Telescope)',
\ ' ,nn Neo-tree ,fs Document symbols',
\ ' ,fo Formatar buffer',
\ ' GIT TREESITTER',
\ ' ,gv Log do projeto af if Função (text object)',
\ ' ,gV Log do arquivo ac ic Classe (text object)',
\ ' ,gm Blame da linha',
\ ' ,d Toggle gitsigns DEBUG (DAP)',
\ ' ,gd Diffview ,dc Continue',
\ ' ,dt Toggle breakpoint',
\ ' NAVEGAÇÃO SESSÃO',
\ ' s Flash jump ,os Obsession on/off',
\ ' ,ha ,hh Harpoon ,u Undotree',
\ ' ,tt Trouble (diagnostics) :A Código <> Teste',
\ '',
\ ' Pressione qualquer tecla para começar...',
\ ]
else
let lines = [
\ '',
\ ' Vim ' . v:version/100 . '.' . v:version%100 . ' — ,e editar configs.vim',
\ '',
\ ' BUSCA LSP (CoC)',
\ ' Ctrl+f Arquivos (fzf) K Documentação',
\ ' Ctrl+b Buffers gd Goto definition',
\ ' ,gf Git files ,rn Renomear símbolo',
\ ' ,rg Ripgrep (conteúdo) ,a Code actions',
\ ' ,bl Linhas do buffer ,gr Referências',
\ ' ,ht Histórico [g ]g Diagnóstico prev/next',
\ ' ,nn NERDTree Space+a Todos diagnósticos',
\ ' Space+o Outline',
\ ' GIT :Format :OR',
\ ' ,gv Log do projeto',
\ ' ,gV Log do arquivo TESTES',
\ ' ,gm Blame da linha ,tn Mais próximo',
\ ' ,d Toggle gutter ,tf Arquivo',
\ ' ,ts Suíte',
\ ' IA',
\ ' Ctrl+\ Claude Code (toggle) SESSÃO',
\ ' ,ce Explicar seleção ,os Obsession on/off',
\ ' ,cf Corrigir código ,u Undotree',
\ ' ,cr Refatorar :A Código <> Teste',
\ '',
\ ' Pressione qualquer tecla para começar...',
\ ]
endif
return lines
endfunction
function! s:StartScreen() abort
" Não mostra se: abriu com arquivo, sessão restaurada, buffer já tem conteúdo,
" ou estamos rodando testes (Vader carregado via --cmd)
if argc() || !empty(v:this_session) || line('$') > 1 || getline(1) !=# ''
\ || exists(':Vader') || !empty(globpath(&runtimepath, 'plugin/vader.vim'))
return
endif
enew
setlocal bufhidden=wipe buftype=nofile nobuflisted nocursorline nocursorcolumn
setlocal noswapfile nomodifiable nonumber norelativenumber signcolumn=no
let lines = s:StartScreenLines()
" Centraliza verticalmente
let padding = (winheight(0) - len(lines)) / 2
let padded = repeat([''], max([0, padding])) + lines
setlocal modifiable
call setline(1, padded)
setlocal nomodifiable
" Enter/Space/q fecham a tela. Qualquer comando que abre um novo buffer
" (ex: Ctrl+f, ,nn, :e) substitui este — bufhidden=wipe limpa sozinho.
nnoremap <buffer><silent> <CR> :enew<CR>
nnoremap <buffer><silent> <Space> :enew<CR>
nnoremap <buffer><silent> q :enew<CR>
endfunction
augroup StartScreen
autocmd!
autocmd VimEnter * call s:StartScreen()
augroup end
" =============================================================================
" vim-which-key — popup de atalhos pendentes ao pressionar <Leader>. Vim
" apenas: o parser dele lê o texto de `:map` no formato clássico do Vim e
" não entende o formato novo do Neovim (keymaps Lua com callback + desc em
" linha separada) — quebra o popup inteiro. No Neovim, which-key.nvim (Lua,
" user/whichkey.lua) cobre o mesmo papel nativamente.
" =============================================================================
if !has('nvim')
let g:which_key_map = {}
let g:which_key_map.e = 'edit configs.vim'
let g:which_key_map.l = 'next buffer'
let g:which_key_map.h = 'previous buffer'
let g:which_key_map.u = 'undotree toggle'
let g:which_key_map.z = 'goyo (zen mode)'
let g:which_key_map.d = 'gitgutter toggle'
let g:which_key_map.q = 'scratch buffer (~/buffer)'
let g:which_key_map.x = 'scratch markdown (~/buffer.md)'
let g:which_key_map.cd = 'cd to file dir'
let g:which_key_map.pp = 'toggle paste mode'
let g:which_key_map.pt = 'vim-ai-autocomplete: toggle auto-trigger'
let g:which_key_map.pr = 'vim-ai-autocomplete: next model'
let g:which_key_map.pm = 'vim-ai-autocomplete: pick model (menu)'
let g:which_key_map.os = 'Obsession (session record)'
let g:which_key_map.mg = 'glow preview (term)'
let g:which_key_map.rg = 'Rg search'
let g:which_key_map.gv = 'GV log'
let g:which_key_map.gV = 'GV! (current file)'
let g:which_key_map.b = {
\ 'name' : '+buffer/tab',
\ 'd' : 'close buffer + tab',
\ 'a' : 'close all buffers',
\ 'l' : 'BLines (fzf)',
\ }
let g:which_key_map.t = {
\ 'name' : '+tab',
\ 'n' : 'new tab',
\ 'o' : 'tab only',
\ 'c' : 'close tab',
\ 'm' : 'move tab',
\ 'e' : 'tabedit here',
\ }
let g:which_key_map.s = {
\ 'name' : '+spell',
\ 's' : 'toggle spell',
\ 'n' : 'next misspelling',
\ 'p' : 'prev misspelling',
\ 'a' : 'add to dict',
\ '?' : 'suggest',
\ }
let g:which_key_map.n = {
\ 'name' : '+nerdtree',
\ 'n' : 'toggle',
\ 'b' : 'from bookmark',
\ 'f' : 'find current file',
\ }
let g:which_key_map.g = {
\ 'name' : '+git/fzf',
\ 'f' : 'GFiles',
\ }
let g:which_key_map.c = {
\ 'name' : '+copy',
\ 's' : 'copy filename',
\ 'l' : 'copy full path',
\ }
let g:which_key_map.db = {
\ 'name' : '+dadbod-ui',
\ '' : 'toggle',
\ 'a' : 'add connection',
\ 'f' : 'find buffer',
\ 'r' : 'rename buffer',
\ }
let g:which_key_map.md = {
\ 'name' : '+markdown preview / mix format diff',
\ 'p' : 'md preview: open',
\ 't' : 'md preview: insert table',
\ 'l' : 'md preview: commands list',
\ }
let g:which_key_map.v = {
\ 'name' : '+vimux',
\ 'p' : 'prompt command',
\ 'l' : 'run last command',
\ 'q' : 'close runner',
\ 'x' : 'interrupt runner',
\ }
let g:which_key_map.i = { 'e' : 'IEx REPL (vimux)' }
let g:which_key_map.mf = 'mix format'
call which_key#register(',', 'g:which_key_map')
nnoremap <silent> <leader> :<C-u>WhichKey ','<CR>
vnoremap <silent> <leader> :<C-u>WhichKeyVisual ','<CR>
" Nota: <leader>md (mix format diff, configs.vim:120) e <leader>mdp/mdt/mdl
" (markdown preview, configs.vim:17-19) compartilham o prefixo "md" — mapping
" real do Vim já resolve isso via timeoutlen (funciona desde antes deste
" plugin); o which-key só documenta o grupo, não redefine as teclas.
endif " !has('nvim')
" =============================================================================
" Customizações LOCAIS (não-versionadas)
" -----------------------------------------------------------------------------
" Última camada da cadeia de carregamento: roda DEPOIS de tudo neste arquivo,
" então vence options e mappings definidos acima (exceto mappings que algum
" plugin/*.vim reescreve depois do vimrc — caso raro).
"
" Carrega, se existirem:
" ~/.vim_runtime/my_configs.vim — arquivo único
" ~/.vim_runtime/my_configs/*.vim — vários arquivos (carregados em ordem)
"
" Ambos são gitignored. Comece copiando o exemplo:
" cp ~/.vim_runtime/my_configs.vim.example ~/.vim_runtime/my_configs.vim
" Veja esse .example para o guia "fica local vs. abre PR".
" =============================================================================
for s:local_cfg in [expand('~/.vim_runtime/my_configs.vim')]
\ + sort(glob('~/.vim_runtime/my_configs/*.vim', 0, 1))
if filereadable(s:local_cfg)
execute 'source' fnameescape(s:local_cfg)
endif
endfor
unlet! s:local_cfg