Movatterモバイル変換


[0]ホーム

URL:


comment

packagestandard library
go1.25.5Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2025 License:BSD-3-ClauseImports:8Imported by:125

Details

Repository

cs.opensource.google/go/go

Links

Documentation

Overview

Package comment implements parsing and reformatting of Go doc comments,(documentation comments), which are comments that immediately precedea top-level declaration of a package, const, func, type, or var.

Go doc comment syntax is a simplified subset of Markdown that supportslinks, headings, paragraphs, lists (without nesting), and preformatted text blocks.The details of the syntax are documented athttps://go.dev/doc/comment.

To parse the text associated with a doc comment (after removing comment markers),use aParser:

var p comment.Parserdoc := p.Parse(text)

The result is a*Doc.To reformat it as a doc comment, HTML, Markdown, or plain text,use aPrinter:

var pr comment.Printeros.Stdout.Write(pr.Text(doc))

TheParser andPrinter types are structs whose fields can bemodified to customize the operations.For details, see the documentation for those types.

Use cases that need additional control over reformatting canimplement their own logic by inspecting the parsed syntax itself.See the documentation forDoc,Block,Text for an overviewand links to additional types.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

funcDefaultLookupPackage

func DefaultLookupPackage(namestring) (importPathstring, okbool)

DefaultLookupPackage is the default package lookupfunction, used when [Parser.LookupPackage] is nil.It recognizes names of the packages from the standardlibrary with single-element import paths, such as math,which would otherwise be impossible to name.

Note that the go/doc package provides a more sophisticatedlookup based on the imports used in the current package.

Types

typeBlock

type Block interface {// contains filtered or unexported methods}

A Block is block-level content in a doc comment,one of*Code,*Heading,*List, or*Paragraph.

typeCode

type Code struct {// Text is the preformatted text, ending with a newline character.// It may be multiple lines, each of which ends with a newline character.// It is never empty, nor does it start or end with a blank line.Textstring}

A Code is a preformatted code block.

typeDoc

type Doc struct {// Content is the sequence of content blocks in the comment.Content []Block// Links is the link definitions in the comment.Links []*LinkDef}

A Doc is a parsed Go doc comment.

typeDocLink

type DocLink struct {Text []Text// text of link// ImportPath, Recv, and Name identify the Go package or symbol// that is the link target. The potential combinations of// non-empty fields are://  - ImportPath: a link to another package//  - ImportPath, Name: a link to a const, func, type, or var in another package//  - ImportPath, Recv, Name: a link to a method in another package//  - Name: a link to a const, func, type, or var in this package//  - Recv, Name: a link to a method in this packageImportPathstring// import pathRecvstring// receiver type, without any pointer star, for methodsNamestring// const, func, type, var, or method name}

A DocLink is a link to documentation for a Go package or symbol.

func (*DocLink)DefaultURL

func (l *DocLink) DefaultURL(baseURLstring)string

DefaultURL constructs and returns the documentation URL for l,using baseURL as a prefix for links to other packages.

The possible forms returned by DefaultURL are:

  • baseURL/ImportPath, for a link to another package
  • baseURL/ImportPath#Name, for a link to a const, func, type, or var in another package
  • baseURL/ImportPath#Recv.Name, for a link to a method in another package
  • #Name, for a link to a const, func, type, or var in this package
  • #Recv.Name, for a link to a method in this package

If baseURL ends in a trailing slash, then DefaultURL insertsa slash between ImportPath and # in the anchored forms.For example, here are some baseURL values and URLs they can generate:

"/pkg/" → "/pkg/math/#Sqrt""/pkg"  → "/pkg/math#Sqrt""/"     → "/math/#Sqrt"""      → "/math#Sqrt"

typeHeading

type Heading struct {Text []Text// the heading text}

A Heading is a doc comment heading.

func (*Heading)DefaultID

func (h *Heading) DefaultID()string

DefaultID returns the default anchor ID for the heading h.

The default anchor ID is constructed by converting everyrune that is not alphanumeric ASCII to an underscoreand then adding the prefix “hdr-”.For example, if the heading text is “Go Doc Comments”,the default ID is “hdr-Go_Doc_Comments”.

typeItalic

type Italicstring

An Italic is a string rendered as italicized text.

typeLink

type Link struct {Autobool// is this an automatic (implicit) link of a literal URL?Text []Text// text of linkURLstring// target URL of link}

A Link is a link to a specific URL.

typeLinkDef

type LinkDef struct {Textstring// the link textURLstring// the link URLUsedbool// whether the comment uses the definition}

A LinkDef is a single link definition.

typeList

type List struct {// Items is the list items.Items []*ListItem// ForceBlankBefore indicates that the list must be// preceded by a blank line when reformatting the comment,// overriding the usual conditions. See the BlankBefore method.//// The comment parser sets ForceBlankBefore for any list// that is preceded by a blank line, to make sure// the blank line is preserved when printing.ForceBlankBeforebool// ForceBlankBetween indicates that list items must be// separated by blank lines when reformatting the comment,// overriding the usual conditions. See the BlankBetween method.//// The comment parser sets ForceBlankBetween for any list// that has a blank line between any two of its items, to make sure// the blank lines are preserved when printing.ForceBlankBetweenbool}

A List is a numbered or bullet list.Lists are always non-empty: len(Items) > 0.In a numbered list, every Items[i].Number is a non-empty string.In a bullet list, every Items[i].Number is an empty string.

func (*List)BlankBefore

func (l *List) BlankBefore()bool

BlankBefore reports whether a reformatting of the commentshould include a blank line before the list.The default rule is the same as for [BlankBetween]:if the list item content contains any blank lines(meaning at least one item has multiple paragraphs)then the list itself must be preceded by a blank line.A preceding blank line can be forced by settingList.ForceBlankBefore.

func (*List)BlankBetween

func (l *List) BlankBetween()bool

BlankBetween reports whether a reformatting of the commentshould include a blank line between each pair of list items.The default rule is that if the list item content contains any blank lines(meaning at least one item has multiple paragraphs)then list items must themselves be separated by blank lines.Blank line separators can be forced by settingList.ForceBlankBetween.

typeListItem

type ListItem struct {// Number is a decimal string in a numbered list// or an empty string in a bullet list.Numberstring// "1", "2", ...; "" for bullet list// Content is the list content.// Currently, restrictions in the parser and printer// require every element of Content to be a *Paragraph.Content []Block// Content of this item.}

A ListItem is a single item in a numbered or bullet list.

typeParagraph

type Paragraph struct {Text []Text}

A Paragraph is a paragraph of text.

typeParser

type Parser struct {// Words is a map of Go identifier words that// should be italicized and potentially linked.// If Words[w] is the empty string, then the word w// is only italicized. Otherwise it is linked, using// Words[w] as the link target.// Words corresponds to the [go/doc.ToHTML] words parameter.Words map[string]string// LookupPackage resolves a package name to an import path.//// If LookupPackage(name) returns ok == true, then [name]// (or [name.Sym] or [name.Sym.Method])// is considered a documentation link to importPath's package docs.// It is valid to return "", true, in which case name is considered// to refer to the current package.//// If LookupPackage(name) returns ok == false,// then [name] (or [name.Sym] or [name.Sym.Method])// will not be considered a documentation link,// except in the case where name is the full (but single-element) import path// of a package in the standard library, such as in [math] or [io.Reader].// LookupPackage is still called for such names,// in order to permit references to imports of other packages// with the same package names.//// Setting LookupPackage to nil is equivalent to setting it to// a function that always returns "", false.LookupPackage func(namestring) (importPathstring, okbool)// LookupSym reports whether a symbol name or method name// exists in the current package.//// If LookupSym("", "Name") returns true, then [Name]// is considered a documentation link for a const, func, type, or var.//// Similarly, if LookupSym("Recv", "Name") returns true,// then [Recv.Name] is considered a documentation link for// type Recv's method Name.//// Setting LookupSym to nil is equivalent to setting it to a function// that always returns false.LookupSym func(recv, namestring) (okbool)}

A Parser is a doc comment parser.The fields in the struct can be filled in before callingParser.Parsein order to customize the details of the parsing process.

func (*Parser)Parse

func (p *Parser) Parse(textstring) *Doc

Parse parses the doc comment text and returns the *Doc form.Comment markers (/* // and */) in the text must have already been removed.

typePlain

type Plainstring

A Plain is a string rendered as plain text (not italicized).

typePrinter

type Printer struct {// HeadingLevel is the nesting level used for// HTML and Markdown headings.// If HeadingLevel is zero, it defaults to level 3,// meaning to use <h3> and ###.HeadingLevelint// HeadingID is a function that computes the heading ID// (anchor tag) to use for the heading h when generating// HTML and Markdown. If HeadingID returns an empty string,// then the heading ID is omitted.// If HeadingID is nil, h.DefaultID is used.HeadingID func(h *Heading)string// DocLinkURL is a function that computes the URL for the given DocLink.// If DocLinkURL is nil, then link.DefaultURL(p.DocLinkBaseURL) is used.DocLinkURL func(link *DocLink)string// DocLinkBaseURL is used when DocLinkURL is nil,// passed to [DocLink.DefaultURL] to construct a DocLink's URL.// See that method's documentation for details.DocLinkBaseURLstring// TextPrefix is a prefix to print at the start of every line// when generating text output using the Text method.TextPrefixstring// TextCodePrefix is the prefix to print at the start of each// preformatted (code block) line when generating text output,// instead of (not in addition to) TextPrefix.// If TextCodePrefix is the empty string, it defaults to TextPrefix+"\t".TextCodePrefixstring// TextWidth is the maximum width text line to generate,// measured in Unicode code points,// excluding TextPrefix and the newline character.// If TextWidth is zero, it defaults to 80 minus the number of code points in TextPrefix.// If TextWidth is negative, there is no limit.TextWidthint}

A Printer is a doc comment printer.The fields in the struct can be filled in before callingany of the printing methodsin order to customize the details of the printing process.

func (*Printer)Comment

func (p *Printer) Comment(d *Doc) []byte

Comment returns the standard Go formatting of theDoc,without any comment markers.

func (*Printer)HTML

func (p *Printer) HTML(d *Doc) []byte

HTML returns an HTML formatting of theDoc.See thePrinter documentation for ways to customize the HTML output.

func (*Printer)Markdown

func (p *Printer) Markdown(d *Doc) []byte

Markdown returns a Markdown formatting of the Doc.See thePrinter documentation for ways to customize the Markdown output.

func (*Printer)Text

func (p *Printer) Text(d *Doc) []byte

Text returns a textual formatting of theDoc.See thePrinter documentation for ways to customize the text output.

typeText

type Text interface {// contains filtered or unexported methods}

A Text is text-level content in a doc comment,one ofPlain,Italic,*Link, or*DocLink.

Source Files

View all Source files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp