Mingo
Mingo

Reputation: 1613

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.

Upvotes: 9

Views: 3582

Answers (2)

sjas
sjas

Reputation: 19667

;; this will output ls
(global-set-key (kbd "C-x :") (lambda () (interactive) (shell-command "ls")))

;; this is bonus and not directly related to the question
;; will insert the current date into active buffer
(global-set-key (kbd "C-x :") (lambda () (interactive) (insert (shell-command-to-string "date"))))

The lambda defines an anonymous function instead. That way you do not have to define a helper function which will be bound to a key in another step.

lambda is the keyword, and the next parentheses pair holds your arguments, if some were needed. Rest is analoguous to any regular function definition.

Upvotes: 3

Tikhon Jelvis
Tikhon Jelvis

Reputation: 68152

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

Upvotes: 13

Related Questions