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?
M-x replace-string
RET ;
RET C-q C-j.
C-q for quoted-insert,
C-j is a newline.
There are four ways I've found to put a newline into the minibuffer.
C-o C-q C-j C-q 12 (12 is the octal value of newline) 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
C-o
! One less key stroke compared to C-q C-j
. Hadn't thought of using that one before.
C-o
doesn't move the point after inserting the newline in the minibuffer, so you still need to press the right arrow key as well if you want to insert something after the newline in the replacement string.
C-o
will enter a newline in the main window when using search, while C-q C-j
will enter the newline in the minibuffer. C-o
does work with query - replace though.
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.
More explicitly:
To replace the semicolon character (;) with a newline, follow these exact steps.
locate the cursor at the upper left of buffer the containing text you want to change Type m-x replace-string and hit Return The mini-buffer will display something like this: Replace string (default ^ -> ): Type in the character you want to replace. In this case, ; and hit Return The mini-buffer will display something like this: string ; with: Now execute C-q C-j 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.
Switch to text mode:
M-x text-mode
Highlight the block to indent.
Indent: Ctrl + M
Switch back to whatever mode...
Inline just:
C-M-S-%
(if the binding keys are still the default) and then replace-string
^J.
Success story sharing
quote-insert
which quotes the next character.C-j
is a literal0x0a
control code, versusRet
which is the key next to your quote and sends0x0d
. en.wikipedia.org/wiki/C0_and_C1_control_codesC-j
in emacs, whileC-m
in vim.