File: yatex.el

package info (click to toggle)
yatex 1.82-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,076 kB
  • sloc: lisp: 15,155; makefile: 194; ruby: 92; sh: 76
file content (3352 lines) | stat: -rw-r--r-- 122,277 bytes parent folder | download | duplicates (2)
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
;;; yatex.el --- Yet Another tex-mode for emacs //쒹// -*- coding: sjis -*-
;;; (c)1991-2019 by HIROSE Yuuji.[yuuji@yatex.org]
;;; Last modified Thu Dec 26 12:46:41 2019 on firestorm
;;; $Id: yatex.el,v 4dad5f91b26c 2019-12-26 12:50 +0859 yuuji $
;;; The latest version of this software is always available at;
;;; https://www.yatex.org/

;;;   This  program  is  distributed  as   a  free  software.   You  can
;;; use/copy/modify/redistribute  this  software   freely  but  with  NO
;;; warranty to anything  as a result of using  this software.  Adopting
;;; code from  this program is also  free.  But I would  not do contract
;;; act.
;;;
;;;   This software can be treated with: ``The 2-Clause BSD License''
;;; (since 2017-09-09, yatex 1.80).

;;; Code:
(require 'yatexlib)
(defconst YaTeX-revision-number "1.82"
  "Revision number of running yatex.el")

;---------- Local variables ----------
(defvar YaTeX-prefix "\C-c"
  "*Prefix key to call YaTeX functions.
You can select favorite prefix key by setq in your ~/.emacs.")

(defvar YaTeX-environment-indent 1
  "*Indentation depth at column width in LaTeX environments.")

(defvar YaTeX-fill-prefix nil
  "*fill-prefix used for auto-fill-mode.
The default value is nil.")

(defvar YaTeX-fill-column 72
  "*fill-column used for auto-fill-mode.")

(defvar YaTeX-comment-prefix "%"
  "TeX comment prefix.")

(defvar YaTeX-current-position-register ?3
  "*Position register to keep where the last completion was done.
All of YaTeX completing input store the current position into
the register YaTeX-current-position-register.  So every time you
make a trip to any other part of text other than you are writing, you can
return to the editing paragraph by calling register-to-point with argument
YaTeX-current-position-register.")

(defvar YaTeX-use-LaTeX2e t "*Use LaTeX2e or not.  Nil means latex 2.09")

(defvar tex-command
  (cond
   (YaTeX-use-LaTeX2e "platex -kanji=%k")
   (YaTeX-japan "jlatex")
   (t "latex"))
  "*Default command for typesetting LaTeX text.
Overridden with `%#! CommandLine...' in the buffer.
`%'s followed by a character are replaced as follows:
%f -> Parent(main) document file name
%r -> %f without extension
%k -> One of Kanji code mnemonic: euc, jis, sjis, utf8
")

(defvar bibtex-command (if YaTeX-japan "pbibtex -kanji=%k" "bibtex")
  "*Default command of BibTeX.
Overridden with `%#BIBTEX CommandLine...' in the buffer.
Pettern `%k' in a string will be replaced with Kanji-code mnemonic of ptex.")

(defvar dvi2-command		;previewer command for your site
  (cond (YaTeX-dos	"dviout -wait=0")
	(YaTeX-macos	"open -a Preview")
	(t		"xdvi -geo +0+0 -s 4"))
  "*Default previewer command including its option.
Overridden with `%#PREVIEW CommandLine...' in the buffer.")

(defvar YaTeX-cmd-gimp "gimp")
(defvar YaTeX-cmd-tgif "tgif")
(defvar YaTeX-cmd-inkscape "inkscape")
(defvar YaTeX-cmd-dia "dia")
(defvar YaTeX-cmd-ooo "soffice")
(defvar YaTeX-cmd-gs "gs")
(defvar YaTeX-cmd-dvips
  (if (YaTeX-executable-find "pdvips") "pdvips" "dvips"))
(defvar YaTeX-cmd-displayline
  "/Applications/Skim.app/Contents/SharedSupport/displayline")
(defvar YaTeX-cmd-edit-ps YaTeX-cmd-gimp)
(defvar YaTeX-cmd-edit-pdf YaTeX-cmd-ooo)
(defvar YaTeX-cmd-edit-ai YaTeX-cmd-inkscape)
(defvar YaTeX-cmd-edit-svg YaTeX-cmd-inkscape)
(defvar YaTeX-cmd-edit-images YaTeX-cmd-gimp)
(defvar YaTeX-cmd-view-images "display -geometry +0+0")

(defvar tex-pdfview-command	;previewer command for your site
  (cond
   (YaTeX-dos	"acroread")
   (YaTeX-macos	(cond
		 ((file-executable-p YaTeX-cmd-displayline) "open -a Skim")
		 (t "open")))
   ((YaTeX-executable-find "evince")		"evince")
   ((YaTeX-executable-find "xreader")		"xreader")
   ((YaTeX-executable-find "atril")		"atril")
   ((YaTeX-executable-find "okular")		"okular")
   ((YaTeX-executable-find "kpdf")		"kpdf")
   ((YaTeX-executable-find "xpdf")		"xpdf")
   ((YaTeX-executable-find "mupdf")		"mupdf")
   (t		"acroread"))
  "*Default PDF viewer command including its option.
Overridden with `%#PDFVIEW CommandLine...' in the buffer.")

(defvar makeindex-command (if YaTeX-dos "makeind" "makeindex")
  "*Default makeindex command.
Overridden with `%#MAKEINDEX CommandLine...' in the buffer.")

(defvar dviprint-command-format
  (if YaTeX-dos "dviprt %s %f%t"
      "dvi2ps %f %t %s | lpr")
  "*Command line string to print out current file.
Overridden with `%#LPR CommandLine...' in the buffer.
Format string %s will be replaced by the filename.  Do not forget to
specify the `from usage' and `to usage' with their option by format string
%f and %t.
  See also documentation of dviprint-from-format and dviprint-to-format.")

(defvar dviprint-from-format
  (if YaTeX-dos "%b-" "-f %b")
  "*`From' page format of dvi filter.  %b will turn to beginning page number.")

(defvar dviprint-to-format
  (if YaTeX-dos "%e" "-t %e")
  "*`To' page format of dvi filter.  %e will turn to end page number.")

(defvar YaTeX-dvipdf-command
  "dvipdfmx"
  "*Command name to convert dvi file to PDF.
Overridden with `%#DVIPDF CommandLine...' in the buffer.")

(defvar YaTeX-default-document-style
  (concat (if YaTeX-japan "js") "article")
  "*Default LaTeX Documentstyle for YaTeX-typeset-region.")

(defvar YaTeX-need-nonstop nil
  "*T for adding `\\nonstopmode{}' to text before invoking latex command.")

(defvar latex-warning-regexp "line.* [0-9]*"
  "*Regular expression of line number of warning message by latex command.")

(defvar latex-error-regexp "l\\.[1-9][0-9]*"
  "*Regular expression of line number of latex error.
Perhaps your latex command stops at this error message with line number of
LaTeX source text.")

(defvar latex-dos-emergency-message
  "Emergency stop"      ;<- for Micro tex, ASCII-pTeX 1.6
  "Message pattern of emergency stop of typesetting.
Because Demacs (GNU Emacs on DOS) cannot have concurrent process, the
latex command which is stopping on a LaTeX error, is terminated by Demacs.
Many latex command on DOS display some messages when it is terminated by
other process, user or OS.  Define to this variable a message string of your
latex command on DOS shown at abnormal termination.
  Remember Demacs's call-process function is not oriented for interactive
process.")

(defvar NTT-jTeX nil
  "*T for using NTT-jTeX for latex command.
More precisely, setting t to this variables inhibits inter-word break on
typeset document by line-break of source text.  That is, YaTeX automatically
put % after each line at filling.
s+CfgɂāA^CvZbg̎Ԃ󂢂Ă܂̂}ꍇ
tɂ(ÂNTT-jTeXŌɌ)B̓Iɂ́AfillƂɊes̏I
%tB")


(defvar YaTeX-item-regexp
  (concat (regexp-quote "\\") "\\(sub\\|bib\\)*item")
  "*Regular expression of item command.")

(defvar YaTeX-sectioning-regexp
  "\\(part\\|chapter\\*?\\|\\(sub\\)*\\(section\\|paragraph\\)\\)\\(\\*\\|\\b\\)"
  "*LaTeX sectioning commands regexp.")

(defvar YaTeX-paragraph-start
  (concat "^[ \t]*%\\|^[ \t]*$\\|\\'\\|^\C-l\\|\\\\\\\\$\\|^[ \t]*\\\\\\("
	  YaTeX-sectioning-regexp		;sectioning commands
	  "\\|[A-z]*item\\|begin{\\|end{"	;special declaration
	  "\\|\\[\\|\\]"
	  "\\|newpage\\b\\|vspace\\b"
	  "\\)")
  "*Paragraph starting regexp of common LaTeX source.  Use this value
for YaTeX-uncomment-paragraph.")

(defvar YaTeX-paragraph-separate
  (concat "^[ \t]*%\\|^[ \t]*$\\|^\C-l\\|\\\\\\\\$\\|^[ \t]*\\\\\\("
	  YaTeX-sectioning-regexp		;sectioning commands
	  "\\|begin{\\|end{"			;special declaration
	  "\\|\\[\\|\\]"
	  "\\|newpage\\b\\|vspace\\b"
	  "\\)")
  "*Paragraph delimiter regexp of common LaTeX source.  Use this value
for YaTeX-uncomment-paragraph.")

(defvar YaTeX-verbatim-environments 
  '("verbatim" "verbatim*" "alltt")
  "*Assume these environments of this variable disable LaTeX commands.")
(defvar YaTeX-verb-regexp "verb\\*?\\|path"
  "*Regexp of verb family.  Do not contain preceding \\\\ nor \\(\\).")
(defvar YaTeX-fill-inhibit-environments
  (append '("tabular" "tabular*" "array" "picture" "eqnarray" "eqnarray*"
	    "longtable" "tabularx"
	    "equation" "equation*" "math" "displaymath")
	  YaTeX-verbatim-environments)
  "*In these environments, YaTeX inhibits fill-paragraph from formatting.
Define those environments as a form of list.")

(defvar YaTeX-itemizing-env-regexp
  "itemize\\|enumerate\\|description\\|list\\|thebibliography"
  "*Regexp of itemizing environments")
(defvar YaTeX-equation-env-regexp
  "array\\*?\\|equation\\*?"
  "*Regexp of environments for equations")
(defvar YaTeX-array-env-regexp
  (concat
   "array\\*?\\|eqnarray\\*?\\|tabbing\\|tabularx?\\*?\\|"	;LaTeX
   "longtable\\|"						;LaTeX2e
   "matrix\\|pmatrix\\|bmatrix\\|vmatrix\\|Vmatrix\\|"		;AMS-LaTeX
   "align\\*?\\|split\\*?\\|aligned\\*?\\|alignat\\*?\\|"	;AMS-LaTeX
   "[bpvV]?matrix\\|smallmatrix\\|cases\\|"			;AMS-LaTeX
   "xalignat\\*?\\|xxalignat\\*?")				;AMS-LaTeX
  "*Regexp of environments where `&' becomes field delimiter.")
(defvar YaTeX-uncomment-once t
  "*T for removing all continuous commenting character(%).
Nil for removing only one commenting character at the beginning-of-line.")

(defvar YaTeX-close-paren-always t
  "*Close parenthesis always when YaTeX-modify-mode is nil.")

(defvar YaTeX-greek-by-maketitle-completion nil
  "*T for greek letters completion by maketitle-type completion.")

(defvar YaTeX-auto-math-mode t
  "*T for changing YaTeX-math mode automatically.")
(defvar YaTeX-use-AMS-LaTeX t
  "*T for using AMS-LaTeX")

(defvar yatex-mode-hook nil
  "*List of functions to be called at the end of yatex-mode initializations.")

(defvar YaTeX-search-file-from-top-directory t
  "*Non-nil means to search input-files from the directory where main file exists.")

(defvar YaTeX-use-font-lock (and (featurep 'font-lock)
				 (fboundp 'x-color-values)
				 (fboundp 'font-lock-fontify-region))
  "*Use font-lock to fontify buffer or not.")

(defvar YaTeX-use-hilit19 (and (featurep 'hilit19) (fboundp 'x-color-values)
			       (fboundp 'hilit-translate)
			       (not YaTeX-use-font-lock))
  "*Use hilit19 to highlight buffer or not.")

(defvar YaTeX-tabular-indentation 4
  "*Indentation column-depth of continueing line in tabular environment.")

(defvar YaTeX-electric-indent-mode -1
  "*(for Emacs 24.4+) Pass this value to electric-indent-local-mode.
-1 means `off'.")

;;-- Math mode values --

(defvar YaTeX-math-key-list-default
  '((";" . YaTeX-math-sign-alist)
    (":" . YaTeX-greek-key-alist))
  "Default key sequence to invoke math-mode's image completion.")

(defvar YaTeX-math-key-list-private nil
  "*User defined alist, math-mode-prefix vs completion alist.")

(defvar YaTeX-math-key-list
  (append YaTeX-math-key-list-private YaTeX-math-key-list-default)
  "Key sequence to invoke math-mode's image completion.")

(defvar YaTeX-skip-default-reader nil
  "Non-nil skips default argument reader of section-type completion.")

(defvar YaTeX-simple-messages nil
  "Non-nil makes minibuffer messages simpler.")

(defvar YaTeX-template-file "~/work/template.tex"
  "*Template TeX source file.  This will be inserted to empty file.")

(defvar YaTeX-addin-prefix "YaTeX:")

(defvar yatex-mode-abbrev-table nil
  "*Abbrev table in use in yatex-mode buffers.")
(define-abbrev-table 'yatex-mode-abbrev-table ())


;------------ Completion table ------------
; Set tex-section-like command possible completion
(defvar section-table
  (append
   '(("part") ("chapter") ("chapter*") ("section") ("section*")
     ("subsection") ("subsection*")
     ("subsubsection") ("paragraph") ("subparagraph")
     ("author") ("thanks") ("documentstyle") ("pagestyle") ("thispagestyle")
     ("title") ("underline") ("label") ("makebox")
     ("footnote") ("footnotetext") ("index")
     ("hspace*") ("vspace*")
     ("bibliography") ("bibliographystyle") ("bibitem") ("cite")
     ("input") ("include") ("includeonly") ("mbox") ("hbox") ("caption")
     ("arabic") ("centering") ("uline")
     ("newcounter")
     ("newlength") ("setlength" 2) ("addtolength" 2) ("settowidth" 2)
     ("setcounter" 2) ("addtocounter" 2) ("stepcounter" 2)
     ("newcommand" 2) ("renewcommand" 2)
     ("newenvironment" 3) ("newtheorem" 2)
     ("cline") ("framebox") ("savebox" 2) ("sbox" 2) ("newsavebox") ("usebox")
     ("date") ("put") ("ref") ("pageref") ("tabref") ("figref") ("raisebox" 2)
     ("multicolumn" 3) ("shortstack") ("parbox" 2)
     ;; for mathmode accent
     ("tilde") ("hat") ("check") ("bar") ("dot") ("ddot") ("vec")
     ("widetilde") ("widehat") ("overline") ("overrightarrow")
     ;; section types in mathmode
     ("frac" 2) ("sqrt") ("mathrm") ("mathbf") ("mathit") ("mathbb")
     ("mathscr") ("mathrsfs")
     ;;cleveref
     ("cref") ("crefrange") ("cpageref") ("labelcref") ("labelcpageref")
     ("frametitle") ("framesubtitle") 				;; beamer
     ("subfigure")						;; subfigure
     ("ruby" 2) ("kenten")					;; okumacro
     ("geometry") ("path")
     )
   (if YaTeX-use-LaTeX2e
       '(("documentclass") ("usepackage")
	 ("textbf") ("textgt") ("textit") ("textmc") ("textmd") ("textnormal")
	 ("textrm") ("textsc") ("textsf") ("textsl") ("texttt") ("textup")
	 ("mathbf") ("mathcal") ("mathit") ("mathnormal") ("mathrm")
	 ("mathsf") ("mathtt") ("text")
	 ("textcircled")
	 ("scalebox" 1) ;is faking of argument position
	 ("rotatebox" 2) ("resizebox" 3) ("reflectbox")
	 ("colorbox" 2) ("fcolorbox" 3) ("textcolor" 2) ("color") ("pagecolor")
	 ("includegraphics") ("includegraphics*")
	 ("includesvg")
	 ("bou")			;defined in plext
	 ("url")			;defined in url
	 ("shadowbox") ("doublebox") ("ovalbox") ("Ovalbox")
	 ("fancyoval")			;defined in fancybox
	 ("keytop") ("mask" 2) ("maskbox" 5) ;defined in ascmac
	 ("bm")				;deined in bm
	 ("verbfile") ("listing")	;defined in misc
	 ("slashbox" 2) ("backslashbox" 2) ;defined in slashbox
	 ))
   (if YaTeX-use-AMS-LaTeX
       '(("DeclareMathOperator" 2) ("boldsymbol") ("pmb") ("eqref")
	 ("tag") ("tag*"))))
  "Default completion table for section-type completion.")

(defvar user-section-table nil)
(defvar tmp-section-table nil)
(defvar YaTeX-ams-math-begin-alist
  '(("align") ("align*") ("multline") ("multline*") ("gather") ("gather*")
    ("alignat") ("alignat*") ("xalignat") ("xalignat*")
    ("xxalignat") ("xxalignat*") ("flalign") ("flalign*") ("equation*")))
(defvar YaTeX-ams-math-gathering-alist
  '(("matrix") ("pmatrix") ("bmatrix") ("Bmatrix") ("vmatrix") ("Vmatrix")
    ("split") ("split*") ("aligned") ("aligned*") ("alignedat") ("gathered")
    ("smallmatrix") ("cases") ("subequations")))
;; Prepare list(not alist) for YaTeX::ref in yatexadd.el
(defvar YaTeX-math-other-env-alist-default
  '(("numcases") ("subnumcases"))
  "Default alist of additional environments for equations")
(defvar YaTeX-math-other-env-alist-private nil
  "*User defined alist of additional environments for equations")
(defvar YaTeX-math-other-env-alist
  (append YaTeX-math-other-env-alist-default
	  YaTeX-math-other-env-alist-private)
  "Alist of additional environments for equations")
(defvar YaTeX-math-other-env-list
  (mapcar 'car YaTeX-math-other-env-alist))

(defvar YaTeX-math-begin-list
  (mapcar 'car YaTeX-ams-math-begin-alist))
(defvar YaTeX-math-gathering-list	;used in yatexadd.el#yatex::ref
  (mapcar 'car YaTeX-ams-math-gathering-alist))

(defvar YaTeX-ams-env-table
  (append YaTeX-ams-math-begin-alist YaTeX-ams-math-gathering-alist)
  "*Standard AMS-LaTeX(2e) environment completion table.")

(defvar YaTeX-use-dot-env-extension t
  "*Use YaTeX's dot-env filter special environment.")

; Set tex-environment possible completion
(defvar env-table
  (append
   '(("quote") ("quotation") ("center") ("verse") ("document")
     ("verbatim") ("itemize") ("enumerate") ("description")
     ("list") ("tabular") ("tabular*") ("table") ("tabbing") ("titlepage")
     ("sloppypar") ("picture") ("displaymath")
     ("eqnarray") ("eqnarray*") ("figure") ("equation") ("equation*")
     ("abstract") ("array")
     ("thebibliography") ("theindex") ("flushleft") ("flushright")
     ("minipage") ("landscape")
     ("supertabular") ("floatingfigure") ("wrapfigure") ("wraptable")
     ("frame") ("block") ("example") ("columns") ("column")	;beamer
     ("tabularx")
     )
   (if YaTeX-use-LaTeX2e
       '(("comment")			;defined in version
	 ("longtable")			;defined in longtable
	 ("screen") ("boxnote") ("shadebox") ;; ("itembox") ;in ascmac
	 ("alltt")			;defined in alltt
	 ("multicols")			;defined in multicol
	 ("breakbox")))			;defined in eclbkbox
   (if YaTeX-use-AMS-LaTeX YaTeX-ams-env-table)
   YaTeX-math-other-env-alist
   (and YaTeX-use-dot-env-extension
	(require 'yatexflt)
	YaTeX-filter-special-env-alist))
  "Default completion table for begin-type completion.")

(defvar user-env-table nil)
(defvar tmp-env-table nil)

; Set {\Large }-like completion
(defvar fontsize-table
  '(("rm") ("em") ("bf") ("boldmath") ("it") ("sl") ("sf") ("sc") ("tt")
    ("dg") ("dm")
    ("tiny") ("scriptsize") ("footnotesize") ("small")("normalsize")
    ("large") ("Large") ("LARGE") ("huge") ("Huge")
    ("rmfamily") ("sffamily") ("ttfamily")
    ("mdseries") ("bfseries") ("upshape")
    ("itshape") ("slshape") ("scshape")
    )
  "Default completion table for large-type completion.")

(defvar LaTeX2e-fontstyle-alist
  '(("rm" . "rmfamily")
    ("sf" . "sffamily")
    ("tt" . "ttfamily")
    ("md" . "mdseries")
    ("bf" . "bfseries")
    ("up" . "upshape")
    ("it" . "itshape")
    ("sl" . "slshape")
    ("sc" . "scshape")))

(defvar user-fontsize-table nil)
(defvar tmp-fontsize-table nil)

(defvar singlecmd-table
  (append
   '(("maketitle") ("makeindex") ("sloppy") ("protect") ("par") ("and")
     ("LaTeX") ("TeX") ("item") ("item[]") ("appendix") ("hline") ("kill")
     ;;("rightarrow") ("Rightarrow") ("leftarrow") ("Leftarrow")
     ("onecolumn") ("twocolumn")
     ("pagebreak") ("nopagebreak") ("tableofcontents")
     ("newpage") ("clearpage") ("cleardoublepage")
     ("footnotemark") ("verb") ("verb*")
     ("linebreak") ("pagebreak") ("noindent") ("indent")
     ("raggedright") ("raggedleft") ("centering")
     ("left") ("right") ("dots") ("smallskip") ("medskip") ("bigskip")
     ("displaystyle")
     ("onslide") ("pause")		;beamer
     )
   (if YaTeX-greek-by-maketitle-completion
       '(("alpha") ("beta") ("gamma") ("delta") ("epsilon")
	 ("varepsilon") ("zeta") ("eta") ("theta")("vartheta")
	 ("iota") ("kappa") ("lambda") ("mu") ("nu") ("xi") ("pi")
	 ("varpi") ("rho") ("varrho") ("sigma") ("varsigma") ("tau")
	 ("upsilon") ("phi") ("varphi") ("chi") ("psi") ("omega")
	 ("Gamma") ("Delta") ("Theta") ("Lambda")("Xi") ("Pi")
	 ("Sigma") ("Upsilon") ("Phi") ("Psi") ("Omega")))
   (if YaTeX-use-LaTeX2e
       '(("return") ("Return") ("yen")))	;defined in ascmac
   (if YaTeX-use-AMS-LaTeX
       '(("nonumber")))
   )
  "Default completion table for maketitle-type completion.")

(defvar user-singlecmd-table nil)
(defvar tmp-singlecmd-table nil)

;---------- Key mode map ----------
;;;
;; Create new key map: YaTeX-mode-map
;; Do not change this section.
;;;
(defvar YaTeX-mode-map nil
  "Keymap used in YaTeX mode")

(defvar YaTeX-prefix-map nil
  "Keymap used when YaTeX-prefix key pushed")

(defvar YaTeX-user-extensional-map (make-sparse-keymap)
  "*Keymap used for the user's customization")
(defvar YaTeX-current-completion-type nil
  "Has current completion type.  This may be used in YaTeX addin functions.")

(defvar YaTeX-modify-mode nil
  "*Current editing mode.
When non-nil, each opening parentheses only opens,
nil enters both open/close parentheses when opening parentheses key pressed.")

(defvar YaTeX-math-mode nil
  "Holds whether current mode is math-mode.")
;;;
;; Define key table
;;;
(if YaTeX-mode-map 
    nil
  (setq YaTeX-mode-map (make-sparse-keymap))
  (setq YaTeX-prefix-map (make-sparse-keymap))
  (define-key YaTeX-mode-map "\"" 'YaTeX-insert-quote)
  (define-key YaTeX-mode-map "{" 'YaTeX-insert-braces)
  (define-key YaTeX-mode-map "(" 'YaTeX-insert-parens)
  (define-key YaTeX-mode-map "$" 'YaTeX-insert-dollar)
  (define-key YaTeX-mode-map "|" 'YaTeX-insert-bar)
  (define-key YaTeX-mode-map "&" 'YaTeX-insert-amper)
  (define-key YaTeX-mode-map "[" 'YaTeX-insert-brackets)
  (define-key YaTeX-mode-map YaTeX-prefix YaTeX-prefix-map)
  (define-key YaTeX-mode-map "\M-\C-@" 'YaTeX-mark-environment)
  (define-key YaTeX-mode-map "\M-\C-a" 'YaTeX-beginning-of-environment)
  (define-key YaTeX-mode-map "\M-\C-e" 'YaTeX-end-of-environment)
  (define-key YaTeX-mode-map "\M-\C-m" 'YaTeX-intelligent-newline)
  (define-key YaTeX-mode-map "\C-i" 'YaTeX-indent-line)
  (YaTeX-define-key "%" 'YaTeX-%-menu)
  (YaTeX-define-key "t" 'YaTeX-typeset-menu)
  (YaTeX-define-key "w" 'YaTeX-switch-mode-menu)
  (YaTeX-define-key "'" 'YaTeX-prev-error)
  (YaTeX-define-key "^" 'YaTeX-visit-main)
  (YaTeX-define-key "4^" 'YaTeX-visit-main-other-window)
  (YaTeX-define-key "4g" 'YaTeX-goto-corresponding-*-other-window)
  (YaTeX-define-key "44" 'YaTeX-switch-to-window)
  (and YaTeX-emacs-19 window-system
       (progn
	 (YaTeX-define-key "5^" 'YaTeX-visit-main-other-frame)
	 (YaTeX-define-key "5g" 'YaTeX-goto-corresponding-*-other-frame)
	 (YaTeX-define-key "55" 'YaTeX-switch-to-window)))
  (YaTeX-define-key " " 'YaTeX-do-completion)
  (YaTeX-define-key "v" 'YaTeX-version)

  (YaTeX-define-key "}" 'YaTeX-insert-braces-region)
  (YaTeX-define-key "]" 'YaTeX-insert-brackets-region)
  (YaTeX-define-key ")" 'YaTeX-insert-parens-region)
  (YaTeX-define-key "$" 'YaTeX-insert-dollars-region)
  (YaTeX-define-key "i" 'YaTeX-fill-item)
  (YaTeX-define-key "\\"
   (function(lambda () (interactive)
      (insert (if (YaTeX-in-math-mode-p) "\\backslash" "\\textbackslash")))))
  (if YaTeX-no-begend-shortcut
      (progn
	(YaTeX-define-key "B" 'YaTeX-make-begin-end-region)
	(YaTeX-define-key "b" 'YaTeX-make-begin-end))
    (YaTeX-define-begend-key "bc" "center")
    (YaTeX-define-begend-key "bd" "document")
    (YaTeX-define-begend-key "bD" "description")
    (YaTeX-define-begend-key "be" "enumerate")
    (YaTeX-define-begend-key "bE" "equation")
    (YaTeX-define-begend-key "bf" "figure")
    (YaTeX-define-begend-key "bi" "itemize")
    (YaTeX-define-begend-key "bl" "flushleft")
    (YaTeX-define-begend-key "bm" "minipage")
    (YaTeX-define-begend-key "bt" "tabbing")
    (YaTeX-define-begend-key "bT" "tabular")
    (YaTeX-define-begend-key "b\^t" "table")
    (YaTeX-define-begend-key "bp" "picture")
    (YaTeX-define-begend-key "bq" "quote")
    (YaTeX-define-begend-key "bQ" "quotation")
    (YaTeX-define-begend-key "br" "flushright")
    (YaTeX-define-begend-key "bv" "verbatim")
    (YaTeX-define-begend-key "bV" "verse")
    (YaTeX-define-key "B " 'YaTeX-make-begin-end-region)
    (YaTeX-define-key "b " 'YaTeX-make-begin-end))
  (YaTeX-define-key "e" 'YaTeX-end-environment)
  (YaTeX-define-key "S" 'YaTeX-make-section-region)
  (YaTeX-define-key "s" 'YaTeX-make-section)
  (YaTeX-define-key "L" 'YaTeX-make-fontsize-region)
  (YaTeX-define-key "l" 'YaTeX-make-fontsize)
  (YaTeX-define-key "m" 'YaTeX-make-singlecmd)
  (YaTeX-define-key "." 'YaTeX-comment-paragraph)
  (YaTeX-define-key "," 'YaTeX-uncomment-paragraph)
  (YaTeX-define-key ">" 'YaTeX-comment-region)
  (YaTeX-define-key "<" 'YaTeX-uncomment-region)
  (YaTeX-define-key "g" 'YaTeX-goto-corresponding-*)
  (YaTeX-define-key "k" 'YaTeX-kill-*)
  (YaTeX-define-key "c" 'YaTeX-change-*)
  (YaTeX-define-key "a" 'YaTeX-make-accent)
  (YaTeX-define-key "?" 'YaTeX-help)
  (YaTeX-define-key "/" 'YaTeX-apropos)
  (YaTeX-define-key "&" 'YaTeX-what-column)
  (YaTeX-define-key "d" 'YaTeX-display-hierarchy)
  (YaTeX-define-key "x" YaTeX-user-extensional-map)
  (YaTeX-define-key "n"
    (function(lambda () (interactive)
       (insert "\\" (if (YaTeX-on-section-command-p "o?oalign") "crcr" "\\")))))
  (if YaTeX-dos
      (define-key YaTeX-prefix-map "\C-r"
	(function(lambda () (interactive)
	   (YaTeX-set-screen-height YaTeX-saved-screen-height) (recenter))))))

(defvar YaTeX-section-completion-map nil
  "*Key map used at YaTeX completion in the minibuffer.")
(if YaTeX-section-completion-map nil
  (setq YaTeX-section-completion-map
	(copy-keymap (or (and (boundp 'gmhist-completion-map)
			      gmhist-completion-map)
			 minibuffer-local-completion-map)))
  (define-key YaTeX-section-completion-map
    " " 'YaTeX-minibuffer-complete)
  (define-key YaTeX-section-completion-map
    "\C-i" 'YaTeX-minibuffer-complete)
  (define-key YaTeX-section-completion-map
    "\C-v" 'YaTeX-read-section-with-overview))

(defvar YaTeX-recursive-map nil
  "*Key map used at YaTeX reading arguments in the minibuffer.")
(if YaTeX-recursive-map nil
  (setq YaTeX-recursive-map (copy-keymap global-map))
  (define-key YaTeX-recursive-map YaTeX-prefix YaTeX-prefix-map)
  (mapcar
   (function
    (lambda (key)
      (define-key YaTeX-mode-map (car key) 'YaTeX-math-insert-sequence)
      (define-key YaTeX-recursive-map (car key) 'YaTeX-math-insert-sequence)))
   YaTeX-math-key-list))
;---------- Define other variable ----------
(defvar YaTeX-env-name "document" "*Initial tex-environment completion")
(defvar YaTeX-section-name
  (if YaTeX-use-LaTeX2e "documentclass" "documentstyle")
  "*Initial tex-section completion")
(defvar YaTeX-fontsize-name "large" "*Initial fontsize completion")
(defvar YaTeX-single-command "maketitle" "*Initial LaTeX single command")
(defvar YaTeX-kanji-code nil
  "*File kanji code used by Japanese TeX.
nil: Do not care (Preserve coding-system)
0: no-conversion (mule)
1: Shift JIS
2: JIS
3: EUC
4: UTF-8")

(defvar YaTeX-coding-system nil "File coding system used by Japanese TeX.")
(cond
 (YaTeX-emacs-20
  (setq YaTeX-coding-system
	(cdr (assoc YaTeX-kanji-code YaTeX-kanji-code-alist))))
 ((boundp 'MULE)
  (setq YaTeX-coding-system
	(symbol-value (cdr (assoc YaTeX-kanji-code YaTeX-kanji-code-alist))))))

(defvar YaTeX-mode-syntax-table nil
  "*Syntax table for yatex-mode")

(if YaTeX-mode-syntax-table nil
  (setq YaTeX-mode-syntax-table (make-syntax-table (standard-syntax-table)))
  (modify-syntax-entry ?\n " " YaTeX-mode-syntax-table)
  (modify-syntax-entry ?\{ "(}" YaTeX-mode-syntax-table)
  (modify-syntax-entry ?\} "){" YaTeX-mode-syntax-table)
  (modify-syntax-entry ?\t " " YaTeX-mode-syntax-table)
  (modify-syntax-entry ?\f ">" YaTeX-mode-syntax-table)
  (modify-syntax-entry ?\n ">" YaTeX-mode-syntax-table)
  (modify-syntax-entry ?$ "$$" YaTeX-mode-syntax-table)
  (modify-syntax-entry ?% "<" YaTeX-mode-syntax-table)
  (modify-syntax-entry ?\\ "/" YaTeX-mode-syntax-table)
  (modify-syntax-entry ?~ " " YaTeX-mode-syntax-table))

(defvar YaTeX-mode-syntax-table-nonparen nil
  "Syntax table for yatex-mode with normal parentheses treated white spaces")
(if YaTeX-mode-syntax-table-nonparen nil
  (setq YaTeX-mode-syntax-table-nonparen
	(make-syntax-table YaTeX-mode-syntax-table))
  (let ((zenparens "()ijuvwxyzmnopstqrkl") (i 0) s)
    (while (string-match "." zenparens i)
      (setq s (substring zenparens (match-beginning 0) (match-end 0))
	    i (1+ i))
      (modify-syntax-entry
       (string-to-char s) " " YaTeX-mode-syntax-table-nonparen))))

;---------- Provide YaTeX-mode ----------
;;;
;; Major mode definition
;;;
(defun yatex-mode ()
  "  Yet Another LaTeX mode: Major mode for editing input files of LaTeX.
-You can invoke processes concerning LaTeX typesetting by
 		\\[YaTeX-typeset-menu]
-Complete LaTeX environment form of `\\begin{env} ... \\end{env}' by
		\\[YaTeX-make-begin-end]
-Enclose region into some environment by
		\\[universal-argument] \\[YaTeX-make-begin-end]
-Complete LaTeX command which takes argument like `\\section{}' by
		\\[YaTeX-make-section]
-Put LaTeX command which takes no arguments like `\\maketitle' by
		\\[YaTeX-make-singlecmd]
-Complete font or character size descriptor like `{\\large }' by
		\\[YaTeX-make-fontsize]
-Enclose region into those descriptors above by
		\\[universal-argument] \\[YaTeX-make-fontsize]
-Enter European accent notations by
		\\[YaTeX-make-accent]
-Toggle various modes of YaTeX by
		\\[YaTeX-switch-mode-menu]
-Change environt name (on the begin/end line) by
		\\[YaTeX-change-*]
-Kill LaTeX command/environment sequences by
		\\[YaTeX-kill-*]
-Kill LaTeX command/environment with its contents 
		\\[universal-argument] \\[YaTeX-kill-*]
-Go to corresponding object (begin/end, file, labels) by
		\\[YaTeX-goto-corresponding-*]   or
		\\[YaTeX-goto-corresponding-*-other-window]   (in other window)
		\\[YaTeX-goto-corresponding-*-other-frame]   (in other frame)
-Go to main LaTeX source text by
		\\[YaTeX-visit-main]   or
		\\[YaTeX-visit-main-other-window]   (in other window)
		\\[YaTeX-visit-main-other-frame]   (in other frame)
-Comment out or uncomment region by
		\\[YaTeX-comment-region]  or  \\[YaTeX-uncomment-region]
-Comment out or uncomment paragraph by
		\\[YaTeX-comment-paragraph]  or  \\[YaTeX-uncomment-paragraph]
-Make an \\item entry hang-indented by
		\\[YaTeX-fill-item]
-Enclose the region with parentheses by
		\\[YaTeX-insert-parens-region]
		\\[YaTeX-insert-braces-region]
		\\[YaTeX-insert-brackets-region]
		\\[YaTeX-insert-dollars-region]
-Look up the corresponding column header of tabular environment by
		\\[YaTeX-what-column]
-Enter a newline and an entry suitable for environment by
		\\[YaTeX-intelligent-newline]
-View the structure of file inclusion by
		\\[YaTeX-display-hierarchy]
-Refer the online help of popular LaTeX commands by
		\\[YaTeX-help]   (help)
		\\[YaTeX-apropos]   (apropos)
-Edit `%# notation' by
		\\[YaTeX-%-menu]

  Those are enough for fastening your editing of LaTeX source.  But further
more features are available and they are documented in the manual.
"
  (interactive)
  (kill-all-local-variables)
  (setq major-mode 'yatex-mode)
  (setq mode-name (if YaTeX-japan "Ă" "YaTeX"))
  (mapcar 'make-local-variable
	  '(dvi2-command fill-column fill-prefix
	    tmp-env-table tmp-section-table tmp-fontsize-table
	    tmp-singlecmd-table paragraph-start paragraph-separate
	    YaTeX-math-mode indent-line-function comment-line-break-function
	    comment-start comment-start-skip
	    ))
  (YaTeX-set-file-coding-system YaTeX-kanji-code YaTeX-coding-system)
  (setq fill-column YaTeX-fill-column
	fill-prefix YaTeX-fill-prefix
	paragraph-start    YaTeX-paragraph-start
	paragraph-separate YaTeX-paragraph-separate
	indent-line-function 'YaTeX-indent-line
	comment-start YaTeX-comment-prefix
	comment-end ""
	comment-start-skip "[^\\\\]%+[ \t]*"
	local-abbrev-table yatex-mode-abbrev-table)
  (if (fboundp 'comment-indent-new-line) ;for Emacs21
      (setq comment-line-break-function 'YaTeX-comment-line-break))
  ;; +dnd for X11 w/ emacs23+
  (and window-system (featurep 'dnd) (require 'yatex23 nil t)
       (set (make-local-variable 'dnd-protocol-alist)
	    (cons (cons "^file:" 'YaTeX-dnd-handler) dnd-protocol-alist)))

  (if (and YaTeX-use-font-lock (featurep 'font-lock))
      (progn
	(require 'yatex19)
	(YaTeX-font-lock-set-default-keywords)
	(or  (featurep 'xemacs)
	     (set (make-local-variable 'font-lock-defaults)
		  (get 'yatex-mode 'font-lock-defaults)))
	;;(font-lock-mode 1)
	))
  (use-local-map YaTeX-mode-map)
  (set-syntax-table YaTeX-mode-syntax-table)
  (if YaTeX-dos (setq YaTeX-saved-screen-height (YaTeX-screen-height)))
  (YaTeX-read-user-completion-table)
  (and (fboundp 'YaTeX-hilit-setup-alist) (YaTeX-hilit-setup-alist))
  (makunbound 'inenv)
  ;(turn-on-auto-fill)			;1.63 -> 1.79off
  (if (fboundp 'electric-indent-local-mode)
      (electric-indent-local-mode YaTeX-electric-indent-mode))
  (and (= 0 (buffer-size)) (file-exists-p YaTeX-template-file)
       (y-or-n-p (format "Insert %s?" YaTeX-template-file))
       (insert-file-contents (expand-file-name YaTeX-template-file)))
  (run-hooks 'text-mode-hook 'yatex-mode-hook))

;---------- Define YaTeX-mode functions ----------
(defvar YaTeX-ec "\\" "Escape character of current mark-up language.")
(defvar YaTeX-ec-regexp (regexp-quote YaTeX-ec))
(defvar YaTeX-struct-begin
  (concat YaTeX-ec "begin{%1}%2")
  "Keyword format of begin-environment.")
(defvar YaTeX-struct-end
  (concat YaTeX-ec "end{%1}")
  "Keyword format of end-environment.")
(defvar YaTeX-struct-name-regexp "[^}]*"
  "Environment name regexp.")
(defvar YaTeX-TeX-token-regexp
  (cond (YaTeX-japan "[A-Za-z*--]+")
	(t "[A-Za-z*]+"))
  "Regexp of characters which can be a member of TeX command's name.")
(defvar YaTeX-kanji-regexp "[--]"
  "Generic regexp of Japanese Kanji (and symbol) characters.")
(defvar YaTeX-command-token-regexp YaTeX-TeX-token-regexp
  "Regexp of characters which can be a member of current mark up language's command name.")

;;(defvar YaTeX-struct-section
;;  (concat YaTeX-ec "%1{%2}")
;;  "Keyword to make section.")

;;;
;; autoload section
;;;

;;autoload from yatexprc.el
(autoload 'YaTeX-visit-main "yatexprc" "Visit main LaTeX file." t)
(autoload 'YaTeX-visit-main-other-window "yatexprc"
  "Visit main other window." t)
(autoload 'YaTeX-main-file-p "yatexprc" "Check if the file is main." t)
(autoload 'YaTeX-get-builtin "yatexprc" "Get %# built-in." t)
(autoload 'YaTeX-system "yatexprc" "Call system command" t)
(autoload 'YaTeX-save-buffers "yatexprc" "Save buffers of same major mode" t)
(autoload 'YaTeX-goto-corresponding-viewer "yatexprc" "Viewer jump line" t)

;;autoload from yatexmth.el
(autoload 'YaTeX-math-insert-sequence "yatexmth" "Image input." t)
(autoload 'YaTeX-in-math-mode-p "yatexmth" "Check if in math-env." t)
(autoload 'YaTeX-toggle-math-mode "yatexmth" "YaTeX math-mode interfaces." t)
(autoload 'YaTeX-math-member-p "yatexmth" "Check if a word is math command." t)
(autoload 'YaTeX-insert-amsparens-region "yatexmth" "AMS parens region" t)
(autoload 'YaTeX-insert-amsbraces-region "yatexmth" "AMS braces region" t)
(autoload 'YaTeX-insert-amsbrackets-region "yatexmth" "AMS brackets region" t)
(autoload 'YaTeX-on-parenthesis-p "yatexmth" "Check if on math-parens" t)
(autoload 'YaTeX-goto-open-paren "yatexmth" "Goto opening paren" t)
(autoload 'YaTeX-change-parentheses "yatexmth" "Change corresponding parens" t)
(autoload 'YaTeX-goto-corresponding-paren "yatexmth" "\bigl\bigr jumps" t)
(autoload 'YaTeX-typeset-math-region "yatexmth" "Typeset math-region" t)

;;autoload from yatexhlp.el
(autoload 'YaTeX-help "yatexhlp" "YaTeX helper with LaTeX commands." t)
(autoload 'YaTeX-apropos "yatexhlp" "Apropos for (La)TeX commands." t)

;;autoload from yatexgen.el
(autoload 'YaTeX-generate "yatexgen" "YaTeX add-in function generator." t)
(autoload 'YaTeX-generate-simple "yatexgen" "YaTeX add-in support." t)

;;autoload from yatexsec.el
(autoload 'YaTeX-section-overview "yatexsec" "YaTeX sectioning(view)" t)
(autoload 'YaTeX-read-section-in-minibuffer "yatexsec" "YaTeX sectioning" t)
(autoload 'YaTeX-make-section-with-overview "yatexsec" "YaTeX sectioning" t)

;;autoload from yatexenv.el
(autoload 'YaTeX-what-column "yatexenv" "YaTeX env. specific funcs" t)
(autoload 'YaTeX-intelligent-newline "yatexenv" "YaTeX env. specific funcs" t)
(autoload 'YaTeX-indent-line-equation "yatexenv" "Indent equation lines." t)
(autoload 'YaTeX-goto-corresponding-leftright "yatexenv" "\\=\\left\\=\\right jumps" t)

;;autoload from yatexhie.el
(autoload 'YaTeX-display-hierarchy "yatexhie"
  "YaTeX document hierarchy browser" t)
(autoload 'YaTeX-display-hierarchy-directly "yatexhie"
  "Same as YaTeX-display-hierarchy.  Call from mouse." t)

;;autoload from yatexpkg.el
(autoload 'YaTeX-package-auto-usepackage "yatexpkg" "Auto \\usepackage" t)

;;autoload from yatexflt.el
(autoload 'YaTeX-filter-goto-source "yatexflt" "Go to graphic source file" t)

;;;
;; YaTeX-mode functions
;;;
(defun YaTeX-insert-begin-end (env region-mode)
  "Insert \\begin{mode-name} and \\end{mode-name}.
This works also for other defined begin/end tokens to define the structure."
  (setq YaTeX-current-completion-type 'begin)
  (let*((ccol (current-column)) beg beg2 exchange
	(arg region-mode)		;for old compatibility
	(indent-column (+ ccol YaTeX-environment-indent))(i 1) func)
    (if (and region-mode (> (point) (mark)))
	(progn (exchange-point-and-mark)
	       (setq exchange t
		     ccol (current-column)
		     indent-column (+ ccol YaTeX-environment-indent))))
    ;;VER2 (insert "\\begin{" env "}" (YaTeX-addin env))
    (setq beg (point))
    (YaTeX-insert-struc 'begin env)
    (setq beg2 (point))
    (insert "\n")
    (indent-to indent-column)
    (save-excursion
      ;;indent optional argument of \begin{env}, if any
      (while (> (point-beginning-of-line) beg)
	(skip-chars-forward "\\s " (point-end-of-line))
	(indent-to indent-column)
	(forward-line -1)))
    (require 'yatexenv)
    (if region-mode
	  ;;if region-mode, indent all text in the region
	(save-excursion
	  (if (fboundp (intern-soft (concat "YaTeX-enclose-" env)))
	      (funcall (intern-soft (concat "YaTeX-enclose-" env))
		       (point) (mark))
	    (while (< (progn (forward-line 1) (point)) (mark))
	      (if (eolp) nil
		(skip-chars-forward " \t\n")
		(indent-to indent-column))))))
    (if region-mode (exchange-point-and-mark))
    (indent-to ccol)
    ;;VER2 (insert "\\end{" env "}\n")
    (YaTeX-insert-struc 'end env)
    (YaTeX-reindent ccol)
    (if region-mode
	(progn
	  (insert "\n")
	  (or exchange (exchange-point-and-mark)))
      (goto-char beg2)
      (YaTeX-intelligent-newline nil)
      (if (fboundp (intern-soft (concat "YaTeX-intelligent-newline-" env)))
	  (progn
	    (message
	     (cond
	      (YaTeX-japan "%s Ŏ̍s̓͂ɐi݂܂B")
	      (t "`%s' produces the next line's template."))
	     (key-description
	      (car (where-is-internal 'YaTeX-intelligent-newline))))))
      (YaTeX-indent-line))
    (YaTeX-package-auto-usepackage env 'env)
    (if YaTeX-current-position-register
	(point-to-register YaTeX-current-position-register))))

(defun YaTeX-make-begin-end (arg)
  "Make LaTeX environment command of \\begin{env.} ... \\end{env.}
by completing read.
 If you invoke this command with universal argument,
\(key binding for universal-argument is \\[universal-argument]\)
you can put REGION into that environment between \\begin and \\end.
If the environment name begins with `.'(dot),
that environment will be treated as `special environment', which
enables special feature such as text conversion."
  (interactive "P")
  (let*
      ((region-p (or arg (YaTeX-region-active-p)))
       (mode (if region-p " region" ""))
       (env
	(save-excursion		;for Emacs24 work-around to avoid point warp 
	  (YaTeX-read-environment
	   (format "Begin environment%s(default %s): " mode YaTeX-env-name))))
       special)
    (if (string= env "")
	(setq env YaTeX-env-name))
    (setq special (assoc env YaTeX-filter-special-env-alist)
	  YaTeX-env-name env)
    (YaTeX-update-table
     (list YaTeX-env-name) 'env-table 'user-env-table 'tmp-env-table)
    (if special
	(YaTeX-insert-filter-special YaTeX-env-name (cdr special) region-p)
      (YaTeX-insert-begin-end YaTeX-env-name region-p))))

(defun YaTeX-make-begin-end-region ()
  "Call YaTeX-make-begin-end with ARG to specify region mode."
  (interactive)
  (YaTeX-make-begin-end t))

(defun YaTeX-guess-section-type ()
  (if (eq major-mode 'yatex-mode)
      (save-excursion
	(cond
	 ((save-excursion (not (search-backward YaTeX-ec nil t)))
	  (if YaTeX-use-LaTeX2e "documentclass" "documentstyle"))
	 ((progn
	    (if (= (char-after (1- (point))) ?~) (forward-char -1))
	    (forward-char -1) (looking-at "\\\|}\\|\\|"))
	  "ref")
	 ((and (looking-at "[a-z \t]")
	       (progn (skip-chars-backward "a-z \t")
		      (looking-at "table\\|figure\\|formula\\|eq\\(\\.\\|uation\\)")))
	  "ref")
	 ((save-excursion
	    (skip-chars-backward "[^A-]")
	    (looking-at "vO\\|Xg"))
	  "ref")
	 ((YaTeX-re-search-active-backward
	   (concat YaTeX-ec-regexp "begin{\\([^}]+\\)}")
	   (regexp-quote YaTeX-comment-prefix)
	   (save-excursion (forward-line -1) (point))
	   t)
	  (let ((env (YaTeX-match-string 1)))
	    (cdr (assoc env
			'(("table" . "caption"))))))
	 ))))

(defun YaTeX-make-section (arg &optional beg end cmd)
  "Make LaTeX \\section{} type command with completing read.
With numeric ARG, you can specify the number of arguments of
LaTeX command.
  For example, if you want to produce LaTeX command

	\\addtolength{\\topmargin}{8mm}

which has two arguments.  You can produce that sequence by typing...
	ESC 2 C-c s add SPC RET \\topm SPC RET 8mm RET
\(by default\)
Then yatex will automatically complete `addtolength' with two arguments
next time.
  You can complete symbol at LaTeX command and the 1st argument.

If the optional 2nd and 3rd argument BEG END are specified, enclose
the region from BEG to END into the first argument of the LaTeX sequence.
Optional 4th arg CMD is LaTeX command name, for non-interactive use."
  (interactive "P")
  (setq YaTeX-current-completion-type 'section)
  (if (or (equal arg '(4)) (YaTeX-region-active-p))
      (setq beg (region-beginning) end (region-end)))
  (unwind-protect
      (let*
	  ((source-window (selected-window))
	   guess
	   (section
	    (or cmd
		(progn
		  (setq guess
			(or (YaTeX-guess-section-type) YaTeX-section-name))
		  (YaTeX-read-section
		   (if YaTeX-simple-messages
		       (format "Section-type (default %s): " guess)
		     (if (> (minibuffer-depth) 0)
			 (format "%s???{} (default %s)%s: "
				 YaTeX-ec guess
				 (format "[level:%d]" (minibuffer-depth)))
		       (format "(C-v for view-section) %s???{%s} (default %s): "
			       YaTeX-ec (if beg "region" "") guess)))
		   nil))))
	   (section (if (string= section "") guess section))
	   (numarg	;; The number of section-type command's argument
	    (or (and (numberp arg) arg)
		(nth 1 (YaTeX-lookup-table section 'section))
		1))
	   (arg-reader (intern-soft (concat "YaTeX::" section)))
	   (addin-args (and arg-reader (fboundp arg-reader)))
	   (title "")
	   (j 1)
	   (after-change-functions nil)	;inhibit font-locking temporarily
	   (enable-recursive-minibuffers t)
	   (mkarg-func
	    (function
	     (lambda (n)
	       (while (<= j n)
		 (unwind-protect
		     (setq title
			   (cond
			    (addin-args (funcall arg-reader j))
			    (YaTeX-skip-default-reader "")
			    (t
			     (read-string-with-history
			      (format "Argument %d of %s: " j section)))))
		   (insert
		    (concat		;to allow nil return value
		     "{" title "}")))
		 (setq j (1+ j))))))
	   );;let
	(setq YaTeX-section-name section)
	(if beg
	    (let*((e (make-marker))
		  (ar2 (intern-soft (concat "YaTeX::" section "-region")))
		  (arp (and ar2 (fboundp ar2))))
	      (goto-char end)
	      (insert "}")
	      (set-marker e (point))
	      (goto-char beg)
	      (unwind-protect
		  (progn
		    (insert YaTeX-ec YaTeX-section-name
			    (YaTeX-addin YaTeX-section-name))
		    (if (> numarg 1) (funcall mkarg-func (1- numarg))))
		(insert "{"))
	      (if arp (funcall ar2 (point) e))
	      (goto-char e)
	      (set-marker e nil))
	  (use-global-map YaTeX-recursive-map)
	  (if (= numarg 0) (YaTeX-make-singlecmd YaTeX-section-name)
	    (progn (insert YaTeX-ec YaTeX-section-name)
		   (insert (YaTeX-addin YaTeX-section-name))))
	  ;;read arguments with add-in
	  (funcall mkarg-func numarg))
	(YaTeX-update-table
	 (if (/= numarg 1) (list section numarg)
	   (list section))
	 'section-table 'user-section-table 'tmp-section-table)
	(if YaTeX-current-position-register
	    (point-to-register YaTeX-current-position-register))
	(if (string= (YaTeX-buffer-substring (- (point) 2) (point))
		     "{}")
	    (forward-char -1))
	(while (string= (YaTeX-buffer-substring (- (point) 3) (1- (point)))
			"{}")
	  (forward-char -2))
	(YaTeX-package-auto-usepackage section 'section))
    (if (<= (minibuffer-depth) 0) (use-global-map global-map))
    (insert "")))		;insert dummy string to fontify(Emacs20)

(defun YaTeX-make-section-region (args beg end)
  "Call YaTeX-make-section with arguments to specify region mode."
 (interactive "P\nr")
 (YaTeX-make-section args beg end))

(defun YaTeX-make-fontsize (arg &optional fontsize)
  "Make completion like {\\large ...} or {\\slant ...} in minibuffer.
If you invoke this command with universal argument, you can put region
into {\\xxx } braces.
\(key binding for universal-argument is \\[universal-argument]\)"
  (interactive "P")
  (YaTeX-sync-local-table 'tmp-fontsize-table)
  (let* ((region-p (if (or arg (YaTeX-region-active-p))
		       (cons (region-beginning) (region-end))))
	 (mode (if region-p "region" ""))
	 (fontsize
	  (or fontsize
	      (YaTeX-read-fontsize
	       (if YaTeX-simple-messages
		   (format "Font or size (default %s): " YaTeX-fontsize-name)
		 (format "{\\??? %s} (default %s)%s: " mode YaTeX-fontsize-name
			 (if (> (minibuffer-depth) 0)
			     (format "[level:%d]" (minibuffer-depth)) "")))
	       nil nil))))
    (if (string= fontsize "")
	(setq fontsize YaTeX-fontsize-name))
    (setq YaTeX-current-completion-type 'large)
    (setq YaTeX-fontsize-name fontsize)
    (YaTeX-update-table
     (list YaTeX-fontsize-name)
     'fontsize-table 'user-fontsize-table 'tmp-fontsize-table)
    (and YaTeX-use-LaTeX2e
	 (YaTeX-latex2e-p)
	 (setq fontsize
	       (cdr (assoc YaTeX-fontsize-name LaTeX2e-fontstyle-alist)))
	 (setq YaTeX-fontsize-name fontsize))
    (if region-p
	(let ((b (car region-p))
	      (e (set-marker (make-marker) (cdr region-p))))
	  (goto-char b)
	  (insert "{\\" YaTeX-fontsize-name " ")
 	  (goto-char e)
	  (insert "}")
	  (set-marker e nil))
      (insert (concat "{\\" YaTeX-fontsize-name " }"))
      (forward-char -1)
      (if YaTeX-current-position-register
	  (point-to-register YaTeX-current-position-register))
      (save-excursion
	(insert (YaTeX-addin YaTeX-fontsize-name)))
      (YaTeX-package-auto-usepackage YaTeX-fontsize-name 'large))))

(defun YaTeX-make-fontsize-region ()
  "Call function:YaTeX-make-fontsize with ARG to specify region mode."
  (interactive)
  (YaTeX-make-fontsize t))

(defvar YaTeX-singlecmd-suffix "" "*Suffix for maketitle-type commands.")
(defvar YaTeX-read-singlecmd-history nil "Holds maketitle-type history.")
(put 'YaTeX-read-singlecmd-history 'no-default t)
(defun YaTeX-make-singlecmd (single)
  (interactive
   (list (YaTeX-cplread-with-learning
	  (if YaTeX-simple-messages
	      (format "maketitle-type (default %s): " YaTeX-single-command)
	    (format "%s??? (default %s)%s: " YaTeX-ec YaTeX-single-command
		    (if (> (minibuffer-depth) 0)
			(format "[level:%d]" (minibuffer-depth)) "")))
	  'singlecmd-table 'user-singlecmd-table 'tmp-singlecmd-table
	  nil nil nil 'YaTeX-read-singlecmd-history)))
  (if (string= single "")
      (setq single YaTeX-single-command))
  (setq YaTeX-single-command single)
  (setq YaTeX-current-completion-type 'maketitle)
  (let ((dollar (and (not (YaTeX-in-math-mode-p))
		     (YaTeX-math-member-p YaTeX-single-command)))
	p q)
    (if dollar (insert "$"))
    (insert YaTeX-ec YaTeX-single-command)
    (setq p (point))
    (insert (YaTeX-addin single) YaTeX-singlecmd-suffix)
    (if dollar (insert "$"))
    (setq q (point))
    (goto-char p)
    (forward-char -2)
    (if (looking-at "\\[\\]") (forward-char 1) (goto-char q)))
  (YaTeX-package-auto-usepackage YaTeX-single-command 'maketitle)
  (if YaTeX-current-position-register
      (point-to-register YaTeX-current-position-register)))

(defvar YaTeX-completion-begin-regexp "[{\\]"
  "Regular expression of limit where LaTeX command's completion begins.")

(defun YaTeX-do-completion ()
  "Try completion on LaTeX command preceding point."
  (interactive)
  (if
      (or (eq (preceding-char) ? )
	  (eq (preceding-char) ?\t)
	  (eq (preceding-char) ?\n)
	  (bobp))
      (message "Nothing to complete.")   ;Do not complete
    (let* ((end (point))
	   (limit (point-beginning-of-line))
	   (completion-begin 
	    (progn (re-search-backward "[ \t\n]" limit 1) (point)))
	   (begin (progn
		    (goto-char end)
		    (if (re-search-backward YaTeX-completion-begin-regexp
					    completion-begin t)
			(1+ (point))
		      nil))))
      (goto-char end)
      (cond
       ((null begin)
	(message "I think it is not a LaTeX sequence."))
       (t
	(mapcar 'YaTeX-sync-local-table
		'(tmp-section-table tmp-env-table tmp-singlecmd-table))
	(let*((pattern (YaTeX-buffer-substring begin end))
	      (all-table
	       (append
		section-table user-section-table tmp-section-table
		env-table     user-env-table     tmp-env-table
		singlecmd-table user-singlecmd-table tmp-singlecmd-table))
	      ;; First,
	      ;; search completion without backslash.
	      (completion (try-completion pattern all-table)))
	  (if
	      (eq completion nil)
	      ;; Next,
	      ;; search completion with backslash
	      (setq completion
		    (try-completion
		     (YaTeX-buffer-substring (1- begin) end)
		     all-table nil)
		    begin (1- begin)))
	  (cond
	   ((null completion)
	    (message (concat "Can't find completion for '" pattern "'"))
	    (ding))
	   ((eq completion t) (message "Sole completion."))
	   ((not (string= completion pattern))
	    (delete-region begin end)
	    (insert completion)
	    )
	   (t
	    (message "Making completion list...")
	    (with-output-to-temp-buffer "*Help*"
	      (display-completion-list
	       (all-completions pattern all-table)))))))))))

(defun YaTeX-toggle-modify-mode (&optional arg)
  (interactive "P")
  (or (memq 'YaTeX-modify-mode mode-line-format)
      (setq mode-line-format
	    (append (list "" 'YaTeX-modify-mode) mode-line-format)))
  (if (or arg (null YaTeX-modify-mode))
      (progn
	(setq YaTeX-modify-mode "*m*")
	(message "Modify mode"))
    (setq YaTeX-modify-mode nil)
    (message "Cancel modify mode."))
  (set-buffer-modified-p (buffer-modified-p)))	;redraw mode-line

(defun YaTeX-switch-mode-menu (arg &optional char)
  (interactive "P")
  (message "Toggle: (M)odify-mode ma(T)h-mode")
  (let ((c (or char (read-char))))
    (cond
     ((= c ?m) (YaTeX-toggle-modify-mode arg))
     ((or (= c ?$) (= c ?t))
      (if YaTeX-auto-math-mode
	  (message "Makes no sense in YaTeX-auto-math-mode.")
	(YaTeX-toggle-math-mode arg))))))

(defun YaTeX-insert-quote ()
  (interactive)
  (insert
   (cond
    ((YaTeX-literal-p) ?\")
    ((= (preceding-char) ?\\ ) ?\")
    ;((= (preceding-char) ?\( ) ?\")
    ((save-excursion (beginning-of-line)
		     (skip-chars-forward "\t ")
		     (looking-at "%#"))
     ?\")
    ((let ((ovl (overlays-at (point))))
       (and ovl
	    (catch 'found
	      (while ovl
		(if (overlay-get (car ovl) 'filter-input) (throw 'found t))
		(setq ovl (cdr ovl))))))
     ?\")
    ((or (= (preceding-char) 32)
	 (= (preceding-char) 9)
	 (= (preceding-char) ?\n)
	 (bobp)
	 (string-match
	  (regexp-quote (char-to-string (preceding-char)))
	  "ABCDHIuvwxyz()"))
     "``")
    (t  "''"))))

(defun YaTeX-closable-p ()
  (and (not YaTeX-modify-mode)
       (not (eq YaTeX-close-paren-always 'never))
       (or YaTeX-close-paren-always (eolp))
       (not (input-pending-p))
       (not (YaTeX-literal-p)))
  ;;(or YaTeX-modify-mode
  ;;    (and (not YaTeX-close-paren-always) (not (eolp)))
  ;;    (input-pending-p)
  ;;    (YaTeX-quick-in-environment-p "verbatim"))
  )

(defun YaTeX-insert-braces-region (beg end &optional open close)
  (interactive "r")
  (save-excursion
    (goto-char end)
    (YaTeX-insert-inherit (or close "}"))
    (goto-char beg)
    (YaTeX-insert-inherit (or open "{"))))

(defun YaTeX-get-macro-at-point (&optional p)
  "Get (La)TeX macro around point P."
  (interactive "d")
  (save-excursion
    (goto-char (setq p (or p (point))))
    (let ((token (substring (substring YaTeX-TeX-token-regexp 1) 0 -2))
	  bsend)
      (and (not (bobp))
	   (or (looking-at YaTeX-TeX-token-regexp)
	       (string-match
		YaTeX-TeX-token-regexp (char-to-string (preceding-char))))
	   (progn
	     (skip-chars-backward token)
	     (equal (preceding-char) ?\\))
	   (save-excursion
	     (setq bsend (point))
	     (skip-chars-backward "\\\\") ;emacs18 doesn't return distance
	     (/= (% (- bsend (point)) 2) 0)) ;consider \\
	   (looking-at YaTeX-TeX-token-regexp)
	   (YaTeX-match-string 0)))))

(defun YaTeX-insert-braces (arg &optional open close)
  (interactive "p")
  (let ((begend-guide
	 (function
	  (lambda ()
	    (if (equal (get 'YaTeX-insert-braces 'begend-guide) 2)
		nil			;if triggered thrice, do nothing
	      (momentary-string-display
	       (format
		(cond
		 (YaTeX-japan "begin/end͂ɂ %s g܂傤")
		 (t "You don't understand Zen of `%s'!"))
		(key-description
		 (car (where-is-internal 'YaTeX-make-begin-end))))
	       (point))
	      (put 'YaTeX-insert-braces 'begend-guide
		   (+ 1 (YaTeX-str2int ;increment counter of beg-end guidance
			 (prin1-to-string
			  (get 'YaTeX-insert-braces 'begend-guide)))))))))
	env macro not-literal b e)
    (cond
     ((YaTeX-region-active-p)
      (YaTeX-insert-braces-region (region-beginning) (region-end)))
     ((YaTeX-jmode) (YaTeX-self-insert arg))
     ((not (YaTeX-closable-p)) (YaTeX-self-insert arg))
     ((save-excursion
	(and (> (- (point) (point-min)) 6)
	     (condition-case () (forward-char -6) (error nil)))
	(looking-at "\\\\left\\\\"))
      (insert "{\\right\\}")
      (forward-char -8))
     ((save-excursion			;from matsu<at>math.s.chiba-u.ac.jp
	(and (> (- (point) (point-min)) 6) (forward-char -6))
	(looking-at "\\\\[bB]igl\\\\"))
      (insert
       (concat
	"{" (buffer-substring (match-beginning 0) (- (match-end 0) 2)) "r\\}"))
      (forward-char -7))
     ((save-excursion
	(and (> (- (point) (point-min)) 7)
	     (condition-case () (forward-char -7) (error nil)))
	(looking-at "\\\\[bB]iggl\\\\"))
      (insert
       (concat
	"{" (buffer-substring (match-beginning 0) (- (match-end 0) 2)) "r\\}"))
      (forward-char -8))
     ((= (preceding-char) ?\\ )
      (insert "{\\}")
      (forward-char -2))		;matsu's hack ends here
     ((and (setq not-literal (not (YaTeX-literal-p)))
	   (equal "end" (setq macro (YaTeX-get-macro-at-point)))
	   (setq env (YaTeX-inner-environment)))
      (funcall begend-guide)
      (insert "{" env "}"))
     ((and not-literal (equal "begin" macro))
      (insert "{")
      (save-excursion
	(indent-to (prog1 (- (current-column) 7) (insert "}\n")))
	(insert "\\end{}")
	(setq e (point)))
      (setq env
	    (YaTeX-read-environment
	     (format "Begin environment(default %s): " YaTeX-env-name)))
      (if (string= "" env) (setq env YaTeX-env-name))
      (setq YaTeX-env-name env)
      (funcall begend-guide)
      (delete-region (- (point) 7) e)
      (YaTeX-insert-begin-end env nil))
     (t
      (insert (or open "{") (or close "}"))
      (forward-char -1)
      (if (and (eq (char-after (point)) ?\}) ;; the case `\\{}'
	       (eq (char-after (- (point) 2)) ?\\ ))
	  (progn (insert "\\") (forward-char -1)))
      ))))

(defun YaTeX-jmode ()
  (or (and (boundp 'canna:*japanese-mode*) canna:*japanese-mode*)
      (and (boundp 'egg:*mode-on*) egg:*mode-on* egg:*input-mode*)
      (and (boundp 'skk-mode) skk-mode (not skk-latin-mode))
      (and (boundp 'default-input-method) default-input-method
	   current-input-method)))

(defun YaTeX-jmode-off ()
  (if (cond
       ((and (boundp 'canna:*japanese-mode*) canna:*japanese-mode*)
	(canna-toggle-japanese-mode) t)
       ((and (boundp 'egg:*mode-on*) egg:*mode-on* egg:*input-mode*)
	(egg:toggle-egg-mode-on-off) t)
       ((and (fboundp 'skk-mode) (boundp 'skk-mode) skk-mode)
	(cond
	 ((fboundp 'skk-latin-mode)
	  (or (and (boundp 'skk-henkan-mode) skk-henkan-mode)
	      (and (boundp 'skk-henkan-on)
		   (or skk-henkan-mode skk-henkan-active))
	      (and (boundp 'j-henkan-on)
		   (or j-henkan-on j-henkan-active))
	      ;; Deactivate jmode if henkan-mode is not running.
	      ;; Suggested by tt.tetsuo.tsukamoto.
	      (progn
		(put 'YaTeX-jmode-on 'skkkata skk-katakana)
		(skk-latin-mode t))))
	 ((fboundp 'skk-mode-off)	(skk-mode-off))
	 (t (j-mode-off)))
	t)
       ((and (fboundp 'toggle-input-method) current-input-method)
	(toggle-input-method) t)
       ((and (fboundp 'fep-force-off) (fep-force-off))))
      (put 'YaTeX-jmode 'jmode t)))

(defun YaTeX-jmode-on ()
  (cond
   ((boundp 'canna:*japanese-mode*)
    (if (not canna:*japanese-mode*) (canna-toggle-japanese-mode)))
   ((boundp 'egg:*mode-on*)
    (and (not egg:*mode-on*) (not egg:*input-mode*)
	 (egg:toggle-egg-mode-on-off)))
   ((and (fboundp 'skk-mode) (boundp 'skk-mode))
    (if (get 'YaTeX-jmode-on 'skkkata)
	(skk-j-mode-on t)
      (skk-mode 1))
    (put 'YaTeX-jmode-on 'skkkata nil))
   ((fboundp 'toggle-input-method)
    (if (not current-input-method) (toggle-input-method)))
   ((and (fboundp 'fep-force-on) (fep-force-on)))))

(defun YaTeX-jmode-back ()
  (if (get 'YaTeX-jmode 'jmode)
      (YaTeX-jmode-on))
  (setplist 'YaTeX-jmode nil))

(defun YaTeX-self-insert (arg)
  (call-interactively (global-key-binding (char-to-string (YaTeX-last-key)))))
(defun YaTeX-insert-inherit (&rest args)
  (apply (if (fboundp 'insert-and-inherit) 'insert-and-inherit 'insert)
	   args))

(defun YaTeX-insert-brackets (arg)
  "Insert Kagi-kakko or \\ [ \\] pair or simply \[."
  (interactive "p")
  (let ((col (1- (current-column))))
    (cond
     ((YaTeX-region-active-p)
      (YaTeX-insert-brackets-region (region-beginning) (region-end)))
     ((YaTeX-jmode) (YaTeX-self-insert arg))
     ((not (YaTeX-closable-p))
      (YaTeX-self-insert arg))
     ((save-excursion
	(and (> (- (point) (point-min)) 5) (forward-char -5))
	(looking-at "\\\\left"))
      (YaTeX-insert-inherit "[\\right]")
      (forward-char -7))
     ((save-excursion			;from matsu<at>math.s.chiba-u.ac.jp
	(and (> (- (point) (point-min)) 5) (forward-char -5))
	(looking-at "\\\\[bB]igl"))
      (YaTeX-insert-inherit
       (concat
	"[" (buffer-substring (match-beginning 0) (- (match-end 0) 1)) "r]"))
      (forward-char -6))
     ((save-excursion
	(and (> (- (point) (point-min)) 6) (forward-char -6))
	(looking-at "\\\\[bB]iggl"))
      (YaTeX-insert-inherit
       (concat
	"[" (buffer-substring (match-beginning 0) (- (match-end 0) 1)) "r]"))
      (forward-char -7))		;matsu's hack ends here
     ((and (= (preceding-char) ?\\ )
	   (/= (char-after (- (point) 2)) ?\\ )
	   (not (YaTeX-in-math-mode-p)))
      (YaTeX-insert-inherit (YaTeX-last-key) "\n")
      (indent-to (max 0 col))
      (YaTeX-insert-inherit "\\]")
      (beginning-of-line)
      (open-line 1)
      (delete-region (point) (progn (beginning-of-line) (point)))
      (indent-to (+ YaTeX-environment-indent (max 0 col)))
      (or YaTeX-auto-math-mode YaTeX-math-mode (YaTeX-toggle-math-mode 1)))
     ((YaTeX-closable-p)
      (YaTeX-insert-inherit "[]")
      (backward-char 1))
     (t (YaTeX-self-insert arg)))))

(defun YaTeX-insert-brackets-region (beg end)
  (interactive "r")
  (YaTeX-insert-braces-region beg end "[" "]"))

(defun YaTeX-insert-parens (arg)
  "Insert parenthesis pair."
  (interactive "p")
  (cond
   ((YaTeX-region-active-p)
    (YaTeX-insert-parens-region (region-beginning) (region-end)))
   ((YaTeX-jmode) (YaTeX-self-insert arg))
   ((not (YaTeX-closable-p)) (YaTeX-self-insert arg))
   ((save-excursion
      (and (> (- (point) (point-min)) 5) (forward-char -5))
      (looking-at "\\\\left"))
    (YaTeX-insert-inherit "(\\right)")
    (forward-char -7))
   ((save-excursion			;from matsu<at>math.s.chiba-u.ac.jp
      (and (> (- (point) (point-min)) 5) (forward-char -5))
      (looking-at "\\\\[bB]igl"))
    (YaTeX-insert-inherit
     (concat
      "(" (buffer-substring (match-beginning 0) (- (match-end 0) 1)) "r)"))
     (forward-char -6))
   ((save-excursion
      (and (> (- (point) (point-min)) 6) (forward-char -6))
      (looking-at "\\\\[bB]iggl"))
    (YaTeX-insert-inherit
     (concat
      "(" (buffer-substring (match-beginning 0) (- (match-end 0) 1)) "r)"))
     (forward-char -7))
   ((= (preceding-char) ?\\ )		;matsu's hack ends here
    (YaTeX-insert-inherit "(\\)")
    (backward-char 2))
   ((YaTeX-closable-p)
    (YaTeX-insert-inherit "()")
    (backward-char 1))
   (t (YaTeX-self-insert arg))))

(defun YaTeX-insert-parens-region (beg end)
  (interactive "r")
  (YaTeX-insert-braces-region beg end "(" ")"))

(defun YaTeX-insert-bar (arg)
  "Insert bar pair."
  (interactive "p")
  (cond
   ((YaTeX-jmode) (YaTeX-self-insert arg))
   ((not (YaTeX-closable-p)) (YaTeX-self-insert arg))
   ((save-excursion
      (and (> (- (point) (point-min)) 5) (forward-char -5))
      (looking-at "\\\\left"))
    (YaTeX-insert-inherit "|\\right|")
    (forward-char -7))
   ((save-excursion			;from matsu<at>math.s.chiba-u.ac.jp
      (and (> (- (point) (point-min)) 5) (forward-char -5))
      (looking-at "\\\\[bB]igl"))
    (insert
     (concat
      "|" (buffer-substring (match-beginning 0) (- (match-end 0) 1)) "r|"))
     (forward-char -6))
   ((save-excursion
      (and (> (- (point) (point-min)) 6) (forward-char -6))
      (looking-at "\\\\[bB]iggl"))
    (insert
     (concat
      "|" (buffer-substring (match-beginning 0) (- (match-end 0) 1)) "r|"))
     (forward-char -7))
   ((save-excursion		; added by Jin <MAF01011<at>nifty.ne.jp>
      (and (> (- (point) (point-min)) 6) (forward-char -6))
      (looking-at "\\\\left\\\\"))
    (YaTeX-insert-inherit "|\\right\\|")
    (forward-char -8))
   ((save-excursion
      (and (> (- (point) (point-min)) 6) (forward-char -6))
      (looking-at "\\\\[bB]igl\\\\"))
    (insert
     (concat
      "|" (buffer-substring (match-beginning 0) (- (match-end 0) 2)) "r\\|"))
     (forward-char -7))
   ((save-excursion
      (and (> (- (point) (point-min)) 7) (forward-char -7))
      (looking-at "\\\\[bB]iggl\\\\"))
    (insert
     (concat
      "|" (buffer-substring (match-beginning 0) (- (match-end 0) 2)) "r\\|"))
     (forward-char -8))		; added by Jin up to here.
   ((= (preceding-char) ?\\ )
    (YaTeX-insert-inherit "|\\|")
    (backward-char 2))
;   ((and (YaTeX-closable-p)
;	 (/= (preceding-char) ?|)
;	 (/= (following-char) ?|))
;    (YaTeX-insert-inherit "||")
;    (backward-char 1))
   (t (YaTeX-self-insert arg))))

(defvar YaTeX-use-jmode-hook
  (and (featurep 'canna) (boundp 'canna:*initialized*) canna:*initialized*)
  ;; (not (and (fboundp 'skk-mode) (boundp 'skk-mode)))
  "*Non-nil means activate automatic jmode switcher within/out math mode.
Hopefully, change default to t in the next version of 1.75.")
(defun YaTeX-jmode-hook (old new)
  "A hook controling jmode on/off."
  ;; This function is called via point-entered/leave hook, so that
  ;; codes in it is evaluated on such emacsen as having text-properties.
  (let ((inhibit-point-motion-hooks t)
	(oldp (plist-get (text-properties-at old) 'point-left))
	(newp (plist-get (text-properties-at new) 'point-left))
	(lnew (plist-get (text-properties-at new) 'last-new))
	(mjmode (plist-get (text-properties-at new) 'mjmode))
	(bmp (buffer-modified-p))
	(jm (YaTeX-jmode)) b e)
    (unwind-protect
	(cond
	 ((eq lnew new) nil)		;Do nothing if continuous entry
	 ((and (not (eq newp 'YaTeX-jmode-hook))
	       (eq oldp 'YaTeX-jmode-hook)
	       (plist-get (text-properties-at old) 'entered))
	  ;; leave
	  (remove-text-properties
	   (setq b (1+ (or (previous-single-property-change old 'point-left)
			   (1- (point)))))
	   (setq e (1- (or (next-single-property-change old 'point-left)
			   (1+ (point)))))
	   (list 'last-new nil 'entered nil))
	  (add-text-properties b e (list 'mjmode jm))
	  (if (boundp 'skk-katakana)
	      (put 'YaTeX-jmode-on 'skkkata skk-katakana))
	  (if (plist-get (text-properties-at old) 'jmode)
	      (YaTeX-jmode-on)))
	 ((and (not (eq oldp 'YaTeX-jmode-hook))
	       (eq newp 'YaTeX-jmode-hook)
	       (not (plist-get (text-properties-at new) 'entered)))
	  ;; enter
	  (add-text-properties
	   (1+ (or (previous-single-property-change new 'point-left)
		   (1- (point))))
	   (1- (or (next-single-property-change new 'point-left)
		   (1+ (point))))
	   (list 'jmode jm 'last-new new 'entered t))
	  (if (boundp 'skk-katakana)	;care for skk katakana mode
	      (put 'YaTeX-jmode-on 'skkkata skk-katakana))
	  (if mjmode (YaTeX-jmode-on) (YaTeX-jmode-off))))
      ;;unwind job
      (set-buffer-modified-p bmp))))

(defun YaTeX-insert-dollar ()
  (interactive)
  (if (or (not (YaTeX-closable-p))
	  (= (preceding-char) 92)
	  (and (YaTeX-in-math-mode-p)
	       (or (/= (preceding-char) ?$) (/= (following-char) ?$))))
      (insert "$")
    (insert "$$")
    (forward-char -1)
    (and YaTeX-use-jmode-hook
	 (fboundp 'add-text-properties)
	 (add-text-properties
	  (1- (point)) (1+ (point))
	  (list 'point-left 'YaTeX-jmode-hook
		'point-entered 'YaTeX-jmode-hook
		'front-sticky t
		'rear-nonsticky t
		'mjmode nil
		'jmode (YaTeX-jmode))))
    (YaTeX-jmode-off)
    (or YaTeX-auto-math-mode YaTeX-math-mode (YaTeX-toggle-math-mode 1))))

(defun YaTeX-insert-dollars-region (beg end)
  (interactive "r")
  (YaTeX-insert-braces-region beg end "$" "$"))

(defun YaTeX-insert-amper ()
  (interactive)
  (if (or (string-match YaTeX-array-env-regexp
			(or (YaTeX-inner-environment t) "document"))
	  (= (preceding-char) 92)
	  (YaTeX-literal-p)
	  (YaTeX-in-math-mode-p))
      (insert "&")
    (insert "\\&")))

(defun YaTeX-version ()
  "Return string of the version of running YaTeX."
  (interactive)
  (message
   (concat "Yet Another tex-mode "
	   (if YaTeX-japan "u쒹v" "`Wild Bird'")
	   " Revision "
	   YaTeX-revision-number)))

(defun YaTeX-typeset-menu (arg &optional char)
  "Typeset, preview, visit error and miscellaneous convenient menu.
Optional second argument CHAR is for non-interactive call from menu."
  (interactive "P")
  (message
   (concat "J)latex R)egion E)nv B)ibtex mk(I)dx "
	   "latex+p(D)f "
	   (if (fboundp 'start-process) "K)ill ")
	   "P)review "
	   (and (boundp 'window-system) window-system "S)earch ")
	   "V)iewErr L)pr"))
  (let ((sw (selected-window)) (c (or char (read-char))))
    (require 'yatexprc)			;for Nemacs's bug
    (select-window sw)
    (cond
     ((memq c '(?j ?\C-j)) (YaTeX-typeset-buffer) ; memq for usability test
      (put 'dvi2-command 'format 'dvi))
     ((= c ?r) (YaTeX-typeset-region))
     ((= c ?e) (YaTeX-typeset-environment))
     ((= c ?b) (YaTeX-call-builtin-on-file
		"BIBTEX" bibtex-command arg))
     ((= c ?i) (YaTeX-call-builtin-on-file
		"MAKEINDEX" makeindex-command arg))
     ((= c ?k) (YaTeX-kill-typeset-process YaTeX-typeset-process))
     ((= c ?p) (call-interactively 'YaTeX-preview))
     ((= c ?q) (YaTeX-system "lpq" "Printer queue"))
     ((= c ?d) (YaTeX-typeset-buffer
		(or (YaTeX-get-builtin "DVIPDF") YaTeX-dvipdf-command))
      (put 'dvi2-command 'format 'pdf))
     ((= c ?v) (YaTeX-view-error))
     ((= c ?l) (YaTeX-lpr arg))
     ((= c ?m) (YaTeX-switch-mode-menu arg))
     ((= c ?s) (YaTeX-xdvi-remote-search arg)))))

(if (fboundp 'wrap-function-to-control-ime)
    (wrap-function-to-control-ime 'YaTeX-typeset-menu t "P"))


(defun YaTeX-%-menu (&optional beg end char)
  "Operate %# notation."
  ;;Do not use interactive"r" for the functions which require no mark
  (interactive)
  (message "!)Edit-%%#! D)VIPDF B)EGIN-END P)review pdf(V)iew L)PR M)akeidx b)ibtex dp(I)")
  (let ((c (or char (read-char))) (string "") key
	(b (make-marker)) (e (make-marker)))
    (save-excursion
      (cond
       ((rindex "!plmibdv" c)		;Edit %#xxx
	(setq key (cdr (assq c '((?! . "!")
				 (?p . "PREVIEW")
				 (?l . "LPR")
				 (?m . "MAKEINDEX")
				 (?d . "DVIPDF")
				 (?v . "PDFVIEW")
				 (?i . "IMAGEDPI")
				 (?b . "BIBTEX")))))
	(YaTeX-getset-builtin key t))

       ((= c ?B)			;%#BEGIN %#END region
	(or end (setq beg (min (point) (mark)) end (max (point) (mark))))
	(set-marker b beg)
	(set-marker e end)
	(goto-char (point-min))
	(while (re-search-forward "^%#\\(BEGIN\\)\\|\\(END\\)$" nil t)
	  (beginning-of-line)
	  (delete-region (point) (progn (forward-line 1) (point))))
	(goto-char b)
	(open-line 1)
	(delete-region (point) (progn (beginning-of-line)(point)));for 19 :-<
	(insert "%#BEGIN")
	(goto-char e)
	(insert "%#END\n")
	(set-marker b nil)
	(set-marker e nil))))))

(defvar YaTeX-refcommand-def-regexp-default
  "label\\|bibitem")
(defvar YaTeX-refcommand-def-regexp-private nil
  "*Regexp of defining label commands")
(defvar YaTeX-refcommand-def-regexp
  (concat (if YaTeX-refcommand-def-regexp-private
	      (concat YaTeX-refcommand-def-regexp-private "\\|"))
	  YaTeX-refcommand-def-regexp-default))

(defvar YaTeX-refcommand-ref-regexp-default
  "\\(page\\|eq\\|fig\\)?ref\\|cite"
  "Regexp of LaTeX's label-referring macros.
Searching for this will be done without `\\\\'.
So you need not add patterns if new referring macro ends with \"ref\".")
(defvar YaTeX-refcommand-ref-regexp-private nil
  "*Regexp of referring label commands.
See documentation of `YaTeX-refcommand-ref-regexp-default'.")
(defvar YaTeX-refcommand-ref-regexp
  (concat (if YaTeX-refcommand-ref-regexp-private
	      (concat YaTeX-refcommand-ref-regexp-private "\\|"))
	  YaTeX-refcommand-ref-regexp-default))

(defvar YaTeX-refcommand-regexp
  (concat YaTeX-refcommand-def-regexp
	  "\\|" YaTeX-refcommand-ref-regexp)
  "Regexp of label defining/referring command name.")

(defun YaTeX-goto-corresponding-label (reverse &optional otherwin)
  "Jump to corresponding \\label{} and \\ref{} or \\cite and \\bibitem.
  The default search direction depends on the command at the cursor position.
When the cursor is on \\ref(\\cite), YaTeX will try to search the
corresponding \\label(\\bibitem) backward,
and if it fails search forward again.  And when the cursor is
on \\label(\\bibitem), YaTeX will search the corresponding \\ref(\\cite)
forward at first and secondary backward.
  Argument REVERSE non-nil makes the default
direction rule reverse.  Since Search string is automatically set in
search-last-string, you can repeat search the same label/ref by typing
\\[isearch-forward] or \\[isearch-backward].
  If optional second argument OTHERWIN is non-nil, move to other window."

  (let ((scmd "") label direc string blist (p (point)) (cb (current-buffer))
	(refcommands YaTeX-refcommand-regexp)
	(foundmsg (format "Type %s %c to return to original position."
			  (key-description
			   (car
			    (or (where-is-internal 'register-to-point)
				(where-is-internal 'jump-to-register))))
			  YaTeX-current-position-register))
	(func (function (lambda (string sfunc)
			  (or
			   (funcall sfunc string nil t)
			   (funcall (if (eq sfunc 're-search-forward)
					're-search-backward 're-search-forward)
				    string nil t))))))
    (cond
     ((YaTeX-on-section-command-p refcommands)
      (setq scmd
	    (cdr
	     (assoc
	      (YaTeX-match-string 1)
	      '(("label" . "\\\\\\(page\\|eq\\)?ref{%k}")
		("ref" . "\\\\label{%k}")
		("eqref" . "\\\\label{%k}")
		("pageref" . "\\\\label{%k}")
		("cite" .
		 "\\\\bibitem\\(\\[[^]]+\\]\\)?{%k}\\|^\\s *@[a-z]+{%k,")
		("bibitem" . "\\\\cite\\(\\[[^]]+\\]\\)?")))))
      (goto-char (match-end 0))
      (let ((label (YaTeX-buffer-substring 
		    (1- (point)) (progn (backward-list 1) (1+ (point)))))
	    (fp (make-marker))fl fn
	    (goother (function (lambda (buffer point)
				 (goto-char point)
				 (if (one-window-p)
				     (split-window-calculate-height
				      YaTeX-default-pop-window-height))
				 (select-window (get-lru-window))
				 (switch-to-buffer buffer)))))
	;(setq string (concat "\\" scmd "{" label "}"))
	;(setq string (concat "\\\\" scmd "{" (regexp-quote label) "}"))
	(setq string (YaTeX-replace-format scmd "k" (regexp-quote label)))
	(setq direc (if (string-match "ref\\|cite" scmd)
			're-search-forward 're-search-backward))
	(if YaTeX-current-position-register
	    (point-to-register YaTeX-current-position-register))
	(if reverse (setq direc (if (eq direc 're-search-forward)
				    're-search-backward 're-search-forward)))
	(if (funcall func string direc)	;label/ref found!
	    (progn
	      (if otherwin (funcall goother cb p))
	      (goto-char (match-beginning 0))
	      (push-mark p))
	  ;;if label/ref not found, search through all yatex buffers.
	  (goto-char p)			;resume position of current buffer
	  (catch 'found
	    (setq blist (YaTeX-yatex-buffer-list))
	    (while blist
	      ;; search for corresponding keyword
	      (set-buffer (car blist))
	      (if (YaTeX-on-section-command-p refcommands)
		  (goto-char (match-beginning 0)))
	      (cond
	       ; cond1
	       ((funcall func string direc)
		(cond
		 (otherwin
		  (set-buffer cb)
		  (funcall goother (car blist) p))
		 ((or (get-buffer-window (car blist))
		      (and YaTeX-emacs-19
			   (get-buffer-window (car blist) t)))
		  (goto-buffer-window (car blist)))
		 (t
		  (switch-to-buffer (car blist))
		  (message foundmsg)))
		(goto-char (match-beginning 0))
		(throw 'found t))
	       ; cond2
	       ((and
		 (string-match "bibitem" scmd)
		 (catch 'found2
		   (save-excursion
		     (goto-char (point-min))
		     (while (YaTeX-re-search-active-forward
			     "\\\\bibliography{\\([^}]*\\)}" "%" nil t)
		       (setq fl (YaTeX-split-string (YaTeX-match-string 1) ","))
		       (while fl
			 (if (or (file-exists-p (setq fn (car fl)))
				 (file-exists-p (setq fn (concat fn ".bib"))))
			     (progn
			       (set-buffer (find-file-noselect fn))
			       (save-excursion
				 (goto-char (point-min))
				 (if (YaTeX-re-search-active-forward
				      string "%" nil t)
				     (throw 'found2
					    (set-marker fp (point)))))))
			 (setq fl (cdr fl)))))))
		(if otherwin
		    (funcall goother (marker-buffer fp) fp)
		  (switch-to-buffer (marker-buffer fp))
		  (goto-char fp))
		(set-marker fp nil)
		(message foundmsg)
		(throw 'found t)))
	      (setq blist (cdr blist)))
	    ;; search for bibliography
	    )))
      (if YaTeX-emacs-19
	  (setq regexp-search-ring
		(cons string (delete string regexp-search-ring)))
	(setq search-last-regexp string)))
     (t nil))))

;;YaTeX-goto-corresponding-environment was moved to yatexlib

(defun YaTeX-goto-corresponding-file (&optional other)
  "Visit or switch buffer of corresponding file,
looking at \\input or \\include or \\includeonly or %#SRC{} on current line."
  (cond
   ((YaTeX-on-includes-p)
    (let ((parent buffer-file-name) input-file b)
      (save-excursion
	(if (and (re-search-forward "[{%]" (point-end-of-line) t)
		 (= ?{ (char-after (match-beginning 0))))
	    nil
	  (skip-chars-backward "^,{"))
	(setq input-file
	      (YaTeX-buffer-substring
	       (point) (progn (skip-chars-forward "^ ,}") (point))))
	(if (not (string-match "\\.\\(tex\\|sty\\)$" input-file))
	    (setq input-file (concat input-file ".tex"))))
      (cond
       (other (YaTeX-switch-to-buffer-other-window input-file))
       ((setq b (YaTeX-get-file-buffer input-file))
	(goto-buffer-window b))
       (t (YaTeX-switch-to-buffer input-file)))
      (or (YaTeX-get-builtin "!")
	  YaTeX-parent-file
	  (setq YaTeX-parent-file parent))))
   ;; On %#SRC{somefilters.src}
   ((YaTeX-on-SRC-p)
    (let ((src (YaTeX-match-string 1)))
      (if other (YaTeX-switch-to-buffer-other-window src)
	(goto-buffer-window (find-file-noselect src)))))))

(defun YaTeX-goto-corresponding-BEGIN-END ()
  (if (not (YaTeX-on-BEGIN-END-p)) nil
    (if (cond
	 ((equal (match-beginning 0) (match-beginning 1)) ;if on %#BEGIN
	  (not (search-forward "%#END" nil t)))
	 (t ; if on %#END
	  (not (search-backward "%#BEGIN" nil t))))
	(error "Corresponding %%#BEGIN/END not found."))
    (beginning-of-line)
    t))

(defvar YaTeX-processed-file-regexp-alist nil
  "Alist of regexp of processed file regexp vs. its file name part;
For example, if you include image file with `\\epsfile{file=FILE}' where
`FILE' is processed file.  You might want to view FILE with other previewer
such as ghostview, or want to preview its source which was drawn with
other drawing tool, tgif for example.  Then you should set entire regexp
of including expression and enclose its file name part with \\\\( and \\\\).

 Ex. (\"\\\\\\\\epsfile{[^}]*file=\\\\([^,} ]+\\\\)\\\\(\\\\.e?ps\\\\)?[^}]*}\" 1)

Where the first group surrounded by \\\\( and \\\\) is the file name part
of expression.  So you should set 1 to second element.  And the first
matching group is sent to (image) processor defined by the variable
YaTeX-file-processor-alist. See also the documentation of
YaTeX-file-processor-alist.

ǂ킩ȂˁBႦ tgif hoge.obj  hoge.eps 
\\epsfile{file=hoge.eps} ŃCN[hĂƂ悤B̍s
\[prefix\] g  tgif Nė~A܂̂悤
K\ݒ肷B\\\\(\\\\)ň͂񂾂Ƃ낪t@CɂȂ悤
ӂBŃt@CԖڂ\\\\(\\\\)ɂȂ邩Xg2ԖڂɏB
ƁA̕ϐ YaTeX-file-processor-alist Œ`ꂽ
vOɓnBƂ킯B
`ςނˁBȂׂ͗ Lisper ɕA
fj쒹̉ŕ!
")

(defvar YaTeX-processed-file-regexp-alist-default
  '(("\\\\epsfile\\(\\[[^]]+\\]\\)?{[^},]*file=\\(\\([^,} ]*/\\)?[^,}. ]+\\)\\(\\.e?ps\\)?[^}]*}" 2)
    ("\\\\epsfig{[^},]*fi\\(le\\|gure\\)=\\(\\([^,} ]*/\\)?[^,}. ]+\\)\\(\\.e?ps\\)?[^}]*}" 2)
    ("\\\\postscriptbox{[^}]*}{[^}]*}{\\(\\([^,} ]*/\\)?[^}. ]+\\)\\(\\.e?ps\\)?}" 1)
    ("\\\\\\(epsfbox\\|epsfig\\)\\*?{\\(\\([^,} ]*/\\)?[^}. ]+\\)\\(\\.e?ps\\)?}" 2) ;\epsfbox{hoge.ps}
    ("\\\\includegraphics\\*?\\(.*\\]\\|\\s \\)?{\\(.*\\)\\(\\.ai\\|\\.pdf\\|\\.svg\\|\\.png\\|\\.jpe?g\\|\\.e?ps\\)}" 2) ;\includegraphics[options...]{hoge.eps}
    ("\\\\\\(psbox\\)\\(\\[[^]]+\\]\\)?{\\(\\([^,} ]*/\\)?[^} ]+\\)\\(\\.e?ps\\)}" 3) ;\psbox[options...]{hoge.eps} (97/1/11)
    ("\\\\input{\\([^} ]+\\)\\(\\.tps\\)}" 1) ;tgif2tex (1998/9/16)
    )
  "See the documentation of YaTeX-processed-file-regexp-alist.")

(defvar YaTeX-file-processor-alist nil
  "*Alist of files' processor vs. its extension;
See also the documentation of YaTeX-processed-file-regexp-alist.")

(defvar YaTeX-file-processor-alist-default
  (list (cons YaTeX-cmd-tgif ".obj")
	(cons YaTeX-cmd-gimp ".xcf")
	(cons YaTeX-cmd-gimp ".xcf.gz")
	(cons YaTeX-cmd-gimp ".xcf.bz2")
	(cons YaTeX-cmd-edit-svg ".svg")
	(cons YaTeX-cmd-edit-svg ".svgz")
	(cons YaTeX-cmd-edit-ai ".ai")
	'("dia" . ".dia")
	(cons YaTeX-cmd-ooo ".odg")
	(cons 'YaTeX-filter-goto-source ".diag")
	(cons 'YaTeX-filter-goto-source ".dot")
	;; List of target file itself below...
	(cons YaTeX-cmd-edit-images ".jpeg")
	(cons YaTeX-cmd-edit-images ".jpg")
	(cons YaTeX-cmd-edit-images ".png")
	(cons YaTeX-cmd-edit-ps ".ps")
	(cons YaTeX-cmd-edit-ps ".eps")
	(cons YaTeX-cmd-edit-pdf ".pdf")
	'(t . ".tex")
	'(t . ".sty")
	'(t . ""))
  "See the documentation of YaTeX-file-processor-alist.")

(defun YaTeX-goto-corresponding-file-processor (&optional other)
  "Execute corresponding file processor."
  (save-excursion
    (or (looking-at YaTeX-ec-regexp)
	(skip-chars-backward (concat "^" YaTeX-ec) (point-beginning-of-line)))
    (let ((list (append YaTeX-processed-file-regexp-alist
			YaTeX-processed-file-regexp-alist-default))
	  (p (point)) flist file
	  (peol (point-end-of-line))
	  (basedir
	   (if YaTeX-search-file-from-top-directory
	       (save-excursion (YaTeX-visit-main t) default-directory)
	     ".")))
      (setq flist (catch 'found
		    (while list
		      (goto-char p)
		      (if (re-search-forward (car (car list)) peol t)
			  (progn
			    (setq file (YaTeX-match-string
					(car (cdr (car list)))))
			    (throw 'found (cdr (car list)))))
		      (setq list (cdr list)))))
      (if flist				;if pattern and file name found
	  (let*((plist (append YaTeX-file-processor-alist
			       YaTeX-file-processor-alist-default))
		(plist0 plist)
		ext cmd src buf (alt (car (cdr flist))))
	    (if (and (re-search-forward
		      (concat YaTeX-comment-prefix "\\s *\\(.*\\)$") peol t)
		     (assoc (setq cmd (YaTeX-match-string 1))
			    YaTeX-file-processor-alist))
		(setq src		;if processor is specified
		      (concat file
			      (cdr (assoc cmd YaTeX-file-processor-alist))))
	      (while plist		;if processor is not specified
		(setq ext (cdr (car plist)))
		(if (and (string< "" (concat file ext))
			 (file-exists-p
			  (expand-file-name (concat file ext) basedir)))
		    (setq cmd (car (car plist))
			  src (concat file ext) plist nil))
		(setq plist (cdr plist)))
	      (if (and (null src) alt YaTeX-create-file-prefix-g)
		  (setq cmd alt
			src (concat file (cdr (assoc alt plist0))))))
	    (if src			;if processor and src file found
		(let ((default-directory basedir))
		  (cond
		   ((stringp cmd)
		    (YaTeX-system (concat cmd " " src) cmd)
		    t)
		   ((eq t cmd)
		    (let ((parent buffer-file-name))
		      (funcall
		       (cond
			(other 'YaTeX-switch-to-buffer-other-window)
			((get-file-buffer src) 'goto-buffer-window)
			(t 'YaTeX-switch-to-buffer))
		       src)
		      (or (YaTeX-get-builtin "!")
			  YaTeX-parent-file
			  (setq YaTeX-parent-file parent))
		      t))
		   ((symbolp cmd)
		    (cond
		     ((symbol-function cmd)
		      (funcall cmd src other)))
		    t)))))))))

(defun YaTeX-on-section-command-p (command)
  "Check if point is on the LaTeX command: COMMAND(regexp).
Return nil if point is not on it.  Otherwise return the
number of argument position.
Section command name is stored in match-data #1.
Parsing information is stored to plist.
Macros name stored to propname 'command.
Macro's argument number stored to propname 'argc."
  (let ((p (point)) md (parg 0) (argc 1) word (grouping 0) (i 0)
	(ec+command (concat YaTeX-ec-regexp "\\(" command "\\)")))
    (setplist 'YaTeX-on-section-command-p nil)
    (while (setq i (string-match "\\\\(" command i))
      (setq grouping (1+ grouping) i (+ i 2)))
    (save-excursion
      (if (looking-at ec+command) nil
	(catch 'found			;caught value has no meaning
	  ;;(1) looking at current position
	  (and (looking-at command)
	       (save-excursion
		 (while (and (not (bobp)) (looking-at command))
		   (forward-char -1))
		 (looking-at ec+command))
	       (goto-char (match-beginning 0))
	       (throw 'found t))
	  ;;If inside of parentheses, try to escape.
	  (unwind-protect
	      (progn
		(set-syntax-table YaTeX-mode-syntax-table-nonparen)
		(while (and (not (= (preceding-char) ?\])) ;skip optional arg
			    (condition-case err
				(progn (up-list -1) t)
			      (error nil)))))
	    (set-syntax-table YaTeX-mode-syntax-table))
	  (while (equal (preceding-char) ?\]) (backward-list))
	  ;;(2) search command directly
	  (skip-chars-forward "^{}[]")
	  (and (YaTeX-re-search-active-backward
		ec+command
		YaTeX-comment-prefix nil t)
	       (>= p (match-beginning 0))
	       (throw 'found (goto-char (match-beginning 0))))
	  ;;(3) search token
	  (goto-char p)
	  (while t
	    (if (bobp) (throw 'found nil))
	    (cond
	     ((looking-at YaTeX-ec-regexp) (throw 'found t))
	     ((looking-at "[[{]") nil)
	     ((looking-at "[]}]")(condition-case nil (up-list -1) (error nil)))
	     (t (skip-chars-backward " \t\r\n")))
	    (skip-chars-backward (concat "^ \t\r\n{}[]" YaTeX-ec-regexp))
	    (or (bobp) (forward-char -1)))))
      (if (and
	   (looking-at (concat ec+command
			       "\\(\\(\\[[^]]+\\]\\|([0-9,]+)\\)*\\)"	;optional arg
			       ;"[ \t\n\r]*{[^}]+}")) ;arg braces
			       "[ \t\n\r]*{[^}]*}")) ;arg braces
	   (not (YaTeX-lookup-table
		 (setq word (YaTeX-match-string 1)) 'singlecmd)))
	  (progn
	    (setq md (match-data))
	    (skip-chars-forward "^{")
	    (if (<= (point) p) (setq parg (1+ parg)))
	    (setq argc
		  (or (car (cdr (YaTeX-lookup-table word 'section)))
		      argc))
	    (put 'YaTeX-on-section-command-p 'argc argc)
	    (put 'YaTeX-on-section-command-p 'command argc)
	    (while (and (>= (setq argc (1- argc)) 0)
			(progn (skip-chars-forward " \t\n\r")
			       (looking-at "{")))
	      (forward-list 1)
	      (if (<= (point) p) (setq parg (1+ parg))))
	    (store-match-data md)
	    (setq i (+ 2 grouping))
	    (if (and (match-beginning i)
		     (>= p (match-beginning i)) (< p (match-end i)))
		-1			;return -1 if point is on optional arg
	      (if (< p (point)) parg))
	    )))))

(defun YaTeX-on-maketitle-p ()
  "Check if point is on maketitle type commands.
Call this function after YaTeX-on-section-command-p."
  (let ((p (point)))
    (save-excursion
      (or (= (char-after (point)) ?\\ )
	  (progn
	    (skip-chars-backward
	     (concat "^" YaTeX-ec-regexp) (point-beginning-of-line))
	    (or (bobp) (bolp) (backward-char 1))))
      (and (looking-at (concat YaTeX-ec-regexp YaTeX-TeX-token-regexp))
	   (<= (match-beginning 0) p)
	   (> (match-end 0) p)))))

(defun YaTeX-on-begin-end-p ()
  (save-excursion
    (if (and (boundp 'in-leftright-p) in-leftright-p)
	;; Dirty workaround for YaTeX-goto-corresponding-leftright 2003/3/28
	(let ((md (match-data)))	; for safety
	  (if (looking-at YaTeX-ec-regexp)
	      nil			; stay here
	    (cond
	     ((looking-at "\\w")		(skip-chars-backward "A-Za-z"))
	     ((looking-at "\\.()\\[\\]|")	(forward-char -1)))
	    (if (equal (char-after (1- (point)))
		       (string-to-char YaTeX-ec))
		(forward-char -1))))
      ;(beginning-of-line)
      (if (equal (char-after (point)) ?\\) nil	;stay here
	(skip-chars-backward "^\n\\\\")
	(or (bolp) (forward-char -1))))
    (re-search-forward
     ;;"\\\\begin{\\([^}]+\\)}\\|\\\\end{\\([^}]+\\)}"
     (concat
      (YaTeX-replace-format-args
       (regexp-quote YaTeX-struct-begin)
       (concat "\\(" YaTeX-struct-name-regexp "\\)") "" "" "")
      "\\|"
      (YaTeX-replace-format-args
       (regexp-quote YaTeX-struct-end)
       (concat "\\(" YaTeX-struct-name-regexp "\\)") "" "" "")
      "\\|\\("
      YaTeX-ec-regexp  ;;"[][()]\\)"
      "[\\]\\[]\\)"
      )
     (point-end-of-line) t)))

(defun YaTeX-on-includes-p ()
  (save-excursion
    (beginning-of-line)
    (re-search-forward "\\(\\(include[^}]*\\)\\|\\(input\\)\\){[^}]*}"
		       (point-end-of-line) t)))

(defun YaTeX-on-comment-p (&optional sw)
  "Return t if current line is commented out.
Optional argument SW t to treat all `%' lines as comment,
even if on `%#' notation."
  (save-excursion
    (beginning-of-line)
    (skip-chars-forward "\\s ")
    (looking-at (if sw "%" "%[^#]"))))

(defun YaTeX-on-BEGIN-END-p ()
  (save-excursion
    (let ((case-fold-search nil))
      (beginning-of-line)
      (re-search-forward
       "\\(%#BEGIN\\)\\|\\(%#END\\)" (point-end-of-line) t))))

(defun YaTeX-on-SRC-p ()
  (save-excursion
    (let ((case-fold-search nil))
      (beginning-of-line)
      (re-search-forward
       "%#SRC{\\([^}]+\\)}" (point-end-of-line) t))))

(defun YaTeX-goto-corresponding-* (arg)
  "Parse current line and call suitable function."
  (interactive "P")
  (let (mm)
    (cond
     ((YaTeX-goto-corresponding-label arg))
     ((YaTeX-goto-corresponding-environment))
     ((YaTeX-goto-corresponding-file-processor arg))
     ((YaTeX-goto-corresponding-file arg))
     ((YaTeX-goto-corresponding-BEGIN-END))
     ((and (setq mm (YaTeX-in-math-mode-p))
	   (YaTeX-goto-corresponding-leftright)))
     ((and ;;mm YaTeX-use-AMS-LaTeX
	   (YaTeX-goto-corresponding-paren)))
     ;;((and (string-match
     ;;	  YaTeX-equation-env-regexp	;to delay loading
     ;;	  (or (YaTeX-inner-environment t) "document"))
     ;;	 (YaTeX-goto-corresponding-leftright)))
     ((YaTeX-goto-corresponding-viewer))
     (t (message "I don't know where to go.")))))

(defun YaTeX-goto-corresponding-*-other-window (arg)
  "Parse current line and call suitable function."
  (interactive "P")
  (YaTeX-goto-corresponding-* t))

(defun YaTeX-comment-region (alt-prefix)
  "Comment out region by '%'.
If you call this function on the 'begin{}' or 'end{}' line,
it comments out whole environment"
  (interactive "P")
  (if (not (YaTeX-on-begin-end-p))
      (YaTeX-comment-region-sub
       (if alt-prefix
	   (read-string-with-history "Insert prefix: ")
	 YaTeX-comment-prefix))
    (YaTeX-comment-uncomment-env 'YaTeX-comment-region-sub)))

(defun YaTeX-uncomment-region (alt-prefix)
  "Uncomment out region by '%'."
  (interactive "P")
  (if (not (YaTeX-on-begin-end-p))
      (YaTeX-uncomment-region-sub
       (if alt-prefix (read-string-with-history "Remove prefix: ")
	 YaTeX-comment-prefix)
       (region-beginning) (region-end) YaTeX-uncomment-once)
    (YaTeX-comment-uncomment-env 'YaTeX-uncomment-region-sub)))

(defun YaTeX-comment-uncomment-env (func)
  "Comment or uncomment out one LaTeX environment switching function by FUNC."
  (let (beg beg2 (p (point)))
    (save-excursion
	(beginning-of-line)
	(setq beg (point))
	(save-match-data
	  (while (and (not (eobp))
		      (not (eolp))
		      (looking-at YaTeX-comment-prefix))
	    (goto-char (match-end 0))))
	(setq beg2 (point))
	(YaTeX-goto-corresponding-environment)
	(beginning-of-line)
	(if (> p (point)) (setq beg (1+ beg2)) (forward-char 1))
	(funcall func YaTeX-comment-prefix beg (point) YaTeX-uncomment-once)))
  (message "%sommented out current environment."
	   (if (string-match "uncom" (symbol-name func)) "Un-c" "C")))

(defun YaTeX-comment-paragraph ()
  "Comment out current paragraph."
  (interactive)
  (save-excursion
    (cond
     ((YaTeX-on-begin-end-p)
      (beginning-of-line)
      (insert YaTeX-comment-prefix)
      (YaTeX-goto-corresponding-environment)
      (beginning-of-line)
      (insert YaTeX-comment-prefix))
     ((YaTeX-on-comment-p)
      (message "Already commented out."))
     (t
      (mark-paragraph)
      (if (looking-at paragraph-separate) (forward-line 1))
      (YaTeX-comment-region-sub "%")))))

(defun YaTeX-uncomment-paragraph ()
  "Uncomment current paragraph."
  (interactive)
  (save-excursion
    (if (YaTeX-on-begin-end-p)
	(let ((p (point-marker)))
	  (YaTeX-goto-corresponding-environment)
	  (YaTeX-remove-prefix YaTeX-comment-prefix YaTeX-uncomment-once)
	  (goto-char p)
	  (YaTeX-remove-prefix YaTeX-comment-prefix YaTeX-uncomment-once)
	  (set-marker p nil))
      (if (YaTeX-on-comment-p)
	  (let*((fill-prefix "")
		;;append `^%' to head of paragraph delimiter.
		(paragraph-start
		 (concat
		  "^$\\|^%\\(" YaTeX-paragraph-separate "\\)"))
		(paragraph-separate paragraph-start))
	    (mark-paragraph)
	    (if (not (bobp)) (forward-line 1))
	    (YaTeX-uncomment-region-sub "%" nil nil YaTeX-uncomment-once))
	(message "This line is not a comment line.")))))

(defun YaTeX-remove-prefix (prefix &optional once)
  "Remove prefix on current line as far as prefix detected. But
optional argument ONCE makes deletion once."
  (interactive "sPrefix:")
  (beginning-of-line)
  (while (re-search-forward (concat "^" prefix) (point-end-of-line) t)
    (replace-match "")
    (if once (end-of-line))))

(defun YaTeX-kill-some-pairs (predicate gofunc kill-contents)
  "Kill some matching pair.
This function assumes that pairs occupy whole of each line where they resid."
  (if (not (funcall predicate)) nil
    (let ((b1 (match-beginning 0)) (e1 (match-end 0))
	  b2 e2)
      (save-excursion
	(funcall gofunc)
	(funcall predicate)		;get match data
	(if (< (point) e1)		;if currently on begin-line
	    (progn
	      (setq b2 b1 e2 e1
		    b1 (match-beginning 0) e1 (match-end 0))
	      (goto-char e2))		;goto end-line's end
	  (setq b2 (match-beginning 0)
		e2 (match-end 0))
	  (goto-char e2))	;now e2 has surely end-line's end
	(skip-chars-forward " \t")
	(and (eolp)
	     (not (eobp))
	     (setq e2 (1+ (point))))
	(if (not kill-contents)
	    (kill-region
	     (progn
	       (goto-char b2)
	       (skip-chars-backward " \t%")
	       (if (bolp) (point) b2))
	     e2))
	(goto-char b1)
	(skip-chars-backward " \t%")
	(if (not kill-contents)
	    (progn
	      (kill-append
	       (buffer-substring
		(setq b1 (if (bolp) (point) b1))
		(setq e1
		      (progn
			(goto-char e1)
			(while (looking-at "{\\| \t") 
			  (forward-list 1))
			(skip-chars-forward " \t")
			(if (and (eolp) (not (eobp)))
			    (1+ (point))
			  (point)))))
	       t)
	      (delete-region b1 e1))
	  (kill-region
	   (if (bolp) (point) b1)
	   e2)))
      t)))

(defun YaTeX-kill-section-command (point kill-all)
  "Kill section-type command at POINT leaving its last argument.
Non-nil for the second argument kill its last argument too."
  (let ((cmd (get 'YaTeX-on-section-command-p 'command))
	(argc (get 'YaTeX-on-section-command-p 'argc))
	beg (end (make-marker)))
    (save-excursion
      (goto-char point)
      (or (looking-at YaTeX-ec-regexp)
	  (progn
	    (skip-chars-backward (concat "^" YaTeX-ec-regexp))
	    (forward-char -1)))
      (setq beg (point))
      (skip-chars-forward "^{")
      (while (> (setq argc (1- argc)) 0)
	(skip-chars-forward "^{")
	(forward-list 1))
      (kill-region beg (point))
      (forward-list 1)
      (set-marker end (point))
      (if kill-all
	  (progn
	    (kill-append (buffer-substring beg end) nil)
	    (delete-region beg end))
	(goto-char beg)
	(kill-append
	 (buffer-substring
	  (point) (progn (skip-chars-forward "^{" end) (1+ (point))))
	 nil)
	(delete-region beg (1+ (point)))
	(goto-char end)
	(set-marker end nil)
	(kill-append (buffer-substring (point) (1- (point))) nil)
	(delete-backward-char 1)))))

(defun YaTeX-kill-paren (kill-contents)
  "Kill parentheses leaving its contents.
But kill its contents if the argument KILL-CONTENTS is non-nil."
  (interactive "P")
  (let (p bsl (backslash-syntax (char-to-string (char-syntax ?\\)))
	  (md (match-data)))
    (unwind-protect
	(save-excursion
	  (modify-syntax-entry ?\\ " ")
	  (if (looking-at "\\s(\\|\\(\\s)\\)")
	      (progn
		(if (match-beginning 1)
		    (up-list -1))
		(if (and (> (point) (point-min))
			 (= (char-after (1- (point))) ?\\ ))
		    (setq p (1- (point)) bsl t)
		  (setq p (point)))
		(forward-list 1)
					;(YaTeX-goto-open-paren t)
		(if kill-contents (delete-region p (point))
		  (backward-delete-char 1)
		  (cond
		   ((save-excursion
		      (forward-char -2)
		      (looking-at (concat YaTeX-ec-regexp "/")))
		    (backward-delete-char 2))
		   ((= (char-after (1- (point))) ?\\)
		    (backward-delete-char 1)))
		  (goto-char p)
		  (if (looking-at
		       (concat "{" YaTeX-ec-regexp
			       YaTeX-command-token-regexp "+"
			       "\\s +"))
		      (delete-region (point) (match-end 0))
		    (delete-char 1)
		    (if bsl (delete-char 1))))
		t)))
      (modify-syntax-entry ?\\ backslash-syntax)
      (store-match-data md))))

(defvar YaTeX-read-environment-history nil "Holds history of environments.")
(put 'YaTeX-read-environment-history 'no-default t)
(defun YaTeX-read-environment (prompt &optional predicate must-match initial)
  "Read a LaTeX environment name with completion."
  (YaTeX-sync-local-table 'tmp-env-table)
  (completing-read-with-history
   prompt
   (append tmp-env-table user-env-table env-table)
   predicate must-match initial
   'YaTeX-read-environment-history))

(defvar YaTeX-read-section-history nil "Holds history of section-types.")
(put 'YaTeX-read-section-history 'no-default t)
(defun YaTeX-read-section (prompt &optional predicate initial)
  "Read a LaTeX section-type command with completion."
  (YaTeX-sync-local-table 'tmp-section-table)
  (let ((minibuffer-completion-table
	 (append tmp-section-table user-section-table section-table)))
    (read-from-minibuffer-with-history
     prompt initial YaTeX-section-completion-map nil
     'YaTeX-read-section-history)))

(defun YaTeX-read-section-with-overview ()
  "Read sectioning command with overview.
This function refers a local variable `source-window' in YaTeX-make-section,
because this function is called with no argument."
  (interactive)
  (require 'yatexsec)			;some case needs this
  (if (> (minibuffer-depth) 1)
      (error "Too many minibuffer levels for overview."))
  (let ((sw (selected-window))
	(minibuffer-max-depth nil) ; for XEmacs20
	(enable-recursive-minibuffers t) sect)
    (unwind-protect
	(progn
	  (select-window source-window)
	  (setq sect (YaTeX-read-section-in-minibuffer
		      "Sectioning(Up=C-p, Down=C-n, Help=?): "
		      YaTeX-sectioning-level (YaTeX-section-overview))))
      (select-window sw))
    (YaTeX-minibuffer-erase)
    (insert sect)
    (exit-minibuffer)))

(defvar YaTeX-read-fontsize-history nil "Holds history of font designator.")
(put 'YaTeX-read-fontsize-history 'no-default t)
(defun YaTeX-read-fontsize (prompt &optional predicate must-match initial)
  "Read a LaTeX font changing command with completion."
  (YaTeX-sync-local-table 'tmp-fontsize-table)
  (completing-read-with-history
   prompt (append tmp-fontsize-table user-fontsize-table fontsize-table)
   predicate must-match initial 'YaTeX-read-fontsize-history))

(defun YaTeX-change-environment ()
  "Change the name of environment."
  (interactive)
  (if (not (YaTeX-on-begin-end-p)) nil
    (save-excursion
      (let (p env newenv (m1 (match-beginning 1)) (m2 (match-beginning 2)))
	(setq env (if m1 (YaTeX-buffer-substring m1 (match-end 1))
		    (YaTeX-buffer-substring m2 (match-end 2))))
	(goto-char (match-beginning 0))
	(set-mark-command nil)
	(YaTeX-goto-corresponding-environment)
	(setq newenv (YaTeX-read-environment
		      (format "Change environment `%s' to: " env)))
	(cond
	 ((string= newenv "")	(message "Change environment cancelled."))
	 ((string= newenv env)	(message "No need to change."))
	 (t
	  (search-forward (concat "{" env) (point-end-of-line) t)
	  (replace-match (concat "{" newenv) t)
	  (exchange-point-and-mark)
	  (search-forward (concat "{" env) (point-end-of-line) t)
	  (replace-match (concat "{" newenv) t)))
	t))))

(defun YaTeX-change-section ()
  "Change section-type command."
  (interactive)
  (let*((where (YaTeX-on-section-command-p YaTeX-command-token-regexp))
	(p (point)) (cmd (YaTeX-match-string 1))
	(beg (make-marker)) (end (make-marker)) old new)
    (if (null where) nil
      (unwind-protect
	  (let ((source-window (selected-window)))
	    (cond
	     ((equal where 0);;if point is on section command
	      (set-marker beg (match-beginning 1))
	      (set-marker end (match-end 1))
	      (goto-char beg)		;beginning of the command
	      (setq new (YaTeX-read-section
			 (format "Change `%s' to: " cmd) nil)
		    old cmd))

	     ((= where -1);;if point is on a optional parameter
	      (set-marker beg (match-beginning 2))
	      (skip-chars-forward "^{")
	      (set-marker end (point))
	      (goto-char p)
	      (setq new
		    (if (fboundp (intern-soft (concat YaTeX-addin-prefix cmd)))
			(YaTeX-addin cmd)
		      (concat "["
			      (read-string
			       (format "Change `%s' to: "
				       (setq old (YaTeX-buffer-substring
						  (1+ beg) (1- end)))))
			      "]"))))

	     ((> where 0);;if point is in arguments' braces
	      (or (looking-at "{")
		  (progn (skip-chars-backward "^{") (forward-char -1)))
	      (set-marker beg (1+ (point)))
	      (forward-list 1)
	      (forward-char -1)
	      (set-marker end (point))
	      (setq old (YaTeX-buffer-substring beg end))
	      (goto-char p)
	      (if (> (length old) 40)
		  (setq old (concat (substring old 0 12) "..."
				    (substring old -12))))
	      (setq new
		    (if (intern-soft (concat "YaTeX::" cmd))
			(funcall (intern-soft (concat "YaTeX::" cmd)) where)
		      (read-string (format "Change `%s' to: " old)))))
	     )				;cond
	    (if (string= old new)
		nil			;do not replace
	      (delete-region beg end)
	      (goto-char beg)
	      (insert-before-markers new)))
	(set-marker beg nil)
	(set-marker end nil))
      ;;(goto-char (marker-position p))
      new)))

(defun YaTeX-change-fontsize ()
  "Change large-type command."
  (let ((lt (append tmp-fontsize-table user-fontsize-table fontsize-table))
	(p (point)) large old new beg end)
    ;;(and (looking-at "}") (up-list -1))
    ;;(and (looking-at "{") (forward-char 1))
    ;;Is above convenient?
    (save-excursion
      (or (looking-at YaTeX-ec-regexp)
	  (progn
	    (skip-chars-backward (concat "^" YaTeX-ec-regexp))
	    (forward-char -1)))
      (cond
       ((and
	 (looking-at
	  (concat YaTeX-ec-regexp "\\(" YaTeX-TeX-token-regexp "\\)"))
	 (< p (match-end 0))
	 (assoc (setq old (YaTeX-match-string 1)) lt))
	(goto-char p)
	(setq beg (match-beginning 1) end (match-end 1) ;save match position
	      new (completing-read
		   (format "Change font/size `%s' to : " old) lt))
	(delete-region beg end)
	(goto-char beg)
	(insert-before-markers new)
	new)
       (t nil)
       ))))

(defun YaTeX-change-math-image ()
  "Change with image completion."
  (let (maketitle memberp beg end)
    (if (and (YaTeX-on-maketitle-p)
	     (progn
	       (setq maketitle (substring (YaTeX-match-string 0) 1))
	       (setq memberp (YaTeX-math-member-p maketitle))))
	(let*((last-command-char (string-to-char (car memberp)))
	      (last-command-event last-command-char))
	  (setq beg (match-beginning 0) end (match-end 0))
	  (delete-region beg end)
	  (YaTeX-math-insert-sequence t (cdr memberp))))))

(defun YaTeX-kill-* (&optional arg)
  "Parse current line and call suitable function.
Non-nil for ARG kills its contents too."
  (interactive "P")
  (cond
   ((YaTeX-kill-some-pairs 'YaTeX-on-begin-end-p
			   'YaTeX-goto-corresponding-environment arg))
   ((YaTeX-kill-some-pairs 'YaTeX-on-BEGIN-END-p
			   'YaTeX-goto-corresponding-BEGIN-END arg))
   ((YaTeX-on-section-command-p YaTeX-command-token-regexp);on any command
    (YaTeX-kill-section-command (match-beginning 0) arg))
   ((YaTeX-kill-paren arg))
   ((and (fboundp 'overlays-at)
	 (member YaTeX-on-the-fly-overlay (overlays-at (point))))
    (YaTeX-on-the-fly-cancel))
   (t (message "I don't know what to kill."))))

(defun YaTeX-change-* ()
  "Parse current line and call suitable function."
  (interactive)
  (cond
   ((YaTeX-change-parentheses))
   ((YaTeX-change-environment))
   ((YaTeX-change-section))
   ((YaTeX-change-fontsize))
   ((YaTeX-change-math-image))
   (t (message "I don't know what to change."))))

;;;
;Check availability of add-in functions
;;;
(cond
 ((featurep 'yatexadd) nil)		;Already provided.
 ((progn (load "yatexadd" t) (featurep 'yatexadd)) nil)
 (t (message "YaTeX add-in functions not supplied.")))

(defun YaTeX-addin (name)
  "Check availability of addin function and call it if exists."
  (if (and (not (get 'YaTeX-generate 'disabled))
	   (intern-soft (concat YaTeX-addin-prefix name))
	   (fboundp (intern-soft (concat YaTeX-addin-prefix name))))
      (let ((s (funcall (intern (concat YaTeX-addin-prefix name)))))
	(if (stringp s) s ""))
    "")) ;Add in function is not bound.


(defun YaTeX-on-item-p (&optional point)
  "Return t if POINT (default is (point)) is on \\item."
  (let ((p (or point (point))))
    (save-excursion
      (goto-char p)
      (end-of-line)
      (setq p (point))
      (re-search-backward YaTeX-paragraph-delimiter nil t)
      (re-search-forward YaTeX-item-regexp p t))))

(defun YaTeX-in-verb-p (&optional point)
  "Check if POINT is in verb or verb*.  Default of POINT is (point)."
  (setq point (or point (point)))
  (save-excursion
    (let ((md (match-data)))
      (goto-char point)
      (unwind-protect
	  (if (not (re-search-backward
		    (concat YaTeX-ec-regexp
			    "\\(" YaTeX-verb-regexp "\\)"
			    "\\([^-A-Za-z_*]\\)")
		    (point-beginning-of-line) t))
	      nil
	    (goto-char (match-end 2))
	    (skip-chars-forward
	     (concat "^" (YaTeX-buffer-substring
			  (match-beginning 2) (match-end 2))))
	    (and (< (match-beginning 2) point) (< (1- point) (point))))
	(store-match-data md)))))

(defun YaTeX-literal-p (&optional point)
  "Check if POINT is in verb or verb* or verbatime environment family.
Default of POINT is (point)."
  (let ((md (match-data)))
    (unwind-protect
	(cond
	 ((equal YaTeX-ec "\\")		;maybe LaTeX
	  (save-excursion
	    (and point (goto-char point))
	    (or (YaTeX-in-verb-p (point))
		(and (not (looking-at "\\\\end{verb"))
		     (YaTeX-quick-in-environment-p
		      YaTeX-verbatim-environments))))))
      (store-match-data md))))

;; Filling \item
(defun YaTeX-remove-trailing-comment (start end)
  "Remove trailing comment from START to end."
  (save-excursion
    (let ((trcom (concat YaTeX-comment-prefix "$")))
      (goto-char start)
      (while (re-search-forward trcom end t)
	(if (/= (char-after (1- (match-beginning 0))) ?\\ )
	    (replace-match "\\1"))))))

(defvar YaTeX-itemize-withlabel-max-indent-depth 8)
(defun YaTeX-get-item-info (&optional recent thisenv)
  "Return the list of the beginning of \\item and column of its item.
If it seems to be outside of itemizing environment, just return nil.
Non-nil for optional argument RECENT refers recent \\item.
Optional second argument THISENV omits calling YaTeX-inner-environment."
  (save-excursion
    (let* ((p (point)) env e0 c cc md
	   (bndry (and (setq env (or thisenv (YaTeX-inner-environment t)))
		       (get 'YaTeX-inner-environment 'point))))
      (end-of-line)
      (if (if recent
	      (catch 'found
		(while (YaTeX-re-search-active-backward
			YaTeX-item-regexp YaTeX-comment-prefix bndry t)
		  (setq md (match-data))
		  (YaTeX-inner-environment t)
		  (store-match-data md)
		  (if (= bndry (get 'YaTeX-inner-environment 'point))
		      (throw 'found t))))
	    (goto-char bndry)
	    (YaTeX-re-search-active-forward
	     YaTeX-item-regexp YaTeX-comment-prefix p t))
	  (progn
	    (goto-char (match-end 0))
	    ;(setq c (current-column))
	    (if (string-match "desc" env)
		(setq c 6)
	      (setq cc (current-column))
	      (if (equal (following-char) ?\[) (forward-list 1))
	      (if (< (- (current-column) cc)
		     YaTeX-itemize-withlabel-max-indent-depth)
		  (setq c 0)
		(move-to-column cc)
		(setq c YaTeX-itemize-withlabel-max-indent-depth)))
	    (skip-chars-forward " \t" (point-end-of-line))
	    (list (point-beginning-of-line) (+ c (current-column))))))))

(defun YaTeX-fill-item ()
  "Fill item in itemize environment."
  (interactive)
  (save-excursion
    (let* ((p (point))
	   (item-term (concat
		       "\\(^[ \t]*$\\)\\|" YaTeX-item-regexp "\\|\\("
		       YaTeX-ec-regexp "\\(begin\\|end\\)\\)"))
	   ;;This value depends on LaTeX.
	   fill-prefix start col
	   (info (YaTeX-get-item-info t)))
      (if (null info) nil		;not on \item, do nothing
	(setq start (car info)
	      col (car (cdr info)))
	(save-excursion
	  (if (re-search-backward "^\\s *$" start t)
	      ;;if separated from \item line, isolate this block
	      (progn
		(setq start (1+ (match-end 0)))
		(goto-char start)
		(skip-chars-forward " \t")
		(delete-region (point) start) ;is this your favor???
		(indent-to col))))
	(beginning-of-line)
	(if (<= (save-excursion
		 (re-search-forward
		  (concat "\\\\end{\\|\\\\begin{\\|^[ \t]*$") nil t)
		 (match-beginning 0))
	       p)
	    (progn  (message "Not on itemize.") nil)
	  (end-of-line)
	  (newline)
	  (indent-to col)
	  (setq fill-prefix
		(YaTeX-buffer-substring (point-beginning-of-line)(point)))
	  (beginning-of-line)
	  (delete-region (point) (progn (forward-line 1) (point)))
	  (re-search-forward item-term nil 1)
	  (YaTeX-remove-trailing-comment start (point))
	  (beginning-of-line)
	  (push-mark (point) t)
	  (goto-char start)
	  (forward-line 1)
	  (while (< (point) (mark))
	    (delete-region (point) (progn (skip-chars-forward " \t") (point)))
	    (forward-line 1))
	  (fill-region-as-paragraph start (mark))
	  (if NTT-jTeX
	      (while (progn(forward-line -1)(end-of-line) (> (point) start))
		(insert ?%)))
	  (pop-mark))))))

(defun YaTeX-fill-paragraph (arg)
  "YaTeX adjustment function for fill-paragraph.
*Protect \\verb from unexpected broken up."
  (interactive "P")
  (cond
   ((not (eq major-mode 'yatex-mode)) (fill-paragraph arg))
   ((YaTeX-quick-in-environment-p YaTeX-fill-inhibit-environments) nil)
   ((YaTeX-in-math-mode-p) nil)
   (t
    (save-excursion
      (let*((verbrex (concat YaTeX-ec-regexp
			     "\\(" YaTeX-verb-regexp "\\)" ;match#1
			     "\\(.\\).*\\(\\2\\)")) ;match #2 and #3
	    (tilderex (concat "\\("
			      YaTeX-kanji-regexp "~"
			      "\\)" YaTeX-ec-regexp
			      "\\|\\("
			      "~" YaTeX-kanji-regexp
			      "\\)"))
	    (p (point)) ii end poslist spacelist lenlist b e n
	    (fill-prefix fill-prefix)
	    (inenv (or (YaTeX-inner-environment t) "document"))
	    (border (get 'YaTeX-inner-environment 'point)))
	(cond
	 ((save-excursion (beginning-of-line) ;if point is on the first
			  (setq end (point))  ;non-whitespace char
			  (skip-chars-forward " \t")
			  (equal (point) p))
	  (setq fill-prefix (YaTeX-buffer-substring p end)))
	 ((and ;;(not YaTeX-emacs-19)
	       (string-match YaTeX-itemizing-env-regexp inenv)
	       (setq ii (YaTeX-get-item-info)))
	  (save-excursion
	    (beginning-of-line)
	    (indent-to-column (car (cdr ii)))
	    (setq fill-prefix
		  (YaTeX-buffer-substring (point) (point-beginning-of-line)))
	    (delete-region (point) (progn (beginning-of-line) (point))))))
	(cond
	 ((string-match "tabular" inenv)
	  (let ((b (point-beginning-of-line))
		(e (point-end-of-line)))
	    (if (re-search-backward
		 "&\\|\\\\\\\\\\|\\\\\\(begin\\|end\\){" border t)
		(setq b (if (match-beginning 1)
			    (progn (forward-line 1) (point))
			  (point-beginning-of-line))))
	    (goto-char p)
	    (if (re-search-forward
		 "&\\|\\\\\\\\\\|\\\\\\(end\\|begin\\){" nil t)
		(setq e (if (match-beginning 1)
			    (progn (forward-line -1)
				   (point-end-of-line))
			  (match-beginning 0))))
	    (set-mark e)
	    (goto-char b)))
	 (t
	  (mark-paragraph)))
	(save-restriction
	  (narrow-to-region (region-beginning) (region-end))
	  (YaTeX-remove-trailing-comment (point-min) (point-max))
	  ;; First, replace spaces in verb to _ temporarily.
	  (goto-char (point-min))
	  (while (YaTeX-re-search-active-forward
		  verbrex YaTeX-comment-prefix (point-max) t)
	    (setq end (match-beginning 3))
	    (goto-char (match-beginning 2))
	    (while (re-search-forward "\\s " end t)
	      (setq poslist (cons (make-marker) poslist)
		    spacelist (cons (preceding-char) spacelist)
		    lenlist (cons 1 lenlist))
	      (replace-match "_")
	      (set-marker (car poslist) (match-beginning 0))))
	  ;; Second, replace "\~\ref{...}" to "\\\ref{...}"
	  (goto-char (point-min))
	  (while (YaTeX-re-search-active-forward
		  tilderex YaTeX-comment-prefix (point-max) t)
	    (if (match-beginning 1)
		(setq b (match-beginning 1) e (match-end 1) n 1)
	      (setq b (match-beginning 2) e (match-end 2) n 2))
	    (setq poslist (cons (make-marker) poslist)
		  spacelist (cons (YaTeX-match-string n) spacelist)
		  lenlist (cons 2 lenlist))
	    (goto-char (match-beginning 0))
	    (delete-region (point) e)
	    (insert YaTeX-ec YaTeX-ec)	;set-marker should be here
	    (set-marker (car poslist) b))
	  ;;(fill-paragraph arg)
	  (fill-region-as-paragraph (point-min) (point-max) arg)
	  (while spacelist
	    (goto-char (car poslist))
	    (set-marker (car poslist) nil)
	    (and (eolp) (skip-chars-forward "\n\t "))
	    (delete-char (car lenlist))
	    (insert (car spacelist))
	    (setq spacelist (cdr spacelist)
		  poslist (cdr poslist)
		  lenlist (cdr lenlist)))
	  (goto-char (point-min))
	  (forward-word 1)
	  (beginning-of-line)
	  (while (re-search-forward "\\\\\\([a-z]*ref\\|cite\\){" nil t)
	    (if (< (point-end-of-line)
		   (save-excursion (forward-char -1) (forward-list 1) (point)))
		(progn (end-of-line)
		       (if (save-excursion
			     (backward-word 1)
			     (looking-at "[^0-9A-z!-)]"))
			   (insert YaTeX-comment-prefix)))))
	  ;; Nonbreak space `~'
	  (goto-char (point-min))
	  (while (YaTeX-re-search-active-forward
		  "~\\(\\s *\\)$" YaTeX-comment-prefix (point-max) t)
	    (delete-region (match-beginning 1) (match-end 1))
	    (insert YaTeX-comment-prefix))
	  (goto-char (point-min))
	  (if (and NTT-jTeX (looking-at "[ \t]\\|^$"))
	      (progn
		(goto-char (point-min))
		(while (not (eobp))
		  (end-of-line)
		  (or (bolp)
		      (save-excursion
			(backward-word 1)
			(looking-at "[0-9A-z!-)]")) ;is not japanese string
		      (progn (setq p (point)) (insert YaTeX-comment-prefix)))
		  (forward-line 1))
		(goto-char p)
		(if (looking-at "%") (delete-char 1)) ;remove last inserted `%'
		))))))))

(if (fboundp 'YaTeX-saved-indent-new-comment-line) nil
  (fset 'YaTeX-saved-indent-new-comment-line
	(symbol-function 'indent-new-comment-line))
  (fset 'indent-new-comment-line 'YaTeX-indent-new-comment-line))

(defun YaTeX-indent-new-comment-line (&optional soft)
  "Tuned `indent-new-comment-line' function for yatex.
See the documentation of `YaTeX-saved-indent-new-comment-line'."
  (interactive)
  (cond
   ((or (not (memq major-mode '(yatex-mode yahtml-mode)))
	(string-match
	 "document"
	 (or (and (boundp 'inenv) inenv)
	     (or (YaTeX-inner-environment t) "document"))))
    (apply 'YaTeX-saved-indent-new-comment-line (if soft (list soft))))
;   ((and (eq major-mode 'yahtml-mode)
;	 (string-match
;	  "^[Pp][Rr][Ee]" (yahtml-inner-environment-but "^[Aa]\\b" t)))
;    (yahtml-indent-new-commnet-line))
   ((and (eq major-mode 'yatex-mode)	;1997/2/4
	 (YaTeX-in-math-mode-p)) nil)		;1996/12/30
   (t (let (fill-prefix)
	(apply 'YaTeX-saved-indent-new-comment-line (if soft (list soft)))))))

(defun YaTeX-fill-* ()
  "Fill paragraph according to its condition."
  (interactive)
  (cond
   ((YaTeX-fill-item))
   ))

;; Accent completion
(defun YaTeX-read-accent-char (x)
  "Read char in accent braces."
  (let ((c (read-char)))
    (concat
     (if (and (or (= c ?i) (= c ?j))
	      (not (string-match (regexp-quote x) "cdb")))
	 "\\" "")
     (char-to-string c))))

(defun YaTeX-make-accent ()
  "Make accent usage."
  (interactive)
  (message "1:` 2:' 3:^ 4:\" 5:~ 6:= 7:. u v H t c d b")
  (let ((c (read-char))(case-fold-search nil))
    (setq c (cond ((and (> c ?0) (< c ?8))
		   (substring "`'^\"~=." (1- (- c ?0)) (- c ?0)))
		  ((= c ?h) "H")
		  (t (char-to-string c))))
    (if (not (string-match c "`'^\"~=.uvHtcdb")) nil
      (insert "\\" c "{}")
      (backward-char 1)
      (insert (YaTeX-read-accent-char c))
      (if (string= c "t") (insert (YaTeX-read-accent-char c)))
      (forward-char 1))))

;; Field skip in tabular
(defun YaTeX-forward-field (arg)
  "Move forward to the ARGth next column field of table."
  (interactive "p")
  (if (< arg 0)
      (YaTeX-backward-field (- arg))
    (let ((ep (save-excursion (YaTeX-end-of-environment) (point)))
	  (wc (car (YaTeX-array-what-column-internal))))
      (while (>= (setq arg (1- arg)) 0)
	(skip-chars-forward "^&\\\\")
	(while (and (not (eobp))
		    (> ep (point))
		    (looking-at "\\&\\|\\\\")
		    (= wc (car (YaTeX-array-what-column-internal))))
	  (skip-chars-forward "&" ep)
	  (while (looking-at "[\n\t ]+\\|\\\\\\\\\\|\\\\.line\\>")
	    (goto-char (match-end 0))
	    ))))))

(defun YaTeX-backward-field (arg)
  "Move backward to the ARGth next column field of table."
  (interactive "p")
  (if (< arg 0)
      (YaTeX-forward-field (- arg))
    (let ((bp (save-excursion
		(YaTeX-beginning-of-environment)
		(point-end-of-line)))
	  (wc (car (YaTeX-array-what-column-internal))))
      (while (>= (setq arg (1- arg)) 0)
	(skip-chars-backward "^&\\\\" bp)
	(while (and (not (bobp))
		    (< bp (point))
		    (memq (preceding-char) '(?& ?\\))
		    (= wc (car (YaTeX-array-what-column-internal))))
	  (skip-chars-backward "&\\\\" bp)
	  (skip-chars-backward "\n\t " bp))
	(if (eolp) (skip-chars-forward "^&\\\\"))))))

;; Indentation
(defun YaTeX-current-indentation ()
  "Return the indentation of current environment."
  (save-excursion
    ;;(beginning-of-line)
    (if (YaTeX-beginning-of-environment t)
	(goto-char (get 'YaTeX-inner-environment 'point))
      (forward-line -1)
      (beginning-of-line)
      (skip-chars-forward " \t"))
    (current-column)))

(defun YaTeX-previous-line-indentation ()
  (save-excursion
    (forward-line -1)
    (skip-chars-forward " \t")
    (current-column)))

(defvar YaTeX-noindent-env-regexp "verbatim\\*?\\|alltt"
  "*Regexp of environment names that should begin with no indentation.
All verbatime-like environment name should match with.")
(defun YaTeX-indent-line ()
  "Indent corrent line referrin current environment."
  (interactive)
  (let ((indent-relative
	 (function
	  (lambda (&optional additional)
	    (YaTeX-reindent
	     (+ (YaTeX-current-indentation)
		(or additional 0)
		YaTeX-environment-indent)))))
	sect depth iteminfo (p (point)) pp (peol (point-end-of-line)) begend
	;;inenv below is sometimes defined in YaTeX-indent-new-comment-line
	(inenv (or (and (boundp 'inenv) inenv) (YaTeX-inner-environment t))))
    ;;(if NTT-jTeX		;;Do you need this section?
    ;;	(save-excursion
    ;;  (end-of-line)
    ;;  (let ((p (point)))
    ;;    (forward-line -1)
    ;;    (end-of-line)
    ;;    (or (= p (point))
    ;;	(progn (backward-char (length YaTeX-comment-prefix))
    ;;	       (not (looking-at (regexp-quote YaTeX-comment-prefix))))
    ;;	(progn
    ;;	  (skip-chars-backward YaTeX-comment-prefix)
    ;;	  (kill-line))))))
    (or inenv (setq inenv "document"))	;is the default environment
    (cond
     ((and
       (prog1 (YaTeX-on-begin-end-p)
	 (setq begend (match-beginning 0)))
       (or (match-beginning 2)		;if \end
	   (and (match-beginning 3)	;if \) \]
		(= (char-syntax (char-after (1+ (match-beginning 3)))) ?\)))))
      (YaTeX-reindent
       (save-excursion
	 (YaTeX-goto-corresponding-environment)
	 (current-column))))
     ;; on the begining of verbatime line, remove all indentation
     ((and begend ;; match-beginning 0 of \begin
	   YaTeX-noindent-env-regexp
	   (stringp YaTeX-noindent-env-regexp)
	   (save-excursion
	     (and ;; if the \begin is the first declaration of this line
	      (progn (beginning-of-line) (skip-chars-forward " \t")
		     (= begend (point)))
	      (progn
		(goto-char begend)
		(looking-at
		 (concat YaTeX-ec-regexp
			 "begin{\\(" YaTeX-noindent-env-regexp "\\)}"))))))
      (save-excursion
	(goto-char begend)
	(delete-region (point) (point-beginning-of-line))))
     ((string-match YaTeX-equation-env-regexp inenv)
      (YaTeX-indent-line-equation))	;autoload-ed from yatexenv
     (;(YaTeX-in-environment-p '("itemize" "enumerate" "description" "list"))
      (string-match YaTeX-itemizing-env-regexp inenv)
      ;;(YaTeX-on-item-p) ??
      ;;(setq iteminfo (YaTeX-get-item-info t))
      (if (save-excursion
	    (beginning-of-line)
	    (re-search-forward YaTeX-item-regexp peol t))
	  (progn
	    (save-excursion
	      (goto-char (1+ (match-beginning 0)))
	      (setq depth
		    (* YaTeX-environment-indent
		       (cond
			((looking-at "subsubsub")	3)
			((looking-at "subsub")	2)
			((looking-at "sub")	1)
			(t			0)))))
	    (funcall indent-relative depth))
	(YaTeX-reindent (or (car (cdr (YaTeX-get-item-info t inenv)))
			    (+ (save-excursion
				 (beginning-of-line)
				 (YaTeX-current-indentation))
			       YaTeX-environment-indent))))
      )
     ((YaTeX-literal-p)			;verbatims
      (tab-to-tab-stop))
     ((string-match "\\(tabular\\|array\\)" inenv) ;1.73
      (let ((n 1) (cc (current-column)) (p (point)))
	(condition-case err
	    (save-excursion
	      (beginning-of-line)
	      (skip-chars-forward "[ \t]")
	      ;;(if (looking-at "&") (forward-char 1))
	      (require 'yatexenv)
	      (setq n (car (YaTeX-array-what-column-internal))))
	  (error nil))
	(YaTeX-reindent
	 (+ (YaTeX-current-indentation)
	    YaTeX-environment-indent
	    (* (1- n) YaTeX-tabular-indentation)))
	(and (= cc (current-column))
	     (= p (point))
	     (equal last-command 'YaTeX-indent-line)
	     ;; if NO indent action occured, move to the next column
	     (YaTeX-forward-field 1))))
     ((and inenv (not (equal "document" inenv)))
      (funcall indent-relative))
     ((YaTeX-on-section-command-p YaTeX-sectioning-regexp)
      (require 'yatexsec)		;to know YaTeX-sectioning-level
      (setq sect (YaTeX-match-string 1))
      (if (string-match "\\*$" sect)
	  (setq sect (substring sect 0 -1)))
      (YaTeX-reindent
       (* (max
	   (1-				;I want chapter to have indentation 0
	    (or (cdr (assoc sect YaTeX-sectioning-level))
		0))
	   0)
	  YaTeX-environment-indent)))
     ;;Default movement
     ((and (bolp) fill-prefix) (insert fill-prefix))
     (t (save-excursion
	  (beginning-of-line)
	  (if fill-prefix
	      (progn
		(delete-region (point)
			       (progn (skip-chars-forward " \t")
				      (point)))
		(insert fill-prefix))
	    (skip-chars-forward " \t")
	    (if (bobp)
		nil
	      (indent-relative-maybe))))
	(skip-chars-forward " \t")))
    ;;if current line is \begin, re-indent \end too
    (if (and (YaTeX-on-begin-end-p) (match-beginning 1))
	(save-excursion
	  ;;(beginning-of-line)
	  ;;(search-forward "\\begin")
	  (goto-char (match-beginning 0))
	  (setq depth (current-column))
	  (YaTeX-goto-corresponding-environment)
	  (YaTeX-reindent depth)))
    (if (or
	 (and NTT-jTeX
	      (save-excursion (beginning-of-line) (looking-at "[ \t]")))
	 (save-excursion
	   (beginning-of-line)
	   (and
	    (not (bobp))
	    (progn
	      (backward-char 1)
	      (re-search-backward
	       "\\\\\\(\\(page\\)?ref\\|cite\\){" (point-beginning-of-line) t))
	    (goto-char (1- (match-end 0)))
	    (> (save-excursion
		 (condition-case ()
		     (progn (forward-list 1) (point))
		   (error (point-max))))
	       (point-end-of-line)))))
	(save-excursion
	  (end-of-line)
	  (let ((p (point)))
	    (forward-line -1)
	    (end-of-line)
	    (or (= p (point))
		(looking-at (regexp-quote YaTeX-comment-prefix))
		(bobp) (bolp)
		(save-excursion
		  (backward-word 1)
		  (looking-at "\\sw+")) ;is not japanese string
		(insert YaTeX-comment-prefix)))))))

(defun YaTeX-comment-line-break (&optional soft)
  "Call comment-indent-new-line and YaTeX-indent-line"
  (comment-indent-new-line soft)
  (YaTeX-indent-line))

(defun YaTeX-latex2e-p ()
  (let ((b (current-buffer))
	(ptn (concat YaTeX-ec "documentclass")))
    (unwind-protect
	(or (save-excursion (search-backward ptn nil t))
	    (progn
	      (YaTeX-visit-main t)
	      (save-excursion (search-backward ptn nil t))))
      (set-buffer b))))

(provide 'yatex)
(defvar yatex-mode-load-hook nil
  "*List of functions to be called when yatex.el is loaded.")
(if (and YaTeX-emacs-19 YaTeX-display-color-p (not (featurep 'yatex19)))
    (load "yatex19"))
(load "yatexhks" t)

;;-------------------- Final hook jobs --------------------
(substitute-all-key-definition
 'fill-paragraph 'YaTeX-fill-paragraph YaTeX-mode-map)
(substitute-all-key-definition
 'kill-buffer 'YaTeX-kill-buffer YaTeX-mode-map)
(run-hooks 'yatex-mode-load-hook)

;; `History' was moved to ChangeLog
;----------------------------- End of yatex.el -----------------------------