【问题标题】:Changing Vim behavior by file type using single `.vimrc` (without ftplugin)使用单个 `.vimrc`(不带 ftplugin)按文件类型更改 Vim 行为
【发布时间】:2012-07-31 21:13:54
【问题描述】:

如何以优雅的方式使用单个 .vimrc 文件(不带 ftplugin)更改 Vim 行为?

我的意思是......如果我对 C/C++ 文件运行了很多推荐,例如:

set nu
set cin
set ai
set mouse=a
color elflord

还有一堆对 AsciiDoc 文件的赞扬,例如:

set syntax=asciidoc
set nocin
set spell spl=en

不提 Python、LaTeX 等......

有解决方案 https://stackoverflow.com/a/159065/544721 用于将autocommand 放在每个自定义命令之前。

有没有一种很好的方法可以在不使用ftplugin 的情况下将它们分组为autocommand - 以便将所有内容保存在单个.vimrc 文件中(更适合在多台机器上移动等)? 相当于if 括号{} 的语句?

【问题讨论】:

标签: vim


【解决方案1】:

您可以使用以下内容:

if has("autocmd")
    augroup LISP
        au!
        au BufReadPost *.cl :set lisp
        au BufReadPost *.cl :set showmatch
        au BufReadPost *.cl :set cpoptions-=m
        au BufReadPost *.cl :set autoindent
    augroup END
    augroup C
        au!
        autocmd BufNewFile,BufRead *.cpp set formatprg=c:\\AStyle\\bin\\AStyle.exe\ -A4Sm0pHUk3s4
        autocmd BufNewFile,BufRead *.c set formatprg=c:\\AStyle\\bin\\AStyle.exe\ -A4Sm0pHUk3s4
        autocmd BufNewFile,BufRead *.h set formatprg=c:\\AStyle\\bin\\AStyle.exe\ -A4Sm0pHUk3s4
        autocmd BufNewFile,BufRead *.cpp set tw=80
        autocmd BufNewFile,BufRead *.c set tw=80
        autocmd BufNewFile,BufRead *.h set tw=80
    augroup END
endif

这会根据打开的文件类型创建命令分组,这些文件类型在 autocmd 部分中指定。您仍然需要在每个之前指定 autocmd 或 au,但它们很好地分组。

【讨论】:

    【解决方案2】:

    我可能会执行每个文件类型的函数来为我进行设置。无耻地扯掉@Derek...

    function! SetUpLispBuffer()
        set lisp
        set showmatch
        set cpoptions-=m
        set autoindent
    endfunction
    
    function! SetUpCBuffer()
        set formatprg=c:\\AStyle\\bin\\AStyle.exe\ -A4Sm0pHUk3s4
        set tw=80
    endfunction
    
    if has("autocmd")
        augroup LISP
            au!
            au BufReadPost *.cl call SetUpLispBuffer()
        augroup END
        augroup C
            au!
            autocmd BufNewFile,BufRead *.{cpp,c,h} call SetUpCBuffer
        augroup END
    endif
    

    当您想要进行更改时要更改的内容要少得多,剪切和粘贴的内容也少得多。

    【讨论】:

    • 我有点新……我好像读到“au!”删除此文件类型组的自动命令。我们为什么要做这个?这会干扰其他 vim 插件吗?谢谢:)
    • au! 删除包含 augroup 中的自动命令,因此只需将它们命名为您认为不会与插件冲突的名称。 (例如,我的 augroups 通常被命名为 TomsFileCleanups 等)
    猜你喜欢
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-01
    相关资源
    最近更新 更多