File: fieldformat.py

package info (click to toggle)
treeline 3.1.5-1.1
  • links: PTS
  • area: main
  • in suites: trixie
  • size: 6,508 kB
  • sloc: python: 20,489; javascript: 998; makefile: 54
file content (2555 lines) | stat: -rw-r--r-- 96,725 bytes parent folder | download | duplicates (3)
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
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
#!/usr/bin/env python3

#******************************************************************************
# fieldformat.py, provides a class to handle field format types
#
# TreeLine, an information storage program
# Copyright (C) 2020, Douglas W. Bell
#
# This is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License, either Version 2 or any later
# version.  This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY.  See the included LICENSE file for details.
#******************************************************************************

import re
import sys
import enum
import datetime
import xml.sax.saxutils as saxutils
import gennumber
import genboolean
import numbering
import matheval
import urltools
import globalref

fieldTypes = [N_('Text'), N_('HtmlText'), N_('OneLineText'), N_('SpacedText'),
              N_('Number'), N_('Math'), N_('Numbering'),
              N_('Date'), N_('Time'), N_('DateTime'), N_('Boolean'),
              N_('Choice'), N_('AutoChoice'), N_('Combination'),
              N_('AutoCombination'), N_('ExternalLink'), N_('InternalLink'),
              N_('Picture'), N_('RegularExpression')]
translatedFieldTypes = [_(name) for name in fieldTypes]
_errorStr = '#####'
_dateStampString = _('Now')
_timeStampString = _('Now')
MathResult = enum.Enum('MathResult', 'number date time boolean text')
_mathResultBlank = {MathResult.number: 0, MathResult.date: 0,
                    MathResult.time: 0, MathResult.boolean: False,
                    MathResult.text: ''}
_multipleSpaceRegEx = re.compile(r' {2,}')
_lineBreakRegEx = re.compile(r'<br\s*/?>', re.I)
_stripTagRe = re.compile(r'<.*?>')
linkRegExp = re.compile(r'<a [^>]*href="([^"]+)"[^>]*>(.*?)</a>', re.I | re.S)
linkSeparateNameRegExp = re.compile(r'(.*) \[(.*)\]\s*$')
_imageRegExp = re.compile(r'<img [^>]*src="([^"]+)"[^>]*>', re.I | re.S)


class TextField:
    """Class to handle a rich-text field format type.

    Stores options and format strings for a text field type.
    Provides methods to return formatted data.
    """
    typeName = 'Text'
    defaultFormat = ''
    showRichTextInCell = True
    evalHtmlDefault = False
    fixEvalHtmlSetting = True
    defaultNumLines = 1
    editorClassName = 'RichTextEditor'
    sortTypeStr = '80_text'
    supportsInitDefault = True
    formatHelpMenuList = []
    def __init__(self, name, formatData=None):
        """Initialize a field format type.

        Arguments:
            name -- the field name string
            formatData -- the dict that defines this field's format
        """
        self.name = name
        if not formatData:
            formatData = {}
        self.prefix = formatData.get('prefix', '')
        self.suffix = formatData.get('suffix', '')
        self.initDefault = formatData.get('init', '')
        self.numLines = formatData.get('lines', type(self).defaultNumLines)
        self.sortKeyNum = formatData.get('sortkeynum', 0)
        self.sortKeyForward = formatData.get('sortkeyfwd', True)
        self.evalHtml = self.evalHtmlDefault
        if not self.fixEvalHtmlSetting:
            self.evalHtml = formatData.get('evalhtml', self.evalHtmlDefault)
        self.useFileInfo = False
        self.showInDialog = True
        self.setFormat(formatData.get('format', type(self).defaultFormat))

    def formatData(self):
        """Return a dictionary of this field's format settings.
        """
        formatData = {'fieldname': self.name, 'fieldtype': self.typeName}
        if self.format:
            formatData['format'] = self.format
        if self.prefix:
            formatData['prefix'] = self.prefix
        if self.suffix:
            formatData['suffix'] = self.suffix
        if self.initDefault:
            formatData['init'] = self.initDefault
        if self.numLines != self.defaultNumLines:
            formatData['lines'] = self.numLines
        if self.sortKeyNum > 0:
            formatData['sortkeynum'] = self.sortKeyNum
        if not self.sortKeyForward:
            formatData['sortkeyfwd'] = False
        if (not self.fixEvalHtmlSetting and
            self.evalHtml != self.evalHtmlDefault):
            formatData['evalhtml'] = self.evalHtml
        return formatData

    def setFormat(self, format):
        """Set the format string and initialize as required.

        Derived classes may raise a ValueError if the format is illegal.
        Arguments:
            format -- the new format string
        """
        self.format = format

    def outputText(self, node, oneLine, noHtml, formatHtml, spotRef=None):
        """Return formatted output text for this field in this node.

        Arguments:
            node -- the tree item storing the data
            oneLine -- if True, returns only first line of output (for titles)
            noHtml -- if True, removes all HTML markup (for titles, etc.)
            formatHtml -- if False, escapes HTML from prefix & suffix
            spotRef -- optional, used for ancestor field refs
        """
        if self.useFileInfo and node.spotRefs:
            # get file info node if not already the file info node
            node = node.treeStructureRef().fileInfoNode
        storedText = node.data.get(self.name, '')
        if storedText:
            return self.formatOutput(storedText, oneLine, noHtml, formatHtml)
        return ''

    def formatOutput(self, storedText, oneLine, noHtml, formatHtml):
        """Return formatted output text from stored text for this field.

        Arguments:
            storedText -- the source text to format
            oneLine -- if True, returns only first line of output (for titles)
            noHtml -- if True, removes all HTML markup (for titles, etc.)
            formatHtml -- if False, escapes HTML from prefix & suffix
        """
        prefix = self.prefix
        suffix = self.suffix
        if oneLine:
            storedText = _lineBreakRegEx.split(storedText, 1)[0]
        if noHtml:
            storedText = removeMarkup(storedText)
            if formatHtml:
                prefix = removeMarkup(prefix)
                suffix = removeMarkup(suffix)
        if not formatHtml:
            prefix = saxutils.escape(prefix)
            suffix = saxutils.escape(suffix)
        return '{0}{1}{2}'.format(prefix, storedText, suffix)

    def editorText(self, node):
        """Return text formatted for use in the data editor.

        The function for default text just returns the stored text.
        Overloads may raise a ValueError if the data does not match the format.
        Arguments:
            node -- the tree item storing the data
        """
        storedText = node.data.get(self.name, '')
        return self.formatEditorText(storedText)

    def formatEditorText(self, storedText):
        """Return text formatted for use in the data editor.

        The function for default text just returns the stored text.
        Overloads may raise a ValueError if the data does not match the format.
        Arguments:
            storedText -- the source text to format
        """
        return storedText

    def storedText(self, editorText):
        """Return new text to be stored based on text from the data editor.

        The function for default text field just returns the editor text.
        Overloads may raise a ValueError if the data does not match the format.
        Arguments:
            editorText -- the new text entered into the editor
        """
        return editorText

    def storedTextFromTitle(self, titleText):
        """Return new text to be stored based on title text edits.

        Overloads may raise a ValueError if the data does not match the format.
        Arguments:
            titleText -- the new title text
        """
        return self.storedText(saxutils.escape(titleText))

    def getInitDefault(self):
        """Return the initial stored value for newly created nodes.
        """
        return self.initDefault

    def setInitDefault(self, editorText):
        """Set the default initial value from editor text.

        The function for default text field just returns the stored text.
        Arguments:
            editorText -- the new text entered into the editor
        """
        self.initDefault = self.storedText(editorText)

    def getEditorInitDefault(self):
        """Return initial value in editor format.
        """
        value = ''
        if self.supportsInitDefault:
            try:
                value = self.formatEditorText(self.initDefault)
            except ValueError:
                pass
        return value

    def initDefaultChoices(self):
        """Return a list of choices for setting the init default.
        """
        return []

    def mathValue(self, node, zeroBlanks=True, noMarkup=True):
        """Return a value to be used in math field equations.

        Return None if blank and not zeroBlanks.
        Arguments:
            node -- the tree item storing the data
            zeroBlanks -- accept blank field values if True
            noMarkup -- if true, remove html markup
        """
        storedText = node.data.get(self.name, '')
        if storedText and noMarkup:
            storedText = removeMarkup(storedText)
        return storedText if storedText or zeroBlanks else None

    def compareValue(self, node):
        """Return a value for comparison to other nodes and for sorting.

        Returns lowercase text for text fields or numbers for non-text fields.
        Arguments:
            node -- the tree item storing the data
        """
        storedText = node.data.get(self.name, '')
        return self.adjustedCompareValue(storedText)

    def adjustedCompareValue(self, value):
        """Return value adjusted like the compareValue for use in conditionals.

        Text version removes any markup and goes to lower case.
        Arguments:
            value -- the comparison value to adjust
        """
        value = removeMarkup(value)
        return value.lower()

    def sortKey(self, node):
        """Return a tuple with field type and comparison value for sorting.

        Allows different types to be sorted.
        Arguments:
            node -- the tree item storing the data
        """
        return (self.sortTypeStr, self.compareValue(node))

    def changeType(self, newType):
        """Change this field's type to newType with a default format.

        Arguments:
            newType -- the new type name, excluding "Field"
        """
        self.__class__ = globals()[newType + 'Field']
        self.setFormat(self.defaultFormat)
        if self.fixEvalHtmlSetting:
            self.evalHtml = self.evalHtmlDefault

    def sepName(self):
        """Return the name enclosed with {* *} separators
        """
        if self.useFileInfo:
            return '{{*!{0}*}}'.format(self.name)
        return '{{*{0}*}}'.format(self.name)

    def getFormatHelpMenuList(self):
        """Return the list of descriptions and keys for the format help menu.
        """
        return self.formatHelpMenuList


class HtmlTextField(TextField):
    """Class to handle an HTML text field format type

    Stores options and format strings for an HTML text field type.
    Does not use the rich text editor.
    Provides methods to return formatted data.
    """
    typeName = 'HtmlText'
    showRichTextInCell = False
    evalHtmlDefault = True
    editorClassName = 'HtmlTextEditor'
    def __init__(self, name, formatData=None):
        """Initialize a field format type.

        Arguments:
            name -- the field name string
            formatData -- the dict that defines this field's format
        """
        super().__init__(name, formatData)

    def storedTextFromTitle(self, titleText):
        """Return new text to be stored based on title text edits.

        Overloads may raise a ValueError if the data does not match the format.
        Arguments:
            titleText -- the new title text
        """
        return self.storedText(titleText)


class OneLineTextField(TextField):
    """Class to handle a single-line rich-text field format type.

    Stores options and format strings for a text field type.
    Provides methods to return formatted data.
    """
    typeName = 'OneLineText'
    editorClassName = 'OneLineTextEditor'
    def __init__(self, name, formatData=None):
        """Initialize a field format type.

        Arguments:
            name -- the field name string
            formatData -- the dict that defines this field's format
        """
        super().__init__(name, formatData)

    def formatOutput(self, storedText, oneLine, noHtml, formatHtml):
        """Return formatted output text from stored text for this field.

        Arguments:
            storedText -- the source text to format
            oneLine -- if True, returns only first line of output (for titles)
            noHtml -- if True, removes all HTML markup (for titles, etc.)
            formatHtml -- if False, escapes HTML from prefix & suffix
        """
        text = _lineBreakRegEx.split(storedText, 1)[0]
        return super().formatOutput(text, oneLine, noHtml, formatHtml)

    def formatEditorText(self, storedText):
        """Return text formatted for use in the data editor.

        Raises a ValueError if the data does not match the format.
        Arguments:
            storedText -- the source text to format
        """
        return _lineBreakRegEx.split(storedText, 1)[0]


class SpacedTextField(TextField):
    """Class to handle a preformatted text field format type.

    Stores options and format strings for a spaced text field type.
    Uses <pre> tags to preserve spacing.
    Does not use the rich text editor.
    Provides methods to return formatted data.
    """
    typeName = 'SpacedText'
    showRichTextInCell = False
    editorClassName = 'PlainTextEditor'
    def __init__(self, name, formatData=None):
        """Initialize a field format type.

        Arguments:
            name -- the field name string
            formatData -- the dict that defines this field's format
        """
        super().__init__(name, formatData)

    def formatOutput(self, storedText, oneLine, noHtml, formatHtml):
        """Return formatted output text from stored text for this field.

        Arguments:
            storedText -- the source text to format
            oneLine -- if True, returns only first line of output (for titles)
            noHtml -- if True, removes all HTML markup (for titles, etc.)
            formatHtml -- if False, escapes HTML from prefix & suffix
        """
        if storedText:
            storedText = '<pre>{0}</pre>'.format(storedText)
        return super().formatOutput(storedText, oneLine, noHtml, formatHtml)

    def formatEditorText(self, storedText):
        """Return text formatted for use in the data editor.

        Arguments:
            storedText -- the source text to format
        """
        return saxutils.unescape(storedText)

    def storedText(self, editorText):
        """Return new text to be stored based on text from the data editor.

        Arguments:
            editorText -- the new text entered into the editor
        """
        return saxutils.escape(editorText)

    def storedTextFromTitle(self, titleText):
        """Return new text to be stored based on title text edits.

        Arguments:
            titleText -- the new title text
        """
        return self.storedText(titleText)


class NumberField(HtmlTextField):
    """Class to handle a general number field format type.

    Stores options and format strings for a number field type.
    Provides methods to return formatted data.
    """
    typeName = 'Number'
    defaultFormat = '#.##'
    evalHtmlDefault = False
    editorClassName = 'LineEditor'
    sortTypeStr = '20_num'
    formatHelpMenuList = [(_('Optional Digit\t#'), '#'),
                          (_('Required Digit\t0'), '0'),
                          (_('Digit or Space (external)\t<space>'), ' '),
                          ('', ''),
                          (_('Decimal Point\t.'), '.'),
                          (_('Decimal Comma\t,'), ','),
                          ('', ''),
                          (_('Comma Separator\t\\,'), '\\,'),
                          (_('Dot Separator\t\\.'), '\\.'),
                          (_('Space Separator (internal)\t<space>'), ' '),
                          ('', ''),
                          (_('Optional Sign\t-'), '-'),
                          (_('Required Sign\t+'), '+'),
                          ('', ''),
                          (_('Exponent (capital)\tE'), 'E'),
                          (_('Exponent (small)\te'), 'e')]

    def __init__(self, name, formatData=None):
        """Initialize a field format type.

        Arguments:
            name -- the field name string
            formatData -- the dict that defines this field's format
        """
        super().__init__(name, formatData)

    def formatOutput(self, storedText, oneLine, noHtml, formatHtml):
        """Return formatted output text from stored text for this field.

        Arguments:
            storedText -- the source text to format
            oneLine -- if True, returns only first line of output (for titles)
            noHtml -- if True, removes all HTML markup (for titles, etc.)
            formatHtml -- if False, escapes HTML from prefix & suffix
        """
        try:
            text = gennumber.GenNumber(storedText).numStr(self.format)
        except ValueError:
            text = _errorStr
        return super().formatOutput(text, oneLine, noHtml, formatHtml)

    def formatEditorText(self, storedText):
        """Return text formatted for use in the data editor.

        Raises a ValueError if the data does not match the format.
        Arguments:
            storedText -- the source text to format
        """
        if not storedText:
            return ''
        return gennumber.GenNumber(storedText).numStr(self.format)

    def storedText(self, editorText):
        """Return new text to be stored based on text from the data editor.

        Raises a ValueError if the data does not match the format.
        Arguments:
            editorText -- the new text entered into the editor
        """
        if not editorText:
            return ''
        return repr(gennumber.GenNumber().setFromStr(editorText, self.format))

    def mathValue(self, node, zeroBlanks=True, noMarkup=True):
        """Return a numeric value to be used in math field equations.

        Return None if blank and not zeroBlanks,
        raise a ValueError if it isn't a number.
        Arguments:
            node -- the tree item storing the data
            zeroBlanks -- replace blank field values with zeros if True
            noMarkup -- not applicable to numbers
        """
        storedText = node.data.get(self.name, '')
        if storedText:
            return gennumber.GenNumber(storedText).num
        return 0 if zeroBlanks else None

    def adjustedCompareValue(self, value):
        """Return value adjusted like the compareValue for use in conditionals.

        Number version converts to a numeric value.
        Arguments:
            value -- the comparison value to adjust
        """
        try:
            return gennumber.GenNumber(value).num
        except ValueError:
            return 0


class MathField(HtmlTextField):
    """Class to handle a math calculation field type.

    Stores options and format strings for a math field type.
    Provides methods to return formatted data.
    """
    typeName = 'Math'
    defaultFormat = '#.##'
    evalHtmlDefault = False
    fixEvalHtmlSetting = False
    editorClassName = 'ReadOnlyEditor'
    def __init__(self, name, formatData=None):
        """Initialize a field format type.

        Arguments:
            name -- the field name string
            formatData -- the attributes that define this field's format
        """
        super().__init__(name, formatData)
        self.equation = None
        self.resultType = MathResult[formatData.get('resulttype', 'number')]
        equationText = formatData.get('eqn', '').strip()
        if equationText:
            self.equation = matheval.MathEquation(equationText)
            try:
                self.equation.validate()
            except ValueError:
                self.equation = None

    def formatData(self):
        """Return a dictionary of this field's attributes.

        Add the math equation to the standard XML output.
        """
        formatData = super().formatData()
        if self.equation:
            formatData['eqn'] = self.equation.equationText()
        if self.resultType != MathResult.number:
            formatData['resulttype'] = self.resultType.name
        return formatData

    def setFormat(self, format):
        """Set the format string and initialize as required.

        Arguments:
            format -- the new format string
        """
        if not hasattr(self, 'equation'):
            self.equation = None
            self.resultType = MathResult.number
        super().setFormat(format)

    def formatOutput(self, storedText, oneLine, noHtml, formatHtml):
        """Return formatted output text from stored text for this field.

        Arguments:
            storedText -- the source text to format
            oneLine -- if True, returns only first line of output (for titles)
            noHtml -- if True, removes all HTML markup (for titles, etc.)
            formatHtml -- if False, escapes HTML from prefix & suffix
        """
        text = storedText
        try:
            if self.resultType == MathResult.number:
                text = gennumber.GenNumber(text).numStr(self.format)
            elif self.resultType == MathResult.date:
                date = datetime.datetime.strptime(text,
                                                  DateField.isoFormat).date()
                text = date.strftime(adjOutDateFormat(self.format))
            elif self.resultType == MathResult.time:
                time = datetime.datetime.strptime(text,
                                                  TimeField.isoFormat).time()
                text = time.strftime(adjOutDateFormat(self.format))
            elif self.resultType == MathResult.boolean:
                text =  genboolean.GenBoolean(text).boolStr(self.format)
        except ValueError:
            text = _errorStr
        return super().formatOutput(text, oneLine, noHtml, formatHtml)

    def formatEditorText(self, storedText):
        """Return text formatted for use in the data editor.

        Raises a ValueError if the data does not match the format.
        Arguments:
            storedText -- the source text to format
        """
        if not storedText:
            return ''
        if self.resultType == MathResult.number:
            return gennumber.GenNumber(storedText).numStr(self.format)
        if self.resultType == MathResult.date:
            date = datetime.datetime.strptime(storedText,
                                              DateField.isoFormat).date()
            editorFormat = adjOutDateFormat(globalref.
                                            genOptions['EditDateFormat'])
            return date.strftime(editorFormat)
        if self.resultType == MathResult.time:
            time = datetime.datetime.strptime(storedText,
                                              TimeField.isoFormat).time()
            editorFormat = adjOutDateFormat(globalref.
                                            genOptions['EditTimeFormat'])
            return time.strftime(editorFormat)
        if self.resultType == MathResult.boolean:
            return genboolean.GenBoolean(storedText).boolStr(self.format)
        if storedText == _errorStr:
            raise ValueError
        return storedText

    def equationText(self):
        """Return the current equation text.
        """
        if self.equation:
            return self.equation.equationText()
        return ''

    def equationValue(self, node):
        """Return a text value from the result of the equation.

        Returns the '#####' error string for illegal math operations.
        Arguments:
            node -- the tree item with this equation
        """
        if self.equation:
            zeroValue = _mathResultBlank[self.resultType]
            try:
                num = self.equation.equationValue(node, self.resultType,
                                                  zeroValue, not self.evalHtml)
            except ValueError:
                return _errorStr
            if num == None:
                return ''
            if self.resultType == MathResult.date:
                date = DateField.refDate + datetime.timedelta(days=num)
                return date.strftime(DateField.isoFormat)
            if self.resultType == MathResult.time:
                dateTime = datetime.datetime.combine(DateField.refDate,
                                                     TimeField.refTime)
                dateTime = dateTime + datetime.timedelta(seconds=num)
                time = dateTime.time()
                return time.strftime(TimeField.isoFormat)
            text = str(num)
            if not self.evalHtml:
                text = saxutils.escape(text)
            return text
        return ''

    def resultClass(self):
        """Return the result type's field class.
        """
        return globals()[self.resultType.name.capitalize() + 'Field']

    def changeResultType(self, resultType):
        """Change the result type and reset the output format.

        Arguments:
            resultType -- the new result type
        """
        if resultType != self.resultType:
            self.resultType = resultType
            self.setFormat(self.resultClass().defaultFormat)

    def mathValue(self, node, zeroBlanks=True, noMarkup=True):
        """Return a numeric value to be used in math field equations.

        Return None if blank and not zeroBlanks,
        raise a ValueError if it isn't valid.
        Arguments:
            node -- the tree item storing the data
            zeroBlanks -- replace blank field values with zeros if True
            noMarkup -- if true, remove html markup
        """
        storedText = node.data.get(self.name, '')
        if storedText:
            if self.resultType == MathResult.number:
                return gennumber.GenNumber(storedText).num
            if self.resultType == MathResult.date:
                date = datetime.datetime.strptime(storedText,
                                                  DateField.isoFormat).date()
                return (date - DateField.refDate).days
            if self.resultType == MathResult.time:
                time = datetime.datetime.strptime(storedText,
                                                  TimeField.isoFormat).time()
                return (time - TimeField.refTime).seconds
            if self.resultType == MathResult.boolean:
                return  genboolean.GenBoolean(storedText).value
            if noMarkup:
                storedText = removeMarkup(storedText)
            return storedText
        return _mathResultBlank[self.resultType] if zeroBlanks else None

    def adjustedCompareValue(self, value):
        """Return value adjusted like the compareValue for use in conditionals.

        Number version converts to a numeric value.
        Arguments:
            value -- the comparison value to adjust
        """
        try:
            if self.resultType == MathResult.number:
                return gennumber.GenNumber(value).num
            if self.resultType == MathResult.date:
                date = datetime.datetime.strptime(value,
                                                  DateField.isoFormat).date()
                return date.strftime(DateField.isoFormat)
            if self.resultType == MathResult.time:
                time = datetime.datetime.strptime(value,
                                                  TimeField.isoFormat).time()
                return time.strftime(TimeField.isoFormat)
            if self.resultType == MathResult.boolean:
                return  genboolean.GenBoolean(value).value
            return value.lower()
        except ValueError:
            return 0

    def sortKey(self, node):
        """Return a tuple with field type and comparison value for sorting.

        Allows different types to be sorted.
        Arguments:
            node -- the tree item storing the data
        """
        return (self.resultClass().sortTypeStr, self.compareValue(node))

    def getFormatHelpMenuList(self):
        """Return the list of descriptions and keys for the format help menu.
        """
        return self.resultClass().formatHelpMenuList


class NumberingField(HtmlTextField):
    """Class to handle formats for hierarchical node numbering.

    Stores options and format strings for a node numbering field type.
    Provides methods to return formatted node numbers.
    """
    typeName = 'Numbering'
    defaultFormat = '1..'
    evalHtmlDefault = False
    editorClassName = 'LineEditor'
    sortTypeStr = '10_numbering'
    formatHelpMenuList = [(_('Number\t1'), '1'),
                          (_('Capital Letter\tA'), 'A'),
                          (_('Small Letter\ta'), 'a'),
                          (_('Capital Roman Numeral\tI'), 'I'),
                          (_('Small Roman Numeral\ti'), 'i'),
                          ('', ''),
                          (_('Level Separator\t/'), '/'),
                          (_('Section Separator\t.'), '.'),
                          ('', ''),
                          (_('"/" Character\t//'), '//'),
                          (_('"." Character\t..'), '..'),
                          ('', ''),
                          (_('Outline Example\tI../A../1../a)/i)'),
                           'I../A../1../a)/i)'),
                          (_('Section Example\t1.1.1.1'), '1.1.1.1')]

    def __init__(self, name, formatData=None):
        """Initialize a field format type.

        Arguments:
            name -- the field name string
            formatData -- the attributes that define this field's format
        """
        self.numFormat = None
        super().__init__(name, formatData)

    def setFormat(self, format):
        """Set the format string and initialize as required.

        Arguments:
            format -- the new format string
        """
        self.numFormat = numbering.NumberingGroup(format)
        super().setFormat(format)

    def formatOutput(self, storedText, oneLine, noHtml, formatHtml):
        """Return formatted output text from stored text for this field.

        Arguments:
            storedText -- the source text to format
            oneLine -- if True, returns only first line of output (for titles)
            noHtml -- if True, removes all HTML markup (for titles, etc.)
            formatHtml -- if False, escapes HTML from prefix & suffix
        """
        try:
            text = self.numFormat.numString(storedText)
        except ValueError:
            text = _errorStr
        return super().formatOutput(text, oneLine, noHtml, formatHtml)

    def formatEditorText(self, storedText):
        """Return text formatted for use in the data editor.

        Raises a ValueError if the data does not match the format.
        Arguments:
            storedText -- the source text to format
        """
        if storedText:
            checkData = [int(num) for num in storedText.split('.')]
        return storedText

    def storedText(self, editorText):
        """Return new text to be stored based on text from the data editor.

        Raises a ValueError if the data does not match the format.
        Arguments:
            editorText -- the new text entered into the editor
        """
        if editorText:
            checkData = [int(num) for num in editorText.split('.')]
        return editorText

    def adjustedCompareValue(self, value):
        """Return value adjusted like the compareValue for use in conditionals.

        Number version converts to a numeric value.
        Arguments:
            value -- the comparison value to adjust
        """
        if value:
            try:
                return [int(num) for num in value.split('.')]
            except ValueError:
                pass
        return [0]


class DateField(HtmlTextField):
    """Class to handle a general date field format type.

    Stores options and format strings for a date field type.
    Provides methods to return formatted data.
    """
    typeName = 'Date'
    defaultFormat = '%B %-d, %Y'
    isoFormat = '%Y-%m-%d'
    evalHtmlDefault = False
    fixEvalHtmlSetting = False
    editorClassName = 'DateEditor'
    refDate = datetime.date(1970, 1, 1)
    sortTypeStr = '40_date'
    formatHelpMenuList = [(_('Day (1 or 2 digits)\t%-d'), '%-d'),
                          (_('Day (2 digits)\t%d'), '%d'), ('', ''),
                          (_('Weekday Abbreviation\t%a'), '%a'),
                          (_('Weekday Name\t%A'), '%A'), ('', ''),
                          (_('Month (1 or 2 digits)\t%-m'), '%-m'),
                          (_('Month (2 digits)\t%m'), '%m'),
                          (_('Month Abbreviation\t%b'), '%b'),
                          (_('Month Name\t%B'), '%B'), ('', ''),
                          (_('Year (2 digits)\t%y'), '%y'),
                          (_('Year (4 digits)\t%Y'), '%Y'), ('', ''),
                          (_('Week Number (0 to 53)\t%-U'), '%-U'),
                          (_('Day of year (1 to 366)\t%-j'), '%-j')]
    def __init__(self, name, formatData=None):
        """Initialize a field format type.

        Arguments:
            name -- the field name string
            formatData -- the dict that defines this field's format
        """
        super().__init__(name, formatData)

    def formatOutput(self, storedText, oneLine, noHtml, formatHtml):
        """Return formatted output text from stored text for this field.

        Arguments:
            storedText -- the source text to format
            oneLine -- if True, returns only first line of output (for titles)
            noHtml -- if True, removes all HTML markup (for titles, etc.)
            formatHtml -- if False, escapes HTML from prefix & suffix
        """
        try:
            date = datetime.datetime.strptime(storedText,
                                              DateField.isoFormat).date()
            text = date.strftime(adjOutDateFormat(self.format))
        except ValueError:
            text = _errorStr
        if not self.evalHtml:
            text = saxutils.escape(text)
        return super().formatOutput(text, oneLine, noHtml, formatHtml)

    def formatEditorText(self, storedText):
        """Return text formatted for use in the data editor.

        Raises a ValueError if the data does not match the format.
        Arguments:
            storedText -- the source text to format
        """
        if not storedText:
            return ''
        date = datetime.datetime.strptime(storedText,
                                          DateField.isoFormat).date()
        editorFormat = adjOutDateFormat(globalref.genOptions['EditDateFormat'])
        return date.strftime(editorFormat)

    def storedText(self, editorText):
        """Return new text to be stored based on text from the data editor.

        Two digit years are interpretted as 1950-2049.
        Raises a ValueError if the data does not match the format.
        Arguments:
            editorText -- the new text entered into the editor
        """
        editorText = _multipleSpaceRegEx.sub(' ', editorText.strip())
        if not editorText:
            return ''
        editorFormat = adjInDateFormat(globalref.genOptions['EditDateFormat'])
        try:
            date = datetime.datetime.strptime(editorText, editorFormat).date()
        except ValueError:  # allow use of a 4-digit year to fix invalid dates
            fullYearFormat = editorFormat.replace('%y', '%Y')
            if fullYearFormat != editorFormat:
                date = datetime.datetime.strptime(editorText,
                                                  fullYearFormat).date()
            else:
                raise
        return date.strftime(DateField.isoFormat)

    def getInitDefault(self):
        """Return the initial stored value for newly created nodes.
        """
        if self.initDefault == _dateStampString:
            date = datetime.date.today()
            return date.strftime(DateField.isoFormat)
        return super().getInitDefault()

    def setInitDefault(self, editorText):
        """Set the default initial value from editor text.

        The function for default text field just returns the stored text.
        Arguments:
            editorText -- the new text entered into the editor
        """
        if editorText == _dateStampString:
            self.initDefault = _dateStampString
        else:
            super().setInitDefault(editorText)

    def getEditorInitDefault(self):
        """Return initial value in editor format.
        """
        if self.initDefault == _dateStampString:
            return _dateStampString
        return super().getEditorInitDefault()

    def initDefaultChoices(self):
        """Return a list of choices for setting the init default.
        """
        return [_dateStampString]

    def mathValue(self, node, zeroBlanks=True, noMarkup=True):
        """Return a numeric value to be used in math field equations.

        Return None if blank and not zeroBlanks,
        raise a ValueError if it isn't a valid date.
        Arguments:
            node -- the tree item storing the data
            zeroBlanks -- replace blank field values with zeros if True
        """
        storedText = node.data.get(self.name, '')
        if storedText:
            date = datetime.datetime.strptime(storedText,
                                              DateField.isoFormat).date()
            return (date - DateField.refDate).days
        return 0 if zeroBlanks else None

    def compareValue(self, node):
        """Return a value for comparison to other nodes and for sorting.

        Returns lowercase text for text fields or numbers for non-text fields.
        Date field uses ISO date format (YYY-MM-DD).
        Arguments:
            node -- the tree item storing the data
        """
        return node.data.get(self.name, '')

    def adjustedCompareValue(self, value):
        """Return value adjusted like the compareValue for use in conditionals.

        Date version converts to an ISO date format (YYYY-MM-DD).
        Arguments:
            value -- the comparison value to adjust
        """
        value = _multipleSpaceRegEx.sub(' ', value.strip())
        if not value:
            return ''
        if value == _dateStampString:
            date = datetime.date.today()
            return date.strftime(DateField.isoFormat)
        try:
            return self.storedText(value)
        except ValueError:
            return value


class TimeField(HtmlTextField):
    """Class to handle a general time field format type

    Stores options and format strings for a time field type.
    Provides methods to return formatted data.
    """
    typeName = 'Time'
    defaultFormat = '%-I:%M:%S %p'
    isoFormat = '%H:%M:%S.%f'
    evalHtmlDefault = False
    fixEvalHtmlSetting = False
    editorClassName = 'TimeEditor'
    numChoiceColumns = 2
    autoAddChoices = False
    refTime = datetime.time()
    sortTypeStr = '50_time'
    formatHelpMenuList = [(_('Hour (0-23, 1 or 2 digits)\t%-H'), '%-H'),
                          (_('Hour (00-23, 2 digits)\t%H'), '%H'),
                          (_('Hour (1-12, 1 or 2 digits)\t%-I'), '%-I'),
                          (_('Hour (01-12, 2 digits)\t%I'), '%I'), ('', ''),
                          (_('Minute (1 or 2 digits)\t%-M'), '%-M'),
                          (_('Minute (2 digits)\t%M'), '%M'), ('', ''),
                          (_('Second (1 or 2 digits)\t%-S'), '%-S'),
                          (_('Second (2 digits)\t%S'), '%S'), ('', ''),
                          (_('Microseconds (6 digits)\t%f'), '%f'), ('', ''),
                          (_('AM/PM\t%p'), '%p')]
    def __init__(self, name, formatData=None):
        """Initialize a field format type.

        Arguments:
            name -- the field name string
            formatData -- the attributes that define this field's format
        """
        super().__init__(name, formatData)

    def formatOutput(self, storedText, oneLine, noHtml, formatHtml):
        """Return formatted output text from stored text for this field.

        Arguments:
            storedText -- the source text to format
            oneLine -- if True, returns only first line of output (for titles)
            noHtml -- if True, removes all HTML markup (for titles, etc.)
            formatHtml -- if False, escapes HTML from prefix & suffix
        """
        try:
            time = datetime.datetime.strptime(storedText,
                                              TimeField.isoFormat).time()
            outFormat = adjOutDateFormat(self.format)
            outFormat = adjTimeAmPm(outFormat, time)
            text = time.strftime(outFormat)
        except ValueError:
            text = _errorStr
        if not self.evalHtml:
            text = saxutils.escape(text)
        return super().formatOutput(text, oneLine, noHtml, formatHtml)

    def formatEditorText(self, storedText):
        """Return text formatted for use in the data editor.

        Raises a ValueError if the data does not match the format.
        Arguments:
            storedText -- the source text to format
        """
        if not storedText:
            return ''
        time = datetime.datetime.strptime(storedText,
                                          TimeField.isoFormat).time()
        editorFormat = adjOutDateFormat(globalref.genOptions['EditTimeFormat'])
        editorFormat = adjTimeAmPm(editorFormat, time)
        return time.strftime(editorFormat)

    def storedText(self, editorText):
        """Return new text to be stored based on text from the data editor.

        Raises a ValueError if the data does not match the format.
        Arguments:
            editorText -- the new text entered into the editor
        """
        editorText = _multipleSpaceRegEx.sub(' ', editorText.strip())
        if not editorText:
            return ''
        editorFormat = adjInDateFormat(globalref.genOptions['EditTimeFormat'])
        time = None
        try:
            time = datetime.datetime.strptime(editorText, editorFormat).time()
        except ValueError:
            noSecFormat = editorFormat.replace(':%S', '')
            noSecFormat = _multipleSpaceRegEx.sub(' ', noSecFormat.strip())
            try:
                time = datetime.datetime.strptime(editorText,
                                                  noSecFormat).time()
            except ValueError:
                for altFormat in (editorFormat, noSecFormat):
                    noAmFormat = altFormat.replace('%p', '')
                    noAmFormat = _multipleSpaceRegEx.sub(' ',
                                                         noAmFormat.strip())
                    try:
                        time = datetime.datetime.strptime(editorText,
                                                          noAmFormat).time()
                        break
                    except ValueError:
                        pass
                if not time:
                    raise ValueError
        return time.strftime(TimeField.isoFormat)

    def annotatedComboChoices(self, editorText):
        """Return a list of (choice, annotation) tuples for the combo box.

        Arguments:
            editorText -- the text entered into the editor
        """
        editorFormat = adjOutDateFormat(globalref.genOptions['EditTimeFormat'])
        choices = [(datetime.datetime.now().time().strftime(editorFormat),
                    '({0})'.format(_timeStampString))]
        for hour in (6, 9, 12, 15, 18, 21, 0):
            choices.append((datetime.time(hour).strftime(editorFormat), ''))
        return choices

    def getInitDefault(self):
        """Return the initial stored value for newly created nodes.
        """
        if self.initDefault == _timeStampString:
            time = datetime.datetime.now().time()
            return time.strftime(TimeField.isoFormat)
        return super().getInitDefault()

    def setInitDefault(self, editorText):
        """Set the default initial value from editor text.

        The function for default text field just returns the stored text.
        Arguments:
            editorText -- the new text entered into the editor
        """
        if editorText == _timeStampString:
            self.initDefault = _timeStampString
        else:
            super().setInitDefault(editorText)

    def getEditorInitDefault(self):
        """Return initial value in editor format.
        """
        if self.initDefault == _timeStampString:
            return _timeStampString
        return super().getEditorInitDefault()

    def initDefaultChoices(self):
        """Return a list of choices for setting the init default.
        """
        return [_timeStampString]

    def mathValue(self, node, zeroBlanks=True, noMarkup=True):
        """Return a numeric value to be used in math field equations.

        Return None if blank and not zeroBlanks,
        raise a ValueError if it isn't a valid time.
        Arguments:
            node -- the tree item storing the data
            zeroBlanks -- replace blank field values with zeros if True
        """
        storedText = node.data.get(self.name, '')
        if storedText:
            time = datetime.datetime.strptime(storedText,
                                              TimeField.isoFormat).time()
            dateTime = datetime.datetime.combine(DateField.refDate, time)
            refDateTime = datetime.datetime.combine(DateField.refDate,
                                                    TimeField.refTime)
            return (dateTime - refDateTime).seconds
        return 0 if zeroBlanks else None

    def compareValue(self, node):
        """Return a value for comparison to other nodes and for sorting.

        Returns lowercase text for text fields or numbers for non-text fields.
        Time field uses HH:MM:SS format.
        Arguments:
            node -- the tree item storing the data
        """
        return node.data.get(self.name, '')

    def adjustedCompareValue(self, value):
        """Return value adjusted like the compareValue for use in conditionals.

        Time version converts to HH:MM:SS format.
        Arguments:
            value -- the comparison value to adjust
        """
        value = _multipleSpaceRegEx.sub(' ', value.strip())
        if not value:
            return ''
        if value == _timeStampString:
            time = datetime.datetime.now().time()
            return time.strftime(TimeField.isoFormat)
        try:
            return self.storedText(value)
        except ValueError:
            return value


class DateTimeField(HtmlTextField):
    """Class to handle a general date and time field format type.

    Stores options and format strings for a date and time field type.
    Provides methods to return formatted data.
    """
    typeName = 'DateTime'
    defaultFormat = '%B %-d, %Y %-I:%M:%S %p'
    isoFormat = '%Y-%m-%d %H:%M:%S.%f'
    evalHtmlDefault = False
    fixEvalHtmlSetting = False
    editorClassName = 'DateTimeEditor'
    refDateTime = datetime.datetime(1970, 1, 1)
    sortTypeStr ='45_datetime'
    formatHelpMenuList = [(_('Day (1 or 2 digits)\t%-d'), '%-d'),
                          (_('Day (2 digits)\t%d'), '%d'), ('', ''),
                          (_('Weekday Abbreviation\t%a'), '%a'),
                          (_('Weekday Name\t%A'), '%A'), ('', ''),
                          (_('Month (1 or 2 digits)\t%-m'), '%-m'),
                          (_('Month (2 digits)\t%m'), '%m'),
                          (_('Month Abbreviation\t%b'), '%b'),
                          (_('Month Name\t%B'), '%B'), ('', ''),
                          (_('Year (2 digits)\t%y'), '%y'),
                          (_('Year (4 digits)\t%Y'), '%Y'), ('', ''),
                          (_('Week Number (0 to 53)\t%-U'), '%-U'),
                          (_('Day of year (1 to 366)\t%-j'), '%-j'),
                          (_('Hour (0-23, 1 or 2 digits)\t%-H'), '%-H'),
                          (_('Hour (00-23, 2 digits)\t%H'), '%H'),
                          (_('Hour (1-12, 1 or 2 digits)\t%-I'), '%-I'),
                          (_('Hour (01-12, 2 digits)\t%I'), '%I'), ('', ''),
                          (_('Minute (1 or 2 digits)\t%-M'), '%-M'),
                          (_('Minute (2 digits)\t%M'), '%M'), ('', ''),
                          (_('Second (1 or 2 digits)\t%-S'), '%-S'),
                          (_('Second (2 digits)\t%S'), '%S'), ('', ''),
                          (_('Microseconds (6 digits)\t%f'), '%f'), ('', ''),
                          (_('AM/PM\t%p'), '%p')]
    def __init__(self, name, formatData=None):
        """Initialize a field format type.

        Arguments:
            name -- the field name string
            formatData -- the dict that defines this field's format
        """
        super().__init__(name, formatData)

    def formatOutput(self, storedText, oneLine, noHtml, formatHtml):
        """Return formatted output text from stored text for this field.

        Arguments:
            storedText -- the source text to format
            oneLine -- if True, returns only first line of output (for titles)
            noHtml -- if True, removes all HTML markup (for titles, etc.)
            formatHtml -- if False, escapes HTML from prefix & suffix
        """
        try:
            dateTime = datetime.datetime.strptime(storedText,
                                                  DateTimeField.isoFormat)
            outFormat = adjOutDateFormat(self.format)
            outFormat = adjTimeAmPm(outFormat, dateTime)
            text = dateTime.strftime(outFormat)
        except ValueError:
            text = _errorStr
        if not self.evalHtml:
            text = saxutils.escape(text)
        return super().formatOutput(text, oneLine, noHtml, formatHtml)

    def formatEditorText(self, storedText):
        """Return text formatted for use in the data editor.

        Raises a ValueError if the data does not match the format.
        Arguments:
            storedText -- the source text to format
        """
        if not storedText:
            return ''
        dateTime = datetime.datetime.strptime(storedText,
                                              DateTimeField.isoFormat)
        editorFormat = '{0} {1}'.format(globalref.genOptions['EditDateFormat'],
                                        globalref.genOptions['EditTimeFormat'])
        editorFormat = adjOutDateFormat(editorFormat)
        editorFormat = adjTimeAmPm(editorFormat, dateTime)
        return dateTime.strftime(editorFormat)

    def storedText(self, editorText):
        """Return new text to be stored based on text from the data editor.

        Two digit years are interpretted as 1950-2049.
        Raises a ValueError if the data does not match the format.
        Arguments:
            editorText -- the new text entered into the editor
        """
        editorText = _multipleSpaceRegEx.sub(' ', editorText.strip())
        if not editorText:
            return ''
        editorFormat = '{0} {1}'.format(globalref.genOptions['EditDateFormat'],
                                        globalref.genOptions['EditTimeFormat'])
        editorFormat = adjInDateFormat(editorFormat)
        dateTime = None
        try:
            dateTime = datetime.datetime.strptime(editorText, editorFormat)
        except ValueError:
            noSecFormat = editorFormat.replace(':%S', '')
            noSecFormat = _multipleSpaceRegEx.sub(' ', noSecFormat.strip())
            altFormats = [editorFormat, noSecFormat]
            for altFormat in altFormats[:]:
                noAmFormat = altFormat.replace('%p', '')
                noAmFormat = _multipleSpaceRegEx.sub(' ', noAmFormat.strip())
                altFormats.append(noAmFormat)
            for altFormat in altFormats[:]:
                fullYearFormat = altFormat.replace('%y', '%Y')
                altFormats.append(fullYearFormat)
            for editorFormat in altFormats[1:]:
                try:
                    dateTime = datetime.datetime.strptime(editorText,
                                                          editorFormat)
                    break
                except ValueError:
                    pass
            if not dateTime:
                raise ValueError
        return dateTime.strftime(DateTimeField.isoFormat)

    def getInitDefault(self):
        """Return the initial stored value for newly created nodes.
        """
        if self.initDefault == _timeStampString:
            dateTime = datetime.datetime.now()
            return dateTime.strftime(DateTimeField.isoFormat)
        return super().getInitDefault()

    def setInitDefault(self, editorText):
        """Set the default initial value from editor text.

        The function for default text field just returns the stored text.
        Arguments:
            editorText -- the new text entered into the editor
        """
        if editorText == _timeStampString:
            self.initDefault = _timeStampString
        else:
            super().setInitDefault(editorText)

    def getEditorInitDefault(self):
        """Return initial value in editor format.
        """
        if self.initDefault == _timeStampString:
            return _timeStampString
        return super().getEditorInitDefault()

    def initDefaultChoices(self):
        """Return a list of choices for setting the init default.
        """
        return [_timeStampString]

    def mathValue(self, node, zeroBlanks=True, noMarkup=True):
        """Return a numeric value to be used in math field equations.

        Return None if blank and not zeroBlanks,
        raise a ValueError if it isn't a valid time.
        Arguments:
            node -- the tree item storing the data
            zeroBlanks -- replace blank field values with zeros if True
        """
        storedText = node.data.get(self.name, '')
        if storedText:
            dateTime = datetime.datetime.strptime(storedText,
                                                  DateTimeField.isoFormat)
            return (dateTime - DateTimeField.refDateTime).total_seconds()
        return 0 if zeroBlanks else None

    def compareValue(self, node):
        """Return a value for comparison to other nodes and for sorting.

        Returns lowercase text for text fields or numbers for non-text fields.
        DateTime field uses YYYY-MM-DD HH:MM:SS format.
        Arguments:
            node -- the tree item storing the data
        """
        return node.data.get(self.name, '')

    def adjustedCompareValue(self, value):
        """Return value adjusted like the compareValue for use in conditionals.

        Time version converts to HH:MM:SS format.
        Arguments:
            value -- the comparison value to adjust
        """
        value = _multipleSpaceRegEx.sub(' ', value.strip())
        if not value:
            return ''
        if value == _timeStampString:
            dateTime = datetime.datetime.now()
            return dateTime.strftime(DateTimeField.isoFormat)
        try:
            return self.storedText(value)
        except ValueError:
            return value


class ChoiceField(HtmlTextField):
    """Class to handle a field with pre-defined, individual text choices.

    Stores options and format strings for a choice field type.
    Provides methods to return formatted data.
    """
    typeName = 'Choice'
    editSep = '/'
    defaultFormat = '1/2/3/4'
    evalHtmlDefault = False
    fixEvalHtmlSetting = False
    editorClassName = 'ComboEditor'
    numChoiceColumns = 1
    autoAddChoices = False
    formatHelpMenuList = [(_('Separator\t/'), '/'), ('', ''),
                          (_('"/" Character\t//'), '//'), ('', ''),
                          (_('Example\t1/2/3/4'), '1/2/3/4')]
    def __init__(self, name, formatData=None):
        """Initialize a field format type.

        Arguments:
            name -- the field name string
            formatData -- the dict that defines this field's format
        """
        super().__init__(name, formatData)

    def setFormat(self, format):
        """Set the format string and initialize as required.

        Arguments:
            format -- the new format string
        """
        super().setFormat(format)
        self.choiceList = self.splitText(self.format)
        if self.evalHtml:
            self.choices = set(self.choiceList)
        else:
            self.choices = set([saxutils.escape(choice) for choice in
                                self.choiceList])

    def formatOutput(self, storedText, oneLine, noHtml, formatHtml):
        """Return formatted output text from stored text for this field.

        Arguments:
            storedText -- the source text to format
            oneLine -- if True, returns only first line of output (for titles)
            noHtml -- if True, removes all HTML markup (for titles, etc.)
            formatHtml -- if False, escapes HTML from prefix & suffix
        """
        if storedText not in self.choices:
            storedText = _errorStr
        return super().formatOutput(storedText, oneLine, noHtml, formatHtml)

    def formatEditorText(self, storedText):
        """Return text formatted for use in the data editor.

        Raises a ValueError if the data does not match the format.
        Arguments:
            storedText -- the source text to format
        """
        if storedText and storedText not in self.choices:
            raise ValueError
        if self.evalHtml:
            return storedText
        return saxutils.unescape(storedText)

    def storedText(self, editorText):
        """Return new text to be stored based on text from the data editor.

        Raises a ValueError if the data does not match the format.
        Arguments:
            editorText -- the new text entered into the editor
        """
        if not self.evalHtml:
            editorText = saxutils.escape(editorText)
        if not editorText or editorText in self.choices:
            return editorText
        raise ValueError

    def comboChoices(self):
        """Return a list of choices for the combo box.
        """
        return self.choiceList

    def initDefaultChoices(self):
        """Return a list of choices for setting the init default.
        """
        return self.choiceList

    def splitText(self, textStr):
        """Split textStr using editSep, return a list of strings.

        Double editSep's are not split (become single).
        Removes duplicates and empty strings.
        Arguments:
            textStr -- the text to split
        """
        result = []
        textStr = textStr.replace(self.editSep * 2, '\0')
        for text in textStr.split(self.editSep):
            text = text.strip().replace('\0', self.editSep)
            if text and text not in result:
                result.append(text)
        return result


class AutoChoiceField(HtmlTextField):
    """Class to handle a field with automatically populated text choices.

    Stores options and possible entries for an auto-choice field type.
    Provides methods to return formatted data.
    """
    typeName = 'AutoChoice'
    evalHtmlDefault = False
    fixEvalHtmlSetting = False
    editorClassName = 'ComboEditor'
    numChoiceColumns = 1
    autoAddChoices = True
    def __init__(self, name, formatData=None):
        """Initialize a field format type.

        Arguments:
            name -- the field name string
            formatData -- the attributes that define this field's format
        """
        super().__init__(name, formatData)
        self.choices = set()

    def formatEditorText(self, storedText):
        """Return text formatted for use in the data editor.

        Arguments:
            storedText -- the source text to format
        """
        if self.evalHtml:
            return storedText
        return saxutils.unescape(storedText)

    def storedText(self, editorText):
        """Return new text to be stored based on text from the data editor.

        Arguments:
            editorText -- the new text entered into the editor
        """
        if self.evalHtml:
            return editorText
        return saxutils.escape(editorText)

    def comboChoices(self):
        """Return a list of choices for the combo box.
        """
        if self.evalHtml:
            choices = self.choices
        else:
            choices = [saxutils.unescape(text) for text in
                       self.choices]
        return sorted(choices, key=str.lower)

    def addChoice(self, text):
        """Add a new choice.

        Arguments:
            text -- the choice to be added
        """
        if text:
            self.choices.add(text)

    def clearChoices(self):
        """Remove all current choices.
        """
        self.choices = set()


class CombinationField(ChoiceField):
    """Class to handle a field with multiple pre-defined text choices.

    Stores options and format strings for a combination field type.
    Provides methods to return formatted data.
    """
    typeName = 'Combination'
    editorClassName = 'CombinationEditor'
    numChoiceColumns = 2
    def __init__(self, name, formatData=None):
        """Initialize a field format type.

        Arguments:
            name -- the field name string
            formatData -- the dict that defines this field's format
        """
        super().__init__(name, formatData)

    def setFormat(self, format):
        """Set the format string and initialize as required.

        Arguments:
            format -- the new format string
        """
        TextField.setFormat(self, format)
        if not self.evalHtml:
            format = saxutils.escape(format)
        self.choiceList = self.splitText(format)
        self.choices = set(self.choiceList)
        self.outputSep = ''

    def outputText(self, node, oneLine, noHtml, formatHtml, spotRef=None):
        """Return formatted output text for this field in this node.

        Sets output separator prior to calling base class methods.
        Arguments:
            node -- the tree item storing the data
            oneLine -- if True, returns only first line of output (for titles)
            noHtml -- if True, removes all HTML markup (for titles, etc.)
            formatHtml -- if False, escapes HTML from prefix & suffix
            spotRef -- optional, used for ancestor field refs
        """
        self.outputSep = node.formatRef.outputSeparator
        return super().outputText(node, oneLine, noHtml, formatHtml, spotRef)

    def formatOutput(self, storedText, oneLine, noHtml, formatHtml):
        """Return formatted output text from stored text for this field.

        Arguments:
            storedText -- the source text to format
            oneLine -- if True, returns only first line of output (for titles)
            noHtml -- if True, removes all HTML markup (for titles, etc.)
            formatHtml -- if False, escapes HTML from prefix & suffix
        """
        selections, valid = self.sortedSelections(storedText)
        if valid:
            result = self.outputSep.join(selections)
        else:
            result = _errorStr
        return TextField.formatOutput(self, result, oneLine, noHtml,
                                      formatHtml)

    def formatEditorText(self, storedText):
        """Return text formatted for use in the data editor.

        Raises a ValueError if the data does not match the format.
        Arguments:
            storedText -- the source text to format
        """
        selections = set(self.splitText(storedText))
        if selections.issubset(self.choices):
            if self.evalHtml:
                return storedText
            return saxutils.unescape(storedText)
        raise ValueError

    def storedText(self, editorText):
        """Return new text to be stored based on text from the data editor.

        Raises a ValueError if the data does not match the format.
        Arguments:
            editorText -- the new text entered into the editor
        """
        if not self.evalHtml:
            editorText = saxutils.escape(editorText)
        selections, valid = self.sortedSelections(editorText)
        if not valid:
            raise ValueError
        return self.joinText(selections)

    def comboChoices(self):
        """Return a list of choices for the combo box.
        """
        if self.evalHtml:
            return self.choiceList
        return [saxutils.unescape(text) for text in self.choiceList]

    def comboActiveChoices(self, editorText):
        """Return a sorted list of choices currently in editorText.

        Arguments:
            editorText -- the text entered into the editor
        """
        selections, valid = self.sortedSelections(saxutils.escape(editorText))
        if self.evalHtml:
            return selections
        return [saxutils.unescape(text) for text in selections]

    def initDefaultChoices(self):
        """Return a list of choices for setting the init default.
        """
        return []

    def sortedSelections(self, inText):
        """Split inText using editSep and sort like format string.

        Return a tuple of resulting selection list and bool validity.
        Valid if all choices are in the format string.
        Arguments:
            inText -- the text to split and sequence
        """
        selections = set(self.splitText(inText))
        result = [text for text in self.choiceList if text in selections]
        return (result, len(selections) == len(result))

    def joinText(self, textList):
        """Join the text list using editSep, return the string.

        Any editSep in text items become double.
        Arguments:
            textList -- the list of text items to join
        """
        return self.editSep.join([text.replace(self.editSep, self.editSep * 2)
                                  for text in textList])


class AutoCombinationField(CombinationField):
    """Class for a field with multiple automatically populated text choices.

    Stores options and possible entries for an auto-choice field type.
    Provides methods to return formatted data.
    """
    typeName = 'AutoCombination'
    autoAddChoices = True
    defaultFormat = ''
    formatHelpMenuList = []
    def __init__(self, name, formatData=None):
        """Initialize a field format type.

        Arguments:
            name -- the field name string
            formatData -- the attributes that define this field's format
        """
        super().__init__(name, formatData)
        self.choices = set()
        self.outputSep = ''

    def outputText(self, node, oneLine, noHtml, formatHtml, spotRef=None):
        """Return formatted output text for this field in this node.

        Sets output separator prior to calling base class methods.
        Arguments:
            node -- the tree item storing the data
            oneLine -- if True, returns only first line of output (for titles)
            noHtml -- if True, removes all HTML markup (for titles, etc.)
            formatHtml -- if False, escapes HTML from prefix & suffix
            spotRef -- optional, used for ancestor field refs
        """
        self.outputSep = node.formatRef.outputSeparator
        return super().outputText(node, oneLine, noHtml, formatHtml, spotRef)

    def formatOutput(self, storedText, oneLine, noHtml, formatHtml):
        """Return formatted output text from stored text for this field.

        Arguments:
            storedText -- the source text to format
            oneLine -- if True, returns only first line of output (for titles)
            noHtml -- if True, removes all HTML markup (for titles, etc.)
            formatHtml -- if False, escapes HTML from prefix & suffix
        """
        result = self.outputSep.join(self.splitText(storedText))
        return TextField.formatOutput(self, result, oneLine, noHtml,
                                      formatHtml)

    def formatEditorText(self, storedText):
        """Return text formatted for use in the data editor.

        Arguments:
            storedText -- the source text to format
        """
        if self.evalHtml:
            return storedText
        return saxutils.unescape(storedText)

    def storedText(self, editorText):
        """Return new text to be stored based on text from the data editor.

        Also resets outputSep, to be defined at the next output.
        Arguments:
            editorText -- the new text entered into the editor
        """
        self.outputSep = ''
        if not self.evalHtml:
            editorText = saxutils.escape(editorText)
        selections = sorted(self.splitText(editorText), key=str.lower)
        return self.joinText(selections)

    def comboChoices(self):
        """Return a list of choices for the combo box.
        """
        if self.evalHtml:
            choices = self.choices
        else:
            choices = [saxutils.unescape(text) for text in
                       self.choices]
        return sorted(choices, key=str.lower)

    def comboActiveChoices(self, editorText):
        """Return a sorted list of choices currently in editorText.

        Arguments:
            editorText -- the text entered into the editor
        """
        selections, valid = self.sortedSelections(saxutils.escape(editorText))
        if self.evalHtml:
            return selections
        return [saxutils.unescape(text) for text in selections]

    def sortedSelections(self, inText):
        """Split inText using editSep and sort like format string.

        Return a tuple of resulting selection list and bool validity.
        This version always returns valid.
        Arguments:
            inText -- the text to split and sequence
        """
        selections = sorted(self.splitText(inText), key=str.lower)
        return (selections, True)

    def addChoice(self, text):
        """Add a new choice.

        Arguments:
            text -- the stored text combinations to be added
        """
        for choice in self.splitText(text):
            self.choices.add(choice)

    def clearChoices(self):
        """Remove all current choices.
        """
        self.choices = set()


class BooleanField(ChoiceField):
    """Class to handle a general boolean field format type.

    Stores options and format strings for a boolean field type.
    Provides methods to return formatted data.
    """
    typeName = 'Boolean'
    defaultFormat = _('yes/no')
    evalHtmlDefault = False
    fixEvalHtmlSetting = False
    sortTypeStr ='30_bool'
    formatHelpMenuList = [(_('true/false'), 'true/false'),
                          (_('T/F'), 'T/F'), ('', ''),
                          (_('yes/no'), 'yes/no'),
                          (_('Y/N'), 'Y/N'), ('', ''),
                          ('1/0', '1/0')]
    def __init__(self, name, formatData=None):
        """Initialize a field format type.

        Arguments:
            name -- the field name string
            formatData -- the dict that defines this field's format
        """
        super().__init__(name, formatData)

    def setFormat(self, format):
        """Set the format string and initialize as required.

        Arguments:
            format -- the new format string
        """
        HtmlTextField.setFormat(self, format)
        self.strippedFormat = removeMarkup(self.format)

    def formatOutput(self, storedText, oneLine, noHtml, formatHtml):
        """Return formatted output text from stored text for this field.

        Arguments:
            storedText -- the source text to format
            oneLine -- if True, returns only first line of output (for titles)
            noHtml -- if True, removes all HTML markup (for titles, etc.)
            formatHtml -- if False, escapes HTML from prefix & suffix
        """
        try:
            text =  genboolean.GenBoolean(storedText).boolStr(self.format)
        except ValueError:
            text = _errorStr
        if not self.evalHtml:
            text = saxutils.escape(text)
        return HtmlTextField.formatOutput(self, text, oneLine, noHtml,
                                          formatHtml)

    def formatEditorText(self, storedText):
        """Return text formatted for use in the data editor.

        Raises a ValueError if the data does not match the format.
        Arguments:
            storedText -- the source text to format
        """
        if not storedText:
            return ''
        boolFormat = self.strippedFormat if self.evalHtml else self.format
        return genboolean.GenBoolean(storedText).boolStr(boolFormat)

    def storedText(self, editorText):
        """Return new text to be stored based on text from the data editor.

        Raises a ValueError if the data does not match the format.
        Arguments:
            editorText -- the new text entered into the editor
        """
        if not editorText:
            return ''
        boolFormat = self.strippedFormat if self.evalHtml else self.format
        try:
            return repr(genboolean.GenBoolean().setFromStr(editorText,
                                                           boolFormat))
        except ValueError:
            return repr(genboolean.GenBoolean(editorText))

    def comboChoices(self):
        """Return a list of choices for the combo box.
        """
        if self.evalHtml:
            return self.splitText(self.strippedFormat)
        return self.splitText(self.format)

    def initDefaultChoices(self):
        """Return a list of choices for setting the init default.
        """
        return self.comboChoices()

    def mathValue(self, node, zeroBlanks=True, noMarkup=True):
        """Return a value to be used in math field equations.

        Return None if blank and not zeroBlanks,
        raise a ValueError if it isn't a valid boolean.
        Arguments:
            node -- the tree item storing the data
            zeroBlanks -- replace blank field values with zeros if True
        """
        storedText = node.data.get(self.name, '')
        if storedText:
            return genboolean.GenBoolean(storedText).value
        return False if zeroBlanks else None

    def compareValue(self, node):
        """Return a value for comparison to other nodes and for sorting.

        Returns lowercase text for text fields or numbers for non-text fields.
        Bool fields return True or False values.
        Arguments:
            node -- the tree item storing the data
        """
        storedText = node.data.get(self.name, '')
        try:
            return genboolean.GenBoolean(storedText).value
        except ValueError:
            return False

    def adjustedCompareValue(self, value):
        """Return value adjusted like the compareValue for use in conditionals.

        Bool version converts to a bool value.
        Arguments:
            value -- the comparison value to adjust
        """
        try:
            return genboolean.GenBoolean().setFromStr(value, self.format).value
        except ValueError:
            try:
                return genboolean.GenBoolean(value).value
            except ValueError:
                return False


class ExternalLinkField(HtmlTextField):
    """Class to handle a field containing various types of external HTML links.

    Protocol choices include http, https, file, mailto.
    Stores data as HTML tags, shows in editors as "protocol:address [name]".
    """
    typeName = 'ExternalLink'
    evalHtmlDefault = False
    editorClassName = 'ExtLinkEditor'
    sortTypeStr ='60_link'

    def __init__(self, name, formatData=None):
        """Initialize a field format type.

        Arguments:
            name -- the field name string
            formatData -- the attributes that define this field's format
        """
        super().__init__(name, formatData)

    def addressAndName(self, storedText):
        """Return the link title and the name from the given stored link.

        Raise ValueError if the stored text is not formatted as a link.
        Arguments:
            storedText -- the source text to format
        """
        if not storedText:
            return ('', '')
        linkMatch = linkRegExp.search(storedText)
        if not linkMatch:
            raise ValueError
        address, name = linkMatch.groups()
        return (address, name)

    def formatOutput(self, storedText, oneLine, noHtml, formatHtml):
        """Return formatted output text from stored text for this field.

        Arguments:
            storedText -- the source text to format
            oneLine -- if True, returns only first line of output (for titles)
            noHtml -- if True, removes all HTML markup (for titles, etc.)
            formatHtml -- if False, escapes HTML from prefix & suffix
        """
        if noHtml:
            linkMatch = linkRegExp.search(storedText)
            if linkMatch:
                address, name = linkMatch.groups()
                storedText = name.strip()
                if not storedText:
                    storedText = address.lstrip('#')
        return super().formatOutput(storedText, oneLine, noHtml, formatHtml)

    def formatEditorText(self, storedText):
        """Return text formatted for use in the data editor.

        Raises a ValueError if the data does not match the format.
        Arguments:
            storedText -- the source text to format
        """
        if not storedText:
            return ''
        address, name = self.addressAndName(storedText)
        name = name.strip()
        if not name:
            name = urltools.shortName(address)
        return '{0} [{1}]'.format(address, name)

    def storedText(self, editorText):
        """Return new text to be stored based on text from the data editor.

        Raises a ValueError if the data does not match the format.
        Arguments:
            editorText -- the new text entered into the editor
        """
        if not editorText:
            return ''
        nameMatch = linkSeparateNameRegExp.match(editorText)
        if nameMatch:
            address, name = nameMatch.groups()
        else:
            raise ValueError
        return '<a href="{0}">{1}</a>'.format(address.strip(), name.strip())

    def adjustedCompareValue(self, value):
        """Return value adjusted like the compareValue for use in conditionals.

        Link fields use link address.
        Arguments:
            value -- the comparison value to adjust
        """
        if not value:
            return ''
        try:
            address, name = self.addressAndName(value)
        except ValueError:
            return value.lower()
        return address.lstrip('#').lower()


class InternalLinkField(ExternalLinkField):
    """Class to handle a field containing internal links to nodes.

    Stores data as HTML local link tag, shows in editors as "id [name]".
    """
    typeName = 'InternalLink'
    editorClassName = 'IntLinkEditor'
    supportsInitDefault = False

    def __init__(self, name, formatData=None):
        """Initialize a field format type.

        Arguments:
            name -- the field name string
            formatData -- the attributes that define this field's format
        """
        super().__init__(name, formatData)

    def editorText(self, node):
        """Return text formatted for use in the data editor.

        Raises a ValueError if the data does not match the format.
        Also raises a ValueError if the link is not a valid destination, with
        the editor text as the second argument to the exception.
        Arguments:
            node -- the tree item storing the data
        """
        storedText = node.data.get(self.name, '')
        return self.formatEditorText(storedText, node.treeStructureRef())

    def formatEditorText(self, storedText, treeStructRef):
        """Return text formatted for use in the data editor.

        Raises a ValueError if the data does not match the format.
        Also raises a ValueError if the link is not a valid destination, with
        the editor text as the second argument to the exception.
        Arguments:
            storedText -- the source text to format
            treeStructRef -- ref to the tree structure to get the linked title
        """
        if not storedText:
            return ''
        address, name = self.addressAndName(storedText)
        address = address.lstrip('#')
        targetNode = treeStructRef.nodeDict.get(address, None)
        linkTitle = targetNode.title() if targetNode else _errorStr
        name = name.strip()
        if not name and targetNode:
            name = linkTitle
        result = 'LinkTo: {0} [{1}]'.format(linkTitle, name)
        if linkTitle == _errorStr:
            raise ValueError('invalid address', result)
        return result

    def storedText(self, editorText):
        """Return new text to be stored based on text from the data editor.

        Uses the "address [name]" format as input, not the final editor form.
        Raises a ValueError if the data does not match the format.
        Arguments:
            editorText -- the new editor text in "address [name]" format
        """
        if not editorText:
            return ''
        nameMatch = linkSeparateNameRegExp.match(editorText)
        if not nameMatch:
            raise ValueError
        address, name = nameMatch.groups()
        if not address:
            raise ValueError('invalid address', '')
        if not name:
            name = _errorStr
        result = '<a href="#{0}">{1}</a>'.format(address.strip(), name.strip())
        if name == _errorStr:
            raise ValueError('invalid name', result)
        return result


class PictureField(HtmlTextField):
    """Class to handle a field containing various types of external HTML links.

    Protocol choices include http, https, file, mailto.
    Stores data as HTML tags, shows in editors as "protocol:address [name]".
    """
    typeName = 'Picture'
    evalHtmlDefault = False
    editorClassName = 'PictureLinkEditor'
    sortTypeStr ='60_link'

    def __init__(self, name, formatData=None):
        """Initialize a field format type.

        Arguments:
            name -- the field name string
            formatData -- the attributes that define this field's format
        """
        super().__init__(name, formatData)

    def formatOutput(self, storedText, oneLine, noHtml, formatHtml):
        """Return formatted output text from stored text for this field.

        Arguments:
            storedText -- the source text to format
            oneLine -- if True, returns only first line of output (for titles)
            noHtml -- if True, removes all HTML markup (for titles, etc.)
            formatHtml -- if False, escapes HTML from prefix & suffix
        """
        if noHtml:
            linkMatch = _imageRegExp.search(storedText)
            if linkMatch:
                address = linkMatch.group(1)
                storedText = address.strip()
        return super().formatOutput(storedText, oneLine, noHtml, formatHtml)

    def formatEditorText(self, storedText):
        """Return text formatted for use in the data editor.

        Raises a ValueError if the data does not match the format.
        Arguments:
            storedText -- the source text to format
        """
        if not storedText:
            return ''
        linkMatch = _imageRegExp.search(storedText)
        if not linkMatch:
            raise ValueError
        return linkMatch.group(1)

    def storedText(self, editorText):
        """Return new text to be stored based on text from the data editor.

        Raises a ValueError if the data does not match the format.
        Arguments:
            editorText -- the new text entered into the editor
        """
        editorText = editorText.strip()
        if not editorText:
            return ''
        nameMatch = linkSeparateNameRegExp.match(editorText)
        if nameMatch:
            address, name = nameMatch.groups()
        else:
            address = editorText
            name = urltools.shortName(address)
        return '<img src="{0}" />'.format(editorText)

    def adjustedCompareValue(self, value):
        """Return value adjusted like the compareValue for use in conditionals.

        Link fields use link address.
        Arguments:
            value -- the comparison value to adjust
        """
        if not value:
            return ''
        linkMatch = _imageRegExp.search(value)
        if not linkMatch:
            return value.lower()
        return linkMatch.group(1).lower()


class RegularExpressionField(HtmlTextField):
    """Class to handle a field format type controlled by a regular expression.

    Stores options and format strings for a number field type.
    Provides methods to return formatted data.
    """
    typeName = 'RegularExpression'
    defaultFormat = '.*'
    evalHtmlDefault = False
    fixEvalHtmlSetting = False
    editorClassName = 'LineEditor'
    formatHelpMenuList = [(_('Any Character\t.'), '.'),
                          (_('End of Text\t$'), '$'),
                          ('', ''),
                          (_('0 Or More Repetitions\t*'), '*'),
                          (_('1 Or More Repetitions\t+'), '+'),
                          (_('0 Or 1 Repetitions\t?'), '?'),
                          ('', ''),
                          (_('Set of Numbers\t[0-9]'), '[0-9]'),
                          (_('Lower Case Letters\t[a-z]'), '[a-z]'),
                          (_('Upper Case Letters\t[A-Z]'), '[A-Z]'),
                          (_('Not a Number\t[^0-9]'), '[^0-9]'),
                          ('', ''),
                          (_('Or\t|'), '|'),
                          (_('Escape a Special Character\t\\'), '\\')]

    def __init__(self, name, formatData=None):
        """Initialize a field format type.

        Arguments:
            name -- the field name string
            formatData -- the dict that defines this field's format
        """
        super().__init__(name, formatData)

    def setFormat(self, format):
        """Set the format string and initialize as required.

        Raise a ValueError if the format is illegal.
        Arguments:
            format -- the new format string
        """
        try:
            re.compile(format)
        except re.error:
            raise ValueError
        super().setFormat(format)

    def formatOutput(self, storedText, oneLine, noHtml, formatHtml):
        """Return formatted output text from stored text for this field.

        Arguments:
            storedText -- the source text to format
            oneLine -- if True, returns only first line of output (for titles)
            noHtml -- if True, removes all HTML markup (for titles, etc.)
            formatHtml -- if False, escapes HTML from prefix & suffix
        """
        match = re.fullmatch(self.format, saxutils.unescape(storedText))
        if not storedText or match:
            text = storedText
        else:
            text = _errorStr
        return super().formatOutput(text, oneLine, noHtml, formatHtml)

    def formatEditorText(self, storedText):
        """Return text formatted for use in the data editor.

        Raises a ValueError if the data does not match the format.
        Arguments:
            storedText -- the source text to format
        """
        if not self.evalHtml:
            storedText = saxutils.unescape(storedText)
        match = re.fullmatch(self.format, storedText)
        if not storedText or match:
            return storedText
        raise ValueError

    def storedText(self, editorText):
        """Return new text to be stored based on text from the data editor.

        Raises a ValueError if the data does not match the format.
        Arguments:
            editorText -- the new text entered into the editor
        """
        match = re.fullmatch(self.format, editorText)
        if not editorText or match:
            if self.evalHtml:
                return editorText
            return saxutils.escape(editorText)
        raise ValueError


class AncestorLevelField(TextField):
    """Placeholder format for ref. to ancestor fields at specific levels.
    """
    typeName = 'AncestorLevel'
    def __init__(self, name, ancestorLevel=1):
        """Initialize a field format placeholder type.

        Arguments:
            name -- the field name string
            ancestorLevel -- the number of generations to go back
        """
        super().__init__(name, {})
        self.ancestorLevel = ancestorLevel

    def outputText(self, node, oneLine, noHtml, formatHtml, spotRef=None):
        """Return formatted output text for this field in this node.

        Finds the appropriate ancestor node to get the field text.
        Arguments:
            node -- the tree node to start from
            oneLine -- if True, returns only first line of output (for titles)
            noHtml -- if True, removes all HTML markup (for titles, etc.)
            formatHtml -- if False, escapes HTML from prefix & suffix
            spotRef -- optional, used for ancestor field refs
        """
        if not spotRef:
            spotRef = node.spotByNumber(0)
        for num in range(self.ancestorLevel):
            spotRef = spotRef.parentSpot
            if not spotRef:
                return ''
        try:
            field = spotRef.nodeRef.formatRef.fieldDict[self.name]
        except (AttributeError, KeyError):
            return ''
        return field.outputText(spotRef.nodeRef, oneLine, noHtml, formatHtml,
                                spotRef)

    def sepName(self):
        """Return the name enclosed with {* *} separators
        """
        return '{{*{0}{1}*}}'.format(self.ancestorLevel * '*', self.name)


class AnyAncestorField(TextField):
    """Placeholder format for ref. to matching ancestor fields at any level.
    """
    typeName = 'AnyAncestor'
    def __init__(self, name):
        """Initialize a field format placeholder type.

        Arguments:
            name -- the field name string
        """
        super().__init__(name, {})

    def outputText(self, node, oneLine, noHtml, formatHtml, spotRef=None):
        """Return formatted output text for this field in this node.

        Finds the appropriate ancestor node to get the field text.
        Arguments:
            node -- the tree node to start from
            oneLine -- if True, returns only first line of output (for titles)
            noHtml -- if True, removes all HTML markup (for titles, etc.)
            formatHtml -- if False, escapes HTML from prefix & suffix
            spotRef -- optional, used for ancestor field refs
        """
        if not spotRef:
            spotRef = node.spotByNumber(0)
        while spotRef.parentSpot:
            spotRef = spotRef.parentSpot
            try:
                field = spotRef.nodeRef.formatRef.fieldDict[self.name]
            except (AttributeError, KeyError):
                pass
            else:
                return field.outputText(spotRef.nodeRef, oneLine, noHtml,
                                        formatHtml, spotRef)
        return ''

    def sepName(self):
        """Return the name enclosed with {* *} separators
        """
        return '{{*?{0}*}}'.format(self.name)


class ChildListField(TextField):
    """Placeholder format for ref. to matching ancestor fields at any level.
    """
    typeName = 'ChildList'
    def __init__(self, name):
        """Initialize a field format placeholder type.

        Arguments:
            name -- the field name string
        """
        super().__init__(name, {})

    def outputText(self, node, oneLine, noHtml, formatHtml, spotRef=None):
        """Return formatted output text for this field in this node.

        Returns a joined list of matching child field data.
        Arguments:
            node -- the tree node to start from
            oneLine -- if True, returns only first line of output (for titles)
            noHtml -- if True, removes all HTML markup (for titles, etc.)
            formatHtml -- if False, escapes HTML from prefix & suffix
            spotRef -- optional, used for ancestor field refs
        """
        result = []
        for child in node.childList:
            try:
                field = child.formatRef.fieldDict[self.name]
            except KeyError:
                pass
            else:
                result.append(field.outputText(child, oneLine, noHtml,
                                               formatHtml, spotRef))
        outputSep = node.formatRef.outputSeparator
        return outputSep.join(result)

    def sepName(self):
        """Return the name enclosed with {* *} separators
        """
        return '{{*&{0}*}}'.format(self.name)


class DescendantCountField(TextField):
    """Placeholder format for count of descendants at a given level.
    """
    typeName = 'DescendantCount'
    def __init__(self, name, descendantLevel=1):
        """Initialize a field format placeholder type.

        Arguments:
            name -- the field name string
            descendantLevel -- the level to descend to
        """
        super().__init__(name, {})
        self.descendantLevel = descendantLevel

    def outputText(self, node, oneLine, noHtml, formatHtml, spotRef=None):
        """Return formatted output text for this field in this node.

        Returns a count of descendants at the approriate level.
        Arguments:
            node -- the tree node to start from
            oneLine -- if True, returns only first line of output (for titles)
            noHtml -- if True, removes all HTML markup (for titles, etc.)
            formatHtml -- if False, escapes HTML from prefix & suffix
            spotRef -- optional, used for ancestor field refs
        """
        newNodes = [node]
        for i in range(self.descendantLevel):
            prevNodes = newNodes
            newNodes = []
            for child in prevNodes:
                newNodes.extend(child.childList)
        return repr(len(newNodes))

    def sepName(self):
        """Return the name enclosed with {* *} separators
        """
        return '{{*#{0}*}}'.format(self.name)


####  Utility Functions  ####

def removeMarkup(text):
    """Return text with all HTML Markup removed and entities unescaped.

    Any <br /> tags are replaced with newlines.
    """
    text = _lineBreakRegEx.sub('\n', text)
    text = _stripTagRe.sub('', text)
    return saxutils.unescape(text)

def adjOutDateFormat(dateFormat):
    """Replace Linux lead zero removal with Windows version in date formats.

    Arguments:
        dateFormat -- the format to modify
    """
    if sys.platform.startswith('win'):
        dateFormat = dateFormat.replace('%-', '%#')
    return dateFormat

def adjInDateFormat(dateFormat):
    """Remove lead zero formatting in date formats for reading dates.

    Arguments:
        dateFormat -- the format to modify
    """
    return dateFormat.replace('%-', '%')

def adjTimeAmPm(timeFormat, time):
    """Add AM/PM to timeFormat if in format and locale skips it.

    Arguments:
        timeFormat -- the format to modify
        time -- the datetime object to check for AM/PM
    """
    if '%p' in timeFormat and time.strftime('%I (%p)').endswith('()'):
        amPm = 'AM' if time.hour < 12 else 'PM'
        timeFormat = re.sub(r'(?<!%)%p', amPm, timeFormat)
    return timeFormat

def translatedTypeName(typeName):
    """Return a translated type name.

    Arguments:
        typeName -- the English type name
    """
    try:
        return translatedFieldTypes[fieldTypes.index(typeName)]
    except ValueError:
        if typeName == 'DescendantCount':
            return _('DescendantCount')
        raise