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)
85 Encoding::Encoding(string const & n, string const & l, string const & g,
86 string const & i, bool f, bool u, Encoding::Package p)
87 : name_(n), latexName_(l), guiName_(g), iconvName_(i), fixedwidth_(f),
88 unsafe_(u), forced_(&forcedselected[n]), package_(p)
91 // ASCII can encode 128 code points and nothing else
92 start_encodable_ = 128;
94 } else if (i == "UTF-8") {
95 // UTF8 can encode all UCS4 code points
96 start_encodable_ = max_ucs4;
105 void Encoding::init() const
110 start_encodable_ = 0;
111 // temporarily switch off lyxerr, since we will generate iconv errors
114 // We do not need to check all UCS4 code points, it is enough
115 // if we check all 256 code points of this encoding.
116 for (unsigned short j = 0; j < 256; ++j) {
117 char const c = char(j);
118 vector<char_type> const ucs4 = eightbit_to_ucs4(&c, 1, iconvName_);
119 if (ucs4.size() != 1)
121 char_type const uc = ucs4[0];
122 CharInfoMap::const_iterator const it = unicodesymbols.find(uc);
123 if (it == unicodesymbols.end())
124 encodable_.insert(uc);
125 else if (!it->second.force()) {
126 if (forced_->empty() || forced_->find(uc) == forced_->end())
127 encodable_.insert(uc);
131 // We do not know how many code points this encoding has, and
132 // they do not have a direct representation as a single byte,
133 // therefore we need to check all UCS4 code points.
134 // This is expensive!
135 for (char_type c = 0; c < max_ucs4; ++c) {
136 vector<char> const eightbit = ucs4_to_eightbit(&c, 1, iconvName_);
137 if (!eightbit.empty()) {
138 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
139 if (it == unicodesymbols.end())
140 encodable_.insert(c);
141 else if (!it->second.force()) {
142 if (forced_->empty() || forced_->find(c) == forced_->end())
143 encodable_.insert(c);
149 CharSet::iterator it = encodable_.find(start_encodable_);
150 while (it != encodable_.end()) {
151 encodable_.erase(it);
153 it = encodable_.find(start_encodable_);
159 bool Encoding::isForced(char_type c) const
161 if (!forced.empty() && forced.find(c) != forced.end())
163 return !forced_->empty() && forced_->find(c) != forced_->end();
167 bool Encoding::encodable(char_type c) const
169 // assure the used encoding is properly initialized
172 if (iconvName_ == "UTF-8" && package_ == none)
174 if (c < start_encodable_ && !isForced(c))
176 if (encodable_.find(c) != encodable_.end())
182 pair<docstring, bool> Encoding::latexChar(char_type c) const
185 return make_pair(docstring(1, c), false);
187 // c cannot (or should not) be encoded in this encoding
188 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
189 if (it == unicodesymbols.end())
190 throw EncodingException(c);
191 // at least one of mathcommand and textcommand is nonempty
192 if (it->second.textcommand().empty())
194 "\\ensuremath{" + it->second.mathcommand() + '}', false);
195 return make_pair(it->second.textcommand(), !it->second.textnotermination());
199 pair<docstring, docstring> Encoding::latexString(docstring const & input, bool dryrun) const
203 bool terminate = false;
204 for (size_t n = 0; n < input.size(); ++n) {
206 char_type const c = input[n];
207 pair<docstring, bool> latex_char = latexChar(c);
208 docstring const latex = latex_char.first;
209 if (terminate && !prefixIs(latex, '\\')
210 && !prefixIs(latex, '{')
211 && !prefixIs(latex, '}')) {
212 // Prevent eating of a following
213 // space or command corruption by
214 // following characters
221 terminate = latex_char.second;
222 } catch (EncodingException & /* e */) {
223 LYXERR0("Uncodable character in latexString!");
225 result += "<" + _("LyX Warning: ")
226 + _("uncodable character") + " '";
227 result += docstring(1, input[n]);
230 uncodable += input[n];
233 return make_pair(result, uncodable);
237 vector<char_type> Encoding::symbolsList() const
239 // assure the used encoding is properly initialized
242 // first all encodable characters
243 vector<char_type> symbols(encodable_.begin(), encodable_.end());
244 // add those below start_encodable_
245 for (char_type c = 0; c < start_encodable_; ++c)
246 symbols.push_back(c);
247 // now the ones from the unicodesymbols file
248 CharInfoMap::const_iterator const end = unicodesymbols.end();
249 CharInfoMap::const_iterator it = unicodesymbols.begin();
250 for (; it != end; ++it)
251 symbols.push_back(it->first);
256 bool Encodings::latexMathChar(char_type c, bool mathmode,
257 Encoding const * encoding, docstring & command,
258 bool & needsTermination)
260 command = empty_docstring();
262 if (encoding->encodable(c))
263 command = docstring(1, c);
264 needsTermination = false;
266 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
267 if (it == unicodesymbols.end()) {
268 if (!encoding || command.empty())
269 throw EncodingException(c);
274 // at least one of mathcommand and textcommand is nonempty
275 bool use_math = (mathmode && !it->second.mathcommand().empty()) ||
276 (!mathmode && it->second.textcommand().empty());
278 command = it->second.mathcommand();
279 needsTermination = !it->second.mathnotermination();
282 if (!encoding || command.empty()) {
283 command = it->second.textcommand();
284 needsTermination = !it->second.textnotermination();
294 char_type Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
295 bool & combining, bool & needsTermination, set<string> * req)
297 CharInfoMap::const_iterator const end = unicodesymbols.end();
298 CharInfoMap::const_iterator it = unicodesymbols.begin();
299 for (combining = false; it != end; ++it) {
300 docstring const math = it->second.mathcommand();
301 docstring const text = it->second.textcommand();
302 if ((cmdtype & MATH_CMD) && math == cmd) {
303 combining = it->second.combining();
304 needsTermination = !it->second.mathnotermination();
305 if (req && it->second.mathfeature() &&
306 !it->second.mathpreamble().empty())
307 req->insert(it->second.mathpreamble());
310 if ((cmdtype & TEXT_CMD) && text == cmd) {
311 combining = it->second.combining();
312 needsTermination = !it->second.textnotermination();
313 if (req && it->second.textfeature() &&
314 !it->second.textpreamble().empty())
315 req->insert(it->second.textpreamble());
319 needsTermination = false;
324 docstring Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
325 bool & needsTermination, docstring & rem, set<string> * req)
327 needsTermination = false;
328 rem = empty_docstring();
329 bool const mathmode = cmdtype & MATH_CMD;
330 bool const textmode = cmdtype & TEXT_CMD;
332 size_t const cmdend = cmd.size();
334 CharInfoMap::const_iterator const uniend = unicodesymbols.end();
335 for (size_t i = 0, j = 0; j < cmdend; ++j) {
336 // Also get the char after a backslash
337 if (j + 1 < cmdend && cmd[j] == '\\') {
340 // Detect things like \=*{e} as well
341 if (j + 3 < cmdend && cmd[j+1] == '*' &&
347 // position of the last character before a possible macro
350 // If a macro argument follows, get it, too
351 // Do it here only for single character commands. Other
352 // combining commands need this too, but they are handled in
353 // the loop below for performance reasons.
354 if (j + 1 < cmdend && cmd[j + 1] == '{') {
357 while (k < cmdend && count) {
358 k = cmd.find_first_of(from_ascii("{}"), k + 1);
359 // braces may not be balanced
360 if (k == docstring::npos)
367 if (k != docstring::npos)
369 } else if (m + 1 < cmdend && isAlphaASCII(cmd[m])) {
370 while (m + 2 < cmdend && isAlphaASCII(cmd[m+1]))
373 // Start with this substring and try augmenting it when it is
374 // the prefix of some command in the unicodesymbols file
375 docstring subcmd = cmd.substr(i, j - i + 1);
377 CharInfoMap::const_iterator it = unicodesymbols.begin();
378 // First part of subcmd which might be a combining character
379 docstring combcmd = (m == j) ? docstring() : cmd.substr(i, m - i + 1);
380 // The combining character of combcmd if it exists
381 CharInfoMap::const_iterator combining = uniend;
382 size_t unicmd_size = 0;
384 for (; it != uniend; ++it) {
385 docstring const math = mathmode ? it->second.mathcommand()
387 docstring const text = textmode ? it->second.textcommand()
389 if (!combcmd.empty() && it->second.combining() &&
390 (math == combcmd || text == combcmd))
392 size_t cur_size = max(math.size(), text.size());
393 // The current math or text unicode command cannot
394 // match, or we already matched a longer one
395 if (cur_size < subcmd.size() || cur_size <= unicmd_size)
398 docstring tmp = subcmd;
400 while (prefixIs(math, tmp) || prefixIs(text, tmp)) {
402 if (k >= cmdend || cur_size <= tmp.size())
410 // The last added char caused a mismatch, because
411 // we didn't exhaust the chars in cmd and didn't
412 // exceed the maximum size of the current unicmd
413 if (k < cmdend && cur_size > tmp.size())
414 tmp.resize(tmp.size() - 1);
416 // If this is an exact match, we found a (longer)
417 // matching entry in the unicodesymbols file.
418 if (math != tmp && text != tmp)
420 // If we found a combining command, we need to append
421 // the macro argument if this has not been done above.
422 if (tmp == combcmd && combining != uniend &&
423 k < cmdend && cmd[k] == '{') {
426 while (l < cmdend && count) {
427 l = cmd.find_first_of(from_ascii("{}"), l + 1);
428 // braces may not be balanced
429 if (l == docstring::npos)
436 if (l != docstring::npos) {
438 subcmd = cmd.substr(i, j - i + 1);
441 // If the entry doesn't start with '\', we take note
442 // of the match and continue (this is not a ultimate
443 // acceptance, as some other entry may match a longer
444 // portion of the cmd string). However, if the entry
445 // does start with '\', we accept the match only if
446 // this is a valid macro, i.e., either it is a single
447 // (nonletter) char macro, or nothing else follows,
448 // or what follows is a nonletter char, or the last
450 else if (tmp[0] != '\\'
451 || (tmp.size() == prefix + 1 &&
452 !isAlphaASCII(tmp[1]) &&
453 (prefix == 1 || !isAlphaASCII(tmp[2])))
455 || !isAlphaASCII(cmd[k])
456 || tmp[tmp.size() - 1] == '}'
461 unicmd_size = cur_size;
463 needsTermination = !it->second.mathnotermination();
465 needsTermination = !it->second.textnotermination();
467 if (math == tmp && it->second.mathfeature() &&
468 !it->second.mathpreamble().empty())
469 req->insert(it->second.mathpreamble());
470 if (text == tmp && it->second.textfeature() &&
471 !it->second.textpreamble().empty())
472 req->insert(it->second.textpreamble());
478 else if (combining != uniend &&
479 prefixIs(subcmd, combcmd + '{')) {
480 // We know that subcmd starts with combcmd and
481 // contains an argument in braces.
482 docstring const arg = subcmd.substr(
483 combcmd.length() + 1,
484 subcmd.length() - combcmd.length() - 2);
485 // If arg is a single character we can construct a
486 // combining sequence.
488 bool argcomb = false;
489 if (arg.size() == 1 && isAlnumASCII(arg[0]))
492 // Use the version of fromLaTeXCommand() that
493 // parses only one command, since we cannot
494 // use more than one character.
497 a = fromLaTeXCommand(arg, cmdtype, argcomb,
499 if (a && req && !argcomb)
500 req->insert(r.begin(), r.end());
503 // In unicode the combining character comes
506 symbols += combining->first;
511 if (j + 1 == cmdend && !unicmd_size) {
512 // No luck. Return what remains
514 if (needsTermination && !rem.empty()) {
515 if (rem.substr(0, 2) == "{}") {
517 needsTermination = false;
518 } else if (rem[0] == ' ') {
519 needsTermination = false;
520 // LaTeX would swallow all spaces
530 CharInfo const & Encodings::unicodeCharInfo(char_type c)
532 static CharInfo empty;
533 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
534 return it != unicodesymbols.end() ? it->second : empty;
538 bool Encodings::isCombiningChar(char_type c)
540 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
541 if (it != unicodesymbols.end())
542 return it->second.combining();
547 string const Encodings::TIPAShortcut(char_type c)
549 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
550 if (it != unicodesymbols.end())
551 return it->second.tipashortcut();
556 bool Encodings::isKnownScriptChar(char_type const c, string & preamble)
558 CharInfoMap::const_iterator const it = unicodesymbols.find(c);
560 if (it == unicodesymbols.end())
563 if (it->second.textpreamble() != "textgreek" && it->second.textpreamble() != "textcyr")
566 if (preamble.empty()) {
567 preamble = it->second.textpreamble();
570 return it->second.textpreamble() == preamble;
574 bool Encodings::isMathAlpha(char_type c)
576 return mathalpha.count(c);
581 Encodings::fromLyXName(string const & name, bool allowUnsafe) const
583 EncodingList::const_iterator const it = encodinglist.find(name);
584 if (!allowUnsafe && it->second.unsafe())
586 return it != encodinglist.end() ? &it->second : 0;
591 Encodings::fromLaTeXName(string const & n, int const & p, bool allowUnsafe) const
594 // FIXME: if we have to test for too many of these synonyms,
595 // we should instead extend the format of lib/encodings
599 // We don't use find_if because it makes copies of the pairs in
601 // This linear search is OK since we don't have many encodings.
602 // Users could even optimize it by putting the encodings they use
603 // most at the top of lib/encodings.
604 EncodingList::const_iterator const end = encodinglist.end();
605 for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
606 if ((it->second.latexName() == name) && (it->second.package() & p)
607 && (!it->second.unsafe() || allowUnsafe))
614 Encodings::fromIconvName(string const & n, int const & p, bool allowUnsafe) const
616 EncodingList::const_iterator const end = encodinglist.end();
617 for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
618 if ((it->second.iconvName() == n) && (it->second.package() & p)
619 && (!it->second.unsafe() || allowUnsafe))
625 Encodings::Encodings()
629 void Encodings::read(FileName const & encfile, FileName const & symbolsfile)
631 // We must read the symbolsfile first, because the Encoding
632 // constructor depends on it.
633 CharSetMap forcednotselected;
635 symbolslex.setFile(symbolsfile);
636 bool getNextToken = true;
637 while (symbolslex.isOK()) {
641 if (!symbolslex.next(true))
646 istringstream is(symbolslex.getString());
647 // reading symbol directly does not work if
648 // char_type == wchar_t.
650 if(!(is >> hex >> tmp))
654 if (!symbolslex.next(true))
656 docstring textcommand = symbolslex.getDocString();
657 if (!symbolslex.next(true))
659 string textpreamble = symbolslex.getString();
660 if (!symbolslex.next(true))
662 string sflags = symbolslex.getString();
667 if (suffixIs(textcommand, '}'))
668 flags |= CharInfoTextNoTermination;
669 while (!sflags.empty()) {
671 sflags = split(sflags, flag, ',');
672 if (flag == "combining") {
673 flags |= CharInfoCombining;
674 } else if (flag == "force") {
675 flags |= CharInfoForce;
676 forced.insert(symbol);
677 } else if (prefixIs(flag, "force=")) {
678 vector<string> encodings =
679 getVectorFromString(flag.substr(6), ";");
680 for (size_t i = 0; i < encodings.size(); ++i)
681 forcedselected[encodings[i]].insert(symbol);
682 flags |= CharInfoForceSelected;
683 } else if (prefixIs(flag, "force!=")) {
684 vector<string> encodings =
685 getVectorFromString(flag.substr(7), ";");
686 for (size_t i = 0; i < encodings.size(); ++i)
687 forcednotselected[encodings[i]].insert(symbol);
688 flags |= CharInfoForceSelected;
689 } else if (flag == "mathalpha") {
690 mathalpha.insert(symbol);
691 } else if (flag == "notermination=text") {
692 flags |= CharInfoTextNoTermination;
693 } else if (flag == "notermination=math") {
694 flags |= CharInfoMathNoTermination;
695 } else if (flag == "notermination=both") {
696 flags |= CharInfoTextNoTermination;
697 flags |= CharInfoMathNoTermination;
698 } else if (flag == "notermination=none") {
699 flags &= ~CharInfoTextNoTermination;
700 flags &= ~CharInfoMathNoTermination;
701 } else if (contains(flag, "tipashortcut=")) {
702 tipashortcut = split(flag, '=');
704 lyxerr << "Ignoring unknown flag `" << flag
705 << "' for symbol `0x"
706 << hex << symbol << dec
710 // mathcommand and mathpreamble have been added for 1.6.0.
711 // make them optional so that old files still work.
712 int const lineno = symbolslex.lineNumber();
713 bool breakout = false;
714 docstring mathcommand;
716 if (symbolslex.next(true)) {
717 if (symbolslex.lineNumber() != lineno) {
718 // line in old format without mathcommand and mathpreamble
719 getNextToken = false;
721 mathcommand = symbolslex.getDocString();
722 if (suffixIs(mathcommand, '}'))
723 flags |= CharInfoMathNoTermination;
724 if (symbolslex.next(true)) {
725 if (symbolslex.lineNumber() != lineno) {
726 // line in new format with mathcommand only
727 getNextToken = false;
729 // line in new format with mathcommand and mathpreamble
730 mathpreamble = symbolslex.getString();
739 // backward compatibility
740 if (mathpreamble == "esintoramsmath")
741 mathpreamble = "esint|amsmath";
743 if (!textpreamble.empty())
744 if (textpreamble[0] != '\\')
745 flags |= CharInfoTextFeature;
746 if (!mathpreamble.empty())
747 if (mathpreamble[0] != '\\')
748 flags |= CharInfoMathFeature;
750 CharInfo info = CharInfo(
751 textcommand, mathcommand,
752 textpreamble, mathpreamble,
753 tipashortcut, flags);
754 LYXERR(Debug::INFO, "Read unicode symbol " << symbol << " '"
755 << to_utf8(info.textcommand()) << "' '" << info.textpreamble()
756 << " '" << info.textfeature() << ' ' << info.textnotermination()
757 << ' ' << to_utf8(info.mathcommand()) << "' '" << info.mathpreamble()
758 << "' " << info.mathfeature() << ' ' << info.mathnotermination()
759 << ' ' << info.combining() << ' ' << info.force()
760 << ' ' << info.forceselected());
762 // we assume that at least one command is nonempty when using unicodesymbols
763 if (info.isUnicodeSymbol()) {
764 unicodesymbols[symbol] = info;
771 // Now read the encodings
777 LexerKeyword encodingtags[] = {
778 { "encoding", et_encoding },
782 Lexer lex(encodingtags);
783 lex.setFile(encfile);
784 lex.setContext("Encodings::read");
790 string const name = lex.getString();
792 string const latexname = lex.getString();
794 string const guiname = lex.getString();
796 string const iconvname = lex.getString();
798 string const width = lex.getString();
799 bool fixedwidth = false;
801 if (width == "fixed")
803 else if (width == "variable")
805 else if (width == "variableunsafe") {
810 lex.printError("Unknown width");
813 string const p = lex.getString();
814 Encoding::Package package = Encoding::none;
816 package = Encoding::none;
817 else if (p == "inputenc")
818 package = Encoding::inputenc;
820 package = Encoding::CJK;
821 else if (p == "japanese")
822 package = Encoding::japanese;
824 lex.printError("Unknown package");
826 LYXERR(Debug::INFO, "Reading encoding " << name);
827 encodinglist[name] = Encoding(name, latexname,
828 guiname, iconvname, fixedwidth, unsafe,
831 if (lex.lex() != et_end)
832 lex.printError("Missing end");
836 lex.printError("Misplaced end");
838 case Lexer::LEX_FEOF:
841 lex.printError("Unknown tag");
846 // Move all information from forcednotselected to forcedselected
847 for (CharSetMap::const_iterator it1 = forcednotselected.begin(); it1 != forcednotselected.end(); ++it1) {
848 for (CharSetMap::iterator it2 = forcedselected.begin(); it2 != forcedselected.end(); ++it2) {
849 if (it2->first != it1->first)
850 it2->second.insert(it1->second.begin(), it1->second.end());