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