Skip to content

Commit e1be3d5

Browse files
committed
Preserve existing eol by default
1 parent 5c10ade commit e1be3d5

File tree

1 file changed

+26
-0
lines changed
  • spring-javaformat/spring-javaformat-formatter/src/main/java/io/spring/javaformat/formatter

1 file changed

+26
-0
lines changed

spring-javaformat/spring-javaformat-formatter/src/main/java/io/spring/javaformat/formatter/Formatter.java

+26
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
package io.spring.javaformat.formatter;
1818

1919
import java.util.Map;
20+
import java.util.regex.Matcher;
21+
import java.util.regex.Pattern;
2022

2123
import org.eclipse.jface.text.IRegion;
2224
import org.eclipse.text.edits.TextEdit;
@@ -56,6 +58,11 @@ public class Formatter {
5658
*/
5759
private static final int DEFAULT_INDENTATION_LEVEL = 0;
5860

61+
/**
62+
* Pattern that matches all line separators into named-capturing group "sep".
63+
*/
64+
private static final Pattern LINE_SEPARATOR_PATTERN = Pattern.compile("(?<sep>(\r\n|\r|\n))");
65+
5966
/**
6067
* The default line separator.
6168
*/
@@ -123,6 +130,9 @@ public TextEdit format(String source, int offset, int length, String lineSeparat
123130

124131
public TextEdit format(int kind, String source, int offset, int length, int indentationLevel,
125132
String lineSeparator) {
133+
if (lineSeparator == null) {
134+
lineSeparator = detectLineSeparator(source);
135+
}
126136
return this.delegate.format(kind, source, offset, length, indentationLevel, lineSeparator);
127137
}
128138

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

150160
public TextEdit format(int kind, String source, IRegion[] regions, int indentationLevel, String lineSeparator) {
161+
if (lineSeparator == null) {
162+
lineSeparator = detectLineSeparator(source);
163+
}
151164
return this.delegate.format(kind, source, regions, indentationLevel, lineSeparator);
152165
}
153166

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

175+
private String detectLineSeparator(String contents) {
176+
Matcher matcher = LINE_SEPARATOR_PATTERN.matcher(contents);
177+
if (!matcher.find()) {
178+
return DEFAULT_LINE_SEPARATOR;
179+
}
180+
String firstMatch = matcher.group("sep");
181+
while (matcher.find()) {
182+
if (!matcher.group("sep").equals(firstMatch)) {
183+
return DEFAULT_LINE_SEPARATOR;
184+
}
185+
}
186+
return firstMatch;
187+
}
162188
}

0 commit comments

Comments
 (0)