2 * \file tex2lyx/text.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
21 #include "FloatList.h"
22 #include "LaTeXPackages.h"
27 #include "insets/ExternalTemplate.h"
29 #include "support/lassert.h"
30 #include "support/convert.h"
31 #include "support/FileName.h"
32 #include "support/filetools.h"
33 #include "support/lstrings.h"
34 #include "support/lyxtime.h"
43 using namespace lyx::support;
48 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
49 Context const & context, InsetLayout const * layout)
51 bool const forcePlainLayout =
52 layout ? layout->forcePlainLayout() : false;
53 Context newcontext(true, context.textclass);
55 newcontext.layout = &context.textclass.plainLayout();
57 newcontext.font = context.font;
58 parse_text(p, os, flags, outer, newcontext);
59 newcontext.check_end_layout(os);
65 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
66 Context const & context, string const & name)
68 InsetLayout const * layout = 0;
69 DocumentClass::InsetLayouts::const_iterator it =
70 context.textclass.insetLayouts().find(from_ascii(name));
71 if (it != context.textclass.insetLayouts().end())
72 layout = &(it->second);
73 parse_text_in_inset(p, os, flags, outer, context, layout);
76 /// parses a paragraph snippet, useful for example for \\emph{...}
77 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
80 Context newcontext(context);
81 // Don't inherit the paragraph-level extra stuff
82 newcontext.par_extra_stuff.clear();
83 parse_text(p, os, flags, outer, newcontext);
84 // Make sure that we don't create invalid .lyx files
85 context.need_layout = newcontext.need_layout;
86 context.need_end_layout = newcontext.need_end_layout;
91 * Thin wrapper around parse_text_snippet() using a string.
93 * We completely ignore \c context.need_layout and \c context.need_end_layout,
94 * because our return value is not used directly (otherwise the stream version
95 * of parse_text_snippet() could be used). That means that the caller needs
96 * to do layout management manually.
97 * This is intended to parse text that does not create any layout changes.
99 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
102 Context newcontext(context);
103 newcontext.need_layout = false;
104 newcontext.need_end_layout = false;
105 newcontext.new_layout_allowed = false;
106 // Avoid warning by Context::~Context()
107 newcontext.par_extra_stuff.clear();
109 parse_text_snippet(p, os, flags, outer, newcontext);
114 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
115 "vpageref", "prettyref", "eqref", 0 };
117 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
118 "vpageref", "formatted", "eqref", 0 };
121 * supported CJK encodings
123 const char * const supported_CJK_encodings[] = {
124 "EUC-JP", "KS", "GB", "UTF8", 0};
127 * the same as supported_CJK_encodings with their corresponding LyX language name
128 * please keep this in sync with supported_CJK_encodings line by line!
130 const char * const coded_supported_CJK_encodings[] = {
131 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional", 0};
133 string CJK2lyx(string const & encoding)
135 char const * const * where = is_known(encoding, supported_CJK_encodings);
137 return coded_supported_CJK_encodings[where - supported_CJK_encodings];
143 * The starred forms are also known except for "citefullauthor",
144 * "citeyear" and "citeyearpar".
146 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
147 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
148 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
152 * No starred form other than "cite*" known.
154 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
155 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
156 // jurabib commands not (yet) supported by LyX:
158 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
159 // "footciteauthor", "footciteyear", "footciteyearpar",
160 "citefield", "citetitle", 0 };
162 /// LaTeX names for quotes
163 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
164 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
165 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
166 "guilsinglleft", "frq", "guilsinglright", 0};
168 /// the same as known_quotes with .lyx names
169 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
170 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
171 "gld", "grd", "gls", "ers", "fls",
172 "fls", "frs", "frs", 0};
174 /// LaTeX names for font sizes
175 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
176 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
178 /// the same as known_sizes with .lyx names
179 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
180 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
182 /// LaTeX 2.09 names for font families
183 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
185 /// LaTeX names for font families
186 char const * const known_font_families[] = { "rmfamily", "sffamily",
189 /// LaTeX names for font family changing commands
190 char const * const known_text_font_families[] = { "textrm", "textsf",
193 /// The same as known_old_font_families, known_font_families and
194 /// known_text_font_families with .lyx names
195 char const * const known_coded_font_families[] = { "roman", "sans",
198 /// LaTeX 2.09 names for font series
199 char const * const known_old_font_series[] = { "bf", 0};
201 /// LaTeX names for font series
202 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
204 /// LaTeX names for font series changing commands
205 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
207 /// The same as known_old_font_series, known_font_series and
208 /// known_text_font_series with .lyx names
209 char const * const known_coded_font_series[] = { "bold", "medium", 0};
211 /// LaTeX 2.09 names for font shapes
212 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
214 /// LaTeX names for font shapes
215 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
218 /// LaTeX names for font shape changing commands
219 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
222 /// The same as known_old_font_shapes, known_font_shapes and
223 /// known_text_font_shapes with .lyx names
224 char const * const known_coded_font_shapes[] = { "italic", "slanted",
225 "smallcaps", "up", 0};
227 /// Known special characters which need skip_spaces_braces() afterwards
228 char const * const known_special_chars[] = {"ldots", "lyxarrow",
229 "textcompwordmark", "slash", 0};
231 /// the same as known_special_chars with .lyx names
232 char const * const known_coded_special_chars[] = {"ldots{}", "menuseparator",
233 "textcompwordmark{}", "slash{}", 0};
236 * Graphics file extensions known by the dvips driver of the graphics package.
237 * These extensions are used to complete the filename of an included
238 * graphics file if it does not contain an extension.
239 * The order must be the same that latex uses to find a file, because we
240 * will use the first extension that matches.
241 * This is only an approximation for the common cases. If we would want to
242 * do it right in all cases, we would need to know which graphics driver is
243 * used and know the extensions of every driver of the graphics package.
245 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
246 "ps.gz", "eps.Z", "ps.Z", 0};
249 * Graphics file extensions known by the pdftex driver of the graphics package.
250 * \sa known_dvips_graphics_formats
252 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
256 * Known file extensions for TeX files as used by \\include.
258 char const * const known_tex_extensions[] = {"tex", 0};
260 /// spaces known by InsetSpace
261 char const * const known_spaces[] = { " ", "space", ",",
262 "thinspace", "quad", "qquad", "enspace", "enskip",
263 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
264 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
265 "upbracefill", "downbracefill", 0};
267 /// the same as known_spaces with .lyx names
268 char const * const known_coded_spaces[] = { "space{}", "space{}",
269 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
270 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
271 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
272 "upbracefill{}", "downbracefill{}", 0};
274 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
275 /// them in ERT. "LaTeXe" must come before "LaTeX"!
276 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
277 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
278 int const known_phrase_lengths[] = {3, 5, 7, 0};
280 // string to store the float type to be able to determine the type of subfloats
281 string float_type = "";
284 /// splits "x=z, y=b" into a map and an ordered keyword vector
285 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
290 keys.resize(v.size());
291 for (size_t i = 0; i < v.size(); ++i) {
292 size_t const pos = v[i].find('=');
293 string const index = trimSpaceAndEol(v[i].substr(0, pos));
294 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
302 * Split a LaTeX length into value and unit.
303 * The latter can be a real unit like "pt", or a latex length variable
304 * like "\textwidth". The unit may contain additional stuff like glue
305 * lengths, but we don't care, because such lengths are ERT anyway.
306 * \returns true if \p value and \p unit are valid.
308 bool splitLatexLength(string const & len, string & value, string & unit)
312 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
313 //'4,5' is a valid LaTeX length number. Change it to '4.5'
314 string const length = subst(len, ',', '.');
315 if (i == string::npos)
318 if (len[0] == '\\') {
319 // We had something like \textwidth without a factor
325 value = trimSpaceAndEol(string(length, 0, i));
329 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
330 if (contains(len, '\\'))
331 unit = trimSpaceAndEol(string(len, i));
333 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
338 /// A simple function to translate a latex length to something LyX can
339 /// understand. Not perfect, but rather best-effort.
340 bool translate_len(string const & length, string & valstring, string & unit)
342 if (!splitLatexLength(length, valstring, unit))
344 // LyX uses percent values
346 istringstream iss(valstring);
351 string const percentval = oss.str();
353 if (unit.empty() || unit[0] != '\\')
355 string::size_type const i = unit.find(' ');
356 string const endlen = (i == string::npos) ? string() : string(unit, i);
357 if (unit == "\\textwidth") {
358 valstring = percentval;
359 unit = "text%" + endlen;
360 } else if (unit == "\\columnwidth") {
361 valstring = percentval;
362 unit = "col%" + endlen;
363 } else if (unit == "\\paperwidth") {
364 valstring = percentval;
365 unit = "page%" + endlen;
366 } else if (unit == "\\linewidth") {
367 valstring = percentval;
368 unit = "line%" + endlen;
369 } else if (unit == "\\paperheight") {
370 valstring = percentval;
371 unit = "pheight%" + endlen;
372 } else if (unit == "\\textheight") {
373 valstring = percentval;
374 unit = "theight%" + endlen;
382 string translate_len(string const & length)
386 if (translate_len(length, value, unit))
388 // If the input is invalid, return what we have.
396 * Translates a LaTeX length into \p value, \p unit and
397 * \p special parts suitable for a box inset.
398 * The difference from translate_len() is that a box inset knows about
399 * some special "units" that are stored in \p special.
401 void translate_box_len(string const & length, string & value, string & unit, string & special)
403 if (translate_len(length, value, unit)) {
404 if (unit == "\\height" || unit == "\\depth" ||
405 unit == "\\totalheight" || unit == "\\width") {
406 special = unit.substr(1);
407 // The unit is not used, but LyX requires a dummy setting
420 * Find a file with basename \p name in path \p path and an extension
423 string find_file(string const & name, string const & path,
424 char const * const * extensions)
426 for (char const * const * what = extensions; *what; ++what) {
427 string const trial = addExtension(name, *what);
428 if (makeAbsPath(trial, path).exists())
435 void begin_inset(ostream & os, string const & name)
437 os << "\n\\begin_inset " << name;
441 void begin_command_inset(ostream & os, string const & name,
442 string const & latexname)
444 begin_inset(os, "CommandInset ");
445 os << name << "\nLatexCommand " << latexname << '\n';
449 void end_inset(ostream & os)
451 os << "\n\\end_inset\n\n";
455 bool skip_braces(Parser & p)
457 if (p.next_token().cat() != catBegin)
460 if (p.next_token().cat() == catEnd) {
469 /// replace LaTeX commands in \p s from the unicodesymbols file with their
471 docstring convert_unicodesymbols(docstring s)
474 for (size_t i = 0; i < s.size();) {
483 docstring parsed = encodings.fromLaTeXCommand(s,
484 Encodings::TEXT_CMD, termination, rem, &req);
485 set<string>::const_iterator it = req.begin();
486 set<string>::const_iterator en = req.end();
487 for (; it != en; ++it)
488 preamble.registerAutomaticallyLoadedPackage(*it);
491 if (s.empty() || s[0] != '\\')
500 /// try to convert \p s to a valid InsetCommand argument
501 string convert_command_inset_arg(string s)
504 // since we don't know the input encoding we can't use from_utf8
505 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
506 // LyX cannot handle newlines in a latex command
507 return subst(s, "\n", " ");
511 void handle_backslash(ostream & os, string const & s)
513 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
515 os << "\n\\backslash\n";
522 void handle_ert(ostream & os, string const & s, Context & context)
524 // We must have a valid layout before outputting the ERT inset.
525 context.check_layout(os);
526 Context newcontext(true, context.textclass);
527 begin_inset(os, "ERT");
528 os << "\nstatus collapsed\n";
529 newcontext.check_layout(os);
530 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
532 os << "\n\\backslash\n";
533 else if (*it == '\n') {
534 newcontext.new_paragraph(os);
535 newcontext.check_layout(os);
539 newcontext.check_end_layout(os);
544 void handle_comment(ostream & os, string const & s, Context & context)
546 // TODO: Handle this better
547 Context newcontext(true, context.textclass);
548 begin_inset(os, "ERT");
549 os << "\nstatus collapsed\n";
550 newcontext.check_layout(os);
551 handle_backslash(os, s);
552 // make sure that our comment is the last thing on the line
553 newcontext.new_paragraph(os);
554 newcontext.check_layout(os);
555 newcontext.check_end_layout(os);
560 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
562 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
565 if (checkModule(name, command))
566 return findLayoutWithoutModule(textclass, name, command);
571 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
573 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
576 if (checkModule(name, command))
577 return findInsetLayoutWithoutModule(textclass, name, command);
582 void eat_whitespace(Parser &, ostream &, Context &, bool);
586 * Skips whitespace and braces.
587 * This should be called after a command has been parsed that is not put into
588 * ERT, and where LyX adds "{}" if needed.
590 void skip_spaces_braces(Parser & p, bool keepws = false)
592 /* The following four examples produce the same typeset output and
593 should be handled by this function:
601 // Unfortunately we need to skip comments, too.
602 // We can't use eat_whitespace since writing them after the {}
603 // results in different output in some cases.
604 bool const skipped_spaces = p.skip_spaces(true);
605 bool const skipped_braces = skip_braces(p);
606 if (keepws && skipped_spaces && !skipped_braces)
607 // put back the space (it is better handled by check_space)
608 p.unskip_spaces(true);
612 void output_command_layout(ostream & os, Parser & p, bool outer,
613 Context & parent_context,
614 Layout const * newlayout)
616 TeXFont const oldFont = parent_context.font;
617 // save the current font size
618 string const size = oldFont.size;
619 // reset the font size to default, because the font size switches
620 // don't affect section headings and the like
621 parent_context.font.size = Context::normalfont.size;
622 // we only need to write the font change if we have an open layout
623 if (!parent_context.atParagraphStart())
624 output_font_change(os, oldFont, parent_context.font);
625 parent_context.check_end_layout(os);
626 Context context(true, parent_context.textclass, newlayout,
627 parent_context.layout, parent_context.font);
628 if (parent_context.deeper_paragraph) {
629 // We are beginning a nested environment after a
630 // deeper paragraph inside the outer list environment.
631 // Therefore we don't need to output a "begin deeper".
632 context.need_end_deeper = true;
634 context.check_deeper(os);
635 context.check_layout(os);
636 unsigned int optargs = 0;
637 while (optargs < context.layout->optargs) {
638 eat_whitespace(p, os, context, false);
639 if (p.next_token().cat() == catEscape ||
640 p.next_token().character() != '[')
642 p.get_token(); // eat '['
643 begin_inset(os, "Argument\n");
644 os << "status collapsed\n\n";
645 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
647 eat_whitespace(p, os, context, false);
650 unsigned int reqargs = 0;
651 while (reqargs < context.layout->reqargs) {
652 eat_whitespace(p, os, context, false);
653 if (p.next_token().cat() != catBegin)
655 p.get_token(); // eat '{'
656 begin_inset(os, "Argument\n");
657 os << "status collapsed\n\n";
658 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
660 eat_whitespace(p, os, context, false);
663 parse_text(p, os, FLAG_ITEM, outer, context);
664 context.check_end_layout(os);
665 if (parent_context.deeper_paragraph) {
666 // We must suppress the "end deeper" because we
667 // suppressed the "begin deeper" above.
668 context.need_end_deeper = false;
670 context.check_end_deeper(os);
671 // We don't need really a new paragraph, but
672 // we must make sure that the next item gets a \begin_layout.
673 parent_context.new_paragraph(os);
674 // Set the font size to the original value. No need to output it here
675 // (Context::begin_layout() will do that if needed)
676 parent_context.font.size = size;
681 * Output a space if necessary.
682 * This function gets called for every whitespace token.
684 * We have three cases here:
685 * 1. A space must be suppressed. Example: The lyxcode case below
686 * 2. A space may be suppressed. Example: Spaces before "\par"
687 * 3. A space must not be suppressed. Example: A space between two words
689 * We currently handle only 1. and 3 and from 2. only the case of
690 * spaces before newlines as a side effect.
692 * 2. could be used to suppress as many spaces as possible. This has two effects:
693 * - Reimporting LyX generated LaTeX files changes almost no whitespace
694 * - Superflous whitespace from non LyX generated LaTeX files is removed.
695 * The drawback is that the logic inside the function becomes
696 * complicated, and that is the reason why it is not implemented.
698 void check_space(Parser & p, ostream & os, Context & context)
700 Token const next = p.next_token();
701 Token const curr = p.curr_token();
702 // A space before a single newline and vice versa must be ignored
703 // LyX emits a newline before \end{lyxcode}.
704 // This newline must be ignored,
705 // otherwise LyX will add an additional protected space.
706 if (next.cat() == catSpace ||
707 next.cat() == catNewline ||
708 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
711 context.check_layout(os);
717 * Parse all arguments of \p command
719 void parse_arguments(string const & command,
720 vector<ArgumentType> const & template_arguments,
721 Parser & p, ostream & os, bool outer, Context & context)
723 string ert = command;
724 size_t no_arguments = template_arguments.size();
725 for (size_t i = 0; i < no_arguments; ++i) {
726 switch (template_arguments[i]) {
729 // This argument contains regular LaTeX
730 handle_ert(os, ert + '{', context);
731 eat_whitespace(p, os, context, false);
732 if (template_arguments[i] == required)
733 parse_text(p, os, FLAG_ITEM, outer, context);
735 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
739 // This argument consists only of a single item.
740 // The presence of '{' or not must be preserved.
742 if (p.next_token().cat() == catBegin)
743 ert += '{' + p.verbatim_item() + '}';
745 ert += p.verbatim_item();
749 // This argument may contain special characters
750 ert += '{' + p.verbatim_item() + '}';
754 // true because we must not eat whitespace
755 // if an optional arg follows we must not strip the
756 // brackets from this one
757 if (i < no_arguments - 1 &&
758 template_arguments[i+1] == optional)
759 ert += p.getFullOpt(true);
761 ert += p.getOpt(true);
765 handle_ert(os, ert, context);
770 * Check whether \p command is a known command. If yes,
771 * handle the command with all arguments.
772 * \return true if the command was parsed, false otherwise.
774 bool parse_command(string const & command, Parser & p, ostream & os,
775 bool outer, Context & context)
777 if (known_commands.find(command) != known_commands.end()) {
778 parse_arguments(command, known_commands[command], p, os,
786 /// Parses a minipage or parbox
787 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
788 unsigned inner_flags, bool outer, Context & parent_context,
789 string const & outer_type, string const & special,
790 string const & inner_type)
794 string hor_pos = "c";
795 // We need to set the height to the LaTeX default of 1\\totalheight
796 // for the case when no height argument is given
797 string height_value = "1";
798 string height_unit = "in";
799 string height_special = "totalheight";
804 string width_special = "none";
805 if (!inner_type.empty() && p.hasOpt()) {
806 if (inner_type != "makebox")
807 position = p.getArg('[', ']');
809 latex_width = p.getArg('[', ']');
810 translate_box_len(latex_width, width_value, width_unit, width_special);
813 if (position != "t" && position != "c" && position != "b") {
814 cerr << "invalid position " << position << " for "
815 << inner_type << endl;
819 if (inner_type != "makebox") {
820 latex_height = p.getArg('[', ']');
821 translate_box_len(latex_height, height_value, height_unit, height_special);
823 hor_pos = p.getArg('[', ']');
826 inner_pos = p.getArg('[', ']');
827 if (inner_pos != "c" && inner_pos != "t" &&
828 inner_pos != "b" && inner_pos != "s") {
829 cerr << "invalid inner_pos "
830 << inner_pos << " for "
831 << inner_type << endl;
832 inner_pos = position;
837 if (inner_type.empty()) {
838 if (special.empty() && outer_type != "framebox")
839 latex_width = "1\\columnwidth";
842 latex_width = p2.getArg('[', ']');
843 string const opt = p2.getArg('[', ']');
846 if (hor_pos != "l" && hor_pos != "c" &&
848 cerr << "invalid hor_pos " << hor_pos
849 << " for " << outer_type << endl;
854 } else if (inner_type != "makebox")
855 latex_width = p.verbatim_item();
856 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
857 // as this is LyX's standard for such cases (except for makebox)
858 // \framebox is more special and handled below
859 if (latex_width.empty() && inner_type != "makebox"
860 && outer_type != "framebox")
861 latex_width = "1\\columnwidth";
863 translate_len(latex_width, width_value, width_unit);
865 bool shadedparbox = false;
866 if (inner_type == "shaded") {
867 eat_whitespace(p, os, parent_context, false);
868 if (outer_type == "parbox") {
870 if (p.next_token().cat() == catBegin)
872 eat_whitespace(p, os, parent_context, false);
878 // If we already read the inner box we have to push the inner env
879 if (!outer_type.empty() && !inner_type.empty() &&
880 (inner_flags & FLAG_END))
881 active_environments.push_back(inner_type);
882 // LyX can't handle length variables
883 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
884 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
885 // Look whether there is some content after the end of the
886 // inner box, but before the end of the outer box.
887 // If yes, we need to output ERT.
889 if (inner_flags & FLAG_END)
890 p.verbatimEnvironment(inner_type);
894 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
895 if ((outer_env && p.next_token().asInput() != "\\end") ||
896 (!outer_env && p.next_token().cat() != catEnd)) {
897 // something is between the end of the inner box and
898 // the end of the outer box, so we need to use ERT.
903 // if only \makebox{content} was used we can set its width to 1\width
904 // because this identic and also identic to \mbox
905 // this doesn't work for \framebox{content}, thus we have to use ERT for this
906 if (latex_width.empty() && inner_type == "makebox") {
909 width_special = "width";
910 } else if (latex_width.empty() && outer_type == "framebox") {
915 if (!outer_type.empty()) {
916 if (outer_flags & FLAG_END)
917 ss << "\\begin{" << outer_type << '}';
919 ss << '\\' << outer_type << '{';
920 if (!special.empty())
924 if (!inner_type.empty()) {
925 if (inner_type != "shaded") {
926 if (inner_flags & FLAG_END)
927 ss << "\\begin{" << inner_type << '}';
929 ss << '\\' << inner_type;
931 if (!position.empty())
932 ss << '[' << position << ']';
933 if (!latex_height.empty())
934 ss << '[' << latex_height << ']';
935 if (!inner_pos.empty())
936 ss << '[' << inner_pos << ']';
937 ss << '{' << latex_width << '}';
938 if (!(inner_flags & FLAG_END))
941 if (inner_type == "shaded")
942 ss << "\\begin{shaded}";
943 handle_ert(os, ss.str(), parent_context);
944 if (!inner_type.empty()) {
945 parse_text(p, os, inner_flags, outer, parent_context);
946 if (inner_flags & FLAG_END)
947 handle_ert(os, "\\end{" + inner_type + '}',
950 handle_ert(os, "}", parent_context);
952 if (!outer_type.empty()) {
953 // If we already read the inner box we have to pop
955 if (!inner_type.empty() && (inner_flags & FLAG_END))
956 active_environments.pop_back();
958 // Ensure that the end of the outer box is parsed correctly:
959 // The opening brace has been eaten by parse_outer_box()
960 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
961 outer_flags &= ~FLAG_ITEM;
962 outer_flags |= FLAG_BRACE_LAST;
964 parse_text(p, os, outer_flags, outer, parent_context);
965 if (outer_flags & FLAG_END)
966 handle_ert(os, "\\end{" + outer_type + '}',
968 else if (inner_type.empty() && outer_type == "framebox")
969 // in this case it is already closed later
972 handle_ert(os, "}", parent_context);
975 // LyX does not like empty positions, so we have
976 // to set them to the LaTeX default values here.
977 if (position.empty())
979 if (inner_pos.empty())
980 inner_pos = position;
981 parent_context.check_layout(os);
982 begin_inset(os, "Box ");
983 if (outer_type == "framed")
985 else if (outer_type == "framebox")
987 else if (outer_type == "shadowbox")
989 else if ((outer_type == "shaded" && inner_type.empty()) ||
990 (outer_type == "minipage" && inner_type == "shaded") ||
991 (outer_type == "parbox" && inner_type == "shaded")) {
993 preamble.registerAutomaticallyLoadedPackage("color");
994 } else if (outer_type == "doublebox")
996 else if (outer_type.empty())
999 os << outer_type << '\n';
1000 os << "position \"" << position << "\"\n";
1001 os << "hor_pos \"" << hor_pos << "\"\n";
1002 os << "has_inner_box " << !inner_type.empty() << "\n";
1003 os << "inner_pos \"" << inner_pos << "\"\n";
1004 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1006 os << "use_makebox " << (inner_type == "makebox") << '\n';
1007 os << "width \"" << width_value << width_unit << "\"\n";
1008 os << "special \"" << width_special << "\"\n";
1009 os << "height \"" << height_value << height_unit << "\"\n";
1010 os << "height_special \"" << height_special << "\"\n";
1011 os << "status open\n\n";
1013 // Unfortunately we can't use parse_text_in_inset:
1014 // InsetBox::forcePlainLayout() is hard coded and does not
1015 // use the inset layout. Apart from that do we call parse_text
1016 // up to two times, but need only one check_end_layout.
1017 bool const forcePlainLayout =
1018 (!inner_type.empty() || inner_type == "makebox") &&
1019 outer_type != "shaded" && outer_type != "framed";
1020 Context context(true, parent_context.textclass);
1021 if (forcePlainLayout)
1022 context.layout = &context.textclass.plainLayout();
1024 context.font = parent_context.font;
1026 // If we have no inner box the contents will be read with the outer box
1027 if (!inner_type.empty())
1028 parse_text(p, os, inner_flags, outer, context);
1030 // Ensure that the end of the outer box is parsed correctly:
1031 // The opening brace has been eaten by parse_outer_box()
1032 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1033 outer_flags &= ~FLAG_ITEM;
1034 outer_flags |= FLAG_BRACE_LAST;
1037 // Find end of outer box, output contents if inner_type is
1038 // empty and output possible comments
1039 if (!outer_type.empty()) {
1040 // If we already read the inner box we have to pop
1042 if (!inner_type.empty() && (inner_flags & FLAG_END))
1043 active_environments.pop_back();
1044 // This does not output anything but comments if
1045 // inner_type is not empty (see use_ert)
1046 parse_text(p, os, outer_flags, outer, context);
1049 context.check_end_layout(os);
1051 #ifdef PRESERVE_LAYOUT
1052 // LyX puts a % after the end of the minipage
1053 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1055 //handle_comment(os, "%dummy", parent_context);
1058 parent_context.new_paragraph(os);
1060 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1061 //handle_comment(os, "%dummy", parent_context);
1064 // We add a protected space if something real follows
1065 if (p.good() && p.next_token().cat() != catComment) {
1066 begin_inset(os, "space ~\n");
1075 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1076 Context & parent_context, string const & outer_type,
1077 string const & special)
1079 eat_whitespace(p, os, parent_context, false);
1080 if (flags & FLAG_ITEM) {
1082 if (p.next_token().cat() == catBegin)
1085 cerr << "Warning: Ignoring missing '{' after \\"
1086 << outer_type << '.' << endl;
1087 eat_whitespace(p, os, parent_context, false);
1090 unsigned int inner_flags = 0;
1092 if (outer_type == "minipage" || outer_type == "parbox") {
1093 p.skip_spaces(true);
1094 while (p.hasOpt()) {
1096 p.skip_spaces(true);
1099 p.skip_spaces(true);
1100 if (outer_type == "parbox") {
1102 if (p.next_token().cat() == catBegin)
1104 p.skip_spaces(true);
1107 if (outer_type == "shaded") {
1108 // These boxes never have an inner box
1110 } else if (p.next_token().asInput() == "\\parbox") {
1111 inner = p.get_token().cs();
1112 inner_flags = FLAG_ITEM;
1113 } else if (p.next_token().asInput() == "\\begin") {
1114 // Is this a minipage or shaded box?
1117 inner = p.getArg('{', '}');
1119 if (inner == "minipage" || inner == "shaded")
1120 inner_flags = FLAG_END;
1125 if (inner_flags == FLAG_END) {
1126 if (inner != "shaded")
1130 eat_whitespace(p, os, parent_context, false);
1132 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1133 outer_type, special, inner);
1135 if (inner_flags == FLAG_ITEM) {
1137 eat_whitespace(p, os, parent_context, false);
1139 parse_box(p, os, flags, inner_flags, outer, parent_context,
1140 outer_type, special, inner);
1145 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1147 parent_context.check_layout(os);
1148 begin_inset(os, "listings\n");
1150 string arg = p.verbatimOption();
1151 os << "lstparams " << '"' << arg << '"' << '\n';
1154 os << "inline true\n";
1156 os << "inline false\n";
1157 os << "status collapsed\n";
1158 Context context(true, parent_context.textclass);
1159 context.layout = &parent_context.textclass.plainLayout();
1162 s = p.plainCommand('!', '!', "lstinline");
1163 context.new_paragraph(os);
1164 context.check_layout(os);
1166 s = p.plainEnvironment("lstlisting");
1167 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1169 os << "\n\\backslash\n";
1170 else if (*it == '\n') {
1171 // avoid adding an empty paragraph at the end
1173 context.new_paragraph(os);
1174 context.check_layout(os);
1179 context.check_end_layout(os);
1184 /// parse an unknown environment
1185 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1186 unsigned flags, bool outer,
1187 Context & parent_context)
1189 if (name == "tabbing")
1190 // We need to remember that we have to handle '\=' specially
1191 flags |= FLAG_TABBING;
1193 // We need to translate font changes and paragraphs inside the
1194 // environment to ERT if we have a non standard font.
1195 // Otherwise things like
1196 // \large\begin{foo}\huge bar\end{foo}
1198 bool const specialfont =
1199 (parent_context.font != parent_context.normalfont);
1200 bool const new_layout_allowed = parent_context.new_layout_allowed;
1202 parent_context.new_layout_allowed = false;
1203 handle_ert(os, "\\begin{" + name + "}", parent_context);
1204 parse_text_snippet(p, os, flags, outer, parent_context);
1205 handle_ert(os, "\\end{" + name + "}", parent_context);
1207 parent_context.new_layout_allowed = new_layout_allowed;
1211 void parse_environment(Parser & p, ostream & os, bool outer,
1212 string & last_env, Context & parent_context)
1214 Layout const * newlayout;
1215 InsetLayout const * newinsetlayout = 0;
1216 string const name = p.getArg('{', '}');
1217 const bool is_starred = suffixIs(name, '*');
1218 string const unstarred_name = rtrim(name, "*");
1219 active_environments.push_back(name);
1221 if (is_math_env(name)) {
1222 parent_context.check_layout(os);
1223 begin_inset(os, "Formula ");
1224 os << "\\begin{" << name << "}";
1225 parse_math(p, os, FLAG_END, MATH_MODE);
1226 os << "\\end{" << name << "}";
1228 if (is_display_math_env(name)) {
1229 // Prevent the conversion of a line break to a space
1230 // (bug 7668). This does not change the output, but
1231 // looks ugly in LyX.
1232 eat_whitespace(p, os, parent_context, false);
1236 else if (is_known(name, preamble.polyglossia_languages)) {
1237 // We must begin a new paragraph if not already done
1238 if (! parent_context.atParagraphStart()) {
1239 parent_context.check_end_layout(os);
1240 parent_context.new_paragraph(os);
1242 // save the language in the context so that it is
1243 // handled by parse_text
1244 parent_context.font.language = preamble.polyglossia2lyx(name);
1245 parse_text(p, os, FLAG_END, outer, parent_context);
1246 // Just in case the environment is empty
1247 parent_context.extra_stuff.erase();
1248 // We must begin a new paragraph to reset the language
1249 parent_context.new_paragraph(os);
1253 else if (unstarred_name == "tabular" || name == "longtable") {
1254 eat_whitespace(p, os, parent_context, false);
1255 string width = "0pt";
1256 if (name == "tabular*") {
1257 width = lyx::translate_len(p.getArg('{', '}'));
1258 eat_whitespace(p, os, parent_context, false);
1260 parent_context.check_layout(os);
1261 begin_inset(os, "Tabular ");
1262 handle_tabular(p, os, name, width, parent_context);
1267 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1268 eat_whitespace(p, os, parent_context, false);
1269 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1270 eat_whitespace(p, os, parent_context, false);
1271 parent_context.check_layout(os);
1272 begin_inset(os, "Float " + unstarred_name + "\n");
1273 // store the float type for subfloats
1274 // subfloats only work with figures and tables
1275 if (unstarred_name == "figure")
1276 float_type = unstarred_name;
1277 else if (unstarred_name == "table")
1278 float_type = unstarred_name;
1282 os << "placement " << opt << '\n';
1283 if (contains(opt, "H"))
1284 preamble.registerAutomaticallyLoadedPackage("float");
1286 Floating const & fl = parent_context.textclass.floats()
1287 .getType(unstarred_name);
1288 if (!fl.floattype().empty() && fl.usesFloatPkg())
1289 preamble.registerAutomaticallyLoadedPackage("float");
1292 os << "wide " << convert<string>(is_starred)
1293 << "\nsideways false"
1294 << "\nstatus open\n\n";
1295 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1297 // We don't need really a new paragraph, but
1298 // we must make sure that the next item gets a \begin_layout.
1299 parent_context.new_paragraph(os);
1301 // the float is parsed thus delete the type
1305 else if (unstarred_name == "sidewaysfigure"
1306 || unstarred_name == "sidewaystable") {
1307 eat_whitespace(p, os, parent_context, false);
1308 parent_context.check_layout(os);
1309 if (unstarred_name == "sidewaysfigure")
1310 begin_inset(os, "Float figure\n");
1312 begin_inset(os, "Float table\n");
1313 os << "wide " << convert<string>(is_starred)
1314 << "\nsideways true"
1315 << "\nstatus open\n\n";
1316 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1318 // We don't need really a new paragraph, but
1319 // we must make sure that the next item gets a \begin_layout.
1320 parent_context.new_paragraph(os);
1322 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1325 else if (name == "wrapfigure" || name == "wraptable") {
1326 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1327 eat_whitespace(p, os, parent_context, false);
1328 parent_context.check_layout(os);
1331 string overhang = "0col%";
1334 lines = p.getArg('[', ']');
1335 string const placement = p.getArg('{', '}');
1337 overhang = p.getArg('[', ']');
1338 string const width = p.getArg('{', '}');
1340 if (name == "wrapfigure")
1341 begin_inset(os, "Wrap figure\n");
1343 begin_inset(os, "Wrap table\n");
1344 os << "lines " << lines
1345 << "\nplacement " << placement
1346 << "\noverhang " << lyx::translate_len(overhang)
1347 << "\nwidth " << lyx::translate_len(width)
1348 << "\nstatus open\n\n";
1349 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1351 // We don't need really a new paragraph, but
1352 // we must make sure that the next item gets a \begin_layout.
1353 parent_context.new_paragraph(os);
1355 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1358 else if (name == "minipage") {
1359 eat_whitespace(p, os, parent_context, false);
1360 // Test whether this is an outer box of a shaded box
1362 // swallow arguments
1363 while (p.hasOpt()) {
1365 p.skip_spaces(true);
1368 p.skip_spaces(true);
1369 Token t = p.get_token();
1370 bool shaded = false;
1371 if (t.asInput() == "\\begin") {
1372 p.skip_spaces(true);
1373 if (p.getArg('{', '}') == "shaded")
1378 parse_outer_box(p, os, FLAG_END, outer,
1379 parent_context, name, "shaded");
1381 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1386 else if (name == "comment") {
1387 eat_whitespace(p, os, parent_context, false);
1388 parent_context.check_layout(os);
1389 begin_inset(os, "Note Comment\n");
1390 os << "status open\n";
1391 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1394 skip_braces(p); // eat {} that might by set by LyX behind comments
1395 preamble.registerAutomaticallyLoadedPackage("verbatim");
1398 else if (name == "verbatim") {
1399 os << "\n\\end_layout\n\n\\begin_layout Verbatim\n";
1400 string const s = p.plainEnvironment("verbatim");
1401 string::const_iterator it2 = s.begin();
1402 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1404 os << "\\backslash ";
1405 else if (*it == '\n') {
1407 // avoid adding an empty paragraph at the end
1408 // FIXME: if there are 2 consecutive spaces at the end ignore it
1409 // because LyX will re-add a \n
1410 // This hack must be removed once bug 8049 is fixed!
1411 if ((it + 1 != et) && (it + 2 != et || *it2 != '\n'))
1412 os << "\n\\end_layout\n\\begin_layout Verbatim\n";
1416 os << "\n\\end_layout\n\n";
1418 // reset to Standard layout
1419 os << "\n\\begin_layout Standard\n";
1422 else if (name == "CJK") {
1423 // the scheme is \begin{CJK}{encoding}{mapping}{text}
1424 // It is impossible to decide if a CJK environment was in its own paragraph or within
1425 // a line. We therefore always assume a paragraph since the latter is a rare case.
1426 eat_whitespace(p, os, parent_context, false);
1427 parent_context.check_end_layout(os);
1428 // store the encoding to be able to reset it
1429 string const encoding_old = p.getEncoding();
1430 string const encoding = p.getArg('{', '}');
1431 // SJIS and BIG5 don't work with LaTeX according to the comment in unicode.cpp
1432 // JIS does not work with LyX's encoding conversion
1433 if (encoding != "SJIS" && encoding != "BIG5" && encoding != "JIS")
1434 p.setEncoding(encoding);
1436 p.setEncoding("utf8");
1437 // LyX doesn't support the second argument so if
1438 // this is used we need to output everything as ERT
1439 string const mapping = p.getArg('{', '}');
1440 if ((!mapping.empty() && mapping != " ")
1441 || (!is_known(encoding, supported_CJK_encodings))) {
1442 parent_context.check_layout(os);
1443 handle_ert(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1445 // we must parse the content as verbatim because e.g. SJIS can contain
1446 // normally invalid characters
1447 string const s = p.plainEnvironment("CJK");
1448 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1450 handle_ert(os, "\\", parent_context);
1451 else if (*it == '$')
1452 handle_ert(os, "$", parent_context);
1457 handle_ert(os, "\\end{" + name + "}",
1460 string const lang = CJK2lyx(encoding);
1461 // store the language because we must reset it at the end
1462 string const lang_old = parent_context.font.language;
1463 parent_context.font.language = lang;
1464 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1465 parent_context.font.language = lang_old;
1466 parent_context.new_paragraph(os);
1468 p.setEncoding(encoding_old);
1472 else if (name == "lyxgreyedout") {
1473 eat_whitespace(p, os, parent_context, false);
1474 parent_context.check_layout(os);
1475 begin_inset(os, "Note Greyedout\n");
1476 os << "status open\n";
1477 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1480 if (!preamble.notefontcolor().empty())
1481 preamble.registerAutomaticallyLoadedPackage("color");
1484 else if (name == "framed" || name == "shaded") {
1485 eat_whitespace(p, os, parent_context, false);
1486 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1490 else if (name == "lstlisting") {
1491 eat_whitespace(p, os, parent_context, false);
1492 // FIXME handle the automatic color package loading
1493 // uwestoehr asks: In what case color is loaded?
1494 parse_listings(p, os, parent_context, false);
1498 else if (!parent_context.new_layout_allowed)
1499 parse_unknown_environment(p, name, os, FLAG_END, outer,
1502 // Alignment and spacing settings
1503 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1504 // therefore are totally broken!
1505 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1506 // they are commands not environments. They are furthermore switches that
1507 // can be ended by another switches, but also by commands like \footnote or
1508 // \parbox. So the only safe way is to leave them untouched.
1509 else if (name == "center" || name == "centering" ||
1510 name == "flushleft" || name == "flushright" ||
1511 name == "singlespace" || name == "onehalfspace" ||
1512 name == "doublespace" || name == "spacing") {
1513 eat_whitespace(p, os, parent_context, false);
1514 // We must begin a new paragraph if not already done
1515 if (! parent_context.atParagraphStart()) {
1516 parent_context.check_end_layout(os);
1517 parent_context.new_paragraph(os);
1519 if (name == "flushleft")
1520 parent_context.add_extra_stuff("\\align left\n");
1521 else if (name == "flushright")
1522 parent_context.add_extra_stuff("\\align right\n");
1523 else if (name == "center" || name == "centering")
1524 parent_context.add_extra_stuff("\\align center\n");
1525 else if (name == "singlespace")
1526 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1527 else if (name == "onehalfspace") {
1528 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1529 preamble.registerAutomaticallyLoadedPackage("setspace");
1530 } else if (name == "doublespace") {
1531 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1532 preamble.registerAutomaticallyLoadedPackage("setspace");
1533 } else if (name == "spacing") {
1534 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1535 preamble.registerAutomaticallyLoadedPackage("setspace");
1537 parse_text(p, os, FLAG_END, outer, parent_context);
1538 // Just in case the environment is empty
1539 parent_context.extra_stuff.erase();
1540 // We must begin a new paragraph to reset the alignment
1541 parent_context.new_paragraph(os);
1545 // The single '=' is meant here.
1546 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1547 eat_whitespace(p, os, parent_context, false);
1548 Context context(true, parent_context.textclass, newlayout,
1549 parent_context.layout, parent_context.font);
1550 if (parent_context.deeper_paragraph) {
1551 // We are beginning a nested environment after a
1552 // deeper paragraph inside the outer list environment.
1553 // Therefore we don't need to output a "begin deeper".
1554 context.need_end_deeper = true;
1556 parent_context.check_end_layout(os);
1557 if (last_env == name) {
1558 // we need to output a separator since LyX would export
1559 // the two environments as one otherwise (bug 5716)
1560 docstring const sep = from_ascii("--Separator--");
1561 TeX2LyXDocClass const & textclass(parent_context.textclass);
1562 if (textclass.hasLayout(sep)) {
1563 Context newcontext(parent_context);
1564 newcontext.layout = &(textclass[sep]);
1565 newcontext.check_layout(os);
1566 newcontext.check_end_layout(os);
1568 parent_context.check_layout(os);
1569 begin_inset(os, "Note Note\n");
1570 os << "status closed\n";
1571 Context newcontext(true, textclass,
1572 &(textclass.defaultLayout()));
1573 newcontext.check_layout(os);
1574 newcontext.check_end_layout(os);
1576 parent_context.check_end_layout(os);
1579 switch (context.layout->latextype) {
1580 case LATEX_LIST_ENVIRONMENT:
1581 context.add_par_extra_stuff("\\labelwidthstring "
1582 + p.verbatim_item() + '\n');
1585 case LATEX_BIB_ENVIRONMENT:
1586 p.verbatim_item(); // swallow next arg
1592 context.check_deeper(os);
1593 // handle known optional and required arguments
1594 // layouts require all optional arguments before the required ones
1595 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1596 // It is impossible to place anything after the environment name,
1597 // but before the first \\item.
1598 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1599 bool need_layout = true;
1600 unsigned int optargs = 0;
1601 while (optargs < context.layout->optargs) {
1602 eat_whitespace(p, os, context, false);
1603 if (p.next_token().cat() == catEscape ||
1604 p.next_token().character() != '[')
1606 p.get_token(); // eat '['
1608 context.check_layout(os);
1609 need_layout = false;
1611 begin_inset(os, "Argument\n");
1612 os << "status collapsed\n\n";
1613 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1615 eat_whitespace(p, os, context, false);
1618 unsigned int reqargs = 0;
1619 while (reqargs < context.layout->reqargs) {
1620 eat_whitespace(p, os, context, false);
1621 if (p.next_token().cat() != catBegin)
1623 p.get_token(); // eat '{'
1625 context.check_layout(os);
1626 need_layout = false;
1628 begin_inset(os, "Argument\n");
1629 os << "status collapsed\n\n";
1630 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1632 eat_whitespace(p, os, context, false);
1636 parse_text(p, os, FLAG_END, outer, context);
1637 context.check_end_layout(os);
1638 if (parent_context.deeper_paragraph) {
1639 // We must suppress the "end deeper" because we
1640 // suppressed the "begin deeper" above.
1641 context.need_end_deeper = false;
1643 context.check_end_deeper(os);
1644 parent_context.new_paragraph(os);
1646 if (!preamble.titleLayoutFound())
1647 preamble.titleLayoutFound(newlayout->intitle);
1648 set<string> const & req = newlayout->requires();
1649 set<string>::const_iterator it = req.begin();
1650 set<string>::const_iterator en = req.end();
1651 for (; it != en; ++it)
1652 preamble.registerAutomaticallyLoadedPackage(*it);
1655 // The single '=' is meant here.
1656 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1657 eat_whitespace(p, os, parent_context, false);
1658 parent_context.check_layout(os);
1659 begin_inset(os, "Flex ");
1660 os << to_utf8(newinsetlayout->name()) << '\n'
1661 << "status collapsed\n";
1662 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1666 else if (name == "appendix") {
1667 // This is no good latex style, but it works and is used in some documents...
1668 eat_whitespace(p, os, parent_context, false);
1669 parent_context.check_end_layout(os);
1670 Context context(true, parent_context.textclass, parent_context.layout,
1671 parent_context.layout, parent_context.font);
1672 context.check_layout(os);
1673 os << "\\start_of_appendix\n";
1674 parse_text(p, os, FLAG_END, outer, context);
1675 context.check_end_layout(os);
1679 else if (known_environments.find(name) != known_environments.end()) {
1680 vector<ArgumentType> arguments = known_environments[name];
1681 // The last "argument" denotes wether we may translate the
1682 // environment contents to LyX
1683 // The default required if no argument is given makes us
1684 // compatible with the reLyXre environment.
1685 ArgumentType contents = arguments.empty() ?
1688 if (!arguments.empty())
1689 arguments.pop_back();
1690 // See comment in parse_unknown_environment()
1691 bool const specialfont =
1692 (parent_context.font != parent_context.normalfont);
1693 bool const new_layout_allowed =
1694 parent_context.new_layout_allowed;
1696 parent_context.new_layout_allowed = false;
1697 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1698 outer, parent_context);
1699 if (contents == verbatim)
1700 handle_ert(os, p.verbatimEnvironment(name),
1703 parse_text_snippet(p, os, FLAG_END, outer,
1705 handle_ert(os, "\\end{" + name + "}", parent_context);
1707 parent_context.new_layout_allowed = new_layout_allowed;
1711 parse_unknown_environment(p, name, os, FLAG_END, outer,
1715 active_environments.pop_back();
1719 /// parses a comment and outputs it to \p os.
1720 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1722 LASSERT(t.cat() == catComment, return);
1723 if (!t.cs().empty()) {
1724 context.check_layout(os);
1725 handle_comment(os, '%' + t.cs(), context);
1726 if (p.next_token().cat() == catNewline) {
1727 // A newline after a comment line starts a new
1729 if (context.new_layout_allowed) {
1730 if(!context.atParagraphStart())
1731 // Only start a new paragraph if not already
1732 // done (we might get called recursively)
1733 context.new_paragraph(os);
1735 handle_ert(os, "\n", context);
1736 eat_whitespace(p, os, context, true);
1739 // "%\n" combination
1746 * Reads spaces and comments until the first non-space, non-comment token.
1747 * New paragraphs (double newlines or \\par) are handled like simple spaces
1748 * if \p eatParagraph is true.
1749 * Spaces are skipped, but comments are written to \p os.
1751 void eat_whitespace(Parser & p, ostream & os, Context & context,
1755 Token const & t = p.get_token();
1756 if (t.cat() == catComment)
1757 parse_comment(p, os, t, context);
1758 else if ((! eatParagraph && p.isParagraph()) ||
1759 (t.cat() != catSpace && t.cat() != catNewline)) {
1768 * Set a font attribute, parse text and reset the font attribute.
1769 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1770 * \param currentvalue Current value of the attribute. Is set to the new
1771 * value during parsing.
1772 * \param newvalue New value of the attribute
1774 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1775 Context & context, string const & attribute,
1776 string & currentvalue, string const & newvalue)
1778 context.check_layout(os);
1779 string const oldvalue = currentvalue;
1780 currentvalue = newvalue;
1781 os << '\n' << attribute << ' ' << newvalue << "\n";
1782 parse_text_snippet(p, os, flags, outer, context);
1783 context.check_layout(os);
1784 os << '\n' << attribute << ' ' << oldvalue << "\n";
1785 currentvalue = oldvalue;
1789 /// get the arguments of a natbib or jurabib citation command
1790 void get_cite_arguments(Parser & p, bool natbibOrder,
1791 string & before, string & after)
1793 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1795 // text before the citation
1797 // text after the citation
1798 after = p.getFullOpt();
1800 if (!after.empty()) {
1801 before = p.getFullOpt();
1802 if (natbibOrder && !before.empty())
1803 swap(before, after);
1808 /// Convert filenames with TeX macros and/or quotes to something LyX
1810 string const normalize_filename(string const & name)
1812 Parser p(trim(name, "\""));
1815 Token const & t = p.get_token();
1816 if (t.cat() != catEscape)
1818 else if (t.cs() == "lyxdot") {
1819 // This is used by LyX for simple dots in relative
1823 } else if (t.cs() == "space") {
1833 /// Convert \p name from TeX convention (relative to master file) to LyX
1834 /// convention (relative to .lyx file) if it is relative
1835 void fix_relative_filename(string & name)
1837 if (FileName::isAbsolute(name))
1840 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1841 from_utf8(getParentFilePath())));
1845 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1846 void parse_noweb(Parser & p, ostream & os, Context & context)
1848 // assemble the rest of the keyword
1852 Token const & t = p.get_token();
1853 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1856 scrap = (p.good() && p.next_token().asInput() == "=");
1858 name += p.get_token().asInput();
1861 name += t.asInput();
1864 if (!scrap || !context.new_layout_allowed ||
1865 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1866 cerr << "Warning: Could not interpret '" << name
1867 << "'. Ignoring it." << endl;
1871 // We use new_paragraph instead of check_end_layout because the stuff
1872 // following the noweb chunk needs to start with a \begin_layout.
1873 // This may create a new paragraph even if there was none in the
1874 // noweb file, but the alternative is an invalid LyX file. Since
1875 // noweb code chunks are implemented with a layout style in LyX they
1876 // always must be in an own paragraph.
1877 context.new_paragraph(os);
1878 Context newcontext(true, context.textclass,
1879 &context.textclass[from_ascii("Scrap")]);
1880 newcontext.check_layout(os);
1883 Token const & t = p.get_token();
1884 // We abuse the parser a bit, because this is no TeX syntax
1886 if (t.cat() == catEscape)
1887 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1890 Context tmp(false, context.textclass,
1891 &context.textclass[from_ascii("Scrap")]);
1892 tmp.need_end_layout = true;
1893 tmp.check_layout(oss);
1894 os << subst(t.asInput(), "\n", oss.str());
1896 // The scrap chunk is ended by an @ at the beginning of a line.
1897 // After the @ the line may contain a comment and/or
1898 // whitespace, but nothing else.
1899 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1900 (p.next_token().cat() == catSpace ||
1901 p.next_token().cat() == catNewline ||
1902 p.next_token().cat() == catComment)) {
1903 while (p.good() && p.next_token().cat() == catSpace)
1904 os << p.get_token().asInput();
1905 if (p.next_token().cat() == catComment)
1906 // The comment includes a final '\n'
1907 os << p.get_token().asInput();
1909 if (p.next_token().cat() == catNewline)
1916 newcontext.check_end_layout(os);
1920 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1921 bool is_macro(Parser & p)
1923 Token first = p.curr_token();
1924 if (first.cat() != catEscape || !p.good())
1926 if (first.cs() == "def")
1928 if (first.cs() != "global" && first.cs() != "long")
1930 Token second = p.get_token();
1932 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1933 second.cat() == catNewline || second.cat() == catComment)) {
1934 second = p.get_token();
1937 bool secondvalid = second.cat() == catEscape;
1939 bool thirdvalid = false;
1940 if (p.good() && first.cs() == "global" && secondvalid &&
1941 second.cs() == "long") {
1942 third = p.get_token();
1944 while (p.good() && !p.isParagraph() &&
1945 (third.cat() == catSpace ||
1946 third.cat() == catNewline ||
1947 third.cat() == catComment)) {
1948 third = p.get_token();
1951 thirdvalid = third.cat() == catEscape;
1953 for (int i = 0; i < pos; ++i)
1958 return (first.cs() == "global" || first.cs() == "long") &&
1959 second.cs() == "def";
1960 return first.cs() == "global" && second.cs() == "long" &&
1961 third.cs() == "def";
1965 /// Parse a macro definition (assumes that is_macro() returned true)
1966 void parse_macro(Parser & p, ostream & os, Context & context)
1968 context.check_layout(os);
1969 Token first = p.curr_token();
1972 string command = first.asInput();
1973 if (first.cs() != "def") {
1975 eat_whitespace(p, os, context, false);
1976 second = p.curr_token();
1977 command += second.asInput();
1978 if (second.cs() != "def") {
1980 eat_whitespace(p, os, context, false);
1981 third = p.curr_token();
1982 command += third.asInput();
1985 eat_whitespace(p, os, context, false);
1986 string const name = p.get_token().cs();
1987 eat_whitespace(p, os, context, false);
1993 while (p.next_token().cat() != catBegin) {
1994 if (p.next_token().cat() == catParameter) {
1999 // followed by number?
2000 if (p.next_token().cat() == catOther) {
2001 char c = p.getChar();
2003 // number = current arity + 1?
2004 if (c == arity + '0' + 1)
2009 paramtext += p.get_token().cs();
2011 paramtext += p.get_token().cs();
2016 // only output simple (i.e. compatible) macro as FormulaMacros
2017 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2019 context.check_layout(os);
2020 begin_inset(os, "FormulaMacro");
2021 os << "\n\\def" << ert;
2024 handle_ert(os, command + ert, context);
2028 void registerExternalTemplatePackages(string const & name)
2030 external::TemplateManager const & etm = external::TemplateManager::get();
2031 external::Template const * const et = etm.getTemplateByName(name);
2034 external::Template::Formats::const_iterator cit = et->formats.end();
2036 cit = et->formats.find("PDFLaTeX");
2037 if (cit == et->formats.end())
2038 // If the template has not specified a PDFLaTeX output,
2039 // we try the LaTeX format.
2040 cit = et->formats.find("LaTeX");
2041 if (cit == et->formats.end())
2043 vector<string>::const_iterator qit = cit->second.requirements.begin();
2044 vector<string>::const_iterator qend = cit->second.requirements.end();
2045 for (; qit != qend; ++qit)
2046 preamble.registerAutomaticallyLoadedPackage(*qit);
2049 } // anonymous namespace
2052 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2055 Layout const * newlayout = 0;
2056 InsetLayout const * newinsetlayout = 0;
2057 char const * const * where = 0;
2058 // Store the latest bibliographystyle and nocite{*} option
2059 // (needed for bibtex inset)
2061 string bibliographystyle = "default";
2062 bool const use_natbib = preamble.isPackageUsed("natbib");
2063 bool const use_jurabib = preamble.isPackageUsed("jurabib");
2066 Token const & t = p.get_token();
2068 // it is impossible to determine the correct document language if CJK is used.
2069 // Therefore write a note at the beginning of the document
2071 context.check_layout(os);
2072 begin_inset(os, "Note Note\n");
2073 os << "status open\n\\begin_layout Plain Layout\n"
2074 << "\\series bold\n"
2075 << "Important information:\n"
2076 << "\\end_layout\n\n"
2077 << "\\begin_layout Plain Layout\n"
2078 << "This document contains text in Chinese, Japanese or Korean.\n"
2079 << " It was therefore impossible for tex2lyx to set the correct document langue for your document."
2080 << " Please set the language manually in the document settings.\n"
2081 << "\\end_layout\n";
2086 // it is impossible to determine the correct encoding for non-CJK Japanese.
2087 // Therefore write a note at the beginning of the document
2088 if (is_nonCJKJapanese) {
2089 context.check_layout(os);
2090 begin_inset(os, "Note Note\n");
2091 os << "status open\n\\begin_layout Plain Layout\n"
2092 << "\\series bold\n"
2093 << "Important information:\n"
2094 << "\\end_layout\n\n"
2095 << "\\begin_layout Plain Layout\n"
2096 << "This document is in Japanese (non-CJK).\n"
2097 << " It was therefore impossible for tex2lyx to determine the correct encoding."
2098 << " The encoding EUC-JP was assumed. If this is incorrect, please set the correct"
2099 << " encoding in the document settings.\n"
2100 << "\\end_layout\n";
2102 is_nonCJKJapanese = false;
2106 debugToken(cerr, t, flags);
2109 if (flags & FLAG_ITEM) {
2110 if (t.cat() == catSpace)
2113 flags &= ~FLAG_ITEM;
2114 if (t.cat() == catBegin) {
2115 // skip the brace and collect everything to the next matching
2117 flags |= FLAG_BRACE_LAST;
2121 // handle only this single token, leave the loop if done
2122 flags |= FLAG_LEAVE;
2125 if (t.cat() != catEscape && t.character() == ']' &&
2126 (flags & FLAG_BRACK_LAST))
2128 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2131 // If there is anything between \end{env} and \begin{env} we
2132 // don't need to output a separator.
2133 if (t.cat() != catSpace && t.cat() != catNewline &&
2134 t.asInput() != "\\begin")
2140 if (t.cat() == catMath) {
2141 // we are inside some text mode thingy, so opening new math is allowed
2142 context.check_layout(os);
2143 begin_inset(os, "Formula ");
2144 Token const & n = p.get_token();
2145 bool const display(n.cat() == catMath && outer);
2147 // TeX's $$...$$ syntax for displayed math
2149 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2151 p.get_token(); // skip the second '$' token
2153 // simple $...$ stuff
2156 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2161 // Prevent the conversion of a line break to a
2162 // space (bug 7668). This does not change the
2163 // output, but looks ugly in LyX.
2164 eat_whitespace(p, os, context, false);
2168 else if (t.cat() == catSuper || t.cat() == catSub)
2169 cerr << "catcode " << t << " illegal in text mode\n";
2171 // Basic support for english quotes. This should be
2172 // extended to other quotes, but is not so easy (a
2173 // left english quote is the same as a right german
2175 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2176 context.check_layout(os);
2177 begin_inset(os, "Quotes ");
2183 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2184 context.check_layout(os);
2185 begin_inset(os, "Quotes ");
2192 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2193 context.check_layout(os);
2194 begin_inset(os, "Quotes ");
2201 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2202 context.check_layout(os);
2203 begin_inset(os, "Quotes ");
2210 else if (t.asInput() == "<"
2211 && p.next_token().asInput() == "<" && noweb_mode) {
2213 parse_noweb(p, os, context);
2216 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2217 check_space(p, os, context);
2219 else if (t.character() == '[' && noweb_mode &&
2220 p.next_token().character() == '[') {
2221 // These can contain underscores
2223 string const s = p.getFullOpt() + ']';
2224 if (p.next_token().character() == ']')
2227 cerr << "Warning: Inserting missing ']' in '"
2228 << s << "'." << endl;
2229 handle_ert(os, s, context);
2232 else if (t.cat() == catLetter) {
2233 context.check_layout(os);
2234 // Workaround for bug 4752.
2235 // FIXME: This whole code block needs to be removed
2236 // when the bug is fixed and tex2lyx produces
2237 // the updated file format.
2238 // The replacement algorithm in LyX is so stupid that
2239 // it even translates a phrase if it is part of a word.
2240 bool handled = false;
2241 for (int const * l = known_phrase_lengths; *l; ++l) {
2242 string phrase = t.cs();
2243 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2244 phrase += p.get_token().cs();
2245 if (is_known(phrase, known_coded_phrases)) {
2246 handle_ert(os, phrase, context);
2250 for (size_t i = 1; i < phrase.length(); ++i)
2258 else if (t.cat() == catOther ||
2259 t.cat() == catAlign ||
2260 t.cat() == catParameter) {
2261 // This translates "&" to "\\&" which may be wrong...
2262 context.check_layout(os);
2266 else if (p.isParagraph()) {
2267 if (context.new_layout_allowed)
2268 context.new_paragraph(os);
2270 handle_ert(os, "\\par ", context);
2271 eat_whitespace(p, os, context, true);
2274 else if (t.cat() == catActive) {
2275 context.check_layout(os);
2276 if (t.character() == '~') {
2277 if (context.layout->free_spacing)
2280 begin_inset(os, "space ~\n");
2287 else if (t.cat() == catBegin) {
2288 Token const next = p.next_token();
2289 Token const end = p.next_next_token();
2290 if (next.cat() == catEnd) {
2292 Token const prev = p.prev_token();
2294 if (p.next_token().character() == '`' ||
2295 (prev.character() == '-' &&
2296 p.next_token().character() == '-'))
2297 ; // ignore it in {}`` or -{}-
2299 handle_ert(os, "{}", context);
2300 } else if (next.cat() == catEscape &&
2301 is_known(next.cs(), known_quotes) &&
2302 end.cat() == catEnd) {
2303 // Something like {\textquoteright} (e.g.
2304 // from writer2latex). LyX writes
2305 // \textquoteright{}, so we may skip the
2306 // braces here for better readability.
2307 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2310 context.check_layout(os);
2311 // special handling of font attribute changes
2312 Token const prev = p.prev_token();
2313 TeXFont const oldFont = context.font;
2314 if (next.character() == '[' ||
2315 next.character() == ']' ||
2316 next.character() == '*') {
2318 if (p.next_token().cat() == catEnd) {
2323 handle_ert(os, "{", context);
2324 parse_text_snippet(p, os,
2327 handle_ert(os, "}", context);
2329 } else if (! context.new_layout_allowed) {
2330 handle_ert(os, "{", context);
2331 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2333 handle_ert(os, "}", context);
2334 } else if (is_known(next.cs(), known_sizes)) {
2335 // next will change the size, so we must
2337 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2339 if (!context.atParagraphStart())
2341 << context.font.size << "\n";
2342 } else if (is_known(next.cs(), known_font_families)) {
2343 // next will change the font family, so we
2344 // must reset it here
2345 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2347 if (!context.atParagraphStart())
2349 << context.font.family << "\n";
2350 } else if (is_known(next.cs(), known_font_series)) {
2351 // next will change the font series, so we
2352 // must reset it here
2353 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2355 if (!context.atParagraphStart())
2357 << context.font.series << "\n";
2358 } else if (is_known(next.cs(), known_font_shapes)) {
2359 // next will change the font shape, so we
2360 // must reset it here
2361 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2363 if (!context.atParagraphStart())
2365 << context.font.shape << "\n";
2366 } else if (is_known(next.cs(), known_old_font_families) ||
2367 is_known(next.cs(), known_old_font_series) ||
2368 is_known(next.cs(), known_old_font_shapes)) {
2369 // next will change the font family, series
2370 // and shape, so we must reset it here
2371 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2373 if (!context.atParagraphStart())
2375 << context.font.family
2377 << context.font.series
2379 << context.font.shape << "\n";
2381 handle_ert(os, "{", context);
2382 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2384 handle_ert(os, "}", context);
2389 else if (t.cat() == catEnd) {
2390 if (flags & FLAG_BRACE_LAST) {
2393 cerr << "stray '}' in text\n";
2394 handle_ert(os, "}", context);
2397 else if (t.cat() == catComment)
2398 parse_comment(p, os, t, context);
2401 // control sequences
2404 else if (t.cs() == "(") {
2405 context.check_layout(os);
2406 begin_inset(os, "Formula");
2408 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2413 else if (t.cs() == "[") {
2414 context.check_layout(os);
2415 begin_inset(os, "Formula");
2417 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2420 // Prevent the conversion of a line break to a space
2421 // (bug 7668). This does not change the output, but
2422 // looks ugly in LyX.
2423 eat_whitespace(p, os, context, false);
2426 else if (t.cs() == "begin")
2427 parse_environment(p, os, outer, last_env,
2430 else if (t.cs() == "end") {
2431 if (flags & FLAG_END) {
2432 // eat environment name
2433 string const name = p.getArg('{', '}');
2434 if (name != active_environment())
2435 cerr << "\\end{" + name + "} does not match \\begin{"
2436 + active_environment() + "}\n";
2439 p.error("found 'end' unexpectedly");
2442 else if (t.cs() == "item") {
2444 bool const optarg = p.hasOpt();
2446 // FIXME: This swallows comments, but we cannot use
2447 // eat_whitespace() since we must not output
2448 // anything before the item.
2449 p.skip_spaces(true);
2450 s = p.verbatimOption();
2452 p.skip_spaces(false);
2454 context.check_layout(os);
2455 if (context.has_item) {
2456 // An item in an unknown list-like environment
2457 // FIXME: Do this in check_layout()!
2458 context.has_item = false;
2460 handle_ert(os, "\\item", context);
2462 handle_ert(os, "\\item ", context);
2465 if (context.layout->labeltype != LABEL_MANUAL) {
2466 // LyX does not support \item[\mybullet]
2467 // in itemize environments
2469 os << parse_text_snippet(p2,
2470 FLAG_BRACK_LAST, outer, context);
2471 } else if (!s.empty()) {
2472 // LyX adds braces around the argument,
2473 // so we need to remove them here.
2474 if (s.size() > 2 && s[0] == '{' &&
2475 s[s.size()-1] == '}')
2476 s = s.substr(1, s.size()-2);
2477 // If the argument contains a space we
2478 // must put it into ERT: Otherwise LyX
2479 // would misinterpret the space as
2480 // item delimiter (bug 7663)
2481 if (contains(s, ' ')) {
2482 handle_ert(os, s, context);
2485 os << parse_text_snippet(p2,
2489 // The space is needed to separate the
2490 // item from the rest of the sentence.
2492 eat_whitespace(p, os, context, false);
2497 else if (t.cs() == "bibitem") {
2499 context.check_layout(os);
2500 eat_whitespace(p, os, context, false);
2501 string label = convert_command_inset_arg(p.verbatimOption());
2502 string key = convert_command_inset_arg(p.verbatim_item());
2503 if (contains(label, '\\') || contains(key, '\\')) {
2504 // LyX can't handle LaTeX commands in labels or keys
2505 handle_ert(os, t.asInput() + '[' + label +
2506 "]{" + p.verbatim_item() + '}',
2509 begin_command_inset(os, "bibitem", "bibitem");
2510 os << "label \"" << label << "\"\n"
2511 "key \"" << key << "\"\n";
2516 else if (is_macro(p)) {
2517 // catch the case of \def\inputGnumericTable
2519 if (t.cs() == "def") {
2520 Token second = p.next_token();
2521 if (second.cs() == "inputGnumericTable") {
2525 Token third = p.get_token();
2527 if (third.cs() == "input") {
2531 string name = normalize_filename(p.verbatim_item());
2532 string const path = getMasterFilePath();
2533 // We want to preserve relative / absolute filenames,
2534 // therefore path is only used for testing
2535 // The file extension is in every case ".tex".
2536 // So we need to remove this extension and check for
2537 // the original one.
2538 name = removeExtension(name);
2539 if (!makeAbsPath(name, path).exists()) {
2540 char const * const Gnumeric_formats[] = {"gnumeric",
2542 string const Gnumeric_name =
2543 find_file(name, path, Gnumeric_formats);
2544 if (!Gnumeric_name.empty())
2545 name = Gnumeric_name;
2547 if (makeAbsPath(name, path).exists())
2548 fix_relative_filename(name);
2550 cerr << "Warning: Could not find file '"
2551 << name << "'." << endl;
2552 context.check_layout(os);
2553 begin_inset(os, "External\n\ttemplate ");
2554 os << "GnumericSpreadsheet\n\tfilename "
2557 context.check_layout(os);
2559 // register the packages that are automatically reloaded
2560 // by the Gnumeric template
2561 registerExternalTemplatePackages("GnumericSpreadsheet");
2566 parse_macro(p, os, context);
2569 else if (t.cs() == "noindent") {
2571 context.add_par_extra_stuff("\\noindent\n");
2574 else if (t.cs() == "appendix") {
2575 context.add_par_extra_stuff("\\start_of_appendix\n");
2576 // We need to start a new paragraph. Otherwise the
2577 // appendix in 'bla\appendix\chapter{' would start
2579 context.new_paragraph(os);
2580 // We need to make sure that the paragraph is
2581 // generated even if it is empty. Otherwise the
2582 // appendix in '\par\appendix\par\chapter{' would
2584 context.check_layout(os);
2585 // FIXME: This is a hack to prevent paragraph
2586 // deletion if it is empty. Handle this better!
2588 "%dummy comment inserted by tex2lyx to "
2589 "ensure that this paragraph is not empty",
2591 // Both measures above may generate an additional
2592 // empty paragraph, but that does not hurt, because
2593 // whitespace does not matter here.
2594 eat_whitespace(p, os, context, true);
2597 // Must catch empty dates before findLayout is called below
2598 else if (t.cs() == "date") {
2599 eat_whitespace(p, os, context, false);
2601 string const date = p.verbatim_item();
2604 preamble.suppressDate(true);
2607 preamble.suppressDate(false);
2608 if (context.new_layout_allowed &&
2609 (newlayout = findLayout(context.textclass,
2612 output_command_layout(os, p, outer,
2613 context, newlayout);
2614 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2615 if (!preamble.titleLayoutFound())
2616 preamble.titleLayoutFound(newlayout->intitle);
2617 set<string> const & req = newlayout->requires();
2618 set<string>::const_iterator it = req.begin();
2619 set<string>::const_iterator en = req.end();
2620 for (; it != en; ++it)
2621 preamble.registerAutomaticallyLoadedPackage(*it);
2624 "\\date{" + p.verbatim_item() + '}',
2629 // Starred section headings
2630 // Must attempt to parse "Section*" before "Section".
2631 else if ((p.next_token().asInput() == "*") &&
2632 context.new_layout_allowed &&
2633 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2636 output_command_layout(os, p, outer, context, newlayout);
2638 if (!preamble.titleLayoutFound())
2639 preamble.titleLayoutFound(newlayout->intitle);
2640 set<string> const & req = newlayout->requires();
2641 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2642 preamble.registerAutomaticallyLoadedPackage(*it);
2645 // Section headings and the like
2646 else if (context.new_layout_allowed &&
2647 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2649 output_command_layout(os, p, outer, context, newlayout);
2651 if (!preamble.titleLayoutFound())
2652 preamble.titleLayoutFound(newlayout->intitle);
2653 set<string> const & req = newlayout->requires();
2654 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2655 preamble.registerAutomaticallyLoadedPackage(*it);
2658 else if (t.cs() == "caption") {
2660 context.check_layout(os);
2662 begin_inset(os, "Caption\n");
2663 Context newcontext(true, context.textclass);
2664 newcontext.font = context.font;
2665 newcontext.check_layout(os);
2666 if (p.next_token().cat() != catEscape &&
2667 p.next_token().character() == '[') {
2668 p.get_token(); // eat '['
2669 begin_inset(os, "Argument\n");
2670 os << "status collapsed\n";
2671 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2673 eat_whitespace(p, os, context, false);
2675 parse_text(p, os, FLAG_ITEM, outer, context);
2676 context.check_end_layout(os);
2677 // We don't need really a new paragraph, but
2678 // we must make sure that the next item gets a \begin_layout.
2679 context.new_paragraph(os);
2682 newcontext.check_end_layout(os);
2685 else if (t.cs() == "subfloat") {
2686 // the syntax is \subfloat[caption]{content}
2687 // if it is a table of figure depends on the surrounding float
2688 bool has_caption = false;
2690 // do nothing if there is no outer float
2691 if (!float_type.empty()) {
2692 context.check_layout(os);
2694 begin_inset(os, "Float " + float_type + "\n");
2696 << "\nsideways false"
2697 << "\nstatus collapsed\n\n";
2700 if (p.next_token().cat() != catEscape &&
2701 p.next_token().character() == '[') {
2702 p.get_token(); // eat '['
2703 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2707 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2708 // the caption comes always as the last
2710 // we must make sure that the caption gets a \begin_layout
2711 os << "\n\\begin_layout Plain Layout";
2713 begin_inset(os, "Caption\n");
2714 Context newcontext(true, context.textclass);
2715 newcontext.font = context.font;
2716 newcontext.check_layout(os);
2717 os << caption << "\n";
2718 newcontext.check_end_layout(os);
2719 // We don't need really a new paragraph, but
2720 // we must make sure that the next item gets a \begin_layout.
2721 //newcontext.new_paragraph(os);
2725 // We don't need really a new paragraph, but
2726 // we must make sure that the next item gets a \begin_layout.
2728 context.new_paragraph(os);
2731 context.check_end_layout(os);
2732 // close the layout we opened
2734 os << "\n\\end_layout\n";
2736 // if the float type is not supported or there is no surrounding float
2739 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2740 handle_ert(os, t.asInput() + '[' + opt_arg +
2741 "]{" + p.verbatim_item() + '}', context);
2743 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2747 else if (t.cs() == "includegraphics") {
2748 bool const clip = p.next_token().asInput() == "*";
2751 string const arg = p.getArg('[', ']');
2752 map<string, string> opts;
2753 vector<string> keys;
2754 split_map(arg, opts, keys);
2756 opts["clip"] = string();
2757 string name = normalize_filename(p.verbatim_item());
2759 string const path = getMasterFilePath();
2760 // We want to preserve relative / absolute filenames,
2761 // therefore path is only used for testing
2762 if (!makeAbsPath(name, path).exists()) {
2763 // The file extension is probably missing.
2764 // Now try to find it out.
2765 string const dvips_name =
2766 find_file(name, path,
2767 known_dvips_graphics_formats);
2768 string const pdftex_name =
2769 find_file(name, path,
2770 known_pdftex_graphics_formats);
2771 if (!dvips_name.empty()) {
2772 if (!pdftex_name.empty()) {
2773 cerr << "This file contains the "
2775 "\"\\includegraphics{"
2777 "However, files\n\""
2778 << dvips_name << "\" and\n\""
2779 << pdftex_name << "\"\n"
2780 "both exist, so I had to make a "
2781 "choice and took the first one.\n"
2782 "Please move the unwanted one "
2783 "someplace else and try again\n"
2784 "if my choice was wrong."
2788 } else if (!pdftex_name.empty()) {
2794 if (makeAbsPath(name, path).exists())
2795 fix_relative_filename(name);
2797 cerr << "Warning: Could not find graphics file '"
2798 << name << "'." << endl;
2800 context.check_layout(os);
2801 begin_inset(os, "Graphics ");
2802 os << "\n\tfilename " << name << '\n';
2803 if (opts.find("width") != opts.end())
2805 << translate_len(opts["width"]) << '\n';
2806 if (opts.find("height") != opts.end())
2808 << translate_len(opts["height"]) << '\n';
2809 if (opts.find("scale") != opts.end()) {
2810 istringstream iss(opts["scale"]);
2814 os << "\tscale " << val << '\n';
2816 if (opts.find("angle") != opts.end()) {
2817 os << "\trotateAngle "
2818 << opts["angle"] << '\n';
2819 vector<string>::const_iterator a =
2820 find(keys.begin(), keys.end(), "angle");
2821 vector<string>::const_iterator s =
2822 find(keys.begin(), keys.end(), "width");
2823 if (s == keys.end())
2824 s = find(keys.begin(), keys.end(), "height");
2825 if (s == keys.end())
2826 s = find(keys.begin(), keys.end(), "scale");
2827 if (s != keys.end() && distance(s, a) > 0)
2828 os << "\tscaleBeforeRotation\n";
2830 if (opts.find("origin") != opts.end()) {
2832 string const opt = opts["origin"];
2833 if (opt.find('l') != string::npos) ss << "left";
2834 if (opt.find('r') != string::npos) ss << "right";
2835 if (opt.find('c') != string::npos) ss << "center";
2836 if (opt.find('t') != string::npos) ss << "Top";
2837 if (opt.find('b') != string::npos) ss << "Bottom";
2838 if (opt.find('B') != string::npos) ss << "Baseline";
2839 if (!ss.str().empty())
2840 os << "\trotateOrigin " << ss.str() << '\n';
2842 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2844 if (opts.find("keepaspectratio") != opts.end())
2845 os << "\tkeepAspectRatio\n";
2846 if (opts.find("clip") != opts.end())
2848 if (opts.find("draft") != opts.end())
2850 if (opts.find("bb") != opts.end())
2851 os << "\tBoundingBox "
2852 << opts["bb"] << '\n';
2853 int numberOfbbOptions = 0;
2854 if (opts.find("bbllx") != opts.end())
2855 numberOfbbOptions++;
2856 if (opts.find("bblly") != opts.end())
2857 numberOfbbOptions++;
2858 if (opts.find("bburx") != opts.end())
2859 numberOfbbOptions++;
2860 if (opts.find("bbury") != opts.end())
2861 numberOfbbOptions++;
2862 if (numberOfbbOptions == 4)
2863 os << "\tBoundingBox "
2864 << opts["bbllx"] << " " << opts["bblly"] << " "
2865 << opts["bburx"] << " " << opts["bbury"] << '\n';
2866 else if (numberOfbbOptions > 0)
2867 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2868 numberOfbbOptions = 0;
2869 if (opts.find("natwidth") != opts.end())
2870 numberOfbbOptions++;
2871 if (opts.find("natheight") != opts.end())
2872 numberOfbbOptions++;
2873 if (numberOfbbOptions == 2)
2874 os << "\tBoundingBox 0bp 0bp "
2875 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2876 else if (numberOfbbOptions > 0)
2877 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2878 ostringstream special;
2879 if (opts.find("hiresbb") != opts.end())
2880 special << "hiresbb,";
2881 if (opts.find("trim") != opts.end())
2883 if (opts.find("viewport") != opts.end())
2884 special << "viewport=" << opts["viewport"] << ',';
2885 if (opts.find("totalheight") != opts.end())
2886 special << "totalheight=" << opts["totalheight"] << ',';
2887 if (opts.find("type") != opts.end())
2888 special << "type=" << opts["type"] << ',';
2889 if (opts.find("ext") != opts.end())
2890 special << "ext=" << opts["ext"] << ',';
2891 if (opts.find("read") != opts.end())
2892 special << "read=" << opts["read"] << ',';
2893 if (opts.find("command") != opts.end())
2894 special << "command=" << opts["command"] << ',';
2895 string s_special = special.str();
2896 if (!s_special.empty()) {
2897 // We had special arguments. Remove the trailing ','.
2898 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2900 // TODO: Handle the unknown settings better.
2901 // Warn about invalid options.
2902 // Check whether some option was given twice.
2904 preamble.registerAutomaticallyLoadedPackage("graphicx");
2907 else if (t.cs() == "footnote" ||
2908 (t.cs() == "thanks" && context.layout->intitle)) {
2910 context.check_layout(os);
2911 begin_inset(os, "Foot\n");
2912 os << "status collapsed\n\n";
2913 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2917 else if (t.cs() == "marginpar") {
2919 context.check_layout(os);
2920 begin_inset(os, "Marginal\n");
2921 os << "status collapsed\n\n";
2922 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2926 else if (t.cs() == "lstinline") {
2928 parse_listings(p, os, context, true);
2931 else if (t.cs() == "ensuremath") {
2933 context.check_layout(os);
2934 string const s = p.verbatim_item();
2935 //FIXME: this never triggers in UTF8
2936 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2939 handle_ert(os, "\\ensuremath{" + s + "}",
2943 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2944 if (preamble.titleLayoutFound()) {
2946 skip_spaces_braces(p);
2948 handle_ert(os, t.asInput(), context);
2951 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
2952 context.check_layout(os);
2953 begin_command_inset(os, "toc", t.cs());
2955 skip_spaces_braces(p);
2956 if (t.cs() == "lstlistoflistings")
2957 preamble.registerAutomaticallyLoadedPackage("listings");
2960 else if (t.cs() == "listoffigures") {
2961 context.check_layout(os);
2962 begin_inset(os, "FloatList figure\n");
2964 skip_spaces_braces(p);
2967 else if (t.cs() == "listoftables") {
2968 context.check_layout(os);
2969 begin_inset(os, "FloatList table\n");
2971 skip_spaces_braces(p);
2974 else if (t.cs() == "listof") {
2975 p.skip_spaces(true);
2976 string const name = p.get_token().cs();
2977 if (context.textclass.floats().typeExist(name)) {
2978 context.check_layout(os);
2979 begin_inset(os, "FloatList ");
2982 p.get_token(); // swallow second arg
2984 handle_ert(os, "\\listof{" + name + "}", context);
2987 else if ((where = is_known(t.cs(), known_text_font_families)))
2988 parse_text_attributes(p, os, FLAG_ITEM, outer,
2989 context, "\\family", context.font.family,
2990 known_coded_font_families[where - known_text_font_families]);
2992 else if ((where = is_known(t.cs(), known_text_font_series)))
2993 parse_text_attributes(p, os, FLAG_ITEM, outer,
2994 context, "\\series", context.font.series,
2995 known_coded_font_series[where - known_text_font_series]);
2997 else if ((where = is_known(t.cs(), known_text_font_shapes)))
2998 parse_text_attributes(p, os, FLAG_ITEM, outer,
2999 context, "\\shape", context.font.shape,
3000 known_coded_font_shapes[where - known_text_font_shapes]);
3002 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3003 context.check_layout(os);
3004 TeXFont oldFont = context.font;
3005 context.font.init();
3006 context.font.size = oldFont.size;
3007 os << "\n\\family " << context.font.family << "\n";
3008 os << "\n\\series " << context.font.series << "\n";
3009 os << "\n\\shape " << context.font.shape << "\n";
3010 if (t.cs() == "textnormal") {
3011 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3012 output_font_change(os, context.font, oldFont);
3013 context.font = oldFont;
3015 eat_whitespace(p, os, context, false);
3018 else if (t.cs() == "textcolor") {
3019 // scheme is \textcolor{color name}{text}
3020 string const color = p.verbatim_item();
3021 // we only support the predefined colors of the color package
3022 if (color == "black" || color == "blue" || color == "cyan"
3023 || color == "green" || color == "magenta" || color == "red"
3024 || color == "white" || color == "yellow") {
3025 context.check_layout(os);
3026 os << "\n\\color " << color << "\n";
3027 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3028 context.check_layout(os);
3029 os << "\n\\color inherit\n";
3030 preamble.registerAutomaticallyLoadedPackage("color");
3032 // for custom defined colors
3033 handle_ert(os, t.asInput() + "{" + color + "}", context);
3036 else if (t.cs() == "underbar" || t.cs() == "uline") {
3037 // \underbar is not 100% correct (LyX outputs \uline
3038 // of ulem.sty). The difference is that \ulem allows
3039 // line breaks, and \underbar does not.
3040 // Do NOT handle \underline.
3041 // \underbar cuts through y, g, q, p etc.,
3042 // \underline does not.
3043 context.check_layout(os);
3044 os << "\n\\bar under\n";
3045 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3046 context.check_layout(os);
3047 os << "\n\\bar default\n";
3048 preamble.registerAutomaticallyLoadedPackage("ulem");
3051 else if (t.cs() == "sout") {
3052 context.check_layout(os);
3053 os << "\n\\strikeout on\n";
3054 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3055 context.check_layout(os);
3056 os << "\n\\strikeout default\n";
3057 preamble.registerAutomaticallyLoadedPackage("ulem");
3060 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3061 t.cs() == "emph" || t.cs() == "noun") {
3062 context.check_layout(os);
3063 os << "\n\\" << t.cs() << " on\n";
3064 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3065 context.check_layout(os);
3066 os << "\n\\" << t.cs() << " default\n";
3067 if (t.cs() == "uuline" || t.cs() == "uwave")
3068 preamble.registerAutomaticallyLoadedPackage("ulem");
3071 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3072 context.check_layout(os);
3073 string name = p.getArg('{', '}');
3074 string localtime = p.getArg('{', '}');
3075 preamble.registerAuthor(name);
3076 Author const & author = preamble.getAuthor(name);
3077 // from_ctime() will fail if LyX decides to output the
3078 // time in the text language. It might also use a wrong
3079 // time zone (if the original LyX document was exported
3080 // with a different time zone).
3081 time_t ptime = from_ctime(localtime);
3082 if (ptime == static_cast<time_t>(-1)) {
3083 cerr << "Warning: Could not parse time `" << localtime
3084 << "´ for change tracking, using current time instead.\n";
3085 ptime = current_time();
3087 if (t.cs() == "lyxadded")
3088 os << "\n\\change_inserted ";
3090 os << "\n\\change_deleted ";
3091 os << author.bufferId() << ' ' << ptime << '\n';
3092 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3093 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3094 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3095 LaTeXPackages::isAvailable("xcolor");
3096 // No need to test for luatex, since luatex comes in
3097 // two flavours (dvi and pdf), like latex, and those
3098 // are detected by pdflatex.
3099 if (pdflatex || xetex) {
3101 preamble.registerAutomaticallyLoadedPackage("ulem");
3102 preamble.registerAutomaticallyLoadedPackage("xcolor");
3103 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3107 preamble.registerAutomaticallyLoadedPackage("dvipost");
3108 } else if (xcolorulem) {
3109 preamble.registerAutomaticallyLoadedPackage("ulem");
3110 preamble.registerAutomaticallyLoadedPackage("xcolor");
3115 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3116 t.cs() == "vphantom") {
3117 context.check_layout(os);
3118 if (t.cs() == "phantom")
3119 begin_inset(os, "Phantom Phantom\n");
3120 if (t.cs() == "hphantom")
3121 begin_inset(os, "Phantom HPhantom\n");
3122 if (t.cs() == "vphantom")
3123 begin_inset(os, "Phantom VPhantom\n");
3124 os << "status open\n";
3125 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3130 else if (t.cs() == "href") {
3131 context.check_layout(os);
3132 string target = p.getArg('{', '}');
3133 string name = p.getArg('{', '}');
3135 size_t i = target.find(':');
3136 if (i != string::npos) {
3137 type = target.substr(0, i + 1);
3138 if (type == "mailto:" || type == "file:")
3139 target = target.substr(i + 1);
3140 // handle the case that name is equal to target, except of "http://"
3141 else if (target.substr(i + 3) == name && type == "http:")
3144 begin_command_inset(os, "href", "href");
3146 os << "name \"" << name << "\"\n";
3147 os << "target \"" << target << "\"\n";
3148 if (type == "mailto:" || type == "file:")
3149 os << "type \"" << type << "\"\n";
3151 skip_spaces_braces(p);
3154 else if (t.cs() == "lyxline") {
3155 // swallow size argument (it is not used anyway)
3157 if (!context.atParagraphStart()) {
3158 // so our line is in the middle of a paragraph
3159 // we need to add a new line, lest this line
3160 // follow the other content on that line and
3161 // run off the side of the page
3162 // FIXME: This may create an empty paragraph,
3163 // but without that it would not be
3164 // possible to set noindent below.
3165 // Fortunately LaTeX does not care
3166 // about the empty paragraph.
3167 context.new_paragraph(os);
3169 if (preamble.indentParagraphs()) {
3170 // we need to unindent, lest the line be too long
3171 context.add_par_extra_stuff("\\noindent\n");
3173 context.check_layout(os);
3174 begin_command_inset(os, "line", "rule");
3175 os << "offset \"0.5ex\"\n"
3176 "width \"100line%\"\n"
3181 else if (t.cs() == "rule") {
3182 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3183 string const width = p.getArg('{', '}');
3184 string const thickness = p.getArg('{', '}');
3185 context.check_layout(os);
3186 begin_command_inset(os, "line", "rule");
3187 if (!offset.empty())
3188 os << "offset \"" << translate_len(offset) << "\"\n";
3189 os << "width \"" << translate_len(width) << "\"\n"
3190 "height \"" << translate_len(thickness) << "\"\n";
3194 else if (is_known(t.cs(), known_phrases) ||
3195 (t.cs() == "protect" &&
3196 p.next_token().cat() == catEscape &&
3197 is_known(p.next_token().cs(), known_phrases))) {
3198 // LyX sometimes puts a \protect in front, so we have to ignore it
3199 // FIXME: This needs to be changed when bug 4752 is fixed.
3201 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3203 context.check_layout(os);
3204 os << known_coded_phrases[where - known_phrases];
3205 skip_spaces_braces(p);
3208 else if ((where = is_known(t.cs(), known_ref_commands))) {
3209 string const opt = p.getOpt();
3211 context.check_layout(os);
3212 begin_command_inset(os, "ref",
3213 known_coded_ref_commands[where - known_ref_commands]);
3214 os << "reference \""
3215 << convert_command_inset_arg(p.verbatim_item())
3218 if (t.cs() == "vref" || t.cs() == "vpageref")
3219 preamble.registerAutomaticallyLoadedPackage("varioref");
3222 // LyX does not support optional arguments of ref commands
3223 handle_ert(os, t.asInput() + '[' + opt + "]{" +
3224 p.verbatim_item() + "}", context);
3228 else if (use_natbib &&
3229 is_known(t.cs(), known_natbib_commands) &&
3230 ((t.cs() != "citefullauthor" &&
3231 t.cs() != "citeyear" &&
3232 t.cs() != "citeyearpar") ||
3233 p.next_token().asInput() != "*")) {
3234 context.check_layout(os);
3235 string command = t.cs();
3236 if (p.next_token().asInput() == "*") {
3240 if (command == "citefullauthor")
3241 // alternative name for "\\citeauthor*"
3242 command = "citeauthor*";
3244 // text before the citation
3246 // text after the citation
3248 get_cite_arguments(p, true, before, after);
3250 if (command == "cite") {
3251 // \cite without optional argument means
3252 // \citet, \cite with at least one optional
3253 // argument means \citep.
3254 if (before.empty() && after.empty())
3259 if (before.empty() && after == "[]")
3260 // avoid \citet[]{a}
3262 else if (before == "[]" && after == "[]") {
3263 // avoid \citet[][]{a}
3267 // remove the brackets around after and before
3268 if (!after.empty()) {
3270 after.erase(after.length() - 1, 1);
3271 after = convert_command_inset_arg(after);
3273 if (!before.empty()) {
3275 before.erase(before.length() - 1, 1);
3276 before = convert_command_inset_arg(before);
3278 begin_command_inset(os, "citation", command);
3279 os << "after " << '"' << after << '"' << "\n";
3280 os << "before " << '"' << before << '"' << "\n";
3282 << convert_command_inset_arg(p.verbatim_item())
3287 else if (use_jurabib &&
3288 is_known(t.cs(), known_jurabib_commands) &&
3289 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3290 context.check_layout(os);
3291 string command = t.cs();
3292 if (p.next_token().asInput() == "*") {
3296 char argumentOrder = '\0';
3297 vector<string> const options =
3298 preamble.getPackageOptions("jurabib");
3299 if (find(options.begin(), options.end(),
3300 "natbiborder") != options.end())
3301 argumentOrder = 'n';
3302 else if (find(options.begin(), options.end(),
3303 "jurabiborder") != options.end())
3304 argumentOrder = 'j';
3306 // text before the citation
3308 // text after the citation
3310 get_cite_arguments(p, argumentOrder != 'j', before, after);
3312 string const citation = p.verbatim_item();
3313 if (!before.empty() && argumentOrder == '\0') {
3314 cerr << "Warning: Assuming argument order "
3315 "of jurabib version 0.6 for\n'"
3316 << command << before << after << '{'
3317 << citation << "}'.\n"
3318 "Add 'jurabiborder' to the jurabib "
3319 "package options if you used an\n"
3320 "earlier jurabib version." << endl;
3322 if (!after.empty()) {
3324 after.erase(after.length() - 1, 1);
3326 if (!before.empty()) {
3328 before.erase(before.length() - 1, 1);
3330 begin_command_inset(os, "citation", command);
3331 os << "after " << '"' << after << '"' << "\n";
3332 os << "before " << '"' << before << '"' << "\n";
3333 os << "key " << '"' << citation << '"' << "\n";
3337 else if (t.cs() == "cite"
3338 || t.cs() == "nocite") {
3339 context.check_layout(os);
3340 string after = convert_command_inset_arg(p.getArg('[', ']'));
3341 string key = convert_command_inset_arg(p.verbatim_item());
3342 // store the case that it is "\nocite{*}" to use it later for
3345 begin_command_inset(os, "citation", t.cs());
3346 os << "after " << '"' << after << '"' << "\n";
3347 os << "key " << '"' << key << '"' << "\n";
3349 } else if (t.cs() == "nocite")
3353 else if (t.cs() == "index" ||
3354 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3355 context.check_layout(os);
3356 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3357 p.getArg('[', ']') : "";
3358 string const kind = arg.empty() ? "idx" : arg;
3359 begin_inset(os, "Index ");
3360 os << kind << "\nstatus collapsed\n";
3361 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3364 preamble.registerAutomaticallyLoadedPackage("splitidx");
3367 else if (t.cs() == "nomenclature") {
3368 context.check_layout(os);
3369 begin_command_inset(os, "nomenclature", "nomenclature");
3370 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3371 if (!prefix.empty())
3372 os << "prefix " << '"' << prefix << '"' << "\n";
3373 os << "symbol " << '"'
3374 << convert_command_inset_arg(p.verbatim_item());
3375 os << "\"\ndescription \""
3376 << convert_command_inset_arg(p.verbatim_item())
3379 preamble.registerAutomaticallyLoadedPackage("nomencl");
3382 else if (t.cs() == "label") {
3383 context.check_layout(os);
3384 begin_command_inset(os, "label", "label");
3386 << convert_command_inset_arg(p.verbatim_item())
3391 else if (t.cs() == "printindex") {
3392 context.check_layout(os);
3393 begin_command_inset(os, "index_print", "printindex");
3394 os << "type \"idx\"\n";
3396 skip_spaces_braces(p);
3397 preamble.registerAutomaticallyLoadedPackage("makeidx");
3398 if (preamble.use_indices() == "true")
3399 preamble.registerAutomaticallyLoadedPackage("splitidx");
3402 else if (t.cs() == "printnomenclature") {
3404 string width_type = "";
3405 context.check_layout(os);
3406 begin_command_inset(os, "nomencl_print", "printnomenclature");
3407 // case of a custom width
3409 width = p.getArg('[', ']');
3410 width = translate_len(width);
3411 width_type = "custom";
3413 // case of no custom width
3414 // the case of no custom width but the width set
3415 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3416 // because the user could have set anything, not only the width
3417 // of the longest label (which would be width_type = "auto")
3418 string label = convert_command_inset_arg(p.getArg('{', '}'));
3419 if (label.empty() && width_type.empty())
3420 width_type = "none";
3421 os << "set_width \"" << width_type << "\"\n";
3422 if (width_type == "custom")
3423 os << "width \"" << width << '\"';
3425 skip_spaces_braces(p);
3426 preamble.registerAutomaticallyLoadedPackage("nomencl");
3429 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3430 context.check_layout(os);
3431 begin_inset(os, "script ");
3432 os << t.cs().substr(4) << '\n';
3433 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3435 if (t.cs() == "textsubscript")
3436 preamble.registerAutomaticallyLoadedPackage("subscript");
3439 else if ((where = is_known(t.cs(), known_quotes))) {
3440 context.check_layout(os);
3441 begin_inset(os, "Quotes ");
3442 os << known_coded_quotes[where - known_quotes];
3444 // LyX adds {} after the quote, so we have to eat
3445 // spaces here if there are any before a possible
3447 eat_whitespace(p, os, context, false);
3451 else if ((where = is_known(t.cs(), known_sizes)) &&
3452 context.new_layout_allowed) {
3453 context.check_layout(os);
3454 TeXFont const oldFont = context.font;
3455 context.font.size = known_coded_sizes[where - known_sizes];
3456 output_font_change(os, oldFont, context.font);
3457 eat_whitespace(p, os, context, false);
3460 else if ((where = is_known(t.cs(), known_font_families)) &&
3461 context.new_layout_allowed) {
3462 context.check_layout(os);
3463 TeXFont const oldFont = context.font;
3464 context.font.family =
3465 known_coded_font_families[where - known_font_families];
3466 output_font_change(os, oldFont, context.font);
3467 eat_whitespace(p, os, context, false);
3470 else if ((where = is_known(t.cs(), known_font_series)) &&
3471 context.new_layout_allowed) {
3472 context.check_layout(os);
3473 TeXFont const oldFont = context.font;
3474 context.font.series =
3475 known_coded_font_series[where - known_font_series];
3476 output_font_change(os, oldFont, context.font);
3477 eat_whitespace(p, os, context, false);
3480 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3481 context.new_layout_allowed) {
3482 context.check_layout(os);
3483 TeXFont const oldFont = context.font;
3484 context.font.shape =
3485 known_coded_font_shapes[where - known_font_shapes];
3486 output_font_change(os, oldFont, context.font);
3487 eat_whitespace(p, os, context, false);
3489 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3490 context.new_layout_allowed) {
3491 context.check_layout(os);
3492 TeXFont const oldFont = context.font;
3493 context.font.init();
3494 context.font.size = oldFont.size;
3495 context.font.family =
3496 known_coded_font_families[where - known_old_font_families];
3497 output_font_change(os, oldFont, context.font);
3498 eat_whitespace(p, os, context, false);
3501 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3502 context.new_layout_allowed) {
3503 context.check_layout(os);
3504 TeXFont const oldFont = context.font;
3505 context.font.init();
3506 context.font.size = oldFont.size;
3507 context.font.series =
3508 known_coded_font_series[where - known_old_font_series];
3509 output_font_change(os, oldFont, context.font);
3510 eat_whitespace(p, os, context, false);
3513 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3514 context.new_layout_allowed) {
3515 context.check_layout(os);
3516 TeXFont const oldFont = context.font;
3517 context.font.init();
3518 context.font.size = oldFont.size;
3519 context.font.shape =
3520 known_coded_font_shapes[where - known_old_font_shapes];
3521 output_font_change(os, oldFont, context.font);
3522 eat_whitespace(p, os, context, false);
3525 else if (t.cs() == "selectlanguage") {
3526 context.check_layout(os);
3527 // save the language for the case that a
3528 // \foreignlanguage is used
3529 context.font.language = babel2lyx(p.verbatim_item());
3530 os << "\n\\lang " << context.font.language << "\n";
3533 else if (t.cs() == "foreignlanguage") {
3534 string const lang = babel2lyx(p.verbatim_item());
3535 parse_text_attributes(p, os, FLAG_ITEM, outer,
3537 context.font.language, lang);
3540 else if (prefixIs(t.cs(), "text")
3541 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3542 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3544 // We have to output the whole command if it has an option
3545 // because LyX doesn't support this yet, see bug #8214,
3546 // only if there is a single option specifying a variant, we can handle it.
3548 string langopts = p.getOpt();
3549 // check if the option contains a variant, if yes, extract it
3550 string::size_type pos_var = langopts.find("variant");
3551 string::size_type i = langopts.find(',');
3552 string::size_type k = langopts.find('=', pos_var);
3553 if (pos_var != string::npos && i == string::npos) {
3555 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3556 lang = preamble.polyglossia2lyx(variant);
3557 parse_text_attributes(p, os, FLAG_ITEM, outer,
3559 context.font.language, lang);
3561 handle_ert(os, t.asInput() + langopts, context);
3563 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3564 parse_text_attributes(p, os, FLAG_ITEM, outer,
3566 context.font.language, lang);
3570 else if (t.cs() == "inputencoding") {
3571 // nothing to write here
3572 string const enc = subst(p.verbatim_item(), "\n", " ");
3576 else if ((where = is_known(t.cs(), known_special_chars))) {
3577 context.check_layout(os);
3578 os << "\\SpecialChar \\"
3579 << known_coded_special_chars[where - known_special_chars]
3581 skip_spaces_braces(p);
3584 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3585 context.check_layout(os);
3586 os << "\\SpecialChar \\nobreakdash-\n";
3590 else if (t.cs() == "textquotedbl") {
3591 context.check_layout(os);
3596 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3597 context.check_layout(os);
3598 os << "\\SpecialChar \\@.\n";
3602 else if (t.cs() == "-") {
3603 context.check_layout(os);
3604 os << "\\SpecialChar \\-\n";
3607 else if (t.cs() == "textasciitilde") {
3608 context.check_layout(os);
3610 skip_spaces_braces(p);
3613 else if (t.cs() == "textasciicircum") {
3614 context.check_layout(os);
3616 skip_spaces_braces(p);
3619 else if (t.cs() == "textbackslash") {
3620 context.check_layout(os);
3621 os << "\n\\backslash\n";
3622 skip_spaces_braces(p);
3625 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3626 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3628 context.check_layout(os);
3632 else if (t.cs() == "char") {
3633 context.check_layout(os);
3634 if (p.next_token().character() == '`') {
3636 if (p.next_token().cs() == "\"") {
3641 handle_ert(os, "\\char`", context);
3644 handle_ert(os, "\\char", context);
3648 else if (t.cs() == "verb") {
3649 context.check_layout(os);
3650 char const delimiter = p.next_token().character();
3651 string const arg = p.getArg(delimiter, delimiter);
3653 oss << "\\verb" << delimiter << arg << delimiter;
3654 handle_ert(os, oss.str(), context);
3657 // Problem: \= creates a tabstop inside the tabbing environment
3658 // and else an accent. In the latter case we really would want
3659 // \={o} instead of \= o.
3660 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3661 handle_ert(os, t.asInput(), context);
3663 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3664 else if (t.cs().size() == 1
3665 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3666 context.check_layout(os);
3667 // try to see whether the string is in unicodesymbols
3670 string command = t.asInput() + "{"
3671 + trimSpaceAndEol(p.verbatim_item())
3674 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3675 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3676 termination, rem, &req);
3679 cerr << "When parsing " << command
3680 << ", result is " << to_utf8(s)
3681 << "+" << to_utf8(rem) << endl;
3683 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3684 preamble.registerAutomaticallyLoadedPackage(*it);
3686 // we did not find a non-ert version
3687 handle_ert(os, command, context);
3690 else if (t.cs() == "\\") {
3691 context.check_layout(os);
3693 handle_ert(os, "\\\\" + p.getOpt(), context);
3694 else if (p.next_token().asInput() == "*") {
3696 // getOpt() eats the following space if there
3697 // is no optional argument, but that is OK
3698 // here since it has no effect in the output.
3699 handle_ert(os, "\\\\*" + p.getOpt(), context);
3702 begin_inset(os, "Newline newline");
3707 else if (t.cs() == "newline" ||
3708 (t.cs() == "linebreak" && !p.hasOpt())) {
3709 context.check_layout(os);
3710 begin_inset(os, "Newline ");
3713 skip_spaces_braces(p);
3716 else if (t.cs() == "input" || t.cs() == "include"
3717 || t.cs() == "verbatiminput") {
3718 string name = t.cs();
3719 if (t.cs() == "verbatiminput"
3720 && p.next_token().asInput() == "*")
3721 name += p.get_token().asInput();
3722 context.check_layout(os);
3723 string filename(normalize_filename(p.getArg('{', '}')));
3724 string const path = getMasterFilePath();
3725 // We want to preserve relative / absolute filenames,
3726 // therefore path is only used for testing
3727 if ((t.cs() == "include" || t.cs() == "input") &&
3728 !makeAbsPath(filename, path).exists()) {
3729 // The file extension is probably missing.
3730 // Now try to find it out.
3731 string const tex_name =
3732 find_file(filename, path,
3733 known_tex_extensions);
3734 if (!tex_name.empty())
3735 filename = tex_name;
3737 bool external = false;
3739 if (makeAbsPath(filename, path).exists()) {
3740 string const abstexname =
3741 makeAbsPath(filename, path).absFileName();
3742 string const abslyxname =
3743 changeExtension(abstexname, ".lyx");
3744 string const absfigname =
3745 changeExtension(abstexname, ".fig");
3746 fix_relative_filename(filename);
3747 string const lyxname =
3748 changeExtension(filename, ".lyx");
3750 external = FileName(absfigname).exists();
3751 if (t.cs() == "input") {
3752 string const ext = getExtension(abstexname);
3754 // Combined PS/LaTeX:
3755 // x.eps, x.pstex_t (old xfig)
3756 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3757 FileName const absepsname(
3758 changeExtension(abstexname, ".eps"));
3759 FileName const abspstexname(
3760 changeExtension(abstexname, ".pstex"));
3761 bool const xfigeps =
3762 (absepsname.exists() ||
3763 abspstexname.exists()) &&
3766 // Combined PDF/LaTeX:
3767 // x.pdf, x.pdftex_t (old xfig)
3768 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3769 FileName const abspdfname(
3770 changeExtension(abstexname, ".pdf"));
3771 bool const xfigpdf =
3772 abspdfname.exists() &&
3773 (ext == "pdftex_t" || ext == "pdf_t");
3777 // Combined PS/PDF/LaTeX:
3778 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3779 string const absbase2(
3780 removeExtension(abstexname) + "_pspdftex");
3781 FileName const abseps2name(
3782 addExtension(absbase2, ".eps"));
3783 FileName const abspdf2name(
3784 addExtension(absbase2, ".pdf"));
3785 bool const xfigboth =
3786 abspdf2name.exists() &&
3787 abseps2name.exists() && ext == "pspdftex";
3789 xfig = xfigpdf || xfigeps || xfigboth;
3790 external = external && xfig;
3793 outname = changeExtension(filename, ".fig");
3795 // Don't try to convert, the result
3796 // would be full of ERT.
3798 } else if (t.cs() != "verbatiminput" &&
3799 tex2lyx(abstexname, FileName(abslyxname),
3806 cerr << "Warning: Could not find included file '"
3807 << filename << "'." << endl;
3811 begin_inset(os, "External\n");
3812 os << "\ttemplate XFig\n"
3813 << "\tfilename " << outname << '\n';
3814 registerExternalTemplatePackages("XFig");
3816 begin_command_inset(os, "include", name);
3817 os << "preview false\n"
3818 "filename \"" << outname << "\"\n";
3819 if (t.cs() == "verbatiminput")
3820 preamble.registerAutomaticallyLoadedPackage("verbatim");
3825 else if (t.cs() == "bibliographystyle") {
3826 // store new bibliographystyle
3827 bibliographystyle = p.verbatim_item();
3828 // If any other command than \bibliography and
3829 // \nocite{*} follows, we need to output the style
3830 // (because it might be used by that command).
3831 // Otherwise, it will automatically be output by LyX.
3834 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3835 if (t2.cat() == catBegin)
3837 if (t2.cat() != catEscape)
3839 if (t2.cs() == "nocite") {
3840 if (p.getArg('{', '}') == "*")
3842 } else if (t2.cs() == "bibliography")
3849 "\\bibliographystyle{" + bibliographystyle + '}',
3854 else if (t.cs() == "bibliography") {
3855 context.check_layout(os);
3856 begin_command_inset(os, "bibtex", "bibtex");
3857 if (!btprint.empty()) {
3858 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3859 // clear the string because the next BibTeX inset can be without the
3860 // \nocite{*} option
3863 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3864 // Do we have a bibliographystyle set?
3865 if (!bibliographystyle.empty())
3866 os << "options " << '"' << bibliographystyle << '"' << "\n";
3870 else if (t.cs() == "parbox") {
3871 // Test whether this is an outer box of a shaded box
3873 // swallow arguments
3874 while (p.hasOpt()) {
3876 p.skip_spaces(true);
3879 p.skip_spaces(true);
3881 if (p.next_token().cat() == catBegin)
3883 p.skip_spaces(true);
3884 Token to = p.get_token();
3885 bool shaded = false;
3886 if (to.asInput() == "\\begin") {
3887 p.skip_spaces(true);
3888 if (p.getArg('{', '}') == "shaded")
3893 parse_outer_box(p, os, FLAG_ITEM, outer,
3894 context, "parbox", "shaded");
3896 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3900 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3901 t.cs() == "shadowbox" || t.cs() == "doublebox")
3902 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3904 else if (t.cs() == "framebox") {
3905 if (p.next_token().character() == '(') {
3906 //the syntax is: \framebox(x,y)[position]{content}
3907 string arg = t.asInput();
3908 arg += p.getFullParentheseArg();
3909 arg += p.getFullOpt();
3910 eat_whitespace(p, os, context, false);
3911 handle_ert(os, arg + '{', context);
3912 parse_text(p, os, FLAG_ITEM, outer, context);
3913 handle_ert(os, "}", context);
3915 string special = p.getFullOpt();
3916 special += p.getOpt();
3917 // LyX does not yet support \framebox without any option
3918 if (!special.empty())
3919 parse_outer_box(p, os, FLAG_ITEM, outer,
3920 context, t.cs(), special);
3922 eat_whitespace(p, os, context, false);
3923 handle_ert(os, "\\framebox{", context);
3924 parse_text(p, os, FLAG_ITEM, outer, context);
3925 handle_ert(os, "}", context);
3930 //\makebox() is part of the picture environment and different from \makebox{}
3931 //\makebox{} will be parsed by parse_box
3932 else if (t.cs() == "makebox") {
3933 if (p.next_token().character() == '(') {
3934 //the syntax is: \makebox(x,y)[position]{content}
3935 string arg = t.asInput();
3936 arg += p.getFullParentheseArg();
3937 arg += p.getFullOpt();
3938 eat_whitespace(p, os, context, false);
3939 handle_ert(os, arg + '{', context);
3940 parse_text(p, os, FLAG_ITEM, outer, context);
3941 handle_ert(os, "}", context);
3943 //the syntax is: \makebox[width][position]{content}
3944 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3948 else if (t.cs() == "smallskip" ||
3949 t.cs() == "medskip" ||
3950 t.cs() == "bigskip" ||
3951 t.cs() == "vfill") {
3952 context.check_layout(os);
3953 begin_inset(os, "VSpace ");
3956 skip_spaces_braces(p);
3959 else if ((where = is_known(t.cs(), known_spaces))) {
3960 context.check_layout(os);
3961 begin_inset(os, "space ");
3962 os << '\\' << known_coded_spaces[where - known_spaces]
3965 // LaTeX swallows whitespace after all spaces except
3966 // "\\,". We have to do that here, too, because LyX
3967 // adds "{}" which would make the spaces significant.
3969 eat_whitespace(p, os, context, false);
3970 // LyX adds "{}" after all spaces except "\\ " and
3971 // "\\,", so we have to remove "{}".
3972 // "\\,{}" is equivalent to "\\," in LaTeX, so we
3973 // remove the braces after "\\,", too.
3978 else if (t.cs() == "newpage" ||
3979 (t.cs() == "pagebreak" && !p.hasOpt()) ||
3980 t.cs() == "clearpage" ||
3981 t.cs() == "cleardoublepage") {
3982 context.check_layout(os);
3983 begin_inset(os, "Newpage ");
3986 skip_spaces_braces(p);
3989 else if (t.cs() == "DeclareRobustCommand" ||
3990 t.cs() == "DeclareRobustCommandx" ||
3991 t.cs() == "newcommand" ||
3992 t.cs() == "newcommandx" ||
3993 t.cs() == "providecommand" ||
3994 t.cs() == "providecommandx" ||
3995 t.cs() == "renewcommand" ||
3996 t.cs() == "renewcommandx") {
3997 // DeclareRobustCommand, DeclareRobustCommandx,
3998 // providecommand and providecommandx could be handled
3999 // by parse_command(), but we need to call
4000 // add_known_command() here.
4001 string name = t.asInput();
4002 if (p.next_token().asInput() == "*") {
4003 // Starred form. Eat '*'
4007 string const command = p.verbatim_item();
4008 string const opt1 = p.getFullOpt();
4009 string const opt2 = p.getFullOpt();
4010 add_known_command(command, opt1, !opt2.empty());
4011 string const ert = name + '{' + command + '}' +
4013 '{' + p.verbatim_item() + '}';
4015 if (t.cs() == "DeclareRobustCommand" ||
4016 t.cs() == "DeclareRobustCommandx" ||
4017 t.cs() == "providecommand" ||
4018 t.cs() == "providecommandx" ||
4019 name[name.length()-1] == '*')
4020 handle_ert(os, ert, context);
4022 context.check_layout(os);
4023 begin_inset(os, "FormulaMacro");
4029 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4030 // let could be handled by parse_command(),
4031 // but we need to call add_known_command() here.
4032 string ert = t.asInput();
4035 if (p.next_token().cat() == catBegin) {
4036 name = p.verbatim_item();
4037 ert += '{' + name + '}';
4039 name = p.verbatim_item();
4044 if (p.next_token().cat() == catBegin) {
4045 command = p.verbatim_item();
4046 ert += '{' + command + '}';
4048 command = p.verbatim_item();
4051 // If command is known, make name known too, to parse
4052 // its arguments correctly. For this reason we also
4053 // have commands in syntax.default that are hardcoded.
4054 CommandMap::iterator it = known_commands.find(command);
4055 if (it != known_commands.end())
4056 known_commands[t.asInput()] = it->second;
4057 handle_ert(os, ert, context);
4060 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4061 bool starred = false;
4062 if (p.next_token().asInput() == "*") {
4066 string name = t.asInput();
4067 string const length = p.verbatim_item();
4070 bool valid = splitLatexLength(length, valstring, unit);
4071 bool known_hspace = false;
4072 bool known_vspace = false;
4073 bool known_unit = false;
4076 istringstream iss(valstring);
4079 if (t.cs()[0] == 'h') {
4080 if (unit == "\\fill") {
4085 known_hspace = true;
4088 if (unit == "\\smallskipamount") {
4090 known_vspace = true;
4091 } else if (unit == "\\medskipamount") {
4093 known_vspace = true;
4094 } else if (unit == "\\bigskipamount") {
4096 known_vspace = true;
4097 } else if (unit == "\\fill") {
4099 known_vspace = true;
4103 if (!known_hspace && !known_vspace) {
4104 switch (unitFromString(unit)) {
4125 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4126 // Literal horizontal length or known variable
4127 context.check_layout(os);
4128 begin_inset(os, "space ");
4136 if (known_unit && !known_hspace)
4138 << translate_len(length);
4140 } else if (known_unit || known_vspace) {
4141 // Literal vertical length or known variable
4142 context.check_layout(os);
4143 begin_inset(os, "VSpace ");
4151 // LyX can't handle other length variables in Inset VSpace/space
4156 handle_ert(os, name + '{' + unit + '}', context);
4157 else if (value == -1.0)
4158 handle_ert(os, name + "{-" + unit + '}', context);
4160 handle_ert(os, name + '{' + valstring + unit + '}', context);
4162 handle_ert(os, name + '{' + length + '}', context);
4166 // The single '=' is meant here.
4167 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4169 context.check_layout(os);
4170 begin_inset(os, "Flex ");
4171 os << to_utf8(newinsetlayout->name()) << '\n'
4172 << "status collapsed\n";
4173 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4177 else if (t.cs() == "includepdf") {
4179 string const arg = p.getArg('[', ']');
4180 map<string, string> opts;
4181 vector<string> keys;
4182 split_map(arg, opts, keys);
4183 string name = normalize_filename(p.verbatim_item());
4184 string const path = getMasterFilePath();
4185 // We want to preserve relative / absolute filenames,
4186 // therefore path is only used for testing
4187 if (!makeAbsPath(name, path).exists()) {
4188 // The file extension is probably missing.
4189 // Now try to find it out.
4190 char const * const pdfpages_format[] = {"pdf", 0};
4191 string const pdftex_name =
4192 find_file(name, path, pdfpages_format);
4193 if (!pdftex_name.empty()) {
4198 if (makeAbsPath(name, path).exists())
4199 fix_relative_filename(name);
4201 cerr << "Warning: Could not find file '"
4202 << name << "'." << endl;
4204 context.check_layout(os);
4205 begin_inset(os, "External\n\ttemplate ");
4206 os << "PDFPages\n\tfilename "
4208 // parse the options
4209 if (opts.find("pages") != opts.end())
4210 os << "\textra LaTeX \"pages="
4211 << opts["pages"] << "\"\n";
4212 if (opts.find("angle") != opts.end())
4213 os << "\trotateAngle "
4214 << opts["angle"] << '\n';
4215 if (opts.find("origin") != opts.end()) {
4217 string const opt = opts["origin"];
4218 if (opt == "tl") ss << "topleft";
4219 if (opt == "bl") ss << "bottomleft";
4220 if (opt == "Bl") ss << "baselineleft";
4221 if (opt == "c") ss << "center";
4222 if (opt == "tc") ss << "topcenter";
4223 if (opt == "bc") ss << "bottomcenter";
4224 if (opt == "Bc") ss << "baselinecenter";
4225 if (opt == "tr") ss << "topright";
4226 if (opt == "br") ss << "bottomright";
4227 if (opt == "Br") ss << "baselineright";
4228 if (!ss.str().empty())
4229 os << "\trotateOrigin " << ss.str() << '\n';
4231 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4233 if (opts.find("width") != opts.end())
4235 << translate_len(opts["width"]) << '\n';
4236 if (opts.find("height") != opts.end())
4238 << translate_len(opts["height"]) << '\n';
4239 if (opts.find("keepaspectratio") != opts.end())
4240 os << "\tkeepAspectRatio\n";
4242 context.check_layout(os);
4243 registerExternalTemplatePackages("PDFPages");
4246 else if (t.cs() == "loadgame") {
4248 string name = normalize_filename(p.verbatim_item());
4249 string const path = getMasterFilePath();
4250 // We want to preserve relative / absolute filenames,
4251 // therefore path is only used for testing
4252 if (!makeAbsPath(name, path).exists()) {
4253 // The file extension is probably missing.
4254 // Now try to find it out.
4255 char const * const lyxskak_format[] = {"fen", 0};
4256 string const lyxskak_name =
4257 find_file(name, path, lyxskak_format);
4258 if (!lyxskak_name.empty())
4259 name = lyxskak_name;
4261 if (makeAbsPath(name, path).exists())
4262 fix_relative_filename(name);
4264 cerr << "Warning: Could not find file '"
4265 << name << "'." << endl;
4266 context.check_layout(os);
4267 begin_inset(os, "External\n\ttemplate ");
4268 os << "ChessDiagram\n\tfilename "
4271 context.check_layout(os);
4272 // after a \loadgame follows a \showboard
4273 if (p.get_token().asInput() == "showboard")
4275 registerExternalTemplatePackages("ChessDiagram");
4279 // try to see whether the string is in unicodesymbols
4280 // Only use text mode commands, since we are in text mode here,
4281 // and math commands may be invalid (bug 6797)
4285 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4286 Encodings::TEXT_CMD, termination, rem, &req);
4289 cerr << "When parsing " << t.cs()
4290 << ", result is " << to_utf8(s)
4291 << "+" << to_utf8(rem) << endl;
4292 context.check_layout(os);
4295 skip_spaces_braces(p);
4296 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4297 preamble.registerAutomaticallyLoadedPackage(*it);
4299 //cerr << "#: " << t << " mode: " << mode << endl;
4300 // heuristic: read up to next non-nested space
4302 string s = t.asInput();
4303 string z = p.verbatim_item();
4304 while (p.good() && z != " " && z.size()) {
4305 //cerr << "read: " << z << endl;
4307 z = p.verbatim_item();
4309 cerr << "found ERT: " << s << endl;
4310 handle_ert(os, s + ' ', context);
4313 string name = t.asInput();
4314 if (p.next_token().asInput() == "*") {
4315 // Starred commands like \vspace*{}
4316 p.get_token(); // Eat '*'
4319 if (!parse_command(name, p, os, outer, context))
4320 handle_ert(os, name, context);
4324 if (flags & FLAG_LEAVE) {
4325 flags &= ~FLAG_LEAVE;