summaryrefslogtreecommitdiff
path: root/lisp/whitespace.el
blob: a2dc6ab9814e1f9ed93d94bc89e7b5b498b8fed4 (plain)
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
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
;;; whitespace.el --- minor mode to visualize TAB, (HARD) SPACE, NEWLINE -*- lexical-binding: t -*-

;; Copyright (C) 2000-2021 Free Software Foundation, Inc.

;; Author: Vinicius Jose Latorre <viniciusjl.gnu@gmail.com>
;; Keywords: data, wp
;; Version: 13.2.2
;; X-URL: https://www.emacswiki.org/cgi-bin/wiki/ViniciusJoseLatorre

;; This file is part of GNU Emacs.

;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.

;;; Commentary:

;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Introduction
;; ------------
;;
;; This package is a minor mode to visualize blanks (TAB, (HARD) SPACE
;; and NEWLINE).
;;
;; whitespace uses two ways to visualize blanks: faces and display
;; table.
;;
;; * Faces are used to highlight the background with a color.
;;   whitespace uses font-lock to highlight blank characters.
;;
;; * Display table changes the way a character is displayed, that is,
;;   it provides a visual mark for characters, for example, at the end
;;   of line (?\xB6), at SPACEs (?\xB7) and at TABs (?\xBB).
;;
;; The `whitespace-style' variable selects which way blanks are
;; visualized.
;;
;; Note that when whitespace is turned on, whitespace saves the
;; font-lock state, that is, if font-lock is on or off.  And
;; whitespace restores the font-lock state when it is turned off.  So,
;; if whitespace is turned on and font-lock is off, whitespace also
;; turns on the font-lock to highlight blanks, but the font-lock will
;; be turned off when whitespace is turned off.  Thus, turn on
;; font-lock before whitespace is on, if you want that font-lock
;; continues on after whitespace is turned off.
;;
;; When whitespace is on, it takes care of highlighting some special
;; characters over the default mechanism of `nobreak-char-display'
;; (which see) and `show-trailing-whitespace' (which see).
;;
;; The trailing spaces are not highlighted while point is at end of line.
;; Also the spaces at beginning of buffer are not highlighted while point is at
;; beginning of buffer; and the spaces at end of buffer are not highlighted
;; while point is at end of buffer.
;;
;; There are two ways of using whitespace: local and global.
;;
;; * Local whitespace affects only the current buffer.
;;
;; * Global whitespace affects all current and future buffers.  That
;;   is, if you turn on global whitespace and then create a new
;;   buffer, the new buffer will also have whitespace on.  The
;;   `whitespace-global-modes' variable controls which major-mode will
;;   be automagically turned on.
;;
;; You can mix the local and global usage without any conflict.  But
;; local whitespace has priority over global whitespace.  Whitespace
;; mode is active in a buffer if you have enabled it in that buffer or
;; if you have enabled it globally.
;;
;; When global and local whitespace are on:
;;
;; * if local whitespace is turned off, whitespace is turned off for
;;   the current buffer only.
;;
;; * if global whitespace is turned off, whitespace continues on only
;;   in the buffers in which local whitespace is on.
;;
;; whitespace was inspired by:
;;
;;    whitespace.el            Rajesh Vaidheeswarran <rv@gnu.org>
;;	Warn about and clean bogus whitespaces in the file
;;	(inspired the idea to warn and clean some blanks)
;;	This was the original `whitespace.el' which was replaced by
;;	`blank-mode.el'.  And later `blank-mode.el' was renamed to
;;	`whitespace.el'.
;;
;;    show-whitespace-mode.el  Aurelien Tisne <aurelien.tisne@free.fr>
;;       Simple mode to highlight whitespaces
;;       (inspired the idea to use font-lock)
;;
;;    whitespace-mode.el       Lawrence Mitchell <wence@gmx.li>
;;       Major mode for editing Whitespace
;;       (inspired the idea to use display table)
;;
;;    visws.el                 Miles Bader <miles@gnu.org>
;;       Make whitespace visible
;;       (handle display table, his code was modified, but the main
;;       idea was kept)
;;
;;
;; Using whitespace
;; ----------------
;;
;; There is no problem if you mix local and global minor mode usage.
;;
;; * LOCAL whitespace:
;;    + To toggle whitespace options locally, type:
;;
;;         M-x whitespace-toggle-options RET
;;
;;    + To activate whitespace locally, type:
;;
;;         C-u 1 M-x whitespace-mode RET
;;
;;    + To deactivate whitespace locally, type:
;;
;;         C-u 0 M-x whitespace-mode RET
;;
;;    + To toggle whitespace locally, type:
;;
;;         M-x whitespace-mode RET
;;
;; * GLOBAL whitespace:
;;    + To toggle whitespace options globally, type:
;;
;;         M-x global-whitespace-toggle-options RET
;;
;;    + To activate whitespace globally, type:
;;
;;         C-u 1 M-x global-whitespace-mode RET
;;
;;    + To deactivate whitespace globally, type:
;;
;;         C-u 0 M-x global-whitespace-mode RET
;;
;;    + To toggle whitespace globally, type:
;;
;;         M-x global-whitespace-mode RET
;;
;; There are also the following useful commands:
;;
;; `whitespace-newline-mode'
;;    Toggle NEWLINE minor mode visualization ("nl" on mode line).
;;
;; `global-whitespace-newline-mode'
;;    Toggle NEWLINE global minor mode visualization ("NL" on mode line).
;;
;; `whitespace-report'
;;    Report some blank problems in buffer.
;;
;; `whitespace-report-region'
;;    Report some blank problems in a region.
;;
;; `whitespace-cleanup'
;;    Cleanup some blank problems in all buffer or at region.
;;    See the function's docstring for more information.
;;
;; `whitespace-cleanup-region'
;;    Cleanup some blank problems at region.
;;
;;
;; Options
;; -------
;;
;; Whitespace's behavior can be changed with `M-x customize-group
;; whitespace', which see for the full list of options.
;;
;;
;; Hooks
;; -----
;;
;; whitespace has the following hook variables:
;;
;; `whitespace-mode-hook'
;;    It is evaluated always when whitespace is turned on locally.
;;
;; `global-whitespace-mode-hook'
;;    It is evaluated always when whitespace is turned on globally.
;;
;; `whitespace-load-hook'
;;    It is evaluated after whitespace package is loaded.
;;
;;
;; Acknowledgments
;; ---------------
;;
;; Thanks to felix (EmacsWiki) for keeping highlight when switching between
;; major modes on a file.
;;
;; Thanks to David Reitter <david.reitter@gmail.com> for suggesting a
;; `whitespace-newline' initialization with low contrast relative to
;; the background color.
;;
;; Thanks to Stephen Deasey <sdeasey@gmail.com> for the
;; `indent-tabs-mode' usage suggestion.
;;
;; Thanks to Eric Cooper <ecc@cmu.edu> for the suggestion to have hook
;; actions when buffer is written as the original whitespace package
;; had.
;;
;; Thanks to nschum (EmacsWiki) for the idea about highlight "long"
;; lines tail.  See EightyColumnRule (EmacsWiki).
;;
;; Thanks to Juri Linkov <juri@jurta.org> for suggesting:
;;    * `define-minor-mode'.
;;    * `global-whitespace-*' name for global commands.
;;
;; Thanks to Robert J. Chassell <bob@gnu.org> for doc fix and testing.
;;
;; Thanks to Drew Adams <drew.adams@oracle.com> for toggle commands
;; suggestion.
;;
;; Thanks to Antti Kaihola <antti.kaihola@linux-aktivaattori.org> for
;; helping to fix `find-file-hooks' reference.
;;
;; Thanks to Andreas Roehler <andreas.roehler@easy-emacs.de> for
;; indicating defface byte-compilation warnings.
;;
;; Thanks to Tim O'Callaghan (EmacsWiki) for the idea about highlight
;; "long" lines.  See EightyColumnRule (EmacsWiki).
;;
;; Thanks to Yanghui Bian <yanghuibian@gmail.com> for indicating a new
;; NEWLINE character mapping.
;;
;; Thanks to Pete Forman <pete.forman@westgeo.com> for indicating
;; whitespace-mode.el on XEmacs.
;;
;; Thanks to Miles Bader <miles@gnu.org> for handling display table via
;; visws.el (his code was modified, but the main idea was kept).
;;
;; Thanks to:
;;    Rajesh Vaidheeswarran <rv@gnu.org>	(original) whitespace.el
;;    Aurelien Tisne <aurelien.tisne@free.fr>	show-whitespace-mode.el
;;    Lawrence Mitchell <wence@gmx.li>		whitespace-mode.el
;;    Miles Bader <miles@gnu.org>		visws.el
;; And to all people who contributed with them.
;;
;;
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;; Code:


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; User Variables:


;;; Interface to the command system


(defgroup whitespace nil
  "Visualize blanks (TAB, (HARD) SPACE and NEWLINE)."
  :link '(emacs-library-link :tag "Source Lisp File" "whitespace.el")
  :version "23.1"
  :group 'convenience)


(defcustom whitespace-style
  '(face
    tabs spaces trailing lines space-before-tab newline
    indentation empty space-after-tab
    space-mark tab-mark newline-mark
    missing-newline-at-eof)
  "Specify which kind of blank is visualized.

It's a list containing some or all of the following values:

   face			enable all visualization via faces (see below).

   trailing		trailing blanks are visualized via faces.
			It has effect only if `face' (see above)
			is present in `whitespace-style'.

   tabs			TABs are visualized via faces.
			It has effect only if `face' (see above)
			is present in `whitespace-style'.

   spaces		SPACEs and HARD SPACEs are visualized via
			faces.
			It has effect only if `face' (see above)
			is present in `whitespace-style'.

   lines		lines which have columns beyond
			`whitespace-line-column' are highlighted via
			faces.
			Whole line is highlighted.
			It has precedence over `lines-tail' (see
			below).
			It has effect only if `face' (see above)
			is present in `whitespace-style'.

   lines-tail		lines which have columns beyond
			`whitespace-line-column' are highlighted via
			faces.
			But only the part of line which goes
			beyond `whitespace-line-column' column.
			It has effect only if `lines' (see above)
			is not present in `whitespace-style'
			and if `face' (see above) is present in
			`whitespace-style'.

   newline		NEWLINEs are visualized via faces.
			It has effect only if `face' (see above)
			is present in `whitespace-style'.

   missing-newline-at-eof Missing newline at the end of the file is
                        visualized via faces.
			It has effect only if `face' (see above)
			is present in `whitespace-style'.

   empty		empty lines at beginning and/or end of buffer
			are visualized via faces.
			It has effect only if `face' (see above)
			is present in `whitespace-style'.

   indentation::tab	`tab-width' or more SPACEs at beginning of line
			are visualized via faces.
			It has effect only if `face' (see above)
			is present in `whitespace-style'.

   indentation::space	TABs at beginning of line are visualized via
			faces.
			It has effect only if `face' (see above)
			is present in `whitespace-style'.

   indentation		`tab-width' or more SPACEs at beginning of line
			are visualized, if `indent-tabs-mode' (which
			see) is non-nil; otherwise, TABs at beginning
			of line are visualized via faces.
			It has effect only if `face' (see above)
			is present in `whitespace-style'.

   big-indent		Big indentations are visualized via faces.
			It has effect only if `face' (see above)
			is present in `whitespace-style'.

   space-after-tab::tab		`tab-width' or more SPACEs after a TAB
				are visualized via faces.
				It has effect only if `face' (see above)
				is present in `whitespace-style'.

   space-after-tab::space	TABs are visualized when `tab-width' or
				more SPACEs occur after a TAB, via
				faces.
				It has effect only if `face' (see above)
				is present in `whitespace-style'.

   space-after-tab		`tab-width' or more SPACEs after a TAB
				are visualized, if `indent-tabs-mode'
				(which see) is non-nil; otherwise,
				the TABs are visualized via faces.
				It has effect only if `face' (see above)
				is present in `whitespace-style'.

   space-before-tab::tab	SPACEs before TAB are visualized via
				faces.
				It has effect only if `face' (see above)
				is present in `whitespace-style'.

   space-before-tab::space	TABs are visualized when SPACEs occur
				before TAB, via faces.
				It has effect only if `face' (see above)
				is present in `whitespace-style'.

   space-before-tab		SPACEs before TAB are visualized, if
				`indent-tabs-mode' (which see) is
				non-nil; otherwise, the TABs are
				visualized via faces.
				It has effect only if `face' (see above)
				is present in `whitespace-style'.

   space-mark		SPACEs and HARD SPACEs are visualized via
			display table.

   tab-mark		TABs are visualized via display table.

   newline-mark		NEWLINEs are visualized via display table.

Any other value is ignored.

If nil, don't visualize TABs, (HARD) SPACEs and NEWLINEs via faces and
via display table.

There is an evaluation order for some values, if they are
included in `whitespace-style' list.  For example, if
indentation, indentation::tab and/or indentation::space are
included in `whitespace-style' list.  The evaluation order for
these values is:

 * For indentation:
   1. indentation
   2. indentation::tab
   3. indentation::space

 * For SPACEs after TABs:
   1. space-after-tab
   2. space-after-tab::tab
   3. space-after-tab::space

 * For SPACEs before TABs:
   1. space-before-tab
   2. space-before-tab::tab
   3. space-before-tab::space

For example, if `indentation' and `indentation::space' are
included in `whitespace-style', the `indentation' value is used
instead of the `indentation::space' value.

One reason to not use faces to visualize spaces (i.e., not
include `face' in `whitespace-style') is to use `whitespace-mode'
only for cleaning up a buffer.  See `whitespace-cleanup' and
`whitespace-cleanup-region'.

See also `whitespace-display-mappings' for documentation."
  :type '(set :tag "Kind of Blank"
              (const :tag "(Face) Face visualization" face)
              (const :tag "(Face) Trailing TABs, SPACEs and HARD SPACEs"
                     trailing)
              (const :tag "(Face) TABs" tabs)
              (const :tag "(Face) SPACEs and HARD SPACEs" spaces)
              (const :tag "(Face) Lines" lines)
              (const :tag "(Face) Lines, only overlong part" lines-tail)
              (const :tag "(Face) NEWLINEs" newline)
              (const :tag "(Face) Missing newlines at EOB"
                     missing-newline-at-eof)
              (const :tag "(Face) Empty Lines At BOB And/Or EOB" empty)
              (const :tag "(Face) Indentation SPACEs" indentation::tab)
              (const :tag "(Face) Indentation TABs"
                     indentation::space)
              (const :tag "(Face) Indentation TABs or SPACEs" indentation)
              (const :tag "(Face) Too much line indentation" big-indent)
              (const :tag "(Face) SPACEs after TAB: SPACEs"
                     space-after-tab::tab)
              (const :tag "(Face) SPACEs after TAB: TABs"
                     space-after-tab::space)
              (const :tag "(Face) SPACEs after TAB" space-after-tab)
              (const :tag "(Face) SPACEs before TAB: SPACEs"
                     space-before-tab::tab)
              (const :tag "(Face) SPACEs before TAB: TABs"
                     space-before-tab::space)
              (const :tag "(Face) SPACEs before TAB" space-before-tab)
              (const :tag "(Mark) SPACEs and HARD SPACEs" space-mark)
              (const :tag "(Mark) TABs" tab-mark)
              (const :tag "(Mark) NEWLINEs" newline-mark))
  :group 'whitespace)

(defvar whitespace-space 'whitespace-space
  "Symbol face used to visualize SPACE.
Used when `whitespace-style' includes the value `spaces'.")
(make-obsolete-variable 'whitespace-space "use the face instead." "24.4")


(defface whitespace-space
  '((((class color) (background dark))
     :background "grey20"      :foreground "darkgray")
    (((class color) (background light))
     :background "LightYellow" :foreground "lightgray")
    (t :inverse-video t))
  "Face used to visualize SPACE."
  :group 'whitespace)


(defvar whitespace-hspace 'whitespace-hspace
  "Symbol face used to visualize HARD SPACE.
Used when `whitespace-style' includes the value `spaces'.")
(make-obsolete-variable 'whitespace-hspace "use the face instead." "24.4")

(defface whitespace-hspace		; 'nobreak-space
  '((((class color) (background dark))
     :background "grey24"        :foreground "darkgray")
    (((class color) (background light))
     :background "LemonChiffon3" :foreground "lightgray")
    (t :inverse-video t))
  "Face used to visualize HARD SPACE."
  :group 'whitespace)


(defvar whitespace-tab 'whitespace-tab
  "Symbol face used to visualize TAB.
Used when `whitespace-style' includes the value `tabs'.")
(make-obsolete-variable 'whitespace-tab
                        "customize the face `whitespace-tab' instead." "24.4")

(defface whitespace-tab
  '((((class color) (background dark))
     :background "grey22" :foreground "darkgray")
    (((class color) (background light))
     :background "beige"  :foreground "lightgray")
    (t :inverse-video t))
  "Face used to visualize TAB."
  :group 'whitespace)


(defvar whitespace-newline 'whitespace-newline
  "Symbol face used to visualize NEWLINE char mapping.
See `whitespace-display-mappings'.
Used when `whitespace-style' includes the values `newline-mark'
and `newline'.")
(make-obsolete-variable 'whitespace-newline "use the face instead." "24.4")

(defface whitespace-newline
  '((default :weight normal)
    (((class color) (background dark)) :foreground "darkgray")
    (((class color) (min-colors 88) (background light)) :foreground "lightgray")
    ;; Displays with 16 colors use lightgray as background, so using a
    ;; lightgray foreground makes the newline mark invisible.
    (((class color) (background light)) :foreground "brown")
    (t :underline t))
  "Face used to visualize NEWLINE char mapping.

See `whitespace-display-mappings'."
  :group 'whitespace)


(defvar whitespace-trailing 'whitespace-trailing
  "Symbol face used to visualize trailing blanks.
Used when `whitespace-style' includes the value `trailing'.")
(make-obsolete-variable 'whitespace-trailing "use the face instead." "24.4")

(defface whitespace-trailing		; 'trailing-whitespace
  '((default :weight bold)
    (((class mono)) :inverse-video t :underline t)
    (t :background "red1" :foreground "yellow"))
  "Face used to visualize trailing blanks."
  :group 'whitespace)


(defvar whitespace-line 'whitespace-line
  "Symbol face used to visualize \"long\" lines.
See `whitespace-line-column'.
Used when `whitespace-style' includes the value `line'.")
(make-obsolete-variable 'whitespace-line "use the face instead." "24.4")

(defface whitespace-line
  '((((class mono)) :inverse-video t :weight bold :underline t)
    (t :background "gray20" :foreground "violet"))
  "Face used to visualize \"long\" lines.

See `whitespace-line-column'."
  :group 'whitespace)


(defvar whitespace-space-before-tab 'whitespace-space-before-tab
  "Symbol face used to visualize SPACEs before TAB.
Used when `whitespace-style' includes the value `space-before-tab'.")
(make-obsolete-variable 'whitespace-space-before-tab
                        "use the face instead." "24.4")

(defface whitespace-space-before-tab
  '((((class mono)) :inverse-video t :weight bold :underline t)
    (t :background "DarkOrange" :foreground "firebrick"))
  "Face used to visualize SPACEs before TAB."
  :group 'whitespace)


(defvar whitespace-indentation 'whitespace-indentation
  "Symbol face used to visualize `tab-width' or more SPACEs at beginning of
line.  Used when `whitespace-style' includes the value `indentation'.")
(make-obsolete-variable 'whitespace-indentation "use the face instead." "24.4")

(defface whitespace-indentation
  '((((class mono)) :inverse-video t :weight bold :underline t)
    (t :background "yellow" :foreground "firebrick"))
  "Face used to visualize `tab-width' or more SPACEs at beginning of line."
  :group 'whitespace)

(defface whitespace-big-indent
  '((((class mono)) :inverse-video t :weight bold :underline t)
    (t :background "red" :foreground "firebrick"))
  "Face used to visualize big indentation."
  :group 'whitespace)

(defface whitespace-missing-newline-at-eof
  '((((class mono)) :inverse-video t :weight bold :underline t)
    (t :background "#d0d040" :foreground "black"))
  "Face used to visualize missing newline at the end of the file.")

(defvar whitespace-empty 'whitespace-empty
  "Symbol face used to visualize empty lines at beginning and/or end of buffer.
Used when `whitespace-style' includes the value `empty'.")
(make-obsolete-variable 'whitespace-empty "use the face instead." "24.4")

(defface whitespace-empty
  '((((class mono)) :inverse-video t :weight bold :underline t)
    (t :background "yellow" :foreground "firebrick" :extend t))
  "Face used to visualize empty lines at beginning and/or end of buffer."
  :group 'whitespace)


(defvar whitespace-space-after-tab 'whitespace-space-after-tab
  "Symbol face used to visualize `tab-width' or more SPACEs after TAB.
Used when `whitespace-style' includes the value `space-after-tab'.")
(make-obsolete-variable 'whitespace-space-after-tab
                        "use the face instead." "24.4")

(defface whitespace-space-after-tab
  '((((class mono)) :inverse-video t :weight bold :underline t)
    (t :background "yellow" :foreground "firebrick"))
  "Face used to visualize `tab-width' or more SPACEs after TAB."
  :group 'whitespace)


(defcustom whitespace-hspace-regexp
  "\\(\u00A0+\\)"
  "Specify HARD SPACE characters regexp.

Here are some examples:

   \"\\\\(^\\xA0+\\\\)\"		\
visualize only leading HARD SPACEs.
   \"\\\\(\\xA0+$\\\\)\"		\
visualize only trailing HARD SPACEs.
   \"\\\\(^\\xA0+\\\\|\\xA0+$\\\\)\"	\
visualize leading and/or trailing HARD SPACEs.
   \"\\t\\\\(\\xA0+\\\\)\\t\"		\
visualize only HARD SPACEs between TABs.

NOTE: Enclose always by \\\\( and \\\\) the elements to highlight.
      Use exactly one pair of enclosing \\\\( and \\\\).

Used when `whitespace-style' includes `spaces'."
  :type '(regexp :tag "HARD SPACE Chars")
  :group 'whitespace)


(defcustom whitespace-space-regexp "\\( +\\)"
  "Specify SPACE characters regexp.

If you're using `mule' package, there may be other characters
besides \" \" that should be considered SPACE.

Here are some examples:

   \"\\\\(^ +\\\\)\"		visualize only leading SPACEs.
   \"\\\\( +$\\\\)\"		visualize only trailing SPACEs.
   \"\\\\(^ +\\\\| +$\\\\)\"	\
visualize leading and/or trailing SPACEs.
   \"\\t\\\\( +\\\\)\\t\"	visualize only SPACEs between TABs.

NOTE: Enclose always by \\\\( and \\\\) the elements to highlight.
      Use exactly one pair of enclosing \\\\( and \\\\).

Used when `whitespace-style' includes `spaces'."
  :type '(regexp :tag "SPACE Chars")
  :group 'whitespace)


(defcustom whitespace-tab-regexp "\\(\t+\\)"
  "Specify TAB characters regexp.

If you're using `mule' package, there may be other characters
besides \"\\t\" that should be considered TAB.

Here are some examples:

   \"\\\\(^\\t+\\\\)\"		visualize only leading TABs.
   \"\\\\(\\t+$\\\\)\"		visualize only trailing TABs.
   \"\\\\(^\\t+\\\\|\\t+$\\\\)\"	\
visualize leading and/or trailing TABs.
   \" \\\\(\\t+\\\\) \"	visualize only TABs between SPACEs.

NOTE: Enclose always by \\\\( and \\\\) the elements to highlight.
      Use exactly one pair of enclosing \\\\( and \\\\).

Used when `whitespace-style' includes `tabs'."
  :type '(regexp :tag "TAB Chars")
  :group 'whitespace)


(defcustom whitespace-trailing-regexp
  "\\([\t \u00A0]+\\)$"
  "Specify trailing characters regexp.

There may be other characters besides:

   \" \"  \"\\t\"  \"\\u00A0\"

that should be considered blank.

NOTE: Enclose always by \"\\\\(\" and \"\\\\)$\" the elements to highlight.
      Use exactly one pair of enclosing elements above.

Used when `whitespace-style' includes `trailing'."
  :type '(regexp :tag "Trailing Chars")
  :group 'whitespace)


(defcustom whitespace-space-before-tab-regexp "\\( +\\)\\(\t+\\)"
  "Specify SPACEs before TAB regexp.

Used when `whitespace-style' includes `space-before-tab',
`space-before-tab::tab' or  `space-before-tab::space'."
  :type '(regexp :tag "SPACEs Before TAB")
  :group 'whitespace)


(defcustom whitespace-indentation-regexp
  '("^\t*\\(\\( \\{%d\\}\\)+\\)[^\n\t]"
    . "^ *\\(\t+\\)[^\n]")
  "Specify regexp for `tab-width' or more SPACEs at beginning of line.

It is a cons where the cons car is used for SPACEs visualization
and the cons cdr is used for TABs visualization.

Used when `whitespace-style' includes `indentation',
`indentation::tab' or  `indentation::space'."
  :type '(cons (string :tag "Indentation SPACEs")
	       (regexp :tag "Indentation TABs"))
  :group 'whitespace)


(defcustom whitespace-empty-at-bob-regexp "\\`\\(\\([ \t]*\n\\)+\\)"
  "Specify regexp for empty lines at beginning of buffer.

Used when `whitespace-style' includes `empty'."
  :type '(regexp :tag "Empty Lines At Beginning Of Buffer")
  :group 'whitespace)


(defcustom whitespace-empty-at-eob-regexp "^\\([ \t\n]+\\)\\'"
  "Specify regexp for empty lines at end of buffer.

Used when `whitespace-style' includes `empty'."
  :type '(regexp :tag "Empty Lines At End Of Buffer")
  :group 'whitespace)


(defcustom whitespace-space-after-tab-regexp
  '("\t+\\(\\( \\{%d,\\}\\)+\\)"
    . "\\(\t+\\) \\{%d,\\}")
  "Specify regexp for `tab-width' or more SPACEs after TAB.

It is a cons where the cons car is used for SPACEs visualization
and the cons cdr is used for TABs visualization.

Used when `whitespace-style' includes `space-after-tab',
`space-after-tab::tab' or `space-after-tab::space'."
  :type '(cons (string :tag "SPACEs After TAB")
	       string)
  :group 'whitespace)

(defcustom whitespace-big-indent-regexp
  "^\\(\\(?:\t\\{4,\\}\\| \\{32,\\}\\)[\t ]*\\)"
  "Specify big indentation regexp.

If you're using `mule' package, there may be other characters
besides \"\\t\" that should be considered TAB.

NOTE: Enclose always by \\\\( and \\\\) the elements to highlight.
      Use exactly one pair of enclosing \\\\( and \\\\).

Used when `whitespace-style' includes `big-indent'."
  :version "25.1"
  :type '(regexp :tag "Detect too much indentation at the beginning of a line")
  :group 'whitespace)


(defcustom whitespace-line-column 80
  "Specify column beyond which the line is highlighted.

It must be an integer or nil.  If nil, the `fill-column' variable value is
used.

Used when `whitespace-style' includes `lines' or `lines-tail'."
  :type '(choice :tag "Line Length Limit"
		 (integer :tag "Line Length")
		 (const :tag "Use fill-column" nil))
  :safe  'integerp
  :group 'whitespace)


;; Hacked from `visible-whitespace-mappings' in visws.el
(defcustom whitespace-display-mappings
  '(
    (space-mark   ?\     []     [?.])		; space - middle dot
    (space-mark   ?\xA0  []     [?_])		; hard space - currency sign
    ;; NEWLINE is displayed using the face `whitespace-newline'
    (newline-mark ?\n    [?$ ?\n])			; eol - dollar sign
    ;; (newline-mark ?\n    [?↵ ?\n] [?$ ?\n])	; eol - downwards arrow
    ;; (newline-mark ?\n    [?¶ ?\n] [?$ ?\n])	; eol - pilcrow
    ;; (newline-mark ?\n    [?¯ ?\n]  [?$ ?\n])	; eol - overscore
    ;; (newline-mark ?\n    [?¬ ?\n]  [?$ ?\n])	; eol - negation
    ;; (newline-mark ?\n    [?° ?\n]  [?$ ?\n])	; eol - degrees
    ;;
    ;; WARNING: the mapping below has a problem.
    ;; When a TAB occupies exactly one column, it will display the
    ;; character ?\xBB at that column followed by a TAB which goes to
    ;; the next TAB column.
    ;; If this is a problem for you, please, comment the line below.
    (tab-mark     ?\t    [ ?\t] [?\\ ?\t])	; tab - right guillemet
    )
  "Specify an alist of mappings for displaying characters.

Each element has the following form:

   (KIND CHAR VECTOR...)

Where:

KIND	is the kind of character.
	It can be one of the following symbols:

	tab-mark	for TAB character

	space-mark	for SPACE or HARD SPACE character

	newline-mark	for NEWLINE character

CHAR	is the character to be mapped.

VECTOR	is a vector of characters to be displayed in place of CHAR.
	The first display vector that can be displayed is used;
	if no display vector for a mapping can be displayed, then
	that character is displayed unmodified.

The NEWLINE character is displayed using the face given by
`whitespace-newline' variable.

Used when `whitespace-style' includes `tab-mark', `space-mark' or
`newline-mark'."
  :type '(repeat
	  (list :tag "Character Mapping"
		(choice :tag "Char Kind"
			(const :tag "Tab" tab-mark)
			(const :tag "Space" space-mark)
			(const :tag "Newline" newline-mark))
		(character :tag "Char")
		(repeat :inline t :tag "Vector List"
			(vector :tag ""
				(repeat :inline t
					:tag "Vector Characters"
					(character :tag "Char"))))))
  :group 'whitespace)


(defcustom whitespace-global-modes t
  "Modes for which global `whitespace-mode' is automagically turned on.

Global `whitespace-mode' is controlled by the command
`global-whitespace-mode'.

If nil, means no modes have `whitespace-mode' automatically
turned on.

If t, all modes that support `whitespace-mode' have it
automatically turned on.

Else it should be a list of `major-mode' symbol names for which
`whitespace-mode' should be automatically turned on.  The sense
of the list is negated if it begins with `not'.  For example:

   (c-mode c++-mode)

means that `whitespace-mode' is turned on for buffers in C and
C++ modes only."
  :type '(choice :tag "Global Modes"
		 (const :tag "None" nil)
		 (const :tag "All" t)
		 (set :menu-tag "Mode Specific" :tag "Modes"
		      :value (not)
		      (const :tag "Except" not)
		      (repeat :inline t
			      (symbol :tag "Mode"))))
  :group 'whitespace)


(defcustom whitespace-action nil
  "Specify which action is taken when a buffer is visited or written.

It's a list containing some or all of the following values:

   nil			no action is taken.

   cleanup		cleanup any bogus whitespace always when local
			whitespace is turned on.
			See `whitespace-cleanup' and
			`whitespace-cleanup-region'.

   report-on-bogus	report if there is any bogus whitespace always
			when local whitespace is turned on.

   auto-cleanup		cleanup any bogus whitespace when buffer is
			written.
			See `whitespace-cleanup' and
			`whitespace-cleanup-region'.

   abort-on-bogus	abort if there is any bogus whitespace and the
			buffer is written.

   warn-if-read-only	give a warning if `cleanup' or `auto-cleanup'
			is included in `whitespace-action' and the
			buffer is read-only.

Any other value is treated as nil."
  :type '(choice :tag "Actions"
		 (const :tag "None" nil)
		 (repeat :tag "Action List"
		  (choice :tag "Action"
			  (const :tag "Cleanup When On" cleanup)
			  (const :tag "Report On Bogus" report-on-bogus)
			  (const :tag "Auto Cleanup" auto-cleanup)
			  (const :tag "Abort On Bogus" abort-on-bogus)
			  (const :tag "Warn If Read-Only" warn-if-read-only))))
  :group 'whitespace)


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; User commands - Local mode


;;;###autoload
(define-minor-mode whitespace-mode
  "Toggle whitespace visualization (Whitespace mode).

See also `whitespace-style', `whitespace-newline' and
`whitespace-display-mappings'."
  :lighter    " ws"
  :init-value nil
  :global     nil
  :group      'whitespace
  (cond
   (noninteractive			; running a batch job
    (setq whitespace-mode nil))
   (whitespace-mode			; whitespace-mode on
    (whitespace-turn-on)
    (whitespace-action-when-on))
   (t					; whitespace-mode off
    (whitespace-turn-off))))


;;;###autoload
(define-minor-mode whitespace-newline-mode
  "Toggle newline visualization (Whitespace Newline mode).

Use `whitespace-newline-mode' only for NEWLINE visualization
exclusively.  For other visualizations, including NEWLINE
visualization together with (HARD) SPACEs and/or TABs, please,
use `whitespace-mode'.

See also `whitespace-newline' and `whitespace-display-mappings'."
  :lighter    " nl"
  :init-value nil
  :global     nil
  :group      'whitespace
  (let ((whitespace-style '(face newline-mark newline)))
    (whitespace-mode (if whitespace-newline-mode
			 1 -1)))
  ;; sync states (running a batch job)
  (setq whitespace-newline-mode whitespace-mode))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; User commands - Global mode


;;;###autoload
(define-minor-mode global-whitespace-mode
  "Toggle whitespace visualization globally (Global Whitespace mode).

See also `whitespace-style', `whitespace-newline' and
`whitespace-display-mappings'."
  :lighter    " WS"
  :init-value nil
  :global     t
  :group      'whitespace
  (cond
   (noninteractive			; running a batch job
    (setq global-whitespace-mode nil))
   (global-whitespace-mode		; global-whitespace-mode on
    (save-current-buffer
      (add-hook 'find-file-hook 'whitespace-turn-on-if-enabled)
      (add-hook 'after-change-major-mode-hook 'whitespace-turn-on-if-enabled)
      (dolist (buffer (buffer-list))	; adjust all local mode
	(set-buffer buffer)
	(unless whitespace-mode
	  (whitespace-turn-on-if-enabled)))))
   (t					; global-whitespace-mode off
    (save-current-buffer
      (remove-hook 'find-file-hook 'whitespace-turn-on-if-enabled)
      (remove-hook 'after-change-major-mode-hook 'whitespace-turn-on-if-enabled)
      (dolist (buffer (buffer-list))	; adjust all local mode
	(set-buffer buffer)
	(unless whitespace-mode
	  (whitespace-turn-off)))))))

(defvar whitespace-enable-predicate
  (lambda ()
    (and (cond
          ((eq whitespace-global-modes t))
          ((listp whitespace-global-modes)
           (if (eq (car-safe whitespace-global-modes) 'not)
               (not (apply #'derived-mode-p (cdr whitespace-global-modes)))
             (apply #'derived-mode-p whitespace-global-modes)))
          (t nil))
         ;; ...we have a display (not running a batch job)
         (not noninteractive)
         ;; ...the buffer is not internal (name starts with a space)
         (not (eq (aref (buffer-name) 0) ?\ ))
         ;; ...the buffer is not special (name starts with *)
         (or (not (eq (aref (buffer-name) 0) ?*))
             ;; except the scratch buffer.
             (string= (buffer-name) "*scratch*"))))
  "Predicate to decide which buffers obey `global-whitespace-mode'.
This function is called with no argument and should return non-nil
if the current buffer should obey `global-whitespace-mode'.
This variable is normally modified via `add-function'.")

(defun whitespace-turn-on-if-enabled ()
  (when (funcall whitespace-enable-predicate)
    (whitespace-turn-on)))

;;;###autoload
(define-minor-mode global-whitespace-newline-mode
  "Toggle global newline visualization (Global Whitespace Newline mode).

Use `global-whitespace-newline-mode' only for NEWLINE
visualization exclusively.  For other visualizations, including
NEWLINE visualization together with (HARD) SPACEs and/or TABs,
please use `global-whitespace-mode'.

See also `whitespace-newline' and `whitespace-display-mappings'."
  :lighter    " NL"
  :init-value nil
  :global     t
  :group      'whitespace
  (let ((whitespace-style '(newline-mark newline)))
    (global-whitespace-mode (if global-whitespace-newline-mode
                                1 -1))
    ;; sync states (running a batch job)
    (setq global-whitespace-newline-mode global-whitespace-mode)))
(make-obsolete 'global-whitespace-newline-mode
               "use `global-whitespace-mode' with `whitespace-style' set to `(newline-mark newline)' instead."
               "28.1")


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; User commands - Toggle


(defconst whitespace-style-value-list
  '(face
    tabs
    spaces
    trailing
    lines
    lines-tail
    newline
    empty
    indentation
    indentation::tab
    indentation::space
    big-indent
    space-after-tab
    space-after-tab::tab
    space-after-tab::space
    space-before-tab
    space-before-tab::tab
    space-before-tab::space
    help-newline       ; value used by `whitespace-insert-option-mark'
    tab-mark
    space-mark
    newline-mark
    )
  "List of valid `whitespace-style' values.")


(defconst whitespace-toggle-option-alist
  '((?f    . face)
    (?t    . tabs)
    (?s    . spaces)
    (?r    . trailing)
    (?l    . lines)
    (?L    . lines-tail)
    (?n    . newline)
    (?e    . empty)
    (?\C-i . indentation)
    (?I    . indentation::tab)
    (?i    . indentation::space)
    (?\C-t . big-indent)
    (?\C-a . space-after-tab)
    (?A    . space-after-tab::tab)
    (?a    . space-after-tab::space)
    (?\C-b . space-before-tab)
    (?B    . space-before-tab::tab)
    (?b    . space-before-tab::space)
    (?T    . tab-mark)
    (?S    . space-mark)
    (?N    . newline-mark)
    (?x    . whitespace-style)
    )
  "Alist of toggle options.

Each element has the form:

   (CHAR . SYMBOL)

Where:

CHAR	is a char which the user will have to type.

SYMBOL	is a valid symbol associated with CHAR.
	See `whitespace-style-value-list'.")


(defvar whitespace-active-style nil
  "Used to save locally `whitespace-style' value.")

(defvar whitespace-point (point)
  "Used to save locally current point value.
Used by function `whitespace-trailing-regexp' (which see).")
(defvar-local whitespace-point--used nil
  "Region whose highlighting depends on `whitespace-point'.")

(defvar whitespace-font-lock-refontify nil
  "Used to save locally the font-lock refontify state.
Used by function `whitespace-post-command-hook' (which see).")

(defvar whitespace-bob-marker nil
  "Used to save locally the bob marker value.
Used by function `whitespace-post-command-hook' (which see).")

(defvar whitespace-eob-marker nil
  "Used to save locally the eob marker value.
Used by function `whitespace-post-command-hook' (which see).")

(defvar whitespace-buffer-changed nil
  "Used to indicate locally if buffer changed.
Used by `whitespace-post-command-hook' and `whitespace-buffer-changed'
functions (which see).")


;;;###autoload
(defun whitespace-toggle-options (arg)
  "Toggle local `whitespace-mode' options.

If local whitespace-mode is off, toggle the option given by ARG
and turn on local whitespace-mode.

If local whitespace-mode is on, toggle the option given by ARG
and restart local whitespace-mode.

Interactively, it reads one of the following chars:

  CHAR	MEANING
  (VIA FACES)
   f	toggle face visualization
   t	toggle TAB visualization
   s	toggle SPACE and HARD SPACE visualization
   r	toggle trailing blanks visualization
   l	toggle \"long lines\" visualization
   L	toggle \"long lines\" tail visualization
   n	toggle NEWLINE visualization
   e	toggle empty line at bob and/or eob visualization
   C-i	toggle indentation SPACEs visualization (via `indent-tabs-mode')
   I	toggle indentation SPACEs visualization
   i	toggle indentation TABs visualization
   C-t	toggle big indentation visualization
   C-a	toggle SPACEs after TAB visualization (via `indent-tabs-mode')
   A	toggle SPACEs after TAB: SPACEs visualization
   a	toggle SPACEs after TAB: TABs visualization
   C-b	toggle SPACEs before TAB visualization (via `indent-tabs-mode')
   B	toggle SPACEs before TAB: SPACEs visualization
   b	toggle SPACEs before TAB: TABs visualization

  (VIA DISPLAY TABLE)
   T	toggle TAB visualization
   S	toggle SPACEs before TAB visualization
   N	toggle NEWLINE visualization

   x	restore `whitespace-style' value
   ?	display brief help

Non-interactively, ARG should be a symbol or a list of symbols.
The valid symbols are:

   face			toggle face visualization
   tabs			toggle TAB visualization
   spaces		toggle SPACE and HARD SPACE visualization
   trailing		toggle trailing blanks visualization
   lines		toggle \"long lines\" visualization
   lines-tail		toggle \"long lines\" tail visualization
   newline		toggle NEWLINE visualization
   empty		toggle empty line at bob and/or eob visualization
   indentation		toggle indentation SPACEs visualization
   indentation::tab	toggle indentation SPACEs visualization
   indentation::space	toggle indentation TABs visualization
   big-indent		toggle big indentation visualization
   space-after-tab		toggle SPACEs after TAB visualization
   space-after-tab::tab		toggle SPACEs after TAB: SPACEs visualization
   space-after-tab::space	toggle SPACEs after TAB: TABs visualization
   space-before-tab		toggle SPACEs before TAB visualization
   space-before-tab::tab	toggle SPACEs before TAB: SPACEs visualization
   space-before-tab::space	toggle SPACEs before TAB: TABs visualization

   tab-mark		toggle TAB visualization
   space-mark		toggle SPACEs before TAB visualization
   newline-mark		toggle NEWLINE visualization

   whitespace-style	restore `whitespace-style' value

See `whitespace-style' and `indent-tabs-mode' for documentation."
  (interactive (whitespace-interactive-char t))
  (let ((whitespace-style
	 (whitespace-toggle-list t arg whitespace-active-style)))
    (whitespace-mode 0)
    (whitespace-mode 1)))


(defvar whitespace-toggle-style nil
  "Used to toggle the global `whitespace-style' value.")


;;;###autoload
(defun global-whitespace-toggle-options (arg)
  "Toggle global `whitespace-mode' options.

If global whitespace-mode is off, toggle the option given by ARG
and turn on global whitespace-mode.

If global whitespace-mode is on, toggle the option given by ARG
and restart global whitespace-mode.

Interactively, it accepts one of the following chars:

  CHAR	MEANING
  (VIA FACES)
   f	toggle face visualization
   t	toggle TAB visualization
   s	toggle SPACE and HARD SPACE visualization
   r	toggle trailing blanks visualization
   l	toggle \"long lines\" visualization
   L	toggle \"long lines\" tail visualization
   n	toggle NEWLINE visualization
   e	toggle empty line at bob and/or eob visualization
   C-i	toggle indentation SPACEs visualization (via `indent-tabs-mode')
   I	toggle indentation SPACEs visualization
   i	toggle indentation TABs visualization
   C-t	toggle big indentation visualization
   C-a	toggle SPACEs after TAB visualization (via `indent-tabs-mode')
   A	toggle SPACEs after TAB: SPACEs visualization
   a	toggle SPACEs after TAB: TABs visualization
   C-b	toggle SPACEs before TAB visualization (via `indent-tabs-mode')
   B	toggle SPACEs before TAB: SPACEs visualization
   b	toggle SPACEs before TAB: TABs visualization

  (VIA DISPLAY TABLE)
   T	toggle TAB visualization
   S	toggle SPACEs before TAB visualization
   N	toggle NEWLINE visualization

   x	restore `whitespace-style' value
   ?	display brief help

Non-interactively, ARG should be a symbol or a list of symbols.
The valid symbols are:

   face			toggle face visualization
   tabs			toggle TAB visualization
   spaces		toggle SPACE and HARD SPACE visualization
   trailing		toggle trailing blanks visualization
   lines		toggle \"long lines\" visualization
   lines-tail		toggle \"long lines\" tail visualization
   newline		toggle NEWLINE visualization
   empty		toggle empty line at bob and/or eob visualization
   indentation		toggle indentation SPACEs visualization
   indentation::tab	toggle indentation SPACEs visualization
   indentation::space	toggle indentation TABs visualization
   big-indent		toggle big indentation visualization
   space-after-tab		toggle SPACEs after TAB visualization
   space-after-tab::tab		toggle SPACEs after TAB: SPACEs visualization
   space-after-tab::space	toggle SPACEs after TAB: TABs visualization
   space-before-tab		toggle SPACEs before TAB visualization
   space-before-tab::tab	toggle SPACEs before TAB: SPACEs visualization
   space-before-tab::space	toggle SPACEs before TAB: TABs visualization

   tab-mark		toggle TAB visualization
   space-mark		toggle SPACEs before TAB visualization
   newline-mark		toggle NEWLINE visualization

   whitespace-style	restore `whitespace-style' value

See `whitespace-style' and `indent-tabs-mode' for documentation."
  (interactive (whitespace-interactive-char nil))
  (let ((whitespace-style
	 (whitespace-toggle-list nil arg whitespace-toggle-style)))
    (setq whitespace-toggle-style whitespace-style)
    (global-whitespace-mode 0)
    (global-whitespace-mode 1)))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; User commands - Cleanup


;;;###autoload
(defun whitespace-cleanup ()
  "Cleanup some blank problems in all buffer or at region.

It usually applies to the whole buffer, but in transient mark
mode when the mark is active, it applies to the region.  It also
applies to the region when it is not in transient mark mode, the
mark is active and \\[universal-argument] was pressed just before
calling `whitespace-cleanup' interactively.

See also `whitespace-cleanup-region'.

The problems cleaned up are:

1. empty lines at beginning of buffer.
2. empty lines at end of buffer.
   If `whitespace-style' includes the value `empty', remove all
   empty lines at beginning and/or end of buffer.

3. `tab-width' or more SPACEs at beginning of line.
   If `whitespace-style' includes the value `indentation':
   replace `tab-width' or more SPACEs at beginning of line by
   TABs, if `indent-tabs-mode' is non-nil; otherwise, replace TABs by
   SPACEs.
   If `whitespace-style' includes the value `indentation::tab',
   replace `tab-width' or more SPACEs at beginning of line by TABs.
   If `whitespace-style' includes the value `indentation::space',
   replace TABs by SPACEs.

4. SPACEs before TAB.
   If `whitespace-style' includes the value `space-before-tab':
   replace SPACEs by TABs, if `indent-tabs-mode' is non-nil;
   otherwise, replace TABs by SPACEs.
   If `whitespace-style' includes the value
   `space-before-tab::tab', replace SPACEs by TABs.
   If `whitespace-style' includes the value
   `space-before-tab::space', replace TABs by SPACEs.

5. SPACEs or TABs at end of line.
   If `whitespace-style' includes the value `trailing', remove
   all SPACEs or TABs at end of line.

6. `tab-width' or more SPACEs after TAB.
   If `whitespace-style' includes the value `space-after-tab':
   replace SPACEs by TABs, if `indent-tabs-mode' is non-nil;
   otherwise, replace TABs by SPACEs.
   If `whitespace-style' includes the value
   `space-after-tab::tab', replace SPACEs by TABs.
   If `whitespace-style' includes the value
   `space-after-tab::space', replace TABs by SPACEs.

See `whitespace-style', `indent-tabs-mode' and `tab-width' for
documentation."
  (interactive "@")
  (cond
   ;; read-only buffer
   (buffer-read-only
    (whitespace-warn-read-only "cleanup"))
   ;; region active
   ((and (or transient-mark-mode
	     current-prefix-arg)
	 mark-active)
    ;; PROBLEMs 1 and 2 are not handled in region
    ;; PROBLEM 3: `tab-width' or more SPACEs at bol
    ;; PROBLEM 4: SPACEs before TAB
    ;; PROBLEM 5: SPACEs or TABs at eol
    ;; PROBLEM 6: `tab-width' or more SPACEs after TAB
    (whitespace-cleanup-region (region-beginning) (region-end)))
   ;; whole buffer
   (t
    (save-excursion
      ;; PROBLEM 1: empty lines at bob
      ;; PROBLEM 2: empty lines at eob
      ;; ACTION: remove all empty lines at bob and/or eob
      (when (memq 'empty whitespace-style)
        (let (overwrite-mode)		; enforce no overwrite
          (goto-char (point-min))
          (when (looking-at whitespace-empty-at-bob-regexp)
            (delete-region (match-beginning 1) (match-end 1)))
          (when (re-search-forward
                 whitespace-empty-at-eob-regexp nil t)
            (delete-region (match-beginning 1) (match-end 1))))))
    ;; PROBLEM 3: `tab-width' or more SPACEs at bol
    ;; PROBLEM 4: SPACEs before TAB
    ;; PROBLEM 5: SPACEs or TABs at eol
    ;; PROBLEM 6: `tab-width' or more SPACEs after TAB
    (whitespace-cleanup-region (point-min) (point-max)))))


;;;###autoload
(defun whitespace-cleanup-region (start end)
  "Cleanup some blank problems at region.

The problems cleaned up are:

1. `tab-width' or more SPACEs at beginning of line.
   If `whitespace-style' includes the value `indentation':
   replace `tab-width' or more SPACEs at beginning of line by TABs,
   if `indent-tabs-mode' is non-nil; otherwise, replace TABs by
   SPACEs.
   If `whitespace-style' includes the value `indentation::tab',
   replace `tab-width' or more SPACEs at beginning of line by TABs.
   If `whitespace-style' includes the value `indentation::space',
   replace TABs by SPACEs.

2. SPACEs before TAB.
   If `whitespace-style' includes the value `space-before-tab':
   replace SPACEs by TABs, if `indent-tabs-mode' is non-nil;
   otherwise, replace TABs by SPACEs.
   If `whitespace-style' includes the value
   `space-before-tab::tab', replace SPACEs by TABs.
   If `whitespace-style' includes the value
   `space-before-tab::space', replace TABs by SPACEs.

3. SPACEs or TABs at end of line.
   If `whitespace-style' includes the value `trailing', remove
   all SPACEs or TABs at end of line.

4. `tab-width' or more SPACEs after TAB.
   If `whitespace-style' includes the value `space-after-tab':
   replace SPACEs by TABs, if `indent-tabs-mode' is non-nil;
   otherwise, replace TABs by SPACEs.
   If `whitespace-style' includes the value
   `space-after-tab::tab', replace SPACEs by TABs.
   If `whitespace-style' includes the value
   `space-after-tab::space', replace TABs by SPACEs.

See `whitespace-style', `indent-tabs-mode' and `tab-width' for
documentation."
  (interactive "@r")
  (if buffer-read-only
      ;; read-only buffer
      (whitespace-warn-read-only "cleanup region")
    ;; non-read-only buffer
    (let ((rstart           (min start end))
	  (rend             (copy-marker (max start end)))
	  overwrite-mode		; enforce no overwrite
	  tmp)
      (save-excursion
        ;; PROBLEM 1: `tab-width' or more SPACEs at bol
        (cond
         ;; ACTION: replace `tab-width' or more SPACEs at bol by TABs, if
         ;; `indent-tabs-mode' is non-nil; otherwise, replace TABs
         ;; by SPACEs.
         ((memq 'indentation whitespace-style)
          (let ((regexp (whitespace-indentation-regexp)))
            (goto-char rstart)
            (while (re-search-forward regexp rend t)
              (setq tmp (current-indentation))
              (goto-char (match-beginning 0))
              (delete-horizontal-space)
              (unless (eolp)
                (indent-to tmp)))))
         ;; ACTION: replace `tab-width' or more SPACEs at bol by TABs.
         ((memq 'indentation::tab whitespace-style)
          (whitespace-replace-action
           'tabify rstart rend
           (whitespace-indentation-regexp 'tab) 0))
         ;; ACTION: replace TABs by SPACEs.
         ((memq 'indentation::space whitespace-style)
          (whitespace-replace-action
           'untabify rstart rend
           (whitespace-indentation-regexp 'space) 0)))
        ;; PROBLEM 3: SPACEs or TABs at eol
        ;; ACTION: remove all SPACEs or TABs at eol
        (when (memq 'trailing whitespace-style)
          (whitespace-replace-action
           'delete-region rstart rend
           whitespace-trailing-regexp 1))
        ;; PROBLEM 4: `tab-width' or more SPACEs after TAB
        (cond
         ;; ACTION: replace `tab-width' or more SPACEs by TABs, if
         ;; `indent-tabs-mode' is non-nil; otherwise, replace TABs
         ;; by SPACEs.
         ((memq 'space-after-tab whitespace-style)
          (whitespace-replace-action
           (if indent-tabs-mode 'tabify 'untabify)
           rstart rend (whitespace-space-after-tab-regexp) 1))
         ;; ACTION: replace `tab-width' or more SPACEs by TABs.
         ((memq 'space-after-tab::tab whitespace-style)
          (whitespace-replace-action
           'tabify rstart rend
           (whitespace-space-after-tab-regexp 'tab) 1))
         ;; ACTION: replace TABs by SPACEs.
         ((memq 'space-after-tab::space whitespace-style)
          (whitespace-replace-action
           'untabify rstart rend
           (whitespace-space-after-tab-regexp 'space) 1)))
        ;; PROBLEM 2: SPACEs before TAB
        (cond
         ;; ACTION: replace SPACEs before TAB by TABs, if
         ;; `indent-tabs-mode' is non-nil; otherwise, replace TABs
         ;; by SPACEs.
         ((memq 'space-before-tab whitespace-style)
          (whitespace-replace-action
           (if indent-tabs-mode 'tabify 'untabify)
           rstart rend whitespace-space-before-tab-regexp
           (if indent-tabs-mode 0 2)))
         ;; ACTION: replace SPACEs before TAB by TABs.
         ((memq 'space-before-tab::tab whitespace-style)
          (whitespace-replace-action
           'tabify rstart rend
           whitespace-space-before-tab-regexp 0))
         ;; ACTION: replace TABs by SPACEs.
         ((memq 'space-before-tab::space whitespace-style)
          (whitespace-replace-action
           'untabify rstart rend
           whitespace-space-before-tab-regexp 2))))
      (set-marker rend nil))))		; point marker to nowhere


(defun whitespace-replace-action (action rstart rend regexp index)
  "Do ACTION in the string matched by REGEXP between RSTART and REND.

INDEX is the level group matched by REGEXP and used by ACTION.

See also `tab-width'."
  (goto-char rstart)
  (while (re-search-forward regexp rend t)
    (goto-char (match-end index))
    (funcall action (match-beginning index) (match-end index))))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; User command - report


(defun whitespace-regexp (regexp &optional kind)
  "Return REGEXP depending on `indent-tabs-mode'."
  (format
   (cond
    ((or (eq kind 'tab)
         indent-tabs-mode)
     (car regexp))
    ((or (eq kind 'space)
         (not indent-tabs-mode))
     (cdr regexp)))
   tab-width))


(defun whitespace-indentation-regexp (&optional kind)
  "Return the indentation regexp depending on `indent-tabs-mode'."
  (whitespace-regexp whitespace-indentation-regexp kind))


(defun whitespace-space-after-tab-regexp (&optional kind)
  "Return the space-after-tab regexp depending on `indent-tabs-mode'."
  (whitespace-regexp whitespace-space-after-tab-regexp kind))


(defconst whitespace-report-list
  (list
   (cons 'empty                   whitespace-empty-at-bob-regexp)
   (cons 'empty                   whitespace-empty-at-eob-regexp)
   (cons 'trailing                whitespace-trailing-regexp)
   (cons 'indentation             nil)
   (cons 'indentation::tab        nil)
   (cons 'indentation::space      nil)
   (cons 'space-before-tab        whitespace-space-before-tab-regexp)
   (cons 'space-before-tab::tab   whitespace-space-before-tab-regexp)
   (cons 'space-before-tab::space whitespace-space-before-tab-regexp)
   (cons 'space-after-tab         nil)
   (cons 'space-after-tab::tab    nil)
   (cons 'space-after-tab::space  nil)
   )
   "List of whitespace bogus symbol and corresponding regexp.")


(defconst whitespace-report-text
  '( ;; `indent-tabs-mode' has non-nil value
    "\
 Whitespace Report

 Current Setting                       Whitespace Problem

 empty                    []     []  empty lines at beginning of buffer
 empty                    []     []  empty lines at end of buffer
 trailing                 []     []  SPACEs or TABs at end of line
 indentation              []     []  >= `tab-width' SPACEs at beginning of line
 indentation::tab         []     []  >= `tab-width' SPACEs at beginning of line
 indentation::space       []     []  TABs at beginning of line
 space-before-tab         []     []  SPACEs before TAB
 space-before-tab::tab    []     []  SPACEs before TAB: SPACEs
 space-before-tab::space  []     []  SPACEs before TAB: TABs
 space-after-tab          []     []  >= `tab-width' SPACEs after TAB
 space-after-tab::tab     []     []  >= `tab-width' SPACEs after TAB: SPACEs
 space-after-tab::space   []     []  >= `tab-width' SPACEs after TAB: TABs

 indent-tabs-mode =
 tab-width        = \n\n"
    . ;; `indent-tabs-mode' has nil value
    "\
 Whitespace Report

 Current Setting                       Whitespace Problem

 empty                    []     []  empty lines at beginning of buffer
 empty                    []     []  empty lines at end of buffer
 trailing                 []     []  SPACEs or TABs at end of line
 indentation              []     []  TABs at beginning of line
 indentation::tab         []     []  >= `tab-width' SPACEs at beginning of line
 indentation::space       []     []  TABs at beginning of line
 space-before-tab         []     []  SPACEs before TAB
 space-before-tab::tab    []     []  SPACEs before TAB: SPACEs
 space-before-tab::space  []     []  SPACEs before TAB: TABs
 space-after-tab          []     []  >= `tab-width' SPACEs after TAB
 space-after-tab::tab     []     []  >= `tab-width' SPACEs after TAB: SPACEs
 space-after-tab::space   []     []  >= `tab-width' SPACEs after TAB: TABs

 indent-tabs-mode =
 tab-width        = \n\n")
  "Text for whitespace bogus report.

It is a cons of strings, where the car part is used when
`indent-tabs-mode' is non-nil, and the cdr part is used when
`indent-tabs-mode' is nil.")


(defconst whitespace-report-buffer-name "*Whitespace Report*"
  "The buffer name for whitespace bogus report.")


;;;###autoload
(defun whitespace-report (&optional force report-if-bogus)
  "Report some whitespace problems in buffer.

Perform `whitespace-report-region' on the current buffer."
  (interactive (list current-prefix-arg))
  (whitespace-report-region (point-min) (point-max)
			    force report-if-bogus))


;;;###autoload
(defun whitespace-report-region (start end &optional force report-if-bogus)
  "Report some whitespace problems in a region.

Return nil if there is no whitespace problem; otherwise, return
non-nil.

If FORCE is non-nil or \\[universal-argument] was pressed just
before calling `whitespace-report-region' interactively, it
forces all classes of whitespace problem to be considered
significant.

If REPORT-IF-BOGUS is t, it reports only when there are any
whitespace problems in buffer; if it is `never', it does not
report problems.

Report if some of the following whitespace problems exist:

* If `indent-tabs-mode' is non-nil:
   empty		1. empty lines at beginning of buffer.
   empty		2. empty lines at end of buffer.
   trailing		3. SPACEs or TABs at end of line.
   indentation		4. line starts with `tab-width' or more SPACEs.
   space-before-tab	5. SPACEs before TAB.
   space-after-tab	6. `tab-width' or more SPACEs after TAB.

* If `indent-tabs-mode' is nil:
   empty		1. empty lines at beginning of buffer.
   empty		2. empty lines at end of buffer.
   trailing		3. SPACEs or TABs at end of line.
   indentation		4. TABS at beginning of line.
   space-before-tab	5. SPACEs before TAB.
   space-after-tab	6. `tab-width' or more SPACEs after TAB.

See `whitespace-style' for documentation.
See also `whitespace-cleanup' and `whitespace-cleanup-region' for
cleaning up these problems."
  (interactive "r")
  (setq force (or current-prefix-arg force))
  (save-excursion
    (let* ((has-bogus nil)
           (rstart    (min start end))
           (rend      (max start end))
           ;; Fall back to whitespace-style so we can run before
           ;; before the mode is active.
           (style     (copy-sequence
                       (or whitespace-active-style whitespace-style)))
           (bogus-list
            (mapcar
             #'(lambda (option)
                 (when force
                   (push (car option) style))
                 (goto-char rstart)
                 (let ((regexp
                        (cond
                         ((eq (car option) 'indentation)
                          (whitespace-indentation-regexp))
                         ((eq (car option) 'indentation::tab)
                          (whitespace-indentation-regexp 'tab))
                         ((eq (car option) 'indentation::space)
                          (whitespace-indentation-regexp 'space))
                         ((eq (car option) 'space-after-tab)
                          (whitespace-space-after-tab-regexp))
                         ((eq (car option) 'space-after-tab::tab)
                          (whitespace-space-after-tab-regexp 'tab))
                         ((eq (car option) 'space-after-tab::space)
                          (whitespace-space-after-tab-regexp 'space))
                         ((eq (car option) 'missing-newline-at-eof)
                          "[^\n]\\'")
                         (t
                          (cdr option)))))
                   (when (re-search-forward regexp rend t)
                     (unless has-bogus
                       (setq has-bogus (memq (car option) style)))
                     t)))
             whitespace-report-list)))
      (when (pcase report-if-bogus ('nil t) ('never nil) (_ has-bogus))
        (whitespace-kill-buffer whitespace-report-buffer-name)
        ;; `indent-tabs-mode' may be local to current buffer
        ;; `tab-width' may be local to current buffer
        (let ((ws-indent-tabs-mode indent-tabs-mode)
              (ws-tab-width tab-width))
          (with-current-buffer (get-buffer-create
                                whitespace-report-buffer-name)
            (erase-buffer)
            (insert (if ws-indent-tabs-mode
                        (car whitespace-report-text)
                      (cdr whitespace-report-text)))
            (goto-char (point-min))
            (forward-line 3)
            (dolist (option whitespace-report-list)
              (forward-line 1)
              (whitespace-mark-x
               27 (memq (car option) style))
              (whitespace-mark-x 7 (car bogus-list))
              (setq bogus-list (cdr bogus-list)))
            (forward-line 1)
            (whitespace-insert-value ws-indent-tabs-mode)
            (whitespace-insert-value ws-tab-width)
            (when has-bogus
              (goto-char (point-max))
              (insert (substitute-command-keys
                       " Type `\\[whitespace-cleanup]'")
                      " to cleanup the buffer.\n\n"
                      (substitute-command-keys
                       " Type `\\[whitespace-cleanup-region]'")
                      " to cleanup a region.\n\n"))
            (whitespace-display-window (current-buffer)))))
      has-bogus)))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Internal functions


(defvar whitespace-font-lock-keywords nil
  "Used to save the value `whitespace-color-on' adds to `font-lock-keywords'.")


(defconst whitespace-help-text
  "\
 Whitespace Toggle Options                  | scroll up  :  SPC   or > |
                                            | scroll down:  M-SPC or < |
 FACES                                      \\__________________________/
 []  f   - toggle face visualization
 []  t   - toggle TAB visualization
 []  s   - toggle SPACE and HARD SPACE visualization
 []  r   - toggle trailing blanks visualization
 []  l   - toggle \"long lines\" visualization
 []  L   - toggle \"long lines\" tail visualization
 []  n   - toggle NEWLINE visualization
 []  e   - toggle empty line at bob and/or eob visualization
 []  C-i - toggle indentation SPACEs visualization (via `indent-tabs-mode')
 []  I   - toggle indentation SPACEs visualization
 []  i   - toggle indentation TABs visualization
 []  C-t - toggle big indentation visualization
 []  C-a - toggle SPACEs after TAB visualization (via `indent-tabs-mode')
 []  A   - toggle SPACEs after TAB: SPACEs visualization
 []  a   - toggle SPACEs after TAB: TABs visualization
 []  C-b - toggle SPACEs before TAB visualization (via `indent-tabs-mode')
 []  B   - toggle SPACEs before TAB: SPACEs visualization
 []  b   - toggle SPACEs before TAB: TABs visualization

 DISPLAY TABLE
 []  T - toggle TAB visualization
 []  S - toggle SPACE and HARD SPACE visualization
 []  N - toggle NEWLINE visualization

      x - restore `whitespace-style' value

      ? - display this text\n\n"
  "Text for whitespace toggle options.")


(defconst whitespace-help-buffer-name "*Whitespace Toggle Options*"
  "The buffer name for whitespace toggle options.")


(defun whitespace-insert-value (value)
  "Insert VALUE at column 20 of next line."
  (forward-line 1)
  (move-to-column 20 t)
  (insert (format "%s" value)))


(defun whitespace-mark-x (nchars condition)
  "Insert the mark (`X' or ` ') after NCHARS depending on CONDITION."
  (forward-char nchars)
  (insert (if condition "X" " ")))


(defun whitespace-insert-option-mark (the-list the-value)
  "Insert the option mark (`X' or ` ') in toggle options buffer."
  (goto-char (point-min))
  (forward-line 2)
  (dolist (sym  the-list)
    (if (eq sym 'help-newline)
	(forward-line 2)
      (forward-line 1)
      (whitespace-mark-x 2 (memq sym the-value)))))


(defun whitespace-help-on (style)
  "Display the whitespace toggle options."
  (unless (get-buffer whitespace-help-buffer-name)
    (delete-other-windows)
    (let ((buffer (get-buffer-create whitespace-help-buffer-name)))
      (with-current-buffer buffer
	(erase-buffer)
	(insert whitespace-help-text)
	(whitespace-insert-option-mark
	 whitespace-style-value-list style)
	(whitespace-display-window buffer)))))


(defun whitespace-display-window (buffer)
  "Display BUFFER in a new window."
  (goto-char (point-min))
  (set-buffer-modified-p nil)
  (when (< (window-height) (* 2 window-min-height))
    (kill-buffer buffer)
    (error "Window height is too small; \
can't split window to display whitespace toggle options"))
  (let ((win (split-window)))
    (set-window-buffer win buffer)
    (shrink-window-if-larger-than-buffer win)))


(defun whitespace-kill-buffer (buffer-name)
  "Kill buffer BUFFER-NAME and windows related with it."
  (let ((buffer (get-buffer buffer-name)))
    (when buffer
      (delete-windows-on buffer)
      (kill-buffer buffer))))


(defun whitespace-help-off ()
  "Remove the buffer and window of the whitespace toggle options."
  (whitespace-kill-buffer whitespace-help-buffer-name))


(defun whitespace-help-scroll (&optional up)
  "Scroll help window, if it exists.

If UP is non-nil, scroll up; otherwise, scroll down."
  (condition-case nil
      (let ((buffer (get-buffer whitespace-help-buffer-name)))
	(if buffer
	    (with-selected-window (get-buffer-window buffer)
	      (if up
		  (scroll-up 3)
		(scroll-down 3)))
	  (ding)))
    ;; handler
    ((error)
     ;; just ignore error
     )))


(defun whitespace-interactive-char (local-p)
  "Interactive function to read a char and return a symbol.

If LOCAL-P is non-nil, it uses a local context; otherwise, it
uses a global context.

It accepts one of the following chars:

  CHAR	MEANING
  (VIA FACES)
   f	toggle face visualization
   t	toggle TAB visualization
   s	toggle SPACE and HARD SPACE visualization
   r	toggle trailing blanks visualization
   l	toggle \"long lines\" visualization
   L	toggle \"long lines\" tail visualization
   n	toggle NEWLINE visualization
   e	toggle empty line at bob and/or eob visualization
   C-i	toggle indentation SPACEs visualization (via `indent-tabs-mode')
   I	toggle indentation SPACEs visualization
   i	toggle indentation TABs visualization
   C-a	toggle SPACEs after TAB visualization (via `indent-tabs-mode')
   A	toggle SPACEs after TAB: SPACEs visualization
   a	toggle SPACEs after TAB: TABs visualization
   C-b	toggle SPACEs before TAB visualization (via `indent-tabs-mode')
   B	toggle SPACEs before TAB: SPACEs visualization
   b	toggle SPACEs before TAB: TABs visualization

  (VIA DISPLAY TABLE)
   T	toggle TAB visualization
   S	toggle SPACE and HARD SPACE visualization
   N	toggle NEWLINE visualization

   x	restore `whitespace-style' value
   ?	display brief help

See also `whitespace-toggle-option-alist'."
  (let* ((is-off (not (if local-p
			  whitespace-mode
			global-whitespace-mode)))
	 (style  (cond (is-off  whitespace-style) ; use default value
		       (local-p whitespace-active-style)
		       (t       whitespace-toggle-style)))
	 (prompt
	  (format "Whitespace Toggle %s (type ? for further options)-"
		  (if local-p "Local" "Global")))
	 ch sym)
    ;; read a valid option and get the corresponding symbol
    (save-window-excursion
      (condition-case data
	  (progn
	    (while
		;; while condition
		(progn
		  (setq ch (read-char prompt))
		  (not
		   (setq sym
			 (cdr
			  (assq ch whitespace-toggle-option-alist)))))
	      ;; while body
	      (cond
	       ((eq ch ?\?)   (whitespace-help-on style))
	       ((eq ch ?\ )   (whitespace-help-scroll t))
	       ((eq ch ?\M- ) (whitespace-help-scroll))
	       ((eq ch ?>)    (whitespace-help-scroll t))
	       ((eq ch ?<)    (whitespace-help-scroll))
	       (t             (ding))))
	    (whitespace-help-off)
	    (message " "))		; clean echo area
	;; handler
	((quit error)
	 (whitespace-help-off)
	 (error (error-message-string data)))))
    (list sym)))			; return the appropriate symbol


(defun whitespace-toggle-list (local-p arg the-list)
  "Toggle options in THE-LIST based on list ARG.

If LOCAL-P is non-nil, it uses a local context; otherwise, it
uses a global context.

ARG is a list of options to be toggled.

THE-LIST is a list of options.  This list will be toggled and the
resultant list will be returned."
  (unless (if local-p whitespace-mode global-whitespace-mode)
    (setq the-list whitespace-style))
  (setq the-list (copy-sequence the-list)) ; keep original list
  (dolist (sym (if (listp arg) arg (list arg)))
    (cond
     ;; ignore help value
     ((eq sym 'help-newline))
     ;; restore default values
     ((eq sym 'whitespace-style)
      (setq the-list whitespace-style))
     ;; toggle valid values
     ((memq sym whitespace-style-value-list)
      (setq the-list (if (memq sym the-list)
			 (delq sym the-list)
		       (cons sym the-list))))))
  the-list)


(defvar whitespace-display-table nil
  "Used to save a local display table.")

(defvar whitespace-display-table-was-local nil
  "Used to remember whether a buffer initially had a local display table.")

(defun whitespace-turn-on ()
  "Turn on whitespace visualization."
  ;; prepare local hooks
  (add-hook 'write-file-functions 'whitespace-write-file-hook nil t)
  ;; create whitespace local buffer environment
  (setq-local whitespace-font-lock-keywords nil)
  (setq-local whitespace-display-table nil)
  (setq-local whitespace-display-table-was-local nil)
  (setq-local whitespace-active-style
              (if (listp whitespace-style)
	          whitespace-style
	        (list whitespace-style)))
  ;; turn on whitespace
  (when whitespace-active-style
    (whitespace-color-on)
    (whitespace-display-char-on)))


(defun whitespace-turn-off ()
  "Turn off whitespace visualization."
  (remove-hook 'write-file-functions 'whitespace-write-file-hook t)
  (when whitespace-active-style
    (whitespace-color-off)
    (whitespace-display-char-off)))


(defun whitespace-style-face-p ()
  "Return t if there is some visualization via face."
  (and (memq 'face whitespace-active-style)
       (or (memq 'tabs                    whitespace-active-style)
	   (memq 'spaces                  whitespace-active-style)
	   (memq 'trailing                whitespace-active-style)
	   (memq 'lines                   whitespace-active-style)
	   (memq 'lines-tail              whitespace-active-style)
	   (memq 'newline                 whitespace-active-style)
	   (memq 'empty                   whitespace-active-style)
	   (memq 'indentation             whitespace-active-style)
	   (memq 'indentation::tab        whitespace-active-style)
	   (memq 'indentation::space      whitespace-active-style)
	   (memq 'big-indent              whitespace-active-style)
	   (memq 'space-after-tab         whitespace-active-style)
	   (memq 'space-after-tab::tab    whitespace-active-style)
	   (memq 'space-after-tab::space  whitespace-active-style)
	   (memq 'space-before-tab        whitespace-active-style)
	   (memq 'space-before-tab::tab   whitespace-active-style)
	   (memq 'space-before-tab::space whitespace-active-style))
       t))


(defun whitespace-color-on ()
  "Turn on color visualization."
  (when (whitespace-style-face-p)
    ;; save current point and refontify when necessary
    (setq-local whitespace-point (point))
    (setq whitespace-point--used
          (let ((ol (make-overlay (point) (point) nil nil t)))
            (delete-overlay ol) ol))
    (setq-local whitespace-font-lock-refontify 0)
    (setq-local whitespace-bob-marker (point-min-marker))
    (setq-local whitespace-eob-marker (point-max-marker))
    (setq-local whitespace-buffer-changed nil)
    (add-hook 'post-command-hook #'whitespace-post-command-hook nil t)
    (add-hook 'before-change-functions #'whitespace-buffer-changed nil t)
    ;; Add whitespace-mode color into font lock.
    (setq
     whitespace-font-lock-keywords
     `(
       (whitespace-point--flush-used)
       ,@(when (memq 'spaces whitespace-active-style)
           ;; Show SPACEs.
           `((,whitespace-space-regexp 1 whitespace-space t)
             ;; Show HARD SPACEs.
             (,whitespace-hspace-regexp 1 whitespace-hspace t)))
       ,@(when (memq 'tabs whitespace-active-style)
           ;; Show TABs.
           `((,whitespace-tab-regexp 1 whitespace-tab t)))
       ,@(when (memq 'trailing whitespace-active-style)
           ;; Show trailing blanks.
           `((,#'whitespace-trailing-regexp 1 whitespace-trailing t)))
       ,@(when (or (memq 'lines      whitespace-active-style)
                   (memq 'lines-tail whitespace-active-style))
           ;; Show "long" lines.
           `((,#'whitespace-lines-regexp
              ,(if (memq 'lines whitespace-active-style)
                   0                    ; whole line
                 2)                     ; line tail
              whitespace-line prepend)))
       ,@(when (or (memq 'space-before-tab whitespace-active-style)
                   (memq 'space-before-tab::tab whitespace-active-style)
                   (memq 'space-before-tab::space whitespace-active-style))
           `((,whitespace-space-before-tab-regexp
              ,(cond
                ((memq 'space-before-tab whitespace-active-style)
                 ;; Show SPACEs before TAB (indent-tabs-mode).
                 (if indent-tabs-mode 1 2))
                ((memq 'space-before-tab::tab whitespace-active-style)
                 1)
                ((memq 'space-before-tab::space whitespace-active-style)
                 2))
              whitespace-space-before-tab t)))
       ,@(when (or (memq 'indentation whitespace-active-style)
                   (memq 'indentation::tab whitespace-active-style)
                   (memq 'indentation::space whitespace-active-style))
           `((,(cond
                ((memq 'indentation whitespace-active-style)
                 ;; Show indentation SPACEs (indent-tabs-mode).
                 (whitespace-indentation-regexp))
                ((memq 'indentation::tab whitespace-active-style)
                 ;; Show indentation SPACEs (SPACEs).
                 (whitespace-indentation-regexp 'tab))
                ((memq 'indentation::space whitespace-active-style)
                 ;; Show indentation SPACEs (TABs).
                 (whitespace-indentation-regexp 'space)))
              1 whitespace-indentation t)))
       ,@(when (memq 'big-indent whitespace-active-style)
           ;; Show big indentation.
           `((,whitespace-big-indent-regexp 1 'whitespace-big-indent t)))
       ,@(when (memq 'empty whitespace-active-style)
           ;; Show empty lines at beginning of buffer.
           `((,#'whitespace-empty-at-bob-regexp
              1 whitespace-empty t)
             ;; Show empty lines at end of buffer.
             (,#'whitespace-empty-at-eob-regexp
              1 whitespace-empty t)))
       ,@(when (or (memq 'space-after-tab whitespace-active-style)
                   (memq 'space-after-tab::tab whitespace-active-style)
                   (memq 'space-after-tab::space whitespace-active-style))
           `((,(cond
                ((memq 'space-after-tab whitespace-active-style)
                 ;; Show SPACEs after TAB (indent-tabs-mode).
                 (whitespace-space-after-tab-regexp))
                ((memq 'space-after-tab::tab whitespace-active-style)
                 ;; Show SPACEs after TAB (SPACEs).
                 (whitespace-space-after-tab-regexp 'tab))
                ((memq 'space-after-tab::space whitespace-active-style)
                 ;; Show SPACEs after TAB (TABs).
                 (whitespace-space-after-tab-regexp 'space)))
              1 whitespace-space-after-tab t)))
       ,@(when (memq 'missing-newline-at-eof whitespace-active-style)
           ;; Show missing newline.
           `(("[^\n]\\'" 0
              ;; Don't mark the end of the buffer is point is there --
              ;; it probably means that the user is typing something
              ;; at the end of the buffer.
              (and (/= whitespace-point (point-max))
                   'whitespace-missing-newline-at-eof)
              t)))))
    (font-lock-add-keywords nil whitespace-font-lock-keywords t)
    (font-lock-flush)))


(defun whitespace-color-off ()
  "Turn off color visualization."
  ;; turn off font lock
  (kill-local-variable 'whitespace-point--used)
  (when (whitespace-style-face-p)
    (remove-hook 'post-command-hook #'whitespace-post-command-hook t)
    (remove-hook 'before-change-functions #'whitespace-buffer-changed t)
    (font-lock-remove-keywords nil whitespace-font-lock-keywords)
    (font-lock-flush)))

(defun whitespace-point--used (start end)
  (let ((ostart (overlay-start whitespace-point--used)))
    (if ostart
        (move-overlay whitespace-point--used
                      (min start ostart)
                      (max end (overlay-end whitespace-point--used)))
      (move-overlay whitespace-point--used start end))))

(defun whitespace-point--flush-used (limit)
  (let ((ostart (overlay-start whitespace-point--used)))
    ;; Strip parts of whitespace-point--used we're about to refresh.
    (when ostart
      (let ((oend (overlay-end whitespace-point--used)))
        (if (<= (point) ostart)
            (if (<= oend limit)
                (delete-overlay whitespace-point--used)
              (move-overlay whitespace-point--used limit oend)))
        (if (<= oend limit)
            (move-overlay whitespace-point--used ostart (point))))))
  nil)

(defun whitespace-trailing-regexp (limit)
  "Match trailing spaces which do not contain the point at end of line."
  (let ((status t))
    (while (if (re-search-forward whitespace-trailing-regexp limit t)
	       (when (= whitespace-point (match-end 1)) ; Loop if point at eol.
                 (whitespace-point--used (match-beginning 0) (match-end 0))
                 t)
	     (setq status nil)))		  ;; end of buffer
    status))

(defun whitespace-lines-regexp (limit)
  (re-search-forward
   (let ((line-column (or whitespace-line-column fill-column)))
     (format
      "^\\([^\t\n]\\{%s\\}\\|[^\t\n]\\{0,%s\\}\t\\)\\{%d\\}%s\\(.+\\)$"
      tab-width
      (1- tab-width)
      (/ line-column tab-width)
      (let ((rem (% line-column tab-width)))
        (if (zerop rem)
            ""
          (format ".\\{%d\\}" rem)))))
   limit t))

(defun whitespace-empty-at-bob-regexp (limit)
  "Match spaces at beginning of buffer which do not contain the point at \
beginning of buffer."
  (let ((b (point))
	r)
    (cond
     ;; at bob
     ((= b 1)
      (setq r (and (looking-at whitespace-empty-at-bob-regexp)
                   (or (/= whitespace-point 1)
                       (progn (whitespace-point--used (match-beginning 0)
                                                      (match-end 0))
                              nil))))
      (set-marker whitespace-bob-marker (if r (match-end 1) b)))
     ;; inside bob empty region
     ((<= limit whitespace-bob-marker)
      (setq r (looking-at whitespace-empty-at-bob-regexp))
      (if r
	  (when (< (match-end 1) limit)
	    (set-marker whitespace-bob-marker (match-end 1)))
	(set-marker whitespace-bob-marker b)))
     ;; intersection with end of bob empty region
     ((<= b whitespace-bob-marker)
      (setq r (looking-at whitespace-empty-at-bob-regexp))
      (set-marker whitespace-bob-marker (if r (match-end 1) b)))
     ;; it is not inside bob empty region
     (t
      (setq r nil)))
    ;; move to end of matching
    (and r (goto-char (match-end 1)))
    r))


(defsubst whitespace-looking-back (regexp limit)
  (save-excursion
    (when (/= 0 (skip-chars-backward " \t\n" limit))
      (unless (bolp)
	(forward-line 1))
      (looking-at regexp))))


(defun whitespace-empty-at-eob-regexp (limit)
  "Match spaces at end of buffer which do not contain the point at end of \
buffer."
  (let ((b (point))
	(e (1+ (buffer-size)))
	r)
    (cond
     ;; at eob
     ((= limit e)
      (goto-char limit)
      (setq r (whitespace-looking-back whitespace-empty-at-eob-regexp b))
      (when (and r (= whitespace-point e))
        (setq r nil)
        (whitespace-point--used (match-beginning 0) (match-end 0)))
      (if r
	  (set-marker whitespace-eob-marker (match-beginning 1))
	(set-marker whitespace-eob-marker limit)
	(goto-char b)))			; return back to initial position
     ;; inside eob empty region
     ((>= b whitespace-eob-marker)
      (goto-char limit)
      (setq r (whitespace-looking-back whitespace-empty-at-eob-regexp b))
      (if r
	  (when (> (match-beginning 1) b)
	    (set-marker whitespace-eob-marker (match-beginning 1)))
	(set-marker whitespace-eob-marker limit)
	(goto-char b)))			; return back to initial position
     ;; intersection with beginning of eob empty region
     ((>= limit whitespace-eob-marker)
      (goto-char limit)
      (setq r (whitespace-looking-back whitespace-empty-at-eob-regexp b))
      (if r
	  (set-marker whitespace-eob-marker (match-beginning 1))
	(set-marker whitespace-eob-marker limit)
	(goto-char b)))			; return back to initial position
     ;; it is not inside eob empty region
     (t
      (setq r nil)))
    r))


(defun whitespace-buffer-changed (_beg _end)
  "Set `whitespace-buffer-changed' variable to t."
  (setq whitespace-buffer-changed t))


(defun whitespace-post-command-hook ()
  "Save current point into `whitespace-point' variable.
Also refontify when necessary."
  (unless (and (eq whitespace-point (point))
               (not whitespace-buffer-changed))
    (setq whitespace-point (point))	; current point position
    (let ((refontify
           (cond
            ;; It is at end of buffer (eob).
            ((= whitespace-point (1+ (buffer-size)))
             (when (whitespace-looking-back whitespace-empty-at-eob-regexp
                                            nil)
               (match-beginning 0)))
            ;; It is at end of line ...
            ((and (eolp)
                  ;; ... with trailing SPACE or TAB
                  (or (memq (preceding-char) '(?\s ?\t))))
             (line-beginning-position))
            ;; It is at beginning of buffer (bob).
            ((and (= whitespace-point 1)
                  (looking-at whitespace-empty-at-bob-regexp))
             (match-end 0))))
          (ostart (overlay-start whitespace-point--used)))
      (cond
       ((not refontify)
        ;; New point does not affect highlighting: just refresh the
        ;; highlighting of old point, if needed.
        (when ostart
          (font-lock-flush ostart
                           (overlay-end whitespace-point--used))
          (delete-overlay whitespace-point--used)))
       ((not ostart)
        ;; Old point did not affect highlighting, but new one does: refresh the
        ;; highlighting of new point.
        (font-lock-flush (min refontify (point)) (max refontify (point))))
       ((save-excursion
          (goto-char ostart)
          (setq ostart (line-beginning-position))
          (and (<= ostart (max refontify (point)))
               (progn
                 (goto-char (overlay-end whitespace-point--used))
                 (let ((oend (line-beginning-position 2)))
                   (<= (min refontify (point)) oend)))))
        ;; The old point highlighting and the new point highlighting
        ;; cover a contiguous region: do a single refresh.
        (font-lock-flush (min refontify (point) ostart)
                         (max refontify (point)
                              (overlay-end whitespace-point--used)))
        (delete-overlay whitespace-point--used))
       (t
        (font-lock-flush (min refontify (point))
                         (max refontify (point)))
        (font-lock-flush ostart (overlay-end whitespace-point--used))
        (delete-overlay whitespace-point--used))))))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Hacked from visws.el (Miles Bader <miles@gnu.org>)


(defun whitespace-style-mark-p ()
  "Return t if there is some visualization via display table."
  (and (or (memq 'tab-mark     whitespace-active-style)
           (memq 'space-mark   whitespace-active-style)
           (memq 'newline-mark whitespace-active-style))
       t))


(defsubst whitespace-char-valid-p (char)
  ;; This check should be improved!!!
  (or (< char 256)
      (characterp char)))


(defun whitespace-display-vector-p (vec)
  "Return true if every character in vector VEC can be displayed."
  (let ((i (length vec)))
    (when (> i 0)
      (while (and (>= (setq i (1- i)) 0)
		  (whitespace-char-valid-p (aref vec i))))
      (< i 0))))


(defun whitespace-display-char-on ()
  "Turn on character display mapping."
  (when (and whitespace-display-mappings
	     (whitespace-style-mark-p))
    (let (vecs vec)
      ;; Remember whether a buffer has a local display table.
      (unless whitespace-display-table-was-local
	(setq whitespace-display-table-was-local t)
        (unless (or whitespace-mode global-whitespace-mode)
	      (setq whitespace-display-table
	      (copy-sequence buffer-display-table)))
	;; Assure `buffer-display-table' is unique
	;; when two or more windows are visible.
	(setq buffer-display-table
	      (copy-sequence buffer-display-table)))
      (unless buffer-display-table
	(setq buffer-display-table (make-display-table)))
      (dolist (entry whitespace-display-mappings)
	;; check if it is to display this mark
	(when (memq (car entry) whitespace-style)
	  ;; Get a displayable mapping.
	  (setq vecs (cddr entry))
	  (while (and vecs
		      (not (whitespace-display-vector-p (car vecs))))
	    (setq vecs (cdr vecs)))
	  ;; Display a valid mapping.
	  (when vecs
	    (setq vec (copy-sequence (car vecs)))
	    ;; NEWLINE char
	    (when (and (eq (cadr entry) ?\n)
		       (memq 'newline whitespace-active-style))
	      ;; Only insert face bits on NEWLINE char mapping to avoid
	      ;; obstruction of other faces like TABs and (HARD) SPACEs
	      ;; faces, font-lock faces, etc.
	      (dotimes (i (length vec))
		(or (eq (aref vec i) ?\n)
		    (aset vec i
			  (make-glyph-code (aref vec i)
					   whitespace-newline)))))
	    ;; Display mapping
	    (aset buffer-display-table (cadr entry) vec)))))))


(defun whitespace-display-char-off ()
  "Turn off character display mapping."
  (and whitespace-display-mappings
       (whitespace-style-mark-p)
       whitespace-display-table-was-local
       (setq whitespace-display-table-was-local nil
	     buffer-display-table whitespace-display-table)))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Hook


(defun whitespace-action-when-on ()
  "Action to be taken always when local whitespace is turned on."
  (cond ((memq 'cleanup whitespace-action)
	 (whitespace-cleanup))
	((memq 'report-on-bogus whitespace-action)
	 (whitespace-report nil t))))


(defun whitespace-write-file-hook ()
  "Action to be taken when buffer is written.
It should be added buffer-locally to `write-file-functions'."
  (cond ((memq 'auto-cleanup whitespace-action)
	 (whitespace-cleanup))
	((memq 'abort-on-bogus whitespace-action)
	 (when (whitespace-report nil t)
	   (error "Abort write due to whitespace problems in %s"
		  (buffer-name)))))
  nil)					; continue hook processing


(defun whitespace-warn-read-only (msg)
  "Warn if buffer is read-only."
  (when (memq 'warn-if-read-only whitespace-action)
    (message "Can't %s: %s is read-only" msg (buffer-name))))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


(defun whitespace-unload-function ()
  "Unload the whitespace library."
  (global-whitespace-mode -1)
  ;; be sure all local whitespace mode is turned off
  (save-current-buffer
    (dolist (buf (buffer-list))
      (set-buffer buf)
      (whitespace-mode -1)))
  nil)					; continue standard unloading


(provide 'whitespace)

(make-obsolete-variable 'whitespace-load-hook
                        "use `with-eval-after-load' instead." "28.1")
(run-hooks 'whitespace-load-hook)


;;; whitespace.el ends here