" My .vimrc " Basic "{{{1 " Absolute "{{{2 if has('vim_starting') if has('win32') || has('win64') set runtimepath=~/.vim,$VIMRUNTIME,~/.vim/after endif set runtimepath^=~/.vim/bundle/* set runtimepath+=~/.vim/bundle/*/after endif if has('kaoriya') " Hate default vimrc and gvimrc. call delete($VIM . '/vimrc') call delete($VIM . '/gvimrc') endif function! s:SID_PREFIX() return matchstr(expand(''), '\d\+_') endfunction " Encoding "{{{2 set encoding=utf-8 if has('iconv') let s:enc_euc = 'euc-jp' let s:enc_jis = 'iso-2022-jp' " Does iconv support JIS X 0213 ? if iconv("\x87\x64\x87\x6a", 'cp932', 'euc-jisx0213') ==# "\xad\xc5\xad\xcb" let s:enc_euc = 'euc-jisx0213' let s:enc_jis = 'iso-2022-jp-3' endif " Make fileencodings let &fileencodings = s:enc_jis let &fileencodings .= ',' . s:enc_euc let &fileencodings .= ',' . 'utf-8' let &fileencodings .= ',' . 'cp932' let &fileencodings .= ',' . 'ucs-bom' unlet s:enc_euc unlet s:enc_jis endif if has('win32') || has('win64') language C set fileformat=unix set termencoding=cp932 elseif has('gui_macvim') language C endif " Options "{{{2 if (1 < &t_Co || has('gui')) && has('syntax') syntax enable if !exists('g:colors_name') colorscheme basic256 endif endif filetype plugin indent on if has('gui_running') set guicursor=a:blinkwait4000-blinkon1500-blinkoff500 if has('gui_gtk2') set guifont=Monospace\ 10 set linespace=5 elseif has('gui_macvim') set guifont=Source\ Code\ Pro:h14 set linespace=6 set macmeta set transparency=0 set visualbell elseif has('gui_win32') set guifont=Consolas:h10.5 set linespace=2 endif set guioptions=AcgM endif if has('kaoriya') && has('gui_win32') set ambiwidth=auto else set ambiwidth=double endif set backspace=indent,eol,start set nobackup if has('clientserver') set clipboard=autoselectml,exclude:cons\|linux endif set complete& set complete-=i set completeopt=menuone,longest set confirm set diffopt=filler,vertical set directory=~/tmp,/tmp set fileformats=unix,dos,mac set hidden set history=1000 if has('multi_byte_ime') || has('xim') set iminsert=0 set imsearch=0 endif set keywordprg=:help set nowritebackup if exists('+shellslash') set shell=bash set shellcmdflag=-c set shellpipe=2>&1\|\ tee set shellslash endif set spelllang=en_us set updatetime=1000 set virtualedit=block if exists('+breakindent') set breakindent endif set cmdheight=1 if has('conceal') set concealcursor=nc set conceallevel=1 endif set nocursorline set display=lastline set noequalalways set foldmethod=marker set nohlsearch set laststatus=2 set linebreak set list let &listchars = "tab:\u00bb ,trail:-,extends:>,precedes:<,conceal:|,nbsp:." set pumheight=20 set ruler set scrolloff=4 set showcmd set showtabline=1 set splitbelow set splitright set ttimeoutlen=50 set wildmenu set wildmode=full set nowrapscan set autoindent set cinoptions=:0,l1,g0,t0,(0,W1s set formatoptions=roqnlmM1 set formatlistpat& let &formatlistpat .= '\|^\s*[*+-]\s*' set ignorecase set incsearch set shiftround set smartcase set smartindent set title set titlestring=Vim:\ %f\ %h%r%m if exists('$TMUX') " Fix window title on tmux. let &t_fs = "\" let &t_ts = "\]2;" endif let &statusline = '' let &statusline .= '%<%f %h%m%r%w' let &statusline .= '%=' let &statusline .= '[' let &statusline .= '%{&l:fileencoding == "" ? &encoding : &l:fileencoding}' let &statusline .= '%{&l:bomb ? "/BOM" : ""}' let &statusline .= ']' let &statusline .= '[%{&l:fileformat}]' let &statusline .= ' %-14.(%l,%c%V%) %P' function! s:my_tabline() "{{{ let s = '' for i in range(1, tabpagenr('$')) let bufnrs = tabpagebuflist(i) let curbufnr = bufnrs[tabpagewinnr(i) - 1] " first window, first appears let no = (i <= 10 ? i - 1 : '#') " display 0-origin tabpagenr. let mod = getbufvar(curbufnr, '&modified') ? '+' : ' ' let title = gettabvar(i, 'title') let title = title != '' ? title : fnamemodify(bufname(curbufnr), ':t') let title = title != '' ? title : '[No Name]' let s .= '%' . i . 'T' let s .= '%#' . (i == tabpagenr() ? 'TabLineSel' : 'TabLine') . '#' let s .= no let s .= mod let s .= title let s .= '%#TabLineFill#' let s .= ' ' endfor let branch_name = s:vcs_branch_name(getcwd()) let s .= '%#TabLineFill#%T' let s .= '%=%#TabLine#' let s .= branch_name let s .= ' | %<' let s .= fnamemodify(getcwd(), ':t') return s endfunction "}}} let &tabline = '%!' . s:SID_PREFIX() . 'my_tabline()' let g:mapleader = ',' let g:maplocalleader = '.' " Misc. "{{{2 " Use this group for any autocmd defined in this file. augroup MyAutoCmd autocmd! augroup END call altercmd#load() call arpeggio#load() call metarw#define_wrapper_commands(0) " Syntax {{{1 " :setlocal wrappers "{{{2 command! -nargs=? -complete=customlist,s:complete_fileencoding SetFileEncoding \ setlocal fileencoding= command! -nargs=? -complete=customlist,s:complete_fileformats SetFileFormat \ setlocal fileformat= function! s:complete_fileencoding(arglead, cmdline, cursorpos) " {encoding: 0} see :help encoding-values. "{{{ let _ = { \ 'ansi': 0, \ 'big5': 0, \ 'chinese': 0, \ 'cp1250': 0, \ 'cp1251': 0, \ 'cp1253': 0, \ 'cp1254': 0, \ 'cp1255': 0, \ 'cp1256': 0, \ 'cp1257': 0, \ 'cp1258': 0, \ 'cp437': 0, \ 'cp737': 0, \ 'cp775': 0, \ 'cp850': 0, \ 'cp852': 0, \ 'cp855': 0, \ 'cp857': 0, \ 'cp860': 0, \ 'cp861': 0, \ 'cp862': 0, \ 'cp863': 0, \ 'cp865': 0, \ 'cp866': 0, \ 'cp869': 0, \ 'cp874': 0, \ 'cp932': 0, \ 'cp936': 0, \ 'cp949': 0, \ 'cp950': 0, \ 'default': 0, \ 'euc-cn': 0, \ 'euc-jp': 0, \ 'euc-kr': 0, \ 'euc-tw': 0, \ 'iso-8859-10': 0, \ 'iso-8859-11': 0, \ 'iso-8859-12': 0, \ 'iso-8859-13': 0, \ 'iso-8859-14': 0, \ 'iso-8859-15': 0, \ 'iso-8859-16': 0, \ 'iso-8859-1': 0, \ 'iso-8859-2': 0, \ 'iso-8859-3': 0, \ 'iso-8859-4': 0, \ 'iso-8859-5': 0, \ 'iso-8859-6': 0, \ 'iso-8859-7': 0, \ 'iso-8859-8': 0, \ 'iso-8859-9': 0, \ 'japan': 0, \ 'koi8-r': 0, \ 'koi8-u': 0, \ 'korea': 0, \ 'latin1': 0, \ 'macroman': 0, \ 'prc': 0, \ 'sjis': 0, \ 'taiwan': 0, \ 'ucs-2': 0, \ 'ucs-2be': 0, \ 'ucs-2le': 0, \ 'ucs-4': 0, \ 'ucs-4be': 0, \ 'ucs-4le': 0, \ 'ucs2be': 0, \ 'unicode': 0, \ 'utf-16': 0, \ 'utf-16le': 0, \ 'utf-32': 0, \ 'utf-32le': 0, \ 'utf-8': 0, \ 'utf8': 0, \ } " }}} for encoding in split(&fileencodings, ',') let _[encoding] = 0 endfor return sort(filter(keys(_), 's:prefix_of_p(a:arglead, v:val)')) endfunction function! s:complete_fileformats(arglead, cmdline, cursorpos) return sort(filter(split(&fileformats, ','), 's:prefix_of_p(a:arglead, v:val)')) endfunction " CD - wrapper of :cd to keep cwd for each tabpage "{{{2 command! -complete=dir -nargs=* CD \ execute 'cd' fnameescape() \ | let t:cwd = getcwd() \ | echo t:cwd AlterCommand cd CD autocmd MyAutoCmd TabEnter * \ if !exists('t:cwd') \ | let t:cwd = getcwd() \ | endif \ | if isdirectory(t:cwd) \ | cd `=t:cwd` \ | endif " MessageClear "{{{2 command! -bar MessageClear \ for i in range(200) | echomsg '' | endfor | unlet i " HelpTagsAll "{{{2 command! -bang -nargs=0 HelpTagsAll call s:cmd_HelpTagsAll(0) function! s:cmd_HelpTagsAll(banged_p) for path in split(globpath(&runtimepath, 'doc'), '\n') if filewritable(path) helptags `=path` if a:banged_p echo fnamemodify(path, ':~') endif endif endfor endfunction " Rename - rename file and buffer "{{{2 command! -complete=file -nargs=1 Rename call s:cmd_Rename() function! s:cmd_Rename(name) let current = expand('%') if &l:readonly || !&l:modifiable || !(filereadable(a:name) || filewritable(current)) echohl ErrorMsg echo 'This file cannot be changes:' a:name echohl None elseif filereadable(a:name) echohl ErrorMsg echo 'Renamed file already exists:' a:name echohl None else file `=a:name` call delete(current) write redraw echo 'Renamed:' current '->' a:name endif endfunction " Source - wrapper of :source with echo "{{{2 command! -bar -complete=file -nargs=1 Source \ echo 'Sourcing ...' expand() \ | source AlterCommand so[urce] Source " SuspendWithAutomticCD "{{{2 command! -bar -nargs=0 SuspendWithAutomticCD \ call s:cmd_SuspendWithAutomticCD() function! s:cmd_SuspendWithAutomticCD() let shell = split(&shell, '/')[-1] if has('gui_running') && has('macunix') silent !open -a Terminal elseif exists('$TMUX') let windows = split(vimproc#system('tmux list-windows'), '\n') call map(windows, 'split(v:val, "^\\d\\+\\zs:\\s")') call filter(windows, 'matchstr(v:val[1], "\\w\\+") ==# shell') let select_command = empty(windows) \ ? 'new-window' \ : 'select-window -t ' . windows[0][0] silent execute '!tmux' \ select_command '\;' \ 'send-keys C-u " cd \"'.getcwd().'\"" C-m' redraw! elseif exists('$WINDOW') silent execute '!screen -X eval' \ '''select '.shell.'''' \ '''stuff "\025 cd \\"'.getcwd().'\\" \015"''' redraw! else suspend endif endfunction " TabpageTitle - name the current tabpage "{{{2 command! -bar -nargs=* TabpageTitle \ if == '' \ | let t:title = input("Set tabpage's title to: ", '') \ | else \ | let t:title = \ | endif \ | redraw! " Utf8 and others - :edit with specified 'fileencoding' "{{{2 command! -bang -bar -complete=file -nargs=? Cp932 \ edit ++enc=cp932 command! -bang -bar -complete=file -nargs=? Eucjp \ edit ++enc=euc-jp command! -bang -bar -complete=file -nargs=? Iso2022jp \ edit ++enc=iso-2022-jp command! -bang -bar -complete=file -nargs=? Utf8 \ edit ++enc=utf-8 command! -bang -bar -complete=file -nargs=? Utf16be \ edit ++enc=utf-16be command! -bang -bar -complete=file -nargs=? Utf16 \ edit ++enc=utf-16le command! -bang -bar -complete=file -nargs=? Utf32be \ edit ++enc=utf-32be command! -bang -bar -complete=file -nargs=? Utf32 \ edit ++enc=utf-32le command! -bang -bar -complete=file -nargs=? Dos \ edit ++ff=dos command! -bang -bar -complete=file -nargs=? Unix \ edit ++ff=unix command! -bang -bar -complete=file -nargs=? Mac \ edit ++ff=mac command! -bang -bar -complete=file -nargs=? Jis Iso2022jp command! -bang -bar -complete=file -nargs=? Sjis Cp932 command! -bang -bar -complete=file -nargs=? Unicode Utf16 " Utilities "{{{1 " :grep wrappers "{{{2 command! -bar -complete=file -nargs=+ Grep call s:grep('grep', []) command! -bar -complete=file -nargs=+ Lgrep call s:grep('lgrep', []) function! s:grep(command, args) let target = join(a:args[:-2], ' ') let grepprg = &l:grepprg == '' ? &grepprg : &l:grepprg if grepprg ==# 'internal' execute a:command '/'.escape(a:args[-1], '/ ').'/j' target else execute a:command.'!' shellescape(a:args[-1]) target endif if a:command ==# 'grep' cwindow else " lgrep lwindow endif endfunction AlterCommand gr[ep] Grep AlterCommand lgr[ep] Lgrep " :make wrappers "{{{2 command! -bar -complete=file -nargs=* Make call s:make('make', []) command! -bar -complete=file -nargs=* Lmake call s:make('lmake', []) function! s:make(command, args) let original_winnr = winnr() try execute a:command.'!' join(a:args) catch echohl ErrorMsg echo v:exception echohl None endtry if a:command ==# 'make' cwindow else " lmake lwindow endif execute original_winnr 'wincmd w' endfunction AlterCommand mak[e] Make AlterCommand lmak[e] Lmake " Buffer cleaner "{{{2 command! -bang -nargs=0 BufferCleaner call s:cmd_BufferCleaner(0) function! s:cmd_BufferCleaner(banged_p) let _ = range(1, bufnr('$')) call filter(_, 'bufexists(v:val) \ && buflisted(v:val) \ && (bufname(v:val) == "" || !filereadable(bufname(v:val))) \ && (a:banged_p || !getbufvar(v:val, "&modified"))') for bufnr in _ silent execute bufnr 'bdelete'.(a:banged_p ? '!' : '') endfor echo len(_) 'buffer deleted' endfunction " Fold debugger "{{{2 command! -range=% FoldDebug \ ,global/^/echo printf("%*d [%-2s] %s", len(line('$')), line('.'), eval(substitute(&l:foldexpr, 'v:lnum', line('.'), '')), getline('.')) " High-level key sequences "{{{2 function! s:keys_to_complete() if &l:completefunc != '' return "\\" elseif &l:filetype ==# 'vim' return "\\" elseif &l:omnifunc != '' return "\\" else return "\" endif endfunction function! s:keys_to_insert_one_character() echohl ModeMsg echo '-- INSERT (one char) --' echohl None return nr2char(getchar()) . "\" endfunction function! s:keys_to_stop_insert_mode_completion() if pumvisible() return "\" else return "\\" endif endfunction " Jump sections "{{{2 " for normal mode. a:pattern is '/regexp' or '?regexp'. function! s:jump_section_n(pattern) let pattern = a:pattern[1:] let forward_p = a:pattern[0] == '/' let flags = forward_p ? 'W' : 'Wb' mark ' let i = 0 while i < v:count1 if search(pattern, flags) == 0 if forward_p normal! G else normal! gg endif break endif let i = i + 1 endwhile endfunction " for visual mode. a:motion is '[[', '[]', ']]' or ']['. function! s:jump_section_v(motion) execute 'normal!' "gv\" execute 'normal' v:count1 . a:motion let line = line('.') let col = col('.') normal! gv call cursor(line, col) endfunction " for operator-pending mode. a:motion is '[[', '[]', ']]' or ']['. function! s:jump_section_o(motion) execute 'normal' v:count1 . a:motion endfunction " Indent setter "{{{2 command! -bar -nargs=1 TabIndent \ setlocal noexpandtab softtabstop< tabstop= shiftwidth= command! -bar -nargs=1 SpaceIndent \ setlocal expandtab tabstop< softtabstop= shiftwidth= " Plugin manager "{{{2 command! -bang -complete=customlist,s:complete_bundle -nargs=+ Bundle \ call s:bundle._call(, 0) function! s:complete_bundle(arglead, cmdline, cursorpos) return filter(keys(s:bundle), \ 'v:val =~# "^[a-z]" && s:prefix_of_p(a:arglead, v:val)') endfunction let s:bundle = { \ 'DIR': $HOME . '/.vim/bundle' \ } function! s:bundle._call(action, ...) dict "{{{3 call call(get(self, a:action, self.help), a:000, self) endfunction function! s:bundle.help(banged_p) dict "{{{3 echo 'Usage:' echo printf(' :Bundle [%s]', \ join(filter(keys(self), 'v:val =~# "^[a-z]"'), '|')) endfunction function! s:bundle.install(package, banged_p) dict "{{{3 let m = matchlist(a:package, '^\(\%(git\|https\?\)://[^/]\+\)\?/*\(.\+\)') if !empty(m) if m[1] == '' let m[1] = 'git://github.com' endif let m[2] = substitute(m[2], '\.git$', '', '') let bundle = self.DIR . '/' . substitute(m[2], '/', '_', '') let command = join([ \ 'git', \ 'clone', \ shellescape(join(m[1:2], '/') . '.git'), \ shellescape(bundle) \ ]) if isdirectory(bundle) echohl ErrorMsg echo 'Already installed package:' a:package echohl None else echo system(command) silent! execute 'source' bundle . '/plugin/*.vim' endif else echohl ErrorMsg echo 'Invalid package:' a:package echohl None endif endfunction function! s:bundle.list(banged_p) dict "{{{3 let bundles = split(glob(self.DIR . '/*'), "\n") echohl Title echo len(bundles) 'plugins available' echohl None for bundle in bundles let head = bundle . '/.git/HEAD' if filereadable(head) echo readfile(head, '')[0] fnamemodify(bundle, ':t') else echo fnamemodify(bundle, ':t') endif endfor endfunction function! s:bundle.update(banged_p) dict "{{{3 for bundle in split(glob(self.DIR . '/*'), "\n") if !a:banged_p \ && localtime() - getftime(bundle . '/.git/FETCH_HEAD') < 60 * 60 * 24 echohl Title echo fnamemodify(bundle, ':t') 'is already updated' echohl None continue endif let git = join([ \ 'git', \ '--git-dir', \ shellescape(bundle . '/.git'), \ '--work-tree', \ shellescape(bundle) \ ]) let remote = split(system(git . ' remote -v'), '\n', !0) if v:shell_error != 0 || remote[0] !~# '^origin\s\(git\|https\?\)://' continue endif echohl Title echo 'Update' fnamemodify(bundle, ':t') '...' echohl None let result = system(git . ' pull --rebase') if v:shell_error == 0 echo result else echohl ErrorMsg echomsg 'Error:' fnamemodify(bundle, ':t') echomsg result echohl None endif endfor endfunction " Sequence number substitutions "{{{2 " " :Seq /{pattern}[/format][/options] " " Example: Print the number in front of each line: " :Seq/^/%03d / " " Example: Set start number and step " :Seq/^/%d /100+2 command! -range -nargs=+ Seq \ ,call s:cmd_Seq() function! s:cmd_Seq(args) range let parse_pattern = '\v^([\x00-\xff]&[^\\"|[:alnum:][:blank:]])' \ . '(%(\\.|.){-})' \ . '%(\1(%(\\.|.){-})' \ . '%(\1(%(\\.|.){-}))?)?$' let _ = matchlist(a:args, parse_pattern) if empty(_) throw 'invalid arguments' endif let separator = _[1] let pattern = _[2] let format = _[3] let options = _[4] let incrementer = { \ 'format': format, \ 'current': 1, \ 'step': 1, \ } let options = '' for c in split(options, '\([+-]\?\d\+\|.\)\zs') if c =~ '^[+-]\d\+' let incrementer.step = str2nr(c) elseif c =~ '^\d' let incrementer.current = str2nr(c) else let options .= c endif endfor function incrementer.call() dict let next = printf(self.format, self.current) let self.current += self.step return next endfunction execute printf('%d,%dsubstitute%s%s%s\=incrementer.call()%s%s', \ a:firstline, \ a:lastline, \ separator, \ pattern, \ separator, \ separator, \ options) endfunction " Toggle options "{{{2 function! s:toggle_grepprg(global_p) let VALUES = ['git grep -n', 'ag --nogroup --nocolor', 'grep -nHE',] let grepprg = &l:grepprg == '' ? &grepprg : &l:grepprg let i = (index(VALUES, grepprg) + 1) % len(VALUES) if a:global_p let &grepprg = VALUES[i] set grepprg? else let &l:grepprg = VALUES[i] setlocal grepprg? endif endfunction if has('vim_starting') silent call s:toggle_grepprg(!0) endif function! s:toggle_foldmethod(global_p) let VALUES = ['marker', 'expr'] let foldmethod = &l:foldmethod == '' ? &foldmethod : &l:foldmethod let i = (index(VALUES, foldmethod) + 1) % len(VALUES) if a:global_p let &foldmethod = VALUES[i] set foldmethod? else let &l:foldmethod = VALUES[i] setlocal foldmethod? endif endfunction function! s:toggle_option(option_name) execute 'setlocal' a:option_name.'!' execute 'setlocal' a:option_name.'?' endfunction function! s:toggle_colorcolumn() if exists('b:textwidth') let &l:textwidth = b:textwidth unlet b:textwidth setlocal colorcolumn& colorcolumn? else let b:textwidth = &l:textwidth if b:textwidth == 0 setlocal textwidth=80 endif setlocal colorcolumn=+1 colorcolumn? endif endfunction " Vertical with "{{{2 function! s:vertical_p() return winwidth(0) > winheight(0) * 5 endfunction function! s:vertical_with(command, args) execute s:vertical_p() ? 'vertical' : '' \ a:command \ join(a:args) endfunction command! -bar -complete=file -nargs=* Split \ call s:vertical_with('split', []) command! -bar -complete=file -nargs=* SplitTop \ call s:vertical_with('topleft', ['split', ]) command! -bar -complete=file -nargs=* SplitBottom \ call s:vertical_with('botright', ['split', ]) command! -bar -complete=help -nargs=* Help \ call s:vertical_with('help', []) command! -bar -complete=file -nargs=* New \ call s:vertical_with('new', []) command! -bar -complete=file -nargs=* SplitLeft SplitTop command! -bar -complete=file -nargs=* SplitRight SplitBottom AlterCommand sp[lit] Split AlterCommand h[elp] Help AlterCommand new New " VCS branch name "{{{2 " Returns the name of the current branch of the given directory. " BUGS: git is only supported. let s:_vcs_branch_name_cache = {} " dir_path = [branch_name, cache_key] function! s:vcs_branch_name(dir) let cache_entry = get(s:_vcs_branch_name_cache, a:dir, 0) if cache_entry is 0 \ || cache_entry[1] !=# s:_vcs_branch_name_cache_key(a:dir) unlet cache_entry let cache_entry = s:_vcs_branch_name(a:dir . '/.git') let s:_vcs_branch_name_cache[a:dir] = cache_entry endif return cache_entry[0] endfunction function! s:_vcs_branch_name_cache_key(dir) return getftime(a:dir . '/.git/HEAD') . getftime(a:dir . '/.git/MERGE_HEAD') endfunction function! s:_vcs_branch_name(dir) if isdirectory(a:dir) if isdirectory(a:dir . '/rebase-apply') if filereadable(a:dir . '/rebase-apply/rebasing') let additional_info = 'REBASE' elseif filereadable(a:dir . '/rebase-apply/applying') let additional_info = 'AM' else let additional_info = 'AM/REBASE' endif let head_info = s:first_line(a:dir . '/HEAD') elseif filereadable(a:dir . '/rebase-merge/interactive') let additional_info = 'REBASE-i' let head_info = s:first_line(a:dir . '/rebase-merge/head-name') elseif isdirectory(a:dir . '/rebase-merge') let additional_info = 'REBASE-m' let head_info = s:first_line(a:dir . '/rebase-merge/head-name') elseif filereadable(a:dir . '/MERGE_HEAD') let additional_info = 'MERGING' let head_info = s:first_line(a:dir . '/HEAD') else " Normal case let additional_info = '' let head_info = s:first_line(a:dir . '/HEAD') endif let branch_name = matchstr(head_info, '^\(ref: \)\?refs/heads/\zs\S\+\ze$') if branch_name == '' let lines = readfile(a:dir . '/logs/HEAD') let co_lines = filter(lines, 'v:val =~# "checkout: moving from"') let log = empty(co_lines) ? '' : co_lines[-1] let branch_name = substitute(log, '^.* to \([^ ]*\)$', '\1', '') if branch_name == '' let branch_name = '(unknown)' endif endif if additional_info != '' let branch_name .= ' ' . '(' . additional_info . ')' endif elseif filereadable(a:dir) return s:_vcs_branch_name(matchstr(s:first_line(a:dir), 'gitdir:\s\zs.*')) else " Not in a git repository. let branch_name = '' endif return [branch_name, s:_vcs_branch_name_cache_key(a:dir)] endfunction function! s:all_combinations(xs) "{{{2 let cs = [] for r in range(1, len(a:xs)) call extend(cs, s:combinations(a:xs, r)) endfor return cs endfunction function! s:close_temporary_windows() "{{{2 let _ = range(1, winnr('$')) let pattern = '^nofile\|quickfix\|help' call filter(_, '!buflisted(winbufnr(v:val)) && \ getbufvar(winbufnr(v:val), "&buftype") =~# pattern') let current_winnr = winnr() if len(_) == winnr('$') call filter(_, 'current_winnr != v:val') endif for winnr in _ execute winnr 'wincmd w' wincmd c endfor execute (current_winnr - len(filter(_, 'v:val < current_winnr'))) \ 'wincmd w' endfunction function! s:combinations(pool, r) "{{{2 let n = len(a:pool) if n < a:r || a:r <= 0 return [] endif let result = [] let indices = range(a:r) call add(result, join(map(copy(indices), 'a:pool[v:val]'), '')) while !0 let broken_p = 0 for i in reverse(range(a:r)) if indices[i] != i + n - a:r let broken_p = !0 break endif endfor if !broken_p break endif let indices[i] += 1 for j in range(i + 1, a:r - 1) let indices[j] = indices[j-1] + 1 endfor call add(result, join(map(copy(indices), 'a:pool[v:val]'), '')) endwhile return result endfunction function! s:first_line(file) "{{{2 let lines = readfile(a:file, '', 1) return 1 <= len(lines) ? lines[0] : '' endfunction function! s:move_window_into_tabpage(target_tabpagenr) "{{{2 " Move the current window into a:target_tabpagenr. if a:target_tabpagenr <= 0 " ignore invalid number. return endif let original_tabnr = tabpagenr() let target_bufnr = bufnr('') let window_view = winsaveview() if a:target_tabpagenr > tabpagenr('$') tabnew tabmove " Move new tabpage at the last. execute target_bufnr 'buffer' let target_tabpagenr = tabpagenr() else execute a:target_tabpagenr 'tabnext' let target_tabpagenr = a:target_tabpagenr if winnr('$') > 1 || bufname(winbufnr(0)) != '' SplitTop endif execute target_bufnr 'buffer' endif call winrestview(window_view) execute original_tabnr 'tabnext' if winnr('$') > 1 close else let target_tabpagenr -= tabpagenr() < target_tabpagenr tabclose endif execute target_tabpagenr 'tabnext' endfunction function! s:operator_search(motion_wiseness) "{{{2 let reg_0 = [@0, getregtype('0')] let visual_command = \ operator#user#visual_command_from_wise_name(a:motion_wiseness) execute 'normal!' '`['.visual_command.'`]"0y' let @/ = '\V' . substitute(escape(@0, '\'), '\n', '\\n', 'g') call histadd('/', @/) execute 'normal!' v:searchforward ? 'n' : 'N' call setreg('0', reg_0[0], reg_0[1]) endfunction function! s:operator_translate(motion_wiseness) "{{{2 let visual_command = \ operator#user#visual_command_from_wise_name(a:motion_wiseness) execute 'normal!' '`['.visual_command.'`]y' let @" = s:translate_with_auto_detect(@0) echo @" endfunction function! s:operator_yank_clipboard(motion_wiseness) "{{{2 let visual_command = \ operator#user#visual_command_from_wise_name(a:motion_wiseness) execute 'normal' '`['.visual_command.'`]"+y' endfunction function! s:prefix_of_p(x, y) "{{{2 return a:x ==# strpart(a:y, 0, len(a:x)) endfunction function! s:translate(text, from, to) "{{{2 let api = 'http://translate.google.com/translate_a/t' let options = {'sl': a:from, 'tl': a:to} let response = webapi#http#post(api, extend({ \ 'client': '0', \ 'q': a:text \ }, options), {'User-Agent': 'Mozilla/5.0'}) if response.status == 200 let result = webapi#json#decode(response.content) if has_key(result, 'sentences') return join(map(result.sentences, \ 'has_key(v:val, "trans") ? v:val.trans : ""')) endif else throw printf("%d %s: %s", response.status, response.message, api) end return '' endfunction function! s:translate_with_auto_detect(text) "{{{2 if a:text =~ '[^\x00-\x7F]' return s:translate(a:text, 'ja', 'en') else " English given return s:translate(a:text, 'en', 'ja') endif endfunction " Mappings "{{{1 " Terminal-GUI interoperability "{{{2 " => x function! s:emulate_meta_esc_behavior_in_terminal() " [key, acceptable-modifiers-except-meta] "{{{ let keys = [ \ ['!', ''], \ ['"', ''], \ ['#', ''], \ ['$', ''], \ ['%', ''], \ ['&', ''], \ ['''', ''], \ ['(', ''], \ [')', ''], \ ['*', ''], \ ['+', ''], \ [',', ''], \ ['-', ''], \ ['.', ''], \ ['0', ''], \ ['1', ''], \ ['2', ''], \ ['3', ''], \ ['4', ''], \ ['5', ''], \ ['6', ''], \ ['7', ''], \ ['8', ''], \ ['9', ''], \ [':', ''], \ [';', ''], \ ['', 'CS'], \ ['', ''], \ ['', 'C'], \ ['', 'CS'], \ ['', 'CS'], \ ['', 'CS'], \ ['', 'CS'], \ ['', 'CS'], \ ['', 'CS'], \ ['', 'CS'], \ ['', 'CS'], \ ['', 'CS'], \ ['', 'CS'], \ ['', 'CS'], \ ['', 'CS'], \ ['', 'CS'], \ ['', 'CS'], \ ['', 'CS'], \ ['', 'CS'], \ ['', 'CS'], \ ['', ''], \ ['', 'CS'], \ ['', 'CS'], \ ['', 'CS'], \ ['', 'CS'], \ ['', 'CS'], \ ['', 'CS'], \ ['', 'CS'], \ ['', 'CS'], \ ['=', ''], \ ['>', ''], \ ['@', 'C'], \ ['A', ''], \ ['B', ''], \ ['C', ''], \ ['D', ''], \ ['E', ''], \ ['F', ''], \ ['G', ''], \ ['H', ''], \ ['I', ''], \ ['J', ''], \ ['K', ''], \ ['L', ''], \ ['M', ''], \ ['N', ''], \ ['O', ''], \ ['P', ''], \ ['Q', ''], \ ['R', ''], \ ['S', ''], \ ['T', ''], \ ['U', ''], \ ['V', ''], \ ['W', ''], \ ['X', ''], \ ['Y', ''], \ ['Z', ''], \ ['[', 'C'], \ [']', 'C'], \ ['^', 'C'], \ ['_', 'C'], \ ['`', ''], \ ['a', 'C'], \ ['b', 'C'], \ ['c', 'C'], \ ['d', 'C'], \ ['e', 'C'], \ ['f', 'C'], \ ['g', 'C'], \ ['h', 'C'], \ ['i', 'C'], \ ['j', 'C'], \ ['k', 'C'], \ ['l', 'C'], \ ['m', 'C'], \ ['n', 'C'], \ ['o', 'C'], \ ['p', 'C'], \ ['q', 'C'], \ ['r', 'C'], \ ['s', 'C'], \ ['t', 'C'], \ ['u', 'C'], \ ['v', 'C'], \ ['w', 'C'], \ ['x', 'C'], \ ['y', 'C'], \ ['z', 'C'], \ ['{', ''], \ ['}', ''], \ ['~', ''], \ ] "}}} for [key, modifiers] in keys let k = matchstr(key, '^<\zs.*\ze>$\|.*') for map in ['map', 'map!'] execute map '' ''.key for m in s:modifier_combinations(modifiers) execute map '' '<'.m.k.'>' endfor endfor endfor endfunction function! s:modifier_combinations(modifiers) let prefixes = map(range(len(a:modifiers)), 'a:modifiers[v:val] . "-"') return s:all_combinations(prefixes) endfunction if has('gui_running') " NUL map map! noremap! * call s:emulate_meta_esc_behavior_in_terminal() endif " Tag jumping "{{{2 " Fallback "{{{3 " the prefix key. nnoremap (arpeggio-default:t) " Basic "{{{3 nnoremap tt vnoremap tt nnoremap tj :tag nnoremap tk :pop nnoremap tl :tags nnoremap tn :tnext nnoremap tp :tprevious nnoremap tP :tfirst nnoremap tN :tlast " additions, like Web browsers nnoremap &l:filetype ==# 'qf' ? "\" : "\" vnoremap &l:filetype ==# 'qf' ? "\" : "\" " addition, interactive use. nnoremap t :tag " With the preview window "{{{3 nnoremap t't } vnoremap t't } nnoremap t'n :ptnext nnoremap t'p :ptprevious nnoremap t'P :ptfirst nnoremap t'N :ptlast nnoremap t'c :pclose " With :split "{{{3 nnoremap tst :call vertical_with('wincmd', [']']) vnoremap tst :call vertical_with('wincmd', [']']) " QuickFix "{{{2 " Fallback "{{{3 " The prefix key. noremap q " Alternative key for the original action. nnoremap Q q " For quickfix list "{{{3 nnoremap qj :cnext nnoremap qk :cprevious nnoremap qr :crewind nnoremap qK :cfirst nnoremap qJ :clast nnoremap qfj :cnfile nnoremap qfk :cpfile nnoremap ql :clist nnoremap qq :cc nnoremap qo :copen nnoremap qc :cclose nnoremap qp :colder nnoremap qn :cnewer nnoremap qm :Make nnoremap qM :Make nnoremap q :Make nnoremap qg :Grep " For location list (mnemonic: Quickfix list for the current Window) "{{{3 nnoremap qwj :lnext nnoremap qwk :lprevious nnoremap qwr :lrewind nnoremap qwK :lfirst nnoremap qwJ :llast nnoremap qwfj :lnfile nnoremap qwfk :lpfile nnoremap qwl :llist nnoremap qwq :ll nnoremap qwo :lopen nnoremap qwc :close nnoremap qwp :lolder nnoremap qwn :lnewer nnoremap qwm :Lmake nnoremap qwM :Lmake nnoremap qw :Lmake nnoremap qwg :Lgrep " Tab pages "{{{2 " Fallback "{{{3 " the prefix key. noremap " Basic "{{{3 " Move new tabpage at the last. nnoremap n :tabnew \| :tabmove nnoremap c :tabclose nnoremap o :tabonly nnoremap i :tabs nmap n nmap c nmap o nmap i nnoremap :TabpageTitle nmap nmap " Moving around tabpages. "{{{3 nnoremap j \ :execute 'tabnext' 1 + (tabpagenr() + v:count1 - 1) % tabpagenr('$') nnoremap k \ :execute 'tabprevious' v:count1 % tabpagenr('$') nnoremap K :tabfirst nnoremap J :tablast nmap j nmap k nmap j " GNU screen like mappings. " Note that the numbers in {lhs}s are 0-origin. See also 'tabline'. for i in range(10) execute 'nnoremap ' (''.(i)) ((i+1).'gt') endfor unlet i " Moving tabpages themselves. "{{{3 nnoremap l \ :execute 'tabmove' min([tabpagenr() + v:count1 - 1, tabpagenr('$')]) nnoremap h \ :execute 'tabmove' max([tabpagenr() - v:count1 - 1, 0]) nnoremap L :tabmove nnoremap H :tabmove 0 nmap l nmap h " Argument list "{{{2 " the prefix key. noremap nnoremap l :args nnoremap j :next nnoremap k :previous nnoremap J :last nnoremap K :first nnoremap wj :wnext nnoremap wk :wprevious nnoremap :args nmap l nmap j nmap k nmap wj nmap wk nmap nmap " Command-line editting "{{{2 " Move the cursor instead of selecting a different match cnoremap cnoremap cmap cmap cnoremap cnoremap cnoremap " cnoremap cnoremap cnoremap cnoremap " Like emacs kill-line. cnoremap \ e getcmdpos() == 1 ? '' : getcmdline()[:getcmdpos()-2] " Escape Command-line mode if the command line is empty (like ) cnoremap getcmdline() == '' ? "\" : "\" cnoremap getcmdline() == '' ? "\" : "\" " Search slashes easily (too lazy to prefix backslashes to slashes) cnoremap / getcmdtype() == '/' ? '\/' : '/' " Command-line window "{{{2 autocmd MyAutoCmd CmdwinEnter * \ call s:on_CmdwinEnter() function! s:on_CmdwinEnter() nnoremap q inoremap q inoremap pumvisible() ? "\" : "\\" inoremap \ getline('.') == '' ? "\\" : col('.') == 1 ? '' : "\" inoremap \ getline('.') == '' ? "\\" : col('.') == 1 ? '' : "\" inoremap \ getline('.') == '' ? "\\" : col('.') == 1 ? '' : "\" imap startinsert! endfunction " Insert mode "{{{2 " Like emacs mappings. inoremap inoremap inoremap inoremap \ indent(line('.')) > 0 && virtcol('.') > indent(line('.')) + 1 \ ? "\\" \ : "\" inoremap \ virtcol('.') < indent(line('.')) ? "\" : "\" inoremap \ repeat("\", max([strchars(getline('.')[col('.') - 1:]), 1])) inoremap pumvisible() ? "\" : "\+" " Alternatives for the original actions. inoremap inoremap " To be able to undo these types of deletion. inoremap u inoremap u " Make I/A available in characterwise-visual and linewise-visual. vnoremap I force_blockwise_visual('I') vnoremap A force_blockwise_visual('A') function! s:force_blockwise_visual(next_key) if mode() ==# 'v' return "\" . a:next_key elseif mode() ==# 'V' return "\0o$" . a:next_key else " mode() ==# "\" return a:next_key endif endfunction " Complete or indent. inoremap pumvisible() \ ? "\" \ : should_indent_rather_than_complete_p() \ ? "\" \ : keys_to_complete() inoremap pumvisible() \ ? "\" \ : should_indent_rather_than_complete_p() \ ? "\" \ : keys_to_complete() function! s:should_indent_rather_than_complete_p() return getline('.')[col('.') - 2] !~ '^\S' endfunction " Section jumping "{{{2 " " Enable *consistent* ]] and other motions in Visual and Operator-pending " mode. Because some ftplugins provide these motions only for Normal mode and " other ftplugins provide these motions with some faults, e.g., not countable. vnoremap ]] :call jump_section_v(']]') vnoremap ][ :call jump_section_v('][') vnoremap [[ :call jump_section_v('[[') vnoremap [] :call jump_section_v('[]') onoremap ]] :call jump_section_o(']]') onoremap ][ :call jump_section_o('][') onoremap [[ :call jump_section_o('[[') onoremap [] :call jump_section_o('[]') " The "{{{2 " to show in the bottom line. map [Space] " fallback noremap [Space] nnoremap [Space]w :w if executable('sudo') nnoremap [Space]W :w sudo:% endif nnoremap [Space]/ :call toggle_option('hlsearch') nnoremap [Space]c :call close_temporary_windows() nnoremap [Space]f nnoremap [Space]fe :SetFileEncoding nnoremap [Space]ff :SetFileFormat nnoremap [Space]ft :setfiletype nnoremap [Space]fs :setlocal filetype? fileencoding? fileformat? " Append one character. nnoremap [Space]A A=keys_to_insert_one_character() nnoremap [Space]a a=keys_to_insert_one_character() " Insert one character. nnoremap [Space]I I=keys_to_insert_one_character() nnoremap [Space]i i=keys_to_insert_one_character() " Put from clipboard. nmap [Space]p "*p " Open a fold. nnoremap [Space]l zo " Close a fold. nnoremap [Space]h zc " Close all folds but including the cursor. nnoremap [Space]v zMzv " Enter command-line window. nnoremap [Space]: q: xnoremap [Space]: q: nnoremap [Space]o nnoremap [Space]oc :call toggle_colorcolumn() nnoremap [Space]og :call toggle_grepprg(0) nnoremap [Space]ol :call toggle_option('cursorline') nnoremap [Space]on :call toggle_option('number') nnoremap [Space]op :call toggle_option('paste') nnoremap [Space]os :call toggle_option('spell') nnoremap [Space]ow :call toggle_option('wrap') nnoremap [Space]oz :call toggle_foldmethod(0) nnoremap [Space]q :Help quickref nnoremap [Space]m :marks nnoremap [Space]r :registers nnoremap [Space]. :Source $MYVIMRC " Windows "{{{2 " Synonyms for the default mappings, with single key strokes. nnoremap w nnoremap W " Search the word nearest to the cursor in new window. nnoremap * :Split \| normal! * nnoremap # :Split \| normal! # " This {lhs} overrides the default action (Move cursor to top-left window). " But I rarely use its {lhs}s, so this mapping is not problematic. nnoremap t \ :call move_window_into_tabpage(ask_tabpage_number()) function! s:ask_tabpage_number() echon 'Which tabpage to move this window into? ' let c = nr2char(getchar()) if c =~# '[0-9]' " Convert 0-origin number (typed by user) into 1-origin number (used by " Vim's internal functions). See also 'tabline'. return 1 + char2nr(c) - char2nr('0') else return 0 endif endfunction nmap t " Like "q", but does ":quit!". nnoremap Q :quit! nnoremap y :Split nmap y " Text objects "{{{2 " Synonyms for <> and [], same as plugin surround. onoremap aa a> vnoremap aa a> onoremap ia i> vnoremap ia i> onoremap ar a] vnoremap ar a] onoremap ir i] vnoremap ir i] " Select the last chaged text - "c" stands for "C"hanged. nnoremap (textobj-last-changed-text) `[v`]h onoremap (textobj-last-changed-text) :normal gc vnoremap (textobj-last-changed-text) :normal gc map gc (textobj-last-changed-text) " Select the last selected text. onoremap gv :normal! gv " Alias for brackets onoremap ( t( vnoremap ( t( onoremap ) t) vnoremap ) t) " Operators "{{{2 " operator-search "{{{3 call operator#user#define('search-forward', \ s:SID_PREFIX() . 'operator_search', \ 'let v:searchforward = 1') call operator#user#define('search-backward', \ s:SID_PREFIX() . 'operator_search', \ 'let v:searchforward = 0') vmap * (operator-search-forward) vmap # (operator-search-backward) " operator-translate "{{{3 call operator#user#define('translate', s:SID_PREFIX() . 'operator_translate') Arpeggio map ot (operator-translate) " operator-yank-clipboard "{{{3 call operator#user#define('yank-clipboard', \ s:SID_PREFIX() . 'operator_yank_clipboard') Arpeggio map oy (operator-yank-clipboard) " Misc. "{{{2 nnoremap :update nnoremap :Help nnoremap :edit nnoremap . :edit . " Delete a character with the black hole register. nnoremap X "_X nnoremap x "_x " "Y" to work from the cursor to the end of line. nnoremap Y y$ " Jump list nnoremap nnoremap " Disable some dangerous key. nnoremap ZZ nnoremap ZQ " Use a backslash (\) to repeat last change. " Since a dot (.) is used as . nmap \ (repeat-.) " Disable solely typed / to avoid unexpected behavior. noremap noremap " Like o/O, but insert additional [count] blank lines. nnoremap (arpeggio-default:o) \ start_insert_mode_with_blank_lines('o') nnoremap O \ start_insert_mode_with_blank_lines('O') function! s:start_insert_mode_with_blank_lines(command) if v:count != v:count1 return a:command " Behave the same as the default commands. endif if a:command ==# 'o' return "\o" . repeat("\", v:count - 1) else " a:command ==# 'O' return "\O" . repeat("\\", v:count - 1) . "\S" endif endfunction noremap nnoremap :SuspendWithAutomticCD " Show the lines which match to the last search pattern. nnoremap g/ :global//print vnoremap g/ :global//print " Alternative . noremap inoremap " c_ mapped from something doesn't work the same as " c_ directly typed by user. cnoremap " Make searching directions consistent. nnoremap n search_forward_p() ? 'nzv' : 'Nzv' nnoremap N search_forward_p() ? 'Nzv' : 'nzv' vnoremap n search_forward_p() ? 'nzv' : 'Nzv' vnoremap N search_forward_p() ? 'Nzv' : 'nzv' onoremap n search_forward_p() ? 'n' : 'N' onoremap N search_forward_p() ? 'N' : 'n' function! s:search_forward_p() return exists('v:searchforward') ? v:searchforward : !0 endfunction " Show the syntax name under the cursor. nnoremap gs \ :echo join(syntax_name_the_cursor(), '/') function! s:syntax_name_the_cursor() return map(synstack(line('.'), col('.')), 'synIDattr(v:val, "name")') endfunction " Filetypes "{{{1 " All filetypes "{{{2 autocmd MyAutoCmd FileType * \ call s:on_FileType_any() function! s:on_FileType_any() " Make omni completion available for all filetypes. if &l:omnifunc == '' setlocal omnifunc=syntaxcomplete#Complete endif " Disable auto wrap. setlocal formatoptions-=t formatoptions-=c " Universal undo for indent scripts. if exists('b:undo_indent') let b:undo_indent .= ' | ' else let b:undo_indent = '' endif let b:undo_indent .= 'setlocal \ autoindent< \ cindent< \ cinkeys< \ cinoptions< \ cinwords< \ copyindent< \ expandtab< \ indentexpr< \ indentkeys< \ lisp< \ lispwords< \ preserveindent< \ shiftround< \ shiftwidth< \ smartindent< \ smarttab< \ softtabstop< \ tabstop< \ ' endfunction " Fix 'fileencoding' to use 'encoding'. autocmd MyAutoCmd BufReadPost * \ if &l:modifiable && !search('[^\x00-\x7F]', 'cnw', 100) \ | setlocal fileencoding= \ | endif " When editing a file, always jump to the last cursor position. autocmd MyAutoCmd BufReadPost * \ if line('''"') > 0 && line('''"') <= line('$') \ | execute 'normal! g''"' \ | endif " Unset 'paste' automatically. autocmd MyAutoCmd InsertLeave * set nopaste " Visualization ideographic space. autocmd MyAutoCmd VimEnter,WinEnter * match Underlined /[\u3000]/ " actionscript "{{{2 autocmd MyAutoCmd FileType actionscript \ TabIndent 4 \ | setlocal commentstring=//%s \ | compiler ant " changelog "{{{2 " Fix the new entry mapping bug. autocmd MyAutoCmd FileType changelog \ noremap o :NewChangelogEntry let g:changelog_timeformat = '%Y-%m-%d' let g:changelog_username = 'Shota Nozaki ' " coffee "{{{2 autocmd MyAutoCmd FileType coffee \ SpaceIndent 2 " css, less, sass, scss "{{{2 autocmd MyAutoCmd FileType css,less,sass,scss \ SpaceIndent 2 \ | setlocal iskeyword+=- " dosini (.ini) "{{{2 autocmd MyAutoCmd FileType dosini \ call s:on_FileType_dosini() function! s:on_FileType_dosini() " Jumping around sections. nnoremap ]] :call jump_section_n('/^\[') nnoremap ][ :call jump_section_n('/\n\[\@=') nnoremap [[ :call jump_section_n('?^\[') nnoremap [] :call jump_section_n('?\n\[\@=') " Folding sections. setlocal foldmethod=expr let &l:foldexpr = '(getline(v:lnum)[0] == "[") ? ">1" :' \ . '(getline(v:lnum) =~# ''^;.*\(__END__\|\*\*\*\)'' ? 0 : "=")' endfunction " git "{{{2 autocmd MyAutoCmd FileType gitcommit \ setlocal nofoldenable " haskell "{{{2 autocmd MyAutoCmd FileType haskell \ SpaceIndent 2 \ | setlocal omnifunc=necoghc#omnifunc \ | compiler cabal autocmd MyAutoCmd FileType cabal \ SpaceIndent 2 " Fix for .hsc highlight let g:hs_allow_hash_operator = 1 let g:haskell_conceal = 0 " haxe "{{{2 autocmd MyAutoCmd FileType haxe \ SpaceIndent 2 \ | setlocal commentstring=//%s " java "{{{2 autocmd MyAutoCmd FileType java \ SpaceIndent 4 \ | compiler gradle \ | setlocal cinoptions=:0,l1,g0,t0,(0,j1 \ | setlocal foldmethod=syntax foldnestmax=2 \ | setlocal textwidth=100 " javascript "{{{2 autocmd MyAutoCmd FileType javascript \ SpaceIndent 2 \ | setlocal omnifunc=jscomplete#CompleteJS " lua "{{{2 autocmd MyAutoCmd FileType lua \ SpaceIndent 2 " markdown "{{{2 autocmd MyAutoCmd FileType markdown \ SpaceIndent 2 let g:markdown_fenced_languages = ['objc'] " objc "{{{2 autocmd MyAutoCmd FileType objc \ SpaceIndent 2 \ | setlocal commentstring=//%s " ocaml "{{{2 autocmd MyAutoCmd FileType ocaml \ SpaceIndent 2 \ | setlocal commentstring=(*%s*) " perl "{{{2 autocmd MyAutoCmd FileType perl \ SpaceIndent 2 " php "{{{2 autocmd MyAutoCmd FileType php \ call s:on_FileType_php() function! s:on_FileType_php() SpaceIndent 2 setlocal commentstring=//%s inoreabbrev /** /**/ endfunction " python "{{{2 autocmd MyAutoCmd FileType python \ SpaceIndent 4 let g:python_highlight_all = 1 " quickfix "{{{2 autocmd MyAutoCmd FileType qf \ setlocal nobuflisted nocursorline " ruby "{{{2 autocmd MyAutoCmd FileType ruby \ SpaceIndent 2 " scheme "{{{2 let g:is_gauche = 1 " sh, zsh "{{{2 autocmd MyAutoCmd FileType sh,zsh \ SpaceIndent 2 let g:is_bash = 1 " sql "{{{2 autocmd MyAutoCmd FileType sql \ SpaceIndent 2 \ | setlocal commentstring=--%s " tex "{{{2 autocmd MyAutoCmd FileType tex,plaintex \ call s:on_FileType_tex() \ | compiler tex function! s:on_FileType_tex() SpaceIndent 2 inoreabbrev \b \textbf{} inoreabbrev \i \textit{} inoreabbrev \r \textrm{} inoreabbrev \s \textsf{} inoreabbrev \t \texttt{} inoreabbrev \l \begin{lstlisting}[]\end{lstlisting} setlocal foldmarker=%{{{,%}}} setlocal iskeyword+=- endfunction let g:tex_flavor = 'latex' " typescript "{{{2 autocmd MyAutoCmd FileType typescript \ SpaceIndent 4 \ | setlocal commentstring=//%s " vim "{{{2 autocmd MyAutoCmd FileType vim \ SpaceIndent 2 let g:vim_indent_cont = 0 let g:vimsyn_embed = 'l' " xml "{{{2 autocmd MyAutoCmd FileType ant,docbk,html,xhtml,xml,xslt,smarty \ call s:on_FileType_xml() function! s:on_FileType_xml() SpaceIndent 2 " Complete proper end-tags. " In the following description, {|} means the cursor position. " Insert the end tag after the cursor. " Before: {|} inoremap >/= \keys_to_stop_insert_mode_completion() \F " Wrap the cursor with the tag. " Before: " {|} " inoremap >> >X/= \keys_to_stop_insert_mode_completion() \ " To deal with namespace prefixes and tag-name-including-hyphens. setlocal iskeyword+=45 " hyphen (-) setlocal iskeyword+=58 " colon (:) endfunction " For light weight template engines autocmd MyAutoCmd FileType haml,jade,slim \ SpaceIndent 2 " Plugins "{{{1 " acceleration "{{{2 call accelerate#map('nv', 'e', '', 'repeat("\", v:count1)') call accelerate#map('nv', 'e', '', 'repeat("\", v:count1)') call accelerate#map('nv', '', 'j', 'gj') call accelerate#map('nv', '', 'k', 'gk') call accelerate#map('nv', '', 'h', 'h') call accelerate#map('nv', 'e', 'l', 'foldclosed(line(".")) != -1 ? "zo" : "l"') " altr "{{{2 call altr#reset() call altr#define('%.m', '%.h') nmap (altr-back) nmap (altr-forward) " clang-complete "{{{2 if system('uname') =~# '^Darwin' let g:clang_library_path = '/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/' let g:clang_auto_user_options = 'path, .clang_complete' endif " exjumplist "{{{2 nmap (exjumplist-next-buffer) nmap (exjumplist-previous-buffer) " gfdiff "{{{2 nmap gh (gfdiff-to) " grex "{{{2 nmap gy (operator-grex-yank)(textobj-entire-a) vmap gy (operator-grex-yank) nmap gd (operator-grex-delete)(textobj-entire-a) vmap gd (operator-grex-delete) " ku "{{{2 autocmd MyAutoCmd FileType ku \ call s:on_FileType_ku() function! s:on_FileType_ku() call ku#default_key_mappings(!0) iunmap iunmap nmap (ku-cancel) imap (ku-cancel) imap (ku-%-cancel-when-empty) \ col('$') <= 2 ? '(ku-cancel)' : '' inoremap (ku-%-delete-backword-char) \ (pumvisible() ? "\" : '') . "\" inoremap (ku-%-delete-backword-word) \ (pumvisible() ? "\" : '') . "\" inoremap (ku-%-delete-backword-line) \ (pumvisible() ? "\" : '') . "\" imap \ (ku-%-cancel-when-empty)(ku-%-delete-backword-char) imap \ (ku-%-cancel-when-empty)(ku-%-delete-backword-word) imap \ (ku-%-cancel-when-empty)(ku-%-delete-backword-line) imap endfunction call ku#custom_action('common', 'cd', s:SID_PREFIX().'ku_common_action_my_cd') call ku#custom_action('common', 'Yank', \ s:SID_PREFIX().'ku_common_action_Yank') call ku#custom_action('common', 'yank', \ s:SID_PREFIX().'ku_common_action_yank') call ku#custom_action('file', 'open-sudo', \ s:SID_PREFIX().'ku_file_action_open_sudo') call ku#custom_action('file/current', 'open-sudo', \ s:SID_PREFIX().'ku_file_action_open_sudo') call ku#custom_action('metarw/git', 'checkout', \ s:SID_PREFIX().'ku_metarw_git_action_checkout') function! s:ku_common_action_my_cd(item) if isdirectory(a:item.word) execute 'CD' a:item.word else " treat a:item as a file name execute 'CD' fnamemodify(a:item.word, ':h') endif endfunction function! s:ku_common_action_yank(item) call setreg('"', a:item.word, 'c') endfunction function! s:ku_common_action_Yank(item) call setreg('"', a:item.word, 'l') endfunction function! s:ku_file_action_open_sudo(item) edit `='sudo:' . fnamemodify(a:item.word, ':p')` endfunction function! s:ku_metarw_git_action_checkout(item) if a:item.ku__completed_p let branch_name = matchstr(a:item.word, '^git:\zs[^:]\+\ze:') let message = system('git checkout ' . shellescape(branch_name)) if v:shell_error == 0 echomsg 'git checkout' branch_name return 0 else return message endif else return 'No such branch: ' . string(a:item.word) endif endfunction call ku#custom_key('common', 'y', 'yank') call ku#custom_key('common', 'Y', 'Yank') call ku#custom_key('buffer', 'd', 'delete') call ku#custom_key('file', 's', 'open-sudo') call ku#custom_key('file/current', 's', 'open-sudo') call ku#custom_key('metarw/git', '/', 'checkout') call ku#custom_key('metarw/git', '?', 'checkout') call ku#custom_prefix('common', '.VIM', expand('~/.vim')) call ku#custom_prefix('common', 'HOME', expand('~')) call ku#custom_prefix('common', 'VIM', expand('$VIMRUNTIME')) call ku#custom_prefix('common', '~', expand('~')) if executable('portageq') call ku#custom_prefix('common', 'PORT', system('portageq portdir')[:-2]) end nmap [Space]k nnoremap [Space]ka :Ku args nnoremap [Space]kb :Ku buffer nnoremap [Space]kc :Ku colorscheme nnoremap [Space]kf :Ku file nnoremap [Space]kg :Ku metarw/git nnoremap [Space]kh :Ku history nnoremap [Space]kj :Ku file/current nnoremap [Space]kl :Ku file_project nnoremap [Space]kq :Ku quickfix nnoremap [Space]kr :Ku register nnoremap [Space]ks :Ku source nnoremap [Space]kt :Ku tags nnoremap [Space]kw :Ku myproject nnoremap [Space]kz :Ku fold nnoremap [Space]k/ :Ku cmd_mru/search nnoremap [Space]k: :Ku cmd_mru/cmd nnoremap [Space]km :Ku file_mru nnoremap [Space]kk :call ku#restart() let g:ku_personal_runtime = expand('~/.vim') let g:ku_file_mru_ignore_pattern = '/$\|/\.git/\|^/\(/\|mnt\|tmp\)' let g:ku_file_mru_limit = 200 " metarw "{{{2 let g:metarw_gist_safe_write = 1 " operator-comment "{{{2 Arpeggio map oc (operator-comment) Arpeggio map od (operator-uncomment) " operator-replece "{{{2 Arpeggio map or (operator-replace) " operator-sort "{{{2 nmap [Space]S (operator-sort)$ nmap [Space]s (operator-sort) vmap [Space]s (operator-sort) " quickrun "{{{2 command! -complete=command -nargs=+ Capture QuickRun vim -src let g:quickrun_config = {} let g:quickrun_config['_'] = { \ 'split': '%{'.s:SID_PREFIX().'vertical_p() ? "vertical" : ""}' \ } let g:quickrun_config['c'] = { \ 'type': 'c/clang' \ } let g:quickrun_config['cpp'] = { \ 'type': 'cpp/clang' \ } let g:quickrun_config['dot'] = { \ 'exec': ['%c -Tps:cairo -o %s:p:r.ps %s'] \ } let g:quickrun_config['php/hhvm'] = { \ 'command': 'hhvm', \ 'exec': ['%c %a %s'] \ } let g:quickrun_config['haxe'] = { \ 'exec': ['%c %a --cwd %s:p:h -x %s:t:r'], \ 'tempfile': '%{fnamemodify(tempname(), ":h")}/%{expand("%:t")}', \ 'hook/sweep/files': ['%S:p:r.n'] \ } let g:quickrun_config['json'] = { \ 'command': 'jq', \ 'exec': ["%c '.' %s"] \ } let g:quickrun_config['javascript'] = { \ 'type': 'javascript/v8' \ } let g:quickrun_config['javascript/v8'] = { \ 'command': executable('d8') ? 'd8' : 'v8', \ 'tempfile': '%{tempname()}.js' \ } let g:quickrun_config['markdown/marked'] = { \ 'outputter': 'null', \ 'command': 'open', \ 'cmdopt': '-g', \ 'exec': '%c %o -a Marked %s' \ } let g:quickrun_config['objc'] = { \ 'command': 'gcc', \ 'exec': ['%c %o %s -o %s:p:r', '%s:p:r %a'], \ 'tempfile': '%{tempname()}.m' \ } let g:quickrun_config['xdefaults'] = { \ 'exec': ['xrdb -remove', 'xrdb -merge %s', 'xrdb -query'] \ } " ref "{{{2 autocmd MyAutoCmd FileType ref \ call s:on_FileType_ref() function! s:on_FileType_ref() nmap (ref-keyword) vmap (ref-keyword) nmap (ref-keyword) vmap (ref-keyword) nmap (ref-forward) nmap (ref-back) nnoremap q c endfunction nmap K (ref-keyword) vmap K (ref-keyword) nnoremap a :call ref#jump('normal', 'alc') vnoremap a :call ref#jump('visual', 'alc') AlterCommand ref Ref let g:ref_alc2_overwrite_alc = 1 let g:ref_no_default_key_mappings = 1 let g:ref_open = 'Split' let g:ref_perldoc_complete_head = 1 let g:ref_phpmanual_path = '/usr/share/php-docs/en/php-chunked-xhtml' let g:ref_wikipedia_lang = 'ja' " scratch "{{{2 nmap s (scratch-open) autocmd MyAutoCmd User PluginScratchInitializeAfter \ call s:on_User_plugin_scratch_initialize_after() function! s:on_User_plugin_scratch_initialize_after() map (scratch-evaluate!) endfunction let g:scratch_show_command = 'SplitTop | hide buffer' " skeleton "{{{2 autocmd MyAutoCmd User plugin-skeleton-detect \ call s:on_User_plugin_skeleton_detect() function! s:on_User_plugin_skeleton_detect() let _ = split(expand('%:p'), '/') if len(_) == 0 return endif let filename = _[-1] let directories = _[:-2] if filename =~# '\.user\.js$' SkeletonLoad userjs endif if filename =~# '\.txt$' && get(directories, -1) ==# 'doc' SkeletonLoad help-doc endif if filename =~# '\.vim$' \ && get(directories, -1) =~# \ '^\v(autoload|colors|compiler|ftdetect|ftplugin|indent|plugin|syntax)' if get(directories, -2) ==# 'after' execute 'SkeletonLoad' 'vim-additional-'.directories[-1] else execute 'SkeletonLoad' 'vim-'.directories[-1] endif endif endfunction autocmd MyAutoCmd User plugin-skeleton-loaded \ call s:on_User_plugin_skeleton_loaded() function! s:on_User_plugin_skeleton_loaded() silent %s/<%=\(.\{-}\)%>/\=eval(submatch(1))/ge if search('<%|%>', 'w') if foldclosed(line('.')) normal! zv endif normal! "_da> else normal! gg endif endfunction " smartinput "{{{2 let g:smartinput_no_default_key_mappings = 1 if exists('g:loaded_smartinput') call smartinput#clear_rules() call smartinput#define_default_rules() endif call smartinput#define_rule({ \ 'at': '\%#', 'char': '{', 'input': '{', \ 'syntax': ['Comment'] \ }) " for PHP "{{{ call smartinput#define_rule({ \ 'at': '\%#', 'char': '@', 'input': '$this->', \ 'filetype': ['php'] \ }) call smartinput#define_rule({ \ 'at': '\%#[$A-Za-z]', 'char': '@', 'input': '@', \ 'filetype': ['php'] \ }) call smartinput#define_rule({ \ 'at': '\%#', 'char': '@', 'input': '@', \ 'filetype': ['php'], 'syntax': ['Comment', 'Constant', 'None'] \ }) " }}} call smartinput#map_trigger_keys() " smartword "{{{2 map w (smartword-w) map b (smartword-b) map e (smartword-e) map ge (smartword-ge) " submode "{{{2 call submode#enter_with('scroll', 'nv', '', '[Space]j') call submode#map('scroll', 'nv', 'e', 'j', \ 'line(".") != line("$") ? "" : ""') call submode#map('scroll', 'nv', 'e', 'k', \ 'line(".") != 1 ? "" : ""') call submode#enter_with('undo/redo', 'n', '', 'g-', 'g-') call submode#enter_with('undo/redo', 'n', '', 'g+', 'g+') call submode#map('undo/redo', 'n', '', '-', 'g-') call submode#map('undo/redo', 'n', '', '+', 'g+') call submode#enter_with('winsize', 'n', '', '', \ ':call '.s:SID_PREFIX().'submode_winsize()') call submode#enter_with('winsize', 'n', '', '', \ ':call '.s:SID_PREFIX().'submode_winsize()') function! s:submode_winsize() let current = winnr() wincmd k | let above = winnr() | execute current 'wincmd w' wincmd j | let below = winnr() | execute current 'wincmd w' wincmd h | let left = winnr() | execute current 'wincmd w' wincmd l | let right = winnr() | execute current 'wincmd w' execute printf('call submode#map("winsize", "n", "r", "j", "%s")', \ above != below && current == below ? "-" : "+") execute printf('call submode#map("winsize", "n", "r", "k", "%s")', \ above != below && current == below ? "+" : "-") execute printf('call submode#map("winsize", "n", "r", "h", "%s")', \ left != right && current == right ? ">" : "<") execute printf('call submode#map("winsize", "n", "r", "l", "%s")', \ left != right && current == right ? "<" : ">") endfunction let g:submode_timeout = 0 " surround "{{{2 nmap S Ysurround$ nmap s Ysurround nmap ss Yssurround " tohtml "{{{2 let g:html_ignore_folding = 1 let g:html_no_pre = 0 let g:html_number_lines = 0 let g:html_use_css = 1 let g:use_xhtml = 1 " vcsi "{{{2 " fallback nnoremap v let g:vcsi_diff_in_commit_buffer_p = 1 let g:vcsi_open_command = 'Split | enew' let g:vcsi_use_native_message_p = 1 " Fin. "{{{1 if filereadable(expand('~/.vimrc.local')) source ~/.vimrc.local endif " must be written at the last. see :help 'secure'. set secure " __END__ "{{{1 " vim: expandtab softtabstop=2 shiftwidth=2 " vim: foldmethod=marker