Lion
Lion

Reputation: 17879

PhpStorm automatically format smart code like Visual Studio

As a .NET developer, I'm familiar with the behavior of Visual Studio which automatically formats the code in the right way, e.g. after writing a semicolon or closing an if-statement. Lets say for example I enter the following not well formatted C# code in Visual Studio

int i=4

After I write the closing ; the IDE will following the code standards and insert spaces around the equal sign:

int i = 4;

But now I have to write a PHP application using PhpStorm. It's annoying that PhpStorm seems not so smart like Visual Studio. When I write there the same code like $i=4 then the formatting is kept ugly, although I enter the semicolon: $i=4;

I found out that I can re-format the whole script using a keyboard combination. But this is not really smart, I always have to repeatedly press the combination.

Is there any way to let PhpStorm act as smart as Visual Studio, so that my code is automatically formatted on semicolons, closing brackets and so on?

Upvotes: 1

Views: 638

Answers (1)

Phiter
Phiter

Reputation: 14992

I couldn't find a solution or a shortcut that already did this, so I made it working by creating a macro.


Steps:

  1. Type a expression like $i=0; and position your cursor after the semicolon: $i=0;enter image description here
  2. Go to Edit -> Macros -> Start Macro Recording
  3. You're now recording a macro. Press CTRL+Wx2 then CTRL+ALT+L then and then ENTER
  4. Go to Edit -> Macros -> Stop Macro Recording
  5. Give a name to your macro, say "Format current expression"
  6. Press CTRL+SHIFT+A and type "Keymap", click the one saying "Settings > Keymap".
  7. Search for {your macro name} and Right click {your macro name} -> Add keyboard Shortcut
  8. Set to a shortcut of your preference. I set mine to ALT+ENTER, because it's not used by any editor commands. A confirmation window will ask about the other commands that use the shortcut, click "Leave".

I think this will work.

Whenever you finish an expression you can press ALT+ENTER to format it.

You can also remove the ENTER shortcut from the "Enter" action in the keymap and use it in your Macro, but I wouldn't recommend it for... well... reasons.


Pay attention at the third step, if you want to do automatically add a semicolon as well, you can just type $i=2, position your cursor after the 2, and add the semicolon when recording the macro.

I'm not sure if pressing CTRL+W twice will always select the command properly, if you wish to select the entire row and format it, instead of pressing CTRL+W, you can press END and then SHIFT+HOME to select the current row.

Upvotes: 0

Related Questions