GuntherRademacher / rr

RR - Railroad Diagram Generator
Apache License 2.0
483 stars 49 forks source link

Add Index and/or TOC #16

Open manticore-projects opened 2 years ago

manticore-projects commented 2 years ago

Greetings.

Please, would it be possible to add an Index and/or TOC to the HTML output in order to navigate in very long HTML files with a lot of productions.

Example: http://manticore-projects.com/JSQLFormatter/syntax.html#

I have post-added this by parsing the XHTML file via XPATH. It works somehow, but yields in an extra step and the heavy JSOUP/SAXON dependencies.


    private static String stripTrailing(String s, String suffix) {
        if (s.endsWith(suffix))
            return s.substring(0, s.length() - suffix.length());
        else
            return s;
    }

    public static void insertTOC(File file) throws IOException {
        System.setProperty(W3CDom.XPathFactoryProperty, "net.sf.saxon.xpath.XPathFactoryImpl");

        Document doc = Jsoup.parse(file, "UTF-8", "", Parser.xmlParser());
        Elements elements = doc.selectXpath("//*[local-name()='a' and not(@href) and @name]");

        ArrayList<String> tocEntries = new ArrayList<>();
        TreeSet<String> indexEntries = new TreeSet<>();

        for (Element link : elements) {
            String key = stripTrailing(link.text(), ":");
            tocEntries.add(key);
            indexEntries.add(key);
        }

        Element tocElement = doc.body().prependElement("H1");
        tocElement.text("Table of Content:");
        tocElement.attr("style", "font-size: 14px; font-weight:bold");

        Element pElement = tocElement.appendElement("p");
        pElement.attr("style", "font-size: 11px; font-weight:normal");
        for (String s : tocEntries) {
            pElement.appendElement("a").attr("href", "#" + s).text(s);
            pElement.appendText(" ");
        }

        Element indexElement = doc.body().prependElement("H1");
        indexElement.text("Index:");
        indexElement.attr("style", "font-size: 14px; font-weight:bold");

        pElement = indexElement.appendElement("p");
        pElement.attr("style", "font-size: 11px; font-weight:normal");
        for (String s : indexEntries) {
            pElement.appendElement("a").attr("href", "#" + s).text(s);
            pElement.appendText(" ");
        }

        FileUtils.writeStringToFile(file, doc.outerHtml(), StandardCharsets.UTF_8);
    }