vimrc/init.vim

1164 lines
40 KiB
VimL

" FIRST TIME SETUP NOTES:
" Windows:
" Add the following environmental variables:
" USER
" Install git
" Neomake:
" Installation config for LaTeX: Add 'ignorechktex' to VerbEnvir in the chktex
" files.
" fyz: (Linux only! TODO: Find a windows method)
" Install fzy systemwide, or configure a custom install location below
" (search for 'g:picker_selector_executable')
" Vimtex:
" Add the following to ~/.latexmkrc, to improve the cleanup of junk
" files:
" push @generated_exts, "synctex.gz";
" push @generated_exts, "run.xml";
" push @generated_exts, "bbl";
" Linux: Install zathura
" Windows: Install sumatrapdf
" if !(has('win32') || has('win64'))
" let $BASH_ENV = "~/.bash_aliases"
" endif
" Automatically reload vimrc on changes {{{
augroup autosource
autocmd!
autocmd bufwritepost init.vim source $MYVIMRC
augroup END
" }}}
" vim-plug {{{
" Install vim-plug if it isn't already installed
if has('win32') || has('win64')
if empty(glob(stdpath('config') . '\autoload\plug.vim'))
execute '!curl -fLo ' . stdpath('config') . '\autoload\plug.vim' . ' --create-dirs ' .
\ 'https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim'
autocmd VimEnter * PlugInstall | source $MYVIMRC
endif
else
if empty(glob(stdpath('data') . '/site/autoload/plug.vim'))
silent execute '!curl -fLo ' . stdpath('data') . '/site/autoload/plug.vim' . ' --create-dirs ' .
\ 'https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim'
autocmd VimEnter * PlugInstall | source $MYVIMRC
endif
endif
" if empty(glob(stdpath('data') . '/site/autoload/let-modeline.vim'))
" silent execute '!curl -fLo ' . stdpath('data') . '/site/autoload/let-modeline.vim' . ' --create-dirs ' .
" \ 'https://raw.githubusercontent.com/LucHermitte/lh-misc/master/plugin/let-modeline.vim'
" endif
" call let-modeline#hello()
if has('win32') || has('win64')
let g:plugged_home = stdpath('data') . '\plugged' " neovim path
else
let g:plugged_home = stdpath('data') . '/plugged' " neovim path
" let g:plugged_home = '~/.vim/plugged' " vim path
endif
call plug#begin(g:plugged_home)
" vim-plug bundles {{{
" VimScript Library
Plug 'inkarkat/vim-ingo-library'
" Enable 'let' in modelines (replace the modeline with VIM:)
Plug 'vim-scripts/let-modeline.vim'
" UI related
Plug 'chriskempson/base16-vim'
Plug 'itchyny/lightline.vim'
Plug 'dracula/vim' " alternate theme
Plug 'jnurmine/Zenburn' " alternate theme
Plug 'romainl/Apprentice' " alternate theme
Plug 'connorholyday/vim-snazzy' " alternate theme
Plug 'morhetz/gruvbox' " alternate theme
Plug 'sonph/onehalf', {'rtp': 'vim/'} " altenate theme
Plug 'romainl/vim-dichromatic' " colorblind theme
" Linting
Plug 'neomake/neomake'
Plug 'fsharp/vim-fsharp', {
\ 'for': 'fsharp',
\ 'do': 'make fsautocomplete',
\}
Plug 'JuliaEditorSupport/julia-vim'
Plug 'rust-lang/rust.vim'
" Language server
Plug 'neovim/nvim-lspconfig'
" Fuzzy finding
" Plug 'jhawthorn/fzy' " Install this systemwide (or configure a manual
" location. See below)
Plug 'srstevenson/vim-picker'
Plug 'junegunn/fzf', { 'do': { -> fzf#install() } }
Plug 'junegunn/fzf.vim'
Plug 'jesseleite/vim-agriculture'
" line indentation guides
Plug 'Yggdroot/indentLine'
" commenting code
Plug 'tpope/vim-commentary'
" shell commands without having to leave vim (eg. rename)
Plug 'tpope/vim-eunuch'
" open file at linenumber via <filename>:<linenumber>
Plug 'wsdjeg/vim-fetch'
" smart view preservation (replacement of manual mkview and loadview)
" Plug 'zhimsel/vim-stay' " TODO: jry
" Todo lists
Plug 'vuciv/vim-bujo'
" Autocompletion {{{
" Deep TabNine {{{
" Plug 'zxqfl/tabnine-vim'
" }}}
" ncm2 {{{
Plug 'ncm2/ncm2'
Plug 'roxma/nvim-yarp'
Plug 'ncm2/ncm2-bufword' " adds words from current buffer
Plug 'ncm2/ncm2-path' " adds paths for current buffer, working directory, and root
Plug 'ncm2/ncm2-jedi' " adds python completion
Plug 'ncm2/ncm2-pyclang' " add C/C++ completion
Plug 'ncm2/ncm2-tern', {'do': 'npm install'} " add javascript completion
Plug 'ncm2/ncm2-html-subscope' " detect javascript/css subscope from html code
Plug 'ncm2/float-preview' " improves the completion preview window
" }}}
" VimTex
Plug 'lervag/vimtex'
" vim-instant-markdown
" Plug 'suan/vim-instant-markdown', {'for': 'markdown'}
Plug 'instant-markdown/vim-instant-markdown', {'for': 'markdown', 'do': 'yarn install'}
" SageMath
Plug 'petRUShka/vim-sage'
" Git {{{
" git diff in vim
Plug 'mhinz/vim-signify'
" Git CLI integration
Plug 'tpope/vim-fugitive'
" See http://vimcasts.org/blog/2011/05/the-fugitive-series/
" Git commit browser
Plug 'junegunn/gv.vim'
" }}}
" vim-test - run perl-tests from inside the editor
Plug 'janko-m/vim-test'
" Syntax highlighting {{{
" Bedre perl-highlighting
Plug 'vim-perl/vim-perl', { 'for': 'perl', 'do': 'make clean carp highlight-all-pragmas moose test-more try-tiny method-signatures' }
" LESS (CSS) syntax highlighting
Plug 'groenewege/vim-less'
" Mojolicious syntax highlighting
Plug 'yko/mojo.vim'
" Haskell syntax highlighting
Plug 'neovimhaskell/haskell-vim'
" OpenSCAD syntax highlighting
Plug 'salkin-mada/openscad.nvim'
" }}}
" Custom JIX modules
if $USER =~ "^jry$" && $HOSTNAME =~ "gnu"
let g:loaded_jix_jump = 1 " don't load
" let g:loaded_jix_neomake = 1 " load
let g:loaded_jix_open_url = 1 " don't load
let g:loaded_jix_perltidy = 1 " don't load
let g:loaded_jix_skeletons = 1 " don't load
let g:loaded_jix_vimtest = 1 " don't load
" let g:loaded_jix_shell = 1 " load
Plug '~/dev-utils/conf/vim'
end
" }}}
call plug#end()
" }}}
" enable plugins and indentation based on the filetype
filetype plugin indent on
" custom file extensions {{{
au BufRead,BufNewFile *.html+itjdk.ep set filetype=html.epl
au BufRead,BufNewFile *.html+stedk.ep set filetype=html.epl
au BufRead,BufNewFile *.html+isbdk.ep set filetype=html.epl
au BufRead,BufNewFile *.c.snip set filetype=c
au BufRead,BufNewFile *.cpp.snip set filetype=cpp
" }}}
" escape terminal on <Esc>
tnoremap <Esc> <C-\><C-n>
" UI config {{{
" Enable syntax highlighting
syntax on
syntax enable
set conceallevel=0
" Highlight unwanted whitespaces
function! HighlightWhitespaces()
if &ft == 'markdown'
" don't match on exactly two trailing whitespaces
match ExtraWhitespace /\S\@<=\s\%#\@<!$\|\s\{3,\}\%#\@<!$\| \+\ze\t/
else
" trailing whitespaces but not if cursor is at end of line /\s\+\%#\@<!$/
" show spaces before a tab / \+\ze\t/
match ExtraWhitespace /\s\+\%#\@<!$\| \+\ze\t/
endif
endfunction
augroup HighlightWhitespacesAugroup
autocmd!
" Apply the rule whenever the colorscheme is changed
" highlight ExtraWhitespace ctermbg=red guibg=red
autocmd ColorScheme * hi ExtraWhitespace ctermbg=Red ctermfg=White guibg=Red guifg=White
" Show trailing whitespace (but not when editing the end of the line) and spaces before a tab.
" Also ensure the highlighting is applied when not editing the end of the line anymore ;-)
" let HighlightWhitespacesBlacklist = ['markdown']
autocmd BufWinEnter,InsertLeave,CursorMovedI * :call HighlightWhitespaces()
" autocmd BufWinEnter,InsertLeave,CursorMovedI * if index(HighlightWhitespacesBlacklist, &ft) < 0 | match ExtraWhitespace /\s\+\%#\@<!$\| \+\ze\t/
" autocmd FileType markdown autocmd BufWinEnter,InsertLeave,CursorMovedI *
augroup END
augroup DontItalicMarkdownLatexUnderscore
autocmd filetype markdown syntax match markdownIgnore "\$.*_.*\$" containedin=markdown
" autocmd filetype markdown syntax match markdownIgnore \M(\\begin\{)?(\$|gather\*?|align\*?|).*_.*(\\end\{)?\2" containedin=markdown
" autocmd filetype markdown syntax match markdownIgnore "\\begin{\(\$\|gather\*\?\|align\*\?\)}.*_.*\\end{\1}" containedin=markdown
augroup END
" " Colorscheme
" let base16colorspace=256
" " colorscheme base16-gruvbox-dark-hard
" colorscheme base16-solarized-dark
" let g:solarized_termcolors=256
" " colorscheme dracula
" " set background=dark
" " disables opaque background
" " NOTE: When a transparent background is needed, ":color default" is
" " easier
" " hi Normal ctermbg=NONE guibg=NONE
" " hi NonText ctermbg=NONE guibg=NONE
" Gruvbox {{{
" let g:gruvbox_italic=1
" let g:gruvbox_contrast_dark='hard'
" colorscheme gruvbox
" }}}
" dichromatic
colorscheme dichromatic
" Recolor selected line in QuickFix window
hi QuickFixLine ctermbg=15 ctermfg=240 cterm=NONE guibg=#585858 guifg=#FFFFFF gui=NONE
hi Pmenu ctermbg=17 guibg=#00005F ctermfg=252 guifg=#DADADA
" Lightline
"\ 'colorscheme': 'solarized',
" \ 'gitbranch': '%{exists("*fugitive#head") && fugitive#head()!=""?"".fugitive#head():""}',
" \ 'gitbranch': '%{FugitiveStatusline()}',
let g:lightline = {
\ 'active': {
\ 'left':[
\ [ 'mode', 'paste' ],
\ [ 'gitbranch', 'readonly', 'filename', 'modified', 'lastmodified' ],
\ ],
\ },
\ 'component': {
\ 'lineinfo': ' %3l:%-2v',
\ 'readonly': '%{&readonly?"":""}',
\ 'gitbranch': '%{exists("*fugitive#head") && fugitive#head()!=""?"".fugitive#head():""}',
\ 'lastmodified': '%{(localtime()-getftime(expand("%:p")) < 60)?"".localtime()-getftime(expand("%:p")):""}',
\ },
\ 'component_visible_condition': {
\ 'readonly': '(&filetype!="help"&& &readonly)',
\ 'modified': '(&filetype!="help"&&(&modified||!&modifiable))',
\ 'gitbranch': '(exists("*fugitive#head") && fugitive#head()!="")',
\ 'lastmodified': '((localtime()-getftime(expand("%:p"))) < 60)',
\ },
\ 'separator': {
\ 'left': '',
\ 'right': '',
\ },
\ 'subseparator': {
\ 'left': '',
\ 'right': '',
\ },
\ 'tabline': {
\ 'left': [ ['tabs'] ],
\ 'right': [ ],
\ }
\}
set showtabline=2 " Always show tabline
set guioptions-=e " Don't use GUI tabline
" True Color Support if it's avaiable in terminal
if has("termguicolors")
set termguicolors
endif
if !has('gui_running')
set t_Co=256
endif
" Enable line numbering
set number
" set relativenumber
" Configure indentLine
let g:indentLine_leadingSpaceEnabled = 1
let g:indentLine_conceallevel = 0
" General behavior
set hidden " hides buffers without changes instead of deleting them
set mouse=a
set noshowmode
set noshowmatch
set nolazyredraw
" let loaded_matchparen = 1 " disable matching parentheses
set foldcolumn=2 " display where folds are defined - but only in 2 layer (increment 2 to add more layers)
" }}}
" Search configuration
set ignorecase
set smartcase
" Indentation {{{
" tabs = 4 spaces
set tabstop=4
" set to the same as tabstop
" 0 automatically defaults to the current value of tabstop
set shiftwidth=0
" if it looks like a tab, we can delete it like a tab
set softtabstop=4
" no tabs! spaces only..
set expandtab
" < and > will hit indentation levels instead of always -4/+4
set shiftround
"}}}
" Highlight tabs and trailing whitespace {{{
set listchars=tab:>-,trail,nbsp,extends:…,precedes:…
set list
" }}}
" TODO: jry: disable this in favor of vim-stay
" Save folds in files {{{
fun! LoadFoldsOnEnter()
" Filetypes to skip in favor of other types folding
if &ft =~ 'markdown'
return
endif
silent! loadview
endfun
augroup autofolding
autocmd!
autocmd BufWinLeave,BufLeave,BufWritePost * nested if filereadable(expand('%')) | silent mkview!
" autocmd BufWinEnter,BufEnter,BufReadPost * silent! loadview
autocmd BufWinEnter,BufEnter,BufReadPost * call LoadFoldsOnEnter()
augroup END
" Enable automatic markdown folding
let g:markdown_folding = 1
" }}}
" Retain undo-history between sessions
if has('persistent_undo')
let myUndoDir = stdpath('data') . '/undodir'
call system('mkdir ' . myUndoDir)
let &undodir = myUndoDir
set undofile
endif
" Todo config {{{
let g:bujo#todo_file_path = stdpath('data') . '/bujo'
command! TODO execute "botright Todo g"
let g:bujo#window_width = 80
function BujoSearchCustom(pattern)
return (search(a:pattern, 'nc', line('.')) || search(a:pattern, 'nbc', line('.')))
endfunction
function BujoSearchCheck()
if BujoSearchCustom('\[ \]')
execute ':s/\[ \]/\[\x\]/'
elseif BujoSearchCustom('\[x\]')
execute ':s/\[x\]/\[ \]/'
else
return
endif
"move cursor back to previous position
execute 'normal!``'
" if BujoSearchCustom('\[ \]')
" execute ':s/\[ \]/\[\/\]/'
" elseif BujoSearchCustom('\[/\]')
" execute ':s/\[\/\]/\[x\]/'
" elseif BujoSearchCustom('\[x\]')
" execute ':s/\[x\]/\[ \]/'
" endif
endfunction
augroup BujoKeybinds
autocmd!
" autocmd FileType markdown nmap <C-S> <Plug>BujoAddnormal
" autocmd FileType markdown imap <C-S> <Plug>BujoAddinsert
" " autocmd FileType markdown nmap <C-Q> <Plug>BujoChecknormal <esc> :nohl<CR>
" " autocmd FileType markdown imap <C-Q> <Plug>BujoCheckinsert <esc> :nohl<CR>
autocmd FileType markdown nmap <C-Q> :call BujoSearchCheck()<CR>
autocmd FileType markdown imap <C-Q> <esc>:call BujoSearchCheck()<CR>i
"
autocmd Filetype markdown nmap <buffer> <C-S> i- [ ]
autocmd Filetype markdown imap <buffer> <C-S> - [ ]
" autocmd Filetype markdown nnoremap <C-S> BujoSearchCustom('\[ \]') ? ':s/\[ \]/\[x\]<CR>' : ':s/\[x\]/\[ \]<CR>'
" autocmd Filetype markdown inoremap <C-S> BujoSearchCustom('\[ \]') ? '<esc>:s/\[ \]/\[x\]<CR>' : '<esc>:s/\[x\]/\[ \]<CR>'
" autocmd Filetype markdown nnoremap <C-S> BujoSearchCustom('\[ \]') ? ':s/\[ \]/\[x\]<CR>' : ':s/\[x\]/\[ \]<CR>'
" autocmd Filetype markdown inoremap <C-S> BujoSearchCustom('\[ \]') ? '<esc>:s/\[ \]/\[x\]<CR>' : '<esc>:s/\[x\]/\[ \]<CR>'
augroup END
" }}}
" JIX Notes {{{
if $USER =~ "^jry$" && $HOSTNAME =~ "gnu"
command! NOTE exec "botright 80 vs " . glob('~/') . 'Notes/Notes' . (FugitiveHead() != "" ? '_'.FugitiveHead() : '')
end
" }}}
" Fuzzy finding
" TODO: Figure out fuzzy finding on windows
if !(has('win32') || has('win64'))
" TODO: Check if the below works, so this note can be erased
if $USER =~ "^jry$" && $HOSTNAME =~ "gnu"
let g:picker_selector_executable = '/home/jry/.fzy/fzy'
" let g:picker_custom_find_executable = 'find'
" nnoremap ¬ :PickerEdit ~/jobxx/<cr>
endif
function! CallPickerEdit()
let l:IsInGitRepo = system('git rev-parse --is-inside-work-tree')
if l:IsInGitRepo =~ 'true'
let l:GitRepoDir = system('git rev-parse --show-toplevel')
execute 'PickerEdit ' . l:GitRepoDir
else
execute 'PickerEdit ' . glob('~/')
" TODO: Verify if this works
" if $USER =~ '^knyff$'
" " TODO: Make PickerEdit work on windows
" execute 'PickerEdit C:\User\' . $USER
" PickerEdit C:\User\knyff\
" else
" PickerEdit ~/
" endif
endif
endfunction
function! CallPickerPDF()
let l:IsInGitRepo = system('git rev-parse --is-inside-work-tree')
if l:IsInGitRepo =~ 'true'
" TODO: Make this work
" let l:CurrBufNr = bufnr('%')
let l:GitRepoDir = system('git rev-parse --show-toplevel')
call picker#File('git ls-files --cached --exclude-standard --others', 'te zathura', l:GitRepoDir)
" execute 'b '.l:CurrBufNr
else
" let l:OldBufNr = bufnr('%')
" echo bufnr('%')
execute 'tabedit'
call picker#File('find ' . glob('~/') . ' -type f', 'te zathura')
" let l:CurrBufNr = bufnr('%')
" echo bufnr('%')
" execute 'tabclose'
" execute 'b '.l:CurrBufNr
endif
endfunction
nnoremap ¬ :call CallPickerEdit()<cr>
nnoremap ¿ :call CallPickerPDF()<cr>
endif
" NeoMake {{{
" Note: Additional neomake configuration (for JIX) is done in
" ~/dev-utils/conf/vim/plugin/neomake.vim
" Full config: when writing or reading a buffer, and on changes in insert and
" normal mode (after 1s; no delay when writing).
call neomake#configure#automake('nrwi', 2000)
" " Autoopen error list
" let g:neomake_open_list = 2 " 0: show hints, 1: show list and move cursor to list, 2: show list, but don't move cursor
" Autoopen error list {{{
let g:neomake_open_list = 0 " Don't let Neomake do it!
" Preserve view (don't automatically scroll) when moving back to
" previous buffer {{
function! SaveWinID()
let t:curWinID = win_getid()
endfunction
function! LoadWinID()
call win_gotoid( t:curWinID )
endfunction
" When switching buffers, open location window, but preserve
" cursor location and view
augroup NeomakeJumpBackHooks
au!
" " autocmd User NeomakeJobInit nested lexpr [] | call AutoSaveWinView() | call SaveWinID()
" " autocmd User NeomakeFinished nested lwindow | call LoadWinID() | call AutoRestoreWinView()
" autocmd User NeomakeJobInit lexpr [] | call SaveWinID()
" autocmd User NeomakeFinished lwindow | call LoadWinID()
augroup END
" autocmd BufLeave * call AutoSaveWinView()
" }}}
" }}}
" Configure for C
let g:c_syntax_for_h=1
let g:neomake_c_enabled_makers = ['gcc']
let g:neomake_gcc_args = [
\ '-fsyntax-only',
\ '-Wall',
\ '-Wextra',
\ '-Wfloat-equal',
\ '-I.',
\ '-fopenmp',
\ '-mp=gpu',
\ '-lm'
\ ]
" \ '-std=c99',
" Configure for C++
let g:cpp_syntax_for_h=1
let g:neomake_cpp_enabled_makers = ['clang', 'gcc'] ", 'clangtidy', 'clangcheck'] - clangtidy and/or clangcheck requires a compilation database
let g:neomake_clang_args = [
\ '-fsyntax-only',
\ '-Wall',
\ '-Wextra',
\ '-Wfloat-equal',
\ '-std=c++17',
\ '-I.',
\ '-fopenmp',
\ '-mp=gpu',
\ '-lm'
\ ]
" Configure for Rust
" let g:neomake_rust_enabled_makers = ['rustc', 'cargo']
let g:neomake_rust_enabled_makers = ['cargo']
" Configure for Haskell
let g:neomake_haskell_enabled_makers = ['hlint']
" let g:neomake_haskell_enabled_makers = ['hlint', 'ghcmod', 'hdevtools', 'liquid']
" Configure HTML at JI
if $USER =~ '^jry$' && $HOSTNAME =~ "^gnu$"
let g:neomake_html_enabled_makers = [] " disable because at work different html files are stiched together
endif
" Configure python at JI
if $USER =~ "^jry$" && $HOSTNAME =~ "^gnu$"
let g:neomake_python_enabled_makers = [] " disable python checking, since it checks for python2, but in production it is python3
endif
" let g:neomake_perl_perlcritic_postprocess = {
" \ entry -> entry.text =~# 'Private subroutine/method used (Use published APIs)'
" \ ? extend(entry, {'valid': -1})
" \ : entry}
" \ || (expand('%:t') =~# 'Test.pm')
" Configure for SageMath
augroup NeomakeSageMath
autocmd!
autocmd BufReadPre,BufEnter *sage.python let b:neomake_python_enabled_makers = []
augroup END
" Configure for Python
augroup PythonConfig
autocmd!
autocmd BufReadPre,BufEnter *.py set foldmethod=indent
augroup END
" Configure for latex
let g:neomake_tex_enabled_makers = ['chktex']
augroup NeomakeTex
autocmd!
autocmd BufReadPre *.sty let b:neomake_tex_enabled_makers = ['chktex']
autocmd BufEnter *.sty let b:neomake_tex_enabled_makers = ['chktex']
augroup END
function! Find_index_and_remove(list, element)
let index = index(a:list, a:element)
if index != -1
call remove(a:list, index)
endif
endfunction
function! Configure_perlcritic_for_test(fname)
let is_test = a:fname =~ 't/lib/'
for arg in ["--exclude Modules::RequireExplicitInclusion", "--exclude Subroutines::ProtectPrivateSubs", "--exclude Subroutines::ProhibitUnusedPrivateSubroutines", "--exclude Variables::ProtectPrivateVars"]
" Clean up perlcritic arguments to prevent duplicates
call Find_index_and_remove(g:neomake_perl_perlcritic_args, arg)
if is_test
" Add perlcritic argument
call add(g:neomake_perl_perlcritic_args, arg)
endif
endfor
endfunction
" Configure for Keymapper (https://github.com/houmain/keymapper) config
" file
let g:neomake_keymapper_enabled_makers = ['keymapper']
let g:neomake_keymapper_maker = {
\ 'exe': 'keymapper',
\ 'args': ['--check', '--no-color'],
\ 'output_stream': 'both',
\ 'append_file': 0,
\ 'errorformat':
\ "%m in line %l",
\ }
let g:neomake_sh_enabled_makers = ['sh', 'shellcheck']
" augroup NeomakeKeymapper
" au!
" autocmd BufNewFile,BufRead *.keymapper.conf set syntax=conf
" " autocmd BufReadPre keymapper.conf let b:neomake_conf_enabled_makers = ['keymapper']
" " autocmd BufEnter keymapper.conf let b:neomake_keymapper_enabled_makers = ['keymapper']
" augroup END
" augroup perlcritic_config
" au!
" au FileType perl call Configure_perlcritic_for_test(expand("<afile>:p"))
" au BufEnter * if &ft == 'perl' | call Configure_perlcritic_for_test(expand("%:p")) | endif
" augroup END
" Goto next linting error
nnoremap ]d :call LocationNext()<cr>
function! LocationNext()
try
lnext
catch
try | lfirst | catch | endtry
endtry
endfunction
" Goto previous linting error
nnoremap [d :lprev<cr>
" Fit the QuickFix window to the number of errors
au FileType qf call AdjustWindowHeight(3, 10)
function! AdjustWindowHeight(minheight, maxheight)
exe max([min([line("$"), a:maxheight]), a:minheight]) . "wincmd _"
endfunction
" }}}
" add a proper delete line command {{{
nnoremap x "_dl
nnoremap <C-e> "_dd
nnoremap <C-j> <C-e>
nnoremap <C-k> <C-y>
" }}}
" haskell-vim {{{
" let g:haskell_classic_highlighting = 1
" let g:haskell_indent_disable = 1
let g:haskell_indent_if = 4 " 3
let g:haskell_indent_case = 4 " 2
let g:haskell_indent_let = 4 " 4
let g:haskell_indent_where = 8 " 6
let g:haskell_indent_before_where = 4 " 2
let g:haskell_indent_after_bare_where = 4 " 2
let g:haskell_indent_do = 4 " 3
let g:haskell_indent_in = 4 " 1
let g:haskell_indent_guard = 4 " 2
" }}}
"au BufRead,BufNewFile *.scad lua require('openscad')
" openscad {{{
lua <<EOF
require 'openscad'
vim.g.openscad_fuzzy_finder = 'fzf'
vim.g.openscad_cheatsheet_window_blend = 15 --%
vim.g.openscad_load_snippets = false
-- should the openscad project automatically be opened on startup
vim.g.openscad_auto_open = false
--vim.g.openscad_default_mappings = true
vim.g.openscad_cheatsheet_toggle_key = '<Enter>'
vim.g.openscad_help_trig_key = '<A-h>'
vim.g.openscad_help_manual_trig_key = '<A-m>'
vim.g.openscad_exec_openscad_trig_key = '<Leader>ll'
vim.g.openscad_top_toggle = '<A-c>'
EOF
" }}}
" TODO:
" disable copying when pasting in visual mode {{{
"vnoremap p <p>:let @"=@0<CR>
"vnoremap p :put<CR>:let @"=@0<CR>
"vnoremap P <h><p>
" }}}
" vim-perl configuration {{{
" highlight advanced perl vars inside strings
let perl_extended_vars = 1
" do highlighting on POD comments
let perl_include_pod = 1
" increase number of lines used when syntax highlighting
let perl_sync_dist = 1000
autocmd BufEnter * :syntax sync minlines=300
" allow subroutine signatures
let perl_sub_signatures = 1
" }}}
" Configure Signify {{{
let g:signify_vcs_list = [ 'git' ]
let g:signify_realtime = 1
" highlight lines in Sy and vimdiff etc.
highlight DiffAdd cterm=bold ctermbg=none ctermfg=119
highlight DiffDelete cterm=bold ctermbg=none ctermfg=167
highlight DiffChange cterm=bold ctermbg=none ctermfg=227
" highlight signs in Sy
highlight SignifySignAdd cterm=bold ctermbg=none ctermfg=119
highlight SignifySignDelete cterm=bold ctermbg=none ctermfg=167
highlight SignifySignChange cterm=bold ctermbg=none ctermfg=227
" highlight signs column
highlight SignColumn ctermbg=none
" }}}
" Configure Vim-Commentary
augroup CustomCommentDefinitions
autocmd!
autocmd FileType matlab setlocal commentstring=%\ %s
autocmd FileType julia setlocal commentstring=#\ %s
autocmd FileType c setlocal commentstring=\/\/\ %s
autocmd FileType cpp setlocal commentstring=\/\/\ %s
autocmd FileType cuda setlocal commentstring=\/\/\ %s
autocmd FileType openscad setlocal commentstring=\/\/\ %s
augroup END
" NCM2
augroup NCM2
autocmd!
" Enable ncm2 for all buffers
autocmd BufEnter * call ncm2#enable_for_buffer()
" :help Ncm2PopupOpen for more information
set completeopt=noinsert,menuone,noselect
" When the <Enter> key is pressed while the popup menu is visible, it only
" hides the menu. Use this mapping to close the menu and also start a new line.
inoremap <expr> <CR> (pumvisible() ? "\<c-y>\<cr>" : "\<CR>")
" Suppress the annoying 'match x of y', 'The only match' and 'Pattern not
" found' messages
set shortmess+=c
" Use <TAB> to select the popup menu:
inoremap <expr> <Tab> pumvisible() ? "\<C-n>" : "\<Tab>"
inoremap <expr> <S-Tab> pumvisible() ? "\<C-p>" : "\<S-Tab>"
" Configure float-preview
let g:float_preview#docked = 1
" LaTeX
autocmd Filetype tex call ncm2#register_source({
\ 'name': 'vimtex',
\ 'priority': 8,
\ 'scope': ['tex'],
\ 'mark': 'tex',
\ 'word_pattern': '\w+',
\ 'complete_pattern': g:vimtex#re#ncm2,
\ 'on_complete': ['ncm2#on_complete#omni', 'vimtex#complete#omnifunc'],
\ })
" C/C++
let g:ncm2_pyclang#library_path = '/usr/lib/libclang.so'
autocmd FileType c,cpp nnoremap <buffer> gd :<c-u>call ncm2_pyclang#goto_declaration()<cr>
augroup END
" VimTex {{
let g:tex_flavor = 'latex'
let g:vimtex_syntax_conceal_disable = 1
let g:vimtex_fold_manual = 1
let g:vimtex_compiler_enabled = 1 " continuous compilation
if has('nvim')
let g:vimtex_compiler_progname = 'nvr' " nvr = neovim remote
endif
if has('win32') || has('win64')
let g:vimtex_view_general_viewer = 'SumatraPDF'
let g:vimtex_view_general_options='-reuse-instance -forward-search @tex @line @pdf'
let g:vimtex_view_general_options_latexmk='-reuse-instance'
else
let g:vimtex_view_general_viewer = 'zathura'
let g:vimtex_view_method = 'zathura'
endif
" Cleanup junk files automatically
augroup MyVimtex
autocmd!
autocmd User VimtexEventQuit call vimtex#compiler#clean(0)
augroup END
let g:vimtex_syntax_packages = {
\ 'biblatex' : {'load' : 2},
\ 'tikz' : {'load' : 2},
\ 'amsmath' : {'load' : 2},
\ 'listings' : {'load' : 2},
\ 'hyperref' : {'load' : 2},
\ 'cleveref' : {'load' : 2},
\ 'booktabs' : {'load' : 2}
\ }
" Add 'gather' as a math zone
" au FileType tex :call TexNewMathZone("M","gather",1)
" au FileType tex :call TexNewMathZone("M","gather*",1)
" au FileType tex :call TexNewMathZone("N","align",1)
" au FileType tex :call TexNewMathZone("N","align*",1)
" }}
" vim-instant-markdown {{
au FileType markdown setlocal conceallevel=0
"Uncomment to override defaults:
let g:instant_markdown_slow = 1
let g:instant_markdown_autostart = 0
au FileType markdown nnoremap <buffer> <Leader>ll :InstantMarkdownPreview<CR>
" stop it with :InstantMarkdownStop
"let g:instant_markdown_open_to_the_world = 1
let g:instant_markdown_allow_unsafe_content = 1 " Allows javascript
"let g:instant_markdown_allow_external_content = 0
"let g:instant_markdown_logfile = '/tmp/instant_markdown.log'
let g:instant_markdown_mathjax = 1
let g:instant_markdown_browser = "firefox --new-window"
"let g:instant_markdown_port = 8888
let g:instant_markdown_autoscroll = 1
"let g:instant_markdown_python = 1
" }}
" Add spell checking to LaTeX documents {{
let g:spellfile_URL = 'http://ftp.vim.org/vim/runtime/spell'
function! SetLanguageSpecificSpellFile()
if &spelllang =~ '^en'
setlocal spellfile+=~/.config/nvim/spell/en.utf-8.add
endif
if &spelllang =~ '^da'
setlocal spellfile+=~/.config/nvim/spell/dk.utf-8.add
endif
endfunction
augroup spelling
au!
au FileType tex,markdown setlocal spell spelllang=en_gb
" As a reminder:
" ]s [s jumps between spelling mistakes
" zg adds the word to the dictionary
" z= shows the suggestions
" in insert mode Ctrl-X s shows the suggestions
" We only want the 10 best suggestions - not over 50
au FileType tex,markdown setlocal spellsuggest+=10
" Add a file for custom suggestions
au FileType tex,markdown setlocal spellsuggest+=file:~/.config/nvim/spell/suggestions
" Add the default spelling file
au FileType tex,markdown execute SetLanguageSpecificSpellFile()
" au FileType tex,markdown setlocal spellfile+=~/.config/nvim/spell/en.utf-8.add
" zg or 1zg adds a word to the dictionary
" Add a file specific wordlist for one-off words that shouldn't be part of
" the dictionary
au FileType tex,markdown setlocal spellfile+=oneoff.utf-8.add
" 2zg adds a word to the dictionary
" Add a LaTeX specific wordlist for e.g. chktex
au FileType tex setlocal spellfile+=~/.config/nvim/spell/LaTeX.utf-8.add
" 3zg adds a word to the dictionary
" Add a Markdown specific wordlist
au FileType markdown setlocal spellfile+=~/.config/nvim/spell/Markdown.utf-8.add
" 3zg adds a word to the dictionary
augroup END
" }}
" Add 80 character line limit {{
augroup textwrapping
au!
" au FileType tex setlocal textwidth=80
augroup END
set colorcolumn=101
highlight ColorColumn ctermbg=5 guibg=purple
" }}
" Change window directory to the same as the open buffer
command! LCDCurrDir lcd %:p:h
function! FindAll()
call inputsave()
let p = input('Enter pattern:')
call inputrestore()
execute 'vimgrep "'.p.'" % |copen'
endfunction
nnoremap <F8> :call FindAll()<cr>
au FileType perl setlocal keywordprg=perldoc\ -T\ -f
function! LoadPerlModule()
set iskeyword+=:
let currentIdent = expand('<cword>')
set iskeyword-=:
e `=system("perlopen -f " . currentIdent)`
endfunction
nnoremap <Leader>pm :call LoadPerlModule()<CR>
nnoremap <S-x> "_dh
" <C-H> is both Ctrl+H and Ctrl+Backspace
inoremap <C-H> <C-w>
inoremap <C-Del> <C-o>"_dw
" Enable vim-test with our perl test naming scheme
let g:test#perl#prove#file_pattern = 'Test.pm$'
" autoreload lightline config
command! LightlineReload call LightlineReload()
function! LightlineReload()
call lightline#init()
call lightline#colorscheme()
call lightline#update()
endfunction
:call LightlineReload()
" Gdiff method:
" :Gdiff
" dp " diffput: add change from this window to the other window (below cursor)
" do " diffget: add change from the other window to this window (below cursor)
" Center cursor when searching
nnoremap n nzz
nnoremap N Nzz
nnoremap * *zz
nnoremap # #zz
nnoremap g* g*zz
nnoremap g# g#zz
function! ZZWrap(...)
exec ':set so=999'
exec join(a:000, ' ')
exec ':set so=0'
endfunction
command! -nargs=* ZZ call ZZWrap(<f-args>)
nnoremap <Space> :nohl<CR>
" Configure buffer splitting {{{
set splitright " When using `vsplit`, place cursor on the rightmost buffer
set splitbelow " When using `split`, place cursor on the bottommost buffer
augroup vimrc_help
autocmd!
" Open `help` buffers in vertical splits instead of horizontal splits
autocmd BufEnter *.txt if &buftype == 'help' | wincmd L | endif
augroup END
" }}}
function! InsertSnip(snip_name)
" Find the template
echo a:snip_name
if a:snip_name =~ '^/' || a:snip_name =~ '^\~/'
let l:fname = a:snip_name
echo l:fname
else
let l:fname = stdpath('config') . '/snippets/' . a:snip_name . '.*'
endif
execute "r ". l:fname
" Autoindent
let l:lines = execute("!wc -l " . expand(l:fname))
let l:lines = matchstr(l:lines, '\d\+')
execute "norm!" "=" . (l:lines-1) . "j"
" Goto the <cursor> tag
if execute("!cat " . expand(l:fname)) =~ '<cursor>'
execute "normal! gg/<cursor>\<cr>\"_8x"
endif
endfunction
function! FzySnip()
if $USER =~ "^jry$" && $HOSTNAME =~ "gnu"
call picker#File('find -follow -type f', 'R', {'cwd': stdpath('config') . '/snippets'})
else
call picker#File('find -follow -type f -name "*.snip"', 'R', {'cwd': stdpath('config') . '/snippets'})
endif
endfunction
command! -nargs=1 R call InsertSnip(<f-args>)
command! -nargs=0 RR call FzySnip()
function! GenerateMarkdownHeaderAnchors()
let l:winview = winsaveview() " save cursor position
exec 'normal! gg'
let l:match = ingo#area#frompattern#Get(0, line('$'), '\v(^#+\s+)@<=.*')
for i in range(0, len(l:match)-1)
let l:line_nr = l:match[i][0][0]
let l:valid = 0 == len(ingo#area#frompattern#Get(l:line_nr, l:line_nr, '\v<a\s+.*name\=.*>'))
if l:valid
let l:line = getbufline(bufname(), l:line_nr)[0]
let l:title = join(split(l:line)[1:-1], '-')
let l:title = tolower(l:title)
let l:title = substitute(l:title, '\V%', '%25', 'g') " MUST be first!
let l:title = substitute(l:title, '\V\', '%5C', 'g')
let l:title = substitute(l:title, '\V^', '%5E', 'g')
let l:title = substitute(l:title, '\V&\|.\|/\|,\|=\|!\|@\|#\|(\|)\|*\|$\|<\|>\|"\|', '', 'g')
let l:title = substitute(l:title, "'", '', 'g')
let l:anchor = '<a name="' . l:title . '"></a>'
let l:next_line = l:line_nr+1
let l:failed = append(l:line_nr, l:anchor)
exec ':' . l:line_nr . ',' . l:next_line .'j'
" use append for appending to the line?
endif
endfor
call winrestview(l:winview) " restore cursor position
endfunction
function! RemoveMarkdownHeaderAnchors()
let l:winview = winsaveview() " save cursor position
exec 'normal! gg'
let l:match = ingo#area#frompattern#Get(0, line('$'), '\v(^#+\s+.*)@<=\s\<a\sname\=.*\>\</a\>')
for i in range(0, len(l:match)-1)
call winrestview({'lnum': l:match[i][0][0], 'col': l:match[i][0][1]-1})
let l:string_length = l:match[i][1][1] - l:match[i][0][1] + 1
exec "normal" '"_d' . l:string_length . "l"
endfor
call winrestview(l:winview) " restore cursor position
endfunction
function! GenerateMarkdownTOC()
" We need remove the anchors before we run doctoc. Otherwise it would
" include the anchors in the link, and the anchors would become incorrect
" Doctoc also doesn't like folds, so disable them beforehand
set nofoldenable
call RemoveMarkdownHeaderAnchors()
exec ":w"
silent exec "!doctoc " . bufname()
exec ":e"
call GenerateMarkdownHeaderAnchors()
set foldenable
exec ":w"
endfunction
augroup MarkdownKeyBinds
autocmd!
autocmd FileType markdown nmap <Leader>lt :call GenerateMarkdownTOC()<CR>
augroup END
" Use ripgrep for vim grepping
if executable("rg")
set grepprg=rg\ --vimgrep\ --smart-case\ --hidden\ --auto-hybrid-regex
set grepformat=%f:%l:%c:%m
endif
if $USER =~ "^jry$" && $HOSTNAME =~ "gnu"
" Setup Perl language server
" See https://github.com/neovim/nvim-lspconfig
lua <<EOF
local jix_lsp = require 'jix.lsp'
local util = require 'lspconfig.util'
-- Mappings.
-- See `:help vim.diagnostic.*` for documentation on any of the below functions
local opts = { noremap=true, silent=true }
--vim.keymap.set('n', '<space>e', vim.diagnostic.open_float, opts)
vim.keymap.set('n', '[d', vim.diagnostic.goto_prev, opts)
vim.keymap.set('n', ']d', vim.diagnostic.goto_next, opts)
--vim.keymap.set('n', '<space>q', vim.diagnostic.setloclist, opts)
-- Use an on_attach function to only map the following keys
-- after the language server attaches to the current buffer
local on_attach = function(client, bufnr)
-- Enable completion triggered by <c-x><c-o>
vim.api.nvim_buf_set_option(bufnr, 'omnifunc', 'v:lua.vim.lsp.omnifunc')
-- Mappings.
-- See `:help vim.lsp.*` for documentation on any of the below functions
local bufopts = { noremap=true, silent=true, buffer=bufnr }
-- Go to definition
vim.keymap.set('n', 'gd', vim.lsp.buf.definition, bufopts)
-- Show perldoc for function under cursor
vim.keymap.set('n', 'K', vim.lsp.buf.hover, bufopts)
-- Show list of function in current module (kræver FZF)
vim.keymap.set('n', 'L', jix_lsp.document_functions, bufopts)
-- Show signature for function under cursor (virker i skrivende stund ikke med subroutine signatures)
--vim.keymap.set('n', '<C-f>', vim.lsp.buf.signature_help, bufopts)
-- Format file with perltidy
vim.keymap.set('n', '<leader>f', function() vim.lsp.buf.format { async = true } end, bufopts)
-- Format visual selection with perltidy
vim.keymap.set('v', '<leader>f', function() vim.lsp.buf.format { async = true } end, bufopts)
-- Slå Neomake fra i buffer for at undgå dobbeltarbejde
vim.api.nvim_command('silent NeomakeDisableBuffer')
end
local config = {
cmd = { 'jix-shell', 'pls' },
filetypes = { 'perl' },
root_dir = util.find_git_ancestor,
settings = {
-- Se https://metacpan.org/pod/PLS#OPTIONS for mulige options
perl = {
perlcritic = {
enabled = true,
perlcriticrc = '/home/jry/jobxx/conf/perlcritic/perlcriticrc',
},
syntax = {
enabled = true,
},
perltidyrc = '~/jobxx/perltidyrc',
},
},
single_file_support = true,
on_attach = on_attach,
handlers = jix_lsp.handlers,
}
require 'lspconfig'.perlpls.setup(config)
EOF
endif