I am writing some ODE notes with lots of pictures generated using Mathematica, and I'd like to include the code used to generate them.
Currently I have a notebook where all the pictures are generated. I have a doImage function that gets a filename, and a graphic object and exports it — nothing fancy at all.
doImage["sine-function",
Plot[
Sin[t],
{t, 0, 2 Pi}
]
]
Is there a way to have doImage also save the code it gets in the second argument? A plaintext rendition, say (it'd eventually get included in a LaTeX file, maybe after being run through pygments for prettyfication) I think one could make the function hold its arguments unevaluated and save them, but ideally the saved code would also keep the formatting! At least, the indentation, say.
I don't really understand why, so let me be explicit: what I am asking is how to get the function all above to produce a textfile whose contexts are
Plot[
Sin[t],
{t, 0, 2 Pi}
]
Since I know how to save a string to a textfile, I would be equally please, of course, with learning how to produce a string which when serialized into a textfile would produce that.
FWIW, one can get an actual plaintext rendtion of a cell of code in a string with its original indentation — or a close approximation thereof — by saying something like
SelectionMove[PreviousCell[CellStyle -> {"Input"}], All, Cell];
FrontEndTokenExecute[SelectedNotebook[], "CopySpecial", "InputText"];
str = NotebookGet[ClipboardNotebook[]][[1, 1, 1]]
It even gets fractions, exponents and roots correct. The lines are wrapped (with correct indentation), but it'd be nice to control at what column, though.




