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();
319 char_type Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
320 bool & combining, bool & needsTermination, set<string> * req)
322 CharInfoMap::const_iterator const end = unicodesymbols.end();
323 CharInfoMap::const_iterator it = unicodesymbols.begin();
324 for (combining = false; it != end; ++it) {
325 if (it->second.deprecated())
327 docstring const math = it->second.mathcommand();
328 docstring const text = it->second.textcommand();
329 if ((cmdtype & MATH_CMD) && math == cmd) {
330 combining = it->second.combining();
331 needsTermination = !it->second.mathnotermination();
332 if (req && it->second.mathfeature() &&
333 !it->second.mathpreamble().empty())
334 req->insert(it->second.mathpreamble());
337 if ((cmdtype & TEXT_CMD) && text == cmd) {
338 combining = it->second.combining();
339 needsTermination = !it->second.textnotermination();
340 if (req && it->second.textfeature() &&
341 !it->second.textpreamble().empty())
342 req->insert(it->second.textpreamble());
346 needsTermination = false;
351 docstring Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
352 bool & needsTermination, docstring & rem, set<string> * req)
354 needsTermination = false;
355 rem = empty_docstring();
356 bool const mathmode = cmdtype & MATH_CMD;
357 bool const textmode = cmdtype & TEXT_CMD;
359 size_t const cmdend = cmd.size();
361 CharInfoMap::const_iterator const uniend = unicodesymbols.end();
362 for (size_t i = 0, j = 0; j < cmdend; ++j) {
363 // Also get the char after a backslash
364 if (j + 1 < cmdend && cmd[j] == '\\') {
367 // Detect things like \=*{e} as well
368 if (j + 3 < cmdend && cmd[j+1] == '*' &&
374 // position of the last character before a possible macro
377 // If a macro argument follows, get it, too
378 // Do it here only for single character commands. Other
379 // combining commands need this too, but they are handled in
380 // the loop below for performance reasons.
381 if (j + 1 < cmdend && cmd[j + 1] == '{') {
384 while (k < cmdend && count) {
385 k = cmd.find_first_of(from_ascii("{}"), k + 1);
386 // braces may not be balanced
387 if (k == docstring::npos)
394 if (k != docstring::npos)
396 } else if (m + 1 < cmdend && isAlphaASCII(cmd[m])) {
397 while (m + 2 < cmdend && isAlphaASCII(cmd[m+1]))
400 // Start with this substring and try augmenting it when it is
401 // the prefix of some command in the unicodesymbols file
402 docstring subcmd = cmd.substr(i, j - i + 1);
404 CharInfoMap::const_iterator it = unicodesymbols.begin();
405 // First part of subcmd which might be a combining character
406 docstring combcmd = (m == j) ? docstring() : cmd.substr(i, m - i + 1);
407 // The combining character of combcmd if it exists
408 CharInfoMap::const_iterator combining = uniend;
409 size_t unicmd_size = 0;
411 for (; it != uniend; ++it) {
412 if (it->second.deprecated())
414 docstring const math = mathmode ? it->second.mathcommand()
416 docstring const text = textmode ? it->second.textcommand()
418 if (!combcmd.empty() && it->second.combining() &&
419 (math == combcmd || text == combcmd))
421 size_t cur_size = max(math.size(), text.size());
422 // The current math or text unicode command cannot
423 // match, or we already matched a longer one
424 if (cur_size < subcmd.size() || cur_size <= unicmd_size)
427 docstring tmp = subcmd;
429 while (prefixIs(math, tmp) || prefixIs(text, tmp)) {
431 if (k >= cmdend || cur_size <= tmp.size())
439 // The last added char caused a mismatch, because
440 // we didn't exhaust the chars in cmd and didn't
441 // exceed the maximum size of the current unicmd
442 if (k < cmdend && cur_size > tmp.size())
443 tmp.resize(tmp.size() - 1);
445 // If this is an exact match, we found a (longer)
446 // matching entry in the unicodesymbols file.
447 if (math != tmp && text != tmp)
449 // If we found a combining command, we need to append
450 // the macro argument if this has not been done above.
451 if (tmp == combcmd && combining != uniend &&
452 k < cmdend && cmd[k] == '{') {
455 while (l < cmdend && count) {
456 l = cmd.find_first_of(from_ascii("{}"), l + 1);
457 // braces may not be balanced
458 if (l == docstring::npos)
465 if (l != docstring::npos) {
467 subcmd = cmd.substr(i, j - i + 1);
470 // If the entry doesn't start with '\', we take note
471 // of the match and continue (this is not a ultimate
472 // acceptance, as some other entry may match a longer
473 // portion of the cmd string). However, if the entry
474 // does start with '\', we accept the match only if
475 // this is a valid macro, i.e., either it is a single
476 // (nonletter) char macro, or nothing else follows,
477 // or what follows is a nonletter char, or the last
479 else if (tmp[0] != '\\'
480 || (tmp.size() == prefix + 1 &&
481 !isAlphaASCII(tmp[1]) &&
482 (prefix == 1 || !isAlphaASCII(tmp[2])))
484 || !isAlphaASCII(cmd[k])
485 || tmp[tmp.size() - 1] == '}'
490 unicmd_size = cur_size;
492 needsTermination = !it->second.mathnotermination();
494 needsTermination = !it->second.textnotermination();
496 if (math == tmp && it->second.mathfeature() &&
497 !it->second.mathpreamble().empty())
498 req->insert(it->second.mathpreamble());
499 if (text == tmp && it->second.textfeature() &&
500 !it->second.textpreamble().empty())
501 req->insert(it->second.textpreamble());
507 else if (combining != uniend &&
508 prefixIs(subcmd, combcmd + '{')) {
509 // We know that subcmd starts with combcmd and
510 // contains an argument in braces.
511 docstring const arg = subcmd.substr(
512 combcmd.length() + 1,
513 subcmd.length() - combcmd.length() - 2);
514 // If arg is a single character we can construct a
515 // combining sequence.
517 bool argcomb = false;
518 if (arg.size() == 1 && isAlnumASCII(arg[0]))
521 // Use the version of fromLaTeXCommand() that
522 // parses only one command, since we cannot
523 // use more than one character.
526 a = fromLaTeXCommand(arg, cmdtype, argcomb,
528 if (a && req && !argcomb)
529 req->insert(r.begin(), r.end());
532 // In unicode the combining character comes
535 symbols += combining->first;
540 if (j + 1 == cmdend && !unicmd_size) {
541 // No luck. Return what remains
543 if (needsTermination && !rem.empty()) {
544 if (rem.substr(0, 2) == "{}") {
546 needsTermination = false;
547 } else if (rem[0] == ' ') {
548 needsTermination = false;
549 // LaTeX would swallow all spaces
559 CharInfo const & Encodings::unicodeCharInfo(char_type c)
561 static CharInfo empty;
562 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
563 return it != unicodesymbols.end() ? it->second : empty;
567 bool Encodings::isCombiningChar(char_type c)
569 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
570 if (it != unicodesymbols.end())
571 return it->second.combining();
576 string const Encodings::TIPAShortcut(char_type c)
578 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
579 if (it != unicodesymbols.end())
580 return it->second.tipashortcut();
585 string const Encodings::isKnownScriptChar(char_type const c)
587 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
589 if (it == unicodesymbols.end())
591 // FIXME: parse complex textpreamble (may be list or alternatives,
592 // e.g., "subscript,textgreek" or "textcomp|textgreek")
593 if (it->second.textpreamble() == "textgreek"
594 || it->second.textpreamble() == "textcyrillic")
595 return it->second.textpreamble();
600 bool Encodings::fontencSupportsScript(string const & fontenc, string const & script)
602 if (script == "textgreek")
603 return (fontenc == "LGR" || fontenc == "TU");
604 if (script == "textcyrillic")
605 return (fontenc == "T2A" || fontenc == "T2B" || fontenc == "T2C"
606 || fontenc == "X2" || fontenc == "TU");
611 bool Encodings::isMathAlpha(char_type c)
613 return mathalpha.count(c);
617 bool Encodings::isUnicodeTextOnly(char_type c)
619 if (isASCII(c) || isMathAlpha(c))
622 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
623 return it == unicodesymbols.end() || it->second.mathcommand().empty();
628 Encodings::fromLyXName(string const & name, bool allowUnsafe) const
630 EncodingList::const_iterator const it = encodinglist.find(name);
631 if (it == encodinglist.end())
633 if (!allowUnsafe && it->second.unsafe())
640 Encodings::fromLaTeXName(string const & n, int const & p, bool allowUnsafe) const
643 // FIXME: if we have to test for too many of these synonyms,
644 // we should instead extend the format of lib/encodings
648 // We don't use find_if because it makes copies of the pairs in
650 // This linear search is OK since we don't have many encodings.
651 // Users could even optimize it by putting the encodings they use
652 // most at the top of lib/encodings.
653 EncodingList::const_iterator const end = encodinglist.end();
654 for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
655 if ((it->second.latexName() == name) && (it->second.package() & p)
656 && (!it->second.unsafe() || allowUnsafe))
663 Encodings::fromIconvName(string const & n, int const & p, bool allowUnsafe) const
665 EncodingList::const_iterator const end = encodinglist.end();
666 for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
667 if ((it->second.iconvName() == n) && (it->second.package() & p)
668 && (!it->second.unsafe() || allowUnsafe))
674 Encodings::Encodings()
678 void Encodings::read(FileName const & encfile, FileName const & symbolsfile)
680 // We must read the symbolsfile first, because the Encoding
681 // constructor depends on it.
682 CharSetMap forcednotselected;
684 symbolslex.setFile(symbolsfile);
685 bool getNextToken = true;
686 while (symbolslex.isOK()) {
690 if (!symbolslex.next(true))
695 istringstream is(symbolslex.getString());
696 // reading symbol directly does not work if
697 // char_type == wchar_t.
699 if(!(is >> hex >> tmp))
703 if (!symbolslex.next(true))
705 docstring textcommand = symbolslex.getDocString();
706 if (!symbolslex.next(true))
708 string textpreamble = symbolslex.getString();
709 if (!symbolslex.next(true))
711 string sflags = symbolslex.getString();
716 if (suffixIs(textcommand, '}'))
717 flags |= CharInfoTextNoTermination;
718 while (!sflags.empty()) {
720 sflags = split(sflags, flag, ',');
721 if (flag == "combining") {
722 flags |= CharInfoCombining;
723 } else if (flag == "force") {
724 flags |= CharInfoForce;
725 forced.insert(symbol);
726 } else if (prefixIs(flag, "force=")) {
727 vector<string> encs =
728 getVectorFromString(flag.substr(6), ";");
729 for (size_t i = 0; i < encs.size(); ++i)
730 forcedselected[encs[i]].insert(symbol);
731 flags |= CharInfoForceSelected;
732 } else if (prefixIs(flag, "force!=")) {
733 vector<string> encs =
734 getVectorFromString(flag.substr(7), ";");
735 for (size_t i = 0; i < encs.size(); ++i)
736 forcednotselected[encs[i]].insert(symbol);
737 flags |= CharInfoForceSelected;
738 } else if (flag == "mathalpha") {
739 mathalpha.insert(symbol);
740 } else if (flag == "notermination=text") {
741 flags |= CharInfoTextNoTermination;
742 } else if (flag == "notermination=math") {
743 flags |= CharInfoMathNoTermination;
744 } else if (flag == "notermination=both") {
745 flags |= CharInfoTextNoTermination;
746 flags |= CharInfoMathNoTermination;
747 } else if (flag == "notermination=none") {
748 flags &= ~CharInfoTextNoTermination;
749 flags &= ~CharInfoMathNoTermination;
750 } else if (contains(flag, "tipashortcut=")) {
751 tipashortcut = split(flag, '=');
752 } else if (flag == "deprecated") {
753 flags |= CharInfoDeprecated;
755 lyxerr << "Ignoring unknown flag `" << flag
756 << "' for symbol `0x"
757 << hex << symbol << dec
761 // mathcommand and mathpreamble have been added for 1.6.0.
762 // make them optional so that old files still work.
763 int const lineno = symbolslex.lineNumber();
764 bool breakout = false;
765 docstring mathcommand;
767 if (symbolslex.next(true)) {
768 if (symbolslex.lineNumber() != lineno) {
769 // line in old format without mathcommand and mathpreamble
770 getNextToken = false;
772 mathcommand = symbolslex.getDocString();
773 if (suffixIs(mathcommand, '}'))
774 flags |= CharInfoMathNoTermination;
775 if (symbolslex.next(true)) {
776 if (symbolslex.lineNumber() != lineno) {
777 // line in new format with mathcommand only
778 getNextToken = false;
780 // line in new format with mathcommand and mathpreamble
781 mathpreamble = symbolslex.getString();
790 // backward compatibility
791 if (mathpreamble == "esintoramsmath")
792 mathpreamble = "esint|amsmath";
794 if (!textpreamble.empty())
795 if (textpreamble[0] != '\\')
796 flags |= CharInfoTextFeature;
797 if (!mathpreamble.empty())
798 if (mathpreamble[0] != '\\')
799 flags |= CharInfoMathFeature;
801 CharInfo info = CharInfo(
802 textcommand, mathcommand,
803 textpreamble, mathpreamble,
804 tipashortcut, flags);
805 LYXERR(Debug::INFO, "Read unicode symbol " << symbol << " '"
806 << to_utf8(info.textcommand()) << "' '" << info.textpreamble()
807 << " '" << info.textfeature() << ' ' << info.textnotermination()
808 << ' ' << to_utf8(info.mathcommand()) << "' '" << info.mathpreamble()
809 << "' " << info.mathfeature() << ' ' << info.mathnotermination()
810 << ' ' << info.combining() << ' ' << info.force()
811 << ' ' << info.forceselected());
813 // we assume that at least one command is nonempty when using unicodesymbols
814 if (info.isUnicodeSymbol()) {
815 unicodesymbols[symbol] = info;
822 // Now read the encodings
828 LexerKeyword encodingtags[] = {
829 { "encoding", et_encoding },
833 Lexer lex(encodingtags);
834 lex.setFile(encfile);
835 lex.setContext("Encodings::read");
841 string const name = lex.getString();
843 string const latexname = lex.getString();
845 string const guiname = lex.getString();
847 string const iconvname = lex.getString();
849 string const width = lex.getString();
850 bool fixedwidth = false;
852 if (width == "fixed")
854 else if (width == "variable")
856 else if (width == "variableunsafe") {
861 lex.printError("Unknown width");
864 string const p = lex.getString();
865 Encoding::Package package = Encoding::none;
867 package = Encoding::none;
868 else if (p == "inputenc")
869 package = Encoding::inputenc;
871 package = Encoding::CJK;
872 else if (p == "japanese")
873 package = Encoding::japanese;
875 lex.printError("Unknown package");
877 LYXERR(Debug::INFO, "Reading encoding " << name);
878 encodinglist[name] = Encoding(name, latexname,
879 guiname, iconvname, fixedwidth, unsafe,
882 if (lex.lex() != et_end)
883 lex.printError("Missing end");
887 lex.printError("Misplaced end");
889 case Lexer::LEX_FEOF:
892 lex.printError("Unknown tag");
897 // Move all information from forcednotselected to forcedselected
898 for (CharSetMap::const_iterator it1 = forcednotselected.begin(); it1 != forcednotselected.end(); ++it1) {
899 for (CharSetMap::iterator it2 = forcedselected.begin(); it2 != forcedselected.end(); ++it2) {
900 if (it2->first != it1->first)
901 it2->second.insert(it1->second.begin(), it1->second.end());