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 ¶
- Variables
- func ActionFailed(verb, subject string) string
- func ActionResult(verb, subject string) string
- func AddHandler(h KeyHandler)
- func Article(word string) string
- func CurrentLanguage() string
- func FormatAgo(count int, unit string) string
- func FormatBytes(bytes int64) string
- func FormatDecimal(f float64) string
- func FormatDecimalN(f float64, decimals int) string
- func FormatNumber(n int64) string
- func FormatOrdinal(n int) string
- func FormatPercent(f float64) string
- func Gerund(verb string) string
- func Init() error
- func IsRTL() bool
- func IsRTLLanguage(lang string) bool
- func Label(word string) string
- func N(format string, value any) string
- func OnMissingKey(h MissingKeyHandler)
- func PastTense(verb string) string
- func PluralForm(noun string) string
- func Pluralize(noun string, count int) string
- func PrependHandler(h KeyHandler)
- func Progress(verb string) string
- func ProgressSubject(verb, subject string) string
- func Quote(s string) string
- func Raw(messageID string, args ...any) string
- func RegisterLocales(fsys fs.FS, dir string)
- func RunHandlerChain(handlers []KeyHandler, key string, args []any, fallback func() string) string
- func SetDebug(enabled bool)
- func SetDefault(s *Service)
- func SetFormality(f Formality)
- func SetGrammarData(lang string, data *GrammarData)
- func SetLanguage(lang string) error
- func SetMode(m Mode)
- func T(messageID string, args ...any) string
- func TemplateFuncs() template.FuncMap
- func TimeAgo(t time.Time) string
- func Title(s string) string
- type ArticleForms
- type Composed
- type CountHandler
- type DoneHandler
- type FSLoader
- type FailHandler
- type Formality
- type GrammarData
- type GrammaticalGender
- type Intent
- type IntentMeta
- type KeyHandler
- type LabelHandler
- type Loader
- type Message
- type MissingKey
- type MissingKeyHandler
- type Mode
- type NounForms
- type NumberFormat
- type NumericHandler
- type Option
- type PluralCategory
- type PluralRule
- type ProgressHandler
- type PunctuationRules
- type Service
- func (s *Service) AddHandler(h KeyHandler)
- func (s *Service) AddMessages(lang string, messages map[string]string)
- func (s *Service) AvailableLanguages() []string
- func (s *Service) ClearHandlers()
- func (s *Service) Debug() bool
- func (s *Service) Direction() TextDirection
- func (s *Service) Formality() Formality
- func (s *Service) Handlers() []KeyHandler
- func (s *Service) IsRTL() bool
- func (s *Service) Language() string
- func (s *Service) LoadFS(fsys fs.FS, dir string) error
- func (s *Service) Mode() Mode
- func (s *Service) PluralCategory(n int) PluralCategory
- func (s *Service) PrependHandler(h KeyHandler)
- func (s *Service) Raw(messageID string, args ...any) string
- func (s *Service) SetDebug(enabled bool)
- func (s *Service) SetFormality(f Formality)
- func (s *Service) SetLanguage(lang string) error
- func (s *Service) SetMode(m Mode)
- func (s *Service) T(messageID string, args ...any) string
- type Subject
- func (s *Subject) Count(n int) *Subject
- func (s *Subject) CountInt() int
- func (s *Subject) CountString() string
- func (s *Subject) Formal() *Subject
- func (s *Subject) Formality(f Formality) *Subject
- func (s *Subject) FormalityString() string
- func (s *Subject) Gender(g string) *Subject
- func (s *Subject) GenderString() string
- func (s *Subject) In(location string) *Subject
- func (s *Subject) Informal() *Subject
- func (s *Subject) IsFormal() bool
- func (s *Subject) IsInformal() bool
- func (s *Subject) IsPlural() bool
- func (s *Subject) LocationString() string
- func (s *Subject) NounString() string
- func (s *Subject) String() string
- type TextDirection
- type TranslationContext
- func (c *TranslationContext) ContextString() string
- func (c *TranslationContext) Formal() *TranslationContext
- func (c *TranslationContext) FormalityValue() Formality
- func (c *TranslationContext) GenderString() string
- func (c *TranslationContext) Get(key string) any
- func (c *TranslationContext) Informal() *TranslationContext
- func (c *TranslationContext) Set(key string, value any) *TranslationContext
- func (c *TranslationContext) WithFormality(f Formality) *TranslationContext
- func (c *TranslationContext) WithGender(gender string) *TranslationContext
- type Translator
- type VerbForms
Constants ¶
This section is empty.
Variables ¶
var ErrServiceNotInitialized = errors.New("i18n: service not initialized")
ErrServiceNotInitialized is returned when the i18n service is not initialized.
Functions ¶
func ActionFailed ¶
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 ¶
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 ¶
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 ¶
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 ¶
FormatBytes formats bytes as human-readable size.
FormatBytes(1536) // "1.5 KB" FormatBytes(1536000) // "1.5 MB" FormatBytes(1536000000) // "1.4 GB"
func FormatDecimal ¶
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 ¶
FormatDecimalN formats a float with N decimal places.
FormatDecimalN(1234.5678, 3) // "1,234.568" (en)
func FormatNumber ¶
FormatNumber formats an integer with locale-specific thousands separators.
FormatNumber(1234567) // "1,234,567" (en) or "1.234.567" (de)
func FormatOrdinal ¶
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 ¶
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 ¶
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 IsRTLLanguage ¶
IsRTLLanguage returns true if the language code uses right-to-left text.
func Label ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 Raw ¶
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 ¶
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 ¶
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 ¶
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 ¶
TemplateFuncs returns the template.FuncMap with all grammar functions. Use this to add grammar helpers to your templates.
tmpl := template.New("").Funcs(i18n.TemplateFuncs())
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 ¶
NewFSLoader creates a loader for the given filesystem and directory.
func (*FSLoader) Languages ¶
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 ¶
LanguagesErr returns any error that occurred during Languages() scan. Returns nil if the scan succeeded.
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).
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.
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.
func CurrentMode ¶
func CurrentMode() Mode
CurrentMode returns the current translation mode from the default service.
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 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 ¶
WithFallback sets the fallback language for missing translations.
func WithFormality ¶
WithFormality sets the default formality level.
func WithHandlers ¶
func WithHandlers(handlers ...KeyHandler) Option
WithHandlers sets custom handlers (replaces default handlers).
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 NewWithLoader ¶
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 ¶
AddMessages adds messages for a language at runtime.
func (*Service) AvailableLanguages ¶
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) Direction ¶
func (s *Service) Direction() TextDirection
Direction returns the text direction for the current language.
func (*Service) Handlers ¶
func (s *Service) Handlers() []KeyHandler
Handlers returns a copy of the current handler chain.
func (*Service) IsRTL ¶
IsRTL returns true if the current language uses right-to-left text direction.
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 ¶
Raw is the raw translation helper without i18n.* namespace magic. Use T() for smart i18n.* handling, Raw() for direct key lookup.
func (*Service) SetDebug ¶
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 ¶
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 ¶
SetLanguage sets the language for translations.
func (*Service) T ¶
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 ¶
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 ¶
Count sets the count for pluralization. Used to determine singular/plural forms in templates.
S("file", files).Count(len(files))
func (*Subject) CountString ¶
CountString returns the count as a string.
func (*Subject) Formal ¶
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 ¶
Formality sets the formality level explicitly.
S("user", name).Formality(FormalityFormal)
func (*Subject) FormalityString ¶
FormalityString returns the formality level as a string. Returns "neutral" if not explicitly set.
func (*Subject) Gender ¶
Gender sets the grammatical gender for languages that require it. Common values: "masculine", "feminine", "neuter"
S("user", user).Gender("female")
func (*Subject) GenderString ¶
GenderString returns the grammatical gender.
func (*Subject) In ¶
In sets the location context for the subject. Used in templates to provide spatial context.
S("file", "config.yaml").In("workspace")
func (*Subject) Informal ¶
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) IsInformal ¶
IsInformal returns true if informal address should be used.
func (*Subject) LocationString ¶
LocationString returns the location context.
func (*Subject) NounString ¶
NounString returns the noun type.
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 ¶
func (c *TranslationContext) Formal() *TranslationContext
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.