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