Wrapping comments with line breaks in PyCharm

2019-01-22 20:03发布

问题:

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?

回答1:

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.



回答2:

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...



回答3:

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).



回答4:

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.



回答5:

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

The Screenshot shows PyCharm version 2016.2.1 Professional.