Search code examples
emacselispdired

How to delete-process with similar name (one at a time) from newest to oldest


I have a situation where I may have several processes running simultaneously with the following names:

preview
preview<1>
preview<2>
preview<3>
preview<4>

I am looking for some assistance, please, to create a function that will delete the newest process (i.e., the one with the highest number) each time the function is activated -- until the processes with numbers no longer exist, and then delete the final process (preview) without a number.

In other words, calling the function once would delete preview<4> -- calling the function again would delete preview<3>, and so on until all of them are gone.

I have a function that previews the file contents from dired mode on an OSX machine using:

EDIT:  Replaced (car (dired-get-marked-files)) with (dired-get-file-for-visit), which permits acting upon the file underneath the cursor even though others have been marked already. Removed global variable, and updated with complete keyboard shortcut.

;; Preview using qlmanage.
(define-key dired-mode-map (kbd "<SPC>") (lambda () (interactive)
  (start-process "preview" nil "qlmanage" "-p" (dired-get-file-for-visit))))

and I have set up a key to delete one process named "preview":

(define-key dired-mode-map (kbd "<escape>") (lambda () (interactive)
  (delete-process (get-process "preview"))

Solution

  • I'd imagine something like this would work:

    (defun kill-last-process-named (name)
      (cl-loop with name-re = 
               (format "^%s\\(?:<\\([[:digit:]]+\\)>\\)?" (regexp-quote name))
       for process in (process-list)
       for pname = (process-name process)
       if (string-match name-re pname)
       collect (cons (string-to-number (or (match-string 1 pname) "0")) process)
       into processes
       finally (delete-process (cdar (cl-sort processes '> :key 'car)))))