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 (size_t n = 0; n < input.size(); ++n) {
232 char_type const c = input[n];
234 pair<docstring, bool> latex_char = latexChar(c);
235 docstring const latex = latex_char.first;
236 if (terminate && !prefixIs(latex, '\\')
237 && !prefixIs(latex, '{')
238 && !prefixIs(latex, '}')) {
239 // Prevent eating of a following
240 // space or command corruption by
241 // following characters
248 terminate = latex_char.second;
249 } catch (EncodingException & /* e */) {
250 LYXERR0("Uncodable character <" << docstring(1, c)
251 << "> in latexString!");
253 result += "<" + _("LyX Warning: ")
254 + _("uncodable character") + " '";
255 result += docstring(1, input[n]);
258 uncodable += input[n];
261 return make_pair(result, uncodable);
265 vector<char_type> Encoding::symbolsList() const
267 // assure the used encoding is properly initialized
270 // first all those below start_encodable_
271 vector<char_type> symbols;
272 for (char_type c = 0; c < start_encodable_; ++c)
273 symbols.push_back(c);
274 // add all encodable characters
275 copy(encodable_.begin(), encodable_.end(), back_inserter(symbols));
276 // now the ones from the unicodesymbols file that are not already there
277 for (auto const & elem : unicodesymbols) {
278 if (find(symbols.begin(), symbols.end(), elem.first) == symbols.end())
279 symbols.push_back(elem.first);
281 // finally, sort the vector
282 sort(symbols.begin(), symbols.end());
287 bool Encodings::latexMathChar(char_type c, bool mathmode,
288 Encoding const * encoding, docstring & command,
289 bool & needsTermination)
291 command = empty_docstring();
293 if (encoding->encodable(c))
294 command = docstring(1, c);
295 needsTermination = false;
297 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
298 if (it == unicodesymbols.end()) {
299 if (!encoding || command.empty())
300 throw EncodingException(c);
305 // at least one of mathcommand and textcommand is nonempty
306 bool use_math = (mathmode && !it->second.mathcommand().empty()) ||
307 (!mathmode && it->second.textcommand().empty());
309 command = it->second.mathcommand();
310 needsTermination = !it->second.mathnotermination();
313 if (!encoding || command.empty()) {
314 command = it->second.textcommand();
315 needsTermination = !it->second.textnotermination();
326 char_type Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
327 bool & combining, bool & needsTermination, set<string> * req)
329 CharInfoMap::const_iterator const end = unicodesymbols.end();
330 CharInfoMap::const_iterator it = unicodesymbols.begin();
331 for (combining = false; it != end; ++it) {
332 if (it->second.deprecated())
334 docstring const math = it->second.mathcommand();
335 docstring const text = it->second.textcommand();
336 if ((cmdtype & MATH_CMD) && math == cmd) {
337 combining = it->second.combining();
338 needsTermination = !it->second.mathnotermination();
339 if (req && it->second.mathfeature() &&
340 !it->second.mathpreamble().empty())
341 req->insert(it->second.mathpreamble());
344 if ((cmdtype & TEXT_CMD) && text == cmd) {
345 combining = it->second.combining();
346 needsTermination = !it->second.textnotermination();
347 if (req && it->second.textfeature() &&
348 !it->second.textpreamble().empty())
349 req->insert(it->second.textpreamble());
353 needsTermination = false;
358 docstring Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
359 bool & needsTermination, docstring & rem, set<string> * req)
361 needsTermination = false;
362 rem = empty_docstring();
363 bool const mathmode = cmdtype & MATH_CMD;
364 bool const textmode = cmdtype & TEXT_CMD;
366 size_t const cmdend = cmd.size();
368 CharInfoMap::const_iterator const uniend = unicodesymbols.end();
369 for (size_t i = 0, j = 0; j < cmdend; ++j) {
370 // Also get the char after a backslash
371 if (j + 1 < cmdend && cmd[j] == '\\') {
374 // Detect things like \=*{e} as well
375 if (j + 3 < cmdend && cmd[j+1] == '*' &&
381 // position of the last character before a possible macro
384 // If a macro argument follows, get it, too
385 // Do it here only for single character commands. Other
386 // combining commands need this too, but they are handled in
387 // the loop below for performance reasons.
388 if (j + 1 < cmdend && cmd[j + 1] == '{') {
391 while (k < cmdend && count) {
392 k = cmd.find_first_of(from_ascii("{}"), k + 1);
393 // braces may not be balanced
394 if (k == docstring::npos)
401 if (k != docstring::npos)
403 } else if (m + 1 < cmdend && isAlphaASCII(cmd[m])) {
404 while (m + 2 < cmdend && isAlphaASCII(cmd[m+1]))
407 // Start with this substring and try augmenting it when it is
408 // the prefix of some command in the unicodesymbols file
409 docstring subcmd = cmd.substr(i, j - i + 1);
411 CharInfoMap::const_iterator it = unicodesymbols.begin();
412 // First part of subcmd which might be a combining character
413 docstring combcmd = (m == j) ? docstring() : cmd.substr(i, m - i + 1);
414 // The combining character of combcmd if it exists
415 CharInfoMap::const_iterator combining = uniend;
416 size_t unicmd_size = 0;
418 for (; it != uniend; ++it) {
419 if (it->second.deprecated())
421 docstring const math = mathmode ? it->second.mathcommand()
423 docstring const text = textmode ? it->second.textcommand()
425 if (!combcmd.empty() && it->second.combining() &&
426 (math == combcmd || text == combcmd))
428 size_t cur_size = max(math.size(), text.size());
429 // The current math or text unicode command cannot
430 // match, or we already matched a longer one
431 if (cur_size < subcmd.size() || cur_size <= unicmd_size)
434 docstring tmp = subcmd;
436 while (prefixIs(math, tmp) || prefixIs(text, tmp)) {
438 if (k >= cmdend || cur_size <= tmp.size())
446 // The last added char caused a mismatch, because
447 // we didn't exhaust the chars in cmd and didn't
448 // exceed the maximum size of the current unicmd
449 if (k < cmdend && cur_size > tmp.size())
450 tmp.resize(tmp.size() - 1);
452 // If this is an exact match, we found a (longer)
453 // matching entry in the unicodesymbols file.
454 if (math != tmp && text != tmp)
456 // If we found a combining command, we need to append
457 // the macro argument if this has not been done above.
458 if (tmp == combcmd && combining != uniend &&
459 k < cmdend && cmd[k] == '{') {
462 while (l < cmdend && count) {
463 l = cmd.find_first_of(from_ascii("{}"), l + 1);
464 // braces may not be balanced
465 if (l == docstring::npos)
472 if (l != docstring::npos) {
474 subcmd = cmd.substr(i, j - i + 1);
477 // If the entry doesn't start with '\', we take note
478 // of the match and continue (this is not a ultimate
479 // acceptance, as some other entry may match a longer
480 // portion of the cmd string). However, if the entry
481 // does start with '\', we accept the match only if
482 // this is a valid macro, i.e., either it is a single
483 // (nonletter) char macro, or nothing else follows,
484 // or what follows is a nonletter char, or the last
486 else if (tmp[0] != '\\'
487 || (tmp.size() == prefix + 1 &&
488 !isAlphaASCII(tmp[1]) &&
489 (prefix == 1 || !isAlphaASCII(tmp[2])))
491 || !isAlphaASCII(cmd[k])
492 || tmp[tmp.size() - 1] == '}'
497 unicmd_size = cur_size;
499 needsTermination = !it->second.mathnotermination();
501 needsTermination = !it->second.textnotermination();
503 if (math == tmp && it->second.mathfeature() &&
504 !it->second.mathpreamble().empty())
505 req->insert(it->second.mathpreamble());
506 if (text == tmp && it->second.textfeature() &&
507 !it->second.textpreamble().empty())
508 req->insert(it->second.textpreamble());
514 else if (combining != uniend &&
515 prefixIs(subcmd, combcmd + '{')) {
516 // We know that subcmd starts with combcmd and
517 // contains an argument in braces.
518 docstring const arg = subcmd.substr(
519 combcmd.length() + 1,
520 subcmd.length() - combcmd.length() - 2);
521 // If arg is a single character we can construct a
522 // combining sequence.
524 bool argcomb = false;
525 if (arg.size() == 1 && isAlnumASCII(arg[0]))
528 // Use the version of fromLaTeXCommand() that
529 // parses only one command, since we cannot
530 // use more than one character.
533 a = fromLaTeXCommand(arg, cmdtype, argcomb,
535 if (a && req && !argcomb)
536 req->insert(r.begin(), r.end());
539 // In unicode the combining character comes
542 symbols += combining->first;
547 if (j + 1 == cmdend && !unicmd_size) {
548 // No luck. Return what remains
550 if (needsTermination && !rem.empty()) {
551 if (rem.substr(0, 2) == "{}") {
553 needsTermination = false;
554 } else if (rem[0] == ' ') {
555 needsTermination = false;
556 // LaTeX would swallow all spaces
566 CharInfo const & Encodings::unicodeCharInfo(char_type c)
568 static CharInfo empty;
569 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
570 return it != unicodesymbols.end() ? it->second : empty;
574 bool Encodings::isCombiningChar(char_type c)
576 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
577 if (it != unicodesymbols.end())
578 return it->second.combining();
583 string const Encodings::TIPAShortcut(char_type c)
585 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
586 if (it != unicodesymbols.end())
587 return it->second.tipashortcut();
592 string const Encodings::isKnownScriptChar(char_type const c)
594 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
596 if (it == unicodesymbols.end())
598 // FIXME: parse complex textpreamble (may be list or alternatives,
599 // e.g., "subscript,textgreek" or "textcomp|textgreek")
600 if (it->second.textpreamble() == "textgreek"
601 || it->second.textpreamble() == "textcyrillic")
602 return it->second.textpreamble();
607 bool Encodings::fontencSupportsScript(string const & fontenc, string const & script)
609 if (script == "textgreek")
610 return (fontenc == "LGR" || fontenc == "TU");
611 if (script == "textcyrillic")
612 return (fontenc == "T2A" || fontenc == "T2B" || fontenc == "T2C"
613 || fontenc == "X2" || fontenc == "TU");
618 bool Encodings::isMathAlpha(char_type c)
620 return mathalpha.count(c);
624 bool Encodings::isUnicodeTextOnly(char_type c)
626 if (isASCII(c) || isMathAlpha(c))
629 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
630 return it == unicodesymbols.end() || it->second.mathcommand().empty();
635 Encodings::fromLyXName(string const & name, bool allowUnsafe) const
637 EncodingList::const_iterator const it = encodinglist.find(name);
638 if (it == encodinglist.end())
640 if (!allowUnsafe && it->second.unsafe())
647 Encodings::fromLaTeXName(string const & n, int const & p, bool allowUnsafe) const
650 // FIXME: if we have to test for too many of these synonyms,
651 // we should instead extend the format of lib/encodings
655 // We don't use find_if because it makes copies of the pairs in
657 // This linear search is OK since we don't have many encodings.
658 // Users could even optimize it by putting the encodings they use
659 // most at the top of lib/encodings.
660 EncodingList::const_iterator const end = encodinglist.end();
661 for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
662 if ((it->second.latexName() == name) && (it->second.package() & p)
663 && (!it->second.unsafe() || allowUnsafe))
670 Encodings::fromIconvName(string const & n, int const & p, bool allowUnsafe) const
672 EncodingList::const_iterator const end = encodinglist.end();
673 for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
674 if ((it->second.iconvName() == n) && (it->second.package() & p)
675 && (!it->second.unsafe() || allowUnsafe))
681 Encodings::Encodings()
685 void Encodings::read(FileName const & encfile, FileName const & symbolsfile)
687 // We must read the symbolsfile first, because the Encoding
688 // constructor depends on it.
689 CharSetMap forcednotselected;
691 symbolslex.setFile(symbolsfile);
692 bool getNextToken = true;
693 while (symbolslex.isOK()) {
697 if (!symbolslex.next(true))
702 istringstream is(symbolslex.getString());
703 // reading symbol directly does not work if
704 // char_type == wchar_t.
706 if(!(is >> hex >> tmp))
710 if (!symbolslex.next(true))
712 docstring textcommand = symbolslex.getDocString();
713 if (!symbolslex.next(true))
715 string textpreamble = symbolslex.getString();
716 if (!symbolslex.next(true))
718 string sflags = symbolslex.getString();
723 if (suffixIs(textcommand, '}'))
724 flags |= CharInfoTextNoTermination;
725 while (!sflags.empty()) {
727 sflags = split(sflags, flag, ',');
728 if (flag == "combining") {
729 flags |= CharInfoCombining;
730 } else if (flag == "force") {
731 flags |= CharInfoForce;
732 forced.insert(symbol);
733 } else if (prefixIs(flag, "force=")) {
734 vector<string> encs =
735 getVectorFromString(flag.substr(6), ";");
736 for (size_t i = 0; i < encs.size(); ++i)
737 forcedselected[encs[i]].insert(symbol);
738 flags |= CharInfoForceSelected;
739 } else if (prefixIs(flag, "force!=")) {
740 vector<string> encs =
741 getVectorFromString(flag.substr(7), ";");
742 for (size_t i = 0; i < encs.size(); ++i)
743 forcednotselected[encs[i]].insert(symbol);
744 flags |= CharInfoForceSelected;
745 } else if (flag == "mathalpha") {
746 mathalpha.insert(symbol);
747 } else if (flag == "notermination=text") {
748 flags |= CharInfoTextNoTermination;
749 } else if (flag == "notermination=math") {
750 flags |= CharInfoMathNoTermination;
751 } else if (flag == "notermination=both") {
752 flags |= CharInfoTextNoTermination;
753 flags |= CharInfoMathNoTermination;
754 } else if (flag == "notermination=none") {
755 flags &= ~CharInfoTextNoTermination;
756 flags &= ~CharInfoMathNoTermination;
757 } else if (contains(flag, "tipashortcut=")) {
758 tipashortcut = split(flag, '=');
759 } else if (flag == "deprecated") {
760 flags |= CharInfoDeprecated;
762 lyxerr << "Ignoring unknown flag `" << flag
763 << "' for symbol `0x"
764 << hex << symbol << dec
768 // mathcommand and mathpreamble have been added for 1.6.0.
769 // make them optional so that old files still work.
770 int const lineno = symbolslex.lineNumber();
771 bool breakout = false;
772 docstring mathcommand;
774 if (symbolslex.next(true)) {
775 if (symbolslex.lineNumber() != lineno) {
776 // line in old format without mathcommand and mathpreamble
777 getNextToken = false;
779 mathcommand = symbolslex.getDocString();
780 if (suffixIs(mathcommand, '}'))
781 flags |= CharInfoMathNoTermination;
782 if (symbolslex.next(true)) {
783 if (symbolslex.lineNumber() != lineno) {
784 // line in new format with mathcommand only
785 getNextToken = false;
787 // line in new format with mathcommand and mathpreamble
788 mathpreamble = symbolslex.getString();
797 // backward compatibility
798 if (mathpreamble == "esintoramsmath")
799 mathpreamble = "esint|amsmath";
801 if (!textpreamble.empty())
802 if (textpreamble[0] != '\\')
803 flags |= CharInfoTextFeature;
804 if (!mathpreamble.empty())
805 if (mathpreamble[0] != '\\')
806 flags |= CharInfoMathFeature;
808 CharInfo info = CharInfo(
809 textcommand, mathcommand,
810 textpreamble, mathpreamble,
811 tipashortcut, flags);
812 LYXERR(Debug::INFO, "Read unicode symbol " << symbol << " '"
813 << to_utf8(info.textcommand()) << "' '" << info.textpreamble()
814 << " '" << info.textfeature() << ' ' << info.textnotermination()
815 << ' ' << to_utf8(info.mathcommand()) << "' '" << info.mathpreamble()
816 << "' " << info.mathfeature() << ' ' << info.mathnotermination()
817 << ' ' << info.combining() << ' ' << info.force()
818 << ' ' << info.forceselected());
820 // we assume that at least one command is nonempty when using unicodesymbols
821 if (info.isUnicodeSymbol()) {
822 unicodesymbols[symbol] = info;
829 // Now read the encodings
835 LexerKeyword encodingtags[] = {
836 { "encoding", et_encoding },
840 Lexer lex(encodingtags);
841 lex.setFile(encfile);
842 lex.setContext("Encodings::read");
848 string const name = lex.getString();
850 string const latexname = lex.getString();
852 string const guiname = lex.getString();
854 string const iconvname = lex.getString();
856 string const width = lex.getString();
857 bool fixedwidth = false;
859 if (width == "fixed")
861 else if (width == "variable")
863 else if (width == "variableunsafe") {
868 lex.printError("Unknown width");
871 string const p = lex.getString();
872 Encoding::Package package = Encoding::none;
874 package = Encoding::none;
875 else if (p == "inputenc")
876 package = Encoding::inputenc;
878 package = Encoding::CJK;
879 else if (p == "japanese")
880 package = Encoding::japanese;
882 lex.printError("Unknown package");
884 LYXERR(Debug::INFO, "Reading encoding " << name);
885 encodinglist[name] = Encoding(name, latexname,
886 guiname, iconvname, fixedwidth, unsafe,
889 if (lex.lex() != et_end)
890 lex.printError("Missing end");
894 lex.printError("Misplaced end");
896 case Lexer::LEX_FEOF:
899 lex.printError("Unknown tag");
904 // Move all information from forcednotselected to forcedselected
905 for (CharSetMap::const_iterator it1 = forcednotselected.begin(); it1 != forcednotselected.end(); ++it1) {
906 for (CharSetMap::iterator it2 = forcedselected.begin(); it2 != forcedselected.end(); ++it2) {
907 if (it2->first != it1->first)
908 it2->second.insert(it1->second.begin(), it1->second.end());