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