Emacs: Spaces to New Lines 📜

By Xah Lee. Date: . Last updated: .

Spaces to New Lines

Here's a command to convert spaces to newline characters.

For example,

cat dog cow

becomes

cat
dog
cow

Here's the code.

(defun xah-space-to-newline ()
  "Replace space sequence to a newline char in current block or selection.

URL `http://xahlee.info/emacs/emacs/emacs_space_to_newline.html'
Created: 2017-08-19
Version: 2025-03-25"
  (interactive)
  (let (xbeg xend)
    (seq-setq (xbeg xend) (if (region-active-p) (list (region-beginning) (region-end)) (list (save-excursion (if (re-search-backward "\n[ \t]*\n" nil 1) (match-end 0) (point))) (save-excursion (if (re-search-forward "\n[ \t]*\n" nil 1) (match-beginning 0) (point))))))
    (save-restriction
      (narrow-to-region xbeg xend)
      (goto-char (point-min))
      (while (re-search-forward " +" nil t)
        (replace-match "\n")))))