LoginSignup
2
1

More than 5 years have passed since last update.

vimで複数行を複製しつつコメントアウト。

Posted at

この記事は Vim Advent Calendar 2012 319日目の記事になります。
前回は@ mittanさんのMacのVimでBGMを聴くでした。

今回は”コメントアウトして編集”を効率化する。 に便乗。これの複数行対応ver. の関数を作ってみました。
*今回作った関数はThe Nerd Commenterに依存してます。

先のリンクにあるように元のコードをコメントアウトしつつ、複製したい事はよくあると思います。

before.rb
hello(name)
  puts 'hello' + name
end

hi(name)
  puts 'hi!' + name
end

以下のようにしたい。でもこれって結構面倒くさいんですよね。ビジュアルモードで複数選択してyしてPして元のコードのところに行ってコメントアウトしてッて感じで…。

after.rb

hello(name)
  puts 'hello' + name
end
# hello(name)
  # puts 'hello' + name
# end

hi(name)
  puts 'hi!' + name
end

これを可能にするvimscriptの関数をざっと作ってみました。
以下を.vimrc に書いて、VでのビジュアルモードでCtrl + d すれば選択したものが複製されつつ元の分がコメントアウトされます。冗長で動作検証も詳しくしてないので、もっと良い書き方あれば教えて下さい。

.vimrc
vnoremap <silent> <C-d> :call DupLines()<CR>
  function! DupLines()  range "{{{
    let selected_num = line("'>") - line("'<") + 1
    let ori_pos = line("'<")

    " 選択中の行をyank
    normal! ""gvy
    " yankした物をPする
    normal P
    " 元のコードを選択
    execute 'normal '.selected_num.'j'
    execute 'normal V'.selected_num.'j'
    " コメントアウトする
    call NERDComment(1, 'norm')
    " ビジュアルモードからエスケープ
    execute "normal! \e\e"
    " 元の位置に戻る
    execute 'normal '.ori_pos.'gg'
  endfunction "}}}
2
1
1

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
2
1