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