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 Parser::Arg Parser::getFullArg(char left, char right, bool allow_escaping)
494 // This is needed if a partial file ends with a command without arguments,
497 return make_pair(false, string());
501 Token t = get_token();
503 if (t.cat() == catComment || t.cat() == catEscape ||
504 t.character() != left) {
506 return make_pair(false, string());
511 if (left != '{' && t.cat() == catBegin) {
515 if (left != '{' && t.cat() == catEnd) {
520 if (t.cat() == catComment) {
522 cerr << "Ignoring comment: " << t.asInput();
525 if (allow_escaping) {
526 if (t.cat() != catEscape && t.character() == right
530 if (t.character() == right) {
531 if (t.cat() == catEscape)
533 if (group_level == 0)
537 result += t.asInput();
540 return make_pair(true, result);
544 string Parser::getArg(char left, char right, bool allow_escaping)
546 return getFullArg(left, right, allow_escaping).second;
550 string Parser::getFullOpt(bool keepws, char left, char right)
552 Arg arg = getFullArg(left, right);
554 return left + arg.second + right;
561 string Parser::getOpt(bool keepws)
563 string const res = getArg('[', ']');
569 return '[' + res + ']';
573 string Parser::getFullParentheseArg()
575 Arg arg = getFullArg('(', ')');
577 return '(' + arg.second + ')';
582 bool Parser::hasListPreamble(string const & itemcmd)
584 // remember current position
585 unsigned int oldpos = pos_;
586 // jump over arguments
591 // and swallow spaces and comments
593 // we have a list preamble if the next thing
594 // that follows is not the \item command
595 bool res = next_token().cs() != itemcmd;
596 // back to orig position
602 string const Parser::ertEnvironment(string const & name)
608 for (Token t = get_token(); good(); t = get_token()) {
609 if (t.cat() == catBegin) {
611 os << '{' << verbatim_item() << '}';
612 } else if (t.asInput() == "\\begin") {
613 string const env = getArg('{', '}');
614 os << "\\begin{" << env << '}'
615 << ertEnvironment(env)
616 << "\\end{" << env << '}';
617 } else if (t.asInput() == "\\end") {
618 string const end = getArg('{', '}');
620 cerr << "\\end{" << end
621 << "} does not match \\begin{" << name
627 cerr << "unexpected end of input" << endl;
632 string const Parser::plainEnvironment(string const & name)
638 for (Token t = get_token(); good(); t = get_token()) {
639 if (t.asInput() == "\\end") {
640 string const end = getArg('{', '}');
644 os << "\\end{" << end << '}';
648 cerr << "unexpected end of input" << endl;
653 string const Parser::plainCommand(char left, char right, string const & name)
657 // check if first token is really the start character
658 Token tok = get_token();
659 if (tok.character() != left) {
660 cerr << "first character does not match start character of command \\" << name << endl;
664 for (Token t = get_token(); good(); t = get_token()) {
665 if (t.character() == right) {
670 cerr << "unexpected end of input" << endl;
675 string const Parser::getCommandLatexParam()
682 if (pos_ + offset >= tokens_.size())
684 if (pos_ + offset >= tokens_.size())
686 Token t = tokens_[pos_ + offset];
687 if (t.cat() == catBegin)
696 Parser::Arg Parser::verbatimStuff(string const & end_string, bool const allow_linebreak)
699 return Arg(false, string());
703 size_t match_index = 0;
704 setCatcodes(VERBATIM_CATCODES);
705 for (Token t = get_token(); good(); t = get_token()) {
706 // FIXME t.asInput() might be longer than we need ?
707 if (t.asInput() == end_string.substr(match_index,
708 t.asInput().length())) {
709 match_index += t.asInput().length();
710 if (match_index >= end_string.length())
713 if (!allow_linebreak && t.asInput() == "\n") {
714 cerr << "unexpected end of input" << endl;
716 setCatcodes(NORMAL_CATCODES);
717 return Arg(false, string());
720 oss << end_string.substr(0, match_index)
729 cerr << "unexpected end of input" << endl;
731 setCatcodes(NORMAL_CATCODES);
732 return Arg(false, string());
734 setCatcodes(NORMAL_CATCODES);
736 return Arg(true, oss.str());
740 string const Parser::verbatimEnvironment(string const & name)
742 //FIXME: do something if endstring is not found
743 string s = verbatimStuff("\\end{" + name + "}").second;
744 // ignore one newline at beginning or end of string
745 if (prefixIs(s, "\n"))
747 if (suffixIs(s, "\n"))
748 s.erase(s.length() - 1,1);
753 string Parser::verbatimOption()
756 if (next_token().character() == '[') {
757 Token t = get_token();
758 for (t = get_token(); t.character() != ']' && good(); t = get_token()) {
759 if (t.cat() == catBegin) {
761 res += '{' + verbatim_item() + '}';
770 string Parser::verbatim_item()
775 if (next_token().cat() == catBegin) {
776 Token t = get_token(); // skip brace
778 for (t = get_token(); t.cat() != catEnd && good(); t = get_token()) {
779 if (t.cat() == catBegin) {
781 res += '{' + verbatim_item() + '}';
788 return get_token().asInput();
792 void Parser::tokenize_one()
799 switch (catcode(c)) {
802 while (is_.get(c) && catcode(c) == catSpace)
804 if (catcode(c) != catSpace)
806 push_back(Token(s, catSpace));
812 docstring s(1, getNewline(is_, c));
813 while (is_.get(c) && catcode(c) == catNewline) {
815 s += getNewline(is_, c);
817 if (catcode(c) != catNewline)
819 push_back(Token(s, catNewline));
824 // We don't treat "%\n" combinations here specially because
825 // we want to preserve them in the preamble
827 while (is_.get(c) && catcode(c) != catNewline)
829 // handle possible DOS line ending
830 if (catcode(c) == catNewline)
831 c = getNewline(is_, c);
832 // Note: The '%' at the beginning and the '\n' at the end
833 // of the comment are not stored.
835 push_back(Token(s, catComment));
842 error("unexpected end of input");
845 if (catcode(c) == catLetter) {
847 while (is_.get(c) && catcode(c) == catLetter)
849 if (catcode(c) != catLetter)
852 push_back(Token(s, catEscape));
858 cerr << "ignoring a char: " << static_cast<uint32_t>(c) << "\n";
863 push_back(Token(docstring(1, c), catcode(c)));
865 //cerr << tokens_.back();
869 void Parser::dump() const
871 cerr << "\nTokens: ";
872 for (unsigned i = 0; i < tokens_.size(); ++i) {
877 cerr << " pos: " << pos_ << "\n";
881 void Parser::error(string const & msg) const
883 cerr << "Line ~" << lineno_ << ": parse error: " << msg << endl;