Search code examples
macosemacselispdired

define keybinding for dired to run a command ("open ") on the file under the cursor


I want to stop using finder in OSX and use dired instead. OSX has a command, "open ", to open any file in the default app from the cli. (Example: "open $the_file"). This works fine with C-! followed by me entering "open " but I'd like to do both those thing with a key combination, say C-0.

How can I create a function that does the equivalent of "C-!" -> "open " in dired when I press C-0 with the cursor over a filepath?

(EDIT: I found a solution, macros!)


Solution

  • I reset lawlist-filename to nil at the end of each example so that it can be used in a variety of other functions, including, but not limited to, dired-read-file-name: dired-read-file-name: pop-up dired mode to read-file-name

    EDIT:  Rewritten with the help of @phils -- uses let bindings, instead of global variables.

    (eval-after-load "dired" '(progn
    
      ;; open anything externally with OSX default app -- Wide-Open-Throttle!
      (define-key dired-mode-map (kbd "z") (lambda () (interactive)
        (let ((lawlist-filename (dired-get-file-for-visit)))
          (start-process "default-app" nil "open" lawlist-filename))))
    
      ;; open *.pdf file externally with the OSX default *.pdf viewer.
      (define-key dired-mode-map (kbd "<SPC>") (lambda () (interactive)
        (let ((lawlist-filename (dired-get-file-for-visit)))
          (if (equal (file-name-extension lawlist-filename) "pdf")
            (start-process "default-pdf-app" nil "open" lawlist-filename)))))
    
      ;; open *.pdf file externally using Skim.
      (define-key dired-mode-map (kbd "v") (lambda () (interactive)
        (let* (
          (lawlist-filename (dired-get-file-for-visit))
          (skim "/Applications/Skim.app/Contents/MacOS/Skim") )
          (if (equal (file-name-extension lawlist-filename) "pdf")
            (start-process "pdf-with-skim" nil "open" "-a" skim lawlist-filename)))))
    
    ))