README
¶
CSS

This package is a CSS3 lexer and parser written in Go. Both follow the specification at CSS Syntax Module Level 3. The lexer takes an io.Reader and converts it into tokens until the EOF. The parser returns a parse tree of the full io.Reader input stream, but the low-level Next
function can be used for stream parsing to returns grammar units until the EOF.
Installation
Run the following command
go get github.com/tdewolff/parse/css
or add the following import and run project with go get
import "github.com/tdewolff/parse/css"
Lexer
Usage
The following initializes a new Lexer with io.Reader r
:
l := css.NewLexer(r)
To tokenize until EOF an error, use:
for {
tt, text := l.Next()
switch tt {
case css.ErrorToken:
// error or EOF set in l.Err()
return
// ...
}
}
All tokens (see CSS Syntax Module Level 3):
ErrorToken // non-official token, returned when errors occur
IdentToken
FunctionToken // rgb( rgba( ...
AtKeywordToken // @abc
HashToken // #abc
StringToken
BadStringToken
UrlToken // url(
BadUrlToken
DelimToken // any unmatched character
NumberToken // 5
PercentageToken // 5%
DimensionToken // 5em
UnicodeRangeToken
IncludeMatchToken // ~=
DashMatchToken // |=
PrefixMatchToken // ^=
SuffixMatchToken // $=
SubstringMatchToken // *=
ColumnToken // ||
WhitespaceToken
CDOToken // <!--
CDCToken // -->
ColonToken
SemicolonToken
CommaToken
BracketToken // ( ) [ ] { }, all bracket tokens use this, Data() can distinguish between the brackets
CommentToken // non-official token
Examples
package main
import (
"os"
"github.com/tdewolff/parse/css"
)
// Tokenize CSS3 from stdin.
func main() {
l := css.NewLexer(os.Stdin)
for {
tt, text := l.Next()
switch tt {
case css.ErrorToken:
if l.Err() != io.EOF {
fmt.Println("Error on line", l.Line(), ":", l.Err())
}
return
case css.IdentToken:
fmt.Println("Identifier", string(text))
case css.NumberToken:
fmt.Println("Number", string(text))
// ...
}
}
}
Parser
Usage
The following creates a new Parser.
// true because this is the content of an inline style attribute
p := css.NewParser(bytes.NewBufferString("color: red;"), true)
To iterate over the stylesheet, use:
for {
gt, _, data := p.Next()
if gt == css.ErrorGrammar {
break
}
// ...
}
All grammar units returned by Next
:
ErrorGrammar
AtRuleGrammar
EndAtRuleGrammar
RulesetGrammar
EndRulesetGrammar
DeclarationGrammar
TokenGrammar
Examples
package main
import (
"bytes"
"fmt"
"github.com/tdewolff/parse/css"
)
func main() {
// true because this is the content of an inline style attribute
p := css.NewParser(bytes.NewBufferString("color: red;"), true)
out := ""
for {
gt, _, data := p.Next()
if gt == css.ErrorGrammar {
break
} else if gt == css.AtRuleGrammar || gt == css.BeginAtRuleGrammar || gt == css.BeginRulesetGrammar || gt == css.DeclarationGrammar {
out += string(data)
if gt == css.DeclarationGrammar {
out += ":"
}
for _, val := range p.Values() {
out += string(val.Data)
}
if gt == css.BeginAtRuleGrammar || gt == css.BeginRulesetGrammar {
out += "{"
} else if gt == css.AtRuleGrammar || gt == css.DeclarationGrammar {
out += ";"
}
} else {
out += string(data)
}
}
fmt.Println(out)
}
License
Released under the MIT license.
Documentation
¶
Overview ¶
Package css is a CSS3 lexer and parser following the specifications at http://www.w3.org/TR/css-syntax-3/.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func HSL2RGB ¶ added in v1.1.0
HSL2RGB converts HSL to RGB with all of range [0,1] from http://www.w3.org/TR/css3-color/#hsl-color
func IsURLUnquoted ¶ added in v1.1.0
IsURLUnquoted returns true if the bytes are a valid unquoted URL.
Types ¶
type GrammarType ¶
type GrammarType uint32
GrammarType determines the type of grammar.
const ( ErrorGrammar GrammarType = iota // extra token when errors occur CommentGrammar AtRuleGrammar BeginAtRuleGrammar EndAtRuleGrammar QualifiedRuleGrammar BeginRulesetGrammar EndRulesetGrammar DeclarationGrammar TokenGrammar CustomPropertyGrammar )
GrammarType values.
func (GrammarType) String ¶
func (tt GrammarType) String() string
String returns the string representation of a GrammarType.
type Hash ¶
type Hash uint32
Hash defines perfect hashes for a predefined list of strings
const ( Ms_Filter Hash = 0xa // -ms-filter Accelerator Hash = 0x4b30b // accelerator Aliceblue Hash = 0x5b109 // aliceblue Alpha Hash = 0x63605 // alpha Antiquewhite Hash = 0x4900c // antiquewhite Aquamarine Hash = 0x7a70a // aquamarine Azimuth Hash = 0x63a07 // azimuth Background Hash = 0x2d0a // background Background_Attachment Hash = 0x4fb15 // background-attachment Background_Color Hash = 0x17c10 // background-color Background_Image Hash = 0x61510 // background-image Background_Position Hash = 0x2d13 // background-position Background_Position_X Hash = 0x8ac15 // background-position-x Background_Position_Y Hash = 0x2d15 // background-position-y Background_Repeat Hash = 0x4211 // background-repeat Background_Size Hash = 0x660f // background-size Behavior Hash = 0x7508 // behavior Black Hash = 0xa505 // black Blanchedalmond Hash = 0xaa0e // blanchedalmond Blueviolet Hash = 0x5b60a // blueviolet Bold Hash = 0xbf04 // bold Border Hash = 0xca06 // border Border_Bottom Hash = 0xca0d // border-bottom Border_Bottom_Color Hash = 0xca13 // border-bottom-color Border_Bottom_Style Hash = 0xe913 // border-bottom-style Border_Bottom_Width Hash = 0x11013 // border-bottom-width Border_Box Hash = 0x1310a // border-box Border_Collapse Hash = 0x1620f // border-collapse Border_Color Hash = 0x18c0c // border-color Border_Left Hash = 0x1980b // border-left Border_Left_Color Hash = 0x19811 // border-left-color Border_Left_Style Hash = 0x1a911 // border-left-style Border_Left_Width Hash = 0x1ba11 // border-left-width Border_Right Hash = 0x1cb0c // border-right Border_Right_Color Hash = 0x1cb12 // border-right-color Border_Right_Style Hash = 0x1dd12 // border-right-style Border_Right_Width Hash = 0x1ef12 // border-right-width Border_Spacing Hash = 0x2010e // border-spacing Border_Style Hash = 0x20f0c // border-style Border_Top Hash = 0x21b0a // border-top Border_Top_Color Hash = 0x21b10 // border-top-color Border_Top_Style Hash = 0x22b10 // border-top-style Border_Top_Width Hash = 0x23b10 // border-top-width Border_Width Hash = 0x24b0c // border-width Bottom Hash = 0xd106 // bottom Box_Shadow Hash = 0x1380a // box-shadow Burlywood Hash = 0x25709 // burlywood Cadetblue Hash = 0x75509 // cadetblue Calc Hash = 0x75204 // calc Caption_Side Hash = 0x2730c // caption-side Caret_Color Hash = 0x2850b // caret-color Center Hash = 0x10a06 // center Charset Hash = 0x47607 // charset Chartreuse Hash = 0x2900a // chartreuse Chocolate Hash = 0x29a09 // chocolate Clear Hash = 0x2c805 // clear Clip Hash = 0x2cd04 // clip Color Hash = 0xd805 // color Column_Rule Hash = 0x3220b // column-rule Column_Rule_Color Hash = 0x32211 // column-rule-color Content Hash = 0x33307 // content Cornflowerblue Hash = 0x3430e // cornflowerblue Cornsilk Hash = 0x35108 // cornsilk Counter_Increment Hash = 0x35911 // counter-increment Counter_Reset Hash = 0x3740d // counter-reset Cue Hash = 0x38103 // cue Cue_After Hash = 0x38109 // cue-after Cue_Before Hash = 0x38a0a // cue-before Currentcolor Hash = 0x39b0c // currentcolor Cursive Hash = 0x3a707 // cursive Cursor Hash = 0x3ba06 // cursor Darkblue Hash = 0xb708 // darkblue Darkcyan Hash = 0xc208 // darkcyan Darkgoldenrod Hash = 0x25f0d // darkgoldenrod Darkgray Hash = 0x26b08 // darkgray Darkgreen Hash = 0x83709 // darkgreen Darkkhaki Hash = 0x94e09 // darkkhaki Darkmagenta Hash = 0x5790b // darkmagenta Darkolivegreen Hash = 0x7c60e // darkolivegreen Darkorange Hash = 0x82b0a // darkorange Darkorchid Hash = 0x9450a // darkorchid Darksalmon Hash = 0x9890a // darksalmon Darkseagreen Hash = 0x9ea0c // darkseagreen Darkslateblue Hash = 0x3c00d // darkslateblue Darkslategray Hash = 0x3cd0d // darkslategray Darkturquoise Hash = 0x3da0d // darkturquoise Darkviolet Hash = 0x3e70a // darkviolet Deeppink Hash = 0x27d08 // deeppink Deepskyblue Hash = 0x95c0b // deepskyblue Default Hash = 0x5ef07 // default Direction Hash = 0xac109 // direction Display Hash = 0x3f107 // display Document Hash = 0x3ff08 // document Dodgerblue Hash = 0x4070a // dodgerblue Elevation Hash = 0x4d409 // elevation Empty_Cells Hash = 0x5200b // empty-cells Fantasy Hash = 0x56107 // fantasy Fill Hash = 0x60c04 // fill Filter Hash = 0x406 // filter Firebrick Hash = 0x41109 // firebrick Flex Hash = 0x41a04 // flex Float Hash = 0x41e05 // float Floralwhite Hash = 0x4230b // floralwhite Font Hash = 0x10304 // font Font_Face Hash = 0x10309 // font-face Font_Family Hash = 0x44d0b // font-family Font_Size Hash = 0x45809 // font-size Font_Size_Adjust Hash = 0x45810 // font-size-adjust Font_Stretch Hash = 0x46c0c // font-stretch Font_Style Hash = 0x47d0a // font-style Font_Variant Hash = 0x4870c // font-variant Font_Weight Hash = 0x4a20b // font-weight Forestgreen Hash = 0x3900b // forestgreen Fuchsia Hash = 0x4ad07 // fuchsia Gainsboro Hash = 0x8809 // gainsboro Ghostwhite Hash = 0x14c0a // ghostwhite Goldenrod Hash = 0x26309 // goldenrod Greenyellow Hash = 0x83b0b // greenyellow Grid Hash = 0x5d204 // grid Height Hash = 0x70906 // height Honeydew Hash = 0x64008 // honeydew Hsl Hash = 0x12203 // hsl Hsla Hash = 0x12204 // hsla Ime_Mode Hash = 0x95608 // ime-mode Import Hash = 0x56806 // import Important Hash = 0x56809 // important Include_Source Hash = 0x8960e // include-source Indianred Hash = 0x57109 // indianred Inherit Hash = 0x5a507 // inherit Initial Hash = 0x5ac07 // initial Keyframes Hash = 0x43109 // keyframes Large Hash = 0x54c05 // large Larger Hash = 0x54c06 // larger Lavender Hash = 0x12408 // lavender Lavenderblush Hash = 0x1240d // lavenderblush Lawngreen Hash = 0x9c09 // lawngreen Layer_Background_Color Hash = 0x17616 // layer-background-color Layer_Background_Image Hash = 0x60f16 // layer-background-image Layout_Flow Hash = 0x5880b // layout-flow Layout_Grid Hash = 0x5cb0b // layout-grid Layout_Grid_Char Hash = 0xa5210 // layout-grid-char Layout_Grid_Char_Spacing Hash = 0xa5218 // layout-grid-char-spacing Layout_Grid_Line Hash = 0x5cb10 // layout-grid-line Layout_Grid_Mode Hash = 0x5e110 // layout-grid-mode Layout_Grid_Type Hash = 0x5f610 // layout-grid-type Left Hash = 0x19f04 // left Lemonchiffon Hash = 0xfa0c // lemonchiffon Letter_Spacing Hash = 0x5bd0e // letter-spacing Lightblue Hash = 0x62509 // lightblue Lightcoral Hash = 0x62e0a // lightcoral Lightcyan Hash = 0x66c09 // lightcyan Lightgoldenrodyellow Hash = 0x67514 // lightgoldenrodyellow Lightgray Hash = 0x69409 // lightgray Lightgreen Hash = 0x69d0a // lightgreen Lightpink Hash = 0x6a709 // lightpink Lightsalmon Hash = 0x6b00b // lightsalmon Lightseagreen Hash = 0x6bb0d // lightseagreen Lightskyblue Hash = 0x6c80c // lightskyblue Lightslateblue Hash = 0x6d40e // lightslateblue Lightsteelblue Hash = 0x6e20e // lightsteelblue Lightyellow Hash = 0x6f00b // lightyellow Limegreen Hash = 0x6fb09 // limegreen Line_Break Hash = 0x5d70a // line-break Line_Height Hash = 0x7040b // line-height Linear_Gradient Hash = 0x70f0f // linear-gradient List_Style Hash = 0x71e0a // list-style List_Style_Image Hash = 0x71e10 // list-style-image List_Style_Position Hash = 0x72e13 // list-style-position List_Style_Type Hash = 0x7410f // list-style-type Local Hash = 0x75005 // local Magenta Hash = 0x57d07 // magenta Margin Hash = 0x2dd06 // margin Margin_Bottom Hash = 0x2dd0d // margin-bottom Margin_Left Hash = 0x2e90b // margin-left Margin_Right Hash = 0x3000c // margin-right Margin_Top Hash = 0x8720a // margin-top Marker_Offset Hash = 0x75e0d // marker-offset Marks Hash = 0x76b05 // marks Mask Hash = 0x78a04 // mask Max_Height Hash = 0x78e0a // max-height Max_Width Hash = 0x79809 // max-width Media Hash = 0xae905 // media Medium Hash = 0x7a106 // medium Mediumaquamarine Hash = 0x7a110 // mediumaquamarine Mediumblue Hash = 0x7b10a // mediumblue Mediumorchid Hash = 0x7bb0c // mediumorchid Mediumpurple Hash = 0x7d40c // mediumpurple Mediumseagreen Hash = 0x7e00e // mediumseagreen Mediumslateblue Hash = 0x7ee0f // mediumslateblue Mediumspringgreen Hash = 0x7fd11 // mediumspringgreen Mediumturquoise Hash = 0x80e0f // mediumturquoise Mediumvioletred Hash = 0x81d0f // mediumvioletred Midnightblue Hash = 0x84b0c // midnightblue Min_Height Hash = 0x8570a // min-height Min_Width Hash = 0x86109 // min-width Mintcream Hash = 0x86a09 // mintcream Mistyrose Hash = 0x88709 // mistyrose Moccasin Hash = 0x89008 // moccasin Monospace Hash = 0x99009 // monospace Namespace Hash = 0x4cc09 // namespace No_Repeat Hash = 0x53309 // no-repeat None Hash = 0x8d204 // none Normal Hash = 0x9706 // normal Olivedrab Hash = 0x8a409 // olivedrab Orangered Hash = 0x82f09 // orangered Orphans Hash = 0x4bc07 // orphans Outline Hash = 0x8d607 // outline Outline_Color Hash = 0x8d60d // outline-color Outline_Style Hash = 0x8e30d // outline-style Outline_Width Hash = 0x8f00d // outline-width Overflow Hash = 0x54008 // overflow Overflow_X Hash = 0x5400a // overflow-x Overflow_Y Hash = 0x8fd0a // overflow-y Padding Hash = 0x2d007 // padding Padding_Bottom Hash = 0x2d00e // padding-bottom Padding_Box Hash = 0x59a0b // padding-box Padding_Left Hash = 0x87b0c // padding-left Padding_Right Hash = 0x9ac0d // padding-right Padding_Top Hash = 0x9a20b // padding-top Page Hash = 0x90704 // page Page_Break_After Hash = 0x90710 // page-break-after Page_Break_Before Hash = 0x91711 // page-break-before Page_Break_Inside Hash = 0x92811 // page-break-inside Palegoldenrod Hash = 0x9390d // palegoldenrod Palegreen Hash = 0x96709 // palegreen Paleturquoise Hash = 0x9700d // paleturquoise Palevioletred Hash = 0x97d0d // palevioletred Papayawhip Hash = 0x9990a // papayawhip Pause Hash = 0x9b905 // pause Pause_After Hash = 0x9b90b // pause-after Pause_Before Hash = 0x9c40c // pause-before Peachpuff Hash = 0x60409 // peachpuff Pitch Hash = 0x9d005 // pitch Pitch_Range Hash = 0x9d00b // pitch-range Play_During Hash = 0x3f40b // play-during Position Hash = 0x3808 // position Powderblue Hash = 0x9db0a // powderblue Progid Hash = 0x9e506 // progid Quotes Hash = 0x9f606 // quotes Radial_Gradient Hash = 0x90f // radial-gradient Repeat Hash = 0x4d06 // repeat Rgb Hash = 0x4f903 // rgb Rgba Hash = 0x4f904 // rgba Richness Hash = 0x55108 // richness Right Hash = 0x1d205 // right Rosybrown Hash = 0x8f09 // rosybrown Round Hash = 0x3205 // round Royalblue Hash = 0x66309 // royalblue Ruby_Align Hash = 0x8c90a // ruby-align Ruby_Overhang Hash = 0x7c0d // ruby-overhang Ruby_Position Hash = 0xdc0d // ruby-position Saddlebrown Hash = 0x4c20b // saddlebrown Sandybrown Hash = 0x52a0a // sandybrown Sans_Serif Hash = 0x5580a // sans-serif Scroll Hash = 0x2b306 // scroll Scrollbar_3d_Light_Color Hash = 0x64c18 // scrollbar-3d-light-color Scrollbar_Arrow_Color Hash = 0x2b315 // scrollbar-arrow-color Scrollbar_Base_Color Hash = 0x43914 // scrollbar-base-color Scrollbar_Dark_Shadow_Color Hash = 0x76f1b // scrollbar-dark-shadow-color Scrollbar_Face_Color Hash = 0x9fb14 // scrollbar-face-color Scrollbar_Highlight_Color Hash = 0xa9e19 // scrollbar-highlight-color Scrollbar_Shadow_Color Hash = 0xa0f16 // scrollbar-shadow-color Scrollbar_Track_Color Hash = 0xa2515 // scrollbar-track-color Seagreen Hash = 0x6c008 // seagreen Seashell Hash = 0x16f08 // seashell Serif Hash = 0x55d05 // serif Size Hash = 0x7104 // size Slateblue Hash = 0x3c409 // slateblue Slategray Hash = 0x3d109 // slategray Small Hash = 0x8c305 // small Smaller Hash = 0x8c307 // smaller Space Hash = 0x15d05 // space Speak Hash = 0xa3a05 // speak Speak_Header Hash = 0xa3a0c // speak-header Speak_Numeral Hash = 0xa460d // speak-numeral Speak_Punctuation Hash = 0xa6a11 // speak-punctuation Speech_Rate Hash = 0xa7b0b // speech-rate Springgreen Hash = 0x8030b // springgreen Steelblue Hash = 0x6e709 // steelblue Stress Hash = 0x2ae06 // stress Stroke Hash = 0x46606 // stroke Supports Hash = 0xa9708 // supports Table_Layout Hash = 0x5820c // table-layout Text_Align Hash = 0x2a10a // text-align Text_Align_Last Hash = 0x2a10f // text-align-last Text_Autospace Hash = 0x1540e // text-autospace Text_Decoration Hash = 0x4e50f // text-decoration Text_Decoration_Color Hash = 0x4e515 // text-decoration-color Text_Emphasis Hash = 0xa840d // text-emphasis Text_Emphasis_Color Hash = 0xa8413 // text-emphasis-color Text_Indent Hash = 0x170b // text-indent Text_Justify Hash = 0x210c // text-justify Text_Kashida_Space Hash = 0x50f12 // text-kashida-space Text_Overflow Hash = 0x53b0d // text-overflow Text_Shadow Hash = 0x520b // text-shadow Text_Transform Hash = 0x2f30e // text-transform Text_Underline_Position Hash = 0x30b17 // text-underline-position Top Hash = 0x22203 // top Transition Hash = 0x3390a // transition Transparent Hash = 0x3690b // transparent Turquoise Hash = 0x3de09 // turquoise Unicode_Bidi Hash = 0xab70c // unicode-bidi Unset Hash = 0xaca05 // unset Vertical_Align Hash = 0x3ac0e // vertical-align Visibility Hash = 0xacf0a // visibility Voice_Family Hash = 0xad90c // voice-family Volume Hash = 0xae506 // volume White Hash = 0x15105 // white White_Space Hash = 0x4970b // white-space Whitesmoke Hash = 0x4290a // whitesmoke Widows Hash = 0x64706 // widows Width Hash = 0x11e05 // width Word_Break Hash = 0x5c0a // word-break Word_Spacing Hash = 0x1410c // word-spacing Word_Wrap Hash = 0x59209 // word-wrap Writing_Mode Hash = 0x6880c // writing-mode X_Large Hash = 0x54a07 // x-large X_Small Hash = 0x8c107 // x-small Xx_Large Hash = 0x54908 // xx-large Xx_Small Hash = 0x8c008 // xx-small Yellow Hash = 0x68306 // yellow Yellowgreen Hash = 0x8400b // yellowgreen Z_Index Hash = 0xaee07 // z-index )
Unique hash definitions to be used instead of strings
type Lexer ¶
type Lexer struct {
// contains filtered or unexported fields
}
Lexer is the state for the lexer.
func (*Lexer) Err ¶
Err returns the error encountered during lexing, this is often io.EOF but also other errors can be returned.
type Parser ¶
type Parser struct {
// contains filtered or unexported fields
}
Parser is the state for the parser.
func NewParser ¶
NewParser returns a new CSS parser from an io.Reader. isInline specifies whether this is an inline style attribute.
Example ¶
Output: color:red;
func (*Parser) Err ¶
Err returns the error encountered during parsing, this is often io.EOF but also other errors can be returned.
func (*Parser) Next ¶
func (p *Parser) Next() (GrammarType, TokenType, []byte)
Next returns the next Grammar. It returns ErrorGrammar when an error was encountered. Using Err() one can retrieve the error message.
type State ¶
type State func(*Parser) GrammarType
State is the state function the parser currently is in.
type TokenType ¶
type TokenType uint32
TokenType determines the type of token, eg. a number or a semicolon.
const ( ErrorToken TokenType = iota // extra token when errors occur IdentToken FunctionToken // rgb( rgba( ... AtKeywordToken // @abc HashToken // #abc StringToken BadStringToken URLToken BadURLToken DelimToken // any unmatched character NumberToken // 5 PercentageToken // 5% DimensionToken // 5em UnicodeRangeToken // U+554A IncludeMatchToken // ~= DashMatchToken // |= PrefixMatchToken // ^= SuffixMatchToken // $= SubstringMatchToken // *= ColumnToken // || WhitespaceToken // space \t \r \n \f CDOToken // <!-- CDCToken // --> ColonToken // : SemicolonToken // ; CommaToken // , LeftBracketToken // [ RightBracketToken // ] LeftParenthesisToken // ( RightParenthesisToken // ) LeftBraceToken // { RightBraceToken // } CommentToken // extra token for comments EmptyToken CustomPropertyNameToken CustomPropertyValueToken )
TokenType values.