Decent Python Code Folding in TextMate
Posted: July 16th, 2009 | Author: Alex | Filed under: Computers | 2 Comments »
TextMate is a great editor, and Python is a great programming languages, but they both have their limitations.
One of TextMate’s nicer features is code folding, which allows you to collapse a block of code (a function, a conditional block, etc.) down to a single line in the editor. This often makes a large piece of code much easier to navigate. TextMate determines where code can be folded by evaluating each line of the code and tagging particular lines with start and end markers.
Doing code folding for Python in this method (only considering a single line at a time) is impossible, since the only clear end of a function in Python is a reduction in indentation level on the next line. For example, here’s a function in C followed by a statement:
int foo(int value) {
printf("%d", value + 5);
}
foo(24);
Here’s the same code written in Python:
def foo(value): print "%d" % (value + 5) foo(24)
As you can see, if you look at the code one line at a time, it’s not clear where the definition of foo in Python ends, whereas the closing curly brace (}) is clearly the end of foo’s definition in C.
By default, TextMate punts: it defines the start of a function or class definition as the start of a foldable region and the first subsequent blank line as the end of that foldable region. This doesn’t really work well, because function definitions without any blank lines aren’t really readable past a certain size.
There is, however, a way to hack your way around this issue. Another of TextMate’s killer features is that you can customize almost everything, including the definition for a given language.
Open the Language Editor through the “Bundles > Bundle Editor >Edit Languages …” menu item (as of TextMate 1.5.8, anyway).
Pull up the language editor for Python, find a line that looks like this:
foldingStopMarker = '^\s*$|^\s*\}|^\s*\]|^\s*\)|^\s*"""\s*$';
and replace it with this:
foldingStopMarker = '^\s*#\s*END_DEF ([a-zA-Z0-9_<]+)';
Now, if you want to fold a function definition in Python, stick a comment at the end of it:
def foo(value): print "%d" % (value + 5) #END_DEF foo
Hope fully this helps out some of you who are using TextMate for Python programming.