Search code examples
emacsdired

How to bind a key to run a shell command in dired emacs


When i use dired mode in emacs, I can run a shell command by type !xxx, But how to bind a key to run this command? For example, I want to press O on a file, then dired will run 'cygstart' to open this file.


Solution

  • You can use the shell-command function. For example:

    (defun ls ()
      "Lists the contents of the current directory."
      (interactive)
      (shell-command "ls"))
    
    (global-set-key (kbd "C-x :") 'ls); Or whatever key you want...
    

    To define a command in a single buffer, you can use local-set-key. In dired, you can get the name of the file at point using dired-file-name-at-point. So, to do exactly what you asked:

    (defun cygstart-in-dired ()
      "Uses the cygstart command to open the file at point."
      (interactive)
      (shell-command (concat "cygstart " (dired-file-name-at-point))))
    (add-hook 'dired-mode-hook '(lambda () 
                                  (local-set-key (kbd "O") 'cygstart-in-dired)))