You can reformat source code to meet the requirements of your code style. PyCharm will lay out spacing, indents, keywords etc. Reformatting can apply to the selected text, entire file, or entire project.
It is also possible to apply reformatting to the parts of the source code only, using the formatting markers.
-
On the main menu, choose
Ctrl+Alt+L.
Alternatively, in the project tool window, right-click the file with the code you want to reformat and from the context menu, select Reformat Code.
or press
-
In the
Reformat Code dialog box, specify the reformatting scope:
- The current file.
- Selected text.
- All files in the current directory, including or omitting subdirectories. You can also include optimizing imports, by selecting the Optimize imports check box, which is enabled for the current directory only.
- Click Run.
- At the beginning of the region, create a line comment (Ctrl+Slash or Ctrl+NumPad /), and then manually type the marker specified in the Formatter off field of Code Style page.
- At the end of the region, create a line comment (Ctrl+Slash or Ctrl+NumPad /), and then manually type the marker specified in the Formatter on field of Code Style page.
- Perform code reformatting, as described above.
Alternatively, create a live template to surround a block of code with formatter off/on markers, see Creating and Editing Live Templates.
Example of using formatting markers
The original source code | The code after reformatting |
---|---|
|
When the formatting markers are disabled, the original formatting is broken:
When the formatting markers are enabled, the original formatting is preserved: |