]> git.lyx.org Git - lyx.git/blob - src/Encoding.cpp
Update my email and status.
[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, bool u, Encoding::Package p)
309         : name_(n), latexName_(l), guiName_(g), iconvName_(i), fixedwidth_(f),
310           unsafe_(u), package_(p)
311 {
312         if (n == "ascii") {
313                 // ASCII can encode 128 code points and nothing else
314                 start_encodable_ = 128;
315                 complete_ = true;
316         } else if (i == "UTF-8") {
317                 // UTF8 can encode all UCS4 code points
318                 start_encodable_ = max_ucs4;
319                 complete_ = true;
320         } else {
321                 complete_ = false;
322         }
323 }
324
325
326 void Encoding::init() const
327 {
328         if (complete_)
329                 return;
330
331         start_encodable_ = 0;
332         // temporarily switch off lyxerr, since we will generate iconv errors
333         lyxerr.disable();
334         if (fixedwidth_) {
335                 // We do not need to check all UCS4 code points, it is enough
336                 // if we check all 256 code points of this encoding.
337                 for (unsigned short j = 0; j < 256; ++j) {
338                         char const c = char(j);
339                         vector<char_type> const ucs4 = eightbit_to_ucs4(&c, 1, iconvName_);
340                         if (ucs4.size() != 1)
341                                 continue;
342                         char_type const uc = ucs4[0];
343                         CharInfoMap::const_iterator const it = unicodesymbols.find(uc);
344                         if (it == unicodesymbols.end() || !it->second.force())
345                                 encodable_.insert(uc);
346                 }
347         } else {
348                 // We do not know how many code points this encoding has, and
349                 // they do not have a direct representation as a single byte,
350                 // therefore we need to check all UCS4 code points.
351                 // This is expensive!
352                 for (char_type c = 0; c < max_ucs4; ++c) {
353                         vector<char> const eightbit = ucs4_to_eightbit(&c, 1, iconvName_);
354                         if (!eightbit.empty()) {
355                                 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
356                                 if (it == unicodesymbols.end() || !it->second.force())
357                                         encodable_.insert(c);
358                         }
359                 }
360         }
361         lyxerr.enable();
362         CharSet::iterator it = encodable_.find(start_encodable_);
363         while (it != encodable_.end()) {
364                 encodable_.erase(it);
365                 ++start_encodable_;
366                 it = encodable_.find(start_encodable_);
367         }
368         complete_ = true;
369 }
370
371
372 bool Encoding::encodable(char_type c) const
373 {
374         // assure the used encoding is properly initialized
375         init();
376
377         if (iconvName_ == "UTF-8" && package_ == none)
378                 return true;
379         if (c < start_encodable_ && !encodings.isForced(c))
380                 return true;
381         if (encodable_.find(c) != encodable_.end())
382                 return true;
383         return false;
384 }
385
386
387 pair<docstring, bool> Encoding::latexChar(char_type c) const
388 {
389         if (encodable(c))
390                 return make_pair(docstring(1, c), false);
391
392         // c cannot (or should not) be encoded in this encoding
393         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
394         if (it == unicodesymbols.end())
395                 throw EncodingException(c);
396         // at least one of mathcommand and textcommand is nonempty
397         if (it->second.textcommand.empty())
398                 return make_pair(
399                         "\\ensuremath{" + it->second.mathcommand + '}', false);
400         return make_pair(it->second.textcommand, !it->second.textnotermination());
401 }
402
403
404 pair<docstring, docstring> Encoding::latexString(docstring const input, bool dryrun) const
405 {
406         docstring result;
407         docstring uncodable;
408         bool terminate = false;
409         for (size_t n = 0; n < input.size(); ++n) {
410                 try {
411                         char_type const c = input[n];
412                         pair<docstring, bool> latex_char = latexChar(c);
413                         docstring const latex = latex_char.first;
414                         if (terminate && !prefixIs(latex, '\\')
415                             && !prefixIs(latex, '{')
416                             && !prefixIs(latex, '}')) {
417                                         // Prevent eating of a following
418                                         // space or command corruption by
419                                         // following characters
420                                         if (latex == " ")
421                                                 result += "{}";
422                                         else
423                                                 result += " ";
424                                 }
425                         result += latex;
426                         terminate = latex_char.second;
427                 } catch (EncodingException & /* e */) {
428                         LYXERR0("Uncodable character in latexString!");
429                         if (dryrun) {
430                                 result += "<" + _("LyX Warning: ")
431                                            + _("uncodable character") + " '";
432                                 result += docstring(1, input[n]);
433                                 result += "'>";
434                         } else
435                                 uncodable += input[n];
436                 }
437         }
438         return make_pair(result, uncodable);
439 }
440
441
442 vector<char_type> Encoding::symbolsList() const
443 {
444         // assure the used encoding is properly initialized
445         init();
446
447         // first all encodable characters
448         vector<char_type> symbols(encodable_.begin(), encodable_.end());
449         // add those below start_encodable_
450         for (char_type c = 0; c < start_encodable_; ++c)
451                 symbols.push_back(c);
452         // now the ones from the unicodesymbols file
453         CharInfoMap::const_iterator const end = unicodesymbols.end();
454         CharInfoMap::const_iterator it = unicodesymbols.begin();
455         for (; it != end; ++it)
456                 symbols.push_back(it->first);
457         return symbols;
458 }
459
460
461 bool Encodings::latexMathChar(char_type c, bool mathmode,
462                         Encoding const * encoding, docstring & command,
463                         bool & needsTermination)
464 {
465         command = empty_docstring();
466         if (encoding)
467                 if (encoding->encodable(c))
468                         command = docstring(1, c);
469         needsTermination = false;
470
471         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
472         if (it == unicodesymbols.end()) {
473                 if (!encoding || command.empty())
474                         throw EncodingException(c);
475                 if (mathmode)
476                         addMathSym(c);
477                 return false;
478         }
479         // at least one of mathcommand and textcommand is nonempty
480         bool use_math = (mathmode && !it->second.mathcommand.empty()) ||
481                         (!mathmode && it->second.textcommand.empty());
482         if (use_math) {
483                 command = it->second.mathcommand;
484                 needsTermination = !it->second.mathnotermination();
485                 addMathCmd(c);
486         } else {
487                 if (!encoding || command.empty()) {
488                         command = it->second.textcommand;
489                         needsTermination = !it->second.textnotermination();
490                         addTextCmd(c);
491                 }
492                 if (mathmode)
493                         addMathSym(c);
494         }
495         return use_math;
496 }
497
498
499 char_type Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
500                 bool & combining, bool & needsTermination, set<string> * req)
501 {
502         CharInfoMap::const_iterator const end = unicodesymbols.end();
503         CharInfoMap::const_iterator it = unicodesymbols.begin();
504         for (combining = false; it != end; ++it) {
505                 docstring const math = it->second.mathcommand;
506                 docstring const text = it->second.textcommand;
507                 if ((cmdtype & MATH_CMD) && math == cmd) {
508                         combining = it->second.combining();
509                         needsTermination = !it->second.mathnotermination();
510                         if (req && it->second.mathfeature() &&
511                             !it->second.mathpreamble.empty())
512                                 req->insert(it->second.mathpreamble);
513                         return it->first;
514                 }
515                 if ((cmdtype & TEXT_CMD) && text == cmd) {
516                         combining = it->second.combining();
517                         needsTermination = !it->second.textnotermination();
518                         if (req && it->second.textfeature() &&
519                             !it->second.textpreamble.empty())
520                                 req->insert(it->second.textpreamble);
521                         return it->first;
522                 }
523         }
524         needsTermination = false;
525         return 0;
526 }
527
528
529 docstring Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
530                 bool & needsTermination, docstring & rem, set<string> * req)
531 {
532         needsTermination = false;
533         rem = empty_docstring();
534         bool const mathmode = cmdtype & MATH_CMD;
535         bool const textmode = cmdtype & TEXT_CMD;
536         docstring symbols;
537         size_t i = 0;
538         size_t const cmdend = cmd.size();
539         CharInfoMap::const_iterator const uniend = unicodesymbols.end();
540         for (size_t j = 0; j < cmdend; ++j) {
541                 // Also get the char after a backslash
542                 if (j + 1 < cmdend && cmd[j] == '\\')
543                         ++j;
544                 // If a macro argument follows, get it, too
545                 if (j + 1 < cmdend && cmd[j + 1] == '{') {
546                         size_t k = j + 1;
547                         int count = 1;
548                         while (k < cmdend && count && k != docstring::npos) {
549                                 k = cmd.find_first_of(from_ascii("{}"), k + 1);
550                                 if (cmd[k] == '{')
551                                         ++count;
552                                 else
553                                         --count;
554                         }
555                         if (k != docstring::npos)
556                                 j = k;
557                 }
558                 // Start with this substring and try augmenting it when it is
559                 // the prefix of some command in the unicodesymbols file
560                 docstring const subcmd = cmd.substr(i, j - i + 1);
561
562                 CharInfoMap::const_iterator it = unicodesymbols.begin();
563                 size_t unicmd_size = 0;
564                 char_type c = 0;
565                 for (; it != uniend; ++it) {
566                         docstring const math = mathmode ? it->second.mathcommand
567                                                         : docstring();
568                         docstring const text = textmode ? it->second.textcommand
569                                                         : docstring();
570                         size_t cur_size = max(math.size(), text.size());
571                         // The current math or text unicode command cannot
572                         // match, or we already matched a longer one
573                         if (cur_size < subcmd.size() || cur_size <= unicmd_size)
574                                 continue;
575
576                         docstring tmp = subcmd;
577                         size_t k = j;
578                         while (prefixIs(math, tmp) || prefixIs(text, tmp)) {
579                                 ++k;
580                                 if (k >= cmdend || cur_size <= tmp.size())
581                                         break;
582                                 tmp += cmd[k];
583                         }
584                         // No match
585                         if (k == j)
586                                 continue;
587
588                         // The last added char caused a mismatch, because
589                         // we didn't exhaust the chars in cmd and didn't
590                         // exceed the maximum size of the current unicmd
591                         if (k < cmdend && cur_size > tmp.size())
592                                 tmp.resize(tmp.size() - 1);
593
594                         // If this is an exact match, we found a (longer)
595                         // matching entry in the unicodesymbols file.
596                         // If the entry doesn't start with '\', we take note
597                         // of the match and continue (this is not a ultimate
598                         // acceptance, as some other entry may match a longer
599                         // portion of the cmd string). However, if the entry
600                         // does start with '\', we accept the match only if
601                         // this is a valid macro, i.e., either it is a single
602                         // (nonletter) char macro, or nothing else follows,
603                         // or what follows is a nonletter char, or the last
604                         // character is a }.
605                         if ((math == tmp || text == tmp)
606                             && (tmp[0] != '\\'
607                                    || (tmp.size() == 2 && !isAlphaASCII(tmp[1]))
608                                    || k == cmdend 
609                                    || !isAlphaASCII(cmd[k])
610                                    || tmp[tmp.size() - 1] == '}')
611                                  ) {
612                                 c = it->first;
613                                 j = k - 1;
614                                 i = j + 1;
615                                 unicmd_size = cur_size;
616                                 if (math == tmp)
617                                         needsTermination = !it->second.mathnotermination();
618                                 else
619                                         needsTermination = !it->second.textnotermination();
620                                 if (req) {
621                                         if (math == tmp && it->second.mathfeature() &&
622                                             !it->second.mathpreamble.empty())
623                                                 req->insert(it->second.mathpreamble);
624                                         if (text == tmp && it->second.textfeature() &&
625                                             !it->second.textpreamble.empty())
626                                                 req->insert(it->second.textpreamble);
627                                 }
628                         }
629                 }
630                 if (unicmd_size)
631                         symbols += c;
632                 else if (j + 1 == cmdend) {
633                         // No luck. Return what remains
634                         rem = cmd.substr(i);
635                         if (needsTermination && !rem.empty()) {
636                                 if (rem.substr(0, 2) == "{}") {
637                                         rem = rem.substr(2);
638                                         needsTermination = false;
639                                 } else if (rem[0] == ' ') {
640                                         needsTermination = false;
641                                         // LaTeX would swallow all spaces
642                                         rem = ltrim(rem);
643                                 }
644                         }
645                 }
646         }
647         return symbols;
648 }
649
650
651 void Encodings::initUnicodeMath(Buffer const & buffer, bool for_master)
652 {
653 #ifdef TEX2LYX
654         // The code below is not needed in tex2lyx and requires additional stuff
655         (void)buffer;
656         (void)for_master;
657 #else
658         if (for_master) {
659                 mathcmd.clear();
660                 textcmd.clear();
661                 mathsym.clear();
662         }
663
664         // Check this buffer
665         Inset & inset = buffer.inset();
666         InsetIterator it = inset_iterator_begin(inset);
667         InsetIterator const end = inset_iterator_end(inset);
668         for (; it != end; ++it)
669                 it->initUnicodeMath();
670
671         if (!for_master)
672                 return;
673
674         // Check children
675         ListOfBuffers blist = buffer.getDescendents();
676         ListOfBuffers::const_iterator bit = blist.begin();
677         ListOfBuffers::const_iterator const bend = blist.end();
678         for (; bit != bend; ++bit)
679                 initUnicodeMath(**bit, false);
680 #endif
681 }
682
683
684 void Encodings::validate(char_type c, LaTeXFeatures & features, bool for_mathed)
685 {
686 #ifdef TEX2LYX
687         // The code below is not needed in tex2lyx and requires additional stuff
688         (void)c;
689         (void)features;
690         (void)for_mathed;
691 #else
692         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
693         if (it != unicodesymbols.end()) {
694                 // In mathed, c could be used both in textmode and mathmode
695                 bool const math_mode = for_mathed && isMathCmd(c);
696                 bool const use_math = math_mode ||
697                                       (!for_mathed && it->second.textcommand.empty());
698                 bool const use_text = (for_mathed && isTextCmd(c)) ||
699                                       (!for_mathed && !it->second.textcommand.empty());
700                 bool const plain_utf8 = (features.runparams().encoding->name() == "utf8-plain");
701                 bool const unicode_math = (features.isRequired("unicode-math")
702                         && features.isAvailable("unicode-math"));
703                 // with utf8-plain, we only load packages when in mathed (see #7766)
704                 // and if we do not use unicode-math
705                 if ((math_mode && !unicode_math)
706                      || (use_math && !plain_utf8)) {
707                         if (!it->second.mathpreamble.empty()) {
708                                 if (it->second.mathfeature()) {
709                                         string feats = it->second.mathpreamble;
710                                         while (!feats.empty()) {
711                                                 string feat;
712                                                 feats = split(feats, feat, ',');
713                                                 features.require(feat);
714                                         }
715                                 } else
716                                         features.addPreambleSnippet(it->second.mathpreamble);
717                         }
718                 }
719                 // with utf8-plain, we do not load packages (see #7766)
720                 if (use_text && !plain_utf8) {
721                         if (!it->second.textpreamble.empty()) {
722                                 if (it->second.textfeature()) {
723                                         string feats = it->second.textpreamble;
724                                         while (!feats.empty()) {
725                                                 string feat;
726                                                 feats = split(feats, feat, ',');
727                                                 features.require(feat);
728                                         }
729                                 } else
730                                         features.addPreambleSnippet(it->second.textpreamble);
731                         }
732                 }
733         }
734         if (for_mathed && isMathSym(c)) {
735                 features.require("amstext");
736                 features.require("lyxmathsym");
737         }
738 #endif
739 }
740
741
742 bool Encodings::isHebrewComposeChar(char_type c)
743 {
744         return c <= 0x05c2 && c >= 0x05b0 && c != 0x05be && c != 0x05c0;
745 }
746
747
748 // Special Arabic letters are ones that do not get connected from left
749 // they are hamza, alef_madda, alef_hamza, waw_hamza, alef_hamza_under,
750 // alef, tah_marbota, dal, thal, rah, zai, wow, alef_maksoura
751
752 bool Encodings::isArabicSpecialChar(char_type c)
753 {
754         return (c >= 0x0621 && c <= 0x0625) || (c >= 0x0630 && c <= 0x0632)
755                 || c == 0x0627 || c == 0x0629 || c == 0x062f || c == 0x0648
756                 || c == 0x0649 || c == 0x0698;
757 }
758
759
760 bool Encodings::isArabicComposeChar(char_type c)
761 {
762         return c >= 0x064b && c <= 0x0652;
763 }
764
765
766 bool Encodings::isArabicChar(char_type c)
767 {
768         return c >= arabic_start && c <= arabic_end
769                 && arabic_table[c-arabic_start][0];
770 }
771
772
773 char_type Encodings::transformChar(char_type c, Encodings::LetterForm form)
774 {
775         return isArabicChar(c) ? arabic_table[c-arabic_start][form] : c;
776 }
777
778
779 bool Encodings::isCombiningChar(char_type c)
780 {
781         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
782         if (it != unicodesymbols.end())
783                 return it->second.combining();
784         return false;
785 }
786
787
788 string const Encodings::TIPAShortcut(char_type c)
789 {
790         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
791         if (it != unicodesymbols.end())
792                 return it->second.tipashortcut;
793         return string();
794 }
795
796
797 bool Encodings::isKnownScriptChar(char_type const c, string & preamble)
798 {
799         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
800
801         if (it == unicodesymbols.end())
802                 return false;
803
804         if (it->second.textpreamble != "textgreek" && it->second.textpreamble != "textcyr")
805                 return false;
806
807         if (preamble.empty()) {
808                 preamble = it->second.textpreamble;
809                 return true;
810         }
811         return it->second.textpreamble == preamble;
812 }
813
814
815 bool Encodings::isForced(char_type c)
816 {
817         return (!forced.empty() && forced.find(c) != forced.end());
818 }
819
820
821 bool Encodings::isMathAlpha(char_type c)
822 {
823         return mathalpha.count(c);
824 }
825
826
827 Encoding const *
828 Encodings::fromLyXName(string const & name, bool allowUnsafe) const
829 {
830         EncodingList::const_iterator const it = encodinglist.find(name);
831         if (!allowUnsafe && it->second.unsafe())
832                 return 0;
833         return it != encodinglist.end() ? &it->second : 0;
834 }
835
836
837 Encoding const *
838 Encodings::fromLaTeXName(string const & n, bool allowUnsafe) const
839 {
840         string name = n;
841         // FIXME: if we have to test for too many of these synonyms,
842         // we should instead extend the format of lib/encodings
843         if (n == "ansinew")
844                 name = "cp1252";
845
846         // We don't use find_if because it makes copies of the pairs in
847         // the map.
848         // This linear search is OK since we don't have many encodings.
849         // Users could even optimize it by putting the encodings they use
850         // most at the top of lib/encodings.
851         EncodingList::const_iterator const end = encodinglist.end();
852         for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
853                 if (it->second.latexName() == name) {
854                         if (!allowUnsafe && it->second.unsafe())
855                                 return 0;
856                         return &it->second;
857                 }
858         return 0;
859 }
860
861
862 Encodings::Encodings()
863 {}
864
865
866 void Encodings::read(FileName const & encfile, FileName const & symbolsfile)
867 {
868         // We must read the symbolsfile first, because the Encoding
869         // constructor depends on it.
870         Lexer symbolslex;
871         symbolslex.setFile(symbolsfile);
872         bool getNextToken = true;
873         while (symbolslex.isOK()) {
874                 char_type symbol;
875                 CharInfo info;
876                 string flags;
877
878                 if (getNextToken) {
879                         if (!symbolslex.next(true))
880                                 break;
881                 } else
882                         getNextToken = true;
883
884                 istringstream is(symbolslex.getString());
885                 // reading symbol directly does not work if
886                 // char_type == wchar_t.
887                 boost::uint32_t tmp;
888                 if(!(is >> hex >> tmp))
889                         break;
890                 symbol = tmp;
891
892                 if (!symbolslex.next(true))
893                         break;
894                 info.textcommand = symbolslex.getDocString();
895                 if (!symbolslex.next(true))
896                         break;
897                 info.textpreamble = symbolslex.getString();
898                 if (!symbolslex.next(true))
899                         break;
900                 flags = symbolslex.getString();
901
902                 info.flags = 0;
903                 if (suffixIs(info.textcommand, '}'))
904                         info.flags |= CharInfoTextNoTermination;
905                 if (suffixIs(info.mathcommand, '}'))
906                         info.flags |= CharInfoMathNoTermination;
907                 while (!flags.empty()) {
908                         string flag;
909                         flags = split(flags, flag, ',');
910                         if (flag == "combining") {
911                                 info.flags |= CharInfoCombining;
912                         } else if (flag == "force") {
913                                 info.flags |= CharInfoForce;
914                                 forced.insert(symbol);
915                         } else if (flag == "mathalpha") {
916                                 mathalpha.insert(symbol);
917                         } else if (flag == "notermination=text") {
918                                 info.flags |= CharInfoTextNoTermination;
919                         } else if (flag == "notermination=math") {
920                                 info.flags |= CharInfoMathNoTermination;
921                         } else if (flag == "notermination=both") {
922                                 info.flags |= CharInfoTextNoTermination;
923                                 info.flags |= CharInfoMathNoTermination;
924                         } else if (flag == "notermination=none") {
925                                 info.flags &= ~CharInfoTextNoTermination;
926                                 info.flags &= ~CharInfoMathNoTermination;
927                         } else if (contains(flag, "tipashortcut=")) {
928                                 info.tipashortcut = split(flag, '=');
929                         } else {
930                                 lyxerr << "Ignoring unknown flag `" << flag
931                                        << "' for symbol `0x"
932                                        << hex << symbol << dec
933                                        << "'." << endl;
934                         }
935                 }
936                 // mathcommand and mathpreamble have been added for 1.6.0.
937                 // make them optional so that old files still work.
938                 int const lineno = symbolslex.lineNumber();
939                 bool breakout = false;
940                 if (symbolslex.next(true)) {
941                         if (symbolslex.lineNumber() != lineno) {
942                                 // line in old format without mathcommand and mathpreamble
943                                 getNextToken = false;
944                         } else {
945                                 info.mathcommand = symbolslex.getDocString();
946                                 if (symbolslex.next(true)) {
947                                         if (symbolslex.lineNumber() != lineno) {
948                                                 // line in new format with mathcommand only
949                                                 getNextToken = false;
950                                         } else {
951                                                 // line in new format with mathcommand and mathpreamble
952                                                 info.mathpreamble = symbolslex.getString();
953                                         }
954                                 } else
955                                         breakout = true;
956                         }
957                 } else {
958                         breakout = true;
959                 }
960
961                 // backward compatibility
962                 if (info.mathpreamble == "esintoramsmath")
963                         info.mathpreamble = "esint|amsmath";
964
965                 if (!info.textpreamble.empty())
966                         if (info.textpreamble[0] != '\\')
967                                 info.flags |= CharInfoTextFeature;
968                 if (!info.mathpreamble.empty())
969                         if (info.mathpreamble[0] != '\\')
970                                 info.flags |= CharInfoMathFeature;
971
972                 LYXERR(Debug::INFO, "Read unicode symbol " << symbol << " '"
973                         << to_utf8(info.textcommand) << "' '" << info.textpreamble
974                         << " '" << info.textfeature() << ' ' << info.textnotermination()
975                         << ' ' << to_utf8(info.mathcommand) << "' '" << info.mathpreamble
976                         << "' " << info.mathfeature() << ' ' << info.mathnotermination()
977                         << ' ' << info.combining() << ' ' << info.force());
978
979                 // we assume that at least one command is nonempty when using unicodesymbols
980                 if (!info.textcommand.empty() || !info.mathcommand.empty())
981                         unicodesymbols[symbol] = info;
982
983                 if (breakout)
984                         break;
985         }
986
987         // Now read the encodings
988         enum {
989                 et_encoding = 1,
990                 et_end
991         };
992
993         LexerKeyword encodingtags[] = {
994                 { "encoding", et_encoding },
995                 { "end", et_end }
996         };
997
998         Lexer lex(encodingtags);
999         lex.setFile(encfile);
1000         lex.setContext("Encodings::read");
1001         while (lex.isOK()) {
1002                 switch (lex.lex()) {
1003                 case et_encoding:
1004                 {
1005                         lex.next();
1006                         string const name = lex.getString();
1007                         lex.next();
1008                         string const latexname = lex.getString();
1009                         lex.next();
1010                         string const guiname = lex.getString();
1011                         lex.next();
1012                         string const iconvname = lex.getString();
1013                         lex.next();
1014                         string const width = lex.getString();
1015                         bool fixedwidth = false;
1016                         bool unsafe = false;
1017                         if (width == "fixed")
1018                                 fixedwidth = true;
1019                         else if (width == "variable")
1020                                 fixedwidth = false;
1021                         else if (width == "variableunsafe") {
1022                                 fixedwidth = false;
1023                                 unsafe = true;
1024                         }
1025                         else
1026                                 lex.printError("Unknown width");
1027
1028                         lex.next();
1029                         string const p = lex.getString();
1030                         Encoding::Package package = Encoding::none;
1031                         if (p == "none")
1032                                 package = Encoding::none;
1033                         else if (p == "inputenc")
1034                                 package = Encoding::inputenc;
1035                         else if (p == "CJK")
1036                                 package = Encoding::CJK;
1037                         else if (p == "japanese")
1038                                 package = Encoding::japanese;
1039                         else
1040                                 lex.printError("Unknown package");
1041
1042                         LYXERR(Debug::INFO, "Reading encoding " << name);
1043                         encodinglist[name] = Encoding(name, latexname,
1044                                 guiname, iconvname, fixedwidth, unsafe,
1045                                 package);
1046
1047                         if (lex.lex() != et_end)
1048                                 lex.printError("Missing end");
1049                         break;
1050                 }
1051                 case et_end:
1052                         lex.printError("Misplaced end");
1053                         break;
1054                 case Lexer::LEX_FEOF:
1055                         break;
1056                 default:
1057                         lex.printError("Unknown tag");
1058                         break;
1059                 }
1060         }
1061 }
1062
1063
1064 } // namespace lyx