1 ;;; meta-mode.el --- major mode for editing Metafont or MetaPost sources
3 ;; Copyright (C) 1997, 2001, 2002, 2003, 2004, 2005
4 ;; Free Software Foundation, Inc.
6 ;; Author: Ulrik Vieth <vieth@thphy.uni-duesseldorf.de>
8 ;; Keywords: Metafont, MetaPost, tex, languages
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
31 ;; This Emacs Lisp package provides a major mode for editing Metafont
32 ;; or MetaPost sources. It includes all the necessary code to set up
33 ;; a major mode including an approriate syntax table, keymap, and a
34 ;; mode-specific pull-down menu. It also provides a sophisticated set
35 ;; of font-lock patterns, a fancy indentation function adapted from
36 ;; AUCTeX's latex.el, and some basic mode-specific editing functions
37 ;; such as functions to move to the beginning or end of the enclosing
38 ;; environment, or to mark, re-indent, or comment-out environments.
39 ;; On the other hand, it doesn't yet provide any functionality for
40 ;; running Metafont or MetaPost in a shell buffer form within Emacs,
41 ;; but such functionality might be added later, either as part of this
42 ;; package or as a separate Emacs Lisp package.
46 ;; An interface to running Metafont or MetaPost as a shell process
47 ;; from within Emacs is currently under development as a separate
48 ;; Emacs Lisp package (meta-buf.el). In order to have that package
49 ;; loaded automatically when first entering Metafont or MetaPost mode,
50 ;; you might use the load-hook provided in this package by adding
51 ;; these lines to your startup file:
53 ;; (add-hook 'meta-mode-load-hook
54 ;; '(lambda () (require 'meta-buf)))
56 ;; The add-on package loaded this way may in turn make use of the
57 ;; mode-hooks provided in this package to activate additional features
58 ;; when entering Metafont or MetaPost mode.
62 ;; If you are using global-font-lock-mode (introduced in Emacs 19.31),
63 ;; fontification in Metafont and/or MetaPost mode will be activated
64 ;; automatically. To speed up fontification for the rather complex
65 ;; patterns used in these modes, it may be a good idea to activate
66 ;; lazy-lock as a font-lock-support-mode (introduced in Emacs 19.32)
67 ;; by adding these lines to your startup file:
69 ;; (global-font-lock-mode t)
70 ;; (setq font-lock-support-mode 'lazy-lock-mode)
72 ;; If you are using an older version of Emacs, which doesn't provide
73 ;; global-font-lock-mode or font-lock-support-mode, you can also
74 ;; activate fontification in Metafont and/or MetaPost mode by adding
75 ;; the following lines to your startup file:
77 ;; (add-hook 'meta-common-mode-hook 'turn-on-font-lock)
78 ;; (add-hook 'meta-common-mode-hook 'turn-on-lazy-lock)
82 ;; Following the usual Emacs Lisp coding conventions, the major modes
83 ;; defined in this package provide several hook variables to allow for
84 ;; local customization when entering the modes. In particular, there
85 ;; is a `meta-common-mode-hook' which applies to both modes as well as
86 ;; `metafont-mode-hook' and `metapost-mode-hook' which apply to the
87 ;; individual modes. In addition, there are several variables and
88 ;; regexps controlling e.g. the behavior of the indentation function,
89 ;; which may be customized via `edit-options'. Please refer to the
90 ;; docstrings in the code below for details.
94 ;; This package is currently available via my "TeX Software" WWW page:
96 ;; http://www.thphy.uni-duesseldorf.de/~vieth/subjects/tex/software.html
98 ;; As of this version 1.0, this package will be uploaded to CTAN
99 ;; archives, where it shall find a permanent home, presumably in
100 ;; tex-archive/support/emacs-modes. It will also be submitted for
101 ;; integration into the GNU Emacs distribution at that time.
105 ;; v 0.0 -- 1997/02/01 UV Started writing meta-mode.el.
106 ;; v 0.1 -- 1997/02/02 UV Added preliminary set of font-lock patterns.
107 ;; v 0.2 -- 1997/02/03 UV Improved and debugged font-lock patterns.
108 ;; Added indent-line-function for TAB.
109 ;; v 0.3 -- 1997/02/17 UV Improved font-lock patterns and syntax table.
110 ;; Improved and debbuged indentation function.
111 ;; v 0.4 -- 1997/02/18 UV Added functions to indent regions for M-C-q,
112 ;; also added a preliminary mode-specific menu.
113 ;; v 0.5 -- 1997/02/19 UV Added functions to skip to next or previous
114 ;; defun and to re-indent or comment-out defuns.
115 ;; v 0.6 -- 1997/02/20 UV More debugging, testing and clean-up.
116 ;; v 0.7 -- 1997/02/22 UV Use easymenu to define mode-specific menu.
117 ;; v 0.8 -- 1997/02/24 UV Added completion function for M-TAB.
118 ;; v 0.9 -- 1997/03/08 UV Added fill-paragraph function for comments.
119 ;; Also fixed a few remaining font-lock problems.
120 ;; Added meta-mode-load-hook to load meta-buf.el.
121 ;; v 1.0 -- 1997/04/07 UV Cleanup for official public release.
123 ;; Historical Footnote:
125 ;; This package was begun on February 1, 1997, exactly 20 years after
126 ;; the genesis of TeX took place according to Don Knuth's own account
127 ;; (cf. ``The Errors of TeX'', reprinted in ``Literate Programming'',
128 ;; Chapter 10, p. 249). What better date could there be to choose?
136 (defgroup meta-font nil
137 "Major mode for editing Metafont or MetaPost sources."
142 (defvar meta-font-lock-keywords
143 (let ((input-keywords
144 "\\(input\\|generate\\)")
146 (concat "\\(begin\\(char\\|fig\\|graph\\|logochar\\)\\|"
147 "\\cmchar\\|dcchar\\|ecchar\\)"))
149 "\\(end\\(char\\|fig\\|graph\\)\\)")
151 "\\(def\\|let\\|mode_def\\|vardef\\)")
153 "\\(primarydef\\|secondarydef\\|tertiarydef\\)")
155 ; '("expr" "suffix" "text" "primary" "secondary" "tertiary") t)
157 (concat "\\(expr\\|primary\\|s\\(econdary\\|uffix\\)\\|"
158 "te\\(rtiary\\|xt\\)\\)"))
160 ; '("boolean" "color" "numeric" "pair" "path" "pen" "picture"
161 ; "string" "transform" "newinternal") t)
163 (concat "\\(boolean\\|color\\|n\\(ewinternal\\|umeric\\)\\|"
164 "p\\(a\\(ir\\|th\\)\\|en\\|icture\\)\\|string\\|"
167 ; '("for" "forever" "forsuffixes" "endfor"
168 ; "step" "until" "upto" "downto" "thru" "within"
169 ; "iff" "if" "elseif" "else" "fi" "exitif" "exitunless"
170 ; "let" "def" "vardef" "enddef" "mode_def"
171 ; "true" "false" "known" "unknown" "and" "or" "not"
172 ; "save" "interim" "inner" "outer" "relax"
173 ; "begingroup" "endgroup" "expandafter" "scantokens"
174 ; "generate" "input" "endinput" "end" "bye"
175 ; "message" "errmessage" "errhelp" "special" "numspecial"
176 ; "readstring" "readfrom" "write") t)
178 (concat "\\(and\\|b\\(egingroup\\|ye\\)\\|"
179 "d\\(ef\\|ownto\\)\\|e\\(lse\\(\\|if\\)"
180 "\\|nd\\(\\|def\\|for\\|group\\|input\\)"
181 "\\|rr\\(help\\|message\\)"
182 "\\|x\\(it\\(if\\|unless\\)\\|pandafter\\)\\)\\|"
183 "f\\(alse\\|i\\|or\\(\\|ever\\|suffixes\\)\\)\\|"
184 "generate\\|i\\(ff?\\|n\\(ner\\|put\\|terim\\)\\)\\|"
185 "known\\|let\\|m\\(essage\\|ode_def\\)\\|"
186 "n\\(ot\\|umspecial\\)\\|o\\(r\\|uter\\)\\|"
187 "re\\(ad\\(from\\|string\\)\\|lax\\)\\|"
188 "s\\(ave\\|cantokens\\|pecial\\|tep\\)\\|"
189 "t\\(hru\\|rue\\)\\|"
190 "u\\(n\\(known\\|til\\)\\|pto\\)\\|"
191 "vardef\\|w\\(ithin\\|rite\\)\\)"))
194 ;; embedded TeX code in btex ... etex
195 (cons (concat "\\(btex\\|verbatimtex\\)"
196 "[ \t]+\\(.*\\)[ \t]+"
198 '((1 font-lock-keyword-face)
199 (2 font-lock-string-face)
200 (3 font-lock-keyword-face)))
201 ;; unary macro definitions: def, vardef, let
202 (cons (concat "\\<" macro-keywords-1 "\\>"
203 "[ \t]+\\(\\sw+\\|\\s_+\\|\\s.+\\)")
204 '((1 font-lock-keyword-face)
205 (2 font-lock-function-name-face)))
206 ;; binary macro defintions: <leveldef> x operator y
207 (cons (concat "\\<" macro-keywords-2 "\\>"
209 "[ \t]*\\(\\sw+\\|\\s.+\\)"
211 '((1 font-lock-keyword-face)
212 (2 font-lock-variable-name-face nil t)
213 (3 font-lock-function-name-face nil t)
214 (4 font-lock-variable-name-face nil t)))
215 ;; variable declarations: numeric, pair, color, ...
216 (cons (concat "\\<" type-keywords "\\>"
217 "\\([ \t]+\\(\\sw+\\)\\)*")
218 '((1 font-lock-type-face)
219 (font-lock-match-meta-declaration-item-and-skip-to-next
220 (goto-char (match-end 1)) nil
221 (1 font-lock-variable-name-face nil t))))
222 ;; argument declarations: expr, suffix, text, ...
223 (cons (concat "\\<" args-keywords "\\>"
224 "\\([ \t]+\\(\\sw+\\|\\s_+\\)\\)*")
225 '((1 font-lock-type-face)
226 (font-lock-match-meta-declaration-item-and-skip-to-next
227 (goto-char (match-end 1)) nil
228 (1 font-lock-variable-name-face nil t))))
229 ;; special case of arguments: expr x of y
230 (cons (concat "\\(expr\\)[ \t]+\\(\\sw+\\)"
231 "[ \t]+\\(of\\)[ \t]+\\(\\sw+\\)")
232 '((1 font-lock-type-face)
233 (2 font-lock-variable-name-face)
234 (3 font-lock-keyword-face nil t)
235 (4 font-lock-variable-name-face nil t)))
236 ;; syntactic keywords
237 (cons (concat "\\<" syntactic-keywords "\\>")
238 'font-lock-keyword-face)
239 ;; beginchar, beginfig
240 (cons (concat "\\<" begin-keywords "\\>")
241 'font-lock-keyword-face)
243 (cons (concat "\\<" end-keywords "\\>")
244 'font-lock-keyword-face)
246 (cons (concat "\\<" input-keywords "\\>"
248 '((1 font-lock-keyword-face)
249 (2 font-lock-constant-face)))
250 ;; embedded Metafont/MetaPost code in comments
251 (cons "|\\([^|]+\\)|"
252 '(1 font-lock-constant-face t))
254 "Default expressions to highlight in Metafont or MetaPost mode.")
257 (defun font-lock-match-meta-declaration-item-and-skip-to-next (limit)
258 ;; Match and move over Metafont/MetaPost declaration item after point.
260 ;; The expected syntax of an item is either "word" or "symbol",
261 ;; possibly ending with optional whitespace. Everything following
262 ;; the item (but belonging to it) is expected to by skipable by
263 ;; `forward-sexp'. The list of items is expected to be separated
264 ;; by commas and terminated by semicolons or equals signs.
266 (if (looking-at "[ \t]*\\(\\sw+\\|\\s_+\\)")
270 ;; Restrict to end of line, currently guaranteed to be LIMIT.
271 (narrow-to-region (point-min) limit)
272 (goto-char (match-end 1))
273 ;; Move over any item value, etc., to the next item.
274 (while (not (looking-at "[ \t]*\\(\\(,\\)\\|;\\|=\\|$\\)"))
275 (goto-char (or (scan-sexps (point) 1) (point-max))))
276 (goto-char (match-end 2)))
283 ;; The data used to prepare the following lists of primitives and
284 ;; standard macros available in Metafont or MetaPost was extracted
285 ;; from the original sources like this:
287 ;; grep '^primitive' texk-7.0/web2c/{mf,mp}.web |\
288 ;; sed 's/primitive(\("[a-zA-Z]*"\).*/\1/' > {mf,mp}_prim.list
290 ;; grep '\(let\|def\|vardef\|primarydef\|secondarydef\|tertiarydef\)'
291 ;; texmf/meta{font,post}/plain.{mf,mp} > {mf,mp}_plain.list
293 (defconst meta-common-primitives-list
294 '("ASCII" "addto" "also" "and" "angle" "atleast" "batchmode"
295 "begingroup" "boolean" "boundarychar" "char" "charcode" "chardp"
296 "charexists" "charext" "charht" "charic" "charlist" "charwd"
297 "contour" "controls" "cosd" "curl" "cycle" "day" "decimal" "def"
298 "delimiters" "designsize" "directiontime" "doublepath" "dump" "else"
299 "elseif" "end" "enddef" "endfor" "endgroup" "endinput" "errhelp"
300 "errmessage" "errorstopmode" "everyjob" "exitif" "expandafter"
301 "expr" "extensible" "false" "fi" "floor" "fontdimen" "fontmaking"
302 "for" "forever" "forsuffixes" "headerbyte" "hex" "if" "inner"
303 "input" "interim" "intersectiontimes" "jobname" "kern" "known"
304 "length" "let" "ligtable" "makepath" "makepen" "message" "mexp"
305 "mlog" "month" "newinternal" "nonstopmode" "normaldeviate" "not"
306 "nullpen" "nullpicture" "numeric" "oct" "odd" "of" "or" "outer"
307 "pair" "path" "pausing" "pen" "pencircle" "penoffset" "picture"
308 "point" "postcontrol" "precontrol" "primary" "primarydef" "quote"
309 "randomseed" "readstring" "reverse" "rotated" "save" "scaled"
310 "scantokens" "scrollmode" "secondary" "secondarydef" "shifted"
311 "shipout" "show" "showdependencies" "showstats" "showstopping"
312 "showtoken" "showvariable" "sind" "skipto" "slanted" "special"
313 "sqrt" "step" "str" "string" "subpath" "substring" "suffix"
314 "tension" "tertiary" "tertiarydef" "text" "time" "to"
315 "tracingcapsules" "tracingchoices" "tracingcommands"
316 "tracingequations" "tracingmacros" "tracingonline" "tracingoutput"
317 "tracingrestores" "tracingspecs" "tracingstats" "tracingtitles"
318 "transform" "transformed" "true" "turningnumber" "uniformdeviate"
319 "unknown" "until" "vardef" "warningcheck" "withpen" "xpart"
320 "xscaled" "xxpart" "xypart" "year" "ypart" "yscaled" "yxpart"
322 "List of primitives common to Metafont and MetaPost.")
324 (defconst metafont-primitives-list
325 '("at" "autorounding" "chardx" "chardy" "cull" "display"
326 "dropping" "fillin" "from" "granularity" "hppp" "inwindow"
327 "keeping" "numspecial" "openwindow" "proofing" "smoothing"
328 "totalweight" "tracingedges" "tracingpens" "turningcheck" "vppp"
329 "withweight" "xoffset" "yoffset")
330 "List of primitives only defined in Metafont.")
332 (defconst metapost-primitives-list
333 '("arclength" "arctime" "bluepart" "bounded" "btex" "clip"
334 "clipped" "color" "dashed" "dashpart" "etex" "filled" "fontpart"
335 "fontsize" "greenpart" "infont" "linecap" "linejoin" "llcorner"
336 "lrcorner" "miterlimit" "mpxbreak" "pathpart" "penpart"
337 "prologues" "readfrom" "redpart" "setbounds" "stroked" "textpart"
338 "textual" "tracinglostchars" "truecorners" "ulcorner" "urcorner"
339 "verbatimtex" "withcolor" "within" "write")
340 "List of primitives only defined in MetaPost.")
342 (defconst meta-common-plain-macros-list
343 '( "abs" "bot" "bye" "byte" "ceiling" "clear_pen_memory"
344 "clearit" "clearpen" "clearxy" "counterclockwise" "cutdraw" "decr"
345 "dir" "direction" "directionpoint" "div" "dotprod" "downto" "draw"
346 "drawdot" "erase" "exitunless" "fill" "filldraw" "flex" "gobble"
347 "hide" "incr" "interact" "interpath" "intersectionpoint" "inverse"
348 "label" "labels" "lft" "loggingall" "magstep" "makelabel" "max"
349 "min" "mod" "numtok" "penlabels" "penpos" "penstroke" "pickup"
350 "range" "reflectedabout" "relax" "rotatedabout" "rotatedaround"
351 "round" "rt" "savepen" "shipit" "softjoin" "solve" "stop"
352 "superellipse" "takepower" "tensepath" "thru" "top" "tracingall"
353 "tracingnone" "undraw" "undrawdot" "unfill" "unfilldraw"
354 "unitvector" "upto" "whatever")
355 "List of macros common to plain Metafont and MetaPost.")
357 (defconst metafont-plain-macros-list
358 '("beginchar" "change_width" "culldraw" "cullit" "cutoff"
359 "define_blacker_pixels" "define_corrected_pixels"
360 "define_good_x_pixels" "define_good_y_pixels"
361 "define_horizontal_corrected_pixels" "define_pixels"
362 "define_whole_blacker_pixels" "define_whole_pixels"
363 "define_whole_vertical_blacker_pixels"
364 "define_whole_vertical_pixels" "endchar" "fix_units"
365 "font_coding_scheme" "font_extra_space" "font_identifier"
366 "font_normal_shrink" "font_normal_space" "font_normal_stretch"
367 "font_quad" "font_size" "font_slant" "font_x_height" "gfcorners"
368 "good.bot" "good.lft" "good.rt" "good.top" "good.x" "good.y"
369 "grayfont" "hround" "imagerules" "italcorr" "labelfont"
370 "lowres_fix" "makebox" "makegrid" "maketicks" "mode_lowres"
371 "mode_proof" "mode_setup" "mode_smoke" "nodisplays" "notransforms"
372 "openit" "penrazor" "pensquare" "proofoffset" "proofrule"
373 "proofrulethickness" "screenchars" "screenrule" "screenstrokes"
374 "showit" "slantfont" "smode" "titlefont" "vround")
375 "List of macros only defined in plain Metafont.")
377 (defconst metapost-plain-macros-list
378 '("arrowhead" "bbox" "beginfig" "buildcycle" "center" "cutafter"
379 "cutbefore" "dashpattern" "dotlabel" "dotlabels" "drawarrow"
380 "drawdblarrow" "drawoptions" "endfig" "image" "label" "off" "on"
382 "List of macros only defined in plain MetaPost.")
384 (defconst metapost-graph-macros-list
385 '("augment" "auto.x" "auto.y" "autogrid" "begingraph" "endgraph"
386 "format" "frame" "gdata" "gdotlabel" "gdraw" "gdrawarrow"
387 "gdrawdblarrow" "gfill" "glabel" "grid" "itick" "otick" "plot"
388 "setcoords" "setrange")
389 "List of macros only defined in MetaPost \"graph\" package.")
391 (defconst metapost-boxes-macros-list
392 '("boxit" "boxjoin" "bpath" "circleit" "drawboxed" "drawboxes"
393 "drawunboxed" "fixpos" "fixsize" "pic" "rboxit")
394 "List of macros only defined in MetaPost \"boxes\" package.")
397 (defvar metafont-symbol-list
398 (append meta-common-primitives-list
399 metafont-primitives-list
400 meta-common-plain-macros-list
401 metafont-plain-macros-list)
402 "List of known symbols to complete in Metafont mode.")
404 (defvar metapost-symbol-list
405 (append meta-common-primitives-list
406 metapost-primitives-list
407 meta-common-plain-macros-list
408 metapost-plain-macros-list
409 metapost-graph-macros-list
410 metapost-boxes-macros-list)
411 "List of known symbols to complete in MetaPost mode.")
414 (defvar meta-symbol-list nil
415 "List of known symbols to complete in Metafont or MetaPost mode.")
417 (defvar meta-symbol-changed nil
418 "Flag indicating whether `meta-symbol-list' has been initialized.")
420 (defvar meta-complete-list nil
421 ; (list (list "\\<\\(\\sw+\\)" 1 'meta-symbol-list)
422 ; (list "" 'ispell-complete-word))
423 "List of ways to perform completion in Metafont or MetaPost mode.
425 Each entry is a list with the following elements:
426 1. Regexp matching the preceding text.
427 2. A number indicating the subgroup in the regexp containing the text.
428 3. A function returning an alist of possible completions.
429 4. Text to append after a succesful completion (if any).
432 1. Regexp matching the preceding text.
433 2. Function to do the actual completion.")
436 (defun meta-add-symbols (&rest entries)
437 "Add entries to list of known symbols in Metafont or MetaPost mode."
438 (if meta-symbol-changed
439 (setq meta-symbol-list (cons entries meta-symbol-list))
440 (setq meta-symbol-changed t)
441 (setq meta-symbol-list (cons entries meta-symbol-list))))
443 (defun meta-symbol-list ()
444 "Return value of list of known symbols in Metafont or MetaPost mode.
445 If the list was changed, sort the list and remove duplicates first."
446 (if (not meta-symbol-changed)
448 (setq meta-symbol-changed nil)
449 (message "Preparing completion list...")
450 ;; sort list of symbols
451 (setq meta-symbol-list
452 (sort (mapcar 'meta-listify (apply 'append meta-symbol-list))
453 'meta-car-string-lessp))
455 (let ((entry meta-symbol-list))
456 (while (and entry (cdr entry))
457 (let ((this (car entry))
458 (next (car (cdr entry))))
459 (if (not (string-equal (car this) (car next)))
460 (setq entry (cdr entry))
461 (if (> (length next) (length this))
462 (setcdr this (cdr next)))
463 (setcdr entry (cdr (cdr entry)))))))
464 (message "Preparing completion list... done"))
467 (defun meta-listify (a)
468 ;; utility function used in `meta-add-symbols'
469 (if (listp a) a (list a)))
471 (defun meta-car-string-lessp (a b)
472 ;; utility function used in `meta-add-symbols'
473 (string-lessp (car a) (car b)))
476 (defun meta-complete-symbol ()
477 "Perform completion on Metafont or MetaPost symbol preceding point."
479 (let ((list meta-complete-list)
482 (setq entry (car list)
484 (if (meta-looking-at-backward (car entry) 200)
486 (if (numberp (nth 1 entry))
487 (let* ((sub (nth 1 entry))
488 (close (nth 3 entry))
489 (begin (match-beginning sub))
490 (end (match-end sub))
491 (pattern (meta-match-buffer 0))
492 (symbol (buffer-substring begin end))
493 (list (funcall (nth 2 entry)))
494 (completion (try-completion symbol list)))
495 (cond ((eq completion t)
497 (not (looking-at (regexp-quote close)))
500 (error "Can't find completion for \"%s\"" pattern))
501 ((not (string-equal symbol completion))
502 (delete-region begin end)
505 (eq (try-completion completion list) t)
506 (not (looking-at (regexp-quote close)))
509 (message "Making completion list...")
510 (let ((list (all-completions symbol list nil)))
511 (with-output-to-temp-buffer "*Completions*"
512 (display-completion-list list)))
513 (message "Making completion list... done"))))
514 (funcall (nth 1 entry)))))
517 (defun meta-looking-at-backward (regexp &optional limit)
518 ;; utility function used in `meta-complete-symbol'
521 (and (re-search-backward
522 regexp (if limit (max (point-min) (- (point) limit))) t)
523 (eq (match-end 0) pos)))))
525 (defun meta-match-buffer (n)
526 ;; utility function used in `meta-complete-symbol'
527 (if (match-beginning n)
528 (let ((str (buffer-substring (match-beginning n) (match-end n))))
529 (set-text-properties 0 (length str) nil str)
537 (defcustom meta-indent-level 2
538 "*Indentation of begin-end blocks in Metafont or MetaPost mode."
543 (defcustom meta-left-comment-regexp "%%+"
544 "*Regexp matching comments that should be placed on the left margin."
548 (defcustom meta-right-comment-regexp nil
549 "*Regexp matching comments that should be placed to the right margin."
550 :type '(choice regexp
551 (const :tag "None" nil))
554 (defcustom meta-ignore-comment-regexp "%[^%]"
555 "*Regexp matching comments that whose indentation should not be touched."
560 (defcustom meta-begin-environment-regexp
561 (concat "\\(begin\\(char\\|fig\\|gr\\(aph\\|oup\\)\\|logochar\\)\\|"
562 "def\\|for\\(\\|ever\\|suffixes\\)\\|if\\|mode_def\\|"
563 "primarydef\\|secondarydef\\|tertiarydef\\|vardef\\)")
564 "*Regexp matching the beginning of environments to be indented."
568 (defcustom meta-end-environment-regexp
569 (concat "\\(end\\(char\\|def\\|f\\(ig\\|or\\)\\|gr\\(aph\\|oup\\)\\)"
571 "*Regexp matching the end of environments to be indented."
575 (defcustom meta-within-environment-regexp
576 ; (concat "\\(e\\(lse\\(\\|if\\)\\|xit\\(if\\|unless\\)\\)\\)")
577 (concat "\\(else\\(\\|if\\)\\)")
578 "*Regexp matching keywords within environments not to be indented."
583 (defun meta-comment-indent ()
584 "Return the indentation for a comment in Metafont or MetaPost mode."
585 (if (and meta-left-comment-regexp
586 (looking-at meta-left-comment-regexp))
588 (skip-chars-backward "\t ")
589 (max (if (bolp) 0 (1+ (current-column)))
592 (defun meta-indent-line ()
593 "Indent the line containing point as Metafont or MetaPost source."
595 (let ((indent (meta-indent-calculate)))
597 (if (/= (current-indentation) indent)
598 (let ((beg (progn (beginning-of-line) (point)))
599 (end (progn (back-to-indentation) (point))))
600 (delete-region beg end)
601 (indent-to indent))))
602 (if (< (current-column) indent)
603 (back-to-indentation))))
605 (defun meta-indent-calculate ()
606 "Return the indentation of current line of Metafont or MetaPost source."
608 (back-to-indentation)
610 ;; Comments to the left margin.
611 ((and meta-left-comment-regexp
612 (looking-at meta-left-comment-regexp))
614 ;; Comments to the right margin.
615 ((and meta-right-comment-regexp
616 (looking-at meta-right-comment-regexp))
618 ;; Comments best left alone.
619 ((and meta-ignore-comment-regexp
620 (looking-at meta-ignore-comment-regexp))
621 (current-indentation))
622 ;; Backindent at end of environments.
624 (concat "\\<" meta-end-environment-regexp "\\>"))
625 (- (meta-indent-calculate-last) meta-indent-level))
626 ;; Backindent at keywords within environments.
628 (concat "\\<" meta-within-environment-regexp "\\>"))
629 (- (meta-indent-calculate-last) meta-indent-level))
630 (t (meta-indent-calculate-last)))))
632 (defun meta-indent-calculate-last ()
633 "Return the indentation of previous line of Metafont or MetaPost source."
636 (skip-chars-backward "\n\t ")
637 (move-to-column (current-indentation))
639 (while (and (looking-at comment-start) (not (bobp)))
640 (skip-chars-backward "\n\t ")
642 (move-to-column (current-indentation))))
645 (t (+ (current-indentation)
646 (meta-indent-level-count)
648 ;; Compensate for backindent at end of environments.
650 (concat "\\<"meta-end-environment-regexp "\\>"))
652 ;; Compensate for backindent within environments.
654 (concat "\\<" meta-within-environment-regexp "\\>"))
659 (defun meta-indent-level-count ()
660 "Count indentation change for begin-end commands in the current line."
665 (point) (save-excursion
666 (re-search-forward "[^\\\\\"]%\\|\n\\|\\'" nil t)
667 (backward-char) (point)))
668 (while (re-search-forward "\\<\\sw+\\>\\|(\\|)" nil t)
670 (goto-char (match-beginning 0))
672 ;; Count number of begin-end keywords within line.
674 (concat "\\<" meta-begin-environment-regexp "\\>"))
675 (setq count (+ count meta-indent-level)))
677 (concat "\\<" meta-end-environment-regexp "\\>"))
678 (setq count (- count meta-indent-level)))
679 ;; Count number of open-close parentheses within line.
681 (setq count (+ count meta-indent-level)))
683 (setq count (- count meta-indent-level)))
689 ;;; Editing commands.
691 (defcustom meta-begin-defun-regexp
692 (concat "\\(begin\\(char\\|fig\\|logochar\\)\\|def\\|mode_def\\|"
693 "primarydef\\|secondarydef\\|tertiarydef\\|vardef\\)")
694 "*Regexp matching beginning of defuns in Metafont or MetaPost mode."
698 (defcustom meta-end-defun-regexp
699 (concat "\\(end\\(char\\|def\\|fig\\)\\)")
700 "*Regexp matching the end of defuns in Metafont or MetaPost mode."
705 (defun meta-beginning-of-defun (&optional arg)
706 "Move backward to beginnning of a defun in Metafont or MetaPost code.
707 With numeric argument, do it that many times.
708 Negative arg -N means move forward to Nth following beginning of defun.
709 Returns t unless search stops due to beginning or end of buffer."
711 (if (or (null arg) (= 0 arg)) (setq arg 1))
712 (and arg (< arg 0) (not (eobp)) (forward-char 1))
713 (and (re-search-backward
714 (concat "\\<" meta-begin-defun-regexp "\\>") nil t arg)
715 (progn (goto-char (match-beginning 0))
716 (skip-chars-backward "%")
717 (skip-chars-backward " \t") t)))
719 (defun meta-end-of-defun (&optional arg)
720 "Move forward to end of a defun in Metafont or MetaPost code.
721 With numeric argument, do it that many times.
722 Negative argument -N means move back to Nth preceding end of defun.
723 Returns t unless search stops due to beginning or end of buffer."
725 (if (or (null arg) (= 0 arg)) (setq arg 1))
726 (and (< arg 0) (not (bobp)) (forward-line -1))
727 (and (re-search-forward
728 (concat "\\<" meta-end-defun-regexp "\\>") nil t arg)
729 (progn (goto-char (match-end 0))
730 (skip-chars-forward ";")
731 (skip-chars-forward " \t")
732 (if (looking-at "\n") (forward-line 1)) t)))
735 (defun meta-comment-region (beg end &optional arg)
736 "Comment out active region as Metafont or MetaPost source."
738 (comment-region beg end arg))
740 (defun meta-uncomment-region (beg end)
741 "Uncomment active region as Metafont or MetaPost source."
743 (comment-region beg end -1))
745 (defun meta-comment-defun (&optional arg)
746 "Comment out current environment as Metafont or MetaPost source.
747 With prefix argument, uncomment the environment.
748 The environment used is the one that contains point or follows point."
751 (let* ((end (if (meta-end-of-defun) (point) (point-max)))
752 (beg (if (meta-beginning-of-defun) (point) (point-min))))
753 (comment-region beg end arg))))
755 (defun meta-uncomment-defun ()
756 "Uncomment current environment as Metafont or MetaPost source."
758 (meta-comment-defun -1))
761 (defun meta-indent-region (beg end)
762 "Indent the active region as Metafont or MetaPost source."
764 (indent-region beg end nil))
766 (defun meta-indent-buffer ()
767 "Indent the whole buffer contents as Metafont or MetaPost source."
770 (indent-region (point-min) (point-max) nil)))
772 (defun meta-indent-defun ()
773 "Indent the current environment as Metafont or MetaPost source.
774 The environment indented is the one that contains point or follows point."
777 (let* ((end (if (meta-end-of-defun) (point) (point-max)))
778 (beg (if (meta-beginning-of-defun) (point) (point-min))))
779 (indent-region beg end nil))))
782 (defun meta-mark-defun ()
783 "Put mark at end of the environment, point at the beginning.
784 The environment marked is the one that contains point or follows point."
788 (push-mark (point) nil t)
789 (meta-beginning-of-defun))
793 ;;; Syntax table, keymap and menu.
795 (defvar meta-mode-abbrev-table nil
796 "Abbrev table used in Metafont or MetaPost mode.")
797 (define-abbrev-table 'meta-mode-abbrev-table ())
799 (defvar meta-mode-syntax-table nil
800 "Syntax table used in Metafont or MetaPost mode.")
801 (if meta-mode-syntax-table
803 (setq meta-mode-syntax-table (make-syntax-table))
804 ;; underscores are word constituents
805 (modify-syntax-entry ?_ "w" meta-mode-syntax-table)
806 ;; miscellaneous non-word symbols
807 (modify-syntax-entry ?# "_" meta-mode-syntax-table)
808 (modify-syntax-entry ?@ "_" meta-mode-syntax-table)
809 (modify-syntax-entry ?$ "_" meta-mode-syntax-table)
810 (modify-syntax-entry ?? "_" meta-mode-syntax-table)
811 (modify-syntax-entry ?! "_" meta-mode-syntax-table)
813 (modify-syntax-entry ?& "." meta-mode-syntax-table)
814 (modify-syntax-entry ?+ "." meta-mode-syntax-table)
815 (modify-syntax-entry ?- "." meta-mode-syntax-table)
816 (modify-syntax-entry ?/ "." meta-mode-syntax-table)
817 (modify-syntax-entry ?* "." meta-mode-syntax-table)
818 (modify-syntax-entry ?. "." meta-mode-syntax-table)
819 (modify-syntax-entry ?: "." meta-mode-syntax-table)
820 (modify-syntax-entry ?= "." meta-mode-syntax-table)
821 (modify-syntax-entry ?< "." meta-mode-syntax-table)
822 (modify-syntax-entry ?> "." meta-mode-syntax-table)
823 (modify-syntax-entry ?| "." meta-mode-syntax-table)
824 ;; opening and closing delimiters
825 (modify-syntax-entry ?\( "()" meta-mode-syntax-table)
826 (modify-syntax-entry ?\) ")(" meta-mode-syntax-table)
827 (modify-syntax-entry ?\[ "(]" meta-mode-syntax-table)
828 (modify-syntax-entry ?\] ")[" meta-mode-syntax-table)
829 (modify-syntax-entry ?\{ "(}" meta-mode-syntax-table)
830 (modify-syntax-entry ?\} "){" meta-mode-syntax-table)
832 (modify-syntax-entry ?% "<" meta-mode-syntax-table)
833 (modify-syntax-entry ?\n ">" meta-mode-syntax-table)
834 ;; escape character, needed for embedded TeX code
835 (modify-syntax-entry ?\\ "\\" meta-mode-syntax-table)
838 (defvar meta-mode-map nil
839 "Keymap used in Metafont or MetaPost mode.")
842 (setq meta-mode-map (make-sparse-keymap))
843 (define-key meta-mode-map "\t" 'meta-indent-line)
844 (define-key meta-mode-map "\C-m" 'reindent-then-newline-and-indent)
845 ;; Comment Paragraphs:
846 ; (define-key meta-mode-map "\M-a" 'backward-sentence)
847 ; (define-key meta-mode-map "\M-e" 'forward-sentence)
848 ; (define-key meta-mode-map "\M-h" 'mark-paragraph)
849 ; (define-key meta-mode-map "\M-q" 'fill-paragraph)
851 (define-key meta-mode-map "\M-\C-a" 'meta-beginning-of-defun)
852 (define-key meta-mode-map "\M-\C-e" 'meta-end-of-defun)
853 (define-key meta-mode-map "\M-\C-h" 'meta-mark-defun)
855 (define-key meta-mode-map "\M-\C-q" 'meta-indent-defun)
856 (define-key meta-mode-map "\C-c\C-qe" 'meta-indent-defun)
857 (define-key meta-mode-map "\C-c\C-qr" 'meta-indent-region)
858 (define-key meta-mode-map "\C-c\C-qb" 'meta-indent-buffer)
860 (define-key meta-mode-map "\C-c%" 'meta-comment-defun)
861 ; (define-key meta-mode-map "\C-uC-c%" 'meta-uncomment-defun)
862 (define-key meta-mode-map "\C-c;" 'meta-comment-region)
863 (define-key meta-mode-map "\C-c:" 'meta-uncomment-region)
864 ;; Symbol Completion:
865 (define-key meta-mode-map "\M-\t" 'meta-complete-symbol)
867 ; (define-key meta-mode-map "\C-c\C-c" 'meta-command-file)
868 ; (define-key meta-mode-map "\C-c\C-k" 'meta-kill-job)
869 ; (define-key meta-mode-map "\C-c\C-l" 'meta-recenter-output)
873 meta-mode-menu meta-mode-map
874 "Menu used in Metafont or MetaPost mode."
876 ["Forward Environment" meta-beginning-of-defun t]
877 ["Backward Environment" meta-end-of-defun t]
879 ["Indent Line" meta-indent-line t]
880 ["Indent Environment" meta-indent-defun t]
881 ["Indent Region" meta-indent-region
882 :active (meta-mark-active)]
883 ["Indent Buffer" meta-indent-buffer t]
885 ["Comment Out Environment" meta-comment-defun t]
886 ["Uncomment Environment" meta-uncomment-defun t]
887 ["Comment Out Region" meta-comment-region
888 :active (meta-mark-active)]
889 ["Uncomment Region" meta-uncomment-region
890 :active (meta-mark-active)]
892 ["Complete Symbol" meta-complete-symbol t]
894 ; ["Command on Buffer" meta-command-file t]
895 ; ["Kill Job" meta-kill-job t]
896 ; ["Recenter Output Buffer" meta-recenter-output-buffer t]
899 ;; Compatibility: XEmacs doesn't have the `mark-active' variable.
900 (defun meta-mark-active ()
901 "Return whether the mark and region are currently active in this buffer."
902 (if (boundp 'mark-active) mark-active (mark)))
908 (defcustom meta-mode-load-hook nil
909 "*Hook evaluated when first loading Metafont or MetaPost mode."
913 (defcustom meta-common-mode-hook nil
914 "*Hook evaluated by both `metafont-mode' and `metapost-mode'."
918 (defcustom metafont-mode-hook nil
919 "*Hook evaluated by `metafont-mode' after `meta-common-mode-hook'."
922 (defcustom metapost-mode-hook nil
923 "*Hook evaluated by `metapost-mode' after `meta-common-mode-hook'."
931 (defun meta-common-initialization ()
932 "Common initialization for Metafont or MetaPost mode."
933 (kill-all-local-variables)
935 (make-local-variable 'paragraph-start)
936 (make-local-variable 'paragraph-separate)
937 (setq paragraph-start
938 (concat page-delimiter "\\|$"))
939 (setq paragraph-separate
940 (concat page-delimiter "\\|$"))
942 (make-local-variable 'paragraph-ignore-fill-prefix)
943 (setq paragraph-ignore-fill-prefix t)
945 (make-local-variable 'comment-start-skip)
946 (make-local-variable 'comment-start)
947 (make-local-variable 'comment-end)
948 (make-local-variable 'comment-multi-line)
949 (setq comment-start-skip "%+[ \t]*")
950 (setq comment-start "%")
951 (setq comment-end "")
952 (setq comment-multi-line nil)
954 (make-local-variable 'parse-sexp-ignore-comments)
955 (setq parse-sexp-ignore-comments t)
957 (make-local-variable 'comment-indent-function)
958 (setq comment-indent-function 'meta-comment-indent)
959 (make-local-variable 'indent-line-function)
960 (setq indent-line-function 'meta-indent-line)
961 ;; No need to define a mode-specific 'indent-region-function.
962 ;; Simply use the generic 'indent-region and 'comment-region.
964 ;; Set defaults for font-lock mode.
965 (make-local-variable 'font-lock-defaults)
966 (setq font-lock-defaults
967 '(meta-font-lock-keywords
968 nil nil ((?_ . "w")) nil
969 (font-lock-comment-start-regexp . "%")))
971 ;; Activate syntax table, keymap and menu.
972 (setq local-abbrev-table meta-mode-abbrev-table)
973 (set-syntax-table meta-mode-syntax-table)
974 (use-local-map meta-mode-map)
975 (easy-menu-add meta-mode-menu)
980 (defun metafont-mode ()
981 "Major mode for editing Metafont sources.
985 Turning on Metafont mode calls the value of the variables
986 `meta-common-mode-hook' and `metafont-mode-hook'."
988 (meta-common-initialization)
989 (setq mode-name "Metafont")
990 (setq major-mode 'metafont-mode)
992 ;; Set defaults for completion function.
993 (make-local-variable 'meta-symbol-list)
994 (make-local-variable 'meta-symbol-changed)
995 (make-local-variable 'meta-complete-list)
996 (setq meta-symbol-list nil)
997 (setq meta-symbol-changed nil)
998 (apply 'meta-add-symbols metafont-symbol-list)
999 (setq meta-complete-list
1000 (list (list "\\<\\(\\sw+\\)" 1 'meta-symbol-list)
1001 (list "" 'ispell-complete-word)))
1002 (run-mode-hooks 'meta-common-mode-hook 'metafont-mode-hook))
1005 (defun metapost-mode ()
1006 "Major mode for editing MetaPost sources.
1010 Turning on MetaPost mode calls the value of the variable
1011 `meta-common-mode-hook' and `metafont-mode-hook'."
1013 (meta-common-initialization)
1014 (setq mode-name "MetaPost")
1015 (setq major-mode 'metapost-mode)
1017 ;; Set defaults for completion function.
1018 (make-local-variable 'meta-symbol-list)
1019 (make-local-variable 'meta-symbol-changed)
1020 (make-local-variable 'meta-complete-list)
1021 (setq meta-symbol-list nil)
1022 (setq meta-symbol-changed nil)
1023 (apply 'meta-add-symbols metapost-symbol-list)
1024 (setq meta-complete-list
1025 (list (list "\\<\\(\\sw+\\)" 1 'meta-symbol-list)
1026 (list "" 'ispell-complete-word)))
1027 (run-mode-hooks 'meta-common-mode-hook 'metapost-mode-hook))
1030 ;;; Just in case ...
1032 (provide 'meta-mode)
1033 (run-hooks 'meta-mode-load-hook)
1035 ;;; arch-tag: ec2916b2-3a83-4cf7-962d-d8019370c006
1036 ;;; meta-mode.el ends here