""""""""""""""""""""""""""""""""""
"         core settings          "
""""""""""""""""""""""""""""""""""

if expand("%") == ".git/COMMIT_EDITMSG"
  finish
endif


filetype plugin indent on
syntax on
colorscheme desert

set runtimepath^=~/.vim/gitplugins/*
set runtimepath+=~/.vim/plugins/*
set runtimepath+=~/.vim
set runtimepath+=~/.vim/after

helptags ~/.vim/gitplugins/vimdoc-ja/doc

let g:vimball_home = "~/.vim"

call altercmd#load()

if &termencoding == ''
  let &termencoding="utf-8"
"  let &termencoding="cp932"
endif

let mapleader = "m"

""""""""""""""""""""""""""""""""""
"             env                "
""""""""""""""""""""""""""""""""""

let $CYGWIN = 'nodosfilewarning acl'

""""""""""""""""""""""""""""""""""
"           settings             "
""""""""""""""""""""""""""""""""""

" singleton.vim
if has('clientserver')
  call singleton#enable()
  let g:singleton#opener = "drop"
endif

if filereadable($HOME . '/.vimrc_local')
  source ~/.vimrc_local
endif

if has('win32')
  let g:vimproc_dll_path = $HOME . '/.vim/proc/proc_win.dll'
elseif has('win32unix')
  let g:vimproc_dll_path = $HOME . '/.vim/proc/proc_cygwin.dll'
else
  let g:vimproc_dll_path = $HOME . '/.vim/proc/proc_mac.so'
endif

set ambiwidth=double
set nu
set autoindent
set iminsert=0
set titlestring=%<%f\ %m%r%h%w%{'['.(&fenc!=''?&fenc:&enc).']['.&ff.']'}\ \ %{getcwd()}
set titlelen=200
set linespace=4
set antialias
set backupdir=~/.vim/backup
set directory=~/.vim/swp
"オートインデント時にタブが2つ入ることを防ぐ
set ts=4 sw=4 sts=0
set scrolloff=5
set wrap
set hlsearch
set smartindent
set timeout timeoutlen=300 ttimeoutlen=200
set shellslash
set incsearch
set laststatus=0

" ubuntu だと画面がちらつく。mac だと音が出ちゃう。
if has('mac')
  set vb t_vb=
endif

set tabstop=2
set shiftwidth=2
set expandtab
set noshowmatch
set matchpairs+=<:>
set shortmess+=I
set complete=.
set pumheight=10
set showcmd
" 矩形選択中は行末にテキストがなくてもカーソルを行末以降に移動させることができる
set virtualedit+=block
set fileencodings=ucs-bom,utf-8,cp932,shift-jis,euc-jp
set fileformats=unix,dos

set ignorecase
""""""""""""""""""""""""""""""""""
"         auto command           "
""""""""""""""""""""""""""""""""""
augroup MyGroup
  autocmd! MyGroup
  au BufWritePre * call s:change_last_mod_date()
  au BufNewFile,BufRead *.scala setf scala
  "set autochdir
  au BufEnter * call s:all_bufenter_setting()
  " for ruby
  autocmd FileType ruby  :setlocal tabstop=2
  autocmd FileType ruby  :setlocal shiftwidth=2
  autocmd FileType ruby  :setlocal expandtab
  " for eruby
  autocmd FileType eruby :setlocal tabstop=2
  autocmd FileType eruby :setlocal shiftwidth=2
  autocmd FileType eruby :setlocal expandtab
  " for scala
  autocmd FileType scala :setlocal tabstop=2
  autocmd FileType scala :setlocal shiftwidth=2
  autocmd FileType scala :setlocal expandtab
  " for vim
  autocmd FileType scala :setlocal tabstop=4
  autocmd FileType scala :setlocal shiftwidth=4
  autocmd FileType scala :setlocal noexpandtab
  " for java
  autocmd FileType java :setlocal tabstop=4
  autocmd FileType java :setlocal shiftwidth=4
  autocmd FileType java :setlocal noexpandtab
  " for javascript
  autocmd FileType javascript :setlocal tabstop=2
  autocmd FileType javascript :setlocal shiftwidth=2
  autocmd FileType javascript :setlocal expandtab
  autocmd FileType javascript call s:javascript_filetype_settings()
  " for c
  autocmd FileType c,cpp,cs :setlocal tabstop=4
  autocmd FileType c,cpp,cs :setlocal shiftwidth=4
  autocmd FileType c,cpp,cs :setlocal expandtab
  " for go
  autocmd FileType go :setlocal tabstop=4
  autocmd FileType go :setlocal shiftwidth=4
  autocmd FileType go :setlocal noexpandtab
  " for markdown
  autocmd BufRead,BufNewFile *.mkd  set filetype=markdown
  autocmd BufRead,BufNewFile *.md   set filetype=markdown
  " for uiki
  autocmd FileType uiki nnoremap <buffer> mq ggvG$:QuickRun<CR>


  autocmd BufRead,BufNewFile *.go set filetype=go

  autocmd BufRead,BufNewFile *.ecob set filetype=cobol

  autocmd FileType netrw setlocal buftype=nofile bufhidden=delete

  autocmd FileType vimshell call s:vimshell_filetype_settings()

  autocmd FileType go       call s:go_settings()
  autocmd FileType unite    call s:unite_my_settings()
  autocmd FileType scratch  call s:scratch_my_settings()
  autocmd FileType tweetvim_say  call s:tweetvim_say_my_settings()
  autocmd FileType vimshell-bg  call s:bg_settings()

  autocmd CmdwinEnter * call s:init_cmdwin()

  autocmd FileType lingr-rooms    :setlocal nonu
  autocmd FileType lingr-rooms    :setlocal nowrap
  autocmd FileType lingr-members  :setlocal nonu
  autocmd FileType lingr-members  :setlocal nowrap
  autocmd FileType lingr-messages :setlocal nonu
  autocmd FileType lingr-members  :setlocal nowrap
  autocmd FileType lingr-messages :setlocal wrap
  autocmd FileType lingr-messages call s:lingr_messages_setting()
  autocmd FileType lingr-say      call s:lingr_say_setting()

  autocmd FileType quickrun       call s:quickrun_setting()

  autocmd BufWritePost *.go call s:go_write_post()

  autocmd BufLeave * call s:buf_leave()

  autocmd InsertEnter * call s:neco_pre_cache()

  autocmd FileType git :setlocal foldlevel=99
augroup END

function! s:buf_leave()
  if &filetype == 'unite'
"    nohlsearch
  endif
endfunction

function! s:neco_pre_cache()
  if exists('b:neco_pre_cache') 
    return
  endif
  let b:neco_pre_cache = 1
  if &filetype == 'vim'
    return
  endif
  if bufname('%') =~ g:neocomplcache_lock_buffer_name_pattern
    return
  endif
  :NeoComplCacheCachingBuffer
"  :NeoComplCacheCachingDictionary
endfunction

function! s:bg_settings()
  AlterCommand <buffer> q bd
endfunction

function! s:go_settings()
  inoremap <buffer> -- :=
endfunction

function! s:go_write_post()
  :GoFmt
  :setfiletype go
endfunction

function! s:all_bufenter_setting()
  setlocal bufhidden=hide
  if &filetype == ''
    if expand("%") =~ '\[quickrun output\]'
      setfiletype quickrun
    else
      setfiletype txt
    endif
  endif

  if &modifiable && join(getline(1,3)) == ''
    setlocal fileencoding=utf-8
    setlocal fileformat=unix
    setlocal nomodified
  endif

  try
    execute ":lcd " . substitute(expand("%:p:h")," ","\\\\ ","g")
  catch
  endtry
endfunction
"
" Last Change を保存時に変更する
"
function! s:change_last_mod_date()
  let lineno = line(".")
  let colno  = col(".")
  :1
  let language =  v:lc_time
  execute ':silent! language time C'
  let time = '" Last Modified: ' . strftime("%d %b %Y")
  " 同じだったらなにもしない
  if !search(time , '' , 5)
    try
      execute '1,5s/" Last Modified:.*/' . time . '/'
    catch
    endtry
  endif
  execute ':silent! language time ' . language
  call cursor(lineno , colno)
endfunction

function! s:javascript_filetype_settings()
"  autocmd BufLeave     <buffer> call jslint#clear()
"  autocmd BufWritePost <buffer> call jslint#check()
"  autocmd CursorMoved  <buffer> call jslint#message()
endfunction

""""""""""""""""""""""""""""""""""
"            colors              "
""""""""""""""""""""""""""""""""""
hi Cursor	  guifg=bg	guibg=orange
" lingr
hi link lingrMessagesSpeaker Statement
hi link lingrRoomsActive     Statement

let java_ignore_javadoc = 1
""""""""""""""""""""""""""""""""""
"             map                "
""""""""""""""""""""""""""""""""""
nnoremap qq q
nnoremap q <ESC>

map <silent> <S-u> :redo<CR>
map bn    :bnext<CR>
"ウインドウのフォーカス移動
map  wh <C-w>h
map  wl <C-w>l
map  wj <C-w>j
map  wk <C-w>k
map gl :macaction selectNextWindow:<CR>
map gh :macaction selectPreviousWindow:<CR>

nnoremap <Space>.   :<C-u>edit   $MYVIMRC<Enter>
nnoremap <Space>s.  :<C-u>source $MYVIMRC<Enter>
nnoremap <Space>g.  :<C-u>edit   $MYGVIMRC<Enter>
noremap  <Space>gs. :<C-u>source $MYGVIMRC<Enter>
noremap  <Space>v.  :<C-u>edit   ~/.vimshrc<Enter>
nnoremap <Space>ss  :<C-u>Source %<Enter>
inoremap <C-d> <Del>
cmap <C-d> <Del>

inoremap <C-u> <C-g>u<C-u>
inoremap <C-w> <C-g>u<C-w>

nnoremap gc `[v`]

"コマンドモードで Ctl + v で貼り付ける
cmap <C-v> <C-R>+
"挿入モードで Ctl + v で貼り付ける
imap <C-v> <C-R>+
"全て選択
map  <C-a><C-a> ggvG$
" gvim で q → bd をしてる用
map <C-q><C-q><C-q> ZQ

cmap <C-e> <End>
cmap <C-a> <HOME>
cmap <C-f> <Right>
cmap <C-b> <Left>
imap <C-e> <End>
imap <C-a> <ESC>^i
imap <C-f> <Right>
imap <C-b> <Left>

nnoremap <C-e> <End>
nnoremap <C-a> <HOME>
nnoremap <C-f> <Right>
nnoremap <C-b> <Left>
" カウントアップ
nnoremap <C-c> <C-a>

nnoremap <M-k> <C-y>
nnoremap <M-j> <C-e>
nnoremap <Leader>s :Scratch<CR>
nnoremap <Leader>v :VimShell<CR>
nnoremap <Leader>w :WriteToFile<CR>
nnoremap <silent> <Leader>o :on<CR>
nnoremap <Leader><Leader> :Unite 
nnoremap <Leader>g  :VimGrep **/*.* 
nnoremap <Space>d :<C-u>pwd<CR>
nnoremap <silent> <C-l> :Unite outline  -winheight=30 -buffer-name=outline<CR>
nnoremap <silent> <C-l><C-l> :Unite outline:!  -winheight=30 -buffer-name=outline<CR>
nnoremap <silent> <C-x><C-x> :TabNew<CR>
nnoremap <silent> <C-x><C-l> :tabnext<CR>
nnoremap <silent> <C-x><C-h> :tabprevious<CR>
nnoremap <silent> <C-f> :tabnext<CR>
nnoremap <silent> <C-b> :tabprevious<CR>
" エンコードを指定して開き直す
nnoremap <Space>r   :e ++enc=
nnoremap <C-w>; <C-w>+
nnoremap w; <C-w>+
nnoremap w- <C-w>-
nnoremap wm 100<C-w>+
nnoremap man :Unite help<CR>
nnoremap <silent>co :Unite -no-quit qflist<CR>
nnoremap <silent><Leader>r :UniteResume<CR>
nnoremap <silent>on 999<C-w>+
nnoremap <silent><Leader><Leader>r :Unite yarm<CR>
"nnoremap <silent><Leader><Leader>w :execute ':edit! ' . g:unite_uiki_path . '/FrontPage.uiki'<CR>
nnoremap <silent><Leader>l :Unite -vertical -winwidth=50 -no-start-insert uiki<CR>
nnoremap cn :cn<CR>
nnoremap cp :cp<CR>
nnoremap wp <C-w>p
nnoremap <C-]> g<C-]>

nnoremap j gj
nnoremap gj j
nnoremap k gk
nnoremap gk k
nnoremap 0 g0
nnoremap g0 0
nnoremap $ g$
nnoremap g$ $

cnoremap <C-p> <Up>
cnoremap <Up> <C-p>
cnoremap <C-n> <Down>
cnoremap <Down> <C-n>

" for unite-rails
nnoremap <C-x><C-m> :Unite rails/model<CR>
nnoremap <C-x><C-c> :Unite rails/controller<CR>
nnoremap <C-x><C-j> :Unite rails/view<CR>
nnoremap <C-x><C-d> :Unite rails/db<CR>
nnoremap <C-x><C-f> :Unite rails/config<CR>
"nnoremap <C-x> :Unite -immediately rails/
nnoremap <C-x> :Unite rails/

nnoremap <silent> t  :Unite tweetvim<CR>
nnoremap <silent> ta :TweetVimListStatuses all<CR>
nnoremap <silent> tm :TweetVimMentions<CR>

nnoremap Y y$

nnoremap <C-@><C-@> :Restart!<CR>

nnoremap <Space>c :Cache<CR>:NeoComplCacheCachingDictionary<CR>
inoremap <C-x><C-c> <esc>:Cache<CR>:NeoComplCacheCachingDictionary<CR>a

nmap <Leader>c <Plug>NERDCommenterToggle
" ターミナルだとなぜか起動時にインサートモードになるので
if has('gui_running')
  nnoremap <silent> <ESC> :noh<CR>
endif

inoremap <silent><C-o> <ESC>o
inoremap <C-j> <ESC>
inoremap jj <ESC>
noremap <silent> <C-j> <ESC>:noh<CR>
inoremap kk <ESC><S-o>
"inoremap () ()<Left>
"inoremap {} {}<Left>
inoremap [[ []<Left>
inoremap <C-q> []<Left>
"inoremap "" ""<Left>
"inoremap '' ''<Left>
"inoremap <> <><Left>
"inoremap  , <Space>,
"inoremap  -- =>

vnoremap <C-e> <End><Left>
vmap <Leader>c <Plug>NERDCommenterToggle
vmap <C-b> :Batch<CR>

cnoremap <C-j> <C-u><ESC>

vnoremap ch :s/\t/\|_=./g<CR>
vnoremap cb :s/\t/\|/g<CR>

""""""""""""""""""""""""""""""""""
"        neo complcache          "
""""""""""""""""""""""""""""""""""
" 起動時に有効
let g:neocomplcache_enable_at_startup = 1

" snippet ファイルの保存先
let g:neocomplcache_snippets_dir='~/.vim/snippets'
" dictionary
if !exists('g:neocomplcache_dictionary_filetype_lists')
  let g:neocomplcache_dictionary_filetype_lists = {}
endif
let neco_dic = g:neocomplcache_dictionary_filetype_lists
let neco_dic.objc        = $HOME . '/.vim/dict/objc.dict'
let neco_dic.javascript  = $HOME . '/.vim/dict/js.dict'
let neco_dic.ruby        = $HOME . '/.vim/dict/ruby.dict'
let neco_dic.eruby       = $HOME . '/.vim/dict/ruby.dict'
let neco_dic.java        = $HOME . '/.vim/dict/java.dict'
let neco_dic.c           = $HOME . '/.vim/dict/c.dict'
let neco_dic.cs          = $HOME . '/.vim/dict/cs.dict'
let neco_dic.go          = $HOME . '/.vim/dict/go.dict'
"let neco_dic.vimshell    = $HOME . '/.vimshell/command-history'
let neco_dic.tweetvim_say = $HOME . '/.tweetvim/screen_name' .
                                \ ',' . $HOME . '/.tweetvim/hash_tag' .
                                \ ',' . $HOME . '/.vim/dict/default.dict'

let neco_dic.unite_twitter = 
      \ $HOME . '/.unite/twitter/screen_name' .
      \ ',' . $HOME . '/.twitvim.tags' .
      \ ',' . $HOME . '/.vim/dict/default.dict'
let neco_dic.hatena      = $HOME . '/.vim/dict/default.dict'
let neco_dic.default     = $HOME . '/.vim/dict/default.dict'
let neco_dic['lingr-say'] = $HOME . '/.lingr.dict'

" 日本語をキャッシュしない
if !exists('g:neocomplcache_keyword_patterns')
	let g:neocomplcache_keyword_patterns = {}
endif
let g:neocomplcache_keyword_patterns['default'] = '\h\w*'
" 補完候補の数
let g:neocomplcache_max_list = 100
" 補完しなくなる文字数
let g:neocomplcache_enable_auto_select = 1
" 補完しないパターン
let g:neocomplcache_disable_caching_file_path_pattern = '\.log\|\.log\.\|\.jax\|Log.txt'
" 自動補完しないパターン
let g:neocomplcache_lock_buffer_name_pattern = '\.log\|\.log\.\|.*quickrun.*\|.jax\|Log.txt'
" 自動選択しないパターン
let g:neocomplcache_disable_auto_select_buffer_name_pattern = 'vimshell'
" キャッシュ中に、メッセージをCommand-lineに表示しない
let g:neocomplcache_enable_caching_message = 0
" キー入力時にキーワード補完を行う入力数を制御する。
let g:neocomplcache_auto_completion_start_length = 2
" 大文字・小文字を無視するか
let g:neocomplcache_enable_ignore_case = 0
let g:neocomplcache_enable_smart_case = 0
if !exists('g:neocomplcache_plugin_rank')
  let g:neocomplcache_plugin_rank = {}
endif
let g:neocomplcache_plugin_rank.snippets_complete = 90
" omni
if !exists('g:neocomplcache_omni_functions')
  let g:neocomplcache_omni_functions = {}
endif
"let g:neocomplcache_omni_functions.javascript = 'jscomplete#CompleteJS'

if !exists('g:neocomplcache_omni_function_list')
  let g:neocomplcache_omni_function_list = {}
endif
"let g:neocomplcache_omni_function_list.javascript = 'jscomplete#CompleteJS'

if !exists('g:neocomplcache_omni_patterns')
  let g:neocomplcache_omni_patterns = {}
endif
"let g:neocomplcache_omni_patterns.javascript = '[^. \t]\.\%(\h\w*\)\?'
"
" ソート条件
function! g:neocomplcache_compare_len(i1, i2)
  let l:diff = len(a:i1.word) - len(a:i2.word)
  if !l:diff
    let l:diff = (a:i1.word ># a:i2.word) ? 1 : -1
  endif
  return l:diff
endfunction
let g:neocomplcache_compare_function = 'g:neocomplcache_compare_len'
" ちらつき防止
let g:neocomplcache_enable_prefetch = 1

"入力に大文字が含まれている場合は、大文字・小文字を無視しない 
"let g:neocomplcache_enable_smart_case = 1
" セパレータ補完
"let g:neocomplcache_enable_auto_delimiter = 1
" 辞書読み込
noremap  <Space>d. :<C-u>NeoComplCacheCachingDictionary<Enter>
" C-kを押すと行末まで削除
inoremap <C-k> <C-o>D
" C-nでneocomplcache補完
inoremap <expr><C-n>  pumvisible() ? "\<C-n>" : "\<C-x>\<C-u>\<C-p>"
" 補完候補が出ていたら確定、なければ改行
inoremap <expr><CR>  pumvisible() ? neocomplcache#close_popup() : "<CR>"
inoremap <expr><C-e> pumvisible() ? neocomplcache#close_popup() : "<End>"
" 補完をキャンセル
inoremap <expr><C-c>  neocomplcache#cancel_popup()
" 補完をアンドゥ
inoremap <expr><C-u>  neocomplcache#undo_completion()

inoremap <silent> <ESC> <ESC>:set iminsert=0<CR>
inoremap <expr><C-h> neocomplcache#smart_close_popup()."\<C-h>"
" snippet 補完
"
imap <expr><C-l> pumvisible() ? 
      \ "\<C-y><Plug>(neocomplcache_snippets_expand)" 
      \ : "<Plug>(neocomplcache_snippets_expand)"
imap <silent> <C-l>l <C-y><Plug>(neocomplcache_snippets_force_expand)
smap <silent> <C-l> <Plug>(neocomplcache_snippets_expand)
command! -nargs=* Nes NeoComplCacheEditSnippets <args>
command! -nargs=* Nel NeoComplCacheLock <args>
command! -nargs=* NSource NeoComplCachePrintSource
command! -nargs=* NecoOff NeoComplCacheDisable
command! -nargs=* NecoOn  NeoComplCacheEnable
command! -nargs=* OutKeyWord  NeoComplCacheOutputKeyword
command! -nargs=* Cache  NeoComplCacheCachingBuffer

""""""""""""""""""""""""""""""""""
"            vimshell            "
""""""""""""""""""""""""""""""""""

"if has('mac')
"  let g:vimshell_prompt = '⚡ '
"else
  let g:vimshell_prompt = '$ '
"endif
let g:vimshell_user_prompt = "printf('%s','')\ngetcwd()"
let g:vimshell_edit_no_split = 1
let g:vimshell_interactive_cygwin_path = 'D:/develop/dev/cygwin/bin'
let g:vimshell_interactive_cygwin_home = 'D:/develop/dev/cygwin/home/Administrator'
let g:vimshell_split_command = 'split'
"let g:vimshell_split_command = "vsplit"
" ディレクトリの補完時に/を補います
let g:vimshell_enable_auto_slash = 1
if !exists('g:vimshell_interactive_cygwin_commands')
  let g:vimshell_interactive_cygwin_commands = {}
endif
let g:vimshell_interactive_cygwin_commands['git'] = {
  \ 'name' : 'git',
  \ 'kind' : 'execute',
  \ 'description' : 'git [{options}...] {command}',
\}
let g:vimshell_interactive_cygwin_commands['termtter'] = {
  \ 'name' : 'termtter',
  \ 'kind' : 'execute',
  \ 'description' : 'git [{options}...] {command}',
\}
let g:vimshell_interactive_cygwin_commands['irb'] = {
  \ 'name' : 'irb',
  \ 'kind' : 'execute',
  \ 'description' : 'git [{options}...] {command}',
\}
"let g:vimshell_interactive_cygwin_commands['rake'] = {
  "\ 'name' : 'rake',
  "\ 'kind' : 'execute',
  "\ 'description' : 'git [{options}...] {command}',
"\}
let g:vimshell_interactive_cygwin_commands['telnet'] = {
  \ 'name' : 'telnet',
  \ 'kind' : 'execute',
  \ 'description' : 'git [{options}...] {command}',
\}

function! s:vimshell_filetype_settings()
  imap <buffer><expr> <CR> (pumvisible() ? "<C-y>" : "<Plug>(vimshell_enter)")
  "imap <buffer><expr> <CR> (pumvisible() ? "<C-y><Tab>" : "<Plug>(vimshell_enter)")
  inoremap <buffer> <C-x> <ESC><C-w>h:on<CR>
  nnoremap <buffer> <CR> Go$<Space>
  imap <buffer> <C-x>     <ESC><C-w>h:on<CR>
  inoremap <C-v> <C-R>+
  inoremap <buffer><expr><C-h> pumvisible() ? "\<C-y>\<C-h>" : "\<C-h>"
  imap <buffer> <C-o> <Plug>(vimshell_enter)
  inoremap <buffer> <C-l> <C-y>
  inoremap <buffer> <expr><silent> <C-s>  unite#sources#vimshell_history#start_complete(1)
  "inoremap <buffer> <expr><silent> <C-s> <ESC>:Unite vimshell/history -default-action=insert -direction=below<CR>
  imap <buffer> <C-h> <Plug>(vimshell_delete_backward_char)
  "nunmap <buffer> <C-d>
  nunm <buffer> q
 	call vimshell#hook#set('preexec'  , ['g:vimshell_preexec'])
	call vimshell#hook#set('postexec' , ['g:vimshell_postexec'])
  call vimshell#set_execute_file('txt,vim,xml,java,jax,jsp,rb,js', 'vim')
  call unite#custom_default_action('source/vimshell/history/completion' , 'insert')

  inoremap <buffer> <silent> <C-n>  <ESC>:<C-u>Unite buffer_tab<CR>
  inoremap <buffer> <silent> <C-r>  <ESC>:<C-u>Unite file_mru -start-insert<CR>
  nnoremap <buffer><silent> <C-n>  :<C-u>Unite buffer_tab<CR>
  inoremap <C-x><C-f> <Esc>:Unite file_rec -input=

  AlterCommand <buffer> q echo 'use bd'

  hi VimShellPrompt guifg=#8ac6f2 gui=NONE
  NeoComplCacheAutoCompletionLength 4
endfunction
" vim コマンド実行前処理
function! g:vimshell_preexec(cmdline, context)
  " 改行する
  if a:cmdline =~ "^vim .*"
    " ホントは色付のユーザプロンプトを出したい
    call append(g:vimshell_prompt , "")
    call append(g:vimshell_prompt , vimshell#get_prompt())
    execute "normal G"
  endif
  if s:is_vimshell_change_termencoding_cmd(a:cmdline)
    set termencoding=cp932
  endif
  return a:cmdline
endfunction
" vim コマンド実行後
function! g:vimshell_postexec(cmdline, context)
  if s:is_vimshell_change_termencoding_cmd(a:cmdline)
    set termencoding=utf-8
  endif
endfunction

function! s:is_vimshell_change_termencoding_cmd(cmdline)
  if !exists('g:vimshell_change_termencoding_cmd')
    return 0
  endif
  let l:args = vimproc#parser#split_args(a:cmdline)
  return len(l:args) > 0 && l:args[0] =~ g:vimshell_change_termencoding_cmd
endfunction


""""""""""""""""""""""""""""""""""
"            vimfiler            "
""""""""""""""""""""""""""""""""""

let g:vimfiler_as_default_explorer = 1

""""""""""""""""""""""""""""""""""
"             unite              "
""""""""""""""""""""""""""""""""""

nnoremap <silent> <C-r>      :<C-u>Unite file_mru -start-insert<CR>
nnoremap <silent> <C-n>      :<C-u>Unite buffer_tab<CR>
nnoremap <silent> <Leader>d  :<C-u>Unite -buffer-name=file -hide-source-names file file/new<CR>
nnoremap <silent> <Leader>b  :<C-u>Unite -no-start-insert bookmark<CR>
nnoremap <silent> <C-t>      :<C-u>Unite tags -start-insert<CR>
nnoremap <Leader>f  :<C-u>Unite file_rec -input=
"nnoremap <C-x><C-f>  :<C-u>Unite file_rec -input=
"inoremap <C-x><C-f> :<C-u>Unite file_rec -input=

nnoremap <silent> <Leader>u  :<C-u>Unite buffer_tab file file_mru bookmark<CR>

"let g:unite_update_time = 200
let g:unite_source_file_mru_time_format = ''
let g:unite_enable_start_insert = 1
let g:unite_source_file_mru_ignore_pattern = '.*Application\ Data.*\|.*デスクトップ.*\|.*Local/Temp/.*\|\[quickrun output\]\|.*Local Settings/Temp/.*\|fugitive://\|\.git\|/private/var'
" unite ウインドウの高さ
let g:unite_winheight  = 10
let g:unite_split_rule = 'leftabove'

"call unite#set_substitute_pattern('', '[[:alnum:]]', '*\0', 100)
call unite#set_substitute_pattern('file', '^\~', substitute(substitute($HOME, '\\', '/', 'g'), ' ', '\\\\ ', 'g'), -200)
if has('win32')
  call unite#set_substitute_pattern('file', '[^~.]\zs/', '*/*', 20)
  call unite#set_substitute_pattern('file', '/\ze[^*]', '/*', 10)
else
  call unite#set_substitute_pattern('file', '[[:alnum:]]', '*\0', -150)
endif

call unite#set_substitute_pattern('file_mru', '[[:alnum:]]', '*\0', 100)
call unite#set_substitute_pattern('file_mru', '[^~.]\zs/', '*/*', 20)
call unite#set_substitute_pattern('file_mru', '/\ze[^*]', '/*', 10)

"call unite#set_substitute_pattern('outline', '[[:alnum:]]', '*\0', 100)
"call unite#set_substitute_pattern('outline', '[^~.]\zs/', '*/*', 20)
"call unite#set_substitute_pattern('outline', '/\ze[^*]', '/*', 10)

call unite#set_buffer_name_option('file', 'smartcase', 0)

call unite#custom_filters('buffer,buffer_tab',
      \ ['matcher_file_name', 'sorter_default', 'converter_file_directory'])

call unite#custom_filters('file',
      \ ['matcher_fuzzy', 'sorter_default', 'converter_default'])

call unite#custom_filters('file_mru',
      \ ['matcher_file_name', 'sorter_default', 'converter_default'])

call unite#custom_filters('uiki',
      \ ['matcher_fuzzy', 'sorter_default', 'converter_default'])

call unite#custom_filters('bookmark',
      \ ['matcher_fuzzy', 'sorter_default', 'converter_bookmark'])

let g:unite_source_outline_cache_dir = ''

call unite#custom_default_action('source/bookmark/directory' , 'vimfiler')

call unite#set_profile('buffer_tab', 'ignorecase', 1)
call unite#set_profile('file'      , 'ignorecase', 1)
call unite#set_profile('file_mru'  , 'ignorecase', 1)
"call unite#set_profile('file_mru'  , 'filters', ['converter_file_directory'])

function! s:unite_my_settings()
  " Overwrite settings.
  if exists(':NeoComplCacheDisableCaching')
    NeoComplCacheDisableCaching
  endif
  if exists(':NeoComplCacheLock')
    NeoComplCacheLock
  endif

  imap <buffer> jj <Plug>(unite_insert_leave)
  "imap <buffer> jj <Plug>(unite_exit)
  imap <buffer> <C-j> <Plug>(unite_exit)
  imap <buffer> <ESC> <Plug>(unite_exit)
	imap <buffer> <C-o> <Plug>(unite_insert_leave):<C-u>call unite#mappings#do_action('above')<CR>
  inoremap <silent><buffer><expr> <C-x><C-i> unite#do_action('insert')
  imap <buffer> <C-e> <Enter>
  nmap <buffer> <C-n> <Plug>(unite_loop_cursor_down)
  nmap <buffer> <C-p> <Plug>(unite_loop_cursor_up)
  nmap <buffer> <C-j> <Plug>(unite_exit)
  " neco 補完
  inoremap <buffer> <C-l>  <C-x><C-u><C-p><Down>
  inoremap <buffer> <C-f> <Right>
  inoremap <buffer> <C-b> <Left>
  inoremap <buffer><expr> <C-r>      unite#mappings#set_current_filters(
        \ empty(unite#mappings#get_current_filters()) ? ['sorter_reverse'] : [])
	inoremap <silent><buffer><expr> <C-d> unite#do_action('delete')
  inoremap <silent><buffer><expr> <C-s> unite#do_action('rec_parent/async')

	nmap <silent><buffer> a <Plug>(unite_insert_enter)
  "startinsert
endfunction

""""""""""""""""""""""""""""""""""
"             go                 "
""""""""""""""""""""""""""""""""""

"let go_highlight_array_whitespace_error = 0
"let go_highlight_space_tab_error = 0
let go_highlight_trailing_whitespace_error = 0

""""""""""""""""""""""""""""""""""
"             misc               "
""""""""""""""""""""""""""""""""""
" hatena.vim
let g:hatena_user = 'basyura'
let g:scratchBackupFile=$HOME . "/.scratch.txt"
" ubuntu の時だけ
if !has('mac') && !has('win32') && !has('win32unix')
	inoremap <silent> <esc> <esc>:call ForceImeOff()<cr>
	inoremap <silent> <C-[> <esc>:call ForceImeOff()<cr>
	inoremap <silent> <C-c> <esc>:call ForceImeOff()<cr>
	function! ForceImeOff()
		let imeoff = system('xvkbd -text "\[Control]\[Shift]\[space]" > /dev/null 2>&1')
	endfunction
endif
	
command! -nargs=? -complete=dir -bang CD  call s:ChangeCurrentDir('<args>', '<bang>') 
function! s:ChangeCurrentDir(directory, bang)

  if &filetype == 'vimfiler'
    execute 'lcd ' . b:vimfiler.current_dir
    return
  endif

  if a:directory == ''
    lcd %:p:h
  else
    execute 'lcd' . a:directory
  endif

  if a:bang == ''
    pwd
  endif
endfunction


" Change current directory.
nnoremap <silent> <Space>cd :<C-u>CD<CR>

" tweetvim
nnoremap <silent> s           :<C-u>TweetVimSay<CR>
nnoremap <silent> <Space>re   :<C-u>TweetVimMentions<CR>
nnoremap <silent> <Space>tt   :<C-u>TweetVimListStatuses basyura all<CR>
let g:tweetvim_display_source = 1
let g:tweetvim_original_hi = 1

if !exists('g:twitvim_browser_cmd')
  if has('mac')
    let g:twitvim_browser_cmd = "open -a firefox "
  else
    let g:twitvim_browser_cmd = "D:/Program\ Files/Mozilla\ Firefox/firefox.exe"
  endif
endif
let g:twitvim_cert_insecure = 1

silent! nmap <Leader>q :QuickRun<CR>

if has('mac')
  let g:quickrun_config = {
        \ '*' : {'into' : 0},
        \ 'uiki': {
        \   'exec'      : 'ucloth %s',
        \   'outputter' : 'browser'  ,
        \ },
        \}
else
  let g:quickrun_config = {
        \ '*' : {'into' : 0},
        \ 'uiki': {
        \   'exec'      : 'ucloth %s',
        \   'outputter' : 'browser'  ,
        \   'region' : {
        \     'first': [1, 0, 0],
        \     'last' :  [line('$'), 0, 0],
        \     'wise' : 'V',
        \    },
        \ },
        \}
endif

let g:quickrun_config.markdown = {
      \ 'exec'      : 'kramdown %s',
      \ 'outputter' : 'browser',
      \ }

if has('mac')
  let g:quickrun_config['cs'] = {
        \ 'command' : 'dmcs',
        \ 'runmode' : 'simple',
        \ 'exec' : ['%c %s > /dev/null', 'mono "%S:p:r:gs?/?\\?.exe" %a', ':call delete("%S:p:r.exe")'],
        \ 'tempfile' : '%{tempname()}.cs',
        \ }
else
  let g:quickrun_config['cs'] = {
        \ 'command' : 'csc',
        \ 'runmode' : 'simple',
        \ 'output_encode' : 'cp932:utf-8',
        \ 'exec' : ['%c /nologo /reference:System.dll %s:gs?/?\\? > /dev/null', '"%S:p:r:gs?/?\\?.exe" %a', ':call delete("%S:p:r.exe")'],
        \ 'tempfile' : '{tempname()}.cs',
        \ }
endif

if has('win32')
  let g:quickrun_config['java'] = {
        \ 'output_encode' : 'cp932:utf-8',
        \ }
endif


nnoremap <Space>full :call FullScreen()<Enter>
function! FullScreen()
  set columns=195
  set lines=43
endfunction


" カーソル位置の highlight グループを取得する.
command! -nargs=0 GetHighlightingGroup echo 'hi<' . synIDattr(synID(line('.'),col('.'),1),'name') . '> trans<' . synIDattr(synID(line('.'),col('.'),0),'name') . '> lo<' . synIDattr(synIDtrans(synID(line('.'),col('.'),1)),'name') . '>'

" Load settings for each location.
augroup vimrc-local
  autocmd!
  "autocmd BufNewFile,BufReadPost,BufWinEnter * call s:vimrc_local(expand('<afile>:p:h'))
  autocmd BufNewFile,BufReadPost * call s:vimrc_local(expand('<afile>:p:h'))
augroup END

command! FindTags call s:vimrc_local(expand('<afile>:p:h'))
function! s:vimrc_local(loc)
"  let files = findfile('.vimrc.local', escape(a:loc, ' ') . ';', -1)
"  for i in reverse(filter(files, 'filereadable(v:val)'))
"    source `=i`
"  endfor
  let &l:tags=findfile('.tags' , '.;')
"  let &tags=findfile('.tags' , '.;')
endfunction

"http://vim-users.jp/2010/03/hack130/
command! -complete=file -nargs=+ VimGrep  call s:grep([<f-args>])
function! s:grep(args)
  execute 'vimgrep' '/'.a:args[-1].'/' join(a:args[:-2]) | :Unite qflist
endfunction

if has('mac')
  let g:restart_vim_progname = "MacVim"
end

" indent xml
command! IndentXML call s:indent_xml()
function! s:indent_xml()
  let xml = util#xml#indent(join(getline(1,'$'),"\n"))
  silent %delete _
  set paste
  execute 'normal i' . xml
  set nopaste
  :0
endfunction
" xpath
command! -nargs=1 XPath let @" = util#xml#xpath_text(join(getline(1,'$'),"\n") , <f-args>) | echo @"

command! MoveLeft call s:MoveLeft()
function! s:MoveLeft()
  winpos 0 0
  set lines=999
endfunction
function! s:scratch_my_settings()
  AlterCommand <buffer> q :Scratch<CR>
endfunction
" for tweetvim say
function! s:tweetvim_say_my_settings()
  if exists(':NeoComplCacheCachingDictionary')
"    :NeoComplCacheCachingDictionary
  endif
  AlterCommand <buffer> q bd!<CR>
  nnoremap <buffer> <silent> <C-j> :bd!<CR>
"  inoremap <buffer> <C-x><C-d> <ESC>:TweetVimBitly<CR>
endfunction
"
function! s:lingr_messages_setting()
  nmap <buffer> <silent> <Space>po <Plug>(lingr-messages-show-say-buffer)
endfunction

function! s:lingr_say_setting()
  nmap <buffer> <silent> <C-j> <Plug>(lingr-say-close)
endfunction

function! s:quickrun_setting()
  nmap <buffer> <C-j> :bd!<CR>
endfunction

command! ChangeTab call s:change_tab()
function! s:change_tab()
  setlocal tabstop=4
  setlocal shiftwidth=4
  setlocal noexpandtab
endfunction

command! CloseAll call s:close_all()
function! s:close_all()
  let l:bufnr = 1
  while l:bufnr <= bufnr('$')
    if buflisted(l:bufnr) && bufname(l:bufnr) !~ "vimshell"
      exec "bd! " . l:bufnr
    endif
    let l:bufnr += 1
  endwhile
endfunction

command! WriteToFile call s:write_to_file()
function! s:write_to_file()
  if &filetype == 'yarm'
    echo 'please use :w'
    return
  end
  try
    silent w
    let msg = ' write to ' . bufname('%') . ' ... OK !!! '
    echohl CursorLine| echo msg | echohl None
  endtry
endfunction

command! GoFmt execute ':VimProcBang gofmt -w %' | execute ':edit! %'

command! TabNew :call s:tabnew()
function! s:tabnew()
  tabnew
  Scratch
  wincmd p
  bd
endfunction

" http://nanasi.jp/articles/vim/kwbd_vim.html
":command! Kwbd let kwbd_bn= bufnr("%")|enew|exe "bdel ".kwbd_bn|unlet kwbd_bn 

"color for cygwin
if has('win32unix')
  "hi Pmenu     ctermfg=white   ctermbg=black cterm=none
  hi Pmenu     ctermfg=LightYellow   ctermbg=black cterm=none
  hi PmenuSel  ctermfg=232     ctermbg=magenta
  hi Special   ctermfg=green cterm=none
  hi PreProc   ctermfg=green cterm=none
endif

"here is a more exotic version of my original Kwbd script
"delete the buffer; keep windows; create a scratch buffer if no buffers left
function! s:Kwbd(kwbdStage)
  if(a:kwbdStage == 1)
    if(!buflisted(winbufnr(0)))
      bd!
      return
    endif
    let s:kwbdBufNum = bufnr("%")
    let s:kwbdWinNum = winnr()
    windo call s:Kwbd(2)
    execute s:kwbdWinNum . 'wincmd w'
    let s:buflistedLeft = 0
    let s:bufFinalJump = 0
    let l:nBufs = bufnr("$")
    let l:i = 1
    while(l:i <= l:nBufs)
      if(l:i != s:kwbdBufNum)
        if(buflisted(l:i))
          let s:buflistedLeft = s:buflistedLeft + 1
        else
          if(bufexists(l:i) && !strlen(bufname(l:i)) && !s:bufFinalJump)
            let s:bufFinalJump = l:i
          endif
        endif
      endif
      let l:i = l:i + 1
    endwhile
    if(!s:buflistedLeft)
      if(s:bufFinalJump)
        windo if(buflisted(winbufnr(0))) | execute "b! " . s:bufFinalJump | endif
      else
        enew
        let l:newBuf = bufnr("%")
        windo if(buflisted(winbufnr(0))) | execute "b! " . l:newBuf | endif
      endif
      execute s:kwbdWinNum . 'wincmd w'
    endif
    if(buflisted(s:kwbdBufNum) || s:kwbdBufNum == bufnr("%"))
      execute "bd! " . s:kwbdBufNum
    endif
    if(!s:buflistedLeft)
      setlocal buflisted
      setlocal bufhidden=delete
      setlocal buftype=nofile
      setlocal noswapfile
      setlocal filetype=scratch
    endif
  else
    if(bufnr("%") == s:kwbdBufNum)
      let prevbufvar = bufnr("#")
      if(prevbufvar > 0 && buflisted(prevbufvar) && prevbufvar != s:kwbdBufNum)
        b #
      else
        bn
      endif
    endif
  endif
endfunction

command! Kwbd call <SID>Kwbd(1)
"nnoremap <silent> <Plug>Kwbd :<C-u>Kwbd<CR>

if filereadable($HOME . '/.vimrc_local_after')
  source ~/.vimrc_local_after
endif

function! s:off_proxy()
  let $http_proxy  = ""
  let $https_proxy = ""
  let $HTTP_PROXY  = ""
  let $HTTPS_PROXY = ""
endfunction
command! OffProxy call <SID>off_proxy()

" vim: foldmethod=marker