jwiegley/use-package

A Useful Recipe: Interactively inspect what `form` `use-package` expands to under various scenarios -- minimal expansion, compilation etc.

emacksnotes opened this issue · 2 comments

Not a issue but a recipe ...

I wonder what variables apart from byte-compile-current-file affects the macroexpansion of use-package. If there are other such variables, they can be prompted for and plugged in to the env bindings below.

Slightly formalized the goings on in #1032

(advice-add 'pp-macroexpand-last-sexp :around
	    (defun pp-macroexpand-last-sexp--around
		(orig-fun &rest orig-args)
	      (pcase-let*
		  ((`(,arg)
		    orig-args)
		   (sexp (pp-last-sexp))
		   (env (when (eq 'use-package (car sexp))
			  `((byte-compile-current-file ,(yes-or-no-p "Byte compilation"))
			    (use-package-expand-minimally ,(yes-or-no-p "Minimal"))))))
		(funcall `(lambda ()
			    ,(macroexp-let* `(,@env)
					    `(progn
					       (if ',arg
						   (save-excursion
						     (insert "\n\n")
						     (apply ,orig-fun ',orig-args))
						 (apply ,orig-fun ',orig-args)))))))))

;; (advice-remove 'pp-macroexpand-last-sexp 'pp-macroexpand-last-sexp--around)

Create a quick binding for the above command

(local-set-key (kbd "C-c C-c") #'pp-macroexpand-last-sexp)

Insert the following in to *scratch* buffer

(use-package rainbow-mode
  :functions (rainbow-x-color-luminance)
  :config
  (rainbow-x-color-luminance "cyan"))

(dolist (elt list value)
  (setq value (cons elt value)))

Put the cursor after any of the above two forms and do C-u C-c C-c and see what happens ...

For example, for byte compilation and minimal scenario I get

(progn
  (eval-and-compile
    (declare-function rainbow-x-color-luminance #1="rainbow-mode")
    (eval-when-compile
      (with-demoted-errors "Cannot load rainbow-mode: %S" nil
			   (unless
			       (featurep 'rainbow-mode)
			     (load #1# nil t)))))
  (require 'rainbow-mode nil nil)
  (rainbow-x-color-luminance "cyan")
  t)

For no byte-compiled, and minimal scenario, I get

(progn
  (require 'rainbow-mode nil nil)
  (rainbow-x-color-luminance "cyan")
  t)

Here is another variation of the above advice ... This uses eval.

(use-package use-package
  :config (advice-add 'pp-macroexpand-last-sexp :around
		      (defun pp-macroexpand-last-sexp--around
			  (orig-fun &rest orig-args)
			(pcase-let*
			    ((`(,arg)
			      orig-args)
			     (sexp (pp-last-sexp))
			     (env (append
				   (when (eq 'use-package (car sexp))
				     `((byte-compile-current-file ,(yes-or-no-p "Byte compilation"))
				       (use-package-expand-minimally ,(yes-or-no-p "Minimal")))))))
			  (eval `(let ,env
				   (if ',arg
				       (save-excursion
					 (insert "\n\n")
					 (apply ',orig-fun ',orig-args))
				     (apply ',orig-fun ',orig-args))))))))