I have emacs configured to refrain from inserting tabs for indentation purposes already. But this does not have any effect when I paste text containing a tab (from an external application, Google Chrome). How can I ensure that tabs are always replaced with spaces in pasted text?

2 Answers 2


As suggested in Qudit's answer, this can be done by advising clipboard-yank and mouse-yank-primary (see section 12.3 of emacs manual):

(defun remove-tabs-in-region (string)
  (subst-char-in-region (point) (mark) ?\t 32))

(advice-add 'clipboard-yank :after #'remove-tabs-in-region)
(advice-add 'mouse-yank-primary :after #'remove-tabs-in-region)

This does not try to be smart, each tab is simply replaced by a space. Maybe indent-region could also be called in the advice?


You can do this by advising the yank commands: clipboard-yank, mouse-yank-primary, yank and yank-pop.

Use (region-beginning) and (region-end) to get the region and then call query-replace to change the tabs to the appropriate numbers of spaces.

  • Could you please write up the advice you are contemplating? It would be helpful to have the code that lays out your solution rather than a loose sketch, especially for users who do not have much (or any) background with elisp.
    – Dan
    Oct 25, 2015 at 13:52
  • 1
    You would only need to advise insert-for-yank-1 (others call it to do the actual insertion). But I still think there might be a better way to do it since you only want to affect the text copied from system clipboard. If you advise something like this, you'll have this function called only any yank, (most of which are benign).
    – wvxvw
    Oct 25, 2015 at 14:00
  • @Dan Are loose sketches unwelcome here?
    – Qudit
    Oct 25, 2015 at 14:16
  • @Qudit: It's not a case of "unwelcome," but rather providing more information. A loose sketch is useful in a comment to get someone started. In general, it's preferable to have answers that provide a self-contained solution. Ideally, the post can help many people in the future, some with enough background to turn the sketch into elisp code, and others who may be just getting started and wouldn't know what to do with the sketch.
    – Dan
    Oct 25, 2015 at 14:37
  • @Dan I do agree that the code is more valuable, but writing a complete function and testing it to make sure it works properly can take longer than writing a loose sketch, so they aren't comparable alternatives to me.
    – Qudit
    Oct 26, 2015 at 11:26

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.