Files
profile/profile.d/lang.sh
T

281 lines
10 KiB
Bash

#!/usr/bin/env bash
# ------------------------------------------------------------------------------
# Copyright (c) 2013-2026 Geoffray Levasseur <fatalerrors@geoffray-levasseur.org>
# Protected by the BSD3 license. Please read bellow for details.
#
# * Redistribution and use in source and binary forms,
# * with or without modification, are permitted provided
# * that the following conditions are met:
# *
# * Redistributions of source code must retain the above
# * copyright notice, this list of conditions and the
# * following disclaimer.
# *
# * Redistributions in binary form must reproduce the above
# * copyright notice, this list of conditions and the following
# * disclaimer in the documentation and/or other materials
# * provided with the distribution.
# *
# * Neither the name of the copyright holder nor the names
# * of any other contributors may be used to endorse or
# * promote products derived from this software without
# * specific prior written permission.
# *
# * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
# * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
# * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# * OF SUCH DAMAGE.
# ------------------------------------------------------------------------------
# Common helpers (helpers/common.sh)
# shellcheck source=../helpers/common.sh
declare -F _profile_load_helpers >/dev/null || . "$(dirname -- "${BASH_SOURCE[0]}")/../helpers/common.sh"
load_conf lang
# ------------------------------------------------------------------------------
# check if a given locale is installed on the system.
# The comparison is tolerant to the various ways the codeset can be written
# across distributions (UTF-8, UTF8, utf8, utf-8, ISO-8859-1, iso88591, ...).
# On success the canonical name, exactly as the system spells it, is printed on
# stdout so callers can feed it verbatim to `export LANG=...` etc.
# Usage: canonical=$(locale_check <locale>) || handle-missing
locale_check()
{
if [[ "${1:-}" == -h || "${1:-}" == --help ]]; then
printf "locale_check: tell whether a locale is installed.\n"
printf "Usage: locale_check <locale>\n"
printf "Prints the name of the locale as the system spells it; status 1 if it is not installed.\n"
return 0
fi
local requested="${1:-}"
[[ -z $requested ]] && { disp W "No locale given to check."; return 1; }
# Split "lang_TERRITORY[.codeset][@modifier]" into base, codeset, modifier.
local req_body="$requested" req_cs="" req_mod=""
[[ $req_body == *@* ]] && { req_mod="${req_body##*@}"; req_body="${req_body%@*}"; }
[[ $req_body == *.* ]] && { req_cs="${req_body##*.}"; req_body="${req_body%.*}"; }
# Normalise the codeset: lowercase then strip every non-alphanumeric char so
# that UTF-8, UTF8, utf8 and utf-8 all compare equal (likewise ISO variants).
local req_cs_norm="${req_cs,,}"
req_cs_norm="${req_cs_norm//[^a-z0-9]/}"
local cand body cs mod cs_norm fallback=""
while IFS= read -r cand; do
[[ -z $cand ]] && continue
body="$cand"; cs=""; mod=""
[[ $body == *@* ]] && { mod="${body##*@}"; body="${body%@*}"; }
[[ $body == *.* ]] && { cs="${body##*.}"; body="${body%.*}"; }
cs_norm="${cs,,}"
cs_norm="${cs_norm//[^a-z0-9]/}"
# Base language and modifier must match exactly.
[[ $body == "$req_body" && $mod == "$req_mod" ]] || continue
# A requested codeset must match (normalised); if none was requested,
# accept any codeset the system provides.
[[ -z $req_cs_norm || $cs_norm == "$req_cs_norm" ]] || continue
# With no codeset requested, UTF-8 is preferred: "locale -a" may list
# an older charset first (fr_FR, fr_FR.iso88591, fr_FR.utf8). Any other
# match is kept as a fallback in case no UTF-8 variant exists.
if [[ -z $req_cs_norm && $cs_norm != "utf8" ]]; then
[[ -z $fallback ]] && fallback="$cand"
continue
fi
printf '%s\n' "$cand"
return 0
done < <(locale -a 2>/dev/null)
if [[ -n $fallback ]]; then
printf '%s\n' "$fallback"
return 0
fi
disp W "Locale '$requested' is not installed on this system."
return 1
}
export -f locale_check
# ------------------------------------------------------------------------------
# Change locale to the given one in parameter
# Usage: setlocale <locale>
setlocale()
{
local PARSED
PARSED=$(getopt -o h --long help -n 'setlocale' -- "$@")
# shellcheck disable=SC2181 # getopt return code is checked immediately after
if [[ $? -ne 0 ]]; then
disp E "Invalid options, use \"setlocale --help\" to display usage."
return 1
fi
# Restore the getopt-normalised (shell-quoted) argument list
local -a _pargs=()
_getopt_split _pargs "$PARSED"
set -- "${_pargs[@]}"
while true; do
case "$1" in
-h|--help)
printf "setlocale: Configure system environment locale variables.\n\n"
printf "Usage: setlocale <locale>\n\n"
printf "Options:\n"
printf " -h, --help Display this help screen\n"
return 0
;;
--)
shift
break
;;
*)
disp E "Invalid options, use \"setlocale --help\" to display usage."
return 1
;;
esac
done
local loc=$1
[[ -z $loc ]] && disp E "No locale specified." && return 1
# Resolve to the exact spelling installed on this system, tolerant to the
# various codeset writings (UTF-8, UTF8, utf8, utf-8, ...).
loc=$(locale_check "$loc") || return 1
# LC_ALL overrides every other variable (setc sets it), and so does any
# per-category variable inherited from the environment: drop them all so
# that the new locale really takes effect.
unset LC_ALL LC_ADDRESS LC_IDENTIFICATION LC_MEASUREMENT LC_NAME \
LC_PAPER LC_TELEPHONE
export LANG=$loc
export LC_MESSAGES=$loc
export LC_TIME=$loc
export LC_NUMERIC=$loc
export LC_MONETARY=$loc
export LC_COLLATE=$loc
export LC_CTYPE=$loc
disp I "Locale set to $loc."
}
export -f setlocale
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# Special case : change locale to C standard
# Usage: setc
setc()
{
if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
printf "setc: Set the console locale to the standard C (POSIX) locale.\n"
printf "Usage: setc\n"
return 0
fi
# Locale definitions
export LC_ALL=C
export LANG=C
disp I "Locale changed to standard C (POSIX)."
}
export -f setc
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# Build dynamic locale shortcuts from SET_LOCALE
# Expected format:
# SET_LOCALE="fr:fr_FR.UTF-8,us:en_US.UTF-8,es:es_ES.UTF-8"
# This creates functions:
# setfr, setus, setes, ...
build_locale_shortcuts()
{
local cfg="${SET_LOCALE:-}"
local item="" alias="" loc="" fname=""
local -a locale_items=()
[[ -z "$cfg" ]] && return 0
IFS=',' read -r -a locale_items <<< "$cfg"
for item in "${locale_items[@]}"; do
# Trim surrounding spaces
item="${item#"${item%%[![:space:]]*}"}"
item="${item%"${item##*[![:space:]]}"}"
[[ -z "$item" ]] && continue
if [[ "$item" != *:* ]]; then
disp W "Ignoring invalid SET_LOCALE entry: '$item' (expected alias:locale)."
continue
fi
alias="${item%%:*}"
loc="${item#*:}"
# Trim alias/locale spaces
alias="${alias#"${alias%%[![:space:]]*}"}"
alias="${alias%"${alias##*[![:space:]]}"}"
loc="${loc#"${loc%%[![:space:]]*}"}"
loc="${loc%"${loc##*[![:space:]]}"}"
# Validate alias for safe function names
if [[ ! "$alias" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]]; then
disp W "Ignoring unsafe locale alias '$alias' in SET_LOCALE."
continue
fi
[[ -z "$loc" ]] && {
disp W "Ignoring empty locale for alias '$alias' in SET_LOCALE."
continue
}
fname="set${alias}"
# The generated function must never replace the real commands
if [[ "$fname" == "setlocale" || "$fname" == "setc" ]]; then
disp W "Ignoring locale alias '$alias' in SET_LOCALE: '$fname' is a profile command."
continue
fi
# Collision warning. A function that already calls setlocale is one of
# these shortcuts, typically inherited through the environment from a
# parent shell that loaded the profile: replacing it is not worth a
# warning at every nested shell.
if declare -F "$fname" >/dev/null 2>&1 && \
! declare -f "$fname" 2>/dev/null | grep -q 'setlocale'; then
disp W "Overriding existing function '$fname'."
fi
# Build function dynamically. %q quotes the locale so that nothing in
# the configuration value can be interpreted by eval. The shortcut
# answers --help without changing anything ("help <command>" calls it).
local qloc
printf -v qloc '%q' "$loc"
eval "${fname}() {
if [[ \"\${1:-}\" == -h || \"\${1:-}\" == --help ]]; then
printf '%s: switch the console locale (see setlocale --help).\n' \"\${FUNCNAME[0]}\"
return 0
fi
setlocale ${qloc}
}"
# shellcheck disable=SC2163
export -f "$fname"
done
unset cfg item alias loc fname locale_items qloc
}
# ------------------------------------------------------------------------------
# Dynamically build locale functions based on SET_LOCALE configuration
build_locale_shortcuts
# ------------------------------------------------------------------------------
# EOF