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.
18 #include "support/convert.h"
19 #include "support/lstrings.h"
20 #include "support/textutils.h"
26 using namespace lyx::support;
33 * Translate a line ending to '\n'.
34 * \p c must have catcode catNewline, and it must be the last character read
37 char_type getNewline(iparserdocstream & is, char_type c)
39 // we have to handle 3 different line endings:
46 if (is.get(wc) && wc != '\n') {
62 ostream & operator<<(ostream & os, Token const & t)
64 if (t.cat() == catComment)
65 os << '%' << t.cs() << '\n';
66 else if (t.cat() == catSpace)
68 else if (t.cat() == catEscape)
69 os << '\\' << t.cs() << ' ';
70 else if (t.cat() == catLetter)
72 else if (t.cat() == catNewline)
73 os << "[" << t.cs().size() << "\\n," << t.cat() << "]\n";
75 os << '[' << t.cs() << ',' << t.cat() << ']';
80 string Token::asInput() const
82 if (cat_ == catComment)
83 return '%' + cs_ + '\n';
84 if (cat_ == catEscape)
90 bool Token::isAlnumASCII() const
92 return cat_ == catLetter ||
93 (cat_ == catOther && cs_.length() == 1 && isDigitASCII(cs_[0]));
98 void debugToken(std::ostream & os, Token const & t, unsigned int flags)
101 os << "t: " << t << " flags: " << flags;
102 if (flags & FLAG_BRACE_LAST) { os << sep << "BRACE_LAST"; sep = '|'; }
103 if (flags & FLAG_RIGHT ) { os << sep << "RIGHT" ; sep = '|'; }
104 if (flags & FLAG_END ) { os << sep << "END" ; sep = '|'; }
105 if (flags & FLAG_BRACK_LAST) { os << sep << "BRACK_LAST"; sep = '|'; }
106 if (flags & FLAG_TEXTMODE ) { os << sep << "TEXTMODE" ; sep = '|'; }
107 if (flags & FLAG_ITEM ) { os << sep << "ITEM" ; sep = '|'; }
108 if (flags & FLAG_LEAVE ) { os << sep << "LEAVE" ; sep = '|'; }
109 if (flags & FLAG_SIMPLE ) { os << sep << "SIMPLE" ; sep = '|'; }
110 if (flags & FLAG_EQUATION ) { os << sep << "EQUATION" ; sep = '|'; }
111 if (flags & FLAG_SIMPLE2 ) { os << sep << "SIMPLE2" ; sep = '|'; }
112 if (flags & FLAG_OPTION ) { os << sep << "OPTION" ; sep = '|'; }
113 if (flags & FLAG_BRACED ) { os << sep << "BRACED" ; sep = '|'; }
114 if (flags & FLAG_CELL ) { os << sep << "CELL" ; sep = '|'; }
115 if (flags & FLAG_TABBING ) { os << sep << "TABBING" ; sep = '|'; }
125 void iparserdocstream::setEncoding(std::string const & e)
127 is_ << lyx::setEncoding(e);
131 void iparserdocstream::putback(char_type c)
137 void iparserdocstream::putback(docstring const & s)
143 iparserdocstream & iparserdocstream::get(char_type &c)
148 //warning_message("unparsed: " + to_utf8(s_));
161 Parser::Parser(idocstream & is, std::string const & fixedenc)
162 : lineno_(0), pos_(0), iss_(nullptr), is_(is),
163 encoding_iconv_(fixedenc.empty() ? "UTF-8" : fixedenc),
164 theCatcodesType_(NORMAL_CATCODES), curr_cat_(UNDECIDED_CATCODES),
165 fixed_enc_(!fixedenc.empty())
168 is_.setEncoding(fixedenc);
173 Parser::Parser(string const & s)
174 : lineno_(0), pos_(0),
175 iss_(new idocstringstream(from_utf8(s))), is_(*iss_),
176 encoding_iconv_("UTF-8"),
177 theCatcodesType_(NORMAL_CATCODES), curr_cat_(UNDECIDED_CATCODES),
178 // An idocstringstream can not change the encoding
191 void Parser::deparse()
194 for(size_type i = pos_ ; i < tokens_.size() ; ++i) {
195 s += tokens_[i].asInput();
197 is_.putback(from_utf8(s));
198 tokens_.erase(tokens_.begin() + pos_, tokens_.end());
199 // make sure that next token is read
204 bool Parser::setEncoding(std::string const & e, int p)
206 // We may (and need to) use unsafe encodings here: Since the text is
207 // converted to unicode while reading from is_, we never see text in
208 // the original encoding of the parser, but operate on utf8 strings
209 // instead. Therefore, we cannot misparse high bytes as {, } or \\.
210 Encoding const * const enc = encodings.fromLaTeXName(e, p, true);
212 warning_message("Unknown encoding " + e + ". Ignoring.");
215 return setEncoding(enc->iconvName());
219 void Parser::catInit()
221 if (curr_cat_ == theCatcodesType_)
223 curr_cat_ = theCatcodesType_;
225 fill(theCatcode_, theCatcode_ + 256, catOther);
226 fill(theCatcode_ + 'a', theCatcode_ + 'z' + 1, catLetter);
227 fill(theCatcode_ + 'A', theCatcode_ + 'Z' + 1, catLetter);
229 theCatcode_[int('@')] = catLetter;
231 if (theCatcodesType_ == NORMAL_CATCODES) {
232 theCatcode_[int('\\')] = catEscape;
233 theCatcode_[int('{')] = catBegin;
234 theCatcode_[int('}')] = catEnd;
235 theCatcode_[int('$')] = catMath;
236 theCatcode_[int('&')] = catAlign;
237 theCatcode_[int('\n')] = catNewline;
238 theCatcode_[int('#')] = catParameter;
239 theCatcode_[int('^')] = catSuper;
240 theCatcode_[int('_')] = catSub;
241 theCatcode_[0x7f] = catIgnore;
242 theCatcode_[int(' ')] = catSpace;
243 theCatcode_[int('\t')] = catSpace;
244 theCatcode_[int('\r')] = catNewline;
245 theCatcode_[int('~')] = catActive;
246 theCatcode_[int('%')] = catComment;
250 CatCode Parser::catcode(char_type c) const
253 return theCatcode_[(unsigned char)c];
258 void Parser::setCatcode(char c, CatCode cat)
260 theCatcode_[(unsigned char)c] = cat;
265 void Parser::setCatcodes(cat_type t)
267 theCatcodesType_ = t;
272 bool Parser::setEncoding(std::string const & e)
274 //warning_message("setting encoding to " + e);
276 // If the encoding is fixed, we must not change the stream encoding
277 // (because the whole input uses that encoding, e.g. if it comes from
278 // the clipboard). We still need to track the original encoding in
279 // encoding_iconv_, so that the generated output is correct.
286 void Parser::push_back(Token const & t)
288 tokens_.push_back(t);
292 // We return a copy here because the tokens_ vector may get reallocated
293 Token const Parser::prev_token() const
295 static const Token dummy;
296 return pos_ > 1 ? tokens_[pos_ - 2] : dummy;
300 // We return a copy here because the tokens_ vector may get reallocated
301 Token const Parser::curr_token() const
303 static const Token dummy;
304 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
308 // We return a copy here because the tokens_ vector may get reallocated
309 Token const Parser::next_token()
311 static const Token dummy;
314 if (pos_ >= tokens_.size())
316 return pos_ < tokens_.size() ? tokens_[pos_] : dummy;
320 // We return a copy here because the tokens_ vector may get reallocated
321 Token const Parser::next_next_token()
323 static const Token dummy;
326 // If tokenize_one() has not been called after the last get_token() we
327 // need to tokenize two more tokens.
328 if (pos_ >= tokens_.size())
330 if (pos_ + 1 >= tokens_.size())
332 return pos_ + 1 < tokens_.size() ? tokens_[pos_ + 1] : dummy;
336 // We return a copy here because the tokens_ vector may get reallocated
337 Token const Parser::get_token()
339 static const Token dummy;
342 if (pos_ >= tokens_.size()) {
344 if (pos_ >= tokens_.size())
347 // warning_message("looking at token " + tokens_[pos_]
348 // + " pos: " + pos_ <<);
349 return tokens_[pos_++];
353 bool Parser::isParagraph()
355 // A new paragraph in TeX is started
356 // - either by a newline, following any amount of whitespace
357 // characters (including zero), and another newline
358 // - or the token \par
359 if (curr_token().cat() == catNewline &&
360 (curr_token().cs().size() > 1 ||
361 (next_token().cat() == catSpace &&
362 next_next_token().cat() == catNewline)))
364 if (curr_token().cat() == catEscape && curr_token().cs() == "par")
370 bool Parser::skip_spaces(bool skip_comments)
372 // We just silently return if we have no more tokens.
373 // skip_spaces() should be callable at any time,
374 // the caller must check p::good() anyway.
375 bool skipped = false;
382 if (curr_token().cat() == catSpace ||
383 curr_token().cat() == catNewline) {
387 if ((curr_token().cat() == catComment && curr_token().cs().empty()))
389 if (skip_comments && curr_token().cat() == catComment) {
390 // If positions_ is not empty we are doing some kind
392 if (!positions_.empty())
393 warning_message("Ignoring comment: " + curr_token().asInput());
403 void Parser::unskip_spaces(bool skip_comments)
406 if ( curr_token().cat() == catSpace ||
407 (curr_token().cat() == catNewline && curr_token().cs().size() == 1))
409 else if (skip_comments && curr_token().cat() == catComment) {
410 // TODO: Get rid of this
411 // If positions_ is not empty we are doing some kind
413 if (!positions_.empty())
414 warning_message("Unignoring comment: " + curr_token().asInput());
423 void Parser::putback()
429 void Parser::pushPosition()
431 positions_.push_back(pos_);
435 void Parser::popPosition()
437 pos_ = positions_.back();
438 positions_.pop_back();
443 void Parser::dropPosition()
445 positions_.pop_back();
449 bool Parser::good() const
451 if (pos_ < tokens_.size())
455 return is_.peek() != idocstream::traits_type::eof();
459 bool Parser::hasOpt(string const & l)
461 // An optional argument can occur in any of the following forms:
469 // remember current position
470 unsigned int oldpos = pos_;
471 // skip spaces and comments
478 if (curr_token().cat() == catSpace ||
479 curr_token().cat() == catNewline ||
480 curr_token().cat() == catComment)
485 bool const retval = (next_token().asInput() == l);
491 bool Parser::hasIdxMacros(string const & c, string const & e)
493 // Check for index entry separator (! or @),
494 // consider escaping via "
495 // \p e marks a terminating delimiter¸
497 // remember current position
498 unsigned int oldpos = pos_;
499 // skip spaces and comments
507 if (curr_token().cat() == catEnd)
509 if (!e.empty() && curr_token().asInput() == e
510 && prev_token().asInput() != "\"")
512 if (curr_token().asInput() == c
513 && prev_token().asInput() != "\"") {
524 Parser::Arg Parser::getFullArg(char left, char right, bool allow_escaping, char e)
528 // This is needed if a partial file ends with a command without arguments,
531 return make_pair(false, string());
533 int group_level = (left == '{') ? 1 : 0;
535 Token t = get_token();
538 && (t.cat() == catComment || t.cat() == catEscape
539 || t.character() != left)) {
541 return make_pair(false, string());
546 if (t.cat() == catBegin) {
551 if (group_level > 0 && t.cat() == catEnd) {
557 if (t.cat() == catComment) {
559 warning_message("Ignoring comment: " + t.asInput());
562 if (allow_escaping) {
563 if (t.cat() != catEscape && t.character() == right
566 } else if (e != char()) {
567 if (prev_token().character() != e && t.character() == right
571 if (t.character() == right) {
572 if (t.cat() == catEscape)
574 if (group_level == 0)
578 result += t.asInput();
581 return make_pair(true, result);
585 string Parser::getArg(char left, char right, bool allow_escaping, char e)
587 return getFullArg(left, right, allow_escaping, e).second;
591 string Parser::getFullOpt(bool keepws, char left, char right)
593 Arg arg = getFullArg(left, right);
595 return left + arg.second + right;
602 string Parser::getOpt(bool keepws)
604 string const res = getArg('[', ']');
610 return '[' + res + ']';
614 string Parser::getFullParentheseArg()
616 Arg arg = getFullArg('(', ')');
618 return '(' + arg.second + ')';
623 bool Parser::hasListPreamble(string const & itemcmd)
625 // remember current position
626 unsigned int oldpos = pos_;
627 // jump over arguments
632 // and swallow spaces and comments
634 // we have a list preamble if the next thing
635 // that follows is not the \item command
636 bool res = next_token().cs() != itemcmd;
637 // back to orig position
643 string const Parser::ertEnvironment(string const & name)
649 for (Token t = get_token(); good(); t = get_token()) {
650 if (t.cat() == catBegin) {
652 os << '{' << verbatim_item() << '}';
653 } else if (t.asInput() == "\\begin") {
654 string const env = getArg('{', '}');
655 os << "\\begin{" << env << '}'
656 << ertEnvironment(env)
657 << "\\end{" << env << '}';
658 } else if (t.asInput() == "\\end") {
659 string const end = getArg('{', '}');
661 warning_message("\\end{" + end
662 + "} does not match \\begin{"
668 warning_message("unexpected end of input");
673 string const Parser::plainEnvironment(string const & name)
679 for (Token t = get_token(); good(); t = get_token()) {
680 if (t.asInput() == "\\end") {
681 string const end = getArg('{', '}');
685 os << "\\end{" << end << '}';
689 warning_message("unexpected end of input");
694 string const Parser::plainCommand(char left, char right, string const & name)
698 // check if first token is really the start character
699 Token tok = get_token();
700 if (tok.character() != left) {
701 warning_message("first character does not match start character of command \\" + name);
705 for (Token t = get_token(); good(); t = get_token()) {
706 if (t.character() == right) {
711 warning_message("unexpected end of input");
716 string const Parser::getCommandLatexParam()
723 if (pos_ + offset >= tokens_.size())
725 if (pos_ + offset >= tokens_.size())
727 Token t = tokens_[pos_ + offset];
728 if (t.cat() == catBegin)
737 Parser::Arg Parser::verbatimStuff(string const & end_string, bool const allow_linebreak)
740 return Arg(false, string());
744 size_t match_index = 0;
745 setCatcodes(VERBATIM_CATCODES);
746 for (Token t = get_token(); good(); t = get_token()) {
747 // FIXME t.asInput() might be longer than we need ?
748 if (t.asInput() == end_string.substr(match_index,
749 t.asInput().length())) {
750 match_index += t.asInput().length();
751 if (match_index >= end_string.length())
754 if (!allow_linebreak && t.asInput() == "\n") {
755 warning_message("unexpected end of input");
757 setCatcodes(NORMAL_CATCODES);
758 return Arg(false, string());
761 oss << end_string.substr(0, match_index)
770 warning_message("unexpected end of input");
772 setCatcodes(NORMAL_CATCODES);
773 return Arg(false, string());
775 setCatcodes(NORMAL_CATCODES);
777 return Arg(true, oss.str());
781 string const Parser::verbatimEnvironment(string const & name)
783 //FIXME: do something if endstring is not found
784 string s = verbatimStuff("\\end{" + name + "}").second;
785 // ignore one newline at beginning or end of string
786 if (prefixIs(s, "\n"))
788 if (suffixIs(s, "\n"))
789 s.erase(s.length() - 1,1);
794 string Parser::verbatimOption()
797 if (next_token().character() == '[') {
798 Token t = get_token();
799 for (t = get_token(); t.character() != ']' && good(); t = get_token()) {
800 if (t.cat() == catBegin) {
802 res += '{' + verbatim_item() + '}';
811 string Parser::verbatim_item()
816 if (next_token().cat() == catBegin) {
817 Token t = get_token(); // skip brace
819 for (t = get_token(); t.cat() != catEnd && good(); t = get_token()) {
820 if (t.cat() == catBegin) {
822 res += '{' + verbatim_item() + '}';
829 return get_token().asInput();
833 void Parser::tokenize_one()
840 switch (catcode(c)) {
843 while (is_.get(c) && catcode(c) == catSpace)
845 if (catcode(c) != catSpace)
847 push_back(Token(s, catSpace));
853 docstring s(1, getNewline(is_, c));
854 while (is_.get(c) && catcode(c) == catNewline) {
856 s += getNewline(is_, c);
858 if (catcode(c) != catNewline)
860 push_back(Token(s, catNewline));
865 // We don't treat "%\n" combinations here specially because
866 // we want to preserve them in the preamble
868 while (is_.get(c) && catcode(c) != catNewline)
870 // handle possible DOS line ending
871 if (catcode(c) == catNewline)
872 c = getNewline(is_, c);
873 // Note: The '%' at the beginning and the '\n' at the end
874 // of the comment are not stored.
876 push_back(Token(s, catComment));
883 error("unexpected end of input");
886 if (catcode(c) == catLetter) {
888 while (is_.get(c) && catcode(c) == catLetter)
890 if (catcode(c) != catLetter)
893 push_back(Token(s, catEscape));
899 warning_message("ignoring a char: " + std::to_string(static_cast<uint32_t>(c)));
904 push_back(Token(docstring(1, c), catcode(c)));
906 //warning_message(tokens_.back());
910 void Parser::dump() const
912 cerr << "\nTokens: ";
913 for (unsigned i = 0; i < tokens_.size(); ++i) {
918 cerr << " pos: " << pos_ << "\n";
922 void Parser::error(string const & msg) const
924 error_message("Line ~" + convert<string>(lineno_) + ": parse error: " + msg);