Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Consider the following expression:

Block[{Print = CopyToClipboard}, doSomething[]]

Now all calls to Print from doSomething[] (and all other functions it may invoke) will copy values to clipboard rather than printing them. Suppose I want to modify this expression such that all calls to Print both copy values to clipboard and print them.

Block[{Print = (CopyToClipboard[#]; Print[#]) &}, doSomething[]]

I need something similar to the above, but which doesn't go into an infinite recursion and where the occurrence of Print within the pure function retains its global meaning that it had before the execution entered the Block. Is it possible?

I understand the difference between Block and Module, and I need to use Block to create a dynamic (rather than lexical) scoping.

share|improve this question
Since you are augmenting a behavior, you are looking for the Villegas-Gayley trick. There are many examples on this site, my personal favorite is from Mr.Wizard. – rcollyer Jun 18 '13 at 1:06
@rcollyer thanks for the shout-out! :-) – Mr.Wizard Jun 18 '13 at 15:30
@Mr.Wizard you're welcome. I'm tempted, if I find the time, to add to the design patterns question the most fundamental pattern in mma: there is no distinction between code and data, and that is a perfect example of it. – rcollyer Jun 18 '13 at 15:32
@rcollyer Probably you know it, but I'd like to mention that languages with this property are called homoiconic. – Vladimir Reshetnikov Jun 18 '13 at 20:34
@VladimirReshetnikov yes, having recently learned that word ... and it has some very interesting consequences. – rcollyer Jun 18 '13 at 20:37
up vote 8 down vote accepted

What you are looking for is the Villegas - Gayley technique:

          Block[{inPrint = True},
              (CopyToClipboard[#]; Print[#])&[arg]

Here, the Internal`InheritedBlock is used to make sure that the redefinition of Block remains local to your execution stack - it is also a dynamic scoping construct, but it preserves the old definitions, unlike Block.

share|improve this answer
StackOverflow reference: – Mr.Wizard Jun 18 '13 at 15:34

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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