Breaking long line in vim using macro

Formatting your source code can be a daunting task even modern IDE’s cannot always auto format your code correctly. One special case here is breaking long lines in python. Python is a special case here because indention matters. Using the following macro it is quite easy to format long lines easily.

Imagine you have the following lines of code

class SomeClass:
    def __init__(self):
        self.available_columns = (
'dummy', 'dummy', 'dummy',  'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy', 'dummy'
            )

You now want to properly format the dictionary available_columns that it does not go over 80 lines and fits indention. To do so open your vim and position you cursor at the beginning of the first dummy. Then press qq to start recording the macro. Press I to get into insert mode. Then indent the line pressing 3 times tab. Then go to column 79 by leaving insert mode by pressing esc and press 79 followed by the pipe symbol |. Next search for the nearest comma to your left by typing slash / and then comma , press shift + n to get the nearest comma to your left. Then go one right by using right arrow and get into insert mode again. Last but not least hit enter. Now leave the macro mode by pressing q again. Then replay the macro by pressing the at symbol and q @q.

Leave a Reply

Your email address will not be published. Required fields are marked *