1 /**
2  * \file Encoding.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Jean-Marc Lasgouttes
8  * \author Dekel Tsur
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12 
13 #include <config.h>
14 
15 #include "Encoding.h"
16 
17 #include "Lexer.h"
18 
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"
25 
26 #include <boost/cstdint.hpp>
27 
28 #include <iterator>
29 #include <algorithm>
30 #include <sstream>
31 
32 using namespace std;
33 using namespace lyx::support;
34 
35 namespace lyx {
36 
37 int const Encoding::any = -1;
38 
39 Encodings encodings;
40 
41 Encodings::MathCommandSet Encodings::mathcmd;
42 Encodings::TextCommandSet Encodings::textcmd;
43 Encodings::MathSymbolSet  Encodings::mathsym;
44 
45 namespace {
46 
47 typedef map<char_type, CharInfo> CharInfoMap;
48 CharInfoMap unicodesymbols;
49 
50 typedef set<char_type> CharSet;
51 typedef map<string, CharSet> CharSetMap;
52 CharSet forced;
53 CharSetMap forcedselected;
54 
55 typedef set<char_type> MathAlphaSet;
56 MathAlphaSet mathalpha;
57 
58 
59 /// The highest code point in UCS4 encoding (1<<20 + 1<<16)
60 char_type const max_ucs4 = 0x110000;
61 
62 } // namespace
63 
64 
EncodingException(char_type c)65 EncodingException::EncodingException(char_type c)
66 	: failed_char(c), par_id(0), pos(0)
67 {
68 }
69 
70 
what() const71 const char * EncodingException::what() const throw()
72 {
73 	return "Could not find LaTeX command for a character";
74 }
75 
76 
CharInfo(docstring const & textcommand,docstring const & mathcommand,std::string const & textpreamble,std::string const & mathpreamble,std::string const & tipashortcut,unsigned int flags)77 CharInfo::CharInfo(
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)
84 {
85 }
86 
87 
Encoding(string const & n,string const & l,string const & g,string const & i,bool f,bool u,Encoding::Package p)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)
92 {
93 	if (n == "ascii") {
94 		// ASCII can encode 128 code points and nothing else
95 		start_encodable_ = 128;
96 		complete_ = true;
97 	} else if (i == "UTF-8") {
98 		// UTF8 can encode all UCS4 code points
99 		start_encodable_ = max_ucs4;
100 		complete_ = true;
101 	} else {
102 		start_encodable_ = 0;
103 		complete_ = false;
104 	}
105 }
106 
107 
init() const108 void Encoding::init() const
109 {
110 	// Since the the constructor is the only method which sets complete_
111 	// to false the test for complete_ is thread-safe without mutex.
112 	if (complete_)
113 		return;
114 
115 	static Mutex mutex;
116 	Mutex::Locker lock(&mutex);
117 
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.
121 	if (complete_)
122 		return;
123 
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_;
130 
131 	start_encodable = 0;
132 	// temporarily switch off lyxerr, since we will generate iconv errors
133 	lyxerr.disable();
134 	if (fixedwidth_) {
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)
141 				continue;
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);
149 			}
150 		}
151 	} else {
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())
161 					encodable.insert(c);
162 				else if (!it->second.force()) {
163 					if (forced_->empty() || forced_->find(c) == forced_->end())
164 						encodable.insert(c);
165 				}
166 			}
167 		}
168 	}
169 	lyxerr.enable();
170 	CharSet::iterator it = encodable.find(start_encodable);
171 	while (it != encodable.end()) {
172 		encodable.erase(it);
173 		++start_encodable;
174 		it = encodable.find(start_encodable);
175 	}
176 	const_cast<Encoding *>(this)->complete_ = true;
177 }
178 
179 
isForced(char_type c) const180 bool Encoding::isForced(char_type c) const
181 {
182 	if (!forced.empty() && forced.find(c) != forced.end())
183 		return true;
184 	return !forced_->empty() && forced_->find(c) != forced_->end();
185 }
186 
187 
encodable(char_type c) const188 bool Encoding::encodable(char_type c) const
189 {
190 	// assure the used encoding is properly initialized
191 	init();
192 
193 	if (iconvName_ == "UTF-8" && package_ == none)
194 		return true;
195 	if (c < start_encodable_ && !isForced(c))
196 		return true;
197 	if (encodable_.find(c) != encodable_.end())
198 		return true;
199 	return false;
200 }
201 
202 
latexChar(char_type c) const203 pair<docstring, bool> Encoding::latexChar(char_type c) const
204 {
205 	if (encodable(c))
206 		return make_pair(docstring(1, c), false);
207 
208 	// c cannot (or should not) be encoded in this encoding
209 	CharInfoMap::const_iterator const it = unicodesymbols.find(c);
210 	if (it == unicodesymbols.end())
211 		throw EncodingException(c);
212 	// at least one of mathcommand and textcommand is nonempty
213 	if (it->second.textcommand().empty())
214 		return make_pair(
215 			"\\ensuremath{" + it->second.mathcommand() + '}', false);
216 	return make_pair(it->second.textcommand(), !it->second.textnotermination());
217 }
218 
219 
latexString(docstring const & input,bool dryrun) const220 pair<docstring, docstring> Encoding::latexString(docstring const & input, bool dryrun) const
221 {
222 	docstring result;
223 	docstring uncodable;
224 	bool terminate = false;
225 	for (size_t n = 0; n < input.size(); ++n) {
226 		try {
227 			char_type const c = input[n];
228 			pair<docstring, bool> latex_char = latexChar(c);
229 			docstring const latex = latex_char.first;
230 			if (terminate && !prefixIs(latex, '\\')
231 			    && !prefixIs(latex, '{')
232 			    && !prefixIs(latex, '}')) {
233 					// Prevent eating of a following
234 					// space or command corruption by
235 					// following characters
236 					if (latex == " ")
237 						result += "{}";
238 					else
239 						result += " ";
240 				}
241 			result += latex;
242 			terminate = latex_char.second;
243 		} catch (EncodingException & /* e */) {
244 			LYXERR0("Uncodable character in latexString!");
245 			if (dryrun) {
246 				result += "<" + _("LyX Warning: ")
247 					   + _("uncodable character") + " '";
248 				result += docstring(1, input[n]);
249 				result += "'>";
250 			} else
251 				uncodable += input[n];
252 		}
253 	}
254 	return make_pair(result, uncodable);
255 }
256 
257 
symbolsList() const258 vector<char_type> Encoding::symbolsList() const
259 {
260 	// assure the used encoding is properly initialized
261 	init();
262 
263 	// first all those below start_encodable_
264 	vector<char_type> symbols;
265 	for (char_type c = 0; c < start_encodable_; ++c)
266 		symbols.push_back(c);
267 	// add all encodable characters
268 	copy(encodable_.begin(), encodable_.end(), back_inserter(symbols));
269 	// now the ones from the unicodesymbols file that are not already there
270 	for (pair<char_type, CharInfo> const & elem : unicodesymbols) {
271 		if (find(symbols.begin(), symbols.end(), elem.first) == symbols.end())
272 			symbols.push_back(elem.first);
273 	}
274 	// finally, sort the vector
275 	sort(symbols.begin(), symbols.end());
276 	return symbols;
277 }
278 
279 
latexMathChar(char_type c,bool mathmode,Encoding const * encoding,docstring & command,bool & needsTermination)280 bool Encodings::latexMathChar(char_type c, bool mathmode,
281 			Encoding const * encoding, docstring & command,
282 			bool & needsTermination)
283 {
284 	command = empty_docstring();
285 	if (encoding)
286 		if (encoding->encodable(c))
287 			command = docstring(1, c);
288 	needsTermination = false;
289 
290 	CharInfoMap::const_iterator const it = unicodesymbols.find(c);
291 	if (it == unicodesymbols.end()) {
292 		if (!encoding || command.empty())
293 			throw EncodingException(c);
294 		if (mathmode)
295 			addMathSym(c);
296 		return false;
297 	}
298 	// at least one of mathcommand and textcommand is nonempty
299 	bool use_math = (mathmode && !it->second.mathcommand().empty()) ||
300 			(!mathmode && it->second.textcommand().empty());
301 	if (use_math) {
302 		command = it->second.mathcommand();
303 		needsTermination = !it->second.mathnotermination();
304 		addMathCmd(c);
305 	} else {
306 		if (!encoding || command.empty()) {
307 			command = it->second.textcommand();
308 			needsTermination = !it->second.textnotermination();
309 		}
310 		if (mathmode)
311 			addMathSym(c);
312 		else
313 			addTextCmd(c);
314 	}
315 	return use_math;
316 }
317 
318 
fromLaTeXCommand(docstring const & cmd,int cmdtype,bool & combining,bool & needsTermination,set<string> * req)319 char_type Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
320 		bool & combining, bool & needsTermination, set<string> * req)
321 {
322 	CharInfoMap::const_iterator const end = unicodesymbols.end();
323 	CharInfoMap::const_iterator it = unicodesymbols.begin();
324 	for (combining = false; it != end; ++it) {
325 		if (it->second.deprecated())
326 			continue;
327 		docstring const math = it->second.mathcommand();
328 		docstring const text = it->second.textcommand();
329 		if ((cmdtype & MATH_CMD) && math == cmd) {
330 			combining = it->second.combining();
331 			needsTermination = !it->second.mathnotermination();
332 			if (req && it->second.mathfeature() &&
333 			    !it->second.mathpreamble().empty())
334 				req->insert(it->second.mathpreamble());
335 			return it->first;
336 		}
337 		if ((cmdtype & TEXT_CMD) && text == cmd) {
338 			combining = it->second.combining();
339 			needsTermination = !it->second.textnotermination();
340 			if (req && it->second.textfeature() &&
341 			    !it->second.textpreamble().empty())
342 				req->insert(it->second.textpreamble());
343 			return it->first;
344 		}
345 	}
346 	needsTermination = false;
347 	return 0;
348 }
349 
350 
fromLaTeXCommand(docstring const & cmd,int cmdtype,bool & needsTermination,docstring & rem,set<string> * req)351 docstring Encodings::fromLaTeXCommand(docstring const & cmd, int cmdtype,
352 		bool & needsTermination, docstring & rem, set<string> * req)
353 {
354 	needsTermination = false;
355 	rem = empty_docstring();
356 	bool const mathmode = cmdtype & MATH_CMD;
357 	bool const textmode = cmdtype & TEXT_CMD;
358 	docstring symbols;
359 	size_t const cmdend = cmd.size();
360 	size_t prefix = 0;
361 	CharInfoMap::const_iterator const uniend = unicodesymbols.end();
362 	for (size_t i = 0, j = 0; j < cmdend; ++j) {
363 		// Also get the char after a backslash
364 		if (j + 1 < cmdend && cmd[j] == '\\') {
365 			++j;
366 			prefix = 1;
367 			// Detect things like \=*{e} as well
368 			if (j + 3 < cmdend && cmd[j+1] == '*' &&
369 			    cmd[j+2] == '{') {
370 				++j;
371 				prefix = 2;
372 			}
373 		}
374 		// position of the last character before a possible macro
375 		// argument
376 		size_t m = j;
377 		// If a macro argument follows, get it, too
378 		// Do it here only for single character commands. Other
379 		// combining commands need this too, but they are handled in
380 		// the loop below for performance reasons.
381 		if (j + 1 < cmdend && cmd[j + 1] == '{') {
382 			size_t k = j + 1;
383 			int count = 1;
384 			while (k < cmdend && count) {
385 				k = cmd.find_first_of(from_ascii("{}"), k + 1);
386 				// braces may not be balanced
387 				if (k == docstring::npos)
388 					break;
389 				if (cmd[k] == '{')
390 					++count;
391 				else
392 					--count;
393 			}
394 			if (k != docstring::npos)
395 				j = k;
396 		} else if (m + 1 < cmdend && isAlphaASCII(cmd[m])) {
397 			while (m + 2 < cmdend && isAlphaASCII(cmd[m+1]))
398 				m++;
399 		}
400 		// Start with this substring and try augmenting it when it is
401 		// the prefix of some command in the unicodesymbols file
402 		docstring subcmd = cmd.substr(i, j - i + 1);
403 
404 		CharInfoMap::const_iterator it = unicodesymbols.begin();
405 		// First part of subcmd which might be a combining character
406 		docstring combcmd = (m == j) ? docstring() : cmd.substr(i, m - i + 1);
407 		// The combining character of combcmd if it exists
408 		CharInfoMap::const_iterator combining = uniend;
409 		size_t unicmd_size = 0;
410 		char_type c = 0;
411 		for (; it != uniend; ++it) {
412 			if (it->second.deprecated())
413 				continue;
414 			docstring const math = mathmode ? it->second.mathcommand()
415 							: docstring();
416 			docstring const text = textmode ? it->second.textcommand()
417 							: docstring();
418 			if (!combcmd.empty() && it->second.combining() &&
419 			    (math == combcmd || text == combcmd))
420 				combining = it;
421 			size_t cur_size = max(math.size(), text.size());
422 			// The current math or text unicode command cannot
423 			// match, or we already matched a longer one
424 			if (cur_size < subcmd.size() || cur_size <= unicmd_size)
425 				continue;
426 
427 			docstring tmp = subcmd;
428 			size_t k = j;
429 			while (prefixIs(math, tmp) || prefixIs(text, tmp)) {
430 				++k;
431 				if (k >= cmdend || cur_size <= tmp.size())
432 					break;
433 				tmp += cmd[k];
434 			}
435 			// No match
436 			if (k == j)
437 				continue;
438 
439 			// The last added char caused a mismatch, because
440 			// we didn't exhaust the chars in cmd and didn't
441 			// exceed the maximum size of the current unicmd
442 			if (k < cmdend && cur_size > tmp.size())
443 				tmp.resize(tmp.size() - 1);
444 
445 			// If this is an exact match, we found a (longer)
446 			// matching entry in the unicodesymbols file.
447 			if (math != tmp && text != tmp)
448 				continue;
449 			// If we found a combining command, we need to append
450 			// the macro argument if this has not been done above.
451 			if (tmp == combcmd && combining != uniend &&
452 			    k < cmdend && cmd[k] == '{') {
453 				size_t l = k;
454 				int count = 1;
455 				while (l < cmdend && count) {
456 					l = cmd.find_first_of(from_ascii("{}"), l + 1);
457 					// braces may not be balanced
458 					if (l == docstring::npos)
459 						break;
460 					if (cmd[l] == '{')
461 						++count;
462 					else
463 						--count;
464 				}
465 				if (l != docstring::npos) {
466 					j = l;
467 					subcmd = cmd.substr(i, j - i + 1);
468 				}
469 			}
470 			// If the entry doesn't start with '\', we take note
471 			// of the match and continue (this is not a ultimate
472 			// acceptance, as some other entry may match a longer
473 			// portion of the cmd string). However, if the entry
474 			// does start with '\', we accept the match only if
475 			// this is a valid macro, i.e., either it is a single
476 			// (nonletter) char macro, or nothing else follows,
477 			// or what follows is a nonletter char, or the last
478 			// character is a }.
479 			else if (tmp[0] != '\\'
480 				   || (tmp.size() == prefix + 1 &&
481 				       !isAlphaASCII(tmp[1]) &&
482 				       (prefix == 1 || !isAlphaASCII(tmp[2])))
483 				   || k == cmdend
484 				   || !isAlphaASCII(cmd[k])
485 				   || tmp[tmp.size() - 1] == '}'
486 				 ) {
487 				c = it->first;
488 				j = k - 1;
489 				i = j + 1;
490 				unicmd_size = cur_size;
491 				if (math == tmp)
492 					needsTermination = !it->second.mathnotermination();
493 				else
494 					needsTermination = !it->second.textnotermination();
495 				if (req) {
496 					if (math == tmp && it->second.mathfeature() &&
497 					    !it->second.mathpreamble().empty())
498 						req->insert(it->second.mathpreamble());
499 					if (text == tmp && it->second.textfeature() &&
500 					    !it->second.textpreamble().empty())
501 						req->insert(it->second.textpreamble());
502 				}
503 			}
504 		}
505 		if (unicmd_size)
506 			symbols += c;
507 		else if (combining != uniend &&
508 		         prefixIs(subcmd, combcmd + '{')) {
509 			// We know that subcmd starts with combcmd and
510 			// contains an argument in braces.
511 			docstring const arg = subcmd.substr(
512 				combcmd.length() + 1,
513 				subcmd.length() - combcmd.length() - 2);
514 			// If arg is a single character we can construct a
515 			// combining sequence.
516 			char_type a;
517 			bool argcomb = false;
518 			if (arg.size() == 1 && isAlnumASCII(arg[0]))
519 				a = arg[0];
520 			else {
521 				// Use the version of fromLaTeXCommand() that
522 				// parses only one command, since we cannot
523 				// use more than one character.
524 				bool dummy = false;
525 				set<string> r;
526 				a = fromLaTeXCommand(arg, cmdtype, argcomb,
527 				                     dummy, &r);
528 				if (a && req && !argcomb)
529 					req->insert(r.begin(), r.end());
530 			}
531 			if (a && !argcomb) {
532 				// In unicode the combining character comes
533 				// after its base
534 				symbols += a;
535 				symbols += combining->first;
536 				i = j + 1;
537 				unicmd_size = 2;
538 			}
539 		}
540 		if (j + 1 == cmdend && !unicmd_size) {
541 			// No luck. Return what remains
542 			rem = cmd.substr(i);
543 			if (needsTermination && !rem.empty()) {
544 				if (rem.substr(0, 2) == "{}") {
545 					rem = rem.substr(2);
546 					needsTermination = false;
547 				} else if (rem[0] == ' ') {
548 					needsTermination = false;
549 					// LaTeX would swallow all spaces
550 					rem = ltrim(rem);
551 				}
552 			}
553 		}
554 	}
555 	return symbols;
556 }
557 
558 
unicodeCharInfo(char_type c)559 CharInfo const & Encodings::unicodeCharInfo(char_type c)
560 {
561 	static CharInfo empty;
562 	CharInfoMap::const_iterator const it = unicodesymbols.find(c);
563 	return it != unicodesymbols.end() ? it->second : empty;
564 }
565 
566 
isCombiningChar(char_type c)567 bool Encodings::isCombiningChar(char_type c)
568 {
569 	CharInfoMap::const_iterator const it = unicodesymbols.find(c);
570 	if (it != unicodesymbols.end())
571 		return it->second.combining();
572 	return false;
573 }
574 
575 
TIPAShortcut(char_type c)576 string const Encodings::TIPAShortcut(char_type c)
577 {
578 	CharInfoMap::const_iterator const it = unicodesymbols.find(c);
579 	if (it != unicodesymbols.end())
580 		return it->second.tipashortcut();
581 	return string();
582 }
583 
584 
isKnownScriptChar(char_type const c,string & preamble)585 bool Encodings::isKnownScriptChar(char_type const c, string & preamble)
586 {
587 	CharInfoMap::const_iterator const it = unicodesymbols.find(c);
588 
589 	if (it == unicodesymbols.end())
590 		return false;
591 
592 	if (it->second.textpreamble() != "textgreek" && it->second.textpreamble() != "textcyr")
593 		return false;
594 
595 	if (preamble.empty()) {
596 		preamble = it->second.textpreamble();
597 		return true;
598 	}
599 	return it->second.textpreamble() == preamble;
600 }
601 
602 
isMathAlpha(char_type c)603 bool Encodings::isMathAlpha(char_type c)
604 {
605 	return mathalpha.count(c);
606 }
607 
608 
isUnicodeTextOnly(char_type c)609 bool Encodings::isUnicodeTextOnly(char_type c)
610 {
611 	if (isASCII(c) || isMathAlpha(c))
612 		return false;
613 
614 	CharInfoMap::const_iterator const it = unicodesymbols.find(c);
615 	return it == unicodesymbols.end() || it->second.mathcommand().empty();
616 }
617 
618 
619 Encoding const *
fromLyXName(string const & name,bool allowUnsafe) const620 Encodings::fromLyXName(string const & name, bool allowUnsafe) const
621 {
622 	EncodingList::const_iterator const it = encodinglist.find(name);
623 	if (it == encodinglist.end())
624 		return 0;
625 	if (!allowUnsafe && it->second.unsafe())
626 		return 0;
627 	return &it->second;
628 }
629 
630 
631 Encoding const *
fromLaTeXName(string const & n,int const & p,bool allowUnsafe) const632 Encodings::fromLaTeXName(string const & n, int const & p, bool allowUnsafe) const
633 {
634 	string name = n;
635 	// FIXME: if we have to test for too many of these synonyms,
636 	// we should instead extend the format of lib/encodings
637 	if (n == "ansinew")
638 		name = "cp1252";
639 
640 	// We don't use find_if because it makes copies of the pairs in
641 	// the map.
642 	// This linear search is OK since we don't have many encodings.
643 	// Users could even optimize it by putting the encodings they use
644 	// most at the top of lib/encodings.
645 	EncodingList::const_iterator const end = encodinglist.end();
646 	for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
647 		if ((it->second.latexName() == name) && (it->second.package() & p)
648 				&& (!it->second.unsafe() || allowUnsafe))
649 			return &it->second;
650 	return 0;
651 }
652 
653 
654 Encoding const *
fromIconvName(string const & n,int const & p,bool allowUnsafe) const655 Encodings::fromIconvName(string const & n, int const & p, bool allowUnsafe) const
656 {
657 	EncodingList::const_iterator const end = encodinglist.end();
658 	for (EncodingList::const_iterator it = encodinglist.begin(); it != end; ++it)
659 		if ((it->second.iconvName() == n) && (it->second.package() & p)
660 				&& (!it->second.unsafe() || allowUnsafe))
661 			return &it->second;
662 	return 0;
663 }
664 
665 
Encodings()666 Encodings::Encodings()
667 {}
668 
669 
read(FileName const & encfile,FileName const & symbolsfile)670 void Encodings::read(FileName const & encfile, FileName const & symbolsfile)
671 {
672 	// We must read the symbolsfile first, because the Encoding
673 	// constructor depends on it.
674 	CharSetMap forcednotselected;
675 	Lexer symbolslex;
676 	symbolslex.setFile(symbolsfile);
677 	bool getNextToken = true;
678 	while (symbolslex.isOK()) {
679 		char_type symbol;
680 
681 		if (getNextToken) {
682 			if (!symbolslex.next(true))
683 				break;
684 		} else
685 			getNextToken = true;
686 
687 		istringstream is(symbolslex.getString());
688 		// reading symbol directly does not work if
689 		// char_type == wchar_t.
690 		boost::uint32_t tmp;
691 		if(!(is >> hex >> tmp))
692 			break;
693 		symbol = tmp;
694 
695 		if (!symbolslex.next(true))
696 			break;
697 		docstring textcommand = symbolslex.getDocString();
698 		if (!symbolslex.next(true))
699 			break;
700 		string textpreamble = symbolslex.getString();
701 		if (!symbolslex.next(true))
702 			break;
703 		string sflags = symbolslex.getString();
704 
705 		string tipashortcut;
706 		int flags = 0;
707 
708 		if (suffixIs(textcommand, '}'))
709 			flags |= CharInfoTextNoTermination;
710 		while (!sflags.empty()) {
711 			string flag;
712 			sflags = split(sflags, flag, ',');
713 			if (flag == "combining") {
714 				flags |= CharInfoCombining;
715 			} else if (flag == "force") {
716 				flags |= CharInfoForce;
717 				forced.insert(symbol);
718 			} else if (prefixIs(flag, "force=")) {
719 				vector<string> encodings =
720 					getVectorFromString(flag.substr(6), ";");
721 				for (size_t i = 0; i < encodings.size(); ++i)
722 					forcedselected[encodings[i]].insert(symbol);
723 				flags |= CharInfoForceSelected;
724 			} else if (prefixIs(flag, "force!=")) {
725 				vector<string> encodings =
726 					getVectorFromString(flag.substr(7), ";");
727 				for (size_t i = 0; i < encodings.size(); ++i)
728 					forcednotselected[encodings[i]].insert(symbol);
729 				flags |= CharInfoForceSelected;
730 			} else if (flag == "mathalpha") {
731 				mathalpha.insert(symbol);
732 			} else if (flag == "notermination=text") {
733 				flags |= CharInfoTextNoTermination;
734 			} else if (flag == "notermination=math") {
735 				flags |= CharInfoMathNoTermination;
736 			} else if (flag == "notermination=both") {
737 				flags |= CharInfoTextNoTermination;
738 				flags |= CharInfoMathNoTermination;
739 			} else if (flag == "notermination=none") {
740 				flags &= ~CharInfoTextNoTermination;
741 				flags &= ~CharInfoMathNoTermination;
742 			} else if (contains(flag, "tipashortcut=")) {
743 				tipashortcut = split(flag, '=');
744 			} else if (flag == "deprecated") {
745 				flags |= CharInfoDeprecated;
746 			} else {
747 				lyxerr << "Ignoring unknown flag `" << flag
748 				       << "' for symbol `0x"
749 				       << hex << symbol << dec
750 				       << "'." << endl;
751 			}
752 		}
753 		// mathcommand and mathpreamble have been added for 1.6.0.
754 		// make them optional so that old files still work.
755 		int const lineno = symbolslex.lineNumber();
756 		bool breakout = false;
757 		docstring mathcommand;
758 		string mathpreamble;
759 		if (symbolslex.next(true)) {
760 			if (symbolslex.lineNumber() != lineno) {
761 				// line in old format without mathcommand and mathpreamble
762 				getNextToken = false;
763 			} else {
764 				mathcommand = symbolslex.getDocString();
765 				if (suffixIs(mathcommand, '}'))
766 					flags |= CharInfoMathNoTermination;
767 				if (symbolslex.next(true)) {
768 					if (symbolslex.lineNumber() != lineno) {
769 						// line in new format with mathcommand only
770 						getNextToken = false;
771 					} else {
772 						// line in new format with mathcommand and mathpreamble
773 						mathpreamble = symbolslex.getString();
774 					}
775 				} else
776 					breakout = true;
777 			}
778 		} else {
779 			breakout = true;
780 		}
781 
782 		// backward compatibility
783 		if (mathpreamble == "esintoramsmath")
784 			mathpreamble = "esint|amsmath";
785 
786 		if (!textpreamble.empty())
787 			if (textpreamble[0] != '\\')
788 				flags |= CharInfoTextFeature;
789 		if (!mathpreamble.empty())
790 			if (mathpreamble[0] != '\\')
791 				flags |= CharInfoMathFeature;
792 
793 		CharInfo info = CharInfo(
794 			textcommand, mathcommand,
795 			textpreamble, mathpreamble,
796 			tipashortcut, flags);
797 		LYXERR(Debug::INFO, "Read unicode symbol " << symbol << " '"
798 			   << to_utf8(info.textcommand()) << "' '" << info.textpreamble()
799 			   << " '" << info.textfeature() << ' ' << info.textnotermination()
800 			   << ' ' << to_utf8(info.mathcommand()) << "' '" << info.mathpreamble()
801 			   << "' " << info.mathfeature() << ' ' << info.mathnotermination()
802 			   << ' ' << info.combining() << ' ' << info.force()
803 			   << ' ' << info.forceselected());
804 
805 		// we assume that at least one command is nonempty when using unicodesymbols
806 		if (info.isUnicodeSymbol()) {
807 			unicodesymbols[symbol] = info;
808 		}
809 
810 		if (breakout)
811 			break;
812 	}
813 
814 	// Now read the encodings
815 	enum {
816 		et_encoding = 1,
817 		et_end
818 	};
819 
820 	LexerKeyword encodingtags[] = {
821 		{ "encoding", et_encoding },
822 		{ "end", et_end }
823 	};
824 
825 	Lexer lex(encodingtags);
826 	lex.setFile(encfile);
827 	lex.setContext("Encodings::read");
828 	while (lex.isOK()) {
829 		switch (lex.lex()) {
830 		case et_encoding:
831 		{
832 			lex.next();
833 			string const name = lex.getString();
834 			lex.next();
835 			string const latexname = lex.getString();
836 			lex.next();
837 			string const guiname = lex.getString();
838 			lex.next();
839 			string const iconvname = lex.getString();
840 			lex.next();
841 			string const width = lex.getString();
842 			bool fixedwidth = false;
843 			bool unsafe = false;
844 			if (width == "fixed")
845 				fixedwidth = true;
846 			else if (width == "variable")
847 				fixedwidth = false;
848 			else if (width == "variableunsafe") {
849 				fixedwidth = false;
850 				unsafe = true;
851 			}
852 			else
853 				lex.printError("Unknown width");
854 
855 			lex.next();
856 			string const p = lex.getString();
857 			Encoding::Package package = Encoding::none;
858 			if (p == "none")
859 				package = Encoding::none;
860 			else if (p == "inputenc")
861 				package = Encoding::inputenc;
862 			else if (p == "CJK")
863 				package = Encoding::CJK;
864 			else if (p == "japanese")
865 				package = Encoding::japanese;
866 			else
867 				lex.printError("Unknown package");
868 
869 			LYXERR(Debug::INFO, "Reading encoding " << name);
870 			encodinglist[name] = Encoding(name, latexname,
871 				guiname, iconvname, fixedwidth, unsafe,
872 				package);
873 
874 			if (lex.lex() != et_end)
875 				lex.printError("Missing end");
876 			break;
877 		}
878 		case et_end:
879 			lex.printError("Misplaced end");
880 			break;
881 		case Lexer::LEX_FEOF:
882 			break;
883 		default:
884 			lex.printError("Unknown tag");
885 			break;
886 		}
887 	}
888 
889 	// Move all information from forcednotselected to forcedselected
890 	for (CharSetMap::const_iterator it1 = forcednotselected.begin(); it1 != forcednotselected.end(); ++it1) {
891 		for (CharSetMap::iterator it2 = forcedselected.begin(); it2 != forcedselected.end(); ++it2) {
892 			if (it2->first != it1->first)
893 				it2->second.insert(it1->second.begin(), it1->second.end());
894 		}
895 	}
896 
897 }
898 
899 
900 } // namespace lyx
901