Create a gist now

Instantly share code, notes, and snippets.

thinca's vimrc for reading-vimrc #10 (2012/09/08)
" == 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}
" == Initial process. == {{{1
" Startup time.
if has('vim_starting') && has('reltime')
let g:startuptime = reltime()
augroup vimrc-startuptime
autocmd! VimEnter * let g:startuptime = reltime(g:startuptime) | redraw
\ | echomsg 'startuptime: ' . reltimestr(g:startuptime)
augroup END
endif
" runtimepath.
set runtimepath&
" filetype plugin indent on
" Even Windows uses "$HOME/.vim".
let &runtimepath = substitute(&runtimepath,
\ escape($HOME, '\') . '/vimfiles', escape($HOME, '\') . '/.vim', 'g')
" neobundle.vim
source <sfile>:h/bundle.vim
let g:rtputil#ignore_pattern = '^_'
call rtputil#new()
\.remove({'path': rtputil#userdir()}).append(rtputil#userdir(), 0)
\.unify(':p:~').apply()
" localrc.vim
if has('vim_starting')
call localrc#load('.init.vimrc', getcwd())
endif
" singleton.vim
call singleton#enable()
" vital.vim
let g:V = vital#of('vital').load(
\ ['Math'],
\ ['DateTime'],
\ ['System.Filepath'],
\ ['Data.List'],
\ ['Data.String'])
" == Utilities for vimrc. == {{{1
function! s:SID()
return matchstr(expand('<sfile>'), '<SNR>\zs\d\+\ze_SID$')
endfunction
function! s:SIDP()
return '<SNR>' . s:SID() . '_'
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' : "\<C-v>" }[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:mkdir(file, ...)
let f = a:0 ? fnamemodify(a:file, a:1) : a:file
if !isdirectory(f)
call mkdir(f, 'p')
endif
endfunction
function! s:has_plugin(name)
return globpath(&runtimepath, 'plugin/' . a:name . '.vim') !=# ''
\ || globpath(&runtimepath, 'autoload/' . a:name . '.vim') !=# ''
endfunction
" == Encoding settings. == {{{1
" Use utf-8.
if &encoding !=? 'utf-8'
let &termencoding = &encoding
set encoding=utf-8
endif
" Must after set of 'encoding'.
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 "IdeographicSpace".
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 hl in ['TabLine', 'TabLineSel']
let id = synIDtrans(hlID(hl))
let bg = synIDattr(id, 'bg', env)
let bg = bg =~# '^#\?\w\+$' ? env . 'bg=' . bg : ''
let attrs = filter(['bold', 'italic', 'reverse', 'inverse',
\ 'standout', 'underline', 'undercurl'],
\ 'synIDattr(id, v:val, env)')
let attr = empty(attrs) ? '' : env . '=' . join(attrs, ',')
execute 'highlight' hl . 'Number' env . 'fg=Red' bg attr
endfor
endfunction
" colorscheme.
set background=dark
if !g:V.is_windows() || has('gui_running')
" ['candycode', 'wuye', 'freya', 'leo']
colorscheme candycode
else "CUI win32
" ['oceandeep']
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:<
" 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& shortmess+=I
if has('kaoriya') && g:V.is_windows() && has('gui_running')
set ambiwidth=auto
else
set ambiwidth=double
endif
set helplang=ja,en
" 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)
if bufname =~# '^[[:alnum:].+-]\+:\\\\'
let bufname = substitute(bufname, '\\', '/', 'g')
endif
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' || buftype ==# 'acwrite'
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! StatusLineExtra()
let extra = ''
for scope in ['w:', 'b:', 't:', 'g:']
if exists(scope . 'statusline_extra')
let extra .= {scope . 'statusline_extra'}
endif
endfor
return extra
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():''}"
if exists('*eskk#statusline')
let line .= '%{eskk#statusline()}'
endif
if exists('*SyntasticStatuslineFlag')
let line .= '%{SyntasticStatuslineFlag()}'
endif
if s:check_flag('statusline_highlight')
let line .= '[' . join(map(synstack(line('.'), col('.')),
\ 'synIDattr(v:val, "name")'.
\ '."(".synIDattr(synIDtrans(v:val), "name").")"'), ',') . ']'
endif
let line .= '%{StatusLineExtra()}'
" let line .= StatusLineExtra()
if has('multi_statusline') && 2 <= &statuslineheight
let line .= '%@' " Separation point.
else
let line .= '%=' " Separation point.
endif
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
let line .= $LANG =~# '^ja' ? ' %l/%L行 %3v桁'
\ : ' %l/%LL %2vC' " Line and column.
let line .= ' %3p%%' " Percentage through file in lines.
return line
endfunction
function! s:tabpage_label(n)
let n = a:n
let bufnrs = tabpagebuflist(n)
let curbufnr = bufnrs[tabpagewinnr(n) - 1] " first window, first appears
let hi = n == tabpagenr() ? 'TabLineSel' : 'TabLine'
let label = ''
if getbufvar(curbufnr, '&filetype') =~# '^lingr-'
" lingr-vim
let unread = lingr#unread_count()
let status = lingr#status()
let label .= '%#' . hi . '#'
let label .= 'lingr - ' . status
if unread != 0
let label .= '(' . unread . ')'
endif
else
let no = len(bufnrs)
if no == 1
let no = ''
endif
let mod = len(filter(bufnrs, 'getbufvar(v:val, "&modified")')) ? '+' : ''
let sp = (no . mod) ==# '' ? '' : ' '
let fname = GetBufname(curbufnr, 1)
if no !=# ''
let label .= '%#' . hi . 'Number#' . no
endif
let label .= '%#' . hi . '#'
let label .= mod . sp . fname
endif
return '%' . a:n . 'T' . label . '%T%#TabLineFill#'
endfunction
function! MakeTabLine()
let titles = map(range(1, tabpagenr('$')), 's:tabpage_label(v:val)')
let sep = ' | '
let tabs = join(titles, sep) . sep . '%#TabLineFill#%T'
let info = '%#TabLine#'
if exists('t:tabline_extra')
let info .= t:tabline_extra . sep
endif
" if s:has_plugin('cfi')
" let info .= cfi#format('%s()' . sep, '')
" endif
if exists('*Uptime')
let info .= Uptime(2) . sep
endif
if s:has_plugin('reanimate') && reanimate#is_saved()
let info .= reanimate#last_point() . sep
endif
let info .= fnamemodify(getcwd(), ":~") . ' '
return tabs . '%=' . info
endfunction
" == Behavior settings. == {{{1
" Enable FileType
filetype off " To reapply 'ftdetect/*.vim'.
filetype plugin indent on
" Search.
set ignorecase smartcase incsearch hlsearch 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 copyindent preserveindent
set cinoptions& cinoptions+=b1,l1,g0,N-s
set cinkeys& cinkeys+=0=break
" 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 nostartofline
set sidescroll=1 sidescrolloff=1
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 wildignorecase
" 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('persistent_undo')
set undodir=~/.backup
augroup vimrc-undofile
autocmd!
autocmd BufReadPre ~/* setlocal undofile
augroup END
endif
set backupcopy=yes
call s:mkdir(expand('~/.backup'))
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;
" view
set viewdir=~/.vim/view viewoptions-=options viewoptions+=slash,unix
augroup vimrc-view
autocmd!
autocmd BufLeave * if expand('%') !=# '' && &buftype ==# ''
\ | mkview
\ | endif
autocmd BufReadPost * if !exists('b:view_loaded') &&
\ expand('%') !=# '' && &buftype ==# ''
\ | silent! loadview
\ | let b:view_loaded = 1
\ | endif
autocmd VimLeave * call map(split(glob(&viewdir . '/*'), "\n"),
\ 'delete(v:val)')
augroup END
" 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 get(b:, 'cursorline_disable', 0)
return
endif
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()
if &l:buftype !=# '' && &l:buftype !=# 'help' ||
\ 0 <= index(['unite', 'vimfiler'], &l:filetype)
unlet! b:lcd
return
endif
if exists('b:lcd') &&
\ (b:lcd ==# '' || getcwd() =~# '^\V' . escape(b:lcd, '\') . '\$')
return
endif
let path = s:lcd_path()
if isdirectory(path)
lcd `=path`
let b:lcd = getcwd()
endif
endfunction
function! s:lcd_path()
let path = ''
let simple = expand('%:p:h')
if &l:buftype ==# 'help'
return simple
endif
let tf = tagfiles()
if !empty(tf)
let tagdir = fnamemodify(tf[0], ':p:h')
if tagdir !=# '' && simple[ : len(tagdir) - 1] ==# tagdir
return tagdir
endif
endif
let base = substitute(expand('%:p'), '\\', '/', 'g')
for dir in ['src', 'include']
let pat = '/' . dir . '/'
if base =~# pat
let path = base[: strridx(base, pat) + len(dir)]
endif
endfor
if path !=# ''
return path
endif
let base = simple
let dirs = ['.svn', '.git', '.bzr', '.hg']
if &l:filetype =~# '^\%(vim\|help\)$'
call add(dirs, 'doc')
endif
for d in dirs
let d = finddir(d, escape(base, ' ?*[]();') . ';')
if d !=# ''
let p = fnamemodify(d, ':p:h:h')
if strlen(path) < strlen(p)
let path = p
endif
endif
endfor
if path !=# ''
return path
endif
return simple
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 * <buffer>
function! s:scratch_buffer()
if exists('b:scratch_buffer') || bufname('%') !=# '' || &l:buftype !=# ''
return
endif
let b:scratch_buffer = 1
call openbuf#add('scratch', bufnr('%'))
setlocal buftype=nofile nobuflisted noswapfile bufhidden=hide
augroup vimrc-scratch
autocmd! * <buffer>
autocmd BufWriteCmd <buffer> call s:scratch_on_BufWriteCmd()
augroup END
endfunction
function! s:scratch_on_BufWriteCmd()
silent! setl buftype< buflisted< swapfile< bufhidden< nomodified
autocmd! vimrc-scratch * <buffer>
if bufname('%') ==# '' && exists('b:scratch_buffer')
execute 'saveas' . (v:cmdbang ? '!' : '') ' <afile>'
filetype detect
endif
call openbuf#remove('scratch', bufnr('%'))
unlet! b:scratch_buffer
endfunction
augroup END
augroup vimrc-auto-mkdir
autocmd!
autocmd BufWritePre * call s:auto_mkdir(expand('<afile>:p:h'), v:cmdbang)
function! s:auto_mkdir(dir, force)
let mes = '"%s" does not exist. Create? [y/N]'
if !isdirectory(a:dir) && (a:force ||
\ input(printf(mes, a:dir)) =~? '^y\%[es]$')
call s:mkdir(a:dir)
endif
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 g:V.system('chmod a+x ' . shellescape(file))
endif
endfunction
endif
if has('vim_starting') && &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:filetype . '.dict'))
\ | let &l:dict = '~/.vim/dict/' . &l:filetype . '.dict'
\ | endif
autocmd FileType
\ * if &l:buftype !=# 'help' && &l:kp ==# '' && mapcheck('K', 'n') ==# ''
\ | silent! execute 'nnoremap <buffer> <unique> K <C-w>}'
\ | endif
" Auto open/close Quickfix/location window.
autocmd QuickFixCmdPost [^l]* call setqflist(g:V.uniq(getqflist()), 'r')
autocmd QuickFixCmdPost [^l]* cwindow | redraw!
autocmd QuickFixCmdPost l* lwindow | redraw!
" Update filetype.
autocmd BufWritePost
\ * if &l:filetype ==# '' || exists('b:ftdetect')
\ | unlet! b:ftdetect
\ | filetype detect
\ | endif
" Check timestamp more for 'autoread'.
autocmd WinEnter * checktime
autocmd BufReadPost bzr_log.* let &l:fileencoding = &termencoding
" Edit something to avoid the confirmation when aborting.
autocmd BufReadPost bzr_log.* if empty(getline(1))
\ | 1 delete _ | silent write
\ | endif
autocmd InsertEnter * if &l:foldmethod ==# 'expr'
\ | let b:foldinfo = [&l:foldmethod, &l:foldexpr]
\ | setlocal foldmethod=manual foldexpr=0
\ | endif
autocmd InsertLeave * if exists('b:foldinfo')
\ | let [&l:foldmethod, &l:foldexpr] = b:foldinfo
\ | endif
autocmd InsertLeave * if &paste | set nopaste | endif
augroup END
" == Key mappings & command definition. == {{{1
" It is likely to be changed by $VIM/vimrc.
if has('vim_starting')
mapclear
mapclear!
endif
" jj to escape
inoremap <expr> j getline('.')[col('.') - 2] ==# 'j' ? "\<BS>\<ESC>" : 'j'
" Physical moving.
noremap j gj
noremap k gk
noremap gj j
noremap gk k
nnoremap <expr> 0 &l:wrap ? 'g0' : '0'
nnoremap <expr> g0 &l:wrap ? '0' : 'g0'
nnoremap <expr> ^ &l:wrap ? 'g^' : '^'
nnoremap <expr> g^ &l:wrap ? '^' : 'g^'
nnoremap <expr> $ &l:wrap ? 'g$' : '$'
nnoremap <expr> g$ &l:wrap ? '$' : 'g$'
" 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 / /\v
nnoremap ? ?\v
cnoremap <expr> s/ getcmdline() =~# '^\A*$' ? 's/\v' : 's/'
cnoremap <expr> g/ getcmdline() =~# '^\A*$' ? 'g/\v' : 'g/'
cnoremap <expr> v/ getcmdline() =~# '^\A*$' ? 'v/\v' : 'v/'
cnoremap s// s//
cnoremap g// g//
cnoremap v// v//
" Control search highlight.
noremap <silent> <Plug>(vimrc-searchafter) Nzz
map * <Plug>(visualstar-*)<Plug>(vimrc-searchafter)
map # <Plug>(visualstar-#)<Plug>(vimrc-searchafter)
map g* <Plug>(visualstar-g*)<Plug>(vimrc-searchafter)
map g# <Plug>(visualstar-g#)<Plug>(vimrc-searchafter)
nnoremap <silent> <ESC><ESC> :<C-u>nohlsearch<CR>
" Search selected area.
vnoremap <silent> z/ <ESC>/\v%V
vnoremap <silent> z? <ESC>?\v%V
" Switch the tab page.
nnoremap <C-n> gt
nnoremap <C-p> gT
" Scroll + Move
nnoremap <C-j> <C-e>gj
nnoremap <C-k> <C-y>gk
" Swap ; and :
noremap ; :
noremap : ;
" Speedy :h
nnoremap <expr> <C-h>
\ printf(":\<C-u>%s ", (78 * 2 <= winwidth(0) ? 'vert ' : '') . 'h')
" Quick completion.
inoremap <C-]> <C-x><C-]>
" Create an undo point before <C-u> and <C-w>.
inoremap <expr> <C-u> (pumvisible() ? "\<C-e>" : '') . "\<C-g>u\<C-u>"
inoremap <expr> <C-w> "\<C-g>u\<C-w>"
inoremap <expr> <CR> pumvisible() ? "\<C-y>\<CR>" : "\<CR>"
inoremap <C-l> <C-o><C-l>
" To uppercase/lowercase the word immediately before.
inoremap <C-g><C-u> <ESC>gUvbgi
inoremap <C-g><C-l> <ESC>guvbgi
" Select the last changed.
nnoremap <expr> gc '`[' . getregtype()[0] . '`]'
onoremap <silent> gc :normal gc<CR>
onoremap <silent> gv :normal gv<CR>
onoremap q /["',.{}()[\]<>]<CR>
" Prevent a typing error.
nmap <C-@> <ESC>
imap <C-@> <ESC>
cmap <C-@> <C-c>
nnoremap <Left> <C-w>h
nnoremap <Down> <C-w>j
nnoremap <Up> <C-w>k
nnoremap <Right> <C-w>l
nnoremap <M-h> <C-w>h
nnoremap <M-j> <C-w>j
nnoremap <M-k> <C-w>k
nnoremap <M-l> <C-w>l
nnoremap <M-H> <C-w>H
nnoremap <M-J> <C-w>J
nnoremap <M-K> <C-w>K
nnoremap <M-L> <C-w>L
" Don't use commands.
noremap ZZ <Nop>
noremap ZQ <Nop>
noremap <C-z> <Nop>
" Mappings for command-line mode.
cnoremap <C-a> <C-b>
cnoremap <C-f> <Right>
cnoremap <C-b> <Left>
" Move the cursor not complete list.
cnoremap <Left> <Space><BS><Left>
cnoremap <Right> <Space><BS><Right>
cnoremap <C-p> <Up>
cnoremap <C-n> <Down>
cnoremap <Up> <C-p>
cnoremap <Down> <C-n>
nnoremap <Space> <Nop>
" Quick save and quit.
nnoremap <silent> <Space>w :<C-u>update<CR>
nnoremap <silent> <Space>W :<C-u>update!<CR>
nnoremap <silent> <Space>q :<C-u>quit<CR>
nnoremap <silent> <Space>Q :<C-u>quit!<CR>
" Change encodings and formats.
nnoremap <Space>e <Nop>
nnoremap <silent> <Space>es :<C-u>setlocal fenc=cp932<CR>
nnoremap <silent> <Space>ee :<C-u>setlocal fenc=euc-jp<CR>
nnoremap <silent> <Space>eu :<C-u>setlocal fenc=utf-8<CR>
nnoremap <silent> <Space>ej :<C-u>setlocal fenc=iso-2022-jp<CR>
nnoremap <silent> <Space>ed :<C-u>setlocal ff=dos<CR>
nnoremap <silent> <Space>ex :<C-u>setlocal ff=unix<CR>
" Change statusline.
nnoremap <Space>s <Nop>
for [s:key, s:var] in [['n', 'bufnr'], ['c', 'char'],
\ ['s', 'filesize'], ['h', 'highlight']]
for [s:prefix, s:scope] in [['', 'g'], ['b', 'b'], ['w', 'w']]
execute printf('nnoremap <silent> <Space>s%s%s '
\ . ':<C-u>call <SID>toggle_flag("%s:statusline_%s")<CR>',
\ s:prefix, s:key, s:scope, s:var)
endfor
endfor
unlet! s:key s:var s:prefix s:scope
" Quick toggle options.
nnoremap <Space>o <Nop>
nnoremap <silent> <Space>oe :<C-u>setlocal expandtab! expandtab?<CR>
nnoremap <silent> <Space>of :<C-u>let &l:foldcolumn=1-&l:foldcolumn<CR>
\:setlocal foldcolumn?<CR>
nnoremap <silent> <Space>on :<C-u>setlocal number! number?<CR>
nnoremap <silent> <Space>ol :<C-u>setlocal list! list?<CR>
nnoremap <silent> <Space>ow :<C-u>setlocal wrap! wrap?<CR>
nnoremap <silent> <Space>op :<C-u>set paste! paste?<CR>
nnoremap <Space>t <Nop>
nnoremap <silent> <Space>tn :<C-u>tabnew<CR>
nnoremap <silent> <Space>tc :<C-u>tabclose<CR>
function! s:grep_same_ext(pat)
let exts = get({
\ 'c': ['c', 'h'],
\ 'cpp': ['cpp', 'h', 'hpp'],
\ }, &l:filetype, [expand('%:e')])
let files = join(map(exts, '"**/*." . v:val'), ' ')
silent! execute 'vimgrep /' . a:pat . '/j ' . files
endfunction
nnoremap <silent> <Space>grep :<C-u>call <SID>grep_same_ext('\C' . @/)<CR>
nnoremap <silent> <Space>Grep :<C-u>call <SID>grep_same_ext('\c' . @/)<CR>
nnoremap <silent> <Space><C-g> :<C-u>vimgrep /<C-r>//gj %<CR>
" <Space><C-n>, <Space><C-p>: Move window position {{{
nnoremap <silent> <Space><C-n> :<C-u>call <SID>swap_window(v:count1)<CR>
nnoremap <silent> <Space><C-p> :<C-u>call <SID>swap_window(-v:count1)<CR>
function! s:swap_window(n)
let curbuf = bufnr('%')
let target = g:V.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=dos
cnoreabbrev ++m ++ff=mac
" This is for editing list separated by an arbitrary character such as $PATH.
nnoremap <silent> <Space>; :<C-u>call <SID>toggle_separate()<CR>
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
%s/\n/\=c
normal! m`$x``
else
execute '%s/\V' . escape(c, '\/') . '/\r/g'
silent global/^$/delete _
endif
endfunction
" Generate help tags.
command! -bar -bang Helptags call rtputil#helptags(<bang>1)
" 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 g:V.system('svn info')
if !g:V.get_last_status()
let source = '!svn cat #' . bufnr
let file = '[svn HEAD]'
endif
endif
if !exists('source')
silent! call g:V.system('bzr info')
if !g:V.get_last_status()
let source = '!bzr cat #' . bufnr
let file = '[bzr tip]'
endif
endif
if !exists('source')
silent! let git_dir = g:V.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 buftype=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 <silent> <Space>diff :call <SID>diff_original()<CR>
" }}}
" Translation interface. {{{
" trans.pl is a translation filter via web translation.
let g:trans = substitute(expand('~/.vim/bin/trans.pl'), '\\', '/', 'g')
let g:trans_vimproc = 1
if executable('perl') && filereadable(g:trans)
nnoremap <silent> <Space>tt :<C-u>set operatorfunc=<SID>echo_translate<CR>g@
nnoremap <silent> <Space>ts :<C-u>set operatorfunc=<SID>swap_translate<CR>g@
vnoremap <silent> <Space>tt :<C-u>echo <SID>translate(visualmode(), 1)<CR>
vnoremap <silent> <Space>ts :<C-u>call <SID>swap_translate(visualmode(), 1)<CR>
onoremap <silent> <Space>tt g@
onoremap <silent> <Space>ts g@
command! -nargs=+ Trans echo s:translate(<q-args>, 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 == 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 = s:has_plugin('vimproc#system') && g:trans_vimproc
\ ? vimproc#system(['perl', g:trans], s)
\ : system('perl ' . shellescape(g:trans), s)
echo ''
redraw
return substitute(s, '^\_s*\|\_s*$', '', 'g')
endfunction
endif
" }}}
" -- Commands.
command! -nargs=1 -bang -bar -complete=file Rename
\ call s:move(<q-args>, <q-bang>, expand('%:h'))
command! -nargs=1 -bang -bar -complete=file Move
\ call s:move(<q-args>, <q-bang>, getcwd())
function! s:move(file, bang, base)
let pwd = getcwd()
cd `=a:base`
try
let from = expand('%:p')
let to = simplify(expand(a:file))
let bang = a:bang
if isdirectory(to)
let to .= '/' . fnamemodify(from, ':t')
endif
if filereadable(to) && !bang
echo '"' . to . '" is exists. Overwrite? [yN]'
if nr2char(getchar()) !=? 'y'
echo 'Cancelled.'
return
endif
let bang = '!'
endif
let dir = fnamemodify(to, ':h')
call s:mkdir(dir)
execute 'saveas' . bang '`=to`'
call delete(from)
finally
cd `=pwd`
endtry
endfunction
command! -nargs=? -bang -bar -complete=file Delete
\ call s:delete_with_confirm(<q-args>, <bang>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
" unique lines without sort.
command! -bar -range=% Unique <line1>,<line2>call s:unique_lines()
function! s:unique_lines() range
let lines = g:V.uniq(getline(a:firstline, a:lastline))
silent execute a:firstline . ',' . a:lastline . 'delete _'
silent execute (a:firstline - 1) . 'put =lines'
endfunction
" FIXME: :diffoff make 'foldmethod' to "namual" (not restored).
command! -bar Diff if &diff | execute 'windo diffoff' | else
\ | execute 'windo diffthis' | endif
if executable('ctags')
" Execute ctags command. And echo for error.
command! -nargs=? -complete=file -bar CtagsR call CtagsR([<f-args>])
function! CtagsR(args)
let args = a:args
let dir = '.'
if !empty(args) && isdirectory(args[0])
let dir = args[0]
call remove(args, 0)
endif
if !empty(args) && args[0] !~# '^-'
echoerr 'Invalid options: ' . join(args)
return
endif
let tagfile = s:tagfile()
if tagfile !=# ''
let dir = fnamemodify(tagfile, ':h')
let args += ['-f', tagfile]
endif
if g:V.is_windows()
let enc = get({
\ 'utf-8': 'utf8',
\ 'cp932': 'sjis',
\ 'euc-jp': 'euc',
\ }, &l:fileencoding ==# '' ? &encoding : &l:fileencoding, '')
if enc !=# ''
let args += ['--jcode=' . enc]
endif
endif
let lang = get({
\ 'cpp': 'C++',
\ 'c': 'C++',
\ 'java': 'Java',
\ }, &l:filetype, '')
if lang !=# ''
let args += ['--languages=' . lang]
endif
call map(add(args, dir), 'shellescape(v:val)')
let cmd = printf('ctags -R --tag-relative=yes %s', join(args))
if g:V.is_windows()
let cmd = 'start /b ' . cmd
else
let cmd .= ' &'
endif
silent execute '!' . cmd
endfunction
function! s:tagfile()
let files = tagfiles()
return empty(files) ? '' : files[0]
endfunction
nnoremap <silent> <Space>tr :<C-u>CtagsR<CR>
endif
command! -bar Tasks execute 'vimgrep /\C\v<(TODO|FIXME|XXX)>/ **/*.'
\ . expand('%:e')
" Show 'runtimepath'.
command! -bar RTP echo substitute(&runtimepath, ',', "\n", 'g')
" :HighlightWith {filetype} ['a 'b] FIXME: Doesn't work in some case.
command! -nargs=+ -range=% HighlightWith
\ <line1>,<line2>call s:highlight_with(<q-args>)
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
if exists('b:current_syntax')
let syntax = b:current_syntax
unlet b:current_syntax
endif
let save_isk= &l:isk " for scheme.
let hlname = 'highlightWith' . substitute(ft, '^.', '\u\0', '')
if c != 0
let hlname .= '_' . c
endif
execute printf('syntax include @%s syntax/%s.vim', hlname, ft)
let &l:isk= save_isk
execute printf('syntax region %s start=/\%%%dl/ end=/\%%%dl$/ '
\ . 'contains=@%s containedin=ALL',
\ hlname, a:firstline, a:lastline, hlname)
let b:highlight_count = c + 1
if exists('syntax')
let b:current_syntax = syntax
endif
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(Redir(a:cmd), a:pat, a:0 && a:1)
endfunction
function! s:cgrep(args, v)
let list = matchlist(a:args, '^\v(/.{-}\\@<!/|\S+)\s+(.+)$')
if empty(list)
call s:echomsg('Cgrep: Invalid arguments: ' . a:args)
return
endif
let pat = list[1] =~# '^/.*/$' ? list[1][1 : -2] : list[1]
echo Cgrep(list[2], pat, a:v)
endfunction
command! -nargs=+ -bang Cgrep call s:cgrep(<q-args>, <bang>0)
command! -nargs=+ Vars PP filter(copy(g:), 'v:key =~# "^<args>"')
" experimental
command! -nargs=+ -bang -bar -complete=file Opener
\ if <q-args> =~# '`=.*`\s*$'
\ | execute s:opener(<q-args>, eval(matchstr(<q-args>, '`=\zs.*\ze`\s*$')))
\ | elseif <q-args> =~# '`.*`\s*$'
\ | execute s:opener(<q-args>)
\ | else
\ | execute s:opener(<q-args>)
\ | endif
function! s:opener(cmdline, ...)
if a:0
let file = a:1
else
let arg = matchstr(a:cmdline, '\%(\\.\|\S\)\+$')
if arg =~# '^`.*`$'
let arg = system(file[1 : -2])
endif
let file = resolve(fnamemodify(glob(arg), ':p'))
endif
let opened = s:bufopened(file)
let opt = a:cmdline[: -len(arg) - 1]
if !empty(opened)
execute 'tabnext' opened[0]
execute opened[1] 'wincmd w'
if opt =~# '\S'
silent execute 'edit' opt
endif
else
return 'tabnew ' . a:cmdline
endif
return ''
endfunction
function! s:bufopened(file)
let f = fnamemodify(a:file, ':p')
for tabnr in range(1, tabpagenr('$'))
let winnr = 1
for nbuf in tabpagebuflist(tabnr)
if f ==# fnamemodify(bufname(nbuf), ':p')
return [tabnr, winnr]
endif
let winnr += 1
endfor
endfor
return []
endfunction
" == Setting according to environments. == {{{1
" cygwin (UTF-8) {{{2
if has('win32unix')
set termencoding=
endif
" Use a mouse in terminal. {{{2
set mouse=a
" For GNU Screen and tmux. {{{2
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 = "\<ESC>"
silent! execute '!echo -n "' . esc . 'k' . escape(a:name, '%#!')
\ . esc . '\\"'
redraw!
endfunction
command! -nargs=? WindowName call s:set_window_name(<q-args>)
function! s:auto_window_name()
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
if $TMUX !=# ''
function! s:vim_plugin_test()
let file = expand('%:p')
let plugin = matchstr(file, s:vim_plugin_dir . '/\zs[^/]\+')
if plugin ==# ''
call g:V.print_error('Not in vim plugin.')
return
endif
call g:V.system(printf('tmux new-window "zsh -i -c \"cd %s/%s; vim\""',
\ s:vim_plugin_dir, plugin))
endfunction
endif
endif
" GUI {{{2
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') && g:V.is_windows()
set guioptions+=C " Remove caption (title) bar. Support Windows only.
endif
if g:V.is_windows()
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
" Saves 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 [x, y] = $XMING ? [0, 0] : [getwinposx(), getwinposy()]
let options = [
\ 'set columns=' . &columns,
\ 'set lines=' . &lines,
\ 'winpos ' . x . ' ' . y,
\ 'set guioptions=' . &guioptions,
\ 'set guifont=' . escape(&guifont, '\ '),
\ ]
call writefile(options, $MYGVIMRC)
endfunction
augroup END
function! s:vim_plugin_test()
let file = expand('%:p')
let plugin = matchstr(file, s:vim_plugin_dir . '/\zs[^/]\+')
if plugin ==# ''
call g:V.print_error('Not in vim plugin.')
return
endif
call vimproc#system_bg(printf('gvim --cmd "cd %s/%s"',
\ s:vim_plugin_dir, plugin))
endfunction
" Does not use IM by default.
set iminsert=0 imsearch=0
else
" CUI {{{2
if executable('winclip')
nnoremap <silent> "+y :<C-u>set operatorfunc=<SID>winclip<CR>g@
nnoremap <silent> "*y :<C-u>set operatorfunc=<SID>winclip<CR>g@
vnoremap <silent> "+y :<C-u>call <SID>winclip()<CR>
vnoremap <silent> "*y :<C-u>call <SID>winclip()<CR>
vnoremap <silent> "+Y :w !winclip<CR><CR>
vnoremap <silent> "*Y :w !winclip<CR><CR>
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')
" Use meta keys in console.
function! s:use_meta_keys()
for i in map(
\ range(char2nr('a'), char2nr('z'))
\ + range(char2nr('A'), char2nr('Z'))
\ + range(char2nr('0'), char2nr('9'))
\ , 'nr2char(v:val)')
" <ESC>O do not map because used by arrow keys.
if i !~# '[O]'
execute 'nmap <ESC>' . i '<M-' . i . '>'
endif
endfor
endfunction
call s:use_meta_keys()
map <NUL> <C-Space>
map! <NUL> <C-Space>
let &t_ti .= "\e[?2004h"
let &t_te .= "\e[?2004l"
function! s:XTermPaste(on)
let &paste = a:on
return ''
endfunction
inoremap <expr> <Esc>[200~ <SID>XTermPaste(1)
inoremap <expr> <Esc>[201~ <SID>XTermPaste(0)
command! Suicide call system('kill -KILL ' . getpid())
endif
endif
" :VimPluginTest {{{2
if exists('*s:vim_plugin_test')
let s:vim_plugin_dir = expand('~/work/vim-plugins')
command! PluginTest call s:vim_plugin_test()
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_vintage_case_default_indent = 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'
" bash
let g:is_bash = 1
" 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
let g:vimclojure#SetupKeyMap = 0
" bzr
let g:bzr_highlight_diff = 1
" doxygen
let g:doxygen_end_punctuation = '[.。]'
" rst (riv)
let g:riv_global_leader = '<LocalLeader>t'
" == Plugin settings. == {{{1
let s:user_rtp = expand('~/.vim')
let s:custom_rtp = expand('~/.vim/custom')
let s:plugin_info = s:user_rtp . '/info'
let s:temp_file_pat = join([
\ '/svn-commit\%(\.\d\+\)\?\.tmp$',
\ '.git/COMMIT_EDITMSG$',
\ '/bzr_log\..\{6}$',
\ ], '\|')
if $TMP !=# ''
let s:temp_file_pat .=
\ '\|^' . substitute(expand($TMP), '\', '[/\\\\]', 'g')
elseif has('unix')
let s:temp_file_pat .= '\|^/tmp/\|^/var/tmp/'
endif
" netrw.vim {{{2
let g:netrw_home = s:plugin_info . '/netrw'
" 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_scrollback_limit = 100000
let g:vimshell_editor_command = $EDITOR
let g:vimshell_prompt = '% '
let g:vimshell_user_prompt = 'fnamemodify(getcwd(), ":~")'
" let g:vimshell_user_prompt = 'fnamemodify(getcwd(), ":~") . " " .' .
" \ 'vimshell#vcs#info("(%s)-[%b]", "(%s)-[%b|%a]")'
let g:vimshell_ignore_case = 1
let g:vimshell_smart_case = 1
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 <Leader>sh <Plug>(vimshell_split_switch)
nmap <Leader>sH <Plug>(vimshell_split_create)
augroup vimrc-plugin-vimshell
autocmd!
autocmd FileType int-* call s:init_vimshell_int()
autocmd FileType term-* call s:init_vimshell_term()
augroup END
function! s:vimshell_complete_history()
if exists('b:interactive') && has_key(b:interactive, 'command_history')
call complete(len(vimshell#get_prompt()) + 1, b:interactive.command_history)
endif
return ''
endfunction
function! s:init_vimshell_int()
silent! iunmap <buffer> <C-l>
inoremap <silent> <buffer> <SID>(vimshell_complete_history)
\ <C-r>=<SID>vimshell_complete_history()<CR><C-p>
imap <buffer> <silent> <C-q> <SID>(vimshell_complete_history)
inoremap <buffer> <expr>
\ <C-k> unite#sources#vimshell_history#start_complete(1)
nnoremap <buffer> <expr>
\ <C-k> unite#sources#vimshell_history#start_complete(0)
nnoremap <buffer> <C-n> gt
nnoremap <buffer> <C-p> gT
endfunction
function! s:init_vimshell_term()
imap <buffer> <ESC> <Plug>(vimshell_term_send_escape)
inoremap <buffer> <ESC><ESC> <ESC>
endfunction
" vimfiler.vim {{{2
let g:vimfiler_as_default_explorer = 1
let g:vimfiler_data_directory = s:plugin_info . '/vimfiler'
let g:vimfiler_split_rule = 'botright'
let g:vimfiler_execute_file_list = {}
for s:i in split(
\ 'asm,bash,c,cc,cf,cfg,cgi,class,clj,cnf,conf,cpp,cs,css,csv,diff,dtd,el,' .
\ 'erb,erl,go,groovy,h,hpp,hs,ini,io,jam,java,jax,js,json,jsp,lhs,log,lua,' .
\ 'map,mf,mkd,ml,ng,note,objectmacro,patch,php,pl,pm,po,pro,properties,ps1,' .
\ 'py,rb,reg,sablecc,scala,scm,sh,sql,ss,tex,txt,vba,viki,vim,vimgolf,xml,' .
\ 'xsl,xul,y,yaml,yml,zsh', ',')
let g:vimfiler_execute_file_list[s:i] = 'vim'
endfor
unlet s:i
nnoremap <silent> <Leader>sf :<C-u>VimFilerSplit<CR>
nnoremap <silent> <Leader>sF :<C-u>VimFilerBufferDir -split<CR>
" neocomplcache.vim {{{2
let g:neocomplcache_enable_at_startup = 1
let g:neocomplcache_enable_prefetch = 1
let g:neocomplcache_enable_camel_case_completion = 1
let g:neocomplcache_temporary_dir = s:plugin_info . '/neocomplcache'
let g:neocomplcache_snippets_dir = s:custom_rtp . '/snippets'
let g:neocomplcache_disable_caching_file_path_pattern =
\ s:temp_file_pat . '\m\|\[.*\]$'
let g:neocomplcache_max_list = 10000
let g:neocomplcache_max_keyword_width = 100
call g:V.set_default('g:neocomplcache_keyword_patterns',
\ {'javascript' : '\v\k+'})
if getftype('/usr/lib/llvm/libclang.so') ==# 'file' && 0
let g:neocomplcache_clang_use_library = 1
let g:neocomplcache_clang_library_path = '/usr/lib/llvm'
let g:neocomplcache_clang_debug = 1
else
call g:V.set_default('g:neocomplcache_plugin_disable',
\ {'clang_complete' : 1})
endif
let g:neocomplcache_plugin_disable.member_complete = 1
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,
\ }
function! s:tab_wrapper()
if neocomplcache#sources#snippets_complete#expandable()
return "\<Plug>(neocomplcache_snippets_jump)"
elseif pumvisible()
return "\<C-y>"
elseif (!exists('b:smart_expandtab') || b:smart_expandtab) &&
\ !&l:expandtab && !search('^\s*\%#', 'nc')
return repeat(' ', &l:tabstop - (virtcol('.') - 1) % &l:tabstop)
endif
return "\<Tab>"
endfunction
inoremap <silent> <Plug>(adjust-indent) <ESC>==I
imap <silent> <expr> <Tab> <SID>tab_wrapper()
inoremap <expr> <C-f> neocomplcache#manual_filename_complete()
inoremap <expr> <C-y> pumvisible() ? neocomplcache#close_popup() : "\<C-y>"
inoremap <expr> <C-e> pumvisible() ? neocomplcache#cancel_popup() : "\<C-e>"
" 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 <buffer>
smap <silent> <Tab> <ESC>a<Plug>(neocomplcache_snippets_expand)
snoremap <C-h> _<C-h>
endfunction
" unite.vim {{{2
let g:unite_data_directory = s:plugin_info . '/unite'
let g:unite_enable_start_insert = 1
let g:unite_source_file_ignore_pattern = '/\.\%(svn\|/\)\?$\|/tags\%(-..\)\?$'
let g:unite_source_file_mru_limit = 1000
let g:unite_source_file_mru_ignore_pattern = s:temp_file_pat
let g:unite_source_history_yank_enable = 1
" let g:unite_source_session_enable_auto_save = 1
nnoremap <silent> <Leader>z :<C-u>Unite -buffer-name=file
\ file_mru file buffer<CR>
nnoremap <silent> <Leader>a <Nop>
nnoremap <silent> <Leader>ab :<C-u>Unite -buffer-name=file buffer<CR>
nnoremap <silent> <Leader>af :<C-u>Unite -buffer-name=file file file/new<CR>
nnoremap <silent> <Leader>aF :<C-u>UniteWithBufferDir -buffer-name=file file<CR>
nnoremap <silent> <Leader>a<C-f> :<C-u>UniteWithBufferDir -buffer-name=file file<CR>
nnoremap <silent> <Leader>am :<C-u>Unite -buffer-name=file file_mru<CR>
nnoremap <silent> <Leader>ar :<C-u>Unite -buffer-name=file file_rec<CR>
nnoremap <silent> <Leader>aR :<C-u>Unite -buffer-name=file file_rec:<C-r>=expand('%:p:h:gs?[ :]?\\\0?')<CR><CR>
nnoremap <silent> <Leader>a<Tab> :<C-u>Unite -vertical tab<CR>
nnoremap <silent> <Leader>ah :<C-u>Unite help<CR>
nnoremap <silent> <Leader>al :<C-u>Unite line<CR>
nnoremap <silent> <Leader>ao :<C-u>Unite -buffer-name=outline -vertical -no-start-insert -create outline<CR>
nnoremap <silent> <Leader>ap :<C-u>Unite tab<CR>
nnoremap <silent> <Leader>at :<C-u>Unite tag<CR>
nnoremap <silent> <Leader>aT :<C-u>Unite tag/file<CR>
nnoremap <silent> <Leader>a<C-t> :<C-u>Unite tag/file<CR>
nnoremap <silent> <Leader>a: :<C-u>Unite history/command<CR>
nnoremap <silent> <Leader>a; :<C-u>Unite history/command<CR>
nnoremap <silent> <Leader>a/ :<C-u>Unite history/search<CR>
nnoremap <silent> <Leader>aq :<C-u>Unite qf<CR>
nnoremap <silent> <Leader>ag :<C-u>Unite -no-quit grep:**<CR>
" nnoremap <silent> <Leader>as :<C-u>Unite session<CR>
nnoremap <silent> <C-]> :<C-u>Unite -immediately -no-start-insert tag:<C-r>=expand('<cword>')<CR><CR>
vnoremap <silent> <C-]> :<C-u>Unite -immediately -no-start-insert -input=<C-r>=escape(<SID>get_range(visualmode(), 'v'), '\ ')<CR> tag<CR>
nnoremap <silent> <C-w><C-]> :<C-u>Unite -immediately -no-start-insert -default-action=split tag:<C-r>=expand('<cword>')<CR><CR>
vnoremap <silent> <C-w><C-]> :<C-u>Unite -immediately -no-start-insert -input=<C-r>=escape(<SID>get_range(visualmode(), 'v'), '\ ')<CR> -default-action=split tag<CR>
call unite#set_substitute_pattern('file', '\$\w\+', '\=eval(submatch(0))', 200)
call unite#set_substitute_pattern('file', '[^~.]\zs/', '*/*', 20)
call unite#set_substitute_pattern('file', '\(^\|/\)\ze[^*;@\\/]', '\1*', 10)
call unite#set_substitute_pattern('file', '^@@', '\=getcwd()."/*"', 2)
call unite#set_substitute_pattern('file', '^@', '\=expand("#:p:h")."/*"', 1)
call unite#set_substitute_pattern('file', '^\\', '~/*')
call unite#set_substitute_pattern('file', '^;v', '~/.vim/*')
call unite#set_substitute_pattern('file', '^;a', '~/.vim/autoload/*')
call unite#set_substitute_pattern('file', '^;b', '~/.vim/bundle/*')
call unite#set_substitute_pattern('file', '^;l', '~/.vim/labs/*')
call unite#set_substitute_pattern('file', '^;g', '~/.vim/plugin/*')
call unite#set_substitute_pattern('file', '^;s', '~/.vim/syntax/*')
call unite#set_substitute_pattern('file', '^;c', '~/.vim/custom/*')
call unite#set_substitute_pattern('file', '^;f', '~/.vim/custom/after/ftplugin/*')
call unite#set_substitute_pattern('file', '^;r', rtputil#split())
if has('win32') || has('win64')
call unite#set_substitute_pattern('file', '^;p', 'C:/Program Files/*')
endif
if isdirectory(expand('~/work/vim-plugins'))
call unite#set_substitute_pattern('file', '^;d', '~/work/vim-plugins/*')
endif
call unite#set_substitute_pattern('file', '\*\*\+', '*', -1)
call unite#set_substitute_pattern('file', '^\~', escape($HOME, '\'), -2)
call unite#set_substitute_pattern('file', '\\\@<! ', '\\ ', -20)
call unite#set_substitute_pattern('file', '\\ \@!', '/', -30)
call unite#set_substitute_pattern('file', ';', ' ', -31)
call unite#set_buffer_name_option('file', 'ignorecase', 1)
call unite#set_buffer_name_option('file', 'smartcase', 0)
" custom_actions for unite. {{{3
" echo action {{{4
let s:unite_action = {
\ 'description': 'Echo the candidates for debug.',
\ 'is_selectable': 1,
\ }
function! s:unite_action.func(candidates)
PP a:candidates
endfunction
call unite#custom_action('common', 'echo', s:unite_action)
unlet! s:unite_action
" tabvsplit action {{{4
let s:unite_action = {
\ 'description': 'Open files to new tabpage with :vsplit.',
\ 'is_selectable': 1,
\ }
function! s:unite_action.func(candidates)
tabnew `=a:candidates[0].action__path`
for c in a:candidates[1 :]
vsplit `=c.action__path`
endfor
endfunction
call unite#custom_action('openable', 'tabvsplit', s:unite_action)
unlet! s:unite_action
" source action for file {{{4
let s:unite_action = {
\ 'description': ':source files',
\ 'is_selectable': 1,
\ }
function! s:unite_action.func(candidates)
for c in a:candidates
source `=c.action__path`
endfor
endfunction
call unite#custom_action('file', 'source', s:unite_action)
unlet! s:unite_action
command! UniteBeautifulAttack Unite -auto-preview colorscheme
" file delete action {{{4
let s:unite_action = {
\ 'description': 'delete selected files',
\ 'is_selectable': 1,
\ }
function! s:unite_action.func(candidates)
call map(filter(copy(a:candidates), 'filewritable(v:val.action__path)'),
\ 'delete(v:val.action__path)')
endfunction
call unite#custom_action('file', 'delete', s:unite_action)
unlet! s:unite_action
" unite-grep.vim {{{2
if executable('ack')
" let g:unite_source_grep_command = 'ack'
" let g:unite_source_grep_default_opts = '-a'
endif
" unite-outline.vim {{{2
call unite#custom_max_candidates('outline', 0)
let g:unite_source_outline_info = {
\ 'clojure': {
\ 'heading': '^(defn\>',
\ },
\ 'coffee': {
\ 'heading': '^class\>\|\w\+\s*[:=]\s*\%((.\{-})\s*\)\?[-=]>'
\ },
\ }
function! g:unite_source_outline_info.coffee.create_heading(
\ which, heading_line, matched_line, context)
return {
\ 'word': a:heading_line,
\ 'level': (len(matchstr(a:heading_line, '^\s*')) / &l:shiftwidth) + 1,
\ 'type': a:matched_line =~# '^class' ? 'class' : 'function',
\ }
endfunction
" unite-locate.vim {{{2
if g:V.is_windows() && executable('es')
let g:unite_locate_command = 'es -i -r -n %d %s'
endif
" alignta.vim {{{2
vnoremap <silent> <C-h> :Alignta<CR>
let g:alignta_default_arguments = '\S\+'
" 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 <Plug>CalendarV
nmap caL <Plug>CalendarH
" gist.vim {{{2
let g:gist_detect_filetype = 1
" skk.vim {{{2
let g:skk_large_jisyo = '~/.vim/dict/skk/SKK-JISYO.utf-8.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
let g:skk_control_j_key = '<C-g><C-j>'
" eskk.vim {{{2
let g:plugin_skk_disable = 1
" let g:eskk_disable = 1
let g:eskk#large_dictionary = {
\ 'path': '~/.vim/dict/skk/SKK-JISYO.utf-8.L',
\ 'sorted': 1,
\ 'encoding': 'utf-8',
\}
let g:eskk#egg_like_newline = 1
let g:eskk#egg_like_newline_completion = 1
let g:eskk#map_normal_keys = 0
let g:eskk#show_annotation = 1
let g:eskk#rom_input_style = 'msime'
let g:eskk#keep_state = 0
" let g:eskk#keep_state = 1
" let g:eskk#keep_state_beyond_buffer = 1
if g:V.is_windows() && !has('gui_running')
let g:eskk#enable_completion = 0
endif
let g:eskk#debug = 1
let g:eskk#directory = s:plugin_info . '/eskk'
let g:eskk#debug_profile = 1
if s:has_plugin('eskk')
augroup vimrc-plugin-eskk
autocmd!
autocmd CursorHold * silent EskkUpdateDictionary
autocmd User eskk-initialize-pre call s:init_eskk()
augroup END
endif
function! s:init_eskk()
let t = eskk#table#new('rom_to_hira*', 'rom_to_hira')
call t.add_map('va', 'ゔぁ')
call t.add_map('vi', 'ゔぃ')
call t.add_map('vu', '')
call t.add_map('ve', 'ゔぇ')
call t.add_map('vo', 'ゔぉ')
call t.add_map('z ', ' ')
call eskk#register_mode_table('hira', t)
unlet t
endfunction
" caw.vim {{{2
nmap <Leader>c <Plug>(caw:prefix)
vmap <Leader>c <Plug>(caw:prefix)
nmap <Plug>(caw:prefix)<Space> <Plug>(caw:i:toggle)
vmap <Plug>(caw:prefix)<Space> <Plug>(caw:i:toggle)
nmap <Plug>(caw:prefix)w <Plug>(caw:wrap:toggle)
vmap <Plug>(caw:prefix)w <Plug>(caw:wrap:toggle)
" open-browser.vim {{{2
nmap m<CR> <Plug>(openbrowser-open)
vmap m<CR> <Plug>(openbrowser-open)
" restart.vim {{{2
let g:restart_save_window_values = 0
let g:restart_sessionoptions =
\ 'blank,curdir,folds,help,localoptions,tabpages,unix'
nnoremap <silent> <Leader><Leader>res :<C-u>Restart<CR>
" nextfile.vim {{{2
call submode#enter_with('nextfile', 'n', 'r', '<Leader>j', '<Plug>(nextfile-next)')
call submode#enter_with('nextfile', 'n', 'r', '<Leader>k', '<Plug>(nextfile-previous)')
call submode#map('nextfile', 'n', 'r', 'j', '<Plug>(nextfile-next)')
call submode#map('nextfile', 'n', 'r', 'k', '<Plug>(nextfile-previous)')
" 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' g:V.modulo(tabpagenr() + a:nr - 1, tabpagenr('$'))
endfunction
let s:movetab = ':<C-u>call ' . s:SIDP() . 'movetab(%d)<CR>'
call submode#enter_with('movetab', 'n', '', '<Space>gt', printf(s:movetab, 1))
call submode#enter_with('movetab', 'n', '', '<Space>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', '', '<C-w>>', '<C-w>>')
call submode#enter_with('winsize', 'n', '', '<C-w><', '<C-w><')
call submode#enter_with('winsize', 'n', '', '<C-w>+', '<C-w>-')
call submode#enter_with('winsize', 'n', '', '<C-w>-', '<C-w>+')
call submode#map('winsize', 'n', '', '>', '<C-w>>')
call submode#map('winsize', 'n', '', '<', '<C-w><')
call submode#map('winsize', 'n', '', '+', '<C-w>-')
call submode#map('winsize', 'n', '', '-', '<C-w>+')
call submode#enter_with('diff', 'n', '', '<Space><Space>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
" fakeclip.vim {{{2
nmap "+Y "+y$
nmap "*Y "*y$
nmap "&Y "&y$
" altr.vim {{{2
call altr#define('%.c', '%.cpp', '%.cc',
\ '%.h', '%.hpp', '%.hh', '%.hxx', '%.h++')
call altr#define('%.coffee', '%.js')
nnoremap <silent> <C-Space> :<C-u>call altr#forward()<CR>
nnoremap <silent> <C-S-Space> :<C-u>call altr#back()<CR>
nnoremap <silent> <C-w><C-Space> :<C-u>split<CR>:call altr#forward()<CR>
nnoremap <silent> <C-w><C-S-Space> :<C-u>split<CR>:call altr#back()<CR>
" smartword.vim {{{2
nmap w <Plug>(smartword-w)
nmap b <Plug>(smartword-b)
nmap e <Plug>(smartword-e)
nmap ge <Plug>(smartword-ge)
vmap w <Plug>(smartword-w)
vmap b <Plug>(smartword-b)
vmap e <Plug>(smartword-e)
vmap ge <Plug>(smartword-ge)
omap <Leader>w <Plug>(smartword-w)
omap <Leader>b <Plug>(smartword-b)
omap <Leader>e <Plug>(smartword-e)
omap <Leader>ge <Plug>(smartword-ge)
" textobj-user.vim {{{2
" textobj-function {{{3
let g:textobj_function_no_default_key_mappings = 1
omap iF <Plug>(textobj-function-i)
omap aF <Plug>(textobj-function-a)
vmap iF <Plug>(textobj-function-i)
vmap aF <Plug>(textobj-function-a)
call textobj#user#plugin('camelcase', {
\ '-': {
\ '*pattern*': '\C\a[a-z0-9]\+',
\ 'select': ["a\<C-w>", "i\<C-w>"],
\ },
\ })
" operator-user.vim {{{2
" operator-replace {{{3
map mp <Plug>(operator-replace)
vmap p <Plug>(operator-replace)
" operator-camelize {{{3
map <Leader>oc <Plug>(operator-camelize)iw
map <Leader>oC <Plug>(operator-decamelize)iw
" operator-sequence {{{3
noremap <expr> <Leader>oU
\ operator#sequence#map("\<Plug>(operator-decamelize)", 'gU') . 'iw'
noremap <expr> <Leader>ou
\ operator#sequence#map("\<Plug>(operator-camelize)", ['b~']) . 'iw'
" ProjectEuler.vim {{{2
let g:projecteuler_dir = s:plugin_info . '/projecteuler/'
let g:projecteuler_user = 'thinca'
let g:projecteuler_problem_lang = 'ja'
" onlinejadge.vim {{{2
let g:onlinejudge_account = {'aoj': {'user': 'thinca'}}
" textmanip.vim {{{2
call submode#enter_with('textmanip', 'v', 'r', 'mv')
call submode#map('textmanip', 'v', 'r', 'h', '<Plug>(textmanip-move-left)')
call submode#map('textmanip', 'v', 'r', 'j', '<Plug>(textmanip-move-down)')
call submode#map('textmanip', 'v', 'r', 'k', '<Plug>(textmanip-move-up)')
call submode#map('textmanip', 'v', 'r', 'l', '<Plug>(textmanip-move-right)')
call submode#map('textmanip', 'v', 'rx', '<ESC>', '<ESC><ESC>')
" quickhl.vim {{{2
map mh <Plug>(quickhl-toggle)
map mH <Plug>(quickhl-reset)
map ms <Plug>(quickhl-toggle)
" reanimate.vim {{{2
let g:reanimate_save_dir = s:plugin_info . '/reanimate'
let g:reanimate_disables = [
\ 'reanimate_viminfo',
\ 'reanimate_window',
\ 'reanimate_message',
\ ]
let g:reanimate_sessionoptions =
\ 'blank,curdir,folds,help,localoptions,tabpages,unix'
augroup vimrc-plugin-reanimate
autocmd!
if argc() == 0 && !exists('g:lingr')
" autocmd VimEnter * ReanimateLoadLatest
endif
autocmd CursorHold,VimLeavePre * ReanimateSaveCursorHold
augroup END
let s:event = {'name': 'user_event'}
function! s:event.load_pre(...)
tabnew
hide tabonly
endfunction
function! s:event.save_pre(...)
silent! argdelete *
endfunction
call reanimate#hook(s:event)
unlet s:event
nnoremap <silent> <Leader>as
\ :<C-u>Unite reanimate -default-action=reanimate_switch<CR>
" syntastic.vim {{{2
let g:loaded_syntastic_plugin = 1
let g:syntastic_cpp_compiler_options = ' -std=c++0x'
" tweetvim.vim {{{2
let g:tweetvim_config_dir = s:plugin_info . '/tweetvim/'
let g:tweetvim_open_buffer_cmd = 'split'
let g:tweetvim_display_separator = 0
nnoremap <silent> <Leader><Leader>v :<C-u>TweetVimSay<CR>
" lingr.vim {{{2
if !exists('g:lingr') && !g:V.is_windows()
" 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'
let g:lingr_vim_additional_rooms = [
\ 'vim',
\ 'gentoo',
\ 'vimjolts',
\ 'editor',
\ 'vimperator',
\ 'bazaar',
\ 'filer',
\ 'git',
\ 'completion',
\ 'java_ja',
\ 'shell',
\ 'scala',
\ 'lingr',
\ 'lowlevel',
\ 'haskell',
\ 'ruby',
\ '_',
\ 'thinca',
\ 'onsg',
\ 'yokohamavim',
\ ]
let g:lingr_vim_rooms_buffer_height = len(g:lingr_vim_additional_rooms) + 1
let g:lingr_vim_count_unread_at_current_room = 1
augroup vimrc-plugin-lingr
autocmd!
autocmd User plugin-lingr-* call s:lingr_event(
\ matchstr(expand('<amatch>'), 'plugin-lingr-\zs\w*'))
autocmd FileType lingr-* call s:init_lingr(expand('<amatch>'))
augroup END
function! s:init_lingr(ft)
if exists('s:window')
nnoremap <buffer> <silent> <C-l>
\ :<C-u>call <SID>auto_window_name()<CR><C-l>
let b:window_name = 'lingr-vim'
endif
if a:ft ==# 'lingr-say'
setlocal statusline=%f\ %m
if exists('*eskk#statusline')
let &l:statusline .= '%{eskk#statusline()}'
endif
elseif a:ft ==# 'lingr-members'
setlocal nowinfixheight
elseif a:ft ==# 'lingr-messages'
nmap <buffer> C vi)*
endif
endfunction
function! s:lingr_event(event)
if a:event ==# 'message' && exists(':WindowName') == 2
execute printf('WindowName %s(%d)', 'lingr-vim', lingr#unread_count())
endif
endfunction
" ambicmd.vim {{{2
cnoremap <expr> <Space> ambicmd#expand("\<Space>")
cnoremap <expr> <CR> ambicmd#expand("\<CR>")
cnoremap <expr> <C-f> ambicmd#expand("\<Right>")
function! s:init_cmdwin()
inoremap <buffer> <expr> <Space> ambicmd#expand("\<Space>")
inoremap <buffer> <expr> <CR> ambicmd#expand("\<CR>")
inoremap <buffer> <expr> <C-f> ambicmd#expand("\<Right>")
inoremap <buffer> <expr> <C-h> col('.') == 1 ? "\<ESC>\<C-w>c" : "\<C-h>"
nnoremap <buffer> <ESC> <C-w>c
nnoremap <buffer> <ESC><ESC> <C-w>c
nnoremap <buffer> q <C-w>c
startinsert!
endfunction
augroup vimrc-plugin-ambicmd
autocmd CmdwinEnter * call s:init_cmdwin()
augroup END
" auto_source.vim {{{2
let g:auto_source#exclude = ['\.gvimrc', '/\.vim/info/']
" singleton.vim {{{2
let g:singleton#opener = 'Opener'
" github.vim {{{2
let g:github#debug = 1
let g:github#debug_file = s:plugin_info . '/github/debug-%Y-%m-%d.log'
" openbuf.vim {{{2
let g:openbuf#config = {
\ '_': {'default': 0},
\ 'test': {'openres': 'loaded'},
\ 'test/foo': {'default': 2},
\ }
" poslist.vim {{{2
let g:poslist_histsize = 1000
map <C-o> <Plug>(poslist-prev-pos)
map <C-i> <Plug>(poslist-next-pos)
map <Leader><C-o> <Plug>(poslist-prev-line)
map <Leader><C-i> <Plug>(poslist-next-line)
map <Space><C-o> <Plug>(poslist-prev-buf)
map <Space><C-i> <Plug>(poslist-next-buf)
" quickrun.vim {{{2
function! s:init_quickrun()
for [key, c] in items({
\ '<Leader>x': '>message',
\ '<Leader>p': '-runner shell',
\ '<Leader>"': '>variable:@"',
\ '<Leader>w': '>buffer',
\ '<Leader>q': '>>buffer',
\ '<Leader>ex': '-hook/eval/enable 1 >message',
\ '<Leader>ep': '-hook/eval/enable 1 -runner shell',
\ '<Leader>e"': '-hook/eval/enable 1 >variable:@"',
\ '<Leader>ew': '-hook/eval/enable 1 >buffer',
\ '<Leader>eq': '-hook/eval/enable 1 >>buffer',
\ })
execute 'nnoremap <silent>' key ':QuickRun' c '-mode n<CR>'
execute 'vnoremap <silent>' key ':QuickRun' c '-mode v<CR>'
endfor
let g:quickrun_config = {
\ '_': {
\ 'debug': 'ss',
\ 'input': '=%{b:input}', 'cmdopt': '%{b:cmdopt}', 'args': '%{b:args}',
\ 'runner': 'vimproc',
\ 'runner/vimproc/updatetime': 500,
\ },
\ 'c/tcc': {'command': 'tcc', 'exec': '%c -run %o %s %a',
\ 'hook/eval/template': 'int main(int argc, char *argv[]){%s;}'},
\ 'cpp/gcc': {'cmdopt': '-std=c++0x'},
\ 'cpp/C': {'cmdopt': '-lstd=c++0x'},
\ 'clojure': {'command': 'clojure-1.4', 'eval_template': '(print %s)'},
\ 'nilscript': {'exec': 'ng.exe %s %a'},
\ 'xmodmap': {},
\ 'mxml': {'exec': ['amxmlc %s', 'adl %s:r-app.xml'],
\ 'output_encode': '&termencoding'},
\ }
if executable('C')
let g:quickrun_config.c = {'type': 'c/C'}
let g:quickrun_config.cpp = {'type': 'cpp/C'}
endif
" if executable('tcc')
" let g:quickrun_config.c = {'type': 'c/tcc'}
" endif
map <Leader>or <Plug>(quickrun-op)
endfunction
call s:init_quickrun()
augroup vimrc-plugin-quickrun
autocmd!
autocmd BufReadPost,BufNewFile [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
call template#load('Scratch.' . ft)
endfunction
nnoremap <silent> <Leader><Leader>s :<C-u>call <SID>open_scratch()<CR>
" ref.vim {{{2
let g:ref_open = 'vsplit'
let g:ref_cache_dir = s:plugin_info . '/ref'
let g:ref_clojure_cmd = 'clojure-1.4'
let g:ref_clojure_precode = '(use ''[clojure.repl :only (doc find-doc)])'
let g:ref_phpmanual_path = $HOME . '/local/share/doc/php'
if executable('refe2')
let g:ref_refe_cmd = 'refe2'
endif
let g:ref_source_webdict_sites = {
\ 'wikipedia': {'url': 'http://ja.wikipedia.org/wiki/%s', 'line': 19},
\ 'wiktionary': {
\ 'url': 'http://ja.wiktionary.org/wiki/%s',
\ 'keyword_encoding': 'utf-8',
\ 'cache': 1,
\ }
\ }
" function! g:ref_source_webdict_sites.wikipedia.filter(output)
" return join(split(a:output, "\n")[18 :], "\n")
" endfunction
let g:ref_source_webdict_use_cache = 1
if executable('w3m')
let g:ref_source_webdict_cmd = 'w3m -dump -O utf-8 %s'
let g:ref_source_webdict_encoding = 'utf-8'
endif
let s:lynx_cmd = 'C:\Program Files\Lynx for Win32\lynx.exe'
if !exists('g:ref_source_webdict_cmd') &&
\ g:V.is_windows() &&
\ executable(s:lynx_cmd)
let g:ref_source_webdict_cmd = [s:lynx_cmd, '-dump', '-nonumbers', '%s']
let g:ref_phpmanual_cmd = g:ref_source_webdict_cmd
endif
nnoremap <silent> <Space>K
\ :<C-u>call ref#jump('normal', 'webdict', {'noenter': 1})<CR>
vnoremap <silent> <Space>K
\ :<C-u>call ref#jump('visual', 'webdict', {'noenter': 1})<CR>
nnoremap <Space><C-h> :<C-u>Ref <C-r>=ref#detect()<CR><Space>
if !exists('g:ref_detect_filetype')
let g:ref_detect_filetype = {}
endif
function! g:ref_detect_filetype._(ft)
return &keywordprg ==# ':help' ? '' : 'man'
endfunction
" template.vim {{{2
augroup vimrc-plugin-template
autocmd!
autocmd FileType * if exists('*template#load')
\ | call template#load('/filetype/' . &l:filetype)
\ | endif
autocmd User plugin-template-loaded call s:template_loaded()
autocmd BufEnter *bundle/custom/template/* setlocal makeprg=
augroup END
function! s:template_loaded()
silent %substitute/<%=\(.\{-}\)%>/\=eval(submatch(1))/ge
call histdel('/', -1)
if exists('b:template_loaded')
unlet b:template_loaded
return
endif
let b:template_loaded = 1
while search('^:TemplateLoad!', 'cw')
let cmd = getline('.')
. delete _
execute cmd
endwhile
1
if search('<+CURSOR+>')
normal! "_da>
endif
endfunction
" vcs.vim {{{2
let g:vcs#debug = 1
let g:vcs#buffer#opener = 'new'
nnoremap <silent> <Leader>va :<C-u>Vcs add<CR>
nnoremap <silent> <Leader>vb :<C-u>Vcs blame<CR>
nnoremap <silent> <Leader>vc :<C-u>Vcs commit<CR>
nnoremap <silent> <Leader>vd :<C-u>Vcs diff<CR>
nnoremap <silent> <Leader>vD :<C-u>Vcs delete<CR>
nnoremap <silent> <Leader>vs :<C-u>Vcs status<CR>
nnoremap <silent> <Leader>vl :<C-u>Vcs log<CR>
nnoremap <silent> <Leader>vzl :<C-u>Vcs log %<CR>
nnoremap <silent> <Leader>vzc :<C-u>Vcs commit %<CR>
nnoremap <silent> <Leader>vzd :<C-u>Vcs diff %<CR>
" verifyenc.vim {{{2
" This is included in the KaoriYa ver by default.
" This plugin has a bug that autocmd is carried out endlessly.
let g:plugin_verifyenc_disable = 1
" dicwin.vim {{{2
" This config is enabled in only my own patch.
let g:dicwin_leader = "\<M-d>"
" errormarker.vim {{{2
let g:loaded_errormarker = 0
" == 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(<q-args>)
" syntax test
function! CurrentSyntax()
let syntax = synstack(line('.'), col('.'))
return empty(syntax) ? '' : synIDattr(syntax[-1], "name")
endfunction
nnoremap <silent> <C-CR> :<C-u>echo join(map(synstack(line('.'), col('.')),
\ 'synIDattr(v:val, "name")
\ ."(".synIDattr(synIDtrans(v:val), "name").")"'), ',')<CR>
inoremap <silent> <C-CR> <C-o>:<C-u>echo join(map(synstack(
\ line('.'), col('.')), 'synIDattr(v:val, "name")
\ ."(".synIDattr(synIDtrans(v:val), "name").")"'), ',') "\n"<CR>
" Redirection with nestable.
function! Redir(...)
return call('quickrun#execute', a:000)
endfunction
" :Capture command. {{{
command! -nargs=+ -bang -complete=command Capture call s:capture(<q-args>)
function! s:capture(cmd)
let result = Redir(a:cmd)
call openbuf#open('capture', printf('[capture:%s]', a:cmd))
setlocal buftype=nofile noswapfile nobackup
silent put =result
silent 1,2 delete _
endfunction
" }}}
" :Halt command. {{{
let s:halt_file = expand('<sfile>:p:h') . '/info/halt_session.vim'
command! -bar -bang Halt call s:halt() | qall<bang>
function! s:halt()
if argc()
execute '1,' . argc() . 'argdelete'
endif
let ssop = &sessionoptions
let &sessionoptions = g:restart_sessionoptions
mksession `=s:halt_file`
let &sessionoptions = ssop
endfunction
if filereadable(s:halt_file) && argc() == 0 && !exists('g:lingr')
augroup vimrc-halt
autocmd!
" autocmd VimEnter * nested source `=s:halt_file` | call delete(s:halt_file)
augroup END
endif
" }}}
" 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')
if file =~# '^\d\+$'
let nr = str2nr(file)
else
let filepat = '\V' . substitute(file, '\\', '/', 'g') . '\v%(\.vim)?$'
for s in split(slist, "\n")
let p = matchlist(s, '^\s*\(\d\+\):\s*\(.*\)$')
if empty(p)
continue
endif
let [nr, sfile] = p[1 : 2]
let sfile = fnamemodify(sfile, ':p:gs?\\?/?')
if sfile =~# filepat &&
\ exists(printf("*\<SNR>%d_%s", nr, fname))
let cfunc = printf("\<SNR>%d_%s", nr, func)
break
endif
endfor
endif
if !exists('nr')
call g:V.print_error('Not sourced: ' . file)
return
elseif !exists('cfunc')
let file = fnamemodify(file, ':p')
call g:V.print_error(printf(
\ 'File found, but function is not defined: %s: %s()', 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 the command in normally?[y/N]'
if getchar() =~? 'y'
execute a:cmd
endif
return
endif
let time = reltime()
let mes = Redir(a:cmd)
let result = a:cmd . ': ' . reltimestr(reltime(time))
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(<q-args>, <bang>0)
command! -bar CountParticipantsOfReadingVimrc
\ silent call s:count_participants_of_reading_vimrc()
function! s:count_participants_of_reading_vimrc()
global/^ /delete _
%substitute/ (.*$//g
sort u
global/^\%(URL Info\.\|VimBots\|Github\|\)$/delete _
endfunction
function! URLDecode(url, ...)
let res =
\ substitute(a:url, '%\(\x\x\)', '\=eval("\"\\x".submatch(1)."\"")', 'g')
return a:0 && a:1 !=# '' ? iconv(res, a:1, &encoding) : res
endfunction
command! -range=% Tsv2csv
\ if getline(<line1>) =~ '\t'
\ | silent! <line1>,<line2> s/\t/","/g
\ | silent! <line1>,<line2> s/^\|$/"/g
\ | endif
" Load a setting for machine local.
call localrc#load('local.vim', expand('<sfile>:h'))
if has('vim_starting')
call localrc#load('.init.after.vimrc', getcwd())
endif
set secure
@mattn
mattn commented Sep 7, 2012

これthincaさんの?

@thinca
Owner
thinca commented Oct 3, 2012

今コメントに気付いた。そうです。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment