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