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