通过下面的代码片段,现在这个问题可以完美解决了,只要是 ensure: t 的包都不会删除,并且会在启动完成后自动把 use-package 安装的包都添加到 custom.el 中。
注意:这个代码片段要放在第一次使用 use-package 之前。
;; package.el updates the saved version of package-selected-packages correctly only
;; after custom-file has been loaded, which is a bug. We work around this by adding
;; the required packages to package-selected-packages after startup is complete.
;; Make `package-autoremove' work with `use-package'
(defvar use-package-selected-packages '(use-package)
"Packages pulled in by use-package.")
(eval-and-compile
(define-advice use-package-handler/:ensure (:around (fn name-symbol keyword args rest state) select)
(let ((items (funcall fn name-symbol keyword args rest state)))
(dolist (ensure args items)
(let ((package
(or (and (eq ensure t) (use-package-as-symbol name-symbol))
ensure)))
(when package
(when (consp package)
(setq package (car package)))
(push `(add-to-list 'use-package-selected-packages ',package) items)))))))
(when (fboundp 'package--save-selected-packages)
(add-hook 'after-init-hook
(lambda ()
(package--save-selected-packages
(seq-uniq (append use-package-selected-packages package-selected-packages))))))