How do I change read/write mode for a file using Emacs?

前端 未结 9 1049
悲&欢浪女
悲&欢浪女 2021-01-29 21:11

If a file is set to read only mode, how do I change it to write mode and vice versa from within Emacs?

9条回答
  •  一生所求
    2021-01-29 22:02

    If only the buffer (and not the file) is read-only, you can use toggle-read-only, which is usually bound to C-x C-q.

    If the file itself is read-only, however, you may find the following function useful:

    (defun set-buffer-file-writable ()
      "Make the file shown in the current buffer writable.
    Make the buffer writable as well."
      (interactive)
      (unix-output "chmod" "+w" (buffer-file-name))
      (toggle-read-only nil)
      (message (trim-right '(?\n) (unix-output "ls" "-l" (buffer-file-name)))))
    

    The function depends on unix-output and trim-right:

    (defun unix-output (command &rest args)
      "Run a unix command and, if it returns 0, return the output as a string.
    Otherwise, signal an error.  The error message is the first line of the output."
      (let ((output-buffer (generate-new-buffer "*stdout*")))
        (unwind-protect
         (let ((return-value (apply 'call-process command nil
                        output-buffer nil args)))
           (set-buffer output-buffer)
           (save-excursion 
             (unless (= return-value 0)
               (goto-char (point-min))
               (end-of-line)
               (if (= (point-min) (point))
               (error "Command failed: %s%s" command
                  (with-output-to-string
                      (dolist (arg args)
                    (princ " ")
                    (princ arg))))
               (error "%s" (buffer-substring-no-properties (point-min) 
                                       (point)))))
             (buffer-substring-no-properties (point-min) (point-max))))
          (kill-buffer output-buffer))))
    
    (defun trim-right (bag string &optional start end)
      (setq bag (if (eq bag t) '(?\  ?\n ?\t ?\v ?\r ?\f) bag)
        start (or start 0)
        end (or end (length string)))
      (while (and (> end 0)
              (member (aref string (1- end)) bag))
        (decf end))
      (substring string start end))
    

    Place the functions in your ~/.emacs.el, evaluate them (or restart emacs). You can then make the file in the current buffer writable with M-x set-buffer-file-writable.

提交回复
热议问题