Version 0 of docstring

Updated 2004-01-25 14:51:53

if 0 {Richard Suchenwirth 2004-01-25 - Languages like Lisp and Python have the docstring feature, where a string in the beginning of a function can be retrieved for on-line (or printed) documentation. Tcl doesn't have this mechanism built-in (and it would be hard to do it exactly the same way, because everything is a string), but a similar mechanism can easily be adopted.

If the docstring is written in comments at the top of a proc body, it is easy to parse it out. In addition, for all procs, even without docstring, you get the "signature" (proc name and arguments with defaults). The code below also serves as usage example: }

 proc docstring procname {
    # reports a proc's args and leading comments.
    # Multiple documentation lines are allowed.
    set res "{usage: $procname [args $procname]}"
    # This comment should not appear in the docstring
    foreach line [split [info body $procname] \n] {
        if {[string trim $line] eq ""} continue
        if ![regexp {\s*#(.+)} $line -> line] break
        lappend res [string trim $line]
    }
    join $res \n
 }
 proc args procname {
    # Signature of a proc: arguments with defaults
    set res ""
    foreach a [info args $procname] {
        if [info default $procname $a default] {
            lappend a $def
        }
        lappend res $a
    }
    set res
 }

#Testing:

 docstring docstring

Arts and crafts of Tcl-Tk programming