Skip to content

Instantly share code, notes, and snippets.

@dmkash
Created November 9, 2021 17:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmkash/e77013b2745c70051c921082c08a7036 to your computer and use it in GitHub Desktop.
Save dmkash/e77013b2745c70051c921082c08a7036 to your computer and use it in GitHub Desktop.
.vimrc cleaned up
set shell=/bin/bash
execute pathogen#infect()
" ==================================================
" LEADER
let mapleader=","
" ==================================================
" SETTINGS
"
" Use Vim settings, rather then Vi settings (much better!).
" This must be first, because it changes other options as a side effect.
set nocompatible
set backspace=indent,eol,start " allow backspacing over everything in insert mode
set encoding=utf-8
set expandtab
set hidden
set history=50 " keep 50 lines of command line history
set ignorecase
set incsearch " do incremental searching
set laststatus=2
set modelines=0
set nobackup
set nofoldenable " Say no to code folding...
set noswapfile
set nowrap " switch wrap off for everything
set nowritebackup
set number " absolute numbering
set ruler " show the cursor position all the time
set shiftwidth=2
set showcmd " display incomplete commands
set showmatch
set showmode
set smartcase
set softtabstop=2
set tabstop=2
set ttyfast
set wildmode=longest,list
set wildmenu
" ==================================================
" COLOR SCHEME
set t_Co=256
syntax enable
set background=dark
colorscheme solarized
" Highlighting the right margin starting at 81 chars
"autocmd VimEnter,Colorscheme * :hi ColorColumn ctermbg=234
set colorcolumn=118
" ==================================================
" STATUS LINE
set statusline=\ %-40f "File path name, left-aligned
set statusline+=\ %(\ [%M%R%H%W%Y]%) "Flags
set statusline+=%= "Right side
set statusline+=%40(buf:%n,\ col:%c,\ line:%l/%L\ (%P)%) "Cursor position
set statusline+=\ %#warningmsg#
set statusline+=%*
" ==================================================
" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
if &t_Co > 2 || has("gui_running")
syntax on
set hlsearch
set guifont=DejaVu\ Sans\ Mono:h11
set guioptions=aAce
endif
if v:progname =~? "evim"
finish
endif
" ==================================================
" MAPPINGS
nnoremap <tab> %
vnoremap <tab> %
nnoremap <leader><space> :noh<cr>
nnoremap <leader>v <C-w>v<C-w>l " Make <leader>v open a new vertical split and switch to it
" Make moving around the buggers easier
nnoremap <C-h> <C-w>h
nnoremap <C-j> <C-w>j
nnoremap <C-k> <C-w>k
nnoremap <C-l> <C-w>l
" Tab Navigation
map <leader>t :tabnew<Space>
map <leader>te :tabnew %%
nnoremap th :tabfirst<CR>
nnoremap tk :tabnext<CR>
nnoremap tj :tabprev<CR>
nnoremap tl :tablast<CR>
" Toggle code folding easily
nnoremap <Space> za
" Provided by vim-rspec
let g:rspec_command="Dispatch ssh user@development.vm.test \". ~/.bash_profile; DISABLE_AIRBRAKE=true rspec {spec} --fail-fast\""
map <leader>rl :call RunNearestSpec() <CR>
map <leader>r :call RunCurrentSpecFile()<CR>
map <leader>ra :call RunAllSpecs() <CR>
map <leader>rs :call RunLastSpec() <CR>
" Edit file in the directory of the file currently being edited
cnoremap %% <C-R>=expand('%:h').'/'<cr>
map <leader>e :e %%
map <leader>es :sp %%
map <leader>ev :vsp %%
map <leader>et :tabe %%
map <leader>em :e app/models/
map <leader>tm :tabe app/models/
map <leader>vm :vsp app/models/
map <leader>f :LAck<space>
" use silver searcher instead of ack
let g:ackprg='ag --vimgrep'
" Search Dash.app (this will only work on Mac)
nmap <silent> <leader>d <Plug>DashSearch
" Toggle between Solarized colorschemes
nmap <leader>tbg :ToggleBG<cr>
" regenerate tags for ctags
map <leader>rt :!/usr/local/bin/ctags --exclude=.git --exclude=*\.js --extra=+f -R *<CR>
map <C-\> :vsp <CR>:exec("tag ".expand("<cword>"))<CR>
" This shows a list of the open buffers and allows you to
" select one by the number
nnoremap <F5> :buffers<CR>:b<Space>
" ==================================================
" RUBY HELPERS
" Like in TextMate, use ctrl-l to insert the hashrocket
imap <C-l> <Space>=><Space>
" Convert 1.8 hash syntax to 1.9 syntax
nmap <leader>19 :%s/:\([^ ]*\)\(\s*\)=>/\1:/gc<cr>
nmap <leader>18 :%s/\(\w\+\):\s/:\1 => /gc<cr>
" ==================================================
" INDENT GUIDES
let g:indent_guides_start_level = 2
let g:indent_guides_guide_size = 1
let g:indent_guides_auto_colors = 0
" ==================================================
" TABULARIZE
command! -nargs=1 -range TabFirst exec <line1> . ',' . <line2> . 'Tabularize /^[^' . escape(<q-args>, '\^$.[?*~') . ']*\zs' . escape(<q-args>, '\^$.[?*~')
nmap <leader>a= :TabFirst =<CR>
vmap <leader>a= :TabFirst =<CR>
nmap <leader>a: :Tabularize/\(:.*\)\@<!:\zs /l0<CR>
vmap <leader>a: :Tabularize/\(:.*\)\@<!:\zs /l0<CR>
nmap <leader>a> :TabFirst =><CR>
vmap <leader>a> :TabFirst =><CR>
nmap <leader>a} :TabFirst {<CR>
vmap <leader>a} :TabFirst {<CR>
vmap <leader>a{ :s/\(\S\)\s\{2,}\(\S\)/\1 \2/g<CR>
" ==================================================
" TABULARIZE
" Add spaces after comment delimiters by default
let g:NERDSpaceDelims = 1
" Use compact syntax for prettified multi-line -comments
let g:NERDCompactSexyComs = 1
" Align line-wise comment delimiters flush left instead of following code
" indentation
let g:NERDDefaultAlign = 'left'
" Allow commenting and inverting empty lines (useful when commenting a region)
let g:NERDCommentEmptyLines = 1
" Enable trimming of trainling whitespace when uncommenting
let g:NERDTrimTrailingWhitespace = 1
" Enable NERDCommenterToggle to check all selected lines is commented or not
let g:NERDToggleCheckAllLines = 1
" ==================================================
" VIM-MARKDOWN
let g:vim_markdown_folding_disabled=1
" Only do this part when compiled with support for autocommands.
if has("autocmd")
" Enable file type detection.
" Use the default filetype settings, so that mail gets 'tw' set to 72,
" 'cindent' is on in C files, etc.
" Also load indent files, to automatically do language-dependent indenting.
filetype plugin indent on
" Put these in an autocmd group, so that we can delete them easily.
augroup vimrcEx
au!
" Set File type to 'text' for files ending in .txt
autocmd BufNewFile,BufRead *.txt setfiletype text
autocmd BufNewFile,BufRead *.md setfiletype markdown
" Set File type to "javascript" for files ending in .docbuilder
autocmd BufNewFile,BufRead *.docbuilder setfiletype javascript
" Enable soft-wrapping for text files
autocmd FileType text,markdown setlocal wrap linebreak nolist textwidth=118 wrapmargin=0
autocmd BufNewFile,BufRead *.md setlocal wrap linebreak nolist textwidth=118 wrapmargin=0
autocmd FileType ruby setlocal textwidth=118
" When editing a file, always jump to the last known cursor position.
" Don't do it when the position is invalid or when inside an event handler
" (happens when dropping a file on gvim).
" Also don't do it when the mark is in the first line, that is the default
" position when opening a file.
autocmd BufReadPost *
\ if line("'\"") > 1 && line("'\"") <= line("$") |
\ exe "normal! g`\"" |
\ endif
augroup END
au BufRead,BufNewFile *.rabl setf ruby
else
set autoindent " always set autoindenting on
endif " has("autocmd")
" Convenient command to see the difference between the current buffer and the
" file it was loaded from, thus the changes you made.
" Only define it when not defined already.
if !exists(":DiffOrig")
command DiffOrig vert new | set bt=nofile | r # | 0d_ | diffthis
\ | wincmd p | diffthis
endif
"""""""""""""""""""""""""""""""""""""""""""""""""""
" FUNCTIONS
"""""""""""""""""""""""""""""""""""""""""""""""""""
" This is from Gary Bernhart's vimrc
function! RenameFile()
let old_name = expand('%')
let new_name = input('New file name: ', expand('%'), 'file')
if new_name != '' && new_name != old_name
exec ':saveas ' . new_name
exec ':silent !rm ' . old_name
redraw!
endif
endfunction
map <leader>n :call RenameFile()<cr>
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" SWITCH BETWEEN TEST AND PRODUCTION CODE
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
function! OpenTestAlternate()
let new_file = AlternateForCurrentFile()
exec ':vsp ' . new_file
endfunction
function! AlternateForCurrentFile()
let current_file = expand("%")
let new_file = current_file
let in_spec = match(current_file, '^spec/') != -1
let going_to_spec = !in_spec
let in_app = match(current_file, '\<controllers\>') != -1 || match(current_file, '\<models\>') != -1 || match(current_file, '\<views\>') != -1 || match(current_file, '\<jobs\>') != -1 || match(current_file, '\<mailers\>') || match(current_file, '\<helpers\>') != -1
if going_to_spec
if in_app
let new_file = substitute(new_file, '^app/', '', '')
end
let new_file = substitute(new_file, '\.rb$', '_spec.rb', '')
let new_file = 'spec/' . new_file
else
let new_file = substitute(new_file, '_spec\.rb$', '.rb', '')
let new_file = substitute(new_file, '^spec/', '', '')
if in_app
let new_file = 'app/' . new_file
end
endif
return new_file
endfunction
nnoremap <leader>. :call OpenTestAlternate()<cr>
" Add files from the QuickFix list to the args
" from http://vimcasts.org/episodes/project-wide-find-and-replace/
command! -nargs=0 -bar Qargs execute 'args' QuickfixFilenames()
function! QuickfixFilenames()
let buffer_numbers = {}
for quickfix_item in getqflist()
let buffer_numbers[quickfix_item['bufnr']] = bufname(quickfix_item['bufnr'])
endfor
return join(map(values(buffer_numbers), 'fnameescape(v:val)'))
endfunction
" Strip out trailing whitespace from lines.
" http://stackoverflow.com/questions/356126/how-can-you-automatically-remove-trailing-whitespace-in-vim
" http://sartak.org/2011/03/end-of-line-whitespace-in-vim.html
function! <SID>StripTrailingWhitespaces()
" Prep -- save last search and cursor position
let _s=@/
let l = line(".")
let c = col(".")
" Strip the whitespace from the end of lines
%s/\s\+$//e
" Restore previous search history and cursor position
let @/=_s
call cursor(l, c)
endfunction
" Call the function every time the buffer is written
autocmd BufWritePre * :call <SID>StripTrailingWhitespaces()
augroup numbertoggle
autocmd!
autocmd BufEnter,FocusGained,InsertLeave * set relativenumber
autocmd BufLeave,FocusLost,InsertEnter * set norelativenumber
augroup END
function! MakeSession()
let b:sessiondir = $HOME . "/.vim/sessions" . getcwd()
if (filewritable(b:sessiondir) != 2)
exe 'silent !mkdir -p ' b:sessiondir
redraw!
endif
let b:filename = b:sessiondir . '/session.vim'
exe "mksession! " . b:filename
endfunction
function! LoadSession()
let b:sessiondir = $HOME . "/.vim/sessions" . getcwd()
let b:sessionfile = b:sessiondir . "/session.vim"
if (filereadable(b:sessionfile))
exe 'source ' b:sessionfile
else
echo "No session loaded."
endif
endfunction
" Make sure that ToggleBG command is loaded
call togglebg#map("")
au FileType qf call AdjustWindowHeight(10, 60)
function! AdjustWindowHeight(minheight, maxheight)
exe max([min([line("$"), a:maxheight]), a:minheight]) . "wincmd _"
endfunction
" Switch Solarized between dark and light for vim, tmux, and iTerm
function! SolarSwap()
if &background ==? 'dark'
set background=light
execute "silent !tmux source-file " . shellescape(expand('~/.dotfiles/tmux/tmux-colors-solarized/tmuxcolors-light.conf'))
else
set background=dark
execute "silent !tmux source-file " . shellescape(expand('~/.dotfiles/tmux/tmux-colors-solarized/tmuxcolors-dark.conf'))
endif
silent !osascript -e 'tell app "System Events" to keystroke "s" using {shift down, option down, control down}'
endfunction
nmap ,s :call SolarSwap()<CR>
" Merge a tab into a split in the previous window
function! MergeTabs()
if tabpagenr() == 1
return
endif
let bufferName = bufname("%")
if tabpagenr("$") == tabpagenr()
close!
else
close!
tabprev
endif
vsplit
execute "buffer " . bufferName
endfunction
nmap <C-W>u :call MergeTabs()<CR>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment