i18n

package
v0.0.6 Latest Latest
Warning

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

Go to latest
Published: Feb 3, 2026 License: EUPL-1.2 Imports: 18 Imported by: 0

Documentation

Overview

Package i18n provides internationalization for the CLI.

Package i18n provides internationalization for the CLI.

Package i18n provides internationalization for the CLI.

Package i18n provides internationalization for the CLI.

Package i18n provides internationalization for the CLI.

Package i18n provides internationalization for the CLI.

Package i18n provides internationalization for the CLI.

Locale files use nested JSON for compatibility with translation tools:

{
    "cli": {
        "success": "Operation completed",
        "count": {
            "items": {
                "one": "{{.Count}} item",
                "other": "{{.Count}} items"
            }
        }
    }
}

Keys are accessed with dot notation: T("cli.success"), T("cli.count.items")

Getting Started

svc, err := i18n.New()
fmt.Println(svc.T("cli.success"))
fmt.Println(svc.T("cli.count.items", map[string]any{"Count": 5}))

Package i18n provides internationalization for the CLI.

Package i18n provides internationalization for the CLI.

Package i18n provides internationalization for the CLI.

Package i18n provides internationalization for the CLI.

Package i18n provides internationalization for the CLI.

Package i18n provides internationalization for the CLI.

Package i18n provides internationalization for the CLI.

Package i18n provides internationalization for the CLI.

Index

Constants

This section is empty.

Variables

View Source
var ErrServiceNotInitialized = errors.New("i18n: service not initialized")

ErrServiceNotInitialized is returned when the i18n service is not initialized.

Functions

func ActionFailed

func ActionFailed(verb, subject string) string

ActionFailed returns a failure message for an action. Generates "Failed to verb subject" form.

ActionFailed("delete", "file")  // "Failed to delete file"
ActionFailed("push", "commits") // "Failed to push commits"

func ActionResult

func ActionResult(verb, subject string) string

ActionResult returns a result message for a completed action. Generates "Subject verbed" form.

ActionResult("delete", "file")  // "File deleted"
ActionResult("commit", "changes") // "Changes committed"

func AddHandler

func AddHandler(h KeyHandler)

AddHandler appends a handler to the default service's handler chain. Does nothing if the service is not initialized.

func Article

func Article(word string) string

Article returns the appropriate indefinite article ("a" or "an") for a word.

Article("file")     // "a"
Article("error")    // "an"
Article("user")     // "a" (sounds like "yoo-zer")
Article("hour")     // "an" (silent h)

func CurrentLanguage

func CurrentLanguage() string

CurrentLanguage returns the current language code from the default service. Returns "en-GB" (the fallback language) if the service is not initialized.

func FormatAgo

func FormatAgo(count int, unit string) string

FormatAgo formats "N unit ago" with proper pluralization. Uses locale-specific patterns from time.ago.{unit}.

FormatAgo(5, "minute") // "5 minutes ago"
FormatAgo(1, "hour")   // "1 hour ago"

func FormatBytes

func FormatBytes(bytes int64) string

FormatBytes formats bytes as human-readable size.

FormatBytes(1536)      // "1.5 KB"
FormatBytes(1536000)   // "1.5 MB"
FormatBytes(1536000000) // "1.4 GB"

func FormatDecimal

func FormatDecimal(f float64) string

FormatDecimal formats a float with locale-specific separators. Uses up to 2 decimal places, trimming trailing zeros.

FormatDecimal(1234.5)  // "1,234.5" (en) or "1.234,5" (de)
FormatDecimal(1234.00) // "1,234" (en) or "1.234" (de)

func FormatDecimalN

func FormatDecimalN(f float64, decimals int) string

FormatDecimalN formats a float with N decimal places.

FormatDecimalN(1234.5678, 3) // "1,234.568" (en)

func FormatNumber

func FormatNumber(n int64) string

FormatNumber formats an integer with locale-specific thousands separators.

FormatNumber(1234567) // "1,234,567" (en) or "1.234.567" (de)

func FormatOrdinal

func FormatOrdinal(n int) string

FormatOrdinal formats a number as an ordinal.

FormatOrdinal(1)  // "1st" (en) or "1." (de)
FormatOrdinal(2)  // "2nd" (en) or "2." (de)
FormatOrdinal(3)  // "3rd" (en) or "3." (de)
FormatOrdinal(11) // "11th" (en) or "11." (de)

func FormatPercent

func FormatPercent(f float64) string

FormatPercent formats a decimal as a percentage.

FormatPercent(0.85)   // "85%" (en) or "85 %" (de)
FormatPercent(0.333)  // "33.3%" (en)
FormatPercent(1.5)    // "150%" (en)

func Gerund

func Gerund(verb string) string

Gerund returns the present participle (-ing form) of a verb. Checks JSON locale data first, then irregular verbs, then applies regular rules.

Gerund("delete")  // "deleting"
Gerund("run")     // "running"
Gerund("die")     // "dying"

func Init

func Init() error

Init initializes the default global service.

func IsRTL

func IsRTL() bool

IsRTL returns true if the current language uses right-to-left text.

func IsRTLLanguage

func IsRTLLanguage(lang string) bool

IsRTLLanguage returns true if the language code uses right-to-left text.

func Label

func Label(word string) string

Label returns a label with a colon suffix. Generates "Word:" form using language-specific punctuation. French uses " :" (space before colon), English uses ":".

Label("status")   // EN: "Status:"  FR: "Statut :"
Label("version")  // EN: "Version:" FR: "Version :"

func N

func N(format string, value any) string

N formats a number using the i18n.numeric.* namespace. Wrapper for T("i18n.numeric.{format}", value).

N("number", 1234567)   // T("i18n.numeric.number", 1234567)
N("percent", 0.85)     // T("i18n.numeric.percent", 0.85)
N("bytes", 1536000)    // T("i18n.numeric.bytes", 1536000)
N("ordinal", 1)        // T("i18n.numeric.ordinal", 1)

func OnMissingKey

func OnMissingKey(h MissingKeyHandler)

OnMissingKey registers a handler for missing translation keys. Called when T() can't find a key in ModeCollect. Thread-safe: can be called concurrently with translations.

i18n.SetMode(i18n.ModeCollect)
i18n.OnMissingKey(func(m i18n.MissingKey) {
    log.Printf("MISSING: %s at %s:%d", m.Key, m.CallerFile, m.CallerLine)
})

func PastTense

func PastTense(verb string) string

PastTense returns the past tense of a verb. Checks JSON locale data first, then irregular verbs, then applies regular rules.

PastTense("delete") // "deleted"
PastTense("run")    // "ran"
PastTense("copy")   // "copied"

func PluralForm

func PluralForm(noun string) string

PluralForm returns the plural form of a noun. Checks JSON locale data first, then irregular nouns, then applies regular rules.

PluralForm("file")   // "files"
PluralForm("child")  // "children"
PluralForm("box")    // "boxes"

func Pluralize

func Pluralize(noun string, count int) string

Pluralize returns the plural form of a noun based on count. If count is 1, returns the singular form unchanged.

Pluralize("file", 1)    // "file"
Pluralize("file", 5)    // "files"
Pluralize("child", 3)   // "children"
Pluralize("box", 2)     // "boxes"

func PrependHandler

func PrependHandler(h KeyHandler)

PrependHandler inserts a handler at the start of the default service's handler chain. Does nothing if the service is not initialized.

func Progress

func Progress(verb string) string

Progress returns a progress message for a verb. Generates "Verbing..." form using language-specific punctuation.

Progress("build")  // "Building..."
Progress("check")  // "Checking..."
Progress("fetch")  // "Fetching..."

func ProgressSubject

func ProgressSubject(verb, subject string) string

ProgressSubject returns a progress message with a subject. Generates "Verbing subject..." form using language-specific punctuation.

ProgressSubject("build", "project")    // "Building project..."
ProgressSubject("check", "config.yaml") // "Checking config.yaml..."

func Quote

func Quote(s string) string

Quote wraps a string in double quotes.

func Raw

func Raw(messageID string, args ...any) string

Raw is the raw translation helper without i18n.* namespace magic. Unlike T(), this does NOT handle i18n.* namespace patterns. Use this for direct key lookups without auto-composition.

Raw("cli.success")              // Direct lookup
T("i18n.label.status")          // Smart: returns "Status:"

func RegisterLocales

func RegisterLocales(fsys fs.FS, dir string)

RegisterLocales registers a filesystem containing locale files to be loaded. Call this in your package's init() to register translations. Locales are loaded when the i18n service initialises.

//go:embed locales/*.json
var localeFS embed.FS

func init() {
    i18n.RegisterLocales(localeFS, "locales")
}

func RunHandlerChain

func RunHandlerChain(handlers []KeyHandler, key string, args []any, fallback func() string) string

RunHandlerChain executes a chain of handlers for a key. Returns empty string if no handler matched (caller should use standard lookup).

func SetDebug

func SetDebug(enabled bool)

SetDebug enables or disables debug mode on the default service. Does nothing if the service is not initialized. In debug mode, translations show their keys: [key] translation

SetDebug(true)
T("cli.success") // "[cli.success] Success"

func SetDefault

func SetDefault(s *Service)

SetDefault sets the global i18n service. Thread-safe: can be called concurrently with Default(). Panics if s is nil.

func SetFormality

func SetFormality(f Formality)

SetFormality sets the default formality level on the default service. Does nothing if the service is not initialized.

SetFormality(FormalityFormal)  // Use formal address (Sie, vous)

func SetGrammarData

func SetGrammarData(lang string, data *GrammarData)

SetGrammarData sets the grammar data for a language. Called by the Service when loading locale files.

func SetLanguage

func SetLanguage(lang string) error

SetLanguage sets the language for the default service. Returns ErrServiceNotInitialized if the service has not been initialized, or an error if the language tag is invalid or unsupported.

Unlike other Set* functions, this returns an error because it validates the language tag against available locales.

func SetMode

func SetMode(m Mode)

SetMode sets the translation mode for the default service. Does nothing if the service is not initialized.

func T

func T(messageID string, args ...any) string

T translates a message using the default service. For semantic intents (core.* namespace), pass a Subject as the first argument.

T("cli.success")                           // Simple translation
T("core.delete", S("file", "config.yaml")) // Semantic intent

func TemplateFuncs

func TemplateFuncs() template.FuncMap

TemplateFuncs returns the template.FuncMap with all grammar functions. Use this to add grammar helpers to your templates.

tmpl := template.New("").Funcs(i18n.TemplateFuncs())

func TimeAgo

func TimeAgo(t time.Time) string

TimeAgo returns a localized relative time string.

TimeAgo(time.Now().Add(-5 * time.Minute)) // "5 minutes ago"
TimeAgo(time.Now().Add(-1 * time.Hour))   // "1 hour ago"

func Title

func Title(s string) string

Title capitalizes the first letter of each word. Uses unicode-aware casing for proper internationalization. Word boundaries are defined as any non-letter character (matching strings.Title behavior).

Types

type ArticleForms

type ArticleForms struct {
	IndefiniteDefault string            // Default indefinite article (e.g., "a")
	IndefiniteVowel   string            // Indefinite article before vowel sounds (e.g., "an")
	Definite          string            // Definite article (e.g., "the")
	ByGender          map[string]string // Gender-specific articles for gendered languages
}

ArticleForms holds article configuration for a language.

type Composed

type Composed struct {
	Question string     // Question form: "Delete config.yaml?"
	Confirm  string     // Confirmation form: "Really delete config.yaml?"
	Success  string     // Success message: "config.yaml deleted"
	Failure  string     // Failure message: "Failed to delete config.yaml"
	Meta     IntentMeta // Intent metadata for UI decisions
}

Composed holds all output forms for an intent after template resolution.

type CountHandler

type CountHandler struct{}

CountHandler handles i18n.count.{noun} → "5 files" patterns.

func (CountHandler) Handle

func (h CountHandler) Handle(key string, args []any, next func() string) string

Handle transforms count keys into pluralized phrases like "5 files".

func (CountHandler) Match

func (h CountHandler) Match(key string) bool

Match returns true for keys starting with "i18n.count.".

type DoneHandler

type DoneHandler struct{}

DoneHandler handles i18n.done.{verb} → "File deleted" patterns.

func (DoneHandler) Handle

func (h DoneHandler) Handle(key string, args []any, next func() string) string

Handle transforms done keys into past-tense completion messages.

func (DoneHandler) Match

func (h DoneHandler) Match(key string) bool

Match returns true for keys starting with "i18n.done.".

type FSLoader

type FSLoader struct {
	// contains filtered or unexported fields
}

FSLoader loads translations from a filesystem (embedded or disk).

func NewFSLoader

func NewFSLoader(fsys fs.FS, dir string) *FSLoader

NewFSLoader creates a loader for the given filesystem and directory.

func (*FSLoader) Languages

func (l *FSLoader) Languages() []string

Languages implements Loader.Languages - returns available language codes. Thread-safe: uses sync.Once to ensure the directory is scanned only once. Returns nil if the directory scan failed (check LanguagesErr for details).

func (*FSLoader) LanguagesErr

func (l *FSLoader) LanguagesErr() error

LanguagesErr returns any error that occurred during Languages() scan. Returns nil if the scan succeeded.

func (*FSLoader) Load

func (l *FSLoader) Load(lang string) (map[string]Message, *GrammarData, error)

Load implements Loader.Load - loads messages and grammar for a language.

type FailHandler

type FailHandler struct{}

FailHandler handles i18n.fail.{verb} → "Failed to delete file" patterns.

func (FailHandler) Handle

func (h FailHandler) Handle(key string, args []any, next func() string) string

Handle transforms fail keys into failure messages like "Failed to delete".

func (FailHandler) Match

func (h FailHandler) Match(key string) bool

Match returns true for keys starting with "i18n.fail.".

type Formality

type Formality int

Formality represents the level of formality in translations. Used for languages that distinguish formal/informal address (Sie/du, vous/tu).

const (
	// FormalityNeutral uses context-appropriate formality (default)
	FormalityNeutral Formality = iota
	// FormalityInformal uses informal address (du, tu, you)
	FormalityInformal
	// FormalityFormal uses formal address (Sie, vous, usted)
	FormalityFormal
)

func (Formality) String

func (f Formality) String() string

String returns the string representation of the Formality.

type GrammarData

type GrammarData struct {
	Verbs    map[string]VerbForms // verb -> forms
	Nouns    map[string]NounForms // noun -> forms
	Articles ArticleForms         // article configuration
	Words    map[string]string    // base word translations
	Punct    PunctuationRules     // language-specific punctuation
}

GrammarData holds language-specific grammar forms loaded from JSON.

func GetGrammarData

func GetGrammarData(lang string) *GrammarData

GetGrammarData returns the grammar data for the specified language. Returns nil if no grammar data is loaded for the language.

type GrammaticalGender

type GrammaticalGender int

GrammaticalGender represents grammatical gender for nouns.

const (
	// GenderNeuter is used for neuter nouns (das in German, it in English)
	GenderNeuter GrammaticalGender = iota
	// GenderMasculine is used for masculine nouns (der in German, le in French)
	GenderMasculine
	// GenderFeminine is used for feminine nouns (die in German, la in French)
	GenderFeminine
	// GenderCommon is used in languages with common gender (Swedish, Dutch)
	GenderCommon
)

func (GrammaticalGender) String

func (g GrammaticalGender) String() string

String returns the string representation of the GrammaticalGender.

type Intent

type Intent struct {
	Meta     IntentMeta // Intent behaviour and characteristics
	Question string     // Template for question form
	Confirm  string     // Template for confirmation form
	Success  string     // Template for success message
	Failure  string     // Template for failure message
}

Intent defines a semantic intent with templates for all output forms.

type IntentMeta

type IntentMeta struct {
	Type      string   // "action", "question", "info"
	Verb      string   // Reference to verb key (e.g., "delete", "save")
	Dangerous bool     // If true, requires extra confirmation
	Default   string   // Default response: "yes" or "no"
	Supports  []string // Extra options supported by this intent
}

IntentMeta defines the behaviour and characteristics of an intent.

type KeyHandler

type KeyHandler interface {
	// Match returns true if this handler should process the key.
	Match(key string) bool

	// Handle processes the key and returns the result.
	// Call next() to delegate to the next handler in the chain.
	Handle(key string, args []any, next func() string) string
}

KeyHandler processes translation keys before standard lookup. Handlers form a chain; each can handle a key or delegate to the next handler. Use this to implement dynamic key patterns like i18n.label.*, i18n.progress.*, etc.

func DefaultHandlers

func DefaultHandlers() []KeyHandler

DefaultHandlers returns the built-in i18n.* namespace handlers.

type LabelHandler

type LabelHandler struct{}

LabelHandler handles i18n.label.{word} → "Status:" patterns.

func (LabelHandler) Handle

func (h LabelHandler) Handle(key string, args []any, next func() string) string

Handle transforms label keys into formatted labels with colons.

func (LabelHandler) Match

func (h LabelHandler) Match(key string) bool

Match returns true for keys starting with "i18n.label.".

type Loader

type Loader interface {
	// Load returns messages and grammar data for a language.
	// Returns an error if the language cannot be loaded.
	Load(lang string) (map[string]Message, *GrammarData, error)

	// Languages returns all available language codes.
	Languages() []string
}

Loader provides translation data to the Service. Implement this interface to support custom storage backends (database, remote API, etc.).

type Message

type Message struct {
	Text  string // Simple string value (non-plural)
	Zero  string // count == 0 (Arabic, Latvian, Welsh)
	One   string // count == 1 (most languages)
	Two   string // count == 2 (Arabic, Welsh)
	Few   string // Small numbers (Slavic: 2-4, Arabic: 3-10)
	Many  string // Larger numbers (Slavic: 5+, Arabic: 11-99)
	Other string // Default/fallback form
}

Message represents a translation - either a simple string or plural forms. Supports full CLDR plural categories for languages with complex plural rules.

func (Message) ForCategory

func (m Message) ForCategory(cat PluralCategory) string

ForCategory returns the appropriate text for a plural category. Falls back through the category hierarchy to find a non-empty string.

func (Message) IsPlural

func (m Message) IsPlural() bool

IsPlural returns true if this message has any plural forms.

type MissingKey

type MissingKey struct {
	Key        string         // The missing translation key
	Args       map[string]any // Arguments passed to the translation
	CallerFile string         // Source file where T() was called
	CallerLine int            // Line number where T() was called
}

MissingKey is dispatched when a translation key is not found in ModeCollect.

type MissingKeyHandler

type MissingKeyHandler func(missing MissingKey)

MissingKeyHandler receives missing key events for analysis.

type Mode

type Mode int

Mode determines how the i18n service handles missing translation keys.

const (
	// ModeNormal returns the key as-is when a translation is missing (production).
	ModeNormal Mode = iota
	// ModeStrict panics immediately when a translation is missing (dev/CI).
	ModeStrict
	// ModeCollect dispatches MissingKey actions and returns [key] (QA testing).
	ModeCollect
)

func CurrentMode

func CurrentMode() Mode

CurrentMode returns the current translation mode from the default service.

func (Mode) String

func (m Mode) String() string

String returns the string representation of the Mode.

type NounForms

type NounForms struct {
	One    string // Singular form
	Other  string // Plural form
	Gender string // Grammatical gender (masculine, feminine, neuter, common)
}

NounForms holds plural and gender information for a noun.

type NumberFormat

type NumberFormat struct {
	ThousandsSep string // "," for en, "." for de
	DecimalSep   string // "." for en, "," for de
	PercentFmt   string // "%s%%" for en, "%s %%" for de (space before %)
}

NumberFormat defines locale-specific number formatting rules.

type NumericHandler

type NumericHandler struct{}

NumericHandler handles i18n.numeric.{format} → formatted numbers.

func (NumericHandler) Handle

func (h NumericHandler) Handle(key string, args []any, next func() string) string

Handle transforms numeric keys into locale-formatted numbers.

func (NumericHandler) Match

func (h NumericHandler) Match(key string) bool

Match returns true for keys starting with "i18n.numeric.".

type Option

type Option func(*Service)

Option configures a Service during construction.

func WithDebug

func WithDebug(enabled bool) Option

WithDebug enables or disables debug mode.

func WithDefaultHandlers

func WithDefaultHandlers() Option

WithDefaultHandlers adds the default i18n.* namespace handlers. Use this after WithHandlers to add defaults back, or to ensure defaults are present.

func WithFallback

func WithFallback(lang string) Option

WithFallback sets the fallback language for missing translations.

func WithFormality

func WithFormality(f Formality) Option

WithFormality sets the default formality level.

func WithHandlers

func WithHandlers(handlers ...KeyHandler) Option

WithHandlers sets custom handlers (replaces default handlers).

func WithMode

func WithMode(m Mode) Option

WithMode sets the translation mode.

type PluralCategory

type PluralCategory int

PluralCategory represents CLDR plural categories. Different languages use different subsets of these categories.

const (
	// PluralOther is the default/fallback category
	PluralOther PluralCategory = iota
	// PluralZero is used when count == 0 (Arabic, Latvian, etc.)
	PluralZero
	// PluralOne is used when count == 1 (most languages)
	PluralOne
	// PluralTwo is used when count == 2 (Arabic, Welsh, etc.)
	PluralTwo
	// PluralFew is used for small numbers (Slavic: 2-4, Arabic: 3-10, etc.)
	PluralFew
	// PluralMany is used for larger numbers (Slavic: 5+, Arabic: 11-99, etc.)
	PluralMany
)

func GetPluralCategory

func GetPluralCategory(lang string, n int) PluralCategory

GetPluralCategory returns the plural category for a count in the given language.

func (PluralCategory) String

func (p PluralCategory) String() string

String returns the string representation of the PluralCategory.

type PluralRule

type PluralRule func(n int) PluralCategory

PluralRule is a function that determines the plural category for a count.

func GetPluralRule

func GetPluralRule(lang string) PluralRule

GetPluralRule returns the plural rule for a language code. Falls back to English rules if the language is not found.

type ProgressHandler

type ProgressHandler struct{}

ProgressHandler handles i18n.progress.{verb} → "Building..." patterns.

func (ProgressHandler) Handle

func (h ProgressHandler) Handle(key string, args []any, next func() string) string

Handle transforms progress keys into gerund phrases like "Building...".

func (ProgressHandler) Match

func (h ProgressHandler) Match(key string) bool

Match returns true for keys starting with "i18n.progress.".

type PunctuationRules

type PunctuationRules struct {
	LabelSuffix    string // Suffix for labels (default ":")
	ProgressSuffix string // Suffix for progress (default "...")
}

PunctuationRules holds language-specific punctuation patterns.

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service provides internationalization and localization.

func Default

func Default() *Service

Default returns the global i18n service, initializing if needed. Thread-safe: can be called concurrently.

func New

func New(opts ...Option) (*Service, error)

New creates a new i18n service with embedded locales and default options.

func NewWithFS

func NewWithFS(fsys fs.FS, dir string, opts ...Option) (*Service, error)

NewWithFS creates a new i18n service loading locales from the given filesystem.

func NewWithLoader

func NewWithLoader(loader Loader, opts ...Option) (*Service, error)

NewWithLoader creates a new i18n service with a custom loader. Use this for custom storage backends (database, remote API, etc.).

loader := NewFSLoader(customFS, "translations")
svc, err := NewWithLoader(loader, WithFallback("de-DE"))

func (*Service) AddHandler

func (s *Service) AddHandler(h KeyHandler)

AddHandler appends a handler to the end of the handler chain. Later handlers have lower priority (run if earlier handlers don't match).

Note: Handlers are executed during T() while holding a read lock. Handlers should not call back into the same Service instance to avoid contention. Grammar functions like PastTense() use currentLangForGrammar() which safely calls Default().Language().

func (*Service) AddMessages

func (s *Service) AddMessages(lang string, messages map[string]string)

AddMessages adds messages for a language at runtime.

func (*Service) AvailableLanguages

func (s *Service) AvailableLanguages() []string

AvailableLanguages returns the list of available language codes.

func (*Service) ClearHandlers

func (s *Service) ClearHandlers()

ClearHandlers removes all handlers from the chain. Useful for testing or disabling all i18n.* magic.

func (*Service) Debug

func (s *Service) Debug() bool

Debug returns whether debug mode is enabled.

func (*Service) Direction

func (s *Service) Direction() TextDirection

Direction returns the text direction for the current language.

func (*Service) Formality

func (s *Service) Formality() Formality

Formality returns the current formality level.

func (*Service) Handlers

func (s *Service) Handlers() []KeyHandler

Handlers returns a copy of the current handler chain.

func (*Service) IsRTL

func (s *Service) IsRTL() bool

IsRTL returns true if the current language uses right-to-left text direction.

func (*Service) Language

func (s *Service) Language() string

Language returns the current language code.

func (*Service) LoadFS

func (s *Service) LoadFS(fsys fs.FS, dir string) error

LoadFS loads additional locale files from a filesystem.

func (*Service) Mode

func (s *Service) Mode() Mode

Mode returns the current translation mode.

func (*Service) PluralCategory

func (s *Service) PluralCategory(n int) PluralCategory

PluralCategory returns the plural category for a count in the current language.

func (*Service) PrependHandler

func (s *Service) PrependHandler(h KeyHandler)

PrependHandler inserts a handler at the start of the handler chain. Prepended handlers have highest priority (run first).

func (*Service) Raw

func (s *Service) Raw(messageID string, args ...any) string

Raw is the raw translation helper without i18n.* namespace magic. Use T() for smart i18n.* handling, Raw() for direct key lookup.

func (*Service) SetDebug

func (s *Service) SetDebug(enabled bool)

SetDebug enables or disables debug mode. In debug mode, translations are prefixed with their key:

[cli.success] Success
[core.delete] Delete config.yaml?

func (*Service) SetFormality

func (s *Service) SetFormality(f Formality)

SetFormality sets the default formality level for translations. This affects languages that distinguish formal/informal address (Sie/du, vous/tu).

svc.SetFormality(FormalityFormal)  // Use formal address

func (*Service) SetLanguage

func (s *Service) SetLanguage(lang string) error

SetLanguage sets the language for translations.

func (*Service) SetMode

func (s *Service) SetMode(m Mode)

SetMode sets the translation mode for missing key handling.

func (*Service) T

func (s *Service) T(messageID string, args ...any) string

T translates a message by its ID with handler chain support.

i18n Namespace Magic

The i18n.* namespace provides auto-composed grammar shortcuts:

T("i18n.label.status")              // → "Status:"
T("i18n.progress.build")            // → "Building..."
T("i18n.progress.check", "config")  // → "Checking config..."
T("i18n.count.file", 5)             // → "5 files"
T("i18n.done.delete", "file")       // → "File deleted"
T("i18n.fail.delete", "file")       // → "Failed to delete file"

For semantic intents, pass a Subject:

T("core.delete", S("file", "config.yaml")) // → "Delete config.yaml?"

Use Raw() for direct key lookup without handler chain processing.

type Subject

type Subject struct {
	Noun  string // The noun type (e.g., "file", "repo", "user")
	Value any    // The actual value (e.g., filename, struct, etc.)
	// contains filtered or unexported fields
}

Subject represents a typed subject with metadata for semantic translations. Use S() to create a Subject and chain methods for additional context.

func S

func S(noun string, value any) *Subject

S creates a new Subject with the given noun and value. The noun is used for grammar rules, the value for display.

S("file", "config.yaml")     // "config.yaml"
S("repo", repo)              // Uses repo.String() or fmt.Sprint()
S("file", path).Count(3).In("workspace")

func (*Subject) Count

func (s *Subject) Count(n int) *Subject

Count sets the count for pluralization. Used to determine singular/plural forms in templates.

S("file", files).Count(len(files))

func (*Subject) CountInt

func (s *Subject) CountInt() int

CountInt returns the count value.

func (*Subject) CountString

func (s *Subject) CountString() string

CountString returns the count as a string.

func (*Subject) Formal

func (s *Subject) Formal() *Subject

Formal sets the formality level to formal (Sie, vous, usted). Use for polite/professional address in languages that distinguish formality.

S("colleague", name).Formal()

func (*Subject) Formality

func (s *Subject) Formality(f Formality) *Subject

Formality sets the formality level explicitly.

S("user", name).Formality(FormalityFormal)

func (*Subject) FormalityString

func (s *Subject) FormalityString() string

FormalityString returns the formality level as a string. Returns "neutral" if not explicitly set.

func (*Subject) Gender

func (s *Subject) Gender(g string) *Subject

Gender sets the grammatical gender for languages that require it. Common values: "masculine", "feminine", "neuter"

S("user", user).Gender("female")

func (*Subject) GenderString

func (s *Subject) GenderString() string

GenderString returns the grammatical gender.

func (*Subject) In

func (s *Subject) In(location string) *Subject

In sets the location context for the subject. Used in templates to provide spatial context.

S("file", "config.yaml").In("workspace")

func (*Subject) Informal

func (s *Subject) Informal() *Subject

Informal sets the formality level to informal (du, tu, tú). Use for casual/friendly address in languages that distinguish formality.

S("friend", name).Informal()

func (*Subject) IsFormal

func (s *Subject) IsFormal() bool

IsFormal returns true if formal address should be used.

func (*Subject) IsInformal

func (s *Subject) IsInformal() bool

IsInformal returns true if informal address should be used.

func (*Subject) IsPlural

func (s *Subject) IsPlural() bool

IsPlural returns true if count != 1.

func (*Subject) LocationString

func (s *Subject) LocationString() string

LocationString returns the location context.

func (*Subject) NounString

func (s *Subject) NounString() string

NounString returns the noun type.

func (*Subject) String

func (s *Subject) String() string

String returns the display value of the subject.

type TextDirection

type TextDirection int

TextDirection represents text directionality.

const (
	// DirLTR is left-to-right text direction (English, German, etc.)
	DirLTR TextDirection = iota
	// DirRTL is right-to-left text direction (Arabic, Hebrew, etc.)
	DirRTL
)

func Direction

func Direction() TextDirection

Direction returns the text direction for the current language.

func (TextDirection) String

func (d TextDirection) String() string

String returns the string representation of the TextDirection.

type TranslationContext

type TranslationContext struct {
	Context   string         // Semantic context (e.g., "navigation", "correctness")
	Gender    string         // Grammatical gender hint (e.g., "masculine", "feminine")
	Formality Formality      // Formality level override
	Extra     map[string]any // Additional context-specific data
}

TranslationContext provides disambiguation for translations. Use this when the same word translates differently in different contexts.

Example: "right" can mean direction or correctness:

T("direction.right", C("navigation")) // → "rechts" (German)
T("status.right", C("correctness"))   // → "richtig" (German)

func C

func C(context string) *TranslationContext

C creates a TranslationContext with the given context string. Chain methods to add more context:

C("navigation").Gender("masculine").Formal()

func (*TranslationContext) ContextString

func (c *TranslationContext) ContextString() string

ContextString returns the context string (nil-safe).

func (*TranslationContext) Formal

Formal sets the formality level to formal.

func (*TranslationContext) FormalityValue

func (c *TranslationContext) FormalityValue() Formality

FormalityValue returns the formality level (nil-safe).

func (*TranslationContext) GenderString

func (c *TranslationContext) GenderString() string

GenderString returns the gender hint (nil-safe).

func (*TranslationContext) Get

func (c *TranslationContext) Get(key string) any

Get retrieves a value from the extra context data.

func (*TranslationContext) Informal

func (c *TranslationContext) Informal() *TranslationContext

Informal sets the formality level to informal.

func (*TranslationContext) Set

func (c *TranslationContext) Set(key string, value any) *TranslationContext

Set adds a key-value pair to the extra context data.

func (*TranslationContext) WithFormality

func (c *TranslationContext) WithFormality(f Formality) *TranslationContext

WithFormality sets an explicit formality level.

func (*TranslationContext) WithGender

func (c *TranslationContext) WithGender(gender string) *TranslationContext

WithGender sets the grammatical gender hint.

type Translator

type Translator interface {
	T(messageID string, args ...any) string
	SetLanguage(lang string) error
	Language() string
	SetMode(m Mode)
	Mode() Mode
	SetDebug(enabled bool)
	Debug() bool
	SetFormality(f Formality)
	Formality() Formality
	Direction() TextDirection
	IsRTL() bool
	PluralCategory(n int) PluralCategory
	AvailableLanguages() []string
}

Translator defines the interface for translation services.

type VerbForms

type VerbForms struct {
	Past   string // Past tense (e.g., "deleted")
	Gerund string // Present participle (e.g., "deleting")
}

VerbForms holds irregular verb conjugations.

Jump to

Keyboard shortcuts

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