Remove xetla pkg
[packages] / xemacs-packages / auctex / context.el
1 ;;; context.el --- Support for ConTeXt documents.
2
3 ;; Copyright (C) 2003-2006, 2008, 2010, 2012, 2014
4 ;;   Free Software Foundation, Inc.
5
6 ;; Maintainer: Berend de Boer <berend@pobox.com>
7 ;; Keywords: tex
8
9 ;; This file is part of AUCTeX.
10
11 ;; AUCTeX is free software; you can redistribute it and/or modify it
12 ;; under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 3, or (at your option)
14 ;; any later version.
15
16 ;; AUCTeX is distributed in the hope that it will be useful, but
17 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19 ;; General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with AUCTeX; see the file COPYING.  If not, write to the Free
23 ;; Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
24 ;; 02110-1301, USA.
25
26 ;;; Commentary:
27
28 ;; This is in progress ConTeXt support for AUCTeX. Please report
29 ;; anomalies or things you believe should be added.
30
31 ;; AUCTeX is closely interwoven with LaTeX.  We have to split up
32 ;; things without breaking 'em.
33
34 ;; some parts are stolen from latex.el and adapted to ConTeXt.
35
36 ;; TODO
37 ;; 1. indentation still bad.
38 ;; 2. paragraph refilling doesn't work 100%, and is very slow.
39 ;; 4. Remove dependency on LaTeX by moving LaTeX commands to TeX.
40 ;; 5. Most ConTeXt macro's don't currently have lisp code to query for
41 ;;    arguments. As ConTeXt arguments are quite complex, the LaTeX way
42 ;;    of querying for arguments just doesn't cut it.
43 ;; 6. Check auto-parsing: does it detect % interface=nl for example?
44 ;; 7. Complete adding ConTeXt macro's. Perhaps parse cont-en.xml and
45 ;;    generate the interfaces?
46 ;; 8. Add to menu: make TeX hash (mktexlsr), context format and metapost format.
47
48 ;; TODO Documentation
49 ;; 1. multifile done differently with ConTeXt
50
51 ;;; Code:
52
53 (require 'tex-buf)
54 (require 'tex)
55 (require 'latex) ; for functions like `TeX-look-at' and `LaTeX-split-long-menu'
56 (require 'plain-tex) ; for `plain-TeX-common-initialization'
57
58 (defgroup ConTeXt-macro nil
59   "Special support for ConTeXt macros in AUCTeX."
60   :prefix "TeX-"
61   :group 'ConTeXt
62   :group 'TeX-macro)
63
64
65 ;;; variables
66
67 ;; globals used in certain macro's.
68 (defvar done-mark nil
69   "Position of point afterwards, default nil (meaning end).")
70
71 (defvar reference nil
72   "Set by `ConTeXt-section-ref', used by `ConTeXt-section-section'.")
73
74 (defvar title nil
75   "Set by `ConTeXt-section-title', used by `ConTeXt-section-section'.")
76
77
78 ;; others
79
80 (defvar ConTeXt-known-interfaces '("cz" "de" "en" "it" "nl" "ro" "uk"))
81
82 (defcustom ConTeXt-default-interface "en"
83   "Default interface to be used when running ConTeXt."
84   :group 'ConTeXt
85   :type 'string)
86
87 (defvar ConTeXt-current-interface "en"
88   "Interface to be used for inserting macros and ConTeXt run.")
89 (make-variable-buffer-local 'ConTeXt-current-interface)
90
91 (defvar ConTeXt-menu-changed nil)
92 ;; Need to update ConTeXt menu.
93 (make-variable-buffer-local 'ConTeXt-menu-changed)
94
95 (defvar ConTeXt-largest-level nil
96   "Largest sectioning level within current document.")
97 (make-variable-buffer-local 'ConTeXt-largest-level)
98
99 (defun ConTeXt-largest-level ()
100   (TeX-update-style)
101   ConTeXt-largest-level)
102
103
104 ;;; Syntax
105
106 (defvar ConTeXt-optop "["
107   "The ConTeXt optional argument opening character.")
108
109 (defvar ConTeXt-optcl "]"
110   "The ConTeXt optional argument closing character.")
111
112
113 ;; Define a ConTeXt macro
114
115 (defvar ConTeXt-define-list ()
116   "Calls ConTeXt-XX-define-list where XX is the current interface.")
117
118 (defun ConTeXt-define-command (what)
119   "The ConTeXt macro to define WHAT."
120   (funcall
121    (intern (concat "ConTeXt-define-command-" ConTeXt-current-interface)) what))
122
123 (defun ConTeXt-insert-define (define)
124   "Insert the ConTeXt define macro DEFINE."
125   (insert TeX-esc (ConTeXt-define-command define))
126   (newline)
127   (indent-according-to-mode)
128   (ConTeXt-arg-setup nil))
129
130
131 ;; Setup a ConTeXt macro
132
133 (defvar ConTeXt-setup-list ()
134   "Calls ConTeXt-XX-setup-list where XX is the current interface.")
135
136 (defun ConTeXt-setup-command (what)
137   "The ConTeXt macro to setup WHAT."
138   (funcall
139    (intern (concat "ConTeXt-setup-command-" ConTeXt-current-interface)) what))
140
141 (defun ConTeXt-insert-setup (setup)
142   "Insert the ConTeXt setup macro SETUP."
143   (insert TeX-esc (ConTeXt-setup-command setup))
144   (newline)
145   (indent-according-to-mode)
146   (ConTeXt-arg-setup nil))
147
148
149 ;; Referencing ConTeXt macro's
150
151 (defvar ConTeXt-referencing-list ()
152   "Calls ConTeXt-XX-other-macro-list where XX is the current interface.")
153
154 (defun ConTeXt-referencing-command (what)
155   "The ConTeXt macro to call WHAT is itself, no interface specific calls."
156   what)
157
158 (defun ConTeXt-insert-referencing (what)
159   "Insert the ConTeXt referencing SETUP."
160   (insert TeX-esc (ConTeXt-referencing-command what))
161   (newline)
162   (indent-according-to-mode)
163   (ConTeXt-arg-setup nil))
164
165
166 ;; Other ConTeXt macro's
167
168 (defvar ConTeXt-other-macro-list ()
169   "Calls ConTeXt-XX-other-macro-list where XX is the current interface.")
170
171 (defun ConTeXt-other-macro-command (what)
172   "The ConTeXt macro to call WHAT is itself, no interface specific calls."
173   what)
174
175 (defun ConTeXt-insert-other-macro (other-macro)
176   "Insert the ConTeXt other macro's macro SETUP."
177   (insert TeX-esc (ConTeXt-other-macro-command other-macro))
178   (newline)
179   (indent-according-to-mode)
180   (ConTeXt-arg-setup nil))
181
182
183 ;;; Project structure
184
185 (defvar ConTeXt-project-structure-list ()
186   "Calls ConTeXt-XX-project-structure where XX is the current interface.")
187
188 (defun ConTeXt-project-structure (N)
189   "Insert a ConTeXt project structure where N is in index into `ConTeXt-project-structure-list'."
190   (funcall (intern(concat
191                    "ConTeXt-project-"
192                    (nth N ConTeXt-project-structure-list)
193                    "-insert"))))
194
195 (defun ConTeXt-project-project-insert ()
196   "Insert a basic template for a new ConTeXt project."
197   (save-excursion
198     (insert "% The following names are examples only\n")
199     (insert TeX-esc (ConTeXt-environment-start-name) (nth 0 ConTeXt-project-structure-list) " myproject")
200     (newline 2)
201     (insert TeX-esc (nth 1 ConTeXt-project-structure-list) " myenvironment")
202     (newline 2)
203     (insert TeX-esc (nth 2 ConTeXt-project-structure-list) " myproduct1")
204     (newline 2)
205     (insert TeX-esc (nth 2 ConTeXt-project-structure-list) " myproduct2")
206     (newline 2)
207     (insert TeX-esc (ConTeXt-environment-stop-name) (nth 0 ConTeXt-project-structure-list))))
208
209 (defun ConTeXt-project-environment-insert ()
210   "Insert a basic template for the environment of a ConTeXt project."
211   (save-excursion
212     (insert "% The name 'myenvironment' is an example only.\n"
213             "% It must match the name in your project file.\n")
214     (insert TeX-esc (ConTeXt-environment-start-name)
215             (nth 1 ConTeXt-project-structure-list) " myenvironment\n\n")
216     (insert "% Put environment charateristics that must be defined at the "
217             "highest level here\n\n")
218     (insert TeX-esc (ConTeXt-environment-stop-name)
219             (nth 1 ConTeXt-project-structure-list))))
220
221 (defun ConTeXt-project-product-insert ()
222   "Insert a basic template for a product of a ConTeXt project."
223   (save-excursion
224     (insert "% The following names are examples only\n")
225     (insert TeX-esc (ConTeXt-environment-start-name)
226             (nth 2 ConTeXt-project-structure-list) " myproduct1")
227     (newline 2)
228     (insert TeX-esc (nth 0 ConTeXt-project-structure-list) " myproject")
229     (newline 2)
230     (insert "% Components are optional. "
231             "You can also just start your document here.\n")
232     (insert TeX-esc (nth 3 ConTeXt-project-structure-list) " mycomponent1")
233     (newline 2)
234     (insert TeX-esc (nth 3 ConTeXt-project-structure-list) " mycomponent2")
235     (newline 2)
236     (insert TeX-esc (ConTeXt-environment-stop-name)
237             (nth 2 ConTeXt-project-structure-list))))
238
239 (defun ConTeXt-project-component-insert ()
240   "Insert a basic template for a component of a ConTeXt project."
241   (save-excursion
242     (insert "% The following names are examples only\n")
243     (insert TeX-esc (ConTeXt-environment-start-name)
244             (nth 3 ConTeXt-project-structure-list) " mycomponent1")
245     (newline 2)
246     (insert TeX-esc (nth 0 ConTeXt-project-structure-list) " myproject\n")
247     (insert TeX-esc (nth 2 ConTeXt-project-structure-list) " myproduct1")
248     (newline 2)
249     (insert "% ... text here ...")
250     (newline 2)
251     (insert TeX-esc (ConTeXt-environment-stop-name)
252             (nth 3 ConTeXt-project-structure-list))))
253
254
255 ;;; Section blocks
256
257 (defvar ConTeXt-section-block-list ()
258   "Calls ConTeXt-XX-section-list where XX is the current interface.")
259
260 (defun ConTeXt-section-block (section-block)
261   "Insert the ConTeXt section block SECTION-BLOCK."
262   (ConTeXt-environment-menu section-block))
263
264
265 ;;; Sections
266
267 (defun ConTeXt-section (arg)
268   "Insert a template for a ConTeXt section.
269 Determinate the type of section to be inserted, by the argument ARG.
270
271 If ARG is nil or missing, use the current level.
272 If ARG is a list (selected by \\[universal-argument]), go downward one level.
273 If ARG is negative, go up that many levels.
274 If ARG is positive or zero, use absolute level:
275
276         0 : part
277         1 : chapter
278         2 : section
279         3 : subsection
280         4 : subsubsection
281         5 : subsubsubsection
282
283 Or:
284
285         0 : title
286         1 : subject
287         2 : subsubject
288         3 : subsubsubject
289
290 The following variables can be set to customize:
291
292 `ConTeXt-section-hook'    Hooks to run when inserting a section.
293 `ConTeXt-section-ref'   Prefix to all section references."
294
295   (interactive "*P")
296   (let* ((val (prefix-numeric-value arg))
297          (level (cond ((null arg)
298                        (ConTeXt-current-section))
299                       ((listp arg)
300                        (ConTeXt-down-section))
301                       ((< val 0)
302                        (ConTeXt-up-section (- val)))
303                       (t val)))
304          (name (ConTeXt-numbered-section-name level))
305          (toc nil)
306          (title "")
307          (done-mark (make-marker)))
308     (newline)
309     (run-hooks 'ConTeXt-numbered-section-hook)
310     (newline)
311     (if (marker-position done-mark)
312         (goto-char (marker-position done-mark)))
313     (set-marker done-mark nil)))
314
315 ;; LaTeX has a max function here, which makes no sense.
316 ;; I think you want to insert a section that is max ConTeXt-largest-level
317 (defun ConTeXt-current-section ()
318   "Return the level of the section that contain point.
319 See also `ConTeXt-section' for description of levels."
320   (save-excursion
321     (min (ConTeXt-largest-level)
322          (if (re-search-backward outline-regexp nil t)
323              (+ 1 (- (ConTeXt-outline-level) (ConTeXt-outline-offset)))
324            (ConTeXt-largest-level)))))
325
326 (defun ConTeXt-down-section ()
327   "Return the value of a section one level under the current.
328 Tries to find what kind of section that have been used earlier in the
329 text, if this fail, it will just return one less than the current
330 section."
331   (save-excursion
332     (let ((current (ConTeXt-current-section))
333           (next nil)
334           (regexp outline-regexp))
335       (if (not (re-search-backward regexp nil t))
336           (1+ current)
337         (while (not next)
338           (cond
339            ((eq (ConTeXt-current-section) current)
340             (if (re-search-forward regexp nil t)
341                 (if (<= (setq next (ConTeXt-current-section)) current) ;Wow!
342                     (setq next (1+ current)))
343               (setq next (1+ current))))
344            ((not (re-search-backward regexp nil t))
345             (setq next (1+ current)))))
346         next))))
347
348 (defun ConTeXt-up-section (arg)
349   "Return the value of the section ARG levels above this one."
350   (save-excursion
351     (if (zerop arg)
352         (ConTeXt-current-section)
353       (let ((current (ConTeXt-current-section)))
354         (while (and (>= (ConTeXt-current-section) current)
355                     (re-search-backward outline-regexp
356                                         nil t)))
357         (ConTeXt-up-section (1- arg))))))
358
359 (defvar ConTeXt-numbered-section-list ()
360   "ConTeXt-XX-section-list where XX is the current interface.")
361
362 (defvar ConTeXt-unnumbered-section-list ()
363   "ConTeXt-XX-section-list where XX is the current interface.")
364
365 (defvar ConTeXt-section-list
366   (append ConTeXt-numbered-section-list ConTeXt-unnumbered-section-list)
367 )
368
369 (defun ConTeXt-numbered-section-name (level)
370   "Return the name of the section corresponding to LEVEL."
371   (let ((entry (TeX-member level ConTeXt-numbered-section-list
372                            (function (lambda (a b) (equal a (nth 1 b)))))))
373     (if entry
374         (nth 0 entry)
375       nil)))
376
377 (defun ConTeXt-unnumbered-section-name (level)
378   "Return the name of the section corresponding to LEVEL."
379   (let ((entry (TeX-member level ConTeXt-unnumbered-section-list
380                            (function (lambda (a b) (equal a (nth 1 b)))))))
381     (if entry
382         (nth 0 entry)
383       nil)))
384
385 (defun ConTeXt-numbered-section-level (name)
386   "Return the level of the section NAME."
387   (let ((entry (TeX-member name ConTeXt-numbered-section-list
388                            (function (lambda (a b) (equal a (nth 0 b)))))))
389     (if entry
390         (nth 1 entry)
391       nil)))
392
393 (defun ConTeXt-unnumbered-section-level (name)
394   "Return the level of the section NAME."
395   (let ((entry (TeX-member name ConTeXt-numbered-section-list
396                            (function (lambda (a b) (equal a (nth 0 b)))))))
397     (if entry
398         (nth 1 entry)
399       nil)))
400
401
402 ;;; Section Hooks.
403
404 (defcustom ConTeXt-numbered-section-hook
405   '(ConTeXt-numbered-section-heading
406     ConTeXt-section-title
407     ConTeXt-section-ref
408     ConTeXt-section-section)
409   "List of hooks to run when a new section is inserted.
410
411 The following variables are set before the hooks are run
412
413 level - numeric section level, see the documentation of `ConTeXt-section'.
414 name - name of the sectioning command, derived from `level'.
415 title - The title of the section, default to an empty string.
416 `done-mark' - Position of point afterwards, default nil (meaning end).
417
418 The following standard hook exist -
419
420 ConTeXt-section-heading: Query the user about the name of the
421 sectioning command.  Modifies `level' and `name'.
422
423 ConTeXt-section-title: Query the user about the title of the
424 section.  Modifies `title'.
425
426 ConTeXt-section-section: Insert ConTeXt section command according to
427 `name', `title', and `reference'.  If `title' is an empty string,
428 `done-mark' will be placed at the point they should be inserted.
429
430 ConTeXt-section-ref: Insert a reference for this section command.
431
432 To get a full featured `ConTeXt-section' command, insert
433
434  (setq ConTeXt-numbered-section-hook
435                          '(ConTeXt-numbered-section-heading
436                                  ConTeXt-section-title
437                                  ConTeXt-section-section
438                                  ConTeXt-section-ref))
439
440 in your .emacs file."
441   :group 'ConTeXt-macro
442   :type 'hook
443   :options
444   '(ConTeXt-numbered-section-heading
445     ConTeXt-section-title
446     ConTeXt-section-ref
447     ConTeXt-section-section))
448
449 (defcustom ConTeXt-unnumbered-section-hook
450   '(ConTeXt-unnumbered-section-heading
451     ConTeXt-section-title
452     ConTeXt-section-ref
453     ConTeXt-section-section)
454   "List of hooks to run when a new section is inserted.
455
456 The following variables are set before the hooks are run
457
458 level - numeric section level, see the documentation of `ConTeXt-section'.
459 name - name of the sectioning command, derived from `level'.
460 title - The title of the section, default to an empty string.
461 `done-mark' - Position of point afterwards, default nil (meaning end).
462
463 The following standard hook exist -
464
465 ConTeXt-section-heading: Query the user about the name of the
466 sectioning command.  Modifies `level' and `name'.
467
468 ConTeXt-section-title: Query the user about the title of the
469 section.  Modifies `title'.
470
471 ConTeXt-section-section: Insert ConTeXt section command according to
472 `name', `title', and `reference'.  If `title' is an empty string,
473 `done-mark' will be placed at the point they should be inserted.
474
475 ConTeXt-section-ref: Insert a reference for this section command.
476
477 To get a full featured `ConTeXt-section' command, insert
478
479  (setq ConTeXt-unnumbered-section-hook
480                          '(ConTeXt-unnumbered-section-heading
481                                  ConTeXt-section-title
482                                  ConTeXt-section-section
483                                  ConTeXt-section-ref))
484
485 in your .emacs file."
486   :group 'ConTeXt-macro
487   :type 'hook
488   :options
489   '(ConTeXt-unnumbered-section-heading
490     ConTeXt-section-title
491     ConTeXt-section-ref
492     ConTeXt-section-section))
493
494 (defun ConTeXt-numbered-section-heading ()
495   "Hook to prompt for ConTeXt section name.
496 Insert this hook into `ConTeXt-numbered-section-hook' to allow the user to change
497 the name of the sectioning command inserted with `\\[ConTeXt-section]'."
498   (let ((string (completing-read
499                  (concat "Select level: (default " name ") ")
500                  ConTeXt-numbered-section-list
501                  nil nil nil)))
502     ;; Update name
503     (if (not (zerop (length string)))
504         (setq name string))))
505
506 (defun ConTeXt-unnumbered-section-heading ()
507   "Hook to prompt for ConTeXt section name.
508 Insert this hook into `ConTeXt-unnumbered-section-hook' to allow the user to change
509 the name of the sectioning command inserted with `\\[ConTeXt-section]'."
510   (let ((string (completing-read
511                  (concat "Select level: (default " name ") ")
512                  ConTeXt-unnumbered-section-list
513                  nil nil nil)))
514     ;; Update name
515     (if (not (zerop (length string)))
516         (setq name string))))
517
518 (defun ConTeXt-section-title ()
519   "Hook to prompt for ConTeXt section title.
520 Insert this hook into `ConTeXt-(un)numbered-section-hook' to allow the user to change
521 the title of the section inserted with `\\[ConTeXt-section]."
522   (setq title (read-string "What title: ")))
523
524 (defun ConTeXt-section-section ()
525   "Hook to insert ConTeXt section command into the file.
526 Insert this hook into `ConTeXt-section-hook' after those hooks which sets
527 the `name', `title', and `reference' variables, but before those hooks which
528 assumes the section already is inserted."
529   (insert TeX-esc name)
530   (cond ((null reference))
531         ((zerop (length reference))
532          (insert ConTeXt-optop)
533          (set-marker done-mark (point))
534          (insert ConTeXt-optcl))
535         (t
536          (insert ConTeXt-optop reference ConTeXt-optcl)))
537   (insert TeX-grop)
538   (if (zerop (length title))
539       (set-marker done-mark (point)))
540   (insert title TeX-grcl)
541   (newline)
542   ;; If RefTeX is available, tell it that we've just made a new section
543   (and (fboundp 'reftex-notice-new-section)
544        (funcall (symbol-function 'reftex-notice-new-section))))
545
546 (defun ConTeXt-section-ref ()
547   "Hook to insert a reference after the sectioning command.
548 Insert this hook into `ConTeXt-section-hook' to prompt for a label to be
549 inserted after the sectioning command."
550
551   (setq reference (completing-read
552                    (TeX-argument-prompt t nil
553                                         "Comma separated list of references")
554                    (LaTeX-label-list) nil nil))
555   ;; No reference or empty string entered?
556   (if (string-equal "" reference)
557       (setq reference nil)))
558
559
560 ;; Various
561 (defun TeX-ConTeXt-sentinel (process name)
562   "Cleanup TeX output buffer after running ConTeXt."
563   (cond ((TeX-TeX-sentinel-check process name))
564         ((save-excursion
565            ;; in a full ConTeXt run there will multiple texutil
566            ;; outputs. Just looking for "another run needed" would
567            ;; find the first occurence
568            (goto-char (point-max))
569            (re-search-backward "TeXUtil " nil t)
570            (re-search-forward "another run needed" nil t))
571          (message (concat "You should run ConTeXt again "
572                           "to get references right, "
573                           (TeX-current-pages)))
574          (setq TeX-command-next TeX-command-default))
575         ((re-search-forward "removed files :" nil t)
576          (message "sucessfully cleaned up"))
577         ((re-search-forward "^ ?TeX\\(Exec\\|Util\\)" nil t) ;; strange regexp --pg
578          (message (concat name ": successfully formatted "
579                           (TeX-current-pages)))
580          (setq TeX-command-next TeX-command-Show))
581         (t
582          (message (concat name ": problems after "
583                           (TeX-current-pages)))
584          (setq TeX-command-next TeX-command-default))))
585
586
587 ;;; Environments
588
589 (defgroup ConTeXt-environment nil
590   "Environments in AUCTeX."
591   :group 'ConTeXt-macro)
592
593 ;; TODO: interface awareness
594 (defcustom ConTeXt-default-environment "itemize"
595   "*The default environment when creating new ones with `ConTeXt-environment'."
596   :group 'ConTeXt-environment
597   :type 'string)
598 (make-variable-buffer-local 'ConTeXt-default-environment)
599
600 (TeX-auto-add-type "environment" "ConTeXt")
601
602 (defadvice ConTeXt-add-environments (after ConTeXt-invalidate-menu (&rest environments) activate)
603   "Add ENVIRONMENTS to the list of known environments."
604   (setq ConTeXt-menu-changed t))
605
606 ;; (defvar ConTeXt-environment-list ()
607 ;;      "ConTeXt-environment-list-XX where XX is the current interface.")
608
609 (defvar ConTeXt-environment-history nil)
610
611 (defun ConTeXt-environment-start-name ()
612   "Return the \\start translated to the language in current interface."
613   ;; it is "inizia", others are "start"
614   (cond ((equal ConTeXt-current-interface "it")
615          "inizia")
616         ((member ConTeXt-current-interface ConTeXt-known-interfaces)
617          "start")
618         (t
619          ;; this should not happen
620          (error "Unknown interface: %s" ConTeXt-current-interface))))
621
622 (defun ConTeXt-environment-stop-name ()
623   "Return the \\stop translated to the language in current interface."
624   ;; it is "termina", others are "stop"
625   (cond ((equal ConTeXt-current-interface "it")
626          "termina")
627         ((member ConTeXt-current-interface ConTeXt-known-interfaces)
628          "stop")
629         (t
630          ;; this should not happen
631          (error "Unknown interface: %s" ConTeXt-current-interface))))
632
633
634 (defun ConTeXt-environment (arg)
635   "Make ConTeXt environment (\\start...-\\stop... pair).
636 With optional ARG, modify current environment."
637   (interactive "*P")
638   (let ((environment (
639                       completing-read (concat "Environment type: (default "
640                                               (if (TeX-near-bobp)
641                                                   "text"
642                                                 ConTeXt-default-environment)
643                                               ") ")
644                       ConTeXt-environment-list
645                       nil nil nil
646                       'ConTeXt-environment-history)
647                      ))
648     ;; Get default
649     (cond ((and (zerop (length environment))
650                 (TeX-near-bobp))
651            (setq environment "text"))
652           ((zerop (length environment))
653            (setq environment ConTeXt-default-environment))
654           (t
655            (setq ConTeXt-default-environment environment)))
656
657     (let ((entry (assoc environment ConTeXt-environment-list)))
658       (when (null entry)
659         (ConTeXt-add-environments (list environment)))
660       (if arg
661           (ConTeXt-modify-environment environment)
662         (ConTeXt-environment-menu environment)))))
663
664 (defun ConTeXt-modify-environment (environment)
665   "Modify current environment."
666   (save-excursion
667     (ConTeXt-find-matching-stop)
668     (re-search-backward (concat (regexp-quote TeX-esc)
669                                 (ConTeXt-environment-stop-name)
670                                 " *\\([a-zA-Z]*\\)")
671                         (save-excursion (beginning-of-line 1) (point)))
672     (replace-match
673      (concat TeX-esc (ConTeXt-environment-stop-name) environment) t t)
674     (beginning-of-line 1)
675     (ConTeXt-find-matching-start)
676     (re-search-forward (concat (regexp-quote TeX-esc)
677                                (ConTeXt-environment-start-name)
678                                " *\\([a-zA-Z]*\\)")
679                        (save-excursion (end-of-line 1) (point)))
680     (replace-match
681      (concat TeX-esc (ConTeXt-environment-start-name) environment) t t)))
682
683
684 (defun ConTeXt-environment-menu (environment)
685   "Insert ENVIRONMENT around point or region."
686   (let ((entry (assoc environment ConTeXt-environment-list)))
687     (cond ((not (and entry (nth 1 entry)))
688            (ConTeXt-insert-environment environment))
689           ((numberp (nth 1 entry))
690            (let ((count (nth 1 entry))
691                  (args ""))
692              (while (> count 0)
693                (setq args (concat args TeX-grop TeX-grcl))
694                (setq count (- count 1)))
695              (ConTeXt-insert-environment environment args)))
696           ((stringp (nth 1 entry))
697            (let ((prompts (cdr entry))
698                  (args ""))
699              (while prompts
700                (setq args (concat args
701                                   TeX-grop
702                                   (read-from-minibuffer
703                                    (concat (car prompts) ": "))
704                                   TeX-grcl))
705                (setq prompts (cdr prompts)))
706              (ConTeXt-insert-environment environment args)))
707           (t
708            (apply (nth 1 entry) environment (nthcdr 2 entry))))))
709
710 (defun ConTeXt-close-environment ()
711   "Insert \\stop... to match the current environment."
712   (interactive "*")
713   (beginning-of-line)
714   (let ((empty-line (looking-at "[ \t]*$")))
715     (end-of-line)
716     (if (not empty-line)
717         (newline)))
718   (insert TeX-esc (ConTeXt-environment-stop-name)
719           (ConTeXt-current-environment))
720   ;; indent broken, so don't do it.
721   ;;(indent-according-to-mode)
722   (end-of-line)
723   (newline))
724
725 (defun ConTeXt-insert-environment (environment &optional extra)
726   "Insert ENVIRONMENT, with optional argument EXTRA."
727   (if (and (TeX-active-mark)
728            (not (eq (mark) (point))))
729       (save-excursion
730         (if (< (mark) (point))
731             (exchange-point-and-mark))
732         (insert TeX-esc (ConTeXt-environment-start-name) environment)
733         (newline)
734         (forward-line -1)
735         (indent-according-to-mode)
736         (if extra (insert extra))
737         (goto-char (mark))
738         (or (TeX-looking-at-backward "^[ \t]*")
739             (newline))
740         (insert TeX-esc (ConTeXt-environment-stop-name) environment)
741         (newline)
742         (forward-line -1)
743         (indent-according-to-mode)
744         ;;(goto-char (point))
745         )
746     (or (TeX-looking-at-backward "^[ \t]*")
747         (newline))
748     (insert TeX-esc (ConTeXt-environment-start-name) environment)
749     (indent-according-to-mode)
750     (if extra (insert extra))
751     (end-of-line)
752     (newline-and-indent)
753     (newline)
754     (insert TeX-esc (ConTeXt-environment-stop-name) environment)
755     (or (looking-at "[ \t]*$")
756         (save-excursion (newline-and-indent)))
757     (indent-according-to-mode)
758     (end-of-line 0)))
759
760 \f
761 ;; with the following we can call a function on an environment. Say
762 ;; you have metapost stuff within your TeX file, go to the environment
763 ;; and run ConTeXt-work-on-environment (suggested Key: C-c !). AUCTeX
764 ;; sees that you are inside e.g. \startMPpage....\stopMPpage and
765 ;; looks in ConTeXt-environment-helper for a function to be called.
766
767 ;; % so pressing C-c ! inside the following ...
768 ;;\startuseMPgraphic{Logo}{Scale}
769 ;; % Top rectangle
770 ;; filldraw (0,0)--(2cm,0)--(2cm,1cm)--(0,1cm)--cycle withcolor blue ;
771 ;; % Bottom black rectangle
772 ;; drawfill (0,0)--(2cm,0)--(2cm,-1cm)--(0,-1cm)--cycle withcolor black;
773 ;; % White Text
774 ;; draw btex \bf AB etex withcolor white ;
775 ;; % resize to size
776 ;; currentpicture := currentpicture scaled \MPvar{Scale} ;
777 ;; \stopuseMPgraphic
778
779 ;; % ...should give you a "new buffer" (currently narrowed to region
780 ;; % and switched to metapost-mode and recursive-edit)
781
782 ;; % Top rectangle
783 ;; filldraw (0,0)--(2cm,0)--(2cm,1cm)--(0,1cm)--cycle withcolor blue ;
784 ;; % Bottom black rectangle
785 ;; drawfill (0,0)--(2cm,0)--(2cm,-1cm)--(0,-1cm)--cycle withcolor black;
786 ;; % White Text
787 ;; draw btex \bf AB etex withcolor white ;
788 ;; % resize to size
789 ;; currentpicture := currentpicture scaled \MPvar{Scale} ;
790
791
792 (defvar ConTeXt-environment-helper
793   '(("useMPgraphic" . ConTeXt-mp-region)
794     ("MPpage" . ConTeXt-mp-region))
795   "Alist that holds functions to call for working on regions.
796 An entry looks like: (\"environment\" . function)")
797
798 (defun ConTeXt-mp-region ()
799   "Edit region in `metapost-mode'."
800   (ConTeXt-mark-environment t)
801   (narrow-to-region (mark) (point))
802   (metapost-mode)
803   (message "Type `M-x exit-recursive-edit' to get back")
804   (recursive-edit)
805   (context-mode)
806   (widen))
807
808 ;; find smarter name. Suggestions welcome
809 (defun ConTeXt-work-on-environment ()
810   "Takes current environment and does something on it (todo: documentation)."
811   (interactive)
812   (let ((fun (cdr (assoc (ConTeXt-current-environment)
813                          ConTeXt-environment-helper))))
814     (when (functionp fun)
815       (funcall fun))))
816
817 (defun ConTeXt-current-environment ()
818   "Return the name of the current environment."
819   ;; don't make this interactive.
820   (let ((beg))
821     (save-excursion
822       (ConTeXt-last-unended-start)
823       (setq beg (+ (point) (length (ConTeXt-environment-start-name)) 1))
824       (goto-char (match-end 0))
825       (skip-chars-forward "a-zA-Z")
826       (buffer-substring beg (point)))))
827
828 (defun ConTeXt-last-unended-start ()
829   "Leave point at the beginning of the last `\\start...' that is unstopped looking from the current cursor."
830   (while (and (re-search-backward "\\\\start[a-zA-Z]*\\|\\\\stop[a-zA-Z]*")
831               (looking-at "\\\\stop[a-zA-Z]*"))
832     (ConTeXt-last-unended-start)))
833
834 (defun ConTeXt-mark-environment (&optional inner)
835   "Set mark to end of current environment (\\start...-\\stop...) and
836 point to the matching begin.
837 If optional INNER is not nil, include \\start... and \\stop, otherwise only
838 the contents."
839   (interactive)
840   (let ((cur (point)))
841     (ConTeXt-find-matching-stop inner)
842     (push-mark (point))
843     (goto-char cur)
844     (ConTeXt-find-matching-start inner)
845     (TeX-activate-region)))
846
847 (defun ConTeXt-find-matching-stop (&optional inner)
848   "Find end of current \\start...\\stop-Pair.
849 If INNER is non-nil, go to the point just past before
850 \\stop... macro.  Otherwise goto the point just past \\stop..."
851   (interactive)
852   (let ((regexp (concat (regexp-quote TeX-esc)
853                         "\\("
854                         (ConTeXt-environment-start-name)
855                         "\\|"
856                         (ConTeXt-environment-stop-name)
857                         "\\)"
858                         ))
859         (level 1)
860         (pos))
861     ;;jump over the \start... when at the beginning of it.
862     (when (looking-at (concat (regexp-quote TeX-esc)
863                               (ConTeXt-environment-start-name)))
864       (re-search-forward regexp nil t))
865     (while (and (> level 0)
866                 (re-search-forward regexp nil t)
867                 (goto-char (1- (match-beginning 1)))
868                 (cond ((looking-at (concat (regexp-quote TeX-esc)
869                                            (ConTeXt-environment-start-name)))
870                        (re-search-forward regexp nil t)
871                        (setq level (1+ level)))
872                       ((looking-at (concat (regexp-quote TeX-esc)
873                                            (ConTeXt-environment-stop-name)))
874                        (re-search-forward regexp nil t)
875                        (setq level (1- level))))))
876     ;; now we have to look if we want to start behind the \start... macro
877     (if inner
878         (beginning-of-line)
879       (skip-chars-forward "a-zA-Z"))))
880
881 (defun ConTeXt-find-matching-start (&optional inner)
882   "Find beginning of current \\start...\\stop-Pair.
883 If INNER is non-nil, go to the point just past the \\start... macro."
884   (interactive)
885   (let ((regexp (concat (regexp-quote TeX-esc)
886                         "\\("
887                         (ConTeXt-environment-start-name)
888                         "\\|"
889                         (ConTeXt-environment-stop-name)
890                         "\\)"
891                         ))
892         (level 1)
893         (pos))
894     (while (and (> level 0)
895                 (re-search-backward regexp nil t)
896                 (cond ((looking-at (concat (regexp-quote TeX-esc)
897                                            (ConTeXt-environment-stop-name)))
898                        (setq level (1+ level)))
899                       ((looking-at (concat (regexp-quote TeX-esc)
900                                            (ConTeXt-environment-start-name)))
901                        (setq level (1- level))))))
902     ;; now we have to look if we want to start behind the \start... macro
903     (when inner
904       ;; \startfoo can have 0 or more {} and [] pairs. I assume that
905       ;; skipping all those parens will be smart enough. It fails when
906       ;; the first part in the \start-\stop-environment is { or [, like
907       ;; in \startquotation   {\em important} \stopquotation. There is
908       ;; yet another pitfall: \startsetups SomeSetup foo bar
909       ;; \stopsetups will use SomeSetup as the argument and the
910       ;; environment
911       (skip-chars-forward "\\\\a-zA-Z")
912       (save-excursion
913         (while (progn
914                  (skip-chars-forward "\t\n ")
915                  (forward-comment 1)
916                  (skip-chars-forward "\t\n ")
917                  (looking-at "\\s\("))
918           (forward-list 1)
919           (setq pos (point))))
920       (when pos
921         (goto-char pos))
922       (unless (bolp)
923         (forward-line)))))
924
925 ;;; items
926
927 (defun ConTeXt-insert-item ()
928   "Insert a new item."
929   (interactive "*")
930   (or (TeX-looking-at-backward "^[ \t]*")
931       (newline))
932   (TeX-insert-macro "item")
933   (indent-according-to-mode))
934
935
936 ;;; Macro Argument Hooks
937
938 (defun ConTeXt-optional-argument-insert (arg &optional prefix)
939   "Insert ARG surrounded by square brackets."
940   (insert ConTeXt-optop)
941   (insert arg)
942   (insert ConTeXt-optcl))
943
944 (defun ConTeXt-required-argument-insert (arg &optional prefix)
945   "Insert ARG surrounded by curly braces."
946   (insert TeX-grop)
947   (insert arg)
948   (insert TeX-grcl))
949
950 (defun ConTeXt-argument-insert (arg optional &optional prefix)
951   "Insert ARG surrounded by curly braces.
952
953 If OPTIONAL, only insert it if not empty, and then use square brackets."
954   (if optional
955       (if
956           (not (string-equal arg ""))
957           (ConTeXt-optional-argument-insert arg prefix))
958     (ConTeXt-required-argument-insert arg prefix)))
959
960 (defun ConTeXt-arg-ref (optional &optional prompt definition)
961   "Prompt for a reference completing with known references."
962   (let ((ref (completing-read (TeX-argument-prompt optional prompt "ref")
963                               (LaTeX-label-list))))
964     (if (and definition (not (string-equal "" ref)))
965         (LaTeX-add-labels ref))
966     (ConTeXt-argument-insert ref optional)))
967
968 (defun ConTeXt-arg-define-ref (&optional prompt)
969   "Prompt for an optional reference completing with known references."
970   (ConTeXt-arg-ref t prompt t))
971
972 (defun ConTeXt-arg-setup (optional &optional prompt)
973   "Prompt for setup arguments."
974   (let ((setup (read-from-minibuffer
975                 (TeX-argument-prompt optional prompt "Setup"))))
976     (ConTeXt-argument-insert setup t)))
977
978
979 ;; paragraph (re)-formatting
980
981 (defvar ConTeXt-item-list ()
982   "List of macro's considered items.")
983
984 (defun ConTeXt-paragraph-commands-regexp ()
985   "Return a regexp matching macros that should have their own line."
986   (concat
987    (regexp-quote TeX-esc) "\\("
988    "[][]\\|"  ; display math delimitors (is this applicable to ConTeXt??)
989    (ConTeXt-environment-start-name) "\\|"
990    (ConTeXt-environment-stop-name) "\\|"
991    (mapconcat 'car ConTeXt-numbered-section-list "\\b\\|") "\\b\\|"
992    (mapconcat 'car ConTeXt-unnumbered-section-list "\\b\\|") "\\b\\|"
993    (mapconcat 'identity ConTeXt-extra-paragraph-commands "\\b\\|")
994    "\\b\\|"
995    (mapconcat 'identity ConTeXt-item-list "\\b\\|") "\\b\\)"))
996
997
998 ;; Outline support
999
1000 (defun ConTeXt-environment-full-start-name (environment)
1001   "Return the ConTeXt macro name that starts ENVIRONMENT.
1002 It is interface aware"
1003   (concat (ConTeXt-environment-start-name) environment))
1004
1005 (defun ConTeXt-outline-regexp (&optional anywhere)
1006   "Return regexp for ConTeXt section blocks and sections.
1007
1008 If optional argument ANYWHERE is not nil, do not require that the
1009 header is at the start of a line."
1010   (concat
1011    (if anywhere "" "^")
1012    "[ \t]*"
1013    (regexp-quote TeX-esc)
1014    "\\("
1015    (mapconcat 'ConTeXt-environment-full-start-name ConTeXt-section-block-list "\\|") "\\|"
1016    (mapconcat 'car ConTeXt-numbered-section-list "\\|")
1017    (mapconcat 'car ConTeXt-unnumbered-section-list "\\|")
1018    "\\)\\b"
1019    (if TeX-outline-extra
1020        "\\|"
1021      "")
1022    (mapconcat 'car TeX-outline-extra "\\|")
1023    "\\|" (ConTeXt-header-end) "\\b"
1024    "\\|" (ConTeXt-trailer-start) "\\b"))
1025
1026 (defvar ConTeXt-text "Name of ConTeXt macro that begins the text body.")
1027
1028 (defun ConTeXt-header-end ()
1029   "Default end of header marker for ConTeXt documents."
1030   (concat
1031    (regexp-quote TeX-esc)
1032    (ConTeXt-environment-start-name)
1033    ConTeXt-text))
1034
1035 (defun ConTeXt-trailer-start ()
1036   "Default start of trailer marker for ConTeXt documents."
1037   (concat
1038    (regexp-quote TeX-esc)
1039    (ConTeXt-environment-stop-name)
1040    ConTeXt-text))
1041
1042 (defun ConTeXt-outline-offset ()
1043   "Offset to add to `ConTeXt-section-list' levels to get outline level."
1044   (- 4 (ConTeXt-largest-level)))
1045
1046 (defun ConTeXt-start-environment-regexp (list)
1047   "Regular expression that matches a start of all environments mentioned in LIST."
1048   (concat
1049    "start\\("
1050    (mapconcat 'identity list "\\|")
1051    "\\)\\b"))
1052
1053 ;; The top headings are \starttext, \startfrontmatter, \startbodymatter etc.
1054 ;; \part, \chapter etc. are children of that.
1055 (defun ConTeXt-outline-level ()
1056   "Find the level of current outline heading in an ConTeXt document."
1057   (cond ((looking-at (concat (ConTeXt-header-end) "\\b")) 1)
1058         ((looking-at (concat (ConTeXt-trailer-start) "\\b")) 1)
1059         ((TeX-look-at TeX-outline-extra)
1060          (max 1 (+ (TeX-look-at TeX-outline-extra)
1061                    (ConTeXt-outline-offset))))
1062         (t
1063          (save-excursion
1064            (skip-chars-forward " \t")
1065            (forward-char 1)
1066            (cond ((looking-at (ConTeXt-start-environment-regexp
1067                                ConTeXt-section-block-list)) 1)
1068                  ((TeX-look-at ConTeXt-section-list)
1069                   (max 1 (+ (TeX-look-at ConTeXt-section-list)
1070                             (ConTeXt-outline-offset))))
1071                  (t
1072                   (error "Unrecognized header")))))))
1073
1074
1075 ;;; Fonts
1076
1077 (defcustom ConTeXt-font-list '((?\C-b "{\\bf " "}")
1078                            (?\C-c "{\\sc " "}")
1079                            (?\C-e "{\\em " "}")
1080                            (?\C-i "{\\it " "}")
1081                            (?\C-r "{\\rm " "}")
1082                            (?\C-s "{\\sl " "}")
1083                            (?\C-t "{\\tt " "}")
1084                            (?\C-d "" "" t))
1085   "List of fonts used by `TeX-font'.
1086
1087 Each entry is a list.
1088 The first element is the key to activate the font.
1089 The second element is the string to insert before point, and the third
1090 element is the string to insert after point.
1091 If the fourth and fifth element are strings, they specify the prefix and
1092 suffix to be used in math mode.
1093 An optional fourth (or sixth) element means always replace if t."
1094   :group 'TeX-macro
1095   :type '(repeat
1096            (group
1097             :value (?\C-a "" "")
1098             (character :tag "Key")
1099             (string :tag "Prefix")
1100             (string :tag "Suffix")
1101             (option (group
1102                      :inline t
1103                      (string :tag "Math Prefix")
1104                      (string :tag "Math Suffix")))
1105             (option (sexp :format "Replace\n" :value t)))))
1106
1107
1108 ;; Imenu support
1109
1110 (defun ConTeXt-outline-name ()
1111   "Guess a name for the current header line."
1112   (save-excursion
1113     (if (re-search-forward "{\\([^\}]*\\)}" (point-at-eol) t)
1114         (match-string 1)
1115       (buffer-substring-no-properties (point) (point-at-eol)))))
1116
1117 ;; This imenu also includes commented out chapters. Perhaps a feature
1118 ;; for LaTeX, not sure we want or need that for ConTeXt.
1119
1120 (defun ConTeXt-imenu-create-index-function ()
1121   "Imenu support function for ConTeXt."
1122   (TeX-update-style)
1123   (let (entries level (regexp (ConTeXt-outline-regexp)))
1124     (goto-char (point-max))
1125     (while (re-search-backward regexp nil t)
1126       (let* ((name (ConTeXt-outline-name))
1127              (level (make-string (1- (ConTeXt-outline-level)) ?\ ))
1128              (label (concat level level name))
1129              (mark (make-marker)))
1130         (set-marker mark (point))
1131         (set-text-properties 0 (length label) nil label)
1132         (setq entries (cons (cons label mark) entries))))
1133     entries))
1134
1135
1136 ;; Indentation, copied from Berend's context mode.
1137 ;; TODO: doesn't work great.
1138
1139 (defvar ConTeXt-indent-allhanging t)
1140 (defvar ConTeXt-indent-arg 2)
1141 (defvar ConTeXt-indent-basic 2)
1142 (defvar ConTeXt-indent-item ConTeXt-indent-basic)
1143 (defvar ConTeXt-indent-item-re "\\\\\\(item\\|sym\\)\\>")
1144
1145 (defvar ConTeXt-indent-syntax-table (make-syntax-table TeX-mode-syntax-table)
1146   "Syntax table used while computing indentation.")
1147
1148 (progn
1149   (modify-syntax-entry ?$ "." ConTeXt-indent-syntax-table)
1150   (modify-syntax-entry ?\( "." ConTeXt-indent-syntax-table)
1151   (modify-syntax-entry ?\) "." ConTeXt-indent-syntax-table))
1152
1153 (defun ConTeXt-indent-line (&optional arg)
1154   (with-syntax-table ConTeXt-indent-syntax-table
1155     ;; TODO: Rather than ignore $, we should try to be more clever about it.
1156     (let ((indent
1157            (save-excursion
1158              (beginning-of-line)
1159              (ConTeXt-find-indent))))
1160       (if (< indent 0) (setq indent 0))
1161       (if (<= (current-column) (current-indentation))
1162           (indent-line-to indent)
1163         (save-excursion (indent-line-to indent))))))
1164
1165 (defun ConTeXt-find-indent (&optional virtual)
1166   "Find the proper indentation of text after point.
1167 VIRTUAL if non-nil indicates that we're only trying to find the
1168 indentation in order to determine the indentation of something
1169 else.  There might be text before point."
1170   (save-excursion
1171     (skip-chars-forward " \t")
1172     (or
1173      ;; Trust the current indentation, if such info is applicable.
1174      (and virtual (>= (current-indentation) (current-column))
1175           (current-indentation))
1176      ;; Put leading close-paren where the matching open brace would be.
1177      (condition-case nil
1178          (and (eq (char-syntax (char-after)) ?\))
1179               (save-excursion
1180                 (skip-syntax-forward " )")
1181                 (backward-sexp 1)
1182                 (ConTeXt-find-indent 'virtual)))
1183        (error nil))
1184      ;; Default (maybe an argument)
1185      (let ((pos (point))
1186            (char (char-after))
1187            (indent 0)
1188            up-list-pos)
1189        ;; Look for macros to be outdented
1190        (cond ((looking-at (concat (regexp-quote TeX-esc)
1191                                   (ConTeXt-environment-stop-name)))
1192               (setq indent (- indent ConTeXt-indent-basic)))
1193              ((looking-at ConTeXt-indent-item-re)
1194               (setq indent (- indent ConTeXt-indent-item))))
1195        ;; Find the previous point which determines our current indentation.
1196        (condition-case err
1197            (progn
1198              (backward-sexp 1)
1199              (while (> (current-column) (current-indentation))
1200                (backward-sexp 1)))
1201          (scan-error
1202           (setq up-list-pos (nth 2 err))))
1203        (cond
1204         ((= (point-min) pos) 0)  ; We're really just indenting the first line.
1205         ((integerp up-list-pos)
1206          ;; Have to indent relative to the open-paren.
1207          (goto-char up-list-pos)
1208          (if (and (not ConTeXt-indent-allhanging)
1209                   (> pos (progn (down-list 1)
1210                                 (forward-comment (point-max))
1211                                 (point))))
1212              ;; Align with the first element after the open-paren.
1213              (current-column)
1214            ;; We're the first element after a hanging brace.
1215            (goto-char up-list-pos)
1216            (+ indent ConTeXt-indent-basic (ConTeXt-find-indent 'virtual))))
1217         ;; We're now at the "beginning" of a line.
1218         ((not (and (not virtual) (eq (char-after) ?\\)))
1219          ;; Nothing particular here: just keep the same indentation.
1220          (+ indent (current-column)))
1221         ;; We're now looking at an item.
1222         ((looking-at ConTeXt-indent-item-re)
1223          ;; Indenting relative to an item, have to re-add the outdenting.
1224          (+ indent (current-column) ConTeXt-indent-item))
1225         ;; We're looking at an environment starter.
1226         ((and (looking-at (concat (regexp-quote TeX-esc)
1227                                   (ConTeXt-environment-start-name)))
1228               (not (looking-at (concat (regexp-quote TeX-esc)
1229                                        (ConTeXt-environment-start-name)
1230                                        ConTeXt-text)))) ; other environments?
1231          (+ indent (current-column) ConTeXt-indent-basic))
1232         (t
1233          (let ((col (current-column)))
1234            (if (not (and char (eq (char-syntax char) ?\()))
1235                ;; If the first char was not an open-paren, there's
1236                ;; a risk that this is really not an argument to the
1237                ;; macro at all.
1238                (+ indent col)
1239              (forward-sexp 1)
1240              (if (< (line-end-position)
1241                     (save-excursion (forward-comment (point-max))
1242                                     (point)))
1243                  ;; we're indenting the first argument.
1244                  (min (current-column) (+ ConTeXt-indent-arg col))
1245                (skip-syntax-forward " ")
1246                (current-column))))))))))
1247
1248
1249 ;; XML inside ConTeXt support
1250
1251 (defun ConTeXt-last-unended-start-xml ()
1252   "Leave point at the beginning of the last `tag' that is unstopped."
1253   (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]*>")
1254               (looking-at "</[_A-Za-z][-:._A-Za-z0-9]*>"))
1255     (ConTeXt-last-unended-start-xml)))
1256
1257 (defun ConTeXt-close-xml-tag ()
1258   "Create an </...> to match the last unclosed <...>.  Not fool-proof."
1259   (interactive "*")
1260   (let ((new-line-needed (bolp)) text indentation)
1261     (save-excursion
1262       (condition-case nil
1263           (ConTeXt-last-unended-start-xml)
1264         (error (error "Couldn't find unended XML tag")))
1265       (setq indentation (current-column))
1266       (re-search-forward "<\\([_A-Za-z][-:._A-Za-z0-9]*\\)")
1267       (setq text (buffer-substring (match-beginning 1) (match-end 1))))
1268     (indent-to indentation)
1269     (insert "</" text ">")
1270     (if new-line-needed (insert ?\n))))
1271
1272
1273 ;; Key bindings
1274
1275 (defvar ConTeXt-mode-map
1276   (let ((map (make-sparse-keymap)))
1277     (set-keymap-parent map TeX-mode-map)
1278
1279     (define-key map "\e\C-a"  'ConTeXt-find-matching-start)
1280     (define-key map "\e\C-e"  'ConTeXt-find-matching-stop)
1281     ;; likely to change in the future
1282     (define-key map "\C-c!"    'ConTeXt-work-on-environment)
1283     (define-key map "\C-c\C-e" 'ConTeXt-environment)
1284     (define-key map "\C-c\n"   'ConTeXt-insert-item)
1285     (or (key-binding "\e\r")
1286         (define-key map "\e\r"    'ConTeXt-insert-item)) ;*** Alias
1287     (define-key map "\C-c]" 'ConTeXt-close-environment)
1288     (define-key map "\C-c\C-s" 'ConTeXt-section)
1289     ;; XML in ConTeXt support
1290     (define-key map "\C-c/" 'ConTeXt-close-xml-tag)
1291     map)
1292   "Keymap used in `ConTeXt-mode'.")
1293
1294
1295 ;;; Menu building
1296
1297 ;; functions to create menu entries
1298
1299 ;; ConTeXt \start... \stop... pairs
1300 ;; (Choose a different name than the one in LaTeX mode.  Otherwise the
1301 ;; contents of the "Insert Environment" and "Change Environment" menus
1302 ;; will not be updated correctly upon loading and switching between
1303 ;; LaTeX and ConTeXt files.  AFAICS this is due to a bug in
1304 ;; easymenu.el not returning the correct keymap when
1305 ;; `easy-menu-change' (and therefore `easy-menu-get-map') is called.
1306 ;; It just sees an entry with a matching name and returns this first
1307 ;; match.)
1308 (defvar ConTeXt-environment-menu-name "Insert Environment   (C-c C-e)")
1309
1310 (defun ConTeXt-environment-menu-entry (entry)
1311   "Create an entry for the environment menu."
1312   (vector (car entry) (list 'ConTeXt-environment-menu (car entry)) t))
1313
1314 (defvar ConTeXt-environment-modify-menu-name "Change Environment   (C-u C-c C-e)")
1315
1316 (defun ConTeXt-environment-modify-menu-entry (entry)
1317   "Create an entry for the change environment menu."
1318   (vector (car entry) (list 'ConTeXt-modify-environment (car entry)) t))
1319
1320 ;; ConTeXt define macros
1321 (defvar ConTeXt-define-menu-name "Define")
1322
1323 (defun ConTeXt-define-menu-entry (entry)
1324   "Create an entry for the define menu."
1325   (vector entry (list 'ConTeXt-define-menu entry)))
1326
1327 (defun ConTeXt-define-menu (define)
1328   "Insert DEFINE from menu."
1329   (ConTeXt-insert-define define))
1330
1331 ;; ConTeXt setup macros
1332 (defvar ConTeXt-setup-menu-name "Setup")
1333
1334 (defun ConTeXt-setup-menu-entry (entry)
1335   "Create an entry for the setup menu."
1336   (vector entry (list 'ConTeXt-setup-menu entry)))
1337
1338 (defun ConTeXt-setup-menu (setup)
1339   "Insert SETUP from menu."
1340   (ConTeXt-insert-setup setup))
1341
1342 ;; ConTeXt referencing macros
1343 (defvar ConTeXt-referencing-menu-name "Referencing")
1344
1345 (defun ConTeXt-referencing-menu-entry (entry)
1346   "Create an entry for the referencing menu."
1347   (vector entry (list 'ConTeXt-referencing-menu entry)))
1348
1349 (defun ConTeXt-referencing-menu (referencing)
1350   "Insert REFERENCING from menu."
1351   (ConTeXt-insert-referencing referencing))
1352
1353 ;; ConTeXt other macros
1354 (defvar ConTeXt-other-macro-menu-name "Other macro")
1355
1356 (defun ConTeXt-other-macro-menu-entry (entry)
1357   "Create an entry for the other macro menu."
1358   (vector entry (list 'ConTeXt-other-macro-menu entry)))
1359
1360 (defun ConTeXt-other-macro-menu (other-macro)
1361   "Insert OTHER MACRO from menu."
1362   (ConTeXt-insert-other-macro other-macro))
1363
1364
1365 ;; meta-structure project structure menu entries
1366
1367 (defvar ConTeXt-project-structure-menu-name "Project Structure")
1368
1369 (defun ConTeXt-project-structure-menu (project-structure)
1370   "Insert project structure from menu."
1371   (ConTeXt-project-structure
1372    (let ((l ConTeXt-project-structure-list))
1373      (- (length l) (length (member project-structure l))))))
1374
1375 (defun ConTeXt-project-structure-menu-entry (entry)
1376   "Create an ENTRY for the project structure menu."
1377   (vector entry (list 'ConTeXt-project-structure-menu entry)))
1378
1379
1380 ;; meta-structure section blocks menu entries
1381
1382 (defvar ConTeXt-section-block-menu-name "Section Block")
1383
1384 (defun ConTeXt-section-block-menu (section-block)
1385   "Insert section block from menu."
1386   (ConTeXt-section-block section-block))
1387
1388 (defun ConTeXt-section-block-menu-entry (entry)
1389   "Create an ENTRY for the section block menu."
1390   (vector entry (list 'ConTeXt-section-block-menu entry)))
1391
1392
1393 ;; section menu entries
1394
1395 (defvar ConTeXt-numbered-section-menu-name "Numbered section  (C-c C-s)")
1396 (defvar ConTeXt-unnumbered-section-menu-name "Unnumbered section")
1397
1398 (defun ConTeXt-section-enable-symbol (level)
1399   "Symbol used to enable section LEVEL in the menu bar."
1400   (intern (concat "ConTeXt-section-" (int-to-string level) "-enable")))
1401
1402 (defun ConTeXt-section-enable (entry)
1403   "Enable or disable section ENTRY from `ConTeXt-section-list'."
1404   (let ((level (nth 1 entry)))
1405     (set (ConTeXt-section-enable-symbol level)
1406          (>= level ConTeXt-largest-level))))
1407
1408 (defun ConTeXt-numbered-section-menu (level)
1409   "Insert numbered section from menu."
1410   (let ((ConTeXt-numbered-section-hook (delq 'ConTeXt-numbered-section-heading
1411                                     (copy-sequence ConTeXt-numbered-section-hook))))
1412     (ConTeXt-section level)))
1413
1414 (defun ConTeXt-unnumbered-section-menu (level)
1415   "Insert unnumbered section from menu."
1416   (let ((ConTeXt-unnumbered-section-hook (delq 'ConTeXt-unnumbered-section-heading
1417                                     (copy-sequence ConTeXt-unnumbered-section-hook))))
1418     (ConTeXt-section level)))
1419
1420 (defun ConTeXt-numbered-section-menu-entry (entry)
1421   "Create an ENTRY for the numbered section menu."
1422   (let ((enable (ConTeXt-section-enable-symbol (nth 1 entry))))
1423     (set enable t)
1424     (vector (car entry) (list 'ConTeXt-numbered-section-menu (nth 1 entry)) enable)))
1425
1426 (defun ConTeXt-unnumbered-section-menu-entry (entry)
1427   "Create an ENTRY for the unnumbered section menu."
1428   (let ((enable (ConTeXt-section-enable-symbol (nth 1 entry))))
1429     (set enable t)
1430     (vector (car entry) (list 'ConTeXt-unnumbered-section-menu (nth 1 entry)) enable)))
1431
1432
1433 ;; etexshow support
1434
1435 (defun ConTeXt-etexshow ()
1436   "Call etexshow, if available, to show the definition of a ConText macro."
1437   (interactive)
1438   (if (fboundp 'etexshow)
1439       (let ()
1440         (require 'etexshow)
1441         (funcall (symbol-function 'etexshow-cmd)))
1442     (error "etexshow is not installed.  Get it from http://levana.de/emacs/")))
1443
1444 ;; menu itself
1445
1446 (easy-menu-define ConTeXt-mode-command-menu
1447   ConTeXt-mode-map
1448   "Command menu used in ConTeXt mode."
1449   (TeX-mode-specific-command-menu 'context-mode))
1450
1451 ;; it seems the menu is evaluated at compile/load-time
1452 ;; we don't have ConTeXt-current-interface at that time
1453 ;; so make sure to do updates based on that variable in
1454 ;; ConTeXt-menu-update
1455 (easy-menu-define ConTeXt-mode-menu
1456   ConTeXt-mode-map
1457   "Menu used in ConTeXt mode."
1458   (TeX-menu-with-help
1459    `("ConTeXt"
1460      (,ConTeXt-project-structure-menu-name)
1461      (,ConTeXt-section-block-menu-name)
1462      (,ConTeXt-numbered-section-menu-name)
1463      (,ConTeXt-unnumbered-section-menu-name)
1464      ["Add Table of Contents to Emacs Menu" (imenu-add-to-menubar "TOC") t]
1465      "-"
1466      ["Macro ..." TeX-insert-macro
1467       :help "Insert a macro and possibly arguments"]
1468      ["Complete" TeX-complete-symbol
1469       :help "Complete the current macro or environment name"]
1470      ["Show ConTeXt Macro Definition" ConTeXt-etexshow]
1471      "-"
1472      (,ConTeXt-environment-menu-name)
1473      (,ConTeXt-environment-modify-menu-name)
1474      ["Item" ConTeXt-insert-item
1475       :help "Insert a new \\item into current environment"]
1476      (,ConTeXt-define-menu-name)
1477      (,ConTeXt-setup-menu-name)
1478      (,ConTeXt-other-macro-menu-name)
1479      "-"
1480      ("Insert Font"
1481       ["Emphasize"  (TeX-font nil ?\C-e) :keys "C-c C-f C-e"]
1482       ["Bold"       (TeX-font nil ?\C-b) :keys "C-c C-f C-b"]
1483       ["Typewriter" (TeX-font nil ?\C-t) :keys "C-c C-f C-t"]
1484       ["Small Caps" (TeX-font nil ?\C-c) :keys "C-c C-f C-c"]
1485       ["Sans Serif" (TeX-font nil ?\C-f) :keys "C-c C-f C-f"]
1486       ["Italic"     (TeX-font nil ?\C-i) :keys "C-c C-f C-i"]
1487       ["Slanted"    (TeX-font nil ?\C-s) :keys "C-c C-f C-s"]
1488       ["Roman"      (TeX-font nil ?\C-r) :keys "C-c C-f C-r"]
1489       ["Calligraphic" (TeX-font nil ?\C-a) :keys "C-c C-f C-a"])
1490      ("Replace Font"
1491       ["Emphasize"  (TeX-font t ?\C-e) :keys "C-u C-c C-f C-e"]
1492       ["Bold"       (TeX-font t ?\C-b) :keys "C-u C-c C-f C-b"]
1493       ["Typewriter" (TeX-font t ?\C-t) :keys "C-u C-c C-f C-t"]
1494       ["Small Caps" (TeX-font t ?\C-c) :keys "C-u C-c C-f C-c"]
1495       ["Sans Serif" (TeX-font t ?\C-f) :keys "C-u C-c C-f C-f"]
1496       ["Italic"     (TeX-font t ?\C-i) :keys "C-u C-c C-f C-i"]
1497       ["Slanted"    (TeX-font t ?\C-s) :keys "C-u C-c C-f C-s"]
1498       ["Roman"      (TeX-font t ?\C-r) :keys "C-u C-c C-f C-r"]
1499       ["Calligraphic" (TeX-font t ?\C-a) :keys "C-u C-c C-f C-a"])
1500      ["Delete Font" (TeX-font t ?\C-d) :keys "C-c C-f C-d"]
1501      "-"
1502      ["Comment or Uncomment Region"
1503       TeX-comment-or-uncomment-region
1504       :help "Make the selected region outcommented or active again"]
1505      ["Comment or Uncomment Paragraph"
1506       TeX-comment-or-uncomment-paragraph
1507       :help "Make the current paragraph outcommented or active again"]
1508      ,TeX-fold-menu
1509      "-" . ,TeX-common-menu-entries)))
1510
1511 (defun ConTeXt-menu-update (&optional menu)
1512   "Update entries on AUCTeX menu."
1513   (or (not (memq major-mode '(context-mode)))
1514       (null ConTeXt-menu-changed)
1515       (not (fboundp 'easy-menu-change))
1516       (progn
1517         (TeX-update-style)
1518         (setq ConTeXt-menu-changed nil)
1519         (message "Updating section menu...")
1520         (mapc 'ConTeXt-section-enable ConTeXt-section-list)
1521         (message "Updating environment menu...")
1522         (easy-menu-change '("ConTeXt") ConTeXt-environment-menu-name
1523                           (LaTeX-split-long-menu
1524                            (mapcar 'ConTeXt-environment-menu-entry
1525                                    (ConTeXt-environment-list))))
1526         (message "Updating modify environment menu...")
1527         (easy-menu-change '("ConTeXt") ConTeXt-environment-modify-menu-name
1528                           (LaTeX-split-long-menu
1529                            (mapcar 'ConTeXt-environment-modify-menu-entry
1530                                    (ConTeXt-environment-list))))
1531         (message "Updating define menu...")
1532         (easy-menu-change '("ConTeXt") ConTeXt-define-menu-name
1533                           (LaTeX-split-long-menu
1534                            (mapcar 'ConTeXt-define-menu-entry
1535                                    ConTeXt-define-list)))
1536         (message "Updating setup menu...")
1537         (easy-menu-change '("ConTeXt") ConTeXt-setup-menu-name
1538                           (LaTeX-split-long-menu
1539                            (mapcar 'ConTeXt-setup-menu-entry
1540                                    ConTeXt-setup-list)))
1541         (message "Updating referencing menu...")
1542         (easy-menu-change '("ConTeXt") ConTeXt-referencing-menu-name
1543                           (LaTeX-split-long-menu
1544                            (mapcar 'ConTeXt-referencing-menu-entry
1545                                    ConTeXt-referencing-list)))
1546         (message "Updating other macro's menu...")
1547         (easy-menu-change '("ConTeXt") ConTeXt-other-macro-menu-name
1548                           (LaTeX-split-long-menu
1549                            (mapcar 'ConTeXt-other-macro-menu-entry
1550                                    ConTeXt-other-macro-list)))
1551         (message "Updating project structure menu...")
1552         (easy-menu-change '("ConTeXt") ConTeXt-project-structure-menu-name
1553                           (LaTeX-split-long-menu
1554                            (mapcar 'ConTeXt-project-structure-menu-entry
1555                                    ConTeXt-project-structure-list)))
1556         (message "Updating section block menu...")
1557         (easy-menu-change '("ConTeXt") ConTeXt-section-block-menu-name
1558                           (LaTeX-split-long-menu
1559                            (mapcar 'ConTeXt-section-block-menu-entry
1560                                    ConTeXt-section-block-list)))
1561         (message "Updating section menu...")
1562         (easy-menu-change '("ConTeXt") ConTeXt-numbered-section-menu-name
1563                           (LaTeX-split-long-menu
1564                            (mapcar 'ConTeXt-numbered-section-menu-entry
1565                                    ConTeXt-numbered-section-list)))
1566         (easy-menu-change '("ConTeXt") ConTeXt-unnumbered-section-menu-name
1567                           (LaTeX-split-long-menu
1568                            (mapcar 'ConTeXt-unnumbered-section-menu-entry
1569                                    ConTeXt-unnumbered-section-list)))
1570         (message "Updating...done")
1571         (and menu (easy-menu-return-item ConTeXt-mode-menu menu))
1572         )))
1573
1574 ;;; Option expander
1575
1576 (defvar ConTeXt-texexec-option-nonstop "--nonstop "
1577   "Command line option for texexec to use nonstopmode.")
1578
1579 (defun ConTeXt-expand-options ()
1580   "Expand options for context command."
1581   (concat
1582    (let ((engine (eval (nth 4 (assq TeX-engine (TeX-engine-alist))))))
1583      (when engine
1584        (format "--engine=%s " engine)))
1585    (unless (eq ConTeXt-current-interface "en")
1586      (format "--interface=%s " ConTeXt-current-interface))
1587    (when TeX-source-correlate-mode
1588      (format "--passon=\"%s\" "
1589              (if (eq (TeX-source-correlate-method-active) 'synctex)
1590                  TeX-synctex-tex-flags
1591                TeX-source-specials-tex-flags)))
1592    (unless TeX-interactive-mode
1593      ConTeXt-texexec-option-nonstop)))
1594
1595 ;;; Mode
1596
1597 ;; ConTeXt variables that are interface aware
1598 ;; They are mapped to interface specific variables
1599
1600 (defvar ConTeXt-language-variable-list
1601   '(ConTeXt-define-list
1602     ConTeXt-setup-list
1603     ConTeXt-referencing-list
1604     ConTeXt-other-macro-list
1605     ConTeXt-project-structure-list
1606     ConTeXt-section-block-list
1607     ConTeXt-numbered-section-list
1608     ConTeXt-unnumbered-section-list
1609     ConTeXt-section-list
1610     ConTeXt-text
1611     ConTeXt-item-list
1612     ConTeXt-extra-paragraph-commands))
1613
1614 (defcustom ConTeXt-clean-intermediate-suffixes
1615   ;; See *suffixes in texutil.pl.
1616   '("\\.tui" "\\.tup" "\\.ted" "\\.tes" "\\.top" "\\.log" "\\.tmp" "\\.run"
1617     "\\.bck" "\\.rlg" "\\.mpt" "\\.mpx" "\\.mpd" "\\.mpo" "\\.tuo" "\\.tub"
1618     "\\.top" "-mpgraph\\.mp" "-mpgraph\\.mpd" "-mpgraph\\.mpo" "-mpgraph\\.mpy"
1619     "-mprun\\.mp" "-mprun\\.mpd" "-mprun\\.mpo" "-mprun\\.mpy")
1620   "List of regexps matching suffixes of files to be deleted.
1621 The regexps will be anchored at the end of the file name to be matched,
1622 i.e. you do _not_ have to cater for this yourself by adding \\\\' or $."
1623   :type '(repeat regexp)
1624   :group 'TeX-command)
1625
1626 (defcustom ConTeXt-clean-output-suffixes
1627   '("\\.dvi" "\\.pdf" "\\.ps")
1628   "List of regexps matching suffixes of files to be deleted.
1629 The regexps will be anchored at the end of the file name to be matched,
1630 i.e. you do _not_ have to cater for this yourself by adding \\\\' or $."
1631   :type '(repeat regexp)
1632   :group 'TeX-command)
1633
1634 (TeX-abbrev-mode-setup context-mode)
1635
1636 (defun ConTeXt-mode-common-initialization ()
1637   "Initialization code that is common for all ConTeXt interfaces."
1638   ;; `plain-TeX-common-initialization' kills all local variables, but
1639   ;; we need to keep ConTeXt-current-interface, so save and restore
1640   ;; it.
1641   (let (save-ConTeXt-current-interface)
1642     (setq save-ConTeXt-current-interface ConTeXt-current-interface)
1643     (plain-TeX-common-initialization)
1644     (setq ConTeXt-current-interface save-ConTeXt-current-interface))
1645   (setq major-mode 'context-mode)
1646
1647   (setq local-abbrev-table context-mode-abbrev-table)
1648
1649   ;; Make language specific variables buffer local
1650   (dolist (symbol ConTeXt-language-variable-list)
1651     (make-variable-buffer-local symbol))
1652
1653   (require (intern (concat "context-" ConTeXt-current-interface)))
1654   (dolist (symbol ConTeXt-language-variable-list)
1655     (set symbol (symbol-value (intern (concat (symbol-name symbol) "-"
1656                                               ConTeXt-current-interface)))))
1657
1658   ;; Create certain regular expressions based on language
1659   (setq ConTeXt-indent-item-re (concat "\\\\\\(" (mapconcat 'identity ConTeXt-item-list "\\|") "\\)\\>"))
1660
1661   ;; What's the deepest level at we can collapse a document?
1662   ;; set only if user has not set it. Need to be set before menu is created.
1663   ;; level 2 is "section"
1664   (or ConTeXt-largest-level
1665       (setq ConTeXt-largest-level 2))
1666
1667   ;; keybindings
1668   (use-local-map ConTeXt-mode-map)
1669
1670   ;; Indenting
1671   (set (make-local-variable 'indent-line-function) 'ConTeXt-indent-line)
1672   (set (make-local-variable 'fill-indent-according-to-mode) t)
1673
1674   ;; Paragraph formatting
1675   (set (make-local-variable 'LaTeX-syntactic-comments) nil)
1676   (set (make-local-variable 'LaTeX-paragraph-commands-regexp)
1677        (ConTeXt-paragraph-commands-regexp))
1678   (set (make-local-variable 'paragraph-ignore-fill-prefix) t)
1679   (set (make-local-variable 'fill-paragraph-function) 'LaTeX-fill-paragraph)
1680   (set (make-local-variable 'adaptive-fill-mode) nil)
1681   (setq paragraph-start
1682         (concat
1683          "[ \t]*\\("
1684          (ConTeXt-paragraph-commands-regexp) "\\|"
1685          "\\$\\$\\|" ; Plain TeX display math
1686          "$\\)"))
1687   (setq paragraph-separate
1688         (concat
1689          "[ \t]*\\("
1690          "\\$\\$" ; Plain TeX display math
1691          "\\|$\\)"))
1692
1693   ;; Keybindings and menu
1694   (use-local-map ConTeXt-mode-map)
1695   (easy-menu-add ConTeXt-mode-menu ConTeXt-mode-map)
1696   (easy-menu-add ConTeXt-mode-command-menu ConTeXt-mode-map)
1697   (setq ConTeXt-menu-changed t)
1698
1699   (if (= emacs-major-version 20)
1700       (make-local-hook 'activate-menubar-hook))
1701   (add-hook 'activate-menubar-hook 'ConTeXt-menu-update nil t)
1702
1703   ;; Outline support
1704   (require 'outline)
1705   (set (make-local-variable 'outline-level) 'ConTeXt-outline-level)
1706   (set (make-local-variable 'outline-regexp) (ConTeXt-outline-regexp t))
1707   ;;(make-local-variable 'outline-heading-end-regexp)
1708   (setq TeX-header-end (ConTeXt-header-end)
1709         TeX-trailer-start (ConTeXt-trailer-start))
1710
1711   ;; font switch support
1712   (set (make-local-variable 'TeX-font-list) ConTeXt-font-list)
1713
1714   ;; imenu support
1715   (set (make-local-variable 'imenu-create-index-function)
1716        'ConTeXt-imenu-create-index-function)
1717
1718   ;; run hooks
1719   (setq TeX-command-default "ConTeXt")
1720   (setq TeX-sentinel-default-function 'TeX-ConTeXt-sentinel)
1721   (TeX-run-mode-hooks 'text-mode-hook 'TeX-mode-hook 'ConTeXt-mode-hook))
1722
1723 (defun context-guess-current-interface ()
1724   "Guess what ConTeXt interface the current buffer is using."
1725   (interactive)
1726   (save-excursion
1727     (goto-char (point-min))
1728     (setq ConTeXt-current-interface
1729           (cond ((re-search-forward "%.*?interface=en" (+ 512 (point)) t)
1730                  "en")
1731                 ((re-search-forward "%.*?interface=nl" (+ 512 (point)) t)
1732                  "nl")
1733                 ((re-search-forward "\\\\starttext" (+ 1024 (point)) t)
1734                  "en")
1735                 ((re-search-forward "\\\\starttekst" (+ 1024 (point)) t)
1736                  "nl")
1737                 (t
1738                  ConTeXt-default-interface)))))
1739
1740 ;;;###autoload
1741 (defalias 'ConTeXt-mode 'context-mode)
1742
1743 ;;;###autoload
1744 (defun context-mode ()
1745   "Major mode in AUCTeX for editing ConTeXt files.
1746
1747 Special commands:
1748 \\{ConTeXt-mode-map}
1749
1750 Entering `context-mode' calls the value of `text-mode-hook',
1751 then the value of `TeX-mode-hook', and then the value
1752 of ConTeXt-mode-hook."
1753   (interactive)
1754   (context-guess-current-interface)
1755   (require (intern (concat "context-" ConTeXt-current-interface)))
1756   (funcall (intern (concat "context-" ConTeXt-current-interface "-mode"))))
1757
1758 (provide 'context)
1759
1760 ;;; context.el ends here