-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinit.lua
1457 lines (1347 loc) · 48.1 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
-- What: Mono-file nvim configuration file Why: Easy to see through everything without needing to navigate thru files Features: - LSP
-- - Auto-complete (in insert mode: ctrl-space, navigate w/ Tab+S-Tab, confirm: Enter)
-- - <leader>df to format document
-- - Harpoon marks: Navigate through main files within each project
--
-- Auto-installs vim-plug
vim.cmd([[
let data_dir = has('nvim') ? stdpath('data') . '/site' : '~/.vim'
let plug_path = data_dir . '/autoload/plug.vim'
if empty(glob(plug_path))
execute '!curl -fLo '.plug_path.' --create-dirs https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim'
execute 'so '.plug_path
endif
]])
-- vim-plug
local Plug = vim.fn['plug#']
-- prepare a list of installed plugins from rtp
local installed_plugins = {}
-- NOTE: nvim_list_runtime_paths will expand wildcard paths for us.
for _, path in ipairs(vim.api.nvim_list_runtime_paths()) do
local last_folder_start = path:find("/[^/]*$")
if last_folder_start then
local plugin_name = path:sub(last_folder_start + 1)
installed_plugins[plugin_name] = true
end
end
local wplug_log = require('plenary.log').new({ plugin = 'wplug_log', level = 'debug', use_console = false })
-- Do Plug if plugin not yet linked in `rtp`. This takes care of Nix-compatibility
local function WPlug(plugin_path, ...)
local plugin_name = string.lower(plugin_path:match("/([^/]+)$"))
if not installed_plugins[plugin_name] then
wplug_log.info("Plugging " .. plugin_path)
Plug(plugin_path, ...)
end
end
vim.call('plug#begin')
-- libs and dependencies
-- Plug('nvim-lua/plenary.nvim') -- The base of all plugins
-- plugins
WPlug('tjdevries/nlua.nvim') -- adds symbols of vim stuffs in init.lua
WPlug('nvim-treesitter/nvim-treesitter') -- language parser engine for highlighting
WPlug('nvim-treesitter/nvim-treesitter-textobjects') -- more text objects
WPlug('nvim-telescope/telescope.nvim', { branch = '0.1.x' }) -- file browser
-- TODO: this might need to be taken extra care in our Nix config
-- What this WPlug declaration means is this repo needs to be built on our running environment
-- -----
-- What to do:
-- - Run `make` at anytime before Nix is done on this repository
-- - Might mean that we fetch this repository, run make, and copy to destination folder
-- - Make sure that if we run `make` at first WPlug run, that `make` is idempotent
-- OR
-- Make sure that WPlug does not run `make` and use the output it needs
WPlug('nvim-telescope/telescope-fzf-native.nvim',
{ ['do'] = 'make >> /tmp/log 2>&1' })
WPlug('nvim-telescope/telescope-file-browser.nvim')
-- cmp: auto-complete/suggestions
WPlug('neovim/nvim-lspconfig') -- built-in LSP configurations
WPlug('hrsh7th/cmp-nvim-lsp')
WPlug('hrsh7th/cmp-path')
WPlug('hrsh7th/cmp-buffer') -- Recommends words within the buffer
WPlug('hrsh7th/cmp-cmdline')
WPlug('hrsh7th/nvim-cmp')
WPlug('hrsh7th/cmp-nvim-lsp-signature-help')
WPlug('onsails/lspkind-nvim')
WPlug('yioneko/nvim-yati', { tag = '*' }) -- copium: fix Python indent auto-correct from smart-indent
WPlug('nathanalderson/yang.vim')
-- WPlug('tzachar/cmp-tabnine', { ['do'] = './install.sh' })
-- DevExp
WPlug('windwp/nvim-autopairs') -- matches pairs like [] (),...
WPlug('windwp/nvim-ts-autotag') -- matches tags <body>hello</body>
WPlug('NMAC427/guess-indent.nvim') -- guesses the indentation of an opened buffer
WPlug('j-hui/fidget.nvim') -- Progress bar for LSP
WPlug('numToStr/Comment.nvim') -- "gc" to comment visual regions/lines
WPlug('lewis6991/gitsigns.nvim') -- add git info to sign columns
WPlug('tpope/vim-fugitive') -- git commands in nvim
WPlug('williamboman/mason.nvim') -- LSP, debuggers,... package manager
WPlug('williamboman/mason-lspconfig.nvim') -- lsp config for mason
WPlug('ThePrimeagen/harpoon') -- 1-click through marked files per project
WPlug('TimUntersberger/neogit') -- Easy-to-see git status
WPlug('folke/trouble.nvim') -- File-grouped workspace diagnostics
WPlug('tpope/vim-dispatch') -- Allows quick build/compile/test vim commands
WPlug('clojure-vim/vim-jack-in') -- Clojure: ":Boot", ":Clj", ":Lein"
WPlug('radenling/vim-dispatch-neovim') -- Add support for neovim's terminal emulator
-- WPlug('Olical/conjure') -- REPL on the source for Clojure (and other LISPs)
WPlug('gennaro-tedesco/nvim-jqx') -- JSON formatter (use :Jqx*)
WPlug('kylechui/nvim-surround') -- surrounds with tags/parenthesis
WPlug('simrat39/rust-tools.nvim') -- config rust-analyzer and nvim integration
-- UI & colorscheme
WPlug('simrat39/inlay-hints.nvim') -- type-hints with pseudo-virtual texts
WPlug('gruvbox-community/gruvbox') -- theme provider
WPlug('nvim-lualine/lualine.nvim') -- fancy status line
WPlug('lukas-reineke/indent-blankline.nvim') -- identation lines on blank lines
WPlug('kyazdani42/nvim-web-devicons') -- icons for folder and filetypes
WPlug('m-demare/hlargs.nvim') -- highlights arguments; great for func prog
WPlug('folke/todo-comments.nvim') -- Highlights TODO
WPlug('NvChad/nvim-colorizer.lua') -- color highlighter with tailwind support
WPlug('roobert/tailwindcss-colorizer-cmp.nvim') -- color for tailiwnd for compe
-- other utilities
WPlug('nvim-treesitter/nvim-treesitter-context') -- Top one-liner context of func/class scope
WPlug('nvim-treesitter/playground') -- Sees Treesitter AST - less hair pulling, more PRs
WPlug('saadparwaiz1/cmp_luasnip') -- snippet engine
WPlug('L3MON4D3/LuaSnip') -- snippet engine
WPlug('mickael-menu/zk-nvim') -- Zettelkasten
WPlug('folke/neodev.nvim') -- Neovim + lua development setup
-- Switch cases:
-- `gsp` -> PascalCase (classes), `gsc` -> camelCase (Java), `gs_` -> snake_case (C/C++/Rust)
-- `gsu` -> UPPER_CASE (CONSTs), `gsk` -> kebab-case (Clojure), `gsK` -> Title-Kebab-Case
-- `gs.` -> dot.case (R)
WPlug('arthurxavierx/vim-caser') -- switch cases
---------
vim.call('plug#end')
local PLUGIN_URI = 'gh:pegasust:dotfiles'
local PLUGIN_LEVEL = 'debug'
local log = require('plenary.log').new({ plugin = PLUGIN_URI, level = PLUGIN_LEVEL, use_console = false })
vim.cmd([[
if len(filter(values(g:plugs), '!isdirectory(v:val.dir)'))
PlugInstall --sync | autocmd VimEnter * so $MYVIMRC
endif
]])
-- special terminals, place them at 4..=7 for ergonomics
-- NOTE: this requires a flawless startup, otherwise, it's going to throw errors
-- since we're basically simulating keystrokes
-- TODO: The correct behavior is to register terminal keystroke with an assigned
-- buffer
vim.api.nvim_create_autocmd({ "VimEnter" }, {
callback = function()
local function named_term(term_idx, term_name)
require('harpoon.term').gotoTerminal(term_idx)
vim.cmd([[:exe ":file ]] .. term_name .. [[" | :bfirst]])
end
-- term:ctl at 4
named_term(4, "term:ctl")
-- term:dev at 5
named_term(5, "term:dev")
-- term:repl at 7
named_term(7, "term:repl")
-- term:repl at 6
named_term(6, "term:repl2")
end
})
vim.g.gruvbox_contrast_dark = "soft";
vim.g.gruvbox_contrast_light = "soft";
vim.opt.ignorecase = true;
vim.opt.smartcase = true;
vim.opt.incsearch = true;
vim.opt.number = true;
vim.opt.relativenumber = true;
vim.opt.autoindent = true;
vim.opt.smartindent = true;
vim.opt.expandtab = true;
vim.opt.exrc = true;
vim.opt.tabstop = 4;
vim.opt.softtabstop = 4;
vim.opt.shiftwidth = 4;
vim.opt.scrolloff = 30;
vim.opt.signcolumn = "yes";
vim.opt.colorcolumn = "80";
vim.opt.background = "dark";
vim.api.nvim_create_user_command('Dark', function(opts)
-- opts: {name, args: str, fargs: Splited<str>, range, ...}
---@type string
local contrast = (opts.args and string.len(opts.args) > 0) and opts.args or vim.g.gruvbox_contrast_dark;
vim.g.gruvbox_contrast_dark = contrast;
vim.opt.background = "dark";
end,
{ nargs = "?", })
vim.api.nvim_create_user_command('Light', function(opts)
-- opts: {name, args: str, fargs: Splited<str>, range, ...}
---@type string
local contrast = (opts.args and string.len(opts.args) > 0) and opts.args or vim.g.gruvbox_contrast_light;
vim.g.gruvbox_contrast_light = contrast;
vim.opt.background = "light";
end,
{ nargs = "?", })
vim.opt.lazyredraw = true
vim.opt.termguicolors = true
vim.opt.cursorline = true
-- some plugins misbehave when we do swap files
vim.opt.swapfile = false
vim.opt.backup = false
vim.opt.undodir = vim.fn.stdpath('state') .. '/.vim/undodir'
vim.opt.undofile = true
-- show menu even if there's 1 selection, and default to no selection
-- Note that we're not setitng `noinsert`, which allows us to "foresee" what the
-- completion would give us. This is faithful to VSCode
vim.opt.completeopt = { "menu", "menuone", "noselect", "noinsert" }
-- vim.opt.clipboard = "unnamedplus"
-- more aggressive swap file writing. ThePrimeagen believes higher number
-- leads to low DX
vim.opt.updatetime = 50
vim.g.mapleader = ' '
vim.g.maplocalleader = ','
-- basic keymaps
-- Since we use space for leader, we're asserting that this does nothing by itself
vim.keymap.set({ 'n', 'v' }, '<Space>', '<Nop>', { silent = true })
-- make :terminal escape out. For zsh-vi-mode, just use Alt-Z or any keybind
-- that does not collide with vi-motion keybind. This is because
-- <Alt-x> -> ^[x; while <Esc> on the terminal is ^[
vim.keymap.set('t', '<Esc>', '<C-\\><C-n>)')
vim.keymap.set({ 'n', 'i', 'v' }, '<c-l>', '<Cmd>mode<Cr>', { desc = "" }) -- redraw on every mode
-- diagnostics (errors/warnings to be shown)
vim.keymap.set('n', '[d', vim.diagnostic.goto_prev)
vim.keymap.set('n', ']d', vim.diagnostic.goto_next)
vim.keymap.set('n', '<leader>e', vim.diagnostic.open_float) -- opens diag in box (floating)
-- vim.keymap.set('n', '<leader>q', vim.diagnostic.setloclist) -- opens list of diags
-- vim.keymap.set('n', '<leader>wq', vim.diagnostic.setqflist) -- workspace diags
vim.keymap.set('n', '<leader>q', '<cmd>TroubleToggle loclist<cr>')
vim.keymap.set('n', '<leader>wq', '<cmd>TroubleToggle workspace_diagnostics<cr>')
vim.keymap.set('n', '<leader>gg', '<cmd>GuessIndent<cr>')
-- color, highlighting, UI stuffs
vim.cmd([[
colorscheme gruvbox
]])
require('hlargs').setup()
require('nvim-web-devicons').setup()
require('trouble').setup {
position = "bottom", -- position of the list can be: bottom, top, left, right
height = 10, -- height of the trouble list when position is top or bottom
width = 50, -- width of the list when position is left or right
icons = true, -- use devicons for filenames
mode = "workspace_diagnostics", -- "workspace_diagnostics", "document_diagnostics", "quickfix", "lsp_references", "loclist"
severity = nil, -- nil (ALL) or vim.diagnostic.severity.ERROR | WARN | INFO | HINT
fold_open = "", -- icon used for open folds
fold_closed = "", -- icon used for closed folds
group = true, -- group results by file
padding = true, -- add an extra new line on top of the list
action_keys = {
-- key mappings for actions in the trouble list
-- map to {} to remove a mapping, for example:
-- close = {},
close = "q", -- close the list
cancel = "<esc>", -- cancel the preview and get back to your last window / buffer / cursor
refresh = "r", -- manually refresh
jump = { "<cr>", "<tab>" }, -- jump to the diagnostic or open / close folds
open_split = { "<c-x>" }, -- open buffer in new split
open_vsplit = { "<c-v>" }, -- open buffer in new vsplit
open_tab = { "<c-t>" }, -- open buffer in new tab
jump_close = { "o" }, -- jump to the diagnostic and close the list
toggle_mode = "m", -- toggle between "workspace" and "document" diagnostics mode
switch_severity = "s", -- switch "diagnostics" severity filter level to HINT / INFO / WARN / ERROR
toggle_preview = "P", -- toggle auto_preview
hover = "K", -- opens a small popup with the full multiline message
preview = "p", -- preview the diagnostic location
close_folds = { "zM", "zm" }, -- close all folds
open_folds = { "zR", "zr" }, -- open all folds
toggle_fold = { "zA", "za" }, -- toggle fold of current file
previous = "k", -- previous item
next = "j" -- next item
},
indent_lines = true, -- add an indent guide below the fold icons
auto_open = false, -- automatically open the list when you have diagnostics
auto_close = false, -- automatically close the list when you have no diagnostics
auto_preview = true, -- automatically preview the location of the diagnostic. <esc> to close preview and go back to last window
auto_fold = false, -- automatically fold a file trouble list at creation
auto_jump = { "lsp_definitions" }, -- for the given modes, automatically jump if there is only a single result
signs = {
-- icons / text used for a diagnostic
error = "",
warning = "",
hint = "",
information = "",
other = "",
},
use_diagnostic_signs = false -- enabling this will use the signs defined in your lsp client
}
-- TODO: Any way to collect all the TODOs and its variants?
require('todo-comments').setup()
-- plugin keymaps
local function remap(mode, key_cmd, binded_fn, opts)
opts = opts or { remap = true }
return vim.keymap.set(mode, key_cmd, binded_fn, opts)
end
-- Comment.nvim
require('Comment').setup()
-- lukas-reineke/indent-blankline.nvim
vim.opt.list = true
vim.opt.listchars:append "space:⋅"
vim.opt.listchars:append "eol:↴"
require("indent_blankline").setup {
show_end_of_line = true,
space_char_blankline = " ",
}
-- User command that transform into 2-spaces by translating to tabstop
vim.api.nvim_create_user_command(
'HalfSpaces',
function(opts)
vim.api.nvim_command("set ts=2 sts=2 noet")
vim.api.nvim_command("retab!")
vim.api.nvim_command("set ts=1 sts=1 et")
vim.api.nvim_command("retab")
vim.api.nvim_command("GuessIndent")
end,
{ nargs = 0 }
)
vim.api.nvim_create_user_command(
'DoubleSpaces',
function(opts)
-- cannot really do 1-space tab. The minimum is 2-space to begin
-- doubling
vim.api.nvim_command("set ts=2 sts=2 noet")
vim.api.nvim_command("retab!")
vim.api.nvim_command("set ts=4 sts=4 et")
vim.api.nvim_command("retab")
vim.api.nvim_command("GuessIndent")
end,
{ nargs = 0 }
)
-- telescope
local fb_actions = require "telescope".extensions.file_browser.actions
local tel_actions = require("telescope.actions")
local tel_actionset = require("telescope.actions.set")
local function term_height()
return vim.opt.lines:get()
end
require('telescope').setup {
defaults = {
mappings = {
n = {
['<C-u>'] = function(prompt_bufnr) tel_actionset.shift_selection(prompt_bufnr, -math.floor(term_height() / 2)) end,
['<C-d>'] = function(prompt_bufnr) tel_actionset.shift_selection(prompt_bufnr, math.floor(term_height() / 2)) end,
},
},
},
extensions = {
fzf = {
fuzzy = true, -- allow fuzzy matches
override_generic_sorter = true,
override_file_sorter = true,
case_mode = 'smart_case'
},
file_browser = {
theme = require('telescope.themes').get_ivy().theme,
hiject_netrw = true, -- disables netrw and use file-browser instead
mappings = {
["i"] = {}, -- disable any shortcut in insert mode for now
["n"] = {
["c"] = fb_actions.create,
["r"] = fb_actions.rename,
["m"] = fb_actions.move,
["y"] = fb_actions.copy,
["d"] = fb_actions.remove,
["o"] = fb_actions.open,
["g"] = fb_actions.goto_parent_dir,
["e"] = fb_actions.goto_home_dir,
["w"] = fb_actions.goto_cwd,
["t"] = fb_actions.change_cwd,
["f"] = fb_actions.toggle_browser,
["h"] = fb_actions.toggle_hidden,
["s"] = fb_actions.toggle_all,
}
}
}
}
}
-- Telescope key remap stuffs
pcall(require('telescope').load_extension, 'fzf')
pcall(require('telescope').load_extension, 'file_browser')
remap('n', '<C-p>', '<cmd>Telescope<cr>', { desc = 'Open Telescope general search' })
remap('n', '<leader>fm', function()
require("telescope").extensions.file_browser.file_browser({})
end, { desc = '[F]ile [M]utation' })
remap('n', '<leader>ff', function()
require('telescope.builtin').find_files({
hidden = false,
no_ignore = false,
follow = false,
})
end, { desc = '[F]ind [F]ile' })
remap('n', '<leader>fa', function()
require('telescope.builtin').find_files({
hidden = true,
no_ignore = true,
follow = true,
})
end, { desc = '[F]ind [A]ll files' })
remap('n', '<leader>fg', function()
require('telescope.builtin').live_grep()
end, { desc = '[F]ind thru [G]rep' })
remap('n', '<leader>fug', function()
-- This relies on many factors: We use `rg` and that `-g '**/*'` effectively
-- drops ignore rules like the default `.gitignore` rule.
require('telescope.builtin').live_grep({ glob_pattern = '**/*' })
end, { desc = '[F]ind thru [u]nrestricted [G]rep' })
remap('n', '<leader>fb', function()
require('telescope.builtin').buffers()
end, { desc = '[F]ind existing [B]uffers' })
remap('n', '<leader>fh', function()
require('telescope.builtin').help_tags()
end, { desc = '[F]ind [H]elp' })
remap('n', '<leader>fd', function()
require('telescope.builtin').diagnostics()
end, { desc = '[F]ind [D]iagnostics' })
-- ZK remap stuffs
remap('n', '<leader>zf', function()
-- vim.cmd([[:ZkNotes]])
require('zk').edit({}, { multi_select = false })
end, { desc = '[Z]ettelkasten [F]iles' })
remap('n', '<leader>zg', function()
vim.cmd(":ZkGrep")
end, { desc = '[Z]ettelkasten [G]rep' })
-- tab management {{{
-- Jump to specific tab with <C-t>[number]
for i = 1, 9 do
vim.api.nvim_set_keymap('n', '<C-t>' .. i, ':tabn ' .. i .. '<CR>', { noremap = true, silent = true })
end
-- Show tab number in tab display
vim.o.showtabline = 1
vim.o.tabline = '%!v:lua.my_tabline()'
function _G.my_tabline()
local s = ''
for i = 1, vim.fn.tabpagenr('$') do
if i == vim.fn.tabpagenr() then
s = s .. '%' .. i .. 'T%#TabLineSel#'
else
s = s .. '%' .. i .. 'T%#TabLine#'
end
local tab = vim.fn.gettabinfo(i)[1]
local tabbuf = tab.variables.buffers
local bufname = "<unknown>"
if tabbuf then
bufname = tabbuf[tab.curwin].name
end
-- Canonicalize tab/buf name
s = s .. ' ' .. i .. ' ' .. vim.fn.fnamemodify(bufname, ':t')
if i ~= vim.fn.tabpagenr('$') then
s = s .. '%#TabLine#|%#TabLine#'
end
end
return s .. '%T%#TabLineFill#%='
end
-- Close all tabs except the first one
vim.api.nvim_set_keymap('n', '<C-t>x', ':tabdo if tabpagenr() > 1 | tabclose | endif<CR>',
{ noremap = true, silent = true, desc = "Close all tabs except the first one", })
-- }}}
-- treesitter
require 'treesitter-context'
require('nvim-treesitter.configs').setup {
yati = {
enable = true,
default_lazy = true,
default_fallback = "auto",
disable = { "nix" }
},
indent = { enable = false },
highlight = {
enable = true,
enable_vim_regex_highlighting = true,
},
incremental_selection = {
enable = true,
keymaps = {
init_selection = '<C-space>',
node_incremental = '<C-space>',
node_decremental = '<C-backspace>',
scope_incremental = '<C-S>'
},
},
textobjects = {
select = {
enable = true,
lookahead = true,
keymaps = {
['af'] = '@function.outer',
['if'] = '@function.inner',
['ac'] = '@class.outer',
['ic'] = '@class.inner',
},
},
},
playground = {
enable = true,
disable = {}
},
-- automatically close and modify HTML and TSX tags
autotag = {
enable = true,
},
}
require('nvim-autopairs').setup {
check_ts = true,
}
local parser_config = require('nvim-treesitter.parsers').get_parser_configs()
parser_config.tsx.filetype_to_parsername = { "javascript", "typescript.tsx" }
parser_config.astro.filetype_to_parsername = { "javascript", "typescript.tsx", "astro" }
require('guess-indent').setup {
auto_cmd = true,
filetype_exclude = { -- A list of filetypes for which the auto command gets disabled
"netrw",
"tutor",
},
-- buftype_exclude = { -- A list of buffer types for which the auto command gets disabled
-- "help",
-- "nofile",
-- "terminal",
-- -- "prompt",
-- },
}
-- harpoon: O(1) buffer/terminal switching
remap('n', '<leader>m', function() require('harpoon.mark').add_file() end, { desc = "[H]arpoon [M]ark" })
local function harpoon_nav(key, nav_file_index, lead_keybind)
lead_keybind = lead_keybind or '<leader>h'
assert(type(key) == "string", "expect key to be string(keybind)")
assert(type(nav_file_index) == "number" and nav_file_index >= 1, "expect 1-indexed number for file index")
return remap('n', lead_keybind .. key,
function() require('harpoon.ui').nav_file(nav_file_index) end,
{ desc = "[H]arpoon navigate " .. tostring(nav_file_index) })
end
-- remap letters to index. Inspired by alternating number of Dvorak programmer
-- best practices: try to keep marked files to be around 4
harpoon_nav('f', 1)
harpoon_nav('j', 2)
harpoon_nav('d', 3)
harpoon_nav('k', 4)
remap('n', '<leader>hh', function() require('harpoon.ui').toggle_quick_menu() end)
for i = 1, 10 do
-- harpoon: navigate files by numbers
harpoon_nav(tostring(i % 10), i)
-- harpoon: navigate terms by numbers
remap('n', '<leader>t' .. tostring(i % 10), function()
require('harpoon.term').gotoTerminal(i)
end)
end
-- neogit: easy-to-see git status. Provides only productivity on staging/unstage
require('neogit').setup {}
remap('n', '<leader>gs', function() require('neogit').open({}) end, { desc = "[G]it [S]tatus" });
-- LSP settings
-- This function gets run when an LSP connects to a particular buffer.
require("inlay-hints").setup {
-- renderer to use
-- possible options are dynamic, eol, virtline and custom
-- renderer = "inlay-hints/render/dynamic",
renderer = "inlay-hints/render/eol",
hints = {
parameter = {
show = true,
highlight = "whitespace",
},
type = {
show = true,
highlight = "Whitespace",
},
},
-- Only show inlay hints for the current line
only_current_line = false,
eol = {
-- whether to align to the extreme right or not
right_align = false,
-- padding from the right if right_align is true
right_align_padding = 7,
parameter = {
separator = ", ",
format = function(hints)
return string.format(" <- (%s)", hints)
end,
},
type = {
separator = ", ",
format = function(hints)
return string.format(" => %s", hints)
end,
},
},
}
local on_attach = function(client, bufnr)
local nmap = function(keys, func, desc)
if desc then
desc = 'LSP: ' .. desc
end
vim.keymap.set('n', keys, func, { noremap = true, buffer = bufnr, desc = desc })
end
nmap('<leader>rn', vim.lsp.buf.rename, '[R]e[n]ame')
nmap('<leader>ca', vim.lsp.buf.code_action, '[C]ode [A]ction')
-- NOTE: I have no clue what this does again
vim.api.nvim_buf_set_option(bufnr, 'omnifunc', 'v:lua.vim.lsp.omnifunc')
nmap('<leader>df', function() vim.lsp.buf.format({ async = true }) end, '[D]ocument [F]ormat')
-- symbols and gotos
nmap('gd', vim.lsp.buf.definition, '[G]oto [D]efinition')
nmap('gi', vim.lsp.buf.implementation, '[G]oto [I]mplementation')
nmap('gr', require('telescope.builtin').lsp_references)
nmap('<leader>ds', require('telescope.builtin').lsp_document_symbols, '[D]ocument [S]ymbols')
nmap('<leader>ws', require('telescope.builtin').lsp_dynamic_workspace_symbols, '[W]orkspace [S]ymbols')
-- documentations & helps
-- NOTE: When you press K, it shows in-line Documentation
-- This is to stay faithful with vim's default keybind for help.
-- See `:help K` for even more info on Vim's original keybindings for help
nmap('K', vim.lsp.buf.hover, 'Hover Documentation')
-- nmap('<C-k>', vim.lsp.buf.signature_help, 'Signature Documentation')
-- Less likely LSP functionality to be used
nmap('gD', vim.lsp.buf.declaration, '[G]oto [D]eclaration')
nmap('gtd', vim.lsp.buf.type_definition, '[G]oto [T]ype [D]efinition')
nmap('<leader>D', vim.lsp.buf.type_definition, 'Type [D]efinition')
--
-- Very rarely used
nmap('<leader>wa', vim.lsp.buf.add_workspace_folder, '[W]orkspace [A]dd Folder')
nmap('<leader>wr', vim.lsp.buf.remove_workspace_folder, '[W]orkspace [R]emove Folder')
nmap('<leader>wl', function()
print(vim.inspect(vim.lsp.buf.list_workspace_folders()))
end, '[W]orkspace [L]ist Folders')
-- enable inlay hints if available
require('inlay-hints').on_attach(client, bufnr)
end
-- nvim-cmp
local cmp = require 'cmp'
local luasnip = require 'luasnip'
local lspkind = require('lspkind')
lspkind.init {
symbol_map = {
Copilot = "",
},
}
cmp.event:on(
"confirm_done",
require('nvim-autopairs.completion.cmp').on_confirm_done()
)
---@alias EntryFilter {id: integer, compe: lsp.CompletionItem, return_type: string, return_type2: string, score: number, label: string, source_name: string, bufnr: number?, offset: number?, kind: lsp.CompletionItemKind }
---@param entry cmp.Entry
---@return EntryFilter
local function entry_filter_sync(entry)
local compe = entry:get_completion_item()
local return_type = compe.data and compe.data.return_type
local return_type2 = compe.detail
local score = entry.score
local label = compe.label
local source_name = entry.source.name
local bufnr = entry.context.bufnr
local offset = entry:get_offset()
local kind = entry:get_kind()
local id = entry.id
return {
id = id,
compe = compe,
return_type = return_type,
return_type2 = return_type2,
score = score,
label = label,
source_name = source_name,
bufnr = bufnr,
offset = offset,
kind = kind,
}
end
---@param entry cmp.Entry
---@param callback fun(entry: EntryFilter): any
local function entry_filter(entry, callback)
entry:resolve(function()
callback(entry_filter_sync(entry))
end)
end
---@type cmp.ConfigSchema
local cmp_config = {
snippet = {
expand = function(args)
luasnip.lsp_expand(args.body)
end,
},
mapping = cmp.mapping.preset.insert {
['<C-l'] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.refresh()
else
fallback()
end
-- 'i': insert, 's': select, 'c': command
end, { 'i', 's' }),
['<C-u>'] = cmp.mapping.scroll_docs(-4),
['<C-d>'] = cmp.mapping.scroll_docs(4),
['<C-space>'] = cmp.mapping.complete(),
['<CR>'] = cmp.mapping.confirm {
behavior = cmp.ConfirmBehavior.Replace,
select = true,
},
-- NOTE: rebind tab and shift-tab since it may break whenever we
-- need to peform manual indentation
['<C-j>'] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_next_item({ behavior = cmp.SelectBehavior.Select })
elseif luasnip.expand_or_jumpable() then
luasnip.expand_or_jump()
else
fallback()
end
end, { 'i', 's' }),
['<C-k>'] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_prev_item({ behavior = cmp.SelectBehavior.Select })
elseif luasnip.jumpable(-1) then
luasnip.jump(-1)
else
fallback()
end
end, { 'i', 's' }),
},
performance = {
debounce = 60,
throttle = 30,
},
formatting = {
fields = { 'abbr', 'kind', 'menu' },
-- vim_items: complete-items (`:h complete-items`)
-- word, abbr, menu, info, kind, icase, equal, dup, empty, user_data
format = function(entry, vim_item)
local kind_fn = lspkind.cmp_format {
with_text = true,
menu = {
buffer = "[buf]",
nvim_lsp = "[LSP]",
nvim_lua = "[api]",
path = "[path]",
luasnip = "[snip]",
gh_issues = "[issues]",
tn = "[TabNine]",
eruby = "[erb]",
nvim_lsp_signature_help = "[sig]",
}
}
vim_item = kind_fn(entry, vim_item)
-- copium that this will force resolve for entry
entry_filter(entry, function(entry)
if entry.source_name == "nvim_lsp" then
log.debug('format:entry: ' .. vim.inspect(entry, { depth = 2 }))
end
end)
return require('tailwindcss-colorizer-cmp').formatter(entry, vim_item)
end,
},
sources = cmp.config.sources( --[[@as cmp.SourceConfig[]] {
{ name = 'nvim_lsp', max_item_count = 30, },
{ name = 'nvim_lsp_signature_help' },
-- NOTE: Path is triggered by `.` and `/`, so when it comes up, it's
-- usually desirable.
{ name = 'path', max_item_count = 20, },
{ name = 'luasnip', max_item_count = 20, },
{
name = 'buffer',
option = {
-- default is only in the current buffer. This grabs recommendations
-- from all visible buffers
get_bufnrs = function()
-- Must always have current buffer
local bufs = { [0] = true }
for _, buf in ipairs(vim.api.nvim_list_bufs()) do
local byte_size = vim.api.nvim_buf_get_offset(buf, vim.api.nvim_buf_line_count(buf))
if byte_size <= 1024 * 1024 then -- 1 MiB max
bufs[buf] = true
end
end
return vim.tbl_keys(bufs)
end,
},
max_item_count = 20,
}
-- NOTE: I don't like cmdline that much. Most of the time, it recommends more harm than good
-- { name = 'cmp_tabnine' },
-- { name = "conjure" },
}),
experimental = { ghost_text = { hl_group = "Comment" }, },
sorting = {
comparators = {
cmp.config.compare.exact,
cmp.config.compare.recently_used,
cmp.config.compare.offset,
cmp.config.compare.score,
cmp.config.compare.kind,
cmp.config.compare.locality,
cmp.config.compare.sort_text,
cmp.config.compare.scope,
},
},
}
cmp.setup(vim.tbl_deep_extend("force", require('cmp.config.default')(), cmp_config))
-- set max autocomplete height. this prevents huge recommendations to take over the screen
vim.o.pumheight = 15 -- 15/70 is good enough ratio for me. I generally go with 80-90 max height, though
vim.o.pumblend = 10 -- semi-transparent for the art, nothing too useful (neovim recommends 0-30)
-- `/` cmdline search.
cmp.setup.cmdline('/', {
mapping = cmp.mapping.preset.cmdline(),
sources = {
{ name = 'buffer' }
}
})
-- `:` cmdline vim command.
cmp.setup.cmdline(':', {
mapping = cmp.mapping.preset.cmdline(),
sources = cmp.config.sources({
{ name = 'path' }
}, {
{
name = 'cmdline',
option = {
ignore_cmds = { 'Man', '!' }
}
}
})
})
-- nvim-cmp supports additional completion capabilities
local capabilities = require('cmp_nvim_lsp').default_capabilities()
-- local tabnine = require('cmp_tabnine.config')
-- tabnine.setup({
-- max_lines = 1000,
-- max_num_results = 20,
-- sort = true,
-- run_on_every_keystroke = true,
-- snippet_placeholder = '..',
-- ignored_file_types = {},
-- show_prediction_strength = true,
-- })
-- default language servers
local servers = {
'clangd', 'rust_analyzer', 'pyright', 'tsserver', 'lua_ls', 'cmake', 'tailwindcss', 'prismals',
'nil_ls', 'eslint', 'terraformls', 'tflint', 'svelte', 'astro', 'clojure_lsp', "bashls", 'yamlls', "ansiblels",
"jsonls", "denols", "gopls", "nickel_ls", 'pylsp',
}
require("mason").setup({
ui = {
icons = {
package_installed = "✓",
package_pending = "➜",
package_uninstalled = "✗"
},
check_outdated_packages_on_open = true,
},
-- NOTE: The default settings is "prepend" https://github.com/williamboman/mason.nvim#default-configuration
-- Which means Mason's installed path is prioritized against our local install
-- see: https://git.pegasust.com/pegasust/aoc/commit/b45dc32c74d84c9f787ebce7a174c9aa1d411fc2
-- This introduces some pitfalls, so we'll take the approach of trusting user's local installation
PATH = "append",
})
require('mason-lspconfig').setup({
-- ensure_installed = servers,
ensure_installed = {
"pylsp", "pyright", "tailwindcss", "svelte", "astro", "lua_ls", "tsserver",
"ansiblels", "yamlls", "docker_compose_language_service", "jsonls",
},
automatic_installation = false,
})
local inlay_hint_tsjs = {
includeInlayEnumMemberValueHints = true,
includeInlayFunctionLikeReturnTypeHints = true,
includeInlayFunctionParameterTypeHints = true,
includeInlayParameterNameHints = 'all', -- "none" | "literals" | "all"
inlcudeInlayParameterNameHintsWhenArgumentMatchesName = false,
includeInlayPropertyDeclarationTypeHints = true,
includeInlayVariableTypeHints = true,
};
require('mason-lspconfig').setup_handlers({
-- default handler
function(server_name)
require('lspconfig')[server_name].setup {
on_attach = on_attach,
capabilities = capabilities,
}
end,
["lua_ls"] = function()
require('lspconfig').lua_ls.setup {
on_attach = on_attach,
capabilities = capabilities,
settings = {
Lua = {
runtime = {
version = "LuaJIT",
path = vim.split(package.path, ";"),
},
diagnostics = {
globals = { "vim" }
},
workspace = {
library = vim.api.nvim_get_runtime_file('', true),
-- Don't prompt me to select
checkThirdParty = false,
},
telemetry = { enable = false },
hint = {
enable = true,
},
format = {
enable = true,
defaultConfig = {
indent_style = "space",
indent_size = 4,
},
},
},
},
}
end,
["pyright"] = function()
require('lspconfig').pyright.setup {
on_attach = on_attach,
capabilities = capabilities,
settings = {
pyright = {
disableLanguageServices = false,
disableOrganizeImports = false,
},
python = {
analysis = {
autoImportCompletions = true,
autoSearchPaths = true,
diagnosticMode = "openFilesOnly",
-- diagnosticSeverityOverrides =
extraPaths = {},
logLevel = "Information",
stubPath = "typings",
typeCheckingMode = "basic",
typeshedPaths = {},