summaryrefslogtreecommitdiffstats
path: root/lisp/init-tramp.el
blob: 28983a786ad9eb7e7ccfa1b3dd9b453b2cfdbc37 (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
53
54
55
(defun sudo-prefix-p (prefix)
  "Return t if PREFIX is a sudo prefix."
  (or (string-equal prefix "/sudo") (string-equal prefix "/sudo:")))

(defun ssh-prefix-p (prefix)
  "Return t if PREFIX is a ssh prefix."
  (string-equal prefix "/ssh"))

(defun sudo-file-name (filename)
  "Return FILENAME with a sudo prefix.

If FILENAME already has a sudo prefix, do nothing. If FILENAME is
accessed over SSH, prefix it with \"/sudo:\". Otherwise, assume
FILENAME is a local path and prefix it with \"/sudo::\"."
  (let* ((splitname (split-string filename ":"))
         (prefix (car splitname))
         (ssh-p (ssh-prefix-p prefix))
         (sudo-p (sudo-prefix-p prefix)))
    (if sudo-p
        filename
      (let ((sudo-prefix (if ssh-p "/sudo" "/sudo:"))
            (components (if ssh-p (cdr splitname) splitname)))
        (mapconcat 'identity (cons sudo-prefix components) ":")))))

(defun 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 (sudo-file-name buffer-file-name))
    (find-file (sudo-file-name (read-file-name "Find file with sudo: ")))))

(defun sudo-current-file ()
  (interactive)
  (sudo-find-file t))

(use-package tramp
  :init
  ;; disable vc integration for remote files
  (setq vc-ignore-dir-regexp
        (format "\\(%s\\)\\|\\(%s\\)"
                vc-ignore-dir-regexp
                tramp-file-name-regexp))

  :bind
  (("C-x +" . sudo-find-file)
   ("C-x !" . 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)))

(provide 'init-tramp)