bootstrap-markdown.js
92.7 KB
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
// Released under MIT license
// Copyright (c) 2009-2010 Dominic Baggott
// Copyright (c) 2009-2010 Ash Berlin
// Copyright (c) 2011 Christoph Dorn <christoph@christophdorn.com> (http://www.christophdorn.com)
/*jshint browser:true, devel:true */
(function( expose ) {
/**
* class Markdown
*
* Markdown processing in Javascript done right. We have very particular views
* on what constitutes 'right' which include:
*
* - produces well-formed HTML (this means that em and strong nesting is
* important)
*
* - has an intermediate representation to allow processing of parsed data (We
* in fact have two, both as [JsonML]: a markdown tree and an HTML tree).
*
* - is easily extensible to add new dialects without having to rewrite the
* entire parsing mechanics
*
* - has a good test suite
*
* This implementation fulfills all of these (except that the test suite could
* do with expanding to automatically run all the fixtures from other Markdown
* implementations.)
*
* ##### Intermediate Representation
*
* *TODO* Talk about this :) Its JsonML, but document the node names we use.
*
* [JsonML]: http://jsonml.org/ "JSON Markup Language"
**/
var Markdown = expose.Markdown = function(dialect) {
switch (typeof dialect) {
case "undefined":
this.dialect = Markdown.dialects.Gruber;
break;
case "object":
this.dialect = dialect;
break;
default:
if ( dialect in Markdown.dialects ) {
this.dialect = Markdown.dialects[dialect];
}
else {
throw new Error("Unknown Markdown dialect '" + String(dialect) + "'");
}
break;
}
this.em_state = [];
this.strong_state = [];
this.debug_indent = "";
};
/**
* parse( markdown, [dialect] ) -> JsonML
* - markdown (String): markdown string to parse
* - dialect (String | Dialect): the dialect to use, defaults to gruber
*
* Parse `markdown` and return a markdown document as a Markdown.JsonML tree.
**/
expose.parse = function( source, dialect ) {
// dialect will default if undefined
var md = new Markdown( dialect );
return md.toTree( source );
};
/**
* toHTML( markdown, [dialect] ) -> String
* toHTML( md_tree ) -> String
* - markdown (String): markdown string to parse
* - md_tree (Markdown.JsonML): parsed markdown tree
*
* Take markdown (either as a string or as a JsonML tree) and run it through
* [[toHTMLTree]] then turn it into a well-formated HTML fragment.
**/
expose.toHTML = function toHTML( source , dialect , options ) {
var input = expose.toHTMLTree( source , dialect , options );
return expose.renderJsonML( input );
};
/**
* toHTMLTree( markdown, [dialect] ) -> JsonML
* toHTMLTree( md_tree ) -> JsonML
* - markdown (String): markdown string to parse
* - dialect (String | Dialect): the dialect to use, defaults to gruber
* - md_tree (Markdown.JsonML): parsed markdown tree
*
* Turn markdown into HTML, represented as a JsonML tree. If a string is given
* to this function, it is first parsed into a markdown tree by calling
* [[parse]].
**/
expose.toHTMLTree = function toHTMLTree( input, dialect , options ) {
// convert string input to an MD tree
if ( typeof input ==="string" ) input = this.parse( input, dialect );
// Now convert the MD tree to an HTML tree
// remove references from the tree
var attrs = extract_attr( input ),
refs = {};
if ( attrs && attrs.references ) {
refs = attrs.references;
}
var html = convert_tree_to_html( input, refs , options );
merge_text_nodes( html );
return html;
};
// For Spidermonkey based engines
function mk_block_toSource() {
return "Markdown.mk_block( " +
uneval(this.toString()) +
", " +
uneval(this.trailing) +
", " +
uneval(this.lineNumber) +
" )";
}
// node
function mk_block_inspect() {
var util = require("util");
return "Markdown.mk_block( " +
util.inspect(this.toString()) +
", " +
util.inspect(this.trailing) +
", " +
util.inspect(this.lineNumber) +
" )";
}
var mk_block = Markdown.mk_block = function(block, trail, line) {
// Be helpful for default case in tests.
if ( arguments.length == 1 ) trail = "\n\n";
var s = new String(block);
s.trailing = trail;
// To make it clear its not just a string
s.inspect = mk_block_inspect;
s.toSource = mk_block_toSource;
if ( line != undefined )
s.lineNumber = line;
return s;
};
function count_lines( str ) {
var n = 0, i = -1;
while ( ( i = str.indexOf("\n", i + 1) ) !== -1 ) n++;
return n;
}
// Internal - split source into rough blocks
Markdown.prototype.split_blocks = function splitBlocks( input, startLine ) {
input = input.replace(/(\r\n|\n|\r)/g, "\n");
// [\s\S] matches _anything_ (newline or space)
// [^] is equivalent but doesn't work in IEs.
var re = /([\s\S]+?)($|\n#|\n(?:\s*\n|$)+)/g,
blocks = [],
m;
var line_no = 1;
if ( ( m = /^(\s*\n)/.exec(input) ) != null ) {
// skip (but count) leading blank lines
line_no += count_lines( m[0] );
re.lastIndex = m[0].length;
}
while ( ( m = re.exec(input) ) !== null ) {
if (m[2] == "\n#") {
m[2] = "\n";
re.lastIndex--;
}
blocks.push( mk_block( m[1], m[2], line_no ) );
line_no += count_lines( m[0] );
}
return blocks;
};
/**
* Markdown#processBlock( block, next ) -> undefined | [ JsonML, ... ]
* - block (String): the block to process
* - next (Array): the following blocks
*
* Process `block` and return an array of JsonML nodes representing `block`.
*
* It does this by asking each block level function in the dialect to process
* the block until one can. Succesful handling is indicated by returning an
* array (with zero or more JsonML nodes), failure by a false value.
*
* Blocks handlers are responsible for calling [[Markdown#processInline]]
* themselves as appropriate.
*
* If the blocks were split incorrectly or adjacent blocks need collapsing you
* can adjust `next` in place using shift/splice etc.
*
* If any of this default behaviour is not right for the dialect, you can
* define a `__call__` method on the dialect that will get invoked to handle
* the block processing.
*/
Markdown.prototype.processBlock = function processBlock( block, next ) {
var cbs = this.dialect.block,
ord = cbs.__order__;
if ( "__call__" in cbs ) {
return cbs.__call__.call(this, block, next);
}
for ( var i = 0; i < ord.length; i++ ) {
//D:this.debug( "Testing", ord[i] );
var res = cbs[ ord[i] ].call( this, block, next );
if ( res ) {
//D:this.debug(" matched");
if ( !isArray(res) || ( res.length > 0 && !( isArray(res[0]) ) ) )
this.debug(ord[i], "didn't return a proper array");
//D:this.debug( "" );
return res;
}
}
// Uhoh! no match! Should we throw an error?
return [];
};
Markdown.prototype.processInline = function processInline( block ) {
return this.dialect.inline.__call__.call( this, String( block ) );
};
/**
* Markdown#toTree( source ) -> JsonML
* - source (String): markdown source to parse
*
* Parse `source` into a JsonML tree representing the markdown document.
**/
// custom_tree means set this.tree to `custom_tree` and restore old value on return
Markdown.prototype.toTree = function toTree( source, custom_root ) {
var blocks = source instanceof Array ? source : this.split_blocks( source );
// Make tree a member variable so its easier to mess with in extensions
var old_tree = this.tree;
try {
this.tree = custom_root || this.tree || [ "markdown" ];
blocks:
while ( blocks.length ) {
var b = this.processBlock( blocks.shift(), blocks );
// Reference blocks and the like won't return any content
if ( !b.length ) continue blocks;
this.tree.push.apply( this.tree, b );
}
return this.tree;
}
finally {
if ( custom_root ) {
this.tree = old_tree;
}
}
};
// Noop by default
Markdown.prototype.debug = function () {
var args = Array.prototype.slice.call( arguments);
args.unshift(this.debug_indent);
if ( typeof print !== "undefined" )
print.apply( print, args );
if ( typeof console !== "undefined" && typeof console.log !== "undefined" )
console.log.apply( null, args );
}
Markdown.prototype.loop_re_over_block = function( re, block, cb ) {
// Dont use /g regexps with this
var m,
b = block.valueOf();
while ( b.length && (m = re.exec(b) ) != null ) {
b = b.substr( m[0].length );
cb.call(this, m);
}
return b;
};
/**
* Markdown.dialects
*
* Namespace of built-in dialects.
**/
Markdown.dialects = {};
/**
* Markdown.dialects.Gruber
*
* The default dialect that follows the rules set out by John Gruber's
* markdown.pl as closely as possible. Well actually we follow the behaviour of
* that script which in some places is not exactly what the syntax web page
* says.
**/
Markdown.dialects.Gruber = {
block: {
atxHeader: function atxHeader( block, next ) {
var m = block.match( /^(#{1,6})\s*(.*?)\s*#*\s*(?:\n|$)/ );
if ( !m ) return undefined;
var header = [ "header", { level: m[ 1 ].length } ];
Array.prototype.push.apply(header, this.processInline(m[ 2 ]));
if ( m[0].length < block.length )
next.unshift( mk_block( block.substr( m[0].length ), block.trailing, block.lineNumber + 2 ) );
return [ header ];
},
setextHeader: function setextHeader( block, next ) {
var m = block.match( /^(.*)\n([-=])\2\2+(?:\n|$)/ );
if ( !m ) return undefined;
var level = ( m[ 2 ] === "=" ) ? 1 : 2;
var header = [ "header", { level : level }, m[ 1 ] ];
if ( m[0].length < block.length )
next.unshift( mk_block( block.substr( m[0].length ), block.trailing, block.lineNumber + 2 ) );
return [ header ];
},
code: function code( block, next ) {
// | Foo
// |bar
// should be a code block followed by a paragraph. Fun
//
// There might also be adjacent code block to merge.
var ret = [],
re = /^(?: {0,3}\t| {4})(.*)\n?/,
lines;
// 4 spaces + content
if ( !block.match( re ) ) return undefined;
block_search:
do {
// Now pull out the rest of the lines
var b = this.loop_re_over_block(
re, block.valueOf(), function( m ) { ret.push( m[1] ); } );
if ( b.length ) {
// Case alluded to in first comment. push it back on as a new block
next.unshift( mk_block(b, block.trailing) );
break block_search;
}
else if ( next.length ) {
// Check the next block - it might be code too
if ( !next[0].match( re ) ) break block_search;
// Pull how how many blanks lines follow - minus two to account for .join
ret.push ( block.trailing.replace(/[^\n]/g, "").substring(2) );
block = next.shift();
}
else {
break block_search;
}
} while ( true );
return [ [ "code_block", ret.join("\n") ] ];
},
horizRule: function horizRule( block, next ) {
// this needs to find any hr in the block to handle abutting blocks
var m = block.match( /^(?:([\s\S]*?)\n)?[ \t]*([-_*])(?:[ \t]*\2){2,}[ \t]*(?:\n([\s\S]*))?$/ );
if ( !m ) {
return undefined;
}
var jsonml = [ [ "hr" ] ];
// if there's a leading abutting block, process it
if ( m[ 1 ] ) {
jsonml.unshift.apply( jsonml, this.processBlock( m[ 1 ], [] ) );
}
// if there's a trailing abutting block, stick it into next
if ( m[ 3 ] ) {
next.unshift( mk_block( m[ 3 ] ) );
}
return jsonml;
},
// There are two types of lists. Tight and loose. Tight lists have no whitespace
// between the items (and result in text just in the <li>) and loose lists,
// which have an empty line between list items, resulting in (one or more)
// paragraphs inside the <li>.
//
// There are all sorts weird edge cases about the original markdown.pl's
// handling of lists:
//
// * Nested lists are supposed to be indented by four chars per level. But
// if they aren't, you can get a nested list by indenting by less than
// four so long as the indent doesn't match an indent of an existing list
// item in the 'nest stack'.
//
// * The type of the list (bullet or number) is controlled just by the
// first item at the indent. Subsequent changes are ignored unless they
// are for nested lists
//
lists: (function( ) {
// Use a closure to hide a few variables.
var any_list = "[*+-]|\\d+\\.",
bullet_list = /[*+-]/,
number_list = /\d+\./,
// Capture leading indent as it matters for determining nested lists.
is_list_re = new RegExp( "^( {0,3})(" + any_list + ")[ \t]+" ),
indent_re = "(?: {0,3}\\t| {4})";
// TODO: Cache this regexp for certain depths.
// Create a regexp suitable for matching an li for a given stack depth
function regex_for_depth( depth ) {
return new RegExp(
// m[1] = indent, m[2] = list_type
"(?:^(" + indent_re + "{0," + depth + "} {0,3})(" + any_list + ")\\s+)|" +
// m[3] = cont
"(^" + indent_re + "{0," + (depth-1) + "}[ ]{0,4})"
);
}
function expand_tab( input ) {
return input.replace( / {0,3}\t/g, " " );
}
// Add inline content `inline` to `li`. inline comes from processInline
// so is an array of content
function add(li, loose, inline, nl) {
if ( loose ) {
li.push( [ "para" ].concat(inline) );
return;
}
// Hmmm, should this be any block level element or just paras?
var add_to = li[li.length -1] instanceof Array && li[li.length - 1][0] == "para"
? li[li.length -1]
: li;
// If there is already some content in this list, add the new line in
if ( nl && li.length > 1 ) inline.unshift(nl);
for ( var i = 0; i < inline.length; i++ ) {
var what = inline[i],
is_str = typeof what == "string";
if ( is_str && add_to.length > 1 && typeof add_to[add_to.length-1] == "string" ) {
add_to[ add_to.length-1 ] += what;
}
else {
add_to.push( what );
}
}
}
// contained means have an indent greater than the current one. On
// *every* line in the block
function get_contained_blocks( depth, blocks ) {
var re = new RegExp( "^(" + indent_re + "{" + depth + "}.*?\\n?)*$" ),
replace = new RegExp("^" + indent_re + "{" + depth + "}", "gm"),
ret = [];
while ( blocks.length > 0 ) {
if ( re.exec( blocks[0] ) ) {
var b = blocks.shift(),
// Now remove that indent
x = b.replace( replace, "");
ret.push( mk_block( x, b.trailing, b.lineNumber ) );
}
else {
break;
}
}
return ret;
}
// passed to stack.forEach to turn list items up the stack into paras
function paragraphify(s, i, stack) {
var list = s.list;
var last_li = list[list.length-1];
if ( last_li[1] instanceof Array && last_li[1][0] == "para" ) {
return;
}
if ( i + 1 == stack.length ) {
// Last stack frame
// Keep the same array, but replace the contents
last_li.push( ["para"].concat( last_li.splice(1, last_li.length - 1) ) );
}
else {
var sublist = last_li.pop();
last_li.push( ["para"].concat( last_li.splice(1, last_li.length - 1) ), sublist );
}
}
// The matcher function
return function( block, next ) {
var m = block.match( is_list_re );
if ( !m ) return undefined;
function make_list( m ) {
var list = bullet_list.exec( m[2] )
? ["bulletlist"]
: ["numberlist"];
stack.push( { list: list, indent: m[1] } );
return list;
}
var stack = [], // Stack of lists for nesting.
list = make_list( m ),
last_li,
loose = false,
ret = [ stack[0].list ],
i;
// Loop to search over block looking for inner block elements and loose lists
loose_search:
while ( true ) {
// Split into lines preserving new lines at end of line
var lines = block.split( /(?=\n)/ );
// We have to grab all lines for a li and call processInline on them
// once as there are some inline things that can span lines.
var li_accumulate = "";
// Loop over the lines in this block looking for tight lists.
tight_search:
for ( var line_no = 0; line_no < lines.length; line_no++ ) {
var nl = "",
l = lines[line_no].replace(/^\n/, function(n) { nl = n; return ""; });
// TODO: really should cache this
var line_re = regex_for_depth( stack.length );
m = l.match( line_re );
//print( "line:", uneval(l), "\nline match:", uneval(m) );
// We have a list item
if ( m[1] !== undefined ) {
// Process the previous list item, if any
if ( li_accumulate.length ) {
add( last_li, loose, this.processInline( li_accumulate ), nl );
// Loose mode will have been dealt with. Reset it
loose = false;
li_accumulate = "";
}
m[1] = expand_tab( m[1] );
var wanted_depth = Math.floor(m[1].length/4)+1;
//print( "want:", wanted_depth, "stack:", stack.length);
if ( wanted_depth > stack.length ) {
// Deep enough for a nested list outright
//print ( "new nested list" );
list = make_list( m );
last_li.push( list );
last_li = list[1] = [ "listitem" ];
}
else {
// We aren't deep enough to be strictly a new level. This is
// where Md.pl goes nuts. If the indent matches a level in the
// stack, put it there, else put it one deeper then the
// wanted_depth deserves.
var found = false;
for ( i = 0; i < stack.length; i++ ) {
if ( stack[ i ].indent != m[1] ) continue;
list = stack[ i ].list;
stack.splice( i+1, stack.length - (i+1) );
found = true;
break;
}
if (!found) {
//print("not found. l:", uneval(l));
wanted_depth++;
if ( wanted_depth <= stack.length ) {
stack.splice(wanted_depth, stack.length - wanted_depth);
//print("Desired depth now", wanted_depth, "stack:", stack.length);
list = stack[wanted_depth-1].list;
//print("list:", uneval(list) );
}
else {
//print ("made new stack for messy indent");
list = make_list(m);
last_li.push(list);
}
}
//print( uneval(list), "last", list === stack[stack.length-1].list );
last_li = [ "listitem" ];
list.push(last_li);
} // end depth of shenegains
nl = "";
}
// Add content
if ( l.length > m[0].length ) {
li_accumulate += nl + l.substr( m[0].length );
}
} // tight_search
if ( li_accumulate.length ) {
add( last_li, loose, this.processInline( li_accumulate ), nl );
// Loose mode will have been dealt with. Reset it
loose = false;
li_accumulate = "";
}
// Look at the next block - we might have a loose list. Or an extra
// paragraph for the current li
var contained = get_contained_blocks( stack.length, next );
// Deal with code blocks or properly nested lists
if ( contained.length > 0 ) {
// Make sure all listitems up the stack are paragraphs
forEach( stack, paragraphify, this);
last_li.push.apply( last_li, this.toTree( contained, [] ) );
}
var next_block = next[0] && next[0].valueOf() || "";
if ( next_block.match(is_list_re) || next_block.match( /^ / ) ) {
block = next.shift();
// Check for an HR following a list: features/lists/hr_abutting
var hr = this.dialect.block.horizRule( block, next );
if ( hr ) {
ret.push.apply(ret, hr);
break;
}
// Make sure all listitems up the stack are paragraphs
forEach( stack, paragraphify, this);
loose = true;
continue loose_search;
}
break;
} // loose_search
return ret;
};
})(),
blockquote: function blockquote( block, next ) {
if ( !block.match( /^>/m ) )
return undefined;
var jsonml = [];
// separate out the leading abutting block, if any. I.e. in this case:
//
// a
// > b
//
if ( block[ 0 ] != ">" ) {
var lines = block.split( /\n/ ),
prev = [],
line_no = block.lineNumber;
// keep shifting lines until you find a crotchet
while ( lines.length && lines[ 0 ][ 0 ] != ">" ) {
prev.push( lines.shift() );
line_no++;
}
var abutting = mk_block( prev.join( "\n" ), "\n", block.lineNumber );
jsonml.push.apply( jsonml, this.processBlock( abutting, [] ) );
// reassemble new block of just block quotes!
block = mk_block( lines.join( "\n" ), block.trailing, line_no );
}
// if the next block is also a blockquote merge it in
while ( next.length && next[ 0 ][ 0 ] == ">" ) {
var b = next.shift();
block = mk_block( block + block.trailing + b, b.trailing, block.lineNumber );
}
// Strip off the leading "> " and re-process as a block.
var input = block.replace( /^> ?/gm, "" ),
old_tree = this.tree,
processedBlock = this.toTree( input, [ "blockquote" ] ),
attr = extract_attr( processedBlock );
// If any link references were found get rid of them
if ( attr && attr.references ) {
delete attr.references;
// And then remove the attribute object if it's empty
if ( isEmpty( attr ) ) {
processedBlock.splice( 1, 1 );
}
}
jsonml.push( processedBlock );
return jsonml;
},
referenceDefn: function referenceDefn( block, next) {
var re = /^\s*\[(.*?)\]:\s*(\S+)(?:\s+(?:(['"])(.*?)\3|\((.*?)\)))?\n?/;
// interesting matches are [ , ref_id, url, , title, title ]
if ( !block.match(re) )
return undefined;
// make an attribute node if it doesn't exist
if ( !extract_attr( this.tree ) ) {
this.tree.splice( 1, 0, {} );
}
var attrs = extract_attr( this.tree );
// make a references hash if it doesn't exist
if ( attrs.references === undefined ) {
attrs.references = {};
}
var b = this.loop_re_over_block(re, block, function( m ) {
if ( m[2] && m[2][0] == "<" && m[2][m[2].length-1] == ">" )
m[2] = m[2].substring( 1, m[2].length - 1 );
var ref = attrs.references[ m[1].toLowerCase() ] = {
href: m[2]
};
if ( m[4] !== undefined )
ref.title = m[4];
else if ( m[5] !== undefined )
ref.title = m[5];
} );
if ( b.length )
next.unshift( mk_block( b, block.trailing ) );
return [];
},
para: function para( block, next ) {
// everything's a para!
return [ ["para"].concat( this.processInline( block ) ) ];
}
}
};
Markdown.dialects.Gruber.inline = {
__oneElement__: function oneElement( text, patterns_or_re, previous_nodes ) {
var m,
res,
lastIndex = 0;
patterns_or_re = patterns_or_re || this.dialect.inline.__patterns__;
var re = new RegExp( "([\\s\\S]*?)(" + (patterns_or_re.source || patterns_or_re) + ")" );
m = re.exec( text );
if (!m) {
// Just boring text
return [ text.length, text ];
}
else if ( m[1] ) {
// Some un-interesting text matched. Return that first
return [ m[1].length, m[1] ];
}
var res;
if ( m[2] in this.dialect.inline ) {
res = this.dialect.inline[ m[2] ].call(
this,
text.substr( m.index ), m, previous_nodes || [] );
}
// Default for now to make dev easier. just slurp special and output it.
res = res || [ m[2].length, m[2] ];
return res;
},
__call__: function inline( text, patterns ) {
var out = [],
res;
function add(x) {
//D:self.debug(" adding output", uneval(x));
if ( typeof x == "string" && typeof out[out.length-1] == "string" )
out[ out.length-1 ] += x;
else
out.push(x);
}
while ( text.length > 0 ) {
res = this.dialect.inline.__oneElement__.call(this, text, patterns, out );
text = text.substr( res.shift() );
forEach(res, add )
}
return out;
},
// These characters are intersting elsewhere, so have rules for them so that
// chunks of plain text blocks don't include them
"]": function () {},
"}": function () {},
__escape__ : /^\\[\\`\*_{}\[\]()#\+.!\-]/,
"\\": function escaped( text ) {
// [ length of input processed, node/children to add... ]
// Only esacape: \ ` * _ { } [ ] ( ) # * + - . !
if ( this.dialect.inline.__escape__.exec( text ) )
return [ 2, text.charAt( 1 ) ];
else
// Not an esacpe
return [ 1, "\\" ];
},
"
// 1 2 3 4 <--- captures
var m = text.match( /^!\[(.*?)\][ \t]*\([ \t]*([^")]*?)(?:[ \t]+(["'])(.*?)\3)?[ \t]*\)/ );
if ( m ) {
if ( m[2] && m[2][0] == "<" && m[2][m[2].length-1] == ">" )
m[2] = m[2].substring( 1, m[2].length - 1 );
m[2] = this.dialect.inline.__call__.call( this, m[2], /\\/ )[0];
var attrs = { alt: m[1], href: m[2] || "" };
if ( m[4] !== undefined)
attrs.title = m[4];
return [ m[0].length, [ "img", attrs ] ];
}
// ![Alt text][id]
m = text.match( /^!\[(.*?)\][ \t]*\[(.*?)\]/ );
if ( m ) {
// We can't check if the reference is known here as it likely wont be
// found till after. Check it in md tree->hmtl tree conversion
return [ m[0].length, [ "img_ref", { alt: m[1], ref: m[2].toLowerCase(), original: m[0] } ] ];
}
// Just consume the '!['
return [ 2, "![" ];
},
"[": function link( text ) {
var orig = String(text);
// Inline content is possible inside `link text`
var res = Markdown.DialectHelpers.inline_until_char.call( this, text.substr(1), "]" );
// No closing ']' found. Just consume the [
if ( !res ) return [ 1, "[" ];
var consumed = 1 + res[ 0 ],
children = res[ 1 ],
link,
attrs;
// At this point the first [...] has been parsed. See what follows to find
// out which kind of link we are (reference or direct url)
text = text.substr( consumed );
// [link text](/path/to/img.jpg "Optional title")
// 1 2 3 <--- captures
// This will capture up to the last paren in the block. We then pull
// back based on if there a matching ones in the url
// ([here](/url/(test))
// The parens have to be balanced
var m = text.match( /^\s*\([ \t]*([^"']*)(?:[ \t]+(["'])(.*?)\2)?[ \t]*\)/ );
if ( m ) {
var url = m[1];
consumed += m[0].length;
if ( url && url[0] == "<" && url[url.length-1] == ">" )
url = url.substring( 1, url.length - 1 );
// If there is a title we don't have to worry about parens in the url
if ( !m[3] ) {
var open_parens = 1; // One open that isn't in the capture
for ( var len = 0; len < url.length; len++ ) {
switch ( url[len] ) {
case "(":
open_parens++;
break;
case ")":
if ( --open_parens == 0) {
consumed -= url.length - len;
url = url.substring(0, len);
}
break;
}
}
}
// Process escapes only
url = this.dialect.inline.__call__.call( this, url, /\\/ )[0];
attrs = { href: url || "" };
if ( m[3] !== undefined)
attrs.title = m[3];
link = [ "link", attrs ].concat( children );
return [ consumed, link ];
}
// [Alt text][id]
// [Alt text] [id]
m = text.match( /^\s*\[(.*?)\]/ );
if ( m ) {
consumed += m[ 0 ].length;
// [links][] uses links as its reference
attrs = { ref: ( m[ 1 ] || String(children) ).toLowerCase(), original: orig.substr( 0, consumed ) };
link = [ "link_ref", attrs ].concat( children );
// We can't check if the reference is known here as it likely wont be
// found till after. Check it in md tree->hmtl tree conversion.
// Store the original so that conversion can revert if the ref isn't found.
return [ consumed, link ];
}
// [id]
// Only if id is plain (no formatting.)
if ( children.length == 1 && typeof children[0] == "string" ) {
attrs = { ref: children[0].toLowerCase(), original: orig.substr( 0, consumed ) };
link = [ "link_ref", attrs, children[0] ];
return [ consumed, link ];
}
// Just consume the "["
return [ 1, "[" ];
},
"<": function autoLink( text ) {
var m;
if ( ( m = text.match( /^<(?:((https?|ftp|mailto):[^>]+)|(.*?@.*?\.[a-zA-Z]+))>/ ) ) != null ) {
if ( m[3] ) {
return [ m[0].length, [ "link", { href: "mailto:" + m[3] }, m[3] ] ];
}
else if ( m[2] == "mailto" ) {
return [ m[0].length, [ "link", { href: m[1] }, m[1].substr("mailto:".length ) ] ];
}
else
return [ m[0].length, [ "link", { href: m[1] }, m[1] ] ];
}
return [ 1, "<" ];
},
"`": function inlineCode( text ) {
// Inline code block. as many backticks as you like to start it
// Always skip over the opening ticks.
var m = text.match( /(`+)(([\s\S]*?)\1)/ );
if ( m && m[2] )
return [ m[1].length + m[2].length, [ "inlinecode", m[3] ] ];
else {
// TODO: No matching end code found - warn!
return [ 1, "`" ];
}
},
" \n": function lineBreak( text ) {
return [ 3, [ "linebreak" ] ];
}
};
// Meta Helper/generator method for em and strong handling
function strong_em( tag, md ) {
var state_slot = tag + "_state",
other_slot = tag == "strong" ? "em_state" : "strong_state";
function CloseTag(len) {
this.len_after = len;
this.name = "close_" + md;
}
return function ( text, orig_match ) {
if ( this[state_slot][0] == md ) {
// Most recent em is of this type
//D:this.debug("closing", md);
this[state_slot].shift();
// "Consume" everything to go back to the recrusion in the else-block below
return[ text.length, new CloseTag(text.length-md.length) ];
}
else {
// Store a clone of the em/strong states
var other = this[other_slot].slice(),
state = this[state_slot].slice();
this[state_slot].unshift(md);
//D:this.debug_indent += " ";
// Recurse
var res = this.processInline( text.substr( md.length ) );
//D:this.debug_indent = this.debug_indent.substr(2);
var last = res[res.length - 1];
//D:this.debug("processInline from", tag + ": ", uneval( res ) );
var check = this[state_slot].shift();
if ( last instanceof CloseTag ) {
res.pop();
// We matched! Huzzah.
var consumed = text.length - last.len_after;
return [ consumed, [ tag ].concat(res) ];
}
else {
// Restore the state of the other kind. We might have mistakenly closed it.
this[other_slot] = other;
this[state_slot] = state;
// We can't reuse the processed result as it could have wrong parsing contexts in it.
return [ md.length, md ];
}
}
}; // End returned function
}
Markdown.dialects.Gruber.inline["**"] = strong_em("strong", "**");
Markdown.dialects.Gruber.inline["__"] = strong_em("strong", "__");
Markdown.dialects.Gruber.inline["*"] = strong_em("em", "*");
Markdown.dialects.Gruber.inline["_"] = strong_em("em", "_");
// Build default order from insertion order.
Markdown.buildBlockOrder = function(d) {
var ord = [];
for ( var i in d ) {
if ( i == "__order__" || i == "__call__" ) continue;
ord.push( i );
}
d.__order__ = ord;
};
// Build patterns for inline matcher
Markdown.buildInlinePatterns = function(d) {
var patterns = [];
for ( var i in d ) {
// __foo__ is reserved and not a pattern
if ( i.match( /^__.*__$/) ) continue;
var l = i.replace( /([\\.*+?|()\[\]{}])/g, "\\$1" )
.replace( /\n/, "\\n" );
patterns.push( i.length == 1 ? l : "(?:" + l + ")" );
}
patterns = patterns.join("|");
d.__patterns__ = patterns;
//print("patterns:", uneval( patterns ) );
var fn = d.__call__;
d.__call__ = function(text, pattern) {
if ( pattern != undefined ) {
return fn.call(this, text, pattern);
}
else
{
return fn.call(this, text, patterns);
}
};
};
Markdown.DialectHelpers = {};
Markdown.DialectHelpers.inline_until_char = function( text, want ) {
var consumed = 0,
nodes = [];
while ( true ) {
if ( text.charAt( consumed ) == want ) {
// Found the character we were looking for
consumed++;
return [ consumed, nodes ];
}
if ( consumed >= text.length ) {
// No closing char found. Abort.
return null;
}
var res = this.dialect.inline.__oneElement__.call(this, text.substr( consumed ) );
consumed += res[ 0 ];
// Add any returned nodes.
nodes.push.apply( nodes, res.slice( 1 ) );
}
}
// Helper function to make sub-classing a dialect easier
Markdown.subclassDialect = function( d ) {
function Block() {}
Block.prototype = d.block;
function Inline() {}
Inline.prototype = d.inline;
return { block: new Block(), inline: new Inline() };
};
Markdown.buildBlockOrder ( Markdown.dialects.Gruber.block );
Markdown.buildInlinePatterns( Markdown.dialects.Gruber.inline );
Markdown.dialects.Maruku = Markdown.subclassDialect( Markdown.dialects.Gruber );
Markdown.dialects.Maruku.processMetaHash = function processMetaHash( meta_string ) {
var meta = split_meta_hash( meta_string ),
attr = {};
for ( var i = 0; i < meta.length; ++i ) {
// id: #foo
if ( /^#/.test( meta[ i ] ) ) {
attr.id = meta[ i ].substring( 1 );
}
// class: .foo
else if ( /^\./.test( meta[ i ] ) ) {
// if class already exists, append the new one
if ( attr["class"] ) {
attr["class"] = attr["class"] + meta[ i ].replace( /./, " " );
}
else {
attr["class"] = meta[ i ].substring( 1 );
}
}
// attribute: foo=bar
else if ( /\=/.test( meta[ i ] ) ) {
var s = meta[ i ].split( /\=/ );
attr[ s[ 0 ] ] = s[ 1 ];
}
}
return attr;
}
function split_meta_hash( meta_string ) {
var meta = meta_string.split( "" ),
parts = [ "" ],
in_quotes = false;
while ( meta.length ) {
var letter = meta.shift();
switch ( letter ) {
case " " :
// if we're in a quoted section, keep it
if ( in_quotes ) {
parts[ parts.length - 1 ] += letter;
}
// otherwise make a new part
else {
parts.push( "" );
}
break;
case "'" :
case '"' :
// reverse the quotes and move straight on
in_quotes = !in_quotes;
break;
case "\\" :
// shift off the next letter to be used straight away.
// it was escaped so we'll keep it whatever it is
letter = meta.shift();
default :
parts[ parts.length - 1 ] += letter;
break;
}
}
return parts;
}
Markdown.dialects.Maruku.block.document_meta = function document_meta( block, next ) {
// we're only interested in the first block
if ( block.lineNumber > 1 ) return undefined;
// document_meta blocks consist of one or more lines of `Key: Value\n`
if ( ! block.match( /^(?:\w+:.*\n)*\w+:.*$/ ) ) return undefined;
// make an attribute node if it doesn't exist
if ( !extract_attr( this.tree ) ) {
this.tree.splice( 1, 0, {} );
}
var pairs = block.split( /\n/ );
for ( p in pairs ) {
var m = pairs[ p ].match( /(\w+):\s*(.*)$/ ),
key = m[ 1 ].toLowerCase(),
value = m[ 2 ];
this.tree[ 1 ][ key ] = value;
}
// document_meta produces no content!
return [];
};
Markdown.dialects.Maruku.block.block_meta = function block_meta( block, next ) {
// check if the last line of the block is an meta hash
var m = block.match( /(^|\n) {0,3}\{:\s*((?:\\\}|[^\}])*)\s*\}$/ );
if ( !m ) return undefined;
// process the meta hash
var attr = this.dialect.processMetaHash( m[ 2 ] );
var hash;
// if we matched ^ then we need to apply meta to the previous block
if ( m[ 1 ] === "" ) {
var node = this.tree[ this.tree.length - 1 ];
hash = extract_attr( node );
// if the node is a string (rather than JsonML), bail
if ( typeof node === "string" ) return undefined;
// create the attribute hash if it doesn't exist
if ( !hash ) {
hash = {};
node.splice( 1, 0, hash );
}
// add the attributes in
for ( a in attr ) {
hash[ a ] = attr[ a ];
}
// return nothing so the meta hash is removed
return [];
}
// pull the meta hash off the block and process what's left
var b = block.replace( /\n.*$/, "" ),
result = this.processBlock( b, [] );
// get or make the attributes hash
hash = extract_attr( result[ 0 ] );
if ( !hash ) {
hash = {};
result[ 0 ].splice( 1, 0, hash );
}
// attach the attributes to the block
for ( a in attr ) {
hash[ a ] = attr[ a ];
}
return result;
};
Markdown.dialects.Maruku.block.definition_list = function definition_list( block, next ) {
// one or more terms followed by one or more definitions, in a single block
var tight = /^((?:[^\s:].*\n)+):\s+([\s\S]+)$/,
list = [ "dl" ],
i, m;
// see if we're dealing with a tight or loose block
if ( ( m = block.match( tight ) ) ) {
// pull subsequent tight DL blocks out of `next`
var blocks = [ block ];
while ( next.length && tight.exec( next[ 0 ] ) ) {
blocks.push( next.shift() );
}
for ( var b = 0; b < blocks.length; ++b ) {
var m = blocks[ b ].match( tight ),
terms = m[ 1 ].replace( /\n$/, "" ).split( /\n/ ),
defns = m[ 2 ].split( /\n:\s+/ );
// print( uneval( m ) );
for ( i = 0; i < terms.length; ++i ) {
list.push( [ "dt", terms[ i ] ] );
}
for ( i = 0; i < defns.length; ++i ) {
// run inline processing over the definition
list.push( [ "dd" ].concat( this.processInline( defns[ i ].replace( /(\n)\s+/, "$1" ) ) ) );
}
}
}
else {
return undefined;
}
return [ list ];
};
// splits on unescaped instances of @ch. If @ch is not a character the result
// can be unpredictable
Markdown.dialects.Maruku.block.table = function table (block, next) {
var _split_on_unescaped = function(s, ch) {
ch = ch || '\\s';
if (ch.match(/^[\\|\[\]{}?*.+^$]$/)) { ch = '\\' + ch; }
var res = [ ],
r = new RegExp('^((?:\\\\.|[^\\\\' + ch + '])*)' + ch + '(.*)'),
m;
while(m = s.match(r)) {
res.push(m[1]);
s = m[2];
}
res.push(s);
return res;
}
var leading_pipe = /^ {0,3}\|(.+)\n {0,3}\|\s*([\-:]+[\-| :]*)\n((?:\s*\|.*(?:\n|$))*)(?=\n|$)/,
// find at least an unescaped pipe in each line
no_leading_pipe = /^ {0,3}(\S(?:\\.|[^\\|])*\|.*)\n {0,3}([\-:]+\s*\|[\-| :]*)\n((?:(?:\\.|[^\\|])*\|.*(?:\n|$))*)(?=\n|$)/,
i, m;
if (m = block.match(leading_pipe)) {
// remove leading pipes in contents
// (header and horizontal rule already have the leading pipe left out)
m[3] = m[3].replace(/^\s*\|/gm, '');
} else if (! ( m = block.match(no_leading_pipe))) {
return undefined;
}
var table = [ "table", [ "thead", [ "tr" ] ], [ "tbody" ] ];
// remove trailing pipes, then split on pipes
// (no escaped pipes are allowed in horizontal rule)
m[2] = m[2].replace(/\|\s*$/, '').split('|');
// process alignment
var html_attrs = [ ];
forEach (m[2], function (s) {
if (s.match(/^\s*-+:\s*$/)) html_attrs.push({align: "right"});
else if (s.match(/^\s*:-+\s*$/)) html_attrs.push({align: "left"});
else if (s.match(/^\s*:-+:\s*$/)) html_attrs.push({align: "center"});
else html_attrs.push({});
});
// now for the header, avoid escaped pipes
m[1] = _split_on_unescaped(m[1].replace(/\|\s*$/, ''), '|');
for (i = 0; i < m[1].length; i++) {
table[1][1].push(['th', html_attrs[i] || {}].concat(
this.processInline(m[1][i].trim())));
}
// now for body contents
forEach (m[3].replace(/\|\s*$/mg, '').split('\n'), function (row) {
var html_row = ['tr'];
row = _split_on_unescaped(row, '|');
for (i = 0; i < row.length; i++) {
html_row.push(['td', html_attrs[i] || {}].concat(this.processInline(row[i].trim())));
}
table[2].push(html_row);
}, this);
return [table];
}
Markdown.dialects.Maruku.inline[ "{:" ] = function inline_meta( text, matches, out ) {
if ( !out.length ) {
return [ 2, "{:" ];
}
// get the preceeding element
var before = out[ out.length - 1 ];
if ( typeof before === "string" ) {
return [ 2, "{:" ];
}
// match a meta hash
var m = text.match( /^\{:\s*((?:\\\}|[^\}])*)\s*\}/ );
// no match, false alarm
if ( !m ) {
return [ 2, "{:" ];
}
// attach the attributes to the preceeding element
var meta = this.dialect.processMetaHash( m[ 1 ] ),
attr = extract_attr( before );
if ( !attr ) {
attr = {};
before.splice( 1, 0, attr );
}
for ( var k in meta ) {
attr[ k ] = meta[ k ];
}
// cut out the string and replace it with nothing
return [ m[ 0 ].length, "" ];
};
Markdown.dialects.Maruku.inline.__escape__ = /^\\[\\`\*_{}\[\]()#\+.!\-|:]/;
Markdown.buildBlockOrder ( Markdown.dialects.Maruku.block );
Markdown.buildInlinePatterns( Markdown.dialects.Maruku.inline );
var isArray = Array.isArray || function(obj) {
return Object.prototype.toString.call(obj) == "[object Array]";
};
var forEach;
// Don't mess with Array.prototype. Its not friendly
if ( Array.prototype.forEach ) {
forEach = function( arr, cb, thisp ) {
return arr.forEach( cb, thisp );
};
}
else {
forEach = function(arr, cb, thisp) {
for (var i = 0; i < arr.length; i++) {
cb.call(thisp || arr, arr[i], i, arr);
}
}
}
var isEmpty = function( obj ) {
for ( var key in obj ) {
if ( hasOwnProperty.call( obj, key ) ) {
return false;
}
}
return true;
}
function extract_attr( jsonml ) {
return isArray(jsonml)
&& jsonml.length > 1
&& typeof jsonml[ 1 ] === "object"
&& !( isArray(jsonml[ 1 ]) )
? jsonml[ 1 ]
: undefined;
}
/**
* renderJsonML( jsonml[, options] ) -> String
* - jsonml (Array): JsonML array to render to XML
* - options (Object): options
*
* Converts the given JsonML into well-formed XML.
*
* The options currently understood are:
*
* - root (Boolean): wether or not the root node should be included in the
* output, or just its children. The default `false` is to not include the
* root itself.
*/
expose.renderJsonML = function( jsonml, options ) {
options = options || {};
// include the root element in the rendered output?
options.root = options.root || false;
var content = [];
if ( options.root ) {
content.push( render_tree( jsonml ) );
}
else {
jsonml.shift(); // get rid of the tag
if ( jsonml.length && typeof jsonml[ 0 ] === "object" && !( jsonml[ 0 ] instanceof Array ) ) {
jsonml.shift(); // get rid of the attributes
}
while ( jsonml.length ) {
content.push( render_tree( jsonml.shift() ) );
}
}
return content.join( "\n\n" );
};
function escapeHTML( text ) {
return text.replace( /&/g, "&" )
.replace( /</g, "<" )
.replace( />/g, ">" )
.replace( /"/g, """ )
.replace( /'/g, "'" );
}
function render_tree( jsonml ) {
// basic case
if ( typeof jsonml === "string" ) {
return escapeHTML( jsonml );
}
var tag = jsonml.shift(),
attributes = {},
content = [];
if ( jsonml.length && typeof jsonml[ 0 ] === "object" && !( jsonml[ 0 ] instanceof Array ) ) {
attributes = jsonml.shift();
}
while ( jsonml.length ) {
content.push( render_tree( jsonml.shift() ) );
}
var tag_attrs = "";
for ( var a in attributes ) {
tag_attrs += " " + a + '="' + escapeHTML( attributes[ a ] ) + '"';
}
// be careful about adding whitespace here for inline elements
if ( tag == "img" || tag == "br" || tag == "hr" ) {
return "<"+ tag + tag_attrs + "/>";
}
else {
return "<"+ tag + tag_attrs + ">" + content.join( "" ) + "</" + tag + ">";
}
}
function convert_tree_to_html( tree, references, options ) {
var i;
options = options || {};
// shallow clone
var jsonml = tree.slice( 0 );
if ( typeof options.preprocessTreeNode === "function" ) {
jsonml = options.preprocessTreeNode(jsonml, references);
}
// Clone attributes if they exist
var attrs = extract_attr( jsonml );
if ( attrs ) {
jsonml[ 1 ] = {};
for ( i in attrs ) {
jsonml[ 1 ][ i ] = attrs[ i ];
}
attrs = jsonml[ 1 ];
}
// basic case
if ( typeof jsonml === "string" ) {
return jsonml;
}
// convert this node
switch ( jsonml[ 0 ] ) {
case "header":
jsonml[ 0 ] = "h" + jsonml[ 1 ].level;
delete jsonml[ 1 ].level;
break;
case "bulletlist":
jsonml[ 0 ] = "ul";
break;
case "numberlist":
jsonml[ 0 ] = "ol";
break;
case "listitem":
jsonml[ 0 ] = "li";
break;
case "para":
jsonml[ 0 ] = "p";
break;
case "markdown":
jsonml[ 0 ] = "html";
if ( attrs ) delete attrs.references;
break;
case "code_block":
jsonml[ 0 ] = "pre";
i = attrs ? 2 : 1;
var code = [ "code" ];
code.push.apply( code, jsonml.splice( i, jsonml.length - i ) );
jsonml[ i ] = code;
break;
case "inlinecode":
jsonml[ 0 ] = "code";
break;
case "img":
jsonml[ 1 ].src = jsonml[ 1 ].href;
delete jsonml[ 1 ].href;
break;
case "linebreak":
jsonml[ 0 ] = "br";
break;
case "link":
jsonml[ 0 ] = "a";
break;
case "link_ref":
jsonml[ 0 ] = "a";
// grab this ref and clean up the attribute node
var ref = references[ attrs.ref ];
// if the reference exists, make the link
if ( ref ) {
delete attrs.ref;
// add in the href and title, if present
attrs.href = ref.href;
if ( ref.title ) {
attrs.title = ref.title;
}
// get rid of the unneeded original text
delete attrs.original;
}
// the reference doesn't exist, so revert to plain text
else {
return attrs.original;
}
break;
case "img_ref":
jsonml[ 0 ] = "img";
// grab this ref and clean up the attribute node
var ref = references[ attrs.ref ];
// if the reference exists, make the link
if ( ref ) {
delete attrs.ref;
// add in the href and title, if present
attrs.src = ref.href;
if ( ref.title ) {
attrs.title = ref.title;
}
// get rid of the unneeded original text
delete attrs.original;
}
// the reference doesn't exist, so revert to plain text
else {
return attrs.original;
}
break;
}
// convert all the children
i = 1;
// deal with the attribute node, if it exists
if ( attrs ) {
// if there are keys, skip over it
for ( var key in jsonml[ 1 ] ) {
i = 2;
break;
}
// if there aren't, remove it
if ( i === 1 ) {
jsonml.splice( i, 1 );
}
}
for ( ; i < jsonml.length; ++i ) {
jsonml[ i ] = convert_tree_to_html( jsonml[ i ], references, options );
}
return jsonml;
}
// merges adjacent text nodes into a single node
function merge_text_nodes( jsonml ) {
// skip the tag name and attribute hash
var i = extract_attr( jsonml ) ? 2 : 1;
while ( i < jsonml.length ) {
// if it's a string check the next item too
if ( typeof jsonml[ i ] === "string" ) {
if ( i + 1 < jsonml.length && typeof jsonml[ i + 1 ] === "string" ) {
// merge the second string into the first and remove it
jsonml[ i ] += jsonml.splice( i + 1, 1 )[ 0 ];
}
else {
++i;
}
}
// if it's not a string recurse
else {
merge_text_nodes( jsonml[ i ] );
++i;
}
}
}
} )( (function() {
if ( typeof exports === "undefined" ) {
window.markdown = {};
return window.markdown;
}
else {
return exports;
}
} )() );
/* ===================================================
* bootstrap-markdown.js v2.10.0
* http://github.com/toopay/bootstrap-markdown
* ===================================================
* Copyright 2013-2016 Taufan Aditya
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================== */
(function(factory){
if (typeof define === "function" && define.amd) {
//RequireJS
define(["jquery"], factory);
} else if (typeof exports === 'object') {
//Backbone.js
factory(require('jquery'));
} else {
//Jquery plugin
factory(jQuery);
}
}(function($){
"use strict"; // jshint ;_;
/* MARKDOWN CLASS DEFINITION
* ========================== */
var Markdown = function (element, options) {
// @TODO : remove this BC on next major release
// @see : https://github.com/toopay/bootstrap-markdown/issues/109
var opts = ['autofocus', 'savable', 'hideable', 'width',
'height', 'resize', 'iconlibrary', 'language',
'footer', 'fullscreen', 'hiddenButtons', 'disabledButtons'];
$.each(opts,function(_, opt){
if (typeof $(element).data(opt) !== 'undefined') {
options = typeof options == 'object' ? options : {}
options[opt] = $(element).data(opt)
}
});
// End BC
// Class Properties
this.$ns = 'bootstrap-markdown';
this.$element = $(element);
this.$editable = {el:null, type:null,attrKeys:[], attrValues:[], content:null};
this.$options = $.extend(true, {}, $.fn.markdown.defaults, options, this.$element.data('options'));
this.$oldContent = null;
this.$isPreview = false;
this.$isFullscreen = false;
this.$editor = null;
this.$textarea = null;
this.$handler = [];
this.$callback = [];
this.$nextTab = [];
this.showEditor();
};
Markdown.prototype = {
constructor: Markdown
, __alterButtons: function(name,alter) {
var handler = this.$handler, isAll = (name == 'all'),that = this;
$.each(handler,function(k,v) {
var halt = true;
if (isAll) {
halt = false;
} else {
halt = v.indexOf(name) < 0;
}
if (halt === false) {
alter(that.$editor.find('button[data-handler="'+v+'"]'));
}
});
}
, __buildButtons: function(buttonsArray, container) {
var i,
ns = this.$ns,
handler = this.$handler,
callback = this.$callback;
for (i=0;i<buttonsArray.length;i++) {
// Build each group container
var y, btnGroups = buttonsArray[i];
for (y=0;y<btnGroups.length;y++) {
// Build each button group
var z,
buttons = btnGroups[y].data,
btnGroupContainer = $('<div/>', {
'class': 'btn-group'
});
for (z=0;z<buttons.length;z++) {
var button = buttons[z],
buttonContainer, buttonIconContainer,
buttonHandler = ns+'-'+button.name,
buttonIcon = this.__getIcon(button.icon),
btnText = button.btnText ? button.btnText : '',
btnClass = button.btnClass ? button.btnClass : 'btn',
tabIndex = button.tabIndex ? button.tabIndex : '-1',
hotkey = typeof button.hotkey !== 'undefined' ? button.hotkey : '',
hotkeyCaption = typeof jQuery.hotkeys !== 'undefined' && hotkey !== '' ? ' ('+hotkey+')' : '';
// Construct the button object
buttonContainer = $('<button></button>');
buttonContainer.text(' ' + this.__localize(btnText)).addClass('btn-default btn-sm').addClass(btnClass);
if(btnClass.match(/btn\-(primary|success|info|warning|danger|link)/)){
buttonContainer.removeClass('btn-default');
}
buttonContainer.attr({
'type': 'button',
'title': this.__localize(button.title) + hotkeyCaption,
'tabindex': tabIndex,
'data-provider': ns,
'data-handler': buttonHandler,
'data-hotkey': hotkey
});
if (button.toggle === true){
buttonContainer.attr('data-toggle', 'button');
}
buttonIconContainer = $('<span/>');
buttonIconContainer.addClass(buttonIcon);
buttonIconContainer.prependTo(buttonContainer);
// Attach the button object
btnGroupContainer.append(buttonContainer);
// Register handler and callback
handler.push(buttonHandler);
callback.push(button.callback);
}
// Attach the button group into container dom
container.append(btnGroupContainer);
}
}
return container;
}
, __setListener: function() {
// Set size and resizable Properties
var hasRows = typeof this.$textarea.attr('rows') !== 'undefined',
maxRows = this.$textarea.val().split("\n").length > 5 ? this.$textarea.val().split("\n").length : '5',
rowsVal = hasRows ? this.$textarea.attr('rows') : maxRows;
this.$textarea.attr('rows',rowsVal);
if (this.$options.resize) {
this.$textarea.css('resize',this.$options.resize);
}
this.$textarea.on({
'focus' : $.proxy(this.focus, this),
'keyup' : $.proxy(this.keyup, this),
'change' : $.proxy(this.change, this),
'select' : $.proxy(this.select, this)
});
if (this.eventSupported('keydown')) {
this.$textarea.on('keydown', $.proxy(this.keydown, this));
}
if (this.eventSupported('keypress')) {
this.$textarea.on('keypress', $.proxy(this.keypress, this))
}
// Re-attach markdown data
this.$textarea.data('markdown',this);
}
, __handle: function(e) {
var target = $(e.currentTarget),
handler = this.$handler,
callback = this.$callback,
handlerName = target.attr('data-handler'),
callbackIndex = handler.indexOf(handlerName),
callbackHandler = callback[callbackIndex];
// Trigger the focusin
$(e.currentTarget).focus();
callbackHandler(this);
// Trigger onChange for each button handle
this.change(this);
// Unless it was the save handler,
// focusin the textarea
if (handlerName.indexOf('cmdSave') < 0) {
this.$textarea.focus();
}
e.preventDefault();
}
, __localize: function(string) {
var messages = $.fn.markdown.messages,
language = this.$options.language;
if (
typeof messages !== 'undefined' &&
typeof messages[language] !== 'undefined' &&
typeof messages[language][string] !== 'undefined'
) {
return messages[language][string];
}
return string;
}
, __getIcon: function(src) {
return typeof src == 'object' ? src[this.$options.iconlibrary] : src;
}
, setFullscreen: function(mode) {
var $editor = this.$editor,
$textarea = this.$textarea;
if (mode === true) {
$editor.addClass('md-fullscreen-mode');
$('body').addClass('md-nooverflow');
this.$options.onFullscreen(this);
} else {
$editor.removeClass('md-fullscreen-mode');
$('body').removeClass('md-nooverflow');
if (this.$isPreview == true) this.hidePreview().showPreview()
}
this.$isFullscreen = mode;
$textarea.focus();
}
, showEditor: function() {
var instance = this,
textarea,
ns = this.$ns,
container = this.$element,
originalHeigth = container.css('height'),
originalWidth = container.css('width'),
editable = this.$editable,
handler = this.$handler,
callback = this.$callback,
options = this.$options,
editor = $( '<div/>', {
'class': 'md-editor',
click: function() {
instance.focus();
}
});
// Prepare the editor
if (this.$editor === null) {
// Create the panel
var editorHeader = $('<div/>', {
'class': 'md-header btn-toolbar'
});
// Merge the main & additional button groups together
var allBtnGroups = [];
if (options.buttons.length > 0) allBtnGroups = allBtnGroups.concat(options.buttons[0]);
if (options.additionalButtons.length > 0) {
// iterate the additional button groups
$.each(options.additionalButtons[0], function(idx, buttonGroup){
// see if the group name of the addional group matches an existing group
var matchingGroups = $.grep(allBtnGroups, function(allButtonGroup, allIdx){
return allButtonGroup.name === buttonGroup.name;
});
// if it matches add the addional buttons to that group, if not just add it to the all buttons group
if(matchingGroups.length > 0) {
matchingGroups[0].data = matchingGroups[0].data.concat(buttonGroup.data);
} else {
allBtnGroups.push(options.additionalButtons[0][idx]);
}
});
}
// Reduce and/or reorder the button groups
if (options.reorderButtonGroups.length > 0) {
allBtnGroups = allBtnGroups
.filter(function(btnGroup) {
return options.reorderButtonGroups.indexOf(btnGroup.name) > -1;
})
.sort(function(a, b) {
if (options.reorderButtonGroups.indexOf(a.name) < options.reorderButtonGroups.indexOf(b.name)) return -1;
if (options.reorderButtonGroups.indexOf(a.name) > options.reorderButtonGroups.indexOf(b.name)) return 1;
return 0;
});
}
// Build the buttons
if (allBtnGroups.length > 0) {
editorHeader = this.__buildButtons([allBtnGroups], editorHeader);
}
if (options.fullscreen.enable) {
editorHeader.append('<div class="md-controls"><a class="md-control md-control-fullscreen" href="#"><span class="'+this.__getIcon(options.fullscreen.icons.fullscreenOn)+'"></span></a></div>').on('click', '.md-control-fullscreen', function(e) {
e.preventDefault();
instance.setFullscreen(true);
});
}
editor.append(editorHeader);
// Wrap the textarea
if (container.is('textarea')) {
container.before(editor);
textarea = container;
textarea.addClass('md-input');
editor.append(textarea);
} else {
var rawContent = (typeof toMarkdown == 'function') ? toMarkdown(container.html()) : container.html(),
currentContent = $.trim(rawContent);
// This is some arbitrary content that could be edited
textarea = $('<textarea/>', {
'class': 'md-input',
'val' : currentContent
});
editor.append(textarea);
// Save the editable
editable.el = container;
editable.type = container.prop('tagName').toLowerCase();
editable.content = container.html();
$(container[0].attributes).each(function(){
editable.attrKeys.push(this.nodeName);
editable.attrValues.push(this.nodeValue);
});
// Set editor to blocked the original container
container.replaceWith(editor);
}
var editorFooter = $('<div/>', {
'class': 'md-footer'
}),
createFooter = false,
footer = '';
// Create the footer if savable
if (options.savable) {
createFooter = true;
var saveHandler = 'cmdSave';
// Register handler and callback
handler.push(saveHandler);
callback.push(options.onSave);
editorFooter.append('<button class="btn btn-success" data-provider="'
+ ns
+ '" data-handler="'
+ saveHandler
+ '"><i class="icon icon-white icon-ok"></i> '
+ this.__localize('Save')
+ '</button>');
}
footer = typeof options.footer === 'function' ? options.footer(this) : options.footer;
if ($.trim(footer) !== '') {
createFooter = true;
editorFooter.append(footer);
}
if (createFooter) editor.append(editorFooter);
// Set width
if (options.width && options.width !== 'inherit') {
if (jQuery.isNumeric(options.width)) {
editor.css('display', 'table');
textarea.css('width', options.width + 'px');
} else {
editor.addClass(options.width);
}
}
// Set height
if (options.height && options.height !== 'inherit') {
if (jQuery.isNumeric(options.height)) {
var height = options.height;
if (editorHeader) height = Math.max(0, height - editorHeader.outerHeight());
if (editorFooter) height = Math.max(0, height - editorFooter.outerHeight());
textarea.css('height', height + 'px');
} else {
editor.addClass(options.height);
}
}
// Reference
this.$editor = editor;
this.$textarea = textarea;
this.$editable = editable;
this.$oldContent = this.getContent();
this.__setListener();
// Set editor attributes, data short-hand API and listener
this.$editor.attr('id',(new Date()).getTime());
this.$editor.on('click', '[data-provider="bootstrap-markdown"]', $.proxy(this.__handle, this));
if (this.$element.is(':disabled') || this.$element.is('[readonly]')) {
this.$editor.addClass('md-editor-disabled');
this.disableButtons('all');
}
if (this.eventSupported('keydown') && typeof jQuery.hotkeys === 'object') {
editorHeader.find('[data-provider="bootstrap-markdown"]').each(function() {
var $button = $(this),
hotkey = $button.attr('data-hotkey');
if (hotkey.toLowerCase() !== '') {
textarea.bind('keydown', hotkey, function() {
$button.trigger('click');
return false;
});
}
});
}
if (options.initialstate === 'preview') {
this.showPreview();
} else if (options.initialstate === 'fullscreen' && options.fullscreen.enable) {
this.setFullscreen(true);
}
} else {
this.$editor.show();
}
if (options.autofocus) {
this.$textarea.focus();
this.$editor.addClass('active');
}
if (options.fullscreen.enable && options.fullscreen !== false) {
this.$editor.append('<div class="md-fullscreen-controls">'
+ '<a href="#" class="exit-fullscreen" title="Exit fullscreen"><span class="' + this.__getIcon(options.fullscreen.icons.fullscreenOff) + '">'
+ '</span></a>'
+ '</div>');
this.$editor.on('click', '.exit-fullscreen', function(e) {
e.preventDefault();
instance.setFullscreen(false);
});
}
// hide hidden buttons from options
this.hideButtons(options.hiddenButtons);
// disable disabled buttons from options
this.disableButtons(options.disabledButtons);
// Trigger the onShow hook
options.onShow(this);
return this;
}
, parseContent: function(val) {
var content;
// parse with supported markdown parser
var val = val || this.$textarea.val();
if (this.$options.parser) {
content = this.$options.parser(val);
} else if (typeof markdown == 'object') {
content = markdown.toHTML(val);
} else if (typeof marked == 'function') {
content = marked(val);
} else {
content = val;
}
return content;
}
, showPreview: function() {
var options = this.$options,
container = this.$textarea,
afterContainer = container.next(),
replacementContainer = $('<div/>',{'class':'md-preview','data-provider':'markdown-preview'}),
content,
callbackContent;
if (this.$isPreview == true) {
// Avoid sequenced element creation on missused scenario
// @see https://github.com/toopay/bootstrap-markdown/issues/170
return this;
}
// Give flag that tell the editor enter preview mode
this.$isPreview = true;
// Disable all buttons
this.disableButtons('all').enableButtons('cmdPreview');
// Try to get the content from callback
callbackContent = options.onPreview(this);
// Set the content based from the callback content if string otherwise parse value from textarea
content = typeof callbackContent == 'string' ? callbackContent : this.parseContent();
// Build preview element
replacementContainer.html(content);
if (afterContainer && afterContainer.attr('class') == 'md-footer') {
// If there is footer element, insert the preview container before it
replacementContainer.insertBefore(afterContainer);
} else {
// Otherwise, just append it after textarea
container.parent().append(replacementContainer);
}
// Set the preview element dimensions
replacementContainer.css({
width: container.outerWidth() + 'px',
height: container.outerHeight() + 'px'
});
if (this.$options.resize) {
replacementContainer.css('resize',this.$options.resize);
}
// Hide the last-active textarea
container.hide();
// Attach the editor instances
replacementContainer.data('markdown',this);
if (this.$element.is(':disabled') || this.$element.is('[readonly]')) {
this.$editor.addClass('md-editor-disabled');
this.disableButtons('all');
}
return this;
}
, hidePreview: function() {
// Give flag that tell the editor quit preview mode
this.$isPreview = false;
// Obtain the preview container
var container = this.$editor.find('div[data-provider="markdown-preview"]');
// Remove the preview container
container.remove();
// Enable all buttons
this.enableButtons('all');
// Disable configured disabled buttons
this.disableButtons(this.$options.disabledButtons);
// Back to the editor
this.$textarea.show();
this.__setListener();
return this;
}
, isDirty: function() {
return this.$oldContent != this.getContent();
}
, getContent: function() {
return this.$textarea.val();
}
, setContent: function(content) {
this.$textarea.val(content);
return this;
}
, findSelection: function(chunk) {
var content = this.getContent(), startChunkPosition;
if (startChunkPosition = content.indexOf(chunk), startChunkPosition >= 0 && chunk.length > 0) {
var oldSelection = this.getSelection(), selection;
this.setSelection(startChunkPosition,startChunkPosition+chunk.length);
selection = this.getSelection();
this.setSelection(oldSelection.start,oldSelection.end);
return selection;
} else {
return null;
}
}
, getSelection: function() {
var e = this.$textarea[0];
return (
('selectionStart' in e && function() {
var l = e.selectionEnd - e.selectionStart;
return { start: e.selectionStart, end: e.selectionEnd, length: l, text: e.value.substr(e.selectionStart, l) };
}) ||
/* browser not supported */
function() {
return null;
}
)();
}
, setSelection: function(start,end) {
var e = this.$textarea[0];
return (
('selectionStart' in e && function() {
e.selectionStart = start;
e.selectionEnd = end;
return;
}) ||
/* browser not supported */
function() {
return null;
}
)();
}
, replaceSelection: function(text) {
var e = this.$textarea[0];
return (
('selectionStart' in e && function() {
e.value = e.value.substr(0, e.selectionStart) + text + e.value.substr(e.selectionEnd, e.value.length);
// Set cursor to the last replacement end
e.selectionStart = e.value.length;
return this;
}) ||
/* browser not supported */
function() {
e.value += text;
return jQuery(e);
}
)();
}
, getNextTab: function() {
// Shift the nextTab
if (this.$nextTab.length === 0) {
return null;
} else {
var nextTab, tab = this.$nextTab.shift();
if (typeof tab == 'function') {
nextTab = tab();
} else if (typeof tab == 'object' && tab.length > 0) {
nextTab = tab;
}
return nextTab;
}
}
, setNextTab: function(start,end) {
// Push new selection into nextTab collections
if (typeof start == 'string') {
var that = this;
this.$nextTab.push(function(){
return that.findSelection(start);
});
} else if (typeof start == 'number' && typeof end == 'number') {
var oldSelection = this.getSelection();
this.setSelection(start,end);
this.$nextTab.push(this.getSelection());
this.setSelection(oldSelection.start,oldSelection.end);
}
return;
}
, __parseButtonNameParam: function (names) {
return typeof names == 'string' ?
names.split(' ') :
names;
}
, enableButtons: function(name) {
var buttons = this.__parseButtonNameParam(name),
that = this;
$.each(buttons, function(i, v) {
that.__alterButtons(buttons[i], function (el) {
el.removeAttr('disabled');
});
});
return this;
}
, disableButtons: function(name) {
var buttons = this.__parseButtonNameParam(name),
that = this;
$.each(buttons, function(i, v) {
that.__alterButtons(buttons[i], function (el) {
el.attr('disabled','disabled');
});
});
return this;
}
, hideButtons: function(name) {
var buttons = this.__parseButtonNameParam(name),
that = this;
$.each(buttons, function(i, v) {
that.__alterButtons(buttons[i], function (el) {
el.addClass('hidden');
});
});
return this;
}
, showButtons: function(name) {
var buttons = this.__parseButtonNameParam(name),
that = this;
$.each(buttons, function(i, v) {
that.__alterButtons(buttons[i], function (el) {
el.removeClass('hidden');
});
});
return this;
}
, eventSupported: function(eventName) {
var isSupported = eventName in this.$element;
if (!isSupported) {
this.$element.setAttribute(eventName, 'return;');
isSupported = typeof this.$element[eventName] === 'function';
}
return isSupported;
}
, keyup: function (e) {
var blocked = false;
switch(e.keyCode) {
case 40: // down arrow
case 38: // up arrow
case 16: // shift
case 17: // ctrl
case 18: // alt
break;
case 9: // tab
var nextTab;
if (nextTab = this.getNextTab(),nextTab !== null) {
// Get the nextTab if exists
var that = this;
setTimeout(function(){
that.setSelection(nextTab.start,nextTab.end);
},500);
blocked = true;
} else {
// The next tab memory contains nothing...
// check the cursor position to determine tab action
var cursor = this.getSelection();
if (cursor.start == cursor.end && cursor.end == this.getContent().length) {
// The cursor already reach the end of the content
blocked = false;
} else {
// Put the cursor to the end
this.setSelection(this.getContent().length,this.getContent().length);
blocked = true;
}
}
break;
case 13: // enter
blocked = false;
break;
case 27: // escape
if (this.$isFullscreen) this.setFullscreen(false);
blocked = false;
break;
default:
blocked = false;
}
if (blocked) {
e.stopPropagation();
e.preventDefault();
}
this.$options.onChange(this);
}
, change: function(e) {
this.$options.onChange(this);
return this;
}
, select: function (e) {
this.$options.onSelect(this);
return this;
}
, focus: function (e) {
var options = this.$options,
isHideable = options.hideable,
editor = this.$editor;
editor.addClass('active');
// Blur other markdown(s)
$(document).find('.md-editor').each(function(){
if ($(this).attr('id') !== editor.attr('id')) {
var attachedMarkdown;
if (attachedMarkdown = $(this).find('textarea').data('markdown'),
attachedMarkdown === null) {
attachedMarkdown = $(this).find('div[data-provider="markdown-preview"]').data('markdown');
}
if (attachedMarkdown) {
attachedMarkdown.blur();
}
}
});
// Trigger the onFocus hook
options.onFocus(this);
return this;
}
, blur: function (e) {
var options = this.$options,
isHideable = options.hideable,
editor = this.$editor,
editable = this.$editable;
if (editor.hasClass('active') || this.$element.parent().length === 0) {
editor.removeClass('active');
if (isHideable) {
// Check for editable elements
if (editable.el !== null) {
// Build the original element
var oldElement = $('<'+editable.type+'/>'),
content = this.getContent(),
currentContent = this.parseContent(content);
$(editable.attrKeys).each(function(k,v) {
oldElement.attr(editable.attrKeys[k],editable.attrValues[k]);
});
// Get the editor content
oldElement.html(currentContent);
editor.replaceWith(oldElement);
} else {
editor.hide();
}
}
// Trigger the onBlur hook
options.onBlur(this);
}
return this;
}
};
/* MARKDOWN PLUGIN DEFINITION
* ========================== */
var old = $.fn.markdown;
$.fn.markdown = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('markdown')
, options = typeof option == 'object' && option;
if (!data) $this.data('markdown', (data = new Markdown(this, options)))
})
};
$.fn.markdown.messages = {};
$.fn.markdown.defaults = {
/* Editor Properties */
autofocus: false,
hideable: false,
savable: false,
width: 'inherit',
height: 'inherit',
resize: 'none',
iconlibrary: 'glyph',
language: 'en',
initialstate: 'editor',
parser: null,
/* Buttons Properties */
buttons: [
[{
name: 'groupFont',
data: [{
name: 'cmdBold',
hotkey: 'Ctrl+B',
title: 'Bold',
icon: { glyph: 'glyphicon glyphicon-bold', fa: 'fa fa-bold', 'fa-3': 'icon-bold' },
callback: function(e){
// Give/remove ** surround the selection
var chunk, cursor, selected = e.getSelection(), content = e.getContent();
if (selected.length === 0) {
// Give extra word
chunk = e.__localize('strong text');
} else {
chunk = selected.text;
}
// transform selection and set the cursor into chunked text
if (content.substr(selected.start-2,2) === '**'
&& content.substr(selected.end,2) === '**' ) {
e.setSelection(selected.start-2,selected.end+2);
e.replaceSelection(chunk);
cursor = selected.start-2;
} else {
e.replaceSelection('**'+chunk+'**');
cursor = selected.start+2;
}
// Set the cursor
e.setSelection(cursor,cursor+chunk.length);
}
},{
name: 'cmdItalic',
title: 'Italic',
hotkey: 'Ctrl+I',
icon: { glyph: 'glyphicon glyphicon-italic', fa: 'fa fa-italic', 'fa-3': 'icon-italic' },
callback: function(e){
// Give/remove * surround the selection
var chunk, cursor, selected = e.getSelection(), content = e.getContent();
if (selected.length === 0) {
// Give extra word
chunk = e.__localize('emphasized text');
} else {
chunk = selected.text;
}
// transform selection and set the cursor into chunked text
if (content.substr(selected.start-1,1) === '_'
&& content.substr(selected.end,1) === '_' ) {
e.setSelection(selected.start-1,selected.end+1);
e.replaceSelection(chunk);
cursor = selected.start-1;
} else {
e.replaceSelection('_'+chunk+'_');
cursor = selected.start+1;
}
// Set the cursor
e.setSelection(cursor,cursor+chunk.length);
}
},{
name: 'cmdHeading',
title: 'Heading',
hotkey: 'Ctrl+H',
icon: { glyph: 'glyphicon glyphicon-header', fa: 'fa fa-header', 'fa-3': 'icon-font' },
callback: function(e){
// Append/remove ### surround the selection
var chunk, cursor, selected = e.getSelection(), content = e.getContent(), pointer, prevChar;
if (selected.length === 0) {
// Give extra word
chunk = e.__localize('heading text');
} else {
chunk = selected.text + '\n';
}
// transform selection and set the cursor into chunked text
if ((pointer = 4, content.substr(selected.start-pointer,pointer) === '### ')
|| (pointer = 3, content.substr(selected.start-pointer,pointer) === '###')) {
e.setSelection(selected.start-pointer,selected.end);
e.replaceSelection(chunk);
cursor = selected.start-pointer;
} else if (selected.start > 0 && (prevChar = content.substr(selected.start-1,1), !!prevChar && prevChar != '\n')) {
e.replaceSelection('\n\n### '+chunk);
cursor = selected.start+6;
} else {
// Empty string before element
e.replaceSelection('### '+chunk);
cursor = selected.start+4;
}
// Set the cursor
e.setSelection(cursor,cursor+chunk.length);
}
}]
},{
name: 'groupLink',
data: [{
name: 'cmdUrl',
title: 'URL/Link',
hotkey: 'Ctrl+L',
icon: { glyph: 'glyphicon glyphicon-link', fa: 'fa fa-link', 'fa-3': 'icon-link' },
callback: function(e){
// Give [] surround the selection and prepend the link
var chunk, cursor, selected = e.getSelection(), content = e.getContent(), link;
if (selected.length === 0) {
// Give extra word
chunk = e.__localize('enter link description here');
} else {
chunk = selected.text;
}
link = prompt(e.__localize('Insert Hyperlink'),'http://');
var urlRegex = new RegExp('^((http|https)://|(mailto:)|(//))[a-z0-9]', 'i');
if (link !== null && link !== '' && link !== 'http://' && urlRegex.test(link)) {
var sanitizedLink = $('<div>'+link+'</div>').text();
// transform selection and set the cursor into chunked text
e.replaceSelection('['+chunk+']('+sanitizedLink+')');
cursor = selected.start+1;
// Set the cursor
e.setSelection(cursor,cursor+chunk.length);
}
}
},{
name: 'cmdImage',
title: 'Image',
hotkey: 'Ctrl+G',
icon: { glyph: 'glyphicon glyphicon-picture', fa: 'fa fa-picture-o', 'fa-3': 'icon-picture' },
callback: function(e){
// Give ![] surround the selection and prepend the image link
var chunk, cursor, selected = e.getSelection(), content = e.getContent(), link;
if (selected.length === 0) {
// Give extra word
chunk = e.__localize('enter image description here');
} else {
chunk = selected.text;
}
link = prompt(e.__localize('Insert Image Hyperlink'),'http://');
var urlRegex = new RegExp('^((http|https)://|(//))[a-z0-9]', 'i');
if (link !== null && link !== '' && link !== 'http://' && urlRegex.test(link)) {
var sanitizedLink = $('<div>'+link+'</div>').text();
// transform selection and set the cursor into chunked text
e.replaceSelection('+'")');
cursor = selected.start+2;
// Set the next tab
e.setNextTab(e.__localize('enter image title here'));
// Set the cursor
e.setSelection(cursor,cursor+chunk.length);
}
}
}]
},{
name: 'groupMisc',
data: [{
name: 'cmdList',
hotkey: 'Ctrl+U',
title: 'Unordered List',
icon: { glyph: 'glyphicon glyphicon-list', fa: 'fa fa-list', 'fa-3': 'icon-list-ul' },
callback: function(e){
// Prepend/Give - surround the selection
var chunk, cursor, selected = e.getSelection(), content = e.getContent();
// transform selection and set the cursor into chunked text
if (selected.length === 0) {
// Give extra word
chunk = e.__localize('list text here');
e.replaceSelection('- '+chunk);
// Set the cursor
cursor = selected.start+2;
} else {
if (selected.text.indexOf('\n') < 0) {
chunk = selected.text;
e.replaceSelection('- '+chunk);
// Set the cursor
cursor = selected.start+2;
} else {
var list = [];
list = selected.text.split('\n');
chunk = list[0];
$.each(list,function(k,v) {
list[k] = '- '+v;
});
e.replaceSelection('\n\n'+list.join('\n'));
// Set the cursor
cursor = selected.start+4;
}
}
// Set the cursor
e.setSelection(cursor,cursor+chunk.length);
}
},
{
name: 'cmdListO',
hotkey: 'Ctrl+O',
title: 'Ordered List',
icon: { glyph: 'glyphicon glyphicon-th-list', fa: 'fa fa-list-ol', 'fa-3': 'icon-list-ol' },
callback: function(e) {
// Prepend/Give - surround the selection
var chunk, cursor, selected = e.getSelection(), content = e.getContent();
// transform selection and set the cursor into chunked text
if (selected.length === 0) {
// Give extra word
chunk = e.__localize('list text here');
e.replaceSelection('1. '+chunk);
// Set the cursor
cursor = selected.start+3;
} else {
if (selected.text.indexOf('\n') < 0) {
chunk = selected.text;
e.replaceSelection('1. '+chunk);
// Set the cursor
cursor = selected.start+3;
} else {
var list = [];
list = selected.text.split('\n');
chunk = list[0];
$.each(list,function(k,v) {
list[k] = '1. '+v;
});
e.replaceSelection('\n\n'+list.join('\n'));
// Set the cursor
cursor = selected.start+5;
}
}
// Set the cursor
e.setSelection(cursor,cursor+chunk.length);
}
},
{
name: 'cmdCode',
hotkey: 'Ctrl+K',
title: 'Code',
icon: { glyph: 'glyphicon glyphicon-asterisk', fa: 'fa fa-code', 'fa-3': 'icon-code' },
callback: function(e) {
// Give/remove ** surround the selection
var chunk, cursor, selected = e.getSelection(), content = e.getContent();
if (selected.length === 0) {
// Give extra word
chunk = e.__localize('code text here');
} else {
chunk = selected.text;
}
// transform selection and set the cursor into chunked text
if (content.substr(selected.start-4,4) === '```\n'
&& content.substr(selected.end,4) === '\n```') {
e.setSelection(selected.start-4, selected.end+4);
e.replaceSelection(chunk);
cursor = selected.start-4;
} else if (content.substr(selected.start-1,1) === '`'
&& content.substr(selected.end,1) === '`') {
e.setSelection(selected.start-1,selected.end+1);
e.replaceSelection(chunk);
cursor = selected.start-1;
} else if (content.indexOf('\n') > -1) {
e.replaceSelection('```\n'+chunk+'\n```');
cursor = selected.start+4;
} else {
e.replaceSelection('`'+chunk+'`');
cursor = selected.start+1;
}
// Set the cursor
e.setSelection(cursor,cursor+chunk.length);
}
},
{
name: 'cmdQuote',
hotkey: 'Ctrl+Q',
title: 'Quote',
icon: { glyph: 'glyphicon glyphicon-comment', fa: 'fa fa-quote-left', 'fa-3': 'icon-quote-left' },
callback: function(e) {
// Prepend/Give - surround the selection
var chunk, cursor, selected = e.getSelection(), content = e.getContent();
// transform selection and set the cursor into chunked text
if (selected.length === 0) {
// Give extra word
chunk = e.__localize('quote here');
e.replaceSelection('> '+chunk);
// Set the cursor
cursor = selected.start+2;
} else {
if (selected.text.indexOf('\n') < 0) {
chunk = selected.text;
e.replaceSelection('> '+chunk);
// Set the cursor
cursor = selected.start+2;
} else {
var list = [];
list = selected.text.split('\n');
chunk = list[0];
$.each(list,function(k,v) {
list[k] = '> '+v;
});
e.replaceSelection('\n\n'+list.join('\n'));
// Set the cursor
cursor = selected.start+4;
}
}
// Set the cursor
e.setSelection(cursor,cursor+chunk.length);
}
}]
},{
name: 'groupUtil',
data: [{
name: 'cmdPreview',
toggle: true,
hotkey: 'Ctrl+P',
title: 'Preview',
btnText: 'Preview',
btnClass: 'btn btn-primary btn-sm',
icon: { glyph: 'glyphicon glyphicon-search', fa: 'fa fa-search', 'fa-3': 'icon-search' },
callback: function(e){
// Check the preview mode and toggle based on this flag
var isPreview = e.$isPreview,content;
if (isPreview === false) {
// Give flag that tell the editor enter preview mode
e.showPreview();
} else {
e.hidePreview();
}
}
}]
}]
],
additionalButtons:[], // Place to hook more buttons by code
reorderButtonGroups:[],
hiddenButtons:[], // Default hidden buttons
disabledButtons:[], // Default disabled buttons
footer: '',
fullscreen: {
enable: true,
icons: {
fullscreenOn: {
fa: 'fa fa-expand',
glyph: 'glyphicon glyphicon-fullscreen',
'fa-3': 'icon-resize-full'
},
fullscreenOff: {
fa: 'fa fa-compress',
glyph: 'glyphicon glyphicon-fullscreen',
'fa-3': 'icon-resize-small'
}
}
},
/* Events hook */
onShow: function (e) {},
onPreview: function (e) {},
onSave: function (e) {},
onBlur: function (e) {},
onFocus: function (e) {},
onChange: function(e) {},
onFullscreen: function(e) {},
onSelect: function (e) {}
};
$.fn.markdown.Constructor = Markdown;
/* MARKDOWN NO CONFLICT
* ==================== */
$.fn.markdown.noConflict = function () {
$.fn.markdown = old;
return this;
};
/* MARKDOWN GLOBAL FUNCTION & DATA-API
* ==================================== */
var initMarkdown = function(el) {
var $this = el;
if ($this.data('markdown')) {
$this.data('markdown').showEditor();
return;
}
$this.markdown()
};
var blurNonFocused = function(e) {
var $activeElement = $(document.activeElement);
// Blur event
$(document).find('.md-editor').each(function(){
var $this = $(this),
focused = $activeElement.closest('.md-editor')[0] === this,
attachedMarkdown = $this.find('textarea').data('markdown') ||
$this.find('div[data-provider="markdown-preview"]').data('markdown');
if (attachedMarkdown && !focused) {
attachedMarkdown.blur();
}
})
};
$(document)
.on('click.markdown.data-api', '[data-provide="markdown-editable"]', function (e) {
initMarkdown($(this));
e.preventDefault();
})
.on('click focusin', function (e) {
blurNonFocused(e);
})
.ready(function(){
$('textarea[data-provide="markdown"]').each(function(){
initMarkdown($(this));
})
});
}));