Update intllib

master
Wuzzy 2016-11-09 05:33:22 +01:00
parent c0241c3999
commit 096080d0db
9 changed files with 521 additions and 118 deletions

View File

@ -0,0 +1,136 @@
# Biblioteca de Internacionalización para Minetest
Por Diego Martínez (kaeza).
Lanzada bajo WTFPL.
Éste mod es un intento de proveer soporte para internacionalización para otros mods
(lo cual Minetest carece actualmente).
## Cómo usar
### Para usuarios finales
Para usar éste mod, simplemente [instálalo](http://wiki.minetest.net/Installing_Mods)
y habilítalo en la interfaz.
Éste mod intenta detectar el idioma del usuario, pero ya que no existe una solución
portable para hacerlo, éste intenta varias alternativas, y utiliza la primera
encontrada:
* Opción `language` en `minetest.conf`.
* Si ésta no está definida, usa la variable de entorno `LANG` (ésta está
siempre definida en SOs como Unix).
* Si todo falla, usa `en` (lo cual básicamente significa textos sin traducir).
En todo caso, el resultado final debe ser el In any case, the end result should be the
[Código de Idioma ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes)
del idioma deseado. Tenga en cuenta tambien que (de momento) solo los dos primeros
caracteres son usados, así que por ejemplo, las opciones `de_DE.UTF-8`, `de_DE`,
y `de` son iguales.
Algunos códigos comúnes: `es` para Español, `pt` para Portugués, `fr` para Francés,
`it` para Italiano, `de` para Aleman.
### Para desarrolladores
Para habilitar funcionalidad en tu mod, copia el siguiente fragmento de código y pégalo
al comienzo de tus archivos fuente:
```lua
-- Boilerplate to support localized strings if intllib mod is installed.
local S
if minetest.get_modpath("intllib") then
S = intllib.Getter()
else
-- Si no requieres patrones de reemplazo (@1, @2, etc) usa ésto:
S = function(s) return s end
-- Si requieres patrones de reemplazo, pero no escapes, usa ésto:
S = function(s,a,...)a={a,...}return s:gsub("@(%d+)",function(n)return a[tonumber(n)]end)end
-- Usa ésto si necesitas funcionalidad completa:
S = function(s,a,...)if a==nil then return s end a={a,...}return s:gsub("(@?)@(%(?)(%d+)(%)?)",function(e,o,n,c)if e==""then return a[tonumber(n)]..(o==""and c or"")else return"@"..o..n..c end end) end
end
```
Tambien necesitarás depender opcionalmente de intllib. Para hacerlo, añade `intllib?`
a tu archivo `depends.txt`. Ten en cuenta tambien que si intllib no está instalado,
la función `S` es definida para regresar la cadena sin cambios. Ésto se hace para
evitar la necesidad de llenar tu código con montones de `if`s (o similar) para verificar
que la biblioteca está instalada.
Luego, para cada cadena de texto a traducir en tu código, usa la función `S`
(definida en el fragmento de arriba) para regresar la cadena traducida. Por ejemplo:
```lua
minetest.register_node("mimod:minodo", {
-- Cadena simple:
description = S("My Fabulous Node"),
-- Cadena con patrones de reemplazo:
description = S("@1 Car", "Blue"),
-- ...
})
```
Nota: Las cadenas en el código fuente por lo general deben estar en ingles ya que
es el idioma que más se habla. Es perfectamente posible especificar las cadenas
fuente en español y proveer una traducción al ingles, pero no se recomienda.
Luego, crea un directorio llamado `locale` dentro del directorio de tu mod, y crea
un archivo "plantilla" (llamado `template.txt` por lo general) con todas las cadenas
a traducir (ver *Formato de archivo de traducciones* más abajo). Los traductores
traducirán las cadenas en éste archivo para agregar idiomas a tu mod.
### Para traductores
Para traducir un mod que tenga soporte para intllib al idioma deseado, copia el
archivo `locale/template.txt` a `locale/IDIOMA.txt` (donde `IDIOMA` es el
[Código de Idioma ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes)
de tu idioma (`es` para español).
Abre el archivo en tu editor favorito, y traduce cada línea colocando el texto
traducido luego del signo de igualdad.
Ver *Formato de archivo de traducciones* más abajo.
## Formato de archivo de traducciones
He aquí un ejemplo de archivo de idioma para el español (`es.txt`):
```cfg
# Un comentario.
# Otro comentario.
Ésta línea es ignorada porque no tiene un signo de igualdad.
Hello, World! = Hola, Mundo!
String with\nnewlines = Cadena con\nsaltos de linea
String with an \= equals sign = Cadena con un signo de \= igualdad
```
Archivos de idioma (o traducción) son archivos de texto sin formato que consisten de
líneas con el formato `texto fuente = texto traducido`. El archivo debe ubicarse en el
subdirectorio `locale` del mod, y su nombre debe ser las dos letras del
[Código de Idioma ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes)
del lenguaje al cual se desea traducir.
Los archivos deben usar la codificación UTF-8.
Las líneas que comienzan en el símbolo numeral (`#`) son comentarios y son ignoradas
por el lector. Tenga en cuenta que los comentarios terminan al final de la línea;
no hay soporte para comentarios multilínea. Las líneas que no contengan un signo
de igualdad (`=`) tambien son ignoradas.
## Palabras finales
Gracias por leer hasta aquí.
Si tienes algún comentario/sugerencia, por favor publica en el
[tema en los foros](https://forum.minetest.net/viewtopic.php?id=4929). Para
reportar errores, usa el [rastreador](https://github.com/minetest-mods/intllib/issues/new)
en Github.
¡Que se hagan las traducciones! :P
\--
Suyo,
Kaeza

View File

@ -0,0 +1,142 @@
# Lib de Internacionalização para Minetest
Por Diego Martínez (kaeza).
Lançado como WTFPL.
Este mod é uma tentativa de fornecer suporte de internacionalização para mods
(algo que Minetest atualmente carece).
## Como usar
### Para usuários finais
Para usar este mod, basta [instalá-lo] (http://wiki.minetest.net/Installing_Mods)
e habilita-lo na GUI.
O modificador tenta detectar o idioma do usuário, mas já que não há atualmente
nenhuma maneira portátil para fazer isso, ele tenta várias alternativas, e usa
o primeiro encontrado:
* `language` definido em `minetest.conf`.
* Se isso não for definido, ele usa a variável de ambiente `LANG` (isso
é sempre definido em SO's Unix-like).
* Se todos falharem, usa `en` (que basicamente significa string não traduzidas).
Em todo caso, o resultado final deve ser um
[Código de Idioma ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes)
do idioma desejado. Observe também que (atualmente) somente até os dois primeiros
caracteres são usados, assim, por exemplo, os códigos `pt_BR.UTF-8`, `pt_BR`, e `pt`
são todos iguais.
Alguns códigos comuns são `es` para o espanhol, `pt` para Português, `fr` para o
francês, `It` para o italiano, `de` Alemão.
### Para desenvolvedores de mods
A fim de habilitá-lo para o seu mod, copie o seguinte trecho de código e cole no
início de seu(s) arquivo(s) fonte(s):
```lua
-- Clichê para apoiar cadeias localizadas se mod intllib está instalado.
local S
if minetest.get_modpath("intllib") then
S = intllib.Getter()
else
-- Se você não usar inserções (@1, @2, etc) você pode usar este:
S = function(s) return s end
-- Se você usar inserções, mas não usar escapes de inserção (\=, \n, etc) isso vai funcionar:
S = function(s,a,...)a={a,...}return s:gsub("@(%d+)",function(n)return a[tonumber(n)]end)end
-- Use isso se você precisar de funcionalidade total:
S = function(s,a,...)if a==nil then return s end a={a,...}return s:gsub("(@?)@(%(?)(%d+)(%)?)",function(e,o,n,c)if e==""then return a[tonumber(n)]..(o==""and c or"")else return"@"..o..n..c end end) end
end
```
Você também vai precisar depender opcionalmente do mod intllib, adicionando "intllib?"
em uma linha vazia de seu depends.txt. Observe também que se intllib não estiver
instalado, a função S() é definido para retornar a string inalterada. Isto é feito
para que você não tenha que usar dezenas de 'if's (ou de estruturas semelhantes)
para verificar se a lib está realmente instalada.
Em seguida, para cada string "traduzível" em suas fontes, use a função S()
(definida no trecho anterior) para retornar uma string traduzida. Por exemplo:
```lua
minetest.register_node("mymod:meunode", {
-- String simples
description = S("Meu Node Fabuloso"),
-- String com inserção de variáveis
description = S("@1 Car", "Blue"),
-- ...
})
```
Em seguida, crie um diretório chamado `locale` dentro do diretório do seu mod,
e crie um arquivo modelo (por convenção, nomeado `template.txt`) contendo todas
as strings traduzíveis (veja *Formato de arquivo Locale* abaixo). Tradutores
irão traduzir as strings neste arquivo para adicionar idiomas ao seu mod.
### Para tradutores
Para traduzir um mod intllib-apoiado para o idioma desejado, copie o
arquivo `locale/template.txt` para`locale/IDIOMA.txt` (onde `IDIOMA` é o
[Código de Idioma ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes)
do idioma desejado.
Abra o novo arquivo no seu editor favorito, e traduza cada linha colocando
o texto traduzido após o sinal de igual.
Veja *Formato de arquivo Locale* abaixo para mais informações sobre o formato de arquivo.
## Formato de arquivo Locale
Aqui está um exemplo de um arquivo locale Português (`pt.txt`):
```cfg
# Um comentário.
# Outro Comentário.
Esta linha é ignorada, uma vez que não tem sinal de igual.
Hello, World! = Ola, Mundo!
String with\nnewlines = String com\nsaltos de linha
String with an \= equals sign = String com sinal de \= igual
```
Locale (ou tradução) são arquivos de texto simples que consistem em linhas da
forma `texto de origem = texto traduzido`. O arquivo deve residir no subdiretório
`locale` do mod, e deve ser nomeado com as duas letras do
[Código de Idioma ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes)
do idioma que deseja apoiar.
Os arquivos de tradução devem usar a codificação UTF-8.
As linhas que começam com um sinal de libra (#) são comentários e são efetivamente
ignorados pelo interpretador. Note que comentários duram apenas até o fim da linha;
não há suporte para comentários de várias linhas. Linhas sem um sinal de igual são
ignoradas também.
Caracteres considerados "especiais" podem ser "escapados" para que sejam
interpretados corretamente. Existem várias sequências de escape que podem ser usadas:
* Qualquer `#` ou `=` pode ser escapado para ser interpretado corretamente.
A sequência `\#` é útil se o texto de origem começa com `#`.
* Sequências de escape comuns são `\n` e` \t`, ou seja, de nova linha e
guia horizontal, respectivamente.
* A sequência de escape especial `\s` representa o caractere de espaço. isto
pode ser útil principalmente para adicionar espaços antes ou depois de fonte ou
textos traduzida, uma vez que estes espaços seriam removidos de outro modo.
## Palavras Finais
Obrigado por ler até este ponto.
Se você tiver quaisquer comentários/sugestões, por favor poste no
[Tópico do fórum](https://forum.minetest.net/viewtopic.php?id=4929) (em inglês). Para
relatórios de bugs, use o [Rastreador de bugs](https://github.com/minetest-mods/intllib/issues/new)
no Github.
Haja textos traduzidos! :P
\--
Atenciosamente,
Kaeza

143
mods/intllib/README.md Normal file
View File

@ -0,0 +1,143 @@
# Internationalization Lib for Minetest
By Diego Martínez (kaeza).
Released as WTFPL.
This mod is an attempt at providing internationalization support for mods
(something Minetest currently lacks).
## How to use
### For end users
To use this mod, just [install it](http://wiki.minetest.net/Installing_Mods)
and enable it in the GUI.
The mod tries to detect the user's language, but since there's currently no
portable way to do this, it tries several alternatives, and uses the first one
found:
* `language` setting in `minetest.conf`.
* If that's not set, it uses the `LANG` environment variable (this is
always set on Unix-like OSes).
* If all else fails, uses `en` (which basically means untranslated strings).
In any case, the end result should be the
[ISO 639-1 Language Code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes)
of the desired language. Also note that (currently) only up to the first two
characters are used, so for example, the settings `de_DE.UTF-8`, `de_DE`,
and `de` are all equal.
Some common codes are `es` for Spanish, `pt` for Portuguese, `fr` for French,
`it` for Italian, `de` for German.
### For mod developers
In order to enable it for your mod, copy the following code snippet and paste
it at the beginning of your source file(s):
```lua
-- Boilerplate to support localized strings if intllib mod is installed.
local S
if minetest.get_modpath("intllib") then
S = intllib.Getter()
else
-- If you don't use insertions (@1, @2, etc) you can use this:
S = function(s) return s end
-- If you use insertions, but not insertion escapes this will work:
S = function(s,a,...)a={a,...}return s:gsub("@(%d+)",function(n)return a[tonumber(n)]end)end
-- Use this if you require full functionality
S = function(s,a,...)if a==nil then return s end a={a,...}return s:gsub("(@?)@(%(?)(%d+)(%)?)",function(e,o,n,c)if e==""then return a[tonumber(n)]..(o==""and c or"")else return"@"..o..n..c end end) end
end
```
You will also need to optionally depend on intllib, to do so add `intllib?` to
an empty line in your `depends.txt`. Also note that if intllib is not installed,
the `S` function is defined so it returns the string unchanged. This is done
so you don't have to sprinkle tons of `if`s (or similar constructs) to check
if the lib is actually installed.
Next, for each translatable string in your sources, use the `S` function
(defined in the snippet) to return the translated string. For example:
```lua
minetest.register_node("mymod:mynode", {
-- Simple string:
description = S("My Fabulous Node"),
-- String with insertions:
description = S("@1 Car", "Blue"),
-- ...
})
```
Then, you create a `locale` directory inside your mod directory, and create
a "template" file (by convention, named `template.txt`) with all the
translatable strings (see *Locale file format* below). Translators will
translate the strings in this file to add languages to your mod.
### For translators
To translate an intllib-supporting mod to your desired language, copy the
`locale/template.txt` file to `locale/LANGUAGE.txt` (where `LANGUAGE` is the
[ISO 639-1 Language Code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes)
of your language.
Open up the new file in your favorite editor, and translate each line putting
the translated text after the equals sign.
See *Locale file format* below for more information about the file format.
## Locale file format
Here's an example for a Spanish locale file (`es.txt`):
```cfg
# A comment.
# Another comment.
This line is ignored since it has no equals sign.
Hello, World! = Hola, Mundo!
String with\nnewlines = Cadena con\nsaltos de linea
String with an \= equals sign = Cadena con un signo de \= igualdad
```
Locale (or translation) files are plain text files consisting of lines of the
form `source text = translated text`. The file must reside in the mod's `locale`
subdirectory, and must be named after the two-letter
[ISO 639-1 Language Code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes)
of the language you want to support.
The translation files should use the UTF-8 encoding.
Lines beginning with a pound sign are comments and are effectively ignored
by the reader. Note that comments only span until the end of the line;
there's no support for multiline comments. Lines without an equals sign are
also ignored.
Characters that are considered "special" can be "escaped" so they are taken
literally. There are also several escape sequences that can be used:
* Any of `#`, `=` can be escaped to take them literally. The `\#`
sequence is useful if your source text begins with `#`.
* The common escape sequences `\n` and `\t`, meaning newline and
horizontal tab respectively.
* The special `\s` escape sequence represents the space character. It
is mainly useful to add leading or trailing spaces to source or
translated texts, as these spaces would be removed otherwise.
## Final words
Thanks for reading up to this point.
Should you have any comments/suggestions, please post them in the
[forum topic](https://forum.minetest.net/viewtopic.php?id=4929). For bug
reports, use the [bug tracker](https://github.com/minetest-mods/intllib/issues/new)
on Github.
Let there be translated texts! :P
\--
Yours Truly,
Kaeza

View File

@ -1,76 +0,0 @@
Internationalization Lib for Minetest
By Diego Martínez (a.k.a. "Kaeza").
Released as WTFPL.
This mod is an attempt at providing internationalization support for mods
(something Minetest currently lacks).
How do I use it?
In order to enable it for your mod, copy the following code snippet and paste
it at the beginning of your source file(s):
-- Boilerplate to support localized strings if intllib mod is installed.
local S
if intllib then
S = intllib.Getter()
else
S = function(s) return s end
end
You will also need to optionally depend on intllib, to do so add "intllib?" to
a empty line in your depends.txt. Also note that if intllib is not installed,
the S() function is defined so it returns the string unchanged. This is done
so you don't have to sprinkle tons of 'if's (or similar constructs) to check
if the lib is actually installed.
Next, for each "translatable" string in your sources, use the S() function
(defined in the snippet) to return the translated string. For example:
minetest.register_node("mymod:mynode", {
description = S("My Fabulous Node"),
<...>
})
Then, you create a `locale' directory inside your mod directory, with files
named after the two-letter ISO Language Code of the languages you want to
support. Here's an example for a Spanish locale file (`es.txt'):
# Lines beginning with a pound sign are comments and are effectively ignored
# by the reader. Note that comments only span until the end of the line;
# there's no support for multiline comments.
Hello, World! = Hola, Mundo!
String with\nnewlines = Cadena con\nsaltos de linea
String with an \= equals sign = Cadena con un signo de \= igualdad
Since there's currently no portable way to detect the language, this library
tries several alternatives, and uses the first one found:
- `language' setting in `minetest.conf'
- `LANG' environment variable (this is always set on Unix-like OSes).
- Default of "en".
Note that in any case only up to the first two characters are used, so for
example, the settings "de_DE.UTF-8", "de_DE", and "de" are all equal.
Windows users have no `LANG' environment variable by default. To add it, do
the following:
- Click Start->Settings->Control Panel.
- Start the "System" applet.
- Click on the "Advanced" tab.
- Click on the "Environment variables" button
- Click "New".
- Type "LANG" (without quotes) as name and the language code as value.
- Click OK until all dialogs are closed.
Alternatively for all platforms, if you don't want to modify system settings,
you may add the following line to your `minetest.conf' file:
language = <language code>
Also note that there are some problems with using accented, and in general
non-latin characters in strings. Until a fix is found, please limit yourself
to using only US-ASCII characters.
Thanks for reading up to this point.
Should you have any comments/suggestions, please post them in the forum topic.
Let there be translated texts! :P
--
Yours Truly,
Kaeza

View File

@ -0,0 +1,3 @@
Internationalization library.
This mod provides a way to internationalize/localize mods to other languages in an easy way.
See the README file for details.

View File

@ -1,59 +1,90 @@
-- Support the old multi-load method
if not minetest.global_exists(intllib) then intllib = {} end
-- Old multi-load method compatibility
if rawget(_G, "intllib") then return end
intllib = {
getters = {},
strings = {},
}
local MP = minetest.get_modpath("intllib")
dofile(MP.."/lib.lua")
local strings = {}
local LANG = minetest.setting_get("language")
if not (LANG and (LANG ~= "")) then LANG = os.getenv("LANGUAGE") end
if not (LANG and (LANG ~= "")) then LANG = os.getenv("LANG") end
if not (LANG and (LANG ~= "")) then LANG = "en" end
LANG = LANG:sub(1, 2)
-- Support the old multi-load method
intllib.getters = intllib.getters or {}
intllib.strings = {}
local INS_CHAR = intllib.INSERTION_CHAR
local insertion_pattern = "("..INS_CHAR.."?)"..INS_CHAR.."(%(?)(%d+)(%)?)"
local function noop_getter(s)
return s
local function make_getter(msgstrs)
return function(s, ...)
local str
if msgstrs then
str = msgstrs[s]
end
if not str or str == "" then
str = s
end
if select("#", ...) == 0 then
return str
end
local args = {...}
str = str:gsub(insertion_pattern, function(escape, open, num, close)
if escape == "" then
local replacement = tostring(args[tonumber(num)])
if open == "" then
replacement = replacement..close
end
return replacement
else
return INS_CHAR..open..num..close
end
end)
return str
end
end
function intllib.Getter(modname)
modname = modname or minetest.get_current_modname()
if not intllib.getters[modname] then
local modpath = minetest.get_modpath(modname)
if modpath then
local filename = modpath.."/locale/"..LANG..".txt"
local msgstr = intllib.load_strings(filename)
intllib.strings[modname] = msgstr or false
if msgstr then
intllib.getters[modname] = function (s)
if msgstr[s] and msgstr[s] ~= "" then
return msgstr[s]
end
return s
end
else
intllib.getters[modname] = noop_getter
end
end
if not intllib.getters[modname] then
local msgstr = intllib.get_strings(modname)
intllib.getters[modname] = make_getter(msgstr)
end
return intllib.getters[modname]
end
function intllib.get_strings(modname)
modname = modname or minetest.get_current_modname()
local msgstr = intllib.strings[modname]
if msgstr == nil then
local modpath = minetest.get_modpath(modname)
msgstr = intllib.load_strings(modpath.."/locale/"..LANG..".txt")
intllib.strings[modname] = msgstr
local function get_locales(code)
local ll, cc = code:match("^(..)_(..)")
if ll then
return { ll.."_"..cc, ll, ll~="en" and "en" or nil }
else
return { code, code~="en" and "en" or nil }
end
return msgstr or nil
end
function intllib.get_strings(modname, langcode)
langcode = langcode or LANG
modname = modname or minetest.get_current_modname()
local msgstr = intllib.strings[modname]
if not msgstr then
local modpath = minetest.get_modpath(modname)
msgstr = { }
for _, l in ipairs(get_locales(langcode)) do
local t = intllib.load_strings(modpath.."/locale/"..l..".txt") or { }
for k, v in pairs(t) do
msgstr[k] = msgstr[k] or v
end
end
intllib.strings[modname] = msgstr
end
return msgstr
end

View File

@ -1,19 +1,41 @@
intllib = intllib or {}
local INS_CHAR = "@"
intllib.INSERTION_CHAR = INS_CHAR
local escapes = {
["\\"] = "\\",
["n"] = "\n",
["s"] = " ",
["t"] = "\t",
["r"] = "\r",
["f"] = "\f",
[INS_CHAR] = INS_CHAR..INS_CHAR,
}
local function unescape(s)
return s:gsub("([\\]?)\\(.)", function(slash, what)
if slash and (slash ~= "") then
return "\\"..what
local function unescape(str)
local parts = {}
local n = 1
local function add(s)
parts[n] = s
n = n + 1
end
local start = 1
while true do
local pos = str:find("\\", start, true)
if pos then
add(str:sub(start, pos - 1))
else
return escapes[what] or what
add(str:sub(start))
break
end
end)
local c = str:sub(pos + 1, pos + 1)
add(escapes[c] or c)
start = pos + 2
end
return table.concat(parts)
end
local function find_eq(s)

2
mods/intllib/mod.conf Normal file
View File

@ -0,0 +1,2 @@
name = intllib

View File

@ -109,7 +109,7 @@ for _, file in ipairs(inputs) do
local infile, e = io.open(file, "r")
if infile then
for line in infile:lines() do
for s in line:gmatch('S%("([^"]*)"%)') do
for s in line:gmatch('S%("([^"]*)"') do
table.insert(messages, s)
end
end