" Path: パス設定 ====================================================== {{{1 " Windowsでも.vimをRumtimeディレクトリにする set runtimepath+=$HOME/.vim " hatena.vimを使う "set runtimepath+=$HOME/.vim/hatena "ヘルプファイルをパスを指定する helptags $HOME/.vim/doc/ " Encodings: 文字コード設定 =========================================== {{{1 " from ずんWiki http://www.kawaz.jp/pukiwiki/?vim#content_1_7 if &encoding !=# 'utf-8' set encoding=japan endif "set fileencoding=japan if has('iconv') let s:enc_euc = 'euc-jp' let s:enc_jis = 'iso-2022-jp' " iconvがJISX0213に対応しているかをチェック if iconv("\x87\x64\x87\x6a", 'cp932', 'euc-jisx0213') ==# "\xad\xc5\xad\xcb" let s:enc_euc = 'euc-jisx0213' let s:enc_jis = 'iso-2022-jp-3' endif " fileencodingsを構築 if &encoding ==# 'utf-8' let s:fileencodings_default = &fileencodings let &fileencodings = s:enc_jis .','. s:enc_euc .',cp932' let &fileencodings = &fileencodings .','. s:fileencodings_default unlet s:fileencodings_default else let &fileencodings = &fileencodings .','. s:enc_jis set fileencodings+=utf-8,ucs-2le,ucs-2 if &encoding =~# '^euc-\%(jp\|jisx0213\)$' set fileencodings+=cp932 set fileencodings-=euc-jp set fileencodings-=euc-jisx0213 let &encoding = s:enc_euc else let &fileencodings = &fileencodings .','. s:enc_euc endif endif " 定数を処分 unlet s:enc_euc unlet s:enc_jis endif " Mouse: マウス設定 =================================================== {{{1 " どのモードでもマウスを使えるようにする set mouse=a " マウスの移動でフォーカスを自動的に切替えない (mousefocus:切替る) set nomousefocus " 入力時にマウスポインタを隠す (nomousehide:隠さない) set mousehide " ビジュアル選択(D&D他)を自動的にクリップボードへ (:help guioptions_a) "set guioptions+=a " Command: コマンド設定 ============================================== {{{1 " "best_of_tipsを開く command! Btips1 :silent e $HOME/.vim/doc/best_tips1.txt command! Btips2 :silent e $HOME/.vim/doc/best_tips2.txt " listcharsを切り替える command! ListCharsDispFull set listchars=tab:^-,eol:$,trail:_,nbsp:% list command! ListCharsDispTab set listchars=tab:^- list command! ListCharsDispEol set listchars=eol:$ list " カレントディレクトリに移動 command! -bar CD execute 'lcd' expand('%:p:h') " .gitのあるディレクトリに移動 command! -bar CDGit call CdDotGitDir() " Autocmd: autocmd設定 ================================================ {{{1 if has("autocmd") filetype plugin on "ファイルタイプにあわせたインデントを利用する filetype indent on " これらのftではインデントを無効に autocmd FileType html :setlocal indentexpr= autocmd FileType xhtml :setlocal indentexpr= " autocomplpop.vim -------------------------------------------------------- "コマンドラインウインドウの中はAutoComplPopを停止する autocmd CmdwinEnter * AutoComplPopDisable autocmd CmdwinLeave * AutoComplPopEnable " rubycomplete.vim -------------------------------------------------------- autocmd FileType ruby,eruby setlocal omnifunc=rubycomplete#Complete autocmd FileType ruby,eruby let g:rubycomplete_buffer_loading = 1 autocmd FileType ruby,eruby let g:rubycomplete_rails = 1 autocmd FileType ruby,eruby let g:rubycomplete_classes_in_global = 1 " PHPの辞書補完とomni補完 ----------------------------------------------------------- autocmd FileType php setlocal omnifunc=phpcomplete#CompletePHP autocmd FileType php :setlocal dictionary+=~/.vim/dict/php5_functions.dict " svnの時は文字コードをutf8設定 ----------------------------------- autocmd FileType svn :setlocal fileencoding=utf-8 " changelog --------------------------------------------------------------- autocmd BufNewFile,BufRead *.changelog setf changelog " rails ------------------------------------------------------------------- autocmd BufNewFile,BufRead app/**/*.rhtml set fenc=utf-8 autocmd BufNewFile,BufRead app/**/*.rb set fenc=utf-8 autocmd FileType ruby :source $HOME/.vim/ftplugin/ruby-matchit.vim " freemaker(Javaテンプレートエンジン) ------------------------------------- autocmd BufNewFile,BufRead *.ftl setf ftl " git.vim コミット後ログを表示する ---------------------------------------- "autocmd BufWritePost COMMIT_EDITMSG exe ":bd" | exe ":Cd" | exe ":GitLog" " markdown autocmd BufRead,BufNewFile *.mkd setf markdown autocmd BufRead,BufNewFile *.md setf markdown " 前回終了したカーソル行に移動 -------------------------------------------- autocmd BufReadPost * if line("'\"") > 0 && line("'\"") <= line("$") | exe "normal g`\"" | endif endif " Options: オプション設定 ============================================= {{{1 syntax on set ambiwidth=double " UTF-8で文字幅表示を2文字分使う set completeopt=menuone,preview set complete+=k " 辞書ファイルからの単語補間 set nrformats="" " 8進数はインクリメントしない "set expandtab " タブを展開 set tabstop=4 set softtabstop=4 set shiftwidth=4 set smartindent " インデントはスマートインデント set ignorecase " 検索文字列が小文字の場合は大文字小文字を区別なく検索する set smartcase " 検索文字列に大文字が含まれている場合は区別して検索する set wrapscan " 検索時に最後まで行ったら最初に戻る set noincsearch " 検索文字列入力時に順次対象文字列にヒットさせない set nolist " タブの左側にカーソル表示 set showcmd " 入力中のコマンドをステータスに表示する set showmatch " 括弧入力時の対応する括弧を表示 set nohlsearch " 検索結果文字列のハイライトを有効にしない set nu " 行番号を表示する set nobackup " バックアップファイルは作らない set wildmenu " コマンドライン補完するときに強化されたものを使う set wildmode=list:longest " コマンドライン補間をシェルっぽく set hidden " バッファが編集中でもその他のファイルを開けるように set autoread " 外部のエディタで編集中のファイルが変更されたら自動で読み直す set wrap " 自動折り返し set laststatus=2 " 常にステータス行を表示 (詳細は:he laststatus) set cmdheight=2 " コマンドラインの高さ (Windows用gvim使用時はgvimrcを編集すること) set title " タイトルを表示 set lazyredraw " マクロなど実行中は描画を中断 set foldmethod=marker " 折畳み "set cursorline " カーソル行を強調表示 "hi CursorLine gui=underline " 下線 set viminfo='50,<1000,s100,\"50 " viminfoの上限数など set backspace=indent,eol,start " バックスペースを強化する設定 set textwidth=0 " Don't wrap words by default set history=100 " コマンド履歴数 set ruler " show the cursor position all the time set guioptions-=T "ツールバーを表示しない set suffixes=.bak,~,.swp,.o,.info,.aux,.log,.dvi,.bbl,.blg,.brf,.cb,.ind,.idx,.ilg,.inx,.out,.toc if has('migemo') set migemo " Migemo用検索 endif "ステータスラインに文字コードと改行文字を表示する(ウインドウ幅によって表示項目を調整) if winwidth(0) >= 120 set statusline=%<[%n]%m%r%h%w%{'['.(&fenc!=''?&fenc:&enc).':'.&ff.']'}%y\ %(%{GitBranch()}\ %)\ %F%=[%{GetB()}]\ %l,%c%V%8P else set statusline=%<[%n]%m%r%h%w%{'['.(&fenc!=''?&fenc:&enc).':'.&ff.']'}%y\ %(%{GitBranch()}\ %)\ %F%=[%{GetB()}]\ %l,%c%V%8P endif " prg設定 set grepprg="grep" " }}}1 " Mapping: マッピング設定 ============================================= {{{1 " Macの場合にLeader設定 if has('mac') && has('gui_running') let mapleader = "\\" endif if has('clipboard') noremap tv :set clipboard= noremap tc :set clipboard=unnamed endif " のタイプがずれた時対策 inoremap "noremap "cnoremap "inoremap " command mode 時 Emacs風のキーバインドに cnoremap cnoremap cnoremap cnoremap cnoremap cnoremap cnoremap " カーソル位置にかかわらず全部消す cnoremap inoremap inoremap inoremap inoremap inoremap " そのコマンドを実行 nnoremap ,e :execute '!' &ft ' %' "インデントを考慮して貼り付け "nnoremap p p='] "表示行単位で行移動する nnoremap j gj nnoremap k gk vnoremap j gj vnoremap k gk "単語の移動 noremap E e noremap W w noremap B b " 標準の単語選択 vnoremap iw iw vnoremap ie ie " 選択時にペーストしたときに最後のレジスタを上書きする vnoremap p p:call SelectPasteTextOverWriteRegister() " マウス操作でスクロールした時に誤操作で意図しないペーストをしない noremap inoremap "クリップボードを使ったコピペ vnoremap "+y inoremap nnoremap i " 全て選択 nnoremap V ggVG " 改行を含まない1行選択 nnoremap v 0v$h "rubyのメソッドやクラスをまとめて選択する(b:block用、m:def用、c:class用、M:module用) nnoremap vab 0/end%Vn nnoremap vib 0/end%kVnj nnoremap vam $?\%(.*#.*def\)\@!def%Vn nnoremap vim $?\%(.*#.*def\)\@!def%kVnj nnoremap vac $?\%(.*#.*class\)\@!class%Vn nnoremap vic $?\%(.*#.*class\)\@!class%kVnj nnoremap vaM $?\%(.*#.*module\)\@!module%Vn nnoremap viM $?\%(.*#.*module\)\@!module%kVnj ".vimrcの再読み込み nnoremap ,vr :source $HOME/.vimrc:source $HOME/.gvimrc " YankRingっぽいレジスタ履歴Yank&Paste vnoremap y :call NumberedRegisterRotation()gvy vnoremap x :call NumberedRegisterRotation()gvx vnoremap d :call NumberedRegisterRotation()gvd nnoremap yy :call NumberedRegisterRotation()yy nnoremap dd :call NumberedRegisterRotation()dd inoremap =RegistersComplete() nnoremap i=RegistersComplete() " 設定をトグルする {{{2 nnoremap tw :set wrap! " }}}2 " 設定を有効にする {{{2 nnoremap ea :AutoComplPopEnable " }}}2 " 設定を無効にする {{{2 nnoremap da :AutoComplPopDisable " }}}2 " 検索時に画面中央にくるようにする " nzzを割り当てるとfold時の検索でnを押して次に進んだ場合に自動展開されない nnoremap n nzzzv nnoremap N Nzzzv nnoremap * *zzzv nnoremap # #zzzv nnoremap g* g*zzzv nnoremap g# g#zzzv " 選択中の文字を検索する "vnoremap n :call SelSearch() vnoremap n :call SearchTheSelectedTextLiteraly() " 選択中の文字をURLエスケープする(1:エンコード 2:デコード) vnoremap ue :call UrlEscapeTheSelectedTextLiteraly(1) vnoremap ud :call UrlEscapeTheSelectedTextLiteraly(2) " migemo検索用(incsearchの設定を行う) nnoremap g/ :set incsearchg/ nnoremap g? :set incsearchg? " perl系正規表現検索用(/でLL系正規表現が使えるようにする。※eregex.vimを使う) nnoremap / :set noincsearch:M/ " vim正規表現検索用(元のデフォルトの/検索は) nnoremap ,/ :set noincsearch/ nnoremap ? :set noincsearch? " textobj-datetimeの設定 silent! call textobj#datetime#default_mappings(1) "ScreenのキーバインドでC-Tを割り当てているため、タグジャンプの戻るはc-[に割り当てる。 nnoremap :pop " tags key map (C-z を C-tに,C-tはGNU/screenとかぶる) noremap " 選択中のCSVカラム名の列をハイライト表示する vnoremap ,hc :call SelectCsvH() if has("win32") " 画面の最大化と元のサイズをキーに割り当て noremap :simalt ~x noremap :simalt ~r "文字の大きさ変更キーマップ noremap _w :simalt ~r:set guifont=MS_Gothic:h12:cSHIFTJIS:set columns=110:set lines=30 noremap _1 :simalt ~r:set columns=110 lines=30 noremap _2 :simalt ~x:let &guifont=substitute(&guifont, ":h\\d\\+:", ":h16:", "") noremap _3 :simalt ~x:let &guifont=substitute(&guifont, ":h\\d\\+:", ":h18:", "") noremap _4 :simalt ~x:let &guifont=substitute(&guifont, ":h\\d\\+:", ":h20:", "") noremap _5 :simalt ~x:let &guifont=substitute(&guifont, ":h\\d\\+:", ":h24:", "") noremap _6 :simalt ~x:let &guifont=substitute(&guifont, ":h\\d\\+:", ":h32:", "") noremap _7 :simalt ~x:let &guifont=substitute(&guifont, ":h\\d\\+:", ":h48:", "") endif " 異なるプロセスvim間でコピー(yanktmp.vim用) noremap sy :call YanktmpYank() noremap sp :call YanktmpPaste_p() noremap sP :call YanktmpPaste_P() " 水平スクロール nnoremap zl nnoremap zh "FuzzyFinder時にCtrl-Dで一行消しできるように inoremap \=repeat('', setline('.', '')) " phpdocumenter.php nnoremap ppd :call PhpDocSingle() vnoremap ppd :call PhpDocRange() " Plugin: プラグイン設定 ============================================== {{{1 " Vimball if has('win32') let g:vimball_home = "C:/configs/.vim/" else let g:vimball_home = "~/configs/.vim/" endif " QuickFix noremap mm QuickFixNote noremap :copen noremap ms QuickFixSave " Gauche autocmd FileType scheme :let is_gauche=1 autocmd FileType scheme :setlocal dictionary+=~/.vim/dict/gosh_completions.dict " QuicRun ----------------------------------------------------- {{{2 nnoremap e :QuickRun let g:quickrun_config = {} let g:quickrun_config['markdown'] = { \ 'type': 'markdown/pandoc', \ 'outputter': 'browser', \ 'cmdopt': '-c ~/style.css -s' \ } " git.vim ----------------------------------------------------- {{{2 nnoremap gs :CD \| GitStatus nnoremap ga :CD \| GitAdd nnoremap gac :CD \| GitAdd =expand("%:t") nnoremap gd :CD \| GitDiff nnoremap gc :CDGit \| GitCommit nnoremap gcs :CDGit \| GitCommit nnoremap gca :CDGit \| GitCommit -a nnoremap gcc :CDGit \| GitCommit =expand("%:t") nnoremap gl :CD \| GitLog nnoremap gs :CD \| GitStatus " ":CD :GitStatus"では (:help )が実行されてしまう。 "nnoremap gs :CD :GitStatus " }}}2 " project.vim ------------------------------------------------------------- {{{2 let g:proj_window_width = 32 " CamelCase Motion -------------------------------------------------------- {{{2 " Replace the default 'w', 'b' and 'e' mappings instead of defining nmap w CamelCaseMotion_w nmap b CamelCaseMotion_b nmap e CamelCaseMotion_e " Replace default 'iw' text-object and define 'ie' and 'ib' motions: omap iw CamelCaseMotion_iw vmap iw CamelCaseMotion_iw omap ib CamelCaseMotion_ib vmap ib CamelCaseMotion_ib omap ie CamelCaseMotion_ie vmap ie CamelCaseMotion_ie " sqlUtil ----------------------------------------------------------------- {{{2 let g:sqlutil_align_where = 1 let g:sqlutil_align_comma = 1 " SourceExplorer ---------------------------------------------------------- {{{2 "自動でプレビューを表示する。TODOうざくなってきたら手動にする。またはソースを追う時だけ自動に変更する let g:SrcExpl_RefreshTime = 1 "プレビューウインドウの高さ let g:SrcExpl_WinHeight = 9 "tagsは自動で作成する let g:SrcExpl_UpdateTags = 1 let g:SrcExpl_RefreshMapKey = "" let g:SrcExpl_GoBackMapKey = "" nnoremap :SrcExplToggle let g:SrcExpl_pluginList = [ \ "__Tag_List__", \ "_NERD_tree_", \ "Source_Explorer" \ ] "FuzzyFinder用 ----------------------------------------------------------- {{{2 nnoremap fb :FuzzyFinderBuffer nnoremap fc :FuzzyFinderMruCmd nnoremap fd :FuzzyFinderDir nnoremap ff :FuzzyFinderFile nnoremap fm :FuzzyFinderMruFile nnoremap fv :FuzzyFinderBookmark nnoremap ft :FuzzyFinderTag "speeddating.vim用のマッピング ------------------------------------------- {{{2 " システム日付を挿入する inoremap dF =strftime('%Y-%m-%dT%H:%M:%S+09:00') inoremap df =strftime('%Y-%m-%dT%H:%M:%S') inoremap dd =strftime('%Y-%m-%d') inoremap dT =strftime('%H:%M:%S') inoremap dt =strftime('%H:%M') " calender.vim ------------------------------------------------------------ {{{2 "let g:calendar_erafmt = '平成,-1988' "let g:calendar_mruler ='1月,2月,3月,4月,5月,6月,7月,8月,9月,10月,11月,12月' "let g:calendar_wruler = '日 月 火 水 木 金 土 日' " NERD_comments.vim ------------------------------------------------------- {{{2 " コメントの間にスペースを空ける let NERDSpaceDelims = 1 " 対応していないファイルに対して警告をしない let NERDShutUp = 1 " netrw ------------------------------------------------------------------- {{{2 let g:netrw_ftp_cmd="netkit-ftp" " netrw-ftp let g:netrw_http_cmd="wget -q -O" " netrw-http " surround.vim ------------------------------------------------------------ {{{2 "surroundに定義を追加する【ASCIIコードを調べるには:echo char2nr("-")】 "タグ系 let g:surround_{char2nr('!')} = "" let g:surround_{char2nr('%')} = "<% \r %>" let g:surround_{char2nr('-')} = "" "変数展開系 let g:surround_{char2nr('#')} = "#{\r}" let g:surround_{char2nr('$')} = "${\r}" let g:surround_{char2nr('@')} = "@{\r}" " tabbar.vim -------------------------------------------------------------- {{{2 let g:Tb_MaxSize=3 " }}}2 " scratch.vim ------------------------------------------------------------ {{{2 let g:scratch_buffer_name = "Scratch" " }}}2 " Color: 色設定 ======================================================= {{{1 " 特定の文字を視覚化。この例では全角スペース " TODO:listcharsの設定と調整する "highlight ZenkakuSpace cterm=underline ctermfg=lightblue guibg=white "match ZenkakuSpace / / if !has('gui_running') set background=dark highlight Folded ctermfg=yellow ctermbg=black highlight FoldColumn ctermfg=yellow ctermbg=black highlight Pmenu ctermfg=white ctermbg=darkgray guibg=#606060 highlight PmenuSel ctermbg=darkred guibg=SlateBlue highlight PmenuSbar ctermbg=darkblue guibg=#404040 endif " Tags: tags設定 ====================================================== {{{1 if has("autochdir") set autochdir set tags=tags; else "set tags=$HOME/.vim/tags,./tags,./../tags,./*/tags,./../../tags,./../../../tags,./../../../../tags,./../../../../../tags set tags+=./tags endif command! -nargs=? Ctags call Ctags() " Function: 関数定義 ================================================== {{{1 " ---------------------------------------------------------------------------- " 関数 " ---------------------------------------------------------------------------- "-------------------------------------------------------- " ステータスライン表示に使用する関数群 " ------------------------------------------------------- function! GetB() let c = matchstr(getline('.'), '.', col('.') - 1) let c = iconv(c, &enc, &fenc) return String2Hex(c) endfunction function! Nr2Hex(nr) let n = a:nr let r = "" while n let r = '0123456789ABCDEF'[n % 16] . r let n = n / 16 endwhile return r endfunc function! String2Hex(str) let out = '' let ix = 0 while ix < strlen(a:str) let out = out . Nr2Hex(char2nr(a:str[ix])) let ix = ix + 1 endwhile return out endfunc "------------------------------------------------------------------- "Screenのステータスラインに編集中のファイルを表示し、 " 終了時にはShellと表示する。※^[ はctrl + v を押しながら [ "------------------------------------------------------------------- function! SetScreenTabName(name) let arg = 'k' . a:name . ' > vim \\' silent! exe '!echo -n "' . arg . "\"" endfunction "------------------------------------------------------------------- " 自動補完をタブで選択できるように(cho45さんから) " http://subtech.g.hatena.ne.jp/cho45/20071009#c1191925480 "------------------------------------------------------------------- "function! InsertTabWrapper() " let col = col('.') - 1 " if !col || getline('.')[col - 1] !~ '\k' " return "\" " else " if pumvisible() " return "\" " else " return "\\" " end " endif "endfunction "" インサート時のTabキーマッピングをInsertTabWrapperで書き換える "inoremap =InsertTabWrapper() "------------------------------------------------ " CSVのハイライト表示 " @see http://www.vim.org/tips/tip.php?tip_id=667 "------------------------------------------------ " csv の特定のカラムをハイライト (put in .vimrc) " :Csv 5 # 5番めのカラムをハイライト function! CSVH(x) execute 'match Keyword /^\([^,]*,\)\{'.a:x.'}\zs[^,]*/' execute 'normal ^'.a:x.'f,' endfunction command! -nargs=1 Csv :call CSVH() "----------------------------- " カラム名からIndex値を取得する "----------------------------- function! CsvCol2Index(colName) ruby << EOF colName = VIM::evaluate("a:colName") columns = eval("[#{VIM::Buffer.current.line}]") colIndex = columns.index(colName) || -1 VIM::command("return '#{colIndex.to_s#}'") EOF endfunction "------------------------------------------------ "選択中のCSVカラムをハイライトする "------------------------------------------------ function! SelectCsvH() "最後のヤンクを保管しておく let tmp = @" "現在選択中のテキストを取得する normal! gv"ty "取得した結果を変数に格納する let seltext=@t let columnNumber = CsvCol2Index(seltext) if columnNumber >= 0 let result = CSVH(columnNumber) else echo "対象のカラムは存在しません" endif "最後のヤンクを書き戻す let @" = tmp let @/ = seltext endfunction "----------------------------- " html escape function "----------------------------- function! HtmlEscape() silent s/&/\&/eg silent s//\>/eg endfunction function! HtmlUnEscape() silent s/<//eg silent s/&/\&/eg endfunction "------------------------------------------------ "選択中の文字列を検索する "------------------------------------------------ "function! SelSearch() " "最後のヤンクを保管しておく " let tmp = @" " "現在選択中のテキストを取得する " normal! gv"ty " "取得した結果を変数に格納する " let seltext=@t " silent! exe ":/" . seltext " "最後のヤンクを書き戻す " let @" = tmp " let @/ = seltext " "二回の移動を組み合わせることで、次の検索したい文字列へジャンプする " normal! N " normal! n "endfunction function! SearchTheSelectedTextLiteraly() let reg_0 = [@0, getregtype('0')] let reg_u = [@", getregtype('"')] normal! gvy let @/ = @0 call histadd('/', '\V' . escape(@0, '\')) normal! n call setreg('0', reg_0[0], reg_0[1]) call setreg('"', reg_u[0], reg_u[1]) endfunction "------------------------------------------------ " tagファイル作成関数 "------------------------------------------------ "taglist.vim用設定 "tagsを使用できるようにする " tag ファイルの指定 "tagファイル作成関数 " 使い方:srcディレクトリをCtagsの引数に渡すと、~/.vim/tags ファイルを作成します。 " 引数がない場合、vimが認識してるカレントディレクトリでctagsを実行します。 " http://d.hatena.ne.jp/smeghead/searchdiary?word=*%5Bvim%5D function! s:Ctags(searchPath) let searchPath = a:searchPath if searchPath ==# "" let searchPath = getcwd() endif exe ':!ctags -R -f ' . $HOME . '/tags' searchPath endfunction "--------------------------------- " 最後に選択したテキストを取得する "----------------------------- function! x:selected_text() let [visual_p, pos, r_, r0] = [mode() =~# "[vV\]", getpos('.'), @@, @0] if visual_p execute "normal! \" endif normal! gvy let _ = @@ let [@@, @0] = [r_, r0] if visual_p normal! gv else call setpos('.', pos) endif return _ endfunction " :argdoと同等 function! Allargs(command) let i = 0 while i < argc() if filereadable(argv(i)) execute "e " . argv(i) execute a:command endif let i = i + 1 endwhile endfunction command! -nargs=+ -complete=command Allargs call Allargs() " IMEの状態を取得する Return 1:ON 0:OFF function! ImeStatus() if has('win32') && has('ruby') ruby << EOF require 'Win32API' # 最前面のウィンドウハンドルを取得(操作中のvimウインドウ) wndObj = Win32API.new('user32.dll', 'GetForegroundWindow', 'v', 'n') hWnd = wndObj.call # IMEのコンテキストを取得 imcObj = Win32API.new('imm32','ImmGetContext','l','l') himc = imcObj.call(hWnd) # IMEの状態を取得 imeOpenObj = Win32API.new('imm32','ImmGetOpenStatus',%w(l),'l') p imeOpenObj.call(himc).to_s VIM::command("return '" + imeOpenObj.call(himc).to_s + "'") EOF else return '0' endif endfunction "------------------------------------------------ " 選択したテキストのURLEscapeを行う関数 "------------------------------------------------ function! UrlEscapeTheSelectedTextLiteraly(escape_flag) if !has('ruby') echoerr "実行にはRubyインターフェースが必要です" return end let reg_0 = [@0, getregtype('0')] let reg_u = [@", getregtype('"')] normal! gvy let @0 = UrlEscape(a:escape_flag) normal! gvp call setreg('0', reg_0[0], reg_0[1]) call setreg('"', reg_u[0], reg_u[1]) endfunction function! UrlEscape(escape_flag) ruby << EOF require 'cgi' convert_text = "" escape_flag = {:escape => "1", :unescape => "2"} selected_text = VIM::evaluate('@0') escape_flag_param = VIM::evaluate('a:escape_flag') if escape_flag_param == escape_flag[:escape] convert_text = CGI.escape(selected_text) elsif escape_flag_param == escape_flag[:unescape] convert_text = CGI.unescape(selected_text) end VIM::command("return '#{convert_text}'") EOF endfunction function SelectPasteTextOverWriteRegister() let @" = @0 endfunction " YankRingっぽいローテーションペーストを行う " TODO:複数行の対応とレジスタ汚染などの問題 function! NumberedRegisterRotation() let @9 = @8 let @8 = @7 let @7 = @6 let @6 = @5 let @5 = @4 let @4 = @3 let @3 = @2 let @2 = @1 let @1 = @" endfunction function! RegistersComplete() call complete(col('.'), [@",@1,@2,@3,@4,@5,@6,@7,@8,@9]) return '' endfunction " .gitのあるディレクトリに移動する function! CdDotGitDir() let l:current_path = getcwd() lcd %:p:h if finddir('.git','.;') !~ ".git$" echo 'Not found dotgit directory.' exec "lcd " . l:current_path return '' endif let l:dotgit_path = SearchDotGitPath('') exec "lcd " . l:dotgit_path endfunction function! SearchDotGitPath(search_path) if finddir('.git', a:search_path) =~ ".git$" return a:search_path else let l:search_path = a:search_path . '../' let l:search_result_path = SearchDotGitPath(l:search_path) return l:search_result_path endif endfunction " Envroiments: 環境固有設定 =========================================== {{{1 "Screenの場合にvimを使用した時にスクリーンタブ名を書き換える if &term =~ "screen" autocmd VimLeave * call SetScreenTabName('shell') autocmd BufEnter * if bufname("") !~ "^\[A-Za-z0-9\]*://" | call SetScreenTabName("%") | endif endif " 公開できない設定やローカルマシンごとの固有設定を読み込む if filereadable("$HOME/.private/.vimrc_private") source $HOME/.private/.vimrc_private endif " Tmp: 一時な設定 ===================================================== {{{1 " Copy and paste with fakeclip " Command-C and Command-V are also available in MacVim " see :help fakeclip-multibyte-on-mac map gy "*y map gp "*p if exists('$WINDOW') || exists('$TMUX') map gY (fakeclip-screen-y) map gP (fakeclip-screen-p) endif " ckfix のエラー箇所を波線でハイライト let g:hier_enabled = 1 " quickfix に出力して、ポッポアップはしない outputter/quickfix " すでに quickfix ウィンドウが開いている場合は閉じるので注意 let s:silent_quickfix = quickrun#outputter#quickfix#new() function! s:silent_quickfix.finish(session) call call(quickrun#outputter#quickfix#new().finish, [a:session], self) :cclose " vim-hier の更新 :HierUpdate " quickfix への出力後に quickfixstatus を有効に :QuickfixStatusEnable endfunction " quickrun に登録 call quickrun#register_outputter("silent_quickfix", s:silent_quickfix) " ファイルの保存後に quickrun.vim が実行するように設定する autocmd BufWritePost *.c,*.h,*.h :QuickRun c -outputter quickfix autocmd FileType qf nnoremap q :q:HierClear " Etc: その他 ========================================================= {{{1 " ^@を削除するテスト inoremap :%s/$//ge:%s//\r/geA " Disable AutoComplPop. let g:acp_enableAtStartup = 0 " Use neocomplcache. let g:neocomplcache_enable_at_startup = 1 " Use smartcase. let g:neocomplcache_enable_smart_case = 1 " Use camel case completion. let g:neocomplcache_enable_camel_case_completion = 1 " Use underbar completion. let g:neocomplcache_enable_underbar_completion = 1 " Set minimum syntax keyword length. let g:neocomplcache_min_syntax_length = 2 let g:neocomplcache_lock_buffer_name_pattern = '\*ku\*' let g:neocomplcache_auto_completion_start_length = 2 " Define dictionary. let g:neocomplcache_dictionary_filetype_lists = { \ 'default' : '', \ 'vimshell' : $HOME.'/.vimshell_hist', \ 'scheme' : $DOTVIM.'/.gosh_completions', \ 'scala' : $DOTVIM.'/dict/scala.dict', \ 'css' : $DOTVIM.'/dict/css.dict', \ 'html' : $DOTVIM.'/dict/html.dict', \ 'perl' : $DOTVIM.'/dict/perl.dict', \ 'ruby' : $DOTVIM.'/dict/ruby.dict' \ } " Define keyword. if !exists('g:neocomplcache_keyword_patterns') let g:neocomplcache_keyword_patterns = {} endif let g:neocomplcache_keyword_patterns['default'] = '\h\w*' " Plugin key-mappings. imap (neocomplcache_snippets_expand) smap (neocomplcache_snippets_expand) inoremap neocomplcache#undo_completion() inoremap neocomplcache#complete_common_string() " SuperTab like snippets behavior. "imap neocomplcache#sources#snippets_complete#expandable() ? "\(neocomplcache_snippets_expand)" : pumvisible() ? "\" : "\" " Recommended key-mappings. " : close popup and save indent. inoremap neocomplcache#smart_close_popup() . "\" " : completion. inoremap pumvisible() ? "\" : "\" " , : close popup and delete backword char. inoremap neocomplcache#smart_close_popup()."\" inoremap neocomplcache#smart_close_popup()."\" inoremap neocomplcache#close_popup() inoremap neocomplcache#cancel_popup() " AutoComplPop like behavior. "let g:neocomplcache_enable_auto_select = 1 " Shell like behavior(not recommended). "set completeopt+=longest "let g:neocomplcache_enable_auto_select = 1 "let g:neocomplcache_disable_auto_complete = 1 "inoremap pumvisible() ? "\" : "\" "inoremap neocomplcache#smart_close_popup() . "\" " Enable omni completion. autocmd FileType css setlocal omnifunc=csscomplete#CompleteCSS autocmd FileType html,markdown setlocal omnifunc=htmlcomplete#CompleteTags autocmd FileType javascript setlocal omnifunc=javascriptcomplete#CompleteJS autocmd FileType python setlocal omnifunc=pythoncomplete#Complete autocmd FileType xml setlocal omnifunc=xmlcomplete#CompleteTags " Enable heavy omni completion. if !exists('g:neocomplcache_omni_patterns') let g:neocomplcache_omni_patterns = {} endif "let g:neocomplcache_omni_patterns.ruby = '[^. *\t]\.\w*\|\h\w*::' autocmd FileType ruby setlocal omnifunc=rubycomplete#Complete let g:neocomplcache_omni_patterns.php = '[^. \t]->\h\w*\|\h\w*::' let g:neocomplcache_omni_patterns.c = '\%(\.\|->\)\h\w*' """ Unite.vim " 起動時にインサートモードで開始 " let g:unite_enable_start_insert = 1 " " " インサート/ノーマルどちらからでも呼び出せるように " キー """ Unite.vim " 起動時にインサートモードで開始 let g:unite_enable_start_insert = 1 let g:unite_source_history_yank_enable = 1 "" インサート/ノーマルどちらからでも呼び出せるようにキーマップ "nnoremap :UniteWithBufferDir -buffer-name=files file "inoremap :UniteWithBufferDir -buffer-name=files file "nnoremap :Unite buffer file_mru "inoremap :Unite buffer file_mru nnoremap fb :Unite buffer nnoremap fc :Unite command nnoremap fd :Unite directory_mru nnoremap ff :UniteWithBufferDir -buffer-name=files file nnoremap fp :Unite -buffer-name=register register nnoremap fm :Unite file_mru nnoremap fv :Unite bookmark " unite.vim上でのキーマッピング autocmd FileType unite call s:unite_my_settings() function! s:unite_my_settings() " 単語単位からパス単位で削除するように変更 imap (unite_delete_backward_path) " ESCキーを2回押すと終了する nmap q imap q endfunction