pegdown 怎样自定义标签

  cheney

    这两天正在改写一个论坛系统,后台markdown转换使用 pegdown ,但是 pegdown 转的 code 比前台转的 code 外层少一层 pre 标签。查文档说是支持自定义标签的。

    If you’d like to customize the rendering of HTML links (Auto-Links, Explicit-Links, Mail-Links, Reference-Links and/or Wiki-Links), e.g. for adding rel=“nofollow” attributes based on some logic you can supply your own instance of a LinkRenderer with the call to markdownToHtml.

    没有找到示例,自己去翻 LinkRenderer 的代码,还是不明白怎么自定义。但是发现 PegDownProcessor 调用的是 ToHtmlSerializer
    ToHtmlSerializer 的 152 行:

    public void visit(CodeNode node) {
        this.printTag((TextNode)node, "code");
    }
    

    既然已经这样了,那么写插件也不好写了,不如直接替换掉它。于是暴力解决

    package club.fullstack.bbs.util;
    
    import com.sun.org.apache.xpath.internal.SourceTree;
    import org.pegdown.*;
    import org.pegdown.ast.CodeNode;
    import org.pegdown.ast.RootNode;
    import org.pegdown.ast.TextNode;
    
    import java.util.Collections;
    import java.util.Map;
    
    /**
     * Created by Cheney on 2016/3/31.
     */
    public class Markdown {
    
        public static void main(String[] args) {
            PegDownProcessor pp = new MyPegDownProcessor();
            String content = pp.markdownToHtml("```test```");
            System.out.println(content);
        }
    }
    
    
    
    class MyToHtmlSerializer extends ToHtmlSerializer{
    
        public MyToHtmlSerializer(LinkRenderer linkRenderer, Map<String, VerbatimSerializer> verbatimSerializers) {
            super(linkRenderer, verbatimSerializers);
        }
    
        public void visit(CodeNode node) {
            this.printer.print("<pre><code>");
            this.printer.printEncoded(node.getText());
            this.printer.print("</code></pre>");
        }
    }
    
    class MyPegDownProcessor extends PegDownProcessor {
        public String markdownToHtml(char[] markdownSource, LinkRenderer linkRenderer, Map<String, VerbatimSerializer> verbatimSerializerMap) {
            try {
                RootNode e = this.parseMarkdown(markdownSource);
                return (new MyToHtmlSerializer(linkRenderer, verbatimSerializerMap)).toHtml(e);
            } catch (ParsingTimeoutException var5) {
                return null;
            }
        }
    }