Skip to content

Commit 16276f5

Browse files
[markdown] Simplify deindentation logic for fenced code block lines (#2187)
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
1 parent 2ef298e commit 16276f5

File tree

2 files changed

+21
-6
lines changed

2 files changed

+21
-6
lines changed

pkgs/markdown/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
(https://dart-lang.github.io/tools).
55
* Update `package:web` API references in the example.
66
* Fix performance and correctness of HTML comment parser.
7+
* Optimize indentation processing of fenced code blocks.
78
* Require Dart `^3.4.0`.
89

910
## 7.3.0

pkgs/markdown/lib/src/block_syntaxes/fenced_code_block_syntax.dart

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import '../ast.dart';
66
import '../block_parser.dart';
7+
import '../charcode.dart' show $space;
78
import '../line.dart';
89
import '../patterns.dart';
910
import '../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

100114
class _FenceMatch {

0 commit comments

Comments
 (0)