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 string const Encodings::isKnownScriptChar(char_type const c)
586 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
588 if (it == unicodesymbols.end())
590 // FIXME: parse complex textpreamble (may be list or alternatives,
591 // e.g., "subscript,textgreek" or "textcomp|textgreek")
592 if (it->second.textpreamble() == "textgreek"
593 || it->second.textpreamble() == "textcyrillic")
594 return it->second.textpreamble();
599 bool Encodings::fontencSupportsScript(string const & fontenc, string const & script)
601 if (script == "textgreek")
602 return (fontenc == "LGR" || fontenc == "TU");
603 if (script == "textcyrillic")
604 return (fontenc == "T2A" || fontenc == "T2B" || fontenc == "T2C"
605 || fontenc == "X2" || fontenc == "TU");
610 bool Encodings::isMathAlpha(char_type c)
612 return mathalpha.count(c);
616 bool Encodings::isUnicodeTextOnly(char_type c)
618 if (isASCII(c) || isMathAlpha(c))
621 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
622 return it == unicodesymbols.end() || it->second.mathcommand().empty();
627 Encodings::fromLyXName(string const & name, bool allowUnsafe) const
629 EncodingList::const_iterator const it = encodinglist.find(name);
630 if (it == encodinglist.end())
632 if (!allowUnsafe && it->second.unsafe())
639 Encodings::fromLaTeXName(string const & n, int const & p, bool allowUnsafe) const
642 // FIXME: if we have to test for too many of these synonyms,
643 // we should instead extend the format of lib/encodings
647 // We don't use find_if because it makes copies of the pairs in
649 // This linear search is OK since we don't have many encodings.
650 // Users could even optimize it by putting the encodings they use
651 // most at the top of lib/encodings.
652 EncodingList::const_iterator const end = encodinglist.end();
653 for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
654 if ((it->second.latexName() == name) && (it->second.package() & p)
655 && (!it->second.unsafe() || allowUnsafe))
662 Encodings::fromIconvName(string const & n, int const & p, bool allowUnsafe) const
664 EncodingList::const_iterator const end = encodinglist.end();
665 for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
666 if ((it->second.iconvName() == n) && (it->second.package() & p)
667 && (!it->second.unsafe() || allowUnsafe))
673 Encodings::Encodings()
677 void Encodings::read(FileName const & encfile, FileName const & symbolsfile)
679 // We must read the symbolsfile first, because the Encoding
680 // constructor depends on it.
681 CharSetMap forcednotselected;
683 symbolslex.setFile(symbolsfile);
684 bool getNextToken = true;
685 while (symbolslex.isOK()) {
689 if (!symbolslex.next(true))
694 istringstream is(symbolslex.getString());
695 // reading symbol directly does not work if
696 // char_type == wchar_t.
698 if(!(is >> hex >> tmp))
702 if (!symbolslex.next(true))
704 docstring textcommand = symbolslex.getDocString();
705 if (!symbolslex.next(true))
707 string textpreamble = symbolslex.getString();
708 if (!symbolslex.next(true))
710 string sflags = symbolslex.getString();
715 if (suffixIs(textcommand, '}'))
716 flags |= CharInfoTextNoTermination;
717 while (!sflags.empty()) {
719 sflags = split(sflags, flag, ',');
720 if (flag == "combining") {
721 flags |= CharInfoCombining;
722 } else if (flag == "force") {
723 flags |= CharInfoForce;
724 forced.insert(symbol);
725 } else if (prefixIs(flag, "force=")) {
726 vector<string> encs =
727 getVectorFromString(flag.substr(6), ";");
728 for (size_t i = 0; i < encs.size(); ++i)
729 forcedselected[encs[i]].insert(symbol);
730 flags |= CharInfoForceSelected;
731 } else if (prefixIs(flag, "force!=")) {
732 vector<string> encs =
733 getVectorFromString(flag.substr(7), ";");
734 for (size_t i = 0; i < encs.size(); ++i)
735 forcednotselected[encs[i]].insert(symbol);
736 flags |= CharInfoForceSelected;
737 } else if (flag == "mathalpha") {
738 mathalpha.insert(symbol);
739 } else if (flag == "notermination=text") {
740 flags |= CharInfoTextNoTermination;
741 } else if (flag == "notermination=math") {
742 flags |= CharInfoMathNoTermination;
743 } else if (flag == "notermination=both") {
744 flags |= CharInfoTextNoTermination;
745 flags |= CharInfoMathNoTermination;
746 } else if (flag == "notermination=none") {
747 flags &= ~CharInfoTextNoTermination;
748 flags &= ~CharInfoMathNoTermination;
749 } else if (contains(flag, "tipashortcut=")) {
750 tipashortcut = split(flag, '=');
751 } else if (flag == "deprecated") {
752 flags |= CharInfoDeprecated;
754 lyxerr << "Ignoring unknown flag `" << flag
755 << "' for symbol `0x"
756 << hex << symbol << dec
760 // mathcommand and mathpreamble have been added for 1.6.0.
761 // make them optional so that old files still work.
762 int const lineno = symbolslex.lineNumber();
763 bool breakout = false;
764 docstring mathcommand;
766 if (symbolslex.next(true)) {
767 if (symbolslex.lineNumber() != lineno) {
768 // line in old format without mathcommand and mathpreamble
769 getNextToken = false;
771 mathcommand = symbolslex.getDocString();
772 if (suffixIs(mathcommand, '}'))
773 flags |= CharInfoMathNoTermination;
774 if (symbolslex.next(true)) {
775 if (symbolslex.lineNumber() != lineno) {
776 // line in new format with mathcommand only
777 getNextToken = false;
779 // line in new format with mathcommand and mathpreamble
780 mathpreamble = symbolslex.getString();
789 // backward compatibility
790 if (mathpreamble == "esintoramsmath")
791 mathpreamble = "esint|amsmath";
793 if (!textpreamble.empty())
794 if (textpreamble[0] != '\\')
795 flags |= CharInfoTextFeature;
796 if (!mathpreamble.empty())
797 if (mathpreamble[0] != '\\')
798 flags |= CharInfoMathFeature;
800 CharInfo info = CharInfo(
801 textcommand, mathcommand,
802 textpreamble, mathpreamble,
803 tipashortcut, flags);
804 LYXERR(Debug::INFO, "Read unicode symbol " << symbol << " '"
805 << to_utf8(info.textcommand()) << "' '" << info.textpreamble()
806 << " '" << info.textfeature() << ' ' << info.textnotermination()
807 << ' ' << to_utf8(info.mathcommand()) << "' '" << info.mathpreamble()
808 << "' " << info.mathfeature() << ' ' << info.mathnotermination()
809 << ' ' << info.combining() << ' ' << info.force()
810 << ' ' << info.forceselected());
812 // we assume that at least one command is nonempty when using unicodesymbols
813 if (info.isUnicodeSymbol()) {
814 unicodesymbols[symbol] = info;
821 // Now read the encodings
827 LexerKeyword encodingtags[] = {
828 { "encoding", et_encoding },
832 Lexer lex(encodingtags);
833 lex.setFile(encfile);
834 lex.setContext("Encodings::read");
840 string const name = lex.getString();
842 string const latexname = lex.getString();
844 string const guiname = lex.getString();
846 string const iconvname = lex.getString();
848 string const width = lex.getString();
849 bool fixedwidth = false;
851 if (width == "fixed")
853 else if (width == "variable")
855 else if (width == "variableunsafe") {
860 lex.printError("Unknown width");
863 string const p = lex.getString();
864 Encoding::Package package = Encoding::none;
866 package = Encoding::none;
867 else if (p == "inputenc")
868 package = Encoding::inputenc;
870 package = Encoding::CJK;
871 else if (p == "japanese")
872 package = Encoding::japanese;
874 lex.printError("Unknown package");
876 LYXERR(Debug::INFO, "Reading encoding " << name);
877 encodinglist[name] = Encoding(name, latexname,
878 guiname, iconvname, fixedwidth, unsafe,
881 if (lex.lex() != et_end)
882 lex.printError("Missing end");
886 lex.printError("Misplaced end");
888 case Lexer::LEX_FEOF:
891 lex.printError("Unknown tag");
896 // Move all information from forcednotselected to forcedselected
897 for (CharSetMap::const_iterator it1 = forcednotselected.begin(); it1 != forcednotselected.end(); ++it1) {
898 for (CharSetMap::iterator it2 = forcedselected.begin(); it2 != forcedselected.end(); ++it2) {
899 if (it2->first != it1->first)
900 it2->second.insert(it1->second.begin(), it1->second.end());