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"
26 #include <boost/cstdint.hpp>
33 using namespace lyx::support;
37 int const Encoding::any = -1;
41 Encodings::MathCommandSet Encodings::mathcmd;
42 Encodings::TextCommandSet Encodings::textcmd;
43 Encodings::MathSymbolSet Encodings::mathsym;
47 typedef map<char_type, CharInfo> CharInfoMap;
48 CharInfoMap unicodesymbols;
50 typedef set<char_type> CharSet;
51 typedef map<string, CharSet> CharSetMap;
53 CharSetMap forcedselected;
55 typedef set<char_type> MathAlphaSet;
56 MathAlphaSet mathalpha;
59 /// The highest code point in UCS4 encoding (1<<20 + 1<<16)
60 char_type const max_ucs4 = 0x110000;
65 EncodingException::EncodingException(char_type c)
66 : failed_char(c), par_id(0), pos(0)
71 const char * EncodingException::what() const throw()
73 return "Could not find LaTeX command for a character";
78 docstring const & textcommand, docstring const & mathcommand,
79 std::string const & textpreamble, std::string const & mathpreamble,
80 std::string const & tipashortcut, unsigned int flags)
81 : textcommand_(textcommand), mathcommand_(mathcommand),
82 textpreamble_(textpreamble), mathpreamble_(mathpreamble),
83 tipashortcut_(tipashortcut), flags_(flags)
88 Encoding::Encoding(string const & n, string const & l, string const & g,
89 string const & i, bool f, bool u, Encoding::Package p)
90 : name_(n), latexName_(l), guiName_(g), iconvName_(i), fixedwidth_(f),
91 unsafe_(u), forced_(&forcedselected[n]), package_(p)
94 // ASCII can encode 128 code points and nothing else
95 start_encodable_ = 128;
97 } else if (i == "UTF-8") {
98 // UTF8 can encode all UCS4 code points
99 start_encodable_ = max_ucs4;
102 start_encodable_ = 0;
108 void Encoding::init() const
110 // Since the the constructor is the only method which sets complete_
111 // to false the test for complete_ is thread-safe without mutex.
116 Mutex::Locker lock(&mutex);
118 // We need to test again for complete_, since another thread could
119 // have set it to true while we were waiting for the lock and we must
120 // not modify an encoding which is already complete.
124 // We do not make any member mutable so that it can be easily verified
125 // that all const methods are thread-safe: init() is the only const
126 // method which changes complete_, encodable_ and start_encodable_, and
127 // it uses a mutex to ensure thread-safety.
128 CharSet & encodable = const_cast<Encoding *>(this)->encodable_;
129 char_type & start_encodable = const_cast<Encoding *>(this)->start_encodable_;
132 // temporarily switch off lyxerr, since we will generate iconv errors
135 // We do not need to check all UCS4 code points, it is enough
136 // if we check all 256 code points of this encoding.
137 for (unsigned short j = 0; j < 256; ++j) {
138 char const c = char(j);
139 vector<char_type> const ucs4 = eightbit_to_ucs4(&c, 1, iconvName_);
140 if (ucs4.size() != 1)
142 char_type const uc = ucs4[0];
143 CharInfoMap::const_iterator const it = unicodesymbols.find(uc);
144 if (it == unicodesymbols.end())
145 encodable.insert(uc);
146 else if (!it->second.force()) {
147 if (forced_->empty() || forced_->find(uc) == forced_->end())
148 encodable.insert(uc);
152 // We do not know how many code points this encoding has, and
153 // they do not have a direct representation as a single byte,
154 // therefore we need to check all UCS4 code points.
155 // This is expensive!
156 for (char_type c = 0; c < max_ucs4; ++c) {
157 vector<char> const eightbit = ucs4_to_eightbit(&c, 1, iconvName_);
158 if (!eightbit.empty()) {
159 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
160 if (it == unicodesymbols.end())
162 else if (!it->second.force()) {
163 if (forced_->empty() || forced_->find(c) == forced_->end())
170 CharSet::iterator it = encodable.find(start_encodable);
171 while (it != encodable.end()) {
174 it = encodable.find(start_encodable);
176 const_cast<Encoding *>(this)->complete_ = true;
180 bool Encoding::isForced(char_type c) const
182 if (!forced.empty() && forced.find(c) != forced.end())
184 return !forced_->empty() && forced_->find(c) != forced_->end();
188 bool Encoding::encodable(char_type c) const
190 // assure the used encoding is properly initialized
193 if (iconvName_ == "UTF-8" && package_ == none)
195 if (c < start_encodable_ && !isForced(c))
197 if (encodable_.find(c) != encodable_.end())
203 pair<docstring, bool> Encoding::latexChar(char_type c) const
206 return make_pair(docstring(1, c), false);
208 // c cannot (or should not) be encoded in this encoding
209 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
210 if (it == unicodesymbols.end())
211 throw EncodingException(c);
212 // at least one of mathcommand and textcommand is nonempty
213 if (it->second.textcommand().empty())
215 "\\ensuremath{" + it->second.mathcommand() + '}', false);
216 return make_pair(it->second.textcommand(), !it->second.textnotermination());
220 pair<docstring, docstring> Encoding::latexString(docstring const & input, bool dryrun) const
224 bool terminate = false;
225 for (size_t n = 0; n < input.size(); ++n) {
227 char_type const c = input[n];
228 pair<docstring, bool> latex_char = latexChar(c);
229 docstring const latex = latex_char.first;
230 if (terminate && !prefixIs(latex, '\\')
231 && !prefixIs(latex, '{')
232 && !prefixIs(latex, '}')) {
233 // Prevent eating of a following
234 // space or command corruption by
235 // following characters
242 terminate = latex_char.second;
243 } catch (EncodingException & /* e */) {
244 LYXERR0("Uncodable character in latexString!");
246 result += "<" + _("LyX Warning: ")
247 + _("uncodable character") + " '";
248 result += docstring(1, input[n]);
251 uncodable += input[n];
254 return make_pair(result, uncodable);
258 vector<char_type> Encoding::symbolsList() const
260 // assure the used encoding is properly initialized
263 // first all those below start_encodable_
264 vector<char_type> symbols;
265 for (char_type c = 0; c < start_encodable_; ++c)
266 symbols.push_back(c);
267 // add all encodable characters
268 copy(encodable_.begin(), encodable_.end(), back_inserter(symbols));
269 // now the ones from the unicodesymbols file that are not already there
270 for (pair<char_type, CharInfo> const & elem : unicodesymbols) {
271 if (find(symbols.begin(), symbols.end(), elem.first) == symbols.end())
272 symbols.push_back(elem.first);
274 // finally, sort the vector
275 sort(symbols.begin(), symbols.end());
280 bool Encodings::latexMathChar(char_type c, bool mathmode,
281 Encoding const * encoding, docstring & command,
282 bool & needsTermination)
284 command = empty_docstring();
286 if (encoding->encodable(c))
287 command = docstring(1, c);
288 needsTermination = false;
290 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
291 if (it == unicodesymbols.end()) {
292 if (!encoding || command.empty())
293 throw EncodingException(c);
298 // at least one of mathcommand and textcommand is nonempty
299 bool use_math = (mathmode && !it->second.mathcommand().empty()) ||
300 (!mathmode && it->second.textcommand().empty());
302 command = it->second.mathcommand();
303 needsTermination = !it->second.mathnotermination();
306 if (!encoding || command.empty()) {
307 command = it->second.textcommand();
308 needsTermination = !it->second.textnotermination();
318 char_type Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
319 bool & combining, bool & needsTermination, set<string> * req)
321 CharInfoMap::const_iterator const end = unicodesymbols.end();
322 CharInfoMap::const_iterator it = unicodesymbols.begin();
323 for (combining = false; it != end; ++it) {
324 if (it->second.deprecated())
326 docstring const math = it->second.mathcommand();
327 docstring const text = it->second.textcommand();
328 if ((cmdtype & MATH_CMD) && math == cmd) {
329 combining = it->second.combining();
330 needsTermination = !it->second.mathnotermination();
331 if (req && it->second.mathfeature() &&
332 !it->second.mathpreamble().empty())
333 req->insert(it->second.mathpreamble());
336 if ((cmdtype & TEXT_CMD) && text == cmd) {
337 combining = it->second.combining();
338 needsTermination = !it->second.textnotermination();
339 if (req && it->second.textfeature() &&
340 !it->second.textpreamble().empty())
341 req->insert(it->second.textpreamble());
345 needsTermination = false;
350 docstring Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
351 bool & needsTermination, docstring & rem, set<string> * req)
353 needsTermination = false;
354 rem = empty_docstring();
355 bool const mathmode = cmdtype & MATH_CMD;
356 bool const textmode = cmdtype & TEXT_CMD;
358 size_t const cmdend = cmd.size();
360 CharInfoMap::const_iterator const uniend = unicodesymbols.end();
361 for (size_t i = 0, j = 0; j < cmdend; ++j) {
362 // Also get the char after a backslash
363 if (j + 1 < cmdend && cmd[j] == '\\') {
366 // Detect things like \=*{e} as well
367 if (j + 3 < cmdend && cmd[j+1] == '*' &&
373 // position of the last character before a possible macro
376 // If a macro argument follows, get it, too
377 // Do it here only for single character commands. Other
378 // combining commands need this too, but they are handled in
379 // the loop below for performance reasons.
380 if (j + 1 < cmdend && cmd[j + 1] == '{') {
383 while (k < cmdend && count) {
384 k = cmd.find_first_of(from_ascii("{}"), k + 1);
385 // braces may not be balanced
386 if (k == docstring::npos)
393 if (k != docstring::npos)
395 } else if (m + 1 < cmdend && isAlphaASCII(cmd[m])) {
396 while (m + 2 < cmdend && isAlphaASCII(cmd[m+1]))
399 // Start with this substring and try augmenting it when it is
400 // the prefix of some command in the unicodesymbols file
401 docstring subcmd = cmd.substr(i, j - i + 1);
403 CharInfoMap::const_iterator it = unicodesymbols.begin();
404 // First part of subcmd which might be a combining character
405 docstring combcmd = (m == j) ? docstring() : cmd.substr(i, m - i + 1);
406 // The combining character of combcmd if it exists
407 CharInfoMap::const_iterator combining = uniend;
408 size_t unicmd_size = 0;
410 for (; it != uniend; ++it) {
411 if (it->second.deprecated())
413 docstring const math = mathmode ? it->second.mathcommand()
415 docstring const text = textmode ? it->second.textcommand()
417 if (!combcmd.empty() && it->second.combining() &&
418 (math == combcmd || text == combcmd))
420 size_t cur_size = max(math.size(), text.size());
421 // The current math or text unicode command cannot
422 // match, or we already matched a longer one
423 if (cur_size < subcmd.size() || cur_size <= unicmd_size)
426 docstring tmp = subcmd;
428 while (prefixIs(math, tmp) || prefixIs(text, tmp)) {
430 if (k >= cmdend || cur_size <= tmp.size())
438 // The last added char caused a mismatch, because
439 // we didn't exhaust the chars in cmd and didn't
440 // exceed the maximum size of the current unicmd
441 if (k < cmdend && cur_size > tmp.size())
442 tmp.resize(tmp.size() - 1);
444 // If this is an exact match, we found a (longer)
445 // matching entry in the unicodesymbols file.
446 if (math != tmp && text != tmp)
448 // If we found a combining command, we need to append
449 // the macro argument if this has not been done above.
450 if (tmp == combcmd && combining != uniend &&
451 k < cmdend && cmd[k] == '{') {
454 while (l < cmdend && count) {
455 l = cmd.find_first_of(from_ascii("{}"), l + 1);
456 // braces may not be balanced
457 if (l == docstring::npos)
464 if (l != docstring::npos) {
466 subcmd = cmd.substr(i, j - i + 1);
469 // If the entry doesn't start with '\', we take note
470 // of the match and continue (this is not a ultimate
471 // acceptance, as some other entry may match a longer
472 // portion of the cmd string). However, if the entry
473 // does start with '\', we accept the match only if
474 // this is a valid macro, i.e., either it is a single
475 // (nonletter) char macro, or nothing else follows,
476 // or what follows is a nonletter char, or the last
478 else if (tmp[0] != '\\'
479 || (tmp.size() == prefix + 1 &&
480 !isAlphaASCII(tmp[1]) &&
481 (prefix == 1 || !isAlphaASCII(tmp[2])))
483 || !isAlphaASCII(cmd[k])
484 || tmp[tmp.size() - 1] == '}'
489 unicmd_size = cur_size;
491 needsTermination = !it->second.mathnotermination();
493 needsTermination = !it->second.textnotermination();
495 if (math == tmp && it->second.mathfeature() &&
496 !it->second.mathpreamble().empty())
497 req->insert(it->second.mathpreamble());
498 if (text == tmp && it->second.textfeature() &&
499 !it->second.textpreamble().empty())
500 req->insert(it->second.textpreamble());
506 else if (combining != uniend &&
507 prefixIs(subcmd, combcmd + '{')) {
508 // We know that subcmd starts with combcmd and
509 // contains an argument in braces.
510 docstring const arg = subcmd.substr(
511 combcmd.length() + 1,
512 subcmd.length() - combcmd.length() - 2);
513 // If arg is a single character we can construct a
514 // combining sequence.
516 bool argcomb = false;
517 if (arg.size() == 1 && isAlnumASCII(arg[0]))
520 // Use the version of fromLaTeXCommand() that
521 // parses only one command, since we cannot
522 // use more than one character.
525 a = fromLaTeXCommand(arg, cmdtype, argcomb,
527 if (a && req && !argcomb)
528 req->insert(r.begin(), r.end());
531 // In unicode the combining character comes
534 symbols += combining->first;
539 if (j + 1 == cmdend && !unicmd_size) {
540 // No luck. Return what remains
542 if (needsTermination && !rem.empty()) {
543 if (rem.substr(0, 2) == "{}") {
545 needsTermination = false;
546 } else if (rem[0] == ' ') {
547 needsTermination = false;
548 // LaTeX would swallow all spaces
558 CharInfo const & Encodings::unicodeCharInfo(char_type c)
560 static CharInfo empty;
561 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
562 return it != unicodesymbols.end() ? it->second : empty;
566 bool Encodings::isCombiningChar(char_type c)
568 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
569 if (it != unicodesymbols.end())
570 return it->second.combining();
575 string const Encodings::TIPAShortcut(char_type c)
577 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
578 if (it != unicodesymbols.end())
579 return it->second.tipashortcut();
584 bool Encodings::isKnownScriptChar(char_type const c, string & preamble)
586 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
588 if (it == unicodesymbols.end())
591 if (it->second.textpreamble() != "textgreek" && it->second.textpreamble() != "textcyr")
594 if (preamble.empty()) {
595 preamble = it->second.textpreamble();
598 return it->second.textpreamble() == preamble;
602 bool Encodings::isMathAlpha(char_type c)
604 return mathalpha.count(c);
608 bool Encodings::isUnicodeTextOnly(char_type c)
610 if (isASCII(c) || isMathAlpha(c))
613 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
614 return it == unicodesymbols.end() || it->second.mathcommand().empty();
619 Encodings::fromLyXName(string const & name, bool allowUnsafe) const
621 EncodingList::const_iterator const it = encodinglist.find(name);
622 if (it == encodinglist.end())
624 if (!allowUnsafe && it->second.unsafe())
631 Encodings::fromLaTeXName(string const & n, int const & p, bool allowUnsafe) const
634 // FIXME: if we have to test for too many of these synonyms,
635 // we should instead extend the format of lib/encodings
639 // We don't use find_if because it makes copies of the pairs in
641 // This linear search is OK since we don't have many encodings.
642 // Users could even optimize it by putting the encodings they use
643 // most at the top of lib/encodings.
644 EncodingList::const_iterator const end = encodinglist.end();
645 for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
646 if ((it->second.latexName() == name) && (it->second.package() & p)
647 && (!it->second.unsafe() || allowUnsafe))
654 Encodings::fromIconvName(string const & n, int const & p, bool allowUnsafe) const
656 EncodingList::const_iterator const end = encodinglist.end();
657 for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
658 if ((it->second.iconvName() == n) && (it->second.package() & p)
659 && (!it->second.unsafe() || allowUnsafe))
665 Encodings::Encodings()
669 void Encodings::read(FileName const & encfile, FileName const & symbolsfile)
671 // We must read the symbolsfile first, because the Encoding
672 // constructor depends on it.
673 CharSetMap forcednotselected;
675 symbolslex.setFile(symbolsfile);
676 bool getNextToken = true;
677 while (symbolslex.isOK()) {
681 if (!symbolslex.next(true))
686 istringstream is(symbolslex.getString());
687 // reading symbol directly does not work if
688 // char_type == wchar_t.
690 if(!(is >> hex >> tmp))
694 if (!symbolslex.next(true))
696 docstring textcommand = symbolslex.getDocString();
697 if (!symbolslex.next(true))
699 string textpreamble = symbolslex.getString();
700 if (!symbolslex.next(true))
702 string sflags = symbolslex.getString();
707 if (suffixIs(textcommand, '}'))
708 flags |= CharInfoTextNoTermination;
709 while (!sflags.empty()) {
711 sflags = split(sflags, flag, ',');
712 if (flag == "combining") {
713 flags |= CharInfoCombining;
714 } else if (flag == "force") {
715 flags |= CharInfoForce;
716 forced.insert(symbol);
717 } else if (prefixIs(flag, "force=")) {
718 vector<string> encodings =
719 getVectorFromString(flag.substr(6), ";");
720 for (size_t i = 0; i < encodings.size(); ++i)
721 forcedselected[encodings[i]].insert(symbol);
722 flags |= CharInfoForceSelected;
723 } else if (prefixIs(flag, "force!=")) {
724 vector<string> encodings =
725 getVectorFromString(flag.substr(7), ";");
726 for (size_t i = 0; i < encodings.size(); ++i)
727 forcednotselected[encodings[i]].insert(symbol);
728 flags |= CharInfoForceSelected;
729 } else if (flag == "mathalpha") {
730 mathalpha.insert(symbol);
731 } else if (flag == "notermination=text") {
732 flags |= CharInfoTextNoTermination;
733 } else if (flag == "notermination=math") {
734 flags |= CharInfoMathNoTermination;
735 } else if (flag == "notermination=both") {
736 flags |= CharInfoTextNoTermination;
737 flags |= CharInfoMathNoTermination;
738 } else if (flag == "notermination=none") {
739 flags &= ~CharInfoTextNoTermination;
740 flags &= ~CharInfoMathNoTermination;
741 } else if (contains(flag, "tipashortcut=")) {
742 tipashortcut = split(flag, '=');
743 } else if (flag == "deprecated") {
744 flags |= CharInfoDeprecated;
746 lyxerr << "Ignoring unknown flag `" << flag
747 << "' for symbol `0x"
748 << hex << symbol << dec
752 // mathcommand and mathpreamble have been added for 1.6.0.
753 // make them optional so that old files still work.
754 int const lineno = symbolslex.lineNumber();
755 bool breakout = false;
756 docstring mathcommand;
758 if (symbolslex.next(true)) {
759 if (symbolslex.lineNumber() != lineno) {
760 // line in old format without mathcommand and mathpreamble
761 getNextToken = false;
763 mathcommand = symbolslex.getDocString();
764 if (suffixIs(mathcommand, '}'))
765 flags |= CharInfoMathNoTermination;
766 if (symbolslex.next(true)) {
767 if (symbolslex.lineNumber() != lineno) {
768 // line in new format with mathcommand only
769 getNextToken = false;
771 // line in new format with mathcommand and mathpreamble
772 mathpreamble = symbolslex.getString();
781 // backward compatibility
782 if (mathpreamble == "esintoramsmath")
783 mathpreamble = "esint|amsmath";
785 if (!textpreamble.empty())
786 if (textpreamble[0] != '\\')
787 flags |= CharInfoTextFeature;
788 if (!mathpreamble.empty())
789 if (mathpreamble[0] != '\\')
790 flags |= CharInfoMathFeature;
792 CharInfo info = CharInfo(
793 textcommand, mathcommand,
794 textpreamble, mathpreamble,
795 tipashortcut, flags);
796 LYXERR(Debug::INFO, "Read unicode symbol " << symbol << " '"
797 << to_utf8(info.textcommand()) << "' '" << info.textpreamble()
798 << " '" << info.textfeature() << ' ' << info.textnotermination()
799 << ' ' << to_utf8(info.mathcommand()) << "' '" << info.mathpreamble()
800 << "' " << info.mathfeature() << ' ' << info.mathnotermination()
801 << ' ' << info.combining() << ' ' << info.force()
802 << ' ' << info.forceselected());
804 // we assume that at least one command is nonempty when using unicodesymbols
805 if (info.isUnicodeSymbol()) {
806 unicodesymbols[symbol] = info;
813 // Now read the encodings
819 LexerKeyword encodingtags[] = {
820 { "encoding", et_encoding },
824 Lexer lex(encodingtags);
825 lex.setFile(encfile);
826 lex.setContext("Encodings::read");
832 string const name = lex.getString();
834 string const latexname = lex.getString();
836 string const guiname = lex.getString();
838 string const iconvname = lex.getString();
840 string const width = lex.getString();
841 bool fixedwidth = false;
843 if (width == "fixed")
845 else if (width == "variable")
847 else if (width == "variableunsafe") {
852 lex.printError("Unknown width");
855 string const p = lex.getString();
856 Encoding::Package package = Encoding::none;
858 package = Encoding::none;
859 else if (p == "inputenc")
860 package = Encoding::inputenc;
862 package = Encoding::CJK;
863 else if (p == "japanese")
864 package = Encoding::japanese;
866 lex.printError("Unknown package");
868 LYXERR(Debug::INFO, "Reading encoding " << name);
869 encodinglist[name] = Encoding(name, latexname,
870 guiname, iconvname, fixedwidth, unsafe,
873 if (lex.lex() != et_end)
874 lex.printError("Missing end");
878 lex.printError("Misplaced end");
880 case Lexer::LEX_FEOF:
883 lex.printError("Unknown tag");
888 // Move all information from forcednotselected to forcedselected
889 for (CharSetMap::const_iterator it1 = forcednotselected.begin(); it1 != forcednotselected.end(); ++it1) {
890 for (CharSetMap::iterator it2 = forcedselected.begin(); it2 != forcedselected.end(); ++it2) {
891 if (it2->first != it1->first)
892 it2->second.insert(it1->second.begin(), it1->second.end());