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