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?

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

  • I have tried this and still appears not to work. Any ideas? – cammil Jan 27 '17 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 Jan 27 '17 at 17:21
  • Actually it appears that the dired-after-readin-hook is not being called. Not sure why. – cammil Jan 27 '17 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 Jan 27 '17 at 17:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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