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
122 * SJIS anf Bg5 cannot be supported as this is not
124 * JIS does not work with LyX's encoding conversion
126 const char * const supported_CJK_encodings[] = {
127 "EUC-JP", "KS", "GB", "UTF8", 0};
130 * the same as supported_CJK_encodings with their corresponding LyX language name
131 * please keep this in sync with supported_CJK_encodings line by line!
133 const char * const coded_supported_CJK_encodings[] = {
134 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional", 0};
136 string CJK2lyx(string const & encoding)
138 char const * const * where = is_known(encoding, supported_CJK_encodings);
140 return coded_supported_CJK_encodings[where - supported_CJK_encodings];
146 * The starred forms are also known except for "citefullauthor",
147 * "citeyear" and "citeyearpar".
149 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
150 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
151 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
155 * No starred form other than "cite*" known.
157 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
158 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
159 // jurabib commands not (yet) supported by LyX:
161 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
162 // "footciteauthor", "footciteyear", "footciteyearpar",
163 "citefield", "citetitle", 0 };
165 /// LaTeX names for quotes
166 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
167 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
168 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
169 "guilsinglleft", "frq", "guilsinglright", 0};
171 /// the same as known_quotes with .lyx names
172 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
173 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
174 "gld", "grd", "gls", "ers", "fls",
175 "fls", "frs", "frs", 0};
177 /// LaTeX names for font sizes
178 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
179 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
181 /// the same as known_sizes with .lyx names
182 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
183 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
185 /// LaTeX 2.09 names for font families
186 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
188 /// LaTeX names for font families
189 char const * const known_font_families[] = { "rmfamily", "sffamily",
192 /// LaTeX names for font family changing commands
193 char const * const known_text_font_families[] = { "textrm", "textsf",
196 /// The same as known_old_font_families, known_font_families and
197 /// known_text_font_families with .lyx names
198 char const * const known_coded_font_families[] = { "roman", "sans",
201 /// LaTeX 2.09 names for font series
202 char const * const known_old_font_series[] = { "bf", 0};
204 /// LaTeX names for font series
205 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
207 /// LaTeX names for font series changing commands
208 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
210 /// The same as known_old_font_series, known_font_series and
211 /// known_text_font_series with .lyx names
212 char const * const known_coded_font_series[] = { "bold", "medium", 0};
214 /// LaTeX 2.09 names for font shapes
215 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
217 /// LaTeX names for font shapes
218 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
221 /// LaTeX names for font shape changing commands
222 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
225 /// The same as known_old_font_shapes, known_font_shapes and
226 /// known_text_font_shapes with .lyx names
227 char const * const known_coded_font_shapes[] = { "italic", "slanted",
228 "smallcaps", "up", 0};
230 /// Known special characters which need skip_spaces_braces() afterwards
231 char const * const known_special_chars[] = {"ldots", "lyxarrow",
232 "textcompwordmark", "slash", 0};
234 /// the same as known_special_chars with .lyx names
235 char const * const known_coded_special_chars[] = {"ldots{}", "menuseparator",
236 "textcompwordmark{}", "slash{}", 0};
239 * Graphics file extensions known by the dvips driver of the graphics package.
240 * These extensions are used to complete the filename of an included
241 * graphics file if it does not contain an extension.
242 * The order must be the same that latex uses to find a file, because we
243 * will use the first extension that matches.
244 * This is only an approximation for the common cases. If we would want to
245 * do it right in all cases, we would need to know which graphics driver is
246 * used and know the extensions of every driver of the graphics package.
248 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
249 "ps.gz", "eps.Z", "ps.Z", 0};
252 * Graphics file extensions known by the pdftex driver of the graphics package.
253 * \sa known_dvips_graphics_formats
255 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
259 * Known file extensions for TeX files as used by \\include.
261 char const * const known_tex_extensions[] = {"tex", 0};
263 /// spaces known by InsetSpace
264 char const * const known_spaces[] = { " ", "space", ",",
265 "thinspace", "quad", "qquad", "enspace", "enskip",
266 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
267 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
268 "upbracefill", "downbracefill", 0};
270 /// the same as known_spaces with .lyx names
271 char const * const known_coded_spaces[] = { "space{}", "space{}",
272 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
273 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
274 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
275 "upbracefill{}", "downbracefill{}", 0};
277 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
278 /// them in ERT. "LaTeXe" must come before "LaTeX"!
279 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
280 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
281 int const known_phrase_lengths[] = {3, 5, 7, 0};
283 // string to store the float type to be able to determine the type of subfloats
284 string float_type = "";
287 /// splits "x=z, y=b" into a map and an ordered keyword vector
288 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
293 keys.resize(v.size());
294 for (size_t i = 0; i < v.size(); ++i) {
295 size_t const pos = v[i].find('=');
296 string const index = trimSpaceAndEol(v[i].substr(0, pos));
297 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
305 * Split a LaTeX length into value and unit.
306 * The latter can be a real unit like "pt", or a latex length variable
307 * like "\textwidth". The unit may contain additional stuff like glue
308 * lengths, but we don't care, because such lengths are ERT anyway.
309 * \returns true if \p value and \p unit are valid.
311 bool splitLatexLength(string const & len, string & value, string & unit)
315 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
316 //'4,5' is a valid LaTeX length number. Change it to '4.5'
317 string const length = subst(len, ',', '.');
318 if (i == string::npos)
321 if (len[0] == '\\') {
322 // We had something like \textwidth without a factor
328 value = trimSpaceAndEol(string(length, 0, i));
332 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
333 if (contains(len, '\\'))
334 unit = trimSpaceAndEol(string(len, i));
336 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
341 /// A simple function to translate a latex length to something LyX can
342 /// understand. Not perfect, but rather best-effort.
343 bool translate_len(string const & length, string & valstring, string & unit)
345 if (!splitLatexLength(length, valstring, unit))
347 // LyX uses percent values
349 istringstream iss(valstring);
354 string const percentval = oss.str();
356 if (unit.empty() || unit[0] != '\\')
358 string::size_type const i = unit.find(' ');
359 string const endlen = (i == string::npos) ? string() : string(unit, i);
360 if (unit == "\\textwidth") {
361 valstring = percentval;
362 unit = "text%" + endlen;
363 } else if (unit == "\\columnwidth") {
364 valstring = percentval;
365 unit = "col%" + endlen;
366 } else if (unit == "\\paperwidth") {
367 valstring = percentval;
368 unit = "page%" + endlen;
369 } else if (unit == "\\linewidth") {
370 valstring = percentval;
371 unit = "line%" + endlen;
372 } else if (unit == "\\paperheight") {
373 valstring = percentval;
374 unit = "pheight%" + endlen;
375 } else if (unit == "\\textheight") {
376 valstring = percentval;
377 unit = "theight%" + endlen;
385 string translate_len(string const & length)
389 if (translate_len(length, value, unit))
391 // If the input is invalid, return what we have.
399 * Translates a LaTeX length into \p value, \p unit and
400 * \p special parts suitable for a box inset.
401 * The difference from translate_len() is that a box inset knows about
402 * some special "units" that are stored in \p special.
404 void translate_box_len(string const & length, string & value, string & unit, string & special)
406 if (translate_len(length, value, unit)) {
407 if (unit == "\\height" || unit == "\\depth" ||
408 unit == "\\totalheight" || unit == "\\width") {
409 special = unit.substr(1);
410 // The unit is not used, but LyX requires a dummy setting
423 * Find a file with basename \p name in path \p path and an extension
426 string find_file(string const & name, string const & path,
427 char const * const * extensions)
429 for (char const * const * what = extensions; *what; ++what) {
430 string const trial = addExtension(name, *what);
431 if (makeAbsPath(trial, path).exists())
438 void begin_inset(ostream & os, string const & name)
440 os << "\n\\begin_inset " << name;
444 void begin_command_inset(ostream & os, string const & name,
445 string const & latexname)
447 begin_inset(os, "CommandInset ");
448 os << name << "\nLatexCommand " << latexname << '\n';
452 void end_inset(ostream & os)
454 os << "\n\\end_inset\n\n";
458 bool skip_braces(Parser & p)
460 if (p.next_token().cat() != catBegin)
463 if (p.next_token().cat() == catEnd) {
472 /// replace LaTeX commands in \p s from the unicodesymbols file with their
474 docstring convert_unicodesymbols(docstring s)
477 for (size_t i = 0; i < s.size();) {
486 docstring parsed = encodings.fromLaTeXCommand(s,
487 Encodings::TEXT_CMD, termination, rem, &req);
488 set<string>::const_iterator it = req.begin();
489 set<string>::const_iterator en = req.end();
490 for (; it != en; ++it)
491 preamble.registerAutomaticallyLoadedPackage(*it);
494 if (s.empty() || s[0] != '\\')
503 /// try to convert \p s to a valid InsetCommand argument
504 string convert_command_inset_arg(string s)
507 // since we don't know the input encoding we can't use from_utf8
508 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
509 // LyX cannot handle newlines in a latex command
510 return subst(s, "\n", " ");
514 void handle_backslash(ostream & os, string const & s)
516 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
518 os << "\n\\backslash\n";
525 void handle_ert(ostream & os, string const & s, Context & context)
527 // We must have a valid layout before outputting the ERT inset.
528 context.check_layout(os);
529 Context newcontext(true, context.textclass);
530 begin_inset(os, "ERT");
531 os << "\nstatus collapsed\n";
532 newcontext.check_layout(os);
533 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
535 os << "\n\\backslash\n";
536 else if (*it == '\n') {
537 newcontext.new_paragraph(os);
538 newcontext.check_layout(os);
542 newcontext.check_end_layout(os);
547 void handle_comment(ostream & os, string const & s, Context & context)
549 // TODO: Handle this better
550 Context newcontext(true, context.textclass);
551 begin_inset(os, "ERT");
552 os << "\nstatus collapsed\n";
553 newcontext.check_layout(os);
554 handle_backslash(os, s);
555 // make sure that our comment is the last thing on the line
556 newcontext.new_paragraph(os);
557 newcontext.check_layout(os);
558 newcontext.check_end_layout(os);
563 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
565 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
568 if (checkModule(name, command))
569 return findLayoutWithoutModule(textclass, name, command);
574 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
576 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
579 if (checkModule(name, command))
580 return findInsetLayoutWithoutModule(textclass, name, command);
585 void eat_whitespace(Parser &, ostream &, Context &, bool);
589 * Skips whitespace and braces.
590 * This should be called after a command has been parsed that is not put into
591 * ERT, and where LyX adds "{}" if needed.
593 void skip_spaces_braces(Parser & p, bool keepws = false)
595 /* The following four examples produce the same typeset output and
596 should be handled by this function:
604 // Unfortunately we need to skip comments, too.
605 // We can't use eat_whitespace since writing them after the {}
606 // results in different output in some cases.
607 bool const skipped_spaces = p.skip_spaces(true);
608 bool const skipped_braces = skip_braces(p);
609 if (keepws && skipped_spaces && !skipped_braces)
610 // put back the space (it is better handled by check_space)
611 p.unskip_spaces(true);
615 void output_command_layout(ostream & os, Parser & p, bool outer,
616 Context & parent_context,
617 Layout const * newlayout)
619 TeXFont const oldFont = parent_context.font;
620 // save the current font size
621 string const size = oldFont.size;
622 // reset the font size to default, because the font size switches
623 // don't affect section headings and the like
624 parent_context.font.size = Context::normalfont.size;
625 // we only need to write the font change if we have an open layout
626 if (!parent_context.atParagraphStart())
627 output_font_change(os, oldFont, parent_context.font);
628 parent_context.check_end_layout(os);
629 Context context(true, parent_context.textclass, newlayout,
630 parent_context.layout, parent_context.font);
631 if (parent_context.deeper_paragraph) {
632 // We are beginning a nested environment after a
633 // deeper paragraph inside the outer list environment.
634 // Therefore we don't need to output a "begin deeper".
635 context.need_end_deeper = true;
637 context.check_deeper(os);
638 context.check_layout(os);
639 unsigned int optargs = 0;
640 while (optargs < context.layout->optargs) {
641 eat_whitespace(p, os, context, false);
642 if (p.next_token().cat() == catEscape ||
643 p.next_token().character() != '[')
645 p.get_token(); // eat '['
646 begin_inset(os, "Argument\n");
647 os << "status collapsed\n\n";
648 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
650 eat_whitespace(p, os, context, false);
653 unsigned int reqargs = 0;
654 while (reqargs < context.layout->reqargs) {
655 eat_whitespace(p, os, context, false);
656 if (p.next_token().cat() != catBegin)
658 p.get_token(); // eat '{'
659 begin_inset(os, "Argument\n");
660 os << "status collapsed\n\n";
661 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
663 eat_whitespace(p, os, context, false);
666 parse_text(p, os, FLAG_ITEM, outer, context);
667 context.check_end_layout(os);
668 if (parent_context.deeper_paragraph) {
669 // We must suppress the "end deeper" because we
670 // suppressed the "begin deeper" above.
671 context.need_end_deeper = false;
673 context.check_end_deeper(os);
674 // We don't need really a new paragraph, but
675 // we must make sure that the next item gets a \begin_layout.
676 parent_context.new_paragraph(os);
677 // Set the font size to the original value. No need to output it here
678 // (Context::begin_layout() will do that if needed)
679 parent_context.font.size = size;
684 * Output a space if necessary.
685 * This function gets called for every whitespace token.
687 * We have three cases here:
688 * 1. A space must be suppressed. Example: The lyxcode case below
689 * 2. A space may be suppressed. Example: Spaces before "\par"
690 * 3. A space must not be suppressed. Example: A space between two words
692 * We currently handle only 1. and 3 and from 2. only the case of
693 * spaces before newlines as a side effect.
695 * 2. could be used to suppress as many spaces as possible. This has two effects:
696 * - Reimporting LyX generated LaTeX files changes almost no whitespace
697 * - Superflous whitespace from non LyX generated LaTeX files is removed.
698 * The drawback is that the logic inside the function becomes
699 * complicated, and that is the reason why it is not implemented.
701 void check_space(Parser & p, ostream & os, Context & context)
703 Token const next = p.next_token();
704 Token const curr = p.curr_token();
705 // A space before a single newline and vice versa must be ignored
706 // LyX emits a newline before \end{lyxcode}.
707 // This newline must be ignored,
708 // otherwise LyX will add an additional protected space.
709 if (next.cat() == catSpace ||
710 next.cat() == catNewline ||
711 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
714 context.check_layout(os);
720 * Parse all arguments of \p command
722 void parse_arguments(string const & command,
723 vector<ArgumentType> const & template_arguments,
724 Parser & p, ostream & os, bool outer, Context & context)
726 string ert = command;
727 size_t no_arguments = template_arguments.size();
728 for (size_t i = 0; i < no_arguments; ++i) {
729 switch (template_arguments[i]) {
732 // This argument contains regular LaTeX
733 handle_ert(os, ert + '{', context);
734 eat_whitespace(p, os, context, false);
735 if (template_arguments[i] == required)
736 parse_text(p, os, FLAG_ITEM, outer, context);
738 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
742 // This argument consists only of a single item.
743 // The presence of '{' or not must be preserved.
745 if (p.next_token().cat() == catBegin)
746 ert += '{' + p.verbatim_item() + '}';
748 ert += p.verbatim_item();
752 // This argument may contain special characters
753 ert += '{' + p.verbatim_item() + '}';
757 // true because we must not eat whitespace
758 // if an optional arg follows we must not strip the
759 // brackets from this one
760 if (i < no_arguments - 1 &&
761 template_arguments[i+1] == optional)
762 ert += p.getFullOpt(true);
764 ert += p.getOpt(true);
768 handle_ert(os, ert, context);
773 * Check whether \p command is a known command. If yes,
774 * handle the command with all arguments.
775 * \return true if the command was parsed, false otherwise.
777 bool parse_command(string const & command, Parser & p, ostream & os,
778 bool outer, Context & context)
780 if (known_commands.find(command) != known_commands.end()) {
781 parse_arguments(command, known_commands[command], p, os,
789 /// Parses a minipage or parbox
790 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
791 unsigned inner_flags, bool outer, Context & parent_context,
792 string const & outer_type, string const & special,
793 string const & inner_type)
797 string hor_pos = "c";
798 // We need to set the height to the LaTeX default of 1\\totalheight
799 // for the case when no height argument is given
800 string height_value = "1";
801 string height_unit = "in";
802 string height_special = "totalheight";
807 string width_special = "none";
808 if (!inner_type.empty() && p.hasOpt()) {
809 if (inner_type != "makebox")
810 position = p.getArg('[', ']');
812 latex_width = p.getArg('[', ']');
813 translate_box_len(latex_width, width_value, width_unit, width_special);
816 if (position != "t" && position != "c" && position != "b") {
817 cerr << "invalid position " << position << " for "
818 << inner_type << endl;
822 if (inner_type != "makebox") {
823 latex_height = p.getArg('[', ']');
824 translate_box_len(latex_height, height_value, height_unit, height_special);
826 hor_pos = p.getArg('[', ']');
829 inner_pos = p.getArg('[', ']');
830 if (inner_pos != "c" && inner_pos != "t" &&
831 inner_pos != "b" && inner_pos != "s") {
832 cerr << "invalid inner_pos "
833 << inner_pos << " for "
834 << inner_type << endl;
835 inner_pos = position;
840 if (inner_type.empty()) {
841 if (special.empty() && outer_type != "framebox")
842 latex_width = "1\\columnwidth";
845 latex_width = p2.getArg('[', ']');
846 string const opt = p2.getArg('[', ']');
849 if (hor_pos != "l" && hor_pos != "c" &&
851 cerr << "invalid hor_pos " << hor_pos
852 << " for " << outer_type << endl;
857 } else if (inner_type != "makebox")
858 latex_width = p.verbatim_item();
859 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
860 // as this is LyX's standard for such cases (except for makebox)
861 // \framebox is more special and handled below
862 if (latex_width.empty() && inner_type != "makebox"
863 && outer_type != "framebox")
864 latex_width = "1\\columnwidth";
866 translate_len(latex_width, width_value, width_unit);
868 bool shadedparbox = false;
869 if (inner_type == "shaded") {
870 eat_whitespace(p, os, parent_context, false);
871 if (outer_type == "parbox") {
873 if (p.next_token().cat() == catBegin)
875 eat_whitespace(p, os, parent_context, false);
881 // If we already read the inner box we have to push the inner env
882 if (!outer_type.empty() && !inner_type.empty() &&
883 (inner_flags & FLAG_END))
884 active_environments.push_back(inner_type);
885 // LyX can't handle length variables
886 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
887 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
888 // Look whether there is some content after the end of the
889 // inner box, but before the end of the outer box.
890 // If yes, we need to output ERT.
892 if (inner_flags & FLAG_END)
893 p.verbatimEnvironment(inner_type);
897 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
898 if ((outer_env && p.next_token().asInput() != "\\end") ||
899 (!outer_env && p.next_token().cat() != catEnd)) {
900 // something is between the end of the inner box and
901 // the end of the outer box, so we need to use ERT.
906 // if only \makebox{content} was used we can set its width to 1\width
907 // because this identic and also identic to \mbox
908 // this doesn't work for \framebox{content}, thus we have to use ERT for this
909 if (latex_width.empty() && inner_type == "makebox") {
912 width_special = "width";
913 } else if (latex_width.empty() && outer_type == "framebox") {
918 if (!outer_type.empty()) {
919 if (outer_flags & FLAG_END)
920 ss << "\\begin{" << outer_type << '}';
922 ss << '\\' << outer_type << '{';
923 if (!special.empty())
927 if (!inner_type.empty()) {
928 if (inner_type != "shaded") {
929 if (inner_flags & FLAG_END)
930 ss << "\\begin{" << inner_type << '}';
932 ss << '\\' << inner_type;
934 if (!position.empty())
935 ss << '[' << position << ']';
936 if (!latex_height.empty())
937 ss << '[' << latex_height << ']';
938 if (!inner_pos.empty())
939 ss << '[' << inner_pos << ']';
940 ss << '{' << latex_width << '}';
941 if (!(inner_flags & FLAG_END))
944 if (inner_type == "shaded")
945 ss << "\\begin{shaded}";
946 handle_ert(os, ss.str(), parent_context);
947 if (!inner_type.empty()) {
948 parse_text(p, os, inner_flags, outer, parent_context);
949 if (inner_flags & FLAG_END)
950 handle_ert(os, "\\end{" + inner_type + '}',
953 handle_ert(os, "}", parent_context);
955 if (!outer_type.empty()) {
956 // If we already read the inner box we have to pop
958 if (!inner_type.empty() && (inner_flags & FLAG_END))
959 active_environments.pop_back();
961 // Ensure that the end of the outer box is parsed correctly:
962 // The opening brace has been eaten by parse_outer_box()
963 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
964 outer_flags &= ~FLAG_ITEM;
965 outer_flags |= FLAG_BRACE_LAST;
967 parse_text(p, os, outer_flags, outer, parent_context);
968 if (outer_flags & FLAG_END)
969 handle_ert(os, "\\end{" + outer_type + '}',
971 else if (inner_type.empty() && outer_type == "framebox")
972 // in this case it is already closed later
975 handle_ert(os, "}", parent_context);
978 // LyX does not like empty positions, so we have
979 // to set them to the LaTeX default values here.
980 if (position.empty())
982 if (inner_pos.empty())
983 inner_pos = position;
984 parent_context.check_layout(os);
985 begin_inset(os, "Box ");
986 if (outer_type == "framed")
988 else if (outer_type == "framebox")
990 else if (outer_type == "shadowbox")
992 else if ((outer_type == "shaded" && inner_type.empty()) ||
993 (outer_type == "minipage" && inner_type == "shaded") ||
994 (outer_type == "parbox" && inner_type == "shaded")) {
996 preamble.registerAutomaticallyLoadedPackage("color");
997 } else if (outer_type == "doublebox")
999 else if (outer_type.empty())
1000 os << "Frameless\n";
1002 os << outer_type << '\n';
1003 os << "position \"" << position << "\"\n";
1004 os << "hor_pos \"" << hor_pos << "\"\n";
1005 os << "has_inner_box " << !inner_type.empty() << "\n";
1006 os << "inner_pos \"" << inner_pos << "\"\n";
1007 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1009 os << "use_makebox " << (inner_type == "makebox") << '\n';
1010 os << "width \"" << width_value << width_unit << "\"\n";
1011 os << "special \"" << width_special << "\"\n";
1012 os << "height \"" << height_value << height_unit << "\"\n";
1013 os << "height_special \"" << height_special << "\"\n";
1014 os << "status open\n\n";
1016 // Unfortunately we can't use parse_text_in_inset:
1017 // InsetBox::forcePlainLayout() is hard coded and does not
1018 // use the inset layout. Apart from that do we call parse_text
1019 // up to two times, but need only one check_end_layout.
1020 bool const forcePlainLayout =
1021 (!inner_type.empty() || inner_type == "makebox") &&
1022 outer_type != "shaded" && outer_type != "framed";
1023 Context context(true, parent_context.textclass);
1024 if (forcePlainLayout)
1025 context.layout = &context.textclass.plainLayout();
1027 context.font = parent_context.font;
1029 // If we have no inner box the contents will be read with the outer box
1030 if (!inner_type.empty())
1031 parse_text(p, os, inner_flags, outer, context);
1033 // Ensure that the end of the outer box is parsed correctly:
1034 // The opening brace has been eaten by parse_outer_box()
1035 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1036 outer_flags &= ~FLAG_ITEM;
1037 outer_flags |= FLAG_BRACE_LAST;
1040 // Find end of outer box, output contents if inner_type is
1041 // empty and output possible comments
1042 if (!outer_type.empty()) {
1043 // If we already read the inner box we have to pop
1045 if (!inner_type.empty() && (inner_flags & FLAG_END))
1046 active_environments.pop_back();
1047 // This does not output anything but comments if
1048 // inner_type is not empty (see use_ert)
1049 parse_text(p, os, outer_flags, outer, context);
1052 context.check_end_layout(os);
1054 #ifdef PRESERVE_LAYOUT
1055 // LyX puts a % after the end of the minipage
1056 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1058 //handle_comment(os, "%dummy", parent_context);
1061 parent_context.new_paragraph(os);
1063 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1064 //handle_comment(os, "%dummy", parent_context);
1067 // We add a protected space if something real follows
1068 if (p.good() && p.next_token().cat() != catComment) {
1069 begin_inset(os, "space ~\n");
1078 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1079 Context & parent_context, string const & outer_type,
1080 string const & special)
1082 eat_whitespace(p, os, parent_context, false);
1083 if (flags & FLAG_ITEM) {
1085 if (p.next_token().cat() == catBegin)
1088 cerr << "Warning: Ignoring missing '{' after \\"
1089 << outer_type << '.' << endl;
1090 eat_whitespace(p, os, parent_context, false);
1093 unsigned int inner_flags = 0;
1095 if (outer_type == "minipage" || outer_type == "parbox") {
1096 p.skip_spaces(true);
1097 while (p.hasOpt()) {
1099 p.skip_spaces(true);
1102 p.skip_spaces(true);
1103 if (outer_type == "parbox") {
1105 if (p.next_token().cat() == catBegin)
1107 p.skip_spaces(true);
1110 if (outer_type == "shaded") {
1111 // These boxes never have an inner box
1113 } else if (p.next_token().asInput() == "\\parbox") {
1114 inner = p.get_token().cs();
1115 inner_flags = FLAG_ITEM;
1116 } else if (p.next_token().asInput() == "\\begin") {
1117 // Is this a minipage or shaded box?
1120 inner = p.getArg('{', '}');
1122 if (inner == "minipage" || inner == "shaded")
1123 inner_flags = FLAG_END;
1128 if (inner_flags == FLAG_END) {
1129 if (inner != "shaded")
1133 eat_whitespace(p, os, parent_context, false);
1135 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1136 outer_type, special, inner);
1138 if (inner_flags == FLAG_ITEM) {
1140 eat_whitespace(p, os, parent_context, false);
1142 parse_box(p, os, flags, inner_flags, outer, parent_context,
1143 outer_type, special, inner);
1148 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1150 parent_context.check_layout(os);
1151 begin_inset(os, "listings\n");
1153 string arg = p.verbatimOption();
1154 os << "lstparams " << '"' << arg << '"' << '\n';
1157 os << "inline true\n";
1159 os << "inline false\n";
1160 os << "status collapsed\n";
1161 Context context(true, parent_context.textclass);
1162 context.layout = &parent_context.textclass.plainLayout();
1165 s = p.plainCommand('!', '!', "lstinline");
1166 context.new_paragraph(os);
1167 context.check_layout(os);
1169 s = p.plainEnvironment("lstlisting");
1170 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1172 os << "\n\\backslash\n";
1173 else if (*it == '\n') {
1174 // avoid adding an empty paragraph at the end
1176 context.new_paragraph(os);
1177 context.check_layout(os);
1182 context.check_end_layout(os);
1187 /// parse an unknown environment
1188 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1189 unsigned flags, bool outer,
1190 Context & parent_context)
1192 if (name == "tabbing")
1193 // We need to remember that we have to handle '\=' specially
1194 flags |= FLAG_TABBING;
1196 // We need to translate font changes and paragraphs inside the
1197 // environment to ERT if we have a non standard font.
1198 // Otherwise things like
1199 // \large\begin{foo}\huge bar\end{foo}
1201 bool const specialfont =
1202 (parent_context.font != parent_context.normalfont);
1203 bool const new_layout_allowed = parent_context.new_layout_allowed;
1205 parent_context.new_layout_allowed = false;
1206 handle_ert(os, "\\begin{" + name + "}", parent_context);
1207 parse_text_snippet(p, os, flags, outer, parent_context);
1208 handle_ert(os, "\\end{" + name + "}", parent_context);
1210 parent_context.new_layout_allowed = new_layout_allowed;
1214 void parse_environment(Parser & p, ostream & os, bool outer,
1215 string & last_env, Context & parent_context)
1217 Layout const * newlayout;
1218 InsetLayout const * newinsetlayout = 0;
1219 string const name = p.getArg('{', '}');
1220 const bool is_starred = suffixIs(name, '*');
1221 string const unstarred_name = rtrim(name, "*");
1222 active_environments.push_back(name);
1224 if (is_math_env(name)) {
1225 parent_context.check_layout(os);
1226 begin_inset(os, "Formula ");
1227 os << "\\begin{" << name << "}";
1228 parse_math(p, os, FLAG_END, MATH_MODE);
1229 os << "\\end{" << name << "}";
1231 if (is_display_math_env(name)) {
1232 // Prevent the conversion of a line break to a space
1233 // (bug 7668). This does not change the output, but
1234 // looks ugly in LyX.
1235 eat_whitespace(p, os, parent_context, false);
1239 else if (is_known(name, preamble.polyglossia_languages)) {
1240 // We must begin a new paragraph if not already done
1241 if (! parent_context.atParagraphStart()) {
1242 parent_context.check_end_layout(os);
1243 parent_context.new_paragraph(os);
1245 // save the language in the context so that it is
1246 // handled by parse_text
1247 parent_context.font.language = preamble.polyglossia2lyx(name);
1248 parse_text(p, os, FLAG_END, outer, parent_context);
1249 // Just in case the environment is empty
1250 parent_context.extra_stuff.erase();
1251 // We must begin a new paragraph to reset the language
1252 parent_context.new_paragraph(os);
1256 else if (unstarred_name == "tabular" || name == "longtable") {
1257 eat_whitespace(p, os, parent_context, false);
1258 string width = "0pt";
1259 if (name == "tabular*") {
1260 width = lyx::translate_len(p.getArg('{', '}'));
1261 eat_whitespace(p, os, parent_context, false);
1263 parent_context.check_layout(os);
1264 begin_inset(os, "Tabular ");
1265 handle_tabular(p, os, name, width, parent_context);
1270 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1271 eat_whitespace(p, os, parent_context, false);
1272 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1273 eat_whitespace(p, os, parent_context, false);
1274 parent_context.check_layout(os);
1275 begin_inset(os, "Float " + unstarred_name + "\n");
1276 // store the float type for subfloats
1277 // subfloats only work with figures and tables
1278 if (unstarred_name == "figure")
1279 float_type = unstarred_name;
1280 else if (unstarred_name == "table")
1281 float_type = unstarred_name;
1285 os << "placement " << opt << '\n';
1286 if (contains(opt, "H"))
1287 preamble.registerAutomaticallyLoadedPackage("float");
1289 Floating const & fl = parent_context.textclass.floats()
1290 .getType(unstarred_name);
1291 if (!fl.floattype().empty() && fl.usesFloatPkg())
1292 preamble.registerAutomaticallyLoadedPackage("float");
1295 os << "wide " << convert<string>(is_starred)
1296 << "\nsideways false"
1297 << "\nstatus open\n\n";
1298 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1300 // We don't need really a new paragraph, but
1301 // we must make sure that the next item gets a \begin_layout.
1302 parent_context.new_paragraph(os);
1304 // the float is parsed thus delete the type
1308 else if (unstarred_name == "sidewaysfigure"
1309 || unstarred_name == "sidewaystable") {
1310 eat_whitespace(p, os, parent_context, false);
1311 parent_context.check_layout(os);
1312 if (unstarred_name == "sidewaysfigure")
1313 begin_inset(os, "Float figure\n");
1315 begin_inset(os, "Float table\n");
1316 os << "wide " << convert<string>(is_starred)
1317 << "\nsideways true"
1318 << "\nstatus open\n\n";
1319 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1321 // We don't need really a new paragraph, but
1322 // we must make sure that the next item gets a \begin_layout.
1323 parent_context.new_paragraph(os);
1325 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1328 else if (name == "wrapfigure" || name == "wraptable") {
1329 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1330 eat_whitespace(p, os, parent_context, false);
1331 parent_context.check_layout(os);
1334 string overhang = "0col%";
1337 lines = p.getArg('[', ']');
1338 string const placement = p.getArg('{', '}');
1340 overhang = p.getArg('[', ']');
1341 string const width = p.getArg('{', '}');
1343 if (name == "wrapfigure")
1344 begin_inset(os, "Wrap figure\n");
1346 begin_inset(os, "Wrap table\n");
1347 os << "lines " << lines
1348 << "\nplacement " << placement
1349 << "\noverhang " << lyx::translate_len(overhang)
1350 << "\nwidth " << lyx::translate_len(width)
1351 << "\nstatus open\n\n";
1352 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1354 // We don't need really a new paragraph, but
1355 // we must make sure that the next item gets a \begin_layout.
1356 parent_context.new_paragraph(os);
1358 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1361 else if (name == "minipage") {
1362 eat_whitespace(p, os, parent_context, false);
1363 // Test whether this is an outer box of a shaded box
1365 // swallow arguments
1366 while (p.hasOpt()) {
1368 p.skip_spaces(true);
1371 p.skip_spaces(true);
1372 Token t = p.get_token();
1373 bool shaded = false;
1374 if (t.asInput() == "\\begin") {
1375 p.skip_spaces(true);
1376 if (p.getArg('{', '}') == "shaded")
1381 parse_outer_box(p, os, FLAG_END, outer,
1382 parent_context, name, "shaded");
1384 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1389 else if (name == "comment") {
1390 eat_whitespace(p, os, parent_context, false);
1391 parent_context.check_layout(os);
1392 begin_inset(os, "Note Comment\n");
1393 os << "status open\n";
1394 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1397 skip_braces(p); // eat {} that might by set by LyX behind comments
1398 preamble.registerAutomaticallyLoadedPackage("verbatim");
1401 else if (name == "verbatim") {
1402 os << "\n\\end_layout\n\n\\begin_layout Verbatim\n";
1403 string const s = p.plainEnvironment("verbatim");
1404 string::const_iterator it2 = s.begin();
1405 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1407 os << "\\backslash ";
1408 else if (*it == '\n') {
1410 // avoid adding an empty paragraph at the end
1411 // FIXME: if there are 2 consecutive spaces at the end ignore it
1412 // because LyX will re-add a \n
1413 // This hack must be removed once bug 8049 is fixed!
1414 if ((it + 1 != et) && (it + 2 != et || *it2 != '\n'))
1415 os << "\n\\end_layout\n\\begin_layout Verbatim\n";
1419 os << "\n\\end_layout\n\n";
1421 // reset to Standard layout
1422 os << "\n\\begin_layout Standard\n";
1425 else if (name == "CJK") {
1426 // the scheme is \begin{CJK}{encoding}{mapping}{text}
1427 // It is impossible to decide if a CJK environment was in its own paragraph or within
1428 // a line. We therefore always assume a paragraph since the latter is a rare case.
1429 eat_whitespace(p, os, parent_context, false);
1430 parent_context.check_end_layout(os);
1431 // store the encoding to be able to reset it
1432 string const encoding_old = p.getEncoding();
1433 string const encoding = p.getArg('{', '}');
1434 // SJIS and Bg5 cammopt be handled by iconv
1435 // JIS does not work with LyX's encoding conversion
1436 if (encoding != "Bg5" && encoding != "JIS" && encoding != "SJIS")
1437 p.setEncoding(encoding);
1439 p.setEncoding("utf8");
1440 // LyX doesn't support the second argument so if
1441 // this is used we need to output everything as ERT
1442 string const mapping = p.getArg('{', '}');
1443 if ((!mapping.empty() && mapping != " ")
1444 || (!is_known(encoding, supported_CJK_encodings))) {
1445 parent_context.check_layout(os);
1446 handle_ert(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1448 // we must parse the content as verbatim because e.g. JIS can contain
1449 // normally invalid characters
1450 string const s = p.plainEnvironment("CJK");
1451 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1453 handle_ert(os, "\\", parent_context);
1454 else if (*it == '$')
1455 handle_ert(os, "$", parent_context);
1459 handle_ert(os, "\\end{" + name + "}",
1462 string const lang = CJK2lyx(encoding);
1463 // store the language because we must reset it at the end
1464 string const lang_old = parent_context.font.language;
1465 parent_context.font.language = lang;
1466 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1467 parent_context.font.language = lang_old;
1468 parent_context.new_paragraph(os);
1470 p.setEncoding(encoding_old);
1474 else if (name == "lyxgreyedout") {
1475 eat_whitespace(p, os, parent_context, false);
1476 parent_context.check_layout(os);
1477 begin_inset(os, "Note Greyedout\n");
1478 os << "status open\n";
1479 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1482 if (!preamble.notefontcolor().empty())
1483 preamble.registerAutomaticallyLoadedPackage("color");
1486 else if (name == "framed" || name == "shaded") {
1487 eat_whitespace(p, os, parent_context, false);
1488 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1492 else if (name == "lstlisting") {
1493 eat_whitespace(p, os, parent_context, false);
1494 // FIXME handle the automatic color package loading
1495 // uwestoehr asks: In what case color is loaded?
1496 parse_listings(p, os, parent_context, false);
1500 else if (!parent_context.new_layout_allowed)
1501 parse_unknown_environment(p, name, os, FLAG_END, outer,
1504 // Alignment and spacing settings
1505 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1506 // therefore are totally broken!
1507 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1508 // they are commands not environments. They are furthermore switches that
1509 // can be ended by another switches, but also by commands like \footnote or
1510 // \parbox. So the only safe way is to leave them untouched.
1511 else if (name == "center" || name == "centering" ||
1512 name == "flushleft" || name == "flushright" ||
1513 name == "singlespace" || name == "onehalfspace" ||
1514 name == "doublespace" || name == "spacing") {
1515 eat_whitespace(p, os, parent_context, false);
1516 // We must begin a new paragraph if not already done
1517 if (! parent_context.atParagraphStart()) {
1518 parent_context.check_end_layout(os);
1519 parent_context.new_paragraph(os);
1521 if (name == "flushleft")
1522 parent_context.add_extra_stuff("\\align left\n");
1523 else if (name == "flushright")
1524 parent_context.add_extra_stuff("\\align right\n");
1525 else if (name == "center" || name == "centering")
1526 parent_context.add_extra_stuff("\\align center\n");
1527 else if (name == "singlespace")
1528 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1529 else if (name == "onehalfspace") {
1530 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1531 preamble.registerAutomaticallyLoadedPackage("setspace");
1532 } else if (name == "doublespace") {
1533 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1534 preamble.registerAutomaticallyLoadedPackage("setspace");
1535 } else if (name == "spacing") {
1536 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1537 preamble.registerAutomaticallyLoadedPackage("setspace");
1539 parse_text(p, os, FLAG_END, outer, parent_context);
1540 // Just in case the environment is empty
1541 parent_context.extra_stuff.erase();
1542 // We must begin a new paragraph to reset the alignment
1543 parent_context.new_paragraph(os);
1547 // The single '=' is meant here.
1548 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1549 eat_whitespace(p, os, parent_context, false);
1550 Context context(true, parent_context.textclass, newlayout,
1551 parent_context.layout, parent_context.font);
1552 if (parent_context.deeper_paragraph) {
1553 // We are beginning a nested environment after a
1554 // deeper paragraph inside the outer list environment.
1555 // Therefore we don't need to output a "begin deeper".
1556 context.need_end_deeper = true;
1558 parent_context.check_end_layout(os);
1559 if (last_env == name) {
1560 // we need to output a separator since LyX would export
1561 // the two environments as one otherwise (bug 5716)
1562 docstring const sep = from_ascii("--Separator--");
1563 TeX2LyXDocClass const & textclass(parent_context.textclass);
1564 if (textclass.hasLayout(sep)) {
1565 Context newcontext(parent_context);
1566 newcontext.layout = &(textclass[sep]);
1567 newcontext.check_layout(os);
1568 newcontext.check_end_layout(os);
1570 parent_context.check_layout(os);
1571 begin_inset(os, "Note Note\n");
1572 os << "status closed\n";
1573 Context newcontext(true, textclass,
1574 &(textclass.defaultLayout()));
1575 newcontext.check_layout(os);
1576 newcontext.check_end_layout(os);
1578 parent_context.check_end_layout(os);
1581 switch (context.layout->latextype) {
1582 case LATEX_LIST_ENVIRONMENT:
1583 context.add_par_extra_stuff("\\labelwidthstring "
1584 + p.verbatim_item() + '\n');
1587 case LATEX_BIB_ENVIRONMENT:
1588 p.verbatim_item(); // swallow next arg
1594 context.check_deeper(os);
1595 // handle known optional and required arguments
1596 // layouts require all optional arguments before the required ones
1597 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1598 // It is impossible to place anything after the environment name,
1599 // but before the first \\item.
1600 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1601 bool need_layout = true;
1602 unsigned int optargs = 0;
1603 while (optargs < context.layout->optargs) {
1604 eat_whitespace(p, os, context, false);
1605 if (p.next_token().cat() == catEscape ||
1606 p.next_token().character() != '[')
1608 p.get_token(); // eat '['
1610 context.check_layout(os);
1611 need_layout = false;
1613 begin_inset(os, "Argument\n");
1614 os << "status collapsed\n\n";
1615 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1617 eat_whitespace(p, os, context, false);
1620 unsigned int reqargs = 0;
1621 while (reqargs < context.layout->reqargs) {
1622 eat_whitespace(p, os, context, false);
1623 if (p.next_token().cat() != catBegin)
1625 p.get_token(); // eat '{'
1627 context.check_layout(os);
1628 need_layout = false;
1630 begin_inset(os, "Argument\n");
1631 os << "status collapsed\n\n";
1632 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1634 eat_whitespace(p, os, context, false);
1638 parse_text(p, os, FLAG_END, outer, context);
1639 context.check_end_layout(os);
1640 if (parent_context.deeper_paragraph) {
1641 // We must suppress the "end deeper" because we
1642 // suppressed the "begin deeper" above.
1643 context.need_end_deeper = false;
1645 context.check_end_deeper(os);
1646 parent_context.new_paragraph(os);
1648 if (!preamble.titleLayoutFound())
1649 preamble.titleLayoutFound(newlayout->intitle);
1650 set<string> const & req = newlayout->requires();
1651 set<string>::const_iterator it = req.begin();
1652 set<string>::const_iterator en = req.end();
1653 for (; it != en; ++it)
1654 preamble.registerAutomaticallyLoadedPackage(*it);
1657 // The single '=' is meant here.
1658 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1659 eat_whitespace(p, os, parent_context, false);
1660 parent_context.check_layout(os);
1661 begin_inset(os, "Flex ");
1662 os << to_utf8(newinsetlayout->name()) << '\n'
1663 << "status collapsed\n";
1664 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1668 else if (name == "appendix") {
1669 // This is no good latex style, but it works and is used in some documents...
1670 eat_whitespace(p, os, parent_context, false);
1671 parent_context.check_end_layout(os);
1672 Context context(true, parent_context.textclass, parent_context.layout,
1673 parent_context.layout, parent_context.font);
1674 context.check_layout(os);
1675 os << "\\start_of_appendix\n";
1676 parse_text(p, os, FLAG_END, outer, context);
1677 context.check_end_layout(os);
1681 else if (known_environments.find(name) != known_environments.end()) {
1682 vector<ArgumentType> arguments = known_environments[name];
1683 // The last "argument" denotes wether we may translate the
1684 // environment contents to LyX
1685 // The default required if no argument is given makes us
1686 // compatible with the reLyXre environment.
1687 ArgumentType contents = arguments.empty() ?
1690 if (!arguments.empty())
1691 arguments.pop_back();
1692 // See comment in parse_unknown_environment()
1693 bool const specialfont =
1694 (parent_context.font != parent_context.normalfont);
1695 bool const new_layout_allowed =
1696 parent_context.new_layout_allowed;
1698 parent_context.new_layout_allowed = false;
1699 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1700 outer, parent_context);
1701 if (contents == verbatim)
1702 handle_ert(os, p.verbatimEnvironment(name),
1705 parse_text_snippet(p, os, FLAG_END, outer,
1707 handle_ert(os, "\\end{" + name + "}", parent_context);
1709 parent_context.new_layout_allowed = new_layout_allowed;
1713 parse_unknown_environment(p, name, os, FLAG_END, outer,
1717 active_environments.pop_back();
1721 /// parses a comment and outputs it to \p os.
1722 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1724 LASSERT(t.cat() == catComment, return);
1725 if (!t.cs().empty()) {
1726 context.check_layout(os);
1727 handle_comment(os, '%' + t.cs(), context);
1728 if (p.next_token().cat() == catNewline) {
1729 // A newline after a comment line starts a new
1731 if (context.new_layout_allowed) {
1732 if(!context.atParagraphStart())
1733 // Only start a new paragraph if not already
1734 // done (we might get called recursively)
1735 context.new_paragraph(os);
1737 handle_ert(os, "\n", context);
1738 eat_whitespace(p, os, context, true);
1741 // "%\n" combination
1748 * Reads spaces and comments until the first non-space, non-comment token.
1749 * New paragraphs (double newlines or \\par) are handled like simple spaces
1750 * if \p eatParagraph is true.
1751 * Spaces are skipped, but comments are written to \p os.
1753 void eat_whitespace(Parser & p, ostream & os, Context & context,
1757 Token const & t = p.get_token();
1758 if (t.cat() == catComment)
1759 parse_comment(p, os, t, context);
1760 else if ((! eatParagraph && p.isParagraph()) ||
1761 (t.cat() != catSpace && t.cat() != catNewline)) {
1770 * Set a font attribute, parse text and reset the font attribute.
1771 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1772 * \param currentvalue Current value of the attribute. Is set to the new
1773 * value during parsing.
1774 * \param newvalue New value of the attribute
1776 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1777 Context & context, string const & attribute,
1778 string & currentvalue, string const & newvalue)
1780 context.check_layout(os);
1781 string const oldvalue = currentvalue;
1782 currentvalue = newvalue;
1783 os << '\n' << attribute << ' ' << newvalue << "\n";
1784 parse_text_snippet(p, os, flags, outer, context);
1785 context.check_layout(os);
1786 os << '\n' << attribute << ' ' << oldvalue << "\n";
1787 currentvalue = oldvalue;
1791 /// get the arguments of a natbib or jurabib citation command
1792 void get_cite_arguments(Parser & p, bool natbibOrder,
1793 string & before, string & after)
1795 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1797 // text before the citation
1799 // text after the citation
1800 after = p.getFullOpt();
1802 if (!after.empty()) {
1803 before = p.getFullOpt();
1804 if (natbibOrder && !before.empty())
1805 swap(before, after);
1810 /// Convert filenames with TeX macros and/or quotes to something LyX
1812 string const normalize_filename(string const & name)
1814 Parser p(trim(name, "\""));
1817 Token const & t = p.get_token();
1818 if (t.cat() != catEscape)
1820 else if (t.cs() == "lyxdot") {
1821 // This is used by LyX for simple dots in relative
1825 } else if (t.cs() == "space") {
1835 /// Convert \p name from TeX convention (relative to master file) to LyX
1836 /// convention (relative to .lyx file) if it is relative
1837 void fix_relative_filename(string & name)
1839 if (FileName::isAbsolute(name))
1842 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1843 from_utf8(getParentFilePath())));
1847 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1848 void parse_noweb(Parser & p, ostream & os, Context & context)
1850 // assemble the rest of the keyword
1854 Token const & t = p.get_token();
1855 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1858 scrap = (p.good() && p.next_token().asInput() == "=");
1860 name += p.get_token().asInput();
1863 name += t.asInput();
1866 if (!scrap || !context.new_layout_allowed ||
1867 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1868 cerr << "Warning: Could not interpret '" << name
1869 << "'. Ignoring it." << endl;
1873 // We use new_paragraph instead of check_end_layout because the stuff
1874 // following the noweb chunk needs to start with a \begin_layout.
1875 // This may create a new paragraph even if there was none in the
1876 // noweb file, but the alternative is an invalid LyX file. Since
1877 // noweb code chunks are implemented with a layout style in LyX they
1878 // always must be in an own paragraph.
1879 context.new_paragraph(os);
1880 Context newcontext(true, context.textclass,
1881 &context.textclass[from_ascii("Scrap")]);
1882 newcontext.check_layout(os);
1885 Token const & t = p.get_token();
1886 // We abuse the parser a bit, because this is no TeX syntax
1888 if (t.cat() == catEscape)
1889 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1892 Context tmp(false, context.textclass,
1893 &context.textclass[from_ascii("Scrap")]);
1894 tmp.need_end_layout = true;
1895 tmp.check_layout(oss);
1896 os << subst(t.asInput(), "\n", oss.str());
1898 // The scrap chunk is ended by an @ at the beginning of a line.
1899 // After the @ the line may contain a comment and/or
1900 // whitespace, but nothing else.
1901 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1902 (p.next_token().cat() == catSpace ||
1903 p.next_token().cat() == catNewline ||
1904 p.next_token().cat() == catComment)) {
1905 while (p.good() && p.next_token().cat() == catSpace)
1906 os << p.get_token().asInput();
1907 if (p.next_token().cat() == catComment)
1908 // The comment includes a final '\n'
1909 os << p.get_token().asInput();
1911 if (p.next_token().cat() == catNewline)
1918 newcontext.check_end_layout(os);
1922 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1923 bool is_macro(Parser & p)
1925 Token first = p.curr_token();
1926 if (first.cat() != catEscape || !p.good())
1928 if (first.cs() == "def")
1930 if (first.cs() != "global" && first.cs() != "long")
1932 Token second = p.get_token();
1934 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1935 second.cat() == catNewline || second.cat() == catComment)) {
1936 second = p.get_token();
1939 bool secondvalid = second.cat() == catEscape;
1941 bool thirdvalid = false;
1942 if (p.good() && first.cs() == "global" && secondvalid &&
1943 second.cs() == "long") {
1944 third = p.get_token();
1946 while (p.good() && !p.isParagraph() &&
1947 (third.cat() == catSpace ||
1948 third.cat() == catNewline ||
1949 third.cat() == catComment)) {
1950 third = p.get_token();
1953 thirdvalid = third.cat() == catEscape;
1955 for (int i = 0; i < pos; ++i)
1960 return (first.cs() == "global" || first.cs() == "long") &&
1961 second.cs() == "def";
1962 return first.cs() == "global" && second.cs() == "long" &&
1963 third.cs() == "def";
1967 /// Parse a macro definition (assumes that is_macro() returned true)
1968 void parse_macro(Parser & p, ostream & os, Context & context)
1970 context.check_layout(os);
1971 Token first = p.curr_token();
1974 string command = first.asInput();
1975 if (first.cs() != "def") {
1977 eat_whitespace(p, os, context, false);
1978 second = p.curr_token();
1979 command += second.asInput();
1980 if (second.cs() != "def") {
1982 eat_whitespace(p, os, context, false);
1983 third = p.curr_token();
1984 command += third.asInput();
1987 eat_whitespace(p, os, context, false);
1988 string const name = p.get_token().cs();
1989 eat_whitespace(p, os, context, false);
1995 while (p.next_token().cat() != catBegin) {
1996 if (p.next_token().cat() == catParameter) {
2001 // followed by number?
2002 if (p.next_token().cat() == catOther) {
2003 char c = p.getChar();
2005 // number = current arity + 1?
2006 if (c == arity + '0' + 1)
2011 paramtext += p.get_token().cs();
2013 paramtext += p.get_token().cs();
2018 // only output simple (i.e. compatible) macro as FormulaMacros
2019 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2021 context.check_layout(os);
2022 begin_inset(os, "FormulaMacro");
2023 os << "\n\\def" << ert;
2026 handle_ert(os, command + ert, context);
2030 void registerExternalTemplatePackages(string const & name)
2032 external::TemplateManager const & etm = external::TemplateManager::get();
2033 external::Template const * const et = etm.getTemplateByName(name);
2036 external::Template::Formats::const_iterator cit = et->formats.end();
2038 cit = et->formats.find("PDFLaTeX");
2039 if (cit == et->formats.end())
2040 // If the template has not specified a PDFLaTeX output,
2041 // we try the LaTeX format.
2042 cit = et->formats.find("LaTeX");
2043 if (cit == et->formats.end())
2045 vector<string>::const_iterator qit = cit->second.requirements.begin();
2046 vector<string>::const_iterator qend = cit->second.requirements.end();
2047 for (; qit != qend; ++qit)
2048 preamble.registerAutomaticallyLoadedPackage(*qit);
2051 } // anonymous namespace
2054 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2057 Layout const * newlayout = 0;
2058 InsetLayout const * newinsetlayout = 0;
2059 char const * const * where = 0;
2060 // Store the latest bibliographystyle and nocite{*} option
2061 // (needed for bibtex inset)
2063 string bibliographystyle = "default";
2064 bool const use_natbib = preamble.isPackageUsed("natbib");
2065 bool const use_jurabib = preamble.isPackageUsed("jurabib");
2068 Token const & t = p.get_token();
2070 // it is impossible to determine the correct document language if CJK is used.
2071 // Therefore write a note at the beginning of the document
2073 context.check_layout(os);
2074 begin_inset(os, "Note Note\n");
2075 os << "status open\n\\begin_layout Plain Layout\n"
2076 << "\\series bold\n"
2077 << "Important information:\n"
2078 << "\\end_layout\n\n"
2079 << "\\begin_layout Plain Layout\n"
2080 << "This document contains text in Chinese, Japanese or Korean.\n"
2081 << " It was therefore impossible for tex2lyx to set the correct document langue for your document."
2082 << " Please set the language manually in the document settings.\n"
2083 << "\\end_layout\n";
2088 // it is impossible to determine the correct encoding for non-CJK Japanese.
2089 // Therefore write a note at the beginning of the document
2090 if (is_nonCJKJapanese) {
2091 context.check_layout(os);
2092 begin_inset(os, "Note Note\n");
2093 os << "status open\n\\begin_layout Plain Layout\n"
2094 << "\\series bold\n"
2095 << "Important information:\n"
2096 << "\\end_layout\n\n"
2097 << "\\begin_layout Plain Layout\n"
2098 << "This document is in Japanese (non-CJK).\n"
2099 << " It was therefore impossible for tex2lyx to determine the correct encoding."
2100 << " The encoding EUC-JP was assumed. If this is incorrect, please set the correct"
2101 << " encoding in the document settings.\n"
2102 << "\\end_layout\n";
2104 is_nonCJKJapanese = false;
2108 debugToken(cerr, t, flags);
2111 if (flags & FLAG_ITEM) {
2112 if (t.cat() == catSpace)
2115 flags &= ~FLAG_ITEM;
2116 if (t.cat() == catBegin) {
2117 // skip the brace and collect everything to the next matching
2119 flags |= FLAG_BRACE_LAST;
2123 // handle only this single token, leave the loop if done
2124 flags |= FLAG_LEAVE;
2127 if (t.cat() != catEscape && t.character() == ']' &&
2128 (flags & FLAG_BRACK_LAST))
2130 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2133 // If there is anything between \end{env} and \begin{env} we
2134 // don't need to output a separator.
2135 if (t.cat() != catSpace && t.cat() != catNewline &&
2136 t.asInput() != "\\begin")
2142 if (t.cat() == catMath) {
2143 // we are inside some text mode thingy, so opening new math is allowed
2144 context.check_layout(os);
2145 begin_inset(os, "Formula ");
2146 Token const & n = p.get_token();
2147 bool const display(n.cat() == catMath && outer);
2149 // TeX's $$...$$ syntax for displayed math
2151 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2153 p.get_token(); // skip the second '$' token
2155 // simple $...$ stuff
2158 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2163 // Prevent the conversion of a line break to a
2164 // space (bug 7668). This does not change the
2165 // output, but looks ugly in LyX.
2166 eat_whitespace(p, os, context, false);
2170 else if (t.cat() == catSuper || t.cat() == catSub)
2171 cerr << "catcode " << t << " illegal in text mode\n";
2173 // Basic support for english quotes. This should be
2174 // extended to other quotes, but is not so easy (a
2175 // left english quote is the same as a right german
2177 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2178 context.check_layout(os);
2179 begin_inset(os, "Quotes ");
2185 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2186 context.check_layout(os);
2187 begin_inset(os, "Quotes ");
2194 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2195 context.check_layout(os);
2196 begin_inset(os, "Quotes ");
2203 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2204 context.check_layout(os);
2205 begin_inset(os, "Quotes ");
2212 else if (t.asInput() == "<"
2213 && p.next_token().asInput() == "<" && noweb_mode) {
2215 parse_noweb(p, os, context);
2218 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2219 check_space(p, os, context);
2221 else if (t.character() == '[' && noweb_mode &&
2222 p.next_token().character() == '[') {
2223 // These can contain underscores
2225 string const s = p.getFullOpt() + ']';
2226 if (p.next_token().character() == ']')
2229 cerr << "Warning: Inserting missing ']' in '"
2230 << s << "'." << endl;
2231 handle_ert(os, s, context);
2234 else if (t.cat() == catLetter) {
2235 context.check_layout(os);
2236 // Workaround for bug 4752.
2237 // FIXME: This whole code block needs to be removed
2238 // when the bug is fixed and tex2lyx produces
2239 // the updated file format.
2240 // The replacement algorithm in LyX is so stupid that
2241 // it even translates a phrase if it is part of a word.
2242 bool handled = false;
2243 for (int const * l = known_phrase_lengths; *l; ++l) {
2244 string phrase = t.cs();
2245 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2246 phrase += p.get_token().cs();
2247 if (is_known(phrase, known_coded_phrases)) {
2248 handle_ert(os, phrase, context);
2252 for (size_t i = 1; i < phrase.length(); ++i)
2260 else if (t.cat() == catOther ||
2261 t.cat() == catAlign ||
2262 t.cat() == catParameter) {
2263 // This translates "&" to "\\&" which may be wrong...
2264 context.check_layout(os);
2268 else if (p.isParagraph()) {
2269 if (context.new_layout_allowed)
2270 context.new_paragraph(os);
2272 handle_ert(os, "\\par ", context);
2273 eat_whitespace(p, os, context, true);
2276 else if (t.cat() == catActive) {
2277 context.check_layout(os);
2278 if (t.character() == '~') {
2279 if (context.layout->free_spacing)
2282 begin_inset(os, "space ~\n");
2289 else if (t.cat() == catBegin) {
2290 Token const next = p.next_token();
2291 Token const end = p.next_next_token();
2292 if (next.cat() == catEnd) {
2294 Token const prev = p.prev_token();
2296 if (p.next_token().character() == '`' ||
2297 (prev.character() == '-' &&
2298 p.next_token().character() == '-'))
2299 ; // ignore it in {}`` or -{}-
2301 handle_ert(os, "{}", context);
2302 } else if (next.cat() == catEscape &&
2303 is_known(next.cs(), known_quotes) &&
2304 end.cat() == catEnd) {
2305 // Something like {\textquoteright} (e.g.
2306 // from writer2latex). LyX writes
2307 // \textquoteright{}, so we may skip the
2308 // braces here for better readability.
2309 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2312 context.check_layout(os);
2313 // special handling of font attribute changes
2314 Token const prev = p.prev_token();
2315 TeXFont const oldFont = context.font;
2316 if (next.character() == '[' ||
2317 next.character() == ']' ||
2318 next.character() == '*') {
2320 if (p.next_token().cat() == catEnd) {
2325 handle_ert(os, "{", context);
2326 parse_text_snippet(p, os,
2329 handle_ert(os, "}", context);
2331 } else if (! context.new_layout_allowed) {
2332 handle_ert(os, "{", context);
2333 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2335 handle_ert(os, "}", context);
2336 } else if (is_known(next.cs(), known_sizes)) {
2337 // next will change the size, so we must
2339 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2341 if (!context.atParagraphStart())
2343 << context.font.size << "\n";
2344 } else if (is_known(next.cs(), known_font_families)) {
2345 // next will change the font family, so we
2346 // must reset it here
2347 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2349 if (!context.atParagraphStart())
2351 << context.font.family << "\n";
2352 } else if (is_known(next.cs(), known_font_series)) {
2353 // next will change the font series, so we
2354 // must reset it here
2355 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2357 if (!context.atParagraphStart())
2359 << context.font.series << "\n";
2360 } else if (is_known(next.cs(), known_font_shapes)) {
2361 // next will change the font shape, so we
2362 // must reset it here
2363 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2365 if (!context.atParagraphStart())
2367 << context.font.shape << "\n";
2368 } else if (is_known(next.cs(), known_old_font_families) ||
2369 is_known(next.cs(), known_old_font_series) ||
2370 is_known(next.cs(), known_old_font_shapes)) {
2371 // next will change the font family, series
2372 // and shape, so we must reset it here
2373 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2375 if (!context.atParagraphStart())
2377 << context.font.family
2379 << context.font.series
2381 << context.font.shape << "\n";
2383 handle_ert(os, "{", context);
2384 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2386 handle_ert(os, "}", context);
2391 else if (t.cat() == catEnd) {
2392 if (flags & FLAG_BRACE_LAST) {
2395 cerr << "stray '}' in text\n";
2396 handle_ert(os, "}", context);
2399 else if (t.cat() == catComment)
2400 parse_comment(p, os, t, context);
2403 // control sequences
2406 else if (t.cs() == "(") {
2407 context.check_layout(os);
2408 begin_inset(os, "Formula");
2410 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2415 else if (t.cs() == "[") {
2416 context.check_layout(os);
2417 begin_inset(os, "Formula");
2419 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2422 // Prevent the conversion of a line break to a space
2423 // (bug 7668). This does not change the output, but
2424 // looks ugly in LyX.
2425 eat_whitespace(p, os, context, false);
2428 else if (t.cs() == "begin")
2429 parse_environment(p, os, outer, last_env,
2432 else if (t.cs() == "end") {
2433 if (flags & FLAG_END) {
2434 // eat environment name
2435 string const name = p.getArg('{', '}');
2436 if (name != active_environment())
2437 cerr << "\\end{" + name + "} does not match \\begin{"
2438 + active_environment() + "}\n";
2441 p.error("found 'end' unexpectedly");
2444 else if (t.cs() == "item") {
2446 bool const optarg = p.hasOpt();
2448 // FIXME: This swallows comments, but we cannot use
2449 // eat_whitespace() since we must not output
2450 // anything before the item.
2451 p.skip_spaces(true);
2452 s = p.verbatimOption();
2454 p.skip_spaces(false);
2456 context.check_layout(os);
2457 if (context.has_item) {
2458 // An item in an unknown list-like environment
2459 // FIXME: Do this in check_layout()!
2460 context.has_item = false;
2462 handle_ert(os, "\\item", context);
2464 handle_ert(os, "\\item ", context);
2467 if (context.layout->labeltype != LABEL_MANUAL) {
2468 // LyX does not support \item[\mybullet]
2469 // in itemize environments
2471 os << parse_text_snippet(p2,
2472 FLAG_BRACK_LAST, outer, context);
2473 } else if (!s.empty()) {
2474 // LyX adds braces around the argument,
2475 // so we need to remove them here.
2476 if (s.size() > 2 && s[0] == '{' &&
2477 s[s.size()-1] == '}')
2478 s = s.substr(1, s.size()-2);
2479 // If the argument contains a space we
2480 // must put it into ERT: Otherwise LyX
2481 // would misinterpret the space as
2482 // item delimiter (bug 7663)
2483 if (contains(s, ' ')) {
2484 handle_ert(os, s, context);
2487 os << parse_text_snippet(p2,
2491 // The space is needed to separate the
2492 // item from the rest of the sentence.
2494 eat_whitespace(p, os, context, false);
2499 else if (t.cs() == "bibitem") {
2501 context.check_layout(os);
2502 eat_whitespace(p, os, context, false);
2503 string label = convert_command_inset_arg(p.verbatimOption());
2504 string key = convert_command_inset_arg(p.verbatim_item());
2505 if (contains(label, '\\') || contains(key, '\\')) {
2506 // LyX can't handle LaTeX commands in labels or keys
2507 handle_ert(os, t.asInput() + '[' + label +
2508 "]{" + p.verbatim_item() + '}',
2511 begin_command_inset(os, "bibitem", "bibitem");
2512 os << "label \"" << label << "\"\n"
2513 "key \"" << key << "\"\n";
2518 else if (is_macro(p)) {
2519 // catch the case of \def\inputGnumericTable
2521 if (t.cs() == "def") {
2522 Token second = p.next_token();
2523 if (second.cs() == "inputGnumericTable") {
2527 Token third = p.get_token();
2529 if (third.cs() == "input") {
2533 string name = normalize_filename(p.verbatim_item());
2534 string const path = getMasterFilePath();
2535 // We want to preserve relative / absolute filenames,
2536 // therefore path is only used for testing
2537 // The file extension is in every case ".tex".
2538 // So we need to remove this extension and check for
2539 // the original one.
2540 name = removeExtension(name);
2541 if (!makeAbsPath(name, path).exists()) {
2542 char const * const Gnumeric_formats[] = {"gnumeric",
2544 string const Gnumeric_name =
2545 find_file(name, path, Gnumeric_formats);
2546 if (!Gnumeric_name.empty())
2547 name = Gnumeric_name;
2549 if (makeAbsPath(name, path).exists())
2550 fix_relative_filename(name);
2552 cerr << "Warning: Could not find file '"
2553 << name << "'." << endl;
2554 context.check_layout(os);
2555 begin_inset(os, "External\n\ttemplate ");
2556 os << "GnumericSpreadsheet\n\tfilename "
2559 context.check_layout(os);
2561 // register the packages that are automatically reloaded
2562 // by the Gnumeric template
2563 registerExternalTemplatePackages("GnumericSpreadsheet");
2568 parse_macro(p, os, context);
2571 else if (t.cs() == "noindent") {
2573 context.add_par_extra_stuff("\\noindent\n");
2576 else if (t.cs() == "appendix") {
2577 context.add_par_extra_stuff("\\start_of_appendix\n");
2578 // We need to start a new paragraph. Otherwise the
2579 // appendix in 'bla\appendix\chapter{' would start
2581 context.new_paragraph(os);
2582 // We need to make sure that the paragraph is
2583 // generated even if it is empty. Otherwise the
2584 // appendix in '\par\appendix\par\chapter{' would
2586 context.check_layout(os);
2587 // FIXME: This is a hack to prevent paragraph
2588 // deletion if it is empty. Handle this better!
2590 "%dummy comment inserted by tex2lyx to "
2591 "ensure that this paragraph is not empty",
2593 // Both measures above may generate an additional
2594 // empty paragraph, but that does not hurt, because
2595 // whitespace does not matter here.
2596 eat_whitespace(p, os, context, true);
2599 // Must catch empty dates before findLayout is called below
2600 else if (t.cs() == "date") {
2601 eat_whitespace(p, os, context, false);
2603 string const date = p.verbatim_item();
2606 preamble.suppressDate(true);
2609 preamble.suppressDate(false);
2610 if (context.new_layout_allowed &&
2611 (newlayout = findLayout(context.textclass,
2614 output_command_layout(os, p, outer,
2615 context, newlayout);
2616 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2617 if (!preamble.titleLayoutFound())
2618 preamble.titleLayoutFound(newlayout->intitle);
2619 set<string> const & req = newlayout->requires();
2620 set<string>::const_iterator it = req.begin();
2621 set<string>::const_iterator en = req.end();
2622 for (; it != en; ++it)
2623 preamble.registerAutomaticallyLoadedPackage(*it);
2626 "\\date{" + p.verbatim_item() + '}',
2631 // Starred section headings
2632 // Must attempt to parse "Section*" before "Section".
2633 else if ((p.next_token().asInput() == "*") &&
2634 context.new_layout_allowed &&
2635 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2638 output_command_layout(os, p, outer, context, newlayout);
2640 if (!preamble.titleLayoutFound())
2641 preamble.titleLayoutFound(newlayout->intitle);
2642 set<string> const & req = newlayout->requires();
2643 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2644 preamble.registerAutomaticallyLoadedPackage(*it);
2647 // Section headings and the like
2648 else if (context.new_layout_allowed &&
2649 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2651 output_command_layout(os, p, outer, context, newlayout);
2653 if (!preamble.titleLayoutFound())
2654 preamble.titleLayoutFound(newlayout->intitle);
2655 set<string> const & req = newlayout->requires();
2656 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2657 preamble.registerAutomaticallyLoadedPackage(*it);
2660 else if (t.cs() == "caption") {
2662 context.check_layout(os);
2664 begin_inset(os, "Caption\n");
2665 Context newcontext(true, context.textclass);
2666 newcontext.font = context.font;
2667 newcontext.check_layout(os);
2668 if (p.next_token().cat() != catEscape &&
2669 p.next_token().character() == '[') {
2670 p.get_token(); // eat '['
2671 begin_inset(os, "Argument\n");
2672 os << "status collapsed\n";
2673 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2675 eat_whitespace(p, os, context, false);
2677 parse_text(p, os, FLAG_ITEM, outer, context);
2678 context.check_end_layout(os);
2679 // We don't need really a new paragraph, but
2680 // we must make sure that the next item gets a \begin_layout.
2681 context.new_paragraph(os);
2684 newcontext.check_end_layout(os);
2687 else if (t.cs() == "subfloat") {
2688 // the syntax is \subfloat[caption]{content}
2689 // if it is a table of figure depends on the surrounding float
2690 bool has_caption = false;
2692 // do nothing if there is no outer float
2693 if (!float_type.empty()) {
2694 context.check_layout(os);
2696 begin_inset(os, "Float " + float_type + "\n");
2698 << "\nsideways false"
2699 << "\nstatus collapsed\n\n";
2702 if (p.next_token().cat() != catEscape &&
2703 p.next_token().character() == '[') {
2704 p.get_token(); // eat '['
2705 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2709 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2710 // the caption comes always as the last
2712 // we must make sure that the caption gets a \begin_layout
2713 os << "\n\\begin_layout Plain Layout";
2715 begin_inset(os, "Caption\n");
2716 Context newcontext(true, context.textclass);
2717 newcontext.font = context.font;
2718 newcontext.check_layout(os);
2719 os << caption << "\n";
2720 newcontext.check_end_layout(os);
2721 // We don't need really a new paragraph, but
2722 // we must make sure that the next item gets a \begin_layout.
2723 //newcontext.new_paragraph(os);
2727 // We don't need really a new paragraph, but
2728 // we must make sure that the next item gets a \begin_layout.
2730 context.new_paragraph(os);
2733 context.check_end_layout(os);
2734 // close the layout we opened
2736 os << "\n\\end_layout\n";
2738 // if the float type is not supported or there is no surrounding float
2741 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2742 handle_ert(os, t.asInput() + '[' + opt_arg +
2743 "]{" + p.verbatim_item() + '}', context);
2745 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2749 else if (t.cs() == "includegraphics") {
2750 bool const clip = p.next_token().asInput() == "*";
2753 string const arg = p.getArg('[', ']');
2754 map<string, string> opts;
2755 vector<string> keys;
2756 split_map(arg, opts, keys);
2758 opts["clip"] = string();
2759 string name = normalize_filename(p.verbatim_item());
2761 string const path = getMasterFilePath();
2762 // We want to preserve relative / absolute filenames,
2763 // therefore path is only used for testing
2764 if (!makeAbsPath(name, path).exists()) {
2765 // The file extension is probably missing.
2766 // Now try to find it out.
2767 string const dvips_name =
2768 find_file(name, path,
2769 known_dvips_graphics_formats);
2770 string const pdftex_name =
2771 find_file(name, path,
2772 known_pdftex_graphics_formats);
2773 if (!dvips_name.empty()) {
2774 if (!pdftex_name.empty()) {
2775 cerr << "This file contains the "
2777 "\"\\includegraphics{"
2779 "However, files\n\""
2780 << dvips_name << "\" and\n\""
2781 << pdftex_name << "\"\n"
2782 "both exist, so I had to make a "
2783 "choice and took the first one.\n"
2784 "Please move the unwanted one "
2785 "someplace else and try again\n"
2786 "if my choice was wrong."
2790 } else if (!pdftex_name.empty()) {
2796 if (makeAbsPath(name, path).exists())
2797 fix_relative_filename(name);
2799 cerr << "Warning: Could not find graphics file '"
2800 << name << "'." << endl;
2802 context.check_layout(os);
2803 begin_inset(os, "Graphics ");
2804 os << "\n\tfilename " << name << '\n';
2805 if (opts.find("width") != opts.end())
2807 << translate_len(opts["width"]) << '\n';
2808 if (opts.find("height") != opts.end())
2810 << translate_len(opts["height"]) << '\n';
2811 if (opts.find("scale") != opts.end()) {
2812 istringstream iss(opts["scale"]);
2816 os << "\tscale " << val << '\n';
2818 if (opts.find("angle") != opts.end()) {
2819 os << "\trotateAngle "
2820 << opts["angle"] << '\n';
2821 vector<string>::const_iterator a =
2822 find(keys.begin(), keys.end(), "angle");
2823 vector<string>::const_iterator s =
2824 find(keys.begin(), keys.end(), "width");
2825 if (s == keys.end())
2826 s = find(keys.begin(), keys.end(), "height");
2827 if (s == keys.end())
2828 s = find(keys.begin(), keys.end(), "scale");
2829 if (s != keys.end() && distance(s, a) > 0)
2830 os << "\tscaleBeforeRotation\n";
2832 if (opts.find("origin") != opts.end()) {
2834 string const opt = opts["origin"];
2835 if (opt.find('l') != string::npos) ss << "left";
2836 if (opt.find('r') != string::npos) ss << "right";
2837 if (opt.find('c') != string::npos) ss << "center";
2838 if (opt.find('t') != string::npos) ss << "Top";
2839 if (opt.find('b') != string::npos) ss << "Bottom";
2840 if (opt.find('B') != string::npos) ss << "Baseline";
2841 if (!ss.str().empty())
2842 os << "\trotateOrigin " << ss.str() << '\n';
2844 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2846 if (opts.find("keepaspectratio") != opts.end())
2847 os << "\tkeepAspectRatio\n";
2848 if (opts.find("clip") != opts.end())
2850 if (opts.find("draft") != opts.end())
2852 if (opts.find("bb") != opts.end())
2853 os << "\tBoundingBox "
2854 << opts["bb"] << '\n';
2855 int numberOfbbOptions = 0;
2856 if (opts.find("bbllx") != opts.end())
2857 numberOfbbOptions++;
2858 if (opts.find("bblly") != opts.end())
2859 numberOfbbOptions++;
2860 if (opts.find("bburx") != opts.end())
2861 numberOfbbOptions++;
2862 if (opts.find("bbury") != opts.end())
2863 numberOfbbOptions++;
2864 if (numberOfbbOptions == 4)
2865 os << "\tBoundingBox "
2866 << opts["bbllx"] << " " << opts["bblly"] << " "
2867 << opts["bburx"] << " " << opts["bbury"] << '\n';
2868 else if (numberOfbbOptions > 0)
2869 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2870 numberOfbbOptions = 0;
2871 if (opts.find("natwidth") != opts.end())
2872 numberOfbbOptions++;
2873 if (opts.find("natheight") != opts.end())
2874 numberOfbbOptions++;
2875 if (numberOfbbOptions == 2)
2876 os << "\tBoundingBox 0bp 0bp "
2877 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2878 else if (numberOfbbOptions > 0)
2879 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2880 ostringstream special;
2881 if (opts.find("hiresbb") != opts.end())
2882 special << "hiresbb,";
2883 if (opts.find("trim") != opts.end())
2885 if (opts.find("viewport") != opts.end())
2886 special << "viewport=" << opts["viewport"] << ',';
2887 if (opts.find("totalheight") != opts.end())
2888 special << "totalheight=" << opts["totalheight"] << ',';
2889 if (opts.find("type") != opts.end())
2890 special << "type=" << opts["type"] << ',';
2891 if (opts.find("ext") != opts.end())
2892 special << "ext=" << opts["ext"] << ',';
2893 if (opts.find("read") != opts.end())
2894 special << "read=" << opts["read"] << ',';
2895 if (opts.find("command") != opts.end())
2896 special << "command=" << opts["command"] << ',';
2897 string s_special = special.str();
2898 if (!s_special.empty()) {
2899 // We had special arguments. Remove the trailing ','.
2900 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2902 // TODO: Handle the unknown settings better.
2903 // Warn about invalid options.
2904 // Check whether some option was given twice.
2906 preamble.registerAutomaticallyLoadedPackage("graphicx");
2909 else if (t.cs() == "footnote" ||
2910 (t.cs() == "thanks" && context.layout->intitle)) {
2912 context.check_layout(os);
2913 begin_inset(os, "Foot\n");
2914 os << "status collapsed\n\n";
2915 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2919 else if (t.cs() == "marginpar") {
2921 context.check_layout(os);
2922 begin_inset(os, "Marginal\n");
2923 os << "status collapsed\n\n";
2924 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2928 else if (t.cs() == "lstinline") {
2930 parse_listings(p, os, context, true);
2933 else if (t.cs() == "ensuremath") {
2935 context.check_layout(os);
2936 string const s = p.verbatim_item();
2937 //FIXME: this never triggers in UTF8
2938 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2941 handle_ert(os, "\\ensuremath{" + s + "}",
2945 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2946 if (preamble.titleLayoutFound()) {
2948 skip_spaces_braces(p);
2950 handle_ert(os, t.asInput(), context);
2953 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
2954 context.check_layout(os);
2955 begin_command_inset(os, "toc", t.cs());
2957 skip_spaces_braces(p);
2958 if (t.cs() == "lstlistoflistings")
2959 preamble.registerAutomaticallyLoadedPackage("listings");
2962 else if (t.cs() == "listoffigures") {
2963 context.check_layout(os);
2964 begin_inset(os, "FloatList figure\n");
2966 skip_spaces_braces(p);
2969 else if (t.cs() == "listoftables") {
2970 context.check_layout(os);
2971 begin_inset(os, "FloatList table\n");
2973 skip_spaces_braces(p);
2976 else if (t.cs() == "listof") {
2977 p.skip_spaces(true);
2978 string const name = p.get_token().cs();
2979 if (context.textclass.floats().typeExist(name)) {
2980 context.check_layout(os);
2981 begin_inset(os, "FloatList ");
2984 p.get_token(); // swallow second arg
2986 handle_ert(os, "\\listof{" + name + "}", context);
2989 else if ((where = is_known(t.cs(), known_text_font_families)))
2990 parse_text_attributes(p, os, FLAG_ITEM, outer,
2991 context, "\\family", context.font.family,
2992 known_coded_font_families[where - known_text_font_families]);
2994 else if ((where = is_known(t.cs(), known_text_font_series)))
2995 parse_text_attributes(p, os, FLAG_ITEM, outer,
2996 context, "\\series", context.font.series,
2997 known_coded_font_series[where - known_text_font_series]);
2999 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3000 parse_text_attributes(p, os, FLAG_ITEM, outer,
3001 context, "\\shape", context.font.shape,
3002 known_coded_font_shapes[where - known_text_font_shapes]);
3004 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3005 context.check_layout(os);
3006 TeXFont oldFont = context.font;
3007 context.font.init();
3008 context.font.size = oldFont.size;
3009 os << "\n\\family " << context.font.family << "\n";
3010 os << "\n\\series " << context.font.series << "\n";
3011 os << "\n\\shape " << context.font.shape << "\n";
3012 if (t.cs() == "textnormal") {
3013 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3014 output_font_change(os, context.font, oldFont);
3015 context.font = oldFont;
3017 eat_whitespace(p, os, context, false);
3020 else if (t.cs() == "textcolor") {
3021 // scheme is \textcolor{color name}{text}
3022 string const color = p.verbatim_item();
3023 // we only support the predefined colors of the color package
3024 if (color == "black" || color == "blue" || color == "cyan"
3025 || color == "green" || color == "magenta" || color == "red"
3026 || color == "white" || color == "yellow") {
3027 context.check_layout(os);
3028 os << "\n\\color " << color << "\n";
3029 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3030 context.check_layout(os);
3031 os << "\n\\color inherit\n";
3032 preamble.registerAutomaticallyLoadedPackage("color");
3034 // for custom defined colors
3035 handle_ert(os, t.asInput() + "{" + color + "}", context);
3038 else if (t.cs() == "underbar" || t.cs() == "uline") {
3039 // \underbar is not 100% correct (LyX outputs \uline
3040 // of ulem.sty). The difference is that \ulem allows
3041 // line breaks, and \underbar does not.
3042 // Do NOT handle \underline.
3043 // \underbar cuts through y, g, q, p etc.,
3044 // \underline does not.
3045 context.check_layout(os);
3046 os << "\n\\bar under\n";
3047 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3048 context.check_layout(os);
3049 os << "\n\\bar default\n";
3050 preamble.registerAutomaticallyLoadedPackage("ulem");
3053 else if (t.cs() == "sout") {
3054 context.check_layout(os);
3055 os << "\n\\strikeout on\n";
3056 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3057 context.check_layout(os);
3058 os << "\n\\strikeout default\n";
3059 preamble.registerAutomaticallyLoadedPackage("ulem");
3062 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3063 t.cs() == "emph" || t.cs() == "noun") {
3064 context.check_layout(os);
3065 os << "\n\\" << t.cs() << " on\n";
3066 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3067 context.check_layout(os);
3068 os << "\n\\" << t.cs() << " default\n";
3069 if (t.cs() == "uuline" || t.cs() == "uwave")
3070 preamble.registerAutomaticallyLoadedPackage("ulem");
3073 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3074 context.check_layout(os);
3075 string name = p.getArg('{', '}');
3076 string localtime = p.getArg('{', '}');
3077 preamble.registerAuthor(name);
3078 Author const & author = preamble.getAuthor(name);
3079 // from_ctime() will fail if LyX decides to output the
3080 // time in the text language. It might also use a wrong
3081 // time zone (if the original LyX document was exported
3082 // with a different time zone).
3083 time_t ptime = from_ctime(localtime);
3084 if (ptime == static_cast<time_t>(-1)) {
3085 cerr << "Warning: Could not parse time `" << localtime
3086 << "´ for change tracking, using current time instead.\n";
3087 ptime = current_time();
3089 if (t.cs() == "lyxadded")
3090 os << "\n\\change_inserted ";
3092 os << "\n\\change_deleted ";
3093 os << author.bufferId() << ' ' << ptime << '\n';
3094 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3095 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3096 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3097 LaTeXPackages::isAvailable("xcolor");
3098 // No need to test for luatex, since luatex comes in
3099 // two flavours (dvi and pdf), like latex, and those
3100 // are detected by pdflatex.
3101 if (pdflatex || xetex) {
3103 preamble.registerAutomaticallyLoadedPackage("ulem");
3104 preamble.registerAutomaticallyLoadedPackage("xcolor");
3105 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3109 preamble.registerAutomaticallyLoadedPackage("dvipost");
3110 } else if (xcolorulem) {
3111 preamble.registerAutomaticallyLoadedPackage("ulem");
3112 preamble.registerAutomaticallyLoadedPackage("xcolor");
3117 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3118 t.cs() == "vphantom") {
3119 context.check_layout(os);
3120 if (t.cs() == "phantom")
3121 begin_inset(os, "Phantom Phantom\n");
3122 if (t.cs() == "hphantom")
3123 begin_inset(os, "Phantom HPhantom\n");
3124 if (t.cs() == "vphantom")
3125 begin_inset(os, "Phantom VPhantom\n");
3126 os << "status open\n";
3127 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3132 else if (t.cs() == "href") {
3133 context.check_layout(os);
3134 string target = p.getArg('{', '}');
3135 string name = p.getArg('{', '}');
3137 size_t i = target.find(':');
3138 if (i != string::npos) {
3139 type = target.substr(0, i + 1);
3140 if (type == "mailto:" || type == "file:")
3141 target = target.substr(i + 1);
3142 // handle the case that name is equal to target, except of "http://"
3143 else if (target.substr(i + 3) == name && type == "http:")
3146 begin_command_inset(os, "href", "href");
3148 os << "name \"" << name << "\"\n";
3149 os << "target \"" << target << "\"\n";
3150 if (type == "mailto:" || type == "file:")
3151 os << "type \"" << type << "\"\n";
3153 skip_spaces_braces(p);
3156 else if (t.cs() == "lyxline") {
3157 // swallow size argument (it is not used anyway)
3159 if (!context.atParagraphStart()) {
3160 // so our line is in the middle of a paragraph
3161 // we need to add a new line, lest this line
3162 // follow the other content on that line and
3163 // run off the side of the page
3164 // FIXME: This may create an empty paragraph,
3165 // but without that it would not be
3166 // possible to set noindent below.
3167 // Fortunately LaTeX does not care
3168 // about the empty paragraph.
3169 context.new_paragraph(os);
3171 if (preamble.indentParagraphs()) {
3172 // we need to unindent, lest the line be too long
3173 context.add_par_extra_stuff("\\noindent\n");
3175 context.check_layout(os);
3176 begin_command_inset(os, "line", "rule");
3177 os << "offset \"0.5ex\"\n"
3178 "width \"100line%\"\n"
3183 else if (t.cs() == "rule") {
3184 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3185 string const width = p.getArg('{', '}');
3186 string const thickness = p.getArg('{', '}');
3187 context.check_layout(os);
3188 begin_command_inset(os, "line", "rule");
3189 if (!offset.empty())
3190 os << "offset \"" << translate_len(offset) << "\"\n";
3191 os << "width \"" << translate_len(width) << "\"\n"
3192 "height \"" << translate_len(thickness) << "\"\n";
3196 else if (is_known(t.cs(), known_phrases) ||
3197 (t.cs() == "protect" &&
3198 p.next_token().cat() == catEscape &&
3199 is_known(p.next_token().cs(), known_phrases))) {
3200 // LyX sometimes puts a \protect in front, so we have to ignore it
3201 // FIXME: This needs to be changed when bug 4752 is fixed.
3203 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3205 context.check_layout(os);
3206 os << known_coded_phrases[where - known_phrases];
3207 skip_spaces_braces(p);
3210 else if ((where = is_known(t.cs(), known_ref_commands))) {
3211 string const opt = p.getOpt();
3213 context.check_layout(os);
3214 begin_command_inset(os, "ref",
3215 known_coded_ref_commands[where - known_ref_commands]);
3216 os << "reference \""
3217 << convert_command_inset_arg(p.verbatim_item())
3220 if (t.cs() == "vref" || t.cs() == "vpageref")
3221 preamble.registerAutomaticallyLoadedPackage("varioref");
3224 // LyX does not support optional arguments of ref commands
3225 handle_ert(os, t.asInput() + '[' + opt + "]{" +
3226 p.verbatim_item() + "}", context);
3230 else if (use_natbib &&
3231 is_known(t.cs(), known_natbib_commands) &&
3232 ((t.cs() != "citefullauthor" &&
3233 t.cs() != "citeyear" &&
3234 t.cs() != "citeyearpar") ||
3235 p.next_token().asInput() != "*")) {
3236 context.check_layout(os);
3237 string command = t.cs();
3238 if (p.next_token().asInput() == "*") {
3242 if (command == "citefullauthor")
3243 // alternative name for "\\citeauthor*"
3244 command = "citeauthor*";
3246 // text before the citation
3248 // text after the citation
3250 get_cite_arguments(p, true, before, after);
3252 if (command == "cite") {
3253 // \cite without optional argument means
3254 // \citet, \cite with at least one optional
3255 // argument means \citep.
3256 if (before.empty() && after.empty())
3261 if (before.empty() && after == "[]")
3262 // avoid \citet[]{a}
3264 else if (before == "[]" && after == "[]") {
3265 // avoid \citet[][]{a}
3269 // remove the brackets around after and before
3270 if (!after.empty()) {
3272 after.erase(after.length() - 1, 1);
3273 after = convert_command_inset_arg(after);
3275 if (!before.empty()) {
3277 before.erase(before.length() - 1, 1);
3278 before = convert_command_inset_arg(before);
3280 begin_command_inset(os, "citation", command);
3281 os << "after " << '"' << after << '"' << "\n";
3282 os << "before " << '"' << before << '"' << "\n";
3284 << convert_command_inset_arg(p.verbatim_item())
3289 else if (use_jurabib &&
3290 is_known(t.cs(), known_jurabib_commands) &&
3291 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3292 context.check_layout(os);
3293 string command = t.cs();
3294 if (p.next_token().asInput() == "*") {
3298 char argumentOrder = '\0';
3299 vector<string> const options =
3300 preamble.getPackageOptions("jurabib");
3301 if (find(options.begin(), options.end(),
3302 "natbiborder") != options.end())
3303 argumentOrder = 'n';
3304 else if (find(options.begin(), options.end(),
3305 "jurabiborder") != options.end())
3306 argumentOrder = 'j';
3308 // text before the citation
3310 // text after the citation
3312 get_cite_arguments(p, argumentOrder != 'j', before, after);
3314 string const citation = p.verbatim_item();
3315 if (!before.empty() && argumentOrder == '\0') {
3316 cerr << "Warning: Assuming argument order "
3317 "of jurabib version 0.6 for\n'"
3318 << command << before << after << '{'
3319 << citation << "}'.\n"
3320 "Add 'jurabiborder' to the jurabib "
3321 "package options if you used an\n"
3322 "earlier jurabib version." << endl;
3324 if (!after.empty()) {
3326 after.erase(after.length() - 1, 1);
3328 if (!before.empty()) {
3330 before.erase(before.length() - 1, 1);
3332 begin_command_inset(os, "citation", command);
3333 os << "after " << '"' << after << '"' << "\n";
3334 os << "before " << '"' << before << '"' << "\n";
3335 os << "key " << '"' << citation << '"' << "\n";
3339 else if (t.cs() == "cite"
3340 || t.cs() == "nocite") {
3341 context.check_layout(os);
3342 string after = convert_command_inset_arg(p.getArg('[', ']'));
3343 string key = convert_command_inset_arg(p.verbatim_item());
3344 // store the case that it is "\nocite{*}" to use it later for
3347 begin_command_inset(os, "citation", t.cs());
3348 os << "after " << '"' << after << '"' << "\n";
3349 os << "key " << '"' << key << '"' << "\n";
3351 } else if (t.cs() == "nocite")
3355 else if (t.cs() == "index" ||
3356 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3357 context.check_layout(os);
3358 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3359 p.getArg('[', ']') : "";
3360 string const kind = arg.empty() ? "idx" : arg;
3361 begin_inset(os, "Index ");
3362 os << kind << "\nstatus collapsed\n";
3363 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3366 preamble.registerAutomaticallyLoadedPackage("splitidx");
3369 else if (t.cs() == "nomenclature") {
3370 context.check_layout(os);
3371 begin_command_inset(os, "nomenclature", "nomenclature");
3372 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3373 if (!prefix.empty())
3374 os << "prefix " << '"' << prefix << '"' << "\n";
3375 os << "symbol " << '"'
3376 << convert_command_inset_arg(p.verbatim_item());
3377 os << "\"\ndescription \""
3378 << convert_command_inset_arg(p.verbatim_item())
3381 preamble.registerAutomaticallyLoadedPackage("nomencl");
3384 else if (t.cs() == "label") {
3385 context.check_layout(os);
3386 begin_command_inset(os, "label", "label");
3388 << convert_command_inset_arg(p.verbatim_item())
3393 else if (t.cs() == "printindex") {
3394 context.check_layout(os);
3395 begin_command_inset(os, "index_print", "printindex");
3396 os << "type \"idx\"\n";
3398 skip_spaces_braces(p);
3399 preamble.registerAutomaticallyLoadedPackage("makeidx");
3400 if (preamble.use_indices() == "true")
3401 preamble.registerAutomaticallyLoadedPackage("splitidx");
3404 else if (t.cs() == "printnomenclature") {
3406 string width_type = "";
3407 context.check_layout(os);
3408 begin_command_inset(os, "nomencl_print", "printnomenclature");
3409 // case of a custom width
3411 width = p.getArg('[', ']');
3412 width = translate_len(width);
3413 width_type = "custom";
3415 // case of no custom width
3416 // the case of no custom width but the width set
3417 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3418 // because the user could have set anything, not only the width
3419 // of the longest label (which would be width_type = "auto")
3420 string label = convert_command_inset_arg(p.getArg('{', '}'));
3421 if (label.empty() && width_type.empty())
3422 width_type = "none";
3423 os << "set_width \"" << width_type << "\"\n";
3424 if (width_type == "custom")
3425 os << "width \"" << width << '\"';
3427 skip_spaces_braces(p);
3428 preamble.registerAutomaticallyLoadedPackage("nomencl");
3431 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3432 context.check_layout(os);
3433 begin_inset(os, "script ");
3434 os << t.cs().substr(4) << '\n';
3435 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3437 if (t.cs() == "textsubscript")
3438 preamble.registerAutomaticallyLoadedPackage("subscript");
3441 else if ((where = is_known(t.cs(), known_quotes))) {
3442 context.check_layout(os);
3443 begin_inset(os, "Quotes ");
3444 os << known_coded_quotes[where - known_quotes];
3446 // LyX adds {} after the quote, so we have to eat
3447 // spaces here if there are any before a possible
3449 eat_whitespace(p, os, context, false);
3453 else if ((where = is_known(t.cs(), known_sizes)) &&
3454 context.new_layout_allowed) {
3455 context.check_layout(os);
3456 TeXFont const oldFont = context.font;
3457 context.font.size = known_coded_sizes[where - known_sizes];
3458 output_font_change(os, oldFont, context.font);
3459 eat_whitespace(p, os, context, false);
3462 else if ((where = is_known(t.cs(), known_font_families)) &&
3463 context.new_layout_allowed) {
3464 context.check_layout(os);
3465 TeXFont const oldFont = context.font;
3466 context.font.family =
3467 known_coded_font_families[where - known_font_families];
3468 output_font_change(os, oldFont, context.font);
3469 eat_whitespace(p, os, context, false);
3472 else if ((where = is_known(t.cs(), known_font_series)) &&
3473 context.new_layout_allowed) {
3474 context.check_layout(os);
3475 TeXFont const oldFont = context.font;
3476 context.font.series =
3477 known_coded_font_series[where - known_font_series];
3478 output_font_change(os, oldFont, context.font);
3479 eat_whitespace(p, os, context, false);
3482 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3483 context.new_layout_allowed) {
3484 context.check_layout(os);
3485 TeXFont const oldFont = context.font;
3486 context.font.shape =
3487 known_coded_font_shapes[where - known_font_shapes];
3488 output_font_change(os, oldFont, context.font);
3489 eat_whitespace(p, os, context, false);
3491 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3492 context.new_layout_allowed) {
3493 context.check_layout(os);
3494 TeXFont const oldFont = context.font;
3495 context.font.init();
3496 context.font.size = oldFont.size;
3497 context.font.family =
3498 known_coded_font_families[where - known_old_font_families];
3499 output_font_change(os, oldFont, context.font);
3500 eat_whitespace(p, os, context, false);
3503 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3504 context.new_layout_allowed) {
3505 context.check_layout(os);
3506 TeXFont const oldFont = context.font;
3507 context.font.init();
3508 context.font.size = oldFont.size;
3509 context.font.series =
3510 known_coded_font_series[where - known_old_font_series];
3511 output_font_change(os, oldFont, context.font);
3512 eat_whitespace(p, os, context, false);
3515 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3516 context.new_layout_allowed) {
3517 context.check_layout(os);
3518 TeXFont const oldFont = context.font;
3519 context.font.init();
3520 context.font.size = oldFont.size;
3521 context.font.shape =
3522 known_coded_font_shapes[where - known_old_font_shapes];
3523 output_font_change(os, oldFont, context.font);
3524 eat_whitespace(p, os, context, false);
3527 else if (t.cs() == "selectlanguage") {
3528 context.check_layout(os);
3529 // save the language for the case that a
3530 // \foreignlanguage is used
3531 context.font.language = babel2lyx(p.verbatim_item());
3532 os << "\n\\lang " << context.font.language << "\n";
3535 else if (t.cs() == "foreignlanguage") {
3536 string const lang = babel2lyx(p.verbatim_item());
3537 parse_text_attributes(p, os, FLAG_ITEM, outer,
3539 context.font.language, lang);
3542 else if (prefixIs(t.cs(), "text")
3543 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3544 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3546 // We have to output the whole command if it has an option
3547 // because LyX doesn't support this yet, see bug #8214,
3548 // only if there is a single option specifying a variant, we can handle it.
3550 string langopts = p.getOpt();
3551 // check if the option contains a variant, if yes, extract it
3552 string::size_type pos_var = langopts.find("variant");
3553 string::size_type i = langopts.find(',');
3554 string::size_type k = langopts.find('=', pos_var);
3555 if (pos_var != string::npos && i == string::npos) {
3557 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3558 lang = preamble.polyglossia2lyx(variant);
3559 parse_text_attributes(p, os, FLAG_ITEM, outer,
3561 context.font.language, lang);
3563 handle_ert(os, t.asInput() + langopts, context);
3565 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3566 parse_text_attributes(p, os, FLAG_ITEM, outer,
3568 context.font.language, lang);
3572 else if (t.cs() == "inputencoding") {
3573 // nothing to write here
3574 string const enc = subst(p.verbatim_item(), "\n", " ");
3578 else if ((where = is_known(t.cs(), known_special_chars))) {
3579 context.check_layout(os);
3580 os << "\\SpecialChar \\"
3581 << known_coded_special_chars[where - known_special_chars]
3583 skip_spaces_braces(p);
3586 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3587 context.check_layout(os);
3588 os << "\\SpecialChar \\nobreakdash-\n";
3592 else if (t.cs() == "textquotedbl") {
3593 context.check_layout(os);
3598 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3599 context.check_layout(os);
3600 os << "\\SpecialChar \\@.\n";
3604 else if (t.cs() == "-") {
3605 context.check_layout(os);
3606 os << "\\SpecialChar \\-\n";
3609 else if (t.cs() == "textasciitilde") {
3610 context.check_layout(os);
3612 skip_spaces_braces(p);
3615 else if (t.cs() == "textasciicircum") {
3616 context.check_layout(os);
3618 skip_spaces_braces(p);
3621 else if (t.cs() == "textbackslash") {
3622 context.check_layout(os);
3623 os << "\n\\backslash\n";
3624 skip_spaces_braces(p);
3627 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3628 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3630 context.check_layout(os);
3634 else if (t.cs() == "char") {
3635 context.check_layout(os);
3636 if (p.next_token().character() == '`') {
3638 if (p.next_token().cs() == "\"") {
3643 handle_ert(os, "\\char`", context);
3646 handle_ert(os, "\\char", context);
3650 else if (t.cs() == "verb") {
3651 context.check_layout(os);
3652 char const delimiter = p.next_token().character();
3653 string const arg = p.getArg(delimiter, delimiter);
3655 oss << "\\verb" << delimiter << arg << delimiter;
3656 handle_ert(os, oss.str(), context);
3659 // Problem: \= creates a tabstop inside the tabbing environment
3660 // and else an accent. In the latter case we really would want
3661 // \={o} instead of \= o.
3662 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3663 handle_ert(os, t.asInput(), context);
3665 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3666 else if (t.cs().size() == 1
3667 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3668 context.check_layout(os);
3669 // try to see whether the string is in unicodesymbols
3672 string command = t.asInput() + "{"
3673 + trimSpaceAndEol(p.verbatim_item())
3676 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3677 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3678 termination, rem, &req);
3681 cerr << "When parsing " << command
3682 << ", result is " << to_utf8(s)
3683 << "+" << to_utf8(rem) << endl;
3685 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3686 preamble.registerAutomaticallyLoadedPackage(*it);
3688 // we did not find a non-ert version
3689 handle_ert(os, command, context);
3692 else if (t.cs() == "\\") {
3693 context.check_layout(os);
3695 handle_ert(os, "\\\\" + p.getOpt(), context);
3696 else if (p.next_token().asInput() == "*") {
3698 // getOpt() eats the following space if there
3699 // is no optional argument, but that is OK
3700 // here since it has no effect in the output.
3701 handle_ert(os, "\\\\*" + p.getOpt(), context);
3704 begin_inset(os, "Newline newline");
3709 else if (t.cs() == "newline" ||
3710 (t.cs() == "linebreak" && !p.hasOpt())) {
3711 context.check_layout(os);
3712 begin_inset(os, "Newline ");
3715 skip_spaces_braces(p);
3718 else if (t.cs() == "input" || t.cs() == "include"
3719 || t.cs() == "verbatiminput") {
3720 string name = t.cs();
3721 if (t.cs() == "verbatiminput"
3722 && p.next_token().asInput() == "*")
3723 name += p.get_token().asInput();
3724 context.check_layout(os);
3725 string filename(normalize_filename(p.getArg('{', '}')));
3726 string const path = getMasterFilePath();
3727 // We want to preserve relative / absolute filenames,
3728 // therefore path is only used for testing
3729 if ((t.cs() == "include" || t.cs() == "input") &&
3730 !makeAbsPath(filename, path).exists()) {
3731 // The file extension is probably missing.
3732 // Now try to find it out.
3733 string const tex_name =
3734 find_file(filename, path,
3735 known_tex_extensions);
3736 if (!tex_name.empty())
3737 filename = tex_name;
3739 bool external = false;
3741 if (makeAbsPath(filename, path).exists()) {
3742 string const abstexname =
3743 makeAbsPath(filename, path).absFileName();
3744 string const abslyxname =
3745 changeExtension(abstexname, ".lyx");
3746 string const absfigname =
3747 changeExtension(abstexname, ".fig");
3748 fix_relative_filename(filename);
3749 string const lyxname =
3750 changeExtension(filename, ".lyx");
3752 external = FileName(absfigname).exists();
3753 if (t.cs() == "input") {
3754 string const ext = getExtension(abstexname);
3756 // Combined PS/LaTeX:
3757 // x.eps, x.pstex_t (old xfig)
3758 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3759 FileName const absepsname(
3760 changeExtension(abstexname, ".eps"));
3761 FileName const abspstexname(
3762 changeExtension(abstexname, ".pstex"));
3763 bool const xfigeps =
3764 (absepsname.exists() ||
3765 abspstexname.exists()) &&
3768 // Combined PDF/LaTeX:
3769 // x.pdf, x.pdftex_t (old xfig)
3770 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3771 FileName const abspdfname(
3772 changeExtension(abstexname, ".pdf"));
3773 bool const xfigpdf =
3774 abspdfname.exists() &&
3775 (ext == "pdftex_t" || ext == "pdf_t");
3779 // Combined PS/PDF/LaTeX:
3780 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3781 string const absbase2(
3782 removeExtension(abstexname) + "_pspdftex");
3783 FileName const abseps2name(
3784 addExtension(absbase2, ".eps"));
3785 FileName const abspdf2name(
3786 addExtension(absbase2, ".pdf"));
3787 bool const xfigboth =
3788 abspdf2name.exists() &&
3789 abseps2name.exists() && ext == "pspdftex";
3791 xfig = xfigpdf || xfigeps || xfigboth;
3792 external = external && xfig;
3795 outname = changeExtension(filename, ".fig");
3797 // Don't try to convert, the result
3798 // would be full of ERT.
3800 } else if (t.cs() != "verbatiminput" &&
3801 tex2lyx(abstexname, FileName(abslyxname),
3808 cerr << "Warning: Could not find included file '"
3809 << filename << "'." << endl;
3813 begin_inset(os, "External\n");
3814 os << "\ttemplate XFig\n"
3815 << "\tfilename " << outname << '\n';
3816 registerExternalTemplatePackages("XFig");
3818 begin_command_inset(os, "include", name);
3819 os << "preview false\n"
3820 "filename \"" << outname << "\"\n";
3821 if (t.cs() == "verbatiminput")
3822 preamble.registerAutomaticallyLoadedPackage("verbatim");
3827 else if (t.cs() == "bibliographystyle") {
3828 // store new bibliographystyle
3829 bibliographystyle = p.verbatim_item();
3830 // If any other command than \bibliography and
3831 // \nocite{*} follows, we need to output the style
3832 // (because it might be used by that command).
3833 // Otherwise, it will automatically be output by LyX.
3836 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3837 if (t2.cat() == catBegin)
3839 if (t2.cat() != catEscape)
3841 if (t2.cs() == "nocite") {
3842 if (p.getArg('{', '}') == "*")
3844 } else if (t2.cs() == "bibliography")
3851 "\\bibliographystyle{" + bibliographystyle + '}',
3856 else if (t.cs() == "bibliography") {
3857 context.check_layout(os);
3858 begin_command_inset(os, "bibtex", "bibtex");
3859 if (!btprint.empty()) {
3860 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3861 // clear the string because the next BibTeX inset can be without the
3862 // \nocite{*} option
3865 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3866 // Do we have a bibliographystyle set?
3867 if (!bibliographystyle.empty())
3868 os << "options " << '"' << bibliographystyle << '"' << "\n";
3872 else if (t.cs() == "parbox") {
3873 // Test whether this is an outer box of a shaded box
3875 // swallow arguments
3876 while (p.hasOpt()) {
3878 p.skip_spaces(true);
3881 p.skip_spaces(true);
3883 if (p.next_token().cat() == catBegin)
3885 p.skip_spaces(true);
3886 Token to = p.get_token();
3887 bool shaded = false;
3888 if (to.asInput() == "\\begin") {
3889 p.skip_spaces(true);
3890 if (p.getArg('{', '}') == "shaded")
3895 parse_outer_box(p, os, FLAG_ITEM, outer,
3896 context, "parbox", "shaded");
3898 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3902 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3903 t.cs() == "shadowbox" || t.cs() == "doublebox")
3904 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3906 else if (t.cs() == "framebox") {
3907 if (p.next_token().character() == '(') {
3908 //the syntax is: \framebox(x,y)[position]{content}
3909 string arg = t.asInput();
3910 arg += p.getFullParentheseArg();
3911 arg += p.getFullOpt();
3912 eat_whitespace(p, os, context, false);
3913 handle_ert(os, arg + '{', context);
3914 parse_text(p, os, FLAG_ITEM, outer, context);
3915 handle_ert(os, "}", context);
3917 string special = p.getFullOpt();
3918 special += p.getOpt();
3919 // LyX does not yet support \framebox without any option
3920 if (!special.empty())
3921 parse_outer_box(p, os, FLAG_ITEM, outer,
3922 context, t.cs(), special);
3924 eat_whitespace(p, os, context, false);
3925 handle_ert(os, "\\framebox{", context);
3926 parse_text(p, os, FLAG_ITEM, outer, context);
3927 handle_ert(os, "}", context);
3932 //\makebox() is part of the picture environment and different from \makebox{}
3933 //\makebox{} will be parsed by parse_box
3934 else if (t.cs() == "makebox") {
3935 if (p.next_token().character() == '(') {
3936 //the syntax is: \makebox(x,y)[position]{content}
3937 string arg = t.asInput();
3938 arg += p.getFullParentheseArg();
3939 arg += p.getFullOpt();
3940 eat_whitespace(p, os, context, false);
3941 handle_ert(os, arg + '{', context);
3942 parse_text(p, os, FLAG_ITEM, outer, context);
3943 handle_ert(os, "}", context);
3945 //the syntax is: \makebox[width][position]{content}
3946 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3950 else if (t.cs() == "smallskip" ||
3951 t.cs() == "medskip" ||
3952 t.cs() == "bigskip" ||
3953 t.cs() == "vfill") {
3954 context.check_layout(os);
3955 begin_inset(os, "VSpace ");
3958 skip_spaces_braces(p);
3961 else if ((where = is_known(t.cs(), known_spaces))) {
3962 context.check_layout(os);
3963 begin_inset(os, "space ");
3964 os << '\\' << known_coded_spaces[where - known_spaces]
3967 // LaTeX swallows whitespace after all spaces except
3968 // "\\,". We have to do that here, too, because LyX
3969 // adds "{}" which would make the spaces significant.
3971 eat_whitespace(p, os, context, false);
3972 // LyX adds "{}" after all spaces except "\\ " and
3973 // "\\,", so we have to remove "{}".
3974 // "\\,{}" is equivalent to "\\," in LaTeX, so we
3975 // remove the braces after "\\,", too.
3980 else if (t.cs() == "newpage" ||
3981 (t.cs() == "pagebreak" && !p.hasOpt()) ||
3982 t.cs() == "clearpage" ||
3983 t.cs() == "cleardoublepage") {
3984 context.check_layout(os);
3985 begin_inset(os, "Newpage ");
3988 skip_spaces_braces(p);
3991 else if (t.cs() == "DeclareRobustCommand" ||
3992 t.cs() == "DeclareRobustCommandx" ||
3993 t.cs() == "newcommand" ||
3994 t.cs() == "newcommandx" ||
3995 t.cs() == "providecommand" ||
3996 t.cs() == "providecommandx" ||
3997 t.cs() == "renewcommand" ||
3998 t.cs() == "renewcommandx") {
3999 // DeclareRobustCommand, DeclareRobustCommandx,
4000 // providecommand and providecommandx could be handled
4001 // by parse_command(), but we need to call
4002 // add_known_command() here.
4003 string name = t.asInput();
4004 if (p.next_token().asInput() == "*") {
4005 // Starred form. Eat '*'
4009 string const command = p.verbatim_item();
4010 string const opt1 = p.getFullOpt();
4011 string const opt2 = p.getFullOpt();
4012 add_known_command(command, opt1, !opt2.empty());
4013 string const ert = name + '{' + command + '}' +
4015 '{' + p.verbatim_item() + '}';
4017 if (t.cs() == "DeclareRobustCommand" ||
4018 t.cs() == "DeclareRobustCommandx" ||
4019 t.cs() == "providecommand" ||
4020 t.cs() == "providecommandx" ||
4021 name[name.length()-1] == '*')
4022 handle_ert(os, ert, context);
4024 context.check_layout(os);
4025 begin_inset(os, "FormulaMacro");
4031 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4032 // let could be handled by parse_command(),
4033 // but we need to call add_known_command() here.
4034 string ert = t.asInput();
4037 if (p.next_token().cat() == catBegin) {
4038 name = p.verbatim_item();
4039 ert += '{' + name + '}';
4041 name = p.verbatim_item();
4046 if (p.next_token().cat() == catBegin) {
4047 command = p.verbatim_item();
4048 ert += '{' + command + '}';
4050 command = p.verbatim_item();
4053 // If command is known, make name known too, to parse
4054 // its arguments correctly. For this reason we also
4055 // have commands in syntax.default that are hardcoded.
4056 CommandMap::iterator it = known_commands.find(command);
4057 if (it != known_commands.end())
4058 known_commands[t.asInput()] = it->second;
4059 handle_ert(os, ert, context);
4062 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4063 bool starred = false;
4064 if (p.next_token().asInput() == "*") {
4068 string name = t.asInput();
4069 string const length = p.verbatim_item();
4072 bool valid = splitLatexLength(length, valstring, unit);
4073 bool known_hspace = false;
4074 bool known_vspace = false;
4075 bool known_unit = false;
4078 istringstream iss(valstring);
4081 if (t.cs()[0] == 'h') {
4082 if (unit == "\\fill") {
4087 known_hspace = true;
4090 if (unit == "\\smallskipamount") {
4092 known_vspace = true;
4093 } else if (unit == "\\medskipamount") {
4095 known_vspace = true;
4096 } else if (unit == "\\bigskipamount") {
4098 known_vspace = true;
4099 } else if (unit == "\\fill") {
4101 known_vspace = true;
4105 if (!known_hspace && !known_vspace) {
4106 switch (unitFromString(unit)) {
4127 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4128 // Literal horizontal length or known variable
4129 context.check_layout(os);
4130 begin_inset(os, "space ");
4138 if (known_unit && !known_hspace)
4140 << translate_len(length);
4142 } else if (known_unit || known_vspace) {
4143 // Literal vertical length or known variable
4144 context.check_layout(os);
4145 begin_inset(os, "VSpace ");
4153 // LyX can't handle other length variables in Inset VSpace/space
4158 handle_ert(os, name + '{' + unit + '}', context);
4159 else if (value == -1.0)
4160 handle_ert(os, name + "{-" + unit + '}', context);
4162 handle_ert(os, name + '{' + valstring + unit + '}', context);
4164 handle_ert(os, name + '{' + length + '}', context);
4168 // The single '=' is meant here.
4169 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4171 context.check_layout(os);
4172 begin_inset(os, "Flex ");
4173 os << to_utf8(newinsetlayout->name()) << '\n'
4174 << "status collapsed\n";
4175 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4179 else if (t.cs() == "includepdf") {
4181 string const arg = p.getArg('[', ']');
4182 map<string, string> opts;
4183 vector<string> keys;
4184 split_map(arg, opts, keys);
4185 string name = normalize_filename(p.verbatim_item());
4186 string const path = getMasterFilePath();
4187 // We want to preserve relative / absolute filenames,
4188 // therefore path is only used for testing
4189 if (!makeAbsPath(name, path).exists()) {
4190 // The file extension is probably missing.
4191 // Now try to find it out.
4192 char const * const pdfpages_format[] = {"pdf", 0};
4193 string const pdftex_name =
4194 find_file(name, path, pdfpages_format);
4195 if (!pdftex_name.empty()) {
4200 if (makeAbsPath(name, path).exists())
4201 fix_relative_filename(name);
4203 cerr << "Warning: Could not find file '"
4204 << name << "'." << endl;
4206 context.check_layout(os);
4207 begin_inset(os, "External\n\ttemplate ");
4208 os << "PDFPages\n\tfilename "
4210 // parse the options
4211 if (opts.find("pages") != opts.end())
4212 os << "\textra LaTeX \"pages="
4213 << opts["pages"] << "\"\n";
4214 if (opts.find("angle") != opts.end())
4215 os << "\trotateAngle "
4216 << opts["angle"] << '\n';
4217 if (opts.find("origin") != opts.end()) {
4219 string const opt = opts["origin"];
4220 if (opt == "tl") ss << "topleft";
4221 if (opt == "bl") ss << "bottomleft";
4222 if (opt == "Bl") ss << "baselineleft";
4223 if (opt == "c") ss << "center";
4224 if (opt == "tc") ss << "topcenter";
4225 if (opt == "bc") ss << "bottomcenter";
4226 if (opt == "Bc") ss << "baselinecenter";
4227 if (opt == "tr") ss << "topright";
4228 if (opt == "br") ss << "bottomright";
4229 if (opt == "Br") ss << "baselineright";
4230 if (!ss.str().empty())
4231 os << "\trotateOrigin " << ss.str() << '\n';
4233 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4235 if (opts.find("width") != opts.end())
4237 << translate_len(opts["width"]) << '\n';
4238 if (opts.find("height") != opts.end())
4240 << translate_len(opts["height"]) << '\n';
4241 if (opts.find("keepaspectratio") != opts.end())
4242 os << "\tkeepAspectRatio\n";
4244 context.check_layout(os);
4245 registerExternalTemplatePackages("PDFPages");
4248 else if (t.cs() == "loadgame") {
4250 string name = normalize_filename(p.verbatim_item());
4251 string const path = getMasterFilePath();
4252 // We want to preserve relative / absolute filenames,
4253 // therefore path is only used for testing
4254 if (!makeAbsPath(name, path).exists()) {
4255 // The file extension is probably missing.
4256 // Now try to find it out.
4257 char const * const lyxskak_format[] = {"fen", 0};
4258 string const lyxskak_name =
4259 find_file(name, path, lyxskak_format);
4260 if (!lyxskak_name.empty())
4261 name = lyxskak_name;
4263 if (makeAbsPath(name, path).exists())
4264 fix_relative_filename(name);
4266 cerr << "Warning: Could not find file '"
4267 << name << "'." << endl;
4268 context.check_layout(os);
4269 begin_inset(os, "External\n\ttemplate ");
4270 os << "ChessDiagram\n\tfilename "
4273 context.check_layout(os);
4274 // after a \loadgame follows a \showboard
4275 if (p.get_token().asInput() == "showboard")
4277 registerExternalTemplatePackages("ChessDiagram");
4281 // try to see whether the string is in unicodesymbols
4282 // Only use text mode commands, since we are in text mode here,
4283 // and math commands may be invalid (bug 6797)
4287 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4288 Encodings::TEXT_CMD, termination, rem, &req);
4291 cerr << "When parsing " << t.cs()
4292 << ", result is " << to_utf8(s)
4293 << "+" << to_utf8(rem) << endl;
4294 context.check_layout(os);
4297 skip_spaces_braces(p);
4298 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4299 preamble.registerAutomaticallyLoadedPackage(*it);
4301 //cerr << "#: " << t << " mode: " << mode << endl;
4302 // heuristic: read up to next non-nested space
4304 string s = t.asInput();
4305 string z = p.verbatim_item();
4306 while (p.good() && z != " " && z.size()) {
4307 //cerr << "read: " << z << endl;
4309 z = p.verbatim_item();
4311 cerr << "found ERT: " << s << endl;
4312 handle_ert(os, s + ' ', context);
4315 string name = t.asInput();
4316 if (p.next_token().asInput() == "*") {
4317 // Starred commands like \vspace*{}
4318 p.get_token(); // Eat '*'
4321 if (!parse_command(name, p, os, outer, context))
4322 handle_ert(os, name, context);
4326 if (flags & FLAG_LEAVE) {
4327 flags &= ~FLAG_LEAVE;