开发者

Emacs: how to set up warning of file size significantly reduced, when saving file?

开发者 https://www.devze.com 2022-12-14 20:05 出处:网络
I had just lost most of the content of my notes in a text file, when I used emacs, and there was a bug, but I ignored the error message, and forced a file save. After a few hours, I found that my newl

I had just lost most of the content of my notes in a text file, when I used emacs, and there was a bug, but I ignored the error message, and forced a file save. After a few hours, I found that my newly saved file had only a few bytes left! Most of my notes in the file had gone.

I wish that I had set up warning of file size change significantly, when saving a file in emacs. I saw such message 开发者_StackOverflowbefore from emacs before, but I don't know how I can set it up now? Please share with m me any pointer to a solution. Worst come to worst, it should be possibe to add some checking in the hook for file save to implement it.

Thanks in advance!

Yu Shen


Depending on what kind of warning you want, this solves your problem. The current delta is 8M, obviously you can customize this how you want. If you want a more intrusive warning, you can uncomment the call to 'y-or-n-p, and get rid of the message.

(defvar check-buffer-size-delta (* 8 1024 1024)
  "Delta in size over which the user will be warned when saving.")
(defun check-buffer-size-on-save ()
  "Warn user if buffer has changed by more than CHECK-BUFFER-SIZE-DELTA since last save"
  (let ((delta (abs (- (buffer-size) buffer-saved-size))))
    (when (> delta check-buffer-size-delta)
      (beep)
      ;; (y-or-n-p "WARNING: Buffer has changed by %d bytes since last save.  Do you know what you're doing? "
      (message "WARNING: Buffer has changed by %d bytes since last save." delta))))

(add-hook 'before-save-hook 'check-buffer-size-on-save)


This is not specific to Emacs, but if you want to avoid losing work in the future, committing your work to a version control system is very helpful. I generally use Git, but some people find Mercurial a bit simpler to use (there are lots of others, like Subversion, Bazaar, and so on, but Git and Mercurial are the most popular distributed revision control systems, which make it easier to just version control a directory on your disk without setting up a server). A version control system allows you to record the history of your work as you go, so if you make some sort of big mistake you can just revert back to an older version.

0

精彩评论

暂无评论...
验证码 换一张
取 消