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"
23 using namespace lyx::support;
30 * Translate a line ending to '\n'.
31 * \p c must have catcode catNewline, and it must be the last character read
34 char_type getNewline(iparserdocstream & is, char_type c)
36 // we have to handle 3 different line endings:
43 if (is.get(wc) && wc != '\n') {
59 ostream & operator<<(ostream & os, Token const & t)
61 if (t.cat() == catComment)
62 os << '%' << t.cs() << '\n';
63 else if (t.cat() == catSpace)
65 else if (t.cat() == catEscape)
66 os << '\\' << t.cs() << ' ';
67 else if (t.cat() == catLetter)
69 else if (t.cat() == catNewline)
70 os << "[" << t.cs().size() << "\\n," << t.cat() << "]\n";
72 os << '[' << t.cs() << ',' << t.cat() << ']';
77 string Token::asInput() const
79 if (cat_ == catComment)
80 return '%' + cs_ + '\n';
81 if (cat_ == catEscape)
87 bool Token::isAlnumASCII() const
89 return cat_ == catLetter ||
90 (cat_ == catOther && cs_.length() == 1 && isDigitASCII(cs_[0]));
95 void debugToken(std::ostream & os, Token const & t, unsigned int flags)
98 os << "t: " << t << " flags: " << flags;
99 if (flags & FLAG_BRACE_LAST) { os << sep << "BRACE_LAST"; sep = '|'; }
100 if (flags & FLAG_RIGHT ) { os << sep << "RIGHT" ; sep = '|'; }
101 if (flags & FLAG_END ) { os << sep << "END" ; sep = '|'; }
102 if (flags & FLAG_BRACK_LAST) { os << sep << "BRACK_LAST"; sep = '|'; }
103 if (flags & FLAG_TEXTMODE ) { os << sep << "TEXTMODE" ; sep = '|'; }
104 if (flags & FLAG_ITEM ) { os << sep << "ITEM" ; sep = '|'; }
105 if (flags & FLAG_LEAVE ) { os << sep << "LEAVE" ; sep = '|'; }
106 if (flags & FLAG_SIMPLE ) { os << sep << "SIMPLE" ; sep = '|'; }
107 if (flags & FLAG_EQUATION ) { os << sep << "EQUATION" ; sep = '|'; }
108 if (flags & FLAG_SIMPLE2 ) { os << sep << "SIMPLE2" ; sep = '|'; }
109 if (flags & FLAG_OPTION ) { os << sep << "OPTION" ; sep = '|'; }
110 if (flags & FLAG_BRACED ) { os << sep << "BRACED" ; sep = '|'; }
111 if (flags & FLAG_CELL ) { os << sep << "CELL" ; sep = '|'; }
112 if (flags & FLAG_TABBING ) { os << sep << "TABBING" ; sep = '|'; }
122 void iparserdocstream::setEncoding(std::string const & e)
124 is_ << lyx::setEncoding(e);
128 void iparserdocstream::putback(char_type c)
134 void iparserdocstream::putback(docstring const & s)
140 iparserdocstream & iparserdocstream::get(char_type &c)
145 //cerr << "unparsed: " << to_utf8(s_) <<endl;
158 Parser::Parser(idocstream & is, std::string const & fixedenc)
159 : lineno_(0), pos_(0), iss_(nullptr), is_(is),
160 encoding_iconv_(fixedenc.empty() ? "UTF-8" : fixedenc),
161 theCatcodesType_(NORMAL_CATCODES), curr_cat_(UNDECIDED_CATCODES),
162 fixed_enc_(!fixedenc.empty())
165 is_.setEncoding(fixedenc);
170 Parser::Parser(string const & s)
171 : lineno_(0), pos_(0),
172 iss_(new idocstringstream(from_utf8(s))), is_(*iss_),
173 encoding_iconv_("UTF-8"),
174 theCatcodesType_(NORMAL_CATCODES), curr_cat_(UNDECIDED_CATCODES),
175 // An idocstringstream can not change the encoding
188 void Parser::deparse()
191 for(size_type i = pos_ ; i < tokens_.size() ; ++i) {
192 s += tokens_[i].asInput();
194 is_.putback(from_utf8(s));
195 tokens_.erase(tokens_.begin() + pos_, tokens_.end());
196 // make sure that next token is read
201 bool Parser::setEncoding(std::string const & e, int p)
203 // We may (and need to) use unsafe encodings here: Since the text is
204 // converted to unicode while reading from is_, we never see text in
205 // the original encoding of the parser, but operate on utf8 strings
206 // instead. Therefore, we cannot misparse high bytes as {, } or \\.
207 Encoding const * const enc = encodings.fromLaTeXName(e, p, true);
209 cerr << "Unknown encoding " << e << ". Ignoring." << std::endl;
212 return setEncoding(enc->iconvName());
216 void Parser::catInit()
218 if (curr_cat_ == theCatcodesType_)
220 curr_cat_ = theCatcodesType_;
222 fill(theCatcode_, theCatcode_ + 256, catOther);
223 fill(theCatcode_ + 'a', theCatcode_ + 'z' + 1, catLetter);
224 fill(theCatcode_ + 'A', theCatcode_ + 'Z' + 1, catLetter);
226 theCatcode_[int('@')] = catLetter;
228 if (theCatcodesType_ == NORMAL_CATCODES) {
229 theCatcode_[int('\\')] = catEscape;
230 theCatcode_[int('{')] = catBegin;
231 theCatcode_[int('}')] = catEnd;
232 theCatcode_[int('$')] = catMath;
233 theCatcode_[int('&')] = catAlign;
234 theCatcode_[int('\n')] = catNewline;
235 theCatcode_[int('#')] = catParameter;
236 theCatcode_[int('^')] = catSuper;
237 theCatcode_[int('_')] = catSub;
238 theCatcode_[0x7f] = catIgnore;
239 theCatcode_[int(' ')] = catSpace;
240 theCatcode_[int('\t')] = catSpace;
241 theCatcode_[int('\r')] = catNewline;
242 theCatcode_[int('~')] = catActive;
243 theCatcode_[int('%')] = catComment;
247 CatCode Parser::catcode(char_type c) const
250 return theCatcode_[(unsigned char)c];
255 void Parser::setCatcode(char c, CatCode cat)
257 theCatcode_[(unsigned char)c] = cat;
262 void Parser::setCatcodes(cat_type t)
264 theCatcodesType_ = t;
269 bool Parser::setEncoding(std::string const & e)
271 //cerr << "setting encoding to " << e << std::endl;
273 // If the encoding is fixed, we must not change the stream encoding
274 // (because the whole input uses that encoding, e.g. if it comes from
275 // the clipboard). We still need to track the original encoding in
276 // encoding_iconv_, so that the generated output is correct.
283 void Parser::push_back(Token const & t)
285 tokens_.push_back(t);
289 // We return a copy here because the tokens_ vector may get reallocated
290 Token const Parser::prev_token() const
292 static const Token dummy;
293 return pos_ > 1 ? tokens_[pos_ - 2] : dummy;
297 // We return a copy here because the tokens_ vector may get reallocated
298 Token const Parser::curr_token() const
300 static const Token dummy;
301 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
305 // We return a copy here because the tokens_ vector may get reallocated
306 Token const Parser::next_token()
308 static const Token dummy;
311 if (pos_ >= tokens_.size())
313 return pos_ < tokens_.size() ? tokens_[pos_] : dummy;
317 // We return a copy here because the tokens_ vector may get reallocated
318 Token const Parser::next_next_token()
320 static const Token dummy;
323 // If tokenize_one() has not been called after the last get_token() we
324 // need to tokenize two more tokens.
325 if (pos_ >= tokens_.size())
327 if (pos_ + 1 >= tokens_.size())
329 return pos_ + 1 < tokens_.size() ? tokens_[pos_ + 1] : dummy;
333 // We return a copy here because the tokens_ vector may get reallocated
334 Token const Parser::get_token()
336 static const Token dummy;
339 if (pos_ >= tokens_.size()) {
341 if (pos_ >= tokens_.size())
344 // cerr << "looking at token " << tokens_[pos_]
345 // << " pos: " << pos_ << '\n';
346 return tokens_[pos_++];
350 bool Parser::isParagraph()
352 // A new paragraph in TeX is started
353 // - either by a newline, following any amount of whitespace
354 // characters (including zero), and another newline
355 // - or the token \par
356 if (curr_token().cat() == catNewline &&
357 (curr_token().cs().size() > 1 ||
358 (next_token().cat() == catSpace &&
359 next_next_token().cat() == catNewline)))
361 if (curr_token().cat() == catEscape && curr_token().cs() == "par")
367 bool Parser::skip_spaces(bool skip_comments)
369 // We just silently return if we have no more tokens.
370 // skip_spaces() should be callable at any time,
371 // the caller must check p::good() anyway.
372 bool skipped = false;
379 if (curr_token().cat() == catSpace ||
380 curr_token().cat() == catNewline) {
384 if ((curr_token().cat() == catComment && curr_token().cs().empty()))
386 if (skip_comments && curr_token().cat() == catComment) {
387 // If positions_ is not empty we are doing some kind
389 if (!positions_.empty())
390 cerr << " Ignoring comment: "
391 << curr_token().asInput();
401 void Parser::unskip_spaces(bool skip_comments)
404 if ( curr_token().cat() == catSpace ||
405 (curr_token().cat() == catNewline && curr_token().cs().size() == 1))
407 else if (skip_comments && curr_token().cat() == catComment) {
408 // TODO: Get rid of this
409 // If positions_ is not empty we are doing some kind
411 if (!positions_.empty())
412 cerr << "Unignoring comment: "
413 << 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 cerr << "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 cerr << "\\end{" << end
661 << "} does not match \\begin{" << name
667 cerr << "unexpected end of input" << endl;
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 cerr << "unexpected end of input" << endl;
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 cerr << "first character does not match start character of command \\" << name << endl;
704 for (Token t = get_token(); good(); t = get_token()) {
705 if (t.character() == right) {
710 cerr << "unexpected end of input" << endl;
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 cerr << "unexpected end of input" << endl;
756 setCatcodes(NORMAL_CATCODES);
757 return Arg(false, string());
760 oss << end_string.substr(0, match_index)
769 cerr << "unexpected end of input" << endl;
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 cerr << "ignoring a char: " << static_cast<uint32_t>(c) << "\n";
903 push_back(Token(docstring(1, c), catcode(c)));
905 //cerr << 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;