Reputation: 10939
I am writing a function to indent all lines in a string in Vim. I am trying to this by using substitute
to replace all start-of-lines with n
spaces:
function! Indent(str, n)
return substitute(a:str, '\v^', repeat(' ', a:n), 'g')
endfunction
This only indents the first line, despite my use of the g
flag. I have also tried using \v\_^
, same result.
Indent("To be or not to be\nThat is the question", 2)
# => " To be or not to be\n That is the question" (DESIRED OUTPUT)
# => " To be or not to be\nThat is the question" (ACTUAL OUTPUT)
How can I modify my regex to get the desired output?
Upvotes: 0
Views: 982
Reputation: 31419
You can do this with split and join fairly easily.
function! Indent(str, n)
let l:sep = repeat(' ', a:n)
return l:sep . join(split(a:str, "\n"), "\n".l:sep)
endfunction
Upvotes: 1
Reputation: 195029
this should do:
substitute(a:str,'\n\|^','&'.repeat(' ', a:n) ,'g')
Upvotes: 1