Forethinker
Forethinker

Reputation: 3758

Wrapping comments with line breaks in PyCharm

I have comments that gets balloon (PEP 8: Line too long ... > 120) I wish there was a command that will wrap the lines with few keystrokes. Right now, even if I type Alt+Enter and press enter on Reformat file, nothing actually changes. Is there a setting or plugin I could use to accomplish the formatting easily?

Upvotes: 43

Views: 26709

Answers (5)

Judge
Judge

Reputation: 679

With recent PyCharm this now is located at "Editor -> Code Style", with the checkbox named "Wrap on typing" enter image description here

The Screenshot shows PyCharm version 2016.2.1 Professional.

Upvotes: 10

AZhao
AZhao

Reputation: 14405

Updated Answer: Use "soft wraps." You can search for it in the help bar.

View > Active Editor > Use Soft Wraps

It won't work for existing text or text that's copied in, but will for any newly typed text.

Upvotes: 4

Nafiul Islam
Nafiul Islam

Reputation: 82440

Firstly, reformatting won't work, not in Python at least, where whitespace is important. PyCharm's "Wrap when typing reaches right margin" option is what you're looking for. Now this will not work when you copy and paste code, but in the places where it gives you trouble, just press enter, and it will work.

Screenshot of where to turn on PyCharm "Wrap when typing reaches right margin" option

Upvotes: 24

Mike
Mike

Reputation: 20196

Under the Edit menu, there is a Fill Paragraph option, which does what I believe you want. You can assign a key command to this in Preferences, under Appearance & Behavior -> Keymap (search for "fill").

Personally, I choose first stroke Esc, second stroke Q, because that's what I've always used in Emacs...

Upvotes: 65

Kevin
Kevin

Reputation: 2889

To be able to auto-reformat comments (and code, for that matter) to honor a right margin after the fact, go into Project Settings under Code Style and then further under Python. Click the Wrapping and Braces tab, and check the "Ensure right margin is not exceeded" checkbox.

Now if you select a region of lines and then run the Code/Reformat Code... command, PyCharm will do its best to wrap the comments or code appropriately.

You will probably have to do some tweaking of the results to suit your stylistic taste. For example, I wish PyCharm would do aggressive filling of text in block comments, at least optionally so.

PyCharm will not reformat code such that it becomes invalid Python, so sometimes it will still leave a line longer than the margin (120 or whatever you set under Project Settings/Code Style/General).

enter image description here

Upvotes: 19

Related Questions