Skip to content

Commit 1d4a75f

Browse files
committed
Make rust-beginning-of-defun ignore comments and strings
Change rust-beginning-of-defun to keep searching when it stops in a comment or a string. Fixes #222.
1 parent 30a9d39 commit 1d4a75f

File tree

2 files changed

+53
-2
lines changed

2 files changed

+53
-2
lines changed

rust-mode-tests.el

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1025,6 +1025,43 @@ All positions are position symbols found in `rust-test-positions-alist'."
10251025
'beginning-of-fn3
10261026
#'beginning-of-defun))
10271027

1028+
(ert-deftest rust-beginning-of-defun-string-comment ()
1029+
(let (fn-1 fn-2 p-1 p-2)
1030+
(with-temp-buffer
1031+
(rust-mode)
1032+
(insert "fn test1() {
1033+
let s=r#\"
1034+
fn test2();
1035+
\"#;")
1036+
(setq p-1 (point))
1037+
(setq fn-1 (1+ p-1))
1038+
(insert "
1039+
fn test3() {
1040+
/*
1041+
fn test4();")
1042+
(setq p-2 (point))
1043+
(insert "\n*/\n}\n")
1044+
(setq fn-2 (point))
1045+
(insert "fn test5() { }")
1046+
1047+
(goto-char p-1)
1048+
(beginning-of-defun)
1049+
(should (eq (point) (point-min)))
1050+
1051+
(beginning-of-defun -2)
1052+
(should (eq (point) fn-2))
1053+
1054+
(goto-char p-2)
1055+
(beginning-of-defun)
1056+
(should (eq (point) fn-1))
1057+
1058+
(beginning-of-defun -1)
1059+
(should (eq (point) fn-2))
1060+
1061+
(goto-char (point-max))
1062+
(beginning-of-defun 2)
1063+
(should (eq (point) fn-1)))))
1064+
10281065
(ert-deftest rust-end-of-defun-from-middle-of-fn ()
10291066
(rust-test-motion
10301067
rust-test-motion-string

rust-mode.el

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1198,8 +1198,22 @@ This is written mainly to be used as `beginning-of-defun-function' for Rust.
11981198
Don't move to the beginning of the line. `beginning-of-defun',
11991199
which calls this, does that afterwards."
12001200
(interactive "p")
1201-
(re-search-backward (concat "^\\(" rust-top-item-beg-re "\\)")
1202-
nil 'move (or arg 1)))
1201+
(let* ((arg (or arg 1))
1202+
(magnitude (abs arg))
1203+
(sign (if (< arg 0) -1 1)))
1204+
;; If moving forward, don't find the defun we might currently be
1205+
;; on.
1206+
(when (< sign 0)
1207+
(end-of-line))
1208+
(catch 'done
1209+
(dotimes (_ magnitude)
1210+
;; Search until we find a match that is not in a string or comment.
1211+
(while (if (re-search-backward (concat "^\\(" rust-top-item-beg-re "\\)")
1212+
nil 'move sign)
1213+
(rust-in-str-or-cmnt)
1214+
;; Did not find it.
1215+
(throw 'done nil)))))
1216+
t))
12031217

12041218
(defun rust-end-of-defun ()
12051219
"Move forward to the next end of defun.

0 commit comments

Comments
 (0)