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