clean Markdown - Java java.lang

Java examples for java.lang:String Markdown

Description

clean Markdown

Demo Code

/*/*w w w  .j  av  a2s  .  co m*/
 *  This file is part of Pegdoc, the documentation generator
 *  
 *  Copyright (C) 2014  Christoph Engelbert (noctarius), Hazelcast, Inc.
 *
 *  Pegdoc is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
//package com.java2s;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.StringReader;

public class Main {
    public static String cleanMarkdown(String markdown) throws IOException {

        boolean newLineBefore = false;
        boolean insideCode = false;
        boolean justLeftCodeblock = false;

        LineNumberReader lnr = new LineNumberReader(new StringReader(
                markdown));
        StringBuilder sb = new StringBuilder(markdown.length());

        String line;
        while ((line = lnr.readLine()) != null) {
            String temp = line.trim();

            if (justLeftCodeblock && !newLineBefore) {
                sb.append("\n");
            }
            justLeftCodeblock = false;

            if (temp.startsWith("```")) {
                insideCode = !insideCode;

                if (insideCode && !newLineBefore) {
                    sb.append('\n');
                } else if (!insideCode) {
                    justLeftCodeblock = true;
                }
                sb.append('\n').append(temp);
            } else {
                sb.append('\n').append(line);
            }

            newLineBefore = temp.length() == 0;
        }

        return sb.toString();
    }
}

Related Tutorials