]> git.lyx.org Git - lyx.git/blob - src/Encoding.cpp
Tracking correctly available translations (take 2)
[lyx.git] / src / Encoding.cpp
1 /**
2  * \file Encoding.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 Dekel Tsur
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "Encoding.h"
16
17 #include "Buffer.h"
18 #include "BufferList.h"
19 #include "InsetIterator.h"
20 #include "LaTeXFeatures.h"
21 #include "Lexer.h"
22 #include "LyXRC.h"
23
24 #include "support/debug.h"
25 #include "support/gettext.h"
26 #include "support/FileName.h"
27 #include "support/lstrings.h"
28 #include "support/textutils.h"
29 #include "support/unicode.h"
30
31 #include <boost/cstdint.hpp>
32
33 #include <sstream>
34
35 using namespace std;
36 using namespace lyx::support;
37
38 namespace lyx {
39
40 Encodings encodings;
41
42 Encodings::MathCommandSet Encodings::mathcmd;
43 Encodings::TextCommandSet Encodings::textcmd;
44 Encodings::MathSymbolSet  Encodings::mathsym;
45
46 namespace {
47
48 char_type arabic_table[172][4] = {
49         {0xfe80, 0xfe80, 0xfe80, 0xfe80}, // 0x0621 = hamza
50         {0xfe81, 0xfe82, 0xfe81, 0xfe82}, // 0x0622 = ligature madda on alef
51         {0xfe83, 0xfe84, 0xfe83, 0xfe84}, // 0x0623 = ligature hamza on alef
52         {0xfe85, 0xfe86, 0xfe85, 0xfe86}, // 0x0624 = ligature hamza on waw
53         {0xfe87, 0xfe88, 0xfe87, 0xfe88}, // 0x0625 = ligature hamza under alef
54         {0xfe89, 0xfe8a, 0xfe8b, 0xfe8c}, // 0x0626 = ligature hamza on ya
55         {0xfe8d, 0xfe8e, 0xfe8d, 0xfe8e}, // 0x0627 = alef
56         {0xfe8f, 0xfe90, 0xfe91, 0xfe92}, // 0x0628 = baa
57         {0xfe93, 0xfe94, 0xfe93, 0xfe94}, // 0x0629 = taa marbuta
58         {0xfe95, 0xfe96, 0xfe97, 0xfe98}, // 0x062a = taa
59         {0xfe99, 0xfe9a, 0xfe9b, 0xfe9c}, // 0x062b = thaa
60         {0xfe9d, 0xfe9e, 0xfe9f, 0xfea0}, // 0x062c = jeem
61         {0xfea1, 0xfea2, 0xfea3, 0xfea4}, // 0x062d = haa
62         {0xfea5, 0xfea6, 0xfea7, 0xfea8}, // 0x062e = khaa
63         {0xfea9, 0xfeaa, 0xfea9, 0xfeaa}, // 0x062f = dal
64
65         {0xfeab, 0xfeac, 0xfeab, 0xfeac}, // 0x0630 = thal
66         {0xfead, 0xfeae, 0xfead, 0xfeae}, // 0x0631 = ra
67         {0xfeaf, 0xfeb0, 0xfeaf, 0xfeb0}, // 0x0632 = zain
68         {0xfeb1, 0xfeb2, 0xfeb3, 0xfeb4}, // 0x0633 = seen
69         {0xfeb5, 0xfeb6, 0xfeb7, 0xfeb8}, // 0x0634 = sheen
70         {0xfeb9, 0xfeba, 0xfebb, 0xfebc}, // 0x0635 = sad
71         {0xfebd, 0xfebe, 0xfebf, 0xfec0}, // 0x0636 = dad
72         {0xfec1, 0xfec2, 0xfec3, 0xfec4}, // 0x0637 = tah
73         {0xfec5, 0xfec6, 0xfec7, 0xfec8}, // 0x0638 = zah
74         {0xfec9, 0xfeca, 0xfecb, 0xfecc}, // 0x0639 = ain
75         {0xfecd, 0xfece, 0xfecf, 0xfed0}, // 0x063a = ghain
76         {0, 0, 0, 0}, // 0x063b
77         {0, 0, 0, 0}, // 0x063c
78         {0, 0, 0, 0}, // 0x063d
79         {0, 0, 0, 0}, // 0x063e
80         {0, 0, 0, 0}, // 0x063f
81
82         {0, 0, 0, 0}, // 0x0640
83         {0xfed1, 0xfed2, 0xfed3, 0xfed4}, // 0x0641 = fa
84         {0xfed5, 0xfed6, 0xfed7, 0xfed8}, // 0x0642 = qaf
85         {0xfed9, 0xfeda, 0xfedb, 0xfedc}, // 0x0643 = kaf
86         {0xfedd, 0xfede, 0xfedf, 0xfee0}, // 0x0644 = lam
87         {0xfee1, 0xfee2, 0xfee3, 0xfee4}, // 0x0645 = meem
88         {0xfee5, 0xfee6, 0xfee7, 0xfee8}, // 0x0646 = noon
89         {0xfee9, 0xfeea, 0xfeeb, 0xfeec}, // 0x0647 = ha
90         {0xfeed, 0xfeee, 0xfeed, 0xfeee}, // 0x0648 = waw
91         {0xfeef, 0xfef0, 0xfeef, 0xfef0}, // 0x0649 = alef maksura
92         {0xfef1, 0xfef2, 0xfef3, 0xfef4}, // 0x064a = ya
93         {0x065b, 0x065b, 0x065b, 0x065b}, // 0x064b = fathatan
94         {0x065c, 0x065c, 0x065c, 0x065c}, // 0x064c = dammatan
95         {0x064d, 0x064d, 0x064d, 0x064d}, // 0x064d = kasratan
96         {0x064e, 0x064e, 0x064e, 0x064e}, // 0x064e = fatha
97         {0x064f, 0x064f, 0x064f, 0x064f}, // 0x064f = damma
98
99         {0x0650, 0x0650, 0x0650, 0x0650}, // 0x0650 = kasra
100         {0x0651, 0x0651, 0x0651, 0x0651}, // 0x0651 = shadda
101         {0x0652, 0x0652, 0x0652, 0x0652}, // 0x0652 = sukun
102
103         {0, 0, 0, 0}, // 0x0653
104         {0, 0, 0, 0}, // 0x0654
105         {0, 0, 0, 0}, // 0x0655
106         {0, 0, 0, 0}, // 0x0656
107         {0, 0, 0, 0}, // 0x0657
108         {0, 0, 0, 0}, // 0x0658
109         {0, 0, 0, 0}, // 0x0659
110         {0, 0, 0, 0}, // 0x065a
111         {0, 0, 0, 0}, // 0x065b
112         {0, 0, 0, 0}, // 0x065c
113         {0, 0, 0, 0}, // 0x065d
114         {0, 0, 0, 0}, // 0x065e
115         {0, 0, 0, 0}, // 0x065f
116         {0, 0, 0, 0}, // 0x0660
117         {0, 0, 0, 0}, // 0x0661
118         {0, 0, 0, 0}, // 0x0662
119         {0, 0, 0, 0}, // 0x0663
120         {0, 0, 0, 0}, // 0x0664
121         {0, 0, 0, 0}, // 0x0665
122         {0, 0, 0, 0}, // 0x0666
123         {0, 0, 0, 0}, // 0x0667
124         {0, 0, 0, 0}, // 0x0668
125         {0, 0, 0, 0}, // 0x0669
126         {0, 0, 0, 0}, // 0x066a
127         {0, 0, 0, 0}, // 0x066b
128         {0, 0, 0, 0}, // 0x066c
129         {0, 0, 0, 0}, // 0x066d
130         {0, 0, 0, 0}, // 0x066e
131         {0, 0, 0, 0}, // 0x066f
132         {0, 0, 0, 0}, // 0x0670
133         {0, 0, 0, 0}, // 0x0671
134         {0, 0, 0, 0}, // 0x0672
135         {0, 0, 0, 0}, // 0x0673
136         {0, 0, 0, 0}, // 0x0674
137         {0, 0, 0, 0}, // 0x0675
138         {0, 0, 0, 0}, // 0x0676
139         {0, 0, 0, 0}, // 0x0677
140         {0, 0, 0, 0}, // 0x0678
141         {0, 0, 0, 0}, // 0x0679
142         {0, 0, 0, 0}, // 0x067a
143         {0, 0, 0, 0}, // 0x067b
144         {0, 0, 0, 0}, // 0x067c
145         {0, 0, 0, 0}, // 0x067d
146         {0xfb56, 0xfb57, 0xfb58, 0xfb59}, // 0x067e = peh 
147         {0, 0, 0, 0}, // 0x067f
148         {0, 0, 0, 0}, // 0x0680
149         {0, 0, 0, 0}, // 0x0681
150         {0, 0, 0, 0}, // 0x0682
151         {0, 0, 0, 0}, // 0x0683
152         {0, 0, 0, 0}, // 0x0684
153         {0, 0, 0, 0}, // 0x0685
154         {0xfb7a, 0xfb7b, 0xfb7c, 0xfb7d}, // 0x0686 = tcheh 
155         {0, 0, 0, 0}, // 0x0687
156         {0, 0, 0, 0}, // 0x0688
157         {0, 0, 0, 0}, // 0x0689
158         {0, 0, 0, 0}, // 0x068a
159         {0, 0, 0, 0}, // 0x068b
160         {0, 0, 0, 0}, // 0x068c
161         {0, 0, 0, 0}, // 0x068d
162         {0, 0, 0, 0}, // 0x068e
163         {0, 0, 0, 0}, // 0x068f
164         {0, 0, 0, 0}, // 0x0690
165         {0, 0, 0, 0}, // 0x0691
166         {0, 0, 0, 0}, // 0x0692
167         {0, 0, 0, 0}, // 0x0693
168         {0, 0, 0, 0}, // 0x0694
169         {0, 0, 0, 0}, // 0x0695
170         {0, 0, 0, 0}, // 0x0696
171         {0, 0, 0, 0}, // 0x0697
172         {0xfb8a, 0xfb8b, 0xfb8a, 0xfb8b}, // 0x0698 = jeh
173         {0, 0, 0, 0}, // 0x0699
174         {0, 0, 0, 0}, // 0x069a
175         {0, 0, 0, 0}, // 0x069b
176         {0, 0, 0, 0}, // 0x069c
177         {0, 0, 0, 0}, // 0x069d
178         {0, 0, 0, 0}, // 0x069e
179         {0, 0, 0, 0}, // 0x069f
180         {0, 0, 0, 0}, // 0x06a0
181         {0, 0, 0, 0}, // 0x06a1
182         {0, 0, 0, 0}, // 0x06a2
183         {0, 0, 0, 0}, // 0x06a3
184         {0, 0, 0, 0}, // 0x06a4
185         {0, 0, 0, 0}, // 0x06a5
186         {0, 0, 0, 0}, // 0x06a6
187         {0, 0, 0, 0}, // 0x06a7
188         {0, 0, 0, 0}, // 0x06a8
189         {0xfb8e, 0xfb8f, 0xfb90, 0xfb91}, // 0x06a9 = farsi kaf 
190         {0, 0, 0, 0}, // 0x06aa
191         {0, 0, 0, 0}, // 0x06ab
192         {0, 0, 0, 0}, // 0x06ac
193         {0, 0, 0, 0}, // 0x06ad
194         {0, 0, 0, 0}, // 0x06ae
195         {0xfb92, 0xfb93, 0xfb94, 0xfb95}, // 0x06af = gaf 
196         {0, 0, 0, 0}, // 0x06b0
197         {0, 0, 0, 0}, // 0x06b1
198         {0, 0, 0, 0}, // 0x06b2
199         {0, 0, 0, 0}, // 0x06b3
200         {0, 0, 0, 0}, // 0x06b4
201         {0, 0, 0, 0}, // 0x06b5
202         {0, 0, 0, 0}, // 0x06b6
203         {0, 0, 0, 0}, // 0x06b7
204         {0, 0, 0, 0}, // 0x06b8
205         {0, 0, 0, 0}, // 0x06b9
206         {0, 0, 0, 0}, // 0x06ba
207         {0, 0, 0, 0}, // 0x06bb
208         {0, 0, 0, 0}, // 0x06bc
209         {0, 0, 0, 0}, // 0x06bd
210         {0, 0, 0, 0}, // 0x06be
211         {0, 0, 0, 0}, // 0x06bf
212         {0, 0, 0, 0}, // 0x06c0
213         {0, 0, 0, 0}, // 0x06c1
214         {0, 0, 0, 0}, // 0x06c2
215         {0, 0, 0, 0}, // 0x06c3
216         {0, 0, 0, 0}, // 0x06c4
217         {0, 0, 0, 0}, // 0x06c5
218         {0, 0, 0, 0}, // 0x06c6
219         {0, 0, 0, 0}, // 0x06c7
220         {0, 0, 0, 0}, // 0x06c8
221         {0, 0, 0, 0}, // 0x06c9
222         {0, 0, 0, 0}, // 0x06ca
223         {0, 0, 0, 0}, // 0x06cb
224         {0xfbfc, 0xfbfd, 0xfbfe, 0xfbff} // 0x06cc = farsi yeh  
225 };
226
227
228 char_type const arabic_start = 0x0621;
229 char_type const arabic_end = 0x06cc;
230
231
232 enum CharInfoFlags {
233         ///
234         CharInfoCombining = 1,
235         ///
236         CharInfoTextFeature = 2,
237         ///
238         CharInfoMathFeature = 4,
239         ///
240         CharInfoForce = 8,
241         ///
242         CharInfoTextNoTermination = 16,
243         ///
244         CharInfoMathNoTermination = 32,
245 };
246
247 /// Information about a single UCS4 character
248 struct CharInfo {
249         /// LaTeX command (text mode) for this character
250         docstring textcommand;
251         /// LaTeX command (math mode) for this character
252         docstring mathcommand;
253         /// Needed LaTeX preamble (or feature) for text mode
254         string textpreamble;
255         /// Needed LaTeX preamble (or feature) for math mode
256         string mathpreamble;
257         /// Is this a combining character?
258         bool combining() const { return flags & CharInfoCombining ? true : false; }
259         /// Is \c textpreamble a feature known by LaTeXFeatures, or a raw LaTeX
260         /// command?
261         bool textfeature() const { return flags & CharInfoTextFeature ? true : false; }
262         /// Is \c mathpreamble a feature known by LaTeXFeatures, or a raw LaTeX
263         /// command?
264         bool mathfeature() const { return flags & CharInfoMathFeature ? true : false; }
265         /// Always force the LaTeX command, even if the encoding contains
266         /// this character?
267         bool force() const { return flags & CharInfoForce ? true : false; }
268         /// TIPA shortcut
269         string tipashortcut;
270         /// \c textcommand needs no termination (such as {} or space).
271         bool textnotermination() const { return flags & CharInfoTextNoTermination ? true : false; }
272         /// \c mathcommand needs no termination (such as {} or space).
273         bool mathnotermination() const { return flags & CharInfoMathNoTermination ? true : false; }
274         ///
275         unsigned int flags;
276 };
277
278
279 typedef map<char_type, CharInfo> CharInfoMap;
280 CharInfoMap unicodesymbols;
281
282 typedef std::set<char_type> CharSet;
283 CharSet forced;
284
285 typedef std::set<char_type> MathAlphaSet;
286 MathAlphaSet mathalpha;
287
288
289 /// The highest code point in UCS4 encoding (1<<20 + 1<<16)
290 char_type const max_ucs4 = 0x110000;
291
292 } // namespace anon
293
294
295 EncodingException::EncodingException(char_type c)
296         : failed_char(c), par_id(0), pos(0)
297 {
298 }
299
300
301 const char * EncodingException::what() const throw()
302 {
303         return "Could not find LaTeX command for a character";
304 }
305
306
307 Encoding::Encoding(string const & n, string const & l, string const & g,
308                    string const & i, bool f, Encoding::Package p)
309         : name_(n), latexName_(l), guiName_(g), iconvName_(i), fixedwidth_(f), package_(p)
310 {
311         if (n == "ascii") {
312                 // ASCII can encode 128 code points and nothing else
313                 start_encodable_ = 128;
314                 complete_ = true;
315         } else if (i == "UTF-8") {
316                 // UTF8 can encode all UCS4 code points
317                 start_encodable_ = max_ucs4;
318                 complete_ = true;
319         } else {
320                 complete_ = false;
321         }
322 }
323
324
325 void Encoding::init() const
326 {
327         if (complete_)
328                 return;
329
330         start_encodable_ = 0;
331         // temporarily switch off lyxerr, since we will generate iconv errors
332         lyxerr.disable();
333         if (fixedwidth_) {
334                 // We do not need to check all UCS4 code points, it is enough
335                 // if we check all 256 code points of this encoding.
336                 for (unsigned short j = 0; j < 256; ++j) {
337                         char const c = char(j);
338                         vector<char_type> const ucs4 = eightbit_to_ucs4(&c, 1, iconvName_);
339                         if (ucs4.size() != 1)
340                                 continue;
341                         char_type const uc = ucs4[0];
342                         CharInfoMap::const_iterator const it = unicodesymbols.find(uc);
343                         if (it == unicodesymbols.end() || !it->second.force())
344                                 encodable_.insert(uc);
345                 }
346         } else {
347                 // We do not know how many code points this encoding has, and
348                 // they do not have a direct representation as a single byte,
349                 // therefore we need to check all UCS4 code points.
350                 // This is expensive!
351                 for (char_type c = 0; c < max_ucs4; ++c) {
352                         vector<char> const eightbit = ucs4_to_eightbit(&c, 1, iconvName_);
353                         if (!eightbit.empty()) {
354                                 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
355                                 if (it == unicodesymbols.end() || !it->second.force())
356                                         encodable_.insert(c);
357                         }
358                 }
359         }
360         lyxerr.enable();
361         CharSet::iterator it = encodable_.find(start_encodable_);
362         while (it != encodable_.end()) {
363                 encodable_.erase(it);
364                 ++start_encodable_;
365                 it = encodable_.find(start_encodable_);
366         }
367         complete_ = true;
368 }
369
370
371 bool Encoding::encodable(char_type c) const
372 {
373         // assure the used encoding is properly initialized
374         init();
375
376         if (iconvName_ == "UTF-8" && package_ == none)
377                 return true;
378         if (c < start_encodable_ && !encodings.isForced(c))
379                 return true;
380         if (encodable_.find(c) != encodable_.end())
381                 return true;
382         return false;
383 }
384
385
386 pair<docstring, bool> Encoding::latexChar(char_type c) const
387 {
388         if (encodable(c))
389                 return make_pair(docstring(1, c), false);
390
391         // c cannot (or should not) be encoded in this encoding
392         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
393         if (it == unicodesymbols.end())
394                 throw EncodingException(c);
395         // at least one of mathcommand and textcommand is nonempty
396         if (it->second.textcommand.empty())
397                 return make_pair(
398                         "\\ensuremath{" + it->second.mathcommand + '}', false);
399         return make_pair(it->second.textcommand, !it->second.textnotermination());
400 }
401
402
403 pair<docstring, docstring> Encoding::latexString(docstring const input, bool dryrun) const
404 {
405         docstring result;
406         docstring uncodable;
407         bool terminate = false;
408         for (size_t n = 0; n < input.size(); ++n) {
409                 try {
410                         char_type const c = input[n];
411                         pair<docstring, bool> latex_char = latexChar(c);
412                         docstring const latex = latex_char.first;
413                         if (terminate && !prefixIs(latex, '\\')
414                             && !prefixIs(latex, '{')
415                             && !prefixIs(latex, '}')) {
416                                         // Prevent eating of a following
417                                         // space or command corruption by
418                                         // following characters
419                                         if (latex == " ")
420                                                 result += "{}";
421                                         else
422                                                 result += " ";
423                                 }
424                         result += latex;
425                         terminate = latex_char.second;
426                 } catch (EncodingException & /* e */) {
427                         LYXERR0("Uncodable character in latexString!");
428                         if (dryrun) {
429                                 result += "<" + _("LyX Warning: ")
430                                            + _("uncodable character") + " '";
431                                 result += docstring(1, input[n]);
432                                 result += "'>";
433                         } else
434                                 uncodable += input[n];
435                 }
436         }
437         return make_pair(result, uncodable);
438 }
439
440
441 vector<char_type> Encoding::symbolsList() const
442 {
443         // assure the used encoding is properly initialized
444         init();
445
446         // first all encodable characters
447         vector<char_type> symbols(encodable_.begin(), encodable_.end());
448         // add those below start_encodable_
449         for (char_type c = 0; c < start_encodable_; ++c)
450                 symbols.push_back(c);
451         // now the ones from the unicodesymbols file
452         CharInfoMap::const_iterator const end = unicodesymbols.end();
453         CharInfoMap::const_iterator it = unicodesymbols.begin();
454         for (; it != end; ++it)
455                 symbols.push_back(it->first);
456         return symbols;
457 }
458
459
460 bool Encodings::latexMathChar(char_type c, bool mathmode,
461                         Encoding const * encoding, docstring & command,
462                         bool & needsTermination)
463 {
464         command = empty_docstring();
465         if (encoding)
466                 if (encoding->encodable(c))
467                         command = docstring(1, c);
468         needsTermination = false;
469
470         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
471         if (it == unicodesymbols.end()) {
472                 if (!encoding || command.empty())
473                         throw EncodingException(c);
474                 if (mathmode)
475                         addMathSym(c);
476                 return false;
477         }
478         // at least one of mathcommand and textcommand is nonempty
479         bool use_math = (mathmode && !it->second.mathcommand.empty()) ||
480                         (!mathmode && it->second.textcommand.empty());
481         if (use_math) {
482                 command = it->second.mathcommand;
483                 needsTermination = !it->second.mathnotermination();
484                 addMathCmd(c);
485         } else {
486                 if (!encoding || command.empty()) {
487                         command = it->second.textcommand;
488                         needsTermination = !it->second.textnotermination();
489                         addTextCmd(c);
490                 }
491                 if (mathmode)
492                         addMathSym(c);
493         }
494         return use_math;
495 }
496
497
498 char_type Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
499                 bool & combining, bool & needsTermination, set<string> * req)
500 {
501         CharInfoMap::const_iterator const end = unicodesymbols.end();
502         CharInfoMap::const_iterator it = unicodesymbols.begin();
503         for (combining = false; it != end; ++it) {
504                 docstring const math = it->second.mathcommand;
505                 docstring const text = it->second.textcommand;
506                 if ((cmdtype & MATH_CMD) && math == cmd) {
507                         combining = it->second.combining();
508                         needsTermination = !it->second.mathnotermination();
509                         if (req && it->second.mathfeature() &&
510                             !it->second.mathpreamble.empty())
511                                 req->insert(it->second.mathpreamble);
512                         return it->first;
513                 }
514                 if ((cmdtype & TEXT_CMD) && text == cmd) {
515                         combining = it->second.combining();
516                         needsTermination = !it->second.textnotermination();
517                         if (req && it->second.textfeature() &&
518                             !it->second.textpreamble.empty())
519                                 req->insert(it->second.textpreamble);
520                         return it->first;
521                 }
522         }
523         needsTermination = false;
524         return 0;
525 }
526
527
528 docstring Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
529                 bool & needsTermination, docstring & rem, set<string> * req)
530 {
531         needsTermination = false;
532         rem = empty_docstring();
533         bool const mathmode = cmdtype & MATH_CMD;
534         bool const textmode = cmdtype & TEXT_CMD;
535         docstring symbols;
536         size_t i = 0;
537         size_t const cmdend = cmd.size();
538         CharInfoMap::const_iterator const uniend = unicodesymbols.end();
539         for (size_t j = 0; j < cmdend; ++j) {
540                 // Also get the char after a backslash
541                 if (j + 1 < cmdend && cmd[j] == '\\')
542                         ++j;
543                 // If a macro argument follows, get it, too
544                 if (j + 1 < cmdend && cmd[j + 1] == '{') {
545                         size_t k = j + 1;
546                         int count = 1;
547                         while (k < cmdend && count && k != docstring::npos) {
548                                 k = cmd.find_first_of(from_ascii("{}"), k + 1);
549                                 if (cmd[k] == '{')
550                                         ++count;
551                                 else
552                                         --count;
553                         }
554                         if (k != docstring::npos)
555                                 j = k;
556                 }
557                 // Start with this substring and try augmenting it when it is
558                 // the prefix of some command in the unicodesymbols file
559                 docstring const subcmd = cmd.substr(i, j - i + 1);
560
561                 CharInfoMap::const_iterator it = unicodesymbols.begin();
562                 size_t unicmd_size = 0;
563                 char_type c = 0;
564                 for (; it != uniend; ++it) {
565                         docstring const math = mathmode ? it->second.mathcommand
566                                                         : docstring();
567                         docstring const text = textmode ? it->second.textcommand
568                                                         : docstring();
569                         size_t cur_size = max(math.size(), text.size());
570                         // The current math or text unicode command cannot
571                         // match, or we already matched a longer one
572                         if (cur_size < subcmd.size() || cur_size <= unicmd_size)
573                                 continue;
574
575                         docstring tmp = subcmd;
576                         size_t k = j;
577                         while (prefixIs(math, tmp) || prefixIs(text, tmp)) {
578                                 ++k;
579                                 if (k >= cmdend || cur_size <= tmp.size())
580                                         break;
581                                 tmp += cmd[k];
582                         }
583                         // No match
584                         if (k == j)
585                                 continue;
586
587                         // The last added char caused a mismatch, because
588                         // we didn't exhaust the chars in cmd and didn't
589                         // exceed the maximum size of the current unicmd
590                         if (k < cmdend && cur_size > tmp.size())
591                                 tmp.resize(tmp.size() - 1);
592
593                         // If this is an exact match, we found a (longer)
594                         // matching entry in the unicodesymbols file.
595                         // If the entry doesn't start with '\', we take note
596                         // of the match and continue (this is not a ultimate
597                         // acceptance, as some other entry may match a longer
598                         // portion of the cmd string). However, if the entry
599                         // does start with '\', we accept the match only if
600                         // this is a valid macro, i.e., either it is a single
601                         // (nonletter) char macro, or nothing else follows,
602                         // or what follows is a nonletter char, or the last
603                         // character is a }.
604                         if ((math == tmp || text == tmp)
605                             && (tmp[0] != '\\'
606                                    || (tmp.size() == 2 && !isAlphaASCII(tmp[1]))
607                                    || k == cmdend 
608                                    || !isAlphaASCII(cmd[k])
609                                    || tmp[tmp.size() - 1] == '}')
610                                  ) {
611                                 c = it->first;
612                                 j = k - 1;
613                                 i = j + 1;
614                                 unicmd_size = cur_size;
615                                 if (math == tmp)
616                                         needsTermination = !it->second.mathnotermination();
617                                 else
618                                         needsTermination = !it->second.textnotermination();
619                                 if (req) {
620                                         if (math == tmp && it->second.mathfeature() &&
621                                             !it->second.mathpreamble.empty())
622                                                 req->insert(it->second.mathpreamble);
623                                         if (text == tmp && it->second.textfeature() &&
624                                             !it->second.textpreamble.empty())
625                                                 req->insert(it->second.textpreamble);
626                                 }
627                         }
628                 }
629                 if (unicmd_size)
630                         symbols += c;
631                 else if (j + 1 == cmdend) {
632                         // No luck. Return what remains
633                         rem = cmd.substr(i);
634                         if (needsTermination && !rem.empty()) {
635                                 if (rem.substr(0, 2) == "{}") {
636                                         rem = rem.substr(2);
637                                         needsTermination = false;
638                                 } else if (rem[0] == ' ') {
639                                         needsTermination = false;
640                                         // LaTeX would swallow all spaces
641                                         rem = ltrim(rem);
642                                 }
643                         }
644                 }
645         }
646         return symbols;
647 }
648
649
650 void Encodings::initUnicodeMath(Buffer const & buffer, bool for_master)
651 {
652 #ifdef TEX2LYX
653         // The code below is not needed in tex2lyx and requires additional stuff
654         (void)buffer;
655         (void)for_master;
656 #else
657         if (for_master) {
658                 mathcmd.clear();
659                 textcmd.clear();
660                 mathsym.clear();
661         }
662
663         // Check this buffer
664         Inset & inset = buffer.inset();
665         InsetIterator it = inset_iterator_begin(inset);
666         InsetIterator const end = inset_iterator_end(inset);
667         for (; it != end; ++it)
668                 it->initUnicodeMath();
669
670         if (!for_master)
671                 return;
672
673         // Check children
674         ListOfBuffers blist = buffer.getDescendents();
675         ListOfBuffers::const_iterator bit = blist.begin();
676         ListOfBuffers::const_iterator const bend = blist.end();
677         for (; bit != bend; ++bit)
678                 initUnicodeMath(**bit, false);
679 #endif
680 }
681
682
683 void Encodings::validate(char_type c, LaTeXFeatures & features, bool for_mathed)
684 {
685 #ifdef TEX2LYX
686         // The code below is not needed in tex2lyx and requires additional stuff
687         (void)c;
688         (void)features;
689         (void)for_mathed;
690 #else
691         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
692         if (it != unicodesymbols.end()) {
693                 // In mathed, c could be used both in textmode and mathmode
694                 bool const math_mode = for_mathed && isMathCmd(c);
695                 bool const use_math = math_mode ||
696                                       (!for_mathed && it->second.textcommand.empty());
697                 bool const use_text = (for_mathed && isTextCmd(c)) ||
698                                       (!for_mathed && !it->second.textcommand.empty());
699                 bool const plain_utf8 = (features.runparams().encoding->name() == "utf8-plain");
700                 // with utf8-plain, we only load packages when in mathed (see #7766)
701                 if (math_mode || (use_math && !plain_utf8)) {
702                         if (!it->second.mathpreamble.empty()) {
703                                 if (it->second.mathfeature()) {
704                                         string feats = it->second.mathpreamble;
705                                         while (!feats.empty()) {
706                                                 string feat;
707                                                 feats = split(feats, feat, ',');
708                                                 features.require(feat);
709                                         }
710                                 } else
711                                         features.addPreambleSnippet(it->second.mathpreamble);
712                         }
713                 }
714                 // with utf8-plain, we do not load packages (see #7766)
715                 if (use_text && !plain_utf8) {
716                         if (!it->second.textpreamble.empty()) {
717                                 if (it->second.textfeature()) {
718                                         string feats = it->second.textpreamble;
719                                         while (!feats.empty()) {
720                                                 string feat;
721                                                 feats = split(feats, feat, ',');
722                                                 features.require(feat);
723                                         }
724                                 } else
725                                         features.addPreambleSnippet(it->second.textpreamble);
726                         }
727                 }
728         }
729         if (for_mathed && isMathSym(c)) {
730                 features.require("amstext");
731                 features.require("lyxmathsym");
732         }
733 #endif
734 }
735
736
737 bool Encodings::isHebrewComposeChar(char_type c)
738 {
739         return c <= 0x05c2 && c >= 0x05b0 && c != 0x05be && c != 0x05c0;
740 }
741
742
743 // Special Arabic letters are ones that do not get connected from left
744 // they are hamza, alef_madda, alef_hamza, waw_hamza, alef_hamza_under,
745 // alef, tah_marbota, dal, thal, rah, zai, wow, alef_maksoura
746
747 bool Encodings::isArabicSpecialChar(char_type c)
748 {
749         return (c >= 0x0621 && c <= 0x0625) || (c >= 0x0630 && c <= 0x0632)
750                 || c == 0x0627 || c == 0x0629 || c == 0x062f || c == 0x0648
751                 || c == 0x0649 || c == 0x0698;
752 }
753
754
755 bool Encodings::isArabicComposeChar(char_type c)
756 {
757         return c >= 0x064b && c <= 0x0652;
758 }
759
760
761 bool Encodings::isArabicChar(char_type c)
762 {
763         return c >= arabic_start && c <= arabic_end
764                 && arabic_table[c-arabic_start][0];
765 }
766
767
768 char_type Encodings::transformChar(char_type c, Encodings::LetterForm form)
769 {
770         return isArabicChar(c) ? arabic_table[c-arabic_start][form] : c;
771 }
772
773
774 bool Encodings::isCombiningChar(char_type c)
775 {
776         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
777         if (it != unicodesymbols.end())
778                 return it->second.combining();
779         return false;
780 }
781
782
783 string const Encodings::TIPAShortcut(char_type c)
784 {
785         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
786         if (it != unicodesymbols.end())
787                 return it->second.tipashortcut;
788         return string();
789 }
790
791
792 bool Encodings::isKnownScriptChar(char_type const c, string & preamble)
793 {
794         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
795
796         if (it == unicodesymbols.end())
797                 return false;
798
799         if (it->second.textpreamble != "textgreek" && it->second.textpreamble != "textcyr")
800                 return false;
801
802         if (preamble.empty()) {
803                 preamble = it->second.textpreamble;
804                 return true;
805         }
806         return it->second.textpreamble == preamble;
807 }
808
809
810 bool Encodings::isForced(char_type c)
811 {
812         return (!forced.empty() && forced.find(c) != forced.end());
813 }
814
815
816 bool Encodings::isMathAlpha(char_type c)
817 {
818         return mathalpha.count(c);
819 }
820
821
822 Encoding const * Encodings::fromLyXName(string const & name) const
823 {
824         EncodingList::const_iterator const it = encodinglist.find(name);
825         return it != encodinglist.end() ? &it->second : 0;
826 }
827
828
829 Encoding const * Encodings::fromLaTeXName(string const & n) const
830 {
831         string name = n;
832         // FIXME: if we have to test for too many of these synonyms,
833         // we should instead extend the format of lib/encodings
834         if (n == "ansinew")
835                 name = "cp1252";
836
837         // We don't use find_if because it makes copies of the pairs in
838         // the map.
839         // This linear search is OK since we don't have many encodings.
840         // Users could even optimize it by putting the encodings they use
841         // most at the top of lib/encodings.
842         EncodingList::const_iterator const end = encodinglist.end();
843         for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
844                 if (it->second.latexName() == name)
845                         return &it->second;
846         return 0;
847 }
848
849
850 Encodings::Encodings()
851 {
852 }
853
854
855 void Encodings::read(FileName const & encfile, FileName const & symbolsfile)
856 {
857         // We must read the symbolsfile first, because the Encoding
858         // constructor depends on it.
859         Lexer symbolslex;
860         symbolslex.setFile(symbolsfile);
861         bool getNextToken = true;
862         while (symbolslex.isOK()) {
863                 char_type symbol;
864                 CharInfo info;
865                 string flags;
866
867                 if (getNextToken) {
868                         if (!symbolslex.next(true))
869                                 break;
870                 } else
871                         getNextToken = true;
872
873                 istringstream is(symbolslex.getString());
874                 // reading symbol directly does not work if
875                 // char_type == wchar_t.
876                 boost::uint32_t tmp;
877                 if(!(is >> hex >> tmp))
878                         break;
879                 symbol = tmp;
880
881                 if (!symbolslex.next(true))
882                         break;
883                 info.textcommand = symbolslex.getDocString();
884                 if (!symbolslex.next(true))
885                         break;
886                 info.textpreamble = symbolslex.getString();
887                 if (!symbolslex.next(true))
888                         break;
889                 flags = symbolslex.getString();
890
891                 info.flags = 0;
892                 if (suffixIs(info.textcommand, '}'))
893                         info.flags |= CharInfoTextNoTermination;
894                 if (suffixIs(info.mathcommand, '}'))
895                         info.flags |= CharInfoMathNoTermination;
896                 while (!flags.empty()) {
897                         string flag;
898                         flags = split(flags, flag, ',');
899                         if (flag == "combining") {
900                                 info.flags |= CharInfoCombining;
901                         } else if (flag == "force") {
902                                 info.flags |= CharInfoForce;
903                                 forced.insert(symbol);
904                         } else if (flag == "mathalpha") {
905                                 mathalpha.insert(symbol);
906                         } else if (flag == "notermination=text") {
907                                 info.flags |= CharInfoTextNoTermination;
908                         } else if (flag == "notermination=math") {
909                                 info.flags |= CharInfoMathNoTermination;
910                         } else if (flag == "notermination=both") {
911                                 info.flags |= CharInfoTextNoTermination;
912                                 info.flags |= CharInfoMathNoTermination;
913                         } else if (flag == "notermination=none") {
914                                 info.flags &= ~CharInfoTextNoTermination;
915                                 info.flags &= ~CharInfoMathNoTermination;
916                         } else if (contains(flag, "tipashortcut=")) {
917                                 info.tipashortcut = split(flag, '=');
918                         } else {
919                                 lyxerr << "Ignoring unknown flag `" << flag
920                                        << "' for symbol `0x"
921                                        << hex << symbol << dec
922                                        << "'." << endl;
923                         }
924                 }
925                 // mathcommand and mathpreamble have been added for 1.6.0.
926                 // make them optional so that old files still work.
927                 int const lineno = symbolslex.lineNumber();
928                 bool breakout = false;
929                 if (symbolslex.next(true)) {
930                         if (symbolslex.lineNumber() != lineno) {
931                                 // line in old format without mathcommand and mathpreamble
932                                 getNextToken = false;
933                         } else {
934                                 info.mathcommand = symbolslex.getDocString();
935                                 if (symbolslex.next(true)) {
936                                         if (symbolslex.lineNumber() != lineno) {
937                                                 // line in new format with mathcommand only
938                                                 getNextToken = false;
939                                         } else {
940                                                 // line in new format with mathcommand and mathpreamble
941                                                 info.mathpreamble = symbolslex.getString();
942                                         }
943                                 } else
944                                         breakout = true;
945                         }
946                 } else {
947                         breakout = true;
948                 }
949
950                 // backward compatibility
951                 if (info.mathpreamble == "esintoramsmath")
952                         info.mathpreamble = "esint|amsmath";
953
954                 if (!info.textpreamble.empty())
955                         if (info.textpreamble[0] != '\\')
956                                 info.flags |= CharInfoTextFeature;
957                 if (!info.mathpreamble.empty())
958                         if (info.mathpreamble[0] != '\\')
959                                 info.flags |= CharInfoMathFeature;
960
961                 LYXERR(Debug::INFO, "Read unicode symbol " << symbol << " '"
962                         << to_utf8(info.textcommand) << "' '" << info.textpreamble
963                         << " '" << info.textfeature() << ' ' << info.textnotermination()
964                         << ' ' << to_utf8(info.mathcommand) << "' '" << info.mathpreamble
965                         << "' " << info.mathfeature() << ' ' << info.mathnotermination()
966                         << ' ' << info.combining() << ' ' << info.force());
967
968                 // we assume that at least one command is nonempty when using unicodesymbols
969                 if (!info.textcommand.empty() || !info.mathcommand.empty())
970                         unicodesymbols[symbol] = info;
971
972                 if (breakout)
973                         break;
974         }
975
976         // Now read the encodings
977         enum {
978                 et_encoding = 1,
979                 et_end
980         };
981
982         LexerKeyword encodingtags[] = {
983                 { "encoding", et_encoding },
984                 { "end", et_end }
985         };
986
987         Lexer lex(encodingtags);
988         lex.setFile(encfile);
989         lex.setContext("Encodings::read");
990         while (lex.isOK()) {
991                 switch (lex.lex()) {
992                 case et_encoding:
993                 {
994                         lex.next();
995                         string const name = lex.getString();
996                         lex.next();
997                         string const latexname = lex.getString();
998                         lex.next();
999                         string const guiname = lex.getString();
1000                         lex.next();
1001                         string const iconvname = lex.getString();
1002                         lex.next();
1003                         string const width = lex.getString();
1004                         bool fixedwidth = false;
1005                         if (width == "fixed")
1006                                 fixedwidth = true;
1007                         else if (width == "variable")
1008                                 fixedwidth = false;
1009                         else
1010                                 lex.printError("Unknown width");
1011
1012                         lex.next();
1013                         string const p = lex.getString();
1014                         Encoding::Package package = Encoding::none;
1015                         if (p == "none")
1016                                 package = Encoding::none;
1017                         else if (p == "inputenc")
1018                                 package = Encoding::inputenc;
1019                         else if (p == "CJK")
1020                                 package = Encoding::CJK;
1021                         else if (p == "japanese")
1022                                 package = Encoding::japanese;
1023                         else
1024                                 lex.printError("Unknown package");
1025
1026                         LYXERR(Debug::INFO, "Reading encoding " << name);
1027                         encodinglist[name] = Encoding(name, latexname,
1028                                 guiname, iconvname, fixedwidth, package);
1029
1030                         if (lex.lex() != et_end)
1031                                 lex.printError("Missing end");
1032                         break;
1033                 }
1034                 case et_end:
1035                         lex.printError("Misplaced end");
1036                         break;
1037                 case Lexer::LEX_FEOF:
1038                         break;
1039                 default:
1040                         lex.printError("Unknown tag");
1041                         break;
1042                 }
1043         }
1044 }
1045
1046
1047 } // namespace lyx