-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit.lua
More file actions
818 lines (721 loc) · 28.2 KB
/
Copy pathinit.lua
File metadata and controls
818 lines (721 loc) · 28.2 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
-- vim:fdm=marker
-- xell neovim nvim config
-- _/ _/ _/_/_/_/ _/ _/
-- _/ _/ _/ _/ _/
-- _/ _/_/_/ _/ _/
-- _/ _/ _/ _/ _/
-- _/ _/ _/_/_/_/ _/_/_/_/ _/_/_/_/
-- Pre and helpers {{{
local function k(keys)
return vim.api.nvim_replace_termcodes(keys, true, true, true)
end
-- }}}
-- General settings {{{
vim.g.mapleader = ','
vim.g.maplocalleader = [[\]]
vim.o.ignorecase = true
vim.o.smartcase = true
vim.o.incsearch = true
vim.o.inccommand = 'split'
vim.o.wrapscan = false
vim.o.wildignore =
'*.o,*.obj,*.dll,*.exe,*.so,*.a,*.lib,*.pyc,*.pyo,*.pyd,*.swp,*.swo,*.class,*.DS_Store,*.orig,*.db,*.javac,*.pyc,*.aux,*.out,*.toc'
vim.o.suffixesadd = '.java,.rs,.lua'
vim.o.updatetime = 500
vim.o.modelineexpr = true
vim.o.shada = "'100,<1000,s500,h" -- ori viminfo
vim.o.sessionoptions = 'buffers,curdir,folds,globals,help,resize,slash,tabpages,winpos,winsize,localoptions,options'
vim.o.grepprg = 'rg --vimgrep --smart-case'
-- Completion
vim.o.pumheight = 20
vim.o.wildmenu = true
vim.o.omnifunc = 'syntaxcomplete#Complete'
vim.o.dictionary = '/usr/share/dict/words'
vim.opt.complete:append('k') -- also scan file(s) in the 'dictionary'
vim.o.infercase = true
vim.keymap.set('i', '<M-space>', '<C-x><C-k>')
-- }}}
-- UI GUI {{{
vim.o.title = true
vim.o.guifont = "Sarasa Term SC Nerd:h14"
vim.o.number = true
vim.o.breakindent = true
vim.o.breakindentopt = 'list:-2'
vim.o.concealcursor = 'nc'
vim.o.smoothscroll = true
vim.o.laststatus = 2 -- nvim-spec
vim.o.shortmess = 'atI'
vim.o.visualbell = true
vim.o.report = 0
vim.o.equalalways = false
vim.o.splitright = true
vim.o.splitbelow = true
vim.o.scrolloff = 10
-- if 'listchars' or 'fillchars' contains double width characters
vim.o.ambiwidth = 'single'
vim.o.listchars = 'tab:▸\\ ,eol:¬'
vim.opt.fillchars = { --- nvim-spec
fold = ' ',
foldopen = ({ '', '' })[1],
foldclose = ({ '', '' })[1],
foldsep = '│',
diff = '╱',
eob = ' ',
vert = '│',
}
-- reload current colorscheme
vim.api.nvim_create_user_command('ReloadColorscheme', function()
vim.cmd.colorscheme(vim.api.nvim_exec2('colorscheme', { output = true })['output'])
end, {})
-- toggle relativenumber
vim.keymap.set('n', '<Leader>nn', function()
vim.wo.relativenumber = not vim.wo.relativenumber
end, { desc = 'Toggle relative number' })
-- show/hide number
vim.keymap.set('n', '<Leader>nN', function()
vim.wo.number = not vim.wo.number
end, { desc = 'Show/hide number' })
-- set colorcolumn cc
vim.keymap.set('n', '<Leader>hc', function()
local col = vim.fn.virtcol('.')
local colorcolumn_list = vim.opt.colorcolumn:get()
for _, v in pairs(colorcolumn_list) do
if v == '' .. col then
vim.opt.colorcolumn:remove('' .. v)
return
end
end
vim.opt.colorcolumn:append('' .. col)
end, { desc = 'Add or remove colorcolumn' })
-- keep bar cursor {{{
local saved_guicursor
local function set_cursor_bar()
-- Clearing guicursor stops nvim's teardown from emitting terminfo Se
-- (ESC[2 q, steady block), which would otherwise override the write below.
-- Plain DECSCUSR, never a \ePtmux; passthrough: tmux's allow-passthrough is
-- off by default, so passthrough is silently swallowed. Writing it plainly
-- also keeps tmux's own per-pane cursor state in sync. Inside tmux the
-- decisive fix is the Se override in ~/.tmux.conf, not this hook.
saved_guicursor = vim.o.guicursor
vim.o.guicursor = ""
io.write("\27[5 q")
end
vim.api.nvim_create_autocmd({ "VimLeave", "VimSuspend" }, { callback = set_cursor_bar })
vim.api.nvim_create_autocmd("VimResume", {
callback = function()
if saved_guicursor then
vim.o.guicursor = saved_guicursor
end
end,
})
-- Cursor: normal-ish => block, insert-ish => bar. Single source of truth for
-- both the main editor and the Ctrl-G temp editor (CLI agents use $EDITOR).
vim.opt.guicursor = "n-v-c-sm:block,i-ci-ve:ver30,o:block,r-cr-o:ver30"
vim.api.nvim_create_autocmd({ "ModeChanged", "WinEnter", "BufEnter" }, {
callback = function()
if vim.bo.buftype ~= "terminal" then
vim.cmd("redraw!") -- re-emits current shape from guicursor
end
end,
})
--- }}}
require('wordcount').setup({
format = function(c)
return string.format(' zh:%d en:%dw/%dc ', c.cjk, c.words, c.chars)
end,
})
-- statusline {{{
-- let g:mystatusline1 = '\ %{winnr()}\ %<%f\ %h%y%m%r\ [%{&ff}]\ [%{&fenc}]'
-- let g:mystatusline2 = '%=%-14.(%l,%c%V%)\ %L\ %P\ '
-- vim.o.statusline = ' %{winnr()} %<%f %h%y%m%r [%{&ff}] [%{&fenc}]' .. ' %{fugitive#statusline()}' .. '%=%-14.(%l,%c%V%) %L %P '
-- https://nuxsh.is-a.dev/blog/custom-nvim-statusline.html
-- vim.g.WinID = {'', '', '', '', '', '', '',}
vim.g.WinID = { '', '', '', '', '', '', '', }
--
--
StatuslineActive = function()
-- '', '', '', '', '', '', '',
-- '', '', '', '', '', '', '',
-- '', '', '', '', '', '', '',
return table.concat {
' %#WinBar#%{winnr()}%#StatusLine# %<%f %h%y%m%r ',
-- ' %{winnr() <= 7 ? g:WinID[winnr() - 1] : winnr()} %<%f %h%y%m%r ',
-- (function ()
-- local digits = {'', '', '', '', '', '', '',}
-- -- local winnr = vim.fn.winnr()
-- if vim.fn.winnr() <= 7 then
-- return ' ' .. digits[vim.fn.winnr()] .. ' '
-- else
-- return ' ' .. vim.fn.winnr() .. ' '
-- end
-- end)(),
-- ' %<%f %h%y%m%r ',
vim.opt.fileformat:get() == 'unix' and '' or '[' .. vim.opt.fileformat:get() .. '] ',
vim.opt.fileencoding:get() == 'utf-8' and '' or '[' .. vim.opt.fileencoding:get() .. '] ',
vim.fn.exists('*FugitiveStatusline') == 0 and '' or (function()
local fs = vim.fn['fugitive#statusline']()
if fs ~= '' then
fs = string.sub(fs, 6, -3)
return ' ' .. fs .. ' '
else
return ''
end
end)(),
require('wordcount').statusline(),
'%=%-14.(%l,%c%V%) %L %P ',
}
end
StatuslineInactive = function()
return table.concat {
' %#WinBar#%{winnr()}%#StatusLineNC# %<%f %h%y%m%r ',
-- ' %{winnr() <= 7 ? g:WinID[winnr() - 1] : winnr()} %<%f %h%y%m%r ',
-- (function ()
-- local digits = {'', '', '', '', '', '', '',}
-- -- local winnr = vim.fn.winnr()
-- if vim.fn.winnr() <= 7 then
-- return ' ' .. digits[vim.fn.winnr()] .. ' '
-- else
-- return ' ' .. vim.fn.winnr() .. ' '
-- end
-- end)(),
-- ' %<%f %h%y%m%r ',
}
end
vim.cmd [[
augroup Statusline
au!
au WinEnter,BufEnter * setlocal statusline=%!v:lua.StatuslineActive()
au WinLeave,BufLeave * setlocal statusline=%!v:lua.StatuslineInactive()
augroup END
]]
-- vim.cmd[[set statusline=%!v:lua.Statusline()]]
--- }}}
-- }}}
-- Special settings {{{
vim.g.netrw_liststyle = 3
vim.g.netrw_keepdir = 0
vim.opt.termguicolors = true
vim.g.seditor_table = {}
vim.opt.diffopt:append('linematch:60')
vim.api.nvim_create_autocmd('FileType', {
group = vim.api.nvim_create_augroup('xell/close_with_q', { clear = true }),
desc = 'Close with <q>',
pattern = {
'git',
'help',
'man',
'qf',
'query',
'scratch',
'spectre_panel',
},
callback = function(args)
vim.keymap.set('n', 'q', '<cmd>quit<cr>', { buffer = args.buf })
end,
})
-- }}}
-- Windows and tab {{{
-- window size TODO
vim.keymap.set('n', '<M-->', '<C-w>-')
vim.keymap.set('n', '<M-=>', '<C-w>+')
vim.keymap.set('n', '<M-,>', '<C-w><')
vim.keymap.set('n', '<M-.>', '<C-w>>')
vim.keymap.set('t', '<M-->', '<C-\\><C-n><C-w>-')
vim.keymap.set('t', '<M-=>', '<C-\\><C-n><C-w>+')
vim.keymap.set('t', '<M-,>', '<C-\\><C-n><C-w><')
vim.keymap.set('t', '<M-.>', '<C-\\><C-n><C-w>>')
vim.keymap.set("n", "<down>", ":resize +1<cr>")
vim.keymap.set("n", "<up>", ":resize -1<cr>")
vim.keymap.set("n", "<right>", ":vertical resize +1<cr>")
vim.keymap.set("n", "<left>", ":vertical resize -1<cr>")
-- <M-n> goes to the n window
for i = 1, 10 do
vim.keymap.set('n', '<M-' .. i .. '>', i .. '<c-w><c-w>')
vim.keymap.set('t', '<M-' .. i .. '>', i .. '<C-\\><C-N><c-w><c-w>')
end
-- <M-h/j/k/l>
for c in ('hjkl'):gmatch '.' do
vim.keymap.set('t', '<M-' .. c .. '>', '<C-\\><C-N><C-w>' .. c)
vim.keymap.set('n', '<M-' .. c .. '>', '<C-w>' .. c)
end
-- <Tab> to jump between two recent windows
vim.keymap.set('n', '<Tab>', function()
local ori_win_nr = vim.fn.winnr() -- vim.api.nvim_win_get_number(0)
-- Asynchronous execution
-- vim.api.nvim_feedkeys(k('<C-w><C-p>'), 'n', true)
vim.cmd('wincmd p')
local cur_win_nr = vim.fn.winnr()
if ori_win_nr == cur_win_nr then
vim.api.nvim_feedkeys(k('<C-w><C-w>'), 'n', true)
end
local win_id = vim.api.nvim_get_current_win()
local config = vim.api.nvim_win_get_config(win_id)
if config.relative ~= '' and config.focusable == false then
vim.api.nvim_feedkeys(k('<C-w><C-w>'), 'n', true)
end
end)
-- <Backspace> to jump clockwise
vim.keymap.set('n', '<Backspace>', '<C-w>W')
-- split
vim.keymap.set('n', '<Leader>s', vim.cmd.split, { desc = 'Split U/D' })
vim.keymap.set('n', '<Leader>v', vim.cmd.vsplit, { desc = 'Split L/R' })
vim.keymap.set('n', '<Leader>S', vim.cmd.new, { desc = 'Split U/D new' })
vim.keymap.set('n', '<Leader>V', vim.cmd.vnew, { desc = 'split L/R new' })
-- close
vim.keymap.set('n', '<Leader>c', '<C-w>c', { desc = 'Close current window' })
vim.keymap.set('n', '<Leader>o', '<C-w>o', { desc = 'Close other windows' })
-- open window arrangment
vim.keymap.set('n', '<Leader>wh', function() vim.cmd [[topleft vertical split]] end, { desc = 'Split far left' })
vim.keymap.set('n', '<Leader>wj', function() vim.cmd [[botright split]] end, { desc = 'Split far bottom' })
vim.keymap.set('n', '<Leader>wk', function() vim.cmd [[topleft split]] end, { desc = 'Split far top' })
vim.keymap.set('n', '<Leader>wl', function() vim.cmd [[botright vertical split]] end, { desc = 'Split far right' })
-- tab, next and previous
vim.keymap.set('n', '<M-t>', ':tabnew<CR>')
vim.keymap.set('t', '<M-t>', '<C-\\><C-o>:tabnew<CR>')
vim.keymap.set('n', '<M-w>', ':tabclose')
vim.keymap.set('n', '<M-[>', 'gT')
vim.keymap.set('n', '<M-]>', 'gt')
vim.keymap.set('t', '<M-[>', [[<C-\><C-n>gT]])
vim.keymap.set('t', '<M-]>', [[<C-\><C-n>gt]])
for i = 1, 9, 1 do
vim.keymap.set('n', '<C-' .. i .. '>', i .. 'gt', { desc = 'Goto ' .. i .. ' tab' })
vim.keymap.set('t', '<C-' .. i .. '>', i .. '<C-\\><C-n>gt', { desc = 'Goto ' .. i .. ' tab' })
end
-- edit current buf in a new tab
vim.api.nvim_create_user_command('TabnewEditBuf', function()
vim.cmd [[exec 'tabe +buf\ ' . bufnr()]]
end, {})
-- window full screen plugin
vim.keymap.set('n', '<C-Enter>', vim.cmd.WinFullScreen)
-- previous and next buffer
vim.keymap.set('n', 'H', '<CMD>bprevious<CR>')
vim.keymap.set('n', 'L', '<CMD>bnext<CR>')
--- }}}
-- Fold {{{
-- vim.o.foldmethod = 'marker'
vim.o.foldcolumn = 'auto' -- nvim-spec
vim.o.foldlevel = 99
vim.o.foldlevelstart = 99
-- vim.o.foldopen = 'all'
vim.o.foldopen = 'block,hor,mark,percent,quickfix,search,tag,undo,insert'
-- toggle fold
--
-- foldexpr (e.g. treesitter's markdown query) deliberately flattens the
-- blank separator line before the next heading/list/etc. to an outer
-- level, purely so closed siblings stack without a gap. Structurally that
-- line belongs to the parent; psychologically a human reading top-to-bottom
-- still considers it part of whatever deeper content just ended, no matter
-- what foldlevel() says. Toggling by strict foldlevel containment therefore
-- closes/opens the wrong (much bigger) fold whenever the cursor sits on one
-- of these flattened lines.
--
-- The same query also folds lists, blockquotes etc., not just ATX headings
-- -- e.g. a list right under a heading gets its own deeper fold. <Space>
-- should never toggle one of those; it should always resolve to the
-- nearest heading, treating list/blockquote/etc. folds as transparent.
--
-- Fix, in two stateless phases (recomputed fresh every press, so toggling
-- stays symmetric even when the cursor never moves):
-- 1. Walk backward over the run of lines flattened to the cursor's own
-- level; if that run is preceded by something deeper, step into it.
-- 2. From there, climb to that fold's true start, and if it isn't an ATX
-- heading, keep climbing to the parent fold's start until one is.
local function is_heading(text)
return text:match('^#+%s') ~= nil
end
-- First line of the fold containing `lnum`, given `lnum` is already known
-- to be at foldlevel `level` (walks back while the level stays >= that,
-- i.e. while still inside the same fold or a nested one).
local function fold_start_at(lnum, level)
local s = lnum
while s > 1 and vim.fn.foldlevel(s - 1) >= level do
s = s - 1
end
return s
end
local function toggle_fold()
local lnum = vim.fn.line('.')
-- Phase 1: attribute a flattened separator line to the deeper content
-- that precedes it, if any.
local level = vim.fn.foldlevel(lnum)
local probe = lnum
while probe > 1 and vim.fn.foldlevel(probe - 1) == level do
probe = probe - 1
end
if probe > 1 and vim.fn.foldlevel(probe - 1) > level then
probe = probe - 1
end
-- Phase 2: climb past non-heading folds (list, blockquote, ...) to the
-- nearest ancestor whose fold actually starts on an ATX heading.
local target
local p, plevel = probe, vim.fn.foldlevel(probe)
while plevel > 0 do
local start = fold_start_at(p, plevel)
if is_heading(vim.fn.getline(start)) then
target = start
break
end
p = start - 1
if p < 1 then break end
plevel = vim.fn.foldlevel(p)
end
target = target or probe
local closed = vim.fn.foldclosed(target)
if closed > 0 then
vim.cmd(closed .. 'foldopen')
else
vim.cmd(target .. 'foldclose')
end
end
vim.keymap.set('n', '<Space>', toggle_fold, { silent = true, desc = 'Toggle the nearest heading fold, transparent to gaps/lists/blockquotes' })
vim.keymap.set('n', 'z[', function()
local current_foldlevel = vim.call('foldlevel', '.')
local line = vim.fn.line('.')
while line >= 1 do
line = line - 1
if vim.fn.foldlevel(line) < current_foldlevel then
break
end
end
vim.call('cursor', { line, '.' })
end, { desc = 'Goto parent fold' })
-- }}}
-- Editing (buffer) {{{
vim.o.expandtab = true
vim.o.tabstop = 4
vim.o.shiftwidth = 4
vim.opt.whichwrap:append('<,>,[,],l,h')
vim.opt.nrformats:append('alpha')
vim.opt.iskeyword:append('-') -- mainly for dictionary lookup
-- clipboard-osc52
vim.o.clipboard = 'unnamedplus'
vim.keymap.set('n', 'j', 'gj', { desc = 'gj' })
vim.keymap.set('n', 'k', 'gk', { desc = 'gk' })
vim.cmd[[xnoremap <expr> j mode() =~ 'V\\|' ? 'j' : 'gj']]
vim.cmd[[xnoremap <expr> k mode() =~ 'V\\|' ? 'k' : 'gk']]
-- Make U opposite to u.
vim.keymap.set('n', 'U', '<C-r>', { desc = 'Redo' })
-- leave cursor in the end of visual block
vim.keymap.set('v', 'y', 'ygv<Esc>')
vim.keymap.set('n', 'P', 'gP')
-- select pasted content
vim.cmd [[nnoremap <expr> gp '`[' . getregtype()[0] . '`]']]
-- vim.keymap.set("n", "gp", "`[v`]", { desc = "Select last pasted text" })
-- indent the just pasted content
vim.keymap.set('n', '<Leader>P=', '`[V`]==', { desc = 'Indent just pasted' })
vim.keymap.set('n', '<Leader>PP', 'p`[V`]==', { desc = 'Paste and indent' })
-- - to g_ last non-blank char
vim.keymap.set('', '-', 'g_')
-- swap ^ and 0 for convenience
vim.keymap.set('', '0', '^')
vim.keymap.set('', '^', '0')
-- move in insert mode
vim.keymap.set({ 'i', 'c' }, '<M-h>', '<Left>')
vim.keymap.set({ 'i', 'c' }, '<M-l>', '<Right>')
vim.keymap.set({ 'i', 'c' }, '<M-j>', '<Down>')
vim.keymap.set({ 'i', 'c' }, '<M-k>', '<Up>')
vim.keymap.set({ 'i', 'c' }, '<M-6>', '<Home>')
vim.keymap.set({ 'i', 'c' }, '<M-4>', '<End>')
vim.keymap.set('i', '<M-->', '<PageDown>')
vim.keymap.set('i', '<M-=>', '<PageUp>')
-- "reload" buffer
vim.keymap.set('n', '<M-e>', '<cmd>e %<CR>')
-- "reload" filetype, hack for highlight and folding
vim.keymap.set('n', '<M-C-l>', function()
vim.t.lbr = vim.wo.linebreak
vim.bo.filetype = vim.o.filetype
-- WriteRoom
if vim.t.showtabline_ori ~= nil then
vim.wo.number = false
end
vim.wo.linebreak = vim.t.lbr
vim.wo.foldmethod = vim.o.foldmethod
vim.print('Refresh the filetype.')
if vim.call('foldlevel', '.') > 0 then
vim.cmd.normal [[zv]]
end
end)
-- <M-s> update/write
vim.keymap.set({ 's', 'i', 'n', 'v' }, '<M-s>', function()
print(select(2, pcall(vim.cmd.update)))
end)
-- page up / down
vim.keymap.set('', '<C-k>', '<C-b>')
vim.keymap.set('', '<C-j>', '<C-f>')
-- search
vim.keymap.set('n', '*', '*``') -- or :keepjumps
vim.keymap.set('n', '#', '#``')
vim.keymap.set('n', '<Leader>ns', function() vim.fn.setreg('/', '') end, { desc = 'Clear search' })
vim.keymap.set('n', '<Leader>nh', function() vim.o.hlsearch = false end, { desc = 'Hide search' })
vim.keymap.set('n', '<Leader>h', function() vim.o.hlsearch = not vim.o.hlsearch end, { desc = 'Hide/show search' })
vim.keymap.set('v', '<Leader>/', 'y/<C-r>=@"<CR><CR>', { desc = 'Search selected' })
vim.api.nvim_create_user_command('Search2LocList', function()
vim.cmd('lvimgrep "' .. vim.fn.getreg('/') .. '" %')
vim.cmd.lwindow()
end, {})
-- Keeping the cursor centered.
vim.keymap.set('n', '<C-d>', '<C-d>zz', { desc = 'Scroll downwards' })
vim.keymap.set('n', '<C-u>', '<C-u>zz', { desc = 'Scroll upwards' })
vim.keymap.set('n', 'n', 'nzzzv', { desc = 'Next result' })
vim.keymap.set('n', 'N', 'Nzzzv', { desc = 'Previous result' })
-- Indent while remaining in visual mode.
vim.keymap.set('v', '<', '<gv')
vim.keymap.set('v', '>', '>gv')
-- highlight/blink yank area
vim.api.nvim_create_autocmd(
{ 'TextYankPost' },
{
pattern = { '*' },
callback = function()
vim.hl.on_yank({ timeout = 500 })
end,
})
-- yank
vim.keymap.set('n', 'Y', '^yg_')
-- toggle conceallevel
vim.keymap.set('n', '<Leader>L', function()
if vim.wo.conceallevel == 2 then
vim.wo.conceallevel = 0
elseif vim.wo.conceallevel == 0 then
vim.wo.conceallevel = 2
end
end, { desc = 'Toggle conceallevel 0/2' })
-- while opening file, jump to last known cursor position (last location)
-- :h lua-guide-autocommands-group
local vim_startup_aug = vim.api.nvim_create_augroup('vimStartup', { clear = true })
vim.api.nvim_create_autocmd({ 'BufReadPost' }, {
pattern = '*',
group = vim_startup_aug,
callback = function()
local reg_doublequote_position = vim.fn.line([['"]])
if reg_doublequote_position >= 1 and
reg_doublequote_position <= vim.fn.line('$') and
vim.bo.filetype ~= 'commit' then
vim.cmd.normal(k([[g`"]]))
end
end,
})
-- Capitalization of the current line
-- Capitalize all words in titles of publications and documents, except a, an, the, at, by, for, in, of, on, to, up, and, as, but, or, and nor.
-- https://taptoe.wordpress.com/2013/02/06/vim-capitalize-every-first-character-of-every-word-in-a-sentence/
vim.api.nvim_create_user_command('Capitalize', function()
vim.cmd [[s/\v^\a|\:\s\a|<%(a>|an>|and>|as>|at>|but>|by>|for>|in>|nor>|of>|on>|or>|the>|to>|up>)@!\a/\U&/g]]
end, {})
-- poorman's surrounding
-- http://www.teifel.net/projects/vim/mappings.html
vim.keymap.set('v', '<Leader>(', [[<ESC>`>a)<ESC>`<i(<ESC>`>ll]])
vim.keymap.set('v', '<Leader><', [[<ESC>`>a><ESC>`<i<<ESC>`>ll]])
vim.keymap.set('v', '<Leader>[', [[<ESC>`>a]<ESC>`<i[<ESC>`>ll]])
vim.keymap.set('v', '<Leader>{', [[<ESC>`>a}<ESC>`<i{<ESC>`>ll]])
vim.keymap.set('v', '<Leader>$', [[<ESC>`>a$<ESC>`<i$<ESC>`>ll]])
vim.keymap.set('v', '<Leader>"', [[<ESC>`>a"<ESC>`<i"<ESC>`>ll]])
vim.keymap.set('v', "<Leader>'", [[<ESC>`>a'<ESC>`<i'<ESC>`>ll]])
-- https://vi.stackexchange.com/questions/25130/close-buffer-in-the-other-instance
-- https://github.com/vim/vim/blob/master/runtime/pack/dist/opt/editexisting/plugin/editexisting.vim
-- vim.cmd.runtime('macros/editexisting.vim')
vim.api.nvim_create_autocmd({ 'SwapExists' }, {
callback = function()
vim.v.swapchoice = 'o'
vim.bo.modifiable = false
end,
})
-- Return to normal mode while losing focus
local focuslost_stopinsert = true
vim.api.nvim_create_autocmd('FocusLost', {
pattern = '*',
group = vim_startup_aug,
desc = 'Return to normal mode while losing focus',
callback = function()
if not focuslost_stopinsert then return end
vim.cmd.stopinsert()
end,
})
vim.api.nvim_create_user_command('ToggleFocusLost', function()
focuslost_stopinsert = not focuslost_stopinsert
vim.notify('FocusLost stopinsert: ' .. (focuslost_stopinsert and 'on' or 'off'))
end, { desc = 'Toggle stopinsert on FocusLost' })
-- curly quote
vim.keymap.set('i', "<M-'>", '’')
-- auto enter zsh vi-mode insert mode
vim.api.nvim_create_autocmd({ "BufEnter", "WinEnter" }, {
pattern = "term://*",
callback = function()
vim.cmd("startinsert")
end,
})
vim.api.nvim_create_autocmd("TermOpen", {
pattern = "term://*",
callback = function()
-- Deliberately delayed: startinsert here makes Nvim start reflecting the
-- terminal's live cursor shape immediately, before the shell has even
-- exec'd and sourced its rc file. That means it captures the terminal's
-- default block cursor (see :help terminal-cursor-style) before zsh's
-- vi-mode plugin has had a chance to send its own DECSCUSR shape escape,
-- and the display never catches up. Waiting lets the shell finish
-- starting first, so the initial shape is already correct.
vim.defer_fn(function()
vim.cmd("startinsert")
end, 1000)
end,
})
-- }}}
-- Commands {{{
vim.keymap.set('n', '<M-q>', [[q:]])
vim.keymap.set('n', 'qq', [[q:]])
-- command mode to search
vim.keymap.set('c', '<C-k>', '<Up>')
vim.keymap.set('c', '<C-j>', '<Down>')
-- google search selection
-- TODO or better https://github.com/lalitmee/browse.nvim
local function uri_encode(string)
local vf = vim.fn
return vf.substitute(vf.iconv(string, 'latin1', 'utf-8'),'[^A-Za-z0-9_.~-]','\\="%".printf("%02X",char2nr(submatch(0)))','g')
end
vim.keymap.set('v', '<M-g>', function()
vim.cmd.normal [["zy]]
vim.ui.open('https://www.google.com/search?q=' .. uri_encode(vim.fn.eval('@z')))
end)
-- look up word in dictionary
vim.keymap.set('n', '<M-d>', function()
vim.ui.open('dict://' .. vim.fn.expand('<cword>'))
end)
-- goto for next or previous link
vim.g.url_pattern = [[[[:alpha:]-]\+:\/\/[^ "'>\])]\+]]
vim.g.markdown_link_pattern = [[\(\[[^\^]\{-}\]\([:\[]\)\@!\(([^ ]\{-}\%(\s"[^"]\{-}"\)\?)\)\?\)]]
vim.g.link_pattern = vim.g.url_pattern .. [[\|]] .. vim.g.markdown_link_pattern
local function move_cursor_to_link(backward)
local link_pattern = vim.b.link_pattern or vim.g.link_pattern
vim.fn.search(link_pattern, 's' .. backward)
end
vim.keymap.set('n', 'g[', function() move_cursor_to_link('b') end, { desc = 'Goto previous link' })
vim.keymap.set('n', 'g]', function() move_cursor_to_link('') end, { desc = 'Goto next link' })
-- diffthis
vim.api.nvim_create_user_command('Diffthis', function()
vim.cmd.diffthis()
vim.wo.wrap = true
vim.api.nvim_feedkeys(k('<C-w>w'), 'n', true)
vim.wo.wrap = true
vim.cmd.diffthis()
end, {})
-- spell including cjk
-- https://stackoverflow.com/questions/18196399/exclude-capitalized-words-from-vim-spell-check
-- vim.cmd[[syn match myCapitalWords +\<\w*[A-Z]\K*\>\|'s+ contains=@NoSpell]]
local function toggle_spell(eng_dialect)
if vim.opt.spell:get() then
vim.opt_local.spell = false or nil
else
vim.opt_local.spell = true
vim.opt_local.spelllang = 'en_' .. eng_dialect .. ',cjk'
end
end
vim.api.nvim_create_user_command('SpellGB', function()
toggle_spell('gb')
end, {})
vim.api.nvim_create_user_command('SpellUS', function()
toggle_spell('us')
end, {})
-- Toggle the quickfix/loclist window -- {{{
-- When toggling these, ignore error messages and restore the cursor to the original window when opening the list
local silent_mods = { mods = { silent = true, emsg_silent = true } }
vim.keymap.set('n', '<Leader>xq', function()
if vim.fn.getqflist({ winid = 0 }).winid ~= 0 then
vim.cmd.cclose(silent_mods)
elseif #vim.fn.getqflist() > 0 then
local win = vim.api.nvim_get_current_win()
vim.cmd.copen(silent_mods)
if win ~= vim.api.nvim_get_current_win() then
vim.cmd.wincmd 'p'
end
end
end, { desc = 'Toggle quickfix list' })
vim.keymap.set('n', '<Leader>xl', function()
if vim.fn.getloclist(0, { winid = 0 }).winid ~= 0 then
vim.cmd.lclose(silent_mods)
elseif #vim.fn.getloclist(0) > 0 then
local win = vim.api.nvim_get_current_win()
vim.cmd.lopen(silent_mods)
if win ~= vim.api.nvim_get_current_win() then
vim.cmd.wincmd 'p'
end
end
end, { desc = 'Toggle location list' })
-- and navigating through the items.
vim.keymap.set('n', '[q', '<cmd>cprev<cr>zvzz', { desc = 'Previous quickfix item' })
vim.keymap.set('n', ']q', '<cmd>cnext<cr>zvzz', { desc = 'Next quickfix item' })
vim.keymap.set('n', '[l', '<cmd>lprev<cr>zvzz', { desc = 'Previous loclist item' })
vim.keymap.set('n', ']l', '<cmd>lnext<cr>zvzz', { desc = 'Next loclist item' })
-- }}}
-- Inspect
vim.keymap.set('n', '<M-i>', '<CMD>Inspect<CR>')
-- }}}
-- Abbreviations {{{
vim.keymap.set('ca', 'xfn', 'echo expand("%:p")')
vim.keymap.set('ca', 'xfnc', 'let @+ = expand("%:p")')
vim.keymap.set('ca', 'ss', function()
vim.cmd [[bel 10new]]
vim.wo.scrolloff = 0
end)
vim.keymap.set('ia', 'xdate', '<C-r>=strftime("%Y-%m-%d %H:%M:%S")<CR>')
-- }}}
require('lsp')
-- auto project-based dir
vim.o.autochdir = false
local root_markers = { ".git", "package.json", "Makefile", "pyproject.toml", "Cargo.toml" }
vim.api.nvim_create_autocmd("BufEnter", {
pattern = "*",
callback = function(args)
local buf = args.buf
-- skip unnamed/special buffers (terminals, help, etc.)
if vim.bo[buf].buftype ~= "" then return end
local root = vim.fs.root(buf, root_markers)
if root and root ~= vim.fn.getcwd() then
-- or lcd if wants per-window roots
vim.cmd.cd(root)
end
end,
})
-- auto treesitter
vim.api.nvim_create_autocmd('FileType', {
callback = function(args)
if vim.bo[args.buf].filetype == 'markdown' then return end
-- only when a parser actually exists for this filetype
if vim.treesitter.get_parser(args.buf, nil, { error = false }) then
-- optional: skip very large files, TS parses the whole buffer
local name = vim.api.nvim_buf_get_name(args.buf)
local st = name ~= '' and vim.uv.fs_stat(name)
if st and st.size > 512 * 1024 then return end
-- no need in new treesitter version
-- vim.treesitter.start(args.buf)
vim.wo[0][0].foldexpr = 'v:lua.vim.treesitter.foldexpr()'
vim.wo[0][0].foldmethod = 'expr'
end
end,
})
-- Bootstrap lazy.nvim
local lazypath = vim.fn.stdpath("data") .. "/lazy/lazy.nvim"
if not (vim.uv or vim.loop).fs_stat(lazypath) then
local lazyrepo = "https://github.com/folke/lazy.nvim.git"
vim.fn.system({ "git", "clone", "--filter=blob:none", "--branch=stable", lazyrepo, lazypath })
end
vim.opt.rtp:prepend(lazypath)
-- Setup lazy.nvim
require("lazy").setup({
spec = {
-- import your plugins
{ import = "plugins" },
},
-- Configure any other settings here. See the documentation for more details.
-- colorscheme that will be used when installing plugins.
install = { colorscheme = { "habamax" } },
-- automatically check for plugin updates
checker = { enabled = false },
dev = {
path = "~/Developer/vim/scripts",
fallback = true,
},
change_detection = {
-- automatically check for config file changes and reload the ui
enabled = true,
notify = false, -- get a notification when changes are found
},
})