From 1aeb7028ae771cd771be55de6d46ceff39ce8402 Mon Sep 17 00:00:00 2001 From: X Code Date: Sat, 18 Dec 2021 18:02:04 -0800 Subject: [PATCH] Refactor code of ResolveLineFormatRule - no logic change --- lib/src/models/rules/format.dart | 57 ++++++++++++++++++-------------- 1 file changed, 33 insertions(+), 24 deletions(-) diff --git a/lib/src/models/rules/format.dart b/lib/src/models/rules/format.dart index d757e92d..634808e4 100644 --- a/lib/src/models/rules/format.dart +++ b/lib/src/models/rules/format.dart @@ -40,42 +40,51 @@ class ResolveLineFormatRule extends FormatRule { result.retain(op.length!); continue; } - final text = op.data as String; - final tmp = Delta(); - var offset = 0; - - final removedBlocks = _getRemovedBlocks(attribute, op); - - for (var lineBreak = text.indexOf('\n'); - lineBreak >= 0; - lineBreak = text.indexOf('\n', offset)) { - tmp - ..retain(lineBreak - offset) - ..retain(1, attribute.toJson()..addEntries(removedBlocks)); - offset = lineBreak + 1; - } - tmp.retain(text.length - offset); - result = result.concat(tmp); - } + final delta = _applyAttribute(opText, op, attribute); + result = result.concat(delta); + } + // And include extra newline after retain while (itr.hasNext) { op = itr.next(); - final text = op.data is String ? (op.data as String?)! : ''; - final lineBreak = text.indexOf('\n'); - if (lineBreak < 0) { + final opText = op.data is String ? op.data as String : ''; + final lf = opText.indexOf('\n'); + if (lf < 0) { result.retain(op.length!); continue; } - final removedBlocks = _getRemovedBlocks(attribute, op); - result - ..retain(lineBreak) - ..retain(1, attribute.toJson()..addEntries(removedBlocks)); + final delta = _applyAttribute(opText, op, attribute, firstOnly: true); + result = result.concat(delta); break; } return result; } + Delta _applyAttribute(String text, Operation op, Attribute attribute, + {bool firstOnly = false}) { + final result = Delta(); + var offset = 0; + var lf = text.indexOf('\n'); + final removedBlocks = _getRemovedBlocks(attribute, op); + while (lf >= 0) { + final actualStyle = attribute.toJson()..addEntries(removedBlocks); + result + ..retain(lf - offset) + ..retain(1, actualStyle); + + if (firstOnly) { + return result; + } + + offset = lf + 1; + lf = text.indexOf('\n', offset); + } + // Retain any remaining characters in text + result.retain(text.length - offset); + return result; + } + Iterable> _getRemovedBlocks( Attribute attribute, Operation op) { // Enforce Block Format exclusivity by rule