[已解决] Emacs 27, rust-mode, 如何让单引号自动的 autopair, 但是,单引号前面如果是 & 则例外。

多谢,似乎将 (add-to-list (make-local-variable 'electric-pair-pairs) '(?' . ?')) 替换为 (modify-syntax-entry ?' "\"" rust-mode-syntax-table) 就工作了。

下面是完整的代码:

(defvar electric-pair-inhibit-predicate-mode-chars-alist
  '((t . nil))
  "A list of major-mode and inhibit chars.

Each element is in the form of (MODE . (CHAR/CHAR-STRING/CHAR-FUNCTION ...)).

MODE
    A mode, or t for all modes.

CHAR
    A character to match the input. for example:

        ?\{

CHAR-STRING
    A pair of character and string, the character to match the input,
    the string for ‘looking-back’. for example:

        (?\{ . \":{\")

CHAR-FUNCTION
    A pair of character and function, the character to match the input,
    the function accept the input character as parameter. for example:

        (?\{ . (lambda (_c)
                 (eq ?: (char-before (1- (point))))))")

(defun electric-pair-inhibit-predicate-function (c)
  (let ((alist
         (append
          (assoc-default major-mode electric-pair-inhibit-predicate-mode-chars-alist)
          (assoc-default t          electric-pair-inhibit-predicate-mode-chars-alist))))
    (or (cl-member c
                   alist
                   :test
                   (lambda (c it)
                     (cond
                      ((characterp it) (equal c it))
                      ((and (consp it) (equal c (car it)))
                       (cond ((stringp   (cdr it)) (looking-back (cdr it) 1))
                             ((functionp (cdr it)) (funcall (cdr it) c)))))))
        (electric-pair-default-inhibit c))))

(with-eval-after-load 'elec-pair
  (setq electric-pair-inhibit-predicate
        #'electric-pair-inhibit-predicate-function))
		
(add-to-list 'electric-pair-inhibit-predicate-mode-chars-alist
                           '(rust-mode . ((?' . "&'"))))
						   
(modify-syntax-entry ?' "\"" rust-mode-syntax-table)						   

下面的代码必须用 setq, 用 setq-local 无效。

(setq electric-pair-inhibit-predicate
        #'electric-pair-inhibit-predicate-function)