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