I would like to reformat code in an entire file from this brace style:

if (condition)

… into this brace style1:

if (condition) {

The bulk of the task should be accomplishable by relocating the opening braces. I would like to do something like

:%s/^M *{$/ {/

… but substitutions don't seem to work across line breaks.

Is there a way to make substitutions work across line breaks? If not, what is the next-best solution that does not involve an external command or plugin? (I'm more interested in text-editing technique than in specialized programming tools.)

1 No flame wars about the choice of brace style, please!

1 Answer 1


You can use \n to do substitutions across multiple lines. There are also special characters which start with \_ that are the same as their normal counterparts, except it adds newline to their character class. For instance, \_s is the same as \s, except it also matches newline characters. Here is your search and replace statement with this special character:

:%s/\n *{$/ {/

Of course, you can make the regex more specific, since this one may match more than you want.


  • I was just typing an answer ;-) Here's my solution: :%s/)\n^\s*{$/) {/, which also makes sure there's the preceding line ends with a )... Apr 5, 2015 at 14:08
  • Yes of course. The regex could be made safer, but I really was just demonstrating the special characters. I'll add that to my answer. Apr 5, 2015 at 14:28
  • 1
    Thanks! It's kind of annoying that you're supposed to use \n to represent a line break in the regex, but ^M (Ctrl-V M) to represent a line break in the substitution text. That's just how it is, I guess. Apr 6, 2015 at 10:24

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.