All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.houbb.md.escape.util.MdEscapeHelper Maven / Gradle / Ivy

The newest version!
package com.github.houbb.md.escape.util;

import com.github.houbb.heaven.util.lang.StringUtil;
import org.apache.commons.text.StringEscapeUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author binbin.hou
 * @since 1.0.0
 */
public class MdEscapeHelper {

    private MdEscapeHelper(){}

    /**
     * 执行转换
     * @param mdContent 文本内容
     * @return 结果
     */
    public static String escape(final String mdContent) {
        if(StringUtil.isEmptyTrim(mdContent)) {
            return mdContent;
        }

        List lines = StringUtil.contentToLines(mdContent);

        List escapeLines = escapeLines(lines);
        return StringUtil.linesToContent(escapeLines);
    }

    /**
     * 1. 代码块保持不变
     * 2. 引用保持不变。
     * @param lines 行
     * @return 结果
     */
    private static List escapeLines(List lines) {
        List results = new ArrayList<>(lines.size());

        boolean isInPreCode = false;
        for(String line : lines) {
            String trim = StringUtil.trim(line);
            if(line.startsWith("   ")) {
                results.add(line);
            } else {
                if(isInPreCode) {
                    results.add(line);
                } else {
                    if(trim.startsWith(">")) {
                        int index = line.indexOf('>');
                        String before = line.substring(0, index+1);
                        String after = line.substring(index+1);
                        String newLine = before + StringEscapeUtils.escapeHtml4(after);
                        results.add(newLine);
                    } else {
                        results.add(StringEscapeUtils.escapeHtml4(line));
                    }
                }

                // 执行变换
                if(trim.startsWith("```")) {
                    isInPreCode = !isInPreCode;
                }
            }
        }
        return results;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy