"======================================================================
" Vundle
"
" {{{1
set nocompatible               " be iMproved
filetype plugin indent off     " required!

if has('win32') || has('win64')
  let $DOTVIM = expand('$HOME/vimfiles')
  " https://github.com/gmarik/vundle/issues/146  
  set shellxquote=
else
  let $DOTVIM = expand('~/.vim')
endif
"let $DOTVIM = expand('$HOME/.vim')
set rtp+=$DOTVIM/bundle/vundle/
call vundle#rc('$DOTVIM/bundle')
"call vundle#rc()

" let Vundle manage Vundle
Bundle 'gmarik/vundle'

" My Bundles :
" original repos on github -----
Bundle 'Shougo/neocomplcache'
Bundle 'Shougo/unite.vim'
Bundle 'Shougo/vimfiler'
Bundle 'Shougo/vimshell'
Bundle 'Shougo/vimproc' 
" == after install, turn shell ~/.vim/bundle/vimproc, (n,g)make -f your_machines_makefile
Bundle 'Lokaltog/vim-easymotion'
Bundle 'Sixeight/unite-grep'
Bundle 'h1mesuke/textobj-wiw'
Bundle 'gregsexton/gitv'
Bundle 'kana/vim-textobj-user'
Bundle 'kien/ctrlp.vim'
"Bundle 'koron/u-nya-vim'
Bundle 'mattn/hahhah-vim'
Bundle 'mattn/vdbi-vim'
Bundle 'thinca/vim-quickrun'
Bundle 'thinca/vim-ref'
Bundle 'tsaleh/vim-align'
Bundle 'tyru/caw.vim'
Bundle 'tyru/open-browser.vim'
Bundle 'tyru/restart.vim'
Bundle 'majutsushi/tagbar'
Bundle 'mattn/gist-vim'
"Bundle 'Lokaltog/vim-powerline'
Bundle 'gregsexton/VimCalc'
Bundle 'Shougo/unite-ssh'
Bundle 'ujihisa/vimshell-ssh'
Bundle 'chrisbra/csv.vim'
Bundle 'sjl/gundo.vim'
" Markdown ---------------------
Bundle 'tpope/vim-markdown'
"Bundle 'hallison/vim-markdown'
" Ruby (on rails) --------------
Bundle 'tpope/vim-rails'
Bundle 'tpope/vim-surround'
Bundle 'tpope/vim-bundler'
" conflicting with neocomplecache
"Bundle 'tpope/vim-endwise'
Bundle 'vim-ruby/vim-ruby'
" Python -----------------------
"Bundle 'fs111/pydoc.vim'
"Bundle 'scrooloose/syntastic'
"Bundle 'klen/python-mode'
" Python -----------------------
Bundle 'hotchpotch/perldoc-vim'
Bundle 'c9s/perlomni.vim'
" vim-scripts repos ------------
Bundle 'autodate.vim'
Bundle 'bufexplorer.zip'
Bundle 'jQuery'
Bundle 'taglist.vim'
Bundle 'ViewOutput'
Bundle 'fugitive.vim'
Bundle 'sudo.vim'
" color shemes ;) --------------
Bundle 'blackboard.vim'
Bundle 'altercation/vim-colors-solarized'
Bundle 'tomasr/molokai'
Bundle 'jpo/vim-railscasts-theme'
Bundle 'hukl/Smyck-Color-Scheme'
" NETA -------------
Bundle 'mattn/webapi-vim'
Bundle 'mattn/unite-advent_calendar'
Bundle 'mattn/togetter-vim'
" non github repos -------------
" Experimental -------------

filetype plugin indent on " required!
syntax on
"
" Brief help
" :BundleList          - list configured bundles
" :BundleInstall(!)    - install(update) bundles
" :BundleSearch(!) foo - search(or refresh cache first) for foo
" :BundleClean(!)      - confirm(or auto-approve) removal of unused bundles
"
" see :h vundle for more details or wiki for FAQ
" NOTE: comments after Bundle command are not allowed..
"1}}}

"======================================================================
" Generic
"
"{{{1
set foldmethod=syntax
set linespace=0
set autoindent
set backspace=2
set wrapscan
set showmatch
set wildmenu
set number
set formatoptions+=mM " テキスト挿入中の自動折り返しを日本語に対応させる
set ruler             " ルーラーを表示 (noruler:非表示)
set nolist            " タブや改行を非表示 (list:表示)
set listchars=tab:>-,extends:<,trail:-,eol:<                     " どの文字でタブや改行を表示するかを設定
set wrap              " 長い行を折り返して表示 (nowrap:折り返さない)
set laststatus=2      " 常にステータス行を表示 (詳細は:he laststatus)
set cmdheight=1       " コマンドラインの高さ (Windows用gvim使用時はgvimrcを編集すること)
set showcmd           " コマンドをステータス行に表示
set title             " タイトルを表示
"set fileencodings=iso-2022-jp-3,iso-2022-jp,euc-jisx0213,euc-jp,utf-8,ucs-bom,euc-jp,euc-jp-ms,cp932      " 文字コード判定用設定(p66@bible)
set fileencodings=utf-8,ucs-bom,euc-jp,euc-jp-ms,cp932      " utfが先に来てくれなれないとイヤ

"" カーソルを行頭、行末で止まらないようにする
"" REF :http://blog.blueblack.net/item_110
" 2011-11-25 止まったほうが嬉しかったのでコメントアウト
"set whichwrap=b,s,h,l,<,>,[,]

" ファイルの保存ダイアログの初期ディレクトリを指定する
"     buffer :  編集中のファイルのあるディレクトリ
"     current:  カレントディレクトリ
"     %PATH% :  ディレクトリを直接指定する
"     last   :  最後に保存したディレクトリ
" REF :http://advweb.seesaa.net/article/11311975.html
set browsedir=buffer

" バックアップファイルを作るディレクトリを指定
" バックアップファイル名にlocaltimeを付与
" REF :http://www15.ocn.ne.jp/~tusr/vim/options_help.html
"      http://d.hatena.ne.jp/zenpou/20071003/1191432687 
set backup
set backupdir=$DOTVIM/.vimbackups
let file = strftime(".%Y%m%d%H%M%S", localtime())
exe "set backupext=".file
unlet file

" セッションの保存に以下の情報を含める
"       -ウィンドウサイズ
"       -Unix系との互換(ディレクトリの区切り文字の違いを吸収する)
" REF :http://www.ac.cyberhome.ne.jp/~yakahaira/vimdoc/usr_21.html
set sessionoptions+=resize
set sessionoptions+=unix,slash

" ステータスラインの表示情報
" REF : http://d.hatena.ne.jp/zenpou/20071003/1191432687
set statusline=
set statusline +=[#%n]\                                   " バッファ番号
set statusline +=%{fugitive#statusline()}\                " fugitive
set statusline +=%t\                                      " ファイル名
set statusline +=%{'['.(&fenc!=''?&fenc:'?').':'.&ff.']'} " 文字コード
set statusline +=%{'['.(&ft!=''?&ft:'ft=?').']'}          " 2008-10-06 ファイルタイプ表示追加
set statusline +=%m                                       " バッファ状態[+]とか
set statusline +=%r                                       " 読み取り専用フラグ
set statusline +=%h                                       " ヘルプバッファ
set statusline +=%w                                       " プレビューウィンドウ
set statusline +=%=                                       " 区切り
set statusline +=%{g:HahHah()}                            " ???
set statusline +=%4l,%2c                                  " 行、列
set statusline +=[%3p%%]                                  " どこにいるか
"set statusline +=%{'['.b:charCounterCount.']'}            " 文字数カウント
set statusline +=\ %{strftime('%x(%a)_%H:%M')}\           " 時間
set statusline +=%<                                       " 折り返しの指定

" 入力モード時、ステータスラインの色を変える
" REF :http://blog.blueblack.net/item_110
highlight statusline term=NONE cterm=NONE guifg=#2E4340 guibg=#ccdc90
augroup InsertHook
  autocmd!
  autocmd InsertEnter * highlight StatusLine guifg=#2E4340 guibg=#ccdc90
  autocmd InsertLeave * highlight StatusLine guifg=#ccdc90 guibg=#2E4340
augroup END

" 検索語が真ん中に来るようにする
" REF :http://www.kawaz.jp/pukiwiki/?vim
nmap n nzz
nmap N Nzz
nmap * *zz
nmap # #zz
nmap g* g*zz
nmap g# g#zz

" 閉じる時自動で内側に移動する
" REF :http://d.hatena.ne.jp/zenpou/20071003/1191432687
if exists("s:did_gvimrc") == 0
  imap <silent> <unique>"" ""<Left>
  imap <silent> <unique>{} {}<Left>
  imap <silent> <unique>[] []<Left>
  imap <silent> <unique>() ()<Left>
  imap <silent> <unique>'' ''<Left>
  imap <silent> <unique><> <><Left>
endif
let s:did_gvimrc = 1

" 挿入モード中に日付を形式で挿入
" REF :http://uprush.net/book/6/229/vimrc.html
inoremap <C-D> <C-R>=strftime("%Y-%m-%d")<CR>
inoremap <C-T> <C-R>=strftime("%H:%M:%S")<CR>

" カーソルの点滅をしない
" SRC :http://takesy.cocolog-nifty.com/atico/2008/02/windowsgvim_bc99.html
set guicursor=a:blinkwait700-blinkon1000-blinkoff0

".が何か一文字という意味になる
set magic

" swpファイルを作成するディレクトリを固定
set directory=$DOTVIM/.swp

" ディレクトリショートカット
nmap <silent> <F4> :e<Space>$DOTVIM/vimrc<CR>
nmap <silent> <F5> :e<Space>$DOTVIM/gvimrc<CR>

" 編集中の内容を保ったまま別の画面に切り替えられるようにする
set hid

" no sound on errors.
set noerrorbells

" Tabでオートインデント
" http://blog.livedoor.jp/pokketo-program/archives/3091245.html
inoremap <Tab> <C-o>==

" 補完用ソースディレクトリをパスに追加
let $PATH=$PATH.":".$HOME."/.vim/.references/bin"

" 印刷時のエンコード設定
set printencoding=utf-8

" http://d.hatena.ne.jp/fuenor/20090907/1252315621
" 縦に連番を入力する
nnoremap <silent> co :ContinuousNumber <C-a><CR>
vnoremap <silent> co :ContinuousNumber <C-a><CR>
command! -count -nargs=1 ContinuousNumber let c = col('.')|for n in range(1, <count>?<count>-line('.'):1)|exec 'normal! j' . n . <q-args>|call cursor('.', c)|endfor

" Y出カーソル位置から行末までをコピー
nnoremap Y y$ 

"1}}}


"----------------------------------------------------------------------
"                       Filetype Settings
"----------------------------------------------------------------------
"{{{1
"======================================================================
" defaults
"
set softtabstop=4
set tabstop=4
set shiftwidth=4
set expandtab
set smarttab

"======================================================================
" ruby/rails {{{2
" Ruby(rails)ファイル編集時のエンコード・タブ展開・インデントを指定
" REF :http://d.hatena.ne.jp/moro/20060328/1143556931
au FileType ruby  :set nowrap softtabstop=2 tabstop=2 tw=0 sw=2 expandtab
au FileType eruby  :set nowrap softtabstop=2 tabstop=2 tw=0 sw=2 expandtab
au BufNewFile *.rb set ft=ruby fencs=utf-8
au BufNewFile,BufRead *.erb set ft=eruby.html fencs=utf-8
" Rspec(http://stackoverflow.com/questions/8848896/why-do-i-get-syntax-highlighting-for-rspec-only-in-some-projects-in-vim)
autocmd BufRead *_spec.rb syn keyword rubyRspec describe context it specify it_should_behave_like before after setup subject its shared_examples_for shared_context let
highlight def link rubyRspec Function

"2}}}

"======================================================================
" python {{{2
" カラーマッピングが微妙に違う ... 何入れたっけ？
" なんでsyntax foldingができんのやろ？
" プラギンいれるとからマッピング狂うし... あれか、作れっちゅう話か.
au FileType python  :set nowrap ts=4 tw=0 sw=4 fdm=indent fdn=3 expandtab
au BufNewFile *.py set ft=python fencs=utf-8

"2}}}

"======================================================================
" R {{{2
" 拡張子が".r"若しくは".R"のファイルを開いた時,ファイルタイプをrにする.
" REF : http://d.hatena.ne.jp/Rion778/20090915/1253031011
au BufRead,BufNewFile *.R set ft=r
au BufRead,BufNewFile *.r set ft=r

"2}}}

"======================================================================
" JavaScript(jQuery) {{{2
" 拡張子が".js",ファイルタイプをjqueryにする.
" REF : http://www.vim.org/scripts/script.php?script_id=2416
au BufRead,BufNewFile jquery.*.js set ft=javascript syntax=jquery shiftwidth=4 tabstop=4 expandtab
"let javaScript_fold=1
function! JavaScriptFold()
    setl foldmethod=syntax
    setl foldlevelstart=1
    syn region foldBraces start=/{/ end=/}/ transparent fold keepend extend

    function! FoldText()
        return substitute(getline(v:foldstart), '{.*', '{...}', '')
    endfunction
    setl foldtext=FoldText()
endfunction
au FileType javascript call JavaScriptFold()
au FileType javascript setl fen

"2}}}

"======================================================================
" Markdown {{{2
" quickrunで自動コンパイル & ブラウザオープン
let g:quickrun_config = {}
let g:quickrun_config['markdown'] = {
      \ 'outputter' : 'browser',
      \ 'type' : 'markdown/pandoc',
      \ 'cmdopt' : '-s',
      \}

"2}}}

"======================================================================
" XML {{{2
au Filetype xml :set fdm=indent

"2}}}

"======================================================================
" perl {{{2
" folding
let perl_fold=1
let perl_fold_blocks=1

"2}}}

"======================================================================
" csv {{{2
" Using csv.vim
au FileType csv :set nowrap softtabstop=4 tabstop=4 tw=0 sw=4 noexpandtab
au BufNewFile *.csv set ft=csv

"2}}}
"
"1}}}


"----------------------------------------------------------------------
"                        Plugin Settings
"----------------------------------------------------------------------
"{{{1
"======================================================================
" rails.vim {{{2
"プレビューアドレス
let g:rails_url='http://localhost:3000/'
" ? "railsのオムニ補完有効化
"let g:rubycomplete_buffer_loading=1
"let g:rubycomplete_classes_in_global=1
"let g:rubycomplete_rails=1

"2}}}

"======================================================================
" BufExplorer {{{2
" バッファ切り替えウィンドウのショートカット設定
nmap <C-q> :BufExplorer<CR>

"2}}}

"======================================================================
" Syntastic {{{2
" python-modeテストのため一時コメントアウト.
" python-modeがヨサゲなら消去.
"" REF : http://www.daisaru11.jp/blog/2011/09/vimsyntasticで文法チェックを自動で行う/
"let g:syntastic_enable_signs=1
"let g:syntastic_auto_loc_list=2
"let g:syntastic_write_only=1

"2}}}

"======================================================================
" VimShell {{{2
" ref: vimshell-variables
" 例えば、このように毎回カレントディレクトリを表示する
let g:vimshell_user_prompt = 'getcwd()'
" |vimshell-internal-shell|を実行する際に、
" シェルを起動する端末プログラムを指定する。
"let g:vimshell_use_terminal_command = "ckw -e"
nmap <F11> :VimShell<CR>
"2}}}

"======================================================================
" neocomplecache {{{2
" ref: :h neocomplcache
" 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 = 3
let g:neocomplcache_lock_buffer_name_pattern = '\*ku\*'

" Define dictionary.
let g:neocomplcache_dictionary_filetype_lists = {
    \ 'default' : '',
    \ 'vimshell' : $HOME.'/.vimshell_hist',
    \ 'scheme' : $HOME.'/.gosh_completions'
        \ }

" 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 <C-k>     <Plug>(neocomplcache_snippets_expand)
smap <C-k>     <Plug>(neocomplcache_snippets_expand)
inoremap <expr><C-g>     neocomplcache#undo_completion()
inoremap <expr><C-l>     neocomplcache#complete_common_string()

" SuperTab like snippets behavior.
imap <expr><TAB> neocomplcache#sources#snippets_complete#expandable() ? "\<Plug>(neocomplcache_snippets_expand)" : pumvisible() ? "\<C-n>" : "\<TAB>"

" Recommended key-mappings.
" <CR>: close popup and save indent.
inoremap <expr><CR>  neocomplcache#close_popup() . "\<CR>"
" <TAB>: completion.
inoremap <expr><TAB>  pumvisible() ? "\<C-n>" : "\<TAB>"
" <C-h>, <BS>: close popup and delete backword char.
inoremap <expr><C-h> neocomplcache#smart_close_popup()."\<C-h>"
inoremap <expr><BS> neocomplcache#smart_close_popup()."\<C-h>"
inoremap <expr><C-y>  neocomplcache#close_popup()
inoremap <expr><C-e>  neocomplcache#cancel_popup()

"" For cursor moving in insert mode(Not recommended)
"inoremap <expr><Left>  neocomplcache#close_popup() . "\<Left>"
"inoremap <expr><Right> neocomplcache#close_popup() . "\<Right>"
"inoremap <expr><Up>    neocomplcache#close_popup() . "\<Up>"
"inoremap <expr><Down>  neocomplcache#close_popup() . "\<Down>"

" 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 <expr><TAB>  pumvisible() ? "\<Down>" : "\<C-x>\<C-u>"
"inoremap <expr><CR>  neocomplcache#smart_close_popup() . "\<CR>"

" 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 completeopt-=preview
autocmd FileType xml setlocal omnifunc=xmlcomplete#CompleteTags
autocmd FileType ruby setlocal omnifunc=rubycomplete#Complete

" Enable heavy omni completion.
if !exists('g:neocomplcache_omni_patterns')
    let g:neocomplcache_omni_patterns = {}
endif
let g:neocomplcache_omni_patterns.ruby = '[^. *\t]\.\h\w*\|\h\w*::'
let g:neocomplcache_omni_patterns.php = '[^. \t]->\h\w*\|\h\w*::'
let g:neocomplcache_omni_patterns.c = '\%(\.\|->\)\h\w*'
let g:neocomplcache_omni_patterns.cpp = '\h\w*\%(\.\|->\)\h\w*\|\h\w*::'

" Supressing ruby-vim bug(https://github.com/Shougo/neocomplcache/issues/209)
if has("ruby")
  silent! ruby nil
endif
"2}}}

"======================================================================
" VimFiler {{{2
" netrwをオーバーライド
let g:vimfiler_as_default_explorer = 1
nmap <F12> :VimFiler<CR>
nmap <C-F12> :VimFilerBufferDir<CR>

"2}}}

"======================================================================
" caw.vim {{{2

"2}}}

"======================================================================
" open-browser.vim {{{2
nmap <Leader>t <Plug>(openbrowser-smart-search)
"2}}}

"======================================================================
" restart.vim {{{2
" https://gist.github.com/862310
" 'MapAlterCommand'がないと怒られた.
command!
\   RestartWithSession
\   -bar
\   let g:restart_sessionoptions = 'blank,curdir,folds,help,localoptions,tabpages'
\   | Restart
"
"MapAlterCommand res[tart] Restart
"MapAlterCommand ers[tart] Restart
"MapAlterCommand rse[tart] Restart
"2}}}

"======================================================================
" vim-easymotion {{{2
"let g:EasyMotion_leader_key = '<Leader>'
"2}}}

"======================================================================
" taglist.vim {{{2
let Tlist_WinWidth = 45
nmap <F10> :Tlist<CR>
"2}}}

"======================================================================
"" python-mode {{{2
"let g:pymode_lint_checker = "pyflakes"
"let g:pydoc = "python H:\\lib\\python\\2.5\\Lib\\pydoc.py"
"let g:pymode_virtualenv = 0
"let g:pymode_lint_cwindow = 1
""2}}}

"======================================================================
" vim-ref {{{2
" [for Ruby]

"2}}}

"======================================================================
" Align {{{2
let g:Align_xstrlen = 3	  " 日本語の整形

"2}}}

"======================================================================
" quickrun {{{2
" quickrun設定
let g:quickrun_config = {}
let g:quickrun_config['markdown'] = {
      \ 'outputter' : 'browser',
      \ 'type' : 'markdown/pandoc',
      \ 'cmdopt' : '-s',
      \}
"if strlen($rvm_bin_path)
"	let g:quickrun_config['ruby'] = {
"      \ 'command': 'ruby',
"      \ 'exec': '$rvm_bin_path/ruby %s',
"      \ 'tempfile': '{tempname()}.rb'
"      \}
"endif

"2}}}

"======================================================================
" Gitv {{{2
" you will be prompted if you wish to delete the topic branch.
let g:Gitv_PromptToDeleteMergeBranch = 1

"2}}}

"======================================================================
" fugitive {{{2
" https://github.com/tpope/vim-fugitive/issues/192
au FileType gitcommit :set noswf
"2}}}

"======================================================================
" autodate {{{2
let autodate_format='%Y-%m-%d'
let autodate_keyword_pre='Last Updated:'
let autodate_keyword_post='.'
"2}}}

"======================================================================
" gist-vim {{{2
let g:github_user = "zeroyonichihachi"
let g:gist_detect_filetype = 1
let g:gist_open_browser_after_post = 1
"let g:gist_browser_command = 'w3m %URL%'
let g:gist_show_privates = 1
"2}}}

"1}}}

"----------------------------------------------------------------------
"                        Key Mappings
"----------------------------------------------------------------------
"{{{1
" Git 
nnoremap <space>gtv :Gitv --all<CR>
nnoremap <space>gst :Gstatus<CR>
nnoremap <space>gps :Git push<CR>
nnoremap <space>gpl :Git pull<CR>
nnoremap <space>gft :Git fetch<CR>
"1}}}

"----------------------------------------------------------------------
"                           Unites
"----------------------------------------------------------------------
"{{{1
" unite-neco {{{
" REF: https://github.com/ujihisa/config/commit/a1d5e08464f2679b4e156f6ddc406191dd2d90b4
let s:unite_source = {'name': 'neco'}

function! s:unite_source.gather_candidates(args, context)
  let necos = [
        \ "~(-'_'-) goes right",
        \ "~(-'_'-) goes right and left",
        \ "~(-'_'-) goes right quickly",
        \ "~(-'_'-) goes right then smile",
        \ "~(-'_'-)  -8(*'_'*) go right and left",
        \ "(=' .' ) ~w",
        \ ]
  return map(necos, '{
        \ "word": v:val,
        \ "source": "neco",
        \ "kind": "command",
        \ "action__command": "Neco " . v:key,
        \ }')
endfunction
call unite#define_source(s:unite_source)

" }}}
"1}}}

"----------------------------------------------------------------------
"                        dast bucket
"----------------------------------------------------------------------
"{{{1
" URLメモ(ブックマーク？)
" TODO:ウィンドウを分割してそこにバッファを開く
nmap <silent> <F8> :e<Space>$DOTVIM/browsmemo.txt<CR>
"1}}}


"------------------------------------------------------------------------------
" vim:set ts=8 sts=2 sw=2 tw=0 fdm=marker:
