如何让emacs自动写入只读文件?

时间:2010-06-19 02:43:09

标签: emacs elisp

我发现自己编辑了许多只读文件。我经常点击C-x C-q来致电toggle-read-only。然后我点击C-x C-s保存并获取,

File foo.txt is write-protected; try to save anyway? (y or n)

点击y后,文件将被保存,文件权限保持为只读。

有没有办法缩短这个过程并使之成为简单地用C-x C-s保存文件而不提示?我应该考虑在chmodbefore-save-hook中插入after-save-hook还是有更好的方式?

4 个答案:

答案 0 :(得分:4)

chmod中添加对before-save-hook的调用将是实现此目的的简洁方法。没有任何设置可以更改以避免权限检查。

根据后续问题,听起来您希望在打开时自动将文件更改为可写。这段代码可以解决问题:

(defun change-file-permissions-to-writable ()
  "to be run from find-file-hook, change write permissions"
  (when (not (file-writable-p buffer-file-name))
    (chmod buffer-file-name (file-modes-symbolic-to-number "u+w" (nth 8 (file-attributes buffer-file-name))))
    (if (not (file-writable-p buffer-file-name))
        (message "Unable to make file writable."))))

(add-hook 'find-file-hook 'change-file-permissions-to-writable)

注意:当我在Windows机器上测试它时,文件权限在我尝试保存缓冲区之前没有显示,但它按预期工作。我个人对这种定制感到不安,但这是你的Emacs。 :)

答案 1 :(得分:3)

我同意Trey认为普遍做一个chmod写入是有风险的 - 只读文件是只读的有一个原因,恕我直言。这是一种在每个缓冲区的基础上专门覆盖事物的方法。它不是理想的,它会在缓冲区的生命周期内覆盖file-writable-p(或者至少在你将my-override-mode-on-save切换回nil之前),但它会让你有意识地逐个文件地做出决定。基础(排序;它实际上是缓冲区的缓冲基础,非常相似)。当然,因为您希望在访问文件时自动切换只读标志,所以您可能对这种区别不感兴趣。不过,这里是;享受它或忽略它。

(make-variable-buffer-local
 (defvar my-override-mode-on-save nil
   "Can be set to automatically ignore read-only mode of a file when saving."))

(defadvice file-writable-p (around my-overide-file-writeable-p act)
  "override file-writable-p if `my-override-mode-on-save' is set."
  (setq ad-return-value (or
                         my-override-mode-on-save
                         ad-do-it)))

(defun my-override-toggle-read-only ()
  "Toggle buffer's read-only status, keeping `my-override-mode-on-save' in sync."
  (interactive)
  (setq my-override-mode-on-save (not my-override-mode-on-save))
  (toggle-read-only))

P.S。感谢Trey对other SO question中的ad-return-value指针。

答案 2 :(得分:1)

因为我发现不断提醒我即将编辑一个我没有权限的文件很有用,当我在缓冲区中打开文件时,我想强迫自己主动使缓冲区可写{{1 }}。然后用手工打开它是非常繁琐的,所以我建议C-x q在没有写入的情况下提示我输入密码。我完全建议您将此代码段放在save-buffer

.emacs

答案 3 :(得分:0)

由于某种原因,我无法确定Trey Jackson solution在Windows下的gnu emacs 25.2上不起作用:从file-modes-rights-to-number调用的file-modes-rights-to-number失败了。 如果有人遇到同样的问题,他可以使用一个不太优雅但可行的解决方案replace block:

(chmod buffer-file-name (file-modes-symbolic-to-number "u+w" (nth 8 (file-attributes buffer-file-name))))

带块:

(cond ((or (eq system-type 'ms-dos) (eq system-type 'windows-nt))
              (progn
                (shell-command-to-string (concat "attrib -R " (buffer-file-name (current-buffer))))
                (message "Setting file and buffer to writeable (%s style)" system-type)
              ))
           ((eq system-type 'gnu/linux)
              (progn
              (shell-command-to-string (concat "chmod u+w " (buffer-file-name (current-buffer))))
              (message "Setting file and buffer to writeable (%s style)" system-type)
             ))
           (t (message "file permission change not handle for OS %s" system-type))               
)