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