
This is just a generic search and replace. Really you could make a macro for any search and replace you do on a regular basis.
;;; A interactive function for replacing all dos ;;; carriage returns (^M) with Unix ;;; line feeds in a selected buffer. (defun dos2unix (buffer) "Automate M-% C-q C-m RET C-q C-j RET" (interactive "b buffer to convert" ) (goto-char (point-min)) (while (search-forward (string ?\C-m) nil t) (replace-match "" nil t)))
#1 by Hagen on January 18, 2008 - 10:34 am
Not to be a smart ass, but the function doesn’t do what it says in the description. It replaces the ^M with nothing, not with ^J. For most files this is fine, since the ^M appears at the end of the line. If the ^M is immersed in the lines you have to (replace-match (string ?\C-j) nil t) of course. In the file I needed this for (thank you for your function as my starting point), both cases appeared. So I solved it inelegant but pragmatic this way:
(defun dos2unix (buffer)
(interactive “b buffer to convert” )
(goto-char (point-min))
(while (search-forward (string ?\C-m?\C-j) nil t)
(replace-match (string ?\C-j) nil t))
(goto-char (point-min))
(while (search-forward (string ?\C-m) nil t)
(replace-match (string ?\C-j) nil t)))
#2 by A R Baboon on January 20, 2008 - 1:18 pm
The Microsoft line ending is prepends each line feed with a carriage return. All we want to do strip out any carriage returns. I would say that we should do a more sophisticated pattern match for line ending, etc., but I am not sure there should ever be carriage returns in a file.
#3 by A R Baboon on January 20, 2008 - 1:21 pm
It would be good to save and restore the point for convenience. Also a unix2dos has now become useful for diff/cvs interactions.