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