1

I am hoping to define an interactive function that I can invoke with M-x <function-name> and that will:

  1. Automatically grab the path to the file
  2. Run the following code on it:

    (require 'tramp)
    C-x C-f /sudo::/path/to/file
    

In case it is not clear, the goal is to have this function (re-)open the file in sudo mode.

How can I go about writing this function? Sorry if this is a bit elementary, I have just started to learn elisp.

Drew
  • 75,699
  • 9
  • 109
  • 225
Amelio Vazquez-Reina
  • 5,157
  • 4
  • 32
  • 47

1 Answers1

4

Do you want to visit (e.g., create) a file that has the same name as the buffer, even if the buffer is not visiting a file? If so:

(defun foo (file)
  (interactive
   (list (expand-file-name (or (buffer-file-name) (buffer-name)))))
  (require 'tramp)
  (find-file (concat "/sudo::" file)))

Do you want to raise an error if the current buffer is not visiting a file? If so:

(defun foo (file)
  (interactive
   (progn (unless (buffer-file-name) (error "Not visiting a file"))
          (list (expand-file-name (buffer-file-name)))))
  (require 'tramp)
  (find-file (concat "/sudo::" file)))
Drew
  • 75,699
  • 9
  • 109
  • 225