summaryrefslogtreecommitdiffstats
path: root/lisp/init-tramp.el
blob: 8c9c579aa3d2b1db4627cae5bf4027333b4fe193 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
;;; init-tramp.el --- configure tramp  -*- lexical-binding:t -*-
;;; Commentary:
;;; Code:

(defun mpolden/sudo-file-name (filename)
  "Add a sudo-like TRAMP method to FILENAME.

If FILENAME already contains a sudo-like method, do nothing. If
FILENAME is accessed over SSH, replace \"/ssh:\" with
\"/sudo:\" or \"/doas:\". Otherwise, assume FILENAME is a local
path and prefix it with \"/sudo::\" or \"/doas::\"."
  ;; sudo:remote-host works because of the special tramp-default-proxies-alist
  ;; configuration below
  (let* ((splitname (split-string filename ":"))
         (method (car splitname)))
    (if (member method '("/sudo" "/doas"))
        filename
      (let* ((is-ssh (equal method "/ssh"))
             (sudo-method (concat (if (executable-find "doas" t) "/doas" "/sudo")
                                  (if is-ssh "" ":")))
             (components (if is-ssh (cdr splitname) splitname)))
        (mapconcat 'identity (cons sudo-method components) ":")))))

(defun mpolden/sudo-find-file (&optional arg)
  "Find file and open it with sudo.
With a prefix ARG prompt edit currently visited file using sudo."
  (interactive "P")
  (if arg
      (find-alternate-file (mpolden/sudo-file-name buffer-file-name))
    (find-file (mpolden/sudo-file-name (read-file-name "Find file with sudo: ")))))

(defun mpolden/sudo-current-file ()
  "Open current file with sudo."
  (interactive)
  (mpolden/sudo-find-file t))

(use-package tramp
  :bind
  (("C-x +" . mpolden/sudo-find-file)
   ("C-x !" . mpolden/sudo-current-file))

  :config
  ;; make sudo:remote-host work as expected
  (add-to-list 'tramp-default-proxies-alist '(nil "\\`root\\'" "/ssh:%h:"))
  (add-to-list 'tramp-default-proxies-alist
               '((regexp-quote (system-name)) nil nil))
  ;; use path configured by remote host
  (add-to-list 'tramp-remote-path 'tramp-own-remote-path))

(provide 'init-tramp)

;;; init-tramp.el ends here