bbcode

package module
v0.0.0-...-48be21c Latest Latest
Warning

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

Go to latest
Published: Aug 7, 2018 License: MIT Imports: 7 Imported by: 3

README

bbcode Build Status

frustra/bbcode is a fast BBCode compiler for Go. It supports custom tags, safe html output (for user-specified input), and allows for graceful parsing of syntax errors similar to the output of a regex bbcode compiler.

Visit the godoc here: http://godoc.org/github.com/frustra/bbcode

Usage

To get started compiling some text, create a compiler instance:

compiler := bbcode.NewCompiler(true, true) // autoCloseTags, ignoreUnmatchedClosingTags
fmt.Println(compiler.Compile("[b]Hello World[/b]"))

// Output:
// <b>Hello World</b>

Supported BBCode Syntax

[tag]basic tag[/tag]
[tag1][tag2]nested tags[/tag2][/tag1]

[tag=value]tag with value[/tag]
[tag arg=value]tag with named argument[/tag]
[tag="quote value"]tag with quoted value[/tag]

[tag=value foo="hello world" bar=baz]multiple tag arguments[/tag]

Default Tags

  • [b]text[/b] --> <b>text</b> (b, i, u, and s all map the same)
  • [url]link[/url] --> <a href="link">link</a>
  • [url=link]text[/url] --> <a href="link">text</a>
  • [img]link[/img] --> <img src="link">
  • [img=link]alt[/img] --> <img alt="alt" title="alt" src="link">
  • [center]text[/center] --> <div style="text-align: center;">text</div>
  • [color=red]text[/color] --> <span style="color: red;">text</span>
  • [size=2]text[/size] --> <span class="size2">text</span>
  • [quote]text[/quote] --> <blockquote><cite>Quote</cite>text</blockquote>
  • [quote=Somebody]text[/quote] --> <blockquote><cite>Somebody said:</cite>text</blockquote>
  • [quote name=Somebody]text[/quote] --> <blockquote><cite>Somebody said:</cite>text</blockquote>
  • [code][b]anything[/b][/code] --> <pre>[b]anything[/b]</pre>

Lists are not currently implemented as a default tag, but can be added as a custom tag.
A working implementation of list tags can be found here

Notes

  • If using with user-supplied input, it's recommended to modify the url tag to sanitize links. By default, urls such as javascript:alert(1); are valid.

  • For HTML tags with multiple attributes, the ordering is not sorted by default. If you need deterministic output, set compiler.SortOutputAttributes to true. This may slightly reduce the compiler performance.

Adding Custom Tags

Custom tag handlers can be added to a compiler using the compiler.SetTag(tag, handler) function:

compiler.SetTag("center", func(node *bbcode.BBCodeNode) (*bbcode.HTMLTag, bool) {
	// Create a new div element to output
	out := bbcode.NewHTMLTag("")
	out.Name = "div"

	// Set the style attribute of our output div
	out.Attrs["style"] = "text-align: center;"

	// Returning true here means continue to parse child nodes.
	// This should be false if children are parsed by this tag's handler, like in the [code] tag.
	return out, true
})

Tag values can be read from the opening tag like this:
Main tag value [tag={value}]: node.GetOpeningTag().Value
Tag arguments [tag name={value}]: node.GetOpeningTag().Args["name"]

bbcode.NewHTMLTag(text) creates a text node by default. By setting tag.Name, the node because an html tag prefixed by the text. The closing html tag is not rendered unless child elements exist. The closing tag can be forced by adding a blank text node:

out := bbcode.NewHTMLTag("")
out.Name = "div"
out.AppendChild(nil) // equivalent to out.AppendChild(bbcode.NewHTMLTag(""))

For more examples of tag definitions, look at the default tag implementations in compiler.go

Overriding Default Tags

The built-in tags can be overridden simply by redefining the tag with compiler.SetTag(tag, handler)

To remove a tag, set the tag handler to nil:

compiler.SetTag("quote", nil)

The default tags can also be modified without completely redefining the tag by calling the default handler:

compiler.SetTag("url", func(node *bbcode.BBCodeNode) (*bbcode.HTMLTag, bool) {
	out, appendExpr := bbcode.DefaultTagCompilers["url"](node)
	out.Attrs["class"] = "bbcode-link"
	return out, appendExpr
})

Auto-Close Tags

Input:

[center][b]text[/center]

Enabled Output:

<div style="text-align: center;"><b>text</b></div>

Disabled Output:

<div style="text-align: center;">[b]text</div>

Ignore Unmatched Closing Tags

Input:

[center]text[/b][/center]

Enabled Output:

<div style="text-align: center;">text</div>

Disabled Output:

<div style="text-align: center;">text[/b]</div>

Documentation

Overview

Package bbcode implements a parser and HTML generator for BBCode.

Index

Constants

View Source
const (
	TEXT        = "text"
	OPENING_TAG = "opening"
	CLOSING_TAG = "closing"
)

Variables

View Source
var DefaultTagCompilers map[string]TagCompilerFunc

Functions

func CompileText

func CompileText(in *BBCodeNode) string

func InsertNewlines

func InsertNewlines(out *HTMLTag)

func Lex

func Lex(str string) chan Token

func ValidURL

func ValidURL(raw string) string

Types

type BBClosingTag

type BBClosingTag struct {
	Name string
	Raw  string
}

type BBCodeNode

type BBCodeNode struct {
	Token
	Parent     *BBCodeNode
	Children   []*BBCodeNode
	ClosingTag *BBClosingTag

	Compiler *Compiler
	Info     interface{}
}

func Parse

func Parse(tokens chan Token) *BBCodeNode

func (*BBCodeNode) GetOpeningTag

func (n *BBCodeNode) GetOpeningTag() *BBOpeningTag

type BBOpeningTag

type BBOpeningTag struct {
	Name  string
	Value string
	Args  map[string]string
	Raw   string
}

func (*BBOpeningTag) String

func (t *BBOpeningTag) String() string

type Compiler

type Compiler struct {
	AutoCloseTags              bool
	IgnoreUnmatchedClosingTags bool
	SortOutputAttributes       bool
	// contains filtered or unexported fields
}

func NewCompiler

func NewCompiler(autoCloseTags, ignoreUnmatchedClosingTags bool) Compiler

func (Compiler) Compile

func (c Compiler) Compile(str string) string

func (Compiler) CompileTree

func (c Compiler) CompileTree(node *BBCodeNode) *HTMLTag

CompileTree transforms BBCodeNode into an HTML tag.

func (Compiler) SetDefault

func (c Compiler) SetDefault(compiler TagCompilerFunc)

func (Compiler) SetTag

func (c Compiler) SetTag(tag string, compiler TagCompilerFunc)

type HTMLTag

type HTMLTag struct {
	Name     string
	Value    string
	Attrs    map[string]string
	Children []*HTMLTag
}

HTMLTag represents a DOM node.

func CompileRaw

func CompileRaw(in *BBCodeNode) *HTMLTag

func NewHTMLTag

func NewHTMLTag(value string) *HTMLTag

NewHTMLTag creates a new HTMLTag with string contents specified by value.

func NewlineTag

func NewlineTag() *HTMLTag

Returns a new HTMLTag representing a line break

func (*HTMLTag) AppendChild

func (t *HTMLTag) AppendChild(child *HTMLTag) *HTMLTag

func (*HTMLTag) Compile

func (t *HTMLTag) Compile(sorted bool) string

The html representation of the tag with or without sorted arguments.

func (*HTMLTag) String

func (t *HTMLTag) String() string

The html representation of the tag with unsorted arguments.

type TagCompilerFunc

type TagCompilerFunc func(*BBCodeNode) (*HTMLTag, bool)
var DefaultTagCompiler TagCompilerFunc

type Token

type Token struct {
	ID    string
	Value interface{}
}

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL