Code folding with Regions in Python using Kate

I once again ended up having to edit a somewhat large Python file. Since I don’t believe in Clean Code’s methodology of splitting things up into thousands of micro-functions and then having to pass tons of variables around as arguments all the time, I’m actually happy with that. Also it’s kinda what code folding was invented for. Unfortunately I usually don’t find it all that helpful, because it doesn’t fold the way I want it to.

I like what C# does with #region and #endregion, where you can freely define a section of code to be folded away, exactly how it makes sense to you the human, who this feature is designed for, rather than the machine that gets to execute the code and thinks in different patterns than you do.

So, I found a way to enable Kate to do this in Python. Here’s how.

First of all, grab a copy of the most recent syntax highlighting definition for Python from upstream. Create a directory named ~/.local/share/org.kde.syntax-highlighting/syntax/ on your machine running Kate and pop it in there.

The lines that Kate’s syntax definition for C# uses to implement the #region feature are these:

<StringDetect attribute="Decimal" context="Decimal" String="#region" beginRegion="Region1"/>
<StringDetect attribute="Decimal" context="Decimal" String="#endregion" endRegion="Region1"/>

Copy those lines verbatim into your shiny new python.xml file, somewhere around where the context for Normal Text is defined:

<contexts>
    <context name="Normal" attribute="Normal Text" lineEndContext="#stay">
        <DetectSpaces attribute="Normal Text"/>

        <StringDetect attribute="Decimal" context="Decimal" String="#region" beginRegion="Region1"/>
        <StringDetect attribute="Decimal" context="Decimal" String="#endregion" endRegion="Region1"/>

        <DetectChar attribute="Normal Text" char="(" context="Tuple" beginRegion="Tuple"/>
        <!-- etc -->

Optionally, at the end of the file, change this line:

<folding indentationsensitive="1" />

to indentationsensitive="0" to reduce the number of folding markers the editor displays.

Restart Kate, and that’s it, you’re good to go :)