I'd like to replace all two-space indents with tabs

I can't do :%s/ /^I/g bc this replaces within lines too.

I can't do :%s/^ /^I/g bc this replaces only the first two spaces of each line, not each level of indentation.

If there were a way to count how many matches were found, something like this could work :%s/^\( \)*/\count^I/g, but I don't know whether any of that exists and I've tried looking it up but couldn't find it.

Is there a way I can replace X spaces at the start of a line with X/2 tabs?


1 Answer 1


Using :h sub-replace-special:

%s@^ \+@\=repeat("\t", strlen(submatch(0)) / &ts)
  • What's &ts here?
    – minseong
    Mar 18, 2021 at 11:53
  • 1
    The value of 'tabstop'.
    – B Layer
    Mar 18, 2021 at 12:00
  • I'm using %s@^\( \)\+@\=repeat("\t", strlen(submatch(0)) / 2) bc the answer gets rid of single spaces. Thanks for showing me this section of :s
    – minseong
    Mar 18, 2021 at 12:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.