commit 367f7c7cc2213ce8b949fbbdb42353fb2441d452 Author: Aaron L. Zeng Date: Mon Oct 12 16:36:02 2026 -0400 Don't insert "--" when auto-filling HTML comments * lisp/textmodes/sgml-mode.el (html-mode): Use default 'comment-line-break-function', i.e. 'comment-indent-new-line' (bug#82043). diff --git a/lisp/textmodes/sgml-mode.el b/lisp/textmodes/sgml-mode.el index 19252b1db60..eadc3e28f6c 100644 --- a/lisp/textmodes/sgml-mode.el +++ b/lisp/textmodes/sgml-mode.el @@ -2423,6 +2423,9 @@ To work around that, do: (setq-local sgml-face-tag-alist html-face-tag-alist) (setq-local sgml-tag-help html-tag-help) (setq-local sgml-whitespace-sensitive-tags '("pre" "textarea")) + ;; Override SGML-specific function of parent sgml-mode + ;; that inserts "--" unnecessary in HTML and derived modes. + (setq-local comment-line-break-function #'comment-indent-new-line) (setq-local outline-regexp "^.*<[Hh][1-6]\\>") (setq-local outline-heading-end-regexp "") (setq-local outline-level commit 25427d84fb3f54cb1da358ab1df288450a6ec5fe Author: Juri Linkov Date: Tue Oct 27 19:47:28 2026 +0200 Fix comment-related values in mhtml-ts-mode * lisp/textmodes/mhtml-ts-mode.el (mhtml-ts-mode--comment-setup): Sync values of 'comment-start-skip' and 'comment-end-skip' for html from sgml-mode (bug#82043). diff --git a/lisp/textmodes/mhtml-ts-mode.el b/lisp/textmodes/mhtml-ts-mode.el index b917ddf9ab4..95b2d57d250 100644 --- a/lisp/textmodes/mhtml-ts-mode.el +++ b/lisp/textmodes/mhtml-ts-mode.el @@ -393,10 +393,10 @@ Return nil if there is no name or if NODE is not a defun node." (pcase lang ('html (setq-local comment-start "") - (setq-local comment-end-skip nil)) + (setq-local comment-end-skip "[ \t]*--[ \t\n]*>")) ('css (setq-local comment-start "/*") (setq-local comment-start-skip "/\\*+[ \t]*") commit d1de756db7073f577bc1ae1a19745dbf6305bd6b Merge: d9a20e25aa7 b0b7d5a9224 Author: Eli Zaretskii Date: Tue Oct 27 14:52:37 2026 +0200 Merge branch 'master' of git.savannah.gnu.org:/srv/git/emacs commit b0b7d5a9224149483c20196355375e6c442cff09 Author: Sean Whitton Date: Tue Oct 27 12:14:59 2026 +0000 VC show-log-entry impls: Guard recentering on window buffer check * lisp/vc/vc-git.el (vc-git-show-log-entry): * lisp/vc/vc.el (vc-default-show-log-entry): Don't recenter unless the selected window's buffer is the current buffer. This is relevant when this code is called under vc-run-delayed. diff --git a/lisp/vc/vc-git.el b/lisp/vc/vc-git.el index becf18a9f2d..02d19ea8e01 100644 --- a/lisp/vc/vc-git.el +++ b/lisp/vc/vc-git.el @@ -2033,7 +2033,8 @@ or BRANCH^ (where \"^\" can be repeated)." (1+ (length (match-string 0 revision)))) (t nil)))) (beginning-of-line) - (when (memq 'long vc-log-view-types) + (when (and (memq 'long vc-log-view-types) + (eq (window-buffer) (current-buffer))) (recenter-top-bottom 0)))) (defun vc-git-expanded-log-entry (revision) diff --git a/lisp/vc/vc.el b/lisp/vc/vc.el index 9e2ae79f4d5..d0d3a7790d0 100644 --- a/lisp/vc/vc.el +++ b/lisp/vc/vc.el @@ -5629,7 +5629,8 @@ to provide the `find-revision' operation instead." (defun vc-default-show-log-entry (_backend rev) (with-no-warnings (log-view-goto-rev rev)) - (when (memq 'long vc-log-view-types) + (when (and (memq 'long vc-log-view-types) + (eq (window-buffer) (current-buffer))) (recenter-top-bottom 0))) (defun vc-default-comment-history (backend file) commit e637e1270d886d224ba5162bc4c330fedc3e0be0 Author: Sean Whitton Date: Tue Oct 27 12:07:54 2026 +0000 dired-rename-file: Don't copy-file through a symlink * lisp/dired-aux.el (dired-rename-file): Don't copy-file through a symlink, instead replace the symlink. diff --git a/lisp/dired-aux.el b/lisp/dired-aux.el index b65b639c826..999e0aada25 100644 --- a/lisp/dired-aux.el +++ b/lisp/dired-aux.el @@ -2401,6 +2401,9 @@ unless OK-IF-ALREADY-EXISTS is non-nil." (file-is-dir-p (copy-directory file newname t)) (t + (when (and ok-if-already-exists + (file-symlink-p newname)) + (delete-file newname)) (copy-file file newname ok-if-already-exists t t t))) (handler-bind commit 82d112e6090dfc86d9a81fb33f3e76da9bec9242 Author: Sean Whitton Date: Tue Oct 27 12:07:17 2026 +0000 ; * lisp/dired-aux.el (dired-rename-file): Reindent. diff --git a/lisp/dired-aux.el b/lisp/dired-aux.el index 87cacd02382..b65b639c826 100644 --- a/lisp/dired-aux.el +++ b/lisp/dired-aux.el @@ -2361,10 +2361,10 @@ Dired renames them using `vc-rename-file'." Signal a `file-already-exists' error if a file NEWNAME already exists unless OK-IF-ALREADY-EXISTS is non-nil." (let* ((file-is-dir-p (file-directory-p file)) - (file-base (file-name-nondirectory file)) - (newname (if (string-empty-p (file-name-nondirectory newname)) - (concat newname file-base) - newname))) + (file-base (file-name-nondirectory file)) + (newname (if (string-empty-p (file-name-nondirectory newname)) + (concat newname file-base) + newname))) (dired-handle-overwrite newname) (dired-maybe-create-dirs (file-name-directory newname)) (if-let* (dired-vc-rename-file commit ce103a4271628d7fbb5d971661a61d9b10668b7d Author: Sean Whitton Date: Tue Oct 27 11:54:42 2026 +0000 dired-rename-file: Pass NO-QUERY non-nil to set-visited-file-name * lisp/dired-aux.el (dired-rename-file): Pass NO-QUERY non-nil to set-visited-file-name, given comment stating intention to silently update the visited file name. diff --git a/lisp/dired-aux.el b/lisp/dired-aux.el index d146f76e5a7..87cacd02382 100644 --- a/lisp/dired-aux.el +++ b/lisp/dired-aux.el @@ -2421,7 +2421,7 @@ unless OK-IF-ALREADY-EXISTS is non-nil." ;; Silently rename the visited file of any buffer visiting this file. (and (get-file-buffer file) (with-current-buffer (get-file-buffer file) - (set-visited-file-name newname nil t))) + (set-visited-file-name newname t t))) (dired-remove-file file) ;; See if it's an inserted subdir, and rename that, too. (when file-is-dir-p commit ab2fa964ce98efccbf83fb336c033be0fda3dfb3 Author: Sean Whitton Date: Tue Oct 27 11:54:01 2026 +0000 dired-rename-file: Avoid vc-delete-file killing the buffer * lisp/vc/vc.el (vc-delete-file): New KEEP argument. When we create a buffer visiting FILE ourselves, be sure to kill it. * lisp/dired-aux.el (dired-rename-file): Hoist modifying NEWNAME for the sake of calls to set-visited-file-name and `dired-rename-subdir'. * test/lisp/vc/vc-tests/vc-test-misc.el (vc-test-dired-rename-file-between-repos): Assert vc-delete-file didn't kill the buffer. diff --git a/lisp/dired-aux.el b/lisp/dired-aux.el index f355ea3e632..d146f76e5a7 100644 --- a/lisp/dired-aux.el +++ b/lisp/dired-aux.el @@ -2360,7 +2360,11 @@ Dired renames them using `vc-rename-file'." "Rename FILE to NEWNAME. Signal a `file-already-exists' error if a file NEWNAME already exists unless OK-IF-ALREADY-EXISTS is non-nil." - (let ((file-is-dir-p (file-directory-p file))) + (let* ((file-is-dir-p (file-directory-p file)) + (file-base (file-name-nondirectory file)) + (newname (if (string-empty-p (file-name-nondirectory newname)) + (concat newname file-base) + newname))) (dired-handle-overwrite newname) (dired-maybe-create-dirs (file-name-directory newname)) (if-let* (dired-vc-rename-file @@ -2370,12 +2374,7 @@ unless OK-IF-ALREADY-EXISTS is non-nil." (vc-backend file))) (file-root (vc-root-dir file-backend (file-name-directory file)))) - (let* ((file-base (file-name-nondirectory file)) - (newname (if (string-empty-p - (file-name-nondirectory newname)) - (concat newname file-base) - newname)) - (newname-backend (ignore-errors + (let* ((newname-backend (ignore-errors (vc-responsible-backend newname))) (newname-root (and newname-backend @@ -2410,7 +2409,7 @@ unless OK-IF-ALREADY-EXISTS is non-nil." (not file-is-dir-p)) (delete-file newname) (delete-directory newname t))))) - (vc-delete-file file 'noconfirm)))) + (vc-delete-file file 'noconfirm 'keep)))) (when newname-backend (let ((newname (expand-file-name newname newname-root)) (default-directory newname-root)) diff --git a/lisp/vc/vc.el b/lisp/vc/vc.el index 2ef13125c3f..9e2ae79f4d5 100644 --- a/lisp/vc/vc.el +++ b/lisp/vc/vc.el @@ -5208,14 +5208,15 @@ backend to NEW-BACKEND, and unregister FILE from the current backend. (vc-checkin file new-backend comment (stringp comment))))) ;;;###autoload -(defun vc-delete-file (file-or-files &optional noconfirm) +(defun vc-delete-file (file-or-files &optional noconfirm keep) "Delete file and mark it as such in the version control system. If called interactively, read FILE-OR-FILES, defaulting to the current buffer's file name if it's under version control. When called from Lisp, FILE-OR-FILES can be a file name or a list of file names. When called from Lisp, optional argument NOCONFIRM non-nil means don't -prompt to confirm deletion. +prompt to confirm deletion, and optional argument KEEP non-nil means not +to kill buffers visiting any of FILE-OR-FILES. For some VCS, FILE-OR-FILES can include directories. These are recursively deleted." (interactive (list (read-file-name "VC delete file: " nil @@ -5260,7 +5261,7 @@ These are recursively deleted." (vc-file-clearprops file) ;; Make sure the buffer is killed and *vc-dir* buffers are ;; updated after this. - (vc-resynch-buffer file nil t))) + (vc-resynch-buffer file keep t))) ;; Alist associating files to delete with their backends. deletions-by-backend) (dolist (file file-or-files) @@ -5272,9 +5273,15 @@ These are recursively deleted." (null make-backup-files) (backup-file-name-p file) (not (file-exists-p file))) - (with-current-buffer (or buf (find-file-noselect file)) - (let ((backup-inhibited nil)) - (backup-buffer)))) + ;; If we reuse BUF, KEEP determines whether we kill it. + ;; But if we create a buffer visiting FILE ourselves then we + ;; kill that as soon as we're finished with it. + (let ((our-buf (and (null buf) (find-file-noselect file)))) + (unwind-protect + (with-current-buffer (or buf our-buf) + (let ((backup-inhibited nil)) + (backup-buffer))) + (when our-buf (kill-buffer our-buf))))) (if backend (push file (alist-get backend deletions-by-backend nil nil #'eq)) diff --git a/test/lisp/vc/vc-tests/vc-test-misc.el b/test/lisp/vc/vc-tests/vc-test-misc.el index c8c4025beee..5f932ffadfc 100644 --- a/test/lisp/vc/vc-tests/vc-test-misc.el +++ b/test/lisp/vc/vc-tests/vc-test-misc.el @@ -712,7 +712,12 @@ See bug#80803 and bug#80967." ;; Test moving between repos with the same backend. (create-repo 'Git git1 "foo.txt") (create-repo 'Git git2 "bar.txt") - (do-rename "git1/" "foo.txt" "../git2/baz.txt" nil) + (let ((buf (find-file-noselect "git1/foo.txt"))) + (unwind-protect + (progn + (do-rename "git1/" "foo.txt" "../git2/baz.txt" nil) + (should (buffer-live-p buf))) + (kill-buffer buf))) (let ((default-directory git1)) (should (eq (vc-state "foo.txt" 'Git) 'removed)) (should-not (file-exists-p "foo.txt"))) commit d9a20e25aa74b015aacd60845ece414a16f8dfb1 Merge: 07cc448fe84 ee8621b8802 Author: Eli Zaretskii Date: Tue Oct 27 13:33:18 2026 +0200 Merge branch 'master' of git.savannah.gnu.org:/srv/git/emacs commit ee8621b880252f9ec8ff6843e3a2cb250bfc5594 Author: Sean Whitton Date: Tue Oct 27 10:29:49 2026 +0000 dired-rename-file: Undo copying when vc-delete-file signals an error * lisp/dired-aux.el (dired-rename-file): Instead of duplicating an error check from vc-delete-file, use handler-bind to undo our work in the event of an error. * test/lisp/vc/vc-tests/vc-test-misc.el (vc-test-dired-rename-file-between-repos): Assert that we undid our copy. diff --git a/lisp/dired-aux.el b/lisp/dired-aux.el index 9afb4a539ec..f355ea3e632 100644 --- a/lisp/dired-aux.el +++ b/lisp/dired-aux.el @@ -2383,9 +2383,6 @@ unless OK-IF-ALREADY-EXISTS is non-nil." (file-name-directory newname))))) (if (equal file-root newname-root) (vc-rename-file file newname ok-if-already-exists) - (when (eq (vc-state file) 'edited) - (error "Please commit or undo your changes before moving %s" - file)) (let ((already-exists (file-exists-p newname))) ;; The delete commands for several VCS (at least Git and ;; Mercurial) will fail if asked to remove a directory @@ -2407,7 +2404,13 @@ unless OK-IF-ALREADY-EXISTS is non-nil." (t (copy-file file newname ok-if-already-exists t t t))) - (vc-delete-file file 'noconfirm))) + (handler-bind + ((error (lambda (_) + (if (or (stringp target) + (not file-is-dir-p)) + (delete-file newname) + (delete-directory newname t))))) + (vc-delete-file file 'noconfirm)))) (when newname-backend (let ((newname (expand-file-name newname newname-root)) (default-directory newname-root)) diff --git a/test/lisp/vc/vc-tests/vc-test-misc.el b/test/lisp/vc/vc-tests/vc-test-misc.el index 8281c83f439..c8c4025beee 100644 --- a/test/lisp/vc/vc-tests/vc-test-misc.el +++ b/test/lisp/vc/vc-tests/vc-test-misc.el @@ -706,6 +706,7 @@ See bug#80803 and bug#80967." (write-region "foo" nil "git1/foo.txt") (should-error (do-rename "git1/" "foo.txt" "../git2/baz.txt" nil)) + (should-not (file-exists-p "git2/baz.txt")) (reset) ;; Test moving between repos with the same backend. commit 07cc448fe84ea187ba2a45d0ee70a78a61bc9eaf Author: Eli Zaretskii Date: Tue Oct 27 12:27:36 2026 +0200 ; * etc/NEWS: Fix last change. diff --git a/etc/NEWS b/etc/NEWS index 69f1245cf10..62c6d39eb4d 100644 --- a/etc/NEWS +++ b/etc/NEWS @@ -24,9 +24,9 @@ applies, and please also update docstrings as needed. * Installation Changes in Emacs 32.1 -** Changed startup options for emacsclient in emacsclient.desktop -The --display=$DISPLAY command line option is replaced with ---reuse-frame in the emacsclient command line options, to make +** Changed startup options for 'emacsclient' in "emacsclient.desktop". +The '--display=$DISPLAY' command-line option is replaced with +'--reuse-frame' in the 'emacsclient' command-line options, to make it compatible with both X11 and Wayland. commit 38524173a946636b30eb65784dac15396bb77d7f Author: Eli Zaretskii Date: Tue Oct 27 12:22:48 2026 +0200 ; Another minor tweak of info.el for tricksy node references * lisp/info.el (Info-node-ref-re): Fix regexp, again, this time not to require a period or comma after a node reference -- because a quoted node might not have them. (Info-fontify-node): Don't be fooled by parentheses in quoted node names, when fontifying menu entries. diff --git a/lisp/info.el b/lisp/info.el index 28c32501a85..01816e957f1 100644 --- a/lisp/info.el +++ b/lisp/info.el @@ -3004,7 +3004,7 @@ Value is the node name, a string." ;; LABEL := [^:,.]+ | TEXT ;; NODE := [^:,.]+ | TEXT (defconst Info-node-ref-re - "\\(\\(\\(([^)]*)\\)?\\(\\([^]+\\)\\|\\([^:]+\\)\\)::\\)\\|\\(\\(\\([^]+\\)\\|\\([^:]+\\)\\):[ \n\t]*\\(([^)]*)\\)?\\(\\(\\([^]+\\)\\)\\|\\([^,.]+\\)\\)[ \t]*[.,]\\)\\)" + "\\(\\(\\(([^)]*)\\)?\\(\\([^]+\\)\\|\\([^:]+\\)\\)::\\)\\|\\(\\(\\([^]+\\)\\|\\([^:]+\\)\\):[ \n\t]*\\(([^)]*)\\)?\\(\\(\\([^]+\\)\\)\\|\\([^,.]+\\)\\)[ \t]*[.,]?\\)\\)" "Regexp to match an Info node reference in a cross-reference or a menu. Supports labels and node names quoted with DEL characters.") @@ -5513,10 +5513,13 @@ and so should be rendered as makeinfo produced them.") (if (and Info-fontify-visited-nodes (save-match-data (let* ((node (buffer-substring node-beg node-end)) + (quoted (string-prefix-p "" node)) ;; Remove DEL-quoting, if any (node (string-replace "" "" node)) (external-link-p - (string-match "\\`(\\([^)]+\\))\\([^)]*\\)" node)) + (and (not quoted) + (string-match + "\\`(\\([^)]+\\))\\([^)]*\\)" node))) (file (if external-link-p (file-name-nondirectory (match-string-no-properties 1 node)) commit 8811a4f971261b51941726388e5afaf60397d101 Author: Johan Myréen Date: Sat Oct 10 17:47:40 2026 +0300 etc/emacsclient.desktop: Replace --display with --reuse-frame * etc/emacsclient.desktop: Replace the --display command line parameter in the Exec= line, and replace it with --reuse-frame (bug#82006). * etc/NEWS: Document the change. diff --git a/etc/NEWS b/etc/NEWS index 21b3bb6ef94..69f1245cf10 100644 --- a/etc/NEWS +++ b/etc/NEWS @@ -24,6 +24,11 @@ applies, and please also update docstrings as needed. * Installation Changes in Emacs 32.1 +** Changed startup options for emacsclient in emacsclient.desktop +The --display=$DISPLAY command line option is replaced with +--reuse-frame in the emacsclient command line options, to make +it compatible with both X11 and Wayland. + * Startup Changes in Emacs 32.1 diff --git a/etc/emacsclient.desktop b/etc/emacsclient.desktop index 4395d3b02bc..cfbd4d97979 100644 --- a/etc/emacsclient.desktop +++ b/etc/emacsclient.desktop @@ -3,7 +3,7 @@ Name=Emacs (Client) GenericName=Text Editor Comment=Edit text MimeType=text/english;text/plain;text/x-makefile;text/x-c++hdr;text/x-c++src;text/x-chdr;text/x-csrc;text/x-java;text/x-moc;text/x-pascal;text/x-tcl;text/x-tex;application/x-shellscript;text/x-c;text/x-c++;x-scheme-handler/org-protocol; -Exec=sh -c "if [ -n \\"\\$*\\" ]; then exec emacsclient --alternate-editor= --display=\\"\\$DISPLAY\\" \\"\\$@\\"; else exec emacsclient --alternate-editor= --create-frame; fi" sh %F +Exec=sh -c "if [ -n \\"\\$*\\" ]; then exec emacsclient --alternate-editor= --reuse-frame \\"\\$@\\"; else exec emacsclient --alternate-editor= --create-frame; fi" sh %F Icon=emacs Type=Application Terminal=false commit 79ae56d026d5fddc3c1b67b76d97b37ce608211e Author: David Ponce Date: Tue Oct 27 10:06:31 2026 +0100 Remove unnecessary calls to 'frame-parameters' (Bug#81916) * lisp/calendar/appt.el (appt-disp-window): Use 'frame-parameter'. * lisp/calendar/cal-x.el (calendar-frame-1): Use 'frame-visible-p'. * lisp/emulation/viper-util.el (viper-get-cursor-color): Use 'frame-parameter'. * lisp/frame.el (frame-notice-user-settings): Use 'frame-visible-p' and 'frame-parameter'. (iconify-or-deiconify-frame): Use 'frame-visible-p'. (frame-width): Define as an alias of 'frame-text-cols'. (frame-height): Define as an alias of 'frame-text-lines'. (set-frame-font): Use 'frame-width' and 'frame-height'. (set-background-color, set-foreground-color) (set-mouse-color, set-frame-name) (frame-hide-title-bar-when-maximized): Use 'frame-parameter'. * lisp/mail/rmail.el (rmail-mail-return): * lisp/menu-bar.el (menu-bar-showhide-window-divider-menu): * nlisp/et/browse-url.el (browse-url-emacs-display): * lisp/play/gamegrid.el (gamegrid-make-mono-x-face): * lisp/talk.el (talk-connect, talk-disconnect): * lisp/textmodes/ispell.el (ispell-display-buffer): * lisp/vc/ediff-init.el (ediff-frame-unsplittable-p): Use 'frame-parameter'. * lisp/vc/ediff-wind.el (ediff-skip-unsuitable-frames): Use 'frame-parameter'. (ediff-make-frame-position): Use 'frame-position'. diff --git a/lisp/calendar/appt.el b/lisp/calendar/appt.el index f12a51c3dc9..fb4014f262b 100644 --- a/lisp/calendar/appt.el +++ b/lisp/calendar/appt.el @@ -429,7 +429,7 @@ separate appointment." (when (minibufferp) (other-window 1) (and (minibufferp) (display-multi-frame-p) (other-frame 1))) - (if (cdr (assq 'unsplittable (frame-parameters))) + (if (frame-parameter nil 'unsplittable) ;; In an unsplittable frame, use something somewhere else. (progn (set-buffer appt-disp-buf) diff --git a/lisp/calendar/cal-x.el b/lisp/calendar/cal-x.el index 3ddc497c7e8..b2eac615401 100644 --- a/lisp/calendar/cal-x.el +++ b/lisp/calendar/cal-x.el @@ -83,7 +83,7 @@ Relevant if `calendar-setup' has the value `one-frame'." Runs `calendar-after-frame-setup-hook', selects frame, iconifies if needed." (run-hooks 'calendar-after-frame-setup-hook) (select-frame frame) - (if (eq 'icon (cdr (assoc 'visibility (frame-parameters frame)))) + (if (eq 'icon (frame-visible-p frame)) (iconify-or-deiconify-frame))) ;; c-d-d is only called after (diary) has been run. diff --git a/lisp/emulation/viper-util.el b/lisp/emulation/viper-util.el index 2e42b9490f3..64f86072b8b 100644 --- a/lisp/emulation/viper-util.el +++ b/lisp/emulation/viper-util.el @@ -74,7 +74,7 @@ (define-obsolete-function-alias 'viper-color-display-p #'display-color-p "29.1") (defun viper-get-cursor-color (&optional _frame) - (cdr (assoc 'cursor-color (frame-parameters)))) + (frame-parameter nil 'cursor-color)) (defmacro viper-frame-value (variable) "Return the value of VARIABLE local to the current frame, if there is one. diff --git a/lisp/frame.el b/lisp/frame.el index 9a6f0f44300..fca62e24d64 100644 --- a/lisp/frame.el +++ b/lisp/frame.el @@ -623,8 +623,7 @@ there (in decreasing order of priority)." ;; If the user has to position the window, ;; Emacs doesn't know its real position until ;; the frame is seen to be visible. - (while (not (cdr (assq 'visibility - (frame-parameters frame-initial-frame)))) + (while (not (frame-visible-p frame-initial-frame)) (sleep-for 1)) (setq parms (frame-parameters frame-initial-frame)) @@ -705,8 +704,7 @@ there (in decreasing order of priority)." (car (or (filtered-frame-list (lambda (frame) - (eq (cdr (assq 'minibuffer - (frame-parameters frame))) + (eq (frame-parameter frame 'minibuffer) 'only))) (minibuffer-frame-list)))) (new-minibuffer (minibuffer-window new-surrogate))) @@ -1339,7 +1337,7 @@ When `switch-to-buffer-obey-display-actions' is non-nil, (defun iconify-or-deiconify-frame () "Iconify the selected frame, or deiconify if it's currently an icon." (interactive) - (if (eq (cdr (assq 'visibility (frame-parameters))) t) + (if (eq (frame-visible-p) t) (iconify-frame) (make-frame-visible))) @@ -1881,25 +1879,8 @@ is given and non-nil, the unwanted frames are iconified instead." ;;;; Convenience functions for accessing and interactively changing ;;;; frame parameters. -(defun frame-height (&optional frame) - "Return number of lines available for display on FRAME. -If FRAME is omitted, describe the currently selected frame. -Exactly what is included in the return value depends on the -window-system and toolkit in use - see `frame-pixel-height' for -more details. The lines are in units of the default font height. - -The result is roughly related to the frame pixel height via -height in pixels = height in lines * `frame-char-height'. -However, this is only approximate, and is complicated e.g. by the -fact that individual window lines and menu bar lines can have -differing font heights." - (cdr (assq 'height (frame-parameters frame)))) - -(defun frame-width (&optional frame) - "Return number of columns available for display on FRAME. -If FRAME is omitted, describe the currently selected frame." - (cdr (assq 'width (frame-parameters frame)))) - +(defalias 'frame-width #'frame-text-cols) +(defalias 'frame-height #'frame-text-lines) (defalias 'frame-border-width #'frame-internal-border-width) (defalias 'frame-pixel-width #'frame-native-width) (defalias 'frame-pixel-height #'frame-native-height) @@ -1977,11 +1958,9 @@ Customization settings." height width) (dolist (f frame-list) (when (display-multi-font-p f) - (if keep-size - (setq height (* (frame-parameter f 'height) - (frame-char-height f)) - width (* (frame-parameter f 'width) - (frame-char-width f)))) + (when keep-size + (setq height (* (frame-height f) (frame-char-height f)) + width (* (frame-width f) (frame-char-width f)))) ;; When set-face-attribute is called for :font, Emacs ;; guesses the best font according to other face attributes ;; (:width, :weight, etc.) so reset them too (Bug#2476). @@ -2032,15 +2011,13 @@ To get the frame's current background color, use `frame-parameters'." (modify-frame-parameters (selected-frame) (list (cons 'background-color color-name))) (or window-system - (face-set-after-frame-default (selected-frame) - (list - (cons 'background-color color-name) - ;; Pass the foreground-color as - ;; well, if defined, to avoid - ;; losing it when faces are reset - ;; to their defaults. - (assq 'foreground-color - (frame-parameters)))))) + (face-set-after-frame-default + (selected-frame) + (list + (cons 'background-color color-name) + ;; Pass the foreground-color as well, if defined, to avoid + ;; losing it when faces are reset to their defaults. + (cons 'foreground-color (frame-parameter nil 'foreground-color)))))) (defun set-foreground-color (color-name) "Set the foreground color of the selected frame to COLOR-NAME. @@ -2050,15 +2027,13 @@ To get the frame's current foreground color, use `frame-parameters'." (modify-frame-parameters (selected-frame) (list (cons 'foreground-color color-name))) (or window-system - (face-set-after-frame-default (selected-frame) - (list - (cons 'foreground-color color-name) - ;; Pass the background-color as - ;; well, if defined, to avoid - ;; losing it when faces are reset - ;; to their defaults. - (assq 'background-color - (frame-parameters)))))) + (face-set-after-frame-default + (selected-frame) + (list + (cons 'foreground-color color-name) + ;; Pass the background-color as well, if defined, to avoid + ;; losing it when faces are reset to their defaults. + (cons 'background-color (frame-parameter nil 'background-color)))))) (defun set-cursor-color (color-name) "Set the text cursor color of the selected frame to COLOR-NAME. @@ -2077,11 +2052,10 @@ customizing the `cursor' face." When called interactively, prompt for the name of the color to use. To get the frame's current mouse color, use `frame-parameters'." (interactive (list (read-color "Mouse color: "))) - (modify-frame-parameters (selected-frame) - (list (cons 'mouse-color - (or color-name - (cdr (assq 'mouse-color - (frame-parameters)))))))) + (modify-frame-parameters + (selected-frame) + (list (cons 'mouse-color + (or color-name (frame-parameter nil 'mouse-color)))))) (defun set-border-color (color-name) "Set the color of the border of the selected frame to COLOR-NAME. @@ -2134,7 +2108,7 @@ When called interactively, prompt for the name of the frame. On text terminals, the frame name is displayed on the mode line. On graphical displays, it is displayed on the frame's title bar." (interactive - (let ((default (cdr (assq 'name (frame-parameters))))) + (let ((default (frame-parameter nil 'name))) (list (read-string (format-prompt "Frame name" default) nil nil default)))) (modify-frame-parameters (selected-frame) @@ -3780,7 +3754,7 @@ Offer NUMBER as default value, if it is a natural number." If FRAME isn't maximized, show the title bar." (set-frame-parameter frame 'undecorated - (eq (alist-get 'fullscreen (frame-parameters frame)) 'maximized))) + (eq (frame-parameter frame 'fullscreen) 'maximized))) (define-obsolete-function-alias 'frame--current-backround-mode #'frame--current-background-mode "30.1") diff --git a/lisp/mail/rmail.el b/lisp/mail/rmail.el index f7770b047b9..b9822653f63 100644 --- a/lisp/mail/rmail.el +++ b/lisp/mail/rmail.el @@ -3797,8 +3797,7 @@ to switch to." ((or (null (delq (selected-frame) (visible-frame-list))) (not (or (window-dedicated-p (frame-selected-window)) (and pop-up-frames (one-window-p)) - (cdr (assq 'mail-dedicated-frame - (frame-parameters)))))) + (frame-parameter nil 'mail-dedicated-frame)))) (let (rmail-flag summary-buffer) (unless (one-window-p) (with-current-buffer diff --git a/lisp/menu-bar.el b/lisp/menu-bar.el index 825fcc7a5fd..83bd446fa09 100644 --- a/lisp/menu-bar.el +++ b/lisp/menu-bar.el @@ -898,11 +898,9 @@ The selected font will be the default on both the existing and future frames." :visible (memq (window-system) '(x w32)) :button (:radio . (and (window-divider-width-valid-p - (cdr (assq 'bottom-divider-width - (frame-parameters)))) + (frame-parameter nil 'bottom-divider-width)) (window-divider-width-valid-p - (cdr (assq 'right-divider-width - (frame-parameters)))))))) + (frame-parameter nil 'right-divider-width)))))) (define-key menu [right-only] '(menu-item "Right Only" menu-bar-right-window-divider @@ -910,11 +908,9 @@ The selected font will be the default on both the existing and future frames." :visible (memq (window-system) '(x w32)) :button (:radio . (and (not (window-divider-width-valid-p - (cdr (assq 'bottom-divider-width - (frame-parameters))))) + (frame-parameter nil 'bottom-divider-width))) (window-divider-width-valid-p - (cdr (assq 'right-divider-width - (frame-parameters)))))))) + (frame-parameter nil 'right-divider-width)))))) (define-key menu [bottom-only] '(menu-item "Bottom Only" menu-bar-bottom-window-divider @@ -922,11 +918,9 @@ The selected font will be the default on both the existing and future frames." :visible (memq (window-system) '(x w32)) :button (:radio . (and (window-divider-width-valid-p - (cdr (assq 'bottom-divider-width - (frame-parameters)))) + (frame-parameter nil 'bottom-divider-width)) (not (window-divider-width-valid-p - (cdr (assq 'right-divider-width - (frame-parameters))))))))) + (frame-parameter nil 'right-divider-width))))))) (define-key menu [no-divider] '(menu-item "None" menu-bar-no-window-divider @@ -934,11 +928,9 @@ The selected font will be the default on both the existing and future frames." :visible (memq (window-system) '(x w32)) :button (:radio . (and (not (window-divider-width-valid-p - (cdr (assq 'bottom-divider-width - (frame-parameters))))) + (frame-parameter nil 'bottom-divider-width))) (not (window-divider-width-valid-p - (cdr (assq 'right-divider-width - (frame-parameters))))))))) + (frame-parameter nil 'right-divider-width))))))) menu)) (defun menu-bar-showhide-fringe-ind-customize () diff --git a/lisp/net/browse-url.el b/lisp/net/browse-url.el index 864c2e11ef9..99e4624804b 100644 --- a/lisp/net/browse-url.el +++ b/lisp/net/browse-url.el @@ -1092,7 +1092,7 @@ This is nil if the display is the same as the DISPLAY environment variable. Actually Emacs could be using several displays; this just returns the one showing the selected frame." - (let ((display (cdr-safe (assq 'display (frame-parameters))))) + (let ((display (frame-parameter nil 'display))) (and (not (equal display (getenv "DISPLAY"))) display))) diff --git a/lisp/play/gamegrid.el b/lisp/play/gamegrid.el index bc2a4b27eab..d69d6d1cfdd 100644 --- a/lisp/play/gamegrid.el +++ b/lisp/play/gamegrid.el @@ -282,8 +282,7 @@ format." (let ((face (make-face 'gamegrid-mono-x-face)) (color (face-foreground 'default))) (if (null color) - (setq color - (cdr-safe (assq 'foreground-color (frame-parameters))))) + (setq color (frame-parameter nil 'foreground-color))) (gamegrid-setup-face face color) face)) diff --git a/lisp/talk.el b/lisp/talk.el index 43b6eda562b..ed71717f671 100644 --- a/lisp/talk.el +++ b/lisp/talk.el @@ -36,7 +36,7 @@ Each element has the form (DISPLAY FRAME BUFFER).") "Connect to display DISPLAY for the Emacs talk group." (interactive "sTalk to display: ") ;; Make sure we have an entry for the current display. - (let ((mydisp (cdr (assq 'display (frame-parameters (selected-frame)))))) + (let ((mydisp (frame-parameter nil 'display))) (talk-add-display mydisp)) ;; Make sure we have an entry for the specified display. (talk-add-display display) @@ -76,7 +76,7 @@ Each element has the form (DISPLAY FRAME BUFFER).") (defun talk-disconnect () "Disconnect this display from the Emacs talk group." (interactive) - (let* ((mydisp (cdr (assq 'display (frame-parameters (selected-frame))))) + (let* ((mydisp (frame-parameter nil 'display)) (elt (assoc mydisp talk-display-alist))) (delete-frame (nth 1 elt)) (kill-buffer (nth 2 elt)) diff --git a/lisp/textmodes/ispell.el b/lisp/textmodes/ispell.el index 13b4e75d4b7..94ce37fa7e5 100644 --- a/lisp/textmodes/ispell.el +++ b/lisp/textmodes/ispell.el @@ -2812,8 +2812,7 @@ argument REFRESH, which is passed to that function as the 4th argument." (defun ispell-display-buffer (buffer) "Show BUFFER in new window above selected one. Also position fit window to BUFFER and select it." - (let* ((unsplittable - (cdr (assq 'unsplittable (frame-parameters (selected-frame))))) + (let* ((unsplittable (frame-parameter nil 'unsplittable)) (window (or (get-buffer-window buffer) (and unsplittable diff --git a/lisp/vc/ediff-init.el b/lisp/vc/ediff-init.el index c24cdd6ecd3..677b40ef7e5 100644 --- a/lisp/vc/ediff-init.el +++ b/lisp/vc/ediff-init.el @@ -1252,7 +1252,7 @@ This default should work without changes." (defsubst ediff-frame-unsplittable-p (frame) (declare (obsolete nil "29.1")) - (cdr (assq 'unsplittable (frame-parameters frame)))) + (frame-parameter frame 'unsplittable)) (defsubst ediff-get-next-window (wind prev-wind) (cond ((window-live-p wind) wind) diff --git a/lisp/vc/ediff-wind.el b/lisp/vc/ediff-wind.el index c7a9b1b349d..62ce7132c43 100644 --- a/lisp/vc/ediff-wind.el +++ b/lisp/vc/ediff-wind.el @@ -862,7 +862,7 @@ Create a new splittable frame if none is found." (* 3 window-min-height)) (if ok-unsplittable nil - (cdr (assq 'unsplittable (frame-parameters wind-frame)))))) + (frame-parameter wind-frame 'unsplittable)))) ;; remember history (setq seen-windows (cons (selected-window) seen-windows)) ;; try new window @@ -1047,9 +1047,9 @@ Create a new splittable frame if none is found." (defun ediff-make-frame-position (ctl-buffer ctl-frame-width ctl-frame-height) (with-current-buffer ctl-buffer (let* ((frame-A (window-frame ediff-window-A)) - (frame-A-parameters (frame-parameters frame-A)) - (frame-A-top (eval (cdr (assoc 'top frame-A-parameters)) t)) - (frame-A-left (eval (cdr (assoc 'left frame-A-parameters)) t)) + (frame-A-pos (frame-position frame-A)) + (frame-A-left (car frame-A-pos)) + (frame-A-top (cdr frame-A-pos)) (frame-A-width (frame-width frame-A)) (ctl-frame ediff-control-frame) horizontal-adjustment upward-adjustment commit e7a184113b991ff4e7e200091aaf8410fde13970 Author: João Távora Date: Tue Oct 27 08:24:35 2026 +0000 Eglot: rework edit-applying logic Previewing versioned edits (clangd sends these) with 'refactor-confirmation' set to 'diff' failed the version check in the temporary buffer. More importantly, the 'edits' field of a 'refactor-file-edit' operation is meant to be a function returning edits, not one applying them. It used to work because atomic-change-group returns nil. But broke on Emacs 26, where it returns t. * lisp/progmodes/eglot.el (eglot--convert-lsp-edits): New function. (eglot--apply-lsp-edits): Rename from eglot--apply-text-edits. Use eglot--convert-lsp-edits. All callers updated. (eglot--translate-workspace-edit): Return edits from the :edits function. diff --git a/lisp/progmodes/eglot.el b/lisp/progmodes/eglot.el index be7995be43e..e458b5372bf 100644 --- a/lisp/progmodes/eglot.el +++ b/lisp/progmodes/eglot.el @@ -3219,7 +3219,7 @@ uses it; didOpen then clears it and recomputes from the new (jsonrpc-notify server :textDocument/willSave params)) (when (eglot-server-capable :textDocumentSync :willSaveWaitUntil) (ignore-errors - (eglot--apply-text-edits + (eglot--apply-lsp-edits (eglot--request server :textDocument/willSaveWaitUntil params :timeout 0.5)))))) @@ -3784,7 +3784,7 @@ for which LSP on-type-formatting should be requested." (t '(:textDocument/formatting :documentFormattingProvider nil))))) (eglot-server-capable-or-lose cap) - (eglot--apply-text-edits + (eglot--apply-lsp-edits (eglot--request (eglot--current-server-or-lose) method @@ -4062,7 +4062,7 @@ for which LSP on-type-formatting should be requested." (delete-region (- (point) (length proxy)) (point)) (funcall snippet-fn (or insertText label)))) (when (cl-plusp (length additionalTextEdits)) - (eglot--apply-text-edits additionalTextEdits))) + (eglot--apply-lsp-edits additionalTextEdits))) (eglot--signal-textDocument/didChange))))))))) @@ -4277,25 +4277,28 @@ Returns a list as described in docstring of `imenu--index-alist'." ;;; Code actions and rename -(cl-defun eglot--apply-text-edits (edits &optional version silent) - "Apply LSP EDITS for current buffer using `refactor-apply-text-edits'. -Error if VERSION non-nil and doesn't match the documents'. Pass -SILENT to `refactor-apply-text-edits'." - (unless edits (cl-return-from eglot--apply-text-edits)) +(defun eglot--convert-lsp-edits (edits &optional version) + "Convert LSP EDITS to a list of (BEG END NEWTEXT) for current buffer. +Error if VERSION non-nil and doesn't match the document's." (when (and version (not (equal version eglot--docver))) (jsonrpc-error "Edits on `%s' require version %d, have %d" (current-buffer) version eglot--docver)) - (refactor-apply-text-edits - (mapcar (lambda (edit) - (eglot--dcase edit - (((TextEdit) range newText) - (cl-destructuring-bind (beg . end) (eglot-range-region range) - (list beg end newText))) - (((InsertReplaceEdit) newText replace) - (cl-destructuring-bind (beg . end) (eglot-range-region replace) - (list beg end newText))))) - edits) - :silent silent)) + (mapcar (lambda (edit) + (eglot--dcase edit + (((TextEdit) range newText) + (cl-destructuring-bind (beg . end) (eglot-range-region range) + (list beg end newText))) + (((InsertReplaceEdit) newText replace) + (cl-destructuring-bind (beg . end) (eglot-range-region replace) + (list beg end newText))))) + edits)) + +(defun eglot--apply-lsp-edits (edits &optional version silent) + "Apply LSP EDITS for current buffer using `refactor-apply-text-edits'. +Error if VERSION non-nil and doesn't match the document's. Pass +SILENT to `refactor-apply-text-edits'." + (refactor-apply-text-edits (eglot--convert-lsp-edits edits version) + :silent silent)) (cl-defun eglot--translate-workspace-edit (wedit) "Compute list of `refactor-operation' from LSP workspace edit WEDIT." @@ -4306,8 +4309,11 @@ SILENT to `refactor-apply-text-edits'." 'refactor-file-edit :file path :edits + ;; Not in a managed buffer when previewing the edits in a + ;; temporary buffer, so don't check the version then. (lambda () - (eglot--apply-text-edits edits version t)))))) + (eglot--convert-lsp-edits + edits (and eglot--managed-mode version))))))) (eglot--dbind ((WorkspaceEdit) changes documentChanges) wedit (append (mapcar commit e53afef2b0632a15efad495c7771e6c4c915e292 Author: João Távora Date: Wed Oct 21 13:44:51 2026 +0100 Refactor: only signal "No refactorings here" interactively * lisp/progmodes/refactor.el (refactor): Return nil non-interactively. * lisp/progmodes/eglot.el (eglot-code-actions): Simplify. diff --git a/lisp/progmodes/eglot.el b/lisp/progmodes/eglot.el index 2edbf6c6338..be7995be43e 100644 --- a/lisp/progmodes/eglot.el +++ b/lisp/progmodes/eglot.el @@ -4460,8 +4460,7 @@ that sub-kinds like \"source.fixAll.ruff\" map to `fix-all'." (interactive (list nil nil nil t)) (let ((rkind (eglot--refactor-kind action-kind))) (cond ((not interactive) - (cl-loop for a in (ignore-error user-error - (refactor beg end rkind)) + (cl-loop for a in (refactor beg end rkind) for data = (oref a data) ;; `rkind' may be broader than ACTION-KIND when (and (eq (oref a backend) 'eglot) diff --git a/lisp/progmodes/refactor.el b/lisp/progmodes/refactor.el index 8a67bdb0240..bec150f679e 100644 --- a/lisp/progmodes/refactor.el +++ b/lisp/progmodes/refactor.el @@ -484,10 +484,12 @@ When INTERACTIVE is nil, return the list of `refactor-action' objects." ;; ...in which case we can skip re-contacting the backend. (overlay-get refactor--suggestion-overlay 'refactor--actions) (refactor--collect beg end :rkind rkind)))) - (unless actions - (user-error (if rkind "No \"%s\" refactorings here" "No refactorings here") - rkind)) - (if interactive (refactor--read-execute-action actions) actions))) + (cond ((not interactive) actions) + ((null actions) + (user-error (if rkind "No \"%s\" refactorings here" + "No refactorings here") + rkind)) + (t (refactor--read-execute-action actions))))) (defmacro refactor--define-kind-command (name kind) "Define NAME to execute KIND refactorings between BEG and END." commit 85da9e6a7a0705cd8181c00e577d160bb60cfea4 Author: João Távora Date: Wed Oct 21 13:43:04 2026 +0100 Refactor: make eglot-code-actions a proper compatibility function * lisp/progmodes/eglot.el (eglot-code-actions): Rework from alias. Accept LSP kind strings and return LSP CodeActions. diff --git a/lisp/progmodes/eglot.el b/lisp/progmodes/eglot.el index 3202cb32593..2edbf6c6338 100644 --- a/lisp/progmodes/eglot.el +++ b/lisp/progmodes/eglot.el @@ -4454,7 +4454,24 @@ that sub-kinds like \"source.fixAll.ruff\" map to `fix-all'." `(,@(eglot--TextDocumentPositionParams) :newName ,newname))))) -(define-obsolete-function-alias 'eglot-code-actions 'refactor "32.1") +(defun eglot-code-actions (beg &optional end action-kind interactive) + "Like `refactor', but ACTION-KIND is a string." + (declare (obsolete refactor "32.1")) + (interactive (list nil nil nil t)) + (let ((rkind (eglot--refactor-kind action-kind))) + (cond ((not interactive) + (cl-loop for a in (ignore-error user-error + (refactor beg end rkind)) + for data = (oref a data) + ;; `rkind' may be broader than ACTION-KIND + when (and (eq (oref a backend) 'eglot) + (or (null action-kind) + (string-prefix-p + action-kind (or (plist-get data :kind) "")))) + collect data)) + (beg (refactor beg end rkind t)) + (t (call-interactively #'refactor))))) + (define-obsolete-function-alias 'eglot-rename 'refactor-rename "32.1") (define-obsolete-function-alias 'eglot-code-action-organize-imports 'refactor-organize-imports "32.1") commit b708ad381c927b4bda8113f7b311de71e1051fc0 Author: João Távora Date: Wed Oct 21 13:43:04 2026 +0100 Refactor: map LSP sub-kinds like "source.fixAll.ruff" to known kinds * lisp/progmodes/eglot.el (eglot--refactor-kind): New function. (refactor-backend-actions): Use it. diff --git a/lisp/progmodes/eglot.el b/lisp/progmodes/eglot.el index 4ffde894423..3202cb32593 100644 --- a/lisp/progmodes/eglot.el +++ b/lisp/progmodes/eglot.el @@ -4384,21 +4384,25 @@ edit was attempted and optionally why not." (fix-all . "source.fixAll")) "Alist mapping `refactor' kind symbols to LSP code action kinds.") +(defun eglot--refactor-kind (lsp-kind) + "Return `refactor' kind for LSP-KIND, a string, or nil. +Use the longest prefix of LSP-KIND in `eglot--refactor-kinds', so +that sub-kinds like \"source.fixAll.ruff\" map to `fix-all'." + (cl-loop for k = lsp-kind + then (and (string-match "\\.[^.]*\\'" k) + (substring k 0 (match-beginning 0))) + while k + thereis (car (rassoc k eglot--refactor-kinds)))) + (cl-defmethod refactor-backend-actions ((_backend (eql eglot)) beg end &key rkind callback trigger-kind) (cl-labels - ((kind (lsp-kind) - (when lsp-kind - (or (car (rassoc lsp-kind eglot--refactor-kinds)) - (let ((dot (string-match-p "\\." lsp-kind))) - (intern (replace-regexp-in-string - "\\." "-" (substring lsp-kind (if dot (1+ dot) 0)))))))) - (convert (actions) + ((convert (actions) (cl-loop for a across actions for ra = (make-instance 'refactor-action :title (plist-get a :title) - :kind (kind (plist-get a :kind)) + :kind (eglot--refactor-kind (plist-get a :kind)) :preferred (plist-get a :isPreferred) :backend 'eglot :data a) commit f6c9c1568011f4d6e6250613dda9ceb427084b64 Author: João Távora Date: Tue Oct 20 09:47:09 2026 +0100 Refactor: trim whitespace from new name in refactor-rename * lisp/progmodes/refactor.el (refactor-rename): Trim NEWNAME. diff --git a/lisp/progmodes/refactor.el b/lisp/progmodes/refactor.el index b464e13b584..8a67bdb0240 100644 --- a/lisp/progmodes/refactor.el +++ b/lisp/progmodes/refactor.el @@ -517,8 +517,8 @@ Interactively, BACKEND is chosen to be the first backend in (user-error "No backend can rename the symbol at point")) (let ((sym-name (buffer-substring-no-properties (car bounds) (cdr bounds)))) (list - (read-from-minibuffer (format "Rename `%s' to: " sym-name) - nil nil nil nil sym-name) + (string-trim (read-from-minibuffer (format "Rename `%s' to: " sym-name) + nil nil nil nil sym-name)) backend)))) (refactor-apply-changeset (refactor-backend-rename backend newname) :origin this-command)) commit 3f77399502f4912109ea69da6ac6dd5949f66915 Author: João Távora Date: Tue Oct 20 09:47:08 2026 +0100 Refactor: don't error on servers lacking code actions or rename * lisp/progmodes/eglot.el (refactor-backend-actions) (refactor-backend-rename-bounds): Decline if unsupported. diff --git a/lisp/progmodes/eglot.el b/lisp/progmodes/eglot.el index a0fde91b8f0..4ffde894423 100644 --- a/lisp/progmodes/eglot.el +++ b/lisp/progmodes/eglot.el @@ -4386,7 +4386,6 @@ edit was attempted and optionally why not." (cl-defmethod refactor-backend-actions ((_backend (eql eglot)) beg end &key rkind callback trigger-kind) - (eglot-server-capable-or-lose :codeActionProvider) (cl-labels ((kind (lsp-kind) (when lsp-kind @@ -4410,6 +4409,8 @@ edit was attempted and optionally why not." (eglot--code-action-params :beg beg :end end :only lsp-rkind :triggerKind trigger-kind))) (cond + ;; Plenty of servers don't do code actions: just offer none. + ((not (eglot-server-capable :codeActionProvider)) nil) (callback (eglot--async-request server @@ -4427,17 +4428,19 @@ edit was attempted and optionally why not." (cl-defmethod refactor-backend-rename-bounds ((_backend (eql eglot))) - (let* ((rename-support (eglot-server-capable-or-lose :renameProvider)) + (let* ((rename-support (eglot-server-capable :renameProvider)) (prepare-support (and (listp rename-support) - (plist-get rename-support :prepareProvider)))) - (cond (prepare-support - (let ((x (eglot--request (eglot--current-server-or-lose) - :textDocument/prepareRename - (eglot--TextDocumentPositionParams)))) - (cond ((null x) nil) - ((plist-get x :range) (eglot-range-region (plist-get x :range))) - ((plist-get x :defaultBehavior) (bounds-of-thing-at-point 'symbol)) - (t (eglot-range-region x))))) + (plist-get rename-support :prepareProvider))) + x) + (cond ((not rename-support) nil) ; decline, another backend may claim + (prepare-support + (setq x (eglot--request (eglot--current-server-or-lose) + :textDocument/prepareRename + (eglot--TextDocumentPositionParams))) + (cond ((null x) nil) + ((plist-get x :range) (eglot-range-region (plist-get x :range))) + ((plist-get x :defaultBehavior) (bounds-of-thing-at-point 'symbol)) + (t (eglot-range-region x)))) (t (bounds-of-thing-at-point 'symbol))))) (cl-defmethod refactor-backend-rename ((_backend (eql eglot)) newname) commit 8748e74d81f50fb76ab1d51828d515e4f768bdf2 Author: João Távora Date: Sat Oct 17 23:43:29 2026 +0100 Refactor: redo mouse events handling again Keeps 'refactor' a usable Lisp entry point with the same signature as the kind-specific commands, and avoids an internal interactive function. * lisp/progmodes/refactor.el (refactor): Rename from 'refactor--1'. Handle mouse events in interactive spec. (refactor--call-at-event): Delete. (refactor--define-kind-command): Call 'refactor'. * lisp/progmodes/eglot.el (eglot-code-actions): Plain obsolete alias to 'refactor' again. diff --git a/lisp/progmodes/eglot.el b/lisp/progmodes/eglot.el index 73a66c9dec8..a0fde91b8f0 100644 --- a/lisp/progmodes/eglot.el +++ b/lisp/progmodes/eglot.el @@ -4447,8 +4447,7 @@ edit was attempted and optionally why not." `(,@(eglot--TextDocumentPositionParams) :newName ,newname))))) -(defalias 'eglot-code-actions #'refactor--1) -(make-obsolete 'eglot-code-actions 'refactor "32.1") +(define-obsolete-function-alias 'eglot-code-actions 'refactor "32.1") (define-obsolete-function-alias 'eglot-rename 'refactor-rename "32.1") (define-obsolete-function-alias 'eglot-code-action-organize-imports 'refactor-organize-imports "32.1") diff --git a/lisp/progmodes/refactor.el b/lisp/progmodes/refactor.el index ab35ac38db7..b464e13b584 100644 --- a/lisp/progmodes/refactor.el +++ b/lisp/progmodes/refactor.el @@ -432,7 +432,8 @@ If there is only one, execute it without asking." menu-items)))))) (when chosen (refactor-backend-execute (oref chosen backend) chosen)))) -(defun refactor--1 (beg &optional end rkind interactive) +;;;###autoload +(defun refactor (beg &optional end rkind interactive) "Find refactoring actions between BEG and END, and offer to run them. If RKIND, a symbol, is non-nil, restrict search to actions of that kind @@ -440,20 +441,30 @@ and its sub-kinds; interactively with a prefix arg, choose from `refactor-kinds'. Interactively, BEG and END default to automatically calculated bounds -and a prefix argument prompts for KIND. +and a prefix argument prompts for KIND. If invoked by a mouse event, +select its window and calculate bounds where it happened. When INTERACTIVE is nil, return the list of `refactor-action' objects." (interactive - `(,@(refactor--bounds) - ,(and current-prefix-arg - (intern - (completing-read - "Kind of refactoring: " - (mapcar (lambda (kind) - (cons (symbol-name kind) kind)) - refactor-kinds) - nil t))) - t)) + (let ((posn (and (mouse-event-p last-nonmenu-event) + (event-start last-nonmenu-event)))) + (when posn (select-window (posn-window posn))) + `(,@(save-excursion + ;; Non-text-area clicks (`posn-area' non-nil) already assume + ;; correct point, but text area clicks are likely on Flymake + ;; some diagnostic and need moving before `refactor--bounds'. + (when (and posn (null (posn-area posn))) + (goto-char (posn-point posn))) + (refactor--bounds)) + ,(and current-prefix-arg + (intern + (completing-read + "Kind of refactoring: " + (mapcar (lambda (kind) + (cons (symbol-name kind) kind)) + refactor-kinds) + nil t))) + t))) (let* ((shortcut ;; Check if we can do an optimization/shortcut. ;; `refactor-suggestion' may just recently have computed @@ -483,35 +494,7 @@ When INTERACTIVE is nil, return the list of `refactor-action' objects." `(defun ,name (beg &optional end) ,(format "Execute `%s' refactorings between BEG and END." kind) (interactive (refactor--bounds)) - (refactor--1 beg end ',kind t))) - -(defun refactor--call-at-event (event what) - "Call WHAT interactively where mouse EVENT happened." - (let ((start (event-start event))) - ;; Don't `posn-set-point', don't actually set it with this click... - (with-selected-window (posn-window start) - (save-excursion - ;; ... also, only momentarily go to it if the click was actually - ;; in the text area, meaning probably user clicked a Flymake - ;; overlay. If the click was on the margin or fringe, WHAT's - ;; interactive spec will know to find actions where point was - ;; before, because that's what prompted the indicator to appear - ;; in the first place. - (unless (posn-area start) - (goto-char (posn-point start))) - (call-interactively what))))) - -;;;###autoload -(defun refactor (&optional event) - "Find refactoring actions here, and offer to run them. -Here is the active region or, if there is none, the Flymake diagnostics -or the expression at point. If EVENT is a mouse event, consider where -it happened instead of point. With a prefix argument, prompt for a kind -of refactoring from `refactor-kinds'." - (interactive (list last-nonmenu-event)) - (if (mouse-event-p event) - (refactor--call-at-event event #'refactor--1) - (call-interactively #'refactor--1))) + (refactor beg end ',kind t))) (refactor--define-kind-command refactor-organize-imports organize-imports) (refactor--define-kind-command refactor-extract extract) commit e95ed8d1fda600e23a402ad3158ccf62fde9d96a Author: João Távora Date: Fri Oct 16 21:21:13 2026 +0100 Refactor: Get rid of 'refactor-at-mouse', use only 'refactor' * lisp/progmodes/refactor.el (refactor--1): Rename from 'refactor'. (refactor--call-at-event): Rename from 'refactor--mouse-call'. No longer return lambda. (refactor): New command, for both keyboard and mouse. (refactor-at-mouse): Delete. (refactor--define-kind-command): Call 'refactor--1'. (refactor-mouse-map, refactor--mode-line-map): Bind 'refactor'. (refactor-suggestion): Say mouse-2 in indicator help-echo, mouse-1 in margin's. * lisp/progmodes/eglot.el (eglot-code-actions): Alias to 'refactor--1', but recommend 'refactor'. (eglot-code-actions-at-mouse): Alias to 'refactor'. * doc/misc/eglot.texi (Refactor and Eglot): Mention 'refactor'. diff --git a/doc/misc/eglot.texi b/doc/misc/eglot.texi index e7b303dee8a..d168c22cb58 100644 --- a/doc/misc/eglot.texi +++ b/doc/misc/eglot.texi @@ -1011,8 +1011,8 @@ first prompts for a @dfn{kind} of action, such as @code{quickfix} or A common use of code actions is fixing the Flymake error diagnostics issued by Eglot (@pxref{Top,,, Flymake, GNU Flymake manual}). Clicking -on a diagnostic with @kbd{mouse-2} invokes @code{refactor-at-mouse} -which pops up a menu of available code actions. The keymap +on a diagnostic with @kbd{mouse-2} invokes the same @code{refactor} +command, which pops up a menu of available code actions. The keymap @code{refactor-mouse-map} can be used to control the mouse binding. The other commands are shortcuts considering only one kind of action. diff --git a/lisp/progmodes/eglot.el b/lisp/progmodes/eglot.el index 06737fcfbcf..73a66c9dec8 100644 --- a/lisp/progmodes/eglot.el +++ b/lisp/progmodes/eglot.el @@ -4447,7 +4447,8 @@ edit was attempted and optionally why not." `(,@(eglot--TextDocumentPositionParams) :newName ,newname))))) -(define-obsolete-function-alias 'eglot-code-actions 'refactor "32.1") +(defalias 'eglot-code-actions #'refactor--1) +(make-obsolete 'eglot-code-actions 'refactor "32.1") (define-obsolete-function-alias 'eglot-rename 'refactor-rename "32.1") (define-obsolete-function-alias 'eglot-code-action-organize-imports 'refactor-organize-imports "32.1") @@ -4460,7 +4461,7 @@ edit was attempted and optionally why not." (define-obsolete-function-alias 'eglot-code-action-quickfix 'refactor-quickfix "32.1") (define-obsolete-function-alias 'eglot-code-actions-at-mouse - 'refactor-at-mouse "32.1") + 'refactor "32.1") (define-obsolete-variable-alias 'eglot-code-action-indications 'refactor-indications "32.1") (define-obsolete-variable-alias 'eglot-code-action-indicator diff --git a/lisp/progmodes/refactor.el b/lisp/progmodes/refactor.el index 4dfbd3d4846..ab35ac38db7 100644 --- a/lisp/progmodes/refactor.el +++ b/lisp/progmodes/refactor.el @@ -432,8 +432,7 @@ If there is only one, execute it without asking." menu-items)))))) (when chosen (refactor-backend-execute (oref chosen backend) chosen)))) -;;;###autoload -(defun refactor (beg &optional end rkind interactive) +(defun refactor--1 (beg &optional end rkind interactive) "Find refactoring actions between BEG and END, and offer to run them. If RKIND, a symbol, is non-nil, restrict search to actions of that kind @@ -484,23 +483,35 @@ When INTERACTIVE is nil, return the list of `refactor-action' objects." `(defun ,name (beg &optional end) ,(format "Execute `%s' refactorings between BEG and END." kind) (interactive (refactor--bounds)) - (refactor beg end ',kind t))) - -(defun refactor--mouse-call (what &optional update-mode-line) - "Make an interactive lambda for calling WHAT with the mouse." - (lambda (event) - (interactive "e") - (let ((start (event-start event))) - (with-selected-window (posn-window start) - (save-excursion - (unless (posn-area start) - (goto-char (posn-point start))) - (call-interactively what) - (when update-mode-line - (force-mode-line-update t))))))) - -(defalias 'refactor-at-mouse (refactor--mouse-call 'refactor) - "Like `refactor', but intended for mouse events.") + (refactor--1 beg end ',kind t))) + +(defun refactor--call-at-event (event what) + "Call WHAT interactively where mouse EVENT happened." + (let ((start (event-start event))) + ;; Don't `posn-set-point', don't actually set it with this click... + (with-selected-window (posn-window start) + (save-excursion + ;; ... also, only momentarily go to it if the click was actually + ;; in the text area, meaning probably user clicked a Flymake + ;; overlay. If the click was on the margin or fringe, WHAT's + ;; interactive spec will know to find actions where point was + ;; before, because that's what prompted the indicator to appear + ;; in the first place. + (unless (posn-area start) + (goto-char (posn-point start))) + (call-interactively what))))) + +;;;###autoload +(defun refactor (&optional event) + "Find refactoring actions here, and offer to run them. +Here is the active region or, if there is none, the Flymake diagnostics +or the expression at point. If EVENT is a mouse event, consider where +it happened instead of point. With a prefix argument, prompt for a kind +of refactoring from `refactor-kinds'." + (interactive (list last-nonmenu-event)) + (if (mouse-event-p event) + (refactor--call-at-event event #'refactor--1) + (call-interactively #'refactor--1))) (refactor--define-kind-command refactor-organize-imports organize-imports) (refactor--define-kind-command refactor-extract extract) @@ -609,8 +620,8 @@ Note additionally: (defvar refactor-mouse-map (let ((map (make-sparse-keymap))) - (define-key map [mouse-2] #'refactor-at-mouse) - (define-key map [left-margin mouse-1] #'refactor-at-mouse) + (define-key map [mouse-2] #'refactor) + (define-key map [left-margin mouse-1] #'refactor) map) "Keymap active on action indicators and clickable diagnostics.") @@ -642,7 +653,7 @@ Note additionally: (setq indicator (propertize refactor-indicator 'face 'refactor-indicator-face - 'help-echo "mouse-1: execute actions at point" + 'help-echo "mouse-2: execute actions at point" 'mouse-face 'highlight 'keymap refactor-mouse-map)) (save-excursion @@ -664,7 +675,10 @@ Note additionally: refactor-indicator-face))) ((memq 'margin refactor-indications) (propertize - "⚡" 'display `((margin left-margin) ,indicator))))) + "⚡" 'display `((margin left-margin) + ,(propertize + indicator 'help-echo + "mouse-1: execute actions at point")))))) (setq refactor--suggestion-overlay ov))))) ;; Answer the ElDoc strategy even if BUF isn't showing, else it ;; could wait for us forever (like in non-interactive tests). @@ -686,8 +700,7 @@ show `refactor-mode-line-indicator' while actions are available." (defvar refactor--mode-line-map (let ((map (make-sparse-keymap))) - (define-key map [mode-line mouse-1] - (refactor--mouse-call 'refactor-at-mouse t)) + (define-key map [mode-line mouse-1] #'refactor) map) "Keymap active on `refactor-mode-line-indicator'.") @@ -710,7 +723,7 @@ show `refactor-mode-line-indicator' while actions are available." ;; Flymake backends may use these categories if they want their ;; diagnostics to be clickable. `refactor-mouse-map' contains -;; a binding for `refactor-at-mouse'. +;; a mouse binding for `refactor'. (cl-loop for i from 1 for type in '(refactor-note refactor-warning refactor-error) commit 28a88dadb992a58bc08f33759658f52b333129eb Author: João Távora Date: Fri Oct 16 22:26:09 2026 +0100 Refactor: show suggestion indicators only in the relevant window Indicators showed in every window displaying the buffer, but stood for actions "at point" of just one of them. Clicking one elsewhere ran actions at the wrong place. * lisp/progmodes/refactor.el (refactor-suggestion): Give overlay a 'window' property. (refactor-mode-line-indicator): Show only in that window. diff --git a/lisp/progmodes/refactor.el b/lisp/progmodes/refactor.el index ad2150395fc..4dfbd3d4846 100644 --- a/lisp/progmodes/refactor.el +++ b/lisp/progmodes/refactor.el @@ -618,6 +618,7 @@ Note additionally: "A member of `eldoc-documentation-functions', for suggesting actions." (when (and refactor-indications (refactor-find-backends)) (let ((buf (current-buffer)) + (win (selected-window)) (bounds (refactor--bounds)) (use-text-p (memq 'eldoc-hint refactor-indications)) indicator blurb) @@ -648,6 +649,8 @@ Note additionally: (goto-char (car bounds)) (let ((ov (make-overlay (car bounds) (cadr bounds)))) (overlay-put ov 'refactor--actions actions) + ;; Elsewhere, the indicator could be far from point. + (overlay-put ov 'window win) (overlay-put ov 'before-string (cond @@ -690,7 +693,9 @@ show `refactor-mode-line-indicator' while actions are available." (defconst refactor-mode-line-indicator '(:eval - (when (overlay-buffer refactor--suggestion-overlay) + (when (and (overlay-buffer refactor--suggestion-overlay) + (eq (overlay-get refactor--suggestion-overlay 'window) + (selected-window))) `(" " (:propertize ,refactor-indicator face refactor-indicator-face commit a07de83c86a211a51b9d1257428079a26b596d44 Author: João Távora Date: Thu Oct 15 23:21:04 2026 +0100 Eglot: restructure manual and describe Refactor integration Code actions and renaming now come from refactor.el. Describe Eglot's use of ElDoc, Flymake, Refactor, Xref, Imenu and completion in one place, keeping commands, options and Lisp tweaks for each together. * doc/misc/eglot.texi (Top): Add new chapter to menu. (Quick Start, Eglot Features): Mention Refactor. Link features to the new chapter. (Using Eglot): Update menu. (Eglot Commands): Move refactoring commands out. (Eglot and Other Emacs Features): New chapter. (ElDoc and Eglot, Flymake and Eglot, Refactor and Eglot) (Xref and Eglot, Imenu and Eglot, Completion and Eglot): New sections. (Customizing Eglot): Update menu and cross-reference. (Customization Variables): Move Refactor options out. Update eglot-mode-map example. Drop eglot-mode-line-action-suggestion. (Other Variables): Mention refactor in eglot-stay-out-of. (More Customization): Delete, moving contents to the new sections. (Performance): Update cross-reference. diff --git a/doc/misc/eglot.texi b/doc/misc/eglot.texi index a9c96d5eb69..e7b303dee8a 100644 --- a/doc/misc/eglot.texi +++ b/doc/misc/eglot.texi @@ -98,6 +98,7 @@ read this manual from within Emacs, type @kbd{M-x eglot-manual * Quick Start:: For the impatient. * Eglot and LSP Servers:: How to work with language servers. * Using Eglot:: Important Eglot commands and variables. +* Eglot and Other Emacs Features:: How Eglot works with ElDoc, Flymake, etc. * Customizing Eglot:: Eglot customization and advanced features. * Advanced server configuration:: Fine-tune a specific language server * Multi-server support:: Use more than one server in a buffer @@ -160,11 +161,11 @@ for details. Use Eglot. Most Eglot facilities are integrated into Emacs features, such as ElDoc, -Flymake, Xref, and Imenu. However, Eglot also provides commands of its -own, mainly to perform tasks by the language server, such as @kbd{M-x -eglot-rename} (to rename an identifier across the entire project), -@kbd{M-x eglot-format} (to reformat and reindent code), and some others. -@xref{Eglot Commands}, for the detailed list of Eglot commands. +Flymake, Xref, Imenu, and Refactor (@pxref{Eglot and Other Emacs +Features}). Eglot also provides commands of its own, mainly to perform +tasks by the language server, such as @kbd{M-x eglot-format} (to +reformat and reindent code), and some others. @xref{Eglot Commands}, +for the detailed list of commands. @item That's it! @@ -403,8 +404,8 @@ commands and variables. While Eglot is enabled in a buffer, it is said to be @dfn{managing} it, using LSP and the specific capabilities of the language server to activate and enhance modern IDE features in Emacs. Some of these -features are provided via other Emacs packages, and some via Eglot -directly (@pxref{Eglot Commands}). +features are provided via other Emacs packages (@pxref{Eglot and Other +Emacs Features}), and some via Eglot directly (@pxref{Eglot Commands}). Here's an overview of the main features that Eglot provides: @@ -413,19 +414,19 @@ Here's an overview of the main features that Eglot provides: At-point documentation: when point is near a symbol or an identifier, information about the identifier's significance in the program (its function or method signature, its type, its custom documentation string, -etc.) is made available via the ElDoc package (@pxref{Programming -Language Doc,,, emacs, GNU Emacs Manual}). +etc.) is made available via the ElDoc package (@pxref{ElDoc and +Eglot}). @item On-the-fly diagnostic annotations, via the Flymake package -(@pxref{Top,,, Flymake, GNU Flymake manual}). Eglot's Flymake backend +(@pxref{Flymake and Eglot}). Eglot's Flymake backend replaces other Flymake backends while it is managing a buffer, and enhances diagnostics with interactive server-suggested fixes (so-called -@dfn{code actions}, @pxref{Eglot Commands}). +@dfn{code actions}, @pxref{Refactor and Eglot}). @item -Finding definitions and uses of identifiers, via Xref (@pxref{Xref,,, -emacs, GNU Emacs Manual}). Eglot provides a backend for the Xref +Finding definitions and uses of identifiers, via Xref (@pxref{Xref and +Eglot}). Eglot provides a backend for the Xref capabilities which uses the language server's understanding of the program source. In particular, it eliminates the need to generate tags tables (@pxref{Tags tables,,, emacs, GNU Emacs Manual}) for languages @@ -433,21 +434,24 @@ which are only supported by the @code{etags} backend. @item Buffer navigation by name of function, class, method, etc., via Imenu -(@pxref{Imenu,,, emacs, GNU Emacs Manual}). Eglot provides its own +(@pxref{Imenu and Eglot}). Eglot provides its own variant of @code{imenu-create-index-function}, which generates the index for the buffer based on the language server's program source analysis. @item Enhanced completion of symbol at point by the @code{completion-at-point} -command (@pxref{Symbol Completion,,, emacs, GNU Emacs Manual}). This -uses the language server's parser data for the completion candidates. +command (@pxref{Completion and Eglot}). This uses the language +server's parser data for the completion candidates. @item -Server-suggested code refactorings. The ElDoc package is also leveraged -to retrieve so-called @dfn{code actions} nearby point. When such -suggestions are available they are annotated with a special indication -and can be easily invoked by the user with the @code{eglot-code-action} -command (@pxref{Eglot Commands}). +Server-assisted code refactorings, via the Refactor library +(@file{refactor.el}). Eglot provides a backend for Refactor's commands, +such as @code{refactor-rename} and @code{refactor}, which use the +language server to rename identifiers across the project and to find +so-called @dfn{code actions}: fixes, refactorings and other edits +applicable near point. Eglot also turns on +@code{refactor-suggestion-mode} to provide special visual indications +when such actions are available (@pxref{Refactor and Eglot}). @item On-the-fly succinct informative annotations, so-called @dfn{inlay @@ -476,30 +480,30 @@ supported and is activated automatically as you type. @item Eglot enhances symbol completion front-ends by providing completion candidates based on the language server's understanding of the source -code (@pxref{Symbol Completion,,, emacs, GNU Emacs Manual}). The -Company package, installable from GNU ELPA, is a popular package known -to work well with Eglot. +code. The Company package, installable from GNU ELPA, is a popular +package known to work well with Eglot (@pxref{Completion and Eglot}). @item If YASnippet, a popular third-party package for automatic insertion of code templates (snippets), is installed, and the language server supports snippet completion candidates, Eglot arranges for the completion package to instantiate these snippets using YASnippet. -(YASnippet can be installed from GNU ELPA.) +(YASnippet can be installed from GNU ELPA.) @xref{Completion and +Eglot}. @item When the server provides at-point documentation formatted as Markdown in addition to plain text, Eglot arranges for the ElDoc package to enrich this text with fontifications, hyperlinks and other nice formatting before displaying it to the user. This makes the documentation shown by -ElDoc look nicer on display. +ElDoc look nicer on display. @xref{ElDoc and Eglot}. @item In addition to enabling and enhancing other features and packages, Eglot also provides a number of user commands based on the capabilities of -language servers. Examples include renaming symbols with -@kbd{eglot-rename} and asking to automatically correct problems with -@kbd{eglot-code-actions}. @xref{Eglot Commands}. +language servers. Examples include reformatting code with +@kbd{eglot-format} and displaying call hierarchies with +@kbd{eglot-show-call-hierarchy}. @xref{Eglot Commands}. @end itemize Not all servers support the full set of LSP capabilities, but most of @@ -705,12 +709,6 @@ to it, @kbd{e} visits its events buffer, @kbd{w} shows its workspace configuration, and @kbd{RET} describes the connection with @code{eglot-describe-connection}. -@item M-x eglot-rename -This command renames the program symbol (a.k.a.@: @dfn{identifier}) at -point to another name. It prompts for the new name of the symbol, and -then modifies all the files in the project which are managed by the -language server of the current buffer to implement the renaming. - @item M-x eglot-format This command reformats the active region according to the language server rules. If no region is active, it reformats the entire @@ -720,35 +718,6 @@ current buffer. This command reformats the current buffer, in the same manner as @code{eglot-format} does. -@cindex code actions -@item M-x eglot-code-actions -@itemx M-x eglot-code-action-organize-imports -@itemx M-x eglot-code-action-quickfix -@itemx M-x eglot-code-action-extract -@itemx M-x eglot-code-action-inline -@itemx M-x eglot-code-action-rewrite -These commands allow you to invoke the so-called @dfn{code actions}: -requests for the language server to provide editing commands for -correcting, refactoring or beautifying your code. These commands may -affect more than one visited file belonging to the project. - -The command @code{eglot-code-actions} asks the server if there are any -code actions for any point in the buffer or contained in the active -region. If there are, you have the choice to execute one of them via -the minibuffer. - -A common use of code actions is fixing the Flymake error diagnostics -issued by Eglot (@pxref{Top,,, Flymake, GNU Flymake manual}). Clicking -on a diagnostic with @kbd{mouse-2} invokes -@code{eglot-code-actions-at-mouse} which pops up a menu of available -code actions. The variable @code{eglot-diagnostics-map} can be used to -control the mouse binding. - -Other commands execute a specific code action. For example, -@code{eglot-code-action-organize-imports} rearranges the program's -@dfn{imports}---declarations of modules whose capabilities the program -uses. - @cindex inlay hints @item M-x eglot-inlay-hints-mode This command toggles LSP @dfn{inlay hints} on and off for the current @@ -840,69 +809,382 @@ deemed uninteresting or temporary, this command can be used to can sometimes be used to unclog a temporarily malfunctioning server. @end ftable -As described in @ref{Eglot Features} most features associated with Eglot -are actually provided by other Emacs packages and features, and Eglot -only enhances them by allowing them to use the information coming from -the language servers. For completeness, here's the list of commands of -those other packages that are very commonly used in Eglot-managed -buffers: +@node Eglot and Other Emacs Features +@chapter Eglot and Other Emacs Features +@cindex Emacs features used by Eglot +@cindex commands of other packages, used with Eglot + +As described in @ref{Eglot Features}, most features associated with +Eglot are actually provided by other Emacs packages and features, and +Eglot only enhances them by allowing them to use the information coming +from the language servers. This chapter describes, for each of them, +the commands that are very commonly used in Eglot-managed buffers, and +how Eglot hooks onto them. + +Eglot hooks onto these packages by setting special variables in its +special minor mode (@pxref{Eglot and Buffers}). To gain finer control +of Eglot's operation, the @code{eglot-managed-mode-hook} should be used +to tweak, subdue or completely override Eglot's setting of these +variables. To keep Eglot away from some of these features altogether, +use @code{eglot-stay-out-of} (@pxref{Other Variables}). The sections +below include examples of such tweaks, which you can add to your init +file (@pxref{Init File,,, emacs, The GNU Emacs Manual}). + +@menu +* ElDoc and Eglot:: Documentation at point. +* Flymake and Eglot:: On-the-fly diagnostics. +* Refactor and Eglot:: Renaming and code actions. +* Xref and Eglot:: Finding definitions and references. +* Imenu and Eglot:: Navigating buffer contents. +* Completion and Eglot:: Completing symbols at point. +@end menu + +@node ElDoc and Eglot +@section ElDoc + +ElDoc displays documentation for the thing at point, such as a +function's signature or a variable's type, usually in the echo area +(@pxref{Programming Language Doc,,, emacs, GNU Emacs Manual}). @c Not @ftable, because the index entries should mention Eglot @table @code @cindex ElDoc, and Eglot @cindex documentation using Eglot +@item M-x eldoc-mode +Toggle ElDoc mode, which automatically displays documentation for the +identifier at point as you move around. Eglot turns it on by default +in the buffers it manages, unless @code{eldoc} is in +@code{eglot-stay-out-of} (@pxref{Other Variables}). + @item M-x eldoc Ask the ElDoc system for help at point. +@item M-x eldoc-doc-buffer +Display the documentation at point in a separate buffer, in fuller form +than the echo area allows. In Eglot-managed buffers, @kbd{C-h .} is +remapped to this command (@pxref{Customization Variables}). +@end table + +When the server provides documentation formatted as Markdown, Eglot +arranges for ElDoc to enrich it with fontifications, hyperlinks and +other nice formatting before displaying it. The variable +@code{eglot-documentation-renderer} controls this (@pxref{Customization +Variables}). + +Eglot hooks onto ElDoc's @code{eldoc-documentation-functions} variable, +adding a number of functions to it: + +@itemize @minus +@item @code{eglot-hover-eldoc-function}, to display general information +about an identifier. +@item @code{eglot-signature-eldoc-function}, to display function +signature information. +@item @code{eglot-highlight-eldoc-function}, to highlight nearby +manifestations of an identifier. +@end itemize + +You can add and remove elements from this list: a simple tweak to remove +the function signature for hypothetical language @code{Foo} may look +like: + +@lisp +(add-hook 'foo-mode-hook + (lambda () + (add-hook 'eglot-managed-mode-hook + (lambda () + (remove-hook 'eldoc-documentation-functions + 'eglot-signature-eldoc-function + nil t)) + nil t))) +@end lisp + +For more sophisticated changes, we can take advantage of ElDoc's +well-defined protocols. @xref{Programming Language Doc,,, emacs, GNU +Emacs Manual}. For instance, the functions in +@code{eldoc-display-functions} control displays of the at-point +documentation produced by @code{eldoc-documentation-functions}. As an +example, to prevent hover documentation from ever reaching the echo +area, while keeping it in the more spacious ElDoc buffer, use something +like the following: + +@lisp +(require 'cl-lib) + +(defun my/special-eglot-hover-function (cb &rest _ignored) + "Same as `eglot-hover-eldoc-function`, but skip the echo area." + (eglot-hover-eldoc-function (lambda (info &rest _ignore) + (funcall cb info :echo 'skip)))) + +;; substitute 'eglot-hover-eldoc-function with our "fixed" variant. +(add-hook + 'eglot-managed-mode-hook + (lambda () + (setq-local eldoc-documentation-functions + (cl-substitute #'my/special-eglot-hover-function + 'eglot-hover-eldoc-function + eldoc-documentation-functions)))) +@end lisp + +@node Flymake and Eglot +@section Flymake + +Flymake checks the buffer for errors and warnings as you edit, and +highlights the problems it finds (@pxref{Top,,, Flymake, GNU Flymake +manual}). + +@table @code @cindex Flymake, and Eglot @cindex on-the-fly diagnostics using Eglot +@item M-x flymake-mode +Toggle Flymake mode, which highlights problems in the source code as +reported by the language server. Eglot turns it on by default in the +buffers it manages, unless @code{flymake} is in +@code{eglot-stay-out-of} (@pxref{Other Variables}). + @item M-x flymake-show-buffer-diagnostics Ask Flymake system to display diagnostics for the current buffer. @item M-x flymake-show-project-diagnostics Ask Flymake to list diagnostics for all the files in the current project. +@end table + +Eglot hooks onto Flymake's @code{flymake-diagnostic-functions} variable, +completely replacing its value with Eglot's own +@code{eglot-flymake-backend} function. Additional backends may be added +to work alongside Eglot's, for example: + +@lisp +(add-hook 'foo-mode-hook + (lambda () + (add-hook 'eglot-managed-mode-hook + (lambda () + (add-hook 'flymake-diagnostic-functions + #'my/special-foo-mode-backend + nil t)) + nil t))) +@end lisp + +@node Refactor and Eglot +@section Refactor + +Refactor, from the @file{refactor.el} library, finds and executes +@dfn{actions} that rewrite program code, such as renaming identifiers, +fixing diagnostics, or extracting functions. + +@table @code +@cindex Refactor, and Eglot +@item M-x refactor-suggestion-mode +Toggle Refactor Suggestion mode, which indicates when code actions are +available at point, according to @code{refactor-indications} (see +below). Eglot turns it on by default in the buffers it manages, unless +@code{refactor} is in @code{eglot-stay-out-of} (@pxref{Other +Variables}). +@cindex renaming identifiers using Eglot +@item M-x refactor-rename +This command renames the program symbol (a.k.a.@: @dfn{identifier}) at +point to another name. It prompts for the new name of the symbol, and +then modifies all the files in the project which are managed by the +language server of the current buffer to implement the renaming. + +@cindex code actions +@item M-x refactor +@itemx M-x refactor-quickfix +@itemx M-x refactor-fix-all +@itemx M-x refactor-organize-imports +@itemx M-x refactor-extract +@itemx M-x refactor-inline +@itemx M-x refactor-rewrite +These commands allow you to invoke the so-called @dfn{code actions}: +requests for the language server to provide editing commands for +correcting, refactoring or beautifying your code. These commands may +affect more than one visited file belonging to the project. + +The command @code{refactor} asks the server if there are any code +actions for the active region or, if there is none, for the Flymake +diagnostics or the expression at point. If there are, you have the +choice to execute one of them via the minibuffer; if there is just one, +it is executed right away. With a prefix argument, @code{refactor} +first prompts for a @dfn{kind} of action, such as @code{quickfix} or +@code{extract}, and considers only actions of that kind. + +A common use of code actions is fixing the Flymake error diagnostics +issued by Eglot (@pxref{Top,,, Flymake, GNU Flymake manual}). Clicking +on a diagnostic with @kbd{mouse-2} invokes @code{refactor-at-mouse} +which pops up a menu of available code actions. The keymap +@code{refactor-mouse-map} can be used to control the mouse binding. + +The other commands are shortcuts considering only one kind of action. +For example, @code{refactor-organize-imports} rearranges the program's +@dfn{imports}---declarations of modules whose capabilities the program +uses, and @code{refactor-fix-all} applies every fix that the server can +make to the whole file. + +Before applying the edits of a code action, these commands may ask for +confirmation, depending on @code{refactor-confirmation} (see below). +@end table + +Refactor also comes with some customization variables: + +@vtable @code +@cindex Refactor, variables + +@item refactor-confirmation +Commands such as @code{refactor-rename} and @code{refactor} result in +the language server sending editing commands to Emacs. This controls +whether and how Emacs asks for confirmation before performing those +edits: as a summary in the minibuffer, as a diff of the proposed +changes, or not at all. This option's value can be crafted to require +this confirmation for specific commands or only when the edit affects +files not yet visited by the user. Consult this option's docstring for +more information. + +@item refactor-indications +This option controls how @code{refactor-suggestion-mode} indicates code +actions available at point. Value is a list of symbols, more than one +can be specified: + +@itemize @minus +@item +@code{eldoc-hint}: ElDoc is used to hint about at-point actions. +@item +@code{left-fringe}: A special indicator appears in the left fringe of +the line that point is currently on. +@item +@code{margin}: A special indicator appears in the margin of the line +that point is currently on. +@item +@code{nearby}: An interactive special indicator appears near point. +@end itemize + +Only one of @code{left-fringe}, @code{margin} and @code{nearby} is used +at a time. If the list is empty, no indication happens. Regardless of +this option, an interactive special indicator also appears in the mode +line while actions are available. + +@item refactor-indicator +This option is a string determining what the special indicator looks +like. +@end vtable + +Eglot hooks onto Refactor's @code{refactor-backend-functions} variable, +adding its own @code{eglot-refactor-backend} function to it. Turning on +@code{refactor-suggestion-mode} adds @code{refactor-suggestion} to +@code{eldoc-documentation-functions} (@pxref{ElDoc and Eglot}). + +@node Xref and Eglot +@section Xref + +Xref finds the definitions of identifiers and the places where they +are used, and lets you jump between them (@pxref{Xref,,, emacs, GNU +Emacs Manual}). + +@table @code @cindex xref, and Eglot @cindex finding definitions of identifiers using Eglot @item M-x xref-find-definitions -Ask Xref to go the definition of the identifier at point. +Ask Xref to go to the definition of the identifier at point, normally +bound to @kbd{M-.} (@pxref{Looking Up Identifiers,,, emacs, GNU Emacs +Manual}). + +@item M-x xref-go-back +Go back to where you were before the last Xref jump, normally bound to +@kbd{M-,}. + +@cindex finding references to identifiers using Eglot +@item M-x xref-find-references +Ask Xref to list all the uses of the identifier at point, normally +bound to @kbd{M-?} (@pxref{Identifier Search,,, emacs, GNU Emacs +Manual}). +@end table + +Eglot hooks onto Xref's @code{xref-backend-functions} variable, adding +its own @code{eglot-xref-backend} function to it. +@node Imenu and Eglot +@section Imenu + +Imenu lets you jump to the definitions in a buffer, such as functions +and classes, by name (@pxref{Imenu,,, emacs, GNU Emacs Manual}). + +@table @code @cindex imenu navigation using Eglot @item M-x imenu Let the user navigate the program source code using buffer index, categorizing program elements by syntactic class (class, method, variable, etc.) and offering completion. +@end table + +Eglot hooks onto Imenu's @code{imenu-create-index-function}, providing +an index generated from the language server's analysis of the program. + +@cindex breadcrumb +The Breadcrumb package, installable from GNU ELPA, uses the same Imenu +index to show where point is in the program's structure, as a path of +nested definitions in the header line. It works well with Eglot. + +@node Completion and Eglot +@section Completion + +Symbol completion offers possible completions of the partial +identifier before point (@pxref{Symbol Completion,,, emacs, GNU Emacs +Manual}). Major modes and packages like Eglot provide the completion +candidates (@pxref{Completion in Buffers,,, elisp, GNU Emacs Lisp +Reference Manual}). +@table @code @cindex symbol completion using Eglot @item M-x completion-at-point -Request completion of the symbol at point. +Request completion of the symbol at point, normally bound to +@kbd{C-M-i} (@pxref{Symbol Completion,,, emacs, GNU Emacs Manual}). +Eglot adds @code{eglot-completion-at-point} to +@code{completion-at-point-functions}, so the candidates come from the +language server. @end table +A very popular alternative is to use a ``completion front-end'' which +offers completions as you type. These use the same candidates. +Examples are the Company and Corfu packages, both installable from GNU +ELPA, and the built-in Completion Preview mode (@pxref{Symbol +Completion,,, emacs, GNU Emacs Manual}). + +Eglot hooks onto Company's @code{company-backends} variable, ensuring +only the @code{company-capf} backend lives there. This ensures that +Company offers the same set of completions as regular +@code{completion-at-point}. + +@cindex YASnippet, and Eglot +If YASnippet, a popular package for automatic insertion of code +templates (snippets) installable from GNU ELPA, is installed, and the +language server supports snippet completion candidates, Eglot arranges +for the completion package to instantiate these snippets using +YASnippet, automatically activating @code{yas-minor-mode} when needed. + @node Customizing Eglot @chapter Customizing Eglot @cindex customizing Eglot -To have Eglot behave like you want it, sometimes it suffices to -customize Emacs packages and features that Eglot uses but to do so for -all of Emacs (regardless of Eglot) . For example, to configure the -amount of space taken up by documentation in the echo area, customize -the ElDoc variable @code{eldoc-echo-area-use-multiline-p}. To configure -Flymake faces used for errors and warnings, customize the -@code{flymake-error} and @code{flymake-warning} faces. +This chapter describes Eglot's user options which you can control from +the Customization facilities (@pxref{Customization,,,emacs, GNU Emacs +Manual}) as well as other Elisp variables controlled from your init file +(@pxref{Init File,,, emacs, The GNU Emacs Manual}). Compared to the breadth of its functionality, Eglot itself has a -relatively small number of customization variables. There is -additionally a set of variables that are usually set from Elisp snippets -(@pxref{Init File,,, emacs, The GNU Emacs Manual}). +relatively small number of customization variables. -Other times, it's necessary to have finer control of Eglot's interaction -with these features. @xref{More Customization}. +Often, the knob that does what you're looking for is not found in Eglot +itself, but in one of the other Emacs packages and features that Eglot +integrates with. For example, to configure the amount of space taken up +by documentation in the echo area, customize the ElDoc variable +@code{eldoc-echo-area-use-multiline-p}. To configure Flymake faces used +for errors and warnings, customize the @code{flymake-error} and +@code{flymake-warning} faces. @xref{Eglot and Other Emacs Features}, +for many other examples. @menu * Customization Variables:: * Other Variables:: -* More Customization:: @end menu @node Customization Variables @@ -952,15 +1234,6 @@ last buffer managed by it is killed. @xref{Shutting Down LSP Servers}. The default is @code{nil}; if you want to shut down a server, use @kbd{M-x eglot-shutdown} (@pxref{Eglot Commands}). -@item eglot-confirm-server-edits -Various Eglot commands and code actions result in the language server -sending editing commands to Emacs. If this option's value is -non-@code{nil}, Eglot will ask for confirmation before performing edits -proposed by the language server. This option's value can be crafted to -require this confirmation for specific commands or only when the edit -affects files not yet visited by the user. Consult this option's -docstring for more information. - @item eglot-ignored-server-capabilities This variable's value is a list of language server capabilities that Eglot should not use. The default is @code{nil}: Eglot uses all of the @@ -994,8 +1267,8 @@ is empty, with the single exception: @kbd{C-h .} is remapped to invoke For example: @lisp - (define-key eglot-mode-map (kbd "C-c r") 'eglot-rename) - (define-key eglot-mode-map (kbd "C-c o") 'eglot-code-action-organize-imports) + (define-key eglot-mode-map (kbd "C-c r") 'refactor-rename) + (define-key eglot-mode-map (kbd "C-c o") 'refactor-organize-imports) (define-key eglot-mode-map (kbd "C-c h") 'eldoc) (define-key eglot-mode-map (kbd "") 'xref-find-definitions) (define-key eglot-mode-map (kbd "") 'eglot-momentary-inlay-hints) @@ -1011,34 +1284,10 @@ buffer is used, else the progress is reported in the mode line. @cindex request cancellation @item eglot-advertise-cancellation Setting this variable to true causes Eglot to send special cancellation -notification for certain stale client request. This may help some LSP +notification for certain stale client requests. This may help some LSP servers avoid doing costly but ultimately useless work on behalf of the client, improving overall performance. -@item eglot-code-action-indications -This variable controls the indication of code actions available at -point. Value is a list of symbols, more than one can be specified: - -@itemize @minus -@item -@code{eldoc-hint}: ElDoc is used to hint about at-point actions. -@item -@code{margin}: A special indicator appears in the margin of the line -that point is currently on. -@item -@code{nearby}: An interactive special indicator appears near point. -@item -@code{mode-line}: An interactive special indicator appears in the mode -line. -@end itemize - -@code{margin} and @code{nearby} are incompatible. If the list is empty, -ElDoc will not hint about at-point actions. - -@item eglot-code-action-indicator -This variable is a string determining what the special indicator looks -like. - @item eglot-mode-line-format This variables controls the shape and look of Eglot's mode line. Its value is a mode line ``construct'', generally a list of symbols and @@ -1056,9 +1305,7 @@ current session's menu; @item @code{eglot-mode-line-pending-requests}: number of pending LSP requests; @item -@code{eglot-mode-line-progress}: progress reporter widgets; -@item -@code{eglot-mode-line-action-suggestion}: LSP code actions at point. +@code{eglot-mode-line-progress}: progress reporter widgets. @end itemize @end vtable @@ -1122,8 +1369,9 @@ automatically try to manage on the user's behalf. It is useful, for example, when you need to use non-LSP Flymake or Company back-ends. To have Eglot stay away from some Emacs feature, add that feature's symbol or a regexp that will match a symbol's name to the list: for example, -the symbol @code{xref} to leave Xref alone, or the string @samp{company} -to stay away from your Company customizations. Here's an example: +the symbol @code{xref} to leave Xref alone, the symbol @code{refactor} +to leave Refactor alone, or the string @samp{company} to stay away from +your Company customizations. Here's an example: @lisp (add-to-list 'eglot-stay-out-of 'flymake) @@ -1134,107 +1382,6 @@ to use Eglot in your @code{eglot-managed-mode-hook} or via some other mechanism. @end table -@node More Customization -@section More Customization - -As explained earlier (@pxref{Eglot and Buffers}), Eglot hooks onto -existing Emacs packages and features by setting special variables in its -special minor mode. To gain finer control of Eglot's operation, the -@code{eglot-managed-mode-hook} should be used to tweak, subdue or -completely override Eglot's setting of these variables. - -@itemize @bullet -@item -Eglot hooks onto ElDoc's @code{eldoc-documentation-functions} variable, -adding a number of functions to it: -@itemize @minus -@item @code{eglot-hover-eldoc-function}, to display general information -about an identifier. -@item @code{eglot-signature-eldoc-function}, to display function -signature information. -@item @code{eglot-highlight-eldoc-function}, to highlight nearby -manifestations of an identifier. -@item @code{eglot-code-action-suggestion}, to retrieve relevant code -actions at point. -@end itemize - -A simple tweak to remove at-point identifier information for -hypothetical language @code{Foo} may look like: - -@lisp -(add-hook 'foo-mode-hook - (lambda () - (add-hook 'eglot-managed-mode-hook - (lambda () - (remove-hook 'eldoc-documentation-functions - 'eglot-hover-eldoc-function - nil t)) - nil t))) -@end lisp - -For more sophisticated changes, we can take advantage of ElDoc's -well-defined protocols. @xref{Programming Language Doc,,, emacs, GNU -Emacs Manual}. For instance, the functions in -@code{eldoc-display-functions} control displays of the at-point -documentation produced by @code{eldoc-documentation-functions}. As an -example, to ensure that hover documentation specifically is never output -into the Echo area (in all programming modes): - -@lisp -(require 'cl-lib) - -(defun my/special-eglot-hover-function (cb &rest _ignored) - "Same as `eglot-hover-eldoc-function`, but skip the echo area." - (eglot-hover-eldoc-function (lambda (info &rest _ignore) - (funcall cb info :echo 'skip)))) - -;; substitute 'eldoc-hover-eldoc-function with our "fixed" variant. -(add-hook - 'eglot-managed-mode-hook - (lambda () - (setq-local eldoc-documentation-functions - (cl-substitute #'my/special-eglot-hover-function - 'eglot-hover-eldoc-function - eldoc-documentation-functions)))) -@end lisp - -@item -Eglot hooks onto Flymake's @code{flymake-diagnostic-functions} variable, -completely replacing its value with Eglot's own -@code{eglot-flymake-backend} function. Additional backends may be added -to work alongside Eglot's. - -@lisp -(add-hook 'foo-mode-hook - (lambda () - (add-hook 'eglot-managed-mode-hook - (lambda () - (add-hook 'flymake-diagnostic-functions - #'my/special-foo-mode-backend - nil t)) - nil t))) -@end lisp - -@item -Eglot hooks onto Xref's @code{xref-backend-functions} variable, adding -its own @code{eglot-xref-backend} function to it. - -@item -Eglot hooks onto Imenu's @code{imenu-create-index-function}. - -@item -Eglot hooks onto Emacs's @code{completion-at-point-functions}. - -@item -Eglot hooks onto Company's @code{company-backends} variable, ensuring -only the @code{company-capf} backend lives there. This ensures the same -set of completions as regular @code{completion-at-point}. - -@item -Eglot hooks onto YASnippet by automatically activating -@code{yas-minor-mode} when needed to expand server-provided snippets. -@end itemize - @node Advanced server configuration @chapter Advanced server configuration @@ -1881,7 +2028,7 @@ Depending on the specific nature of the performance bottleneck, sometimes a workaround is to turn off these features on the Eglot side using the @code{eglot-ignored-server-capabilities} and @code{eglot-managed-mode-hook} variables (@pxref{Other Variables} and -@pxref{More Customization}). +@ref{Eglot and Other Emacs Features}). Another aspect that may cause performance degradation is the amount of JSONRPC information exchanged with Emacs. Using an LSP program like commit f2568db52eb1503f98085a74467d55e9f65f2248 Author: João Távora Date: Fri Oct 9 19:31:53 2026 +0100 Add refactor.el; move generic code actions machinery out of Eglot Most of Eglot's code actions code wasn't LSP-specific, and could be useful to other major and minor modes. Extract it to new refactor.el, leaving Eglot with just the LSP-specific backend; old entry points now redirect there via obsolete aliases. * etc/NEWS: Announce new library refactor.el. * etc/EGLOT-NEWS: Announce move of code actions to refactor.el. * lisp/progmodes/refactor.el: New file. * lisp/progmodes/eglot.el (refactor-backend-name, refactor-backend-actions) (refactor-backend-execute, refactor-backend-rename) (refactor-backend-rename-bounds): New cl-defmethods. (eglot-refactor-backend, eglot--translate-workspace-edit): New helpers. (eglot--refactor-kinds): New variable. (eglot--managed-mode): Register refactor backend, start refactor-suggestion-mode. (eglot--apply-workspace-edit, eglot--apply-text-edits): Rework to use refactor.el. (eglot--flymake-diag-type): Use refactor diagnostic types. (eglot-mode-line-format): Drop eglot-mode-line-action-suggestion. (eglot-code-action-suggestion, eglot--read-execute-code-action) (eglot--code-action-bounds, eglot--rename-interactive) (eglot--confirm-server-edits, eglot--propose-changes-as-diff): Delete. (eglot--code-action): Delete macro. (eglot--suggestion-overlay, eglot--fringe-action): Delete. (eglot-code-actions, eglot-rename, eglot-code-actions-at-mouse) (eglot-code-action-organize-imports, eglot-code-action-extract) (eglot-code-action-inline, eglot-code-action-rewrite) (eglot-code-action-quickfix): Add obsolete aliases. (eglot-code-action-indications, eglot-code-action-indicator) (eglot-diagnostics-map, eglot-confirm-server-edits): Add obsolete variable aliases. (eglot-code-action-indicator-face): Add obsolete face alias. (eglot-mode-line-action-suggestion): Make obsolete. * test/lisp/progmodes/eglot-tests.el (eglot-test-rename-a-symbol): Tweak. diff --git a/etc/EGLOT-NEWS b/etc/EGLOT-NEWS index 8fcdbe13bbf..81bd908dced 100644 --- a/etc/EGLOT-NEWS +++ b/etc/EGLOT-NEWS @@ -34,6 +34,13 @@ now sends such completions, so set the variable to nil to keep the behavior of earlier clangd versions (which used a inserting 'TextEdit'). See docstring for an example. +** Code actions and renaming now use the new Refactor library + +Eglot's code actions machinery has moved to the new Refactor package, +for which Eglot is now a backend. The old commands are obsolete aliases +for Refactor's: for example, 'eglot-code-actions' is now 'M-x refactor' +and 'eglot-rename' is now 'M-x refactor-rename'. + ** Miscellaneous bugs fixed (bug#81593, bug#81538, bug#81514, bug#81425) diff --git a/etc/NEWS b/etc/NEWS index 5815aca45ad..21b3bb6ef94 100644 --- a/etc/NEWS +++ b/etc/NEWS @@ -533,6 +533,16 @@ Identifiers (UUIDs). It provides methods for generating UUIDs, parsing them, and outputting them as a string, a unibyte binary string, or as a number. ++++ +** New library 'refactor'. +This library provides a language-agnostic interface for performing +refactoring actions such as renaming identifiers, extracting and +inlining functions, and fixing diagnostics. Its commands include +'M-x refactor' and 'M-x refactor-rename'. The actual actions are +supplied by Refactor backends defined by major modes and packages. +Refactor was extracted from Eglot, which is its main user and backend. +The library is also available as a GNU ELPA package. + * Incompatible Lisp Changes in Emacs 32.1 diff --git a/lisp/progmodes/eglot.el b/lisp/progmodes/eglot.el index 6ed3bb9a008..06737fcfbcf 100644 --- a/lisp/progmodes/eglot.el +++ b/lisp/progmodes/eglot.el @@ -7,7 +7,7 @@ ;; Maintainer: João Távora ;; URL: https://github.com/joaotavora/eglot ;; Keywords: convenience, languages -;; Package-Requires: ((emacs "26.3") (eldoc "1.16.0") (external-completion "0.1") (flymake "1.4.5") (jsonrpc "1.0.29") (project "0.11.2") (seq "2.23") (xref "1.7.0")) +;; Package-Requires: ((emacs "26.3") (eldoc "1.16.0") (external-completion "0.1") (flymake "1.4.5") (jsonrpc "1.0.29") (project "0.11.2") (refactor "0.1") (seq "2.23") (xref "1.7.0")) ;; This is a GNU ELPA :core package. Avoid adding functionality ;; that is not available in the version of Emacs recorded above or any @@ -45,12 +45,14 @@ ;; * Eglot's main job is to hook up the information that language ;; servers offer via LSP to Emacs's UI facilities: Xref for ;; definition-chasing, Flymake for diagnostics, Eldoc for at-point -;; documentation, etc. Eglot's job is generally *not* to provide -;; such a UI itself, though a small number of simple -;; counter-examples do exist, e.g. in the `eglot-rename' command or -;; the `eglot-inlay-hints-mode' minor mode. When a new UI is -;; evidently needed, consider adding a new package to Emacs, or -;; extending an existing one. +;; documentation, Refactor for code action collection and execution, +;; etc. Eglot's job is generally *not* to provide such a UI itself, +;; though a fair number of simple counter-examples do exist, e.g. in +;; the `eglot-inlay-hints-mode' and `eglot-semantic-tokens-mode' minor +;; modes, and the `eglot-show-call-hierarchy' and +;; `eglot-show-type-hierarchy' commands. When a new UI is evidently +;; needed, consider adding a new package to Emacs, or extending an +;; existing one. ;; ;; * Eglot was designed to function with just the UI facilities found ;; in the latest Emacs core, as long as those facilities are also @@ -129,7 +131,7 @@ (funcall reload 'seq nil 'reload) ;; For those packages which are not preloaded OTOH, signal an error if ;; the loaded file is not the one that should have been loaded. - (mapc reload '(project flymake xref jsonrpc external-completion)))) + (mapc reload '(project flymake xref jsonrpc external-completion refactor)))) ;; Keep the eval-when-compile requires at the end, in case it's already been ;; required unconditionally by some earlier `require'. @@ -501,40 +503,6 @@ the LSP connection. That can be done by `eglot-reconnect'." (const :tag "Pretty-printed lisp" lisp))))) :package-version '(Eglot . "1.17.30")) -(defcustom eglot-confirm-server-edits '((t . maybe-summary)) - "Control if changes proposed by LSP should be confirmed with user. - -If this variable's value is the symbol `diff', a diff buffer pops -up, allowing the user to apply each change individually. If the -symbol `summary' or any other non-nil value, the user is prompted -in the minibuffer with a short summary of changes. The symbols -`maybe-diff' and `maybe-summary' mean that the confirmation is -offered to the user only if the changes target files not visited -in buffers. Finally, a nil value means all changes are applied -directly without any confirmation. - -This variable's value can also be an alist ((KEY . ACTION) ...) -where KEY is either a symbol designating the invoked Emacs command -(such as `eglot-rename', `eglot-code-actions', -`eglot-code-action-quickfix', etc.), or a list of file operation -kinds (`create', `rename', `delete') contained in the edit. -ACTION is one of the symbols described above. The value t for -KEY is accepted and its ACTION is the default value for commands -or file operation kinds not in the alist." - :type (let ((basic-choices - '((const :tag "Use diff" diff) - (const :tag "Summarize and prompt" summary) - (const :tag "Maybe use diff" maybe-diff) - (const :tag "Maybe summarize and prompt" maybe-summary) - (const :tag "Don't confirm" nil)))) - `(choice ,@basic-choices - (alist :tag "Per-command or per-kind alist" - :key-type (choice (function :tag "Command") - (repeat :tag "File operation kinds" symbol) - (const :tag "Default" t)) - :value-type (choice . ,basic-choices)))) - :package-version '(Eglot . "1.17.30")) - (defcustom eglot-extend-to-xref nil "If non-nil, activate Eglot in cross-referenced non-project files." :type 'boolean) @@ -613,55 +581,6 @@ servers." :type 'boolean :package-version '(Eglot . "1.22")) -(defface eglot-code-action-indicator-face - '((t (:inherit warning :weight bold))) - "Face used for code action suggestions.") - -(defcustom eglot-code-action-indications - '(eldoc-hint left-fringe margin) - "How Eglot indicates there's are code actions available at point. -Value is a list of symbols, more than one can be specified: - -- `eldoc-hint': ElDoc is used to hint about at-point actions; -- `left-fringe': A special indicator appears on the left fringe; -- `margin': A special indicator appears in the margin; -- `nearby': A special indicator appears near point; -- `mode-line': A special indicator appears in the mode-line. - -If the list is empty, Eglot will not hint about code actions at point. - -Note additionally: - -- Some values are incompatible; if one or more of `nearby', - `left-fringe' and `margin' are specified, earlier values take - precedence. -- The indicators for many of these are customizable via - `eglot-code-action-indicator' (which see), except for `left-fringe'. -- `mode-line' only works if `eglot-mode-line-action-suggestion' exists - in `eglot-mode-line-format' (which see)." - :type '(set - :tag "Tick the ones you're interested in" - (const :tag "ElDoc textual hint" eldoc-hint) - (const :tag "Right besides point" nearby) - (const :tag "In mode line" mode-line) - (const :tag "In left fringe" left-fringe) - (const :tag "In margin" margin)) - :package-version '(Eglot . "1.19")) - -(defcustom eglot-code-action-indicator - (cl-loop for c in '(?↯ ?⭍ ?✓ ?α ??) - when (char-displayable-p c) - return (make-string 1 c)) - "Indicator string for code action suggestions." - :type (let ((basic-choices - (cl-loop for c in '(?↯ ?⭍ ?✓ ?α ??) - when (char-displayable-p c) - collect `(const :tag ,(format "Use `%c'" c) - ,(make-string 1 c))))) - `(choice ,@basic-choices - (string :tag "Specify your own"))) - :package-version '(Eglot . "1.19")) - (defvar eglot-withhold-process-id nil "If non-nil, Eglot will not send the Emacs process id to the language server. This can be useful when using docker to run a language server.") @@ -2421,9 +2340,6 @@ source of a partial report. VERSION is the LSP Document version reported for diagnostics in MAP. PREV-MAP contains the diagnostics of the previous reports for TOKEN.") -(defvar-local eglot--suggestion-overlay (make-overlay 0 0) - "Overlay for `eglot-code-action-suggestion'.") - (define-minor-mode eglot--managed-mode "Mode for source buffers managed by some Eglot project." :init-value nil :lighter nil :keymap eglot-mode-map :interactive nil @@ -2450,6 +2366,9 @@ the previous reports for TOKEN.") (add-hook 'after-save-hook #'eglot--signal-textDocument/didSave nil t) (unless (eglot--stay-out-of-p 'xref) (add-hook 'xref-backend-functions #'eglot-xref-backend nil t)) + (unless (eglot--stay-out-of-p 'refactor) + (add-hook 'refactor-backend-functions #'eglot-refactor-backend nil t) + (refactor-suggestion-mode 1)) (add-hook 'completion-at-point-functions #'eglot-completion-at-point nil t) (add-hook 'completion-in-region-mode-hook #'eglot--capf-session-flush nil t) (add-hook 'company-after-completion-hook #'eglot--capf-session-flush nil t) @@ -2470,8 +2389,7 @@ the previous reports for TOKEN.") (unless (eglot--stay-out-of-p 'eldoc) (dolist (f (list #'eglot-signature-eldoc-function #'eglot-hover-eldoc-function - #'eglot-highlight-eldoc-function - #'eglot-code-action-suggestion)) + #'eglot-highlight-eldoc-function)) (add-hook 'eldoc-documentation-functions f t t)) (eldoc-mode 1)) (cl-pushnew (current-buffer) (eglot--managed-buffers (eglot-current-server)))) @@ -2492,6 +2410,8 @@ the previous reports for TOKEN.") (remove-hook 'after-save-hook #'eglot--signal-textDocument/didSave t) (unless (eglot--stay-out-of-p 'xref) (remove-hook 'xref-backend-functions #'eglot-xref-backend t)) + (unless (eglot--stay-out-of-p 'refactor) + (remove-hook 'refactor-backend-functions #'eglot-refactor-backend t)) (remove-hook 'completion-at-point-functions #'eglot-completion-at-point t) (remove-hook 'completion-in-region-mode-hook #'eglot--capf-session-flush t) (remove-hook 'company-after-completion-hook #'eglot--capf-session-flush t) @@ -2501,8 +2421,7 @@ the previous reports for TOKEN.") (unless (eglot--stay-out-of-p 'eldoc) (dolist (f (list #'eglot-hover-eldoc-function #'eglot-signature-eldoc-function - #'eglot-highlight-eldoc-function - #'eglot-code-action-suggestion)) + #'eglot-highlight-eldoc-function)) (remove-hook 'eldoc-documentation-functions f t))) (cl-loop for (var . saved-binding) in eglot--saved-bindings do (set (make-local-variable var) saved-binding)) @@ -2687,8 +2606,7 @@ If it is activated, also signal textDocument/didOpen." eglot-mode-line-session eglot-mode-line-error eglot-mode-line-pending-requests - eglot-mode-line-progress - eglot-mode-line-action-suggestion) + eglot-mode-line-progress) "Mode line construct for customizing Eglot information. Meaningful symbols in this construct include: @@ -2703,8 +2621,6 @@ Meaningful symbols in this construct include: - `eglot-mode-line-pending-requests': number of pending LSP requests; - `eglot-mode-line-progress': progress reporter widgets; - -- `eglot-mode-line-action-suggestion': LSP code action at point. " :type '(repeat (choice string symbol)) :package-version '(Eglot . "1.19")) @@ -2715,7 +2631,6 @@ Meaningful symbols in this construct include: (put 'eglot-mode-line-error 'risky-local-variable t) (put 'eglot-mode-line-pending-requests 'risky-local-variable t) (put 'eglot-mode-line-progress 'risky-local-variable t) -(put 'eglot-mode-line-action-suggestion 'risky-local-variable t) (defun eglot--mode-line-props (thing face defs &optional prepend) "Helper for function `eglot--mode-line-format'. @@ -2809,16 +2724,9 @@ still unanswered LSP requests to the server\n")))) (mapconcat #'identity blurbs "\n")))))) "Eglot mode line construct for LSP progress reports.") -(defconst eglot-mode-line-action-suggestion - '(:eval - (when (and (memq 'mode-line eglot-code-action-indications) - (overlay-buffer eglot--suggestion-overlay)) - (eglot--mode-line-props - eglot-code-action-indicator 'eglot-code-action-indicator-face - `((mouse-1 - eglot-code-actions-at-mouse - "execute code actions at point"))))) - "Eglot mode line construct for at-point code actions.") +(defconst eglot-mode-line-action-suggestion nil) +(make-obsolete 'eglot-mode-line-action-suggestion + "Use `refactor-suggestion-mode' instead." 32.1) (add-to-list 'mode-line-misc-info @@ -3341,24 +3249,6 @@ uses it; didOpen then clears it and recomputes from the new ;;; Flymake integration -(put 'eglot-note 'flymake-category 'flymake-note) -(put 'eglot-warning 'flymake-category 'flymake-warning) -(put 'eglot-error 'flymake-category 'flymake-error) - -(defvar eglot-diagnostics-map - (let ((map (make-sparse-keymap))) - (define-key map [mouse-2] #'eglot-code-actions-at-mouse) - (define-key map [left-margin mouse-1] #'eglot-code-actions-at-mouse) - map) - "Keymap active in Eglot-backed Flymake diagnostic overlays.") - -(cl-loop for i from 1 - for type in '(eglot-note eglot-warning eglot-error) - do (put type 'flymake-overlay-control - `((mouse-face . highlight) - (priority . ,(+ 50 i)) - (keymap . ,eglot-diagnostics-map)))) - (defun eglot--flymake-sniff-diagnostics (beg &optional end) "Like `flymake-diagnostics', but for Eglot-specific diagnostics." (cl-loop for diag in (flymake-diagnostics beg end) @@ -3454,11 +3344,11 @@ version the diagnostics pertain to." (report (cdr entry) :stay)))))))))) (defun eglot--flymake-diag-type (severity) - "Convert LSP diagnostic SEVERITY to Eglot/Flymake diagnostic type." - (cond ((null severity) 'eglot-error) - ((<= severity 1) 'eglot-error) - ((= severity 2) 'eglot-warning) - (t 'eglot-note))) + "Convert LSP diagnostic SEVERITY to a refactor/Flymake diagnostic type." + (cond ((null severity) 'refactor-error) + ((<= severity 1) 'refactor-error) + ((= severity 2) 'refactor-warning) + (t 'refactor-note))) (defun eglot--flymake-make-diag (diag-spec version region) "Convert LSP diagnostic DIAG-SPEC to Flymake diagnostic. @@ -3653,6 +3543,9 @@ If KEEP, knowingly push a dummy do-nothing update." ;;; Xref integration (defun eglot-xref-backend () "Eglot xref backend." 'eglot) +;;; Refactor integration +(defun eglot-refactor-backend () "Eglot refactor backend." 'eglot) + (defvar eglot--temp-location-buffers (make-hash-table :test #'equal) "Helper variable for `eglot--collecting-xrefs'.") @@ -4385,305 +4278,88 @@ Returns a list as described in docstring of `imenu--index-alist'." ;;; Code actions and rename (cl-defun eglot--apply-text-edits (edits &optional version silent) - "Apply EDITS for current buffer if at VERSION, or if it's nil. -If SILENT, don't echo progress in mode-line." + "Apply LSP EDITS for current buffer using `refactor-apply-text-edits'. +Error if VERSION non-nil and doesn't match the documents'. Pass +SILENT to `refactor-apply-text-edits'." (unless edits (cl-return-from eglot--apply-text-edits)) - (unless (or (not version) (equal version eglot--docver)) + (when (and version (not (equal version eglot--docver))) (jsonrpc-error "Edits on `%s' require version %d, have %d" (current-buffer) version eglot--docver)) - (atomic-change-group - (let* ((change-group (prepare-change-group)) - (howmany (length edits)) - (reporter (unless silent - (make-progress-reporter - (eglot--format "[eglot] applying %s edits to `%s'..." - howmany (current-buffer)) - 0 howmany))) - (done 0)) - (mapc (pcase-lambda (`(,newText ,beg . ,end)) - (if (> emacs-major-version 30) - (replace-region-contents beg end newText) - (let ((source (current-buffer))) - (with-temp-buffer - (insert newText) - (let ((temp (current-buffer))) - (with-current-buffer source - (save-excursion - (save-restriction - (narrow-to-region beg end) - (with-no-warnings - (replace-buffer-contents temp))))))))) - (when reporter - (eglot--reporter-update reporter (cl-incf done)))) - (mapcar (lambda (edit) - (eglot--dcase edit - (((TextEdit) range newText) - (cons newText (eglot-range-region range 'markers))) - (((InsertReplaceEdit) newText replace) - (cons newText (eglot-range-region replace 'markers))))) - (reverse edits))) - (undo-amalgamate-change-group change-group) - (when reporter - (progress-reporter-done reporter))))) - -(defun eglot--confirm-server-edits (origin prepared) - "Helper for `eglot--apply-workspace-edit. -ORIGIN is a symbol designating a command. PREPARED is a list of -operations to apply. Reads the `eglot-confirm-server-edits' user -option and returns a symbol like `diff', `summary' or nil." - (let (v op-kinds) - (cond ((symbolp eglot-confirm-server-edits) eglot-confirm-server-edits) - ;; Check for command-based entry - ((setq v (assoc origin eglot-confirm-server-edits)) (cdr v)) - ;; Check for operation-kind-based entry - ((and (setq op-kinds (mapcar #'car prepared)) - (setq v (cl-find-if (lambda (entry) - (and (listp (car entry)) - (cl-some (lambda (kind) - (memq kind (car entry))) - op-kinds))) - eglot-confirm-server-edits))) - (cdr v)) - ;; Default entry - ((setq v (assoc t eglot-confirm-server-edits)) (cdr v))))) - -(defun eglot--propose-changes-as-diff (server prepared) - "Helper for `eglot--apply-workspace-edit'. -Goal is to popup a `diff-mode' buffer containing all the changes -of PREPARED, ready to apply with C-c C-a. PREPARED is a -list ((FILENAME EDITS VERSION)...)." - (with-current-buffer (get-buffer-create (eglot--server-buffer-name - server "proposed changes")) - (buffer-disable-undo (current-buffer)) - (let ((inhibit-read-only t) - (target (current-buffer))) - (diff-mode) - (erase-buffer) - (pcase-dolist (`(_ _ _ ,path ,edits ,_) prepared) - (with-temp-buffer - (let* ((diff (current-buffer)) - (existing-buf (find-buffer-visiting path)) - (existing-buf-label (prin1-to-string existing-buf))) - (with-temp-buffer - (if existing-buf - (insert-buffer-substring existing-buf) - (insert-file-contents path)) - (eglot--apply-text-edits edits nil t) - (diff-no-select (or existing-buf path) (current-buffer) nil t diff) - (when existing-buf - ;; Here we have to pretend the label of the unsaved - ;; buffer is the actual file, just so that we can - ;; diff-apply without troubles. If there's a better - ;; way, it probably involves changes to `diff.el'. - (with-current-buffer diff - (goto-char (point-min)) - (while (search-forward existing-buf-label nil t) - (replace-match (buffer-file-name existing-buf)))))) - (with-current-buffer target - (insert-buffer-substring diff)))))) - (setq-local buffer-read-only t) - (buffer-enable-undo (current-buffer)) - (goto-char (point-min)) - (pop-to-buffer (current-buffer)) - (font-lock-ensure) - (current-buffer))) - -(cl-defun eglot--apply-workspace-edit (server wedit origin &aux prepared) + (refactor-apply-text-edits + (mapcar (lambda (edit) + (eglot--dcase edit + (((TextEdit) range newText) + (cl-destructuring-bind (beg . end) (eglot-range-region range) + (list beg end newText))) + (((InsertReplaceEdit) newText replace) + (cl-destructuring-bind (beg . end) (eglot-range-region replace) + (list beg end newText))))) + edits) + :silent silent)) + +(cl-defun eglot--translate-workspace-edit (wedit) + "Compute list of `refactor-operation' from LSP workspace edit WEDIT." + (let ((pathify (symbol-function 'eglot-uri-to-path)) + (text-edit-op + (lambda (path edits version) + (make-instance + 'refactor-file-edit + :file path + :edits + (lambda () + (eglot--apply-text-edits edits version t)))))) + (eglot--dbind ((WorkspaceEdit) changes documentChanges) wedit + (append + (mapcar + (lambda (ch) + (pcase (plist-get ch :kind) + ("create" + (eglot--dbind ((CreateFile) uri ((:options o))) ch + (make-instance + 'refactor-file-creation + :file (funcall pathify uri) + :if-exists (cond ((plist-get o :ignoreIfExists) 'skip) + ((plist-get o :overwrite) 'overwrite) + (t 'error))))) + ("rename" + (eglot--dbind ((RenameFile) oldUri newUri ((:options o))) ch + (make-instance + 'refactor-file-renaming + :from (funcall pathify oldUri) + :to (funcall pathify newUri) + :if-exists (cond ((plist-get o :ignoreIfExists) 'skip) + ((plist-get o :overwrite) 'overwrite) + (t 'error))))) + ("delete" + (eglot--dbind ((DeleteFile) uri ((:options o))) ch + (make-instance + 'refactor-file-deletion + :file (funcall pathify uri) + :recursive (plist-get o :recursive) + :if-missing (if (plist-get o :ignoreIfNotExists) + 'skip 'error)))) + (_ + ;; It's a TextDocumentEdit (no kind field) + (eglot--dbind ((TextDocumentEdit) textDocument edits) ch + (eglot--dbind ((VersionedTextDocumentIdentifier) uri version) + textDocument + (funcall text-edit-op (funcall pathify uri) + edits version)))))) + documentChanges) + (unless (and changes documentChanges) + ;; Prefer `documentChanges' over sort-of-deprecated `changes'. + (cl-loop for (uri edits) on changes by #'cddr + collect (funcall text-edit-op (funcall pathify uri) + edits nil))))))) + +(cl-defun eglot--apply-workspace-edit (server wedit origin) "Apply (or offer to apply) the workspace edit WEDIT. ORIGIN is a symbol designating the command that originated this edit -proposed by the server. Returns a list (APPLIED REASON) indicating if -the edit was attempted and optionally why not." - ;; JT@2026-01-11: Note to future (self?). Most if this big function - ;; is preparing with the `prepared' (OP ...) list , where each OP is - ;; (KIND DESC APPLY-FN . MORE). KIND is a symbol, DESC is a string. - ;; APPLY-FN is a unary function of OP that applies the change. - ;; Sometimes there is MORE data, such as when KIND is eg. 'text-edit' - ;; and needs extra info for the diff rendering. - (cl-labels - ((pathify (x) (eglot-uri-to-path x)) - (do-create (path &key overwrite ignoreIfExists - &allow-other-keys) - (let ((exists (file-exists-p path))) - (when (and exists (not ignoreIfExists) (not overwrite)) - (eglot--error "File %s already exists" path)) - (when (or (not exists) overwrite) - (let ((dir (file-name-directory path))) - (unless (file-directory-p dir) - (make-directory dir t))) - (write-region "" nil path nil 'nomessage)))) - (do-rename (old-path new-path &key overwrite ignoreIfExists - &allow-other-keys) - (let ((new-exists (file-exists-p new-path))) - (when (and new-exists (not ignoreIfExists) (not overwrite)) - (eglot--error "File %s already exists" new-path)) - (let ((dir (file-name-directory new-path))) - (unless (file-directory-p dir) - (make-directory dir t))) - ;; If the old file is visited, rename the buffer too - (let ((buf (find-buffer-visiting old-path))) - (when buf - (with-current-buffer buf - (set-visited-file-name new-path t t)))) - (rename-file old-path new-path overwrite))) - (do-delete (path &key recursive ignoreIfNotExists &allow-other-keys) - (let ((exists (file-exists-p path))) - (when (and (not exists) (not ignoreIfNotExists)) - (eglot--error "File %s does not exist" path)) - (when exists - ;; Kill buffer if the file is visited - (let ((buf (find-buffer-visiting path))) - (when buf (kill-buffer buf))) - (delete-file path recursive)))) - (text-edit-op (path edits version) - `(text-edit - ,(format "Change %s (%d change%s)" path (length edits) - (if (> (length edits) 1) "s" "")) - ,(lambda (_op) - (with-current-buffer (find-file-noselect path) - (eglot--apply-text-edits edits version))) - ,path ,edits ,version)) - (mkfn (doit-fn &rest things) - (lambda (op) - (apply doit-fn things) - (eglot--message - "%s" (replace-regexp-in-string "^\\([^ ]+\\) " "\\1d " (cadr op))))) - (prepare (ch) - (pcase (plist-get ch :kind) - ("create" - (eglot--dbind ((CreateFile) uri ((:options o))) ch - (let ((p (pathify uri))) - `(create ,(format "Create `%s'" p) ,(mkfn #'do-create p o))))) - ("rename" - (eglot--dbind ((RenameFile) oldUri newUri ((:options o))) ch - (let ((ol (pathify oldUri)) (nw (pathify newUri))) - `(rename ,(format "Rename `%s' to `%s'" ol nw) - ,(mkfn #'do-rename ol nw o))))) - ("delete" - (eglot--dbind ((DeleteFile) uri ((:options o))) ch - (let ((p (pathify uri))) - `(delete ,(format "Delete `%s'" p) ,(mkfn #'do-delete p o))))) - (_ - ;; It's a TextDocumentEdit (no kind field) - (eglot--dbind ((TextDocumentEdit) textDocument edits) ch - (eglot--dbind ((VersionedTextDocumentIdentifier) uri version) - textDocument (text-edit-op (pathify uri) edits version)))))) - (user-accepts-p () - (y-or-n-p - (format "[eglot] Server wants to:\n%s\nProceed? " - (mapconcat (lambda (op) (concat " " (cadr op))) - prepared "\n")))) - (apply-all () - (cl-loop - for op in prepared - for (_kind _desc fn) = op - do (funcall fn op) - finally (eldoc) (eglot--message "Workspace edit successful")) - `(t nil))) - (eglot--dbind ((WorkspaceEdit) changes documentChanges) wedit - (setq prepared (mapcar #'prepare documentChanges)) - (unless (and changes documentChanges) - ;; Prefer `documentChanges' over sort-of-deprecated `changes'. - (cl-loop for (uri edits) on changes by #'cddr - do (push (text-edit-op (pathify uri) edits nil) prepared))) - (let* ((decision (eglot--confirm-server-edits origin prepared)) - (all-text-edits (cl-loop for (kind . _) in prepared - always (eq kind 'text-edit))) - (peaceful - (and - all-text-edits - (cl-loop for op in prepared - always (find-buffer-visiting (cadddr op)))))) - (cond - ((and (and (memq decision '(maybe-diff maybe-summary)) peaceful)) - (apply-all)) - ((memq decision '(diff maybe-diff)) - (cond (all-text-edits - (pop-to-buffer - (eglot--propose-changes-as-diff server prepared)) - `(nil "decision to apply manually")) - (t - ;; `map-y-or-n-p' heroics. Iterate over prepared - ;; operations with individual prompts, showing diffs - ;; for text-edit operations. - (let* ((wconf (current-window-configuration)) - (applied 0) - (total (length prepared))) - (unwind-protect - (progn - (map-y-or-n-p - (lambda (op) - (when (eq (car op) 'text-edit) - (display-buffer - (eglot--propose-changes-as-diff server (list op)))) - (format "[eglot] %s? " (cadr op))) - (lambda (op) - (set-window-configuration wconf) - (funcall (caddr op) op) - (cl-incf applied)) - (lambda () - ;; Skip text-edits for files that don't exist - ;; (e.g. user skipped the create operation). - (cl-loop for op = (pop prepared) while op - when (or (not (eq (car op) 'text-edit)) - (file-exists-p (cadddr op))) - return op)) - '("change" "changes" "apply")) - (if (= applied total) - (progn - (eldoc) - (eglot--message "Workspace edit successful") - `(t nil)) - `(nil "decision to abort"))) - (set-window-configuration wconf)))))) - ((memq decision '(t summary maybe-summary)) - (if (user-accepts-p) (apply-all) `(nil "decision to decline"))) - ((apply-all))))))) - -(cl-defun eglot--rename-interactive - (&aux - def region - (rename-support (eglot-server-capable-or-lose :renameProvider)) - (prepare-support (and (listp rename-support) - (plist-get rename-support :prepareProvider)))) - (setq - def - (cond (prepare-support - (let ((x (eglot--request (eglot--current-server-or-lose) - :textDocument/prepareRename - (eglot--TextDocumentPositionParams)))) - (cond ((null x) (user-error "[eglot] Can't rename here")) - ((plist-get x :placeholder)) - ((plist-get x :defaultBehavior) (thing-at-point 'symbol t)) - ((setq region (eglot-range-region x)) - (buffer-substring-no-properties (car region) (cdr region)))))) - (t (thing-at-point 'symbol t)))) - (list (read-from-minibuffer - (format "Rename `%s' to: " (or def "unknown symbol")) - nil nil nil nil def))) - -(defun eglot-rename (newname) - "Rename the current symbol to NEWNAME." - (interactive (eglot--rename-interactive)) - (let ((server (eglot--current-server-or-lose))) - (eglot--apply-workspace-edit - server - (eglot--request server :textDocument/rename `(,@(eglot--TextDocumentPositionParams) - :newName ,newname)) - this-command))) - -(defun eglot--code-action-bounds () - "Calculate appropriate bounds depending on region and point." - (let (diags boftap) - (cond ((use-region-p) `(,(region-beginning) ,(region-end))) - ((setq diags (eglot--flymake-sniff-diagnostics (point))) - (cl-loop for d in diags - minimizing (flymake-diagnostic-beg d) into beg - maximizing (flymake-diagnostic-end d) into end - finally (cl-return (list beg end)))) - ((setq boftap (bounds-of-thing-at-point 'sexp)) - (list (car boftap) (cdr boftap))) - (t - (list (point) (point)))))) +proposed by SERVER. Returns a list (APPLIED REASON) indicating if the +edit was attempted and optionally why not." + (ignore server) + (refactor-apply-changeset (eglot--translate-workspace-edit wedit) + :origin origin)) (cl-defun eglot--code-action-params (&key (beg (point)) (end beg) only triggerKind) @@ -4697,159 +4373,104 @@ the edit was attempted and optionally why not." ,@(when only `(:only [,only])) ,@(when triggerKind `(:triggerKind ,triggerKind))))) -(defun eglot-code-actions (beg &optional end action-kind interactive) - "Find LSP code actions of type ACTION-KIND between BEG and END. -Interactively, offer to execute them. -If ACTION-KIND is nil, consider all kinds of actions. -Interactively, default BEG and END to region's bounds else BEG is -point and END is nil, which results in a request for code actions -at point. With prefix argument, prompt for ACTION-KIND." - (interactive - `(,@(eglot--code-action-bounds) - ,(and current-prefix-arg - (completing-read "[eglot] Action kind: " - '("quickfix" "refactor.extract" "refactor.inline" - "refactor.rewrite" "source.organizeImports"))) - t)) +(cl-defmethod refactor-backend-name ((_backend (eql eglot))) + "Eglot") + +(defvar eglot--refactor-kinds + '((quickfix . "quickfix") (refactor . "refactor") + (extract . "refactor.extract") (inline . "refactor.inline") + (rewrite . "refactor.rewrite") (move . "refactor.move") + (source . "source") (organize-imports . "source.organizeImports") + (fix-all . "source.fixAll")) + "Alist mapping `refactor' kind symbols to LSP code action kinds.") + +(cl-defmethod refactor-backend-actions + ((_backend (eql eglot)) beg end &key rkind callback trigger-kind) (eglot-server-capable-or-lose :codeActionProvider) - (let* ((server (eglot--current-server-or-lose)) - (shortcut (and interactive - (not (listp last-nonmenu-event)) ;; not run by mouse - (overlayp eglot--suggestion-overlay) - (overlay-buffer eglot--suggestion-overlay) - (= beg (overlay-start eglot--suggestion-overlay)) - (= end (overlay-end eglot--suggestion-overlay)))) - (actions - (if shortcut - (overlay-get eglot--suggestion-overlay 'eglot--actions) - (eglot--request - server - :textDocument/codeAction - (eglot--code-action-params :beg beg :end end :only action-kind)))) - ;; Redo filtering, in case the `:only' didn't go through. - (actions (cl-loop for a across actions - when (or (not action-kind) - ;; github#847 - (string-prefix-p action-kind (plist-get a :kind))) - collect a))) - (cond - ((and shortcut actions (null (cdr actions))) - (eglot-execute server (car actions))) - (interactive - (eglot--read-execute-code-action actions server action-kind)) - (t actions)))) - -(defalias 'eglot-code-actions-at-mouse (eglot--mouse-call 'eglot-code-actions) - "Like `eglot-code-actions', but intended for mouse events.") - -(defun eglot--read-execute-code-action (actions server &optional action-kind) - "Helper for interactive calls to `eglot-code-actions'." - (let* ((menu-items - (or (cl-loop for a in actions - collect (cons (plist-get a :title) a)) - (apply #'eglot--error - (if action-kind `("No \"%s\" code actions here" ,action-kind) - `("No code actions here"))))) - (preferred-action (cl-find-if - (lambda (menu-item) - (plist-get (cdr menu-item) :isPreferred)) - menu-items)) - (default-action (car (or preferred-action (car menu-items)))) - (chosen (if (and action-kind (null (cadr menu-items))) - (cdr (car menu-items)) - (if (listp last-nonmenu-event) - (x-popup-menu last-nonmenu-event `("Eglot code actions:" - ("dummy" ,@menu-items))) - (cdr (assoc (completing-read - (format "[eglot] Pick an action (default %s): " - default-action) - menu-items nil t nil nil default-action) - menu-items)))))) - (when chosen - (eglot-execute server chosen)))) - -(defmacro eglot--code-action (name kind) - "Define NAME to execute KIND code action." - `(defun ,name (beg &optional end) - ,(format "Execute `%s' code actions between BEG and END." kind) - (interactive (eglot--code-action-bounds)) - (eglot-code-actions beg end ,kind t))) - -(eglot--code-action eglot-code-action-organize-imports "source.organizeImports") -(eglot--code-action eglot-code-action-extract "refactor.extract") -(eglot--code-action eglot-code-action-inline "refactor.inline") -(eglot--code-action eglot-code-action-rewrite "refactor.rewrite") -(eglot--code-action eglot-code-action-quickfix "quickfix") - -(define-fringe-bitmap 'eglot--fringe-action - [#b00000111 - #b00001110 - #b00011100 - #b00111000 - #b01111111 - #b00001110 - #b01011100 - #b01111000 - #b01110000 - #b01111000] - nil nil 'center) - -(defun eglot-code-action-suggestion (cb &rest _ignored) - "A member of `eldoc-documentation-functions', for suggesting actions." - (when (and (eglot-server-capable :codeActionProvider) - eglot-code-action-indications) - (let ((buf (current-buffer)) - (bounds (eglot--code-action-bounds)) - (use-text-p (memq 'eldoc-hint eglot-code-action-indications)) - tooltip blurb) - (eglot--async-request - (eglot--current-server-or-lose) - :textDocument/codeAction - (eglot--code-action-params :beg (car bounds) :end (cadr bounds) - :triggerKind 2) - :success-fn - (lambda (actions) - (eglot--when-buffer-window buf - (delete-overlay eglot--suggestion-overlay) - (when (cl-plusp (length actions)) - (setq blurb - (substitute-command-keys - (eglot--format "\\[eglot-code-actions]: %s" - (plist-get (aref actions 0) :title)))) - (if (>= (length actions) 2) - (setq blurb (concat blurb (format " (and %s more actions)" - (1- (length actions)))))) - (setq tooltip - (propertize eglot-code-action-indicator - 'face 'eglot-code-action-indicator-face - 'help-echo "mouse-1: execute code actions at point" - 'mouse-face 'highlight - 'keymap eglot-diagnostics-map)) - (save-excursion - (goto-char (car bounds)) - (let ((ov (make-overlay (car bounds) (cadr bounds)))) - (overlay-put ov 'eglot--actions actions) - (overlay-put ov 'eglot--overlay t) - (overlay-put - ov - 'before-string - (cond - ((memq 'nearby eglot-code-action-indications) - tooltip) - ((and - (memq 'left-fringe eglot-code-action-indications) - (< 0 (nth 0 (window-fringes)))) - (propertize - "⚡" 'display `(left-fringe - eglot--fringe-action - eglot-code-action-indicator-face))) - ((memq 'margin eglot-code-action-indications) - (propertize - "⚡" 'display `((margin left-margin) ,tooltip))))) - (setq eglot--suggestion-overlay ov)))) - (when use-text-p (funcall cb blurb)))) - :hint :textDocument/codeAction) - (and use-text-p t)))) + (cl-labels + ((kind (lsp-kind) + (when lsp-kind + (or (car (rassoc lsp-kind eglot--refactor-kinds)) + (let ((dot (string-match-p "\\." lsp-kind))) + (intern (replace-regexp-in-string + "\\." "-" (substring lsp-kind (if dot (1+ dot) 0)))))))) + (convert (actions) + (cl-loop for a across actions + for ra = (make-instance + 'refactor-action + :title (plist-get a :title) + :kind (kind (plist-get a :kind)) + :preferred (plist-get a :isPreferred) + :backend 'eglot + :data a) + collect ra))) + (let* ((server (eglot--current-server-or-lose)) + (lsp-rkind (and rkind (cdr (assq rkind eglot--refactor-kinds)))) + (params + (eglot--code-action-params :beg beg :end end :only lsp-rkind + :triggerKind trigger-kind))) + (cond + (callback + (eglot--async-request + server + :textDocument/codeAction + params + :success-fn (lambda (actions) (funcall callback (convert actions))) + :hint :textDocument/codeAction) + :async) + (t + (convert (eglot--request server :textDocument/codeAction params))))))) + +(cl-defmethod refactor-backend-execute + ((_backend (eql eglot)) action) + (eglot-execute (eglot--current-server-or-lose) (oref action data))) + +(cl-defmethod refactor-backend-rename-bounds + ((_backend (eql eglot))) + (let* ((rename-support (eglot-server-capable-or-lose :renameProvider)) + (prepare-support (and (listp rename-support) + (plist-get rename-support :prepareProvider)))) + (cond (prepare-support + (let ((x (eglot--request (eglot--current-server-or-lose) + :textDocument/prepareRename + (eglot--TextDocumentPositionParams)))) + (cond ((null x) nil) + ((plist-get x :range) (eglot-range-region (plist-get x :range))) + ((plist-get x :defaultBehavior) (bounds-of-thing-at-point 'symbol)) + (t (eglot-range-region x))))) + (t (bounds-of-thing-at-point 'symbol))))) + +(cl-defmethod refactor-backend-rename ((_backend (eql eglot)) newname) + (let ((server (eglot--current-server-or-lose))) + (eglot--translate-workspace-edit + (eglot--request server :textDocument/rename + `(,@(eglot--TextDocumentPositionParams) + :newName ,newname))))) + +(define-obsolete-function-alias 'eglot-code-actions 'refactor "32.1") +(define-obsolete-function-alias 'eglot-rename 'refactor-rename "32.1") +(define-obsolete-function-alias 'eglot-code-action-organize-imports + 'refactor-organize-imports "32.1") +(define-obsolete-function-alias 'eglot-code-action-extract + 'refactor-extract "32.1") +(define-obsolete-function-alias 'eglot-code-action-inline + 'refactor-inline "32.1") +(define-obsolete-function-alias 'eglot-code-action-rewrite + 'refactor-rewrite "32.1") +(define-obsolete-function-alias 'eglot-code-action-quickfix + 'refactor-quickfix "32.1") +(define-obsolete-function-alias 'eglot-code-actions-at-mouse + 'refactor-at-mouse "32.1") +(define-obsolete-variable-alias 'eglot-code-action-indications + 'refactor-indications "32.1") +(define-obsolete-variable-alias 'eglot-code-action-indicator + 'refactor-indicator "32.1") +(define-obsolete-face-alias 'eglot-code-action-indicator-face + 'refactor-indicator-face "32.1") +(define-obsolete-variable-alias 'eglot-diagnostics-map + 'refactor-mouse-map "32.1") +(define-obsolete-variable-alias 'eglot-confirm-server-edits + 'refactor-confirmation "32.1") ;;; File watchers (aka didChangeWatchedFiles) diff --git a/lisp/progmodes/refactor.el b/lisp/progmodes/refactor.el new file mode 100644 index 00000000000..ad2150395fc --- /dev/null +++ b/lisp/progmodes/refactor.el @@ -0,0 +1,995 @@ +;;; refactor.el --- Language-agnostic refactoring interface -*- lexical-binding: t; -*- + +;; Copyright (C) 2026 Free Software Foundation, Inc. +;; Author: João Távora + +;; Version: 0.1 +;; Keywords: convenience, languages +;; Package-Requires: ((emacs "26.3") (eldoc "1.14.0")) + +;; This is a GNU ELPA :core package. Avoid adding functionality that +;; is not available in the version of Emacs recorded above. + +;; This file is part of GNU Emacs. + +;; GNU Emacs is free software: you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. + +;; GNU Emacs is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with GNU Emacs. If not, see . + +;;; Commentary: + +;; `refactor.el' is a library for adding refactoring support for any +;; programming language. A refactoring, or refactor, is any rewrite to +;; a program that maintains its intended meaning, while (hopefully) +;; improving it. It could be extracting a function, inlining a +;; variable, renaming an identifier, organizing imports, or +;; automatically fixing a diagnostic. In `refactor.el' each such +;; potential rewrite is called an _action_ and embodied by the +;; `refactor-action' object. +;; +;; Note that this library is completely agnostic about the programming +;; language and major mode. By itself, it has no knowledge of how these +;; actions are discovered and eventually carried out: that's for other +;; Elisp programs to define and set up, in the form of `refactor.el' +;; _backends_. A very significant part of the code was extracted from +;; Emacs' LSP client Eglot, which now contains a simpler backend that +;; makes use of refactor.el. +;; +;;;; User interface +;; +;; In buffers where a working backend is set up, the library provides +;; some useful UI: a number of interactive commands for selecting +;; actions -- `refactor', `refactor-rename' and a few more shortcut +;; commands -- as well as the `refactor-suggestion-mode' minor mode, +;; which leverages the ElDoc system and endeavors to constantly keep the +;; user informed of which actions are available. This minor mode is the +;; familiar "lightning bolt/lightbulb on the side" that some IDEs +;; display. The variable `refactor-indications' is its main point of +;; customization. +;; +;; Each action has a "kind", which is used by the aforementioned +;; shortcut commands. For example, `refactor-quickfix' restricts +;; actions at point to the specific kind `quickfix' and ignores are +;; actions of other kids (like, say `extract' or `inline'). Depending +;; on the number of actions avaiable and the specific command, actions +;; are either automatically selected or presented to the user for +;; selection. +;; +;; Once an action is selected, it is executed, but its changes aren't +;; necessarily applied right away. The variable `refactor-confirmation' +;; controls whether and how the user confirms them first: as a summary +;; in the minibuffer, as a diff of the proposed changes, or not at all. +;; The choice can depend on the command, on the kinds of file +;; operations involved, and on whether the affected files are visited +;; in buffers. +;; +;;;; Elisp API +;; +;; The Elisp-facing parts of this library are useful for backend +;; authors: there are two distinct Elisp-facing interfaces, independent +;; of each other. Either is useful alone, though they can and normally +;; work together. +;; +;; - Action discovery and selection +;; +;; The interactive commands are entry points that communicate with +;; "refactor backends", i.e. any object returned by +;; `refactor-backend-functions'. The base `refactor' command asks +;; backends via `refactor-backend-actions' what "actions" +;; (i.e. potential refactorings) can be carried out for the buffer +;; near point. This is much like `xref-backend-functions' except that +;; unlike Xref, every applicable backend contributes. The backend who +;; provided the chosen action (regardless of how it was chosen) is +;; asked again to carry it out. This invokes its implementation of +;; the `refactor-backend-execute' method. Executing an action could +;; entail changes to the current buffer or to other buffers, even +;; changes to unvisited files, creation or deletion of files: the +;; library puts no constraints on the scope of an action. +;; +;; - Changeset application: +;; +;; To simplify and give consistency to the execution of actions, +;; we use the concept of _changeset_, an ordered list of +;; `refactor-operation' objects. Though not required, a normal +;; implementation of `refactor-backend-execute' would compute such a +;; changeset, then offer to apply it by calling +;; `refactor-apply-changeset'. `refactor-apply-changeset' carries out +;; each `refactor-operation' -- edits to files, creation of files, +;; renaming and deletion of files -- according to certain rules. For +;; example, it may offer a preview to the user as a summarized +;; description and ask for confirmation in the minibuffer, or it may +;; present the changeset as a diff, or it may skip confirmation +;; altogether. This is according to the user preferences in +;; `refactor-confirmation'. Note that an Elisp program may call this +;; directly for applying changes in a consistent and uniform manner +;; outside the context of `refactor-backend-execute'. +;; +;;; Code: + +(require 'cl-lib) +(require 'eieio) +(require 'flymake) +(eval-when-compile (require 'subr-x)) + +(defgroup refactor nil + "Refactoring support." ; hmmm, a bit short no? + :prefix "refactor-" + :group 'tools) + +;;;; Backends +;; JT@2026-08-21: While a hook may be overkill (a plain buffer-local +;; variable would likely do), it matches the Xref precedent. + +(defvar refactor-backend-functions nil + "Special hook to find the refactor backends for the current context. +Each function in this hook is called in turn with no arguments, and +should return nil if it is not applicable, or a refactor backend, that +is, a value on which the `refactor-backend-*' generic functions +dispatch. Unlike `xref-backend-functions' (which inspired this) every +backend contributes: for example the actions each supplies are merged +into a single list for the user to choose from.") + +(defun refactor-find-backends () + "Return the refactor backends applicable in the current context. +Run every function on `refactor-backend-functions' in turn and +collect the non-nil backends they return." + (let (retval) + (run-hook-wrapped 'refactor-backend-functions + (lambda (a) + (when-let* ((x (funcall a))) (push x retval)) + nil)) + (reverse retval))) + +(cl-defgeneric refactor-backend-name (backend) + "Return a short human-readable name for BACKEND." + (:method (backend) (symbol-name backend))) + +(cl-defgeneric refactor-backend-actions + (backend beg end &key rkind callback trigger-kind) + "Compute refactoring actions BACKEND offers between BEG and END. + +RKIND, if non-nil, restricts the result to that kind and its +sub-kinds. + +If CALLBACK is nil, return the list of `refactor-action' objects +directly; blocking to do so is acceptable. + +If CALLBACK is non-nil, either return the list of actions directly +anyway (when that is cheap) or return `:async' after arranging for +CALLBACK to be called with the list of actions eventually (but at most +once). CALLBACK may also be invoked synchronously, before this +function returns.") + +(cl-defgeneric refactor-backend-execute (backend action) + "Have BACKEND carry ACTION out, by whatever means it likes." + (:method (_backend _action) + (error "Refactor backend doesn't know how to execute actions"))) + +(cl-defgeneric refactor-backend-rename-bounds (backend) + "Return bounds of thing BACKEND could rename near point. +If the return value is a cons of buffer positions (BEG . END), these are +the bounds of the nearby thing that BACKEND claims as renameable. +A nil return means BACKEND does not claim this as renameable." + (:method (_backend) nil)) + +(cl-defgeneric refactor-backend-rename (backend newname) + "Compute a changeset renaming the identifier at point to NEWNAME." + (:method (_backend _newname) nil)) + + +;;;; Utils + +(defmacro refactor--defclass (name superclasses docstring &rest specs) + "Util for cutting down on defclass boilerplate. +NAME, SUPERCLASSES and DOCSTRING are as in `defclass'. Each of SPECS +is (SLOT INITFORM SLOT-DOCSTRING)." + (declare (indent 2) (debug (&define name sexp stringp &rest sexp))) + `(defclass ,name ,superclasses + ,(mapcar (lambda (spec) + (cl-destructuring-bind (slot initform slotdoc) spec + `(,slot :initarg ,(intern (concat ":" (symbol-name slot))) + :initform ,initform + :documentation ,slotdoc))) + specs) + :documentation ,docstring)) + + +;;;; Actions + +(refactor--defclass refactor-action () + "A refactoring a backend offers to perform." + (title nil "One-line description, shown to the user.") + (kind nil "A symbol from `refactor-kinds', or nil.") + (preferred nil "Non-nil if this is the obvious choice here.") + (backend nil "The backend that offered this action.") + (data nil "Opaque payload, meaningful to the backend.")) + + +;;;; Kinds + +;; Every action is tagged with a "kind" symbol. Could be e.g. +;; `quickfix' or `extract'. Kinds are organized in a hierarchy which is +;; what RKIND in `refactor' matches against. Specialized commands scope +;; down to just some kinds: so `M-x refactor-quickfix' offers only +;; actions tagged `quickfix'. In contrast, asking for the `refactor' +;; kind (with a prefix argument to `M-x refactor') also offers +;; `extract', `inline', `rewrite' and `move' ones. Plain `M-x refactor' +;; doesn't filter, and offers everything. Backends tag their actions +;; with any of the kinds defined below or may use the macros to define +;; their own. + +(defvar refactor-kinds nil + "List of all refactoring kinds defined so far, in definition order.") + +(defmacro refactor-defkind (name parent docstring) + "Define NAME as a kind of refactoring. +PARENT is the kind NAME specializes, or nil if NAME is itself a +top-level kind. DOCSTRING describes NAME to the user." + (declare (doc-string 3) (indent 2)) + `(progn + (put ',name 'refactor-kind-parent ',parent) + (put ',name 'refactor-kind-documentation ,docstring) + (unless (memq ',name refactor-kinds) + (setq refactor-kinds (append refactor-kinds (list ',name)))) + ',name)) + +(defun refactor-kind-matches-p (kind filter) + "Return non-nil if KIND is FILTER or one of its sub-kinds. +A nil FILTER matches everything." + (or (null filter) + (cl-loop for k = kind then (get k 'refactor-kind-parent) + while k thereis (eq k filter)))) + +(refactor-defkind quickfix nil "Fix a problem reported at point.") +(refactor-defkind refactor nil "Change code without changing what it does.") +(refactor-defkind extract refactor "Extract code into a new named entity.") +(refactor-defkind inline refactor "Inline a named entity into its call sites.") +(refactor-defkind rewrite refactor "Restate code in a different form.") +(refactor-defkind move refactor "Move an entity somewhere else.") +(refactor-defkind source nil "Act on a file rather than on a selection.") +(refactor-defkind organize-imports source "Tidy up import declarations.") +(refactor-defkind fix-all source "Apply every fix available in the file.") + + +;;;; Changesets + +;; A changeset is an ordered list of operations, each an instance of a +;; class below. Backends make them with `make-instance', and may +;; subclass the classes for operations we haven't thought of; +;; `refactor-apply-changeset' shows them to the user and carries them +;; out. FIXME: move this to the manual later. + +(refactor--defclass refactor-operation () + "Superclass of the operations making up a changeset.") + +(refactor--defclass refactor-file-edit (refactor-operation) + "Operation changing the text of a single file." + (file nil "Absolute name of the file to change.") + (edits nil "\ +Either a list of (BEG END NEWTEXT), where BEG and END are integer +positions valid in the widened buffer visiting the file, or a +function of no arguments returning such a list, called with that +buffer current. Edits must not overlap.")) + +(refactor--defclass refactor-file-creation (refactor-operation) + "Operation creating a file." + (file nil "Absolute name of the file to create.") + (contents nil "Initial contents, or nil for an empty file.") + (if-exists 'error "What to do if file exists: `error', `skip' or `overwrite'.")) + +(refactor--defclass refactor-file-renaming (refactor-operation) + "Operation renaming a file." + (from nil "Absolute name of the file to rename.") + (to nil "Absolute name to rename it to.") + (if-exists 'error "What to do if new name is taken: `error', `skip' or `overwrite'.")) + +(refactor--defclass refactor-file-deletion (refactor-operation) + "Operation deleting a file." + (file nil "Absolute name of the file to delete.") + (recursive nil "Non-nil to delete a directory's contents too.") + (if-missing 'error "What to do if file does not exist: `error' or `skip'.")) + +(cl-defgeneric refactor-operation-kind (operation) + "Return a symbol classifying OPERATION. +One of `edit', `create', `rename' or `delete' (the symbols +`refactor-confirmation' matches against)." + (:method ((_ refactor-file-edit)) 'edit) + (:method ((_ refactor-file-creation)) 'create) + (:method ((_ refactor-file-renaming)) 'rename) + (:method ((_ refactor-file-deletion)) 'delete)) + +(cl-defgeneric refactor-describe (operation) + "Return a one-line description of OPERATION." + (:method ((op refactor-file-edit)) + (with-slots (file edits) op + (if (functionp edits) + (format "Change `%s'" file) + (format "Change `%s' (%d change%s)" file + (length edits) (if (cdr edits) "s" ""))))) + (:method ((op refactor-file-creation)) + (format "Create `%s'" (oref op file))) + (:method ((op refactor-file-renaming)) + (with-slots (from to) op + (format "Rename `%s' to `%s'" from to))) + (:method ((op refactor-file-deletion)) + (format "Delete `%s'" (oref op file)))) + + +;;;; Collecting actions + +(cl-defun refactor--collect + (beg end &key rkind callback trigger-kind) + "Gather actions for BEG END from every applicable backend. + +This is the workhorse for `refactor' and `refactor-suggestion', the sync +and async modes of collecting actions, respectively. + +If CALLBACK is nil, return the merged list of `refactor-action's. + +If CALLBACK is non-nil, return `:async' and call CALLBACK once with the +merged list when every backend has delivered (which may happen before +this function returns, depending on the backends). A backend that +signals an error counts as having delivered no actions." + (let ((slots + ;; Each slot is (BACKEND DELIVERED-P . ACTIONS), DELIVERED-P + ;; being non-nil once BACKEND has delivered ACTIONS, via its + ;; callback or by returning them. + (mapcar (lambda (backend) (list backend nil)) + (refactor-find-backends)))) + (cl-labels + ((merged () + ;; Keep the first of each title, in hook order rather than + ;; delivery order, so that earlier backends win clashes even + ;; if they are slower. + (cl-remove-duplicates (apply #'append (mapcar #'cddr slots)) + :key (lambda (a) (oref a title)) + :test #'equal :from-end t)) + (deliver (result slot) + (setcar (cdr slot) t) + (setcdr (cdr slot) result) + (when (and callback (cl-every #'cadr slots)) + (funcall callback (merged)))) + (filter (actions) + (cl-remove-if-not + (lambda (a) + (refactor-kind-matches-p (oref a kind) rkind)) + actions))) + (dolist (slot slots) + (condition-case-unless-debug oops + (let ((result + (refactor-backend-actions + (car slot) beg end + :callback + (and callback + (lambda (result) + (deliver (filter result) slot))) + :rkind rkind + :trigger-kind trigger-kind))) + ;; A backend may even call its callback before returning + ;; actual actions. When it does, trust the callback's + ;; result over the return value. + (unless (or (cadr slot) + (eq result :async)) + (deliver (filter result) slot))) + (error + (message "refactor: backend %S failed: %S" + (car slot) (cdr oops)) + ;; Deliver no actions, unless already delivered. + (unless (cadr slot) (deliver nil slot))))) + (if callback :async (merged))))) + + +;;;; Commands + +(defvar refactor--suggestion-overlay) + +(defun refactor--bounds () + "Return (BEG END) for the current refactoring context. +This is the active region, if any, else it's the span covering any +Flymake diagnostics at point, else the bounds of the expression at +point, else point." + (let (diags boftap) + (cond ((use-region-p) `(,(region-beginning) ,(region-end))) + ((setq diags (flymake-diagnostics (point) (point))) + (cl-loop for d in diags + minimizing (flymake-diagnostic-beg d) into beg + maximizing (flymake-diagnostic-end d) into end + finally (cl-return (list beg end)))) + ((setq boftap (bounds-of-thing-at-point 'sexp)) + (list (car boftap) (cdr boftap))) + (t + (list (point) (point)))))) + +(defun refactor--read-execute-action (actions) + "Choose and execute one of ACTIONS, a list of `refactor-action's. +If there is only one, execute it without asking." + (let* ((menu-items (cl-loop for a in actions + collect (cons (oref a title) a))) + (preferred-action + (cl-find-if (lambda (menu-item) + (oref (cdr menu-item) preferred)) + menu-items)) + (default-action (car (or preferred-action (car menu-items)))) + (chosen (if (null (cdr menu-items)) + (cdr (car menu-items)) + (if (listp last-nonmenu-event) + (x-popup-menu last-nonmenu-event + `("Refactor:" + ("dummy" ,@menu-items))) + (cdr (assoc (completing-read + (format "Pick a refactoring (default %s): " + default-action) + menu-items nil t nil nil default-action) + menu-items)))))) + (when chosen (refactor-backend-execute (oref chosen backend) chosen)))) + +;;;###autoload +(defun refactor (beg &optional end rkind interactive) + "Find refactoring actions between BEG and END, and offer to run them. + +If RKIND, a symbol, is non-nil, restrict search to actions of that kind +and its sub-kinds; interactively with a prefix arg, choose from +`refactor-kinds'. + +Interactively, BEG and END default to automatically calculated bounds +and a prefix argument prompts for KIND. + +When INTERACTIVE is nil, return the list of `refactor-action' objects." + (interactive + `(,@(refactor--bounds) + ,(and current-prefix-arg + (intern + (completing-read + "Kind of refactoring: " + (mapcar (lambda (kind) + (cons (symbol-name kind) kind)) + refactor-kinds) + nil t))) + t)) + (let* ((shortcut + ;; Check if we can do an optimization/shortcut. + ;; `refactor-suggestion' may just recently have computed + ;; exactly what we wanted, stashing it in + ;; `refactor--suggestion-overlay'. Not when asked for a + ;; specific RKIND, though: those suggestions were requested + ;; with an "automatic" trigger kind, and backends may hold + ;; back some actions, like `fix-all' ones, in that case. + (and interactive + (null rkind) + (not (listp last-nonmenu-event)) ; not run by mouse + (overlay-buffer refactor--suggestion-overlay) + (= beg (overlay-start refactor--suggestion-overlay)) + (= end (overlay-end refactor--suggestion-overlay)))) + (actions + (if shortcut + ;; ...in which case we can skip re-contacting the backend. + (overlay-get refactor--suggestion-overlay 'refactor--actions) + (refactor--collect beg end :rkind rkind)))) + (unless actions + (user-error (if rkind "No \"%s\" refactorings here" "No refactorings here") + rkind)) + (if interactive (refactor--read-execute-action actions) actions))) + +(defmacro refactor--define-kind-command (name kind) + "Define NAME to execute KIND refactorings between BEG and END." + `(defun ,name (beg &optional end) + ,(format "Execute `%s' refactorings between BEG and END." kind) + (interactive (refactor--bounds)) + (refactor beg end ',kind t))) + +(defun refactor--mouse-call (what &optional update-mode-line) + "Make an interactive lambda for calling WHAT with the mouse." + (lambda (event) + (interactive "e") + (let ((start (event-start event))) + (with-selected-window (posn-window start) + (save-excursion + (unless (posn-area start) + (goto-char (posn-point start))) + (call-interactively what) + (when update-mode-line + (force-mode-line-update t))))))) + +(defalias 'refactor-at-mouse (refactor--mouse-call 'refactor) + "Like `refactor', but intended for mouse events.") + +(refactor--define-kind-command refactor-organize-imports organize-imports) +(refactor--define-kind-command refactor-extract extract) +(refactor--define-kind-command refactor-inline inline) +(refactor--define-kind-command refactor-rewrite rewrite) +(refactor--define-kind-command refactor-quickfix quickfix) +(refactor--define-kind-command refactor-fix-all fix-all) + +;;;###autoload +(defun refactor-rename (newname backend) + "Rename the symbol at point to NEWNAME via BACKEND. +Interactively, BACKEND is chosen to be the first backend in +`refactor-backend-functions' that claims the symbol at point." + (interactive + (pcase-let ((`(,backend . ,bounds) + (cl-loop for b in (refactor-find-backends) + when (refactor-backend-rename-bounds b) + return (cons b it)))) + (unless backend + (user-error "No backend can rename the symbol at point")) + (let ((sym-name (buffer-substring-no-properties (car bounds) (cdr bounds)))) + (list + (read-from-minibuffer (format "Rename `%s' to: " sym-name) + nil nil nil nil sym-name) + backend)))) + (refactor-apply-changeset (refactor-backend-rename backend newname) + :origin this-command)) + + +;;;; Suggestions + +;; Like in eglot, the state is a single overlay marking the bounds of +;; the actions available at point; `refactor-suggestion' is an ElDoc +;; member computing them, possibly asynchronously. +;; `refactor-suggestion-mode' adds it to `eldoc-documentation-functions' +;; and cleans up the overlay when disabled. The mode's lighter is +;; `refactor-mode-line-indicator', which shows `refactor-indicator' +;; while the overlay exists. Eglot, for one, does it when entering +;; `eglot--managed-mode'. + +(defcustom refactor-indications '(eldoc-hint left-fringe margin) + "How refactor backends indicate there are actions available at point. +Value is a list of symbols, more than one can be specified: + +- `eldoc-hint': ElDoc is used to hint about at-point actions; +- `left-fringe': A special indicator appears on the left fringe; +- `margin': A special indicator appears in the margin; +- `nearby': A special indicator appears near point. + +If the list is empty, no hinting happens. + +Note additionally: + +- Some values are incompatible; if one or more of `nearby', + `left-fringe' and `margin' are specified, earlier values take + precedence. +- The indicators for many of these are customizable via + `refactor-indicator' (which see), except for `left-fringe'." + :type '(set + :tag "Tick the ones you're interested in" + (const :tag "ElDoc textual hint" eldoc-hint) + (const :tag "Right besides point" nearby) + (const :tag "In left fringe" left-fringe) + (const :tag "In margin" margin))) + +(defface refactor-indicator-face + '((t (:inherit warning :weight bold))) + "Face used for action suggestions.") + +(defcustom refactor-indicator + (cl-loop for c in '(?↯ ?⭍ ?✓ ?α ??) + when (char-displayable-p c) + return (make-string 1 c)) + "Indicator string for action suggestions." + :type (let ((basic-choices + (cl-loop for c in '(?↯ ?⭍ ?✓ ?α ??) + when (char-displayable-p c) + collect `(const :tag ,(format "Use `%c'" c) + ,(make-string 1 c))))) + `(choice ,@basic-choices + (string :tag "Specify your own")))) + +(defvar-local refactor--suggestion-overlay (make-overlay 0 0) + "Overlay for `refactor-suggestion'.") + +(define-fringe-bitmap 'refactor--fringe-action + [#b00000111 + #b00001110 + #b00011100 + #b00111000 + #b01111111 + #b00001110 + #b01011100 + #b01111000 + #b01110000 + #b01111000] + nil nil 'center) + +(defmacro refactor--when-buffer-window (buf &rest body) + "Check BUF showing somewhere, then do BODY in it." + (declare (indent 1) (debug t)) + (let ((b (gensym))) + `(let ((,b ,buf)) + (when (get-buffer-window ,b) + (with-current-buffer ,b ,@body))))) + +(defvar refactor-mouse-map + (let ((map (make-sparse-keymap))) + (define-key map [mouse-2] #'refactor-at-mouse) + (define-key map [left-margin mouse-1] #'refactor-at-mouse) + map) + "Keymap active on action indicators and clickable diagnostics.") + +(defun refactor-suggestion (cb &rest _) + "A member of `eldoc-documentation-functions', for suggesting actions." + (when (and refactor-indications (refactor-find-backends)) + (let ((buf (current-buffer)) + (bounds (refactor--bounds)) + (use-text-p (memq 'eldoc-hint refactor-indications)) + indicator blurb) + (refactor--collect + (car bounds) (cadr bounds) + :trigger-kind 2 + :callback + (lambda (actions) + (refactor--when-buffer-window + buf + (when (overlay-buffer refactor--suggestion-overlay) + (delete-overlay refactor--suggestion-overlay)) + (when (cl-plusp (length actions)) + (setq blurb + (substitute-command-keys + (format "\\[refactor]: %s" + (oref (car actions) title)))) + (when (cdr actions) + (setq blurb (concat blurb (format " (and %s more actions)" + (length (cdr actions)))))) + (setq indicator + (propertize refactor-indicator + 'face 'refactor-indicator-face + 'help-echo "mouse-1: execute actions at point" + 'mouse-face 'highlight + 'keymap refactor-mouse-map)) + (save-excursion + (goto-char (car bounds)) + (let ((ov (make-overlay (car bounds) (cadr bounds)))) + (overlay-put ov 'refactor--actions actions) + (overlay-put + ov 'before-string + (cond + ((memq 'nearby refactor-indications) + indicator) + ((and (memq 'left-fringe refactor-indications) + (< 0 (nth 0 (window-fringes)))) + (propertize + "⚡" 'display `(left-fringe + refactor--fringe-action + refactor-indicator-face))) + ((memq 'margin refactor-indications) + (propertize + "⚡" 'display `((margin left-margin) ,indicator))))) + (setq refactor--suggestion-overlay ov))))) + ;; Answer the ElDoc strategy even if BUF isn't showing, else it + ;; could wait for us forever (like in non-interactive tests). + (when use-text-p (funcall cb blurb)))) + (and use-text-p t)))) + +;;;###autoload +(define-minor-mode refactor-suggestion-mode + "Minor mode for showing refactoring suggestions at point. +Add `refactor-suggestion' to `eldoc-documentation-functions' and +show `refactor-mode-line-indicator' while actions are available." + :init-value nil + :lighter refactor-mode-line-indicator + (if refactor-suggestion-mode + (add-hook 'eldoc-documentation-functions #'refactor-suggestion nil t) + (remove-hook 'eldoc-documentation-functions #'refactor-suggestion t) + (when (overlay-buffer refactor--suggestion-overlay) + (delete-overlay refactor--suggestion-overlay)))) + +(defvar refactor--mode-line-map + (let ((map (make-sparse-keymap))) + (define-key map [mode-line mouse-1] + (refactor--mouse-call 'refactor-at-mouse t)) + map) + "Keymap active on `refactor-mode-line-indicator'.") + +(defconst refactor-mode-line-indicator + '(:eval + (when (overlay-buffer refactor--suggestion-overlay) + `(" " (:propertize + ,refactor-indicator + face refactor-indicator-face + keymap ,refactor--mode-line-map + help-echo "mouse-1: execute actions at point" + mouse-face mode-line-highlight)))) + "Mode line construct for at-point refactoring actions.") +(put 'refactor-mode-line-indicator 'risky-local-variable t) + + +;;;; Flymake integration + +;; Flymake backends may use these categories if they want their +;; diagnostics to be clickable. `refactor-mouse-map' contains +;; a binding for `refactor-at-mouse'. +(cl-loop + for i from 1 + for type in '(refactor-note refactor-warning refactor-error) + for ftype in '(flymake-note flymake-warning flymake-error) + do + (put type 'flymake-category ftype) + (put type 'flymake-overlay-control + `((mouse-face . highlight) + (priority . ,(+ 50 i)) + (keymap . ,refactor-mouse-map)))) + + +;;;; Applying changes + +(cl-defun refactor-apply-text-edits (edits &key silent) + "Apply EDITS to current buffer as single undoable step. + +EDITS is a list of (BEG END NEWTEXT), or a function of no +arguments returning such a list, which is called with this buffer +current. BEG and END are positions valid in the widened buffer. +Edits must not overlap, but need not be sorted. + +Unless SILENT, report progress in the echo area." + (when (functionp edits) (setq edits (funcall edits))) + (unless edits (cl-return-from refactor-apply-text-edits)) + (atomic-change-group + (let* ((change-group (prepare-change-group)) + (howmany (length edits)) + (reporter (unless silent + (make-progress-reporter + (format "Applying %s edits to `%s'..." + howmany (current-buffer)) + 0 howmany))) + (done 0)) + ;; Convert every edit to markers up front, so that applying one + ;; cannot invalidate the positions of the others. + (mapc (pcase-lambda (`(,beg ,end ,newtext)) + (if (> emacs-major-version 30) + (replace-region-contents beg end newtext) + ;; Before Emacs 31, `replace-region-contents' wanted a + ;; function, so go through a temporary buffer. + (let ((source (current-buffer))) + (with-temp-buffer + (insert newtext) + (let ((temp (current-buffer))) + (with-current-buffer source + (save-excursion + (save-restriction + (narrow-to-region beg end) + (with-no-warnings + (replace-buffer-contents temp))))))))) + (when reporter + (progress-reporter-update reporter (cl-incf done)))) + (mapcar (pcase-lambda (`(,beg ,end ,newtext)) + (list (copy-marker beg) (copy-marker end) newtext)) + (reverse edits))) + (undo-amalgamate-change-group change-group) + (when reporter (progress-reporter-done reporter))))) + +(defcustom refactor-confirmation '((t . maybe-summary)) + "Control if changes proposed by a backend should be confirmed with user. + +If this variable's value is the symbol `diff', a diff buffer pops +up, allowing the user to apply each change individually. If the +symbol `summary' or any other non-nil value, the user is prompted +in the minibuffer with a short summary of changes. The symbols +`maybe-diff' and `maybe-summary' mean that the confirmation is +offered to the user only if the changes target files not visited +in buffers. Finally, a nil value means all changes are applied +directly without any confirmation. + +This variable's value can also be an alist ((KEY . ACTION) ...) +where KEY is either a symbol designating the invoked Emacs command +\(such as `refactor-rename', `refactor', `refactor-quickfix', +etc.), or a list of file operation kinds (`create', `rename', +`delete') contained in the changeset. ACTION is one of the +symbols described above. The value t for KEY is accepted and its +ACTION is the default value for commands or file operation kinds +not in the alist." + :type (let ((basic-choices + '((const :tag "Use diff" diff) + (const :tag "Summarize and prompt" summary) + (const :tag "Maybe use diff" maybe-diff) + (const :tag "Maybe summarize and prompt" maybe-summary) + (const :tag "Don't confirm" nil)))) + `(choice ,@basic-choices + (alist :tag "Per-command or per-kind alist" + :key-type (choice (function :tag "Command") + (repeat :tag "File operation kinds" symbol) + (const :tag "Default" t)) + :value-type (choice . ,basic-choices)))) + :version "32.1") + +(defconst refactor--changes-buffer-name "*refactor changes*" + "Name of the buffer used to preview proposed changes as a diff.") + +(defun refactor--confirmation (origin operations) + "Return the confirmation ACTION to use for OPERATIONS. +ORIGIN is a symbol designating the command that asked for them. Reads +`refactor-confirmation' and returns a symbol like `diff' or `summary', +or nil to apply without confirming." + (let ((v (lambda (candidate) (cdr (assq candidate refactor-confirmation)))) + kinds) + (or (and (symbolp refactor-confirmation) refactor-confirmation) + ;; Check for command-based entry + (funcall v origin) + ;; Check for operation-kind-based entry + (and (setq kinds (mapcar #'refactor-operation-kind operations)) + (cl-some (lambda (entry) + (and (listp (car entry)) + (cl-some (lambda (kind) + (memq kind (car entry))) + kinds) + (cdr entry))) + refactor-confirmation)) + ;; Default entry + (funcall v t)))) + +(cl-defgeneric refactor--apply-operation (operation) + "Carry OPERATION out." + (:method ((op refactor-file-edit)) + (with-slots (file edits) op + (with-current-buffer (find-file-noselect file) + (refactor-apply-text-edits edits)))) + (:method ((op refactor-file-creation)) + (with-slots (file contents if-exists) op + (let ((exists (file-exists-p file))) + (when (and exists (eq if-exists 'error)) + (error "File %s already exists" file)) + (when (or (not exists) (eq if-exists 'overwrite)) + (let ((dir (file-name-directory file))) + (unless (file-directory-p dir) (make-directory dir t))) + (write-region (or contents "") nil file nil 'nomessage))))) + (:method ((op refactor-file-renaming)) + (with-slots (from to if-exists) op + (let ((new-exists (file-exists-p to))) + (when (and new-exists (eq if-exists 'error)) + (error "File %s already exists" to)) + (unless (and new-exists (eq if-exists 'skip)) + (let ((dir (file-name-directory to))) + (unless (file-directory-p dir) (make-directory dir t))) + ;; If the old file is visited, rename the buffer too + (when-let* ((buf (find-buffer-visiting from))) + (with-current-buffer buf (set-visited-file-name to t t))) + (rename-file from to (eq if-exists 'overwrite)))))) + (:method ((op refactor-file-deletion)) + (with-slots (file recursive if-missing) op + (let ((exists (file-exists-p file))) + (when (and (not exists) (eq if-missing 'error)) + (error "File %s does not exist" file)) + (when exists + ;; Kill the buffer if the file is visited + (when-let* ((buf (find-buffer-visiting file))) (kill-buffer buf)) + (delete-file file recursive)))))) + +(defun refactor--apply-and-report (operation) + "Carry OPERATION out and say so in the echo area." + (refactor--apply-operation operation) + (unless (refactor-file-edit-p operation) + (message "%s" (replace-regexp-in-string + "^\\([^ ]+\\) " "\\1d " + (refactor-describe operation))))) + +(defun refactor--file-text (file) + "Insert the full text of FILE into the current buffer. +If a buffer is visiting FILE, take the text from there instead, +disregarding any narrowing, so that positions in the result agree +with positions in the widened buffer." + (if-let* ((buf (find-buffer-visiting file))) + (insert (with-current-buffer buf + (save-restriction + (widen) + (buffer-substring-no-properties (point-min) (point-max))))) + (insert-file-contents file))) + +(defun refactor--propose-changes-as-diff (operations) + "Return a `diff-mode' buffer with the changes OPERATIONS would make. +OPERATIONS are all `refactor-file-edit's. The buffer is ready to +apply with \\\\[diff-apply-buffer]." + (with-current-buffer (get-buffer-create refactor--changes-buffer-name) + (buffer-disable-undo (current-buffer)) + (let ((inhibit-read-only t) + (target (current-buffer))) + (diff-mode) + (erase-buffer) + (dolist (op operations) + (with-temp-buffer + (let* ((diff (current-buffer)) + (path (oref op file)) + (existing-buf (find-buffer-visiting path)) + (existing-buf-label (prin1-to-string existing-buf))) + (with-temp-buffer + (refactor--file-text path) + (refactor-apply-text-edits (oref op edits) + :silent t) + (diff-no-select (or existing-buf path) (current-buffer) nil t diff) + (when existing-buf + ;; Here we have to pretend the label of the unsaved + ;; buffer is the actual file, so that `diff-apply-buffer' + ;; works. If there's a better way, it probably involves + ;; changes to `diff.el'. + (with-current-buffer diff + (goto-char (point-min)) + (while (search-forward existing-buf-label nil t) + (replace-match (buffer-file-name existing-buf)))))) + (with-current-buffer target + (insert-buffer-substring diff)))))) + (setq-local buffer-read-only t) + (buffer-enable-undo (current-buffer)) + (goto-char (point-min)) + (font-lock-ensure) + (current-buffer))) + +(cl-defun refactor-apply-changeset (operations &key origin) + "Apply OPERATIONS, a changeset, after confirming with the user. + +OPERATIONS is a list of `refactor-operation' objects, applied in +order. ORIGIN is a symbol designating the command that produced +them; `refactor-confirmation' may key on it. + +Return a list (APPLIED REASON) saying whether the changes were +applied and, if not, why not; REASON is nil when they were." + (cl-labels + ((user-accepts-p () + (y-or-n-p + (format "These changes will be made:\n%s\nProceed? " + (mapconcat (lambda (op) + (concat " " (refactor-describe op))) + operations "\n")))) + (apply-all () + (mapc #'refactor--apply-and-report operations) + (eldoc) + (message "Refactoring applied") + `(t nil))) + (let* ((decision (refactor--confirmation origin operations)) + (all-edits (cl-every #'refactor-file-edit-p operations)) + (peaceful (and all-edits + (cl-every (lambda (op) + (find-buffer-visiting (oref op file))) + operations)))) + (cond + ((and (memq decision '(maybe-diff maybe-summary)) peaceful) + (apply-all)) + ((memq decision '(diff maybe-diff)) + (cond (all-edits + (pop-to-buffer (refactor--propose-changes-as-diff operations)) + `(nil "decision to apply manually")) + (t + ;; `map-y-or-n-p' heroics. Iterate over operations with + ;; individual prompts, showing diffs for edits. + (let* ((wconf (current-window-configuration)) + (remaining operations) + (applied 0) + (total (length operations))) + (unwind-protect + (progn + (map-y-or-n-p + (lambda (op) + (when (refactor-file-edit-p op) + (display-buffer + (refactor--propose-changes-as-diff (list op)))) + (format "%s? " (refactor-describe op))) + (lambda (op) + (set-window-configuration wconf) + (refactor--apply-and-report op) + (cl-incf applied)) + (lambda () + ;; Skip edits to files that don't exist (e.g. + ;; the user skipped the create operation). + (cl-loop for op = (pop remaining) while op + when (or (not (refactor-file-edit-p op)) + (file-exists-p (oref op file))) + return op)) + '("change" "changes" "apply")) + (if (= applied total) + (progn + (eldoc) + (message "Refactoring applied") + `(t nil)) + `(nil "decision to abort"))) + (set-window-configuration wconf)))))) + ((memq decision '(t summary maybe-summary)) + (if (user-accepts-p) (apply-all) `(nil "decision to decline"))) + ((apply-all)))))) + +(provide 'refactor) +;;; refactor.el ends here diff --git a/test/lisp/progmodes/eglot-tests.el b/test/lisp/progmodes/eglot-tests.el index 266ca8ce3fd..d09d66b372f 100644 --- a/test/lisp/progmodes/eglot-tests.el +++ b/test/lisp/progmodes/eglot-tests.el @@ -653,7 +653,7 @@ directory hierarchy." (eglot--find-file-noselect "rename-project/main.c") (eglot--tests-connect) (goto-char (point-min)) (search-forward "foo") - (eglot-rename "bar") + (refactor-rename "bar" 'eglot) (should (equal (buffer-string) "int bar() {return 42;} int main() {return bar();}"))))) commit 6986459062cad277b8e0f304575d20ec4c00f3cb Author: João Távora Date: Tue Oct 27 07:47:10 2026 +0000 Flymake: don't call trusted-content-p in Emacs < 30 in flymake.el * lisp/progmodes/flymake.el (flymake--run-backend): Add fboundp check. diff --git a/lisp/progmodes/flymake.el b/lisp/progmodes/flymake.el index 9dc39d83f22..0b79e31de92 100644 --- a/lisp/progmodes/flymake.el +++ b/lisp/progmodes/flymake.el @@ -1326,7 +1326,10 @@ with a report function." (flymake--state-disabled state) nil (flymake--state-reported-p state) nil)) (condition-case-unless-debug err - (if (or (trusted-content-p) (function-get backend 'flymake-always-safe)) + (if (or + ;; No notion of trust before Emacs 30. + (if (fboundp 'trusted-content-p) (trusted-content-p) t) + (function-get backend 'flymake-always-safe)) (apply backend (flymake-make-report-fn backend run-token) args) ;; FIXME: Use `bwrap' for untrusted content. commit e5e3b5f4c047ca1de8634813b826917edc2516ab Author: João Távora Date: Tue Oct 27 07:47:10 2026 +0000 Xref: make xref.el loadable in Emacs 26 again Package-Requires says Emacs 26.1. Not all things will work (like xref-edit-mode), but at least it is loadable and keeps the basic functionality. * lisp/progmodes/xref.el (text-property-search): Require softly. (xref-mouse-mode-map): Don't use defvar-keymap. diff --git a/lisp/progmodes/xref.el b/lisp/progmodes/xref.el index bdad1cb77bf..ad5d1327f0e 100644 --- a/lisp/progmodes/xref.el +++ b/lisp/progmodes/xref.el @@ -85,7 +85,7 @@ (require 'cl-lib) (require 'ring) (require 'project) -(require 'text-property-search) +(require 'text-property-search nil t) ; Emacs≥27 (require 'map) (eval-and-compile @@ -1970,7 +1970,7 @@ This command is intended to be bound to a mouse event." (xref-find-references identifier)) (user-error "No identifier here")))) -(defvar-keymap xref-mouse-mode-map +(defvar xref-mouse-mode-map ;; Using "Control-Click" has been popularized TextMate and it's ;; descendants (Sublime, Atom, VSCode) and even other traditions such ;; as Eclipse or the IntelliJ editor suite. @@ -1978,9 +1978,12 @@ This command is intended to be bound to a mouse event." ;; TODO: Add some kind of hovering indication that a identifier under ;; the mouse cursor has a definition we could jump to. - ;; Don't run `mouse-buffer-menu' on the down event. - "C-" #'ignore - "C-" #'xref-find-definitions-at-mouse) + (let ((map (make-sparse-keymap))) + ;; Don't run `mouse-buffer-menu' on the down event. + (define-key map [C-down-mouse-1] #'ignore) + (define-key map [C-mouse-1] #'xref-find-definitions-at-mouse) + map) + "Keymap for `xref-mouse-mode'.") ;;;###autoload (define-minor-mode xref-mouse-mode