]> git.lyx.org Git - lyx.git/blob - src/Language.cpp
"AsBabelOptions" no longer required. Part2.
[lyx.git] / src / Language.cpp
1 /**
2  * \file Language.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Jean-Marc Lasgouttes
8  * \author Jürgen Spitzmüller
9  * \author Dekel Tsur
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "Language.h"
17
18 #include "Encoding.h"
19 #include "LaTeXFonts.h"
20 #include "Lexer.h"
21 #include "LyXRC.h"
22
23 #include "support/debug.h"
24 #include "support/FileName.h"
25 #include "support/filetools.h"
26 #include "support/lassert.h"
27 #include "support/lstrings.h"
28 #include "support/Messages.h"
29
30 using namespace std;
31 using namespace lyx::support;
32
33 namespace lyx {
34
35 Languages languages;
36 Language const * ignore_language = 0;
37 Language const * default_language = 0;
38 Language const * latex_language = 0;
39 Language const * reset_language = 0;
40
41
42 bool Language::isPolyglossiaExclusive() const
43 {
44         return babel().empty() && !polyglossia().empty() && requires().empty();
45 }
46
47
48 bool Language::isBabelExclusive() const
49 {
50         return !babel().empty() && polyglossia().empty() && requires().empty();
51 }
52
53
54 docstring const Language::translateLayout(string const & m) const
55 {
56         if (m.empty())
57                 return docstring();
58
59         if (!isAscii(m)) {
60                 lyxerr << "Warning: not translating `" << m
61                        << "' because it is not pure ASCII.\n";
62                 return from_utf8(m);
63         }
64
65         TranslationMap::const_iterator it = layoutTranslations_.find(m);
66         if (it != layoutTranslations_.end())
67                 return it->second;
68
69         docstring t = from_ascii(m);
70         cleanTranslation(t);
71         return t;
72 }
73
74
75 string Language::fontenc(BufferParams const & params) const
76 {
77         // Don't use LaTeX fonts, so just return the language's preferred
78         // (although this is not used with nonTeXFonts anyway).
79         if (params.useNonTeXFonts)
80                 return fontenc_.front() == "ASCII" ? "T1" : fontenc_.front();
81
82         // Determine optimal font encoding
83         // We check whether the used rm font supports an encoding our language supports
84         LaTeXFont const & lf =
85                 theLaTeXFonts().getLaTeXFont(from_ascii(params.fontsRoman()));
86         vector<string> const lfe = lf.fontencs();
87         for (auto & fe : fontenc_) {
88                 // ASCII means: support all T* encodings plus OT1
89                 if (fe == "ASCII") {
90                         for (auto & afe : lfe) {
91                                 if (afe == "OT1" || prefixIs(afe, "T"))
92                                         // we found a suitable one; return that.
93                                         return afe;
94                         }
95                 }
96                 // For other encodings, just check whether the font supports it
97                 if (lf.hasFontenc(fe))
98                         return fe;
99         }
100         // We did not find a suitable one; just take the first in the list,
101         // the priorized one (which is "T1" for ASCII).
102         return fontenc_.front() == "ASCII" ? "T1" : fontenc_.front();
103 }
104
105
106 string Language::dateFormat(size_t i) const
107 {
108         if (i > dateformats_.size())
109                 return string();
110         return dateformats_.at(i);
111 }
112
113
114 bool Language::readLanguage(Lexer & lex)
115 {
116         enum LanguageTags {
117                 LA_BABELNAME = 1,
118                 LA_DATEFORMATS,
119                 LA_ENCODING,
120                 LA_END,
121                 LA_FONTENC,
122                 LA_GUINAME,
123                 LA_HAS_GUI_SUPPORT,
124                 LA_INTERNAL_ENC,
125                 LA_LANG_CODE,
126                 LA_LANG_VARIETY,
127                 LA_POLYGLOSSIANAME,
128                 LA_POLYGLOSSIAOPTS,
129                 LA_POSTBABELPREAMBLE,
130                 LA_PREBABELPREAMBLE,
131                 LA_PROVIDES,
132                 LA_REQUIRES,
133                 LA_QUOTESTYLE,
134                 LA_RTL
135         };
136
137         // Keep these sorted alphabetically!
138         LexerKeyword languageTags[] = {
139                 { "babelname",            LA_BABELNAME },
140                 { "dateformats",          LA_DATEFORMATS },
141                 { "encoding",             LA_ENCODING },
142                 { "end",                  LA_END },
143                 { "fontencoding",         LA_FONTENC },
144                 { "guiname",              LA_GUINAME },
145                 { "hasguisupport",        LA_HAS_GUI_SUPPORT },
146                 { "internalencoding",     LA_INTERNAL_ENC },
147                 { "langcode",             LA_LANG_CODE },
148                 { "langvariety",          LA_LANG_VARIETY },
149                 { "polyglossianame",      LA_POLYGLOSSIANAME },
150                 { "polyglossiaopts",      LA_POLYGLOSSIAOPTS },
151                 { "postbabelpreamble",    LA_POSTBABELPREAMBLE },
152                 { "prebabelpreamble",     LA_PREBABELPREAMBLE },
153                 { "provides",             LA_PROVIDES },
154                 { "quotestyle",           LA_QUOTESTYLE },
155                 { "requires",             LA_REQUIRES },
156                 { "rtl",                  LA_RTL }
157         };
158
159         bool error = false;
160         bool finished = false;
161         lex.pushTable(languageTags);
162         // parse style section
163         while (!finished && lex.isOK() && !error) {
164                 int le = lex.lex();
165                 // See comment in LyXRC.cpp.
166                 switch (le) {
167                 case Lexer::LEX_FEOF:
168                         continue;
169
170                 case Lexer::LEX_UNDEF: // parse error
171                         lex.printError("Unknown language tag `$$Token'");
172                         error = true;
173                         continue;
174
175                 default:
176                         break;
177                 }
178                 switch (static_cast<LanguageTags>(le)) {
179                 case LA_END: // end of structure
180                         finished = true;
181                         break;
182                 case LA_BABELNAME:
183                         lex >> babel_;
184                         break;
185                 case LA_POLYGLOSSIANAME:
186                         lex >> polyglossia_name_;
187                         break;
188                 case LA_POLYGLOSSIAOPTS:
189                         lex >> polyglossia_opts_;
190                         break;
191                 case LA_QUOTESTYLE:
192                         lex >> quote_style_;
193                         break;
194                 case LA_ENCODING:
195                         lex >> encodingStr_;
196                         break;
197                 case LA_FONTENC: {
198                         lex.eatLine();
199                         vector<string> const fe =
200                                 getVectorFromString(lex.getString(true), "|");
201                         fontenc_.insert(fontenc_.end(), fe.begin(), fe.end());
202                         break;
203                 }
204                 case LA_DATEFORMATS: {
205                         lex.eatLine();
206                         vector<string> const df =
207                                 getVectorFromString(trim(lex.getString(true), "\""), "|");
208                         dateformats_.insert(dateformats_.end(), df.begin(), df.end());
209                         break;
210                 }
211                 case LA_GUINAME:
212                         lex >> display_;
213                         break;
214                 case LA_HAS_GUI_SUPPORT:
215                         lex >> has_gui_support_;
216                         break;
217                 case LA_INTERNAL_ENC:
218                         lex >> internal_enc_;
219                         break;
220                 case LA_LANG_CODE:
221                         lex >> code_;
222                         break;
223                 case LA_LANG_VARIETY:
224                         lex >> variety_;
225                         break;
226                 case LA_POSTBABELPREAMBLE:
227                         babel_postsettings_ =
228                                 lex.getLongString(from_ascii("EndPostBabelPreamble"));
229                         break;
230                 case LA_PREBABELPREAMBLE:
231                         babel_presettings_ =
232                                 lex.getLongString(from_ascii("EndPreBabelPreamble"));
233                         break;
234                 case LA_REQUIRES:
235                         lex >> requires_;
236                         break;
237                 case LA_PROVIDES:
238                         lex >> provides_;
239                         break;
240                 case LA_RTL:
241                         lex >> rightToLeft_;
242                         break;
243                 }
244         }
245         lex.popTable();
246         return finished && !error;
247 }
248
249
250 bool Language::read(Lexer & lex)
251 {
252         encoding_ = 0;
253         internal_enc_ = 0;
254         rightToLeft_ = 0;
255
256         if (!lex.next()) {
257                 lex.printError("No name given for language: `$$Token'.");
258                 return false;
259         }
260
261         lang_ = lex.getString();
262         LYXERR(Debug::INFO, "Reading language " << lang_);
263         if (!readLanguage(lex)) {
264                 LYXERR0("Error parsing language `" << lang_ << '\'');
265                 return false;
266         }
267
268         encoding_ = encodings.fromLyXName(encodingStr_);
269         if (!encoding_ && !encodingStr_.empty()) {
270                 encoding_ = encodings.fromLyXName("iso8859-1");
271                 LYXERR0("Unknown encoding " << encodingStr_);
272         }
273         if (fontenc_.empty())
274                 fontenc_.push_back("ASCII");
275         if (dateformats_.empty()) {
276                 dateformats_.push_back("MMMM dd, yyyy");
277                 dateformats_.push_back("MMM dd, yyyy");
278                 dateformats_.push_back("M/d/yyyy");
279         }
280         return true;
281 }
282
283
284 void Language::readLayoutTranslations(Language::TranslationMap const & trans, bool replace)
285 {
286         TranslationMap::const_iterator const end = trans.end();
287         for (TranslationMap::const_iterator it = trans.begin(); it != end; ++it) {
288                 if (replace
289                         || layoutTranslations_.find(it->first) == layoutTranslations_.end())
290                         layoutTranslations_[it->first] = it->second;
291         }
292 }
293
294
295 void Languages::read(FileName const & filename)
296 {
297         Lexer lex;
298         lex.setFile(filename);
299         lex.setContext("Languages::read");
300         while (lex.isOK()) {
301                 int le = lex.lex();
302                 switch (le) {
303                 case Lexer::LEX_FEOF:
304                         continue;
305
306                 default:
307                         break;
308                 }
309                 if (lex.getString() != "Language") {
310                         lex.printError("Unknown Language tag `$$Token'");
311                         continue;
312                 }
313                 Language l;
314                 l.read(lex);
315                 if (!lex)
316                         break;
317                 if (l.lang() == "latex") {
318                         // Check if latex language was not already defined.
319                         LASSERT(latex_language == 0, continue);
320                         static const Language latex_lang = l;
321                         latex_language = &latex_lang;
322                 } else if (l.lang() == "ignore") {
323                         // Check if ignore language was not already defined.
324                         LASSERT(ignore_language == 0, continue);
325                         static const Language ignore_lang = l;
326                         ignore_language = &ignore_lang;
327                 } else
328                         languagelist[l.lang()] = l;
329         }
330
331         default_language = getLanguage("english");
332         if (!default_language) {
333                 LYXERR0("Default language \"english\" not found!");
334                 default_language = &(*languagelist.begin()).second;
335                 LYXERR0("Using \"" << default_language->lang() << "\" instead!");
336         }
337
338         // Read layout translations
339         FileName const path = libFileSearch(string(), "layouttranslations");
340         readLayoutTranslations(path);
341 }
342
343
344 namespace {
345
346 bool readTranslations(Lexer & lex, Language::TranslationMap & trans)
347 {
348         while (lex.isOK()) {
349                 if (lex.checkFor("End"))
350                         break;
351                 if (!lex.next(true))
352                         return false;
353                 string const key = lex.getString();
354                 if (!lex.next(true))
355                         return false;
356                 docstring const val = lex.getDocString();
357                 trans[key] = val;
358         }
359         return true;
360 }
361
362
363 enum Match {
364         NoMatch,
365         ApproximateMatch,
366         ExactMatch
367 };
368
369
370 Match match(string const & code, Language const & lang)
371 {
372         // we need to mimic gettext: code can be a two-letter code, which
373         // should match all variants, e.g. "de" should match "de_DE",
374         // "de_AT" etc.
375         // special case for chinese:
376         // simplified  => code == "zh_CN", langcode == "zh_CN"
377         // traditional => code == "zh_TW", langcode == "zh_CN"
378         string const variety = lang.variety();
379         string const langcode = variety.empty() ?
380                                 lang.code() : lang.code() + '_' + variety;
381         string const name = lang.lang();
382         if ((code == langcode && name != "chinese-traditional")
383                 || (code == "zh_TW"  && name == "chinese-traditional"))
384                 return ExactMatch;
385         if ((code.size() == 2) && (langcode.size() > 2)
386                 && (code + '_' == langcode.substr(0, 3)))
387                 return ApproximateMatch;
388         return NoMatch;
389 }
390
391 } // namespace
392
393
394
395 Language const * Languages::getFromCode(string const & code) const
396 {
397         LanguageList::const_iterator const lbeg = languagelist.begin();
398         LanguageList::const_iterator const lend = languagelist.end();
399         // Try for exact match first
400         for (LanguageList::const_iterator lit = lbeg; lit != lend; ++lit) {
401                 if (match(code, lit->second) == ExactMatch)
402                         return &lit->second;
403         }
404         // If not found, look for lang prefix (without country) instead
405         for (LanguageList::const_iterator lit = lbeg; lit != lend; ++lit) {
406                 if (match(code, lit->second) == ApproximateMatch)
407                         return &lit->second;
408         }
409         LYXERR0("Unknown language `" + code + "'");
410         return 0;
411 }
412
413
414 void Languages::readLayoutTranslations(support::FileName const & filename)
415 {
416         Lexer lex;
417         lex.setFile(filename);
418         lex.setContext("Languages::read");
419
420         // 1) read all translations (exact and approximate matches) into trans
421         typedef std::map<string, Language::TranslationMap> TransMap;
422         TransMap trans;
423         LanguageList::iterator const lbeg = languagelist.begin();
424         LanguageList::iterator const lend = languagelist.end();
425         while (lex.isOK()) {
426                 if (!lex.checkFor("Translation")) {
427                         if (lex.isOK())
428                                 lex.printError("Unknown layout translation tag `$$Token'");
429                         break;
430                 }
431                 if (!lex.next(true))
432                         break;
433                 string const code = lex.getString();
434                 bool found = getFromCode(code);
435                 if (!found) {
436                         lex.printError("Unknown language `" + code + "'");
437                         break;
438                 }
439                 if (!readTranslations(lex, trans[code])) {
440                         lex.printError("Could not read layout translations for language `"
441                                 + code + "'");
442                         break;
443                 }
444         }
445
446         // 2) merge all translations into the languages
447         // exact translations overwrite approximate ones
448         TransMap::const_iterator const tbeg = trans.begin();
449         TransMap::const_iterator const tend = trans.end();
450         for (TransMap::const_iterator tit = tbeg; tit != tend; ++tit) {
451                 for (LanguageList::iterator lit = lbeg; lit != lend; ++lit) {
452                         Match const m = match(tit->first, lit->second);
453                         if (m == NoMatch)
454                                 continue;
455                         lit->second.readLayoutTranslations(tit->second,
456                                                            m == ExactMatch);
457                 }
458         }
459
460 }
461
462
463 Language const * Languages::getLanguage(string const & language) const
464 {
465         if (language == "reset")
466                 return reset_language;
467         if (language == "ignore")
468                 return ignore_language;
469         const_iterator it = languagelist.find(language);
470         return it == languagelist.end() ? reset_language : &it->second;
471 }
472
473
474 } // namespace lyx