Update multi-term buffer name based on PWD

后端 未结 2 1607
南笙
南笙 2021-01-15 17:38

If I use konsole or other terminal, the terminal tag name can change based on PWD. But in multi-term, the buffer name is *terminal*. This is not v

相关标签:
2条回答
  • 2021-01-15 17:43

    AFAIK there is no easy way to retrieve information from a running process.

    But if you want to get the current directory you could:

    1. ask the shell to print it
    2. parse and trace the command-line for functions like cd, pushd, popd…
    3. poll /proc/PID/cwd

    The first method is described in the header of term.el (M-xfind-libraryRETtermRET).

    And now, thank you for your question, you gave me the opportunity to do this:

    (defadvice term-send-input (after update-current-directory)
      (let* ((pid (process-id (get-buffer-process (current-buffer))))
             (cwd (file-truename (format "/proc/%d/cwd" pid))))
        (cd cwd)))
    
    (ad-activate 'term-send-input)
    

    It's a naive implementation of the third method and it doesn't work if the user uses su or ssh. However, I don't know if it's possible withouth using the first or the second method.

    In your case, you can just replace the cd command with whatever you want.

    0 讨论(0)
  • 2021-01-15 17:43

    Building off of Daimrod's answer for polling /proc/PID/cwd, I found a way get around the problem that Reed pointed out where the advice doesn't pick up the updated CWD immediately and you have to hit Enter twice.

    If you move the CWD update code to its own function and use run-at-time to call it from the advice at a later time, it will pick up the updated CWD correctly. Unfortunately I don't know enough about Emacs' scheduling to explain why this works (any enlightenment would be appreciated).

    Here's my code based on Daimrod's. Note I advised term-send-input for line-mode and term-send-return for char-mode. I tested this using multi-term on Emacs 24.3.1:

    (defadvice term-send-input (after update-current-directory)
      (run-at-time "0.1 sec" nil 'term-update-dir)
      )
    
    (ad-activate 'term-send-input)
    
    (defadvice term-send-return (after update-current-directory)
      (run-at-time "0.1 sec" nil 'term-update-dir)
      )
    
    (ad-activate 'term-send-return)
    
    (defun term-update-dir ()
      (let* ((pid (process-id (get-buffer-process (current-buffer))))
             (cwd (file-truename (format "/proc/%d/cwd" pid))))
        (unless (equal (file-name-as-directory cwd) default-directory)
          (message (concat "Switching dir to " cwd))
          (cd cwd)))
      )
    
    0 讨论(0)
提交回复
热议问题