Difference between revisions of "Translations / i18n / localizations for programs"

From Free Pascal wiki
Jump to navigationJump to search
(→‎See also: Add explicit link to "everything else" for this subject)
 
(60 intermediate revisions by 18 users not shown)
Line 1: Line 1:
 
{{Translations_/_i18n_/_localizations_for_programs}}
 
{{Translations_/_i18n_/_localizations_for_programs}}
==Overview==
 
  
This is about how a program can use different strings for various languages like english, chinese, german, finnish, italian, ... .
+
This is about how a program can use different strings for various languages like English, Chinese, German, Finnish, Italian and any other language.
Basically it works like this: Add a ''resourcestring'' for every caption, compile to get the .rst and/or .po files (the IDE can do this automatically), create one translated .po file for each language (there are free graphical tools) and use the functions of the LCL ''translations'' unit to load the right one at start of the program.
 
  
==Date, time and number format==
+
* '''i18n''' is short for '''internationalization''' (18 being the number of characters between i and n of the word internationalization)
 +
* '''l10n''' is short for '''localization''' (10 being the number of characters between l and n of the word localization)
  
Under Linux, BSD, Mac OS X there are several locales defining things like time and date format or the thousand separator. In order to initialize the RTL you need to iclude the clocale unit in the uses section of your program (lpr file).
 
  
==Resourcestrings==
+
==Quick i18n==
  
For example
+
This is intended as be a quick guide to introduce yourself in the world of translations and get things done quickly. Check also [[Language Codes]] and [[BidiMode]].
<delphi>resourcestring
 
  Caption1 = 'Some text';
 
  HelloWorld1 = 'Hello World';</delphi>
 
  
These are like normal string constants, that means you can assign them to any string. For example
+
For your information the most used languages in the world ([http://www.redlinels.com/2014/01/10/most-widely-spoken-languages/ source]) are:
<delphi>Label1.Caption := HelloWorld1;</delphi>
 
  
When fpc compiles them, it creates for each unit a file '''unitname.rst''', containing the resourcestring data (name + content).
+
* 1 - Chinese: With more than 1.2 billion native speakers in the world
 +
* 2 - Spanish: Spanish occupies the No. 2 spot and is spoken in approximately 30 countries.
 +
* 3 - English: 335 million worldwide—about 5% of the world’s population. (This does not takes into account second language spoken).
 +
* 4 - Hindi: Spoken by over 260 million people.
 +
* 5 - Arabic: Spoken in almost 60 countries around the world.
 +
* 6 - Portuguese: Population of Brazil is over 200 million. The population of Portugal is just over 10 million.
 +
* 7 - Bengali: The main language of Bangladesh (population, 155 million) and one of India’s many official languages.
 +
* 8 - Russian and Japanese.
  
==.po Files==
+
===poedit===
  
There are many free graphical tools to edit .po files, which are simple text like the .rst files, but with some more options, like a header providing fields for author, encoding, language and date. Every fpc installation provides the tool '''rstconv''' (windows: rstconv.exe). This tool can be used to convert a .rst file into a .po file. The IDE can do this automatically.
+
The best known tool is a program called [https://poedit.net/ poedit]. poedit is a tool for translators. It produces both PO and MO as output.
Examples for free tools: kbabel, poedit.
 
  
Example using rstconv directly:
+
===Translating Forms===
  rstconv -i unit1.rst -o unit1.po
 
  
==Translating==
+
When you save a form with the i18n options enabled, it generates a file .lrj, that file is used to create the final .po file. So is very important that you include that file with your source code in the version system you're using, don't add that file to ignored (say .gitignore), else your translations will be broken.
  
For every language the .po file must be copied and translated. The LCL translation unit uses the common language codes (en=english, de=german, it=italian, ...) to search. For example the german translation of unit1.po would be unit1.de.po. This means, copy the unit1.po file to unit1.de.po, unit1.it.po, and whatever language you want to support and then the translators can edit their specific .po file.
+
===Translating Resourcestrings===
  
'''Note to brazilians/portugueses:''': Lazarus IDE and LCL has only brazillian portuguese translations and these files are 'pb.po' extensions and not 'pt.po'.
+
This is the way to store a resourcestring in a unit:
  
==IDE options for automatic updates of .po files==
+
<syntaxhighlight lang="pascal">
 +
resourcestring
 +
  Caption1 = 'Some text';
 +
  HelloWorld1 = 'Hello World';
 +
</syntaxhighlight>
  
*The unit containing the resource strings must be added to the package or project.
+
Resourcestrings are like normal string constants, that means you can assign them to any string:
*You must provide a .po path, this means a separate directory. For example: create a sub directory ''language'' in the package / project directory. For projects go to the Project > Project Options. For packages go to Options > IDE integration.
 
  
When this options are enabled, the IDE generates or updates the base .po file using the information contained in .rst and .lrt files (rstconv tool is then not necesary). The update process begins by collecting all existing entries found in base .po file and in .rst and .lrt files and then applying the following features it finds and brings up to date any translated .xx.po file.  
+
<syntaxhighlight lang="pascal">Label1.Caption := HelloWorld1;</syntaxhighlight>
  
===Remove of Obsolete entries===
+
===Compiling into .po files===
  
Entries in base .po file not found in .rst and .lrt files are removed, subsequently, all entries found in translated .xx.po files not found in base .po file are also removed. This way .po files are not cluttered with obsolete entries and translators don't have to translate entries that are not used.
+
Resourcestrings are compiled into .po files if you enable i18n in the Lazarus IDE. Go to Project > Project Options > i18n > Enable i18n. When you recompile your application the .po files will be updated. You may also select a directory where .po files will be stored, recommended '''po_files'''.
  
===Duplicate entries===
+
The default translation is recommended to be in English or the default language of your application, since it will be loaded if no other translation file is found.
  
Duplicate entries occur when for some reason the same text is used for diferent resource strings, a random example of this is the file lazarus/ide/lazarusidestrconst.pas for the 'Gutter' string:
+
When you have your '''project1.po''' copy and paste it and rename it to '''project1.es.po''' or one of the [[Language Codes]] of your choice. Then you will have 2 languages: English and Spanish. Then you must send to the translator the files for translation.
<Delphi>  dlfMouseSimpleGutterSect = 'Gutter';
 
  dlgMouseOptNodeGutter = 'Gutter';
 
  dlgGutter = 'Gutter';
 
  dlgAddHiAttrGroupGutter = 'Gutter';
 
</Delphi>
 
A converted .rst file for this resource strings would look similar to this in a .po file:
 
  
#: lazarusidestrconsts.dlfmousesimpleguttersect
+
Your folder structure will look something like this:
msgid "Gutter"
 
msgstr ""
 
#: lazarusidestrconsts.dlgaddhiattrgroupgutter
 
msgid "Gutter"
 
msgstr ""
 
etc.
 
 
Where the lines starting with "#: " are considered comments and the tools used to translate this entries see the repeated msgid "Gutter" lines like duplicated entries and produce errors or warnings on loading or saving. Duplicate entries are considered a normal eventuality on .po files and they need to have some context attached to them. The msgctxt keyword is used to add context to duplicated entries and the automatic update tool use the entry ID (the text next to "#: " prefix) as the context, for the previous example it would produce something like this:
 
  
#: lazarusidestrconsts.dlfmousesimpleguttersect
+
<syntaxhighlight lang="text">
msgctxt "lazarusidestrconsts.dlfmousesimpleguttersect"
+
project1\po_files\
msgid "Gutter"
+
project1\po_files\project1.po
msgstr ""
+
project1\po_files\project1.es.po
#: lazarusidestrconsts.dlgaddhiattrgroupgutter
+
</syntaxhighlight>
msgctxt "lazarusidestrconsts.dlgaddhiattrgroupgutter"
 
msgid "Gutter"
 
msgstr ""
 
etc.
 
 
On translated .xx.po files the automatic tool does one additional check: if the duplicated entry was already translated, the new entry gets the old translation, so it appears like being translated automatically.
 
  
The automatic detection of duplicates is not yet perfect, duplicate detection is made as items are added to the list and it may happen that some untranslated entries are read first. So it may take several passes to get all duplicates automatically translated by the tool.
+
===Converting .po files to .mo files===
  
===Fuzzy entries===
+
When you have the translation finished in the .po file, you want to compile it to .mo to load it faster since is a binary format. To convert to .mo you can use poedit and go to File > Compile as .mo.
  
Changes in resource strings affect translations, for example if initially a resource string was defined like:
+
Note that [[Everything else about translations]] has a section about where a Lazarus app looks for its language files.
<Delphi>dlgEdColor = 'Syntax highlight';</Delphi>
 
  
this would produce a .po entry similar to this
+
===Automatic translation===
  
#: lazarusidestrconsts.dlgedcolor
+
When you have the .mo files ready, put them in the '''locale''' or '''languages''' folder right to your application executable, then include the unit '''DefaultTranslator''' and that's all. The translation will be done automatically.
msgid "Syntax higlight"
 
msgstr ""
 
which if translated to spanish langauge (this sample was taken from lazarus history), may result in
 
#: lazarusidestrconsts.dlgedcolor
 
msgid "Syntax higlight"
 
msgstr "Color"
 
Suppose then that at a later time, the resource string has been changed to
 
<Delphi>
 
  dlgEdColor = 'Colors';
 
</Delphi>
 
the resulting .po entry may become
 
#: lazarusidestrconsts.dlgedcolor
 
msgid "Colors"
 
msgstr ""
 
Note that while ID remained the same lazarusidestrconsts.dlgedcolor the string has changed from 'Syntax highlight' to 'Colors', as the string was already translated the old translation may not match the new the new meaning. Indeed, for the new string probably 'Colores' may be a better translation.  
 
The automatic update tool notices this situation and produce an entry like this:
 
#: lazarusidestrconsts.dlgedcolor
 
#, fuzzy
 
#| msgid "Syntax highlight"
 
msgctxt "lazarusidestrconsts.dlgedcolor"
 
msgid "Colors"
 
msgstr "Color"
 
In terms of .po file format, the "#," prefix means the entry has a flag (fuzzy) and translator programs may present to the translator user a special gui for this item, in this case the flag would mean that the translation in its current state is doubtful and needs to be reviewed more careful by translator. The "#|" prefix indicates what was the previous untranslated string of this entry and gives the translator a hint why the entry was marked as fuzzy.
 
  
==Translating Forms, Datamodules and Frames==
+
<syntaxhighlight lang="pascal">
 +
uses
 +
  DefaultTranslator;
 +
</syntaxhighlight>
  
When the i18n option is enabled for the project / package then the IDE automatically creates .lrt files for every form. It creates the .lrt file on saving a unit. So, if you enable the option for the first time, you must open every form once, move it a little bit, so that it is modified, and save the form. For example if you save a form ''unit1.pas'' the IDE creates a ''unit1.lrt''. And on compile the IDE gathers all strings of all .lrt files and all .rst file into a single .po file (projectname.po or packagename.po) in the i18n directory.
+
You want to distribute only the .mo files in the '''locale''' or '''languages''' directory, since .po files are usefull only for making the translation and compiling them into a .mo file.
  
For the forms to be actually translated at runtime, you have to assign a translator to LRSTranslator (defined in LResources) in the initialization section to one of your units
+
Your folder structure will look something like this:
  
<Delphi>...
+
<syntaxhighlight lang="text">
uses
+
project1\project1.exe
  ...
+
project1\locale\
  LResources;
+
project1\locale\project1.mo
...
+
project1\locale\project1.es.mo
...
+
</syntaxhighlight>
initialization
 
  LRSTranslator := TPoTranslator.Create('/path/to/the/po/file');</Delphi>
 
  
<s>However there's no TPoTranslator class (i.e a class that translates using .po files) available in the LCL. This is a possible implementation (partly lifted from DefaultTranslator.pas in the LCL):</s> The following code isn't needed anymore if you use recent Lazarus 0.9.29 snapshots. Simply include DefaultTranslator in Uses clause.
+
===Testing translations===
  
<Delphi>unit PoTranslator;
+
When you have everything ready. you want to test if the translations looks fine in your application for each language you have. Automatic translation has a feature that you can use in order to test each language quickly.
  
{$mode objfpc}{$H+}
+
You must run your executable with the command line parameter '''--lang''' followed by the language code of your choice.
  
interface
+
You will run your executable like this in order to test Spanish translation:
  
uses
+
<syntaxhighlight lang="text">
  Classes, SysUtils, LResources, typinfo, Translations;
+
project1.exe --lang es
 +
</syntaxhighlight>
  
type
+
And you will see the translated application.
  
{ TPoTranslator }
+
You can do this with the IDE. Go to '''Run > Run Parameters ...'''. In that window in the input '''Command line parameters (without application name)''' write this:
  
TPoTranslator=class(TAbstractTranslator)
+
<syntaxhighlight lang="text">
private
+
--lang it
  FPOFile:TPOFile;
+
</syntaxhighlight>
public
 
  constructor Create(POFileName:string);
 
  destructor Destroy;override;
 
  procedure TranslateStringProperty(Sender:TObject;
 
    const Instance: TPersistent; PropInfo: PPropInfo; var Content:string);override;
 
end;
 
  
implementation
+
Then '''Run (F9)''' and you will see the translated application.
  
{ TPoTranslator }
+
===Final steps===
  
constructor TPoTranslator.Create(POFileName: string);
+
These steps are to get a better result for your entire translation.
begin
 
  inherited Create;
 
  FPOFile:=TPOFile.Create(POFileName);
 
end;
 
  
destructor TPoTranslator.Destroy;
+
====Translate LCL====
begin
 
  FPOFile.Free;
 
  inherited Destroy;
 
end;
 
  
procedure TPoTranslator.TranslateStringProperty(Sender: TObject;
+
To get everything translated you must include the LCL translations into your application '''locale''' folder.
  const Instance: TPersistent; PropInfo: PPropInfo; var Content: string);
 
var
 
  s: String;
 
begin
 
  if not Assigned(FPOFile) then exit;
 
  if not Assigned(PropInfo) then exit;
 
{DO we really need this?}
 
  if Instance is TComponent then
 
  if csDesigning in (Instance as TComponent).ComponentState then exit;
 
{End DO :)}
 
  if (AnsiUpperCase(PropInfo^.PropType^.Name)<>'TTRANSLATESTRING') then exit;
 
  s:=FPOFile.Translate(Content, Content);
 
  if s<>'' then Content:=s;
 
end;
 
  
end.</Delphi>
+
Copy everything inside the folder '''C:\lazarus\lcl\languages''' to your '''locale''' folder. Then you will have the LCL translated for your application.
  
Alternatively you can transform the .po file into .mo using msgfmt (isn't needed anymore if you use recent 0.9.29 snapshot) and simply use the DefaultTranslator unit
+
====Format Settings====
  
<Delphi>...
+
For Windows you must read [[Step-by-step instructions for creating multi-language applications#Format settings]] to get format settings in the right place.
uses
 
  ...
 
  DefaultTranslator;</Delphi>
 
  
which will automatically look in several standard places for a .mo file (the disadvantage is that you'll have to keep around both the .mo files for the DefaultTranslator unit and the .po files for TranslateUnitResourceStrings).
+
Under Linux, BSD and macOS there are several locales defining things like time and date format or the thousands separator. In order to initialize the RTL you need to include the '''clocale''' unit in the uses section of your program (.lpr file).
If you use DefaultTranslator, it will try to automatically detect the language based on the LANG environment variable (overridable using the --lang command line switch), then look in these places for the translation (LANG stands for the desired language):
 
  
*  <Application Directory>/LANG/<Application Filename>.mo
+
====BiDiMode====
*  <Application Directory>/languages/LANG/<Application Filename>.mo
 
*  <Application Directory>/locale/LANG/<Application Filename>.mo
 
*  <Application Directory>/locale/LC_MESSAGES/LANG/<Application Filename>.mo
 
  
under unix-like systems it will also look in
+
[[BidiMode]] is for languages like Arabic that read and write right to left. See also [http://www.w3.org/International/questions/qa-scripts.en Script direction and languages] for a list of LTR (Left To Right) and RTL (Right To Left) languages and most used languages in general.
  
*  /usr/share/locale/LANG/LC_MESSAGES/<Application Filename>.mo
+
With this unit you can determine what BiDiMode is right for you. This code is tested in Lazarus Trunk and may or not work in current release (see the changes on this page to get the old source).
  
as well as using the short part of the language (e.g. if it is "es_ES" or "es_ES.UTF-8" and it doesn't exist it will also try "es")
+
First save this unit as ubidimodetools.pas:
  
==Translating at start of program==
+
<syntaxhighlight lang="pascal">
 +
unit ubidimodetools;
  
For every .po file, you must call TranslateUnitResourceStrings of the LCL translations unit. For example:
+
{$mode objfpc}{$H+}
  
<pascal>    {First of all: add "gettext" and "translations" units in uses clause}
+
interface
    procedure TForm1.FormCreate(Sender: TObject);
 
    var
 
      PODirectory, Lang, FallbackLang: String;
 
    begin
 
      PODirectory := '/path/to/lazarus/lcl/languages/';
 
      GetLanguageIDs(Lang, FallbackLang); // in unit gettext
 
      TranslateUnitResourceStrings('LCLStrConsts', PODirectory + 'lclstrconsts.%s.po', Lang, FallbackLang);
 
      MessageDlg('Title', 'Text', mtInformation, [mbOk, mbCancel, mbYes], 0);
 
    end;</pascal>
 
  
==Compiling po files into the executable==
+
uses
 +
  Classes, SysUtils;
  
If you don't want to install the .po files, but put all files of the application into the executable, use the following:
+
function GetLang: string;
 +
function GetBiDiMode: TBiDiMode;
  
*Create a new unit (not a form!).
+
implementation
*Convert the .po file(s) to .lrs using tools/lazres:
 
<pre>
 
./lazres unit1.lrs unit1.de.po
 
</pre>
 
  
This will create an include file unit1.lrs beginning with
+
uses
<pascal>LazarusResources.Add('unit1.de','PO',[
+
  FileUtil, LCLProc, LazUTF8;
  ...</pascal>
 
  
*Add the code:
+
function GetLang: string;
<pascal>uses LResources, Translations;
+
var
 +
  T: string; // unused FallBackLang
 +
  i: integer;
 +
begin
 +
  Result := '';
 +
  { We use the same method that is used in LCLTranslator unit }
 +
 
 +
  for i := 1 to Paramcount - 1 do
 +
    if (ParamStrUTF8(i) = '--LANG') or (ParamStrUTF8(i) = '-l') or
 +
      (ParamStrUTF8(i) = '--lang') then
 +
      Result := ParamStrUTF8(i + 1);
 +
 
 +
  //Win32 user may decide to override locale with LANG variable.
 +
  if Result = '' then
 +
    Result := GetEnvironmentVariableUTF8('LANG');
  
resourcestring
+
   if Result = '' then
   MyCaption = 'Caption';
+
    LazGetLanguageIDs(Result, {%H-}T);
 +
end;
  
function TranslateUnitResourceStrings: boolean;
+
function GetBiDiMode: TBiDiMode;
var
 
  r: TLResource;
 
  POFile: TPOFile;
 
 
begin
 
begin
   r:=LazarusResources.Find('unit1.de','PO');
+
   case GetLang of
  POFile:=TPOFile.Create;
+
    // Arabic
  try
+
    'ar': Result := bdRightToLeft;
     POFile.ReadPOText(r.Value);
+
     else
    Result:=Translations.TranslateUnitResourceStrings('unit1',POFile);
+
      Result := bdLeftToRight;
  finally
 
    POFile.Free;
 
 
   end;
 
   end;
 
end;
 
end;
  
initialization
+
end.
  {$I unit1.lrs}</pascal>
+
</syntaxhighlight>
 +
 
 +
When you create a form do this:
 +
 
 +
<syntaxhighlight lang="pascal">
 +
BiDiMode := GetBiDiMode;
 +
</syntaxhighlight>
 +
 
 +
'''Note:''' You must be sure that you have the proper translations in order to get it working.
  
* Call TranslateUnitResourceStrings at the beginning of the program. You can do that in the initialization section if you like.
+
'''Note 2:''' Maybe this is not neccesary at all since Windows can change the BiDiMode automatically.
  
==Translating the IDE==
+
===Technical Details===
  
===Files===
+
====gettext====
The .po files of the IDE are in the lazarus source directory:
+
 
*lazarus/languages strings for the IDE
+
The main technology involved in the process of translations is [https://www.gnu.org/software/gettext/manual/gettext.html GNU gettext]. FPC comes with the gettext unit.
*lcl/languages/ strings for the LCL
+
 
*ideintf/languages/ strings for the IDE interface
+
<syntaxhighlight lang="pascal">
 +
uses
 +
  gettext;
 +
</syntaxhighlight>
 +
 
 +
====PO====
 +
 
 +
PO – Portable Object. This is the file that you receive back from the translators. It’s a text file that includes the original text and the translations.
 +
 
 +
====MO====
 +
 
 +
MO – Machine Object. The MO file includes the exact same contents as the PO file. The two files differ in their format. While a PO file is a text file and is easy for humans to read, MO files are compiled and are easy for computers to read. The unit gettext implements TMOFile and has several procedures to do the translation from .mo files, if you want to use it.
 +
 
 +
<syntaxhighlight lang="pascal">
 +
unit gettext;
 +
 
 +
...
 +
 
 +
TMOFile = class
 +
 
 +
...
  
===Translators===
+
  procedure GetLanguageIDs(var Lang, FallbackLang: string);
*german translation is maintained by Joerg Braun.
+
  procedure TranslateResourceStrings(AFile: TMOFile);
*finnish translation is maintained by Seppo Suurtarla
+
  procedure TranslateUnitResourceStrings(const AUnitName:string; AFile: TMOFile);
*russian translation is maintained by Maxim Ganetsky
+
  procedure TranslateResourceStrings(const AFilename: String);
 +
  procedure TranslateUnitResourceStrings(const AUnitName:string; const AFilename: String);
 +
</syntaxhighlight>
  
When you want to start a new translation, ask on the mailing if someone is already working on that.
+
==Everything else about translations==
  
Please read carefully: [[Lazarus_Documentation#Translations|Translations]]
+
Here is all the translation material that was here in the past. There are a lot of articles about translations that can cause trouble to novices. To keep it simple this other material has been moved to: [[Everything else about translations]]. Please keep this article as clean as possible.
  
 
==See also==
 
==See also==
  
[[IDE_Development#Translations.2C_i18n.2C_lrt_files.2C_po_files|IDE Development: Translations, i18n, lrt, po files]]
+
* [[IDE_Development#Translations.2C_i18n.2C_lrt_files.2C_po_files|IDE Development: Translations, i18n, lrt, po files]]
 +
* [[Getting_translation_strings_right|Getting translation strings right]]
 +
* [[Lazarus_Documentation#Translating.2FInternationalization.2FLocalization|Translating/Internationalization/Localization]]
 +
* [[Step-by-step_instructions_for_creating_multi-language_applications|Step-by-step instructions for creating multi-language applications]]
 +
* [[Everything_else_about_translations#Compiling_po_files_into_the_executable_and_change_language_while_running|Embedding po files into the executable]]
  
 
[[Category:Tutorials]]
 
[[Category:Tutorials]]
 
[[Category:Localization]]
 
[[Category:Localization]]

Latest revision as of 22:50, 24 January 2021

Deutsch (de) English (en) español (es) français (fr) 日本語 (ja) 한국어 (ko) polski (pl) português (pt) русский (ru) 中文(中国大陆)‎ (zh_CN)

This is about how a program can use different strings for various languages like English, Chinese, German, Finnish, Italian and any other language.

  • i18n is short for internationalization (18 being the number of characters between i and n of the word internationalization)
  • l10n is short for localization (10 being the number of characters between l and n of the word localization)


Quick i18n

This is intended as be a quick guide to introduce yourself in the world of translations and get things done quickly. Check also Language Codes and BidiMode.

For your information the most used languages in the world (source) are:

  • 1 - Chinese: With more than 1.2 billion native speakers in the world
  • 2 - Spanish: Spanish occupies the No. 2 spot and is spoken in approximately 30 countries.
  • 3 - English: 335 million worldwide—about 5% of the world’s population. (This does not takes into account second language spoken).
  • 4 - Hindi: Spoken by over 260 million people.
  • 5 - Arabic: Spoken in almost 60 countries around the world.
  • 6 - Portuguese: Population of Brazil is over 200 million. The population of Portugal is just over 10 million.
  • 7 - Bengali: The main language of Bangladesh (population, 155 million) and one of India’s many official languages.
  • 8 - Russian and Japanese.

poedit

The best known tool is a program called poedit. poedit is a tool for translators. It produces both PO and MO as output.

Translating Forms

When you save a form with the i18n options enabled, it generates a file .lrj, that file is used to create the final .po file. So is very important that you include that file with your source code in the version system you're using, don't add that file to ignored (say .gitignore), else your translations will be broken.

Translating Resourcestrings

This is the way to store a resourcestring in a unit:

resourcestring
  Caption1 = 'Some text';
  HelloWorld1 = 'Hello World';

Resourcestrings are like normal string constants, that means you can assign them to any string:

Label1.Caption := HelloWorld1;

Compiling into .po files

Resourcestrings are compiled into .po files if you enable i18n in the Lazarus IDE. Go to Project > Project Options > i18n > Enable i18n. When you recompile your application the .po files will be updated. You may also select a directory where .po files will be stored, recommended po_files.

The default translation is recommended to be in English or the default language of your application, since it will be loaded if no other translation file is found.

When you have your project1.po copy and paste it and rename it to project1.es.po or one of the Language Codes of your choice. Then you will have 2 languages: English and Spanish. Then you must send to the translator the files for translation.

Your folder structure will look something like this:

project1\po_files\
project1\po_files\project1.po
project1\po_files\project1.es.po

Converting .po files to .mo files

When you have the translation finished in the .po file, you want to compile it to .mo to load it faster since is a binary format. To convert to .mo you can use poedit and go to File > Compile as .mo.

Note that Everything else about translations has a section about where a Lazarus app looks for its language files.

Automatic translation

When you have the .mo files ready, put them in the locale or languages folder right to your application executable, then include the unit DefaultTranslator and that's all. The translation will be done automatically.

uses
  DefaultTranslator;

You want to distribute only the .mo files in the locale or languages directory, since .po files are usefull only for making the translation and compiling them into a .mo file.

Your folder structure will look something like this:

project1\project1.exe
project1\locale\
project1\locale\project1.mo
project1\locale\project1.es.mo

Testing translations

When you have everything ready. you want to test if the translations looks fine in your application for each language you have. Automatic translation has a feature that you can use in order to test each language quickly.

You must run your executable with the command line parameter --lang followed by the language code of your choice.

You will run your executable like this in order to test Spanish translation:

project1.exe --lang es

And you will see the translated application.

You can do this with the IDE. Go to Run > Run Parameters .... In that window in the input Command line parameters (without application name) write this:

--lang it

Then Run (F9) and you will see the translated application.

Final steps

These steps are to get a better result for your entire translation.

Translate LCL

To get everything translated you must include the LCL translations into your application locale folder.

Copy everything inside the folder C:\lazarus\lcl\languages to your locale folder. Then you will have the LCL translated for your application.

Format Settings

For Windows you must read Step-by-step instructions for creating multi-language applications#Format settings to get format settings in the right place.

Under Linux, BSD and macOS there are several locales defining things like time and date format or the thousands separator. In order to initialize the RTL you need to include the clocale unit in the uses section of your program (.lpr file).

BiDiMode

BidiMode is for languages like Arabic that read and write right to left. See also Script direction and languages for a list of LTR (Left To Right) and RTL (Right To Left) languages and most used languages in general.

With this unit you can determine what BiDiMode is right for you. This code is tested in Lazarus Trunk and may or not work in current release (see the changes on this page to get the old source).

First save this unit as ubidimodetools.pas:

unit ubidimodetools;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils;

function GetLang: string;
function GetBiDiMode: TBiDiMode;

implementation

uses
  FileUtil, LCLProc, LazUTF8;

function GetLang: string;
var
  T: string; // unused FallBackLang
  i: integer;
begin
  Result := '';
  { We use the same method that is used in LCLTranslator unit }

  for i := 1 to Paramcount - 1 do
    if (ParamStrUTF8(i) = '--LANG') or (ParamStrUTF8(i) = '-l') or
      (ParamStrUTF8(i) = '--lang') then
      Result := ParamStrUTF8(i + 1);

  //Win32 user may decide to override locale with LANG variable.
  if Result = '' then
    Result := GetEnvironmentVariableUTF8('LANG');

  if Result = '' then
    LazGetLanguageIDs(Result, {%H-}T);
end;

function GetBiDiMode: TBiDiMode;
begin
  case GetLang of
    // Arabic
    'ar': Result := bdRightToLeft;
    else
      Result := bdLeftToRight;
  end;
end;

end.

When you create a form do this:

BiDiMode := GetBiDiMode;

Note: You must be sure that you have the proper translations in order to get it working.

Note 2: Maybe this is not neccesary at all since Windows can change the BiDiMode automatically.

Technical Details

gettext

The main technology involved in the process of translations is GNU gettext. FPC comes with the gettext unit.

uses
  gettext;

PO

PO – Portable Object. This is the file that you receive back from the translators. It’s a text file that includes the original text and the translations.

MO

MO – Machine Object. The MO file includes the exact same contents as the PO file. The two files differ in their format. While a PO file is a text file and is easy for humans to read, MO files are compiled and are easy for computers to read. The unit gettext implements TMOFile and has several procedures to do the translation from .mo files, if you want to use it.

unit gettext;

...

TMOFile = class

...

  procedure GetLanguageIDs(var Lang, FallbackLang: string);
  procedure TranslateResourceStrings(AFile: TMOFile);
  procedure TranslateUnitResourceStrings(const AUnitName:string; AFile: TMOFile);
  procedure TranslateResourceStrings(const AFilename: String);
  procedure TranslateUnitResourceStrings(const AUnitName:string; const AFilename: String);

Everything else about translations

Here is all the translation material that was here in the past. There are a lot of articles about translations that can cause trouble to novices. To keep it simple this other material has been moved to: Everything else about translations. Please keep this article as clean as possible.

See also