File: erubis

package info (click to toggle)
ruby-erubis 2.7.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,260 kB
  • sloc: ruby: 8,758; ansic: 97; makefile: 72; php: 17
file content (3468 lines) | stat: -rwxr-xr-x 83,019 bytes parent folder | download | duplicates (4)
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
#!/usr/bin/env ruby

###
### $Release: 2.7.0 $
### copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
###

#--begin of require 'erubis/main'
###
### $Release: 2.7.0 $
### copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
###

require 'yaml'
#--begin of require 'erubis'
##
## $Release: 2.7.0 $
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
##

##
## an implementation of eRuby
##
## ex.
##   input = <<'END'
##    <ul>
##     <% for item in @list %>
##      <li><%= item %>
##          <%== item %></li>
##     <% end %>
##    </ul>
##   END
##   list = ['<aaa>', 'b&b', '"ccc"']
##   eruby = Erubis::Eruby.new(input)
##   puts "--- code ---"
##   puts eruby.src
##   puts "--- result ---"
##   context = Erubis::Context.new()   # or new(:list=>list)
##   context[:list] = list
##   puts eruby.evaluate(context)
##
## result:
##   --- source ---
##   _buf = ''; _buf << '<ul>
##   ';  for item in @list 
##    _buf << '  <li>'; _buf << ( item ).to_s; _buf << '
##   '; _buf << '      '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</li>
##   ';  end 
##    _buf << '</ul>
##   ';
##   _buf.to_s
##   --- result ---
##    <ul>
##      <li><aaa>
##          &lt;aaa&gt;</li>
##      <li>b&b
##          b&amp;b</li>
##      <li>"ccc"
##          &quot;ccc&quot;</li>
##    </ul>
##


module Erubis
  VERSION = ('$Release: 2.7.0 $' =~ /([.\d]+)/) && $1
end

#--begin of require 'erubis/engine'
##
## $Release: 2.7.0 $
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
##


#--begin of require 'erubis/generator'
##
## $Release: 2.7.0 $
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
##

#--begin of require 'erubis/util'
##
## $Release: 2.7.0 $
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
##

module Kernel

  ##
  ## raise NotImplementedError
  ##
  def not_implemented     #:doc:
    backtrace = caller()
    method_name = (backtrace.shift =~ /`(\w+)'$/) && $1
    mesg = "class #{self.class.name} must implement abstract method '#{method_name}()'."
    #mesg = "#{self.class.name}##{method_name}() is not implemented."
    err = NotImplementedError.new mesg
    err.set_backtrace backtrace
    raise err
  end
  private :not_implemented

end
#--end of require 'erubis/util'

module Erubis


  ##
  ## code generator, called by Converter module
  ##
  module Generator

    def self.supported_properties()  # :nodoc:
      return [
              [:escapefunc,    nil,    "escape function name"],
            ]
    end

    attr_accessor :escapefunc

    def init_generator(properties={})
      @escapefunc = properties[:escapefunc]
    end


    ## (abstract) escape text string
    ##
    ## ex.
    ##   def escape_text(text)
    ##     return text.dump
    ##     # or return "'" + text.gsub(/['\\]/, '\\\\\&') + "'"
    ##   end
    def escape_text(text)
      not_implemented
    end

    ## return escaped expression code (ex. 'h(...)' or 'htmlspecialchars(...)')
    def escaped_expr(code)
      code.strip!
      return "#{@escapefunc}(#{code})"
    end

    ## (abstract) add @preamble to src
    def add_preamble(src)
      not_implemented
    end

    ## (abstract) add text string to src
    def add_text(src, text)
      not_implemented
    end

    ## (abstract) add statement code to src
    def add_stmt(src, code)
      not_implemented
    end

    ## (abstract) add expression literal code to src. this is called by add_expr().
    def add_expr_literal(src, code)
      not_implemented
    end

    ## (abstract) add escaped expression code to src. this is called by add_expr().
    def add_expr_escaped(src, code)
      not_implemented
    end

    ## (abstract) add expression code to src for debug. this is called by add_expr().
    def add_expr_debug(src, code)
      not_implemented
    end

    ## (abstract) add @postamble to src
    def add_postamble(src)
      not_implemented
    end


  end


end
#--end of require 'erubis/generator'
#--begin of require 'erubis/converter'
##
## $Release: 2.7.0 $
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
##

#--already included require 'erubis/util'

module Erubis


  ##
  ## convert
  ##
  module Converter

    attr_accessor :preamble, :postamble, :escape

    def self.supported_properties    # :nodoc:
      return [
              [:preamble,  nil,    "preamble (no preamble when false)"],
              [:postamble, nil,    "postamble (no postamble when false)"],
              [:escape,    nil,    "escape expression or not in default"],
             ]
    end

    def init_converter(properties={})
      @preamble  = properties[:preamble]
      @postamble = properties[:postamble]
      @escape    = properties[:escape]
    end

    ## convert input string into target language
    def convert(input)
      codebuf = ""    # or []
      @preamble.nil? ? add_preamble(codebuf) : (@preamble && (codebuf << @preamble))
      convert_input(codebuf, input)
      @postamble.nil? ? add_postamble(codebuf) : (@postamble && (codebuf << @postamble))
      @_proc = nil    # clear cached proc object
      return codebuf  # or codebuf.join()
    end

    protected

    ##
    ## detect spaces at beginning of line
    ##
    def detect_spaces_at_bol(text, is_bol)
      lspace = nil
      if text.empty?
        lspace = "" if is_bol
      elsif text[-1] == ?\n
        lspace = ""
      else
        rindex = text.rindex(?\n)
        if rindex
          s = text[rindex+1..-1]
          if s =~ /\A[ \t]*\z/
            lspace = s
            #text = text[0..rindex]
            text[rindex+1..-1] = ''
          end
        else
          if is_bol && text =~ /\A[ \t]*\z/
            #lspace = text
            #text = nil
            lspace = text.dup
            text[0..-1] = ''
          end
        end
      end
      return lspace
    end

    ##
    ## (abstract) convert input to code
    ##
    def convert_input(codebuf, input)
      not_implemented
    end

  end


  module Basic
  end


  ##
  ## basic converter which supports '<% ... %>' notation.
  ##
  module Basic::Converter
    include Erubis::Converter

    def self.supported_properties    # :nodoc:
      return [
              [:pattern,  '<% %>', "embed pattern"],
              [:trim,      true,   "trim spaces around <% ... %>"],
             ]
    end

    attr_accessor :pattern, :trim

    def init_converter(properties={})
      super(properties)
      @pattern = properties[:pattern]
      @trim    = properties[:trim] != false
    end

    protected

    ## return regexp of pattern to parse eRuby script
    def pattern_regexp(pattern)
      @prefix, @postfix = pattern.split()   # '<% %>' => '<%', '%>'
      #return /(.*?)(^[ \t]*)?#{@prefix}(=+|\#)?(.*?)-?#{@postfix}([ \t]*\r?\n)?/m
      #return /(^[ \t]*)?#{@prefix}(=+|\#)?(.*?)-?#{@postfix}([ \t]*\r?\n)?/m
      return /#{@prefix}(=+|-|\#|%)?(.*?)([-=])?#{@postfix}([ \t]*\r?\n)?/m
    end
    module_function :pattern_regexp

    #DEFAULT_REGEXP = /(.*?)(^[ \t]*)?<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m
    #DEFAULT_REGEXP = /(^[ \t]*)?<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m
    #DEFAULT_REGEXP = /<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m
    DEFAULT_REGEXP = pattern_regexp('<% %>')

    public

    def convert_input(src, input)
      pat = @pattern
      regexp = pat.nil? || pat == '<% %>' ? DEFAULT_REGEXP : pattern_regexp(pat)
      pos = 0
      is_bol = true     # is beginning of line
      input.scan(regexp) do |indicator, code, tailch, rspace|
        match = Regexp.last_match()
        len  = match.begin(0) - pos
        text = input[pos, len]
        pos  = match.end(0)
        ch   = indicator ? indicator[0] : nil
        lspace = ch == ?= ? nil : detect_spaces_at_bol(text, is_bol)
        is_bol = rspace ? true : false
        add_text(src, text) if text && !text.empty?
        ## * when '<%= %>', do nothing
        ## * when '<% %>' or '<%# %>', delete spaces iff only spaces are around '<% %>'
        if ch == ?=              # <%= %>
          rspace = nil if tailch && !tailch.empty?
          add_text(src, lspace) if lspace
          add_expr(src, code, indicator)
          add_text(src, rspace) if rspace
        elsif ch == ?\#          # <%# %>
          n = code.count("\n") + (rspace ? 1 : 0)
          if @trim && lspace && rspace
            add_stmt(src, "\n" * n)
          else
            add_text(src, lspace) if lspace
            add_stmt(src, "\n" * n)
            add_text(src, rspace) if rspace
          end
        elsif ch == ?%           # <%% %>
          s = "#{lspace}#{@prefix||='<%'}#{code}#{tailch}#{@postfix||='%>'}#{rspace}"
          add_text(src, s)
        else                     # <% %>
          if @trim && lspace && rspace
            add_stmt(src, "#{lspace}#{code}#{rspace}")
          else
            add_text(src, lspace) if lspace
            add_stmt(src, code)
            add_text(src, rspace) if rspace
          end
        end
      end
      #rest = $' || input                        # ruby1.8
      rest = pos == 0 ? input : input[pos..-1]   # ruby1.9
      add_text(src, rest)
    end

    ## add expression code to src
    def add_expr(src, code, indicator)
      case indicator
      when '='
        @escape ? add_expr_escaped(src, code) : add_expr_literal(src, code)
      when '=='
        @escape ? add_expr_literal(src, code) : add_expr_escaped(src, code)
      when '==='
        add_expr_debug(src, code)
      end
    end

  end


  module PI
  end

  ##
  ## Processing Instructions (PI) converter for XML.
  ## this class converts '<?rb ... ?>' and '${...}' notation.
  ##
  module PI::Converter
    include Erubis::Converter

    def self.desc   # :nodoc:
      "use processing instructions (PI) instead of '<% %>'"
    end

    def self.supported_properties    # :nodoc:
      return [
              [:trim,      true,   "trim spaces around <% ... %>"],
              [:pi,        'rb',   "PI (Processing Instrunctions) name"],
              [:embchar,   '@',    "char for embedded expression pattern('@{...}@')"],
              [:pattern,  '<% %>', "embed pattern"],
             ]
    end

    attr_accessor :pi, :prefix

    def init_converter(properties={})
      super(properties)
      @trim    = properties.fetch(:trim, true)
      @pi      = properties[:pi] if properties[:pi]
      @embchar = properties[:embchar] || '@'
      @pattern = properties[:pattern]
      @pattern = '<% %>' if @pattern.nil?  #|| @pattern == true
    end

    def convert(input)
      code = super(input)
      return @header || @footer ? "#{@header}#{code}#{@footer}" : code
    end

    protected

    def convert_input(codebuf, input)
      unless @regexp
        @pi ||= 'e'
        ch = Regexp.escape(@embchar)
        if @pattern
          left, right = @pattern.split(' ')
          @regexp = /<\?#{@pi}(?:-(\w+))?(\s.*?)\?>([ \t]*\r?\n)?|#{ch}(!*)?\{(.*?)\}#{ch}|#{left}(=+)(.*?)#{right}/m
        else
          @regexp = /<\?#{@pi}(?:-(\w+))?(\s.*?)\?>([ \t]*\r?\n)?|#{ch}(!*)?\{(.*?)\}#{ch}/m
        end
      end
      #
      is_bol = true
      pos = 0
      input.scan(@regexp) do |pi_arg, stmt, rspace,
                              indicator1, expr1, indicator2, expr2|
        match = Regexp.last_match
        len = match.begin(0) - pos
        text = input[pos, len]
        pos = match.end(0)
        lspace = stmt ? detect_spaces_at_bol(text, is_bol) : nil
        is_bol = stmt && rspace ? true : false
        add_text(codebuf, text) # unless text.empty?
        #
        if stmt
          if @trim && lspace && rspace
            add_pi_stmt(codebuf, "#{lspace}#{stmt}#{rspace}", pi_arg)
          else
            add_text(codebuf, lspace) if lspace
            add_pi_stmt(codebuf, stmt, pi_arg)
            add_text(codebuf, rspace) if rspace
          end
        else
          add_pi_expr(codebuf, expr1 || expr2, indicator1 || indicator2)
        end
      end
      #rest = $' || input                        # ruby1.8
      rest = pos == 0 ? input : input[pos..-1]   # ruby1.9
      add_text(codebuf, rest)
    end

    #--
    #def convert_input(codebuf, input)
    #  parse_stmts(codebuf, input)
    #  #parse_stmts2(codebuf, input)
    #end
    #
    #def parse_stmts(codebuf, input)
    #  #regexp = pattern_regexp(@pattern)
    #  @pi ||= 'e'
    #  @stmt_pattern ||= /<\?#{@pi}(?:-(\w+))?(\s.*?)\?>([ \t]*\r?\n)?/m
    #  is_bol = true
    #  pos = 0
    #  input.scan(@stmt_pattern) do |pi_arg, code, rspace|
    #    match = Regexp.last_match
    #    len  = match.begin(0) - pos
    #    text = input[pos, len]
    #    pos  = match.end(0)
    #    lspace = detect_spaces_at_bol(text, is_bol)
    #    is_bol = rspace ? true : false
    #    parse_exprs(codebuf, text) # unless text.empty?
    #    if @trim && lspace && rspace
    #      add_pi_stmt(codebuf, "#{lspace}#{code}#{rspace}", pi_arg)
    #    else
    #      add_text(codebuf, lspace)
    #      add_pi_stmt(codebuf, code, pi_arg)
    #      add_text(codebuf, rspace)
    #    end
    #  end
    #  rest = $' || input
    #  parse_exprs(codebuf, rest)
    #end
    #
    #def parse_exprs(codebuf, input)
    #  unless @expr_pattern
    #    ch = Regexp.escape(@embchar)
    #    if @pattern
    #      left, right = @pattern.split(' ')
    #      @expr_pattern = /#{ch}(!*)?\{(.*?)\}#{ch}|#{left}(=+)(.*?)#{right}/
    #    else
    #      @expr_pattern = /#{ch}(!*)?\{(.*?)\}#{ch}/
    #    end
    #  end
    #  pos = 0
    #  input.scan(@expr_pattern) do |indicator1, code1, indicator2, code2|
    #    indicator = indicator1 || indicator2
    #    code = code1 || code2
    #    match = Regexp.last_match
    #    len  = match.begin(0) - pos
    #    text = input[pos, len]
    #    pos  = match.end(0)
    #    add_text(codebuf, text) # unless text.empty?
    #    add_pi_expr(codebuf, code, indicator)
    #  end
    #  rest = $' || input
    #  add_text(codebuf, rest)
    #end
    #++

    def add_pi_stmt(codebuf, code, pi_arg)  # :nodoc:
      case pi_arg
      when nil      ;  add_stmt(codebuf, code)
      when 'header' ;  @header = code
      when 'footer' ;  @footer = code
      when 'comment';  add_stmt(codebuf, "\n" * code.count("\n"))
      when 'value'  ;  add_expr_literal(codebuf, code)
      else          ;  add_stmt(codebuf, code)
      end
    end

    def add_pi_expr(codebuf, code, indicator)  # :nodoc:
      case indicator
      when nil, '', '=='    # @{...}@ or <%== ... %>
        @escape == false ? add_expr_literal(codebuf, code) : add_expr_escaped(codebuf, code)
      when '!', '='         # @!{...}@ or <%= ... %>
        @escape == false ? add_expr_escaped(codebuf, code) : add_expr_literal(codebuf, code)
      when '!!', '==='      # @!!{...}@ or <%=== ... %>
        add_expr_debug(codebuf, code)
      else
        # ignore
      end
    end

  end


end
#--end of require 'erubis/converter'
#--begin of require 'erubis/evaluator'
##
## $Release: 2.7.0 $
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
##

#--begin of require 'erubis/error'
##
## $Release: 2.7.0 $
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
##

module Erubis


  ##
  ## base error class
  ##
  class ErubisError < StandardError
  end


  ##
  ## raised when method or function is not supported
  ##
  class NotSupportedError < ErubisError
  end


end
#--end of require 'erubis/error'
#--begin of require 'erubis/context'
##
## $Release: 2.7.0 $
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
##


module Erubis


  ##
  ## context object for Engine#evaluate
  ##
  ## ex.
  ##   template = <<'END'
  ##   Hello <%= @user %>!
  ##   <% for item in @list %>
  ##    - <%= item %>
  ##   <% end %>
  ##   END
  ##
  ##   context = Erubis::Context.new(:user=>'World', :list=>['a','b','c'])
  ##   # or
  ##   # context = Erubis::Context.new
  ##   # context[:user] = 'World'
  ##   # context[:list] = ['a', 'b', 'c']
  ##
  ##   eruby = Erubis::Eruby.new(template)
  ##   print eruby.evaluate(context)
  ##
  class Context
    include Enumerable

    def initialize(hash=nil)
      hash.each do |name, value|
        self[name] = value
      end if hash
    end

    def [](key)
      return instance_variable_get("@#{key}")
    end

    def []=(key, value)
      return instance_variable_set("@#{key}", value)
    end

    def keys
      return instance_variables.collect { |name| name[1..-1] }
    end

    def each
      instance_variables.each do |name|
        key = name[1..-1]
        value = instance_variable_get(name)
        yield(key, value)
      end
    end

    def to_hash
      hash = {}
      self.keys.each { |key| hash[key] = self[key] }
      return hash
    end

    def update(context_or_hash)
      arg = context_or_hash
      if arg.is_a?(Hash)
        arg.each do |key, val|
          self[key] = val
        end
      else
        arg.instance_variables.each do |varname|
          key = varname[1..-1]
          val = arg.instance_variable_get(varname)
          self[key] = val
        end
      end
    end

  end


end
#--end of require 'erubis/context'


module Erubis

  EMPTY_BINDING = binding()


  ##
  ## evaluate code
  ##
  module Evaluator

    def self.supported_properties    # :nodoc:
      return []
    end

    attr_accessor :src, :filename

    def init_evaluator(properties)
      @filename = properties[:filename]
    end

    def result(*args)
      raise NotSupportedError.new("evaluation of code except Ruby is not supported.")
    end

    def evaluate(*args)
      raise NotSupportedError.new("evaluation of code except Ruby is not supported.")
    end

  end


  ##
  ## evaluator for Ruby
  ##
  module RubyEvaluator
    include Evaluator

    def self.supported_properties    # :nodoc:
      list = Evaluator.supported_properties
      return list
    end

    ## eval(@src) with binding object
    def result(_binding_or_hash=TOPLEVEL_BINDING)
      _arg = _binding_or_hash
      if _arg.is_a?(Hash)
        _b = binding()
        eval _arg.collect{|k,v| "#{k} = _arg[#{k.inspect}]; "}.join, _b
      elsif _arg.is_a?(Binding)
        _b = _arg
      elsif _arg.nil?
        _b = binding()
      else
        raise ArgumentError.new("#{self.class.name}#result(): argument should be Binding or Hash but passed #{_arg.class.name} object.")
      end
      return eval(@src, _b, (@filename || '(erubis'))
    end

    ## invoke context.instance_eval(@src)
    def evaluate(_context=Context.new)
      _context = Context.new(_context) if _context.is_a?(Hash)
      #return _context.instance_eval(@src, @filename || '(erubis)')
      #@_proc ||= eval("proc { #{@src} }", Erubis::EMPTY_BINDING, @filename || '(erubis)')
      @_proc ||= eval("proc { #{@src} }", binding(), @filename || '(erubis)')
      return _context.instance_eval(&@_proc)
    end

    ## if object is an Class or Module then define instance method to it,
    ## else define singleton method to it.
    def def_method(object, method_name, filename=nil)
      m = object.is_a?(Module) ? :module_eval : :instance_eval
      object.__send__(m, "def #{method_name}; #{@src}; end", filename || @filename || '(erubis)')
    end


  end


end
#--end of require 'erubis/evaluator'
#--already included require 'erubis/context'


module Erubis


  ##
  ## (abstract) abstract engine class.
  ## subclass must include evaluator and converter module.
  ##
  class Engine
    #include Evaluator
    #include Converter
    #include Generator

    def initialize(input=nil, properties={})
      #@input = input
      init_generator(properties)
      init_converter(properties)
      init_evaluator(properties)
      @src    = convert(input) if input
    end


    ##
    ## convert input string and set it to @src
    ##
    def convert!(input)
      @src = convert(input)
    end


    ##
    ## load file, write cache file, and return engine object.
    ## this method create code cache file automatically.
    ## cachefile name can be specified with properties[:cachename],
    ## or filname + 'cache' is used as default.
    ##
    def self.load_file(filename, properties={})
      cachename = properties[:cachename] || (filename + '.cache')
      properties[:filename] = filename
      timestamp = File.mtime(filename)
      if test(?f, cachename) && timestamp == File.mtime(cachename)
        engine = self.new(nil, properties)
        engine.src = File.read(cachename)
      else
        input = File.open(filename, 'rb') {|f| f.read }
        engine = self.new(input, properties)
        tmpname = cachename + rand().to_s[1,8]
        File.open(tmpname, 'wb') {|f| f.write(engine.src) }
        File.rename(tmpname, cachename)
        File.utime(timestamp, timestamp, cachename)
      end
      engine.src.untaint   # ok?
      return engine
    end


    ##
    ## helper method to convert and evaluate input text with context object.
    ## context may be Binding, Hash, or Object.
    ##
    def process(input, context=nil, filename=nil)
      code = convert(input)
      filename ||= '(erubis)'
      if context.is_a?(Binding)
        return eval(code, context, filename)
      else
        context = Context.new(context) if context.is_a?(Hash)
        return context.instance_eval(code, filename)
      end
    end


    ##
    ## helper method evaluate Proc object with contect object.
    ## context may be Binding, Hash, or Object.
    ##
    def process_proc(proc_obj, context=nil, filename=nil)
      if context.is_a?(Binding)
        filename ||= '(erubis)'
        return eval(proc_obj, context, filename)
      else
        context = Context.new(context) if context.is_a?(Hash)
        return context.instance_eval(&proc_obj)
      end
    end


  end  # end of class Engine


  ##
  ## (abstract) base engine class for Eruby, Eperl, Ejava, and so on.
  ## subclass must include generator.
  ##
  class Basic::Engine < Engine
    include Evaluator
    include Basic::Converter
    include Generator
  end


  class PI::Engine < Engine
    include Evaluator
    include PI::Converter
    include Generator
  end


end
#--end of require 'erubis/engine'
#require 'erubis/generator'
#require 'erubis/converter'
#require 'erubis/evaluator'
#require 'erubis/error'
#require 'erubis/context'
#requier 'erubis/util'
#--begin of require 'erubis/helper'
##
## $Release: 2.7.0 $
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
##


module Erubis

  ##
  ## helper for xml
  ##
  module XmlHelper

    module_function

    ESCAPE_TABLE = {
      '&' => '&amp;',
      '<' => '&lt;',
      '>' => '&gt;',
      '"' => '&quot;',
      "'" => '&#039;',
    }

    def escape_xml(value)
      value.to_s.gsub(/[&<>"]/) { |s| ESCAPE_TABLE[s] }   # or /[&<>"']/
      #value.to_s.gsub(/[&<>"]/) { ESCAPE_TABLE[$&] }
    end

    def escape_xml2(value)
      return value.to_s.gsub(/\&/,'&amp;').gsub(/</,'&lt;').gsub(/>/,'&gt;').gsub(/"/,'&quot;')
    end

    alias h escape_xml
    alias html_escape escape_xml

    def url_encode(str)
      return str.gsub(/[^-_.a-zA-Z0-9]+/) { |s|
        s.unpack('C*').collect { |i| "%%%02X" % i }.join
      }
    end

    alias u url_encode

  end


end
#--end of require 'erubis/helper'
#--begin of require 'erubis/enhancer'
##
## $Release: 2.7.0 $
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
##


module Erubis


  ##
  ## switch '<%= ... %>' to escaped and '<%== ... %>' to unescaped
  ##
  ## ex.
  ##   class XmlEruby < Eruby
  ##     include EscapeEnhancer
  ##   end
  ##
  ## this is language-indenedent.
  ##
  module EscapeEnhancer

    def self.desc   # :nodoc:
      "switch '<%= %>' to escaped and '<%== %>' to unescaped"
    end

    #--
    #def self.included(klass)
    #  klass.class_eval <<-END
    #    alias _add_expr_literal add_expr_literal
    #    alias _add_expr_escaped add_expr_escaped
    #    alias add_expr_literal _add_expr_escaped
    #    alias add_expr_escaped _add_expr_literal
    #  END
    #end
    #++

    def add_expr(src, code, indicator)
      case indicator
      when '='
        @escape ? add_expr_literal(src, code) : add_expr_escaped(src, code)
      when '=='
        @escape ? add_expr_escaped(src, code) : add_expr_literal(src, code)
      when '==='
        add_expr_debug(src, code)
      end
    end

  end


  #--
  ## (obsolete)
  #module FastEnhancer
  #end
  #++


  ##
  ## use $stdout instead of string
  ##
  ## this is only for Eruby.
  ##
  module StdoutEnhancer

    def self.desc   # :nodoc:
      "use $stdout instead of array buffer or string buffer"
    end

    def add_preamble(src)
      src << "#{@bufvar} = $stdout;"
    end

    def add_postamble(src)
      src << "\n''\n"
    end

  end


  ##
  ## use print statement instead of '_buf << ...'
  ##
  ## this is only for Eruby.
  ##
  module PrintOutEnhancer

    def self.desc   # :nodoc:
      "use print statement instead of '_buf << ...'"
    end

    def add_preamble(src)
    end

    def add_text(src, text)
      src << " print '#{escape_text(text)}';" unless text.empty?
    end

    def add_expr_literal(src, code)
      src << " print((#{code}).to_s);"
    end

    def add_expr_escaped(src, code)
      src << " print #{escaped_expr(code)};"
    end

    def add_postamble(src)
      src << "\n" unless src[-1] == ?\n
    end

  end


  ##
  ## enable print function
  ##
  ## Notice: use Eruby#evaluate() and don't use Eruby#result()
  ## to be enable print function.
  ##
  ## this is only for Eruby.
  ##
  module PrintEnabledEnhancer

    def self.desc   # :nodoc:
      "enable to use print function in '<% %>'"
    end

    def add_preamble(src)
      src << "@_buf = "
      super
    end

    def print(*args)
      args.each do |arg|
        @_buf << arg.to_s
      end
    end

    def evaluate(context=nil)
      _src = @src
      if context.is_a?(Hash)
        context.each do |key, val| instance_variable_set("@#{key}", val) end
      elsif context
        context.instance_variables.each do |name|
          instance_variable_set(name, context.instance_variable_get(name))
        end
      end
      return instance_eval(_src, (@filename || '(erubis)'))
    end

  end


  ##
  ## return array instead of string
  ##
  ## this is only for Eruby.
  ##
  module ArrayEnhancer

    def self.desc   # :nodoc:
      "return array instead of string"
    end

    def add_preamble(src)
      src << "#{@bufvar} = [];"
    end

    def add_postamble(src)
      src << "\n" unless src[-1] == ?\n
      src << "#{@bufvar}\n"
    end

  end


  ##
  ## use an Array object as buffer (included in Eruby by default)
  ##
  ## this is only for Eruby.
  ##
  module ArrayBufferEnhancer

    def self.desc   # :nodoc:
      "use an Array object for buffering (included in Eruby class)"
    end

    def add_preamble(src)
      src << "_buf = [];"
    end

    def add_postamble(src)
      src << "\n" unless src[-1] == ?\n
      src << "_buf.join\n"
    end

  end


  ##
  ## use String class for buffering
  ##
  ## this is only for Eruby.
  ##
  module StringBufferEnhancer

    def self.desc   # :nodoc:
      "use a String object for buffering"
    end

    def add_preamble(src)
      src << "#{@bufvar} = '';"
    end

    def add_postamble(src)
      src << "\n" unless src[-1] == ?\n
      src << "#{@bufvar}.to_s\n"
    end

  end


  ##
  ## use StringIO class for buffering
  ##
  ## this is only for Eruby.
  ##
  module StringIOEnhancer  # :nodoc:

    def self.desc   # :nodoc:
      "use a StringIO object for buffering"
    end

    def add_preamble(src)
      src << "#{@bufvar} = StringIO.new;"
    end

    def add_postamble(src)
      src << "\n" unless src[-1] == ?\n
      src << "#{@bufvar}.string\n"
    end

  end


  ##
  ## set buffer variable name to '_erbout' as well as '_buf'
  ##
  ## this is only for Eruby.
  ##
  module ErboutEnhancer

    def self.desc   # :nodoc:
      "set '_erbout = _buf = \"\";' to be compatible with ERB."
    end

    def add_preamble(src)
      src << "_erbout = #{@bufvar} = '';"
    end

    def add_postamble(src)
      src << "\n" unless src[-1] == ?\n
      src << "#{@bufvar}.to_s\n"
    end

  end


  ##
  ## remove text and leave code, especially useful when debugging.
  ##
  ## ex.
  ##   $ erubis -s -E NoText file.eruby | more
  ##
  ## this is language independent.
  ##
  module NoTextEnhancer

    def self.desc   # :nodoc:
      "remove text and leave code (useful when debugging)"
    end

    def add_text(src, text)
      src << ("\n" * text.count("\n"))
      if text[-1] != ?\n
        text =~ /^(.*?)\z/
        src << (' ' * $1.length)
      end
    end

  end


  ##
  ## remove code and leave text, especially useful when validating HTML tags.
  ##
  ## ex.
  ##   $ erubis -s -E NoCode file.eruby | tidy -errors
  ##
  ## this is language independent.
  ##
  module NoCodeEnhancer

    def self.desc   # :nodoc:
      "remove code and leave text (useful when validating HTML)"
    end

    def add_preamble(src)
    end

    def add_postamble(src)
    end

    def add_text(src, text)
      src << text
    end

    def add_expr(src, code, indicator)
      src << "\n" * code.count("\n")
    end

    def add_stmt(src, code)
      src << "\n" * code.count("\n")
    end

  end


  ##
  ## get convert faster, but spaces around '<%...%>' are not trimmed.
  ##
  ## this is language-independent.
  ##
  module SimplifyEnhancer

    def self.desc   # :nodoc:
      "get convert faster but leave spaces around '<% %>'"
    end

    #DEFAULT_REGEXP = /(^[ \t]*)?<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m
    SIMPLE_REGEXP = /<%(=+|\#)?(.*?)-?%>/m

    def convert(input)
      src = ""
      add_preamble(src)
      #regexp = pattern_regexp(@pattern)
      pos = 0
      input.scan(SIMPLE_REGEXP) do |indicator, code|
        match = Regexp.last_match
        index = match.begin(0)
        text  = input[pos, index - pos]
        pos   = match.end(0)
        add_text(src, text)
        if !indicator              # <% %>
          add_stmt(src, code)
        elsif indicator[0] == ?\#  # <%# %>
          n = code.count("\n")
          add_stmt(src, "\n" * n)
        else                       # <%= %>
          add_expr(src, code, indicator)
        end
      end
      #rest = $' || input                      # ruby1.8
      rest = pos == 0 ? input : input[pos..-1]  # ruby1.9
      add_text(src, rest)
      add_postamble(src)
      return src
    end

  end


  ##
  ## enable to use other embedded expression pattern (default is '\[= =\]').
  ##
  ## notice! this is an experimental. spec may change in the future.
  ##
  ## ex.
  ##   input = <<END
  ##   <% for item in list %>
  ##     <%= item %> : <%== item %>
  ##     [= item =] : [== item =]
  ##   <% end %>
  ##   END
  ##
  ##   class BiPatternEruby
  ##     include BiPatternEnhancer
  ##   end
  ##   eruby = BiPatternEruby.new(input, :bipattern=>'\[= =\]')
  ##   list = ['<a>', 'b&b', '"c"']
  ##   print eruby.result(binding())
  ##
  ##   ## output
  ##     <a> : &lt;a&gt;
  ##     <a> : &lt;a&gt;
  ##     b&b : b&amp;b
  ##     b&b : b&amp;b
  ##     "c" : &quot;c&quot;
  ##     "c" : &quot;c&quot;
  ##
  ## this is language independent.
  ##
  module BiPatternEnhancer

    def self.desc   # :nodoc:
      "another embedded expression pattern (default '\[= =\]')."
    end

    def initialize(input, properties={})
      self.bipattern = properties[:bipattern]    # or '\$\{ \}'
      super
    end

    ## when pat is nil then '\[= =\]' is used
    def bipattern=(pat)   # :nodoc:
      @bipattern = pat || '\[= =\]'
      pre, post = @bipattern.split()
      @bipattern_regexp = /(.*?)#{pre}(=*)(.*?)#{post}/m
    end

    def add_text(src, text)
      return unless text
      m = nil
      text.scan(@bipattern_regexp) do |txt, indicator, code|
        m = Regexp.last_match
        super(src, txt)
        add_expr(src, code, '=' + indicator)
      end
      #rest = $' || text                    # ruby1.8
      rest = m ? text[m.end(0)..-1] : text  # ruby1.9
      super(src, rest)
    end

  end


  ##
  ## regards lines starting with '^[ \t]*%' as program code
  ##
  ## in addition you can specify prefix character (default '%')
  ##
  ## this is language-independent.
  ##
  module PrefixedLineEnhancer

    def self.desc   # :nodoc:
      "regard lines matched to '^[ \t]*%' as program code"
    end

    def init_generator(properties={})
      super
      @prefixchar = properties[:prefixchar]
    end

    def add_text(src, text)
      unless @prefixrexp
        @prefixchar ||= '%'
        @prefixrexp = Regexp.compile("^([ \\t]*)\\#{@prefixchar}(.*?\\r?\\n)")
      end
      pos = 0
      text2 = ''
      text.scan(@prefixrexp) do
        space = $1
        line  = $2
        space, line = '', $1 unless $2
        match = Regexp.last_match
        len   = match.begin(0) - pos
        str   = text[pos, len]
        pos   = match.end(0)
        if text2.empty?
          text2 = str
        else
          text2 << str
        end
        if line[0, 1] == @prefixchar
          text2 << space << line
        else
          super(src, text2)
          text2 = ''
          add_stmt(src, space + line)
        end
      end
      #rest = pos == 0 ? text : $'             # ruby1.8
      rest = pos == 0 ? text : text[pos..-1]   # ruby1.9
      unless text2.empty?
        text2 << rest if rest
        rest = text2
      end
      super(src, rest)
    end

  end


  ##
  ## regards lines starting with '%' as program code
  ##
  ## this is for compatibility to eruby and ERB.
  ##
  ## this is language-independent.
  ##
  module PercentLineEnhancer
    include PrefixedLineEnhancer

    def self.desc   # :nodoc:
      "regard lines starting with '%' as program code"
    end

    #--
    #def init_generator(properties={})
    #  super
    #  @prefixchar = '%'
    #  @prefixrexp = /^\%(.*?\r?\n)/
    #end
    #++

    def add_text(src, text)
      unless @prefixrexp
        @prefixchar = '%'
        @prefixrexp = /^\%(.*?\r?\n)/
      end
      super(src, text)
    end

  end


  ##
  ## [experimental] allow header and footer in eRuby script
  ##
  ## ex.
  ##   ====================
  ##   ## without header and footer
  ##   $ cat ex1.eruby
  ##   <% def list_items(list) %>
  ##   <%   for item in list %>
  ##   <li><%= item %></li>
  ##   <%   end %>
  ##   <% end %>
  ##
  ##   $ erubis -s ex1.eruby
  ##   _buf = []; def list_items(list)
  ##   ;   for item in list
  ##   ; _buf << '<li>'; _buf << ( item ).to_s; _buf << '</li>
  ##   ';   end
  ##   ; end
  ##   ;
  ##   _buf.join
  ##
  ##   ## with header and footer
  ##   $ cat ex2.eruby
  ##   <!--#header:
  ##   def list_items(list)
  ##    #-->
  ##   <%  for item in list %>
  ##   <li><%= item %></li>
  ##   <%  end %>
  ##   <!--#footer:
  ##   end
  ##    #-->
  ##
  ##   $ erubis -s -c HeaderFooterEruby ex4.eruby
  ##
  ##   def list_items(list)
  ##    _buf = []; _buf << '
  ##   ';  for item in list
  ##   ; _buf << '<li>'; _buf << ( item ).to_s; _buf << '</li>
  ##   ';  end
  ##   ; _buf << '
  ##   ';
  ##   _buf.join
  ##   end
  ##
  ##   ====================
  ##
  ## this is language-independent.
  ##
  module HeaderFooterEnhancer

    def self.desc   # :nodoc:
      "allow header/footer in document (ex. '<!--#header: #-->')"
    end

    HEADER_FOOTER_PATTERN = /(.*?)(^[ \t]*)?<!--\#(\w+):(.*?)\#-->([ \t]*\r?\n)?/m

    def add_text(src, text)
      m = nil
      text.scan(HEADER_FOOTER_PATTERN) do |txt, lspace, word, content, rspace|
        m = Regexp.last_match
        flag_trim = @trim && lspace && rspace
        super(src, txt)
        content = "#{lspace}#{content}#{rspace}" if flag_trim
        super(src, lspace) if !flag_trim && lspace
        instance_variable_set("@#{word}", content)
        super(src, rspace) if !flag_trim && rspace
      end
      #rest = $' || text                    # ruby1.8
      rest = m ? text[m.end(0)..-1] : text  # ruby1.9
      super(src, rest)
    end

    attr_accessor :header, :footer

    def convert(input)
      source = super
      return @src = "#{@header}#{source}#{@footer}"
    end

  end


  ##
  ## delete indentation of HTML.
  ##
  ## this is language-independent.
  ##
  module DeleteIndentEnhancer

    def self.desc   # :nodoc:
      "delete indentation of HTML."
    end

    def convert_input(src, input)
      input = input.gsub(/^[ \t]+</, '<')
      super(src, input)
    end

  end


  ##
  ## convert "<h1><%=title%></h1>" into "_buf << %Q`<h1>#{title}</h1>`"
  ##
  ## this is only for Eruby.
  ##
  module InterpolationEnhancer

    def self.desc   # :nodoc:
      "convert '<p><%=text%></p>' into '_buf << %Q`<p>\#{text}</p>`'"
    end

    def convert_input(src, input)
      pat = @pattern
      regexp = pat.nil? || pat == '<% %>' ? Basic::Converter::DEFAULT_REGEXP : pattern_regexp(pat)
      pos = 0
      is_bol = true     # is beginning of line
      str = ''
      input.scan(regexp) do |indicator, code, tailch, rspace|
        match = Regexp.last_match()
        len  = match.begin(0) - pos
        text = input[pos, len]
        pos  = match.end(0)
        ch   = indicator ? indicator[0] : nil
        lspace = ch == ?= ? nil : detect_spaces_at_bol(text, is_bol)
        is_bol = rspace ? true : false
        _add_text_to_str(str, text)
        ## * when '<%= %>', do nothing
        ## * when '<% %>' or '<%# %>', delete spaces iff only spaces are around '<% %>'
        if ch == ?=              # <%= %>
          rspace = nil if tailch && !tailch.empty?
          str << lspace if lspace
          add_expr(str, code, indicator)
          str << rspace if rspace
        elsif ch == ?\#          # <%# %>
          n = code.count("\n") + (rspace ? 1 : 0)
          if @trim && lspace && rspace
            add_text(src, str)
            str = ''
            add_stmt(src, "\n" * n)
          else
            str << lspace if lspace
            add_text(src, str)
            str = ''
            add_stmt(src, "\n" * n)
            str << rspace if rspace
          end
        else                     # <% %>
          if @trim && lspace && rspace
            add_text(src, str)
            str = ''
            add_stmt(src, "#{lspace}#{code}#{rspace}")
          else
            str << lspace if lspace
            add_text(src, str)
            str = ''
            add_stmt(src, code)
            str << rspace if rspace
          end
        end
      end
      #rest = $' || input                       # ruby1.8
      rest = pos == 0 ? input : input[pos..-1]  # ruby1.9
      _add_text_to_str(str, rest)
      add_text(src, str)
    end

    def add_text(src, text)
      return if !text || text.empty?
      #src << " _buf << %Q`" << text << "`;"
      if text[-1] == ?\n
        text[-1] = "\\n"
        src << " #{@bufvar} << %Q`#{text}`\n"
      else
        src << " #{@bufvar} << %Q`#{text}`;"
      end
    end

    def _add_text_to_str(str, text)
      return if !text || text.empty?
      str << text.gsub(/[`\#\\]/, '\\\\\&')
    end

    def add_expr_escaped(str, code)
      str << "\#{#{escaped_expr(code)}}"
    end

    def add_expr_literal(str, code)
      str << "\#{#{code}}"
    end

  end


end
#--end of require 'erubis/enhancer'
#require 'erubis/tiny'
#--begin of require 'erubis/engine/eruby'
##
## $Release: 2.7.0 $
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
##

#--already included require 'erubis/engine'
#--already included require 'erubis/enhancer'


module Erubis


  ##
  ## code generator for Ruby
  ##
  module RubyGenerator
    include Generator
    #include ArrayBufferEnhancer
    include StringBufferEnhancer

    def init_generator(properties={})
      super
      @escapefunc ||= "Erubis::XmlHelper.escape_xml"
      @bufvar     = properties[:bufvar] || "_buf"
    end

    def self.supported_properties()  # :nodoc:
      return []
    end

    def escape_text(text)
      text.gsub(/['\\]/, '\\\\\&')   # "'" => "\\'",  '\\' => '\\\\'
    end

    def escaped_expr(code)
      return "#{@escapefunc}(#{code})"
    end

    #--
    #def add_preamble(src)
    #  src << "#{@bufvar} = [];"
    #end
    #++

    def add_text(src, text)
      src << " #{@bufvar} << '" << escape_text(text) << "';" unless text.empty?
    end

    def add_stmt(src, code)
      #src << code << ';'
      src << code
      src << ';' unless code[-1] == ?\n
    end

    def add_expr_literal(src, code)
      src << " #{@bufvar} << (" << code << ').to_s;'
    end

    def add_expr_escaped(src, code)
      src << " #{@bufvar} << " << escaped_expr(code) << ';'
    end

    def add_expr_debug(src, code)
      code.strip!
      s = (code.dump =~ /\A"(.*)"\z/) && $1
      src << ' $stderr.puts("*** debug: ' << s << '=#{(' << code << ').inspect}");'
    end

    #--
    #def add_postamble(src)
    #  src << "\n#{@bufvar}.join\n"
    #end
    #++

  end


  ##
  ## engine for Ruby
  ##
  class Eruby < Basic::Engine
    include RubyEvaluator
    include RubyGenerator
  end


  ##
  ## fast engine for Ruby
  ##
  class FastEruby < Eruby
    include InterpolationEnhancer
  end


  ##
  ## swtich '<%= %>' to escaped and '<%== %>' to not escaped
  ##
  class EscapedEruby < Eruby
    include EscapeEnhancer
  end


  ##
  ## sanitize expression (<%= ... %>) by default
  ##
  ## this is equivalent to EscapedEruby and is prepared only for compatibility.
  ##
  class XmlEruby < Eruby
    include EscapeEnhancer
  end


  class PI::Eruby < PI::Engine
    include RubyEvaluator
    include RubyGenerator

    def init_converter(properties={})
      @pi = 'rb'
      super(properties)
    end

  end


end
#--end of require 'erubis/engine/eruby'
#require 'erubis/engine/enhanced'    # enhanced eruby engines
#require 'erubis/engine/optimized'   # generates optimized ruby code
#require 'erubis/engine/ephp'
#require 'erubis/engine/ec'
#require 'erubis/engine/ejava'
#require 'erubis/engine/escheme'
#require 'erubis/engine/eperl'
#require 'erubis/engine/ejavascript'

#--begin of require 'erubis/local-setting'
##
## $Release: 2.7.0 $
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
##

##
## you can add site-local settings here.
## this files is required by erubis.rb
##
#--end of require 'erubis/local-setting'
#--end of require 'erubis'
#--begin of require 'erubis/tiny'
##
## $Release: 2.7.0 $
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
##

module Erubis

  ##
  ## tiny and the simplest implementation of eRuby
  ##
  ## ex.
  ##   eruby = TinyEruby.new(File.read('example.rhtml'))
  ##   print eruby.src                 # print ruby code
  ##   print eruby.result(binding())   # eval ruby code with Binding object
  ##   print eruby.evalute(context)    # eval ruby code with context object
  ##
  class TinyEruby

    def initialize(input=nil)
      @src = convert(input) if input
    end
    attr_reader :src

    EMBEDDED_PATTERN = /<%(=+|\#)?(.*?)-?%>/m

    def convert(input)
      src = "_buf = '';"           # preamble
      pos = 0
      input.scan(EMBEDDED_PATTERN) do |indicator, code|
        m = Regexp.last_match
        text = input[pos...m.begin(0)]
        pos  = m.end(0)
        #src << " _buf << '" << escape_text(text) << "';"
        text.gsub!(/['\\]/, '\\\\\&')
        src << " _buf << '" << text << "';" unless text.empty?
        if !indicator              # <% %>
          src << code << ";"
        elsif indicator == '#'     # <%# %>
          src << ("\n" * code.count("\n"))
        else                       # <%= %>
          src << " _buf << (" << code << ").to_s;"
        end
      end
      #rest = $' || input                        # ruby1.8
      rest = pos == 0 ? input : input[pos..-1]   # ruby1.9
      #src << " _buf << '" << escape_text(rest) << "';"
      rest.gsub!(/['\\]/, '\\\\\&')
      src << " _buf << '" << rest << "';" unless rest.empty?
      src << "\n_buf.to_s\n"       # postamble
      return src
    end

    #def escape_text(text)
    #  return text.gsub!(/['\\]/, '\\\\\&') || text
    #end

    def result(_binding=TOPLEVEL_BINDING)
      eval @src, _binding
    end

    def evaluate(_context=Object.new)
      if _context.is_a?(Hash)
        _obj = Object.new
        _context.each do |k, v| _obj.instance_variable_set("@#{k}", v) end
        _context = _obj
      end
      _context.instance_eval @src
    end

  end



  module PI
  end

  class PI::TinyEruby

    def initialize(input=nil, options={})
      @escape  = options[:escape] || 'Erubis::XmlHelper.escape_xml'
      @src = convert(input) if input
    end

    attr_reader :src

    EMBEDDED_PATTERN = /(^[ \t]*)?<\?rb(\s.*?)\?>([ \t]*\r?\n)?|@(!+)?\{(.*?)\}@/m

    def convert(input)
      src = "_buf = '';"           # preamble
      pos = 0
      input.scan(EMBEDDED_PATTERN) do |lspace, stmt, rspace, indicator, expr|
        match = Regexp.last_match
        len   = match.begin(0) - pos
        text  = input[pos, len]
        pos   = match.end(0)
        #src << " _buf << '" << escape_text(text) << "';"
        text.gsub!(/['\\]/, '\\\\\&')
        src << " _buf << '" << text << "';" unless text.empty?
        if stmt                # <?rb ... ?>
          if lspace && rspace
            src << "#{lspace}#{stmt}#{rspace}"
          else
            src << " _buf << '" << lspace << "';" if lspace
            src << stmt << ";"
            src << " _buf << '" << rspace << "';" if rspace
          end
        else                       # ${...}, $!{...}
          if !indicator
            src << " _buf << " << @escape << "(" << expr << ");"
          elsif indicator == '!'
            src << " _buf << (" << expr << ").to_s;"
          end
        end
      end
      #rest = $' || input                        # ruby1.8
      rest = pos == 0 ? input : input[pos..-1]   # ruby1.9
      #src << " _buf << '" << escape_text(rest) << "';"
      rest.gsub!(/['\\]/, '\\\\\&')
      src << " _buf << '" << rest << "';" unless rest.empty?
      src << "\n_buf.to_s\n"       # postamble
      return src
    end

    #def escape_text(text)
    #  return text.gsub!(/['\\]/, '\\\\\&') || text
    #end

    def result(_binding=TOPLEVEL_BINDING)
      eval @src, _binding
    end

    def evaluate(_context=Object.new)
      if _context.is_a?(Hash)
        _obj = Object.new
        _context.each do |k, v| _obj.instance_variable_set("@#{k}", v) end
        _context = _obj
      end
      _context.instance_eval @src
    end

  end


end
#--end of require 'erubis/tiny'
#--begin of require 'erubis/engine/enhanced'
##
## $Release: 2.7.0 $
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
##

#--already included require 'erubis/enhancer'
#--already included require 'erubis/engine/eruby'


module Erubis


  #--
  ## moved to engine/ruby.rb
  #class EscapedEruby < Eruby
  #  include EscapeEnhancer
  #end
  #++


  #--
  ### (obsolete)
  #class FastEruby < Eruby
  #  include FastEnhancer
  #end
  #++


  class StdoutEruby < Eruby
    include StdoutEnhancer
  end


  class PrintOutEruby < Eruby
    include PrintOutEnhancer
  end


  class PrintEnabledEruby < Eruby
    include PrintEnabledEnhancer
  end


  class ArrayEruby < Eruby
    include ArrayEnhancer
  end


  class ArrayBufferEruby < Eruby
    include ArrayBufferEnhancer
  end


  class StringBufferEruby < Eruby
    include StringBufferEnhancer
  end


  class StringIOEruby < Eruby
    include StringIOEnhancer
  end


  class ErboutEruby < Eruby
    include ErboutEnhancer
  end


  class NoTextEruby < Eruby
    include NoTextEnhancer
  end


  class NoCodeEruby < Eruby
    include NoCodeEnhancer
  end


  class SimplifiedEruby < Eruby
    include SimplifyEnhancer
  end


  class StdoutSimplifiedEruby < Eruby
    include StdoutEnhancer
    include SimplifyEnhancer
  end


  class PrintOutSimplifiedEruby < Eruby
    include PrintOutEnhancer
    include SimplifyEnhancer
  end


  class BiPatternEruby < Eruby
    include BiPatternEnhancer
  end


  class PercentLineEruby < Eruby
    include PercentLineEnhancer
  end


  class PrefixedLineEruby < Eruby
    include PrefixedLineEnhancer
  end


  class HeaderFooterEruby < Eruby
    include HeaderFooterEnhancer
  end


  class DeleteIndentEruby < Eruby
    include DeleteIndentEnhancer
  end


  class InterpolationEruby < Eruby
    include InterpolationEnhancer
  end


end
#--end of require 'erubis/engine/enhanced'
#--begin of require 'erubis/engine/optimized'
##
## $Release: 2.7.0 $
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
##


#--already included require 'erubis/engine/eruby'


module Erubis


  module OptimizedGenerator
    include Generator

    def self.supported_properties()  # :nodoc:
      return []
    end

    def init_generator(properties={})
      super
      @escapefunc ||= "Erubis::XmlHelper.escape_xml"
      @initialized = false
      @prev_is_expr = false
    end

    protected

    def escape_text(text)
      text.gsub(/['\\]/, '\\\\\&')   # "'" => "\\'",  '\\' => '\\\\'
    end

    def escaped_expr(code)
      @escapefunc ||= 'Erubis::XmlHelper.escape_xml'
      return "#{@escapefunc}(#{code})"
    end

    def switch_to_expr(src)
      return if @prev_is_expr
      @prev_is_expr = true
      src << ' _buf'
    end

    def switch_to_stmt(src)
      return unless @prev_is_expr
      @prev_is_expr = false
      src << ';'
    end

    def add_preamble(src)
      #@initialized = false
      #@prev_is_expr = false
    end

    def add_text(src, text)
      return if text.empty?
      if @initialized
        switch_to_expr(src)
        src << " << '" << escape_text(text) << "'"
      else
        src << "_buf = '" << escape_text(text) << "';"
        @initialized = true
      end
    end

    def add_stmt(src, code)
      switch_to_stmt(src) if @initialized
      #super
      src << code
      src << ';' unless code[-1] == ?\n
    end

    def add_expr_literal(src, code)
      unless @initialized; src << "_buf = ''"; @initialized = true; end
      switch_to_expr(src)
      src << " << (" << code << ").to_s"
    end

    def add_expr_escaped(src, code)
      unless @initialized; src << "_buf = ''"; @initialized = true; end
      switch_to_expr(src)
      src << " << " << escaped_expr(code)
    end

    def add_expr_debug(src, code)
      code.strip!
      s = (code.dump =~ /\A"(.*)"\z/) && $1
      src << ' $stderr.puts("*** debug: ' << s << '=#{(' << code << ').inspect}");'
    end

    def add_postamble(src)
      #super if @initialized
      src << "\n_buf\n" if @initialized
    end

  end  # end of class OptimizedEruby


  ##
  ## Eruby class which generates optimized ruby code
  ##
  class OptimizedEruby < Basic::Engine    # Eruby
    include RubyEvaluator
    include OptimizedGenerator

    def init_converter(properties={})
      @pi = 'rb'
      super(properties)
    end

  end


  ##
  ## XmlEruby class which generates optimized ruby code
  ##
  class OptimizedXmlEruby < OptimizedEruby
    include EscapeEnhancer

    def add_expr_debug(src, code)
      switch_to_stmt(src) if indicator == '===' && !@initialized
      super
    end

  end  # end of class OptimizedXmlEruby

end
#--end of require 'erubis/engine/optimized'
#--already included require 'erubis/engine/eruby'
#--begin of require 'erubis/engine/ephp'
##
## $Release: 2.7.0 $
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
##

#--already included require 'erubis/engine'
#--already included require 'erubis/enhancer'


module Erubis


  module PhpGenerator
    include Generator

    def self.supported_properties()  # :nodoc:
      return []
    end

    def init_generator(properties={})
      super
      @escapefunc ||= 'htmlspecialchars'
    end

    def add_preamble(src)
      # empty
    end

    def escape_text(text)
      return text.gsub!(/<\?xml\b/, '<<?php ?>?xml') || text
    end

    def add_text(src, text)
      src << escape_text(text)
    end

    def add_expr_literal(src, code)
      code.strip!
      src << "<?php echo #{code}; ?>"
    end

    def add_expr_escaped(src, code)
      add_expr_literal(src, escaped_expr(code))
    end

    def add_expr_debug(src, code)
      code.strip!
      s = code.gsub(/\'/, "\\'")
      src << "<?php error_log('*** debug: #{s}='.(#{code}), 0); ?>"
    end

    def add_stmt(src, code)
      src << "<?php"
      src << " " if code[0] != ?\ #
      if code[-1] == ?\n
        code.chomp!
        src << code << "?>\n"
      else
        src << code << "?>"
      end
    end

    def add_postamble(src)
      # empty
    end

  end


  ##
  ## engine for PHP
  ##
  class Ephp < Basic::Engine
    include PhpGenerator
  end


  class EscapedEphp < Ephp
    include EscapeEnhancer
  end


  #class XmlEphp < Ephp
  #  include EscapeEnhancer
  #end


  class PI::Ephp < PI::Engine
    include PhpGenerator

    def init_converter(properties={})
      @pi = 'php'
      super(properties)
    end

  end


end
#--end of require 'erubis/engine/ephp'
#--begin of require 'erubis/engine/ec'
##
## $Release: 2.7.0 $
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
##

#--already included require 'erubis/engine'
#--already included require 'erubis/enhancer'


module Erubis


  module CGenerator
    include Generator

    def self.supported_properties()  # :nodoc:
      return [
              [:indent, '',       "indent spaces (ex. '  ')"],
              [:out,    'stdout', "output file pointer name"],
            ]
    end

    def init_generator(properties={})
      super
      @escapefunc ||= "escape"
      @indent = properties[:indent] || ''
      @out = properties[:out] || 'stdout'
    end

    def add_preamble(src)
      src << "#line 1 \"#{self.filename}\"\n" if self.filename
    end

    def escape_text(text)
      @@table_ ||= { "\r"=>"\\r", "\n"=>"\\n", "\t"=>"\\t", '"'=>'\\"', "\\"=>"\\\\" }
      text.gsub!(/[\r\n\t"\\]/) { |m| @@table_[m] }
      return text
    end

    def escaped_expr(code)
      return "#{@escapefunc}(#{code.strip}, #{@out})"
    end

    def add_text(src, text)
      return if text.empty?
      src << (src.empty? || src[-1] == ?\n ? @indent : ' ')
      src << "fputs("
      i = 0
      text.each_line do |line|
        src << "\n" << @indent << '      ' if i > 0
        i += 1
        src << '"' << escape_text(line) << '"'
      end
      src << ", #{@out});"   #<< (text[-1] == ?\n ? "\n" : "")
      src << "\n" if text[-1] == ?\n
    end

    def add_stmt(src, code)
      src << code
    end

    def add_expr_literal(src, code)
      src << @indent if src.empty? || src[-1] == ?\n
      src << " fprintf(#{@out}, " << code.strip << ');'
    end

    def add_expr_escaped(src, code)
      src << @indent if src.empty? || src[-1] == ?\n
      src << ' ' << escaped_expr(code) << ';'
    end

    def add_expr_debug(src, code)
      code.strip!
      s = nil
      if code =~ /\A\".*?\"\s*,\s*(.*)/
        s = $1.gsub(/[%"]/, '\\\1') + '='
      end
      src << @indent if src.empty? || src[-1] == ?\n
      src << " fprintf(stderr, \"*** debug: #{s}\" #{code});"
    end

    def add_postamble(src)
      # empty
    end

  end


  ##
  ## engine for C
  ##
  class Ec < Basic::Engine
    include CGenerator
  end


  class EscapedEc < Ec
    include EscapeEnhancer
  end


  #class XmlEc < Ec
  #  include EscapeEnhancer
  #end

  class PI::Ec < PI::Engine
    include CGenerator

    def init_converter(properties={})
      @pi = 'c'
      super(properties)
    end

  end


end
#--end of require 'erubis/engine/ec'
#--begin of require 'erubis/engine/ecpp'
##
## $Release: 2.7.0 $
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
##

#--already included require 'erubis/engine'
#--already included require 'erubis/enhancer'


module Erubis


  module CppGenerator
    include Generator

    def self.supported_properties()  # :nodoc:
      return [
              [:indent, '',       "indent spaces (ex. '  ')"],
              [:bufvar, '_buf',   "buffer variable name"],
            ]
    end

    def init_generator(properties={})
      super
      @escapefunc ||= "escape"
      @indent = properties[:indent] || ''
      @bufvar = properties[:bufvar] || '_buf'
    end

    def add_preamble(src)
      src << "#line 1 \"#{self.filename}\"\n" if self.filename
    end

    def escape_text(text)
      @@table_ ||= { "\r"=>"\\r", "\n"=>"\\n", "\t"=>"\\t", '"'=>'\\"', "\\"=>"\\\\" }
      text.gsub!(/[\r\n\t"\\]/) { |m| @@table_[m] }
      return text
    end

    def escaped_expr(code)
      return "#{@escapefunc}(#{code.strip})"
    end

    def add_text(src, text)
      return if text.empty?
      src << (src.empty? || src[-1] == ?\n ? @indent : ' ')
      src << "_buf << "
      i = 0
      text.each_line do |line|
        src << "\n" << @indent << "        " if i > 0
        i += 1
        src << '"' << escape_text(line) << '"'
      end
      src << ";"   #<< (text[-1] == ?\n ? "\n" : "")
      src << "\n" if text[-1] == ?\n
    end

    def add_stmt(src, code)
      src << code
    end

    def add_expr_literal(src, code)
      src << @indent if src.empty? || src[-1] == ?\n
      src << " _buf << (" << code.strip << ");"
    end

    def add_expr_escaped(src, code)
      src << @indent if src.empty? || src[-1] == ?\n
      src << ' ' << escaped_expr(code) << ';'
    end

    def add_expr_debug(src, code)
      code.strip!
      src << @indent if src.empty? || src[-1] == ?\n
      src << " std::cerr << \"*** debug: #{code.gsub(/(")/, '\\\&')}=\" << (#{code});"
    end

    def add_postamble(src)
      # empty
    end

  end


  ##
  ## engine for C
  ##
  class Ecpp < Basic::Engine
    include CppGenerator
  end


  class EscapedEcpp < Ecpp
    include EscapeEnhancer
  end


  #class XmlEcpp < Ecpp
  #  include EscapeEnhancer
  #end

  class PI::Ecpp < PI::Engine
    include CppGenerator

    def init_converter(properties={})
      @pi = 'cpp'
      super(properties)
    end

  end


end
#--end of require 'erubis/engine/ecpp'
#--begin of require 'erubis/engine/ejava'
##
## $Release: 2.7.0 $
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
##

#--already included require 'erubis/engine'
#--already included require 'erubis/enhancer'


module Erubis


  module JavaGenerator
    include Generator

    def self.supported_properties()   # :nodoc:
      return [
              [:indent,   '',       "indent spaces (ex. '  ')"],
              [:bufvar,   '_buf',   "output buffer variable name"],
              [:bufclass, 'StringBuffer', "output buffer class (ex. 'StringBuilder')"],
            ]
    end

    def init_generator(properties={})
      super
      @escapefunc ||= 'escape'
      @indent = properties[:indent] || ''
      @bufvar = properties[:bufvar] || '_buf'
      @bufclass = properties[:bufclass] || 'StringBuffer'
    end

    def add_preamble(src)
      src << "#{@indent}#{@bufclass} #{@bufvar} = new #{@bufclass}();"
    end

    def escape_text(text)
      @@table_ ||= { "\r"=>"\\r", "\n"=>"\\n", "\t"=>"\\t", '"'=>'\\"', "\\"=>"\\\\" }
      return text.gsub!(/[\r\n\t"\\]/) { |m| @@table_[m] } || text
    end

    def add_text(src, text)
      return if text.empty?
      src << (src.empty? || src[-1] == ?\n ? @indent : ' ')
      src << @bufvar << ".append("
      i = 0
      text.each_line do |line|
        src << "\n" << @indent << '          + ' if i > 0
        i += 1
        src << '"' << escape_text(line) << '"'
      end
      src << ");" << (text[-1] == ?\n ? "\n" : "")
    end

    def add_stmt(src, code)
      src << code
    end

    def add_expr_literal(src, code)
      src << @indent if src.empty? || src[-1] == ?\n
      code.strip!
      src << " #{@bufvar}.append(#{code});"
    end

    def add_expr_escaped(src, code)
      add_expr_literal(src, escaped_expr(code))
    end

    def add_expr_debug(src, code)
      code.strip!
      src << @indent if src.empty? || src[-1] == ?\n
      src << " System.err.println(\"*** debug: #{code}=\"+(#{code}));"
    end

    def add_postamble(src)
      src << "\n" if src[-1] == ?;
      src << @indent << "return " << @bufvar << ".toString();\n"
      #src << @indent << "System.out.print(" << @bufvar << ".toString());\n"
    end

  end


  ##
  ## engine for Java
  ##
  class Ejava < Basic::Engine
    include JavaGenerator
  end


  class EscapedEjava < Ejava
    include EscapeEnhancer
  end


  #class XmlEjava < Ejava
  #  include EscapeEnhancer
  #end

  class PI::Ejava < PI::Engine
    include JavaGenerator

    def init_converter(properties={})
      @pi = 'java'
      super(properties)
    end

  end

end
#--end of require 'erubis/engine/ejava'
#--begin of require 'erubis/engine/escheme'
##
## $Release: 2.7.0 $
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
##

#--already included require 'erubis/engine'
#--already included require 'erubis/enhancer'


module Erubis


  module SchemeGenerator
    include Generator

    def self.supported_properties()  # :nodoc:
      return [
              [:func,  '_add',   "function name (ex. 'display')"],
              ]
    end

    def init_generator(properties={})
      super
      @escapefunc ||= 'escape'
      @func = properties[:func] || '_add'   # or 'display'
    end

    def add_preamble(src)
      return unless @func == '_add'
      src << "(let ((_buf '())) " + \
               "(define (_add x) (set! _buf (cons x _buf))) "
      #src << "(let* ((_buf '())" + \
      #             " (_add (lambda (x) (set! _buf (cons x _buf))))) "
    end

    def escape_text(text)
      @table_ ||= { '"'=>'\\"', '\\'=>'\\\\' }
      text.gsub!(/["\\]/) { |m| @table_[m] }
      return text
    end

    def escaped_expr(code)
      code.strip!
      return "(#{@escapefunc} #{code})"
    end

    def add_text(src, text)
      return if text.empty?
      t = escape_text(text)
      if t[-1] == ?\n
        t[-1, 1] = ''
        src << "(#{@func} \"" << t << "\\n\")\n"
      else
        src << "(#{@func} \"" << t << '")'
      end
    end

    def add_stmt(src, code)
      src << code
    end

    def add_expr_literal(src, code)
      code.strip!
      src << "(#{@func} #{code})"
    end

    def add_expr_escaped(src, code)
      add_expr_literal(src, escaped_expr(code))
    end

    def add_expr_debug(src, code)
      s = (code.strip! || code).gsub(/\"/, '\\"')
      src << "(display \"*** debug: #{s}=\")(display #{code.strip})(display \"\\n\")"
    end

    def add_postamble(src)
      return unless @func == '_add'
      src << "\n" unless src[-1] == ?\n
      src << "  (reverse _buf))\n"
    end

  end


  ##
  ## engine for Scheme
  ##
  class Escheme < Basic::Engine
    include SchemeGenerator
  end


  class EscapedEscheme < Escheme
    include EscapeEnhancer
  end


  #class XmlEscheme < Escheme
  #  include EscapeEnhancer
  #end


  class PI::Escheme < PI::Engine
    include SchemeGenerator

    def init_converter(properties={})
      @pi = 'scheme'
      super(properties)
    end

  end


end
#--end of require 'erubis/engine/escheme'
#--begin of require 'erubis/engine/eperl'
##
## $Release: 2.7.0 $
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
##

#--already included require 'erubis/engine'
#--already included require 'erubis/enhancer'


module Erubis


  module PerlGenerator
    include Generator

    def self.supported_properties()  # :nodoc:
      return [
              [:func, 'print', "function name"],
              ]
    end

    def init_generator(properties={})
      super
      @escapefunc ||= 'encode_entities'
      @func = properties[:func] || 'print'
    end

    def add_preamble(src)
      src << "use HTML::Entities; ";
    end

    def escape_text(text)
      return text.gsub!(/['\\]/, '\\\\\&') || text
    end

    def add_text(src, text)
      src << @func << "('" << escape_text(text) << "'); " unless text.empty?
    end

    def add_expr_literal(src, code)
      code.strip!
      src << @func << "(" << code << "); "
    end

    def add_expr_escaped(src, code)
      add_expr_literal(src, escaped_expr(code))
    end

    def add_expr_debug(src, code)
      code.strip!
      s = code.gsub(/\'/, "\\'")
      src << @func << "('*** debug: #{code}=', #{code}, \"\\n\");"
    end

    def add_stmt(src, code)
      src << code
    end

    def add_postamble(src)
      src << "\n" unless src[-1] == ?\n
    end

  end


  ##
  ## engine for Perl
  ##
  class Eperl < Basic::Engine
    include PerlGenerator
  end


  class EscapedEperl < Eperl
    include EscapeEnhancer
  end


  #class XmlEperl < Eperl
  #  include EscapeEnhancer
  #end


  class PI::Eperl < PI::Engine
    include PerlGenerator

    def init_converter(properties={})
      @pi = 'perl'
      super(properties)
    end

  end


end
#--end of require 'erubis/engine/eperl'
#--begin of require 'erubis/engine/ejavascript'
##
## $Release: 2.7.0 $
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
##

#--already included require 'erubis/engine'
#--already included require 'erubis/enhancer'


module Erubis


  module JavascriptGenerator
    include Generator

    def self.supported_properties()   # :nodoc:
      list = []
      #list << [:indent,   '',       "indent spaces (ex. '  ')"]
      #list << [:bufvar,      '_buf',   "output buffer variable name"]
      list << [:docwrite, true,     "use 'document.write()' when true"]
      return list
    end

    def init_generator(properties={})
      super
      @escapefunc ||= 'escape'
      @indent = properties[:indent] || ''
      @bufvar = properties[:bufvar] || '_buf'
      @docwrite = properties[:docwrite] != false  # '!= false' will be removed in the next release
    end

    def add_preamble(src)
      src << "#{@indent}var #{@bufvar} = [];"
    end

    def escape_text(text)
      @@table_ ||= { "\r"=>"\\r", "\n"=>"\\n\\\n", "\t"=>"\\t", '"'=>'\\"', "\\"=>"\\\\" }
      return text.gsub!(/[\r\n\t"\\]/) { |m| @@table_[m] } || text
    end

    def add_indent(src, indent)
      src << (src.empty? || src[-1] == ?\n ? indent : ' ')
    end

    def add_text(src, text)
      return if text.empty?
      add_indent(src, @indent)
      src << @bufvar << '.push("'
      s = escape_text(text)
      if s[-1] == ?\n
        s[-2, 2] = ''
        src << s << "\");\n"
      else
        src << s << "\");"
      end
    end

    def add_stmt(src, code)
      src << code
    end

    def add_expr_literal(src, code)
      add_indent(src, @indent)
      code.strip!
      src << "#{@bufvar}.push(#{code});"
    end

    def add_expr_escaped(src, code)
      add_expr_literal(src, escaped_expr(code))
    end

    def add_expr_debug(src, code)
      add_indent(src, @indent)
      code.strip!
      src << "alert(\"*** debug: #{code}=\"+(#{code}));"
    end

    def add_postamble(src)
      src << "\n" if src[-1] == ?;
      if @docwrite
        src << @indent << 'document.write(' << @bufvar << ".join(\"\"));\n"
      else
        src << @indent << @bufvar << ".join(\"\");\n"
      end
    end

  end


  ##
  ## engine for JavaScript
  ##
  class Ejavascript < Basic::Engine
    include JavascriptGenerator
  end


  class EscapedEjavascript < Ejavascript
    include EscapeEnhancer
  end


  #class XmlEjavascript < Ejavascript
  #  include EscapeEnhancer
  #end


  class PI::Ejavascript < PI::Engine
    include JavascriptGenerator

    def init_converter(properties={})
      @pi = 'js'
      super(properties)
    end

  end


end
#--end of require 'erubis/engine/ejavascript'


module Erubis


  Ejs = Ejavascript
  EscapedEjs = EscapedEjavascript


  class CommandOptionError < ErubisError
  end


  ##
  ## main class of command
  ##
  ## ex.
  ##   Main.main(ARGV)
  ##
  class Main

    def self.main(argv=ARGV)
      status = 0
      begin
        Main.new.execute(ARGV)
      rescue CommandOptionError => ex
        $stderr.puts ex.message
        status = 1
      end
      exit(status)
    end

    def initialize
      @single_options = "hvxztTSbeBXNUC"
      @arg_options    = "pcrfKIlaE" #C
      @option_names   = {
        'h' => :help,
        'v' => :version,
        'x' => :source,
        'z' => :syntax,
        'T' => :unexpand,
        't' => :untabify,      # obsolete
        'S' => :intern,
        'b' => :bodyonly,
        'B' => :binding,
        'p' => :pattern,
        'c' => :context,
        #'C' => :class,
        'e' => :escape,
        'r' => :requires,
        'f' => :datafiles,
        'K' => :kanji,
        'I' => :includes,
        'l' => :lang,
        'a' => :action,
        'E' => :enhancers,
        'X' => :notext,
        'N' => :linenum,
        'U' => :unique,
        'C' => :compact,
      }
      assert unless @single_options.length + @arg_options.length == @option_names.length
      (@single_options + @arg_options).each_byte do |ch|
        assert unless @option_names.key?(ch.chr)
      end
    end


    def execute(argv=ARGV)
      ## parse command-line options
      options, properties = parse_argv(argv, @single_options, @arg_options)
      filenames = argv
      options['h'] = true if properties[:help]
      opts = Object.new
      arr = @option_names.collect {|ch, name| "def #{name}; @#{name}; end\n" }
      opts.instance_eval arr.join
      options.each do |ch, val|
        name = @option_names[ch]
        opts.instance_variable_set("@#{name}", val)
      end

      ## help, version, enhancer list
      if opts.help || opts.version
        puts version()         if opts.version
        puts usage()           if opts.help
        puts show_properties() if opts.help
        puts show_enhancers()  if opts.help
        return
      end

      ## include path
      opts.includes.split(/,/).each do |path|
        $: << path
      end if opts.includes

      ## require library
      opts.requires.split(/,/).each do |library|
        require library
      end if opts.requires

      ## action
      action = opts.action
      action ||= 'syntax'  if opts.syntax
      action ||= 'convert' if opts.source || opts.notext

      ## lang
      lang = opts.lang || 'ruby'
      action ||= 'convert' if opts.lang

      ## class name of Eruby
      #classname = opts.class
      classname = nil
      klass = get_classobj(classname, lang, properties[:pi])

      ## kanji code
      $KCODE = opts.kanji if opts.kanji

      ## read context values from yaml file
      datafiles = opts.datafiles
      context = load_datafiles(datafiles, opts)

      ## parse context data
      if opts.context
        context = parse_context_data(opts.context, opts)
      end

      ## properties for engine
      properties[:escape]   = true         if opts.escape && !properties.key?(:escape)
      properties[:pattern]  = opts.pattern if opts.pattern
      #properties[:trim]     = false        if opts.notrim
      properties[:preamble] = properties[:postamble] = false if opts.bodyonly
      properties[:pi]       = nil          if properties[:pi] == true

      ## create engine and extend enhancers
      engine = klass.new(nil, properties)
      enhancers = get_enhancers(opts.enhancers)
      #enhancers.push(Erubis::EscapeEnhancer) if opts.escape
      enhancers.each do |enhancer|
        engine.extend(enhancer)
        engine.bipattern = properties[:bipattern] if enhancer == Erubis::BiPatternEnhancer
      end

      ## no-text
      engine.extend(Erubis::NoTextEnhancer) if opts.notext

      ## convert and execute
      val = nil
      msg = "Syntax OK\n"
      if filenames && !filenames.empty?
        filenames.each do |filename|
          File.file?(filename)  or
            raise CommandOptionError.new("#{filename}: file not found.")
          engine.filename = filename
          engine.convert!(File.read(filename))
          val = do_action(action, engine, context, filename, opts)
          msg = nil if val
        end
      else
        engine.filename = filename = '(stdin)'
        engine.convert!($stdin.read())
        val = do_action(action, engine, context, filename, opts)
        msg = nil if val
      end
      print msg if action == 'syntax' && msg

    end

    private

    def do_action(action, engine, context, filename, opts)
      case action
      when 'convert'
        s = manipulate_src(engine.src, opts)
      when nil, 'exec', 'execute'
        s = opts.binding ? engine.result(context.to_hash) : engine.evaluate(context)
      when 'syntax'
        s = check_syntax(filename, engine.src)
      else
        raise "*** internal error"
      end
      print s if s
      return s
    end

    def manipulate_src(source, opts)
      flag_linenum   = opts.linenum
      flag_unique    = opts.unique
      flag_compact   = opts.compact
      if flag_linenum
        n = 0
        source.gsub!(/^/) { n += 1; "%5d:  " % n }
        source.gsub!(/^ *\d+:\s+?\n/, '')      if flag_compact
        source.gsub!(/(^ *\d+:\s+?\n)+/, "\n") if flag_unique
      else
        source.gsub!(/^\s*?\n/, '')      if flag_compact
        source.gsub!(/(^\s*?\n)+/, "\n") if flag_unique
      end
      return source
    end

    def usage(command=nil)
      command ||= File.basename($0)
      buf = []
      buf << "erubis - embedded program converter for multi-language"
      buf << "Usage: #{command} [..options..] [file ...]"
      buf << "  -h, --help    : help"
      buf << "  -v            : version"
      buf << "  -x            : show converted code"
      buf << "  -X            : show converted code, only ruby code and no text part"
      buf << "  -N            : numbering: add line numbers            (for '-x/-X')"
      buf << "  -U            : unique: compress empty lines to a line (for '-x/-X')"
      buf << "  -C            : compact: remove empty lines            (for '-x/-X')"
      buf << "  -b            : body only: no preamble nor postamble   (for '-x/-X')"
      buf << "  -z            : syntax checking"
      buf << "  -e            : escape (equal to '--E Escape')"
      buf << "  -p pattern    : embedded pattern (default '<% %>')"
      buf << "  -l lang       : convert but no execute (ruby/php/c/cpp/java/scheme/perl/js)"
      buf << "  -E e1,e2,...  : enhancer names (Escape, PercentLine, BiPattern, ...)"
      buf << "  -I path       : library include path"
      buf << "  -K kanji      : kanji code (euc/sjis/utf8) (default none)"
      buf << "  -c context    : context data string (yaml inline style or ruby code)"
      buf << "  -f datafile   : context data file ('*.yaml', '*.yml', or '*.rb')"
      #buf << "  -t            : expand tab characters in YAML file"
      buf << "  -T            : don't expand tab characters in YAML file"
      buf << "  -S            : convert mapping key from string to symbol in YAML file"
      buf << "  -B            : invoke 'result(binding)' instead of 'evaluate(context)'"
      buf << "  --pi=name     : parse '<?name ... ?>' instead of '<% ... %>'"
      #'
      #  -T            : don't trim spaces around '<% %>'
      #  -c class      : class name (XmlEruby/PercentLineEruby/...) (default Eruby)
      #  -r library    : require library
      #  -a            : action (convert/execute)
      return buf.join("\n")
    end

    def collect_supported_properties(erubis_klass)
      list = []
      erubis_klass.ancestors.each do |klass|
        if klass.respond_to?(:supported_properties)
          list.concat(klass.supported_properties)
        end
      end
      return list
    end

    def show_properties
      s = "supported properties:\n"
      basic_props = collect_supported_properties(Erubis::Basic::Engine)
      pi_props    = collect_supported_properties(Erubis::PI::Engine)
      list = []
      common_props = basic_props & pi_props
      list << ['(common)', common_props]
      list << ['(basic)',  basic_props - common_props]
      list << ['(pi)',     pi_props    - common_props]
      %w[ruby php c cpp java scheme perl javascript].each do |lang|
        klass = Erubis.const_get("E#{lang}")
        list << [lang, collect_supported_properties(klass) - basic_props]
      end
      list.each do |lang, props|
        s << "  * #{lang}\n"
        props.each do |name, default_val, desc|
          s << ("     --%-23s : %s\n" % ["#{name}=#{default_val.inspect}", desc])
        end
      end
      s << "\n"
      return s
    end

    def show_enhancers
      dict = {}
      ObjectSpace.each_object(Module) do |mod|
        dict[$1] = mod if mod.name =~ /\AErubis::(.*)Enhancer\z/
      end
      s = "enhancers:\n"
      dict.sort_by {|name, mod| name }.each do |name, mod|
        s << ("  %-13s : %s\n" % [name, mod.desc])
      end
      return s
    end

    def version
      return Erubis::VERSION
    end

    def parse_argv(argv, arg_none='', arg_required='', arg_optional='')
      options = {}
      context = {}
      while argv[0] && argv[0][0] == ?-
        optstr = argv.shift
        optstr = optstr[1, optstr.length-1]
        #
        if optstr[0] == ?-    # context
          optstr =~ /\A\-([-\w]+)(?:=(.*))?/  or
            raise CommandOptionError.new("-#{optstr}: invalid context value.")
          name, value = $1, $2
          name  = name.gsub(/-/, '_').intern
          #value = value.nil? ? true : YAML.load(value)   # error, why?
          value = value.nil? ? true : YAML.load("---\n#{value}\n")
          context[name] = value
          #
        else                  # options
          while optstr && !optstr.empty?
            optchar = optstr[0].chr
            optstr = optstr[1..-1]
            if arg_none.include?(optchar)
              options[optchar] = true
            elsif arg_required.include?(optchar)
              arg = optstr.empty? ? argv.shift : optstr  or
                raise CommandOptionError.new("-#{optchar}: #{@option_names[optchar]} required.")
              options[optchar] = arg
              optstr = nil
            elsif arg_optional.include?(optchar)
              arg = optstr.empty? ? true : optstr
              options[optchar] = arg
              optstr = nil
            else
              raise CommandOptionError.new("-#{optchar}: unknown option.")
            end
          end
        end
        #
      end  # end of while

      return options, context
    end


    def untabify(str, width=8)
      list = str.split(/\t/)
      last = list.pop
      sb = ''
      list.each do |s|
        column = (n = s.rindex(?\n)) ? s.length - n - 1 : s.length
        n = width - (column % width)
        sb << s << (' ' * n)
      end
      sb << last
      return sb
    end
    #--
    #def untabify(str, width=8)
    #  sb = ''
    #  str.scan(/(.*?)\t/m) do |s, |
    #    len = (n = s.rindex(?\n)) ? s.length - n - 1 : s.length
    #    sb << s << (" " * (width - len % width))
    #  end
    #  return $' ? (sb << $') : str
    #end
    #++


    def get_classobj(classname, lang, pi)
      classname ||= "E#{lang}"
      base_module = pi ? Erubis::PI : Erubis
      begin
        klass = base_module.const_get(classname)
      rescue NameError
        klass = nil
      end
      unless klass
        if lang
          msg = "-l #{lang}: invalid language name (class #{base_module.name}::#{classname} not found)."
        else
          msg = "-c #{classname}: invalid class name."
        end
        raise CommandOptionError.new(msg)
      end
      return klass
    end

    def get_enhancers(enhancer_names)
      return [] unless enhancer_names
      enhancers = []
      shortname = nil
      begin
        enhancer_names.split(/,/).each do |name|
          shortname = name
          enhancers << Erubis.const_get("#{shortname}Enhancer")
        end
      rescue NameError
        raise CommandOptionError.new("#{shortname}: no such Enhancer (try '-h' to show all enhancers).")
      end
      return enhancers
    end

    def load_datafiles(filenames, opts)
      context = Erubis::Context.new
      return context unless filenames
      filenames.split(/,/).each do |filename|
        filename.strip!
        test(?f, filename) or raise CommandOptionError.new("#{filename}: file not found.")
        if filename =~ /\.ya?ml$/
          if opts.unexpand
            ydoc = YAML.load_file(filename)
          else
            ydoc = YAML.load(untabify(File.read(filename)))
          end
          ydoc.is_a?(Hash) or raise CommandOptionError.new("#{filename}: root object is not a mapping.")
          intern_hash_keys(ydoc) if opts.intern
          context.update(ydoc)
        elsif filename =~ /\.rb$/
          str = File.read(filename)
          context2 = Erubis::Context.new
          _instance_eval(context2, str)
          context.update(context2)
        else
          CommandOptionError.new("#{filename}: '*.yaml', '*.yml', or '*.rb' required.")
        end
      end
      return context
    end

    def _instance_eval(_context, _str)
      _context.instance_eval(_str)
    end

    def parse_context_data(context_str, opts)
      if context_str[0] == ?{
        require 'yaml'
        ydoc = YAML.load(context_str)
        unless ydoc.is_a?(Hash)
          raise CommandOptionError.new("-c: root object is not a mapping.")
        end
        intern_hash_keys(ydoc) if opts.intern
        return ydoc
      else
        context = Erubis::Context.new
        context.instance_eval(context_str, '-c')
        return context
      end
    end

    def intern_hash_keys(obj, done={})
      return if done.key?(obj.__id__)
      case obj
      when Hash
        done[obj.__id__] = obj
        obj.keys.each do |key|
          obj[key.intern] = obj.delete(key) if key.is_a?(String)
        end
        obj.values.each do |val|
          intern_hash_keys(val, done) if val.is_a?(Hash) || val.is_a?(Array)
        end
      when Array
        done[obj.__id__] = obj
        obj.each do |val|
          intern_hash_keys(val, done) if val.is_a?(Hash) || val.is_a?(Array)
        end
      end
    end

    def check_syntax(filename, src)
      require 'open3'
      #command = (ENV['_'] || 'ruby') + ' -wc'   # ENV['_'] stores command name
      bin = ENV['_'] && File.basename(ENV['_']) =~ /^ruby/ ? ENV['_'] : 'ruby'
      command = bin + ' -wc'
      stdin, stdout, stderr = Open3.popen3(command)
      stdin.write(src)
      stdin.close
      result = stdout.read()
      stdout.close()
      errmsg = stderr.read()
      stderr.close()
      return nil unless errmsg && !errmsg.empty?
      errmsg =~ /\A-:(\d+): /
      linenum, message = $1, $'
      return "#{filename}:#{linenum}: #{message}"
    end

    if defined?(RUBY_ENGINE) && RUBY_ENGINE == "rbx"
      def check_syntax(filename, src)
        require 'compiler'
        verbose = $VERBOSE
        msg = nil
        begin
          $VERBOSE = true
          Rubinius::Compiler.compile_string(src, filename)
        rescue SyntaxError => ex
          ex_linenum = ex.line
          linenum = 0
          srcline = src.each_line do |line|
            linenum += 1
            break line if linenum == ex_linenum
          end
          msg = "#{ex.message}\n"
          msg << srcline
          msg << "\n" unless srcline =~ /\n\z/
          msg << (" " * (ex.column-1)) << "^\n"
        ensure
          $VERBOSE = verbose
        end
        return msg
      end
    end

  end

end
#--end of require 'erubis/main'

Erubis::Main.main(ARGV)