allyourcode
allyourcode

Reputation: 22623

How do you add or remove text to the end of many lines at once in Emacs?

e.g. I want to add a double quote to the end of a bunch of highlighted lines. Or I want to delete two characters from a bunch of highlighted lines. Is there a command for this? I know there is "M-x r t" for inserting a rectangle of text, but this only works if everything is lined up vertically, which isn't generally the case of the ends of lines.

Upvotes: 5

Views: 519

Answers (3)

joao
joao

Reputation: 3566

Here's a more visual way, see the results in every line as you type them in one line.

Grab a recent copy of YASnippet and add to your .emacs

(require 'yasnippet)

(defun yas/add-to-end-of-lines-snippet ()
  (interactive)
  (when (region-active-p)
    (let ((snippet (replace-regexp-in-string "$" "$1" (buffer-substring (region-beginning) (region-end)))))
      (delete-region (region-beginning) (region-end))
      (yas/expand-snippet snippet))))

Now select a region and type M-x add-to-end-of-lines-snippet.

Upvotes: 3

choroba
choroba

Reputation: 241988

You can

  1. save a keyboard macro with C-x(C-e"C-fC-x), resp. C-x(C-eBackspaceBackspaceC-fC-x). Then invoke the macro with C-xe, e, e, e...
  2. do a regex replacement with M-C-%. Replace $ with " to add a double quote, replace ..$ with nothing to delete last two characters.

Upvotes: 7

Reactormonk
Reactormonk

Reputation: 21730

M-xreplace-regexp $ " should work, but I'm not sure if replace-regexp respects mark.

Upvotes: 5

Related Questions