4

This is what I have so far:

(defun find-and-toggle ()
  (interactive)
  (find-dired "~/my-project" "-name *.py")
  (dired-toggle-marks))

This switches to the find-dired buffer, but dired-toggle-marks appears to do nothing. What am I doing incorrectly?

1 Answer 1

4

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).

4
  • I have tried this and still appears not to work. Any ideas?
    – cammil
    Commented Jan 27, 2017 at 17:10
  • I used the code in your answer, then ran (find-and-toggle) the find-dired buffer appeared, with some found files, but none were toggled. Not sure if that is not enough information?
    – cammil
    Commented Jan 27, 2017 at 17:21
  • Actually it appears that the dired-after-readin-hook is not being called. Not sure why.
    – cammil
    Commented Jan 27, 2017 at 17:27
  • I edited the answer to take care of this. Thx. Let me know if it still does not work for you.
    – Drew
    Commented Jan 27, 2017 at 17:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.