# Is it possible to use the global definition of a symbol as part of its new local definition set in a Block?

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.

• 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

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

InternalInheritedBlock[{Print},
Unprotect[Print];
Module[{inPrint},
Print[arg_]/;!TrueQ[inPrint]:=
Block[{inPrint = True},
(CopyToClipboard[#]; Print[#])&[arg]
];
];
your-code
]


Here, the InternalInheritedBlock 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.