首页 文章

Tab键== 4个空格并在Vim中的花括号后自动缩进

提问于
浏览
1108

如何使vi - Vim从不使用制表符(将空格转换为制表符,不好!),使制表键== 4个空格,并在像Emacs这样的大括号块之后自动缩进代码?

另外,如何保存这些设置,以便我再也不必输入它们?

我已经看到了与此相关的其他问题,但它似乎总是与我想要的有点不同 .

9 回答

  • 28

    正如下面的几个答案中所指出的,现在首选方法不是使用smartindent,而是使用以下(在.vimrc中):

    filetype plugin indent on
    " show existing tab with 4 spaces width
    set tabstop=4
    " when indenting with '>', use 4 spaces width
    set shiftwidth=4
    " On pressing tab, insert 4 spaces
    set expandtab
    

    在.vimrc:文件中:
    设置smartindent
    设置tabstop = 4
    设置shiftwidth = 4
    设置expandtab
    帮助文件需要一些时间来习惯,但是你读的越多,Vim就越好:help smartindent
    更好的是,您可以在源代码中嵌入这些设置以实现可移植性:帮助自动设置
    要查看当前设置:: set all
    正如ashwh在评论中指出的那样,smartindent已被cindent取代,“更聪明地工作”,虽然仍然主要用于具有类C语法的语言:: help C-indenting

  • 1652

    相关的,如果你打开一个同时使用制表符和空格的文件,假设你已经有了

    set expandtab ts=4 sw=4 ai
    

    您可以使用整个文件中的空格替换所有选项卡

    :%retab
    
  • 45

    获取特定于文件类型的缩进的最佳方法是在vimrc中使用 filetype plugin indent on . 然后你可以在.vim / ftplugin / c.vim中指定像 set sw=4 sts=4 et 之类的东西,例如,不必为正在编辑的所有文件创建全局文件,其他非C类型语法也将正确缩进(甚至是lisps) .

  • 46

    要在大多数文件中使用4个空格的选项卡,在Makefile中使用真正的8-wide tab char,并在各种文件(包括C / C)中自动缩进,请将其放在 ~/.vimrc 文件中:

    " Only do this part when compiled with support for autocommands.
    if has("autocmd")
        " Use filetype detection and file-based automatic indenting.
        filetype plugin indent on
    
        " Use actual tab chars in Makefiles.
        autocmd FileType make set tabstop=8 shiftwidth=8 softtabstop=0 noexpandtab
    endif
    
    " For everything else, use a tab width of 4 space chars.
    set tabstop=4       " The width of a TAB is set to 4.
                        " Still it is a \t. It is just that
                        " Vim will interpret it to be having
                        " a width of 4.
    set shiftwidth=4    " Indents will have a width of 4.
    set softtabstop=4   " Sets the number of columns for a TAB.
    set expandtab       " Expand TABs to spaces.
    
  • 9

    在许多Linux系统上,如Ubuntu,默认情况下 .vimrc 文件不存在,因此建议您先创建它 .

    不要使用主目录中存在的 .viminfo 文件 . 它用于不同的目的 .

    第1步:转到您的主目录

    cd ~

    第2步:创建文件

    vim .vimrc

    第3步:添加上述配置

    filetype plugin indent on
    set tabstop=4
    set shiftwidth=4
    set expandtab
    

    第3步:按Shift ZZ保存文件 .

  • 11

    推荐的方法是使用基于文件类型的缩进,如果不够,只使用smartindent和cindent .

    将以下内容添加到.vimrc中

    set expandtab
    set shiftwidth=2
    set softtabstop=2
    filetype plugin indent on
    

    希望它有助于作为一个不同的答案 .

  • 212

    编辑你的〜/ .vimrc

    $ vim ~/.vimrc
    

    添加以下行:

    set tabstop=4
    set shiftwidth=4
    set softtabstop=4
    set expandtab
    
  • 7

    来自VIM wiki

    :set tabstop=4
    :set shiftwidth=4
    :set expandtab
    
  • 84

    自动缩进基于当前语法模式 . 我知道如果您正在编辑Foo.java,那么输入 { 并按Enter键缩进以下行 .

    至于标签,有两种设置 . 在Vim中,键入一个冒号,然后“set tabstop = 4”,它将设置选项卡显示为四个空格 . 再次点击冒号并输入“set expandtab”,它将为制表符插入空格 .

    您可以将这些设置放在主目录中的.vimrc(或Windows上的_vimrc)中,这样您只需键入一次即可 .

相关问题