Skip to content

Commit f73f321

Browse files
authored
Merge pull request #163 from Wilfred/preserve_point_rustfmt
Correctly restore point position after running rustfmt
2 parents ba5ff90 + 2540d7e commit f73f321

File tree

2 files changed

+24
-5
lines changed

2 files changed

+24
-5
lines changed

rust-mode-tests.el

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2561,6 +2561,18 @@ Fontification needs to include this whole string or none of it.
25612561
)
25622562
)
25632563

2564+
(ert-deftest rust-test-revert-hook-preserves-point ()
2565+
(with-temp-buffer
2566+
;; Insert some code, and put point in the middle.
2567+
(insert "fn foo() {}\n")
2568+
(insert "fn bar() {}\n")
2569+
(insert "fn baz() {}\n")
2570+
(goto-char (point-min))
2571+
(forward-line 1)
2572+
(let ((initial-point (point)))
2573+
(rust--after-revert-hook)
2574+
(should (equal initial-point (point))))))
2575+
25642576
;; If electric-pair-mode is available, load it and run the tests that use it. If not,
25652577
;; no error--the tests will be skipped.
25662578
(require 'elec-pair nil t)

rust-mode.el

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1270,10 +1270,16 @@ This is written mainly to be used as `end-of-defun-function' for Rust."
12701270
(unless (executable-find rust-rustfmt-bin)
12711271
(error "Could not locate executable \"%s\"" rust-rustfmt-bin))
12721272

1273-
(let ((cur-point (point))
1273+
(let ((cur-line (line-number-at-pos))
1274+
(cur-column (current-column))
12741275
(cur-win-start (window-start)))
12751276
(rust--format-call (current-buffer))
1276-
(goto-char cur-point)
1277+
;; Move to the same line and column as before. This is best
1278+
;; effort: if rustfmt inserted lines before point, we end up in
1279+
;; the wrong place. See issue #162.
1280+
(goto-char (point-min))
1281+
(forward-line (1- cur-line))
1282+
(forward-char cur-column)
12771283
(set-window-start (selected-window) cur-win-start))
12781284

12791285
;; Issue #127: Running this on a buffer acts like a revert, and could cause
@@ -1365,9 +1371,10 @@ This is written mainly to be used as `end-of-defun-function' for Rust."
13651371
;; to use `font-lock-ensure', which doesn't exist in Emacs 24 and earlier.
13661372
;; If it's not available, fall back to calling `font-lock-fontify-region'
13671373
;; on the whole buffer.
1368-
(if (fboundp 'font-lock-ensure)
1369-
(font-lock-ensure)
1370-
(font-lock-fontify-region (point-min) (point-max))))
1374+
(save-excursion
1375+
(if (fboundp 'font-lock-ensure)
1376+
(font-lock-ensure)
1377+
(font-lock-fontify-region (point-min) (point-max)))))
13711378

13721379
(defun rust--before-save-hook ()
13731380
(when rust-format-on-save (rust-format-buffer)))

0 commit comments

Comments
 (0)