Skip to content

Commit

Permalink
Expose Colour.BrightenOrDarken (useful for #211).
Browse files Browse the repository at this point in the history
  • Loading branch information
alecthomas committed Dec 30, 2018
1 parent 881a441 commit 69c9a26
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 9 deletions.
8 changes: 8 additions & 0 deletions colour.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,14 @@ func (c Colour) Brighten(factor float64) Colour {
return NewColour(uint8(r), uint8(g), uint8(b))
}

// BrightenOrDarken brightens a colour if it is < 0.5 brighteness or darkens if > 0.5 brightness.
func (c Colour) BrightenOrDarken(factor float64) Colour {
if c.Brightness() < 0.5 {
return c.Brighten(factor)
}
return c.Brighten(-factor)
}

// Brightness of the colour (roughly) in the range 0.0 to 1.0
func (c Colour) Brightness() float64 {
return (float64(c.Red()) + float64(c.Green()) + float64(c.Blue())) / 255.0 / 3.0
Expand Down
11 changes: 2 additions & 9 deletions formatters/html/html.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,27 +99,20 @@ func (f *Formatter) Format(w io.Writer, style *chroma.Style, iterator chroma.Ite
return f.writeHTML(w, style, iterator.Tokens())
}

func brightenOrDarken(colour chroma.Colour, factor float64) chroma.Colour {
if colour.Brightness() < 0.5 {
return colour.Brighten(factor)
}
return colour.Brighten(-factor)
}

// Ensure that style entries exist for highlighting, etc.
func (f *Formatter) restyle(style *chroma.Style) (*chroma.Style, error) {
builder := style.Builder()
bg := builder.Get(chroma.Background)
// If we don't have a line highlight colour, make one that is 10% brighter/darker than the background.
if !style.Has(chroma.LineHighlight) {
highlight := chroma.StyleEntry{Background: bg.Background}
highlight.Background = brightenOrDarken(highlight.Background, 0.1)
highlight.Background = highlight.Background.BrightenOrDarken(0.1)
builder.AddEntry(chroma.LineHighlight, highlight)
}
// If we don't have line numbers, use the text colour but 20% brighter/darker
if !style.Has(chroma.LineNumbers) {
text := chroma.StyleEntry{Colour: bg.Colour}
text.Colour = brightenOrDarken(text.Colour, 0.5)
text.Colour = text.Colour.BrightenOrDarken(0.5)
builder.AddEntry(chroma.LineNumbers, text)
builder.AddEntry(chroma.LineNumbersTable, text)
}
Expand Down

0 comments on commit 69c9a26

Please sign in to comment.