对于已保存的文件,可以使用下面的方法进行空格和TAB的替换
TAB替换为空格:
:set ts=4
:set expandtab
:%retab!
空格替换为TAB:
:set ts=4
:set noexpandtab
:%retab!
在linux环境下,作为python开发环境,设置的.vimrc
set autoindent " 换行自动缩进
set shiftwidth=4 " 自动缩进时的宽度
set ts=4 " tabstop的宽度
set expandtab " tab换成空格
set softtabstop=4 " 退格键
set paste " 粘贴时不自动换行
关于使用tab还是空格的争执很多...各有各的道理...可参考以下文章:
https://www.techug.com/post/why-tabs-are-clearly-superior.html
https://www.zhihu.com/question/19960028/answer/15262434
我的感觉:
1. 使用tab制表符时, 对于行首的缩进等没有关系。
但对于数据结构/注释/define宏的定义的对齐, 如以下情况:
struct dwc3 {
› struct work_struct› drd_work;
› struct dwc3_trb›› *ep0_trb;
› void› › › *bounce;
› void› › › *scratchbuf;
› u8› › › *setup_buf;
› dma_addr_t› › ep0_trb_addr;
› dma_addr_t› › bounce_addr;
› dma_addr_t› › scratch_addr;
› struct dwc3_request› ep0_usb_req;
› struct completion› ep0_in_setup;
内核中建议tab不展开为空格, 且一个tab宽度为8个字符。故你的IDE必须按要求设置。
如果将tab宽度设置为4个, 则代码就变成下面这样了....
struct dwc3 {
› struct work_struct› drd_work;
› struct dwc3_trb›› *ep0_trb;
› void› › › *bounce;
› void› › › *scratchbuf;
› u8› › › *setup_buf;
› dma_addr_t› › ep0_trb_addr;
› dma_addr_t› › bounce_addr;
› dma_addr_t› › scratch_addr;
› struct dwc3_request›ep0_usb_req;
› struct completion› ep0_in_setup;
.....
其他还有注释, 宏定义等情况...
都会遇到类似的问题...
另外code review的网页浏览器, 一个制表符为多少, 并不一定和你一致...
所以也会遇到代码对齐的问题....
所以我的习惯还是将tab制表符展开成空格。宽度为4个...
如此任何IDE, 浏览器一类, 看上去效果是一样的了...
但Linux内核却是使用制表符的, 包括你修改其他人的代码...
归根结底...对于你不是作者的代码... 还是尽量和作者保持一致吧...
一些常见软件的缩进设置, 请参考以下文章...
https://tedlogan.com/techblog3.html
Tabs are eight columns wide. Each indentation level is one tab. (Popular with the Linux kernel.)
:set tabstop=8 softtabstop=8 shiftwidth=8 noexpandtab
Tabs are four columns wide. Each indentation level is one tab. (Popular with Windows developers using Visual Studio.)
:set tabstop=4 softtabstop=4 shiftwidth=4 noexpandtab
Each indentation level is four spaces. Tabs are not used. (Popular with Java programmers.)
:set softtabstop=4 shiftwidth=4 expandtab
还有...
Just to prove it's possible, here are some more ... creative indentation styles and their vim representation:
- Tabs are eight columns wide. Each indentation level is three columns, which may be spaces or tabs.
:set tabstop=8 softtabstop=3 shiftwidth=3 noexpandtab
- Tabs are five columns wide. Each indentation level is six columns, which may be spaces or tabs.
:set tabstop=5 softtabstop=6 shiftwidth=6 noexpandtab
... you get the idea.