Emacs: Convert File Line Ending

By Xah Lee. Date: . Last updated: .

Here's emacs command that convert file line endings (Linux, Microsoft Windows, Mac OS 9), on current file, or marked files in dired in batch.

(defun xah-change-file-line-ending-style (Files Style)
  "Change current file or dired marked file's newline convention.

When called in lisp, Style is one of 'unix 'dos 'mac or any of accepted emacs coding system. See `list-coding-systems'.

URL `http://xahlee.info/emacs/emacs/elisp_convert_line_ending.html'
Version: 2016-10-16"
  (interactive
   (list
    (if (eq major-mode 'dired-mode )
        (dired-get-marked-files)
      (list (buffer-file-name)))
    (ido-completing-read "Line ending:" '("Linux/MacOSX/Unix" "MacOS9" "Windows") "PREDICATE" "REQUIRE-MATCH")))
  (let* (
         ($codingSystem
          (cond
           ((equal Style "Linux/MacOSX/Unix") 'unix)
           ((equal Style "MacOS9") 'mac)
           ((equal Style "Windows") 'dos)
           (t (error "code logic error 65327. Expect one of it." )))))
    (mapc
     (lambda (x) (xah-convert-file-coding-system x $codingSystem))
     Files)))

(defun xah-convert-file-coding-system (Fpath Coding-System)
  "Convert file's encoding.
 Fpath is full path to file.
 Coding-System is one of 'unix 'dos 'mac or any of accepted emacs coding system. See `list-coding-systems'.

If the file is already opened, it will be saved after this command.

URL `http://xahlee.info/emacs/emacs/elisp_convert_line_ending.html'
Version: 2015-07-24"
  (let ($buffer
        ($bufferOpened-p (get-file-buffer Fpath)))
    (if $bufferOpened-p
        (with-current-buffer $bufferOpened-p
          (set-buffer-file-coding-system Coding-System)
          (save-buffer))
      (progn
        (setq $buffer (find-file Fpath))
        (set-buffer-file-coding-system Coding-System)
        (save-buffer)
        (kill-buffer $buffer)))))

See also:

Spent a few hours here?

Xah Emacs Commands

buffer

file

edit

edit brackets

copy paste

whitespace

reformat

misc