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/lstrings.h"
19 #include "support/textutils.h"
25 using namespace lyx::support;
32 * Translate a line ending to '\n'.
33 * \p c must have catcode catNewline, and it must be the last character read
36 char_type getNewline(iparserdocstream & is, char_type c)
38 // we have to handle 3 different line endings:
45 if (is.get(wc) && wc != '\n') {
61 ostream & operator<<(ostream & os, Token const & t)
63 if (t.cat() == catComment)
64 os << '%' << t.cs() << '\n';
65 else if (t.cat() == catSpace)
67 else if (t.cat() == catEscape)
68 os << '\\' << t.cs() << ' ';
69 else if (t.cat() == catLetter)
71 else if (t.cat() == catNewline)
72 os << "[" << t.cs().size() << "\\n," << t.cat() << "]\n";
74 os << '[' << t.cs() << ',' << t.cat() << ']';
79 string Token::asInput() const
81 if (cat_ == catComment)
82 return '%' + cs_ + '\n';
83 if (cat_ == catEscape)
89 bool Token::isAlnumASCII() const
91 return cat_ == catLetter ||
92 (cat_ == catOther && cs_.length() == 1 && isDigitASCII(cs_[0]));
97 void debugToken(std::ostream & os, Token const & t, unsigned int flags)
100 os << "t: " << t << " flags: " << flags;
101 if (flags & FLAG_BRACE_LAST) { os << sep << "BRACE_LAST"; sep = '|'; }
102 if (flags & FLAG_RIGHT ) { os << sep << "RIGHT" ; sep = '|'; }
103 if (flags & FLAG_END ) { os << sep << "END" ; sep = '|'; }
104 if (flags & FLAG_BRACK_LAST) { os << sep << "BRACK_LAST"; sep = '|'; }
105 if (flags & FLAG_TEXTMODE ) { os << sep << "TEXTMODE" ; sep = '|'; }
106 if (flags & FLAG_ITEM ) { os << sep << "ITEM" ; sep = '|'; }
107 if (flags & FLAG_LEAVE ) { os << sep << "LEAVE" ; sep = '|'; }
108 if (flags & FLAG_SIMPLE ) { os << sep << "SIMPLE" ; sep = '|'; }
109 if (flags & FLAG_EQUATION ) { os << sep << "EQUATION" ; sep = '|'; }
110 if (flags & FLAG_SIMPLE2 ) { os << sep << "SIMPLE2" ; sep = '|'; }
111 if (flags & FLAG_OPTION ) { os << sep << "OPTION" ; sep = '|'; }
112 if (flags & FLAG_BRACED ) { os << sep << "BRACED" ; sep = '|'; }
113 if (flags & FLAG_CELL ) { os << sep << "CELL" ; sep = '|'; }
114 if (flags & FLAG_TABBING ) { os << sep << "TABBING" ; sep = '|'; }
124 void iparserdocstream::setEncoding(std::string const & e)
126 is_ << lyx::setEncoding(e);
130 void iparserdocstream::putback(char_type c)
136 void iparserdocstream::putback(docstring const & s)
142 iparserdocstream & iparserdocstream::get(char_type &c)
147 //warning_message("unparsed: " + to_utf8(s_));
160 Parser::Parser(idocstream & is, std::string const & fixedenc)
161 : lineno_(0), pos_(0), iss_(nullptr), is_(is),
162 encoding_iconv_(fixedenc.empty() ? "UTF-8" : fixedenc),
163 theCatcodesType_(NORMAL_CATCODES), curr_cat_(UNDECIDED_CATCODES),
164 fixed_enc_(!fixedenc.empty())
167 is_.setEncoding(fixedenc);
172 Parser::Parser(string const & s)
173 : lineno_(0), pos_(0),
174 iss_(new idocstringstream(from_utf8(s))), is_(*iss_),
175 encoding_iconv_("UTF-8"),
176 theCatcodesType_(NORMAL_CATCODES), curr_cat_(UNDECIDED_CATCODES),
177 // An idocstringstream can not change the encoding
190 void Parser::deparse()
193 for(size_type i = pos_ ; i < tokens_.size() ; ++i) {
194 s += tokens_[i].asInput();
196 is_.putback(from_utf8(s));
197 tokens_.erase(tokens_.begin() + pos_, tokens_.end());
198 // make sure that next token is read
203 bool Parser::setEncoding(std::string const & e, int p)
205 // We may (and need to) use unsafe encodings here: Since the text is
206 // converted to unicode while reading from is_, we never see text in
207 // the original encoding of the parser, but operate on utf8 strings
208 // instead. Therefore, we cannot misparse high bytes as {, } or \\.
209 Encoding const * const enc = encodings.fromLaTeXName(e, p, true);
211 warning_message("Unknown encoding " + e + ". Ignoring.");
214 return setEncoding(enc->iconvName());
218 void Parser::catInit()
220 if (curr_cat_ == theCatcodesType_)
222 curr_cat_ = theCatcodesType_;
224 fill(theCatcode_, theCatcode_ + 256, catOther);
225 fill(theCatcode_ + 'a', theCatcode_ + 'z' + 1, catLetter);
226 fill(theCatcode_ + 'A', theCatcode_ + 'Z' + 1, catLetter);
228 theCatcode_[int('@')] = catLetter;
230 if (theCatcodesType_ == NORMAL_CATCODES) {
231 theCatcode_[int('\\')] = catEscape;
232 theCatcode_[int('{')] = catBegin;
233 theCatcode_[int('}')] = catEnd;
234 theCatcode_[int('$')] = catMath;
235 theCatcode_[int('&')] = catAlign;
236 theCatcode_[int('\n')] = catNewline;
237 theCatcode_[int('#')] = catParameter;
238 theCatcode_[int('^')] = catSuper;
239 theCatcode_[int('_')] = catSub;
240 theCatcode_[0x7f] = catIgnore;
241 theCatcode_[int(' ')] = catSpace;
242 theCatcode_[int('\t')] = catSpace;
243 theCatcode_[int('\r')] = catNewline;
244 theCatcode_[int('~')] = catActive;
245 theCatcode_[int('%')] = catComment;
249 CatCode Parser::catcode(char_type c) const
252 return theCatcode_[(unsigned char)c];
257 void Parser::setCatcode(char c, CatCode cat)
259 theCatcode_[(unsigned char)c] = cat;
264 void Parser::setCatcodes(cat_type t)
266 theCatcodesType_ = t;
271 bool Parser::setEncoding(std::string const & e)
273 //warning_message("setting encoding to " + e);
275 // If the encoding is fixed, we must not change the stream encoding
276 // (because the whole input uses that encoding, e.g. if it comes from
277 // the clipboard). We still need to track the original encoding in
278 // encoding_iconv_, so that the generated output is correct.
285 void Parser::push_back(Token const & t)
287 tokens_.push_back(t);
291 // We return a copy here because the tokens_ vector may get reallocated
292 Token const Parser::prev_token() const
294 static const Token dummy;
295 return pos_ > 1 ? tokens_[pos_ - 2] : dummy;
299 // We return a copy here because the tokens_ vector may get reallocated
300 Token const Parser::curr_token() const
302 static const Token dummy;
303 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
307 // We return a copy here because the tokens_ vector may get reallocated
308 Token const Parser::next_token()
310 static const Token dummy;
313 if (pos_ >= tokens_.size())
315 return pos_ < tokens_.size() ? tokens_[pos_] : dummy;
319 // We return a copy here because the tokens_ vector may get reallocated
320 Token const Parser::next_next_token()
322 static const Token dummy;
325 // If tokenize_one() has not been called after the last get_token() we
326 // need to tokenize two more tokens.
327 if (pos_ >= tokens_.size())
329 if (pos_ + 1 >= tokens_.size())
331 return pos_ + 1 < tokens_.size() ? tokens_[pos_ + 1] : dummy;
335 // We return a copy here because the tokens_ vector may get reallocated
336 Token const Parser::get_token()
338 static const Token dummy;
341 if (pos_ >= tokens_.size()) {
343 if (pos_ >= tokens_.size())
346 // warning_message("looking at token " + tokens_[pos_]
347 // + " pos: " + pos_ <<);
348 return tokens_[pos_++];
352 bool Parser::isParagraph()
354 // A new paragraph in TeX is started
355 // - either by a newline, following any amount of whitespace
356 // characters (including zero), and another newline
357 // - or the token \par
358 if (curr_token().cat() == catNewline &&
359 (curr_token().cs().size() > 1 ||
360 (next_token().cat() == catSpace &&
361 next_next_token().cat() == catNewline)))
363 if (curr_token().cat() == catEscape && curr_token().cs() == "par")
369 bool Parser::skip_spaces(bool skip_comments)
371 // We just silently return if we have no more tokens.
372 // skip_spaces() should be callable at any time,
373 // the caller must check p::good() anyway.
374 bool skipped = false;
381 if (curr_token().cat() == catSpace ||
382 curr_token().cat() == catNewline) {
386 if ((curr_token().cat() == catComment && curr_token().cs().empty()))
388 if (skip_comments && curr_token().cat() == catComment) {
389 // If positions_ is not empty we are doing some kind
391 if (!positions_.empty())
392 warning_message("Ignoring comment: " + curr_token().asInput());
402 void Parser::unskip_spaces(bool skip_comments)
405 if ( curr_token().cat() == catSpace ||
406 (curr_token().cat() == catNewline && curr_token().cs().size() == 1))
408 else if (skip_comments && curr_token().cat() == catComment) {
409 // TODO: Get rid of this
410 // If positions_ is not empty we are doing some kind
412 if (!positions_.empty())
413 warning_message("Unignoring comment: " + curr_token().asInput());
422 void Parser::putback()
428 void Parser::pushPosition()
430 positions_.push_back(pos_);
434 void Parser::popPosition()
436 pos_ = positions_.back();
437 positions_.pop_back();
442 void Parser::dropPosition()
444 positions_.pop_back();
448 bool Parser::good() const
450 if (pos_ < tokens_.size())
454 return is_.peek() != idocstream::traits_type::eof();
458 bool Parser::hasOpt(string const & l)
460 // An optional argument can occur in any of the following forms:
468 // remember current position
469 unsigned int oldpos = pos_;
470 // skip spaces and comments
477 if (curr_token().cat() == catSpace ||
478 curr_token().cat() == catNewline ||
479 curr_token().cat() == catComment)
484 bool const retval = (next_token().asInput() == l);
490 bool Parser::hasIdxMacros(string const & c, string const & e)
492 // Check for index entry separator (! or @),
493 // consider escaping via "
494 // \p e marks a terminating delimiter¸
496 // remember current position
497 unsigned int oldpos = pos_;
498 // skip spaces and comments
506 if (curr_token().cat() == catEnd)
508 if (!e.empty() && curr_token().asInput() == e
509 && prev_token().asInput() != "\"")
511 if (curr_token().asInput() == c
512 && prev_token().asInput() != "\"") {
523 Parser::Arg Parser::getFullArg(char left, char right, bool allow_escaping, char e)
527 // This is needed if a partial file ends with a command without arguments,
530 return make_pair(false, string());
532 int group_level = (left == '{') ? 1 : 0;
534 Token t = get_token();
537 && (t.cat() == catComment || t.cat() == catEscape
538 || t.character() != left)) {
540 return make_pair(false, string());
545 if (t.cat() == catBegin) {
550 if (group_level > 0 && t.cat() == catEnd) {
556 if (t.cat() == catComment) {
558 warning_message("Ignoring comment: " + t.asInput());
561 if (allow_escaping) {
562 if (t.cat() != catEscape && t.character() == right
565 } else if (e != char()) {
566 if (prev_token().character() != e && t.character() == right
570 if (t.character() == right) {
571 if (t.cat() == catEscape)
573 if (group_level == 0)
577 result += t.asInput();
580 return make_pair(true, result);
584 string Parser::getArg(char left, char right, bool allow_escaping, char e)
586 return getFullArg(left, right, allow_escaping, e).second;
590 string Parser::getFullOpt(bool keepws, char left, char right)
592 Arg arg = getFullArg(left, right);
594 return left + arg.second + right;
601 string Parser::getOpt(bool keepws)
603 string const res = getArg('[', ']');
609 return '[' + res + ']';
613 string Parser::getFullParentheseArg()
615 Arg arg = getFullArg('(', ')');
617 return '(' + arg.second + ')';
622 bool Parser::hasListPreamble(string const & itemcmd)
624 // remember current position
625 unsigned int oldpos = pos_;
626 // jump over arguments
631 // and swallow spaces and comments
633 // we have a list preamble if the next thing
634 // that follows is not the \item command
635 bool res = next_token().cs() != itemcmd;
636 // back to orig position
642 string const Parser::ertEnvironment(string const & name)
648 for (Token t = get_token(); good(); t = get_token()) {
649 if (t.cat() == catBegin) {
651 os << '{' << verbatim_item() << '}';
652 } else if (t.asInput() == "\\begin") {
653 string const env = getArg('{', '}');
654 os << "\\begin{" << env << '}'
655 << ertEnvironment(env)
656 << "\\end{" << env << '}';
657 } else if (t.asInput() == "\\end") {
658 string const end = getArg('{', '}');
660 warning_message("\\end{" + end
661 + "} does not match \\begin{"
667 warning_message("unexpected end of input");
672 string const Parser::plainEnvironment(string const & name)
678 for (Token t = get_token(); good(); t = get_token()) {
679 if (t.asInput() == "\\end") {
680 string const end = getArg('{', '}');
684 os << "\\end{" << end << '}';
688 warning_message("unexpected end of input");
693 string const Parser::plainCommand(char left, char right, string const & name)
697 // check if first token is really the start character
698 Token tok = get_token();
699 if (tok.character() != left) {
700 warning_message("first character does not match start character of command \\" + name);
704 for (Token t = get_token(); good(); t = get_token()) {
705 if (t.character() == right) {
710 warning_message("unexpected end of input");
715 string const Parser::getCommandLatexParam()
722 if (pos_ + offset >= tokens_.size())
724 if (pos_ + offset >= tokens_.size())
726 Token t = tokens_[pos_ + offset];
727 if (t.cat() == catBegin)
736 Parser::Arg Parser::verbatimStuff(string const & end_string, bool const allow_linebreak)
739 return Arg(false, string());
743 size_t match_index = 0;
744 setCatcodes(VERBATIM_CATCODES);
745 for (Token t = get_token(); good(); t = get_token()) {
746 // FIXME t.asInput() might be longer than we need ?
747 if (t.asInput() == end_string.substr(match_index,
748 t.asInput().length())) {
749 match_index += t.asInput().length();
750 if (match_index >= end_string.length())
753 if (!allow_linebreak && t.asInput() == "\n") {
754 warning_message("unexpected end of input");
756 setCatcodes(NORMAL_CATCODES);
757 return Arg(false, string());
760 oss << end_string.substr(0, match_index)
769 warning_message("unexpected end of input");
771 setCatcodes(NORMAL_CATCODES);
772 return Arg(false, string());
774 setCatcodes(NORMAL_CATCODES);
776 return Arg(true, oss.str());
780 string const Parser::verbatimEnvironment(string const & name)
782 //FIXME: do something if endstring is not found
783 string s = verbatimStuff("\\end{" + name + "}").second;
784 // ignore one newline at beginning or end of string
785 if (prefixIs(s, "\n"))
787 if (suffixIs(s, "\n"))
788 s.erase(s.length() - 1,1);
793 string Parser::verbatimOption()
796 if (next_token().character() == '[') {
797 Token t = get_token();
798 for (t = get_token(); t.character() != ']' && good(); t = get_token()) {
799 if (t.cat() == catBegin) {
801 res += '{' + verbatim_item() + '}';
810 string Parser::verbatim_item()
815 if (next_token().cat() == catBegin) {
816 Token t = get_token(); // skip brace
818 for (t = get_token(); t.cat() != catEnd && good(); t = get_token()) {
819 if (t.cat() == catBegin) {
821 res += '{' + verbatim_item() + '}';
828 return get_token().asInput();
832 void Parser::tokenize_one()
839 switch (catcode(c)) {
842 while (is_.get(c) && catcode(c) == catSpace)
844 if (catcode(c) != catSpace)
846 push_back(Token(s, catSpace));
852 docstring s(1, getNewline(is_, c));
853 while (is_.get(c) && catcode(c) == catNewline) {
855 s += getNewline(is_, c);
857 if (catcode(c) != catNewline)
859 push_back(Token(s, catNewline));
864 // We don't treat "%\n" combinations here specially because
865 // we want to preserve them in the preamble
867 while (is_.get(c) && catcode(c) != catNewline)
869 // handle possible DOS line ending
870 if (catcode(c) == catNewline)
871 c = getNewline(is_, c);
872 // Note: The '%' at the beginning and the '\n' at the end
873 // of the comment are not stored.
875 push_back(Token(s, catComment));
882 error("unexpected end of input");
885 if (catcode(c) == catLetter) {
887 while (is_.get(c) && catcode(c) == catLetter)
889 if (catcode(c) != catLetter)
892 push_back(Token(s, catEscape));
898 warning_message("ignoring a char: " + std::to_string(static_cast<uint32_t>(c)));
903 push_back(Token(docstring(1, c), catcode(c)));
905 //warning_message(tokens_.back());
909 void Parser::dump() const
911 cerr << "\nTokens: ";
912 for (unsigned i = 0; i < tokens_.size(); ++i) {
917 cerr << " pos: " << pos_ << "\n";
921 void Parser::error(string const & msg) const
923 cerr << "Line ~" << lineno_ << ": parse error: " << msg << endl;