histyle

package
v1.2.4 Latest Latest
Warning

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

Go to latest
Published: Mar 2, 2021 License: BSD-3-Clause Imports: 22 Imported by: 3

Documentation

Overview

package histyle provides syntax highlighting styles -- it is based on github.com/alecthomas/chroma which in turn was based on the python pygments package. Note that this package depends on goki/gi and goki /pi and cannot be imported there -- is imported into goki/gi/giv

Index

Constants

This section is empty.

Variables

View Source
var ChromaToTokensMap map[chroma.TokenType]token.Tokens

ChromaToTokensMap maps from chroma.TokenType to Tokens -- built from opposite map

View Source
var CustomStyles = Styles{}

CustomStyles are user's special styles

View Source
var KiT_Style = kit.Types.AddType(&Style{}, StyleProps)
View Source
var KiT_StyleEntry = kit.Types.AddType(&StyleEntry{}, StyleEntryProps)
View Source
var KiT_Styles = kit.Types.AddType(&Styles{}, StylesProps)
View Source
var KiT_Trilean = kit.Enums.AddEnumAltLower(TrileanN, kit.NotBitFlag, nil, "")
View Source
var PrefsStylesFileName = "hi_styles.json"

PrefsStylesFileName is the name of the preferences file in App prefs directory for saving / loading the custom styles

View Source
var Props = map[token.Tokens]ki.Props{
	token.TextSpellErr: {
		"text-decoration": 1 << uint32(gist.DecoDottedUnderline),
	},
}

TagsProps are default properties for custom tags (tokens) -- if set in style then used there but otherwise we use these as a fallback -- typically not overridden

View Source
var StyleDefault = gi.HiStyleName("emacs")

StyleDefault is the default highlighting style name -- can set this to whatever you want

View Source
var StyleEntryProps = ki.Props{
	"inline": true,
}
View Source
var StyleNames []string

StyleNames are all the names of all the available highlighting styles

View Source
var StyleProps = ki.Props{
	"MainMenu": ki.PropSlice{
		{"AppMenu", ki.BlankProp{}},
		{"File", ki.PropSlice{
			{"OpenJSON", ki.Props{
				"label":    "Open from file",
				"desc":     "You can save and open styles to / from files to share, experiment, transfer, etc",
				"shortcut": gi.KeyFunMenuOpen,
				"Args": ki.PropSlice{
					{"File Name", ki.Props{
						"ext": ".histy",
					}},
				},
			}},
			{"SaveJSON", ki.Props{
				"label":    "Save to file",
				"desc":     "You can save and open styles to / from files to share, experiment, transfer, etc",
				"shortcut": gi.KeyFunMenuSaveAs,
				"Args": ki.PropSlice{
					{"File Name", ki.Props{
						"ext": ".histy",
					}},
				},
			}},
		}},
		{"Edit", "Copy Cut Paste Dupe"},
		{"Window", "Windows"},
	},
	"ToolBar": ki.PropSlice{
		{"OpenJSON", ki.Props{
			"label": "Open from file",
			"icon":  "file-open",
			"desc":  "You can save and open styles to / from files to share, experiment, transfer, etc -- save from standard ones and load into custom ones for example",
			"Args": ki.PropSlice{
				{"File Name", ki.Props{
					"ext": ".histy",
				}},
			},
		}},
		{"SaveJSON", ki.Props{
			"label": "Save to file",
			"icon":  "file-save",
			"desc":  "You can save and open styles to / from files to share, experiment, transfer, etc -- save from standard ones and load into custom ones for example",
			"Args": ki.PropSlice{
				{"File Name", ki.Props{
					"ext": ".histy",
				}},
			},
		}},
	},
}

StyleProps define the ToolBar and MenuBar for view

View Source
var StylesChanged = false

StylesChanged is used for gui updating while editing

View Source
var StylesProps = ki.Props{
	"MainMenu": ki.PropSlice{
		{"AppMenu", ki.BlankProp{}},
		{"File", ki.PropSlice{
			{"OpenPrefs", ki.Props{}},
			{"SavePrefs", ki.Props{
				"shortcut": gi.KeyFunMenuSave,
				"updtfunc": func(sti interface{}, act *gi.Action) {
					act.SetActiveStateUpdt(StylesChanged && sti.(*Styles) == &CustomStyles)
				},
			}},
			{"sep-file", ki.BlankProp{}},
			{"OpenJSON", ki.Props{
				"label":    "Open...",
				"desc":     "You can save and open styles to / from files to share, experiment, transfer, etc",
				"shortcut": gi.KeyFunMenuOpen,
				"Args": ki.PropSlice{
					{"File Name", ki.Props{
						"ext": ".json",
					}},
				},
			}},
			{"SaveJSON", ki.Props{
				"label":    "Save As...",
				"desc":     "You can save and open styles to / from files to share, experiment, transfer, etc",
				"shortcut": gi.KeyFunMenuSaveAs,
				"Args": ki.PropSlice{
					{"File Name", ki.Props{
						"ext": ".json",
					}},
				},
			}},
			{"SaveAll", ki.Props{
				"label": "Save All...",
				"desc":  "Saves each style individually to selected directory (be sure to select a dir only!)",
				"Args": ki.PropSlice{
					{"Dir Name", ki.Props{}},
				},
			}},
		}},
		{"Edit", "Copy Cut Paste Dupe"},
		{"Window", "Windows"},
	},
	"ToolBar": ki.PropSlice{
		{"Add", ki.Props{
			"desc": "Add a new style to the list.",
			"icon": "plus",
			"updtfunc": func(sti interface{}, act *gi.Action) {
				act.SetActiveStateUpdt(sti.(*Styles) == &CustomStyles)
			},
		}},
		{"SavePrefs", ki.Props{
			"desc": "saves styles to app prefs directory, in file hi_styles.json, which will be loaded automatically at startup into your CustomStyles.",
			"icon": "file-save",
			"updtfunc": func(sti interface{}, act *gi.Action) {
				act.SetActiveStateUpdt(StylesChanged && sti.(*Styles) == &CustomStyles)
			},
		}},
		{"sep-file", ki.BlankProp{}},
		{"OpenJSON", ki.Props{
			"label": "Open from file",
			"icon":  "file-open",
			"desc":  "You can save and open styles to / from files to share, experiment, transfer, etc",
			"Args": ki.PropSlice{
				{"File Name", ki.Props{
					"ext": ".json",
				}},
			},
		}},
		{"SaveJSON", ki.Props{
			"label": "Save to file",
			"icon":  "file-save",
			"desc":  "You can save and open styles to / from files to share, experiment, transfer, etc",
			"Args": ki.PropSlice{
				{"File Name", ki.Props{
					"ext": ".json",
				}},
			},
		}},
		{"sep-std", ki.BlankProp{}},
		{"ViewStd", ki.Props{
			"desc":    `Shows the standard styles that are compiled into the program (from <a href="https://github.com/alecthomas/chroma">github.com/alecthomas/chroma</a>).  Save a style from there and load it into custom as a starting point for creating a variant of an existing style.`,
			"confirm": true,
			"updtfunc": func(sti interface{}, act *gi.Action) {
				act.SetActiveStateUpdt(sti.(*Styles) != &StdStyles)
			},
		}},
	},
}

StylesProps define the ToolBar and MenuBar for view

View Source
var TokensToChromaMap = map[token.Tokens]chroma.TokenType{
	token.EOF:                 chroma.EOFType,
	token.Background:          chroma.Background,
	token.Error:               chroma.Error,
	token.None:                chroma.None,
	token.Keyword:             chroma.Keyword,
	token.KeywordConstant:     chroma.KeywordConstant,
	token.KeywordDeclaration:  chroma.KeywordDeclaration,
	token.KeywordNamespace:    chroma.KeywordNamespace,
	token.KeywordPseudo:       chroma.KeywordPseudo,
	token.KeywordReserved:     chroma.KeywordReserved,
	token.KeywordType:         chroma.KeywordType,
	token.Name:                chroma.Name,
	token.NameAttribute:       chroma.NameAttribute,
	token.NameBuiltin:         chroma.NameBuiltin,
	token.NameBuiltinPseudo:   chroma.NameBuiltinPseudo,
	token.NameClass:           chroma.NameClass,
	token.NameConstant:        chroma.NameConstant,
	token.NameDecorator:       chroma.NameDecorator,
	token.NameEntity:          chroma.NameEntity,
	token.NameException:       chroma.NameException,
	token.NameFunction:        chroma.NameFunction,
	token.NameFunctionMagic:   chroma.NameFunctionMagic,
	token.NameLabel:           chroma.NameLabel,
	token.NameNamespace:       chroma.NameNamespace,
	token.NameOperator:        chroma.NameOperator,
	token.NameOther:           chroma.NameOther,
	token.NamePseudo:          chroma.NamePseudo,
	token.NameProperty:        chroma.NameProperty,
	token.NameTag:             chroma.NameTag,
	token.NameVar:             chroma.NameVariable,
	token.NameVarAnonymous:    chroma.NameVariableAnonymous,
	token.NameVarClass:        chroma.NameVariableClass,
	token.NameVarGlobal:       chroma.NameVariableGlobal,
	token.NameVarInstance:     chroma.NameVariableInstance,
	token.NameVarMagic:        chroma.NameVariableMagic,
	token.Literal:             chroma.Literal,
	token.LiteralDate:         chroma.LiteralDate,
	token.LiteralOther:        chroma.LiteralOther,
	token.LitStr:              chroma.LiteralString,
	token.LitStrAffix:         chroma.LiteralStringAffix,
	token.LitStrAtom:          chroma.LiteralStringAtom,
	token.LitStrBacktick:      chroma.LiteralStringBacktick,
	token.LitStrBoolean:       chroma.LiteralStringBoolean,
	token.LitStrChar:          chroma.LiteralStringChar,
	token.LitStrDelimiter:     chroma.LiteralStringDelimiter,
	token.LitStrDoc:           chroma.LiteralStringDoc,
	token.LitStrDouble:        chroma.LiteralStringDouble,
	token.LitStrEscape:        chroma.LiteralStringEscape,
	token.LitStrHeredoc:       chroma.LiteralStringHeredoc,
	token.LitStrInterpol:      chroma.LiteralStringInterpol,
	token.LitStrName:          chroma.LiteralStringName,
	token.LitStrOther:         chroma.LiteralStringOther,
	token.LitStrRegex:         chroma.LiteralStringRegex,
	token.LitStrSingle:        chroma.LiteralStringSingle,
	token.LitStrSymbol:        chroma.LiteralStringSymbol,
	token.LitNum:              chroma.LiteralNumber,
	token.LitNumBin:           chroma.LiteralNumberBin,
	token.LitNumFloat:         chroma.LiteralNumberFloat,
	token.LitNumHex:           chroma.LiteralNumberHex,
	token.LitNumInteger:       chroma.LiteralNumberInteger,
	token.LitNumIntegerLong:   chroma.LiteralNumberIntegerLong,
	token.LitNumOct:           chroma.LiteralNumberOct,
	token.Operator:            chroma.Operator,
	token.OperatorWord:        chroma.OperatorWord,
	token.Punctuation:         chroma.Punctuation,
	token.Comment:             chroma.Comment,
	token.CommentHashbang:     chroma.CommentHashbang,
	token.CommentMultiline:    chroma.CommentMultiline,
	token.CommentSingle:       chroma.CommentSingle,
	token.CommentSpecial:      chroma.CommentSpecial,
	token.CommentPreproc:      chroma.CommentPreproc,
	token.CommentPreprocFile:  chroma.CommentPreprocFile,
	token.Text:                chroma.Text,
	token.TextWhitespace:      chroma.TextWhitespace,
	token.TextSymbol:          chroma.TextSymbol,
	token.TextPunctuation:     chroma.TextPunctuation,
	token.TextStyle:           chroma.Generic,
	token.TextStyleDeleted:    chroma.GenericDeleted,
	token.TextStyleEmph:       chroma.GenericEmph,
	token.TextStyleError:      chroma.GenericError,
	token.TextStyleHeading:    chroma.GenericHeading,
	token.TextStyleInserted:   chroma.GenericInserted,
	token.TextStyleOutput:     chroma.GenericOutput,
	token.TextStylePrompt:     chroma.GenericPrompt,
	token.TextStyleStrong:     chroma.GenericStrong,
	token.TextStyleSubheading: chroma.GenericSubheading,
	token.TextStyleTraceback:  chroma.GenericTraceback,
	token.TextStyleUnderline:  chroma.GenericUnderline,
}

TokensToChromaMap maps from Tokens to chroma.TokenType

Functions

func Asset added in v0.9.11

func Asset(name string) ([]byte, error)

Asset loads and returns the asset for the given name. It returns an error if the asset could not be found or could not be loaded.

func AssetDir added in v0.9.11

func AssetDir(name string) ([]string, error)

AssetDir returns the file names below a certain directory embedded in the file by go-bindata. For example if you run go-bindata on data/... and data contains the following hierarchy:

data/
  foo.txt
  img/
    a.png
    b.png

then AssetDir("data") would return []string{"foo.txt", "img"} AssetDir("data/img") would return []string{"a.png", "b.png"} AssetDir("foo.txt") and AssetDir("notexist") would return an error AssetDir("") will return []string{"data"}.

func AssetInfo added in v0.9.11

func AssetInfo(name string) (os.FileInfo, error)

AssetInfo loads and returns the asset info for the given name. It returns an error if the asset could not be found or could not be loaded.

func AssetNames added in v0.9.11

func AssetNames() []string

AssetNames returns the names of the assets. nolint: deadcode

func Init

func Init()

Init must be called to initialize the hi styles -- post startup so chroma stuff is all in place, and loads custom styles

func MergeAvailStyles

func MergeAvailStyles()

MergeAvailStyles updates AvailStyles as combination of std and custom styles

func MustAsset added in v0.9.11

func MustAsset(name string) []byte

MustAsset is like Asset but panics when Asset would return an error. It simplifies safe initialization of global variables. nolint: deadcode

func RestoreAsset added in v0.9.11

func RestoreAsset(dir, name string) error

RestoreAsset restores an asset under the given directory

func RestoreAssets added in v0.9.11

func RestoreAssets(dir, name string) error

RestoreAssets restores an asset under the given directory recursively

func TokenFromChroma added in v0.9.4

func TokenFromChroma(ct chroma.TokenType) token.Tokens

FromChroma converts a chroma.TokenType to a pi token.Tokens

func TokenToChroma added in v0.9.4

func TokenToChroma(tok token.Tokens) chroma.TokenType

TokenToChroma converts to a chroma.TokenType

Types

type Style

type Style map[token.Tokens]*StyleEntry

Style is a full style map of styles for different token.Tokens tag values

func AvailStyle

func AvailStyle(nm gi.HiStyleName) *Style

AvailStyle returns a style by name from the AvailStyles list -- if not found default is used as a fallback

func (*Style) CopyFrom

func (hs *Style) CopyFrom(ss *Style)

CopyFrom copies a style from source style

func (Style) OpenJSON

func (hs Style) OpenJSON(filename gi.FileName) error

Open hi style from a JSON-formatted file.

func (Style) SaveJSON

func (hs Style) SaveJSON(filename gi.FileName) error

Save hi style to a JSON-formatted file.

func (Style) Tag

func (hs Style) Tag(tag token.Tokens) StyleEntry

Tag returns a StyleEntry for given Tag. Will try sub-category or category if an exact match is not found. does NOT add the background properties -- those are always kept separate.

func (Style) TagRaw

func (hs Style) TagRaw(tag token.Tokens) StyleEntry

TagRaw returns a StyleEntry for given tag without any inheritance of anything will be IsZero if not defined for this style

func (Style) ToCSS

func (hs Style) ToCSS() map[token.Tokens]string

ToCSS generates a CSS style sheet for this style, by token.Tokens tag

func (Style) ToProps

func (hs Style) ToProps() ki.Props

ToProps generates list of ki.Props for this style

type StyleEntry

type StyleEntry struct {
	Color      gist.Color `desc:"text color"`
	Background gist.Color `desc:"background color"`
	Border     gist.Color `view:"-" desc:"border color? not sure what this is -- not really used"`
	Bold       Trilean    `desc:"bold font"`
	Italic     Trilean    `desc:"italic font"`
	Underline  Trilean    `desc:"underline"`
	NoInherit  bool       `desc:"don't inherit these settings from sub-category or category levels -- otherwise everything with a Pass is inherited"`
}

StyleEntry is one value in the map of highlight style values

func (StyleEntry) Inherit

func (s StyleEntry) Inherit(ancestors ...StyleEntry) StyleEntry

Inherit styles from ancestors.

Ancestors should be provided from oldest, furthest away to newest, closest.

func (StyleEntry) IsZero

func (s StyleEntry) IsZero() bool

func (StyleEntry) String

func (se StyleEntry) String() string

// FromChroma copies styles from chroma

func (he *StyleEntry) FromChroma(ce chroma.StyleEntry) {
	if ce.Colour.IsSet() {
		he.Color.SetString(ce.Colour.String(), nil)
	} else {
		he.Color.SetToNil()
	}
	if ce.Background.IsSet() {
		he.Background.SetString(ce.Background.String(), nil)
	} else {
		he.Background.SetToNil()
	}
	if ce.Border.IsSet() {
		he.Border.SetString(ce.Border.String(), nil)
	} else {
		he.Border.SetToNil()
	}
	he.Bold = Trilean(ce.Bold)
	he.Italic = Trilean(ce.Italic)
	he.Underline = Trilean(ce.Underline)
	he.NoInherit = ce.NoInherit
}

// StyleEntryFromChroma returns a new style entry from corresponding chroma version

func StyleEntryFromChroma(ce chroma.StyleEntry) StyleEntry {
	he := StyleEntry{}
	he.FromChroma(ce)
	return he
}

func (StyleEntry) Sub

func (s StyleEntry) Sub(e StyleEntry) StyleEntry

Sub subtracts two style entries, returning an entry with only the differences set

func (StyleEntry) ToCSS

func (se StyleEntry) ToCSS() string

ToCSS converts StyleEntry to CSS attributes.

func (StyleEntry) ToProps

func (se StyleEntry) ToProps() ki.Props

ToProps converts StyleEntry to ki.Props attributes.

type Styles

type Styles map[string]*Style

Styles is a collection of styles

var AvailStyles Styles

AvailStyles are all highlighting styles

var StdStyles Styles

StdStyles are the styles from chroma package

func (*Styles) Add

func (hs *Styles) Add() *Style

Add adds a new style to the list

func (*Styles) CopyFrom

func (hs *Styles) CopyFrom(os Styles)

CopyFrom copies styles from another collection

func (*Styles) Names

func (hs *Styles) Names() []string

Names outputs names of styles in collection

func (*Styles) OpenDefaults added in v0.9.4

func (hs *Styles) OpenDefaults() error

OpenDefaults opens the default highlighting styles (from chroma originally) These are encoded as an asset from defaults.histys

func (*Styles) OpenJSON

func (hs *Styles) OpenJSON(filename gi.FileName) error

Open hi styles from a JSON-formatted file.

func (*Styles) OpenPrefs

func (hs *Styles) OpenPrefs() error

OpenPrefs opens Styles from App standard prefs directory, using PrefsStylesFileName

func (*Styles) SaveAll added in v0.9.4

func (hs *Styles) SaveAll(dir gi.FileName)

SaveAll saves all styles individually to chosen directory

func (*Styles) SaveJSON

func (hs *Styles) SaveJSON(filename gi.FileName) error

Save hi styles to a JSON-formatted file.

func (*Styles) SavePrefs

func (hs *Styles) SavePrefs() error

SavePrefs saves Styles to App standard prefs directory, using PrefsStylesFileName

func (*Styles) ViewStd

func (hs *Styles) ViewStd()

ViewStd shows the standard styles that are compiled into the program via chroma package

type Trilean

type Trilean uint8

Trilean value for StyleEntry value inheritance.

const (
	Pass Trilean = iota
	Yes
	No

	TrileanN
)

func (*Trilean) FromString

func (i *Trilean) FromString(s string) error

func (Trilean) MarshalJSON

func (ev Trilean) MarshalJSON() ([]byte, error)

func (Trilean) Prefix

func (t Trilean) Prefix(s string) string

func (Trilean) String

func (i Trilean) String() string

func (*Trilean) UnmarshalJSON

func (ev *Trilean) UnmarshalJSON(b []byte) error

Jump to

Keyboard shortcuts

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