I have big portions of code where functions are formatted with the opening curly brace on the next line, like this :

function foo()

I'm trying to figure out how to search / replace in order to change it to this :

function foo(){
  • 1
    Today, most languages have tools to format code consistently and allow you to change a convention afterwards. Since you did not specify the language, I cannot point you to a tool for your language. But for example there is prettier.io which allows you to format a wide variety of languages. Integration into vim can be done via formatprg or use a plugin such as github.com/prettier/vim-prettier or github.com/sbdchd/neoformat.
    – Hotschke
    Commented Apr 3, 2019 at 15:13
  • This is for Wordpress, so a mix of php and html. prettier.io seems nice, but the PHP plugin is in alpha stage and not recommended for production. I'll have a look at the other ones. In the end I'm also happy to learn vimscript by implementing my own simple solutions on a specific need basis.
    – mike23
    Commented Apr 4, 2019 at 5:44
  • I did a quick check on some of the php & html formatters: as far as I see none of them supports mixed html/php files php-cs-fixer, prettier-php. So you have to apply them manually on code parts and it cannot be fully automated. I also doubt that vim can provide any help with that except manually running substitute commands. But this is a general vim feature not specific to formatting which adds your question to the long list of how can I replace X with Y.
    – Hotschke
    Commented Apr 4, 2019 at 7:22

1 Answer 1


You can use the new line character is your search (\n for linux):


Replaces )\s*\n{ into ){

The c flag at the end will ask you to confirm before each replacement.

EDIT: Another solution would be to use the join line feature (J) with the g command:

:g/function [^{]\+$/join

Which will execute the command join on every line matching the pattern function [^{]\+$ ("function" followed by anything without a {).

It will however put a space by default between ) and {, it can be changed by running the following before the g command:

:set nojoinspaces
  • 1
    You dont need norm J, :join is an ex command
    – D. Ben Knoble
    Commented Apr 3, 2019 at 17:17
  • Thanks! I did not know this one :-)
    – padawin
    Commented Apr 3, 2019 at 22:23
  • And even if you did need norm you should use norm! instead. I think.
    – 3N4N
    Commented Apr 4, 2019 at 3:56
  • @padawin thanks, I like the join solution, as it can easily be adapted to apply the formatting to Classes also.
    – mike23
    Commented Apr 4, 2019 at 7:50

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.