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 && ((0xb7 <= 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
202 if (c < start_encodable_ && !isForced(c))
204 if (encodable_.find(c) != encodable_.end())
210 pair<docstring, bool> Encoding::latexChar(char_type c) const
213 return make_pair(docstring(1, c), false);
215 // c cannot (or should not) be encoded in this encoding
216 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
217 if (it == unicodesymbols.end())
218 throw EncodingException(c);
219 // at least one of mathcommand and textcommand is nonempty
220 if (it->second.textcommand().empty())
222 "\\ensuremath{" + it->second.mathcommand() + '}', false);
223 return make_pair(it->second.textcommand(), !it->second.textnotermination());
227 pair<docstring, docstring> Encoding::latexString(docstring const & input, bool dryrun) const
231 bool terminate = false;
232 for (size_t n = 0; n < input.size(); ++n) {
233 char_type const c = input[n];
235 pair<docstring, bool> latex_char = latexChar(c);
236 docstring const latex = latex_char.first;
237 if (terminate && !prefixIs(latex, '\\')
238 && !prefixIs(latex, '{')
239 && !prefixIs(latex, '}')) {
240 // Prevent eating of a following
241 // space or command corruption by
242 // following characters
249 terminate = latex_char.second;
250 } catch (EncodingException & /* e */) {
251 LYXERR0("Uncodable character <" << docstring(1, c)
252 << "> in latexString!");
254 result += "<" + _("LyX Warning: ")
255 + _("uncodable character") + " '";
256 result += docstring(1, input[n]);
259 uncodable += input[n];
262 return make_pair(result, uncodable);
266 vector<char_type> Encoding::symbolsList() const
268 // assure the used encoding is properly initialized
271 // first all those below start_encodable_
272 vector<char_type> symbols;
273 for (char_type c = 0; c < start_encodable_; ++c)
274 symbols.push_back(c);
275 // add all encodable characters
276 copy(encodable_.begin(), encodable_.end(), back_inserter(symbols));
277 // now the ones from the unicodesymbols file that are not already there
278 for (pair<char_type, CharInfo> const & elem : unicodesymbols) {
279 if (find(symbols.begin(), symbols.end(), elem.first) == symbols.end())
280 symbols.push_back(elem.first);
282 // finally, sort the vector
283 sort(symbols.begin(), symbols.end());
288 bool Encodings::latexMathChar(char_type c, bool mathmode,
289 Encoding const * encoding, docstring & command,
290 bool & needsTermination)
292 command = empty_docstring();
294 if (encoding->encodable(c))
295 command = docstring(1, c);
296 needsTermination = false;
298 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
299 if (it == unicodesymbols.end()) {
300 if (!encoding || command.empty())
301 throw EncodingException(c);
306 // at least one of mathcommand and textcommand is nonempty
307 bool use_math = (mathmode && !it->second.mathcommand().empty()) ||
308 (!mathmode && it->second.textcommand().empty());
310 command = it->second.mathcommand();
311 needsTermination = !it->second.mathnotermination();
314 if (!encoding || command.empty()) {
315 command = it->second.textcommand();
316 needsTermination = !it->second.textnotermination();
327 char_type Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
328 bool & combining, bool & needsTermination, set<string> * req)
330 CharInfoMap::const_iterator const end = unicodesymbols.end();
331 CharInfoMap::const_iterator it = unicodesymbols.begin();
332 for (combining = false; it != end; ++it) {
333 if (it->second.deprecated())
335 docstring const math = it->second.mathcommand();
336 docstring const text = it->second.textcommand();
337 if ((cmdtype & MATH_CMD) && math == cmd) {
338 combining = it->second.combining();
339 needsTermination = !it->second.mathnotermination();
340 if (req && it->second.mathfeature() &&
341 !it->second.mathpreamble().empty())
342 req->insert(it->second.mathpreamble());
345 if ((cmdtype & TEXT_CMD) && text == cmd) {
346 combining = it->second.combining();
347 needsTermination = !it->second.textnotermination();
348 if (req && it->second.textfeature() &&
349 !it->second.textpreamble().empty())
350 req->insert(it->second.textpreamble());
354 needsTermination = false;
359 docstring Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
360 bool & needsTermination, docstring & rem, set<string> * req)
362 needsTermination = false;
363 rem = empty_docstring();
364 bool const mathmode = cmdtype & MATH_CMD;
365 bool const textmode = cmdtype & TEXT_CMD;
367 size_t const cmdend = cmd.size();
369 CharInfoMap::const_iterator const uniend = unicodesymbols.end();
370 for (size_t i = 0, j = 0; j < cmdend; ++j) {
371 // Also get the char after a backslash
372 if (j + 1 < cmdend && cmd[j] == '\\') {
375 // Detect things like \=*{e} as well
376 if (j + 3 < cmdend && cmd[j+1] == '*' &&
382 // position of the last character before a possible macro
385 // If a macro argument follows, get it, too
386 // Do it here only for single character commands. Other
387 // combining commands need this too, but they are handled in
388 // the loop below for performance reasons.
389 if (j + 1 < cmdend && cmd[j + 1] == '{') {
392 while (k < cmdend && count) {
393 k = cmd.find_first_of(from_ascii("{}"), k + 1);
394 // braces may not be balanced
395 if (k == docstring::npos)
402 if (k != docstring::npos)
404 } else if (m + 1 < cmdend && isAlphaASCII(cmd[m])) {
405 while (m + 2 < cmdend && isAlphaASCII(cmd[m+1]))
408 // Start with this substring and try augmenting it when it is
409 // the prefix of some command in the unicodesymbols file
410 docstring subcmd = cmd.substr(i, j - i + 1);
412 CharInfoMap::const_iterator it = unicodesymbols.begin();
413 // First part of subcmd which might be a combining character
414 docstring combcmd = (m == j) ? docstring() : cmd.substr(i, m - i + 1);
415 // The combining character of combcmd if it exists
416 CharInfoMap::const_iterator combining = uniend;
417 size_t unicmd_size = 0;
419 for (; it != uniend; ++it) {
420 if (it->second.deprecated())
422 docstring const math = mathmode ? it->second.mathcommand()
424 docstring const text = textmode ? it->second.textcommand()
426 if (!combcmd.empty() && it->second.combining() &&
427 (math == combcmd || text == combcmd))
429 size_t cur_size = max(math.size(), text.size());
430 // The current math or text unicode command cannot
431 // match, or we already matched a longer one
432 if (cur_size < subcmd.size() || cur_size <= unicmd_size)
435 docstring tmp = subcmd;
437 while (prefixIs(math, tmp) || prefixIs(text, tmp)) {
439 if (k >= cmdend || cur_size <= tmp.size())
447 // The last added char caused a mismatch, because
448 // we didn't exhaust the chars in cmd and didn't
449 // exceed the maximum size of the current unicmd
450 if (k < cmdend && cur_size > tmp.size())
451 tmp.resize(tmp.size() - 1);
453 // If this is an exact match, we found a (longer)
454 // matching entry in the unicodesymbols file.
455 if (math != tmp && text != tmp)
457 // If we found a combining command, we need to append
458 // the macro argument if this has not been done above.
459 if (tmp == combcmd && combining != uniend &&
460 k < cmdend && cmd[k] == '{') {
463 while (l < cmdend && count) {
464 l = cmd.find_first_of(from_ascii("{}"), l + 1);
465 // braces may not be balanced
466 if (l == docstring::npos)
473 if (l != docstring::npos) {
475 subcmd = cmd.substr(i, j - i + 1);
478 // If the entry doesn't start with '\', we take note
479 // of the match and continue (this is not a ultimate
480 // acceptance, as some other entry may match a longer
481 // portion of the cmd string). However, if the entry
482 // does start with '\', we accept the match only if
483 // this is a valid macro, i.e., either it is a single
484 // (nonletter) char macro, or nothing else follows,
485 // or what follows is a nonletter char, or the last
487 else if (tmp[0] != '\\'
488 || (tmp.size() == prefix + 1 &&
489 !isAlphaASCII(tmp[1]) &&
490 (prefix == 1 || !isAlphaASCII(tmp[2])))
492 || !isAlphaASCII(cmd[k])
493 || tmp[tmp.size() - 1] == '}'
498 unicmd_size = cur_size;
500 needsTermination = !it->second.mathnotermination();
502 needsTermination = !it->second.textnotermination();
504 if (math == tmp && it->second.mathfeature() &&
505 !it->second.mathpreamble().empty())
506 req->insert(it->second.mathpreamble());
507 if (text == tmp && it->second.textfeature() &&
508 !it->second.textpreamble().empty())
509 req->insert(it->second.textpreamble());
515 else if (combining != uniend &&
516 prefixIs(subcmd, combcmd + '{')) {
517 // We know that subcmd starts with combcmd and
518 // contains an argument in braces.
519 docstring const arg = subcmd.substr(
520 combcmd.length() + 1,
521 subcmd.length() - combcmd.length() - 2);
522 // If arg is a single character we can construct a
523 // combining sequence.
525 bool argcomb = false;
526 if (arg.size() == 1 && isAlnumASCII(arg[0]))
529 // Use the version of fromLaTeXCommand() that
530 // parses only one command, since we cannot
531 // use more than one character.
534 a = fromLaTeXCommand(arg, cmdtype, argcomb,
536 if (a && req && !argcomb)
537 req->insert(r.begin(), r.end());
540 // In unicode the combining character comes
543 symbols += combining->first;
548 if (j + 1 == cmdend && !unicmd_size) {
549 // No luck. Return what remains
551 if (needsTermination && !rem.empty()) {
552 if (rem.substr(0, 2) == "{}") {
554 needsTermination = false;
555 } else if (rem[0] == ' ') {
556 needsTermination = false;
557 // LaTeX would swallow all spaces
567 CharInfo const & Encodings::unicodeCharInfo(char_type c)
569 static CharInfo empty;
570 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
571 return it != unicodesymbols.end() ? it->second : empty;
575 bool Encodings::isCombiningChar(char_type c)
577 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
578 if (it != unicodesymbols.end())
579 return it->second.combining();
584 string const Encodings::TIPAShortcut(char_type c)
586 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
587 if (it != unicodesymbols.end())
588 return it->second.tipashortcut();
593 string const Encodings::isKnownScriptChar(char_type const c)
595 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
597 if (it == unicodesymbols.end())
599 // FIXME: parse complex textpreamble (may be list or alternatives,
600 // e.g., "subscript,textgreek" or "textcomp|textgreek")
601 if (it->second.textpreamble() == "textgreek"
602 || it->second.textpreamble() == "textcyrillic")
603 return it->second.textpreamble();
608 bool Encodings::fontencSupportsScript(string const & fontenc, string const & script)
610 if (script == "textgreek")
611 return (fontenc == "LGR" || fontenc == "TU");
612 if (script == "textcyrillic")
613 return (fontenc == "T2A" || fontenc == "T2B" || fontenc == "T2C"
614 || fontenc == "X2" || fontenc == "TU");
619 bool Encodings::isMathAlpha(char_type c)
621 return mathalpha.count(c);
625 bool Encodings::isUnicodeTextOnly(char_type c)
627 if (isASCII(c) || isMathAlpha(c))
630 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
631 return it == unicodesymbols.end() || it->second.mathcommand().empty();
636 Encodings::fromLyXName(string const & name, bool allowUnsafe) const
638 EncodingList::const_iterator const it = encodinglist.find(name);
639 if (it == encodinglist.end())
641 if (!allowUnsafe && it->second.unsafe())
648 Encodings::fromLaTeXName(string const & n, int const & p, bool allowUnsafe) const
651 // FIXME: if we have to test for too many of these synonyms,
652 // we should instead extend the format of lib/encodings
656 // We don't use find_if because it makes copies of the pairs in
658 // This linear search is OK since we don't have many encodings.
659 // Users could even optimize it by putting the encodings they use
660 // most at the top of lib/encodings.
661 EncodingList::const_iterator const end = encodinglist.end();
662 for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
663 if ((it->second.latexName() == name) && (it->second.package() & p)
664 && (!it->second.unsafe() || allowUnsafe))
671 Encodings::fromIconvName(string const & n, int const & p, bool allowUnsafe) const
673 EncodingList::const_iterator const end = encodinglist.end();
674 for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
675 if ((it->second.iconvName() == n) && (it->second.package() & p)
676 && (!it->second.unsafe() || allowUnsafe))
682 Encodings::Encodings()
686 void Encodings::read(FileName const & encfile, FileName const & symbolsfile)
688 // We must read the symbolsfile first, because the Encoding
689 // constructor depends on it.
690 CharSetMap forcednotselected;
692 symbolslex.setFile(symbolsfile);
693 bool getNextToken = true;
694 while (symbolslex.isOK()) {
698 if (!symbolslex.next(true))
703 istringstream is(symbolslex.getString());
704 // reading symbol directly does not work if
705 // char_type == wchar_t.
707 if(!(is >> hex >> tmp))
711 if (!symbolslex.next(true))
713 docstring textcommand = symbolslex.getDocString();
714 if (!symbolslex.next(true))
716 string textpreamble = symbolslex.getString();
717 if (!symbolslex.next(true))
719 string sflags = symbolslex.getString();
724 if (suffixIs(textcommand, '}'))
725 flags |= CharInfoTextNoTermination;
726 while (!sflags.empty()) {
728 sflags = split(sflags, flag, ',');
729 if (flag == "combining") {
730 flags |= CharInfoCombining;
731 } else if (flag == "force") {
732 flags |= CharInfoForce;
733 forced.insert(symbol);
734 } else if (prefixIs(flag, "force=")) {
735 vector<string> encs =
736 getVectorFromString(flag.substr(6), ";");
737 for (size_t i = 0; i < encs.size(); ++i)
738 forcedselected[encs[i]].insert(symbol);
739 flags |= CharInfoForceSelected;
740 } else if (prefixIs(flag, "force!=")) {
741 vector<string> encs =
742 getVectorFromString(flag.substr(7), ";");
743 for (size_t i = 0; i < encs.size(); ++i)
744 forcednotselected[encs[i]].insert(symbol);
745 flags |= CharInfoForceSelected;
746 } else if (flag == "mathalpha") {
747 mathalpha.insert(symbol);
748 } else if (flag == "notermination=text") {
749 flags |= CharInfoTextNoTermination;
750 } else if (flag == "notermination=math") {
751 flags |= CharInfoMathNoTermination;
752 } else if (flag == "notermination=both") {
753 flags |= CharInfoTextNoTermination;
754 flags |= CharInfoMathNoTermination;
755 } else if (flag == "notermination=none") {
756 flags &= ~CharInfoTextNoTermination;
757 flags &= ~CharInfoMathNoTermination;
758 } else if (contains(flag, "tipashortcut=")) {
759 tipashortcut = split(flag, '=');
760 } else if (flag == "deprecated") {
761 flags |= CharInfoDeprecated;
763 lyxerr << "Ignoring unknown flag `" << flag
764 << "' for symbol `0x"
765 << hex << symbol << dec
769 // mathcommand and mathpreamble have been added for 1.6.0.
770 // make them optional so that old files still work.
771 int const lineno = symbolslex.lineNumber();
772 bool breakout = false;
773 docstring mathcommand;
775 if (symbolslex.next(true)) {
776 if (symbolslex.lineNumber() != lineno) {
777 // line in old format without mathcommand and mathpreamble
778 getNextToken = false;
780 mathcommand = symbolslex.getDocString();
781 if (suffixIs(mathcommand, '}'))
782 flags |= CharInfoMathNoTermination;
783 if (symbolslex.next(true)) {
784 if (symbolslex.lineNumber() != lineno) {
785 // line in new format with mathcommand only
786 getNextToken = false;
788 // line in new format with mathcommand and mathpreamble
789 mathpreamble = symbolslex.getString();
798 // backward compatibility
799 if (mathpreamble == "esintoramsmath")
800 mathpreamble = "esint|amsmath";
802 if (!textpreamble.empty())
803 if (textpreamble[0] != '\\')
804 flags |= CharInfoTextFeature;
805 if (!mathpreamble.empty())
806 if (mathpreamble[0] != '\\')
807 flags |= CharInfoMathFeature;
809 CharInfo info = CharInfo(
810 textcommand, mathcommand,
811 textpreamble, mathpreamble,
812 tipashortcut, flags);
813 LYXERR(Debug::INFO, "Read unicode symbol " << symbol << " '"
814 << to_utf8(info.textcommand()) << "' '" << info.textpreamble()
815 << " '" << info.textfeature() << ' ' << info.textnotermination()
816 << ' ' << to_utf8(info.mathcommand()) << "' '" << info.mathpreamble()
817 << "' " << info.mathfeature() << ' ' << info.mathnotermination()
818 << ' ' << info.combining() << ' ' << info.force()
819 << ' ' << info.forceselected());
821 // we assume that at least one command is nonempty when using unicodesymbols
822 if (info.isUnicodeSymbol()) {
823 unicodesymbols[symbol] = info;
830 // Now read the encodings
836 LexerKeyword encodingtags[] = {
837 { "encoding", et_encoding },
841 Lexer lex(encodingtags);
842 lex.setFile(encfile);
843 lex.setContext("Encodings::read");
849 string const name = lex.getString();
851 string const latexname = lex.getString();
853 string const guiname = lex.getString();
855 string const iconvname = lex.getString();
857 string const width = lex.getString();
858 bool fixedwidth = false;
860 if (width == "fixed")
862 else if (width == "variable")
864 else if (width == "variableunsafe") {
869 lex.printError("Unknown width");
872 string const p = lex.getString();
873 Encoding::Package package = Encoding::none;
875 package = Encoding::none;
876 else if (p == "inputenc")
877 package = Encoding::inputenc;
879 package = Encoding::CJK;
880 else if (p == "japanese")
881 package = Encoding::japanese;
883 lex.printError("Unknown package");
885 LYXERR(Debug::INFO, "Reading encoding " << name);
886 encodinglist[name] = Encoding(name, latexname,
887 guiname, iconvname, fixedwidth, unsafe,
890 if (lex.lex() != et_end)
891 lex.printError("Missing end");
895 lex.printError("Misplaced end");
897 case Lexer::LEX_FEOF:
900 lex.printError("Unknown tag");
905 // Move all information from forcednotselected to forcedselected
906 for (CharSetMap::const_iterator it1 = forcednotselected.begin(); it1 != forcednotselected.end(); ++it1) {
907 for (CharSetMap::iterator it2 = forcedselected.begin(); it2 != forcedselected.end(); ++it2) {
908 if (it2->first != it1->first)
909 it2->second.insert(it1->second.begin(), it1->second.end());