]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/Parser.h
Update tex2lyx test files
[lyx.git] / src / tex2lyx / Parser.h
1 // -*- C++ -*-
2 /**
3  * \file Parser.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author André Pönitz
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef PARSER_H
13 #define PARSER_H
14
15 #include <string>
16 #include <utility>
17 #include <vector>
18
19 #include "support/docstream.h"
20
21 namespace lyx {
22
23
24 enum mode_type {UNDECIDED_MODE, TEXT_MODE, MATH_MODE, MATHTEXT_MODE, TABLE_MODE};
25
26 mode_type asMode(mode_type oldmode, std::string const & str);
27
28
29 // These are TeX's catcodes
30 enum CatCode {
31         catEscape,     // 0    backslash
32         catBegin,      // 1    {
33         catEnd,        // 2    }
34         catMath,       // 3    $
35         catAlign,      // 4    &
36         catNewline,    // 5    ^^M
37         catParameter,  // 6    #
38         catSuper,      // 7    ^
39         catSub,        // 8    _
40         catIgnore,     // 9
41         catSpace,      // 10   space
42         catLetter,     // 11   a-zA-Z
43         catOther,      // 12   none of the above
44         catActive,     // 13   ~
45         catComment,    // 14   %
46         catInvalid     // 15   <delete>
47 };
48
49
50 enum {
51         FLAG_BRACE_LAST = 1 << 1,  //  last closing brace ends the parsing
52         FLAG_RIGHT      = 1 << 2,  //  next \\right ends the parsing process
53         FLAG_END        = 1 << 3,  //  next \\end ends the parsing process
54         FLAG_BRACK_LAST = 1 << 4,  //  next closing bracket ends the parsing
55         FLAG_TEXTMODE   = 1 << 5,  //  we are in a box
56         FLAG_ITEM       = 1 << 6,  //  read a (possibly braced token)
57         FLAG_LEAVE      = 1 << 7,  //  leave the loop at the end
58         FLAG_SIMPLE     = 1 << 8,  //  next $ leaves the loop
59         FLAG_EQUATION   = 1 << 9,  //  next \] leaves the loop
60         FLAG_SIMPLE2    = 1 << 10, //  next \) leaves the loop
61         FLAG_OPTION     = 1 << 11, //  read [...] style option
62         FLAG_BRACED     = 1 << 12, //  read {...} style argument
63         FLAG_CELL       = 1 << 13, //  read table cell
64         FLAG_TABBING    = 1 << 14  //  We are inside a tabbing environment
65 };
66
67
68
69 //
70 // Helper class for parsing
71 //
72
73 class Token {
74 public:
75         ///
76         Token() : cs_(), cat_(catIgnore) {}
77         ///
78         Token(docstring const & cs, CatCode cat) : cs_(to_utf8(cs)), cat_(cat) {}
79
80         /// Returns the token as string
81         std::string const & cs() const { return cs_; }
82         /// Returns the catcode of the token
83         CatCode cat() const { return cat_; }
84         /** Get the character of tokens that were constructed from a single
85          * character input or a two character input and cat_ == catEscape.
86          * FIXME: The intended usage is not clear. The Token class in
87          *        ../mathed/MathParser.cpp (which is the anchestor of this
88          *        class) uses a separate char member for this method. I
89          *        believe that the intended usage is to not cover tokens with
90          *        catEscape or catComment, e.g. \code
91          *        return (cs_.empty() || cat_ == catEscape || cat_ == catComment) ? 0 : cs_[0];
92          *        \endcode
93          *        All usages of this method should be checked. gb 2011-01-05
94          */
95         char character() const { return cs_.empty() ? 0 : cs_[0]; }
96         /// Returns the token verbatim
97         std::string asInput() const;
98         /// Is the token an alphanumerical character?
99         bool isAlnumASCII() const;
100
101 private:
102         ///
103         std::string cs_;
104         ///
105         CatCode cat_;
106 };
107
108 std::ostream & operator<<(std::ostream & os, Token const & t);
109
110 #ifdef FILEDEBUG
111 extern void debugToken(std::ostream & os, Token const & t, unsigned int flags);
112 #endif
113
114
115 /*!
116  * Actual parser class
117  *
118  * The parser parses every character of the inputstream into a token
119  * and classifies the token.
120  * The following transformations are done:
121  * - Consecutive spaces are combined into one single token with CatCode catSpace
122  * - Consecutive newlines are combined into one single token with CatCode catNewline
123  * - Comments and %\n combinations are parsed into one token with CatCode catComment
124  */
125
126 class Parser {
127         /// noncopyable
128         Parser(Parser const & p);
129         Parser & operator=(Parser const & p);
130 public:
131         ///
132         Parser(idocstream & is);
133         ///
134         Parser(std::string const & s);
135         ///
136         ~Parser();
137
138         /// change the latex encoding of the input stream
139         void setEncoding(std::string const & encoding);
140         /// get the current latex encoding of the input stream
141         std::string getEncoding() const { return encoding_latex_; }
142
143         ///
144         int lineno() const { return lineno_; }
145         ///
146         void putback();
147         /// store current position
148         void pushPosition();
149         /// restore previous position
150         void popPosition();
151         /// dump contents to screen
152         void dump() const;
153
154         /// Does an optional argument follow after the current token?
155         bool hasOpt();
156         ///
157         typedef std::pair<bool, std::string> Arg;
158         /*!
159          * Get an argument enclosed by \p left and \p right.
160          * If \p allow_escaping is true, a right delimiter escaped by a
161          * backslash does not count as delimiter, but is included in the
162          * argument.
163          * \returns wether an argument was found in \p Arg.first and the
164          * argument in \p Arg.second. \see getArg().
165          */
166         Arg getFullArg(char left, char right, bool allow_escaping = true);
167         /*!
168          * Get an argument enclosed by \p left and \p right.
169          * If \p allow_escaping is true, a right delimiter escaped by a
170          * backslash does not count as delimiter, but is included in the
171          * argument.
172          * \returns the argument (without \p left and \p right) or the empty
173          * string if the next non-space token is not \p left. Use
174          * getFullArg() if you need to know wether there was an empty
175          * argument or no argument at all.
176          */
177         std::string getArg(char left, char right, bool allow_escaping = true);
178         /*!
179          * Like getOpt(), but distinguishes between a missing argument ""
180          * and an empty argument "[]".
181          */
182         std::string getFullOpt(bool keepws = false);
183         /*!
184          * \returns getArg('[', ']') including the brackets or the
185          * empty string if there is no such argument.
186          * No whitespace is eaten if \p keepws is true and no optional
187          * argument exists. This is important if an optional argument is
188          * parsed that would go after a command in ERT: In this case the
189          * whitespace is needed to separate the ERT from the subsequent
190          * word. Without it, the ERT and the next word would be concatenated
191          * during .tex export, thus creating an invalid command.
192          */
193         std::string getOpt(bool keepws = false);
194         /*!
195          * \returns getFullArg('(', ')') including the parentheses or the
196          * empty string if there is no such argument.
197          */
198         std::string getFullParentheseArg();
199         /*!
200          * \returns the contents of the environment \p name.
201          * <tt>\begin{name}</tt> must be parsed already, <tt>\end{name}</tt>
202          * is parsed but not returned.
203          */
204         std::string const verbatimEnvironment(std::string const & name);
205         /*
206          * The same as verbatimEnvironment(std::string const & name) but
207          * \begin and \end commands inside the name environment are not parsed.
208          * This function is designed to parse verbatim environments.
209          */
210         std::string const plainEnvironment(std::string const & name);
211         /*
212          * Basically the same as plainEnvironment(std::string const & name) but
213          * instead of \begin and \end commands the parsing is started/stopped
214          * at given characters.
215          * This function is designed to parse verbatim commands.
216          */
217         std::string const plainCommand(char left, char right, std::string const & name);
218         /*!
219          * Returns the character of the current token and increments
220          * the token position.
221          */
222         char getChar();
223         ///
224         void error(std::string const & msg);
225         /// Parses one token from \p is 
226         void tokenize_one();
227         ///
228         void push_back(Token const & t);
229         /// The previous token.
230         Token const prev_token() const;
231         /// The current token.
232         Token const curr_token() const;
233         /// The next token.
234         Token const next_token();
235         /// The next but one token.
236         Token const next_next_token();
237         /// Make the next token current and return that.
238         Token const get_token();
239         /// \return whether the current token starts a new paragraph
240         bool isParagraph();
241         /// skips spaces (and comments if \p skip_comments is true)
242         /// \return whether whitespace was skipped (not comments)
243         bool skip_spaces(bool skip_comments = false);
244         /// puts back spaces (and comments if \p skip_comments is true)
245         void unskip_spaces(bool skip_comments = false);
246         ///
247         void lex(std::string const & s);
248         ///
249         bool good();
250         ///
251         std::string verbatim_item();
252         ///
253         std::string verbatimOption();
254         /// resets the parser to initial state
255         void reset();
256         ///
257         void setCatCode(char c, CatCode cat);
258         ///
259         CatCode getCatCode(char c) const;
260
261 private:
262         ///
263         int lineno_;
264         ///
265         std::vector<Token> tokens_;
266         ///
267         unsigned pos_;
268         ///
269         std::vector<unsigned> positions_;
270         ///
271         idocstringstream * iss_;
272         ///
273         idocstream & is_;
274         /// latex name of the current encoding
275         std::string encoding_latex_;
276 };
277
278
279
280 } // namespace lyx
281
282 #endif