Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pycharm code reformatting: align lines by operator

In Jetbrains Pycharm (Professional, 2016.1), is there a way (built in or third-party) to modify the code style in python to align consecutive lines by an operator, particularly an assignment one? For example, I would like

var1 = 5
variable2 = 10
varbl3 = 15

to be reformatted to

var1      = 5
variable2 = 10
varbl3    = 15

I am aware of several packages that let me do this manually with an external command (I am currently using Front-End Alignment, but String Manupulation also works decently), but it precludes me from also using code reformatting (which I otherwise find very useful) on the same piece of code.

I am aware this does not follow PEP-8 standards, and I don't wish to have a debate about the merits/demerits of aligning code. Is there a way to allow the reformat code option to automatically take care of this for me?

like image 864
Ben Bartlett Avatar asked Jun 28 '16 17:06

Ben Bartlett


People also ask

How do I align codes in PyCharm?

While in the editor, select the necessary code fragment and press Ctrl+Alt+I . If you need to adjust indentation settings, in the Settings/Preferences dialog ( Ctrl+Alt+S ), go to Editor | Code Style. On the appropriate language page, on the Tabs and Indents tab, specify the appropriate indents options and click OK.

How do I change the format in PyCharm?

Reformat File dialog The dialog appears when you press Ctrl+Alt+Shift+L in the editor of the current file. If you choose Code | Reformat Code from the main menu or press Ctrl+Alt+L , PyCharm tries to reformat the source code of the specified scope automatically.

How do you fix the line too long in PyCharm?

To configure the line length, open settings Ctrl+Alt+S , navigate to Editor | Code Style, and type the necessary length in the Hard wrap at N columns field.


1 Answers

To my knowledge, there isn't an automatic way.

That said, something I found very helpful is "Add multiline carets on double ⌥ (Option key) with arrow keys" (found in General>Smart Keys) along with "Move Caret to Next Word".

  1. Put the cursor on line 1, double tap ⌥ and hold then press the down arrow the number of lines to edit.

  2. Let go of ⌥ (to get Pycharm out of 'add more cursors mode') then using "Move Caret to Next Word" ⌥→ move the cursors just before the = on each line.

  3. Add a bunch of spaces till all the equal signs are past the alignment point.

  4. Put the cursors back to the start of the line to get them aligned again.

  5. Move them to the alignment point.

  6. Shift ⌥ → to highlight the space up to the =.

  7. Then backspace to line everything up.

** I'm on mac, so the keys are going to be different for other OS.

like image 64
Marcel Wilson Avatar answered Oct 09 '22 13:10

Marcel Wilson