44
55import '../ast.dart' ;
66import '../block_parser.dart' ;
7+ import '../charcode.dart' show $space;
78import '../line.dart' ;
89import '../patterns.dart' ;
910import '../util.dart' ;
@@ -50,11 +51,6 @@ class FencedCodeBlockSyntax extends BlockSyntax {
5051 return Element ('pre' , [code]);
5152 }
5253
53- String _removeIndentation (String content, int length) {
54- final text = content.replaceFirst (RegExp ('^\\ s{0,$length }' ), '' );
55- return content.substring (content.length - text.length);
56- }
57-
5854 @override
5955 List <Line > parseChildLines (
6056 BlockParser parser, [
@@ -76,7 +72,7 @@ class FencedCodeBlockSyntax extends BlockSyntax {
7672 ! closingFence.marker.startsWith (openingMarker) ||
7773 closingFence.hasInfo) {
7874 childLines.add (
79- Line (_removeIndentation (parser.current.content, indent)),
75+ Line (_removeLeadingSpaces (parser.current.content, upTo : indent)),
8076 );
8177 parser.advance ();
8278 } else {
@@ -95,6 +91,24 @@ class FencedCodeBlockSyntax extends BlockSyntax {
9591
9692 return childLines;
9793 }
94+
95+ /// Removes the leading spaces (` ` ) from [content] up the given [upTo] count.
96+ static String _removeLeadingSpaces (String content, {required int upTo}) {
97+ var leadingSpacesCount = 0 ;
98+
99+ // Find the index of the first non-space character
100+ // or the first space after the maximum removed specified by 'upTo'.
101+ while (leadingSpacesCount < upTo && leadingSpacesCount < content.length) {
102+ // We can just check for space (` `) since fenced code blocks
103+ // consider spaces before the opening code fence as the
104+ // indentation that should be removed.
105+ if (content.codeUnitAt (leadingSpacesCount) != $space) {
106+ break ;
107+ }
108+ leadingSpacesCount += 1 ;
109+ }
110+ return content.substring (leadingSpacesCount);
111+ }
98112}
99113
100114class _FenceMatch {
0 commit comments