Your code is doing what you want - almost. The problem is that it does not wait for the Dired buffer to be filled with the listing before it executes the toggling of marks. It toggles marks before any files are actually listed - so it does nothing.
You can see this if you add, e.g., (sleep-for 2.0)
or similar after your call to find-dired
.
A real solution involves not just waiting arbitrarily but checking to see when the find
command is finished before toggling the marks.
You can put the mark-toggling on a hook such as dired-readin-hook
. However, since you also want to remove that action from the hook after it is done, the function that you add to the hook should do both of these things: (1) toggle the marks and then (2) remove itself from the hook.
(defun find-and-toggle ()
(interactive)
(add-hook 'dired-after-readin-hook 'f-dired-toggle-marks)
(find-dired "~/my-project" "-name *.py"))
(defun f-dired-toggle-marks ()
(dired-toggle-marks)
(remove-hook 'dired-after-readin-hook 'f-dired-toggle-marks))
Oops. For that to work you need to use library find-dired+.el
.
Here is some code that works without that library:
(defun find-and-toggle ()
(interactive)
(advice-add 'find-dired-sentinel :after 'f-dired-toggle-marks)
(find-dired "~/my-project" "-name *.py"))
(defun f-dired-toggle-marks (&rest ignore)
(dired-toggle-marks)
(advice-remove 'find-dired-sentinel 'f-dired-toggle-marks))
Among other enhancements, the version of find-dired-sentinel
in library find-dired+.el
runs hooks find-dired-hook
and dired-after-readin-hook
. Without that library you need to advise function find-dired-sentinel
.
If you have an older version of Emacs, which does not have the new advice system (advice-add
, advice-remove
) then you will need to use the old advice system (defadvice
).