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" ))))))

Emacs Text Transform Under Cursor

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

Enhanced Editing Commands Topic

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

Or Buy Xah Emacs Tutorial

Or buy a nice keyboard: Best Keyboards for Emacs

If you have a question, put $5 at patreon and message me.