Emacs: Convert File Line Ending for All Files in a Dir 🚀

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.

put this in your Emacs Init File:

(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 2022-04-07"
    (if (eq major-mode 'dired-mode )
      (list (buffer-file-name)))
    (completing-read "Line ending:" '("Linux/MacOSX/Unix" "MacOS9" "Windows") nil "REQUIRE-MATCH")))
  (let* (
           ((equal Style "Linux/MacOSX/Unix") 'unix)
           ((equal Style "MacOS9") 'mac)
           ((equal Style "Windows") 'dos)
           (t (error "code logic error 65327. Expect one of it." )))))
     (lambda (x) (xah-convert-file-coding-system x xcodingSystem))

(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 2022-01-23 2022-01-23"
  (let (
        (xbufferOpened-p (get-file-buffer Fpath)))
    (if xbufferOpened-p
        (with-current-buffer xbufferOpened-p
          (if (string-match (concat (symbol-name Coding-System) "$")
                            (symbol-name buffer-file-coding-system))
              (set-buffer-file-coding-system Coding-System)
      (with-temp-file Fpath
        (insert-file-contents Fpath)
        (if (string-match (concat (symbol-name Coding-System) "$")
                          (symbol-name buffer-file-coding-system))
            (set-buffer-file-coding-system Coding-System)))))))

Emacs Line Ending

Xah Emacs Commands