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 "support/lassert.h"
28 #include "support/convert.h"
29 #include "support/FileName.h"
30 #include "support/filetools.h"
31 #include "support/lstrings.h"
32 #include "support/lyxtime.h"
41 using namespace lyx::support;
46 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
47 Context const & context, InsetLayout const * layout)
49 bool const forcePlainLayout =
50 layout ? layout->forcePlainLayout() : false;
51 Context newcontext(true, context.textclass);
53 newcontext.layout = &context.textclass.plainLayout();
55 newcontext.font = context.font;
56 parse_text(p, os, flags, outer, newcontext);
57 newcontext.check_end_layout(os);
63 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
64 Context const & context, string const & name)
66 InsetLayout const * layout = 0;
67 DocumentClass::InsetLayouts::const_iterator it =
68 context.textclass.insetLayouts().find(from_ascii(name));
69 if (it != context.textclass.insetLayouts().end())
70 layout = &(it->second);
71 parse_text_in_inset(p, os, flags, outer, context, layout);
74 /// parses a paragraph snippet, useful for example for \\emph{...}
75 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
78 Context newcontext(context);
79 // Don't inherit the paragraph-level extra stuff
80 newcontext.par_extra_stuff.clear();
81 parse_text(p, os, flags, outer, newcontext);
82 // Make sure that we don't create invalid .lyx files
83 context.need_layout = newcontext.need_layout;
84 context.need_end_layout = newcontext.need_end_layout;
89 * Thin wrapper around parse_text_snippet() using a string.
91 * We completely ignore \c context.need_layout and \c context.need_end_layout,
92 * because our return value is not used directly (otherwise the stream version
93 * of parse_text_snippet() could be used). That means that the caller needs
94 * to do layout management manually.
95 * This is intended to parse text that does not create any layout changes.
97 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
100 Context newcontext(context);
101 newcontext.need_layout = false;
102 newcontext.need_end_layout = false;
103 newcontext.new_layout_allowed = false;
104 // Avoid warning by Context::~Context()
105 newcontext.par_extra_stuff.clear();
107 parse_text_snippet(p, os, flags, outer, newcontext);
112 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
113 "vpageref", "prettyref", "eqref", 0 };
115 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
116 "vpageref", "formatted", "eqref", 0 };
120 * The starred forms are also known except for "citefullauthor",
121 * "citeyear" and "citeyearpar".
123 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
124 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
125 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
129 * No starred form other than "cite*" known.
131 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
132 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
133 // jurabib commands not (yet) supported by LyX:
135 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
136 // "footciteauthor", "footciteyear", "footciteyearpar",
137 "citefield", "citetitle", 0 };
139 /// LaTeX names for quotes
140 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
141 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
142 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
143 "guilsinglleft", "frq", "guilsinglright", 0};
145 /// the same as known_quotes with .lyx names
146 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
147 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
148 "gld", "grd", "gls", "ers", "fls",
149 "fls", "frs", "frs", 0};
151 /// LaTeX names for font sizes
152 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
153 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
155 /// the same as known_sizes with .lyx names
156 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
157 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
159 /// LaTeX 2.09 names for font families
160 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
162 /// LaTeX names for font families
163 char const * const known_font_families[] = { "rmfamily", "sffamily",
166 /// the same as known_old_font_families and known_font_families with .lyx names
167 char const * const known_coded_font_families[] = { "roman", "sans",
170 /// LaTeX 2.09 names for font series
171 char const * const known_old_font_series[] = { "bf", 0};
173 /// LaTeX names for font series
174 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
176 /// the same as known_old_font_series and known_font_series with .lyx names
177 char const * const known_coded_font_series[] = { "bold", "medium", 0};
179 /// LaTeX 2.09 names for font shapes
180 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
182 /// LaTeX names for font shapes
183 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
186 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
187 char const * const known_coded_font_shapes[] = { "italic", "slanted",
188 "smallcaps", "up", 0};
191 * Graphics file extensions known by the dvips driver of the graphics package.
192 * These extensions are used to complete the filename of an included
193 * graphics file if it does not contain an extension.
194 * The order must be the same that latex uses to find a file, because we
195 * will use the first extension that matches.
196 * This is only an approximation for the common cases. If we would want to
197 * do it right in all cases, we would need to know which graphics driver is
198 * used and know the extensions of every driver of the graphics package.
200 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
201 "ps.gz", "eps.Z", "ps.Z", 0};
204 * Graphics file extensions known by the pdftex driver of the graphics package.
205 * \sa known_dvips_graphics_formats
207 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
211 * Known file extensions for TeX files as used by \\include.
213 char const * const known_tex_extensions[] = {"tex", 0};
215 /// spaces known by InsetSpace
216 char const * const known_spaces[] = { " ", "space", ",",
217 "thinspace", "quad", "qquad", "enspace", "enskip",
218 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
219 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
220 "upbracefill", "downbracefill", 0};
222 /// the same as known_spaces with .lyx names
223 char const * const known_coded_spaces[] = { "space{}", "space{}",
224 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
225 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
226 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
227 "upbracefill{}", "downbracefill{}", 0};
229 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
230 /// them in ERT. "LaTeXe" must come before "LaTeX"!
231 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
232 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
233 int const known_phrase_lengths[] = {3, 5, 7, 0};
235 // string to store the float type to be able to determine the type of subfloats
236 string float_type = "";
239 /// splits "x=z, y=b" into a map and an ordered keyword vector
240 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
245 keys.resize(v.size());
246 for (size_t i = 0; i < v.size(); ++i) {
247 size_t const pos = v[i].find('=');
248 string const index = trimSpaceAndEol(v[i].substr(0, pos));
249 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
257 * Split a LaTeX length into value and unit.
258 * The latter can be a real unit like "pt", or a latex length variable
259 * like "\textwidth". The unit may contain additional stuff like glue
260 * lengths, but we don't care, because such lengths are ERT anyway.
261 * \returns true if \p value and \p unit are valid.
263 bool splitLatexLength(string const & len, string & value, string & unit)
267 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
268 //'4,5' is a valid LaTeX length number. Change it to '4.5'
269 string const length = subst(len, ',', '.');
270 if (i == string::npos)
273 if (len[0] == '\\') {
274 // We had something like \textwidth without a factor
280 value = trimSpaceAndEol(string(length, 0, i));
284 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
285 if (contains(len, '\\'))
286 unit = trimSpaceAndEol(string(len, i));
288 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
293 /// A simple function to translate a latex length to something LyX can
294 /// understand. Not perfect, but rather best-effort.
295 bool translate_len(string const & length, string & valstring, string & unit)
297 if (!splitLatexLength(length, valstring, unit))
299 // LyX uses percent values
301 istringstream iss(valstring);
306 string const percentval = oss.str();
308 if (unit.empty() || unit[0] != '\\')
310 string::size_type const i = unit.find(' ');
311 string const endlen = (i == string::npos) ? string() : string(unit, i);
312 if (unit == "\\textwidth") {
313 valstring = percentval;
314 unit = "text%" + endlen;
315 } else if (unit == "\\columnwidth") {
316 valstring = percentval;
317 unit = "col%" + endlen;
318 } else if (unit == "\\paperwidth") {
319 valstring = percentval;
320 unit = "page%" + endlen;
321 } else if (unit == "\\linewidth") {
322 valstring = percentval;
323 unit = "line%" + endlen;
324 } else if (unit == "\\paperheight") {
325 valstring = percentval;
326 unit = "pheight%" + endlen;
327 } else if (unit == "\\textheight") {
328 valstring = percentval;
329 unit = "theight%" + endlen;
337 string translate_len(string const & length)
341 if (translate_len(length, value, unit))
343 // If the input is invalid, return what we have.
351 * Translates a LaTeX length into \p value, \p unit and
352 * \p special parts suitable for a box inset.
353 * The difference from translate_len() is that a box inset knows about
354 * some special "units" that are stored in \p special.
356 void translate_box_len(string const & length, string & value, string & unit, string & special)
358 if (translate_len(length, value, unit)) {
359 if (unit == "\\height" || unit == "\\depth" ||
360 unit == "\\totalheight" || unit == "\\width") {
361 special = unit.substr(1);
362 // The unit is not used, but LyX requires a dummy setting
375 * Find a file with basename \p name in path \p path and an extension
378 string find_file(string const & name, string const & path,
379 char const * const * extensions)
381 for (char const * const * what = extensions; *what; ++what) {
382 string const trial = addExtension(name, *what);
383 if (makeAbsPath(trial, path).exists())
390 void begin_inset(ostream & os, string const & name)
392 os << "\n\\begin_inset " << name;
396 void begin_command_inset(ostream & os, string const & name,
397 string const & latexname)
399 begin_inset(os, "CommandInset ");
400 os << name << "\nLatexCommand " << latexname << '\n';
404 void end_inset(ostream & os)
406 os << "\n\\end_inset\n\n";
410 bool skip_braces(Parser & p)
412 if (p.next_token().cat() != catBegin)
415 if (p.next_token().cat() == catEnd) {
424 /// replace LaTeX commands in \p s from the unicodesymbols file with their
426 docstring convert_unicodesymbols(docstring s)
429 for (size_t i = 0; i < s.size();) {
436 docstring parsed = encodings.fromLaTeXCommand(s, rem,
437 Encodings::TEXT_CMD);
440 if (s.empty() || s[0] != '\\')
449 /// try to convert \p s to a valid InsetCommand argument
450 string convert_command_inset_arg(string s)
453 // since we don't know the input encoding we can't use from_utf8
454 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
455 // LyX cannot handle newlines in a latex command
456 return subst(s, "\n", " ");
460 void handle_backslash(ostream & os, string const & s)
462 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
464 os << "\n\\backslash\n";
471 void handle_ert(ostream & os, string const & s, Context & context)
473 // We must have a valid layout before outputting the ERT inset.
474 context.check_layout(os);
475 Context newcontext(true, context.textclass);
476 begin_inset(os, "ERT");
477 os << "\nstatus collapsed\n";
478 newcontext.check_layout(os);
479 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
481 os << "\n\\backslash\n";
482 else if (*it == '\n') {
483 newcontext.new_paragraph(os);
484 newcontext.check_layout(os);
488 newcontext.check_end_layout(os);
493 void handle_comment(ostream & os, string const & s, Context & context)
495 // TODO: Handle this better
496 Context newcontext(true, context.textclass);
497 begin_inset(os, "ERT");
498 os << "\nstatus collapsed\n";
499 newcontext.check_layout(os);
500 handle_backslash(os, s);
501 // make sure that our comment is the last thing on the line
502 newcontext.new_paragraph(os);
503 newcontext.check_layout(os);
504 newcontext.check_end_layout(os);
509 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
511 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
514 if (checkModule(name, command))
515 return findLayoutWithoutModule(textclass, name, command);
520 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
522 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
525 if (checkModule(name, command))
526 return findInsetLayoutWithoutModule(textclass, name, command);
531 void eat_whitespace(Parser &, ostream &, Context &, bool);
535 * Skips whitespace and braces.
536 * This should be called after a command has been parsed that is not put into
537 * ERT, and where LyX adds "{}" if needed.
539 void skip_spaces_braces(Parser & p, bool keepws = false)
541 /* The following four examples produce the same typeset output and
542 should be handled by this function:
550 // Unfortunately we need to skip comments, too.
551 // We can't use eat_whitespace since writing them after the {}
552 // results in different output in some cases.
553 bool const skipped_spaces = p.skip_spaces(true);
554 bool const skipped_braces = skip_braces(p);
555 if (keepws && skipped_spaces && !skipped_braces)
556 // put back the space (it is better handled by check_space)
557 p.unskip_spaces(true);
561 void output_command_layout(ostream & os, Parser & p, bool outer,
562 Context & parent_context,
563 Layout const * newlayout)
565 TeXFont const oldFont = parent_context.font;
566 // save the current font size
567 string const size = oldFont.size;
568 // reset the font size to default, because the font size switches
569 // don't affect section headings and the like
570 parent_context.font.size = Context::normalfont.size;
571 // we only need to write the font change if we have an open layout
572 if (!parent_context.atParagraphStart())
573 output_font_change(os, oldFont, parent_context.font);
574 parent_context.check_end_layout(os);
575 Context context(true, parent_context.textclass, newlayout,
576 parent_context.layout, parent_context.font);
577 if (parent_context.deeper_paragraph) {
578 // We are beginning a nested environment after a
579 // deeper paragraph inside the outer list environment.
580 // Therefore we don't need to output a "begin deeper".
581 context.need_end_deeper = true;
583 context.check_deeper(os);
584 context.check_layout(os);
585 unsigned int optargs = 0;
586 while (optargs < context.layout->optargs) {
587 eat_whitespace(p, os, context, false);
588 if (p.next_token().cat() == catEscape ||
589 p.next_token().character() != '[')
591 p.get_token(); // eat '['
592 begin_inset(os, "Argument\n");
593 os << "status collapsed\n\n";
594 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
596 eat_whitespace(p, os, context, false);
599 unsigned int reqargs = 0;
600 while (reqargs < context.layout->reqargs) {
601 eat_whitespace(p, os, context, false);
602 if (p.next_token().cat() != catBegin)
604 p.get_token(); // eat '{'
605 begin_inset(os, "Argument\n");
606 os << "status collapsed\n\n";
607 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
609 eat_whitespace(p, os, context, false);
612 parse_text(p, os, FLAG_ITEM, outer, context);
613 context.check_end_layout(os);
614 if (parent_context.deeper_paragraph) {
615 // We must suppress the "end deeper" because we
616 // suppressed the "begin deeper" above.
617 context.need_end_deeper = false;
619 context.check_end_deeper(os);
620 // We don't need really a new paragraph, but
621 // we must make sure that the next item gets a \begin_layout.
622 parent_context.new_paragraph(os);
623 // Set the font size to the original value. No need to output it here
624 // (Context::begin_layout() will do that if needed)
625 parent_context.font.size = size;
630 * Output a space if necessary.
631 * This function gets called for every whitespace token.
633 * We have three cases here:
634 * 1. A space must be suppressed. Example: The lyxcode case below
635 * 2. A space may be suppressed. Example: Spaces before "\par"
636 * 3. A space must not be suppressed. Example: A space between two words
638 * We currently handle only 1. and 3 and from 2. only the case of
639 * spaces before newlines as a side effect.
641 * 2. could be used to suppress as many spaces as possible. This has two effects:
642 * - Reimporting LyX generated LaTeX files changes almost no whitespace
643 * - Superflous whitespace from non LyX generated LaTeX files is removed.
644 * The drawback is that the logic inside the function becomes
645 * complicated, and that is the reason why it is not implemented.
647 void check_space(Parser & p, ostream & os, Context & context)
649 Token const next = p.next_token();
650 Token const curr = p.curr_token();
651 // A space before a single newline and vice versa must be ignored
652 // LyX emits a newline before \end{lyxcode}.
653 // This newline must be ignored,
654 // otherwise LyX will add an additional protected space.
655 if (next.cat() == catSpace ||
656 next.cat() == catNewline ||
657 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
660 context.check_layout(os);
666 * Parse all arguments of \p command
668 void parse_arguments(string const & command,
669 vector<ArgumentType> const & template_arguments,
670 Parser & p, ostream & os, bool outer, Context & context)
672 string ert = command;
673 size_t no_arguments = template_arguments.size();
674 for (size_t i = 0; i < no_arguments; ++i) {
675 switch (template_arguments[i]) {
677 // This argument contains regular LaTeX
678 handle_ert(os, ert + '{', context);
679 eat_whitespace(p, os, context, false);
680 parse_text(p, os, FLAG_ITEM, outer, context);
684 // This argument consists only of a single item.
685 // The presence of '{' or not must be preserved.
687 if (p.next_token().cat() == catBegin)
688 ert += '{' + p.verbatim_item() + '}';
690 ert += p.verbatim_item();
693 // This argument may contain special characters
694 ert += '{' + p.verbatim_item() + '}';
697 // true because we must not eat whitespace
698 // if an optional arg follows we must not strip the
699 // brackets from this one
700 if (i < no_arguments - 1 &&
701 template_arguments[i+1] == optional)
702 ert += p.getFullOpt(true);
704 ert += p.getOpt(true);
708 handle_ert(os, ert, context);
713 * Check whether \p command is a known command. If yes,
714 * handle the command with all arguments.
715 * \return true if the command was parsed, false otherwise.
717 bool parse_command(string const & command, Parser & p, ostream & os,
718 bool outer, Context & context)
720 if (known_commands.find(command) != known_commands.end()) {
721 parse_arguments(command, known_commands[command], p, os,
729 /// Parses a minipage or parbox
730 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
731 unsigned inner_flags, bool outer, Context & parent_context,
732 string const & outer_type, string const & special,
733 string const & inner_type)
737 string hor_pos = "c";
738 // We need to set the height to the LaTeX default of 1\\totalheight
739 // for the case when no height argument is given
740 string height_value = "1";
741 string height_unit = "in";
742 string height_special = "totalheight";
744 if (!inner_type.empty() && p.hasOpt()) {
745 position = p.getArg('[', ']');
746 if (position != "t" && position != "c" && position != "b") {
747 cerr << "invalid position " << position << " for "
748 << inner_type << endl;
752 latex_height = p.getArg('[', ']');
753 translate_box_len(latex_height, height_value, height_unit, height_special);
756 inner_pos = p.getArg('[', ']');
757 if (inner_pos != "c" && inner_pos != "t" &&
758 inner_pos != "b" && inner_pos != "s") {
759 cerr << "invalid inner_pos "
760 << inner_pos << " for "
761 << inner_type << endl;
762 inner_pos = position;
770 if (inner_type.empty()) {
772 latex_width = "\\columnwidth";
775 latex_width = p2.getArg('[', ']');
776 string const opt = p2.getArg('[', ']');
779 if (hor_pos != "l" && hor_pos != "c" &&
781 cerr << "invalid hor_pos " << hor_pos
782 << " for " << outer_type << endl;
788 latex_width = p.verbatim_item();
789 translate_len(latex_width, width_value, width_unit);
790 bool shadedparbox = false;
791 if (inner_type == "shaded") {
792 eat_whitespace(p, os, parent_context, false);
793 if (outer_type == "parbox") {
795 if (p.next_token().cat() == catBegin)
797 eat_whitespace(p, os, parent_context, false);
803 // If we already read the inner box we have to push the inner env
804 if (!outer_type.empty() && !inner_type.empty() &&
805 (inner_flags & FLAG_END))
806 active_environments.push_back(inner_type);
807 // LyX can't handle length variables
808 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
809 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
810 // Look whether there is some content after the end of the
811 // inner box, but before the end of the outer box.
812 // If yes, we need to output ERT.
814 if (inner_flags & FLAG_END)
815 p.verbatimEnvironment(inner_type);
819 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
820 if ((outer_env && p.next_token().asInput() != "\\end") ||
821 (!outer_env && p.next_token().cat() != catEnd)) {
822 // something is between the end of the inner box and
823 // the end of the outer box, so we need to use ERT.
830 if (!outer_type.empty()) {
831 if (outer_flags & FLAG_END)
832 ss << "\\begin{" << outer_type << '}';
834 ss << '\\' << outer_type << '{';
835 if (!special.empty())
839 if (!inner_type.empty()) {
840 if (inner_type != "shaded") {
841 if (inner_flags & FLAG_END)
842 ss << "\\begin{" << inner_type << '}';
844 ss << '\\' << inner_type;
846 if (!position.empty())
847 ss << '[' << position << ']';
848 if (!latex_height.empty())
849 ss << '[' << latex_height << ']';
850 if (!inner_pos.empty())
851 ss << '[' << inner_pos << ']';
852 ss << '{' << latex_width << '}';
853 if (!(inner_flags & FLAG_END))
856 if (inner_type == "shaded")
857 ss << "\\begin{shaded}";
858 handle_ert(os, ss.str(), parent_context);
859 if (!inner_type.empty()) {
860 parse_text(p, os, inner_flags, outer, parent_context);
861 if (inner_flags & FLAG_END)
862 handle_ert(os, "\\end{" + inner_type + '}',
865 handle_ert(os, "}", parent_context);
867 if (!outer_type.empty()) {
868 // If we already read the inner box we have to pop
870 if (!inner_type.empty() && (inner_flags & FLAG_END))
871 active_environments.pop_back();
872 parse_text(p, os, outer_flags, outer, parent_context);
873 if (outer_flags & FLAG_END)
874 handle_ert(os, "\\end{" + outer_type + '}',
877 handle_ert(os, "}", parent_context);
880 // LyX does not like empty positions, so we have
881 // to set them to the LaTeX default values here.
882 if (position.empty())
884 if (inner_pos.empty())
885 inner_pos = position;
886 // FIXME: Support makebox
887 bool const use_makebox = false;
888 parent_context.check_layout(os);
889 begin_inset(os, "Box ");
890 if (outer_type == "framed")
892 else if (outer_type == "framebox")
894 else if (outer_type == "shadowbox")
896 else if ((outer_type == "shaded" && inner_type.empty()) ||
897 (outer_type == "minipage" && inner_type == "shaded") ||
898 (outer_type == "parbox" && inner_type == "shaded")) {
900 preamble.registerAutomaticallyLoadedPackage("color");
901 } else if (outer_type == "doublebox")
903 else if (outer_type.empty())
906 os << outer_type << '\n';
907 os << "position \"" << position << "\"\n";
908 os << "hor_pos \"" << hor_pos << "\"\n";
909 os << "has_inner_box " << !inner_type.empty() << "\n";
910 os << "inner_pos \"" << inner_pos << "\"\n";
911 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
913 os << "use_makebox " << use_makebox << '\n';
914 os << "width \"" << width_value << width_unit << "\"\n";
915 os << "special \"none\"\n";
916 os << "height \"" << height_value << height_unit << "\"\n";
917 os << "height_special \"" << height_special << "\"\n";
918 os << "status open\n\n";
920 // Unfortunately we can't use parse_text_in_inset:
921 // InsetBox::forcePlainLayout() is hard coded and does not
922 // use the inset layout. Apart from that do we call parse_text
923 // up to two times, but need only one check_end_layout.
925 bool const forcePlainLayout =
926 (!inner_type.empty() || use_makebox) &&
927 outer_type != "shaded" && outer_type != "framed";
928 Context context(true, parent_context.textclass);
929 if (forcePlainLayout)
930 context.layout = &context.textclass.plainLayout();
932 context.font = parent_context.font;
934 // If we have no inner box the contents will be read with the outer box
935 if (!inner_type.empty())
936 parse_text(p, os, inner_flags, outer, context);
938 // Ensure that the end of the outer box is parsed correctly:
939 // The opening brace has been eaten by parse_outer_box()
940 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
941 outer_flags &= ~FLAG_ITEM;
942 outer_flags |= FLAG_BRACE_LAST;
945 // Find end of outer box, output contents if inner_type is
946 // empty and output possible comments
947 if (!outer_type.empty()) {
948 // If we already read the inner box we have to pop
950 if (!inner_type.empty() && (inner_flags & FLAG_END))
951 active_environments.pop_back();
952 // This does not output anything but comments if
953 // inner_type is not empty (see use_ert)
954 parse_text(p, os, outer_flags, outer, context);
957 context.check_end_layout(os);
959 #ifdef PRESERVE_LAYOUT
960 // LyX puts a % after the end of the minipage
961 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
963 //handle_comment(os, "%dummy", parent_context);
966 parent_context.new_paragraph(os);
968 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
969 //handle_comment(os, "%dummy", parent_context);
972 // We add a protected space if something real follows
973 if (p.good() && p.next_token().cat() != catComment) {
974 begin_inset(os, "space ~\n");
983 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
984 Context & parent_context, string const & outer_type,
985 string const & special)
987 eat_whitespace(p, os, parent_context, false);
988 if (flags & FLAG_ITEM) {
990 if (p.next_token().cat() == catBegin)
993 cerr << "Warning: Ignoring missing '{' after \\"
994 << outer_type << '.' << endl;
995 eat_whitespace(p, os, parent_context, false);
998 unsigned int inner_flags = 0;
1000 if (outer_type == "minipage" || outer_type == "parbox") {
1001 p.skip_spaces(true);
1002 while (p.hasOpt()) {
1004 p.skip_spaces(true);
1007 p.skip_spaces(true);
1008 if (outer_type == "parbox") {
1010 if (p.next_token().cat() == catBegin)
1012 eat_whitespace(p, os, parent_context, false);
1015 if (outer_type == "shaded") {
1016 // These boxes never have an inner box
1018 } else if (p.next_token().asInput() == "\\parbox") {
1019 inner = p.get_token().cs();
1020 inner_flags = FLAG_ITEM;
1021 } else if (p.next_token().asInput() == "\\begin") {
1022 // Is this a minipage or shaded box?
1025 inner = p.getArg('{', '}');
1027 if (inner == "minipage" || inner == "shaded")
1028 inner_flags = FLAG_END;
1033 if (inner_flags == FLAG_END) {
1034 if (inner != "shaded")
1038 eat_whitespace(p, os, parent_context, false);
1040 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1041 outer_type, special, inner);
1043 if (inner_flags == FLAG_ITEM) {
1045 eat_whitespace(p, os, parent_context, false);
1047 parse_box(p, os, flags, inner_flags, outer, parent_context,
1048 outer_type, special, inner);
1053 void parse_listings(Parser & p, ostream & os, Context & parent_context)
1055 parent_context.check_layout(os);
1056 begin_inset(os, "listings\n");
1057 os << "inline false\n"
1058 << "status collapsed\n";
1059 Context context(true, parent_context.textclass);
1060 context.layout = &parent_context.textclass.plainLayout();
1061 context.check_layout(os);
1062 string const s = p.verbatimEnvironment("lstlisting");
1063 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1065 os << "\n\\backslash\n";
1066 else if (*it == '\n') {
1067 // avoid adding an empty paragraph at the end
1069 context.new_paragraph(os);
1070 context.check_layout(os);
1075 context.check_end_layout(os);
1080 /// parse an unknown environment
1081 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1082 unsigned flags, bool outer,
1083 Context & parent_context)
1085 if (name == "tabbing")
1086 // We need to remember that we have to handle '\=' specially
1087 flags |= FLAG_TABBING;
1089 // We need to translate font changes and paragraphs inside the
1090 // environment to ERT if we have a non standard font.
1091 // Otherwise things like
1092 // \large\begin{foo}\huge bar\end{foo}
1094 bool const specialfont =
1095 (parent_context.font != parent_context.normalfont);
1096 bool const new_layout_allowed = parent_context.new_layout_allowed;
1098 parent_context.new_layout_allowed = false;
1099 handle_ert(os, "\\begin{" + name + "}", parent_context);
1100 parse_text_snippet(p, os, flags, outer, parent_context);
1101 handle_ert(os, "\\end{" + name + "}", parent_context);
1103 parent_context.new_layout_allowed = new_layout_allowed;
1107 void parse_environment(Parser & p, ostream & os, bool outer,
1108 string & last_env, bool & title_layout_found,
1109 Context & parent_context)
1111 Layout const * newlayout;
1112 InsetLayout const * newinsetlayout = 0;
1113 string const name = p.getArg('{', '}');
1114 const bool is_starred = suffixIs(name, '*');
1115 string const unstarred_name = rtrim(name, "*");
1116 active_environments.push_back(name);
1118 if (is_math_env(name)) {
1119 parent_context.check_layout(os);
1120 begin_inset(os, "Formula ");
1121 os << "\\begin{" << name << "}";
1122 parse_math(p, os, FLAG_END, MATH_MODE);
1123 os << "\\end{" << name << "}";
1127 else if (name == "tabular" || name == "longtable") {
1128 eat_whitespace(p, os, parent_context, false);
1129 parent_context.check_layout(os);
1130 begin_inset(os, "Tabular ");
1131 handle_tabular(p, os, name == "longtable", parent_context);
1136 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1137 eat_whitespace(p, os, parent_context, false);
1138 parent_context.check_layout(os);
1139 begin_inset(os, "Float " + unstarred_name + "\n");
1140 // store the float type for subfloats
1141 // subfloats only work with figures and tables
1142 if (unstarred_name == "figure")
1143 float_type = unstarred_name;
1144 else if (unstarred_name == "table")
1145 float_type = unstarred_name;
1149 os << "placement " << p.getArg('[', ']') << '\n';
1150 os << "wide " << convert<string>(is_starred)
1151 << "\nsideways false"
1152 << "\nstatus open\n\n";
1153 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1155 // We don't need really a new paragraph, but
1156 // we must make sure that the next item gets a \begin_layout.
1157 parent_context.new_paragraph(os);
1159 // the float is parsed thus delete the type
1163 else if (unstarred_name == "sidewaysfigure"
1164 || unstarred_name == "sidewaystable") {
1165 eat_whitespace(p, os, parent_context, false);
1166 parent_context.check_layout(os);
1167 if (unstarred_name == "sidewaysfigure")
1168 begin_inset(os, "Float figure\n");
1170 begin_inset(os, "Float table\n");
1171 os << "wide " << convert<string>(is_starred)
1172 << "\nsideways true"
1173 << "\nstatus open\n\n";
1174 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1176 // We don't need really a new paragraph, but
1177 // we must make sure that the next item gets a \begin_layout.
1178 parent_context.new_paragraph(os);
1182 else if (name == "wrapfigure" || name == "wraptable") {
1183 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1184 eat_whitespace(p, os, parent_context, false);
1185 parent_context.check_layout(os);
1188 string overhang = "0col%";
1191 lines = p.getArg('[', ']');
1192 string const placement = p.getArg('{', '}');
1194 overhang = p.getArg('[', ']');
1195 string const width = p.getArg('{', '}');
1197 if (name == "wrapfigure")
1198 begin_inset(os, "Wrap figure\n");
1200 begin_inset(os, "Wrap table\n");
1201 os << "lines " << lines
1202 << "\nplacement " << placement
1203 << "\noverhang " << lyx::translate_len(overhang)
1204 << "\nwidth " << lyx::translate_len(width)
1205 << "\nstatus open\n\n";
1206 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1208 // We don't need really a new paragraph, but
1209 // we must make sure that the next item gets a \begin_layout.
1210 parent_context.new_paragraph(os);
1214 else if (name == "minipage") {
1215 eat_whitespace(p, os, parent_context, false);
1216 // Test whether this is an outer box of a shaded box
1218 // swallow arguments
1219 while (p.hasOpt()) {
1221 p.skip_spaces(true);
1224 p.skip_spaces(true);
1225 Token t = p.get_token();
1226 bool shaded = false;
1227 if (t.asInput() == "\\begin") {
1228 p.skip_spaces(true);
1229 if (p.getArg('{', '}') == "shaded")
1234 parse_outer_box(p, os, FLAG_END, outer,
1235 parent_context, name, "shaded");
1237 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1242 else if (name == "comment") {
1243 eat_whitespace(p, os, parent_context, false);
1244 parent_context.check_layout(os);
1245 begin_inset(os, "Note Comment\n");
1246 os << "status open\n";
1247 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1250 skip_braces(p); // eat {} that might by set by LyX behind comments
1253 else if (name == "lyxgreyedout") {
1254 eat_whitespace(p, os, parent_context, false);
1255 parent_context.check_layout(os);
1256 begin_inset(os, "Note Greyedout\n");
1257 os << "status open\n";
1258 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1261 if (!preamble.notefontcolor().empty())
1262 preamble.registerAutomaticallyLoadedPackage("color");
1265 else if (name == "framed" || name == "shaded") {
1266 eat_whitespace(p, os, parent_context, false);
1267 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1271 else if (name == "lstlisting") {
1272 eat_whitespace(p, os, parent_context, false);
1273 // FIXME handle listings with parameters
1274 // If this is added, don't forgot to handle the
1275 // automatic color package loading
1277 parse_unknown_environment(p, name, os, FLAG_END,
1278 outer, parent_context);
1280 parse_listings(p, os, parent_context);
1284 else if (!parent_context.new_layout_allowed)
1285 parse_unknown_environment(p, name, os, FLAG_END, outer,
1288 // Alignment and spacing settings
1289 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1290 // therefore are totally broken!
1291 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1292 // they are commands not environments. They are furthermore switches that
1293 // can be ended by another switches, but also by commands like \footnote or
1294 // \parbox. So the only safe way is to leave them untouched.
1295 else if (name == "center" || name == "centering" ||
1296 name == "flushleft" || name == "flushright" ||
1297 name == "singlespace" || name == "onehalfspace" ||
1298 name == "doublespace" || name == "spacing") {
1299 eat_whitespace(p, os, parent_context, false);
1300 // We must begin a new paragraph if not already done
1301 if (! parent_context.atParagraphStart()) {
1302 parent_context.check_end_layout(os);
1303 parent_context.new_paragraph(os);
1305 if (name == "flushleft")
1306 parent_context.add_extra_stuff("\\align left\n");
1307 else if (name == "flushright")
1308 parent_context.add_extra_stuff("\\align right\n");
1309 else if (name == "center" || name == "centering")
1310 parent_context.add_extra_stuff("\\align center\n");
1311 else if (name == "singlespace")
1312 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1313 else if (name == "onehalfspace")
1314 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1315 else if (name == "doublespace")
1316 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1317 else if (name == "spacing")
1318 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1319 parse_text(p, os, FLAG_END, outer, parent_context);
1320 // Just in case the environment is empty
1321 parent_context.extra_stuff.erase();
1322 // We must begin a new paragraph to reset the alignment
1323 parent_context.new_paragraph(os);
1327 // The single '=' is meant here.
1328 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1329 eat_whitespace(p, os, parent_context, false);
1330 Context context(true, parent_context.textclass, newlayout,
1331 parent_context.layout, parent_context.font);
1332 if (parent_context.deeper_paragraph) {
1333 // We are beginning a nested environment after a
1334 // deeper paragraph inside the outer list environment.
1335 // Therefore we don't need to output a "begin deeper".
1336 context.need_end_deeper = true;
1338 parent_context.check_end_layout(os);
1339 if (last_env == name) {
1340 // we need to output a separator since LyX would export
1341 // the two environments as one otherwise (bug 5716)
1342 docstring const sep = from_ascii("--Separator--");
1343 TeX2LyXDocClass const & textclass(parent_context.textclass);
1344 if (textclass.hasLayout(sep)) {
1345 Context newcontext(parent_context);
1346 newcontext.layout = &(textclass[sep]);
1347 newcontext.check_layout(os);
1348 newcontext.check_end_layout(os);
1350 parent_context.check_layout(os);
1351 begin_inset(os, "Note Note\n");
1352 os << "status closed\n";
1353 Context newcontext(true, textclass,
1354 &(textclass.defaultLayout()));
1355 newcontext.check_layout(os);
1356 newcontext.check_end_layout(os);
1358 parent_context.check_end_layout(os);
1361 switch (context.layout->latextype) {
1362 case LATEX_LIST_ENVIRONMENT:
1363 context.add_par_extra_stuff("\\labelwidthstring "
1364 + p.verbatim_item() + '\n');
1367 case LATEX_BIB_ENVIRONMENT:
1368 p.verbatim_item(); // swallow next arg
1374 context.check_deeper(os);
1375 // handle known optional and required arguments
1376 // layouts require all optional arguments before the required ones
1377 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1378 // It is impossible to place anything after the environment name,
1379 // but before the first \\item.
1380 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1381 bool need_layout = true;
1382 unsigned int optargs = 0;
1383 while (optargs < context.layout->optargs) {
1384 eat_whitespace(p, os, context, false);
1385 if (p.next_token().cat() == catEscape ||
1386 p.next_token().character() != '[')
1388 p.get_token(); // eat '['
1390 context.check_layout(os);
1391 need_layout = false;
1393 begin_inset(os, "Argument\n");
1394 os << "status collapsed\n\n";
1395 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1397 eat_whitespace(p, os, context, false);
1400 unsigned int reqargs = 0;
1401 while (reqargs < context.layout->reqargs) {
1402 eat_whitespace(p, os, context, false);
1403 if (p.next_token().cat() != catBegin)
1405 p.get_token(); // eat '{'
1407 context.check_layout(os);
1408 need_layout = false;
1410 begin_inset(os, "Argument\n");
1411 os << "status collapsed\n\n";
1412 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1414 eat_whitespace(p, os, context, false);
1418 parse_text(p, os, FLAG_END, outer, context);
1419 context.check_end_layout(os);
1420 if (parent_context.deeper_paragraph) {
1421 // We must suppress the "end deeper" because we
1422 // suppressed the "begin deeper" above.
1423 context.need_end_deeper = false;
1425 context.check_end_deeper(os);
1426 parent_context.new_paragraph(os);
1428 if (!title_layout_found)
1429 title_layout_found = newlayout->intitle;
1432 // The single '=' is meant here.
1433 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1434 eat_whitespace(p, os, parent_context, false);
1435 parent_context.check_layout(os);
1436 begin_inset(os, "Flex ");
1437 os << to_utf8(newinsetlayout->name()) << '\n'
1438 << "status collapsed\n";
1439 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1443 else if (name == "appendix") {
1444 // This is no good latex style, but it works and is used in some documents...
1445 eat_whitespace(p, os, parent_context, false);
1446 parent_context.check_end_layout(os);
1447 Context context(true, parent_context.textclass, parent_context.layout,
1448 parent_context.layout, parent_context.font);
1449 context.check_layout(os);
1450 os << "\\start_of_appendix\n";
1451 parse_text(p, os, FLAG_END, outer, context);
1452 context.check_end_layout(os);
1456 else if (known_environments.find(name) != known_environments.end()) {
1457 vector<ArgumentType> arguments = known_environments[name];
1458 // The last "argument" denotes wether we may translate the
1459 // environment contents to LyX
1460 // The default required if no argument is given makes us
1461 // compatible with the reLyXre environment.
1462 ArgumentType contents = arguments.empty() ?
1465 if (!arguments.empty())
1466 arguments.pop_back();
1467 // See comment in parse_unknown_environment()
1468 bool const specialfont =
1469 (parent_context.font != parent_context.normalfont);
1470 bool const new_layout_allowed =
1471 parent_context.new_layout_allowed;
1473 parent_context.new_layout_allowed = false;
1474 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1475 outer, parent_context);
1476 if (contents == verbatim)
1477 handle_ert(os, p.verbatimEnvironment(name),
1480 parse_text_snippet(p, os, FLAG_END, outer,
1482 handle_ert(os, "\\end{" + name + "}", parent_context);
1484 parent_context.new_layout_allowed = new_layout_allowed;
1488 parse_unknown_environment(p, name, os, FLAG_END, outer,
1492 active_environments.pop_back();
1496 /// parses a comment and outputs it to \p os.
1497 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1499 LASSERT(t.cat() == catComment, return);
1500 if (!t.cs().empty()) {
1501 context.check_layout(os);
1502 handle_comment(os, '%' + t.cs(), context);
1503 if (p.next_token().cat() == catNewline) {
1504 // A newline after a comment line starts a new
1506 if (context.new_layout_allowed) {
1507 if(!context.atParagraphStart())
1508 // Only start a new paragraph if not already
1509 // done (we might get called recursively)
1510 context.new_paragraph(os);
1512 handle_ert(os, "\n", context);
1513 eat_whitespace(p, os, context, true);
1516 // "%\n" combination
1523 * Reads spaces and comments until the first non-space, non-comment token.
1524 * New paragraphs (double newlines or \\par) are handled like simple spaces
1525 * if \p eatParagraph is true.
1526 * Spaces are skipped, but comments are written to \p os.
1528 void eat_whitespace(Parser & p, ostream & os, Context & context,
1532 Token const & t = p.get_token();
1533 if (t.cat() == catComment)
1534 parse_comment(p, os, t, context);
1535 else if ((! eatParagraph && p.isParagraph()) ||
1536 (t.cat() != catSpace && t.cat() != catNewline)) {
1545 * Set a font attribute, parse text and reset the font attribute.
1546 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1547 * \param currentvalue Current value of the attribute. Is set to the new
1548 * value during parsing.
1549 * \param newvalue New value of the attribute
1551 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1552 Context & context, string const & attribute,
1553 string & currentvalue, string const & newvalue)
1555 context.check_layout(os);
1556 string const oldvalue = currentvalue;
1557 currentvalue = newvalue;
1558 os << '\n' << attribute << ' ' << newvalue << "\n";
1559 parse_text_snippet(p, os, flags, outer, context);
1560 context.check_layout(os);
1561 os << '\n' << attribute << ' ' << oldvalue << "\n";
1562 currentvalue = oldvalue;
1566 /// get the arguments of a natbib or jurabib citation command
1567 void get_cite_arguments(Parser & p, bool natbibOrder,
1568 string & before, string & after)
1570 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1572 // text before the citation
1574 // text after the citation
1575 after = p.getFullOpt();
1577 if (!after.empty()) {
1578 before = p.getFullOpt();
1579 if (natbibOrder && !before.empty())
1580 swap(before, after);
1585 /// Convert filenames with TeX macros and/or quotes to something LyX
1587 string const normalize_filename(string const & name)
1589 Parser p(trim(name, "\""));
1592 Token const & t = p.get_token();
1593 if (t.cat() != catEscape)
1595 else if (t.cs() == "lyxdot") {
1596 // This is used by LyX for simple dots in relative
1600 } else if (t.cs() == "space") {
1610 /// Convert \p name from TeX convention (relative to master file) to LyX
1611 /// convention (relative to .lyx file) if it is relative
1612 void fix_relative_filename(string & name)
1614 if (FileName::isAbsolute(name))
1617 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1618 from_utf8(getParentFilePath())));
1622 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1623 void parse_noweb(Parser & p, ostream & os, Context & context)
1625 // assemble the rest of the keyword
1629 Token const & t = p.get_token();
1630 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1633 scrap = (p.good() && p.next_token().asInput() == "=");
1635 name += p.get_token().asInput();
1638 name += t.asInput();
1641 if (!scrap || !context.new_layout_allowed ||
1642 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1643 cerr << "Warning: Could not interpret '" << name
1644 << "'. Ignoring it." << endl;
1648 // We use new_paragraph instead of check_end_layout because the stuff
1649 // following the noweb chunk needs to start with a \begin_layout.
1650 // This may create a new paragraph even if there was none in the
1651 // noweb file, but the alternative is an invalid LyX file. Since
1652 // noweb code chunks are implemented with a layout style in LyX they
1653 // always must be in an own paragraph.
1654 context.new_paragraph(os);
1655 Context newcontext(true, context.textclass,
1656 &context.textclass[from_ascii("Scrap")]);
1657 newcontext.check_layout(os);
1660 Token const & t = p.get_token();
1661 // We abuse the parser a bit, because this is no TeX syntax
1663 if (t.cat() == catEscape)
1664 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1667 Context tmp(false, context.textclass,
1668 &context.textclass[from_ascii("Scrap")]);
1669 tmp.need_end_layout = true;
1670 tmp.check_layout(oss);
1671 os << subst(t.asInput(), "\n", oss.str());
1673 // The scrap chunk is ended by an @ at the beginning of a line.
1674 // After the @ the line may contain a comment and/or
1675 // whitespace, but nothing else.
1676 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1677 (p.next_token().cat() == catSpace ||
1678 p.next_token().cat() == catNewline ||
1679 p.next_token().cat() == catComment)) {
1680 while (p.good() && p.next_token().cat() == catSpace)
1681 os << p.get_token().asInput();
1682 if (p.next_token().cat() == catComment)
1683 // The comment includes a final '\n'
1684 os << p.get_token().asInput();
1686 if (p.next_token().cat() == catNewline)
1693 newcontext.check_end_layout(os);
1697 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1698 bool is_macro(Parser & p)
1700 Token first = p.curr_token();
1701 if (first.cat() != catEscape || !p.good())
1703 if (first.cs() == "def")
1705 if (first.cs() != "global" && first.cs() != "long")
1707 Token second = p.get_token();
1709 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1710 second.cat() == catNewline || second.cat() == catComment)) {
1711 second = p.get_token();
1714 bool secondvalid = second.cat() == catEscape;
1716 bool thirdvalid = false;
1717 if (p.good() && first.cs() == "global" && secondvalid &&
1718 second.cs() == "long") {
1719 third = p.get_token();
1721 while (p.good() && !p.isParagraph() &&
1722 (third.cat() == catSpace ||
1723 third.cat() == catNewline ||
1724 third.cat() == catComment)) {
1725 third = p.get_token();
1728 thirdvalid = third.cat() == catEscape;
1730 for (int i = 0; i < pos; ++i)
1735 return (first.cs() == "global" || first.cs() == "long") &&
1736 second.cs() == "def";
1737 return first.cs() == "global" && second.cs() == "long" &&
1738 third.cs() == "def";
1742 /// Parse a macro definition (assumes that is_macro() returned true)
1743 void parse_macro(Parser & p, ostream & os, Context & context)
1745 context.check_layout(os);
1746 Token first = p.curr_token();
1749 string command = first.asInput();
1750 if (first.cs() != "def") {
1752 eat_whitespace(p, os, context, false);
1753 second = p.curr_token();
1754 command += second.asInput();
1755 if (second.cs() != "def") {
1757 eat_whitespace(p, os, context, false);
1758 third = p.curr_token();
1759 command += third.asInput();
1762 eat_whitespace(p, os, context, false);
1763 string const name = p.get_token().cs();
1764 eat_whitespace(p, os, context, false);
1770 while (p.next_token().cat() != catBegin) {
1771 if (p.next_token().cat() == catParameter) {
1776 // followed by number?
1777 if (p.next_token().cat() == catOther) {
1778 char c = p.getChar();
1780 // number = current arity + 1?
1781 if (c == arity + '0' + 1)
1786 paramtext += p.get_token().cs();
1788 paramtext += p.get_token().cs();
1793 // only output simple (i.e. compatible) macro as FormulaMacros
1794 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1796 context.check_layout(os);
1797 begin_inset(os, "FormulaMacro");
1798 os << "\n\\def" << ert;
1801 handle_ert(os, command + ert, context);
1804 } // anonymous namespace
1807 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1810 Layout const * newlayout = 0;
1811 InsetLayout const * newinsetlayout = 0;
1812 // Store the latest bibliographystyle and nocite{*} option
1813 // (needed for bibtex inset)
1815 string bibliographystyle;
1816 bool const use_natbib = preamble.isPackageUsed("natbib");
1817 bool const use_jurabib = preamble.isPackageUsed("jurabib");
1819 bool title_layout_found = false;
1821 Token const & t = p.get_token();
1824 debugToken(cerr, t, flags);
1827 if (flags & FLAG_ITEM) {
1828 if (t.cat() == catSpace)
1831 flags &= ~FLAG_ITEM;
1832 if (t.cat() == catBegin) {
1833 // skip the brace and collect everything to the next matching
1835 flags |= FLAG_BRACE_LAST;
1839 // handle only this single token, leave the loop if done
1840 flags |= FLAG_LEAVE;
1843 if (t.cat() != catEscape && t.character() == ']' &&
1844 (flags & FLAG_BRACK_LAST))
1846 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1849 // If there is anything between \end{env} and \begin{env} we
1850 // don't need to output a separator.
1851 if (t.cat() != catSpace && t.cat() != catNewline &&
1852 t.asInput() != "\\begin")
1858 if (t.cat() == catMath) {
1859 // we are inside some text mode thingy, so opening new math is allowed
1860 context.check_layout(os);
1861 begin_inset(os, "Formula ");
1862 Token const & n = p.get_token();
1863 if (n.cat() == catMath && outer) {
1864 // TeX's $$...$$ syntax for displayed math
1866 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1868 p.get_token(); // skip the second '$' token
1870 // simple $...$ stuff
1873 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1879 else if (t.cat() == catSuper || t.cat() == catSub)
1880 cerr << "catcode " << t << " illegal in text mode\n";
1882 // Basic support for english quotes. This should be
1883 // extended to other quotes, but is not so easy (a
1884 // left english quote is the same as a right german
1886 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1887 context.check_layout(os);
1888 begin_inset(os, "Quotes ");
1894 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1895 context.check_layout(os);
1896 begin_inset(os, "Quotes ");
1903 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1904 context.check_layout(os);
1905 begin_inset(os, "Quotes ");
1912 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1913 context.check_layout(os);
1914 begin_inset(os, "Quotes ");
1921 else if (t.asInput() == "<"
1922 && p.next_token().asInput() == "<" && noweb_mode) {
1924 parse_noweb(p, os, context);
1927 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1928 check_space(p, os, context);
1930 else if (t.character() == '[' && noweb_mode &&
1931 p.next_token().character() == '[') {
1932 // These can contain underscores
1934 string const s = p.getFullOpt() + ']';
1935 if (p.next_token().character() == ']')
1938 cerr << "Warning: Inserting missing ']' in '"
1939 << s << "'." << endl;
1940 handle_ert(os, s, context);
1943 else if (t.cat() == catLetter) {
1944 context.check_layout(os);
1945 // Workaround for bug 4752.
1946 // FIXME: This whole code block needs to be removed
1947 // when the bug is fixed and tex2lyx produces
1948 // the updated file format.
1949 // The replacement algorithm in LyX is so stupid that
1950 // it even translates a phrase if it is part of a word.
1951 bool handled = false;
1952 for (int const * l = known_phrase_lengths; *l; ++l) {
1953 string phrase = t.cs();
1954 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
1955 phrase += p.get_token().cs();
1956 if (is_known(phrase, known_coded_phrases)) {
1957 handle_ert(os, phrase, context);
1961 for (size_t i = 1; i < phrase.length(); ++i)
1969 else if (t.cat() == catOther ||
1970 t.cat() == catAlign ||
1971 t.cat() == catParameter) {
1972 // This translates "&" to "\\&" which may be wrong...
1973 context.check_layout(os);
1977 else if (p.isParagraph()) {
1978 if (context.new_layout_allowed)
1979 context.new_paragraph(os);
1981 handle_ert(os, "\\par ", context);
1982 eat_whitespace(p, os, context, true);
1985 else if (t.cat() == catActive) {
1986 context.check_layout(os);
1987 if (t.character() == '~') {
1988 if (context.layout->free_spacing)
1991 begin_inset(os, "space ~\n");
1998 else if (t.cat() == catBegin &&
1999 p.next_token().cat() == catEnd) {
2001 Token const prev = p.prev_token();
2003 if (p.next_token().character() == '`' ||
2004 (prev.character() == '-' &&
2005 p.next_token().character() == '-'))
2006 ; // ignore it in {}`` or -{}-
2008 handle_ert(os, "{}", context);
2012 else if (t.cat() == catBegin) {
2013 context.check_layout(os);
2014 // special handling of font attribute changes
2015 Token const prev = p.prev_token();
2016 Token const next = p.next_token();
2017 TeXFont const oldFont = context.font;
2018 if (next.character() == '[' ||
2019 next.character() == ']' ||
2020 next.character() == '*') {
2022 if (p.next_token().cat() == catEnd) {
2027 handle_ert(os, "{", context);
2028 parse_text_snippet(p, os,
2031 handle_ert(os, "}", context);
2033 } else if (! context.new_layout_allowed) {
2034 handle_ert(os, "{", context);
2035 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2037 handle_ert(os, "}", context);
2038 } else if (is_known(next.cs(), known_sizes)) {
2039 // next will change the size, so we must
2041 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2043 if (!context.atParagraphStart())
2045 << context.font.size << "\n";
2046 } else if (is_known(next.cs(), known_font_families)) {
2047 // next will change the font family, so we
2048 // must reset it here
2049 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2051 if (!context.atParagraphStart())
2053 << context.font.family << "\n";
2054 } else if (is_known(next.cs(), known_font_series)) {
2055 // next will change the font series, so we
2056 // must reset it here
2057 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2059 if (!context.atParagraphStart())
2061 << context.font.series << "\n";
2062 } else if (is_known(next.cs(), known_font_shapes)) {
2063 // next will change the font shape, so we
2064 // must reset it here
2065 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2067 if (!context.atParagraphStart())
2069 << context.font.shape << "\n";
2070 } else if (is_known(next.cs(), known_old_font_families) ||
2071 is_known(next.cs(), known_old_font_series) ||
2072 is_known(next.cs(), known_old_font_shapes)) {
2073 // next will change the font family, series
2074 // and shape, so we must reset it here
2075 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2077 if (!context.atParagraphStart())
2079 << context.font.family
2081 << context.font.series
2083 << context.font.shape << "\n";
2085 handle_ert(os, "{", context);
2086 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2088 handle_ert(os, "}", context);
2092 else if (t.cat() == catEnd) {
2093 if (flags & FLAG_BRACE_LAST) {
2096 cerr << "stray '}' in text\n";
2097 handle_ert(os, "}", context);
2100 else if (t.cat() == catComment)
2101 parse_comment(p, os, t, context);
2104 // control sequences
2107 else if (t.cs() == "(") {
2108 context.check_layout(os);
2109 begin_inset(os, "Formula");
2111 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2116 else if (t.cs() == "[") {
2117 context.check_layout(os);
2118 begin_inset(os, "Formula");
2120 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2125 else if (t.cs() == "begin")
2126 parse_environment(p, os, outer, last_env,
2127 title_layout_found, context);
2129 else if (t.cs() == "end") {
2130 if (flags & FLAG_END) {
2131 // eat environment name
2132 string const name = p.getArg('{', '}');
2133 if (name != active_environment())
2134 cerr << "\\end{" + name + "} does not match \\begin{"
2135 + active_environment() + "}\n";
2138 p.error("found 'end' unexpectedly");
2141 else if (t.cs() == "item") {
2144 bool optarg = false;
2145 if (p.next_token().cat() != catEscape &&
2146 p.next_token().character() == '[') {
2147 p.get_token(); // eat '['
2148 s = parse_text_snippet(p, FLAG_BRACK_LAST,
2153 context.check_layout(os);
2154 if (context.has_item) {
2155 // An item in an unknown list-like environment
2156 // FIXME: Do this in check_layout()!
2157 context.has_item = false;
2159 handle_ert(os, "\\item", context);
2161 handle_ert(os, "\\item ", context);
2164 if (context.layout->labeltype != LABEL_MANUAL) {
2165 // LyX does not support \item[\mybullet]
2166 // in itemize environments
2167 handle_ert(os, "[", context);
2169 handle_ert(os, "]", context);
2170 } else if (!s.empty()) {
2171 // The space is needed to separate the
2172 // item from the rest of the sentence.
2174 eat_whitespace(p, os, context, false);
2179 else if (t.cs() == "bibitem") {
2181 context.check_layout(os);
2182 string label = convert_command_inset_arg(p.getArg('[', ']'));
2183 string key = convert_command_inset_arg(p.verbatim_item());
2184 if (contains(label, '\\') || contains(key, '\\')) {
2185 // LyX can't handle LaTeX commands in labels or keys
2186 handle_ert(os, t.asInput() + '[' + label +
2187 "]{" + p.verbatim_item() + '}',
2190 begin_command_inset(os, "bibitem", "bibitem");
2191 os << "label \"" << label << "\"\n"
2192 "key \"" << key << "\"\n";
2197 else if (is_macro(p))
2198 parse_macro(p, os, context);
2200 else if (t.cs() == "noindent") {
2202 context.add_par_extra_stuff("\\noindent\n");
2205 else if (t.cs() == "appendix") {
2206 context.add_par_extra_stuff("\\start_of_appendix\n");
2207 // We need to start a new paragraph. Otherwise the
2208 // appendix in 'bla\appendix\chapter{' would start
2210 context.new_paragraph(os);
2211 // We need to make sure that the paragraph is
2212 // generated even if it is empty. Otherwise the
2213 // appendix in '\par\appendix\par\chapter{' would
2215 context.check_layout(os);
2216 // FIXME: This is a hack to prevent paragraph
2217 // deletion if it is empty. Handle this better!
2219 "%dummy comment inserted by tex2lyx to "
2220 "ensure that this paragraph is not empty",
2222 // Both measures above may generate an additional
2223 // empty paragraph, but that does not hurt, because
2224 // whitespace does not matter here.
2225 eat_whitespace(p, os, context, true);
2228 // Must catch empty dates before findLayout is called below
2229 else if (t.cs() == "date") {
2230 string const date = p.verbatim_item();
2232 preamble.suppressDate(true);
2234 preamble.suppressDate(false);
2235 if (context.new_layout_allowed &&
2236 (newlayout = findLayout(context.textclass,
2239 output_command_layout(os, p, outer,
2240 context, newlayout);
2242 if (!title_layout_found)
2243 title_layout_found = newlayout->intitle;
2245 handle_ert(os, "\\date{" + date + '}',
2250 // Starred section headings
2251 // Must attempt to parse "Section*" before "Section".
2252 else if ((p.next_token().asInput() == "*") &&
2253 context.new_layout_allowed &&
2254 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2257 output_command_layout(os, p, outer, context, newlayout);
2259 if (!title_layout_found)
2260 title_layout_found = newlayout->intitle;
2263 // Section headings and the like
2264 else if (context.new_layout_allowed &&
2265 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2267 output_command_layout(os, p, outer, context, newlayout);
2269 if (!title_layout_found)
2270 title_layout_found = newlayout->intitle;
2273 else if (t.cs() == "caption") {
2275 context.check_layout(os);
2277 begin_inset(os, "Caption\n");
2278 Context newcontext(true, context.textclass);
2279 newcontext.font = context.font;
2280 newcontext.check_layout(os);
2281 if (p.next_token().cat() != catEscape &&
2282 p.next_token().character() == '[') {
2283 p.get_token(); // eat '['
2284 begin_inset(os, "Argument\n");
2285 os << "status collapsed\n";
2286 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2288 eat_whitespace(p, os, context, false);
2290 parse_text(p, os, FLAG_ITEM, outer, context);
2291 context.check_end_layout(os);
2292 // We don't need really a new paragraph, but
2293 // we must make sure that the next item gets a \begin_layout.
2294 context.new_paragraph(os);
2297 newcontext.check_end_layout(os);
2300 else if (t.cs() == "subfloat") {
2301 // the syntax is \subfloat[caption]{content}
2302 // if it is a table of figure depends on the surrounding float
2303 bool has_caption = false;
2305 // do nothing if there is no outer float
2306 if (!float_type.empty()) {
2307 context.check_layout(os);
2309 begin_inset(os, "Float " + float_type + "\n");
2311 << "\nsideways false"
2312 << "\nstatus collapsed\n\n";
2315 if (p.next_token().cat() != catEscape &&
2316 p.next_token().character() == '[') {
2317 p.get_token(); // eat '['
2318 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2322 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2323 // the caption comes always as the last
2325 // we must make sure that the caption gets a \begin_layout
2326 os << "\n\\begin_layout Plain Layout";
2328 begin_inset(os, "Caption\n");
2329 Context newcontext(true, context.textclass);
2330 newcontext.font = context.font;
2331 newcontext.check_layout(os);
2332 os << caption << "\n";
2333 newcontext.check_end_layout(os);
2334 // We don't need really a new paragraph, but
2335 // we must make sure that the next item gets a \begin_layout.
2336 //newcontext.new_paragraph(os);
2340 // We don't need really a new paragraph, but
2341 // we must make sure that the next item gets a \begin_layout.
2343 context.new_paragraph(os);
2346 context.check_end_layout(os);
2347 // close the layout we opened
2349 os << "\n\\end_layout\n";
2351 // if the float type is not supported or there is no surrounding float
2354 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2355 handle_ert(os, t.asInput() + '[' + opt_arg +
2356 "]{" + p.verbatim_item() + '}', context);
2358 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2362 else if (t.cs() == "includegraphics") {
2363 bool const clip = p.next_token().asInput() == "*";
2366 string const arg = p.getArg('[', ']');
2367 map<string, string> opts;
2368 vector<string> keys;
2369 split_map(arg, opts, keys);
2371 opts["clip"] = string();
2372 string name = normalize_filename(p.verbatim_item());
2374 string const path = getMasterFilePath();
2375 // We want to preserve relative / absolute filenames,
2376 // therefore path is only used for testing
2377 if (!makeAbsPath(name, path).exists()) {
2378 // The file extension is probably missing.
2379 // Now try to find it out.
2380 string const dvips_name =
2381 find_file(name, path,
2382 known_dvips_graphics_formats);
2383 string const pdftex_name =
2384 find_file(name, path,
2385 known_pdftex_graphics_formats);
2386 if (!dvips_name.empty()) {
2387 if (!pdftex_name.empty()) {
2388 cerr << "This file contains the "
2390 "\"\\includegraphics{"
2392 "However, files\n\""
2393 << dvips_name << "\" and\n\""
2394 << pdftex_name << "\"\n"
2395 "both exist, so I had to make a "
2396 "choice and took the first one.\n"
2397 "Please move the unwanted one "
2398 "someplace else and try again\n"
2399 "if my choice was wrong."
2403 } else if (!pdftex_name.empty()) {
2409 if (makeAbsPath(name, path).exists())
2410 fix_relative_filename(name);
2412 cerr << "Warning: Could not find graphics file '"
2413 << name << "'." << endl;
2415 context.check_layout(os);
2416 begin_inset(os, "Graphics ");
2417 os << "\n\tfilename " << name << '\n';
2418 if (opts.find("width") != opts.end())
2420 << translate_len(opts["width"]) << '\n';
2421 if (opts.find("height") != opts.end())
2423 << translate_len(opts["height"]) << '\n';
2424 if (opts.find("scale") != opts.end()) {
2425 istringstream iss(opts["scale"]);
2429 os << "\tscale " << val << '\n';
2431 if (opts.find("angle") != opts.end()) {
2432 os << "\trotateAngle "
2433 << opts["angle"] << '\n';
2434 vector<string>::const_iterator a =
2435 find(keys.begin(), keys.end(), "angle");
2436 vector<string>::const_iterator s =
2437 find(keys.begin(), keys.end(), "width");
2438 if (s == keys.end())
2439 s = find(keys.begin(), keys.end(), "height");
2440 if (s == keys.end())
2441 s = find(keys.begin(), keys.end(), "scale");
2442 if (s != keys.end() && distance(s, a) > 0)
2443 os << "\tscaleBeforeRotation\n";
2445 if (opts.find("origin") != opts.end()) {
2447 string const opt = opts["origin"];
2448 if (opt.find('l') != string::npos) ss << "left";
2449 if (opt.find('r') != string::npos) ss << "right";
2450 if (opt.find('c') != string::npos) ss << "center";
2451 if (opt.find('t') != string::npos) ss << "Top";
2452 if (opt.find('b') != string::npos) ss << "Bottom";
2453 if (opt.find('B') != string::npos) ss << "Baseline";
2454 if (!ss.str().empty())
2455 os << "\trotateOrigin " << ss.str() << '\n';
2457 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2459 if (opts.find("keepaspectratio") != opts.end())
2460 os << "\tkeepAspectRatio\n";
2461 if (opts.find("clip") != opts.end())
2463 if (opts.find("draft") != opts.end())
2465 if (opts.find("bb") != opts.end())
2466 os << "\tBoundingBox "
2467 << opts["bb"] << '\n';
2468 int numberOfbbOptions = 0;
2469 if (opts.find("bbllx") != opts.end())
2470 numberOfbbOptions++;
2471 if (opts.find("bblly") != opts.end())
2472 numberOfbbOptions++;
2473 if (opts.find("bburx") != opts.end())
2474 numberOfbbOptions++;
2475 if (opts.find("bbury") != opts.end())
2476 numberOfbbOptions++;
2477 if (numberOfbbOptions == 4)
2478 os << "\tBoundingBox "
2479 << opts["bbllx"] << " " << opts["bblly"] << " "
2480 << opts["bburx"] << " " << opts["bbury"] << '\n';
2481 else if (numberOfbbOptions > 0)
2482 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2483 numberOfbbOptions = 0;
2484 if (opts.find("natwidth") != opts.end())
2485 numberOfbbOptions++;
2486 if (opts.find("natheight") != opts.end())
2487 numberOfbbOptions++;
2488 if (numberOfbbOptions == 2)
2489 os << "\tBoundingBox 0bp 0bp "
2490 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2491 else if (numberOfbbOptions > 0)
2492 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2493 ostringstream special;
2494 if (opts.find("hiresbb") != opts.end())
2495 special << "hiresbb,";
2496 if (opts.find("trim") != opts.end())
2498 if (opts.find("viewport") != opts.end())
2499 special << "viewport=" << opts["viewport"] << ',';
2500 if (opts.find("totalheight") != opts.end())
2501 special << "totalheight=" << opts["totalheight"] << ',';
2502 if (opts.find("type") != opts.end())
2503 special << "type=" << opts["type"] << ',';
2504 if (opts.find("ext") != opts.end())
2505 special << "ext=" << opts["ext"] << ',';
2506 if (opts.find("read") != opts.end())
2507 special << "read=" << opts["read"] << ',';
2508 if (opts.find("command") != opts.end())
2509 special << "command=" << opts["command"] << ',';
2510 string s_special = special.str();
2511 if (!s_special.empty()) {
2512 // We had special arguments. Remove the trailing ','.
2513 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2515 // TODO: Handle the unknown settings better.
2516 // Warn about invalid options.
2517 // Check whether some option was given twice.
2521 else if (t.cs() == "footnote" ||
2522 (t.cs() == "thanks" && context.layout->intitle)) {
2524 context.check_layout(os);
2525 begin_inset(os, "Foot\n");
2526 os << "status collapsed\n\n";
2527 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2531 else if (t.cs() == "marginpar") {
2533 context.check_layout(os);
2534 begin_inset(os, "Marginal\n");
2535 os << "status collapsed\n\n";
2536 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2540 else if (t.cs() == "ensuremath") {
2542 context.check_layout(os);
2543 string const s = p.verbatim_item();
2544 //FIXME: this never triggers in UTF8
2545 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2548 handle_ert(os, "\\ensuremath{" + s + "}",
2552 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2553 if (title_layout_found) {
2555 skip_spaces_braces(p);
2557 handle_ert(os, t.asInput(), context);
2560 else if (t.cs() == "tableofcontents") {
2561 context.check_layout(os);
2562 begin_command_inset(os, "toc", "tableofcontents");
2564 skip_spaces_braces(p);
2567 else if (t.cs() == "listoffigures") {
2568 context.check_layout(os);
2569 begin_inset(os, "FloatList figure\n");
2571 skip_spaces_braces(p);
2574 else if (t.cs() == "listoftables") {
2575 context.check_layout(os);
2576 begin_inset(os, "FloatList table\n");
2578 skip_spaces_braces(p);
2581 else if (t.cs() == "listof") {
2582 p.skip_spaces(true);
2583 string const name = p.get_token().cs();
2584 if (context.textclass.floats().typeExist(name)) {
2585 context.check_layout(os);
2586 begin_inset(os, "FloatList ");
2589 p.get_token(); // swallow second arg
2591 handle_ert(os, "\\listof{" + name + "}", context);
2594 else if (t.cs() == "textrm")
2595 parse_text_attributes(p, os, FLAG_ITEM, outer,
2596 context, "\\family",
2597 context.font.family, "roman");
2599 else if (t.cs() == "textsf")
2600 parse_text_attributes(p, os, FLAG_ITEM, outer,
2601 context, "\\family",
2602 context.font.family, "sans");
2604 else if (t.cs() == "texttt")
2605 parse_text_attributes(p, os, FLAG_ITEM, outer,
2606 context, "\\family",
2607 context.font.family, "typewriter");
2609 else if (t.cs() == "textmd")
2610 parse_text_attributes(p, os, FLAG_ITEM, outer,
2611 context, "\\series",
2612 context.font.series, "medium");
2614 else if (t.cs() == "textbf")
2615 parse_text_attributes(p, os, FLAG_ITEM, outer,
2616 context, "\\series",
2617 context.font.series, "bold");
2619 else if (t.cs() == "textup")
2620 parse_text_attributes(p, os, FLAG_ITEM, outer,
2622 context.font.shape, "up");
2624 else if (t.cs() == "textit")
2625 parse_text_attributes(p, os, FLAG_ITEM, outer,
2627 context.font.shape, "italic");
2629 else if (t.cs() == "textsl")
2630 parse_text_attributes(p, os, FLAG_ITEM, outer,
2632 context.font.shape, "slanted");
2634 else if (t.cs() == "textsc")
2635 parse_text_attributes(p, os, FLAG_ITEM, outer,
2637 context.font.shape, "smallcaps");
2639 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2640 context.check_layout(os);
2641 TeXFont oldFont = context.font;
2642 context.font.init();
2643 context.font.size = oldFont.size;
2644 os << "\n\\family " << context.font.family << "\n";
2645 os << "\n\\series " << context.font.series << "\n";
2646 os << "\n\\shape " << context.font.shape << "\n";
2647 if (t.cs() == "textnormal") {
2648 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2649 output_font_change(os, context.font, oldFont);
2650 context.font = oldFont;
2652 eat_whitespace(p, os, context, false);
2655 else if (t.cs() == "textcolor") {
2656 // scheme is \textcolor{color name}{text}
2657 string const color = p.verbatim_item();
2658 // we only support the predefined colors of the color package
2659 if (color == "black" || color == "blue" || color == "cyan"
2660 || color == "green" || color == "magenta" || color == "red"
2661 || color == "white" || color == "yellow") {
2662 context.check_layout(os);
2663 os << "\n\\color " << color << "\n";
2664 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2665 context.check_layout(os);
2666 os << "\n\\color inherit\n";
2667 preamble.registerAutomaticallyLoadedPackage("color");
2669 // for custom defined colors
2670 handle_ert(os, t.asInput() + "{" + color + "}", context);
2673 else if (t.cs() == "underbar" || t.cs() == "uline") {
2674 // \underbar is not 100% correct (LyX outputs \uline
2675 // of ulem.sty). The difference is that \ulem allows
2676 // line breaks, and \underbar does not.
2677 // Do NOT handle \underline.
2678 // \underbar cuts through y, g, q, p etc.,
2679 // \underline does not.
2680 context.check_layout(os);
2681 os << "\n\\bar under\n";
2682 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2683 context.check_layout(os);
2684 os << "\n\\bar default\n";
2685 preamble.registerAutomaticallyLoadedPackage("ulem");
2688 else if (t.cs() == "sout") {
2689 context.check_layout(os);
2690 os << "\n\\strikeout on\n";
2691 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2692 context.check_layout(os);
2693 os << "\n\\strikeout default\n";
2694 preamble.registerAutomaticallyLoadedPackage("ulem");
2697 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
2698 t.cs() == "emph" || t.cs() == "noun") {
2699 context.check_layout(os);
2700 os << "\n\\" << t.cs() << " on\n";
2701 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2702 context.check_layout(os);
2703 os << "\n\\" << t.cs() << " default\n";
2704 if (t.cs() == "uuline" || t.cs() == "uwave")
2705 preamble.registerAutomaticallyLoadedPackage("ulem");
2708 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
2709 context.check_layout(os);
2710 string name = p.getArg('{', '}');
2711 string localtime = p.getArg('{', '}');
2712 preamble.registerAuthor(name);
2713 Author const & author = preamble.getAuthor(name);
2714 // from_ctime() will fail if LyX decides to output the
2715 // time in the text language. It might also use a wrong
2716 // time zone (if the original LyX document was exported
2717 // with a different time zone).
2718 time_t ptime = from_ctime(localtime);
2719 if (ptime == static_cast<time_t>(-1)) {
2720 cerr << "Warning: Could not parse time `" << localtime
2721 << "´ for change tracking, using current time instead.\n";
2722 ptime = current_time();
2724 if (t.cs() == "lyxadded")
2725 os << "\n\\change_inserted ";
2727 os << "\n\\change_deleted ";
2728 os << author.bufferId() << ' ' << ptime << '\n';
2729 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2730 bool dvipost = LaTeXPackages::isAvailable("dvipost");
2731 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
2732 LaTeXPackages::isAvailable("xcolor");
2733 // No need to test for luatex, since luatex comes in
2734 // two flavours (dvi and pdf), like latex, and those
2735 // are detected by pdflatex.
2736 if (pdflatex || xetex) {
2738 preamble.registerAutomaticallyLoadedPackage("ulem");
2739 preamble.registerAutomaticallyLoadedPackage("xcolor");
2740 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
2744 preamble.registerAutomaticallyLoadedPackage("dvipost");
2745 } else if (xcolorulem) {
2746 preamble.registerAutomaticallyLoadedPackage("ulem");
2747 preamble.registerAutomaticallyLoadedPackage("xcolor");
2752 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
2753 t.cs() == "vphantom") {
2754 context.check_layout(os);
2755 if (t.cs() == "phantom")
2756 begin_inset(os, "Phantom Phantom\n");
2757 if (t.cs() == "hphantom")
2758 begin_inset(os, "Phantom HPhantom\n");
2759 if (t.cs() == "vphantom")
2760 begin_inset(os, "Phantom VPhantom\n");
2761 os << "status open\n";
2762 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
2767 else if (t.cs() == "href") {
2768 context.check_layout(os);
2769 string target = p.getArg('{', '}');
2770 string name = p.getArg('{', '}');
2772 size_t i = target.find(':');
2773 if (i != string::npos) {
2774 type = target.substr(0, i + 1);
2775 if (type == "mailto:" || type == "file:")
2776 target = target.substr(i + 1);
2777 // handle the case that name is equal to target, except of "http://"
2778 else if (target.substr(i + 3) == name && type == "http:")
2781 begin_command_inset(os, "href", "href");
2783 os << "name \"" << name << "\"\n";
2784 os << "target \"" << target << "\"\n";
2785 if (type == "mailto:" || type == "file:")
2786 os << "type \"" << type << "\"\n";
2788 skip_spaces_braces(p);
2791 else if (t.cs() == "lyxline") {
2792 // swallow size argument (it is not used anyway)
2794 if (!context.atParagraphStart()) {
2795 // so our line is in the middle of a paragraph
2796 // we need to add a new line, lest this line
2797 // follow the other content on that line and
2798 // run off the side of the page
2799 // FIXME: This may create an empty paragraph,
2800 // but without that it would not be
2801 // possible to set noindent below.
2802 // Fortunately LaTeX does not care
2803 // about the empty paragraph.
2804 context.new_paragraph(os);
2806 if (preamble.indentParagraphs()) {
2807 // we need to unindent, lest the line be too long
2808 context.add_par_extra_stuff("\\noindent\n");
2810 context.check_layout(os);
2811 begin_command_inset(os, "line", "rule");
2812 os << "offset \"0.5ex\"\n"
2813 "width \"100line%\"\n"
2818 else if (t.cs() == "rule") {
2819 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
2820 string const width = p.getArg('{', '}');
2821 string const thickness = p.getArg('{', '}');
2822 context.check_layout(os);
2823 begin_command_inset(os, "line", "rule");
2824 if (!offset.empty())
2825 os << "offset \"" << translate_len(offset) << "\"\n";
2826 os << "width \"" << translate_len(width) << "\"\n"
2827 "height \"" << translate_len(thickness) << "\"\n";
2831 else if (is_known(t.cs(), known_phrases) ||
2832 (t.cs() == "protect" &&
2833 p.next_token().cat() == catEscape &&
2834 is_known(p.next_token().cs(), known_phrases))) {
2835 // LyX sometimes puts a \protect in front, so we have to ignore it
2836 // FIXME: This needs to be changed when bug 4752 is fixed.
2837 char const * const * where = is_known(
2838 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
2840 context.check_layout(os);
2841 os << known_coded_phrases[where - known_phrases];
2842 skip_spaces_braces(p);
2845 else if (is_known(t.cs(), known_ref_commands)) {
2846 string const opt = p.getOpt();
2848 context.check_layout(os);
2849 char const * const * where = is_known(t.cs(),
2850 known_ref_commands);
2851 begin_command_inset(os, "ref",
2852 known_coded_ref_commands[where - known_ref_commands]);
2853 os << "reference \""
2854 << convert_command_inset_arg(p.verbatim_item())
2858 // LyX does not support optional arguments of ref commands
2859 handle_ert(os, t.asInput() + '[' + opt + "]{" +
2860 p.verbatim_item() + "}", context);
2864 else if (use_natbib &&
2865 is_known(t.cs(), known_natbib_commands) &&
2866 ((t.cs() != "citefullauthor" &&
2867 t.cs() != "citeyear" &&
2868 t.cs() != "citeyearpar") ||
2869 p.next_token().asInput() != "*")) {
2870 context.check_layout(os);
2871 string command = t.cs();
2872 if (p.next_token().asInput() == "*") {
2876 if (command == "citefullauthor")
2877 // alternative name for "\\citeauthor*"
2878 command = "citeauthor*";
2880 // text before the citation
2882 // text after the citation
2884 get_cite_arguments(p, true, before, after);
2886 if (command == "cite") {
2887 // \cite without optional argument means
2888 // \citet, \cite with at least one optional
2889 // argument means \citep.
2890 if (before.empty() && after.empty())
2895 if (before.empty() && after == "[]")
2896 // avoid \citet[]{a}
2898 else if (before == "[]" && after == "[]") {
2899 // avoid \citet[][]{a}
2903 // remove the brackets around after and before
2904 if (!after.empty()) {
2906 after.erase(after.length() - 1, 1);
2907 after = convert_command_inset_arg(after);
2909 if (!before.empty()) {
2911 before.erase(before.length() - 1, 1);
2912 before = convert_command_inset_arg(before);
2914 begin_command_inset(os, "citation", command);
2915 os << "after " << '"' << after << '"' << "\n";
2916 os << "before " << '"' << before << '"' << "\n";
2918 << convert_command_inset_arg(p.verbatim_item())
2923 else if (use_jurabib &&
2924 is_known(t.cs(), known_jurabib_commands) &&
2925 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
2926 context.check_layout(os);
2927 string command = t.cs();
2928 if (p.next_token().asInput() == "*") {
2932 char argumentOrder = '\0';
2933 vector<string> const options =
2934 preamble.getPackageOptions("jurabib");
2935 if (find(options.begin(), options.end(),
2936 "natbiborder") != options.end())
2937 argumentOrder = 'n';
2938 else if (find(options.begin(), options.end(),
2939 "jurabiborder") != options.end())
2940 argumentOrder = 'j';
2942 // text before the citation
2944 // text after the citation
2946 get_cite_arguments(p, argumentOrder != 'j', before, after);
2948 string const citation = p.verbatim_item();
2949 if (!before.empty() && argumentOrder == '\0') {
2950 cerr << "Warning: Assuming argument order "
2951 "of jurabib version 0.6 for\n'"
2952 << command << before << after << '{'
2953 << citation << "}'.\n"
2954 "Add 'jurabiborder' to the jurabib "
2955 "package options if you used an\n"
2956 "earlier jurabib version." << endl;
2958 if (!after.empty()) {
2960 after.erase(after.length() - 1, 1);
2962 if (!before.empty()) {
2964 before.erase(before.length() - 1, 1);
2966 begin_command_inset(os, "citation", command);
2967 os << "after " << '"' << after << '"' << "\n";
2968 os << "before " << '"' << before << '"' << "\n";
2969 os << "key " << '"' << citation << '"' << "\n";
2973 else if (t.cs() == "cite"
2974 || t.cs() == "nocite") {
2975 context.check_layout(os);
2976 string after = convert_command_inset_arg(p.getArg('[', ']'));
2977 string key = convert_command_inset_arg(p.verbatim_item());
2978 // store the case that it is "\nocite{*}" to use it later for
2981 begin_command_inset(os, "citation", t.cs());
2982 os << "after " << '"' << after << '"' << "\n";
2983 os << "key " << '"' << key << '"' << "\n";
2985 } else if (t.cs() == "nocite")
2989 else if (t.cs() == "index") {
2990 context.check_layout(os);
2991 begin_inset(os, "Index idx\n");
2992 os << "status collapsed\n";
2993 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
2997 else if (t.cs() == "nomenclature") {
2998 context.check_layout(os);
2999 begin_command_inset(os, "nomenclature", "nomenclature");
3000 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3001 if (!prefix.empty())
3002 os << "prefix " << '"' << prefix << '"' << "\n";
3003 os << "symbol " << '"'
3004 << convert_command_inset_arg(p.verbatim_item());
3005 os << "\"\ndescription \""
3006 << convert_command_inset_arg(p.verbatim_item())
3011 else if (t.cs() == "label") {
3012 context.check_layout(os);
3013 begin_command_inset(os, "label", "label");
3015 << convert_command_inset_arg(p.verbatim_item())
3020 else if (t.cs() == "printindex") {
3021 context.check_layout(os);
3022 begin_command_inset(os, "index_print", "printindex");
3023 os << "type \"idx\"\n";
3025 skip_spaces_braces(p);
3028 else if (t.cs() == "printnomenclature") {
3030 string width_type = "";
3031 context.check_layout(os);
3032 begin_command_inset(os, "nomencl_print", "printnomenclature");
3033 // case of a custom width
3035 width = p.getArg('[', ']');
3036 width = translate_len(width);
3037 width_type = "custom";
3039 // case of no custom width
3040 // the case of no custom width but the width set
3041 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3042 // because the user could have set anything, not only the width
3043 // of the longest label (which would be width_type = "auto")
3044 string label = convert_command_inset_arg(p.getArg('{', '}'));
3045 if (label.empty() && width_type.empty())
3046 width_type = "none";
3047 os << "set_width \"" << width_type << "\"\n";
3048 if (width_type == "custom")
3049 os << "width \"" << width << '\"';
3051 skip_spaces_braces(p);
3054 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3055 context.check_layout(os);
3056 begin_inset(os, "script ");
3057 os << t.cs().substr(4) << '\n';
3058 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3060 if (t.cs() == "textsubscript")
3061 preamble.registerAutomaticallyLoadedPackage("subscript");
3064 else if (is_known(t.cs(), known_quotes)) {
3065 char const * const * where = is_known(t.cs(), known_quotes);
3066 context.check_layout(os);
3067 begin_inset(os, "Quotes ");
3068 os << known_coded_quotes[where - known_quotes];
3070 // LyX adds {} after the quote, so we have to eat
3071 // spaces here if there are any before a possible
3073 eat_whitespace(p, os, context, false);
3077 else if (is_known(t.cs(), known_sizes) &&
3078 context.new_layout_allowed) {
3079 char const * const * where = is_known(t.cs(), known_sizes);
3080 context.check_layout(os);
3081 TeXFont const oldFont = context.font;
3082 context.font.size = known_coded_sizes[where - known_sizes];
3083 output_font_change(os, oldFont, context.font);
3084 eat_whitespace(p, os, context, false);
3087 else if (is_known(t.cs(), known_font_families) &&
3088 context.new_layout_allowed) {
3089 char const * const * where =
3090 is_known(t.cs(), known_font_families);
3091 context.check_layout(os);
3092 TeXFont const oldFont = context.font;
3093 context.font.family =
3094 known_coded_font_families[where - known_font_families];
3095 output_font_change(os, oldFont, context.font);
3096 eat_whitespace(p, os, context, false);
3099 else if (is_known(t.cs(), known_font_series) &&
3100 context.new_layout_allowed) {
3101 char const * const * where =
3102 is_known(t.cs(), known_font_series);
3103 context.check_layout(os);
3104 TeXFont const oldFont = context.font;
3105 context.font.series =
3106 known_coded_font_series[where - known_font_series];
3107 output_font_change(os, oldFont, context.font);
3108 eat_whitespace(p, os, context, false);
3111 else if (is_known(t.cs(), known_font_shapes) &&
3112 context.new_layout_allowed) {
3113 char const * const * where =
3114 is_known(t.cs(), known_font_shapes);
3115 context.check_layout(os);
3116 TeXFont const oldFont = context.font;
3117 context.font.shape =
3118 known_coded_font_shapes[where - known_font_shapes];
3119 output_font_change(os, oldFont, context.font);
3120 eat_whitespace(p, os, context, false);
3122 else if (is_known(t.cs(), known_old_font_families) &&
3123 context.new_layout_allowed) {
3124 char const * const * where =
3125 is_known(t.cs(), known_old_font_families);
3126 context.check_layout(os);
3127 TeXFont const oldFont = context.font;
3128 context.font.init();
3129 context.font.size = oldFont.size;
3130 context.font.family =
3131 known_coded_font_families[where - known_old_font_families];
3132 output_font_change(os, oldFont, context.font);
3133 eat_whitespace(p, os, context, false);
3136 else if (is_known(t.cs(), known_old_font_series) &&
3137 context.new_layout_allowed) {
3138 char const * const * where =
3139 is_known(t.cs(), known_old_font_series);
3140 context.check_layout(os);
3141 TeXFont const oldFont = context.font;
3142 context.font.init();
3143 context.font.size = oldFont.size;
3144 context.font.series =
3145 known_coded_font_series[where - known_old_font_series];
3146 output_font_change(os, oldFont, context.font);
3147 eat_whitespace(p, os, context, false);
3150 else if (is_known(t.cs(), known_old_font_shapes) &&
3151 context.new_layout_allowed) {
3152 char const * const * where =
3153 is_known(t.cs(), known_old_font_shapes);
3154 context.check_layout(os);
3155 TeXFont const oldFont = context.font;
3156 context.font.init();
3157 context.font.size = oldFont.size;
3158 context.font.shape =
3159 known_coded_font_shapes[where - known_old_font_shapes];
3160 output_font_change(os, oldFont, context.font);
3161 eat_whitespace(p, os, context, false);
3164 else if (t.cs() == "selectlanguage") {
3165 context.check_layout(os);
3166 // save the language for the case that a
3167 // \foreignlanguage is used
3169 context.font.language = babel2lyx(p.verbatim_item());
3170 os << "\n\\lang " << context.font.language << "\n";
3173 else if (t.cs() == "foreignlanguage") {
3174 string const lang = babel2lyx(p.verbatim_item());
3175 parse_text_attributes(p, os, FLAG_ITEM, outer,
3177 context.font.language, lang);
3180 else if (t.cs() == "inputencoding") {
3181 // nothing to write here
3182 string const enc = subst(p.verbatim_item(), "\n", " ");
3186 else if (t.cs() == "ldots") {
3187 context.check_layout(os);
3188 os << "\\SpecialChar \\ldots{}\n";
3189 skip_spaces_braces(p);
3192 else if (t.cs() == "lyxarrow") {
3193 context.check_layout(os);
3194 os << "\\SpecialChar \\menuseparator\n";
3195 skip_spaces_braces(p);
3198 else if (t.cs() == "textcompwordmark") {
3199 context.check_layout(os);
3200 os << "\\SpecialChar \\textcompwordmark{}\n";
3201 skip_spaces_braces(p);
3204 else if (t.cs() == "slash") {
3205 context.check_layout(os);
3206 os << "\\SpecialChar \\slash{}\n";
3207 skip_spaces_braces(p);
3210 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3211 context.check_layout(os);
3212 os << "\\SpecialChar \\nobreakdash-\n";
3216 else if (t.cs() == "textquotedbl") {
3217 context.check_layout(os);
3222 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3223 context.check_layout(os);
3224 os << "\\SpecialChar \\@.\n";
3228 else if (t.cs() == "-") {
3229 context.check_layout(os);
3230 os << "\\SpecialChar \\-\n";
3233 else if (t.cs() == "textasciitilde") {
3234 context.check_layout(os);
3236 skip_spaces_braces(p);
3239 else if (t.cs() == "textasciicircum") {
3240 context.check_layout(os);
3242 skip_spaces_braces(p);
3245 else if (t.cs() == "textbackslash") {
3246 context.check_layout(os);
3247 os << "\n\\backslash\n";
3248 skip_spaces_braces(p);
3251 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3252 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3254 context.check_layout(os);
3258 else if (t.cs() == "char") {
3259 context.check_layout(os);
3260 if (p.next_token().character() == '`') {
3262 if (p.next_token().cs() == "\"") {
3267 handle_ert(os, "\\char`", context);
3270 handle_ert(os, "\\char", context);
3274 else if (t.cs() == "verb") {
3275 context.check_layout(os);
3276 char const delimiter = p.next_token().character();
3277 string const arg = p.getArg(delimiter, delimiter);
3279 oss << "\\verb" << delimiter << arg << delimiter;
3280 handle_ert(os, oss.str(), context);
3283 // Problem: \= creates a tabstop inside the tabbing environment
3284 // and else an accent. In the latter case we really would want
3285 // \={o} instead of \= o.
3286 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3287 handle_ert(os, t.asInput(), context);
3289 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3290 else if (t.cs().size() == 1
3291 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3292 context.check_layout(os);
3293 // try to see whether the string is in unicodesymbols
3295 string command = t.asInput() + "{"
3296 + trimSpaceAndEol(p.verbatim_item())
3298 docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
3301 cerr << "When parsing " << command
3302 << ", result is " << to_utf8(s)
3303 << "+" << to_utf8(rem) << endl;
3306 // we did not find a non-ert version
3307 handle_ert(os, command, context);
3310 else if (t.cs() == "\\") {
3311 context.check_layout(os);
3313 handle_ert(os, "\\\\" + p.getOpt(), context);
3314 else if (p.next_token().asInput() == "*") {
3316 // getOpt() eats the following space if there
3317 // is no optional argument, but that is OK
3318 // here since it has no effect in the output.
3319 handle_ert(os, "\\\\*" + p.getOpt(), context);
3322 begin_inset(os, "Newline newline");
3327 else if (t.cs() == "newline" ||
3328 (t.cs() == "linebreak" && !p.hasOpt())) {
3329 context.check_layout(os);
3330 begin_inset(os, "Newline ");
3333 skip_spaces_braces(p);
3336 else if (t.cs() == "input" || t.cs() == "include"
3337 || t.cs() == "verbatiminput") {
3338 string name = t.cs();
3339 if (t.cs() == "verbatiminput"
3340 && p.next_token().asInput() == "*")
3341 name += p.get_token().asInput();
3342 context.check_layout(os);
3343 string filename(normalize_filename(p.getArg('{', '}')));
3344 string const path = getMasterFilePath();
3345 // We want to preserve relative / absolute filenames,
3346 // therefore path is only used for testing
3347 if ((t.cs() == "include" || t.cs() == "input") &&
3348 !makeAbsPath(filename, path).exists()) {
3349 // The file extension is probably missing.
3350 // Now try to find it out.
3351 string const tex_name =
3352 find_file(filename, path,
3353 known_tex_extensions);
3354 if (!tex_name.empty())
3355 filename = tex_name;
3357 bool external = false;
3359 if (makeAbsPath(filename, path).exists()) {
3360 string const abstexname =
3361 makeAbsPath(filename, path).absFileName();
3362 string const abslyxname =
3363 changeExtension(abstexname, ".lyx");
3364 string const absfigname =
3365 changeExtension(abstexname, ".fig");
3366 fix_relative_filename(filename);
3367 string const lyxname =
3368 changeExtension(filename, ".lyx");
3370 external = FileName(absfigname).exists();
3371 if (t.cs() == "input") {
3372 string const ext = getExtension(abstexname);
3374 // Combined PS/LaTeX:
3375 // x.eps, x.pstex_t (old xfig)
3376 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3377 FileName const absepsname(
3378 changeExtension(abstexname, ".eps"));
3379 FileName const abspstexname(
3380 changeExtension(abstexname, ".pstex"));
3381 bool const xfigeps =
3382 (absepsname.exists() ||
3383 abspstexname.exists()) &&
3386 // Combined PDF/LaTeX:
3387 // x.pdf, x.pdftex_t (old xfig)
3388 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3389 FileName const abspdfname(
3390 changeExtension(abstexname, ".pdf"));
3391 bool const xfigpdf =
3392 abspdfname.exists() &&
3393 (ext == "pdftex_t" || ext == "pdf_t");
3397 // Combined PS/PDF/LaTeX:
3398 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3399 string const absbase2(
3400 removeExtension(abstexname) + "_pspdftex");
3401 FileName const abseps2name(
3402 addExtension(absbase2, ".eps"));
3403 FileName const abspdf2name(
3404 addExtension(absbase2, ".pdf"));
3405 bool const xfigboth =
3406 abspdf2name.exists() &&
3407 abseps2name.exists() && ext == "pspdftex";
3409 xfig = xfigpdf || xfigeps || xfigboth;
3410 external = external && xfig;
3413 outname = changeExtension(filename, ".fig");
3415 // Don't try to convert, the result
3416 // would be full of ERT.
3418 } else if (t.cs() != "verbatiminput" &&
3419 tex2lyx(abstexname, FileName(abslyxname),
3426 cerr << "Warning: Could not find included file '"
3427 << filename << "'." << endl;
3431 begin_inset(os, "External\n");
3432 os << "\ttemplate XFig\n"
3433 << "\tfilename " << outname << '\n';
3435 begin_command_inset(os, "include", name);
3436 os << "preview false\n"
3437 "filename \"" << outname << "\"\n";
3442 else if (t.cs() == "bibliographystyle") {
3443 // store new bibliographystyle
3444 bibliographystyle = p.verbatim_item();
3445 // If any other command than \bibliography and
3446 // \nocite{*} follows, we need to output the style
3447 // (because it might be used by that command).
3448 // Otherwise, it will automatically be output by LyX.
3451 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3452 if (t2.cat() == catBegin)
3454 if (t2.cat() != catEscape)
3456 if (t2.cs() == "nocite") {
3457 if (p.getArg('{', '}') == "*")
3459 } else if (t2.cs() == "bibliography")
3466 "\\bibliographystyle{" + bibliographystyle + '}',
3471 else if (t.cs() == "bibliography") {
3472 context.check_layout(os);
3473 begin_command_inset(os, "bibtex", "bibtex");
3474 if (!btprint.empty()) {
3475 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3476 // clear the string because the next BibTeX inset can be without the
3477 // \nocite{*} option
3480 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3481 // Do we have a bibliographystyle set?
3482 if (!bibliographystyle.empty())
3483 os << "options " << '"' << bibliographystyle << '"' << "\n";
3487 else if (t.cs() == "parbox") {
3488 // Test whether this is an outer box of a shaded box
3490 // swallow arguments
3491 while (p.hasOpt()) {
3493 p.skip_spaces(true);
3496 p.skip_spaces(true);
3498 if (p.next_token().cat() == catBegin)
3500 p.skip_spaces(true);
3501 Token to = p.get_token();
3502 bool shaded = false;
3503 if (to.asInput() == "\\begin") {
3504 p.skip_spaces(true);
3505 if (p.getArg('{', '}') == "shaded")
3510 parse_outer_box(p, os, FLAG_ITEM, outer,
3511 context, "parbox", "shaded");
3513 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3517 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3518 t.cs() == "shadowbox" || t.cs() == "doublebox")
3519 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3521 else if (t.cs() == "framebox") {
3522 string special = p.getFullOpt();
3523 special += p.getOpt();
3524 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), special);
3527 //\makebox() is part of the picture environment and different from \makebox{}
3528 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
3529 else if (t.cs() == "makebox") {
3530 string arg = t.asInput();
3531 if (p.next_token().character() == '(')
3532 //the syntax is: \makebox(x,y)[position]{content}
3533 arg += p.getFullParentheseArg();
3535 //the syntax is: \makebox[width][position]{content}
3536 arg += p.getFullOpt();
3537 handle_ert(os, arg + p.getFullOpt(), context);
3540 else if (t.cs() == "smallskip" ||
3541 t.cs() == "medskip" ||
3542 t.cs() == "bigskip" ||
3543 t.cs() == "vfill") {
3544 context.check_layout(os);
3545 begin_inset(os, "VSpace ");
3548 skip_spaces_braces(p);
3551 else if (is_known(t.cs(), known_spaces)) {
3552 char const * const * where = is_known(t.cs(), known_spaces);
3553 context.check_layout(os);
3554 begin_inset(os, "space ");
3555 os << '\\' << known_coded_spaces[where - known_spaces]
3558 // LaTeX swallows whitespace after all spaces except
3559 // "\\,". We have to do that here, too, because LyX
3560 // adds "{}" which would make the spaces significant.
3562 eat_whitespace(p, os, context, false);
3563 // LyX adds "{}" after all spaces except "\\ " and
3564 // "\\,", so we have to remove "{}".
3565 // "\\,{}" is equivalent to "\\," in LaTeX, so we
3566 // remove the braces after "\\,", too.
3571 else if (t.cs() == "newpage" ||
3572 (t.cs() == "pagebreak" && !p.hasOpt()) ||
3573 t.cs() == "clearpage" ||
3574 t.cs() == "cleardoublepage") {
3575 context.check_layout(os);
3576 begin_inset(os, "Newpage ");
3579 skip_spaces_braces(p);
3582 else if (t.cs() == "DeclareRobustCommand" ||
3583 t.cs() == "DeclareRobustCommandx" ||
3584 t.cs() == "newcommand" ||
3585 t.cs() == "newcommandx" ||
3586 t.cs() == "providecommand" ||
3587 t.cs() == "providecommandx" ||
3588 t.cs() == "renewcommand" ||
3589 t.cs() == "renewcommandx") {
3590 // DeclareRobustCommand, DeclareRobustCommandx,
3591 // providecommand and providecommandx could be handled
3592 // by parse_command(), but we need to call
3593 // add_known_command() here.
3594 string name = t.asInput();
3595 if (p.next_token().asInput() == "*") {
3596 // Starred form. Eat '*'
3600 string const command = p.verbatim_item();
3601 string const opt1 = p.getFullOpt();
3602 string const opt2 = p.getFullOpt();
3603 add_known_command(command, opt1, !opt2.empty());
3604 string const ert = name + '{' + command + '}' +
3606 '{' + p.verbatim_item() + '}';
3608 if (t.cs() == "DeclareRobustCommand" ||
3609 t.cs() == "DeclareRobustCommandx" ||
3610 t.cs() == "providecommand" ||
3611 t.cs() == "providecommandx" ||
3612 name[name.length()-1] == '*')
3613 handle_ert(os, ert, context);
3615 context.check_layout(os);
3616 begin_inset(os, "FormulaMacro");
3622 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3623 // let could be handled by parse_command(),
3624 // but we need to call add_known_command() here.
3625 string ert = t.asInput();
3628 if (p.next_token().cat() == catBegin) {
3629 name = p.verbatim_item();
3630 ert += '{' + name + '}';
3632 name = p.verbatim_item();
3637 if (p.next_token().cat() == catBegin) {
3638 command = p.verbatim_item();
3639 ert += '{' + command + '}';
3641 command = p.verbatim_item();
3644 // If command is known, make name known too, to parse
3645 // its arguments correctly. For this reason we also
3646 // have commands in syntax.default that are hardcoded.
3647 CommandMap::iterator it = known_commands.find(command);
3648 if (it != known_commands.end())
3649 known_commands[t.asInput()] = it->second;
3650 handle_ert(os, ert, context);
3653 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3654 bool starred = false;
3655 if (p.next_token().asInput() == "*") {
3659 string name = t.asInput();
3660 string const length = p.verbatim_item();
3663 bool valid = splitLatexLength(length, valstring, unit);
3664 bool known_hspace = false;
3665 bool known_vspace = false;
3666 bool known_unit = false;
3669 istringstream iss(valstring);
3672 if (t.cs()[0] == 'h') {
3673 if (unit == "\\fill") {
3678 known_hspace = true;
3681 if (unit == "\\smallskipamount") {
3683 known_vspace = true;
3684 } else if (unit == "\\medskipamount") {
3686 known_vspace = true;
3687 } else if (unit == "\\bigskipamount") {
3689 known_vspace = true;
3690 } else if (unit == "\\fill") {
3692 known_vspace = true;
3696 if (!known_hspace && !known_vspace) {
3697 switch (unitFromString(unit)) {
3718 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3719 // Literal horizontal length or known variable
3720 context.check_layout(os);
3721 begin_inset(os, "space ");
3729 if (known_unit && !known_hspace)
3731 << translate_len(length);
3733 } else if (known_unit || known_vspace) {
3734 // Literal vertical length or known variable
3735 context.check_layout(os);
3736 begin_inset(os, "VSpace ");
3744 // LyX can't handle other length variables in Inset VSpace/space
3749 handle_ert(os, name + '{' + unit + '}', context);
3750 else if (value == -1.0)
3751 handle_ert(os, name + "{-" + unit + '}', context);
3753 handle_ert(os, name + '{' + valstring + unit + '}', context);
3755 handle_ert(os, name + '{' + length + '}', context);
3759 // The single '=' is meant here.
3760 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3762 context.check_layout(os);
3763 begin_inset(os, "Flex ");
3764 os << to_utf8(newinsetlayout->name()) << '\n'
3765 << "status collapsed\n";
3766 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3771 // try to see whether the string is in unicodesymbols
3772 // Only use text mode commands, since we are in text mode here,
3773 // and math commands may be invalid (bug 6797)
3775 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
3776 rem, Encodings::TEXT_CMD);
3779 cerr << "When parsing " << t.cs()
3780 << ", result is " << to_utf8(s)
3781 << "+" << to_utf8(rem) << endl;
3782 context.check_layout(os);
3784 skip_spaces_braces(p);
3786 //cerr << "#: " << t << " mode: " << mode << endl;
3787 // heuristic: read up to next non-nested space
3789 string s = t.asInput();
3790 string z = p.verbatim_item();
3791 while (p.good() && z != " " && z.size()) {
3792 //cerr << "read: " << z << endl;
3794 z = p.verbatim_item();
3796 cerr << "found ERT: " << s << endl;
3797 handle_ert(os, s + ' ', context);
3800 string name = t.asInput();
3801 if (p.next_token().asInput() == "*") {
3802 // Starred commands like \vspace*{}
3803 p.get_token(); // Eat '*'
3806 if (!parse_command(name, p, os, outer, context))
3807 handle_ert(os, name, context);
3811 if (flags & FLAG_LEAVE) {
3812 flags &= ~FLAG_LEAVE;