FairEmail/app/src/main/java/eu/faircode/email/Markdown.java

63 lines
2.2 KiB
Java
Raw Normal View History

2024-02-19 15:06:44 +00:00
package eu.faircode.email;
/*
This file is part of FairEmail.
FairEmail 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
(at your option) any later version.
FairEmail 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 FairEmail. If not, see <http://www.gnu.org/licenses/>.
Copyright 2018-2024 by Marcel Bokhorst (M66B)
*/
2024-02-20 09:59:17 +00:00
import com.vladsch.flexmark.html2md.converter.FlexmarkHtmlConverter;
2024-02-20 11:35:01 +00:00
import com.vladsch.flexmark.util.data.DataHolder;
import com.vladsch.flexmark.util.data.MutableDataSet;
2024-02-20 09:59:17 +00:00
2024-02-20 07:54:20 +00:00
import org.commonmark.Extension;
import org.commonmark.ext.gfm.strikethrough.StrikethroughExtension;
import org.commonmark.ext.gfm.tables.TablesExtension;
2024-02-19 15:06:44 +00:00
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
2024-02-20 07:54:20 +00:00
import java.util.Arrays;
import java.util.List;
2024-02-19 15:06:44 +00:00
public class Markdown {
static String toHtml(String markdown) {
2024-02-20 09:56:33 +00:00
markdown = markdown.replace('\u00a0', ' ');
2024-02-20 07:54:20 +00:00
List<Extension> extensions = Arrays.asList(
TablesExtension.create(),
StrikethroughExtension.create());
Parser p = Parser.builder()
.extensions(extensions)
.build();
2024-02-19 15:06:44 +00:00
Node d = p.parse(markdown);
2024-02-20 07:54:20 +00:00
HtmlRenderer r = HtmlRenderer.builder()
.extensions(extensions)
.build();
2024-02-19 15:06:44 +00:00
return r.render(d);
}
2024-02-20 09:56:33 +00:00
static String fromHtml(String html) {
2024-02-20 09:59:17 +00:00
// https://github.com/vsch/flexmark-java/wiki/Extensions#html-to-markdown
2024-02-20 11:35:01 +00:00
DataHolder options = new MutableDataSet()
.set(FlexmarkHtmlConverter.SETEXT_HEADINGS, false)
.toImmutable();
String markdown = FlexmarkHtmlConverter.builder(options)
2024-02-20 09:59:17 +00:00
.build()
.convert(html);
return markdown.replaceAll("\n\n\\s+<!-- -->\n", "");
2024-02-19 15:06:44 +00:00
}
}