Change 2-space indentation to 4-space in vim

I have codes copied from the Internet that are indented with 2 spaces, and I want to change it to 4-space indentation. I wonder if there is a short vim procedure to complete a task without having to write a vim script? This is how I am doing this with an HTML file:

  • Record macro
  • Go to beginning of line
  • Visually select all spaces until the first "<"
  • Yan and paste all the spaces (mainly to double them)
  • Repeat macro playback to end of file

Shorter qa0vt<yp<esc>jq

Traps:

The macro does not work for an empty line or a line that does not start with "<". And I do not know how to extend this solution to a non-HTML file.

+70
vim
Jun 03 '13 at 0:37
source share
6 answers

The general way to change the indentation is to change the tab:

Paste your file into an empty buffer, then:

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

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

 :set ts=4 sts=4 et :retab 

This changes each TAB to 4 spaces.

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

+137
Jun 03 '13 at 7:42 on
source share

This is possible with :set shiftwidth=4 and gg=G

+46
Jun 03 '13 at 0:46
source share

What I'm doing is very similar to esneider and cforbish approaches, but typing a little faster:

 :%s/^\s*/&& 

It simply replaces the leading space (spaces or tabs) with twice as many leading ones ( & is replaced by the matching expression).

+23
Sep 24 '13 at 3:24
source share

I used this regex (it doubles the number of leading spaces):

 %s;^\(\s\+\);\=repeat(' ', len(submatch(0))*2);g 
+2
Jun 03 '13 at 1:00
source share

Similar (but somewhat simpler) to cforbish's answer, this regular expression will duplicate leading spaces

 :%s/^\( \+\)/\1\1 



Or you can use this other regular expression to convert 2-spaces to 4-spaces, while preserving single spaces (and odd sums at all)

 :%s/^\(\( \)\+\)/\1\1 

I.e

  • 1 space ⇢ 1 space
  • 2 spaces ⇢ 4 spaces
  • 3 spaces ⇢ 5 spaces
  • 4 spaces ⇢ 8 spaces
+1
Jun 04 '13 at 4:11
source share

This is a very old question, however all the answers ... are wrong ... Vim has a very simple way to overwrite the whole file. I found out about this after I wrote my own function to do this, so I am in the same trap of ignorance;)

type

 gg=G 

this assumes you have a tab that you like (so for OP it will be ts = 4)

I found out about this from http://vim.wikia.com/wiki/Fix_indentation , which mentions

In normal mode, typing gg = G will re-specify the entire file. This is a special case; = is the operator. Just like d or y, it will act on any text that you move using the cursor move command. In this case, gg positions the cursor in the first line, then = G indents from the current cursor position to the end of the buffer.

-one
Feb 18 '15 at 2:12
source share



All Articles