17
17
package io .spring .javaformat .formatter ;
18
18
19
19
import java .util .Map ;
20
+ import java .util .regex .Matcher ;
21
+ import java .util .regex .Pattern ;
20
22
21
23
import org .eclipse .jface .text .IRegion ;
22
24
import org .eclipse .text .edits .TextEdit ;
@@ -56,6 +58,11 @@ public class Formatter {
56
58
*/
57
59
private static final int DEFAULT_INDENTATION_LEVEL = 0 ;
58
60
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
+
59
66
/**
60
67
* The default line separator.
61
68
*/
@@ -123,6 +130,9 @@ public TextEdit format(String source, int offset, int length, String lineSeparat
123
130
124
131
public TextEdit format (int kind , String source , int offset , int length , int indentationLevel ,
125
132
String lineSeparator ) {
133
+ if (lineSeparator == null ) {
134
+ lineSeparator = detectLineSeparator (source );
135
+ }
126
136
return this .delegate .format (kind , source , offset , length , indentationLevel , lineSeparator );
127
137
}
128
138
@@ -148,6 +158,9 @@ public TextEdit format(String source, IRegion[] regions, String lineSeparator) {
148
158
}
149
159
150
160
public TextEdit format (int kind , String source , IRegion [] regions , int indentationLevel , String lineSeparator ) {
161
+ if (lineSeparator == null ) {
162
+ lineSeparator = detectLineSeparator (source );
163
+ }
151
164
return this .delegate .format (kind , source , regions , indentationLevel , lineSeparator );
152
165
}
153
166
@@ -159,4 +172,17 @@ public void setOptions(Map<String, String> options) {
159
172
this .delegate .setOptions (options );
160
173
}
161
174
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
+ }
162
188
}
0 commit comments