" == Naming convention. == {{{1 " Command name " - CamelCase " Global function name " - CamelCase " Local function name " - s:split_by_underbar " Group name for autocmd " - split-by-dash " In vimrc, start with "vimrc" " - vimrc-{unique-name} " In vim plugin, start with "plugin" " - plugin-{plugin-name} " - plugin-{plugin-name}-{unique-name} " In other custom files, start with "custom" " - custom-{unique-name} " == Check version and features. == {{{1 " First of all, Vim 7.2 or later only. if v:version < 702 echoerr 'Error: vimrc: Require the Vim 7.2 or later.' finish endif for feat in ['multi_byte', 'iconv', 'syntax', 'autocmd'] if !has(feat) echoerr 'Error: vimrc: Require the feature "' . feat . '"' finish endif endfor unlet feat if !exists('g:loaded_vimrc') let g:loaded_vimrc = 0 endif " Reset the key mappings. " It is likely to be changed by $VIM/vimrc. if g:loaded_vimrc == 0 mapclear mapclear! endif " == Utilities for vimrc. == {{{1 function! s:SID() return matchstr(expand(''), '\zs\d\+\ze_SID$') endfunction function! s:SIDP() return '' . s:SID() . '_' endfunction function! s:set_default(var, val) if !exists(a:var) || type({a:var}) != type(a:val) let {a:var} = a:val endif endfunction function! s:check_flag(flag) if exists('b:' . a:flag) return b:{a:flag} endif if exists('g:' . a:flag) return g:{a:flag} endif return 0 endfunction function! s:toggle_flag(flag) if !exists(a:flag) let {a:flag} = 1 else let {a:flag} = !{a:flag} endif endfunction function! s:get_range(type, mode) if a:mode == 'o' let vm = { \ 'line' : 'V', \ 'char' : 'v', \ 'block' : "\" }[a:type] let [sm, em] = ['[', ']'] let save_sel = &selection set selection=inclusive elseif a:mode == 'v' let [vm, sm, em] = [a:type, '<', '>'] end let save_reg = @" execute 'silent normal! `' . sm . vm . '`' . em . 'y' let selected = @" let @" = save_reg if a:mode == 'o' let &selection = save_sel endif return selected endfunction function! s:modulo(n, m) let d = a:n * a:m < 0 ? 1 : 0 return a:n + (-(a:n + (0 < a:m ? d : -d)) / a:m + d) * a:m endfunction function! s:echoerr(mes) " {{{2 echohl ErrorMsg for m in split(a:mes, "\n") echomsg m endfor echohl None endfunction let s:is_win = has('win32') || has('win64') " == Environmental unification. == {{{1 set runtimepath& " Even Windows use "$HOME/.vim". let &rtp = substitute(&rtp, \ escape($HOME, '\') . '/vimfiles', escape($HOME, '\') . '/.vim', 'g') " Additional runtimepath. function! s:add_runtimepath(dir) " {{{2 if isdirectory(a:dir) let &runtimepath = fnamemodify(a:dir, ':~:gs?,?\,?') . ',' . &runtimepath let after = a:dir . '/after' if isdirectory(after) let &runtimepath .= ',' . fnamemodify(after, ':~:gs?,?\,?') endif endif endfunction function! s:add_package_runtimepath(base) " {{{2 for rtp in reverse(split(glob(a:base . '/*'), "\n")) call s:add_runtimepath(rtp) endfor endfunction call s:add_package_runtimepath('~/.vim/package') call s:add_runtimepath(expand('~/.vim/custom')) " == Encoding settings. == {{{1 " Use utf-8. if &encoding !=? 'utf-8' let &termencoding = &encoding set encoding=utf-8 endif if $LANG !~? 'UTF-8$' let $LANG='ja_JP.UTF-8' endif scriptencoding utf-8 if has('guess_encode') set fileencodings=ucs-bom,iso-2022-jp,guess,euc-jp,cp932 else set fileencodings=ucs-bom,iso-2022-jp,euc-jp,cp932 endif augroup vimrc-fileencoding autocmd! autocmd BufReadPost * if &modifiable && !search('[^\x00-\x7F]', 'cnw') \ | setlocal fileencoding= | endif augroup END " == Appearance settings. == {{{1 set guioptions+=M syntax enable augroup vimrc-highlight autocmd! autocmd ColorScheme * call s:highlight_additional() autocmd VimEnter,WinEnter * call s:syntax_additional() augroup END function! s:syntax_additional() let preset = exists('w:syntax_additional') if &l:list if !preset let w:syntax_additional = matchadd('IdeographicSpace', ' ') endif elseif preset call matchdelete(w:syntax_additional) unlet w:syntax_additional endif endfunction function! s:highlight_additional() " Highlight "Ideographic Space". highlight IdeographicSpace term=underline ctermbg=DarkGreen guibg=DarkGreen " Change the cursor color when IME is on. highlight CursorIM guibg=Red guifg=NONE let env = has('gui_running') ? 'gui' : 'cterm' for hi in ['TabLine', 'TabLineSel'] let bg = synIDattr(synIDtrans(hlID(hi)), 'bg', env) let bg = bg != '-1' ? env . 'bg=' . bg : '' execute 'highlight' hi . 'Number' env . 'fg=Red' bg endfor endfunction " colorscheme. set background=dark if !s:is_win || has('gui_running') " ['candycode', 'wuye', 'freya', 'leo'] colorscheme candycode else "CUI win32 colorscheme default endif " Show (partial) command in the last line of the screen. set showcmd " Show invisible characters. set list listchars=tab:^\ ,trail:_,extends:>,precedes:< " Visual bell (Disable beep). set visualbell t_bv= " Display the last line as much as possible in a window. set display=lastline set matchpairs& matchpairs+=<:> set laststatus=2 statusline=%!MakeStatusLine() set showtabline=2 tabline=%!MakeTabLine() " Don't show :intro when startup. set shortmess+=I if has('kaoriya') && s:is_win && has('gui_running') set ambiwidth=auto else set ambiwidth=double endif set helplang=en,ja " Get character code on cursor with 'fileencoding'. function! GetCharacterCode() let str = iconv(matchstr(getline('.'), '.', col('.') - 1), &enc, &fenc) let out = '0x' for i in range(strlen(str)) let out .= printf('%02X', char2nr(str[i])) endfor if str == '' let out .= '00' endif return out endfunction " Return the current file size in human readable format. function! GetFileSize() let size = &encoding ==# &fileencoding || &fileencoding == '' \ ? line2byte(line('$') + 1) - 1 : getfsize(expand('%')) if size < 0 let size = 0 endif for unit in ['B', 'KB', 'MB'] if size < 1024 return size . unit endif let size = size / 1024 endfor return size . 'GB' endfunction function! GetBufname(bufnr, tail) let bufname = bufname(a:bufnr) let buftype = getbufvar(a:bufnr, '&buftype') if bufname == '' if buftype == '' return '[No Name]' elseif buftype ==# 'quickfix' return '[Quickfix List]' elseif buftype ==# 'nofile' || buftype ==# 'acwrite' return '[Scratch]' endif endif if buftype ==# 'nofile' return bufname endif if a:tail return fnamemodify(bufname, ':t') endif let fullpath = fnamemodify(bufname, ':p') if exists('b:lcd') && b:lcd != '' let bufname = matchstr(fullpath, '^\V\(' . escape(b:lcd, '\') \ . '\v)?[/\\]?\zs.*') endif return bufname endfunction function! MakeStatusLine() let line = '' if s:check_flag('statusline_bufnr') let line .= '[%n] ' " Buffer number. endif let line .= '%<' " Truncate point. " Buffer name. let line .= '%{GetBufname("", 0)}' " Character encoding let line .= " [%{(&fenc!=''?&fenc:&enc).(&bomb?'(BOM)':'')}:" " File format (+ &binary and &endofline) let line .= "%{&ff.(&bin?'(BIN'.(&eol?'':'-noeol').')':'')}]" let line .= '%y' " Filetype. let line .= '%m' " Modified flag. let line .= '%r' " Readonly flag. let line .= '%h' " Help buffer hlag. let line .= '%w' " Preview window flag. " The state of SKK. let line .= "%{exists('b:skk_on')&&b:skk_on?SkkGetModeStr():''}" let line .= '%=' " Separation point. if s:check_flag('statusline_filesize') let line .= '[%{GetFileSize()}]' " Rough file size. endif if s:check_flag('statusline_char') let line .= '[%{GetCharacterCode()}]' " Character code under the cursor. endif if $LANG =~ '^ja' let line .= ' %l/%L行 %3v桁' " Line and column. else let line .= ' %l/%LL %2vC' " Line and column. endif let line .= ' %3p%%' " Percentage through file in lines. return line endfunction function! MakeTabLine() let line = '' for i in range(1, tabpagenr('$')) let bufnrs = tabpagebuflist(i) let curbufnr = bufnrs[tabpagewinnr(i) - 1] " first window, first appears let hi = i == tabpagenr() ? 'TabLineSel' : 'TabLine' let line .= '%'.i.'T' if getbufvar(curbufnr, '&filetype') =~# '^lingr-' " lingr-vim let unread = lingr#unread_count() let status = lingr#status() let line .= '%#' . hi . '#' let line .= 'lingr - ' . status if unread != 0 let line .= '(' . unread . ')' endif else let no = len(bufnrs) if no is 1 let no = '' endif let mod = len(filter(bufnrs, 'getbufvar(v:val, "&modified")')) ? '+' : '' let sp = (no . mod) == '' ? '' : ' ' let title = GetBufname(curbufnr, 1) if no != '' let line .= '%#' . hi . 'Number#' . no endif let line .= '%#' . hi . '#' let line .= mod . sp . title endif let line .= '%#TabLineFill#' let line .= ' | ' endfor let line .= '%#TabLineFill#%T%=%#TabLine#' let line .= '%{fnamemodify(getcwd(), ":~")} ' return line endfunction " == Behavior settings. == {{{1 " Enable FileType filetype off " reapply package/custom/ftdetect/*.vim. filetype plugin indent on " Search. set ignorecase smartcase incsearch grepprg=internal if has('migemo') " 'migemo' option changes the behavior of "g?". " NOTE: 'migemo' option is local to buffer. set nomigemo migemodict=$HOME/.vim/dict/migemo/migemo-dict endif " Tab and indent. set tabstop=2 shiftwidth=2 autoindent smartindent preserveindent " Auto reload when changed by external. set autoread " Enable backspace. set backspace=indent,eol,start " Allow move between line end and next line head. set whichwrap=b,s,<,>,[,] " Format settings for multi byte character. set formatoptions& formatoptions+=mM formatoptions-=r formatoptions-=o " The following needs autofmt plugin. let g:plugin_format_disable = 1 set formatexpr=autofmt#japanese#formatexpr() " Minimal number of screen lines to keep above and below the cursor. set scrolloff=3 set modeline " Open a window. set splitbelow splitright set switchbuf& switchbuf+=useopen " Completion. set complete& complete+=k set completeopt& completeopt+=menuone completeopt-=preview set infercase " Command-line completion. set wildmenu wildmode=list:longest,full " Foldings. set foldlevelstart=99 " History number for search and command mode. set history=1000 set timeoutlen=5000 set nrformats& nrformats-=octal " Backup. set backup set backupdir=./.backup,~/.backup " Paths of swap file and backup file. if $TMP != '' execute 'set backupdir+=' . escape(expand($TMP), ' \') elseif has('unix') set backupdir+=/tmp endif let &directory = &backupdir if has('viminfo') " TELLME: The history is not saved in specified number. set viminfo='500,<500,s50,h,rA:,rB: end " Free move in Visual mode blockwise. set virtualedit& virtualedit+=block " Don't search tags file in current directory. And search upward. set tags& tags-=tags tags+=./tags; " It sometimes fails in the searching of Japanese help unless this setting. set notagbsearch " autocmd augroup vimrc-auto-cursorline autocmd! autocmd CursorMoved,CursorMovedI * call s:auto_cursorline('CursorMoved') autocmd CursorHold,CursorHoldI * call s:auto_cursorline('CursorHold') autocmd WinEnter * call s:auto_cursorline('WinEnter') autocmd WinLeave * call s:auto_cursorline('WinLeave') let s:cursorline_lock = 0 function! s:auto_cursorline(event) if a:event ==# 'WinEnter' setlocal cursorline let s:cursorline_lock = 2 elseif a:event ==# 'WinLeave' setlocal nocursorline elseif a:event ==# 'CursorMoved' if s:cursorline_lock if 1 < s:cursorline_lock let s:cursorline_lock = 1 else setlocal nocursorline let s:cursorline_lock = 0 endif endif elseif a:event ==# 'CursorHold' setlocal cursorline let s:cursorline_lock = 1 endif endfunction augroup END augroup vimrc-lcd autocmd! autocmd BufReadPre,BufFilePre * unlet! b:lcd autocmd BufReadPost,BufFilePost,BufEnter * call s:lcd() function! s:lcd() let path = '' let simple = expand('%:p:h') if &l:buftype != '' && &l:buftype != 'help' unlet! b:lcd return endif if exists('b:lcd') && \ (b:lcd == '' || getcwd() =~# '^\V' . escape(b:lcd, '\') . '\$') return endif if path == '' && &l:buftype ==# 'help' let path = simple endif if path == '' let tf = tagfiles() if !empty(tf) let path = fnamemodify(tf[0], ':p:h') endif endif if path == '' let base = expand('%:p:h') for d in ['.git', '.bzr', '.hg'] let d = finddir(d, escape(base, '?*[]();') . ';') if d != '' let path = fnamemodify(d, ':p:h:h') break endif endfor endif if path == '' let base = substitute(expand('%:p'), '\\', '/', 'g') if base =~# '/src/' let path = base[: strridx(base, '/src/') + 3] endif endif if path == '' let path = simple endif if isdirectory(path) lcd `=path` let b:lcd = getcwd() endif endfunction augroup END augroup vimrc-scratch-buffer autocmd! " Make a scratch buffer when unnamed buffer. autocmd BufEnter * call s:scratch_buffer() autocmd FileType qfreplace autocmd! vimrc-scratch * function! s:scratch_buffer() if exists('b:scratch_buffer') || bufname('%') != '' || &l:buftype != '' return endif let b:scratch_buffer = 1 setlocal buftype=nofile nobuflisted noswapfile bufhidden=hide augroup vimrc-scratch autocmd! * autocmd BufWriteCmd call s:scratch_on_BufWriteCmd() augroup END endfunction function! s:scratch_on_BufWriteCmd() silent! setl buftype< buflisted< swapfile< bufhidden< nomodified autocmd! vimrc-scratch * if bufname('%') == '' && exists('b:scratch_buffer') execute 'saveas' . (v:cmdbang ? '!' : '') ' ' filetype detect endif unlet! b:scratch_buffer endfunction augroup END if executable('chmod') augroup vimrc-autoexecutable autocmd! autocmd BufWritePost * call s:add_permission_x() augroup END function! s:add_permission_x() let file = expand(':p') if getline(1) =~ '^#!' && !executable(file) silent! call system('chmod a+x ' . shellescape(file)) endif endfunction endif if &binary " launched with -b option augroup vimrc-xxd autocmd! autocmd BufReadPost * if &l:binary | setlocal filetype=xxd | endif augroup END endif augroup vimrc-misc autocmd! " Jump to the last editing position. autocmd BufReadPost * if line("'\"") && line("'\"") <= line('$') \ | execute 'normal! g`"' | endif " Set 'dictionary'. autocmd FileType * if filereadable(expand('~/.vim/dict/' . &l:ft . '.dict')) \ | let &l:dict='~/.vim/dict/' . &l:ft . '.dict' | endif autocmd FileType * if &l:buftype !=# 'help' && &l:kp == '' && \ mapcheck('K', 'n') == '' \ | silent! execute 'nnoremap K }' | endif " Auto open/close Quickfix/location window. autocmd QuickFixCmdPost [^l]* cwindow | redraw! autocmd QuickFixCmdPost l* lwindow | redraw! autocmd BufWritePost * if &l:filetype == '' || exists('b:ftdetect') \ | unlet! b:ftdetect | filetype detect | endif autocmd BufReadPost bzr_log.* let &l:fileencoding = &termencoding " Edit something to avoid the confirmation when aborting. autocmd BufReadPost bzr_log.* 1 delete _ | silent write augroup END " == Key mappings & command definition. == {{{1 " Physical moving. noremap j gj noremap k gk noremap gj j noremap gk k " Yank to the end of line. (It is same as C and D) nnoremap Y y$ " Current line at center of window and open the folding. noremap n nzzzv noremap N Nzzzv " Very magic by default. nnoremap / :set hlsearch/\v nnoremap ? :set hlsearch?\v cnoremap s/ getcmdline() =~# '^\A*$' ? 's/\v' : 's/' cnoremap g/ getcmdline() =~# '^\A*$' ? 'g/\v' : 'g/' cnoremap v/ getcmdline() =~# '^\A*$' ? 'v/\v' : 'v/' cnoremap s// s// cnoremap g// g// cnoremap v// v// " Control search highlight. noremap (vimrc-searchafter) Nzz:set hlsearch map * (visualstar-*)(vimrc-searchafter) map # (visualstar-#)(vimrc-searchafter) map g* (visualstar-g*)(vimrc-searchafter) map g# (visualstar-g#)(vimrc-searchafter) nnoremap :set nohlsearch " Search selected area. vnoremap z/ /\v%V vnoremap z? ?\v%V " Switch the tab page. nnoremap gt nnoremap gT " Scroll + Move nnoremap gj nnoremap gk " Swap ; and : noremap ; : noremap : ; " Speedy :h nnoremap speedy_help('h') function! s:speedy_help(help) let help = a:help if 78 * 2 <= winwidth(0) let help = 'vert ' . help endif return ":\" . help . ' ' endfunction " Quick completion. inoremap inoremap neocomplcache#manual_filename_complete() " Create an undo point before and . inoremap (pumvisible() ? "\" : '') . "\u\" inoremap "\u\" inoremap pumvisible() ? "\\" : "\" inoremap " Select the last changed. nnoremap gc `[v`] onoremap q /["',.{}()[\]<>] " Prevent a typing error. nmap inoremap cnoremap nnoremap h nnoremap j nnoremap k nnoremap l nnoremap h nnoremap j nnoremap k nnoremap l " Don't use commands. noremap ZZ noremap ZQ " Mappings for command-line mode. cnoremap cnoremap cnoremap " Move the cursor not complete list. cnoremap cnoremap cnoremap cnoremap cnoremap cnoremap nnoremap " Quick save and quit. nnoremap w :update nnoremap W :update! nnoremap q :quit nnoremap Q :quit! " Change encodings and formats. nnoremap e nnoremap es :setl fenc=cp932 nnoremap ee :setl fenc=euc-jp nnoremap eu :setl fenc=utf-8 nnoremap ed :setl ff=dos nnoremap ex :setl ff=unix " Change statusline. nnoremap s nnoremap sn \ :call toggle_flag('g:statusline_bufnr') nnoremap sc \ :call toggle_flag('g:statusline_char') nnoremap ss \ :call toggle_flag('g:statusline_filesize') " Quick toggle options. nnoremap o nnoremap of :let &l:foldcolumn=1-&l:foldcolumn \:setl fdc? nnoremap on :setl number! number? nnoremap t nnoremap tn :tabnew nnoremap tc :tabclose function! s:grep_same_ext(pat) silent! execute 'lvimgrep /' . a:pat . '/j **/*.' . expand('%:e') endfunction nnoremap grep :call grep_same_ext('\C' . @/) nnoremap Grep :call grep_same_ext('\c' . @/) " , : Move window position {{{ nnoremap :call swap_window(v:count1) nnoremap :call swap_window(-v:count1) function! s:swap_window(n) "{{{ let curbuf = bufnr('%') let target = s:modulo(winnr() + a:n - 1, winnr('$')) + 1 " 'hide' is necessary to keep the undo history. execute 'hide' winbufnr(target) . 'buffer' execute target . 'wincmd w' execute curbuf . 'buffer' endfunction "}}} " }}} " Shortcut enc and ff. cnoreabbrev ++u ++enc=utf8 cnoreabbrev ++c ++enc=cp932 cnoreabbrev ++s ++enc=cp932 cnoreabbrev ++e ++enc=euc-jp cnoreabbrev ++j ++enc=iso-2022-jp cnoreabbrev ++x ++ff=unix cnoreabbrev ++d ++ff=dox cnoreabbrev ++m ++ff=mac " This is for editing list separated by a arbitrary character such as $PATH. nnoremap ; :call toggle_separate() function! s:toggle_separate() let c = getchar() if type(c) == type(0) let c = nr2char(c) endif if c !~ '[[:print:]]' return endif if stridx(getline('.'), c) < 0 execute '%s/\n/' . c normal! m`$x`` else execute '%s/' . c . '/\r/g' silent global/^$/delete _ endif endfunction " Generate help tags. command! -bar Helptags call s:helptags() function! s:helptags() " {{{2 for i in filter(map(split(&rtp, ','), 'expand(v:val) . "/doc"'), \ 'isdirectory(v:val) && $VIM != v:val[: len($VIM) - 1]') echo i[ : -5] try execute 'helptags' i catch call s:echoerr(matchstr(v:exception, '^.\{-}:\zsE\d\+:.*$')) endtry endfor endfunction " Show the diff between the current buffer and the last saved file. {{{ " TODO: Become plugin. function! s:diff_original() if exists('b:diff_current') execute bufwinnr(b:diff_current) 'wincmd w' endif if exists('b:diff_original') diffoff execute b:diff_original 'bwipeout' unlet b:diff_original return endif let bufnr = bufnr('%') let ft = &l:filetype let fenc = &l:fileencoding if &modified let source = '#' . bufnr let file = '[last save]' endif if !exists('source') silent! call system('svn info') if !v:shell_error let source = '!svn cat #' . bufnr let file = '[svn HEAD]' endif endif if !exists('source') silent! call system('bzr info') if !v:shell_error let source = '!bzr cat #' . bufnr let file = '[bzr tip]' endif endif if !exists('source') silent! let git_dir = system('git rev-parse --git-dir') if git_dir != '' let source = '!git cat-file blob HEAD:' . \ expand('#' . bufnr . ':p')[strlen(fnamemodify(git_dir, ':p')) - 5:] let source = substitute(source, '\\', '/', 'g') let file = '[git HEAD]' endif endif if !exists('source') echo 'There is not the diff.' return endif vertical new let b:diff_current = bufnr let bufnr = bufnr('%') setlocal bt=nofile let &l:filetype = ft let &l:fileencoding = fenc file `=file . fnamemodify(bufname(b:diff_current), ':.')` silent! execute 'read' source 0 delete _ diffthis wincmd p diffthis let b:diff_original = bufnr endfunction nnoremap diff :call diff_original() " }}} " Translation interface. {{{ " trans.pl is a translation filter via web translation. let g:trans = expand('~/.vim/bin/trans.pl') if executable('perl') && filereadable(g:trans) nnoremap tt :set operatorfunc=echo_translateg@ nnoremap ts :set operatorfunc=swap_translateg@ vnoremap tt :echo translate(visualmode(), 1) vnoremap ts :call swap_translate(visualmode(), 1) command! -nargs=+ Trans echo s:translate(, 2) function! s:echo_translate(type) echo s:translate(a:type) endfunction function! s:swap_translate(type, ...) let [save_reg, save_reg_type] = [getreg('"'), getregtype('"')] let @" = s:translate(a:type, a:0 && a:1) normal! gvp call setreg('"', save_reg, save_reg_type) endfunction function! s:translate(type, ...) if a:0 && a:1 is 2 let s = a:type else let s = s:get_range(a:type, a:0 && a:1 ? 'v' : 'o') endif if &filetype ==# 'help' let s = substitute(s, '[*|]', '', 'g') endif if s =~ '^\S*$' let s = substitute(s, '\(\l\)\(\u\)', '\1 \2', 'g') let s = substitute(s, '[_-]', ' ', 'g') let s = substitute(s, '\u\{2,}', '\0 ', 'g') let s = substitute(s, '\s\+', ' ', 'g') let s = substitute(tolower(s), '^\s*\|\s*$', '', 'g') endif echo 'During translation...' let s = exists('*vimproc#system') \ ? vimproc#system(['perl', g:trans], s) \ : system('perl ' . shellescape(g:trans), s) echo '' redraw return s endfunction endif " }}} " -- Commands. command! -nargs=1 -bang -bar -complete=file Rename Move command! -nargs=1 -bang -bar -complete=file Move \ call s:move(, ) function! s:move(file, bang) " {{{2 let from = expand('%:p') let to = simplify(expand(a:file)) if isdirectory(to) let to .= '/' . fnamemodify(from, ':t') endif let dir = fnamemodify(to, ':h') if !isdirectory(dir) call mkdir(dir, 'p') endif execute 'saveas' . a:bang '`=to`' call delete(from) endfunction command! -nargs=? -bang -bar -complete=file Delete \ call s:delete_with_confirm(, 0) function! s:delete_with_confirm(file, force) let file = a:file == '' ? expand('%') : a:file if !a:force echo 'Delete "' . file . '"? [y/N]:' endif if a:force || nr2char(getchar()) ==? 'y' call delete(file) echo 'Deleted "' . file . '"!' else echo 'Cancelled.' endif endfunction command! -bar Diff if &diff | execute 'windo diffoff' | else \ | execute 'windo diffthis' | endif if executable('ctags') " Execute ctags command. And echo for error. command! -bar CtagsR echo iconv(system(printf('ctags -R %s', \ len(tagfiles()) ? '-f ' . tagfiles()[0] . ' ' . \ fnamemodify(tagfiles()[0], ':h') : '.')), &tenc, &enc) nnoremap tr :CtagsR endif command! -bar Tasks execute 'vimgrep /\C\v<(TODO|FIXME|XXX):/ **/*.' \ . expand('%:e') " :HighlightWith {filetype} ['a 'b] XXX: Don't work in some case. command! -nargs=+ -range=% HighlightWith ,call s:highlight_with() function! s:highlight_with(args) range if a:firstline == 1 && a:lastline == line('$') return endif let c = get(b:, 'highlight_count', 0) let ft = matchstr(a:args, '^\w\+') if globpath(&rtp, 'syntax/' . ft . '.vim') == '' return endif unlet! b:current_syntax let save_isk= &l:isk " For scheme. execute printf('syntax include @highlightWith%d syntax/%s.vim', \ c, ft) let &l:isk= save_isk execute printf('syntax region highlightWith%d start=/\%%%dl/ end=/\%%%dl$/ ' \ . 'contains=@highlightWith%d', \ c, a:firstline, a:lastline, c) let b:highlight_count = c + 1 endfunction " Grep({text}, {pat} [, invert]) function! Grep(text, pat, ...) let op = a:0 && a:1 ? '!~#' : '=~#' return join(filter(split(a:text, "\n"), 'v:val' . op . 'a:pat'), "\n") endfunction " CommandGrep function! Cgrep(cmd, pat, ...) return Grep(C(a:cmd), a:pat, a:0 && a:1) endfunction function! s:cgrep(args, v) let list = matchlist(a:args, '^\v(/.{-}\\@, 0) command! -nargs=+ Vars PP filter(copy(g:), 'v:key =~# "^"') " == Setting according to environments. == {{{1 " cygwin (UTF-8) if has('win32unix') set termencoding= endif " Use a mouse in terminal. set mouse=a " For GNU Screen and tmux. if $WINDOW != '' || $TMUX != '' let s:window = 1 " Use a mouse in screen. if has('mouse') set ttymouse=xterm2 endif function! s:set_window_name(name) let esc = "\" silent! execute '!echo -n "' . esc . 'k' . escape(a:name, '%#!') \ . esc . '\\"' redraw! endfunction command! -nargs=? WindowName call s:set_window_name() function! s:auto_window_name() " {{{2 let varname = 'window_name' for scope in ['w:', 'b:', 't:', 'g:'] if exists(scope .varname) call s:set_window_name(eval(scope . varname)) return endif endfor if bufname('%') !~ '^\[A-Za-z0-9\]*:/' call s:set_window_name('v:' . expand('%:t')) endif endfunction augroup vimrc-screen autocmd! autocmd VimEnter * call s:set_window_name(0 < argc() ? \ 'v:' . fnamemodify(argv(0), ':t') : 'vim') autocmd BufEnter,BufFilePost * call s:auto_window_name() autocmd VimLeave * call s:set_window_name(len($SHELL) ? \ fnamemodify($SHELL, ':t') : 'shell') augroup END let s:vim_plugin_dir = expand('~/work/vim-plugins') if isdirectory(s:vim_plugin_dir) if $TMUX != '' function! s:vim_plugin_test() " {{{2 let file = expand('%:p') let plugin = matchstr(file, s:vim_plugin_dir . '/\zs[^/]\+') if plugin == '' call s:echoerr('Not in vim plugin.') return endif call system(printf('tmux new-window "zsh -i -c \"cd %s/%s; vim\""', \ s:vim_plugin_dir, plugin)) endfunction command! VimPluginTest call s:vim_plugin_test() endif endif endif " GUI if has('gui_running') " My default gui settings. function! s:init_guioptions() " GUI option to use by default. winpos 0 0 " Disable Toolbar and menu, and use non-GUI tab pages line. set guioptions-=T guioptions-=m guioptions-=e " Hide any scrollbar. set guioptions-=l guioptions-=r guioptions-=L guioptions-=R if has('kaoriya') && s:is_win set guioptions+=C " Remove caption (title) bar. Support Windows only. endif if s:is_win set guifont=M+2VM+IPAG_circle:h9:cDEFAULT,MS_Gothic:h9:cDEFAULT elseif has('x11') set guifont= elseif has('unix') set guifont=M+2M+IPAG\ 9 endif endfunction command! -nargs=0 -bar InitGuioptions call s:init_guioptions() let $MYGVIMRC = expand('~/.gvimrc') if !filereadable($MYGVIMRC) InitGuioptions endif " Save guioptions and window info to $MYGVIMRC when leaving vim. augroup vimrc-guioptons autocmd! autocmd VimLeavePre * call s:save_options() function! s:save_options() if !exists('$MYGVIMRC') return endif let options = [ \ 'set columns=' . &columns, \ 'set lines=' . &lines, \ 'winpos ' . getwinposx() . ' ' . getwinposy(), \ 'set guioptions=' . &guioptions, \ 'set guifont=' . escape(&guifont, '\ '), \ ] call writefile(options, $MYGVIMRC) endfunction augroup END " Do not use IME by default. set iminsert=0 imsearch=0 " Don't use commands in gui. noremap else " CUI if executable('winclip') nnoremap "+y :set operatorfunc=winclipg@ nnoremap "*y :set operatorfunc=winclipg@ vnoremap "+y :call winclip() vnoremap "*y :call winclip() vnoremap "+Y :w !winclip vnoremap "*Y :w !winclip function! s:winclip(...) let s = s:get_range(a:0 ? a:1 : visualmode(), a:0 ? 'o' : 'v') let temp = tempname() call writefile(split(s, "\n", 1), temp, 'b') silent! execute '!winclip ' . shellescape(temp) call delete(temp) endfunction endif if has('unix') function! s:emulate_meta_keys() " Emulate meta key in console. for i in map( \ range(char2nr('a'), char2nr('z')) \ + range(char2nr('A'), char2nr('Z')) \ + range(char2nr('0'), char2nr('9')) \ , 'nr2char(v:val)') " O do not map because used by arrow keys. if i !~# '[O]' execute 'nmap ' . i '' endif endfor map map! endfunction call s:emulate_meta_keys() endif endif " == Filetype settings. == {{{1 " Java let g:java_highlight_functions = 'style' let g:java_highlight_all = 1 let g:java_allow_cpp_keywords = 1 " PHP let g:php_folding = 1 " Python let g:python_highlight_all = 1 " Scheme let g:is_gauche = 1 " gauref let g:gauref_file = '~/.vim/ftplugin/scheme/gauche-refj.txt' " XML let g:xml_syntax_folding = 1 " Vim let g:vimsyntax_noerror = 1 let g:vim_indent_cont = 0 " lisp let g:lisp_rainbow = 1 " Clojure let g:vimclojure#HighlightBuiltins = 1 let g:vimclojure#ParenRainbow = 1 " bzr let g:bzr_highlight_diff = 1 " == Plugin settings. == {{{1 let s:user_rtp = expand('~/.vim') let s:custom_rtp = expand('~/.vim/custom') let s:plugin_info = s:user_rtp . '/info/' " netrw.vim {{{2 let g:netrw_home = s:plugin_info . '/netrw' " taglist.vim {{{2 let g:Tlist_Show_One_File = 1 let g:Tlist_Exit_OnlyWindow = 1 nnoremap l :TlistToggle " NERD_Tree.vim {{{2 let g:NERDTreeHijackNetrw = 0 nnoremap e :NERDTreeToggle " NERD_Comment.vim {{{2 " Don't warn even unknown filetype. let NERDShutUp = 1 " Use /* xxx */ not /*xxx*/ let NERDSpaceDelims = 1 " fuf.vim {{{2 nnoremap ab :FufBuffer nnoremap ac :FufMruCmd vnoremap c :FufMruCmd :'<,'> nnoremap d :FufDir \ =fnamemodify('.', ':p') nnoremap af :FufFile nnoremap a :FufFile \ =expand('%:~:.:h')/ nnoremap am :FufMruFile nnoremap g :FufTaggedFile nnoremap t :FufTag let g:fuf_ignoreCase = 1 let g:fuf_maxMenuWidth = 200 let g:fuf_infoFile = s:plugin_info . 'fuzzyfinder' let g:fuf_file_exclude = '\%(\.svn\|\.git\|\.hg\|\.bzr\)\>' let g:fuf_abbrevMap = { \ '\C^VA' : map(split(&rtp, ','),'escape(fnamemodify(v:val, ":~"), "\\") . "/autoload/"'), \ '\C^VF' : map(split(&rtp, ','),'escape(fnamemodify(v:val, ":~"), "\\") . "/ftplugin/"'), \ '\C^VP' : map(split(&rtp, ','),'escape(fnamemodify(v:val, ":~"), "\\") . "/plugin/"'), \ '\C^VS' : map(split(&rtp, ','),'escape(fnamemodify(v:val, ":~"), "\\") . "/syntax/"'), \ '\C^VC' : map(split(&rtp, ','),'escape(fnamemodify(v:val, ":~"), "\\") . "/colors/"'), \ } let g:fuf_mrufile_exclude = \ '\v\c\~$|\.bak$|\.swp$|\.org$|\/tmp' \ . '|\V' . join(map(split(escape(&backupdir, '\'), ','), \ 'v:val . "\\.\\*"'), '\|') let g:fuf_mruFile_maxItem = 200 let g:fuf_mruCmd_maxItem = 50 augroup vimrc-plugin-fuzzyfinder autocmd! autocmd FileType fuf inoremap augroup END " vimshell.vim {{{2 let g:vimshell_vimshrc_path = $HOME . '/.vim/vimshrc' let g:vimshell_enable_interactive = 1 let g:vimshell_temporary_directory = s:plugin_info . 'vimshell' let g:vimshell_prompt = '% ' let g:vimshell_user_prompt = 'fnamemodify(getcwd(), ":~") . " " .' . \ 'vimshell#vcs#info("(%s)-[%b]", "(%s)-[%b|%a]")' if !exists('g:vimshell_execute_file_list') let g:vimshell_execute_file_list = { \ 'rb': 'ruby', \ 'pl': 'perl', \ 'py': 'python', \ 'scm': 'gosh', \ 'hs': 'runghc', \ 'scala': 'scala', \ 'lua': 'lua', \ 'jar': 'java -jar', \ } endif nmap sh (vimshell_split_switch) nmap sH (vimshell_split_create) " vimfiler.vim {{{2 let g:vimfiler_as_default_explorer = 1 " neocomplcache.vim {{{2 let g:neocomplcache_enable_at_startup = 1 let g:neocomplcache_enable_camel_case_completion = 1 " let g:neocomplcache_enable_quick_match = 0 let g:neocomplcache_temporary_dir = s:plugin_info . 'neocomplcache' let g:neocomplcache_snippets_dir = s:custom_rtp . '/snippets' call s:set_default('g:neocomplcache_keyword_patterns', \ {'javascript' : '\v\k+'}) call s:set_default('g:neocomplcache_same_filetype_lists', \ {'javascript' : 'java'}) call s:set_default('g:neocomplcache_quick_match_patterns', \ {'default' : '@'}) let g:neocomplcache_auto_completion_start_length = 1 let g:neocomplcache_plugin_completion_length_list = { \ 'snippets_complete' : 1, \ 'buffer_complete' : 2, \ 'syntax_complete' : 2, \ 'tags_complete' : 3, \ } imap neocomplcache#plugin#snippets_complete#expandable() ? \ "\(neocomplcache_snippets_expand)" : "\" inoremap pumvisible() ? neocomplcache#close_popup() : "\" inoremap pumvisible() ? neocomplcache#cancel_popup() : "\" " Start editing with any key in the select mode. " This overwrites :vmap. augroup vimrc-plugin-snippets autocmd! autocmd VimEnter,BufEnter * call s:snippets_remap() augroup END function! s:snippets_remap() smapclear smapclear smap a(neocomplcache_snippets_expand) snoremap _ endfunction " rsense.vim {{{2 " let g:rsenseHome = expand("~/app/rsense") " let g:rsenseUseOmniFunc = 1 " calendar.vim {{{2 let g:calendar_navi_label = '前月,今月,次月' let g:calendar_mruler = \ '睦月,如月,弥生,卯月,皐月,水無月,文月,葉月,長月,神無月,霜月,師走' let g:calendar_wruler = '日 月 火 水 木 金 土' nmap cal CalendarV nmap caL CalendarH " skk.vim {{{2 let g:skk_large_jisyo = '~/.vim/dict/skk/SKK-JISYO.L' let g:skk_auto_save_jisyo = 1 let g:skk_keep_state = 1 let g:skk_egg_like_newline = 1 let g:skk_show_annotation = 1 let g:skk_use_face = 1 highlight default skk_henkan ctermbg=1 ctermfg=15 guibg=#0000FF guifg=#FFFFFF " Following options are patched by id:krogue. let g:skk_sticky_key = ';' let g:skk_kakutei_key = '.' let g:skk_use_color_cursor = 1 " eskk.vim {{{2 let g:eskk_large_dictionary = { \ 'path': '~/.vim/dict/skk/SKK-JISYO.L', \ 'sorted': 1, \ 'encoding': 'utf-8', \} let g:eskk_show_annotation = 1 " let g:eskk_debug = 1 " let g:eskk_debug_profile = 1 " submode.vim {{{2 " let g:submode_timeout = 0 " TELLME: The above setting do not work. " Use the following instead of above. let g:submode_timeoutlen = 1000000 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('change-list', 'n', '', 'g;', 'g;') call submode#enter_with('change-list', 'n', '', 'g,', 'g,') call submode#map('change-list', 'n', '', ';', 'g;') call submode#map('change-list', 'n', '', ',', 'g,') call submode#enter_with('changetab', 'n', '', 'gt', 'gt') call submode#enter_with('changetab', 'n', '', 'gT', 'gT') call submode#map('changetab', 'n', '', 't', 'gt') call submode#map('changetab', 'n', '', 'T', 'gT') function! s:movetab(nr) execute 'tabmove' s:modulo(tabpagenr() + a:nr - 1, tabpagenr('$')) endfunction let s:movetab = ':call ' . s:SIDP() . 'movetab(%d)' call submode#enter_with('movetab', 'n', '', 'gt', printf(s:movetab, 1)) call submode#enter_with('movetab', 'n', '', 'gT', printf(s:movetab, -1)) call submode#map('movetab', 'n', '', 't', printf(s:movetab, 1)) call submode#map('movetab', 'n', '', 'T', printf(s:movetab, -1)) unlet s:movetab call submode#enter_with('winsize', 'n', '', '>', '>') call submode#enter_with('winsize', 'n', '', '<', '<') call submode#enter_with('winsize', 'n', '', '+', '-') call submode#enter_with('winsize', 'n', '', '-', '+') call submode#map('winsize', 'n', '', '>', '>') call submode#map('winsize', 'n', '', '<', '<') call submode#map('winsize', 'n', '', '+', '-') call submode#map('winsize', 'n', '', '-', '+') call submode#enter_with('diff', 'n', '', 'diff') call submode#map('diff', 'n', '', 'j', ']c') " next diff call submode#map('diff', 'n', '', 'k', '[c') " prev diff call submode#map('diff', 'n', '', 'h', 'do') " get diff call submode#map('diff', 'n', '', 'l', 'dp') " put diff call submode#map('diff', 'n', '', 'u', 'do]c') " get diff and next diff call submode#map('diff', 'n', '', 'i', 'dp]c') " put diff and next diff " metarw.vim {{{2 call metarw#define_wrapper_commands(1) " ku.vim {{{2 let g:ku_personal_runtime = s:user_rtp let g:ku_file_mru_file = s:plugin_info . 'ku/file_mru' let g:ku_file_mru_limit = 200 let g:ku_file_mru_ignore_pattern = join([ \ '/svn-commit\%(\.\d\+\)\?\.tmp$', \ '.git/COMMIT_EDITMSG$', \ '/bzr_log\..\{6}$', \ ], '\|') if $TMP != '' let g:ku_file_mru_ignore_pattern .= \ '\|^' . substitute(expand($TMP), '\', '/', 'g') elseif has('unix') let g:ku_file_mru_ignore_pattern .= '\|^/tmp/\|^/var/tmp/' endif nnoremap ku :Ku nnoremap ka :Ku args nnoremap b :Ku buffer nnoremap : :Ku cmd_mru/cmd nnoremap ; :Ku cmd_mru/cmd nnoremap / :Ku cmd_mru/search nnoremap f :Ku file nnoremap \ :call ku#start('file', expand('%:~:.:h') . '/') nnoremap kg :Ku metarw/git nnoremap kh :Ku history nnoremap m :Ku file_mru nnoremap kq :Ku quickfix nnoremap ks :Ku source function! s:ku_action_file_delete(item) execute 'Delete' a:item.word endfunction " call ku#custom_action('file', 'delete', s:SIDP() . 'ku_action_file_delete') " call ku#custom_key('file', 'd', 'delete') call ku#custom_prefix('file', '~', $HOME) call ku#custom_prefix('file', '\', $HOME . '/') call ku#custom_prefix('file', '.v', $HOME . '/.vim/') call ku#custom_prefix('file', '.va', $HOME . '/.vim/autoload/') call ku#custom_prefix('file', '.vp', $HOME . '/.vim/package/') call ku#custom_prefix('file', '.vl', $HOME . '/.vim/plugin/') call ku#custom_prefix('file', '.vs', $HOME . '/.vim/syntax/') call ku#custom_prefix('file', '.vc', $HOME . '/.vim/custom/') call ku#custom_prefix('file', '.vcp', s:custom_rtp . '/plugin/') call ku#custom_prefix('file', '.vf', s:custom_rtp . '/after/ftplugin/') if s:is_win call ku#custom_prefix('file', '.p', 'C:/Program Files/') endif if isdirectory(expand('~/work/vim-plugins')) call ku#custom_prefix('file', '.vd', $HOME . '/work/vim-plugins/') endif " fakeclip.vim {{{2 nmap "+Y "+y$ nmap "*Y "*y$ nmap "&Y "&y$ " smartword.vim {{{2 nmap w (smartword-w) nmap b (smartword-b) nmap e (smartword-e) nmap ge (smartword-ge) vmap w (smartword-w) vmap b (smartword-b) vmap e (smartword-e) vmap ge (smartword-ge) omap w (smartword-w) omap b (smartword-b) omap e (smartword-e) omap ge (smartword-ge) " textobj-user.vim {{{2 " textobj-function let g:textobj_function_no_default_key_mappings = 1 omap iF (textobj-function-i) omap aF (textobj-function-a) vmap iF (textobj-function-i) vmap aF (textobj-function-a) " operator-user.vim {{{2 " operator-replace map mp (operator-replace) " ProjectEuler.vim {{{2 let g:projecteuler_dir = s:plugin_info . 'projecteuler/' let g:projecteuler_user = 'thinca' let g:projecteuler_problem_lang = 'ja' " lingr.vim {{{2 if !exists('g:lingr') " Only when started by the 'lingr' command(alias), lingr.vim is used. " alias lingr="vim --cmd 'let g:lingr = 1' -c LingrLaunch" let g:loaded_lingr_vim = 1 endif let g:lingr_vim_user = 'thinca' augroup vimrc-plugin-lingr autocmd! autocmd User plugin-lingr-* call s:lingr_event( \ matchstr(expand(''), 'plugin-lingr-\zs\w*')) autocmd FileType lingr-* call s:init_lingr(expand('')) augroup END function! s:init_lingr(ft) if exists('s:window') nnoremap :call auto_window_name() let b:window_name = 'lingr-vim' endif endfunction function! s:lingr_event(event) if a:event ==# 'message' && exists(':WindowName') execute printf('WindowName %s(%d)', 'lingr-vim', lingr#unread_count()) endif endfunction " quickrun.vim {{{2 function! s:init_quickrun() for [key, c] in items({ \ 'x': '>:', \ 'p': '>!', \ '"': '>=@"', \ 'w': '', \ 'q': '>>', \ 'vx': '-eval 1 >:', \ 'vp': '-eval 1 >!', \ 'v"': '-eval 1 >=@"', \ 'vw': '-eval 1', \ 'vq': '-eval 1 >>', \ }) execute 'nnoremap ' key ':QuickRun' c '-mode n' execute 'vnoremap ' key ':QuickRun' c '-mode v' endfor let g:quickrun_config = { \ '_': {'debug': 1, 'input': '={b:input}', 'args': '{b:args}'}, \ 'clojure': {'command': 'clj', 'eval_template': '(print %s)'}, \ 'markdown': {'command': 'mdv2html'}, \ 'xmodmap': {}, \ 'mxml': {'exec': ['amxmlc %s', 'adl %s:r-app.xml'], \ 'output_encode': '&tenc:&enc'}, \ 'vimgolf': { \ 'command': 'vim', \ 'exec': ['touch temp', '%c -u NONE -s %s temp >/dev/null 2>\&1', \ 'cat temp', 'rm -f temp >/dev/null 2>\&1']} \ } if has('python') let g:quickrun_config._.runmode = 'async:python' elseif has('clientserver') && !empty(v:servername) let g:quickrun_config._.runmode = 'async:remote:vimproc' endif if executable('C') let g:quickrun_config.c = {'command': 'C', 'exec': '%c -m %s %a'} let g:quickrun_config.cpp = {'command': 'C', 'exec': '%c -p %s %a'} endif map x1 (quicklaunch-1) nmap x2 (quicklaunch-2) vmap x3 (quicklaunch-3) nmap r (quickrun-op) endfunction call s:init_quickrun() augroup vimrc-plugin-quickrun autocmd! autocmd BufReadPost,BufNewFile [Rr]akefile,[Rr]akefile.rb \ let b:quickrun_config = {'exec': 'rake -f %s'} augroup END function! s:complete_open_scratch(a, c, p) return filter(keys(extend(copy(g:quickrun#default_config), \ g:quickrun_config)), 'v:val != "*" && v:val =~ "^".a:a') endfunction function! s:open_scratch() let ft = input('type?', '', 'customlist,' . s:SIDP() \ . 'complete_open_scratch') if ft == '' return endif if 78 * 2 < winwidth(0) vnew else new endif let &l:filetype = ft execute 'TemplateLoad Scratch.' . ft endfunction nnoremap s :call open_scratch() " template.vim {{{2 augroup vimrc-plugin-template autocmd! autocmd FileType * if exists(':TemplateLoad') \ | execute 'TemplateLoad /filetype/' . &l:filetype \ | endif autocmd User plugin-template-loaded call s:template_loaded() autocmd BufEnter *package/custom/template/* setlocal makeprg= augroup END function! s:template_loaded() silent %substitute/<%=\(.\{-}\)%>/\=eval(submatch(1))/ge call histdel('/', -1) if search('<+CURSOR+>') normal! "_da> endif endfunction " ref.vim {{{2 let g:ref_open = 'vsplit' let g:ref_cache_dir = s:plugin_info . 'ref' let g:ref_phpmanual_path = $HOME . '/share/doc/php' let g:ref_alc_start_linenumber = 37 let g:ref_alc_use_cache = 1 nnoremap K \ :call ref#jump('normal', 'alc', {'noenter': 1}) vnoremap K \ :call ref#jump('visual', 'alc', {'noenter': 1}) nnoremap :Ref alc nnoremap :Ref =ref#detect() if !exists('g:ref_detect_filetype') let g:ref_detect_filetype = {} endif function! g:ref_detect_filetype._(ft) if &keywordprg ==# ':help' return '' endif return 'man' endfunction " poslist.vim {{{2 let g:poslist_histsize = 1000 map (poslist-prev-pos) map (poslist-next-pos) map (poslist-prev-buf) map (poslist-next-buf) " verifyenc.vim (Included in the KaoriYa ver by default.) " This plugin has a bug that autocmd is carried out endlessly. let plugin_verifyenc_disable = 1 " dicwin.vim " This config is enabled in only my own patch. let g:dicwin_leader = "\" " == Misc. == {{{1 " Assist b:undo_ftplugin function! SetUndoFtplugin(com) let command = 'execute ' . string(a:com) if exists('b:undo_ftplugin') let command .= ' | ' . b:undo_ftplugin endif let b:undo_ftplugin = command endfunction command! -nargs=1 -bang -complete=command SetUndoFtplugin \ call SetUndoFtplugin() " syntax test nnoremap :echo join(map(synstack(line('.'), col('.')), \ 'synIDattr(v:val, "name") \ ."(".synIDattr(synIDtrans(v:val), "name").")"'), ',') inoremap :echo join(map(synstack( \ line('.'), col('.')), 'synIDattr(v:val, "name") \ ."(".synIDattr(synIDtrans(v:val), "name").")"'), ',') "\n" " Redirection with nestable. " Colored output will be broken. function! Redir(...) let temp = tempname() let save_vfile = &verbosefile let &verbosefile = temp try for c in a:000 silent execute c endfor finally if &verbosefile ==# temp let &verbosefile = save_vfile let res = join(readfile(temp), "\n") call delete(temp) return res endif endtry endfunction function! C(...) redir => result for c in a:000 silent execute c endfor redir END return result endfunction command! -nargs=+ -bang -complete=command Capture call s:capture() function! s:capture(cmd) " {{{2 let result = C(a:cmd) new put =result silent 1,3 delete _ endfunction " for debug: Call a script local function. " Usage: " - S('local_func') " -> call s:local_func() in current file. " - S('plugin/hoge.vim:local_func', 'string', 10) " -> call s:local_func('string', 10) in *plugin/hoge.vim. " - S('plugin/hoge:local_func("string", 10)') " -> call s:local_func("string", 10) in *plugin/hoge(.vim)?. function! S(f, ...) let [file, func] =a:f =~ ':' ? split(a:f, ':') : [expand('%:p'), a:f] let fname = matchstr(func, '^\w*') " Get sourced scripts. let slist = Redir('scriptnames') let filepat = '\V' . escape(file, '\') . '\v%(\.vim)?$' for s in split(slist, "\n") if s =~ filepat let nr = matchstr(s, '^\s*\zs\d\+\ze:') if exists(printf("*\%d_%s", nr, fname)) let cfunc = printf("\%d_%s", nr, func) break endif endif endfor if !exists('nr') echoerr 'Not sourced: ' . file return elseif !exists('cfunc') let file = fnamemodify(file, ':p') echoerr 'File found, but function is not defined: ' . file . ':' . fname return endif return 0 <= match(func, '^\w*\s*(.*)\s*$') \ ? eval(cfunc) : call(cfunc, a:000) endfunction function! s:time(cmd, log) if !has('reltime') echo 'Feature +reltime is disabled. Do you run a command in normally?[y/N]' if getchar() =~? 'y' execute a:cmd endif return endif let mes = Redir('let time = reltime()', a:cmd, \ 'let s:result = reltime(time)') let result = a:cmd . ': ' . reltimestr(s:result) unlet! s:result echo mes if a:log echomsg result else echo result endif endfunction command! -nargs=1 -complete=command -bang Time call s:time(, 0) " == vimrc for local. == {{{1 " Load a setting for machine local. if filereadable(expand(':h') . '/local.vim') source :h/local.vim endif " Load settings for each location. augroup vimrc-local autocmd! autocmd BufNewFile,BufReadPost * call s:vimrc_local(expand(':p:h'), \ ['.local.vimrc', 'vimrc_local.vim']) autocmd FileType * call s:vimrc_local(expand(':p:h'), \ '.local.' . expand('') . '.vimrc') augroup END function! s:vimrc_local(loc, files) let targets = [] for f in type(a:files) == type([]) ? a:files : [a:files] call extend(targets, findfile(f, escape(a:loc, ' ') . ';', -1)) endfor for i in reverse(filter(targets, 'filereadable(v:val)')) source `=i` endfor endfunction if g:loaded_vimrc == 0 call s:vimrc_local(getcwd(), '.init.vimrc') endif set secure let g:loaded_vimrc += 1 " vim: foldmethod=marker