package bamboo.task;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.regex.Pattern;

public class HeadingContentHandler extends DefaultHandler {
    private static Pattern WHITESPACE_RE = Pattern.compile("\\s+");
    private StringBuilder text = new StringBuilder();
    private int depth = 0;

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if (depth > 0 || localName.equals("h1")) {
            depth++;
            if (text.length() != 0) {
                text.append(" ");
            }
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if (depth > 0) {
            depth--;
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        if (depth > 0) {
            text.append(ch, start, length);
        }
    }

    @Override
    public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
        if (depth > 0) {
            text.append(ch, start, length);
        }
    }

    public String getText() {
        return WHITESPACE_RE.matcher(text).replaceAll(" ");
    }
}

@@ -364,16 +364,60 @@
 pth = 0;
+%0A    private boolean sawAnyHeadings = false;
 %0A%0A    @O
@@ -614,16 +614,51 @@
 epth++;%0A
+            sawAnyHeadings = true;%0A
         
@@ -1323,24 +1323,58 @@
 getText() %7B%0A
+        if (sawAnyHeadings) %7B%0A    
         retu
@@ -1417,20 +1417,72 @@
 ceAll(%22 %22);%0A
+        %7D else %7B%0A            return null;%0A        %7D%0A
     %7D%0A%7D%0A

Set h1 to null if no headings are present