Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Detect and preserve line separators instead of using system default #340

Closed
wants to merge 6 commits into from
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Preserve existing eol by default
  • Loading branch information
ParkerM committed Feb 15, 2023
commit b0c889f48342ac035d700f1c53752267582a3818
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
package io.spring.javaformat.formatter;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.jface.text.IRegion;
import org.eclipse.text.edits.TextEdit;
Expand Down Expand Up @@ -56,6 +58,11 @@ public class Formatter {
*/
private static final int DEFAULT_INDENTATION_LEVEL = 0;

/**
* Pattern that matches all line separators into named-capturing group "sep".
*/
private static final Pattern LINE_SEPARATOR_PATTERN = Pattern.compile("(?<sep>(\r\n|\r|\n))");

/**
* The default line separator.
*/
Expand Down Expand Up @@ -123,6 +130,9 @@ public TextEdit format(String source, int offset, int length, String lineSeparat

public TextEdit format(int kind, String source, int offset, int length, int indentationLevel,
String lineSeparator) {
if (lineSeparator == null) {
lineSeparator = detectLineSeparator(source);
}
return this.delegate.format(kind, source, offset, length, indentationLevel, lineSeparator);
}

Expand All @@ -148,6 +158,9 @@ public TextEdit format(String source, IRegion[] regions, String lineSeparator) {
}

public TextEdit format(int kind, String source, IRegion[] regions, int indentationLevel, String lineSeparator) {
if (lineSeparator == null) {
lineSeparator = detectLineSeparator(source);
}
return this.delegate.format(kind, source, regions, indentationLevel, lineSeparator);
}

Expand All @@ -159,4 +172,17 @@ public void setOptions(Map<String, String> options) {
this.delegate.setOptions(options);
}

private String detectLineSeparator(String contents) {
Matcher matcher = LINE_SEPARATOR_PATTERN.matcher(contents);
if (!matcher.find()) {
return DEFAULT_LINE_SEPARATOR;
}
String firstMatch = matcher.group("sep");
while (matcher.find()) {
if (!matcher.group("sep").equals(firstMatch)) {
return DEFAULT_LINE_SEPARATOR;
}
}
return firstMatch;
}
}