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/textutils.h"
23 #include "support/unicode.h"
25 #include <boost/cstdint.hpp>
31 using namespace lyx::support;
35 int const Encoding::any = -1;
39 Encodings::MathCommandSet Encodings::mathcmd;
40 Encodings::TextCommandSet Encodings::textcmd;
41 Encodings::MathSymbolSet Encodings::mathsym;
45 typedef map<char_type, CharInfo> CharInfoMap;
46 CharInfoMap unicodesymbols;
48 typedef set<char_type> CharSet;
49 typedef map<string, CharSet> CharSetMap;
51 CharSetMap forcedselected;
53 typedef set<char_type> MathAlphaSet;
54 MathAlphaSet mathalpha;
57 /// The highest code point in UCS4 encoding (1<<20 + 1<<16)
58 char_type const max_ucs4 = 0x110000;
63 EncodingException::EncodingException(char_type c)
64 : failed_char(c), par_id(0), pos(0)
69 const char * EncodingException::what() const throw()
71 return "Could not find LaTeX command for a character";
76 docstring const & textcommand, docstring const & mathcommand,
77 std::string const & textpreamble, std::string const & mathpreamble,
78 std::string const & tipashortcut, unsigned int flags)
79 : textcommand_(textcommand), mathcommand_(mathcommand),
80 textpreamble_(textpreamble), mathpreamble_(mathpreamble),
81 tipashortcut_(tipashortcut), flags_(flags)
86 Encoding::Encoding(string const & n, string const & l, string const & g,
87 string const & i, bool f, bool u, Encoding::Package p)
88 : name_(n), latexName_(l), guiName_(g), iconvName_(i), fixedwidth_(f),
89 unsafe_(u), forced_(&forcedselected[n]), package_(p)
92 // ASCII can encode 128 code points and nothing else
93 start_encodable_ = 128;
95 } else if (i == "UTF-8") {
96 // UTF8 can encode all UCS4 code points
97 start_encodable_ = max_ucs4;
100 start_encodable_ = 0;
106 void Encoding::init() const
111 start_encodable_ = 0;
112 // temporarily switch off lyxerr, since we will generate iconv errors
115 // We do not need to check all UCS4 code points, it is enough
116 // if we check all 256 code points of this encoding.
117 for (unsigned short j = 0; j < 256; ++j) {
118 char const c = char(j);
119 vector<char_type> const ucs4 = eightbit_to_ucs4(&c, 1, iconvName_);
120 if (ucs4.size() != 1)
122 char_type const uc = ucs4[0];
123 CharInfoMap::const_iterator const it = unicodesymbols.find(uc);
124 if (it == unicodesymbols.end())
125 encodable_.insert(uc);
126 else if (!it->second.force()) {
127 if (forced_->empty() || forced_->find(uc) == forced_->end())
128 encodable_.insert(uc);
132 // We do not know how many code points this encoding has, and
133 // they do not have a direct representation as a single byte,
134 // therefore we need to check all UCS4 code points.
135 // This is expensive!
136 for (char_type c = 0; c < max_ucs4; ++c) {
137 vector<char> const eightbit = ucs4_to_eightbit(&c, 1, iconvName_);
138 if (!eightbit.empty()) {
139 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
140 if (it == unicodesymbols.end())
141 encodable_.insert(c);
142 else if (!it->second.force()) {
143 if (forced_->empty() || forced_->find(c) == forced_->end())
144 encodable_.insert(c);
150 CharSet::iterator it = encodable_.find(start_encodable_);
151 while (it != encodable_.end()) {
152 encodable_.erase(it);
154 it = encodable_.find(start_encodable_);
160 bool Encoding::isForced(char_type c) const
162 if (!forced.empty() && forced.find(c) != forced.end())
164 return !forced_->empty() && forced_->find(c) != forced_->end();
168 bool Encoding::encodable(char_type c) const
170 // assure the used encoding is properly initialized
173 if (iconvName_ == "UTF-8" && package_ == none)
175 if (c < start_encodable_ && !isForced(c))
177 if (encodable_.find(c) != encodable_.end())
183 pair<docstring, bool> Encoding::latexChar(char_type c) const
186 return make_pair(docstring(1, c), false);
188 // c cannot (or should not) be encoded in this encoding
189 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
190 if (it == unicodesymbols.end())
191 throw EncodingException(c);
192 // at least one of mathcommand and textcommand is nonempty
193 if (it->second.textcommand().empty())
195 "\\ensuremath{" + it->second.mathcommand() + '}', false);
196 return make_pair(it->second.textcommand(), !it->second.textnotermination());
200 pair<docstring, docstring> Encoding::latexString(docstring const & input, bool dryrun) const
204 bool terminate = false;
205 for (size_t n = 0; n < input.size(); ++n) {
207 char_type const c = input[n];
208 pair<docstring, bool> latex_char = latexChar(c);
209 docstring const latex = latex_char.first;
210 if (terminate && !prefixIs(latex, '\\')
211 && !prefixIs(latex, '{')
212 && !prefixIs(latex, '}')) {
213 // Prevent eating of a following
214 // space or command corruption by
215 // following characters
222 terminate = latex_char.second;
223 } catch (EncodingException & /* e */) {
224 LYXERR0("Uncodable character in latexString!");
226 result += "<" + _("LyX Warning: ")
227 + _("uncodable character") + " '";
228 result += docstring(1, input[n]);
231 uncodable += input[n];
234 return make_pair(result, uncodable);
238 vector<char_type> Encoding::symbolsList() const
240 // assure the used encoding is properly initialized
243 // first all encodable characters
244 vector<char_type> symbols(encodable_.begin(), encodable_.end());
245 // add those below start_encodable_
246 for (char_type c = 0; c < start_encodable_; ++c)
247 symbols.push_back(c);
248 // now the ones from the unicodesymbols file
249 CharInfoMap::const_iterator const end = unicodesymbols.end();
250 CharInfoMap::const_iterator it = unicodesymbols.begin();
251 for (; it != end; ++it)
252 symbols.push_back(it->first);
257 bool Encodings::latexMathChar(char_type c, bool mathmode,
258 Encoding const * encoding, docstring & command,
259 bool & needsTermination)
261 command = empty_docstring();
263 if (encoding->encodable(c))
264 command = docstring(1, c);
265 needsTermination = false;
267 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
268 if (it == unicodesymbols.end()) {
269 if (!encoding || command.empty())
270 throw EncodingException(c);
275 // at least one of mathcommand and textcommand is nonempty
276 bool use_math = (mathmode && !it->second.mathcommand().empty()) ||
277 (!mathmode && it->second.textcommand().empty());
279 command = it->second.mathcommand();
280 needsTermination = !it->second.mathnotermination();
283 if (!encoding || command.empty()) {
284 command = it->second.textcommand();
285 needsTermination = !it->second.textnotermination();
295 char_type Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
296 bool & combining, bool & needsTermination, set<string> * req)
298 CharInfoMap::const_iterator const end = unicodesymbols.end();
299 CharInfoMap::const_iterator it = unicodesymbols.begin();
300 for (combining = false; it != end; ++it) {
301 docstring const math = it->second.mathcommand();
302 docstring const text = it->second.textcommand();
303 if ((cmdtype & MATH_CMD) && math == cmd) {
304 combining = it->second.combining();
305 needsTermination = !it->second.mathnotermination();
306 if (req && it->second.mathfeature() &&
307 !it->second.mathpreamble().empty())
308 req->insert(it->second.mathpreamble());
311 if ((cmdtype & TEXT_CMD) && text == cmd) {
312 combining = it->second.combining();
313 needsTermination = !it->second.textnotermination();
314 if (req && it->second.textfeature() &&
315 !it->second.textpreamble().empty())
316 req->insert(it->second.textpreamble());
320 needsTermination = false;
325 docstring Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
326 bool & needsTermination, docstring & rem, set<string> * req)
328 needsTermination = false;
329 rem = empty_docstring();
330 bool const mathmode = cmdtype & MATH_CMD;
331 bool const textmode = cmdtype & TEXT_CMD;
333 size_t const cmdend = cmd.size();
335 CharInfoMap::const_iterator const uniend = unicodesymbols.end();
336 for (size_t i = 0, j = 0; j < cmdend; ++j) {
337 // Also get the char after a backslash
338 if (j + 1 < cmdend && cmd[j] == '\\') {
341 // Detect things like \=*{e} as well
342 if (j + 3 < cmdend && cmd[j+1] == '*' &&
348 // position of the last character before a possible macro
351 // If a macro argument follows, get it, too
352 // Do it here only for single character commands. Other
353 // combining commands need this too, but they are handled in
354 // the loop below for performance reasons.
355 if (j + 1 < cmdend && cmd[j + 1] == '{') {
358 while (k < cmdend && count) {
359 k = cmd.find_first_of(from_ascii("{}"), k + 1);
360 // braces may not be balanced
361 if (k == docstring::npos)
368 if (k != docstring::npos)
370 } else if (m + 1 < cmdend && isAlphaASCII(cmd[m])) {
371 while (m + 2 < cmdend && isAlphaASCII(cmd[m+1]))
374 // Start with this substring and try augmenting it when it is
375 // the prefix of some command in the unicodesymbols file
376 docstring subcmd = cmd.substr(i, j - i + 1);
378 CharInfoMap::const_iterator it = unicodesymbols.begin();
379 // First part of subcmd which might be a combining character
380 docstring combcmd = (m == j) ? docstring() : cmd.substr(i, m - i + 1);
381 // The combining character of combcmd if it exists
382 CharInfoMap::const_iterator combining = uniend;
383 size_t unicmd_size = 0;
385 for (; it != uniend; ++it) {
386 docstring const math = mathmode ? it->second.mathcommand()
388 docstring const text = textmode ? it->second.textcommand()
390 if (!combcmd.empty() && it->second.combining() &&
391 (math == combcmd || text == combcmd))
393 size_t cur_size = max(math.size(), text.size());
394 // The current math or text unicode command cannot
395 // match, or we already matched a longer one
396 if (cur_size < subcmd.size() || cur_size <= unicmd_size)
399 docstring tmp = subcmd;
401 while (prefixIs(math, tmp) || prefixIs(text, tmp)) {
403 if (k >= cmdend || cur_size <= tmp.size())
411 // The last added char caused a mismatch, because
412 // we didn't exhaust the chars in cmd and didn't
413 // exceed the maximum size of the current unicmd
414 if (k < cmdend && cur_size > tmp.size())
415 tmp.resize(tmp.size() - 1);
417 // If this is an exact match, we found a (longer)
418 // matching entry in the unicodesymbols file.
419 if (math != tmp && text != tmp)
421 // If we found a combining command, we need to append
422 // the macro argument if this has not been done above.
423 if (tmp == combcmd && combining != uniend &&
424 k < cmdend && cmd[k] == '{') {
427 while (l < cmdend && count) {
428 l = cmd.find_first_of(from_ascii("{}"), l + 1);
429 // braces may not be balanced
430 if (l == docstring::npos)
437 if (l != docstring::npos) {
439 subcmd = cmd.substr(i, j - i + 1);
442 // If the entry doesn't start with '\', we take note
443 // of the match and continue (this is not a ultimate
444 // acceptance, as some other entry may match a longer
445 // portion of the cmd string). However, if the entry
446 // does start with '\', we accept the match only if
447 // this is a valid macro, i.e., either it is a single
448 // (nonletter) char macro, or nothing else follows,
449 // or what follows is a nonletter char, or the last
451 else if (tmp[0] != '\\'
452 || (tmp.size() == prefix + 1 &&
453 !isAlphaASCII(tmp[1]) &&
454 (prefix == 1 || !isAlphaASCII(tmp[2])))
456 || !isAlphaASCII(cmd[k])
457 || tmp[tmp.size() - 1] == '}'
462 unicmd_size = cur_size;
464 needsTermination = !it->second.mathnotermination();
466 needsTermination = !it->second.textnotermination();
468 if (math == tmp && it->second.mathfeature() &&
469 !it->second.mathpreamble().empty())
470 req->insert(it->second.mathpreamble());
471 if (text == tmp && it->second.textfeature() &&
472 !it->second.textpreamble().empty())
473 req->insert(it->second.textpreamble());
479 else if (combining != uniend &&
480 prefixIs(subcmd, combcmd + '{')) {
481 // We know that subcmd starts with combcmd and
482 // contains an argument in braces.
483 docstring const arg = subcmd.substr(
484 combcmd.length() + 1,
485 subcmd.length() - combcmd.length() - 2);
486 // If arg is a single character we can construct a
487 // combining sequence.
489 bool argcomb = false;
490 if (arg.size() == 1 && isAlnumASCII(arg[0]))
493 // Use the version of fromLaTeXCommand() that
494 // parses only one command, since we cannot
495 // use more than one character.
498 a = fromLaTeXCommand(arg, cmdtype, argcomb,
500 if (a && req && !argcomb)
501 req->insert(r.begin(), r.end());
504 // In unicode the combining character comes
507 symbols += combining->first;
512 if (j + 1 == cmdend && !unicmd_size) {
513 // No luck. Return what remains
515 if (needsTermination && !rem.empty()) {
516 if (rem.substr(0, 2) == "{}") {
518 needsTermination = false;
519 } else if (rem[0] == ' ') {
520 needsTermination = false;
521 // LaTeX would swallow all spaces
531 CharInfo const & Encodings::unicodeCharInfo(char_type c)
533 static CharInfo empty;
534 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
535 return it != unicodesymbols.end() ? it->second : empty;
539 bool Encodings::isCombiningChar(char_type c)
541 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
542 if (it != unicodesymbols.end())
543 return it->second.combining();
548 string const Encodings::TIPAShortcut(char_type c)
550 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
551 if (it != unicodesymbols.end())
552 return it->second.tipashortcut();
557 bool Encodings::isKnownScriptChar(char_type const c, string & preamble)
559 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
561 if (it == unicodesymbols.end())
564 if (it->second.textpreamble() != "textgreek" && it->second.textpreamble() != "textcyr")
567 if (preamble.empty()) {
568 preamble = it->second.textpreamble();
571 return it->second.textpreamble() == preamble;
575 bool Encodings::isMathAlpha(char_type c)
577 return mathalpha.count(c);
582 Encodings::fromLyXName(string const & name, bool allowUnsafe) const
584 EncodingList::const_iterator const it = encodinglist.find(name);
585 if (it == encodinglist.end())
587 if (!allowUnsafe && it->second.unsafe())
594 Encodings::fromLaTeXName(string const & n, int const & p, bool allowUnsafe) const
597 // FIXME: if we have to test for too many of these synonyms,
598 // we should instead extend the format of lib/encodings
602 // We don't use find_if because it makes copies of the pairs in
604 // This linear search is OK since we don't have many encodings.
605 // Users could even optimize it by putting the encodings they use
606 // most at the top of lib/encodings.
607 EncodingList::const_iterator const end = encodinglist.end();
608 for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
609 if ((it->second.latexName() == name) && (it->second.package() & p)
610 && (!it->second.unsafe() || allowUnsafe))
617 Encodings::fromIconvName(string const & n, int const & p, bool allowUnsafe) const
619 EncodingList::const_iterator const end = encodinglist.end();
620 for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
621 if ((it->second.iconvName() == n) && (it->second.package() & p)
622 && (!it->second.unsafe() || allowUnsafe))
628 Encodings::Encodings()
632 void Encodings::read(FileName const & encfile, FileName const & symbolsfile)
634 // We must read the symbolsfile first, because the Encoding
635 // constructor depends on it.
636 CharSetMap forcednotselected;
638 symbolslex.setFile(symbolsfile);
639 bool getNextToken = true;
640 while (symbolslex.isOK()) {
644 if (!symbolslex.next(true))
649 istringstream is(symbolslex.getString());
650 // reading symbol directly does not work if
651 // char_type == wchar_t.
653 if(!(is >> hex >> tmp))
657 if (!symbolslex.next(true))
659 docstring textcommand = symbolslex.getDocString();
660 if (!symbolslex.next(true))
662 string textpreamble = symbolslex.getString();
663 if (!symbolslex.next(true))
665 string sflags = symbolslex.getString();
670 if (suffixIs(textcommand, '}'))
671 flags |= CharInfoTextNoTermination;
672 while (!sflags.empty()) {
674 sflags = split(sflags, flag, ',');
675 if (flag == "combining") {
676 flags |= CharInfoCombining;
677 } else if (flag == "force") {
678 flags |= CharInfoForce;
679 forced.insert(symbol);
680 } else if (prefixIs(flag, "force=")) {
681 vector<string> encodings =
682 getVectorFromString(flag.substr(6), ";");
683 for (size_t i = 0; i < encodings.size(); ++i)
684 forcedselected[encodings[i]].insert(symbol);
685 flags |= CharInfoForceSelected;
686 } else if (prefixIs(flag, "force!=")) {
687 vector<string> encodings =
688 getVectorFromString(flag.substr(7), ";");
689 for (size_t i = 0; i < encodings.size(); ++i)
690 forcednotselected[encodings[i]].insert(symbol);
691 flags |= CharInfoForceSelected;
692 } else if (flag == "mathalpha") {
693 mathalpha.insert(symbol);
694 } else if (flag == "notermination=text") {
695 flags |= CharInfoTextNoTermination;
696 } else if (flag == "notermination=math") {
697 flags |= CharInfoMathNoTermination;
698 } else if (flag == "notermination=both") {
699 flags |= CharInfoTextNoTermination;
700 flags |= CharInfoMathNoTermination;
701 } else if (flag == "notermination=none") {
702 flags &= ~CharInfoTextNoTermination;
703 flags &= ~CharInfoMathNoTermination;
704 } else if (contains(flag, "tipashortcut=")) {
705 tipashortcut = split(flag, '=');
707 lyxerr << "Ignoring unknown flag `" << flag
708 << "' for symbol `0x"
709 << hex << symbol << dec
713 // mathcommand and mathpreamble have been added for 1.6.0.
714 // make them optional so that old files still work.
715 int const lineno = symbolslex.lineNumber();
716 bool breakout = false;
717 docstring mathcommand;
719 if (symbolslex.next(true)) {
720 if (symbolslex.lineNumber() != lineno) {
721 // line in old format without mathcommand and mathpreamble
722 getNextToken = false;
724 mathcommand = symbolslex.getDocString();
725 if (suffixIs(mathcommand, '}'))
726 flags |= CharInfoMathNoTermination;
727 if (symbolslex.next(true)) {
728 if (symbolslex.lineNumber() != lineno) {
729 // line in new format with mathcommand only
730 getNextToken = false;
732 // line in new format with mathcommand and mathpreamble
733 mathpreamble = symbolslex.getString();
742 // backward compatibility
743 if (mathpreamble == "esintoramsmath")
744 mathpreamble = "esint|amsmath";
746 if (!textpreamble.empty())
747 if (textpreamble[0] != '\\')
748 flags |= CharInfoTextFeature;
749 if (!mathpreamble.empty())
750 if (mathpreamble[0] != '\\')
751 flags |= CharInfoMathFeature;
753 CharInfo info = CharInfo(
754 textcommand, mathcommand,
755 textpreamble, mathpreamble,
756 tipashortcut, flags);
757 LYXERR(Debug::INFO, "Read unicode symbol " << symbol << " '"
758 << to_utf8(info.textcommand()) << "' '" << info.textpreamble()
759 << " '" << info.textfeature() << ' ' << info.textnotermination()
760 << ' ' << to_utf8(info.mathcommand()) << "' '" << info.mathpreamble()
761 << "' " << info.mathfeature() << ' ' << info.mathnotermination()
762 << ' ' << info.combining() << ' ' << info.force()
763 << ' ' << info.forceselected());
765 // we assume that at least one command is nonempty when using unicodesymbols
766 if (info.isUnicodeSymbol()) {
767 unicodesymbols[symbol] = info;
774 // Now read the encodings
780 LexerKeyword encodingtags[] = {
781 { "encoding", et_encoding },
785 Lexer lex(encodingtags);
786 lex.setFile(encfile);
787 lex.setContext("Encodings::read");
793 string const name = lex.getString();
795 string const latexname = lex.getString();
797 string const guiname = lex.getString();
799 string const iconvname = lex.getString();
801 string const width = lex.getString();
802 bool fixedwidth = false;
804 if (width == "fixed")
806 else if (width == "variable")
808 else if (width == "variableunsafe") {
813 lex.printError("Unknown width");
816 string const p = lex.getString();
817 Encoding::Package package = Encoding::none;
819 package = Encoding::none;
820 else if (p == "inputenc")
821 package = Encoding::inputenc;
823 package = Encoding::CJK;
824 else if (p == "japanese")
825 package = Encoding::japanese;
827 lex.printError("Unknown package");
829 LYXERR(Debug::INFO, "Reading encoding " << name);
830 encodinglist[name] = Encoding(name, latexname,
831 guiname, iconvname, fixedwidth, unsafe,
834 if (lex.lex() != et_end)
835 lex.printError("Missing end");
839 lex.printError("Misplaced end");
841 case Lexer::LEX_FEOF:
844 lex.printError("Unknown tag");
849 // Move all information from forcednotselected to forcedselected
850 for (CharSetMap::const_iterator it1 = forcednotselected.begin(); it1 != forcednotselected.end(); ++it1) {
851 for (CharSetMap::iterator it2 = forcedselected.begin(); it2 != forcedselected.end(); ++it2) {
852 if (it2->first != it1->first)
853 it2->second.insert(it1->second.begin(), it1->second.end());