xuinkrbin.
xuinkrbin.

Reputation: 1015

Emacs equivalent to VIM's `%`?

In VIM, One can use % to indicate the current filename when invoking a shell command. Can Anyone point Me in the direction of documentation showing what the equivalent is in emacs?

Upvotes: 5

Views: 762

Answers (3)

pjammer
pjammer

Reputation: 9577

in my case, using the emacs 24 gui version from homebrew.... I see the filename as the 3rd item in from the bottom left corner of the (minor)-mode-bar, just above the mini-buffer.

To see where i am, using ido-mode i just do C-x C-f No config needed there.

Upvotes: 0

jpkotta
jpkotta

Reputation: 9437

You can use this whenever the minibuffer expects you to type something (caveat: does not work with ido, but obviously you can always get out of that with e.g. C-x C-f). You can also use it in regular buffers.

(defun insert-filename-or-buffername (&optional arg)
  "If the buffer has a file, insert the base name of that file.
  Otherwise insert the buffer name.  With prefix argument, insert the full file name."
  (interactive "P")
  (let* ((buffer (window-buffer (minibuffer-selected-window)))
         (file-path-maybe (buffer-file-name buffer)))
    (insert (if file-path-maybe
                (if arg
                    file-path-maybe
                  (file-name-nondirectory file-path-maybe))
              (buffer-name buffer)))))

(define-key minibuffer-local-map (kbd "C-c f") 'insert-filename-or-buffername)

Upvotes: 1

scottfrazer
scottfrazer

Reputation: 17337

There isn't one. But this is Emacs! So here:

(defun my-shell-command-on-current-file (command &optional output-buffer error-buffer)
  "Run a shell command on the current file (or marked dired files).
In the shell command, the file(s) will be substituted wherever a '%' is."
  (interactive (list (read-from-minibuffer "Shell command: "
                                           nil nil nil 'shell-command-history)
                     current-prefix-arg
                     shell-command-default-error-buffer))
  (cond ((buffer-file-name)
         (setq command (replace-regexp-in-string "%" (buffer-file-name) command nil t)))
        ((and (equal major-mode 'dired-mode) (save-excursion (dired-move-to-filename)))
         (setq command (replace-regexp-in-string "%" (mapconcat 'identity (dired-get-marked-files) " ") command nil t))))
  (shell-command command output-buffer error-buffer))

(global-set-key (kbd "M-!") 'my-shell-command-on-current-file)

Upvotes: 5

Related Questions