"              ,dPYb,
"              IP'`Yb
"              I8  8I
"              I8  8'
"    ,gggg,gg  I8 dP  gg,gggg,      ,gggg,gg    ,gggg,    ,gggg,gg
"   dP"  "Y8I  I8dP   I8P"  "Yb    dP"  "Y8I   dP"  "Yb  dP"  "Y8I
"  i8'    ,8I  I8P    I8'    ,8i  i8'    ,8I  i8'       i8'    ,8I
" ,d8,   ,d8b,,d8b,_ ,I8 _  ,d8' ,d8,   ,d8b,,d8,_    _,d8,   ,d8b,
" P"Y8888P"`Y88P'"Y88PI8 YY88888PP"Y8888P"`Y8P""Y8888PPP"Y8888P"`Y8
"                     I8
"                 I8                              ,dPYb,
"                 I8                              IP'`Yb
"              88888888             gg             I8  8I
"                 I8                ""             I8  8'
"                 I8     ,gggg,gg   gg     ,gggg,  I8 dPgg,     ,ggggg,   gg      gg
"                 I8    dP"  "Y8I   88    dP"  "Yb I8dP" "8I   dP"  "Y8gggI8      8I
"    Δ~~~~Δ    ,I8,  i8'    ,8I   88   i8'       I8P    I8  i8'    ,8I  I8,    ,8I
"    ξ・ェ・ξ ,d88b,,d8,   ,d8b,_,88,_,d8,_    _,d8     I8,,d8,   ,d8' ,d8b,  ,d8b,
"    ξ     ξ  8P""Y8P"Y8888P"`Y88P""Y8P""Y8888PP88P     `Y8P"Y8888P"   8P'"Y88P"`Y8
"    ξ     ξ
"    ξ     “~~~~~〜〇
"    ξ                ξ
"    ξ ξξ~~~~〜~ξ ξ
"    ξ_ξξ_ξξ_ξξ_ξ  =з =з =з  @alpaca_taichou
augroup MyAutoCmd
  autocmd!
augroup END

augroup MyWindow
  autocmd!
augroup END

" ----------------------------------------
" Utils {{{
function! s:current_git() "{{{
  let current_dir = getcwd()
  let s:git_root_cache = get(s:, 'git_root_cache', {})
  if has_key(s:git_root_cache, current_dir)
    return s:git_root_cache[current_dir]
  endif

  let git_root = system('git rev-parse --show-toplevel')
  if git_root =~ 'fatal: Not a git repository'
    " throw "No a git repository."
    return ''
  endif

  let s:git_root_cache[current_dir] = substitute(git_root, '\n', '', 'g')

  return s:git_root_cache[current_dir]
endfunction"}}}
function! s:filetype() "{{{
  return get([&filetype], 0, '')
endfunction"}}}
function! s:complement_delimiter_of_directory(path) "{{{
  return isdirectory(a:path) ? a:path . '/' : a:path
endfunction"}}}
function! NeoBundleGet(name) "{{{
  if !exists('s:dummy_neobundle_source')
    let s:dummy_neobundle_source = { 'hooks' : {} }
    function! s:dummy_neobundle_source.hooks.on_source(_)
    endfunction
  endif

  let bundle = neobundle#get(a:name)
  return empty(bundle) ? s:dummy_neobundle_source : bundle
endfunction"}}}
"}}}

" ----------------------------------------
" initialize "{{{
if has('vim_starting') "{{{
  let g:my = {}

  " OS
  let s:is_windows = has('win32') || has('win64')
  let s:is_mac     = has('mac')
  let s:is_unix    = has('unix')

  " user information
  let g:my.info = {
        \ 'author':  'Ishii Hiroyuki',
        \ 'email':   'alprhcp666@gmail.com',
        \ 'github':  'alpaca-tc',
        \ 'lingr':   'alpaca_taichou',
        \ 'twitter': 'alpaca_taichou'
        \ }

  let g:my.conf = {
        \ 'initialize' : 1,
        \ 'winheight' : winheight(0),
        \ 'winwidth' : winwidth(0),
        \ }

  let g:my.bin = {
        \ 'ctags' : '/Applications/MacVim.app/Contents/MacOS/ctags',
        \ 'git' : executable('hub') ? 'hub' : 'git',
        \ }

  let g:my.dir = {
        \ 'neobundle':   expand('~/.bundle'),
        \ 'ctrlp':       expand('~/.vim.trash/ctrlp'),
        \ 'memolist':    expand('~/.memolist'),
        \ 'snippets':    expand('~/.vim/snippet'),
        \ 'swap_dir':    expand('~/.vim.trash/vimswap'),
        \ 'trash_dir':   expand('~/.vim.trash/'),
        \ 'viminfo':     expand('~/.vim.trash/viminfo'),
        \ 'undodir':     expand('~/.vim.trash/undodir'),
        \ 'unite':       expand('~/.vim.trash/unite'),
        \ 'vimref':      expand('~/.vim.trash/vim-ref'),
        \ 'vimfiler':    expand('~/.vim.trash/vimfiler'),
        \ 'vimshell':    expand('~/.vim.trash/vimshell'),
        \ 'neocomplete': expand('~/.vim.trash/neocomplete'),
        \ 'vim-session': expand('~/.vim.trash/vimsession'),
        \ 'evernote':    expand('~/.vim.trash/evernote'),
        \ 'trash':       expand('~/.Trash'),
        \ }

  let g:my.ft = {
        \ 'html_files':      ['eruby', 'html', 'php', 'haml'],
        \ 'ruby_files':      ['ruby', 'Gemfile', 'haml', 'eruby', 'yaml'],
        \ 'js_files':        ['javascript', 'coffeescript', 'node', 'json', 'typescript'],
        \ 'python_files':    ['python', 'python*'],
        \ 'scala_files':     ['scala'],
        \ 'sh_files':        ['sh'],
        \ 'php_files':       ['php', 'phtml'],
        \ 'c_files':         ['c', 'cpp'],
        \ 'style_files':     ['css', 'scss', 'sass'],
        \ 'markup_files':    ['html', 'haml', 'erb', 'php', 'xhtml'],
        \ 'english_files':   ['markdown', 'help', 'text'],
        \ 'program_files':   ['ruby', 'php', 'python', 'eruby', 'vim', 'javascript', 'coffee', 'scala', 'java', 'go', 'cpp', 'haml'],
        \ 'ignore_patterns': ['vimfiler', 'unite'],
        \ }
endif"}}}

if has('vim_starting') && g:my.conf.initialize
  call alpaca#initialize#directory(values(g:my.dir))
endif
"}}}

" ----------------------------------------
" basic settings "{{{
set nocompatible
let &directory = g:my.dir.swap_dir
set backspace=indent,eol,start
set clipboard+=autoselect,unnamed
set formatoptions+=lcqmM
set modelines=1
set ttymouse=xterm2
set nomore
set nobackup
set nowritebackup
set norestorescreen
set noshowmode
set timeout timeoutlen=400 ttimeoutlen=90 updatetime=1000
set viminfo='1000,<800,s300,\"1000,f1,:1000,/1000
execute 'set viminfo+=n' . g:my.dir.viminfo . '/.viminfo'
set visualbell t_vb=
set helplang=en
set langmenu=en_us.UTF-8
language en_US.UTF-8

if v:version >= 703
  set undofile
  let &undodir = g:my.dir.undodir
endif

nnoremap <Space><Space>s :<C-U>source ~/.vim/vimrc<CR>
nnoremap <Space><Space>v :<C-U>tabnew ~/.vim/vimrc<CR>
nnoremap <Space><Space>b :<C-U>tabnew ~/.bundle<CR>
"}}}

" ----------------------------------------
" Initialize Neobundle {{{
filetype plugin indent off
let g:neobundle#types#git#default_protocol = 'https'
let g:neobundle#install_max_processes = s:is_mac ? 50 : 10

if has('vim_starting') && g:my.conf.initialize && !isdirectory(g:my.dir.neobundle.'/neobundle.vim')
  call system('git clone https://github.com/Shougo/neobundle.vim.git '. g:my.dir.neobundle . '/neobundle.vim')
endif

if has('vim_starting')
  execute 'set runtimepath+=' . g:my.dir.neobundle . '/neobundle.vim'
  call neobundle#rc(g:my.dir.neobundle)
endif
"}}}

" ----------------------------------------
" NeoBundle  " {{{
NeoBundleFetch 'Shougo/neobundle.vim'

" For asynchronous communication
NeoBundleLazy 'Shougo/vimproc', {
      \ 'autoload' : {
      \   'function_prefix' : 'vimproc',
      \ },
      \ 'build' : {
      \   'mac' : 'make -f make_mac.mak',
      \   'unix' : 'make -f make_unix.mak',
      \ }}

" An awesome improvement to the Vim status bar.
NeoBundleLazy 'itchyny/lightline.vim', {
      \ 'autoload' : {
      \   'insert' : 1,
      \ }}

NeoBundleLazy 'mattn/webapi-vim', {
      \ 'autoload' : {
      \   'function_prefix': 'webapi'
      \ }}

" Accelerator Up-Down moving
NeoBundleLazy 'rhysd/accelerated-jk', {
      \ 'autoload' : {
      \   'mappings' : [
      \     ['n', '<Plug>(accelerated_jk_gj)'], ['n', '<Plug>(accelerated_jk_gk)']
      \ ] }}

NeoBundleLazy 'edsono/vim-matchit', { 'autoload' : {
      \ 'filetypes': g:my.ft.program_files,
      \ 'mappings' : ['nx', '%'] }}

NeoBundleLazy 'tpope/vim-surround', {
      \ 'autoload' : {
      \   'mappings' : [
      \     ['nx', '<Plug>Dsurround'], ['nx', '<Plug>Csurround' ],
      \     ['nx', '<Plug>Ysurround' ], ['nx', '<Plug>YSurround' ],
      \     ['nx', '<Plug>Yssurround'], ['nx', '<Plug>YSsurround'],
      \     ['nx', '<Plug>YSsurround'], ['nx', '<Plug>VgSurround'],
      \     ['nx', '<Plug>VSurround']
      \ ] }}
NeoBundleLazy 'camelcasemotion', { 'autoload' : {
      \ 'mappings' : [
      \   '<Plug>CamelCaseMotion_w', '<Plug>CamelCaseMotion_b',
      \   '<Plug>CamelCaseMotion_e', '<Plug>CamelCaseMotion_iw',
      \   '<Plug>CamelCaseMotion_ib', '<Plug>CamelCaseMotion_ie']
      \ }}
NeoBundleLazy 'kana/vim-arpeggio', { 'autoload': {
      \ 'functions': ['arpeggio#map'],
      \ 'insert' : 1,
      \ }}
NeoBundleLazy 'thinca/vim-quickrun', { 'autoload' : {
      \   'mappings' : [['nxo', '<Plug>(quickrun)']],
      \   'commands' : 'QuickRun' }}
NeoBundleLazy 'scrooloose/syntastic', {
      \ 'autoload': {
      \   'filetypes' : g:my.ft.program_files
      \ },
      \ 'build' : {
      \   'mac' : join(['brew install tidy', 'brew install csslint', 'gem install sass', 'npm install -g jslint', 'gem install rubocop'], ' && ')
      \ }}
NeoBundleLazy 'vim-scripts/sudo.vim', {
      \ 'autoload': { 'commands': ['SudoRead', 'SudoWrite'] }}
NeoBundleLazy 'thinca/vim-ref', { 'autoload' : {
      \ 'commands' : {
      \   'name' : 'Ref',
      \   'complete' : 'customlist,ref#complete',
      \ },
      \ 'unite_sources' : [
      \   'ref/erlang', 'ref/man', 'ref/perldoc',
      \   'ref/phpmanual', 'ref/pydoc', 'ref/redis', 'ref/refe', 'ref/webdict'
      \ ],
      \ 'mappings' : ['n', 'K', '<Plug>(ref-keyword)']
      \ }}
" 暗黒美夢王
NeoBundleLazy 'Shougo/unite.vim', {
      \ 'autoload' : {
      \   'commands' : [ {
      \     'name' : 'Unite',
      \     'complete' : 'customlist,unite#complete_source'},
      \     'UniteBookmarkAdd', 'UniteClose', 'UniteResume',
      \     'UniteWithBufferDir', 'UniteWithCurrentDir', 'UniteWithCursorWord',
      \     'UniteWithInput', 'UniteWithInputDirectory']
      \ }}
NeoBundleLazy 'Shougo/vimfiler', {
      \ 'depends' : 'Shougo/unite.vim',
      \ 'autoload' : {
      \   'explorer' : 1,
      \   'commands' : [
      \     { 'name' : 'VimFiler',
      \       'complete' : 'customlist,vimfiler#complete' },
      \     { 'name' : 'VimFilerBufferDir',
      \       'complete' : 'customlist,vimfiler#complete' },
      \     { 'name' : 'VimFilerExplorer',
      \       'complete' : 'customlist,vimfiler#complete' },
      \   ],
      \   'mappings' : ['<Plug>(vimfiler_switch)'],
      \ }}
NeoBundleLazy 'Shougo/neocomplete', { 'autoload' : {
      \   'insert' : 1,
      \ }}
NeoBundleLazy 'Shougo/neosnippet', {
      \ 'autoload' : {
      \   'commands' : [
      \     { 'name' : 'NeoSnippetEdit', 'complete' : 'file' },
      \     { 'name' : 'NeoSnippetSource', 'complete' : 'file' }
      \   ],
      \   'filetypes' : 'snippet',
      \   'insert' : 1,
      \   'unite_sources' : ['snippet', 'neosnippet/user', 'neosnippet/runtime'],
      \ }}
NeoBundleLazy 'Shougo/vimshell', {
      \ 'autoload' : {
      \   'commands' : ['VimShell', 'VimShellBufferDir'],
      \ }}
NeoBundleLazy 'Shougo/echodoc', {
      \ 'autoload' : {
      \   'insert' : 1,
      \ }}

NeoBundleLazy 'alpaca-tc/alpaca_remove_dust.vim', {
      \ 'autoload': {
      \   'commands': [
      \     'RemoveDustDisable', 'RemoveDustEnable',
      \     'RemoveDust', 'RemoveDustForce',
      \ ]
      \ }}

" Asynchronous updating tags
NeoBundleLazy 'alpaca-tc/alpaca_tags', {
      \ 'depends': ['Shougo/vimproc', 'Shougo/unite.vim'],
      \ 'autoload' : {
      \   'commands' : ['Tags', 'TagsSet', 'TagsBundle', 'TagsCleanCache'],
      \   'unite_sources' : ['tags']
      \ }}

" Interface for lang-8.com(dev)
" NeoBundle 'alpaca-tc/lang-8.vim', {
"       \ 'autoload': {
"       \   'commands' : ['PostJournal']
"       \ }}

NeoBundleLazy 'alpaca-tc/alpaca_window.vim', {
      \ 'autoload': {
      \   'mappings' : [
      \     '<Plug>(alpaca_window_new)', '<Plug>(alpaca_window_smart_new)',
      \     '<Plug>(alpaca_window_tabnew)', '<Plug>(alpaca_window_move_next_window_or_tab)',
      \     '<Plug>(alpaca_window_move_previous_window_or_tab)', '<Plug>(alpaca_window_move_buffer_into_last_tab)'
      \   ],
      \   'functions' : [
      \     'alpaca_window#set_smart_close', 'alpaca_window#smart_close', 'alpaca_window#open_buffer'
      \   ],
      \ }}
NeoBundleLazy 'junegunn/vim-easy-align', { 'autoload': {
      \ 'commands' : ['EasyAlign'] }}
NeoBundleLazy 'grep.vim', {
      \ 'autoload' : { 'commands': ["Grep", "Rgrep", "GrepBuffer"] }}

" For visualizing 'undo tree'
NeoBundleLazy 'sjl/gundo.vim', {
      \ 'autoload' : { 'commands': ["GundoToggle", 'GundoRenderGraph'] }}

" Need to fix bug in jsctags/jsctags/ctags/writter.js:67 Trait.required -> []
NeoBundleLazy 'majutsushi/tagbar', {
      \ 'build' : {
      \   'mac' : 'npm install jsctags && gem ins CoffeeTags',
      \   'unix' : 'npm install https://github.com/faceleg/doctorjs',
      \ },
      \ 'autoload' : {
      \   'commands': ["TagbarToggle", "TagbarTogglePause", "TagbarOpen"],
      \   'fuctions': ['tagbar#currenttag'] }}

NeoBundleLazy 'open-browser.vim', { 'autoload' : {
      \ 'mappings' : ['<Plug>(open-browser-wwwsearch)', '<Plug>(openbrowser-open)'],
      \ 'function_prefix' : 'openbrowser',
      \ 'functions' : ['openbrowser#open'],
      \ 'commands' : ['OpenBrowserSearch', 'OpenBrowser', 'OpenBrowserSmartSearch'] }}

" Comment Plugins
NeoBundleLazy 'tomtom/tcomment_vim', { 'autoload' : {
      \ 'commands' : ['TComment', 'TCommentAs', 'TCommentMaybeInline'] }}
NeoBundleLazy 'tyru/caw.vim', {
      \ 'autoload' : {
      \   'insert' : 1,
      \   'mappings' : [ '<Plug>(caw:prefix)', '<Plug>(caw:i:toggle)'],
      \ }}

" For Git
NeoBundleLazy 'tpope/vim-fugitive', { 'autoload': {
      \ 'commands': ['Gcommit', 'Gblame', 'Ggrep', 'Gdiff'] }}
NeoBundleLazy 'Shougo/git-vim', {
      \ 'autoload' : {
      \ 'function_prefix' : 'git',
      \ 'commands': [
      \   { 'name': 'GitDiff',     'complete' : 'customlist,git#list_commits' },
      \   { 'name': 'GitVimDiff',  'complete' : 'customlist,git#list_commits' },
      \   { 'name': 'Git',         'complete' : 'customlist,git#list_commits' },
      \   { 'name': 'GitCheckout', 'complete' : 'customlist,git#list_commits' },
      \   { 'name': 'GitAdd',      'complete' : 'file' },
      \   'GitLog', 'GitCommit', 'GitBlame', 'GitPush'] }}
NeoBundleLazy 'mattn/gist-vim', {
      \ 'depends': ['mattn/webapi-vim' ],
      \ 'autoload' : {
      \   'commands' : 'Gist' }}

" Viewer and writer for memo
NeoBundleLazy 'glidenote/memolist.vim', { 'autoload' : {
      \ 'commands' : ['MemoNew', 'MemoGrep']
      \ }}
NeoBundleLazy 'kakkyz81/evervim', { 'autoload': {
      \ 'branch' : 'unite',
      \ 'commands' : ['EvervimCreateNote', 'EvervimNotebookList'],
      \ 'unite_sources' : ['evervim/notebook', 'evernote/note', 'evernote/tag', 'evernote/query']
      \ }}

" The awesome plugin looks for one of a few specific patterns under
" the cursor and performs a substition depending on the pattern.
NeoBundleLazy 'AndrewRadev/switch.vim', { 'autoload' : {
      \ 'commands' : 'Switch',
      \ }}
NeoBundleLazy 't9md/vim-textmanip', { 'autoload' : {
      \ 'mappings' : [
      \   '<Plug>(textmanip-move-down)', '<Plug>(textmanip-move-up)',
      \   '<Plug>(textmanip-move-left)', '<Plug>(textmanip-move-right)',
      \   '<Plug>(textmanip-move-smart-left)', '<Plug>(textmanip-move-smart-right)',
      \ ],
      \ }}

" For displaying thin vertical lines at each indentation level
if has('conceal')
  NeoBundleLazy 'Yggdroot/indentLine', { 'autoload' : {
        \   'commands' : ['IndentLinesReset', 'IndentLinesToggle'],
        \   'filetypes': g:my.ft.program_files,
        \ }}
else
  NeoBundleLazy 'nathanaelkane/vim-indent-guides', {
        \ 'autoload': {
        \   'commands': ['IndentGuidesEnable', 'IndentGuidesToggle'],
        \   'filetypes': g:my.ft.program_files,
        \ }}
endif

NeoBundleLazy 'alpaca-tc/vim-qfreplace', { 'autoload' : {
      \ 'filetypes' : ['unite', 'quickfix'],
      \ 'functions' : 'qfreplace#start',
      \ 'commands' : 'Qfreplace',
      \ }}
NeoBundleLazy 'alpaca-tc/unite-session', { 'autoload' : {
      \ 'unite_sources': 'session',
      \ 'commands' : [
      \   { 'name' : 'UniteSessionSave',
      \     'complete' : 'customlist,GetUniteSessionPath' },
      \   { 'name' : 'UniteSessionLoad',
      \     'complete' : 'customlist,GetUniteSessionPath' }
      \   ] }}
function! GetUniteSessionPath(arglead, cmdline, cursorpos) "{{{
  call unite#util#set_default('g:unite_source_session_path', g:my.dir.unite . '/session')
  let sessions = split(glob(g:unite_source_session_path . '/*'), '\n')
  call filter(sessions, 'stridx(v:val, a:arglead) == 0')

  return map(sessions, 'fnamemodify(v:val, ":t:r")')
endfunction"}}}

NeoBundleLazy 'Shougo/unite-outline', {
      \ 'depends' : 'Shougo/unite.vim',
      \ 'autoload' : {
      \   'unite_sources' : 'outline' },
      \ }
NeoBundleLazy 'kmnk/vim-unite-giti', {
      \ 'autoload': {
      \   'unite_sources': [
      \     'giti', 'giti/branch', 'giti/branch/new', 'giti/branch_all',
      \     'giti/pull_request/base', 'giti/pull_request/head',
      \     'giti/config', 'giti/log', 'giti/remote', 'giti/status'
      \   ]
      \ }}
NeoBundleLazy 'Shougo/unite-help', { 'autoload' : {
      \ 'unite_sources' : 'help'
      \ }}
NeoBundleLazy 'thinca/vim-unite-history', { 'autoload' : {
      \ 'unite_sources' : ['history/command', 'history/search']
      \ }}
NeoBundleLazy 'basyura/TweetVim', { 'depends' :
      \ ['basyura/twibill.vim', 'tyru/open-browser.vim', 'Shougo/unite.vim'],
      \ 'autoload' : {
      \   'commands' : [ 'TweetVimAccessToken', 'TweetVimAddAccount',
      \     'TweetVimBitly', 'TweetVimCommandSay', 'TweetVimCurrentLineSay',
      \     'TweetVimHomeTimeline', 'TweetVimListStatuses', 'TweetVimMentions',
      \     'TweetVimSay', 'TweetVimSearch', 'TweetVimSwitchAccount',
      \     'TweetVimUserTimeline', 'TweetVimVersion' ],
      \   'unite_sources' : ['tweetvim', 'tweetvim/account']
      \ }}

NeoBundleLazy 'alpaca-tc/unite-git-aliases', { 'autoload' : {
      \ 'unite_sources' : 'git_aliases' }}

" For inputing several candidates with a single key
NeoBundleLazy 'kana/vim-smartchr', { 'autoload' : {
      \ 'insert' : 1,
      \ 'filetypes' : g:my.ft.program_files,
      \ 'autoload': {
      \   'function_prefix' : 'smartchr',
      \ }
      \ }}

if has('ruby')
  " The input support for English
  NeoBundleLazy 'alpaca-tc/alpaca_english', {
        \ 'build' : {
        \   'mac' : 'bundle',
        \   'unix' : 'bundle',
        \   'other' : 'bundle',
        \ },
        \ 'autoload' : {
        \   'commands' : ['AlpacaEnglishDisable', 'AlpacaEnglishEnable', 'AlpacaEnglishSay'],
        \   'unite_sources': ['english_dictionary', 'english_example', 'english_thesaurus'],
        \ }}

  " For payroll accounting
  NeoBundleLazy 'alpaca-tc/snail_csv2google_sheet', { 'autoload': {
        \ 'commands' : [
        \   { 'name': 'Snail', 'complete' : 'file' },
        \ ],
        \ }}
endif

NeoBundleLazy 'kana/vim-niceblock', { 'autoload' : {
      \ 'mappings' : ['<Plug>(niceblock-I)', '<Plug>(niceblock-A)']
      \ }}

NeoBundleLazy 'airblade/vim-gitgutter', {
      \ 'autoload': {
      \   'commands': [
      \     'GitGutterDisable', 'GitGutterEnable', 'GitGutterToggle', 'GitGutter',
      \     'GitGutterAll', 'GitGutterNextHunk', 'GitGutterPrevHunk', ''
      \ ]}}
NeoBundleLazy 'DirDiff.vim', { 'autoload' : {
      \ 'commands' : 'DirDiff'
      \ }}
NeoBundleLazy 'repeat.vim', { 'autoload' : {
      \ 'mappings' : '.',
      \ }}
NeoBundleLazy 'terryma/vim-multiple-cursors', { 'autload': {
      \ 'function_prefix': 'multiple_cursors',
      \ }}
NeoBundleLazy 'alpaca-tc/auto-pairs', { 'autoload' : {
      \ 'insert': 1 }}

" NeoBundleFetch 'github/gitignore'

" Generating Ricty Font.
" let g:ricty_generate_command = join([
"       \   'sh ricty_generator.sh',
"       \   neobundle#get_neobundle_dir().'/alpaca/fonts/Inconsolata.otf',
"       \   neobundle#get_neobundle_dir().'/alpaca/fonts/migu-1m-regular.ttf',
"       \   neobundle#get_neobundle_dir().'/alpaca/fonts/migu-1m-bold.ttf',
"       \ ], ' ')
" NeoBundleFetch 'yascentur/Ricty', {
"       \ 'depends' : 'alpaca-tc/alpaca',
"       \ 'autoload' : {
"       \   'build' : {
"       \     'mac'  : g:ricty_generate_command,
"       \     'unix' : g:ricty_generate_command,
"       \   }
"       \ }}

" The light converter and beautifier
NeoBundleLazy 'alpaca-tc/beautify.vim', {
      \ 'branch': 'v0.2',
      \ 'build' : {
      \   'mac': 'npm install -g js-beautify && gem install html2haml --pre && npm install -g js2coffee',
      \ },
      \ 'autoload' : {
      \   'commands' : [
      \     {
      \       'name' : 'Beautify',
      \       'complete' : 'customlist,beautify#complete_options'
      \     }
      \ ]
      \ }}

" CSS / SASS
" ----------------------------------------
NeoBundleLazy 'hail2u/vim-css3-syntax', { 'autoload' : {
      \   'filetypes' : g:my.ft.style_files,
      \ }}
NeoBundleLazy 'AtsushiM/sass-compile.vim', {
      \ 'autoload': { 'filetypes': ['sass', 'scss'] }}
NeoBundleLazy 'vim-less', {
      \ 'autoload': { 'filetypes': ['less'] }
      \ }

" HTML
" ----------------------------------------
NeoBundleLazy 'alpaca-tc/html5.vim', { 'autoload' : {
      \   'filetypes' : g:my.ft.markup_files,
      \   'functions' : ['HtmlIndentGet']
      \ }}
NeoBundleLazy 'mattn/emmet-vim', {
      \ 'autoload': {
      \   'function_prefix': 'emmet',
      \   'filetypes': g:my.ft.html_files + g:my.ft.style_files,
      \   'mappings' : ['<Plug>(EmmetExpandAbbr)']
      \ }}

" HAML
" ----------------------------------------
" NeoBundleLazy 'tpope/vim-haml', { 'autoload' : {
"       \   'filetypes' : ['haml'],
"       \ }}

" Haskell
" ----------------------------------------
" NeoBundleLazy 'ujihisa/neco-ghc', { 'autoload' : {
"       \ 'filetypes' : 'haskell'
"       \ }}

" JavaScript / Coffee-script / TypeScript
" ----------------------------------------
NeoBundleLazy 'jiangmiao/simple-javascript-indenter', { 'autoload' : {
      \ 'filetypes' : ['javascript', 'json', 'nginx'],
      \ }}
NeoBundleLazy 'alpaca-tc/documentation', { 'autoload' : {
      \ 'commands' : ['Documentation', 'DocumentationAppend'] }}
NeoBundleLazy 'leafgarland/typescript-vim', { 'autoload' : {
      \ 'filetypes' : ['typescript']
      \ }}
NeoBundleLazy 'kchmck/vim-coffee-script', { 'autoload' : {
      \ 'filetypes' : 'coffee',
      \ 'commands' : ['CoffeeCompile', 'CoffeeWatch', 'CoffeeMake'],
      \ }}
if has('python') && executable('npm')
  NeoBundleLazy 'marijnh/tern_for_vim', {
        \ 'build' : 'npm install',
        \ 'autoload' : {
        \ 'functions': ['tern#Complete', 'tern#Enable'],
        \ 'filetypes' : g:my.ft.js_files
        \ }}
else
  NeoBundleLazy 'teramako/jscomplete-vim', { 'autoload' : {
        \ 'filetypes' : g:my.ft.js_files
        \ }}
endif

" NeoBundleLazy 'claco/jasmine.vim', { 'autoload' : {
"       \ 'filetypes' : g:my.ft.js_files }}

"  go
" ----------------------------------------
NeoBundleLazy 'fsouza/go.vim', { 'autoload' : {
      \ 'filetypes' : ['go'] }}

"  Markdown
" ----------------------------------------
NeoBundleLazy 'tpope/vim-markdown', { 'autoload' : {
      \ 'filetypes' : ['markdown'] }}

"  PHP
" ----------------------------------------
" NeoBundleLazy 'alpaca-tc/alpaca_wordpress.vim', { 'autoload' : {
"       \ 'filetypes': 'php' }}

" Binary
" ----------------------------------------
NeoBundleLazy 'Shougo/vinarise', {
      \ 'depends': ['s-yukikaze/vinarise-plugin-peanalysis'],
      \ 'build' : {
      \   'mac' : 'brew install binutils',
      \ },
      \ 'autoload': { 'commands': 'Vinarise' }}

" Objective-c
" ----------------------------------------
" NeoBundle 'msanders/cocoa.vim'

" Ruby
" ----------------------------------------
NeoBundleLazy 'tpope/vim-rails', { 'autoload' : {
      \ 'filetypes' : g:my.ft.ruby_files }}
NeoBundleLazy 'alpaca-tc/vim-endwise.git', {
      \ 'autoload' : {
      \   'insert' : 1,
      \ }}

" Rails
NeoBundleLazy 'basyura/unite-rails', {
      \ 'depends' : 'Shougo/unite.vim',
      \ 'autoload' : {
      \   'unite_sources' : [
      \     'rails/bundle', 'rails/bundled_gem', 'rails/config',
      \     'rails/controller', 'rails/db', 'rails/destroy', 'rails/features',
      \     'rails/gem', 'rails/gemfile', 'rails/generate', 'rails/git', 'rails/helper',
      \     'rails/heroku', 'rails/initializer', 'rails/javascript', 'rails/lib', 'rails/log',
      \     'rails/mailer', 'rails/model', 'rails/rake', 'rails/route', 'rails/schema', 'rails/spec',
      \     'rails/stylesheet', 'rails/view'
      \   ]
      \ }}
NeoBundleLazy 'taka84u9/vim-ref-ri', {
      \ 'depends': ['Shougo/unite.vim', 'thinca/vim-ref'],
      \ 'autoload': {
      \   'filetypes': g:my.ft.ruby_files,
      \   'unite_sources' : 'ref/ri',
      \ }}
" NeoBundleLazy 'alpaca-tc/neorspec.vim', {
"       \ 'depends' : ['alpaca-tc/vim-rails', 'tpope/vim-dispatch'],
"       \ 'autoload' : {
"       \   'commands' : ['RSpec', 'RSpecAll', 'RSpecCurrent', 'RSpecNearest', 'RSpecRetry']
"       \ }}

" Slim
" ----------------------------------------
NeoBundleLazy 'slim-template/vim-slim', { 'autolaod' : {
      \ 'filetypes' : 'slim' }}

" Nginx
" ----------------------------------------
NeoBundleLazy 'mutewinter/nginx.vim', {
      \ 'autoload' : { 'filetypes': 'nginx' }}

" python
" ----------------------------------------
NeoBundleLazy 'yuroyoro/vim-python', { 'autoload' : {
      \ 'filetypes' : g:my.ft.python_files }}
if has("python")
  NeoBundleLazy 'davidhalter/jedi-vim', {
        \ 'build' : {
        \     'mac' : 'git submodule update --init',
        \     'unix' : 'git submodule update --init',
        \    },
        \ 'autoload' : { 'filetypes': g:my.ft.python_files }
        \ }
endif

" Scala
" ----------------------------------------
" NeoBundleLazy 'andreypopp/ensime', { 'autoload' : {
"       \ 'filetypes' : g:my.ft.scala_files }}
" NeoBundleLazy 'aemoncannon/ensime', {
"       \ "branch" : "scala-2.9",
"       \ 'autoload' : { 'filetypes' : g:my.ft.scala_files }}
" NeoBundleLazy 'alpaca-tc/vimside', {
"       \ 'depends': [
"       \   'megaannum/self', 'megaannum/forms',
"       \   'Shougo/vimproc', 'Shougo/vimshell',
"       \   'aemoncannon/ensime',
"       \ ],
"       \ 'autoload' : { 'filetypes' : g:my.ft.scala_files }}

" C++ / C / C#
" TODO check out [here]( http://d.hatena.ne.jp/thinca/20130522/1369234427 )
" ----------------------------------------
" NeoBundleLazy 'Rip-Rip/clang_complete', {
"      \ 'autoload' : {
"      \     'filetypes' : g:my.ft.c_files,
"      \    },
"      \ }
" NeoBundleLazy 'osyo-manga/neocomplcache-clang_complete', { 'autoload' : {
"      \ 'filetypes' : g:my.ft.c_files,
"      \ }}
" NeoBundleLazy "vim-jp/cpp-vim", { 'autoload' : {
"       \ 'filetypes' : g:my.ft.c_files,
"       \ }}

" Sh
" ----------------------------------------
NeoBundleLazy 'sh.vim', { 'autoload': {
      \ 'filetypes': g:my.ft.sh_files }}

" TEST
" ----------------------------------------
NeoBundleLazy 'mattn/excitetranslate-vim', {
      \ 'depends': 'mattn/webapi-vim',
      \ 'autoload' : { 'commands': ['ExciteTranslate']}
      \ }
" NeoBundle 'kana/vim-altr'

" Installation check.
if has('vim_starting') && g:my.conf.initialize && neobundle#exists_not_installed_bundles()
  echomsg 'Not installed bundles : ' .  string(neobundle#get_not_installed_bundle_names())
  NeoBundleInstall!
endif

filetype plugin indent on
"}}}

" ----------------------------------------
" Editing"{{{
set autoread
set nostartofline
set hidden
set nrformats-=octal
set nrformats+=alpha
set textwidth=0
" set gdefault
" set splitright
set splitbelow
set previewheight=5
set helpheight=14
set matchtime=1

if has('multi_byte_ime')
  set iminsert=0 imsearch=0
endif

xnoremap < <gv
xnoremap m :sort<CR>
xnoremap > >gv

nnoremap <silent><Space><Space>q :qall!<CR>
nnoremap <silent><Space><Space>w :wall!<CR>
nnoremap <silent><Space>q :q!<CR>
nnoremap <silent><Space>w :wq<CR>
nnoremap <silent><Space>s :SudoWrite %<CR>

nnoremap <silent><C-L> :call <SID>redraw_and_doautocmd()<CR>
function! s:redraw_and_doautocmd() "{{{
  silent doautocmd CursorHoldI <buffer>
  redraw!
endfunction"}}}

nnoremap re :%s!
xnoremap re :s!
xnoremap rep y:%s!<C-r>=substitute(@0, '!', '\\!', 'g')<CR>!!g<Left><Left>

nnoremap ,f :FileType<Space>
command! -nargs=? -complete=filetype FileType execute 'set filetype=' . <q-args>

function! s:define_abbreviations() "{{{
  " Abbreviations {{{
  let s:abbr_dictionary = {
        \ 'javascript' : [
        \   'elsif else if',
        \   'elseif else if',
        \ ],
        \ 'vim' : [
        \ ],
        \ 'yaml': [
        \   '<< << : *'
        \ ],
        \ 'ruby.rspec' : [
        \   'sh should',
        \   "reqs require 'spec_helper'",
        \ ],
        \ 'ruby' : [
        \   'req require',
        \ ],
        \ 'scss': [
        \   'in include',
        \   'im import',
        \   'mi mixin',
        \ ],
        \ 'python' : [
        \   'im import',
        \ ],
        \ 'gitcommit' : [
        \   'wip [WIP]',
        \   'imo IMO',
        \ ],
        \ }
  "}}}

  autocmd! Abbreviations
  for [filetype, abbreviation_definitions] in items(s:abbr_dictionary)
    call alpaca#initialize#define_abbreviations(abbreviation_definitions, filetype)
  endfor
endfunction

if has('vim_starting')
  augroup Abbreviations
    autocmd!
    autocmd FileType * call <SID>define_abbreviations()
  augroup END
endif
"}}}

let g:end_tag_commant_format = '<!-- /%tag_name%id%class -->'
nnoremap ,t :call alpaca#function#html#endtag_comment()<CR>

inoremap <C-R> <C-R><C-R>
inoremap <C-R><C-R> <C-R>"

cnoremap <C-R> <C-R><C-R>
cnoremap <C-R><C-R> <C-R>"
cnoremap <C-L> <Right>

xnoremap H <Nop>
inoremap <C-@> <Nop>

augroup MyEditing
  autocmd!
  autocmd BufEnter * execute ':silent! lcd! ' . expand('%:p:h')
  autocmd Filetype xml,html,eruby inoremap <buffer> </ </<C-X><C-O>
  autocmd FileType slim,ruby,eruby,haml,racc,ruby.racc inoremap <buffer>\| \|\|<Left>
augroup END
"}}}

" ----------------------------------------
" Searching {{{
set hlsearch
set ignorecase
set incsearch
set smartcase
set wrapscan

nnoremap <silent> n nvv
nnoremap <silent> N Nvv

nnoremap <silent>,mc :<C-u>call alpaca#function#macdict#close()<CR>
nnoremap <silent>,mf :<C-u>call alpaca#function#macdict#focus()<CR>
nnoremap <silent>,mo :<C-u>call alpaca#function#macdict#with_cursor_word()<CR>
command! -nargs=1 Dict call alpaca#function#macdict#search(<q-args>)
"}}}

" ----------------------------------------
" Moving {{{
set virtualedit+=block
set whichwrap=b,s,h,l,~,<,>,[,]

inoremap <silent><C-A> <End>
inoremap <silent><C-L> <Right>
inoremap jj <Esc>
nnoremap $ g_
xnoremap $ g_
nnoremap <silent><Down> gj
nnoremap <silent><Up>   gk
nnoremap <silent>j gj
nnoremap <silent>k gk
nnoremap <silent>gj j
nnoremap <silent>gk k
nnoremap <silent>Y y$

let g:alpaca_window_default_filetype = 'ruby'
let g:alpaca_window_max_height = g:my.conf.winheight
let g:alpaca_window_max_width = g:my.conf.winwidth
nmap <silent>L            <Plug>(alpaca_window_move_next_window_or_tab)
nmap <silent>H            <Plug>(alpaca_window_move_previous_window_or_tab)
nmap <silent><C-W>n       <Plug>(alpaca_window_smart_new)
nmap <silent><C-W><C-N>   <Plug>(alpaca_window_smart_new)

function! s:search_same_indent_line(next) "{{{
  let current_line = getline('.')
  let current_indent_level = len(matchstr((current_line), '^\s*'))
  let current_pos = line('.')

  for line_pos in a:next ? range(current_pos + 1, line('$')) : range(current_pos - 1, 1, -1)
    let line = getline(line_pos)
    let indent_level = len(matchstr((line), '^\s*'))
    if indent_level == current_indent_level && line != ''
      return cursor(line_pos, current_indent_level + 1)
    endif
  endfor

  echomsg 'Not found'
endfunction"}}}
nnoremap <silent>_n :<C-U>call <SID>search_same_indent_line(1)<CR>
nnoremap <silent>_p :<C-U>call <SID>search_same_indent_line(0)<CR>

augroup MyAutoCmd
  autocmd BufReadPost * if line("'\"") > 0 && line("'\"") <= line('$') | execute "normal g`\"" | endif
augroup END
"}}}

" ----------------------------------------
" Tab {{{
nmap [tag_or_tab] <Nop>
nmap t [tag_or_tab]
nmap <silent>[tag_or_tab]c      <Plug>(alpaca_window_tabnew)
nmap <silent>[tag_or_tab]w      <Plug>(alpaca_window_move_buffer_into_last_tab)
nnoremap <silent>[tag_or_tab]n  :tabnext<CR>
nnoremap <silent>[tag_or_tab]p  :tabprevious<CR>
nnoremap <silent>[tag_or_tab]x  :tabclose<CR>
nnoremap <silent>[tag_or_tab]o  <C-W>T

for num in range(0, 9)
  execute 'nnoremap <silent>[tag_or_tab]'.num.'  :tabnext '.num'<CR>'
  execute 'nnoremap <silent>[tag_or_tab]m'.num.'  :tabmove '.num'<CR>'
endfor
unlet num
"}}}

" ----------------------------------------
" Encoding {{{
set ambiwidth=double
set encoding=utf-8
set fileencodings=utf-8,sjis,shift-jis,euc-jp,utf-16,ascii,ucs-bom,cp932,iso-2022-jp
set fileformat=unix
set fileformats=unix,dos,mac
set suffixes=.bak,~,.swp,.o,.info,.aux,.log,.dvi,.bbl,.blg,.brf,.cb,.ind,.idx,.ilg,.inx,.out,.toc
set termencoding=utf8

command! -bang -bar -complete=file -nargs=? Cp932 edit<bang> ++enc=cp932 <args>
command! -bang -bar -complete=file -nargs=? Euc edit<bang> ++enc=euc-jp <args>
command! -bang -bar -complete=file -nargs=? Iso2022jp edit<bang> ++enc=iso-2022-jp <args>
command! -bang -bar -complete=file -nargs=? Jis  Iso2022jp<bang> <args>
command! -bang -bar -complete=file -nargs=? Sjis  Cp932<bang> <args>
command! -bang -bar -complete=file -nargs=? Unicode Utf16<bang> <args>
command! -bang -bar -complete=file -nargs=? Utf16 edit<bang> ++enc=ucs-2le <args>
command! -bang -bar -complete=file -nargs=? Utf16be edit<bang> ++enc=ucs-2 <args>
command! -bang -bar -complete=file -nargs=? Utf8 edit<bang> ++enc=utf-8 <args>
" }}}

" ----------------------------------------
" Indent {{{
set autoindent
set expandtab
set smartindent
set smarttab
set softtabstop=2
set shiftwidth=2
set tabstop=2
filetype indent on
"}}}

" ----------------------------------------
" Display {{{
" set noequalalways
" set cursorline
" set titlelen=95
set pumheight=20
set breakat=\\;:,!?
set cdpath+=~
set cmdheight=2
set equalalways
set laststatus=2
set lazyredraw
set browsedir=buffer
set list
set listchars=tab:␣.,trail:›,extends:>,precedes:<
set fillchars=stl:\ ,stlnc:\ ,fold:\ ,diff:-
set matchpairs+=<:>
set number
set scrolloff=8
set noshowcmd
set showfulltag
set showmatch
set showtabline=1
set spelllang=en
set nospell
set t_Co=256
set title
set ttyfast
set shortmess=aTI

set foldenable
set foldmethod=marker
set foldlevelstart=0
set foldminlines=2
set foldnestmax=2

if v:version >= 703
  highlight ColorColumn guibg=#012345
  set conceallevel=2 concealcursor=iv
  set colorcolumn=81
endif

augroup MyWindow
  autocmd VimResized * execute "normal! \<c-w>="
augroup END

colorscheme desertEx
syntax on
"}}}

" ----------------------------------------
" Tags {{{
set tags=./tags

" Vim's bug.
if v:version < 703 || (v:version == 7.3 && !has('patch336'))
  set notagbsearch
endif

nnoremap [tag_or_tab]t  <C-]>
nnoremap [tag_or_tab]h  :<C-u>pop<CR>
nnoremap [tag_or_tab]l  :<C-u>tag<CR>
nnoremap [tag_or_tab]j  :<C-u>tprevious<CR>
nnoremap [tag_or_tab]k  :<C-u>tags<CR>
nnoremap [tag_or_tab]s  :<C-u>tselect<CR>

augroup AlpacaTags
  autocmd!
  if exists(':Tags')
    autocmd BufWritePost Gemfile TagsBundle
    autocmd BufRead,BufNew * TagsSet
    " autocmd BufWritePost * TagsUpdate
  endif
augroup END
"}}}

" ----------------------------------------
" Dictionary {{{
function! s:set_dictionary_automatically() "{{{
  let filetype = &filetype
  if empty(filetype) || count(g:my.ft.ignore_patterns, filetype) > 0
    return
  endif

  let dict_name = split(filetype, '\.')

  setl dictionary=

  let filetypes = []
  for ft in dict_name
    call add(filetypes, ft)

    let dict_path = '~/.vim/dict/'. join(filetypes, '.') .'.dict'
    execute 'setl dictionary+=' . dict_path

    if exists(':NeoSnippetSource')
      let snippet_path = '~/.vim/snippet/'. join(filetypes, '.') .'.snip'
      if filereadable(snippet_path)
        execute 'NeoSnippetSource '. snippet_path
      endif
    endif
  endfor
endfunc"}}}

augroup MyAutoCmd
  autocmd FileType * call <SID>set_dictionary_automatically()
augroup END

nnoremap <buffer><Space>d :execute join([alpaca_window#util#get_smart_split_command('split'), split(&dictionary, ',')[-1]], ' ')<CR>
nnoremap <buffer><Space><Space>d :execute join([alpaca_window#util#get_smart_split_command('split'), split(&dictionary, ',')[-2]], ' ')<CR>
nnoremap <buffer><Space><Space><Space>d :execute join([alpaca_window#util#get_smart_split_command('split'), split(&dictionary, ',')[-3]], ' ')<CR>
"}}}

" ----------------------------------------
" History {{{
set complete=.,w,b,u,U,s,i,d,t
set completeopt=menu,menuone
set history=1000
set infercase
set wildchar=<tab>
set wildmenu
set showfulltag
set wildoptions=tagfile
set wildmode=longest:full,full
" set thesaurus+=~/.vim/thesaurus/mthes10/mthesaur.txt

" Complement command in command-line like zsh
cnoremap <C-P> <UP>
cnoremap <C-N> <Down>
"}}}

" ----------------------------------------
" Plugin settings {{{
nnoremap [plug] <Nop>
nmap <C-H> [plug]

" ------------------------------------
let bundle = NeoBundleGet('vim-arpeggio')
function! bundle.hooks.on_source(bundle) "{{{
  let escape = '<Esc>:nohlsearch<CR>'
  call arpeggio#map('i', 's', 0, 'jk', escape)
  call arpeggio#map('v', 's', 0, 'jk', escape)
  call arpeggio#map('x', 's', 0, 'jk', escape)
  call arpeggio#map('c', 's', 0, 'jk', escape)
endfunction "}}}
unlet bundle

" ------------------------------------
xnoremap <silent>n :<C-U>EasyAlign<CR>
xnoremap e :EasyAlign<Space>

" ------------------------------------
nmap cs  <Plug>Csurround
nmap ds  <Plug>Dsurround
nmap ySS <Plug>YSsurround
nmap ySs <Plug>YSsurround
nmap ys  <Plug>Ysurround
nmap yss <Plug>Yssurround

xmap S   <Plug>VSurround
xmap gS  <Plug>VgSurround
xmap s   <Plug>VSurround

let bundle = NeoBundleGet('vim-surround')
function! bundle.hooks.on_source(bundle) "{{{
  let g:surround_no_mappings = 1
  let s:surround_definitions = {
        \ join(g:my.ft.ruby_files, ',') : {
        \   '#':  "#{\r}",
        \   '%':  "<% \r %>",
        \   '-':  "<% \r -%>",
        \   '=':  "<%= \r %>",
        \   'w':  "%w!\r!",
        \   'W':  "%W!\r!",
        \   'q':  "%q!\r!",
        \   'Q':  "%Q!\r!",
        \   'r':  "%r!\r!",
        \   'R':  "%R!\r!",
        \   '\"':  '\"\r\"',
        \   "'":  "'\r'",
        \   '{':  "{ \r }",
        \   'd':  'do\n \r end',
        \ },
        \ join(g:my.ft.php_files, ',') : {
        \   '<' : '<?php \r ?>',
        \ },
        \ '_' : {
        \   '(' : "(\r)",
        \   '[' : "[\r]",
        \   '{' : "{ \r }",
        \   '#':  "#{\r}",
        \ },
        \ 'snippet' : {
        \   '$' : "${\r}",
        \ }
        \ }

  let s:surround_definitions =
        \ alpaca#initialize#redefine_dict_to_each_filetype(s:surround_definitions, {})

  function! s:define_variable_for_surround(mapping_dict) "{{{
    for [key, mapping] in items(a:mapping_dict)
      let var_name = 'surround_'.char2nr(key)
      call alpaca#let_b:(var_name, mapping)
    endfor
  endfunction"}}}

  function! s:get_definition(filetype) "{{{
    let filetype = a:filetype

    let memo = []
    let filetypes = []

    for ft in split(filetype, '\.')
      call add(filetypes, ft)
      let ft_name = join(filetypes, '.')

      if has_key(s:surround_definitions, ft_name)
        let definition = s:surround_definitions[ft_name]
        call add(memo, definition)
      endif
    endfor

    if has_key(s:surround_definitions, '_')
      let definition = s:surround_definitions['_']
      call add(memo, definition)
    endif

    return memo
  endfunction"}}}

  function! s:define_variables_for_surround() "{{{
    let s:surrond_definitions_cache = get(s:, 'surrond_definitions_cache', {})
    let filetype = &filetype

    if !has_key(s:surrond_definitions_cache, filetype)
      let s:surrond_definitions_cache[filetype] = s:get_definition(filetype)
    endif

    for mappings in get(s:surrond_definitions_cache, filetype, [])
      call s:define_variable_for_surround(mappings)
    endfor
  endfunction"}}}

  augroup MySurroundMapping
    autocmd!
    autocmd FileType * call <SID>define_variables_for_surround()
  augroup END
endfunction"}}}
function! bundle.hooks.on_post_source(bundle) "{{{
  call s:define_variables_for_surround()
endfunction"}}}
unlet bundle

" ------------------------------------
nnoremap <silent><C-G><C-G> :<C-u>Rgrep<Space><C-r><C-w> *<CR><CR>
nnoremap <silent><C-G><C-B> :<C-u>GrepBuffer<Space><C-r><C-w><CR>
let bundle = NeoBundleGet('grep.vim')
function! bundle.hooks.on_source(bundle) "{{{
  let Grep_Find_Use_Xargs = 0
  let Grep_Skip_Dirs = '.svn .git .swp .hg cache compile'
  let Grep_Skip_Files = '*.bak *~ .swp .swa .swo'
  let Grep_Xargs_Options = '--print0'
endfunction "}}}
unlet bundle

" ------------------------------------
nnoremap <Space>t :TagbarToggle<CR>
let bundle = NeoBundleGet('tagbar')
function! bundle.hooks.on_source(bundle) "{{{
  augroup MyTagbarCmd
    autocmd!
    autocmd FileType tagbar
          \ nnoremap <buffer><Space> <Space>
          \|nnoremap <buffer><space>t :<C-U>TagbarToggle<CR>
  augroup END

  if exists('g:my.bin.ctags') && executable(g:my.bin.ctags)
    let g:tagbar_ctags_bin = g:my.bin.ctags
  else
    let g:tagbar_ctags_bin = 'ctags'
  endif

  let g:tagbar_autoclose = 0
  " let g:tagbar_sort = 0
  let g:tagbar_compact    = 1
  let g:tagbar_autofocus  = 1
  let g:tagbar_autoshowtag= 1
  let g:tagbar_iconchars  =  ['▸', '▾']
  let g:tagbar_width = 40
endfunction "}}}
unlet bundle

" ------------------------------------
" open-browser
nmap ,o <Plug>(openbrowser-open)
xmap ,o <Plug>(openbrowser-open)
nnoremap ,g :<C-u>OpenBrowserSearch<Space><C-R><C-W><CR>

" ------------------------------------
nnoremap <silent>,r :QuickRun<CR>
let bundle = NeoBundleGet('vim-quickrun')
function! bundle.hooks.on_source(bundle) "{{{
  let g:quickrun_config = {}
  let g:quickrun_no_default_key_mappings = 1

  let g:quickrun_config._ = {
        \ 'runner' : 'vimproc',
        \ }
  let g:quickrun_config.javascript = {
        \ 'command': 'node'}

  let g:quickrun_config.lisp = {
        \ 'command': 'clisp' }

  let g:quickrun_config['coffee.compile'] = {
        \ 'command' : 'coffee',
        \ 'exec' : ['%c -cbp %s'] }

  let g:quickrun_config['coffee'] = {
        \ 'command' : 'coffee'
        \ }
  let g:quickrun_config['coffee.javascript'] = g:quickrun_config['coffee']

  let g:quickrun_config.markdown = {
        \ 'outputter': 'browser',
        \ 'cmdopt': '-s' }

  let g:quickrun_config.applescript = {
        \ 'command' : 'osascript' , 'output' : '_'}

  let g:quickrun_config['racc.ruby'] = {
        \ 'command': 'racc',
        \ 'cmdopt' : '-o',
        \ 'args'   : 'main.rb',
        \ 'outputter': 'message',
        \ 'exec'   : '%c %o %a %s', }

  let g:quickrun_config['racc.run'] = {
        \ 'command': 'ruby',
        \ 'args'   : 'main.rb',
        \ 'exec'   : '%c %a src/', }

  let g:quickrun_config['ruby.rspec'] = {
        \ 'type' : 'ruby.rspec',
        \ 'command': 'rspec',
        \ 'exec': 'bundle exec %c %o %s', }

  augroup QuickRunAutoCmd
    autocmd!
    autocmd FileType quickrun call alpaca_window#smart_close()
  augroup END
endfunction"}}}
unlet bundle

" ----------------------------------------
let bundle = NeoBundleGet('zencoding-vim')
function! bundle.hooks.on_source(bundle) "{{{
  let g:user_zen_complete_tag = 1
  let g:user_zen_expandabbr_key = '<C-E>'
  let g:user_zen_leader_key = '<c-y>'
  " let g:user_zen_leader_key = '<C-Y>'

  let g:user_zen_settings = {
        \ 'lang' : 'ja',
        \ 'html' : {
        \   'filters' : 'html',
        \   'indentation' : ''
        \ },
        \ 'css' : {
        \   'filters' : 'fc',
        \ },
        \ 'scss' : {
        \   'snippets': {
        \     'fs' : 'font-size: ${cursor};',
        \   },
        \ },
        \ 'php' : {
        \   'extends' : 'html',
        \   'filters' : 'html,c',
        \ },
        \ }
endfunction "}}}
unlet bundle

" ----------------------------------------
imap <buffer><C-E> <C-Y>,
let bundle = NeoBundleGet('emmet-vim')
function! bundle.hooks.on_source(bundle) "{{{
  let g:user_emmet_mode = 'iv'
  let g:user_emmet_leader_key = '<C-Y>'
  let g:use_emmet_complete_tag = 1
  let g:user_emmet_settings = {
        \ 'lang' : 'ja',
        \ 'html' : {
        \   'filters' : 'html',
        \ },
        \ 'php' : {
        \   'extends' : 'html',
        \   'filters' : 'html',
        \ },
        \}
  augroup EmmitVim
    autocmd!
    autocmd BufEnter,FileType * let g:user_emmet_settings.indentation = '               '[:&tabstop]
  augroup END
endfunction"}}}
unlet bundle

" ----------------------------------------
nnoremap <C-K> :<C-U>Ref alc <Space><C-R><C-W><CR>
xnoremap <C-K> :<C-U>Ref alc <Space><C-R><C-W><CR>
nnoremap ra  :<C-U>Ref alc<Space>
nnoremap rp  :<C-U>Ref phpmanual<Space>
nnoremap rr  :<C-U>Unite ref/refe -immediately -input=
nnoremap ri  :<C-U>Unite ref/ri -immediately -input=
nnoremap rm  :<C-U>Unite ref/man -immediately -input=
nnoremap rpy :<C-U>Unite ref/pydoc -immediately -input=
nnoremap rpe :<C-U>Unite ref/perldoc -immediately -input=
nmap <silent><buffer>K <Plug>(ref-keyword)

let bundle = NeoBundleGet('vim-ref')
function bundle.hooks.on_source(bundle) "{{{
  let g:ref_open                    = 'tabnew'
  let g:ref_cache_dir               = g:my.dir.vimref
  let g:ref_phpmanual_path          = expand('~/.vim/ref/php-chunked-xhtml')
  " let g:ref_refe_encoding           = 'utf-8'
  let g:ref_no_default_key_mappings = 1

  augroup VimRef
    autocmd!
    autocmd FileType ruby,eruby,ruby.rspec nnoremap <silent><buffer>KK :<C-U>Unite -no-start-insert ref/ri -default-action=split -immediately -input=<C-R><C-W><CR>
    autocmd FileType ruby,eruby,ruby.rspec nnoremap <silent><buffer>K  :<C-U>Unite -no-start-insert ref/refe -immediately -input=<C-R><C-W><CR>
  augroup END
endfunction "}}}
unlet bundle

" ----------------------------------------
nnoremap <silent>gM :Gcommit --amend<CR>
nnoremap <silent>gb :Gblame<CR>
nnoremap <silent>gB :Gbrowse<CR>
nnoremap <silent>gm :Gcommit<CR>
let bundle = NeoBundleGet('vim-fugitive')
function! bundle.hooks.on_source(bundle) "{{{
  augroup MyGitCmd
    autocmd!
    autocmd FileType fugitiveblame vertical res 25
    autocmd FileType gitcommit,git-diff nnoremap <buffer>q :q<CR>
  augroup END

  let g:fugitive_git_executable = g:my.bin.git
endfunction"}}}
function! bundle.hooks.on_post_source(bundle) "{{{
  call fugitive#detect(expand('<amatch>:p'))
endfunction "}}}
command! GitFugitiveReload call fugitive#detect(expand('<amatch>:p'))
unlet bundle

" ----------------------------------------
nnoremap gA :<C-U>GitAdd<Space>
nnoremap <silent>ga :<C-U>GitAdd<CR>
nnoremap <silent>gd :<C-U>GitDiff HEAD<CR>
nnoremap gp :<C-U>Git push<Space>
nnoremap gD :<C-U>GitDiff<Space>
let bundle = NeoBundleGet('git-vim')
function! bundle.hooks.on_source(bundle) "{{{
  let g:git_bin = g:my.bin.git
  let g:git_command_edit = 'vnew'
  let g:git_no_default_mappings = 1
endfunction "}}}
unlet bundle

" ------------------------------------
" let bundle = NeoBundleGet('camelcasemotion')
" function bundle.hooks.on_source(bundle) "{{{
  map <silent> w <Plug>CamelCaseMotion_w
  map <silent> b <Plug>CamelCaseMotion_b
  sunmap w
  sunmap b

  nnoremap diw di,w
  nnoremap dib di,b
  nnoremap die di,e

  nnoremap ciw ci,w
  nnoremap cib ci,b
  nnoremap cie ci,e

  omap <silent>iw <Plug>CamelCaseMotion_iw
  xmap <silent>iw <Plug>CamelCaseMotion_iw
  omap <silent>ib <Plug>CamelCaseMotion_ib
  xmap <silent>ib <Plug>CamelCaseMotion_ib
  omap <silent>ie <Plug>CamelCaseMotion_ie
  xmap <silent>ie <Plug>CamelCaseMotion_ie
" endfunction "}}}
" unlet bundle

" ------------------------------------
nnoremap <silent>,v  :<C-U>VimShell<CR>
nnoremap <silent>,V  :<C-U>VimShellBufferDir<CR>
let bundle = NeoBundleGet('vimshell')
function! bundle.hooks.on_source(bundle) "{{{
  let g:vimshell_user_prompt  = '"(" . getcwd() . ")" '
  let g:vimshell_prompt       = '$ '
  let g:vimshell_ignore_case  = 1
  let g:vimshell_smart_case   = 1
  let g:vimshell_temporary_directory = g:my.dir.vimshell

  let s:vimshell_altercmd = [
        \ 'vi vim',
        \ 'g git',
        \ 'r rails',
        \ 'diff diff --unified',
        \ 'du du -h',
        \ 'free free -m -l -t',
        \ 'll ls -lh',
        \ 'la ls -a'
        \ ]
  call map(map(s:vimshell_altercmd, "split(v:val, ' ')"), '[v:val[0], join(v:val[1:], " ")]')
  " => [['vi', 'vim'], ['la', 'ls -a']]

  function! s:vimshell_settings()
    for altercmd in s:vimshell_altercmd
      call vimshell#altercmd#define(altercmd[0], altercmd[1])
    endfor
  endfunction

  augroup MyAutoCmd
    autocmd FileType vimshell call <SID>vimshell_settings()
  augroup END
endfunction "}}}
unlet bundle

" ------------------------------------
function! s:edit_memolist() "{{{
  let pwd = getcwd()
  lcd `=g:my.dir.memolist`
  Unite file
  lcd `=pwd`
endfunction"}}}
nnoremap <silent><Space>mn :MemoNew<CR>
nnoremap <silent><Space>ml :call <SID>edit_memolist()<CR>

let bundle = NeoBundleGet('memolist.vim')
function! bundle.hooks.on_source(bundle) "{{{
  let g:memolist_path              = g:my.dir.memolist
  let g:memolist_template_dir_path = g:my.dir.trash
  let g:memolist_memo_suffix       = 'md'
  let g:memolist_memo_date         = '%D %T'
  let g:memolist_vimfiler          = 1
endfunction"}}}
unlet bundle

" ----------------------------------------
nnoremap <Space>en :<C-U>EvervimCreateNote<CR>
nnoremap <Space>el :<C-U>Unite evervim/notebook<CR>

let bundle = NeoBundleGet('evervim')
function! bundle.hooks.on_source(bundle) "{{{
  let evernote_dir = get(g:my.dir, 'evernote', '~/.evervim')
  let evernote_path = evernote_dir . '/.evernote_token'

  if !filereadable(evernote_path)
    execute 'OpenBrowser https://www.evernote.com/api/DeveloperToken.action'
    let evernote = input('DeveloperToken:')
    call writefile([evernote], evernote_path)
  endif

  let g:evervim_workdir = evernote_dir
  let g:evervim_devtoken = substitute(system('cat ' . evernote_path), '\n$', '', 'g')
endfunction"}}}
unlet bundle

" ------------------------------------
" coffee-script
" ------------------------------------
function! CompileCoffeeAutomatically() "{{{
  augroup MyCofeeSetting
    autocmd!
    autocmd BufWritePost <buffer> silent CoffeeMake! -cb | cwindow | redraw!
    autocmd FileType <buffer> autocmd! MyCofeeSetting
    autocmd User User CoffeeWatch set filetype=javascript
  augroup END
endfunction"}}}

" ------------------------------------
" t_comment
" ------------------------------------
let g:tcommentmaps = 0
noremap <silent><C-_><c-_> :TComment<CR>
noremap <silent><C-_>c :TComment<CR>

" ------------------------------------
" vim-rails {{{
let bundle = NeoBundleGet('vim-rails')
function! bundle.hooks.on_source(bundle) "{{{
  let g:dbext_default_SQLITE_bin = 'mysql2'
  let g:rails_default_file='config/database.yml'
  let g:rails_gnu_screen=1
  let g:rails_level = 4
  let g:rails_mappings=1
  let g:rails_modelines=0
  let g:rails_syntax = 1
  let g:rails_url='http://localhost:3000'

  function! s:unite_rails_setting() "{{{
    nnoremap <buffer><Space>r :R<CR>
    nnoremap <buffer><Space>a :A<CR>

    nnoremap <buffer>[plug]            :<C-U>UniteGit app/models<CR>
    nnoremap <buffer>[plug]<C-H>       :<C-U>UniteGit app/controllers<CR>
    nnoremap <buffer>[plug]<C-H><C-H>  :<C-U>UniteGit app/views<CR>
    nnoremap <buffer>[plug]v           :<C-U>UniteGit app/views<CR>

    nnoremap <buffer>[plug]c           :<C-U>UniteGit config<CR>
    nnoremap <buffer>[plug]j           :<C-U>UniteGit app/assets/javascripts<CR>
    nnoremap <buffer>[plug]a           :<C-U>UniteGit app/assets/stylesheets<CR>
    nnoremap <buffer>[plug]s           :<C-U>UniteGit spec<CR>
    nnoremap <buffer>[plug]d           :<C-U>UniteGit db<CR>
    nnoremap <buffer>[plug]i           :<C-U>UniteGit db/migrate<CR>
    nnoremap <buffer>[plug]f           :<C-U>UniteGit db/fixtures<CR>
    nnoremap <buffer>[plug]m           :<C-U>UniteGit app/mailers<CR>
    nnoremap <buffer>[plug]l           :<C-U>UniteGit lib<CR>
    nnoremap <buffer>[plug]p           :<C-U>UniteGit public<CR>
    nnoremap <buffer>[plug]g           :<C-U>UniteGit Gemfile<CR>
    nnoremap <buffer>[plug]r           :<C-U>UniteGit config/routes.rb<CR>
    nnoremap <buffer>[plug]h           :<C-U>UniteGit app/helpers<CR>

    " for syntax in split(glob($HOME . '/.vim/syntax/ruby.rails.*.vim'))
    "   execute 'source ' . syntax
    " endfor

    " nnoremap <buffer><silent>,cr  :<C-U>RSpecCurrent<CR>
    " nnoremap <buffer><silent>,nr :<C-U>RSpecNearest<CR>
    " nnoremap <buffer><silent>,lr :<C-U>RSpecRetry<CR>
    " nnoremap <buffer><silent>,ar :<C-U>RSpecAll<CR>
  endfunction"}}}

  augroup RailsDictSetting
    autocmd!
    autocmd User Rails call <SID>unite_rails_setting()
  augroup END
endfunction"}}}

function! s:load_vim_rails() "{{{
  if exists('s:loaded_vim_rails')
    return
  endif

  let root_dir = s:current_git()
  if !empty(root_dir) && filereadable(root_dir . '/config/environments/development.rb')
    let s:loaded_vim_rails = 1

    autocmd! LoadVimRails
    augroup! LoadVimRails
    NeoBundleSource vim-rails
  endif
endfunction"}}}

if has('vim_starting') && !exists('s:loaded_vim_rails')
  augroup LoadVimRails
    autocmd!
    autocmd BufEnter * call <SID>load_vim_rails()
  augroup END
endif
"}}}

" ------------------------------------
" vim-rspec
" ------------------------------------
let g:RspecKeymap = 0
function! s:rspec_settings() "{{{
  setl foldmethod=syntax foldlevel=2 foldlevelstart=1 foldminlines=10 foldnestmax=10

  augroup RspecSetting
    autocmd!
    autocmd FileType RSpecOutput setl nofoldenable
  augroup END
endfunction "}}}

augroup MyAutoCmd
  autocmd FileType ruby.rspec call <SID>rspec_settings()
augroup END

" ------------------------------------
let bundle = NeoBundleGet('gist-vim')
function! bundle.hooks.on_source(bundle) "{{{
  let g:gist_browser_command         = 'w3m %URL%'
  let g:gist_clip_command            = 'pbcopy'
  let g:gist_detect_filetype         = 1
  let g:gist_open_browser_after_post = 1
  let g:github_user                  = g:my.info.github
endfunction"}}}
unlet bundle

" ------------------------------------
nnoremap <silent>[unite]w  :<C-U>Unite tweetvim -buffer-name=tweetvim -no-start-insert<CR>
nnoremap <silent>tv :<C-U>TweetVimSay<CR>

let bundle = NeoBundleGet('TweetVim')
function! bundle.hooks.on_source(bundle) "{{{
  let g:tweetvim_async_post      = 1
  let g:tweetvim_display_source  = 1
  let g:tweetvim_display_time    = 1
  let g:tweetvim_open_buffer_cmd = 'tabnew'
endfunction"}}}
unlet bundle

" ------------------------------------
" sass-compile.vim
" ------------------------------------
let bundle = NeoBundleGet('sass-compile.vim')
function! bundle.hooks.on_source(bundle) "{{{
  let g:sass_compile_cdloop = 5
  let g:sass_compile_cssdir = ['css', 'stylesheet']
  let g:sass_compile_file = ['scss', 'sass']
  let g:sass_started_dirs = []
  let g:sass_compile_beforecmd = ''
endfunction"}}}
unlet bundle

function! CompileSassAutomatically() "{{{
  augroup CompileSassAutomatically
    autocmd!
    autocmd BufWritePost <buffer> SassCompile
    autocmd FileType <buffer> autocmd! AutoSassCompile
  augroup END
endfunction"}}}

" ------------------------------------
" operator-camelize.vim
" ------------------------------------
xmap ,u <Plug>(operator-camelize)
xmap ,U <Plug>(operator-decamelize)

" ------------------------------------
let bundle = NeoBundleGet('vim-smartchr')
function! bundle.hooks.on_source(bundle) "{{{
  augroup MySmarChr
    autocmd!
    autocmd FileType c,cpp    inoremap <buffer><expr> . smartchr#loop('.', '->', '..', '...')
    autocmd FileType perl,php inoremap <buffer><expr> - smartchr#loop('-', '->')
    autocmd FileType coffee   inoremap <buffer><expr> - smartchr#loop('-', '->', '=>')
    autocmd FileType scala    inoremap <buffer><expr> - smartchr#loop('-', '->', '=>')
    autocmd FileType yaml,eruby inoremap <buffer><expr> < smartchr#loop('<', '<%', '<%=')
          \| inoremap <buffer><expr> > smartchr#loop('>', '%>', '-%>')
  augroup END
endfunction"}}}
unlet bundle

" ------------------------------------
let bundle = NeoBundleGet('syntastic')
function! bundle.hooks.on_source(bundle) "{{{
  let g:syntastic_auto_jump           = 1
  let g:syntastic_auto_loc_list       = 1
  let g:syntastic_check_on_open       = 0
  let g:syntastic_echo_current_error  = 0
  let g:syntastic_enable_balloons     = has('balloon_eval')
  let g:syntastic_enable_highlighting = 0
  let g:syntastic_enable_signs        = 1
  let g:syntastic_loc_list_height     = 2
  let g:syntastic_error_symbol        = '>'
  let g:syntastic_warning_symbol      = 'X'

  let s:passive_filetypes       = ['html', 'yaml', 'racc.ruby', 'eruby']
  let g:syntastic_ruby_checkers = ['mri', 'rubocop']
  let g:syntastic_mode_map      = {
        \ 'mode'              : 'active',
        \ 'active_filetypes'  : g:my.ft.program_files,
        \ 'passive_filetypes' : copy(s:passive_filetypes),
        \ }
endfunction"}}}
unlet bundle

" ------------------------------------
let bundle = NeoBundleGet('vim-indent-guides')
function! bundle.hooks.on_source(bundle) "{{{
  let g:indent_guides_auto_colors           = 0
  let g:indent_guides_color_change_percent  = 20
  let g:indent_guides_enable_on_vim_startup = 1
  let g:indent_guides_guide_size            = 1
  let g:indent_guides_space_guides          = 1
  let g:indent_guides_start_level           = 2
  highlight IndentGuidesOdd  ctermbg=235
  highlight IndentGuidesEven ctermbg=233
  nnoremap <Space>i :IndentGuidesToggle<CR>

  augroup MyAutoCmd
    autocmd BufEnter,FileType * let g:indent_guides_guide_size = &tabstop
  augroup END
endfunction"}}}
unlet bundle

" ------------------------------------
" vim-endwise
" ------------------------------------
let g:endwise_no_mappings = 1

" ------------------------------------
let bundle = NeoBundleGet('jedi-vim')
function! bundle.hooks.on_source(bundle) "{{{
  let g:jedi#auto_initialization      = 1
  let g:jedi#documentation_command    = 'K'
  let g:jedi#goto_assignments_command = ',g'
  let g:jedi#goto_definitions_command = ',d'
  let g:jedi#popup_on_dot             = 0
  let g:jedi#rename_command           = ',R'
  let g:jedi#usages_command           = ',n'
  let g:jedi#use_tabs_not_buffers     = 0
endfunction"}}}
unlet bundle

" ------------------------------------
let bundle = NeoBundleGet('vinarise')
function! bundle.hooks.on_source(bundle) "{{{
  let g:vinarise_objdump_command = 'gobjdump'
endfunction"}}}
unlet bundle

" ------------------------------------
" let bundle = NeoBundleGet('vim-textmanip')
" function! bundle.hooks.on_source(bundle) "{{{
  xmap <C-j> <Plug>(textmanip-move-down)
  xmap <C-k> <Plug>(textmanip-move-up)
  xmap <C-h> <Plug>(textmanip-move-smart-left)
  xmap <C-l> <Plug>(textmanip-move-smart-right)
  " xmap <C-h> <Plug>(textmanip-move-left)
  " xmap <C-l> <Plug>(textmanip-move-right)
" endfunction"}}}
" unlet bundle

" ------------------------------------
" Gundo.vim
" ------------------------------------
nnoremap U :GundoToggle<CR>

" ------------------------------------
" let bundle = NeoBundleGet('accelerated-jk')
" function! bundle.hooks.on_source(bundle) "{{{
nmap <silent>j <Plug>(accelerated_jk_gj)
nmap <silent>k <Plug>(accelerated_jk_gk)
" endfunction"}}}
" unlet bundle

" ------------------------------------
let bundle = NeoBundleGet('alpaca_wordpress.vim')
function! bundle.hooks.on_source(bundle) "{{{
  let g:alpaca_wordpress_syntax = 1
  let g:alpaca_wordpress_use_default_setting = 1
endfunction"}}}
unlet bundle

" ------------------------------------
" excitetranslate
" ------------------------------------
xnoremap E :<C-U>ExciteTranslate<CR>

" ------------------------------------
"  jscomplete-vim
" ------------------------------------
let g:jscomplete_use = ['dom', 'moz', 'ex6th']

" ------------------------------------
let bundle = NeoBundleGet('caw.vim')
function! bundle.hooks.on_source(bundle) "{{{
  nmap gc <Plug>(caw:prefix)
  xmap gc <Plug>(caw:prefix)
  nmap gcc <Plug>(caw:i:toggle)
  xmap gcc <Plug>(caw:i:toggle)
endfunction"}}}
unlet bundle

" ------------------------------------
"  vim-scala
" ------------------------------------
let g:scala_use_default_keymappings = 0

" ------------------------------------
" alpaca_remove_dust
" ------------------------------------
let g:remove_dust_enable = 1
if exists(':RemoveDust')
  augroup RemoveDust
    autocmd!
    autocmd BufWritePre * RemoveDust
  augroup END
endif

" ------------------------------------
" vim-niceblock
" ------------------------------------
xmap I  <Plug>(niceblock-I)
xmap A  <Plug>(niceblock-A)

" ------------------------------------
nnoremap ! :Switch<CR>
let bundle = NeoBundleGet('switch.vim')
function! bundle.hooks.on_source(bundle) "{{{
  "{{{
  let s:switch_definition = {
        \ '*': [
        \   ['is', 'are'],
        \   ['true', 'false'],
        \ ],
        \ 'sass,scss,css' : [
        \   ['solid', 'dotted'],
        \   ['left', 'right'],
        \ ],
        \ 'ruby,eruby,haml' : [
        \   ['if', 'unless'],
        \   ['while', 'until'],
        \   ['.blank?', '.present?'],
        \   ['include', 'extend'],
        \   ['class', 'module'],
        \   ['.inject', '.delete_if'],
        \   ['.map', '.map!'],
        \   ['attr_accessor', 'attr_reader', 'attr_writer'],
        \   ['else', 'elsif'],
        \ ],
        \ 'coffee' : [
        \   ['if', 'unless'],
        \ ],
        \ 'Gemfile,Berksfile' : [
        \   ['=', '<', '<=', '>', '>=', '~>'],
        \ ],
        \ 'ruby.application_template' : [
        \   ['yes?', 'no?'],
        \   ['lib', 'initializer', 'file', 'vendor', 'rakefile'],
        \   ['controller', 'model', 'view', 'migration', 'scaffold'],
        \ ],
        \ 'html,php' : [
        \   { '<!--\([a-zA-Z0-9 /]\+\)--></\(div\|ul\|li\|a\)>' : '</\2><!--\1-->' },
        \ ],
        \ 'rails' : [
        \   [100, ':continue', ':information'],
        \   [101, ':switching_protocols'],
        \   [102, ':processing'],
        \   [200, ':ok', ':success'],
        \   [201, ':created'],
        \   [202, ':accepted'],
        \   [203, ':non_authoritative_information'],
        \   [204, ':no_content'],
        \   [205, ':reset_content'],
        \   [206, ':partial_content'],
        \   [207, ':multi_status'],
        \   [208, ':already_reported'],
        \   [226, ':im_used'],
        \   [300, ':multiple_choices'],
        \   [301, ':moved_permanently'],
        \   [302, ':found'],
        \   [303, ':see_other'],
        \   [304, ':not_modified'],
        \   [305, ':use_proxy'],
        \   [306, ':reserved'],
        \   [307, ':temporary_redirect'],
        \   [308, ':permanent_redirect'],
        \   [400, ':bad_request'],
        \   [401, ':unauthorized'],
        \   [402, ':payment_required'],
        \   [403, ':forbidden'],
        \   [404, ':not_found'],
        \   [405, ':method_not_allowed'],
        \   [406, ':not_acceptable'],
        \   [407, ':proxy_authentication_required'],
        \   [408, ':request_timeout'],
        \   [409, ':conflict'],
        \   [410, ':gone'],
        \   [411, ':length_required'],
        \   [412, ':precondition_failed'],
        \   [413, ':request_entity_too_large'],
        \   [414, ':request_uri_too_long'],
        \   [415, ':unsupported_media_type'],
        \   [416, ':requested_range_not_satisfiable'],
        \   [417, ':expectation_failed'],
        \   [422, ':unprocessable_entity'],
        \   [423, ':precondition_required'],
        \   [424, ':too_many_requests'],
        \   [426, ':request_header_fields_too_large'],
        \   [500, ':internal_server_error'],
        \   [501, ':not_implemented'],
        \   [502, ':bad_gateway'],
        \   [503, ':service_unavailable'],
        \   [504, ':gateway_timeout'],
        \   [505, ':http_version_not_supported'],
        \   [506, ':variant_also_negotiates'],
        \   [507, ':insufficient_storage'],
        \   [508, ':loop_detected'],
        \   [510, ':not_extended'],
        \   [511, ':network_authentication_required'],
        \ ],
        \ 'apache': [
        \   ['None', 'All']
        \ ],
        \ 'c' : [
        \   ['signed', 'unsigned'],
        \ ],
        \ 'css,scss,sass': [
        \   ['collapse', 'separate'],
        \   ['margin', 'padding'],
        \ ],
        \ 'gitrebase' : [
        \   ['pick', 'reword', 'edit', 'squash', 'fixup', 'exec'],
        \   ['^p\s', 'pick '],
        \   ['^r\s', 'reword '],
        \   ['^e', 'edit '],
        \   ['^s', 'squash '],
        \   ['^f', 'fixup '],
        \   ['^e', 'exec '],
        \ ],
        \ 'rspec': [
        \   ['describe', 'context', 'specific', 'example'],
        \   ['before', 'after'],
        \   ['be_true', 'be_false'],
        \   ['get', 'post', 'put', 'delete'],
        \   ['==', 'eql', 'equal'],
        \   { '\.should_not': '\.should' },
        \   ['\.to_not', '\.to'],
        \   { '\([^. ]\+\)\.should\(_not\|\)': 'expect(\1)\.to\2' },
        \   { 'expect(\([^. ]\+\))\.to\(_not\|\)': '\1.should\2' },
        \ ],
        \ 'vim' : [
        \   { '\vhttps{,1}://github.com/([^/]+)/([^/]+)(\.git){,1}': '\1/\2' },
        \   ['call', 'return', 'echo'],
        \   ['NeoBundle', 'NeoBundleLazy'],
        \   { 'let\s\+\([gstb]:\a\+\|\a\+\)\s*\(.\|+\|-\|*\|\\\)\{,1}=\s*\(\a\+\)\s*.*$' : 'unlet \1' },
        \   ['echo', 'echomsg'],
        \   ['if', 'elseif'],
        \ ],
        \ 'markdown' : [
        \   ['[ ]', '[x]'],
        \   ['#', '##', '###', '####', '#####'],
        \   { '\(\*\*\|__\)\(.*\)\1': '_\2_' },
        \   { '\(\*\|_\)\(.*\)\1': '__\2__' },
        \ ]
        \ }
  "}}}

  let s:switch_definition =
        \ alpaca#initialize#redefine_dict_to_each_filetype(s:switch_definition, [])

  function! s:define_switch_mappings() "{{{
    if exists('b:switch_custom_definitions')
      unlet b:switch_custom_definitions
    endif

    if empty(&filetype)
      return
    endif

    let defines = []
    for filetype in split(&ft, '\.')
      if has_key(s:switch_definition, filetype)
        let defines = extend(defines, s:switch_definition[filetype])
      endif
    endfor

    if exists('b:rails_root')
      let defines = extend(defines, s:switch_definition['rails'])
    endif

    if has_key(s:switch_definition, '*')
      let defines = extend(defines, s:switch_definition['*'])
    endif

    if !empty('defines')
      call alpaca#let_b:('switch_custom_definitions', defines)
    endif
  endfunction"}}}

  augroup MyAutoCmd
    autocmd Filetype * call <SID>define_switch_mappings()
  augroup END

  call <SID>define_switch_mappings()
endfunction"}}}
unlet bundle

" ------------------------------------
let bundle = NeoBundleGet('alpaca_tags')
function! bundle.hooks.on_source(bundle) "{{{
  " let g:alpaca_tags_ctags_bin = g:my.bin.ctags
  " let g:alpaca_update_tags_config = {
  let g:alpaca_tags_config = {
        \ '_' : '-R --sort=yes --languages=+Ruby --languages=-js,JavaScript',
        \ 'default' : '--languages=-css,scss,html,js,JavaScript',
        \ 'js' : '--languages=+js',
        \ '-js' : '--languages=-js,JavaScript',
        \ 'vim' : '--languages=+Vim,vim',
        \ 'php' : '--languages=+php',
        \ '-vim' : '--languages=-Vim,vim',
        \ '-style': '--languages=-css,scss,js,JavaScript,html',
        \ 'scss' : '--languages=+scss --languages=-css',
        \ 'css' : '--languages=+css',
        \ 'java' : '--languages=+java $JAVA_HOME/src',
        \ 'ruby': '--languages=+Ruby',
        \ 'coffee': '--languages=+coffee',
        \ '-coffee': '--languages=-coffee',
        \ 'bundle': '--languages=+Ruby',
        \ }
  let g:alpaca_tags_print_to_console = {
        \ 'debug' : 0,
        \ 'setted tags' : 0,
        \ 'created/updated tags' : 1,
        \ }
endfunction"}}}
unlet bundle

" ------------------------------------
function! s:toggle_gitgutter() "{{{
  let is_active = get(g:, 'gitgutter_enabled', 0)

  if is_active
    echomsg 'Gitgutter disabled'
    GitGutterDisable
  else
    echomsg 'Gitgutter enabled'
    GitGutterEnable
  endif
endfunction"}}}

if exists(':GitGutterEnable')
  nnoremap <silent><Space>g :call <SID>toggle_gitgutter()<CR>
endif

" ------------------------------------
let bundle = NeoBundleGet('tern_for_vim')
function! bundle.hooks.on_post_source(bundle) "{{{
  " call tern#Enable()
endfunction"}}}
unlet bundle

" ------------------------------------
let bundle = NeoBundleGet('alpaca_english')
function! bundle.hooks.on_source(bundle) "{{{
  let g:alpaca_english_enable                      = 1
  let g:alpaca_english_max_candidates              = 100
  let g:alpaca_english_enable_duplicate_candidates = 1

  " DEVELOPMENT VERSION
  let g:alpaca_english_web_search_url   = 'http://eow.alc.co.jp/%s/UTF-8/'
  let g:alpaca_english_web_search_xpath = "div[@id='resultsList']/ul/li"
endfunction"}}}
unlet bundle

" ----------------------------------------
" vim-multiple-cursors
" ----------------------------------------
xnoremap <C-N> :<C-U>call multiple_cursors#new('n')<CR>
nnoremap <C-N> :<C-U>call multiple_cursors#new('n')<CR>

" ----------------------------------------
nnoremap <Space>i :<C-U>IndentLinesToggle<CR>

let bundle = NeoBundleGet('indentLine')
function! bundle.hooks.on_source(bundle) "{{{
  let g:indentLine_color_term = 239
  let g:indentLine_fileType = g:my.ft.program_files
  " let g:indentLine_color_gui = '#A4E57E'
  " let g:indentLine_char = 'c'
endfunction"}}}
unlet bundle

" ----------------------------------------
let g:neocomplete#enable_at_startup = 1

let bundle = NeoBundleGet(has('lua') ? 'neocomplete' : 'nothing!!')
function! bundle.hooks.on_source(bundle) "{{{
  let g:neocomplete#auto_completion_start_length      = 3
  let g:neocomplete#sources#syntax#min_keyword_length = 3
  let g:neocomplete#lock_buffer_name_pattern          = '\*ku\*'
  let g:neocomplete#auto_completion_start_length      = g:neocomplete#sources#syntax#min_keyword_length
  " let g:neocomplete#ctags_arguments = g:alpaca_update_tags_config
  let g:neocomplete#data_directory                    = g:my.dir.neocomplete
  let g:neocomplete#enable_auto_close_preview         = 0
  let g:neocomplete#enable_auto_select                = 0
  " let g:neocomplete_caching_limit_file_size = 500000
  " let g:neocomplete_max_keyword_width       = 120
  " let g:neocomplete_enable_cursor_hold_i    = 0
  " let g:neocomplete#enable_smart_case       = 1
  " let g:neocomplete#enable_refresh_always   = 0

  let g:neocomplete#enable_complete_select          = 0
  let g:neocomplete#enable_fuzzy_completion         = 0
  let g:neocomplete#force_overwrite_completefunc    = 1
  let g:neocomplete#manual_completion_start_length  = 0

  let g:neocomplete#sources#buffer#cache_limit_size = 700000
  let g:neocomplete#sources#tags#cache_limit_size   = 1000000
  let g:neocomplete#sources#include#max_proceslses  = 30
  let g:neocomplete#max_list                        = 100
  let g:neocomplete#skip_auto_completion_time       = '0.1'

  let g:neocomplete#disable_auto_select_buffer_name_pattern =
        \ '\[Command Line\]'
  call neocomplete#custom#source('tag', 'disabled', 1)

  if $USER == 'root'
    let g:neocomplete#data_directory = '/tmp'
  endif

  let s:neocomplete_initialize_lists = [
        \ 'neocomplete#sources#include#patterns',
        \ 'neocomplete#sources#omni#functions',
        \ 'neocomplete#sources#omni#input_patterns',
        \ 'neocomplete#force_omni_input_patterns',
        \ 'neocomplete#keyword_patterns',
        \ 'neocomplete#sources#vim#complete_functions',
        \ 'neocomplete#delimiter_patterns',
        \ 'neocomplete#sources#dictionary#dictionaries',
        \ 'neocomplete#sources',
        \ 'neocomplete#text_mode_filetypes',
        \ ]

  for initialize_variable in s:neocomplete_initialize_lists
    call alpaca#let_g:(initialize_variable, {})
  endfor

  let g:neocomplete#text_mode_filetypes = {
        \ 'markdown' : 1,
        \ 'gitcommit' : 1,
        \ 'text' : 1,
        \ }

  let g:neocomplete#sources#omni#functions.java = 'eclim#java#complete#CodeComplete'
  if has('python')
    let g:neocomplete#sources#omni#functions.javascript = 'tern#Complete'
  endif

  let g:neocomplete#keyword_patterns = {
        \ '_' : '[0-9a-zA-Z:#_]\+',
        \ 'c' : '[^.[:digit:]*\t]\%(\.\|->\)',
        \ 'mail' : '^\s*\w\+',
        \ 'perl' : '\h\w*->\h\w*\|\h\w*::',
        \ }

  let g:neocomplete#sources#include#patterns = {
        \ 'scala' : '^import',
        \ 'scss'  : '^\s*\<\%(@import\)\>',
        \ 'php'   : '^\s*\<\%(inlcude\|\|include_once\|require\|require_once\)\>',
        \ }

  let g:neocomplete#sources#omni#input_patterns.php =
        \ '[^. \t]->\%(\h\w*\)\?\|\h\w*::\%(\h\w*\)\?'
  let g:neocomplete#sources#omni#input_patterns.c =
    \ '[^.[:digit:] *\t]\%(\.\|->\)\%(\h\w*\)\?'
  let g:neocomplete#sources#omni#input_patterns.cpp =
    \ '[^.[:digit:] *\t]\%(\.\|->\)\%(\h\w*\)\?\|\h\w*::\%(\h\w*\)\?'

  let g:neocomplete#force_omni_input_patterns.c =
        \ '[^.[:digit:] *\t]\%(\.\|->\)'
  let g:neocomplete#force_omni_input_patterns.cpp =
        \ '[^.[:digit:] *\t]\%(\.\|->\)\|\h\w*::'
  let g:neocomplete#force_omni_input_patterns.objc =
        \ '[^.[:digit:] *\t]\%(\.\|->\)'
  let g:neocomplete#force_omni_input_patterns.objcpp =
        \ '[^.[:digit:] *\t]\%(\.\|->\)\|\h\w*::'

  let g:neocomplete#sources#vim#complete_functions = {
        \ 'Ref' : 'ref#complete',
        \ 'Unite' : 'unite#complete_source',
        \ 'VimShellExecute' :
        \      'vimshell#vimshell_execute_complete',
        \ 'VimShellInteractive' :
        \      'vimshell#vimshell_execute_complete',
        \ 'VimShellTerminal' :
        \      'vimshell#vimshell_execute_complete',
        \ 'VimShell' : 'vimshell#complete',
        \ 'VimFiler' : 'vimfiler#complete',
        \ 'Vinarise' : 'vinarise#complete',
        \}

  let neocomplete#sources#dictionary#dictionaries = {
        \ 'default'             : '',
        \ 'javascript.timobile' : $HOME.'/.vim/dict/timobile.dict',
        \ 'coffee.timobile'     : $HOME.'/.vim/dict/timobile.dict',
        \ 'vimshell' : g:my.dir.vimshell . '/command-history',
        \ }

  for dict in split(glob($HOME.'/.vim/dict/*.dict'))
    let ft = matchstr(dict, '[a-zA-Z0-9.]\+\ze\.dict$')
    let neocomplete#sources#dictionary#dictionaries[ft] = dict
  endfor
  unlet dict
  unlet ft

  augroup MyAutoCmd
    autocmd BufReadPre *
          \ if &previewwindow
          \|  au BufEnter <buffer>
          \|  if &previewwindow
          \|    call alpaca_window#smart_close()
          \|  endif
          \|endif
  augroup END

  imap <expr><C-G> neocomplete#undo_completion()
  imap <expr><TAB> neosnippet#expandable() ? "\<Plug>(neosnippet_expand_or_jump)" : pumvisible() ? neocomplete#complete_common_string() : "\<TAB>"
  inoremap <expr><C-e> neocomplete#cancel_popup()

  function! s:my_crinsert() "{{{
    return neocomplete#close_popup() . "\<CR>"
  endfunction"}}}
  inoremap <silent><CR> <C-R>=<SID>my_crinsert()<CR>
  inoremap <expr><C-h> neocomplete#smart_close_popup()."\<C-h>"
  inoremap <expr><C-X><C-F>  neocomplete#start_manual_complete('file')
  inoremap <expr><C-G>     neocomplete#undo_completion()
  inoremap <expr><C-N>  pumvisible() ? "\<C-N>" : "\<C-X>\<C-U>\<C-P>\<Down>"
  inoremap <expr><C-P>  pumvisible() ? "\<C-P>" : "\<C-P>\<C-N>"
  inoremap <expr><C-@> neocomplete#start_manual_complete(['neosnippet'])

  inoremap <expr><Left>  neocomplete#close_popup() . "\<Left>"
  inoremap <expr><Right> neocomplete#close_popup() . "\<Right>"
  inoremap <expr><Up>    neocomplete#close_popup() . "\<Up>"
  inoremap <expr><Down>  neocomplete#close_popup() . "\<Down>"

  inoremap <expr><TAB>  pumvisible() ? "\<C-n>" :
        \ <SID>check_back_space() ? "\<TAB>" :
        \ neocomplete#start_manual_complete()
  function! s:check_back_space() "{{{
    let col = col('.') - 1
    return !col || getline('.')[col - 1]  =~ '\s'
  endfunction"}}}
endfunction"}}}
unlet bundle

" ----------------------------------------
" echodoc
let g:echodoc_enable_at_startup = 1

" ------------------------------------
" VimFiler "{{{
nnoremap <silent><Space>f  :call <SID>vim_filer_explorer_git()<CR>
nnoremap <silent>,,  :VimFilerBufferDir<CR>
nnoremap <silent>,n  :VimFilerCreate<CR>

function! s:vim_filer_explorer_git() "{{{
  let path = (system('git rev-parse --is-inside-work-tree') == "true\n") ? s:current_git() : '.'
  execute 'VimFiler -explorer' path
endfunction"}}}
command! VimFilerExplorerGit call <SID>vim_filer_explorer_git()

let bundle = NeoBundleGet('vimfiler')
function! bundle.hooks.on_source(bundle) "{{{
  let g:vimfiler_data_directory = g:my.dir.vimfiler
  let g:vimfiler_safe_mode_by_default = 0
  let g:vimfiler_as_default_explorer = 1
  let g:vimfiler_sort_type = 'filename'
  let g:vimfiler_preview_action = ''
  let g:vimfiler_enable_auto_cd= 1
  let g:vimfiler_file_icon = '-'
  let g:vimfiler_readonly_file_icon = 'x'
  let g:vimfiler_tree_closed_icon = '‣'
  let g:vimfiler_tree_leaf_icon = ' '
  let g:vimfiler_tree_opened_icon = '▾'
  let g:vimfiler_marked_file_icon = '✓'
  let g:vimfiler_ignore_pattern = '\v^(\.git|\.)'

  function! s:vimfiler_settings() "{{{
    if !exists('b:vimfiler')
      return
    endif

    setl nonumber
    nmap <buffer><C-J> [unite]
    nmap <buffer><CR>  <Plug>(vimfiler_edit_file)
    nmap <buffer>f     <Plug>(vimfiler_toggle_mark_current_line)
    nnoremap <buffer>b :<C-U>UniteBookmarkAdd<CR>
    nnoremap <buffer><expr>p vimfiler#do_action('preview')
    nnoremap <buffer>v v
    nnoremap <buffer>u :<C-U>Unite file -no-start-insert -buffer-name=file<CR>
  endfunction"}}}

  augroup VimFilerKeyMapping
    autocmd!
    autocmd FileType vimfiler call <SID>vimfiler_settings()
  augroup END
endfunction"}}}
unlet bundle
"}}}

" ----------------------------------------
nnoremap <silent><Space>e   :NeoSnippetEdit -split<CR>
nnoremap <silent>so         :call <SID>open_neosnippet_sources()<CR>
function! s:open_neosnippet_sources() "{{{
  silent! execute 'Unite neosnippet/user neosnippet/runtime -no-start-insert -default-action=neosnippet_source -input=' . s:filetype()
endfunction"}}}

let bundle = NeoBundleGet('neosnippet')
function! bundle.hooks.on_source(bundle) "{{{
  let g:neosnippet#snippets_directory = g:my.dir.snippets
  let g:neosnippet#enable_preview = 1
  " let g:neosnippet#disable_runtime_snippets = {
  "       \ '_' : 1
  "       \ }

  call unite#custom_action('neosnippet/user', 'open', 'neosnippet_source')
  call unite#custom_action('neosnippet/runtime', 'open', 'neosnippet_source')
  imap <silent><C-K>     <ESC>:<C-U>call unite#start(['snippet'], { 'input': expand('<cword>')})<CR>
  imap <silent><C-F>     <Plug>(neosnippet_expand_or_jump)
  smap <silent><C-F>     <Plug>(neosnippet_expand_or_jump)
endfunction "}}}
unlet bundle

" ----------------------------------------
" unite.vim"{{{
" keymappings
nmap [unite] <Nop>
nmap <C-J> [unite]

nnoremap [unite]f               :Unite -buffer-name=file -no-start-insert file_rec:
nnoremap <silent><Space>b       :UniteBookmarkAdd<CR>
nnoremap <silent>[unite]b       :Unite buffer -buffer-name=buffer<CR>
nnoremap <silent>[unite]j       :Unite file_mru -buffer-name=file_mru<CR>
nnoremap <silent>[unite]B       :Unite bookmark -buffer-name=bookmark<CR>
nnoremap <silent>[unite]<C-F>   :UniteGit<CR>

nnoremap <silent>[unite]e       :Unite english_dictionary -buffer-name=english_dictionary<CR>
nnoremap <silent>[unite]x       :Unite english_example -horizontal -buffer-name=example<CR>
nnoremap <silent>[unite]a       :Unite web_search -horizontal -buffer-name=web_search<CR>
nnoremap <silent>[unite]T       :Unite english_thesaurus -horizontal -buffer-name=thesaurus<CR>

nnoremap <silent>g/             :call <SID>unite_with_same_syntax('Unite -buffer-name=line_fast -hide-source-names -horizontal -no-empty -start-insert -no-quit line/fast')<CR>
nnoremap <silent>g*             :call <SID>unite_with_same_syntax('Unite -buffer-name=line_fast -hide-source-names -horizontal -no-empty -start-insert -no-quit line/fast -input=<C-R><C-W>')<CR>

function! s:unite_git_root(...) "{{{
  let git_root = s:current_git()
  let path = empty(a:000) ? '' : a:1
  let absolute_path = s:complement_delimiter_of_directory(git_root) . path

  if isdirectory(absolute_path)
    execute 'Unite -buffer-name=file file_rec/async:'.absolute_path
    lcd `=absolute_path`
    file `='*unite* - ' . path`
  elseif filereadable(absolute_path)
    edit `=absolute_path`
  else
    echomsg path . ' is not exists!'
  endif
endfunction"}}}
function! s:unite_git_complete(arg_lead, cmd_line, cursor_pos) "{{{
  let git_root = s:complement_delimiter_of_directory(s:current_git())
  let files = globpath(git_root, a:arg_lead . '*')
  let file_list = split(files, '\n')
  let file_list = map(file_list, 's:complement_delimiter_of_directory(v:val)')
  let file_list = map(file_list, "substitute(v:val, git_root, '', 'g')")

  return file_list
endfunction "}}}
command! -nargs=? -complete=customlist,s:unite_git_complete UniteGit call <SID>unite_git_root(<f-args>)

" nnoremap <silent>[unite]ra       :<C-U>Unite -buffer-name=rake rake<CR>
nnoremap <silent>[unite]s        :Unite session -buffer-name=session -no-empty<CR>
nnoremap <silent>[unite]/        :Unite history/search -buffer-name=history_search -no-empty<CR>
nnoremap <silent>[unite]:        :Unite history/command -buffer-name=history_command -no-empty<CR>
nnoremap <silent>[unite]h        :Unite help -no-quit -buffer-name=help<CR>
nnoremap <silent>[unite]o        :Unite outline -no-start-insert -horizontal -no-quit -buffer-name=outline -hide-source-names<CR>
nnoremap <silent><expr>[unite]t  ':Unite tags -horizontal -buffer-name=tags -input='.expand("<cword>").'<CR>'
nnoremap <silent><expr>[tag_or_tab]t ':Unite tags -immediately -horizontal -auto-preview -buffer-name=tags -input='.expand("<cword>").'<CR>'

" vim-unite-giti
nnoremap <silent>gl :Unite giti/log -buffer-name=giti_log -no-start-insert -horizontal<CR>
nnoremap <silent>gP :Unite giti/pull_request/base -buffer-name=giti_pull_request -no-start-insert -horizontal<CR>
nnoremap <silent>gs :Unite giti/status -buffer-name=giti_status -no-start-insert -horizontal<CR>
nnoremap <silent>gh :Unite giti/branch_all -buffer-name=giti_branchall -no-start-insert<CR>

function! s:unite_with_same_syntax(cmd) "{{{
  let old_syntax = &syntax

  execute a:cmd

  if !empty(old_syntax)
    execute 'setl syntax=' . old_syntax
  endif
endfunction"}}}

let bundle = NeoBundleGet('unite.vim')
function! bundle.hooks.on_source(bundle) "{{{
  highlight UniteCursorLine ctermbg=236 cterm=none
  let g:unite_cursor_line_highlight='UniteCursorLine'
  let g:unite_data_directory=g:my.dir.unite
  let g:unite_enable_split_vertically=0
  let g:unite_update_time=50
  let g:unite_enable_start_insert=1
  let g:unite_winheight=15

  let g:unite_source_directory_mru_limit = 200
  let g:unite_source_directory_mru_time_format="(%m-%d %H:%M) "
  let g:unite_source_file_mru_time_format="(%m-%d %H:%M) "
  let g:unite_source_file_mru_filename_format=":~:."
  let g:unite_source_file_mru_limit = 300
  let g:unite_source_directory_mru_ignore_pattern = ''

  let g:unite_winheight = 20
  let g:unite_marked_icon = "✓"
  let g:unite_force_overwrite_statusline=1
  let g:unite_source_history_yank_enable = 0
  let s:unite_hooks = {}

  call alpaca#let_g:('unite_source_menu_menus', {})

  call unite#custom_source('file_rec', 'max_candidates', 5000)
  call unite#custom_source('file_rec/async', 'max_candidates', 5000)
  call unite#custom_source('giti/branch_all', 'max_candidates', 5000)
  call unite#custom_source('giti/log', 'max_candidates', 5000)
  call unite#custom_source('line', 'max_candidates', 5000)
  call unite#custom_source('line/fast', 'max_candidates', 5000)
  call unite#custom_source('tag', 'max_candidates', 5000)
  call unite#custom_source('tags', 'max_candidates', 5000)
  let g:giti_git_command = executable('hub') ? 'hub' : 'git'
  let g:giti_log_default_line_count = 500

  augroup MyUniteCmd
    autocmd!
    autocmd FileType unite call <SID>unite_my_settings()
  augroup END

  function! s:unite_my_settings() "{{{
    augroup MyUniteBufferCmd
      autocmd!
      autocmd! * <buffer>
      autocmd BufEnter <buffer> if winnr('$') == 1 |quit| endif
    augroup END

    setl nolist
    if has('gui')
      setl cursorline
    endif
    highlight link uniteMarkedLine Identifier
    highlight link uniteCandidateInputKeyword Statement

    nmap     <silent><buffer>f <Plug>(unite_toggle_mark_current_candidate)
    xmap     <silent><buffer>f <Plug>(unite_toggle_mark_selected_candidates)
    nmap     <silent><buffer><C-H> <Plug>(unite_toggle_transpose_window)
    nmap     <silent><buffer>p <Plug>(unite_toggle_auto_preview)
    nnoremap <silent><buffer><expr>S unite#do_action('split')
    nnoremap <silent><buffer><expr>V unite#do_action('vsplit')
    nnoremap <silent><buffer><expr>,, unite#do_action('vimfiler')
    nnoremap <silent><buffer>C gg0wC
    nnoremap <expr><buffer>re unite#do_action('replace')

    let unite = unite#get_current_unite()
    if unite.source_names == ['grep']
      let unite.buffer_name = 'grep'
    endif
    let buffer_name = unite.buffer_name != '' ? unite.buffer_name : '_'

    if has_key(s:unite_hooks, buffer_name)
      call s:unite_hooks[buffer_name]()
    endif
  endfunction"}}}

  " ----------------------------------------
  " Hooks
  function! s:unite_hooks.file_mru() "{{{
    syntax match uniteSource__FileMru_Dir /.*\// containedin=uniteSource__FileMru contains=uniteSource__FileMru_Time,uniteCandidateInputKeyword nextgroup=uniteSource__FileMru_Dir

    highlight link uniteSource__FileMru_Dir Directory
    highlight link uniteSource__FileMru_Time Comment
    call unite#custom#source('file_mru', 'ignore_pattern', '')
  endfunction"}}}

  function! s:unite_hooks.file() "{{{
    nmap <buffer><Tab> <Plug>(unite_do_default_action)
    syntax match uniteFileDirectory '.*\/'
    highlight link uniteFileDirectory Directory
  endfunction"}}}

  function! s:unite_hooks.line_fast() "{{{
    augroup MyUniteBufferCmd
      call alpaca_window#util#fold_buffer_automatically()
    augroup END
  endfunction"}}}

  function! s:unite_hooks.history_command() "{{{
    setl syntax=vim
  endfunction"}}}

  " grep {{{
  if executable('ag')
    let g:unite_source_grep_command = 'ag'
    let g:unite_source_grep_default_opts = '--nocolor --nogroup'
    let g:unite_source_grep_recursive_opt = ''
  else
    let g:unite_source_grep_command =  'grep'
    let g:unite_source_grep_recursive_opt = '-R'
  endif


  function! s:unite_hooks.grep() "{{{
    nnoremap <expr><buffer>re unite#do_action('replace')

    augroup MyUniteBufferCmd
      call alpaca_window#util#fold_buffer_automatically()
    augroup END
  endfunction"}}}
  "}}}

  function! s:unite_hooks.outline() "{{{
    nnoremap <buffer><C-J> gj

    augroup MyUniteBufferCmd
      call alpaca_window#util#fold_buffer_automatically()
    augroup END
  endfunction"}}}

  " vim-unite-giti {{{
  function! s:unite_hooks.giti_status() "{{{
    " nnoremap <silent><buffer><expr>gM unite#do_action('ammend')
    nnoremap <silent><buffer><expr>ga unite#do_action('stage')
    nnoremap <silent><buffer><expr>gc unite#do_action('checkout')
    nnoremap <silent><buffer><expr>gd unite#do_action('diff')
    nnoremap <silent><buffer><expr>gu unite#do_action('unstage')
  endfunction"}}}

  function! s:unite_hooks.giti_log() "{{{
    nnoremap <silent><buffer><expr>gd unite#do_action('diff')
    nnoremap <silent><buffer><expr>d unite#do_action('diff')
  endfunction"}}}
  "}}}
endfunction"}}}
unlet bundle
"}}}

" ----------------------------------------
let bundle = NeoBundleGet('vim-ruby')
function! bundle.hooks.on_source(bundle) "{{{
  let g:rubycomplete_buffer_loading    = 0
  let g:rubycomplete_classes_in_global = 0
  let g:rubycomplete_rails             = 0
endfunction "}}}
unlet bundle

" ----------------------------------------
let bundle = NeoBundleGet('jekyll.vim')
function! bundle.hooks.on_source(bundle) "{{{
  let g:jekyll_path = s:current_git()
endfunction"}}}
unlet bundle

" ----------------------------------------
let bundle = NeoBundleGet('auto-pairs')
function! bundle.hooks.on_source(bundle) "{{{
  let g:auto_pairs#map_space = 0
  let g:auto_pairs#map_cr = 0
endfunction"}}}
function! bundle.hooks.on_post_source(bundle) "{{{
  call auto_pairs#try_init()
endfunction"}}}
unlet bundle

" ----------------------------------------
" lightline
" ----------------------------------------
"{{{
if has('vim_starting')
  let g:lightline = {
        \ 'colorscheme': 'wombat',
        \ }
endif
"}}}

" ----------------------------------------
let bundle = NeoBundleGet('unite-session')
function! bundle.hooks.on_source(bundle) "{{{
  " let g:unite_source_session_options='blank,buffers,curdir,folds,help,tabpages,winsize'
  let g:unite_source_session_options='buffers,curdir,tabpages'
  let g:unite_source_session_enable_auto_save=0
endfunction"}}}
unlet bundle

" ----------------------------------------
let bundle = NeoBundleGet('beautify.vim')
function! bundle.hooks.on_source(bundle) "{{{
  " let g:beautify#default_outputter = 'tabnew'
  let g:beautify#beautifier#html2haml#ruby19_attributes = 1
endfunction"}}}
unlet bundle

" ----------------------------------------
" alpaca_english
function! s:toggle_spell() "{{{
  if &spell
    setl nospell
    echo 'English mode disabled'
    AlpacaEnglishDisable
    call english#autocollect#load()
  else
    setl spell
    echo 'English mode enabled'
    AlpacaEnglishEnable
    call english#autocollect#unload()
  endif

  nnoremap ;; :<C-U>AlpacaEnglishSay<CR>
  xnoremap ;; :AlpacaEnglishSay<CR>
endfunction"}}}
nnoremap <silent>,s :<C-U>call <SID>toggle_spell()<CR>

" ----------------------------------------
" Other plugin settings {{{
let g:git_aliases#author_name = g:my.info.github
let g:snail_csv2google_sheet_hourly_rete = 2200
" let g:lang8_email_address = 'alprhcp666@gmail.com'
"}}}
"}}}

" ----------------------------------------
function! s:update_ruby_ctags() "{{{
  call alpaca#system_bg('rbenv ctags')
  call alpaca#system_bg('gem ctags')
endfunction"}}}
command! UpdateRubyTags call <SID>update_ruby_ctags()

" ----------------------------------------
" Clean memory {{{
function! s:clear_memory() "{{{
  if exists(':NeoCompleteClean')
    NeoCompleteClean
    NeoCompleteDisable
    NeoCompleteEnable
  endif

  if exists(':TagsCleanCache')
    TagsCleanCache
    TagsSet
    set tags=
  endif

  execute '1,' . bufnr('$') . 'bwipeout'
endfunction "}}}

command! UnwatchBuffer setlocal buftype=nofile nobuflisted noswapfile bufhidden=hide
command! Clean call <SID>clear_memory()
command! CleanSwap call alpaca#system_bg('rm -rf ' . g:my.dir.swap_dir . '/*')
command! CleanAll call alpaca#system_bg('rm -rf ' . g:my.dir.trash_dir . '*')
"}}}

" ----------------------------------------
" Open macvim"{{{
function! s:open_macvim() "{{{
  UniteSessionSave for_mvim
  Clean

  call alpaca#system_bg('mvim -c "UniteSessionLoad for_mvim"')
endfunction"}}}
command! -nargs=0 Mvim call s:open_macvim()

function! s:open_vim() "{{{
  if has('gui')
    UniteSessionSave for_vim
    Clean
  else
    UniteSessionLoad for_vim
  endif
endfunction"}}}
command! -nargs=0 Vim call s:open_vim()
"}}}

" ----------------------------------------
" For lang-8 product {{{
function! s:doautocmd_for_lang8() "{{{
  let pwd = getcwd()

  if pwd =~ 'lang-8'
    let g:neorspec_command = 'Dispatch spec {spec}'
    nnoremap <buffer>[plug]c           :UniteGit config<CR>
    nnoremap <buffer>[plug]j           :UniteGit public/static/javascripts<CR>
    nnoremap <buffer>[plug]a           :UniteGit public/static/sass<CR>
    nnoremap <buffer>[plug]m           :UniteGit app/models/mailer<CR>
  else
    let g:neorspec_command = 'Dispatch rspec {spec}'
  endif
endfunction"}}}

augroup MyAutoCmd
  autocmd User Rails call <SID>doautocmd_for_lang8()
augroup END
"}}}

" for evaluate_text_selected
function! s:get_script_variables() "{{{
  return s:
endfunction"}}}

if !has('vim_starting')
  call neobundle#call_hook('on_source')
endif

set secure