1 ;;; meta-mode.el --- major mode for editing Metafont or MetaPost sources.
3 ;; Copyright (C) 1997 by Ulrik Vieth.
5 ;; Author: Ulrik Vieth <vieth@thphy.uni-duesseldorf.de>
7 ;; Keywords: Metafont, MetaPost, tex, languages
9 ;;; This file is *not* part of GNU Emacs.
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)
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.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING. If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
30 ;; This Emacs Lisp package provides a major mode for editing Metafont
31 ;; or MetaPost sources. It includes all the necessary code to set up
32 ;; a major mode including an approriate syntax table, keymap, and a
33 ;; mode-specific pull-down menu. It also provides a sophisticated set
34 ;; of font-lock patterns, a fancy indentation function adapted from
35 ;; AUC-TeX's latex.el, and some basic mode-specific editing functions
36 ;; such as functions to move to the beginning or end of the enclosing
37 ;; environment, or to mark, re-indent, or comment-out environments.
38 ;; On the other hand, it doesn't yet provide any functionality for
39 ;; running Metafont or MetaPost in a shell buffer form within Emacs,
40 ;; but such functionality might be added later, either as part of this
41 ;; package or as a separate Emacs Lisp package.
45 ;; Install this file (meta-mode.el) in your personal or system-wide
46 ;; Emacs Lisp directory and add these lines to your startup files:
48 ;; (autoload 'metafont-mode "meta-mode" "Metafont editing mode." t)
49 ;; (autoload 'metapost-mode "meta-mode" "MetaPost editing mode." t)
51 ;; (setq auto-mode-alist
52 ;; (append '(("\\.mf\\'" . metafont-mode)
53 ;; ("\\.mp\\'" . metapost-mode)) auto-mode-alist))
55 ;; An interface to running Metafont or MetaPost as a shell process
56 ;; from within Emacs is currently under development as a separate
57 ;; Emacs Lisp package (meta-buf.el). In order to have that package
58 ;; loaded automatically when first entering Metafont or MetaPost mode,
59 ;; you might use the load-hook provided in this package by adding
60 ;; these lines to your startup file:
62 ;; (add-hook 'meta-mode-load-hook
63 ;; '(lambda () (require 'meta-buf)))
65 ;; The add-on package loaded this way may in turn make use of the
66 ;; mode-hooks provided in this package to activate additional features
67 ;; when entering Metafont or MetaPost mode.
71 ;; If you are using global-font-lock-mode (introduced in Emacs 19.31),
72 ;; fontification in Metafont and/or MetaPost mode will be activated
73 ;; automatically. To speed up fontification for the rather complex
74 ;; patterns used in these modes, it may be a good idea to activate
75 ;; lazy-lock as a font-lock-support-mode (introduced in Emacs 19.32)
76 ;; by adding these lines to your startup file:
78 ;; (global-font-lock-mode t)
79 ;; (setq font-lock-support-mode 'lazy-lock-mode)
81 ;; If you are using an older version of Emacs, which doesn't provide
82 ;; global-font-lock-mode or font-lock-support-mode, you can also
83 ;; activate fontification in Metafont and/or MetaPost mode by adding
84 ;; the following lines to your startup file:
86 ;; (add-hook 'meta-common-mode-hook 'turn-on-font-lock)
87 ;; (add-hook 'meta-common-mode-hook 'turn-on-lazy-lock)
91 ;; Following the usual Emacs Lisp coding conventions, the major modes
92 ;; defined in this package provide several hook variables to allow for
93 ;; local customization when entering the modes. In particular, there
94 ;; is a `meta-common-mode-hook' which applies to both modes as well as
95 ;; `metafont-mode-hook' and `metapost-mode-hook' which apply to the
96 ;; individual modes. In addition, there are several variables and
97 ;; regexps controlling e.g. the behavior of the indentation function,
98 ;; which may be customized via `edit-options'. Please refer to the
99 ;; docstrings in the code below for details.
103 ;; This package is currently available via my "TeX Software" WWW page:
105 ;; http://www.thphy.uni-duesseldorf.de/~vieth/subjects/tex/software.html
107 ;; As of this version 1.0, this package will be uploaded to CTAN
108 ;; archives, where it shall find a permanent home, presumably in
109 ;; tex-archive/support/emacs-modes. It will also be submitted for
110 ;; integration into the GNU Emacs distribution at that time.
114 ;; v 0.0 -- 1997/02/01 UV Started writing meta-mode.el.
115 ;; v 0.1 -- 1997/02/02 UV Added preliminary set of font-lock patterns.
116 ;; v 0.2 -- 1997/02/03 UV Improved and debugged font-lock patterns.
117 ;; Added indent-line-function for TAB.
118 ;; v 0.3 -- 1997/02/17 UV Improved font-lock patterns and syntax table.
119 ;; Improved and debbuged indentation function.
120 ;; v 0.4 -- 1997/02/18 UV Added functions to indent regions for M-C-q,
121 ;; also added a preliminary mode-specific menu.
122 ;; v 0.5 -- 1997/02/19 UV Added functions to skip to next or previous
123 ;; defun and to re-indent or comment-out defuns.
124 ;; v 0.6 -- 1997/02/20 UV More debugging, testing and clean-up.
125 ;; v 0.7 -- 1997/02/22 UV Use easymenu to define mode-specific menu.
126 ;; v 0.8 -- 1997/02/24 UV Added completion function for M-TAB.
127 ;; v 0.9 -- 1997/03/08 UV Added fill-paragraph function for comments.
128 ;; Also fixed a few remaining font-lock problems.
129 ;; Added meta-mode-load-hook to load meta-buf.el.
130 ;; v 1.0 -- 1997/04/07 UV Cleanup for official public release.
132 ;; Historical Footnote:
134 ;; This package was begun on February 1, 1997, exactly 20 years after
135 ;; the genesis of TeX took place according to Don Knuth's own account
136 ;; (cf. ``The Errors of TeX'', reprinted in ``Literate Programming'',
137 ;; Chapter 10, p. 249). What better date could there be to choose?
147 (defvar meta-font-lock-keywords
148 (let ((input-keywords
149 "\\(input\\|generate\\)")
151 (concat "\\(begin\\(char\\|fig\\|graph\\|logochar\\)\\|"
152 "\\cmchar\\|dcchar\\|ecchar\\)"))
154 "\\(end\\(char\\|fig\\|graph\\)\\)")
156 "\\(def\\|let\\|mode_def\\|vardef\\)")
158 "\\(primarydef\\|secondarydef\\|tertiarydef\\)")
160 ; '("expr" "suffix" "text" "primary" "secondary" "tertiary") t)
162 (concat "\\(expr\\|primary\\|s\\(econdary\\|uffix\\)\\|"
163 "te\\(rtiary\\|xt\\)\\)"))
165 ; '("boolean" "color" "numeric" "pair" "path" "pen" "picture"
166 ; "string" "transform" "newinternal") t)
168 (concat "\\(boolean\\|color\\|n\\(ewinternal\\|umeric\\)\\|"
169 "p\\(a\\(ir\\|th\\)\\|en\\|icture\\)\\|string\\|"
172 ; '("for" "forever" "forsuffixes" "endfor"
173 ; "step" "until" "upto" "downto" "thru" "within"
174 ; "iff" "if" "elseif" "else" "fi" "exitif" "exitunless"
175 ; "let" "def" "vardef" "enddef" "mode_def"
176 ; "true" "false" "known" "unknown" "and" "or" "not"
177 ; "save" "interim" "inner" "outer" "relax"
178 ; "begingroup" "endgroup" "expandafter" "scantokens"
179 ; "generate" "input" "endinput" "end" "bye"
180 ; "message" "errmessage" "errhelp" "special" "numspecial"
181 ; "readstring" "readfrom" "write") t)
183 (concat "\\(and\\|b\\(egingroup\\|ye\\)\\|"
184 "d\\(ef\\|ownto\\)\\|e\\(lse\\(\\|if\\)"
185 "\\|nd\\(\\|def\\|for\\|group\\|input\\)"
186 "\\|rr\\(help\\|message\\)"
187 "\\|x\\(it\\(if\\|unless\\)\\|pandafter\\)\\)\\|"
188 "f\\(alse\\|i\\|or\\(\\|ever\\|suffixes\\)\\)\\|"
189 "generate\\|i\\(ff?\\|n\\(ner\\|put\\|terim\\)\\)\\|"
190 "known\\|let\\|m\\(essage\\|ode_def\\)\\|"
191 "n\\(ot\\|umspecial\\)\\|o\\(r\\|uter\\)\\|"
192 "re\\(ad\\(from\\|string\\)\\|lax\\)\\|"
193 "s\\(ave\\|cantokens\\|pecial\\|tep\\)\\|"
194 "t\\(hru\\|rue\\)\\|"
195 "u\\(n\\(known\\|til\\)\\|pto\\)\\|"
196 "vardef\\|w\\(ithin\\|rite\\)\\)"))
199 ;; embedded TeX code in btex ... etex
200 (cons (concat "\\(btex\\|verbatimtex\\)"
201 "[ \t]+\\(.*\\)[ \t]+"
203 '((1 font-lock-keyword-face)
204 (2 font-lock-string-face)
205 (3 font-lock-keyword-face)))
206 ;; unary macro definitions: def, vardef, let
207 (cons (concat "\\<" macro-keywords-1 "\\>"
208 "[ \t]+\\(\\sw+\\|\\s_+\\|\\s.+\\)")
209 '((1 font-lock-keyword-face)
210 (2 font-lock-function-name-face)))
211 ;; binary macro defintions: <leveldef> x operator y
212 (cons (concat "\\<" macro-keywords-2 "\\>"
214 "[ \t]*\\(\\sw+\\|\\s.+\\)"
216 '((1 font-lock-keyword-face)
217 (2 font-lock-variable-name-face nil t)
218 (3 font-lock-function-name-face nil t)
219 (4 font-lock-variable-name-face nil t)))
220 ;; variable declarations: numeric, pair, color, ...
221 (cons (concat "\\<" type-keywords "\\>"
222 "\\([ \t]+\\(\\sw+\\)\\)*")
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 ;; argument declarations: expr, suffix, text, ...
228 (cons (concat "\\<" args-keywords "\\>"
229 "\\([ \t]+\\(\\sw+\\|\\s_+\\)\\)*")
230 '((1 font-lock-type-face)
231 (font-lock-match-meta-declaration-item-and-skip-to-next
232 (goto-char (match-end 1)) nil
233 (1 font-lock-variable-name-face nil t))))
234 ;; special case of arguments: expr x of y
235 (cons (concat "\\(expr\\)[ \t]+\\(\\sw+\\)"
236 "[ \t]+\\(of\\)[ \t]+\\(\\sw+\\)")
237 '((1 font-lock-type-face)
238 (2 font-lock-variable-name-face)
239 (3 font-lock-keyword-face nil t)
240 (4 font-lock-variable-name-face nil t)))
241 ;; syntactic keywords
242 (cons (concat "\\<" syntactic-keywords "\\>")
243 'font-lock-keyword-face)
244 ;; beginchar, beginfig
245 (cons (concat "\\<" begin-keywords "\\>")
246 'font-lock-keyword-face)
248 (cons (concat "\\<" end-keywords "\\>")
249 'font-lock-keyword-face)
251 (cons (concat "\\<" input-keywords "\\>"
253 '((1 font-lock-keyword-face)
254 (2 font-lock-reference-face)))
255 ;; embedded Metafont/MetaPost code in comments
256 (cons "|\\([^|]+\\)|"
257 '(1 font-lock-reference-face t))
259 "Default expressions to highlight in Metafont or MetaPost mode.")
262 (defun font-lock-match-meta-declaration-item-and-skip-to-next (limit)
263 ;; Match and move over Metafont/MetaPost declaration item after point.
265 ;; The expected syntax of an item is either "word" or "symbol",
266 ;; possibly ending with optional whitespace. Everything following
267 ;; the item (but belonging to it) is expected to by skipable by
268 ;; `forward-sexp'. The list of items is expected to be separated
269 ;; by commas and terminated by semicolons or equals signs.
271 (if (looking-at "[ \t]*\\(\\sw+\\|\\s_+\\)")
275 ;; Restrict to end of line, currently guaranteed to be LIMIT.
276 (narrow-to-region (point-min) limit)
277 (goto-char (match-end 1))
278 ;; Move over any item value, etc., to the next item.
279 (while (not (looking-at "[ \t]*\\(\\(,\\)\\|;\\|=\\|$\\)"))
280 (goto-char (or (scan-sexps (point) 1) (point-max))))
281 (goto-char (match-end 2)))
288 ;; The data used to prepare the following lists of primitives and
289 ;; standard macros available in Metafont or MetaPost was extracted
290 ;; from the original sources like this:
292 ;; grep '^primitive' texk-7.0/web2c/{mf,mp}.web |\
293 ;; sed 's/primitive(\("[a-zA-Z]*"\).*/\1/' > {mf,mp}_prim.list
295 ;; grep '\(let\|def\|vardef\|primarydef\|secondarydef\|tertiarydef\)'
296 ;; texmf/meta{font,post}/plain.{mf,mp} > {mf,mp}_plain.list
298 (defconst meta-common-primitives-list
299 '("ASCII" "addto" "also" "and" "angle" "atleast" "batchmode"
300 "begingroup" "boolean" "boundarychar" "char" "charcode" "chardp"
301 "charexists" "charext" "charht" "charic" "charlist" "charwd"
302 "contour" "controls" "cosd" "curl" "cycle" "day" "decimal" "def"
303 "delimiters" "designsize" "directiontime" "doublepath" "dump" "else"
304 "elseif" "end" "enddef" "endfor" "endgroup" "endinput" "errhelp"
305 "errmessage" "errorstopmode" "everyjob" "exitif" "expandafter"
306 "expr" "extensible" "false" "fi" "floor" "fontdimen" "fontmaking"
307 "for" "forever" "forsuffixes" "headerbyte" "hex" "if" "inner"
308 "input" "interim" "intersectiontimes" "jobname" "kern" "known"
309 "length" "let" "ligtable" "makepath" "makepen" "message" "mexp"
310 "mlog" "month" "newinternal" "nonstopmode" "normaldeviate" "not"
311 "nullpen" "nullpicture" "numeric" "oct" "odd" "of" "or" "outer"
312 "pair" "path" "pausing" "pen" "pencircle" "penoffset" "picture"
313 "point" "postcontrol" "precontrol" "primary" "primarydef" "quote"
314 "randomseed" "readstring" "reverse" "rotated" "save" "scaled"
315 "scantokens" "scrollmode" "secondary" "secondarydef" "shifted"
316 "shipout" "show" "showdependencies" "showstats" "showstopping"
317 "showtoken" "showvariable" "sind" "skipto" "slanted" "special"
318 "sqrt" "step" "str" "string" "subpath" "substring" "suffix"
319 "tension" "tertiary" "tertiarydef" "text" "time" "to"
320 "tracingcapsules" "tracingchoices" "tracingcommands"
321 "tracingequations" "tracingmacros" "tracingonline" "tracingoutput"
322 "tracingrestores" "tracingspecs" "tracingstats" "tracingtitles"
323 "transform" "transformed" "true" "turningnumber" "uniformdeviate"
324 "unknown" "until" "vardef" "warningcheck" "withpen" "xpart"
325 "xscaled" "xxpart" "xypart" "year" "ypart" "yscaled" "yxpart"
327 "List of primitives common to Metafont and MetaPost.")
329 (defconst metafont-primitives-list
330 '("at" "autorounding" "chardx" "chardy" "cull" "display"
331 "dropping" "fillin" "from" "granularity" "hppp" "inwindow"
332 "keeping" "numspecial" "openwindow" "proofing" "smoothing"
333 "totalweight" "tracingedges" "tracingpens" "turningcheck" "vppp"
334 "withweight" "xoffset" "yoffset")
335 "List of primitives only defined in Metafont.")
337 (defconst metapost-primitives-list
338 '("arclength" "arctime" "bluepart" "bounded" "btex" "clip"
339 "clipped" "color" "dashed" "dashpart" "etex" "filled" "fontpart"
340 "fontsize" "greenpart" "infont" "linecap" "linejoin" "llcorner"
341 "lrcorner" "miterlimit" "mpxbreak" "pathpart" "penpart"
342 "prologues" "readfrom" "redpart" "setbounds" "stroked" "textpart"
343 "textual" "tracinglostchars" "truecorners" "ulcorner" "urcorner"
344 "verbatimtex" "withcolor" "within" "write")
345 "List of primitives only defined in MetaPost.")
347 (defconst meta-common-plain-macros-list
348 '( "abs" "bot" "bye" "byte" "ceiling" "clear_pen_memory"
349 "clearit" "clearpen" "clearxy" "counterclockwise" "cutdraw" "decr"
350 "dir" "direction" "directionpoint" "div" "dotprod" "downto" "draw"
351 "drawdot" "erase" "exitunless" "fill" "filldraw" "flex" "gobble"
352 "hide" "incr" "interact" "interpath" "intersectionpoint" "inverse"
353 "label" "labels" "lft" "loggingall" "magstep" "makelabel" "max"
354 "min" "mod" "numtok" "penlabels" "penpos" "penstroke" "pickup"
355 "range" "reflectedabout" "relax" "rotatedabout" "rotatedaround"
356 "round" "rt" "savepen" "shipit" "softjoin" "solve" "stop"
357 "superellipse" "takepower" "tensepath" "thru" "top" "tracingall"
358 "tracingnone" "undraw" "undrawdot" "unfill" "unfilldraw"
359 "unitvector" "upto" "whatever")
360 "List of macros common to plain Metafont and MetaPost.")
362 (defconst metafont-plain-macros-list
363 '("beginchar" "change_width" "culldraw" "cullit" "cutoff"
364 "define_blacker_pixels" "define_corrected_pixels"
365 "define_good_x_pixels" "define_good_y_pixels"
366 "define_horizontal_corrected_pixels" "define_pixels"
367 "define_whole_blacker_pixels" "define_whole_pixels"
368 "define_whole_vertical_blacker_pixels"
369 "define_whole_vertical_pixels" "endchar" "fix_units"
370 "font_coding_scheme" "font_extra_space" "font_identifier"
371 "font_normal_shrink" "font_normal_space" "font_normal_stretch"
372 "font_quad" "font_size" "font_slant" "font_x_height" "gfcorners"
373 "good.bot" "good.lft" "good.rt" "good.top" "good.x" "good.y"
374 "grayfont" "hround" "imagerules" "italcorr" "labelfont"
375 "lowres_fix" "makebox" "makegrid" "maketicks" "mode_lowres"
376 "mode_proof" "mode_setup" "mode_smoke" "nodisplays" "notransforms"
377 "openit" "penrazor" "pensquare" "proofoffset" "proofrule"
378 "proofrulethickness" "screenchars" "screenrule" "screenstrokes"
379 "showit" "slantfont" "smode" "titlefont" "vround")
380 "List of macros only defined in plain Metafont.")
382 (defconst metapost-plain-macros-list
383 '("arrowhead" "bbox" "beginfig" "buildcycle" "center" "cutafter"
384 "cutbefore" "dashpattern" "dotlabel" "dotlabels" "drawarrow"
385 "drawdblarrow" "drawoptions" "endfig" "image" "label" "off" "on"
387 "List of macros only defined in plain MetaPost.")
389 (defconst metapost-graph-macros-list
390 '("augment" "auto.x" "auto.y" "autogrid" "begingraph" "endgraph"
391 "format" "frame" "gdata" "gdotlabel" "gdraw" "gdrawarrow"
392 "gdrawdblarrow" "gfill" "glabel" "grid" "itick" "otick" "plot"
393 "setcoords" "setrange")
394 "List of macros only defined in MetaPost \"graph\" package.")
396 (defconst metapost-boxes-macros-list
397 '("boxit" "boxjoin" "bpath" "circleit" "drawboxed" "drawboxes"
398 "drawunboxed" "fixpos" "fixsize" "pic" "rboxit")
399 "List of macros only defined in MetaPost \"boxes\" package.")
402 (defvar metafont-symbol-list
403 (append meta-common-primitives-list
404 metafont-primitives-list
405 meta-common-plain-macros-list
406 metafont-plain-macros-list)
407 "List of known symbols to complete in Metafont mode.")
409 (defvar metapost-symbol-list
410 (append meta-common-primitives-list
411 metapost-primitives-list
412 meta-common-plain-macros-list
413 metapost-plain-macros-list
414 metapost-graph-macros-list
415 metapost-boxes-macros-list)
416 "List of known symbols to complete in MetaPost mode.")
419 (defvar meta-symbol-list nil
420 "List of known symbols to complete in Metafont or MetaPost mode.")
422 (defvar meta-symbol-changed nil
423 "Flag indicating whether `meta-symbol-list' has been initialized.")
425 (defvar meta-complete-list nil
426 ; (list (list "\\<\\(\\sw+\\)" 1 'meta-symbol-list)
427 ; (list "" 'ispell-complete-word))
428 "List of ways to perform completion in Metafont or MetaPost mode.
430 Each entry is a list with the following elements:
431 1. Regexp matching the preceding text.
432 2. A number indicating the subgroup in the regexp containing the text.
433 3. A function returning an alist of possible completions.
434 4. Text to append after a succesful completion (if any).
437 1. Regexp matching the preceding text.
438 2. Function to do the actual completion.")
441 (defun meta-add-symbols (&rest entries)
442 "Add entries to list of known symbols in Metafont or MetaPost mode."
443 (if meta-symbol-changed
444 (setq meta-symbol-list (cons entries meta-symbol-list))
445 (setq meta-symbol-changed t)
446 (setq meta-symbol-list (cons entries meta-symbol-list))))
448 (defun meta-symbol-list ()
449 "Return value of list of known symbols in Metafont or MetaPost mode.
450 If the list was changed, sort the list and remove duplicates first."
451 (if (not meta-symbol-changed)
453 (setq meta-symbol-changed nil)
454 (message "Preparing completion list...")
455 ;; sort list of symbols
456 (setq meta-symbol-list
457 (sort (mapcar 'meta-listify (apply 'append meta-symbol-list))
458 'meta-car-string-lessp))
460 (let ((entry meta-symbol-list))
461 (while (and entry (cdr entry))
462 (let ((this (car entry))
463 (next (car (cdr entry))))
464 (if (not (string-equal (car this) (car next)))
465 (setq entry (cdr entry))
466 (if (> (length next) (length this))
467 (setcdr this (cdr next)))
468 (setcdr entry (cdr (cdr entry)))))))
469 (message "Preparing completion list... done"))
472 (defun meta-listify (a)
473 ;; utility function used in `meta-add-symbols'
474 (if (listp a) a (list a)))
476 (defun meta-car-string-lessp (a b)
477 ;; utility function used in `meta-add-symbols'
478 (string-lessp (car a) (car b)))
481 (defun meta-complete-symbol ()
482 "Perform completion on Metafont or MetaPost symbol preceding point."
484 (let ((list meta-complete-list)
487 (setq entry (car list)
489 (if (meta-looking-at-backward (car entry) 200)
491 (if (numberp (nth 1 entry))
492 (let* ((sub (nth 1 entry))
493 (close (nth 3 entry))
494 (begin (match-beginning sub))
495 (end (match-end sub))
496 (pattern (meta-match-buffer 0))
497 (symbol (buffer-substring begin end))
498 (list (funcall (nth 2 entry)))
499 (completion (try-completion symbol list)))
500 (cond ((eq completion t)
502 (not (looking-at (regexp-quote close)))
505 (error "Can't find completion for \"%s\"" pattern))
506 ((not (string-equal symbol completion))
507 (delete-region begin end)
510 (eq (try-completion completion list) t)
511 (not (looking-at (regexp-quote close)))
514 (message "Making completion list...")
515 (let ((list (all-completions symbol list nil)))
516 (with-output-to-temp-buffer "*Completions*"
517 (display-completion-list list)))
518 (message "Making completion list... done"))))
519 (funcall (nth 1 entry)))))
522 (defun meta-looking-at-backward (regexp &optional limit)
523 ;; utility function used in `meta-complete-symbol'
526 (and (re-search-backward
527 regexp (if limit (max (point-min) (- (point) limit))) t)
528 (eq (match-end 0) pos)))))
530 (defun meta-match-buffer (n)
531 ;; utility function used in `meta-complete-symbol'
532 (if (match-beginning n)
533 (let ((str (buffer-substring (match-beginning n) (match-end n))))
534 (set-text-properties 0 (length str) nil str)
542 (defvar meta-indent-level 2
543 "*Indentation of begin-end blocks in Metafont or MetaPost mode.")
546 (defvar meta-left-comment-regexp "%%+"
547 "*Regexp matching comments that should be placed on the left margin.")
549 (defvar meta-right-comment-regexp nil
550 "*Regexp matching comments that should be placed to the right margin.")
552 (defvar meta-ignore-comment-regexp "%[^%]"
553 "*Regexp matching comments that whose indentation should not be touched.")
556 (defvar meta-begin-environment-regexp
557 (concat "\\(begin\\(char\\|fig\\|gr\\(aph\\|oup\\)\\|logochar\\)\\|"
558 "def\\|for\\(\\|ever\\|suffixes\\)\\|if\\|mode_def\\|"
559 "primarydef\\|secondarydef\\|tertiarydef\\|vardef\\)")
560 "*Regexp matching the beginning of environments to be indented.")
562 (defvar meta-end-environment-regexp
563 (concat "\\(end\\(char\\|def\\|f\\(ig\\|or\\)\\|gr\\(aph\\|oup\\)\\)"
565 "*Regexp matching the end of environments to be indented.")
567 (defvar meta-within-environment-regexp
568 ; (concat "\\(e\\(lse\\(\\|if\\)\\|xit\\(if\\|unless\\)\\)\\)")
569 (concat "\\(else\\(\\|if\\)\\)")
570 "*Regexp matching keywords within environments not to be indented.")
573 (defun meta-comment-indent ()
574 "Return the indentation for a comment in Metafont or MetaPost mode."
575 (if (and meta-left-comment-regexp
576 (looking-at meta-left-comment-regexp))
578 (skip-chars-backward "\t ")
579 (max (if (bolp) 0 (1+ (current-column)))
582 (defun meta-indent-line ()
583 "Indent the line containing point as Metafont or MetaPost source."
585 (let ((indent (meta-indent-calculate)))
587 (if (/= (current-indentation) indent)
588 (let ((beg (progn (beginning-of-line) (point)))
589 (end (progn (back-to-indentation) (point))))
590 (delete-region beg end)
591 (indent-to indent))))
592 (if (< (current-column) indent)
593 (back-to-indentation))))
595 (defun meta-indent-calculate ()
596 "Return the indentation of current line of Metafont or MetaPost source."
598 (back-to-indentation)
600 ;; Comments to the left margin.
601 ((and meta-left-comment-regexp
602 (looking-at meta-left-comment-regexp))
604 ;; Comments to the right margin.
605 ((and meta-right-comment-regexp
606 (looking-at meta-right-comment-regexp))
608 ;; Comments best left alone.
609 ((and meta-ignore-comment-regexp
610 (looking-at meta-ignore-comment-regexp))
611 (current-indentation))
612 ;; Backindent at end of environments.
614 (concat "\\<" meta-end-environment-regexp "\\>"))
615 (- (meta-indent-calculate-last) meta-indent-level))
616 ;; Backindent at keywords within environments.
618 (concat "\\<" meta-within-environment-regexp "\\>"))
619 (- (meta-indent-calculate-last) meta-indent-level))
620 (t (meta-indent-calculate-last)))))
622 (defun meta-indent-calculate-last ()
623 "Return the indentation of previous line of Metafont or MetaPost source."
626 (skip-chars-backward "\n\t ")
627 (move-to-column (current-indentation))
629 (while (and (looking-at comment-start) (not (bobp)))
630 (skip-chars-backward "\n\t ")
632 (move-to-column (current-indentation))))
635 (t (+ (current-indentation)
636 (meta-indent-level-count)
638 ;; Compensate for backindent at end of environments.
640 (concat "\\<"meta-end-environment-regexp "\\>"))
642 ;; Compensate for backindent within environments.
644 (concat "\\<" meta-within-environment-regexp "\\>"))
649 (defun meta-indent-level-count ()
650 "Count indentation change for begin-end commands in the current line."
655 (point) (save-excursion
656 (re-search-forward "[^\\\\\"]%\\|\n\\|\\'" nil t)
657 (backward-char) (point)))
658 (while (re-search-forward "\\<\\sw+\\>\\|(\\|)" nil t)
660 (goto-char (match-beginning 0))
662 ;; Count number of begin-end keywords within line.
664 (concat "\\<" meta-begin-environment-regexp "\\>"))
665 (setq count (+ count meta-indent-level)))
667 (concat "\\<" meta-end-environment-regexp "\\>"))
668 (setq count (- count meta-indent-level)))
669 ;; Count number of open-close parentheses within line.
671 (setq count (+ count meta-indent-level)))
673 (setq count (- count meta-indent-level)))
679 ;;; Filling paragraphs.
681 (defun meta-fill-paragraph (&optional justify)
682 "Like \\[fill-paragraph], but handle Metafont or MetaPost comments.
683 If any part of the current line is a comment, fill the comment or the
684 paragraph of it that point is in, preserving the comment's indentation
685 and initial semicolons."
687 (let (has-comment ; Non-nil if line contains a comment.
688 has-code-and-comment ; Non-nil if line contains code and a comment.
689 comment-fill-prefix ; If has-comment, fill-prefix for the comment.
691 ;; Figure out what kind of comment we are looking at.
695 ;; A line with nothing but a comment on it?
696 ((looking-at (concat "[ \t]*" comment-start-skip))
698 (setq comment-fill-prefix
699 (buffer-substring (match-beginning 0) (match-end 0))))
700 ;; A line with some code, followed by a comment?
703 (narrow-to-region (point-min)
704 (save-excursion (end-of-line) (point)))
705 (while (not (looking-at (concat comment-start "\\|$")))
706 (skip-chars-forward (concat "^" comment-start "\n\"\\\\"))
708 ((eq (char-after (point)) ?\\) (forward-char 2))
709 ((eq (char-after (point)) ?\") (forward-sexp 1))))
710 (looking-at comment-start-skip))
713 has-code-and-comment t)
714 (setq comment-fill-prefix
715 (concat (make-string (/ (current-column) 8) ?\t)
716 (make-string (% (current-column) 8) ?\ )
717 (buffer-substring (match-beginning 0) (match-end 0)))))
719 (if (not has-comment)
720 (fill-paragraph justify)
721 ;; Narrow to include only the comment, and then fill the region.
726 ;; Find the first line we should include in the region to fill.
728 (while (and (zerop (forward-line -1))
729 (looking-at (concat "^[ \t]*" comment-start))))
730 (or (looking-at (concat ".*" comment-start))
733 ;; Find the beginning of the first line past the region to fill.
735 (while (progn (forward-line 1)
736 (looking-at (concat "^[ \t]*" comment-start))))
738 (let* ((paragraph-start
739 (concat paragraph-start "\\|[ \t%]*$"))
741 (concat paragraph-start "\\|[ \t%]*$"))
742 (paragraph-ignore-fill-prefix nil)
743 (fill-prefix comment-fill-prefix)
744 (after-line (if has-code-and-comment
745 (save-excursion (forward-line 1) (point))))
746 (end (progn (forward-paragraph)
747 (or (bolp) (newline 1))
749 (beg (progn (backward-paragraph)
750 (if (eq (point) after-line) (forward-line -1))
752 (after-pos (save-excursion
754 (if (not (looking-at fill-prefix))
756 (re-search-forward comment-start-skip)
759 (fill-region-as-paragraph beg end justify nil after-pos))
765 ;;; Editing commands.
767 (defvar meta-begin-defun-regexp
768 (concat "\\(begin\\(char\\|fig\\|logochar\\)\\|def\\|mode_def\\|"
769 "primarydef\\|secondarydef\\|tertiarydef\\|vardef\\)")
770 "*Regexp matching beginning of defuns in Metafont or MetaPost mode.")
772 (defvar meta-end-defun-regexp
773 (concat "\\(end\\(char\\|def\\|fig\\)\\)")
774 "*Regexp matching the end of defuns in Metafont or MetaPost mode.")
777 (defun meta-beginning-of-defun (&optional arg)
778 "Move backward to beginnning of a defun in Metafont or MetaPost code.
779 With numeric argument, do it that many times.
780 Negative arg -N means move forward to Nth following beginning of defun.
781 Returns t unless search stops due to beginning or end of buffer."
783 (if (or (null arg) (= 0 arg)) (setq arg 1))
784 (and arg (< arg 0) (not (eobp)) (forward-char 1))
785 (and (re-search-backward
786 (concat "\\<" meta-begin-defun-regexp "\\>") nil t arg)
787 (progn (goto-char (match-beginning 0))
788 (skip-chars-backward "%")
789 (skip-chars-backward " \t") t)))
791 (defun meta-end-of-defun (&optional arg)
792 "Move forward to end of a defun in Metafont or MetaPost code.
793 With numeric argument, do it that many times.
794 Negative argument -N means move back to Nth preceding end of defun.
795 Returns t unless search stops due to beginning or end of buffer."
797 (if (or (null arg) (= 0 arg)) (setq arg 1))
798 (and (< arg 0) (not (bobp)) (forward-line -1))
799 (and (re-search-forward
800 (concat "\\<" meta-end-defun-regexp "\\>") nil t arg)
801 (progn (goto-char (match-end 0))
802 (skip-chars-forward ";")
803 (skip-chars-forward " \t")
804 (if (looking-at "\n") (forward-line 1)) t)))
807 (defun meta-comment-region (beg end &optional arg)
808 "Comment out active region as Metafont or MetaPost source."
810 (comment-region beg end arg))
812 (defun meta-uncomment-region (beg end)
813 "Uncomment active region as Metafont or MetaPost source."
815 (comment-region beg end -1))
817 (defun meta-comment-defun (&optional arg)
818 "Comment out current environment as Metafont or MetaPost source.
819 With prefix argument, uncomment the environment.
820 The environment used is the one that contains point or follows point."
823 (let* ((end (if (meta-end-of-defun) (point) (point-max)))
824 (beg (if (meta-beginning-of-defun) (point) (point-min))))
825 (comment-region beg end arg))))
827 (defun meta-uncomment-defun ()
828 "Uncomment current environment as Metafont or MetaPost source."
830 (meta-comment-defun -1))
833 (defun meta-indent-region (beg end)
834 "Indent the active region as Metafont or MetaPost source."
836 (indent-region beg end nil))
838 (defun meta-indent-buffer ()
839 "Indent the whole buffer contents as Metafont or MetaPost source."
842 (indent-region (point-min) (point-max) nil)))
844 (defun meta-indent-defun ()
845 "Indent the current environment as Metafont or MetaPost source.
846 The environment indented is the one that contains point or follows point."
849 (let* ((end (if (meta-end-of-defun) (point) (point-max)))
850 (beg (if (meta-beginning-of-defun) (point) (point-min))))
851 (indent-region beg end nil))))
854 (defun meta-mark-defun ()
855 "Put mark at end of the environment, point at the beginning.
856 The environment marked is the one that contains point or follows point."
860 (push-mark (point) nil t)
861 (meta-beginning-of-defun))
865 ;;; Syntax table, keymap and menu.
867 (defvar meta-mode-abbrev-table nil
868 "Abbrev table used in Metafont or MetaPost mode.")
869 (define-abbrev-table 'meta-mode-abbrev-table ())
871 (defvar meta-mode-syntax-table nil
872 "Syntax table used in Metafont or MetaPost mode.")
873 (if meta-mode-syntax-table
875 (setq meta-mode-syntax-table (make-syntax-table))
876 ;; underscores are word constituents
877 (modify-syntax-entry ?_ "w" meta-mode-syntax-table)
878 ;; miscellaneous non-word symbols
879 (modify-syntax-entry ?# "_" meta-mode-syntax-table)
880 (modify-syntax-entry ?@ "_" meta-mode-syntax-table)
881 (modify-syntax-entry ?$ "_" meta-mode-syntax-table)
882 (modify-syntax-entry ?? "_" meta-mode-syntax-table)
883 (modify-syntax-entry ?! "_" meta-mode-syntax-table)
885 (modify-syntax-entry ?& "." meta-mode-syntax-table)
886 (modify-syntax-entry ?+ "." meta-mode-syntax-table)
887 (modify-syntax-entry ?- "." meta-mode-syntax-table)
888 (modify-syntax-entry ?/ "." meta-mode-syntax-table)
889 (modify-syntax-entry ?* "." meta-mode-syntax-table)
890 (modify-syntax-entry ?. "." meta-mode-syntax-table)
891 (modify-syntax-entry ?: "." meta-mode-syntax-table)
892 (modify-syntax-entry ?= "." meta-mode-syntax-table)
893 (modify-syntax-entry ?< "." meta-mode-syntax-table)
894 (modify-syntax-entry ?> "." meta-mode-syntax-table)
895 (modify-syntax-entry ?| "." meta-mode-syntax-table)
896 ;; opening and closing delimiters
897 (modify-syntax-entry ?\( "()" meta-mode-syntax-table)
898 (modify-syntax-entry ?\) ")(" meta-mode-syntax-table)
899 (modify-syntax-entry ?\[ "(]" meta-mode-syntax-table)
900 (modify-syntax-entry ?\] ")[" meta-mode-syntax-table)
901 (modify-syntax-entry ?\{ "(}" meta-mode-syntax-table)
902 (modify-syntax-entry ?\} "){" meta-mode-syntax-table)
904 (modify-syntax-entry ?% "<" meta-mode-syntax-table)
905 (modify-syntax-entry ?\n ">" meta-mode-syntax-table)
906 ;; escape character, needed for embedded TeX code
907 (modify-syntax-entry ?\\ "\\" meta-mode-syntax-table)
910 (defvar meta-mode-map nil
911 "Keymap used in Metafont or MetaPost mode.")
914 (setq meta-mode-map (make-sparse-keymap))
915 (define-key meta-mode-map "\t" 'meta-indent-line)
916 (define-key meta-mode-map "\C-m" 'reindent-then-newline-and-indent)
917 ;; Comment Paragraphs:
918 ; (define-key meta-mode-map "\M-a" 'backward-sentence)
919 ; (define-key meta-mode-map "\M-e" 'forward-sentence)
920 ; (define-key meta-mode-map "\M-h" 'mark-paragraph)
921 ; (define-key meta-mode-map "\M-q" 'fill-paragraph)
923 (define-key meta-mode-map "\M-\C-a" 'meta-beginning-of-defun)
924 (define-key meta-mode-map "\M-\C-e" 'meta-end-of-defun)
925 (define-key meta-mode-map "\M-\C-h" 'meta-mark-defun)
927 (define-key meta-mode-map "\M-\C-q" 'meta-indent-defun)
928 (define-key meta-mode-map "\C-c\C-qe" 'meta-indent-defun)
929 (define-key meta-mode-map "\C-c\C-qr" 'meta-indent-region)
930 (define-key meta-mode-map "\C-c\C-qb" 'meta-indent-buffer)
932 (define-key meta-mode-map "\C-c%" 'meta-comment-defun)
933 ; (define-key meta-mode-map "\C-uC-c%" 'meta-uncomment-defun)
934 (define-key meta-mode-map "\C-c;" 'meta-comment-region)
935 (define-key meta-mode-map "\C-c:" 'meta-uncomment-region)
936 ;; Symbol Completion:
937 (define-key meta-mode-map "\M-\t" 'meta-complete-symbol)
939 ; (define-key meta-mode-map "\C-c\C-c" 'meta-command-file)
940 ; (define-key meta-mode-map "\C-c\C-k" 'meta-kill-job)
941 ; (define-key meta-mode-map "\C-c\C-l" 'meta-recenter-output)
945 meta-mode-menu meta-mode-map
946 "Menu used in Metafont or MetaPost mode."
948 ["Forward Environment" meta-beginning-of-defun t]
949 ["Backward Environment" meta-end-of-defun t]
951 ["Indent Line" meta-indent-line t]
952 ["Indent Environment" meta-indent-defun t]
953 ["Indent Region" meta-indent-region
954 :active (meta-mark-active)]
955 ["Indent Buffer" meta-indent-buffer t]
957 ["Comment Out Environment" meta-comment-defun t]
958 ["Uncomment Environment" meta-uncomment-defun t]
959 ["Comment Out Region" meta-comment-region
960 :active (meta-mark-active)]
961 ["Uncomment Region" meta-uncomment-region
962 :active (meta-mark-active)]
964 ["Complete Symbol" meta-complete-symbol t]
966 ; ["Command on Buffer" meta-command-file t]
967 ; ["Kill Job" meta-kill-job t]
968 ; ["Recenter Output Buffer" meta-recenter-output-buffer t]
971 ;; Compatibility: XEmacs doesn't have the `mark-active' variable.
972 (defun meta-mark-active ()
973 "Return whether the mark and region are currently active in this buffer."
974 (or (and (boundp 'mark-active) mark-active) (mark)))
980 (defvar meta-mode-load-hook nil
981 "*Hook evaluated when first loading Metafont or MetaPost mode.")
983 (defvar meta-common-mode-hook nil
984 "*Hook evaluated by both `metafont-mode' and `metapost-mode'.")
986 (defvar metafont-mode-hook nil
987 "*Hook evaluated by `metafont-mode' after `meta-common-mode-hook'.")
988 (defvar metapost-mode-hook nil
989 "*Hook evaluated by `metapost-mode' after `meta-common-mode-hook'.")
995 (defun meta-common-initialization ()
996 "Common initialization for Metafont or MetaPost mode."
997 (kill-all-local-variables)
999 (make-local-variable 'paragraph-start)
1000 (make-local-variable 'paragraph-separate)
1001 (setq paragraph-start
1002 (concat page-delimiter "\\|$"))
1003 (setq paragraph-separate
1004 (concat page-delimiter "\\|$"))
1006 (make-local-variable 'paragraph-ignore-fill-prefix)
1007 (setq paragraph-ignore-fill-prefix t)
1009 (make-local-variable 'comment-start-skip)
1010 (make-local-variable 'comment-start)
1011 (make-local-variable 'comment-end)
1012 (make-local-variable 'comment-multi-line)
1013 (setq comment-start-skip "%+[ \t]*")
1014 (setq comment-start "%")
1015 (setq comment-end "")
1016 (setq comment-multi-line nil)
1018 (make-local-variable 'parse-sexp-ignore-comments)
1019 (setq parse-sexp-ignore-comments t)
1021 (make-local-variable 'comment-indent-function)
1022 (setq comment-indent-function 'meta-comment-indent)
1023 (make-local-variable 'fill-paragraph-function)
1024 (setq fill-paragraph-function 'meta-fill-paragraph)
1025 (make-local-variable 'indent-line-function)
1026 (setq indent-line-function 'meta-indent-line)
1027 ;; No need to define a mode-specific 'indent-region-function.
1028 ;; Simply use the generic 'indent-region and 'comment-region.
1030 ;; Set defaults for font-lock mode.
1031 (make-local-variable 'font-lock-defaults)
1032 (setq font-lock-defaults
1033 '(meta-font-lock-keywords
1034 nil nil ((?_ . "w")) nil
1035 (font-lock-comment-start-regexp . "%")))
1037 ;; Activate syntax table, keymap and menu.
1038 (setq local-abbrev-table meta-mode-abbrev-table)
1039 (set-syntax-table meta-mode-syntax-table)
1040 (use-local-map meta-mode-map)
1041 (easy-menu-add meta-mode-menu)
1045 (defun metafont-mode ()
1046 "Major mode for editing Metafont sources.
1050 Turning on Metafont mode calls the value of the variables
1051 `meta-common-mode-hook' and `metafont-mode-hook'."
1053 (meta-common-initialization)
1054 (setq mode-name "Metafont")
1055 (setq major-mode 'metafont-mode)
1057 ;; Set defaults for completion function.
1058 (make-local-variable 'meta-symbol-list)
1059 (make-local-variable 'meta-symbol-changed)
1060 (make-local-variable 'meta-complete-list)
1061 (setq meta-symbol-list nil)
1062 (setq meta-symbol-changed nil)
1063 (apply 'meta-add-symbols metafont-symbol-list)
1064 (setq meta-complete-list
1065 (list (list "\\<\\(\\sw+\\)" 1 'meta-symbol-list)
1066 (list "" 'ispell-complete-word)))
1067 (run-hooks 'meta-common-mode-hook 'metafont-mode-hook))
1069 (defun metapost-mode ()
1070 "Major mode for editing MetaPost sources.
1074 Turning on MetaPost mode calls the value of the variable
1075 `meta-common-mode-hook' and `metafont-mode-hook'."
1077 (meta-common-initialization)
1078 (setq mode-name "MetaPost")
1079 (setq major-mode 'metapost-mode)
1081 ;; Set defaults for completion function.
1082 (make-local-variable 'meta-symbol-list)
1083 (make-local-variable 'meta-symbol-changed)
1084 (make-local-variable 'meta-complete-list)
1085 (setq meta-symbol-list nil)
1086 (setq meta-symbol-changed nil)
1087 (apply 'meta-add-symbols metapost-symbol-list)
1088 (setq meta-complete-list
1089 (list (list "\\<\\(\\sw+\\)" 1 'meta-symbol-list)
1090 (list "" 'ispell-complete-word)))
1091 (run-hooks 'meta-common-mode-hook 'metapost-mode-hook))
1094 ;;; Just in case ...
1096 (provide 'meta-mode)
1097 (run-hooks 'meta-mode-load-hook)
1099 ;;; meta-mode.el ends here