1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // This file contains the infrastructure to create a code
6 // snippet for search results.
8 // Note: At the moment, this only creates HTML snippets.
21 Text string // HTML-escaped
24 func (p *Presentation) newSnippet(fset *token.FileSet, decl ast.Decl, id *ast.Ident) *Snippet {
25 // TODO instead of pretty-printing the node, should use the original source instead
27 p.writeNode(&buf1, nil, fset, decl)
28 // wrap text with <pre> tag
30 buf2.WriteString("<pre>")
31 FormatText(&buf2, buf1.Bytes(), -1, true, id.Name, nil)
32 buf2.WriteString("</pre>")
33 return &Snippet{fset.Position(id.Pos()).Line, buf2.String()}
36 func findSpec(list []ast.Spec, id *ast.Ident) ast.Spec {
37 for _, spec := range list {
38 switch s := spec.(type) {
44 for _, n := range s.Names {
58 func (p *Presentation) genSnippet(fset *token.FileSet, d *ast.GenDecl, id *ast.Ident) *Snippet {
59 s := findSpec(d.Specs, id)
61 return nil // declaration doesn't contain id - exit gracefully
64 // only use the spec containing the id for the snippet
74 return p.newSnippet(fset, dd, id)
77 func (p *Presentation) funcSnippet(fset *token.FileSet, d *ast.FuncDecl, id *ast.Ident) *Snippet {
79 return nil // declaration doesn't contain id - exit gracefully
82 // only use the function signature for the snippet
90 return p.newSnippet(fset, dd, id)
93 // NewSnippet creates a text snippet from a declaration decl containing an
94 // identifier id. Parts of the declaration not containing the identifier
95 // may be removed for a more compact snippet.
96 func NewSnippet(fset *token.FileSet, decl ast.Decl, id *ast.Ident) *Snippet {
97 // TODO(bradfitz, adg): remove this function. But it's used by indexer, which
98 // doesn't have a *Presentation, and NewSnippet needs a TabWidth.
101 return p.NewSnippet(fset, decl, id)
104 // NewSnippet creates a text snippet from a declaration decl containing an
105 // identifier id. Parts of the declaration not containing the identifier
106 // may be removed for a more compact snippet.
107 func (p *Presentation) NewSnippet(fset *token.FileSet, decl ast.Decl, id *ast.Ident) *Snippet {
109 switch d := decl.(type) {
111 s = p.genSnippet(fset, d, id)
113 s = p.funcSnippet(fset, d, id)
116 // handle failure gracefully
119 fmt.Fprintf(&buf, `<span class="alert">could not generate a snippet for <span class="highlight">%s</span></span>`, id.Name)
120 s = &Snippet{fset.Position(id.Pos()).Line, buf.String()}