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
192 if (iconvName_ == "UTF-8" && package_ == none)
194 // platex does not load inputenc: force conversion of supported characters
195 if (package_ == Encoding::japanese
196 && ((0x7f < c && c <= 0x05ff) // Latin-1 Supplement ... Hebrew
197 || (0x1d00 < c && c <= 0x218f) // Phonetic Extensions ... Number Forms
198 || (0x2193 < c && c <= 0x2aff) // Arrows ... Supplemental Mathematical Operators
199 || (0xfb00 < c && c <= 0xfb4f) // Alphabetic Presentation Forms
200 || (0x1d400 < c && c <= 0x1d7ff)) // Mathematical Alphanumeric Symbols
201 && c != 0xa2 && c != 0xa3 && c != 0xa5 && c != 0xa7 // exceptions
202 && c != 0xa8 && c != 0xb0 && c != 0xb4 && c != 0xb6)
204 if (c < start_encodable_ && !isForced(c))
206 if (encodable_.find(c) != encodable_.end())
212 pair<docstring, bool> Encoding::latexChar(char_type c) const
215 return make_pair(docstring(1, c), false);
217 // c cannot (or should not) be encoded in this encoding
218 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
219 if (it == unicodesymbols.end())
220 throw EncodingException(c);
221 // at least one of mathcommand and textcommand is nonempty
222 if (it->second.textcommand().empty())
224 "\\ensuremath{" + it->second.mathcommand() + '}', false);
225 return make_pair(it->second.textcommand(), !it->second.textnotermination());
229 pair<docstring, docstring> Encoding::latexString(docstring const & input, bool dryrun) const
233 bool terminate = false;
234 for (size_t n = 0; n < input.size(); ++n) {
236 char_type const c = input[n];
237 pair<docstring, bool> latex_char = latexChar(c);
238 docstring const latex = latex_char.first;
239 if (terminate && !prefixIs(latex, '\\')
240 && !prefixIs(latex, '{')
241 && !prefixIs(latex, '}')) {
242 // Prevent eating of a following
243 // space or command corruption by
244 // following characters
251 terminate = latex_char.second;
252 } catch (EncodingException & /* e */) {
253 LYXERR0("Uncodable character in latexString!");
255 result += "<" + _("LyX Warning: ")
256 + _("uncodable character") + " '";
257 result += docstring(1, input[n]);
260 uncodable += input[n];
263 return make_pair(result, uncodable);
267 vector<char_type> Encoding::symbolsList() const
269 // assure the used encoding is properly initialized
272 // first all those below start_encodable_
273 vector<char_type> symbols;
274 for (char_type c = 0; c < start_encodable_; ++c)
275 symbols.push_back(c);
276 // add all encodable characters
277 copy(encodable_.begin(), encodable_.end(), back_inserter(symbols));
278 // now the ones from the unicodesymbols file that are not already there
279 for (pair<char_type, CharInfo> const & elem : unicodesymbols) {
280 if (find(symbols.begin(), symbols.end(), elem.first) == symbols.end())
281 symbols.push_back(elem.first);
283 // finally, sort the vector
284 sort(symbols.begin(), symbols.end());
289 bool Encodings::latexMathChar(char_type c, bool mathmode,
290 Encoding const * encoding, docstring & command,
291 bool & needsTermination)
293 command = empty_docstring();
295 if (encoding->encodable(c))
296 command = docstring(1, c);
297 needsTermination = false;
299 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
300 if (it == unicodesymbols.end()) {
301 if (!encoding || command.empty())
302 throw EncodingException(c);
307 // at least one of mathcommand and textcommand is nonempty
308 bool use_math = (mathmode && !it->second.mathcommand().empty()) ||
309 (!mathmode && it->second.textcommand().empty());
311 command = it->second.mathcommand();
312 needsTermination = !it->second.mathnotermination();
315 if (!encoding || command.empty()) {
316 command = it->second.textcommand();
317 needsTermination = !it->second.textnotermination();
328 char_type Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
329 bool & combining, bool & needsTermination, set<string> * req)
331 CharInfoMap::const_iterator const end = unicodesymbols.end();
332 CharInfoMap::const_iterator it = unicodesymbols.begin();
333 for (combining = false; it != end; ++it) {
334 if (it->second.deprecated())
336 docstring const math = it->second.mathcommand();
337 docstring const text = it->second.textcommand();
338 if ((cmdtype & MATH_CMD) && math == cmd) {
339 combining = it->second.combining();
340 needsTermination = !it->second.mathnotermination();
341 if (req && it->second.mathfeature() &&
342 !it->second.mathpreamble().empty())
343 req->insert(it->second.mathpreamble());
346 if ((cmdtype & TEXT_CMD) && text == cmd) {
347 combining = it->second.combining();
348 needsTermination = !it->second.textnotermination();
349 if (req && it->second.textfeature() &&
350 !it->second.textpreamble().empty())
351 req->insert(it->second.textpreamble());
355 needsTermination = false;
360 docstring Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
361 bool & needsTermination, docstring & rem, set<string> * req)
363 needsTermination = false;
364 rem = empty_docstring();
365 bool const mathmode = cmdtype & MATH_CMD;
366 bool const textmode = cmdtype & TEXT_CMD;
368 size_t const cmdend = cmd.size();
370 CharInfoMap::const_iterator const uniend = unicodesymbols.end();
371 for (size_t i = 0, j = 0; j < cmdend; ++j) {
372 // Also get the char after a backslash
373 if (j + 1 < cmdend && cmd[j] == '\\') {
376 // Detect things like \=*{e} as well
377 if (j + 3 < cmdend && cmd[j+1] == '*' &&
383 // position of the last character before a possible macro
386 // If a macro argument follows, get it, too
387 // Do it here only for single character commands. Other
388 // combining commands need this too, but they are handled in
389 // the loop below for performance reasons.
390 if (j + 1 < cmdend && cmd[j + 1] == '{') {
393 while (k < cmdend && count) {
394 k = cmd.find_first_of(from_ascii("{}"), k + 1);
395 // braces may not be balanced
396 if (k == docstring::npos)
403 if (k != docstring::npos)
405 } else if (m + 1 < cmdend && isAlphaASCII(cmd[m])) {
406 while (m + 2 < cmdend && isAlphaASCII(cmd[m+1]))
409 // Start with this substring and try augmenting it when it is
410 // the prefix of some command in the unicodesymbols file
411 docstring subcmd = cmd.substr(i, j - i + 1);
413 CharInfoMap::const_iterator it = unicodesymbols.begin();
414 // First part of subcmd which might be a combining character
415 docstring combcmd = (m == j) ? docstring() : cmd.substr(i, m - i + 1);
416 // The combining character of combcmd if it exists
417 CharInfoMap::const_iterator combining = uniend;
418 size_t unicmd_size = 0;
420 for (; it != uniend; ++it) {
421 if (it->second.deprecated())
423 docstring const math = mathmode ? it->second.mathcommand()
425 docstring const text = textmode ? it->second.textcommand()
427 if (!combcmd.empty() && it->second.combining() &&
428 (math == combcmd || text == combcmd))
430 size_t cur_size = max(math.size(), text.size());
431 // The current math or text unicode command cannot
432 // match, or we already matched a longer one
433 if (cur_size < subcmd.size() || cur_size <= unicmd_size)
436 docstring tmp = subcmd;
438 while (prefixIs(math, tmp) || prefixIs(text, tmp)) {
440 if (k >= cmdend || cur_size <= tmp.size())
448 // The last added char caused a mismatch, because
449 // we didn't exhaust the chars in cmd and didn't
450 // exceed the maximum size of the current unicmd
451 if (k < cmdend && cur_size > tmp.size())
452 tmp.resize(tmp.size() - 1);
454 // If this is an exact match, we found a (longer)
455 // matching entry in the unicodesymbols file.
456 if (math != tmp && text != tmp)
458 // If we found a combining command, we need to append
459 // the macro argument if this has not been done above.
460 if (tmp == combcmd && combining != uniend &&
461 k < cmdend && cmd[k] == '{') {
464 while (l < cmdend && count) {
465 l = cmd.find_first_of(from_ascii("{}"), l + 1);
466 // braces may not be balanced
467 if (l == docstring::npos)
474 if (l != docstring::npos) {
476 subcmd = cmd.substr(i, j - i + 1);
479 // If the entry doesn't start with '\', we take note
480 // of the match and continue (this is not a ultimate
481 // acceptance, as some other entry may match a longer
482 // portion of the cmd string). However, if the entry
483 // does start with '\', we accept the match only if
484 // this is a valid macro, i.e., either it is a single
485 // (nonletter) char macro, or nothing else follows,
486 // or what follows is a nonletter char, or the last
488 else if (tmp[0] != '\\'
489 || (tmp.size() == prefix + 1 &&
490 !isAlphaASCII(tmp[1]) &&
491 (prefix == 1 || !isAlphaASCII(tmp[2])))
493 || !isAlphaASCII(cmd[k])
494 || tmp[tmp.size() - 1] == '}'
499 unicmd_size = cur_size;
501 needsTermination = !it->second.mathnotermination();
503 needsTermination = !it->second.textnotermination();
505 if (math == tmp && it->second.mathfeature() &&
506 !it->second.mathpreamble().empty())
507 req->insert(it->second.mathpreamble());
508 if (text == tmp && it->second.textfeature() &&
509 !it->second.textpreamble().empty())
510 req->insert(it->second.textpreamble());
516 else if (combining != uniend &&
517 prefixIs(subcmd, combcmd + '{')) {
518 // We know that subcmd starts with combcmd and
519 // contains an argument in braces.
520 docstring const arg = subcmd.substr(
521 combcmd.length() + 1,
522 subcmd.length() - combcmd.length() - 2);
523 // If arg is a single character we can construct a
524 // combining sequence.
526 bool argcomb = false;
527 if (arg.size() == 1 && isAlnumASCII(arg[0]))
530 // Use the version of fromLaTeXCommand() that
531 // parses only one command, since we cannot
532 // use more than one character.
535 a = fromLaTeXCommand(arg, cmdtype, argcomb,
537 if (a && req && !argcomb)
538 req->insert(r.begin(), r.end());
541 // In unicode the combining character comes
544 symbols += combining->first;
549 if (j + 1 == cmdend && !unicmd_size) {
550 // No luck. Return what remains
552 if (needsTermination && !rem.empty()) {
553 if (rem.substr(0, 2) == "{}") {
555 needsTermination = false;
556 } else if (rem[0] == ' ') {
557 needsTermination = false;
558 // LaTeX would swallow all spaces
568 CharInfo const & Encodings::unicodeCharInfo(char_type c)
570 static CharInfo empty;
571 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
572 return it != unicodesymbols.end() ? it->second : empty;
576 bool Encodings::isCombiningChar(char_type c)
578 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
579 if (it != unicodesymbols.end())
580 return it->second.combining();
585 string const Encodings::TIPAShortcut(char_type c)
587 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
588 if (it != unicodesymbols.end())
589 return it->second.tipashortcut();
594 string const Encodings::isKnownScriptChar(char_type const c)
596 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
598 if (it == unicodesymbols.end())
600 // FIXME: parse complex textpreamble (may be list or alternatives,
601 // e.g., "subscript,textgreek" or "textcomp|textgreek")
602 if (it->second.textpreamble() == "textgreek"
603 || it->second.textpreamble() == "textcyrillic")
604 return it->second.textpreamble();
609 bool Encodings::fontencSupportsScript(string const & fontenc, string const & script)
611 if (script == "textgreek")
612 return (fontenc == "LGR" || fontenc == "TU");
613 if (script == "textcyrillic")
614 return (fontenc == "T2A" || fontenc == "T2B" || fontenc == "T2C"
615 || fontenc == "X2" || fontenc == "TU");
620 bool Encodings::isMathAlpha(char_type c)
622 return mathalpha.count(c);
626 bool Encodings::isUnicodeTextOnly(char_type c)
628 if (isASCII(c) || isMathAlpha(c))
631 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
632 return it == unicodesymbols.end() || it->second.mathcommand().empty();
637 Encodings::fromLyXName(string const & name, bool allowUnsafe) const
639 EncodingList::const_iterator const it = encodinglist.find(name);
640 if (it == encodinglist.end())
642 if (!allowUnsafe && it->second.unsafe())
649 Encodings::fromLaTeXName(string const & n, int const & p, bool allowUnsafe) const
652 // FIXME: if we have to test for too many of these synonyms,
653 // we should instead extend the format of lib/encodings
657 // We don't use find_if because it makes copies of the pairs in
659 // This linear search is OK since we don't have many encodings.
660 // Users could even optimize it by putting the encodings they use
661 // most at the top of lib/encodings.
662 EncodingList::const_iterator const end = encodinglist.end();
663 for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
664 if ((it->second.latexName() == name) && (it->second.package() & p)
665 && (!it->second.unsafe() || allowUnsafe))
672 Encodings::fromIconvName(string const & n, int const & p, bool allowUnsafe) const
674 EncodingList::const_iterator const end = encodinglist.end();
675 for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
676 if ((it->second.iconvName() == n) && (it->second.package() & p)
677 && (!it->second.unsafe() || allowUnsafe))
683 Encodings::Encodings()
687 void Encodings::read(FileName const & encfile, FileName const & symbolsfile)
689 // We must read the symbolsfile first, because the Encoding
690 // constructor depends on it.
691 CharSetMap forcednotselected;
693 symbolslex.setFile(symbolsfile);
694 bool getNextToken = true;
695 while (symbolslex.isOK()) {
699 if (!symbolslex.next(true))
704 istringstream is(symbolslex.getString());
705 // reading symbol directly does not work if
706 // char_type == wchar_t.
708 if(!(is >> hex >> tmp))
712 if (!symbolslex.next(true))
714 docstring textcommand = symbolslex.getDocString();
715 if (!symbolslex.next(true))
717 string textpreamble = symbolslex.getString();
718 if (!symbolslex.next(true))
720 string sflags = symbolslex.getString();
725 if (suffixIs(textcommand, '}'))
726 flags |= CharInfoTextNoTermination;
727 while (!sflags.empty()) {
729 sflags = split(sflags, flag, ',');
730 if (flag == "combining") {
731 flags |= CharInfoCombining;
732 } else if (flag == "force") {
733 flags |= CharInfoForce;
734 forced.insert(symbol);
735 } else if (prefixIs(flag, "force=")) {
736 vector<string> encs =
737 getVectorFromString(flag.substr(6), ";");
738 for (size_t i = 0; i < encs.size(); ++i)
739 forcedselected[encs[i]].insert(symbol);
740 flags |= CharInfoForceSelected;
741 } else if (prefixIs(flag, "force!=")) {
742 vector<string> encs =
743 getVectorFromString(flag.substr(7), ";");
744 for (size_t i = 0; i < encs.size(); ++i)
745 forcednotselected[encs[i]].insert(symbol);
746 flags |= CharInfoForceSelected;
747 } else if (flag == "mathalpha") {
748 mathalpha.insert(symbol);
749 } else if (flag == "notermination=text") {
750 flags |= CharInfoTextNoTermination;
751 } else if (flag == "notermination=math") {
752 flags |= CharInfoMathNoTermination;
753 } else if (flag == "notermination=both") {
754 flags |= CharInfoTextNoTermination;
755 flags |= CharInfoMathNoTermination;
756 } else if (flag == "notermination=none") {
757 flags &= ~CharInfoTextNoTermination;
758 flags &= ~CharInfoMathNoTermination;
759 } else if (contains(flag, "tipashortcut=")) {
760 tipashortcut = split(flag, '=');
761 } else if (flag == "deprecated") {
762 flags |= CharInfoDeprecated;
764 lyxerr << "Ignoring unknown flag `" << flag
765 << "' for symbol `0x"
766 << hex << symbol << dec
770 // mathcommand and mathpreamble have been added for 1.6.0.
771 // make them optional so that old files still work.
772 int const lineno = symbolslex.lineNumber();
773 bool breakout = false;
774 docstring mathcommand;
776 if (symbolslex.next(true)) {
777 if (symbolslex.lineNumber() != lineno) {
778 // line in old format without mathcommand and mathpreamble
779 getNextToken = false;
781 mathcommand = symbolslex.getDocString();
782 if (suffixIs(mathcommand, '}'))
783 flags |= CharInfoMathNoTermination;
784 if (symbolslex.next(true)) {
785 if (symbolslex.lineNumber() != lineno) {
786 // line in new format with mathcommand only
787 getNextToken = false;
789 // line in new format with mathcommand and mathpreamble
790 mathpreamble = symbolslex.getString();
799 // backward compatibility
800 if (mathpreamble == "esintoramsmath")
801 mathpreamble = "esint|amsmath";
803 if (!textpreamble.empty())
804 if (textpreamble[0] != '\\')
805 flags |= CharInfoTextFeature;
806 if (!mathpreamble.empty())
807 if (mathpreamble[0] != '\\')
808 flags |= CharInfoMathFeature;
810 CharInfo info = CharInfo(
811 textcommand, mathcommand,
812 textpreamble, mathpreamble,
813 tipashortcut, flags);
814 LYXERR(Debug::INFO, "Read unicode symbol " << symbol << " '"
815 << to_utf8(info.textcommand()) << "' '" << info.textpreamble()
816 << " '" << info.textfeature() << ' ' << info.textnotermination()
817 << ' ' << to_utf8(info.mathcommand()) << "' '" << info.mathpreamble()
818 << "' " << info.mathfeature() << ' ' << info.mathnotermination()
819 << ' ' << info.combining() << ' ' << info.force()
820 << ' ' << info.forceselected());
822 // we assume that at least one command is nonempty when using unicodesymbols
823 if (info.isUnicodeSymbol()) {
824 unicodesymbols[symbol] = info;
831 // Now read the encodings
837 LexerKeyword encodingtags[] = {
838 { "encoding", et_encoding },
842 Lexer lex(encodingtags);
843 lex.setFile(encfile);
844 lex.setContext("Encodings::read");
850 string const name = lex.getString();
852 string const latexname = lex.getString();
854 string const guiname = lex.getString();
856 string const iconvname = lex.getString();
858 string const width = lex.getString();
859 bool fixedwidth = false;
861 if (width == "fixed")
863 else if (width == "variable")
865 else if (width == "variableunsafe") {
870 lex.printError("Unknown width");
873 string const p = lex.getString();
874 Encoding::Package package = Encoding::none;
876 package = Encoding::none;
877 else if (p == "inputenc")
878 package = Encoding::inputenc;
880 package = Encoding::CJK;
881 else if (p == "japanese")
882 package = Encoding::japanese;
884 lex.printError("Unknown package");
886 LYXERR(Debug::INFO, "Reading encoding " << name);
887 encodinglist[name] = Encoding(name, latexname,
888 guiname, iconvname, fixedwidth, unsafe,
891 if (lex.lex() != et_end)
892 lex.printError("Missing end");
896 lex.printError("Misplaced end");
898 case Lexer::LEX_FEOF:
901 lex.printError("Unknown tag");
906 // Move all information from forcednotselected to forcedselected
907 for (CharSetMap::const_iterator it1 = forcednotselected.begin(); it1 != forcednotselected.end(); ++it1) {
908 for (CharSetMap::iterator it2 = forcedselected.begin(); it2 != forcedselected.end(); ++it2) {
909 if (it2->first != it1->first)
910 it2->second.insert(it1->second.begin(), it1->second.end());