]> git.lyx.org Git - lyx.git/blob - src/Encoding.cpp
Make InsetSpecialChar names more consistent
[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 <sstream>
29 #include <algorithm>
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 anon
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
192         if (iconvName_ == "UTF-8" && package_ == none)
193                 return true;
194         if (c < start_encodable_ && !isForced(c))
195                 return true;
196         if (encodable_.find(c) != encodable_.end())
197                 return true;
198         return false;
199 }
200
201
202 pair<docstring, bool> Encoding::latexChar(char_type c) const
203 {
204         if (encodable(c))
205                 return make_pair(docstring(1, c), false);
206
207         // c cannot (or should not) be encoded in this encoding
208         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
209         if (it == unicodesymbols.end())
210                 throw EncodingException(c);
211         // at least one of mathcommand and textcommand is nonempty
212         if (it->second.textcommand().empty())
213                 return make_pair(
214                         "\\ensuremath{" + it->second.mathcommand() + '}', false);
215         return make_pair(it->second.textcommand(), !it->second.textnotermination());
216 }
217
218
219 pair<docstring, docstring> Encoding::latexString(docstring const & input, bool dryrun) const
220 {
221         docstring result;
222         docstring uncodable;
223         bool terminate = false;
224         for (size_t n = 0; n < input.size(); ++n) {
225                 try {
226                         char_type const c = input[n];
227                         pair<docstring, bool> latex_char = latexChar(c);
228                         docstring const latex = latex_char.first;
229                         if (terminate && !prefixIs(latex, '\\')
230                             && !prefixIs(latex, '{')
231                             && !prefixIs(latex, '}')) {
232                                         // Prevent eating of a following
233                                         // space or command corruption by
234                                         // following characters
235                                         if (latex == " ")
236                                                 result += "{}";
237                                         else
238                                                 result += " ";
239                                 }
240                         result += latex;
241                         terminate = latex_char.second;
242                 } catch (EncodingException & /* e */) {
243                         LYXERR0("Uncodable character in latexString!");
244                         if (dryrun) {
245                                 result += "<" + _("LyX Warning: ")
246                                            + _("uncodable character") + " '";
247                                 result += docstring(1, input[n]);
248                                 result += "'>";
249                         } else
250                                 uncodable += input[n];
251                 }
252         }
253         return make_pair(result, uncodable);
254 }
255
256
257 vector<char_type> Encoding::symbolsList() const
258 {
259         // assure the used encoding is properly initialized
260         init();
261
262         // first all encodable characters
263         vector<char_type> symbols(encodable_.begin(), encodable_.end());
264         // add those below start_encodable_
265         for (char_type c = 0; c < start_encodable_; ++c)
266                 symbols.push_back(c);
267         // now the ones from the unicodesymbols file
268         CharInfoMap::const_iterator const end = unicodesymbols.end();
269         CharInfoMap::const_iterator it = unicodesymbols.begin();
270         for (; it != end; ++it)
271                 symbols.push_back(it->first);
272         return symbols;
273 }
274
275
276 bool Encodings::latexMathChar(char_type c, bool mathmode,
277                         Encoding const * encoding, docstring & command,
278                         bool & needsTermination)
279 {
280         command = empty_docstring();
281         if (encoding)
282                 if (encoding->encodable(c))
283                         command = docstring(1, c);
284         needsTermination = false;
285
286         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
287         if (it == unicodesymbols.end()) {
288                 if (!encoding || command.empty())
289                         throw EncodingException(c);
290                 if (mathmode)
291                         addMathSym(c);
292                 return false;
293         }
294         // at least one of mathcommand and textcommand is nonempty
295         bool use_math = (mathmode && !it->second.mathcommand().empty()) ||
296                         (!mathmode && it->second.textcommand().empty());
297         if (use_math) {
298                 command = it->second.mathcommand();
299                 needsTermination = !it->second.mathnotermination();
300                 addMathCmd(c);
301         } else {
302                 if (!encoding || command.empty()) {
303                         command = it->second.textcommand();
304                         needsTermination = !it->second.textnotermination();
305                         addTextCmd(c);
306                 }
307                 if (mathmode)
308                         addMathSym(c);
309         }
310         return use_math;
311 }
312
313
314 char_type Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
315                 bool & combining, bool & needsTermination, set<string> * req)
316 {
317         CharInfoMap::const_iterator const end = unicodesymbols.end();
318         CharInfoMap::const_iterator it = unicodesymbols.begin();
319         for (combining = false; it != end; ++it) {
320                 docstring const math = it->second.mathcommand();
321                 docstring const text = it->second.textcommand();
322                 if ((cmdtype & MATH_CMD) && math == cmd) {
323                         combining = it->second.combining();
324                         needsTermination = !it->second.mathnotermination();
325                         if (req && it->second.mathfeature() &&
326                             !it->second.mathpreamble().empty())
327                                 req->insert(it->second.mathpreamble());
328                         return it->first;
329                 }
330                 if ((cmdtype & TEXT_CMD) && text == cmd) {
331                         combining = it->second.combining();
332                         needsTermination = !it->second.textnotermination();
333                         if (req && it->second.textfeature() &&
334                             !it->second.textpreamble().empty())
335                                 req->insert(it->second.textpreamble());
336                         return it->first;
337                 }
338         }
339         needsTermination = false;
340         return 0;
341 }
342
343
344 docstring Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
345                 bool & needsTermination, docstring & rem, set<string> * req)
346 {
347         needsTermination = false;
348         rem = empty_docstring();
349         bool const mathmode = cmdtype & MATH_CMD;
350         bool const textmode = cmdtype & TEXT_CMD;
351         docstring symbols;
352         size_t const cmdend = cmd.size();
353         size_t prefix = 0;
354         CharInfoMap::const_iterator const uniend = unicodesymbols.end();
355         for (size_t i = 0, j = 0; j < cmdend; ++j) {
356                 // Also get the char after a backslash
357                 if (j + 1 < cmdend && cmd[j] == '\\') {
358                         ++j;
359                         prefix = 1;
360                         // Detect things like \=*{e} as well
361                         if (j + 3 < cmdend && cmd[j+1] == '*' &&
362                             cmd[j+2] == '{') {
363                                 ++j;
364                                 prefix = 2;
365                         }
366                 }
367                 // position of the last character before a possible macro
368                 // argument
369                 size_t m = j;
370                 // If a macro argument follows, get it, too
371                 // Do it here only for single character commands. Other
372                 // combining commands need this too, but they are handled in
373                 // the loop below for performance reasons.
374                 if (j + 1 < cmdend && cmd[j + 1] == '{') {
375                         size_t k = j + 1;
376                         int count = 1;
377                         while (k < cmdend && count) {
378                                 k = cmd.find_first_of(from_ascii("{}"), k + 1);
379                                 // braces may not be balanced
380                                 if (k == docstring::npos)
381                                         break;
382                                 if (cmd[k] == '{')
383                                         ++count;
384                                 else
385                                         --count;
386                         }
387                         if (k != docstring::npos)
388                                 j = k;
389                 } else if (m + 1 < cmdend && isAlphaASCII(cmd[m])) {
390                         while (m + 2 < cmdend && isAlphaASCII(cmd[m+1]))
391                                 m++;
392                 }
393                 // Start with this substring and try augmenting it when it is
394                 // the prefix of some command in the unicodesymbols file
395                 docstring subcmd = cmd.substr(i, j - i + 1);
396
397                 CharInfoMap::const_iterator it = unicodesymbols.begin();
398                 // First part of subcmd which might be a combining character
399                 docstring combcmd = (m == j) ? docstring() : cmd.substr(i, m - i + 1);
400                 // The combining character of combcmd if it exists
401                 CharInfoMap::const_iterator combining = uniend;
402                 size_t unicmd_size = 0;
403                 char_type c = 0;
404                 for (; it != uniend; ++it) {
405                         docstring const math = mathmode ? it->second.mathcommand()
406                                                         : docstring();
407                         docstring const text = textmode ? it->second.textcommand()
408                                                         : docstring();
409                         if (!combcmd.empty() && it->second.combining() &&
410                             (math == combcmd || text == combcmd))
411                                 combining = it;
412                         size_t cur_size = max(math.size(), text.size());
413                         // The current math or text unicode command cannot
414                         // match, or we already matched a longer one
415                         if (cur_size < subcmd.size() || cur_size <= unicmd_size)
416                                 continue;
417
418                         docstring tmp = subcmd;
419                         size_t k = j;
420                         while (prefixIs(math, tmp) || prefixIs(text, tmp)) {
421                                 ++k;
422                                 if (k >= cmdend || cur_size <= tmp.size())
423                                         break;
424                                 tmp += cmd[k];
425                         }
426                         // No match
427                         if (k == j)
428                                 continue;
429
430                         // The last added char caused a mismatch, because
431                         // we didn't exhaust the chars in cmd and didn't
432                         // exceed the maximum size of the current unicmd
433                         if (k < cmdend && cur_size > tmp.size())
434                                 tmp.resize(tmp.size() - 1);
435
436                         // If this is an exact match, we found a (longer)
437                         // matching entry in the unicodesymbols file.
438                         if (math != tmp && text != tmp)
439                                 continue;
440                         // If we found a combining command, we need to append
441                         // the macro argument if this has not been done above.
442                         if (tmp == combcmd && combining != uniend &&
443                             k < cmdend && cmd[k] == '{') {
444                                 size_t l = k;
445                                 int count = 1;
446                                 while (l < cmdend && count) {
447                                         l = cmd.find_first_of(from_ascii("{}"), l + 1);
448                                         // braces may not be balanced
449                                         if (l == docstring::npos)
450                                                 break;
451                                         if (cmd[l] == '{')
452                                                 ++count;
453                                         else
454                                                 --count;
455                                 }
456                                 if (l != docstring::npos) {
457                                         j = l;
458                                         subcmd = cmd.substr(i, j - i + 1);
459                                 }
460                         }
461                         // If the entry doesn't start with '\', we take note
462                         // of the match and continue (this is not a ultimate
463                         // acceptance, as some other entry may match a longer
464                         // portion of the cmd string). However, if the entry
465                         // does start with '\', we accept the match only if
466                         // this is a valid macro, i.e., either it is a single
467                         // (nonletter) char macro, or nothing else follows,
468                         // or what follows is a nonletter char, or the last
469                         // character is a }.
470                         else if (tmp[0] != '\\'
471                                    || (tmp.size() == prefix + 1 &&
472                                        !isAlphaASCII(tmp[1]) &&
473                                        (prefix == 1 || !isAlphaASCII(tmp[2])))
474                                    || k == cmdend
475                                    || !isAlphaASCII(cmd[k])
476                                    || tmp[tmp.size() - 1] == '}'
477                                  ) {
478                                 c = it->first;
479                                 j = k - 1;
480                                 i = j + 1;
481                                 unicmd_size = cur_size;
482                                 if (math == tmp)
483                                         needsTermination = !it->second.mathnotermination();
484                                 else
485                                         needsTermination = !it->second.textnotermination();
486                                 if (req) {
487                                         if (math == tmp && it->second.mathfeature() &&
488                                             !it->second.mathpreamble().empty())
489                                                 req->insert(it->second.mathpreamble());
490                                         if (text == tmp && it->second.textfeature() &&
491                                             !it->second.textpreamble().empty())
492                                                 req->insert(it->second.textpreamble());
493                                 }
494                         }
495                 }
496                 if (unicmd_size)
497                         symbols += c;
498                 else if (combining != uniend &&
499                          prefixIs(subcmd, combcmd + '{')) {
500                         // We know that subcmd starts with combcmd and
501                         // contains an argument in braces.
502                         docstring const arg = subcmd.substr(
503                                 combcmd.length() + 1,
504                                 subcmd.length() - combcmd.length() - 2);
505                         // If arg is a single character we can construct a
506                         // combining sequence.
507                         char_type a;
508                         bool argcomb = false;
509                         if (arg.size() == 1 && isAlnumASCII(arg[0]))
510                                 a = arg[0];
511                         else {
512                                 // Use the version of fromLaTeXCommand() that
513                                 // parses only one command, since we cannot
514                                 // use more than one character.
515                                 bool dummy = false;
516                                 set<string> r;
517                                 a = fromLaTeXCommand(arg, cmdtype, argcomb,
518                                                      dummy, &r);
519                                 if (a && req && !argcomb)
520                                         req->insert(r.begin(), r.end());
521                         }
522                         if (a && !argcomb) {
523                                 // In unicode the combining character comes
524                                 // after its base
525                                 symbols += a;
526                                 symbols += combining->first;
527                                 i = j + 1;
528                                 unicmd_size = 2;
529                         }
530                 }
531                 if (j + 1 == cmdend && !unicmd_size) {
532                         // No luck. Return what remains
533                         rem = cmd.substr(i);
534                         if (needsTermination && !rem.empty()) {
535                                 if (rem.substr(0, 2) == "{}") {
536                                         rem = rem.substr(2);
537                                         needsTermination = false;
538                                 } else if (rem[0] == ' ') {
539                                         needsTermination = false;
540                                         // LaTeX would swallow all spaces
541                                         rem = ltrim(rem);
542                                 }
543                         }
544                 }
545         }
546         return symbols;
547 }
548
549
550 CharInfo const & Encodings::unicodeCharInfo(char_type c)
551 {
552         static CharInfo empty;
553         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
554         return it != unicodesymbols.end() ? it->second : empty;
555 }
556
557
558 bool Encodings::isCombiningChar(char_type c)
559 {
560         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
561         if (it != unicodesymbols.end())
562                 return it->second.combining();
563         return false;
564 }
565
566
567 string const Encodings::TIPAShortcut(char_type c)
568 {
569         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
570         if (it != unicodesymbols.end())
571                 return it->second.tipashortcut();
572         return string();
573 }
574
575
576 bool Encodings::isKnownScriptChar(char_type const c, string & preamble)
577 {
578         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
579
580         if (it == unicodesymbols.end())
581                 return false;
582
583         if (it->second.textpreamble() != "textgreek" && it->second.textpreamble() != "textcyr")
584                 return false;
585
586         if (preamble.empty()) {
587                 preamble = it->second.textpreamble();
588                 return true;
589         }
590         return it->second.textpreamble() == preamble;
591 }
592
593
594 bool Encodings::isMathAlpha(char_type c)
595 {
596         return mathalpha.count(c);
597 }
598
599
600 Encoding const *
601 Encodings::fromLyXName(string const & name, bool allowUnsafe) const
602 {
603         EncodingList::const_iterator const it = encodinglist.find(name);
604         if (it == encodinglist.end())
605                 return 0;
606         if (!allowUnsafe && it->second.unsafe())
607                 return 0;
608         return &it->second;
609 }
610
611
612 Encoding const *
613 Encodings::fromLaTeXName(string const & n, int const & p, bool allowUnsafe) const
614 {
615         string name = n;
616         // FIXME: if we have to test for too many of these synonyms,
617         // we should instead extend the format of lib/encodings
618         if (n == "ansinew")
619                 name = "cp1252";
620
621         // We don't use find_if because it makes copies of the pairs in
622         // the map.
623         // This linear search is OK since we don't have many encodings.
624         // Users could even optimize it by putting the encodings they use
625         // most at the top of lib/encodings.
626         EncodingList::const_iterator const end = encodinglist.end();
627         for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
628                 if ((it->second.latexName() == name) && (it->second.package() & p)
629                                 && (!it->second.unsafe() || allowUnsafe))
630                         return &it->second;
631         return 0;
632 }
633
634
635 Encoding const *
636 Encodings::fromIconvName(string const & n, int const & p, bool allowUnsafe) const
637 {
638         EncodingList::const_iterator const end = encodinglist.end();
639         for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
640                 if ((it->second.iconvName() == n) && (it->second.package() & p)
641                                 && (!it->second.unsafe() || allowUnsafe))
642                         return &it->second;
643         return 0;
644 }
645
646
647 Encodings::Encodings()
648 {}
649
650
651 void Encodings::read(FileName const & encfile, FileName const & symbolsfile)
652 {
653         // We must read the symbolsfile first, because the Encoding
654         // constructor depends on it.
655         CharSetMap forcednotselected;
656         Lexer symbolslex;
657         symbolslex.setFile(symbolsfile);
658         bool getNextToken = true;
659         while (symbolslex.isOK()) {
660                 char_type symbol;
661
662                 if (getNextToken) {
663                         if (!symbolslex.next(true))
664                                 break;
665                 } else
666                         getNextToken = true;
667
668                 istringstream is(symbolslex.getString());
669                 // reading symbol directly does not work if
670                 // char_type == wchar_t.
671                 boost::uint32_t tmp;
672                 if(!(is >> hex >> tmp))
673                         break;
674                 symbol = tmp;
675
676                 if (!symbolslex.next(true))
677                         break;
678                 docstring textcommand = symbolslex.getDocString();
679                 if (!symbolslex.next(true))
680                         break;
681                 string textpreamble = symbolslex.getString();
682                 if (!symbolslex.next(true))
683                         break;
684                 string sflags = symbolslex.getString();
685
686                 string tipashortcut;
687                 int flags = 0;
688
689                 if (suffixIs(textcommand, '}'))
690                         flags |= CharInfoTextNoTermination;
691                 while (!sflags.empty()) {
692                         string flag;
693                         sflags = split(sflags, flag, ',');
694                         if (flag == "combining") {
695                                 flags |= CharInfoCombining;
696                         } else if (flag == "force") {
697                                 flags |= CharInfoForce;
698                                 forced.insert(symbol);
699                         } else if (prefixIs(flag, "force=")) {
700                                 vector<string> encodings =
701                                         getVectorFromString(flag.substr(6), ";");
702                                 for (size_t i = 0; i < encodings.size(); ++i)
703                                         forcedselected[encodings[i]].insert(symbol);
704                                 flags |= CharInfoForceSelected;
705                         } else if (prefixIs(flag, "force!=")) {
706                                 vector<string> encodings =
707                                         getVectorFromString(flag.substr(7), ";");
708                                 for (size_t i = 0; i < encodings.size(); ++i)
709                                         forcednotselected[encodings[i]].insert(symbol);
710                                 flags |= CharInfoForceSelected;
711                         } else if (flag == "mathalpha") {
712                                 mathalpha.insert(symbol);
713                         } else if (flag == "notermination=text") {
714                                 flags |= CharInfoTextNoTermination;
715                         } else if (flag == "notermination=math") {
716                                 flags |= CharInfoMathNoTermination;
717                         } else if (flag == "notermination=both") {
718                                 flags |= CharInfoTextNoTermination;
719                                 flags |= CharInfoMathNoTermination;
720                         } else if (flag == "notermination=none") {
721                                 flags &= ~CharInfoTextNoTermination;
722                                 flags &= ~CharInfoMathNoTermination;
723                         } else if (contains(flag, "tipashortcut=")) {
724                                 tipashortcut = split(flag, '=');
725                         } else {
726                                 lyxerr << "Ignoring unknown flag `" << flag
727                                        << "' for symbol `0x"
728                                        << hex << symbol << dec
729                                        << "'." << endl;
730                         }
731                 }
732                 // mathcommand and mathpreamble have been added for 1.6.0.
733                 // make them optional so that old files still work.
734                 int const lineno = symbolslex.lineNumber();
735                 bool breakout = false;
736                 docstring mathcommand;
737                 string mathpreamble;
738                 if (symbolslex.next(true)) {
739                         if (symbolslex.lineNumber() != lineno) {
740                                 // line in old format without mathcommand and mathpreamble
741                                 getNextToken = false;
742                         } else {
743                                 mathcommand = symbolslex.getDocString();
744                                 if (suffixIs(mathcommand, '}'))
745                                         flags |= CharInfoMathNoTermination;
746                                 if (symbolslex.next(true)) {
747                                         if (symbolslex.lineNumber() != lineno) {
748                                                 // line in new format with mathcommand only
749                                                 getNextToken = false;
750                                         } else {
751                                                 // line in new format with mathcommand and mathpreamble
752                                                 mathpreamble = symbolslex.getString();
753                                         }
754                                 } else
755                                         breakout = true;
756                         }
757                 } else {
758                         breakout = true;
759                 }
760
761                 // backward compatibility
762                 if (mathpreamble == "esintoramsmath")
763                         mathpreamble = "esint|amsmath";
764
765                 if (!textpreamble.empty())
766                         if (textpreamble[0] != '\\')
767                                 flags |= CharInfoTextFeature;
768                 if (!mathpreamble.empty())
769                         if (mathpreamble[0] != '\\')
770                                 flags |= CharInfoMathFeature;
771
772                 CharInfo info = CharInfo(
773                         textcommand, mathcommand,
774                         textpreamble, mathpreamble,
775                         tipashortcut, flags);
776                 LYXERR(Debug::INFO, "Read unicode symbol " << symbol << " '"
777                            << to_utf8(info.textcommand()) << "' '" << info.textpreamble()
778                            << " '" << info.textfeature() << ' ' << info.textnotermination()
779                            << ' ' << to_utf8(info.mathcommand()) << "' '" << info.mathpreamble()
780                            << "' " << info.mathfeature() << ' ' << info.mathnotermination()
781                            << ' ' << info.combining() << ' ' << info.force()
782                            << ' ' << info.forceselected());
783
784                 // we assume that at least one command is nonempty when using unicodesymbols
785                 if (info.isUnicodeSymbol()) {
786                         unicodesymbols[symbol] = info;
787                 }
788
789                 if (breakout)
790                         break;
791         }
792
793         // Now read the encodings
794         enum {
795                 et_encoding = 1,
796                 et_end
797         };
798
799         LexerKeyword encodingtags[] = {
800                 { "encoding", et_encoding },
801                 { "end", et_end }
802         };
803
804         Lexer lex(encodingtags);
805         lex.setFile(encfile);
806         lex.setContext("Encodings::read");
807         while (lex.isOK()) {
808                 switch (lex.lex()) {
809                 case et_encoding:
810                 {
811                         lex.next();
812                         string const name = lex.getString();
813                         lex.next();
814                         string const latexname = lex.getString();
815                         lex.next();
816                         string const guiname = lex.getString();
817                         lex.next();
818                         string const iconvname = lex.getString();
819                         lex.next();
820                         string const width = lex.getString();
821                         bool fixedwidth = false;
822                         bool unsafe = false;
823                         if (width == "fixed")
824                                 fixedwidth = true;
825                         else if (width == "variable")
826                                 fixedwidth = false;
827                         else if (width == "variableunsafe") {
828                                 fixedwidth = false;
829                                 unsafe = true;
830                         }
831                         else
832                                 lex.printError("Unknown width");
833
834                         lex.next();
835                         string const p = lex.getString();
836                         Encoding::Package package = Encoding::none;
837                         if (p == "none")
838                                 package = Encoding::none;
839                         else if (p == "inputenc")
840                                 package = Encoding::inputenc;
841                         else if (p == "CJK")
842                                 package = Encoding::CJK;
843                         else if (p == "japanese")
844                                 package = Encoding::japanese;
845                         else
846                                 lex.printError("Unknown package");
847
848                         LYXERR(Debug::INFO, "Reading encoding " << name);
849                         encodinglist[name] = Encoding(name, latexname,
850                                 guiname, iconvname, fixedwidth, unsafe,
851                                 package);
852
853                         if (lex.lex() != et_end)
854                                 lex.printError("Missing end");
855                         break;
856                 }
857                 case et_end:
858                         lex.printError("Misplaced end");
859                         break;
860                 case Lexer::LEX_FEOF:
861                         break;
862                 default:
863                         lex.printError("Unknown tag");
864                         break;
865                 }
866         }
867
868         // Move all information from forcednotselected to forcedselected
869         for (CharSetMap::const_iterator it1 = forcednotselected.begin(); it1 != forcednotselected.end(); ++it1) {
870                 for (CharSetMap::iterator it2 = forcedselected.begin(); it2 != forcedselected.end(); ++it2) {
871                         if (it2->first != it1->first)
872                                 it2->second.insert(it1->second.begin(), it1->second.end());
873                 }
874         }
875
876 }
877
878
879 } // namespace lyx