开发者

Indenting with spaces but still use preferred shiftwidth in Vim?

I'm having a problem using spaces for indenting in Vim. The coding guidelines of many projects specify that code should be indented using spaces and not tabs. Fair enough. But is there any way that, when I am working with their code, to still see and use my preferred shift width?

For example, this piece of code is indented using 8 spaces:

function foo() {
        return 'foo';
}

Is there any way that, when I open this in Vim, it displays (and indents, for edits) as th开发者_如何学运维is (shiftwidth of 4):

function foo() {
    // edited to add this comment
    return 'foo';
}

But, when I save it, it saved like so (8 space indents):

function foo() {
        // edited to add this comment
        return 'foo';
}

This happens quite naturally when you use tabs for indenting. Just adjust your shiftwidth and voila, you can edit in whatever indent you personally prefer. But, most projects these days seem to require indents using spaces. And it seems impossible to edit a file in my personally preferred shiftwidth, yet still conform to a project's indent guidelines when using spaces.


See the vim help for retab. It has an example to do what you're asking.

In case you don't have the same vim help file I do:

                                                        *retab-example*
Example for using autocommands and ":retab" to edit a file which is stored
with tabstops at 8 but edited with tabstops set at 4.  Warning: white space
inside of strings can change!  Also see 'softtabstop' option. >

  :auto BufReadPost     *.xx    retab! 4
  :auto BufWritePre     *.xx    retab! 8
  :auto BufWritePost    *.xx    retab! 4
  :auto BufNewFile      *.xx    set ts=4
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜