// Package utils provides utility functions. package utils import ( "encoding/json" "fmt" "os" "path/filepath" "regexp" "strings" "charm.land/glamour/v2" "charm.land/glamour/v2/ansi" "charm.land/glamour/v2/styles" "charm.land/lipgloss/v2" "charm.land/x/nerdfont" "github.com/mitchellh/go-homedir" ) // RemoveFrontmatter removes the front matter header of a markdown file. func RemoveFrontmatter(content []byte) []byte { if frontmatterBoundaries := detectFrontmatter(content); frontmatterBoundaries[0] == 0 { return content[frontmatterBoundaries[1]:] } return content } var yamlPattern = regexp.MustCompile(`(?m)^---\r?\n(\s*\r?\n)?`) func detectFrontmatter(c []byte) []int { if matches := yamlPattern.FindAllIndex(c, 2); len(matches) > 1 { return []int{matches[0][0], matches[1][1]} } return []int{-1, -1} } // ExpandPath expands tilde and all environment variables from the given path. func ExpandPath(path string) string { s, err := homedir.Expand(path) if err == nil { return os.ExpandEnv(s) } return os.ExpandEnv(path) } // WrapCodeBlock wraps a string in a code block with the given language. func WrapCodeBlock(s, language string) string { return "```" + language + "\n" + s + "```" } var markdownExtensions = []string{ ".md", ".mdown", ".mkdn", ".mkd", ".markdown", } // IsMarkdownFile returns whether the filename has a markdown extension. func IsMarkdownFile(filename string) bool { ext := filepath.Ext(filename) if ext == "" { // By default, assume it's a markdown file. return true } for _, v := range markdownExtensions { if strings.EqualFold(ext, v) { return true } } // Has an extension but not markdown // so assume this is a code file. return false } // GlamourStyle returns a glamour.TermRendererOption based on the given style. func GlamourStyle(style string, isCode bool) glamour.TermRendererOption { return func(tr *glamour.TermRenderer) error { styleConfig, err := styleConfigFor(style, isCode) if err != nil { return err } if !isCode && TextSizingEnabled() { AddHeadingSizeMarkers(&styleConfig) } if err := glamour.WithStyles(styleConfig)(tr); err != nil { return fmt.Errorf("glamour: error applying styles: %w", err) } return nil } } func styleConfigFor(style string, isCode bool) (ansi.StyleConfig, error) { if !isCode { if style == "auto" { style = styles.DarkStyle } if cfg, ok := styles.DefaultStyles[style]; ok { builtin := *cfg useNerdFontAlertIcons(&builtin, style) return builtin, nil } return styleConfigFromFile(style) } // If we are rendering a pure code block, we need to modify the style to // remove the indentation. switch style { case "auto": if lipgloss.HasDarkBackground(os.Stdin, os.Stdout) { style = styles.DarkStyle } else { style = styles.LightStyle } case styles.TokyoNightStyle: style = styles.DraculaStyle case styles.DarkStyle, styles.LightStyle, styles.PinkStyle, styles.NoTTYStyle, styles.DraculaStyle: default: return styleConfigFromFile(style) } styleConfig := *styles.DefaultStyles[style] var margin uint styleConfig.CodeBlock.Margin = &margin return styleConfig, nil } func styleConfigFromFile(path string) (ansi.StyleConfig, error) { jsonBytes, err := os.ReadFile(path) //nolint:gosec if err != nil { return ansi.StyleConfig{}, fmt.Errorf("glamour: error reading file: %w", err) } var styleConfig ansi.StyleConfig if err := json.Unmarshal(jsonBytes, &styleConfig); err != nil { return ansi.StyleConfig{}, fmt.Errorf("glamour: error parsing style file: %w", err) } return styleConfig, nil } // Nerd Font glyphs for the GitHub alerts, matching the octicons GitHub itself // uses. Each one is followed by a space, like the Unicode fallback. const ( nerdFontNote = "\uf449 " // nf-oct-info nerdFontTip = "\uf400 " // nf-oct-light_bulb nerdFontImportant = "\uf50a " // nf-oct-report nerdFontWarning = "\uf421 " // nf-oct-alert nerdFontCaution = "\uf46e " // nf-oct-stop ) // useNerdFontAlertIcons swaps the alert icons of a built-in style for their // Nerd Font counterparts when the terminal renders them, keeping the style's // Unicode icon as the fallback. The plain styles are left alone, since they // are meant to be portable. func useNerdFontAlertIcons(cfg *ansi.StyleConfig, style string) { if style == styles.NoTTYStyle || style == styles.AsciiStyle { return } icons := []struct { alert *ansi.StyleAlert icon string }{ {&cfg.Alerts.Note, nerdFontNote}, {&cfg.Alerts.Tip, nerdFontTip}, {&cfg.Alerts.Important, nerdFontImportant}, {&cfg.Alerts.Warning, nerdFontWarning}, {&cfg.Alerts.Caution, nerdFontCaution}, } for _, i := range icons { i.alert.Title.Prefix = nerdfont.Glyph(i.icon, i.alert.Title.Prefix) } }