Windows 10, Emacs 25.1, Magit

I select some text (Shift + Arrow Down) from the Unstaged changes section. Here is a screenshot:


Then I paste into another buffer (*scratch*).

This is the result:


Is it possible to strip the leading +s when killing lines from diff hunks?

4 Answers 4


Magit doesn't support that currently, but it should be doable. I'll probably do that soon. I sometimes could use that feature too.

Meanwhile use a macro to replace the +s after yanking: <f3> C-d C-n <f4>....

  • 1
    After yank I do next: 1) Set cursor over first "+", 2) Start command <C-return> (cua-set-rectangle-mark) , 3) Select only "+" (one column) and press Del for delete all symbols "+"
    – Alex
    Commented Oct 11, 2017 at 9:56
  • @Alex Could you not use cua-rectangle-mark-mode from within the magit buffer?
    – 0x5453
    Commented Oct 11, 2017 at 12:49
  • I use cua-rectangle-mark-mode in another buffer (not magit) after yank text.
    – Alex
    Commented Oct 11, 2017 at 13:18
  • Without CUA, after yank: C-a C-f C-x C-x C-x r d.
    – Alan Third
    Commented Oct 12, 2017 at 13:20

Until Magit supports something like this, the behavior is easy to get with a custom command. I have something similar to the following command in my configuration. If you call it with a prefix argument, it will remove the leading diff markers.

(defun km/magit-copy-region-hunk (&optional no-column)
  (interactive "P")
  (when (magit-section-internal-region-p)
    (magit-section-when hunk
      (let ((text (buffer-substring-no-properties
                   (region-beginning) (region-end))))
        (kill-new (if no-column
                      (replace-regexp-in-string "^[ \\+\\-]" "" text)

Edit: With the developmental version of Magit (what will be v2.91.0), you can strip the diff markers by marking a region of a hunk and calling magit-copy-section-value with a prefix argument.

  • No docstrings in your configuration?! For shame. :) Works well though +1.
    – Basil
    Commented Oct 12, 2017 at 15:38

Going off of Kyle Meyer's answer, if you want to copy the diff without needing to hit the prefix key, you can use the following:

(defun copy-diff-region ()
  "Copy diff region without + or - markers."
  (let ((text (buffer-substring-no-properties
               (region-beginning) (region-end))))
    (kill-new (replace-regexp-in-string "^[\\+\\-]" "" text))))

From the manual:

If a prefix argument is used and the region is within a hunk, then it strips the diff marker column and keeps only either the added or removed lines, depending on the sign of the prefix argument.

I can confirm that C-u C-w after selecting a region copies the lines without the prefix.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.