]> git.lyx.org Git - features.git/blob - src/Encoding.cpp
CharInfo: allow to store several commands (both text and math) for each character.
[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         docstring symbols;
385         size_t const cmdend = cmd.size();
386         size_t prefix = 0;
387         CharInfoMap::const_iterator const uniend = unicodesymbols.end();
388         for (size_t i = 0, j = 0; j < cmdend; ++j) {
389                 // Also get the char after a backslash
390                 if (j + 1 < cmdend && cmd[j] == '\\') {
391                         ++j;
392                         prefix = 1;
393                         // Detect things like \=*{e} as well
394                         if (j + 3 < cmdend && cmd[j+1] == '*' &&
395                             cmd[j+2] == '{') {
396                                 ++j;
397                                 prefix = 2;
398                         }
399                 }
400                 // position of the last character before a possible macro
401                 // argument
402                 size_t m = j;
403                 // If a macro argument follows, get it, too
404                 // Do it here only for single character commands. Other
405                 // combining commands need this too, but they are handled in
406                 // the loop below for performance reasons.
407                 if (j + 1 < cmdend && cmd[j + 1] == '{') {
408                         size_t k = j + 1;
409                         int count = 1;
410                         while (k < cmdend && count) {
411                                 k = cmd.find_first_of(from_ascii("{}"), k + 1);
412                                 // braces may not be balanced
413                                 if (k == docstring::npos)
414                                         break;
415                                 if (cmd[k] == '{')
416                                         ++count;
417                                 else
418                                         --count;
419                         }
420                         if (k != docstring::npos)
421                                 j = k;
422                 } else if (m + 1 < cmdend && isAlphaASCII(cmd[m])) {
423                         while (m + 2 < cmdend && isAlphaASCII(cmd[m+1]))
424                                 m++;
425                 }
426                 // Start with this substring and try augmenting it when it is
427                 // the prefix of some command in the unicodesymbols file
428                 docstring subcmd = cmd.substr(i, j - i + 1);
429
430                 CharInfoMap::const_iterator it = unicodesymbols.begin();
431                 // First part of subcmd which might be a combining character
432                 docstring combcmd = (m == j) ? docstring() : cmd.substr(i, m - i + 1);
433                 // The combining character of combcmd if it exists
434                 CharInfoMap::const_iterator combining = uniend;
435                 size_t unicmd_size = 0;
436                 char_type c = 0;
437                 for (; it != uniend; ++it) {
438                         if (it->second.deprecated())
439                                 continue;
440                         docstring const math = mathmode ? it->second.mathCommand()
441                                                         : docstring();
442                         docstring const text = textmode ? it->second.textCommand()
443                                                         : docstring();
444                         if (!combcmd.empty() && it->second.combining() &&
445                             (math == combcmd || text == combcmd))
446                                 combining = it;
447                         size_t cur_size = max(math.size(), text.size());
448                         // The current math or text unicode command cannot
449                         // match, or we already matched a longer one
450                         if (cur_size < subcmd.size() || cur_size <= unicmd_size)
451                                 continue;
452
453                         docstring tmp = subcmd;
454                         size_t k = j;
455                         while (prefixIs(math, tmp) || prefixIs(text, tmp)) {
456                                 ++k;
457                                 if (k >= cmdend || cur_size <= tmp.size())
458                                         break;
459                                 tmp += cmd[k];
460                         }
461                         // No match
462                         if (k == j)
463                                 continue;
464
465                         // The last added char caused a mismatch, because
466                         // we didn't exhaust the chars in cmd and didn't
467                         // exceed the maximum size of the current unicmd
468                         if (k < cmdend && cur_size > tmp.size())
469                                 tmp.resize(tmp.size() - 1);
470
471                         // If this is an exact match, we found a (longer)
472                         // matching entry in the unicodesymbols file.
473                         if (math != tmp && text != tmp)
474                                 continue;
475                         // If we found a combining command, we need to append
476                         // the macro argument if this has not been done above.
477                         if (tmp == combcmd && combining != uniend &&
478                             k < cmdend && cmd[k] == '{') {
479                                 size_t l = k;
480                                 int count = 1;
481                                 while (l < cmdend && count) {
482                                         l = cmd.find_first_of(from_ascii("{}"), l + 1);
483                                         // braces may not be balanced
484                                         if (l == docstring::npos)
485                                                 break;
486                                         if (cmd[l] == '{')
487                                                 ++count;
488                                         else
489                                                 --count;
490                                 }
491                                 if (l != docstring::npos) {
492                                         j = l;
493                                         subcmd = cmd.substr(i, j - i + 1);
494                                 }
495                         }
496                         // If the entry doesn't start with '\', we take note
497                         // of the match and continue (this is not a ultimate
498                         // acceptance, as some other entry may match a longer
499                         // portion of the cmd string). However, if the entry
500                         // does start with '\', we accept the match only if
501                         // this is a valid macro, i.e., either it is a single
502                         // (nonletter) char macro, or nothing else follows,
503                         // or what follows is a nonletter char, or the last
504                         // character is a }.
505                         else if (tmp[0] != '\\'
506                                    || (tmp.size() == prefix + 1 &&
507                                        !isAlphaASCII(tmp[1]) &&
508                                        (prefix == 1 || !isAlphaASCII(tmp[2])))
509                                    || k == cmdend
510                                    || !isAlphaASCII(cmd[k])
511                                    || tmp[tmp.size() - 1] == '}'
512                                  ) {
513                                 c = it->first;
514                                 j = k - 1;
515                                 i = j + 1;
516                                 unicmd_size = cur_size;
517                                 if (math == tmp)
518                                         needsTermination = !it->second.mathNoTermination();
519                                 else
520                                         needsTermination = !it->second.textNoTermination();
521                                 if (req) {
522                                         if (math == tmp && it->second.mathFeature() &&
523                                             !it->second.mathPreamble().empty())
524                                                 req->insert(it->second.mathPreamble());
525                                         if (text == tmp && it->second.textFeature() &&
526                                             !it->second.textPreamble().empty())
527                                                 req->insert(it->second.textPreamble());
528                                 }
529                         }
530                 }
531                 if (unicmd_size)
532                         symbols += c;
533                 else if (combining != uniend &&
534                          prefixIs(subcmd, combcmd + '{')) {
535                         // We know that subcmd starts with combcmd and
536                         // contains an argument in braces.
537                         docstring const arg = subcmd.substr(
538                                 combcmd.length() + 1,
539                                 subcmd.length() - combcmd.length() - 2);
540                         // If arg is a single character we can construct a
541                         // combining sequence.
542                         char_type a;
543                         bool argcomb = false;
544                         if (arg.size() == 1 && isAlnumASCII(arg[0]))
545                                 a = arg[0];
546                         else {
547                                 // Use the version of fromLaTeXCommand() that
548                                 // parses only one command, since we cannot
549                                 // use more than one character.
550                                 bool dummy = false;
551                                 set<string> r;
552                                 a = fromLaTeXCommand(arg, cmdtype, argcomb,
553                                                      dummy, &r);
554                                 if (a && req && !argcomb)
555                                         req->insert(r.begin(), r.end());
556                         }
557                         if (a && !argcomb) {
558                                 // In unicode the combining character comes
559                                 // after its base
560                                 symbols += a;
561                                 symbols += combining->first;
562                                 i = j + 1;
563                                 unicmd_size = 2;
564                         }
565                 }
566                 if (j + 1 == cmdend && !unicmd_size) {
567                         // No luck. Return what remains
568                         rem = cmd.substr(i);
569                         if (needsTermination && !rem.empty()) {
570                                 if (rem.substr(0, 2) == "{}") {
571                                         rem = rem.substr(2);
572                                         needsTermination = false;
573                                 } else if (rem[0] == ' ') {
574                                         needsTermination = false;
575                                         // LaTeX would swallow all spaces
576                                         rem = ltrim(rem);
577                                 }
578                         }
579                 }
580         }
581         return symbols;
582 }
583
584
585 CharInfo const & Encodings::unicodeCharInfo(char_type c)
586 {
587         static CharInfo empty;
588         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
589         return it != unicodesymbols.end() ? it->second : empty;
590 }
591
592
593 bool Encodings::isCombiningChar(char_type c)
594 {
595         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
596         if (it != unicodesymbols.end())
597                 return it->second.combining();
598         return false;
599 }
600
601
602 string const Encodings::TIPAShortcut(char_type c)
603 {
604         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
605         if (it != unicodesymbols.end())
606                 return it->second.tipaShortcut();
607         return string();
608 }
609
610
611 string const Encodings::isKnownScriptChar(char_type const c)
612 {
613         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
614
615         if (it == unicodesymbols.end())
616                 return string();
617         // FIXME: parse complex textPreamble (may be list or alternatives,
618         //                e.g., "subscript,textgreek" or "textcomp|textgreek")
619         if (it->second.textPreamble() == "textgreek"
620                 || it->second.textPreamble() == "textcyrillic")
621                 return it->second.textPreamble();
622         return string();
623 }
624
625
626 bool Encodings::fontencSupportsScript(string const & fontenc, string const & script)
627 {
628         if (script == "textgreek")
629                 return (fontenc == "LGR" || fontenc == "TU");
630         if (script == "textcyrillic")
631                 return (fontenc == "T2A" || fontenc == "T2B" || fontenc == "T2C"
632                                 || fontenc == "X2" || fontenc == "TU");
633         return false;
634 }
635
636
637 bool Encodings::isMathAlpha(char_type c)
638 {
639         return mathalpha.count(c);
640 }
641
642
643 bool Encodings::isUnicodeTextOnly(char_type c)
644 {
645         if (isASCII(c) || isMathAlpha(c))
646                 return false;
647
648         CharInfoMap::const_iterator const it = unicodesymbols.find(c);
649         return it == unicodesymbols.end() || it->second.mathCommand().empty();
650 }
651
652
653 Encoding const *
654 Encodings::fromLyXName(string const & name, bool allowUnsafe) const
655 {
656         EncodingList::const_iterator const it = encodinglist.find(name);
657         if (it == encodinglist.end())
658                 return nullptr;
659         if (!allowUnsafe && it->second.unsafe())
660                 return nullptr;
661         return &it->second;
662 }
663
664
665 Encoding const *
666 Encodings::fromLaTeXName(string const & n, int p, bool allowUnsafe) const
667 {
668         string name = n;
669         // FIXME: if we have to test for too many of these synonyms,
670         // we should instead extend the format of lib/encodings
671         if (n == "ansinew")
672                 name = "cp1252";
673
674         // We don't use find_if because it makes copies of the pairs in
675         // the map.
676         // This linear search is OK since we don't have many encodings.
677         // Users could even optimize it by putting the encodings they use
678         // most at the top of lib/encodings.
679         EncodingList::const_iterator const end = encodinglist.end();
680         for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
681                 if ((it->second.latexName() == name) && (it->second.package() & p)
682                                 && (!it->second.unsafe() || allowUnsafe))
683                         return &it->second;
684         return nullptr;
685 }
686
687
688 Encoding const *
689 Encodings::fromIconvName(string const & n, int p, bool allowUnsafe) const
690 {
691         EncodingList::const_iterator const end = encodinglist.end();
692         for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
693                 if ((it->second.iconvName() == n) && (it->second.package() & p)
694                                 && (!it->second.unsafe() || allowUnsafe))
695                         return &it->second;
696         return nullptr;
697 }
698
699
700 Encodings::Encodings()
701 {}
702
703
704 void Encodings::read(FileName const & encfile, FileName const & symbolsfile)
705 {
706         // We must read the symbolsfile first, because the Encoding
707         // constructor depends on it.
708         CharSetMap forcednotselected;
709         Lexer symbolslex;
710         symbolslex.setFile(symbolsfile);
711         bool getNextToken = true;
712         while (symbolslex.isOK()) {
713                 char_type symbol;
714
715                 if (getNextToken) {
716                         if (!symbolslex.next(true))
717                                 break;
718                 } else
719                         getNextToken = true;
720
721                 istringstream is(symbolslex.getString());
722                 // reading symbol directly does not work if
723                 // char_type == wchar_t.
724                 uint32_t tmp;
725                 if(!(is >> hex >> tmp))
726                         break;
727                 symbol = tmp;
728
729                 if (!symbolslex.next(true))
730                         break;
731                 docstring textcommand = symbolslex.getDocString();
732                 if (!symbolslex.next(true))
733                         break;
734                 string textpreamble = symbolslex.getString();
735                 if (!symbolslex.next(true))
736                         break;
737                 string sflags = symbolslex.getString();
738
739                 string tipashortcut;
740                 int flags = 0;
741
742                 if (suffixIs(textcommand, '}'))
743                         flags |= CharInfoTextNoTermination;
744                 while (!sflags.empty()) {
745                         string flag;
746                         sflags = split(sflags, flag, ',');
747                         if (flag == "combining") {
748                                 flags |= CharInfoCombining;
749                         } else if (flag == "force") {
750                                 flags |= CharInfoForce;
751                                 forced.insert(symbol);
752                         } else if (prefixIs(flag, "force=")) {
753                                 vector<string> encs =
754                                         getVectorFromString(flag.substr(6), ";");
755                                 for (auto const & enc : encs)
756                                         forcedselected[enc].insert(symbol);
757                                 flags |= CharInfoForceSelected;
758                         } else if (prefixIs(flag, "force!=")) {
759                                 vector<string> encs =
760                                         getVectorFromString(flag.substr(7), ";");
761                                 for (auto const & enc : encs)
762                                         forcednotselected[enc].insert(symbol);
763                                 flags |= CharInfoForceSelected;
764                         } else if (flag == "mathalpha") {
765                                 mathalpha.insert(symbol);
766                         } else if (flag == "notermination=text") {
767                                 flags |= CharInfoTextNoTermination;
768                         } else if (flag == "notermination=math") {
769                                 flags |= CharInfoMathNoTermination;
770                         } else if (flag == "notermination=both") {
771                                 flags |= CharInfoTextNoTermination;
772                                 flags |= CharInfoMathNoTermination;
773                         } else if (flag == "notermination=none") {
774                                 flags &= ~CharInfoTextNoTermination;
775                                 flags &= ~CharInfoMathNoTermination;
776                         } else if (contains(flag, "tipaShortcut=")) {
777                                 tipashortcut = split(flag, '=');
778                         } else if (flag == "deprecated") {
779                                 flags |= CharInfoDeprecated;
780                         } else {
781                                 lyxerr << "Ignoring unknown flag `" << flag
782                                        << "' for symbol `0x"
783                                        << hex << symbol << dec
784                                        << "'." << endl;
785                         }
786                 }
787                 // mathCommand and mathPreamble have been added for 1.6.0.
788                 // make them optional so that old files still work.
789                 int const lineno = symbolslex.lineNumber();
790                 bool breakout = false;
791                 docstring mathcommand;
792                 string mathpreamble;
793                 if (symbolslex.next(true)) {
794                         if (symbolslex.lineNumber() != lineno) {
795                                 // line in old format without mathCommand and mathPreamble
796                                 getNextToken = false;
797                         } else {
798                                 mathcommand = symbolslex.getDocString();
799                                 if (suffixIs(mathcommand, '}'))
800                                         flags |= CharInfoMathNoTermination;
801                                 if (symbolslex.next(true)) {
802                                         if (symbolslex.lineNumber() != lineno) {
803                                                 // line in new format with mathCommand only
804                                                 getNextToken = false;
805                                         } else {
806                                                 // line in new format with mathCommand and mathPreamble
807                                                 mathpreamble = symbolslex.getString();
808                                         }
809                                 } else
810                                         breakout = true;
811                         }
812                 } else {
813                         breakout = true;
814                 }
815
816                 // backward compatibility
817                 if (mathpreamble == "esintoramsmath")
818                         mathpreamble = "esint|amsmath";
819
820                 if (!textpreamble.empty())
821                         if (textpreamble[0] != '\\')
822                                 flags |= CharInfoTextFeature;
823                 if (!mathpreamble.empty())
824                         if (mathpreamble[0] != '\\')
825                                 flags |= CharInfoMathFeature;
826
827                 CharInfo info = CharInfo(
828                         textcommand, mathcommand,
829                         textpreamble, mathpreamble,
830                         tipashortcut, flags);
831                 LYXERR(Debug::INFO, "Read unicode symbol " << symbol << " '"
832                                                            << to_utf8(info.textCommand()) << "' '" << info.textPreamble()
833                                                            << " '" << info.textFeature() << ' ' << info.textNoTermination()
834                                                            << ' ' << to_utf8(info.mathCommand()) << "' '" << info.mathPreamble()
835                                                            << "' " << info.mathFeature() << ' ' << info.mathNoTermination()
836                            << ' ' << info.combining() << ' ' << info.force()
837                            << ' ' << info.forceSelected());
838
839                 // we assume that at least one command is nonempty when using unicodesymbols
840                 if (info.isUnicodeSymbol()) {
841                         unicodesymbols[symbol] = info;
842                 }
843
844                 if (breakout)
845                         break;
846         }
847
848         // Now read the encodings
849         enum {
850                 et_encoding = 1,
851                 et_end
852         };
853
854         LexerKeyword encodingtags[] = {
855                 { "encoding", et_encoding },
856                 { "end", et_end }
857         };
858
859         Lexer lex(encodingtags);
860         lex.setFile(encfile);
861         lex.setContext("Encodings::read");
862         while (lex.isOK()) {
863                 switch (lex.lex()) {
864                 case et_encoding:
865                 {
866                         lex.next();
867                         string const name = lex.getString();
868                         lex.next();
869                         string const latexname = lex.getString();
870                         lex.next();
871                         string const guiname = lex.getString();
872                         lex.next();
873                         string const iconvname = lex.getString();
874                         lex.next();
875                         string const width = lex.getString();
876                         bool fixedwidth = false;
877                         bool unsafe = false;
878                         if (width == "fixed")
879                                 fixedwidth = true;
880                         else if (width == "variable")
881                                 fixedwidth = false;
882                         else if (width == "variableunsafe") {
883                                 fixedwidth = false;
884                                 unsafe = true;
885                         }
886                         else
887                                 lex.printError("Unknown width");
888
889                         lex.next();
890                         string const p = lex.getString();
891                         Encoding::Package package = Encoding::none;
892                         if (p == "none")
893                                 package = Encoding::none;
894                         else if (p == "inputenc")
895                                 package = Encoding::inputenc;
896                         else if (p == "CJK")
897                                 package = Encoding::CJK;
898                         else if (p == "japanese")
899                                 package = Encoding::japanese;
900                         else
901                                 lex.printError("Unknown package");
902
903                         LYXERR(Debug::INFO, "Reading encoding " << name);
904                         encodinglist[name] = Encoding(name, latexname,
905                                 guiname, iconvname, fixedwidth, unsafe,
906                                 package);
907
908                         if (lex.lex() != et_end)
909                                 lex.printError("Missing end");
910                         break;
911                 }
912                 case et_end:
913                         lex.printError("Misplaced end");
914                         break;
915                 case Lexer::LEX_FEOF:
916                         break;
917                 default:
918                         lex.printError("Unknown tag");
919                         break;
920                 }
921         }
922
923         // Move all information from forcednotselected to forcedselected
924         for (CharSetMap::const_iterator it1 = forcednotselected.begin(); it1 != forcednotselected.end(); ++it1) {
925                 for (CharSetMap::iterator it2 = forcedselected.begin(); it2 != forcedselected.end(); ++it2) {
926                         if (it2->first != it1->first)
927                                 it2->second.insert(it1->second.begin(), it1->second.end());
928                 }
929         }
930
931 }
932
933
934 } // namespace lyx