Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change 2-space indent to 4-space in vim

Tags:

vim

I've some codes copied from the Internet that have 2-space indenting and I want to change it into 4-space indenting. I wonder if there is a short vim routine to accomplish the task without having to write vim script? Here is how I'm currently doing it with an HTML file:

  • Record a macro
  • Go to the beginning of a line
  • Visual select all whitespaces until the first occurrence of "<"
  • Yank and paste all whitespaces (basically to double them)
  • Replay the macro till the end of the file

In short qa0vt<yp<esc>jq

Pitfalls:

The macro fails for a blank line or a line that doesn't start with "<". And I have no idea how to extend this solution to non-HTML file.

like image 833
Lim H. Avatar asked Jun 03 '13 00:06

Lim H.


People also ask

How do I indent 4 spaces in Vim?

The shiftwidth parameter controls your indentation size; if you want four space indents, use :set shiftwidth=4 , or the abbreviation :set sw=4 . If only this is done, then indentation will be created using a mixture of spaces and tabs, because noexpandtab is the default. Use :set expandtab .

How do I change the indentation in Vim?

Start in the top of a file (to get there, press gg anywhere in the file.). Then press =G , and Vim will fix the indentation in the whole file. If you don't start in the beginning of the file, it will fix indentation from current line to the bottom of file.

Is a tab 4 spaces?

Answer. In most code editors, tabs are not the same as 2 spaces or 4 spaces by default. A tab is stored differently than spaces in the code. Tabs can be seen as a big “jump” in the text, while spaces are always 1 space each.


1 Answers

A general way of changing the indent is by changing the tabstop:

Paste your file into an empty buffer, then:

:set ts=2 sts=2 noet :retab! 

This changes every 2 spaces to a TAB character, then:

:set ts=4 sts=4 et :retab 

This changes every TAB to 4 spaces.

The advantage of this method is that you can also use it the other way around, to convert from 4 to 2 spaces for example.

like image 110
Daan Bakker Avatar answered Oct 08 '22 04:10

Daan Bakker