]> git.lizzy.rs Git - rust.git/blob - src/etc/emacs/rust-mode.el
rollup merge of #20642: michaelwoerister/sane-source-locations-pt1
[rust.git] / src / etc / emacs / rust-mode.el
1 ;;; rust-mode.el --- A major emacs mode for editing Rust source code
2
3 ;; Version: 0.2.0
4 ;; Author: Mozilla
5 ;; Url: https://github.com/rust-lang/rust
6 ;; Keywords: languages
7
8 ;;; Commentary:
9 ;;
10
11 ;;; Code:
12
13 (eval-when-compile (require 'misc))
14
15 ;; for GNU Emacs < 24.3
16 (eval-when-compile
17   (unless (fboundp 'setq-local)
18     (defmacro setq-local (var val)
19       "Set variable VAR to value VAL in current buffer."
20       (list 'set (list 'make-local-variable (list 'quote var)) val))))
21
22 ;; Syntax definitions and helpers
23 (defvar rust-mode-syntax-table
24   (let ((table (make-syntax-table)))
25
26     ;; Operators
27     (dolist (i '(?+ ?- ?* ?/ ?& ?| ?^ ?! ?< ?> ?~ ?@))
28       (modify-syntax-entry i "." table))
29
30     ;; Strings
31     (modify-syntax-entry ?\" "\"" table)
32     (modify-syntax-entry ?\\ "\\" table)
33
34     ;; mark _ as a word constituent so that identifiers
35     ;; such as xyz_type don't cause type to be highlighted
36     ;; as a keyword
37     (modify-syntax-entry ?_ "w" table)
38
39     ;; Comments
40     (modify-syntax-entry ?/  ". 124b" table)
41     (modify-syntax-entry ?*  ". 23"   table)
42     (modify-syntax-entry ?\n "> b"    table)
43     (modify-syntax-entry ?\^m "> b"   table)
44
45     table))
46
47 (defgroup rust-mode nil
48   "Support for Rust code."
49   :link '(url-link "http://www.rust-lang.org/")
50   :group 'languages)
51
52 (defcustom rust-indent-offset 4
53   "Indent Rust code by this number of spaces."
54   :type 'integer
55   :group 'rust-mode)
56
57 (defcustom rust-indent-method-chain nil
58   "Indent Rust method chains, aligned by the '.' operators"
59   :type 'boolean
60   :group 'rust-mode)
61
62 (defun rust-paren-level () (nth 0 (syntax-ppss)))
63 (defun rust-in-str-or-cmnt () (nth 8 (syntax-ppss)))
64 (defun rust-rewind-past-str-cmnt () (goto-char (nth 8 (syntax-ppss))))
65 (defun rust-rewind-irrelevant ()
66   (let ((starting (point)))
67     (skip-chars-backward "[:space:]\n")
68     (if (looking-back "\\*/") (backward-char))
69     (if (rust-in-str-or-cmnt)
70         (rust-rewind-past-str-cmnt))
71     (if (/= starting (point))
72         (rust-rewind-irrelevant))))
73
74 (defun rust-align-to-expr-after-brace ()
75   (save-excursion
76     (forward-char)
77     ;; We don't want to indent out to the open bracket if the
78     ;; open bracket ends the line
79     (when (not (looking-at "[[:blank:]]*\\(?://.*\\)?$"))
80       (when (looking-at "[[:space:]]")
81     (forward-word 1)
82     (backward-word 1))
83       (current-column))))
84
85 (defun rust-align-to-method-chain ()
86   (save-excursion
87     (previous-line)
88     (end-of-line)
89     (backward-word 1)
90     (backward-char)
91     (when (looking-at "\\..+\(.*\)\n")
92       (- (current-column) rust-indent-offset))))
93
94 (defun rust-rewind-to-beginning-of-current-level-expr ()
95   (let ((current-level (rust-paren-level)))
96     (back-to-indentation)
97     (while (> (rust-paren-level) current-level)
98       (backward-up-list)
99       (back-to-indentation))))
100
101 (defun rust-mode-indent-line ()
102   (interactive)
103   (let ((indent
104          (save-excursion
105            (back-to-indentation)
106            ;; Point is now at beginning of current line
107            (let* ((level (rust-paren-level))
108                   (baseline
109                    ;; Our "baseline" is one level out from the indentation of the expression
110                    ;; containing the innermost enclosing opening bracket.  That
111                    ;; way if we are within a block that has a different
112                    ;; indentation than this mode would give it, we still indent
113                    ;; the inside of it correctly relative to the outside.
114                    (if (= 0 level)
115                        0
116                      (or
117                       (when rust-indent-method-chain
118                         (rust-align-to-method-chain))
119                      (save-excursion
120                        (backward-up-list)
121                        (rust-rewind-to-beginning-of-current-level-expr)
122                        (+ (current-column) rust-indent-offset))))))
123              (cond
124               ;; A function return type is indented to the corresponding function arguments
125               ((looking-at "->")
126                (save-excursion
127                  (backward-list)
128                  (or (rust-align-to-expr-after-brace)
129                      (+ baseline rust-indent-offset))))
130
131               ;; A closing brace is 1 level unindended
132               ((looking-at "}") (- baseline rust-indent-offset))
133
134               ;;Line up method chains by their .'s
135               ((when (and rust-indent-method-chain
136                           (looking-at "\..+\(.*\);?\n"))
137                  (or
138                   (let ((method-indent (rust-align-to-method-chain)))
139                     (when method-indent
140                       (+ method-indent rust-indent-offset)))
141                   (+ baseline rust-indent-offset))))
142
143               
144               ;; Doc comments in /** style with leading * indent to line up the *s
145               ((and (nth 4 (syntax-ppss)) (looking-at "*"))
146                (+ 1 baseline))
147
148               ;; If we're in any other token-tree / sexp, then:
149               (t
150                (or
151                 ;; If we are inside a pair of braces, with something after the
152                 ;; open brace on the same line and ending with a comma, treat
153                 ;; it as fields and align them.
154                 (when (> level 0)
155                   (save-excursion
156                     (rust-rewind-irrelevant)
157                     (backward-up-list)
158                     ;; Point is now at the beginning of the containing set of braces
159                     (rust-align-to-expr-after-brace)))
160
161                 (progn
162                   (back-to-indentation)
163                   ;; Point is now at the beginning of the current line
164                   (if (or
165                        ;; If this line begins with "else" or "{", stay on the
166                        ;; baseline as well (we are continuing an expression,
167                        ;; but the "else" or "{" should align with the beginning
168                        ;; of the expression it's in.)
169                        (looking-at "\\<else\\>\\|{")
170
171                        (save-excursion
172                          (rust-rewind-irrelevant)
173                          ;; Point is now at the end of the previous ine
174                          (or
175                           ;; If we are at the first line, no indentation is needed, so stay at baseline...
176                           (= 1 (line-number-at-pos (point)))
177                           ;; ..or if the previous line ends with any of these:
178                           ;;     { ? : ( , ; [ }
179                           ;; then we are at the beginning of an expression, so stay on the baseline...
180                           (looking-back "[(,:;?[{}]\\|[^|]|")
181                           ;; or if the previous line is the end of an attribute, stay at the baseline...
182                           (progn (rust-rewind-to-beginning-of-current-level-expr) (looking-at "#")))))
183                       baseline
184
185                     ;; Otherwise, we are continuing the same expression from the previous line,
186                     ;; so add one additional indent level
187                     (+ baseline rust-indent-offset))))))))))
188
189     ;; If we're at the beginning of the line (before or at the current
190     ;; indentation), jump with the indentation change.  Otherwise, save the
191     ;; excursion so that adding the indentations will leave us at the
192     ;; equivalent position within the line to where we were before.
193     (if (<= (current-column) (current-indentation))
194         (indent-line-to indent)
195       (save-excursion (indent-line-to indent)))))
196
197
198 ;; Font-locking definitions and helpers
199 (defconst rust-mode-keywords
200   '("as"
201     "box" "break"
202     "const" "continue" "crate"
203     "do"
204     "else" "enum" "extern"
205     "false" "fn" "for"
206     "if" "impl" "in"
207     "let" "loop"
208     "match" "mod" "move" "mut"
209     "priv" "pub"
210     "ref" "return"
211     "self" "static" "struct" "super"
212     "true" "trait" "type"
213     "unsafe" "use"
214     "virtual"
215     "where" "while"))
216
217 (defconst rust-special-types
218   '("u8" "i8"
219     "u16" "i16"
220     "u32" "i32"
221     "u64" "i64"
222
223     "f32" "f64"
224     "float" "int" "uint" "isize" "usize"
225     "bool"
226     "str" "char"))
227
228 (defconst rust-re-ident "[[:word:][:multibyte:]_][[:word:][:multibyte:]_[:digit:]]*")
229 (defconst rust-re-CamelCase "[[:upper:]][[:word:][:multibyte:]_[:digit:]]*")
230 (defun rust-re-word (inner) (concat "\\<" inner "\\>"))
231 (defun rust-re-grab (inner) (concat "\\(" inner "\\)"))
232 (defun rust-re-grabword (inner) (rust-re-grab (rust-re-word inner)))
233 (defun rust-re-item-def (itype)
234   (concat (rust-re-word itype) "[[:space:]]+" (rust-re-grab rust-re-ident)))
235
236 (defvar rust-mode-font-lock-keywords
237   (append
238    `(
239      ;; Keywords proper
240      (,(regexp-opt rust-mode-keywords 'words) . font-lock-keyword-face)
241
242      ;; Special types
243      (,(regexp-opt rust-special-types 'words) . font-lock-type-face)
244
245      ;; Attributes like `#[bar(baz)]` or `#![bar(baz)]` or `#[bar = "baz"]`
246      (,(rust-re-grab (concat "#\\!?\\[" rust-re-ident "[^]]*\\]"))
247       1 font-lock-preprocessor-face keep)
248
249      ;; Syntax extension invocations like `foo!`, highlight including the !
250      (,(concat (rust-re-grab (concat rust-re-ident "!")) "[({[:space:][]")
251       1 font-lock-preprocessor-face)
252
253      ;; Field names like `foo:`, highlight excluding the :
254      (,(concat (rust-re-grab rust-re-ident) ":[^:]") 1 font-lock-variable-name-face)
255
256      ;; Module names like `foo::`, highlight including the ::
257      (,(rust-re-grab (concat rust-re-ident "::")) 1 font-lock-type-face)
258
259      ;; Lifetimes like `'foo`
260      (,(concat "'" (rust-re-grab rust-re-ident) "[^']") 1 font-lock-variable-name-face)
261
262      ;; Character constants, since they're not treated as strings
263      ;; in order to have sufficient leeway to parse 'lifetime above.
264      (,(rust-re-grab "'[^']'") 1 font-lock-string-face)
265      (,(rust-re-grab "'\\\\[nrt]'") 1 font-lock-string-face)
266      (,(rust-re-grab "'\\\\x[[:xdigit:]]\\{2\\}'") 1 font-lock-string-face)
267      (,(rust-re-grab "'\\\\u[[:xdigit:]]\\{4\\}'") 1 font-lock-string-face)
268      (,(rust-re-grab "'\\\\U[[:xdigit:]]\\{8\\}'") 1 font-lock-string-face)
269
270      ;; CamelCase Means Type Or Constructor
271      (,(rust-re-grabword rust-re-CamelCase) 1 font-lock-type-face)
272      )
273
274    ;; Item definitions
275    (mapcar #'(lambda (x)
276                (list (rust-re-item-def (car x))
277                      1 (cdr x)))
278            '(("enum" . font-lock-type-face)
279              ("struct" . font-lock-type-face)
280              ("type" . font-lock-type-face)
281              ("mod" . font-lock-type-face)
282              ("use" . font-lock-type-face)
283              ("fn" . font-lock-function-name-face)
284              ("static" . font-lock-constant-face)))))
285
286 (defun rust-fill-prefix-for-comment-start (line-start)
287   "Determine what to use for `fill-prefix' based on what is at the beginning of a line."
288   (let ((result
289          ;; Replace /* with same number of spaces
290          (replace-regexp-in-string
291           "\\(?:/\\*+\\)[!*]"
292           (lambda (s)
293             ;; We want the * to line up with the first * of the comment start
294             (concat (make-string (- (length s) 2) ?\x20) "*"))
295           line-start)))
296     ;; Make sure we've got at least one space at the end
297     (if (not (= (aref result (- (length result) 1)) ?\x20))
298         (setq result (concat result " ")))
299     result))
300
301 (defun rust-in-comment-paragraph (body)
302   ;; We might move the point to fill the next comment, but we don't want it
303   ;; seeming to jump around on the user
304   (save-excursion
305     ;; If we're outside of a comment, with only whitespace and then a comment
306     ;; in front, jump to the comment and prepare to fill it.
307     (when (not (nth 4 (syntax-ppss)))
308       (beginning-of-line)
309       (when (looking-at (concat "[[:space:]\n]*" comment-start-skip))
310         (goto-char (match-end 0))))
311
312     ;; We need this when we're moving the point around and then checking syntax
313     ;; while doing paragraph fills, because the cache it uses isn't always
314     ;; invalidated during this.
315     (syntax-ppss-flush-cache 1)
316     ;; If we're at the beginning of a comment paragraph with nothing but
317     ;; whitespace til the next line, jump to the next line so that we use the
318     ;; existing prefix to figure out what the new prefix should be, rather than
319     ;; inferring it from the comment start.
320     (let ((next-bol (line-beginning-position 2)))
321       (while (save-excursion
322                (end-of-line)
323                (syntax-ppss-flush-cache 1)
324                (and (nth 4 (syntax-ppss))
325                     (save-excursion
326                       (beginning-of-line)
327                       (looking-at paragraph-start))
328                     (looking-at "[[:space:]]*$")
329                     (nth 4 (syntax-ppss next-bol))))
330         (goto-char next-bol)))
331
332     (syntax-ppss-flush-cache 1)
333     ;; If we're on the last line of a multiline-style comment that started
334     ;; above, back up one line so we don't mistake the * of the */ that ends
335     ;; the comment for a prefix.
336     (when (save-excursion
337             (and (nth 4 (syntax-ppss (line-beginning-position 1)))
338                  (looking-at "[[:space:]]*\\*/")))
339       (goto-char (line-end-position 0)))
340     (funcall body)))
341
342 (defun rust-with-comment-fill-prefix (body)
343   (let*
344       ((line-string (buffer-substring-no-properties
345                      (line-beginning-position) (line-end-position)))
346        (line-comment-start
347         (when (nth 4 (syntax-ppss))
348           (cond
349            ;; If we're inside the comment and see a * prefix, use it
350            ((string-match "^\\([[:space:]]*\\*+[[:space:]]*\\)"
351                           line-string)
352             (match-string 1 line-string))
353            ;; If we're at the start of a comment, figure out what prefix
354            ;; to use for the subsequent lines after it
355            ((string-match (concat "[[:space:]]*" comment-start-skip) line-string)
356             (rust-fill-prefix-for-comment-start
357              (match-string 0 line-string))))))
358        (fill-prefix
359         (or line-comment-start
360             fill-prefix)))
361     (funcall body)))
362
363 (defun rust-find-fill-prefix ()
364   (rust-with-comment-fill-prefix (lambda () fill-prefix)))
365
366 (defun rust-fill-paragraph (&rest args)
367   "Special wrapping for `fill-paragraph' to handle multi-line comments with a * prefix on each line."
368   (rust-in-comment-paragraph
369    (lambda ()
370      (rust-with-comment-fill-prefix
371       (lambda ()
372         (let
373             ((fill-paragraph-function
374               (if (not (eq fill-paragraph-function 'rust-fill-paragraph))
375                   fill-paragraph-function))
376              (fill-paragraph-handle-comment t))
377           (apply 'fill-paragraph args)
378           t))))))
379
380 (defun rust-do-auto-fill (&rest args)
381   "Special wrapping for `do-auto-fill' to handle multi-line comments with a * prefix on each line."
382   (rust-with-comment-fill-prefix
383    (lambda ()
384      (apply 'do-auto-fill args)
385      t)))
386
387 (defun rust-fill-forward-paragraph (arg)
388   ;; This is to work around some funny behavior when a paragraph separator is
389   ;; at the very top of the file and there is a fill prefix.
390   (let ((fill-prefix nil)) (forward-paragraph arg)))
391
392 (defun rust-comment-indent-new-line (&optional arg)
393   (rust-with-comment-fill-prefix
394    (lambda () (comment-indent-new-line arg))))
395
396 ;;; Imenu support
397 (defvar rust-imenu-generic-expression
398   (append (mapcar #'(lambda (x)
399                       (list nil (rust-re-item-def x) 1))
400                   '("enum" "struct" "type" "mod" "fn" "trait"))
401           `(("Impl" ,(rust-re-item-def "impl") 1)))
402   "Value for `imenu-generic-expression' in Rust mode.
403
404 Create a flat index of the item definitions in a Rust file.
405
406 Imenu will show all the enums, structs, etc. at the same level.
407 Implementations will be shown under the `Impl` subheading.  Use
408 idomenu (imenu with `ido-mode') for best mileage.")
409
410 ;;; Defun Motions
411
412 ;;; Start of a Rust item
413 (defvar rust-top-item-beg-re
414   (concat "^\\s-*\\(?:priv\\|pub\\)?\\s-*"
415           (regexp-opt
416            '("enum" "struct" "type" "mod" "use" "fn" "static" "impl"
417              "extern" "impl" "static" "trait"))))
418
419 (defun rust-beginning-of-defun (&optional arg)
420   "Move backward to the beginning of the current defun.
421
422 With ARG, move backward multiple defuns.  Negative ARG means
423 move forward.
424
425 This is written mainly to be used as `beginning-of-defun-function' for Rust.
426 Don't move to the beginning of the line. `beginning-of-defun',
427 which calls this, does that afterwards."
428   (interactive "p")
429   (re-search-backward (concat "^\\(" rust-top-item-beg-re "\\)\\_>")
430                       nil 'move (or arg 1)))
431
432 (defun rust-end-of-defun ()
433   "Move forward to the next end of defun.
434
435 With argument, do it that many times.
436 Negative argument -N means move back to Nth preceding end of defun.
437
438 Assume that this is called after beginning-of-defun. So point is
439 at the beginning of the defun body.
440
441 This is written mainly to be used as `end-of-defun-function' for Rust."
442   (interactive "p")
443   ;; Find the opening brace
444   (re-search-forward "[{]" nil t)
445   (goto-char (match-beginning 0))
446   ;; Go to the closing brace
447   (forward-sexp))
448
449 ;; For compatibility with Emacs < 24, derive conditionally
450 (defalias 'rust-parent-mode
451   (if (fboundp 'prog-mode) 'prog-mode 'fundamental-mode))
452
453
454 ;;;###autoload
455 (define-derived-mode rust-mode rust-parent-mode "Rust"
456   "Major mode for Rust code."
457   :group 'rust-mode
458   :syntax-table rust-mode-syntax-table
459
460   ;; Indentation
461   (setq-local indent-line-function 'rust-mode-indent-line)
462
463   ;; Fonts
464   (setq-local font-lock-defaults '(rust-mode-font-lock-keywords nil nil nil nil))
465
466   ;; Misc
467   (setq-local comment-start "// ")
468   (setq-local comment-end   "")
469   (setq-local indent-tabs-mode nil)
470
471   ;; Allow paragraph fills for comments
472   (setq-local comment-start-skip "\\(?://[/!]*\\|/\\*[*!]?\\)[[:space:]]*")
473   (setq-local paragraph-start
474        (concat "[[:space:]]*\\(?:" comment-start-skip "\\|\\*/?[[:space:]]*\\|\\)$"))
475   (setq-local paragraph-separate paragraph-start)
476   (setq-local normal-auto-fill-function 'rust-do-auto-fill)
477   (setq-local fill-paragraph-function 'rust-fill-paragraph)
478   (setq-local fill-forward-paragraph-function 'rust-fill-forward-paragraph)
479   (setq-local adaptive-fill-function 'rust-find-fill-prefix)
480   (setq-local comment-multi-line t)
481   (setq-local comment-line-break-function 'rust-comment-indent-new-line)
482   (setq-local imenu-generic-expression rust-imenu-generic-expression)
483   (setq-local beginning-of-defun-function 'rust-beginning-of-defun)
484   (setq-local end-of-defun-function 'rust-end-of-defun))
485
486 ;;;###autoload
487 (add-to-list 'auto-mode-alist '("\\.rs\\'" . rust-mode))
488
489 (defun rust-mode-reload ()
490   (interactive)
491   (unload-feature 'rust-mode)
492   (require 'rust-mode)
493   (rust-mode))
494
495 ;; Issue #6887: Rather than inheriting the 'gnu compilation error
496 ;; regexp (which is broken on a few edge cases), add our own 'rust
497 ;; compilation error regexp and use it instead.
498 (defvar rustc-compilation-regexps
499   (let ((file "\\([^\n]+\\)")
500         (start-line "\\([0-9]+\\)")
501         (start-col  "\\([0-9]+\\)")
502         (end-line   "\\([0-9]+\\)")
503         (end-col    "\\([0-9]+\\)")
504         (error-or-warning "\\(?:[Ee]rror\\|\\([Ww]arning\\)\\)"))
505     (let ((re (concat "^" file ":" start-line ":" start-col
506                       ": " end-line ":" end-col
507                       " \\(?:[Ee]rror\\|\\([Ww]arning\\)\\):")))
508       (cons re '(1 (2 . 4) (3 . 5) (6)))))
509   "Specifications for matching errors in rustc invocations.
510 See `compilation-error-regexp-alist for help on their format.")
511
512 (eval-after-load 'compile
513   '(progn
514      (add-to-list 'compilation-error-regexp-alist-alist
515                   (cons 'rustc rustc-compilation-regexps))
516      (add-to-list 'compilation-error-regexp-alist 'rustc)))
517
518 (provide 'rust-mode)
519
520 ;;; rust-mode.el ends here