Skip to content

Instantly share code, notes, and snippets.

@timhughes
Last active November 1, 2023 13:12
Show Gist options
  • Save timhughes/653eaef9e268ca747354e21624b71422 to your computer and use it in GitHub Desktop.
Save timhughes/653eaef9e268ca747354e21624b71422 to your computer and use it in GitHub Desktop.
vimrc
" vim: set ft=vim ts=4 sw=4 tw=600 et :
""""""""""" README """""""""""""""
" To use this you will need to do the following.
" Follow the instructions at https://github.com/ryanoasis/nerd-fonts#font-installation
" to get the nice fonts. My preference is https://github.com/ryanoasis/nerd-fonts/tree/master/patched-fonts/LiberationMono/complete
" With the font installed you need to select the font in your terminal emulator
"
" Simple install of nerd font is:
"
" mkdir -p ~/.local/share/fonts
" cd ~/.local/share/fonts
" curl -fLo "Literation Mono Powerline Nerd Font Complete.ttf" https://raw.githubusercontent.com/ryanoasis/nerd-fonts/master/patched-fonts/LiberationMono/complete/Literation%20Mono%20Powerline%20Nerd%20Font%20Complete.ttf
"
" You may need to refresh yout font cache:
"
" fc-cache --really-force --verbose
"
" Make the required directories and get the plugin manager:
"
" Run on the cli `vim +qa`
"
" TODO:
" - convert to functions https://github.com/stefanoborini/dotfiles/blob/master/vimrc
" - take a look at this color scheme https://dribbble.com/shots/1021755-Flat-UI-Terminal-Theme
"
""""""""""""""""""""""""""""""""""
set nocompatible " be iMproved - needs to be at the top
" -----------------------------
" Backups, Tmp Files, and Undo
" -----------------------------
" Using double trailing slashes in the path tells vim to enable a feature
" where it avoids name collisions.
set backupdir=$HOME/.cache/vim/backup//
set backupcopy=yes
set backup
set backupskip+=svn-commit.tmp,svn-commit.[0-9]*.tmp
set directory=/tmp//
let g:SESSION_DIR = $HOME.'/.cache/vim/sessions//'
if has('persistent_undo')
set undofile
set undodir=$HOME/.cache/vim/undo//
endif
" Create system vim dirs
if finddir(&backupdir) == ''
silent call mkdir(&backupdir, "p")
endif
if finddir(g:SESSION_DIR) == ''
silent call mkdir(g:SESSION_DIR, "p")
endif
if finddir(&undodir) == ''
silent call mkdir(&undodir, "p")
endif
" Make clipboard 1000 lines long and up to 1000kb
set viminfo='100,<10000
"let g:username = 'Tim Hughes'
let g:username = system('printf "$(getent passwd $USER|cut -d: -f5| cut -d, -f1)"')
let g:email = $EMAIL " get this from env var set in ~/.bashrc
" ---------------
" Behaviors
" ---------------
set autoread " Automatically reload changes if detected
set wildmenu " "Show possible matches are shown just above the command line
set autowrite " Writes on make/shell commands
set autoread
set pastetoggle=<F3> " toggle between paste and normal: for 'safer' pasting from keyboard
" Modeline
set modeline " read the little thing at the bottom of the page
"set modelines=5 " default numbers of lines to read for modeline instructions
set showcmd " This shows what you are typing as a command.
set hlsearch " highlight search
set incsearch " Start searching as you type
set nowrap " '
" Tabs
set tabstop=4 " Set the default tabstop
set softtabstop=4 " Number of spaces that a <Tab> counts for while editing
set shiftwidth=4 " Set the default shift width for indents
set expandtab " Make tabs into spaces (set by tabstop)
set smarttab " Smarter tab levels
set shiftround " Round indent to multiple of 'shiftwidth' for > and < commands
set autoindent " Auto indent
set smartindent " Smart indent
set showmatch " Show matching brackets.
set matchtime=5 " Bracket blinking.
set laststatus=2 " Always show status line.
set ruler " Show ruler
set nolist " Display unprintable characters f12 - switches
"set mouse-=a " Disable mouse
set mouse= " Disable mouse
set mousehide " Hide mouse after chars typed
set textwidth=80
"highlight ColorColumn ctermbg=234 guibg=gray15
"set colorcolumn=+1 " Causes cut and paste issues
set hidden " see :help hidden
if !&scrolloff
set scrolloff=1 "always leave 1 line at the bottom and top when scrolling
endif
if !&sidescrolloff
set sidescrolloff=5
endif
set display+=lastline
set re=1 "fix for ssh keys in yaml files
set maxmempattern=5000
set backspace=indent,eol,start
" Plugin Manager {
let enable_plugins = 1 "enable switching plugins off for debugging
let fresh_install = 0
" Vim-Plug Manager let enable_plugins = 1 "enable switching plugins off for debugging
if enable_plugins
if empty(glob('~/.vim/autoload/plug.vim'))
silent !curl -fLo ~/.vim/autoload/plug.vim --create-dirs
\ https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
autocmd VimEnter * PlugInstall --sync | source $MYVIMRC
let fresh_install = 1
endif
call plug#begin('~/.vim/plugged')
""""" Add plugins here """"""""""""""
"Plug 'chrisbra/csv.vim'
Plug 'neoclide/coc.nvim', {'branch': 'release'}
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" odds and sods
" Full path fuzzy file, buffer, mru, tag, ... finder for Vim.
Plug 'ctrlpvim/ctrlp.vim'
" https://github.com/mg979/vim-visual-multi
Plug 'mg979/vim-visual-multi'
"
Plug 'aperezdc/vim-template'
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Gives RGB hex codes the color #fe2 #8e1876
Plug 'lilydjwg/colorizer'
"" Revision control
Plug 'tpope/vim-fugitive'
Plug 'airblade/vim-gitgutter'
Plug 'gregsexton/gitv'
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" This setting should not be enabled if using another completer. It also must
" be set before ALE is loaded. see :help g:ale_completion_enabled
let g:ale_completion_enabled = 0
Plug 'dense-analysis/ale'
let g:ale_echo_msg_error_str = 'Err'
let g:ale_echo_msg_warning_str = 'Warn'
let g:ale_echo_msg_format = '[%linter%] %s [%severity%]'
let g:ale_fix_on_save = 1
let g:ale_lint_delay = 100
let g:ale_linters = {}
let g:ale_linters.go = [
\ 'gopls',
\ ]
let g:ale_linters.python = [
\ 'flake8',
\ 'mypy',
\ 'pylint',
\ 'pyright',
\ 'bandit',
"\ 'vulture',
\ 'jedils',
\ 'pyls'
\ ]
let g:ale_fixers = {'*': ['remove_trailing_lines', 'trim_whitespace'],}
let g:ale_fixers.python = [
\ 'trim_whitespace',
\ 'remove_trailing_lines',
\ 'add_blank_lines_for_python_control_statements',
\ 'autoimport',
\ 'reorder-python-imports',
\ 'black',
\ ]
let g:ale_fixers.ruby = [ 'remove_trailing_lines', 'trim_whitespace', 'rubocop']
let g:ale_fixers.yaml = [ 'prettier' ]
let g:ale_fixers.json = [ 'prettier' ]
let g:ale_fixers.puppet = ['remove_trailing_lines', 'trim_whitespace', 'puppetlint']
"let g:ale_fixers.java = ['remove_trailing_lines', 'trim_whitespace', 'google_java_format']
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Only one of s:deoplete_enabled or s:asyncomplete_enabled should be set to 1
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Deoplete
"
" pip install --user pynvim
"
let s:deoplete_enabled = 0
if (s:deoplete_enabled)
if has('nvim')
Plug 'Shougo/deoplete.nvim', { 'do': ':UpdateRemotePlugins' }
else
Plug 'Shougo/deoplete.nvim'
Plug 'roxma/nvim-yarp'
Plug 'roxma/vim-hug-neovim-rpc'
endif
let g:deoplete#enable_at_startup = 1
Plug 'deoplete-plugins/deoplete-jedi'
endif
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" asyncomplete.vim
"
let s:asyncomplete_enabled = 1
if (s:asyncomplete_enabled)
Plug 'prabirshrestha/asyncomplete.vim'
inoremap <expr> <Tab> pumvisible() ? "\<C-n>" : "\<Tab>"
inoremap <expr> <S-Tab> pumvisible() ? "\<C-p>" : "\<S-Tab>"
inoremap <expr> <cr> pumvisible() ? asyncomplete#close_popup() : "\<cr>"
imap <c-space> <Plug>(asyncomplete_force_refresh)
Plug 'prabirshrestha/vim-lsp'
Plug 'prabirshrestha/asyncomplete-lsp.vim'
" Register language server
if executable('jedi-language-server')
" pip install -u jedi-language-server
au User lsp_setup call lsp#register_server({
\ 'name': 'jedils',
\ 'cmd': {server_info->['jedi-language-server']},
\ 'allowlist': ['python'],
\ })
elseif executable('pyls')
" pip install -u python-language-server
au User lsp_setup call lsp#register_server({
\ 'name': 'pyls',
\ 'cmd': {server_info->['pyls']},
\ 'allowlist': ['python'],
\ })
endif
" Use ALE's function for asyncomplete defaults
au User asyncomplete_setup call asyncomplete#register_source(asyncomplete#sources#ale#get_source_options({
\ 'priority': 10,
\ }))
endif
"""""""""""""""""""""""""""""""""""""""""""
" Needs to be before 'ryanoasis/vim-webdevicons'
Plug 'preservim/tagbar'
nmap <F10> :TagbarToggle<CR>
let g:tagbar_width = 25
" go get -u github.com/jstemmer/gotags
let g:tagbar_type_go = {
\ 'ctagstype' : 'go',
\ 'kinds' : [
\ 'p:package',
\ 'i:imports:1',
\ 'c:constants',
\ 'v:variables',
\ 't:types',
\ 'n:interfaces',
\ 'w:fields',
\ 'e:embedded',
\ 'm:methods',
\ 'r:constructor',
\ 'f:functions'
\ ],
\ 'sro' : '.',
\ 'kind2scope' : {
\ 't' : 'ctype',
\ 'n' : 'ntype'
\ },
\ 'scope2kind' : {
\ 'ctype' : 't',
\ 'ntype' : 'n'
\ },
\ 'ctagsbin' : 'gotags',
\ 'ctagsargs' : '-sort -silent'
\ }
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Plug 'scrooloose/nerdtree' |
\ Plug 'Xuyuanp/nerdtree-git-plugin' |
\ Plug 'ryanoasis/vim-devicons' |
\ Plug 'tiagofumo/vim-nerdtree-syntax-highlight'
nnoremap <silent> <F9> :NERDTreeToggle<CR>
let NERDTreeIgnore = ['\.pyc$', '\.pyo$', '\.sqlite3$', '\.git/$']
let g:NERDTreeFileExtensionHighlightFullName = 1
let g:NERDTreeExactMatchHighlightFullName = 1
let g:NERDTreePatternMatchHighlightFullName = 1
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" https://github.com/bling/vim-airline#integrating-with-powerline-fonts
Plug 'bling/vim-airline'
let g:airline_powerline_fonts = 1
let g:airline#extensions#tabline#enabled = 1
let g:airline#extensions#tabline#buffer_idx_mode = 1
let g:airline#extensions#tabline#left_sep = ''
let g:airline#extensions#tabline#left_alt_sep = '|'
let g:airline#extensions#ale#enabled = 1
""""""""""""""""""""""""""""""""""""""""""""""""""""
"" Colour schemes
Plug 'tomasr/molokai'
""""""""""""""""""""""""""""""""""""""""""""""""
"" Go
Plug 'fatih/vim-go', { 'do': ':GoUpdateBinaries' }
"" TOML
Plug 'cespare/vim-toml'
"" Puppet
Plug 'rodjek/vim-puppet'
Plug 'godlygeek/tabular'
"" Ruby
Plug 'ngmy/vim-rubocop'
"" Javascript
Plug 'jelera/vim-javascript-syntax'
"" JSON
Plug 'elzr/vim-json'
let g:vim_json_syntax_conceal = 0
"" Python
"Plug 'python-rope/ropevim'
Plug 'Glench/Vim-Jinja2-Syntax'
Plug 'mgedmin/python-imports.vim'
autocmd FileType python nnoremap <buffer> <F5> :ImportName<CR>
Plug 'sophacles/vim-bundle-mako'
"""""""""""""""""""""""""""""""""""""
call plug#end()
endif " end plugin_enabled
"
filetype plugin indent on " Automatically detect file types. Required after bundles.
syntax on " enable syntax
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" This needs to be after plugin
try
colorscheme molokai
" Turn on truecolor if we can
if (has("termguicolors"))
set termguicolors
else
set t_Co=256
endif
catch /^Vim\%((\a\+)\)\=:E185/
colorscheme default
endtry
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" GUI
if ! has('gui_running')
set ttimeoutlen=10
augroup FastEscape
autocmd!
au InsertEnter * set timeoutlen=0
au InsertLeave * set timeoutlen=1000
augroup END
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Custom menus
amenu V&iew.NERDTreeToggle :NERDTreeToggle<CR>
amenu Git.Commit :Gcommit -a<CR>
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Tollbar
" http://superuser.com/questions/11289/how-do-i-customize-the-gvim-toolbar
tmenu ToolBar.tagbar Toggle display of the Tagbar
amenu icon=task-due ToolBar.tagbar :TagbarToggle<CR>
set guifont=Liberation\ Mono\ 10
endif
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Custom Commands
" Leader is by default '\' but we can remap to whatever we want
let mapleader='\'
" example custom command. (we have an autocommand for this one though
" :nmap <Leader>s :source $MYVIMRC<CR>
nnoremap <leader>? :ALEDetail<cr>
"inoremap <F1> <Esc>:make<CR>
"noremap <F1> <Esc>:make<CR>
"inoremap <F2> <Esc>:make<CR>
"noremap <F2> <Esc>:make<CR>
"inoremap <F3> Allocated to pastetoggle
"noremap <F3> Allocated to pastetoggle
"inoremap <F4> <Esc>:make<CR>
"noremap <F4> <Esc>:make<CR>
"inoremap <F5> <Esc>:make<CR>
"noremap <F5> <Esc>:make<CR>
"inoremap <F6> Allocated to Autopep8
"noremap <F6> <Esc>:make<CR>
"inoremap <F7> <Esc>:make<CR>
"noremap <F7> Allocated to CommentToggle
"inoremap <F8> Allocated to IDE Toggle
"noremap <F8> Allocated to IDE Toggle
"inoremap <F9> <Esc>:make<CR>
"noremap <F9> <Esc>:make<CR>
"inoremap <F10> <Esc>:cnext<CR>
"noremap <F10> <Esc>:cnext<CR>
"inoremap <F11> <Esc>:cprev<CR>
"noremap <F11> <Esc>:cprev<CR>
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" general autocommands
" Remove ALL autocommands for vimrc to avoid duplicates and re-read vimrc after edit
autocmd! bufwritepost ~/.vimrc source ~/.vimrc
" format xml files using xmllint
autocmd FileType xml setlocal equalprg=xmllint\ --format\ --recover\ -\ 2>/dev/null
" This breaks templates
"autocmd FileType html setlocal equalprg=tidy\ --doctype\ html5\ 2>/dev/null
" this doesn't appear to work https://github.com/rodjek/vim-puppet/pull/29
autocmd BufRead,BufNewFile *.pp set filetype=puppet
autocmd BufRead,BufNewFile Guardfile,Rakefile,Gemfile,Vagrantfile set filetype=ruby
autocmd BufRead,BufNewFile *.json set filetype=json
autocmd BufRead,BufNewFile *.md,*.rst setlocal expandtab textwidth=80
autocmd FileType ruby,puppet,html,yaml setlocal expandtab shiftwidth=2 softtabstop=2
autocmd FileType puppet setlocal expandtab shiftwidth=2 softtabstop=2 textwidth=139
autocmd FileType python,rst,php setlocal expandtab shiftwidth=4 softtabstop=4 textwidth=79
autocmd FileType qf wincmd J " Make the quickfix window always be at very bottom
autocmd FileType qf setlocal wrap
autocmd FileType taskedit setlocal textwidth=999
" Hopefully covered by vim-json
" augroup json_autocmd
" autocmd!
" autocmd FileType json set autoindent
" autocmd FileType json set formatoptions=tcq2l
" autocmd FileType json set textwidth=78 shiftwidth=2
" autocmd FileType json set softtabstop=2 tabstop=8
" autocmd FileType json set expandtab
" autocmd FileType json setlocal equalprg=python\ -mjson.tool\ 2>/dev/null
" autocmd FileType json set foldmethod=syntax
" augroup END
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
highlight ExtraWhitespace ctermbg=red guibg=red
match ExtraWhitespace /\s\+$/
autocmd BufWinEnter * match ExtraWhitespace /\s\+$/
autocmd InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
autocmd InsertLeave * match ExtraWhitespace /\s\+$/
autocmd BufWinLeave * call clearmatches()
" remove trailing whitespace from files
function! TrimWhiteSpace()
%s/\s\+$//e
endfunction
command! TrimWhiteSpace call TrimWhiteSpace()
au FileType vim,python,puppet,ruby,yaml,html,javascript,htmldjango,go,rst,md,markdown autocmd BufWritePre,FileWritePre * :call TrimWhiteSpace()
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Make html indentation work properly
let g:html_indent_script1 = "inc"
let g:html_indent_style1 = "inc"
let g:html_indent_inctags = "html,body,head"
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" We can use different key mappings for easy navigation between splits
" to save a keystroke. So instead of ctrl-w then j, it's just ctrl-j:
"nnoremap <C-j> <C-w><C-j>
"nnoremap <C-k> <C-w><C-k>
"nnoremap <C-l> <C-w><C-l>
"nnoremap <C-h> <C-w><C-h>
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" commenting code
autocmd FileType c,cpp,java,scala,javascript let b:comment_leader = '//'
autocmd FileType sh,ruby,python,puppet,yaml let b:comment_leader = '#'
autocmd FileType conf,fstab,brazil-config let b:comment_leader = '#'
autocmd FileType tex let b:comment_leader = '%'
autocmd FileType mail let b:comment_leader = '>'
autocmd FileType vim let b:comment_leader = '"'
function! CommentToggle()
execute ':silent! s/\([^ ]\)/' . b:comment_leader . ' \1/'
execute ':silent! s/^\( *\)' . b:comment_leader . ' \?' . b:comment_leader . ' \?/\1/'
endfunction
vnoremap <silent> <Leader>t :call CommentToggle()<CR>
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Append modeline after last line in buffer.
" type \ml to add a modeline based on your current settings
" Use substitute() instead of printf() to handle '%%s' modeline in LaTeX
" files.
function! AppendModeline()
let l:modeline = printf(" vim: set ft=%s ts=%d sw=%d tw=%d %set :",
\ &filetype, &tabstop, &shiftwidth, &textwidth, &expandtab ? '' : 'no')
let l:modeline = substitute(&commentstring, "%s", l:modeline, "")
call append(line("$"), l:modeline)
endfunction
nnoremap <silent> <Leader>ml :call AppendModeline()<CR>
"===============================================================================
" http://vim.wikia.com/wiki/Deleting_a_buffer_without_closing_the_window
"here is a more exotic version of my original Kwbd script
"delete the buffer; keep windows; create a scratch buffer if no buffers left
function s:Kwbd(kwbdStage)
if(a:kwbdStage == 1)
if(&modified)
let answer = confirm("This buffer has been modified. Are you sure you want to delete it?", "&Yes\n&No", 2)
if(answer != 1)
return
endif
endif
if(!buflisted(winbufnr(0)))
bd!
return
endif
let s:kwbdBufNum = bufnr("%")
let s:kwbdWinNum = winnr()
windo call s:Kwbd(2)
execute s:kwbdWinNum . 'wincmd w'
let s:buflistedLeft = 0
let s:bufFinalJump = 0
let l:nBufs = bufnr("$")
let l:i = 1
while(l:i <= l:nBufs)
if(l:i != s:kwbdBufNum)
if(buflisted(l:i))
let s:buflistedLeft = s:buflistedLeft + 1
else
if(bufexists(l:i) && !strlen(bufname(l:i)) && !s:bufFinalJump)
let s:bufFinalJump = l:i
endif
endif
endif
let l:i = l:i + 1
endwhile
if(!s:buflistedLeft)
if(s:bufFinalJump)
windo if(buflisted(winbufnr(0))) | execute "b! " . s:bufFinalJump | endif
else
enew
let l:newBuf = bufnr("%")
windo if(buflisted(winbufnr(0))) | execute "b! " . l:newBuf | endif
endif
execute s:kwbdWinNum . 'wincmd w'
endif
if(buflisted(s:kwbdBufNum) || s:kwbdBufNum == bufnr("%"))
execute "bd! " . s:kwbdBufNum
endif
if(!s:buflistedLeft)
set buflisted
set bufhidden=delete
set buftype=
setlocal noswapfile
endif
else
if(bufnr("%") == s:kwbdBufNum)
let prevbufvar = bufnr("#")
if(prevbufvar > 0 && buflisted(prevbufvar) && prevbufvar != s:kwbdBufNum)
b #
else
bn
endif
endif
endif
endfunction
command! Kwbd call s:Kwbd(1)
nnoremap <silent> <Plug>Kwbd :<C-u>Kwbd<CR>
" Create a mapping (e.g. in your .vimrc) like this:
nmap <C-W>! <Plug>Kwbd
"================================================================================
" http://vim.wikia.com/wiki/Switching_case_of_characters#Twiddle_case
" With the following (for example, in vimrc), you can visually select text then
" press ~ to convert the text to UPPER CASE, then to lower case, then to Title
" Case. Keep pressing ~ until you get the case you want.
function! TwiddleCase(str)
if a:str ==# toupper(a:str)
let result = tolower(a:str)
elseif a:str ==# tolower(a:str)
let result = substitute(a:str,'\(\<\w\+\>\)', '\u\1', 'g')
else
let result = toupper(a:str)
endif
return result
endfunction
vnoremap ~ y:call setreg('', TwiddleCase(@"), getregtype(''))<CR>gv""Pgv
set tags+=tags
hi DiffAdd ctermfg=NONE ctermbg=Green
hi DiffChange ctermfg=NONE ctermbg=NONE
hi DiffDelete ctermfg=LightBlue ctermbg=Red
hi DiffText ctermfg=Yellow ctermbg=Red
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment