Initial Commit
[packages] / xemacs-packages / x-symbol / lisp / x-symbol-tex.el
1 ;;; x-symbol-tex.el --- token language "TeX macro" for package x-symbol
2
3 ;; Copyright (C) 1996-2003 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Christoph Wedler <wedler@users.sourceforge.net>
6 ;; Maintainer: (Please use `M-x x-symbol-package-bug' to contact the maintainer)
7 ;; Version: 4.5.X
8 ;; Keywords: WYSIWYG, LaTeX, wp, math, internationalization
9 ;; X-URL: http://x-symbol.sourceforge.net/
10
11 ;; This program is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15 ;;
16 ;; This program is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20 ;;
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with this program; if not, write to the Free Software
23 ;; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24
25 ;;; Commentary:
26
27 ;; If you want to use package x-symbol, please visit the URL (use
28 ;; \\[x-symbol-package-web]) and read the info (use \\[x-symbol-package-info]).
29
30 ;; Token language tex is registered in x-symbol-hooks.
31
32 ;;; Code:
33
34 (provide 'x-symbol-tex)
35
36 (eval-when-compile
37   (require 'cl)
38   (require 'x-symbol-macs)
39   (require 'x-symbol))
40
41 (eval-when-compile
42   (defvar TeX-master)
43   (defvar file) (defvar line) (defvar offset)
44   (defvar string) (defvar after-string))
45
46 ;; (defgroup x-symbol-tex ...) in x-symbol-hooks.el
47 ;; (defcustom x-symbol-tex-name ...) in x-symbol-hooks.el
48 ;; (defcustom x-symbol-tex-modes ...) in x-symbol-hooks.el
49
50
51 ;;;===========================================================================
52 ;;;  Auto-style
53 ;;;===========================================================================
54
55 (defcustom x-symbol-tex-auto-style
56   '(;; during eval, `buffer-file-name' is sans-version and mode-suffixes
57     (if buffer-file-name (string-match "\\.tex\\'" buffer-file-name) t)
58     (if x-symbol-mode
59         (x-symbol-auto-coding-alist x-symbol-tex-auto-coding-alist nil
60                                     (if x-symbol-tex-coding-master
61                                         'x-symbol-tex-auto-coding-alist)))
62     x-symbol-coding (not x-symbol-mode)
63     x-symbol-mode x-symbol-mode)
64   "Values for X-Symbol's buffer-local variables with language `tex'.
65 See language access `x-symbol-LANG-auto-style'."
66   :group 'x-symbol-tex
67   :group 'x-symbol-mode
68   :type 'x-symbol-auto-style)
69
70 (defcustom x-symbol-tex-auto-coding-alist
71   '(("\\\\usepackage[ \t]*\\[\\([A-Za-z]+[0-9]+\\)\\]{inputenc}" 1
72      ("latin1" . iso-8859-1)
73      ("latin2" . iso-8859-2)
74      ("latin3" . iso-8859-3)
75      ("latin5" . iso-8859-9)
76      ("latin9" . iso-8859-15))
77     ("\\`[ \t]*%&.*[  \t]+--?translate-file[ \t]*=[ \t]*i\\([A-Za-z]+[0-9]+\\)-" 1
78      ("l1" . iso-8859-1)
79      ("l2" . iso-8859-2)))
80   "*Alist used to determine the file coding with language `tex'.
81 Used in the default value of `x-symbol-tex-auto-style'.  See variable
82 `x-symbol-auto-coding-alist' for details."
83   :group 'x-symbol-tex
84   :group 'x-symbol-mode
85   :type 'x-symbol-auto-coding)
86
87 (defcustom x-symbol-tex-coding-master 'TeX-master
88   "*If non-nil, symbol of local variable with name of master file.
89 Used inside function `x-symbol-tex-auto-coding-alist'."
90   :group 'x-symbol-tex
91   :group 'x-symbol-mode
92   :type 'boolean)
93
94
95 ;;;===========================================================================
96 ;;;  General language accesses, see `x-symbol-language-access-alist'
97 ;;;===========================================================================
98
99 (defcustom x-symbol-tex-modeline-name "tex"
100   "Modeline name of token language `tex'.
101 See language access `x-symbol-LANG-modeline-name'."
102   :group 'x-symbol-tex
103   :type 'string)
104
105 (defcustom x-symbol-tex-header-groups-alist nil
106   "Header/submenu specification of the specific menu for language `tex'.
107 See language access `x-symbol-LANG-header-groups-alist'."
108   :group 'x-symbol-tex
109   :group 'x-symbol-input-init
110   :type 'x-symbol-headers)
111
112 (defcustom x-symbol-tex-electric-ignore 'x-symbol-tex-default-electric-ignore
113   "Specification restricting input method ELECTRIC with language `tex'.
114 See language access `x-symbol-LANG-electric-ignore'."
115   :group 'x-symbol-tex
116   :group 'x-symbol-input-control
117   :type 'x-symbol-function-or-regexp)
118
119 (defcustom x-symbol-tex-electric-ignore-regexp "[A-Za-z]~\\'"
120   "*Regexp matching contexts not to be used for input method ELECTRIC.
121 Used by `x-symbol-tex-default-electric-ignore'."
122   :group 'x-symbol-tex
123   :group 'x-symbol-input-control
124   :type '(choice (const :tag "None" nil) regexp))
125
126 (defcustom x-symbol-tex-token-suppress-space t
127   "*If non-nil, suppress space after text-mode control words.
128 If non-nil, inserting SPC without prefix argument after a text-mode only
129 control word will only replace the control word with the character
130 according to `x-symbol-token-input', it will not insert the space."
131   :group 'x-symbol-tex
132   :group 'x-symbol-input-control
133   :type 'boolean)
134
135 (defvar x-symbol-tex-extra-menu-items
136   '(("Conversion"
137      "---"
138      ["tex: Decode Accented Letters (alt)" x-symbol-tex-xdecode-latex
139       :active (and x-symbol-mode (not buffer-read-only))]
140      ["tex: Remove Braces around Letters" x-symbol-tex-xdecode-old
141       :active (and x-symbol-mode (not buffer-read-only))]))
142   "Extra menu entries in menu for language `tex'.
143 See language access `x-symbol-LANG-extra-menu-items'.")
144
145 (defvar x-symbol-tex-token-grammar
146   '(x-symbol-make-grammar
147     :encode-spec x-symbol-tex-encode
148     :decode-regexp "\\\\\\(?:[@A-Za-z]+\\|[-{}#_&|%$]\\|[.~^\"'`=]\\(?:[A-Za-z]\\|{}\\|\\(\\\\\\)[ij][@A-Za-z]?\\)\\)"
149     :decode-spec x-symbol-tex-decode
150     :input-regexp ("\\\\\\(?:[.~^\"'`=]\\\\[ij]\\|[ckvuHr]\\(?: [A-Za-z]\\|{ ?}\\)\\)\\'" "\\\\\\(?:[@A-Za-z]+\\|[-{}#_&|%$]\\|[.~^\"'`=]\\(?:[A-Za-z]\\|{}\\)\\)\\'")
151     :input-spec x-symbol-tex-token-input
152     :token-list x-symbol-tex-default-token-list
153     :after-init x-symbol-tex-after-init-language)
154   "Grammar of token language `tex'.
155 See language access `x-symbol-LANG-token-grammar'.")
156
157 ;; The following vars could be made customizable, but it would not be a good
158 ;; idea if different users have a different decode behavior:
159
160 (defvar x-symbol-tex-verb-delimiter-regexp "[-!#$&*+/=?^|~]"
161   "Regexp matching delimiters of \verb arguments not to be decoded.")
162 ;; by default: not letter, digits, punctuation and quotation
163
164 (defvar x-symbol-tex-env-verbatim-regexp "{verbatim\\*?}"
165   "Regexp matching environments with a contents not to be decoded.
166 The regexp should also match the surrounding braces.")
167
168 (defvar x-symbol-tex-env-tabbing-regexp "{tabbing}"
169   "Regexp matching environments with a contents not to be decoded.
170 The regexp should also match the surrounding braces.")
171
172 (defvar x-symbol-tex-user-table nil
173   "User table defining TeX macros, used in `x-symbol-tex-table'.")
174
175 (defvar x-symbol-tex-generated-data nil
176   "Generated data for token language `tex'.
177 See language access `x-symbol-LANG-generated-data'.")
178
179
180 ;;;===========================================================================
181 ;;;  Image support
182 ;;;===========================================================================
183
184 (defcustom x-symbol-tex-master-directory 'x-symbol-tex-default-master-directory
185   "Specification of the master directory for images for language `tex'.
186 See language access `x-symbol-LANG-master-directory'."
187   :group 'x-symbol-tex
188   :group 'x-symbol-image-language
189   :type 'function)
190
191 (defcustom x-symbol-tex-image-searchpath
192   (let ((dirs (or (getenv "TEXPICTS") (getenv "TEXINPUTS")))
193         dir result)
194     (if dirs (setq dirs (if (fboundp 'split-path)
195                             (split-path dirs)
196                           (parse-colon-path dirs))))
197     (while dirs
198       (when (setq dir (pop dirs))
199         (or (member dir '("" "/"))      ; `parse-colon-path': foo// -> /
200             (member (setq dir (file-name-as-directory dir)) result)
201             (push dir result))))
202     (nreverse (if (member "./" result) result (cons "./" result))))
203   "Search path for implicitly relative image file names.
204 See language access `x-symbol-LANG-image-searchpath'."
205   :group 'x-symbol-tex
206   :group 'x-symbol-image-language
207   :type '(repeat directory))
208
209 (defcustom x-symbol-tex-image-cached-dirs '("figures/")
210   "Directory parts of images stored in the memory cache.
211 See language access `x-symbol-LANG-image-cached-dirs'."
212   :group 'x-symbol-tex
213   :group 'x-symbol-image-language
214   :type '(repeat string))
215
216 (defcustom x-symbol-tex-image-keywords
217   ;; keep it short!
218   '("\\.\\(eps\\|ps\\(tex\\)?\\|gif\\|png\\|jpe?g\\|pdf\\)\\'"
219     ("\\\\epsf\\(box\\|file\\)[ \t]*\\(\\[[^][\n]*\\]\\)?{\\([^ \t\n,{}]+\\.e?ps\\)}" 3)
220     ("\\\\e?psfig[ \t]*{file=\\([^ \t\n,{}]+\\.e?ps\\)[^\n{}]*}" 1)
221     ("\\\\includegraphics\\*?[ \t]*\\(\\[[^][\n]*\\]\\)?\\(\\[[^][\n]*\\]\\)?{\\([^ \t\n,{}]+\\)}" 3 ".\\.[^./]+\\'" ".eps")
222     ("\\\\input[ \t]*{\\([^ \t\n,{}]+\\.pstex\\)_t}" 1))
223   "Keywords for image insertion commands of language `tex'.
224 See language access `x-symbol-LANG-image-keywords'."
225   :group 'x-symbol-tex
226   :group 'x-symbol-image-language
227   :type 'x-symbol-image-keywords)
228
229
230 ;;;===========================================================================
231 ;;;  Super- and Subscripts
232 ;;;===========================================================================
233
234 (defcustom x-symbol-tex-subscript-matcher 'x-symbol-tex-subscript-matcher
235   "Function matching super-/subscripts for language `tex'.
236 See language access `x-symbol-LANG-subscript-matcher'."
237   :group 'x-symbol-tex
238   :type 'function)
239
240 (defcustom x-symbol-tex-invisible-braces nil
241   "TODO"
242   :group 'x-symbol-tex
243   :type 'boolean)
244
245 (defcustom x-symbol-tex-font-lock-allowed-faces
246   '(tex-math-face
247     font-lock-string-face font-lock-doc-string-face font-latex-math-face)
248   "*Faces which are allowed when fontifying simple super- and subscripts.
249 Package x-symbol only uses super- and subscripts if they are in braces,
250 if the \"^\"/\"_\" has not been fontified yet or is only fontified with
251 faces which appear in this list.  Value t means, always use super- and
252 subscripts."
253   :group 'x-symbol-tex
254   :type '(repeat (symbol :tag "Face name"))) ; face would create faces... :-(
255
256 (defvar x-symbol-tex-font-lock-regexp
257   "[^\000-\040\134\177-\237]\\([_^]\\)\\([^ \t\n\f%\\}^_$#&~]\\|\\\\[@A-Za-z]+\\)"
258   "Regexp matching the prefix of super-/subscripts.
259 The first regexp group should match the super-/subscript command.")
260
261 (defvar x-symbol-tex-font-lock-limit-regexp "[\n^_]"
262   "Regexp matching the limit for the end of super-/subscripts.
263 This regexp should match the end of line.")
264
265
266 ;;;===========================================================================
267 ;;;  Charsym Info
268 ;;;===========================================================================
269
270 (defface x-symbol-tex-math-face
271   '((((class color) (background light))
272      (:foreground "purple3")))
273   "*Face, normally used for tokens only allowed in TeX's math mode.
274 Used in `x-symbol-tex-class-face-alist'."
275   :group 'x-symbol-tex
276   :group 'x-symbol-info-general)
277
278 (defface x-symbol-tex-text-face
279   '((((class color) (background light))
280      (:foreground "Royalblue")))
281   "*Face, normally used for tokens only allowed in TeX's text mode.
282 Used in `x-symbol-tex-class-face-alist'."
283   :group 'x-symbol-tex
284   :group 'x-symbol-info-general)
285
286 (defcustom x-symbol-tex-class-alist
287   '((text)
288     (math)
289     (accent "accent" (x-symbol-info-face))
290     (aletter "acc.letter" (x-symbol-info-face))
291     (letter "letter" (x-symbol-info-face))
292     (greek "greek" (x-symbol-info-face))
293     (ordinary "ordinary" (x-symbol-info-face))
294     (binop "binop" (x-symbol-info-face))
295     (bigop "bigop" (x-symbol-info-face))
296     (relation "relation" (x-symbol-info-face))
297     (delim "delimiter" (x-symbol-info-face))
298     (punct "punctuation" (x-symbol-info-face))
299     (quote "quote" (x-symbol-info-face))
300     (space "space" (x-symbol-info-face))
301     (special "special" (x-symbol-info-face))
302     (latexsym "latexsym.sty" (x-symbol-emph-info-face)) ; w/ latexsym or amssymb
303     (amssymb "amssymb.sty" (x-symbol-emph-info-face))
304     (stmaryrd "stmaryrd.sty" (x-symbol-emph-info-face))
305     (T1 "T1 fontenc.sty" (x-symbol-emph-info-face))
306     (correct-T1 "correct: T1 fontenc.sty" (x-symbol-info-face))
307     (inputenc "inputenc.sty" (x-symbol-emph-info-face)) ; v0.97
308     (inputenc-unavail "inputenc.sty: unavailable" (x-symbol-emph-info-face))
309 ;;;    (inputenc-incorrect "old inputenc: incorrect" . red) ; IMHO
310     (gobbles-spc "gobbles space" (x-symbol-info-face))
311     (user "user" (x-symbol-emph-info-face))
312     (VALID "unknown TeX class" (x-symbol-emph-info-face))
313     (INVALID "no TeX macro" (x-symbol-emph-info-face)))
314   "Token classes displayed by info in echo area, for language `tex'.
315 See language access `x-symbol-LANG-class-alist'."
316   :group 'x-symbol-tex
317   :group 'x-symbol-info-strings
318   :type 'x-symbol-class-info)
319
320 (defcustom x-symbol-tex-class-face-alist
321   '((math x-symbol-tex-math-face (x-symbol-tex-math-face))
322     (text x-symbol-tex-text-face (x-symbol-tex-text-face)))
323   "Color scheme in language specific grid and info, for language `tex'.
324 See language access `x-symbol-LANG-class-face-alist'."
325   :group 'x-symbol-tex
326   :group 'x-symbol-input-init
327   :group 'x-symbol-info-general
328   :type 'x-symbol-class-faces)
329
330
331 ;;;===========================================================================
332 ;;;  Misc
333 ;;;===========================================================================
334
335 ;;;###autoload
336 (defun x-symbol-tex-auto-coding-alist (alist &optional limit)
337   "Find encoding in file `x-symbol-tex-coding-master'.
338 For ALIST and LIMIT, see `x-symbol-auto-coding-alist'."
339   ;; called inside `save-excursion'
340   (and (local-variable-p x-symbol-tex-coding-master (current-buffer))
341        ;; I don't like the idea of having to visit a second file in order to
342        ;; visit first one, but people have complained about X-Symbol not
343        ;; recognizing \usepackage[latinN]{inputenc} in the master file...  Not
344        ;; only that, a file should describe its encoding itself...
345        (stringp (symbol-value x-symbol-tex-coding-master))
346        (condition-case nil
347            (let ((master (expand-file-name
348                           (symbol-value x-symbol-tex-coding-master))))
349              ;; I have absolutely no intention to use `find-file-noselect'
350              ;; here, i.e., decode the master file via X-Symbol in order to get
351              ;; the correct coding for the current buffer
352              (set-buffer (get-buffer-create " x-symbol master"))
353              (insert-file-contents master nil nil nil
354                                    ;; 5th arg not t with empty accessible part
355                                    ;; (XEmacs bug workaround: would infloop)
356                                    (> (point-max) (point-min)))
357              (x-symbol-auto-coding-alist alist limit))
358          (error nil))))
359
360 (defun x-symbol-tex-default-master-directory ()
361   "Convert NAME to absolute file name, respecting `TeX-master'.
362 Variable `TeX-master' should be buffer-local and a string to be used.
363 Used as default value of `x-symbol-tex-master-directory'."
364   (and (local-variable-p 'TeX-master (current-buffer))
365        (stringp TeX-master)
366        (file-name-directory (expand-file-name TeX-master))))
367
368 (defun x-symbol-tex-default-electric-ignore (context charsym)
369   "Non nil, if CONTEXT should not be replaced by input method ELECTRIC.
370 Return non-nil if `x-symbol-tex-electric-ignore-regexp' matches CONTEXT
371 or if CHARSYM represents a TeX macro which can only be used in math mode
372 whereas point is in a text area or vice versa.  This function uses
373 package \"texmathp\" whose variables you might want to customize.  Used
374 as default value for `x-symbol-tex-electric-ignore'."
375   (or (and x-symbol-tex-electric-ignore-regexp
376            (string-match x-symbol-tex-electric-ignore-regexp context))
377       (condition-case nil
378           (let ((class (car (gethash charsym
379                                      (x-symbol-generated-token-classes
380                                       x-symbol-tex-generated-data)))))
381             (cond ((eq class 'math) (not (texmathp)))
382                   ((eq class 'text) (texmathp))))
383         (error nil))))
384
385
386 ;;;===========================================================================
387 ;;;  The tables
388 ;;;===========================================================================
389
390 (defun x-symbol-tex-default-token-list (tokens)
391   (if (stringp tokens)
392       (list (cons (if (string-match "\\\\ \\'" tokens)
393                       (concat (substring tokens 0 (match-beginning 0)) "{ }")
394                     tokens)
395                   (if (string-match "\\\\[A-Za-z]+\\'" tokens) t)))
396     (mapcar (lambda (x)
397               (cons x (if (string-match "\\\\[A-Za-z]+\\'" x) 'math)))
398             tokens)))
399
400 (defun x-symbol-tex-after-init-language ()
401   (let ((decode-obarray (x-symbol-generated-decode-obarray
402                          x-symbol-tex-generated-data))
403         (tex-accent '(nil tex-accent)))
404     (set (intern "\\begin" decode-obarray) '(nil tex-begin))
405     (set (intern "\\end" decode-obarray)   '(nil tex-end))
406     (set (intern "\\verb" decode-obarray)  '(nil tex-verb))
407     (set (intern "\\c" decode-obarray) tex-accent)
408     (set (intern "\\k" decode-obarray) tex-accent)
409     (set (intern "\\v" decode-obarray) tex-accent)
410     (set (intern "\\u" decode-obarray) tex-accent)
411     (set (intern "\\H" decode-obarray) tex-accent)
412     (set (intern "\\r" decode-obarray) tex-accent)))
413
414
415 ;;;===========================================================================
416 ;;;  The tables
417 ;;;===========================================================================
418
419 (defvar x-symbol-tex-required-fonts nil
420   "Features providing required fonts for language `tex'.
421 See language access `x-symbol-LANG-required-fonts'.")
422
423 (defvar x-symbol-tex-latin1-table
424   '((nobreakspace (space) . "\\nobreakspace")
425     (exclamdown (text punct) . "\\textexclamdown")
426     (cent (text inputenc-unavail) . "\\textcent")
427     (sterling (ordinary) . "\\pounds")
428     (currency (text inputenc) . "\\textcurrency")
429     (yen (text inputenc-unavail) . "\\textyen")
430     (brokenbar (text inputenc-unavail) . "\\textbrokenbar")
431     (section (ordinary) . "\\S")
432     (diaeresis (text accent) . "\\\"{}")
433     (copyright (text ordinary) . "\\textcopyright")
434     (ordfeminine (text ordinary inputenc) . "\\textordfeminine")
435     (guillemotleft (text quote T1) . "\\guillemotleft")
436     (notsign (math ordinary) "\\lnot" "\\neg")
437     (hyphen (special) "\\-")
438     (registered (text ordinary) . "\\textregistered")
439     (macron (text accent) . "\\={}")
440     (degree (text ordinary inputenc) . "\\textdegree")
441     (plusminus (math binop) "\\pm")
442     (twosuperior (math ordinary inputenc) "\\mathtwosuperior")
443     (threesuperior (math ordinary inputenc) "\\maththreesuperior")
444     (acute (text accent) . "\\'{}")
445     (mu1 (math greek user) "\\mathmicro")
446     (paragraph (ordinary) . "\\P")
447     (periodcentered (text punct) . "\\textperiodcentered")
448     (cedilla (text accent) . "\\c\\ ")
449     (onesuperior (math ordinary inputenc) "\\mathonesuperior")
450     (masculine (text ordinary inputenc) . "\\textordmasculine")
451     (guillemotright (text quote T1) . "\\guillemotright")
452     (onequarter (text ordinary inputenc) . "\\textonequarter")
453     (onehalf (text ordinary inputenc) . "\\textonehalf")
454     (threequarters (text ordinary inputenc) . "\\textthreequarters")
455     (questiondown (text punct) . "\\textquestiondown")
456     (Agrave (text aletter) . "\\`A")
457     (Aacute (text aletter) . "\\'A")
458     (Acircumflex (text aletter) . "\\^A")
459     (Atilde (text aletter) . "\\~A")
460     (Adiaeresis (text aletter) . "\\\"A")
461     (Aring (text aletter) . "\\AA")
462     (AE (text letter) . "\\AE")
463     (Ccedilla (text aletter) . "\\c C")
464     (Egrave (text aletter) . "\\`E")
465     (Eacute (text aletter) . "\\'E")
466     (Ecircumflex (text aletter) . "\\^E")
467     (Ediaeresis (text aletter) . "\\\"E")
468     (Igrave (text aletter) . "\\`I")
469     (Iacute (text aletter) . "\\'I")
470     (Icircumflex (text aletter) . "\\^I")
471     (Idiaeresis (text aletter) . "\\\"I")
472     (ETH (text letter T1) . "\\DH")
473     (Ntilde (text aletter) . "\\~N")
474     (Ograve (text aletter) . "\\`O")
475     (Oacute (text aletter) . "\\'O")
476     (Ocircumflex (text aletter) . "\\^O")
477     (Otilde (text aletter) . "\\~O")
478     (Odiaeresis (text aletter) . "\\\"O")
479     (multiply (math binop) "\\times")
480     (Ooblique (text letter) . "\\O")
481     (Ugrave (text aletter) . "\\`U")
482     (Uacute (text aletter) . "\\'U")
483     (Ucircumflex (text aletter) . "\\^U")
484     (Udiaeresis (text aletter) . "\\\"U")
485     (Yacute (text aletter) . "\\'Y")
486     (THORN (text letter T1) . "\\TH")
487     (ssharp (text letter) . "\\ss")
488     (agrave (text aletter) . "\\`a")
489     (aacute (text aletter) . "\\'a")
490     (acircumflex (text aletter) . "\\^a")
491     (atilde (text aletter) . "\\~a")
492     (adiaeresis (text aletter) . "\\\"a")
493     (aring (text aletter) . "\\aa")
494     (ae (text letter) . "\\ae")
495     (ccedilla (text aletter) . "\\c c")
496     (egrave (text aletter) . "\\`e")
497     (eacute (text aletter) . "\\'e")
498     (ecircumflex (text aletter) . "\\^e")
499     (ediaeresis (text aletter) . "\\\"e")
500     (igrave (text aletter) . "\\`\\i")
501     (iacute (text aletter) . "\\'\\i")
502     (icircumflex (text aletter) . "\\^\\i")
503     (idiaeresis (text aletter) . "\\\"\\i")
504     (eth (text letter T1) . "\\dh")
505     (ntilde (text aletter) . "\\~n")
506     (ograve (text aletter) . "\\`o")
507     (oacute (text aletter) . "\\'o")
508     (ocircumflex (text aletter) . "\\^o")
509     (otilde (text aletter) . "\\~o")
510     (odiaeresis (text aletter) . "\\\"o")
511     (division (math binop) "\\div")
512     (oslash (text letter) . "\\o")
513     (ugrave (text aletter) . "\\`u")
514     (uacute (text aletter) . "\\'u")
515     (ucircumflex (text aletter) . "\\^u")
516     (udiaeresis (text aletter) . "\\\"u")
517     (yacute (text aletter) . "\\'y")
518     (thorn (text letter T1) . "\\th")
519     (ydiaeresis (text aletter) . "\\\"y"))
520   "Table defining TeX macros, see `x-symbol-tex-table'.")
521
522 (defvar x-symbol-tex-latinN-table
523   '((Aogonek (text aletter T1) . "\\k A")
524     (breve (text accent) . "\\u{}")
525     (Lslash (text letter) . "\\L")
526     (Lcaron (text aletter correct-T1) . "\\v L")
527     (Sacute (text aletter) . "\\'S")
528     (Scaron (text aletter) . "\\v S")
529     (Scedilla (text aletter) . "\\c S")
530     (Tcaron (text aletter) . "\\v T")
531     (Zacute (text aletter) . "\\'Z")
532     (Zcaron (text aletter) . "\\v Z")
533     (Zdotaccent (text aletter) . "\\.Z")
534     (aogonek (text aletter T1) . "\\k a")
535     (ogonek (text accent T1) . "\\k\\ ")
536     (lslash (text letter) . "\\l")
537     (lcaron (text aletter correct-T1) . "\\v l")
538     (sacute (text aletter) . "\\'s")
539     (caron (text accent) . "\\v{}")
540     (scaron (text aletter) . "\\v s")
541     (scedilla (text aletter) . "\\c s")
542     (tcaron (text aletter correct-T1) . "\\v t")
543     (zacute (text aletter) . "\\'z")
544     (hungarumlaut (text accent) . "\\H{}")
545     (zcaron (text aletter) . "\\v z")
546     (zdotaccent (text aletter) . "\\.z")
547     (Racute (text aletter) . "\\'R")
548     (Abreve (text aletter) . "\\u A")
549     (Lacute (text aletter) . "\\'L")
550     (Cacute (text aletter) . "\\'C")
551     (Ccaron (text aletter) . "\\v C")
552     (Eogonek (text aletter T1) . "\\k E")
553     (Ecaron (text aletter) . "\\v E")
554     (Dcaron (text aletter) . "\\v D")
555     (Dbar (text letter inputenc T1) . "\\DJ")
556     (Nacute (text aletter) . "\\'N")
557     (Ncaron (text aletter) . "\\v N")
558     (Ohungarumlaut (text aletter) . "\\H O")
559     (Rcaron (text aletter) . "\\v R")
560     (Uring (text aletter) . "\\r U")
561     (Uhungarumlaut (text aletter) . "\\H U")
562     (Tcedilla (text aletter) . "\\c T")
563     (racute (text aletter) . "\\'r")
564     (abreve (text aletter) . "\\u a")
565     (lacute (text aletter) . "\\'l")
566     (cacute (text aletter) . "\\'c")
567     (ccaron (text aletter) . "\\v c")
568     (eogonek (text aletter T1) . "\\k e")
569     (ecaron (text aletter) . "\\v e")
570     (dcaron (text aletter correct-T1) . "\\v d")
571     (dbar (text letter inputenc T1) . "\\dj")
572     (nacute (text aletter) . "\\'n")
573     (ncaron (text aletter) . "\\v n")
574     (ohungarumlaut (text aletter) . "\\H o")
575     (rcaron (text aletter) . "\\v r")
576     (uring (text aletter) . "\\r u")
577     (uhungarumlaut (text aletter) . "\\H u")
578     (tcedilla (text aletter) . "\\c t")
579     (dotaccent (text accent) . "\\.{}")
580     (Hbar (text letter inputenc-unavail) . "\\textmalteseH")
581     (Hcircumflex (text aletter) . "\\^H")
582     (Idotaccent (text aletter) . "\\.I")
583     (Gbreve (text aletter) . "\\u G")
584     (Jcircumflex (text aletter) . "\\^J")
585     (hbar (text letter inputenc-unavail) . "\\textmalteseh")
586     (hcircumflex (text aletter) . "\\^h")
587     (dotlessi (text letter) . "\\i")
588     (gbreve (text aletter) . "\\u g")
589     (jcircumflex (text aletter) . "\\^\\j")
590     (Cdotaccent (text aletter) . "\\.C")
591     (Ccircumflex (text aletter) . "\\^C")
592     (Gdotaccent (text aletter) . "\\.G")
593     (Gcircumflex (text aletter) . "\\^G")
594     (Ubreve (text aletter) . "\\u U")
595     (Scircumflex (text aletter) . "\\^S")
596     (cdotaccent (text aletter) . "\\.c")
597     (ccircumflex (text aletter) . "\\^c")
598     (gdotaccent (text aletter) . "\\.g")
599     (gcircumflex (text aletter) . "\\^g")
600     (ubreve (text aletter) . "\\u u")
601     (scircumflex (text aletter) . "\\^s")
602     (euro (text ordinary inputenc-unavail) . "\\texteuro")
603     (OE (text letter) . "\\OE")
604     (oe (text letter) . "\\oe")
605     (Ydiaeresis (text aletter) . "\\\"Y"))
606   "Table defining TeX macros, see `x-symbol-tex-table'.")
607
608 ;; Characters w/ NEW weren't defined before, w/ (NEW) were defined at other
609 ;; positions.  If we get problems in the nomule version (e.g., w/ font-lock),
610 ;; we could be forced to move these characters to the xsymb1 font.
611 (defvar x-symbol-tex-xsymb0-table
612   ;; With elems (SYMBOL (TEX-CLASS ...) TEX-MACRO ...)
613   '((numbersign1 (ordinary) "\\#")      ; NEW
614     ;;(existential)
615     (suchthat (math relation) "\\ni" "\\owns")
616     (asterisk1 (math binop) "\\ast")            ; NEW
617     ;;(comma1 (mark) "\\quotesinglbase")        ; not in {}! (spacing)
618     (period1 (math punct) "\\ldotp")            ; (NEW)
619     (colon1 (math punct) "\\colon")             ; (NEW)
620     (congruent (math relation) "\\cong")
621     (Delta (math greek) "\\Delta")
622     (Phi (math greek) "\\Phi")
623     (Gamma (math greek) "\\Gamma")
624     (theta1 (math greek) "\\vartheta")
625     (Lambda (math greek) "\\Lambda")
626     (Pi (math greek) "\\Pi")
627     (Theta (math greek) "\\Theta")
628     (Sigma (math greek) "\\Sigma")
629     (sigma1 (math greek) "\\varsigma")
630     (Omega (math greek) "\\Omega")
631     (Xi (math greek) "\\Xi")
632     (Psi (math greek) "\\Psi")
633     ;;(therefore (math relation) "\\therefore")
634     (perpendicular (math ordinary) "\\bot")     ; (NEW)
635     (underscore1 (ordinary) "\\_")      ; NEW
636     ;;(radicalex)
637     (alpha (math greek) "\\alpha")
638     (beta (math greek) "\\beta")
639     (chi (math greek) "\\chi")
640     (delta (math greek) "\\delta")
641     (epsilon (math greek) "\\epsilon")
642     (phi (math greek) "\\phi")
643     (gamma (math greek) "\\gamma")
644     (eta (math greek) "\\eta")
645     (iota (math greek) "\\iota")
646     (phi1 (math greek) "\\varphi")
647     (kappa (math greek) "\\kappa")
648     (lambda (math greek) "\\lambda")
649     (mu (math greek) "\\mu")
650     (nu (math greek) "\\nu")
651     (pi (math greek) "\\pi")
652     (theta (math greek) "\\theta")
653     (rho (math greek) "\\rho")
654     (sigma (math greek) "\\sigma")
655     (tau (math greek) "\\tau")
656     (upsilon (math greek) "\\upsilon")
657     (omega1 (math greek) "\\varpi")
658     (omega (math greek) "\\omega")
659     (xi (math greek) "\\xi")
660     (psi (math greek) "\\psi")
661     (zeta (math greek) "\\zeta")
662     (bar1 (math relation) "\\mid")              ; (NEW)
663     (similar (math relation) "\\sim")
664     (Upsilon1 (math greek) "\\Upsilon")
665     (minute (math ordinary) "\\prime")
666     (lessequal (math relation) "\\leq" "\\le")
667     ;;(fraction)
668     (infinity (math ordinary) "\\infty")
669     (florin (text ordinary user) . "\\textflorin") ; NEW
670     (club (math ordinary) "\\clubsuit")
671     (diamond (math ordinary) "\\diamondsuit")
672     (heart (math ordinary) "\\heartsuit")
673     (spade (math ordinary) "\\spadesuit")
674     (arrowboth (math relation) "\\leftrightarrow")
675     (arrowleft (math relation) "\\gets" "\\leftarrow")
676     (arrowup (math relation delim) "\\uparrow")
677     (arrowright (math relation) "\\to" "\\rightarrow")
678     (arrowdown (math relation delim) "\\downarrow")
679     (ring (text accent) . "\\r{}")      ; NEW
680     ;;(second)
681     (greaterequal (math relation) "\\geq" "\\ge")
682     (proportional (math relation) "\\propto")
683     (partialdiff (math ordinary) "\\partial")
684     (bullet (math binop) "\\bullet")
685     (notequal (math relation) "\\neq" "\\ne")
686     (equivalence (math relation) "\\equiv")
687     (approxequal (math relation) "\\approx")
688     (ellipsis (ordinary gobbles-spc) "\\ldots")
689     ;;(carriagereturn)
690     (aleph (math letter) "\\aleph")
691     (Ifraktur (math letter) "\\Im")
692     (Rfraktur (math letter) "\\Re")
693     (weierstrass (math letter) "\\wp")
694     (circlemultiply (math binop) "\\otimes")
695     (circleplus (math binop) "\\oplus")
696     (emptyset (math ordinary) "\\emptyset")
697     (intersection (math binop) "\\cap")
698     (union (math binop) "\\cup")
699     (propersuperset (math relation) "\\supset")
700     (reflexsuperset (math relation) "\\supseteq")
701     (notsubset (math relation user) "\\nsubset")
702     (propersubset (math relation) "\\subset")
703     (reflexsubset (math relation) "\\subseteq")
704     (element (math relation) "\\in")
705     (notelement (math relation) "\\notin")
706     (angle (ordinary gobbles-spc) "\\angle")
707     (gradient (math ordinary) "\\nabla")
708     (product (math bigop) "\\prod")
709     (radical (math ordinary) "\\surd")
710     (periodcentered1 (math binop) "\\cdot")     ; (NEW)
711     (logicaland (math binop) "\\land" "\\wedge")
712     (logicalor (math binop) "\\lor" "\\vee")
713     (arrowdblboth (math relation) "\\Leftrightarrow" "\\lequiv")
714     (arrowdblleft (math relation) "\\Leftarrow")
715     (arrowdblup (math relation delim) "\\Uparrow")
716     (arrowdblright (math relation) "\\Rightarrow")
717     (arrowdbldown (math relation delim) "\\Downarrow")
718     (lozenge (math ordinary amssymb) "\\lozenge")
719     (angleleft (math delim) "\\langle") ; (NEW)
720     (trademark (text ordinary) . "\\texttrademark")
721     (summation (math bigop) "\\sum")
722     (angleright (math delim) "\\rangle") ; (NEW)
723     (integral (math bigop) "\\int"))
724   "Table defining TeX macros, see `x-symbol-tex-table'.")
725
726 (defvar x-symbol-tex-xsymb1-table
727   ;; With elems (SYMBOL (TEX-CLASS ...) TEX-MACRO ...)
728   '((verticaldots (ordinary gobbles-spc) "\\vdots")
729     (backslash1 (text ordinary) . "\\textbackslash")
730     (dagger (ordinary) . "\\dag")
731     (percent2 (ordinary) "\\%")         ; NEW
732     (guilsinglright (text quote T1) . "\\guilsinglright")
733     (NG (text letter T1) . "\\NG")
734     (dotlessj (text letter) . "\\j")
735     (ng (text letter T1) . "\\ng")
736     (sharp (math ordinary) "\\sharp")
737     (ceilingleft (math delim) "\\lceil")
738     (ceilingright (math delim) "\\rceil")
739     (star (math binop) "\\star")
740     (lozenge1 (math ordinary latexsym) "\\Diamond")
741     (braceleft2 (delim) "\\{")          ; \lbrace is math-only
742     (circleslash (math binop) "\\oslash")
743     (braceright2 (delim) "\\}")         ; \rbrace is math-only
744     (triangle1 (math binop) "\\bigtriangleup")
745     (smltriangleright (math binop) "\\triangleright")
746     (triangleleft (math binop latexsym) "\\lhd")
747     (triangle (math ordinary) "\\triangle")
748     (triangleright (math binop latexsym) "\\rhd")
749     (trianglelefteq (math binop latexsym) "\\unlhd")
750     (trianglerighteq (math binop latexsym) "\\unrhd")
751     (periodcentered2 (math punct) "\\cdotp")
752     (dotequal (math relation) "\\doteq")
753     (wrong (math binop) "\\wr")
754     (natural (math ordinary) "\\natural")
755     (flat (math ordinary) "\\flat")
756     (epsilon1 (math greek) "\\varepsilon")
757     (hbarmath (math letter) "\\hbar")
758     (imath (math letter) "\\imath")
759     (kappa1 (math greek amssymb) "\\varkappa")
760     (jmath (math letter) "\\jmath")
761     (ell (math letter) "\\ell")
762     (amalg (math binop) "\\amalg")
763     (rho1 (math greek) "\\varrho")
764     (top (math ordinary) "\\top")
765     (Mho (math greek latexsym) "\\mho")
766     (floorleft (math delim) "\\lfloor")
767     (floorright (math delim) "\\rfloor")
768     (perpendicular1 (math relation) "\\perp")
769     (box (math ordinary latexsym) "\\Box")
770     (asciicircum1 (text ordinary) . "\\textasciicircum")
771     (asciitilde1 (text ordinary) . "\\textasciitilde")
772     (leadsto (math relation latexsym) "\\leadsto")
773     (longarrowleft (math relation) "\\longleftarrow")
774     (arrowupdown (math relation delim) "\\updownarrow")
775     (longarrowright (math relation) "\\longrightarrow")
776     (longmapsto (math relation) "\\longmapsto")
777     (longarrowdblboth (math relation) "\\Longleftrightarrow")
778     (longarrowdblleft (math relation) "\\Longleftarrow")
779     (arrowdblupdown (math relation delim) "\\Updownarrow")
780     (longarrowdblright (math relation) "\\Longrightarrow")
781     (mapsto (math relation) "\\mapsto")
782     (iff (math relation) "\\iff")
783     (hookleftarrow (math relation) "\\hookleftarrow")
784     (hookrightarrow (math relation) "\\hookrightarrow")
785     (arrownortheast (math relation) "\\nearrow")
786     (arrowsoutheast (math relation) "\\searrow")
787     (arrownorthwest (math relation) "\\nwarrow")
788     (arrowsouthwest (math relation) "\\swarrow")
789     (rightleftharpoons (math relation) "\\rightleftharpoons")
790     (leftharpoondown (math relation) "\\leftharpoondown")
791     (rightharpoondown (math relation) "\\rightharpoondown")
792     (leftharpoonup (math relation) "\\leftharpoonup")
793     (rightharpoonup (math relation) "\\rightharpoonup")
794     (bardbl (math ordinary delim) "\\|") ; removed \Vert
795     (bardbl1 (math relation) "\\parallel")
796     (backslash2 (math ordinary delim) "\\backslash")
797     (backslash3 (math binop) "\\setminus")
798     (diagonaldots (math ordinary) "\\ddots")
799     (simequal (math relation) "\\simeq")
800     (digamma (math ordinary amssymb) "\\digamma")
801     (asym (math relation) "\\asymp")
802     (minusplus (math binop) "\\mp")
803     (bowtie (math relation) "\\bowtie")
804     (centraldots (math ordinary) "\\cdots")
805     (visiblespace (text ordinary) . "\\textvisiblespace")
806     (dagger1 (math binop) "\\dagger")
807     (circledot (math binop) "\\odot")
808     (propersqsuperset (math relation latexsym) "\\sqsupset")
809     (reflexsqsuperset (math relation) "\\sqsupseteq")
810     (gradient1 (math binop) "\\bigtriangledown")
811     (propersqsubset (math relation latexsym) "\\sqsubset")
812     (reflexsqsubset (math relation) "\\sqsubseteq")
813     (smllozenge (math binop) "\\diamond")
814     (lessless (math relation) "\\ll")
815     (greatergreater (math relation) "\\gg")
816     (unionplus (math binop) "\\uplus")
817     (sqintersection (math binop) "\\sqcap")
818     (squnion (math binop) "\\sqcup")
819     (frown (math relation) "\\frown")
820     (smile (math relation) "\\smile")
821     (reflexprec (math relation) "\\preceq")
822     (reflexsucc (math relation) "\\succeq")
823     (properprec (math relation) "\\prec")
824     (propersucc (math relation) "\\succ")
825     (bardash (math relation) "\\vdash")
826     (dashbar (math relation) "\\dashv")
827     (bardashdbl (math relation) "\\models")
828     (smlintegral (math ordinary) "\\smallint")
829     (circleintegral (math bigop) "\\oint")
830     (coproduct (math bigop) "\\coprod")
831     (bigcircledot (math bigop) "\\bigodot")
832     (bigcirclemultiply (math bigop) "\\bigotimes")
833     (bigcircleplus (math bigop) "\\bigoplus")
834     (biglogicaland (math bigop) "\\bigwedge")
835     (biglogicalor (math bigop) "\\bigvee")
836     (bigintersection (math bigop) "\\bigcap")
837     (bigunion (math bigop) "\\bigcup")
838     (bigunionplus (math bigop) "\\biguplus")
839     (bigsqunion (math bigop) "\\bigsqcup")
840     (bigcircle (math binop) "\\bigcirc")
841     (guilsinglleft (text quote T1) . "\\guilsinglleft")
842     (circleminus (math binop) "\\ominus")
843     (smltriangleleft (math binop) "\\triangleleft")
844     (existential1 (math ordinary) "\\exists")
845     (daggerdbl1 (math binop) "\\ddagger")
846     (daggerdbl (ordinary) . "\\ddag")
847     (bigbowtie (math relation latexsym) "\\Join")
848     (circ (math binop) "\\circ")
849     (grave (text accent) . "\\`{}")     ; NEW
850     (circumflex (text accent) . "\\^{}") ; NEW
851     (tilde (text accent) . "\\~{}")     ; NEW
852     (longarrowboth (math relation) "\\longleftrightarrow")
853     (endash (text ordinary) . "\\textendash") ; NEW
854     (emdash (text ordinary) . "\\textemdash")
855     (ampersand2 (ordinary) "\\&")       ; NEW
856     (universal1 (math ordinary) "\\forall")
857     (booleans (math letter user) "\\setB")
858     (complexnums (math letter user) "\\setC")
859     (natnums (math letter user) "\\setN")
860     (rationalnums (math letter user) "\\setQ")
861     (realnums (math letter user) "\\setR")
862     (integers (math letter user) "\\setZ")
863     (lesssim (math relation amssymb) "\\lesssim")
864     (greatersim (math relation amssymb) "\\gtrsim")
865     (lessapprox (math relation amssymb) "\\lessapprox")
866     (greaterapprox (math relation amssymb) "\\gtrapprox")
867     (definedas (math relation amssymb) "\\triangleq")
868     (circleminus1 (math binop amssymb) "\\circleddash")
869     (circleasterisk (math binop amssymb) "\\circledast")
870     (circlecirc (math binop amssymb) "\\circledcirc")
871     (dollar1 (ordinary) "\\$")
872     (therefore1 (math relation amssymb) "\\therefore")
873     (coloncolon (math relation user) "\\coloncolon")
874     (bigsqintersection (math bigop stmaryrd) "\\bigsqcap")
875     (semanticsleft (math delim stmaryrd) "\\llbracket")
876     (semanticsright (math delim stmaryrd) "\\rrbracket")
877     (cataleft (math delim stmaryrd) "\\llparenthesis")
878     (cataright (math delim stmaryrd) "\\rrparenthesis")
879     ;;(quotedblbase (mark T1) "\\quotedblbase") ; not in {}! (spacing)
880     ;;(quotedblleft (mark) . "\\textquotedblleft") ; not in {}! (spacing)
881     ;;(quotedblright (mark) . "\\textquotedblright") ; not in {}! (spacing)
882     ;;(perthousand)
883     )
884   "Table defining TeX macros, see `x-symbol-tex-table'.")
885
886 (defvar x-symbol-tex-table
887   (append x-symbol-tex-user-table
888           '(nil)
889           x-symbol-tex-latin1-table
890           x-symbol-tex-latinN-table
891           x-symbol-tex-xsymb0-table
892           x-symbol-tex-xsymb1-table)
893   "Table defining `tex' tokens for the characters.
894 See language access `x-symbol-LANG-table'.  Use
895 `x-symbol-tex-user-table' to define private TeX macros or shadow
896 existing ones.")
897
898
899 ;;;===========================================================================
900 ;;;  Super- and Subscripts
901 ;;;===========================================================================
902
903 (defun x-symbol-tex-subscript-matcher (limit)
904   (block nil
905     (let (beg mid)
906       (or (bolp) (backward-char))
907       ;; (backward-char) is not necessary in the loop because: if a simple =
908       ;; braces-less subscript is not allowed according to the "allowed" faces,
909       ;; then a directly following _ or ^ is also not allowed...
910       (while (re-search-forward x-symbol-tex-font-lock-regexp limit t)
911         (setq beg (match-beginning 1)
912               mid (match-beginning 2))
913         (if (if (eq (char-after mid) ?\{)
914                 (let ((end (save-restriction
915                              (narrow-to-region
916                               (point)
917                               (save-excursion
918                                 (re-search-forward
919                                  x-symbol-tex-font-lock-limit-regexp
920                                  limit 'limit)
921                                 (point)))
922                              (ignore-errors (scan-lists (point) 1 1)))))
923                   (when (and end (eq (char-before end) ?}))
924                     (goto-char end)
925                     (store-match-data
926                      (if x-symbol-tex-invisible-braces
927                          (list beg end
928                                beg (1+ mid)
929                                (1+ mid) (1- end)
930                                (1- end) end)
931                        (list beg end beg mid mid end)))
932                     t))
933               (or (eq x-symbol-tex-font-lock-allowed-faces t)
934                   (let ((faces (plist-get (text-properties-at beg) 'face)))
935                     (cond ((null faces))
936                           ((consp faces)
937                            (while (and faces (memq (car faces) x-symbol-tex-font-lock-allowed-faces))
938                              (setq faces (cdr faces)))
939                            (null faces))
940                           ((memq faces
941                                  x-symbol-tex-font-lock-allowed-faces))))))
942             (return (if (eq (char-after beg) ?_)
943                         'x-symbol-sub-face
944                       'x-symbol-sup-face)))))))
945
946
947 ;;;===========================================================================
948 ;;;  Conversion
949 ;;;===========================================================================
950
951 (defun x-symbol-tex-encode (encode-table fchar-table fchar-fb-table)
952   (let (char)
953     (x-symbol-encode-for-charsym ((encode-table fchar-table fchar-fb-table)
954                                   token)
955       (and (eq (char-before) ?\\)
956            (x-symbol-even-escapes-before-p (1- (point)) ?\\)
957            (insert ?\ ))
958       (insert (car token))
959       (delete-char x-symbol-encode-rchars)
960       (when (cdr token)                 ; \MACRO
961         (setq char (char-after))
962         (cond ((memq char '(?\ ?\t ?\n ?\r nil))
963                ;; faster than any `looking-at' or `or'ed `eq's
964                (or (eq (cdr token) 'math)
965                    (insert-before-markers "{}")))
966               ((or (and (<= ?a char) (<= char ?z))
967                    (and (<= ?@ char) (<= char ?Z)))
968                ;; much faster than any `looking-at', XEmacs' 3-arg `<=' is
969                ;; slower than `and'ed 2-arg `<='s
970                (insert-before-markers " ")))))))
971
972 (defun x-symbol-tex-decode (decode-regexp decode-obarray unique)
973   (let ((in-tabbing nil)
974         retry charsym after)
975     (x-symbol-decode-for-charsym ((decode-regexp decode-obarray)
976                                   token beg end)
977         (if (setq retry (match-beginning 1))
978             (goto-char retry))
979       (cond ((and (eq (char-before beg) ?\\)
980                   (x-symbol-even-escapes-before-p (1- beg) ?\\))
981              (if (setq retry (match-beginning 1)) (goto-char retry)))
982             ((and in-tabbing
983                   (memq (char-after (1+ beg)) '(?\` ?\' ?= ?-)))
984              (if (setq retry (match-beginning 1)) (goto-char retry)))
985             ((x-symbol-decode-unique-test token unique))
986             ;; would be bad to decode a part only because of unique decoding
987             ((setq charsym (car token))
988              (if (eq (cadr token) t)    ; text-mode \MACRO
989                  (unless
990                      (cond ((eq (setq after (char-after)) ?\ )
991                             (setq after (char-after (incf end)))
992                             (if unique
993                                 (not (or (and (<= ?a after) (<= after ?z))
994                                          (and (<= ?@ after) (<= after ?Z))))
995                               (memq after '(?\ ?\t ?\n ?\r ?% nil))))
996                            ((eq after ?\{)
997                             (if (eq (char-after (incf end)) ?\})
998                                 (or (memq (char-after (incf end))
999                                           '(?\ ?\t ?\n ?\r nil))
1000                                     (decf end 2))
1001                               (decf end))
1002                             nil)
1003                            (t
1004                             (memq (char-after) '(?\t ?\n ?\r ?% nil))))
1005                    (goto-char end)
1006                    (insert-before-markers (gethash charsym
1007                                                    x-symbol-cstring-table))
1008                    (delete-region beg end))
1009                (replace-match (gethash charsym x-symbol-cstring-table) t t)))
1010             ;; special definitions -------------------------------------------
1011             ((eq (setq charsym (cadr token)) 'tex-begin) ; \begin
1012              (skip-chars-forward " \t")
1013              (cond ((looking-at x-symbol-tex-env-verbatim-regexp)
1014                     (setq retry (concat "\\\\end[ \t]*"
1015                                         (regexp-quote (match-string 0))))
1016                     (while (and (re-search-forward retry nil t)
1017                                 (not (x-symbol-even-escapes-before-p
1018                                       (match-beginning 0) ?\\)))))
1019                    ((looking-at x-symbol-tex-env-tabbing-regexp)
1020                     (setq in-tabbing t))))
1021             ((eq charsym 'tex-end)      ; \end
1022              (skip-chars-forward " \t")
1023              (and in-tabbing
1024                   (looking-at x-symbol-tex-env-tabbing-regexp)
1025                   (setq in-tabbing nil)))
1026             ((eq charsym 'tex-verb)     ; \verb
1027              (skip-chars-forward " \t")
1028              (when (looking-at x-symbol-tex-verb-delimiter-regexp)
1029                (setq after (char-after))
1030                (forward-char)
1031                (while (not (or (eq (char-after) after) (eobp)))
1032                  (forward-char))))
1033             ((eq charsym 'tex-accent)   ; accents \c, \k, \v, \u, \H, \r
1034             ;; there are 41 chars using these accents => do something special
1035             ;; here instead using an complicated regexp for the main search
1036              (when (looking-at " [A-Za-z]\\|{}")
1037                (goto-char (setq end (match-end 0)))
1038                (when (setq token (symbol-value
1039                                   (intern-soft (buffer-substring beg end)
1040                                                decode-obarray)))
1041                  (unless (x-symbol-decode-unique-test token unique)
1042                    (goto-char end)
1043                    (insert-before-markers (gethash (car token)
1044                                                    x-symbol-cstring-table))
1045                    (delete-region beg end)))))))))
1046
1047 (defun x-symbol-tex-token-input (input-regexp decode-obarray command-char)
1048   (let ((res (x-symbol-match-token-before
1049               '(?\\ (math . "[a-z@-Z]") (t . "[a-z@-Z]"))
1050               input-regexp decode-obarray command-char)))
1051     (and x-symbol-tex-token-suppress-space
1052          (eq (caddr res) t)             ; text mode \MACRO
1053          (eq command-char ?\ )
1054          (null prefix-arg)
1055          (setq prefix-arg 0))
1056     res))
1057
1058
1059 ;;;===========================================================================
1060 ;;;  AucTeX, preview-latex
1061 ;;;===========================================================================
1062
1063 (defun x-symbol-tex-translate-locations (file-buffer beg end locations)
1064   ;;(set-buffer conv-buffer)
1065   (let ((char-offset (1- beg))
1066         changed
1067         ;; Kludge to prevent undo list truncation:
1068         (undo-limit most-positive-fixnum) ; Emacs
1069         (undo-strong-limit most-positive-fixnum) ; Emacs
1070         (undo-high-threshold -1)        ; XEmacs
1071         (undo-threshold -1))            ; XEmacs
1072     (setq buffer-undo-list t)
1073     (erase-buffer)
1074     (insert-buffer-substring file-buffer beg end)
1075     (map-extents (lambda (e dummy) (delete-extent e) nil))
1076     (setq buffer-undo-list nil)
1077     (x-symbol-encode-all)
1078     (let* ((curr (car locations))
1079            (file (aref curr 0))
1080            (line (aref curr 1))
1081            string after-string)
1082       (while curr
1083         (when buffer-undo-list
1084           (setq string (aref curr 2))
1085           (if (number-or-marker-p string)
1086               (setq string (- string char-offset))
1087             (goto-char 1)
1088             (setq string (or (and (stringp (setq after-string (aref curr 3)))
1089                                   (search-forward (concat string after-string)
1090                                                   nil t)
1091                                   (- (point) (length after-string)))
1092                              (search-forward string nil t))))
1093           (when string
1094             (aset curr 2 (copy-marker string t))
1095             ;; The second arg t is important in both Emacs and XEmacs: this is
1096             ;; a marker which should keep its correct position after the
1097             ;; `primitive-undo's, the encoding has already been done.
1098             (aset curr 3 beg)
1099             (push curr changed)))
1100         (or (and (setq locations (cdr locations))
1101                  (eq line (aref (setq curr (car locations)) 1))
1102                  (equal file (aref curr 0)))
1103             (setq curr nil))))
1104     (when changed
1105       (let ((tail buffer-undo-list)
1106             mpos)
1107         (setq buffer-undo-list t)
1108         (while tail (setq tail (primitive-undo (length tail) tail)))
1109         (dolist (curr changed)
1110           (setq mpos (aref curr 2))
1111           (aset curr 2 (+ char-offset mpos))
1112           (aset curr 3 beg)
1113           (set-marker mpos nil))))
1114     locations))
1115
1116 (put 'x-symbol-tex-error-location 'TeX-translate-via-list
1117      'x-symbol-tex-preview-locations)
1118
1119 (defun x-symbol-tex-error-location ()
1120   (unless (string= string " ")
1121     (save-excursion
1122       (set-buffer (find-file-noselect file))
1123       (when x-symbol-mode
1124         (save-restriction
1125           (widen)
1126           (let ((file-buffer (current-buffer))
1127                 (conv-buffer (get-buffer-create " x-symbol error location"))
1128                 (location (vector nil nil string
1129                                   (and (boundp 'after-string) after-string)))
1130                 beg end pos)
1131             (goto-line (+ offset line))
1132             (setq beg (point))
1133             (end-of-line)
1134             (setq end (point))
1135             (set-buffer conv-buffer)
1136             (erase-buffer)
1137             (when (fboundp 'set-buffer-multibyte)
1138               (set-buffer-multibyte t))
1139             (x-symbol-inherit-from-buffer file-buffer)
1140             (x-symbol-tex-translate-locations file-buffer beg end
1141                                               (list location))
1142             ;; narrow-to-region gets confused otherwise...
1143             (set-buffer file-buffer)
1144             (when (numberp (setq pos (aref location 2)))
1145               (setq string (buffer-substring beg pos))
1146               (and (boundp 'after-string)
1147                    (setq after-string (buffer-substring pos end))))))))))
1148
1149 (defun x-symbol-tex-preview-locations (locations)
1150   (when locations
1151     (prog1 locations
1152       (let* ((conv-buffer (get-buffer-create " x-symbol error location"))
1153              file
1154              (dir default-directory))
1155         (save-excursion
1156           (set-buffer conv-buffer)
1157           (erase-buffer)
1158           (when (fboundp 'set-buffer-multibyte)
1159             (set-buffer-multibyte t))
1160           (while locations
1161             (setq file (aref (car locations) 0))
1162             (set-buffer (find-file-noselect (expand-file-name file dir)))
1163             (if x-symbol-mode
1164                 (save-restriction
1165                   (widen)
1166                   (goto-char 1)
1167                   (let ((file-buffer (current-buffer))
1168                         (pline 1)
1169                         (line (aref (car locations) 1))
1170                         beg end)
1171                     (set-buffer conv-buffer)
1172                     (x-symbol-inherit-from-buffer file-buffer)
1173                     (while line
1174                       (set-buffer file-buffer)
1175                       (if (>= line pline)
1176                           (if (eq selective-display t)
1177                               (re-search-forward "[\n\C-m]"
1178                                                  nil 'end (- line pline))
1179                             (forward-line (- line pline)))
1180                         (goto-line line))
1181                       (setq beg (point))
1182                       (end-of-line)
1183                       (setq end (point))
1184                       (set-buffer conv-buffer)
1185                       (setq locations
1186                             (x-symbol-tex-translate-locations file-buffer
1187                                                               beg end
1188                                                               locations))
1189                       (setq pline line
1190                             line (and locations
1191                                       (equal (aref (car locations) 0) file)
1192                                       (aref (car locations) 1))))
1193                     ;; narrow-to-region gets confused otherwise...
1194                     (set-buffer file-buffer)))
1195               (while (and (setq locations (cdr locations))
1196                           (equal (aref (car locations) 0) file))))))))))
1197
1198
1199 ;;;===========================================================================
1200 ;;;  Extra decoding = executed after normal decoding
1201 ;;;===========================================================================
1202
1203 (defun x-symbol-tex-xdecode-old (&optional beg end)
1204   "Remove braces around text-mode characters like {C}."
1205   (interactive (and (region-active-p) (list (region-beginning) (region-end))))
1206   (unless (eq x-symbol-language 'tex)
1207     (error "Command is meant to be used with token language `tex'"))
1208   (unless x-symbol-mode
1209     (error "Command is meant to be used if X-Symbol mode is enabled"))
1210   (or beg (setq beg (point-min)))
1211   (or end (setq end (point-max)))
1212   (save-excursion
1213     (save-restriction
1214       (narrow-to-region beg end)
1215       (let ((first-change-hook nil)     ; no `flyspell-mode' here
1216             (after-change-functions nil) ; no fontification!
1217             (count 0)
1218             (case-fold-search (x-symbol-grammar-case-function
1219                                x-symbol-tex-token-grammar))
1220             (regexp (if (featurep 'mule)
1221                         "{[^\000-\177]}"
1222                       "{\\(?:[\240-\377]\\|[\200-\237][\240-\377]\\)}"))
1223             (token-classes (x-symbol-generated-token-classes
1224                             x-symbol-tex-generated-data))
1225             charsym
1226             (end (make-marker)))
1227         (goto-char (point-min))
1228         (while (re-search-forward regexp nil t)
1229           (set-marker end (point))
1230           (goto-char (1+ (match-beginning 0)))
1231           (when (and (setq charsym (x-symbol-encode-charsym-after))
1232                      (x-symbol-even-escapes-before-p (match-beginning 0) ?\\)
1233                      (eq (car (gethash charsym token-classes)) 'text))
1234             (goto-char (match-beginning 0))
1235             (delete-char 1)
1236             (goto-char end)
1237             (delete-char -1)
1238             (incf count)))
1239         (if font-lock-mode (x-symbol-fontify (point-min) (point-max)))
1240         (set-marker end nil)
1241         (if (interactive-p)
1242             (message "Converted %d old TeX sequences like {C} in %s"
1243                      count (x-symbol-region-text t)))))))
1244
1245 (defvar x-symbol-tex-xdecode-obarray nil)
1246
1247 (defun x-symbol-tex-xdecode-latex (&optional beg end)
1248   "Decode LaTeX sequences for accented characters like \'{C}."
1249   (interactive (and (region-active-p) (list (region-beginning) (region-end))))
1250   (unless (eq x-symbol-language 'tex)
1251     (error "Command is meant to be used with token language `tex'"))
1252   (unless x-symbol-mode
1253     (error "Command is meant to be used if X-Symbol mode is enabled"))
1254   (or beg (setq beg (point-min)))
1255   (or end (setq end (point-max)))
1256   (unless x-symbol-tex-xdecode-obarray
1257     (let ((re "\\`\\(\\\\[.~^\"'`=ckvuHr]\\) ?\\([A-Za-z]\\|\\\\[ij]\\)\\'")
1258           (ij (list (cons "\\i" (gethash 'dotlessi x-symbol-cstring-table))
1259                     (cons "\\j" (gethash 'dotlessj x-symbol-cstring-table))))
1260           alist)
1261       (maphash (lambda (charsym value)
1262                  (setq value (car value))
1263                  (when (string-match re value)
1264                    (push (list (format "%s{%s}"
1265                                        (match-string 1 value)
1266                                        (or (cdr (assoc (match-string 2 value)
1267                                                        ij))
1268                                            (match-string 2 value)))
1269                                charsym nil)
1270                          alist)))
1271                (x-symbol-generated-encode-table x-symbol-tex-generated-data))
1272       (setq x-symbol-tex-xdecode-obarray (x-symbol-alist-to-obarray alist))))
1273   (save-excursion
1274     (save-restriction
1275       (narrow-to-region beg end)
1276       (let ((first-change-hook nil)     ; no `flyspell-mode' here
1277             (after-change-functions nil)) ; no fontification!
1278         (goto-char (point-min))
1279         (x-symbol-decode-lisp
1280          '(?\\)
1281          (format "\\\\[.~^\"'`=ckvuHr]{\\(?:[A-Za-z]\\|%s\\|%s\\)}"
1282                  (gethash 'dotlessi x-symbol-cstring-table)
1283                  (gethash 'dotlessj x-symbol-cstring-table))
1284          x-symbol-tex-xdecode-obarray nil)
1285         (if font-lock-mode (x-symbol-fontify (point-min) (point-max)))
1286         (if (interactive-p)
1287             (message "Decoded alternative TeX sequences like \\'{C} in %s"
1288                      (x-symbol-region-text t)))))))
1289
1290 ;;; Local IspellPersDict: .ispell_xsymb
1291 ;;; x-symbol-tex.el ends here