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