Skip to main content
summaryrefslogtreecommitdiffstats
blob: 2b34203f45b5cf02399dcdda7479696f0a1e5a01 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
/*******************************************************************************
 * Copyright (c) 2000, 2016 IBM Corporation and others.
 *
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License 2.0
 * which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *     Anton Leherbauer (Wind River Systems)
 *     Sergey Prigogin (Google)
 *******************************************************************************/
package org.eclipse.cdt.internal.formatter;

import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterOptions;
import org.eclipse.cdt.core.parser.util.CharArrayUtils;
import org.eclipse.cdt.internal.formatter.align.Alignment;
import org.eclipse.cdt.internal.formatter.align.AlignmentException;
import org.eclipse.cdt.internal.formatter.scanner.Scanner;
import org.eclipse.cdt.internal.formatter.scanner.Token;
import org.eclipse.jface.text.Position;
import org.eclipse.text.edits.MultiTextEdit;
import org.eclipse.text.edits.ReplaceEdit;
import org.eclipse.text.edits.TextEdit;

/**
 * This class is responsible for dumping formatted source.
 *
 * @since 4.0
 */
public class Scribe {
	private static final String EMPTY_STRING = ""; //$NON-NLS-1$
	private static final String SPACE = " "; //$NON-NLS-1$

	private static final int INITIAL_SIZE = 100;

	private final DefaultCodeFormatterOptions preferences;
	public final Scanner scanner;

	/** one-based column */
	public int column = 1;

	// Most specific alignment.
	public Alignment currentAlignment;
	public Alignment memberAlignment;
	public AlignmentException currentAlignmentException;

	/** @see Alignment#tailFormatter */
	private Runnable tailFormatter;

	public Token currentToken;

	// Edits management
	private OptimizedReplaceEdit[] edits;
	public int editsIndex;

	public int indentationLevel;
	public int numberOfIndentations;
	public int indentationSize;

	private final String lineSeparator;
	private final boolean indentEmptyLines;
	private final int pageWidth;
	private boolean preserveNewLines;
	private boolean checkLineWrapping;
	public int lastNumberOfNewLines;
	private boolean preserveLineBreakIndentation;
	boolean formatBrace;
	public int line;

	public boolean needSpace;
	public boolean pendingSpace;

	public int tabLength;
	public int tabChar;
	private final boolean useTabsOnlyForLeadingIndents;

	private int textRegionEnd;
	private int textRegionStart;
	public int scannerEndPosition;

	private List<Position> fSkipPositions = Collections.emptyList();

	private boolean skipOverInactive;

	private int fSkipStartOffset = Integer.MAX_VALUE;
	private int fSkipEndOffset;
	private int fSkippedIndentations;

	/* Comments formatting */
	private static final int NO_TRAILING_COMMENT = 0x0000;
	private static final int BASIC_TRAILING_COMMENT = 0x0100;
	private int[] lineOffsets;
	private int numLines;

	// Class to store previous line comment information
	static class LineComment {
		boolean contiguous;
		int currentIndentation;
		int indentation;
		int lines;
		char[] leadingSpaces = CharArrayUtils.EMPTY_CHAR_ARRAY;
	}

	final LineComment lastLineComment = new LineComment();

	Scribe(CodeFormatterVisitor formatter, int offset, int length) {
		scanner = new Scanner();
		preferences = formatter.preferences;
		pageWidth = preferences.page_width;
		tabLength = preferences.tab_size;
		indentationLevel = 0; // initialize properly
		numberOfIndentations = 0;
		useTabsOnlyForLeadingIndents = preferences.use_tabs_only_for_leading_indentations;
		indentEmptyLines = preferences.indent_empty_lines;
		tabChar = preferences.tab_char;
		if (tabChar == DefaultCodeFormatterOptions.MIXED) {
			indentationSize = preferences.indentation_size;
		} else {
			indentationSize = tabLength;
		}
		lineSeparator = preferences.line_separator;
		indentationLevel = preferences.initial_indentation_level * indentationSize;
		preserveNewLines = false;
		textRegionStart = offset;
		textRegionEnd = offset + length;
		reset();
	}

	private final void addDeleteEdit(int start, int end) {
		addOptimizedReplaceEdit(start, end - start + 1, EMPTY_STRING);
	}

	public final void addInsertEdit(int insertPosition, CharSequence insertedString) {
		addOptimizedReplaceEdit(insertPosition, 0, insertedString);
	}

	/**
	 * Adds a replace edit.
	 * @param start  start offset (inclusive)
	 * @param end  end offset (inclusive)
	 * @param replacement  the replacement string
	 */
	public final void addReplaceEdit(int start, int end, CharSequence replacement) {
		addOptimizedReplaceEdit(start, end - start + 1, replacement);
	}

	private final void addOptimizedReplaceEdit(int offset, int length, CharSequence replacement) {
		if (edits.length == editsIndex) {
			resize();
		}
		if (editsIndex > 0) {
			// Try to merge last two edits
			final OptimizedReplaceEdit previous = edits[editsIndex - 1];
			final int previousOffset = previous.offset;
			final int previousLength = previous.length;
			final int endOffsetOfPreviousEdit = previousOffset + previousLength;
			final int replacementLength = replacement.length();
			final String previousReplacement = previous.replacement;
			final int previousReplacementLength = previousReplacement.length();
			if (previousOffset == offset && previousLength == length
					&& (replacementLength == 0 || previousReplacementLength == 0)) {
				if (currentAlignment != null) {
					final Location location = currentAlignment.location;
					if (location.editsIndex == editsIndex) {
						location.editsIndex--;
						location.textEdit = previous;
					}
				}
				editsIndex--;
				return;
			}
			if (endOffsetOfPreviousEdit == offset) {
				if (length != 0) {
					if (replacementLength != 0) {
						editsIndex--;
						appendOptimizedReplaceEdit(previousOffset, previousLength + length,
								previousReplacement + replacement);
					} else if (previousLength + length == previousReplacementLength) {
						// Check the characters. If they are identical,
						// we can get rid of the previous edit.
						boolean canBeRemoved = true;
						loop: for (int i = previousOffset; i < previousOffset + previousReplacementLength; i++) {
							if (scanner.source[i] != previousReplacement.charAt(i - previousOffset)) {
								editsIndex--;
								appendOptimizedReplaceEdit(previousOffset, previousReplacementLength,
										previousReplacement);
								canBeRemoved = false;
								break loop;
							}
						}
						if (canBeRemoved) {
							if (currentAlignment != null) {
								final Location location = currentAlignment.location;
								if (location.editsIndex == editsIndex) {
									location.editsIndex--;
									location.textEdit = previous;
								}
							}
							editsIndex--;
						}
					} else {
						editsIndex--;
						appendOptimizedReplaceEdit(previousOffset, previousLength + length, previousReplacement);
					}
				} else {
					if (replacementLength != 0) {
						editsIndex--;
						appendOptimizedReplaceEdit(previousOffset, previousLength, previousReplacement + replacement);
					}
				}
			} else {
				assert endOffsetOfPreviousEdit < offset;
				appendOptimizedReplaceEdit(offset, length, replacement);
			}
		} else {
			appendOptimizedReplaceEdit(offset, length, replacement);
		}
	}

	/**
	 * Trims redundant prefix from a replacement edit and, if there is anything left, appends
	 * the replacement edit to the edits array.
	 */
	private void appendOptimizedReplaceEdit(int offset, int length, CharSequence replacement) {
		int replacementLength = replacement.length();
		int i;
		for (i = 0; i < length && i < replacementLength; i++, offset++) {
			if (scanner.source[offset] != replacement.charAt(i))
				break;
		}
		length -= i;
		if (i > 0) {
			replacement = i == replacementLength ? EMPTY_STRING : replacement.subSequence(i, replacementLength);
		}
		if (length > 0 || replacement.length() > 0) {
			edits[editsIndex++] = new OptimizedReplaceEdit(offset, length, replacement);
		}
	}

	public void alignFragment(Alignment alignment, int fragmentIndex) {
		alignment.alignFragment(fragmentIndex);
	}

	public void consumeNextToken() {
		printComment();
		currentToken = scanner.nextToken();
		addDeleteEdit(scanner.getCurrentTokenStartPosition(), scanner.getCurrentTokenEndPosition());
	}

	public Alignment createAlignment(String name, int mode, int count, int sourceRestart) {
		return createAlignment(name, mode, Alignment.R_INNERMOST, count, sourceRestart);
	}

	public Alignment createAlignment(String name, int mode, int count, int sourceRestart, boolean adjust) {
		return createAlignment(name, mode, Alignment.R_INNERMOST, count, sourceRestart, adjust);
	}

	public Alignment createAlignment(String name, int mode, int tieBreakRule, int count, int sourceRestart) {
		return createAlignment(name, mode, tieBreakRule, count, sourceRestart, preferences.continuation_indentation,
				false);
	}

	public Alignment createAlignment(String name, int mode, int count, int sourceRestart, int continuationIndent,
			boolean adjust) {
		return createAlignment(name, mode, Alignment.R_INNERMOST, count, sourceRestart, continuationIndent, adjust);
	}

	public Alignment createAlignment(String name, int mode, int tieBreakRule, int count, int sourceRestart,
			int continuationIndent, boolean adjust) {
		Alignment alignment = new Alignment(name, mode, tieBreakRule, this, count, sourceRestart, continuationIndent);
		// adjust break indentation
		if (adjust && memberAlignment != null) {
			Alignment current = memberAlignment;
			while (current.enclosing != null) {
				current = current.enclosing;
			}
			if ((current.mode & Alignment.M_MULTICOLUMN) != 0) {
				final int indentSize = indentationSize;
				switch (current.chunkKind) {
				case Alignment.CHUNK_METHOD:
				case Alignment.CHUNK_TYPE:
					if ((mode & Alignment.M_INDENT_BY_ONE) != 0) {
						alignment.breakIndentationLevel = indentationLevel + indentSize;
					} else {
						alignment.breakIndentationLevel = indentationLevel + continuationIndent * indentSize;
					}
					alignment.update();
					break;
				case Alignment.CHUNK_FIELD:
					if ((mode & Alignment.M_INDENT_BY_ONE) != 0) {
						alignment.breakIndentationLevel = current.originalIndentationLevel + indentSize;
					} else {
						alignment.breakIndentationLevel = current.originalIndentationLevel
								+ continuationIndent * indentSize;
					}
					alignment.update();
					break;
				}
			} else {
				switch (current.mode & Alignment.SPLIT_MASK) {
				case Alignment.M_COMPACT_SPLIT:
				case Alignment.M_COMPACT_FIRST_BREAK_SPLIT:
				case Alignment.M_NEXT_PER_LINE_SPLIT:
				case Alignment.M_NEXT_SHIFTED_SPLIT:
				case Alignment.M_ONE_PER_LINE_SPLIT:
					final int indentSize = indentationSize;
					switch (current.chunkKind) {
					case Alignment.CHUNK_METHOD:
					case Alignment.CHUNK_TYPE:
						if ((mode & Alignment.M_INDENT_BY_ONE) != 0) {
							alignment.breakIndentationLevel = indentationLevel + indentSize;
						} else {
							alignment.breakIndentationLevel = indentationLevel + continuationIndent * indentSize;
						}
						alignment.update();
						break;
					case Alignment.CHUNK_FIELD:
						if ((mode & Alignment.M_INDENT_BY_ONE) != 0) {
							alignment.breakIndentationLevel = current.originalIndentationLevel + indentSize;
						} else {
							alignment.breakIndentationLevel = current.originalIndentationLevel
									+ continuationIndent * indentSize;
						}
						alignment.update();
						break;
					}
					break;
				}
			}
		}
		return alignment;
	}

	public Alignment createMemberAlignment(String name, int mode, int count, int sourceRestart) {
		Alignment alignment = createAlignment(name, mode, Alignment.R_INNERMOST, count, sourceRestart);
		alignment.breakIndentationLevel = indentationLevel;
		return alignment;
	}

	public void enterAlignment(Alignment alignment) {
		alignment.enclosing = currentAlignment;
		currentAlignment = alignment;
	}

	public void enterMemberAlignment(Alignment alignment) {
		alignment.enclosing = memberAlignment;
		memberAlignment = alignment;
	}

	public void exitAlignment(Alignment alignment, boolean discardAlignment) {
		Alignment current = currentAlignment;
		while (current != null) {
			if (current == alignment)
				break;
			current = current.enclosing;
		}
		if (current == null) {
			throw new AbortFormatting("could not find matching alignment: " + alignment); //$NON-NLS-1$
		}
		indentationLevel = alignment.location.outputIndentationLevel;
		numberOfIndentations = alignment.location.numberOfIndentations;
		if (discardAlignment) {
			currentAlignment = alignment.enclosing;
		}
	}

	public void exitMemberAlignment(Alignment alignment) {
		Alignment current = memberAlignment;
		while (current != null) {
			if (current == alignment)
				break;
			current = current.enclosing;
		}
		if (current == null) {
			throw new AbortFormatting("could not find matching alignment: " + alignment); //$NON-NLS-1$
		}
		indentationLevel = current.location.outputIndentationLevel;
		numberOfIndentations = current.location.numberOfIndentations;
		memberAlignment = current.enclosing;
	}

	public Alignment getAlignment(String name) {
		if (currentAlignment != null) {
			return currentAlignment.getAlignment(name);
		}
		return null;
	}

	private int getIndentationOfOffset(int offset) {
		int beginningOfLine = getLineStart(offset);
		int indent = 0;
		for (int i = beginningOfLine; i < offset; i++) {
			indent = computeIndentation(scanner.source[i], indent);
		}
		return indent;
	}

	/**
	 * Computes indentation after applying a character at a given indentation position.
	 * @param text the text to be applied.
	 * @param indent the initial indentation.
	 * @return the resulting indentation.
	 */
	private int computeIndentation(char c, int indent) {
		switch (c) {
		case '\t':
			return tabLength > 0 ? indent + tabLength - indent % tabLength : indent;
		case '\r':
		case '\n':
			return 0;
		default:
			return indent + 1;
		}
	}

	/**
	 * Computes indentation after applying a given text at a given indentation position.
	 * @param text the text to be applied.
	 * @param indent the initial indentation.
	 * @return the resulting indentation.
	 */
	private int computeIndentation(char[] text, int indent) {
		if (text == null)
			return indent;
		int length = text.length;
		for (int i = 0; i < length; i++) {
			indent = computeIndentation(text[i], indent);
		}
		return indent;
	}

	private int computeIndentation(CharSequence text, int indent) {
		if (text == null)
			return indent;
		int length = text.length();
		for (int i = 0; i < length; i++) {
			indent = computeIndentation(text.charAt(i), indent);
		}
		return indent;
	}

	public String getEmptyLines(int linesNumber) {
		StringBuilder buffer = new StringBuilder();
		if (lastNumberOfNewLines == 0) {
			linesNumber++; // add an extra line breaks
			for (int i = 0; i < linesNumber; i++) {
				if (indentEmptyLines)
					printIndentationIfNecessary(buffer);
				buffer.append(lineSeparator);
			}
			lastNumberOfNewLines += linesNumber;
			line += linesNumber;
			column = 1;
			needSpace = false;
			pendingSpace = false;
		} else if (lastNumberOfNewLines == 1) {
			for (int i = 0; i < linesNumber; i++) {
				if (indentEmptyLines)
					printIndentationIfNecessary(buffer);
				buffer.append(lineSeparator);
			}
			lastNumberOfNewLines += linesNumber;
			line += linesNumber;
			column = 1;
			needSpace = false;
			pendingSpace = false;
		} else {
			if ((lastNumberOfNewLines - 1) >= linesNumber) {
				// there is no need to add new lines
				return EMPTY_STRING;
			}
			final int realNewLineNumber = linesNumber - lastNumberOfNewLines + 1;
			for (int i = 0; i < realNewLineNumber; i++) {
				if (indentEmptyLines)
					printIndentationIfNecessary(buffer);
				buffer.append(lineSeparator);
			}
			lastNumberOfNewLines += realNewLineNumber;
			line += realNewLineNumber;
			column = 1;
			needSpace = false;
			pendingSpace = false;
		}
		return String.valueOf(buffer);
	}

	public OptimizedReplaceEdit getLastEdit() {
		if (editsIndex > 0) {
			return edits[editsIndex - 1];
		}
		return null;
	}

	Alignment getMemberAlignment() {
		return memberAlignment;
	}

	public String getNewLine() {
		if (lastNumberOfNewLines >= 1) {
			column = 1; // Ensure that the scribe is at the beginning of a new line
			return EMPTY_STRING;
		}
		line++;
		lastNumberOfNewLines = 1;
		column = 1;
		needSpace = false;
		pendingSpace = false;
		return lineSeparator;
	}

	/**
	 * Returns next indentation level based on column estimated position (if
	 * column is not indented, then uses indentationLevel)
	 */
	public int getNextIndentationLevel(int someColumn) {
		int indent = someColumn - 1;
		if (indent == 0)
			return indentationLevel;
		if (tabChar == DefaultCodeFormatterOptions.TAB && !useTabsOnlyForLeadingIndents) {
			// Round up to a multiple of indentationSize.
			indent += indentationSize - 1;
			return indent - indent % indentationSize;
		} else {
			return indent;
		}
	}

	private String getPreserveEmptyLines(int count) {
		if (count == 0 && !preserveNewLines) {
			// preserve line breaks in wrapping if specified
			if (!preferences.join_wrapped_lines && lastNumberOfNewLines == 0) {
				// Create new line
				StringBuilder tempBuffer = new StringBuilder();
				tempBuffer.append(getNewLine());

				if (currentAlignment != null && !formatBrace) {
					indentationLevel = currentAlignment.breakIndentationLevel;
				}

				// Set the flag to indicate that a specific indentation is currently in used
				preserveLineBreakIndentation = true;

				// Print the computed indentation in the buffer
				printIndentationIfNecessary(tempBuffer);

				return tempBuffer.toString();
			}
			return EMPTY_STRING;
		}
		if (preferences.number_of_empty_lines_to_preserve != 0) {
			int linesToPreserve = Math.min(count, preferences.number_of_empty_lines_to_preserve);
			return getEmptyLines(linesToPreserve);
		} else if (preserveNewLines) {
			return getNewLine();
		}
		return EMPTY_STRING;
	}

	public TextEdit getRootEdit() {
		MultiTextEdit edit = null;
		int length = textRegionEnd - textRegionStart;
		if (textRegionStart <= 0) {
			if (length <= 0) {
				edit = new MultiTextEdit(0, 0);
			} else {
				edit = new MultiTextEdit(0, textRegionEnd);
			}
		} else {
			edit = new MultiTextEdit(textRegionStart, length);
		}
		for (int i = 0, max = editsIndex; i < max; i++) {
			OptimizedReplaceEdit currentEdit = edits[i];
			if (isValidEdit(currentEdit)) {
				edit.addChild(new ReplaceEdit(currentEdit.offset, currentEdit.length, currentEdit.replacement));
			}
		}
		edits = null;
		return edit;
	}

	public void handleLineTooLong() {
		// Search for closest breakable alignment, using tie-breaking rules.
		// Look for innermost breakable one.
		int relativeDepth = 0;
		Alignment targetAlignment = currentAlignment;
		while (targetAlignment != null && targetAlignment.tieBreakRule == Alignment.R_INNERMOST) {
			if (targetAlignment.couldBreak()) {
				throwAlignmentException(AlignmentException.LINE_TOO_LONG, relativeDepth);
			}
			targetAlignment = targetAlignment.enclosing;
			relativeDepth++;
		}

		// Look for outermost breakable one.
		relativeDepth = 0;
		int outerMostDepth = -1;
		targetAlignment = currentAlignment;
		while (targetAlignment != null) {
			if (targetAlignment.tieBreakRule == Alignment.R_OUTERMOST && targetAlignment.couldBreak()) {
				outerMostDepth = relativeDepth;
			}
			targetAlignment = targetAlignment.enclosing;
			relativeDepth++;
		}
		if (outerMostDepth >= 0) {
			throwAlignmentException(AlignmentException.LINE_TOO_LONG, outerMostDepth);
		}

		// Look for innermost breakable one but don't stop if we encounter a R_OUTERMOST
		// tie-breaking rule.
		relativeDepth = 0;
		targetAlignment = currentAlignment;
		while (targetAlignment != null) {
			if (targetAlignment.couldBreak()) {
				throwAlignmentException(AlignmentException.LINE_TOO_LONG, relativeDepth);
			}
			targetAlignment = targetAlignment.enclosing;
			relativeDepth++;
		}
		// Did not find any breakable location - proceed
	}

	private void throwAlignmentException(int kind, int relativeDepth) {
		AlignmentException e = new AlignmentException(kind, relativeDepth);
		currentAlignmentException = e;
		throw e;
	}

	public void indent() {
		if (shouldSkip(scanner.getCurrentPosition())) {
			fSkippedIndentations++;
			return;
		}
		indentationLevel += indentationSize;
		numberOfIndentations++;
	}

	/**
	 * @param translationUnitSource
	 */
	public void initializeScanner(char[] translationUnitSource) {
		scanner.setSource(translationUnitSource);
		scannerEndPosition = translationUnitSource.length;
		scanner.resetTo(0, scannerEndPosition);
		edits = new OptimizedReplaceEdit[INITIAL_SIZE];
		// Locate line breaks.
		lineOffsets = new int[200];
		numLines = 0;
		lineOffsets[numLines++] = 0;
		for (int i = 0; i < translationUnitSource.length; i++) {
			if (translationUnitSource[i] == '\n') {
				int len = lineOffsets.length;
				if (numLines >= len)
					System.arraycopy(lineOffsets, 0, lineOffsets = new int[len + (len + 1) / 2], 0, len);
				lineOffsets[numLines++] = i + 1;
			}
		}
	}

	/**
	 * @param list
	 */
	public void setSkipPositions(List<Position> list) {
		fSkipPositions = list;
		skipOverInactive = !list.isEmpty();
	}

	/**
	 * Returns offset of the start of the line containing a given offset.
	 */
	private int getLineStart(int offset) {
		// Binary search
		int down = 0;
		int up = numLines;
		while (true) {
			int mid = (down + up) / 2;
			int lineOffset = lineOffsets[mid];
			if (mid == down) {
				return lineOffset;
			}
			if (lineOffset > offset) {
				up = mid;
			} else {
				down = mid;
			}
		}
	}

	private boolean isOnFirstColumn(int offset) {
		return getLineStart(offset) == offset;
	}

	private boolean isValidEdit(OptimizedReplaceEdit edit) {
		final int editLength = edit.length;
		final int editReplacementLength = edit.replacement.length();
		final int editOffset = edit.offset;
		if (editLength != 0) {
			if (textRegionStart <= editOffset && editOffset + editLength <= textRegionEnd) {
				if (editReplacementLength != 0 && editLength == editReplacementLength) {
					for (int i = editOffset, max = editOffset + editLength; i < max; i++) {
						if (scanner.source[i] != edit.replacement.charAt(i - editOffset)) {
							return true;
						}
					}
					return false;
				} else {
					return true;
				}
			} else if (editOffset + editLength == textRegionStart) {
				int i = editOffset;
				for (int max = editOffset + editLength; i < max; i++) {
					int replacementStringIndex = i - editOffset;
					if (replacementStringIndex >= editReplacementLength
							|| scanner.source[i] != edit.replacement.charAt(replacementStringIndex)) {
						break;
					}
				}
				if (i - editOffset != editReplacementLength && i != editOffset + editLength - 1) {
					edit.offset = textRegionStart;
					edit.length = 0;
					edit.replacement = edit.replacement.substring(i - editOffset);
					return true;
				}
			}
		} else if (textRegionStart <= editOffset && editOffset < textRegionEnd) {
			return true;
		} else if (editOffset == scannerEndPosition && editOffset == textRegionEnd) {
			return true;
		}
		return false;
	}

	private void preserveEmptyLines(int count, int insertPosition) {
		if (count > 0) {
			if (preferences.number_of_empty_lines_to_preserve != 0) {
				int linesToPreserve = Math.min(count, preferences.number_of_empty_lines_to_preserve);
				printEmptyLines(linesToPreserve, insertPosition);
			} else {
				printNewLine(insertPosition);
			}
		} else {
			printNewLine(insertPosition);
		}
	}

	public void printRaw(int startOffset, int length) {
		if (length <= 0) {
			return;
		}
		int currentPosition = scanner.getCurrentPosition();
		if (shouldSkip(currentPosition)) {
			return;
		}
		if (startOffset > currentPosition) {
			printComment();
			currentPosition = scanner.getCurrentPosition();
		}
		if (startOffset + length < currentPosition) {
			return; // Don't move backwards
		}
		boolean savedPreserveNL = preserveNewLines;
		boolean savedSkipOverInactive = skipOverInactive;
		int savedScannerEndPos = scannerEndPosition;
		preserveNewLines = true;
		skipOverInactive = false;
		scannerEndPosition = startOffset + length;
		try {
			scanner.resetTo(Math.max(startOffset, currentPosition), startOffset + length);
			int parenLevel = 0;
			while (true) {
				boolean hasWhitespace = printComment();
				currentToken = scanner.nextToken();
				if (currentToken == null) {
					if (hasWhitespace) {
						space();
					}
					break;
				}
				if (pendingSpace) {
					addInsertEdit(scanner.getCurrentTokenStartPosition(), SPACE);
					pendingSpace = false;
					needSpace = false;
				}
				switch (currentToken.type) {
				case Token.tLBRACE: {
					scanner.resetTo(scanner.getCurrentTokenStartPosition(), scannerEndPosition);
					formatOpeningBrace(preferences.brace_position_for_block,
							preferences.insert_space_before_opening_brace_in_block);
					if (preferences.indent_statements_compare_to_block) {
						indent();
					}
					break;
				}
				case Token.tRBRACE: {
					scanner.resetTo(scanner.getCurrentTokenStartPosition(), scannerEndPosition);
					if (preferences.indent_statements_compare_to_block) {
						unIndent();
					}
					formatClosingBrace(preferences.brace_position_for_block);
					break;
				}
				case Token.tLPAREN:
					++parenLevel;
					print(currentToken.getLength(), hasWhitespace);
					if (parenLevel > 0) {
						indentForContinuation();
						if (column <= indentationLevel) {
							// HACK: avoid indent in same line
							column = indentationLevel + 1;
						}
					}
					break;
				case Token.tRPAREN:
					--parenLevel;
					if (parenLevel >= 0) {
						unIndentForContinuation();
					}
					print(currentToken.getLength(), hasWhitespace);
					break;
				case Token.tSEMI:
					print(currentToken.getLength(), preferences.insert_space_before_semicolon);
					break;
				case Token.t_catch:
				case Token.t_else:
					if (preferences.insert_new_line_before_else_in_if_statement) {
						printNewLine(currentToken.offset);
					} else {
						hasWhitespace = true;
					}
					print(currentToken.getLength(), hasWhitespace);
					break;
				default:
					if (currentToken.isVisibilityModifier()
							&& !preferences.indent_access_specifier_compare_to_type_header) {
						int indentLevel = indentationLevel;
						if (indentationLevel > 0)
							unIndent();
						print(currentToken.getLength(), hasWhitespace);
						while (indentationLevel < indentLevel) {
							indent();
						}
					} else {
						print(currentToken.getLength(), hasWhitespace);
					}
				}
				hasWhitespace = false;
			}
		} finally {
			scannerEndPosition = savedScannerEndPos;
			scanner.resetTo(startOffset + length, scannerEndPosition);
			skipOverInactive = savedSkipOverInactive;
			preserveNewLines = savedPreserveNL;
		}
	}

	public void indentForContinuation() {
		for (int i = 0; i < preferences.continuation_indentation; i++) {
			indent();
		}
	}

	public void unIndentForContinuation() {
		for (int i = 0; i < preferences.continuation_indentation; i++) {
			unIndent();
		}
	}

	public void formatOpeningBrace(String bracePosition, boolean insertSpaceBeforeBrace) {
		if (DefaultCodeFormatterConstants.NEXT_LINE.equals(bracePosition)) {
			printNewLine();
		} else if (DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED.equals(bracePosition)) {
			printNewLine();
			indent();
		}
		printNextToken(Token.tLBRACE, insertSpaceBeforeBrace);

		printTrailingComment();
	}

	public void formatClosingBrace(String block_brace_position) {
		printNextToken(Token.tRBRACE);
		printTrailingComment();
		if (DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED.equals(block_brace_position)) {
			unIndent();
		}
	}

	private void print(int length, boolean considerSpaceIfAny) {
		if (checkLineWrapping && length + column - 1 > pageWidth) {
			handleLineTooLong();
		}
		lastNumberOfNewLines = 0;
		if (indentationLevel != 0) {
			printIndentationIfNecessary();
		}
		if (considerSpaceIfAny) {
			space();
		}
		if (pendingSpace) {
			addInsertEdit(scanner.getCurrentTokenStartPosition(), SPACE);
		}
		if (checkLineWrapping && length + column - 1 > pageWidth) {
			handleLineTooLong();
		}
		pendingSpace = false;
		column += length;
		needSpace = true;
	}

	private void printBlockComment(boolean forceNewLine) {
		int currentTokenStartPosition = scanner.getCurrentTokenStartPosition();
		int currentTokenEndPosition = scanner.getCurrentTokenEndPosition() + 1;

		scanner.resetTo(currentTokenStartPosition, currentTokenEndPosition);
		int currentCharacter;
		boolean isNewLine = false;
		int start = currentTokenStartPosition;
		int nextCharacterStart = currentTokenStartPosition;
		printIndentationIfNecessary();
		if (pendingSpace) {
			addInsertEdit(currentTokenStartPosition, SPACE);
		}
		needSpace = false;
		pendingSpace = false;
		int previousStart = currentTokenStartPosition;

		while (nextCharacterStart <= currentTokenEndPosition && (currentCharacter = scanner.getNextChar()) != -1) {
			nextCharacterStart = scanner.getCurrentPosition();

			switch (currentCharacter) {
			case '\r':
				if (isNewLine) {
					line++;
				}
				start = previousStart;
				isNewLine = true;
				if (scanner.getNextChar('\n')) {
					currentCharacter = '\n';
					nextCharacterStart = scanner.getCurrentPosition();
				}
				break;
			case '\n':
				if (isNewLine) {
					line++;
				}
				start = previousStart;
				isNewLine = true;
				break;
			default:
				if (isNewLine) {
					if (Character.isWhitespace((char) currentCharacter)) {
						int previousStartPosition = scanner.getCurrentPosition();
						while (currentCharacter != -1 && currentCharacter != '\r' && currentCharacter != '\n'
								&& Character.isWhitespace((char) currentCharacter)) {
							previousStart = nextCharacterStart;
							previousStartPosition = scanner.getCurrentPosition();
							currentCharacter = scanner.getNextChar();
							nextCharacterStart = scanner.getCurrentPosition();
						}
						if (currentCharacter == '\r' || currentCharacter == '\n') {
							nextCharacterStart = previousStartPosition;
						}
					}
					column = 1;
					line++;

					StringBuilder buffer = new StringBuilder();
					buffer.append(lineSeparator);
					printIndentationIfNecessary(buffer);
					buffer.append(' ');

					addReplaceEdit(start, previousStart - 1, String.valueOf(buffer));
				} else {
					column += (nextCharacterStart - previousStart);
				}
				isNewLine = false;
			}
			previousStart = nextCharacterStart;
			scanner.setCurrentPosition(nextCharacterStart);
		}
		lastNumberOfNewLines = 0;
		needSpace = false;
		scanner.resetTo(currentTokenEndPosition, scannerEndPosition);
		if (forceNewLine) {
			startNewLine();
		}
	}

	private void printPreprocessorDirective() {
		int currentTokenStartPosition = scanner.getCurrentTokenStartPosition();
		int currentTokenEndPosition = scanner.getCurrentTokenEndPosition() + 1;

		scanner.resetTo(currentTokenStartPosition, currentTokenEndPosition);
		int currentCharacter;
		boolean isNewLine = false;
		int nextCharacterStart = currentTokenStartPosition;
		needSpace = false;
		pendingSpace = false;
		int previousStart = currentTokenStartPosition;

		while (nextCharacterStart <= currentTokenEndPosition && (currentCharacter = scanner.getNextChar()) != -1) {
			nextCharacterStart = scanner.getCurrentPosition();

			switch (currentCharacter) {
			case '\r':
				isNewLine = true;
				if (scanner.getNextChar('\n')) {
					currentCharacter = '\n';
					nextCharacterStart = scanner.getCurrentPosition();
				}
				break;
			case '\n':
				isNewLine = true;
				break;
			default:
				if (isNewLine) {
					column = 1;
					line++;
				} else {
					column += (nextCharacterStart - previousStart);
				}
				isNewLine = false;
			}
			previousStart = nextCharacterStart;
			scanner.setCurrentPosition(nextCharacterStart);
		}
		lastNumberOfNewLines = isNewLine ? 1 : 0;
		needSpace = false;
		if (currentAlignment != null) {
			indentationLevel = currentAlignment.breakIndentationLevel;
		}
		scanner.resetTo(currentTokenEndPosition, scannerEndPosition);
	}

	public void printEndOfTranslationUnit() {
		int currentTokenStartPosition = scanner.getCurrentPosition();
		if (currentTokenStartPosition <= scannerEndPosition) {
			printRaw(currentTokenStartPosition, scannerEndPosition - currentTokenStartPosition + 1);
		}
	}

	public boolean printComment() {
		return printComment(NO_TRAILING_COMMENT);
	}

	/**
	 * Prints comment at the current position.
	 *
	 * @return {@code true} if a writespace character was encountered preceding the next token,
	 */
	public boolean printComment(int trailing) {
		// If we have a space between two tokens we ensure it will be dumped in the formatted
		// string.
		int currentTokenStartPosition = scanner.getCurrentPosition();
		if (shouldSkip(currentTokenStartPosition)) {
			return false;
		}
		boolean hasComment = false;
		boolean hasLineComment = false;
		boolean hasWhitespace = false;
		char[] whiteSpaces = CharArrayUtils.EMPTY_CHAR_ARRAY;
		int lines = 0;
		while ((currentToken = scanner.nextToken()) != null) {
			if (skipOverInactive) {
				Position inactivePos = getInactivePosAt(scanner.getCurrentTokenStartPosition());
				if (inactivePos != null) {
					int startOffset = Math.min(scanner.getCurrentTokenStartPosition(), inactivePos.getOffset());
					int endOffset = Math.min(scannerEndPosition, inactivePos.getOffset() + inactivePos.getLength());
					if (startOffset < endOffset) {
						int savedIndentLevel = indentationLevel;
						scanner.resetTo(scanner.getCurrentTokenStartPosition(), scanner.eofPosition);
						printRaw(startOffset, endOffset - startOffset);
						while (indentationLevel > savedIndentLevel) {
							unIndent();
						}
						while (indentationLevel < savedIndentLevel) {
							indent();
						}
						scanner.resetTo(endOffset, scanner.eofPosition);
						continue;
					}
				}
			}
			int tokenStartPosition = scanner.getCurrentTokenStartPosition();
			switch (currentToken.type) {
			case Token.tWHITESPACE:
				whiteSpaces = scanner.getCurrentTokenSource();
				int whitespacesEndPosition = scanner.getCurrentTokenEndPosition();
				lines = 0;
				for (int i = 0, max = whiteSpaces.length; i < max; i++) {
					switch (whiteSpaces[i]) {
					case '\r':
						if ((i + 1) < max) {
							if (whiteSpaces[i + 1] == '\n') {
								i++;
							}
						}
						lines++;
						break;
					case '\n':
						lines++;
					}
				}
				// If following token is a line comment on the same line or the line just after,
				// then it might be not really formatted as a trailing comment.
				boolean realTrailing = trailing != NO_TRAILING_COMMENT;
				if (realTrailing && scanner.peekNextChar() == '/' && lines == 0) {
					boolean canChangeTrailing = false;
					// For basic trailing comment preceded by a line comment, then it depends on
					// the comments relative position when following comment column (after having
					// been rounded) is below the preceding one, then it becomes not a good idea
					// to change the trailing flag.
					if (trailing == BASIC_TRAILING_COMMENT && hasLineComment) {
						int currentCommentIndentation = computeIndentation(whiteSpaces, 0);
						int relativeIndentation = currentCommentIndentation - lastLineComment.currentIndentation;
						if (tabLength == 0) {
							canChangeTrailing = relativeIndentation == 0;
						} else {
							canChangeTrailing = relativeIndentation > -tabLength;
						}
					}
					// If the trailing can be changed, then look at the following tokens.
					if (canChangeTrailing) {
						int currentTokenPosition = scanner.getCurrentTokenStartPosition();
						if (scanner.getNextToken() == Token.tLINECOMMENT) {
							realTrailing = !hasLineComment;
							switch (scanner.getNextToken()) {
							case Token.tLINECOMMENT:
								// At least two contiguous line comments.
								// The formatter should not consider comments as trailing ones.
								realTrailing = false;
								break;
							case Token.tWHITESPACE:
								if (scanner.getNextToken() == Token.tLINECOMMENT) {
									// At least two contiguous line comments.
									// The formatter should not consider comments as trailing ones.
									realTrailing = false;
								}
								break;
							}
						}
						scanner.resetTo(currentTokenPosition, scanner.eofPosition);
						scanner.getNextToken(); // Get current token again to restore the scanner state.
					}
				}
				// Strategy to consume spaces and eventually leave at this stage
				// depends on the fact that a trailing comment is expected or not
				if (realTrailing) {
					// If a line comment is consumed, no other comment can be on the same line after
					if (hasLineComment) {
						if (lines >= 1) {
							currentTokenStartPosition = tokenStartPosition;
							preserveEmptyLines(lines, currentTokenStartPosition);
							addDeleteEdit(currentTokenStartPosition, whitespacesEndPosition);
							scanner.resetTo(scanner.getCurrentPosition(), scannerEndPosition);
							return hasWhitespace;
						}
						scanner.resetTo(currentTokenStartPosition, scannerEndPosition);
						return hasWhitespace;
					}
					// If one or several new lines are consumed, following comments
					// cannot be considered as trailing ones.
					if (lines >= 1) {
						if (hasComment) {
							printNewLine(tokenStartPosition);
						}
						scanner.resetTo(currentTokenStartPosition, scannerEndPosition);
						return hasWhitespace;
					}
					// Delete consumed white spaces
					hasWhitespace = true;
					currentTokenStartPosition = scanner.getCurrentPosition();
					addDeleteEdit(tokenStartPosition, whitespacesEndPosition);
				} else {
					if (lines == 0) {
						hasWhitespace = true;
						addDeleteEdit(scanner.getCurrentTokenStartPosition(), scanner.getCurrentTokenEndPosition());
					} else if (hasComment) {
						if (lines == 1) {
							printNewLine(scanner.getCurrentTokenStartPosition());
						} else {
							preserveEmptyLines(lines - 1, scanner.getCurrentTokenStartPosition());
						}
						addDeleteEdit(scanner.getCurrentTokenStartPosition(), scanner.getCurrentTokenEndPosition());
					} else if (hasLineComment) {
						preserveEmptyLines(lines, scanner.getCurrentTokenStartPosition());
						addDeleteEdit(scanner.getCurrentTokenStartPosition(), scanner.getCurrentTokenEndPosition());
					} else if (lines != 0 && (!preferences.join_wrapped_lines
							|| preferences.number_of_empty_lines_to_preserve != 0)) {
						String preservedEmptyLines = getPreserveEmptyLines(lines - 1);
						addReplaceEdit(scanner.getCurrentTokenStartPosition(), scanner.getCurrentTokenEndPosition(),
								preservedEmptyLines);
						hasWhitespace = preservedEmptyLines.length() == 0;
					} else {
						addDeleteEdit(scanner.getCurrentTokenStartPosition(), scanner.getCurrentTokenEndPosition());
						hasWhitespace = true;
					}
				}
				currentTokenStartPosition = scanner.getCurrentPosition();
				break;
			case Token.tLINECOMMENT:
				if (lines >= 1) {
					if (lines > 1) {
						preserveEmptyLines(lines - 1, scanner.getCurrentTokenStartPosition());
					} else if (lines == 1) {
						printNewLine(scanner.getCurrentTokenStartPosition());
					}
				} else if (hasWhitespace) {
					// Look whether comments line may be contiguous or not
					// Note that when preceding token is a comment line, then only one line
					// is enough to have an empty line as the line end is included in the comment line.
					// If comments are contiguous, store the white spaces to be able to compute
					// the current comment indentation
					if (lines > 1 || (lines == 1 && hasLineComment)) {
						lastLineComment.contiguous = false;
					}
					lastLineComment.leadingSpaces = whiteSpaces;
					lastLineComment.lines = lines;
				}
				whiteSpaces = CharArrayUtils.EMPTY_CHAR_ARRAY;
				hasWhitespace = false;
				printLineComment();
				currentTokenStartPosition = scanner.getCurrentPosition();
				hasLineComment = true;
				lines = 0;
				break;
			case Token.tBLOCKCOMMENT:
				if (lines >= 1) {
					if (lines > 1) {
						preserveEmptyLines(lines - 1, scanner.getCurrentTokenStartPosition());
					} else if (lines == 1) {
						printNewLine(scanner.getCurrentTokenStartPosition());
					}
				} else if (hasWhitespace) {
					space();
				}
				whiteSpaces = CharArrayUtils.EMPTY_CHAR_ARRAY;
				hasWhitespace = false;
				printBlockComment(false);
				currentTokenStartPosition = scanner.getCurrentPosition();
				hasLineComment = false;
				hasComment = true;
				lines = 0;
				break;
			case Token.tPREPROCESSOR:
			case Token.tPREPROCESSOR_DEFINE:
			case Token.tPREPROCESSOR_INCLUDE:
				if (column != 1)
					printNewLine(scanner.getCurrentTokenStartPosition());
				if (lines >= 1) {
					if (lines > 1) {
						preserveEmptyLines(lines - 1, scanner.getCurrentTokenStartPosition());
					} else if (lines == 1) {
						// printNewLine(scanner.getCurrentTokenStartPosition());
					}
				}
				whiteSpaces = CharArrayUtils.EMPTY_CHAR_ARRAY;
				hasWhitespace = false;
				printPreprocessorDirective();
				printNewLine();
				currentTokenStartPosition = scanner.getCurrentPosition();
				hasLineComment = false;
				hasComment = false;
				lines = 0;
				break;
			default:
				// step back one token
				scanner.resetTo(currentTokenStartPosition, scannerEndPosition);
				return hasWhitespace;
			}
		}
		scanner.resetTo(currentTokenStartPosition, scannerEndPosition);
		return hasWhitespace;
	}

	/**
	 * @param offset
	 * @return
	 */
	private Position getInactivePosAt(int offset) {
		for (Iterator<Position> iter = fSkipPositions.iterator(); iter.hasNext();) {
			Position pos = iter.next();
			if (pos.includes(offset)) {
				return pos;
			}
		}
		return null;
	}

	private void printLineComment() {
		int currentTokenStartPosition = scanner.getCurrentTokenStartPosition();
		int currentTokenEndPosition = scanner.getCurrentTokenEndPosition() + 1;
		scanner.resetTo(currentTokenStartPosition, currentTokenEndPosition);
		int currentCharacter;
		int start = currentTokenStartPosition;
		int nextCharacterStart = currentTokenStartPosition;

		// Print comment line indentation
		int commentIndentationLevel;
		boolean onFirstColumn = isOnFirstColumn(start);
		if (!preferences.comment_line_up_line_comment_in_blocks_on_first_column && indentationLevel == 0) {
			commentIndentationLevel = column - 1;
		} else {
			if (onFirstColumn && preferences.never_indent_line_comments_on_first_column) {
				commentIndentationLevel = column - 1;
			} else {
				// Indentation may be specific for contiguous comment
				// see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=293300
				if (lastLineComment.contiguous) {
					// The leading spaces have been set while looping in the printComment(int) method
					int currentCommentIndentation = computeIndentation(lastLineComment.leadingSpaces, 0);
					// Keep the current comment indentation when over the previous contiguous line comment
					// and the previous comment has not been re-indented
					int relativeIndentation = currentCommentIndentation - lastLineComment.currentIndentation;
					boolean similarCommentsIndentation = false;
					if (tabLength == 0) {
						similarCommentsIndentation = relativeIndentation == 0;
					} else if (relativeIndentation > -tabLength) {
						similarCommentsIndentation = relativeIndentation == 0
								|| currentCommentIndentation != 0 && lastLineComment.currentIndentation != 0;
					}
					if (similarCommentsIndentation && lastLineComment.indentation != indentationLevel) {
						int currentIndentationLevel = indentationLevel;
						indentationLevel = lastLineComment.indentation;
						printIndentationIfNecessary();
						indentationLevel = currentIndentationLevel;
						commentIndentationLevel = lastLineComment.indentation;
					} else {
						printIndentationIfNecessary();
						commentIndentationLevel = column - 1;
					}
				} else {
					printIndentationIfNecessary();
					commentIndentationLevel = column - 1;
				}
			}
		}

		// Prepare white space before the comment.
		StringBuilder whitespace = null;
		if (!lastLineComment.contiguous && commentIndentationLevel != indentationLevel
				&& !(preferences.never_indent_line_comments_on_first_column && onFirstColumn)) {
			whitespace = new StringBuilder();
			int whitespaceStartPosition = currentTokenStartPosition - lastLineComment.leadingSpaces.length;
			int indent = getIndentationOfOffset(whitespaceStartPosition);
			int distance = computeIndentation(lastLineComment.leadingSpaces, indent) - indent;
			if (preferences.comment_preserve_white_space_between_code_and_line_comment
					&& distance >= preferences.comment_min_distance_between_code_and_line_comment) {
				whitespace.append(lastLineComment.leadingSpaces);
			} else {
				for (int i = 0; i < preferences.comment_min_distance_between_code_and_line_comment; i++) {
					whitespace.append(' ');
				}
			}
		}

		// Store line comment information
		lastLineComment.currentIndentation = getIndentationOfOffset(currentTokenStartPosition);
		lastLineComment.contiguous = true;

		while (true) {
			Location location = new Location(this, scanner.getCurrentPosition());
			int commentIndent = commentIndentationLevel;

			// Add pending space if necessary
			if (whitespace != null) {
				addInsertEdit(currentTokenStartPosition, whitespace);
				commentIndent = computeIndentation(whitespace, commentIndentationLevel);
				needSpace = false;
				pendingSpace = false;
			}
			lastLineComment.indentation = commentIndent;

			int previousStart = currentTokenStartPosition;

			int indent = commentIndent;
			loop: while (nextCharacterStart <= currentTokenEndPosition
					&& (currentCharacter = scanner.getNextChar()) != -1) {
				nextCharacterStart = scanner.getCurrentPosition();

				switch (currentCharacter) {
				case '\r':
				case '\n':
					start = previousStart;
					break loop;
				}
				indent = computeIndentation((char) currentCharacter, indent);
				previousStart = nextCharacterStart;
			}

			if (start != currentTokenStartPosition) {
				// This means that the line comment doesn't end the file
				addReplaceEdit(start, currentTokenEndPosition - 1, lineSeparator);
				line++;
				column = 1;
				lastNumberOfNewLines = 1;
			}
			if (!checkLineWrapping || indent <= pageWidth || whitespace == null || commentIndent
					- commentIndentationLevel <= preferences.comment_min_distance_between_code_and_line_comment) {
				break;
			}

			// Maximum line length was exceeded. Try to reduce white space before the comment by
			// removing the last white space character.
			whitespace.deleteCharAt(whitespace.length() - 1);
			if (computeIndentation(lastLineComment.leadingSpaces, commentIndentationLevel)
					- commentIndentationLevel < preferences.comment_min_distance_between_code_and_line_comment) {
				// The white space shrank too much. Rebuild it to satisfy the minimum distance
				// requirement.
				whitespace.delete(0, whitespace.length());
				for (int i = 0; i < preferences.comment_min_distance_between_code_and_line_comment; i++) {
					whitespace.append(' ');
				}
			}
			resetAt(location);
			scanner.resetTo(location.inputOffset, scanner.eofPosition);
		}

		needSpace = false;
		pendingSpace = false;
		// realign to the proper value
		if (currentAlignment != null) {
			if (memberAlignment != null) {
				// select the last alignment
				if (currentAlignment.location.inputOffset > memberAlignment.location.inputOffset) {
					if (currentAlignment.couldBreak() && currentAlignment.wasSplit) {
						currentAlignment.performFragmentEffect();
					}
				} else {
					indentationLevel = Math.max(indentationLevel, memberAlignment.breakIndentationLevel);
				}
			} else if (currentAlignment.couldBreak() && currentAlignment.wasSplit) {
				currentAlignment.performFragmentEffect();
			}
			if (currentAlignment.name.equals(Alignment.BINARY_EXPRESSION) && currentAlignment.enclosing != null
					&& currentAlignment.enclosing.equals(Alignment.BINARY_EXPRESSION)
					&& indentationLevel < currentAlignment.breakIndentationLevel) {
				indentationLevel = currentAlignment.breakIndentationLevel;
			}
		}
		scanner.resetTo(currentTokenEndPosition, scannerEndPosition);
	}

	public void printEmptyLines(int linesNumber) {
		printEmptyLines(linesNumber, scanner.getCurrentTokenEndPosition() + 1);
	}

	private void printEmptyLines(int linesNumber, int insertPosition) {
		final String buffer = getEmptyLines(linesNumber);
		if (!buffer.isEmpty()) {
			addInsertEdit(insertPosition, buffer);
		}
	}

	void printIndentationIfNecessary() {
		if (column > indentationLevel)
			return;
		StringBuilder buffer = new StringBuilder();
		printIndentationIfNecessary(buffer);
		if (buffer.length() > 0) {
			addInsertEdit(scanner.getCurrentTokenStartPosition(), buffer);
			pendingSpace = false;
		}
	}

	private void printIndentationIfNecessary(StringBuilder buffer) {
		switch (tabChar) {
		case DefaultCodeFormatterOptions.TAB:
			boolean useTabsForLeadingIndents = useTabsOnlyForLeadingIndents;
			int numberOfLeadingIndents = numberOfIndentations;
			int indentationsAsTab = 0;
			if (useTabsForLeadingIndents) {
				while (column <= indentationLevel) {
					if (indentationsAsTab < numberOfLeadingIndents) {
						buffer.append('\t');
						indentationsAsTab++;
						int complement = tabLength - ((column - 1) % tabLength); // amount of space
						column += complement;
						needSpace = false;
					} else {
						buffer.append(' ');
						column++;
						needSpace = false;
					}
				}
			} else {
				while (column <= indentationLevel - indentationLevel % tabLength) {
					buffer.append('\t');
					int complement = tabLength - ((column - 1) % tabLength); // amount of space
					column += complement;
					needSpace = false;
				}
				while (column <= indentationLevel) {
					buffer.append(' ');
					column++;
					needSpace = false;
				}
			}
			break;
		case DefaultCodeFormatterOptions.SPACE:
			while (column <= indentationLevel) {
				buffer.append(' ');
				column++;
				needSpace = false;
			}
			break;
		case DefaultCodeFormatterOptions.MIXED:
			useTabsForLeadingIndents = useTabsOnlyForLeadingIndents;
			numberOfLeadingIndents = numberOfIndentations;
			indentationsAsTab = 0;
			if (useTabsForLeadingIndents) {
				final int columnForLeadingIndents = numberOfLeadingIndents * indentationSize;
				while (column <= indentationLevel) {
					if (column <= columnForLeadingIndents) {
						if ((column - 1 + tabLength) <= indentationLevel) {
							buffer.append('\t');
							column += tabLength;
						} else if ((column - 1 + indentationSize) <= indentationLevel) {
							// print one indentation
							for (int i = 0, max = indentationSize; i < max; i++) {
								buffer.append(' ');
								column++;
							}
						} else {
							buffer.append(' ');
							column++;
						}
					} else {
						for (int i = column, max = indentationLevel; i <= max; i++) {
							buffer.append(' ');
							column++;
						}
					}
					needSpace = false;
				}
			} else {
				while (column <= indentationLevel) {
					if ((column - 1 + tabLength) <= indentationLevel) {
						buffer.append('\t');
						column += tabLength;
					} else if ((column - 1 + indentationSize) <= indentationLevel) {
						// print one indentation
						for (int i = 0, max = indentationSize; i < max; i++) {
							buffer.append(' ');
							column++;
						}
					} else {
						buffer.append(' ');
						column++;
					}
					needSpace = false;
				}
			}
			break;
		}
	}

	public void enterNode() {
		lastLineComment.contiguous = false;
	}

	public void startNewLine() {
		if (column > 1) {
			printNewLine();
		}
	}

	public void printNewLine() {
		printNewLine(scanner.getCurrentPosition());
	}

	public void printNewLine(int insertPosition) {
		if (shouldSkip(scanner.getCurrentPosition())) {
			return;
		}
		if (lastNumberOfNewLines >= 1) {
			// Ensure that the scribe is at the beginning of a new line
			// only if no specific indentation has been previously set.
			if (!preserveLineBreakIndentation) {
				column = 1;
			}
			preserveLineBreakIndentation = false;
			return;
		}
		addInsertEdit(insertPosition, lineSeparator);
		line++;
		lastNumberOfNewLines = 1;
		column = 1;
		needSpace = false;
		pendingSpace = false;
		preserveLineBreakIndentation = false;
		lastLineComment.contiguous = false;
	}

	public void printNextToken(int expectedTokenType) {
		printNextToken(expectedTokenType, false);
	}

	public void printNextToken(int expectedTokenType, boolean considerSpaceIfAny) {
		// Set brace flag, it's useful for the scribe while preserving line breaks
		switch (expectedTokenType) {
		case Token.tRBRACE:
		case Token.tLBRACE:
			formatBrace = true;
			lastLineComment.contiguous = false;
		}
		try {
			printComment();
			if (shouldSkip(scanner.getCurrentPosition())) {
				return;
			}
			currentToken = scanner.nextToken();
			if (currentToken == null || expectedTokenType != currentToken.type) {
				if (pendingSpace) {
					addInsertEdit(scanner.getCurrentTokenStartPosition(), SPACE);
				}
				pendingSpace = false;
				needSpace = true;
				throw new AbortFormatting("[" + (line + 1) + "/" + column + "] Unexpected token type, expecting:" + //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
						expectedTokenType + ", actual:" + currentToken);//$NON-NLS-1$
			}
			print(currentToken.getLength(), considerSpaceIfAny);
		} finally {
			formatBrace = false;
		}
	}

	public void printNextToken(int[] expectedTokenTypes) {
		printNextToken(expectedTokenTypes, false);
	}

	public void printNextToken(int[] expectedTokenTypes, boolean considerSpaceIfAny) {
		printComment();
		if (shouldSkip(scanner.getCurrentPosition())) {
			return;
		}
		currentToken = scanner.nextToken();
		if (Arrays.binarySearch(expectedTokenTypes, currentToken.type) < 0) {
			if (pendingSpace) {
				addInsertEdit(scanner.getCurrentTokenStartPosition(), SPACE);
			}
			pendingSpace = false;
			needSpace = true;
			StringBuilder expectations = new StringBuilder(5);
			for (int i = 0; i < expectedTokenTypes.length; i++) {
				if (i > 0) {
					expectations.append(',');
				}
				expectations.append(expectedTokenTypes[i]);
			}
			throw new AbortFormatting("[" + (line + 1) + "/" + column + "] unexpected token type, expecting:[" //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
					+ expectations.toString() + "], actual:" + currentToken); //$NON-NLS-1$
		}
		print(currentToken.getLength(), considerSpaceIfAny);
	}

	private void printRuler(StringBuilder stringBuffer) {
		for (int i = 0; i < pageWidth; i++) {
			if ((i % tabLength) == 0) {
				stringBuffer.append('+');
			} else {
				stringBuffer.append('-');
			}
		}
		stringBuffer.append(lineSeparator);

		for (int i = 0; i < (pageWidth / tabLength); i++) {
			stringBuffer.append(i);
			stringBuffer.append('\t');
		}
	}

	public void printSpaces(int numSpaces) {
		if (numSpaces > 0) {
			int currentPosition = scanner.getCurrentPosition();
			StringBuilder spaces = new StringBuilder(numSpaces);
			for (int i = 0; i < numSpaces; i++) {
				spaces.append(' ');
			}
			addInsertEdit(currentPosition, spaces);
			pendingSpace = false;
			needSpace = false;
		}
	}

	public void printTrailingComment() {
		printComment(BASIC_TRAILING_COMMENT);
	}

	void redoAlignment(AlignmentException e) {
		if (e.relativeDepth > 0) { // if exception targets a distinct context
			e.relativeDepth--; // record fact that current context got traversed
			currentAlignment = currentAlignment.enclosing; // pop currentLocation
			throw e; // rethrow
		}
		// Reset scribe/scanner to restart at this given location
		resetAt(currentAlignment.location);
		scanner.resetTo(currentAlignment.location.inputOffset, scanner.eofPosition);
		// Clean alignment chunkKind so it will think it is a new chunk again
		currentAlignment.chunkKind = 0;
		currentAlignmentException = null;
	}

	void redoMemberAlignment(AlignmentException e) {
		// Reset scribe/scanner to restart at this given location
		resetAt(memberAlignment.location);
		scanner.resetTo(memberAlignment.location.inputOffset, scanner.eofPosition);
		// Clean alignment chunkKind so it will think it is a new chunk again
		memberAlignment.chunkKind = 0;
		currentAlignmentException = null;
	}

	public void reset() {
		checkLineWrapping = true;
		line = 0;
		column = 1;
		editsIndex = 0;
	}

	private void resetAt(Location location) {
		line = location.outputLine;
		column = location.outputColumn;
		indentationLevel = location.outputIndentationLevel;
		needSpace = location.needSpace;
		pendingSpace = location.pendingSpace;
		numberOfIndentations = location.numberOfIndentations;
		lastNumberOfNewLines = location.lastNumberOfNewLines;
		editsIndex = location.editsIndex;
		if (editsIndex > 0) {
			edits[editsIndex - 1] = location.textEdit;
		}
		setTailFormatter(location.tailFormatter);
	}

	private void resize() {
		System.arraycopy(edits, 0, (edits = new OptimizedReplaceEdit[editsIndex * 2]), 0, editsIndex);
	}

	public void space() {
		if (!needSpace)
			return;
		if (shouldSkip(scanner.getCurrentPosition())) {
			return;
		}
		lastNumberOfNewLines = 0;
		pendingSpace = true;
		column++;
		needSpace = false;
	}

	public void undoSpace() {
		if (pendingSpace) {
			pendingSpace = false;
			needSpace = true;
			column--;
		}
	}

	@Override
	public String toString() {
		StringBuilder buffer = new StringBuilder();
		buffer.append("(page width = ").append(pageWidth).append(") - (tabChar = "); //$NON-NLS-1$//$NON-NLS-2$
		switch (tabChar) {
		case DefaultCodeFormatterOptions.TAB:
			buffer.append("TAB"); //$NON-NLS-1$
			break;
		case DefaultCodeFormatterOptions.SPACE:
			buffer.append("SPACE"); //$NON-NLS-1$
			break;
		default:
			buffer.append("MIXED"); //$NON-NLS-1$
		}
		buffer.append(") - (tabSize = ").append(tabLength).append(')') //$NON-NLS-1$/
				.append(lineSeparator).append("(line = ").append(line).append(") - (column = ").append(column) //$NON-NLS-1$//$NON-NLS-2$
				.append(") - (identationLevel = ").append(indentationLevel).append(')') //$NON-NLS-1$
				.append(lineSeparator).append("(needSpace = ").append(needSpace).append(") - (lastNumberOfNewLines = ") //$NON-NLS-1$//$NON-NLS-2$
				.append(lastNumberOfNewLines).append(") - (checkLineWrapping = ").append(checkLineWrapping).append(')') //$NON-NLS-1$
				.append(lineSeparator)
				.append("==================================================================================") //$NON-NLS-1$
				.append(lineSeparator);
		printRuler(buffer);
		return buffer.toString();
	}

	public void unIndent() {
		if (shouldSkip(scanner.getCurrentPosition())) {
			fSkippedIndentations--;
			return;
		}
		indentationLevel -= indentationSize;
		numberOfIndentations--;
	}

	/**
	 */
	public boolean printModifiers() {
		int currentTokenStartPosition = scanner.getCurrentPosition();
		if (shouldSkip(currentTokenStartPosition)) {
			return false;
		}
		boolean isFirstModifier = true;
		boolean hasComment = false;
		while ((currentToken = scanner.nextToken()) != null) {
			switch (currentToken.type) {
			case Token.t_typedef:
			case Token.t_extern:
			case Token.t_static:
			case Token.t_auto:
			case Token.t_register:
			case Token.t_const:
			case Token.t_signed:
			case Token.t_unsigned:
			case Token.t_volatile:
			case Token.t_virtual:
			case Token.t_mutable:
			case Token.t_explicit:
			case Token.t_friend:
			case Token.t_inline:
			case Token.t_restrict:
				print(currentToken.getLength(), !isFirstModifier);
				isFirstModifier = false;
				currentTokenStartPosition = scanner.getCurrentPosition();
				break;
			case Token.tBLOCKCOMMENT:
				printBlockComment(false);
				currentTokenStartPosition = scanner.getCurrentPosition();
				hasComment = true;
				break;
			case Token.tLINECOMMENT:
				printLineComment();
				currentTokenStartPosition = scanner.getCurrentPosition();
				break;
			case Token.tWHITESPACE:
				addDeleteEdit(scanner.getCurrentTokenStartPosition(), scanner.getCurrentTokenEndPosition());
				int count = 0;
				char[] whiteSpaces = scanner.getCurrentTokenSource();
				for (int i = 0, max = whiteSpaces.length; i < max; i++) {
					switch (whiteSpaces[i]) {
					case '\r':
						if ((i + 1) < max) {
							if (whiteSpaces[i + 1] == '\n') {
								i++;
							}
						}
						count++;
						break;
					case '\n':
						count++;
					}
				}
				if (count >= 1 && hasComment) {
					printNewLine();
				}
				currentTokenStartPosition = scanner.getCurrentPosition();
				hasComment = false;
				break;
			case Token.tPREPROCESSOR:
			case Token.tPREPROCESSOR_DEFINE:
			case Token.tPREPROCESSOR_INCLUDE:
				if (column != 1)
					printNewLine(scanner.getCurrentTokenStartPosition());
				printPreprocessorDirective();
				printNewLine();
				currentTokenStartPosition = scanner.getCurrentPosition();
				hasComment = false;
				break;
			default:
				if (currentToken.getType() == Token.tIDENTIFIER) {
					if (currentToken.getText().startsWith("__")) { //$NON-NLS-1$
						// assume this is a declspec modifier
						print(currentToken.getLength(), !isFirstModifier);
						isFirstModifier = false;
						currentTokenStartPosition = scanner.getCurrentPosition();
						if ((currentToken = scanner.nextToken()) != null) {
							if (currentToken.getType() == Token.tLPAREN) {
								if (skipToToken(Token.tRPAREN)) {
									currentToken = scanner.nextToken();
									currentToken = scanner.nextToken();
									currentTokenStartPosition = scanner.getCurrentPosition();
								}
							}
						}
						break;
					}
				}
				// Step back one token
				scanner.resetTo(currentTokenStartPosition, scannerEndPosition);
				return !isFirstModifier;
			}
		}
		return !isFirstModifier;
	}

	/**
	 * Skips to the next occurrence of the given token type.
	 * If successful, the next token will be the expected token,
	 * otherwise the scanner position is left unchanged.
	 *
	 * @param expectedTokenType
	 * @return  <code>true</code> if a matching token was skipped to
	 */
	public boolean skipToToken(int expectedTokenType) {
		int skipStart = scanner.getCurrentPosition();
		if (shouldSkip(skipStart)) {
			return true;
		}
		int tokenStart = findToken(expectedTokenType);
		if (tokenStart < 0) {
			return false;
		}
		printRaw(skipStart, tokenStart - skipStart);
		currentToken = scanner.nextToken();
		scanner.resetTo(tokenStart, scannerEndPosition);
		return true;
	}

	/**
	 * Searches for the next occurrence of the given token type.
	 * If successful, returns the offset of the found token, otherwise -1.
	 * The scanner position is left unchanged.
	 *
	 * @param tokenType type of the token to look for
	 * @return the position of the matching token, if found, otherwise -1.
	 */
	public int findToken(int tokenType) {
		return findToken(tokenType, scannerEndPosition - 1);
	}

	/**
	 * Searches for the next occurrence of the given token type.
	 * If successful, returns the offset of the found token, otherwise -1.
	 * The scanner position is left unchanged.
	 *
	 * @param tokenType type of the token to look for
	 * @param endPosition end position limiting the search
	 * @return the position of the matching token, if found, otherwise -1.
	 */
	public int findToken(int tokenType, int endPosition) {
		int startPosition = scanner.getCurrentPosition();
		if (startPosition >= endPosition) {
			return -1;
		}
		try {
			int braceLevel = 0;
			int parenLevel = 0;
			switch (tokenType) {
			case Token.tRBRACE:
				++braceLevel;
				break;
			case Token.tRPAREN:
				++parenLevel;
				break;
			}
			Token token;
			while ((token = scanner.nextToken()) != null) {
				if (scanner.getCurrentTokenEndPosition() > endPosition)
					return -1;

				switch (token.type) {
				case Token.tLBRACE:
					if (tokenType != Token.tLBRACE) {
						++braceLevel;
					}
					break;
				case Token.tRBRACE:
					--braceLevel;
					break;
				case Token.tLPAREN:
					if (tokenType != Token.tLPAREN) {
						++parenLevel;
					}
					break;
				case Token.tRPAREN:
					--parenLevel;
					break;
				case Token.tWHITESPACE:
				case Token.tLINECOMMENT:
				case Token.tBLOCKCOMMENT:
				case Token.tPREPROCESSOR:
				case Token.tPREPROCESSOR_DEFINE:
				case Token.tPREPROCESSOR_INCLUDE:
					continue;
				}
				if (braceLevel <= 0 && parenLevel <= 0) {
					if (token.type == tokenType) {
						return scanner.getCurrentTokenStartPosition();
					}
				}
				if (braceLevel < 0 || parenLevel < 0) {
					break;
				}
			}
		} finally {
			scanner.resetTo(startPosition, scannerEndPosition);
		}
		return -1;
	}

	/**
	 * Searches for the next occurrence of the given token type.
	 * If successful, returns the offset of the found token, otherwise -1.
	 * The scanner position is left unchanged.
	 *
	 * @param tokenType type of the token to look for
	 * @param startPosition position where to start the search
	 * @param endPosition end position limiting the search
	 * @return the position of the matching token, if found, otherwise -1.
	 */
	public int findToken(int tokenType, int startPosition, int endPosition) {
		int currentPosition = scanner.getCurrentPosition();
		try {
			scanner.resetTo(startPosition, scannerEndPosition);
			return findToken(tokenType, endPosition);
		} finally {
			scanner.resetTo(currentPosition, scannerEndPosition);
		}
	}

	public boolean printCommentPreservingNewLines() {
		final boolean savedPreserveNL = preserveNewLines;
		preserveNewLines = true;
		try {
			return printComment();
		} finally {
			preserveNewLines = savedPreserveNL;
		}
	}

	boolean shouldSkip(int offset) {
		return offset >= fSkipStartOffset && offset < fSkipEndOffset;
	}

	void skipRange(int offset, int endOffset) {
		if (offset == fSkipStartOffset) {
			return;
		}
		final int currentPosition = scanner.getCurrentPosition();
		if (offset > currentPosition) {
			fSkipStartOffset = Integer.MAX_VALUE;
			printRaw(currentPosition, offset - currentPosition);
		}
		fSkipStartOffset = offset;
		fSkipEndOffset = endOffset;
	}

	boolean skipRange() {
		return fSkipEndOffset > 0;
	}

	void restartAtOffset(int offset) {
		final int currentPosition = scanner.getCurrentPosition();
		if (fSkipEndOffset > 0) {
			fSkipStartOffset = Integer.MAX_VALUE;
			fSkipEndOffset = 0;
			while (fSkippedIndentations < 0) {
				unIndent();
				fSkippedIndentations++;
			}
			if (offset > currentPosition) {
				printRaw(currentPosition, offset - currentPosition);
				scanner.resetTo(offset, scannerEndPosition);
			}
			while (fSkippedIndentations > 0) {
				indent();
				fSkippedIndentations--;
			}
		} else if (offset > currentPosition) {
			boolean hasSpace = printComment();
			final int nextPosition = scanner.getCurrentPosition();
			if (offset > nextPosition) {
				if (hasSpace) {
					space();
				}
				printRaw(nextPosition, offset - nextPosition);
				scanner.resetTo(offset, scannerEndPosition);
			}
		}
	}

	/*
	 * Returns the tail formatter associated with the current alignment or, if there is no current
	 * alignment, with the scribe itself.
	 * @see #tailFormatter
	 */
	public Runnable getTailFormatter() {
		if (currentAlignment != null) {
			return currentAlignment.tailFormatter;
		} else {
			return this.tailFormatter;
		}
	}

	/*
	 * Returns the tail formatter associated with the current alignment or, if there is no current
	 * alignment, with the scribe itself. The tail formatter associated with the alignment or
	 * the scribe is set to {@code null}.
	 * @see #tailFormatter
	 */
	public Runnable takeTailFormatter() {
		Runnable formatter;
		if (currentAlignment != null) {
			formatter = currentAlignment.tailFormatter;
			currentAlignment.tailFormatter = null;
		} else {
			formatter = this.tailFormatter;
			this.tailFormatter = null;
		}
		return formatter;
	}

	/*
	 * Sets the tail formatter associated with the current alignment or, if there is no current
	 * alignment, with the scribe itself.
	 * @see #tailFormatter
	 */
	public void setTailFormatter(Runnable tailFormatter) {
		if (currentAlignment != null) {
			currentAlignment.tailFormatter = tailFormatter;
		} else {
			this.tailFormatter = tailFormatter;
		}
	}

	/*
	 * Runs the tail formatter associated with the current alignment or, if there is no current
	 * alignment, with the scribe itself.
	 * @see #tailFormatter
	 */
	public void runTailFormatter() {
		Runnable formatter = getTailFormatter();
		if (formatter != null)
			formatter.run();
	}
}

Back to the top