~mwshinn/+junk/notes

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
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
;;; notes2-mode.el --- Based on markdown-mode.el

;; Copyright (C) 2007-2013 Jason R. Blevins <jrblevin@sdf.org>
;; Copyright (C) 2007, 2009 Edward O'Connor <ted@oconnor.cx>
;; Copyright (C) 2007 Conal Elliott <conal@conal.net>
;; Copyright (C) 2008 Greg Bognar <greg_bognar@hms.harvard.edu>
;; Copyright (C) 2008 Dmitry Dzhus <mail@sphinx.net.ru>
;; Copyright (C) 2008 Bryan Kyle <bryan.kyle@gmail.com>
;; Copyright (C) 2008 Ben Voui <intrigeri@boum.org>
;; Copyright (C) 2009 Ankit Solanki <ankit.solanki@gmail.com>
;; Copyright (C) 2009 Hilko Bengen <bengen@debian.org>
;; Copyright (C) 2009 Peter Williams <pezra@barelyenough.org>
;; Copyright (C) 2010 George Ogata <george.ogata@gmail.com>
;; Copyright (C) 2011 Eric Merritt <ericbmerritt@gmail.com>
;; Copyright (C) 2011 Philippe Ivaldi <pivaldi@sfr.fr>
;; Copyright (C) 2011 Jeremiah Dodds <jeremiah.dodds@gmail.com>
;; Copyright (C) 2011 Christopher J. Madsen <cjm@cjmweb.net>
;; Copyright (C) 2011 Shigeru Fukaya <shigeru.fukaya@gmail.com>
;; Copyright (C) 2011 Joost Kremers <joostkremers@fastmail.fm>
;; Copyright (C) 2011-2012 Donald Ephraim Curtis <dcurtis@milkbox.net>
;; Copyright (C) 2012 Akinori Musha <knu@idaemons.org>
;; Copyright (C) 2012 Zhenlei Jia <zhenlei.jia@gmail.com>
;; Copyright (C) 2012 Peter Jones <pjones@pmade.com>
;; Copyright (C) 2013 Matus Goljer <dota.keys@gmail.com>

;; Author: Jason R. Blevins <jrblevin@sdf.org>
;; Maintainer: Jason R. Blevins <jrblevin@sdf.org>
;; Created: May 24, 2007
;; Version: 2.0
;; Keywords: Markdown, GitHub Flavored Markdown, itex
;; URL: http://jblevins.org/projects/markdown-mode/

;; This file is not part of GNU Emacs.

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

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

;; You should have received a copy of the GNU General Public License
;; along with this program; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.

;;; Commentary:

;; markdown-mode is a major mode for editing [Markdown][]-formatted
;; text files in GNU Emacs.  markdown-mode is free software, licensed
;; under the GNU GPL.
;;
;;  [Markdown]: http://daringfireball.net/projects/markdown/
;;
;; The latest stable version is markdown-mode 2.0, released on March 24, 2013:
;;
;;    * [markdown-mode.el][]
;;    * [Screenshot][][^theme]
;;    * [Release notes][]
;;
;;  [markdown-mode.el]: http://jblevins.org/projects/markdown-mode/markdown-mode.el
;;  [screenshot]: http://jblevins.org/projects/markdown-mode/screenshots/20130131-002.png
;;  [release notes]: http://jblevins.org/projects/markdown-mode/rev-2-0
;;
;; [^theme]: The theme used in the screenshot is
;;   [color-theme-twilight](https://github.com/crafterm/twilight-emacs).
;;
;; markdown-mode is also available in several package managers, including:
;;
;;    * Debian and Ubuntu Linux: [emacs-goodies-el][]
;;    * RedHat and Fedora Linux: [emacs-goodies][]
;;    * OpenBSD: [textproc/markdown-mode][]
;;    * Arch Linux (AUR): [emacs-markdown-mode-git][]
;;    * MacPorts: [markdown-mode.el][macports-package] ([pending][macports-ticket])
;;    * FreeBSD: [textproc/markdown-mode.el][freebsd-port]
;;
;;  [emacs-goodies-el]: http://packages.debian.org/emacs-goodies-el
;;  [emacs-goodies]: https://admin.fedoraproject.org/pkgdb/acls/name/emacs-goodies
;;  [textproc/markdown-mode]: http://pkgsrc.se/textproc/markdown-mode
;;  [emacs-markdown-mode-git]: http://aur.archlinux.org/packages.php?ID=30389
;;  [macports-package]: https://trac.macports.org/browser/trunk/dports/editors/markdown-mode.el/Portfile
;;  [macports-ticket]: http://trac.macports.org/ticket/35716
;;  [freebsd-port]: http://svnweb.freebsd.org/ports/head/textproc/markdown-mode.el
;;
;; The latest development version can be downloaded directly
;; ([markdown-mode.el][devel.el]) or it can be obtained from the
;; (browsable and clonable) Git repository at
;; <http://jblevins.org/git/markdown-mode.git>.  The entire repository,
;; including the full project history, can be cloned via the Git protocol
;; by running
;;
;;     git clone git://jblevins.org/git/markdown-mode.git
;;
;;  [devel.el]: http://jblevins.org/git/markdown-mode.git/plain/markdown-mode.el

;;; Installation:

;; Make sure to place `markdown-mode.el` somewhere in the load-path and add
;; the following lines to your `.emacs` file to associate markdown-mode
;; with `.text`, `.markdown`, and `.md` files:
;;
;;     (autoload 'markdown-mode "markdown-mode"
;;        "Major mode for editing Markdown files" t)
;;     (add-to-list 'auto-mode-alist '("\\.text\\'" . markdown-mode))
;;     (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode))
;;     (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode))
;;
;; There is no official Markdown file extension, nor is there even a
;; _de facto_ standard, so you can easily add, change, or remove any
;; of the file extensions above as needed.

;;; Usage:

;; Keybindings are grouped by prefixes based on their function.  For
;; example, the commands for inserting links are grouped under `C-c
;; C-a`, where the `C-a` is a mnemonic for the HTML `<a>` tag.  In
;; other cases, the connection to HTML is not direct.  For example,
;; commands dealing with headings begin with `C-c C-t` (mnemonic:
;; titling).  The primary commands in each group will are described
;; below.  You can obtain a list of all keybindings by pressing `C-c
;; C-h`.  Movement and shifting commands tend to be associated with
;; paired delimiters such as `M-{` and `M-}` or `C-c <` and `C-c >`.
;; Outline navigation keybindings the same as in `org-mode'.  Finally,
;; commands for running Markdown or doing maintenance on an open file
;; are grouped under the `C-c C-c` prefix.  The most commonly used
;; commands are described below.  You can obtain a list of all
;; keybindings by pressing `C-c C-h`.
;;
;;   * Hyperlinks: `C-c C-a`
;;
;;     In this group, `C-c C-a l` inserts an inline link of the form
;;     `[text](url)`.  The link text is determined as follows.  First,
;;     if there is an active region (i.e., when transient mark mode is
;;     on and the mark is active), use it as the link text.  Second,
;;     if the point is at a word, use that word as the link text.  In
;;     these two cases, the original text will be replaced with the
;;     link and point will be left at the position for inserting a
;;     URL.  Otherwise, insert empty link markup and place the point
;;     for inserting the link text.
;;
;;     `C-c C-a L` inserts a reference link of the form `[text][label]`
;;     and, optionally, a corresponding reference label definition.
;;     The link text is determined in the same way as with an inline
;;     link (using the region, when active, or the word at the point),
;;     but instead of inserting empty markup as a last resort, the
;;     link text will be read from the minibuffer.  The reference
;;     label will be read from the minibuffer in both cases, with
;;     completion from the set of currently defined references.  To
;;     create an implicit reference link, press `RET` to accept the
;;     default, an empty label.  If the entered referenced label is
;;     not defined, additionally prompt for the URL and (optional)
;;     title.  If a URL is provided, a reference definition will be
;;     inserted in accordance with `markdown-reference-location'.
;;     If a title is given, it will be added to the end of the
;;     reference definition and will be used to populate the title
;;     attribute when converted to XHTML.
;;
;;     `C-c C-a u` inserts a bare url, delimited by angle brackets.  When
;;     there is an active region, the text in the region is used as the
;;     URL.  If the point is at a URL, that url is used.  Otherwise,
;;     insert angle brackets and position the point in between them
;;     for inserting the URL.
;;
;;     `C-c C-a f` inserts a footnote marker at the point, inserts a
;;     footnote definition below, and positions the point for
;;     inserting the footnote text.  Note that footnotes are an
;;     extension to Markdown and are not supported by all processors.
;;
;;     `C-c C-a w` behaves much like the inline link insertion command
;;     and inserts a wiki link of the form `[[WikiLink]]`.  If there
;;     is an active region, use the region as the link text.  If the
;;     point is at a word, use the word as the link text.  If there is
;;     no active region and the point is not at word, simply insert
;;     link markup.  Note that wiki links are an extension to Markdown
;;     and are not supported by all processors.
;;
;;   * Images: `C-c C-i`
;;
;;     `C-c C-i i` inserts markup for an inline image, using the
;;     active region or the word at point, if any, as the alt text.
;;     `C-c C-i I` behaves similarly and inserts a reference-style
;;     image.
;;
;;   * Styles: `C-c C-s`
;;
;;     `C-c C-s e` inserts markup to make a region or word italic (`e`
;;     for `<em>` or emphasis).  If there is an active region, make
;;     the region italic.  If the point is at a non-italic word, make
;;     the word italic.  If the point is at an italic word or phrase,
;;     remove the italic markup.  Otherwise, simply insert italic
;;     delimiters and place the cursor in between them.  Similarly,
;;     use `C-c C-s s` for bold (`<strong>`) and `C-c C-s c` for
;;     inline code (`<code>`).
;;
;;     `C-c C-s b` inserts a blockquote using the active region, if any,
;;     or starts a new blockquote.  `C-c C-s C-b` is a variation which
;;     always operates on the region, regardless of whether it is
;;     active or not.  The appropriate amount of indentation, if any,
;;     is calculated automatically given the surrounding context, but
;;     may be adjusted later using the region indentation commands.
;;
;;     `C-c C-s p` behaves similarly for inserting preformatted code
;;     blocks, with `C-c C-s C-p` being the region-only counterpart.
;;
;;   * Headings: `C-c C-t`
;;
;;     All heading insertion commands use the text in the active
;;     region, if any, as the heading text.  Otherwise, if the current
;;     line is not blank, they use the text on the current line.
;;     Finally, the setext commands will prompt for heading text if
;;     there is no active region and the current line is blank.
;;     
;;     `C-c C-t h` inserts a heading with automatically chosen type and
;;     level (both determined by the previous heading).  `C-c C-t H`
;;     behaves similarly, but uses setext (underlined) headings when
;;     possible, still calculating the level automatically.
;;     In cases where the automatically-determined level is not what
;;     you intended, the level can be quickly promoted or demoted
;;     (as described below).  Alternatively, a `C-u` prefix can be
;;     given to insert a heading promoted by one level or a `C-u C-u`
;;     prefix can be given to insert a heading demoted by one level.
;;
;;     To insert a heading of a specific level and type, use `C-c C-t 1`
;;     through `C-c C-t 6` for atx (hash mark) headings and `C-c C-t !` or
;;     `C-c C-t @` for setext headings of level one or two, respectively.
;;     Note that `!` is `S-1` and `@` is `S-2`.
;;
;;     If the point is at a heading, these commands will replace the
;;     existing markup in order to update the level and/or type of the
;;     heading.  To remove the markup of the heading at the point,
;;     press `C-c C-k` to kill the heading and press `C-y` to yank the
;;     heading text back into the buffer.
;;
;;   * Horizontal Rules: `C-c -`
;;
;;     `C-c -` inserts a horizontal rule.  By default, insert the
;;     first string in the list `markdown-hr-strings' (the most
;;     prominent rule).  With a `C-u` prefix, insert the last string.
;;     With a numeric prefix `N`, insert the string in position `N`
;;     (counting from 1).
;;
;;   * Markdown and Maintenance Commands: `C-c C-c`
;;
;;     *Compile:* `C-c C-c m` will run Markdown on the current buffer
;;     and show the output in another buffer.  *Preview*: `C-c C-c p`
;;     runs Markdown on the current buffer and previews, stores the
;;     output in a temporary file, and displays the file in a browser.
;;     *Export:* `C-c C-c e` will run Markdown on the current buffer
;;     and save the result in the file `basename.html`, where
;;     `basename` is the name of the Markdown file with the extension
;;     removed.  *Export and View:* press `C-c C-c v` to export the
;;     file and view it in a browser.  **For both export commands, the
;;     output file will be overwritten without notice.**
;;     *Open:* `C-c C-c o` will open the Markdown source file directly
;;     using `markdown-open-command'.
;;
;;     To summarize:
;;
;;       - `C-c C-c m`: `markdown-command' > `*markdown-output*` buffer.
;;       - `C-c C-c p`: `markdown-command' > temporary file > browser.
;;       - `C-c C-c e`: `markdown-command' > `basename.html`.
;;       - `C-c C-c v`: `markdown-command' > `basename.html` > browser.
;;       - `C-c C-c w`: `markdown-command' > kill ring.
;;       - `C-c C-c o`: `markdown-open-command'.
;;
;;     `C-c C-c c` will check for undefined references.  If there are
;;     any, a small buffer will open with a list of undefined
;;     references and the line numbers on which they appear.  In Emacs
;;     22 and greater, selecting a reference from this list and
;;     pressing `RET` will insert an empty reference definition at the
;;     end of the buffer.  Similarly, selecting the line number will
;;     jump to the corresponding line.
;;
;;     `C-c C-c n` renumbers any ordered lists in the buffer that are
;;     out of sequence.
;;
;;     `C-c C-c ]` completes all headings and normalizes all horizontal
;;     rules in the buffer.
;;
;;   * Following Links: `C-c C-o`
;;
;;     Press `C-c C-o` when the point is on an inline or reference
;;     link to open the URL in a browser.  When the point is at a
;;     wiki link, open it in another buffer (in the current window,
;;     or in the other window with the `C-u` prefix).  Use `M-p` and
;;     `M-n` to quickly jump to the previous or next link of any type.
;;
;;   * Jumping: `C-c C-j`
;;
;;     Use `C-c C-j` to jump from the object at point to its counterpart
;;     elsewhere in the text, when possible.  Jumps between reference
;;     links and definitions; between footnote markers and footnote
;;     text.  If more than one link uses the same reference name, a
;;     new buffer will be created containing clickable buttons for jumping
;;     to each link.  You may press `TAB` or `S-TAB` to jump between
;;     buttons in this window.
;;
;;   * Promotion and Demotion: `C-c C--` and `C-c C-=`
;;
;;     Headings, horizontal rules, and list items can be promoted and
;;     demoted, as well as bold and italic text.  For headings,
;;     "promotion" means *decreasing* the level (i.e., moving from
;;     `<h2>` to `<h1>`) while "demotion" means *increasing* the
;;     level.  For horizontal rules, promotion and demotion means
;;     moving backward or forward through the list of rule strings in
;;     `markdown-hr-strings'.  For bold and italic text, promotion and
;;     demotion means changing the markup from underscores to asterisks.
;;     Press `C-c C--` or `M-LEFT` to promote the element at the point
;;     if possible.
;;
;;     To remember these commands, note that `-` is for decreasing the
;;     level (promoting), and `=` (on the same key as `+`) is for
;;     increasing the level (demoting).  Similarly, the left and right
;;     arrow keys indicate the direction that the atx heading markup
;;     is moving in when promoting or demoting.
;;
;;   * Completion: `C-c C-]`
;;
;;     Complete markup is in normalized form, which means, for
;;     example, that the underline portion of a setext header is the
;;     same length as the heading text, or that the number of leading
;;     and trailing hash marks of an atx header are equal and that
;;     there is no extra whitespace in the header text.  `C-c C-]`
;;     completes the markup at the point, if it is determined to be
;;     incomplete.
;;
;;   * Editing Lists: `M-RET`, `M-UP`, `M-DOWN`, `M-LEFT`, and `M-RIGHT`
;;
;;     New list items can be inserted with `M-RET`.  This command
;;     determines the appropriate marker (one of the possible
;;     unordered list markers or the next number in sequence for an
;;     ordered list) and indentation level by examining nearby list
;;     items.  If there is no list before or after the point, start a
;;     new list.  Prefix this command by `C-u` to decrease the
;;     indentation by one level.  Prefix this command by `C-u C-u` to
;;     increase the indentation by one level.
;;
;;     Existing list items can be moved up or down with `M-UP` or
;;     `M-DOWN` and indented or exdented with `M-RIGHT` or `M-LEFT`.
;;
;;   * Shifting the Region: `C-c <` and `C-c >`
;;
;;     Text in the region can be indented or exdented as a group using
;;     `C-c >` to indent to the next indentation point (calculated in
;;     the current context), and `C-c <` to exdent to the previous
;;     indentation point.  These keybindings are the same as those for
;;     similar commands in `python-mode'.
;;
;;   * Killing Elements: `C-c C-k`
;;
;;     Press `C-c C-k` to kill the thing at point and add important
;;     text, without markup, to the kill ring.  Possible things to
;;     kill include (roughly in order of precedece): inline code,
;;     headings, horizonal rules, links (add link text to kill ring),
;;     images (add alt text to kill ring), angle URIs, email
;;     addresses, bold, italics, reference definitions (add URI to
;;     kill ring), footnote markers and text (kill both marker and
;;     text, add text to kill ring), and list items.
;;
;;   * Outline Navigation: `C-c C-n`, `C-c C-p`, `C-c C-f`, `C-c C-b`, and `C-c C-u`
;;
;;     Navigation between headings is possible using `outline-mode'.
;;     Use `C-c C-n` and `C-c C-p` to move between the next and previous
;;     visible headings.  Similarly, `C-c C-f` and `C-c C-b` move to the
;;     next and previous visible headings at the same level as the one
;;     at the point.  Finally, `C-c C-u` will move up to a lower-level
;;     (higher precedence) visible heading.
;;
;;   * Movement by Paragraph or Block: `M-{` and `M-}`
;;
;;     The definition of a "paragraph" is slightly different in
;;     markdown-mode than, say, text-mode, because markdown-mode
;;     supports filling for list items and respects hard line breaks,
;;     both of which break paragraphs.  So, markdown-mode overrides
;;     the usual paragraph navigation commands `M-{` and `M-}` so that
;;     with a `C-u` prefix, these commands jump to the beginning or
;;     end of an entire block of text, respectively, where "blocks"
;;     are separated by one or more lines.
;;
;;   * Movement by Defun: `C-M-a`, `C-M-e`, and `C-M-h`
;;
;;     The usual Emacs commands can be used to move by defuns
;;     (top-level major definitions).  In markdown-mode, a defun is a
;;     section.  As usual, `C-M-a` will move the point to the
;;     beginning of the current or preceding defun, `C-M-e` will move
;;     to the end of the current or following defun, and `C-M-h` will
;;     put the region around the entire defun.
;;
;; As noted, many of the commands above behave differently depending
;; on whether Transient Mark mode is enabled or not.  When it makes
;; sense, if Transient Mark mode is on and the region is active, the
;; command applies to the text in the region (e.g., `C-c C-s s` makes the
;; region bold).  For users who prefer to work outside of Transient
;; Mark mode, since Emacs 22 it can be enabled temporarily by pressing
;; `C-SPC C-SPC`.  When this is not the case, many commands then
;; proceed to look work with the word or line at the point.
;;
;; When applicable, commands that specifically act on the region even
;; outside of Transient Mark mode have the same keybinding as their
;; standard counterpart, but the letter is uppercase.  For example,
;; `markdown-insert-blockquote' is bound to `C-c C-s b` and only acts on
;; the region in Transient Mark mode while `markdown-blockquote-region'
;; is bound to `C-c C-s B` and always applies to the region (when nonempty).
;;
;; Note that these region-specific functions are useful in many
;; cases where it may not be obvious.  For example, yanking text from
;; the kill ring sets the mark at the beginning of the yanked text
;; and moves the point to the end.  Therefore, the (inactive) region
;; contains the yanked text.  So, `C-y` followed by `C-c C-s C-b` will
;; yank text and turn it into a blockquote.
;;
;; markdown-mode attempts to be flexible in how it handles
;; indentation.  When you press `TAB` repeatedly, the point will cycle
;; through several possible indentation levels corresponding to things
;; you might have in mind when you press `RET` at the end of a line or
;; `TAB`.  For example, you may want to start a new list item,
;; continue a list item with hanging indentation, indent for a nested
;; pre block, and so on.  Exdention is handled similarly when backspace
;; is pressed at the beginning of the non-whitespace portion of a line.
;;
;; markdown-mode supports outline-minor-mode as well as org-mode-style
;; visibility cycling for atx- or hash-style headings.  There are two
;; types of visibility cycling: Pressing `S-TAB` cycles globally between
;; the table of contents view (headings only), outline view (top-level
;; headings only), and the full document view.  Pressing `TAB` while the
;; point is at a heading will cycle through levels of visibility for the
;; subtree: completely folded, visible children, and fully visible.
;; Note that mixing hash and underline style headings will give undesired
;; results.

;;; Customization:

;; Although no configuration is *necessary* there are a few things
;; that can be customized.  The `M-x customize-mode` command
;; provides an interface to all of the possible customizations:
;;
;;   * `markdown-command' - the command used to run Markdown (default:
;;     `markdown`).  This variable may be customized to pass
;;     command-line options to your Markdown processor of choice.
;;
;;   * `markdown-command-needs-filename' - set to `t' if
;;     `markdown-command' does not accept standard input (default:
;;     `nil').  When `nil', `markdown-mode' will pass the Markdown
;;     content to `markdown-command' using standard input (`stdin`).
;;     When set to `t', `markdown-mode' will pass the name of the file
;;     as the final command-line argument to `markdown-command'.  Note
;;     that in the latter case, you will only be able to run
;;     `markdown-command' from buffers which are visiting a file.
;;
;;   * `markdown-open-command' - the command used for calling a standalone
;;     Markdown previewer which is capable of opening Markdown source files
;;     directly (default: `nil').  This command will be called
;;     with a single argument, the filename of the current buffer.
;;     A representative program is the Mac app [Marked][], a
;;     live-updating MultiMarkdown previewer which has a command line
;;     utility at `/usr/local/bin/mark`.
;;
;;   * `markdown-hr-strings' - list of strings to use when inserting
;;     horizontal rules.  Different strings will not be distinguished
;;     when converted to HTML--they will all be converted to
;;     `<hr/>`--but they may add visual distinction and style to plain
;;     text documents.  To maintain some notion of promotion and
;;     demotion, keep these sorted from largest to smallest.
;;
;;   * `markdown-bold-underscore' - set to a non-nil value to use two
;;     underscores for bold instead of two asterisks (default: `nil').
;;
;;   * `markdown-italic-underscore' - set to a non-nil value to use
;;     underscores for italic instead of asterisks (default: `nil').
;;
;;   * `markdown-indent-function' - the function to use for automatic
;;     indentation (default: `markdown-indent-line').
;;
;;   * `markdown-indent-on-enter' - set to a non-nil value to
;;     automatically indent new lines when the enter key is pressed
;;     (default: `t')
;;
;;   * `markdown-wiki-link-alias-first' - set to a non-nil value to
;;     treat aliased wiki links like `[[link text|PageName]]`
;;     (default: `t').  When set to nil, they will be treated as
;;     `[[PageName|link text]]'.
;;
;;   * `markdown-uri-types' - a list of protocol schemes (e.g., "http")
;;     for URIs that `markdown-mode' should highlight.
;;
;;   * `markdown-enable-math' - syntax highlighting for LaTeX
;;     fragments (default: `nil').  Set this to `t' to turn on math
;;     support by default.  Math support can be toggled later using
;;     the function `markdown-enable-math'."
;;
;;   * `markdown-css-path' - CSS file to link to in XHTML output
;;     (default: `""`).
;;
;;   * `markdown-content-type' - when set to a nonempty string, an
;;     `http-equiv` attribute will be included in the XHTML `<head>`
;;     block (default: `""`).  If needed, the suggested values are
;;     `application/xhtml+xml` or `text/html`.  See also:
;;     `markdown-coding-system'.
;;
;;   * `markdown-coding-system' - used for specifying the character
;;     set identifier in the `http-equiv` attribute when included
;;     (default: `nil').  See `markdown-content-type', which must
;;     be set before this variable has any effect.  When set to `nil',
;;     `buffer-file-coding-system' will be used to automatically
;;     determine the coding system string (falling back to
;;     `iso-8859-1' when unavailable).  Common settings are `utf-8'
;;     and `iso-latin-1'.
;;
;;   * `markdown-xhtml-header-content' - additional content to include
;;     in the XHTML `<head>` block (default: `""`).
;;
;;   * `markdown-xhtml-standalone-regexp' - a regular expression which
;;     `markdown-mode' uses to determine whether the output of
;;     `markdown-command' is a standalone XHTML document or an XHTML
;;     fragment (default: `"^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"`).  If
;;     this regular expression not matched in the first five lines of
;;     output, `markdown-mode' assumes the output is a fragment and
;;     adds a header and footer.
;;
;;   * `markdown-link-space-sub-char' - a character to replace spaces
;;     when mapping wiki links to filenames (default: `"_"`).
;;     For example, use an underscore for compatibility with the
;;     Python Markdown WikiLinks extension.  In `gfm2-mode', this is
;;     set to `"-"` to conform with GitHub wiki links.
;;
;;   * `markdown-reference-location' - where to insert reference
;;     definitions (default: `header`).  The possible locations are
;;     the end of the document (`end`), after the current block
;;     (`immediately`), before the next header (`header`).
;;
;;   * `markdown-footnote-location' - where to insert footnote text
;;     (default: `end`).  The set of location options is the same as
;;     for `markdown-reference-location'.
;;
;; Additionally, the faces used for syntax highlighting can be modified to
;; your liking by issuing `M-x customize-group RET markdown-faces`
;; or by using the "Markdown Faces" link at the bottom of the mode
;; customization screen.
;;
;; [Marked]: https://itunes.apple.com/us/app/marked/id448925439?ls=1&mt=12&partnerId=30&siteID=GpHp3Acs1Yo

;;; Extensions:

;; Besides supporting the basic Markdown syntax, markdown-mode also
;; includes syntax highlighting for `[[Wiki Links]]` by default.  Wiki
;; links may be followed by pressing `C-c C-o` when the point
;; is at a wiki link.  Use `M-p` and `M-n` to quickly jump to the
;; previous and next links (including links of other types).
;; Aliased or piped wiki links of the form `[[link text|PageName]]`
;; are also supported.  Since some wikis reverse these components, set
;; `markdown-wiki-link-alias-first' to nil to treat them as
;; `[[PageName|link text]]`.
;;
;; [SmartyPants][] support is possible by customizing `markdown-command'.
;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
;; then you can set `markdown-command' to `"markdown | smartypants"`.
;; You can do this either by using `M-x customize-group markdown`
;; or by placing the following in your `.emacs` file:
;;
;;     (defun markdown-custom ()
;;       "markdown-mode-hook"
;;       (setq markdown-command "markdown | smartypants"))
;;     (add-hook 'markdown-mode-hook '(lambda() (markdown-custom)))
;;
;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
;;
;; Syntax highlighting for mathematical expressions written
;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
;; can be enabled by setting `markdown-enable-math' to a non-nil value,
;; either via customize or by placing `(setq markdown-enable-math t)`
;; in `.emacs`, and then restarting Emacs or calling
;; `markdown-reload-extensions'.

;;; GitHub Flavored Markdown:

;; A [GitHub Flavored Markdown][GFM2] (GFM2) mode, `gfm2-mode', is also
;; available.  The GitHub implementation of differs slightly from
;; standard Markdown.  The most important differences are that
;; newlines are significant, triggering hard line breaks, and that
;; underscores inside of words (e.g., variable names) need not be
;; escaped.  As such, `gfm2-mode' turns off `auto-fill-mode' and turns
;; on `visual-line-mode' (or `longlines-mode' if `visual-line-mode' is
;; not available).  Underscores inside of words (such as
;; test_variable) will not trigger emphasis.
;;
;; Wiki links in this mode will be treated as on GitHub, with hyphens
;; replacing spaces in filenames and where the first letter of the
;; filename capitalized.  For example, `[[wiki link]]' will map to a
;; file named `Wiki-link` with the same extension as the current file.
;;
;; GFM2 code blocks, with optional programming language keywords, will
;; be highlighted.  They can be inserted with `C-c C-s P`.  If there
;; is an active region, the text in the region will be placed inside
;; the code block.  You will be prompted for the name of the language,
;; but may press enter to continue without naming a language.
;;
;; For a more complete GitHub-flavored markdown experience, consider
;; adding README.md to your `auto-mode-alist':
;;
;;     (add-to-list 'auto-mode-alist '("README\\.md\\'" . gfm2-mode))
;;
;; For GFM2 preview can be powered by setting `markdown-command' to
;; use [Docter][].  This may also be configured to work with [Marked][]
;; for `markdown-open-command'.
;;
;; [GFM2]: http://github.github.com/github-flavored-markdown/
;; [Docter]: https://github.com/alampros/Docter

;;; Acknowledgments:

;; markdown-mode has benefited greatly from the efforts of the
;; following people:
;;
;;   * Cyril Brulebois <cyril.brulebois@enst-bretagne.fr> for Debian packaging.
;;   * Conal Elliott <conal@conal.net> for a font-lock regexp patch.
;;   * Edward O'Connor <hober0@gmail.com> for a font-lock regexp fix and
;;     GitHub Flavored Markdown mode (`gfm2-mode').
;;   * Greg Bognar <greg_bognar@hms.harvard.edu> for menus and running
;;     `markdown' with an active region.
;;   * Daniel Burrows <dburrows@debian.org> for filing Debian bug #456592.
;;   * Peter S. Galbraith <psg@debian.org> for maintaining `emacs-goodies-el`.
;;   * Dmitry Dzhus <mail@sphinx.net.ru> for undefined reference checking.
;;   * Carsten Dominik <carsten@orgmode.org> for `org-mode', from which the
;;     visibility cycling functionality was derived, and for a bug fix
;;     related to `orgtbl-mode'.
;;   * Bryan Kyle <bryan.kyle@gmail.com> for indentation code.
;;   * Ben Voui <intrigeri@boum.org> for font-lock face customizations.
;;   * Ankit Solanki <ankit.solanki@gmail.com> for `longlines.el`
;;     compatibility and custom CSS.
;;   * Hilko Bengen <bengen@debian.org> for proper XHTML output.
;;   * Jose A. Ortega Ruiz <jao@gnu.org> for Emacs 23 fixes.
;;   * Nelson Minar <nelson@santafe.edu> for `html-helper-mode', from which
;;     comment matching functions were derived.
;;   * Alec Resnick <alec@sproutward.org> for bug reports.
;;   * Joost Kremers <joostkremers@fastmail.fm> for footnote-handling
;;     functions, bug reports regarding indentation, and
;;     fixes for byte-compilation warnings.
;;   * Peter Williams <pezra@barelyenough.org> for `fill-paragraph'
;;     enhancements.
;;   * George Ogata <george.ogata@gmail.com> for fixing several
;;     byte-compilation warnings.
;;   * Eric Merritt <ericbmerritt@gmail.com> for wiki link features.
;;   * Philippe Ivaldi <pivaldi@sfr.fr> for XHTML preview
;;     customizations and XHTML export.
;;   * Jeremiah Dodds <jeremiah.dodds@gmail.com> for supporting
;;     Markdown processors which do not accept input from stdin.
;;   * Werner Dittmann <werner.dittmann@t-online.de> for bug reports
;;     regarding the `cl` dependency and `auto-fill-mode' and indentation.
;;   * Scott Pfister <scott.pfister@gmail.com> for generalizing the space
;;     substitution character for mapping wiki links to filenames.
;;   * Marcin Kasperski <marcin.kasperski@mekk.waw.pl> for a patch to
;;     escape shell commands.
;;   * Christopher J. Madsen <cjm@cjmweb.net> for patches to fix a match
;;     data bug and to prefer `visual-line-mode' in `gfm2-mode'.
;;   * Shigeru Fukaya <shigeru.fukaya@gmail.com> for better adherence to
;;     Emacs Lisp coding conventions.
;;   * Donald Ephraim Curtis <dcurtis@milkbox.net> for fixing the `fill-paragraph'
;;     regexp, refactoring the compilation and preview functions,
;;     heading font-lock generalizations, list renumbering,
;;     and kill ring save.
;;   * Kevin Porter <kportertx@gmail.com> for wiki link handling in `gfm2-mode'.
;;   * Max Penet <max.penet@gmail.com> and Peter Eisentraut <peter_e@gmx.net>
;;     for an autoload token for `gfm2-mode'.
;;   * Ian Yang <me@iany.me> for improving the reference definition regex.
;;   * Akinori Musha <knu@idaemons.org> for an imenu index function.
;;   * Michael Sperber <sperber@deinprogramm.de> for XEmacs fixes.
;;   * Francois Gannaz <francois.gannaz@free.fr> for suggesting charset
;;     declaration in XHTML output.
;;   * Zhenlei Jia <zhenlei.jia@gmail.com> for smart exdention function.
;;   * Matus Goljer <dota.keys@gmail.com> for improved wiki link following
;;     and GFM2 code block insertion.
;;   * Peter Jones <pjones@pmade.com> for link following functions.
;;   * Bryan Fink <bryan.fink@gmail.com> for a bug report regarding
;;     externally modified files.
;;   * Vegard Vesterheim <vegard.vesterheim@uninett.no> for a bug fix
;;     related to `orgtbl-mode'.
;;   * Makoto Motohashi <mkt.motohashi@gmail.com> for before- and after-
;;     export hooks and unit test improvements.
;;   * Michael Dwyer <mdwyer@ehtech.in> for `gfm2-mode' underscore regexp.
;;   * Chris Lott <chris@chrislott.org> for suggesting reference label
;;     completion.

;;; Bugs:

;; Although markdown-mode is developed and tested primarily using
;; GNU Emacs 24, compatibility with earlier Emacsen is also a
;; priority.
;;
;; If you find any bugs in markdown-mode, please construct a test case
;; or a patch and email me at <jrblevin@sdf.org>.

;;; History:

;; markdown-mode was written and is maintained by Jason Blevins.  The
;; first version was released on May 24, 2007.
;;
;;   * 2007-05-24: Version 1.1
;;   * 2007-05-25: Version 1.2
;;   * 2007-06-05: [Version 1.3][]
;;   * 2007-06-29: Version 1.4
;;   * 2007-10-11: [Version 1.5][]
;;   * 2008-06-04: [Version 1.6][]
;;   * 2009-10-01: [Version 1.7][]
;;   * 2011-08-12: [Version 1.8][]
;;   * 2011-08-15: [Version 1.8.1][]
;;   * 2013-01-25: [Version 1.9][]
;;   * 2013-03-18: [Version 2.0][]
;;
;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
;; [Version 1.9]: http://jblevins.org/projects/markdown-mode/rev-1-9
;; [Version 2.0]: http://jblevins.org/projects/markdown-mode/rev-2-0


;;; Code:

(require 'easymenu)
(require 'outline)
(require 'thingatpt)
(eval-when-compile (require 'cl))


;;; Constants =================================================================

(defconst notes2-mode-version "2.0"
  "Notes2 mode version number.")

(defconst notes2-output-buffer-name "*notes2-output*"
  "Name of temporary buffer for notes2 command output.")


;;; Customizable Variables ====================================================

(defvar notes2-mode-hook nil
  "Hook run when entering Notes2 mode.")

(defvar notes2-before-export-hook nil
  "Hook run before running Notes2 to export XHTML output.
The hook may modify the buffer, which will be restored to it's
original state after exporting is complete.")

(defvar notes2-after-export-hook nil
  "Hook run after XHTML output has been saved.
Any changes to the output buffer made by this hook will be saved.")

(defgroup notes2 nil
  "Major mode for editing text files in Notes2 format."
  :prefix "notes2-"
  :group 'wp
  :link '(url-link "http://jblevins.org/projects/notes2-mode/"))

(defcustom notes2-command "notes2"
  "Command to run notes2."
  :group 'notes2
  :type 'string)

(defcustom notes2-command-needs-filename nil
  "Set to non-nil if `notes2-command' does not accept input from stdin.
Instead, it will be passed a filename as the final command line
option.  As a result, you will only be able to run Notes2 from
buffers which are visiting a file."
  :group 'notes2
  :type 'boolean)

(defcustom notes2-open-command nil
  "Command used for opening Notes2 files directly.
For example, a standalone Notes2 previewer.  This command will
be called with a single argument: the filename of the current
buffer."
  :group 'notes2
  :type 'string)

(defcustom notes2-hr-strings
  '("-------------------------------------------------------------------------------"
    "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
    "---------------------------------------"
    "* * * * * * * * * * * * * * * * * * * *"
    "---------"
    "* * * * *")
  "Strings to use when inserting horizontal rules.
The first string in the list will be the default when inserting a
horizontal rule.  Strings should be listed in decreasing order of
prominence (as in headings from level one to six) for use with
promotion and demotion functions."
  :group 'notes2
  :type 'list)

(defcustom notes2-bold-underscore nil
  "Use two underscores for bold instead of two asterisks."
  :group 'notes2
  :type 'boolean)

(defcustom notes2-italic-underscore nil
  "Use underscores for italic instead of asterisks."
  :group 'notes2
  :type 'boolean)

(defcustom notes2-indent-function 'notes2-indent-line
  "Function to use to indent."
  :group 'notes2
  :type 'function)

(defcustom notes2-indent-on-enter t
  "Automatically indent new lines when enter key is pressed.
When this variable is set to t, pressing RET will call
`newline-and-indent'.  When set to nil, define RET to call
`newline' as usual.  In the latter case, you can still use
auto-indentation by pressing \\[newline-and-indent]."
  :group 'notes2
  :type 'boolean)

(defcustom notes2-wiki-link-alias-first t
  "When non-nil, treat aliased wiki links like [[alias text|PageName]].
Otherwise, they will be treated as [[PageName|alias text]]."
  :group 'notes2
  :type 'boolean)

(defcustom notes2-uri-types
  '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
    "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
    "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
  "Link types for syntax highlighting of URIs."
  :group 'notes2
  :type 'list)

(defcustom notes2-css-path ""
  "URL of CSS file to link to in the output XHTML."
  :group 'notes2
  :type 'string)

(defcustom notes2-content-type ""
  "Content type string for the http-equiv header in XHTML output.
When set to a non-empty string, insert the http-equiv attribute.
Otherwise, this attribute is omitted."
  :group 'notes2
  :type 'string)

(defcustom notes2-coding-system nil
  "Character set string for the http-equiv header in XHTML output.
Defaults to `buffer-file-coding-system' (and falling back to
`iso-8859-1' when not available).  Common settings are `utf-8'
and `iso-latin-1'.  Use `list-coding-systems' for more choices."
  :group 'notes2
  :type 'coding-system)

(defcustom notes2-xhtml-header-content ""
  "Additional content to include in the XHTML <head> block."
  :group 'notes2
  :type 'string)

(defcustom notes2-xhtml-standalone-regexp
  "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
  "Regexp indicating whether `notes2-command' output is standalone XHTML."
  :group 'notes2
  :type 'regexp)

(defcustom notes2-link-space-sub-char "_"
  "Character to use instead of spaces when mapping wiki links to filenames."
  :group 'notes2
  :type 'string)

(defcustom notes2-use-ncbi-spellcheck t
  "Set to non-nil if you would like to use NCBI spellcheck when
connected to the internet.  This is implemented as an extension
to flyspell-mode.  When flyspell-mode is enabled, whenever it
finds a word that it believes to be a misspelling (such as
phenylalenine or neurotrophin), it will query the NCBI eSpell API
to check whether the word is actually misspelled.  

This has no effect if not connected to the internet.  This also has no effect
if flyspell-mode is disabled.  

Disabling this will speed up notes2-mode significantly when
flyspell-mode is enabled.  Also, when this option is enabled,
some incorrectly spelled words will be detected as being
correctly spelled, since NCBI doesn't distinguish between 'correct
words' and 'words that are so incorrect it can't even begin to
guess what you meant'."
  :group 'notes2
  :type 'boolean)


;;; Font Lock =================================================================

(require 'font-lock)

(defvar notes2-italic-face 'notes2-italic-face
  "Face name to use for italic text.")

(defvar notes2-underline-face 'notes2-underline-face
  "Face name to use for underline text.")

(defvar notes2-bold-face 'notes2-bold-face
  "Face name to use for bold text.")

(defvar notes2-important-face 'notes2-important-face
  "Face name to use for important text.")

(defvar notes2-update-face 'notes2-update-face
  "Face name to use for updates with UPDATE syntax.")

(defvar notes2-title-face 'notes2-title-face
  "Face name to use for the document title.")

(defvar notes2-header-delimiter-face 'notes2-header-delimiter-face
  "Face name to use as a base for header delimiters.")

(defvar notes2-header-rule-face 'notes2-header-rule-face
  "Face name to use as a base for header rules.")

(defvar notes2-header-face 'notes2-header-face
  "Face name to use as a base for headers.")

(defvar notes2-header-face-1 'notes2-header-face-1
  "Face name to use for level-1 headers.")

(defvar notes2-header-face-2 'notes2-header-face-2
  "Face name to use for level-2 headers.")

(defvar notes2-header-face-3 'notes2-header-face-3
  "Face name to use for level-3 headers.")

(defvar notes2-header-face-4 'notes2-header-face-4
  "Face name to use for level-4 headers.")

(defvar notes2-header-face-5 'notes2-header-face-5
  "Face name to use for level-5 headers.")

(defvar notes2-header-face-6 'notes2-header-face-6
  "Face name to use for level-6 headers.")

(defvar notes2-inline-code-face 'notes2-inline-code-face
  "Face name to use for inline code.")

(defvar notes2-highlight-face 'notes2-highlight-face
  "Face name to use for highlighted text.")

(defvar notes2-strikeout-face 'notes2-strikeout-face
  "Face name to use for struckout text.")

(defvar notes2-list-face 'notes2-list-face
  "Face name to use for list markers.")

(defvar notes2-blockquote-face 'notes2-blockquote-face
  "Face name to use for blockquote.")

(defvar notes2-pre-face 'notes2-pre-face
  "Face name to use for preformatted text.")

(defvar notes2-language-keyword-face 'notes2-language-keyword-face
  "Face name to use for programming language identifiers.")

(defvar notes2-link-face 'notes2-link-face
  "Face name to use for links.")

(defvar notes2-missing-link-face 'notes2-missing-link-face
  "Face name to use for links where the linked file does not exist.")

(defvar notes2-reference-face 'notes2-reference-face
  "Face name to use for reference.")

(defvar notes2-url-face 'notes2-url-face
  "Face name to use for URLs.")

(defvar notes2-link-title-face 'notes2-link-title-face
  "Face name to use for reference link titles.")

(defvar notes2-comment-face 'notes2-comment-face
  "Face name to use for HTML comments.")

(defvar notes2-math-face 'notes2-math-face
  "Face name to use for LaTeX expressions.")

(defvar notes2-metadata-key-face 'notes2-metadata-key-face
  "Face name to use for metadata keys.")

(defvar notes2-metadata-value-face 'notes2-metadata-value-face
  "Face name to use for metadata values.")

(defgroup notes2-faces nil
  "Faces used in Notes2 Mode"
  :group 'notes2
  :group 'faces)

(defface notes2-italic-face
  '((t (:inherit italic)))
  "Face for italic text."
  :group 'notes2-faces)

(defface notes2-underline-face
  '((t (:inherit underline)))
  "Face for underlined text."
  :group 'notes2-faces)

(defface notes2-bold-face
  '((t (:inherit bold)))
  "Face for bold text."
  :group 'notes2-faces)

(defface notes2-important-face
  '((t (:inherit bold :foreground "#ff0000")))
  "Face for bold text."
  :group 'notes2-faces)

(defface notes2-update-face
  '((t (:inherit bold)))
  "Face for bold text."
  :group 'notes2-faces)

(defface notes2-title-face
  '((t (:bold t :height 1.4 :inherit variable-pitch)))
  "Face for the document title."
  :group 'notes2-faces)

(defface notes2-header-rule-face
  '((t (:inherit font-lock-function-name-face :weight bold)))
  "Base face for headers rules."
  :group 'notes2-faces)

(defface notes2-header-delimiter-face
  '((t (:inherit font-lock-function-name-face :weight bold)))
  "Base face for headers hash delimiter."
  :group 'notes2-faces)

(defface notes2-header-face
  '((t (:inherit font-lock-function-name-face :weight bold)))
  "Base face for headers."
  :group 'notes2-faces)

(defface notes2-header-face-1
  '((t (:inherit notes2-header-face)))
  "Face for level-1 headers."
  :group 'notes2-faces)

(defface notes2-header-face-2
  '((t (:inherit notes2-header-face)))
  "Face for level-2 headers."
  :group 'notes2-faces)

(defface notes2-header-face-3
  '((t (:inherit notes2-header-face)))
  "Face for level-3 headers."
  :group 'notes2-faces)

(defface notes2-header-face-4
  '((t (:inherit notes2-header-face)))
  "Face for level-4 headers."
  :group 'notes2-faces)

(defface notes2-header-face-5
  '((t (:inherit notes2-header-face)))
  "Face for level-5 headers."
  :group 'notes2-faces)

(defface notes2-header-face-6
  '((t (:inherit notes2-header-face)))
  "Face for level-6 headers."
  :group 'notes2-faces)

(defface notes2-inline-code-face
  '((t (:inherit font-lock-constant-face)))
  "Face for inline code."
  :group 'notes2-faces)

(defface notes2-highlight-face
  '((t (:inherit font-lock-constant-face :background "#FFFF00" :foreground "#000000")))
  "Face for highlighted text."
  :group 'notes2-faces)

(defface notes2-strikeout-face
  '((t (:inherit font-lock-builtin-face :strike-through t :foreground "#FF0000")))
  "Face for list item markers."
  :group 'notes2-faces)

(defface notes2-blockquote-face
  '((t (:inherit font-lock-doc-face)))
  "Face for blockquote sections."
  :group 'notes2-faces)

(defface notes2-pre-face
  '((t (:inherit font-lock-constant-face)))
  "Face for preformatted text."
  :group 'notes2-faces)

(defface notes2-language-keyword-face
  '((t (:inherit font-lock-type-face)))
  "Face for programming language identifiers."
  :group 'notes2-faces)

(defface notes2-link-face
  '((t (:inherit font-lock-keyword-face)))
  "Face for links."
  :group 'notes2-faces)

(defface notes2-missing-link-face
  '((t (:inherit font-lock-warning-face)))
  "Face for missing links."
  :group 'notes2-faces)

(defface notes2-todo-face
  '((t (:inherit bold :foreground "#ff0000")))
  "Face for TODO entries."
  :group 'notes2-faces)

(defface notes2-url-face
  '((t (:inherit font-lock-string-face)))
  "Face for URLs."
  :group 'notes2-faces)

(defface notes2-link-title-face
  '((t (:inherit font-lock-comment-face)))
  "Face for reference link titles."
  :group 'notes2-faces)

(defface notes2-reference-face
  '((t (:inherit font-lock-keyword-face)))
  "Face for reference link titles."
  :group 'notes2-faces)

(defface notes2-comment-face
  '((t (:inherit font-lock-comment-face)))
  "Face for HTML comments."
  :group 'notes2-faces)

(defface notes2-math-face
  '((t (:inherit font-lock-string-face)))
  "Face for LaTeX expressions."
  :group 'notes2-faces)

(defface notes2-metadata-key-face
  '((t (:inherit font-lock-variable-name-face)))
  "Face for metadata keys."
  :group 'notes2-faces)

(defface notes2-metadata-value-face
  '((t (:inherit font-lock-string-face)))
  "Face for metadata values."
  :group 'notes2-faces)

(defconst notes2-regex-link-inline
  "\\(\\[\\[\\([^]^][^]]*\\|\\)\\]\\)\\(\\[\\([^)]*?\\)\\]\\]\\)"
  "Regular expression for a [text](file) or an image link ![text](file).
Group 1 matchs the entire first square bracket term, including the text.
Group 2 matches the text inside the first square brackets (the url).
Group 3 matches the entire (optional) second parenthesis term, including the URL and title.
Group 4 matches the title (optional).")

(defconst notes2-regex-title
  "\\`\\(.*\\)$"
  "Regexp identifying the document title.")

(defconst notes2-regex-header
  "^\\(\\*+\\)[ \t]*\\(.*?\\)[ \t]*\\(\\**\\)$"
  "Regexp identifying Notes2 headers.")

(defconst notes2-regex-header-1-atx
  "^\\(\\*\\)[ \t]+\\(.+?\\)[ \t]*\\(\\**\\)$"
  "Regular expression for level 1 atx-style (hash mark) headers.")

(defconst notes2-regex-header-2-atx
  "^\\(\\*\\*\\)[ \t]+\\(.+?\\)[ \t]*\\(\\**\\)$"
  "Regular expression for level 2 atx-style (hash mark) headers.")

(defconst notes2-regex-header-3-atx
  "^\\(\\*\\*\\*\\)[ \t]+\\(.+?\\)[ \t]*\\(\\**\\)$"
  "Regular expression for level 3 atx-style (hash mark) headers.")

(defconst notes2-regex-header-4-atx
  "^\\(\\*\\*\\*\\*\\)[ \t]+\\(.+?\\)[ \t]*\\(\\**\\)$"
  "Regular expression for level 4 atx-style (hash mark) headers.")

(defconst notes2-regex-header-5-atx
  "^\\(\\*\\*\\*\\*\\*\\)[ \t]+\\(.+?\\)[ \t]*\\(\\**\\)$"
  "Regular expression for level 5 atx-style (hash mark) headers.")

(defconst notes2-regex-header-6-atx
  "^\\(\\*\\*\\*\\*\\*\\*\\)[ \t]+\\(.+?\\)[ \t]*\\(\\**\\)$"
  "Regular expression for level 6 atx-style (hash mark) headers.")

(defconst notes2-regex-header-atx
  "^\\(\\*+\\)[ \t]*\\(.*?\\)[ \t]*\\(\\**\\)$"
  "Regular expression for generic atx-style (hash mark) headers.
  Equal to notes2-regex-header.")

(defconst notes2-regex-hr
  "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
  "Regular expression for matching Notes2 horizontal rules.")

(defconst notes2-regex-code
  "\\(\\\"\\|[^\\]\\)\\(\\(\"+\\)\\(\\(.\\|\n[^\n]\\)*?[^\"]\\)\\3\\)\\([^\"]\\|\\\"\\)"
  "Regular expression for matching inline code fragments.")

(defconst notes2-regex-highlight
  "\\(\\|\\|[^\\]\\)\\(\\(|+\\)\\(\\(.\\|\n[^\n]\\)*?[^|]\\)\\3\\)\\([^|]\\|\\|\\)"
  "Regular expression for matching highlighted fragments.")

(defconst notes2-regex-strikeout
  "\\(\\~\\|[^\\]\\)\\(\\(~+\\)\\(\\(.\\|\n[^\n]\\)*?[^~]\\)\\3\\)\\([^~]\\|\\~\\)"
  "Regular expression for matching strikeouts.")

(defconst notes2-regex-pre
  "^\\(    \\|\t\\).*$"
  "Regular expression for matching preformatted text sections.")

(defconst notes2-regex-list
  "^\\([ \t]*\\)\\([0-9]+\\.\\|[-]\\)\\([ \t]+\\)"
  "Regular expression for matching list items.")

(defconst notes2-regex-bold
  "\\(\\\\*\\|[^\\]\\)\\(\\(\\*+\\)\\(\\(.\\|\n[^\n]\\)*?[^\\*]\\)\\3\\)\\([^\\*]\\|\\\\*\\)"
  "Regular expression for matching bold text.
Group 1 matches the space or tab before the opening asterisk, if
any, ensuring it is at the start of a word.  Group 2 matches the
entire expression, including delimiters.  Groups 3 and 5 matches
the opening and closing delimiters.  Group 4 matches the text
inside the delimiters.  Group 6 matches the final character, if
any, to ensure it is at the end of a word.")

(defconst notes2-regex-important
  "^\\(->\\)[ \t]"
  "Regular expression for matching the important text '->'
  symbol.")

(defconst notes2-regex-update
  "^UPDATE[ \t]*([0-9/-]+):[ \t]+"
  "Regular expression for matching UPDATE notation.")

(defconst notes2-regex-todo
  "^TODO.*$"
  "Regular expression for matching TODO notation.")

(defconst notes2-regex-italic
  "\\(\\/\\|[^\\]\\)\\(\\(/+\\)\\(\\(.\\|\n[^\n]\\)*?[^/]\\)\\3\\)\\([^/]\\|\\/\\)"
  "Regular expression for matching italic text.")

(defconst notes2-regex-underline
  "\\(\\_\\|[^\\]\\)\\(\\(_+\\)\\(\\(.\\|\n[^\n]\\)*?[^_]\\)\\3\\)\\([^_]\\|\\_\\)"
  "Regular expression for matching underlined text.")

(defconst notes2-regex-blockquote
  "^[ \t]*\\(>\\).*$"
  "Regular expression for matching blockquote lines.")

(defconst notes2-regex-wiki-link
  "\\(?:^\\|[^\\]\\)\\(\\[\\[\\([^]|]+\\)\\(|\\([^]]+\\)\\)?\\]\\]\\)"
  "Regular expression for matching wiki links.
This matches typical bracketed [[WikiLinks]] as well as 'aliased'
wiki links of the form [[PageName|link text]].  In this regular
expression, group 1 matches the entire link, including square
brackets, group 2 matches the first component of the wiki link
and group 4 matches the second component, after the pipe, when
present.  The meanings of the first and second components depend
on the value of `notes2-wiki-link-alias-first'.")

(defconst notes2-regex-angle-image
  (concat "^\\(<\\)\\([^<\n][^>\n]*\\)\\(>\\)$")
  "Regular expression for matching inline URIs in angle brackets.")

(defconst notes2-regex-reference
  (concat "^\\(<<\\)\\([^<][^>]*\\)\\(>>\\)$")
  "Regular expression for matching inline URIs in angle brackets.")

(defconst notes2-regex-link-generic
  (concat "\\(?:" notes2-regex-link-inline
          ;"\\|" notes2-regex-wiki-link
          "\\|" notes2-regex-angle-image "\\)")
  "Regular expression for matching any recognized link.")

(defconst notes2-regex-block-separator
  "\\(\\`\\|\\(\n[ \t]*\n\\)[^\n \t]\\)"
  "Regular expression for matching block boundaries.")

(defconst notes2-regex-math-inline
  "\\(^\\|[^\\]\\)\\(\\$\\($\\$\\([^\\$]\\|\\\\.\\)*\\$\\$\\|\\([^\\$]\\|\\\\.\\)*\\)\\$\\)"
  "Regular expression for itex $..$ or $$$..$$$ math mode expressions.")

(defconst notes2-regex-code-block
  "^===>?\n\\(\\(.\\|\\\n\\)+?\\)<?===$"
  "Regular expression for itex $..$ or $$..$$ math mode expressions.")

(defconst notes2-regex-multinotes2-metadata
  "^[ \t]*\\([[:alpha:]][[:alpha:]_-]*?\\):[ \t]*\\(.*\\)$"
  "Regular expression for matching MultiNotes2 metadata.")

(defconst notes2-regex-multinotes2-metadata-end
  "^[ \t]*\\([[:alpha:]][[:alpha:]_-]*?\\):[ \t]*\\(.*\\)[ \n]*\\'"
  "Regular expression for matching MultiNotes2 metadata at the
  end of the document.")

(defvar notes2-mode-font-lock-keywords-basic
  (list
   (cons 'notes2-match-fenced-code-blocks '((0 notes2-pre-face)))
   ;(cons notes2-regex-code-block '((0 notes2-inline-code-face)))
   (cons notes2-regex-blockquote 'notes2-blockquote-face)
   ;(cons 'notes2-match-pre-blocks '((0 notes2-pre-face)))
   ;(cons 'notes2-match-code 'notes2-inline-code-face)
   (cons notes2-regex-code 'notes2-inline-code-face)
   (cons notes2-regex-highlight '(2 notes2-highlight-face))
   (cons notes2-regex-strikeout '(2 notes2-strikeout-face))
   (cons 'notes2-match-comments '((0 notes2-comment-face)))
   (cons notes2-regex-title 'notes2-title-face)
   (cons notes2-regex-math-inline '(2 notes2-math-face))
   (cons notes2-regex-header-6-atx '((1 notes2-header-delimiter-face)
                                       (2 notes2-header-face-6)
                                       (3 notes2-header-delimiter-face)))
   (cons notes2-regex-header-5-atx '((1 notes2-header-delimiter-face)
                                       (2 notes2-header-face-5)
                                       (3 notes2-header-delimiter-face)))
   (cons notes2-regex-header-4-atx '((1 notes2-header-delimiter-face)
                                       (2 notes2-header-face-4)
                                       (3 notes2-header-delimiter-face)))
   (cons notes2-regex-header-3-atx '((1 notes2-header-delimiter-face)
                                       (2 notes2-header-face-3)
                                       (3 notes2-header-delimiter-face)))
   (cons notes2-regex-header-2-atx '((1 notes2-header-delimiter-face)
                                       (2 notes2-header-face-2)
                                       (3 notes2-header-delimiter-face)))
   (cons notes2-regex-header-1-atx '((1 notes2-header-delimiter-face)
                                       (2 notes2-header-face-1)
                                       (3 notes2-header-delimiter-face)))
   (cons 'notes2-match-generic-metadata-front '((1 notes2-metadata-key-face)
                                                (2 notes2-metadata-value-face)))
   (cons notes2-regex-multinotes2-metadata-end '((1 notes2-metadata-key-face)
                                              (2 notes2-metadata-value-face)))
   (cons notes2-regex-hr 'notes2-header-face)
   (cons notes2-regex-angle-image 'notes2-link-face)
   (cons notes2-regex-reference 'notes2-reference-face)
   (cons notes2-regex-list '(2 notes2-list-face))
   (cons notes2-regex-link-inline '((2 notes2-url-face t)
                                      (4 notes2-link-face t)))
   (cons notes2-regex-update 'notes2-update-face)
   (cons notes2-regex-todo 'notes2-important-face)
   (cons notes2-regex-bold '(2 notes2-bold-face))
   (cons notes2-regex-italic '(2 notes2-italic-face))
   (cons notes2-regex-underline '(2 notes2-underline-face))
   (cons notes2-regex-important '((1 notes2-important-face t)))
   )
  "Syntax highlighting for Notes2 files.")

(defvar notes2-mode-font-lock-keywords nil
  "Default highlighting expressions for Notes2 mode.
This variable is defined as a buffer-local variable for dynamic
extension support.")


;;; Compatibility =============================================================

(defun notes2-replace-regexp-in-string (regexp rep string)
  "Replace ocurrences of REGEXP with REP in STRING.
This is a compatibility wrapper to provide `replace-regexp-in-string'
in XEmacs 21."
  (if (featurep 'xemacs)
      (replace-in-string string regexp rep)
    (replace-regexp-in-string regexp rep string)))

;; `notes2-use-region-p' is a compatibility function which checks
;; for an active region, with fallbacks for older Emacsen and XEmacs.
(eval-and-compile
  (cond
   ;; Emacs 23 and newer
   ((fboundp 'use-region-p)
    (defalias 'notes2-use-region-p 'use-region-p))
   ;; Older Emacsen
   ((and (boundp 'transient-mark-mode) (boundp 'mark-active))
    (defun notes2-use-region-p ()
      "Compatibility wrapper to provide `use-region-p'."
      (and transient-mark-mode mark-active)))
   ;; XEmacs
   ((fboundp 'region-active-p)
    (defalias 'notes2-use-region-p 'region-active-p))))

(defun notes2-use-buttons-p ()
  "Determine whether this Emacs supports buttons."
  (or (featurep 'button) (locate-library "button")))


;;; Notes2 Parsing Functions ================================================

(defun notes2-cur-line-blank-p ()
  "Return t if the current line is blank and nil otherwise."
  (save-excursion
    (beginning-of-line)
    (re-search-forward "^\\s *$" (line-end-position) t)))

(defun notes2-prev-line-blank-p ()
  "Return t if the previous line is blank and nil otherwise.
If we are at the first line, then consider the previous line to be blank."
  (or (= (line-beginning-position) (point-min))
      (save-excursion
        (forward-line -1)
        (notes2-cur-line-blank-p))))

(defun notes2-next-line-blank-p ()
  "Return t if the next line is blank and nil otherwise.
If we are at the last line, then consider the next line to be blank."
  (or (= (line-end-position) (point-max))
      (save-excursion
        (forward-line 1)
        (notes2-cur-line-blank-p))))

(defun notes2-prev-line-indent-p ()
  "Return t if the previous line is indented and nil otherwise."
  (save-excursion
    (forward-line -1)
    (goto-char (line-beginning-position))
    (if (re-search-forward "^\\s " (line-end-position) t) t)))

(defun notes2-cur-line-indent ()
  "Return the number of leading whitespace characters in the current line."
  (save-match-data
    (save-excursion
      (goto-char (line-beginning-position))
      (re-search-forward "^[ \t]+" (line-end-position) t)
      (current-column))))

(defun notes2-prev-line-indent ()
  "Return the number of leading whitespace characters in the previous line."
  (save-excursion
    (forward-line -1)
    (notes2-cur-line-indent)))

(defun notes2-next-line-indent ()
  "Return the number of leading whitespace characters in the next line."
  (save-excursion
    (forward-line 1)
    (notes2-cur-line-indent)))

(defun notes2-cur-non-list-indent ()
  "Return beginning position of list item text (not including the list marker).
Return nil if the current line is not the beginning of a list item."
  (save-match-data
    (save-excursion
      (beginning-of-line)
      (when (re-search-forward notes2-regex-list (line-end-position) t)
        (current-column)))))

(defun notes2-prev-non-list-indent ()
  "Return position of the first non-list-marker on the previous line."
  (save-excursion
    (forward-line -1)
    (notes2-cur-non-list-indent)))

(defun notes2-new-baseline-p ()
  "Determine if the current line begins a new baseline level."
  (save-excursion
    (beginning-of-line)
    (save-match-data
      (or (looking-at notes2-regex-header)
          (looking-at notes2-regex-hr)
          (and (null (notes2-cur-non-list-indent))
               (= (notes2-cur-line-indent) 0)
               (notes2-prev-line-blank-p))))))

(defun notes2-search-backward-baseline ()
  "Search backward baseline point with no indentation and not a list item."
  (end-of-line)
  (let (stop)
    (while (not (or stop (bobp)))
      (re-search-backward notes2-regex-block-separator nil t)
      (when (match-end 2)
        (goto-char (match-end 2))
        (cond
         ((notes2-new-baseline-p)
          (setq stop t))
         ((looking-at notes2-regex-list)
          (setq stop nil))
         (t (setq stop t)))))))

(defun notes2-update-list-levels (marker indent levels)
  "Update list levels given list MARKER, block INDENT, and current LEVELS.
Here, MARKER is a string representing the type of list, INDENT is an integer
giving the indentation, in spaces, of the current block, and LEVELS is a
list of the indentation levels of parent list items.  When LEVELS is nil,
it means we are at baseline (not inside of a nested list)."
  (cond
   ;; New list item at baseline.
   ((and marker (null levels))
    (setq levels (list indent)))
   ;; List item with greater indentation (four or more spaces).
   ;; Increase list level.
   ((and marker (>= indent (+ (car levels) 2)))
    (setq levels (cons indent levels)))
   ;; List item with greater or equal indentation (less than four spaces).
   ;; Do not increase list level.
   ((and marker (>= indent (car levels)))
    levels)
   ;; Lesser indentation level.
   ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
   ;; indentation could move back more than one list level).  Note
   ;; that this block need not be the beginning of list item.
   ((< indent (car levels))
    (while (and (> (length levels) 1)
                (< indent (+ (cadr levels) 2)))
      (setq levels (cdr levels)))
    levels)
   ;; Otherwise, do nothing.
   (t levels)))

(defun notes2-calculate-list-levels ()
  "Calculate list levels at point.
Return a list of the form (n1 n2 n3 ...) where n1 is the
indentation of the deepest nested list item in the branch of
the list at the point, n2 is the indentation of the parent
list item, and so on.  The depth of the list item is therefore
the length of the returned list.  If the point is not at or
immediately  after a list item, return nil."
  (save-excursion
    (let ((first (point)) levels indent pre-regexp)
      ;; Find a baseline point with zero list indentation
      (notes2-search-backward-baseline)
      ;; Search for all list items between baseline and LOC
      (while (and (< (point) first)
                  (re-search-forward notes2-regex-list first t))
        (setq pre-regexp (format "^\\(  \\|\t\\)\\{%d\\}" (1+ (length levels))))
        (beginning-of-line)
        (cond
         ;; Make sure this is not a header or hr
         ((notes2-new-baseline-p) (setq levels nil))
         ;; Make sure this is not a line from a pre block
         ((looking-at pre-regexp))
         ;; If not, then update levels
         (t
          (setq indent (notes2-cur-line-indent))
          (setq levels (notes2-update-list-levels (match-string 2)
                                                    indent levels))))
        (end-of-line))
      levels)))

(defun notes2-prev-list-item (level)
  "Search backward from point for a list item with indentation LEVEL.
Set point to the beginning of the item, and return point, or nil
upon failure."
  (let (bounds indent prev)
    (setq prev (point))
    (forward-line -1)
    (setq indent (notes2-cur-line-indent))
    (while
        (cond
         ;; Stop at beginning of buffer
         ((bobp) (setq prev nil))
         ;; Continue if current line is blank
         ((notes2-cur-line-blank-p) t)
         ;; List item
         ((and (looking-at notes2-regex-list)
               (setq bounds (notes2-cur-list-item-bounds)))
          (cond
           ;; Continue at item with greater indentation
           ((> (nth 3 bounds) level) t)
           ;; Stop and return point at item of equal indentation
           ((= (nth 3 bounds) level)
            (setq prev (point))
            nil)
           ;; Stop and return nil at item with lesser indentation
           ((< (nth 3 bounds) level)
            (setq prev nil)
            nil)))
         ;; Continue while indentation is the same or greater
         ((>= indent level) t)
         ;; Stop if current indentation is less than list item
         ;; and the next is blank
         ((and (< indent level)
               (notes2-next-line-blank-p))
          (setq prev nil))
         ;; Stop at a header
         ((looking-at notes2-regex-header) (setq prev nil))
         ;; Stop at a horizontal rule
         ((looking-at notes2-regex-hr) (setq prev nil))
         ;; Otherwise, continue.
         (t t))
      (forward-line -1)
      (setq indent (notes2-cur-line-indent)))
    prev))

(defun notes2-next-list-item (level)
  "Search forward from point for the next list item with indentation LEVEL.
Set point to the beginning of the item, and return point, or nil
upon failure."
  (let (bounds indent prev next)
    (setq next (point))
    (forward-line)
    (setq indent (notes2-cur-line-indent))
    (while
        (cond
         ;; Stop at end of the buffer.
         ((eobp) (setq prev nil))
         ;; Continue if the current line is blank
         ((notes2-cur-line-blank-p) t)
         ;; List item
         ((and (looking-at notes2-regex-list)
               (setq bounds (notes2-cur-list-item-bounds)))
          (cond
           ;; Continue at item with greater indentation
           ((> (nth 3 bounds) level) t)
           ;; Stop and return point at item of equal indentation
           ((= (nth 3 bounds) level)
            (setq next (point))
            nil)
           ;; Stop and return nil at item with lesser indentation
           ((< (nth 3 bounds) level)
            (setq next nil)
            nil)))
         ;; Continue while indentation is the same or greater
         ((>= indent level) t)
         ;; Stop if current indentation is less than list item
         ;; and the previous line was blank.
         ((and (< indent level)
               (notes2-prev-line-blank-p))
          (setq next nil))
         ;; Stop at a header
         ((looking-at notes2-regex-header) (setq next nil))
         ;; Stop at a horizontal rule
         ((looking-at notes2-regex-hr) (setq next nil))
         ;; Otherwise, continue.
         (t t))
      (forward-line)
      (setq indent (notes2-cur-line-indent)))
    next))

(defun notes2-cur-list-item-end (level)
  "Move to the end of the current list item with nonlist indentation LEVEL.
If the point is not in a list item, do nothing."
  (let (indent)
    (forward-line)
    (setq indent (notes2-cur-line-indent))
    (while
        (cond
         ;; Stop at end of the buffer.
         ((eobp) nil)
         ;; Continue if the current line is blank
         ((notes2-cur-line-blank-p) t)
         ;; Continue while indentation is the same or greater
         ((>= indent level) t)
         ;; Stop if current indentation is less than list item
         ;; and the previous line was blank.
         ((and (< indent level)
               (notes2-prev-line-blank-p))
          nil)
         ;; Stop at a new list item of the same or lesser indentation
         ((looking-at notes2-regex-list) nil)
         ;; Stop at a header
         ((looking-at notes2-regex-header) nil)
         ;; Stop at a horizontal rule
         ((looking-at notes2-regex-hr) nil)
         ;; Otherwise, continue.
         (t t))
      (forward-line)
      (setq indent (notes2-cur-line-indent)))
    ;; Don't skip over whitespace for empty list items (marker and
    ;; whitespace only), just move to end of whitespace.
    (if (looking-back (concat notes2-regex-list "\\s-*"))
          (goto-char (match-end 3))
      (skip-syntax-backward "-"))))

(defun notes2-cur-list-item-bounds ()
  "Return bounds and indentation of the current list item.
Return a list of the form (begin end indent nonlist-indent marker).
If the point is not inside a list item, return nil.
Leave match data intact for `notes2-regex-list'."
  (let (cur prev-begin prev-end indent nonlist-indent marker)
    ;; Store current location
    (setq cur (point))
    ;; Verify that cur is between beginning and end of item
    (save-excursion
      (end-of-line)
      (when (re-search-backward notes2-regex-list nil t)
        (setq prev-begin (match-beginning 0))
        (setq indent (length (match-string 1)))
        (setq nonlist-indent (length (match-string 0)))
        (setq marker (concat (match-string 2) (match-string 3)))
        (save-match-data
          (notes2-cur-list-item-end nonlist-indent)
          (setq prev-end (point)))
        (when (and (>= cur prev-begin)
                   (<= cur prev-end)
                   nonlist-indent)
          (list prev-begin prev-end indent nonlist-indent marker))))))

(defun notes2-bounds-of-thing-at-point (thing)
  "Call `bounds-of-thing-at-point' for THING with slight modifications.
Does not include trailing newlines when THING is 'line.  Handles the
end of buffer case by setting both endpoints equal to the value of
`point-max', since an empty region will trigger empty markup insertion.
Return bounds of form (beg . end) if THING is found, or nil otherwise."
  (let* ((bounds (bounds-of-thing-at-point thing))
         (a (car bounds))
         (b (cdr bounds)))
    (when bounds
      (when (eq thing 'line)
        (cond ((and (eobp) (notes2-cur-line-blank-p))
               (setq a b))
              ((char-equal (char-before b) ?\^J)
               (setq b (1- b)))))
      (cons a b))))

(defun notes2-code-at-point-p ()
  "Return non-nil if the point is at an inline code fragment.
Return nil otherwise.  Set match data according to
`notes2-match-code' upon success.
This function searches the block for a code fragment that
contains the point using `notes2-match-code'.  We do this
because `thing-at-point-looking-at' does not work reliably with
`notes2-regex-code'."
  (interactive)
  (save-excursion
    (let ((old-point (point))
          (end-of-block (progn (notes2-end-of-block) (point)))
          found)
      (notes2-beginning-of-block)
      (while (and (notes2-match-code end-of-block)
                  (setq found t)
                  (< (match-end 0) old-point)))
      (and found                              ; matched something
           (<= (match-beginning 0) old-point) ; match contains old-point
           (>= (match-end 0) old-point)))))


;;; Notes2 Font Lock Matching Functions =====================================

(defun notes2-match-comments (last)
  "Match C-style comments from the point to LAST."
  (cond ((search-forward "/*" last t)
         (backward-char 2)
         (let ((beg (point)))
           (cond ((search-forward "*/" last t)
                  (set-match-data (list beg (point)))
                  t)
                 (t nil))))
        (t nil)))

(defun notes2-match-code (last)
  "Match inline code from the point to LAST."
  (unless (bobp)
    (backward-char 1))
  (cond ((re-search-forward notes2-regex-code last t)
         (set-match-data (list (match-beginning 2) (match-end 2)
                               (match-beginning 4) (match-end 4)))
         (goto-char (match-end 0))
         t)
        (t (forward-char 2) nil)))

(defun notes2-match-pre-blocks (last)
  "Match Notes2 pre blocks from point to LAST."
  (let ((levels (notes2-calculate-list-levels))
        indent pre-regexp end-regexp begin end stop)
    (while (and (< (point) last) (not end))
      ;; Search for a region with sufficient indentation
      (if (null levels)
          (setq indent 1)
        (setq indent (1+ (length levels))))
      (setq pre-regexp (format "^\\(    \\|\t\\)\\{%d\\}" indent))
      (setq end-regexp (format "^\\(    \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))

      (cond
       ;; If not at the beginning of a line, move forward
       ((not (bolp)) (forward-line))
       ;; Move past blank lines
       ((notes2-cur-line-blank-p) (forward-line))
       ;; At headers and horizontal rules, reset levels
       ((notes2-new-baseline-p) (forward-line) (setq levels nil))
       ;; If the current line has sufficient indentation, mark out pre block
       ((looking-at pre-regexp)
        (setq begin (match-beginning 0))
        (while (and (or (looking-at pre-regexp) (notes2-cur-line-blank-p))
                    (not (eobp)))
          (forward-line))
        (setq end (point)))
       ;; If current line has a list marker, update levels, move to end of block
       ((looking-at notes2-regex-list)
        (setq levels (notes2-update-list-levels
                      (match-string 2) (notes2-cur-line-indent) levels))
        (notes2-end-of-block-element))
       ;; If this is the end of the indentation level, adjust levels accordingly.
       ;; Only match end of indentation level if levels is not the empty list.
       ((and (car levels) (looking-at end-regexp))
        (setq levels (notes2-update-list-levels
                      nil (notes2-cur-line-indent) levels))
        (notes2-end-of-block-element))
       (t (notes2-end-of-block-element))))

    (if (not (and begin end))
        ;; Return nil if no pre block was found
        nil
      ;; Set match data and return t upon success
      (set-match-data (list begin end))
      t)))

(defun notes2-match-fenced-code-blocks (last)
  "Match fenced code blocks from the point to LAST."
  (cond ((search-forward-regexp "^\\([=]\\{3,\\}\\)>?$" last t)
         (beginning-of-line)
         (let ((beg (point)))
           (forward-line)
           (cond ((search-forward-regexp
                   "^<?===$" last t)
                  (set-match-data (list beg (point)))
                  t)
                 (t nil))))
        (t nil)))

(defun notes2-match-generic-metadata-front (last)
  "Match generic metadata specified by REGEXP from the point to LAST."
  (let ((header-end (save-excursion
                      (goto-char (point-min))
                      (if (re-search-forward "\n\n" (point-max) t)
                          (match-beginning 0)
                        (point-max)))))
    (cond ((>= (point) header-end)
           ;; Don't match anything outside of the header.
           nil)
          ((re-search-forward notes2-regex-multinotes2-metadata (min last header-end) t)
           ;; If a metadata item is found, it may span several lines.
           (let ((key-beginning (match-beginning 1))
                 (key-end (match-end 1))
                 (value-beginning (match-beginning 2)))
             (while (and (not (looking-at notes2-regex-multinotes2-metadata))
                         (not (> (point) (min last header-end)))
                         (not (eobp)))
               (forward-line))
             (unless (eobp)
               (forward-line -1)
               (end-of-line))
             (set-match-data (list key-beginning (point) ; complete metadata
                                   key-beginning key-end ; key
                                   value-beginning (point))) ; value
           t))
          (t nil))))

(defun notes2-match-multinotes2-metadata (last)
  "Match MultiNotes2 metadata from the point to LAST."
  (notes2-match-generic-metadata notes2-regex-multinotes2-metadata last))

(defun notes2-font-lock-extend-region ()
  "Extend the search region to include an entire block of text.
This helps improve font locking for block constructs such as pre blocks."
  ;; Avoid compiler warnings about these global variables from font-lock.el.
  ;; See the documentation for variable `font-lock-extend-region-functions'.
  (eval-when-compile (defvar font-lock-beg) (defvar font-lock-end))
  (save-excursion
    (goto-char font-lock-beg)
    (unless (looking-back "\n\n")
      (let ((found (or (re-search-backward "\n\n" nil t) (point-min))) (oldbeg font-lock-beg) (oldend font-lock-end))
        (goto-char font-lock-end)
        (when (re-search-forward "\n\n" nil t)
          (setq font-lock-end (match-beginning 0))
          (setq font-lock-beg found)
          ; Take care of the case where this region contains part of a
          ; long code segment
          (goto-char font-lock-beg)
          (when (and (re-search-backward "\\([\n]\\|.\\)\\(\n<?===>?\n\\)\\([\n]\\|.\\)" nil t) 
                     (string= (match-string 1) "\n"))
            (setq font-lock-beg (match-beginning 2)))
          (goto-char font-lock-end)
          (when (and (re-search-forward "\\([\n]\\|.\\)\\(\n<?===>?\n\\)\\([\n]\\|.\\)" nil t)
                     (string= (match-string 3) "\n"))
            (setq font-lock-end (match-end 2)))
          ;; (when (and (re-search-backward "^\\(<?===>?\\)$" nil t) 
          ;;            (string= (match-string 0) "===>"))
          ;;   (setq font-lock-beg (match-beginning 0)))
          ;; (goto-char font-lock-end)
          ;; (when (and (re-search-forward "^\\(<?===>?\\)$" nil t)
          ;;            (string= (match-string 0) "<==="))
          ;;   (setq font-lock-end (match-end 0)))

          )
        (or (not (= oldend font-lock-end)) (not (= oldbeg font-lock-beg)))
        ))))


;;; Syntax Table ==============================================================

(defvar notes2-mode-syntax-table
  (let ((tab (make-syntax-table text-mode-syntax-table)))
    (modify-syntax-entry ?\" "." tab)
    tab)
  "Syntax table for `notes2-mode'.")


;;; Element Insertion =========================================================

(defun notes2-ensure-blank-line-before ()
  "If previous line is not already blank, insert a blank line before point."
  (unless (bolp) (insert "\n"))
  (unless (or (bobp) (looking-back "\n\\s-*\n")) (insert "\n")))

(defun notes2-ensure-blank-line-after ()
  "If following line is not already blank, insert a blank line after point.
Return the point where it was originally."
  (save-excursion
    (unless (eolp) (insert "\n"))
    (unless (or (eobp) (looking-at "\n\\s-*\n")) (insert "\n"))))

(defun notes2-wrap-or-insert (s1 s2 &optional thing beg end)
  "Insert the strings S1 and S2, wrapping around region or THING.
If a region is specified by the optional BEG and END arguments,
wrap the strings S1 and S2 around that region.
If there is an active region, wrap the strings S1 and S2 around
the region.  If there is not an active region but the point is at
THING, wrap that thing (which defaults to word).  Otherwise, just
insert S1 and S2 and place the cursor in between.  Return the
bounds of the entire wrapped string, or nil if nothing was wrapped
and S1 and S2 were only inserted."
  (let (a b bounds new-point)
    (cond
     ;; Given region
     ((and beg end)
      (setq a beg
            b end
            new-point (+ (point) (length s1))))
     ;; Active region
     ((notes2-use-region-p)
      (setq a (region-beginning)
            b (region-end)
            new-point (+ (point) (length s1))))
     ;; Thing (word) at point
     ((setq bounds (notes2-bounds-of-thing-at-point (or thing 'word)))
      (setq a (car bounds)
            b (cdr bounds)
            new-point (+ (point) (length s1))))
     ;; No active region and no word
     (t
      (setq a (point)
            b (point))))
    (goto-char b)
    (insert s2)
    (goto-char a)
    (insert s1)
    (when new-point (goto-char new-point))
    (if (= a b)
        nil
      (setq b (+ b (length s1) (length s2)))
      (cons a b))))

(defun notes2-point-after-unwrap (cur prefix suffix)
  "Return desired position of point after an unwrapping operation.
CUR gives the position of the point before the operation.
Additionally, two cons cells must be provided.  PREFIX gives the
bounds of the prefix string and SUFFIX gives the bounds of the
suffix string."
  (cond ((< cur (cdr prefix)) (car prefix))
        ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
        ((<= cur (cdr suffix))
         (- cur (+ (- (cdr prefix) (car prefix))
                   (- cur (car suffix)))))
        (t cur)))

(defun notes2-unwrap-thing-at-point (regexp all text)
  "Remove prefix and suffix of thing at point and reposition the point.
When the thing at point matches REGEXP, replace the subexpression
ALL with the string in subexpression TEXT.  Reposition the point
in an appropriate location accounting for the removal of prefix
and suffix strings.  Return new bounds of string from group TEXT.
When REGEXP is nil, assumes match data is already set."
  (when (or (null regexp)
            (thing-at-point-looking-at regexp))
    (let ((cur (point))
          (prefix (cons (match-beginning all) (match-beginning text)))
          (suffix (cons (match-end text) (match-end all)))
          (bounds (cons (match-beginning text) (match-end text))))
      ;; Replace the thing at point
      (replace-match (match-string text) t t nil all)
      ;; Reposition the point
      (goto-char (notes2-point-after-unwrap cur prefix suffix))
      ;; Adjust bounds
      (setq bounds (cons (car prefix)
                         (- (cdr bounds) (- (cdr prefix) (car prefix))))))))

(defun notes2-unwrap-things-in-region (beg end regexp all text)
  "Remove prefix and suffix of all things in region from BEG to END.
When a thing in the region matches REGEXP, replace the
subexpression ALL with the string in subexpression TEXT.
Return a cons cell containing updated bounds for the region."
  (save-excursion
    (goto-char beg)
    (let ((removed 0) len-all len-text)
      (while (re-search-forward regexp (- end removed) t)
        (setq len-all (length (match-string-no-properties all)))
        (setq len-text (length (match-string-no-properties text)))
        (setq removed (+ removed (- len-all len-text)))
        (replace-match (match-string text) t t nil all))
      (cons beg (- end removed)))))

(defun notes2-insert-hr (arg)
  "Insert or replace a horizonal rule.
By default, use the first element of `notes2-hr-strings'.  When
ARG is non-nil, as when given a prefix, select a different
element as follows.  When prefixed with \\[universal-argument],
use the last element of `notes2-hr-strings' instead.  When
prefixed with an integer from 1 to the length of
`notes2-hr-strings', use the element in that position instead."
  (interactive "*P")
  (when (thing-at-point-looking-at notes2-regex-hr)
    (delete-region (match-beginning 0) (match-end 0)))
  (notes2-ensure-blank-line-before)
  (cond ((equal arg '(4))
         (insert (car (reverse notes2-hr-strings))))
        ((and (integerp arg) (> arg 0)
              (<= arg (length notes2-hr-strings)))
         (insert (nth (1- arg) notes2-hr-strings)))
        (t
         (insert (car notes2-hr-strings))))
  (notes2-ensure-blank-line-after))

(defun notes2-insert-bold ()
  "Insert markup to make a region or word bold.
If there is an active region, make the region bold.  If the point
is at a non-bold word, make the word bold.  If the point is at a
bold word or phrase, remove the bold markup.  Otherwise, simply
insert bold delimiters and place the cursor in between them."
  (interactive)
  (let ((delim (if notes2-bold-underscore "__" "**")))
    (if (notes2-use-region-p)
        ;; Active region
        (let ((bounds (notes2-unwrap-things-in-region
                       (region-beginning) (region-end)
                       notes2-regex-bold 2 4)))
          (notes2-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
      ;; Bold markup removal, bold word at point, or empty markup insertion
      (if (thing-at-point-looking-at notes2-regex-bold)
          (notes2-unwrap-thing-at-point nil 2 4)
        (notes2-wrap-or-insert delim delim 'word nil nil)))))

(defun notes2-insert-italic ()
  "Insert markup to make a region or word italic.
If there is an active region, make the region italic.  If the point
is at a non-italic word, make the word italic.  If the point is at an
italic word or phrase, remove the italic markup.  Otherwise, simply
insert italic delimiters and place the cursor in between them."
  (interactive)
  (let ((delim (if notes2-italic-underscore "_" "*")))
    (if (notes2-use-region-p)
        ;; Active region
        (let ((bounds (notes2-unwrap-things-in-region
                       (region-beginning) (region-end)
                       notes2-regex-italic 2 4)))
          (notes2-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
      ;; Italic markup removal, italic word at point, or empty markup insertion
      (if (thing-at-point-looking-at notes2-regex-italic)
          (notes2-unwrap-thing-at-point nil 2 4)
        (notes2-wrap-or-insert delim delim 'word nil nil)))))

(defun notes2-insert-code ()
  "Insert markup to make a region or word an inline code fragment.
If there is an active region, make the region an inline code
fragment.  If the point is at a word, make the word an inline
code fragment.  Otherwise, simply insert code delimiters and
place the cursor in between them."
  (interactive)
  (if (notes2-use-region-p)
      ;; Active region
      (let ((bounds (notes2-unwrap-things-in-region
                     (region-beginning) (region-end)
                     notes2-regex-code 2 4)))
        (notes2-wrap-or-insert "\"" "\"" nil (car bounds) (cdr bounds)))
    ;; Code markup removal, code markup for word, or empty markup insertion
    (if (notes2-code-at-point-p)
        (notes2-unwrap-thing-at-point nil 0 1)
      (notes2-wrap-or-insert "\"" "\"" 'word nil nil))))

(defun notes2-insert-link ()
  "Insert an inline link, using region or word as link text if possible.
If there is an active region, use the region as the link text.  If the
point is at a word, use the word as the link text.  In these cases, the
point will be left at the position for inserting a URL.  If there is no
active region and the point is not at word, simply insert link markup and
place the point in the position to enter link text."
  (interactive)
  (let ((bounds (notes2-wrap-or-insert "[" "]()")))
    (when bounds
      (goto-char (- (cdr bounds) 1)))))

(defun notes2-insert-uri ()
  "Insert markup for an inline URI.
If there is an active region, use it as the URI.  If the point is
at a URI, wrap it with angle brackets.  If the point is at an
inline URI, remove the angle brackets.  Otherwise, simply insert
angle brackets place the point between them."
  (interactive)
  (if (notes2-use-region-p)
      ;; Active region
      (let ((bounds (notes2-unwrap-things-in-region
                     (region-beginning) (region-end)
                     notes2-regex-angle-image 0 2)))
        (notes2-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
    ;; Markup removal, URI at point, or empty markup insertion
    (if (thing-at-point-looking-at notes2-regex-angle-image)
        (notes2-unwrap-thing-at-point nil 0 2)
      (notes2-wrap-or-insert "<" ">" 'url nil nil))))

(defun notes2-insert-wiki-link ()
  "Insert a wiki link of the form [[WikiLink]].
If there is an active region, use the region as the link text.
If the point is at a word, use the word as the link text.  If
there is no active region and the point is not at word, simply
insert link markup."
  (interactive)
  (if (notes2-use-region-p)
      ;; Active region
      (notes2-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
    ;; Markup removal, wiki link at at point, or empty markup insertion
    (if (thing-at-point-looking-at notes2-regex-wiki-link)
        (if (or notes2-wiki-link-alias-first
                (null (match-string 4)))
            (notes2-unwrap-thing-at-point nil 1 2)
          (notes2-unwrap-thing-at-point nil 1 4))
      (notes2-wrap-or-insert "[[" "]]"))))

(defun notes2-insert-image (&optional arg)
  "Insert image markup using region or word as alt text if possible.
If there is an active region, use the region as the alt text.  If the
point is at a word, use the word as the alt text.  In these cases, the
point will be left at the position for inserting a URL.  If there is no
active region and the point is not at word, simply insert image markup and
place the point in the position to enter alt text.  If ARG is nil, insert
inline image markup.  Otherwise, insert reference image markup."
  (interactive "*P")
  (let ((bounds (if arg
                    (notes2-wrap-or-insert "![" "][]")
                  (notes2-wrap-or-insert "![" "]()"))))
    (when bounds
      (goto-char (- (cdr bounds) 1)))))

(defun notes2-remove-header ()
  "Remove header markup if point is at a header.
Return bounds of remaining header text if a header was removed
and nil otherwise."
  (interactive "*")
  (notes2-unwrap-thing-at-point notes2-regex-header-atx 0 2))

(defun notes2-insert-header (&optional level text setext)
  "Insert or replace header markup.
The level of the header is specified by LEVEL and header text is
given by TEXT.  LEVEL must be an integer from 1 and 6, and the
default value is 1.
When TEXT is nil, the header text is obtained as follows.
If there is an active region, it is used as the header text.
Otherwise, the current line will be used as the header text.
If there is not an active region and the point is at a header,
remove the header markup and replace with level N header.
Otherwise, insert empty header markup and place the cursor in
between.
The style of the header will be atx (hash marks) unless
SETEXT is non-nil, in which case a setext-style (underlined)
header will be inserted."
  (interactive "p\nsHeader text: ")
  (setq level (min (max (or level 1) 1) (if setext 2 6)))
  ;; Determine header text if not given
  (when (null text)
    (if (notes2-use-region-p)
        ;; Active region
        (setq text (delete-and-extract-region (region-beginning) (region-end)))
      ;; No active region
      (notes2-remove-header)
      (setq text (delete-and-extract-region
                  (line-beginning-position) (line-end-position)))
      (when (and setext (string-match "^[ \t]*$" text))
        (setq text (read-string "Header text: "))))
    (setq text (notes2-compress-whitespace-string text)))
  ;; Insertion with given text
  (notes2-ensure-blank-line-before)
  (let (hdr)
    (setq hdr (make-string level ?#))
    (insert hdr " " text " " hdr))
  (notes2-ensure-blank-line-after))

(defun notes2-insert-header-dwim (&optional arg setext)
  "Insert or replace header markup.
The level and type of the header are determined automatically by
the type and level of the previous header, unless a prefix
argument is given via ARG.
With a numeric prefix valued 1 to 6, insert a header of the given
level, with the type being determined automatically (note that
only level 1 or 2 setext headers are possible).

With a \\[universal-argument] prefix (i.e., when ARG is (4)),
promote the heading by one level.
With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
demote the heading by one level.
When SETEXT is non-nil, prefer setext-style headers when
possible (levels one and two).

When there is an active region, use it for the header text.  When
the point is at an existing header, change the type and level
according to the rules above.
Otherwise, if the line is not empty, create a header using the
text on the current line as the header text.
Finally, if the point is on a blank line, insert empty header
markup (atx) or prompt for text (setext).
See `notes2-insert-header' for more details about how the
header text is determined."
  (interactive "*P")
  (let (level)
    (save-excursion
      (when (re-search-backward notes2-regex-header nil t)
        ;; level of previous header
        (setq level (notes2-outline-level))
        ;; match groups 1 and 2 indicate setext headers
        (setq setext (or setext (match-end 1) (match-end 3)))))
    ;; check prefix argument
    (cond
     ((and (equal arg '(4)) (> level 1)) ;; C-u
      (decf level))
     ((and (equal arg '(16)) (< level 6)) ;; C-u C-u
      (incf level))
     (arg ;; numeric prefix
      (setq level (prefix-numeric-value arg))))
    ;; setext headers must be level one or two
    (and level (setq setext (and setext (<= level 2))))
    ;; insert the heading
    (notes2-insert-header level nil setext)))

(defun notes2-insert-header-atx-1 ()
  "Insert a first level atx-style (hash mark) header.
See `notes2-insert-header'."
  (interactive "*")
  (notes2-insert-header 1 nil nil))

(defun notes2-insert-header-atx-2 ()
  "Insert a level two atx-style (hash mark) header.
See `notes2-insert-header'."
  (interactive "*")
  (notes2-insert-header 2 nil nil))

(defun notes2-insert-header-atx-3 ()
  "Insert a level three atx-style (hash mark) header.
See `notes2-insert-header'."
  (interactive "*")
  (notes2-insert-header 3 nil nil))

(defun notes2-insert-header-atx-4 ()
  "Insert a level four atx-style (hash mark) header.
See `notes2-insert-header'."
  (interactive "*")
  (notes2-insert-header 4 nil nil))

(defun notes2-insert-header-atx-5 ()
  "Insert a level five atx-style (hash mark) header.
See `notes2-insert-header'."
  (interactive "*")
  (notes2-insert-header 5 nil nil))

(defun notes2-insert-header-atx-6 ()
  "Insert a sixth level atx-style (hash mark) header.
See `notes2-insert-header'."
  (interactive "*")
  (notes2-insert-header 6 nil nil))

(defun notes2-blockquote-indentation (loc)
  "Return string containing necessary indentation for a blockquote at LOC.
Also see `notes2-pre-indentation'."
  (save-excursion
    (goto-char loc)
    (let* ((list-level (length (notes2-calculate-list-levels)))
           (indent ""))
      (dotimes (count list-level indent)
        (setq indent (concat indent "    "))))))

(defun notes2-insert-blockquote ()
  "Start a blockquote section (or blockquote the region).
If Transient Mark mode is on and a region is active, it is used as
the blockquote text."
  (interactive)
  (if (notes2-use-region-p)
      (notes2-blockquote-region (region-beginning) (region-end))
    (notes2-ensure-blank-line-before)
    (insert (notes2-blockquote-indentation (point)) "> ")
    (notes2-ensure-blank-line-after)))

(defun notes2-block-region (beg end prefix)
  "Format the region using a block prefix.
Arguments BEG and END specify the beginning and end of the
region.  The characters PREFIX will appear at the beginning
of each line."
  (save-excursion
    (let* ((end-marker (make-marker))
           (beg-marker (make-marker)))
      ;; Ensure blank line after and remove extra whitespace
      (goto-char end)
      (skip-syntax-backward "-")
      (set-marker end-marker (point))
      (delete-horizontal-space)
      (notes2-ensure-blank-line-after)
      ;; Ensure blank line before and remove extra whitespace
      (goto-char beg)
      (skip-syntax-forward "-")
      (delete-horizontal-space)
      (notes2-ensure-blank-line-before)
      (set-marker beg-marker (point))
      ;; Insert PREFIX before each line
      (goto-char beg-marker)
      (while (and (< (line-beginning-position) end-marker)
                  (not (eobp)))
        (insert prefix)
        (forward-line)))))

(defun notes2-blockquote-region (beg end)
  "Blockquote the region.
Arguments BEG and END specify the beginning and end of the region."
  (interactive "*r")
  (notes2-block-region
   beg end (concat (notes2-blockquote-indentation
                    (max (point-min) (1- beg))) "> ")))

(defun notes2-pre-indentation (loc)
  "Return string containing necessary whitespace for a pre block at LOC.
Also see `notes2-blockquote-indentation'."
  (save-excursion
    (goto-char loc)
    (let* ((list-level (length (notes2-calculate-list-levels)))
           indent)
      (dotimes (count (1+ list-level) indent)
        (setq indent (concat indent "    "))))))

(defun notes2-insert-pre ()
  "Start a preformatted section (or apply to the region).
If Transient Mark mode is on and a region is active, it is marked
as preformatted text."
  (interactive)
  (if (notes2-use-region-p)
      (notes2-pre-region (region-beginning) (region-end))
    (notes2-ensure-blank-line-before)
    (insert (notes2-pre-indentation (point)))
    (notes2-ensure-blank-line-after)))

(defun notes2-pre-region (beg end)
  "Format the region as preformatted text.
Arguments BEG and END specify the beginning and end of the region."
  (interactive "*r")
  (let ((indent (notes2-pre-indentation (max (point-min) (1- beg)))))
    (notes2-block-region beg end indent)))



;;; Element Removal ===========================================================

(defun notes2-kill-thing-at-point ()
  "Kill thing at point and add important text, without markup, to kill ring.
Possible things to kill include (roughly in order of precedence):
inline code, headers, horizonal rules, links (add link text to
kill ring), images (add alt text to kill ring), angle uri, email
addresses, bold, italics, reference definition (add URI to kill
ring), footnote markers and text (kill both marker and text, add
text to kill ring), and list items."
  (interactive "*")
  (let (val tmp)
    (cond
     ;; Inline code
     ((notes2-code-at-point-p)
      (kill-new (match-string 1))
      (delete-region (match-beginning 0) (match-end 0)))
     ;; ATX header
     ((thing-at-point-looking-at notes2-regex-header-atx)
      (kill-new (match-string 2))
      (delete-region (match-beginning 0) (match-end 0)))
     ;; Horizonal rule
     ((thing-at-point-looking-at notes2-regex-hr)
      (kill-new (match-string 0))
      (delete-region (match-beginning 0) (match-end 0)))
     ;; Inline link or image (add link or alt text to kill ring)
     ((thing-at-point-looking-at notes2-regex-link-inline)
      (kill-new (match-string 4))
      (delete-region (match-beginning 0) (match-end 0)))
     ;; Angle image (add URL to kill ring)
     ((thing-at-point-looking-at notes2-regex-angle-image)
      (kill-new (match-string 2))
      (delete-region (match-beginning 0) (match-end 0)))
     ;; Wiki link (add alias text to kill ring)
     ;((thing-at-point-looking-at notes2-regex-wiki-link)
     ; (kill-new (notes2-wiki-link-alias))
     ; (delete-region (match-beginning 1) (match-end 1)))
     ;; Bold
     ((thing-at-point-looking-at notes2-regex-bold)
      (kill-new (match-string 4))
      (delete-region (match-beginning 2) (match-end 2)))
     ;; Italics
     ((thing-at-point-looking-at notes2-regex-italic)
      (kill-new (match-string 4))
      (delete-region (match-beginning 2) (match-end 2)))
     ;; List item
     ((setq val (notes2-cur-list-item-bounds))
      (kill-new (delete-and-extract-region (first val) (second val))))
     (t
      (error "Nothing found at point to kill")))))


;;; Indentation ====================================================================

(defun notes2-indent-find-next-position (cur-pos positions)
  "Return the position after the index of CUR-POS in POSITIONS.
Positions are calculated by `notes2-calc-indents'."
  (while (and positions
              (not (equal cur-pos (car positions))))
    (setq positions (cdr positions)))
  (or (cadr positions) 0))

(defun notes2-exdent-find-next-position (cur-pos positions)
  "Return the maximal element that precedes CUR-POS from POSITIONS.
Positions are calculated by `notes2-calc-indents'."
  (let ((result 0))
    (dolist (i positions)
      (when (< i cur-pos)
        (setq result (max result i))))
    result))

(defun notes2-indent-line ()
  "Indent the current line using some heuristics.
If the _previous_ command was either `notes2-enter-key' or
`notes2-cycle', then we should cycle to the next
reasonable indentation position.  Otherwise, we could have been
called directly by `notes2-enter-key', by an initial call of
`notes2-cycle', or indirectly by `auto-fill-mode'.  In
these cases, indent to the default position.
Positions are calculated by `notes2-calc-indents'."
  (interactive)
  (let ((positions (notes2-calc-indents))
        (cur-pos (current-column)))
    (if (not (equal this-command 'notes2-cycle))
        (indent-line-to (car positions))
      (setq positions (sort (delete-dups positions) '<))
      (indent-line-to
       (notes2-indent-find-next-position cur-pos positions)))))

(defun notes2-calc-indents ()
  "Return a list of indentation columns to cycle through.
The first element in the returned list should be considered the
default indentation level.  This function does not worry about
duplicate positions, which are handled up by calling functions."
  (let (pos prev-line-pos positions)

    ;; Indentation of previous line
    (setq prev-line-pos (notes2-prev-line-indent))
    (setq positions (cons prev-line-pos positions))

    ;; Indentation of previous non-list-marker text
    (when (setq pos (notes2-prev-non-list-indent))
      (setq positions (cons pos positions)))

    ;; Indentation required for a pre block in current context
    (setq pos (length (notes2-pre-indentation (point))))
    (setq positions (cons pos positions))

    ;; Indentation of the previous line + tab-width
    (if prev-line-pos
        (setq positions (cons (+ prev-line-pos tab-width) positions))
      (setq positions (cons tab-width positions)))

    ;; Indentation of the previous line - tab-width
    (if (and prev-line-pos (> prev-line-pos tab-width))
        (setq positions (cons (- prev-line-pos tab-width) positions)))

    ;; Indentation of all preceeding list markers (when in a list)
    (when (setq pos (notes2-calculate-list-levels))
      (setq positions (append pos positions)))

    ;; First column
    (setq positions (cons 0 positions))

    ;; Return reversed list
    (reverse positions)))

(defun notes2-enter-key ()
  "Handle RET according to to the value of `notes2-indent-on-enter'."
  (interactive)
  (if notes2-indent-on-enter
      (newline-and-indent)
    (newline)))

(defun notes2-exdent-or-delete (arg)
  "Handle BACKSPACE by cycling through indentation points.
When BACKSPACE is pressed, if there is only whitespace
before the current point, then exdent the line one level.
Otherwise, do normal delete by repeating
`backward-delete-char-untabify' ARG times."
  (interactive "*p")
  (let ((cur-pos (current-column))
        (start-of-indention (save-excursion
                              (back-to-indentation)
                              (current-column)))
        (positions (notes2-calc-indents)))
    (if (and (> cur-pos 0) (= cur-pos start-of-indention))
        (indent-line-to (notes2-exdent-find-next-position cur-pos positions))
      (backward-delete-char-untabify arg))))

(defun notes2-find-leftmost-column (beg end)
  "Find the leftmost column in the region from BEG to END."
  (let ((mincol 1000))
    (save-excursion
      (goto-char beg)
      (while (< (point) end)
        (back-to-indentation)
        (unless (looking-at "[ \t]*$")
	  (setq mincol (min mincol (current-column))))
        (forward-line 1)
        ))
    mincol))

(defun notes2-indent-region (beg end arg)
  "Indent the region from BEG to END using some heuristics.
When ARG is non-nil, exdent the region instead.
See `notes2-indent-line' and `notes2-indent-line'."
  (interactive "*r\nP")
  (let* ((positions (sort (delete-dups (notes2-calc-indents)) '<))
         (leftmostcol (notes2-find-leftmost-column beg end))
         (next-pos (if arg
                       (notes2-exdent-find-next-position leftmostcol positions)
                     (notes2-indent-find-next-position leftmostcol positions))))
    (indent-rigidly beg end (- next-pos leftmostcol))
    (setq deactivate-mark nil)))

(defun notes2-exdent-region (beg end)
  "Call `notes2-indent-region' on region from BEG to END with prefix."
  (interactive "*r")
  (notes2-indent-region (region-beginning) (region-end) t))


;;; Markup Completion =========================================================

(defconst notes2-complete-alist
  '((notes2-regex-header-atx . notes2-complete-atx)
    (notes2-regex-hr . notes2-complete-hr))
  "Association list of form (regexp . function) for markup completion.")

(defun notes2-incomplete-atx-p ()
  "Return t if ATX header markup is incomplete and nil otherwise.
Assumes match data is available for `notes2-regex-header-atx'.
Checks that the number of trailing hash marks equals the number of leading
hash marks, that there is only a single space before and after the text,
and that there is no extraneous whitespace in the text."
  (save-match-data
    (or
     ;; Number of starting and ending hash marks differs
     (not (= (length (match-string 1)) (length (match-string 3))))
     ;; When the header text is not empty...
     (and (> (length (match-string 2)) 0)
          ;; ...if there are extra leading, trailing, or interior spaces
          (or (not (= (match-beginning 2) (1+ (match-end 1))))
              (not (= (match-beginning 3) (1+ (match-end 2))))
              (string-match "[ \t\n]\\{2\\}" (match-string 2))))
     ;; When the header text is empty...
     (and (= (length (match-string 2)) 0)
          ;; ...if there are too many or too few spaces
          (not (= (match-beginning 3) (+ (match-end 1) 2)))))))

(defun notes2-complete-atx ()
  "Complete and normalize ATX headers.
Add or remove hash marks to the end of the header to match the
beginning.  Ensure that there is only a single space between hash
marks and header text.  Removes extraneous whitespace from header text.
Assumes match data is available for `notes2-regex-header-atx'.
Return nil if markup was complete and non-nil if markup was completed."
  (when (notes2-incomplete-atx-p)
    (let* ((new-marker (make-marker))
           (new-marker (set-marker new-marker (match-end 2))))
      ;; Hash marks and spacing at end
      (goto-char (match-end 2))
      (delete-region (match-end 2) (match-end 3))
      (insert " " (match-string 1))
      ;; Remove extraneous whitespace from title
      (replace-match (notes2-compress-whitespace-string (match-string 2))
                     t t nil 2)
      ;; Spacing at beginning
      (goto-char (match-end 1))
      (delete-region (match-end 1) (match-beginning 2))
      (insert " ")
      ;; Leave point at end of text
      (goto-char new-marker))))

(defun notes2-incomplete-hr-p ()
  "Return non-nil if hr is not in `notes2-hr-strings' and nil otherwise.
Assumes match data is available for `notes2-regex-hr'."
  (not (member (match-string 0) notes2-hr-strings)))

(defun notes2-complete-hr ()
  "Complete horizontal rules.
If horizontal rule string is a member of `notes2-hr-strings',
do nothing.  Otherwise, replace with the car of
`notes2-hr-strings'.
Assumes match data is available for `notes2-regex-hr'.
Return nil if markup was complete and non-nil if markup was completed."
  (when (notes2-incomplete-hr-p)
    (replace-match (car notes2-hr-strings))
    t))

(defun notes2-complete ()
  "Complete markup of object near point or in region when active.
Handle all objects in `notes2-complete-alist', in order.
See `notes2-complete-at-point' and `notes2-complete-region'."
  (interactive "*")
  (if (notes2-use-region-p)
      (notes2-complete-region (region-beginning) (region-end))
    (notes2-complete-at-point)))

(defun notes2-complete-at-point ()
  "Complete markup of object near point.
Handle all elements of `notes2-complete-alist' in order."
  (interactive "*")
  (let ((list notes2-complete-alist) found changed)
    (while list
      (let ((regexp (eval (caar list)))
            (function (cdar list)))
        (setq list (cdr list))
        (when (thing-at-point-looking-at regexp)
          (setq found t)
          (setq changed (funcall function))
          (setq list nil))))
    (if found
        (or changed (error "Markup at point is complete"))
      (error "Nothing to complete at point"))))

(defun notes2-complete-region (beg end)
  "Complete markup of objects in region from BEG to END.
Handle all objects in `notes2-complete-alist', in
order."
  (interactive "*r")
  (let ((end-marker (set-marker (make-marker) end)))
    (dolist (element notes2-complete-alist)
      (let ((regexp (eval (car element)))
            (function (cdr element)))
        (goto-char beg)
        (while (re-search-forward regexp end-marker 'limit)
          (save-excursion (funcall function)))))))

(defun notes2-complete-buffer ()
  "Complete markup for all objects in the current buffer."
  (interactive "*")
  (notes2-complete-region (point-min) (point-max)))


;;; Markup Cycling ============================================================

(defun notes2-cycle-atx (arg &optional remove)
  "Cycle ATX header markup.
Promote header (decrease level) when ARG is 1 and demote
header (increase level) if arg is -1.  When REMOVE is non-nil,
remove the header when the level reaches zero and stop cycling
when it reaches six.  Otherwise, perform a proper cycling through
levels one through six.  Assumes match data is available for
`notes2-regex-header-atx'."
  (let* ((old-level (length (match-string 1)))
         (new-level (+ old-level arg))
         (text (match-string 2)))
    (when (not remove)
      (setq new-level (% new-level 6))
      (setq new-level (cond ((= new-level 0) 6)
                            ((< new-level 0) (+ new-level 6))
                            (t new-level))))
    (cond
     ((= new-level 0)
      (notes2-unwrap-thing-at-point nil 0 2))
     ((<= new-level 6)
      (goto-char (match-beginning 0))
      (delete-region (match-beginning 0) (match-end 0))
      (notes2-insert-header new-level text nil)))))

(defun notes2-cycle-hr (arg &optional remove)
  "Cycle string used for horizontal rule from `notes2-hr-strings'.
When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
backwards (promote).  When REMOVE is non-nil, remove the hr instead
of cycling when the end of the list is reached.
Assumes match data is available for `notes2-regex-hr'."
  (let* ((strings (if (= arg -1)
                      (reverse notes2-hr-strings)
                    notes2-hr-strings))
         (tail (member (match-string 0) strings))
         (new (or (cadr tail)
                  (if remove
                      (if (= arg 1)
                          ""
                        (car tail))
                    (car strings)))))
    (replace-match new)))

(defun notes2-cycle-bold ()
  "Cycle bold markup between underscores and asterisks.
Assumes match data is available for `notes2-regex-bold'."
  (save-excursion
    (let* ((old-delim (match-string 3))
           (new-delim (if (string-equal old-delim "**") "__" "**")))
      (replace-match new-delim t t nil 3)
      (replace-match new-delim t t nil 5))))

(defun notes2-cycle-italic ()
  "Cycle italic markup between underscores and asterisks.
Assumes match data is available for `notes2-regex-italic'."
  (save-excursion
    (let* ((old-delim (match-string 3))
           (new-delim (if (string-equal old-delim "*") "_" "*")))
      (replace-match new-delim t t nil 3)
      (replace-match new-delim t t nil 5))))


;;; Keymap ====================================================================

(defvar notes2-mode-map
  (let ((map (make-keymap)))
    ;; Element insertion
    (define-key map "\C-c\C-al" 'notes2-insert-link)
    (define-key map "\C-c\C-au" 'notes2-insert-uri)
    ;(define-key map "\C-c\C-aw" 'notes2-insert-wiki-link)
    (define-key map "\C-c\C-ii" 'notes2-insert-image)
    (define-key map "\C-c\C-th" 'notes2-insert-header-dwim)
    (define-key map "\C-c\C-t1" 'notes2-insert-header-atx-1)
    (define-key map "\C-c\C-t2" 'notes2-insert-header-atx-2)
    (define-key map "\C-c\C-t3" 'notes2-insert-header-atx-3)
    (define-key map "\C-c\C-t4" 'notes2-insert-header-atx-4)
    (define-key map "\C-c\C-t5" 'notes2-insert-header-atx-5)
    (define-key map "\C-c\C-t6" 'notes2-insert-header-atx-6)
    (define-key map "\C-c\C-ss" 'notes2-insert-bold)
    (define-key map "\C-c\C-se" 'notes2-insert-italic)
    (define-key map "\C-c\C-sc" 'notes2-insert-code)
    (define-key map "\C-c\C-sb" 'notes2-insert-blockquote)
    (define-key map "\C-c\C-s\C-b" 'notes2-blockquote-region)
    (define-key map "\C-c\C-sp" 'notes2-insert-pre)
    (define-key map "\C-c\C-s\C-p" 'notes2-pre-region)
    (define-key map "\C-c-" 'notes2-insert-hr)
    ;; Element removal
    (define-key map (kbd "C-c C-k") 'notes2-kill-thing-at-point)
    ;; Promotion, Demotion, Completion, and Cycling
    (define-key map (kbd "C-c C--") 'notes2-promote)
    (define-key map (kbd "C-c C-=") 'notes2-demote)
    (define-key map (kbd "C-c C-]") 'notes2-complete)
    ;; Following and Jumping
    (define-key map (kbd "C-c C-o") 'notes2-follow-thing-at-point)
    ;; Indentation
    (define-key map (kbd "C-m") 'notes2-enter-key)
    (define-key map (kbd "<backspace>") 'notes2-exdent-or-delete)
    (define-key map (kbd "C-c >") 'notes2-indent-region)
    (define-key map (kbd "C-c <") 'notes2-exdent-region)
    ;; Visibility cycling
    (define-key map (kbd "<tab>") 'notes2-cycle)
    (define-key map (kbd "<S-iso-lefttab>") 'notes2-shifttab)
    (define-key map (kbd "<S-tab>")  'notes2-shifttab)
    (define-key map (kbd "<backtab>") 'notes2-shifttab)
    ;; Header navigation
    (define-key map (kbd "C-c C-n") 'outline-next-visible-heading)
    (define-key map (kbd "C-c C-p") 'outline-previous-visible-heading)
    (define-key map (kbd "C-c C-f") 'outline-forward-same-level)
    (define-key map (kbd "C-c C-b") 'outline-backward-same-level)
    (define-key map (kbd "C-c C-u") 'outline-up-heading)
    ;; Buffer-wide commands
    (define-key map (kbd "C-c C-c") 'notes2-compile)
    (define-key map (kbd "C-c C-v") 'notes2-view)
    (define-key map (kbd "C-c C-e") 'notes2-extract-code)
    (define-key map (kbd "C-c C-l") 'notes2-latexify-notes)
    ;; List editing
    (define-key map (kbd "M-<up>") 'notes2-move-up)
    (define-key map (kbd "M-<down>") 'notes2-move-down)
    (define-key map (kbd "M-<left>") 'notes2-promote)
    (define-key map (kbd "M-<right>") 'notes2-demote)
    (define-key map (kbd "M-<return>") 'notes2-insert-list-item)
    ;; Movement
    (define-key map (kbd "M-{") 'notes2-backward-paragraph)
    (define-key map (kbd "M-}") 'notes2-forward-paragraph)
    (define-key map (kbd "M-n") 'notes2-next-link)
    (define-key map (kbd "M-p") 'notes2-previous-link)
    ;; Alternative keys (in case of problems with the arrow keys)
    (define-key map (kbd "C-c C-x u") 'notes2-move-up)
    (define-key map (kbd "C-c C-x d") 'notes2-move-down)
    (define-key map (kbd "C-c C-x l") 'notes2-promote)
    (define-key map (kbd "C-c C-x r") 'notes2-demote)
    (define-key map (kbd "C-c C-x m") 'notes2-insert-list-item)
    map)
  "Keymap for Notes2 major mode.")


;;; Menu ==================================================================

(easy-menu-define notes2-mode-menu notes2-mode-map
  "Menu for Notes2 mode"
  '("Notes2"
    ("Show/Hide"
     ["Cycle visibility" notes2-cycle (outline-on-heading-p)]
     ["Cycle global visibility" notes2-shifttab])
    "---"
    ["Compile" notes2-compile]
    ["View" notes2-view]
    ["Latexify" notes2-latexify-notes]
    ["Extract code" notes2-extract-code]
    ["Errors" notes2-error-output]
    "---"
    ("Headings"
     ["Automatic" notes2-insert-header-dwim]
     "---"
     ["First level atx" notes2-insert-header-atx-1]
     ["Second level atx" notes2-insert-header-atx-2]
     ["Third level atx" notes2-insert-header-atx-3]
     ["Fourth level atx" notes2-insert-header-atx-4]
     ["Fifth level atx" notes2-insert-header-atx-5]
     ["Sixth level atx" notes2-insert-header-atx-6])
    "---"
    ["Bold" notes2-insert-bold]
    ["Italic" notes2-insert-italic]
    ["Blockquote" notes2-insert-blockquote]
    ["Preformatted" notes2-insert-pre]
    ["Code" notes2-insert-code]
    "---"
    ["Insert inline link" notes2-insert-link]
    ["Insert URL" notes2-insert-uri]
    ["Insert inline image" notes2-insert-image]
    ["Insert list item" notes2-insert-list-item]
    ["Insert horizontal rule" notes2-insert-hr]
    ["Kill element" notes2-kill-thing-at-point]
    "---"
    ["Follow link" notes2-follow-thing-at-point]
    ("Outline"
     ["Next visible heading" outline-next-visible-heading]
     ["Previous visible heading" outline-previous-visible-heading]
     ["Forward same level" outline-forward-same-level]
     ["Backward same level" outline-backward-same-level]
     ["Up to parent heading" outline-up-heading])
    "---"
    ("Completion and Cycling"
     ["Complete" notes2-complete]
     ["Promote" notes2-promote]
     ["Demote" notes2-demote])
    ("List editing"
     ["Indent list item" notes2-demote]
     ["Exdent list item" notes2-promote])
    ("Region shifting"
     ["Indent region" notes2-indent-region]
     ["Exdent region" notes2-exdent-region])
    "---"
    ["Clean up list numbering" notes2-cleanup-list-numbers]
    ["Complete markup" notes2-complete-buffer]
    "---"
    ["Version" notes2-show-version]
    ))


;;; imenu =====================================================================

(defun notes2-imenu-create-index ()
  "Create and return an imenu index alist for the current buffer.
See `imenu-create-index-function' and `imenu--index-alist' for details."
  (let* ((root '(nil . nil))
         cur-alist
         (cur-level 0)
         (empty-heading "-")
         (self-heading ".")
         hashes pos level heading)
    (save-excursion
      (goto-char (point-min))
      (while (re-search-forward notes2-regex-header (point-max) t)
        (cond
         ((setq heading (match-string-no-properties 1))
          (setq pos (match-beginning 1)
                level 1))
         ((setq heading (match-string-no-properties 3))
          (setq pos (match-beginning 3)
                level 2))
         ((setq hashes (match-string-no-properties 5))
          (setq heading (match-string-no-properties 6)
                pos (match-beginning 5)
                level (length hashes))))
        (let ((alist (list (cons heading pos))))
          (cond
           ((= cur-level level)         ; new sibling
            (setcdr cur-alist alist)
            (setq cur-alist alist))
           ((< cur-level level)         ; first child
            (dotimes (i (- level cur-level 1))
              (setq alist (list (cons empty-heading alist))))
            (if cur-alist
                (let* ((parent (car cur-alist))
                       (self-pos (cdr parent)))
                  (setcdr parent (cons (cons self-heading self-pos) alist)))
              (setcdr root alist))      ; primogenitor
            (setq cur-alist alist)
            (setq cur-level level))
           (t                           ; new sibling of an ancestor
            (let ((sibling-alist (last (cdr root))))
              (dotimes (i (1- level))
                (setq sibling-alist (last (cdar sibling-alist))))
              (setcdr sibling-alist alist)
              (setq cur-alist alist))
            (setq cur-level level)))))
      (cdr root))))


;;; Lists =====================================================================

(defun notes2-insert-list-item (&optional arg)
  "Insert a new list item.
If the point is inside unordered list, insert a bullet mark.  If
the point is inside ordered list, insert the next number followed
by a period.  Use the previous list item to determine the amount
of whitespace to place before and after list markers.

With a \\[universal-argument] prefix (i.e., when ARG is (4)),
decrease the indentation by one level.

With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
increase the indentation by one level."
  (interactive "p")
  (skip-chars-backward " \t")
  (let (bounds item-indent marker indent new-indent new-loc)
    (save-match-data
      ;; Look for a list item on current or previous non-blank line
      (save-excursion
        (while (and (not (setq bounds (notes2-cur-list-item-bounds)))
                    (not (bobp))
                    (notes2-cur-line-blank-p))
          (forward-line -1)))
      (when bounds
        (cond ((save-excursion
                 (skip-chars-backward " \t")
                 (looking-at notes2-regex-list))
               (beginning-of-line)
               (insert "\n")
               (forward-line -1))
              ((not (notes2-cur-line-blank-p))
               (newline)))
        (setq new-loc (point)))
      ;; Look ahead for a list item on next non-blank line
      (unless bounds
        (save-excursion
          (while (and (null bounds)
                      (not (eobp))
                      (notes2-cur-line-blank-p))
            (forward-line)
            (setq bounds (notes2-cur-list-item-bounds))))
        (when bounds
          (setq new-loc (point))
          (unless (notes2-cur-line-blank-p)
            (newline))))
      (if (not bounds)
          ;; When not in a list, start a new unordered one
          (progn
            (unless (notes2-cur-line-blank-p)
              (insert "\n"))
            (insert "* "))
        ;; Compute indentation for a new list item
        (setq item-indent (nth 2 bounds))
        (setq marker (nth 4 bounds))
        (setq indent (cond
                      ((= arg 4) (max (- item-indent 2) 0))
                      ((= arg 16) (+ item-indent 2))
                      (t item-indent)))
        (setq new-indent (make-string indent 32))
        (goto-char new-loc)
        (cond
         ;; Ordered list
         ((string-match "[0-9]" marker)
          (if (= arg 16) ;; starting a new column indented one more level
              (insert (concat new-indent "1. "))
            ;; travel up to the last item and pick the correct number.  If
            ;; the argument was nil, "new-indent = item-indent" is the same,
            ;; so we don't need special treatment. Neat.
            (save-excursion
              (while (not (looking-at (concat new-indent "\\([0-9]+\\)\\.")))
                (forward-line -1)))
            (insert (concat new-indent
                            (int-to-string (1+ (string-to-number (match-string 1))))
                            ". "))))
         ;; Unordered list
         ((string-match "[\\*\\+-]" marker)
          (insert new-indent marker)))))))

(defun notes2-move-list-item-up ()
  "Move the current list item up in the list when possible."
  (interactive)
  (let (cur prev old)
    (when (setq cur (notes2-cur-list-item-bounds))
      (setq old (point))
      (goto-char (nth 0 cur))
      (if (notes2-prev-list-item (nth 3 cur))
          (progn
            (setq prev (notes2-cur-list-item-bounds))
            (condition-case nil
                (progn
                  (transpose-regions (nth 0 prev) (nth 1 prev)
                                     (nth 0 cur) (nth 1 cur) t)
                  (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
              ;; Catch error in case regions overlap.
              (error (goto-char old))))
        (goto-char old)))))

(defun notes2-move-list-item-down ()
  "Move the current list item down in the list when possible."
  (interactive)
  (let (cur next old)
    (when (setq cur (notes2-cur-list-item-bounds))
      (setq old (point))
      (if (notes2-next-list-item (nth 3 cur))
          (progn
            (setq next (notes2-cur-list-item-bounds))
            (condition-case nil
                (progn
                  (transpose-regions (nth 0 cur) (nth 1 cur)
                                     (nth 0 next) (nth 1 next) nil)
                  (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
              ;; Catch error in case regions overlap.
              (error (goto-char old))))
        (goto-char old)))))

(defun notes2-demote-list-item (&optional bounds)
  "Indent (or demote) the current list item.
Optionally, BOUNDS of the current list item may be provided if available."
  (interactive)
  (when (or bounds (setq bounds (notes2-cur-list-item-bounds)))
    (save-excursion
      (save-match-data
        (let* ((end-marker (make-marker))
               (end-marker (set-marker end-marker (nth 1 bounds))))
          (goto-char (nth 0 bounds))
          (while (< (point) end-marker)
            (unless (notes2-cur-line-blank-p)
              (insert "  "))
            (forward-line)))))))

(defun notes2-promote-list-item (&optional bounds)
  "Unindent (or promote) the current list item.
Optionally, BOUNDS of the current list item may be provided if available."
  (interactive)
  (when (or bounds (setq bounds (notes2-cur-list-item-bounds)))
    (save-excursion
      (save-match-data
        (let* ((end-marker (make-marker))
               (end-marker (set-marker end-marker (nth 1 bounds)))
               num regexp)
          (goto-char (nth 0 bounds))
          (when (looking-at "^[ ]\\{1,2\\}")
            (setq num (- (match-end 0) (match-beginning 0)))
            (setq regexp (format "^[ ]\\{1,%d\\}" num))
            (while (and (< (point) end-marker)
                        (re-search-forward regexp end-marker t))
              (replace-match "" nil nil)
              (forward-line))))))))

(defun notes2-cleanup-list-numbers-level (&optional pfx)
  "Update the numbering for level PFX (as a string of spaces).

Assume that the previously found match was for a numbered item in
a list."
  (let ((cpfx pfx)
        (idx 0)
        (continue t)
        (step t)
        (sep nil))
    (while (and continue (not (eobp)))
      (setq step t)
      (cond
       ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
        (setq cpfx (match-string-no-properties 1))
        (cond
         ((string= cpfx pfx)
          (replace-match
           (concat pfx (number-to-string  (setq idx (1+ idx))) ". "))
          (setq sep nil))
         ;; indented a level
         ((string< pfx cpfx)
          (setq sep (notes2-cleanup-list-numbers-level cpfx))
          (setq step nil))
         ;; exit the loop
         (t
          (setq step nil)
          (setq continue nil))))

       ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
        (setq cpfx (match-string-no-properties 1))
        (cond
         ;; reset if separated before
         ((string= cpfx pfx) (when sep (setq idx 0)))
         ((string< cpfx pfx)
          (setq step nil)
          (setq continue nil))))
       (t (setq sep t)))

      (when step
        (beginning-of-line)
        (setq continue (= (forward-line) 0))))
    sep))

(defun notes2-cleanup-list-numbers ()
  "Update the numbering of ordered lists."
  (interactive)
  (save-excursion
    (goto-char (point-min))
    (notes2-cleanup-list-numbers-level "")))


;;; Outline ===================================================================

(defvar notes2-cycle-global-status 1)
(defvar notes2-cycle-subtree-status nil)

(defun notes2-end-of-subtree (&optional invisible-OK)
  "Move to the end of the current subtree.
Only visible heading lines are considered, unless INVISIBLE-OK is
non-nil.
Derived from `org-end-of-subtree'."
  (outline-back-to-heading invisible-OK)
  (let ((first t)
        (level (funcall outline-level)))
    (while (and (not (eobp))
                (or first (> (funcall outline-level) level)))
      (setq first nil)
      (outline-next-heading))
    (if (memq (preceding-char) '(?\n ?\^M))
        (progn
          ;; Go to end of line before heading
          (forward-char -1)
          (if (memq (preceding-char) '(?\n ?\^M))
              ;; leave blank line before heading
              (forward-char -1)))))
  (point))

(defun notes2-cycle (&optional arg)
  "Visibility cycling for Notes2 mode.
If ARG is t, perform global visibility cycling.  If the point is
at an atx-style header, cycle visibility of the corresponding
subtree.  Otherwise, insert a tab using `indent-relative'.
Derived from `org-cycle'."
  (interactive "P")
  (cond
   ((eq arg t) ;; Global cycling
    (cond
     ((and (eq last-command this-command)
           (eq notes2-cycle-global-status 2))
      ;; Move from overview to contents
      (hide-sublevels 1)
      (message "CONTENTS")
      (setq notes2-cycle-global-status 3))

     ((and (eq last-command this-command)
           (eq notes2-cycle-global-status 3))
      ;; Move from contents to all
      (show-all)
      (message "SHOW ALL")
      (setq notes2-cycle-global-status 1))

     (t
      ;; Defaults to overview
      (hide-body)
      (message "OVERVIEW")
      (setq notes2-cycle-global-status 2))))

   ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
    ;; At a heading: rotate between three different views
    (outline-back-to-heading)
    (let ((goal-column 0) eoh eol eos)
      ;; Determine boundaries
      (save-excursion
        (outline-back-to-heading)
        (save-excursion
          (beginning-of-line 2)
          (while (and (not (eobp)) ;; this is like `next-line'
                      (get-char-property (1- (point)) 'invisible))
            (beginning-of-line 2)) (setq eol (point)))
        (outline-end-of-heading)   (setq eoh (point))
        (notes2-end-of-subtree t)
        (skip-chars-forward " \t\n")
        (beginning-of-line 1) ; in case this is an item
        (setq eos (1- (point))))
      ;; Find out what to do next and set `this-command'
      (cond
       ((= eos eoh)
        ;; Nothing is hidden behind this heading
        (message "EMPTY ENTRY")
        (setq notes2-cycle-subtree-status nil))
       ((>= eol eos)
        ;; Entire subtree is hidden in one line: open it
        (show-entry)
        (show-children)
        (message "CHILDREN")
        (setq notes2-cycle-subtree-status 'children))
       ((and (eq last-command this-command)
             (eq notes2-cycle-subtree-status 'children))
        ;; We just showed the children, now show everything.
        (show-subtree)
        (message "SUBTREE")
        (setq notes2-cycle-subtree-status 'subtree))
       (t
        ;; Default action: hide the subtree.
        (hide-subtree)
        (message "FOLDED")
        (setq notes2-cycle-subtree-status 'folded)))))

   (t
    (indent-for-tab-command))))

(defun notes2-shifttab ()
  "Global visibility cycling.
Calls `notes2-cycle' with argument t."
  (interactive)
  (notes2-cycle t))

(defun notes2-outline-level ()
  "Return the depth to which a statement is nested in the outline."
  (cond
   ((match-end 1) 1)
   ((match-end 3) 2)
   ((- (match-end 5) (match-beginning 5)))))


;;; Movement ==================================================================

(defun notes2-beginning-of-defun (&optional arg)
  "`beginning-of-defun-function' for Notes2.
Move backward to the beginning of the current or previous section.
When ARG is non-nil, repeat that many times.  When ARG is negative,
move forward to the ARG-th following section."
  (interactive "P")
  (or arg (setq arg 1))
  (or (re-search-backward notes2-regex-header nil t arg)
      (goto-char (point-min))))

(defun notes2-end-of-defun (&optional arg)
  "`end-of-defun-function' for Notes2.
Move forward to the end of the current or following section.
When ARG is non-nil, repeat that many times.  When ARG is negative,
move back to the ARG-th preceding section."
  (interactive "P")
  (or arg (setq arg 1))
  (when (looking-at notes2-regex-header)
    (goto-char (match-beginning 0))
    (forward-char 1))
  (if (re-search-forward notes2-regex-header nil t arg)
      (goto-char (match-beginning 0))
    (goto-char (point-max)))
  (skip-syntax-backward "-"))

(defun notes2-beginning-of-block ()
  "Move the point to the start of the previous text block."
  (interactive)
  (if (re-search-backward notes2-regex-block-separator nil t)
      (goto-char (or (match-end 2) (match-end 0)))
    (goto-char (point-min))))

(defun notes2-end-of-block ()
  "Move the point to the start of the next text block."
  (interactive)
  (beginning-of-line)
  (skip-syntax-forward "-")
  (when (= (point) (point-min))
    (forward-char))
  (if (re-search-forward notes2-regex-block-separator nil t)
      (goto-char (or (match-end 2) (match-end 0)))
    (goto-char (point-max)))
  (skip-syntax-backward "-")
  (forward-line))

(defun notes2-forward-paragraph (arg)
  "Move forward one or more paragraphs or by one block.
When ARG is nil or a numeric prefix, call `forward-paragraph'
with ARG.  When called with \\[universal-argument], call
`notes2-end-of-block' instead."
  (interactive "P")
  (or arg (setq arg 1))
  (cond ((integerp arg)
         (forward-paragraph arg))
        ((equal arg '(4))
         (notes2-end-of-block))))

(defun notes2-backward-paragraph (arg)
  "Move backward one or more paragraphs or by one block.
When ARG is nil or a numeric prefix, call `backward-paragraph'
with ARG.  When called with \\[universal-argument], call
`notes2-beginning-of-block' instead."
  (interactive "P")
  (or arg (setq arg 1))
  (cond ((integerp arg)
         (backward-paragraph arg))
        ((equal arg '(4))
         (notes2-beginning-of-block))))

(defun notes2-end-of-block-element ()
  "Move the point to the start of the next block unit.
Stops at blank lines, list items, headers, and horizontal rules."
  (interactive)
  (forward-line)
  (while (and (or (not (notes2-prev-line-blank-p))
                  (notes2-cur-line-blank-p))
              (not (or (looking-at notes2-regex-list)
                       (looking-at notes2-regex-header)
                       (looking-at notes2-regex-hr)))
              (not (eobp)))
    (forward-line)))

(defun notes2-next-link ()
  "Jump to next inline, reference, or wiki link.
If successful, return point.  Otherwise, return nil.
See `notes2-wiki-link-p' and `notes2-previous-wiki-link'."
  (interactive)
  (let ((opoint (point)))
    (when (or (notes2-link-p) (notes2-wiki-link-p))
      ;; At a link already, move past it.
      (goto-char (+ (match-end 0) 1)))
    ;; Search for the next wiki link and move to the beginning.
    (if (re-search-forward notes2-regex-link-generic nil t)
        ;; Group 1 will move past non-escape character in wiki link regexp.
        ;; Go to beginning of group zero for all other link types.
        (goto-char (or (match-beginning 1) (match-beginning 0)))
      (goto-char opoint)
      nil)))

(defun notes2-previous-link ()
  "Jump to previous wiki link.
If successful, return point.  Otherwise, return nil.
See `notes2-wiki-link-p' and `notes2-next-wiki-link'."
  (interactive)
  (if (re-search-backward notes2-regex-link-generic nil t)
      (goto-char (or (match-beginning 1) (match-beginning 0)))
    nil))


;;; Generic Structure Editing, Completion, and Cycling Commands ===============

(defun notes2-move-up ()
  "Move list item up.
Calls `notes2-move-list-item-up'."
  (interactive)
  (notes2-move-list-item-up))

(defun notes2-move-down ()
  "Move list item down.
Calls `notes2-move-list-item-down'."
  (interactive)
  (notes2-move-list-item-down))

(defun notes2-promote ()
  "Either promote header or list item at point or cycle markup.
See `notes2-cycle-atx', `notes2-cycle-setext', and
`notes2-promote-list-item'."
  (interactive)
  (let (bounds)
    (cond
     ;; Promote atx header
     ((thing-at-point-looking-at notes2-regex-header-atx)
      (notes2-cycle-atx -1))
     ;; Promote horizonal rule
     ((thing-at-point-looking-at notes2-regex-hr)
      (notes2-cycle-hr -1))
     ;; Promote list item
     ((setq bounds (notes2-cur-list-item-bounds))
      (notes2-promote-list-item))
     ;; Promote bold
     ((thing-at-point-looking-at notes2-regex-bold)
      (notes2-cycle-bold))
     ;; Promote italic
     ((thing-at-point-looking-at notes2-regex-italic)
      (notes2-cycle-italic))
     (t
      (error "Nothing to promote at point")))))

(defun notes2-demote ()
  "Either demote header or list item at point or cycle or remove markup.
See `notes2-cycle-atx', `notes2-cycle-setext', and
`notes2-demote-list-item'."
  (interactive)
  (let (bounds)
    (cond
     ;; Demote atx header
     ((thing-at-point-looking-at notes2-regex-header-atx)
      (notes2-cycle-atx 1))
     ;; Demote horizonal rule
     ((thing-at-point-looking-at notes2-regex-hr)
      (notes2-cycle-hr 1))
     ;; Demote list item
     ((setq bounds (notes2-cur-list-item-bounds))
      (notes2-demote-list-item))
     ;; Demote bold
     ((thing-at-point-looking-at notes2-regex-bold)
      (notes2-cycle-bold))
     ;; Demote italic
     ((thing-at-point-looking-at notes2-regex-italic)
      (notes2-cycle-italic))
     (t
      (error "Nothing to demote at point")))))


;;; Commands ==================================================================

(defun notes2-extract-code ()
  "Run the extract-code utility on the current notes file."
  (interactive) 
  (save-window-excursion 
    (shell-command (concatenate 'string 
                                "/opt/notes-bin/extract-code.pl " 
                                (buffer-file-name)
                                ))))

(defun notes2-compile ()
  "Compile the current notes file with the ncompile utility.
Notify the user when it is completed.  Display errors if there
are any."
  (interactive) 
  (let ((oldwindow (current-window-configuration))
        (ncompileoutput (shell-command-to-string (concatenate 'string 
                                                              "/opt/notes-bin/ncompile " (buffer-file-name)))))
    (if (string-match-p "Output written on " ncompileoutput)
        (message "Compilation complete.  Use C-c C-v to view.")
      (progn
        (pop-to-buffer (generate-new-buffer "*Error output*"))
        (insert ncompileoutput))
      )
    ))

(defun notes2-error-output ()
  "Display any errors from the last compile attempt."
  (interactive)
  (let ((buffername (buffer-file-name)))
    (if (file-exists-p (concatenate 'string buffername ".log"))
        (progn
          (pop-to-buffer (generate-new-buffer "*Error output*"))
          (find-file (concatenate 'string buffername ".log"))
          (end-of-buffer)
          )
      (message "No errors"))
    ))

(defun notes2-view ()
  "View a PDF previously generated by notes2-compile"
  (interactive) 
  (save-window-excursion 
    (shell-command (concatenate 'string 
                                "okular " 
                                (buffer-file-name)
                                ".pdf &"))))

(defun notes2-latexify-notes ()
  "Run latexify-notes.pl and display the output in a new buffer."
  (interactive nil)
  (shell-command (concatenate 'string "/opt/notes-bin/latexify-notes.pl " (buffer-file-name)))
  )



;;; Links =====================================================================

(defun notes2-link-p ()
  "Return non-nil when `point' is at a non-wiki link.
See `notes2-wiki-link-p' for more information."
  (let ((case-fold-search nil))
    (and (not (notes2-wiki-link-p))
         (or (thing-at-point-looking-at notes2-regex-link-inline)
             (thing-at-point-looking-at notes2-regex-angle-image)))))

(defun notes2-link-link ()
  "Return the link part of the regular (non-wiki) link at point.
Works with both inline and reference style links.  If point is
not at a link or the link reference is not defined returns nil."
  (cond
   ((thing-at-point-looking-at notes2-regex-link-inline)
    (match-string-no-properties 2))
   ((thing-at-point-looking-at notes2-regex-angle-image)
    (match-string-no-properties 2))
   (t nil)))

(defun notes2-follow-link-at-point ()
  "Open the current non-wiki link in a browser."
  (interactive)
  (if (notes2-link-p) (browse-url (notes2-link-link))
    (error "Point is not at a Notes2 link or URI")))


;;; WikiLink Following/Markup =================================================

(defun notes2-wiki-link-p ()
  "Return non-nil when `point' is at a true wiki link.
A true wiki link name matches `notes2-regex-wiki-link' but does not
match the current file name after conversion.  This modifies the data
returned by `match-data'.  Note that the potential wiki link name must
be available via `match-string'."
  (let ((case-fold-search nil))
    (and (thing-at-point-looking-at notes2-regex-wiki-link)
         (or (not buffer-file-name)
             (not (string-equal (buffer-file-name)
                                (notes2-convert-wiki-link-to-filename
                                 (notes2-wiki-link-link)))))
         (not (save-match-data
                (save-excursion))))))

(defun notes2-wiki-link-link ()
  "Return the link part of the wiki link using current match data.
The location of the link component depends on the value of
`notes2-wiki-link-alias-first'."
  (if notes2-wiki-link-alias-first
      (or (match-string-no-properties 4) (match-string-no-properties 2))
    (match-string-no-properties 2)))

(defun notes2-wiki-link-alias ()
  "Return the alias or text part of the wiki link using current match data.
The location of the alias component depends on the value of
`notes2-wiki-link-alias-first'."
  (if notes2-wiki-link-alias-first
      (match-string-no-properties 2)
    (or (match-string-no-properties 4) (match-string-no-properties 2))))

(defun notes2-convert-wiki-link-to-filename (name)
  "Generate a filename from the wiki link NAME.
Spaces in NAME are replaced with `notes2-link-space-sub-char'.
When in `gfm2-mode', follow GitHub's conventions where [[Test Test]]
and [[test test]] both map to Test-test.ext."
  (let ((basename (notes2-replace-regexp-in-string
                   "[[:space:]\n]" notes2-link-space-sub-char name)))
    (concat basename
            (if (buffer-file-name)
                (concat "."
                        (file-name-extension (buffer-file-name)))))))

(defun notes2-follow-wiki-link (name &optional other)
  "Follow the wiki link NAME.
Convert the name to a file name and call `find-file'.  Ensure that
the new buffer remains in `notes2-mode'.  Open the link in another
window when OTHER is non-nil."
  (let ((filename (notes2-convert-wiki-link-to-filename name))
        (wp (file-name-directory buffer-file-name)))
    (when other (other-window 1))
    (find-file (concat wp filename)))
  (when (not (eq major-mode 'notes2-mode))
    (notes2-mode)))

(defun notes2-follow-wiki-link-at-point (&optional arg)
  "Find Wiki Link at point.
With prefix argument ARG, open the file in other window.
See `notes2-wiki-link-p' and `notes2-follow-wiki-link'."
  (interactive "P")
  (if (notes2-wiki-link-p)
      (notes2-follow-wiki-link (notes2-wiki-link-link) arg)
    (error "Point is not at a Wiki Link")))

(defun notes2-highlight-wiki-link (from to face)
  "Highlight the wiki link in the region between FROM and TO using FACE."
  (put-text-property from to 'font-lock-face face))

(defun notes2-unfontify-region-wiki-links (from to)
  "Remove wiki link faces from the region specified by FROM and TO."
  (interactive "nfrom: \nnto: ")
  (remove-text-properties from to '(font-lock-face notes2-link-face))
  (remove-text-properties from to '(font-lock-face notes2-missing-link-face)))

(defun notes2-fontify-region-wiki-links (from to)
  "Search region given by FROM and TO for wiki links and fontify them.
If a wiki link is found check to see if the backing file exists
and highlight accordingly."
  (goto-char from)
  (save-match-data
    (while (re-search-forward notes2-regex-wiki-link to t)
      (let ((highlight-beginning (match-beginning 1))
            (highlight-end (match-end 1))
            (file-name
             (notes2-convert-wiki-link-to-filename
              (notes2-wiki-link-link))))
        (if (file-exists-p file-name)
            (notes2-highlight-wiki-link
             highlight-beginning highlight-end notes2-link-face)
          (notes2-highlight-wiki-link
           highlight-beginning highlight-end notes2-link-face)
          (notes2-highlight-wiki-link
           highlight-beginning highlight-end notes2-missing-link-face))))))

(defun notes2-extend-changed-region (from to)
  "Extend region given by FROM and TO so that we can fontify all links.
The region is extended to the first newline before and the first
newline after."
  ;; start looking for the first new line before 'from
  (goto-char from)
  (re-search-backward "\n" nil t)
  (let ((new-from (point-min))
        (new-to (point-max)))
    (if (not (= (point) from))
        (setq new-from (point)))
    ;; do the same thing for the first new line after 'to
    (goto-char to)
    (re-search-forward "\n" nil t)
    (if (not (= (point) to))
        (setq new-to (point)))
    (values new-from new-to)))

(defun notes2-check-change-for-wiki-link (from to change)
  "Check region between FROM and TO for wiki links and re-fontfy as needed.
Designed to be used with the `after-change-functions' hook.
CHANGE is the number of bytes of pre-change text replaced by the
given range."
  (interactive "nfrom: \nnto: \nnchange: ")
  (let* ((modified (buffer-modified-p))
         (buffer-undo-list t)
         (inhibit-read-only t)
         (inhibit-point-motion-hooks t)
         deactivate-mark
         buffer-file-truename)
     (unwind-protect
         (save-excursion
           (save-match-data
             (save-restriction
               ;; Extend the region to fontify so that it starts
               ;; and ends at safe places.
               (multiple-value-bind (new-from new-to)
                   (notes2-extend-changed-region from to)
                 ;; Unfontify existing fontification (start from scratch)
                 (notes2-unfontify-region-wiki-links new-from new-to)
                 ;; Now do the fontification.
                 (notes2-fontify-region-wiki-links new-from new-to)))))
       (and (not modified)
            (buffer-modified-p)
            (set-buffer-modified-p nil)))))

(defun notes2-fontify-buffer-wiki-links ()
  "Refontify all wiki links in the buffer."
  (interactive)
  (notes2-check-change-for-wiki-link (point-min) (point-max) 0))


;;; Following and Jumping =====================================================

(defun notes2-follow-thing-at-point (arg)
  "Follow thing at point if possible, such as a reference link or wiki link.
Opens inline and reference links in a browser.  Opens wiki links
to other files in the current window, or the another window if
ARG is non-nil.
See `notes2-follow-link-at-point' and
`notes2-follow-wiki-link-at-point'."
  (interactive "P")
  (cond ((notes2-link-p)
         (notes2-follow-link-at-point))
        ((notes2-wiki-link-p)
         (notes2-follow-wiki-link-at-point arg))
        (t
         (error "Nothing to follow at point"))))


;;; Miscellaneous =============================================================

(defun notes2-compress-whitespace-string (str)
  "Compress whitespace in STR and return result.
Leading and trailing whitespace is removed.  Sequences of multiple
spaces, tabs, and newlines are replaced with single spaces."
  (replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
                            (replace-regexp-in-string "[ \t\n]+" " " str)))

(defun notes2-line-number-at-pos (&optional pos)
  "Return (narrowed) buffer line number at position POS.
If POS is nil, use current buffer location.
This is an exact copy of `line-number-at-pos' for use in emacs21."
  (let ((opoint (or pos (point))) start)
    (save-excursion
      (goto-char (point-min))
      (setq start (point))
      (goto-char opoint)
      (forward-line 0)
      (1+ (count-lines start (point))))))

(defun notes2-nobreak-p ()
  "Return nil if it is acceptable to break the current line at the point."
  ;; inside in square brackets (e.g., link anchor text)
  (looking-back "\\[[^]]*"))

(defun notes2-adaptive-fill-function ()
  "Return prefix for filling paragraph or nil if not determined."
  (cond
   ;; List item inside blockquote
   ((looking-at "^[ \t]*>[ \t]*\\([0-9]+\\.\\|[*+-]\\)[ \t]+")
    (replace-regexp-in-string
     "[0-9\\.*+-]" " " (match-string-no-properties 0)))
   ;; Blockquote
   ((looking-at "^[ \t]*>[ \t]*")
    (match-string-no-properties 0))
   ;; Important "-> " designator
   ((save-excursion 
      (re-search-backward "\n\n")
      (forward-char 2)
      (looking-at "-> "))
    "   ")
   ;; Captions for figures
   ((save-excursion 
      (re-search-backward "\n\n")
      (forward-char 2)
      (looking-at "<<"))
    "  ")
   ;; Math environment
   ;; ((save-excursion 
   ;;    (re-search-backward "\n\n")
   ;;    (forward-char 2)
   ;;    (looking-at "\\$\\$\\$"))
   ;;  (match-string-no-properties 0))
   ;; Comment
   ((looking-at "^[ \t]*#[ \t]*")
    (match-string-no-properties 0))
   ;; List items
   ((looking-at notes2-regex-list)
    (match-string-no-properties 0))
   ;; No match
   (t nil)))


;;; Extensions ================================================================

(defun notes2-reload-extensions ()
  "Check settings, update font-lock keywords, and re-fontify buffer."
  (interactive)
  (when (eq major-mode 'notes2-mode)
    (setq notes2-mode-font-lock-keywords
          notes2-mode-font-lock-keywords-basic)
    (setq font-lock-defaults '(notes2-mode-font-lock-keywords))
    (font-lock-refresh-defaults)))

; TODO
(defun notes2-spell-check-here ()
  "Check if the word at the point should be spell checked.
   Integrates with flyspell via the
   flyspell-generic-check-word-predicate function."
  (interactive)
)

; 
(setq flyspell-ncbi-espell-lookup-cache (make-hash-table :test 'equal))
(defun flyspell-ncbi-espell-lookup (beg end info)
  "Lookup a word with the NCBI eSpell API."
  (unless (gethash (buffer-substring (+ 1 beg) end) flyspell-ncbi-espell-lookup-cache nil)
    ; Get the output of the ncbi-espell-lookup.pl program
    (let ((oldwindow (current-window-configuration))
          (espelloutput (shell-command-to-string (concatenate 'string 
                                                                "/opt/notes-bin/ncbi-espell-lookup.pl \"" (downcase  (buffer-substring (+ 1 beg) end)) "\""))))
      (unless (string= espelloutput "___ERROR___")
          (progn
            (puthash (buffer-substring (+ 1 beg) end) espelloutput flyspell-ncbi-espell-lookup-cache)
            ; Add the corrected word to the buffer-local dictionary if a correction is available.
            (unless (string-match " " espelloutput) (process-send-string ispell-process
                                                                         (concat "@" espelloutput "\n")))))))
  (if (string= (gethash (buffer-substring (+ 1 beg) end) flyspell-ncbi-espell-lookup-cache nil) "")
      t
      nil)
)



;;; Mode Definition  ==========================================================

(defun notes2-show-version ()
  "Show the version number in the minibuffer."
  (interactive)
  (message "notes2-mode, version %s" notes2-mode-version))

;;;###autoload
(define-derived-mode notes2-mode text-mode "Notes2"
  "Major mode for editing Notes2 files."
  ;; Natural Notes2 tab width
  (setq tab-width 2)
  ;; Comments
  (make-local-variable 'comment-start)
  (setq comment-start "/\* ")
  (make-local-variable 'comment-end)
  (setq comment-end " \*/")
  (make-local-variable 'comment-start-skip)
  (setq comment-start-skip "/\\*[ \t]*")
  (make-local-variable 'comment-column)
  (setq comment-column 0)
  ;; Font lock.
  (set (make-local-variable 'notes2-mode-font-lock-keywords) nil)
  (set (make-local-variable 'font-lock-defaults) nil)
  (set (make-local-variable 'font-lock-multiline) t)
  (set (make-local-variable 'jit-lock-chunk-size) 1500)
  (notes2-reload-extensions)
  ;; Extensions
  (add-hook 'hack-local-variables-hook 'notes2-reload-extensions)
  ;; For imenu support
  (setq imenu-create-index-function 'notes2-imenu-create-index)
  ;; For menu support in XEmacs
  (easy-menu-add notes2-mode-menu notes2-mode-map)
  ;; Defun movement
  (set (make-local-variable 'beginning-of-defun-function)
       'notes2-beginning-of-defun)
  (set (make-local-variable 'end-of-defun-function)
       'notes2-end-of-defun)
  ;; Paragraph filling
  (set (make-local-variable 'paragraph-start)
       "\f\\|[ \t]*$\\|[ \t]*[*+-] \\|[ \t]*[0-9]+\\.\\|[ \t]*: \\|{\\|<")
  (set (make-local-variable 'paragraph-separate)
       "\\(?:[ \t\f]*\\)$")
  (set (make-local-variable 'adaptive-fill-first-line-regexp)
       "\\`[ \t]*>[ \t]*?\\'")
  (set (make-local-variable 'adaptive-fill-function)
       'notes2-adaptive-fill-function)
  ;; Outline mode
  (make-local-variable 'outline-regexp)
  (setq outline-regexp notes2-regex-header)
  (make-local-variable 'outline-level)
  (setq outline-level 'notes2-outline-level)
  ;; Cause use of ellipses for invisible text.
  (add-to-invisibility-spec '(outline . t))
  ;; Indentation and filling
  (make-local-variable 'fill-nobreak-predicate)
  (add-hook 'fill-nobreak-predicate 'notes2-nobreak-p)
  (setq indent-line-function notes2-indent-function)

  ;; Prepare hooks for XEmacs compatibility
  (when (featurep 'xemacs)
    (make-local-hook 'after-change-functions)
    (make-local-hook 'font-lock-extend-region-functions)
    (make-local-hook 'window-configuration-change-hook))

  ;; Enable NCBI spellcheck if enabled.
  (when notes2-use-ncbi-spellcheck
    (add-hook (make-local-variable 'flyspell-incorrect-hook) 'flyspell-ncbi-espell-lookup))

  ;; Multiline font lock
  (add-hook 'font-lock-extend-region-functions
            'notes2-font-lock-extend-region)

  ;; Anytime text changes make sure it gets fontified correctly
  ;(add-hook 'after-change-functions 'notes2-check-change-for-wiki-link t t)

  ;; If we left the buffer there is a really good chance we were
  ;; creating one of the wiki link documents. Make sure we get
  ;; refontified when we come back.
  ;(add-hook 'window-configuration-change-hook
  ;          'notes2-fontify-buffer-wiki-links t t)

  ;; do the initial link fontification
  ;(notes2-fontify-buffer-wiki-links)
  (orgtbl-mode)
  (org-link-minor-mode)
  )

;;(add-to-list 'auto-mode-alist '("\\.text$" . notes2-mode))



(provide 'notes2-mode)

;;; notes2-mode.el ends here