Folding Python code

Since we're working with Python code throughout this book, let's play with some folds in our code. First, you'll need to change a setting called foldmethod to indent in your .vimrc file:

set foldmethod=indent
Don't forget to reload your ~/.vimrc file by either restarting Vim or executing :source $MYVIMRC.

This will tell Vim to fold based on indentation (there are multiple ways to work with folds; see the following section, Types of folds, for more information).

Open animal_farm.py and you will see portions of our file folded away:

Navigate your cursor to one of the folded lines. Hitting zo will open the current fold:

Whenever your cursor is over a potential fold (an indented chunk of code in this example), zc will close the fold.

To visualize where folds are, you can use :set foldcolumn=N, where N is 0..12. This will dedicate the first N columns to the left of the screen to indicate folds with the - (beginning of an open fold), | (contents of an open fold), and + (closed fold) symbols.

You can also use za to toggle folds (open closed folds and close open folds).

You can open and close all folds in the file at the same time using zR and zM, respectively.

Setting an automatic foldmethod setting (such as indent) will display all files as folded by default. It's a matter of preference, and you may prefer to have the folds open when opening a new file. Adding autocmd BufRead * normal zR to your .vimrc file will keep the folds open as you open new files. This command tells Vim to execute zR (open all folds) when reading a buffer.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.42.94