Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:markdown/markdown.dart' as md;

/// Parses markdown code blocks (indentation or fenced) into paragraphs.
/// This prevents code blocks from being dropped if the editor doesn't support them,
/// and effectively strips indentation from 4-space indented blocks (as per md spec).
class MarkdownSoftCodeBlockParser extends CustomMarkdownParser {
const MarkdownSoftCodeBlockParser();

@override
List<Node> transform(
md.Node node,
List<CustomMarkdownParser> parsers, {
MarkdownListType listType = MarkdownListType.unknown,
int? startNumber,
}) {
if (node is md.Element && node.tag == 'pre') {
String text = '';

if (node.children?.isNotEmpty == true) {
final codeNode = node.children!.first;
if (codeNode is md.Element && codeNode.tag == 'code') {
text = codeNode.textContent;
} else {
text = node.textContent;
}
} else {
text = node.textContent;
}

// Remove trailing newline which code blocks often have
if (text.endsWith('\n')) {
text = text.substring(0, text.length - 1);
}

// Split into multiple lines and create a paragraph for each
// This effectively "flattens" the code block into text
final lines = text.split('\n');
return lines.map((line) => paragraphNode(text: line)).toList();
}
return [];
}
}
1 change: 1 addition & 0 deletions lib/src/plugins/markdown/decoder/parser/parser.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export 'custom_markdown_node_parser.dart';
export 'markdown_block_quote_parser.dart';
export 'markdown_divider_parser.dart';
export 'markdown_soft_code_block_parser.dart';
export 'markdown_heading_parser.dart';
export 'markdown_image_parser.dart';
export 'markdown_ordered_list_item_parser.dart';
Expand Down
1 change: 1 addition & 0 deletions lib/src/plugins/markdown/document_markdown.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ Document markdownToDocument(
markdownParsers: [
...markdownParsers,
const MarkdownParagraphParserV2(),
const MarkdownSoftCodeBlockParser(),
const MarkdownHeadingParserV2(),
const MarkdownTodoListParserV2(),
const MarkdownUnorderedListParserV2(),
Expand Down
Loading