21
21
import java .util .Collections ;
22
22
import java .util .Map ;
23
23
import java .util .Properties ;
24
+ import java .util .regex .MatchResult ;
25
+ import java .util .regex .Matcher ;
26
+ import java .util .regex .Pattern ;
24
27
25
28
import org .eclipse .jdt .core .formatter .CodeFormatter ;
26
29
import org .eclipse .jface .text .IRegion ;
@@ -116,6 +119,9 @@ public TextEdit format(String source, int offset, int length, String lineSeparat
116
119
@ Override
117
120
public TextEdit format (int kind , String source , int offset , int length , int indentationLevel ,
118
121
String lineSeparator ) {
122
+ if (lineSeparator == null ) {
123
+ lineSeparator = detectLineSeparator (source );
124
+ }
119
125
return this .delegate .format (kind , source , offset , length , indentationLevel , lineSeparator );
120
126
}
121
127
@@ -142,6 +148,9 @@ public TextEdit format(String source, IRegion[] regions, String lineSeparator) {
142
148
143
149
@ Override
144
150
public TextEdit format (int kind , String source , IRegion [] regions , int indentationLevel , String lineSeparator ) {
151
+ if (lineSeparator == null ) {
152
+ lineSeparator = detectLineSeparator (source );
153
+ }
145
154
return this .delegate .format (kind , source , regions , indentationLevel , lineSeparator );
146
155
}
147
156
@@ -201,4 +210,18 @@ private static void applyConfig(Properties properties, JavaFormatConfig javaForm
201
210
202
211
}
203
212
213
+ private String detectLineSeparator (String contents ) {
214
+ Pattern newlinePattern = Pattern .compile ("(?<sep>\r ?\n )$" , Pattern .MULTILINE );
215
+ Matcher matcher = newlinePattern .matcher (contents );
216
+ if (!matcher .find ()) {
217
+ return DEFAULT_LINE_SEPARATOR ;
218
+ }
219
+ String firstMatch = matcher .group ("sep" );
220
+ while (matcher .find ()) {
221
+ if (!matcher .group ("sep" ).equals (firstMatch )) {
222
+ return Formatter .DEFAULT_LINE_SEPARATOR ;
223
+ }
224
+ }
225
+ return firstMatch ;
226
+ }
204
227
}
0 commit comments