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