File: context.el

package info (click to toggle)
xemacs21-packages 2007.04.27-1
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 109,716 kB
  • ctags: 85,086
  • sloc: lisp: 1,177,163; ansic: 16,426; java: 13,399; xml: 6,152; makefile: 3,552; sh: 3,519; asm: 3,007; perl: 749; ruby: 257; csh: 113; haskell: 93; python: 47; awk: 44
file content (1508 lines) | stat: -rw-r--r-- 51,183 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
;;; context.el --- Support for ConTeXt documents.

;; Copyright (C) 2003, 2004 Free Software Foundation, Inc.

;; Maintainer: Berend de Boer <berend@pobox.com>
;; Keywords: tex

;; This file is part of AUCTeX.

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

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

;; You should have received a copy of the GNU General Public License
;; along with AUCTeX; see the file COPYING.  If not, write to the Free
;; Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
;; 02111-1307, USA.

;;; Commentary:

;; This is in progress ConTeXt support for AUCTeX. Please report
;; anomalies or things you believe should be added.

;; AUCTeX is closely intervowen with LaTeX.  We have to split up
;; things without breaking 'em.

;; some parts are stolen from latex.el and adapted to ConTeXt.

;; TODO
;; 1. indentation still bad.
;; 2. paragraph refilling doesn't work 100%, and is very slow.
;; 4. Remove dependency on LaTeX by moving LaTeX commands to TeX.
;; 5. Most ConTeXt macro's don't currently have lisp code to query for
;;    arguments. As ConTeXt arguments are quite complex, the LaTeX way
;;    of querying for arguments just doesn't cut it.
;; 6. Check auto-parsing: does it detect % interface=nl for example?
;; 7. Complete adding ConTeXt macro's. Perhaps parse cont-en.xml and
;;    generate the interfaces?
;; 8. Add to menu: make TeX hash (mktexlsr), context format and metapost format.

;; TODO Documentation
;; 1. multifile done differently with ConTeXt

;;; Code:

(require 'tex-buf)
(require 'tex)
;; need functions like TeX-look-at and LaTeX-split-long-menu
(require 'latex)

(defgroup ConTeXt-macro nil
  "Special support for ConTeXt macros in AUCTeX."
  :prefix "TeX-"
  :group 'ConTeXt
  :group 'TeX-macro)


;;; variables

;; globals used in certain macro's.
(defvar done-mark nil
  "Position of point afterwards, default nil (meaning end).")

(defvar reference nil
  "Set by `ConTeXt-section-ref', used by `ConTeXt-section-section'.")

(defvar title nil
  "Set by `ConTeXt-section-title', used by `ConTeXt-section-section'.")


;; others

(setq ConTeXt-known-interfaces '("cz" "de" "en" "it" "nl" "ro" "uk"))

(defcustom ConTeXt-default-interface "en"
  "Default interface to be used when running ConTeXt."
  :group 'ConTeXt
  :type 'string)

(defvar ConTeXt-current-interface "en"
  "Interface to be used for inserting macros and ConTeXt run.")

(defvar ConTeXt-menu-changed nil)
;; Need to update ConTeXt menu.
(make-variable-buffer-local 'ConTeXt-menu-changed)

(defvar ConTeXt-largest-level nil
  "Largest sectioning level within current document.")
(make-variable-buffer-local 'ConTeXt-largest-level)

(defun ConTeXt-largest-level ()
  (TeX-update-style)
  ConTeXt-largest-level)


;;; Syntax

(defvar ConTeXt-optop "["
  "The ConTeXt optional argument opening character.")

(defvar ConTeXt-optcl "]"
  "The ConTeXt optional argument closing character.")


;; Setup a ConTeXt macro

(defvar ConTeXt-setup-list ()
  "Calls ConTeXt-XX-setup-list where XX is the current interface.")

(defun ConTeXt-setup-command (what)
  "The ConTeXt macro to setup WHAT."
  (funcall
   (intern (concat "ConTeXt-setup-command-" ConTeXt-current-interface)) what))

(defun ConTeXt-insert-setup (setup)
  "Insert the ConTeXt setup macro SETUP."
  (insert TeX-esc (ConTeXt-setup-command setup))
  (newline)
  (indent-according-to-mode)
  (ConTeXt-arg-setup nil))


;;; Project structure

(defvar ConTeXt-project-structure-list ()
  "Calls ConTeXt-XX-project-structure where XX is the current interface.")

(defun ConTeXt-project-structure (N)
  "Insert a ConTeXt project structure where N is in index into `ConTeXt-project-structure-list'."
  (funcall (intern(concat
		   "ConTeXt-project-"
		   (nth N ConTeXt-project-structure-list)
		   "-insert"))))

(defun ConTeXt-project-project-insert ()
  "Insert a basic template for a new ConTeXt project."
  (save-excursion
    (insert "% The following names are examples only\n")
    (insert TeX-esc (ConTeXt-environment-start-name) (nth 0 ConTeXt-project-structure-list) " myproject")
    (newline 2)
    (insert TeX-esc (nth 1 ConTeXt-project-structure-list) " myenvironment")
    (newline 2)
    (insert TeX-esc (nth 2 ConTeXt-project-structure-list) " myproduct1")
    (newline 2)
    (insert TeX-esc (nth 2 ConTeXt-project-structure-list) " myproduct2")
    (newline 2)
    (insert TeX-esc (ConTeXt-environment-stop-name) (nth 0 ConTeXt-project-structure-list))))

(defun ConTeXt-project-environment-insert ()
  "Insert a basic template for the environment of a ConTeXt project."
  (save-excursion
    (insert "% The name 'myenvironment' is an example only.\n"
	    "% It must match the name in your project file.\n")
    (insert TeX-esc (ConTeXt-environment-start-name)
	    (nth 1 ConTeXt-project-structure-list) " myenvironment\n\n")
    (insert "% Put environment charateristics that must be defined at the "
	    "highest level here\n\n")
    (insert TeX-esc (ConTeXt-environment-stop-name)
	    (nth 1 ConTeXt-project-structure-list))))

(defun ConTeXt-project-product-insert ()
  "Insert a basic template for a product of a ConTeXt project."
  (save-excursion
    (insert "% The following names are examples only\n")
    (insert TeX-esc (ConTeXt-environment-start-name)
	    (nth 2 ConTeXt-project-structure-list) " myproduct1")
    (newline 2)
    (insert TeX-esc (nth 0 ConTeXt-project-structure-list) " myproject")
    (newline 2)
    (insert "% Components are optional. "
	    "You can also just start your document here.\n")
    (insert TeX-esc (nth 3 ConTeXt-project-structure-list) " mycomponent1")
    (newline 2)
    (insert TeX-esc (nth 3 ConTeXt-project-structure-list) " mycomponent2")
    (newline 2)
    (insert TeX-esc (ConTeXt-environment-stop-name)
	    (nth 2 ConTeXt-project-structure-list))))

(defun ConTeXt-project-component-insert ()
  "Insert a basic template for a component of a ConTeXt project."
  (save-excursion
    (insert "% The following names are examples only\n")
    (insert TeX-esc (ConTeXt-environment-start-name)
	    (nth 3 ConTeXt-project-structure-list) " mycomponent1")
    (newline 2)
    (insert TeX-esc (nth 0 ConTeXt-project-structure-list) " myproject\n")
    (insert TeX-esc (nth 2 ConTeXt-project-structure-list) " myproduct1")
    (newline 2)
    (insert "% ... text here ...")
    (newline 2)
    (insert TeX-esc (ConTeXt-environment-stop-name)
	    (nth 3 ConTeXt-project-structure-list))))


;;; Section blocks

(defvar ConTeXt-section-block-list ()
  "Calls ConTeXt-XX-section-list where XX is the current interface.")

(defun ConTeXt-section-block (section-block)
  "Insert the ConTeXt section block SECTION-BLOCK."
  (ConTeXt-environment-menu section-block))


;;; Sections

(defun ConTeXt-section (arg)
  "Insert a template for a ConTeXt section.
Determinate the type of section to be inserted, by the argument ARG.

If ARG is nil or missing, use the current level.
If ARG is a list (selected by \\[universal-argument]), go downward one level.
If ARG is negative, go up that many levels.
If ARG is positive or zero, use absolute level:

	0 : part
	1 : chapter
	2 : section
	3 : subsection
	4 : subsubsection
	5 : subsubsubsection

Or:

	0 : title
	1 : subject
	2 : subsubject
	3 : subsubsubject

The following variables can be set to customize:

`ConTeXt-section-hook'    Hooks to run when inserting a section.
`ConTeXt-section-ref'   Prefix to all section references."

  (interactive "*P")
  (let* ((val (prefix-numeric-value arg))
	 (level (cond ((null arg)
		       (ConTeXt-current-section))
		      ((listp arg)
		       (ConTeXt-down-section))
		      ((< val 0)
		       (ConTeXt-up-section (- val)))
		      (t val)))
	 (name (ConTeXt-section-name level))
	 (toc nil)
	 (title "")
	 (done-mark (make-marker)))
    (newline)
    (run-hooks 'ConTeXt-section-hook)
    (newline)
    (if (marker-position done-mark)
	(goto-char (marker-position done-mark)))
    (set-marker done-mark nil)))

;; LaTeX has a max function here, which makes no sense.
;; I think you want to insert a section that is max ConTeXt-largest-level
(defun ConTeXt-current-section ()
  "Return the level of the section that contain point.
See also `ConTeXt-section' for description of levels."
  (save-excursion
    (min (ConTeXt-largest-level)
	 (if (re-search-backward outline-regexp nil t)
	     (+ 1 (- (ConTeXt-outline-level) (ConTeXt-outline-offset)))
	   (ConTeXt-largest-level)))))

(defun ConTeXt-down-section ()
  "Return the value of a section one level under the current.
Tries to find what kind of section that have been used earlier in the
text, if this fail, it will just return one less than the current
section."
  (save-excursion
    (let ((current (ConTeXt-current-section))
	  (next nil)
	  (regexp outline-regexp))
      (if (not (re-search-backward regexp nil t))
	  (1+ current)
	(while (not next)
	  (cond
	   ((eq (ConTeXt-current-section) current)
	    (if (re-search-forward regexp nil t)
		(if (<= (setq next (ConTeXt-current-section)) current) ;Wow!
		    (setq next (1+ current)))
	      (setq next (1+ current))))
	   ((not (re-search-backward regexp nil t))
	    (setq next (1+ current)))))
	next))))

(defun ConTeXt-up-section (arg)
  "Return the value of the section ARG levels above this one."
  (save-excursion
    (if (zerop arg)
	(ConTeXt-current-section)
      (let ((current (ConTeXt-current-section)))
	(while (and (>= (ConTeXt-current-section) current)
		    (re-search-backward outline-regexp
					nil t)))
	(ConTeXt-up-section (1- arg))))))

(defvar ConTeXt-section-list ()
  "ConTeXt-XX-section-list where XX is the current interface.")

(defun ConTeXt-section-name (level)
  "Return the name of the section corresponding to LEVEL."
  (let ((entry (TeX-member level ConTeXt-section-list
			   (function (lambda (a b) (equal a (nth 1 b)))))))
    (if entry
	(nth 0 entry)
      nil)))

(defun ConTeXt-section-level (name)
  "Return the level of the section NAME."
  (let ((entry (TeX-member name ConTeXt-section-list
			   (function (lambda (a b) (equal a (nth 0 b)))))))

    (if entry
	(nth 1 entry)
      nil)))


;;; Section Hooks.

(defcustom ConTeXt-section-hook
  '(ConTeXt-section-heading
    ConTeXt-section-title
    ConTeXt-section-ref
    ConTeXt-section-section)
  "List of hooks to run when a new section is inserted.

The following variables are set before the hooks are run

level - numeric section level, see the documentation of `ConTeXt-section'.
name - name of the sectioning command, derived from `level'.
title - The title of the section, default to an empty string.
`done-mark' - Position of point afterwards, default nil (meaning end).

The following standard hook exist -

ConTeXt-section-heading: Query the user about the name of the
sectioning command.  Modifies `level' and `name'.

ConTeXt-section-title: Query the user about the title of the
section.  Modifies `title'.

ConTeXt-section-section: Insert ConTeXt section command according to
`name', `title', and `reference'.  If `title' is an empty string,
`done-mark' will be placed at the point they should be inserted.

ConTeXt-section-ref: Insert a reference for this section command.

To get a full featured `ConTeXt-section' command, insert

 (setq ConTeXt-section-hook
			 '(ConTeXt-section-heading
				 ConTeXt-section-title
				 ConTeXt-section-section
				 ConTeXt-section-ref))

in your .emacs file."
  :type 'hook
  :options
  '(ConTeXt-section-heading
    ConTeXt-section-title
    ConTeXt-section-ref
    ConTeXt-section-section))

(defun ConTeXt-section-heading ()
  "Hook to prompt for ConTeXt section name.
Insert this hook into `ConTeXt-section-hook' to allow the user to change
the name of the sectioning command inserted with `\\[ConTeXt-section]'."
  (let ((string (completing-read
		 (concat "Select level: (default " name ") ")
		 ConTeXt-section-list
		 nil nil nil)))
    ;; Update name
    (if (not (zerop (length string)))
	(setq name string))))

(defun ConTeXt-section-title ()
  "Hook to prompt for ConTeXt section title.
Insert this hook into `ConTeXt-section-hook' to allow the user to change
the title of the section inserted with `\\[ConTeXt-section]."
  (setq title (read-string "What title: ")))

(defun ConTeXt-section-section ()
  "Hook to insert ConTeXt section command into the file.
Insert this hook into `ConTeXt-section-hook' after those hooks which sets
the `name', `title', and `reference' variables, but before those hooks which
assumes the section already is inserted."
  (insert TeX-esc name)
  (cond ((null reference))
	((zerop (length reference))
	 (insert ConTeXt-optop)
	 (set-marker done-mark (point))
	 (insert ConTeXt-optcl))
	(t
	 (insert ConTeXt-optop reference ConTeXt-optcl)))
  (insert TeX-grop)
  (if (zerop (length title))
      (set-marker done-mark (point)))
  (insert title TeX-grcl)
  (newline)
  ;; If RefTeX is available, tell it that we've just made a new section
  (and (fboundp 'reftex-notice-new-section)
       (funcall (symbol-function 'reftex-notice-new-section))))

(defun ConTeXt-section-ref ()
  "Hook to insert a reference after the sectioning command.
Insert this hook into `ConTeXt-section-hook' to prompt for a label to be
inserted after the sectioning command."

  (setq reference (completing-read
		   (TeX-argument-prompt t nil
					"Comma separated list of references")
		   (LaTeX-label-list) nil nil))
  ;; No reference or empty string entered?
  (if (string-equal "" reference)
      (setq reference nil)))


;; Various
(defun TeX-ConTeXt-sentinel (process name)
  "Cleanup TeX output buffer after running ConTeXt."
  (cond ((TeX-TeX-sentinel-check process name))
	((save-excursion
	   ;; in a full ConTeXt run there will multiple texutil
	   ;; outputs. Just looking for "another run needed" would
	   ;; find the first occurence
	   (goto-char (point-max))
	   (re-search-backward "TeXUtil " nil t)
	   (re-search-forward "another run needed" nil t))
	 (message (concat "You should run ConTeXt again "
			  "to get references right, "
			  (TeX-current-pages)))
	 (setq TeX-command-next TeX-command-default))
	((re-search-forward "removed files :" nil t)
	 (message "sucessfully cleaned up"))
	((re-search-forward "^ TeX\\(Exec\\|Util\\)" nil t) ;; strange regexp --pg
	 (message (concat name ": successfully formatted "
			  (TeX-current-pages)))
	 (setq TeX-command-next TeX-command-Show))
	(t
	 (message (concat name ": problems after "
			  (TeX-current-pages)))
	 (setq TeX-command-next TeX-command-default))))


;;; Environments

(defgroup ConTeXt-environment nil
  "Environments in AUCTeX."
  :group 'ConTeXt-macro)

;; TODO: interface awareness
(defcustom ConTeXt-default-environment "itemize"
  "*The default environment when creating new ones with `ConTeXt-environment'."
  :group 'ConTeXt-environment
  :type 'string)
(make-variable-buffer-local 'ConTeXt-default-environment)

(TeX-auto-add-type "environment" "ConTeXt")

(fset 'ConTeXt-add-environments-auto
      (symbol-function 'ConTeXt-add-environments))
(defun ConTeXt-add-environments (&rest environments)
  "Add ENVIRONMENTS to the list of known environments."
  (apply 'ConTeXt-add-environments-auto environments)
  (setq ConTeXt-menu-changed t))

;; (defvar ConTeXt-environment-list ()
;; 	"ConTeXt-environment-list-XX where XX is the current interface.")

(defvar ConTeXt-environment-history nil)

(defun ConTeXt-environment-start-name ()
  "Return the \\start translated to the language in current interface."
  ;; it is "inizia", others are "start"
  (cond ((equal ConTeXt-current-interface "it")
	 "inizia")
	((member ConTeXt-current-interface ConTeXt-known-interfaces)
	 "start")
	(t
	 ;; this should not happen
	 (error "Unknown interface: " ConTeXt-current-interface))))

(defun ConTeXt-environment-stop-name ()
  "Return the \\stop translated to the language in current interface."
  ;; it is "termina", others are "stop"
  (cond ((equal ConTeXt-current-interface "it")
	 "termina")
	((member ConTeXt-current-interface ConTeXt-known-interfaces)
	 "stop")
	(t
	 ;; this should not happen
	 (error "Unknown interface: " ConTeXt-current-interface))))


(defun ConTeXt-environment (arg)
  "Make ConTeXt environment (\\start...-\\stop... pair).
With optional ARG, modify current environment."
  (interactive "*P")
  (let ((environment (
		      completing-read (concat "Environment type: (default "
					      (if (TeX-near-bobp)
						  "text"
						ConTeXt-default-environment)
					      ") ")
		      ConTeXt-environment-list
		      nil nil nil
		      'ConTeXt-environment-history)
		     ))
    ;; Get default
    (cond ((and (zerop (length environment))
		(TeX-near-bobp))
	   (setq environment "text"))
	  ((zerop (length environment))
	   (setq environment ConTeXt-default-environment))
	  (t
	   (setq ConTeXt-default-environment environment)))

    (let ((entry (assoc environment ConTeXt-environment-list)))
      (when (null entry)
	(ConTeXt-add-environments (list environment)))
      (if arg
	  (ConTeXt-modify-environment environment)
	(ConTeXt-environment-menu environment)))))

(defun ConTeXt-modify-environment (environment)
  "Modify current environment."
  (save-excursion
    (ConTeXt-find-matching-stop)
    (re-search-backward (concat (regexp-quote TeX-esc)
				(ConTeXt-environment-stop-name)
				" *\\([a-zA-Z]*\\)")
			(save-excursion (beginning-of-line 1) (point)))
    (replace-match
     (concat TeX-esc (ConTeXt-environment-stop-name) environment) t t)
    (beginning-of-line 1)
    (ConTeXt-find-matching-start)
    (re-search-forward (concat (regexp-quote TeX-esc)
			       (ConTeXt-environment-start-name)
			       " *\\([a-zA-Z]*\\)")
		       (save-excursion (end-of-line 1) (point)))
    (replace-match
     (concat TeX-esc (ConTeXt-environment-start-name) environment) t t)))


(defun ConTeXt-environment-menu (environment)
  "Insert ENVIRONMENT around point or region."
  (let ((entry (assoc environment ConTeXt-environment-list)))
    (cond ((not (and entry (nth 1 entry)))
	   (ConTeXt-insert-environment environment))
	  ((numberp (nth 1 entry))
	   (let ((count (nth 1 entry))
		 (args ""))
	     (while (> count 0)
	       (setq args (concat args TeX-grop TeX-grcl))
	       (setq count (- count 1)))
	     (ConTeXt-insert-environment environment args)))
	  ((stringp (nth 1 entry))
	   (let ((prompts (cdr entry))
		 (args ""))
	     (while prompts
	       (setq args (concat args
				  TeX-grop
				  (read-from-minibuffer
				   (concat (car prompts) ": "))
				  TeX-grcl))
	       (setq prompts (cdr prompts)))
	     (ConTeXt-insert-environment environment args)))
	  (t
	   (apply (nth 1 entry) environment (nthcdr 2 entry))))))

(defun ConTeXt-close-environment ()
  "Insert \\stop... to match the current environment."
  (interactive "*")
  (beginning-of-line)
  (let ((empty-line (looking-at "[ \t]*$")))
    (end-of-line)
    (if (not empty-line)
	(newline)))
  (insert TeX-esc (ConTeXt-environment-stop-name)
	  (ConTeXt-current-environment))
  ;; indent broken, so don't do it.
  ;;(indent-according-to-mode)
  (end-of-line)
  (newline))

(defun ConTeXt-insert-environment (environment &optional extra)
  "Insert ENVIRONMENT, with optional argument EXTRA."
  (if (and (TeX-active-mark)
	   (not (eq (mark) (point))))
      (save-excursion
	(if (< (mark) (point))
	    (exchange-point-and-mark))
	(insert TeX-esc (ConTeXt-environment-start-name) environment)
	(newline)
	(forward-line -1)
	(indent-according-to-mode)
	(if extra (insert extra))
	(goto-char (mark))
	(or (TeX-looking-at-backward "^[ \t]*")
	    (newline))
	(insert TeX-esc (ConTeXt-environment-stop-name) environment)
	(newline)
	(forward-line -1)
	(indent-according-to-mode)
	;;(goto-char (point))
	)
    (or (TeX-looking-at-backward "^[ \t]*")
	(newline))
    (insert TeX-esc (ConTeXt-environment-start-name) environment)
    (indent-according-to-mode)
    (if extra (insert extra))
    (end-of-line)
    (newline-and-indent)
    (newline)
    (insert TeX-esc (ConTeXt-environment-stop-name) environment)
    (or (looking-at "[ \t]*$")
	(save-excursion (newline-and-indent)))
    (indent-according-to-mode)
    (end-of-line 0)))


;; with the following we can call a function on an environment. Say
;; you have metapost stuff within your TeX file, go to the environment
;; and run ConTeXt-work-on-environment (suggested Key: C-c !). AUCTeX
;; sees that you are inside e.g. \startMPpage....\stopMPpage and
;; looks in ConTeXt-environment-helper for a function to be called.

;; % so pressing C-c ! inside the following ...
;;\startuseMPgraphic{Logo}{Scale}
;; % Top rectangle
;; filldraw (0,0)--(2cm,0)--(2cm,1cm)--(0,1cm)--cycle withcolor blue ;
;; % Bottom black rectangle
;; drawfill (0,0)--(2cm,0)--(2cm,-1cm)--(0,-1cm)--cycle withcolor black;
;; % White Text
;; draw btex \bf AB etex withcolor white ;
;; % resize to size
;; currentpicture := currentpicture scaled \MPvar{Scale} ;
;; \stopuseMPgraphic

;; % ...should give you a "new buffer" (currently narrowed to region
;; % and switched to metapost-mode and recursive-edit)

;; % Top rectangle
;; filldraw (0,0)--(2cm,0)--(2cm,1cm)--(0,1cm)--cycle withcolor blue ;
;; % Bottom black rectangle
;; drawfill (0,0)--(2cm,0)--(2cm,-1cm)--(0,-1cm)--cycle withcolor black;
;; % White Text
;; draw btex \bf AB etex withcolor white ;
;; % resize to size
;; currentpicture := currentpicture scaled \MPvar{Scale} ;


(defvar ConTeXt-environment-helper
  '(("useMPgraphic" . ConTeXt-mp-region)
    ("MPpage" . ConTeXt-mp-region))
  "Alist that holds functions to call for working on regions.
An entry looks like: (\"environment\" . function)")

(defun ConTeXt-mp-region ()
  "Edit region in `metapost-mode'."
  (ConTeXt-mark-environment t)
  (narrow-to-region (mark) (point))
  (metapost-mode)
  (message "Type `M-x exit-recursive-edit' to get back")
  (recursive-edit)
  (context-mode)
  (widen))

;; find smarter name. Suggestions welcome
(defun ConTeXt-work-on-environment ()
  "Takes current environment and does something on it (todo: documentation)."
  (interactive)
  (let ((fun (cdr (assoc (ConTeXt-current-environment)
			 ConTeXt-environment-helper))))
    (when (functionp fun)
      (funcall fun))))

(defun ConTeXt-current-environment ()
  "Return the name of the current environment."
  ;; don't make this interactive.
  (let ((beg))
    (save-excursion
      (ConTeXt-last-unended-start)
      (setq beg (+ (point) (length (ConTeXt-environment-start-name)) 1))
      (goto-char (match-end 0))
      (skip-chars-forward "a-zA-Z")
      (buffer-substring beg (point)))))

(defun ConTeXt-last-unended-start ()
  "Leave point at the beginning of the last `\\start...' that is unstopped looking from the current cursor."
  (while (and (re-search-backward "\\\\start[a-zA-Z]*\\|\\\\stop[a-zA-Z]*")
              (looking-at "\\\\stop[a-zA-Z]*"))
    (ConTeXt-last-unended-start)))

(defun ConTeXt-mark-environment (&optional inner)
  "Set mark to end of current environment (\\start...-\\stop...) and
point to the matching begin.
If optional INNER is not nil, include \\start... and \\stop, otherwise only
the contents."
  (interactive)
  (let ((cur (point)))
    (ConTeXt-find-matching-stop inner)
    (set-mark (point))
    (goto-char cur)
    (ConTeXt-find-matching-start inner)
    (TeX-activate-region)))

(defun ConTeXt-find-matching-stop (&optional inner)
  "Find end of current \\start...\\stop-Pair.
If INNER is non-nil, go to the point just past before
\\stop... macro.  Otherwise goto the point just past \\stop..."
  (interactive)
  (let ((regexp (concat (regexp-quote TeX-esc)
			"\\("
			(ConTeXt-environment-start-name)
			"\\|"
			(ConTeXt-environment-stop-name)
			"\\)"
			))
	(level 1)
	(pos))
    ;;jump over the \start... when at the beginning of it.
    (when (looking-at (concat (regexp-quote TeX-esc)
			      (ConTeXt-environment-start-name)))
      (re-search-forward regexp nil t))
    (while (and (> level 0)
		(re-search-forward regexp nil t)
		(goto-char (1- (match-beginning 1)))
		(cond ((looking-at (concat (regexp-quote TeX-esc)
					   (ConTeXt-environment-start-name)))
		       (re-search-forward regexp nil t)
		       (setq level (1+ level)))
		      ((looking-at (concat (regexp-quote TeX-esc)
					   (ConTeXt-environment-stop-name)))
		       (re-search-forward regexp nil t)
		       (setq level (1- level))))))
    ;; now we have to look if we want to start behind the \start... macro
    (if inner
	(beginning-of-line)
      (skip-chars-forward "a-zA-Z"))))

(defun ConTeXt-find-matching-start (&optional inner)
  "Find beginning of current \\start...\\stop-Pair.
If INNER is non-nil, go to the point just past the \\start... macro."
  (interactive)
  (let ((regexp (concat (regexp-quote TeX-esc)
			"\\("
			(ConTeXt-environment-start-name)
			"\\|"
			(ConTeXt-environment-stop-name)
			"\\)"
			))
	(level 1)
	(pos))
    (while (and (> level 0)
		(re-search-backward regexp nil t)
		(cond ((looking-at (concat (regexp-quote TeX-esc)
					   (ConTeXt-environment-stop-name)))
		       (setq level (1+ level)))
		      ((looking-at (concat (regexp-quote TeX-esc)
					   (ConTeXt-environment-start-name)))
		       (setq level (1- level))))))
    ;; now we have to look if we want to start behind the \start... macro
    (when inner
      ;; \startfoo can have 0 or more {} and [] pairs. I assume that
      ;; skipping all those parens will be smart enough. It fails when
      ;; the first part in the \start-\stop-environment is { or [, like
      ;; in \startquotation   {\em important} \stopquotation. There is
      ;; yet another pitfall: \startsetups SomeSetup foo bar
      ;; \stopsetups will use SomeSetup as the argument and the
      ;; environment
      (skip-chars-forward "\\\\a-zA-Z")
      (save-excursion
	(while (progn
		 (skip-chars-forward "\t\n ")
		 (forward-comment 1)
		 (skip-chars-forward "\t\n ")
		 (looking-at "\\s\("))
	  (forward-list 1)
	  (setq pos (point))))
      (when pos
	(goto-char pos))
      (unless (bolp)
	(forward-line)))))

;;; items

(defun ConTeXt-insert-item ()
  "Insert a new item."
  (interactive "*")
  (or (TeX-looking-at-backward "^[ \t]*")
      (newline))
  (TeX-insert-macro "item")
  (indent-according-to-mode))


;;; Macro Argument Hooks

(defun ConTeXt-optional-argument-insert (arg &optional prefix)
  "Insert ARG surrounded by square brackets."
  (insert ConTeXt-optop)
  (insert arg)
  (insert ConTeXt-optcl))

(defun ConTeXt-required-argument-insert (arg &optional prefix)
  "Insert ARG surrounded by curly braces."
  (insert TeX-grop)
  (insert arg)
  (insert TeX-grcl))

(defun ConTeXt-argument-insert (arg optional &optional prefix)
  "Insert ARG surrounded by curly braces.

If OPTIONAL, only insert it if not empty, and then use square brackets."
  (if optional
      (if
	  (not (string-equal arg ""))
	  (ConTeXt-optional-argument-insert arg prefix))
    (ConTeXt-required-argument-insert arg prefix)))

(defun ConTeXt-arg-ref (optional &optional prompt definition)
  "Prompt for a reference completing with known references."
  (let ((ref (completing-read (TeX-argument-prompt optional prompt "ref")
			      (LaTeX-label-list))))
    (if (and definition (not (string-equal "" ref)))
	(LaTeX-add-labels ref))
    (ConTeXt-argument-insert ref optional)))

(defun ConTeXt-arg-define-ref (&optional prompt)
  "Prompt for an optional reference completing with known references."
  (ConTeXt-arg-ref t prompt t))

(defun ConTeXt-arg-setup (optional &optional prompt)
  "Prompt for setup arguments."
  (let ((setup (read-from-minibuffer
		(TeX-argument-prompt optional prompt "setup"))))
    (ConTeXt-argument-insert setup t)))


;; paragraph (re)-formatting

(defvar ConTeXt-item-list ()
  "List of macro's considered items.")

(defvar ConTeXt-extra-paragraph-commands
  '("crlf" "par")
  "List of ConTeXt macros that should have their own line besides the section(-block) commands.")

(defun ConTeXt-paragraph-commands-regexp ()
  "Return a regexp matching macros that should have their own line."
  (concat
   (regexp-quote TeX-esc) "\\("
   "[][]\\|"  ; display math delimitors (is this applicable to ConTeXt??)
   (ConTeXt-environment-start-name) "\\|"
   (ConTeXt-environment-stop-name) "\\|"
   (mapconcat 'car ConTeXt-section-list "\\b\\|") "\\b\\|"
   (mapconcat 'identity ConTeXt-extra-paragraph-commands "\\b\\|")
   "\\b\\|"
   (mapconcat 'identity ConTeXt-item-list "\\b\\|") "\\b\\)"))


;; Outline support

(defun ConTeXt-environment-full-start-name (environment)
  "Return the ConTeXt macro name that starts ENVIRONMENT.
It is interface aware"
  (concat (ConTeXt-environment-start-name) environment))

(defun ConTeXt-outline-regexp (&optional anywhere)
  "Return regexp for ConTeXt section blocks and sections.

If optional argument ANYWHERE is not nil, do not require that the
header is at the start of a line."
  (concat
   (if anywhere "" "^")
   "[ \t]*"
   (regexp-quote TeX-esc)
   "\\("
   (mapconcat 'ConTeXt-environment-full-start-name ConTeXt-section-block-list "\\|") "\\|"
   (mapconcat 'car ConTeXt-section-list "\\|")
   "\\)\\b"
   (if TeX-outline-extra
       "\\|"
     "")
   (mapconcat 'car TeX-outline-extra "\\|")
   "\\|" (ConTeXt-header-end) "\\b"
   "\\|" (ConTeXt-trailer-start) "\\b"))

(defvar ConTeXt-text "Name of ConTeXt macro that begins the text body.")

(defun ConTeXt-header-end ()
  "Default end of header marker for ConTeXt documents."
  (concat
   (regexp-quote TeX-esc)
   (ConTeXt-environment-start-name)
   ConTeXt-text))

(defun ConTeXt-trailer-start ()
  "Default start of trailer marker for ConTeXt documents."
  (concat
   (regexp-quote TeX-esc)
   (ConTeXt-environment-stop-name)
   ConTeXt-text))

(defun ConTeXt-outline-offset ()
  "Offset to add to `ConTeXt-section-list' levels to get outline level."
  (- 4 (ConTeXt-largest-level)))

(defun ConTeXt-start-environment-regexp (list)
  "Regular expression that matches a start of all environments mentioned in LIST."
  (concat
   "start\\("
   (mapconcat 'identity list "\\|")
   "\\)\\b"))

;; The top headings are \starttext, \startfrontmatter, \startbodymatter etc.
;; \part, \chapter etc. are children of that.
(defun ConTeXt-outline-level ()
  "Find the level of current outline heading in an ConTeXt document."
  (cond ((looking-at (concat (ConTeXt-header-end) "\\b")) 1)
	((looking-at (concat (ConTeXt-trailer-start) "\\b")) 1)
	((TeX-look-at TeX-outline-extra)
	 (max 1 (+ (TeX-look-at TeX-outline-extra)
		   (ConTeXt-outline-offset))))
	(t
	 (save-excursion
	   (skip-chars-forward " \t")
	   (forward-char 1)
	   (cond ((looking-at (ConTeXt-start-environment-regexp
			       ConTeXt-section-block-list)) 1)
		 ((TeX-look-at ConTeXt-section-list)
		  (max 1 (+ (TeX-look-at ConTeXt-section-list)
			    (ConTeXt-outline-offset))))
		 (t
		  (error "Unrecognized header")))))))


;;; Fonts

(defcustom ConTeXt-font-list '((?\C-b "{\\bf " "}")
			   (?\C-c "{\\sc " "}")
			   (?\C-e "{\\em " "}")
			   (?\C-i "{\\it " "}")
			   (?\C-r "{\\rm " "}")
			   (?\C-s "{\\sl " "}")
			   (?\C-t "{\\tt " "}")
			   (?\C-d "" "" t))
  "List of fonts used by `TeX-font'.

Each entry is a list.
The first element is the key to activate the font.
The second element is the string to insert before point, and the third
element is the string to insert after point.
If the fourth and fifth element are strings, they specify the prefix and
suffix to be used in math mode.
An optional fourth (or sixth) element means always replace if t."
  :group 'TeX-macro
  :type '(repeat
	   (group
	    :value (?\C-a "" "")
	    (character :tag "Key")
	    (string :tag "Prefix")
	    (string :tag "Suffix")
	    (option (group
		     :inline t
		     (string :tag "Math Prefix")
		     (string :tag "Math Suffix")))
	    (option (sexp :format "Replace\n" :value t)))))


;; Imenu support

(defun ConTeXt-outline-name ()
  "Guess a name for the current header line."
  (save-excursion
    (if (re-search-forward "{\\([^\}]*\\)}" (point-at-eol) t)
	(match-string 1)
      (buffer-substring-no-properties (point) (point-at-eol)))))

;; This imenu also includes commented out chapters. Perhaps a feature
;; for LaTeX, not sure we want or need that for ConTeXt.

(defun ConTeXt-imenu-create-index-function ()
  "Imenu support function for ConTeXt."
  (TeX-update-style)
  (let (entries level (regexp (ConTeXt-outline-regexp)))
    (goto-char (point-max))
    (while (re-search-backward regexp nil t)
      (let* ((name (ConTeXt-outline-name))
	     (level (make-string (1- (ConTeXt-outline-level)) ?\ ))
	     (label (concat level level name))
	     (mark (make-marker)))
	(set-marker mark (point))
	(set-text-properties 0 (length label) nil label)
	(setq entries (cons (cons label mark) entries))))
    entries))


;; Indentation, copied from Berend's context mode.
;; TODO: doesn't work great.

(defvar ConTeXt-indent-allhanging t)
(defvar ConTeXt-indent-arg 2)
(defvar ConTeXt-indent-basic 2)
(defvar ConTeXt-indent-item ConTeXt-indent-basic)
(defvar ConTeXt-indent-item-re "\\\\\\\(item\\|setup[a-zA-Z]*\\)\\>")

(defvar ConTeXt-indent-syntax-table (make-syntax-table TeX-mode-syntax-table)
  "Syntax table used while computing indentation.")

(progn
  (modify-syntax-entry ?$ "." ConTeXt-indent-syntax-table)
  (modify-syntax-entry ?\( "." ConTeXt-indent-syntax-table)
  (modify-syntax-entry ?\) "." ConTeXt-indent-syntax-table))

(defun ConTeXt-indent-line (&optional arg)
  (with-syntax-table ConTeXt-indent-syntax-table
    ;; TODO: Rather than ignore $, we should try to be more clever about it.
    (let ((indent
	   (save-excursion
	     (beginning-of-line)
	     (ConTeXt-find-indent))))
      (if (< indent 0) (setq indent 0))
      (if (<= (current-column) (current-indentation))
	  (indent-line-to indent)
	(save-excursion (indent-line-to indent))))))

(defun ConTeXt-find-indent (&optional virtual)
  "Find the proper indentation of text after point.
VIRTUAL if non-nil indicates that we're only trying to find the indentation
	in order to determine the indentation of something else.
There might be text before point."
  (save-excursion
    (skip-chars-forward " \t")
    (or
     ;; Trust the current indentation, if such info is applicable.
     (and virtual (>= (current-indentation) (current-column))
	  (current-indentation))
     ;; Put leading close-paren where the matching open brace would be.
     (and (eq (char-syntax (char-after)) ?\))
	  (ignore-errors
	   (save-excursion
	     (skip-syntax-forward " )")
	     (backward-sexp 1)
	     (ConTeXt-find-indent 'virtual))))
     ;; Default (maybe an argument)
     (let ((pos (point))
	   (char (char-after))
	   ;; Outdent \item if necessary.
	   (indent (if (looking-at ConTeXt-indent-item-re)
		       (- ConTeXt-indent-item) 0))
	   up-list-pos)
       ;; Find the previous point which determines our current indentation.
       (condition-case err
	   (progn
	     (backward-sexp 1)
	     (while (> (current-column) (current-indentation))
	       (backward-sexp 1)))
	 (scan-error
	  (setq up-list-pos (nth 2 err))))
       (cond
	((= (point-min) pos) 0)	 ; We're really just indenting the first line.
	((integerp up-list-pos)
	 ;; Have to indent relative to the open-paren.
	 (goto-char up-list-pos)
	 (if (and (not ConTeXt-indent-allhanging)
		  (> pos (progn (down-list 1)
				(forward-comment (point-max))
				(point))))
	     ;; Align with the first element after the open-paren.
	     (current-column)
	   ;; We're the first element after a hanging brace.
	   (goto-char up-list-pos)
	   (+ indent ConTeXt-indent-basic (ConTeXt-find-indent 'virtual))))
	;; We're now at the "beginning" of a line.
	((not (and (not virtual) (eq (char-after) ?\\)))
	 ;; Nothing particular here: just keep the same indentation.
	 (+ indent (current-column)))
	;; We're now looking at a macro call.
	((looking-at ConTeXt-indent-item-re)
	 ;; Indenting relative to an item, have to re-add the outdenting.
	 (+ indent (current-column) ConTeXt-indent-item))
	(t
	 (let ((col (current-column)))
	   (if (not (eq (char-syntax char) ?\())
	       ;; If the first char was not an open-paren, there's
	       ;; a risk that this is really not an argument to the
	       ;; macro at all.
	       (+ indent col)
	     (forward-sexp 1)
	     (if (< (line-end-position)
		    (save-excursion (forward-comment (point-max))
				    (point)))
		 ;; we're indenting the first argument.
		 (min (current-column) (+ ConTeXt-indent-arg col))
	       (skip-syntax-forward " ")
	       (current-column))))))))))


;; XML inside ConTeXt support

(defun ConTeXt-last-unended-start-xml ()
  "Leave point at the beginning of the last `tag' that is unstopped."
  (while (and (re-search-backward "<[_A-Za-z][-:._A-Za-z0-9]*\\([ \t\r\n]\\|[_A-Za-z][-:._A-Za-z0-9]*\=\"[^\"]*\"\\)*>\\|</[_A-Za-z][-:_A-Za-z0-9]*>")
	      (looking-at "</[_A-Za-z][-:._A-Za-z0-9]*>"))
    (ConTeXt-last-unended-start-xml)))

(defun ConTeXt-close-xml-tag ()
  "Create an </...> to match the last unclosed <...>.  Not fool-proof."
  (interactive "*")
  (let ((new-line-needed (bolp)) text indentation)
    (save-excursion
      (condition-case nil
	  (ConTeXt-last-unended-start-xml)
	(error (error "Couldn't find unended XML tag")))
      (setq indentation (current-column))
      (re-search-forward "<\\([_A-Za-z][-:._A-Za-z0-9]*\\)")
      (setq text (buffer-substring (match-beginning 1) (match-end 1))))
    (indent-to indentation)
    (insert "</" text ">")
    (if new-line-needed (insert ?\n))))


;; Key bindings

(defvar ConTeXt-mode-map
  (let ((map (make-sparse-keymap)))
    (set-keymap-parent map TeX-mode-map)

    (define-key map "\e\C-a"  'ConTeXt-find-matching-start)
    (define-key map "\e\C-e"  'ConTeXt-find-matching-stop)
    ;; likely to change in the future
    (define-key map "\C-c!"    'ConTeXt-work-on-environment)
    (define-key map "\C-c\C-e" 'ConTeXt-environment)
    (define-key map "\C-c\n"   'ConTeXt-insert-item)
    (or (key-binding "\e\r")
	(define-key map "\e\r"    'ConTeXt-insert-item)) ;*** Alias
    (define-key map "\C-c]" 'ConTeXt-close-environment)
    (define-key map "\C-c\C-s" 'ConTeXt-section)
    ;; XML in ConTeXt support
    (define-key map "\C-c/" 'ConTeXt-close-xml-tag)
    map)
  "Keymap used in `ConTeXt-mode'.")


;;; Menu building

;; functions to create menu entries

;; ConTeXt \start... \stop... pairs
;; (Choose a different name than the one in LaTeX mode.  Otherwise the
;; contents of the "Insert Environment" and "Change Environment" menus
;; will not be updated correctly upon loading and switching between
;; LaTeX and ConTeXt files.  AFAICS this is due to a bug in
;; easymenu.el not returning the correct keymap when
;; `easy-menu-change' (and therefore `easy-menu-get-map') is called.
;; It just sees an entry with a matching name and returns this first
;; match.)
(defvar ConTeXt-environment-menu-name "Insert Environment   (C-c C-e)")

(defun ConTeXt-environment-menu-entry (entry)
  "Create an entry for the environment menu."
  (vector (car entry) (list 'ConTeXt-environment-menu (car entry)) t))

(defvar ConTeXt-environment-modify-menu-name "Change Environment   (C-u C-c C-e)")

(defun ConTeXt-environment-modify-menu-entry (entry)
  "Create an entry for the change environment menu."
  (vector (car entry) (list 'ConTeXt-modify-environment (car entry)) t))

;; ConTeXt setup macros
(defvar ConTeXt-setup-menu-name "Setup")

(defun ConTeXt-setup-menu-entry (entry)
  "Create an entry for the setup menu."
  (vector entry (list 'ConTeXt-setup-menu entry)))

(defun ConTeXt-setup-menu (setup)
  "Insert SETUP from menu."
  (ConTeXt-insert-setup setup))


;; meta-structure project structure menu entries

(defvar ConTeXt-project-structure-menu-name "Project Structure")

(defun ConTeXt-project-structure-menu (project-structure)
  "Insert project structure from menu."
  (ConTeXt-project-structure
   (let ((l ConTeXt-project-structure-list))
     (- (length l) (length (member project-structure l))))))

(defun ConTeXt-project-structure-menu-entry (entry)
  "Create an ENTRY for the project structure menu."
  (vector entry (list 'ConTeXt-project-structure-menu entry)))


;; meta-structure section blocks menu entries

(defvar ConTeXt-section-block-menu-name "Section Block")

(defun ConTeXt-section-block-menu (section-block)
  "Insert section block from menu."
  (ConTeXt-section-block section-block))

(defun ConTeXt-section-block-menu-entry (entry)
  "Create an ENTRY for the section block menu."
  (vector entry (list 'ConTeXt-section-block-menu entry)))


;; section menu entries

(defvar ConTeXt-section-menu-name "Section  (C-c C-s)")

(defun ConTeXt-section-enable-symbol (level)
  "Symbol used to enable section LEVEL in the menu bar."
  (intern (concat "ConTeXt-section-" (int-to-string level) "-enable")))

(defun ConTeXt-section-enable (entry)
  "Enable or disable section ENTRY from `ConTeXt-section-list'."
  (let ((level (nth 1 entry)))
    (set (ConTeXt-section-enable-symbol level)
	 (>= level ConTeXt-largest-level))))

(defun ConTeXt-section-menu (level)
  "Insert section from menu."
  (let ((ConTeXt-section-hook (delq 'ConTeXt-section-heading
				    (copy-sequence ConTeXt-section-hook))))
    (ConTeXt-section level)))

(defun ConTeXt-section-menu-entry (entry)
  "Create an ENTRY for the section menu."
  (let ((enable (ConTeXt-section-enable-symbol (nth 1 entry))))
    (set enable t)
    (vector (car entry) (list 'ConTeXt-section-menu (nth 1 entry)) enable)))


;; etexshow support

(defun ConTeXt-etexshow ()
  "Call etexshow, if available, to show the definition of a ConText macro."
  (interactive)
  (if (fboundp 'etexshow)
      (let ()
	(require 'etexshow)
	(funcall (symbol-function 'etexshow-cmd)))
    (error "etexshow is not installed.  Get it from http://levana.de/emacs/")))

;; menu itself

(easy-menu-define ConTeXt-mode-command-menu
  ConTeXt-mode-map
  "Command menu used in ConTeXt mode."
  (TeX-mode-specific-command-menu 'context-mode))

;; it seems the menu is evaluated at compile/load-time
;; we don't have ConTeXt-current-interface at that time
;; so make sure to do updates based on that variable in
;; ConTeXt-menu-update
(easy-menu-define ConTeXt-mode-menu
  ConTeXt-mode-map
  "Menu used in ConTeXt mode."
  (TeX-menu-with-help
   `("ConTeXt"
     (,ConTeXt-project-structure-menu-name)
     (,ConTeXt-section-block-menu-name)
     (,ConTeXt-section-menu-name)
     ["Add Table of Contents to Emacs Menu" (imenu-add-to-menubar "TOC") t]
     "-"
     ["Macro ..." TeX-insert-macro
      :help "Insert a macro and possibly arguments"]
     ["Complete" TeX-complete-symbol
      :help "Complete the current macro or environment name"]
     ["Show ConTeXt Macro Definition" ConTeXt-etexshow]
     "-"
     (,ConTeXt-environment-menu-name)
     (,ConTeXt-environment-modify-menu-name)
     ["Item" ConTeXt-insert-item
      :help "Insert a new \\item into current environment"]
     (,ConTeXt-setup-menu-name)
     "-"
     ("Insert Font"
      ["Emphasize"  (TeX-font nil ?\C-e) :keys "C-c C-f C-e"]
      ["Bold"       (TeX-font nil ?\C-b) :keys "C-c C-f C-b"]
      ["Typewriter" (TeX-font nil ?\C-t) :keys "C-c C-f C-t"]
      ["Small Caps" (TeX-font nil ?\C-c) :keys "C-c C-f C-c"]
      ["Sans Serif" (TeX-font nil ?\C-f) :keys "C-c C-f C-f"]
      ["Italic"     (TeX-font nil ?\C-i) :keys "C-c C-f C-i"]
      ["Slanted"    (TeX-font nil ?\C-s) :keys "C-c C-f C-s"]
      ["Roman"      (TeX-font nil ?\C-r) :keys "C-c C-f C-r"]
      ["Calligraphic" (TeX-font nil ?\C-a) :keys "C-c C-f C-a"])
     ("Replace Font"
      ["Emphasize"  (TeX-font t ?\C-e) :keys "C-u C-c C-f C-e"]
      ["Bold"       (TeX-font t ?\C-b) :keys "C-u C-c C-f C-b"]
      ["Typewriter" (TeX-font t ?\C-t) :keys "C-u C-c C-f C-t"]
      ["Small Caps" (TeX-font t ?\C-c) :keys "C-u C-c C-f C-c"]
      ["Sans Serif" (TeX-font t ?\C-f) :keys "C-u C-c C-f C-f"]
      ["Italic"     (TeX-font t ?\C-i) :keys "C-u C-c C-f C-i"]
      ["Slanted"    (TeX-font t ?\C-s) :keys "C-u C-c C-f C-s"]
      ["Roman"      (TeX-font t ?\C-r) :keys "C-u C-c C-f C-r"]
      ["Calligraphic" (TeX-font t ?\C-a) :keys "C-u C-c C-f C-a"])
     ["Delete Font" (TeX-font t ?\C-d) :keys "C-c C-f C-d"]
     "-"
     ["Comment or Uncomment Region"
      TeX-comment-or-uncomment-region
      :help "Make the selected region outcommented or active again"]
     ["Comment or Uncomment Paragraph"
      TeX-comment-or-uncomment-paragraph
      :help "Make the current paragraph outcommented or active again"]
     ,TeX-fold-menu
     "-" . ,TeX-common-menu-entries)))

(defun ConTeXt-menu-update (&optional menu)
  "Update entries on AUCTeX menu."
  (or (not (memq major-mode '(context-mode)))
      (null ConTeXt-menu-changed)
      (not (fboundp 'easy-menu-change))
      (progn
	(TeX-update-style)
	(setq ConTeXt-menu-changed nil)
	(message "Updating section menu...")
	(mapcar 'ConTeXt-section-enable ConTeXt-section-list)
	(message "Updating environment menu...")
	(easy-menu-change '("ConTeXt") ConTeXt-environment-menu-name
			  (LaTeX-split-long-menu
			   (mapcar 'ConTeXt-environment-menu-entry
				   (ConTeXt-environment-list))))
	(message "Updating modify environment menu...")
	(easy-menu-change '("ConTeXt") ConTeXt-environment-modify-menu-name
			  (LaTeX-split-long-menu
			   (mapcar 'ConTeXt-environment-modify-menu-entry
				   (ConTeXt-environment-list))))
	(message "Updating setup menu...")
	(easy-menu-change '("ConTeXt") ConTeXt-setup-menu-name
			  (LaTeX-split-long-menu
			   (mapcar 'ConTeXt-setup-menu-entry
				   ConTeXt-setup-list)))
	(message "Updating project structure menu...")
	(easy-menu-change '("ConTeXt") ConTeXt-project-structure-menu-name
			  (LaTeX-split-long-menu
			   (mapcar 'ConTeXt-project-structure-menu-entry
				   ConTeXt-project-structure-list)))
	(message "Updating section block menu...")
	(easy-menu-change '("ConTeXt") ConTeXt-section-block-menu-name
			  (LaTeX-split-long-menu
			   (mapcar 'ConTeXt-section-block-menu-entry
				   ConTeXt-section-block-list)))
	(message "Updating section menu...")
	(easy-menu-change '("ConTeXt") ConTeXt-section-menu-name
			  (LaTeX-split-long-menu
			   (mapcar 'ConTeXt-section-menu-entry
				   ConTeXt-section-list)))
	(message "Updating...done")
	(and menu (easy-menu-return-item ConTeXt-mode-menu menu))
	)))

;;; Option expander

(defun ConTeXt-expand-options ()
  "Expand options for texexec command."
  (concat
   (and TeX-PDF-mode "--pdf ")
   (if TeX-Omega-mode
       (and ConTeXt-Omega-engine
	    (format "--tex=%s " ConTeXt-Omega-engine))
     (and ConTeXt-engine
	  (format "--tex=%s " ConTeXt-engine)))
   (unless (eq ConTeXt-current-interface "en")
     (format "--interface=%s " ConTeXt-current-interface))
   (if TeX-source-specials-mode
       (format
	"--passon=\"%s\" "
	(concat
	 TeX-source-specials-tex-flags
	 (unless TeX-interactive-mode
	   " -interaction=nonstopmode")))
     (unless TeX-interactive-mode
       "--passon=\"-interaction=nonstopmode\" "))))

;;; Mode

;; ConTeXt variables that are interface aware
;; They are mapped to interface specific variables

(defvar ConTeXt-language-variable-list
  '(ConTeXt-setup-list ConTeXt-project-structure-list
		       ConTeXt-section-block-list ConTeXt-section-list
		       ConTeXt-text ConTeXt-item-list))


(defun ConTeXt-mode-common-initialization ()
  "Initialization code that is common for all ConTeXt interfaces."
  (plain-TeX-common-initialization)
  (setq major-mode 'context-mode)

  ;; Make language specific variables buffer local
  (dolist (symbol ConTeXt-language-variable-list)
    (make-variable-buffer-local symbol))

  (require (intern (concat "context-" ConTeXt-current-interface)))
  (dolist (symbol ConTeXt-language-variable-list)
    (set symbol (symbol-value (intern (concat (symbol-name symbol) "-"
					      ConTeXt-current-interface)))))


  ;; What's the deepest level at we can collapse a document?
  ;; set only if user has not set it. Need to be set before menu is created.
  ;; level 2 is "section"
  (or ConTeXt-largest-level
      (setq ConTeXt-largest-level 2))

  ;; keybindings
  (use-local-map ConTeXt-mode-map)

  ;; Indenting
  (set (make-local-variable 'indent-line-function) 'ConTeXt-indent-line)
  (set (make-local-variable 'fill-indent-according-to-mode) t)

  ;; Paragraph formatting
  (set (make-local-variable 'LaTeX-syntactic-comments) nil)
  (set (make-local-variable 'LaTeX-paragraph-commands-regexp)
       (ConTeXt-paragraph-commands-regexp))
  (set (make-local-variable 'paragraph-ignore-fill-prefix) t)
  (set (make-local-variable 'fill-paragraph-function) 'LaTeX-fill-paragraph)
  (set (make-local-variable 'adaptive-fill-mode) nil)
  (setq paragraph-start
	(concat
	 "[ \t]*\\("
	 (ConTeXt-paragraph-commands-regexp) "\\|"
	 "\\$\\$\\|" ; Plain TeX display math
	 "$\\)"))
  (setq paragraph-separate
	(concat
	 "[ \t]*\\("
	 "\\$\\$" ; Plain TeX display math
	 "\\|$\\)"))

  ;; Keybindings and menu
  (use-local-map ConTeXt-mode-map)
  (easy-menu-add ConTeXt-mode-menu ConTeXt-mode-map)
  (easy-menu-add ConTeXt-mode-command-menu ConTeXt-mode-map)
  (setq ConTeXt-menu-changed t)

  (if (= emacs-major-version 20)
      (make-local-hook 'activate-menubar-hook))
  (add-hook 'activate-menubar-hook 'ConTeXt-menu-update nil t)

  ;; Outline support
  (require 'outline)
  (set (make-local-variable 'outline-level) 'ConTeXt-outline-level)
  (set (make-local-variable 'outline-regexp) (ConTeXt-outline-regexp t))
  ;;(make-local-variable 'outline-heading-end-regexp)
  (setq TeX-header-end (ConTeXt-header-end)
	TeX-trailer-start (ConTeXt-trailer-start))

  ;; font switch support
  (set (make-local-variable 'TeX-font-list) ConTeXt-font-list)

  ;; imenu support
  (set (make-local-variable 'imenu-create-index-function)
       'ConTeXt-imenu-create-index-function)

  ;; run hooks
  (setq TeX-command-default "ConTeXt")
  (setq TeX-sentinel-default-function 'TeX-ConTeXt-sentinel)
  (run-hooks 'text-mode-hook 'TeX-mode-hook 'ConTeXt-mode-hook))

(defun context-guess-current-interface ()
  "Guess what ConTeXt interface the current buffer is using."
  (save-excursion
    (goto-char (point-min))
    (setq ConTeXt-current-interface
	  (cond ((re-search-forward "%.*?interface=en" (+ 512 (point)) t)
		 "en")
		((re-search-forward "%.*?interface=nl" (+ 512 (point)) t)
		 "nl")
		((re-search-forward "\\\\starttext" (+ 1024 (point)) t)
		 "en")
		((re-search-forward "\\\\starttekst" (+ 1024 (point)) t)
		 "nl")
		(t
		 ConTeXt-default-interface)))))

(TeX-defun context-mode ()
  "Major mode in %s for editing ConTeXt files.

Special commands:
\\{ConTeXt-mode-map}

Entering `context-mode' calls the value of `text-mode-hook',
then the value of `TeX-mode-hook', and then the value
of context-mode-hook."
  (interactive)
  (context-guess-current-interface)
  (require (intern (concat "context-" ConTeXt-current-interface)))
  (funcall (intern (concat "context-" ConTeXt-current-interface "-mode"))))

(provide 'context)

;;; context.el ends here