hledger-lib
Safe HaskellNone
LanguageGHC2021

Hledger.Utils.I18n

Description

Internationalization support for hledger's user-facing output.

Translations live in catalogs in the gettext PO file format, which the usual translator tools (Poedit, Weblate, Lokalize) understand. Built-in catalogs are embedded in the executables; a user can override one, or add a language, with a file in their hledger config directory (see translationsOverrideDir). Lookups are pure functions of a Translations value, so there is no process-global locale state, and hledger-web can serve a different language to each request.

Conventions:

  • The msgid is the English text. A missing or empty translation falls back to it, and noTranslations is the identity, so English output is unaffected by this machinery.
  • Parameters are {name} placeholders substituted after lookup (trf), never printf formats: a translation can not crash the program.
  • Short words used in more than one sense carry a context (trc).
  • Use tr (or trc, trf) where text is displayed and a Translations value is at hand, usually from the report options. Use i18n (or i18nc) only to mark a literal that is stored earlier, in data such as a report spec or a menu item, before any catalog is available; it is then translated with tr at display time. Both forms are what the catalog extraction tool looks for.
  • A malformed catalog is reported as a warning and ignored.

This module is experimental and its API may change.

Synopsis

Translations

data Translations Source #

A set of translations for one language, looked up by English text (optionally qualified by a context, see trc).

Constructors

Translations 

Fields

  • trLang :: Text

    language tag, eg "de", "pt-BR", "zh-Hans"

  • trMessages :: Map Text Text

    msgid (or "contextx04msgid") -> translation

  • trPlurals :: Map Text [Text]

    singular msgid -> one translation per plural form

  • trPluralForms :: Maybe PluralForms

    this language's plural rule, from the catalog header

Instances

Instances details
Show Translations Source #

Shows only the language, so that option dumps stay readable.

Instance details

Defined in Hledger.Utils.I18n

Methods

showsPrec :: Int -> Translations -> ShowS

show :: Translations -> String

showList :: [Translations] -> ShowS

data PluralForms Source #

A language's plural rule: how many forms it has, and which form a count selects.

Constructors

PluralForms 

Fields

noTranslations :: Translations Source #

English: every lookup returns its argument.

tr :: Translations -> Text -> Text Source #

Translate this English text, or return it unchanged if there is no translation.

trc :: Translations -> Text -> Text -> Text Source #

Like tr, but for a short text that is used in more than one sense. The context (eg "column heading") disambiguates it in the catalog.

trf :: Translations -> Text -> [(Text, Text)] -> Text Source #

Translate this English template, then fill in its {name} placeholders. Placeholders that are not given stay as they are. Values are inserted verbatim, without being scanned for placeholders themselves.

trn :: Translations -> Int -> Text -> Text -> Text Source #

Translate a count phrase, choosing the plural form this language uses for the count, then fill in the {n} placeholder. The two English forms are the msgid and msgid_plural; without a translation, the singular is used for 1 and the plural otherwise.

i18n :: Text -> Text Source #

Mark an English literal that is stored now, in data such as a report spec or a menu item, and translated later by tr at the point where it is displayed. This is the identity; its purpose is to make the catalog extraction tool collect the literal. (Like gettext's N_.) Where a Translations value is already at hand, use tr directly instead.

i18nc :: Text -> Text -> Text Source #

Like i18n, for a literal that will be translated with a context by trc.

trTimeLocale :: Translations -> TimeLocale Source #

The default time locale with month names translated, for formatting dates. The names are looked up with contexts "month" (full name) and "month abbrev" (short name, used as a column heading).

translationsForLangOption :: Maybe String -> IO Translations Source #

Choose translations according to the value of a --lang option. No option means English, without reading any files. "auto" follows the LANGUAGE, LC_ALL, LC_MESSAGES and LANG environment variables (see langPrefsFromEnv), falling back to English. Anything else is a language tag, which must have a catalog, built-in or in translationsOverrideDir; otherwise a usage error is raised.

substitutePlaceholders :: [(Text, Text)] -> Text -> Text Source #

Replace each {name} in the text with the value given for that name. Names not given are left in place; values are not scanned again.

placeholders :: Text -> Set Text Source #

The placeholder names in a template.

Catalogs

parsePo :: String -> Text -> Text -> Either String Translations Source #

Parse a catalog in PO format. The arguments are a name for error messages, the language tag to record, and the file's content.

Handles what translator tools produce: the header entry, translator and extracted comments, references, flags, previous-msgid comments, obsolete entries, contexts, plural forms, multi-line strings, C escapes, a byte order mark and CRLF line endings. Entries flagged fuzzy are skipped (except that the header's Plural-Forms is still used), and an empty translation counts as untranslated. Duplicate entries and a non-UTF-8 charset are errors.

mergeTranslations :: Translations -> Translations -> Translations Source #

Merge two catalogs; entries in the second take precedence.

builtinTranslations :: Map Text Translations Source #

The built-in catalogs, parsed. A catalog that fails to parse is omitted; the unit tests ensure that does not happen in a release.

builtinLanguages :: [Text] Source #

The languages with a built-in catalog, plus English.

availableLanguages :: IO [Text] Source #

The language tags for which a catalog exists, built-in or in the user's override directory. Always includes "en".

Listing the built-in languages parses the built-in catalogs (whichever of them parse are the ones available), once per process. With --debug, reports how long that took.

loadTranslations :: Text -> IO Translations Source #

Load the translations for this language tag (which should be one returned by availableLanguages): the built-in catalog if any, with the user's catalog merged over it if any. With --debug, reports what was loaded, its size, and how long it took.

loadAllTranslations :: IO (Map Text Translations) Source #

Load the translations for every available language.

translationsOverrideDir :: IO FilePath Source #

The directory where a user can put a translation catalog named LANG.po, to override a built-in one or to add a language: the locale subdirectory of hledger's config directory (~.confighledger/locale on unix, %APPDATA%\hledger\locale on windows).

startingCatalog :: Text -> Either String (Text, Bool, ByteString) Source #

The catalog to start translating a language from, for --write-lang: the language's canonical tag, whether the catalog is a built-in one, and its content. That is the built-in catalog for the language if there is one (found as --lang finds it, so de-AT gives de), otherwise the template, with its header filled in so that hledger can use it straight away. English, or something that is not a language tag, gives an error message.

writeStartingCatalog :: Text -> IO (Either String (FilePath, Text, Bool)) Source #

Write the catalog to start translating a language from (see startingCatalog) into translationsOverrideDir, where --lang will find it, returning its path, tag and whether it is a built-in catalog. If the user has a catalog for that language already, it is left alone and an error message returned.

Language tags

isValidLangTag :: Text -> Bool Source #

Is this a well-formed language tag, safe to use in a cookie ? Two or three letters, then optional subtags of one to eight letters or digits, separated by hyphens.

normalizeLangTag :: Text -> Maybe Text Source #

Convert a language tag as found in the environment or an HTTP header to canonical form, or Nothing if it does not name a language.

Handles POSIX locale names (de_DE.UTF-8@euro becomes de-DE; C, POSIX and an empty value become Nothing), Accept-Language quality suffixes, and letter case (pt-br becomes pt-BR). Chinese region tags map to the script tags zh-Hans and zh-Hant, and Norwegian's no to nb.

langTagCandidates :: Text -> [Text] Source #

The tags to try for a language tag, most specific first: the tag itself, then with subtags dropped from the right.

shortLangTag :: Text -> Text Source #

The shortest spelling of a language tag that selects it, for showing to users: the tag with subtags dropped from the right, as far as the result still normalizes to the tag. Eg zh-Hans is shown as zh, since zh means zh-Hans; but pt-BR stays pt-BR, since pt is a different language tag.

resolveLang :: [Text] -> [Text] -> Maybe Text Source #

Given the available language tags and a list of preferred tags in order of preference (raw, as from the environment or a browser), choose the first available one. Each preference is tried with its subtags dropped from the right before moving on to the next, so that de-CH followed by en chooses de over en when only de is available.

langPrefsFromEnv :: [(String, String)] -> [Text] Source #

The languages a user prefers, in order, according to these environment variables, following gettext: the effective locale is LC_ALL, else LC_MESSAGES, else LANG; if that is unset or C/POSIX the result is empty (English) and LANGUAGE is ignored; otherwise the colon-separated LANGUAGE list is consulted first, then the locale.

Plural forms

parsePluralForms :: Text -> Maybe PluralForms Source #

Parse a PO header's Plural-Forms value, eg "nplurals=2; plural=(n != 1);". The plural expression is the C expression subset gettext allows: n, integers, parentheses, !, %, comparisons, &&, ||, and ?:.

Tests