1 ;;; rust-mode.el --- A major emacs mode for editing Rust source code
5 ;; Url: https://github.com/rust-lang/rust
13 (eval-when-compile (require 'misc))
15 ;; for GNU Emacs < 24.3
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))))
22 ;; Syntax definitions and helpers
23 (defvar rust-mode-syntax-table
24 (let ((table (make-syntax-table)))
27 (dolist (i '(?+ ?- ?* ?/ ?& ?| ?^ ?! ?< ?> ?~ ?@))
28 (modify-syntax-entry i "." table))
31 (modify-syntax-entry ?\" "\"" table)
32 (modify-syntax-entry ?\\ "\\" table)
34 ;; mark _ as a word constituent so that identifiers
35 ;; such as xyz_type don't cause type to be highlighted
37 (modify-syntax-entry ?_ "w" table)
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)
47 (defgroup rust-mode nil
48 "Support for Rust code."
49 :link '(url-link "http://www.rust-lang.org/")
52 (defcustom rust-indent-offset 4
53 "Indent Rust code by this number of spaces."
57 (defcustom rust-indent-method-chain nil
58 "Indent Rust method chains, aligned by the '.' operators"
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))))
74 (defun rust-align-to-expr-after-brace ()
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:]]")
85 (defun rust-align-to-method-chain ()
91 (when (looking-at "\\..+\(.*\)\n")
92 (- (current-column) rust-indent-offset))))
94 (defun rust-rewind-to-beginning-of-current-level-expr ()
95 (let ((current-level (rust-paren-level)))
97 (while (> (rust-paren-level) current-level)
99 (back-to-indentation))))
101 (defun rust-mode-indent-line ()
105 (back-to-indentation)
106 ;; Point is now at beginning of current line
107 (let* ((level (rust-paren-level))
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.
117 (when rust-indent-method-chain
118 (rust-align-to-method-chain))
121 (rust-rewind-to-beginning-of-current-level-expr)
122 (+ (current-column) rust-indent-offset))))))
124 ;; A function return type is indented to the corresponding function arguments
128 (or (rust-align-to-expr-after-brace)
129 (+ baseline rust-indent-offset))))
131 ;; A closing brace is 1 level unindended
132 ((looking-at "}") (- baseline rust-indent-offset))
134 ;;Line up method chains by their .'s
135 ((when (and rust-indent-method-chain
136 (looking-at "\..+\(.*\);?\n"))
138 (let ((method-indent (rust-align-to-method-chain)))
140 (+ method-indent rust-indent-offset)))
141 (+ baseline rust-indent-offset))))
144 ;; Doc comments in /** style with leading * indent to line up the *s
145 ((and (nth 4 (syntax-ppss)) (looking-at "*"))
148 ;; If we're in any other token-tree / sexp, then:
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.
156 (rust-rewind-irrelevant)
158 ;; Point is now at the beginning of the containing set of braces
159 (rust-align-to-expr-after-brace)))
162 (back-to-indentation)
163 ;; Point is now at the beginning of the current line
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\\>\\|{")
172 (rust-rewind-irrelevant)
173 ;; Point is now at the end of the previous ine
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:
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 "#")))))
185 ;; Otherwise, we are continuing the same expression from the previous line,
186 ;; so add one additional indent level
187 (+ baseline rust-indent-offset))))))))))
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)))))
198 ;; Font-locking definitions and helpers
199 (defconst rust-mode-keywords
202 "const" "continue" "crate"
204 "else" "enum" "extern"
208 "match" "mod" "move" "mut"
211 "self" "static" "struct" "super"
212 "true" "trait" "type"
217 (defconst rust-special-types
224 "float" "int" "uint" "isize" "usize"
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)))
236 (defvar rust-mode-font-lock-keywords
240 (,(regexp-opt rust-mode-keywords 'words) . font-lock-keyword-face)
243 (,(regexp-opt rust-special-types 'words) . font-lock-type-face)
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)
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)
253 ;; Field names like `foo:`, highlight excluding the :
254 (,(concat (rust-re-grab rust-re-ident) ":[^:]") 1 font-lock-variable-name-face)
256 ;; Module names like `foo::`, highlight including the ::
257 (,(rust-re-grab (concat rust-re-ident "::")) 1 font-lock-type-face)
259 ;; Lifetimes like `'foo`
260 (,(concat "'" (rust-re-grab rust-re-ident) "[^']") 1 font-lock-variable-name-face)
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)
270 ;; CamelCase Means Type Or Constructor
271 (,(rust-re-grabword rust-re-CamelCase) 1 font-lock-type-face)
275 (mapcar #'(lambda (x)
276 (list (rust-re-item-def (car 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)))))
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."
289 ;; Replace /* with same number of spaces
290 (replace-regexp-in-string
293 ;; We want the * to line up with the first * of the comment start
294 (concat (make-string (- (length s) 2) ?\x20) "*"))
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 " ")))
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
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)))
309 (when (looking-at (concat "[[:space:]\n]*" comment-start-skip))
310 (goto-char (match-end 0))))
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
323 (syntax-ppss-flush-cache 1)
324 (and (nth 4 (syntax-ppss))
327 (looking-at paragraph-start))
328 (looking-at "[[:space:]]*$")
329 (nth 4 (syntax-ppss next-bol))))
330 (goto-char next-bol)))
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)))
342 (defun rust-with-comment-fill-prefix (body)
344 ((line-string (buffer-substring-no-properties
345 (line-beginning-position) (line-end-position)))
347 (when (nth 4 (syntax-ppss))
349 ;; If we're inside the comment and see a * prefix, use it
350 ((string-match "^\\([[:space:]]*\\*+[[:space:]]*\\)"
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))))))
359 (or line-comment-start
363 (defun rust-find-fill-prefix ()
364 (rust-with-comment-fill-prefix (lambda () fill-prefix)))
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
370 (rust-with-comment-fill-prefix
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)
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
384 (apply 'do-auto-fill args)
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)))
392 (defun rust-comment-indent-new-line (&optional arg)
393 (rust-with-comment-fill-prefix
394 (lambda () (comment-indent-new-line arg))))
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.
404 Create a flat index of the item definitions in a Rust file.
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.")
412 ;;; Start of a Rust item
413 (defvar rust-top-item-beg-re
414 (concat "^\\s-*\\(?:priv\\|pub\\)?\\s-*"
416 '("enum" "struct" "type" "mod" "use" "fn" "static" "impl"
417 "extern" "impl" "static" "trait"))))
419 (defun rust-beginning-of-defun (&optional arg)
420 "Move backward to the beginning of the current defun.
422 With ARG, move backward multiple defuns. Negative ARG means
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."
429 (re-search-backward (concat "^\\(" rust-top-item-beg-re "\\)\\_>")
430 nil 'move (or arg 1)))
432 (defun rust-end-of-defun ()
433 "Move forward to the next end of defun.
435 With argument, do it that many times.
436 Negative argument -N means move back to Nth preceding end of defun.
438 Assume that this is called after beginning-of-defun. So point is
439 at the beginning of the defun body.
441 This is written mainly to be used as `end-of-defun-function' for Rust."
443 ;; Find the opening brace
444 (re-search-forward "[{]" nil t)
445 (goto-char (match-beginning 0))
446 ;; Go to the closing brace
449 ;; For compatibility with Emacs < 24, derive conditionally
450 (defalias 'rust-parent-mode
451 (if (fboundp 'prog-mode) 'prog-mode 'fundamental-mode))
455 (define-derived-mode rust-mode rust-parent-mode "Rust"
456 "Major mode for Rust code."
458 :syntax-table rust-mode-syntax-table
461 (setq-local indent-line-function 'rust-mode-indent-line)
464 (setq-local font-lock-defaults '(rust-mode-font-lock-keywords nil nil nil nil))
467 (setq-local comment-start "// ")
468 (setq-local comment-end "")
469 (setq-local indent-tabs-mode nil)
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))
487 (add-to-list 'auto-mode-alist '("\\.rs\\'" . rust-mode))
489 (defun rust-mode-reload ()
491 (unload-feature 'rust-mode)
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.")
512 (eval-after-load 'compile
514 (add-to-list 'compilation-error-regexp-alist-alist
515 (cons 'rustc rustc-compilation-regexps))
516 (add-to-list 'compilation-error-regexp-alist 'rustc)))
520 ;;; rust-mode.el ends here