Create a gist now

Instantly share code, notes, and snippets.

@edi9999 /.vimrc
Last active Mar 13, 2016

What would you like to do?
.vimrc bug
set nocompatible " be iMproved, required
" ----------------------------------------------------------------------------
" Vim SETTINGS
" ----------------------------------------------------------------------------
syntax enable
let mapleader = ','
set synmaxcol=400
set mouse=n
set number
set relativenumber
set cursorline
set textwidth=0
set pastetoggle=<F11>
set background=dark
set shortmess=filmnrwxtToO
set showcmd
set history=5000
set backspace=indent,eol,start
set wrap
" Don't update the display while executing macros
set scrolloff=8
set lazyredraw
set ignorecase
set smartcase
set autoread
set hlsearch
set incsearch
" Have a list when having completion
" http://stackoverflow.com/questions/704282/filename-completion-in-reverse-order
set wildmenu
set splitright
set splitbelow
set ttimeoutlen=0
set listchars=tab:>-,trail:-
set list
" size of an "indent"
set shiftwidth=4
" size of a hard tabstop
set tabstop=4
" a combination of spaces and tabs are used to simulate tab stops at a width
" other than the (hard)tabstop
set softtabstop=4
set expandtab
set noswapfile
set nobackup
set nowritebackup
if has('vim_starting')
set foldmethod=indent
endif
set guioptions-=m "remove menu bar
set guioptions-=T "remove toolbar
set guioptions-=r "remove right-hand scroll bar
set tags=./tags;/,tags;/
set viminfo='100,<50,s10,h,f1
set foldlevelstart=99
let javaScript_fold=1
" Use persistent undo
if has('persistent_undo')
" Save all undo files in a single location (less messy, more risky)...
set undodir=$HOME/tmp/.VIM_UNDO_FILES
" Save a lot of back-history...
set undolevels=5000
" Actually switch on persistent undo
set undofile
endif
" Follow symlinks when opening a file
" NOTE: this happens with directory symlinks anyway (due to Vim's chdir/getcwd
" magic when getting filenames).
" Sources:
" - https://github.com/tpope/vim-fugitive/issues/147#issuecomment-7572351
" - http://www.reddit.com/r/vim/comments/yhsn6/is_it_possible_to_work_around_the_symlink_bug/c5w91qw
function! MyFollowSymlink(...)
if exists('w:no_resolve_symlink') && w:no_resolve_symlink
return
endif
let fname = a:0 ? a:1 : expand('%')
if fname =~? '^\w\+:/'
" Do not mess with 'fugitive://' etc.
return
endif
let fname = simplify(fname)
let resolvedfile = resolve(fname)
if resolvedfile == fname
return
endif
let resolvedfile = fnameescape(resolvedfile)
let sshm = &shm
set shortmess+=A " silence ATTENTION message about swap file (would get displayed twice)
exec 'file ' . resolvedfile
exec 'w!'
let &shm=sshm
" Re-init fugitive.
silent! call fugitive#detect(resolvedfile)
if &modifiable
" Only display a note when editing a file, especially not for `:help`.
silent! redraw " Redraw now, to avoid hit-enter prompt.
echomsg 'Resolved symlink: =>' resolvedfile
redraw " Redraw now, to avoid hit-enter prompt.
endif
endfunction
command! FollowSymlink silent! call MyFollowSymlink()
command! ToggleFollowSymlink let w:no_resolve_symlink = !get(w:, 'no_resolve_symlink', 0) | echo "w:no_resolve_symlink =>" w:no_resolve_symlink
augroup followSymLinks
autocmd!
au BufReadPost * nested call MyFollowSymlink(expand('%'))
augroup END
" ----------------------------------------------------------------------------
" Bundles
" ----------------------------------------------------------------------------
" set the runtime path to include plug.vim
if has('vim_starting')
" Required:
source ~/.vim/autoload/plug.vim
endif
source ~/asynccommand.vim
set rtp+=~/.fzf
call plug#begin()
" Themes
Plug 'junegunn/seoul256.vim'
" Plug 'altercation/vim-colors-solarized'
" Plug 'flazz/vim-colorschemes'
" Utilities
Plug 'junegunn/goyo.vim', {'on': 'Goyo'}
Plug 'junegunn/fzf.vim'
Plug 'rking/ag.vim', {'on': 'Ag'}
Plug 'junegunn/vim-pseudocl'
Plug 'junegunn/vim-fnr'
Plug 'justinmk/vim-gtfo'
Plug 'majutsushi/tagbar'
Plug 'vim-scripts/ReplaceWithRegister'
Plug 'AndrewRadev/splitjoin.vim'
Plug 'junegunn/rainbow_parentheses.vim'
Plug 'junegunn/vim-after-object'
Plug 'osyo-manga/vim-over'
Plug 'AndrewRadev/splitjoin.vim'
" Plug 'tpope/vim-sensible'
Plug 'tpope/vim-unimpaired'
Plug 'Align', {'on': 'Align'}
Plug 'tommcdo/vim-exchange'
Plug 'scrooloose/syntastic'
Plug 'tpope/vim-fugitive'
Plug 'airblade/vim-gitgutter'
Plug 'mbbill/undotree', {'on': 'UndotreeToggle'}
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-surround'
Plug 'airblade/vim-rooter'
Plug 'tpope/vim-dispatch'
Plug 'tpope/vim-repeat'
Plug 'honza/vim-snippets'
Plug 'tpope/vim-abolish'
Plug 'wellle/targets.vim'
Plug 'bogado/file-line'
Plug 'tpope/vim-vinegar'
Plug 'kassio/neoterm'
Plug 'vim-scripts/SearchComplete'
" Languages
Plug 'moorereason/vim-markdownfmt'
Plug 'tobyS/pdv'
Plug 'othree/html5.vim'
Plug 'moll/vim-node'
Plug 'elzr/vim-json'
Plug 'fatih/vim-go'
Plug 'avakhov/vim-yaml'
Plug 'vim-php/vim-php-refactoring'
Plug 'mattn/emmet-vim'
Plug 'tpope/vim-markdown'
Plug 'isRuslan/vim-es6'
Plug 'agirorn/vim-coloresque'
Plug 'hail2u/vim-css3-syntax'
Plug 'amirh/HTML-AutoCloseTag'
Plug 'kchmck/vim-coffee-script'
Plug 'ingydotnet/yaml-vim'
" For hunter
Plug 'mattn/webapi-vim'
Plug 'ogranada/hunter'
Plug 'benekastah/neomake'
Plug 'chip/vim-fat-finger'
if has('python')
Plug 'editorconfig/editorconfig-vim'
Plug 'SirVer/ultisnips'
endif
call plug#end()
" ----------------------------------------------------------------------------
" Bundle configuration
" ----------------------------------------------------------------------------
augroup rainbow
autocmd!
autocmd Filetype javascript,perl,vim silent! RainbowParentheses
augroup END
let g:rainbow#max_level = 16
let g:rainbow#pairs = [['(', ')'], ['{', '}'], ['[', ']']]
let g:rainbow#colors = {
\ 'dark': [
\ ['122' , '122' ] ,
\ ['130' , '122' ] ,
\ ['171' , '122' ] ,
\ ['62' , '122' ] ,
\ ['179' , '122' ] ,
\ ['1' , '122' ] ,
\ ['7' , '122' ] ,
\ ['94' , '122' ] ,
\ ['68' , '122' ]
\ ] ,
\ 'light': [
\ ['122' , '122' ] ,
\ ['122' , '122' ] ,
\ ['122' , '122' ] ,
\ ['122' , '122' ] ,
\ ['122' , '122' ] ,
\ ['122' , '122' ] ,
\ ['122' , '122' ] ,
\ ['122' , '122' ] ,
\ ['122' , '122' ]
\ ]
\ }
augroup Rainbow
autocmd!
autocmd VimEnter * silent! call after_object#enable([']', '['], '=', ':', '-', '#', ' ')
augroup END
" -----------
if has('vim_starting')
set statusline+=%#warningmsg#
set statusline+=%{SyntasticStatuslineFlag()}
set statusline+=%*
endif
let g:markdownfmt_autosave=1
" Use - for surrounding with **
let g:surround_{char2nr("-")} = "**\r**"
let g:surround_{char2nr("+")} = "```\r```"
let g:ctrlp_open_new_file = 'r'
if isdirectory(expand('~/.$VIM_V/bundle/PIV'))
let g:DisableAutoPHPFolding = 0
let g:PIVAutoClose = 0
endif
let g:ackprg = 'ag --nogroup --nocolor --column'
let g:ack_use_dispatch=1
let g:php_refactor_command='php ~/php-refactoring-browser/src/bin/refactor'
let g:UltiSnipsListSnippets='<c-l>'
let g:pdv_template_dir = $HOME .'/.templates_snip'
let g:gitgutter_map_keys = 0
let g:gitgutter_sign_added = '+'
let g:gitgutter_sign_modified = '~~'
let g:gitgutter_sign_removed = '--'
let g:gitgutter_sign_removed_first_line = '--'
let g:gitgutter_sign_modified_removed = '-~'
let g:syntastic_always_populate_loc_list = 1
let g:syntastic_auto_loc_list = 0
let g:syntastic_check_on_open = 1
let g:syntastic_check_on_wq = 1
let g:syntastic_javascript_checkers = ['eslint']
let g:syntastic_javascript_eslint_exec = 'jlint'
let g:neomake_javascript_eslint_exe = 'jlint'
let g:neomake_open_list = 2
let g:syntastic_vim_checkers = ['vint']
let g:rooter_disable_map = 1
let g:multi_cursor_exit_from_insert_mode = 0
highlight GitGutterAdd ctermbg=black
highlight GitGutterAdd ctermfg=green
highlight GitGutterChange ctermbg=grey
highlight GitGutterChange ctermfg=yellow
highlight GitGutterDelete ctermbg=white
highlight GitGutterDelete ctermfg=red
highlight GitGutterChangeDelete ctermbg=white
highlight GitGutterChangeDelete ctermfg=red
command! SynOff let g:syntastic_mode_map = {
\ "mode": "passive",
\ "active_filetypes": [],
\ "passive_filetypes": [] }
command! SynOn let g:syntastic_mode_map = {
\ "mode": "active",
\ "active_filetypes": [],
\ "passive_filetypes": [] }
SynOff
" ------------
" Colorschemes
" ------------
silent! colorscheme seoul256
" colorscheme badwolf
" colorscheme Monokai
" colorscheme two2tango
" colorscheme freya
" colorscheme earendel
" colorscheme moria
" colorscheme github
" colorscheme codeschool
" colorscheme solarized
" ----------------------------------------------------------------------------
" AgCommand
" ----------------------------------------------------------------------------
function! s:ag_to_qf(line)
let parts = split(a:line, ':')
return {'filename': parts[0], 'lnum': parts[1], 'col': parts[2],
\ 'text': join(parts[3:], ':')}
endfunction
function! s:directory_opener(lines)
execute 'e '.a:lines[0]
execute 'only'
endfunction
nnoremap <silent> <C-j> :J<cr>
command! -nargs=* J call fzf#run({
\ 'source': 'source ~/z.sh && _z -l 2>&1 | sed "s/[0-9\.]\+\s\+//" | sed "s@\$@/@"',
\ 'sink*': function('<sid>directory_opener'),
\ 'options': '--ansi '.
\ '--color hl:68,hl+:110',
\ 'down': '50%'
\ })
function! s:ag_handler(lines)
if len(a:lines) < 2 | return | endif
let cmd = get({'ctrl-x': 'split',
\ 'ctrl-v': 'vertical split',
\ 'ctrl-t': 'tabe'}, a:lines[0], 'e')
let list = map(a:lines[1:], 's:ag_to_qf(v:val)')
let first = list[0]
execute cmd escape(first.filename, ' %#\')
execute first.lnum
execute 'normal!' first.col.'|zz'
if len(list) > 1
call setqflist(list)
copen
wincmd p
endif
endfunction
command! -nargs=* A call fzf#run({
\ 'source': printf('ag --nogroup --column --color "%s"',
\ escape(empty(<q-args>) ? '^(?=.)' : <q-args>, '"\')),
\ 'sink*': function('<sid>ag_handler'),
\ 'options': '--ansi --expect=ctrl-t,ctrl-v,ctrl-x --delimiter : --nth 4.. '.
\ '--multi --bind ctrl-a:select-all,ctrl-d:deselect-all '.
\ '--color hl:68,hl+:110',
\ 'down': '50%'
\ })
" ----------------------------------------------------------------------------
" Experimental
" ----------------------------------------------------------------------------
command! -bang AutoSave
\ augroup autosave
\| exec 'autocmd!'
\| if <bang>1
\| exec 'autocmd TextChanged,InsertLeave <buffer> silent update'
\| endif
\| augroup END
function! Consolate()
:execute "normal! Oconsole.log();\<esc>hP"
endfunction
command! -nargs=0 Consolate :call Consolate()
function! EditSubstitute(args)
if (len(a:args))<2
return
endif
let s:delimiter = (a:args[0])
let s:split = split(a:args,s:delimiter,1)[1:]
let s:fullpath = expand('%:p')
let s:bar = substitute(s:fullpath, s:split[0], s:split[1], '')
echo (s:bar)
silent execute('edit '.s:bar)
endfunction
command! -nargs=* EditSubstitute :call EditSubstitute(<q-args>)
command! -nargs=* Et :call EditSubstitute("/src\\(.*\\)\\.js/test\\1.test.js")
command! -nargs=* Es :call EditSubstitute("/test\\(.*\\)\\.test.js/src\\1.js")
" -------------------
" Windowing repeating
" -------------------
function! s:Wincmd(count, key)
" If count is not zero, use the original count. If otherwise, don't
" include a count.
let if_count = a:count ? a:count : ''
" This builds a wincmd from the given key, and saves it so
" it can be repeated.
let g:last_wincmd = 'wincmd ' . nr2char(a:key)
" Execute the built wincmd
execute if_count . g:last_wincmd
endfunction
function! s:WincmdRepeat(count)
" If a count is given, repeat the last wincmd that amount of times.
" If otherwise, just repeat once.
let if_count = a:count ? a:count : ''
execute if_count . g:last_wincmd
endfunction
" Overwrite the default <C-w> mapping so that the last wincmd can be kept
" track of. The getchar function is what captures the key pressed
" directly afterwards. The <C-u> is to remove any cmdline range that vim
" automatically inserted.
nnoremap <silent> <C-w> :<C-u>call <SID>Wincmd(v:count, getchar())<cr>
" This just calls the function which repeats the previous wincmd. It
" does except a count, which is the number of times it should repeat the
" previous wincmd. Also, you can replace Q with whatever key you want.
nnoremap <silent> Q :<C-u> call <SID>WincmdRepeat(v:count)<cr>
" ----------------------------------------------------------------------------
" Filetype defaults
" ----------------------------------------------------------------------------
augroup Filetypes
autocmd!
autocmd BufEnter *.vimrc :setlocal foldmethod=expr foldexpr=VimrcFolds() foldtext=VimrcFoldText()
autocmd BufEnter *.md,*.markdown :setlocal filetype=markdown
autocmd BufEnter *.coffee :setlocal filetype=coffee
autocmd BufEnter *.yml,*.yaml :setlocal filetype=yaml
autocmd BufEnter *.exl :setlocal filetype=exl
autocmd BufEnter *.bowerrc,*.babelrc,*.eslintrc :setlocal filetype=json
autocmd BufEnter *.es6 :setlocal filetype=javascript
autocmd BufNewFile,BufReadPost,BufFilePost *.js,*.bowerrc,*.babelrc,*.eslintrc,*.yml,*.yaml,*.es6 :setlocal tabstop=2 shiftwidth=2 softtabstop=2 expandtab
autocmd FileType php nnoremap <Leader>p :call pdv#DocumentWithSnip()<cr>
autocmd FileType php vnoremap <Leader>p :call pdv#DocumentWithSnip()<cr>
autocmd FileType xml setlocal equalprg=export\ XMLLINT_INDENT\=\"\ \ \ \ \"\ &&\ xmllint\ --format\ --recover\ -\ 2>/dev/null
autocmd FileType netrw setl bufhidden=wipe
autocmd FileType markdown,bash,sh,html,coffee :setlocal noexpandtab
autocmd FileType markdown :setlocal listchars=tab:\ \ ,trail:-
autocmd FileType yaml,vim,coffee,html,sql,json,phtml,php,js,javascript,txt,md,python,css,rb,md,markdown,bash,sh,shell autocmd BufWritePre <buffer> :call StripTrailingWhitespace()
autocmd BufWritePost * :silent !touch /tmp/swatch
augroup END
" -----------
" FZF
" -----------
function! s:buflist()
redir => ls
silent ls
redir END
return split(ls, '\n')
endfunction
function! s:bufopen(e)
execute 'buffer' matchstr(a:e, '^[ 0-9]*')
endfunction
command! VerticalTerm :vs term://zsh
nnoremap <silent> <A-n> :VerticalTerm<cr>A
nnoremap <silent> <Leader>C :call fzf#run({
\ 'source':
\ map(split(globpath(&rtp, "colors/*.vim"), "\n"),
\ "substitute(fnamemodify(v:val, ':t'), '\\..\\{-}$', '', '')"),
\ 'sink': 'colo',
\ 'options': '+m',
\ 'left': 20,
\ 'launcher': 'xterm -geometry 20x30 -e bash -ic %s'
\ })<cr>
nnoremap <silent> <C-b> :call fzf#run({
\ 'source': reverse(<sid>buflist()),
\ 'sink': function('<sid>bufopen'),
\ 'options': '+m',
\ 'down': len(<sid>buflist()) + 2
\ })<cr>
nnoremap Y y$
nnoremap <C-p> :call fzf#run({
\ 'dir':expand('%:p:h'),
\ 'sink': 'e'
\ })<cr>
nnoremap <silent> <C-f> :FZF<cr>
command! FZFTag if !empty(tagfiles()) | call fzf#run({
\ 'source': "sed '/^\\!/d;s/\t.*//' " . join(tagfiles()) . ' | nauniq',
\ 'sink': 'tag',
\ 'options': '+m',
\ 'left': 60,
\ }) | else | echo 'No tags' | endif
nnoremap <silent> <Leader>t :FZFTag<cr>
" ============================================================================
" V - v:oldfiles
" ============================================================================
command! V
\ call fzf#run({'source': filter(copy(v:oldfiles), '!empty(glob(v:val))'),
\ 'sink': 'e',
\ 'down': '30%'})
" ====================
" Buffer search
" ====================
function! s:line_handler(l)
let keys = split(a:l, ':\t')
exec 'buf' keys[0]
exec keys[1]
normal! ^zz
endfunction
function! s:buffer_lines()
let res = []
for b in filter(range(1, bufnr('$')), 'buflisted(v:val)')
call extend(res, map(getbufline(b,0,'$'), 'b . ":\t" . (v:key + 1) . ":\t" . v:val '))
endfor
return res
endfunction
command! FZFLines call fzf#run({
\ 'source': <sid>buffer_lines(),
\ 'sink': function('<sid>line_handler'),
\ 'options': '--extended --nth=3..',
\ 'down': '60%'
\})
function! s:align_lists(lists)
let maxes = {}
for list in a:lists
let i = 0
while i < len(list)
let maxes[i] = max([get(maxes, i, 0), len(list[i])])
let i += 1
endwhile
endfor
for list in a:lists
call map(list, "printf('%-'.maxes[v:key].'s', v:val)")
endfor
return a:lists
endfunction
function! s:btags_source()
let lines = map(split(system(printf(
\ 'ctags -f - --sort=no --excmd=number --language-force=%s %s',
\ &filetype, expand('%:S'))), "\n"), 'split(v:val, "\t")')
if v:shell_error
throw 'failed to extract tags'
endif
return map(s:align_lists(lines), 'join(v:val, "\t")')
endfunction
function! s:btags_sink(line)
execute split(a:line, "\t")[2]
endfunction
function! s:btags()
try
call fzf#run({'source': s:btags_source(),
\'down': '40%',
\'options': '+m -d "\t" --with-nth 1,4.. -n 1 --tiebreak=index',
\'sink': function('s:btags_sink')})
catch
echohl WarningMsg
echom v:exception
echohl None
endtry
endfunction
command! BTags call s:btags()
" -------------
" Cleanup commands
" -------------
func! AddSpaceAfterColumn()
s/:\([\$(_a-z0-9\[\]"']\)/: \1/ge
endfunc
func! AddSpaceBeforeEqual()
s/\([a-z)_0-9"'\[\]]\)=/\1 =/ge
endfunc
func! AddSpaceAfterEqual()
s/=\([\$(_a-z0-9\[\]"']\)/= \1/ge
endfunc
func! AddSpaceAfterArrow()
s/=>\([\$a-z0-9"'\[\]]\)/=> \1/ge
endfunc
func! AddSpaceAfterComma()
s/,\(\S\)/, \1/ge
endfunc
func! CleanUpFileHabiteo()
% call AddSpaceAfterComma()
% call AddSpaceBeforeEqual()
% call AddSpaceAfterEqual()
% call AddSpaceAfterArrow()
endfunc
func! CleanUpLineHabiteo()
call AddSpaceAfterComma()
call AddSpaceBeforeEqual()
call AddSpaceAfterEqual()
call AddSpaceAfterArrow()
endfunc
function! QueryAlign()
let _s=@/
:norm ma
:norm V}k
:norm ^10<"
:silent '<,'>norm I + "
:silent '<,'>norm A"
:norm `a
let @/=_s
endfunction
function! TableAlign()
let _s=@/
:norm ma
/|
:norm V}
:Align |
:silent norm 2<
execute "normal! \<Esc>"
:norm `a
let @/=_s
endfunction
function! StripTrailingWhitespace()
let l:winview = winsaveview()
silent! %s/\s\+$//
call winrestview(l:winview)
endfunction
" ----------------------------------------------------------------------------
" Filetype specific settings
" ----------------------------------------------------------------------------
function! VimrcFolds()
let thisline = getline(v:lnum)
let next2line = getline(v:lnum+2)
if match(thisline, '^" ----') >=0 && match(next2line, '^" ----') >= 0
return '>1'
else
return '='
endif
endfunction
function! VimrcFoldText()
let foldsize = (v:foldend-v:foldstart)
return getline(v:foldstart+1).' ('.foldsize.' lines)'
endfunction
function! s:GoyoEnter()
:silent !tmux set status off
:set noshowmode
:set nonumber
:setlocal wrap
:setlocal wrapmargin=80
let b:quitting = 0
let b:quitting_bang = 0
autocmd QuitPre <buffer> let b:quitting = 1
cabbrev <buffer> q! let b:quitting_bang = 1 <bar> q!
endfunction
function! s:GoyoLeave()
:silent !tmux set status on
" Quit Vim if this is the only remaining buffer
if b:quitting && len(filter(range(1, bufnr('$')), 'buflisted(v:val)')) == 1
if b:quitting_bang
qa!
else
qa
endif
endif
:set showmode
:setlocal number
:setlocal nowrap
endfunction
augroup Goyo
autocmd!
autocmd User GoyoEnter nested call <SID>GoyoEnter()
autocmd User GoyoLeave nested call <SID>GoyoLeave()
augroup END
" ---------
" GVIM specific
" ---------
let s:pattern = '^\(.* \)\([1-9][0-9]*\)$'
let s:minfontsize = 6
let s:maxfontsize = 16
function! AdjustFontSize(amount)
if has('gui_gtk2') && has('gui_running')
let fontname = substitute(&guifont, s:pattern, '\1', '')
let cursize = substitute(&guifont, s:pattern, '\2', '')
let newsize = cursize + a:amount
if (newsize >= s:minfontsize) && (newsize <= s:maxfontsize)
let newfont = fontname . newsize
let &guifont = newfont
endif
else
echoerr 'You need to run the GTK2 version of Vim to use this function.'
endif
endfunction
function! LargerFont()
call AdjustFontSize(1)
endfunction
command! LargerFont call LargerFont()
function! SmallerFont()
call AdjustFontSize(-1)
endfunction
command! SmallerFont call SmallerFont()
" ----------
" Motion mappings
" ----------
function! s:Buflisted()
return filter(range(1, bufnr('$')), 'buflisted(v:val)')
endfunction
function! g:Go_to_last_file()
let b = extend(
\ filter(copy(v:oldfiles),
\ "v:val !~? 'fugitive:\\|^/tmp/\\|.git/'"),
\ filter(map(s:Buflisted(), 'bufname(v:val)'), '!empty(v:val)'))
execute('e ' . b[0])
return b[0]
endfunction
command! L silent call g:Go_to_last_file()
function! s:ZealMotion(type) abort
let reg_save = @@
call s:CopyMotionForType(a:type)
execute "normal :!tmux split \"source ~/scripts/zeal.load ; zealdoc '" . shellescape(@@) ."'\" \<cr>"
let @@ = reg_save
endfunction
function! s:SearchMotion(type) abort
let reg_save = @@
call s:CopyMotionForType(a:type)
execute 'normal! :!firefox -search ' . shellescape(@@) . "\<cr>"
let @@ = reg_save
endfunction
function! s:NpmInstallMotion(type) abort
let reg_save = @@
call s:CopyMotionForType(a:type)
execute 'normal! :!npm install --save ' . shellescape(@@) . "\<cr>"
let @@ = reg_save
endfunction
function! s:CopyMotionForType(type)
if a:type ==# 'v'
silent execute 'normal! `<' . a:type . '`>y'
elseif a:type ==# 'char'
silent execute 'normal! `[v`]y'
endif
endfunction
function! s:AMotion(type) abort
let reg_save = @@
call s:CopyMotionForType(a:type)
execute 'normal! :A ' . @@ . "\<cr>"
let @@ = reg_save
endfunction
nnoremap <silent> <Leader>a :set opfunc=<SID>AMotion<cr>g@
xnoremap <silent> <Leader>a :<C-U>call <SID>AMotion(visualmode())<cr>
function! s:AgMotion(type) abort
let reg_save = @@
call s:CopyMotionForType(a:type)
execute 'normal! :Ag ' . shellescape(@@) . "\<cr>"
let @@ = reg_save
endfunction
nnoremap <silent> <Leader>z :set opfunc=<SID>ZealMotion<cr>g@
xnoremap <silent> <Leader>z :<C-U>call <SID>ZealMotion(visualmode())<cr>
nnoremap <silent> <Leader>f :set opfunc=<SID>SearchMotion<cr>g@
xnoremap <silent> <Leader>f :<C-U>call <SID>SearchMotion(visualmode())<cr>
nnoremap <silent> <Leader>n :set opfunc=<SID>NpmInstallMotion<cr>g@
xnoremap <silent> <Leader>n :<C-U>call <SID>NpmInstallMotion(visualmode())<cr>
" ----------
" Normal mappings
" ----------
" maximize current visible window
nnoremap <Leader>o :only<cr>
nnoremap <Leader>d :e %:h<cr>
nnoremap <up> :m .-2<cr>==
nnoremap <down> :m .+1<cr>==
inoremap <up> <Esc>:m .-2<cr>==gi
inoremap <down> <Esc>:m .+1<cr>==gi
nnoremap <right> :bn<cr>
nnoremap <left> :bp<cr>
vnoremap <down> :m '>+1<cr>gv
vnoremap <up> :m '<-2<cr>gv
nnoremap <A-4> :tabprevious<cr>
nnoremap <A-6> :tabnext<cr>
nnoremap <A-5> :tabnew<cr>
inoremap jj <Esc>
nnoremap <Leader>ev :e ~/.${VIM_V}rc<cr>
nnoremap <Leader>eb :e ~/.bashrc<cr>
nnoremap <Leader>eu :e ~/.config/nvim/plugged<cr>
nnoremap <Leader>et :e ~/.tmux.conf<cr>
"Source vimrc
nnoremap <Leader>sv :source $MYVIMRC<cr>
"remove find results
command! H let @/=''
nnoremap <silent><esc> <esc>:nohlsearch<CR><esc>
nnoremap <space> :
nnoremap <C-n> :bp\|bd #<cr>
nnoremap <ScrollWhellUp> <C-Y>
nnoremap <ScrollWhellDown> <C-E>
highlight SignColumn ctermbg=brown
highlight SignColumn ctermfg=white
nnoremap <Leader>l :FZFLines<cr>
function! LocationPrevious()
try
lprev
catch /^Vim\%((\a\+)\)\=:E553/
echom('ep')
llast
catch /^Vim\%((\a\+)\)\=:E776/
echom('No location list')
catch /^Vim\%((\a\+)\)\=:E42/
echom('No Errors')
endtry
endfunction
function! LocationNext()
try
lnext
catch /^Vim\%((\a\+)\)\=:E553/
lfirst
catch /^Vim\%((\a\+)\)\=:E776/
echom('No location list')
catch /^Vim\%((\a\+)\)\=:E42/
echom('No Errors')
endtry
endfunction
inoremap <F1> <nop>
nnoremap <F1> :call LocationNext()<cr>
nnoremap <F2> :call LocationPrevious()<cr>
nnoremap <Leader>c :read !cat<cr>
nnoremap K :Neomake<cr>
nnoremap \k :w! \| :Neomake<cr>
if(has("nvim"))
tnoremap <Esc> <C-\><C-n>
tnoremap <A-h> <C-\><C-n><C-w>h
tnoremap <A-j> <C-\><C-n><C-w>j
tnoremap <A-k> <C-\><C-n><C-w>k
tnoremap <A-l> <C-\><C-n><C-w>l
tnoremap <a-a> <esc>a
tnoremap <a-b> <esc>b
tnoremap <a-d> <esc>d
tnoremap <a-f> <esc>f
endif
nnoremap <A-h> <C-w>h
nnoremap <A-j> <C-w>j
nnoremap <A-k> <C-w>k
nnoremap <A-l> <C-w>l
cnoremap <Esc>b <S-Left>
cnoremap <Esc>f <S-Right>
cnoremap <A-b> <S-Left>
cnoremap <A-f> <S-Right>
cnoremap <A-d> <S-Right><C-w>
nnoremap <silent> <Leader>v :BTags<cr>
nnoremap \\ :w!<cr>
function! EslintFix()
:w!
:!jlint % --fix
:e
endfunction
nnoremap \s :call EslintFix()<cr>
nnoremap <Leader>q :qa!<cr>
" Save a file as root (,W)
nnoremap <leader>W :w !sudo tee % > /dev/null<cr>
function! s:ToggleTestOnly()
let l:winview = winsaveview()
if match(join(getline(1,'.'), "\n"),"describe\\\.only")!=-1 || match(join(getline(1,'.'), "\n"),"it\\\.only")!=-1
normal j
silent execute "?only("
normal 0f.dt(
else
let l:itmatch=match(join(reverse(getline(1,'.')), '\n'),'it(')
let l:dematch=match(join(reverse(getline(1,'.')), '\n'),'describe(')
if (l:itmatch==-1 && l:dematch==-1)
return
endif
normal j
if l:itmatch<l:dematch && l:itmatch!=-1
silent execute "?it("
else
silent execute "?describe("
endif
normal ea.only
endif
call winrestview(l:winview)
endfunction
command! ToggleTestOnly call s:ToggleTestOnly()
nnoremap <Leader>n :ToggleTestOnly<cr>
" Toggle the UndoTree on an off with F8
nnoremap <F8> :UndotreeToggle<cr>
function! CopyWholeFile()
let l:winview = winsaveview()
let _s=@/
:norm ggyG
:call CopyVar()
let @/=_s
call winrestview(l:winview)
endfunction
function! CopyVar()
redir! > /tmp/varfile | sil exe 'echo @"' |redir end
call system ("sed '1d' /tmp/varfile > /tmp/tmpvarfile; mv /tmp/tmpvarfile /tmp/varfile")
call system('cat /tmp/varfile | copy && rm /tmp/varfile')
endfunction
nnoremap <Leader>y :call CopyVar()<cr>
nnoremap <Leader>Y :call CopyWholeFile()<cr>
nnoremap gn :GitGutterNextHunk<cr>
nnoremap gN :GitGutterPrevHunk<cr>
nnoremap gs :GitGutterStageHunk<cr>
nnoremap gr :GitGutterRevertHunk<cr>
"====[ I'm sick of typing :%s/.../.../g ]=======
nnoremap S :%s//g<LEFT><LEFT>
nnoremap <expr> M ':%s/' . @/ . '//g<LEFT><LEFT>'
vnoremap <expr> M ':s/' . @/ . '//g<LEFT><LEFT>'
" Because , is useful but is our leader
nnoremap ,, ,
" Open last selected area when pasted
noremap gV `[v`]
nnoremap yr :.w !bash<cr>
vnoremap < <gv
vnoremap > >gv
cnoremap :: <C-r>=expand('%:p:h').'/'<cr>
function! s:escaped(first, last) abort
let files = getline(a:first, a:last)
call filter(files, 'v:val !~# "^\" "')
call map(files, 'substitute(v:val, "[/*|@=]\\=\\%(\\t.*\\)\\=$", "", "")')
return join(map(files, 'fnamemodify(b:netrw_curdir."/".v:val,":~:.")'), ' ')
endfunction
cnoremap ;; <C-R>=<SID>escaped(line('.'), line('.') - 1 + v:count1)<cr>
" Make vaa select the entire file...
vmap aa VGo1G
imap <c-x><c-k> <plug>(fzf-complete-word)
imap <c-x><c-f> <plug>(fzf-complete-file-ag)
imap <c-x><c-j> <plug>(fzf-complete-file-ag)
imap <c-x><c-l> <plug>(fzf-complete-line)
" fzf mappings
nnoremap <Leader>m :Map<cr>
" fzf buffers
nnoremap <Leader>b :Buffers<cr>
" Align | Tables
nnoremap <Leader>g :call TableAlign()<cr>
" Search with */# from visual mode
vnoremap * "zy/<c-r>z<cr>
vnoremap # "zy?<c-r>z<cr>n
nnoremap <silent> <Leader>ag :Ag <C-R><C-W><cr>
silent !echo $NVIM_LISTEN_ADDRESS >> /tmp/nvim_listen_adress
function! Eslint()
call system('cat .gitignore .eslintignore > /tmp/ignore_path; jlint . --ignore-path /tmp/ignore_path --fix --cache -f unix | grep "^$" -v | grep -v -E "[0-9]+ problems?" > /tmp/qf')
cfile /tmp/qf
copen
endfunction
nnoremap <Leader>p :call Eslint()<cr>
function! RealignColumns()
%s/:\([{"]\)/: \1/g
endfunction
" Open tag in new vsplit
nnoremap <silent><Leader><C-]> <C-w><C-]><C-w>L
fun! UltiVim()
exec 'e ~/.vim/UltiSnips/'. &filetype . '.snippets'
endf
command! UltiVim :call UltiVim()
fun! s:DetectSheBang()
if getline(1) ==# '#!/bin/bash'
set ft=sh
endif
endfun
fun! s:OpenTermAsync()
let command = 'echo "foo" > /tmp/f'
silent exec 'enew'
call termopen(command,)
silent exec 'stopinsert'
bp
endfun
command! Ta :call s:OpenTermAsync()
augroup detectShebang
autocmd!
autocmd BufNewFile,BufRead * call s:DetectSheBang()
augroup END
"I have the habit of recording scratch macros in the q register. This makes playback easier.
nnoremap <bs> @q
"With this I don't have to do stuff like 100@q, I can just visually select lines and press backspace.
vnoremap <silent> <bs> :norm @q<cr>
" :let @q = '^'<cr> stores ^ inside register q
" ^ moves the cursor to the first non whitespace character on the line
" qQ begins recording a macro inside register q by appending (!=overwriting) the next typed keys to its previous content (qq would overwrite the ^ we just stored in @q)
nnoremap qq :let @q = '^'<cr>^qQ
nnoremap \ <C-w>
nnoremap ,A :A<cr>
nnoremap s ciw
nnoremap <F8> :TagbarToggle<cr>
nnoremap <C-w>f :vertical wincmd f<cr>
nnoremap <leader>m :<c-u><c-r>='let @'. 'q' .' = '. string(getreg("q"))<cr><c-f><left>
" Profile
" ----------------------------------------------------------------------------
function! s:profile(bang)
if a:bang
profile pause
noautocmd qall
else
profile start /tmp/profile.log
profile func *
profile file *
endif
endfunction
command! -bang Profile call s:profile(<bang>0)
command! -nargs=* Viw execute('e '.system(printf('getloc "%s"',escape(empty(<q-args>) ? '' : <q-args>, '"\'))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment