Add back serializeDocumentToMarkdown
This commit is contained in:
parent
4b06e9cabe
commit
390a7b393f
|
|
@ -31,6 +31,75 @@ MutableDocument deserializeMarkdownToDocument(String markdown) {
|
|||
return MutableDocument(nodes: nodeVisitor.content);
|
||||
}
|
||||
|
||||
String serializeDocumentToMarkdown(Document doc) {
|
||||
final StringBuffer buffer = StringBuffer();
|
||||
|
||||
bool isFirstLine = true;
|
||||
for (int i = 0; i < doc.nodes.length; ++i) {
|
||||
final node = doc.nodes[i];
|
||||
|
||||
if (!isFirstLine) {
|
||||
// Create a new line to encode the given node.
|
||||
buffer.writeln('');
|
||||
} else {
|
||||
isFirstLine = false;
|
||||
}
|
||||
|
||||
if (node is ImageNode) {
|
||||
buffer.write('');
|
||||
} else if (node is HorizontalRuleNode) {
|
||||
buffer.write('---');
|
||||
} else if (node is ListItemNode) {
|
||||
final indent = List.generate(node.indent + 1, (index) => ' ').join('');
|
||||
final symbol = node.type == ListItemType.unordered ? '*' : '1.';
|
||||
|
||||
buffer.write('$indent$symbol ${node.text.toMarkdown()}');
|
||||
|
||||
final nodeBelow = i < doc.nodes.length - 1 ? doc.nodes[i + 1] : null;
|
||||
if (nodeBelow != null && (nodeBelow is! ListItemNode)) {
|
||||
// This list item is the last item in the list. Add an extra
|
||||
// blank line after it.
|
||||
buffer.writeln('');
|
||||
}
|
||||
} else if (node is ParagraphNode) {
|
||||
final Attribution blockType = node.getMetadataValue('blockType');
|
||||
|
||||
if (blockType == header1Attribution) {
|
||||
buffer.write('# ${node.text.toMarkdown()}');
|
||||
} else if (blockType == header2Attribution) {
|
||||
buffer.write('## ${node.text.toMarkdown()}');
|
||||
} else if (blockType == header3Attribution) {
|
||||
buffer.write('### ${node.text.toMarkdown()}');
|
||||
} else if (blockType == header4Attribution) {
|
||||
buffer.write('#### ${node.text.toMarkdown()}');
|
||||
} else if (blockType == header5Attribution) {
|
||||
buffer.write('##### ${node.text.toMarkdown()}');
|
||||
} else if (blockType == header6Attribution) {
|
||||
buffer.write('###### ${node.text.toMarkdown()}');
|
||||
} else if (blockType == blockquoteAttribution) {
|
||||
// TODO: handle multiline
|
||||
buffer.write('> ${node.text.toMarkdown()}');
|
||||
} else if (blockType == codeAttribution) {
|
||||
buffer //
|
||||
..writeln('```') //
|
||||
..writeln(node.text.toMarkdown()) //
|
||||
..write('```');
|
||||
} else {
|
||||
buffer.write(node.text.toMarkdown());
|
||||
}
|
||||
|
||||
// Separates paragraphs with blank lines.
|
||||
// If we are at the last node we don't add a trailing
|
||||
// blank line.
|
||||
if (i != doc.nodes.length - 1) {
|
||||
buffer.writeln();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
/// Converts structured markdown to a list of [DocumentNode]s.
|
||||
///
|
||||
/// To use [_MarkdownToDocument], obtain a series of markdown
|
||||
|
|
|
|||
Loading…
Reference in New Issue