How do I "evaluate in place" programmatically? Need to evaluate Defer[] result in non-interactive setting

Defer is a special head that behaves like Hold, but it has an additional rule for output: it disappears from the output box expression.

There is nothing special about how it is handled as input -- all the "magic" takes place during output formatting. To emulate this process, simply apply a ToBoxes ToExpression pair:

r = Defer[Integrate][Cos[x], x];

r // ToBoxes // ToExpression

Sin[x]

This is superior to a simple replacement of all instances of Defer with Identity as it replicates the output-input process, whereas replacement does not:

x = {Defer};
x /. Defer -> Identity
x // ToBoxes // ToExpression
{Identity} 

{Defer}

One could instead match the head Defer, i.e. /. Defer[x_] :> x, but if the desire is to replicate output and re-input I believe box conversion is the appropriate method. See for example:

  • Graphics in Notebook Different from Graphics Expression?

As suggested in the comments by both me and Jens

r = Defer[Integrate][Cos[x], x];
r /. Defer -> Identity
Sin[x]