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