diff --git a/src/cmd/doc/doc_test.go b/src/cmd/doc/doc_test.go index 5532cf537d6..22468db1ff8 100644 --- a/src/cmd/doc/doc_test.go +++ b/src/cmd/doc/doc_test.go @@ -721,6 +721,37 @@ var tests = []test{ []string{"Foo struct"}, nil, }, + { + "formatted doc on function", + []string{p, "ExportedFormattedDoc"}, + []string{ + `func ExportedFormattedDoc\(a int\) bool`, + ` Comment about exported function with formatting\. + + Example + + fmt\.Println\(FormattedDoc\(\)\) + + Text after pre-formatted block\.`, + }, + nil, + }, + { + "formatted doc on type field", + []string{p, "ExportedFormattedType.ExportedField"}, + []string{ + `type ExportedFormattedType struct`, + ` // Comment before exported field with formatting\. + //[ ] + // Example + //[ ] + // a\.ExportedField = 123 + //[ ] + // Text after pre-formatted block\.`, + `ExportedField int`, + }, + nil, + }, } func TestDoc(t *testing.T) { diff --git a/src/cmd/doc/pkg.go b/src/cmd/doc/pkg.go index e3a44c42838..12b76c2ad09 100644 --- a/src/cmd/doc/pkg.go +++ b/src/cmd/doc/pkg.go @@ -5,6 +5,7 @@ package main import ( + "bufio" "bytes" "fmt" "go/ast" @@ -221,7 +222,7 @@ func (pkg *Package) emit(comment string, node ast.Node) { } if comment != "" && !showSrc { pkg.newlines(1) - doc.ToText(&pkg.buf, comment, " ", indent, indentedWidth) + doc.ToText(&pkg.buf, comment, indent, indent+indent, indentedWidth) pkg.newlines(2) // Blank line after comment to separate from next item. } else { pkg.newlines(1) @@ -1005,8 +1006,13 @@ func (pkg *Package) printFieldDoc(symbol, fieldName string) bool { pkg.Printf("type %s struct {\n", typ.Name) } if field.Doc != nil { - for _, comment := range field.Doc.List { - doc.ToText(&pkg.buf, comment.Text, indent, indent, indentedWidth) + // To present indented blocks in comments correctly, process the comment as + // a unit before adding the leading // to each line. + docBuf := bytes.Buffer{} + doc.ToText(&docBuf, field.Doc.Text(), "", indent, indentedWidth) + scanner := bufio.NewScanner(&docBuf) + for scanner.Scan() { + fmt.Fprintf(&pkg.buf, "%s// %s\n", indent, scanner.Bytes()) } } s := pkg.oneLineNode(field.Type) diff --git a/src/cmd/doc/testdata/pkg.go b/src/cmd/doc/testdata/pkg.go index 88e8c215d01..759b7723a6c 100644 --- a/src/cmd/doc/testdata/pkg.go +++ b/src/cmd/doc/testdata/pkg.go @@ -207,3 +207,25 @@ const ( Duplicate = iota duplicate ) + +// Comment about exported function with formatting. +// +// Example +// +// fmt.Println(FormattedDoc()) +// +// Text after pre-formatted block. +func ExportedFormattedDoc(a int) bool { + return true +} + +type ExportedFormattedType struct { + // Comment before exported field with formatting. + // + // Example + // + // a.ExportedField = 123 + // + // Text after pre-formatted block. + ExportedField int +}