" {{{1 set encoding=utf-8 scriptencoding utf-8 " vimrcでマルチバイト文字を使うためにscriptencodingを設定する。 " この時、set encodingはscriptencodingより先に宣言する。 " vimrcやgvimrcがあると自動的にset nocompatibleになるので、set nocompatibleは書かない。 " 書くとオプションhistoryが初期化され、履歴が削除されてしまう。 " vim -u " のように指定して起動すると、set nocompatibleにならないので、 " vim -u -N " のように-Nオプションを付けて起動する " cf. vimrcアンチパターン - rbtnn雑記 " http://rbtnn.hateblo.jp/entry/2014/11/30/174749 " 初期設定 {{{1 " ============================================================================ " vimrcが検索される順番 (:help vimrc) " " Unix $HOME/.vimrc、$HOME/.vim/vimrc " MS-Windows $HOME/_vimrc、$HOME/vimfiles/vimrc、 " $VIM/_vimrc " " windowsでは$VIM(vim.exeがあるディレクトリ)も検索される。 " 例えばkaoriya版vimのディレクトリにvimrcとvimfiles(.vim)を入れておくと、ディレクトリごと持ち運ぶことができる。 " vimrcがあるディレクトリ let g:vim_home = expand(':p:h:h') if has('win32') set runtimepath& execute 'set runtimepath^=' . g:vim_home . '/.vim' execute 'set runtimepath+=' . g:vim_home . '/.vim/after' cd ~ endif let $VIMRC_DIR = g:vim_home .'/.vim/rc' let $VIM_CACHE_DIR = $HOME . '/.cache/vim' if !isdirectory($VIM_CACHE_DIR) call mkdir($VIM_CACHE_DIR, 'p') endif let g:dein_dir = g:vim_home . '/.cache/vim/dein' call has('python3') " call has('python') " MacVim-KaoriYaでは一度にpython2かpython3の片方しか使えない。 " has('python3')を呼び出すと、python3が有効になる " :help has-python " if has('python3') " " let $PYTHONHOME = expand('~/.pyenv/versions/3.5.2') " " set pythonthreedll=$HOME/.pyenv/versions/3.5.2/lib/libpython3.5m.dylib " endif if !exists('g:memo_directory') let g:memo_directory = expand('~/Dropbox/memo/doc') endif if empty($SRC_ROOT) let $SRC_ROOT = $HOME . '/src' endif let s:dotfiles_home = $SRC_ROOT.'/github.com/tmsanrinsha/dotfiles/home' " vimrc全体で使うaugroup {{{1 " ============================================================================ " http://rhysd.hatenablog.com/entry/2012/12/19/001145 " autocmd!の回数を減らすことでVimの起動を早くする " ネームスペースを別にしたい場合は別途augroupを作る augroup MyVimrc autocmd! augroup END " function, command {{{1 " ============================================================================ function! SourceRc(path) " {{{2 if filereadable(expand('$VIMRC_DIR/'.a:path)) execute 'source $VIMRC_DIR/'.a:path endif endfunction " MyHasPatch {{{2 " 引数の書き方はpatch-x.x.xxx if has('patch-7.4.237') function! MyHasPatch(str) return has(a:str) endfunction else function! MyHasPatch(str) let l:patches = split(matchstr(a:str, '\v(\d|\.)+'), '\.') return v:version > l:patches[0] . 0 . l:patches[1] || \ v:version == l:patches[0] . 0 . l:patches[1] && has('patch' . l:patches[2]) endfunction endif " バッファ名nameを持つウィンドウに移動する {{{2 function! GotoWin(name) let l:nr = bufwinnr(a:name) if l:nr > 0 execute l:nr . 'wincmd w' endif return l:nr endfunction function! IsInstalled(plugin) " {{{2 " NeoBundleLazyを使うと最初はruntimepathに含まれないため、 " runtimepathのチェックでプラグインがインストールされているかをチェックできない " neobundle#is_installedを直接使うとneobundleがない場合にエラーが出るので確認 if exists('*dein#tap') return dein#tap(a:plugin) elseif exists('*neobundle#is_installed') return neobundle#is_installed(a:plugin) else " runtimepathにあるか " http://yomi322.hateblo.jp/entry/2012/06/20/225559 " return !empty(globpath(&runtimepath, 'plugin/' . a:plugin . '.vim')) " \ || !empty(globpath(&runtimepath, 'autoload/' . a:plugin . '.vim')) " \ || !empty(globpath(&runtimepath, 'colors/' . a:plugin . '.vim')) return match(&runtimepath, a:plugin) >= 0 endif endfunction function! EnableDeoplete() abort return (has('nvim') || has('timers')) && has('python3') endfunction function! GetPassword() abort " {{{2 if !exists('g:password') let g:password = inputsecret('password: ') endif return g:password endfunction command! Makelink call s:makelink() " {{{2 function! s:makelink() abort let l:real_path = expand('%:p') let l:symlink_path = substitute(l:real_path, '.*/home', $HOME, '') call system('ln -s ' . shellescape(l:real_path) . ' ' . shellescape(l:symlink_path)) endfunction " FixSpaces {{{2 " ---------------------------------------------------------------------------- " original " [ntpeters/vim-better-whitespace: Better whitespace highlighting for Vim](https://github.com/ntpeters/vim-better-whitespace) " Removes all extraneous whitespace in the file command! -range=% FixSpaces call fix_spaces(, ) function! s:fix_spaces(line1, line2) " Save the current search and cursor position let _s=@/ let l = line('.') let c = col('.') " Trim trailing spaces silent! execute ':' . a:line1 . ',' . a:line2 . 's/\s\+$//e' " Replace unicode spaces to normal space silent! execute ':' . a:line1 . ',' . a:line2 . 's/\%u00A0\|\%u180E\|\%u2000\|\%u2001\|\%u2002\|\%u2003\|\%u2004\|\%u2005\|\%u2006\|\%u2007\|\%u2008\|\%u2009\|\%u200A\|\%u2028\|\%u2029\|\%u202F\|\%u205F\|\%u3000/ /ge' " Restore the saved search and cursor position let @/=_s call cursor(l, c) endfunction " IndentChange {{{2 " ---------------------------------------------------------------------------- " インデント幅を変更する " " 例 " 1) バッファ全体のインデントを4から2に変更する " :IndentChange 4 2 " 2) ビジュアル選択部分のインデントを2から4に変更する " :'<,'>IndentChange 2 4 " " 置換部分は " - vim-jp » Hack #143: 見た目を変えずにタブ文字とスペースを相互に変換する " http://vim-jp.org/vim-users-jp/2010/04/30/Hack-143.html " を参考にした command! -range=% -nargs=* IndentChange call indent_change(, , ) function! s:indent_change(line1, line2, from, to) execute a:line1 . ',' . a:line2 . 's@^\v(%( {' . a:from . '})+)@\=repeat(" ", len(submatch(1))/' . a:from . '*' . a:to . ')@' endfunction " from以下でファイルの保存したら、to以下にディレクトリ構成を保ってコピーする {{{2 " ---------------------------------------------------------------------------- function! SetAutocmdSyncSaveDir(sync_save_dir_list) abort for sync_save_dir in a:sync_save_dir_list " この処理は時間がかかるので、コメントアウト " if len(glob(sync_save_dir['glob'])) == 0 " echoerr 'no match glob' " endif execute 'autocmd MyVimrc BufWritePost ' . sync_save_dir['glob'] \ . ' call s:syncSaveDir("' . sync_save_dir['from'] . '", "' . sync_save_dir['to'] . '")' endfor endfunction function! s:syncSaveDir(from, to) let l:current_file = expand('%:p') " カレントファイルのフルパスのfrom部分をtoに置換する。 " バックスラッシュをエスケープする必要あり let l:target_file = substitute(l:current_file, escape(a:from, '\'), a:to , '') let l:target_dir = fnamemodify(l:target_file, ':h') if !isdirectory(l:target_dir) call mkdir(l:target_dir, 'p') endif call writefile(readfile(l:current_file, 'b'), l:target_file, 'b') endfunction " Call a script local function. {{{2 " ---------------------------------- " [スクリプトローカルな関数を手軽に呼び出す - 永遠に未完成](http://thinca.hatenablog.com/entry/20111228/1325077104) " 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. redir =>slist silent scriptnames redir END 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("*\%d_%s", nr, fname)) let cfunc = printf("\%d_%s", nr, func) break endif endfor if !exists('nr') echoerr 'Not sourced: ' . file return elseif !exists('cfunc') let file = fnamemodify(file, ':p') echoerr 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 " SetEventIgnore {{{2 " ---------------------------------------------------------------------------- " qfreplaceを使うときなどにイベントを無視したいとき " TODO 置換対象が10行を超えたら自動的にeventignoreする command! EventIgnore set eventignore=BufEnter,BufWritePost,BufWrite,FileAppendPre,BufWritePost,FileWritePost,FileWritePost nobackup command! EventIgnoreOff set eventignore= backup " 1}}} call SourceRc('local_pre.vim') " 基本設定 {{{1 " ============================================================================ " 現在のモードを表示 set showmode " コマンドを表示 set showcmd " コマンドラインの高さを2行にする set cmdheight=2 " 行番号を表示する set number " 1行が長い場合でも表示 set display=lastline " set ruler " 閉じ括弧が入力されたとき、対応する開き括弧にわずかの間ジャンプする set showmatch " マッチを表示する時間を0.1秒にする set matchtime=1 " set matchpairs+=<:> " 7.3.769からmatchpairsにマルチバイト文字が使える if MyHasPatch('patch-7.3.769') set matchpairs+=「:」,『:』,(:),【:】,《:》,〈:〉,[:],‘:’,“:” endif " %の拡張する。%で開始タグ、終了タグを移動、ifとendifを移動など runtime macros/matchit.vim " ビジュアルベルにして、設定を空にすることで、ビープ音もビジュアルベルも無効化 set visualbell t_vt= " CTRL-AやCTRL-Xを使った時の文字の増減の設定 " alpha アルファベットの増減 " octal 8進数の増減 " hex 16進数の増減 " * アルファベットは増減させない " * 0で始まる数字列を8進数とみなさず、10進数として増減させる。 " * 10進数と16進数を増減させる。 set nrformats=hex "変更中のファイルでも、保存しないで他のファイルを表示 set hidden set shellslash " macに最初から入っているvimはセキュリティの問題からシステムのvimrcでset modelines=0している。 " http://unix.stackexchange.com/questions/19875/setting-vim-filetype-with-modeline-not-working-as-expected " この問題は7.0.234と7.0.235のパッチで修正された " https://bugzilla.redhat.com/show_bug.cgi?id=cve-2007-2438 if MyHasPatch('patch-7.0.234') && MyHasPatch('patch-7.0.235') set modelines& else set modelines=0 endif " マウスを使えるようにする " altやoptionを押しながら、マウスを使うと、set mouseを設定しない時の動きになる。 set mouse=a " cursor {{{1 " ============================================================================ " 挿入モードでの , , CTRL-W, CTRL-U の働きの設定 " indent autoindent を超えてバックスペースを働かせる " eol 改行を超えてバックスペースを働かせる (行を連結する) " start 挿入区間の始めでバックスペースを働かせるが CTRL-W と CTRL-U は " 挿入区間の始めでいったん止まる set backspace=indent,eol,start " カーソルを行頭、行末で止まらないようにする。 set whichwrap& " set whichwrap=b,s,h,l,<,>,[,],~ " 矩形選択でカーソル位置の制限を解除 set virtualedit=block " encode, fileformat {{{1 " ============================================================================ " 文字コード " set encoding=utf-8 上で設定 " カレントバッファのファイルの文字エンコーディングをUTF-8にする。新規にファイルを作った時などに影響する " setにするとvimrcをリロードした時、バッファのfileencodingを変更してしまうのでsetglobalにする " :h setglobal setglobal fileencoding=utf-8 " ファイルの読み込み時に文字エンコーディングを判定する順番 " kaoriya版ではguess_encodeというものがあるので、それを使う if has('guess_encode') set fileencodings=guess,ucs-boms,utf-8,euc-jp,cp932 else set fileencodings=ucs-boms,utf-8,euc-jp,cp932 endif " Vimテクニックバイブル「2-7ファイルの文字コードを変換する」に書いてあるfileencodings。 " ただし2つあるeuc-jpの2番目を消した " if has("win32") " set fileencodings=iso-2222-jp-3,iso-2022-jp,euc-jisx0213,euc-jp,utf-8,ucs-bom,eucjp-ms,cp932 " endif " エンコーディングを指定して開き直す command! EncCp932 edit ++enc=cp932 command! EncEucjp edit ++enc=euc-jp command! EncIso2022jp edit ++enc=iso-2022-jp command! EncUtf8 edit ++enc=utf-8 command! EncLatin1 edit ++enc=latin1 " alias command! EncJis EncIso2022jp command! EncSjis EncCp932 " 改行コードの設定 set fileformat=unix " 改行コードを判定する順番 set fileformats=unix,dos,mac " 改行コードを指定して開き直すには " :e ++ff=dos " などとする " 最後に改行が無いテキストファイルに改行を付加しない if exists('&fixeol') set nofixeol endif "□や○の文字があってもカーソル位置がずれないようにはdoubleを設定する " デフォルトはsingle " singleに設定したほうが画面が乱れにくい set ambiwidth=double " decode, encode {{{1 " ============================================================================ " 数値文字参照をデコード command! DecodeNumCharRef s/&#\(\d\+\);/\=nr2char(submatch(1))/gc " URIデコード command! -range DecodeUri ,!decode_uri " tab, indent {{{1 " ============================================================================ " 挿入モードでを押したときにスペースに展開する。タブそのものを使いたいときはコメントアウト set expandtab " 画面上でタブ文字が占める幅 set tabstop=2 try " を挿入したり、を使った時の幅 " -1に設定するとtabstopの値と同じにする " を使った時に1スペース削除したい場合はコメントアウト set softtabstop=-1 " 自動インデントやコマンド<と>などに使われる空白の数 " 0の場合はtabstopと同じ値 set shiftwidth=0 catch /E487/ let &softtabstop = &tabstop let &shiftwidth = &tabstop endtry " コマンド<や>でインデントする際に'shiftwidth'の倍数に丸める set shiftround " :h indent.txt " 後のものが有効にされると、前のものより優先される " set autoindent " 一つ前の行に基づくインデント " set smartindent " 'autoindent' と同様だが幾つかのC構文を認識し、適切な箇所のイン " デントを増減させる。 set cindent " 他の2つの方法よりも賢く動作し、設定することで異なるインデント " スタイルにも対応できる。 set cinkeys-=0# " 行の先頭で '#' をタイプした時 " :h 'smartindent' " 新しく作った行の最初の文字が '#' のとき、その行のインデントは取り除か " れ、'#' は最前列に置かれる。次の行のインデントは '#' の行の前と同じに " なる。こうしてほしくないなら、次のマッピングを使うこと。 " ":inoremap # X^H#" " ここで ^H は CTRL-V CTRL-H と打ち込むと入力される。 " コマンド ">>" を使ったとき、'#' で始まる行は右に移動しない。 " 不可視文字 {{{1 " ============================================================================ " 不可視文字の表示 set list " tab: »- " 行末の空白: ・ " ノーブレークスペース: _ " 画面の右側に文字があるとき: » " 画面の左側に文字があるとき: « set listchars=tab:»-,trail:・,nbsp:_,extends:»,precedes:« " set listchars=tab:»-,trail:_,extends:»,precedes:«,nbsp:%,eol:↵ if has('conceal') " For snippet_complete marker. " concealcursor=nivにしない。隠さないほうがいいので空にする set conceallevel=2 " autocmd MyVimrc Filetype json,markdown " \ setlocal concealcursor= endif " スペース以外の空白文字をハイライト {{{2 " ---------------------------------------------------------------------------- " (Vimテクニックバイブル1-11)+ unicode spacesもハイライトするようにした " [Vimで全角空白以外のユニコードの空白文字もハイライト&取り除く - Qiita](http://qiita.com/tmsanrinsha/items/d6c11f2b7788eb24c776) augroup MyVimrc autocmd ColorScheme * highlight UnicodeSpaces cterm=underline ctermfg=59 ctermbg=16 gui=underline guifg=#465457 guibg=#000000 " autocmd ColorScheme * " \ execute 'highlight UnicodeSpaces' " \ . ' ctermfg=' . synIDattr(synIDtrans(hlID('SpecialKey')), 'fg', 'cterm') " \ . ' ctermbg=' . synIDattr(synIDtrans(hlID('SpecialKey')), 'bg', 'cterm') " \ . ' guifg=' . synIDattr(synIDtrans(hlID('SpecialKey')), 'fg', 'gui') " \ . ' guibg=' . synIDattr(synIDtrans(hlID('SpecialKey')), 'bg', 'gui') " \ . ' cterm=underline gui=underline' highlight UnicodeSpaces cterm=underline ctermfg=59 ctermbg=16 gui=underline guifg=#465457 guibg=#000000 autocmd VimEnter,WinEnter * match UnicodeSpaces /\%u180E\|\%u2000\|\%u2001\|\%u2002\|\%u2003\|\%u2004\|\%u2005\|\%u2006\|\%u2007\|\%u2008\|\%u2009\|\%u200A\|\%u2028\|\%u2029\|\%u202F\|\%u205F\|\%u3000\|−\|‐/ augroup END " format {{{1 " ============================================================================ set textwidth=0 " :h fo-table set formatoptions& " r : Insert modeでを押したら、comment leaderを挿入する set formatoptions+=r " M : マルチバイト文字の連結(J)でスペースを挿入しない set formatoptions+=M if MyHasPatch('patch-7.3.541') && MyHasPatch('patch-7.3.550') " j : コメント行の連結でcomment leaderを取り除く set formatoptions+=j endif " t : textwidthを使って自動的に折り返す set formatoptions-=t " c : textwidthを使って、コマントを自動的に折り返しcomment leaderを挿入する set formatoptions-=c " o : Normal modeでoまたOを押したら、comment leaderを挿入する set formatoptions+=o set formatexpr= " mapping {{{1 " ============================================================================ " :h map-modes " gvimにAltのmappingをしたい場合は先にset encoding=...をしておく " key mappingに対しては9000ミリ秒待ち、key codeに対しては20ミリ秒待つ " コマンドラインモードでを押した時に消えるのが早くなるなど。 set timeout timeoutlen=9000 ttimeoutlen=20 " MacVimでMETAキーを使えるようにする if exists('+macmeta') set macmeta endif let g:mapleader = ';' let g:maplocalleader = '\' " maparg() " 現在の設定のrhsを返す " prefix " http://blog.bouzuya.net/2012/03/26/prefixedmap-vim/ " [:space:]でmapするようにするとVimFilerのスペースキーでキー待ちが発生しなくなる nnoremap [:space:] xnoremap [:space:] nmap [:space:] xmap [:space:] " を使っていいかも " nmap (my-space) " nnoremap (my-space) " noremap ; : " noremap : ; nnoremap [Colon] : " inoremap jj " cnoremap jj nnoremap Y y$ " カーソルを表示行で移動するようにする nnoremap j gj xnoremap j gj nnoremap gj xnoremap gj nnoremap k gk xnoremap k gk nnoremap gk xnoremap gk nnoremap gj j xnoremap gj j nnoremap gk k xnoremap gk k nnoremap 0 g0 xnoremap 0 g0 nnoremap $ g$ " ヴィジュアルモード時は$で論理的行末まで行きたいのでコメントアウト " xnoremap $ g$ nnoremap g0 0 xnoremap g0 0 nnoremap g$ $ xnoremap g$ $ " goto file nnoremap gf gF xnoremap gf gF nnoremap gF gf xnoremap gF gf nnoremap f F xnoremap f F nnoremap F f xnoremap F f nnoremap gf gF xnoremap gf gF nnoremap gF gf xnoremap gF gf nnoremap ]h /\vhttps?:\/\/ nnoremap [h ?\vhttps\?:// inoremap dt strftime('%Y-%m-%d') cnoremap dt strftime('%Y-%m-%d') nnoremap :w inoremap :w " [【Vim】シェルの実行結果を行としてではなく現在のカーソル位置に挿入する - Qiita](https://qiita.com/tmsanrinsha/items/44a4377e3c3ce024fa16) " ---------------------------------------------------------------------------- inoremap ! system() cnoremap ! system() function! s:system() let command = input("!", '', 'shellcmd') return substitute(system(command), '\n\+$', '', '') endfunction " でカーソル前の数式の結果を=の後に出力する {{{2 " ---------------------------------------------------------------------------- " Vim scriptテクニックバイブル4-3によると " " = " " " の順にいいらしい inoremap "\u" . EvalExpression() function! EvalExpression() abort let expression = getline('.') let expression = matchstr(expression, '[0-9.+\-*/()^ ]\+') " 1/4を0.25としてほしいのでluaeval()を使う return ' = ' . string(luaeval(expression)) endfunction " statusline {{{1 " ============================================================================ " 最下ウィンドウにいつステータス行が表示されるかを設定する。 " 0: 全く表示しない " 1: ウィンドウの数が2以上のときのみ表示 " 2: 常に表示 set laststatus=2 " statuslineはlightline.vimでやっている " :help 'statusline' " f バッファ内のファイルのパス(入力された通り、またはカレントディレクトリに対する相対パス) " m 修正フラグ " = ここから右寄せ " r 読み込み専用フラグ " fenc ファイルエンコード " enc Vim内部で使うエンコード " ff ファイルフォーマット(改行コード) " Y ファイルタイプ " P 現在の行がファイル内の何%の位置にあるか " %v 何列目 " %l 何行目 " set statuslineで設定するとスペースを入れるために'\ '、縦線を入れるために'\|'のようにエスケープしなくてはならないので " let &statuslineで設定する " let &statusline = '%f%m%=%r%{(&fenc!=""?&fenc:&enc)} | %{&ff} | %Y | %P | %v:%l' " titlestring {{{1 " ============================================================================ set title let &titlestring = "%{expand('%:p')} @" . hostname() " tmux使用時(おそらくtermがxterm*ではない場合)t_ts, t_fsがセットされないのでセットする let &t_ts = "\e]0;" let &t_fs = "\007" " window {{{1 " ============================================================================ " nnoremap h " nnoremap j " nnoremap k " nnoremap l nnoremap - nnoremap + nnoremap < nnoremap > nnoremap = nnoremap p set splitbelow set splitright " カーソルの上下に最低でも1行は表示させる。常にカーソル行を真ん中にする場合は999など set scrolloff=1 " 左右スクロール時 set sidescrolloff=2 " 横スクロールを1文字ずつ set sidescroll=1 " 横方向に半画面分移動 nnoremap zL nnoremap zH " ウィンドウ分割時に等分にしない " fugitiveを使った時のdiffが等分になって欲しいのでコメントアウト " set noequalalways "縦分割されたウィンドウのスクロールを同期させる "同期させたいウィンドウ上でを押せばおk "解除はもう一度を押す "横スクロールも同期させたい場合はこちら "http://ogawa.s18.xrea.com/fswiki/wiki.cgi?page=Vim%A4%CE%A5%E1%A5%E2 "nnoremap :set scrollbind! " tab page {{{1 " ============================================================================ " いつタブページのラベルを表示するかを指定する。 " 0: 表示しない " 1: 2個以上のタブページがあるときのみ表示 " 2: 常に表示 set showtabline=1 " 一番右にタブを作る " nnoremap :tablast tabnew nnoremap :tabnew nnoremap :tabn nnoremap :tabp nnoremap gt nnoremap gT nnoremap :1tabn nnoremap :2tabn nnoremap :3tabn nnoremap :4tabn nnoremap :5tabn nnoremap :6tabn nnoremap :7tabn nnoremap :8tabn nnoremap :9tabn nnoremap :10tabn " [【vim】タブを自由に移動させる | blog.remora.cx](http://blog.remora.cx/2012/10/move-tab-in-vim.html) " Command-line mode {{{1 " ============================================================================ "コマンド入力時にTabを押すと補完メニューを表示する。決定したい時は文字を打つか、ctrl-eなど。 set wildmenu " コマンドモードの補完をシェルの補完のような動きにする " で共通する最長の文字列まで補完して一覧表示 " 再度を打つと候補を選択。で逆 " 決定したい時は文字を打つか、ctrl-eなど。 set wildmode=list:longest,full " 保存する履歴の数 set history=10000 "前方一致をCtrl+PとCtrl+Nで cnoremap cnoremap cnoremap cnoremap nnoremap Q q: " vim-emacscommandlineでは右に進むになっているので、 " コマンドラインウィンドウを開きたいときはにする cnoremap " 外部コマンド実行でエイリアスを使うための設定 " http://sanrinsha.lolipop.jp/blog/2013/09/vim-alias.html " bashスクリプトをquickrunで実行した時にエイリアス展開されてしまうのでコメント " アウト " let $BASH_ENV=expand('~/.bashenv') " let $ZDOTDIR=expand('~/.vim/') " }}} " cmdline-window {{{ " ============================================================================ " http://vim-users.jp/2010/07/hack161/ " nnoremap (command-line-enter) q: " xnoremap (command-line-enter) q: " nnoremap (command-line-norange) q: " " nmap : (command-line-enter) " xmap : (command-line-enter) autocmd MyVimrc CmdwinEnter * call s:init_cmdwin() function! s:init_cmdwin() nnoremap q :quit nnoremap :quit inoremap pumvisible() ? "\\" : "\" " inoremap pumvisible() ? "\\" : "\" " inoremap pumvisible() ? "\\" : "\" " Completion. inoremap pumvisible() ? "\" : "\" inoremap pumvisible() ? "\" : "\\" startinsert! endfunction " }}} " ビジュアルモード {{{1 " ============================================================================= " ビジュアル矩形モードでなくても、IやAで挿入できるようにする {{{ " ----------------------------------------------------------------------------- " http://labs.timedia.co.jp/2012/10/vim-more-useful-blockwise-insertion.html vnoremap I force_blockwise_visual('I') vnoremap A force_blockwise_visual('A') function! s:force_blockwise_visual(next_key) if mode() ==# 'v' return "\" . a:next_key elseif mode() ==# 'V' return "\0o$" . a:next_key else " mode() ==# "\" return a:next_key endif endfunction " 最後に変更したテキスト(ペーストした部分など)を選択 " ---------------------------------------------------------------------------- nnoremap gm `[v`] vnoremap gm :normal gm onoremap gm :normal gm "}}} "}}} " :terminal {{{1 " ============================================================================= if has('terminal') for i in range(32,126) let c = nr2char(i) " set =\\ 他のsetに影響する? " set はインサートモードから抜けて、コマンド打つときに引っかかる " set >=\> >に対してsetできない " set =\P \ePは制御シーケンスで使用するためsetしない " set =\[ これがあるとvim起動した後、2cが打たれる let skip_chars = [' ', ':', '>', 'P', '[', '"'] " E33がでるので~をescapeする if match(skip_chars, escape(c, '~')) >= 0 continue endif let c = escape(c, '|') " シングルクォートだとと\が文字列になってしまうでダブルクォートで設定 execute 'tnoremap '.c endfor tnoremap :tabnew tnoremap :tabnext tnoremap :tabprevious tnoremap :1tabn tnoremap :2tabn tnoremap :3tabn tnoremap :4tabn tnoremap :5tabn tnoremap :6tabn tnoremap :7tabn tnoremap :8tabn tnoremap :9tabn tnoremap :10tabn tnoremap [ N tnoremap ; N tnoremap . " tnoremap q :bdelete! function! s:terminal_new(args) abort try " ディレクトリに権限がない時は失敗する execute 'lcd ' . my#path#buffer_dir() catch /E472/ endtry " execute "botright terminal ++rows=12" a:args execute "botright terminal" a:args endfunction function! s:terminal_open(args) abort if empty(term_list()) call s:terminal_new(a:args) else execute 'sbuffer ' . term_list()[0] endif endfunction set switchbuf=usetab command! -nargs=* TerminalNew call s:terminal_new() " すでに :terminal が存在していればその :terminal を使用する command! -nargs=* TerminalOpen call s:terminal_open() nnoremap tn :TerminalNew nnoremap to :TerminalOpen noremap !! :terminal ++close " - Vim で :terminal の使い勝手をよくした - Secret Garden(Instrumental) " http://secret-garden.hatenablog.com/entry/2017/11/14/113127 " - Vim :drop for :buffer - jump to window if buffer is already open with tab autocomplete - Stack Overflow " https://stackoverflow.com/questions/28392784/vim-drop-for-buffer-jump-to-window-if-buffer-is-already-open-with-tab-autoco endif " complete {{{1 " ============================================================================ inoremap pumvisible() ? "\" : "\" inoremap pumvisible() ? "\" : "\" " ポップアップメニューをで消す inoremap pumvisible() ? "\" : "\" " previewしない set completeopt-=preview if MyHasPatch('patch-7.4.775') " insert,selectしない " set completeopt+=noinsert,noselect endif if has("patch-7.4.314") set shortmess+=c endif " cd, file, diretory, path {{{1 " ============================================================================ " gfなどでファイルを探索するパスに、ファイルのディレクトリからルートディレクトリまでを追加する set path+=./;/ " cd {{{2 " ---------------------------------------------------------------------------- "augroup CD " autocmd! " autocmd BufEnter * execute ":lcd " . expand("%:p:h") "augroup END " 現在編集中のファイルのディレクトリをカレントディレクトリにする nnoremap [:space:]gc :cd =my#path#buffer_dir() echo 'cd '.my#path#buffer_dir() nnoremap [:space:]gC :cd =my#path#project_dir() echo 'cd ' my#path#project_dir() nnoremap [:space:]Gc :windo cd =my#path#buffer_dir() nnoremap [:space:]GC :windo cd =my#path#project_dir() command! Shell lcd %:h shell " pathの情報を挿入したり、レジストリに書き込むmapの設定 {{{2 " ---------------------------------------------------------------------------- function! s:set_map_registers(map_key, expr) abort execute 'inoremap ' . a:map_key . ' =' . a:expr . '' execute 'cnoremap ' . a:map_key . ' =' . a:expr . '' execute 'nnoremap y' . a:map_key . ' :let @" = ' . a:expr . ' echo "yanked: " . @"' execute 'nnoremap [:space:]y' . a:map_key . ' :let @* = ' . a:expr . ' echo "copied: " . @*' endfunction " file name " call s:set_map_registers('f', 'my#path#buffer("")') call s:set_map_registers('f', 'my#path#buffer(":t")') " full path of file call s:set_map_registers('F', 'my#path#buffer(":p")') " path of directory call s:set_map_registers('d', 'my#path#buffer(":h") . "/"') " full path of directory call s:set_map_registers('D', 'my#path#buffer_dir() . "/"') " project relative path call s:set_map_registers('p', 'my#path#project_relative_path("")') call s:set_map_registers('P', 'my#path#project_relative_path(":h")') " yank Hugo用のMarkdownのリンク call s:set_map_registers('h', 'my#hugo_ref(my#path#buffer(":p"))') " Rename {{{2 " ---------------------------------------------------------------------------- " Vim-users.jp - Hack #17: Vimを終了することなく編集中ファイルのファイル名を変更する " http://vim-users.jp/2009/05/hack17/ " command! -nargs=1 -complete=file Rename f |call delete(expand('#')) " 上のコマンドだとパーミッションは引き継がれないので、mvで処理するようにする。 command! -nargs=1 -complete=file Rename call s:move(expand('%'), '') function! s:move(src, dest) call system('mv '.a:src.' '.a:dest) execute 'e '.a:dest bdelete # endfunction " TODO: rename()を試す " Resolve {{{2 " ---------------------------------------------------------------------------- " リンクの実体で開き直す command! Resolve call s:resolve_edit() function! s:resolve_edit() abort let l:file = resolve(expand('%')) new bwipeout # execute 'edit '.l:file endfunction " Vim-users.jp - Hack #202: 自動的にディレクトリを作成する {{{2 autocmd MyVimrc BufWritePre * call s:auto_mkdir(expand(':p:h'), v:cmdbang) function! s:auto_mkdir(dir, force) if !isdirectory(a:dir) && (a:force || \ input(printf('"%s" does not exist. Create? [y/N]', a:dir)) =~? '^y\%[es]$') call mkdir(iconv(a:dir, &encoding, &termencoding), 'p') endif endfunction " ctags {{{1 " ============================================================================ if has('path_extra') set tags+=~/tags/*.tags endif nnoremap g] :tab stj =expand('') function! s:ctags(dir) call system('ctags -R -f ~/tags "'.fnamemodify(a:dir, ':p').'" &') " call system('ctags.sh -d ~/tags --tag-relative=yes -R --append=yes --exclude=.git"'.fnamemodify(a:dir, ':p').'" &') endfunction command! -nargs=1 -complete=file Ctags call s:ctags('') " Gitリポジトリ以下のときに、保存するたびにctagsを実行 {{{2 " ---------------------------------------------------------------------------- " [GitのhookでCtagsを実行する | SanRin舎](http://sanrinsha.lolipop.jp/blog/2014/04/git-hook-ctags.html) autocmd MyVimrc BufWritePost * \ if exists('b:git_dir') && executable(b:git_dir.'/hooks/ctags') | \ call system('"'.b:git_dir.'/hooks/ctags" &') | \ endif " tagsの設定 {{{2 " ---------------------------------------------------------------------------- autocmd MyVimrc FileType * call s:configure_tag() function! s:configure_tag() if (!empty(&buftype) && &buftype !=# 'help') || &filetype ==# 'java' return endif if &filetype =~# '^\(vim\|help\)$' execute 'setlocal tags+=' . g:dein_dir . '/repos/**/.git/tags' " globpathの引数が4つまでになるのは7.4.279以上 " [Vim script言語仕様の変更 · rbtnn/vimscript Wiki](https://github.com/rbtnn/vimscript/wiki/Vim-script%E8%A8%80%E8%AA%9E%E4%BB%95%E6%A7%98%E3%81%AE%E5%A4%89%E6%9B%B4) " execute 'setlocal tags+='.join(globpath(&runtimepath, '.git/tags', 0, 1), ',') " execute 'setlocal tags+='.substitute(globpath(&runtimepath, '.git/tags', 0), "\", ',', 'g') endif " とりあえず、fugitiveが設定してくれるので任す " let ft = (&filetype == 'help') ? 'vim' : &filetype " execute 'setlocal tags+=' . b:git_dir . '/tags/' . ft . '.tags' " nnoremap :UniteWithCursorWord -immediately tag endfunction " tagsにその都度個別に追加する版 {{{3 " 全部tagsに追加しても遅くないのと#使ってないものが検索できないのでやめた " " helpやfiletypeがjavaのとき以外 " " autocmd MyVimrc FileType * " \ if empty(&buftype) && &filetype != 'java' " \| nnoremap :MyUniteTag " \| endif " " function! s: " if &filetype == 'vim' " " quickrun#is_runnig()などの上でしたときにquickrunリポジトリ " " の.git/tagsをtagsに追加する。 " let plugin_name = matchstr(expand(''), '[^#]\+\ze#') " if plugin_name != '' " " execute 'setlocal tags+='.substitute(globpath(&runtimepath, 'autoload/'.plugin_name.'.vim'), 'autoload/'.plugin_name.'.vim', '.git/tags', '') " endif " endif " UniteWithCursorWord -immediately tag " endfunction " command! MyUniteTag call s: " tsukkee/unite-tag {{{2 " ---------------------------------------------------------------------------- nnoremap [unite]t :Unite tag " let g:unite_source_tag_max_fname_length = 1000 " let g:unite_source_tag_max_name_length = 100 " let g:unite_source_tag_strict_truncate_string = 0 " crypt {{{1 " ============================================================================ " [Using VIM as Your Password Manager - Stelfox Athenæum](http://stelfox.net/blog/2013/11/using-vim-as-your-password-manager/) " 暗号化して保存するためには " :set cryptmethod=blowfish2 (Vim 7.4.399以前はblowfish) " :X " has('crypt-blowfish'), has('crypt-blowfish2')で使用できる暗号化アルゴリズムを確認できる autocmd MyVimrc BufReadPost * \ if &key != "" \ | setlocal noswapfile nowritebackup noshelltemp secure \ | endif " man {{{1 " ============================================================================ " runtime ftplugin/man.vimで使えるManコマンドは " - macでのManの調子が悪い " - 補完がきかない " のでvim-refの:Ref manを使うことにする " [vim-utils/vim-man: View and grep man pages in vim](https://github.com/vim-utils/vim-man) " はオリジナルのman.vimを改変したもので、補完は効くようになったが、cuiのmacvimでうまくいかない " :Man でマニュアルを開く " http://vim.wikia.com/wiki/Using_vim_as_a_man-page_viewer_under_Unix " [manをVimで見る - rcmdnk's blog](http://rcmdnk.github.io/blog/2014/07/20/computer-vim/) " runtime ftplugin/man.vim " nmap K K " let $PAGER='' " コマンドラインでmanを使ったとき、vimの:Manで見るようにするためには ".zshrc .bashrc等にも記述が必要 cabbrev Man Ref man " printing {{{1 " ============================================================================ set printoptions=wrap:y,number:y,header:0 set printfont=Andale\ Mono:h12:cUTF8 " errorformat, quickfix, make {{{1 " ============================================================================ set errorformat+=%f:\ line\ %l:\ %m set errorformat+=%f:\ 行\ %l:\ %m set errorformat+=%f:\ %l\ 行:\ %m set errorformat-=%-G%.%# nmap [q (QuickFixCurrentNumberQPrev) nmap ]q (QuickFixCurrentNumberQNext) nnoremap [Q :cprevious nnoremap ]Q :cnext noremap [:quickfix:] nmap q [:quickfix:] noremap [:quickfix:]c :cexpr [] QfstatuslineUpdate noremap [:quickfix:]o :botright copen noremap [:quickfix:]q :cclose nnoremap [L :lprevious nnoremap ]L :lnext noremap [*location] nmap l [*location] noremap [*location]o :lopen noremap [*location]q :lclose " 現在のカーソル位置の次/前のquickfix/location listに飛ぶにはQuickFixCurrentNumberを使う " http://www.vim.org/scripts/script.php?script_id=4449 " show quickfix automatically {{{2 " ---------------------------------------------------------------------------- " これをやるとneocomlcacheの補完時にquickfix winodow(中身はtags)が開くのでコメントアウト " autocmd MyVimrc QuickfixCmdPost * if !empty(getqflist()) | botright cwindow | botright lwindow | endif " quickfixの高さを最小にする {{{2 " ---------------------------------------------------------------------------- " Automatically fitting a quickfix window height - Vim Tips Wiki " http://vim.wikia.com/wiki/Automatically_fitting_a_quickfix_window_height " autocmd MyVimrc FileType qf call s:adjust_qf_window_height(1, 12) " function! s:adjust_qf_window_height(minheight, maxheight) " let l:l = 1 " let l:n_lines = 0 " let l:w_width = winwidth(0) " while l:l <= line('$') " " number to float for division " let l:l_len = strlen(getline(l:l)) + 0.0 " let l:line_width = l:l_len/l:w_width " let l:n_lines += float2nr(ceil(l:line_width)) " let l:l += 1 " endw " execute max([min([l:n_lines, a:maxheight]), a:minheight]) . 'wincmd _' " endfunction " errorformatの確認のための関数 {{{2 " ---------------------------------------------------------------------------- " Vim - errorformatについて(入門編) - Qiita " function! ErrFmtTest(errfmt,lines) let l:temp_errorformat = &errorformat try let &errorformat = a:errfmt cexpr join(a:lines,"\n") copen catch echo v:exception echo v:throwpoint finally let &errorformat = l:temp_errorformat endtry endfunction " QfMessages {{{2 " ---------------------------------------------------------------------------- " Vim script でエラーが出た時のmessagesのエラー箇所に飛ぶ function! s:qf_messages() let str_messages = '' redir => str_messages silent! messages redir END let qflist = s:parse_error_messages(str_messages) call setqflist(qflist, 'r') botright cwindow endfunction function! s:parse_error_messages(messages) abort " 戻り値。setqflistの引数に使う配列 let qflist = [] " qflistの要素になる辞書 let qf_info = {} " qflistの要素となる辞書の配列。エラー内容がスタックトレースのときに使用 let qf_info_list = [] " 読み込んだファイルの内容をキャッシュしておくための辞書 let files = {} if v:lang =~# 'ja_JP' let regex_error_detect = '^.\+\ze の処理中にエラーが検出されました:$' let regex_line = '^行\s\+\zs\d\+\ze:$' let regex_last_set = '最後にセットしたスクリプト: \zs\f\+' else let regex_error_detect = '^Error detected while processing \zs.\+\ze:$' let regex_line = '^line\s\+\zs\d\+\e:$' let regex_last_set = 'Last set from \zs\f\+' endif for line in split(a:messages, "\n") if line =~# regex_error_detect " ... の処理中にエラーが検出されました:' let matched = matchstr(line, regex_error_detect) if matched =~# '^function' " function 253_fuga の処理中にエラーが検出されました: " function 253_piyo[1]..253_fuga の処理中にエラーが検出されました: let matched = matchstr(matched, '^function \zs\S*') let stacks = reverse(split(matched, '\.\.')) for stack in stacks let [func_name, offset] = (stack =~# '\S\+\[\d') \ ? matchlist(stack, '\(\S\+\)\[\(\d\+\)\]')[1:2] \ : [stack, 0] " 辞書関数の数字は{}で囲む let func_name = func_name =~# '^\d\+$' ? '{' . func_name . '}' : func_name redir => verbose_func execute 'silent verbose function ' . func_name redir END let filename = matchstr(verbose_func, regex_last_set) let filename = expand(filename) if !has_key(files, filename) let files[filename] = readfile(filename) endif if func_name =~# '{\d\+}' let func_lines = split(verbose_func, "\n") unlet func_lines[1] let max_line = len(func_lines) let func_lines[0] = '^\s*fu\%[nction]!\=\s\+\zs\S\+\.\S\+' for i in range(1, max_line - 2) let func_lines[i] = '^\s*' . matchstr(func_lines[i], '^\d\+\s*\zs.*') endfor let func_lines[max_line - 1] = '^\s*endf[unction]' let lnum = 0 while 1 let lnum = match(files[filename], func_lines[0], lnum) if lnum < 0 throw 'No dictionary function' endif let find_dic_func = 1 for i in range(1, max_line - 1) if files[filename][lnum + i] !~# func_lines[i] let lnum = lnum + i let find_dic_func = 0 break endif endfor if find_dic_func break endif endwhile let func_name = matchstr(files[filename][lnum], func_lines[0]) let lnum += 1 + offset else let func_name = substitute(func_name, '\d\+_', 's:', '') let lnum = match(files[filename], '^\s*fu\%[nction]!\=\s\+' . func_name) + 1 + offset endif call add(qf_info_list, { \ 'filename': filename, \ 'lnum': lnum, \ 'text': func_name, \}) endfor else " の処理中にエラーが検出されました: let filename = expand(matchstr(line, regex_error_detect)) let qf_info.filename = expand(filename) endif elseif line =~# regex_line " 行 1: let lnum = matchstr(line, regex_line) if len(qf_info_list) > 0 let qf_info_list[0]['lnum'] += lnum else let qf_info.lnum = lnum endif elseif line =~# '^E' " E492: エディタのコマンドではありません: one let [nr, text] = matchlist(line, '^E\(\d\+\): \(.\+\)')[1:2] if len(qf_info_list) > 0 if len(qf_info_list) == 1 let qf_info_list[0]['nr'] = nr let qf_info_list[0]['text'] = 'in ' . qf_info_list[0]['text'] . ' | ' . text else let i = 0 for val in qf_info_list let val['nr'] = nr let val['text'] = '#' . i . ' in ' . val['text'] . (i == 0 ? (' | ' . text) : '') let i += 1 endfor endif let qflist += qf_info_list else let qf_info.nr = nr let qf_info.text = text call add(qflist, qf_info) endif let qf_info = {} let qf_info_list = [] endif endfor return qflist endfunction command! -nargs=0 QfMessages call s:qf_messages() nnoremap [:quickfix:]m :QfMessages " 参考サイト " * [Vim scriptをsourceしてエラーがあればquickfixに表示する - ぼっち勉強会](http://kannokanno.hatenablog.com/entry/20120723/1343147069) " Ip2host {{{1 " ============================================================================ function! s:Ip2host(line1, line2) for l:linenum in range(a:line1, a:line2) let l:oldline = getline(l:linenum) let l:newline = substitute(l:oldline, \ '\v((%(2%([0-4]\d|5[0-5])|1\d\d|[1-9]?\d)\.){3}%(2%([0-4]\d|5[0-5])|1\d\d|[1-9]?\d))', \ '\=substitute(system("nslookup ".submatch(1)), "\\v.*%(name = |: )([0-9a-z-.]+).*", "\\1","")', \ '') call setline(l:linenum, l:newline) endfor endfunction command! -range=% Ip2host call s:Ip2host(, ) " filetype {{{1 " ============================================================================ nnoremap [FILETYPE] nmap F [FILETYPE] nnoremap [FILETYPE]d :setlocal filetype=diff nnoremap [FILETYPE]h :setlocal filetype=html nnoremap [FILETYPE]j :setlocal filetype=javascript nnoremap [FILETYPE]m :setlocal filetype=markdown nnoremap [FILETYPE]ph :setlocal filetype=php nnoremap [FILETYPE]py :setlocal filetype=python nnoremap [FILETYPE]R :setlocal filetype=r nnoremap [FILETYPE]s :setlocal filetype=sql nnoremap [FILETYPE]s :setlocal filetype=sql nnoremap [FILETYPE]sh :let b:sql_type_overrride = 'hive' setlocal filetype=sql nnoremap [FILETYPE]v :setlocal filetype=vim nnoremap [FILETYPE]x :setlocal filetype=xml " プラグインなどで変更された設定をグローバルな値に戻す " *.txtでtextwidth=78されちゃう " [vimrc_exampleのロードのタイミング - Google グループ](https://groups.google.com/forum/#!topic/vim_jp/Z_3NSVO57FE "vimrc_exampleのロードのタイミング - Google グループ") autocmd MyVimrc FileType vim,text,markdown call s:override_plugin_setting() " autocmd MyVimrc FileType vim,text call s:override_plugin_setting() function! s:override_plugin_setting() setlocal textwidth< setlocal textwidth=0 setlocal formatoptions< endfunction " HTML {{{2 " ---------------------------------------------------------------------------- function! s:live_reload(dir) abort if !executable('livereloadx') if input('livereloadx is not installed. npm -g install livereloadx? [y/N]') =~? '^y\%[es]$' if !executable('npm') echo 'npm is not found' return endif !npm -g install livereloadx else return endif endif let sub = vimproc#popen2('livereloadx --include ''*.md'' -s '.a:dir) augroup LiveReload execute 'autocmd LiveReload VimLeavePre * call vimproc#kill('.sub.pid.', 15)' augroup END call vimproc#popen2('open -a Google\ Chrome http://localhost:35729/'.expand('%:t:r').'.html') endfunction command! LiveReloadBufferDir call s:live_reload(expand('%:p:h')) command! LiveReloadProjectDir call s:live_reload(my#path#project_dir()) " JavaScript {{{2 " ---------------------------------------------------------------------------- autocmd MyVimrc FileType javascript call s:configure_javascript() function! s:configure_javascript() setlocal syntax=jquery " .を入れたほうがneocompleteの補完がうまくいく " setlocal iskeyword+=. endfunction " Vim {{{2 " ---------------------------------------------------------------------------- " \を打った時のindentの幅 " let g:vim_indent_cont = &sw let g:vim_indent_cont = 0 " http://vim-users.jp/2009/09/hack74/ " .vimrcと.gvimrcの編集 nnoremap [VIM] nmap v [VIM] execute 'nnoremap [VIM]e :edit '.s:dotfiles_home.'/.vim/vimrc' execute 'nnoremap [VIM]E :edit '.s:dotfiles_home.'/.vim/gvimrc' execute 'nnoremap [VIM]b :edit '.s:dotfiles_home.'/.vim/rc/neobundle.vim' execute 'nnoremap [VIM]p :edit '.s:dotfiles_home.'/.vim/rc/plugin.vim' execute 'nnoremap [VIM]d :edit '.s:dotfiles_home.'/.vim/rc/dein.vim' " vimrcの実体を開く。systemだと最後にが入ってうまくいかない " execute 'nnoremap [VIM]l :edit '.substitute(system('readlink ~/.vim/rc/local.vim'), "\", '', '').'' execute 'nnoremap [VIM]l :edit '.resolve(expand('~/.vim/rc/local.vim')).'' " Load .gvimrc after .vimrc edited at GVim. nnoremap [VIM]r :new \| source $MYVIMRC \| if has('gui_running') \| source $MYGVIMRC \| endif \| q \| echo 'vimrc reloaded!' ""vimrc auto update "augroup MyAutoCmd " autocmd! " " nested: autocmdの実行中に更に別のautocmdを実行する " autocmd BufWritePost .vimrc nested source $MYVIMRC " " autocmd BufWritePost .vimrc RcbVimrc "augroup END " autocmd MyVimrc BufWritePost *.vim " \ if filereadable(expand('%')) " \| source % " \| endif " vimperator {{{2 " ---------------------------------------------------------------------------- autocmd MyVimrc FileType vimperator \ setlocal comments=:\" " help {{{2 " ---------------------------------------------------------------------------- " set helplang=en,ja autocmd MyVimrc FileType help call s:setting_help() function! s:setting_help() nnoremap K nnoremap q :q " nnoremap ]] /.* nnoremap ] /.* nnoremap [[ ?.* nnoremap [ ?.* nnoremap ]' /'.*' nnoremap [' /'.*' | " デフォルトは!-~,^*,^|,^",192-255だが()を外したい。 " -=()が効かない? setlocal iskeyword=!-39,42-~,^*,^\|,^\",192-255 endfunction " memo {{{1 " ============================================================================ function! s:memo_new(base_dir) abort let prefix = strftime('%Y/%m/') let filename = input('Input file name: ', prefix) if filename == '' return endif let filename = a:base_dir . '/' . filename let dir = fnamemodify(filename, ':h') if !isdirectory(dir) call mkdir(dir, 'p') endif execute 'new ' fnameescape(filename) endfunction let g:memo_directory = expand('~/Dropbox/memo/content') command! MemoNew call s:memo_new(g:memo_directory) command! MemoDiaryNew call s:memo_new(g:memo_directory . '/diary') nnoremap mn :MemoNew nnoremap md :MemoDiaryNew nnoremap [unite]fM :execute 'Unite mtime:' . g:memo_directory nnoremap [unite]gM :execute 'Unite grep:'.g:memo_directory " Hugo {{{1 " ============================================================================ let g:hugo_directory = $SRC_ROOT.'/github.com/tmsanrinsha/site' let g:hugo_post_directory = g:hugo_directory . '/content/post' command! HugoNew call s:memo_new(g:hugo_post_directory) function! s:hugo_get_path() abort let matches = matchlist(expand('%:p:r'), '\([^/]\+/[^/]\+/[^/]\+/\)\([^/]\+\)$') return matches[1] . system('encode_uri', matches[2]) endfunction function! s:hugo_preview() abort let result = system("ps | grep 'hugo server --watch --buildDrafts=tru[e]'") if result == '' call system("$HOME/src/github.com/tmsanrinsha/site/deploy.sh -D 1> $HOME/logs/hugo.log 2>&1 &") endif call openbrowser#open('http://localhost:1313/' . s:hugo_get_path()) endfunction function! s:hugo_open() abort call openbrowser#open('https://tmsanrinsha.net/' . s:hugo_get_path()) endfunction nnoremap [:hugo:] nmap h [:hugo:] nnoremap [:hugo:]n :HugoNew nnoremap [:hugo:]p :call hugo_preview() nnoremap [:hugo:]o :call hugo_open() nnoremap [:hugo:]d :QuickRun -type sh -srcfile =g:hugo_directory/deploy.sh nnoremap [unite]fh :Unite mtime:=g:hugo_post_directory nnoremap [unite]gh :Unite grep:=g:hugo_post_directory " }}} if !has('gui_running') call SourceRc('non-gui.vim') endif " plugin load {{{1 " ============================================================================ let g:dein_repo_dir = g:dein_dir . '/repos/github.com/Shougo/dein.vim' if isdirectory(g:dein_repo_dir) call SourceRc('dein.vim') elseif IsInstalled('neobundle.vim') call SourceRc('neobundle.vim') call SourceRc('plugin.vim') else " bundle以下にあるpluginをいくつかruntimepathへ追加する " let s:load_plugin_list = [ " \ 'sudo.vim', 'my_molokai', 'vim-smartword' " \] " " for path in split(glob($HOME.'/.vim/bundle/*'), '\n') " " let s:plugin_name = matchstr(path, '[^/]\+$') " " if isdirectory(path) && index(s:load_plugin_list, s:plugin_name) >= 0 " " let &runtimepath = &runtimepath.','.path " " end " " endfor " for s:plugin in s:load_plugin_list " if isdirectory($HOME.'/.vim/bundle/'.s:plugin) " let &runtimepath = &runtimepath . ',' . g:dein_dir . '/repos/github.com/vim-scripts/sudo.vim' " endif " endfor " let &runtimepath = &runtimepath . ',' . g:dein_dir . '/repos/github.com/vim-scripts/sudo.vim' " nnoremap W :w sudo:% filetype plugin indent on endif if has('win32') && has('kaoriya') set runtimepath+=$VIM/plugins/vimproc endif " search, substitute {{{1 " ============================================================================ " インクリメンタルサーチ set incsearch " 検索パターンの大文字小文字を区別しない set ignorecase " 検索パターンに大文字が含まれていたら、大文字小文字を区別する。 set smartcase set hlsearch "検索結果をハイライト " ESCキー2度押しでハイライトのトグル nnoremap :set hlsearch! if IsInstalled('vim-asterisk') nmap n (anzu-n) nmap N (anzu-N) map * (asterisk-z*)(anzu-update-search-status) map # (asterisk-gz*)(anzu-update-search-status) let g:asterisk#keeppos = 1 " /で検索語句を入力してEnter押した直後にunite.vimを使うとhighlightがなくなる " denite.nvimなら大丈夫かも " map / (incsearch-forward) " map ? (incsearch-backward) " " map g/ (incsearch-stay) " " augroup incsearch-keymap " autocmd! " autocmd VimEnter * call s:incsearch_keymap() " augroup END " function! s:incsearch_keymap() " IncSearchNoreMap (incsearch-next) " IncSearchNoreMap (incsearch-prev) " endfunction " " let g:incsearch#emacs_like_keymap = 1 else nnoremap * *N nnoremap # g*N " /で検索しても、?で検索してもnで前方検索、Nで後方検索 " http://deris.hatenablog.jp/entry/2014/05/20/235807 nnoremap n search_forward_p() ? 'n' : 'N' nnoremap N search_forward_p() ? 'N' : 'n' vnoremap n search_forward_p() ? 'n' : 'N' vnoremap N search_forward_p() ? 'N' : 'n' function! s:search_forward_p() return exists('v:searchforward') ? v:searchforward : 1 endfunction endif " バックスラッシュやクエスチョンを状況に合わせ自動的にエスケープ cnoremap / getcmdtype() == '/' ? '\/' : '/' cnoremap ? getcmdtype() == '?' ? '\?' : '?' cnoremap \/ getcmdtype() == '/' ? '/' : '\/' cnoremap \? getcmdtype() == '?' ? '?' : '\?' "ヴィビュアルモードで選択した範囲だけ検索 xnoremap / /\%V xnoremap ? ?\%V " rename nmap [:space:]r #:%s/////gc vmap [:space:]r #://gc%s/// " , {{{1 " ============================================================================ if IsInstalled('yankround.vim') && IsInstalled('QuickFixCurrentNumber') nmap yankround#is_active() ? "\(yankround-prev)" : "\(QuickFixCurrentNumberQPrev)" nmap yankround#is_active() ? "\(yankround-next)" : "\(QuickFixCurrentNumberQNext)" endif " emacs keybind {{{1 " ============================================================================ " vim/gvim挿入モードのキーを若干Emacs風味にカスタマイズ - fudisti " - https://sites.google.com/site/fudist/Home/vim-nihongo-ban/tips/vim-key-emacs " コマンドラインモードはhttps://github.com/tmsanrinsha/vim-emacscommandline 参照 inoremap inoremap " inoremap " inoremap inoremap inoremap inoremap I inoremap if !IsInstalled('lexima.vim') inoremap " inoremap "\u".(col('.') == col('$') ? '^y$A=="' : '') endif " 元々のi_CTRL-Dは左にインデントする処理。 " 右にインデントするのがi_CTRL-Tなのでに設定する inoremap "カーソル位置から後の単語を削除 inoremap u=MyDeleteWord() """""""""""""""""""""""""""""" "カーソル以降の単語削除 """""""""""""""""""""""""""""" function! MyDeleteWord() if col('.') == col('$') return '' endif let save_cursor = getpos('.') silent exec 'normal! wge' if save_cursor[1] != line('.') || (save_cursor[2] > col('.')) call setpos('.', save_cursor) return MyExecExCommand('normal! dw', 'onemore') endif silent exec 'normal! v' call setpos('.', save_cursor) return MyExecExCommand('normal! d') endfunction """""""""""""""""""""""""""""" "IMEの状態とカーソル位置保存のためを使用してコマンドを実行。 """""""""""""""""""""""""""""" function! MyExecExCommand(cmd, ...) let saved_ve = &virtualedit let index = 1 while index <= a:0 if a:{index} ==# 'onemore' silent setlocal virtualedit+=onemore endif let index = index + 1 endwhile silent exec a:cmd if a:0 > 0 silent exec 'setlocal virtualedit='.saved_ve endif return '' endfunction " neocomplcacheにて設定 " inoremap if !IsInstalled('neosnippet.vim') inoremap D endif inoremap u " * があるときにを打つと右にインデントしたい " →insertモードで打つと右にインデントできる " function! s:MyIndent() " if match(getline('.'), '^\s*\*') >= 0 " normal! >>A " else " execute "normal! i\" " endif " endfunction " command! MyIndent call s:MyIndent() " inoremap :MyIndent " インデントしない改行 " [vim-jp » Hack #57: 空行を挿入する](http://vim-jp.org/vim-users-jp/2009/08/15/Hack-57.html) " [空行を挿入する+α - derisの日記](http://deris.hatenablog.jp/entry/20130404/1365086716) nnoremap :call append(line('.'), '')j imap " syntax highlight, colorscheme {{{1 " ============================================================================ " 256色を使えるようにする set t_Co=256 " シンタックスハイライトを効かせる " markdownのファイルを開いた後にsytax enableをするとハイライトがおかしくなる。 " vimrcをリローダブルにするため、すでにシンタックスが効いているなら、syntax enableをしない if !exists('g:syntax_on') syntax enable endif if IsInstalled('my_molokai') " let g:molokai_original = 1 " let g:rehash256 = 1 let g:molokai_16_color = 1 colorscheme molokai-customized " colorscheme monokai endif " let g:solarized_termcolors=256 " let g:solarized_contrast = 'high' " colorscheme solarized " colorscheme pencil " 16色の色見本 " :so $VIMRUNTIME/syntax/colortest.vim " 新しいウィンドウを開き、全てのハイライトグループ名をそれぞれの色を使って表示 " :so $VIMRUNTIME/syntax/hitest.vim " カーソル以下のカラースキームの情報の取得 {{{2 " ---------------------------------------------------------------------------- " http://cohama.hateblo.jp/entry/2013/08/11/020849 function! s:get_syn_id(transparent) let l:synid = synID(line('.'), col('.'), 1) if a:transparent return synIDtrans(l:synid) else return l:synid endif endfunction function! s:get_syn_attr(synid) let l:name = synIDattr(a:synid, 'name') let l:ctermfg = synIDattr(a:synid, 'fg', 'cterm') let l:ctermbg = synIDattr(a:synid, 'bg', 'cterm') let l:guifg = synIDattr(a:synid, 'fg', 'gui') let l:guibg = synIDattr(a:synid, 'bg', 'gui') return { \ 'name': l:name, \ 'ctermfg': l:ctermfg, \ 'ctermbg': l:ctermbg, \ 'guifg': l:guifg, \ 'guibg': l:guibg \} endfunction function! s:get_syn_info() let l:baseSyn = s:get_syn_attr(s:get_syn_id(0)) echo 'name: ' . l:baseSyn.name . \ ' ctermfg: ' . l:baseSyn.ctermfg . \ ' ctermbg: ' . l:baseSyn.ctermbg . \ ' guifg: ' . l:baseSyn.guifg . \ ' guibg: ' . l:baseSyn.guibg let l:linkedSyn = s:get_syn_attr(s:get_syn_id(1)) echo 'link to' echo 'name: ' . l:linkedSyn.name . \ ' ctermfg: ' . l:linkedSyn.ctermfg . \ ' ctermbg: ' . l:linkedSyn.ctermbg . \ ' guifg: ' . l:linkedSyn.guifg . \ ' guibg: ' . l:linkedSyn.guibg endfunction command! SyntaxInfo call s:get_syn_info() " }}} " Rgb2xterm {{{2 " ---------------------------------------------------------------------------- " true color(#FF0000など)を一番近い256色の番号に変換する " http://d.hatena.ne.jp/y_yanbe/20080611 "" the 6 value iterations in the xterm color cube let s:valuerange = [ 0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF ] "" 16 basic colors let s:basic16 = [ [ 0x00, 0x00, 0x00 ], [ 0xCD, 0x00, 0x00 ], [ 0x00, 0xCD, 0x00 ], [ 0xCD, 0xCD, 0x00 ], [ 0x00, 0x00, 0xEE ], [ 0xCD, 0x00, 0xCD ], [ 0x00, 0xCD, 0xCD ], [ 0xE5, 0xE5, 0xE5 ], [ 0x7F, 0x7F, 0x7F ], [ 0xFF, 0x00, 0x00 ], [ 0x00, 0xFF, 0x00 ], [ 0xFF, 0xFF, 0x00 ], [ 0x5C, 0x5C, 0xFF ], [ 0xFF, 0x00, 0xFF ], [ 0x00, 0xFF, 0xFF ], [ 0xFF, 0xFF, 0xFF ] ] function! s:xterm2rgb(color) " 16 basic colors let l:r=0 let l:g=0 let l:b=0 if a:color<16 let l:r = s:basic16[a:color][0] let l:g = s:basic16[a:color][1] let l:b = s:basic16[a:color][2] endif " color cube color if a:color>=16 && a:color<=232 let l:color=a:color-16 let l:r = s:valuerange[(l:color/36)%6] let l:g = s:valuerange[(l:color/6)%6] let l:b = s:valuerange[l:color%6] endif " gray tone if a:color>=233 && a:color<=253 let l:r=8+(a:color-232)*0x0a let l:g=l:r let l:b=l:r endif let l:rgb=[l:r,l:g,l:b] return l:rgb endfunction " selects the nearest xterm color for a rgb value like #FF0000 function! s:rgb2xterm(color) let s:colortable=[] for l:c in range(0, 254) let l:color = s:xterm2rgb(l:c) call add(s:colortable, l:color) endfor let l:best_match=0 let l:smallest_distance = 10000000000 let l:r = eval('0x'.a:color[0].a:color[1]) let l:g = eval('0x'.a:color[2].a:color[3]) let l:b = eval('0x'.a:color[4].a:color[5]) for l:c in range(0,254) let l:d = pow(s:colortable[l:c][0] - l:r, 2) + pow(s:colortable[l:c][1] - l:g, 2) + pow(s:colortable[l:c][2] - l:b, 2) if l:d < l:smallest_distance let l:smallest_distance = l:d let l:best_match = l:c endif endfor return l:best_match endfunction command! -nargs=1 Rgb2xterm echo s:rgb2xterm() command! -nargs=1 Xterm2rgb echo s:xterm2rgb() " その他の参考になりそうな変換 " [xterm - Wikipedia, the free encyclopedia](https://en.wikipedia.org/wiki/Xterm) " [vim-coloresque/vim-coloresque.vim at master · gorodinskiy/vim-coloresque](https://github.com/gorodinskiy/vim-coloresque/blob/master/after/syntax/css/vim-coloresque.vim) " syntaxの遡る行数を上げる {{{2 " ---------------------------------------------------------------------------- " グローバルな設定では無いらしく、autocmd FileTypeで設定 " autocmd MyVimrc FileType html,markdown,php syntax sync minlines=500 maxlines=5000 autocmd MyVimrc FileType markdown syntax sync minlines=500 maxlines=5000 " :syntax syncでminmalとmaximalの値を確認できる " 参考 " [Big Sky :: 意外と知られていないvimのtips(開発に便利な設定)](http://mattn.kaoriya.net/software/vim/20070821175457.htm) " :h :syn-sync-maxlines " :h doxygen-syntax " let g:load_dosygen_syntax=1 " cursorlineは重いので必要なときだけ有効にする {{{2 " ---------------------------------------------------------------------------- " 'cursorline' を必要な時にだけ有効にする - 永遠に未完成 " set updatetime=100 " updatetimeミリ秒ごとにswapファイルが作られないようにswapファイルの設定を消す " あとswapファイルが度々作られて、表示がでるのがいやなのでnoswapにする set noswapfile " CursorHold を使って、setlocal cursorlineをするとj, kで短い行に行ったあと長い行にいったとき " にカラムが戻らないのでコメントアウト " augroup MyVimrc " " autocmd CursorMoved,CursorMovedI * call s:auto_cursorline('CursorMoved') " " autocmd CursorHold,CursorHoldI * call s:auto_cursorline('CursorHold') " " autocmd CursorMoved * call s:auto_cursorline('CursorMoved') " autocmd CursorHold * call s:auto_cursorline('CursorHold') " autocmd InsertEnter * call s:auto_cursorline('InsertEnter') " autocmd WinEnter * call s:auto_cursorline('WinEnter') " autocmd WinLeave * call s:auto_cursorline('WinLeave') " augroup END " " let s:cursorline_lock = 0 " function! s:auto_cursorline(event) " if &filetype ==# 'qf' || &diff " if &cursorline " setlocal nocursorline " endif " return " endif " " if a:event ==# 'WinEnter' " setlocal cursorline " let s:cursorline_lock = 2 " elseif a:event ==# 'WinLeave' " setlocal cursorline " elseif a:event ==# 'CursorMoved' " if s:cursorline_lock " if s:cursorline_lock > 1 " 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 " elseif a:event ==# 'InsertEnter' " setlocal nocursorline " endif " endfunction set cursorline autocmd MyVimrc WinEnter * \ if &filetype ==# 'qf' || &diff \| setlocal nocursorline \| else \| setlocal cursorline \| endif " diff {{{1 " ============================================================================ set diffopt+=vertical nnoremap [:diff:] nmap [:space:]d [:diff:] xnoremap [:diff:] xmap [:space:]d [:diff:] nnoremap [:diff:]t :diffthis nnoremap [:diff:]u :diffupdate nnoremap [:diff:]o :diffoff nnoremap [:diff:]T :windo diffthis nnoremap [:diff:]O :windo diffoff nnoremap [:diff:]s :vertical diffsplit nnoremap [:diff:]w :set diffopt+=iwhite nnoremap [:diff:]W :set diffopt-=iwhite nnoremap [:diff:]p :%diffput nnoremap [:diff:]g :%diffget xnoremap [:diff:]p :diffput xnoremap [:diff:]g :diffget " vimdiffでより賢いアルゴリズム (patience, histogram) を使う - Qiita {{{2 " ---------------------------------------------------------------------------- " http://qiita.com/takaakikasai/items/3d4f8a4867364a46dfa3 " https://github.com/fumiyas/home-commands/blob/master/git-diff-normal let s:git_diff_normal='git-diff-normal' " let s:git_diff_normal_opts=["--diff-algorithm=histogram"] " gitのバージョンが1.7だと--diff-algorithmが使えなかった let s:git_diff_normal_opts=['--patience'] function! GitDiffNormal() let args=[s:git_diff_normal] if &diffopt =~# 'iwhite' call add(args, '--ignore-all-space') endif call extend(args, s:git_diff_normal_opts) call extend(args, [v:fname_in, v:fname_new]) let cmd=join(args, ' ') . '>' . v:fname_out call system(cmd) endfunction autocmd MyVimrc FilterWritePre * \ if &diff && !exists('g:my_check_diff') \| if executable(s:git_diff_normal) && executable('git') \| set diffexpr=GitDiffNormal() \| endif \| let g:my_check_diff = 1 \| endif " DiffOrig {{{2 " ---------------------------------------------------------------------------- " Convenient command to see the difference between the current buffer and the " file it was loaded from, thus the changes you made. " Only define it when not defined already. " Revert with: ":delcommand DiffOrig". if !exists(":DiffOrig") command DiffOrig vert new | set bt=nofile | r ++edit # | 0d_ | diffthis \ | wincmd p | diffthis endif " diffchar.vim {{{2 " ---------------------------------------------------------------------------- " vimdiffで単語単位の差分表示: diffchar.vimが超便利 - Qiita " http://qiita.com/takaakikasai/items/0d617b6e0aed490dff35 if IsInstalled('diffchar.vim') let g:DiffUnit='Word3' " vimdiffで起動した時にdiffcharを有効にする " diffupdateした時にうまくいかない気がするのでコメントアウト " if &diff " autocmd MyVimrc VimEnter * %SDChar " endif " Gdiff使った時に自動的にdiffcharを有効にしたかったが、エラーが出るため断念 " autocmd MyVimrc BufEnter * " \ if &diff | " \ execute '%SDChar' | " \ endif endif " vim-singleton {{{1 " ============================================================================ if IsInstalled('vim-singleton') && has('gui_running') call singleton#enable() endif " sudo.vim {{{1 " ============================================================================== " sudo権限で保存する " http://sanrinsha.lolipop.jp/blog/2012/01/sudo-vim.html if IsInstalled('sudo.vim') nnoremap W :w sudo:% else nnoremap W :w !sudo tee % >/dev/null endif " vim-smartword {{{1 " ============================================================================== if IsInstalled('vim-smartword') map w (smartword-w) map b (smartword-b) map e (smartword-e) map ge (smartword-ge) map [:space:]w (smartword-basic-w) map [:space:]b (smartword-basic-b) map [:space:]e (smartword-basic-e) map [:space:]ge (smartword-basic-ge) endif " unite.vim {{{1 " ============================================================================ if IsInstalled('unite.vim') let g:unite_data_directory = $VIM_CACHE_DIR.'/unite' let g:unite_enable_start_insert = 1 " let g:unite_source_find_max_candidates = 1000 nnoremap [unite] nmap , [unite] " uniteの選択のカラー(color)をPmenuSelにする。uniteバッファ以外もCursorLineの色がPmenuSelになってしまう " augroup MyVimrc " autocmd Filetype unite hi! link CursorLine PmenuSel " autocmd BufLeave \[unite\]* highlight! link CursorLine NONE " augroup END " uniteウィンドウを閉じる " nmap [unite]q :UniteClose " UniteCloseではすべてのuniteのウィンドウを閉じてくれないので、以下を使う nmap [unite]q :call GotoWin('\[unite\]')(unite_all_exit) nnoremap , :call GotoWin('\[unite\]') " 前回のuniteの結果を表示する。このunite画面を終了後にカーソルが戻る位置も前回の起動した位置になってしまう nnoremap [unite], :UniteResume " バッファ nnoremap [unite]b :Unite buffer " ファイル内検索結果 nnoremap [unite]l :Unite line nnoremap [unite]: :Unite command " Unite output {{{2 " ------------------------------------------------------------------------ " Unite output:map {{{3 " unite-mappingではnormalのマッピングしか出ないので、すべてのマッピングを出力するようにする " http://d.hatena.ne.jp/osyo-manga/20130307/1362621589 nnoremap [unite]m :Unite output:mapmap!lmap -default-action=open " :h map-listing " ノーマル、ビジュアル、選択、オペレータ待機 " n ノーマル " v ビジュアル、選択 " s 選択 " x ビジュアル " o オペレータ待機 " ! 挿入、コマンドライン " i 挿入 " l 挿入、コマンドライン、Lang-Argでの ":lmap" マップ " c コマンドライン " * 再マップされません " & スクリプトローカルなマップだけが再マップされます " @ バッファローカルなマップです。 " Unite output:message {{{3 " [unite-messages をつくってみる - C++でゲームプログラミング](http://d.hatena.ne.jp/osyo-manga/20131030/1383144724) " :messagesの最後をunite.vimで表示する nnoremap [unite]Om :Unite output:messages -log -buffer-name=messages -no-start-insert " Unite output:autocmd {{{3 nnoremap [unite]Oa :Unite output:autocmd " Unite outputでruntimpathを出力する {{{3 nnoremap [unite]Or :Unite output:echo\ join(split(&runtimepath,','),\"\\n\") " Unite directory {{{2 " ------------------------------------------------------------------------ " カレントディレクトリ以下のディレクトリ nnoremap [unite]dc :Unite directory " カレントバッファのディレクトリ以下 nnoremap [unite]d. :execute "Unite directory:" . my#path#buffer_dir() nnoremap [unite]dp :execute "Unite directory:" . my#path#project_dir() nnoremap [unite]dd :Unite directory:$SRC_ROOT/github.com/tmsanrinsha/dotfiles nnoremap [unite]dv :Unite directory:$SRC_ROOT/github.com/tmsanrinsha/dotfiles/home/.vim nnoremap [unite]dV :Unite directory:$VIM nnoremap [unite]db :Unite directory:$HOME/.vim/bundle nnoremap [unite]da :Unite directory:/Applications directory:$HOME/Applications " Unite file(_rec) {{{2 " ------------------------------------------------------------------------ " プロジェクトディレクトリ以下のファイル " こちらのコマンドだと、カレントディレクトリがあるプロジェクトディレクトリ以下 " nnoremap [unite]fp :Unite file_rec:! " こちらのコマンドだと、カレントバッファのファイルがあるプロジェクトディレクトリ以下 nnoremap [unite]fp :call unite_file_project('-start-insert') function! s:unite_file_project(...) let l:opts = (a:0 ? join(a:000, ' ') : '') let l:project_dir = my#path#project_dir() call unite#custom#source( \ 'neomru/file', 'matchers', \ ['matcher_project_files', 'matcher_context']) if isdirectory(l:project_dir.'/.git') execute 'lcd '.l:project_dir execute 'Unite '.opts.' neomru/file file_rec/git:--cached:--others:--exclude-standard' else execute 'Unite '.opts.' neomru/file file_rec/async:'.l:project_dir endif call unite#custom#source( \ 'neomru/file', 'matchers', \ ['matcher_context']) endfunction nnoremap [unite]f. :execute "Unite file_rec/async:" . my#path#buffer_dir() nnoremap [unite]fv :Unite file_rec/async:$SRC_ROOT/github.com/tmsanrinsha/dotfiles/home/.vim nnoremap [unite]fV :Unite file_rec/async:$VIM nnoremap [unite]fd :Unite file_rec/async:$SRC_ROOT/github.com/tmsanrinsha/dotfiles " unite grep {{{2 " ------------------------------------------------------------------------ " カレントディレクトリに対してgrep nnoremap [unite]gc :Unite grep:. " カレントバッファのディレクトリ以下に対してgrep nnoremap [unite]g. :execute "Unite grep:".escape(expand('%:p:h'), ' ') " 全バッファに対してgrep nnoremap [unite]gB :Unite grep:$buffers " プロジェクト内のファイルに対してgrep nnoremap [unite]gp :call unite_grep_project('-start-insert') function! s:unite_grep_project(...) let opts = (a:0 ? join(a:000, ' ') : '') let l:project_dir = my#path#project_dir() if !executable('ag') && isdirectory(l:project_dir.'/.git') execute 'Unite '.opts.' grep/git:/:--untracked' else execute 'Unite '.opts.' grep:'.l:project_dir endif endfunction nnoremap [unite]gd :Unite grep:$SRC_ROOT/github.com/tmsanrinsha/dotfiles execute 'nnoremap [unite]gD :Unite grep:' . g:dein_dir . '' nnoremap [unite]gv :Unite grep:$SRC_ROOT/github.com/tmsanrinsha/dotfiles/home/.vim nnoremap [unite]gV :Unite grep:$VIM nnoremap [unite]gb :Unite grep:$HOME/.vim/bundle "}}} "レジスタ一覧 nnoremap [unite]r :Unite -buffer-name=register register " ヤンク履歴 let g:unite_source_history_yank_enable = 1 "history/yankの有効化 nnoremap [unite]y :Unite history/yank " ブックマーク nnoremap [unite]B :Unite bookmark nnoremap [unite]j :Unite jump nnoremap [unite]D :Unite dein -default-action=vimfiler endif " neossh.vim {{{1 " ========================================================================= " let g:neossh#ssh_command = 'ftp.sh -p PORT HOSTNAME' " let g:neossh#list_command = 'ls' " let ls -lFa', " let g:neossh#copy_directory_command', " let scp -P PORT -q -r $srcs $dest', " let g:neossh#copy_file_command', " let scp -P PORT -q $srcs $dest', " let g:neossh#delete_file_command', " let rm $srcs', " let g:neossh#delete_directory_command', " let rm -r $srcs', " let g:neossh#move_command', " let mv $srcs $dest', " let g:neossh#mkdir_command', " let mkdir $dest', " let g:neossh#newfile_command', " let touch $dest', " let g:unite_source_ssh_enable_debug = 1 " unite-outline {{{1 " ========================================================================= if IsInstalled('unite-outline') nnoremap [unite]o :Unite outline nnoremap [unite]of :Unite outline:folding nnoremap [unite]oo :Unite -vertical -winwidth=40 -no-auto-resize -no-quit outline endif autocmd MyVimrc FileType yaml \ nnoremap [unite]o :Unite outline:folding " tacroe/unite-mark {{{1 " ========================================================================= nnoremap [unite]` :Unite mark " neoyank.vim {{{1 " ========================================================================= if IsInstalled('neoyank.vim') nnoremap [unite]hy :Unite history/yank let g:neoyank#file = $VIM_CACHE_DIR.'/yankring.txt' endif " vim-unite-history {{{1 " ========================================================================= if IsInstalled('vim-unite-history') nnoremap [unite]hc :Unite history/command nnoremap [unite]hs :Unite history/search cnoremap :Unite history/command -start-insert -default-action=edit inoremap ,hc :Unite history/command -start-insert -default-action=insert endif " unite-ghq {{{1 " ============================================================================ if IsInstalled('unite-ghq') nnoremap [unite]dg :Unite ghq endif " cdr *cdr* {{{1 " ============================================================================ if IsInstalled('vital.vim') let g:recent_dirs_file = $ZDOTDIR.'/.cache/chpwd-recent-dirs' augroup cdr autocmd! autocmd BufEnter * call s:update_cdr(my#path#buffer_dir()) augroup END function! s:update_cdr(dir) " .gitなどのdirectoryは書き込まない let l:ignore_pattern = '\%(^\|/\)\.\%(hg\|git\|bzr\|svn\)\%($\|/\)'. \ '\|^\%(\\\\\|/mnt/\|/media/\|/temp/\|/tmp/\|\%(/private\)\=/var/folders/\)' if !isdirectory(a:dir) || a:dir =~ l:ignore_pattern return end if filereadable(g:recent_dirs_file) let l:recent_dirs = readfile(g:recent_dirs_file) call insert(l:recent_dirs, "$'".a:dir."'", 0) let l:V = vital#of('vital') let l:List = l:V.import('Data.List') let l:recent_dirs = l:List.uniq(l:recent_dirs) call writefile(l:recent_dirs, g:recent_dirs_file) endif endfunction endif " unite-zsh-cdr.vim {{{2 " ---------------------------------------------------------------------------- if IsInstalled('unite-zsh-cdr.vim') nnoremap [unite]dr :Unite zsh-cdr nnoremap :Unite zsh-cdr let g:unite_zsh_cdr_chpwd_recent_dirs = g:recent_dirs_file endif " Denite.nvim {{{1 " ============================================================================ " unite.vimの後で上書きしたいので、tomlではなくここに書く if IsInstalled('denite.nvim') nnoremap [unite], :Denite -resume nnoremap [unite]H :Denite help " カレントディレクトリ以下 nnoremap [unite]f :Denite file_rec nnoremap [unite]d :Denite directory_rec -default-action=vimfiler nnoremap [unite]g :Denite grep " カレントバッファディレクトリ nnoremap [unite]f. :Denite file_rec:`my#path#buffer_dir()` nnoremap [unite]d. :Denite directory_rec:`my#path#buffer_dir()` -default-action=vimfiler nnoremap [unite]g. :Denite grep:`my#path#buffer_dir()` " プロジェクトディレクトリ nnoremap [unite]fp :Denite file_rec:`my#path#project_dir()` nnoremap [unite]dp :Denite directory_rec:`my#path#project_dir()` -default-action=vimfiler nnoremap [unite]gp :Denite grep:`my#path#project_dir()` " dotfiles let dotfiles_dirs = ['$SRC_ROOT/github.com/tmsanrinsha/dotfiles'] function! s:denite_multi_args(name, args_arr, ...) abort let context = get(a:, 1, []) let arr = [] for args in a:args_arr call add(arr, {'name': a:name, 'args': [args]}) endfor if empty(context) call denite#start(arr) else call denite#start(arr, context) endif endfunction nnoremap [unite]fd :call denite_multi_args('file_rec', dotfiles_dirs) nnoremap [unite]dd :call denite_multi_args('directory_rec', dotfiles_dirs, {'default_action': 'vimfiler'}) nnoremap [unite]gd :call denite#start([{'name': 'grep', 'args': [dotfiles_dirs]}]) " Vim nnoremap [unite]fv :Denite file_rec:$SRC_ROOT/github.com/tmsanrinsha/dotfiles/home/.vim nnoremap [unite]dv :Denite directory_rec:$SRC_ROOT/github.com/tmsanrinsha/dotfiles/home/.vim -default-action=vimfiler nnoremap [unite]gv :Denite grep:$SRC_ROOT/github.com/tmsanrinsha/dotfiles/home/.vim " $Vim nnoremap [unite]fV :Denite file_rec:$VIM nnoremap [unite]dV :Denite directory_rec:$VIM -default-action=vimfiler nnoremap [unite]gV :Denite grep:$VIM " dein.vim nnoremap [unite]fD :Denite file_rec:`g:dein_dir` nnoremap [unite]dD :Denite directory_rec:`g:dein_dir` -default-action=vimfiler nnoremap [unite]gD :Denite grep:`g:dein_dir` " Hugo nnoremap [unite]fh :Denite file_rec:`g:hugo_post_directory` nnoremap [unite]gh :Denite grep:`g:hugo_post_directory` endif " vimfiler {{{1 " ============================================================================ let g:vimfiler_as_default_explorer = 1 " セーフモードを無効にした状態で起動する let g:vimfiler_safe_mode_by_default = 0 let g:vimfiler_data_directory = $VIM_CACHE_DIR.'/vimfiler' let g:vimfiler_tree_opened_icon = '▾' let g:vimfiler_tree_closed_icon = '▸' let g:vimfiler_tree_leaf_icon = ' ' nnoremap [VIMFILER] nmap f [VIMFILER] nnoremap [VIMFILER]f :VimFiler nnoremap [VIMFILER]b :VimFilerBufferDir nnoremap [VIMFILER]c :VimFilerCurrentDir nnoremap [VIMFILER]t :cd %:h:VimFilerTab nnoremap [VIMFILER]p :execute "VimFilerExplorer ". unite#util#path2project_directory(expand('%')) " vimfilerでvim-surroundのmapを消す。vimfilerからunite.vimを使った時エラーがでるのでsilentする autocmd MyVimrc BufEnter vimfiler* \ silent! nunmap ds \| silent! nunmap cs autocmd MyVimrc BufLeave vimfiler* \ nmap ds Dsurround \| nmap cs Csurround " vimshell {{{1 " ============================================================================ if IsInstalled('vimshell.vim') nmap H [VIMSHELL] xmap H [VIMSHELL] nnoremap [VIMSHELL]H :VimShellPop nnoremap [VIMSHELL]b :VimShellBufferDir -popup nnoremap [VIMSHELL]c :VimShellCurrentDir -popup nnoremap [VIMSHELL]i :VimShellInteractive nnoremap [VIMSHELL]ipy :VimShellInteractive python nnoremap [VIMSHELL]iph :VimShellInteractive php nnoremap [VIMSHELL]irb :VimShellInteractive irb nnoremap [VIMSHELL]iR :VimShellInteractive R nnoremap [VIMSHELL]s :VimShellSendString xnoremap [VIMSHELL]s :VimShellSendString function! s:vimshell_on_source() abort nnoremap [VIMSHELL] " ss: 非同期で開いたインタプリタに現在の行を評価させる "vmap ss :VimShellSendString "" 選択中にss: 非同期で開いたインタプリタに選択行を評価させる "nnoremap ss :VimShellSendString if has('mac') call vimshell#set_execute_file('html', 'gexe open -a /Applications/Firefox.app/Contents/MacOS/firefox') call vimshell#set_execute_file('avi,mp4,mpg,ogm,mkv,wmv,mov', 'gexe open -a /Applications/MPlayerX.app/Contents/MacOS/MPlayerX') endif let g:vimshell_prompt = hostname() . '> ' let g:vimshell_user_prompt = 'fnamemodify(getcwd(), ":~")' let g:vimshell_right_prompt = 'vcs#info("(%s)-[%b] ", "(%s)-[%b|%a] ")' " Shougo/vim-vcs is required let g:vimshell_data_directory = $VIM_CACHE_DIR.'/vimshell' let g:vimshell_max_command_history = 3000 let g:vimshell_vimshrc_path = $VIMRC_DIR.'/.vimshrc' autocmd MyVimrc FileType vimshell \ setlocal nonumber \| setlocal nocursorline \| nmap q (vimshell_hide)= \| imap (vimshell_history_neocomplete) \| imap (vimshell_zsh_complete) \| call vimshell#altercmd#define('g', 'git') \| call vimshell#altercmd#define('l', 'll') \| call vimshell#altercmd#define('ll', 'ls -l') \| call vimshell#altercmd#define('la', 'ls -a') \| call vimshell#altercmd#define('lla', 'ls -la') "\| call vimshell#hook#add('chpwd', 'my_chpwd', 'g:my_chpwd') "function! g:my_chpwd(args, context) " call vimshell#execute('ls') "endfunction autocmd MyVimrc FileType int-* \ inoremap pumvisible() ? "\" : "\\" " \| execute 'setlocal filetype='.matchstr(&filetype, 'int-\zs.*') let g:vimshell_split_command = 'split' endfunction execute 'autocmd MyVimrc User' 'dein#source#' . g:dein#name \ 'call s:vimshell_on_source()' endif " SirVer/ultisnips {{{1 " ============================================================================== " let g:UltiSnipsUsePythonVersion = 2 " " let g:UltiSnipsSnippetsDir=$HOME.'/.vim/bundle/vim-snippets/UltiSnips' " let g:UltiSnipsExpandTrigger="" " let g:UltiSnipsJumpForwardTrigger="" " let g:UltiSnipsJumpBackwardTrigger="" " " " If you want :UltiSnipsEdit to split your window. " let g:UltiSnipsEditSplit="vertical" " Shougo/context_filetype.vim: 部分的にfiletypeを変更する{{{1 " ============================================================================= if IsInstalled('context_filetype.vim') let g:context_filetype#filetypes = deepcopy(context_filetype#default_filetypes()) " markdown call add(g:context_filetype#filetypes.markdown, { \ 'filetype': 'css', \ 'start': ']*\)\? type="text/css"\%( [^>]*\)\?>', \ 'end': '' \}) " Rmd let g:context_filetype#filetypes.rmd = g:context_filetype#filetypes.markdown " cvim let g:context_filetype#filetypes.cvim = [ \ { \ 'filetype': 'javascript', \ 'start': ' -> {{', \ 'end': '}}' \ } \] endif " tmsanrinsha/SyntaxRange: 部分的にsyntaxを変更する{{{1 " ============================================================================= " [dein.vimのtomlのhook_*部分をシンタックスハイライトさせる - Qiita](http://qiita.com/tmsanrinsha/items/9670628aef3144c7919b) if IsInstalled('vim-SyntaxRange') autocmd MyVimrc BufNewFile,BufRead dein*.toml call s:syntax_range_dein() function! s:syntax_range_dein() abort let start = '^\s*hook_\%('. \ 'add\|source\|post_source\|post_update'. \ '\)\s*=\s*%s' call SyntaxRange#Include(printf(start, "'''"), "'''", 'vim', '') call SyntaxRange#Include(printf(start, '"""'), '"""', 'vim', '') endfunction autocmd MyVimrc BufNewFile,BufRead cvimrc call SyntaxRange#Include(' -> {{', '}}', 'javascript', '') endif " thinca/vim-template {{{1 " ============================================================================ autocmd MyVimrc User plugin-template-loaded call s:setup_template() function! s:setup_template() abort %s/<+FILE ROOT+>/\=expand('%:t:r')/ge %s/<+RFC 3339+>/\=strftime('%Y-%m-%dT%H:%M:%S+09:00')/ge if search('<+CURSOR+>') execute 'normal! "_da>' endif endfunction " vim-watchdogs {{{1 " ============================================================================ if IsInstalled('vim-watchdogs') augroup WatchdogsSetting autocmd! autocmd BufWritePre * \ call dein#source("vim-watchdogs") | \ autocmd! WatchdogsSetting augroup END endif " quickfix系プラグインのアップデート {{{1 " ============================================================================ " quickfixを開いてHierUpdateなどをしたい場合は以下のようにする " autocmd MyVimrc FileType qf call s:qf_update() " function! s:qf_update() " " error 788| in s:qf_update | 現在は他のバッファを編集することは許されません " " というエラーがでる " windo HierUpdate " windo QfsignsUpdate " windo QuickfixStatusEnable " endfunction " qfsigns {{{1 " ============================================================================ " let g:qfsigns#AutoJump = 1 let g:qfsigns#Config = {'id': '5050', 'name': 'qfsign'} sign define qfsign texthl=SignColumn text=>> " quickfixsign_vim {{{1 " ============================================================================ " let g:quickfixsigns_classes = ['qfl'] " operator {{{1 " ============================================================================ onoremap ; t; if IsInstalled('vim-operator-user') map [:space:]c (operator-camelize-toggle) map [:space:]p (operator-replace) map [:space:]P "+(operator-replace) map [:space:]/ (operator-search) " surround {{{2 " ------------------------------------------------------------------------ map sa (operator-surround-append) map sd (operator-surround-delete) map sr (operator-surround-replace) nmap saa (operator-surround-append)(textobj-multiblock-i) nmap saA (operator-surround-append)(textobj-multiblock-a) nmap sdd (operator-surround-delete)(textobj-multiblock-a) nmap srr (operator-surround-replace)(textobj-multiblock-a) nmap sd" (operator-surround-delete)a" nmap sr" (operator-surround-delete)a" let g:operator#surround#blocks = {} " zは全角 let g:operator#surround#blocks['-'] = [ \ { 'block' : ['(', ')'], 'motionwise' : ['char', 'line', 'block'], 'keys' : ['z('] }, \ { 'block' : ['「', '」'], 'motionwise' : ['char', 'line', 'block'], 'keys' : ['z['] }, \ { 'block' : ['『', '』'], 'motionwise' : ['char', 'line', 'block'], 'keys' : ['2z['] }, \ ] endif " clipboard copy {{{1 " ============================================================================ nmap [:space:]y "*y xmap [:space:]y "*y nmap [:space:]yy "*yy nmap [:space:]Y "*y$ " vim-fakeclip {{{1 " ---------------------------------------------------------------------------- if IsInstalled('vim-fakeclip') " +clipboardでもfakeclipのキーマッピングを使う let g:fakeclip_provide_clipboard_key_mappings = 1 " クリップボードコピーのコマンドにrfpbcopyを使う " let g:fakeclip_write_clipboard_command = 'rfpbcopy' let g:fakeclip_write_clipboard_command = 'paste64.mac' endif " textobj {{{1 " ============================================================================ if IsInstalled('vim-textobj-lastpat') let g:textobj_lastpat_no_default_key_mappings = 1 nmap gn (textobj-lastpat-n) nmap gN (textobj-lastpat-N) endif omap ab (textobj-multiblock-a) omap ib (textobj-multiblock-i) xmap ab (textobj-multiblock-a) xmap ib (textobj-multiblock-i) " matchparisの括弧を追加 let g:textobj_multiblock_blocks = [] for s:val in split(&matchpairs, ',') let s:pair = split(s:val, ':') call add(g:textobj_multiblock_blocks, s:pair) endfor omap ic (textobj-comment-i) xmap ic (textobj-comment-i) omap ac (textobj-comment-a) xmap ac (textobj-comment-a) omap aC (textobj-comment-big-a) xmap aC (textobj-comment-big-a) omap iC (textobj-context-i) xmap iC (textobj-context-i) omap ae (textobj-entire-a) omap ie (textobj-entire-i) xmap ae (textobj-entire-a) xmap ie (textobj-entire-i) " let g:textobj_conflict_no_default_key_mappings = 1 " omap ix (textobj-conflict-i) " omap ax (textobj-conflict-a) " xmap ix (textobj-conflict-i) " omap ax (textobj-conflict-a) if IsInstalled('vim-textobj-xbrackets') " change surround function nmap csf vax(ovct( " delte surround function nmap dsf vax(ovdt( " これも良さそう " [hoge() で囲みたい症候群 - vim 初心者の作業メモ](http://d.hatena.ne.jp/syngan/20140301/1393676442) endif " vim-multiple-cursors {{{1 " ============================================================================ if IsInstalled('vim-multiple-cursors') let g:multi_cursor_use_default_mapping = 0 let g:multi_cursor_next_key='+' let g:multi_cursor_prev_key='-' let g:multi_cursor_skip_key='&' let g:multi_cursor_quit_key='' endif " vim-partedit {{{1 " ============================================================================ if IsInstalled('vim-partedit') " let g:partedit#auto_prefix = 0 nnoremap pe :MyParteditContext xnoremap pe :Partedit -opener split nnoremap pq :ParteditEnd function! s:partedit_context() let context = context_filetype#get() let startline = context['range'][0][0] ? context['range'][0][0] : 1 let endline = context['range'][1][0] ? context['range'][1][0] : '$' let filetype = context['filetype'] " openerはedit以外は保存時にエラーが出る call partedit#start(startline, endline, {'filetype': filetype, 'opener': 'edit'}) endf command! MyParteditContext call s:partedit_context() endif " vim-alignta {{{1 " ============================================================================== if IsInstalled('vim-alignta') xnoremap [ALIGNTA] xmap a [ALIGNTA] xnoremap [ALIGNTA]s :Alignta \S\+ xnoremap [ALIGNTA]= :Alignta = xnoremap [ALIGNTA]> :Alignta => xnoremap [ALIGNTA]: :Alignta : endif " LeafCage/yankround.vim :paste:yank: {{{1 " ============================================================================ nnoremap ]p p`[v`]= nnoremap ]P P`[v`]= xnoremap ]p p`[v`]= xnoremap ]P P`[v`]= " インデントを考慮したペースト]p,]Pとペーストしたテキストの最後に行くペーストgp,gPを合わせたようなもの nnoremap ]gp p`[v`]=`] nnoremap ]gP P`[v`]=`] xnoremap ]gp p`[v`]=`] xnoremap ]gP P`[v`]=`] if IsInstalled('yankround.vim') let g:yankround_dir = $VIM_CACHE_DIR.'/yankround' let g:yankround_use_region_hl = 1 autocmd MyVimrc ColorScheme * \ highlight! YankRoundRegion ctermfg=16 ctermbg=187 doautocmd MyVimrc ColorScheme nmap p (yankround-p) xmap p (yankround-p) nmap P (yankround-P) nmap gp (yankround-gp) xmap gp (yankround-gp) nmap gP (yankround-gP) endif " gf {{{1 " ============================================================================ " =をファイル名に使われる文字から外す set isfname-== " spaceをファイル名に使われる文字に含める " これをやると2つ以上のファイル・ディレクトリを引数にとるコマンドで、2つ目以降の引数の補完がうまくいかなくなる " set isfname+=32 " vim-gf-user {{{2 " ---------------------------------------------------------------------------- if IsInstalled('vim-gf-user') let g:gf_user_no_default_key_mappings = 1 " ディレクトリの場合にうまくvimfilerが開かない " gf#user#doのtryを外すと開く。エラーではないのかcatchはできない " :eで開き直すとvimfilerが起動する nmap [:space:]gf (gf-user-gf) xmap [:space:]gf (gf-user-gf) nmap [:space:]gF (gf-user-gF) xmap [:space:]gF (gf-user-gF) nmap [:space:]f (gf-user-f) xmap [:space:]f (gf-user-f) nmap [:space:] (gf-user-) xmap [:space:] (gf-user-) nmap [:space:]F (gf-user-F) xmap [:space:]F (gf-user-F) nmap [:space:]gf (gf-user-gf) xmap [:space:]gf (gf-user-gf) nmap [:space:]gF (gf-user-gF) " カーソル下のファイル名のファイルを、現在開いているファイルと同じディレクトリに開く function! GfNewFile() let path = expand('%:p:h').'/'.expand('') let line = 0 if path =~# ':\d\+:\?$' let line = matchstr(path, '\d\+:\?$') let path = matchstr(path, '.*\ze:\d\+:\?$') endif return { \ 'path': path, \ 'line': line, \ 'col': 0, \ } endfunction call gf#user#extend('GfNewFile', 3000) endif " Project {{{1 " ============================================================================ "" vim-projectionist {{{2 " ---------------------------------------------------------------------------- " [Vimでプロジェクトを扱う - SanRin舎](https://tmsanrinsha.net/post/2017/07/vim-project/) if !exists('g:projectionist_heuristics') let g:projectionist_heuristics = {} endif """ Chef repo {{{3 let g:projectionist_heuristics['chefignore'] = { \ 'attributes/*.rb': { \ 'type': 'attribute' \ }, \ 'files/*.rb': { \ 'type': 'file' \ }, \ 'libraries/*.rb': { \ 'type': 'library', \ 'alternate': 'spec/unit/libraries/{}_spec.rb' \ }, \ 'recipes/*.rb': { \ 'type': 'recipe', \ 'alternate': 'spec/unit/recipes/{}_spec.rb' \ }, \ 'spec/unit/*_spec.rb': { \ 'type': 'spec', \ 'alternate': '{}.rb', \ }, \ 'templates/*.rb': { \ 'type': 'template' \ }, \} """ Java {{{3 let g:projectionist_heuristics['build.gradle'] = {} """ PHP {{{3 let g:projectionist_heuristics['composer.json|phpunit.xml'] = { \ 'src/*.php': { \ 'type': 'src', \ 'alternate': 'tests/{}Test.php' \ }, \ 'tests/*Test.php': { \ 'type': 'src', \ 'alternate': 'src/{}.php' \ } \} " let g:projectionist_heuristics['__init__.py'] = {} """ memo {{{3 let g:projectionist_heuristics['content/'] = { \ 'content/*.md': { \ 'type': 'content', \ 'alternate': 'static/files/{}/' \ } \} """ complete {{{3 inoremap my#alternate() " tcomment_vim {{{1 " ============================================================================ if IsInstalled('tcomment_vim') " コメントアウトしてコピー nmap y yyPTComment_j xmap y ygvTComment_gvp let g:tcommentTextObjectInlineComment = '' endif " vim-jsbeautify {{{1 " ============================================================================== if IsInstalled('vim-jsbeautify') autocmd MyVimrc FileType javascript setlocal formatexpr=JsBeautify() autocmd MyVimrc FileType css setlocal formatexpr=CSSBeautify() autocmd MyVimrc FileType html setlocal formatexpr=HtmlBeautify() " こう設定しないとpangloss/vim-javascriptに上書きされてしまう " ⇡しなくてもうまくいった " autocmd MyVimrc BufRead *.js setlocal formatexpr=JsBeautify() else autocmd MyVimrc FileType html \ nnoremap gq :%s/>\rgg=G \| xnoremap gq :s/>\rgg=G endif " automatic {{{1 " ============================================================================ " http://d.hatena.ne.jp/osyo-manga/20130812/1376314945 " http://blog.supermomonga.com/articles/vim/automatic.html " let g:automatic_default_set_config = { " \ 'height' : '20%', " \ 'move' : 'bottom', " \ } " let g:automatic_config = [ " \ { " \ 'match' : {'bufname' : 'vimshell'} " \ } " \] " fold {{{1 " ============================================================================ set foldmethod=marker " foldmethod=expr が重い場合の対処法 - 永遠に未完成 " autocmd MyVimrc InsertEnter * \| if &l:foldmethod ==# 'expr' \| let b:foldinfo = [&l:foldmethod, &l:foldexpr] \| setlocal foldmethod=manual foldexpr=0 \| endif autocmd MyVimrc InsertLeave * \| if exists('b:foldinfo') \| let [&l:foldmethod, &l:foldexpr] = b:foldinfo \| endif " http://leafcage.hateblo.jp/entry/2013/04/24/053113 " 現在のカーソルの位置以外の折りたたみを閉じる nnoremap z- zMzv nnoremap l foldclosed('.') != -1 ? 'zo' : 'l' if IsInstalled('foldCC') set foldtext=FoldCCtext() set foldcolumn=1 set fillchars=vert:\| let g:foldCCtext_head = '' " let g:foldCCtext_head = '"▸ " . v:folddashes . " "' " let g:foldCCtext_head = 'repeat(" ", v:foldlevel) . "+ "' let g:foldCCtext_tail = 'printf("[Lv%d %3d]", v:foldlevel, v:foldend-v:foldstart+1)' nnoremap :echo FoldCCnavi() endif " swap, backup {{{1 " ============================================================================ " updatetimeを短くして、CursorHoldに使うので " swap fileがupdatetimeごと頻繁に作成されないようにnoswapfileにする " vimfilerを使っているとnoswapfileに設定される " set noswapfile "" デフォルトの設定にある~/tmpを入れておくと、swapファイルが自分のホームディレクトリ以下に生成されてしまい、他の人が編集中か判断できなくなるので除く "" set directory& "" set directory-=~/tmp "" " 他の人が編集する可能性がない場合はswapファイルを作成しない "" if has('win32') || has('mac') "" set noswapfile "" endif " スワップファイルがあるときに常にRead-Onlyで開く " 個人的に便利だと思うVimの基本設定のランキングを発表します! - プログラムモグモグ " http://itchyny.hatenablog.com/entry/2014/12/25/090000 " crontabのエラー対策 {{{2 " ---------------------------------------------------------------------------- " FreeBSD, Macでcrontab -eしたときに " crontab: temp file must be edited in place " というエラーが出てcrontabが更新されないときの対策 " [crontabをVimで編集した時に出るエラーの対処法](http://sanrinsha.lolipop.jp/blog/2013/03/post-10825.html) set backupskip& set backupskip+=/home/tmp/*,/private/tmp/* " backup {{{2 " ---------------------------------------------------------------------------- if !IsInstalled('vim-bkup') " https://tmsanrinsha.net/post/2013/03/vimで富豪的バックアップ/ set backup augroup backup autocmd! autocmd BufWritePre,FileWritePre,FileAppendPre * call UpdateBackupFile(expand('%')) function! UpdateBackupFile(file) let dir = fnamemodify(a:file, ':p:h') " Windowsのドライブ名を置換 (e.g. C: -> /C/) let dir = substitute(dir, '\v\c^([a-z]):', '/\1/' , '') let todir = expand('$VIM_CACHE_DIR/backup') . dir if !isdirectory(todir) call mkdir(todir, 'p') endif let &backupdir = todir let &backupext = '-' . strftime("%Y%m%d_%H%M%S") endfunction augroup END endif " session {{{1 " ============================================================================ " 前回のカーソル位置にジャンプ {{{2 " ---------------------------------------------------------------------------- " Always Jump to the Last Known Cursor Position autocmd MyVimrc BufReadPost * \ if line("'\"") > 1 && line("'\"") <= line("$") | \ execute "normal! g`\"" | \ endif " session {{{2 " ---------------------------------------------------------------------------- " optionsを設定するとおかしくなる set sessionoptions-=options autocmd MyVimrc VimLeavePre * call s:save_session() function! s:save_session() if !empty(expand('%')) mksession! $VIM_CACHE_DIR/session.vim endif endfunction " undo {{{1 " ============================================================================ " undoの履歴をファイルに保存し、Vim を一度終了したとしてもundoやredoを行えるようにする {{{2 " ---------------------------------------------------------------------------- " 開いた時に前回保存時と内容が違う場合はリセットされる if has('persistent_undo') set undofile if !isdirectory($VIM_CACHE_DIR.'/undo') call mkdir($VIM_CACHE_DIR.'/undo', 'p') endif set undodir=$VIM_CACHE_DIR/undo endif " 現在行に対するundo {{{2 " ---------------------------------------------------------------------------- " [Undo certain modifications - Vi and Vim Stack Exchange](https://vi.stackexchange.com/questions/4026/undo-certain-modifications) function! s:undoline() let pos = getpos(".") let current = getline(pos[1]) let chg = changenr() while changenr() > 0 && current ==# getline(pos[1]) silent undo endwhile let old = getline(pos[1]) while changenr() < chg silent redo endwhile " undo if we jumped over a gap if changenr() > chg silent undo endif call setpos('.', pos) if old ==# current echo 'no change found' else call setline(pos[1], old) endif endfunction map U :call undoline() " [Undo certain modifications - Vi and Vim Stack Exchange](https://vi.stackexchange.com/questions/4026/undo-certain-modifications) " diff-fold, patchutils " C++ {{{1 " ============================================================================ " if IsInstalled('vim-cpp-auto-include') " autocmd MyVimrc BufWritePre *.cpp :ruby CppAutoInclude::process " endif " phpcomplete.vim {{{1 " ============================================================================ let g:phpcomplete_enhance_jump_to_definition = 1 " let g:phpcomplete_mappings = { " \ 'jump_to_def': '', " \ 'jump_to_def_split': '', " \ 'jump_to_def_vsplit': '', " \} " stephpy/vim-php-cs-fixer {{{1 " ============================================================================ nnoremap pcd :call PhpCsFixerFixDirectory() nnoremap pcf :call PhpCsFixerFixFile() let g:php_cs_fixer_dry_run = 1 let g:php_cs_fixer_verbose = 1 let g:php_cs_fixer_level = 'all' " let g:php_cs_fixer_path = '~/sample/vendor/bin/php-cs-fixer' " vim-json {{{1 " ============================================================================ let g:vim_json_syntax_conceal = 0 " Python, jedi-vim {{{1 " ============================================================================ " " pythonのsys.pathの設定 " {{{2 " " ---------------------------------------------------------------------------- " " [VimのPythonインターフェースのパスの問題を解消する - Qiita](http://qiita.com/tmsanrinsha/items/cfa3808b8d0cc915cd75) " function! Set_python_path() " if ! exists('g:python_path') " let g:python_path = system('python -', 'import sys;sys.stdout.write(",".join(sys.path))') " endif " " python <などのマッピングをしない let vimrplugin_assign = 0 autocmd MyVimrc FileType r \ nmap r RSendFile \ | nmap re RESendFile \ | nmap ss RSendLine \ | vmap ss RESendSelection \ | imap RSendLineo " result <- fun( " par1 = "abc", " par2 = "def", " par3 = 3 " ) " を " result <- fun( " par1 = "abc", " par2 = "def", " par3 = 3 " ) " にする。最後の括弧がにならない " let r_indent_align_args = 0 " autowitch/hive.vim {{{1 " ============================================================================ autocmd MyVimrc BufNewFile,BufRead *.hql,*.q \ let b:sql_type_overrride = 'hive' \| setlocal filetype=sql " vimconsole.vim {{{1 " ============================================================================== if IsInstalled('vimconsole.vim') let g:vimconsole#auto_redraw = 1 augroup MyVimrc autocmd FileType vim,vimconsole \ nnoremap :VimConsoleToggle \ | nnoremap :VimConsoleClear augroup END let g:vimconsole#maximum_caching_objects_count = 100 endif " instant-markdown-vim {{{1 " ============================================================================ " let g:instant_markdown_slow = 1 " let g:instant_markdown_autostart = 0 " autocmd MyVimrc FileType markdown nnoremap r :InstantMarkdownPreview " Git {{{1 " ============================================================================ " Git {{{2 " ---------------------------------------------------------------------------- " コミットメッセージは72文字で折り返す " http://keijinsonyaban.blogspot.jp/2011/01/git.html " 72列目に線を引く " Insert modeで始める autocmd MyVimrc BufRead */.git/COMMIT_EDITMSG \ setlocal colorcolumn=+1 \| startinsert " ftpluginによって、自動で折り返す設定になるので、自分のvimrcで設定したglobalな値に戻す autocmd MyVimrc FileType gitcommit \ setlocal formatoptions< " " vim-fugitive {{{2 " ---------------------------------------------------------------------------- if IsInstalled('vim-fugitive') nnoremap [fugitive] nmap g [fugitive] nnoremap [fugitive]a :Gwrite nnoremap [fugitive]ci :Gcommit nnoremap [fugitive]co :Git checkout % nnoremap [fugitive]d :Gdiff nnoremap [fugitive]s :Gstatus nnoremap [fugitive]l :Glog nnoremap [fugitive]b :Git browse nnoremap [fugitive]ps :Git push nnoremap [fugitive]psf :Git push -f nnoremap [fugitive]pso :Git push origin nnoremap [fugitive]pl :Git pull --rebase nnoremap [fugitive]fo :Git fetch origin nnoremap [fugitive]for :Git fetch origin:Git rebase origin/master nnoremap [fugitive]2 :diffget //2 diffupdate\ nnoremap [fugitive]3 :diffget //3 diffupdate\ " Gbrowse ではgit config --global web.browserの値は見てない " ~/.vim/bundle/vim-fugitive/plugin/fugitive.vim if !has('gui_running') && $SSH_CLIENT !=# '' let g:netrw_browsex_viewer = 'rfbrowser' endif " gitcommitでカーソル行のファイルをrmする function! s:gitcommit_rm() if executable('rmtrash') let s:my_rm_commant = 'rmtrash' else let s:my_rm_commant = 'rm -r' endif " nnoremapだととrのremapができないのでnmap " nmapだと:が;になってしまうので[Colon]を使う execute "nmap r [Colon]call system('" . s:my_rm_commant . " \"' . expand('%:h:h') . '/\"')r" endfunction autocmd MyVimrc FileType gitcommit \ call s:gitcommit_rm() \| nmap co [Colon]Git checkout " vimfiler上でfugitiveのコマンドを使う autocmd MyVimrc FileType vimfiler \ autocmd CursorMoved let b:git_dir = '' | call fugitive#detect(vimfiler#get_filename()) endif " open-browser.vim {{{1 " ============================================================================ if IsInstalled('open-browser.vim') nmap gx (openbrowser-smart-search) vmap gx (openbrowser-smart-search) nmap (openbrowser-smart-search) vmap (openbrowser-smart-search) autocmd MyVimrc FileType mql4,php \ nnoremap K :MyOpenbrowserSearch n \| xnoremap K :MyOpenbrowserSearch v function! s:my_openbrowser_search(mode) if a:mode ==# 'n' let search_text = expand('') elseif a:mode ==# 'v' let V = vital#of('vital') let Buffer = V.import('Vim.Buffer') let search_text = Buffer.get_last_selected() endif call openbrowser#search(search_text, &filetype) endfunction command! -nargs=1 MyOpenbrowserSearch call s:my_openbrowser_search('') endif if IsInstalled('keysender.vim') && IsInstalled('vim2browser') inoremap :Vim2ChromeAppendAll:KeysenderKeyCode 52 nnoremap :Vim2ChromeAppendAll:KeysenderKeyCode 52 endif " lightline, statusline {{{1 " ============================================================================ " \ 'paste': '%{&paste?"PASTE":""}', " \ 'readonly': '%2*%{&filetype=="help"?"":&readonly?"RO":""}%*', " \ 'paste': '%{&paste?"PASTE":""}%R%H%W%q', let g:lightline = { \ 'colorscheme': 'my_powerline', \ 'active': { \ 'left': [ \ ['mode'], \ ['flag_red'], \ ['flag', 'filename', 'fugitive', 'currenttag', 'anzu'] \ ], \ 'right': [ \ ['syntaxcheck', 'column', 'lineinfo'], \ ['percent'], \ ['fileformat', 'fileencoding', 'filetype'] \ ] \ }, \ 'inactive': { \ 'left': [ \ ['flag', 'filename', 'fugitive', 'currenttag', 'anzu'] \ ], \ 'right': [ \ ['syntaxcheck', 'column', 'lineinfo'], \ ['percent'], \ ['fileformat', 'fileencoding', 'filetype'] \ ] \ }, \ 'component_visible_condition': { \ 'flag': '(&filetype == "help" || &filetype == "qf")', \ }, \ 'component_expand': { \ 'syntaxcheck': 'qfstatusline#Update', \ }, \ 'component_type': { \ 'syntaxcheck': 'error', \ }, \} " %R: 読み込み専用フラグ ,RO " $W: プレビューウィンドフラグ ,PRV " %<: 行が長過ぎるときに切り詰める位置 let g:lightline['component'] = { \ 'flag_red': '%{&paste?"PASTE":""}%R%W', \ 'flag': '%H%q', \ 'lineinfo': '%l:%v', \ 'fileformat': '%<%{&ff}' \} let g:lightline['component_function'] = { \ 'mode': 'lightline#mode', \ 'fugitive': 'MyFugitive', \ 'filename': 'MyFilename', \ 'filetype': 'MyFiletype', \ 'fileencoding': 'MyFileencoding', \ 'anzu': 'anzu#search_status', \ 'currenttag': 'MyCurrentTag', \ 'column': 'GetCurrentColumn', \} let g:lightline['separator'] = { 'left': '', 'right': '' } let g:lightline['subseparator'] = { 'left': '|', 'right': '|' } let g:lightline['mode_map'] = { \ 'n' : 'N', \ 'i' : 'I', \ 'R' : 'R', \ 'v' : 'V', \ 'V' : 'VL', \ 'c' : 'C', \ "\": 'VB', \ 's' : 'S', \ 'S' : 'SL', \ "\": 'SB', \ '?': '' \} " [vim-qfstatusline を作ってみた - mabulog](http://kazuomabuo.hatenablog.jp/entry/2014/06/11/211947) {{{ " :WatchdogsRun後にlightline.vimを更新 " \ 'right': [ " \ ['syntaxcheck', 'lineinfo'], " \ 'component_expand': { " \ 'syntaxcheck': 'qfstatusline#Update', " \ }, " \ 'component_type': { " \ 'syntaxcheck': 'error', " \ }, let g:Qfstatusline#UpdateCmd = function('lightline#update') " }}} " 途中で色変更をするとInsert modeがおかしくなる " autocmd MyVimrc ColorScheme * " \ hi User1 ctermfg=red guifg=red function! MyModified() return &filetype =~# 'help\|qf\|gitcommit\|vimfiler\|gundo' ? '' : &modified ? '+' : &modifiable ? '' : '-' endfunction function! MyReadonly() return &filetype !~? 'help\|vimfiler\|gundo' && &readonly ? 'RO' : '' endfunction function! MyFilename() if &filetype ==# 'vimfiler' return vimfiler#get_status_string() elseif &filetype ==# 'unite' return unite#get_status_string() elseif &filetype ==# 'vimshell' return vimshell#get_status_string() elseif &filetype ==# 'help' return expand('%:t') elseif &filetype ==# 'qf' || &filetype ==# 'gitcommit' return '' endif let filename = expand('%:~:.') if filename ==# '' let filename = '[No Name]' " elseif strlen(filename) > winwidth(0) - strlen(MyFugitive() . anzu#search_status()) - 10 " " elseif strlen(filename) > winwidth(0) - 40 " " 長いときに/と最初の文字だけにする " " /Users/tmsanrinsha/src/github.com/tmsanrinsha/dotfiles -> /U/t/s/g/t/d " let filename = substitute(filename, '/\zs\(.\)[^/]\+\ze/' , '\1', 'g') endif return filename . MyModified() endfunction function! MyFugitive() try if &filetype !~? 'gundo' && exists('*fugitive#head') && strlen(fugitive#head()) return fugitive#head() endif catch endtry return '' endfunction function! MyFileformat() return winwidth(0) > 0 ? &fileformat : '' endfunction function! MyFileencoding() return winwidth(0) > 0 ? (strlen(&fileencoding) ? &fileencoding : &encoding) : '' endfunction function! MyFiletype() return winwidth(0) > 0 ? (strlen(&filetype) ? &filetype : 'no ft') : '' endfunction function! MyCurrentTag() " return tagbar#currenttag('%s', '') return '' endfunction " [vimでCSVの特定カラムでハイライトを行う - Qiita](http://qiita.com/rita_cano_bika/items/e447c042e70327014609) " を参考にした function! GetCurrentColumn() if &filetype ==# 'tsv' return 'c'.(strlen(substitute(getline('.')[0:col('.')-1], '[^\t]', '', 'g')) + 1) elseif &filetype ==# 'csv' return 'c'.(strlen(substitute(getline('.')[0:col('.')-1], '[^,]', '', 'g')) + 1) else return '' endif endfunction " call lightline#init() " vim-quickhl {{{1 " ============================================================================ nmap [:space:]m (quickhl-manual-this) xmap [:space:]m (quickhl-manual-this) nmap [:space:]M (quickhl-manual-reset) xmap [:space:]M (quickhl-manual-reset) " vim-scripts/AnsiEsc.vim {{{1 " ============================================================================ autocmd MyVimrc FileType quickrun AnsiEsc " autocmd MyVimrc FileType qf call s:call_ansi_esc() " function! s:call_ansi_esc() abort " AnsiEsc " runtime syntax/qf.vim " endfunction " rainbow {{{1 " ============================================================================ if IsInstalled('rainbow') let g:rainbow_active = 1 let g:rainbow_conf = { \ 'guifgs': ['#FA248F', '#FA8F24', '#8FFA24', '#24FA8F', '#248FFA', '#8F24FA', '#FA2424', '#FAFA24', '#24FA24', '#24FAFA', '#2424FA', '#FA24FA'], \ 'ctermfgs': ['198', '208', '118', '48', '33', '93', '9', '11', '10', '14', '21', '13'], \ 'operators': '_,_', \ 'parentheses': [['(',')'], ['\[','\]'], ['{','}']], \ 'separately': { \ '*': {}, \ 'lisp': { \ 'guifgs': ['royalblue3', 'darkorange3', 'seagreen3', 'firebrick', 'darkorchid3'], \ 'ctermfgs': ['darkgray', 'darkblue', 'darkmagenta', 'darkcyan', 'darkred', 'darkgreen'], \ }, \ 'html': { \ 'parentheses': [['(',')'], ['\[','\]'], ['{','}']], \ }, \ 'xml': { \ 'parentheses': [['(',')'], ['\[','\]'], ['{','}']], \ }, \ 'vim': { \ 'parentheses': [['(',')'], ['\[','\]'], ['{','}']], \ }, \ } \} endif " junkfile.vim {{{1 " ============================================================================ if IsInstalled('junkfile.vim') let g:junkfile#directory = $JUNKFILE let g:junkfile#edit_command = 'new' language time C command! -nargs=0 MyJunkfile call junkfile#open(strftime('%b_%d_%a_%H%M%S.')) command! -nargs=0 JunkfileFiletype call junkfile#open_immediately( \ strftime('%b_%d_%a_%H%M%S.') . &filetype) nnoremap [:junk] nmap j [:junk] nnoremap [:junk]o :MyJunkfile nnoremap [:junk]n :MyJunkfile nnoremap [:junk]f :JunkfileFiletype nnoremap [unite]fj :Unite junkfile endif " insertPrintDebug {{{1 " ============================================================================ function! s:insertPrintDebug(mode) abort if a:mode == 'n' let str = expand('') else let tmp = @" silent normal! gvy let str = @" let @" = tmp endif let debug = printf("console.log('%s: ' + %s)", str, str) execute 'normal! o' . debug endfunction nnoremap P :call insertPrintDebug('n') xnoremap P :call insertPrintDebug('v') " local {{{1 " ============================================================================ call SourceRc('local.vim')