How can I replace a character with a newline in Emacs?

EmacsReplace

Emacs Problem Overview


I am trying to replace a character - say ; - with a new line using replace-string and/or replace-regexp in Emacs.

I have tried the following commands:

  • M-x replace-string RET ; RET \n

    This will replace ; with two characters: \n.

  • M-x replace-regex RET ; RET \n

    This results in the following error (shown in the minibuffer):

    > Invalid use of `' in replacement text.

What's wrong with using replace-string for this task? Is there another way to do it?

Emacs Solutions


Solution 1 - Emacs

M-x replace-string RET ; RET C-q C-j.

  • C-q for quoted-insert,

  • C-j is a newline.

Solution 2 - Emacs

There are four ways I've found to put a newline into the minibuffer.

  1. C-o

  2. C-q C-j

  3. C-q 12 (12 is the octal value of newline)

  4. C-x o to the main window, kill a newline with C-k, then C-x o back to the minibuffer, yank it with C-y

Solution 3 - Emacs

Don't forget that you can always cut and paste into the minibuffer.

So you can just copy a newline character (or any string) from your buffer, then yank it when prompted for the replacement text.

Solution 4 - Emacs

More explicitly:

To replace the semicolon character (;) with a newline, follow these exact steps.

  1. locate the cursor at the upper left of buffer the containing text you want to change

  2. Type m-x replace-string and hit Return

  3. The mini-buffer will display something like this: Replace string (default ^ -> ):

  4. Type in the character you want to replace. In this case, ; and hit Return

  5. The mini-buffer will display something like this:

    string ; with:

  6. Now execute C-q C-j

  7. All instances of semicolon will be replaced a newline (from the cursor location to the end of the buffer will now appear)

There is a bit more to it than the original explanation says.

Solution 5 - Emacs

Switch to text mode:

M-x text-mode

Highlight the block to indent.

Indent: Ctrl + M </kbd>

Switch back to whatever mode...

Solution 6 - Emacs

Inline just:

C-M-S-% (if the binding keys are still the default) and then replace-string ^J.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLeiView Question on Stackoverflow
Solution 1 - EmacsJonathan ArkellView Answer on Stackoverflow
Solution 2 - EmacsslipmthgooseView Answer on Stackoverflow
Solution 3 - EmacsBloatView Answer on Stackoverflow
Solution 4 - EmacsafcView Answer on Stackoverflow
Solution 5 - EmacsenkdrView Answer on Stackoverflow
Solution 6 - EmacsAiad FarisView Answer on Stackoverflow