radian-software / radian

🍉 Dotfiles that marry elegance and practicality.
MIT License
490 stars 47 forks source link

radian-fix-whitespace-mode when buffer-file-coding-system is binary #480

Closed haji-ali closed 1 year ago

haji-ali commented 3 years ago

Consider the following code

(progn
  (switch-to-buffer (generate-new-buffer "test.bin"))
  (insert "\r\n")
  (setq buffer-file-coding-system 'binary)
  (write-file "/tmp/test.bin")  )

When executed in Radian, the mode radian-fix-whitespace-mode is automatically enabled causing the \r to not be written. This is working as programmed since radian-fix-whitespace-mode is enabled regardless of buffer-file-coding-system and has an enabled global mode (so even if I disabled the mode before writing, write-file actually renables it).

I am not sure what is the best way to fix this from Radian. I am currently doing

(progn
  (switch-to-buffer (generate-new-buffer "test.bin"))
  (setq buffer-file-coding-system 'binary)
  (radian-fix-whitespace-mode -1)
  (insert "\r\n")
  (setq buffer-file-name "/tmp/test.bin")
  (save-buffer))

to get around this problem. But I was wondering if there's a better solution.

PS: This is a MWE of a more serious problem. In my case, when saving archive files (from arc-mode), radian-fix-whitespace-mode changes the content of the buffer causing the archive file to be corrupted.

raxod502 commented 3 years ago

Perhaps https://github.com/raxod502/radian/pull/481 would be a simple solution?

haji-ali commented 3 years ago

I think this solution should fix the issue with write-file when it reloads the file, but it would still require disabling radian-fix-whitespace-mode before calling write-file.

This is because, in the example above, radian-fix-whitespace-mode is enabled before I get to set buffer-file-coding-system.

One solution would be for radian-fix-whitespace-mode to use before-save-hook to enable these options conditionally and disable them if buffer-file-coding-system is binary (or no-conversion which is an alias per the docs).

raxod502 commented 3 years ago

Ah, I see. Yes, that seems pretty reasonable. We can globally add a function to before-save-hook that will inspect the value of radian-fix-whitespace-mode and set require-final-newline accordingly. Furthermore, that function can conditionally invoke delete-trailing-whitespace, instead of the mode adding delete-trailing-whitespace directly to before-save-hook.