4
4
5
5
import '../ast.dart' ;
6
6
import '../block_parser.dart' ;
7
+ import '../charcode.dart' show $space;
7
8
import '../line.dart' ;
8
9
import '../patterns.dart' ;
9
10
import '../util.dart' ;
@@ -50,11 +51,6 @@ class FencedCodeBlockSyntax extends BlockSyntax {
50
51
return Element ('pre' , [code]);
51
52
}
52
53
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
-
58
54
@override
59
55
List <Line > parseChildLines (
60
56
BlockParser parser, [
@@ -76,7 +72,7 @@ class FencedCodeBlockSyntax extends BlockSyntax {
76
72
! closingFence.marker.startsWith (openingMarker) ||
77
73
closingFence.hasInfo) {
78
74
childLines.add (
79
- Line (_removeIndentation (parser.current.content, indent)),
75
+ Line (_removeLeadingSpaces (parser.current.content, upTo : indent)),
80
76
);
81
77
parser.advance ();
82
78
} else {
@@ -95,6 +91,24 @@ class FencedCodeBlockSyntax extends BlockSyntax {
95
91
96
92
return childLines;
97
93
}
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
+ }
98
112
}
99
113
100
114
class _FenceMatch {
0 commit comments