]> code.delx.au - gnu-emacs-elpa/blob - packages/sml-mode/sml-mode.el
Add SML-mode.
[gnu-emacs-elpa] / packages / sml-mode / sml-mode.el
1 ;;; sml-mode.el --- Major mode for editing (Standard) ML -*- lexical-binding: t; coding: utf-8 -*-
2
3 ;; Copyright (C) 1989,1999,2000,2004,2007,2010-2012 Free Software Foundation, Inc.
4
5 ;; Maintainer: (Stefan Monnier) <monnier@iro.umontreal.ca>
6 ;; Version: 6.0
7 ;; Keywords: SML
8 ;; Authors of previous versions:
9 ;; Lars Bo Nielsen
10 ;; Olin Shivers
11 ;; Fritz Knabe (?)
12 ;; Steven Gilmore (?)
13 ;; Matthew Morley <mjm@scs.leeds.ac.uk>
14 ;; Matthias Blume <blume@cs.princeton.edu>
15 ;; (Stefan Monnier) <monnier@iro.umontreal.ca>
16
17 ;; This file is part of GNU Emacs.
18
19 ;; GNU Emacs is free software: you can redistribute it and/or modify
20 ;; it under the terms of the GNU General Public License as published by
21 ;; the Free Software Foundation, either version 3 of the License, or
22 ;; (at your option) any later version.
23
24 ;; GNU Emacs is distributed in the hope that it will be useful,
25 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
26 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 ;; GNU General Public License for more details.
28
29 ;; You should have received a copy of the GNU General Public License
30 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
31
32 ;;; Commentary:
33
34 ;; A major mode to edit Standard ML (SML) code.
35 ;; Provides the following features, among others:
36 ;; - Indentation.
37 ;; - Syntax highlighting.
38 ;; - Prettified display of ->, =>, fn, ...
39 ;; - Imenu.
40 ;; - which-function-mode.
41 ;; - Skeletons/templates.
42 ;; - Electric pipe key.
43 ;; - outline-minor-mode (with some known problems).
44 ;; - Interaction with a read-eval-print loop.
45
46 ;;; Code:
47
48 (eval-when-compile (require 'cl))
49 (require 'smie nil 'noerror)
50 (require 'electric)
51
52 (defgroup sml ()
53 "Editing SML code."
54 :group 'languages)
55
56 (defcustom sml-indent-level 4
57 "Basic indentation step for SML code."
58 :type 'integer)
59
60 (defcustom sml-indent-args sml-indent-level
61 "Indentation of args placed on a separate line."
62 :type 'integer)
63
64 (defcustom sml-rightalign-and t
65 "If non-nil, right-align `and' with its leader.
66 If nil: If t:
67 datatype a = A datatype a = A
68 and b = B and b = B"
69 :type 'boolean)
70
71 (defcustom sml-electric-pipe-mode t
72 "If non-nil, automatically insert appropriate template when hitting |."
73 :type 'boolean)
74
75 (defvar sml-mode-hook nil
76 "Run upon entering `sml-mode'.
77 This is a good place to put your preferred key bindings.")
78
79 ;; font-lock setup
80
81 (defvar sml-outline-regexp
82 ;; `st' and `si' are to match structure and signature.
83 "\f\\|s[ti]\\|[ \t]*\\(let[ \t]+\\)?\\(fun\\|and\\)\\_>"
84 "Regexp matching a major heading.
85 This actually can't work without extending `outline-minor-mode' with the
86 notion of \"the end of an outline\".")
87
88 ;;
89 ;; Internal defines
90 ;;
91
92 (defvar sml-mode-map
93 (let ((map (make-sparse-keymap)))
94 ;; Text-formatting commands:
95 (define-key map "\C-c\C-m" 'sml-insert-form)
96 (define-key map "\M-|" 'sml-electric-pipe)
97 (define-key map "\M-\ " 'sml-electric-space)
98 (define-key map [backtab] 'sml-back-to-outer-indent)
99 map)
100 "The keymap used in `sml-mode'.")
101
102 (defvar sml-mode-syntax-table
103 (let ((st (make-syntax-table)))
104 (modify-syntax-entry ?\* ". 23n" st)
105 (modify-syntax-entry ?\( "()1" st)
106 (modify-syntax-entry ?\) ")(4" st)
107 (mapc (lambda (c) (modify-syntax-entry c "_" st)) "._'")
108 (mapc (lambda (c) (modify-syntax-entry c "." st)) ",;")
109 ;; `!' is not really a prefix-char, oh well!
110 (mapc (lambda (c) (modify-syntax-entry c "'" st)) "~#!")
111 (mapc (lambda (c) (modify-syntax-entry c "." st)) "%&$+-/:<=>?@`^|")
112 st)
113 "The syntax table used in `sml-mode'.")
114
115
116 (easy-menu-define sml-mode-menu sml-mode-map "Menu used in `sml-mode'."
117 '("SML"
118 ("Process"
119 ["Start SML repl" run-sml t]
120 ["-" nil nil]
121 ["Compile the project" sml-prog-proc-compile t]
122 ["Send file" sml-prog-proc-load-file t]
123 ["Switch to SML repl" sml-prog-proc-switch-to t]
124 ["--" nil nil]
125 ["Send buffer" sml-prog-proc-send-buffer t]
126 ["Send region" sml-prog-proc-send-region t]
127 ["Send function" sml-send-function t]
128 ["Goto next error" next-error t])
129 ["Insert SML form" sml-insert-form t]
130 ("Forms" :filter sml-forms-menu)
131 ["Indent region" indent-region t]
132 ["Outdent line" sml-back-to-outer-indent t]
133 ["-----" nil nil]
134 ["Customize SML-mode" (customize-group 'sml) t]
135 ["SML mode help" describe-mode t]))
136
137 ;;
138 ;; Regexps
139 ;;
140
141 (defun sml-syms-re (syms)
142 (concat "\\_<" (regexp-opt syms t) "\\_>"))
143
144 ;;
145
146 (defconst sml-module-head-syms
147 '("signature" "structure" "functor" "abstraction"))
148
149
150 (defconst sml-=-starter-syms
151 (list* "|" "val" "fun" "and" "datatype" "type" "abstype" "eqtype"
152 sml-module-head-syms)
153 "Symbols that can be followed by a `='.")
154 (defconst sml-=-starter-re
155 (concat "\\S.|\\S.\\|" (sml-syms-re (cdr sml-=-starter-syms)))
156 "Symbols that can be followed by a `='.")
157
158 (defconst sml-non-nested-of-starter-re
159 (sml-syms-re '("datatype" "abstype" "exception"))
160 "Symbols that can introduce an `of' that shouldn't behave like a paren.")
161
162 (defconst sml-starters-syms
163 (append sml-module-head-syms
164 '("abstype" "datatype" "exception" "fun"
165 "local" "infix" "infixr" "sharing" "nonfix"
166 "open" "type" "val" "and"
167 "withtype" "with"))
168 "The starters of new expressions.")
169
170 (defconst sml-pipeheads
171 '("|" "of" "fun" "fn" "and" "handle" "datatype" "abstype"
172 "(" "{" "[")
173 "A `|' corresponds to one of these.")
174
175 (defconst sml-keywords-regexp
176 (sml-syms-re '("abstraction" "abstype" "and" "andalso" "as" "before" "case"
177 "datatype" "else" "end" "eqtype" "exception" "do" "fn"
178 "fun" "functor" "handle" "if" "in" "include" "infix"
179 "infixr" "let" "local" "nonfix" "o" "of" "op" "open" "orelse"
180 "overload" "raise" "rec" "sharing" "sig" "signature"
181 "struct" "structure" "then" "type" "val" "where" "while"
182 "with" "withtype"))
183 "A regexp that matches any and all keywords of SML.")
184
185 (eval-and-compile
186 (defconst sml-id-re "\\sw\\(?:\\sw\\|\\s_\\)*"))
187
188 (defconst sml-tyvarseq-re
189 (concat "\\(?:\\(?:'+" sml-id-re "\\|(\\(?:[,']\\|" sml-id-re
190 "\\|\\s-\\)+)\\)\\s-+\\)?"))
191
192 ;;; Font-lock settings ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
193
194 (defcustom sml-font-lock-symbols nil
195 "Display \\ and -> and such using symbols in fonts.
196 This may sound like a neat trick, but be extra careful: it changes the
197 alignment and can thus lead to nasty surprises w.r.t layout."
198 :type 'boolean)
199
200 (defconst sml-font-lock-symbols-alist
201 '(("fn" . ?λ)
202 ("andalso" . ?∧) ;; ?⋀
203 ("orelse" . ?∨) ;; ?⋁
204 ;; ("as" . ?≡)
205 ("not" . ?¬)
206 ("div" . ?÷)
207 ("*" . ?×)
208 ("o" . ?○)
209 ("->" . ?→)
210 ("=>" . ?⇒)
211 ("<-" . ?←)
212 ("<>" . ?≠)
213 (">=" . ?≥)
214 ("<=" . ?≤)
215 ("..." . ?⋯)
216 ;; ("::" . ?∷)
217 ;; Some greek letters for type parameters.
218 ("'a" . ?α)
219 ("'b" . ?β)
220 ("'c" . ?γ)
221 ("'d" . ?δ)
222 ))
223
224 (defun sml-font-lock-compose-symbol ()
225 "Compose a sequence of ascii chars into a symbol.
226 Regexp match data 0 points to the chars."
227 ;; Check that the chars should really be composed into a symbol.
228 (let* ((start (match-beginning 0))
229 (end (match-end 0))
230 (syntaxes (if (eq (char-syntax (char-after start)) ?w)
231 '(?w) '(?. ?\\))))
232 (if (or (memq (char-syntax (or (char-before start) ?\ )) syntaxes)
233 (memq (char-syntax (or (char-after end) ?\ )) syntaxes)
234 (memq (get-text-property start 'face)
235 '(font-lock-doc-face font-lock-string-face
236 font-lock-comment-face)))
237 ;; No composition for you. Let's actually remove any composition
238 ;; we may have added earlier and which is now incorrect.
239 (remove-text-properties start end '(composition))
240 ;; That's a symbol alright, so add the composition.
241 (compose-region start end (cdr (assoc (match-string 0)
242 sml-font-lock-symbols-alist)))))
243 ;; Return nil because we're not adding any face property.
244 nil)
245
246 (defun sml-font-lock-symbols-keywords ()
247 (when sml-font-lock-symbols
248 `((,(regexp-opt (mapcar 'car sml-font-lock-symbols-alist) t)
249 (0 (sml-font-lock-compose-symbol))))))
250
251 ;; The font lock regular expressions.
252
253 (defconst sml-font-lock-keywords
254 `(;;(sml-font-comments-and-strings)
255 (,(concat "\\_<\\(fun\\|and\\)\\s-+" sml-tyvarseq-re
256 "\\(" sml-id-re "\\)\\s-+[^ \t\n=]")
257 (1 font-lock-keyword-face)
258 (2 font-lock-function-name-face))
259 (,(concat "\\_<\\(\\(?:data\\|abs\\|with\\|eq\\)?type\\)\\s-+"
260 sml-tyvarseq-re "\\(" sml-id-re "\\)")
261 (1 font-lock-keyword-face)
262 (2 font-lock-type-def-face))
263 (,(concat "\\_<\\(val\\)\\s-+\\(?:" sml-id-re "\\_>\\s-*\\)?\\("
264 sml-id-re "\\)\\s-*[=:]")
265 (1 font-lock-keyword-face)
266 (2 font-lock-variable-name-face))
267 (,(concat "\\_<\\(structure\\|functor\\|abstraction\\)\\s-+\\("
268 sml-id-re "\\)")
269 (1 font-lock-keyword-face)
270 (2 font-lock-module-def-face))
271 (,(concat "\\_<\\(signature\\)\\s-+\\(" sml-id-re "\\)")
272 (1 font-lock-keyword-face)
273 (2 font-lock-interface-def-face))
274
275 (,sml-keywords-regexp . font-lock-keyword-face)
276 ,@(sml-font-lock-symbols-keywords))
277 "Regexps matching standard SML keywords.")
278
279 (defface font-lock-type-def-face
280 '((t (:bold t)))
281 "Font Lock mode face used to highlight type definitions."
282 :group 'font-lock-highlighting-faces)
283 (defvar font-lock-type-def-face 'font-lock-type-def-face
284 "Face name to use for type definitions.")
285
286 (defface font-lock-module-def-face
287 '((t (:bold t)))
288 "Font Lock mode face used to highlight module definitions."
289 :group 'font-lock-highlighting-faces)
290 (defvar font-lock-module-def-face 'font-lock-module-def-face
291 "Face name to use for module definitions.")
292
293 (defface font-lock-interface-def-face
294 '((t (:bold t)))
295 "Font Lock mode face used to highlight interface definitions."
296 :group 'font-lock-highlighting-faces)
297 (defvar font-lock-interface-def-face 'font-lock-interface-def-face
298 "Face name to use for interface definitions.")
299
300 ;;
301 ;; Code to handle nested comments and unusual string escape sequences
302 ;;
303
304 (defvar sml-syntax-prop-table
305 (let ((st (make-syntax-table)))
306 (modify-syntax-entry ?\\ "." st)
307 (modify-syntax-entry ?* "." st)
308 st)
309 "Syntax table for text-properties.")
310
311 (defconst sml-font-lock-syntactic-keywords
312 `(("^\\s-*\\(\\\\\\)" (1 ',sml-syntax-prop-table))))
313
314 (defconst sml-font-lock-defaults
315 '(sml-font-lock-keywords nil nil nil nil
316 (font-lock-syntactic-keywords . sml-font-lock-syntactic-keywords)))
317
318
319 ;;; Indentation with SMIE
320
321 (defconst sml-smie-grammar
322 ;; We have several problem areas where SML's syntax can't be handled by an
323 ;; operator precedence grammar:
324 ;;
325 ;; "= A before B" is "= A) before B" if this is the
326 ;; `boolean-=' but it is "= (A before B)" if it's the `definitional-='.
327 ;; We can work around the problem by tweaking the lexer to return two
328 ;; different tokens for the two different kinds of `='.
329 ;; "of A | B" in a "case" we want "of (A | B, but in a `datatype'
330 ;; we want "of A) | B".
331 ;; "= A | B" can be "= A ) | B" if the = is from a "fun" definition,
332 ;; but it is "= (A | B" if it is a `datatype' definition (of course, if
333 ;; the previous token introducing the = is `and', deciding whether
334 ;; it's a datatype or a function requires looking even further back).
335 ;; "functor foo (...) where type a = b = ..." the first `=' looks very much
336 ;; like a `definitional-=' even tho it's just an equality constraint.
337 ;; Currently I don't even try to handle `where' at all.
338 (smie-prec2->grammar
339 (smie-merge-prec2s
340 (smie-bnf->prec2
341 '((exp ("if" exp "then" exp "else" exp)
342 ("case" exp "of" branches)
343 ("let" decls "in" cmds "end")
344 ("struct" decls "end")
345 ("sig" decls "end")
346 (sexp)
347 (sexp "handle" branches)
348 ("fn" sexp "=>" exp))
349 ;; "simple exp"s are the ones that can appear to the left of `handle'.
350 (sexp (sexp ":" type) ("(" exps ")")
351 (sexp "orelse" sexp)
352 (marg ":>" type)
353 (sexp "andalso" sexp))
354 (cmds (cmds ";" cmds) (exp))
355 (exps (exps "," exps) (exp)) ; (exps ";" exps)
356 (branches (sexp "=>" exp) (branches "|" branches))
357 ;; Operator precedence grammars handle separators much better then
358 ;; starters/terminators, so let's pretend that let/fun are separators.
359 (decls (sexp "d=" exp)
360 (sexp "d=" databranches)
361 (funbranches "|" funbranches)
362 (sexp "=of" type) ;After "exception".
363 ;; FIXME: Just like PROCEDURE in Pascal and Modula-2, this
364 ;; interacts poorly with the other constructs since I
365 ;; can't make "local" a separator like fun/val/type/...
366 ("local" decls "in" decls "end")
367 ;; (decls "local" decls "in" decls "end")
368 (decls "functor" decls)
369 (decls "signature" decls)
370 (decls "structure" decls)
371 (decls "type" decls)
372 (decls "open" decls)
373 (decls "and" decls)
374 (decls "infix" decls)
375 (decls "infixr" decls)
376 (decls "nonfix" decls)
377 (decls "abstype" decls)
378 (decls "datatype" decls)
379 (decls "exception" decls)
380 (decls "fun" decls)
381 (decls "val" decls))
382 (type (type "->" type)
383 (type "*" type))
384 (funbranches (sexp "d=" exp))
385 (databranches (sexp "=of" type) (databranches "d|" databranches))
386 ;; Module language.
387 ;; (mexp ("functor" marg "d=" mexp)
388 ;; ("structure" marg "d=" mexp)
389 ;; ("signature" marg "d=" mexp))
390 (marg (marg ":" type) (marg ":>" type))
391 (toplevel (decls) (exp) (toplevel ";" toplevel)))
392 ;; '(("local" . opener))
393 ;; '((nonassoc "else") (right "handle"))
394 '((nonassoc "of") (assoc "|")) ; "case a of b => case c of d => e | f"
395 '((nonassoc "handle") (assoc "|")) ; Idem for "handle".
396 '((assoc "->") (assoc "*"))
397 '((assoc "val" "fun" "type" "datatype" "abstype" "open" "infix" "infixr"
398 "nonfix" "functor" "signature" "structure" "exception"
399 ;; "local"
400 )
401 (assoc "and"))
402 '((assoc "orelse") (assoc "andalso") (nonassoc ":"))
403 '((assoc ";")) '((assoc ",")) '((assoc "d|")))
404
405 (smie-precs->prec2
406 '((nonassoc "andalso") ;To anchor the prec-table.
407 (assoc "before") ;0
408 (assoc ":=" "o") ;3
409 (nonassoc ">" ">=" "<>" "<" "<=" "=") ;4
410 (assoc "::" "@") ;5
411 (assoc "+" "-" "^") ;6
412 (assoc "/" "*" "quot" "rem" "div" "mod") ;7
413 (nonassoc " -dummy- "))) ;Bogus anchor at the end.
414 )))
415
416 (defvar sml-indent-separator-outdent 2)
417
418 (defun sml-smie-rules (kind token)
419 ;; I much preferred the pcase version of the code, especially while
420 ;; edebugging the code. But that will have to wait until we get rid of
421 ;; support for Emacs-23.
422 (case kind
423 (:elem (case token
424 (basic sml-indent-level)
425 (args sml-indent-args)))
426 (:list-intro (member token '("fn")))
427 (:after
428 (cond
429 ((equal token "struct") 0)
430 ((equal token "=>") (if (smie-rule-hanging-p) 0 2))
431 ((equal token "in") (if (smie-rule-parent-p "local") 0))
432 ((equal token "of") 3)
433 ((member token '("(" "{" "[")) (if (not (smie-rule-hanging-p)) 2))
434 ((equal token "else") (if (smie-rule-hanging-p) 0)) ;; (:next "if" 0)
435 ((member token '("|" "d|" ";" ",")) (smie-rule-separator kind))
436 ((equal token "d=")
437 (if (and (smie-rule-parent-p "val") (smie-rule-next-p "fn")) -3))))
438 (:before
439 (cond
440 ((equal token "=>") (if (smie-rule-parent-p "fn") 3))
441 ((equal token "of") 1)
442 ;; In case the language is extended to allow a | directly after of.
443 ((and (equal token "|") (smie-rule-prev-p "of")) 1)
444 ((member token '("|" "d|" ";" ",")) (smie-rule-separator kind))
445 ;; Treat purely syntactic block-constructs as being part of their parent,
446 ;; when the opening statement is hanging.
447 ((member token '("let" "(" "[" "{"))
448 (if (smie-rule-hanging-p) (smie-rule-parent)))
449 ;; Treat if ... else if ... as a single long syntactic construct.
450 ;; Similarly, treat fn a => fn b => ... as a single construct.
451 ((member token '("if" "fn"))
452 (and (not (smie-rule-bolp))
453 (smie-rule-prev-p (if (equal token "if") "else" "=>"))
454 (smie-rule-parent)))
455 ((equal token "and")
456 ;; FIXME: maybe "and" (c|sh)ould be handled as an smie-separator.
457 (cond
458 ((smie-rule-parent-p "datatype") (if sml-rightalign-and 5 0))
459 ((smie-rule-parent-p "fun" "val") 0)))
460 ((equal token "d=")
461 (cond
462 ((smie-rule-parent-p "datatype") (if (smie-rule-bolp) 2))
463 ((smie-rule-parent-p "structure" "signature") 0)))
464 ;; Indent an expression starting with "local" as if it were starting
465 ;; with "fun".
466 ((equal token "local") (smie-indent-keyword "fun"))
467 ;; FIXME: type/val/fun/... are separators but "local" is not, even though
468 ;; it appears in the same list. Try to fix up the problem by hand.
469 ;; ((or (equal token "local")
470 ;; (equal (cdr (assoc token smie-grammar))
471 ;; (cdr (assoc "fun" smie-grammar))))
472 ;; (let ((parent (save-excursion (smie-backward-sexp))))
473 ;; (when (or (and (equal (nth 2 parent) "local")
474 ;; (null (car parent)))
475 ;; (progn
476 ;; (setq parent (save-excursion (smie-backward-sexp "fun")))
477 ;; (eq (car parent) (nth 1 (assoc "fun" smie-grammar)))))
478 ;; (goto-char (nth 1 parent))
479 ;; (cons 'column (smie-indent-virtual)))))
480 ))))
481
482 (defun sml-smie-definitional-equal-p ()
483 "Figure out which kind of \"=\" this is.
484 Assumes point is right before the = sign."
485 ;; The idea is to look backward for the first occurrence of a token that
486 ;; requires a definitional "=" and then see if there's such a definitional
487 ;; equal between that token and ourselves (in which case we're not
488 ;; a definitional = ourselves).
489 ;; The "search for =" is naive and will match "=>" and "<=", but it turns
490 ;; out to be OK in practice because such tokens very rarely (if ever) appear
491 ;; between the =-starter and the corresponding definitional equal.
492 ;; One known problem case is code like:
493 ;; "functor foo (structure s : S) where type t = s.t ="
494 ;; where the "type t = s.t" is mistaken for a type definition.
495 (let ((re (concat "\\(" sml-=-starter-re "\\)\\|=")))
496 (save-excursion
497 (and (re-search-backward re nil t)
498 (or (match-beginning 1)
499 ;; If we first hit a "=", then that = is probably definitional
500 ;; and we're an equality, but not necessarily. One known
501 ;; problem case is code like:
502 ;; "functor foo (structure s : S) where type t = s.t ="
503 ;; where the first = is more like an equality (tho it doesn't
504 ;; matter much) and the second is definitional.
505 ;;
506 ;; FIXME: The test below could be used to recognize that the
507 ;; second = is not a mere equality, but that's not enough to
508 ;; parse the construct properly: we'd need something
509 ;; like a third kind of = token for structure definitions, in
510 ;; order for the parser to be able to skip the "type t = s.t"
511 ;; as a sub-expression.
512 ;;
513 ;; (and (not (looking-at "=>"))
514 ;; (not (eq ?< (char-before))) ;Not a <=
515 ;; (re-search-backward re nil t)
516 ;; (match-beginning 1)
517 ;; (equal "type" (buffer-substring (- (match-end 1) 4)
518 ;; (match-end 1))))
519 )))))
520
521 (defun sml-smie-non-nested-of-p ()
522 ;; FIXME: Maybe datatype-|-p makes this nested-of business unnecessary.
523 "Figure out which kind of \"of\" this is.
524 Assumes point is right before the \"of\" symbol."
525 (save-excursion
526 (and (re-search-backward (concat "\\(" sml-non-nested-of-starter-re
527 "\\)\\|\\_<case\\_>") nil t)
528 (match-beginning 1))))
529
530 (defun sml-smie-datatype-|-p ()
531 "Figure out which kind of \"|\" this is.
532 Assumes point is right before the | symbol."
533 (save-excursion
534 (forward-char 1) ;Skip the |.
535 (let ((after-type-def
536 '("|" "of" "in" "datatype" "and" "exception" "abstype" "infix"
537 "infixr" "nonfix" "local" "val" "fun" "structure" "functor"
538 "signature")))
539 (or (member (sml-smie-forward-token-1) after-type-def) ;Skip the tag.
540 (member (sml-smie-forward-token-1) after-type-def)))))
541
542 (defun sml-smie-forward-token-1 ()
543 (forward-comment (point-max))
544 (buffer-substring-no-properties
545 (point)
546 (progn
547 (or (/= 0 (skip-syntax-forward "'w_"))
548 (skip-syntax-forward ".'"))
549 (point))))
550
551 (defun sml-smie-forward-token ()
552 (let ((sym (sml-smie-forward-token-1)))
553 (cond
554 ((equal "op" sym)
555 (concat "op " (sml-smie-forward-token-1)))
556 ((member sym '("|" "of" "="))
557 ;; The important lexer for indentation's performance is the backward
558 ;; lexer, so for the forward lexer we delegate to the backward one.
559 (save-excursion (sml-smie-backward-token)))
560 (t sym))))
561
562 (defun sml-smie-backward-token-1 ()
563 (forward-comment (- (point)))
564 (buffer-substring-no-properties
565 (point)
566 (progn
567 (or (/= 0 (skip-syntax-backward ".'"))
568 (skip-syntax-backward "'w_"))
569 (point))))
570
571 (defun sml-smie-backward-token ()
572 (let ((sym (sml-smie-backward-token-1)))
573 (unless (zerop (length sym))
574 ;; FIXME: what should we do if `sym' = "op" ?
575 (let ((point (point)))
576 (if (equal "op" (sml-smie-backward-token-1))
577 (concat "op " sym)
578 (goto-char point)
579 (cond
580 ((string= sym "=") (if (sml-smie-definitional-equal-p) "d=" "="))
581 ((string= sym "of") (if (sml-smie-non-nested-of-p) "=of" "of"))
582 ((string= sym "|") (if (sml-smie-datatype-|-p) "d|" "|"))
583 (t sym)))))))
584
585 ;;;;
586 ;;;; Imenu support
587 ;;;;
588
589 (defvar sml-imenu-regexp
590 (concat "^[ \t]*\\(let[ \t]+\\)?"
591 (regexp-opt (append sml-module-head-syms
592 '("and" "fun" "datatype" "abstype" "type")) t)
593 "\\_>"))
594
595 (defun sml-imenu-create-index ()
596 (let (alist)
597 (goto-char (point-max))
598 (while (re-search-backward sml-imenu-regexp nil t)
599 (save-excursion
600 (let ((kind (match-string 2))
601 (column (progn (goto-char (match-beginning 2)) (current-column)))
602 (location
603 (progn (goto-char (match-end 0))
604 (forward-comment (point-max))
605 (when (looking-at sml-tyvarseq-re)
606 (goto-char (match-end 0)))
607 (point)))
608 (name (sml-smie-forward-token)))
609 ;; Eliminate trivial renamings.
610 (when (or (not (member kind '("structure" "signature")))
611 (progn (search-forward "=")
612 (forward-comment (point-max))
613 (looking-at "sig\\|struct")))
614 (push (cons (concat (make-string (/ column 2) ?\ ) name) location)
615 alist)))))
616 alist))
617
618 ;;; Generic prog-proc interaction.
619
620 (require 'comint)
621 (require 'compile)
622
623 (defvar sml-prog-proc-mode-map
624 (let ((map (make-sparse-keymap)))
625 (define-key map [?\C-c ?\C-l] 'sml-prog-proc-load-file)
626 (define-key map [?\C-c ?\C-c] 'sml-prog-proc-compile)
627 (define-key map [?\C-c ?\C-z] 'sml-prog-proc-switch-to)
628 (define-key map [?\C-c ?\C-r] 'sml-prog-proc-send-region)
629 (define-key map [?\C-c ?\C-b] 'sml-prog-proc-send-buffer)
630 ;; FIXME: Add
631 ;; (define-key map [?\M-C-x] 'sml-prog-proc-send-defun)
632 ;; (define-key map [?\C-x ?\C-e] 'sml-prog-proc-send-last-sexp)
633 ;; FIXME: Add menu. Now, that's trickier because keymap inheritance
634 ;; doesn't play nicely with menus!
635 map)
636 "Keymap for `sml-prog-proc-mode'.")
637
638 (defvar sml-prog-proc--buffer nil
639 "The inferior-process buffer to which to send code.")
640 (make-variable-buffer-local 'sml-prog-proc--buffer)
641
642 (defstruct (sml-prog-proc-descriptor
643 (:constructor sml-prog-proc-make)
644 (:predicate nil)
645 (:copier nil))
646 (name nil :read-only t)
647 (run nil :read-only t)
648 (load-cmd nil :read-only t)
649 (chdir-cmd nil :read-only t)
650 (command-eol "\n" :read-only t)
651 (compile-commands-alist nil :read-only t))
652
653 (defvar sml-prog-proc-descriptor nil
654 "Struct containing the various functions to create a new process, ...")
655
656 (defmacro sml-prog-proc--prop (prop)
657 `(,(intern (format "sml-prog-proc-descriptor-%s" prop))
658 (or sml-prog-proc-descriptor
659 ;; FIXME: Look for available ones and pick one.
660 (error "Not a `sml-prog-proc' buffer"))))
661 (defmacro sml-prog-proc--call (method &rest args)
662 `(funcall (sml-prog-proc--prop ,method) ,@args))
663
664 ;; The inferior process and his buffer are basically interchangeable.
665 ;; Currently the code takes sml-prog-proc--buffer as the main reference,
666 ;; but all users should either use sml-prog-proc-proc or sml-prog-proc-buffer
667 ;; to find the info.
668
669 (defun sml-prog-proc-proc ()
670 "Return the inferior process for the code in current buffer."
671 (or (and (buffer-live-p sml-prog-proc--buffer)
672 (get-buffer-process sml-prog-proc--buffer))
673 (when (derived-mode-p 'sml-prog-proc-mode 'sml-prog-proc-comint-mode)
674 (setq sml-prog-proc--buffer (current-buffer))
675 (get-buffer-process sml-prog-proc--buffer))
676 (let ((ppd sml-prog-proc-descriptor)
677 (buf (sml-prog-proc--call run)))
678 (with-current-buffer buf
679 (if (and ppd (null sml-prog-proc-descriptor))
680 (set (make-local-variable 'sml-prog-proc-descriptor) ppd)))
681 (setq sml-prog-proc--buffer buf)
682 (get-buffer-process sml-prog-proc--buffer))))
683
684 (defun sml-prog-proc-buffer ()
685 "Return the buffer of the inferior process."
686 (process-buffer (sml-prog-proc-proc)))
687
688 (defun sml-prog-proc-switch-to ()
689 "Switch to the buffer running the read-eval-print process."
690 (pop-to-buffer (sml-prog-proc-buffer)))
691
692 (defun sml-prog-proc-send-string (proc str)
693 "Send command STR to PROC, with an EOL terminator appended."
694 (with-current-buffer (process-buffer proc)
695 ;; FIXME: comint-send-string does not pass the string through
696 ;; comint-input-filter-function, so we have to do it by hand.
697 ;; Maybe we should insert the command into the buffer and then call
698 ;; comint-send-input?
699 (sml-prog-proc-comint-input-filter-function nil)
700 (comint-send-string proc (concat str (sml-prog-proc--prop command-eol)))))
701
702 (defun sml-prog-proc-load-file (file &optional and-go)
703 "Load FILE into the read-eval-print process.
704 FILE is the file visited by the current buffer.
705 If prefix argument AND-GO is used, then we additionally switch
706 to the buffer where the process is running."
707 (interactive
708 (list (or buffer-file-name
709 (read-file-name "File to load: " nil nil t))
710 current-prefix-arg))
711 (comint-check-source file)
712 (let ((proc (sml-prog-proc-proc)))
713 (sml-prog-proc-send-string proc (sml-prog-proc--call load-cmd file))
714 (when and-go (pop-to-buffer (process-buffer proc)))))
715
716 (defvar sml-prog-proc--tmp-file nil)
717
718 (defun sml-prog-proc-send-region (start end &optional and-go)
719 "Send the content of the region to the read-eval-print process.
720 START..END delimit the region; AND-GO if non-nil indicate to additionally
721 switch to the process's buffer."
722 (interactive "r\nP")
723 (if (> start end) (let ((tmp end)) (setq end start) (setq start tmp))
724 (if (= start end) (error "Nothing to send: the region is empty")))
725 (let ((proc (sml-prog-proc-proc))
726 (tmp (make-temp-file "emacs-region")))
727 (write-region start end tmp nil 'silently)
728 (when sml-prog-proc--tmp-file
729 (ignore-errors (delete-file (car sml-prog-proc--tmp-file)))
730 (set-marker (cdr sml-prog-proc--tmp-file) nil))
731 (setq sml-prog-proc--tmp-file (cons tmp (copy-marker start)))
732 (sml-prog-proc-send-string proc (sml-prog-proc--call load-cmd tmp))
733 (when and-go (pop-to-buffer (process-buffer proc)))))
734
735 (defun sml-prog-proc-send-buffer (&optional and-go)
736 "Send the content of the current buffer to the read-eval-print process.
737 AND-GO if non-nil indicate to additionally switch to the process's buffer."
738 (interactive "P")
739 (sml-prog-proc-send-region (point-min) (point-max) and-go))
740
741 (define-derived-mode sml-prog-proc-mode prog-mode "Sml-Prog-Proc"
742 "Major mode for editing source code and interact with an interactive loop."
743 )
744
745 ;;; Extended comint-mode for Sml-Prog-Proc.
746
747 (defun sml-prog-proc-chdir (dir)
748 "Change the working directory of the inferior process to DIR."
749 (interactive "DChange to directory: ")
750 (let ((dir (expand-file-name dir))
751 (proc (sml-prog-proc-proc)))
752 (with-current-buffer (process-buffer proc)
753 (sml-prog-proc-send-string proc (sml-prog-proc--call chdir-cmd dir))
754 (setq default-directory (file-name-as-directory dir)))))
755
756 (defun sml-prog-proc-comint-input-filter-function (str)
757 ;; `compile.el' doesn't know that file location info from errors should be
758 ;; recomputed afresh (without using stale info from earlier compilations).
759 (compilation-forget-errors) ;Has to run before compilation-fake-loc.
760 (if (and sml-prog-proc--tmp-file (marker-buffer (cdr sml-prog-proc--tmp-file)))
761 (compilation-fake-loc (cdr sml-prog-proc--tmp-file)
762 (car sml-prog-proc--tmp-file)))
763 str)
764
765 (define-derived-mode sml-prog-proc-comint-mode comint-mode "Sml-Prog-Proc-Comint"
766 "Major mode for an inferior process used to run&compile source code."
767 ;; Enable compilation-minor-mode, but only after the child mode is setup
768 ;; since the child-mode might want to add rules to
769 ;; compilation-error-regexp-alist.
770 (add-hook 'after-change-major-mode-hook #'compilation-minor-mode nil t)
771 ;; The keymap of compilation-minor-mode is too unbearable, so we
772 ;; need to hide most of the bindings.
773 (let ((map (make-sparse-keymap)))
774 (dolist (keys '([menu-bar] [follow-link]))
775 ;; Preserve some of the bindings.
776 (define-key map keys (lookup-key compilation-minor-mode-map keys)))
777 (add-to-list 'minor-mode-overriding-map-alist
778 (cons 'compilation-minor-mode map)))
779
780 (add-hook 'comint-input-filter-functions
781 #'sml-prog-proc-comint-input-filter-function nil t))
782
783 (defvar sml-prog-proc--compile-command nil
784 "The command used by default by `sml-prog-proc-compile'.")
785
786 (defun sml-prog-proc-compile (command &optional and-go)
787 "Pass COMMAND to the read-eval-loop process to compile the current file.
788
789 You can then use the command \\[next-error] to find the next error message
790 and move to the source code that caused it.
791
792 Interactively, prompts for the command if `compilation-read-command' is
793 non-nil. With prefix arg, always prompts.
794
795 Prefix arg AND-GO also means to switch to the read-eval-loop buffer afterwards."
796 (interactive
797 (let* ((dir default-directory)
798 (cmd "cd \"."))
799 ;; Look for files to determine the default command.
800 (while (and (stringp dir)
801 (progn
802 (dolist (cf (sml-prog-proc--prop compile-commands-alist))
803 (when (file-exists-p (expand-file-name (cdr cf) dir))
804 (setq cmd (concat cmd "\"; " (car cf)))
805 (return nil)))
806 (not cmd)))
807 (let ((newdir (file-name-directory (directory-file-name dir))))
808 (setq dir (unless (equal newdir dir) newdir))
809 (setq cmd (concat cmd "/.."))))
810 (setq cmd
811 (cond
812 ((local-variable-p 'sml-prog-proc--compile-command)
813 sml-prog-proc--compile-command)
814 ((string-match "^\\s-*cd\\s-+\"\\.\"\\s-*;\\s-*" cmd)
815 (substring cmd (match-end 0)))
816 ((string-match "^\\s-*cd\\s-+\"\\(\\./\\)" cmd)
817 (replace-match "" t t cmd 1))
818 ((string-match ";" cmd) cmd)
819 (t sml-prog-proc--compile-command)))
820 ;; code taken from compile.el
821 (list (if (or compilation-read-command current-prefix-arg)
822 (read-from-minibuffer "Compile command: "
823 cmd nil nil '(compile-history . 1))
824 cmd))))
825 ;; ;; now look for command's file to determine the directory
826 ;; (setq dir default-directory)
827 ;; (while (and (stringp dir)
828 ;; (dolist (cf (sml-prog-proc--prop compile-commands-alist) t)
829 ;; (when (and (equal cmd (car cf))
830 ;; (file-exists-p (expand-file-name (cdr cf) dir)))
831 ;; (return nil))))
832 ;; (let ((newdir (file-name-directory (directory-file-name dir))))
833 ;; (setq dir (unless (equal newdir dir) newdir))))
834 ;; (setq dir (or dir default-directory))
835 ;; (list cmd dir)))
836 (set (make-local-variable 'sml-prog-proc--compile-command) command)
837 (save-some-buffers (not compilation-ask-about-save) nil)
838 (let ((dir default-directory))
839 (when (string-match "^\\s-*cd\\s-+\"\\([^\"]+\\)\"\\s-*;" command)
840 (setq dir (match-string 1 command))
841 (setq command (replace-match "" t t command)))
842 (setq dir (expand-file-name dir))
843 (let ((proc (sml-prog-proc-proc))
844 (eol (sml-prog-proc--prop command-eol)))
845 (with-current-buffer (process-buffer proc)
846 (setq default-directory dir)
847 (sml-prog-proc-send-string
848 proc (concat (sml-prog-proc--call chdir-cmd dir)
849 ;; Strip the newline, to avoid adding a prompt.
850 (if (string-match "\n\\'" eol)
851 (replace-match " " t t eol) eol)
852 command))
853 (when and-go (pop-to-buffer (process-buffer proc)))))))
854
855
856 ;;; SML Sml-Prog-Proc support.
857
858 (defcustom sml-program-name "sml"
859 "Program to run as Standard SML read-eval-print loop."
860 :type 'string)
861
862 (defcustom sml-default-arg ""
863 "Default command line option to pass to `sml-program-name', if any."
864 :type 'string)
865
866 (defcustom sml-host-name ""
867 "Host on which to run `sml-program-name'."
868 :type 'string)
869
870 (defcustom sml-config-file "~/.smlproc.sml"
871 "File that should be fed to the SML process when started."
872 :type 'string)
873
874
875 (defcustom sml-prompt-regexp "^[-=>#] *"
876 "Regexp used to recognise prompts in the inferior SML process."
877 :type 'regexp)
878
879 (defcustom sml-compile-commands-alist
880 '(("CMB.make()" . "all-files.cm")
881 ("CMB.make()" . "pathconfig")
882 ("CM.make()" . "sources.cm")
883 ("use \"load-all\"" . "load-all"))
884 "Commands used by default by `sml-sml-prog-proc-compile'.
885 Each command is associated with its \"main\" file.
886 It is perfectly OK to associate several files with a command or several
887 commands with the same file.")
888
889 ;; FIXME: Try to auto-detect the process and set those vars accordingly.
890
891 (defvar sml-use-command "use \"%s\""
892 "Template for loading a file into the inferior SML process.
893 Set to \"use \\\"%s\\\"\" for SML/NJ or Edinburgh ML;
894 set to \"PolyML.use \\\"%s\\\"\" for Poly/ML, etc.")
895
896 (defvar sml-cd-command "OS.FileSys.chDir \"%s\""
897 "Command template for changing working directories under SML.
898 Set this to nil if your compiler can't change directories.
899
900 The format specifier \"%s\" will be converted into the directory name
901 specified when running the command \\[sml-cd].")
902
903 (defvar sml-error-regexp-alist
904 `( ;; Poly/ML messages
905 ("^\\(Error\\|Warning:\\) in '\\(.+\\)', line \\([0-9]+\\)" 2 3)
906 ;; Moscow ML
907 ("^File \"\\([^\"]+\\)\", line \\([0-9]+\\)\\(-\\([0-9]+\\)\\)?, characters \\([0-9]+\\)-\\([0-9]+\\):" 1 2 5)
908 ;; SML/NJ: the file-pattern is anchored to avoid
909 ;; pathological behavior with very long lines.
910 ("^[-= ]*\\(.*[^\n)]\\)\\( (.*)\\)?:\\([0-9]+\\)\\.\\([0-9]+\\)\\(-\\([0-9]+\\)\\.\\([0-9]+\\)\\)? \\(Error\\|Warnin\\(g\\)\\): .*" 1
911 (3 . 6) (4 . 7) (9))
912 ;; SML/NJ's exceptions: see above.
913 ("^ +\\(raised at: \\)?\\(.+\\):\\([0-9]+\\)\\.\\([0-9]+\\)\\(-\\([0-9]+\\)\\.\\([0-9]+\\)\\)" 2
914 (3 . 6) (4 . 7)))
915 "Alist that specifies how to match errors in compiler output.
916 See `compilation-error-regexp-alist' for a description of the format.")
917
918 (defconst sml-pp-functions
919 (sml-prog-proc-make :name "SML"
920 :run (lambda () (call-interactively #'sml-run))
921 :load-cmd (lambda (file) (format sml-use-command file))
922 :chdir-cmd (lambda (dir) (format sml-cd-command dir))
923 :compile-commands-alist sml-compile-commands-alist
924 :command-eol ";\n"
925 ))
926
927 ;; font-lock support
928 (defconst inferior-sml-font-lock-keywords
929 `(;; prompt and following interactive command
930 ;; FIXME: Actually, this should already be taken care of by comint.
931 (,(concat "\\(" sml-prompt-regexp "\\)\\(.*\\)")
932 (1 font-lock-prompt-face)
933 (2 font-lock-command-face keep))
934 ;; CM's messages
935 ("^\\[\\(.*GC #.*\n\\)*.*\\]" . font-lock-comment-face)
936 ;; SML/NJ's irritating GC messages
937 ("^GC #.*" . font-lock-comment-face))
938 "Font-locking specification for inferior SML mode.")
939
940 (defface font-lock-prompt-face
941 '((t (:bold t)))
942 "Font Lock mode face used to highlight prompts."
943 :group 'font-lock-highlighting-faces)
944 (defvar font-lock-prompt-face 'font-lock-prompt-face
945 "Face name to use for prompts.")
946
947 (defface font-lock-command-face
948 '((t (:bold t)))
949 "Font Lock mode face used to highlight interactive commands."
950 :group 'font-lock-highlighting-faces)
951 (defvar font-lock-command-face 'font-lock-command-face
952 "Face name to use for interactive commands.")
953
954 (defconst inferior-sml-font-lock-defaults
955 '(inferior-sml-font-lock-keywords nil nil nil nil))
956
957 (defun sml--read-run-cmd ()
958 (list
959 (read-string "SML command: " sml-program-name)
960 (if (or current-prefix-arg (> (length sml-default-arg) 0))
961 (read-string "Any args: " sml-default-arg)
962 sml-default-arg)
963 (if (or current-prefix-arg (> (length sml-host-name) 0))
964 (read-string "On host: " sml-host-name)
965 sml-host-name)))
966
967 (defun sml-run (cmd arg &optional host)
968 "Run the program CMD with given arguments ARG.
969 The command is run in buffer *CMD* using mode `inferior-sml-mode'.
970 If the buffer already exists and has a running process, then
971 just go to this buffer.
972
973 If a prefix argument is used, the user is also prompted for a HOST
974 on which to run CMD using `remote-shell-program'.
975
976 \(Type \\[describe-mode] in the process's buffer for a list of commands.)"
977 (interactive (sml--read-run-cmd))
978 (let* ((pname (file-name-nondirectory cmd))
979 (args (split-string arg))
980 (file (when (and sml-config-file (file-exists-p sml-config-file))
981 sml-config-file)))
982 ;; And this -- to keep these as defaults even if
983 ;; they're set in the mode hooks.
984 (setq sml-program-name cmd)
985 (setq sml-default-arg arg)
986 (setq sml-host-name host)
987 ;; For remote execution, use `remote-shell-program'
988 (when (> (length host) 0)
989 (setq args (list* host "cd" default-directory ";" cmd args))
990 (setq cmd remote-shell-program))
991 ;; Go for it.
992 (save-current-buffer
993 (let ((exec-path (if (and (file-name-directory cmd)
994 (not (file-name-absolute-p cmd)))
995 ;; If the command has slashes, make sure we
996 ;; first look relative to the current directory.
997 ;; Emacs-21 does it for us, but not Emacs-20.
998 (cons default-directory exec-path) exec-path)))
999 (pop-to-buffer (apply 'make-comint pname cmd file args)))
1000
1001 (inferior-sml-mode)
1002 (goto-char (point-max))
1003 (current-buffer))))
1004
1005 (defun sml-send-function (&optional and-go)
1006 "Send current paragraph to the inferior SML process.
1007 With a prefix argument AND-GO switch to the repl buffer as well."
1008 (interactive "P")
1009 (save-excursion
1010 (sml-mark-function)
1011 (sml-prog-proc-send-region (point) (mark)))
1012 (if and-go (sml-prog-proc-switch-to)))
1013
1014 (defvar inferior-sml-mode-map
1015 (let ((map (make-sparse-keymap)))
1016 (set-keymap-parent map comint-mode-map)
1017 (define-key map "\C-c\C-s" 'run-sml)
1018 (define-key map "\C-c\C-l" 'sml-load-file)
1019 (define-key map "\t" 'completion-at-point)
1020 map)
1021 "Keymap for inferior-sml mode.")
1022
1023
1024 (declare-function smerge-refine-subst "smerge-mode"
1025 (beg1 end1 beg2 end2 props-c))
1026
1027 (defun inferior-sml-next-error-hook ()
1028 ;; Try to recognize SML/NJ type error message and to highlight finely the
1029 ;; difference between the two types (in case they're large, it's not
1030 ;; always obvious to spot it).
1031 ;;
1032 ;; Sample messages:
1033 ;;
1034 ;; Data.sml:31.9-33.33 Error: right-hand-side of clause doesn't agree with function result type [tycon mismatch]
1035 ;; expression: Hstring
1036 ;; result type: Hstring * int
1037 ;; in declaration:
1038 ;; des2hs = (fn SYM_ID hs => hs
1039 ;; | SYM_OP hs => hs
1040 ;; | SYM_CHR hs => hs)
1041 ;; Data.sml:35.44-35.63 Error: operator and operand don't agree [tycon mismatch]
1042 ;; operator domain: Hstring * Hstring
1043 ;; operand: (Hstring * int) * (Hstring * int)
1044 ;; in expression:
1045 ;; HSTRING.ieq (h1,h2)
1046 ;; vparse.sml:1861.6-1922.14 Error: case object and rules don't agree [tycon mismatch]
1047 ;; rule domain: STConstraints list list option
1048 ;; object: STConstraints list option
1049 ;; in expression:
1050 (save-current-buffer
1051 (when (and (derived-mode-p 'sml-mode 'inferior-sml-mode)
1052 (boundp 'next-error-last-buffer)
1053 (bufferp next-error-last-buffer)
1054 (set-buffer next-error-last-buffer)
1055 (derived-mode-p 'inferior-sml-mode)
1056 ;; The position of `point' is not guaranteed :-(
1057 (looking-at (concat ".*\\[tycon mismatch\\]\n"
1058 " \\(operator domain\\|expression\\|rule domain\\): +")))
1059 (require 'smerge-mode)
1060 (save-excursion
1061 (let ((b1 (match-end 0))
1062 e1 b2 e2)
1063 (when (re-search-forward "\n in \\(expression\\|declaration\\):\n"
1064 nil t)
1065 (setq e2 (match-beginning 0))
1066 (when (re-search-backward
1067 "\n \\(operand\\|result type\\|object\\): +"
1068 b1 t)
1069 (setq e1 (match-beginning 0))
1070 (setq b2 (match-end 0))
1071 (smerge-refine-subst b1 e1 b2 e2
1072 '((face . smerge-refined-change))))))))))
1073
1074 (define-derived-mode inferior-sml-mode sml-prog-proc-comint-mode "Inferior-SML"
1075 "Major mode for interacting with an inferior SML process.
1076
1077 The following commands are available:
1078 \\{inferior-sml-mode-map}
1079
1080 An SML process can be fired up (again) with \\[sml].
1081
1082 Customisation: Entry to this mode runs the hooks on `comint-mode-hook'
1083 and `inferior-sml-mode-hook' (in that order).
1084
1085 Variables controlling behaviour of this mode are
1086
1087 `sml-program-name' (default \"sml\")
1088 Program to run as SML.
1089
1090 `sml-use-command' (default \"use \\\"%s\\\"\")
1091 Template for loading a file into the inferior SML process.
1092
1093 `sml-cd-command' (default \"System.Directory.cd \\\"%s\\\"\")
1094 SML command for changing directories in SML process (if possible).
1095
1096 `sml-prompt-regexp' (default \"^[\\-=] *\")
1097 Regexp used to recognise prompts in the inferior SML process.
1098
1099 You can send text to the inferior SML process from other buffers containing
1100 SML source.
1101 `switch-to-sml' switches the current buffer to the SML process buffer.
1102 `sml-send-function' sends the current *paragraph* to the SML process.
1103 `sml-send-region' sends the current region to the SML process.
1104
1105 Prefixing the sml-send-<whatever> commands with \\[universal-argument]
1106 causes a switch to the SML process buffer after sending the text.
1107
1108 For information on running multiple processes in multiple buffers, see
1109 documentation for variable `sml-buffer'.
1110
1111 Commands:
1112 RET after the end of the process' output sends the text from the
1113 end of process to point.
1114 RET before the end of the process' output copies the current line
1115 to the end of the process' output, and sends it.
1116 DEL converts tabs to spaces as it moves back.
1117 TAB file name completion, as in shell-mode, etc.."
1118 (setq comint-prompt-regexp sml-prompt-regexp)
1119 (sml-mode-variables)
1120
1121 ;; We have to install it globally, 'cause it's run in the *source* buffer :-(
1122 (add-hook 'next-error-hook 'inferior-sml-next-error-hook)
1123
1124 ;; Make TAB add a " rather than a space at the end of a file name.
1125 (set (make-local-variable 'comint-completion-addsuffix) '(?/ . ?\"))
1126
1127 (set (make-local-variable 'font-lock-defaults)
1128 inferior-sml-font-lock-defaults)
1129
1130 ;; Compilation support (used for `next-error').
1131 (set (make-local-variable 'compilation-error-regexp-alist)
1132 sml-error-regexp-alist)
1133 ;; FIXME: move it to sml-mode?
1134 (set (make-local-variable 'compilation-error-screen-columns) nil)
1135
1136 (setq mode-line-process '(": %s")))
1137
1138 ;;; MORE CODE FOR SML-MODE
1139
1140 ;;;###autoload
1141 (add-to-list 'auto-mode-alist '("\\.s\\(ml\\|ig\\)\\'" . sml-mode))
1142
1143 (defvar comment-quote-nested)
1144
1145 ;;;###autoload
1146 (define-derived-mode sml-mode sml-prog-proc-mode "SML"
1147 "\\<sml-mode-map>Major mode for editing Standard ML code.
1148 This mode runs `sml-mode-hook' just before exiting.
1149 See also (info \"(sml-mode)Top\").
1150 \\{sml-mode-map}"
1151 (set (make-local-variable 'sml-prog-proc-descriptor) sml-pp-functions)
1152 (set (make-local-variable 'font-lock-defaults) sml-font-lock-defaults)
1153 (set (make-local-variable 'outline-regexp) sml-outline-regexp)
1154 (set (make-local-variable 'imenu-create-index-function)
1155 'sml-imenu-create-index)
1156 (set (make-local-variable 'add-log-current-defun-function)
1157 'sml-current-fun-name)
1158 ;; Treat paragraph-separators in comments as paragraph-separators.
1159 (set (make-local-variable 'paragraph-separate)
1160 (concat "\\([ \t]*\\*)?\\)?\\(" paragraph-separate "\\)"))
1161 (set (make-local-variable 'require-final-newline) t)
1162 (set (make-local-variable 'electric-indent-chars)
1163 (cons ?\; (if (boundp 'electric-indent-chars)
1164 electric-indent-chars '(?\n))))
1165 (set (make-local-variable 'electric-layout-rules)
1166 `((?\; . ,(lambda ()
1167 (save-excursion
1168 (skip-chars-backward " \t;")
1169 (unless (or (bolp)
1170 (progn (skip-chars-forward " \t;")
1171 (eolp)))
1172 'after))))))
1173 (when sml-electric-pipe-mode
1174 (add-hook 'post-self-insert-hook #'sml-post-self-insert-pipe nil t))
1175 (sml-mode-variables))
1176
1177 (defun sml-mode-variables ()
1178 (set-syntax-table sml-mode-syntax-table)
1179 (setq local-abbrev-table sml-mode-abbrev-table)
1180 ;; Setup indentation and sexp-navigation.
1181 (smie-setup sml-smie-grammar #'sml-smie-rules
1182 :backward-token #'sml-smie-backward-token
1183 :forward-token #'sml-smie-forward-token)
1184 (set (make-local-variable 'parse-sexp-ignore-comments) t)
1185 (set (make-local-variable 'comment-start) "(* ")
1186 (set (make-local-variable 'comment-end) " *)")
1187 (set (make-local-variable 'comment-start-skip) "(\\*+\\s-*")
1188 (set (make-local-variable 'comment-end-skip) "\\s-*\\*+)")
1189 ;; No need to quote nested comments markers.
1190 (set (make-local-variable 'comment-quote-nested) nil))
1191
1192 (defun sml-funname-of-and ()
1193 "Name of the function this `and' defines, or nil if not a function.
1194 Point has to be right after the `and' symbol and is not preserved."
1195 (forward-comment (point-max))
1196 (if (looking-at sml-tyvarseq-re) (goto-char (match-end 0)))
1197 (let ((sym (sml-smie-forward-token)))
1198 (forward-comment (point-max))
1199 (unless (or (member sym '(nil "d="))
1200 (member (sml-smie-forward-token) '("d=")))
1201 sym)))
1202
1203 (defun sml-find-forward (re)
1204 (while (progn (forward-comment (point-max))
1205 (not (looking-at re)))
1206 (or (ignore-errors (forward-sexp 1) t) (forward-char 1))))
1207
1208 (defun sml-electric-pipe ()
1209 "Insert a \"|\".
1210 Depending on the context insert the name of function, a \"=>\" etc."
1211 (interactive)
1212 (unless (save-excursion (skip-chars-backward "\t ") (bolp)) (insert "\n"))
1213 (insert "| ")
1214 (unless (sml-post-self-insert-pipe (1- (point)))
1215 (indent-according-to-mode)))
1216
1217 (defun sml-post-self-insert-pipe (&optional acp)
1218 (when (or acp (and (eq ?| last-command-event)
1219 (setq acp (electric--after-char-pos))))
1220 (let ((text
1221 (save-excursion
1222 (goto-char (1- acp)) ;Jump before the "|" we just inserted.
1223 (let ((sym (sml-find-matching-starter sml-pipeheads
1224 ;; (sml-op-prec "|" 'back)
1225 )))
1226 (sml-smie-forward-token)
1227 (forward-comment (point-max))
1228 (cond
1229 ((string= sym "|")
1230 (let ((f (sml-smie-forward-token)))
1231 (sml-find-forward "\\(=>\\|=\\||\\)\\S.")
1232 (cond
1233 ((looking-at "|") nil) ; A datatype or an OR pattern?
1234 ((looking-at "=>") " => ") ;`case', or `fn' or `handle'.
1235 ((looking-at "=") ;A function.
1236 (cons (concat f " ")" = ")))))
1237 ((string= sym "and")
1238 ;; Could be a datatype or a function.
1239 (let ((funname (sml-funname-of-and)))
1240 (if funname (cons (concat funname " ") " = ") nil)))
1241 ((string= sym "fun")
1242 (while (and (setq sym (sml-smie-forward-token))
1243 (string-match "^'" sym))
1244 (forward-comment (point-max)))
1245 (cons (concat sym " ") " = "))
1246 ((member sym '("case" "handle" "of")) " => ") ;; "fn"?
1247 ;;((member sym '("abstype" "datatype")) "")
1248 (t nil))))))
1249 (when text
1250 (save-excursion
1251 (goto-char (1- acp))
1252 (unless (save-excursion (skip-chars-backward "\t ") (bolp))
1253 (insert "\n")))
1254 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
1255 (let ((use-region (and (use-region-p) (< (point) (mark)))))
1256 ;; (skeleton-proxy-new `(nil ,(if (consp text) (pop text)) _ ,text))
1257 (when (consp text) (insert (pop text)))
1258 (if (not use-region)
1259 (save-excursion (insert text))
1260 (goto-char (mark))
1261 (insert text)))
1262 (indent-according-to-mode)
1263 t))))
1264
1265
1266 ;;; Misc
1267
1268 (defun sml-mark-function ()
1269 "Mark the surrounding function. Or try to at least."
1270 (interactive)
1271 ;; FIXME: Provide beginning-of-defun-function so mark-defun "just works".
1272 (let ((start (point)))
1273 (sml-beginning-of-defun)
1274 (let ((beg (point)))
1275 (smie-forward-sexp 'halfsexp)
1276 (if (or (< start beg) (> start (point)))
1277 (progn
1278 (goto-char start)
1279 (mark-paragraph))
1280 (push-mark nil t t)
1281 (goto-char beg)))))
1282
1283 (defun sml-back-to-outer-indent ()
1284 "Unindents to the next outer level of indentation."
1285 (interactive)
1286 (save-excursion
1287 (forward-line 0)
1288 (let ((start-column (current-indentation))
1289 indent)
1290 (when (> start-column 0)
1291 (save-excursion
1292 (while (>= (setq indent
1293 (if (re-search-backward "^[ \t]*[^\n\t]" nil t)
1294 (current-indentation)
1295 0))
1296 start-column))
1297 (skip-chars-forward " \t")
1298 (let ((pos (point)))
1299 (move-to-column start-column)
1300 (when (re-search-backward " \\([^ \t\n]\\)" pos t)
1301 (goto-char (match-beginning 1))
1302 (setq indent (current-column)))))
1303 (indent-line-to indent)))))
1304
1305 (defun sml-find-matching-starter (syms)
1306 (let ((halfsexp nil)
1307 tok)
1308 ;;(sml-smie-forward-token)
1309 (while (not (or (bobp)
1310 (member (nth 2 (setq tok (smie-backward-sexp halfsexp)))
1311 syms)))
1312 (cond
1313 ((null (car tok)) nil)
1314 ((numberp (car tok)) (setq halfsexp 'half))
1315 (t (goto-char (cadr tok)))))
1316 (if (nth 2 tok) (goto-char (cadr tok)))
1317 (nth 2 tok)))
1318
1319 (defun sml-skip-siblings ()
1320 (let (tok)
1321 (while (and (not (bobp))
1322 (progn (setq tok (smie-backward-sexp 'half))
1323 (cond
1324 ((null (car tok)) t)
1325 ((numberp (car tok)) t)
1326 (t nil)))))
1327 (if (nth 2 tok) (goto-char (cadr tok)))
1328 (nth 2 tok)))
1329
1330 (defun sml-beginning-of-defun ()
1331 (let ((sym (sml-find-matching-starter sml-starters-syms)))
1332 (if (member sym '("fun" "and" "functor" "signature" "structure"
1333 "abstraction" "datatype" "abstype"))
1334 (save-excursion (sml-smie-forward-token) (forward-comment (point-max))
1335 (sml-smie-forward-token))
1336 ;; We're inside a "non function declaration": let's skip all other
1337 ;; declarations that we find at the same level and try again.
1338 (sml-skip-siblings)
1339 ;; Obviously, let's not try again if we're at bobp.
1340 (unless (bobp) (sml-beginning-of-defun)))))
1341
1342 (defcustom sml-max-name-components 3
1343 "Maximum number of components to use for the current function name."
1344 :type 'integer)
1345
1346 (defun sml-current-fun-name ()
1347 (save-excursion
1348 (let ((count sml-max-name-components)
1349 fullname name)
1350 (end-of-line)
1351 (while (and (> count 0)
1352 (setq name (sml-beginning-of-defun)))
1353 (decf count)
1354 (setq fullname (if fullname (concat name "." fullname) name))
1355 ;; Skip all other declarations that we find at the same level.
1356 (sml-skip-siblings))
1357 fullname)))
1358
1359
1360 ;;; INSERTING PROFORMAS (COMMON SML-FORMS)
1361
1362 (defvar sml-forms-alist nil
1363 "Alist of code templates.
1364 You can extend this alist to your heart's content. For each additional
1365 template NAME in the list, declare a keyboard macro or function (or
1366 interactive command) called 'sml-form-NAME'.
1367 If 'sml-form-NAME' is a function it takes no arguments and should
1368 insert the template at point\; if this is a command it may accept any
1369 sensible interactive call arguments\; keyboard macros can't take
1370 arguments at all.
1371 `sml-forms-alist' understands let, local, case, abstype, datatype,
1372 signature, structure, and functor by default.")
1373
1374 (defmacro sml-def-skeleton (name interactor &rest elements)
1375 (let ((fsym (intern (concat "sml-form-" name))))
1376 `(progn
1377 (add-to-list 'sml-forms-alist ',(cons name fsym))
1378 (define-abbrev sml-mode-abbrev-table ,name "" ',fsym nil 'system)
1379 (let ((abbrev (abbrev-symbol ,name sml-mode-abbrev-table)))
1380 (abbrev-put abbrev :case-fixed t)
1381 (abbrev-put abbrev :enable-function
1382 (lambda () (not (nth 8 (syntax-ppss))))))
1383 (define-skeleton ,fsym
1384 ,(format "SML-mode skeleton for `%s..' expressions" name)
1385 ,interactor
1386 ,(concat name " ") >
1387 ,@elements))))
1388 (put 'sml-def-skeleton 'lisp-indent-function 2)
1389
1390 (sml-def-skeleton "let" nil
1391 @ "\nin " > _ "\nend" >)
1392
1393 (sml-def-skeleton "if" nil
1394 @ " then " > _ "\nelse " > _)
1395
1396 (sml-def-skeleton "local" nil
1397 @ "\nin" > _ "\nend" >)
1398
1399 (sml-def-skeleton "case" "Case expr: "
1400 str "\nof " > _ " => ")
1401
1402 (sml-def-skeleton "signature" "Signature name: "
1403 str " =\nsig" > "\n" > _ "\nend" >)
1404
1405 (sml-def-skeleton "structure" "Structure name: "
1406 str " =\nstruct" > "\n" > _ "\nend" >)
1407
1408 (sml-def-skeleton "functor" "Functor name: "
1409 str " () : =\nstruct" > "\n" > _ "\nend" >)
1410
1411 (sml-def-skeleton "datatype" "Datatype name and type params: "
1412 str " =" \n)
1413
1414 (sml-def-skeleton "abstype" "Abstype name and type params: "
1415 str " =" \n _ "\nwith" > "\nend" >)
1416
1417 ;;
1418
1419 (sml-def-skeleton "struct" nil
1420 _ "\nend" >)
1421
1422 (sml-def-skeleton "sig" nil
1423 _ "\nend" >)
1424
1425 (sml-def-skeleton "val" nil
1426 @ " = " > _)
1427
1428 (sml-def-skeleton "fn" nil
1429 @ " =>" > _)
1430
1431 (sml-def-skeleton "fun" nil
1432 @ " =" > _)
1433
1434 ;;
1435
1436 (defun sml-forms-menu (_menu)
1437 (mapcar (lambda (x) (vector (car x) (cdr x) t))
1438 sml-forms-alist))
1439
1440 (defvar sml-last-form "let")
1441
1442 (defun sml-electric-space ()
1443 "Expand a symbol into an SML form, or just insert a space.
1444 If the point directly precedes a symbol for which an SML form exists,
1445 the corresponding form is inserted."
1446 (interactive)
1447 (let ((abbrev-mode (not abbrev-mode))
1448 (last-command-event ?\s)
1449 ;; Bind `this-command' to fool skeleton's special abbrev handling.
1450 (this-command 'self-insert-command))
1451 (call-interactively 'self-insert-command)))
1452
1453 (defun sml-insert-form (name newline)
1454 "Interactive short-cut to insert the NAME common SML form.
1455 If a prefix argument is given insert a NEWLINE and indent first, or
1456 just move to the proper indentation if the line is blank\; otherwise
1457 insert at point (which forces indentation to current column).
1458
1459 The default form to insert is 'whatever you inserted last time'
1460 \(just hit return when prompted\)\; otherwise the command reads with
1461 completion from `sml-forms-alist'."
1462 (interactive
1463 (list (completing-read
1464 (format "Form to insert (default %s): " sml-last-form)
1465 sml-forms-alist nil t nil nil sml-forms-alist)
1466 current-prefix-arg))
1467 (setq sml-last-form name)
1468 (unless (or (not newline)
1469 (save-excursion (beginning-of-line) (looking-at "\\s-*$")))
1470 (insert "\n"))
1471 (when (memq (char-syntax (preceding-char)) '(?_ ?w)) (insert " "))
1472 (let ((f (cdr (assoc name sml-forms-alist))))
1473 (cond
1474 ((commandp f) (command-execute f))
1475 (f (funcall f))
1476 (t (error "Undefined SML form: %s" name)))))
1477
1478 ;;;
1479 ;;; MLton support
1480 ;;;
1481
1482 (defvar sml-mlton-command "mlton"
1483 "Command to run MLton. Can include arguments.")
1484
1485 (defvar sml-mlton-mainfile nil)
1486
1487 (defconst sml-mlton-error-regexp-alist
1488 ;; I wish they just changed MLton to use one of the standard
1489 ;; error formats.
1490 `(("^\\(?:Error\\|\\(Warning\\)\\): \\(.+\\) \\([0-9]+\\)\\.\\([0-9]+\\)\\.$"
1491 2 3 4
1492 ;; If subgroup 1 matched, then it's a warning, otherwise it's an error.
1493 (1))))
1494
1495 (defvar compilation-error-regexp-alist)
1496 (eval-after-load "compile"
1497 '(dolist (x sml-mlton-error-regexp-alist)
1498 (add-to-list 'compilation-error-regexp-alist x)))
1499
1500 (defun sml-mlton-typecheck (mainfile)
1501 "Typecheck using MLton.
1502 MAINFILE is the top level file of the project."
1503 (interactive
1504 (list (if (and sml-mlton-mainfile (not current-prefix-arg))
1505 sml-mlton-mainfile
1506 (read-file-name "Main file: "))))
1507 (setq sml-mlton-mainfile mainfile)
1508 (save-some-buffers)
1509 (require 'compile)
1510 (dolist (x sml-mlton-error-regexp-alist)
1511 (add-to-list 'compilation-error-regexp-alist x))
1512 (with-current-buffer (find-file-noselect mainfile)
1513 (compile (concat sml-mlton-command
1514 " -stop tc " ;Stop right after type checking.
1515 (shell-quote-argument
1516 (file-relative-name buffer-file-name))))))
1517
1518 ;;;
1519 ;;; MLton's def-use info.
1520 ;;;
1521
1522 (defvar sml-defuse-file nil)
1523
1524 (defun sml-defuse-file ()
1525 (or sml-defuse-file (sml-defuse-set-file)))
1526
1527 (defun sml-defuse-set-file ()
1528 "Specify the def-use file to use."
1529 (interactive)
1530 (setq sml-defuse-file (read-file-name "Def-use file: ")))
1531
1532 (defun sml-defuse-symdata-at-point ()
1533 (save-excursion
1534 (sml-smie-forward-token)
1535 (let ((symname (sml-smie-backward-token)))
1536 (if (equal symname "op")
1537 (save-excursion (setq symname (sml-smie-forward-token))))
1538 (when (string-match "op " symname)
1539 (setq symname (substring symname (match-end 0)))
1540 (forward-word)
1541 (forward-comment (point-max)))
1542 (list symname
1543 ;; Def-use files seem to count chars, not columns.
1544 ;; We hope here that they don't actually count bytes.
1545 ;; Also they seem to start counting at 1.
1546 (1+ (- (point) (progn (beginning-of-line) (point))))
1547 (save-restriction
1548 (widen) (1+ (count-lines (point-min) (point))))
1549 buffer-file-name))))
1550
1551 (defconst sml-defuse-def-regexp
1552 "^[[:alpha:]]+ \\([^ \n]+\\) \\(.+\\) \\([0-9]+\\)\\.\\([0-9]+\\)$")
1553 (defconst sml-defuse-use-regexp-format "^ %s %d\\.%d $")
1554
1555 (defun sml-defuse-jump-to-def ()
1556 "Jump to the definition corresponding to the symbol at point."
1557 (interactive)
1558 (let ((symdata (sml-defuse-symdata-at-point)))
1559 (if (null (car symdata))
1560 (error "Not on a symbol")
1561 (with-current-buffer (find-file-noselect (sml-defuse-file))
1562 (goto-char (point-min))
1563 (unless (re-search-forward
1564 (format sml-defuse-use-regexp-format
1565 (concat "\\(?:"
1566 ;; May be an absolute file name.
1567 (regexp-quote (nth 3 symdata))
1568 "\\|"
1569 ;; Or a relative file name.
1570 (regexp-quote (file-relative-name
1571 (nth 3 symdata)))
1572 "\\)")
1573 (nth 2 symdata)
1574 (nth 1 symdata))
1575 nil t)
1576 ;; FIXME: This is typically due to editing: any minor editing will
1577 ;; mess everything up. We should try to fail more gracefully.
1578 (error "Def-use info not found"))
1579 (unless (re-search-backward sml-defuse-def-regexp nil t)
1580 ;; This indicates a bug in this code.
1581 (error "Internal failure while looking up def-use"))
1582 (unless (equal (match-string 1) (nth 0 symdata))
1583 ;; FIXME: This again is most likely due to editing.
1584 (error "Incoherence in the def-use info found"))
1585 (let ((line (string-to-number (match-string 3)))
1586 (char (string-to-number (match-string 4))))
1587 (pop-to-buffer (find-file-noselect (match-string 2)))
1588 (goto-char (point-min))
1589 (forward-line (1- line))
1590 (forward-char (1- char)))))))
1591
1592 ;;;
1593 ;;; SML/NJ's Compilation Manager support
1594 ;;;
1595
1596 (defvar sml-cm-mode-syntax-table sml-mode-syntax-table)
1597 (defvar sml-cm-font-lock-keywords
1598 `(,(concat "\\_<" (regexp-opt '("library" "group" "is" "structure"
1599 "functor" "signature" "funsig") t)
1600 "\\_>")))
1601 ;;;###autoload
1602 (add-to-list 'completion-ignored-extensions ".cm/")
1603 ;; This was used with the old compilation manager.
1604 (add-to-list 'completion-ignored-extensions "CM/")
1605 ;;;###autoload
1606 (add-to-list 'auto-mode-alist '("\\.cm\\'" . sml-cm-mode))
1607 ;;;###autoload
1608 (define-derived-mode sml-cm-mode fundamental-mode "SML-CM"
1609 "Major mode for SML/NJ's Compilation Manager configuration files."
1610 (set (make-local-variable 'sml-prog-proc-descriptor) sml-pp-functions)
1611 (set (make-local-variable 'font-lock-defaults)
1612 '(sml-cm-font-lock-keywords nil t nil nil)))
1613
1614 ;;;
1615 ;;; ML-Lex support
1616 ;;;
1617
1618 (defvar sml-lex-font-lock-keywords
1619 (append
1620 `((,(concat "^%" sml-id-re) . font-lock-builtin-face)
1621 ("^%%" . font-lock-module-def-face))
1622 sml-font-lock-keywords))
1623 (defconst sml-lex-font-lock-defaults
1624 (cons 'sml-lex-font-lock-keywords (cdr sml-font-lock-defaults)))
1625
1626 ;;;###autoload
1627 (define-derived-mode sml-lex-mode sml-mode "SML-Lex"
1628 "Major Mode for editing ML-Lex files."
1629 (set (make-local-variable 'font-lock-defaults) sml-lex-font-lock-defaults))
1630
1631 ;;;
1632 ;;; ML-Yacc support
1633 ;;;
1634
1635 (defface sml-yacc-bnf-face
1636 '((t (:foreground "darkgreen")))
1637 "Face used to highlight (non)terminals in `sml-yacc-mode'.")
1638 (defvar sml-yacc-bnf-face 'sml-yacc-bnf-face)
1639
1640 (defcustom sml-yacc-indent-action 16
1641 "Indentation column of the opening paren of actions."
1642 :type 'integer)
1643
1644 (defcustom sml-yacc-indent-pipe nil
1645 "Indentation column of the pipe char in the BNF.
1646 If nil, align it with `:' or with previous cases."
1647 :type 'integer)
1648
1649 (defcustom sml-yacc-indent-term nil
1650 "Indentation column of the (non)term part.
1651 If nil, align it with previous cases."
1652 :type 'integer)
1653
1654 (defvar sml-yacc-font-lock-keywords
1655 (cons `((concat "^\\(" sml-id-re "\\s-*:\\|\\s-*|\\)\\(\\s-*" sml-id-re
1656 "\\)*\\s-*\\(\\(%" sml-id-re "\\)\\s-+" sml-id-re "\\|\\)")
1657 (0 (save-excursion
1658 (save-match-data
1659 (goto-char (match-beginning 0))
1660 (unless (or (re-search-forward "\\_<of\\_>"
1661 (match-end 0) 'move)
1662 (progn (forward-comment (point-max))
1663 (not (looking-at "("))))
1664 sml-yacc-bnf-face))))
1665 (4 font-lock-builtin-face t t))
1666 sml-lex-font-lock-keywords))
1667 (defconst sml-yacc-font-lock-defaults
1668 (cons 'sml-yacc-font-lock-keywords (cdr sml-font-lock-defaults)))
1669
1670 (defun sml-yacc-indent-line ()
1671 "Indent current line of ML-Yacc code."
1672 (let ((savep (> (current-column) (current-indentation)))
1673 (indent (max (or (ignore-errors (sml-yacc-indentation)) 0) 0)))
1674 (if savep
1675 (save-excursion (indent-line-to indent))
1676 (indent-line-to indent))))
1677
1678 (defun sml-yacc-indentation ()
1679 (save-excursion
1680 (back-to-indentation)
1681 (or (and (looking-at (eval-when-compile
1682 (concat "%\\|" sml-id-re "\\s-*:")))
1683 0)
1684 (when (save-excursion
1685 (condition-case nil (progn (up-list -1) nil) (scan-error t)))
1686 ;; We're outside an action.
1687 (cond
1688 ;; Special handling of indentation inside %term and %nonterm
1689 ((save-excursion
1690 (and (re-search-backward "^%\\(\\sw+\\)" nil t)
1691 (member (match-string 1) '("term" "nonterm"))))
1692 (if (numberp sml-yacc-indent-term) sml-yacc-indent-term
1693 (let ((offset (if (looking-at "|") -2 0)))
1694 (forward-line -1)
1695 (looking-at "\\s-*\\(%\\sw*\\||\\)?\\s-*")
1696 (goto-char (match-end 0))
1697 (+ offset (current-column)))))
1698 ((looking-at "(") sml-yacc-indent-action)
1699 ((looking-at "|")
1700 (if (numberp sml-yacc-indent-pipe) sml-yacc-indent-pipe
1701 (backward-sexp 1)
1702 (while (progn (forward-comment (- (point)))
1703 (/= 0 (skip-syntax-backward "w_"))))
1704 (forward-comment (- (point)))
1705 (if (not (looking-at "\\s-$"))
1706 (1- (current-column))
1707 (skip-syntax-forward " ")
1708 (- (current-column) 2))))))
1709 ;; default to SML rules
1710 (smie-indent-calculate))))
1711
1712 ;;;###autoload
1713 (add-to-list 'auto-mode-alist '("\\.grm\\'" . sml-yacc-mode))
1714 ;;;###autoload
1715 (define-derived-mode sml-yacc-mode sml-mode "SML-Yacc"
1716 "Major Mode for editing ML-Yacc files."
1717 (set (make-local-variable 'indent-line-function) 'sml-yacc-indent-line)
1718 (set (make-local-variable 'font-lock-defaults) sml-yacc-font-lock-defaults))
1719
1720 \f
1721 (provide 'sml-mode)
1722
1723 ;;; sml-mode.el ends here