Wednesday, January 28, 2009

emacs change from Unix to Dos endings?

How to change file line endings between Mac/Dos/Unix?

Open the file, then do “Alt+x set-buffer-file-coding-system” (Ctrl+x Enter f). Give it a value of mac, dos, unix. Then, when you save the file, it'll be saved with the proper encoding for newlines.


ctl-x return f then dos

Note: Unixes (including Linuxes and Mac OS X) uses LF (ascii 10; line feed) for newline. Mac OS Classic uses CR (ascii 13; carriage return) for newline. (Mac OS X prefers LF but accepts CR too) Windows uses CR followed by LF ("\r\n") for its newline char. See wikipedia newline for detail.

To do it batch on a list of files, use the following lisp code:

(defun to-unix-eol (fpath)
"Change file's line ending to unix convention."
(let (mybuffer)
(setq mybuffer (find-file fpath))
(set-buffer-file-coding-system 'unix) ; or 'mac or 'dos
(kill-buffer mybuffer)

(mapc 'to-unix-eol
; ...
If you want the function to work on marked files in dired, then use the following code:

(defun dired-2unix-marked-files ()
"Change to unix line ending for marked (or next arg) files."
(mapc 'to-unix-eol (dired-get-marked-files))

Select the code and do “Alt+x eval-region”, then “Alt+x dired”, then press “m” to mark the files you want, then do “Alt+x dired-dos2unix-marked-files”.

hat tip: