gettext utilities
gettext declaration
gettext Operations
gettext Installation
msgcat Program
msgconv Program
msggrep Program
msgfilter Program
msguniq Program
msgcomm Program
msgcmp Program
msgattrib Program
msgen Program
msgexec Program
msgfmt Program
msgunfmt Program
gettextize Program
gettext utilitiesThis manual documents the GNU gettext tools and the GNU libintl library, version 0.17.
--- The Detailed Node Listing ---
Introduction
The User's View
Setting the POSIX Locale
Preparing Program Sources
Making the PO Template File
Creating a New PO File
Updating Existing PO Files
Editing PO Files
Emacs's PO File Editor
Using Translation Compendia
Manipulating PO Files
Highlighting parts of PO files
Producing Binary MO Files
The Programmer's View
About catgets
About gettext
Temporary Notes for the Programmers Chapter
The Translator's View
Organization
National Teams
The Maintainer's View
Files You Must Create or Alter
Autoconf macros for use in configure.ac
Integrating with CVS
Other Programming Languages
The Translator's View
Individual Programming Languages
sh - Shell Script
Perl
Internationalizable Data
Concluding Remarks
Language Codes
Licenses
This chapter explains the goals sought in the creation
of GNU gettext and the free Translation Project.
Then, it explains a few broad concepts around
Native Language Support, and positions message translation with regard
to other aspects of national and cultural variance, as they apply
to programs. It also surveys those files used to convey the
translations. It explains how the various tools interact in the
initial generation of these files, and later, how the maintenance
cycle should usually operate.
In this manual, we use he when speaking of the programmer or
maintainer, she when speaking of the translator, and they
when speaking of the installers or end users of the translated program.
This is only a convenience for clarifying the documentation. It is
absolutely not meant to imply that some roles are more appropriate
to males or females. Besides, as you might guess, GNU gettext
is meant to be useful for people using computers, whatever their sex,
race, religion or nationality!
Please send suggestions and corrections to:
Internet address:
bug-gnu-gettext@gnu.org
Please include the manual's edition number and update date in your messages.
gettextUsually, programs are written and documented in English, and use English at execution time to interact with users. This is true not only of GNU software, but also of a great deal of proprietary and free software. Using a common language is quite handy for communication between developers, maintainers and users from all countries. On the other hand, most people are less comfortable with English than with their own native language, and would prefer to use their mother tongue for day to day's work, as far as possible. Many would simply love to see their computer screen showing a lot less of English, and far more of their own language.
However, to many people, this dream might appear so far fetched that they may believe it is not even worth spending time thinking about it. They have no confidence at all that the dream might ever become true. Yet some have not lost hope, and have organized themselves. The Translation Project is a formalization of this hope into a workable structure, which has a good chance to get all of us nearer the achievement of a truly multi-lingual set of programs.
GNU gettext is an important step for the Translation Project,
as it is an asset on which we may build many other steps. This package
offers to programmers, translators and even users, a well integrated
set of tools and documentation. Specifically, the GNU gettext
utilities are a set of tools that provides a framework within which
other free packages may produce multi-lingual messages. These tools
include
GNU gettext is designed to minimize the impact of
internationalization on program sources, keeping this impact as small
and hardly noticeable as possible. Internationalization has better
chances of succeeding if it is very light weighted, or at least,
appear to be so, when looking at program sources.
The Translation Project also uses the GNU gettext distribution
as a vehicle for documenting its structure and methods. This goes
beyond the strict technicalities of documenting the GNU gettext
proper. By so doing, translators will find in a single place, as
far as possible, all they need to know for properly doing their
translating work. Also, this supplemental documentation might also
help programmers, and even curious users, in understanding how GNU
gettext is related to the remainder of the Translation
Project, and consequently, have a glimpse at the big picture.
Two long words appear all the time when we discuss support of native language in programs, and these words have a precise meaning, worth being explained here, once and for all in this document. The words are internationalization and localization. Many people, tired of writing these long words over and over again, took the habit of writing i18n and l10n instead, quoting the first and last letter of each word, and replacing the run of intermediate letters by a number merely telling how many such letters there are. But in this manual, in the sake of clarity, we will patiently write the names in full, each time...
By internationalization, one refers to the operation by which a
program, or a set of programs turned into a package, is made aware of and
able to support multiple languages. This is a generalization process,
by which the programs are untied from calling only English strings or
other English specific habits, and connected to generic ways of doing
the same, instead. Program developers may use various techniques to
internationalize their programs. Some of these have been standardized.
GNU gettext offers one of these standards. See Programmers.
By localization, one means the operation by which, in a set of programs already internationalized, one gives the program all needed information so that it can adapt itself to handle its input and output in a fashion which is correct for some native language and cultural habits. This is a particularisation process, by which generic methods already implemented in an internationalized program are used in specific ways. The programming environment puts several functions to the programmers disposal which allow this runtime configuration. The formal description of specific set of cultural habits for some country, together with all associated translations targeted to the same native language, is called the locale for this language or country. Users achieve localization of programs by setting proper values to special environment variables, prior to executing those programs, identifying which locale should be used.
In fact, locale message support is only one component of the cultural data that makes up a particular locale. There are a whole host of routines and functions provided to aid programmers in developing internationalized software and which allow them to access the data stored in a particular locale. When someone presently refers to a particular locale, they are obviously referring to the data stored within that particular locale. Similarly, if a programmer is referring to “accessing the locale routines”, they are referring to the complete suite of routines that access all of the locale's information.
One uses the expression Native Language Support, or merely NLS, for speaking of the overall activity or feature encompassing both internationalization and localization, allowing for multi-lingual interactions in a program. In a nutshell, one could say that internationalization is the operation by which further localizations are made possible.
Also, very roughly said, when it comes to multi-lingual messages, internationalization is usually taken care of by programmers, and localization is usually taken care of by translators.
For a totally multi-lingual distribution, there are many things to translate beyond output messages.
gettext offers a complete toolset for
translating messages output by C programs. Perl scripts and shell
scripts will also need to be translated. Even if there are today some hooks
by which this can be done, these hooks are not integrated as well as they
should be.
autoconf or bison, are able
to produce other programs (or scripts). Even if the generating
programs themselves are internationalized, the generated programs they
produce may need internationalization on their own, and this indirect
internationalization could be automated right from the generating
program. In fact, quite usually, generating and generated programs
could be internationalized independently, as the effort needed is
fairly orthogonal.
recode program is able to reconstruct at execution.
Since these descriptions are extracted from the RFC by mechanical means,
translating them properly would require a prior translation of the RFC
itself.
gcc to allow diacriticized characters in identifiers or use
translated keywords; ‘rm -i’ might accept something else than
‘y’ or ‘n’ for replies, etc. Even if the program will
eventually make most of its output in the foreign languages, one has
to decide whether the input syntax, option values, etc., are to be
localized or not.
As we already stressed, translation is only one aspect of locales.
Other internationalization aspects are system services and are handled
in GNU libc. There
are many attributes that are needed to define a country's cultural
conventions. These attributes include beside the country's native
language, the formatting of the date and time, the representation of
numbers, the symbols for currency, etc. These local rules are
termed the country's locale. The locale represents the knowledge
needed to support the country's native attributes.
There are a few major areas which may vary between countries and
hence, define what a locale must describe. The following list helps
putting multi-lingual messages into the proper context of other tasks
related to locales. See the GNU libc manual for details.
Time of the day may be noted as hh:mm, hh.mm,
or otherwise. Some locales require time to be specified in 24-hour
mode rather than as AM or PM. Further, the nature and yearly extent
of the Daylight Saving correction vary widely between countries.
12,345.67 English
12.345,67 German
12345,67 French
1,2345.67 Asia
Some programs could go further and use different unit systems, like
English units or Metric units, or even take into account variants
about how numbers are spelled in full.
gettext provides the means for developers and users to
easily change the language that the software uses to communicate to
the user.
These areas of cultural conventions are called locale categories. It is an unfortunate term; locale aspects or locale feature categories would be a better term, because each “locale category” describes an area or task that requires localization. The concrete data that describes the cultural conventions for such an area and for a particular culture is also called a locale category. In this sense, a locale is composed of several locale categories: the locale category describing the codeset, the locale category describing the formatting of numbers, the locale category containing the translated messages, and so on.
Components of locale outside of message handling are standardized in
the ISO C standard and the POSIX:2001 standard (also known as the SUSV3
specification). GNU libc
fully implements this, and most other modern systems provide a more
or less reasonable support for at least some of the missing components.
The letters PO in .po files means Portable Object, to distinguish it from .mo files, where MO stands for Machine Object. This paradigm, as well as the PO file format, is inspired by the NLS standard developed by Uniforum, and first implemented by Sun in their Solaris system.
PO files are meant to be read and edited by humans, and associate each
original, translatable string of a given package with its translation
in a particular target language. A single PO file is dedicated to
a single target language. If a package supports many languages,
there is one such PO file per language supported, and each package
has its own set of PO files. These PO files are best created by
the xgettext program, and later updated or refreshed through
the msgmerge program. Program xgettext extracts all
marked messages from a set of C files and initializes a PO file with
empty translations. Program msgmerge takes care of adjusting
PO files between releases of the corresponding sources, commenting
obsolete entries, initializing new ones, and updating all source
line references. Files ending with .pot are kind of base
translation files found in distributions, in PO file format.
MO files are meant to be read by programs, and are binary in nature.
A few systems already offer tools for creating and handling MO files
as part of the Native Language Support coming with the system, but the
format of these MO files is often different from system to system,
and non-portable. The tools already provided with these systems don't
support all the features of GNU gettext. Therefore GNU
gettext uses its own format for MO files. Files ending with
.gmo are really MO files, when it is known that these files use
the GNU format.
gettextThe following diagram summarizes the relation between the files
handled by GNU gettext and the tools acting on these files.
It is followed by somewhat detailed explanations, which you should
read while keeping an eye on the diagram. Having a clear understanding
of these interrelations will surely help programmers, translators
and maintainers.
Original C Sources ───> Preparation ───> Marked C Sources ───╮
│
â•─────────<─── GNU gettext Library │
â•─── make <───┤ │
│ ╰─────────<────────────────────┬───────────────╯
│ │
│ â•─────<─── PACKAGE.pot <─── xgettext <───╯ â•───<─── PO Compendium
│ │ │ ↑
│ │ ╰───╮ │
│ ╰───╮ ├───> PO editor ───╮
│ ├────> msgmerge ──────> LANG.po ────>────────╯ │
│ â•───╯ │
│ │ │
│ ╰─────────────<───────────────╮ │
│ ├─── New LANG.po <────────────────────╯
│ â•─── LANG.gmo <─── msgfmt <───╯
│ │
│ ╰───> install ───> /.../LANG/PACKAGE.mo ───╮
│ ├───> "Hello world!"
╰───────> install ───> /.../bin/PROGRAM ───────╯
As a programmer, the first step to bringing GNU gettext
into your package is identifying, right in the C sources, those strings
which are meant to be translatable, and those which are untranslatable.
This tedious job can be done a little more comfortably using emacs PO
mode, but you can use any means familiar to you for modifying your
C sources. Beside this some other simple, standard changes are needed to
properly initialize the translation library. See Sources, for
more information about all this.
For newly written software the strings of course can and should be
marked while writing it. The gettext approach makes this
very easy. Simply put the following lines at the beginning of each file
or in a central header file:
#define _(String) (String)
#define N_(String) String
#define textdomain(Domain)
#define bindtextdomain(Package, Directory)
Doing this allows you to prepare the sources for internationalization.
Later when you feel ready for the step to use the gettext library
simply replace these definitions by the following:
#include <libintl.h>
#define _(String) gettext (String)
#define gettext_noop(String) String
#define N_(String) gettext_noop (String)
and link against libintl.a or libintl.so. Note that on
GNU systems, you don't need to link with libintl because the
gettext library functions are already contained in GNU libc.
That is all you have to change.
Once the C sources have been modified, the xgettext program
is used to find and extract all translatable strings, and create a
PO template file out of all these. This package.pot file
contains all original program strings. It has sets of pointers to
exactly where in C sources each string is used. All translations
are set to empty. The letter t in .pot marks this as
a Template PO file, not yet oriented towards any particular language.
See xgettext Invocation, for more details about how one calls the
xgettext program. If you are really lazy, you might
be interested at working a lot more right away, and preparing the
whole distribution setup (see Maintainers). By doing so, you
spare yourself typing the xgettext command, as make
should now generate the proper things automatically for you!
The first time through, there is no lang.po yet, so the
msgmerge step may be skipped and replaced by a mere copy of
package.pot to lang.po, where lang
represents the target language. See Creating for details.
Then comes the initial translation of messages. Translation in itself is a whole matter, still exclusively meant for humans, and whose complexity far overwhelms the level of this manual. Nevertheless, a few hints are given in some other chapter of this manual (see Translators). You will also find there indications about how to contact translating teams, or becoming part of them, for sharing your translating concerns with others who target the same native language.
While adding the translated messages into the lang.po PO file, if you are not using one of the dedicated PO file editors (see Editing), you are on your own for ensuring that your efforts fully respect the PO file format, and quoting conventions (see PO Files). This is surely not an impossible task, as this is the way many people have handled PO files around 1995. On the other hand, by using a PO file editor, most details of PO file format are taken care of for you, but you have to acquire some familiarity with PO file editor itself.
If some common translations have already been saved into a compendium PO file, translators may use PO mode for initializing untranslated entries from the compendium, and also save selected translations into the compendium, updating it (see Compendium). Compendium files are meant to be exchanged between members of a given translation team.
Programs, or packages of programs, are dynamic in nature: users write bug reports and suggestion for improvements, maintainers react by modifying programs in various ways. The fact that a package has already been internationalized should not make maintainers shy of adding new strings, or modifying strings already translated. They just do their job the best they can. For the Translation Project to work smoothly, it is important that maintainers do not carry translation concerns on their already loaded shoulders, and that translators be kept as free as possible of programming concerns.
The only concern maintainers should have is carefully marking new
strings as translatable, when they should be, and do not otherwise
worry about them being translated, as this will come in proper time.
Consequently, when programs and their strings are adjusted in various
ways by maintainers, and for matters usually unrelated to translation,
xgettext would construct package.pot files which are
evolving over time, so the translations carried by lang.po
are slowly fading out of date.
It is important for translators (and even maintainers) to understand that package translation is a continuous process in the lifetime of a package, and not something which is done once and for all at the start. After an initial burst of translation activity for a given package, interventions are needed once in a while, because here and there, translated entries become obsolete, and new untranslated entries appear, needing translation.
The msgmerge program has the purpose of refreshing an already
existing lang.po file, by comparing it with a newer
package.pot template file, extracted by xgettext
out of recent C sources. The refreshing operation adjusts all
references to C source locations for strings, since these strings
move as programs are modified. Also, msgmerge comments out as
obsolete, in lang.po, those already translated entries
which are no longer used in the program sources (see Obsolete Entries). It finally discovers new strings and inserts them in
the resulting PO file as untranslated entries (see Untranslated Entries). See msgmerge Invocation, for more information about what
msgmerge really does.
Whatever route or means taken, the goal is to obtain an updated lang.po file offering translations for all strings.
The temporal mobility, or fluidity of PO files, is an integral part of the translation game, and should be well understood, and accepted. People resisting it will have a hard time participating in the Translation Project, or will give a hard time to other participants! In particular, maintainers should relax and include all available official PO files in their distributions, even if these have not recently been updated, without exerting pressure on the translator teams to get the job done. The pressure should rather come from the community of users speaking a particular language, and maintainers should consider themselves fairly relieved of any concern about the adequacy of translation files. On the other hand, translators should reasonably try updating the PO files they are responsible for, while the package is undergoing pretest, prior to an official distribution.
Once the PO file is complete and dependable, the msgfmt program
is used for turning the PO file into a machine-oriented format, which
may yield efficient retrieval of translations by the programs of the
package, whenever needed at runtime (see MO Files). See msgfmt Invocation, for more information about all modes of execution
for the msgfmt program.
Finally, the modified and marked C sources are compiled and linked
with the GNU gettext library, usually through the operation of
make, given a suitable Makefile exists for the project,
and the resulting executable is installed somewhere users will find it.
The MO files themselves should also be properly installed. Given the
appropriate environment variables are set (see Setting the POSIX Locale),
the program should localize itself automatically, whenever it executes.
The remainder of this manual has the purpose of explaining in depth the various steps outlined above.
Nowadays, when users log into a computer, they usually find that all their programs show messages in their native language – at least for users of languages with an active free software community, like French or German; to a lesser extent for languages with a smaller participation in free software and the GNU project, like Hindi and Filipino.
How does this work? How can the user influence the language that is used by the programs? This chapter will answer it.
The default language is often already specified during operating system installation. When the operating system is installed, the installer typically asks for the language used for the installation process and, separately, for the language to use in the installed system. Some OS installers only ask for the language once.
This determines the system-wide default language for all users. But the installers often give the possibility to install extra localizations for additional languages. For example, the localizations of KDE (the K Desktop Environment) and OpenOffice.org are often bundled separately, as one installable package per language.
At this point it is good to consider the intended use of the machine: If it is a machine designated for personal use, additional localizations are probably not necessary. If, however, the machine is in use in an organization or company that has international relationships, one can consider the needs of guest users. If you have a guest from abroad, for a week, what could be his preferred locales? It may be worth installing these additional localizations ahead of time, since they cost only a bit of disk space at this point.
The system-wide default language is the locale configuration that is used when a new user account is created. But the user can have his own locale configuration that is different from the one of the other users of the same machine. He can specify it, typically after the first login, as described in the next section.
The immediately available programs in a user's desktop come from a group of programs called a “desktop environment”; it usually includes the window manager, a web browser, a text editor, and more. The most common free desktop environments are KDE, GNOME, and Xfce.
The locale used by GUI programs of the desktop environment can be specified in a configuration screen called “control center”, “language settings” or “country settings”.
Individual GUI programs that are not part of the desktop environment can have their locale specified either in a settings panel, or through environment variables.
For some programs, it is possible to specify the locale through environment
variables, possibly even to a different locale than the desktop's locale.
This means, instead of starting a program through a menu or from the file
system, you can start it from the command-line, after having set some
environment variables. The environment variables can be those specified
in the next section (Setting the POSIX Locale); for some versions of
KDE, however, the locale is specified through a variable KDE_LANG,
rather than LANG or LC_ALL.
As a user, if your language has been installed for this package, in the
simplest case, you only have to set the LANG environment variable
to the appropriate ‘ll_CC’ combination. For example,
let's suppose that you speak German and live in Germany. At the shell
prompt, merely execute
‘setenv LANG de_DE’ (in csh),
‘export LANG; LANG=de_DE’ (in sh) or
‘export LANG=de_DE’ (in bash). This can be done from your
.login or .profile file, once and for all.
A locale name usually has the form ‘ll_CC’. Here
‘ll’ is an ISO 639 two-letter language code, and
‘CC’ is an ISO 3166 two-letter country code. For example,
for German in Germany, ll is de, and CC is DE.
You find a list of the language codes in appendix Language Codes and
a list of the country codes in appendix Country Codes.
You might think that the country code specification is redundant. But in fact, some languages have dialects in different countries. For example, ‘de_AT’ is used for Austria, and ‘pt_BR’ for Brazil. The country code serves to distinguish the dialects.
Many locale names have an extended syntax ‘ll_CC.encoding’ that also specifies the character encoding. These are in use because between 2000 and 2005, most users have switched to locales in UTF-8 encoding. For example, the German locale on glibc systems is nowadays ‘de_DE.UTF-8’. The older name ‘de_DE’ still refers to the German locale as of 2000 that stores characters in ISO-8859-1 encoding – a text encoding that cannot even accomodate the Euro currency sign.
Some locale names use ‘ll_CC.@variant’ instead of ‘ll_CC’. The ‘@variant’ can denote any kind of characteristics that is not already implied by the language ll and the country CC. It can denote a particular monetary unit. For example, on glibc systems, ‘de_DE@euro’ denotes the locale that uses the Euro currency, in contrast to the older locale ‘de_DE’ which implies the use of the currency before 2002. It can also denote a dialect of the language, or the script used to write text (for example, ‘sr_RS@latin’ uses the Latin script, whereas ‘sr_RS’ uses the Cyrillic script to write Serbian), or the orthography rules, or similar.
On other systems, some variations of this scheme are used, such as ‘ll’. You can get the list of locales supported by your system for your language by running the command ‘locale -a | grep '^ll'’.
There is also a special locale, called ‘C’. When it is used, it disables all localization: in this locale, all programs standardized by POSIX use English messages and an unspecified character encoding (often US-ASCII, but sometimes also ISO-8859-1 or UTF-8, depending on the operating system).
A locale is composed of several locale categories, see Aspects. When a program looks up locale dependent values, it does this according to the following environment variables, in priority order:
LANGUAGE
LC_ALL
LC_xxx, according to selected locale category:
LC_CTYPE, LC_NUMERIC, LC_TIME, LC_COLLATE,
LC_MONETARY, LC_MESSAGES, ...
LANG
Variables whose value is set but is empty are ignored in this lookup.
LANG is the normal environment variable for specifying a locale.
As a user, you normally set this variable (unless some of the other variables
have already been set by the system, in /etc/profile or similar
initialization files).
LC_CTYPE, LC_NUMERIC, LC_TIME, LC_COLLATE,
LC_MONETARY, LC_MESSAGES, and so on, are the environment
variables meant to override LANG and affecting a single locale
category only. For example, assume you are a Swedish user in Spain, and you
want your programs to handle numbers and dates according to Spanish
conventions, and only the messages should be in Swedish. Then you could
create a locale named ‘sv_ES’ or ‘sv_ES.UTF-8’ by use of the
localedef program. But it is simpler, and achieves the same effect,
to set the LANG variable to es_ES.UTF-8 and the
LC_MESSAGES variable to sv_SE.UTF-8; these two locales come
already preinstalled with the operating system.
LC_ALL is an environment variable that overrides all of these.
It is typically used in scripts that run particular programs. For example,
configure scripts generated by GNU autoconf use LC_ALL to make
sure that the configuration tests don't operate in locale dependent ways.
Some systems, unfortunately, set LC_ALL in /etc/profile or in
similar initialization files. As a user, you therefore have to unset this
variable if you want to set LANG and optionally some of the other
LC_xxx variables.
The LANGUAGE variable is described in the next subsection.
Not all programs have translations for all languages. By default, an
English message is shown in place of a nonexistent translation. If you
understand other languages, you can set up a priority list of languages.
This is done through a different environment variable, called
LANGUAGE. GNU gettext gives preference to LANGUAGE
over LC_ALL and LANG for the purpose of message handling,
but you still need to have LANG (or LC_ALL) set to the primary
language; this is required by other parts of the system libraries.
For example, some Swedish users who would rather read translations in
German than English for when Swedish is not available, set LANGUAGE
to ‘sv:de’ while leaving LANG to ‘sv_SE’.
Special advice for Norwegian users: The language code for Norwegian
bokma*l changed from ‘no’ to ‘nb’ recently (in 2003).
During the transition period, while some message catalogs for this language
are installed under ‘nb’ and some older ones under ‘no’, it is
recommended for Norwegian users to set LANGUAGE to ‘nb:no’ so that
both newer and older translations are used.
In the LANGUAGE environment variable, but not in the other
environment variables, ‘ll_CC’ combinations can be
abbreviated as ‘ll’ to denote the language's main dialect.
For example, ‘de’ is equivalent to ‘de_DE’ (German as spoken in
Germany), and ‘pt’ to ‘pt_PT’ (Portuguese as spoken in Portugal)
in this context.
Note: The variable LANGUAGE is ignored if the locale is set to
‘C’. In other words, you have to first enable localization, by setting
LANG (or LC_ALL) to a value other than ‘C’, before you can
use a language priority list through the LANGUAGE variable.
Languages are not equally well supported in all packages using GNU
gettext, and more translations are added over time. Usually, you
use the translations that are shipped with the operating system
or with particular packages that you install afterwards. But you can also
install newer localizations directly. For doing this, you will need an
understanding where each localization file is stored on the file system.
For programs that participate in the Translation Project, you can start looking for translations here: http://translationproject.org/team/index.html. A snapshot of this information is also found in the ABOUT-NLS file that is shipped with GNU gettext.
For programs that are part of the KDE project, the starting point is: http://i18n.kde.org/.
For programs that are part of the GNOME project, the starting point is: http://www.gnome.org/i18n/.
For other programs, you may check whether the program's source code package contains some ll.po files; often they are kept together in a directory called po/. Each ll.po file contains the message translations for the language whose abbreviation of ll.
The GNU gettext toolset helps programmers and translators
at producing, updating and using translation files, mainly those
PO files which are textual, editable files. This chapter explains
the format of PO files.
A PO file is made up of many entries, each entry holding the relation between an original untranslated string and its corresponding translation. All entries in a given PO file usually pertain to a single project, and all translations are expressed in a single target language. One PO file entry has the following schematic structure:
white-space
# translator-comments
#. extracted-comments
#: reference...
#, flag...
#| msgid previous-untranslated-string
msgid untranslated-string
msgstr translated-string
The general structure of a PO file should be well understood by the translator. When using PO mode, very little has to be known about the format details, as PO mode takes care of them for her.
A simple entry can look like this:
#: lib/error.c:116
msgid "Unknown system error"
msgstr "Error desconegut del sistema"
Entries begin with some optional white space. Usually, when generated
through GNU gettext tools, there is exactly one blank line
between entries. Then comments follow, on lines all starting with the
character #. There are two kinds of comments: those which have
some white space immediately following the # - the translator
comments -, which comments are created and maintained exclusively by the
translator, and those which have some non-white character just after the
# - the automatic comments -, which comments are created and
maintained automatically by GNU gettext tools. Comment lines
starting with #. contain comments given by the programmer, directed
at the translator; these comments are called extracted comments
because the xgettext program extracts them from the program's
source code. Comment lines starting with #: contain references to
the program's source code. Comment lines starting with #, contain
flags; more about these below. Comment lines starting with #|
contain the previous untranslated string for which the translator gave
a translation.
All comments, of either kind, are optional.
After white space and comments, entries show two strings, namely
first the untranslated string as it appears in the original program
sources, and then, the translation of this string. The original
string is introduced by the keyword msgid, and the translation,
by msgstr. The two strings, untranslated and translated,
are quoted in various ways in the PO file, using "
delimiters and \ escapes, but the translator does not really
have to pay attention to the precise quoting format, as PO mode fully
takes care of quoting for her.
The msgid strings, as well as automatic comments, are produced
and managed by other GNU gettext tools, and PO mode does not
provide means for the translator to alter these. The most she can
do is merely deleting them, and only by deleting the whole entry.
On the other hand, the msgstr string, as well as translator
comments, are really meant for the translator, and PO mode gives her
the full control she needs.
The comment lines beginning with #, are special because they are
not completely ignored by the programs as comments generally are. The
comma separated list of flags is used by the msgfmt
program to give the user some better diagnostic messages. Currently
there are two forms of flags defined:
fuzzymsgmerge program or it can be
inserted by the translator herself. It shows that the msgstr
string might not be a correct translation (anymore). Only the translator
can judge if the translation requires further modification, or is
acceptable as is. Once satisfied with the translation, she then removes
this fuzzy attribute. The msgmerge program inserts this
when it combined the msgid and msgstr entries after fuzzy
search only. See Fuzzy Entries.
c-formatno-c-formatxgettext program adds them. In an automated PO file processing
system as proposed here the user changes would be thrown away again as
soon as the xgettext program generates a new template file.
The c-format flag tells that the untranslated string and the
translation are supposed to be C format strings. The no-c-format
flag tells that they are not C format strings, even though the untranslated
string happens to look like a C format string (with ‘%’ directives).
In case the c-format flag is given for a string the msgfmt
does some more tests to check to validity of the translation.
See msgfmt Invocation, c-format Flag and c-format.
objc-formatno-objc-formatsh-formatno-sh-formatpython-formatno-python-formatlisp-formatno-lisp-formatelisp-formatno-elisp-formatlibrep-formatno-librep-formatscheme-formatno-scheme-formatsmalltalk-formatno-smalltalk-formatjava-formatno-java-formatcsharp-formatno-csharp-formatawk-formatno-awk-formatobject-pascal-formatno-object-pascal-formatycp-formatno-ycp-formattcl-formatno-tcl-formatperl-formatno-perl-formatperl-brace-formatno-perl-brace-formatphp-formatno-php-formatgcc-internal-formatno-gcc-internal-formatqt-formatno-qt-formatkde-formatno-kde-formatboost-formatno-boost-formatIt is also possible to have entries with a context specifier. They look like this:
white-space
# translator-comments
#. extracted-comments
#: reference...
#, flag...
#| msgctxt previous-context
#| msgid previous-untranslated-string
msgctxt context
msgid untranslated-string
msgstr translated-string
The context serves to disambiguate messages with the same
untranslated-string. It is possible to have several entries with
the same untranslated-string in a PO file, provided that they each
have a different context. Note that an empty context string
and an absent msgctxt line do not mean the same thing.
A different kind of entries is used for translations which involve plural forms.
white-space
# translator-comments
#. extracted-comments
#: reference...
#, flag...
#| msgid previous-untranslated-string-singular
#| msgid_plural previous-untranslated-string-plural
msgid untranslated-string-singular
msgid_plural untranslated-string-plural
msgstr[0] translated-string-case-0
...
msgstr[N] translated-string-case-n
Such an entry can look like this:
#: src/msgcmp.c:338 src/po-lex.c:699
#, c-format
msgid "found %d fatal error"
msgid_plural "found %d fatal errors"
msgstr[0] "s'ha trobat %d error fatal"
msgstr[1] "s'han trobat %d errors fatals"
Here also, a msgctxt context can be specified before msgid,
like above.
The previous-untranslated-string is optionally inserted by the
msgmerge program, at the same time when it marks a message fuzzy.
It helps the translator to see which changes were done by the developers
on the untranslated-string.
It happens that some lines, usually whitespace or comments, follow the very last entry of a PO file. Such lines are not part of any entry, and will be dropped when the PO file is processed by the tools, or may disturb some PO file editors.
The remainder of this section may be safely skipped by those using a PO file editor, yet it may be interesting for everybody to have a better idea of the precise format of a PO file. On the other hand, those wishing to modify PO files by hand should carefully continue reading on.
Each of untranslated-string and translated-string respects the C syntax for a character string, including the surrounding quotes and embedded backslashed escape sequences. When the time comes to write multi-line strings, one should not use escaped newlines. Instead, a closing quote should follow the last character on the line to be continued, and an opening quote should resume the string at the beginning of the following PO file line. For example:
msgid ""
"Here is an example of how one might continue a very long string\n"
"for the common case the string represents multi-line output.\n"
In this example, the empty string is used on the first line, to
allow better alignment of the H from the word ‘Here’
over the f from the word ‘for’. In this example, the
msgid keyword is followed by three strings, which are meant
to be concatenated. Concatenating the empty string does not change
the resulting overall string, but it is a way for us to comply with
the necessity of msgid to be followed by a string on the same
line, while keeping the multi-line presentation left-justified, as
we find this to be a cleaner disposition. The empty string could have
been omitted, but only if the string starting with ‘Here’ was
promoted on the first line, right after msgid.2 It was not really necessary
either to switch between the two last quoted strings immediately after
the newline ‘\n’, the switch could have occurred after any
other character, we just did it this way because it is neater.
One should carefully distinguish between end of lines marked as ‘\n’ inside quotes, which are part of the represented string, and end of lines in the PO file itself, outside string quotes, which have no incidence on the represented string.
Outside strings, white lines and comments may be used freely.
Comments start at the beginning of a line with ‘#’ and extend
until the end of the PO file line. Comments written by translators
should have the initial ‘#’ immediately followed by some white
space. If the ‘#’ is not immediately followed by white space,
this comment is most likely generated and managed by specialized GNU
tools, and might disappear or be replaced unexpectedly when the PO
file is given to msgmerge.
For the programmer, changes to the C source code fall into three
categories. First, you have to make the localization functions
known to all modules needing message translation. Second, you should
properly trigger the operation of GNU gettext when the program
initializes, usually from the main function. Last, you should
identify, adjust and mark all constant strings in your program
needing translation.
gettext declarationPresuming that your set of programs, or package, has been adjusted
so all needed GNU gettext files are available, and your
Makefile files are adjusted (see Maintainers), each C module
having translated C strings should contain the line:
#include <libintl.h>
Similarly, each C module containing printf()/fprintf()/...
calls with a format string that could be a translated C string (even if
the C string comes from a different C module) should contain the line:
#include <libintl.h>
gettext OperationsThe initialization of locale data should be done with more or less the same code in every program, as demonstrated below:
int
main (int argc, char *argv[])
{
...
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
...
}
PACKAGE and LOCALEDIR should be provided either by
config.h or by the Makefile. For now consult the gettext
or hello sources for more information.
The use of LC_ALL might not be appropriate for you.
LC_ALL includes all locale categories and especially
LC_CTYPE. This latter category is responsible for determining
character classes with the isalnum etc. functions from
ctype.h which could especially for programs, which process some
kind of input language, be wrong. For example this would mean that a
source code using the ç (c-cedilla character) is runnable in
France but not in the U.S.
Some systems also have problems with parsing numbers using the
scanf functions if an other but the LC_ALL locale category is
used. The standards say that additional formats but the one known in the
"C" locale might be recognized. But some systems seem to reject
numbers in the "C" locale format. In some situation, it might
also be a problem with the notation itself which makes it impossible to
recognize whether the number is in the "C" locale or the local
format. This can happen if thousands separator characters are used.
Some locales define this character according to the national
conventions to '.' which is the same character used in the
"C" locale to denote the decimal point.
So it is sometimes necessary to replace the LC_ALL line in the
code above by a sequence of setlocale lines
{
...
setlocale (LC_CTYPE, "");
setlocale (LC_MESSAGES, "");
...
}
On all POSIX conformant systems the locale categories LC_CTYPE,
LC_MESSAGES, LC_COLLATE, LC_MONETARY,
LC_NUMERIC, and LC_TIME are available. On some systems
which are only ISO C compliant, LC_MESSAGES is missing, but
a substitute for it is defined in GNU gettext's <libintl.h> and
in GNU gnulib's <locale.h>.
Note that changing the LC_CTYPE also affects the functions
declared in the <ctype.h> standard header and some functions
declared in the <string.h> and <stdlib.h> standard headers.
If this is not
desirable in your application (for example in a compiler's parser),
you can use a set of substitute functions which hardwire the C locale,
such as found in the modules ‘c-ctype’, ‘c-strcase’,
‘c-strcasestr’, ‘c-strtod’, ‘c-strtold’ in the GNU gnulib
source distribution.
It is also possible to switch the locale forth and back between the
environment dependent locale and the C locale, but this approach is
normally avoided because a setlocale call is expensive,
because it is tedious to determine the places where a locale switch
is needed in a large program's source, and because switching a locale
is not multithread-safe.
Before strings can be marked for translations, they sometimes need to be adjusted. Usually preparing a string for translation is done right before marking it, during the marking phase which is described in the next sections. What you have to keep in mind while doing that is the following.
Let's look at some examples of these guidelines.
Translatable strings should be in good English style. If slang language with abbreviations and shortcuts is used, often translators will not understand the message and will produce very inappropriate translations.
"%s: is parameter\n"
This is nearly untranslatable: Is the displayed item a parameter or the parameter?
"No match"
The ambiguity in this message makes it unintelligible: Is the program attempting to set something on fire? Does it mean "The given object does not match the template"? Does it mean "The template does not fit for any of the objects"?
In both cases, adding more words to the message will help both the translator and the English speaking user.
Translatable strings should be entire sentences. It is often not possible to translate single verbs or adjectives in a substitutable way.
printf ("File %s is %s protected", filename, rw ? "write" : "read");
Most translators will not look at the source and will thus only see the
string "File %s is %s protected", which is unintelligible. Change
this to
printf (rw ? "File %s is write protected" : "File %s is read protected",
filename);
This way the translator will not only understand the message, she will also be able to find the appropriate grammatical construction. A French translator for example translates "write protected" like "protected against writing".
Entire sentences are also important because in many languages, the declination of some word in a sentence depends on the gender or the number (singular/plural) of another part of the sentence. There are usually more interdependencies between words than in English. The consequence is that asking a translator to translate two half-sentences and then combining these two half-sentences through dumb string concatenation will not work, for many languages, even though it would work for English. That's why translators need to handle entire sentences.
Often sentences don't fit into a single line. If a sentence is output
using two subsequent printf statements, like this
printf ("Locale charset \"%s\" is different from\n", lcharset);
printf ("input file charset \"%s\".\n", fcharset);
the translator would have to translate two half sentences, but nothing
in the POT file would tell her that the two half sentences belong together.
It is necessary to merge the two printf statements so that the
translator can handle the entire sentence at once and decide at which
place to insert a line break in the translation (if at all):
printf ("Locale charset \"%s\" is different from\n\
input file charset \"%s\".\n", lcharset, fcharset);
You may now ask: how about two or more adjacent sentences? Like in this case:
puts ("Apollo 13 scenario: Stack overflow handling failed.");
puts ("On the next stack overflow we will crash!!!");
Should these two statements merged into a single one? I would recommend to merge them if the two sentences are related to each other, because then it makes it easier for the translator to understand and translate both. On the other hand, if one of the two messages is a stereotypic one, occurring in other places as well, you will do a favour to the translator by not merging the two. (Identical messages occurring in several places are combined by xgettext, so the translator has to handle them once only.)
Translatable strings should be limited to one paragraph; don't let a single message be longer than ten lines. The reason is that when the translatable string changes, the translator is faced with the task of updating the entire translated string. Maybe only a single word will have changed in the English string, but the translator doesn't see that (with the current translation tools), therefore she has to proofread the entire message.
Many GNU programs have a ‘--help’ output that extends over several screen pages. It is a courtesy towards the translators to split such a message into several ones of five to ten lines each. While doing that, you can also attempt to split the documented options into groups, such as the input options, the output options, and the informative output options. This will help every user to find the option he is looking for.
Hardcoded string concatenation is sometimes used to construct English strings:
strcpy (s, "Replace ");
strcat (s, object1);
strcat (s, " with ");
strcat (s, object2);
strcat (s, "?");
In order to present to the translator only entire sentences, and also
because in some languages the translator might want to swap the order
of object1 and object2, it is necessary to change this
to use a format string:
sprintf (s, "Replace %s with %s?", object1, object2);
A similar case is compile time concatenation of strings. The ISO C 99
include file <inttypes.h> contains a macro PRId64 that
can be used as a formatting directive for outputting an ‘int64_t’
integer through printf. It expands to a constant string, usually
"d" or "ld" or "lld" or something like this, depending on the platform.
Assume you have code like
printf ("The amount is %0" PRId64 "\n", number);
The gettext tools and library have special support for these
<inttypes.h> macros. You can therefore simply write
printf (gettext ("The amount is %0" PRId64 "\n"), number);
The PO file will contain the string "The amount is %0<PRId64>\n".
The translators will provide a translation containing "%0<PRId64>"
as well, and at runtime the gettext function's result will
contain the appropriate constant string, "d" or "ld" or "lld".
This works only for the predefined <inttypes.h> macros. If
you have defined your own similar macros, let's say ‘MYPRId64’,
that are not known to xgettext, the solution for this problem
is to change the code like this:
char buf1[100];
sprintf (buf1, "%0" MYPRId64, number);
printf (gettext ("The amount is %s\n"), buf1);
This means, you put the platform dependent code in one statement, and the internationalization code in a different statement. Note that a buffer length of 100 is safe, because all available hardware integer types are limited to 128 bits, and to print a 128 bit integer one needs at most 54 characters, regardless whether in decimal, octal or hexadecimal.
All this applies to other programming languages as well. For example, in Java and C#, string concatenation is very frequently used, because it is a compiler built-in operator. Like in C, in Java, you would change
System.out.println("Replace "+object1+" with "+object2+"?");
into a statement involving a format string:
System.out.println(
MessageFormat.format("Replace {0} with {1}?",
new Object[] { object1, object2 }));
Similarly, in C#, you would change
Console.WriteLine("Replace "+object1+" with "+object2+"?");
into a statement involving a format string:
Console.WriteLine(
String.Format("Replace {0} with {1}?", object1, object2));
Unusual markup or control characters should not be used in translatable strings. Translators will likely not understand the particular meaning of the markup or control characters.
For example, if you have a convention that ‘|’ delimits the left-hand and right-hand part of some GUI elements, translators will often not understand it without specific comments. It might be better to have the translator translate the left-hand and right-hand part separately.
Another example is the ‘argp’ convention to use a single ‘\v’ (vertical tab) control character to delimit two sections inside a string. This is flawed. Some translators may convert it to a simple newline, some to blank lines. With some PO file editors it may not be easy to even enter a vertical tab control character. So, you cannot be sure that the translation will contain a ‘\v’ character, at the corresponding position. The solution is, again, to let the translator translate two separate strings and combine at run-time the two translated strings with the ‘\v’ required by the convention.
HTML markup, however, is common enough that it's probably ok to use in translatable strings. But please bear in mind that the GNU gettext tools don't verify that the translations are well-formed HTML.
All strings requiring translation should be marked in the C sources. Marking
is done in such a way that each translatable string appears to be
the sole argument of some function or preprocessor macro. There are
only a few such possible functions or macros meant for translation,
and their names are said to be marking keywords. The marking is
attached to strings themselves, rather than to what we do with them.
This approach has more uses. A blatant example is an error message
produced by formatting. The format string needs translation, as
well as some strings inserted through some ‘%s’ specification
in the format, while the result from sprintf may have so many
different instances that it is impractical to list them all in some
‘error_string_out()’ routine, say.
This marking operation has two goals. The first goal of marking is for triggering the retrieval of the translation, at run time. The keyword is possibly resolved into a routine able to dynamically return the proper translation, as far as possible or wanted, for the argument string. Most localizable strings are found in executable positions, that is, attached to variables or given as parameters to functions. But this is not universal usage, and some translatable strings appear in structured initializations. See Special cases.
The second goal of the marking operation is to help xgettext
at properly extracting all translatable strings when it scans a set
of program sources and produces PO file templates.
The canonical keyword for marking translatable strings is
‘gettext’, it gave its name to the whole GNU gettext
package. For packages making only light use of the ‘gettext’
keyword, macro or function, it is easily used as is. However,
for packages using the gettext interface more heavily, it
is usually more convenient to give the main keyword a shorter, less
obtrusive name. Indeed, the keyword might appear on a lot of strings
all over the package, and programmers usually do not want nor need
their program sources to remind them forcefully, all the time, that they
are internationalized. Further, a long keyword has the disadvantage
of using more horizontal space, forcing more indentation work on
sources for those trying to keep them within 79 or 80 columns.
Many packages use ‘_’ (a simple underline) as a keyword,
and write ‘_("Translatable string")’ instead of ‘gettext
("Translatable string")’. Further, the coding rule, from GNU standards,
wanting that there is a space between the keyword and the opening
parenthesis is relaxed, in practice, for this particular usage.
So, the textual overhead per translatable string is reduced to
only three characters: the underline and the two parentheses.
However, even if GNU gettext uses this convention internally,
it does not offer it officially. The real, genuine keyword is truly
‘gettext’ indeed. It is fairly easy for those wanting to use
‘_’ instead of ‘gettext’ to declare:
#include <libintl.h>
#define _(String) gettext (String)
instead of merely using ‘#include <libintl.h>’.
The marking keywords ‘gettext’ and ‘_’ take the translatable
string as sole argument. It is also possible to define marking functions
that take it at another argument position. It is even possible to make
the marked argument position depend on the total number of arguments of
the function call; this is useful in C++. All this is achieved using
xgettext's ‘--keyword’ option.
Note also that long strings can be split across lines, into multiple
adjacent string tokens. Automatic string concatenation is performed
at compile time according to ISO C and ISO C++; xgettext also
supports this syntax.
Later on, the maintenance is relatively easy. If, as a programmer, you add or modify a string, you will have to ask yourself if the new or altered string requires translation, and include it within ‘_()’ if you think it should be translated. For example, ‘"%s"’ is an example of string not requiring translation. But ‘"%s: %d"’ does require translation, because in French, unlike in English, it's customary to put a space before a colon.
In PO mode, one set of features is meant more for the programmer than for the translator, and allows him to interactively mark which strings, in a set of program sources, are translatable, and which are not. Even if it is a fairly easy job for a programmer to find and mark such strings by other means, using any editor of his choice, PO mode makes this work more comfortable. Further, this gives translators who feel a little like programmers, or programmers who feel a little like translators, a tool letting them work at marking translatable strings in the program sources, while simultaneously producing a set of translation in some language, for the package being internationalized.
The set of program sources, targeted by the PO mode commands describe here, should have an Emacs tags table constructed for your project, prior to using these PO file commands. This is easy to do. In any shell window, change the directory to the root of your project, then execute a command resembling:
etags src/*.[hc] lib/*.[hc]
presuming here you want to process all .h and .c files from the src/ and lib/ directories. This command will explore all said files and create a TAGS file in your root directory, somewhat summarizing the contents using a special file format Emacs can understand.
For packages following the GNU coding standards, there is
a make goal tags or TAGS which constructs the tag files in
all directories and for all files containing source code.
Once your TAGS file is ready, the following commands assist the programmer at marking translatable strings in his set of sources. But these commands are necessarily driven from within a PO file window, and it is likely that you do not even have such a PO file yet. This is not a problem at all, as you may safely open a new, empty PO file, mainly for using these commands. This empty PO file will slowly fill in while you mark strings as translatable in your program sources.
po-tags-search).
po-mark-translatable).
po-select-mark-and-mark).
The , (po-tags-search) command searches for the next
occurrence of a string which looks like a possible candidate for
translation, and displays the program source in another Emacs window,
positioned in such a way that the string is near the top of this other
window. If the string is too big to fit whole in this window, it is
positioned so only its end is shown. In any case, the cursor
is left in the PO file window. If the shown string would be better
presented differently in different native languages, you may mark it
using M-, or M-.. Otherwise, you might rather ignore it
and skip to the next string by merely repeating the , command.
A string is a good candidate for translation if it contains a sequence of three or more letters. A string containing at most two letters in a row will be considered as a candidate if it has more letters than non-letters. The command disregards strings containing no letters, or isolated letters only. It also disregards strings within comments, or strings already marked with some keyword PO mode knows (see below).
If you have never told Emacs about some TAGS file to use, the command will request that you specify one from the minibuffer, the first time you use the command. You may later change your TAGS file by using the regular Emacs command M-x visit-tags-table, which will ask you to name the precise TAGS file you want to use. See Tag Tables.
Each time you use the , command, the search resumes from where it was left by the previous search, and goes through all program sources, obeying the TAGS file, until all sources have been processed. However, by giving a prefix argument to the command (C-u ,), you may request that the search be restarted all over again from the first program source; but in this case, strings that you recently marked as translatable will be automatically skipped.
Using this , command does not prevent using of other regular
Emacs tags commands. For example, regular tags-search or
tags-query-replace commands may be used without disrupting the
independent , search sequence. However, as implemented, the
initial , command (or the , command is used with a
prefix) might also reinitialize the regular Emacs tags searching to the
first tags file, this reinitialization might be considered spurious.
The M-, (po-mark-translatable) command will mark the
recently found string with the ‘_’ keyword. The M-.
(po-select-mark-and-mark) command will request that you type
one keyword from the minibuffer and use that keyword for marking
the string. Both commands will automatically create a new PO file
untranslated entry for the string being marked, and make it the
current entry (making it easy for you to immediately proceed to its
translation, if you feel like doing it right away). It is possible
that the modifications made to the program source by M-, or
M-. render some source line longer than 80 columns, forcing you
to break and re-indent this line differently. You may use the O
command from PO mode, or any other window changing command from
Emacs, to break out into the program source window, and do any
needed adjustments. You will have to use some regular Emacs command
to return the cursor to the PO file window, if you want command
, for the next string, say.
The M-. command has a few built-in speedups, so you do not have to explicitly type all keywords all the time. The first such speedup is that you are presented with a preferred keyword, which you may accept by merely typing <RET> at the prompt. The second speedup is that you may type any non-ambiguous prefix of the keyword you really mean, and the command will complete it automatically for you. This also means that PO mode has to know all your possible keywords, and that it will not accept mistyped keywords.
If you reply ? to the keyword request, the command gives a list of all known keywords, from which you may choose. When the command is prefixed by an argument (C-u M-.), it inhibits updating any program source or PO file buffer, and does some simple keyword management instead. In this case, the command asks for a keyword, written in full, which becomes a new allowed keyword for later M-. commands. Moreover, this new keyword automatically becomes the preferred keyword for later commands. By typing an already known keyword in response to C-u M-., one merely changes the preferred keyword and does nothing more.
All keywords known for M-. are recognized by the , command when scanning for strings, and strings already marked by any of those known keywords are automatically skipped. If many PO files are opened simultaneously, each one has its own independent set of known keywords. There is no provision in PO mode, currently, for deleting a known keyword, you have to quit the file (maybe using q) and reopen it afresh. When a PO file is newly brought up in an Emacs window, only ‘gettext’ and ‘_’ are known as keywords, and ‘gettext’ is preferred for the M-. command. In fact, this is not useful to prefer ‘_’, as this one is already built in the M-, command.
In C programs strings are often used within calls of functions from the
printf family. The special thing about these format strings is
that they can contain format specifiers introduced with %. Assume
we have the code
printf (gettext ("String `%s' has %d characters\n"), s, strlen (s));
A possible German translation for the above string might be:
"%d Zeichen lang ist die Zeichenkette `%s'"
A C programmer, even if he cannot speak German, will recognize that
there is something wrong here. The order of the two format specifiers
is changed but of course the arguments in the printf don't have.
This will most probably lead to problems because now the length of the
string is regarded as the address.
To prevent errors at runtime caused by translations the msgfmt
tool can check statically whether the arguments in the original and the
translation string match in type and number. If this is not the case
and the ‘-c’ option has been passed to msgfmt, msgfmt
will give an error and refuse to produce a MO file. Thus consequent
use of ‘msgfmt -c’ will catch the error, so that it cannot cause
cause problems at runtime.
If the word order in the above German translation would be correct one would have to write
"%2$d Zeichen lang ist die Zeichenkette `%1$s'"
The routines in msgfmt know about this special notation.
Because not all strings in a program must be format strings it is not
useful for msgfmt to test all the strings in the .po file.
This might cause problems because the string might contain what looks
like a format specifier, but the string is not used in printf.
Therefore the xgettext adds a special tag to those messages it
thinks might be a format string. There is no absolute rule for this,
only a heuristic. In the .po file the entry is marked using the
c-format flag in the #, comment line (see PO Files).
The careful reader now might say that this again can cause problems.
The heuristic might guess it wrong. This is true and therefore
xgettext knows about a special kind of comment which lets
the programmer take over the decision. If in the same line as or
the immediately preceding line to the gettext keyword
the xgettext program finds a comment containing the words
xgettext:c-format, it will mark the string in any case with
the c-format flag. This kind of comment should be used when
xgettext does not recognize the string as a format string but
it really is one and it should be tested. Please note that when the
comment is in the same line as the gettext keyword, it must be
before the string to be translated.
This situation happens quite often. The printf function is often
called with strings which do not contain a format specifier. Of course
one would normally use fputs but it does happen. In this case
xgettext does not recognize this as a format string but what
happens if the translation introduces a valid format specifier? The
printf function will try to access one of the parameters but none
exists because the original code does not pass any parameters.
xgettext of course could make a wrong decision the other way
round, i.e. a string marked as a format string actually is not a format
string. In this case the msgfmt might give too many warnings and
would prevent translating the .po file. The method to prevent
this wrong decision is similar to the one used above, only the comment
to use must contain the string xgettext:no-c-format.
If a string is marked with c-format and this is not correct the
user can find out who is responsible for the decision. See
xgettext Invocation to see how the --debug option can be
used for solving this problem.
The attentive reader might now point out that it is not always possible
to mark translatable string with gettext or something like this.
Consider the following case:
{
static const char *messages[] = {
"some very meaningful message",
"and another one"
};
const char *string;
...
string
= index > 1 ? "a default message" : messages[index];
fputs (string);
...
}
While it is no problem to mark the string "a default message" it
is not possible to mark the string initializers for messages.
What is to be done? We have to fulfill two tasks. First we have to mark the
strings so that the xgettext program (see xgettext Invocation)
can find them, and second we have to translate the string at runtime
before printing them.
The first task can be fulfilled by creating a new keyword, which names a no-op. For the second we have to mark all access points to a string from the array. So one solution can look like this:
#define gettext_noop(String) String
{
static const char *messages[] = {
gettext_noop ("some very meaningful message"),
gettext_noop ("and another one")
};
const char *string;
...
string
= index > 1 ? gettext ("a default message") : gettext (messages[index]);
fputs (string);
...
}
Please convince yourself that the string which is written by
fputs is translated in any case. How to get xgettext know
the additional keyword gettext_noop is explained in xgettext Invocation.
The above is of course not the only solution. You could also come along with the following one:
#define gettext_noop(String) String
{
static const char *messages[] = {
gettext_noop ("some very meaningful message",
gettext_noop ("and another one")
};
const char *string;
...
string
= index > 1 ? gettext_noop ("a default message") : messages[index];
fputs (gettext (string));
...
}
But this has a drawback. The programmer has to take care that
he uses gettext_noop for the string "a default message".
A use of gettext could have in rare cases unpredictable results.
One advantage is that you need not make control flow analysis to make sure the output is really translated in any case. But this analysis is generally not very difficult. If it should be in any situation you can use this second method in this situation.
Code sometimes has bugs, but translations sometimes have bugs too. The users need to be able to report them. Reporting translation bugs to the programmer or maintainer of a package is not very useful, since the maintainer must never change a translation, except on behalf of the translator. Hence the translation bugs must be reported to the translators.
Here is a way to organize this so that the maintainer does not need to forward translation bug reports, nor even keep a list of the addresses of the translators or their translation teams.
Every program has a place where is shows the bug report address. For GNU programs, it is the code which handles the “–help” option, typically in a function called “usage”. In this place, instruct the translator to add her own bug reporting address. For example, if that code has a statement
printf (_("Report bugs to <%s>.\n"), PACKAGE_BUGREPORT);
you can add some translator instructions like this:
/* TRANSLATORS: The placeholder indicates the bug-reporting address
for this package. Please add _another line_ saying
"Report translation bugs to <...>\n" with the address for translation
bugs (typically your translation team's web or email address). */
printf (_("Report bugs to <%s>.\n"), PACKAGE_BUGREPORT);
These will be extracted by ‘xgettext’, leading to a .pot file that contains this:
#. TRANSLATORS: The placeholder indicates the bug-reporting address
#. for this package. Please add _another line_ saying
#. "Report translation bugs to <...>\n" with the address for translation
#. bugs (typically your translation team's web or email address).
#: src/hello.c:178
#, c-format
msgid "Report bugs to <%s>.\n"
msgstr ""
Should names of persons, cities, locations etc. be marked for translation or not? People who only know languages that can be written with Latin letters (English, Spanish, French, German, etc.) are tempted to say “no”, because names usually do not change when transported between these languages. However, in general when translating from one script to another, names are translated too, usually phonetically or by transliteration. For example, Russian or Greek names are converted to the Latin alphabet when being translated to English, and English or French names are converted to the Katakana script when being translated to Japanese. This is necessary because the speakers of the target language in general cannot read the script the name is originally written in.
As a programmer, you should therefore make sure that names are marked for translation, with a special comment telling the translators that it is a proper name and how to pronounce it. Like this:
printf (_("Written by %s.\n"),
/* TRANSLATORS: This is a proper name. See the gettext
manual, section Names. Note this is actually a non-ASCII
name: The first name is (with Unicode escapes)
"Fran\u00e7ois" or (with HTML entities) "François".
Pronunciation is like "fraa-swa pee-nar". */
_("Francois Pinard"));
As a translator, you should use some care when translating names, because it is frustrating if people see their names mutilated or distorted. If your language uses the Latin script, all you need to do is to reproduce the name as perfectly as you can within the usual character set of your language. In this particular case, this means to provide a translation containing the c-cedilla character. If your language uses a different script and the people speaking it don't usually read Latin words, it means transliteration; but you should still give, in parentheses, the original writing of the name – for the sake of the people that do read the Latin script. Here is an example, using Greek as the target script:
#. This is a proper name. See the gettext
#. manual, section Names. Note this is actually a non-ASCII
#. name: The first name is (with Unicode escapes)
#. "Fran\u00e7ois" or (with HTML entities) "François".
#. Pronunciation is like "fraa-swa pee-nar".
msgid "Francois Pinard"
msgstr "\phi\rho\alpha\sigma\omicron\alpha \pi\iota\nu\alpha\rho"
" (Francois Pinard)"
Because translation of names is such a sensitive domain, it is a good idea to test your translation before submitting it.
The translation project http://sourceforge.net/projects/translation has set up a POT file and translation domain consisting of program author names, with better facilities for the translator than those presented here. Namely, there the original name is written directly in Unicode (rather than with Unicode escapes or HTML entities), and the pronunciation is denoted using the International Phonetic Alphabet (see http://www.wikipedia.org/wiki/International_Phonetic_Alphabet).
However, we don't recommend this approach for all POT files in all packages, because this would force translators to use PO files in UTF-8 encoding, which is - in the current state of software (as of 2003) - a major hassle for translators using GNU Emacs or XEmacs with po-mode.
When you are preparing a library, not a program, for the use of
gettext, only a few details are different. Here we assume that
the library has a translation domain and a POT file of its own. (If
it uses the translation domain and POT file of the main program, then
the previous sections apply without changes.)
setlocale (LC_ALL, ""). It's the
responsibility of the main program to set the locale. The library's
documentation should mention this fact, so that developers of programs
using the library are aware of it.
textdomain (PACKAGE), because it
would interfere with the text domain set by the main program.
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
For a library it is reduced to
bindtextdomain (PACKAGE, LOCALEDIR);
If your library's API doesn't already have an initialization function,
you need to create one, containing at least the bindtextdomain
invocation. However, you usually don't need to export and document this
initialization function: It is sufficient that all entry points of the
library call the initialization function if it hasn't been called before.
The typical idiom used to achieve this is a static boolean variable that
indicates whether the initialization function has been called. Like this:
static bool libfoo_initialized;
static void
libfoo_initialize (void)
{
bindtextdomain (PACKAGE, LOCALEDIR);
libfoo_initialized = true;
}
/* This function is part of the exported API. */
struct foo *
create_foo (...)
{
/* Must ensure the initialization is performed. */
if (!libfoo_initialized)
libfoo_initialize ();
...
}
/* This function is part of the exported API. The argument must be
non-NULL and have been created through create_foo(). */
int
foo_refcount (struct foo *argument)
{
/* No need to invoke the initialization function here, because
create_foo() must already have been called before. */
...
}
#include <libintl.h>
#define _(String) gettext (String)
for a program. For a library, which has its own translation domain, it reads like this:
#include <libintl.h>
#define _(String) dgettext (PACKAGE, String)
In other words, dgettext is used instead of gettext.
Similarly, the dngettext function should be used in place of the
ngettext function.
After preparing the sources, the programmer creates a PO template file.
This section explains how to use xgettext for this purpose.
xgettext creates a file named domainname.po. You
should then rename it to domainname.pot. (Why doesn't
xgettext create it under the name domainname.pot
right away? The answer is: for historical reasons. When xgettext
was specified, the distinction between a PO file and PO file template
was fuzzy, and the suffix ‘.pot’ wasn't in use at that time.)
xgettext Programxgettext [option] [inputfile] ...
The xgettext program extracts translatable strings from given
input files.
If inputfile is ‘-’, standard input is read.
If the output file is ‘-’ or ‘/dev/stdout’, the output is written to standard output.
C, C++, ObjectiveC, PO, Python,
Lisp, EmacsLisp, librep, Scheme, Smalltalk,
Java, JavaProperties, C#, awk, YCP,
Tcl, Perl, PHP, GCC-source, NXStringTable,
RST, Glade.
--language=C++.
By default the language is guessed depending on the input file name extension.
By default the input files are assumed to be in ASCII.
This option has an effect with most languages, namely C, C++, ObjectiveC,
Shell, Python, Lisp, EmacsLisp, librep, Java, C#, awk, Tcl, Perl, PHP,
GCC-source, Glade.
If keywordspec is a C identifier id, xgettext looks
for strings in the first argument of each call to the function or macro
id. If keywordspec is of the form
‘id:argnum’, xgettext looks for strings in the
argnumth argument of the call. If keywordspec is of the form
‘id:argnum1,argnum2’, xgettext looks for
strings in the argnum1st argument and in the argnum2nd argument
of the call, and treats them as singular/plural variants for a message
with plural handling. Also, if keywordspec is of the form
‘id:contextargnumc,argnum’ or
‘id:argnum,contextargnumc’, xgettext treats
strings in the contextargnumth argument as a context specifier.
And, as a special-purpose support for GNOME, if keywordspec is of the
form ‘id:argnumg’, xgettext recognizes the
argnumth argument as a string with context, using the GNOME glib
syntax ‘"msgctxt|msgid"’.
Furthermore, if keywordspec is of the form
‘id:...,totalnumargst’, xgettext recognizes this
argument specification only if the number of actual arguments is equal to
totalnumargs. This is useful for disambiguating overloaded function
calls in C++.
Finally, if keywordspec is of the form
‘id:argnum...,"xcomment"’, xgettext, when
extracting a message from the specified argument strings, adds an extracted
comment xcomment to the message. Note that when used through a normal
shell command line, the double-quotes around the xcomment need to be
escaped.
This option has an effect with most languages, namely C, C++, ObjectiveC, Shell, Python, Lisp, EmacsLisp, librep, Java, C#, awk, Tcl, Perl, PHP, GCC-source, Glade.
The default keyword specifications, which are always looked for if not explicitly disabled, are language dependent. They are:
gettext, dgettext:2,
dcgettext:2, ngettext:1,2, dngettext:2,3,
dcngettext:2,3, gettext_noop, and pgettext:1c,2,
dpgettext:2c,3, dcpgettext:2c,3, npgettext:1c,2,3,
dnpgettext:2c,3,4, dcnpgettext:2c,3,4.
NSLocalizedString, _,
NSLocalizedStaticString, __.
gettext, ngettext:1,2, eval_gettext,
eval_ngettext:1,2.
gettext, ugettext, dgettext:2,
ngettext:1,2, ungettext:1,2, dngettext:2,3, _.
gettext, ngettext:1,2, gettext-noop.
_.
_.
gettext, ngettext:1,2, gettext-noop.
GettextResource.gettext:2,
GettextResource.ngettext:2,3, GettextResource.pgettext:2c,3,
GettextResource.npgettext:2c,3,4, gettext, ngettext:1,2,
pgettext:1c,2, npgettext:1c,2,3, getString.
GetString, GetPluralString:1,2,
GetParticularString:1c,2, GetParticularPluralString:1c,2,3.
dcgettext, dcngettext:1,2.
::msgcat::mc.
gettext, %gettext, $gettext, dgettext:2,
dcgettext:2, ngettext:1,2, dngettext:2,3,
dcngettext:2,3, gettext_noop.
_, gettext, dgettext:2, dcgettext:2,
ngettext:1,2, dngettext:2,3, dcngettext:2,3.
label, title, text, format,
copyright, comments, preview_text, tooltip.
To disable the default keyword specifications, the option ‘-k’ or
‘--keyword’ or ‘--keyword=’, without a keywordspec, can be
used.
--flag=function:arg:lang-format
is that in language lang, the specified function expects as
argth argument a format string. (For those of you familiar with
GCC function attributes, --flag=function:arg:c-format is
roughly equivalent to the declaration
‘__attribute__ ((__format__ (__printf__, arg, ...)))’ attached
to function in a C source file.)
For example, if you use the ‘error’ function from GNU libc, you can
specify its behaviour through --flag=error:3:c-format. The effect of
this specification is that xgettext will mark as format strings all
gettext invocations that occur as argth argument of
function.
This is useful when such strings contain no format string directives:
together with the checks done by ‘msgfmt -c’ it will ensure that
translators cannot accidentally use format string directives that would
lead to a crash at runtime.
--flag=function:arg:pass-lang-format
is that in language lang, if the function call occurs in a
position that must yield a format string, then its argth argument
must yield a format string of the same type as well. (If you know GCC
function attributes, the --flag=function:arg:pass-c-format
option is roughly equivalent to the declaration
‘__attribute__ ((__format_arg__ (arg)))’ attached to function
in a C source file.)
For example, if you use the ‘_’ shortcut for the gettext function,
you should use --flag=_:1:pass-c-format. The effect of this
specification is that xgettext will propagate a format string
requirement for a _("string") call to its first argument, the literal
"string", and thus mark it as a format string.
This is useful when such strings contain no format string directives:
together with the checks done by ‘msgfmt -c’ it will ensure that
translators cannot accidentally use format string directives that would
lead to a crash at runtime.
c-format and possible-c-format to show who was
responsible for marking a message as a format string. The latter form is
used if the xgettext program decided, the format form is used if
the programmer prescribed it.
By default only the c-format form is used. The translator should
not have to care about these details.
This implementation of xgettext is able to process a few awkward
cases, like strings in preprocessor macros, ANSI concatenation of
adjacent strings, and escaped end of lines for continued strings.
.properties syntax. Note
that this file format doesn't support plural forms and silently drops
obsolete messages.
.strings syntax.
Note that this file format doesn't support plural forms.
This is useful for testing purposes because it eliminates a source
of variance for generated .gmo files. With --omit-header,
two invocations of xgettext on the same files with the same
options at different times are guaranteed to produce the same results.
Note that using this option will lead to an error if the resulting file
would not entirely be in ASCII.
The default value for string is the Free Software Foundation, Inc.,
simply because xgettext was first used in the GNU project.
It can be your email address, or a mailing list address where translators can write to without being subscribed, or the URL of a web page through which the translators can contact you.
The default value is empty, which means that translators will be clueless!
Don't forget to specify this option.
When starting a new translation, the translator creates a file called LANG.po, as a copy of the package.pot template file with modifications in the initial comments (at the beginning of the file) and in the header entry (the first entry, near the beginning of the file).
The easiest way to do so is by use of the ‘msginit’ program. For example:
$ cd PACKAGE-VERSION
$ cd po
$ msginit
The alternative way is to do the copy and modifications by hand. To do so, the translator copies package.pot to LANG.po. Then she modifies the initial comments and the header entry of this file.
msginit Programmsginit [option]
The msginit program creates a new PO file, initializing the meta
information with values from the user's environment.
If no inputfile is given, the current directory is searched for the POT file. If it is ‘-’, standard input is read.
If no output file is given, it depends on the ‘--locale’ option or the user's locale setting. If it is ‘-’, the results are written to standard output.
.properties
syntax, not in PO file syntax.
.strings syntax, not in PO file syntax.
.properties syntax. Note
that this file format doesn't support plural forms and silently drops
obsolete messages.
.strings syntax.
Note that this file format doesn't support plural forms.
The initial comments "SOME DESCRIPTIVE TITLE", "YEAR" and "FIRST AUTHOR <EMAIL@ADDRESS>, YEAR" ought to be replaced by sensible information. This can be done in any text editor; if Emacs is used and it switched to PO mode automatically (because it has recognized the file's suffix), you can disable it by typing M-x fundamental-mode.
Modifying the header entry can already be done using PO mode: in Emacs, type M-x po-mode RET and then RET again to start editing the entry. You should fill in the following fields.
xgettext.
xgettext. It contains an email
address or URL where you can report bugs in the untranslated strings:
xgettext.
Before starting a translation, it is a good idea to get in touch with your translation team, not only to make sure you don't do duplicated work, but also to coordinate difficult linguistic issues.
In the Free Translation Project, each translation team has its own mailing
list. The up-to-date list of teams can be found at the Free Translation
Project's homepage, http://translationproject.org/, in the "Teams"
area.
msgmerge and msgfmt programs, as well as for users whose
locale's character encoding differs from yours (see Charset conversion).
You get the character encoding of your locale by running the shell command ‘locale charmap’. If the result is ‘C’ or ‘ANSI_X3.4-1968’, which is equivalent to ‘ASCII’ (= ‘US-ASCII’), it means that your locale is not correctly configured. In this case, ask your translation team which charset to use. ‘ASCII’ is not usable for any language except Latin.
Because the PO files must be portable to operating systems with less advanced
internationalization facilities, the character encodings that can be used
are limited to those supported by both GNU libc and GNU
libiconv. These are:
ASCII, ISO-8859-1, ISO-8859-2, ISO-8859-3,
ISO-8859-4, ISO-8859-5, ISO-8859-6, ISO-8859-7,
ISO-8859-8, ISO-8859-9, ISO-8859-13, ISO-8859-14,
ISO-8859-15,
KOI8-R, KOI8-U, KOI8-T,
CP850, CP866, CP874,
CP932, CP949, CP950, CP1250, CP1251,
CP1252, CP1253, CP1254, CP1255, CP1256,
CP1257, GB2312, EUC-JP, EUC-KR, EUC-TW,
BIG5, BIG5-HKSCS, GBK, GB18030, SHIFT_JIS,
JOHAB, TIS-620, VISCII, GEORGIAN-PS, UTF-8.
In the GNU system, the following encodings are frequently used for the corresponding languages.
ISO-8859-1 for
Afrikaans, Albanian, Basque, Breton, Catalan, Cornish, Danish, Dutch,
English, Estonian, Faroese, Finnish, French, Galician, German,
Greenlandic, Icelandic, Indonesian, Irish, Italian, Malay, Manx,
Norwegian, Occitan, Portuguese, Spanish, Swedish, Tagalog, Uzbek,
Walloon,
ISO-8859-2 for
Bosnian, Croatian, Czech, Hungarian, Polish, Romanian, Serbian, Slovak,
Slovenian,
ISO-8859-3 for Maltese,
ISO-8859-5 for Macedonian, Serbian,
ISO-8859-6 for Arabic,
ISO-8859-7 for Greek,
ISO-8859-8 for Hebrew,
ISO-8859-9 for Turkish,
ISO-8859-13 for Latvian, Lithuanian, Maori,
ISO-8859-14 for Welsh,
ISO-8859-15 for
Basque, Catalan, Dutch, English, Finnish, French, Galician, German, Irish,
Italian, Portuguese, Spanish, Swedish, Walloon,
KOI8-R for Russian,
KOI8-U for Ukrainian,
KOI8-T for Tajik,
CP1251 for Bulgarian, Byelorussian,
GB2312, GBK, GB18030
for simplified writing of Chinese,
BIG5, BIG5-HKSCS
for traditional writing of Chinese,
EUC-JP for Japanese,
EUC-KR for Korean,
TIS-620 for Thai,
GEORGIAN-PS for Georgian,
UTF-8 for any language, including those listed above.
When single quote characters or double quote characters are used in translations for your language, and your locale's encoding is one of the ISO-8859-* charsets, it is best if you create your PO files in UTF-8 encoding, instead of your locale's encoding. This is because in UTF-8 the real quote characters can be represented (single quote characters: U+2018, U+2019, double quote characters: U+201C, U+201D), whereas none of ISO-8859-* charsets has them all. Users in UTF-8 locales will see the real quote characters, whereas users in ISO-8859-* locales will see the vertical apostrophe and the vertical double quote instead (because that's what the character set conversion will transliterate them to).
To enter such quote characters under X11, you can change your keyboard
mapping using the xmodmap program. The X11 names of the quote
characters are "leftsinglequotemark", "rightsinglequotemark",
"leftdoublequotemark", "rightdoublequotemark", "singlelowquotemark",
"doublelowquotemark".
Note that only recent versions of GNU Emacs support the UTF-8 encoding: Emacs 20 with Mule-UCS, and Emacs 21. As of January 2001, XEmacs doesn't support the UTF-8 encoding.
The character encoding name can be written in either upper or lower case.
Usually upper case is preferred.
8bit.
msgmerge Programmsgmerge [option] def.po ref.pot
The msgmerge program merges two Uniforum style .po files together.
The def.po file is an existing PO file with translations which will
be taken over to the newly created file as long as they still match;
comments will be preserved, but extracted comments and file positions will
be discarded. The ref.pot file is the last created PO file with
up-to-date source references but old translations, or a PO Template file
(generally created by xgettext); any translations or comments
in the file will be discarded, however dot comments and file positions
will be preserved. Where an exact match cannot be found, fuzzy matching
is used to produce better results.
The results are written to standard output if no output file is specified or if it is ‘-’.
The result is written back to def.po.
The version control method may be selected via the --backup option
or through the VERSION_CONTROL environment variable. Here are the
values:
--backup is given).
The backup suffix is ‘~’, unless set with --suffix or the
SIMPLE_BACKUP_SUFFIX environment variable.
.properties
syntax, not in PO file syntax.
.strings syntax, not in PO file syntax.
.properties syntax. Note
that this file format doesn't support plural forms and silently drops
obsolete messages.
.strings syntax.
Note that this file format doesn't support plural forms.
For those of you being the lucky users of Emacs, PO mode has been specifically created for providing a cozy environment for editing or modifying PO files. While editing a PO file, PO mode allows for the easy browsing of auxiliary and compendium PO files, as well as for following references into the set of C program sources from which PO files have been derived. It has a few special features, among which are the interactive marking of program strings as translatable, and the validation of PO files with easy repositioning to PO file lines showing errors.
For the beginning, besides main PO mode commands (see Main PO Commands), you should know how to move between entries (see Entry Positioning), and how to handle untranslated entries (see Untranslated Entries).
gettext InstallationOnce you have received, unpacked, configured and compiled the GNU
gettext distribution, the ‘make install’ command puts in
place the programs xgettext, msgfmt, gettext, and
msgmerge, as well as their available message catalogs. To
top off a comfortable installation, you might also want to make the
PO mode available to your Emacs users.
During the installation of the PO mode, you might want to modify your file .emacs, once and for all, so it contains a few lines looking like:
(setq auto-mode-alist
(cons '("\\.po\\'\\|\\.po\\." . po-mode) auto-mode-alist))
(autoload 'po-mode "po-mode" "Major mode for translators to edit PO files" t)
Later, whenever you edit some .po file, or any file having the string ‘.po.’ within its name, Emacs loads po-mode.elc (or po-mode.el) as needed, and automatically activates PO mode commands for the associated buffer. The string PO appears in the mode line for any buffer for which PO mode is active. Many PO files may be active at once in a single Emacs session.
If you are using Emacs version 20 or newer, and have already installed the appropriate international fonts on your system, you may also tell Emacs how to determine automatically the coding system of every PO file. This will often (but not always) cause the necessary fonts to be loaded and used for displaying the translations on your Emacs screen. For this to happen, add the lines:
(modify-coding-system-alist 'file "\\.po\\'\\|\\.po\\."
'po-find-file-coding-system)
(autoload 'po-find-file-coding-system "po-mode")
to your .emacs file. If, with this, you still see boxes instead of international characters, try a different font set (via Shift Mouse button 1).
After setting up Emacs with something similar to the lines in
Installation, PO mode is activated for a window when Emacs finds a
PO file in that window. This puts the window read-only and establishes a
po-mode-map, which is a genuine Emacs mode, in a way that is not derived
from text mode in any way. Functions found on po-mode-hook,
if any, will be executed.
When PO mode is active in a window, the letters ‘PO’ appear in the mode line for that window. The mode line also displays how many entries of each kind are held in the PO file. For example, the string ‘132t+3f+10u+2o’ would tell the translator that the PO mode contains 132 translated entries (see Translated Entries, 3 fuzzy entries (see Fuzzy Entries), 10 untranslated entries (see Untranslated Entries) and 2 obsolete entries (see Obsolete Entries). Zero-coefficients items are not shown. So, in this example, if the fuzzy entries were unfuzzied, the untranslated entries were translated and the obsolete entries were deleted, the mode line would merely display ‘145t’ for the counters.
The main PO commands are those which do not fit into the other categories of subsequent sections. These allow for quitting PO mode or for managing windows in special ways.
po-undo).
po-quit).
po-confirm-and-quit).
po-other-window).
po-help).
po-statistics).
po-validate).
The command _ (po-undo) interfaces to the Emacs
undo facility. See Undoing Changes. Each time U is typed, modifications which the translator
did to the PO file are undone a little more. For the purpose of
undoing, each PO mode command is atomic. This is especially true for
the <RET> command: the whole edition made by using a single
use of this command is undone at once, even if the edition itself
implied several actions. However, while in the editing window, one
can undo the edition work quite parsimoniously.
The commands Q (po-quit) and q
(po-confirm-and-quit) are used when the translator is done with the
PO file. The former is a bit less verbose than the latter. If the file
has been modified, it is saved to disk first. In both cases, and prior to
all this, the commands check if any untranslated messages remain in the
PO file and, if so, the translator is asked if she really wants to leave
off working with this PO file. This is the preferred way of getting rid
of an Emacs PO file buffer. Merely killing it through the usual command
C-x k (kill-buffer) is not the tidiest way to proceed.
The command 0 (po-other-window) is another, softer way,
to leave PO mode, temporarily. It just moves the cursor to some other
Emacs window, and pops one if necessary. For example, if the translator
just got PO mode to show some source context in some other, she might
discover some apparent bug in the program source that needs correction.
This command allows the translator to change sex, become a programmer,
and have the cursor right into the window containing the program she
(or rather he) wants to modify. By later getting the cursor back
in the PO file window, or by asking Emacs to edit this file once again,
PO mode is then recovered.
The command h (po-help) displays a summary of all available PO
mode commands. The translator should then type any character to resume
normal PO mode operations. The command ? has the same effect
as h.
The command = (po-statistics) computes the total number of
entries in the PO file, the ordinal of the current entry (counted from
1), the number of untranslated entries, the number of obsolete entries,
and displays all these numbers.
The command V (po-validate) launches msgfmt in
checking and verbose
mode over the current PO file. This command first offers to save the
current PO file on disk. The msgfmt tool, from GNU gettext,
has the purpose of creating a MO file out of a PO file, and PO mode uses
the features of this program for checking the overall format of a PO file,
as well as all individual entries.
The program msgfmt runs asynchronously with Emacs, so the
translator regains control immediately while her PO file is being studied.
Error output is collected in the Emacs ‘*compilation*’ buffer,
displayed in another window. The regular Emacs command C-x`
(next-error), as well as other usual compile commands, allow the
translator to reposition quickly to the offending parts of the PO file.
Once the cursor is on the line in error, the translator may decide on
any PO mode action which would help correcting the error.
The cursor in a PO file window is almost always part of an entry. The only exceptions are the special case when the cursor is after the last entry in the file, or when the PO file is empty. The entry where the cursor is found to be is said to be the current entry. Many PO mode commands operate on the current entry, so moving the cursor does more than allowing the translator to browse the PO file, this also selects on which entry commands operate.
Some PO mode commands alter the position of the cursor in a specialized way. A few of those special purpose positioning are described here, the others are described in following sections (for a complete list try C-h m):
po-current-entry).
po-next-entry).
po-previous-entry).
po-first-entry).
po-last-entry).
po-push-location).
po-pop-location).
po-exchange-location).
Any Emacs command able to reposition the cursor may be used
to select the current entry in PO mode, including commands which
move by characters, lines, paragraphs, screens or pages, and search
commands. However, there is a kind of standard way to display the
current entry in PO mode, which usual Emacs commands moving
the cursor do not especially try to enforce. The command .
(po-current-entry) has the sole purpose of redisplaying the
current entry properly, after the current entry has been changed by
means external to PO mode, or the Emacs screen otherwise altered.
It is yet to be decided if PO mode helps the translator, or otherwise irritates her, by forcing a rigid window disposition while she is doing her work. We originally had quite precise ideas about how windows should behave, but on the other hand, anyone used to Emacs is often happy to keep full control. Maybe a fixed window disposition might be offered as a PO mode option that the translator might activate or deactivate at will, so it could be offered on an experimental basis. If nobody feels a real need for using it, or a compulsion for writing it, we should drop this whole idea. The incentive for doing it should come from translators rather than programmers, as opinions from an experienced translator are surely more worth to me than opinions from programmers thinking about how others should do translation.
The commands n (po-next-entry) and p
(po-previous-entry) move the cursor the entry following,
or preceding, the current one. If n is given while the
cursor is on the last entry of the PO file, or if p
is given while the cursor is on the first entry, no move is done.
The commands < (po-first-entry) and >
(po-last-entry) move the cursor to the first entry, or last
entry, of the PO file. When the cursor is located past the last
entry in a PO file, most PO mode commands will return an error saying
‘After last entry’. Moreover, the commands < and >
have the special property of being able to work even when the cursor
is not into some PO file entry, and one may use them for nicely
correcting this situation. But even these commands will fail on a
truly empty PO file. There are development plans for the PO mode for it
to interactively fill an empty PO file from sources. See Marking.
The translator may decide, before working at the translation of a particular entry, that she needs to browse the remainder of the PO file, maybe for finding the terminology or phraseology used in related entries. She can of course use the standard Emacs idioms for saving the current cursor location in some register, and use that register for getting back, or else, use the location ring.
PO mode offers another approach, by which cursor locations may be saved
onto a special stack. The command m (po-push-location)
merely adds the location of current entry to the stack, pushing
the already saved locations under the new one. The command
r (po-pop-location) consumes the top stack element and
repositions the cursor to the entry associated with that top element.
This position is then lost, for the next r will move the cursor
to the previously saved location, and so on until no locations remain
on the stack.
If the translator wants the position to be kept on the location stack, maybe for taking a look at the entry associated with the top element, then go elsewhere with the intent of getting back later, she ought to use m immediately after r.
The command x (po-exchange-location) simultaneously
repositions the cursor to the entry associated with the top element of
the stack of saved locations, and replaces that top element with the
location of the current entry before the move. Consequently, repeating
the x command toggles alternatively between two entries.
For achieving this, the translator will position the cursor on the
first entry, use m, then position to the second entry, and
merely use x for making the switch.
There are many different ways for encoding a particular string into a
PO file entry, because there are so many different ways to split and
quote multi-line strings, and even, to represent special characters
by backslashed escaped sequences. Some features of PO mode rely on
the ability for PO mode to scan an already existing PO file for a
particular string encoded into the msgid field of some entry.
Even if PO mode has internally all the built-in machinery for
implementing this recognition easily, doing it fast is technically
difficult. To facilitate a solution to this efficiency problem,
we decided on a canonical representation for strings.
A conventional representation of strings in a PO file is currently
under discussion, and PO mode experiments with a canonical representation.
Having both xgettext and PO mode converging towards a uniform
way of representing equivalent strings would be useful, as the internal
normalization needed by PO mode could be automatically satisfied
when using xgettext from GNU gettext. An explicit
PO mode normalization should then be only necessary for PO files
imported from elsewhere, or for when the convention itself evolves.
So, for achieving normalization of at least the strings of a given PO file needing a canonical representation, the following PO mode command is available:
The special command M-x po-normalize, which has no associated
keys, revises all entries, ensuring that strings of both original
and translated entries use uniform internal quoting in the PO file.
It also removes any crumb after the last entry. This command may be
useful for PO files freshly imported from elsewhere, or if we ever
improve on the canonical quoting format we use. This canonical format
is not only meant for getting cleaner PO files, but also for greatly
speeding up msgid string lookup for some other PO mode commands.
M-x po-normalize presently makes three passes over the entries.
The first implements heuristics for converting PO files for GNU
gettext 0.6 and earlier, in which msgid and msgstr
fields were using K&R style C string syntax for multi-line strings.
These heuristics may fail for comments not related to obsolete
entries and ending with a backslash; they also depend on subsequent
passes for finalizing the proper commenting of continued lines for
obsolete entries. This first pass might disappear once all oldish PO
files would have been adjusted. The second and third pass normalize
all msgid and msgstr strings respectively. They also
clean out those trailing backslashes used by XView's msgfmt
for continued lines.
Having such an explicit normalizing command allows for importing PO
files from other sources, but also eases the evolution of the current
convention, evolution driven mostly by aesthetic concerns, as of now.
It is easy to make suggested adjustments at a later time, as the
normalizing command and eventually, other GNU gettext tools
should greatly automate conformance. A description of the canonical
string format is given below, for the particular benefit of those not
having Emacs handy, and who would nevertheless want to handcraft
their PO files in nice ways.
Right now, in PO mode, strings are single line or multi-line. A string goes multi-line if and only if it has embedded newlines, that is, if it matches ‘[^\n]\n+[^\n]’. So, we would have:
msgstr "\n\nHello, world!\n\n\n"
but, replacing the space by a newline, this becomes:
msgstr ""
"\n"
"\n"
"Hello,\n"
"world!\n"
"\n"
"\n"
We are deliberately using a caricatural example, here, to make the point clearer. Usually, multi-lines are not that bad looking. It is probable that we will implement the following suggestion. We might lump together all initial newlines into the empty string, and also all newlines introducing empty lines (that is, for n > 1, the n-1'th last newlines would go together on a separate string), so making the previous example appear:
msgstr "\n\n"
"Hello,\n"
"world!\n"
"\n\n"
There are a few yet undecided little points about string normalization, to be documented in this manual, once these questions settle.
Each PO file entry for which the msgstr field has been filled with
a translation, and which is not marked as fuzzy (see Fuzzy Entries),
is said to be a translated entry. Only translated entries will
later be compiled by GNU msgfmt and become usable in programs.
Other entry types will be excluded; translation will not occur for them.
Some commands are more specifically related to translated entry processing.
po-next-translated-entry).
po-previous-translated-entry).
The commands t (po-next-translated-entry) and T
(po-previous-translated-entry) move forwards or backwards, chasing
for an translated entry. If none is found, the search is extended and
wraps around in the PO file buffer.
Translated entries usually result from the translator having edited in
a translation for them, Modifying Translations. However, if the
variable po-auto-fuzzy-on-edit is not nil, the entry having
received a new translation first becomes a fuzzy entry, which ought to
be later unfuzzied before becoming an official, genuine translated entry.
See Fuzzy Entries.
Each PO file entry may have a set of attributes, which are
qualities given a name and explicitly associated with the translation,
using a special system comment. One of these attributes
has the name fuzzy, and entries having this attribute are said
to have a fuzzy translation. They are called fuzzy entries, for short.
Fuzzy entries, even if they account for translated entries for
most other purposes, usually call for revision by the translator.
Those may be produced by applying the program msgmerge to
update an older translated PO files according to a new PO template
file, when this tool hypothesises that some new msgid has
been modified only slightly out of an older one, and chooses to pair
what it thinks to be the old translation for the new modified entry.
The slight alteration in the original string (the msgid string)
should often be reflected in the translated string, and this requires
the intervention of the translator. For this reason, msgmerge
might mark some entries as being fuzzy.
Also, the translator may decide herself to mark an entry as fuzzy for her own convenience, when she wants to remember that the entry has to be later revisited. So, some commands are more specifically related to fuzzy entry processing.
po-next-fuzzy-entry).
po-previous-fuzzy-entry).
po-unfuzzy).
The commands z (po-next-fuzzy-entry) and Z
(po-previous-fuzzy-entry) move forwards or backwards, chasing for
a fuzzy entry. If none is found, the search is extended and wraps
around in the PO file buffer.
The command <TAB> (po-unfuzzy) removes the fuzzy
attribute associated with an entry, usually leaving it translated.
Further, if the variable po-auto-select-on-unfuzzy has not
the nil value, the <TAB> command will automatically chase
for another interesting entry to work on. The initial value of
po-auto-select-on-unfuzzy is nil.
The initial value of po-auto-fuzzy-on-edit is nil. However,
if the variable po-auto-fuzzy-on-edit is set to t, any entry
edited through the <RET> command is marked fuzzy, as a way to
ensure some kind of double check, later. In this case, the usual paradigm
is that an entry becomes fuzzy (if not already) whenever the translator
modifies it. If she is satisfied with the translation, she then uses
<TAB> to pick another entry to work on, clearing the fuzzy attribute
on the same blow. If she is not satisfied yet, she merely uses <SPC>
to chase another entry, leaving the entry fuzzy.
The translator may also use the <DEL> command
(po-fade-out-entry) over any translated entry to mark it as being
fuzzy, when she wants to easily leave a trace she wants to later return
working at this entry.
Also, when time comes to quit working on a PO file buffer with the q command, the translator is asked for confirmation, if fuzzy string still exists.
When xgettext originally creates a PO file, unless told
otherwise, it initializes the msgid field with the untranslated
string, and leaves the msgstr string to be empty. Such entries,
having an empty translation, are said to be untranslated entries.
Later, when the programmer slightly modifies some string right in
the program, this change is later reflected in the PO file
by the appearance of a new untranslated entry for the modified string.
The usual commands moving from entry to entry consider untranslated entries on the same level as active entries. Untranslated entries are easily recognizable by the fact they end with ‘msgstr ""’.
The work of the translator might be (quite naively) seen as the process of seeking for an untranslated entry, editing a translation for it, and repeating these actions until no untranslated entries remain. Some commands are more specifically related to untranslated entry processing.
po-next-untranslated-entry).
po-previous-untransted-entry).
po-kill-msgstr).
The commands u (po-next-untranslated-entry) and U
(po-previous-untransted-entry) move forwards or backwards,
chasing for an untranslated entry. If none is found, the search is
extended and wraps around in the PO file buffer.
An entry can be turned back into an untranslated entry by
merely emptying its translation, using the command k
(po-kill-msgstr). See Modifying Translations.
Also, when time comes to quit working on a PO file buffer with the q command, the translator is asked for confirmation, if some untranslated string still exists.
By obsolete PO file entries, we mean those entries which are
commented out, usually by msgmerge when it found that the
translation is not needed anymore by the package being localized.
The usual commands moving from entry to entry consider obsolete
entries on the same level as active entries. Obsolete entries are
easily recognizable by the fact that all their lines start with
#, even those lines containing msgid or msgstr.
Commands exist for emptying the translation or reinitializing it to the original untranslated string. Commands interfacing with the kill ring may force some previously saved text into the translation. The user may interactively edit the translation. All these commands may apply to obsolete entries, carefully leaving the entry obsolete after the fact.
Moreover, some commands are more specifically related to obsolete entry processing.
po-next-obsolete-entry).
po-previous-obsolete-entry).
po-fade-out-entry).
The commands o (po-next-obsolete-entry) and O
(po-previous-obsolete-entry) move forwards or backwards,
chasing for an obsolete entry. If none is found, the search is
extended and wraps around in the PO file buffer.
PO mode does not provide ways for un-commenting an obsolete entry
and making it active, because this would reintroduce an original
untranslated string which does not correspond to any marked string
in the program sources. This goes with the philosophy of never
introducing useless msgid values.
However, it is possible to comment out an active entry, so making
it obsolete. GNU gettext utilities will later react to the
disappearance of a translation by using the untranslated string.
The command <DEL> (po-fade-out-entry) pushes the current entry
a little further towards annihilation. If the entry is active (it is a
translated entry), then it is first made fuzzy. If it is already fuzzy,
then the entry is merely commented out, with confirmation. If the entry
is already obsolete, then it is completely deleted from the PO file.
It is easy to recycle the translation so deleted into some other PO file
entry, usually one which is untranslated. See Modifying Translations.
Here is a quite interesting problem to solve for later development of PO mode, for those nights you are not sleepy. The idea would be that PO mode might become bright enough, one of these days, to make good guesses at retrieving the most probable candidate, among all obsolete entries, for initializing the translation of a newly appeared string. I think it might be a quite hard problem to do this algorithmically, as we have to develop good and efficient measures of string similarity. Right now, PO mode completely lets the decision to the translator, when the time comes to find the adequate obsolete translation, it merely tries to provide handy tools for helping her to do so.
PO mode prevents direct modification of the PO file, by the usual means Emacs gives for altering a buffer's contents. By doing so, it pretends helping the translator to avoid little clerical errors about the overall file format, or the proper quoting of strings, as those errors would be easily made. Other kinds of errors are still possible, but some may be caught and diagnosed by the batch validation process, which the translator may always trigger by the V command. For all other errors, the translator has to rely on her own judgment, and also on the linguistic reports submitted to her by the users of the translated package, having the same mother tongue.
When the time comes to create a translation, correct an error diagnosed mechanically or reported by a user, the translators have to resort to using the following commands for modifying the translations.
po-edit-msgstr).
po-msgid-to-msgstr).
po-kill-msgstr).
po-kill-ring-save-msgstr).
po-yank-msgstr).
The command <RET> (po-edit-msgstr) opens a new Emacs
window meant to edit in a new translation, or to modify an already existing
translation. The new window contains a copy of the translation taken from
the current PO file entry, all ready for edition, expunged of all quoting
marks, fully modifiable and with the complete extent of Emacs modifying
commands. When the translator is done with her modifications, she may use
C-c C-c to close the subedit window with the automatically requoted
results, or C-c C-k to abort her modifications. See Subedit,
for more information.
The command <LFD> (po-msgid-to-msgstr) initializes, or
reinitializes the translation with the original string. This command is
normally used when the translator wants to redo a fresh translation of
the original string, disregarding any previous work.
It is possible to arrange so, whenever editing an untranslated
entry, the <LFD> command be automatically executed. If you set
po-auto-edit-with-msgid to t, the translation gets
initialised with the original string, in case none exists already.
The default value for po-auto-edit-with-msgid is nil.
In fact, whether it is best to start a translation with an empty string, or rather with a copy of the original string, is a matter of taste or habit. Sometimes, the source language and the target language are so different that is simply best to start writing on an empty page. At other times, the source and target languages are so close that it would be a waste to retype a number of words already being written in the original string. A translator may also like having the original string right under her eyes, as she will progressively overwrite the original text with the translation, even if this requires some extra editing work to get rid of the original.
The command k (po-kill-msgstr) merely empties the
translation string, so turning the entry into an untranslated
one. But while doing so, its previous contents is put apart in
a special place, known as the kill ring. The command w
(po-kill-ring-save-msgstr) has also the effect of taking a
copy of the translation onto the kill ring, but it otherwise leaves
the entry alone, and does not remove the translation from the
entry. Both commands use exactly the Emacs kill ring, which is shared
between buffers, and which is well known already to Emacs lovers.
The translator may use k or w many times in the course of her work, as the kill ring may hold several saved translations. From the kill ring, strings may later be reinserted in various Emacs buffers. In particular, the kill ring may be used for moving translation strings between different entries of a single PO file buffer, or if the translator is handling many such buffers at once, even between PO files.
To facilitate exchanges with buffers which are not in PO mode, the translation string put on the kill ring by the k command is fully unquoted before being saved: external quotes are removed, multi-line strings are concatenated, and backslash escaped sequences are turned into their corresponding characters. In the special case of obsolete entries, the translation is also uncommented prior to saving.
The command y (po-yank-msgstr) completely replaces the
translation of the current entry by a string taken from the kill ring.
Following Emacs terminology, we then say that the replacement
string is yanked into the PO file buffer.
See Yanking.
The first time y is used, the translation receives the value of
the most recent addition to the kill ring. If y is typed once
again, immediately, without intervening keystrokes, the translation
just inserted is taken away and replaced by the second most recent
addition to the kill ring. By repeating y many times in a row,
the translator may travel along the kill ring for saved strings,
until she finds the string she really wanted.
When a string is yanked into a PO file entry, it is fully and automatically requoted for complying with the format PO files should have. Further, if the entry is obsolete, PO mode then appropriately push the inserted string inside comments. Once again, translators should not burden themselves with quoting considerations besides, of course, the necessity of the translated string itself respective to the program using it.
Note that k or w are not the only commands pushing strings on the kill ring, as almost any PO mode command replacing translation strings (or the translator comments) automatically saves the old string on the kill ring. The main exceptions to this general rule are the yanking commands themselves.
To better illustrate the operation of killing and yanking, let's
use an actual example, taken from a common situation. When the
programmer slightly modifies some string right in the program, his
change is later reflected in the PO file by the appearance
of a new untranslated entry for the modified string, and the fact
that the entry translating the original or unmodified string becomes
obsolete. In many cases, the translator might spare herself some work
by retrieving the unmodified translation from the obsolete entry,
then initializing the untranslated entry msgstr field with
this retrieved translation. Once this done, the obsolete entry is
not wanted anymore, and may be safely deleted.
When the translator finds an untranslated entry and suspects that a
slight variant of the translation exists, she immediately uses m
to mark the current entry location, then starts chasing obsolete
entries with o, hoping to find some translation corresponding
to the unmodified string. Once found, she uses the <DEL> command
for deleting the obsolete entry, knowing that <DEL> also kills
the translation, that is, pushes the translation on the kill ring.
Then, r returns to the initial untranslated entry, and y
then yanks the saved translation right into the msgstr
field. The translator is then free to use <RET> for fine
tuning the translation contents, and maybe to later use u,
then m again, for going on with the next untranslated string.
When some sequence of keys has to be typed over and over again, the translator may find it useful to become better acquainted with the Emacs capability of learning these sequences and playing them back under request. See Keyboard Macros.
Any translation work done seriously will raise many linguistic difficulties, for which decisions have to be made, and the choices further documented. These documents may be saved within the PO file in form of translator comments, which the translator is free to create, delete, or modify at will. These comments may be useful to herself when she returns to this PO file after a while.
Comments not having whitespace after the initial ‘#’, for example,
those beginning with ‘#.’ or ‘#:’, are not translator
comments, they are exclusively created by other gettext tools.
So, the commands below will never alter such system added comments,
they are not meant for the translator to modify. See PO Files.
The following commands are somewhat similar to those modifying translations, so the general indications given for those apply here. See Modifying Translations.
po-edit-comment).
po-kill-comment).
po-kill-ring-save-comment).
po-yank-comment).
These commands parallel PO mode commands for modifying the translation strings, and behave much the same way as they do, except that they handle this part of PO file comments meant for translator usage, rather than the translation strings. So, if the descriptions given below are slightly succinct, it is because the full details have already been given. See Modifying Translations.
The command # (po-edit-comment) opens a new Emacs window
containing a copy of the translator comments on the current PO file entry.
If there are no such comments, PO mode understands that the translator wants
to add a comment to the entry, and she is presented with an empty screen.
Comment marks (#) and the space following them are automatically
removed before edition, and reinstated after. For translator comments
pertaining to obsolete entries, the uncommenting and recommenting operations
are done twice. Once in the editing window, the keys C-c C-c
allow the translator to tell she is finished with editing the comment.
See Subedit, for further details.
Functions found on po-subedit-mode-hook, if any, are executed after
the string has been inserted in the edit buffer.
The command K (po-kill-comment) gets rid of all
translator comments, while saving those comments on the kill ring.
The command W (po-kill-ring-save-comment) takes
a copy of the translator comments on the kill ring, but leaves
them undisturbed in the current entry. The command Y
(po-yank-comment) completely replaces the translator comments
by a string taken at the front of the kill ring. When this command
is immediately repeated, the comments just inserted are withdrawn,
and replaced by other strings taken along the kill ring.
On the kill ring, all strings have the same nature. There is no distinction between translation strings and translator comments strings. So, for example, let's presume the translator has just finished editing a translation, and wants to create a new translator comment to document why the previous translation was not good, just to remember what was the problem. Foreseeing that she will do that in her documentation, the translator may want to quote the previous translation in her translator comments. To do so, she may initialize the translator comments with the previous translation, still at the head of the kill ring. Because editing already pushed the previous translation on the kill ring, she merely has to type M-w prior to #, and the previous translation will be right there, all ready for being introduced by some explanatory text.
On the other hand, presume there are some translator comments already
and that the translator wants to add to those comments, instead
of wholly replacing them. Then, she should edit the comment right
away with #. Once inside the editing window, she can use the
regular Emacs commands C-y (yank) and M-y
(yank-pop) to get the previous translation where she likes.
The PO subedit minor mode has a few peculiarities worth being described in fuller detail. It installs a few commands over the usual editing set of Emacs, which are described below.
po-subedit-exit).
po-subedit-abort).
po-subedit-cycle-auxiliary).
The window's contents represents a translation for a given message,
or a translator comment. The translator may modify this window to
her heart's content. Once this is done, the command C-c C-c
(po-subedit-exit) may be used to return the edited translation into
the PO file, replacing the original translation, even if it moved out of
sight or if buffers were switched.
If the translator becomes unsatisfied with her translation or comment,
to the extent she prefers keeping what was existent prior to the
<RET> or # command, she may use the command C-c C-k
(po-subedit-abort) to merely get rid of edition, while preserving
the original translation or comment. Another way would be for her to exit
normally with C-c C-c, then type U once for undoing the
whole effect of last edition.
The command C-c C-a (po-subedit-cycle-auxiliary)
allows for glancing through translations
already achieved in other languages, directly while editing the current
translation. This may be quite convenient when the translator is fluent
at many languages, but of course, only makes sense when such completed
auxiliary PO files are already available to her (see Auxiliary).
Functions found on po-subedit-mode-hook, if any, are executed after
the string has been inserted in the edit buffer.
While editing her translation, the translator should pay attention to not
inserting unwanted <RET> (newline) characters at the end of
the translated string if those are not meant to be there, or to removing
such characters when they are required. Since these characters are not
visible in the editing buffer, they are easily introduced by mistake.
To help her, <RET> automatically puts the character <
at the end of the string being edited, but this < is not really
part of the string. On exiting the editing window with C-c C-c,
PO mode automatically removes such < and all whitespace added after
it. If the translator adds characters after the terminating <, it
looses its delimiting property and integrally becomes part of the string.
If she removes the delimiting <, then the edited string is taken
as is, with all trailing newlines, even if invisible. Also, if
the translated string ought to end itself with a genuine <, then
the delimiting < may not be removed; so the string should appear,
in the editing window, as ending with two < in a row.
When a translation (or a comment) is being edited, the translator may move the cursor back into the PO file buffer and freely move to other entries, browsing at will. If, with an edition pending, the translator wanders in the PO file buffer, she may decide to start modifying another entry. Each entry being edited has its own subedit buffer. It is possible to simultaneously edit the translation and the comment of a single entry, or to edit entries in different PO files, all at once. Typing <RET> on a field already being edited merely resumes that particular edit. Yet, the translator should better be comfortable at handling many Emacs windows!
Pending subedits may be completed or aborted in any order, regardless of how or when they were started. When many subedits are pending and the translator asks for quitting the PO file (with the q command), subedits are automatically resumed one at a time, so she may decide for each of them.
PO mode is particularly powerful when used with PO files
created through GNU gettext utilities, as those utilities
insert special comments in the PO files they generate.
Some of these special comments relate the PO file entry to
exactly where the untranslated string appears in the program sources.
When the translator gets to an untranslated entry, she is fairly often faced with an original string which is not as informative as it normally should be, being succinct, cryptic, or otherwise ambiguous. Before choosing how to translate the string, she needs to understand better what the string really means and how tight the translation has to be. Most of the time, when problems arise, the only way left to make her judgment is looking at the true program sources from where this string originated, searching for surrounding comments the programmer might have put in there, and looking around for helping clues of any kind.
Surely, when looking at program sources, the translator will receive more help if she is a fluent programmer. However, even if she is not versed in programming and feels a little lost in C code, the translator should not be shy at taking a look, once in a while. It is most probable that she will still be able to find some of the hints she needs. She will learn quickly to not feel uncomfortable in program code, paying more attention to programmer's comments, variable and function names (if he dared choosing them well), and overall organization, than to the program code itself.
The following commands are meant to help the translator at getting program source context for a PO file entry.
po-cycle-source-reference).
po-select-source-reference).
po-consider-source-path).
po-ignore-source-path).
The commands s (po-cycle-source-reference) and M-s
(po-select-source-reference) both open another window displaying
some source program file, and already positioned in such a way that
it shows an actual use of the string to be translated. By doing
so, the command gives source program context for the string. But if
the entry has no source context references, or if all references
are unresolved along the search path for program sources, then the
command diagnoses this as an error.
Even if s (or M-s) opens a new window, the cursor stays in the PO file window. If the translator really wants to get into the program source window, she ought to do it explicitly, maybe by using command O.
When s is typed for the first time, or for a PO file entry which is different of the last one used for getting source context, then the command reacts by giving the first context available for this entry, if any. If some context has already been recently displayed for the current PO file entry, and the translator wandered off to do other things, typing s again will merely resume, in another window, the context last displayed. In particular, if the translator moved the cursor away from the context in the source file, the command will bring the cursor back to the context. By using s many times in a row, with no other commands intervening, PO mode will cycle to the next available contexts for this particular entry, getting back to the first context once the last has been shown.
The command M-s behaves differently. Instead of cycling through references, it lets the translator choose a particular reference among many, and displays that reference. It is best used with completion, if the translator types <TAB> immediately after M-s, in response to the question, she will be offered a menu of all possible references, as a reminder of which are the acceptable answers. This command is useful only where there are really many contexts available for a single string to translate.
Program source files are usually found relative to where the PO
file stands. As a special provision, when this fails, the file is
also looked for, but relative to the directory immediately above it.
Those two cases take proper care of most PO files. However, it might
happen that a PO file has been moved, or is edited in a different
place than its normal location. When this happens, the translator
should tell PO mode in which directory normally sits the genuine PO
file. Many such directories may be specified, and all together, they
constitute what is called the search path for program sources.
The command S (po-consider-source-path) is used to interactively
enter a new directory at the front of the search path, and the command
M-S (po-ignore-source-path) is used to select, with completion,
one of the directories she does not want anymore on the search path.
PO mode is able to help the knowledgeable translator, being fluent in many languages, at taking advantage of translations already achieved in other languages she just happens to know. It provides these other language translations as additional context for her own work. Moreover, it has features to ease the production of translations for many languages at once, for translators preferring to work in this way.
An auxiliary PO file is an existing PO file meant for the same package the translator is working on, but targeted to a different mother tongue language. Commands exist for declaring and handling auxiliary PO files, and also for showing contexts for the entry under work.
Here are the auxiliary file commands available in PO mode.
po-cycle-auxiliary).
po-select-auxiliary).
po-consider-as-auxiliary).
po-ignore-as-auxiliary).
Command A (po-consider-as-auxiliary) adds the current
PO file to the list of auxiliary files, while command M-A
(po-ignore-as-auxiliary just removes it.
The command a (po-cycle-auxiliary) seeks all auxiliary PO
files, round-robin, searching for a translated entry in some other language
having an msgid field identical as the one for the current entry.
The found PO file, if any, takes the place of the current PO file in
the display (its window gets on top). Before doing so, the current PO
file is also made into an auxiliary file, if not already. So, a
in this newly displayed PO file will seek another PO file, and so on,
so repeating a will eventually yield back the original PO file.
The command C-c C-a (po-select-auxiliary) asks the translator
for her choice of a particular auxiliary file, with completion, and
then switches to that selected PO file. The command also checks if
the selected file has an msgid field identical as the one for
the current entry, and if yes, this entry becomes current. Otherwise,
the cursor of the selected file is left undisturbed.
For all this to work fully, auxiliary PO files will have to be normalized,
in that way that msgid fields should be written exactly
the same way. It is possible to write msgid fields in various
ways for representing the same string, different writing would break the
proper behaviour of the auxiliary file commands of PO mode. This is not
expected to be much a problem in practice, as most existing PO files have
their msgid entries written by the same GNU gettext tools.
However, PO files initially created by PO mode itself, while marking
strings in source files, are normalised differently. So are PO
files resulting of the ‘M-x normalize’ command. Until these
discrepancies between PO mode and other GNU gettext tools get
fully resolved, the translator should stay aware of normalisation issues.
A compendium is a special PO file containing a set of translations recurring in many different packages. The translator can use gettext tools to build a new compendium, to add entries to her compendium, and to initialize untranslated entries, or to update already translated entries, from translations kept in the compendium.
Basically every PO file consisting of translated entries only can be declared as a valid compendium. Often the translator wants to have special compendia; let's consider two cases: concatenating PO files and extracting a message subset from a PO file.
To concatenate several valid PO files into one compendium file you can use ‘msgcomm’ or ‘msgcat’ (the latter preferred):
msgcat -o compendium.po file1.po file2.po
By default, msgcat will accumulate divergent translations
for the same string. Those occurrences will be marked as fuzzy
and highly visible decorated; calling msgcat on
file1.po:
#: src/hello.c:200
#, c-format
msgid "Report bugs to <%s>.\n"
msgstr "Comunicar `bugs' a <%s>.\n"
and file2.po:
#: src/bye.c:100
#, c-format
msgid "Report bugs to <%s>.\n"
msgstr "Comunicar \"bugs\" a <%s>.\n"
will result in:
#: src/hello.c:200 src/bye.c:100
#, fuzzy, c-format
msgid "Report bugs to <%s>.\n"
msgstr ""
"#-#-#-#-# file1.po #-#-#-#-#\n"
"Comunicar `bugs' a <%s>.\n"
"#-#-#-#-# file2.po #-#-#-#-#\n"
"Comunicar \"bugs\" a <%s>.\n"
The translator will have to resolve this “conflict” manually; she
has to decide whether the first or the second version is appropriate
(or provide a new translation), to delete the “marker lines”, and
finally to remove the fuzzy mark.
If the translator knows in advance the first found translation of a message is always the best translation she can make use to the ‘--use-first’ switch:
msgcat --use-first -o compendium.po file1.po file2.po
A good compendium file must not contain fuzzy or untranslated
entries. If input files are “dirty” you must preprocess the input
files or postprocess the result using ‘msgattrib --translated --no-fuzzy’.
Nobody wants to translate the same messages again and again; thus you may wish to have a compendium file containing getopt.c messages.
To extract a message subset (e.g., all getopt.c messages) from an existing PO file into one compendium file you can use ‘msggrep’:
msggrep --location src/getopt.c -o compendium.po file.po
You can use a compendium file to initialize a translation from scratch or to update an already existing translation.
Since a PO file with translations does not exist the translator can merely use /dev/null to fake the “old” translation file.
msgmerge --compendium compendium.po -o file.po /dev/null file.pot
Concatenate the compendium file(s) and the existing PO, merge the result with the POT file and remove the obsolete entries (optional, here done using ‘sed’):
msgcat --use-first -o update.po compendium1.po compendium2.po file.po
msgmerge update.po file.pot | msgattrib --no-obsolete > file.po
Sometimes it is necessary to manipulate PO files in a way that is better
performed automatically than by hand. GNU gettext includes a
complete set of tools for this purpose.
When merging two packages into a single package, the resulting POT file will be the concatenation of the two packages' POT files. Thus the maintainer must concatenate the two existing package translations into a single translation catalog, for each language. This is best performed using ‘msgcat’. It is then the translators' duty to deal with any possible conflicts that arose during the merge.
When a translator takes over the translation job from another translator, but she uses a different character encoding in her locale, she will convert the catalog to her character encoding. This is best done through the ‘msgconv’ program.
When a maintainer takes a source file with tagged messages from another package, he should also take the existing translations for this source file (and not let the translators do the same job twice). One way to do this is through ‘msggrep’, another is to create a POT file for that source file and use ‘msgmerge’.
When a translator wants to adjust some translation catalog for a special dialect or orthography — for example, German as written in Switzerland versus German as written in Germany — she needs to apply some text processing to every message in the catalog. The tool for doing this is ‘msgfilter’.
Another use of msgfilter is to produce approximately the POT file for
which a given PO file was made. This can be done through a filter command
like ‘msgfilter sed -e d | sed -e '/^# /d'’. Note that the original
POT file may have had different comments and different plural message counts,
that's why it's better to use the original POT file if available.
When a translator wants to check her translations, for example according to orthography rules or using a non-interactive spell checker, she can do so using the ‘msgexec’ program.
When third party tools create PO or POT files, sometimes duplicates cannot
be avoided. But the GNU gettext tools give an error when they
encounter duplicate msgids in the same file and in the same domain.
To merge duplicates, the ‘msguniq’ program can be used.
‘msgcomm’ is a more general tool for keeping or throwing away duplicates, occurring in different files.
‘msgcmp’ can be used to check whether a translation catalog is completely translated.
‘msgattrib’ can be used to select and extract only the fuzzy or untranslated messages of a translation catalog.
‘msgen’ is useful as a first step for preparing English translation catalogs. It copies each message's msgid to its msgstr.
Finally, for those applications where all these various programs are not sufficient, a library ‘libgettextpo’ is provided that can be used to write other specialized programs that process PO files.
msgcat Programmsgcat [option] [inputfile]...
The msgcat program concatenates and merges the specified PO files.
It finds messages which are common to two or more of the specified PO files.
By using the --more-than option, greater commonality may be requested
before messages are printed. Conversely, the --less-than option may be
used to specify less commonality before messages are printed (i.e.
‘--less-than=2’ will only print the unique messages). Translations,
comments and extract comments will be cumulated, except that if
--use-first is specified, they will be taken from the first PO file
to define them. File positions from all PO files will be cumulated.
If inputfile is ‘-’, standard input is read.
The results are written to standard output if no output file is specified or if it is ‘-’.
.properties
syntax, not in PO file syntax.
.strings syntax, not in PO file syntax.
--color.
See The –style option for details.
.properties syntax. Note
that this file format doesn't support plural forms and silently drops
obsolete messages.
.strings syntax.
Note that this file format doesn't support plural forms.
msgconv Programmsgconv [option] [inputfile]
The msgconv program converts a translation catalog to a different
character encoding.
If no inputfile is given or if it is ‘-’, standard input is read.
The results are written to standard output if no output file is specified or if it is ‘-’.
The default encoding is the current locale's encoding.
.properties
syntax, not in PO file syntax.
.strings syntax, not in PO file syntax.
.properties syntax. Note
that this file format doesn't support plural forms and silently drops
obsolete messages.
.strings syntax.
Note that this file format doesn't support plural forms.
msggrep Programmsggrep [option] [inputfile]
The msggrep program extracts all messages of a translation catalog
that match a given pattern or belong to some given source files.
If no inputfile is given or if it is ‘-’, standard input is read.
The results are written to standard output if no output file is specified or if it is ‘-’.
[-N sourcefile]... [-M domainname]...
[-J msgctxt-pattern] [-K msgid-pattern] [-T msgstr-pattern]
[-C comment-pattern]
A message is selected if
When more than one selection criterion is specified, the set of selected messages is the union of the selected messages of each criterion.
msgctxt-pattern or msgid-pattern or msgstr-pattern syntax:
[-E | -F] [-e pattern | -f file]...
patterns are basic regular expressions by default, or extended regular expressions if -E is given, or fixed strings if -F is given.
.properties
syntax, not in PO file syntax.
.strings syntax, not in PO file syntax.
.properties syntax. Note
that this file format doesn't support plural forms and silently drops
obsolete messages.
.strings syntax.
Note that this file format doesn't support plural forms.
To extract the messages that come from the source files
gnulib-lib/error.c and gnulib-lib/getopt.c:
msggrep -N gnulib-lib/error.c -N gnulib-lib/getopt.c input.po
To extract the messages that contain the string “Please specify” in the original string:
msggrep --msgid -F -e 'Please specify' input.po
To extract the messages that have a context specifier of either “Menu>File” or “Menu>Edit” or a submenu of them:
msggrep --msgctxt -E -e '^Menu>(File|Edit)' input.po
To extract the messages whose translation contains one of the strings in the
file wordlist.txt:
msggrep --msgstr -F -f wordlist.txt input.po
msgfilter Programmsgfilter [option] filter [filter-option]
The msgfilter program applies a filter to all translations of a
translation catalog.
If no inputfile is given or if it is ‘-’, standard input is read.
The results are written to standard output if no output file is specified or if it is ‘-’.
The filter can be any program that reads a translation from standard input and writes a modified translation to standard output. A frequently used filter is ‘sed’. A few particular built-in filters are also recognized.
Note: If the filter is not a built-in filter, you have to care about encodings:
It is your responsibility to ensure that the filter can cope
with input encoded in the translation catalog's encoding. If the
filter wants input in a particular encoding, you can in a first step
convert the translation catalog to that encoding using the ‘msgconv’
program, before invoking ‘msgfilter’. If the filter wants input
in the locale's encoding, but you want to avoid the locale's encoding, then
you can first convert the translation catalog to UTF-8 using the
‘msgconv’ program and then make ‘msgfilter’ work in an UTF-8
locale, by using the LC_ALL environment variable.
Note: Most translations in a translation catalog don't end with a newline
character. For this reason, it is important that the filter
recognizes its last input line even if it ends without a newline, and that
it doesn't add an undesired trailing newline at the end. The ‘sed’
program on some platforms is known to ignore the last line of input if it
is not terminated with a newline. You can use GNU sed instead; it
does not have this limitation.
The filter ‘recode-sr-latin’ is recognized as a built-in filter. The command ‘recode-sr-latin’ converts Serbian text, written in the Cyrillic script, to the Latin script. The command ‘msgfilter recode-sr-latin’ applies this conversion to the translations of a PO file. Thus, it can be used to convert an sr.po file to an sr@latin.po file.
The use of built-in filters is not sensitive to the current locale's encoding. Moreover, when used with a built-in filter, ‘msgfilter’ can automatically convert the message catalog to the UTF-8 encoding when needed.
.properties
syntax, not in PO file syntax.
.strings syntax, not in PO file syntax.
.properties syntax. Note
that this file format doesn't support plural forms and silently drops
obsolete messages.
.strings syntax.
Note that this file format doesn't support plural forms.
To convert German translations to Swiss orthography (in an UTF-8 locale):
msgconv -t UTF-8 de.po | msgfilter sed -e 's/ß/ss/g'
To convert Serbian translations in Cyrillic script to Latin script:
msgfilter recode-sr-latin sr.po
msguniq Programmsguniq [option] [inputfile]
The msguniq program unifies duplicate translations in a translation
catalog. It finds duplicate translations of the same message ID. Such
duplicates are invalid input for other programs like msgfmt,
msgmerge or msgcat. By default, duplicates are merged
together. When using the ‘--repeated’ option, only duplicates are
output, and all other messages are discarded. Comments and extracted
comments will be cumulated, except that if ‘--use-first’ is
specified, they will be taken from the first translation. File positions
will be cumulated. When using the ‘--unique’ option, duplicates are
discarded.
If no inputfile is given or if it is ‘-’, standard input is read.
The results are written to standard output if no output file is specified or if it is ‘-’.
.properties
syntax, not in PO file syntax.
.strings syntax, not in PO file syntax.
.properties syntax. Note
that this file format doesn't support plural forms and silently drops
obsolete messages.
.strings syntax.
Note that this file format doesn't support plural forms.
msgcomm Programmsgcomm [option] [inputfile]...
The msgcomm program finds messages which are common to two or more
of the specified PO files.
By using the --more-than option, greater commonality may be requested
before messages are printed. Conversely, the --less-than option may be
used to specify less commonality before messages are printed (i.e.
‘--less-than=2’ will only print the unique messages). Translations,
comments and extract comments will be preserved, but only from the first
PO file to define them. File positions from all PO files will be
cumulated.
If inputfile is ‘-’, standard input is read.
The results are written to standard output if no output file is specified or if it is ‘-’.
.properties
syntax, not in PO file syntax.
.strings syntax, not in PO file syntax.
.properties syntax. Note
that this file format doesn't support plural forms and silently drops
obsolete messages.
.strings syntax.
Note that this file format doesn't support plural forms.
msgcmp Programmsgcmp [option] def.po ref.pot
The msgcmp program compares two Uniforum style .po files to check that
both contain the same set of msgid strings. The def.po file is an
existing PO file with the translations. The ref.pot file is the last
created PO file, or a PO Template file (generally created by xgettext).
This is useful for checking that you have translated each and every message
in your program. Where an exact match cannot be found, fuzzy matching is
used to produce better diagnostics.
.properties
syntax, not in PO file syntax.
.strings syntax, not in PO file syntax.
msgattrib Programmsgattrib [option] [inputfile]
The msgattrib program filters the messages of a translation catalog
according to their attributes, and manipulates the attributes.
If no inputfile is given or if it is ‘-’, standard input is read.
The results are written to standard output if no output file is specified or if it is ‘-’.
Attributes are modified after the message selection/removal has been performed. If the ‘--only-file’ or ‘--ignore-file’ option is specified, the attribute modification is applied only to those messages that are listed in the only-file and not listed in the ignore-file.
.properties
syntax, not in PO file syntax.
.strings syntax, not in PO file syntax.
.properties syntax. Note
that this file format doesn't support plural forms and silently drops
obsolete messages.
.strings syntax.
Note that this file format doesn't support plural forms.
msgen Programmsgen [option] inputfile
The msgen program creates an English translation catalog. The
input file is the last created English PO file, or a PO Template file
(generally created by xgettext). Untranslated entries are assigned a
translation that is identical to the msgid.
Note: ‘msginit --no-translator --locale=en’ performs a very similar
task. The main difference is that msginit cares specially about
the header entry, whereas msgen doesn't.
If inputfile is ‘-’, standard input is read.
The results are written to standard output if no output file is specified or if it is ‘-’.
.properties
syntax, not in PO file syntax.
.strings syntax, not in PO file syntax.
.properties syntax. Note
that this file format doesn't support plural forms and silently drops
obsolete messages.
.strings syntax.
Note that this file format doesn't support plural forms.
msgexec Programmsgexec [option] command [command-option]
The msgexec program applies a command to all translations of a
translation catalog.
The command can be any program that reads a translation from standard
input. It is invoked once for each translation. Its output becomes
msgexec's output. msgexec's return code is the maximum return code
across all invocations.
A special builtin command called ‘0’ outputs the translation, followed by a null byte. The output of ‘msgexec 0’ is suitable as input for ‘xargs -0’.
During each command invocation, the environment variable
MSGEXEC_MSGID is bound to the message's msgid, and the environment
variable MSGEXEC_LOCATION is bound to the location in the PO file
of the message. If the message has a context, the environment variable
MSGEXEC_MSGCTXT is bound to the message's msgctxt, otherwise it is
unbound.
Note: It is your responsibility to ensure that the command can cope
with input encoded in the translation catalog's encoding. If the
command wants input in a particular encoding, you can in a first step
convert the translation catalog to that encoding using the ‘msgconv’
program, before invoking ‘msgexec’. If the command wants input
in the locale's encoding, but you want to avoid the locale's encoding, then
you can first convert the translation catalog to UTF-8 using the
‘msgconv’ program and then make ‘msgexec’ work in an UTF-8
locale, by using the LC_ALL environment variable.
If no inputfile is given or if it is ‘-’, standard input is read.
.properties
syntax, not in PO file syntax.
.strings syntax, not in PO file syntax.
Translators are usually only interested in seeing the untranslated and fuzzy messages of a PO file. Also, when a message is set fuzzy because the msgid changed, they want to see the differences between the previous msgid and the current one (especially if the msgid is long and only few words in it have changed). Finally, it's always welcome to highlight the different sections of a message in a PO file (comments, msgid, msgstr, etc.).
Such highlighting is possible through the msgcat options
‘--color’ and ‘--style’.
--color optionThe ‘--color=when’ option specifies under which conditions colorized output should be generated. The when part can be one of the following:
alwaysyesnevernoautottyhtml‘--color’ is equivalent to ‘--color=yes’. The default is ‘--color=auto’.
Thus, a command like ‘msgcat vi.po’ will produce colorized output when called by itself in a command window. Whereas in a pipe, such as ‘msgcat vi.po | less -R’, it will not produce colorized output. To get colorized output in this situation nevertheless, use the command ‘msgcat --color vi.po | less -R’.
The ‘--color=html’ option will produce output that can be viewed in a browser. This can be useful, for example, for Indic languages, because the renderic of Indic scripts in browser is usually better than in terminal emulators.
Note that the output produced with the --color option is not
a valid PO file in itself. It contains additional terminal-specific escape
sequences or HTML tags. A PO file reader will give a syntax error when
confronted with such content. Except for the ‘--color=html’ case,
you therefore normally don't need to save output produced with the
--color option in a file.
TERMThe environment variable TERM contains a identifier for the text
window's capabilities. You can get a detailed list of these cababilities
by using the ‘infocmp’ command, using ‘man 5 terminfo’ as a
reference.
When producing text with embedded color directives, msgcat looks
at the TERM variable. Text windows today typically support at least
8 colors. Often, however, the text window supports 16 or more colors,
even though the TERM variable is set to a identifier denoting only
8 supported colors. It can be worth setting the TERM variable to
a different value in these cases:
xtermxterm is in most cases built with support for 16 colors. It can also
be built with support for 88 or 256 colors (but not both). You can try to
set TERM to either xterm-16color, xterm-88color, or
xterm-256color.
rxvtrxvt is often built with support for 16 colors. You can try to set
TERM to rxvt-16color.
konsolekonsole too is often built with support for 16 colors. You can try to
set TERM to konsole-16color or xterm-16color.
After setting TERM, you can verify it by invoking
‘msgcat --color=test’ and seeing whether the output looks like a
reasonable color map.
--style optionThe ‘--style=style_file’ option specifies the style file to use
when colorizing. It has an effect only when the --color option is
effective.
If the --style option is not specified, the environment variable
PO_STYLE is considered. It is meant to point to the user's
preferred style for PO files.
The default style file is $prefix/share/gettext/styles/po-default.css,
where $prefix is the installation location.
A few style files are predefined:
You can use these styles without specifying a directory. They are actually
located in $prefix/share/gettext/styles/, where $prefix is the
installation location.
You can also design your own styles. This is described in the next section.
The same style file can be used for styling of a PO file, for terminal output and for HTML output. It is written in CSS (Cascading Style Sheet) syntax. See http://www.w3.org/TR/css2/cover.html for a formal definition of CSS. Many HTML authoring tutorials also contain explanations of CSS.
In the case of HTML output, the style file is embedded in the HTML output.
In the case of text output, the style file is interpreted by the
msgcat program. This means, in particular, that when
@import is used with relative file names, the file names are
@import, in the case of
text output. (Actually, @imports are not yet supported in this case,
due to a limitation in libcroco.)
CSS rules are built up from selectors and declarations. The declarations specify graphical properties; the selectors specify specify when they apply.
In PO files, the following simple selectors (based on "CSS classes", see the CSS2 spec, section 5.8.3) are supported.
.header.translated.untranslated.fuzzy.obsolete white-space
# translator-comments
#. extracted-comments
#: reference...
#, flag...
#| msgid previous-untranslated-string
msgid untranslated-string
msgstr translated-string
.comment.translator-comment.extracted-comment.reference-comment.reference.flag-comment.flag.fuzzy-flag.previous-comment.previousmsgid etc.) and the spaces between them.
.msgidmsgid etc.) and the spaces between them.
.msgstrmsgstr etc.) and the spaces between them.
.keywordmsgid, msgstr, etc.).
.string.text.escape-sequence.format-directivejava-format and csharp-format, with a ‘~’ in the case of
lisp-format and scheme-format, or with ‘$’ in the case of
sh-format).
.invalid-format-directive.added.changed.removedThese selectors can be combined to hierarchical selectors. For example,
.msgstr .invalid-format-directive { color: red; }
will highlight the invalid format directives in the translated strings.
In text mode, pseudo-classes (CSS2 spec, section 5.11) and pseudo-elements (CSS2 spec, section 5.12) are not supported.
The declarations in HTML mode are not limited; any graphical attribute supported by the browsers can be used.
The declarations in text mode are limited to the following properties. Other properties will be silently ignored.
color (CSS2 spec, section 14.1)background-color (CSS2 spec, section 14.2.1)font-weight (CSS2 spec, section 15.2.3)normal and bold. Values >= 600 are rendered as
bold.
font-style (CSS2 spec, section 15.2.3)italic and oblique are
rendered the same way.
text-decoration (CSS2 spec, section 16.3.1)none and
underline.
less for viewing PO filesThe ‘less’ program is a popular text file browser for use in a text screen or terminal emulator. It also supports text with embedded escape sequences for colors and text decorations.
You can use less to view a PO file like this (assuming an UTF-8
environment):
msgcat --to-code=UTF-8 --color xyz.po | less -R
You can simplify this to this simple command:
less xyz.po
after these three preparations:
LESS environment
variable. In sh shells:
$ LESS="$LESS -R -f"
$ export LESS
LESSOPEN and
LESSCLOSE environment variables, as indicated in the manual page
(‘man less’).
msgcat on them, producing
a temporary file. Like this:
case "$1" in
*.po)
tmpfile=`mktemp "${TMPDIR-/tmp}/less.XXXXXX"`
msgcat --to-code=UTF-8 --color "$1" > "$tmpfile"
echo "$tmpfile"
exit 0
;;
esac
For the tasks for which a combination of ‘msgattrib’, ‘msgcat’ etc. is not sufficient, a set of C functions is provided in a library, to make it possible to process PO files in your own programs. When you use this library, you don't need to write routines to parse the PO file; instead, you retrieve a pointer in memory to each of messages contained in the PO file. Functions for writing PO files are not provided at this time.
The functions are declared in the header file ‘<gettext-po.h>’, and are defined in a library called ‘libgettextpo’.
This is a pointer type that refers to the contents of a PO file, after it has been read into memory.
This is a pointer type that refers to an iterator that produces a sequence of messages.
This is a pointer type that refers to a message of a PO file, including its translation.
The
po_file_readfunction reads a PO file into memory. The file name is given as argument. The return value is a handle to the PO file's contents, valid untilpo_file_freeis called on it. In case of error, the return value isNULL, anderrnois set.
The
po_file_freefunction frees a PO file's contents from memory, including all messages that are only implicitly accessible through iterators.
The
po_file_domainsfunction returns the domains for which the given PO file has messages. The return value is aNULLterminated array which is valid as long as the file handle is valid. For PO files which contain no ‘domain’ directive, the return value contains only one domain, namely the default domain"messages".
The
po_message_iteratorreturns an iterator that will produce the messages of file that belong to the given domain. If domain isNULL, the default domain is used instead. To list the messages, use the functionpo_next_messagerepeatedly.
The
po_message_iterator_freefunction frees an iterator previously allocated through thepo_message_iteratorfunction.
The
po_next_messagefunction returns the next message from iterator and advances the iterator. It returnsNULLwhen the iterator has reached the end of its message list.
The following functions returns details of a po_message_t. Recall
that the results are valid as long as the file handle is valid.
The
po_message_msgidfunction returns themsgid(untranslated English string) of a message. This is guaranteed to be non-NULL.
The
po_message_msgid_pluralfunction returns themsgid_plural(untranslated English plural string) of a message with plurals, orNULLfor a message without plural.
The
po_message_msgstrfunction returns themsgstr(translation) of a message. For an untranslated message, the return value is an empty string.
The
po_message_msgstr_pluralfunction returns themsgstr[index]of a message with plurals, orNULLwhen the index is out of range or for a message without plural.
Here is an example code how these functions can be used.
const char *filename = ...;
po_file_t file = po_file_read (filename);
if (file == NULL)
error (EXIT_FAILURE, errno, "couldn't open the PO file %s", filename);
{
const char * const *domains = po_file_domains (file);
const char * const *domainp;
for (domainp = domains; *domainp; domainp++)
{
const char *domain = *domainp;
po_message_iterator_t iterator = po_message_iterator (file, domain);
for (;;)
{
po_message_t *message = po_next_message (iterator);
if (message == NULL)
break;
{
const char *msgid = po_message_msgid (message);
const char *msgstr = po_message_msgstr (message);
...
}
}
po_message_iterator_free (iterator);
}
}
po_file_free (file);
msgfmt Programmsgfmt [option] filename.po ...
The msgfmt programs generates a binary message catalog from a textual
translation description.
If an input file is ‘-’, standard input is read.
ResourceBundle class.
GettextResourceSet.
We find this behaviour of Sun's implementation rather silly and so by default this mode is not selected.
If the output file is ‘-’, output is written to standard output.
The class name is determined by appending the locale name to the resource name, separated with an underscore. The ‘-d’ option is mandatory. The class is written under the specified directory.
The ‘-l’ and ‘-d’ options are mandatory. The .dll file is written in a subdirectory of the specified directory whose name depends on the locale.
The ‘-l’ and ‘-d’ options are mandatory. The .msg file is written in the specified directory.
.properties
syntax, not in PO file syntax.
.strings syntax, not in PO file syntax.
--check-format, --check-header,
--check-domain.
If the string represents a format string used in a
printf-like function both strings should have the same number of
‘%’ format specifiers, with matching types. If the flag
c-format or possible-c-format appears in the special
comment <#,> for this entry a check is performed. For example, the
check will diagnose using ‘%.*s’ against ‘%s’, or ‘%d’
against ‘%s’, or ‘%d’ against ‘%x’. It can even handle
positional parameters.
Normally the xgettext program automatically decides whether a
string is a format string or not. This algorithm is not perfect,
though. It might regard a string as a format string though it is not
used in a printf-like function and so msgfmt might report
errors where there are none.
To solve this problem the programmer can dictate the decision to the
xgettext program (see c-format). The translator should not
consider removing the flag from the <#,> line. This "fix" would be
reversed again as soon as msgmerge is called the next time.
--output-file
option
msgunfmt Programmsgunfmt [option] [file]...
The msgunfmt program converts a binary message catalog to a
Uniforum style .po file.
ResourceBundle class.
GettextResourceSet.
If no input file is given or if it is ‘-’, standard input is read.
The class name is determined by appending the locale name to the resource name,
separated with an underscore. The class is located using the CLASSPATH.
The ‘-l’ and ‘-d’ options are mandatory. The .msg file is located in a subdirectory of the specified directory whose name depends on the locale.
The ‘-l’ and ‘-d’ options are mandatory. The .msg file is located in the specified directory.
The results are written to standard output if no output file is specified or if it is ‘-’.
.properties syntax. Note
that this file format doesn't support plural forms and silently drops
obsolete messages.
.strings syntax.
Note that this file format doesn't support plural forms.
The format of the generated MO files is best described by a picture, which appears below.
The first two words serve the identification of the file. The magic
number will always signal GNU MO files. The number is stored in the
byte order of the generating machine, so the magic number really is
two numbers: 0x950412de and 0xde120495. The second
word describes the current revision of the file format. For now the
revision is 0. This might change in future versions, and ensures
that the readers of MO files can distinguish new formats from old
ones, so that both can be handled correctly. The version is kept
separate from the magic number, instead of using different magic
numbers for different formats, mainly because /etc/magic is
not updated often. It might be better to have magic separated from
internal format version identification.
Follow a number of pointers to later tables in the file, allowing for the extension of the prefix part of MO files without having to recompile programs reading them. This might become useful for later inserting a few flag bits, indication about the charset used, new tables, or other things.
Then, at offset O and offset T in the picture, two tables of string descriptors can be found. In both tables, each string descriptor uses two 32 bits integers, one for the string length, another for the offset of the string in the MO file, counting in bytes from the start of the file. The first table contains descriptors for the original strings, and is sorted so the original strings are in increasing lexicographical order. The second table contains descriptors for the translated strings, and is parallel to the first table: to find the corresponding translation one has to access the array slot in the second array with the same index.
Having the original strings sorted enables the use of simple binary
search, for when the MO file does not contain an hashing table, or
for when it is not practical to use the hashing table provided in
the MO file. This also has another advantage, as the empty string
in a PO file GNU gettext is usually translated into
some system information attached to that particular MO file, and the
empty string necessarily becomes the first in both the original and
translated tables, making the system information very easy to find.
The size S of the hash table can be zero. In this case, the
hash table itself is not contained in the MO file. Some people might
prefer this because a precomputed hashing table takes disk space, and
does not win that much speed. The hash table contains indices
to the sorted array of strings in the MO file. Conflict resolution is
done by double hashing. The precise hashing algorithm used is fairly
dependent on GNU gettext code, and is not documented here.
As for the strings themselves, they follow the hash file, and each
is terminated with a <NUL>, and this <NUL> is not counted in
the length which appears in the string descriptor. The msgfmt
program has an option selecting the alignment for MO file strings.
With this option, each string is separately aligned so it starts at
an offset which is a multiple of the alignment value. On some RISC
machines, a correct alignment will speed things up.
Contexts are stored by storing the concatenation of the context, a <EOT> byte, and the original string, instead of the original string.
Plural forms are stored by letting the plural of the original string follow the singular of the original string, separated through a <NUL> byte. The length which appears in the string descriptor includes both. However, only the singular of the original string takes part in the hash table lookup. The plural variants of the translation are all stored consecutively, separated through a <NUL> byte. Here also, the length in the string descriptor includes all of them.
Nothing prevents a MO file from having embedded <NUL>s in strings. However, the program interface currently used already presumes that strings are <NUL> terminated, so embedded <NUL>s are somewhat useless. But the MO file format is general enough so other interfaces would be later possible, if for example, we ever want to implement wide characters right in MO files, where <NUL> bytes may accidentally appear. (No, we don't want to have wide characters in MO files. They would make the file unnecessarily large, and the ‘wchar_t’ type being platform dependent, MO files would be platform dependent as well.)
This particular issue has been strongly debated in the GNU
gettext development forum, and it is expectable that MO file
format will evolve or change over time. It is even possible that many
formats may later be supported concurrently. But surely, we have to
start somewhere, and the MO file format described here is a good start.
Nothing is cast in concrete, and the format may later evolve fairly
easily, so we should feel comfortable with the current approach.
byte
+------------------------------------------+
0 | magic number = 0x950412de |
| |
4 | file format revision = 0 |
| |
8 | number of strings | == N
| |
12 | offset of table with original strings | == O
| |
16 | offset of table with translation strings | == T
| |
20 | size of hashing table | == S
| |
24 | offset of hashing table | == H
| |
. .
. (possibly more entries later) .
. .
| |
O | length & offset 0th string ----------------.
O + 8 | length & offset 1st string ------------------.
... ... | |
O + ((N-1)*8)| length & offset (N-1)th string | | |
| | | |
T | length & offset 0th translation ---------------.
T + 8 | length & offset 1st translation -----------------.
... ... | | | |
T + ((N-1)*8)| length & offset (N-1)th translation | | | | |
| | | | | |
H | start hash table | | | | |
... ... | | | |
H + S * 4 | end hash table | | | | |
| | | | | |
| NUL terminated 0th string <----------------' | | |
| | | | |
| NUL terminated 1st string <------------------' | |
| | | |
... ... | |
| | | |
| NUL terminated 0th translation <---------------' |
| | |
| NUL terminated 1st translation <-----------------'
| |
... ...
| |
+------------------------------------------+
One aim of the current message catalog implementation provided by
GNU gettext was to use the system's message catalog handling, if the
installer wishes to do so. So we perhaps should first take a look at
the solutions we know about. The people in the POSIX committee did not
manage to agree on one of the semi-official standards which we'll
describe below. In fact they couldn't agree on anything, so they decided
only to include an example of an interface. The major Unix vendors
are split in the usage of the two most important specifications: X/Open's
catgets vs. Uniforum's gettext interface. We'll describe them both and
later explain our solution of this dilemma.
catgets
The catgets implementation is defined in the X/Open Portability
Guide, Volume 3, XSI Supplementary Definitions, Chapter 5. But the
process of creating this standard seemed to be too slow for some of
the Unix vendors so they created their implementations on preliminary
versions of the standard. Of course this leads again to problems while
writing platform independent programs: even the usage of catgets
does not guarantee a unique interface.
Another, personal comment on this that only a bunch of committee members could have made this interface. They never really tried to program using this interface. It is a fast, memory-saving implementation, an user can happily live with it. But programmers hate it (at least I and some others do...)
But we must not forget one point: after all the trouble with transferring the rights on Unix(tm) they at last came to X/Open, the very same who published this specification. This leads me to making the prediction that this interface will be in future Unix standards (e.g. Spec1170) and therefore part of all Unix implementation (implementations, which are allowed to wear this name).
The interface to the catgets implementation consists of three
functions which correspond to those used in file access: catopen
to open the catalog for using, catgets for accessing the message
tables, and catclose for closing after work is done. Prototypes
for the functions and the needed definitions are in the
<nl_types.h> header file.
nl_catd catd = catopen ("catalog_name", 0);
The function takes as the argument the name of the catalog. This usual
refers to the name of the program or the package. The second parameter
is not further specified in the standard. I don't even know whether it
is implemented consistently among various systems. So the common advice
is to use 0 as the value. The return value is a handle to the
message catalog, equivalent to handles to file returned by open.
This handle is of course used in the catgets function which can
be used like this:
char *translation = catgets (catd, set_no, msg_id, "original string");
The first parameter is this catalog descriptor. The second parameter
specifies the set of messages in this catalog, in which the message
described by msg_id is obtained. catgets therefore uses a
three-stage addressing:
catalog name set number message ID translation
The fourth argument is not used to address the translation. It is given
as a default value in case when one of the addressing stages fail. One
important thing to remember is that although the return type of catgets
is char * the resulting string must not be changed. It
should better be const char *, but the standard is published in
1988, one year before ANSI C.
The last of these functions is used and behaves as expected:
catclose (catd);
After this no catgets call using the descriptor is legal anymore.
catgets Interface?!
Now that this description seemed to be really easy — where are the
problems we speak of? In fact the interface could be used in a
reasonable way, but constructing the message catalogs is a pain. The
reason for this lies in the third argument of catgets: the unique
message ID. This has to be a numeric value for all messages in a single
set. Perhaps you could imagine the problems keeping such a list while
changing the source code. Add a new message here, remove one there. Of
course there have been developed a lot of tools helping to organize this
chaos but one as the other fails in one aspect or the other. We don't
want to say that the other approach has no problems but they are far
more easy to manage.
gettext
The definition of the gettext interface comes from a Uniforum
proposal. It was submitted there by Sun, who had implemented the
gettext function in SunOS 4, around 1990. Nowadays, the
gettext interface is specified by the OpenI18N standard.
The main point about this solution is that it does not follow the method of normal file handling (open-use-close) and that it does not burden the programmer with so many tasks, especially the unique key handling. Of course here also a unique key is needed, but this key is the message itself (how long or short it is). See Comparison for a more detailed comparison of the two methods.
The following section contains a rather detailed description of the
interface. We make it that detailed because this is the interface
we chose for the GNU gettext Library. Programmers interested
in using this library will be interested in this description.
The minimal functionality an interface must have is a) to select a domain the strings are coming from (a single domain for all programs is not reasonable because its construction and maintenance is difficult, perhaps impossible) and b) to access a string in a selected domain.
This is principally the description of the gettext interface. It
has a global domain which unqualified usages reference. Of course this
domain is selectable by the user.
char *textdomain (const char *domain_name);
This provides the possibility to change or query the current status of
the current global domain of the LC_MESSAGE category. The
argument is a null-terminated string, whose characters must be legal in
the use in filenames. If the domain_name argument is NULL,
the function returns the current value. If no value has been set
before, the name of the default domain is returned: messages.
Please note that although the return value of textdomain is of
type char * no changing is allowed. It is also important to know
that no checks of the availability are made. If the name is not
available you will see this by the fact that no translations are provided.
To use a domain set by textdomain the function
char *gettext (const char *msgid);
is to be used. This is the simplest reasonable form one can imagine.
The translation of the string msgid is returned if it is available
in the current domain. If it is not available, the argument itself is
returned. If the argument is NULL the result is undefined.
One thing which should come into mind is that no explicit dependency to
the used domain is given. The current value of the domain is used.
If this changes between two
executions of the same gettext call in the program, both calls
reference a different message catalog.
For the easiest case, which is normally used in internationalized
packages, once at the beginning of execution a call to textdomain
is issued, setting the domain to a unique name, normally the package
name. In the following code all strings which have to be translated are
filtered through the gettext function. That's all, the package speaks
your language.
While this single name domain works well for most applications there
might be the need to get translations from more than one domain. Of
course one could switch between different domains with calls to
textdomain, but this is really not convenient nor is it fast. A
possible situation could be one case subject to discussion during this
writing: all
error messages of functions in the set of common used functions should
go into a separate domain error. By this mean we would only need
to translate them once.
Another case are messages from a library, as these have to be
independent of the current domain set by the application.
For this reasons there are two more functions to retrieve strings:
char *dgettext (const char *domain_name, const char *msgid);
char *dcgettext (const char *domain_name, const char *msgid,
int category);
Both take an additional argument at the first place, which corresponds
to the argument of textdomain. The third argument of
dcgettext allows to use another locale category but LC_MESSAGES.
But I really don't know where this can be useful. If the
domain_name is NULL or category has an value beside
the known ones, the result is undefined. It should also be noted that
this function is not part of the second known implementation of this
function family, the one found in Solaris.
A second ambiguity can arise by the fact, that perhaps more than one domain has the same name. This can be solved by specifying where the needed message catalog files can be found.
char *bindtextdomain (const char *domain_name,
const char *dir_name);
Calling this function binds the given domain to a file in the specified
directory (how this file is determined follows below). Especially a
file in the systems default place is not favored against the specified
file anymore (as it would be by solely using textdomain). A
NULL pointer for the dir_name parameter returns the binding
associated with domain_name. If domain_name itself is
NULL nothing happens and a NULL pointer is returned. Here
again as for all the other functions is true that none of the return
value must be changed!
It is important to remember that relative path names for the
dir_name parameter can be trouble. Since the path is always
computed relative to the current directory different results will be
achieved when the program executes a chdir command. Relative
paths should always be avoided to avoid dependencies and
unreliabilities.
Because many different languages for many different packages have to be
stored we need some way to add these information to file message catalog
files. The way usually used in Unix environments is have this encoding
in the file name. This is also done here. The directory name given in
bindtextdomains second argument (or the default directory),
followed by the name of the locale, the locale category, and the domain name
are concatenated:
dir_name/locale/LC_category/domain_name.mo
The default value for dir_name is system specific. For the GNU library, and for packages adhering to its conventions, it's:
/usr/local/share/locale
locale is the name of the locale category which is designated by
LC_category. For gettext and dgettext this
LC_category is always LC_MESSAGES.3
The name of the locale category is determined through
setlocale (LC_category, NULL).
4
When using the function dcgettext, you can specify the locale category
through the third argument.
gettext uses
gettext not only looks up a translation in a message catalog. It
also converts the translation on the fly to the desired output character
set. This is useful if the user is working in a different character set
than the translator who created the message catalog, because it avoids
distributing variants of message catalogs which differ only in the
character set.
The output character set is, by default, the value of nl_langinfo
(CODESET), which depends on the LC_CTYPE part of the current
locale. But programs which store strings in a locale independent way
(e.g. UTF-8) can request that gettext and related functions
return the translations in that encoding, by use of the
bind_textdomain_codeset function.
Note that the msgid argument to gettext is not subject to
character set conversion. Also, when gettext does not find a
translation for msgid, it returns msgid unchanged –
independently of the current output character set. It is therefore
recommended that all msgids be US-ASCII strings.
The
bind_textdomain_codesetfunction can be used to specify the output character set for message catalogs for domain domainname. The codeset argument must be a valid codeset name which can be used for theiconv_openfunction, or a null pointer.If the codeset parameter is the null pointer,
bind_textdomain_codesetreturns the currently selected codeset for the domain with the name domainname. It returnsNULLif no codeset has yet been selected.The
bind_textdomain_codesetfunction can be used several times. If used multiple times with the same domainname argument, the later call overrides the settings made by the earlier one.The
bind_textdomain_codesetfunction returns a pointer to a string containing the name of the selected codeset. The string is allocated internally in the function and must not be changed by the user. If the system went out of core during the execution ofbind_textdomain_codeset, the return value isNULLand the global variable errno is set accordingly.
One place where the gettext functions, if used normally, have big
problems is within programs with graphical user interfaces (GUIs). The
problem is that many of the strings which have to be translated are very
short. They have to appear in pull-down menus which restricts the
length. But strings which are not containing entire sentences or at
least large fragments of a sentence may appear in more than one
situation in the program but might have different translations. This is
especially true for the one-word strings which are frequently used in
GUI programs.
As a consequence many people say that the gettext approach is
wrong and instead catgets should be used which indeed does not
have this problem. But there is a very simple and powerful method to
handle this kind of problems with the gettext functions.
Contexts can be added to strings to be translated. A context dependent translation lookup is when a translation for a given string is searched, that is limited to a given context. The translation for the same string in a different context can be different. The different translations of the same string in different contexts can be stored in the in the same MO file, and can be edited by the translator in the same PO file.
The gettext.h include file contains the lookup macros for strings
with contexts. They are implemented as thin macros and inline functions
over the functions from <libintl.h>.
const char *pgettext (const char *msgctxt, const char *msgid);
In a call of this macro, msgctxt and msgid must be string literals. The macro returns the translation of msgid, restricted to the context given by msgctxt.
The msgctxt string is visible in the PO file to the translator. You should try to make it somehow canonical and never changing. Because every time you change an msgctxt, the translator will have to review the translation of msgid.
Finding a canonical msgctxt string that doesn't change over time can
be hard. But you shouldn't use the file name or class name containing the
pgettext call – because it is a common development task to rename
a file or a class, and it shouldn't cause translator work. Also you shouldn't
use a comment in the form of a complete English sentence as msgctxt –
because orthography or grammar changes are often applied to such sentences,
and again, it shouldn't force the translator to do a review.
The ‘p’ in ‘pgettext’ stands for “particular”: pgettext
fetches a particular translation of the msgid.
const char *dpgettext (const char *domain_name,
const char *msgctxt, const char *msgid);
const char *dcpgettext (const char *domain_name,
const char *msgctxt, const char *msgid,
int category);
These are generalizations of pgettext. They behave similarly to
dgettext and dcgettext, respectively. The domain_name
argument defines the translation domain. The category argument
allows to use another locale category than LC_MESSAGES.
As as example consider the following fictional situation. A GUI program has a menu bar with the following entries:
+------------+------------+--------------------------------------+
| File | Printer | |
+------------+------------+------------------