vim で xmpfilter を使う設定をしてみる

Ubuntu で。

sudo aptitude install rubygem

sudo gem install rcodetools
sudo gem install fastri # rcodetools インストール時におすすめされたので入れてみた

/var/lib/gems/1.8/bin に Path を通すと、xmpfilter を実行できるはず。

そして、適当に .vimrc に以下のような設定をしておく。

noremap <silent> <Space>xa :!xmpfilter -a<CR>
nmap    <silent> <Space>xa V<Space>xa
noremap <silent> <Space>xm :!xmpfilter -m<CR>
nmap    <silent> <Space>xm V<Space>xm

これで、xa を押すと、こんな感じで "# => " のところに値が書き込まれる。

#!/usr/bin/env ruby

a, b = "foo", "bar"                                # => ["foo", "bar"]
str = a + b                                        # => "foobar"
str << a << b                                      # => "foobarfoobar"
str.length                                         # => 12
c = -11                                            # => -11
d = (0...10).map{|x| x}                            # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3.upto(5) do |i|
  c += 5                                           # => -6, -1, 4
  puts "#{c}, #{i}"
end
# >> -6, 3
# >> -1, 4
# >> 4, 5

(ref. Vim+xmpfilterでirbいらずのRuby試行錯誤開発 - ナレッジエース)


しかし、こういうのは自動でやりたいなぁということで...、

~/.vim/ftplugin/ruby/xmpfilter.vim

function! s:Xmpfilter()
  let s:cursor = getpos(".")
  %!xmpfilter -a
  call setpos(".", s:cursor)
endfunction

if !exists("g:xmpfilter")
  let g:xmpfilter = 1
  if executable("xmpfilter")
    au BufWritePre *.rb silent call <SID>Xmpfilter()
  endif
endif

これで、保存時に xmpfilter を自動でかけることができる。

さらに、~/.vimrc に以下を書いておいて、保存も自動でするようにしている。

function! AutoUp()
  if expand('%') =~ g:svbfre && !&readonly && &buftype == ''
    silent update
  endif
endfunction

autocmd CursorHold * nested call AutoUp()
set updatetime=3000
let g:svbfre = '.\+'

autocmd に "nested" を指定することで autocmd 経由で発動されたイベントにも autocmd が適用されるようになる。
ので、これで、AutoUp() の延長の BufWritePre イベントで xmpfilter が実行される。

初めは上みたいに別けて記述してたけど、~/.vim/ftplugin/ruby.vim にまとめてみた。

if executable("xmpfilter")
  function! s:Xmpfilter()
    let s:cursor = getpos(".")
    %!xmpfilter -a
    call setpos(".", s:cursor)
  endfunction

  au BufWritePre <buffer> silent call <SID>Xmpfilter()

  noremap <buffer> <silent> <Space>xa :!xmpfilter -a<CR>
  nmap    <buffer> <silent> <Space>xa V<Space>xa
  noremap <buffer> <silent> <Space>xm :!xmpfilter -m<CR>
  nmap    <buffer> <silent> <Space>xm V<Space>xm
endif

おまけ

~/.vimrc に...

保存時に行末の空白文字を消す

function! RTrim()
  let s:cursor = getpos(".")
  %s/\s\+$//e
  call setpos(".", s:cursor)
endfunction

autocmd BufWritePre * call RTrim()

最近のステータスライン

function! SetStatusline()
  if winwidth(0) >= 110
    set statusline=%<[%n]%m%r%h%w%{'['.(&fenc!=''?&fenc:&enc).':'.&ff.']'}%y\ %f%=[%{fnamemodify(getcwd(),':~')}]\ [%{GetB()}]\ %l,%c%V%8P
  else
    set statusline=%<[%n]%m%r%h%w%{'['.(&fenc!=''?&fenc:&enc).':'.&ff.']'}%y\ %f%=[%{GetB()}]\ %l,%c%V%8P
  endif
endfunction

autocmd VimResized * call SetStatusline()