Search code examples
phpstorm

in PhpStorm, is it possible to reformat injected code within a PHP file?


PhpStorm can apply code style rules for specific languages with the Reformat Code command. PhpStorm can also recognize a language embedded within a file of another language (known in PhpStorm as 'Language Injection'). So, I expect that a language would be subject to its code style rules wherever the language is used -- whether embedded or in its own file.

I've found that this works as expected for css/js within an html file, but not for language injections within PHP files. PhpStorm will recognize css within a heredoc, and html as a heredoc and in single- and double- quoted strings -- yet reformatting does not work in any of these cases.

Short of using an intermediary file to reformat the code, how can I get PhpStorm to reformat these sections of code? I am using PhpStorm 6.0.3 for Mac.

Their documentation states:

PhpStorm supports full coding assistance for:

  • CSS and JavaScript in an HTML or XML file.
  • CSS, JavaScript, and SQL outside PHP code blocks and inside PHP string literals.

The second bullet seems only half true, as css/js/sql are recognized but not subjected to code styles inside PHP string literals. And injected html is not specified; but between PhpStorm recognizing the language injections and its capability to apply code styles to an arbitrary selection, all the pieces for formatting embedded languages seem to be there. What am I missing?


Solution

  • To reformat injected code according to PhpStorm code styles Preferences, select the injected code and open the Intention Actions list (Alt+Enter), and select "Edit __ Fragment" to edit it in it's own dedicated window (documentation). In this window, code formatting will work as expected.