简体   繁体   中英

Replacing newlines with spaces in Vim

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?

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

这应该做:

substitute(a:str,'\n\|^','&'.repeat(' ', a:n) ,'g')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM