The corporate rules about indention forces us to surround our if conditions with spaces like this (in a C and C++ codebase) :

 if (<space>foo == bar<space>)

Is there any emacs tool to insert them automatically?

  • 1
    I'm not aware of any function in Emacs that can help you with this, but you should be able to use astyle with the --pad-header option to accomplish what you want. This might help. Commented Sep 14, 2017 at 17:57
  • such changes 1) should have been incorporated when you wrote the code. and 2) can be easily performed globally via a simple find and replace operation. Commented Sep 14, 2017 at 23:36
  • Or run clang-format from a hook before you save.
    – InHarmsWay
    Commented Oct 2, 2017 at 11:12

2 Answers 2


Note: not a full answer, but may help.

I don't know about a tool… the main challenge seems to be capturing X in occurrences of if (X). The tricky thing is that you can't just search for a regular expression and be done: X has to have balanced parenthesis. Easy? Not so fast: parenthesis do not need to be balanced if they are

  • inside of strings "asd)";
  • in a char ')'; or
  • inside of a comment.

I think these might be the only cases that matter. Assuming there is no macro trickery in your codebase! Our recipe would then be

  1. Scan until if[:space:]*([:space:]*
  2. Replace the next occurrence of [:space:]*([:space:]* by a ( (parenthesis surrounded by spaces),
  3. move the cursor forwards, and continue so long as you have not found a closing parenthesis matching the first one (i.e., balancing the first one), skipping strings and comments. The key point here is to save the position whenever you transition from non-space to space character.
  4. Save the position of the matching ).

At this point we have

      ... if ( balanced-parenthesis-exp)    )
                                        ^   ^
                                        |   |
                                        |  closing par (b)
                                     end of condition (a)

To conclude,

  1. Replace what's between (a) and (b) by ) (space followed by parenthesis)

This should be enough to get you started!


I would use replace-regexp the forward space is easy use M-X RET replace-regexp RET if<space>( RET if<space>(<space>. You could use a similar replace-regexp rule to do the second space. For the second space, you would probably have to use several replace-regexp rules depending on what character your second variable ends with.

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.