Emacsのanythingで.ssh/configを情報源としてtramp接続

.ssh/configはたいへん便利です。

Host foo
  Hostname example.com
  User     example

としておけば、

ssh foo

で接続できちゃうし、IdentityFileやportなんかも覚えさせておけちゃう。

ので、これをAnythingの情報源にしたら、さらにハピーになれます。

(defvar anything-c-source-my-hosts
  '((name . "hosts")
    (candidates . (lambda () (anything-c-source-my-hosts-candidates)))
    (type . file)
    (action . (("Tramp" . anything-tramp-open)))))

(defun anything-c-source-my-hosts-candidates ()
  "Tramp candidates."
  (let ((source (split-string
                 (with-temp-buffer
                   (insert-file-contents "~/.ssh/config")
                   (buffer-string))
                 "\n"))
        (hosts (list)))
    ;; trim
    (dolist (host source)
      (when (string-match "[H\\|h]ost +\\(.+?\\)$" host)
        (setq host (string-trim (substring host (match-beginning 1) (match-end 2))))
        (unless (string= host "*")
          (add-to-list
           'hosts
           (concat "/" tramp-default-method ":" host ":") t))))
    hosts))

(defun anything-tramp-open (path)
  "Tramp open.  PATH is path."
  (find-file path))

(defun my-anything-for-tramp ()
  "Anything command for .ssh/config."
  (interactive)
  (anything-other-buffer
   '(anything-c-source-my-hosts)
   "*my-anything-for-tramp*"))

ジャンル: Emacs