1 ;;; sml-mode.el --- Major mode for editing (Standard) ML -*- lexical-binding: t; coding: utf-8 -*-
3 ;; Copyright (C) 1989,1999,2000,2004,2007,2010-2013 Free Software Foundation, Inc.
5 ;; Maintainer: (Stefan Monnier) <monnier@iro.umontreal.ca>
8 ;; Author: Lars Bo Nielsen
12 ;; Matthew Morley <mjm@scs.leeds.ac.uk>
13 ;; Matthias Blume <blume@cs.princeton.edu>
14 ;; (Stefan Monnier) <monnier@iro.umontreal.ca>
16 ;; This file is part of GNU Emacs.
18 ;; GNU Emacs is free software: you can redistribute it and/or modify
19 ;; it under the terms of the GNU General Public License as published by
20 ;; the Free Software Foundation, either version 3 of the License, or
21 ;; (at your option) any later version.
23 ;; GNU Emacs is distributed in the hope that it will be useful,
24 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
25 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 ;; GNU General Public License for more details.
28 ;; You should have received a copy of the GNU General Public License
29 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
33 ;; A major mode to edit Standard ML (SML) code.
34 ;; Provides the following features, among others:
36 ;; - Syntax highlighting.
37 ;; - Prettified display of ->, =>, fn, ...
39 ;; - which-function-mode.
40 ;; - Skeletons/templates.
41 ;; - Electric pipe key.
42 ;; - outline-minor-mode (with some known problems).
43 ;; - Interaction with a read-eval-print loop.
47 ;; - Indentation after "functor toto() where type foo = bar ="
48 ;; Because the last is treated as an equality comparison.
49 ;; - indentation of a declaration after a long `datatype' can be slow.
53 ;;;;; Changes since 5.0:
55 ;; - sml-electric-pipe-mode to make the | key electric.
56 ;; - Removal of a lot of compatibility code. Requires Emacs-24.
57 ;; - Integrate in GNU ELPA.
59 ;;;;; Changes since 4.1:
61 ;; - New indentation code using SMIE when available.
62 ;; - `sml-back-to-outer-indent' is now on S-tab (aka `backtab') rather
64 ;; - Support for electric-layout-mode and electric-indent-mode.
65 ;; - `sml-mark-defun' tries to be more clever.
66 ;; - A single file (sml-mode.el) is needed unless you want to use an
67 ;; interactive process like SML/NJ, or if your Emacs does not provide SMIE.
69 ;;;;; Changes since 4.0:
71 ;; - Switch to GPLv3+.
72 ;; - When possible (i.e. running under Emacs>=23), be case-sensitive when
73 ;; expanding abbreviations, and don't expand them in comments and strings.
74 ;; - When you `next-error' to a type error, highlight the actual parts of the
76 ;; - Flush the recorded errors not only upon sml-compile and friends, but also
77 ;; when typing commands directly at the prompt.
78 ;; - New command sml-mlton-typecheck.
79 ;; - Simple support to parse errors and warnings in MLton's output.
80 ;; - Simple support for MLton's def-use files.
82 ;;;;; Changes since 3.9.5:
84 ;; - No need to add the dir to your load-path any more.
85 ;; The sml-mode-startup.el file does it for you.
86 ;; - Symbols like -> can be displayed as real arrows.
87 ;; See sml-font-lock-symbols.
88 ;; - Fix some incompatibilities with the upcoming Emacs-21.4.
89 ;; - Indentation rules improved. New customizable variable
90 ;; `sml-rightalign-and'. Also `sml-symbol-indent' is now customizable.
92 ;;;;; Changes since 3.9.3:
94 ;; - New add-log support (try C-x 4 a from within an SML function).
96 ;; - sml-bindings has disappeared.
97 ;; - The code skeletons are now abbrevs as well.
98 ;; - A new *sml* process is sent the content of sml-config-file
99 ;; (~/.sml-proc.sml) if it exists.
100 ;; - `sml-compile' works yet a bit differently. The command can begin
101 ;; with `cd "path";' and it will be replaced by OS.FileSys.chDir.
102 ;; - run-sml now pops up the new buffer. It can also run the command on
103 ;; another machine. And it always prompts for the command name.
104 ;; Use a prefix argument if you want to give args or to specify a host on
105 ;; which to run the command.
106 ;; - mouse-2 to yank in *sml* should work again (but won't work for next-error
108 ;; - New major-modes sml-cm-mode, sml-lex-mode and sml-yacc-mode.
109 ;; - sml-load-hook has disappeared as has inferior-sml-load-hook.
110 ;; - sml-mode-startup.el is now automatically generated and you're supposed to
111 ;; `load' it from .emacs or site-start.el.
112 ;; - Minor bug fixes.
116 (eval-when-compile (require 'cl))
117 (require 'smie nil 'noerror)
124 (defcustom sml-indent-level 4
125 "Basic indentation step for SML code."
128 (defcustom sml-indent-args sml-indent-level
129 "Indentation of args placed on a separate line."
132 (defcustom sml-rightalign-and t
133 "If non-nil, right-align `and' with its leader.
135 datatype a = A datatype a = A
139 (defcustom sml-electric-pipe-mode t
140 "If non-nil, automatically insert appropriate template when hitting |."
143 (defvar sml-mode-hook nil
144 "Run upon entering `sml-mode'.
145 This is a good place to put your preferred key bindings.")
149 (defvar sml-outline-regexp
150 ;; `st' and `si' are to match structure and signature.
151 "
\f\\|s[ti]\\|[ \t]*\\(let[ \t]+\\)?\\(fun\\|and\\)\\_>"
152 "Regexp matching a major heading.
153 This actually can't work without extending `outline-minor-mode' with the
154 notion of \"the end of an outline\".")
161 (let ((map (make-sparse-keymap)))
162 ;; Text-formatting commands:
163 (define-key map "\C-c\C-m" 'sml-insert-form)
164 (define-key map "\M-|" 'sml-electric-pipe)
165 (define-key map "\M-\ " 'sml-electric-space)
166 (define-key map [backtab] 'sml-back-to-outer-indent)
167 ;; The standard binding is C-c C-z, but we add this one for compatibility.
168 (define-key map "\C-c\C-s" 'sml-prog-proc-switch-to)
170 "The keymap used in `sml-mode'.")
172 (defvar sml-mode-syntax-table
173 (let ((st (make-syntax-table)))
174 (modify-syntax-entry ?\* ". 23n" st)
175 (modify-syntax-entry ?\( "()1" st)
176 (modify-syntax-entry ?\) ")(4" st)
177 (mapc (lambda (c) (modify-syntax-entry c "_" st)) "._'")
178 (mapc (lambda (c) (modify-syntax-entry c "." st)) ",;")
179 ;; `!' is not really a prefix-char, oh well!
180 (mapc (lambda (c) (modify-syntax-entry c "'" st)) "~#!")
181 (mapc (lambda (c) (modify-syntax-entry c "." st)) "%&$+-/:<=>?@`^|")
183 "The syntax table used in `sml-mode'.")
186 (easy-menu-define sml-mode-menu sml-mode-map "Menu used in `sml-mode'."
189 ["Start SML repl" sml-run t]
191 ["Compile the project" sml-prog-proc-compile t]
192 ["Send file" sml-prog-proc-load-file t]
193 ["Switch to SML repl" sml-prog-proc-switch-to t]
195 ["Send buffer" sml-prog-proc-send-buffer t]
196 ["Send region" sml-prog-proc-send-region t]
197 ["Send function" sml-send-function t]
198 ["Goto next error" next-error t])
199 ["Insert SML form" sml-insert-form t]
200 ("Forms" :filter sml-forms-menu)
201 ["Indent region" indent-region t]
202 ["Outdent line" sml-back-to-outer-indent t]
204 ["Customize SML-mode" (customize-group 'sml) t]
205 ["SML mode help" describe-mode t]))
211 (defun sml-syms-re (syms)
212 (concat "\\_<" (regexp-opt syms t) "\\_>"))
216 (defconst sml-module-head-syms
217 '("signature" "structure" "functor" "abstraction"))
220 (defconst sml-=-starter-syms
221 (list* "|" "val" "fun" "and" "datatype" "type" "abstype" "eqtype"
222 sml-module-head-syms)
223 "Symbols that can be followed by a `='.")
224 (defconst sml-=-starter-re
225 (concat "\\S.|\\S.\\|" (sml-syms-re (cdr sml-=-starter-syms)))
226 "Symbols that can be followed by a `='.")
228 (defconst sml-non-nested-of-starter-re
229 (sml-syms-re '("datatype" "abstype" "exception"))
230 "Symbols that can introduce an `of' that shouldn't behave like a paren.")
232 (defconst sml-starters-syms
233 (append sml-module-head-syms
234 '("abstype" "datatype" "exception" "fun"
235 "local" "infix" "infixr" "sharing" "nonfix"
236 "open" "type" "val" "and"
238 "The starters of new expressions.")
240 (defconst sml-pipeheads
241 '("|" "of" "fun" "fn" "and" "handle" "datatype" "abstype"
243 "A `|' corresponds to one of these.")
245 (defconst sml-keywords-regexp
246 (sml-syms-re '("abstraction" "abstype" "and" "andalso" "as" "before" "case"
247 "datatype" "else" "end" "eqtype" "exception" "do" "fn"
248 "fun" "functor" "handle" "if" "in" "include" "infix"
249 "infixr" "let" "local" "nonfix" "o" "of" "op" "open" "orelse"
250 "overload" "raise" "rec" "sharing" "sig" "signature"
251 "struct" "structure" "then" "type" "val" "where" "while"
253 "A regexp that matches any and all keywords of SML.")
256 (defconst sml-id-re "\\sw\\(?:\\sw\\|\\s_\\)*"))
258 (defconst sml-tyvarseq-re
259 (concat "\\(?:\\(?:'+" sml-id-re "\\|(\\(?:[,']\\|" sml-id-re
260 "\\|\\s-\\)+)\\)\\s-+\\)?"))
262 ;;; Font-lock settings ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
264 (defcustom sml-font-lock-symbols nil
265 "Display \\ and -> and such using symbols in fonts.
266 This may sound like a neat trick, but be extra careful: it changes the
267 alignment and can thus lead to nasty surprises w.r.t layout."
270 (defconst sml-font-lock-symbols-alist
272 ("andalso" . ?∧) ;; ?⋀
273 ("orelse" . ?∨) ;; ?⋁
287 ;; Some greek letters for type parameters.
294 (defun sml-font-lock-compose-symbol ()
295 "Compose a sequence of ascii chars into a symbol.
296 Regexp match data 0 points to the chars."
297 ;; Check that the chars should really be composed into a symbol.
298 (let* ((start (match-beginning 0))
300 (syntaxes (if (eq (char-syntax (char-after start)) ?w)
302 (if (or (memq (char-syntax (or (char-before start) ?\ )) syntaxes)
303 (memq (char-syntax (or (char-after end) ?\ )) syntaxes)
304 (memq (get-text-property start 'face)
305 '(font-lock-doc-face font-lock-string-face
306 font-lock-comment-face)))
307 ;; No composition for you. Let's actually remove any composition
308 ;; we may have added earlier and which is now incorrect.
309 (remove-text-properties start end '(composition))
310 ;; That's a symbol alright, so add the composition.
311 (compose-region start end (cdr (assoc (match-string 0)
312 sml-font-lock-symbols-alist)))))
313 ;; Return nil because we're not adding any face property.
316 (defun sml-font-lock-symbols-keywords ()
317 (when sml-font-lock-symbols
318 `((,(regexp-opt (mapcar 'car sml-font-lock-symbols-alist) t)
319 (0 (sml-font-lock-compose-symbol))))))
321 ;; The font lock regular expressions.
323 (defconst sml-font-lock-keywords
324 `(;;(sml-font-comments-and-strings)
325 (,(concat "\\_<\\(fun\\|and\\)\\s-+" sml-tyvarseq-re
326 "\\(" sml-id-re "\\)\\s-+[^ \t\n=]")
327 (1 font-lock-keyword-face)
328 (2 font-lock-function-name-face))
329 (,(concat "\\_<\\(\\(?:data\\|abs\\|with\\|eq\\)?type\\)\\s-+"
330 sml-tyvarseq-re "\\(" sml-id-re "\\)")
331 (1 font-lock-keyword-face)
332 (2 font-lock-type-def-face))
333 (,(concat "\\_<\\(val\\)\\s-+\\(?:" sml-id-re "\\_>\\s-*\\)?\\("
334 sml-id-re "\\)\\s-*[=:]")
335 (1 font-lock-keyword-face)
336 (2 font-lock-variable-name-face))
337 (,(concat "\\_<\\(structure\\|functor\\|abstraction\\)\\s-+\\("
339 (1 font-lock-keyword-face)
340 (2 font-lock-module-def-face))
341 (,(concat "\\_<\\(signature\\)\\s-+\\(" sml-id-re "\\)")
342 (1 font-lock-keyword-face)
343 (2 font-lock-interface-def-face))
345 (,sml-keywords-regexp . font-lock-keyword-face)
346 ,@(sml-font-lock-symbols-keywords))
347 "Regexps matching standard SML keywords.")
349 (defface font-lock-type-def-face
351 "Font Lock mode face used to highlight type definitions."
352 :group 'font-lock-highlighting-faces)
353 (defvar font-lock-type-def-face 'font-lock-type-def-face
354 "Face name to use for type definitions.")
356 (defface font-lock-module-def-face
358 "Font Lock mode face used to highlight module definitions."
359 :group 'font-lock-highlighting-faces)
360 (defvar font-lock-module-def-face 'font-lock-module-def-face
361 "Face name to use for module definitions.")
363 (defface font-lock-interface-def-face
365 "Font Lock mode face used to highlight interface definitions."
366 :group 'font-lock-highlighting-faces)
367 (defvar font-lock-interface-def-face 'font-lock-interface-def-face
368 "Face name to use for interface definitions.")
371 ;; Code to handle nested comments and unusual string escape sequences
374 (defvar sml-syntax-prop-table
375 (let ((st (make-syntax-table)))
376 (modify-syntax-entry ?\\ "." st)
377 (modify-syntax-entry ?* "." st)
379 "Syntax table for text-properties.")
381 (defconst sml-font-lock-syntactic-keywords
382 `(("^\\s-*\\(\\\\\\)" (1 ',sml-syntax-prop-table))))
384 (defconst sml-font-lock-defaults
385 '(sml-font-lock-keywords nil nil nil nil
386 (font-lock-syntactic-keywords . sml-font-lock-syntactic-keywords)))
389 ;;; Indentation with SMIE
391 (defconst sml-smie-grammar
392 ;; We have several problem areas where SML's syntax can't be handled by an
393 ;; operator precedence grammar:
395 ;; "= A before B" is "= A) before B" if this is the
396 ;; `boolean-=' but it is "= (A before B)" if it's the `definitional-='.
397 ;; We can work around the problem by tweaking the lexer to return two
398 ;; different tokens for the two different kinds of `='.
399 ;; "of A | B" in a "case" we want "of (A | B, but in a `datatype'
400 ;; we want "of A) | B".
401 ;; "= A | B" can be "= A ) | B" if the = is from a "fun" definition,
402 ;; but it is "= (A | B" if it is a `datatype' definition (of course, if
403 ;; the previous token introducing the = is `and', deciding whether
404 ;; it's a datatype or a function requires looking even further back).
405 ;; "functor foo (...) where type a = b = ..." the first `=' looks very much
406 ;; like a `definitional-=' even tho it's just an equality constraint.
407 ;; Currently I don't even try to handle `where' at all.
411 '((exp ("if" exp "then" exp "else" exp)
412 ("case" exp "of" branches)
413 ("let" decls "in" cmds "end")
414 ("struct" decls "end")
417 (sexp "handle" branches)
418 ("fn" sexp "=>" exp))
419 ;; "simple exp"s are the ones that can appear to the left of `handle'.
420 (sexp (sexp ":" type) ("(" exps ")")
423 (sexp "andalso" sexp))
424 (cmds (cmds ";" cmds) (exp))
425 (exps (exps "," exps) (exp)) ; (exps ";" exps)
426 (branches (sexp "=>" exp) (branches "|" branches))
427 ;; Operator precedence grammars handle separators much better then
428 ;; starters/terminators, so let's pretend that let/fun are separators.
429 (decls (sexp "d=" exp)
430 (sexp "d=" databranches)
431 (funbranches "|" funbranches)
432 (sexp "=of" type) ;After "exception".
433 ;; FIXME: Just like PROCEDURE in Pascal and Modula-2, this
434 ;; interacts poorly with the other constructs since I
435 ;; can't make "local" a separator like fun/val/type/...
436 ("local" decls "in" decls "end")
437 ;; (decls "local" decls "in" decls "end")
438 (decls "functor" decls)
439 (decls "signature" decls)
440 (decls "structure" decls)
444 (decls "infix" decls)
445 (decls "infixr" decls)
446 (decls "nonfix" decls)
447 (decls "abstype" decls)
448 (decls "datatype" decls)
449 (decls "exception" decls)
452 (type (type "->" type)
454 (funbranches (sexp "d=" exp))
455 (databranches (sexp "=of" type) (databranches "d|" databranches))
457 ;; (mexp ("functor" marg "d=" mexp)
458 ;; ("structure" marg "d=" mexp)
459 ;; ("signature" marg "d=" mexp))
460 (marg (marg ":" type) (marg ":>" type))
461 (toplevel (decls) (exp) (toplevel ";" toplevel)))
462 ;; '(("local" . opener))
463 ;; '((nonassoc "else") (right "handle"))
464 '((nonassoc "of") (assoc "|")) ; "case a of b => case c of d => e | f"
465 '((nonassoc "handle") (assoc "|")) ; Idem for "handle".
466 '((assoc "->") (assoc "*"))
467 '((assoc "val" "fun" "type" "datatype" "abstype" "open" "infix" "infixr"
468 "nonfix" "functor" "signature" "structure" "exception"
472 '((assoc "orelse") (assoc "andalso") (nonassoc ":"))
473 '((assoc ";")) '((assoc ",")) '((assoc "d|")))
476 '((nonassoc "andalso") ;To anchor the prec-table.
479 (nonassoc ">" ">=" "<>" "<" "<=" "=") ;4
481 (assoc "+" "-" "^") ;6
482 (assoc "/" "*" "quot" "rem" "div" "mod") ;7
483 (nonassoc " -dummy- "))) ;Bogus anchor at the end.
486 (defvar sml-indent-separator-outdent 2)
488 (defun sml-smie-rules (kind token)
489 ;; I much preferred the pcase version of the code, especially while
490 ;; edebugging the code. But that will have to wait until we get rid of
491 ;; support for Emacs-23.
494 (basic sml-indent-level)
495 (args sml-indent-args)))
496 (:list-intro (member token '("fn")))
499 ((equal token "struct") 0)
500 ((equal token "=>") (if (smie-rule-hanging-p) 0 2))
501 ((equal token "in") (if (smie-rule-parent-p "local") 0))
502 ((equal token "of") 3)
503 ((member token '("(" "{" "[")) (if (not (smie-rule-hanging-p)) 2))
504 ((equal token "else") (if (smie-rule-hanging-p) 0)) ;; (:next "if" 0)
505 ((member token '("|" "d|" ";" ",")) (smie-rule-separator kind))
507 (if (and (smie-rule-parent-p "val") (smie-rule-next-p "fn")) -3))))
510 ((equal token "=>") (if (smie-rule-parent-p "fn") 3))
511 ((equal token "of") 1)
512 ;; In case the language is extended to allow a | directly after of.
513 ((and (equal token "|") (smie-rule-prev-p "of")) 1)
514 ((member token '("|" "d|" ";" ",")) (smie-rule-separator kind))
515 ;; Treat purely syntactic block-constructs as being part of their parent,
516 ;; when the opening statement is hanging.
517 ((member token '("let" "(" "[" "{"))
518 (if (smie-rule-hanging-p) (smie-rule-parent)))
519 ;; Treat if ... else if ... as a single long syntactic construct.
520 ;; Similarly, treat fn a => fn b => ... as a single construct.
521 ((member token '("if" "fn"))
522 (and (not (smie-rule-bolp))
523 (smie-rule-prev-p (if (equal token "if") "else" "=>"))
526 ;; FIXME: maybe "and" (c|sh)ould be handled as an smie-separator.
528 ((smie-rule-parent-p "datatype") (if sml-rightalign-and 5 0))
529 ((smie-rule-parent-p "fun" "val") 0)))
532 ((smie-rule-parent-p "datatype") (if (smie-rule-bolp) 2))
533 ((smie-rule-parent-p "structure" "signature") 0)))
534 ;; Indent an expression starting with "local" as if it were starting
536 ((equal token "local") (smie-indent-keyword "fun"))
537 ;; FIXME: type/val/fun/... are separators but "local" is not, even though
538 ;; it appears in the same list. Try to fix up the problem by hand.
539 ;; ((or (equal token "local")
540 ;; (equal (cdr (assoc token smie-grammar))
541 ;; (cdr (assoc "fun" smie-grammar))))
542 ;; (let ((parent (save-excursion (smie-backward-sexp))))
543 ;; (when (or (and (equal (nth 2 parent) "local")
544 ;; (null (car parent)))
546 ;; (setq parent (save-excursion (smie-backward-sexp "fun")))
547 ;; (eq (car parent) (nth 1 (assoc "fun" smie-grammar)))))
548 ;; (goto-char (nth 1 parent))
549 ;; (cons 'column (smie-indent-virtual)))))
552 (defun sml-smie-definitional-equal-p ()
553 "Figure out which kind of \"=\" this is.
554 Assumes point is right before the = sign."
555 ;; The idea is to look backward for the first occurrence of a token that
556 ;; requires a definitional "=" and then see if there's such a definitional
557 ;; equal between that token and ourselves (in which case we're not
558 ;; a definitional = ourselves).
559 ;; The "search for =" is naive and will match "=>" and "<=", but it turns
560 ;; out to be OK in practice because such tokens very rarely (if ever) appear
561 ;; between the =-starter and the corresponding definitional equal.
562 ;; One known problem case is code like:
563 ;; "functor foo (structure s : S) where type t = s.t ="
564 ;; where the "type t = s.t" is mistaken for a type definition.
565 (let ((re (concat "\\(" sml-=-starter-re "\\)\\|=")))
567 (and (re-search-backward re nil t)
568 (or (match-beginning 1)
569 ;; If we first hit a "=", then that = is probably definitional
570 ;; and we're an equality, but not necessarily. One known
571 ;; problem case is code like:
572 ;; "functor foo (structure s : S) where type t = s.t ="
573 ;; where the first = is more like an equality (tho it doesn't
574 ;; matter much) and the second is definitional.
576 ;; FIXME: The test below could be used to recognize that the
577 ;; second = is not a mere equality, but that's not enough to
578 ;; parse the construct properly: we'd need something
579 ;; like a third kind of = token for structure definitions, in
580 ;; order for the parser to be able to skip the "type t = s.t"
581 ;; as a sub-expression.
583 ;; (and (not (looking-at "=>"))
584 ;; (not (eq ?< (char-before))) ;Not a <=
585 ;; (re-search-backward re nil t)
586 ;; (match-beginning 1)
587 ;; (equal "type" (buffer-substring (- (match-end 1) 4)
591 (defun sml-smie-non-nested-of-p ()
592 ;; FIXME: Maybe datatype-|-p makes this nested-of business unnecessary.
593 "Figure out which kind of \"of\" this is.
594 Assumes point is right before the \"of\" symbol."
596 (and (re-search-backward (concat "\\(" sml-non-nested-of-starter-re
597 "\\)\\|\\_<case\\_>") nil t)
598 (match-beginning 1))))
600 (defun sml-smie-datatype-|-p ()
601 "Figure out which kind of \"|\" this is.
602 Assumes point is right before the | symbol."
604 (forward-char 1) ;Skip the |.
605 (let ((after-type-def
606 '("|" "of" "in" "datatype" "and" "exception" "abstype" "infix"
607 "infixr" "nonfix" "local" "val" "fun" "structure" "functor"
609 (or (member (sml-smie-forward-token-1) after-type-def) ;Skip the tag.
610 (member (sml-smie-forward-token-1) after-type-def)))))
612 (defun sml-smie-forward-token-1 ()
613 (forward-comment (point-max))
614 (buffer-substring-no-properties
617 (or (/= 0 (skip-syntax-forward "'w_"))
618 (skip-syntax-forward ".'"))
621 (defun sml-smie-forward-token ()
622 (let ((sym (sml-smie-forward-token-1)))
625 (concat "op " (sml-smie-forward-token-1)))
626 ((member sym '("|" "of" "="))
627 ;; The important lexer for indentation's performance is the backward
628 ;; lexer, so for the forward lexer we delegate to the backward one.
629 (save-excursion (sml-smie-backward-token)))
632 (defun sml-smie-backward-token-1 ()
633 (forward-comment (- (point)))
634 (buffer-substring-no-properties
637 (or (/= 0 (skip-syntax-backward ".'"))
638 (skip-syntax-backward "'w_"))
641 (defun sml-smie-backward-token ()
642 (let ((sym (sml-smie-backward-token-1)))
643 (unless (zerop (length sym))
644 ;; FIXME: what should we do if `sym' = "op" ?
645 (let ((point (point)))
646 (if (equal "op" (sml-smie-backward-token-1))
650 ((string= sym "=") (if (sml-smie-definitional-equal-p) "d=" "="))
651 ((string= sym "of") (if (sml-smie-non-nested-of-p) "=of" "of"))
652 ((string= sym "|") (if (sml-smie-datatype-|-p) "d|" "|"))
659 (defvar sml-imenu-regexp
660 (concat "^[ \t]*\\(let[ \t]+\\)?"
661 (regexp-opt (append sml-module-head-syms
662 '("and" "fun" "datatype" "abstype" "type")) t)
665 (defun sml-imenu-create-index ()
667 (goto-char (point-max))
668 (while (re-search-backward sml-imenu-regexp nil t)
670 (let ((kind (match-string 2))
671 (column (progn (goto-char (match-beginning 2)) (current-column)))
673 (progn (goto-char (match-end 0))
674 (forward-comment (point-max))
675 (when (looking-at sml-tyvarseq-re)
676 (goto-char (match-end 0)))
678 (name (sml-smie-forward-token)))
679 ;; Eliminate trivial renamings.
680 (when (or (not (member kind '("structure" "signature")))
681 (progn (search-forward "=")
682 (forward-comment (point-max))
683 (looking-at "sig\\|struct")))
684 (push (cons (concat (make-string (/ column 2) ?\ ) name) location)
688 ;;; Generic prog-proc interaction.
693 (defvar sml-prog-proc-mode-map
694 (let ((map (make-sparse-keymap)))
695 (define-key map [?\C-c ?\C-l] 'sml-prog-proc-load-file)
696 (define-key map [?\C-c ?\C-c] 'sml-prog-proc-compile)
697 (define-key map [?\C-c ?\C-z] 'sml-prog-proc-switch-to)
698 (define-key map [?\C-c ?\C-r] 'sml-prog-proc-send-region)
699 (define-key map [?\C-c ?\C-b] 'sml-prog-proc-send-buffer)
701 ;; (define-key map [?\M-C-x] 'sml-prog-proc-send-defun)
702 ;; (define-key map [?\C-x ?\C-e] 'sml-prog-proc-send-last-sexp)
703 ;; FIXME: Add menu. Now, that's trickier because keymap inheritance
704 ;; doesn't play nicely with menus!
706 "Keymap for `sml-prog-proc-mode'.")
708 (defvar sml-prog-proc--buffer nil
709 "The inferior-process buffer to which to send code.")
710 (make-variable-buffer-local 'sml-prog-proc--buffer)
712 (defstruct (sml-prog-proc-descriptor
713 (:constructor sml-prog-proc-make)
716 (name nil :read-only t)
717 (run nil :read-only t)
718 (load-cmd nil :read-only t)
719 (chdir-cmd nil :read-only t)
720 (command-eol "\n" :read-only t)
721 (compile-commands-alist nil :read-only t))
723 (defvar sml-prog-proc-descriptor nil
724 "Struct containing the various functions to create a new process, ...")
726 (defmacro sml-prog-proc--prop (prop)
727 `(,(intern (format "sml-prog-proc-descriptor-%s" prop))
728 (or sml-prog-proc-descriptor
729 ;; FIXME: Look for available ones and pick one.
730 (error "Not a `sml-prog-proc' buffer"))))
731 (defmacro sml-prog-proc--call (method &rest args)
732 `(funcall (sml-prog-proc--prop ,method) ,@args))
734 ;; The inferior process and his buffer are basically interchangeable.
735 ;; Currently the code takes sml-prog-proc--buffer as the main reference,
736 ;; but all users should either use sml-prog-proc-proc or sml-prog-proc-buffer
739 (defun sml-prog-proc-proc ()
740 "Return the inferior process for the code in current buffer."
741 (or (and (buffer-live-p sml-prog-proc--buffer)
742 (get-buffer-process sml-prog-proc--buffer))
743 (when (derived-mode-p 'sml-prog-proc-mode 'sml-prog-proc-comint-mode)
744 (setq sml-prog-proc--buffer (current-buffer))
745 (get-buffer-process sml-prog-proc--buffer))
746 (let ((ppd sml-prog-proc-descriptor)
747 (buf (sml-prog-proc--call run)))
748 (with-current-buffer buf
749 (if (and ppd (null sml-prog-proc-descriptor))
750 (set (make-local-variable 'sml-prog-proc-descriptor) ppd)))
751 (setq sml-prog-proc--buffer buf)
752 (get-buffer-process sml-prog-proc--buffer))))
754 (defun sml-prog-proc-buffer ()
755 "Return the buffer of the inferior process."
756 (process-buffer (sml-prog-proc-proc)))
758 (defun sml-prog-proc-switch-to ()
759 "Switch to the buffer running the read-eval-print process."
761 (pop-to-buffer (sml-prog-proc-buffer)))
763 (defun sml-prog-proc-send-string (proc str)
764 "Send command STR to PROC, with an EOL terminator appended."
765 (with-current-buffer (process-buffer proc)
766 ;; FIXME: comint-send-string does not pass the string through
767 ;; comint-input-filter-function, so we have to do it by hand.
768 ;; Maybe we should insert the command into the buffer and then call
769 ;; comint-send-input?
770 (sml-prog-proc-comint-input-filter-function nil)
771 (comint-send-string proc (concat str (sml-prog-proc--prop command-eol)))))
773 (defun sml-prog-proc-load-file (file &optional and-go)
774 "Load FILE into the read-eval-print process.
775 FILE is the file visited by the current buffer.
776 If prefix argument AND-GO is used, then we additionally switch
777 to the buffer where the process is running."
779 (list (or buffer-file-name
780 (read-file-name "File to load: " nil nil t))
782 (comint-check-source file)
783 (let ((proc (sml-prog-proc-proc)))
784 (sml-prog-proc-send-string proc (sml-prog-proc--call load-cmd file))
785 (when and-go (pop-to-buffer (process-buffer proc)))))
787 (defvar sml-prog-proc--tmp-file nil)
789 (defun sml-prog-proc-send-region (start end &optional and-go)
790 "Send the content of the region to the read-eval-print process.
791 START..END delimit the region; AND-GO if non-nil indicate to additionally
792 switch to the process's buffer."
794 (if (> start end) (let ((tmp end)) (setq end start) (setq start tmp))
795 (if (= start end) (error "Nothing to send: the region is empty")))
796 (let ((proc (sml-prog-proc-proc))
797 (tmp (make-temp-file "emacs-region")))
798 (write-region start end tmp nil 'silently)
799 (when sml-prog-proc--tmp-file
800 (ignore-errors (delete-file (car sml-prog-proc--tmp-file)))
801 (set-marker (cdr sml-prog-proc--tmp-file) nil))
802 (setq sml-prog-proc--tmp-file (cons tmp (copy-marker start)))
803 (sml-prog-proc-send-string proc (sml-prog-proc--call load-cmd tmp))
804 (when and-go (pop-to-buffer (process-buffer proc)))))
806 (defun sml-prog-proc-send-buffer (&optional and-go)
807 "Send the content of the current buffer to the read-eval-print process.
808 AND-GO if non-nil indicate to additionally switch to the process's buffer."
810 (sml-prog-proc-send-region (point-min) (point-max) and-go))
812 (define-derived-mode sml-prog-proc-mode prog-mode "Sml-Prog-Proc"
813 "Major mode for editing source code and interact with an interactive loop."
816 ;;; Extended comint-mode for Sml-Prog-Proc.
818 (defun sml-prog-proc-chdir (dir)
819 "Change the working directory of the inferior process to DIR."
820 (interactive "DChange to directory: ")
821 (let ((dir (expand-file-name dir))
822 (proc (sml-prog-proc-proc)))
823 (with-current-buffer (process-buffer proc)
824 (sml-prog-proc-send-string proc (sml-prog-proc--call chdir-cmd dir))
825 (setq default-directory (file-name-as-directory dir)))))
827 (defun sml-prog-proc-comint-input-filter-function (str)
828 ;; `compile.el' doesn't know that file location info from errors should be
829 ;; recomputed afresh (without using stale info from earlier compilations).
830 (compilation-forget-errors) ;Has to run before compilation-fake-loc.
831 (if (and sml-prog-proc--tmp-file (marker-buffer (cdr sml-prog-proc--tmp-file)))
832 (compilation-fake-loc (cdr sml-prog-proc--tmp-file)
833 (car sml-prog-proc--tmp-file)))
836 (defvar sml-prog-proc-comint-mode-map
837 (let ((map (make-sparse-keymap)))
838 (define-key map "\C-c\C-l" 'sml-prog-proc-load-file)
841 (define-derived-mode sml-prog-proc-comint-mode comint-mode "Sml-Prog-Proc-Comint"
842 "Major mode for an inferior process used to run&compile source code."
843 ;; Enable compilation-minor-mode, but only after the child mode is setup
844 ;; since the child-mode might want to add rules to
845 ;; compilation-error-regexp-alist.
846 (add-hook 'after-change-major-mode-hook #'compilation-minor-mode nil t)
847 ;; The keymap of compilation-minor-mode is too unbearable, so we
848 ;; need to hide most of the bindings.
849 (let ((map (make-sparse-keymap)))
850 (dolist (keys '([menu-bar] [follow-link]))
851 ;; Preserve some of the bindings.
852 (define-key map keys (lookup-key compilation-minor-mode-map keys)))
853 (add-to-list 'minor-mode-overriding-map-alist
854 (cons 'compilation-minor-mode map)))
856 (add-hook 'comint-input-filter-functions
857 #'sml-prog-proc-comint-input-filter-function nil t))
859 (defvar sml-prog-proc--compile-command nil
860 "The command used by default by `sml-prog-proc-compile'.")
862 (defun sml-prog-proc-compile (command &optional and-go)
863 "Pass COMMAND to the read-eval-loop process to compile the current file.
865 You can then use the command \\[next-error] to find the next error message
866 and move to the source code that caused it.
868 Interactively, prompts for the command if `compilation-read-command' is
869 non-nil. With prefix arg, always prompts.
871 Prefix arg AND-GO also means to switch to the read-eval-loop buffer afterwards."
873 (let* ((dir default-directory)
875 ;; Look for files to determine the default command.
876 (while (and (stringp dir)
878 (dolist (cf (sml-prog-proc--prop compile-commands-alist))
879 (when (file-exists-p (expand-file-name (cdr cf) dir))
880 (setq cmd (concat cmd "\"; " (car cf)))
883 (let ((newdir (file-name-directory (directory-file-name dir))))
884 (setq dir (unless (equal newdir dir) newdir))
885 (setq cmd (concat cmd "/.."))))
888 ((local-variable-p 'sml-prog-proc--compile-command)
889 sml-prog-proc--compile-command)
890 ((string-match "^\\s-*cd\\s-+\"\\.\"\\s-*;\\s-*" cmd)
891 (substring cmd (match-end 0)))
892 ((string-match "^\\s-*cd\\s-+\"\\(\\./\\)" cmd)
893 (replace-match "" t t cmd 1))
894 ((string-match ";" cmd) cmd)
895 (t sml-prog-proc--compile-command)))
896 ;; code taken from compile.el
897 (list (if (or compilation-read-command current-prefix-arg)
898 (read-from-minibuffer "Compile command: "
899 cmd nil nil '(compile-history . 1))
901 ;; ;; now look for command's file to determine the directory
902 ;; (setq dir default-directory)
903 ;; (while (and (stringp dir)
904 ;; (dolist (cf (sml-prog-proc--prop compile-commands-alist) t)
905 ;; (when (and (equal cmd (car cf))
906 ;; (file-exists-p (expand-file-name (cdr cf) dir)))
908 ;; (let ((newdir (file-name-directory (directory-file-name dir))))
909 ;; (setq dir (unless (equal newdir dir) newdir))))
910 ;; (setq dir (or dir default-directory))
912 (set (make-local-variable 'sml-prog-proc--compile-command) command)
913 (save-some-buffers (not compilation-ask-about-save) nil)
914 (let ((dir default-directory))
915 (when (string-match "^\\s-*cd\\s-+\"\\([^\"]+\\)\"\\s-*;" command)
916 (setq dir (match-string 1 command))
917 (setq command (replace-match "" t t command)))
918 (setq dir (expand-file-name dir))
919 (let ((proc (sml-prog-proc-proc))
920 (eol (sml-prog-proc--prop command-eol)))
921 (with-current-buffer (process-buffer proc)
922 (setq default-directory dir)
923 (sml-prog-proc-send-string
924 proc (concat (sml-prog-proc--call chdir-cmd dir)
925 ;; Strip the newline, to avoid adding a prompt.
926 (if (string-match "\n\\'" eol)
927 (replace-match " " t t eol) eol)
929 (when and-go (pop-to-buffer (process-buffer proc)))))))
932 ;;; SML Sml-Prog-Proc support.
934 (defcustom sml-program-name "sml"
935 "Program to run as Standard SML read-eval-print loop."
938 (defcustom sml-default-arg ""
939 "Default command line option to pass to `sml-program-name', if any."
942 (defcustom sml-host-name ""
943 "Host on which to run `sml-program-name'."
946 (defcustom sml-config-file "~/.smlproc.sml"
947 "File that should be fed to the SML process when started."
951 (defcustom sml-prompt-regexp "^[-=>#] *"
952 "Regexp used to recognise prompts in the inferior SML process."
955 (defcustom sml-compile-commands-alist
956 '(("CMB.make()" . "all-files.cm")
957 ("CMB.make()" . "pathconfig")
958 ("CM.make()" . "sources.cm")
959 ("use \"load-all\"" . "load-all"))
960 "Commands used by default by `sml-sml-prog-proc-compile'.
961 Each command is associated with its \"main\" file.
962 It is perfectly OK to associate several files with a command or several
963 commands with the same file.")
965 ;; FIXME: Try to auto-detect the process and set those vars accordingly.
967 (defvar sml-use-command "use \"%s\""
968 "Template for loading a file into the inferior SML process.
969 Set to \"use \\\"%s\\\"\" for SML/NJ or Edinburgh ML;
970 set to \"PolyML.use \\\"%s\\\"\" for Poly/ML, etc.")
972 (defvar sml-cd-command "OS.FileSys.chDir \"%s\""
973 "Command template for changing working directories under SML.
974 Set this to nil if your compiler can't change directories.
976 The format specifier \"%s\" will be converted into the directory name
977 specified when running the command \\[sml-cd].")
979 (defvar sml-error-regexp-alist
980 `( ;; Poly/ML messages
981 ("^\\(Error\\|Warning:\\) in '\\(.+\\)', line \\([0-9]+\\)" 2 3)
983 ("^File \"\\([^\"]+\\)\", line \\([0-9]+\\)\\(-\\([0-9]+\\)\\)?, characters \\([0-9]+\\)-\\([0-9]+\\):" 1 2 5)
984 ;; SML/NJ: the file-pattern is anchored to avoid
985 ;; pathological behavior with very long lines.
986 ("^[-= ]*\\(.*[^\n)]\\)\\( (.*)\\)?:\\([0-9]+\\)\\.\\([0-9]+\\)\\(-\\([0-9]+\\)\\.\\([0-9]+\\)\\)? \\(Error\\|Warnin\\(g\\)\\): .*" 1
988 ;; SML/NJ's exceptions: see above.
989 ("^ +\\(raised at: \\)?\\(.+\\):\\([0-9]+\\)\\.\\([0-9]+\\)\\(-\\([0-9]+\\)\\.\\([0-9]+\\)\\)" 2
991 "Alist that specifies how to match errors in compiler output.
992 See `compilation-error-regexp-alist' for a description of the format.")
994 (defconst sml-pp-functions
995 (sml-prog-proc-make :name "SML"
996 :run (lambda () (call-interactively #'sml-run))
997 :load-cmd (lambda (file) (format sml-use-command file))
998 :chdir-cmd (lambda (dir) (format sml-cd-command dir))
999 :compile-commands-alist sml-compile-commands-alist
1003 ;; font-lock support
1004 (defconst inferior-sml-font-lock-keywords
1005 `(;; prompt and following interactive command
1006 ;; FIXME: Actually, this should already be taken care of by comint.
1007 (,(concat "\\(" sml-prompt-regexp "\\)\\(.*\\)")
1008 (1 font-lock-prompt-face)
1009 (2 font-lock-command-face keep))
1011 ("^\\[\\(.*GC #.*\n\\)*.*\\]" . font-lock-comment-face)
1012 ;; SML/NJ's irritating GC messages
1013 ("^GC #.*" . font-lock-comment-face))
1014 "Font-locking specification for inferior SML mode.")
1016 (defface font-lock-prompt-face
1018 "Font Lock mode face used to highlight prompts."
1019 :group 'font-lock-highlighting-faces)
1020 (defvar font-lock-prompt-face 'font-lock-prompt-face
1021 "Face name to use for prompts.")
1023 (defface font-lock-command-face
1025 "Font Lock mode face used to highlight interactive commands."
1026 :group 'font-lock-highlighting-faces)
1027 (defvar font-lock-command-face 'font-lock-command-face
1028 "Face name to use for interactive commands.")
1030 (defconst inferior-sml-font-lock-defaults
1031 '(inferior-sml-font-lock-keywords nil nil nil nil))
1033 (defun sml--read-run-cmd ()
1035 (read-string "SML command: " sml-program-name)
1036 (if (or current-prefix-arg (> (length sml-default-arg) 0))
1037 (read-string "Any args: " sml-default-arg)
1039 (if (or current-prefix-arg (> (length sml-host-name) 0))
1040 (read-string "On host: " sml-host-name)
1044 (defalias 'run-sml 'sml-run)
1047 (defun sml-run (cmd arg &optional host)
1048 "Run the program CMD with given arguments ARG.
1049 The command is run in buffer *CMD* using mode `inferior-sml-mode'.
1050 If the buffer already exists and has a running process, then
1051 just go to this buffer.
1053 If a prefix argument is used, the user is also prompted for a HOST
1054 on which to run CMD using `remote-shell-program'.
1056 \(Type \\[describe-mode] in the process's buffer for a list of commands.)"
1057 (interactive (sml--read-run-cmd))
1058 (let* ((pname (file-name-nondirectory cmd))
1059 (args (split-string arg))
1060 (file (when (and sml-config-file (file-exists-p sml-config-file))
1062 ;; And this -- to keep these as defaults even if
1063 ;; they're set in the mode hooks.
1064 (setq sml-program-name cmd)
1065 (setq sml-default-arg arg)
1066 (setq sml-host-name host)
1067 ;; For remote execution, use `remote-shell-program'
1068 (when (> (length host) 0)
1069 (setq args (list* host "cd" default-directory ";" cmd args))
1070 (setq cmd remote-shell-program))
1072 (save-current-buffer
1073 (let ((exec-path (if (and (file-name-directory cmd)
1074 (not (file-name-absolute-p cmd)))
1075 ;; If the command has slashes, make sure we
1076 ;; first look relative to the current directory.
1077 ;; Emacs-21 does it for us, but not Emacs-20.
1078 (cons default-directory exec-path) exec-path)))
1079 (pop-to-buffer (apply 'make-comint pname cmd file args)))
1082 (goto-char (point-max))
1085 (defun sml-send-function (&optional and-go)
1086 "Send current paragraph to the inferior SML process.
1087 With a prefix argument AND-GO switch to the repl buffer as well."
1091 (sml-prog-proc-send-region (point) (mark)))
1092 (if and-go (sml-prog-proc-switch-to)))
1094 (defvar inferior-sml-mode-map
1095 (let ((map (make-sparse-keymap)))
1096 (set-keymap-parent map comint-mode-map)
1097 (define-key map "\C-c\C-s" 'sml-run)
1098 (define-key map "\t" 'completion-at-point)
1100 "Keymap for inferior-sml mode.")
1103 (declare-function smerge-refine-subst "smerge-mode"
1104 (beg1 end1 beg2 end2 props-c))
1106 (defun inferior-sml-next-error-hook ()
1107 ;; Try to recognize SML/NJ type error message and to highlight finely the
1108 ;; difference between the two types (in case they're large, it's not
1109 ;; always obvious to spot it).
1113 ;; Data.sml:31.9-33.33 Error: right-hand-side of clause doesn't agree with function result type [tycon mismatch]
1114 ;; expression: Hstring
1115 ;; result type: Hstring * int
1117 ;; des2hs = (fn SYM_ID hs => hs
1118 ;; | SYM_OP hs => hs
1119 ;; | SYM_CHR hs => hs)
1120 ;; Data.sml:35.44-35.63 Error: operator and operand don't agree [tycon mismatch]
1121 ;; operator domain: Hstring * Hstring
1122 ;; operand: (Hstring * int) * (Hstring * int)
1124 ;; HSTRING.ieq (h1,h2)
1125 ;; vparse.sml:1861.6-1922.14 Error: case object and rules don't agree [tycon mismatch]
1126 ;; rule domain: STConstraints list list option
1127 ;; object: STConstraints list option
1129 (save-current-buffer
1130 (when (and (derived-mode-p 'sml-mode 'inferior-sml-mode)
1131 (boundp 'next-error-last-buffer)
1132 (bufferp next-error-last-buffer)
1133 (set-buffer next-error-last-buffer)
1134 (derived-mode-p 'inferior-sml-mode)
1135 ;; The position of `point' is not guaranteed :-(
1136 (looking-at (concat ".*\\[tycon mismatch\\]\n"
1137 " \\(operator domain\\|expression\\|rule domain\\): +")))
1138 (require 'smerge-mode)
1140 (let ((b1 (match-end 0))
1142 (when (re-search-forward "\n in \\(expression\\|declaration\\):\n"
1144 (setq e2 (match-beginning 0))
1145 (when (re-search-backward
1146 "\n \\(operand\\|result type\\|object\\): +"
1148 (setq e1 (match-beginning 0))
1149 (setq b2 (match-end 0))
1150 (smerge-refine-subst b1 e1 b2 e2
1151 '((face . smerge-refined-change))))))))))
1153 (define-derived-mode inferior-sml-mode sml-prog-proc-comint-mode "Inferior-SML"
1154 "Major mode for interacting with an inferior SML process.
1156 The following commands are available:
1157 \\{inferior-sml-mode-map}
1159 An SML process can be fired up (again) with \\[sml].
1161 Customisation: Entry to this mode runs the hooks on `comint-mode-hook'
1162 and `inferior-sml-mode-hook' (in that order).
1164 Variables controlling behaviour of this mode are
1166 `sml-program-name' (default \"sml\")
1167 Program to run as SML.
1169 `sml-use-command' (default \"use \\\"%s\\\"\")
1170 Template for loading a file into the inferior SML process.
1172 `sml-cd-command' (default \"System.Directory.cd \\\"%s\\\"\")
1173 SML command for changing directories in SML process (if possible).
1175 `sml-prompt-regexp' (default \"^[\\-=] *\")
1176 Regexp used to recognise prompts in the inferior SML process.
1178 You can send text to the inferior SML process from other buffers containing
1180 `switch-to-sml' switches the current buffer to the SML process buffer.
1181 `sml-send-function' sends the current *paragraph* to the SML process.
1182 `sml-send-region' sends the current region to the SML process.
1184 Prefixing the sml-send-<whatever> commands with \\[universal-argument]
1185 causes a switch to the SML process buffer after sending the text.
1187 For information on running multiple processes in multiple buffers, see
1188 documentation for variable `sml-buffer'.
1191 RET after the end of the process' output sends the text from the
1192 end of process to point.
1193 RET before the end of the process' output copies the current line
1194 to the end of the process' output, and sends it.
1195 DEL converts tabs to spaces as it moves back.
1196 TAB file name completion, as in shell-mode, etc.."
1197 (setq comint-prompt-regexp sml-prompt-regexp)
1198 (sml-mode-variables)
1200 ;; We have to install it globally, 'cause it's run in the *source* buffer :-(
1201 (add-hook 'next-error-hook 'inferior-sml-next-error-hook)
1203 ;; Make TAB add a " rather than a space at the end of a file name.
1204 (set (make-local-variable 'comint-completion-addsuffix) '("/" . "\""))
1206 (set (make-local-variable 'font-lock-defaults)
1207 inferior-sml-font-lock-defaults)
1209 ;; Compilation support (used for `next-error').
1210 (set (make-local-variable 'compilation-error-regexp-alist)
1211 sml-error-regexp-alist)
1212 ;; FIXME: move it to sml-mode?
1213 (set (make-local-variable 'compilation-error-screen-columns) nil)
1215 (setq mode-line-process '(": %s")))
1217 ;;; MORE CODE FOR SML-MODE
1220 (add-to-list 'auto-mode-alist '("\\.s\\(ml\\|ig\\)\\'" . sml-mode))
1222 (defvar comment-quote-nested)
1225 (define-derived-mode sml-mode sml-prog-proc-mode "SML"
1226 "\\<sml-mode-map>Major mode for editing Standard ML code.
1227 This mode runs `sml-mode-hook' just before exiting.
1228 See also (info \"(sml-mode)Top\").
1230 (set (make-local-variable 'font-lock-defaults) sml-font-lock-defaults)
1231 (set (make-local-variable 'outline-regexp) sml-outline-regexp)
1232 (set (make-local-variable 'imenu-create-index-function)
1233 'sml-imenu-create-index)
1234 (set (make-local-variable 'add-log-current-defun-function)
1235 'sml-current-fun-name)
1236 ;; Treat paragraph-separators in comments as paragraph-separators.
1237 (set (make-local-variable 'paragraph-separate)
1238 (concat "\\([ \t]*\\*)?\\)?\\(" paragraph-separate "\\)"))
1239 (set (make-local-variable 'require-final-newline) t)
1240 (set (make-local-variable 'electric-indent-chars)
1241 (cons ?\; (if (boundp 'electric-indent-chars)
1242 electric-indent-chars '(?\n))))
1243 (set (make-local-variable 'electric-layout-rules)
1244 `((?\; . ,(lambda ()
1246 (skip-chars-backward " \t;")
1248 (progn (skip-chars-forward " \t;")
1251 (when sml-electric-pipe-mode
1252 (add-hook 'post-self-insert-hook #'sml-post-self-insert-pipe nil t))
1253 (sml-mode-variables))
1255 (defun sml-mode-variables ()
1256 (set (make-local-variable 'sml-prog-proc-descriptor) sml-pp-functions)
1257 (set-syntax-table sml-mode-syntax-table)
1258 (setq local-abbrev-table sml-mode-abbrev-table)
1259 ;; Setup indentation and sexp-navigation.
1260 (smie-setup sml-smie-grammar #'sml-smie-rules
1261 :backward-token #'sml-smie-backward-token
1262 :forward-token #'sml-smie-forward-token)
1263 (set (make-local-variable 'parse-sexp-ignore-comments) t)
1264 (set (make-local-variable 'comment-start) "(* ")
1265 (set (make-local-variable 'comment-end) " *)")
1266 (set (make-local-variable 'comment-start-skip) "(\\*+\\s-*")
1267 (set (make-local-variable 'comment-end-skip) "\\s-*\\*+)")
1268 ;; No need to quote nested comments markers.
1269 (set (make-local-variable 'comment-quote-nested) nil))
1271 (defun sml-funname-of-and ()
1272 "Name of the function this `and' defines, or nil if not a function.
1273 Point has to be right after the `and' symbol and is not preserved."
1274 (forward-comment (point-max))
1275 (if (looking-at sml-tyvarseq-re) (goto-char (match-end 0)))
1276 (let ((sym (sml-smie-forward-token)))
1277 (forward-comment (point-max))
1278 (unless (or (member sym '(nil "d="))
1279 (member (sml-smie-forward-token) '("d=")))
1282 (defun sml-find-forward (re)
1283 (while (progn (forward-comment (point-max))
1284 (not (looking-at re)))
1285 (or (ignore-errors (forward-sexp 1) t) (forward-char 1))))
1287 (defun sml-electric-pipe ()
1289 Depending on the context insert the name of function, a \"=>\" etc."
1291 (unless (save-excursion (skip-chars-backward "\t ") (bolp)) (insert "\n"))
1293 (unless (sml-post-self-insert-pipe (1- (point)))
1294 (indent-according-to-mode)))
1296 (defun sml-post-self-insert-pipe (&optional acp)
1297 (when (or acp (and (eq ?| last-command-event)
1298 (setq acp (electric--after-char-pos))))
1301 (goto-char (1- acp)) ;Jump before the "|" we just inserted.
1302 (let ((sym (sml-find-matching-starter sml-pipeheads
1303 ;; (sml-op-prec "|" 'back)
1305 (sml-smie-forward-token)
1306 (forward-comment (point-max))
1309 (let ((f (sml-smie-forward-token)))
1310 (sml-find-forward "\\(=>\\|=\\||\\)\\S.")
1312 ((looking-at "|") nil) ; A datatype or an OR pattern?
1313 ((looking-at "=>") " => ") ;`case', or `fn' or `handle'.
1314 ((looking-at "=") ;A function.
1315 (cons (concat f " ")" = ")))))
1316 ((string= sym "and")
1317 ;; Could be a datatype or a function.
1318 (let ((funname (sml-funname-of-and)))
1319 (if funname (cons (concat funname " ") " = ") nil)))
1320 ((string= sym "fun")
1321 (while (and (setq sym (sml-smie-forward-token))
1322 (string-match "^'" sym))
1323 (forward-comment (point-max)))
1324 (cons (concat sym " ") " = "))
1325 ((member sym '("case" "handle" "of")) " => ") ;; "fn"?
1326 ;;((member sym '("abstype" "datatype")) "")
1330 (goto-char (1- acp))
1331 (unless (save-excursion (skip-chars-backward "\t ") (bolp))
1333 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
1334 (let ((use-region (and (use-region-p) (< (point) (mark)))))
1335 ;; (skeleton-proxy-new `(nil ,(if (consp text) (pop text)) _ ,text))
1336 (when (consp text) (insert (pop text)))
1337 (if (not use-region)
1338 (save-excursion (insert text))
1341 (indent-according-to-mode)
1347 (defun sml-mark-function ()
1348 "Mark the surrounding function. Or try to at least."
1350 ;; FIXME: Provide beginning-of-defun-function so mark-defun "just works".
1351 (let ((start (point)))
1352 (sml-beginning-of-defun)
1353 (let ((beg (point)))
1354 (smie-forward-sexp 'halfsexp)
1355 (if (or (< start beg) (> start (point)))
1362 (defun sml-back-to-outer-indent ()
1363 "Unindents to the next outer level of indentation."
1367 (let ((start-column (current-indentation))
1369 (when (> start-column 0)
1371 (while (>= (setq indent
1372 (if (re-search-backward "^[ \t]*[^\n\t]" nil t)
1373 (current-indentation)
1376 (skip-chars-forward " \t")
1377 (let ((pos (point)))
1378 (move-to-column start-column)
1379 (when (re-search-backward " \\([^ \t\n]\\)" pos t)
1380 (goto-char (match-beginning 1))
1381 (setq indent (current-column)))))
1382 (indent-line-to indent)))))
1384 (defun sml-find-matching-starter (syms)
1385 (let ((halfsexp nil)
1387 ;;(sml-smie-forward-token)
1388 (while (not (or (bobp)
1389 (member (nth 2 (setq tok (smie-backward-sexp halfsexp)))
1392 ((null (car tok)) nil)
1393 ((numberp (car tok)) (setq halfsexp 'half))
1394 (t (goto-char (cadr tok)))))
1395 (if (nth 2 tok) (goto-char (cadr tok)))
1398 (defun sml-skip-siblings ()
1400 (while (and (not (bobp))
1401 (progn (setq tok (smie-backward-sexp 'half))
1403 ((null (car tok)) t)
1404 ((numberp (car tok)) t)
1406 (if (nth 2 tok) (goto-char (cadr tok)))
1409 (defun sml-beginning-of-defun ()
1410 (let ((sym (sml-find-matching-starter sml-starters-syms)))
1411 (if (member sym '("fun" "and" "functor" "signature" "structure"
1412 "abstraction" "datatype" "abstype"))
1413 (save-excursion (sml-smie-forward-token) (forward-comment (point-max))
1414 (sml-smie-forward-token))
1415 ;; We're inside a "non function declaration": let's skip all other
1416 ;; declarations that we find at the same level and try again.
1418 ;; Obviously, let's not try again if we're at bobp.
1419 (unless (bobp) (sml-beginning-of-defun)))))
1421 (defcustom sml-max-name-components 3
1422 "Maximum number of components to use for the current function name."
1425 (defun sml-current-fun-name ()
1427 (let ((count sml-max-name-components)
1430 (while (and (> count 0)
1431 (setq name (sml-beginning-of-defun)))
1433 (setq fullname (if fullname (concat name "." fullname) name))
1434 ;; Skip all other declarations that we find at the same level.
1435 (sml-skip-siblings))
1439 ;;; INSERTING PROFORMAS (COMMON SML-FORMS)
1441 (defvar sml-forms-alist nil
1442 "Alist of code templates.
1443 You can extend this alist to your heart's content. For each additional
1444 template NAME in the list, declare a keyboard macro or function (or
1445 interactive command) called 'sml-form-NAME'.
1446 If 'sml-form-NAME' is a function it takes no arguments and should
1447 insert the template at point\; if this is a command it may accept any
1448 sensible interactive call arguments\; keyboard macros can't take
1450 `sml-forms-alist' understands let, local, case, abstype, datatype,
1451 signature, structure, and functor by default.")
1453 (defmacro sml-def-skeleton (name interactor &rest elements)
1454 (let ((fsym (intern (concat "sml-form-" name))))
1456 (add-to-list 'sml-forms-alist ',(cons name fsym))
1457 (define-abbrev sml-mode-abbrev-table ,name "" ',fsym nil 'system)
1458 (let ((abbrev (abbrev-symbol ,name sml-mode-abbrev-table)))
1459 (abbrev-put abbrev :case-fixed t)
1460 (abbrev-put abbrev :enable-function
1461 (lambda () (not (nth 8 (syntax-ppss))))))
1462 (define-skeleton ,fsym
1463 ,(format "SML-mode skeleton for `%s..' expressions" name)
1465 ,(concat name " ") >
1467 (put 'sml-def-skeleton 'lisp-indent-function 2)
1469 (sml-def-skeleton "let" nil
1470 @ "\nin " > _ "\nend" >)
1472 (sml-def-skeleton "if" nil
1473 @ " then " > _ "\nelse " > _)
1475 (sml-def-skeleton "local" nil
1476 @ "\nin" > _ "\nend" >)
1478 (sml-def-skeleton "case" "Case expr: "
1479 str "\nof " > _ " => ")
1481 (sml-def-skeleton "signature" "Signature name: "
1482 str " =\nsig" > "\n" > _ "\nend" >)
1484 (sml-def-skeleton "structure" "Structure name: "
1485 str " =\nstruct" > "\n" > _ "\nend" >)
1487 (sml-def-skeleton "functor" "Functor name: "
1488 str " () : =\nstruct" > "\n" > _ "\nend" >)
1490 (sml-def-skeleton "datatype" "Datatype name and type params: "
1493 (sml-def-skeleton "abstype" "Abstype name and type params: "
1494 str " =" \n _ "\nwith" > "\nend" >)
1498 (sml-def-skeleton "struct" nil
1501 (sml-def-skeleton "sig" nil
1504 (sml-def-skeleton "val" nil
1507 (sml-def-skeleton "fn" nil
1510 (sml-def-skeleton "fun" nil
1515 (defun sml-forms-menu (_menu)
1516 (mapcar (lambda (x) (vector (car x) (cdr x) t))
1519 (defvar sml-last-form "let")
1521 (defun sml-electric-space ()
1522 "Expand a symbol into an SML form, or just insert a space.
1523 If the point directly precedes a symbol for which an SML form exists,
1524 the corresponding form is inserted."
1526 (let ((abbrev-mode (not abbrev-mode))
1527 (last-command-event ?\s)
1528 ;; Bind `this-command' to fool skeleton's special abbrev handling.
1529 (this-command 'self-insert-command))
1530 (call-interactively 'self-insert-command)))
1532 (defun sml-insert-form (name newline)
1533 "Interactive short-cut to insert the NAME common SML form.
1534 If a prefix argument is given insert a NEWLINE and indent first, or
1535 just move to the proper indentation if the line is blank\; otherwise
1536 insert at point (which forces indentation to current column).
1538 The default form to insert is 'whatever you inserted last time'
1539 \(just hit return when prompted\)\; otherwise the command reads with
1540 completion from `sml-forms-alist'."
1542 (list (completing-read
1543 (format "Form to insert (default %s): " sml-last-form)
1544 sml-forms-alist nil t nil nil sml-forms-alist)
1545 current-prefix-arg))
1546 (setq sml-last-form name)
1547 (unless (or (not newline)
1548 (save-excursion (beginning-of-line) (looking-at "\\s-*$")))
1550 (when (memq (char-syntax (preceding-char)) '(?_ ?w)) (insert " "))
1551 (let ((f (cdr (assoc name sml-forms-alist))))
1553 ((commandp f) (command-execute f))
1555 (t (error "Undefined SML form: %s" name)))))
1561 (defvar sml-mlton-command "mlton"
1562 "Command to run MLton. Can include arguments.")
1564 (defvar sml-mlton-mainfile nil)
1566 (defconst sml-mlton-error-regexp-alist
1567 ;; I wish they just changed MLton to use one of the standard
1569 `(("^\\(?:Error\\|\\(Warning\\)\\): \\(.+\\) \\([0-9]+\\)\\.\\([0-9]+\\)\\.$"
1571 ;; If subgroup 1 matched, then it's a warning, otherwise it's an error.
1574 (defvar compilation-error-regexp-alist)
1575 (eval-after-load "compile"
1576 '(dolist (x sml-mlton-error-regexp-alist)
1577 (add-to-list 'compilation-error-regexp-alist x)))
1579 (defun sml-mlton-typecheck (mainfile)
1580 "Typecheck using MLton.
1581 MAINFILE is the top level file of the project."
1583 (list (if (and sml-mlton-mainfile (not current-prefix-arg))
1585 (read-file-name "Main file: "))))
1586 (setq sml-mlton-mainfile mainfile)
1589 (dolist (x sml-mlton-error-regexp-alist)
1590 (add-to-list 'compilation-error-regexp-alist x))
1591 (with-current-buffer (find-file-noselect mainfile)
1592 (compile (concat sml-mlton-command
1593 " -stop tc " ;Stop right after type checking.
1594 (shell-quote-argument
1595 (file-relative-name buffer-file-name))))))
1598 ;;; MLton's def-use info.
1601 (defvar sml-defuse-file nil)
1603 (defun sml-defuse-file ()
1604 (or sml-defuse-file (sml-defuse-set-file)))
1606 (defun sml-defuse-set-file ()
1607 "Specify the def-use file to use."
1609 (setq sml-defuse-file (read-file-name "Def-use file: ")))
1611 (defun sml-defuse-symdata-at-point ()
1613 (sml-smie-forward-token)
1614 (let ((symname (sml-smie-backward-token)))
1615 (if (equal symname "op")
1616 (save-excursion (setq symname (sml-smie-forward-token))))
1617 (when (string-match "op " symname)
1618 (setq symname (substring symname (match-end 0)))
1620 (forward-comment (point-max)))
1622 ;; Def-use files seem to count chars, not columns.
1623 ;; We hope here that they don't actually count bytes.
1624 ;; Also they seem to start counting at 1.
1625 (1+ (- (point) (progn (beginning-of-line) (point))))
1627 (widen) (1+ (count-lines (point-min) (point))))
1628 buffer-file-name))))
1630 (defconst sml-defuse-def-regexp
1631 "^[[:alpha:]]+ \\([^ \n]+\\) \\(.+\\) \\([0-9]+\\)\\.\\([0-9]+\\)$")
1632 (defconst sml-defuse-use-regexp-format "^ %s %d\\.%d $")
1634 (defun sml-defuse-jump-to-def ()
1635 "Jump to the definition corresponding to the symbol at point."
1637 (let ((symdata (sml-defuse-symdata-at-point)))
1638 (if (null (car symdata))
1639 (error "Not on a symbol")
1640 (with-current-buffer (find-file-noselect (sml-defuse-file))
1641 (goto-char (point-min))
1642 (unless (re-search-forward
1643 (format sml-defuse-use-regexp-format
1645 ;; May be an absolute file name.
1646 (regexp-quote (nth 3 symdata))
1648 ;; Or a relative file name.
1649 (regexp-quote (file-relative-name
1655 ;; FIXME: This is typically due to editing: any minor editing will
1656 ;; mess everything up. We should try to fail more gracefully.
1657 (error "Def-use info not found"))
1658 (unless (re-search-backward sml-defuse-def-regexp nil t)
1659 ;; This indicates a bug in this code.
1660 (error "Internal failure while looking up def-use"))
1661 (unless (equal (match-string 1) (nth 0 symdata))
1662 ;; FIXME: This again is most likely due to editing.
1663 (error "Incoherence in the def-use info found"))
1664 (let ((line (string-to-number (match-string 3)))
1665 (char (string-to-number (match-string 4))))
1666 (pop-to-buffer (find-file-noselect (match-string 2)))
1667 (goto-char (point-min))
1668 (forward-line (1- line))
1669 (forward-char (1- char)))))))
1672 ;;; SML/NJ's Compilation Manager support
1675 (defvar sml-cm-mode-syntax-table sml-mode-syntax-table)
1676 (defvar sml-cm-font-lock-keywords
1677 `(,(concat "\\_<" (regexp-opt '("library" "group" "is" "structure"
1678 "functor" "signature" "funsig") t)
1681 (add-to-list 'completion-ignored-extensions ".cm/")
1682 ;; This was used with the old compilation manager.
1683 (add-to-list 'completion-ignored-extensions "CM/")
1685 (add-to-list 'auto-mode-alist '("\\.cm\\'" . sml-cm-mode))
1687 (define-derived-mode sml-cm-mode fundamental-mode "SML-CM"
1688 "Major mode for SML/NJ's Compilation Manager configuration files."
1689 (set (make-local-variable 'sml-prog-proc-descriptor) sml-pp-functions)
1690 (set (make-local-variable 'font-lock-defaults)
1691 '(sml-cm-font-lock-keywords nil t nil nil)))
1697 (defvar sml-lex-font-lock-keywords
1699 `((,(concat "^%" sml-id-re) . font-lock-builtin-face)
1700 ("^%%" . font-lock-module-def-face))
1701 sml-font-lock-keywords))
1702 (defconst sml-lex-font-lock-defaults
1703 (cons 'sml-lex-font-lock-keywords (cdr sml-font-lock-defaults)))
1706 (define-derived-mode sml-lex-mode sml-mode "SML-Lex"
1707 "Major Mode for editing ML-Lex files."
1708 (set (make-local-variable 'font-lock-defaults) sml-lex-font-lock-defaults))
1714 (defface sml-yacc-bnf-face
1715 '((t (:foreground "darkgreen")))
1716 "Face used to highlight (non)terminals in `sml-yacc-mode'.")
1717 (defvar sml-yacc-bnf-face 'sml-yacc-bnf-face)
1719 (defcustom sml-yacc-indent-action 16
1720 "Indentation column of the opening paren of actions."
1723 (defcustom sml-yacc-indent-pipe nil
1724 "Indentation column of the pipe char in the BNF.
1725 If nil, align it with `:' or with previous cases."
1728 (defcustom sml-yacc-indent-term nil
1729 "Indentation column of the (non)term part.
1730 If nil, align it with previous cases."
1733 (defvar sml-yacc-font-lock-keywords
1734 (cons `((concat "^\\(" sml-id-re "\\s-*:\\|\\s-*|\\)\\(\\s-*" sml-id-re
1735 "\\)*\\s-*\\(\\(%" sml-id-re "\\)\\s-+" sml-id-re "\\|\\)")
1738 (goto-char (match-beginning 0))
1739 (unless (or (re-search-forward "\\_<of\\_>"
1740 (match-end 0) 'move)
1741 (progn (forward-comment (point-max))
1742 (not (looking-at "("))))
1743 sml-yacc-bnf-face))))
1744 (4 font-lock-builtin-face t t))
1745 sml-lex-font-lock-keywords))
1746 (defconst sml-yacc-font-lock-defaults
1747 (cons 'sml-yacc-font-lock-keywords (cdr sml-font-lock-defaults)))
1749 (defun sml-yacc-indent-line ()
1750 "Indent current line of ML-Yacc code."
1751 (let ((savep (> (current-column) (current-indentation)))
1752 (indent (max (or (ignore-errors (sml-yacc-indentation)) 0) 0)))
1754 (save-excursion (indent-line-to indent))
1755 (indent-line-to indent))))
1757 (defun sml-yacc-indentation ()
1759 (back-to-indentation)
1760 (or (and (looking-at (eval-when-compile
1761 (concat "%\\|" sml-id-re "\\s-*:")))
1763 (when (save-excursion
1764 (condition-case nil (progn (up-list -1) nil) (scan-error t)))
1765 ;; We're outside an action.
1767 ;; Special handling of indentation inside %term and %nonterm
1769 (and (re-search-backward "^%\\(\\sw+\\)" nil t)
1770 (member (match-string 1) '("term" "nonterm"))))
1771 (if (numberp sml-yacc-indent-term) sml-yacc-indent-term
1772 (let ((offset (if (looking-at "|") -2 0)))
1774 (looking-at "\\s-*\\(%\\sw*\\||\\)?\\s-*")
1775 (goto-char (match-end 0))
1776 (+ offset (current-column)))))
1777 ((looking-at "(") sml-yacc-indent-action)
1779 (if (numberp sml-yacc-indent-pipe) sml-yacc-indent-pipe
1781 (while (progn (forward-comment (- (point)))
1782 (/= 0 (skip-syntax-backward "w_"))))
1783 (forward-comment (- (point)))
1784 (if (not (looking-at "\\s-$"))
1785 (1- (current-column))
1786 (skip-syntax-forward " ")
1787 (- (current-column) 2))))))
1788 ;; default to SML rules
1789 (smie-indent-calculate))))
1792 (add-to-list 'auto-mode-alist '("\\.grm\\'" . sml-yacc-mode))
1794 (define-derived-mode sml-yacc-mode sml-mode "SML-Yacc"
1795 "Major Mode for editing ML-Yacc files."
1796 (set (make-local-variable 'indent-line-function) 'sml-yacc-indent-line)
1797 (set (make-local-variable 'font-lock-defaults) sml-yacc-font-lock-defaults))
1802 ;;; sml-mode.el ends here