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
|
" One vimrc for Mac and Linux. Source of truth: /Users/xs/dev_env/core/vimrc
" Mac: cp core/vimrc ~/.vimrc Linux: sudo bash core/vim.sh (copies it to /etc/vimrc or /etc/vim/vimrc)
set nocompatible " /etc/vimrc is read before vim leaves vi mode; without this \ continuations and <leader> break
set backspace=indent,eol,start " vim default is empty (no backspacing over indent/eol/insert start); stock /etc/vimrc and defaults.vim set it, both replaced/skipped here
" gt: go to next tab (right, wraps)
" gT: go to previous tab (left, wraps)
" 2gt: go to tab number 2 (counted from 1 at the left)
" :q: close the current window, and the tab too if it was the last window in it
" ZZ: save if changed, then close the window (and the tab if it was the last window in it)
" ZQ: close the window WITHOUT saving (like :q!), and the tab too if it was the last window in it
" g<Tab>: jump to the last-accessed tab (press g, release, then Tab); toggles between two tabs
" Ctrl-w w: cycle windows in this tab, e.g. into and out of the K popup (Ctrl-w p toggles back)
" 7G12|: go to line 7, column 12 (normal-mode keys, no colon; 3w moves 3 words)
" :set foldcolumn=0 : hide the 12-wide fold gutter (:set foldcolumn=12 brings it back)
" Reset an edited cargo dependency: delete ~/.cargo/registry/src/<index>/<crate>-<ver>/ then run cargo fetch
"
" Setup (LSP servers below are optional — each is guarded by executable()):
" plugins: curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
" https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
" then launch vim and run :PlugInstall
" rust: curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
" rustup component add rust-analyzer
" python: curl -LsSf https://astral.sh/uv/install.sh | sh
" uv tool install ruff && uv tool install pyright
"
" Stop vim from auto-loading defaults.vim, which loads AFTER this file and
" would otherwise silently override settings here. Everything is in this file.
let g:skip_defaults_vim = 1
" ===== Shortcuts: one line each, <leader> = \ (comment follows the |) =====
inoremap <C-a> <Home>| " insert Ctrl-a: jump to line start
inoremap <C-e> <End>| " insert Ctrl-e: jump to line end
inoremap <silent><expr> <C-l> pumvisible() ? "\<C-e>" : asyncomplete#force_refresh()| " insert Ctrl-l: toggle completion menu
inoremap <expr> <Tab> pumvisible() ? "\<C-n>" : "\<Tab>"| " in menu Tab: next item
inoremap <expr> <S-Tab> pumvisible() ? "\<C-p>" : "\<S-Tab>"| " in menu Shift-Tab: previous item
inoremap <expr> <CR> pumvisible() ? "\<C-y>" : "\<CR>"| " in menu Enter: accept item
nnoremap <C-a> 0| " Ctrl-a: jump to line start
nnoremap <C-e> $| " Ctrl-e: jump to line end
nnoremap <silent> <C-l> :<C-U>nohlsearch<CR><C-l>| " Ctrl-l: clear search highlight
nnoremap <silent> <C-p> :<C-U>Files<CR>| " Ctrl-p: fuzzy-find a file
nnoremap <silent> <leader>rg :<C-U>Rg<CR>| " \rg: search text in project
nnoremap <silent> <leader>b :<C-U>Buffers<CR>| " \b: list open buffers
nnoremap <silent> <leader>n :<C-U>NERDTreeToggle<CR>| " \n: toggle file tree
nnoremap <silent> gd :<C-U>call <SID>GotoDef()<CR>| " gd: go to definition (Ctrl-o back)
nnoremap <silent> gr :<C-U>LspReferences<CR>| " gr: list every place the symbol under the cursor is used (Enter jumps)
nnoremap <silent> ]r :<C-U>execute v:count1 . 'cnext'<CR>| " ]r: next use from the gr list (across files)
nnoremap <silent> [r :<C-U>execute v:count1 . 'cprevious'<CR>| " [r: previous use from the gr list
nnoremap <silent> ]e :<C-U>LspNextDiagnostic<CR>| " ]e: jump to the next error/warning in this file
nnoremap <silent> [e :<C-U>LspPreviousDiagnostic<CR>| " [e: jump to the previous error/warning in this file
nnoremap <silent> gy :<C-U>tab LspTypeDefinition<CR>| " gy: go to type definition in a new tab (e -> struct DirEntry)
nnoremap <silent> <leader>k :<C-U>call ToggleHover()<CR>| " \k: toggle hover docs
nnoremap <silent> K :<C-U>call ToggleHover()<CR>| " K: toggle hover docs (same as \k)
nnoremap <silent> <leader>D :<C-U>LspDocumentation<CR>| " \D: show documentation
nnoremap <silent> <leader>e :<C-U>call ToggleDiagnostic()<CR>| " \e: show error on this line
nnoremap <silent> <leader>l :<C-U>LspDocumentDiagnostics<CR>| " \l: list errors in this file
nnoremap <silent> <leader>L :<C-U>LspDocumentDiagnostics --buffers=*<CR>| " \L: list every error the servers know (Rust: whole crate; Python: open files)
nnoremap <silent> <leader>a :<C-U>LspCodeAction<CR>| " \a: code actions popup
nnoremap <silent> <leader>rn :<C-U>LspRename<CR>| " \rn: rename symbol
nnoremap <silent> <leader>f :<C-U>LspDocumentFormat<CR>| " \f: format file
nnoremap <silent> <leader>em :<C-U>call ExpandMacro()<CR>| " \em: expand macro under cursor
" ===== Clipboard: every yank goes to both places, neither blocks; paste is always local =====
" local: OSC 52 sends @" to the terminal you type in (inside tmux needs set-clipboard on)
" remote: background ssh job writes @" to RAM file /dev/shm/clip/buf on g:clip_host; failure is silent
let g:clip_host = 'root@p.noml.ch'
let g:clip = ['ssh', '-o', 'ControlMaster=auto', '-o', 'ControlPersist=yes', '-o', 'ControlPath=~/.ssh/cm-%C', '-o', 'ServerAliveInterval=30', '-o', 'ConnectTimeout=3', '-o', 'StrictHostKeyChecking=no', '-o', 'UserKnownHostsFile=/dev/null', '-o', 'LogLevel=ERROR', g:clip_host]
augroup clipboard
au!
au TextYankPost * call echoraw("\e]52;c;" . (exists('*str2blob') ? base64_encode(str2blob(split(@", "\n", 1))) : system("base64 | tr -d '\\n'", @")) . "\x07")
au TextYankPost * let g:clip_job = job_start(g:clip + ['umask 077; mkdir -p /dev/shm/clip && cat >/dev/shm/clip/new && mv /dev/shm/clip/new /dev/shm/clip/buf'], {'in_io': 'pipe', 'out_io': 'null', 'err_io': 'null'}) | call ch_sendraw(g:clip_job, @") | call ch_close_in(g:clip_job)
augroup END
" ===== end clipboard =====
filetype plugin indent on
set number
set wrap
set breakindent
set breakindentopt=shift:1
set expandtab
set shiftwidth=4
set softtabstop=4
set tabstop=4
set noautoindent
set nosmartindent
set hlsearch
set incsearch
set ignorecase
set smartcase
set scrolloff=8
set signcolumn=no
set foldcolumn=12
set laststatus=2
set statusline=%F
set wildmenu
set splitright
set splitbelow
set hidden " gd/LSP jumps reuse the window even with unsaved changes
set noswapfile
set regexpengine=2
set completeopt=menu,menuone,noinsert,noselect
set mouse=a
if has('mouse_sgr')
set ttymouse=sgr
endif
set undofile
set undodir=~/.vim/undo
if !isdirectory($HOME . '/.vim/undo')
call mkdir($HOME . '/.vim/undo', 'p')
endif
if has('termguicolors')
if !empty($TMUX)
let &t_8f = "\<Esc>[38;2;%lu;%lu;%lum"
let &t_8b = "\<Esc>[48;2;%lu;%lu;%lum"
endif
set termguicolors
endif
colorscheme zellner
" Files rustup and cargo manage (toolchains, downloaded crates) open locked; :setl ma noro to override
function! s:LockIfManaged() abort
if !exists('s:managed')
let l:cargo = empty($CARGO_HOME) ? expand('~/.cargo') : $CARGO_HOME
let s:managed = [l:cargo . '/registry', l:cargo . '/git']
if executable('rustup')
call add(s:managed, trim(system('rustup show home')))
endif
endif
for l:dir in s:managed
if stridx(expand('%:p'), l:dir . '/') == 0
setlocal readonly nomodifiable
return
endif
endfor
endfunction
augroup managed_readonly
autocmd!
autocmd BufReadPost * call s:LockIfManaged()
augroup END
" vim-plug is optional: skip the plugin block until plug.vim is installed (see Setup above)
if filereadable(expand('~/.vim/autoload/plug.vim'))
call plug#begin('~/.vim/plugged')
Plug 'prabirshrestha/async.vim'
Plug 'prabirshrestha/vim-lsp'
Plug 'prabirshrestha/asyncomplete.vim'
Plug 'prabirshrestha/asyncomplete-lsp.vim'
Plug 'rust-lang/rust.vim'
Plug 'junegunn/fzf', { 'do': { -> fzf#install() } }
Plug 'junegunn/fzf.vim'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-surround'
Plug 'tpope/vim-fugitive'
Plug 'airblade/vim-gitgutter'
Plug 'preservim/nerdtree'
call plug#end()
endif
let g:gitgutter_sign_column_always = 0
" rust-analyzer: a file that is a target of its nearest Cargo.toml (src/ examples/ tests/
" benches/ build.rs, or its path is in the manifest) uses that crate. Any other .rs file is
" loaded standalone via detachedFiles, with checkOnSave off (cargo check needs a Cargo.toml).
function! RustCrate() abort
let l:p = expand('%:p')
let l:d = lsp#utils#find_nearest_parent_file_directory(l:p, 'Cargo.toml')
if empty(l:d) | return '' | endif
let l:d = substitute(fnamemodify(l:d, ':p'), '/$', '', '')
let l:rel = stridx(l:p, l:d . '/') == 0 ? l:p[len(l:d) + 1:] : ''
if l:rel =~# '^\(src\|examples\|tests\|benches\)/\|^build\.rs$'
\ || (!empty(l:rel) && stridx(join(readfile(l:d . '/Cargo.toml')), '"' . l:rel . '"') >= 0)
return l:d
endif
return ''
endfunction
function! s:RustAddDetached() abort
let l:p = expand('%:p')
if empty(l:p) || !isdirectory(fnamemodify(l:p, ':h')) || index(g:ra_init.detachedFiles, l:p) >= 0 | return 0 | endif
call add(g:ra_init.detachedFiles, l:p)
return 1
endfunction
" Called once at server start (root_uri is read just before the init options).
function! RustRoot() abort
let l:c = RustCrate()
let g:ra_init.checkOnSave = empty(l:c) ? v:false : v:true
if !empty(l:c) | return l:c | endif
call s:RustAddDetached()
return expand('%:p:h')
endfunction
let g:ra_init = {
\ 'completion': {'autoimport': {'enable': v:true}, 'postfix': {'enable': v:true}},
\ 'checkOnSave': v:true, 'detachedFiles': []}
augroup rust_detached
au!
" standalone file opened while the server already runs: add it live (check setting untouched)
au BufEnter *.rs if exists('g:lsp_loaded') && lsp#get_server_status('rust-analyzer') ==# 'running'
\ && empty(RustCrate()) && s:RustAddDetached()
\ | call lsp#update_workspace_config('rust-analyzer', {'rust-analyzer': g:ra_init}) | endif
augroup END
" Language servers are looked up on $PATH (exepath); a server that isn't on $PATH is skipped
" rust-analyzer: normally the rustup proxy shim (portable across toolchains/machines)
let s:ra = exepath('rust-analyzer')
if !empty(s:ra)
au User lsp_setup call lsp#register_server({
\ 'name': 'rust-analyzer', 'allowlist': ['rust'],
\ 'cmd': {server_info -> [s:ra]},
\ 'root_uri': {server_info -> lsp#utils#path_to_uri(RustRoot())},
\ 'initialization_options': g:ra_init,
\ 'workspace_config': {'rust-analyzer': g:ra_init}})
endif
let s:ruff = exepath('ruff')
if !empty(s:ruff)
au User lsp_setup call lsp#register_server({
\ 'name': 'ruff',
\ 'cmd': {server_info -> [s:ruff, 'server']},
\ 'allowlist': ['python'],
\ })
endif
let s:uv_bin = exepath('uv')
if !empty(exepath('ty')) && !empty(s:uv_bin)
" Launched through `uv run` (not the raw path) so it picks up whichever
" project's .venv is active via cwd/VIRTUAL_ENV.
au User lsp_setup call lsp#register_server({
\ 'name': 'ty',
\ 'cmd': {server_info -> [s:uv_bin, 'run', 'ty', 'server']},
\ 'allowlist': ['python'],
\ })
endif
" tofu-ls (OpenTofu/Terraform .tf) for go-to-definition
let s:tofu_ls = exepath('tofu-ls')
if !empty(s:tofu_ls)
au User lsp_setup call lsp#register_server({
\ 'name': 'tofu-ls',
\ 'cmd': {server_info -> [s:tofu_ls, 'serve']},
\ 'allowlist': ['terraform', 'terraform-vars'],
\ })
endif
" gopls (Go) for go-to-definition
let s:gopls = exepath('gopls')
if !empty(s:gopls)
au User lsp_setup call lsp#register_server({
\ 'name': 'gopls',
\ 'cmd': {server_info -> [s:gopls]},
\ 'allowlist': ['go'],
\ 'root_uri': {server_info -> lsp#utils#path_to_uri(lsp#utils#find_nearest_parent_file_directory(lsp#utils#get_buffer_path(), 'go.mod'))},
\ })
endif
" Force per-keystroke LSP sync for Python (vim-lsp only syncs on
" InsertLeave/TextChanged by default, not while actively typing).
autocmd FileType python autocmd TextChangedI <buffer> doautocmd <nomodeline> TextChanged
let g:lsp_diagnostics_echo_cursor = 1
let g:lsp_diagnostics_float_cursor = 0
let g:lsp_diagnostics_virtual_text_enabled = 0
let g:lsp_diagnostics_signs_enabled = 0
let g:lsp_document_highlight_enabled = 0
let g:lsp_preview_float = 0
let g:lsp_hover_ui = 'preview'
let g:lsp_code_action_ui = 'float' " \a = one popup menu, not 3 windows
let g:lsp_signature_help_enabled = 0
function! s:set_preview_height() abort
let &previewheight = max([10, &lines * 40 / 100])
endfunction
call s:set_preview_height()
autocmd VimResized * call s:set_preview_height()
" Toggle hover docs in the preview window.
function! ToggleHover() abort
for l:nr in range(1, winnr('$'))
if getwinvar(l:nr, '&previewwindow')
pclose
return
endif
endfor
LspHover
endfunction
" Show the current line's diagnostic in a preview window.
function! ToggleDiagnostic() abort
for l:nr in range(1, winnr('$'))
if getwinvar(l:nr, '&previewwindow')
pclose
return
endif
endfor
let l:diag = lsp#internal#diagnostics#under_cursor#get_diagnostic()
if empty(l:diag)
echo 'No diagnostic on this line'
return
endif
let l:cur = win_getid()
botright new
execute 'resize ' . &previewheight
setlocal buftype=nofile bufhidden=wipe noswapfile previewwindow
call setline(1, split(l:diag['message'], "\n"))
setlocal nomodifiable
call win_gotoid(l:cur)
endfunction
" rust-analyzer macro expansion (LSP extension, no built-in command).
function! ExpandMacro() abort
let l:params = {
\ 'textDocument': { 'uri': lsp#utils#get_buffer_uri() },
\ 'position': lsp#get_position(),
\ }
call lsp#send_request('rust-analyzer', {
\ 'method': 'rust-analyzer/expandMacro',
\ 'params': l:params,
\ 'on_notification': function('s:expand_macro_handler'),
\ })
endfunction
function! s:expand_macro_handler(data) abort
if !has_key(a:data, 'response') || empty(a:data['response'])
echo 'ExpandMacro: no response / not a macro'
return
endif
let l:result = get(a:data['response'], 'result', v:null)
if l:result is v:null
echo 'ExpandMacro: nothing to expand at cursor'
return
endif
botright new
setlocal buftype=nofile bufhidden=wipe noswapfile filetype=rust
call setline(1, split('// expansion of: ' . l:result['name'], "\n"))
call append(line('$'), split(l:result['expansion'], "\n"))
endfunction
" gd: say when rust-analyzer is still starting/indexing instead of a false "No definition found"
let g:lsp_work_done_progress_enabled = 1
function! s:GotoDef() abort
if &filetype ==# 'rust'
let l:st = lsp#get_server_status('rust-analyzer')
if l:st !=# 'running'
echo 'rust-analyzer ' . l:st . ', try again in a few seconds'
return
endif
let l:busy = filter(copy(lsp#get_progress()),
\ {_, p -> p['server'] ==# 'rust-analyzer' && get(p, 'title', '') !~? 'check'})
if !empty(l:busy)
echo 'rust-analyzer still indexing: ' . get(l:busy[0], 'title', '') . ' ' . get(l:busy[0], 'message', '')
return
endif
endif
tab LspDefinition
endfunction
" Numbered tab labels (1:main.rs 2:fs.rs): the number is what Ngt jumps to.
function! TabLine() abort
let l:s = ''
for l:i in range(1, tabpagenr('$'))
let l:buf = tabpagebuflist(l:i)[tabpagewinnr(l:i) - 1]
let l:name = fnamemodify(bufname(l:buf), ':t')
if l:name ==# ''
let l:name = '[No Name]'
endif
let l:hl = l:i == tabpagenr() ? '%#TabLineSel#' : '%#TabLine#'
let l:s .= l:hl . ' ' . l:i . ':' . l:name . ' '
endfor
return l:s . '%#TabLineFill#'
endfunction
set tabline=%!TabLine()
|