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>
32 using namespace lyx::support;
36 int const Encoding::any = -1;
40 Encodings::MathCommandSet Encodings::mathcmd;
41 Encodings::TextCommandSet Encodings::textcmd;
42 Encodings::MathSymbolSet Encodings::mathsym;
46 typedef map<char_type, CharInfo> CharInfoMap;
47 CharInfoMap unicodesymbols;
49 typedef set<char_type> CharSet;
50 typedef map<string, CharSet> CharSetMap;
52 CharSetMap forcedselected;
54 typedef set<char_type> MathAlphaSet;
55 MathAlphaSet mathalpha;
58 /// The highest code point in UCS4 encoding (1<<20 + 1<<16)
59 char_type const max_ucs4 = 0x110000;
64 EncodingException::EncodingException(char_type c)
65 : failed_char(c), par_id(0), pos(0)
70 const char * EncodingException::what() const throw()
72 return "Could not find LaTeX command for a character";
77 docstring const & textcommand, docstring const & mathcommand,
78 std::string const & textpreamble, std::string const & mathpreamble,
79 std::string const & tipashortcut, unsigned int flags)
80 : textcommand_(textcommand), mathcommand_(mathcommand),
81 textpreamble_(textpreamble), mathpreamble_(mathpreamble),
82 tipashortcut_(tipashortcut), flags_(flags)
87 Encoding::Encoding(string const & n, string const & l, string const & g,
88 string const & i, bool f, bool u, Encoding::Package p)
89 : name_(n), latexName_(l), guiName_(g), iconvName_(i), fixedwidth_(f),
90 unsafe_(u), forced_(&forcedselected[n]), package_(p)
93 // ASCII can encode 128 code points and nothing else
94 start_encodable_ = 128;
96 } else if (i == "UTF-8") {
97 // UTF8 can encode all UCS4 code points
98 start_encodable_ = max_ucs4;
101 start_encodable_ = 0;
107 void Encoding::init() const
109 // Since the the constructor is the only method which sets complete_
110 // to false the test for complete_ is thread-safe without mutex.
115 Mutex::Locker lock(&mutex);
117 // We need to test again for complete_, since another thread could
118 // have set it to true while we were waiting for the lock and we must
119 // not modify an encoding which is already complete.
123 // We do not make any member mutable so that it can be easily verified
124 // that all const methods are thread-safe: init() is the only const
125 // method which changes complete_, encodable_ and start_encodable_, and
126 // it uses a mutex to ensure thread-safety.
127 CharSet & encodable = const_cast<Encoding *>(this)->encodable_;
128 char_type & start_encodable = const_cast<Encoding *>(this)->start_encodable_;
131 // temporarily switch off lyxerr, since we will generate iconv errors
134 // We do not need to check all UCS4 code points, it is enough
135 // if we check all 256 code points of this encoding.
136 for (unsigned short j = 0; j < 256; ++j) {
137 char const c = char(j);
138 vector<char_type> const ucs4 = eightbit_to_ucs4(&c, 1, iconvName_);
139 if (ucs4.size() != 1)
141 char_type const uc = ucs4[0];
142 CharInfoMap::const_iterator const it = unicodesymbols.find(uc);
143 if (it == unicodesymbols.end())
144 encodable.insert(uc);
145 else if (!it->second.force()) {
146 if (forced_->empty() || forced_->find(uc) == forced_->end())
147 encodable.insert(uc);
151 // We do not know how many code points this encoding has, and
152 // they do not have a direct representation as a single byte,
153 // therefore we need to check all UCS4 code points.
154 // This is expensive!
155 for (char_type c = 0; c < max_ucs4; ++c) {
156 vector<char> const eightbit = ucs4_to_eightbit(&c, 1, iconvName_);
157 if (!eightbit.empty()) {
158 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
159 if (it == unicodesymbols.end())
161 else if (!it->second.force()) {
162 if (forced_->empty() || forced_->find(c) == forced_->end())
169 CharSet::iterator it = encodable.find(start_encodable);
170 while (it != encodable.end()) {
173 it = encodable.find(start_encodable);
175 const_cast<Encoding *>(this)->complete_ = true;
179 bool Encoding::isForced(char_type c) const
181 if (!forced.empty() && forced.find(c) != forced.end())
183 return !forced_->empty() && forced_->find(c) != forced_->end();
187 bool Encoding::encodable(char_type c) const
189 // assure the used encoding is properly initialized
192 if (iconvName_ == "UTF-8" && package_ == none)
194 if (c < start_encodable_ && !isForced(c))
196 if (encodable_.find(c) != encodable_.end())
202 pair<docstring, bool> Encoding::latexChar(char_type c) const
205 return make_pair(docstring(1, c), false);
207 // c cannot (or should not) be encoded in this encoding
208 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
209 if (it == unicodesymbols.end())
210 throw EncodingException(c);
211 // at least one of mathcommand and textcommand is nonempty
212 if (it->second.textcommand().empty())
214 "\\ensuremath{" + it->second.mathcommand() + '}', false);
215 return make_pair(it->second.textcommand(), !it->second.textnotermination());
219 pair<docstring, docstring> Encoding::latexString(docstring const & input, bool dryrun) const
223 bool terminate = false;
224 for (size_t n = 0; n < input.size(); ++n) {
226 char_type const c = input[n];
227 pair<docstring, bool> latex_char = latexChar(c);
228 docstring const latex = latex_char.first;
229 if (terminate && !prefixIs(latex, '\\')
230 && !prefixIs(latex, '{')
231 && !prefixIs(latex, '}')) {
232 // Prevent eating of a following
233 // space or command corruption by
234 // following characters
241 terminate = latex_char.second;
242 } catch (EncodingException & /* e */) {
243 LYXERR0("Uncodable character in latexString!");
245 result += "<" + _("LyX Warning: ")
246 + _("uncodable character") + " '";
247 result += docstring(1, input[n]);
250 uncodable += input[n];
253 return make_pair(result, uncodable);
257 vector<char_type> Encoding::symbolsList() const
259 // assure the used encoding is properly initialized
262 // first all encodable characters
263 vector<char_type> symbols(encodable_.begin(), encodable_.end());
264 // add those below start_encodable_
265 for (char_type c = 0; c < start_encodable_; ++c)
266 symbols.push_back(c);
267 // now the ones from the unicodesymbols file
268 CharInfoMap::const_iterator const end = unicodesymbols.end();
269 CharInfoMap::const_iterator it = unicodesymbols.begin();
270 for (; it != end; ++it)
271 symbols.push_back(it->first);
276 bool Encodings::latexMathChar(char_type c, bool mathmode,
277 Encoding const * encoding, docstring & command,
278 bool & needsTermination)
280 command = empty_docstring();
282 if (encoding->encodable(c))
283 command = docstring(1, c);
284 needsTermination = false;
286 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
287 if (it == unicodesymbols.end()) {
288 if (!encoding || command.empty())
289 throw EncodingException(c);
294 // at least one of mathcommand and textcommand is nonempty
295 bool use_math = (mathmode && !it->second.mathcommand().empty()) ||
296 (!mathmode && it->second.textcommand().empty());
298 command = it->second.mathcommand();
299 needsTermination = !it->second.mathnotermination();
302 if (!encoding || command.empty()) {
303 command = it->second.textcommand();
304 needsTermination = !it->second.textnotermination();
314 char_type Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
315 bool & combining, bool & needsTermination, set<string> * req)
317 CharInfoMap::const_iterator const end = unicodesymbols.end();
318 CharInfoMap::const_iterator it = unicodesymbols.begin();
319 for (combining = false; it != end; ++it) {
320 docstring const math = it->second.mathcommand();
321 docstring const text = it->second.textcommand();
322 if ((cmdtype & MATH_CMD) && math == cmd) {
323 combining = it->second.combining();
324 needsTermination = !it->second.mathnotermination();
325 if (req && it->second.mathfeature() &&
326 !it->second.mathpreamble().empty())
327 req->insert(it->second.mathpreamble());
330 if ((cmdtype & TEXT_CMD) && text == cmd) {
331 combining = it->second.combining();
332 needsTermination = !it->second.textnotermination();
333 if (req && it->second.textfeature() &&
334 !it->second.textpreamble().empty())
335 req->insert(it->second.textpreamble());
339 needsTermination = false;
344 docstring Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
345 bool & needsTermination, docstring & rem, set<string> * req)
347 needsTermination = false;
348 rem = empty_docstring();
349 bool const mathmode = cmdtype & MATH_CMD;
350 bool const textmode = cmdtype & TEXT_CMD;
352 size_t const cmdend = cmd.size();
354 CharInfoMap::const_iterator const uniend = unicodesymbols.end();
355 for (size_t i = 0, j = 0; j < cmdend; ++j) {
356 // Also get the char after a backslash
357 if (j + 1 < cmdend && cmd[j] == '\\') {
360 // Detect things like \=*{e} as well
361 if (j + 3 < cmdend && cmd[j+1] == '*' &&
367 // position of the last character before a possible macro
370 // If a macro argument follows, get it, too
371 // Do it here only for single character commands. Other
372 // combining commands need this too, but they are handled in
373 // the loop below for performance reasons.
374 if (j + 1 < cmdend && cmd[j + 1] == '{') {
377 while (k < cmdend && count) {
378 k = cmd.find_first_of(from_ascii("{}"), k + 1);
379 // braces may not be balanced
380 if (k == docstring::npos)
387 if (k != docstring::npos)
389 } else if (m + 1 < cmdend && isAlphaASCII(cmd[m])) {
390 while (m + 2 < cmdend && isAlphaASCII(cmd[m+1]))
393 // Start with this substring and try augmenting it when it is
394 // the prefix of some command in the unicodesymbols file
395 docstring subcmd = cmd.substr(i, j - i + 1);
397 CharInfoMap::const_iterator it = unicodesymbols.begin();
398 // First part of subcmd which might be a combining character
399 docstring combcmd = (m == j) ? docstring() : cmd.substr(i, m - i + 1);
400 // The combining character of combcmd if it exists
401 CharInfoMap::const_iterator combining = uniend;
402 size_t unicmd_size = 0;
404 for (; it != uniend; ++it) {
405 docstring const math = mathmode ? it->second.mathcommand()
407 docstring const text = textmode ? it->second.textcommand()
409 if (!combcmd.empty() && it->second.combining() &&
410 (math == combcmd || text == combcmd))
412 size_t cur_size = max(math.size(), text.size());
413 // The current math or text unicode command cannot
414 // match, or we already matched a longer one
415 if (cur_size < subcmd.size() || cur_size <= unicmd_size)
418 docstring tmp = subcmd;
420 while (prefixIs(math, tmp) || prefixIs(text, tmp)) {
422 if (k >= cmdend || cur_size <= tmp.size())
430 // The last added char caused a mismatch, because
431 // we didn't exhaust the chars in cmd and didn't
432 // exceed the maximum size of the current unicmd
433 if (k < cmdend && cur_size > tmp.size())
434 tmp.resize(tmp.size() - 1);
436 // If this is an exact match, we found a (longer)
437 // matching entry in the unicodesymbols file.
438 if (math != tmp && text != tmp)
440 // If we found a combining command, we need to append
441 // the macro argument if this has not been done above.
442 if (tmp == combcmd && combining != uniend &&
443 k < cmdend && cmd[k] == '{') {
446 while (l < cmdend && count) {
447 l = cmd.find_first_of(from_ascii("{}"), l + 1);
448 // braces may not be balanced
449 if (l == docstring::npos)
456 if (l != docstring::npos) {
458 subcmd = cmd.substr(i, j - i + 1);
461 // If the entry doesn't start with '\', we take note
462 // of the match and continue (this is not a ultimate
463 // acceptance, as some other entry may match a longer
464 // portion of the cmd string). However, if the entry
465 // does start with '\', we accept the match only if
466 // this is a valid macro, i.e., either it is a single
467 // (nonletter) char macro, or nothing else follows,
468 // or what follows is a nonletter char, or the last
470 else if (tmp[0] != '\\'
471 || (tmp.size() == prefix + 1 &&
472 !isAlphaASCII(tmp[1]) &&
473 (prefix == 1 || !isAlphaASCII(tmp[2])))
475 || !isAlphaASCII(cmd[k])
476 || tmp[tmp.size() - 1] == '}'
481 unicmd_size = cur_size;
483 needsTermination = !it->second.mathnotermination();
485 needsTermination = !it->second.textnotermination();
487 if (math == tmp && it->second.mathfeature() &&
488 !it->second.mathpreamble().empty())
489 req->insert(it->second.mathpreamble());
490 if (text == tmp && it->second.textfeature() &&
491 !it->second.textpreamble().empty())
492 req->insert(it->second.textpreamble());
498 else if (combining != uniend &&
499 prefixIs(subcmd, combcmd + '{')) {
500 // We know that subcmd starts with combcmd and
501 // contains an argument in braces.
502 docstring const arg = subcmd.substr(
503 combcmd.length() + 1,
504 subcmd.length() - combcmd.length() - 2);
505 // If arg is a single character we can construct a
506 // combining sequence.
508 bool argcomb = false;
509 if (arg.size() == 1 && isAlnumASCII(arg[0]))
512 // Use the version of fromLaTeXCommand() that
513 // parses only one command, since we cannot
514 // use more than one character.
517 a = fromLaTeXCommand(arg, cmdtype, argcomb,
519 if (a && req && !argcomb)
520 req->insert(r.begin(), r.end());
523 // In unicode the combining character comes
526 symbols += combining->first;
531 if (j + 1 == cmdend && !unicmd_size) {
532 // No luck. Return what remains
534 if (needsTermination && !rem.empty()) {
535 if (rem.substr(0, 2) == "{}") {
537 needsTermination = false;
538 } else if (rem[0] == ' ') {
539 needsTermination = false;
540 // LaTeX would swallow all spaces
550 CharInfo const & Encodings::unicodeCharInfo(char_type c)
552 static CharInfo empty;
553 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
554 return it != unicodesymbols.end() ? it->second : empty;
558 bool Encodings::isCombiningChar(char_type c)
560 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
561 if (it != unicodesymbols.end())
562 return it->second.combining();
567 string const Encodings::TIPAShortcut(char_type c)
569 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
570 if (it != unicodesymbols.end())
571 return it->second.tipashortcut();
576 bool Encodings::isKnownScriptChar(char_type const c, string & preamble)
578 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
580 if (it == unicodesymbols.end())
583 if (it->second.textpreamble() != "textgreek" && it->second.textpreamble() != "textcyr")
586 if (preamble.empty()) {
587 preamble = it->second.textpreamble();
590 return it->second.textpreamble() == preamble;
594 bool Encodings::isMathAlpha(char_type c)
596 return mathalpha.count(c);
601 Encodings::fromLyXName(string const & name, bool allowUnsafe) const
603 EncodingList::const_iterator const it = encodinglist.find(name);
604 if (it == encodinglist.end())
606 if (!allowUnsafe && it->second.unsafe())
613 Encodings::fromLaTeXName(string const & n, int const & p, bool allowUnsafe) const
616 // FIXME: if we have to test for too many of these synonyms,
617 // we should instead extend the format of lib/encodings
621 // We don't use find_if because it makes copies of the pairs in
623 // This linear search is OK since we don't have many encodings.
624 // Users could even optimize it by putting the encodings they use
625 // most at the top of lib/encodings.
626 EncodingList::const_iterator const end = encodinglist.end();
627 for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
628 if ((it->second.latexName() == name) && (it->second.package() & p)
629 && (!it->second.unsafe() || allowUnsafe))
636 Encodings::fromIconvName(string const & n, int const & p, bool allowUnsafe) const
638 EncodingList::const_iterator const end = encodinglist.end();
639 for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
640 if ((it->second.iconvName() == n) && (it->second.package() & p)
641 && (!it->second.unsafe() || allowUnsafe))
647 Encodings::Encodings()
651 void Encodings::read(FileName const & encfile, FileName const & symbolsfile)
653 // We must read the symbolsfile first, because the Encoding
654 // constructor depends on it.
655 CharSetMap forcednotselected;
657 symbolslex.setFile(symbolsfile);
658 bool getNextToken = true;
659 while (symbolslex.isOK()) {
663 if (!symbolslex.next(true))
668 istringstream is(symbolslex.getString());
669 // reading symbol directly does not work if
670 // char_type == wchar_t.
672 if(!(is >> hex >> tmp))
676 if (!symbolslex.next(true))
678 docstring textcommand = symbolslex.getDocString();
679 if (!symbolslex.next(true))
681 string textpreamble = symbolslex.getString();
682 if (!symbolslex.next(true))
684 string sflags = symbolslex.getString();
689 if (suffixIs(textcommand, '}'))
690 flags |= CharInfoTextNoTermination;
691 while (!sflags.empty()) {
693 sflags = split(sflags, flag, ',');
694 if (flag == "combining") {
695 flags |= CharInfoCombining;
696 } else if (flag == "force") {
697 flags |= CharInfoForce;
698 forced.insert(symbol);
699 } else if (prefixIs(flag, "force=")) {
700 vector<string> encodings =
701 getVectorFromString(flag.substr(6), ";");
702 for (size_t i = 0; i < encodings.size(); ++i)
703 forcedselected[encodings[i]].insert(symbol);
704 flags |= CharInfoForceSelected;
705 } else if (prefixIs(flag, "force!=")) {
706 vector<string> encodings =
707 getVectorFromString(flag.substr(7), ";");
708 for (size_t i = 0; i < encodings.size(); ++i)
709 forcednotselected[encodings[i]].insert(symbol);
710 flags |= CharInfoForceSelected;
711 } else if (flag == "mathalpha") {
712 mathalpha.insert(symbol);
713 } else if (flag == "notermination=text") {
714 flags |= CharInfoTextNoTermination;
715 } else if (flag == "notermination=math") {
716 flags |= CharInfoMathNoTermination;
717 } else if (flag == "notermination=both") {
718 flags |= CharInfoTextNoTermination;
719 flags |= CharInfoMathNoTermination;
720 } else if (flag == "notermination=none") {
721 flags &= ~CharInfoTextNoTermination;
722 flags &= ~CharInfoMathNoTermination;
723 } else if (contains(flag, "tipashortcut=")) {
724 tipashortcut = split(flag, '=');
726 lyxerr << "Ignoring unknown flag `" << flag
727 << "' for symbol `0x"
728 << hex << symbol << dec
732 // mathcommand and mathpreamble have been added for 1.6.0.
733 // make them optional so that old files still work.
734 int const lineno = symbolslex.lineNumber();
735 bool breakout = false;
736 docstring mathcommand;
738 if (symbolslex.next(true)) {
739 if (symbolslex.lineNumber() != lineno) {
740 // line in old format without mathcommand and mathpreamble
741 getNextToken = false;
743 mathcommand = symbolslex.getDocString();
744 if (suffixIs(mathcommand, '}'))
745 flags |= CharInfoMathNoTermination;
746 if (symbolslex.next(true)) {
747 if (symbolslex.lineNumber() != lineno) {
748 // line in new format with mathcommand only
749 getNextToken = false;
751 // line in new format with mathcommand and mathpreamble
752 mathpreamble = symbolslex.getString();
761 // backward compatibility
762 if (mathpreamble == "esintoramsmath")
763 mathpreamble = "esint|amsmath";
765 if (!textpreamble.empty())
766 if (textpreamble[0] != '\\')
767 flags |= CharInfoTextFeature;
768 if (!mathpreamble.empty())
769 if (mathpreamble[0] != '\\')
770 flags |= CharInfoMathFeature;
772 CharInfo info = CharInfo(
773 textcommand, mathcommand,
774 textpreamble, mathpreamble,
775 tipashortcut, flags);
776 LYXERR(Debug::INFO, "Read unicode symbol " << symbol << " '"
777 << to_utf8(info.textcommand()) << "' '" << info.textpreamble()
778 << " '" << info.textfeature() << ' ' << info.textnotermination()
779 << ' ' << to_utf8(info.mathcommand()) << "' '" << info.mathpreamble()
780 << "' " << info.mathfeature() << ' ' << info.mathnotermination()
781 << ' ' << info.combining() << ' ' << info.force()
782 << ' ' << info.forceselected());
784 // we assume that at least one command is nonempty when using unicodesymbols
785 if (info.isUnicodeSymbol()) {
786 unicodesymbols[symbol] = info;
793 // Now read the encodings
799 LexerKeyword encodingtags[] = {
800 { "encoding", et_encoding },
804 Lexer lex(encodingtags);
805 lex.setFile(encfile);
806 lex.setContext("Encodings::read");
812 string const name = lex.getString();
814 string const latexname = lex.getString();
816 string const guiname = lex.getString();
818 string const iconvname = lex.getString();
820 string const width = lex.getString();
821 bool fixedwidth = false;
823 if (width == "fixed")
825 else if (width == "variable")
827 else if (width == "variableunsafe") {
832 lex.printError("Unknown width");
835 string const p = lex.getString();
836 Encoding::Package package = Encoding::none;
838 package = Encoding::none;
839 else if (p == "inputenc")
840 package = Encoding::inputenc;
842 package = Encoding::CJK;
843 else if (p == "japanese")
844 package = Encoding::japanese;
846 lex.printError("Unknown package");
848 LYXERR(Debug::INFO, "Reading encoding " << name);
849 encodinglist[name] = Encoding(name, latexname,
850 guiname, iconvname, fixedwidth, unsafe,
853 if (lex.lex() != et_end)
854 lex.printError("Missing end");
858 lex.printError("Misplaced end");
860 case Lexer::LEX_FEOF:
863 lex.printError("Unknown tag");
868 // Move all information from forcednotselected to forcedselected
869 for (CharSetMap::const_iterator it1 = forcednotselected.begin(); it1 != forcednotselected.end(); ++it1) {
870 for (CharSetMap::iterator it2 = forcedselected.begin(); it2 != forcedselected.end(); ++it2) {
871 if (it2->first != it1->first)
872 it2->second.insert(it1->second.begin(), it1->second.end());