index all rss twitter github linkedin email
Álvaro Ramírez

Álvaro Ramírez

06 April 2020 Emacs's counsel-M-x meets multiple cursors

I'm a fan of Magnar Sveen's multiple cursors Emacs implementation. It's just so fun to use and works very well with commands bound to my favorite keys.

Every now and then I'd like to execute extended commands on all cursors, but they have no keys bound to them. If you're an ivy/counsel fan like me (and all packages by Abo Abo), you use counsel-M-x to invoke commands. However, counsel-M-x doesn't support multiple cursors out of the box. Luckily, this is Emacs and we can fix that…

Back in December 2019, I made a note to revisit u/snippins1987's weekly tip to pair helm-M-x with multiple cursors. Finally got back to it. With a few changes, we can also make the snippet work with counsel-M-x \o/.

(defun adviced:counsel-M-x-action (orig-fun &rest r)
  "Additional support for multiple cursors."
  (apply orig-fun r)
  (let ((cmd (intern (car r))))
    (when (and (boundp 'multiple-cursors-mode)
               (not (memq cmd mc--default-cmds-to-run-once))
               (not (memq cmd mc/cmds-to-run-once))
               (or mc/always-run-for-all
                   (memq cmd mc--default-cmds-to-run-for-all)
                   (memq cmd mc/cmds-to-run-for-all)
                   (mc/prompt-for-inclusion-in-whitelist cmd)))
      (mc/execute-command-for-all-fake-cursors cmd))))

(advice-add #'counsel-M-x-action