I'm setting up a fairly large (~50 functions) test library in C++. I forgot that the functions have to return integers. I actually forgot to put a return type at all, how dumb is that? I added the int return type at the start of each function with:

:%s/^[a-z]/int &/g

but now I can't figure out how to add return 0; to each of them. I tried:

:%s/{\r\r}/{\r\treturn 0;\r}/g

and variations of it, and each said it couldn't find the pattern. The functions are set up like:

int function_name()


and I want them to look like:

int function_name()
    return 0;

any ideas???


vim has that idiosyncrasy in that you have to use \n to match a newline character in a regexp, but \r (\r being otherwise CR, not newline) to insert it in the right hand side of the s/LHS/RHS/ command (where \n inserts a NUL instead).

I never understood why. Even considering that the Enter key sends a \r character which vim has to convert to NL (like the tty line discipline does when the terminal is in canonical mode) doesn't explain everything. You'll also notice that when you enter the \n character (by pressing Ctrl+J), vim inserts a NUL character.

:h NL-used-for-Nul tells us that it's because vim stores NULs internally as NLs (I suppose so that it can still use NUL delimited strings), but it doesn't explain why it decided to make that visible to the user in the interface.

Anyway, it's the way it is so we have to make do with it, so here:

:%s/{\n\n}/{\r\treturn 0;\r}/g

(we are matching newline characters, replacing them with CR characters that are converted to newline characters).

  • This answer worked, but inserted a tab of size 8 spaces (i use 4 usually). Easy fix via V and <, but am looking for a single command. Is there something missing in the command or do I have a setting missing in my .vimrc? I have set autoindent, set smarttab, and set shiftwidth=4 in it already. – adam-watson May 29 '15 at 21:01
  • @Adam, It inserts a tab character. tab characters don't have width, they are control characters like CR or BS. For text editors or terminals, they move the cursor to the next tab stop. In vim you can change the number of columns between tab stops with the ts/tabstop option. – Stéphane Chazelas May 29 '15 at 21:16

You can use

:%s/^}/    return 0;\r}/g

You don't really need to care about the opening braces, it is enough to find the closing braces with 0 indentation.

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.