-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.lua
1223 lines (1034 loc) · 38.7 KB
/
init.lua
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
-- /// Utilities ///
-- Taken from https://oroques.dev/notes/neovim-init
function map(mode, lhs, rhs, opts)
local options = {noremap = true}
if opts then options = vim.tbl_extend('force', options, opts) end
vim.api.nvim_set_keymap(mode, lhs, rhs, options)
end
-- Debug print a lua datastructure
function dump(o)
if type(o) == 'table' then
local s = '{ '
for k,v in pairs(o) do
if type(k) ~= 'number' then k = '"'..tostring(k)..'"' end
s = s .. '['..tostring(k)..'] = ' .. dump(v) .. ','
end
return s .. '} '
else
return tostring(o)
end
end
-- /// Plugin Management ///
local ensure_packer = function()
local fn = vim.fn
local install_path = fn.stdpath('data')..'/site/pack/packer/start/packer.nvim'
if fn.empty(fn.glob(install_path)) > 0 then
fn.system({'git', 'clone', '--depth', '1', 'https://github.com/wbthomason/packer.nvim', install_path})
vim.cmd [[packadd packer.nvim]]
return true
end
return false
end
local packer_bootstrap = ensure_packer()
local function notInGoogle3()
print(string.find(vim.fn.getcwd(), '/google/src') == nil)
return string.find(vim.fn.getcwd(), '/google/src') == nil
end
local not_in_google3 = string.find(vim.fn.getcwd(), '/google/src') == nil
require('packer').startup(function(use)
use 'wbthomason/packer.nvim'
-- use 'danth/pathfinder.vim';
use 'eandrju/cellular-automaton.nvim';
use 'yuttie/comfortable-motion.vim';
use 'ggvgc/vim-fuzzysearch';
use 'AndrewRadev/splitjoin.vim';
-- Automatically delete extra characters (like quotes) when joining lines.
use 'flwyd/vim-conjoin';
-- Automatically set tabstop/shiftwidth based on current file or nearby files.
use 'tpope/vim-sleuth';
-- Change cases using e.g. cru for upper case.
use 'tpope/vim-abolish';
use 'kylechui/nvim-surround';
use 'tpope/vim-repeat';
use 'windwp/nvim-autopairs';
-- Automatically align code.
use 'junegunn/vim-easy-align';
-- Highlight current word with cursor on it across whole buffer.
use 'RRethy/vim-illuminate';
-- Animates window resizing.
use 'camspiers/animate.vim';
use 'lukas-reineke/indent-blankline.nvim';
-- Add scrollbars.
use { 'dstein64/nvim-scrollview', branch = 'main' };
use 'vim-airline/vim-airline';
-- Persist settings between sessions
use 'zhimsel/vim-stay';
-- Better directory browsing. Access the directory the current file is in with
-- the - key.
use 'stevearc/oil.nvim';
use 'tpope/vim-eunuch';
-- Make it so that when a buffer is deleted, the window stays.
use 'qpkorr/vim-bufkill';
use 'kana/vim-altr';
-- Open files at specified lines using file:line syntax.
use 'wsdjeg/vim-fetch';
use {'junegunn/fzf', run = vim.fn['fzf#install']};
use { 'junegunn/fzf.vim' };
use 'pbogut/fzf-mru.vim';
use 'ludovicchabant/vim-lawrencium';
use 'mhinz/vim-signify';
use {'rafamadriz/friendly-snippets'};
use {'hrsh7th/cmp-buffer'};
use {'hrsh7th/cmp-cmdline'};
use {'hrsh7th/cmp-emoji'};
use {'hrsh7th/cmp-calc'};
use {'hrsh7th/cmp-path'};
use {'hrsh7th/cmp-nvim-lua'};
use {'f3fora/cmp-spell'};
use {'hrsh7th/cmp-nvim-lsp'};
use 'L3MON4D3/LuaSnip';
use 'saadparwaiz1/cmp_luasnip';
use {'hrsh7th/nvim-cmp'};
use {'nvim-treesitter/nvim-treesitter', run = ':TSUpdate'};
use 'nvim-treesitter/nvim-treesitter-textobjects';
use 'nvim-treesitter/nvim-treesitter-context';
use 'nvim-treesitter/playground';
use 'p00f/nvim-ts-rainbow';
use { 'neovim/nvim-lspconfig', run = install_python_ls };
use 'nvim-lua/lsp-status.nvim';
use 'mgedmin/python-imports.vim';
use 'Olical/conjure';
use 'gpanders/nvim-parinfer';
use 'mechatroner/rainbow_csv';
use 'masukomi/vim-markdown-folding';
use 'ron89/thesaurus_query.vim';
use 'tikhomirov/vim-glsl';
use 'dart-lang/dart-vim-plugin';
-- Attmpts to make vim better when reading terminal data from kitty
-- TODO FIX
use 'rkitover/vimpager';
use 'habamax/vim-godot';
use 'dhruvasagar/vim-table-mode';
use 'whonore/vim-sentencer';
use 'ruanyl/vim-gh-line';
use 'ggandor/leap.nvim';
use 'guns/vim-sexp';
use 'romainl/vim-cool';
use 'echasnovski/mini.nvim';
use 'lewis6991/whatthejump.nvim';
use {'gen740/SmoothCursor.nvim',
config = function() require('smoothcursor').setup({cursor = ">",
linehl = "CursorLine",
texthl = "CursorLine"}) end}
if vim.fn.filereadable(vim.fn.expand('~/google_dotfiles/google.lua')) ~= 0 then
require('google_dotfiles/google').load_google_plugins(use)
-- else
-- TODO find a way to put the codefmt lines here so that I can source
-- google.vim in my google-specific config.
end
use {'google/vim-maktaba'};
use {'google/vim-codefmt'};
-- Automatically set up your configuration after cloning packer.nvim
-- Put this at the end after all plugins
if packer_bootstrap then
require('packer').sync()
end
end)
-- /// General ///
vim.g.maplocalleader=" "
-- /// Right Click Menu ///
vim.cmd('nnoremenu PopUp.Rain <Cmd>CellularAutomaton make_it_rain<CR>')
-- /// Navigation ///
require('leap').set_default_keymaps()
-- Jump backwards
vim.keymap.set('n', '<C-p>', function()
require 'whatthejump'.show_jumps(false)
return '<C-o>'
end, {expr = true})
-- Jump forwards
vim.keymap.set('n', '<C-d>', function()
require 'whatthejump'.show_jumps(true)
return '<C-i>'
end, {expr = true})
-- Nicer up/down movement on long lines.
map('n', 'j', 'gj')
map('n', 'k', 'gk')
-- Smooth scrolling
vim.g.comfortable_motion_no_default_key_mappings = true
map('n', '<PageDown>', ':call comfortable_motion#flick(50)<CR>10j', { silent = true })
map('n', '<PageUp>', ':call comfortable_motion#flick(-50)<CR>10k', { silent = true })
map('v', '<PageDown>', '10jzz', { silent = true })
map('v', '<PageUp>', '10kzz', { silent = true })
-- Hit escape twice to clear old search highlighting. vim-cool kinda makes
-- this obselete.
map('n', '<Esc><Esc>', ':let @/=""<CR>', {silent = true})
vim.g.CoolTotalMatches = true
map('n', '<localleader>pe', ':PathfinderExplain<CR>')
vim.g.pf_autorun_delay = 1
-- /// Editing and Formatting ///
-- Use "gm" to duplicate lines (faster than copy/pasting).
require('mini.operators').setup({})
-- Rename word and prime to replace other occurances
-- Can also search for something then use 'cgn' to "change next searched occurance".
map('v', '//', [[y/\V<C-R>=escape(@",'/\')<CR><CR>]])
map('n', 'ct', '*Ncw<C-r>"')
map('n', 'cT', '*Ncw')
-- Make U redo
map('n', 'U', '<C-r>')
-- Rename word across file
map('n', 'cW', ':%s/\\<<C-r><C-w>\\>/')
-- Transform single line code blocks to multi-line ones and vice-versa.
vim.g.splitjoin_split_mapping = ''
vim.g.splitjoin_join_mapping = ''
map('n', 'SJ', ':SplitjoinJoin<cr>')
map('n', 'SS', ':SplitjoinSplit<cr>')
-- Delete until the next 'closing' character (quote or brace)
map('n', "d'", 'd/[\\]\\}\\)\'"]<CR>:let @/ = ""<CR>')
-- Keep visual selection when indenting or dedenting.
-- https://superuser.com/questions/310417/how-to-keep-in-visual-mode-after-identing-by-shift-in-vim
map('v', '<', '<gv')
map('v', '>', '>gv')
-- False to play nicely with parinfer, see
-- https://github.com/eraserhd/parinfer-rust/issues/136
vim.wo.linebreak = false
vim.o.textwidth = 79
vim.bo.wrapmargin = 0
vim.bo.formatoptions = 'jcroql'
-- Make new lines indent automatically.
vim.bo.autoindent = true
-- Reformat paragraphs when typing anywhere in them (not just when adding to
-- their end).
-- vim.cmd("command AutoWrapToggle if &fo =~ 'a' | set fo-=a | else | set fo+=a | endif")
-- map('n', '<C-a>', ':AutoWrapToggle<CR>')
-- Note that this command imports all ftplugin files, which may have unindended
-- effects.
vim.cmd('filetype plugin indent on')
-- Make tabs create 2 spaces by default. Note that this is overwritten by
-- vim-sleuth and ftplugin files.
vim.o.tabstop = 2
vim.o.shiftwidth = 2
vim.o.expandtab = true
-- Command to trim all trailing whitespace in the file.
vim.cmd(
[[
function! TrimWhitespace()
let l:save = winsaveview()
%s/\s\+$//e
call winrestview(l:save)
endfunction
command! TrimWhitespace call TrimWhitespace()
]]
)
-- Repeatable hotkeys to surround text objects with quotes/parens/etc.
require("nvim-surround").setup({
keymaps = { -- vim-surround style keymaps
visual = "F",
},
})
-- Automatically close parens.
local npairs = require('nvim-autopairs')
npairs.setup({
disable_filetype = { "TelescopePrompt" , "clojure" },
})
-- /// Visuals ///
require('illuminate').configure()
-- Show tabs as actual characters.
vim.wo.list = true
vim.wo.listchars = 'tab:>-'
-- My custom colorscheme defined in ~/.vim/colors.
vim.cmd('colorscheme terminal')
vim.o.termguicolors = false
vim.o.background = 'dark'
-- Function to determine the highlight group under the cursor (to help change
-- its color).
vim.cmd(
[[
function! SynGroup()
let l:s = synID(line('.'), col('.'), 1)
echo synIDattr(l:s, 'name') . ' -> ' . synIDattr(synIDtrans(l:s), 'name')
endfun
command! SynGroup call SynGroup()
]]
)
-- Highlights the line the cursor is currently on.
vim.wo.cursorline = true
-- Creates a line to show the max desired line length.
vim.wo.colorcolumn = '+1'
-- Makes vim faster when making new lines after long lines by preventing syntax
-- highlighting after a certain width.
vim.o.synmaxcol = 2000
-- Show relative line numbers on left side of buffer.
vim.wo.number = true
vim.wo.relativenumber = true
-- Adds indentation line hints.
require('ibl').setup{
indent = {char = "¦"},
}
-- Syntax highlighting for specific filetypes
vim.cmd(
[[
au BufRead,BufNewFile *.blueprint set filetype=gcl
]]
)
-- /// User Interface ///
-- Allow mouse usage in the terminal.
vim.o.mouse = 'a'
-- Set title of (e.g. X11) window vim is in. See :h statusline for info about
-- how to customize this.
vim.o.title = true
vim.o.titlestring = "%t (%{expand('%:~:.:h')}) - NVIM"
-- Add bottom bar with various info.
-- Uncomment to get top bar with all buffer names.
-- let g:airline#extensions#tabline#enabled = 1
-- Last section determines the max width for different parts of the bottom bar.
-- See https://github.com/vim-airline/vim-airline/issues/694 for some
-- explanation.
vim.cmd(
[[
let g:airline#extensions#branch#enabled = 1
let g:airline#extensions#branch#displayed_head_limit = 15
let g:airline#extensions#ale#enabled = 1
let g:airline#extensions#default#section_truncate_width = { 'a': 40, 'b': 40, 'c': 50, 'x': 110, 'y': 110, 'z': 110, }
]]
)
-- Theme located in ~/.vim/autoload/airline/themes/terminal.vim.
vim.g.airline_theme = 'terminal'
-- Use :help statusline for customization options here.
vim.g.airline_section_c = '%f%m'
-- Remove the last bottom bar section.
vim.g.airline_section_z = ''
-- Use the system clipboard for everything by default. See
-- https://vi.stackexchange.com/questions/84/how-can-i-copy-text-to-the-system-clipboard-from-vim.
vim.o.clipboard = 'unnamedplus'
-- Copy filename of current buffer to clipboard
map('n', 'yf', ':let @+ = expand("%:p")<CR>')
-- Copy filename of current buffer in relref format to clipboard (to make
-- personal website writing easier).
-- TODO add this to a local vimrc file in the website directory, once I find a
-- clean way to do that.
map('n', 'yl',
':let @+ = \'{{< relref "\' .. substitute(expand("%:p"), "/home/kovas/website/content", "", "") .. \'\" >}}\'<CR>')
-- stay/view will annoyingly remember to change working dirs when opening files
-- sometimes, this should prevent that
vim.o.autochdir = false
-- For some unknown reason, on some machines the oil config gets overwritten by
-- a startup script. So I load it last here with a VimEnter autocommand to
-- make sure this is the config I end up with.
vim.api.nvim_create_autocmd({"VimEnter"}, {
callback = function()
require("oil").setup({
default_file_explorer = true,
prompt_save_on_select_new_entry = false,
skip_confirm_for_simple_edits = true,
keymaps = {
["<CR>"] = "actions.select",
["<C-l>"] = "actions.refresh",
["g?"] = "actions.show_help",
-- These conflict with my custom mappings for all buffer types
["<C-p>"] = false,
["<C-s>"] = false,
},
use_default_keymaps = false,
})
end,
})
vim.keymap.set("n", "-", require("oil").open, { desc = "Open parent directory" })
map('n', 'm', ':wincmd W<CR>')
map('n', 'M', ':wincmd w<CR>')
-- "Chrome-like" mappings
map('n', '<C-l>', ':')
-- Make vertical split with ctrl-t, moving the next split.
map('n', '<C-t>', ':vsplit | wincmd w<CR>')
-- Gets number of windows that are not floating (actually show buffer contents).
local function get_num_windows()
local count = 0
-- print(dump(vim.api.nvim_tabpage_list_wins(0)))
for _, winnr in pairs(vim.api.nvim_list_wins()) do
local cfg = vim.api.nvim_win_get_config(winnr)
local bufnr = vim.api.nvim_win_get_buf(winnr)
local ft = vim.api.nvim_buf_get_option(bufnr, "filetype")
if cfg.focusable then
-- print(dump(cfg))
-- print(ft)
-- print(vim.api.nvim_buf_get_name(bufnr))
count = count + 1
end
end
return count
end
-- When this is equal to 1, then some extra C-w bindings are created that make
-- my custom C-w slow. See
-- https://github.com/dstein64/nvim-scrollview/blob/d03d1e305306b8b6927d63182384be0831fa3831/plugin/scrollview.vim#L164.
vim.g.scrollview_auto_workarounds = 0
-- Close windows, then the whole session, with C-w
vim.keymap.set("n", "<C-w>", function()
local win_amount = get_num_windows()
if win_amount == 1 then
vim.cmd(':wqa<CR>')
else
vim.cmd('wincmd q')
end
end,
{noremap = true,
nowait = true})
-- Do this automatically when the vim window is resized.
vim.cmd('autocmd VimResized * wincmd =')
-- /// Buffers and Files ///
-- Switch between buffers without saving.
vim.o.hidden = true
-- Do not automatically reload files if working on Google code, otherwise read
-- files automatically if they change.
if not_in_google3 then
vim.o.autoread = true
-- Trigger `autoread` when files changes on disk
-- https://unix.stackexchange.com/questions/149209/refresh-changed-content-of-file-opened-in-vim/383044#383044
-- https://vi.stackexchange.com/questions/13692/prevent-focusgained-autocmd-running-in-command-line-editing-mode
vim.cmd('autocmd FocusGained,BufEnter,CursorHold,CursorHoldI * if !bufexists("[Command Line]") | checktime | endif')
-- Notification after file change
-- https://vi.stackexchange.com/questions/13091/autocmd-event-for-autoread
vim.cmd('autocmd FileChangedShellPost * echohl WarningMsg | echo "File changed on disk. Buffer reloaded." | echohl None')
else
vim.o.autoread = false
end
-- Switch between h/cc files (and other related files) with alt-shift-h/l.
map('n', '<A-L>', '<Plug>(altr-forward)')
map('n', '<A-H>', '<Plug>(altr-back)')
-- Goes to current filename string in the current directory's BUILD file.
map('n', 'gb', ":execute 'e +/' . escape(escape(expand('%:t'), '.'), '.') . ' %:h/BUILD'<CR>")
-- Create directories on write if they don't already exist.
-- See also https://github.com/pbrisbin/vim-mkdir
vim.cmd(
[[
function g: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 g:MkNonExDir(expand('<afile>'), +expand('<abuf>'))
augroup END
]]
)
-- Save all buffers with ctrl-s.
map('n', '<C-S>', ':wa<CR>')
-- /// Searching ///
-- map('n', '<space>', ':FuzzySearch<CR>')
vim.g.fzf_history_dir = '~/.local/share/fzf-history'
-- Search in files starting from directory with current buffer and working way
-- up with a maximum of 100 files using the , key.
-- vim.cmd(
-- [[
-- let g:types = { 'dict': type({}), 'funcref': type(function('call')), 'string': type(''), 'list': type([]) }
-- function! g:Warn(message)
-- echohl WarningMsg
-- echom a:message
-- echohl None
-- return 0
-- endfunction
-- function! g:Myag(query, ...)
-- if type(a:query) != g:types.string
-- return g:Warn('Invalid query argument')
-- endif
-- let query = empty(a:query) ? '^(?=.)' : a:query
-- let args = copy(a:000)
-- let ag_opts = len(args) > 1 && type(args[0]) == g:types.string ? remove(args, 0) : ''
-- let command = ag_opts . ' ' . fzf#shellescape(query) . ' ' .
-- \ printf('$(find_up.bash %s -type f | head -n 100)',
-- \ expand('%:h'))
-- return call('fzf#vim#ag_raw', insert(args, command, 0))
-- endfunction
-- command! -bang -nargs=* MyAg call g:Myag(<q-args>, <bang>0)
-- ]]
-- )
-- map('n', ',', ':MyAg ')
-- Search through all files in the current buffer's directory with " when in a
-- oil directory buffer.
vim.cmd(
[[
function! g:Dirag(query, ...)
if type(a:query) != type('')
return g:Warn('Invalid query argument')
endif
let query = empty(a:query) ? '^(?=.)' : a:query
let args = copy(a:000)
let ag_opts = len(args) > 1 && type(args[0]) == type('') ? remove(args, 0) : ''
let directory = substitute(expand('%:h'), 'oil:\/\/', '', '')
let command = ag_opts . ' -a ' . fzf#shellescape(query) . ' ' . directory
return call('fzf#vim#ag_raw', insert(args, command, 0))
endfunction
command! -bang -nargs=* DirAg call g:Dirag(<q-args>, {'options': '--delimiter : --nth 4..'}, <bang>0)
autocmd FileType oil nnoremap <buffer> ? :DirAg<CR>
]]
)
-- Search in all buffer lines.
map('n', '?', ':Lines<CR>')
-- Search through most recently used files with the ' key.
vim.g.fzf_mru_max = 1000000
-- This is used instead of 'google3' because when fig uses vimdiff it puts the
-- vim instance at the root of the CitC client (the dir _containing_ google3).
vim.g.fzf_mru_store_relative_dirs = {'/google/src/cloud/'}
-- Exclude files with google3/ in them - these will be opened only when things are
-- merged via vimdiff.
vim.g.fzf_mru_exclude = '/tmp/\\|google3/'
-- Make a separate function here to avoid the "press enter to continue" prompts
-- vim uses when the command line exceeds the size of the command window. The
-- separate function does not show the FZFMru command in the window.
vim.api.nvim_create_user_command('MRU', function()
vim.cmd ":FZFMru -m -x --no-sort --tiebreak=index --nth=-1,.. --delimiter=/ --preview 'batcat --color=always --style=plain --theme=base16 {}'"
end,
{nargs = 0, desc = 'Find most recently used files.'}
)
map('n', "'", ":MRU<CR>")
-- The '10000 part of this will make it so that 1000 oldfiles are remembered (the
-- last 10000 files will be available with the FZFMru command)
vim.o.shada = "!,'10000,<50,s10,h"
-- /// Version Control ///
vim.g.signify_realtime = true
vim.g.signify_cursorhold_insert = false
vim.g.signify_cursorhold_normal = false
-- Go back and forth in history with ]r or [r.
-- taken from https://github.com/mhinz/vim-signify/issues/284
vim.g.target_commit = 0
vim.cmd(
[[
function ChangeTargetCommit(older_or_younger)
if a:older_or_younger ==# 'older'
let g:target_commit += 1
elseif g:target_commit==#0
echom 'No timetravel! Cannot diff against HEAD~-1'
return
else
let g:target_commit -= 1
endif
let g:signify_vcs_cmds.git = printf('%s%d%s', 'git diff --no-color --no-ext-diff -U0 HEAD~', g:target_commit, ' -- %f')
let g:signify_vcs_cmds.hg = printf('%s%d%s', 'hg diff --config extensions.color=! --config defaults.diff= --nodates -U0 --rev .~', g:target_commit, ' -- %f')
let g:signify_vcs_cmds_diffmode.hg = printf('%s%d %s', 'hg cat --rev .~', g:target_commit, '%f')
let l:cur_rev_cmd = printf('hg log --rev .~%d --template ''{node|short} {fill(desc, "50")|firstline}\n''', g:target_commit)
let l:cur_rev = system(l:cur_rev_cmd)
let l:output_msg = printf('%s%d %s', 'Now diffing against HEAD~', g:target_commit, l:cur_rev)
echom l:output_msg
:SignifyRefresh
endfunction
]]
)
vim.cmd("command! SignifyOlder call ChangeTargetCommit('older')")
vim.cmd("command! SignifyNewer call ChangeTargetCommit('younger')")
map('n', ']r', ':SignifyOlder<CR>')
map('n', '[r', ':SignifyNewer<CR>')
-- TODO Add this for git too.
vim.cmd(
[[
function HgDiffTarget()
let l:cur_rev_cmd = printf('hg log --rev .~%d --template ''{node}''', g:target_commit)
let l:cur_rev = system(l:cur_rev_cmd)
execute 'Hgvdiff' l:cur_rev
endfunction
command! HgDiffTargetCmd call HgDiffTarget()
]]
)
-- /// Diffing ///
-- Make obtain/put commands in diff mode auto jump to the next change.
map('n', 'do', 'do]c')
map('n', 'dp', 'dp]c')
-- Get diff between current buffer and what is saved to disk using the
-- DiffSaved command.
vim.cmd(
[[
function! g:DiffWithSaved()
let filetype=&ft
diffthis
vnew | r # | normal! 1Gdd
diffthis
exe "setlocal bt=nofile bh=wipe nobl noswf ro ft=" . filetype
endfunction
com! DiffSaved call g:DiffWithSaved()
]]
)
-- /// Completion and Snippets ///
-- Setup nvim-cmp.
local cmp = require'cmp'
local has_words_before = function()
local line, col = unpack(vim.api.nvim_win_get_cursor(0))
return col ~= 0 and vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]:sub(col, col):match("%s") == nil
end
local source_names = {
nvim_lsp = "(LSP)",
emoji = "(Emoji)",
path = "(Path)",
calc = "(Calc)",
cmp_tabnine = "(Tabnine)",
luasnip = "(Snippet)",
buffer = "(Buffer)",
tmux = "(TMUX)",
nvim_ciderlsp = "(ML-Autocompletion!)"
}
local luasnip = require("luasnip")
require("luasnip.loaders.from_vscode").lazy_load()
require("luasnip.loaders.from_snipmate").lazy_load()
cmp.setup({
snippet = {
expand = function(args)
luasnip.lsp_expand(args.body)
end,
},
mapping = {
['<C-d>'] = cmp.mapping.scroll_docs(-4),
['<C-f>'] = cmp.mapping.scroll_docs(4),
['<C-Space>'] = cmp.mapping.complete(),
['<C-e>'] = cmp.mapping.close(),
['<CR>'] = cmp.mapping.confirm({ select = false }),
-- From https://github.com/hrsh7th/nvim-cmp/wiki/Example-mappings
["<Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_next_item()
elseif luasnip.expand_or_jumpable() then
luasnip.expand_or_jump()
elseif has_words_before() then
cmp.complete()
else
fallback()
end
end, { "i", "s", "c" }),
["<S-Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_prev_item()
elseif luasnip.jumpable(-1) then
luasnip.jump(-1)
else
fallback()
end
end, { "i", "s", "c" }),
},
sources = {
{ name = 'nvim_ciderlsp' },
{ name = 'nvim_lsp' },
{ name = 'luasnip' },
{ name = 'emoji' },
{ name = 'calc' },
{ name = 'spell' },
{ name = 'path' },
{ name = 'nvim_lua' },
{ name = 'buffer',
option = {
-- Complete from all open buffers, not just the current one.
-- https://github.com/hrsh7th/cmp-buffer/issues/1.
get_bufnrs = function()
return vim.api.nvim_list_bufs()
end
},
},
},
formatting = {
fields = { "kind", "abbr", "menu" },
format = function(entry, vim_item)
vim_item.kind = vim_item.kind
vim_item.menu = source_names[entry.source.name]
-- vim_item.dup = duplicates[entry.source.name]
return vim_item
end
},
})
cmp.setup.cmdline("/", {sources = {{name = "buffer"}}})
cmp.setup.cmdline(":", {
sources = cmp.config.sources({{name = "path"}}, {{name = "cmdline"}})
})
-- Setup lspconfig.
-- require('lspconfig')[%YOUR_LSP_SERVER%].setup {
-- capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities())
-- }
-- Integration with nvim-autopairs.
_G.MUtils= {} -- skip it, if you use another global object
vim.g.completion_confirm_key = ""
MUtils.completion_confirm=function()
if vim.fn.pumvisible() ~= 0 then
if vim.fn.complete_info()["selected"] ~= -1 then
return vim.fn["compe#confirm"](npairs.esc("<cr>"))
else
return npairs.esc("<cr>")
end
else
return npairs.autopairs_cr()
end
end
map('i' , '<CR>','v:lua.MUtils.completion_confirm()', {expr = true})
map('i', '<C-l>', '<plug>(fzf-complete-line)')
-- /// Language - General ///
-- require('dim').setup({})
vim.cmd [[
command! TSHighlightCapturesUnderCursor :lua require'nvim-treesitter-playground.hl-info'.show_hl_captures()<cr>
]]
-- Adds multicolored parenthesis to make it easier to see how they match up.
require('nvim-treesitter.configs').setup {
ensure_installed = {'python', 'clojure', 'luadoc', 'lua', 'markdown', 'vim', 'vimdoc'},
highlight = {enable = true},
-- TODO Re-enable when this works better for python.
-- https://github.com/nvim-treesitter/nvim-treesitter/issues/1136 might be
-- related
-- indent = {enable = true},
rainbow = {
enable = true,
extended_mode = true, -- Highlight also non-parentheses delimiters
max_file_lines = 1000, -- Do not enable for files with more than 1000 lines
termcolors = { '3', '4', '1', '3', '4', '1', '3', '4' }
},
textobjects = {
lsp_interop = {
enable = true,
peek_definition_code = {
["gi"] = "@function.outer",
["gI"] = "@class.outer",
},
},
select = {
enable = true,
keymaps = {
-- You can use the capture groups defined in textobjects.scm
["af"] = "@function.outer",
["if"] = "@function.inner",
["ac"] = "@class.outer",
["ic"] = "@class.inner",
},
},
move = {
enable = true,
set_jumps = true, -- whether to set jumps in the jumplist
goto_next_start = {
["]m"] = "@function.outer",
["]]"] = "@class.outer",
},
goto_next_end = {
["]M"] = "@function.outer",
["]["] = "@class.outer",
},
goto_previous_start = {
["[m"] = "@function.outer",
["[["] = "@class.outer",
},
goto_previous_end = {
["[M"] = "@function.outer",
["[]"] = "@class.outer",
},
},
},
playground = {
enable = true,
disable = {},
updatetime = 25, -- Debounced time for highlighting nodes in the playground from source code
persist_queries = false, -- 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 = '?',
},
}
}
require'treesitter-context'.setup{
enable = true, -- Enable this plugin (Can be enabled/disabled later via commands)
max_lines = 0, -- How many lines the window should span. Values <= 0 mean no limit.
min_window_height = 0, -- Minimum editor window height to enable context. Values <= 0 mean no limit.
line_numbers = true,
multiline_threshold = 2, -- Maximum number of lines to show for a single context
trim_scope = 'outer', -- Which context lines to discard if `max_lines` is exceeded. Choices: 'inner', 'outer'
mode = 'cursor', -- Line used to calculate context. Choices: 'cursor', 'topline'
-- Separator between context and content. Should be a single character string, like '-'.
-- When separator is set, the context will only show up when there are at least 2 lines above cursorline.
separator = nil,
zindex = 20, -- The Z-index of the context window
on_attach = nil, -- (fun(buf: integer): boolean) return false to disable attaching
}
local hl = function(group, opts)
opts.default = true
vim.api.nvim_set_hl(0, group, opts)
end
-- Misc {{{
hl('@comment', {link = 'Comment'})
-- hl('@error', {link = 'Error'})
hl('@none', {bg = 'NONE', fg = 'NONE'})
hl('@preproc', {link = 'PreProc'})
hl('@define', {link = 'Define'})
hl('@operator', {link = 'Operator'})
-- }}}
-- Punctuation {{{
hl('@punctuation.delimiter', {link = 'Delimiter'})
hl('@punctuation.bracket', {link = 'Delimiter'})
hl('@punctuation.special', {link = 'Delimiter'})
-- }}}
-- Literals {{{
hl('@string', {link = 'String'})
hl('@string.regex', {link = 'String'})
hl('@string.escape', {link = 'SpecialChar'})
hl('@string.special', {link = 'SpecialChar'})
hl('@character', {link = 'Character'})
hl('@character.special', {link = 'SpecialChar'})
hl('@boolean', {link = 'Boolean'})
hl('@number', {link = 'Number'})
hl('@float', {link = 'Float'})
-- }}}
-- Functions {{{
hl('@function', {link = 'Function'})
hl('@function.call', {link = 'Function'})
hl('@function.builtin', {link = 'Special'})
hl('@function.macro', {link = 'Macro'})
hl('@method', {link = 'Function'})
hl('@method.call', {link = 'Function'})
hl('@constructor', {link = 'Function'})
hl('@parameter', {link = 'Identifier'})
-- }}}
-- Keywords {{{
hl('@keyword', {link = 'Keyword'})
hl('@keyword.function', {link = 'Keyword'})
hl('@keyword.operator', {link = 'Keyword'})
hl('@keyword.return', {link = 'Keyword'})
hl('@conditional', {link = 'Conditional'})
hl('@repeat', {link = 'Repeat'})
hl('@debug', {link = 'Debug'})
hl('@label', {link = 'Label'})
hl('@include', {link = 'Include'})
hl('@exception', {link = 'Exception'})
-- }}}
-- Types {{{
hl('@type', {link = 'Type'})
hl('@type.builtin', {link = 'Type'})
hl('@type.qualifier', {link = 'Type'})
hl('@type.definition', {link = 'Typedef'})
hl('@storageclass', {link = 'StorageClass'})
hl('@attribute', {link = 'PreProc'})
hl('@field', {link = 'Normal'})
hl('@property', {link = 'Identifier'})
-- }}}
-- Identifiers {{{
hl('@variable', {link = 'Normal'})
hl('@variable.builtin', {link = 'Normal'})
hl('@constant', {link = 'Constant'})
hl('@constant.builtin', {link = 'Special'})
hl('@constant.macro', {link = 'Define'})
hl('@namespace', {link = 'Include'})
hl('@symbol', {link = 'Identifier'})
-- }}}
-- Text {{{
hl('@text', {link = 'Normal'})
hl('@text.strong', {bold = true})
hl('@text.emphasis', {italic = true})
hl('@text.underline', {underline = true})
hl('@text.strike', {strikethrough = true})
hl('@text.title', {link = 'Title'})
hl('@text.literal', {link = 'String'})
hl('@text.uri', {link = 'Underlined'})
hl('@text.math', {link = 'Special'})
hl('@text.environment', {link = 'Macro'})
hl('@text.environment.name', {link = 'Type'})
hl('@text.reference', {link = 'Constant'})
hl('@text.todo', {link = 'Todo'})
hl('@text.note', {link = 'SpecialComment'})
hl('@text.warning', {link = 'WarningMsg'})
hl('@text.danger', {link = 'ErrorMsg'})
-- }}}
-- Tags {{{
hl('@tag', {link = 'Tag'})
hl('@tag.attribute', {link = 'Identifier'})
hl('@tag.delimiter', {link = 'Delimiter'})
-- }}}
-- vim.wo.foldmethod = 'expr'
-- vim.wo.foldexpr = 'nvim_treesitter#foldexpr()'
vim.cmd('set foldmethod=expr')
vim.cmd('set foldexpr=nvim_treesitter#foldexpr()')
vim.cmd('set foldlevelstart=99')
local function install_python_ls()
vim.cmd('!pip install python-language-server[all] yapf')
end
local nvim_lsp = require('lspconfig')
-- Range formatting
-- See https://github.com/neovim/neovim/issues/14680
function format_range_operator(motion)
local old_func = vim.go.operatorfunc
_G.op_func_formatting = function()
local start = vim.api.nvim_buf_get_mark(0, '[')
local finish = vim.api.nvim_buf_get_mark(0, ']')
vim.lsp.buf.range_formatting({}, start, finish)
vim.go.operatorfunc = old_func
_G.op_func_formatting = nil
end
vim.go.operatorfunc = 'v:lua.op_func_formatting'
vim.api.nvim_feedkeys('g@' .. motion, 'n', false)
end