I18N

From GnuCash
Revision as of 03:40, 16 March 2022 by Fell (talk | contribs) (Preparation: Update links)
Jump to: navigation, search

This section collects some notes for developers/programmers on how to correctly prepare their code for translations.

General Thoughts

Which strings translation need
* Obvisious strings presented to the user should be translatable,
* but strings, which go into the log, should not. At least some of us have problems to read log entries in CJK writing.
* Pure numerical — including date, time and, monetary — strings should be formated according Locale Settings, but usually not translated.
* Strings containing only a special symbol like bullets usually need no translation. But in some cases there can be different typographical conventions like for quoting.
* Verify, that arrows like >> are properly reverted if you run the program in a RTL written language:
LANG=he_IL.utf8 gnucash
Usually our used tools are smart enough and then no translation is required.
* Never mark an empty string as translatable. The gettext tools use the empty string for their message catalog header. So it will confuse translators to have your preceding comment in the header of their .po file.
Separate content and form
Avoid markups, leading and trailing spaces; use functions to generate uppercase text or other formated text, …
Often the GUI offers better options for highlighting.
Granulation
With a few exceptions like labels, menu entries, or table elements use full sentences in proper US English. Because grammars are very different do not concat them, but use format strings. Usually the longest allowed element is a paragraph, but it is not easy to find a change like a fixed typo in a full paragraph.
Split repeated elements for translation and compose them for output by a format string.
Example
Msg1 = Sentence1, Sentence2
Msg2 = Sentence1, Sentence3
For the translators it is less work to translate Sentence1, Sentence2, Sentence3 each once.
Avoid Ambiguity
This can be achieved in several ways:
  • Use of full sentences, i.e. for tooltips.
  • Use of context for short messages like column headers.
  • Adding translator comments.
  • Add an entry to the glossary, if a term needs explanation and is used more than once.
Recommendations
If a message has more than one parameter, insert ordinal numbers already in the source like in C "%1$s contains %2$s." allowing the translator to write "%2$s is part of %1$s." instead.
Conventions
A few conventions are defined in GUI Guidelines.
Textual
US English instead of british English or more worse (~our vs. ~or, ~zation vs. ~sation …).
Separate sentences by one space only after the full stop, not runoff style!
Recycle already existing strings
Try to use the same label and tooltip in glade and schema files—GUI_Guidelines#Tooltips_and_Descriptions_of_Preferences
To get a dictionary
cd $BUILDDIR
ninja pot
msgcat --no-location -s -o po/gnucash-dict.pot po/gnucash.pot
# to suppress location lines insert: --no-location
See msggrep --help for query options.

String Manipulation

On translated strings you must not use standard C(++) functions as defined in ctype.h or <cstring> (string.h)! They assume ASCII characters, which have a size of 1 byte/char, but UTF-8 chars can have up to 4 byte/char. Instead use GLib's Unicode Manipulation.

How to make strings in code translatable

Strings in Glade files

In Glade files translatable strings have the form:

   <property name="label"
      translatable="yes"
      context="infinitive" 
      comments="Additional infos for the translator">Some translatable text with _mnemonic</property>
   <property name="visible">True</property>
   <property name="can_focus">True</property>
   <property name="receives_default">False</property>
   <property name="use_underline">True</property>
Note
The linebreaks between property attibutes were inserted for legability.
Attributes
translatable
required for translation,
context
Optional to restrict the context,
comments
Optional for additional infos.

For the mnemonic property use_underline see Translation#Special_characters_and_other_tips.

Attention
   <property name="label" translatable="yes">
Some translatable text
with multiple lines.
</property>
will result in
#: gnucash/gtkbuilder/foo.glade:11
msgid ""
"\n"
"Some translatable text\n"
"with multiple lines.\n"
msgstr ""
, but the first and last newline are usually undesired. To avoid them write
   <property name="label" translatable="yes">Some translatable text
with multiple lines.</property>

Strings in C files

Preparation

Each C module

  • having translated C strings or
  • containing printf()/fprintf()/... calls with a format string that could be a translated C string
should contain the line:
#include <libintl.h>
Source
https://www.gnu.org/software/gettext/manual/html_node/Importing.html.
If you want to use the 1-letter+underline abbreviations as we do, in lieu of insert
#include <glib/gi18n.h>
Details
https://docs.gtk.org/glib/i18n.html
Instant translation

Normally, strings in C code just need to be enclosed with the function _( ). Well, actually it is a macro declared as #define _(String) gettext (String), but this is usually just an implementation detail. For example,

 func("A translatable string!");

should instead be written as

 func(_("A translatable string!"));
When not to use instant translation
  • It is important to keep in mind that _( ) is a function; this means that in certain situations it cannot be used. For example,
     gchar* array_of_strings[] = {_("first string"), _("second string"), _("third string")};
    
    would cause a compiler error.
  • Static variables are created at program initialization before main so there's no locale or gettext text_domain. That means that these strings won't get translated. The fix is to use the N_(x) macro to mark them for xgettext and then call gettext (via the _(x) macro) when you pass them to the GtkWidget for display.
Delayed Translation

Instead, these strings should be wrapped with the N_( ) macro, which is declared as #define N_(String) gettext_noop(String). Then, whenever one of the strings is actually used (as opposed to declared), it should be wrapped with the _( ) function again:

gchar* array_of_strings[] = {N_("first string"), N_("second string"), N_("third string")};
:
func(_(array_of_strings[0]));
Another use case for gettext_noop() are strings which should be stored untranslated in some backend (log files, configuration or GnuCash data), but displayed translated to the user.
gchar* msg = N_("Something went wrong!");   /* Tell xgettext to insert the string into gnucash.pot */
PWARN (msg);   /* Record it untranslated in the trace file */
/* pop up a window with ... */
   _(msg)   /* Inform the user with the translated message */
Using Context

Whenever there are ambiguities, define a context. We often use

  1. one letter abbreviations
    1. as the column header and
    2. as a status flag
  2. samples to determinate the wide of a column or an input field.
  3. Another use case would be Invoice:
    1. in general,
    2. from supplier,
    3. to client.

There a 2 functions to tell the translator and gettext the context:

Ancient
  Q_("Column header for 'Reconciled'|R");
and
Recent
  C_("Column header for 'Reconciled'", "R")
Both will result in
#: gnucash/gnome/reconcile-view.c:425
#: gnucash/register/ledger-core/split-register-layout.c:691
#: gnucash/register/ledger-core/split-register-model.c:306
msgctxt "Column header for 'Reconciled'"
msgid "R"
msgstr ""

The benefit of C_(): also a NC_() macro (#Delayed Translation) exists, but no NQ_(). A NC_() macro will be translatable by using the form:

C_("navigation","back")  // must be string literals

const char* domain = NULL;
const char* context = "navigation";
const char* msgid = "back";
g_dpgettext2 (domain, context, msgid)
.
Context form
Please use similar forms of contexts like the existing entries. Use e.g.
grep -n 'msgctxt' po/de.po | sort -fk2.1
for a list.
Note
Before GnuCash 3.7 there was another selfmade form, which got replaced as it was error prone. Bug 797349 - "A"ssociate header badly translated

Strings in C Preprocessor Macros

Xgettext doesn't run cpp and can't see inside macros. Call gettext in the macro, not on the macro.

Wrong
#define EXPLANATION "The list below shows ..."
/* snip */
gnc_ui_object_references_show( _(EXPLANATION), list);
Right
#define EXPLANATION  _("The list below shows ...")
/* snip */
gnc_ui_object_references_show(EXPLANATION, list);

Strings in C++ files

For strings in C++ files the same techniques as for C files can be used. The drawback of this is one could only work with C-style strings (char*), which means one would not be able to benefit from the many advantages of C++.

A better alternative is to use boost::locale's message translation functionality.

In order to use this, one needs to add the following near the top of the C++ source file:

#include <boost/locale.hpp>
// Optionally:
namespace bl = boost::locale;
/* to be able to use bl::translate
 * and               bl::format
 * instead of boost::locale::translate
 * and        boost::locale::format    */

After that using boost::locale essentially means using boost::locale::translate() instead of gettext(). This function is designed to be used in a stream and work with the locale imbued in the stream, so one would usually

  1. create a stringstream,
  2. imbue the desired locale,
  3. stream the result of boost::locale::translate and boost::locale::format into this stream,
  4. when completely done, copy the string from the stringstream.

The link above gives some more elaborate examples and you can find some examples in the gnucash code already as well, like in filepathutils.cpp.

The biggest hurdle at the time of this writing is imbuing a locale in the stream. For most of the uses in gnucash this should simply be the global locale. However we don't set this yet in the C++ environment (where to do this still has to be determined). So the few spots in the code where we use this feature are generating a locale on the spot to imbue and that continues to be required until we set a global C++ locale.

Formatted strings

Some strings can have placeholders in that can only be completed at runtime, like a number of transactions in a selection, or the name of a file to be opened. The C world has a whole set of functions that work with such format strings (printf and all variants).

For C++ a more elegant method exists as well in the form of boost's localized text formatting. These have several advantages over the C based format functions, so in C++ it's recommended to use the boost::locale::format features.

Strings in SCM files

The general form is
;; enable I18N:
(use-modules (ice-9 i18n))
;; General Form:
(gettext msg [domain [category]])
;; The abbreviation changed with Guile 3:
(G_ "Some translatable string")
.
Source
Guile Manual: Gettext Support
See also
Guile Manual: Formatted Output

Plural Forms

Not all languages have the same simple kind of plural forms as english. See gettexts Plural-forms for details.

Avoid underline

Because Underline _marks mnemonics in the GUI, do not use it for other purposes. It would confuse msgfmt -c --check-accelerators="_" else. Use the normal dash - instead.

Avoid Markups and Other Formating

It is annoying, if you have to translate "number", "number:", "number: ", "<b>number</b>", "Number", "NUMBER" all separate. In many cases you can move the formating elements outside of the translatable string or use functions for case conversion.

Mask Unintended Line Breaks

In some languages like Scheme you can enter continous text over several lines like
   (_ "This report is useful to calculate periodic business tax payable/receivable from
 authorities. From 'Edit report options' above, choose your Business Income and Business Expense accounts.
 Each transaction may contain, in addition to the accounts payable/receivable or bank accounts,
 a split to a tax account, e.g. Income:Sales -$1000, Liability:GST on Sales -$100, Asset:Bank $1100.")
This will result in gnucash.pot as
#: gnucash/report/standard-reports/income-gst-statement.scm:43
msgid ""
"This report is useful to calculate periodic business tax payable/receivable "
"from\n"
" authorities. From 'Edit report options' above, choose your Business Income "
"and Business Expense accounts.\n"
" Each transaction may contain, in addition to the accounts payable/"
"receivable or bank accounts,\n"
" a split to a tax account, e.g. Income:Sales -$1000, Liability:GST on Sales -"
"$100, Asset:Bank $1100."

Watch all the "\n"s, which get inserted by xgettext and the leading spaces in the next line. While the newlines are ignored by the HTML renderer, the translators get confused.

Instead mask the line endings by "\":
   (_ "This report is useful to calculate periodic business tax payable/receivable from \
authorities. From 'Edit report options' above, choose your Business Income and Business Expense accounts. \
Each transaction may contain, in addition to the accounts payable/receivable or bank accounts, \
a split to a tax account, e.g. Income:Sales -$1000, Liability:GST on Sales -$100, Asset:Bank $1100.")
and the translators will get:
#: gnucash/report/standard-reports/income-gst-statement.scm:43
msgid ""
"This report is useful to calculate periodic business tax payable/receivable "
"from authorities. From 'Edit report options' above, choose your Business "
"Income and Business Expense accounts. Each transaction may contain, in "
"addition to the accounts payable/receivable or bank accounts, a split to a "
"tax account, e.g. Income:Sales -$1000, Liability:GST on Sales -$100, Asset:"
"Bank $1100."

Add Infos for Translators

Often it is useful to give the translators some additional information about the meaning of specific words or full messages.

  • Each financial term should have a glossary entry because the meaning can be slightly differ by language or country.
  • Each term with a GnuCash specific meaning like "Bill", too.
  • If the same explanation is required more than once, consider to add a section to the glossary.

Glossary

If you introduce new terms which are more than once used, you should include them to Translation#The_glossary_file. The instruction is in Translation#Terms missing or inadequate in the glossary file.

Translator Comments for Single Messages

You can insert a section of comment lines direct before the related string, where the first comment starts with "Translators:".

  • There must not be any control statement (if, case, while …) between comment and string.
  • Using block comments instead of line comments will allow the gettext tools to do their own wrapping.
  • If the same message appears several times in the source files, the comment should only be attached to the first occurrence.
In C based files
Example:
 /* Translators: the following string deals about:
    The Answer to Life, the Universe and Everything
    Source:
    https://en.wikipedia.org/wiki/Phrases_from_The_Hitchhiker%27s_Guide_to_the_Galaxy */
 func(_("42"));

In the pot and po files, this comment will show up as follows:

#. Translators: the following string deals about:
#. The Answer to Life, the Universe and Everything
#. Source:
#. https://en.wikipedia.org/wiki/Phrases_from_The_Hitchhiker%27s_Guide_to_the_Galaxy
#: foo/bar.c:123
msgid "42"
msgstr ""
Notes
An empty comment line will end the process. If the string " Source:" were missing, the URL were not part of the output.
Do not decorate translator comments by a frame of stars:
 /* Translators: the following string deals about:                                    *
  * The Answer to Life, the Universe and Everything                                   *
  * Source:                                                                           *
  * https://en.wikipedia.org/wiki/Phrases_from_The_Hitchhiker%27s_Guide_to_the_Galaxy */
After its reformatting by xgettext, it would look terrible in the message cataloges.
In SCM files

If the first expression has a translatable string and the file has a long header comment, split the line before the string and insert a translator comment. Otherwise the POT file will be flooded with file headers.

Example
;; Boston, MA  02110-1301,  USA       gnu@gnu.org
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


(define GNC_COMMODITY_NS_CURRENCY
;; Translators: Namespaces of commodities
   (gettext "CURRENCY"))
In XML
Some variants like Glade have their specific tags. Others like GSettings use simple XML comments:
 <!-- Translators: A list of words which are not allowed to be typed, in
      GVariant serialization syntax.
      See: https://developer.gnome.org/glib/stable/gvariant-text.html -->
 <default l10n='messages' context='Banned words'>['bad', 'words']</default>
In HTML + PHP
Here it is important, that the comment is not in the HTML, but the PHP part:
<img class="featureimage" src="<?=$top_dir?>/images/features/<?PHP 
//Translators: If you already translated the guide, you can copy the image into /images/features/ as e.g. basics_AccountRelationships.ll.png
echo T_("basics_AccountRelationships.C.png");
?>" alt="[Basic account relationship]" />

Borrowing Code

Ideally they would use their own text domain like in our use of ISOcode.

If not - like in 2.7 /borrowed/goffice - we should consider some msgcat magic with their po files to

  • update our existing po files
  • create new po files.

At present a bash script was written to take care of the first part: import-goffice-translations.sh in contrib/.


This script can be used to import translations from the goffice source directory into our po files. Note this script will run over all of our existing po files in one go, so it can only be used to update all po files at once.

There is no code to create new po files. I think this can be done in a few steps as well, as in

  1. create the new po file as we would normally do for gnucash (see msginit elsewhere on this page)
  2. run the script mentioned above to import goffice translations
  3. this may change more files than needed, use git checkout to undo the changes to files you didn't want to alter
  4. continue as usual with translation work.

Using Other Programming Languages

  1. Adapt https://www.gnu.org/software/gettext/manual/gettext.html#Sources for your source language.
    Note
    The initialization is done in gnucash/gnucash-bin.c, search #ifdef HAVE_GETTEXT.
  2. Add the file extensions of the source files, which contain translatable strings, to the list of make_gnucash_potfiles in po/CMakeLists.txt.
    Verify the ${path} in the next section is still correct.
  3. Are changes required in po/gnucash-pot.cmake, i.e. additional --keyword or --flag options for xgettext?
  4. If there are files in the search path, which should be skipped, add them with the reason to po/POTFILES.skip
  5. Write down your experience as a subsection here.

Python

Python gettext seems to need a separate initialization in addition to that in gnucash/gnucash-bin.c. There is a developmental Pull Request dealing with that: [1].

Further Reading

If you want to read more about this topic, GnomeI18nDeveloperTips might be a good starting point.

Follow the rules of the Gnome Human Interface Guide like Writing style and Typography.

More technical and historical details can be found in Gettext Manual: The Programmer’s View,

Guile/Scheme
Guile Reference Manual: Support for Internationalization,
Python
The Python Standard Library: Internationalization.