CollioTV
CollioTV

Reputation: 686

Executing shell command on emacs file opening

I'm currently using the terminal Terminator, and i got a bash function set_title() { printf '\e]2;%s\a' "$*"; } wich permit me to set the terminator window title

So I would want to know if it's possible to execute this specific shell command (like this): set_title ##filename on each opening (or re-opening) of the said file in emacs?

(btw english is not my native language, please be indulgent!)

Upvotes: 1

Views: 406

Answers (2)

Stefan
Stefan

Reputation: 28531

If you mean that you're running the non-GUI Emacs inside bash inside Terminator and you want Terminator's title to reflect the current file in Emacs, then the fact that bash sits in between is of no use to you: Emacs is in control here.

But you can define an Elisp function that will do the same job as your set_title:

(defun my-set-title (title)
  (send-string-to-terminal (format "\e]2;%s\a" title)))

And then you could use it via find-file-hook:

(add-hook 'find-file-hook (lambda () (my-set-title buffer-file-name)))

Note that this will set the terminal's title to the last file Emacs visits, so if you switch back to a previous file-buffer via C-x C-b, the title won't be updated to reflect the current buffer's file name. If you want to do that, you'd need something more like:

(defvar my-last-file nil)

(defun my-keep-file-title ()
  (when (and buffer-file-name
             (not (equal buffer-file-name my-last-file)))
    (setq my-last-file buffer-file-name)
    (my-set-title buffer-file-name)))

(add-hook 'post-command-hook #'my-keep-file-title)

Upvotes: 1

sds
sds

Reputation: 60014

As suggested by @Dan, you can do

(add-hook find-file-hook
  (lambda ()
    (when (string= buffer-file-name "my-file")
      (shell-command "printf ...."))))

to call printf when you open "my-file".

However, if what you want is to set the frame title (emacs calls "frame" what window managers call "window"), you should be setting frame-title-format, e.g.:

(setq frame-title-format
      '(buffer-file-name "%b - %f" ; File buffer
        (dired-directory dired-directory ; Dired buffer
         (revert-buffer-function "%b" ; Buffer Menu
          ("%b - Dir: " default-directory)))) ; Plain buffer
      icon-title-format "%b")

Upvotes: 1

Related Questions