脱秀丸。そしてvimへ……

会社のデスクトップがWindowsからLinuxになるかもしれないとのことで、慣れるためにテキストエディタ秀丸からvimに変えてみた。


オリジナルではなくKaoriYa版をインストール。gvimを常用することにした。
そしてサーバで使ってたvim 6.3の.vimrcをベースに色々付け加えて一通りのカスタマイズ完了。
というわけでメモも兼ねてお約束の.vimrc晒し。


設定内容新しくしたエントリ → .vimrc/.gvimrc晒し - ぱせらんメモ

.vimrc

"全般
set nocompatible
set viminfo+=!   "yankring用に!を追加
"set shellslash   "パス区切りをスラッシュにする
set lazyredraw
set t_Co=256
"colorscheme rdark
colorscheme desert

"Low-Contrast Color Schemes
"http://www.vim.org/scripts/script.php?script_id=1448

"rdark
"http://www.vim.org/scripts/script.php?script_id=1732

"ChocolateLiquor
"http://www.vim.org/scripts/script.php?script_id=592

"Tab関係
"tabstop(ts) Tab文字を画面上で何文字に展開するか
set tabstop=4
"shiftwidth(sw) インデントの幅
set shiftwidth=4
"softtabstop(sts) Tabキーを押したときに挿入される空白の量
set softtabstop=0
"expandtab(et) Tab文字を空白に展開
"set expandtab

"入力関係
set backspace=indent,eol,start  "BSでなんでも消せるようにする
set formatoptions+=mM           "整形オプションにマルチバイト系を追加
set autoindent
set smartindent

"コマンド補完
set wildmenu
set wildmode=list:full
set completeopt=menu,preview,menuone

"検索関係
set incsearch    "インクリメンタルサーチ
set nowrapscan   "ラップしない
set ignorecase   "大文字小文字無視
set smartcase    "大文字で始めたら大文字小文字を区別する

"表示関係
set number       "行番号表示
"set ruler        "ルーラー表示(ステータスライン変えてるから意味ない)
set title        "ウィンドウのタイトルを書き換える
set cursorline   "カーソル行を強調表示

"ポップアップのカラー
hi Pmenu ctermbg=darkgray guibg=darkgray
hi PmenuSel ctermbg=brown ctermfg=white guibg=brown guifg=white
hi PmenuSbar ctermbg=black guibg=black

"特殊文字(SpecialKey)の見える化
set list
set listchars=tab:>.,trail:_,nbsp:%,extends:>,precedes:<
highlight SpecialKey term=underline ctermfg=darkgray guifg=darkgray

"カーソル下の文字コード
"http://vimwiki.net/?tips%2F98
function! Getb()
  let c = matchstr(getline('.'), '.', col('.') - 1)
  let c = iconv(c, &enc, &fenc)
  return String2Dec(c)
endfunction
function! GetB()
  let c = matchstr(getline('.'), '.', col('.') - 1)
  let c = iconv(c, &enc, &fenc)
  return String2Hex(c)
endfunction
" :help eval-examples
" The function Nr2Hex() returns the Hex string of a number.
func! Nr2Hex(nr)
  let n = a:nr
  let r = ""
  while n
    let r = '0123456789ABCDEF'[n % 16] . r
    let n = n / 16
  endwhile
  return r
endfunc
" The function String2Hex() converts each character in a string to a two
" character Hex string.
func! String2Hex(str)
  let out = ''
  let ix = 0
  while ix < strlen(a:str)
    let out = out . Nr2Hex(char2nr(a:str[ix]))
    let ix = ix + 1
  endwhile
  return out
endfunc
func! String2Dec(str)
  let out = ''
  let ix = 0
  while ix < strlen(a:str)
    if ix == 1
      let out = out . ','
    endif
    let out = out . printf('%3d', char2nr(a:str[ix]))
    let ix = ix + 1
  endwhile
  return out
endfunc

"ステータスライン関係
set laststatus=2 "ステータスラインを常に表示
"set statusline=%y=[%{&fileencoding}][\%{&fileformat}]\ %F%m%r%=<%c:%l>
"ファイルパス [filetype][fenc][ff]    桁(ASCII=10進数,HEX=16進数) 行/全体(位置)[修正フラグ]
set statusline=%<%F\ %r%h%w%y%{'['.(&fenc!=''?&fenc:&enc).']['.&ff.']'}%=%4v(ASCII=%{Getb()},HEX=%{GetB()})\ %l/%L(%P)%m

"入力モード時、ステータスラインのカラーを変更
augroup InsertHook
autocmd!
autocmd InsertEnter * highlight StatusLine ctermfg=black ctermbg=white guifg=#2E4340 guibg=#ccdc90
autocmd InsertLeave * highlight StatusLine ctermfg=black ctermbg=lightgray guifg=black guibg=#c2bfa5
augroup END

"エンコーディング関係
set fileformat=unix
set fileformats=unix,dos,mac
if has('win32')
  set encoding=cp932
else
  set encoding=utf-8
  set termencoding=utf-8
endif
set fileencoding=utf-8
"set fileencodings=iso-2022-jp,cp932,euc-jp,utf-8,utf-16,ucs-2-internal,ucs-2

"文字コードの自動認識
"http://www.kawaz.jp/pukiwiki/?vim#content_1_7
if &encoding !=# 'utf-8'
  set encoding=japan
  set fileencoding=japan
endif
if has('iconv')
  let s:enc_euc = 'euc-jp'
  let s:enc_jis = 'iso-2022-jp'
  " iconvがeucJP-msに対応しているかをチェック
  if iconv("\x87\x64\x87\x6a", 'cp932', 'eucjp-ms') ==# "\xad\xc5\xad\xcb"
    let s:enc_euc = 'eucjp-ms'
    let s:enc_jis = 'iso-2022-jp-3'
  " iconvがJISX0213に対応しているかをチェック
  elseif iconv("\x87\x64\x87\x6a", 'cp932', 'euc-jisx0213') ==# "\xad\xc5\xad\xcb"
    let s:enc_euc = 'euc-jisx0213'
    let s:enc_jis = 'iso-2022-jp-3'
  endif
  " fileencodingsを構築
  if &encoding ==# 'utf-8'
    let s:fileencodings_default = &fileencodings
    let &fileencodings = s:enc_jis .','. s:enc_euc .',cp932'
    let &fileencodings = &fileencodings .','. s:fileencodings_default
    unlet s:fileencodings_default
  else
    let &fileencodings = &fileencodings .','. s:enc_jis
    set fileencodings+=utf-8,ucs-2le,ucs-2
    if &encoding =~# '^\(euc-jp\|euc-jisx0213\|eucjp-ms\)$'
      set fileencodings+=cp932
      set fileencodings-=euc-jp
      set fileencodings-=euc-jisx0213
      set fileencodings-=eucjp-ms
      let &encoding = s:enc_euc
      let &fileencoding = s:enc_euc
    else
      let &fileencodings = &fileencodings .','. s:enc_euc
    endif
  endif
  " 定数を処分
  unlet s:enc_euc
  unlet s:enc_jis
endif
" 日本語を含まない場合は fileencoding に encoding を使うようにする
if has('autocmd')
  function! AU_ReCheck_FENC()
    if &fileencoding =~# 'iso-2022-jp' && search("[^\x01-\x7e]", 'n') == 0
      let &fileencoding=&encoding
    endif
  endfunction
  autocmd BufReadPost * call AU_ReCheck_FENC()
endif

" □とか○の文字があってもカーソル位置がずれないようにする
if exists('&ambiwidth')
  " 一部のUCS文字の幅を自動計測して決める
  if has('kaoriya')
    set ambiwidth=auto
  else
    set ambiwidth=double
  endif
endif

"ファイルタイプ関係
syntax on           "シンタックスハイライト
filetype indent on  "ファイルタイプによるインデントを行う
filetype plugin on  "ファイルタイプによるプラグインを使う

"バックアップファイル, スワップファイル
if has('win32')
  "set backupext=.bak
  set backupdir=D:/temp/vim_backup
  set directory=D:/temp/vim_backup
else
  set backupdir=~/vim_backup
  set directory=~/vim_backup
endif

"操作関係
set scrolloff=5     "スクロール時に表示を5行確保

"Ctrl+上下で5行ずつ移動
map <C-Up> <Up><Up><Up><Up><Up>
imap <C-Up> <Up><Up><Up><Up><Up>
map <C-Down> <Down><Down><Down><Down><Down>
imap <C-Down> <Down><Down><Down><Down><Down>

"フレームサイズをテンキーの+-で変更する
map <kPlus> <C-W>+
map <kMinus> <C-W>-

"タブ切り替え
nnoremap <C-Tab>   gt
nnoremap <C-S-Tab> gT

"マウス関係
"set mouse=a
"set ttymouse=xterm2

"set tags=tags       "タグファイル
set grepprg=internal "内蔵grepを使う


"========== プラグイン設定 ==========

"autocomplpop
"http://www.vim.org/scripts/script.php?script_id=1879
autocmd FileType * let g:AutoComplPop_CompleteOption='.,w,b,u,t,i'
autocmd FileType php let g:AutoComplPop_CompleteOption='.,w,b,u,t,k$VIM/vimfiles/dict/php.dict'
"補完候補を出したまま改行できるようにする
inoremap <expr> <CR> pumvisible() ? "\<C-Y>\<CR>" : "\<CR>"

"PHP辞書
"http://www.asahi-net.or.jp/~wv7y-kmr/memo/vim_php.html

"taglist
"http://www.vim.org/scripts/script.php?script_id=273
if has('win32')
  let Tlist_Ctags_Cmd="ctags.exe"
else
  let Tlist_Ctags_Cmd="ctags"
endif
let Tlist_Show_One_File=1
let Tlist_Exit_OnlyWindow=1
let Tlist_Use_Right_Window=1
map <silent> <leader>tl :TlistToggle<CR>

"bufexplorer
"http://www.vim.org/scripts/script.php?script_id=42
map <silent> <leader>bl :BufExplorer<CR>

"winmanager
"http://www.vim.org/scripts/script.php?script_id=95
let g:bufExplorerOpenMode=1
let g:bufExplorerSplitBelow=1
let g:bufExplorerSplitType=15

map <C-w><C-f> :FirstExplorerWindow<CR>
map <C-w><C-b> :BottomExplorerWindow<CR>
map <C-w><C-t> :WMToggle<CR>

let g:winManagerWindowLayout = 'FileExplorer|BufExplorer|TagList'

"matchit
:source $VIMRUNTIME/macros/matchit.vim

"mru.vim
"http://www.vim.org/scripts/script.php?script_id=521
let MRU_Max_Entries=20

"smooth-scroll.vim
"http://www.vim.org/scripts/script.php?script_id=1601
nmap <PageDown> <C-F>
nmap <PageUp> <C-B>

"Align.vim
"http://www.vim.org/scripts/script.php?script_id=294

"surround.vim
"http://www.vim.org/scripts/script.php?script_id=1697

"eregex.vim
"http://www.vector.co.jp/soft/unix/writing/se265654.html

"vcscommand.vim
"http://www.vim.org/scripts/script.php?script_id=90

"yankring.vim
"http://www.vim.org/scripts/script.php?script_id=1234

"svn-diff.vim
"http://www.vim.org/scripts/script.php?script_id=978

"grep.vim
"http://www.vim.org/scripts/script.php?script_id=311

"phpmanual.vim
"http://www.asahi-net.or.jp/~wv7y-kmr/tools/phpmanual.html

"monday.vim
"http://www.vim.org/scripts/script.php?script_id=1046

"commentout.vim
"http://nanasi.jp/articles/vim/commentout_source.html

"Chalice
"http://www.kaoriya.net/
set runtimepath+=$VIM/vimfiles/chalice


"========== プライベートな拡張 ==========

"memo
function! Memo()
  if has('win32')
    :split D:/memo.lst
  else
    :split ~/memo.lst
  endif
endf
command! Memo :call Memo()

.gvimrc

"全般
set t_Co=256
"colorscheme rdark
colorscheme desert

"Low-Contrast Color Schemes
"http://www.vim.org/scripts/script.php?script_id=1448

"rdark
"http://www.vim.org/scripts/script.php?script_id=1732

"ChocolateLiquor
"http://www.vim.org/scripts/script.php?script_id=592

"ポップアップのカラー
hi Pmenu ctermbg=darkgray guibg=darkgray
hi PmenuSel ctermbg=brown ctermfg=white guibg=brown guifg=white
hi PmenuSbar ctermbg=black guibg=black

"特殊文字(SpecialKey)の見える化。listcharsはlcsでも設定可能。
"trailは行末スペース。
set list
set listchars=tab:>.,trail:_,nbsp:%,extends:>,precedes:<
highlight SpecialKey term=underline ctermfg=darkgray guifg=darkgray

"81桁目以降を強調表示
"hi over80column guibg=dimgray
"match over80column /.\%>81v/

"ウィンドウ関係
set columns=160
set lines=70
set cmdheight=2  "コマンドラインの高さ(GUI使用時)
winpos 70 70
if has('win32')
  set guifont=MS_Gothic:h10:cSHIFTJIS
endif

"マウス関係
set mouse=a
" マウスの移動でフォーカスを自動的に切替えない (mousefocus:切替る)
set nomousefocus
" 入力時にマウスポインタを隠す (nomousehide:隠さない)
set mousehide

"IME関係
if has('multi_byte_ime') || has('xim')
  " IME ON時のカーソルの色を設定
  highlight CursorIM guibg=lightgreen guifg=NONE
  " 挿入モード・検索モードでのデフォルトのIME状態設定
  set iminsert=0 imsearch=0
endif

"URLをブラウザで開く
"Chaliceからfunction拝借
"let BrowserPath = 'C:\Program Files\Mozilla Firefox\firefox.exe'
function! AL_execute(cmd)
  if 0 && exists('g:AL_option_nosilent') && g:AL_option_nosilent != 0
    execute a:cmd
  else
    silent! execute a:cmd
  endif
endfunction

function! s:AL_open_url_win32(url)
  let url = substitute(a:url, '%', '%25', 'g')
  if url =~# ' '
    let url = substitute(url, ' ', '%20', 'g')
    let url = substitute(url, '^file://', 'file:/', '')
  endif
  " If 'url' has % or #, all of those characters are expanded to buffer name
  " by execute().  Below escape() suppress this.  system() does not expand
  " those characters.
  let url = escape(url, '%#')
  " Start system related URL browser
  if !has('win95') && url !~ '[&!]'
    " for Win NT/2K/XP
    call AL_execute('!start /min cmd /c start ' . url)
    " MEMO: "cmd" causes some side effects.  Some strings like "%CD%" is
    " expanded (may be environment variable?) by cmd.
  else
    " It is known this rundll32 method has a problem when opening URL that
    " matches http://*.html.  It is better to use ShellExecute() API for
    " this purpose, open some URL.  Command "cmd" and "start" on NT/2K?XP
    " does this.
    call AL_execute("!start rundll32 url.dll,FileProtocolHandler " . url)
  endif
endfunction

function! Browser()
    let line0 = getline(".")
    let line = matchstr(line0, "http[^ ]*")
    if line==""
      let line = matchstr(line0, "ftp[^ ]*")
    endif
    if line==""
      let line = matchstr(line0, "file[^ ]*")
    endif
"    exec ":silent !start \"" . g:BrowserPath . "\" \"" . line . "\""
    call s:AL_open_url_win32(line)
endfunction
map <Leader>w :call Browser()<CR>

プラグイン

.vimrc中にも書いてあるけど改めて。

autocomplpop.vim

http://www.vim.org/scripts/script.php?script_id=1879
入力補完をリアルタイムにポップアップ表示してくれるプラグイン
ファイルタイプと組み合わせて設定すればプログラム言語に合わせた入力補完ができて便利。
ただ挿入モード時にカーソル移動してると引っかかるのが玉に瑕。入力したときだけポップアップするようにできないかなぁ。


下記のサイトを参考に若干改造をした。
http://blog.blueblack.net/item_164

ちなみにPHP辞書の作り方はこちら。
http://www.asahi-net.or.jp/~wv7y-kmr/memo/vim_php.html

phpmanual.vim

http://www.asahi-net.or.jp/~wv7y-kmr/tools/phpmanual.html
rubyのrefe.vimみたいにPHPのマニュアルをすぐに引けるプラグイン
ただしWindowsで使うにはwgetやらw3mやらも用意しないと行けないので少し面倒くさい。

taglist.vim

http://www.vim.org/scripts/script.php?script_id=273
関数や変数の一覧を別ウィンドウで表示するプラグイン。ctagsが必要。

bufexplorer.vim

http://www.vim.org/scripts/script.php?script_id=42
バッファの一覧を表示するプラグイン。:lsよりも便利。

winmanager.vim

http://www.vim.org/scripts/script.php?script_id=95
ディレクトリのファイル一覧、バッファ一覧、タグ一覧を別ウィンドウで表示できるプラグイン。テラ便利。

mru.vim

http://www.vim.org/scripts/script.php?script_id=521
Most Recently Used……つまり「最近開いたファイル」ってやつ。

smooth-scroll.vim

http://www.vim.org/scripts/script.php?script_id=1601
C-U, C-D, C-F, C-Bなんかでスムーススクロールを実現してくれるプラグイン
ぱぱっと切り替わると一瞬どっちにスクロールしたのかわからなくなる人にお勧め。


下記のサイトを参考にcursorlineが有効なときの改造をした。
http://blog.blueblack.net/item_219

Align.vim

http://www.vim.org/scripts/script.php?script_id=294
テキスト整形をやってくれるプラグイン。奥が深すぎて簡単な使い方しかできないw
高性能なテキスト整形ツールAlignの使い方 #1 インストールから設定まで — 名無しのvim使いを見ると凄さがわかると思う。

$a = array(
    'id' => 1234,
    'name' => 'foo',
    'email' => 'foo@example.com'
);

これを

$a = array(
    'id'    => 1234,
    'name'  => 'foo',
    'email' => 'foo@example.com'
);

一発でこんな感じにできる。

one two three four five
six seven eight nine ten
eleven twelve thirteen fourteen fifteen

こんなのを

one    two    three    four     five
six    seven  eight    nine     ten
eleven twelve thirteen fourteen fifteen

こんな感じにもしてくれる。

surround.vim

http://www.vim.org/scripts/script.php?script_id=1697
クォートをつけたり外したり、タグで挟んだり消したりといった、文字列を囲ったりする処理を一発でやってくれるプラグイン
参考:vim の text-object をより便利に使えるプラグイン - surround.vim - 2nd life

eregex.vim

http://www.vector.co.jp/soft/unix/writing/se265654.html
vim正規表現perlrubyと同じような正規表現で入力できるようになるプラグイン
プログラミングでPCREとかに慣れてる人は快適になること間違いなし。

vcscommand.vim

http://www.vim.org/scripts/script.php?script_id=90
CVS, SVN, SVKの操作ができるようになるプラグイン。まぁシェル叩いてもいいんだけど。

yankring.vim

http://www.vim.org/scripts/script.php?script_id=1234
yankの履歴を順番に呼び出せるプラグインレジスタを探さなくてもC-n/pで順次呼び出せるので便利。
WindowsではCLCLというクリップボード履歴管理ツールを使っているので、こういうのが欲しかった。

svn-diff.vim

http://www.vim.org/scripts/script.php?script_id=978
svnでコミットする際のログエディタとして呼び出されると、自動的にコミット内容のdiffを表示してくれるファイルタイプ型プラグイン
vcscommand.vimとの連携はできないけど、すげー便利かも。

grep.vim

http://www.vim.org/scripts/script.php?script_id=311
grepプラグインgrep自体は標準のでもいいんだけど、GrepBufferという全バッファに対してgrepできる機能がすてき。

commentout.vim

http://nanasi.jp/articles/vim/commentout_source.html
コメントアウトコメントアウト解除を簡単に行えるプラグイン
矩形選択してIとかで挿入するよりもだいぶ楽。/* 〜 */もできるし。

monday.vim

http://www.vim.org/scripts/script.php?script_id=1046
C-a/xで数値だけでなく曜日や月の名前もインクリメント/デクリメントできるようになるプラグイン
それだけではあまり用途が思いつかないけど、実はこの変換ルールが簡単に定義できるようになっているので、true←→falseとかpublic→protected→private→publicなんてことも出来るようになる。……と名無しのVIM使いさんのところに紹介されていたw

matchit.vim

http://www.vim.org/scripts/script.php?script_id=39
%による対応括弧への移動を強化してHTMLタグとかif/endifとかでも移動できるようにするプラグイン
標準添付なのでダウンロードしてこなくても:sourceで読み込めば使えるようになる。


以下は導入してないけど参考として。

autoclose.vim

http://www.vim.org/scripts/script.php?script_id=1849
クォートや括弧を入力した際に自動的に閉じ括弧を補完してくれるプラグイン
閉じ括弧が二重入力されないような制御もされてるらしい。
EclipseなどのIDEでそういう機能に慣れている人は導入してみるといいかも。

project.vim

http://www.vim.org/scripts/script.php?script_id=69
プロジェクトリソース一覧を表示したりコンパイルしたりといったIDEを構築するプラグイン
これで開発するのが流行っぽい節があるけど、定義とかめどいし、受託開発だと構成もばらばらなので自分はwinmanagerで十分かも。

favex.vim

http://www.vim.org/scripts/script.php?script_id=539
ファイルやディレクトリをお気に入りとして管理できるプラグイン

templates.vim

http://www.vim.org/scripts/script.php?script_id=1172
新規バッファを作成するときに、ファイルタイプに合わせてテンプレートを読み込んでくれるプラグイン
実は秀丸でもテンプレート系のプラグインを使っていて、HTML4とかXHTMLとかのテンプレートを一発で呼び出せるようにしていたので、もしかしたら導入するかも。
でもいくつかファイルを用意しておいて:readで読み込ませるようなファンクションでも作った方が使い分けも出来ていいかも。