Do you know about AutoGeneratePackage
? Either code below will save the cells marked InitializationCell
(see menu Cell > Cell Properties > Initialization Cell, shortcut ctrl-8):
SetOptions[EvaluationNotebook[], AutoGeneratedPackage -> Automatic]
SetOptions[EvaluationNotebook[], AutoGeneratedPackage -> Manual]
See the documentation for the difference between Automatic
and Manual
.
You could also look at the code for GeneralUtilities`PrintDefinitions
(via GeneralUtilities`PrintDefinitions[GeneralUtilities`PrintDefinitions]
), which prints code to a notebook. It may take some work to figure it out, since it does a lot of pretty-print formatting with hyperlinks. It's much more complicated than the basic task you want to do.
Here's a usage string generator similar to what you want:
ClearAll[fff];
fff[x_, y_ : 2] := x + y;
fff[x_, y_, z_] := x z + y;
fff::usage = StringJoin@ Riffle[ToString /@ HoldForm @@@ DownValues[fff][[All, 1]], "\n"];
? fff
A more complicated example:
ClearAll[fn];
fn[e_, {x_, a_, b_}][x0_?NumericQ] := Block[{x = x0}, e];
fn[e_, {x_, a_, b_}]["Domain"] := {x, a, b};
fn[e_, {x_, a_, b_}]["Variable"] := x;
fn[e_, x_Symbol] := fn[e, {x, 0, 1}]; (* default domain *)
fn /: Plot[f_fn] :=
With[{x = f["Variable"], domain = f["Domain"]}, Plot[f[x], domain]];
fn::usage = StringJoin@ Riffle[
ToString /@ HoldForm @@@ Join[UpValues[fn], SubValues[fn], DownValues[fn]][[All, 1]],
"\n"];
One could also just write a utility function to use on functions under development:
usage[symb_] := HoldForm @@@
Join[UpValues[symb], SubValues[symb], DownValues[symb]][[All, 1]] //
Column;