Skip to content

Commit

Permalink
Only compute line ending when match is found
Browse files Browse the repository at this point in the history
  • Loading branch information
nielsdebruin committed Dec 11, 2024
1 parent 4c375f9 commit 988c910
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 11 deletions.
15 changes: 9 additions & 6 deletions rewrite-core/src/main/java/org/openrewrite/text/Find.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
Expand Down Expand Up @@ -92,8 +91,8 @@ public String getDescription() {
@Nullable
String filePattern;

private static LinkedList<Integer> findAllNewLineIndexes(String input) {
LinkedList<Integer> indexes = new LinkedList<>();
private static List<Integer> findAllNewLineIndexes(String input) {
List<Integer> indexes = new ArrayList<>();
int index = input.indexOf('\n'); // Find the first occurrence

while (index != -1) {
Expand Down Expand Up @@ -142,17 +141,21 @@ public Tree visit(@Nullable Tree tree, ExecutionContext ctx) {
List<PlainText.Snippet> snippets = new ArrayList<>();
int previousEnd = 0;

LinkedList<Integer> newlineIndexes = findAllNewLineIndexes(rawText);
List<Integer> newlineIndexes = null;
int lastNewLineIndex = -1;

while (matcher.find()) {
if (newlineIndexes == null) {
newlineIndexes = findAllNewLineIndexes(rawText);
}

int matchStart = matcher.start();
snippets.add(snippet(rawText.substring(previousEnd, matchStart)));
snippets.add(SearchResult.found(snippet(rawText.substring(matchStart, matcher.end()))));
previousEnd = matcher.end();

while (!newlineIndexes.isEmpty() && newlineIndexes.peek() < matchStart) {
lastNewLineIndex = newlineIndexes.pop();
while (!newlineIndexes.isEmpty() && newlineIndexes.get(0) < matchStart) {
lastNewLineIndex = newlineIndexes.remove(0);
}
int startLine = Math.max(0, lastNewLineIndex + 1);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ void regexWithoutMultilineAndDotall() {
)
);
}

@Test
void regexMatchingWhitespaceWithoutMultilineWithDotall() {
rewriteRun(
Expand All @@ -154,11 +155,6 @@ void regexMatchingWhitespaceWithoutMultilineWithDotall() {
Zero
One Two
Three
""",
"""
Zero
~~>One Two
Three
"""
)
);
Expand Down

0 comments on commit 988c910

Please sign in to comment.