]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/Parser.h
Implement deparsing of tokens
[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 enum cat_type {
50         NORMAL_CATCODES,
51         VERBATIM_CATCODES,
52         UNDECIDED_CATCODES
53 };
54
55
56 enum {
57         FLAG_BRACE_LAST = 1 << 1,  //  last closing brace ends the parsing
58         FLAG_RIGHT      = 1 << 2,  //  next \\right ends the parsing process
59         FLAG_END        = 1 << 3,  //  next \\end ends the parsing process
60         FLAG_BRACK_LAST = 1 << 4,  //  next closing bracket ends the parsing
61         FLAG_TEXTMODE   = 1 << 5,  //  we are in a box
62         FLAG_ITEM       = 1 << 6,  //  read a (possibly braced token)
63         FLAG_LEAVE      = 1 << 7,  //  leave the loop at the end
64         FLAG_SIMPLE     = 1 << 8,  //  next $ leaves the loop
65         FLAG_EQUATION   = 1 << 9,  //  next \] leaves the loop
66         FLAG_SIMPLE2    = 1 << 10, //  next \) leaves the loop
67         FLAG_OPTION     = 1 << 11, //  read [...] style option
68         FLAG_BRACED     = 1 << 12, //  read {...} style argument
69         FLAG_CELL       = 1 << 13, //  read table cell
70         FLAG_TABBING    = 1 << 14  //  We are inside a tabbing environment
71 };
72
73
74
75 //
76 // Helper class for parsing
77 //
78
79 class Token {
80 public:
81         ///
82         Token() : cs_(), cat_(catIgnore) {}
83         ///
84         Token(docstring const & cs, CatCode cat) : cs_(to_utf8(cs)), cat_(cat) {}
85
86         /// Returns the token as string
87         std::string const & cs() const { return cs_; }
88         /// Returns the catcode of the token
89         CatCode cat() const { return cat_; }
90         /** Get the character of tokens that were constructed from a single
91          * character input or a two character input and cat_ == catEscape.
92          * FIXME: The intended usage is not clear. The Token class in
93          *        ../mathed/MathParser.cpp (which is the anchestor of this
94          *        class) uses a separate char member for this method. I
95          *        believe that the intended usage is to not cover tokens with
96          *        catEscape or catComment, e.g. \code
97          *        return (cs_.empty() || cat_ == catEscape || cat_ == catComment) ? 0 : cs_[0];
98          *        \endcode
99          *        All usages of this method should be checked. gb 2011-01-05
100          */
101         char character() const { return cs_.empty() ? 0 : cs_[0]; }
102         /// Returns the token verbatim
103         std::string asInput() const;
104         /// Is the token an alphanumerical character?
105         bool isAlnumASCII() const;
106
107 private:
108         ///
109         std::string cs_;
110         ///
111         CatCode cat_;
112 };
113
114 std::ostream & operator<<(std::ostream & os, Token const & t);
115
116 #ifdef FILEDEBUG
117 extern void debugToken(std::ostream & os, Token const & t, unsigned int flags);
118 #endif
119
120 // A docstream version that supports putback even when not buffered
121 class iparserdocstream
122 {
123 public:
124         iparserdocstream(idocstream & is) : is_(is) {};
125
126         operator bool() const { return is_; };
127
128         idocstream & docstream() { return is_; };
129
130         void putback(char_type c) { s_ += c; };
131
132         iparserdocstream & get(char_type &c)
133         {
134                 if (s_.empty())
135                         is_.get(c);
136                 else {
137                         c = s_[0];
138                         s_.erase(0,1);
139                 }
140                 return *this;
141         };
142 private:
143         ///
144         idocstream & is_;
145         ///
146         docstring s_;
147 };
148
149
150 /*!
151  * Actual parser class
152  *
153  * The parser parses every character of the inputstream into a token
154  * and classifies the token.
155  * The following transformations are done:
156  * - Consecutive spaces are combined into one single token with CatCode catSpace
157  * - Consecutive newlines are combined into one single token with CatCode catNewline
158  * - Comments and %\n combinations are parsed into one token with CatCode catComment
159  */
160
161 class Parser {
162         /// noncopyable
163         Parser(Parser const & p);
164         Parser & operator=(Parser const & p);
165 public:
166         ///
167         Parser(idocstream & is);
168         ///
169         Parser(std::string const & s);
170         ///
171         ~Parser();
172
173         /** forget already parsed next tokens and put the
174          * corresponding characters into the input stream for
175          * re-reading. Useful when changing catcodes. */
176         void deparse();
177
178         ///
179         CatCode catcode(char_type c) const;
180         ///
181         void setCatcode(char c, CatCode cat);
182         /// set parser to normal or verbatim mode
183         void setCatcodes(cat_type t);
184
185         /// change the iconv encoding of the input stream
186         /// according to the latex encoding and package
187         void setEncoding(std::string const & encoding, int const & package);
188         /// change the iconv encoding of the input stream
189         void setEncoding(std::string const & encoding);
190         /// get the current iconv encoding of the input stream
191         std::string getEncoding() const { return encoding_iconv_; }
192
193         ///
194         int lineno() const { return lineno_; }
195         ///
196         void putback();
197         /// store current position
198         void pushPosition();
199         /// restore previous position
200         void popPosition();
201         /// dump contents to screen
202         void dump() const;
203
204         /// Does an optional argument follow after the current token?
205         bool hasOpt();
206         ///
207         typedef std::pair<bool, std::string> Arg;
208         /*!
209          * Get an argument enclosed by \p left and \p right.
210          * If \p allow_escaping is true, a right delimiter escaped by a
211          * backslash does not count as delimiter, but is included in the
212          * argument.
213          * \returns wether an argument was found in \p Arg.first and the
214          * argument in \p Arg.second. \see getArg().
215          */
216         Arg getFullArg(char left, char right, bool allow_escaping = true);
217         /*!
218          * Get an argument enclosed by \p left and \p right.
219          * If \p allow_escaping is true, a right delimiter escaped by a
220          * backslash does not count as delimiter, but is included in the
221          * argument.
222          * \returns the argument (without \p left and \p right) or the empty
223          * string if the next non-space token is not \p left. Use
224          * getFullArg() if you need to know wether there was an empty
225          * argument or no argument at all.
226          */
227         std::string getArg(char left, char right, bool allow_escaping = true);
228         /*!
229          * Like getOpt(), but distinguishes between a missing argument ""
230          * and an empty argument "[]".
231          */
232         std::string getFullOpt(bool keepws = false);
233         /*!
234          * \returns getArg('[', ']') including the brackets or the
235          * empty string if there is no such argument.
236          * No whitespace is eaten if \p keepws is true and no optional
237          * argument exists. This is important if an optional argument is
238          * parsed that would go after a command in ERT: In this case the
239          * whitespace is needed to separate the ERT from the subsequent
240          * word. Without it, the ERT and the next word would be concatenated
241          * during .tex export, thus creating an invalid command.
242          */
243         std::string getOpt(bool keepws = false);
244         /*!
245          * \returns getFullArg('(', ')') including the parentheses or the
246          * empty string if there is no such argument.
247          */
248         std::string getFullParentheseArg();
249         /*!
250          * \returns the contents of the environment \p name.
251          * <tt>\begin{name}</tt> must be parsed already, <tt>\end{name}</tt>
252          * is parsed but not returned. This parses nested environments properly.
253          */
254         std::string const ertEnvironment(std::string const & name);
255         /*
256          * The same as ertEnvironment(std::string const & name) but
257          * \begin and \end commands inside the name environment are not parsed.
258          * This function is designed to parse verbatim environments.
259          */
260         std::string const plainEnvironment(std::string const & name);
261         /*
262          * Basically the same as plainEnvironment(std::string const & name) but
263          * instead of \begin and \end commands the parsing is started/stopped
264          * at given characters.
265          * This function is designed to parse verbatim commands.
266          */
267         std::string const plainCommand(char left, char right, std::string const & name);
268         /*
269          * Basically the same as plainEnvironment() but the parsing is
270          * stopped at string \p end_string. Contrary to the other
271          * methods, this uses proper catcode setting. This function is
272          * designed to parse verbatim environments and command. The
273          * intention is to eventually replace all of its siblings.
274          */
275         std::string const verbatimStuff(std::string const & end_string);
276         /*
277          * \returns the contents of the environment \p name.
278          * <tt>\begin{name}</tt> must be parsed already,
279          * <tt>\end{name}</tt> is parsed but not returned. The string
280          * is parsed with proper verbatim catcodes and one newline is
281          * removed from head and tail of the string if applicable.
282          */
283         std::string const verbatimEnvironment(std::string const & end_string);
284         ///
285         std::string verbatim_item();
286         ///
287         std::string verbatimOption();
288         /*!
289          * Returns the character of the current token and increments
290          * the token position.
291          */
292         char getChar();
293         ///
294         void error(std::string const & msg);
295         /// The previous token.
296         Token const prev_token() const;
297         /// The current token.
298         Token const curr_token() const;
299         /// The next token.
300         Token const next_token();
301         /// The next but one token.
302         Token const next_next_token();
303         /// Make the next token current and return that.
304         Token const get_token();
305         /// \return whether the current token starts a new paragraph
306         bool isParagraph();
307         /// skips spaces (and comments if \p skip_comments is true)
308         /// \return whether whitespace was skipped (not comments)
309         bool skip_spaces(bool skip_comments = false);
310         /// puts back spaces (and comments if \p skip_comments is true)
311         void unskip_spaces(bool skip_comments = false);
312         ///
313         bool good();
314         /// resets the parser to initial state
315         void reset();
316
317 private:
318         /// Setup catcode table
319         void catInit();
320         /// Parses one token from \p is
321         void tokenize_one();
322         ///
323         void push_back(Token const & t);
324         ///
325         int lineno_;
326         ///
327         std::vector<Token> tokens_;
328         ///
329         size_t pos_;
330         ///
331         std::vector<unsigned> positions_;
332         ///
333         idocstringstream * iss_;
334         ///
335         iparserdocstream is_;
336         /// iconv name of the current encoding
337         std::string encoding_iconv_;
338         ///
339         CatCode theCatcode_[256];
340         //
341         cat_type theCatcodesType_;
342         //
343         cat_type curr_cat_;
344 };
345
346
347
348 } // namespace lyx
349
350 #endif