3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
16 #include "support/lstrings.h"
17 #include "support/textutils.h"
22 using namespace lyx::support;
29 * Translate a line ending to '\n'.
30 * \p c must have catcode catNewline, and it must be the last character read
33 char_type getNewline(iparserdocstream & is, char_type c)
35 // we have to handle 3 different line endings:
42 if (is.get(wc) && wc != '\n') {
58 ostream & operator<<(ostream & os, Token const & t)
60 if (t.cat() == catComment)
61 os << '%' << t.cs() << '\n';
62 else if (t.cat() == catSpace)
64 else if (t.cat() == catEscape)
65 os << '\\' << t.cs() << ' ';
66 else if (t.cat() == catLetter)
68 else if (t.cat() == catNewline)
69 os << "[" << t.cs().size() << "\\n," << t.cat() << "]\n";
71 os << '[' << t.cs() << ',' << t.cat() << ']';
76 string Token::asInput() const
78 if (cat_ == catComment)
79 return '%' + cs_ + '\n';
80 if (cat_ == catEscape)
86 bool Token::isAlnumASCII() const
88 return cat_ == catLetter ||
89 (cat_ == catOther && cs_.length() == 1 && isDigitASCII(cs_[0]));
94 void debugToken(std::ostream & os, Token const & t, unsigned int flags)
97 os << "t: " << t << " flags: " << flags;
98 if (flags & FLAG_BRACE_LAST) { os << sep << "BRACE_LAST"; sep = '|'; }
99 if (flags & FLAG_RIGHT ) { os << sep << "RIGHT" ; sep = '|'; }
100 if (flags & FLAG_END ) { os << sep << "END" ; sep = '|'; }
101 if (flags & FLAG_BRACK_LAST) { os << sep << "BRACK_LAST"; sep = '|'; }
102 if (flags & FLAG_TEXTMODE ) { os << sep << "TEXTMODE" ; sep = '|'; }
103 if (flags & FLAG_ITEM ) { os << sep << "ITEM" ; sep = '|'; }
104 if (flags & FLAG_LEAVE ) { os << sep << "LEAVE" ; sep = '|'; }
105 if (flags & FLAG_SIMPLE ) { os << sep << "SIMPLE" ; sep = '|'; }
106 if (flags & FLAG_EQUATION ) { os << sep << "EQUATION" ; sep = '|'; }
107 if (flags & FLAG_SIMPLE2 ) { os << sep << "SIMPLE2" ; sep = '|'; }
108 if (flags & FLAG_OPTION ) { os << sep << "OPTION" ; sep = '|'; }
109 if (flags & FLAG_BRACED ) { os << sep << "BRACED" ; sep = '|'; }
110 if (flags & FLAG_CELL ) { os << sep << "CELL" ; sep = '|'; }
111 if (flags & FLAG_TABBING ) { os << sep << "TABBING" ; sep = '|'; }
121 void iparserdocstream::setEncoding(std::string const & e)
123 is_ << lyx::setEncoding(e);
127 void iparserdocstream::putback(char_type c)
133 void iparserdocstream::putback(docstring const & s)
139 iparserdocstream & iparserdocstream::get(char_type &c)
144 //cerr << "unparsed: " << to_utf8(s_) <<endl;
157 Parser::Parser(idocstream & is, std::string const & fixedenc)
158 : lineno_(0), pos_(0), iss_(nullptr), is_(is),
159 encoding_iconv_(fixedenc.empty() ? "UTF-8" : fixedenc),
160 theCatcodesType_(NORMAL_CATCODES), curr_cat_(UNDECIDED_CATCODES),
161 fixed_enc_(!fixedenc.empty())
164 is_.setEncoding(fixedenc);
169 Parser::Parser(string const & s)
170 : lineno_(0), pos_(0),
171 iss_(new idocstringstream(from_utf8(s))), is_(*iss_),
172 encoding_iconv_("UTF-8"),
173 theCatcodesType_(NORMAL_CATCODES), curr_cat_(UNDECIDED_CATCODES),
174 // An idocstringstream can not change the encoding
187 void Parser::deparse()
190 for(size_type i = pos_ ; i < tokens_.size() ; ++i) {
191 s += tokens_[i].asInput();
193 is_.putback(from_utf8(s));
194 tokens_.erase(tokens_.begin() + pos_, tokens_.end());
195 // make sure that next token is read
200 bool Parser::setEncoding(std::string const & e, int p)
202 // We may (and need to) use unsafe encodings here: Since the text is
203 // converted to unicode while reading from is_, we never see text in
204 // the original encoding of the parser, but operate on utf8 strings
205 // instead. Therefore, we cannot misparse high bytes as {, } or \\.
206 Encoding const * const enc = encodings.fromLaTeXName(e, p, true);
208 cerr << "Unknown encoding " << e << ". Ignoring." << std::endl;
211 return setEncoding(enc->iconvName());
215 void Parser::catInit()
217 if (curr_cat_ == theCatcodesType_)
219 curr_cat_ = theCatcodesType_;
221 fill(theCatcode_, theCatcode_ + 256, catOther);
222 fill(theCatcode_ + 'a', theCatcode_ + 'z' + 1, catLetter);
223 fill(theCatcode_ + 'A', theCatcode_ + 'Z' + 1, catLetter);
225 theCatcode_[int('@')] = catLetter;
227 if (theCatcodesType_ == NORMAL_CATCODES) {
228 theCatcode_[int('\\')] = catEscape;
229 theCatcode_[int('{')] = catBegin;
230 theCatcode_[int('}')] = catEnd;
231 theCatcode_[int('$')] = catMath;
232 theCatcode_[int('&')] = catAlign;
233 theCatcode_[int('\n')] = catNewline;
234 theCatcode_[int('#')] = catParameter;
235 theCatcode_[int('^')] = catSuper;
236 theCatcode_[int('_')] = catSub;
237 theCatcode_[0x7f] = catIgnore;
238 theCatcode_[int(' ')] = catSpace;
239 theCatcode_[int('\t')] = catSpace;
240 theCatcode_[int('\r')] = catNewline;
241 theCatcode_[int('~')] = catActive;
242 theCatcode_[int('%')] = catComment;
246 CatCode Parser::catcode(char_type c) const
249 return theCatcode_[(unsigned char)c];
254 void Parser::setCatcode(char c, CatCode cat)
256 theCatcode_[(unsigned char)c] = cat;
261 void Parser::setCatcodes(cat_type t)
263 theCatcodesType_ = t;
268 bool Parser::setEncoding(std::string const & e)
270 //cerr << "setting encoding to " << e << std::endl;
272 // If the encoding is fixed, we must not change the stream encoding
273 // (because the whole input uses that encoding, e.g. if it comes from
274 // the clipboard). We still need to track the original encoding in
275 // encoding_iconv_, so that the generated output is correct.
282 void Parser::push_back(Token const & t)
284 tokens_.push_back(t);
288 // We return a copy here because the tokens_ vector may get reallocated
289 Token const Parser::prev_token() const
291 static const Token dummy;
292 return pos_ > 1 ? tokens_[pos_ - 2] : dummy;
296 // We return a copy here because the tokens_ vector may get reallocated
297 Token const Parser::curr_token() const
299 static const Token dummy;
300 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
304 // We return a copy here because the tokens_ vector may get reallocated
305 Token const Parser::next_token()
307 static const Token dummy;
310 if (pos_ >= tokens_.size())
312 return pos_ < tokens_.size() ? tokens_[pos_] : dummy;
316 // We return a copy here because the tokens_ vector may get reallocated
317 Token const Parser::next_next_token()
319 static const Token dummy;
322 // If tokenize_one() has not been called after the last get_token() we
323 // need to tokenize two more tokens.
324 if (pos_ >= tokens_.size())
326 if (pos_ + 1 >= tokens_.size())
328 return pos_ + 1 < tokens_.size() ? tokens_[pos_ + 1] : dummy;
332 // We return a copy here because the tokens_ vector may get reallocated
333 Token const Parser::get_token()
335 static const Token dummy;
338 if (pos_ >= tokens_.size()) {
340 if (pos_ >= tokens_.size())
343 // cerr << "looking at token " << tokens_[pos_]
344 // << " pos: " << pos_ << '\n';
345 return tokens_[pos_++];
349 bool Parser::isParagraph()
351 // A new paragraph in TeX is started
352 // - either by a newline, following any amount of whitespace
353 // characters (including zero), and another newline
354 // - or the token \par
355 if (curr_token().cat() == catNewline &&
356 (curr_token().cs().size() > 1 ||
357 (next_token().cat() == catSpace &&
358 next_next_token().cat() == catNewline)))
360 if (curr_token().cat() == catEscape && curr_token().cs() == "par")
366 bool Parser::skip_spaces(bool skip_comments)
368 // We just silently return if we have no more tokens.
369 // skip_spaces() should be callable at any time,
370 // the caller must check p::good() anyway.
371 bool skipped = false;
378 if (curr_token().cat() == catSpace ||
379 curr_token().cat() == catNewline) {
383 if ((curr_token().cat() == catComment && curr_token().cs().empty()))
385 if (skip_comments && curr_token().cat() == catComment) {
386 // If positions_ is not empty we are doing some kind
388 if (!positions_.empty())
389 cerr << " Ignoring comment: "
390 << curr_token().asInput();
400 void Parser::unskip_spaces(bool skip_comments)
403 if ( curr_token().cat() == catSpace ||
404 (curr_token().cat() == catNewline && curr_token().cs().size() == 1))
406 else if (skip_comments && curr_token().cat() == catComment) {
407 // TODO: Get rid of this
408 // If positions_ is not empty we are doing some kind
410 if (!positions_.empty())
411 cerr << "Unignoring comment: "
412 << curr_token().asInput();
421 void Parser::putback()
427 void Parser::pushPosition()
429 positions_.push_back(pos_);
433 void Parser::popPosition()
435 pos_ = positions_.back();
436 positions_.pop_back();
441 void Parser::dropPosition()
443 positions_.pop_back();
447 bool Parser::good() const
449 if (pos_ < tokens_.size())
453 return is_.peek() != idocstream::traits_type::eof();
457 bool Parser::hasOpt(string const & l)
459 // An optional argument can occur in any of the following forms:
467 // remember current position
468 unsigned int oldpos = pos_;
469 // skip spaces and comments
476 if (curr_token().cat() == catSpace ||
477 curr_token().cat() == catNewline ||
478 curr_token().cat() == catComment)
483 bool const retval = (next_token().asInput() == l);
489 Parser::Arg Parser::getFullArg(char left, char right, bool allow_escaping)
493 // This is needed if a partial file ends with a command without arguments,
496 return make_pair(false, string());
500 Token t = get_token();
502 if (t.cat() == catComment || t.cat() == catEscape ||
503 t.character() != left) {
505 return make_pair(false, string());
510 if (left != '{' && t.cat() == catBegin) {
514 if (left != '{' && t.cat() == catEnd) {
519 if (t.cat() == catComment) {
521 cerr << "Ignoring comment: " << t.asInput();
524 if (allow_escaping) {
525 if (t.cat() != catEscape && t.character() == right
529 if (t.character() == right) {
530 if (t.cat() == catEscape)
532 if (group_level == 0)
536 result += t.asInput();
539 return make_pair(true, result);
543 string Parser::getArg(char left, char right, bool allow_escaping)
545 return getFullArg(left, right, allow_escaping).second;
549 string Parser::getFullOpt(bool keepws, char left, char right)
551 Arg arg = getFullArg(left, right);
553 return left + arg.second + right;
560 string Parser::getOpt(bool keepws)
562 string const res = getArg('[', ']');
568 return '[' + res + ']';
572 string Parser::getFullParentheseArg()
574 Arg arg = getFullArg('(', ')');
576 return '(' + arg.second + ')';
581 bool Parser::hasListPreamble(string const & itemcmd)
583 // remember current position
584 unsigned int oldpos = pos_;
585 // jump over arguments
590 // and swallow spaces and comments
592 // we have a list preamble if the next thing
593 // that follows is not the \item command
594 bool res = next_token().cs() != itemcmd;
595 // back to orig position
601 string const Parser::ertEnvironment(string const & name)
607 for (Token t = get_token(); good(); t = get_token()) {
608 if (t.cat() == catBegin) {
610 os << '{' << verbatim_item() << '}';
611 } else if (t.asInput() == "\\begin") {
612 string const env = getArg('{', '}');
613 os << "\\begin{" << env << '}'
614 << ertEnvironment(env)
615 << "\\end{" << env << '}';
616 } else if (t.asInput() == "\\end") {
617 string const end = getArg('{', '}');
619 cerr << "\\end{" << end
620 << "} does not match \\begin{" << name
626 cerr << "unexpected end of input" << endl;
631 string const Parser::plainEnvironment(string const & name)
637 for (Token t = get_token(); good(); t = get_token()) {
638 if (t.asInput() == "\\end") {
639 string const end = getArg('{', '}');
643 os << "\\end{" << end << '}';
647 cerr << "unexpected end of input" << endl;
652 string const Parser::plainCommand(char left, char right, string const & name)
656 // check if first token is really the start character
657 Token tok = get_token();
658 if (tok.character() != left) {
659 cerr << "first character does not match start character of command \\" << name << endl;
663 for (Token t = get_token(); good(); t = get_token()) {
664 if (t.character() == right) {
669 cerr << "unexpected end of input" << endl;
674 string const Parser::getCommandLatexParam()
681 if (pos_ + offset >= tokens_.size())
683 if (pos_ + offset >= tokens_.size())
685 Token t = tokens_[pos_ + offset];
686 if (t.cat() == catBegin)
695 Parser::Arg Parser::verbatimStuff(string const & end_string, bool const allow_linebreak)
698 return Arg(false, string());
702 size_t match_index = 0;
703 setCatcodes(VERBATIM_CATCODES);
704 for (Token t = get_token(); good(); t = get_token()) {
705 // FIXME t.asInput() might be longer than we need ?
706 if (t.asInput() == end_string.substr(match_index,
707 t.asInput().length())) {
708 match_index += t.asInput().length();
709 if (match_index >= end_string.length())
712 if (!allow_linebreak && t.asInput() == "\n") {
713 cerr << "unexpected end of input" << endl;
715 setCatcodes(NORMAL_CATCODES);
716 return Arg(false, string());
719 oss << end_string.substr(0, match_index)
728 cerr << "unexpected end of input" << endl;
730 setCatcodes(NORMAL_CATCODES);
731 return Arg(false, string());
733 setCatcodes(NORMAL_CATCODES);
735 return Arg(true, oss.str());
739 string const Parser::verbatimEnvironment(string const & name)
741 //FIXME: do something if endstring is not found
742 string s = verbatimStuff("\\end{" + name + "}").second;
743 // ignore one newline at beginning or end of string
744 if (prefixIs(s, "\n"))
746 if (suffixIs(s, "\n"))
747 s.erase(s.length() - 1,1);
752 string Parser::verbatimOption()
755 if (next_token().character() == '[') {
756 Token t = get_token();
757 for (t = get_token(); t.character() != ']' && good(); t = get_token()) {
758 if (t.cat() == catBegin) {
760 res += '{' + verbatim_item() + '}';
769 string Parser::verbatim_item()
774 if (next_token().cat() == catBegin) {
775 Token t = get_token(); // skip brace
777 for (t = get_token(); t.cat() != catEnd && good(); t = get_token()) {
778 if (t.cat() == catBegin) {
780 res += '{' + verbatim_item() + '}';
787 return get_token().asInput();
791 void Parser::tokenize_one()
798 switch (catcode(c)) {
801 while (is_.get(c) && catcode(c) == catSpace)
803 if (catcode(c) != catSpace)
805 push_back(Token(s, catSpace));
811 docstring s(1, getNewline(is_, c));
812 while (is_.get(c) && catcode(c) == catNewline) {
814 s += getNewline(is_, c);
816 if (catcode(c) != catNewline)
818 push_back(Token(s, catNewline));
823 // We don't treat "%\n" combinations here specially because
824 // we want to preserve them in the preamble
826 while (is_.get(c) && catcode(c) != catNewline)
828 // handle possible DOS line ending
829 if (catcode(c) == catNewline)
830 c = getNewline(is_, c);
831 // Note: The '%' at the beginning and the '\n' at the end
832 // of the comment are not stored.
834 push_back(Token(s, catComment));
841 error("unexpected end of input");
844 if (catcode(c) == catLetter) {
846 while (is_.get(c) && catcode(c) == catLetter)
848 if (catcode(c) != catLetter)
851 push_back(Token(s, catEscape));
857 cerr << "ignoring a char: " << static_cast<uint32_t>(c) << "\n";
862 push_back(Token(docstring(1, c), catcode(c)));
864 //cerr << tokens_.back();
868 void Parser::dump() const
870 cerr << "\nTokens: ";
871 for (unsigned i = 0; i < tokens_.size(); ++i) {
876 cerr << " pos: " << pos_ << "\n";
880 void Parser::error(string const & msg) const
882 cerr << "Line ~" << lineno_ << ": parse error: " << msg << endl;