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 and Bg5 cannot be supported as they are 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 cannot 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 string const absMaster = makeAbsPath(getMasterFilePath()).absFileName();
1843 string const absParent = makeAbsPath(getParentFilePath()).absFileName();
1844 string const abs = makeAbsPath(name, absMaster).absFileName();
1845 name = to_utf8(makeRelPath(from_utf8(abs), from_utf8(absParent)));
1849 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1850 void parse_noweb(Parser & p, ostream & os, Context & context)
1852 // assemble the rest of the keyword
1856 Token const & t = p.get_token();
1857 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1860 scrap = (p.good() && p.next_token().asInput() == "=");
1862 name += p.get_token().asInput();
1865 name += t.asInput();
1868 if (!scrap || !context.new_layout_allowed ||
1869 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1870 cerr << "Warning: Could not interpret '" << name
1871 << "'. Ignoring it." << endl;
1875 // We use new_paragraph instead of check_end_layout because the stuff
1876 // following the noweb chunk needs to start with a \begin_layout.
1877 // This may create a new paragraph even if there was none in the
1878 // noweb file, but the alternative is an invalid LyX file. Since
1879 // noweb code chunks are implemented with a layout style in LyX they
1880 // always must be in an own paragraph.
1881 context.new_paragraph(os);
1882 Context newcontext(true, context.textclass,
1883 &context.textclass[from_ascii("Scrap")]);
1884 newcontext.check_layout(os);
1887 Token const & t = p.get_token();
1888 // We abuse the parser a bit, because this is no TeX syntax
1890 if (t.cat() == catEscape)
1891 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1894 Context tmp(false, context.textclass,
1895 &context.textclass[from_ascii("Scrap")]);
1896 tmp.need_end_layout = true;
1897 tmp.check_layout(oss);
1898 os << subst(t.asInput(), "\n", oss.str());
1900 // The scrap chunk is ended by an @ at the beginning of a line.
1901 // After the @ the line may contain a comment and/or
1902 // whitespace, but nothing else.
1903 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1904 (p.next_token().cat() == catSpace ||
1905 p.next_token().cat() == catNewline ||
1906 p.next_token().cat() == catComment)) {
1907 while (p.good() && p.next_token().cat() == catSpace)
1908 os << p.get_token().asInput();
1909 if (p.next_token().cat() == catComment)
1910 // The comment includes a final '\n'
1911 os << p.get_token().asInput();
1913 if (p.next_token().cat() == catNewline)
1920 newcontext.check_end_layout(os);
1924 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1925 bool is_macro(Parser & p)
1927 Token first = p.curr_token();
1928 if (first.cat() != catEscape || !p.good())
1930 if (first.cs() == "def")
1932 if (first.cs() != "global" && first.cs() != "long")
1934 Token second = p.get_token();
1936 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1937 second.cat() == catNewline || second.cat() == catComment)) {
1938 second = p.get_token();
1941 bool secondvalid = second.cat() == catEscape;
1943 bool thirdvalid = false;
1944 if (p.good() && first.cs() == "global" && secondvalid &&
1945 second.cs() == "long") {
1946 third = p.get_token();
1948 while (p.good() && !p.isParagraph() &&
1949 (third.cat() == catSpace ||
1950 third.cat() == catNewline ||
1951 third.cat() == catComment)) {
1952 third = p.get_token();
1955 thirdvalid = third.cat() == catEscape;
1957 for (int i = 0; i < pos; ++i)
1962 return (first.cs() == "global" || first.cs() == "long") &&
1963 second.cs() == "def";
1964 return first.cs() == "global" && second.cs() == "long" &&
1965 third.cs() == "def";
1969 /// Parse a macro definition (assumes that is_macro() returned true)
1970 void parse_macro(Parser & p, ostream & os, Context & context)
1972 context.check_layout(os);
1973 Token first = p.curr_token();
1976 string command = first.asInput();
1977 if (first.cs() != "def") {
1979 eat_whitespace(p, os, context, false);
1980 second = p.curr_token();
1981 command += second.asInput();
1982 if (second.cs() != "def") {
1984 eat_whitespace(p, os, context, false);
1985 third = p.curr_token();
1986 command += third.asInput();
1989 eat_whitespace(p, os, context, false);
1990 string const name = p.get_token().cs();
1991 eat_whitespace(p, os, context, false);
1997 while (p.next_token().cat() != catBegin) {
1998 if (p.next_token().cat() == catParameter) {
2003 // followed by number?
2004 if (p.next_token().cat() == catOther) {
2005 char c = p.getChar();
2007 // number = current arity + 1?
2008 if (c == arity + '0' + 1)
2013 paramtext += p.get_token().cs();
2015 paramtext += p.get_token().cs();
2020 // only output simple (i.e. compatible) macro as FormulaMacros
2021 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2023 context.check_layout(os);
2024 begin_inset(os, "FormulaMacro");
2025 os << "\n\\def" << ert;
2028 handle_ert(os, command + ert, context);
2032 void registerExternalTemplatePackages(string const & name)
2034 external::TemplateManager const & etm = external::TemplateManager::get();
2035 external::Template const * const et = etm.getTemplateByName(name);
2038 external::Template::Formats::const_iterator cit = et->formats.end();
2040 cit = et->formats.find("PDFLaTeX");
2041 if (cit == et->formats.end())
2042 // If the template has not specified a PDFLaTeX output,
2043 // we try the LaTeX format.
2044 cit = et->formats.find("LaTeX");
2045 if (cit == et->formats.end())
2047 vector<string>::const_iterator qit = cit->second.requirements.begin();
2048 vector<string>::const_iterator qend = cit->second.requirements.end();
2049 for (; qit != qend; ++qit)
2050 preamble.registerAutomaticallyLoadedPackage(*qit);
2053 } // anonymous namespace
2056 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2059 Layout const * newlayout = 0;
2060 InsetLayout const * newinsetlayout = 0;
2061 char const * const * where = 0;
2062 // Store the latest bibliographystyle and nocite{*} option
2063 // (needed for bibtex inset)
2065 string bibliographystyle = "default";
2066 bool const use_natbib = preamble.isPackageUsed("natbib");
2067 bool const use_jurabib = preamble.isPackageUsed("jurabib");
2070 Token const & t = p.get_token();
2072 // it is impossible to determine the correct document language if CJK is used.
2073 // Therefore write a note at the beginning of the document
2075 context.check_layout(os);
2076 begin_inset(os, "Note Note\n");
2077 os << "status open\n\\begin_layout Plain Layout\n"
2078 << "\\series bold\n"
2079 << "Important information:\n"
2080 << "\\end_layout\n\n"
2081 << "\\begin_layout Plain Layout\n"
2082 << "This document contains text in Chinese, Japanese or Korean.\n"
2083 << " It was therefore impossible for tex2lyx to set the correct document langue for your document."
2084 << " Please set the language manually in the document settings.\n"
2085 << "\\end_layout\n";
2090 // it is impossible to determine the correct encoding for non-CJK Japanese.
2091 // Therefore write a note at the beginning of the document
2092 if (is_nonCJKJapanese) {
2093 context.check_layout(os);
2094 begin_inset(os, "Note Note\n");
2095 os << "status open\n\\begin_layout Plain Layout\n"
2096 << "\\series bold\n"
2097 << "Important information:\n"
2098 << "\\end_layout\n\n"
2099 << "\\begin_layout Plain Layout\n"
2100 << "This document is in Japanese (non-CJK).\n"
2101 << " It was therefore impossible for tex2lyx to determine the correct encoding."
2102 << " The encoding EUC-JP was assumed. If this is incorrect, please set the correct"
2103 << " encoding in the document settings.\n"
2104 << "\\end_layout\n";
2106 is_nonCJKJapanese = false;
2110 debugToken(cerr, t, flags);
2113 if (flags & FLAG_ITEM) {
2114 if (t.cat() == catSpace)
2117 flags &= ~FLAG_ITEM;
2118 if (t.cat() == catBegin) {
2119 // skip the brace and collect everything to the next matching
2121 flags |= FLAG_BRACE_LAST;
2125 // handle only this single token, leave the loop if done
2126 flags |= FLAG_LEAVE;
2129 if (t.cat() != catEscape && t.character() == ']' &&
2130 (flags & FLAG_BRACK_LAST))
2132 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2135 // If there is anything between \end{env} and \begin{env} we
2136 // don't need to output a separator.
2137 if (t.cat() != catSpace && t.cat() != catNewline &&
2138 t.asInput() != "\\begin")
2144 if (t.cat() == catMath) {
2145 // we are inside some text mode thingy, so opening new math is allowed
2146 context.check_layout(os);
2147 begin_inset(os, "Formula ");
2148 Token const & n = p.get_token();
2149 bool const display(n.cat() == catMath && outer);
2151 // TeX's $$...$$ syntax for displayed math
2153 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2155 p.get_token(); // skip the second '$' token
2157 // simple $...$ stuff
2160 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2165 // Prevent the conversion of a line break to a
2166 // space (bug 7668). This does not change the
2167 // output, but looks ugly in LyX.
2168 eat_whitespace(p, os, context, false);
2172 else if (t.cat() == catSuper || t.cat() == catSub)
2173 cerr << "catcode " << t << " illegal in text mode\n";
2175 // Basic support for english quotes. This should be
2176 // extended to other quotes, but is not so easy (a
2177 // left english quote is the same as a right german
2179 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2180 context.check_layout(os);
2181 begin_inset(os, "Quotes ");
2187 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2188 context.check_layout(os);
2189 begin_inset(os, "Quotes ");
2196 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2197 context.check_layout(os);
2198 begin_inset(os, "Quotes ");
2205 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2206 context.check_layout(os);
2207 begin_inset(os, "Quotes ");
2214 else if (t.asInput() == "<"
2215 && p.next_token().asInput() == "<" && noweb_mode) {
2217 parse_noweb(p, os, context);
2220 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2221 check_space(p, os, context);
2223 else if (t.character() == '[' && noweb_mode &&
2224 p.next_token().character() == '[') {
2225 // These can contain underscores
2227 string const s = p.getFullOpt() + ']';
2228 if (p.next_token().character() == ']')
2231 cerr << "Warning: Inserting missing ']' in '"
2232 << s << "'." << endl;
2233 handle_ert(os, s, context);
2236 else if (t.cat() == catLetter) {
2237 context.check_layout(os);
2238 // Workaround for bug 4752.
2239 // FIXME: This whole code block needs to be removed
2240 // when the bug is fixed and tex2lyx produces
2241 // the updated file format.
2242 // The replacement algorithm in LyX is so stupid that
2243 // it even translates a phrase if it is part of a word.
2244 bool handled = false;
2245 for (int const * l = known_phrase_lengths; *l; ++l) {
2246 string phrase = t.cs();
2247 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2248 phrase += p.get_token().cs();
2249 if (is_known(phrase, known_coded_phrases)) {
2250 handle_ert(os, phrase, context);
2254 for (size_t i = 1; i < phrase.length(); ++i)
2262 else if (t.cat() == catOther ||
2263 t.cat() == catAlign ||
2264 t.cat() == catParameter) {
2265 // This translates "&" to "\\&" which may be wrong...
2266 context.check_layout(os);
2270 else if (p.isParagraph()) {
2271 if (context.new_layout_allowed)
2272 context.new_paragraph(os);
2274 handle_ert(os, "\\par ", context);
2275 eat_whitespace(p, os, context, true);
2278 else if (t.cat() == catActive) {
2279 context.check_layout(os);
2280 if (t.character() == '~') {
2281 if (context.layout->free_spacing)
2284 begin_inset(os, "space ~\n");
2291 else if (t.cat() == catBegin) {
2292 Token const next = p.next_token();
2293 Token const end = p.next_next_token();
2294 if (next.cat() == catEnd) {
2296 Token const prev = p.prev_token();
2298 if (p.next_token().character() == '`' ||
2299 (prev.character() == '-' &&
2300 p.next_token().character() == '-'))
2301 ; // ignore it in {}`` or -{}-
2303 handle_ert(os, "{}", context);
2304 } else if (next.cat() == catEscape &&
2305 is_known(next.cs(), known_quotes) &&
2306 end.cat() == catEnd) {
2307 // Something like {\textquoteright} (e.g.
2308 // from writer2latex). LyX writes
2309 // \textquoteright{}, so we may skip the
2310 // braces here for better readability.
2311 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2314 context.check_layout(os);
2315 // special handling of font attribute changes
2316 Token const prev = p.prev_token();
2317 TeXFont const oldFont = context.font;
2318 if (next.character() == '[' ||
2319 next.character() == ']' ||
2320 next.character() == '*') {
2322 if (p.next_token().cat() == catEnd) {
2327 handle_ert(os, "{", context);
2328 parse_text_snippet(p, os,
2331 handle_ert(os, "}", context);
2333 } else if (! context.new_layout_allowed) {
2334 handle_ert(os, "{", context);
2335 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2337 handle_ert(os, "}", context);
2338 } else if (is_known(next.cs(), known_sizes)) {
2339 // next will change the size, so we must
2341 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2343 if (!context.atParagraphStart())
2345 << context.font.size << "\n";
2346 } else if (is_known(next.cs(), known_font_families)) {
2347 // next will change the font family, so we
2348 // must reset it here
2349 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2351 if (!context.atParagraphStart())
2353 << context.font.family << "\n";
2354 } else if (is_known(next.cs(), known_font_series)) {
2355 // next will change the font series, so we
2356 // must reset it here
2357 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2359 if (!context.atParagraphStart())
2361 << context.font.series << "\n";
2362 } else if (is_known(next.cs(), known_font_shapes)) {
2363 // next will change the font shape, so we
2364 // must reset it here
2365 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2367 if (!context.atParagraphStart())
2369 << context.font.shape << "\n";
2370 } else if (is_known(next.cs(), known_old_font_families) ||
2371 is_known(next.cs(), known_old_font_series) ||
2372 is_known(next.cs(), known_old_font_shapes)) {
2373 // next will change the font family, series
2374 // and shape, so we must reset it here
2375 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2377 if (!context.atParagraphStart())
2379 << context.font.family
2381 << context.font.series
2383 << context.font.shape << "\n";
2385 handle_ert(os, "{", context);
2386 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2388 handle_ert(os, "}", context);
2393 else if (t.cat() == catEnd) {
2394 if (flags & FLAG_BRACE_LAST) {
2397 cerr << "stray '}' in text\n";
2398 handle_ert(os, "}", context);
2401 else if (t.cat() == catComment)
2402 parse_comment(p, os, t, context);
2405 // control sequences
2408 else if (t.cs() == "(") {
2409 context.check_layout(os);
2410 begin_inset(os, "Formula");
2412 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2417 else if (t.cs() == "[") {
2418 context.check_layout(os);
2419 begin_inset(os, "Formula");
2421 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2424 // Prevent the conversion of a line break to a space
2425 // (bug 7668). This does not change the output, but
2426 // looks ugly in LyX.
2427 eat_whitespace(p, os, context, false);
2430 else if (t.cs() == "begin")
2431 parse_environment(p, os, outer, last_env,
2434 else if (t.cs() == "end") {
2435 if (flags & FLAG_END) {
2436 // eat environment name
2437 string const name = p.getArg('{', '}');
2438 if (name != active_environment())
2439 cerr << "\\end{" + name + "} does not match \\begin{"
2440 + active_environment() + "}\n";
2443 p.error("found 'end' unexpectedly");
2446 else if (t.cs() == "item") {
2448 bool const optarg = p.hasOpt();
2450 // FIXME: This swallows comments, but we cannot use
2451 // eat_whitespace() since we must not output
2452 // anything before the item.
2453 p.skip_spaces(true);
2454 s = p.verbatimOption();
2456 p.skip_spaces(false);
2458 context.check_layout(os);
2459 if (context.has_item) {
2460 // An item in an unknown list-like environment
2461 // FIXME: Do this in check_layout()!
2462 context.has_item = false;
2464 handle_ert(os, "\\item", context);
2466 handle_ert(os, "\\item ", context);
2469 if (context.layout->labeltype != LABEL_MANUAL) {
2470 // LyX does not support \item[\mybullet]
2471 // in itemize environments
2473 os << parse_text_snippet(p2,
2474 FLAG_BRACK_LAST, outer, context);
2475 } else if (!s.empty()) {
2476 // LyX adds braces around the argument,
2477 // so we need to remove them here.
2478 if (s.size() > 2 && s[0] == '{' &&
2479 s[s.size()-1] == '}')
2480 s = s.substr(1, s.size()-2);
2481 // If the argument contains a space we
2482 // must put it into ERT: Otherwise LyX
2483 // would misinterpret the space as
2484 // item delimiter (bug 7663)
2485 if (contains(s, ' ')) {
2486 handle_ert(os, s, context);
2489 os << parse_text_snippet(p2,
2493 // The space is needed to separate the
2494 // item from the rest of the sentence.
2496 eat_whitespace(p, os, context, false);
2501 else if (t.cs() == "bibitem") {
2503 context.check_layout(os);
2504 eat_whitespace(p, os, context, false);
2505 string label = convert_command_inset_arg(p.verbatimOption());
2506 string key = convert_command_inset_arg(p.verbatim_item());
2507 if (contains(label, '\\') || contains(key, '\\')) {
2508 // LyX can't handle LaTeX commands in labels or keys
2509 handle_ert(os, t.asInput() + '[' + label +
2510 "]{" + p.verbatim_item() + '}',
2513 begin_command_inset(os, "bibitem", "bibitem");
2514 os << "label \"" << label << "\"\n"
2515 "key \"" << key << "\"\n";
2520 else if (is_macro(p)) {
2521 // catch the case of \def\inputGnumericTable
2523 if (t.cs() == "def") {
2524 Token second = p.next_token();
2525 if (second.cs() == "inputGnumericTable") {
2529 Token third = p.get_token();
2531 if (third.cs() == "input") {
2535 string name = normalize_filename(p.verbatim_item());
2536 string const path = makeAbsPath(getMasterFilePath()).absFileName();
2537 // We want to preserve relative / absolute filenames,
2538 // therefore path is only used for testing
2539 // The file extension is in every case ".tex".
2540 // So we need to remove this extension and check for
2541 // the original one.
2542 name = removeExtension(name);
2543 if (!makeAbsPath(name, path).exists()) {
2544 char const * const Gnumeric_formats[] = {"gnumeric",
2546 string const Gnumeric_name =
2547 find_file(name, path, Gnumeric_formats);
2548 if (!Gnumeric_name.empty())
2549 name = Gnumeric_name;
2551 if (makeAbsPath(name, path).exists())
2552 fix_relative_filename(name);
2554 cerr << "Warning: Could not find file '"
2555 << name << "'." << endl;
2556 context.check_layout(os);
2557 begin_inset(os, "External\n\ttemplate ");
2558 os << "GnumericSpreadsheet\n\tfilename "
2561 context.check_layout(os);
2563 // register the packages that are automatically reloaded
2564 // by the Gnumeric template
2565 registerExternalTemplatePackages("GnumericSpreadsheet");
2570 parse_macro(p, os, context);
2573 else if (t.cs() == "noindent") {
2575 context.add_par_extra_stuff("\\noindent\n");
2578 else if (t.cs() == "appendix") {
2579 context.add_par_extra_stuff("\\start_of_appendix\n");
2580 // We need to start a new paragraph. Otherwise the
2581 // appendix in 'bla\appendix\chapter{' would start
2583 context.new_paragraph(os);
2584 // We need to make sure that the paragraph is
2585 // generated even if it is empty. Otherwise the
2586 // appendix in '\par\appendix\par\chapter{' would
2588 context.check_layout(os);
2589 // FIXME: This is a hack to prevent paragraph
2590 // deletion if it is empty. Handle this better!
2592 "%dummy comment inserted by tex2lyx to "
2593 "ensure that this paragraph is not empty",
2595 // Both measures above may generate an additional
2596 // empty paragraph, but that does not hurt, because
2597 // whitespace does not matter here.
2598 eat_whitespace(p, os, context, true);
2601 // Must catch empty dates before findLayout is called below
2602 else if (t.cs() == "date") {
2603 eat_whitespace(p, os, context, false);
2605 string const date = p.verbatim_item();
2608 preamble.suppressDate(true);
2611 preamble.suppressDate(false);
2612 if (context.new_layout_allowed &&
2613 (newlayout = findLayout(context.textclass,
2616 output_command_layout(os, p, outer,
2617 context, newlayout);
2618 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2619 if (!preamble.titleLayoutFound())
2620 preamble.titleLayoutFound(newlayout->intitle);
2621 set<string> const & req = newlayout->requires();
2622 set<string>::const_iterator it = req.begin();
2623 set<string>::const_iterator en = req.end();
2624 for (; it != en; ++it)
2625 preamble.registerAutomaticallyLoadedPackage(*it);
2628 "\\date{" + p.verbatim_item() + '}',
2633 // Starred section headings
2634 // Must attempt to parse "Section*" before "Section".
2635 else if ((p.next_token().asInput() == "*") &&
2636 context.new_layout_allowed &&
2637 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2640 output_command_layout(os, p, outer, context, newlayout);
2642 if (!preamble.titleLayoutFound())
2643 preamble.titleLayoutFound(newlayout->intitle);
2644 set<string> const & req = newlayout->requires();
2645 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2646 preamble.registerAutomaticallyLoadedPackage(*it);
2649 // Section headings and the like
2650 else if (context.new_layout_allowed &&
2651 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2653 output_command_layout(os, p, outer, context, newlayout);
2655 if (!preamble.titleLayoutFound())
2656 preamble.titleLayoutFound(newlayout->intitle);
2657 set<string> const & req = newlayout->requires();
2658 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2659 preamble.registerAutomaticallyLoadedPackage(*it);
2662 else if (t.cs() == "caption") {
2664 context.check_layout(os);
2666 begin_inset(os, "Caption\n");
2667 Context newcontext(true, context.textclass);
2668 newcontext.font = context.font;
2669 newcontext.check_layout(os);
2670 if (p.next_token().cat() != catEscape &&
2671 p.next_token().character() == '[') {
2672 p.get_token(); // eat '['
2673 begin_inset(os, "Argument\n");
2674 os << "status collapsed\n";
2675 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2677 eat_whitespace(p, os, context, false);
2679 parse_text(p, os, FLAG_ITEM, outer, context);
2680 context.check_end_layout(os);
2681 // We don't need really a new paragraph, but
2682 // we must make sure that the next item gets a \begin_layout.
2683 context.new_paragraph(os);
2686 newcontext.check_end_layout(os);
2689 else if (t.cs() == "subfloat") {
2690 // the syntax is \subfloat[caption]{content}
2691 // if it is a table of figure depends on the surrounding float
2692 bool has_caption = false;
2694 // do nothing if there is no outer float
2695 if (!float_type.empty()) {
2696 context.check_layout(os);
2698 begin_inset(os, "Float " + float_type + "\n");
2700 << "\nsideways false"
2701 << "\nstatus collapsed\n\n";
2704 if (p.next_token().cat() != catEscape &&
2705 p.next_token().character() == '[') {
2706 p.get_token(); // eat '['
2707 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2711 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2712 // the caption comes always as the last
2714 // we must make sure that the caption gets a \begin_layout
2715 os << "\n\\begin_layout Plain Layout";
2717 begin_inset(os, "Caption\n");
2718 Context newcontext(true, context.textclass);
2719 newcontext.font = context.font;
2720 newcontext.check_layout(os);
2721 os << caption << "\n";
2722 newcontext.check_end_layout(os);
2723 // We don't need really a new paragraph, but
2724 // we must make sure that the next item gets a \begin_layout.
2725 //newcontext.new_paragraph(os);
2729 // We don't need really a new paragraph, but
2730 // we must make sure that the next item gets a \begin_layout.
2732 context.new_paragraph(os);
2735 context.check_end_layout(os);
2736 // close the layout we opened
2738 os << "\n\\end_layout\n";
2740 // if the float type is not supported or there is no surrounding float
2743 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2744 handle_ert(os, t.asInput() + '[' + opt_arg +
2745 "]{" + p.verbatim_item() + '}', context);
2747 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2751 else if (t.cs() == "includegraphics") {
2752 bool const clip = p.next_token().asInput() == "*";
2755 string const arg = p.getArg('[', ']');
2756 map<string, string> opts;
2757 vector<string> keys;
2758 split_map(arg, opts, keys);
2760 opts["clip"] = string();
2761 string name = normalize_filename(p.verbatim_item());
2763 string const path = makeAbsPath(getMasterFilePath()).absFileName();
2764 // We want to preserve relative / absolute filenames,
2765 // therefore path is only used for testing
2766 if (!makeAbsPath(name, path).exists()) {
2767 // The file extension is probably missing.
2768 // Now try to find it out.
2769 string const dvips_name =
2770 find_file(name, path,
2771 known_dvips_graphics_formats);
2772 string const pdftex_name =
2773 find_file(name, path,
2774 known_pdftex_graphics_formats);
2775 if (!dvips_name.empty()) {
2776 if (!pdftex_name.empty()) {
2777 cerr << "This file contains the "
2779 "\"\\includegraphics{"
2781 "However, files\n\""
2782 << dvips_name << "\" and\n\""
2783 << pdftex_name << "\"\n"
2784 "both exist, so I had to make a "
2785 "choice and took the first one.\n"
2786 "Please move the unwanted one "
2787 "someplace else and try again\n"
2788 "if my choice was wrong."
2792 } else if (!pdftex_name.empty()) {
2798 if (makeAbsPath(name, path).exists())
2799 fix_relative_filename(name);
2801 cerr << "Warning: Could not find graphics file '"
2802 << name << "'." << endl;
2804 context.check_layout(os);
2805 begin_inset(os, "Graphics ");
2806 os << "\n\tfilename " << name << '\n';
2807 if (opts.find("width") != opts.end())
2809 << translate_len(opts["width"]) << '\n';
2810 if (opts.find("height") != opts.end())
2812 << translate_len(opts["height"]) << '\n';
2813 if (opts.find("scale") != opts.end()) {
2814 istringstream iss(opts["scale"]);
2818 os << "\tscale " << val << '\n';
2820 if (opts.find("angle") != opts.end()) {
2821 os << "\trotateAngle "
2822 << opts["angle"] << '\n';
2823 vector<string>::const_iterator a =
2824 find(keys.begin(), keys.end(), "angle");
2825 vector<string>::const_iterator s =
2826 find(keys.begin(), keys.end(), "width");
2827 if (s == keys.end())
2828 s = find(keys.begin(), keys.end(), "height");
2829 if (s == keys.end())
2830 s = find(keys.begin(), keys.end(), "scale");
2831 if (s != keys.end() && distance(s, a) > 0)
2832 os << "\tscaleBeforeRotation\n";
2834 if (opts.find("origin") != opts.end()) {
2836 string const opt = opts["origin"];
2837 if (opt.find('l') != string::npos) ss << "left";
2838 if (opt.find('r') != string::npos) ss << "right";
2839 if (opt.find('c') != string::npos) ss << "center";
2840 if (opt.find('t') != string::npos) ss << "Top";
2841 if (opt.find('b') != string::npos) ss << "Bottom";
2842 if (opt.find('B') != string::npos) ss << "Baseline";
2843 if (!ss.str().empty())
2844 os << "\trotateOrigin " << ss.str() << '\n';
2846 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2848 if (opts.find("keepaspectratio") != opts.end())
2849 os << "\tkeepAspectRatio\n";
2850 if (opts.find("clip") != opts.end())
2852 if (opts.find("draft") != opts.end())
2854 if (opts.find("bb") != opts.end())
2855 os << "\tBoundingBox "
2856 << opts["bb"] << '\n';
2857 int numberOfbbOptions = 0;
2858 if (opts.find("bbllx") != opts.end())
2859 numberOfbbOptions++;
2860 if (opts.find("bblly") != opts.end())
2861 numberOfbbOptions++;
2862 if (opts.find("bburx") != opts.end())
2863 numberOfbbOptions++;
2864 if (opts.find("bbury") != opts.end())
2865 numberOfbbOptions++;
2866 if (numberOfbbOptions == 4)
2867 os << "\tBoundingBox "
2868 << opts["bbllx"] << " " << opts["bblly"] << " "
2869 << opts["bburx"] << " " << opts["bbury"] << '\n';
2870 else if (numberOfbbOptions > 0)
2871 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2872 numberOfbbOptions = 0;
2873 if (opts.find("natwidth") != opts.end())
2874 numberOfbbOptions++;
2875 if (opts.find("natheight") != opts.end())
2876 numberOfbbOptions++;
2877 if (numberOfbbOptions == 2)
2878 os << "\tBoundingBox 0bp 0bp "
2879 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2880 else if (numberOfbbOptions > 0)
2881 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2882 ostringstream special;
2883 if (opts.find("hiresbb") != opts.end())
2884 special << "hiresbb,";
2885 if (opts.find("trim") != opts.end())
2887 if (opts.find("viewport") != opts.end())
2888 special << "viewport=" << opts["viewport"] << ',';
2889 if (opts.find("totalheight") != opts.end())
2890 special << "totalheight=" << opts["totalheight"] << ',';
2891 if (opts.find("type") != opts.end())
2892 special << "type=" << opts["type"] << ',';
2893 if (opts.find("ext") != opts.end())
2894 special << "ext=" << opts["ext"] << ',';
2895 if (opts.find("read") != opts.end())
2896 special << "read=" << opts["read"] << ',';
2897 if (opts.find("command") != opts.end())
2898 special << "command=" << opts["command"] << ',';
2899 string s_special = special.str();
2900 if (!s_special.empty()) {
2901 // We had special arguments. Remove the trailing ','.
2902 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2904 // TODO: Handle the unknown settings better.
2905 // Warn about invalid options.
2906 // Check whether some option was given twice.
2908 preamble.registerAutomaticallyLoadedPackage("graphicx");
2911 else if (t.cs() == "footnote" ||
2912 (t.cs() == "thanks" && context.layout->intitle)) {
2914 context.check_layout(os);
2915 begin_inset(os, "Foot\n");
2916 os << "status collapsed\n\n";
2917 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2921 else if (t.cs() == "marginpar") {
2923 context.check_layout(os);
2924 begin_inset(os, "Marginal\n");
2925 os << "status collapsed\n\n";
2926 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2930 else if (t.cs() == "lstinline") {
2932 parse_listings(p, os, context, true);
2935 else if (t.cs() == "ensuremath") {
2937 context.check_layout(os);
2938 string const s = p.verbatim_item();
2939 //FIXME: this never triggers in UTF8
2940 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2943 handle_ert(os, "\\ensuremath{" + s + "}",
2947 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2948 if (preamble.titleLayoutFound()) {
2950 skip_spaces_braces(p);
2952 handle_ert(os, t.asInput(), context);
2955 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
2956 context.check_layout(os);
2957 begin_command_inset(os, "toc", t.cs());
2959 skip_spaces_braces(p);
2960 if (t.cs() == "lstlistoflistings")
2961 preamble.registerAutomaticallyLoadedPackage("listings");
2964 else if (t.cs() == "listoffigures") {
2965 context.check_layout(os);
2966 begin_inset(os, "FloatList figure\n");
2968 skip_spaces_braces(p);
2971 else if (t.cs() == "listoftables") {
2972 context.check_layout(os);
2973 begin_inset(os, "FloatList table\n");
2975 skip_spaces_braces(p);
2978 else if (t.cs() == "listof") {
2979 p.skip_spaces(true);
2980 string const name = p.get_token().cs();
2981 if (context.textclass.floats().typeExist(name)) {
2982 context.check_layout(os);
2983 begin_inset(os, "FloatList ");
2986 p.get_token(); // swallow second arg
2988 handle_ert(os, "\\listof{" + name + "}", context);
2991 else if ((where = is_known(t.cs(), known_text_font_families)))
2992 parse_text_attributes(p, os, FLAG_ITEM, outer,
2993 context, "\\family", context.font.family,
2994 known_coded_font_families[where - known_text_font_families]);
2996 else if ((where = is_known(t.cs(), known_text_font_series)))
2997 parse_text_attributes(p, os, FLAG_ITEM, outer,
2998 context, "\\series", context.font.series,
2999 known_coded_font_series[where - known_text_font_series]);
3001 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3002 parse_text_attributes(p, os, FLAG_ITEM, outer,
3003 context, "\\shape", context.font.shape,
3004 known_coded_font_shapes[where - known_text_font_shapes]);
3006 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3007 context.check_layout(os);
3008 TeXFont oldFont = context.font;
3009 context.font.init();
3010 context.font.size = oldFont.size;
3011 os << "\n\\family " << context.font.family << "\n";
3012 os << "\n\\series " << context.font.series << "\n";
3013 os << "\n\\shape " << context.font.shape << "\n";
3014 if (t.cs() == "textnormal") {
3015 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3016 output_font_change(os, context.font, oldFont);
3017 context.font = oldFont;
3019 eat_whitespace(p, os, context, false);
3022 else if (t.cs() == "textcolor") {
3023 // scheme is \textcolor{color name}{text}
3024 string const color = p.verbatim_item();
3025 // we only support the predefined colors of the color package
3026 if (color == "black" || color == "blue" || color == "cyan"
3027 || color == "green" || color == "magenta" || color == "red"
3028 || color == "white" || color == "yellow") {
3029 context.check_layout(os);
3030 os << "\n\\color " << color << "\n";
3031 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3032 context.check_layout(os);
3033 os << "\n\\color inherit\n";
3034 preamble.registerAutomaticallyLoadedPackage("color");
3036 // for custom defined colors
3037 handle_ert(os, t.asInput() + "{" + color + "}", context);
3040 else if (t.cs() == "underbar" || t.cs() == "uline") {
3041 // \underbar is not 100% correct (LyX outputs \uline
3042 // of ulem.sty). The difference is that \ulem allows
3043 // line breaks, and \underbar does not.
3044 // Do NOT handle \underline.
3045 // \underbar cuts through y, g, q, p etc.,
3046 // \underline does not.
3047 context.check_layout(os);
3048 os << "\n\\bar under\n";
3049 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3050 context.check_layout(os);
3051 os << "\n\\bar default\n";
3052 preamble.registerAutomaticallyLoadedPackage("ulem");
3055 else if (t.cs() == "sout") {
3056 context.check_layout(os);
3057 os << "\n\\strikeout on\n";
3058 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3059 context.check_layout(os);
3060 os << "\n\\strikeout default\n";
3061 preamble.registerAutomaticallyLoadedPackage("ulem");
3064 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3065 t.cs() == "emph" || t.cs() == "noun") {
3066 context.check_layout(os);
3067 os << "\n\\" << t.cs() << " on\n";
3068 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3069 context.check_layout(os);
3070 os << "\n\\" << t.cs() << " default\n";
3071 if (t.cs() == "uuline" || t.cs() == "uwave")
3072 preamble.registerAutomaticallyLoadedPackage("ulem");
3075 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3076 context.check_layout(os);
3077 string name = p.getArg('{', '}');
3078 string localtime = p.getArg('{', '}');
3079 preamble.registerAuthor(name);
3080 Author const & author = preamble.getAuthor(name);
3081 // from_ctime() will fail if LyX decides to output the
3082 // time in the text language. It might also use a wrong
3083 // time zone (if the original LyX document was exported
3084 // with a different time zone).
3085 time_t ptime = from_ctime(localtime);
3086 if (ptime == static_cast<time_t>(-1)) {
3087 cerr << "Warning: Could not parse time `" << localtime
3088 << "´ for change tracking, using current time instead.\n";
3089 ptime = current_time();
3091 if (t.cs() == "lyxadded")
3092 os << "\n\\change_inserted ";
3094 os << "\n\\change_deleted ";
3095 os << author.bufferId() << ' ' << ptime << '\n';
3096 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3097 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3098 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3099 LaTeXPackages::isAvailable("xcolor");
3100 // No need to test for luatex, since luatex comes in
3101 // two flavours (dvi and pdf), like latex, and those
3102 // are detected by pdflatex.
3103 if (pdflatex || xetex) {
3105 preamble.registerAutomaticallyLoadedPackage("ulem");
3106 preamble.registerAutomaticallyLoadedPackage("xcolor");
3107 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3111 preamble.registerAutomaticallyLoadedPackage("dvipost");
3112 } else if (xcolorulem) {
3113 preamble.registerAutomaticallyLoadedPackage("ulem");
3114 preamble.registerAutomaticallyLoadedPackage("xcolor");
3119 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3120 t.cs() == "vphantom") {
3121 context.check_layout(os);
3122 if (t.cs() == "phantom")
3123 begin_inset(os, "Phantom Phantom\n");
3124 if (t.cs() == "hphantom")
3125 begin_inset(os, "Phantom HPhantom\n");
3126 if (t.cs() == "vphantom")
3127 begin_inset(os, "Phantom VPhantom\n");
3128 os << "status open\n";
3129 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3134 else if (t.cs() == "href") {
3135 context.check_layout(os);
3136 string target = p.getArg('{', '}');
3137 string name = p.getArg('{', '}');
3139 size_t i = target.find(':');
3140 if (i != string::npos) {
3141 type = target.substr(0, i + 1);
3142 if (type == "mailto:" || type == "file:")
3143 target = target.substr(i + 1);
3144 // handle the case that name is equal to target, except of "http://"
3145 else if (target.substr(i + 3) == name && type == "http:")
3148 begin_command_inset(os, "href", "href");
3150 os << "name \"" << name << "\"\n";
3151 os << "target \"" << target << "\"\n";
3152 if (type == "mailto:" || type == "file:")
3153 os << "type \"" << type << "\"\n";
3155 skip_spaces_braces(p);
3158 else if (t.cs() == "lyxline") {
3159 // swallow size argument (it is not used anyway)
3161 if (!context.atParagraphStart()) {
3162 // so our line is in the middle of a paragraph
3163 // we need to add a new line, lest this line
3164 // follow the other content on that line and
3165 // run off the side of the page
3166 // FIXME: This may create an empty paragraph,
3167 // but without that it would not be
3168 // possible to set noindent below.
3169 // Fortunately LaTeX does not care
3170 // about the empty paragraph.
3171 context.new_paragraph(os);
3173 if (preamble.indentParagraphs()) {
3174 // we need to unindent, lest the line be too long
3175 context.add_par_extra_stuff("\\noindent\n");
3177 context.check_layout(os);
3178 begin_command_inset(os, "line", "rule");
3179 os << "offset \"0.5ex\"\n"
3180 "width \"100line%\"\n"
3185 else if (t.cs() == "rule") {
3186 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3187 string const width = p.getArg('{', '}');
3188 string const thickness = p.getArg('{', '}');
3189 context.check_layout(os);
3190 begin_command_inset(os, "line", "rule");
3191 if (!offset.empty())
3192 os << "offset \"" << translate_len(offset) << "\"\n";
3193 os << "width \"" << translate_len(width) << "\"\n"
3194 "height \"" << translate_len(thickness) << "\"\n";
3198 else if (is_known(t.cs(), known_phrases) ||
3199 (t.cs() == "protect" &&
3200 p.next_token().cat() == catEscape &&
3201 is_known(p.next_token().cs(), known_phrases))) {
3202 // LyX sometimes puts a \protect in front, so we have to ignore it
3203 // FIXME: This needs to be changed when bug 4752 is fixed.
3205 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3207 context.check_layout(os);
3208 os << known_coded_phrases[where - known_phrases];
3209 skip_spaces_braces(p);
3212 else if ((where = is_known(t.cs(), known_ref_commands))) {
3213 string const opt = p.getOpt();
3215 context.check_layout(os);
3216 begin_command_inset(os, "ref",
3217 known_coded_ref_commands[where - known_ref_commands]);
3218 os << "reference \""
3219 << convert_command_inset_arg(p.verbatim_item())
3222 if (t.cs() == "vref" || t.cs() == "vpageref")
3223 preamble.registerAutomaticallyLoadedPackage("varioref");
3226 // LyX does not support optional arguments of ref commands
3227 handle_ert(os, t.asInput() + '[' + opt + "]{" +
3228 p.verbatim_item() + "}", context);
3232 else if (use_natbib &&
3233 is_known(t.cs(), known_natbib_commands) &&
3234 ((t.cs() != "citefullauthor" &&
3235 t.cs() != "citeyear" &&
3236 t.cs() != "citeyearpar") ||
3237 p.next_token().asInput() != "*")) {
3238 context.check_layout(os);
3239 string command = t.cs();
3240 if (p.next_token().asInput() == "*") {
3244 if (command == "citefullauthor")
3245 // alternative name for "\\citeauthor*"
3246 command = "citeauthor*";
3248 // text before the citation
3250 // text after the citation
3252 get_cite_arguments(p, true, before, after);
3254 if (command == "cite") {
3255 // \cite without optional argument means
3256 // \citet, \cite with at least one optional
3257 // argument means \citep.
3258 if (before.empty() && after.empty())
3263 if (before.empty() && after == "[]")
3264 // avoid \citet[]{a}
3266 else if (before == "[]" && after == "[]") {
3267 // avoid \citet[][]{a}
3271 // remove the brackets around after and before
3272 if (!after.empty()) {
3274 after.erase(after.length() - 1, 1);
3275 after = convert_command_inset_arg(after);
3277 if (!before.empty()) {
3279 before.erase(before.length() - 1, 1);
3280 before = convert_command_inset_arg(before);
3282 begin_command_inset(os, "citation", command);
3283 os << "after " << '"' << after << '"' << "\n";
3284 os << "before " << '"' << before << '"' << "\n";
3286 << convert_command_inset_arg(p.verbatim_item())
3291 else if (use_jurabib &&
3292 is_known(t.cs(), known_jurabib_commands) &&
3293 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3294 context.check_layout(os);
3295 string command = t.cs();
3296 if (p.next_token().asInput() == "*") {
3300 char argumentOrder = '\0';
3301 vector<string> const options =
3302 preamble.getPackageOptions("jurabib");
3303 if (find(options.begin(), options.end(),
3304 "natbiborder") != options.end())
3305 argumentOrder = 'n';
3306 else if (find(options.begin(), options.end(),
3307 "jurabiborder") != options.end())
3308 argumentOrder = 'j';
3310 // text before the citation
3312 // text after the citation
3314 get_cite_arguments(p, argumentOrder != 'j', before, after);
3316 string const citation = p.verbatim_item();
3317 if (!before.empty() && argumentOrder == '\0') {
3318 cerr << "Warning: Assuming argument order "
3319 "of jurabib version 0.6 for\n'"
3320 << command << before << after << '{'
3321 << citation << "}'.\n"
3322 "Add 'jurabiborder' to the jurabib "
3323 "package options if you used an\n"
3324 "earlier jurabib version." << endl;
3326 if (!after.empty()) {
3328 after.erase(after.length() - 1, 1);
3330 if (!before.empty()) {
3332 before.erase(before.length() - 1, 1);
3334 begin_command_inset(os, "citation", command);
3335 os << "after " << '"' << after << '"' << "\n";
3336 os << "before " << '"' << before << '"' << "\n";
3337 os << "key " << '"' << citation << '"' << "\n";
3341 else if (t.cs() == "cite"
3342 || t.cs() == "nocite") {
3343 context.check_layout(os);
3344 string after = convert_command_inset_arg(p.getArg('[', ']'));
3345 string key = convert_command_inset_arg(p.verbatim_item());
3346 // store the case that it is "\nocite{*}" to use it later for
3349 begin_command_inset(os, "citation", t.cs());
3350 os << "after " << '"' << after << '"' << "\n";
3351 os << "key " << '"' << key << '"' << "\n";
3353 } else if (t.cs() == "nocite")
3357 else if (t.cs() == "index" ||
3358 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3359 context.check_layout(os);
3360 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3361 p.getArg('[', ']') : "";
3362 string const kind = arg.empty() ? "idx" : arg;
3363 begin_inset(os, "Index ");
3364 os << kind << "\nstatus collapsed\n";
3365 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3368 preamble.registerAutomaticallyLoadedPackage("splitidx");
3371 else if (t.cs() == "nomenclature") {
3372 context.check_layout(os);
3373 begin_command_inset(os, "nomenclature", "nomenclature");
3374 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3375 if (!prefix.empty())
3376 os << "prefix " << '"' << prefix << '"' << "\n";
3377 os << "symbol " << '"'
3378 << convert_command_inset_arg(p.verbatim_item());
3379 os << "\"\ndescription \""
3380 << convert_command_inset_arg(p.verbatim_item())
3383 preamble.registerAutomaticallyLoadedPackage("nomencl");
3386 else if (t.cs() == "label") {
3387 context.check_layout(os);
3388 begin_command_inset(os, "label", "label");
3390 << convert_command_inset_arg(p.verbatim_item())
3395 else if (t.cs() == "printindex") {
3396 context.check_layout(os);
3397 begin_command_inset(os, "index_print", "printindex");
3398 os << "type \"idx\"\n";
3400 skip_spaces_braces(p);
3401 preamble.registerAutomaticallyLoadedPackage("makeidx");
3402 if (preamble.use_indices() == "true")
3403 preamble.registerAutomaticallyLoadedPackage("splitidx");
3406 else if (t.cs() == "printnomenclature") {
3408 string width_type = "";
3409 context.check_layout(os);
3410 begin_command_inset(os, "nomencl_print", "printnomenclature");
3411 // case of a custom width
3413 width = p.getArg('[', ']');
3414 width = translate_len(width);
3415 width_type = "custom";
3417 // case of no custom width
3418 // the case of no custom width but the width set
3419 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3420 // because the user could have set anything, not only the width
3421 // of the longest label (which would be width_type = "auto")
3422 string label = convert_command_inset_arg(p.getArg('{', '}'));
3423 if (label.empty() && width_type.empty())
3424 width_type = "none";
3425 os << "set_width \"" << width_type << "\"\n";
3426 if (width_type == "custom")
3427 os << "width \"" << width << '\"';
3429 skip_spaces_braces(p);
3430 preamble.registerAutomaticallyLoadedPackage("nomencl");
3433 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3434 context.check_layout(os);
3435 begin_inset(os, "script ");
3436 os << t.cs().substr(4) << '\n';
3437 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3439 if (t.cs() == "textsubscript")
3440 preamble.registerAutomaticallyLoadedPackage("subscript");
3443 else if ((where = is_known(t.cs(), known_quotes))) {
3444 context.check_layout(os);
3445 begin_inset(os, "Quotes ");
3446 os << known_coded_quotes[where - known_quotes];
3448 // LyX adds {} after the quote, so we have to eat
3449 // spaces here if there are any before a possible
3451 eat_whitespace(p, os, context, false);
3455 else if ((where = is_known(t.cs(), known_sizes)) &&
3456 context.new_layout_allowed) {
3457 context.check_layout(os);
3458 TeXFont const oldFont = context.font;
3459 context.font.size = known_coded_sizes[where - known_sizes];
3460 output_font_change(os, oldFont, context.font);
3461 eat_whitespace(p, os, context, false);
3464 else if ((where = is_known(t.cs(), known_font_families)) &&
3465 context.new_layout_allowed) {
3466 context.check_layout(os);
3467 TeXFont const oldFont = context.font;
3468 context.font.family =
3469 known_coded_font_families[where - known_font_families];
3470 output_font_change(os, oldFont, context.font);
3471 eat_whitespace(p, os, context, false);
3474 else if ((where = is_known(t.cs(), known_font_series)) &&
3475 context.new_layout_allowed) {
3476 context.check_layout(os);
3477 TeXFont const oldFont = context.font;
3478 context.font.series =
3479 known_coded_font_series[where - known_font_series];
3480 output_font_change(os, oldFont, context.font);
3481 eat_whitespace(p, os, context, false);
3484 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3485 context.new_layout_allowed) {
3486 context.check_layout(os);
3487 TeXFont const oldFont = context.font;
3488 context.font.shape =
3489 known_coded_font_shapes[where - known_font_shapes];
3490 output_font_change(os, oldFont, context.font);
3491 eat_whitespace(p, os, context, false);
3493 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3494 context.new_layout_allowed) {
3495 context.check_layout(os);
3496 TeXFont const oldFont = context.font;
3497 context.font.init();
3498 context.font.size = oldFont.size;
3499 context.font.family =
3500 known_coded_font_families[where - known_old_font_families];
3501 output_font_change(os, oldFont, context.font);
3502 eat_whitespace(p, os, context, false);
3505 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3506 context.new_layout_allowed) {
3507 context.check_layout(os);
3508 TeXFont const oldFont = context.font;
3509 context.font.init();
3510 context.font.size = oldFont.size;
3511 context.font.series =
3512 known_coded_font_series[where - known_old_font_series];
3513 output_font_change(os, oldFont, context.font);
3514 eat_whitespace(p, os, context, false);
3517 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3518 context.new_layout_allowed) {
3519 context.check_layout(os);
3520 TeXFont const oldFont = context.font;
3521 context.font.init();
3522 context.font.size = oldFont.size;
3523 context.font.shape =
3524 known_coded_font_shapes[where - known_old_font_shapes];
3525 output_font_change(os, oldFont, context.font);
3526 eat_whitespace(p, os, context, false);
3529 else if (t.cs() == "selectlanguage") {
3530 context.check_layout(os);
3531 // save the language for the case that a
3532 // \foreignlanguage is used
3533 context.font.language = babel2lyx(p.verbatim_item());
3534 os << "\n\\lang " << context.font.language << "\n";
3537 else if (t.cs() == "foreignlanguage") {
3538 string const lang = babel2lyx(p.verbatim_item());
3539 parse_text_attributes(p, os, FLAG_ITEM, outer,
3541 context.font.language, lang);
3544 else if (prefixIs(t.cs(), "text")
3545 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3546 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3548 // We have to output the whole command if it has an option
3549 // because LyX doesn't support this yet, see bug #8214,
3550 // only if there is a single option specifying a variant, we can handle it.
3552 string langopts = p.getOpt();
3553 // check if the option contains a variant, if yes, extract it
3554 string::size_type pos_var = langopts.find("variant");
3555 string::size_type i = langopts.find(',');
3556 string::size_type k = langopts.find('=', pos_var);
3557 if (pos_var != string::npos && i == string::npos) {
3559 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3560 lang = preamble.polyglossia2lyx(variant);
3561 parse_text_attributes(p, os, FLAG_ITEM, outer,
3563 context.font.language, lang);
3565 handle_ert(os, t.asInput() + langopts, context);
3567 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3568 parse_text_attributes(p, os, FLAG_ITEM, outer,
3570 context.font.language, lang);
3574 else if (t.cs() == "inputencoding") {
3575 // nothing to write here
3576 string const enc = subst(p.verbatim_item(), "\n", " ");
3580 else if ((where = is_known(t.cs(), known_special_chars))) {
3581 context.check_layout(os);
3582 os << "\\SpecialChar \\"
3583 << known_coded_special_chars[where - known_special_chars]
3585 skip_spaces_braces(p);
3588 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3589 context.check_layout(os);
3590 os << "\\SpecialChar \\nobreakdash-\n";
3594 else if (t.cs() == "textquotedbl") {
3595 context.check_layout(os);
3600 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3601 context.check_layout(os);
3602 os << "\\SpecialChar \\@.\n";
3606 else if (t.cs() == "-") {
3607 context.check_layout(os);
3608 os << "\\SpecialChar \\-\n";
3611 else if (t.cs() == "textasciitilde") {
3612 context.check_layout(os);
3614 skip_spaces_braces(p);
3617 else if (t.cs() == "textasciicircum") {
3618 context.check_layout(os);
3620 skip_spaces_braces(p);
3623 else if (t.cs() == "textbackslash") {
3624 context.check_layout(os);
3625 os << "\n\\backslash\n";
3626 skip_spaces_braces(p);
3629 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3630 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3632 context.check_layout(os);
3636 else if (t.cs() == "char") {
3637 context.check_layout(os);
3638 if (p.next_token().character() == '`') {
3640 if (p.next_token().cs() == "\"") {
3645 handle_ert(os, "\\char`", context);
3648 handle_ert(os, "\\char", context);
3652 else if (t.cs() == "verb") {
3653 context.check_layout(os);
3654 char const delimiter = p.next_token().character();
3655 string const arg = p.getArg(delimiter, delimiter);
3657 oss << "\\verb" << delimiter << arg << delimiter;
3658 handle_ert(os, oss.str(), context);
3661 // Problem: \= creates a tabstop inside the tabbing environment
3662 // and else an accent. In the latter case we really would want
3663 // \={o} instead of \= o.
3664 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3665 handle_ert(os, t.asInput(), context);
3667 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3668 else if (t.cs().size() == 1
3669 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3670 context.check_layout(os);
3671 // try to see whether the string is in unicodesymbols
3674 string command = t.asInput() + "{"
3675 + trimSpaceAndEol(p.verbatim_item())
3678 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3679 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3680 termination, rem, &req);
3683 cerr << "When parsing " << command
3684 << ", result is " << to_utf8(s)
3685 << "+" << to_utf8(rem) << endl;
3687 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3688 preamble.registerAutomaticallyLoadedPackage(*it);
3690 // we did not find a non-ert version
3691 handle_ert(os, command, context);
3694 else if (t.cs() == "\\") {
3695 context.check_layout(os);
3697 handle_ert(os, "\\\\" + p.getOpt(), context);
3698 else if (p.next_token().asInput() == "*") {
3700 // getOpt() eats the following space if there
3701 // is no optional argument, but that is OK
3702 // here since it has no effect in the output.
3703 handle_ert(os, "\\\\*" + p.getOpt(), context);
3706 begin_inset(os, "Newline newline");
3711 else if (t.cs() == "newline" ||
3712 (t.cs() == "linebreak" && !p.hasOpt())) {
3713 context.check_layout(os);
3714 begin_inset(os, "Newline ");
3717 skip_spaces_braces(p);
3720 else if (t.cs() == "input" || t.cs() == "include"
3721 || t.cs() == "verbatiminput") {
3722 string name = t.cs();
3723 if (t.cs() == "verbatiminput"
3724 && p.next_token().asInput() == "*")
3725 name += p.get_token().asInput();
3726 context.check_layout(os);
3727 string filename(normalize_filename(p.getArg('{', '}')));
3728 string const path = makeAbsPath(getMasterFilePath()).absFileName();
3729 // We want to preserve relative / absolute filenames,
3730 // therefore path is only used for testing
3731 if ((t.cs() == "include" || t.cs() == "input") &&
3732 !makeAbsPath(filename, path).exists()) {
3733 // The file extension is probably missing.
3734 // Now try to find it out.
3735 string const tex_name =
3736 find_file(filename, path,
3737 known_tex_extensions);
3738 if (!tex_name.empty())
3739 filename = tex_name;
3741 bool external = false;
3743 if (makeAbsPath(filename, path).exists()) {
3744 string const abstexname =
3745 makeAbsPath(filename, path).absFileName();
3746 string const abslyxname =
3747 changeExtension(abstexname, ".lyx");
3748 string const absfigname =
3749 changeExtension(abstexname, ".fig");
3750 fix_relative_filename(filename);
3751 string const lyxname =
3752 changeExtension(filename, ".lyx");
3754 external = FileName(absfigname).exists();
3755 if (t.cs() == "input") {
3756 string const ext = getExtension(abstexname);
3758 // Combined PS/LaTeX:
3759 // x.eps, x.pstex_t (old xfig)
3760 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3761 FileName const absepsname(
3762 changeExtension(abstexname, ".eps"));
3763 FileName const abspstexname(
3764 changeExtension(abstexname, ".pstex"));
3765 bool const xfigeps =
3766 (absepsname.exists() ||
3767 abspstexname.exists()) &&
3770 // Combined PDF/LaTeX:
3771 // x.pdf, x.pdftex_t (old xfig)
3772 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3773 FileName const abspdfname(
3774 changeExtension(abstexname, ".pdf"));
3775 bool const xfigpdf =
3776 abspdfname.exists() &&
3777 (ext == "pdftex_t" || ext == "pdf_t");
3781 // Combined PS/PDF/LaTeX:
3782 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3783 string const absbase2(
3784 removeExtension(abstexname) + "_pspdftex");
3785 FileName const abseps2name(
3786 addExtension(absbase2, ".eps"));
3787 FileName const abspdf2name(
3788 addExtension(absbase2, ".pdf"));
3789 bool const xfigboth =
3790 abspdf2name.exists() &&
3791 abseps2name.exists() && ext == "pspdftex";
3793 xfig = xfigpdf || xfigeps || xfigboth;
3794 external = external && xfig;
3797 outname = changeExtension(filename, ".fig");
3799 // Don't try to convert, the result
3800 // would be full of ERT.
3802 } else if (t.cs() != "verbatiminput" &&
3803 tex2lyx(abstexname, FileName(abslyxname),
3810 cerr << "Warning: Could not find included file '"
3811 << filename << "'." << endl;
3815 begin_inset(os, "External\n");
3816 os << "\ttemplate XFig\n"
3817 << "\tfilename " << outname << '\n';
3818 registerExternalTemplatePackages("XFig");
3820 begin_command_inset(os, "include", name);
3821 os << "preview false\n"
3822 "filename \"" << outname << "\"\n";
3823 if (t.cs() == "verbatiminput")
3824 preamble.registerAutomaticallyLoadedPackage("verbatim");
3829 else if (t.cs() == "bibliographystyle") {
3830 // store new bibliographystyle
3831 bibliographystyle = p.verbatim_item();
3832 // If any other command than \bibliography and
3833 // \nocite{*} follows, we need to output the style
3834 // (because it might be used by that command).
3835 // Otherwise, it will automatically be output by LyX.
3838 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3839 if (t2.cat() == catBegin)
3841 if (t2.cat() != catEscape)
3843 if (t2.cs() == "nocite") {
3844 if (p.getArg('{', '}') == "*")
3846 } else if (t2.cs() == "bibliography")
3853 "\\bibliographystyle{" + bibliographystyle + '}',
3858 else if (t.cs() == "bibliography") {
3859 context.check_layout(os);
3860 begin_command_inset(os, "bibtex", "bibtex");
3861 if (!btprint.empty()) {
3862 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3863 // clear the string because the next BibTeX inset can be without the
3864 // \nocite{*} option
3867 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3868 // Do we have a bibliographystyle set?
3869 if (!bibliographystyle.empty())
3870 os << "options " << '"' << bibliographystyle << '"' << "\n";
3874 else if (t.cs() == "parbox") {
3875 // Test whether this is an outer box of a shaded box
3877 // swallow arguments
3878 while (p.hasOpt()) {
3880 p.skip_spaces(true);
3883 p.skip_spaces(true);
3885 if (p.next_token().cat() == catBegin)
3887 p.skip_spaces(true);
3888 Token to = p.get_token();
3889 bool shaded = false;
3890 if (to.asInput() == "\\begin") {
3891 p.skip_spaces(true);
3892 if (p.getArg('{', '}') == "shaded")
3897 parse_outer_box(p, os, FLAG_ITEM, outer,
3898 context, "parbox", "shaded");
3900 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3904 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3905 t.cs() == "shadowbox" || t.cs() == "doublebox")
3906 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3908 else if (t.cs() == "framebox") {
3909 if (p.next_token().character() == '(') {
3910 //the syntax is: \framebox(x,y)[position]{content}
3911 string arg = t.asInput();
3912 arg += p.getFullParentheseArg();
3913 arg += p.getFullOpt();
3914 eat_whitespace(p, os, context, false);
3915 handle_ert(os, arg + '{', context);
3916 parse_text(p, os, FLAG_ITEM, outer, context);
3917 handle_ert(os, "}", context);
3919 string special = p.getFullOpt();
3920 special += p.getOpt();
3921 // LyX does not yet support \framebox without any option
3922 if (!special.empty())
3923 parse_outer_box(p, os, FLAG_ITEM, outer,
3924 context, t.cs(), special);
3926 eat_whitespace(p, os, context, false);
3927 handle_ert(os, "\\framebox{", context);
3928 parse_text(p, os, FLAG_ITEM, outer, context);
3929 handle_ert(os, "}", context);
3934 //\makebox() is part of the picture environment and different from \makebox{}
3935 //\makebox{} will be parsed by parse_box
3936 else if (t.cs() == "makebox") {
3937 if (p.next_token().character() == '(') {
3938 //the syntax is: \makebox(x,y)[position]{content}
3939 string arg = t.asInput();
3940 arg += p.getFullParentheseArg();
3941 arg += p.getFullOpt();
3942 eat_whitespace(p, os, context, false);
3943 handle_ert(os, arg + '{', context);
3944 parse_text(p, os, FLAG_ITEM, outer, context);
3945 handle_ert(os, "}", context);
3947 //the syntax is: \makebox[width][position]{content}
3948 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3952 else if (t.cs() == "smallskip" ||
3953 t.cs() == "medskip" ||
3954 t.cs() == "bigskip" ||
3955 t.cs() == "vfill") {
3956 context.check_layout(os);
3957 begin_inset(os, "VSpace ");
3960 skip_spaces_braces(p);
3963 else if ((where = is_known(t.cs(), known_spaces))) {
3964 context.check_layout(os);
3965 begin_inset(os, "space ");
3966 os << '\\' << known_coded_spaces[where - known_spaces]
3969 // LaTeX swallows whitespace after all spaces except
3970 // "\\,". We have to do that here, too, because LyX
3971 // adds "{}" which would make the spaces significant.
3973 eat_whitespace(p, os, context, false);
3974 // LyX adds "{}" after all spaces except "\\ " and
3975 // "\\,", so we have to remove "{}".
3976 // "\\,{}" is equivalent to "\\," in LaTeX, so we
3977 // remove the braces after "\\,", too.
3982 else if (t.cs() == "newpage" ||
3983 (t.cs() == "pagebreak" && !p.hasOpt()) ||
3984 t.cs() == "clearpage" ||
3985 t.cs() == "cleardoublepage") {
3986 context.check_layout(os);
3987 begin_inset(os, "Newpage ");
3990 skip_spaces_braces(p);
3993 else if (t.cs() == "DeclareRobustCommand" ||
3994 t.cs() == "DeclareRobustCommandx" ||
3995 t.cs() == "newcommand" ||
3996 t.cs() == "newcommandx" ||
3997 t.cs() == "providecommand" ||
3998 t.cs() == "providecommandx" ||
3999 t.cs() == "renewcommand" ||
4000 t.cs() == "renewcommandx") {
4001 // DeclareRobustCommand, DeclareRobustCommandx,
4002 // providecommand and providecommandx could be handled
4003 // by parse_command(), but we need to call
4004 // add_known_command() here.
4005 string name = t.asInput();
4006 if (p.next_token().asInput() == "*") {
4007 // Starred form. Eat '*'
4011 string const command = p.verbatim_item();
4012 string const opt1 = p.getFullOpt();
4013 string const opt2 = p.getFullOpt();
4014 add_known_command(command, opt1, !opt2.empty());
4015 string const ert = name + '{' + command + '}' +
4017 '{' + p.verbatim_item() + '}';
4019 if (t.cs() == "DeclareRobustCommand" ||
4020 t.cs() == "DeclareRobustCommandx" ||
4021 t.cs() == "providecommand" ||
4022 t.cs() == "providecommandx" ||
4023 name[name.length()-1] == '*')
4024 handle_ert(os, ert, context);
4026 context.check_layout(os);
4027 begin_inset(os, "FormulaMacro");
4033 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4034 // let could be handled by parse_command(),
4035 // but we need to call add_known_command() here.
4036 string ert = t.asInput();
4039 if (p.next_token().cat() == catBegin) {
4040 name = p.verbatim_item();
4041 ert += '{' + name + '}';
4043 name = p.verbatim_item();
4048 if (p.next_token().cat() == catBegin) {
4049 command = p.verbatim_item();
4050 ert += '{' + command + '}';
4052 command = p.verbatim_item();
4055 // If command is known, make name known too, to parse
4056 // its arguments correctly. For this reason we also
4057 // have commands in syntax.default that are hardcoded.
4058 CommandMap::iterator it = known_commands.find(command);
4059 if (it != known_commands.end())
4060 known_commands[t.asInput()] = it->second;
4061 handle_ert(os, ert, context);
4064 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4065 bool starred = false;
4066 if (p.next_token().asInput() == "*") {
4070 string name = t.asInput();
4071 string const length = p.verbatim_item();
4074 bool valid = splitLatexLength(length, valstring, unit);
4075 bool known_hspace = false;
4076 bool known_vspace = false;
4077 bool known_unit = false;
4080 istringstream iss(valstring);
4083 if (t.cs()[0] == 'h') {
4084 if (unit == "\\fill") {
4089 known_hspace = true;
4092 if (unit == "\\smallskipamount") {
4094 known_vspace = true;
4095 } else if (unit == "\\medskipamount") {
4097 known_vspace = true;
4098 } else if (unit == "\\bigskipamount") {
4100 known_vspace = true;
4101 } else if (unit == "\\fill") {
4103 known_vspace = true;
4107 if (!known_hspace && !known_vspace) {
4108 switch (unitFromString(unit)) {
4129 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4130 // Literal horizontal length or known variable
4131 context.check_layout(os);
4132 begin_inset(os, "space ");
4140 if (known_unit && !known_hspace)
4142 << translate_len(length);
4144 } else if (known_unit || known_vspace) {
4145 // Literal vertical length or known variable
4146 context.check_layout(os);
4147 begin_inset(os, "VSpace ");
4155 // LyX can't handle other length variables in Inset VSpace/space
4160 handle_ert(os, name + '{' + unit + '}', context);
4161 else if (value == -1.0)
4162 handle_ert(os, name + "{-" + unit + '}', context);
4164 handle_ert(os, name + '{' + valstring + unit + '}', context);
4166 handle_ert(os, name + '{' + length + '}', context);
4170 // The single '=' is meant here.
4171 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4173 context.check_layout(os);
4174 begin_inset(os, "Flex ");
4175 os << to_utf8(newinsetlayout->name()) << '\n'
4176 << "status collapsed\n";
4177 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4181 else if (t.cs() == "includepdf") {
4183 string const arg = p.getArg('[', ']');
4184 map<string, string> opts;
4185 vector<string> keys;
4186 split_map(arg, opts, keys);
4187 string name = normalize_filename(p.verbatim_item());
4188 string const path = makeAbsPath(getMasterFilePath()).absFileName();
4189 // We want to preserve relative / absolute filenames,
4190 // therefore path is only used for testing
4191 if (!makeAbsPath(name, path).exists()) {
4192 // The file extension is probably missing.
4193 // Now try to find it out.
4194 char const * const pdfpages_format[] = {"pdf", 0};
4195 string const pdftex_name =
4196 find_file(name, path, pdfpages_format);
4197 if (!pdftex_name.empty()) {
4202 if (makeAbsPath(name, path).exists())
4203 fix_relative_filename(name);
4205 cerr << "Warning: Could not find file '"
4206 << name << "'." << endl;
4208 context.check_layout(os);
4209 begin_inset(os, "External\n\ttemplate ");
4210 os << "PDFPages\n\tfilename "
4212 // parse the options
4213 if (opts.find("pages") != opts.end())
4214 os << "\textra LaTeX \"pages="
4215 << opts["pages"] << "\"\n";
4216 if (opts.find("angle") != opts.end())
4217 os << "\trotateAngle "
4218 << opts["angle"] << '\n';
4219 if (opts.find("origin") != opts.end()) {
4221 string const opt = opts["origin"];
4222 if (opt == "tl") ss << "topleft";
4223 if (opt == "bl") ss << "bottomleft";
4224 if (opt == "Bl") ss << "baselineleft";
4225 if (opt == "c") ss << "center";
4226 if (opt == "tc") ss << "topcenter";
4227 if (opt == "bc") ss << "bottomcenter";
4228 if (opt == "Bc") ss << "baselinecenter";
4229 if (opt == "tr") ss << "topright";
4230 if (opt == "br") ss << "bottomright";
4231 if (opt == "Br") ss << "baselineright";
4232 if (!ss.str().empty())
4233 os << "\trotateOrigin " << ss.str() << '\n';
4235 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4237 if (opts.find("width") != opts.end())
4239 << translate_len(opts["width"]) << '\n';
4240 if (opts.find("height") != opts.end())
4242 << translate_len(opts["height"]) << '\n';
4243 if (opts.find("keepaspectratio") != opts.end())
4244 os << "\tkeepAspectRatio\n";
4246 context.check_layout(os);
4247 registerExternalTemplatePackages("PDFPages");
4250 else if (t.cs() == "loadgame") {
4252 string name = normalize_filename(p.verbatim_item());
4253 string const path = makeAbsPath(getMasterFilePath()).absFileName();
4254 // We want to preserve relative / absolute filenames,
4255 // therefore path is only used for testing
4256 if (!makeAbsPath(name, path).exists()) {
4257 // The file extension is probably missing.
4258 // Now try to find it out.
4259 char const * const lyxskak_format[] = {"fen", 0};
4260 string const lyxskak_name =
4261 find_file(name, path, lyxskak_format);
4262 if (!lyxskak_name.empty())
4263 name = lyxskak_name;
4265 if (makeAbsPath(name, path).exists())
4266 fix_relative_filename(name);
4268 cerr << "Warning: Could not find file '"
4269 << name << "'." << endl;
4270 context.check_layout(os);
4271 begin_inset(os, "External\n\ttemplate ");
4272 os << "ChessDiagram\n\tfilename "
4275 context.check_layout(os);
4276 // after a \loadgame follows a \showboard
4277 if (p.get_token().asInput() == "showboard")
4279 registerExternalTemplatePackages("ChessDiagram");
4283 // try to see whether the string is in unicodesymbols
4284 // Only use text mode commands, since we are in text mode here,
4285 // and math commands may be invalid (bug 6797)
4289 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4290 Encodings::TEXT_CMD, termination, rem, &req);
4293 cerr << "When parsing " << t.cs()
4294 << ", result is " << to_utf8(s)
4295 << "+" << to_utf8(rem) << endl;
4296 context.check_layout(os);
4299 skip_spaces_braces(p);
4300 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4301 preamble.registerAutomaticallyLoadedPackage(*it);
4303 //cerr << "#: " << t << " mode: " << mode << endl;
4304 // heuristic: read up to next non-nested space
4306 string s = t.asInput();
4307 string z = p.verbatim_item();
4308 while (p.good() && z != " " && z.size()) {
4309 //cerr << "read: " << z << endl;
4311 z = p.verbatim_item();
4313 cerr << "found ERT: " << s << endl;
4314 handle_ert(os, s + ' ', context);
4317 string name = t.asInput();
4318 if (p.next_token().asInput() == "*") {
4319 // Starred commands like \vspace*{}
4320 p.get_token(); // Eat '*'
4323 if (!parse_command(name, p, os, outer, context))
4324 handle_ert(os, name, context);
4328 if (flags & FLAG_LEAVE) {
4329 flags &= ~FLAG_LEAVE;