Emacs: Spaces to New Lines

By Xah Lee. Date: . Last updated: .

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.
Works on current block or selection.

URL `http://ergoemacs.org/emacs/emacs_space_to_newline.html'
Version 2017-08-19"
  (interactive)
  (let* ( $p1 $p2 )
    (if (use-region-p)
        (progn
          (setq $p1 (region-beginning))
          (setq $p2 (region-end)))
      (save-excursion
        (if (re-search-backward "\n[ \t]*\n" nil "move")
            (progn (re-search-forward "\n[ \t]*\n")
                   (setq $p1 (point)))
          (setq $p1 (point)))
        (re-search-forward "\n[ \t]*\n" nil "move")
        (skip-chars-backward " \t\n" )
        (setq $p2 (point))))
    (save-excursion
      (save-restriction
        (narrow-to-region $p1 $p2)
        (goto-char (point-min))
        (while (re-search-forward " +" nil t)
          (replace-match "\n" ))))))

Text Transform Topic

  1. Emacs: Toggle Letter Case
  2. Emacs: Change to Title Case
  3. Emacs: Upcase Sentences
  4. Emacs: Cycle Replace Space Hyphen Underscore
  5. Emacs: Remove Accent Marks
  6. Emacs: Escape Quotes Command
  7. Emacs: Spaces to New Lines
  8. Emacs: Quote Lines
  9. Emacs: Change Brackets and Quotes
  10. Emacs: CSS Compressor
  11. Emacs: Replace Greek Letter Names to Unicode
  12. Emacs: Convert Straight/Curly Quotes
  13. Emacs: Convert English/Chinese Punctuations
  14. Emacs: Lines to HTML Table

Enhanced Editing Commands Topic

  1. Emacs: Select Line, between Quotes, Extend Selection
  2. Emacs: Copy/Cut Current Line If No Selection
  3. Emacs: Copy/Cut All or Selection
  4. Emacs: Paste or Paste Previous
  5. Emacs: Delete Whitespace around Cursor
  6. Emacs: Move Cursor to Beginning of Line/Paragraph
  7. Emacs: Move Cursor by Text Block
  8. Emacs: Move Cursor to Bracket/Quote
  9. Emacs: Move Cursor to Punctuation
  10. Emacs: Delete Text Block
  11. Emacs: Toggle Comment Current Line
  12. Emacs: Insert Date Time
Like my tutorial? Put $5 at patreon

Or Buy Xah Emacs Tutorial

Or buy a nice keyboard: Best Keyboard for Emacs