]> code.delx.au - gnu-emacs/blob - lisp/progmodes/meta-mode.el
Convert consecutive FSF copyright years to ranges.
[gnu-emacs] / lisp / progmodes / meta-mode.el
1 ;;; meta-mode.el --- major mode for editing Metafont or MetaPost sources
2
3 ;; Copyright (C) 1997, 2001-2011 Free Software Foundation, Inc.
4
5 ;; Author: Ulrik Vieth <vieth@thphy.uni-duesseldorf.de>
6 ;; Version: 1.0
7 ;; Keywords: Metafont, MetaPost, tex, languages
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs 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 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs 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 GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; Description:
27 ;;
28 ;; This Emacs Lisp package provides a major mode for editing Metafont
29 ;; or MetaPost sources. It includes all the necessary code to set up
30 ;; a major mode including an approriate syntax table, keymap, and a
31 ;; mode-specific pull-down menu. It also provides a sophisticated set
32 ;; of font-lock patterns, a fancy indentation function adapted from
33 ;; AUCTeX's latex.el, and some basic mode-specific editing functions
34 ;; such as functions to move to the beginning or end of the enclosing
35 ;; environment, or to mark, re-indent, or comment-out environments.
36 ;; On the other hand, it doesn't yet provide any functionality for
37 ;; running Metafont or MetaPost in a shell buffer form within Emacs,
38 ;; but such functionality might be added later, either as part of this
39 ;; package or as a separate Emacs Lisp package.
40
41 ;; Installation:
42 ;;
43 ;; An interface to running Metafont or MetaPost as a shell process
44 ;; from within Emacs is currently under development as a separate
45 ;; Emacs Lisp package (meta-buf.el). In order to have that package
46 ;; loaded automatically when first entering Metafont or MetaPost mode,
47 ;; you might use the load-hook provided in this package by adding
48 ;; these lines to your startup file:
49 ;;
50 ;; (add-hook 'meta-mode-load-hook
51 ;; (lambda () (require 'meta-buf)))
52 ;;
53 ;; The add-on package loaded this way may in turn make use of the
54 ;; mode-hooks provided in this package to activate additional features
55 ;; when entering Metafont or MetaPost mode.
56
57 ;; Font Lock Support:
58 ;;
59 ;; If you are using global-font-lock-mode (introduced in Emacs 19.31),
60 ;; fontification in Metafont and/or MetaPost mode will be activated
61 ;; automatically. To speed up fontification for the rather complex
62 ;; patterns used in these modes, it may be a good idea to activate
63 ;; lazy-lock as a font-lock-support-mode (introduced in Emacs 19.32)
64 ;; by adding these lines to your startup file:
65 ;;
66 ;; (global-font-lock-mode t)
67 ;; (setq font-lock-support-mode 'lazy-lock-mode)
68 ;;
69 ;; If you are using an older version of Emacs, which doesn't provide
70 ;; global-font-lock-mode or font-lock-support-mode, you can also
71 ;; activate fontification in Metafont and/or MetaPost mode by adding
72 ;; the following lines to your startup file:
73 ;;
74 ;; (add-hook 'meta-common-mode-hook 'turn-on-font-lock)
75 ;; (add-hook 'meta-common-mode-hook 'turn-on-lazy-lock)
76
77 ;; Customization:
78 ;;
79 ;; Following the usual Emacs Lisp coding conventions, the major modes
80 ;; defined in this package provide several hook variables to allow for
81 ;; local customization when entering the modes. In particular, there
82 ;; is a `meta-common-mode-hook' which applies to both modes as well as
83 ;; `metafont-mode-hook' and `metapost-mode-hook' which apply to the
84 ;; individual modes. In addition, there are several variables and
85 ;; regexps controlling e.g. the behavior of the indentation function,
86 ;; which may be customized via `edit-options'. Please refer to the
87 ;; docstrings in the code below for details.
88
89 ;; Availability:
90 ;;
91 ;; This package is currently available via my "TeX Software" WWW page:
92 ;;
93 ;; http://www.thphy.uni-duesseldorf.de/~vieth/subjects/tex/software.html
94 ;;
95 ;; As of this version 1.0, this package will be uploaded to CTAN
96 ;; archives, where it shall find a permanent home, presumably in
97 ;; tex-archive/support/emacs-modes. It will also be submitted for
98 ;; integration into the GNU Emacs distribution at that time.
99 ;;
100 ;; History:
101 ;;
102 ;; v 0.0 -- 1997/02/01 UV Started writing meta-mode.el.
103 ;; v 0.1 -- 1997/02/02 UV Added preliminary set of font-lock patterns.
104 ;; v 0.2 -- 1997/02/03 UV Improved and debugged font-lock patterns.
105 ;; Added indent-line-function for TAB.
106 ;; v 0.3 -- 1997/02/17 UV Improved font-lock patterns and syntax table.
107 ;; Improved and debbuged indentation function.
108 ;; v 0.4 -- 1997/02/18 UV Added functions to indent regions for M-C-q,
109 ;; also added a preliminary mode-specific menu.
110 ;; v 0.5 -- 1997/02/19 UV Added functions to skip to next or previous
111 ;; defun and to re-indent or comment-out defuns.
112 ;; v 0.6 -- 1997/02/20 UV More debugging, testing and clean-up.
113 ;; v 0.7 -- 1997/02/22 UV Use easymenu to define mode-specific menu.
114 ;; v 0.8 -- 1997/02/24 UV Added completion function for M-TAB.
115 ;; v 0.9 -- 1997/03/08 UV Added fill-paragraph function for comments.
116 ;; Also fixed a few remaining font-lock problems.
117 ;; Added meta-mode-load-hook to load meta-buf.el.
118 ;; v 1.0 -- 1997/04/07 UV Cleanup for official public release.
119 ;;
120 ;; Historical Footnote:
121 ;;
122 ;; This package was begun on February 1, 1997, exactly 20 years after
123 ;; the genesis of TeX took place according to Don Knuth's own account
124 ;; (cf. ``The Errors of TeX'', reprinted in ``Literate Programming'',
125 ;; Chapter 10, p. 249). What better date could there be to choose?
126 ;;
127
128 \f
129 ;;; Code:
130
131 (require 'easymenu)
132
133 (defgroup meta-font nil
134 "Major mode for editing Metafont or MetaPost sources."
135 :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
136 :group 'languages)
137
138 ;;; Fontification.
139
140 (defvar meta-font-lock-keywords
141 (let ((input-keywords
142 "\\(input\\|generate\\)")
143 (begin-keywords
144 (concat "\\(begin\\(char\\|fig\\|graph\\|logochar\\)\\|"
145 "\\cmchar\\|dcchar\\|ecchar\\)"))
146 (end-keywords
147 "\\(end\\(char\\|fig\\|graph\\)\\)")
148 (macro-keywords-1
149 "\\(def\\|let\\|mode_def\\|vardef\\)")
150 (macro-keywords-2
151 "\\(primarydef\\|secondarydef\\|tertiarydef\\)")
152 ;(make-regexp
153 ; '("expr" "suffix" "text" "primary" "secondary" "tertiary") t)
154 (args-keywords
155 (concat "\\(expr\\|primary\\|s\\(econdary\\|uffix\\)\\|"
156 "te\\(rtiary\\|xt\\)\\)"))
157 ;(make-regexp
158 ; '("boolean" "color" "numeric" "pair" "path" "pen" "picture"
159 ; "string" "transform" "newinternal") t)
160 (type-keywords
161 (concat "\\(boolean\\|color\\|n\\(ewinternal\\|umeric\\)\\|"
162 "p\\(a\\(ir\\|th\\)\\|en\\|icture\\)\\|string\\|"
163 "transform\\)"))
164 ;(make-regexp
165 ; '("for" "forever" "forsuffixes" "endfor"
166 ; "step" "until" "upto" "downto" "thru" "within"
167 ; "iff" "if" "elseif" "else" "fi" "exitif" "exitunless"
168 ; "let" "def" "vardef" "enddef" "mode_def"
169 ; "true" "false" "known" "unknown" "and" "or" "not"
170 ; "save" "interim" "inner" "outer" "relax"
171 ; "begingroup" "endgroup" "expandafter" "scantokens"
172 ; "generate" "input" "endinput" "end" "bye"
173 ; "message" "errmessage" "errhelp" "special" "numspecial"
174 ; "readstring" "readfrom" "write") t)
175 (syntactic-keywords
176 (concat "\\(and\\|b\\(egingroup\\|ye\\)\\|"
177 "d\\(ef\\|ownto\\)\\|e\\(lse\\(\\|if\\)"
178 "\\|nd\\(\\|def\\|for\\|group\\|input\\)"
179 "\\|rr\\(help\\|message\\)"
180 "\\|x\\(it\\(if\\|unless\\)\\|pandafter\\)\\)\\|"
181 "f\\(alse\\|i\\|or\\(\\|ever\\|suffixes\\)\\)\\|"
182 "generate\\|i\\(ff?\\|n\\(ner\\|put\\|terim\\)\\)\\|"
183 "known\\|let\\|m\\(essage\\|ode_def\\)\\|"
184 "n\\(ot\\|umspecial\\)\\|o\\(r\\|uter\\)\\|"
185 "re\\(ad\\(from\\|string\\)\\|lax\\)\\|"
186 "s\\(ave\\|cantokens\\|pecial\\|tep\\)\\|"
187 "t\\(hru\\|rue\\)\\|"
188 "u\\(n\\(known\\|til\\)\\|pto\\)\\|"
189 "vardef\\|w\\(ithin\\|rite\\)\\)"))
190 )
191 (list
192 ;; embedded TeX code in btex ... etex
193 (cons (concat "\\(btex\\|verbatimtex\\)"
194 "[ \t\f]+\\(.*\\)[ \t\f]+"
195 "\\(etex\\)")
196 '((1 font-lock-keyword-face)
197 (2 font-lock-string-face)
198 (3 font-lock-keyword-face)))
199 ;; unary macro definitions: def, vardef, let
200 (cons (concat "\\<" macro-keywords-1 "\\>"
201 "[ \t\f]+\\(\\sw+\\|\\s_+\\|\\s.+\\)")
202 '((1 font-lock-keyword-face)
203 (2 font-lock-function-name-face)))
204 ;; binary macro defintions: <leveldef> x operator y
205 (cons (concat "\\<" macro-keywords-2 "\\>"
206 "[ \t\f]+\\(\\sw+\\)"
207 "[ \t\f]*\\(\\sw+\\|\\s.+\\)"
208 "[ \t\f]*\\(\\sw+\\)")
209 '((1 font-lock-keyword-face)
210 (2 font-lock-variable-name-face nil t)
211 (3 font-lock-function-name-face nil t)
212 (4 font-lock-variable-name-face nil t)))
213 ;; variable declarations: numeric, pair, color, ...
214 (cons (concat "\\<" type-keywords "\\>"
215 "\\([ \t\f]+\\(\\sw+\\)\\)*")
216 '((1 font-lock-type-face)
217 (font-lock-match-meta-declaration-item-and-skip-to-next
218 (goto-char (match-end 1)) nil
219 (1 font-lock-variable-name-face nil t))))
220 ;; argument declarations: expr, suffix, text, ...
221 (cons (concat "\\<" args-keywords "\\>"
222 "\\([ \t\f]+\\(\\sw+\\|\\s_+\\)\\)*")
223 '((1 font-lock-type-face)
224 (font-lock-match-meta-declaration-item-and-skip-to-next
225 (goto-char (match-end 1)) nil
226 (1 font-lock-variable-name-face nil t))))
227 ;; special case of arguments: expr x of y
228 (cons (concat "\\(expr\\)[ \t\f]+\\(\\sw+\\)"
229 "[ \t\f]+\\(of\\)[ \t\f]+\\(\\sw+\\)")
230 '((1 font-lock-type-face)
231 (2 font-lock-variable-name-face)
232 (3 font-lock-keyword-face nil t)
233 (4 font-lock-variable-name-face nil t)))
234 ;; syntactic keywords
235 (cons (concat "\\<" syntactic-keywords "\\>")
236 'font-lock-keyword-face)
237 ;; beginchar, beginfig
238 (cons (concat "\\<" begin-keywords "\\>")
239 'font-lock-keyword-face)
240 ;; endchar, endfig
241 (cons (concat "\\<" end-keywords "\\>")
242 'font-lock-keyword-face)
243 ;; input, generate
244 (cons (concat "\\<" input-keywords "\\>"
245 "[ \t\f]+\\(\\sw+\\)")
246 '((1 font-lock-keyword-face)
247 (2 font-lock-constant-face)))
248 ;; embedded Metafont/MetaPost code in comments
249 (cons "|\\([^|]+\\)|"
250 '(1 font-lock-constant-face t))
251 ))
252 "Default expressions to highlight in Metafont or MetaPost mode.")
253
254
255 (defun font-lock-match-meta-declaration-item-and-skip-to-next (limit)
256 ;; Match and move over Metafont/MetaPost declaration item after point.
257 ;;
258 ;; The expected syntax of an item is either "word" or "symbol",
259 ;; possibly ending with optional whitespace. Everything following
260 ;; the item (but belonging to it) is expected to by skipable by
261 ;; `forward-sexp'. The list of items is expected to be separated
262 ;; by commas and terminated by semicolons or equals signs.
263 ;;
264 (if (looking-at "[ \t\f]*\\(\\sw+\\|\\s_+\\)")
265 (save-match-data
266 (condition-case nil
267 (save-restriction
268 ;; Restrict to end of line, currently guaranteed to be LIMIT.
269 (narrow-to-region (point-min) limit)
270 (goto-char (match-end 1))
271 ;; Move over any item value, etc., to the next item.
272 (while (not (looking-at "[ \t\f]*\\(\\(,\\)\\|;\\|=\\|$\\)"))
273 (goto-char (or (scan-sexps (point) 1) (point-max))))
274 (goto-char (match-end 2)))
275 (error t)))))
276
277
278 \f
279 ;;; Completion.
280
281 ;; The data used to prepare the following lists of primitives and
282 ;; standard macros available in Metafont or MetaPost was extracted
283 ;; from the original sources like this:
284 ;;
285 ;; grep '^primitive' texk-7.0/web2c/{mf,mp}.web |\
286 ;; sed 's/primitive(\("[a-zA-Z]*"\).*/\1/' > {mf,mp}_prim.list
287 ;;
288 ;; grep '\(let\|def\|vardef\|primarydef\|secondarydef\|tertiarydef\)'
289 ;; texmf/meta{font,post}/plain.{mf,mp} > {mf,mp}_plain.list
290
291 (defconst meta-common-primitives-list
292 '("ASCII" "addto" "also" "and" "angle" "atleast" "batchmode"
293 "begingroup" "boolean" "boundarychar" "char" "charcode" "chardp"
294 "charexists" "charext" "charht" "charic" "charlist" "charwd"
295 "contour" "controls" "cosd" "curl" "cycle" "day" "decimal" "def"
296 "delimiters" "designsize" "directiontime" "doublepath" "dump" "else"
297 "elseif" "end" "enddef" "endfor" "endgroup" "endinput" "errhelp"
298 "errmessage" "errorstopmode" "everyjob" "exitif" "expandafter"
299 "expr" "extensible" "false" "fi" "floor" "fontdimen" "fontmaking"
300 "for" "forever" "forsuffixes" "headerbyte" "hex" "if" "inner"
301 "input" "interim" "intersectiontimes" "jobname" "kern" "known"
302 "length" "let" "ligtable" "makepath" "makepen" "message" "mexp"
303 "mlog" "month" "newinternal" "nonstopmode" "normaldeviate" "not"
304 "nullpen" "nullpicture" "numeric" "oct" "odd" "of" "or" "outer"
305 "pair" "path" "pausing" "pen" "pencircle" "penoffset" "picture"
306 "point" "postcontrol" "precontrol" "primary" "primarydef" "quote"
307 "randomseed" "readstring" "reverse" "rotated" "save" "scaled"
308 "scantokens" "scrollmode" "secondary" "secondarydef" "shifted"
309 "shipout" "show" "showdependencies" "showstats" "showstopping"
310 "showtoken" "showvariable" "sind" "skipto" "slanted" "special"
311 "sqrt" "step" "str" "string" "subpath" "substring" "suffix"
312 "tension" "tertiary" "tertiarydef" "text" "time" "to"
313 "tracingcapsules" "tracingchoices" "tracingcommands"
314 "tracingequations" "tracingmacros" "tracingonline" "tracingoutput"
315 "tracingrestores" "tracingspecs" "tracingstats" "tracingtitles"
316 "transform" "transformed" "true" "turningnumber" "uniformdeviate"
317 "unknown" "until" "vardef" "warningcheck" "withpen" "xpart"
318 "xscaled" "xxpart" "xypart" "year" "ypart" "yscaled" "yxpart"
319 "yypart" "zscaled")
320 "List of primitives common to Metafont and MetaPost.")
321
322 (defconst metafont-primitives-list
323 '("at" "autorounding" "chardx" "chardy" "cull" "display"
324 "dropping" "fillin" "from" "granularity" "hppp" "inwindow"
325 "keeping" "numspecial" "openwindow" "proofing" "smoothing"
326 "totalweight" "tracingedges" "tracingpens" "turningcheck" "vppp"
327 "withweight" "xoffset" "yoffset")
328 "List of primitives only defined in Metafont.")
329
330 (defconst metapost-primitives-list
331 '("arclength" "arctime" "bluepart" "bounded" "btex" "clip"
332 "clipped" "color" "dashed" "dashpart" "etex" "filled" "fontpart"
333 "fontsize" "greenpart" "infont" "linecap" "linejoin" "llcorner"
334 "lrcorner" "miterlimit" "mpxbreak" "pathpart" "penpart"
335 "prologues" "readfrom" "redpart" "setbounds" "stroked" "textpart"
336 "textual" "tracinglostchars" "truecorners" "ulcorner" "urcorner"
337 "verbatimtex" "withcolor" "within" "write")
338 "List of primitives only defined in MetaPost.")
339
340 (defconst meta-common-plain-macros-list
341 '( "abs" "bot" "bye" "byte" "ceiling" "clear_pen_memory"
342 "clearit" "clearpen" "clearxy" "counterclockwise" "cutdraw" "decr"
343 "dir" "direction" "directionpoint" "div" "dotprod" "downto" "draw"
344 "drawdot" "erase" "exitunless" "fill" "filldraw" "flex" "gobble"
345 "hide" "incr" "interact" "interpath" "intersectionpoint" "inverse"
346 "label" "labels" "lft" "loggingall" "magstep" "makelabel" "max"
347 "min" "mod" "numtok" "penlabels" "penpos" "penstroke" "pickup"
348 "range" "reflectedabout" "relax" "rotatedabout" "rotatedaround"
349 "round" "rt" "savepen" "shipit" "softjoin" "solve" "stop"
350 "superellipse" "takepower" "tensepath" "thru" "top" "tracingall"
351 "tracingnone" "undraw" "undrawdot" "unfill" "unfilldraw"
352 "unitvector" "upto" "whatever")
353 "List of macros common to plain Metafont and MetaPost.")
354
355 (defconst metafont-plain-macros-list
356 '("beginchar" "change_width" "culldraw" "cullit" "cutoff"
357 "define_blacker_pixels" "define_corrected_pixels"
358 "define_good_x_pixels" "define_good_y_pixels"
359 "define_horizontal_corrected_pixels" "define_pixels"
360 "define_whole_blacker_pixels" "define_whole_pixels"
361 "define_whole_vertical_blacker_pixels"
362 "define_whole_vertical_pixels" "endchar" "fix_units"
363 "font_coding_scheme" "font_extra_space" "font_identifier"
364 "font_normal_shrink" "font_normal_space" "font_normal_stretch"
365 "font_quad" "font_size" "font_slant" "font_x_height" "gfcorners"
366 "good.bot" "good.lft" "good.rt" "good.top" "good.x" "good.y"
367 "grayfont" "hround" "imagerules" "italcorr" "labelfont"
368 "lowres_fix" "makebox" "makegrid" "maketicks" "mode_lowres"
369 "mode_proof" "mode_setup" "mode_smoke" "nodisplays" "notransforms"
370 "openit" "penrazor" "pensquare" "proofoffset" "proofrule"
371 "proofrulethickness" "screenchars" "screenrule" "screenstrokes"
372 "showit" "slantfont" "smode" "titlefont" "vround")
373 "List of macros only defined in plain Metafont.")
374
375 (defconst metapost-plain-macros-list
376 '("arrowhead" "bbox" "beginfig" "buildcycle" "center" "cutafter"
377 "cutbefore" "dashpattern" "dotlabel" "dotlabels" "drawarrow"
378 "drawdblarrow" "drawoptions" "endfig" "image" "label" "off" "on"
379 "thelabel")
380 "List of macros only defined in plain MetaPost.")
381
382 (defconst metapost-graph-macros-list
383 '("augment" "auto.x" "auto.y" "autogrid" "begingraph" "endgraph"
384 "format" "frame" "gdata" "gdotlabel" "gdraw" "gdrawarrow"
385 "gdrawdblarrow" "gfill" "glabel" "grid" "itick" "otick" "plot"
386 "setcoords" "setrange")
387 "List of macros only defined in MetaPost \"graph\" package.")
388
389 (defconst metapost-boxes-macros-list
390 '("boxit" "boxjoin" "bpath" "circleit" "drawboxed" "drawboxes"
391 "drawunboxed" "fixpos" "fixsize" "pic" "rboxit")
392 "List of macros only defined in MetaPost \"boxes\" package.")
393
394
395 (defvar metafont-symbol-list
396 (append meta-common-primitives-list
397 metafont-primitives-list
398 meta-common-plain-macros-list
399 metafont-plain-macros-list)
400 "List of known symbols to complete in Metafont mode.")
401
402 (defvar metapost-symbol-list
403 (append meta-common-primitives-list
404 metapost-primitives-list
405 meta-common-plain-macros-list
406 metapost-plain-macros-list
407 metapost-graph-macros-list
408 metapost-boxes-macros-list)
409 "List of known symbols to complete in MetaPost mode.")
410
411
412 (defvar meta-symbol-list nil
413 "List of known symbols to complete in Metafont or MetaPost mode.")
414
415 (defvar meta-symbol-changed nil
416 "Flag indicating whether `meta-symbol-list' has been initialized.")
417
418 (defvar meta-complete-list nil
419 ; (list (list "\\<\\(\\sw+\\)" 1 'meta-symbol-list)
420 ; (list "" 'ispell-complete-word))
421 "List of ways to perform completion in Metafont or MetaPost mode.
422
423 Each entry is a list with the following elements:
424 1. Regexp matching the preceding text.
425 2. A number indicating the subgroup in the regexp containing the text.
426 3. A function returning an alist of possible completions.
427 4. Text to append after a succesful completion (if any).
428
429 Or alternatively:
430 1. Regexp matching the preceding text.
431 2. Function to do the actual completion.")
432
433
434 (defun meta-add-symbols (&rest entries)
435 "Add entries to list of known symbols in Metafont or MetaPost mode."
436 (if meta-symbol-changed
437 (setq meta-symbol-list (cons entries meta-symbol-list))
438 (setq meta-symbol-changed t)
439 (setq meta-symbol-list (cons entries meta-symbol-list))))
440
441 (defun meta-symbol-list ()
442 "Return value of list of known symbols in Metafont or MetaPost mode.
443 If the list was changed, sort the list and remove duplicates first."
444 (if (not meta-symbol-changed)
445 ()
446 (setq meta-symbol-changed nil)
447 (message "Preparing completion list...")
448 ;; sort list of symbols
449 (setq meta-symbol-list
450 (sort (mapcar 'meta-listify (apply 'append meta-symbol-list))
451 'meta-car-string-lessp))
452 ;; remove duplicates
453 (let ((entry meta-symbol-list))
454 (while (and entry (cdr entry))
455 (let ((this (car entry))
456 (next (car (cdr entry))))
457 (if (not (string-equal (car this) (car next)))
458 (setq entry (cdr entry))
459 (if (> (length next) (length this))
460 (setcdr this (cdr next)))
461 (setcdr entry (cdr (cdr entry)))))))
462 (message "Preparing completion list... done"))
463 meta-symbol-list)
464
465 (defun meta-listify (a)
466 ;; utility function used in `meta-add-symbols'
467 (if (listp a) a (list a)))
468
469 (defun meta-car-string-lessp (a b)
470 ;; utility function used in `meta-add-symbols'
471 (string-lessp (car a) (car b)))
472
473
474 (defun meta-complete-symbol ()
475 "Perform completion on Metafont or MetaPost symbol preceding point."
476 ;; FIXME: Use completion-at-point-functions.
477 (interactive "*")
478 (let ((list meta-complete-list)
479 entry)
480 (while list
481 (setq entry (car list)
482 list (cdr list))
483 (if (meta-looking-at-backward (car entry) 200)
484 (setq list nil)))
485 (if (numberp (nth 1 entry))
486 (let* ((sub (nth 1 entry))
487 (close (nth 3 entry))
488 (begin (match-beginning sub))
489 (end (match-end sub))
490 (list (funcall (nth 2 entry))))
491 (completion-in-region
492 begin end
493 (if (zerop (length close)) list
494 (apply-partially 'completion-table-with-terminator
495 close list))))
496 (funcall (nth 1 entry)))))
497
498
499 (defun meta-looking-at-backward (regexp &optional limit)
500 ;; utility function used in `meta-complete-symbol'
501 (let ((pos (point)))
502 (save-excursion
503 (and (re-search-backward
504 regexp (if limit (max (point-min) (- (point) limit))) t)
505 (eq (match-end 0) pos)))))
506
507 (defun meta-match-buffer (n)
508 ;; utility function used in `meta-complete-symbol'
509 (if (match-beginning n)
510 (let ((str (buffer-substring (match-beginning n) (match-end n))))
511 (set-text-properties 0 (length str) nil str)
512 (copy-sequence str))
513 ""))
514
515
516 \f
517 ;;; Indentation.
518
519 (defcustom meta-indent-level 2
520 "Indentation of begin-end blocks in Metafont or MetaPost mode."
521 :type 'integer
522 :group 'meta-font)
523
524
525 (defcustom meta-left-comment-regexp "%%+"
526 "Regexp matching comments that should be placed on the left margin."
527 :type 'regexp
528 :group 'meta-font)
529
530 (defcustom meta-right-comment-regexp nil
531 "Regexp matching comments that should be placed to the right margin."
532 :type '(choice regexp
533 (const :tag "None" nil))
534 :group 'meta-font)
535
536 (defcustom meta-ignore-comment-regexp "%[^%]"
537 "Regexp matching comments that whose indentation should not be touched."
538 :type 'regexp
539 :group 'meta-font)
540
541
542 (defcustom meta-begin-environment-regexp
543 (concat "\\(begin\\(char\\|fig\\|gr\\(aph\\|oup\\)\\|logochar\\)\\|"
544 "def\\|for\\(\\|ever\\|suffixes\\)\\|if\\|mode_def\\|"
545 "primarydef\\|secondarydef\\|tertiarydef\\|vardef\\)")
546 "Regexp matching the beginning of environments to be indented."
547 :type 'regexp
548 :group 'meta-font)
549
550 (defcustom meta-end-environment-regexp
551 (concat "\\(end\\(char\\|def\\|f\\(ig\\|or\\)\\|gr\\(aph\\|oup\\)\\)"
552 "\\|fi\\)")
553 "Regexp matching the end of environments to be indented."
554 :type 'regexp
555 :group 'meta-font)
556
557 (defcustom meta-within-environment-regexp
558 ; (concat "\\(e\\(lse\\(\\|if\\)\\|xit\\(if\\|unless\\)\\)\\)")
559 (concat "\\(else\\(\\|if\\)\\)")
560 "Regexp matching keywords within environments not to be indented."
561 :type 'regexp
562 :group 'meta-font)
563
564
565 (defun meta-comment-indent ()
566 "Return the indentation for a comment in Metafont or MetaPost mode."
567 (if (and meta-left-comment-regexp
568 (looking-at meta-left-comment-regexp))
569 (current-column)
570 (skip-chars-backward "\t\f ")
571 (max (if (bolp) 0 (1+ (current-column)))
572 comment-column)))
573
574 (defun meta-indent-line ()
575 "Indent the line containing point as Metafont or MetaPost source."
576 (interactive)
577 (let ((indent (meta-indent-calculate)))
578 (if (/= (current-indentation) indent)
579 (save-excursion
580 (delete-region (line-beginning-position)
581 (progn (back-to-indentation) (point)))
582 (indent-to indent)))
583 (if (< (current-column) indent)
584 (back-to-indentation))))
585
586 (defun meta-indent-calculate ()
587 "Return the indentation of current line of Metafont or MetaPost source."
588 ;; Indentation within strings is not considered as Meta* don't allow multi
589 ;; line strings.
590 (save-excursion
591 (back-to-indentation)
592 (cond
593 ;; Comments to the left margin.
594 ((and meta-left-comment-regexp
595 (looking-at meta-left-comment-regexp))
596 0)
597 ;; Comments to the right margin.
598 ((and meta-right-comment-regexp
599 (looking-at meta-right-comment-regexp))
600 comment-column)
601 ;; Comments best left alone.
602 ((and meta-ignore-comment-regexp
603 (looking-at meta-ignore-comment-regexp))
604 (current-indentation))
605 ;; Beginning of buffer.
606 ((eq (point-at-bol) (point-min))
607 0)
608 ;; Backindent at end of environments.
609 ((meta-indent-looking-at-code
610 (concat "\\<" meta-end-environment-regexp "\\>"))
611 (- (meta-indent-current-indentation) meta-indent-level))
612 ;; Backindent at keywords within environments.
613 ((meta-indent-looking-at-code
614 (concat "\\<" meta-within-environment-regexp "\\>"))
615 (- (meta-indent-current-indentation) meta-indent-level))
616 (t (meta-indent-current-indentation)))))
617
618 (defun meta-indent-in-string-p ()
619 "Tell if the point is in a string."
620 (or (nth 3 (syntax-ppss))
621 (eq (get-text-property (point) 'face) font-lock-string-face)))
622
623 (defun meta-indent-looking-at-code (regexp)
624 "Same as `looking-at' but checks that the point is not in a string."
625 (unless (meta-indent-in-string-p)
626 (looking-at regexp)))
627
628 (defun meta-indent-previous-line ()
629 "Go to the previous line of code, skipping comments."
630 (skip-chars-backward "\n\t\f ")
631 (move-to-column (current-indentation))
632 ;; Ignore comments.
633 (while (and (looking-at comment-start) (not (bobp)))
634 (skip-chars-backward "\n\t\f ")
635 (when (not (bobp))
636 (move-to-column (current-indentation)))))
637
638 (defun meta-indent-unfinished-line ()
639 "Tell if the current line of code ends with an unfinished expression."
640 (save-excursion
641 (end-of-line)
642 ;; Skip backward the comments.
643 (let ((point-not-in-string (point)))
644 (while (search-backward comment-start (point-at-bol) t)
645 (unless (meta-indent-in-string-p)
646 (setq point-not-in-string (point))))
647 (goto-char point-not-in-string))
648 ;; Search for the end of the previous expression.
649 (if (search-backward ";" (point-at-bol) t)
650 (progn (while (and (meta-indent-in-string-p)
651 (search-backward ";" (point-at-bol) t)))
652 (if (= (char-after) ?\;)
653 (forward-char)
654 (beginning-of-line)))
655 (beginning-of-line))
656 ;; See if the last statement of the line is environment-related,
657 ;; or exists at all.
658 (if (meta-indent-looking-at-code
659 (concat "[ \t\f]*\\($\\|" (regexp-quote comment-start)
660 "\\|\\<" meta-end-environment-regexp "\\>"
661 "\\|\\<" meta-begin-environment-regexp "\\>"
662 "\\|\\<" meta-within-environment-regexp "\\>\\)"))
663 nil
664 t)))
665
666 (defun meta-indent-current-indentation ()
667 "Return the indentation wanted for the current line of code."
668 (+ (meta-indent-current-nesting)
669 (if (save-excursion
670 (back-to-indentation)
671 (and (not (looking-at (concat "\\<" meta-end-environment-regexp "\\>"
672 "\\|\\<" meta-within-environment-regexp "\\>")))
673 (progn (meta-indent-previous-line)
674 (meta-indent-unfinished-line))))
675 meta-indent-level
676 0)))
677
678 (defun meta-indent-current-nesting ()
679 "Return the indentation according to the nearest environment keyword."
680 (save-excursion
681 (save-restriction
682 (widen)
683 (back-to-indentation)
684 (let ((to-add 0))
685 ;; If we found some environment marker backward...
686 (if (catch 'found
687 (while (re-search-backward
688 (concat "(\\|)\\|\\<" meta-end-environment-regexp "\\>"
689 "\\|\\<" meta-begin-environment-regexp "\\>"
690 "\\|\\<" meta-within-environment-regexp "\\>")
691 nil t)
692 ;; If we aren't in a string or in a comment, we've found something.
693 (unless (or (meta-indent-in-string-p)
694 (nth 4 (syntax-ppss)))
695 (cond ((= (char-after) ?\()
696 (setq to-add (+ to-add meta-indent-level)))
697 ((= (char-after) ?\))
698 (setq to-add (- to-add meta-indent-level)))
699 (t (throw 'found t))))))
700 (progn
701 ;; ... then use it to compute the current indentation.
702 (back-to-indentation)
703 (+ to-add (current-indentation) (meta-indent-level-count)
704 ;; Compensate for backindent of end and within keywords.
705 (if (meta-indent-looking-at-code
706 (concat "\\<" meta-end-environment-regexp "\\>\\|"
707 "\\<" meta-within-environment-regexp "\\>"))
708 meta-indent-level
709 ;; Compensate for unfinished line.
710 (if (save-excursion
711 (meta-indent-previous-line)
712 (meta-indent-unfinished-line))
713 (- meta-indent-level)
714 0))))
715 0)))))
716
717 (defun meta-indent-level-count ()
718 "Count indentation change for begin-end commands in the current line."
719 (save-excursion
720 (save-restriction
721 (let ((count 0))
722 (narrow-to-region
723 (point) (save-excursion
724 (re-search-forward "[^\\\\\"]%\\|\n\\|\\'" nil t)
725 (backward-char) (point)))
726 (while (re-search-forward "\\<\\sw+\\>\\|(\\|)" nil t)
727 (save-excursion
728 (goto-char (match-beginning 0))
729 (cond
730 ;; Count number of begin-end keywords within line.
731 ((meta-indent-looking-at-code
732 (concat "\\<" meta-begin-environment-regexp "\\>"))
733 (setq count (+ count meta-indent-level)))
734 ((meta-indent-looking-at-code
735 (concat "\\<" meta-end-environment-regexp "\\>"))
736 (setq count (- count meta-indent-level))))))
737 count))))
738
739
740 \f
741 ;;; Editing commands.
742
743 (defcustom meta-begin-defun-regexp
744 (concat "\\(begin\\(char\\|fig\\|logochar\\)\\|def\\|mode_def\\|"
745 "primarydef\\|secondarydef\\|tertiarydef\\|vardef\\)")
746 "Regexp matching beginning of defuns in Metafont or MetaPost mode."
747 :type 'regexp
748 :group 'meta-font)
749
750 (defcustom meta-end-defun-regexp
751 (concat "\\(end\\(char\\|def\\|fig\\)\\)")
752 "Regexp matching the end of defuns in Metafont or MetaPost mode."
753 :type 'regexp
754 :group 'meta-font)
755
756
757 (defun meta-beginning-of-defun (&optional arg)
758 "Move backward to beginnning of a defun in Metafont or MetaPost code.
759 With numeric argument, do it that many times.
760 Negative arg -N means move forward to Nth following beginning of defun.
761 Returns t unless search stops due to beginning or end of buffer."
762 (interactive "p")
763 (if (or (null arg) (= 0 arg)) (setq arg 1))
764 (and arg (< arg 0) (not (eobp)) (forward-char 1))
765 (and (re-search-backward
766 (concat "\\<" meta-begin-defun-regexp "\\>") nil t arg)
767 (progn (goto-char (match-beginning 0))
768 (skip-chars-backward "%")
769 (skip-chars-backward " \t\f") t)))
770
771 (defun meta-end-of-defun (&optional arg)
772 "Move forward to end of a defun in Metafont or MetaPost code.
773 With numeric argument, do it that many times.
774 Negative argument -N means move back to Nth preceding end of defun.
775 Returns t unless search stops due to beginning or end of buffer."
776 (interactive "p")
777 (if (or (null arg) (= 0 arg)) (setq arg 1))
778 (and (< arg 0) (not (bobp)) (forward-line -1))
779 (and (re-search-forward
780 (concat "\\<" meta-end-defun-regexp "\\>") nil t arg)
781 (progn (goto-char (match-end 0))
782 (skip-chars-forward ";")
783 (skip-chars-forward " \t\f")
784 (if (looking-at "\n") (forward-line 1)) t)))
785
786
787 (defun meta-comment-region (beg end &optional arg)
788 "Comment out active region as Metafont or MetaPost source."
789 (interactive "r")
790 (comment-region beg end arg))
791
792 (defun meta-uncomment-region (beg end)
793 "Uncomment active region as Metafont or MetaPost source."
794 (interactive "r")
795 (comment-region beg end -1))
796
797 (defun meta-comment-defun (&optional arg)
798 "Comment out current environment as Metafont or MetaPost source.
799 With prefix argument, uncomment the environment.
800 The environment used is the one that contains point or follows point."
801 (interactive "P")
802 (save-excursion
803 (let* ((end (if (meta-end-of-defun) (point) (point-max)))
804 (beg (if (meta-beginning-of-defun) (point) (point-min))))
805 (comment-region beg end arg))))
806
807 (defun meta-uncomment-defun ()
808 "Uncomment current environment as Metafont or MetaPost source."
809 (interactive)
810 (meta-comment-defun -1))
811
812
813 (defun meta-indent-region (beg end)
814 "Indent the active region as Metafont or MetaPost source."
815 (interactive "r")
816 (indent-region beg end nil))
817
818 (defun meta-indent-buffer ()
819 "Indent the whole buffer contents as Metafont or MetaPost source."
820 (interactive)
821 (save-excursion
822 (indent-region (point-min) (point-max) nil)))
823
824 (defun meta-indent-defun ()
825 "Indent the current environment as Metafont or MetaPost source.
826 The environment indented is the one that contains point or follows point."
827 (interactive)
828 (save-excursion
829 (let* ((end (if (meta-end-of-defun) (point) (point-max)))
830 (beg (if (meta-beginning-of-defun) (point) (point-min))))
831 (indent-region beg end nil))))
832
833
834 (defun meta-mark-defun ()
835 "Put mark at end of the environment, point at the beginning.
836 The environment marked is the one that contains point or follows point."
837 (interactive)
838 (push-mark (point))
839 (meta-end-of-defun)
840 (push-mark (point) nil t)
841 (meta-beginning-of-defun))
842
843
844 \f
845 ;;; Syntax table, keymap and menu.
846
847 (define-abbrev-table 'meta-mode-abbrev-table ()
848 "Abbrev table used in Metafont or MetaPost mode.")
849
850 (defvar meta-common-mode-syntax-table
851 (let ((st (make-syntax-table)))
852 ;; underscores are word constituents
853 (modify-syntax-entry ?_ "w" st)
854 ;; miscellaneous non-word symbols
855 (modify-syntax-entry ?# "_" st)
856 (modify-syntax-entry ?@ "_" st)
857 (modify-syntax-entry ?$ "_" st)
858 (modify-syntax-entry ?? "_" st)
859 (modify-syntax-entry ?! "_" st)
860 ;; binary operators
861 (modify-syntax-entry ?& "." st)
862 (modify-syntax-entry ?+ "." st)
863 (modify-syntax-entry ?- "." st)
864 (modify-syntax-entry ?/ "." st)
865 (modify-syntax-entry ?* "." st)
866 (modify-syntax-entry ?. "." st)
867 (modify-syntax-entry ?: "." st)
868 (modify-syntax-entry ?= "." st)
869 (modify-syntax-entry ?< "." st)
870 (modify-syntax-entry ?> "." st)
871 (modify-syntax-entry ?| "." st)
872 ;; opening and closing delimiters
873 (modify-syntax-entry ?\( "()" st)
874 (modify-syntax-entry ?\) ")(" st)
875 (modify-syntax-entry ?\[ "(]" st)
876 (modify-syntax-entry ?\] ")[" st)
877 (modify-syntax-entry ?\{ "(}" st)
878 (modify-syntax-entry ?\} "){" st)
879 ;; comment character
880 (modify-syntax-entry ?% "<" st)
881 (modify-syntax-entry ?\n ">" st)
882 ;; escape character, needed for embedded TeX code
883 (modify-syntax-entry ?\\ "\\" st)
884 st)
885 "Syntax table used in Metafont or MetaPost mode.")
886
887 (defvar meta-common-mode-map
888 (let ((map (make-sparse-keymap)))
889 ;; Comment Paragraphs:
890 ;; (define-key map "\M-a" 'backward-sentence)
891 ;; (define-key map "\M-e" 'forward-sentence)
892 ;; (define-key map "\M-h" 'mark-paragraph)
893 ;; (define-key map "\M-q" 'fill-paragraph)
894 ;; Navigation:
895 (define-key map "\M-\C-a" 'meta-beginning-of-defun)
896 (define-key map "\M-\C-e" 'meta-end-of-defun)
897 (define-key map "\M-\C-h" 'meta-mark-defun)
898 ;; Indentation:
899 (define-key map "\M-\C-q" 'meta-indent-defun)
900 (define-key map "\C-c\C-qe" 'meta-indent-defun)
901 (define-key map "\C-c\C-qr" 'meta-indent-region)
902 (define-key map "\C-c\C-qb" 'meta-indent-buffer)
903 ;; Commenting Out:
904 (define-key map "\C-c%" 'meta-comment-defun)
905 ;; (define-key map "\C-uC-c%" 'meta-uncomment-defun)
906 (define-key map "\C-c;" 'meta-comment-region)
907 (define-key map "\C-c:" 'meta-uncomment-region)
908 ;; Symbol Completion:
909 (define-key map "\M-\t" 'meta-complete-symbol)
910 ;; Shell Commands:
911 ;; (define-key map "\C-c\C-c" 'meta-command-file)
912 ;; (define-key map "\C-c\C-k" 'meta-kill-job)
913 ;; (define-key map "\C-c\C-l" 'meta-recenter-output)
914 map)
915 "Keymap used in Metafont or MetaPost mode.")
916 (define-obsolete-variable-alias 'meta-mode-map 'meta-common-mode-map "24.1")
917
918 (easy-menu-define
919 meta-mode-menu meta-common-mode-map
920 "Menu used in Metafont or MetaPost mode."
921 (list "Meta"
922 ["Forward Environment" meta-beginning-of-defun t]
923 ["Backward Environment" meta-end-of-defun t]
924 "--"
925 ["Indent Line" meta-indent-line t]
926 ["Indent Environment" meta-indent-defun t]
927 ["Indent Region" meta-indent-region
928 :active (meta-mark-active)]
929 ["Indent Buffer" meta-indent-buffer t]
930 "--"
931 ["Comment Out Environment" meta-comment-defun t]
932 ["Uncomment Environment" meta-uncomment-defun t]
933 ["Comment Out Region" meta-comment-region
934 :active (meta-mark-active)]
935 ["Uncomment Region" meta-uncomment-region
936 :active (meta-mark-active)]
937 "--"
938 ["Complete Symbol" meta-complete-symbol t]
939 ; "--"
940 ; ["Command on Buffer" meta-command-file t]
941 ; ["Kill Job" meta-kill-job t]
942 ; ["Recenter Output Buffer" meta-recenter-output-buffer t]
943 ))
944
945 ;; Compatibility: XEmacs doesn't have the `mark-active' variable.
946 (defun meta-mark-active ()
947 "Return whether the mark and region are currently active in this buffer."
948 (if (boundp 'mark-active) mark-active (mark)))
949
950
951 \f
952 ;;; Hook variables.
953
954 (defcustom meta-mode-load-hook nil
955 "Hook evaluated when first loading Metafont or MetaPost mode."
956 :type 'hook
957 :group 'meta-font)
958
959 (defcustom meta-common-mode-hook nil
960 "Hook evaluated by both `metafont-mode' and `metapost-mode'."
961 :type 'hook
962 :group 'meta-font)
963
964 (defcustom metafont-mode-hook nil
965 "Hook evaluated by `metafont-mode' after `meta-common-mode-hook'."
966 :type 'hook
967 :group 'meta-font)
968 (defcustom metapost-mode-hook nil
969 "Hook evaluated by `metapost-mode' after `meta-common-mode-hook'."
970 :type 'hook
971 :group 'meta-font)
972
973
974 \f
975 ;;; Initialization.
976
977 (define-derived-mode meta-common-mode prog-mode "-Meta-common-"
978 "Common initialization for Metafont or MetaPost mode."
979 :abbrev-table meta-mode-abbrev-table
980 (set (make-local-variable 'paragraph-start)
981 (concat page-delimiter "\\|$"))
982 (set (make-local-variable 'paragraph-separate)
983 (concat page-delimiter "\\|$"))
984
985 (set (make-local-variable 'paragraph-ignore-fill-prefix) t)
986
987 (set (make-local-variable 'comment-start-skip) "%+[ \t\f]*")
988 (set (make-local-variable 'comment-start) "%")
989 (set (make-local-variable 'comment-end) "")
990 (set (make-local-variable 'comment-multi-line) nil)
991
992 ;; We use `back-to-indentation' but \f is no indentation sign.
993 (modify-syntax-entry ?\f "_ ")
994
995 (set (make-local-variable 'parse-sexp-ignore-comments) t)
996
997 (set (make-local-variable 'comment-indent-function) #'meta-comment-indent)
998 (set (make-local-variable 'indent-line-function) #'meta-indent-line)
999 ;; No need to define a mode-specific 'indent-region-function.
1000 ;; Simply use the generic 'indent-region and 'comment-region.
1001
1002 ;; Set defaults for font-lock mode.
1003 (set (make-local-variable 'font-lock-defaults)
1004 '(meta-font-lock-keywords
1005 nil nil ((?_ . "w")) nil
1006 (font-lock-comment-start-regexp . "%")))
1007
1008 ;; Activate syntax table, keymap and menu.
1009 (easy-menu-add meta-mode-menu))
1010
1011
1012 ;;;###autoload
1013 (define-derived-mode metafont-mode meta-common-mode "Metafont"
1014 "Major mode for editing Metafont sources."
1015 ;; Set defaults for completion function.
1016 (set (make-local-variable 'meta-symbol-list) nil)
1017 (set (make-local-variable 'meta-symbol-changed) nil)
1018 (apply 'meta-add-symbols metafont-symbol-list)
1019 (set (make-local-variable 'meta-complete-list)
1020 (list (list "\\<\\(\\sw+\\)" 1 'meta-symbol-list)
1021 (list "" 'ispell-complete-word))))
1022
1023 ;;;###autoload
1024 (define-derived-mode metapost-mode meta-common-mode "MetaPost"
1025 "Major mode for editing MetaPost sources."
1026 ;; Set defaults for completion function.
1027 (set (make-local-variable 'meta-symbol-list) nil)
1028 (set (make-local-variable 'meta-symbol-changed) nil)
1029 (apply 'meta-add-symbols metapost-symbol-list)
1030 (set (make-local-variable 'meta-complete-list)
1031 (list (list "\\<\\(\\sw+\\)" 1 'meta-symbol-list)
1032 (list "" 'ispell-complete-word))))
1033
1034
1035 ;;; Just in case ...
1036
1037 (provide 'meta-mode)
1038 (run-hooks 'meta-mode-load-hook)
1039
1040 ;;; meta-mode.el ends here