For example I have a block of code
Module[{}, a=1;b=2;...]
I want to have a function called gencode, so when I run gencode, it will generate an input cell which contains this block of code just like I type them by hand.
How to write this gencode?
Answer
CellPrint plus ExpressionCell are tools for generating cells. They do not hold their arguments, so some control of evaluation is necessary (Defer). [Update: In response to Szabolcs' comment, may as well let options be passed.]
ClearAll[gencode];
SetAttributes[gencode, HoldAll];
gencode[code_, opts : OptionsPattern[Cell]] :=
CellPrint@ExpressionCell[Defer@code, "Input", opts];
Examples:

Or following Szabolcs:
gencode[Module[{a, b}, a = 1; b = 2; a + b], GeneratedCell -> False]
Comments
Post a Comment