Completely re-wrap in PyCharm / removing unnecessary wrapping

Viewed 68

I have "Wrap on typing" enabled in my PyCharm settings, which works great if I type a new line, but it seems to be quite messy when editing already wrapped code, as it keeps existing line-breaks even if they are superfluous.

I also use Ctrl-Alt-L to auto-format my code, but that doesn't remove unnecessary line breaks either.

Example: Let's say I originally wrote this code in one go, without putting manual line breaks, then PyCharm's "Wrap on typing" wraps it like this:

def main():
    x = some_long_function_call(['apple', 'banana', 'orange', 'pear', 
                                 'lemon', 'grapefruit', 'pineapple', 'grape',
                                 'plum', 'apricot'])

PyCharm wrapped this nicely, but let's say I want to add 'watermelon' before 'lemon', PyCharm decides the line 2 is too long, and wraps it like this:

def main():
    x = some_long_function_call(['apple', 'banana', 'orange', 'pear', 
                                 'watermelon',
                                 'lemon', 'grapefruit', 'pineapple', 'grape',
                                 'plum', 'apricot'])

This is not optimal, and pressing Ctrl-Alt-L doesn't fix it either. Now I move the stuff from line 3 up to line 2 and let PyCharm rewrap, and I get:

def main():
    x = some_long_function_call(['apple', 'banana', 'orange', 'pear', 
                                 'watermelon', 'lemon', 'grapefruit', 
                                 'pineapple', 'grape',
                                 'plum', 'apricot'])

Better, but there is still space. I need to manually move 'apricot' up to line 4, to get the better wrapping:

def main():
    x = some_long_function_call(['apple', 'banana', 'orange', 'pear',
                                 'watermelon', 'lemon', 'grapefruit',
                                 'pineapple', 'grape', 'plum', 'apricot'])

Now, if I move everything into one long line and allow PyCharm to rewrap it by pressing Ctrl+Alt+L, i get an arguably even nicer wrapping:

def main():
    x = some_long_function_call(
        ['apple', 'banana', 'orange', 'pear', 'watermelon', 'lemon',
         'grapefruit', 'pineapple', 'grape', 'plum', 'apricot'])

Is there any way I can get to the last or even the second-to-last wrapping after adding 'watermelon' without having to manually moving things around?

Basically, a feature that would "unwrap and rewrap" my code would solve it.

1 Answers

Found that it's a setting in PyCharm, under:

Settings -> Editor -> Python -> Keep when reformatting -> Line breaks

If I uncheck that, Ctrl+Shift+L completely rewraps the text.

Related