3

私には単純な目標があります: Map Ctrl-C は、vim を強制終了するために使用したことがないと思うコマンドで、行の先頭に正しい文字を自動的に挿入して、その行をコメントアウトします。ファイルのファイルタイプ。

自動コマンドを使用してファイルの種類を認識し、ファイルが開いているときに vim 変数を正しいコメント文字に設定できると考えました。だから私は次のようなものを試しました:

" Control C, which is NEVER used. Now comments out lines!
autocmd BufNewFile,BufRead *.c let CommentChar = "//"
autocmd BufNewFile,BufRead *.py let CommentChar = "#"
map <C-C> mwI:echo &CommentChar<Esc>`wll

そのマップは私の現在の位置をマークし、挿入モードで行の先頭に移動し、その時点でコメント文字をエコーし​​ 、コマンドモードに入り、設定マークに戻り、2文字右に移動して挿入されたコメント文字 (C スタイルのコメントを想定)。

イタリック体の部分は私が問題を抱えている部分です。私がやりたいことを表すためのプレースホルダーとしてしかありません。これを達成する方法を理解するのを手伝ってもらえますか? strlen(CommentChar) を使用して正しい数のスペースを右に移動すると、ボーナス ポイントが得られます。ビジュアルモードでブロックスタイルのコメントを行う方法を含むvim-masterの追加ボーナスポイント!!

私はまだ vim スクリプトに関してかなり初心者です。私の .vimrc の長さはわずか 98 行なので、回答があれば説明していただければ助かります。ありがとう。

4

2 に答える 2

5

You can use <C-r> here:

noremap <C-c> mwI<C-r>=g:CommentChar<CR><Esc>`wll

see :h i_CTRL-R.

Also look at NERDCommenter plugin, with it mapping will look like this:

" By default, NERDCommenter uses /* ... */ comments for c code.
" Make it use // instead
let NERD_c_alt_style=1
noremap <C-c> :call NERDComment(0, "norm")<CR>

And you will not have to define comment characters by yourself.

于 2010-10-06T06:16:08.517 に答える
3

ある時点でこれをvimのヒントwikiから削除し、自分で使用しました。唯一の欠点は、何らかの理由で行末にスペースが追加されることです。おそらく、私が見落としていた小さなものです。

" Set comment characters for common languages
autocmd FileType python,sh,bash,zsh,ruby,perl,muttrc let StartComment="#" | let EndComment=""
autocmd FileType html let StartComment="<!--" | let EndComment="-->"
autocmd FileType php,cpp,javascript let StartComment="//" | let EndComment=""
autocmd FileType c,css let StartComment="/*" | let EndComment="*/"
autocmd FileType vim let StartComment="\"" | let EndComment=""
autocmd FileType ini let StartComment=";" | let EndComment=""

" Toggle comments on a visual block
function! CommentLines()
    try
        execute ":s@^".g:StartComment." @\@g"
        execute ":s@ ".g:EndComment."$@@g"
    catch
        execute ":s@^@".g:StartComment." @g"
        execute ":s@$@ ".g:EndComment."@g"
    endtry
endfunction

" Comment conveniently
vmap <Leader>c :call CommentLines()<CR>
于 2010-10-06T13:56:04.857 に答える