Can Vim display two spaces for indentation, while keeping four spaces in the file?

爷,独闯天下 提交于 2019-12-21 07:33:18

问题


I want to work on someone else's project, and he uses 4 spaces for indentation. I use 2, and my screen is not big enough to edit using 4 spaces comfortably.

Can I configure Vim to display 2 spaces for indentation, but write 4 to the file?


回答1:


This is the opposite of what was asked here.

Yes, you can! If you have the "conceal" option, you can try this out.

:syntax match spaces /  / conceal cchar= "Don't forget the space after cchar!
:set concealcursor=nvi
:set conceallevel=1

Here are what these commands do:

  • Set the replacement character for 2 spaces to 1 space
  • Keep text under cursor concealed for normal, visual, and insert modes
  • Enable concealing text with one character

You still have to set your tabstop, softtabstop and shiftwidth to 4, but it looks and feels like it is 2! However, when you write the file, it's really 4.

If you want to turn concealment off you can do one of two things:

  1. Remove conceal rule :syntax clear spaces or
  2. Allow concealed text to be expanded under the cursor :set concealcursor=



回答2:


The help has an example for a similar use case of different tab widths, see :help retab-example.

Adapting that to halving / doubling spaces:

:autocmd BufReadPost,BufWritePost  * %substitute/^\( \+\)\1/\1/e
:autocmd BufWritePre               * %substitute/^ \+/&&/e



回答3:


If he uses true spaces instead of tabs (which it sounds like), no, you cannot have vim display 2 spaces where there are 4. However, you can tell vim the following commands to replace all 4-space groups with the tab character, and then display them as 2 spaces.

:set tabstop=4 ! display a tab as 4 columns
:set shiftwidth=4
:set noexpandtab
:gg=G   ! convert the whole file to tabs
:set tabstop=2 !display a tab as 2 columns
:set shiftwidth=2

When you are ready to submit your work,

:set tabstop=4
:set shiftwidth=4
:set expandtab
:%retab

Should convert it back.



来源:https://stackoverflow.com/questions/13849368/can-vim-display-two-spaces-for-indentation-while-keeping-four-spaces-in-the-fil

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!