tramp-term.el icon indicating copy to clipboard operation
tramp-term.el copied to clipboard

Automatically "cd" into directory from default-directory

Open matthewbauer opened this issue 6 years ago • 2 comments

This would be helpful to me. Basically, when 'tramp-term' has no arguments, load up what's in default-directory, parsing host, username and directory using tramp.

matthewbauer avatar Mar 04 '18 21:03 matthewbauer

You could do something like that:

(add-hook 'tramp-term-after-initialized-hook (lambda (host) (term-send-raw-string (concat "cd " default-directory (kbd "RET")))))

apauzies avatar May 16 '19 03:05 apauzies

The following function will do this,and a bit more: This will look at the current buffer's working directory and open a terminal pointing at that directory. If the buffer is local, it just opens an ansi-term. If its a TRAMP buffer, it opens a tramp-term to that host, and then 'cd's to the same working directory.

Just call my-tramp-term-here. It will work with local buffers and tramp/ssh buffers, but not other tramp transports (I don't think tramp-term itself supports those either). It also only works with a single hop.

I can work this up into a pull request to add it to tramp-term itself if desired. I'm very new to elisp, so this might not be the smartest implementation but it seems to work.

(defun my-tramp-term--cd-hook(host)
  (term-send-raw-string (concat "cd " (tramp-file-name-localname ts) ";clear" (kbd "RET")))
)

(defun my-tramp-term-here()
    (interactive)
    (if (tramp-tramp-file-p default-directory)
         (let ((ts (tramp-dissect-file-name default-directory)))
           (if (string= (tramp-file-name-method ts) "ssh")
               (progn
                 (add-hook 'tramp-term-after-initialized-hook 'my-tramp-term--cd-hook)
                 (if (tramp-file-name-user ts)
                     (tramp-term (list (tramp-file-name-user ts) (tramp-file-name-host ts)))
                   (tramp-term (list (tramp-file-name-host ts)))
                   )
                 (remove-hook 'tramp-term-after-initialized-hook 'my-tramp-term--cd-hook)
                 )
             (message "tramp-term-here: Unsupported Tramp method. Only ssh supported"))
           )
      (ansi-term (or explicit-shell-file-name "bash") "localhost")
      )
    )

bdk0 avatar Sep 03 '21 17:09 bdk0