3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
19 #include "support/debug.h"
20 #include "support/gettext.h"
21 #include "support/lstrings.h"
22 #include "support/mutex.h"
23 #include "support/textutils.h"
24 #include "support/unicode.h"
32 using namespace lyx::support;
36 int const Encoding::any = -1;
40 Encodings::MathCommandSet Encodings::mathcmd;
41 Encodings::TextCommandSet Encodings::textcmd;
42 Encodings::MathSymbolSet Encodings::mathsym;
46 typedef map<char_type, CharInfo> CharInfoMap;
47 CharInfoMap unicodesymbols;
49 typedef set<char_type> CharSet;
50 typedef map<string, CharSet> CharSetMap;
52 CharSetMap forcedselected;
54 typedef set<char_type> MathAlphaSet;
55 MathAlphaSet mathalpha;
58 /// The highest code point in UCS4 encoding (1<<20 + 1<<16)
59 char_type const max_ucs4 = 0x110000;
64 EncodingException::EncodingException(char_type c)
65 : failed_char(c), par_id(0), pos(0)
70 const char * EncodingException::what() const noexcept
72 return "Could not find LaTeX command for a character";
77 docstring const & textcommand, docstring const & mathcommand,
78 std::string const & textpreamble, std::string const & mathpreamble,
79 std::string const & tipashortcut, unsigned int flags)
80 : textcommand_(textcommand), mathcommand_(mathcommand),
81 textpreamble_(textpreamble), mathpreamble_(mathpreamble),
82 tipashortcut_(tipashortcut), flags_(flags)
87 Encoding::Encoding(string const & n, string const & l, string const & g,
88 string const & i, bool f, bool u, Encoding::Package p)
89 : name_(n), latexName_(l), guiName_(g), iconvName_(i), fixedwidth_(f),
90 unsafe_(u), forced_(&forcedselected[n]), package_(p)
93 // ASCII can encode 128 code points and nothing else
94 start_encodable_ = 128;
96 } else if (i == "UTF-8") {
97 // UTF8 can encode all UCS4 code points
98 start_encodable_ = max_ucs4;
101 start_encodable_ = 0;
107 void Encoding::init() const
109 // Since the the constructor is the only method which sets complete_
110 // to false the test for complete_ is thread-safe without mutex.
115 Mutex::Locker lock(&mutex);
117 // We need to test again for complete_, since another thread could
118 // have set it to true while we were waiting for the lock and we must
119 // not modify an encoding which is already complete.
123 // We do not make any member mutable so that it can be easily verified
124 // that all const methods are thread-safe: init() is the only const
125 // method which changes complete_, encodable_ and start_encodable_, and
126 // it uses a mutex to ensure thread-safety.
127 CharSet & encodable = const_cast<Encoding *>(this)->encodable_;
128 char_type & start_encodable = const_cast<Encoding *>(this)->start_encodable_;
131 // temporarily switch off lyxerr, since we will generate iconv errors
134 // We do not need to check all UCS4 code points, it is enough
135 // if we check all 256 code points of this encoding.
136 for (unsigned short j = 0; j < 256; ++j) {
137 char const c = char(j);
138 vector<char_type> const ucs4 = eightbit_to_ucs4(&c, 1, iconvName_);
139 if (ucs4.size() != 1)
141 char_type const uc = ucs4[0];
142 CharInfoMap::const_iterator const it = unicodesymbols.find(uc);
143 if (it == unicodesymbols.end())
144 encodable.insert(uc);
145 else if (!it->second.force()) {
146 if (forced_->empty() || forced_->find(uc) == forced_->end())
147 encodable.insert(uc);
151 // We do not know how many code points this encoding has, and
152 // they do not have a direct representation as a single byte,
153 // therefore we need to check all UCS4 code points.
154 // This is expensive!
155 for (char_type c = 0; c < max_ucs4; ++c) {
156 vector<char> const eightbit = ucs4_to_eightbit(&c, 1, iconvName_);
157 if (!eightbit.empty()) {
158 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
159 if (it == unicodesymbols.end())
161 else if (!it->second.force()) {
162 if (forced_->empty() || forced_->find(c) == forced_->end())
169 CharSet::iterator it = encodable.find(start_encodable);
170 while (it != encodable.end()) {
173 it = encodable.find(start_encodable);
175 const_cast<Encoding *>(this)->complete_ = true;
179 bool Encoding::isForced(char_type c) const
181 if (!forced.empty() && forced.find(c) != forced.end())
183 return !forced_->empty() && forced_->find(c) != forced_->end();
187 bool Encoding::encodable(char_type c) const
189 // assure the used encoding is properly initialized
191 if (iconvName_ == "UTF-8" && package_ == none)
193 // platex does not load inputenc: force conversion of supported characters
194 if (package_ == Encoding::japanese
195 && ((0xb7 <= c && c <= 0x05ff) // Latin-1 Supplement ... Hebrew
196 || (0x1d00 <= c && c <= 0x218f) // Phonetic Extensions ... Number Forms
197 || (0x2193 <= c && c <= 0x2aff) // Arrows ... Supplemental Mathematical Operators
198 || (0xfb00 <= c && c <= 0xfb4f) // Alphabetic Presentation Forms
199 || (0x1d400 <= c && c <= 0x1d7ff))) // Mathematical Alphanumeric Symbols
201 if (c < start_encodable_ && !isForced(c))
203 if (encodable_.find(c) != encodable_.end())
209 pair<docstring, bool> Encoding::latexChar(char_type c) const
212 return make_pair(docstring(1, c), false);
214 // c cannot (or should not) be encoded in this encoding
215 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
216 if (it == unicodesymbols.end())
217 throw EncodingException(c);
218 // at least one of mathcommand and textcommand is nonempty
219 if (it->second.textcommand().empty())
221 "\\ensuremath{" + it->second.mathcommand() + '}', false);
222 return make_pair(it->second.textcommand(), !it->second.textnotermination());
226 pair<docstring, docstring> Encoding::latexString(docstring const & input, bool dryrun) const
230 bool terminate = false;
231 for (char_type const c : input) {
233 pair<docstring, bool> latex_char = latexChar(c);
234 docstring const latex = latex_char.first;
235 if (terminate && !prefixIs(latex, '\\')
236 && !prefixIs(latex, '{')
237 && !prefixIs(latex, '}')) {
238 // Prevent eating of a following
239 // space or command corruption by
240 // following characters
247 terminate = latex_char.second;
248 } catch (EncodingException & /* e */) {
249 LYXERR0("Uncodable character <" << docstring(1, c)
250 << "> in latexString!");
252 result += "<" + _("LyX Warning: ")
253 + _("uncodable character") + " '";
254 result += docstring(1, c);
260 return make_pair(result, uncodable);
264 vector<char_type> Encoding::symbolsList() const
266 // assure the used encoding is properly initialized
269 // first all those below start_encodable_
270 vector<char_type> symbols;
271 for (char_type c = 0; c < start_encodable_; ++c)
272 symbols.push_back(c);
273 // add all encodable characters
274 copy(encodable_.begin(), encodable_.end(), back_inserter(symbols));
275 // now the ones from the unicodesymbols file that are not already there
276 for (auto const & elem : unicodesymbols) {
277 if (find(symbols.begin(), symbols.end(), elem.first) == symbols.end())
278 symbols.push_back(elem.first);
280 // finally, sort the vector
281 sort(symbols.begin(), symbols.end());
286 bool Encodings::latexMathChar(char_type c, bool mathmode,
287 Encoding const * encoding, docstring & command,
288 bool & needsTermination)
290 command = empty_docstring();
292 if (encoding->encodable(c))
293 command = docstring(1, c);
294 needsTermination = false;
296 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
297 if (it == unicodesymbols.end()) {
298 if (!encoding || command.empty())
299 throw EncodingException(c);
304 // at least one of mathcommand and textcommand is nonempty
305 bool use_math = (mathmode && !it->second.mathcommand().empty()) ||
306 (!mathmode && it->second.textcommand().empty());
308 command = it->second.mathcommand();
309 needsTermination = !it->second.mathnotermination();
312 if (!encoding || command.empty()) {
313 command = it->second.textcommand();
314 needsTermination = !it->second.textnotermination();
325 char_type Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
326 bool & combining, bool & needsTermination, set<string> * req)
328 CharInfoMap::const_iterator const end = unicodesymbols.end();
329 CharInfoMap::const_iterator it = unicodesymbols.begin();
330 for (combining = false; it != end; ++it) {
331 if (it->second.deprecated())
333 docstring const math = it->second.mathcommand();
334 docstring const text = it->second.textcommand();
335 if ((cmdtype & MATH_CMD) && math == cmd) {
336 combining = it->second.combining();
337 needsTermination = !it->second.mathnotermination();
338 if (req && it->second.mathfeature() &&
339 !it->second.mathpreamble().empty())
340 req->insert(it->second.mathpreamble());
343 if ((cmdtype & TEXT_CMD) && text == cmd) {
344 combining = it->second.combining();
345 needsTermination = !it->second.textnotermination();
346 if (req && it->second.textfeature() &&
347 !it->second.textpreamble().empty())
348 req->insert(it->second.textpreamble());
352 needsTermination = false;
357 docstring Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
358 bool & needsTermination, docstring & rem, set<string> * req)
360 needsTermination = false;
361 rem = empty_docstring();
362 bool const mathmode = cmdtype & MATH_CMD;
363 bool const textmode = cmdtype & TEXT_CMD;
365 size_t const cmdend = cmd.size();
367 CharInfoMap::const_iterator const uniend = unicodesymbols.end();
368 for (size_t i = 0, j = 0; j < cmdend; ++j) {
369 // Also get the char after a backslash
370 if (j + 1 < cmdend && cmd[j] == '\\') {
373 // Detect things like \=*{e} as well
374 if (j + 3 < cmdend && cmd[j+1] == '*' &&
380 // position of the last character before a possible macro
383 // If a macro argument follows, get it, too
384 // Do it here only for single character commands. Other
385 // combining commands need this too, but they are handled in
386 // the loop below for performance reasons.
387 if (j + 1 < cmdend && cmd[j + 1] == '{') {
390 while (k < cmdend && count) {
391 k = cmd.find_first_of(from_ascii("{}"), k + 1);
392 // braces may not be balanced
393 if (k == docstring::npos)
400 if (k != docstring::npos)
402 } else if (m + 1 < cmdend && isAlphaASCII(cmd[m])) {
403 while (m + 2 < cmdend && isAlphaASCII(cmd[m+1]))
406 // Start with this substring and try augmenting it when it is
407 // the prefix of some command in the unicodesymbols file
408 docstring subcmd = cmd.substr(i, j - i + 1);
410 CharInfoMap::const_iterator it = unicodesymbols.begin();
411 // First part of subcmd which might be a combining character
412 docstring combcmd = (m == j) ? docstring() : cmd.substr(i, m - i + 1);
413 // The combining character of combcmd if it exists
414 CharInfoMap::const_iterator combining = uniend;
415 size_t unicmd_size = 0;
417 for (; it != uniend; ++it) {
418 if (it->second.deprecated())
420 docstring const math = mathmode ? it->second.mathcommand()
422 docstring const text = textmode ? it->second.textcommand()
424 if (!combcmd.empty() && it->second.combining() &&
425 (math == combcmd || text == combcmd))
427 size_t cur_size = max(math.size(), text.size());
428 // The current math or text unicode command cannot
429 // match, or we already matched a longer one
430 if (cur_size < subcmd.size() || cur_size <= unicmd_size)
433 docstring tmp = subcmd;
435 while (prefixIs(math, tmp) || prefixIs(text, tmp)) {
437 if (k >= cmdend || cur_size <= tmp.size())
445 // The last added char caused a mismatch, because
446 // we didn't exhaust the chars in cmd and didn't
447 // exceed the maximum size of the current unicmd
448 if (k < cmdend && cur_size > tmp.size())
449 tmp.resize(tmp.size() - 1);
451 // If this is an exact match, we found a (longer)
452 // matching entry in the unicodesymbols file.
453 if (math != tmp && text != tmp)
455 // If we found a combining command, we need to append
456 // the macro argument if this has not been done above.
457 if (tmp == combcmd && combining != uniend &&
458 k < cmdend && cmd[k] == '{') {
461 while (l < cmdend && count) {
462 l = cmd.find_first_of(from_ascii("{}"), l + 1);
463 // braces may not be balanced
464 if (l == docstring::npos)
471 if (l != docstring::npos) {
473 subcmd = cmd.substr(i, j - i + 1);
476 // If the entry doesn't start with '\', we take note
477 // of the match and continue (this is not a ultimate
478 // acceptance, as some other entry may match a longer
479 // portion of the cmd string). However, if the entry
480 // does start with '\', we accept the match only if
481 // this is a valid macro, i.e., either it is a single
482 // (nonletter) char macro, or nothing else follows,
483 // or what follows is a nonletter char, or the last
485 else if (tmp[0] != '\\'
486 || (tmp.size() == prefix + 1 &&
487 !isAlphaASCII(tmp[1]) &&
488 (prefix == 1 || !isAlphaASCII(tmp[2])))
490 || !isAlphaASCII(cmd[k])
491 || tmp[tmp.size() - 1] == '}'
496 unicmd_size = cur_size;
498 needsTermination = !it->second.mathnotermination();
500 needsTermination = !it->second.textnotermination();
502 if (math == tmp && it->second.mathfeature() &&
503 !it->second.mathpreamble().empty())
504 req->insert(it->second.mathpreamble());
505 if (text == tmp && it->second.textfeature() &&
506 !it->second.textpreamble().empty())
507 req->insert(it->second.textpreamble());
513 else if (combining != uniend &&
514 prefixIs(subcmd, combcmd + '{')) {
515 // We know that subcmd starts with combcmd and
516 // contains an argument in braces.
517 docstring const arg = subcmd.substr(
518 combcmd.length() + 1,
519 subcmd.length() - combcmd.length() - 2);
520 // If arg is a single character we can construct a
521 // combining sequence.
523 bool argcomb = false;
524 if (arg.size() == 1 && isAlnumASCII(arg[0]))
527 // Use the version of fromLaTeXCommand() that
528 // parses only one command, since we cannot
529 // use more than one character.
532 a = fromLaTeXCommand(arg, cmdtype, argcomb,
534 if (a && req && !argcomb)
535 req->insert(r.begin(), r.end());
538 // In unicode the combining character comes
541 symbols += combining->first;
546 if (j + 1 == cmdend && !unicmd_size) {
547 // No luck. Return what remains
549 if (needsTermination && !rem.empty()) {
550 if (rem.substr(0, 2) == "{}") {
552 needsTermination = false;
553 } else if (rem[0] == ' ') {
554 needsTermination = false;
555 // LaTeX would swallow all spaces
565 CharInfo const & Encodings::unicodeCharInfo(char_type c)
567 static CharInfo empty;
568 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
569 return it != unicodesymbols.end() ? it->second : empty;
573 bool Encodings::isCombiningChar(char_type c)
575 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
576 if (it != unicodesymbols.end())
577 return it->second.combining();
582 string const Encodings::TIPAShortcut(char_type c)
584 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
585 if (it != unicodesymbols.end())
586 return it->second.tipashortcut();
591 string const Encodings::isKnownScriptChar(char_type const c)
593 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
595 if (it == unicodesymbols.end())
597 // FIXME: parse complex textpreamble (may be list or alternatives,
598 // e.g., "subscript,textgreek" or "textcomp|textgreek")
599 if (it->second.textpreamble() == "textgreek"
600 || it->second.textpreamble() == "textcyrillic")
601 return it->second.textpreamble();
606 bool Encodings::fontencSupportsScript(string const & fontenc, string const & script)
608 if (script == "textgreek")
609 return (fontenc == "LGR" || fontenc == "TU");
610 if (script == "textcyrillic")
611 return (fontenc == "T2A" || fontenc == "T2B" || fontenc == "T2C"
612 || fontenc == "X2" || fontenc == "TU");
617 bool Encodings::isMathAlpha(char_type c)
619 return mathalpha.count(c);
623 bool Encodings::isUnicodeTextOnly(char_type c)
625 if (isASCII(c) || isMathAlpha(c))
628 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
629 return it == unicodesymbols.end() || it->second.mathcommand().empty();
634 Encodings::fromLyXName(string const & name, bool allowUnsafe) const
636 EncodingList::const_iterator const it = encodinglist.find(name);
637 if (it == encodinglist.end())
639 if (!allowUnsafe && it->second.unsafe())
646 Encodings::fromLaTeXName(string const & n, int p, bool allowUnsafe) const
649 // FIXME: if we have to test for too many of these synonyms,
650 // we should instead extend the format of lib/encodings
654 // We don't use find_if because it makes copies of the pairs in
656 // This linear search is OK since we don't have many encodings.
657 // Users could even optimize it by putting the encodings they use
658 // most at the top of lib/encodings.
659 EncodingList::const_iterator const end = encodinglist.end();
660 for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
661 if ((it->second.latexName() == name) && (it->second.package() & p)
662 && (!it->second.unsafe() || allowUnsafe))
669 Encodings::fromIconvName(string const & n, int p, bool allowUnsafe) const
671 EncodingList::const_iterator const end = encodinglist.end();
672 for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
673 if ((it->second.iconvName() == n) && (it->second.package() & p)
674 && (!it->second.unsafe() || allowUnsafe))
680 Encodings::Encodings()
684 void Encodings::read(FileName const & encfile, FileName const & symbolsfile)
686 // We must read the symbolsfile first, because the Encoding
687 // constructor depends on it.
688 CharSetMap forcednotselected;
690 symbolslex.setFile(symbolsfile);
691 bool getNextToken = true;
692 while (symbolslex.isOK()) {
696 if (!symbolslex.next(true))
701 istringstream is(symbolslex.getString());
702 // reading symbol directly does not work if
703 // char_type == wchar_t.
705 if(!(is >> hex >> tmp))
709 if (!symbolslex.next(true))
711 docstring textcommand = symbolslex.getDocString();
712 if (!symbolslex.next(true))
714 string textpreamble = symbolslex.getString();
715 if (!symbolslex.next(true))
717 string sflags = symbolslex.getString();
722 if (suffixIs(textcommand, '}'))
723 flags |= CharInfoTextNoTermination;
724 while (!sflags.empty()) {
726 sflags = split(sflags, flag, ',');
727 if (flag == "combining") {
728 flags |= CharInfoCombining;
729 } else if (flag == "force") {
730 flags |= CharInfoForce;
731 forced.insert(symbol);
732 } else if (prefixIs(flag, "force=")) {
733 vector<string> encs =
734 getVectorFromString(flag.substr(6), ";");
735 for (auto const & enc : encs)
736 forcedselected[enc].insert(symbol);
737 flags |= CharInfoForceSelected;
738 } else if (prefixIs(flag, "force!=")) {
739 vector<string> encs =
740 getVectorFromString(flag.substr(7), ";");
741 for (auto const & enc : encs)
742 forcednotselected[enc].insert(symbol);
743 flags |= CharInfoForceSelected;
744 } else if (flag == "mathalpha") {
745 mathalpha.insert(symbol);
746 } else if (flag == "notermination=text") {
747 flags |= CharInfoTextNoTermination;
748 } else if (flag == "notermination=math") {
749 flags |= CharInfoMathNoTermination;
750 } else if (flag == "notermination=both") {
751 flags |= CharInfoTextNoTermination;
752 flags |= CharInfoMathNoTermination;
753 } else if (flag == "notermination=none") {
754 flags &= ~CharInfoTextNoTermination;
755 flags &= ~CharInfoMathNoTermination;
756 } else if (contains(flag, "tipashortcut=")) {
757 tipashortcut = split(flag, '=');
758 } else if (flag == "deprecated") {
759 flags |= CharInfoDeprecated;
761 lyxerr << "Ignoring unknown flag `" << flag
762 << "' for symbol `0x"
763 << hex << symbol << dec
767 // mathcommand and mathpreamble have been added for 1.6.0.
768 // make them optional so that old files still work.
769 int const lineno = symbolslex.lineNumber();
770 bool breakout = false;
771 docstring mathcommand;
773 if (symbolslex.next(true)) {
774 if (symbolslex.lineNumber() != lineno) {
775 // line in old format without mathcommand and mathpreamble
776 getNextToken = false;
778 mathcommand = symbolslex.getDocString();
779 if (suffixIs(mathcommand, '}'))
780 flags |= CharInfoMathNoTermination;
781 if (symbolslex.next(true)) {
782 if (symbolslex.lineNumber() != lineno) {
783 // line in new format with mathcommand only
784 getNextToken = false;
786 // line in new format with mathcommand and mathpreamble
787 mathpreamble = symbolslex.getString();
796 // backward compatibility
797 if (mathpreamble == "esintoramsmath")
798 mathpreamble = "esint|amsmath";
800 if (!textpreamble.empty())
801 if (textpreamble[0] != '\\')
802 flags |= CharInfoTextFeature;
803 if (!mathpreamble.empty())
804 if (mathpreamble[0] != '\\')
805 flags |= CharInfoMathFeature;
807 CharInfo info = CharInfo(
808 textcommand, mathcommand,
809 textpreamble, mathpreamble,
810 tipashortcut, flags);
811 LYXERR(Debug::INFO, "Read unicode symbol " << symbol << " '"
812 << to_utf8(info.textcommand()) << "' '" << info.textpreamble()
813 << " '" << info.textfeature() << ' ' << info.textnotermination()
814 << ' ' << to_utf8(info.mathcommand()) << "' '" << info.mathpreamble()
815 << "' " << info.mathfeature() << ' ' << info.mathnotermination()
816 << ' ' << info.combining() << ' ' << info.force()
817 << ' ' << info.forceselected());
819 // we assume that at least one command is nonempty when using unicodesymbols
820 if (info.isUnicodeSymbol()) {
821 unicodesymbols[symbol] = info;
828 // Now read the encodings
834 LexerKeyword encodingtags[] = {
835 { "encoding", et_encoding },
839 Lexer lex(encodingtags);
840 lex.setFile(encfile);
841 lex.setContext("Encodings::read");
847 string const name = lex.getString();
849 string const latexname = lex.getString();
851 string const guiname = lex.getString();
853 string const iconvname = lex.getString();
855 string const width = lex.getString();
856 bool fixedwidth = false;
858 if (width == "fixed")
860 else if (width == "variable")
862 else if (width == "variableunsafe") {
867 lex.printError("Unknown width");
870 string const p = lex.getString();
871 Encoding::Package package = Encoding::none;
873 package = Encoding::none;
874 else if (p == "inputenc")
875 package = Encoding::inputenc;
877 package = Encoding::CJK;
878 else if (p == "japanese")
879 package = Encoding::japanese;
881 lex.printError("Unknown package");
883 LYXERR(Debug::INFO, "Reading encoding " << name);
884 encodinglist[name] = Encoding(name, latexname,
885 guiname, iconvname, fixedwidth, unsafe,
888 if (lex.lex() != et_end)
889 lex.printError("Missing end");
893 lex.printError("Misplaced end");
895 case Lexer::LEX_FEOF:
898 lex.printError("Unknown tag");
903 // Move all information from forcednotselected to forcedselected
904 for (CharSetMap::const_iterator it1 = forcednotselected.begin(); it1 != forcednotselected.end(); ++it1) {
905 for (CharSetMap::iterator it2 = forcedselected.begin(); it2 != forcedselected.end(); ++it2) {
906 if (it2->first != it1->first)
907 it2->second.insert(it1->second.begin(), it1->second.end());