Folding all h1 (or h2 or h3...) headings at once

How about a keyboard shortcut to fold all h1 (or h2 or h3) level headings at once?

For example, something like ⌘ + 1 would toggle between folding and expanding all h1 level headings. The same goes for ⌘ + 2 for h2 and so on.

Those shortcuts are already mapped to marking the current line as a h1 or h2.

But here’s an applescript that I think will do what you want:

tell application "FoldingText"
  tell front document
    evaluate script "function(editor, options) {
      var tree = editor.tree(),
        each = tree.firstLineNode();
      editor.operation(function() {
        while (each) {
          if (each.type() === 'heading' && each.typeIndentLevel() === options.level) {
          each = each.nextLineNode();
    }" with options {level:1}
  end tell
end tell

It clears all folds, and then folds heading nodes with an indent level matching the passed in “level”. In the script right now level:1 meaning “#” headings are folded. If you change it to level:2 then “##” headings will be folded.


There is also this plugin, which creates two keyboard shortcuts:

  • Collapse whole document one more level ⌘⌥-
  • Expand whole document one more level ⌘⌥+

(Not only hash headings, but also all lists and sublists in the document are folded/unfolded to level N+1, or N-1)