LoginSignup
5
10

More than 5 years have passed since last update.

折角だからVimの設定ファイル置いてみる

Last updated at Posted at 2017-02-09

更新

2018/03/31 スワップファイルとかの設定変更。設定が通らなくて苦労した。あと自作コマンド作った
2018/03/20 Nvimを試して、ついでにプラグインも入れ替え。設定ファイルも分割したので、1から書き換え
2017/12/31 思えばCMDとかPSから使わなきゃならない理由は無かったから、GVimで良かったんだ。これで背景問題は解決だ。GVimの設定も後で追加しよう
2017/12/26 Windowsでのエラーはパス周り変えて、vimrcとNERDTreePluginsのgit_status.vimから環境依存文字を置き換えれば消えた。でもカラースキーマを適用すると変な色になったり背景が白っぽくなるの解消できてない
2017/12/13 プラグインも増えたしdeinとmolokaiのインストールまで自動化(Windowsでは無理)したvimrc。でもWindowsでは大量のエラーを吐いて動かせない
糞雑魚初心者のプラグインとか一切入ってないVimの設定そのまま置いてみる

vimrc(本体)

init.vim(.vimrc)
runtime! /config/*.vim
source $HOME/.config/nvim/commands.vim

set laststatus=2
set ambiwidth=double
syntax on

vimrc(基本設定)

conf.vim(基本設定)
set number
set title
set showmatch
set tabstop=4
set shiftwidth=4
set noexpandtab
set softtabstop=4
set autoindent
set wrap
set showbreak=set breakindent
set breakindentopt=shift:2
set linebreak
set ignorecase
set smartcase
set wrapscan
set fileencoding=utf-8
set fileencodings=utf-8,cp932,euc-jp,shift_jis
set incsearch
set hlsearch
set ruler
set autoread
set matchpairs=(:),{:},[:],<:>
set wildmenu wildmode=longest:full
set cursorline
set clipboard+=unnamed,unnamedplus
autocmd Vimenter,Colorscheme * hi CursorLine cterm=underline
set backspace=2
set list
set listchars=tab:»-,eol:«,trail:set showcmd

if has('nvim')
    set directory=$HOME/.config/nvim/vimfiles/swap
    set backupdir=$HOME/.config/nvim/vimfiles/back
    set undodir=$HOME/.config/nvim/vimfiles/undo
    set viminfo+=n$HOME/.config/nvim/vimfiles/viminfo
else
    set directory=$HOME/.vim/vimfiles/swap
    set backupdir=$HOME/.vim/vimfiles/back
    set undodir=$HOME/.vim/vimfiles/undo
    set viminfo+=n$HOME/.vim/vimfiles/viminfo
endif
"viminfoのみ、ファイル名まで指定してやる必要があるので注意
set swapfile
set backup
set undofile

"molokaiがなければダウンロード
if has('nvim')
    if !filereadable(expand('~/.config/nvim/colors/molokai.vim'))
        call system('mkdir ~/.config/nvim/colors')
        call system('curl 
    https://raw.githubusercontent.com/tomasr/molokai/master/colors/molokai.vim > ~/.config/nvim/colors/molokai.vim')
    endif
else
    if !filereadable(expand('~/.vim/colors/molokai.vim'))
        call system('mkdir ~/.vim/colors')
        call system('curl 
    https://raw.githubusercontent.com/tomasr/molokai/master/colors/molokai.vim > ~/.vim/colors/molokai.vim')
    endif
endif

try
    colorscheme molokai
catch
    colorscheme elflord
endtry

if has('mouse')
    set mouse=a
endif

set t_Co=256

hi Normal ctermbg=none

vimrc(GUI用追加設定)

conf_gui.vim(Gvim向け設定)
if has('gui')
    set guioptions-=T
    set guioptions-=m
    set guioptions-=r
    set guioptions-=R
    set guioptions-=l
    set guioptions-=L

    set guifont=Source_Code_Pro:h10,MigMix_1M:h10,Consolas:h10 guifontwide=MigMix_1M:h10,Consolas:h10

    "メニューと中身の文字化け対策
    let $LANG='ja_jp.utf-8'
    set fileencodings=utf-8,euc-jp,sjis
    source $VIMRUNTIME/delmenu.vim
    set encoding=utf-8
    source$VIMRUNTIME/menu.vim

    "ウィンドウサイズを終了時に保存、起動時に復元
    if has('nvim')
        let g:save_window_file = expand('~/.config/nvim/vimfiles/vimwindow')
    else
        let g:save_window_file = expand('~/.vim/vimfiles/vimwindow')
    endif

    augroup SaveWindow
        autocmd!
        autocmd VimLeavePre * call s:save_window()

        function! s:save_window()
            let options = [
                \ 'set columns=' . &columns,
                \ 'set lines=' . &lines,
                \ 'winpos' . getwinposx() . ' ' .getwinposy(),
            ]
            call writefile(options, g:save_window_file)
        endfunction
    augroup END
    if filereadable(g:save_window_file)
        execute 'source' g:save_window_file
    endif

    "カーソルの設定
    set guicursor=a:blinkon0
    if has('multi_byte_ime')
        highlight Cursor guifg=Black guibg=White
        highlight CursorIM guifg=none guibg=Red
    endif

    let g:nerdtree_tabs_open_on_gui_startup=0

    autocmd FocusGained * set transparency=235
    autocmd FocusLost * set transparency=215
endif

プラグイン管理

dein.vim(deinの設定)
"install dein
if &compatible
    set nocompatible
endif

if has('nvim')
    let s:dein_dir = expand('~/.config/nvim/dein')
    let s:dein_repo_dir = s:dein_dir . '/repos/github.com/Shougo/dein.vim'
else
    let s:dein_dir = expand('~/.vim/dein')
    let s:dein_repo_dir = s:dein_dir . '/repos/github.com/Shougo/dein.vim'
endif

if &runtimepath !~# 'dein.vim'
    if !isdirectory(s:dein_repo_dir)
        execute '!git clone https://github.com/Shougo/dein.vim' s:dein_repo_dir
    endif

    execute 'set runtimepath^=' . fnamemodify(s:dein_repo_dir, ':p')
endif

if dein#load_state(s:dein_dir)
    call dein#begin(s:dein_dir)

    if has('nvim')
        let g:rc_dir = expand('~/.config/nvim')
    else
        let g:rc_dir = expand('~/.vim')
    endif

    let s:toml = g:rc_dir . '/dein/toml/dein.toml'
    let s:lazy_toml = g:rc_dir . '/dein/toml/dein_lazy.toml'

    call dein#load_toml(s:toml, {'lazy':0})
    call dein#load_toml(s:lazy_toml, {'lazy':1})

    call dein#end()
    call dein#save_state()
endif

"起動時に自動でプラグインをチェック・インストール
"if dein#check_install()
"    call dein#install()
"endif

プラグイン設定

dein.toml(プラグインの設定)
[[plugins]] #dein
    repo = 'Shougo/dein.vim'

[[plugins]] #indent guide
    repo = 'nathanaelkane/vim-indent-guides'

    hook_add = '''
        let g:indent_guides_enable_on_vim_startup = 1
        let g:indent_guides_start_level = 2
        let g:indent_guides_color_change_percent = 10
        let g:indent_guides_guide_size = 0
        let g:indent_guides_autocolors = 0
        autocmd Vimenter,Colorscheme * :hi IndentGuidesOdd  guibg=#005500 ctermbg=0
        autocmd Vimenter,Colorscheme * :hi IndentGuidesEven guibg=#000055 ctermbg=235
    '''

[[plugins]]
    repo = 'osyo-manga/vim-over'

[[plugins]] #git cmd
    repo = 'tpope/vim-fugitive'

[[plugins]] #check syntax
    repo = 'vim-syntastic/syntastic'

[[plugins]] #Trailing WhiteSpace
    repo = 'bronson/vim-trailing-whitespace'

    hook_add = '''
        let g:extra_whitespace_ignored_filetypes = ['unite']
        autocmd BufWritePre * :FixWhitespace
    '''

[[plugins]] #view git status
    repo = 'airblade/vim-gitgutter'

    hook_add = '''
        let g:gitgutter_highlight_lines = 1
        set updatetime=250
        let g:gitgutter_sign_added = '✚'
        let g:gitgutter_sign_modified = '➤'
        let g:gitgutter_sign_removed = '✘'
        let g:gitgutter_sign_modified_removed = "➜"
        autocmd Vimenter,Colorscheme * :hi GitGutterAddLine ctermfg=none ctermbg=17
        autocmd Vimenter,Colorscheme * :hi GitGutterChangeLine ctermfg=none ctermbg=53
        autocmd Vimenter,Colorscheme * :hi GitGutterDeleteLine ctermfg=none ctermbg=52
        autocmd Vimenter,Colorscheme * :hi GitGutterChangeDeleteLine ctermfg=none ctermbg=53

        let g:NERDTreeIndicatorMapCustom = {
            \ "Modified"  : "➤",
            \ "Staged"    : "✚",
            \ "Untracked" : "✭",
            \ "Renamed"   : "➜",
            \ "Unmerged"  : "═",
            \ "Deleted"   : "✖",
            \ "Dirty"     : "✗",
            \ "Clean"     : "✔︎",
            \ 'Ignored'   : '☒',
            \ "Unknown"   : "?"
        \ }
    '''

[[plugins]] #lightline
    repo = 'itchyny/lightline.vim'

    hook_add = '''
        let g:lightline = {
            \ 'colorscheme': 'molokai',
            \ 'mode_map': {'c': 'NORMAL'},
            \ 'active': {
                \ 'left': [
                    \ ['mode', 'paste'],
                    \ ['fugitive', 'gitgutter', 'filename'],
                \ ],
            \ 'right': [
                \ ['lineinfo', 'syntastic'],
                \ ['percent'],
                \ ['fileencoding', 'filetype'],
            \ ]
        \ },
        \ 'component_function': {
            \ 'modified': 'MyModified',
            \ 'readonly': 'MyReadonly',
            \ 'fugitive': 'MyFugitive',
            \ 'filename': 'MyFilename',
            \ 'fileformat': 'MyFileformat',
            \ 'filetype': 'MyFiletype',
            \ 'fileencoding': 'MyFileencoding',
            \ 'mode': 'MyMode',
            \ 'syntastic': 'SyntasticStatuslineFlag',
            \ 'charcode': 'MyCharCode',
            \ 'gitgutter': 'MyGitGutter',
        \ },
        \ 'separator': {'left': '', 'right': ''},
            \ 'subseparator': {'left': '>', 'right': '<'}
        \ }

        function! MyModified()
            return &ft =~ 'help\|vimfiler\|gundo' ? '' : &modified ? '➜' : &modifiable ? '' : '-'
        endfunction

        function! MyReadonly()
            return &ft !~? 'help\|vimfiler\|gundo' && &ro ? '⚠' : ''
        endfunction

        function! MyFilename()
            return ('' != MyReadonly() ? MyReadonly() . ' ' : '') .
                \ (&ft == 'vimfiler' ? vimfiler#get_status_string() :
                \  &ft == 'unite' ? unite#get_status_string() :
                \  &ft == 'vimshell' ? substitute(b:vimshell.current_dir,expand('~'),'~','') :
                \ '' != expand('%:t') ? expand('%:t') : '[No Name]') .
                \ ('' != MyModified() ? ' ' . MyModified() : '')
        endfunction

        function! MyFugitive()
            try
                if &ft !~? 'vimfiler\|gundo' && exists('*fugitive#head')
                    let _ = fugitive#head()
                    return strlen(_) ? '@'._ : ''
                endif
            catch
            endtry
            return ''
        endfunction

        function! MyFileformat()
            return winwidth('.') > 70 ? &fileformat : ''
        endfunction

        function! MyFiletype()
            return winwidth('.') > 70 ? (strlen(&filetype) ? &filetype : 'no ft') : ''
        endfunction

        function! MyFileencoding()
            return winwidth('.') > 70 ? (strlen(&fenc) ? &fenc : &enc) : ''
        endfunction

        function! MyMode()
            return winwidth('.') > 60 ? lightline#mode() : ''
        endfunction

        function! MyGitGutter()
            if ! exists('*GitGutterGetHunkSummary')
                \ || ! get(g:, 'gitgutter_enabled', 0)
                \ || winwidth('.') <= 90
                return ''
            endif
            let symbols = [
                \ '✚',
                \ '➤',
                \ '✘'
            \ ]
            let hunks = GitGutterGetHunkSummary()
            let ret = []
            for i in [0, 1, 2]
                if hunks[i] > 0
                    call add(ret, symbols[i] . hunks[i])
                endif
            endfor
            return join(ret, ' ')
        endfunction

        " https://github.com/Lokaltog/vim-powerline/blob/develop/autoload/Powerline/Functions.vim
        function! MyCharCode()
            if winwidth('.') <= 70
                return ''
            endif

            " Get the output of :ascii
            redir => ascii
            silent! ascii
            redir END

            if match(ascii, 'NUL') != -1
                return 'NUL'
            endif

            " Zero pad hex values
            let nrformat = '0x%02x'

            let encoding = (&fenc == '' ? &enc : &fenc)

            if encoding == 'utf-8'
                " Zero pad with 4 zeroes in unicode files
                let nrformat = '0x%04x'
            endif

            " Get the character and the numeric value from the return value of :ascii
            " This matches the two first pieces of the return value, e.g.
            " "<F>  70" => char: 'F', nr: '70'
            let [str, char, nr; rest] = matchlist(ascii, '\v\<(.{-1,})\>\s*([0-9]+)')

            " Format the numeric value
            let nr = printf(nrformat, nr)

            return "'". char ."' ". nr
        endfunction
    '''

遅延起動するプラグイン

dein_lazy.toml
[[plugins]]
    repo = 'cohama/lexima.vim'
    on_i = 1

#[[plugins]] #load autoclose when type=insert
#    repo = 'Townk/vim-autoclose'

[[plugins]] #load complete when type=insert & has python3
    repo = 'Shougo/deoplete.nvim'
    if = '''has('python3')'''
    if = '''has('timers')'''

    hook_add = '''
        let g:deoplete#enable_at_startup = 1

        "C-j/kで候補移動
        inoremap <expr><C-j> pumvisible() ? "\<C-n>" : "\<C-j>"
        inoremap <expr><C-k> pumvisible() ? "\<C-p>" : "\<C-k>"

        if has('conceal')
            set conceallevel=2 concealcursor=niv
        endif
    '''

[[plugins]]
    repo = 'roxma/nvim-yarp'
    if = '''!has('nvim')'''
    on_source = ['deoplete']

[[plugins]]
    repo = 'roxma/vim-hug-neovim-rpc'
    if = '''!has('nvim')'''
    on_source = ['deoplete']

[[plugins]]
    repo = 'Shougo/neco-vim'
    on_source = ['deoplete']

[[plugins]]
    repo = 'Shougo/neco-syntax'
    on_source = ['deoplete']

[[plugins]]
    repo = 'Shougo/neco-look'
    on_source = ['deoplete']

[[plugins]] #load complete when type=insert & !has python3 & has lua
    repo = 'Shougo/neocomplete.vim'
    on_i = 1
    if = '''!has('python3')'''
    if = '''has('lua')'''

    hook_add = '''
        "C-j/kかTab/S-Tabで候補移動
        inoremap <expr><C-j> pumvisible() ? "\<C-n>" : "\<C-j>"
        inoremap <expr><C-k> pumvisible() ? "\<C-p>" : "\<C-k>"
        imap <expr><TAB> pumvisible() ? "<C-n>" : neosnippet#jumpable() ? "<Plug>(neosnippet_expand_or_jump)" : "<TAB>"
        imap <expr><S-TAB> pumvisible() ? "<C-p>" : neosnippet#jumpable() ? "<Plug>(neosnippet_expand_or_jump)" : "<S-TAB>"

        "CRで候補確定・展開
        imap <expr><CR> neosnippet#expandable() ? "<Plug>(neosnippet_expand_or_jump)" : pumvisible() ? "<C-y>" : "<CR>"

        if has('conceal')
            set conceallevel=2 concealcursor=niv
        endif
    '''


[[plugins]] #load toml syntax when filetype=toml
    repo = 'cespare/vim-toml'
    on_ft = ['toml']

[[plugins]] #comment out
    repo = 'tyru/caw.vim'
    on_map = ['<Plug>(caw:hatpos:toggle)']

[[plugins]] #load nerdtree when called
    repo = 'scrooloose/nerdtree'
    on_cmd = ['NERDTree']
    on_cmd = ['NERDTreeToggle']

    hook_add='''
        let g:NERDTreeIgnore = ['\.swp$', '\.meta$']
        let g:NERDTreeQuitOnOpen = 1
    '''

[[plugins]] #call NT tab with NT
    repo = 'jistr/vim-nerdtree-tabs'
    on_source = ['NERDTree']

[[plugins]] #call NT git with NT
    repo = 'Xuyuanp/nerdtree-git-plugin'
    on_source = ['NERDTree']

[[plugins]] #undo graph
    repo = 'sjl/gundo.vim'
    if = '''has('python')'''
    on_cmd = ['GundoToggle']

    hook_add = '''
        let g:gundo_width = 30
        let g:gundo_help = 0
        let g:gundo_preview_bottom = 1
        "let g:gundo_preview_height = 10
        let g:gundo_preview_statusline = 1
        let g:gundo_tree_statusline = 1
        let g:gundo_return_on_revert = 0
    '''

キーマップ

keymap.vim
"割当削除
noremap <Space> <Nop>
noremap s <Nop>
noremap <BS> <Nop>
noremap <CR> <Nop>

"ハイライト切り替え
nnoremap @ :noh<CR>

"カーソル操作
noremap K H
noremap J L
noremap H ^
noremap L $
noremap mj zb
noremap mm zz
noremap mk zt

"Wで前の単語に移動
noremap W b

"ページ操作
noremap <C-Up> <C-u>
noremap <C-k> <C-u>
noremap <C-Down> <C-d>
noremap <C-j> <C-d>

"ペースト時にインデント崩れを防止
nnoremap p :set paste<CR><ESC>p:set nopaste<CR><ESC>

"タブ操作
nnoremap ta :tabe<CR>
nnoremap tc :tabc<CR>
nnoremap tl :tabn<CR>
nnoremap th :tabN<CR>

"スプリット操作
nnoremap ss :split<CR>
nnoremap sv :vsplit<CR>
nnoremap sh <C-w>h
nnoremap sj <C-w>j
nnoremap sk <C-w>k
nnoremap sl <C-w>l

"s+Shift(h j k l)でスプリットの場所を移動、rで回転
nnoremap s<S-h> <C-w>H
nnoremap s<S-j> <C-w>J
nnoremap s<S-k> <C-w>K
nnoremap s<S-l> <C-w>L
nnoremap s<S-r> <C-w>r

"(- = + _)ででスプリットサイズを変更
nnoremap - <C-w><C-->
nnoremap = <C-w><C-+>
nnoremap + <C-w><C->>
nnoremap _ <C-w><C-<>

nnoremap <S-u> <C-r>
"Ctrl+uで変更を取り消し
nnoremap <C-u> <S-u>
"?で置換開始
nnoremap ? :%s///

"ビジュアルでCtrl+uで大文字小文字反転
vnoremap <C-u> ~

"1行削除して詰める
noremap <S-x> <S-v>x

"visualで選択した文字を*で検索
vnoremap * "zy:let @/ = @z<CR>n

"visualでCtrl+y/pでクリップボードにコピー/ペースト
vnoremap <C-y> "*y
vnoremap <C-p> "*p

noremap ; :
noremap : ;

"[/]<CR>で宣言元/元の場所に移動
noremap [<CR> [<C-i>
noremap ]<CR> <C-o>

"Qをマクロ用に
nnoremap Q @
nnoremap QQ @@

"Ctrl+/でコメントアウト
nmap <C-_> <Plug>(caw:hatpos:toggle)
vmap <C-_> <Plug>(caw:hatpos:toggle)

noremap <C-e> :NERDTreeToggle<CR>

nnoremap # :GundoToggle<CR>

自作コマンド

commands.vim
"開いているファイルのUndoファイルを削除
command! RmUndoFile call RemoveUndoFile()
function! RemoveUndoFile()
    let g:UndoFile = expand('%')
    let g:UndoFileName = fnamemodify(g:UndoFile, ":t")

    if strlen(g:UndoFileName)!=0
        let g:RemoveUndoFile = "rm ~/.config/nvim/vimfiles/undo/*\%" . g:UndoFileName
        echo g:RemoveUndoFile
        call system(g:RemoveUndoFile)
    else
        echo 'Target is nothing'
    endif
endfunction

"開いているファイルのBackupファイルを削除
command! RmBackupFile call RemoveBackupFile()
function! RemoveBackupFile()
    let g:BackupFile = expand('%')
    let g:BackupFileName = fnamemodify(g:BackupFile, ":t")

    if strlen(g:BackupFileName)!=0
        let g:RemoveBackupFile = "rm ~/.config/nvim/vimfiles/back/" . g:BackupFileName . "\~"
        echo g:RemoveBackupFile
        call system(g:RemoveBackupFile)
    else
        echo 'Target is nothing'
    endif
endfunction

"開いているファイルのSwapファイルを削除(異常終了した後とかに使う用
command! RmSwapFile call RemoveSwapFile()
function! RemoveSwapFile()
    let g:SwapFile = expand('%')
    let g:SwapFileName = fnamemodify(g:SwapFile, ":t")

    if strlen(g:SwapFileName)!=0
        let g:RemoveSwapFile = "rm ~/.config/nvim/vimfiles/swap/" . g:SwapFileName . ".swp"
        echo g:RemoveSwapFile
        call system(g:RemoveSwapFile)
    else
        echo 'Target is nothing'
    endif
endfunction

参考

申し訳ないけどもう覚えてない…なんか色々

5
10
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
10