5

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

if (condition)
{
    body;
}

… into this brace style1:

if (condition) {
    body;
}

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!

8

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.

References:

  • 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 )... – Martin Tournoij Apr 5 '15 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. – EvergreenTree Apr 5 '15 at 14:28
  • 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. – 200_success Apr 6 '15 at 10:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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