]> git.lyx.org Git - lyx.git/blob - src/Encoding.cpp
Set language to OS input language when moving cursor
[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/mutex.h"
23 #include "support/textutils.h"
24 #include "support/unicode.h"
25
26 #include <algorithm>
27 #include <cstdint>
28 #include <iterator>
29 #include <sstream>
30
31 using namespace std;
32 using namespace lyx::support;
33
34 namespace lyx {
35
36 int const Encoding::any = -1;
37
38 Encodings encodings;
39
40 Encodings::MathCommandSet Encodings::mathcmd;
41 Encodings::TextCommandSet Encodings::textcmd;
42 Encodings::MathSymbolSet  Encodings::mathsym;
43
44 namespace {
45
46 typedef map<char_type, CharInfo> CharInfoMap;
47 CharInfoMap unicodesymbols;
48
49 typedef set<char_type> CharSet;
50 typedef map<string, CharSet> CharSetMap;
51 CharSet forced;
52 CharSetMap forcedselected;
53
54 typedef set<char_type> MathAlphaSet;
55 MathAlphaSet mathalpha;
56
57
58 /// The highest code point in UCS4 encoding (1<<20 + 1<<16)
59 char_type const max_ucs4 = 0x110000;
60
61 } // namespace
62
63
64 EncodingException::EncodingException(char_type c)
65         : failed_char(c), par_id(0), pos(0)
66 {
67 }
68
69
70 const char * EncodingException::what() const throw()
71 {
72         return "Could not find LaTeX command for a character";
73 }
74
75
76 CharInfo::CharInfo(
77         docstring const & textcommand, docstring const & mathcommand,
78         std::string const & textpreamble, std::string const & mathpreamble,
79         std::string const & tipashortcut, unsigned int flags)
80         : textcommand_(textcommand), mathcommand_(mathcommand),
81           textpreamble_(textpreamble), mathpreamble_(mathpreamble),
82           tipashortcut_(tipashortcut), flags_(flags)
83 {
84 }
85
86
87 Encoding::Encoding(string const & n, string const & l, string const & g,
88                    string const & i, bool f, bool u, Encoding::Package p)
89         : name_(n), latexName_(l), guiName_(g), iconvName_(i), fixedwidth_(f),
90           unsafe_(u), forced_(&forcedselected[n]), package_(p)
91 {
92         if (n == "ascii") {
93                 // ASCII can encode 128 code points and nothing else
94                 start_encodable_ = 128;
95                 complete_ = true;
96         } else if (i == "UTF-8") {
97                 // UTF8 can encode all UCS4 code points
98                 start_encodable_ = max_ucs4;
99                 complete_ = true;
100         } else {
101                 start_encodable_ = 0;
102                 complete_ = false;
103         }
104 }
105
106
107 void Encoding::init() const
108 {
109         // Since the the constructor is the only method which sets complete_
110         // to false the test for complete_ is thread-safe without mutex.
111         if (complete_)
112                 return;
113
114         static Mutex mutex;
115         Mutex::Locker lock(&mutex);
116
117         // We need to test again for complete_, since another thread could
118         // have set it to true while we were waiting for the lock and we must
119         // not modify an encoding which is already complete.
120         if (complete_)
121                 return;
122
123         // We do not make any member mutable  so that it can be easily verified
124         // that all const methods are thread-safe: init() is the only const
125         // method which changes complete_, encodable_ and start_encodable_, and
126         // it uses a mutex to ensure thread-safety.
127         CharSet & encodable = const_cast<Encoding *>(this)->encodable_;
128         char_type & start_encodable = const_cast<Encoding *>(this)->start_encodable_;
129
130         start_encodable = 0;
131         // temporarily switch off lyxerr, since we will generate iconv errors
132         lyxerr.disable();
133         if (fixedwidth_) {
134                 // We do not need to check all UCS4 code points, it is enough
135                 // if we check all 256 code points of this encoding.
136                 for (unsigned short j = 0; j < 256; ++j) {
137                         char const c = char(j);
138                         vector<char_type> const ucs4 = eightbit_to_ucs4(&c, 1, iconvName_);
139                         if (ucs4.size() != 1)
140                                 continue;
141                         char_type const uc = ucs4[0];
142                         CharInfoMap::const_iterator const it = unicodesymbols.find(uc);
143                         if (it == unicodesymbols.end())
144                                 encodable.insert(uc);
145                         else if (!it->second.force()) {
146                                 if (forced_->empty() || forced_->find(uc) == forced_->end())
147                                         encodable.insert(uc);
148                         }
149                 }
150         } else {
151                 // We do not know how many code points this encoding has, and
152                 // they do not have a direct representation as a single byte,
153                 // therefore we need to check all UCS4 code points.
154                 // This is expensive!
155                 for (char_type c = 0; c < max_ucs4; ++c) {
156                         vector<char> const eightbit = ucs4_to_eightbit(&c, 1, iconvName_);
157                         if (!eightbit.empty()) {
158                                 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
159                                 if (it == unicodesymbols.end())
160                                         encodable.insert(c);
161                                 else if (!it->second.force()) {
162                                         if (forced_->empty() || forced_->find(c) == forced_->end())
163                                                 encodable.insert(c);
164                                 }
165                         }
166                 }
167         }
168         lyxerr.enable();
169         CharSet::iterator it = encodable.find(start_encodable);
170         while (it != encodable.end()) {
171                 encodable.erase(it);
172                 ++start_encodable;
173                 it = encodable.find(start_encodable);
174         }
175         const_cast<Encoding *>(this)->complete_ = true;
176 }
177
178
179 bool Encoding::isForced(char_type c) const
180 {
181         if (!forced.empty() && forced.find(c) != forced.end())
182                 return true;
183         return !forced_->empty() && forced_->find(c) != forced_->end();
184 }
185
186
187 bool Encoding::encodable(char_type c) const
188 {
189         // assure the used encoding is properly initialized
190         init();
191         if (iconvName_ == "UTF-8" && package_ == none)
192                 return true;
193         // platex does not load inputenc: force conversion of supported characters
194         if (package_ == Encoding::japanese
195             && ((0xb7 <= c && c <= 0x05ff) // Latin-1 Supplement ... Hebrew
196                         || (0x1d00 <= c && c <= 0x218f) // Phonetic Extensions ... Number Forms
197                         || (0x2193 <= c && c <= 0x2aff) // Arrows ... Supplemental Mathematical Operators
198                         || (0xfb00 <= c && c <= 0xfb4f) // Alphabetic Presentation Forms
199                         || (0x1d400 <= c && c <= 0x1d7ff))) // Mathematical Alphanumeric Symbols
200                 return false;
201         if (c < start_encodable_ && !isForced(c))
202                 return true;
203         if (encodable_.find(c) != encodable_.end())
204                 return true;
205         return false;
206 }
207
208
209 pair<docstring, bool> Encoding::latexChar(char_type c) const
210 {
211         if (encodable(c))
212                 return make_pair(docstring(1, c), false);
213
214         // c cannot (or should not) be encoded in this encoding
215         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
216         if (it == unicodesymbols.end())
217                 throw EncodingException(c);
218         // at least one of mathcommand and textcommand is nonempty
219         if (it->second.textcommand().empty())
220                 return make_pair(
221                         "\\ensuremath{" + it->second.mathcommand() + '}', false);
222         return make_pair(it->second.textcommand(), !it->second.textnotermination());
223 }
224
225
226 pair<docstring, docstring> Encoding::latexString(docstring const & input, bool dryrun) const
227 {
228         docstring result;
229         docstring uncodable;
230         bool terminate = false;
231         for (size_t n = 0; n < input.size(); ++n) {
232                 char_type const c = input[n];
233                 try {
234                         pair<docstring, bool> latex_char = latexChar(c);
235                         docstring const latex = latex_char.first;
236                         if (terminate && !prefixIs(latex, '\\')
237                             && !prefixIs(latex, '{')
238                             && !prefixIs(latex, '}')) {
239                                         // Prevent eating of a following
240                                         // space or command corruption by
241                                         // following characters
242                                         if (latex == " ")
243                                                 result += "{}";
244                                         else
245                                                 result += " ";
246                                 }
247                         result += latex;
248                         terminate = latex_char.second;
249                 } catch (EncodingException & /* e */) {
250                         LYXERR0("Uncodable character <" << docstring(1, c) 
251                                         << "> in latexString!");
252                         if (dryrun) {
253                                 result += "<" + _("LyX Warning: ")
254                                            + _("uncodable character") + " '";
255                                 result += docstring(1, input[n]);
256                                 result += "'>";
257                         } else
258                                 uncodable += input[n];
259                 }
260         }
261         return make_pair(result, uncodable);
262 }
263
264
265 vector<char_type> Encoding::symbolsList() const
266 {
267         // assure the used encoding is properly initialized
268         init();
269
270         // first all those below start_encodable_
271         vector<char_type> symbols;
272         for (char_type c = 0; c < start_encodable_; ++c)
273                 symbols.push_back(c);
274         // add all encodable characters
275         copy(encodable_.begin(), encodable_.end(), back_inserter(symbols));
276         // now the ones from the unicodesymbols file that are not already there
277         for (pair<char_type, CharInfo> const & elem : unicodesymbols) {
278                 if (find(symbols.begin(), symbols.end(), elem.first) == symbols.end())
279                         symbols.push_back(elem.first);
280         }
281         // finally, sort the vector
282         sort(symbols.begin(), symbols.end());
283         return symbols;
284 }
285
286
287 bool Encodings::latexMathChar(char_type c, bool mathmode,
288                         Encoding const * encoding, docstring & command,
289                         bool & needsTermination)
290 {
291         command = empty_docstring();
292         if (encoding)
293                 if (encoding->encodable(c))
294                         command = docstring(1, c);
295         needsTermination = false;
296
297         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
298         if (it == unicodesymbols.end()) {
299                 if (!encoding || command.empty())
300                         throw EncodingException(c);
301                 if (mathmode)
302                         addMathSym(c);
303                 return false;
304         }
305         // at least one of mathcommand and textcommand is nonempty
306         bool use_math = (mathmode && !it->second.mathcommand().empty()) ||
307                         (!mathmode && it->second.textcommand().empty());
308         if (use_math) {
309                 command = it->second.mathcommand();
310                 needsTermination = !it->second.mathnotermination();
311                 addMathCmd(c);
312         } else {
313                 if (!encoding || command.empty()) {
314                         command = it->second.textcommand();
315                         needsTermination = !it->second.textnotermination();
316                 }
317                 if (mathmode)
318                         addMathSym(c);
319                 else
320                         addTextCmd(c);
321         }
322         return use_math;
323 }
324
325
326 char_type Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
327                 bool & combining, bool & needsTermination, set<string> * req)
328 {
329         CharInfoMap::const_iterator const end = unicodesymbols.end();
330         CharInfoMap::const_iterator it = unicodesymbols.begin();
331         for (combining = false; it != end; ++it) {
332                 if (it->second.deprecated())
333                         continue;
334                 docstring const math = it->second.mathcommand();
335                 docstring const text = it->second.textcommand();
336                 if ((cmdtype & MATH_CMD) && math == cmd) {
337                         combining = it->second.combining();
338                         needsTermination = !it->second.mathnotermination();
339                         if (req && it->second.mathfeature() &&
340                             !it->second.mathpreamble().empty())
341                                 req->insert(it->second.mathpreamble());
342                         return it->first;
343                 }
344                 if ((cmdtype & TEXT_CMD) && text == cmd) {
345                         combining = it->second.combining();
346                         needsTermination = !it->second.textnotermination();
347                         if (req && it->second.textfeature() &&
348                             !it->second.textpreamble().empty())
349                                 req->insert(it->second.textpreamble());
350                         return it->first;
351                 }
352         }
353         needsTermination = false;
354         return 0;
355 }
356
357
358 docstring Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
359                 bool & needsTermination, docstring & rem, set<string> * req)
360 {
361         needsTermination = false;
362         rem = empty_docstring();
363         bool const mathmode = cmdtype & MATH_CMD;
364         bool const textmode = cmdtype & TEXT_CMD;
365         docstring symbols;
366         size_t const cmdend = cmd.size();
367         size_t prefix = 0;
368         CharInfoMap::const_iterator const uniend = unicodesymbols.end();
369         for (size_t i = 0, j = 0; j < cmdend; ++j) {
370                 // Also get the char after a backslash
371                 if (j + 1 < cmdend && cmd[j] == '\\') {
372                         ++j;
373                         prefix = 1;
374                         // Detect things like \=*{e} as well
375                         if (j + 3 < cmdend && cmd[j+1] == '*' &&
376                             cmd[j+2] == '{') {
377                                 ++j;
378                                 prefix = 2;
379                         }
380                 }
381                 // position of the last character before a possible macro
382                 // argument
383                 size_t m = j;
384                 // If a macro argument follows, get it, too
385                 // Do it here only for single character commands. Other
386                 // combining commands need this too, but they are handled in
387                 // the loop below for performance reasons.
388                 if (j + 1 < cmdend && cmd[j + 1] == '{') {
389                         size_t k = j + 1;
390                         int count = 1;
391                         while (k < cmdend && count) {
392                                 k = cmd.find_first_of(from_ascii("{}"), k + 1);
393                                 // braces may not be balanced
394                                 if (k == docstring::npos)
395                                         break;
396                                 if (cmd[k] == '{')
397                                         ++count;
398                                 else
399                                         --count;
400                         }
401                         if (k != docstring::npos)
402                                 j = k;
403                 } else if (m + 1 < cmdend && isAlphaASCII(cmd[m])) {
404                         while (m + 2 < cmdend && isAlphaASCII(cmd[m+1]))
405                                 m++;
406                 }
407                 // Start with this substring and try augmenting it when it is
408                 // the prefix of some command in the unicodesymbols file
409                 docstring subcmd = cmd.substr(i, j - i + 1);
410
411                 CharInfoMap::const_iterator it = unicodesymbols.begin();
412                 // First part of subcmd which might be a combining character
413                 docstring combcmd = (m == j) ? docstring() : cmd.substr(i, m - i + 1);
414                 // The combining character of combcmd if it exists
415                 CharInfoMap::const_iterator combining = uniend;
416                 size_t unicmd_size = 0;
417                 char_type c = 0;
418                 for (; it != uniend; ++it) {
419                         if (it->second.deprecated())
420                                 continue;
421                         docstring const math = mathmode ? it->second.mathcommand()
422                                                         : docstring();
423                         docstring const text = textmode ? it->second.textcommand()
424                                                         : docstring();
425                         if (!combcmd.empty() && it->second.combining() &&
426                             (math == combcmd || text == combcmd))
427                                 combining = it;
428                         size_t cur_size = max(math.size(), text.size());
429                         // The current math or text unicode command cannot
430                         // match, or we already matched a longer one
431                         if (cur_size < subcmd.size() || cur_size <= unicmd_size)
432                                 continue;
433
434                         docstring tmp = subcmd;
435                         size_t k = j;
436                         while (prefixIs(math, tmp) || prefixIs(text, tmp)) {
437                                 ++k;
438                                 if (k >= cmdend || cur_size <= tmp.size())
439                                         break;
440                                 tmp += cmd[k];
441                         }
442                         // No match
443                         if (k == j)
444                                 continue;
445
446                         // The last added char caused a mismatch, because
447                         // we didn't exhaust the chars in cmd and didn't
448                         // exceed the maximum size of the current unicmd
449                         if (k < cmdend && cur_size > tmp.size())
450                                 tmp.resize(tmp.size() - 1);
451
452                         // If this is an exact match, we found a (longer)
453                         // matching entry in the unicodesymbols file.
454                         if (math != tmp && text != tmp)
455                                 continue;
456                         // If we found a combining command, we need to append
457                         // the macro argument if this has not been done above.
458                         if (tmp == combcmd && combining != uniend &&
459                             k < cmdend && cmd[k] == '{') {
460                                 size_t l = k;
461                                 int count = 1;
462                                 while (l < cmdend && count) {
463                                         l = cmd.find_first_of(from_ascii("{}"), l + 1);
464                                         // braces may not be balanced
465                                         if (l == docstring::npos)
466                                                 break;
467                                         if (cmd[l] == '{')
468                                                 ++count;
469                                         else
470                                                 --count;
471                                 }
472                                 if (l != docstring::npos) {
473                                         j = l;
474                                         subcmd = cmd.substr(i, j - i + 1);
475                                 }
476                         }
477                         // If the entry doesn't start with '\', we take note
478                         // of the match and continue (this is not a ultimate
479                         // acceptance, as some other entry may match a longer
480                         // portion of the cmd string). However, if the entry
481                         // does start with '\', we accept the match only if
482                         // this is a valid macro, i.e., either it is a single
483                         // (nonletter) char macro, or nothing else follows,
484                         // or what follows is a nonletter char, or the last
485                         // character is a }.
486                         else if (tmp[0] != '\\'
487                                    || (tmp.size() == prefix + 1 &&
488                                        !isAlphaASCII(tmp[1]) &&
489                                        (prefix == 1 || !isAlphaASCII(tmp[2])))
490                                    || k == cmdend
491                                    || !isAlphaASCII(cmd[k])
492                                    || tmp[tmp.size() - 1] == '}'
493                                  ) {
494                                 c = it->first;
495                                 j = k - 1;
496                                 i = j + 1;
497                                 unicmd_size = cur_size;
498                                 if (math == tmp)
499                                         needsTermination = !it->second.mathnotermination();
500                                 else
501                                         needsTermination = !it->second.textnotermination();
502                                 if (req) {
503                                         if (math == tmp && it->second.mathfeature() &&
504                                             !it->second.mathpreamble().empty())
505                                                 req->insert(it->second.mathpreamble());
506                                         if (text == tmp && it->second.textfeature() &&
507                                             !it->second.textpreamble().empty())
508                                                 req->insert(it->second.textpreamble());
509                                 }
510                         }
511                 }
512                 if (unicmd_size)
513                         symbols += c;
514                 else if (combining != uniend &&
515                          prefixIs(subcmd, combcmd + '{')) {
516                         // We know that subcmd starts with combcmd and
517                         // contains an argument in braces.
518                         docstring const arg = subcmd.substr(
519                                 combcmd.length() + 1,
520                                 subcmd.length() - combcmd.length() - 2);
521                         // If arg is a single character we can construct a
522                         // combining sequence.
523                         char_type a;
524                         bool argcomb = false;
525                         if (arg.size() == 1 && isAlnumASCII(arg[0]))
526                                 a = arg[0];
527                         else {
528                                 // Use the version of fromLaTeXCommand() that
529                                 // parses only one command, since we cannot
530                                 // use more than one character.
531                                 bool dummy = false;
532                                 set<string> r;
533                                 a = fromLaTeXCommand(arg, cmdtype, argcomb,
534                                                      dummy, &r);
535                                 if (a && req && !argcomb)
536                                         req->insert(r.begin(), r.end());
537                         }
538                         if (a && !argcomb) {
539                                 // In unicode the combining character comes
540                                 // after its base
541                                 symbols += a;
542                                 symbols += combining->first;
543                                 i = j + 1;
544                                 unicmd_size = 2;
545                         }
546                 }
547                 if (j + 1 == cmdend && !unicmd_size) {
548                         // No luck. Return what remains
549                         rem = cmd.substr(i);
550                         if (needsTermination && !rem.empty()) {
551                                 if (rem.substr(0, 2) == "{}") {
552                                         rem = rem.substr(2);
553                                         needsTermination = false;
554                                 } else if (rem[0] == ' ') {
555                                         needsTermination = false;
556                                         // LaTeX would swallow all spaces
557                                         rem = ltrim(rem);
558                                 }
559                         }
560                 }
561         }
562         return symbols;
563 }
564
565
566 CharInfo const & Encodings::unicodeCharInfo(char_type c)
567 {
568         static CharInfo empty;
569         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
570         return it != unicodesymbols.end() ? it->second : empty;
571 }
572
573
574 bool Encodings::isCombiningChar(char_type c)
575 {
576         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
577         if (it != unicodesymbols.end())
578                 return it->second.combining();
579         return false;
580 }
581
582
583 string const Encodings::TIPAShortcut(char_type c)
584 {
585         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
586         if (it != unicodesymbols.end())
587                 return it->second.tipashortcut();
588         return string();
589 }
590
591
592 string const Encodings::isKnownScriptChar(char_type const c)
593 {
594         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
595
596         if (it == unicodesymbols.end())
597                 return string();
598         // FIXME: parse complex textpreamble (may be list or alternatives,
599         //                e.g., "subscript,textgreek" or "textcomp|textgreek")
600         if (it->second.textpreamble() == "textgreek"
601                 || it->second.textpreamble() == "textcyrillic")
602                 return it->second.textpreamble();
603         return string();
604 }
605
606
607 bool Encodings::fontencSupportsScript(string const & fontenc, string const & script)
608 {
609         if (script == "textgreek")
610                 return (fontenc == "LGR" || fontenc == "TU");
611         if (script == "textcyrillic")
612                 return (fontenc == "T2A" || fontenc == "T2B" || fontenc == "T2C"
613                                 || fontenc == "X2" || fontenc == "TU");
614         return false;
615 }
616
617
618 bool Encodings::isMathAlpha(char_type c)
619 {
620         return mathalpha.count(c);
621 }
622
623
624 bool Encodings::isUnicodeTextOnly(char_type c)
625 {
626         if (isASCII(c) || isMathAlpha(c))
627                 return false;
628
629         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
630         return it == unicodesymbols.end() || it->second.mathcommand().empty();
631 }
632
633
634 Encoding const *
635 Encodings::fromLyXName(string const & name, bool allowUnsafe) const
636 {
637         EncodingList::const_iterator const it = encodinglist.find(name);
638         if (it == encodinglist.end())
639                 return 0;
640         if (!allowUnsafe && it->second.unsafe())
641                 return 0;
642         return &it->second;
643 }
644
645
646 Encoding const *
647 Encodings::fromLaTeXName(string const & n, int const & p, bool allowUnsafe) const
648 {
649         string name = n;
650         // FIXME: if we have to test for too many of these synonyms,
651         // we should instead extend the format of lib/encodings
652         if (n == "ansinew")
653                 name = "cp1252";
654
655         // We don't use find_if because it makes copies of the pairs in
656         // the map.
657         // This linear search is OK since we don't have many encodings.
658         // Users could even optimize it by putting the encodings they use
659         // most at the top of lib/encodings.
660         EncodingList::const_iterator const end = encodinglist.end();
661         for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
662                 if ((it->second.latexName() == name) && (it->second.package() & p)
663                                 && (!it->second.unsafe() || allowUnsafe))
664                         return &it->second;
665         return 0;
666 }
667
668
669 Encoding const *
670 Encodings::fromIconvName(string const & n, int const & p, bool allowUnsafe) const
671 {
672         EncodingList::const_iterator const end = encodinglist.end();
673         for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
674                 if ((it->second.iconvName() == n) && (it->second.package() & p)
675                                 && (!it->second.unsafe() || allowUnsafe))
676                         return &it->second;
677         return 0;
678 }
679
680
681 Encodings::Encodings()
682 {}
683
684
685 void Encodings::read(FileName const & encfile, FileName const & symbolsfile)
686 {
687         // We must read the symbolsfile first, because the Encoding
688         // constructor depends on it.
689         CharSetMap forcednotselected;
690         Lexer symbolslex;
691         symbolslex.setFile(symbolsfile);
692         bool getNextToken = true;
693         while (symbolslex.isOK()) {
694                 char_type symbol;
695
696                 if (getNextToken) {
697                         if (!symbolslex.next(true))
698                                 break;
699                 } else
700                         getNextToken = true;
701
702                 istringstream is(symbolslex.getString());
703                 // reading symbol directly does not work if
704                 // char_type == wchar_t.
705                 uint32_t tmp;
706                 if(!(is >> hex >> tmp))
707                         break;
708                 symbol = tmp;
709
710                 if (!symbolslex.next(true))
711                         break;
712                 docstring textcommand = symbolslex.getDocString();
713                 if (!symbolslex.next(true))
714                         break;
715                 string textpreamble = symbolslex.getString();
716                 if (!symbolslex.next(true))
717                         break;
718                 string sflags = symbolslex.getString();
719
720                 string tipashortcut;
721                 int flags = 0;
722
723                 if (suffixIs(textcommand, '}'))
724                         flags |= CharInfoTextNoTermination;
725                 while (!sflags.empty()) {
726                         string flag;
727                         sflags = split(sflags, flag, ',');
728                         if (flag == "combining") {
729                                 flags |= CharInfoCombining;
730                         } else if (flag == "force") {
731                                 flags |= CharInfoForce;
732                                 forced.insert(symbol);
733                         } else if (prefixIs(flag, "force=")) {
734                                 vector<string> encs =
735                                         getVectorFromString(flag.substr(6), ";");
736                                 for (size_t i = 0; i < encs.size(); ++i)
737                                         forcedselected[encs[i]].insert(symbol);
738                                 flags |= CharInfoForceSelected;
739                         } else if (prefixIs(flag, "force!=")) {
740                                 vector<string> encs =
741                                         getVectorFromString(flag.substr(7), ";");
742                                 for (size_t i = 0; i < encs.size(); ++i)
743                                         forcednotselected[encs[i]].insert(symbol);
744                                 flags |= CharInfoForceSelected;
745                         } else if (flag == "mathalpha") {
746                                 mathalpha.insert(symbol);
747                         } else if (flag == "notermination=text") {
748                                 flags |= CharInfoTextNoTermination;
749                         } else if (flag == "notermination=math") {
750                                 flags |= CharInfoMathNoTermination;
751                         } else if (flag == "notermination=both") {
752                                 flags |= CharInfoTextNoTermination;
753                                 flags |= CharInfoMathNoTermination;
754                         } else if (flag == "notermination=none") {
755                                 flags &= ~CharInfoTextNoTermination;
756                                 flags &= ~CharInfoMathNoTermination;
757                         } else if (contains(flag, "tipashortcut=")) {
758                                 tipashortcut = split(flag, '=');
759                         } else if (flag == "deprecated") {
760                                 flags |= CharInfoDeprecated;
761                         } else {
762                                 lyxerr << "Ignoring unknown flag `" << flag
763                                        << "' for symbol `0x"
764                                        << hex << symbol << dec
765                                        << "'." << endl;
766                         }
767                 }
768                 // mathcommand and mathpreamble have been added for 1.6.0.
769                 // make them optional so that old files still work.
770                 int const lineno = symbolslex.lineNumber();
771                 bool breakout = false;
772                 docstring mathcommand;
773                 string mathpreamble;
774                 if (symbolslex.next(true)) {
775                         if (symbolslex.lineNumber() != lineno) {
776                                 // line in old format without mathcommand and mathpreamble
777                                 getNextToken = false;
778                         } else {
779                                 mathcommand = symbolslex.getDocString();
780                                 if (suffixIs(mathcommand, '}'))
781                                         flags |= CharInfoMathNoTermination;
782                                 if (symbolslex.next(true)) {
783                                         if (symbolslex.lineNumber() != lineno) {
784                                                 // line in new format with mathcommand only
785                                                 getNextToken = false;
786                                         } else {
787                                                 // line in new format with mathcommand and mathpreamble
788                                                 mathpreamble = symbolslex.getString();
789                                         }
790                                 } else
791                                         breakout = true;
792                         }
793                 } else {
794                         breakout = true;
795                 }
796
797                 // backward compatibility
798                 if (mathpreamble == "esintoramsmath")
799                         mathpreamble = "esint|amsmath";
800
801                 if (!textpreamble.empty())
802                         if (textpreamble[0] != '\\')
803                                 flags |= CharInfoTextFeature;
804                 if (!mathpreamble.empty())
805                         if (mathpreamble[0] != '\\')
806                                 flags |= CharInfoMathFeature;
807
808                 CharInfo info = CharInfo(
809                         textcommand, mathcommand,
810                         textpreamble, mathpreamble,
811                         tipashortcut, flags);
812                 LYXERR(Debug::INFO, "Read unicode symbol " << symbol << " '"
813                            << to_utf8(info.textcommand()) << "' '" << info.textpreamble()
814                            << " '" << info.textfeature() << ' ' << info.textnotermination()
815                            << ' ' << to_utf8(info.mathcommand()) << "' '" << info.mathpreamble()
816                            << "' " << info.mathfeature() << ' ' << info.mathnotermination()
817                            << ' ' << info.combining() << ' ' << info.force()
818                            << ' ' << info.forceselected());
819
820                 // we assume that at least one command is nonempty when using unicodesymbols
821                 if (info.isUnicodeSymbol()) {
822                         unicodesymbols[symbol] = info;
823                 }
824
825                 if (breakout)
826                         break;
827         }
828
829         // Now read the encodings
830         enum {
831                 et_encoding = 1,
832                 et_end
833         };
834
835         LexerKeyword encodingtags[] = {
836                 { "encoding", et_encoding },
837                 { "end", et_end }
838         };
839
840         Lexer lex(encodingtags);
841         lex.setFile(encfile);
842         lex.setContext("Encodings::read");
843         while (lex.isOK()) {
844                 switch (lex.lex()) {
845                 case et_encoding:
846                 {
847                         lex.next();
848                         string const name = lex.getString();
849                         lex.next();
850                         string const latexname = lex.getString();
851                         lex.next();
852                         string const guiname = lex.getString();
853                         lex.next();
854                         string const iconvname = lex.getString();
855                         lex.next();
856                         string const width = lex.getString();
857                         bool fixedwidth = false;
858                         bool unsafe = false;
859                         if (width == "fixed")
860                                 fixedwidth = true;
861                         else if (width == "variable")
862                                 fixedwidth = false;
863                         else if (width == "variableunsafe") {
864                                 fixedwidth = false;
865                                 unsafe = true;
866                         }
867                         else
868                                 lex.printError("Unknown width");
869
870                         lex.next();
871                         string const p = lex.getString();
872                         Encoding::Package package = Encoding::none;
873                         if (p == "none")
874                                 package = Encoding::none;
875                         else if (p == "inputenc")
876                                 package = Encoding::inputenc;
877                         else if (p == "CJK")
878                                 package = Encoding::CJK;
879                         else if (p == "japanese")
880                                 package = Encoding::japanese;
881                         else
882                                 lex.printError("Unknown package");
883
884                         LYXERR(Debug::INFO, "Reading encoding " << name);
885                         encodinglist[name] = Encoding(name, latexname,
886                                 guiname, iconvname, fixedwidth, unsafe,
887                                 package);
888
889                         if (lex.lex() != et_end)
890                                 lex.printError("Missing end");
891                         break;
892                 }
893                 case et_end:
894                         lex.printError("Misplaced end");
895                         break;
896                 case Lexer::LEX_FEOF:
897                         break;
898                 default:
899                         lex.printError("Unknown tag");
900                         break;
901                 }
902         }
903
904         // Move all information from forcednotselected to forcedselected
905         for (CharSetMap::const_iterator it1 = forcednotselected.begin(); it1 != forcednotselected.end(); ++it1) {
906                 for (CharSetMap::iterator it2 = forcedselected.begin(); it2 != forcedselected.end(); ++it2) {
907                         if (it2->first != it1->first)
908                                 it2->second.insert(it1->second.begin(), it1->second.end());
909                 }
910         }
911
912 }
913
914
915 } // namespace lyx