Skip to content

Instantly share code, notes, and snippets.

@ieure
Created November 2, 2019 19:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ieure/885335e047878d504d39b34e1a1ff4e6 to your computer and use it in GitHub Desktop.
Save ieure/885335e047878d504d39b34e1a1ff4e6 to your computer and use it in GitHub Desktop.
(defun toggle-alternate-file-as-root (&optional filename)
"Toggle between the current file as the default user and as root."
(interactive)
(let* ((filename (or filename (buffer-file-name)))
(parsed (when (tramp-tramp-file-p filename)
(coerce (tramp-dissect-file-name filename)
'list))))
(unless filename
(error "No file in this buffer."))
(find-alternate-file
(if (equal '("sudo" "root") (butlast parsed 2))
;; As non-root
(if (or
(string= "localhost" (nth 2 parsed))
(string= (system-name) (nth 2 parsed)))
(nth -1 parsed)
(apply 'tramp-make-tramp-file-name
(append (list tramp-default-method nil) (cddr parsed))))
;; As root
(if parsed
(apply 'tramp-make-tramp-file-name
(append '("sudo" "root") (cddr parsed)))
(tramp-make-tramp-file-name "sudo" "root" nil "localhost" nil filename))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment