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"
26 #include "support/lassert.h"
27 #include "support/convert.h"
28 #include "support/FileName.h"
29 #include "support/filetools.h"
30 #include "support/lstrings.h"
39 using namespace lyx::support;
44 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
45 Context const & context, InsetLayout const * layout)
47 bool const forcePlainLayout =
48 layout ? layout->forcePlainLayout() : false;
49 Context newcontext(true, context.textclass);
51 newcontext.layout = &context.textclass.plainLayout();
53 newcontext.font = context.font;
54 parse_text(p, os, flags, outer, newcontext);
55 newcontext.check_end_layout(os);
61 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
62 Context const & context, string const & name)
64 InsetLayout const * layout = 0;
65 DocumentClass::InsetLayouts::const_iterator it =
66 context.textclass.insetLayouts().find(from_ascii(name));
67 if (it != context.textclass.insetLayouts().end())
68 layout = &(it->second);
69 parse_text_in_inset(p, os, flags, outer, context, layout);
72 /// parses a paragraph snippet, useful for example for \\emph{...}
73 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
76 Context newcontext(context);
77 // Don't inherit the paragraph-level extra stuff
78 newcontext.par_extra_stuff.clear();
79 parse_text(p, os, flags, outer, newcontext);
80 // Make sure that we don't create invalid .lyx files
81 context.need_layout = newcontext.need_layout;
82 context.need_end_layout = newcontext.need_end_layout;
87 * Thin wrapper around parse_text_snippet() using a string.
89 * We completely ignore \c context.need_layout and \c context.need_end_layout,
90 * because our return value is not used directly (otherwise the stream version
91 * of parse_text_snippet() could be used). That means that the caller needs
92 * to do layout management manually.
93 * This is intended to parse text that does not create any layout changes.
95 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
98 Context newcontext(context);
99 newcontext.need_layout = false;
100 newcontext.need_end_layout = false;
101 newcontext.new_layout_allowed = false;
102 // Avoid warning by Context::~Context()
103 newcontext.par_extra_stuff.clear();
105 parse_text_snippet(p, os, flags, outer, newcontext);
110 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
111 "vpageref", "prettyref", "eqref", 0 };
113 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
114 "vpageref", "formatted", "eqref", 0 };
118 * The starred forms are also known except for "citefullauthor",
119 * "citeyear" and "citeyearpar".
121 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
122 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
123 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
127 * No starred form other than "cite*" known.
129 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
130 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
131 // jurabib commands not (yet) supported by LyX:
133 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
134 // "footciteauthor", "footciteyear", "footciteyearpar",
135 "citefield", "citetitle", 0 };
137 /// LaTeX names for quotes
138 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
139 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
140 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
141 "guilsinglleft", "frq", "guilsinglright", 0};
143 /// the same as known_quotes with .lyx names
144 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
145 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
146 "gld", "grd", "gls", "ers", "fls",
147 "fls", "frs", "frs", 0};
149 /// LaTeX names for font sizes
150 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
151 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
153 /// the same as known_sizes with .lyx names
154 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
155 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
157 /// LaTeX 2.09 names for font families
158 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
160 /// LaTeX names for font families
161 char const * const known_font_families[] = { "rmfamily", "sffamily",
164 /// the same as known_old_font_families and known_font_families with .lyx names
165 char const * const known_coded_font_families[] = { "roman", "sans",
168 /// LaTeX 2.09 names for font series
169 char const * const known_old_font_series[] = { "bf", 0};
171 /// LaTeX names for font series
172 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
174 /// the same as known_old_font_series and known_font_series with .lyx names
175 char const * const known_coded_font_series[] = { "bold", "medium", 0};
177 /// LaTeX 2.09 names for font shapes
178 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
180 /// LaTeX names for font shapes
181 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
184 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
185 char const * const known_coded_font_shapes[] = { "italic", "slanted",
186 "smallcaps", "up", 0};
189 * Graphics file extensions known by the dvips driver of the graphics package.
190 * These extensions are used to complete the filename of an included
191 * graphics file if it does not contain an extension.
192 * The order must be the same that latex uses to find a file, because we
193 * will use the first extension that matches.
194 * This is only an approximation for the common cases. If we would want to
195 * do it right in all cases, we would need to know which graphics driver is
196 * used and know the extensions of every driver of the graphics package.
198 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
199 "ps.gz", "eps.Z", "ps.Z", 0};
202 * Graphics file extensions known by the pdftex driver of the graphics package.
203 * \sa known_dvips_graphics_formats
205 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
209 * Known file extensions for TeX files as used by \\include.
211 char const * const known_tex_extensions[] = {"tex", 0};
213 /// spaces known by InsetSpace
214 char const * const known_spaces[] = { " ", "space", ",",
215 "thinspace", "quad", "qquad", "enspace", "enskip",
216 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
217 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
218 "upbracefill", "downbracefill", 0};
220 /// the same as known_spaces with .lyx names
221 char const * const known_coded_spaces[] = { "space{}", "space{}",
222 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
223 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
224 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
225 "upbracefill{}", "downbracefill{}", 0};
227 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
228 /// them in ERT. "LaTeXe" must come before "LaTeX"!
229 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
230 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
231 int const known_phrase_lengths[] = {3, 5, 7, 0};
233 // string to store the float type to be able to determine the type of subfloats
234 string float_type = "";
237 /// splits "x=z, y=b" into a map and an ordered keyword vector
238 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
243 keys.resize(v.size());
244 for (size_t i = 0; i < v.size(); ++i) {
245 size_t const pos = v[i].find('=');
246 string const index = trimSpaceAndEol(v[i].substr(0, pos));
247 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
255 * Split a LaTeX length into value and unit.
256 * The latter can be a real unit like "pt", or a latex length variable
257 * like "\textwidth". The unit may contain additional stuff like glue
258 * lengths, but we don't care, because such lengths are ERT anyway.
259 * \returns true if \p value and \p unit are valid.
261 bool splitLatexLength(string const & len, string & value, string & unit)
265 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
266 //'4,5' is a valid LaTeX length number. Change it to '4.5'
267 string const length = subst(len, ',', '.');
268 if (i == string::npos)
271 if (len[0] == '\\') {
272 // We had something like \textwidth without a factor
278 value = trimSpaceAndEol(string(length, 0, i));
282 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
283 if (contains(len, '\\'))
284 unit = trimSpaceAndEol(string(len, i));
286 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
291 /// A simple function to translate a latex length to something LyX can
292 /// understand. Not perfect, but rather best-effort.
293 bool translate_len(string const & length, string & valstring, string & unit)
295 if (!splitLatexLength(length, valstring, unit))
297 // LyX uses percent values
299 istringstream iss(valstring);
304 string const percentval = oss.str();
306 if (unit.empty() || unit[0] != '\\')
308 string::size_type const i = unit.find(' ');
309 string const endlen = (i == string::npos) ? string() : string(unit, i);
310 if (unit == "\\textwidth") {
311 valstring = percentval;
312 unit = "text%" + endlen;
313 } else if (unit == "\\columnwidth") {
314 valstring = percentval;
315 unit = "col%" + endlen;
316 } else if (unit == "\\paperwidth") {
317 valstring = percentval;
318 unit = "page%" + endlen;
319 } else if (unit == "\\linewidth") {
320 valstring = percentval;
321 unit = "line%" + endlen;
322 } else if (unit == "\\paperheight") {
323 valstring = percentval;
324 unit = "pheight%" + endlen;
325 } else if (unit == "\\textheight") {
326 valstring = percentval;
327 unit = "theight%" + endlen;
335 string translate_len(string const & length)
339 if (translate_len(length, value, unit))
341 // If the input is invalid, return what we have.
349 * Translates a LaTeX length into \p value, \p unit and
350 * \p special parts suitable for a box inset.
351 * The difference from translate_len() is that a box inset knows about
352 * some special "units" that are stored in \p special.
354 void translate_box_len(string const & length, string & value, string & unit, string & special)
356 if (translate_len(length, value, unit)) {
357 if (unit == "\\height" || unit == "\\depth" ||
358 unit == "\\totalheight" || unit == "\\width") {
359 special = unit.substr(1);
360 // The unit is not used, but LyX requires a dummy setting
373 * Find a file with basename \p name in path \p path and an extension
376 string find_file(string const & name, string const & path,
377 char const * const * extensions)
379 for (char const * const * what = extensions; *what; ++what) {
380 string const trial = addExtension(name, *what);
381 if (makeAbsPath(trial, path).exists())
388 void begin_inset(ostream & os, string const & name)
390 os << "\n\\begin_inset " << name;
394 void begin_command_inset(ostream & os, string const & name,
395 string const & latexname)
397 begin_inset(os, "CommandInset ");
398 os << name << "\nLatexCommand " << latexname << '\n';
402 void end_inset(ostream & os)
404 os << "\n\\end_inset\n\n";
408 bool skip_braces(Parser & p)
410 if (p.next_token().cat() != catBegin)
413 if (p.next_token().cat() == catEnd) {
422 /// replace LaTeX commands in \p s from the unicodesymbols file with their
424 docstring convert_unicodesymbols(docstring s)
427 for (size_t i = 0; i < s.size();) {
434 docstring parsed = encodings.fromLaTeXCommand(s, rem,
435 Encodings::TEXT_CMD);
438 if (s.empty() || s[0] != '\\')
447 /// try to convert \p s to a valid InsetCommand argument
448 string convert_command_inset_arg(string s)
451 // since we don't know the input encoding we can't use from_utf8
452 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
453 // LyX cannot handle newlines in a latex command
454 return subst(s, "\n", " ");
458 void handle_backslash(ostream & os, string const & s)
460 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
462 os << "\n\\backslash\n";
469 void handle_ert(ostream & os, string const & s, Context & context)
471 // We must have a valid layout before outputting the ERT inset.
472 context.check_layout(os);
473 Context newcontext(true, context.textclass);
474 begin_inset(os, "ERT");
475 os << "\nstatus collapsed\n";
476 newcontext.check_layout(os);
477 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
479 os << "\n\\backslash\n";
480 else if (*it == '\n') {
481 newcontext.new_paragraph(os);
482 newcontext.check_layout(os);
486 newcontext.check_end_layout(os);
491 void handle_comment(ostream & os, string const & s, Context & context)
493 // TODO: Handle this better
494 Context newcontext(true, context.textclass);
495 begin_inset(os, "ERT");
496 os << "\nstatus collapsed\n";
497 newcontext.check_layout(os);
498 handle_backslash(os, s);
499 // make sure that our comment is the last thing on the line
500 newcontext.new_paragraph(os);
501 newcontext.check_layout(os);
502 newcontext.check_end_layout(os);
507 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
509 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
512 if (checkModule(name, command))
513 return findLayoutWithoutModule(textclass, name, command);
518 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
520 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
523 if (checkModule(name, command))
524 return findInsetLayoutWithoutModule(textclass, name, command);
529 void eat_whitespace(Parser &, ostream &, Context &, bool);
533 * Skips whitespace and braces.
534 * This should be called after a command has been parsed that is not put into
535 * ERT, and where LyX adds "{}" if needed.
537 void skip_spaces_braces(Parser & p, bool keepws = false)
539 /* The following four examples produce the same typeset output and
540 should be handled by this function:
548 // Unfortunately we need to skip comments, too.
549 // We can't use eat_whitespace since writing them after the {}
550 // results in different output in some cases.
551 bool const skipped_spaces = p.skip_spaces(true);
552 bool const skipped_braces = skip_braces(p);
553 if (keepws && skipped_spaces && !skipped_braces)
554 // put back the space (it is better handled by check_space)
555 p.unskip_spaces(true);
559 void output_command_layout(ostream & os, Parser & p, bool outer,
560 Context & parent_context,
561 Layout const * newlayout)
563 TeXFont const oldFont = parent_context.font;
564 // save the current font size
565 string const size = oldFont.size;
566 // reset the font size to default, because the font size switches
567 // don't affect section headings and the like
568 parent_context.font.size = Context::normalfont.size;
569 // we only need to write the font change if we have an open layout
570 if (!parent_context.atParagraphStart())
571 output_font_change(os, oldFont, parent_context.font);
572 parent_context.check_end_layout(os);
573 Context context(true, parent_context.textclass, newlayout,
574 parent_context.layout, parent_context.font);
575 if (parent_context.deeper_paragraph) {
576 // We are beginning a nested environment after a
577 // deeper paragraph inside the outer list environment.
578 // Therefore we don't need to output a "begin deeper".
579 context.need_end_deeper = true;
581 context.check_deeper(os);
582 context.check_layout(os);
583 unsigned int optargs = 0;
584 while (optargs < context.layout->optargs) {
585 eat_whitespace(p, os, context, false);
586 if (p.next_token().cat() == catEscape ||
587 p.next_token().character() != '[')
589 p.get_token(); // eat '['
590 begin_inset(os, "Argument\n");
591 os << "status collapsed\n\n";
592 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
594 eat_whitespace(p, os, context, false);
597 unsigned int reqargs = 0;
598 while (reqargs < context.layout->reqargs) {
599 eat_whitespace(p, os, context, false);
600 if (p.next_token().cat() != catBegin)
602 p.get_token(); // eat '{'
603 begin_inset(os, "Argument\n");
604 os << "status collapsed\n\n";
605 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
607 eat_whitespace(p, os, context, false);
610 parse_text(p, os, FLAG_ITEM, outer, context);
611 context.check_end_layout(os);
612 if (parent_context.deeper_paragraph) {
613 // We must suppress the "end deeper" because we
614 // suppressed the "begin deeper" above.
615 context.need_end_deeper = false;
617 context.check_end_deeper(os);
618 // We don't need really a new paragraph, but
619 // we must make sure that the next item gets a \begin_layout.
620 parent_context.new_paragraph(os);
621 // Set the font size to the original value. No need to output it here
622 // (Context::begin_layout() will do that if needed)
623 parent_context.font.size = size;
628 * Output a space if necessary.
629 * This function gets called for every whitespace token.
631 * We have three cases here:
632 * 1. A space must be suppressed. Example: The lyxcode case below
633 * 2. A space may be suppressed. Example: Spaces before "\par"
634 * 3. A space must not be suppressed. Example: A space between two words
636 * We currently handle only 1. and 3 and from 2. only the case of
637 * spaces before newlines as a side effect.
639 * 2. could be used to suppress as many spaces as possible. This has two effects:
640 * - Reimporting LyX generated LaTeX files changes almost no whitespace
641 * - Superflous whitespace from non LyX generated LaTeX files is removed.
642 * The drawback is that the logic inside the function becomes
643 * complicated, and that is the reason why it is not implemented.
645 void check_space(Parser & p, ostream & os, Context & context)
647 Token const next = p.next_token();
648 Token const curr = p.curr_token();
649 // A space before a single newline and vice versa must be ignored
650 // LyX emits a newline before \end{lyxcode}.
651 // This newline must be ignored,
652 // otherwise LyX will add an additional protected space.
653 if (next.cat() == catSpace ||
654 next.cat() == catNewline ||
655 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
658 context.check_layout(os);
664 * Parse all arguments of \p command
666 void parse_arguments(string const & command,
667 vector<ArgumentType> const & template_arguments,
668 Parser & p, ostream & os, bool outer, Context & context)
670 string ert = command;
671 size_t no_arguments = template_arguments.size();
672 for (size_t i = 0; i < no_arguments; ++i) {
673 switch (template_arguments[i]) {
675 // This argument contains regular LaTeX
676 handle_ert(os, ert + '{', context);
677 eat_whitespace(p, os, context, false);
678 parse_text(p, os, FLAG_ITEM, outer, context);
682 // This argument consists only of a single item.
683 // The presence of '{' or not must be preserved.
685 if (p.next_token().cat() == catBegin)
686 ert += '{' + p.verbatim_item() + '}';
688 ert += p.verbatim_item();
691 // This argument may contain special characters
692 ert += '{' + p.verbatim_item() + '}';
695 // true because we must not eat whitespace
696 // if an optional arg follows we must not strip the
697 // brackets from this one
698 if (i < no_arguments - 1 &&
699 template_arguments[i+1] == optional)
700 ert += p.getFullOpt(true);
702 ert += p.getOpt(true);
706 handle_ert(os, ert, context);
711 * Check whether \p command is a known command. If yes,
712 * handle the command with all arguments.
713 * \return true if the command was parsed, false otherwise.
715 bool parse_command(string const & command, Parser & p, ostream & os,
716 bool outer, Context & context)
718 if (known_commands.find(command) != known_commands.end()) {
719 parse_arguments(command, known_commands[command], p, os,
727 /// Parses a minipage or parbox
728 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
729 unsigned inner_flags, bool outer, Context & parent_context,
730 string const & outer_type, string const & special,
731 string const & inner_type)
735 string hor_pos = "c";
736 // We need to set the height to the LaTeX default of 1\\totalheight
737 // for the case when no height argument is given
738 string height_value = "1";
739 string height_unit = "in";
740 string height_special = "totalheight";
742 if (!inner_type.empty() && p.hasOpt()) {
743 position = p.getArg('[', ']');
744 if (position != "t" && position != "c" && position != "b") {
745 cerr << "invalid position " << position << " for "
746 << inner_type << endl;
750 latex_height = p.getArg('[', ']');
751 translate_box_len(latex_height, height_value, height_unit, height_special);
754 inner_pos = p.getArg('[', ']');
755 if (inner_pos != "c" && inner_pos != "t" &&
756 inner_pos != "b" && inner_pos != "s") {
757 cerr << "invalid inner_pos "
758 << inner_pos << " for "
759 << inner_type << endl;
760 inner_pos = position;
768 if (inner_type.empty()) {
770 latex_width = "\\columnwidth";
773 latex_width = p2.getArg('[', ']');
774 string const opt = p2.getArg('[', ']');
777 if (hor_pos != "l" && hor_pos != "c" &&
779 cerr << "invalid hor_pos " << hor_pos
780 << " for " << outer_type << endl;
786 latex_width = p.verbatim_item();
787 translate_len(latex_width, width_value, width_unit);
788 bool shadedparbox = false;
789 if (inner_type == "shaded") {
790 eat_whitespace(p, os, parent_context, false);
791 if (outer_type == "parbox") {
793 if (p.next_token().cat() == catBegin)
795 eat_whitespace(p, os, parent_context, false);
801 // If we already read the inner box we have to push the inner env
802 if (!outer_type.empty() && !inner_type.empty() &&
803 (inner_flags & FLAG_END))
804 active_environments.push_back(inner_type);
805 // LyX can't handle length variables
806 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
807 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
808 // Look whether there is some content after the end of the
809 // inner box, but before the end of the outer box.
810 // If yes, we need to output ERT.
812 if (inner_flags & FLAG_END)
813 p.verbatimEnvironment(inner_type);
817 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
818 if ((outer_env && p.next_token().asInput() != "\\end") ||
819 (!outer_env && p.next_token().cat() != catEnd)) {
820 // something is between the end of the inner box and
821 // the end of the outer box, so we need to use ERT.
828 if (!outer_type.empty()) {
829 if (outer_flags & FLAG_END)
830 ss << "\\begin{" << outer_type << '}';
832 ss << '\\' << outer_type << '{';
833 if (!special.empty())
837 if (!inner_type.empty()) {
838 if (inner_type != "shaded") {
839 if (inner_flags & FLAG_END)
840 ss << "\\begin{" << inner_type << '}';
842 ss << '\\' << inner_type;
844 if (!position.empty())
845 ss << '[' << position << ']';
846 if (!latex_height.empty())
847 ss << '[' << latex_height << ']';
848 if (!inner_pos.empty())
849 ss << '[' << inner_pos << ']';
850 ss << '{' << latex_width << '}';
851 if (!(inner_flags & FLAG_END))
854 if (inner_type == "shaded")
855 ss << "\\begin{shaded}";
856 handle_ert(os, ss.str(), parent_context);
857 if (!inner_type.empty()) {
858 parse_text(p, os, inner_flags, outer, parent_context);
859 if (inner_flags & FLAG_END)
860 handle_ert(os, "\\end{" + inner_type + '}',
863 handle_ert(os, "}", parent_context);
865 if (!outer_type.empty()) {
866 // If we already read the inner box we have to pop
868 if (!inner_type.empty() && (inner_flags & FLAG_END))
869 active_environments.pop_back();
870 parse_text(p, os, outer_flags, outer, parent_context);
871 if (outer_flags & FLAG_END)
872 handle_ert(os, "\\end{" + outer_type + '}',
875 handle_ert(os, "}", parent_context);
878 // LyX does not like empty positions, so we have
879 // to set them to the LaTeX default values here.
880 if (position.empty())
882 if (inner_pos.empty())
883 inner_pos = position;
884 // FIXME: Support makebox
885 bool const use_makebox = false;
886 parent_context.check_layout(os);
887 begin_inset(os, "Box ");
888 if (outer_type == "framed")
890 else if (outer_type == "framebox")
892 else if (outer_type == "shadowbox")
894 else if ((outer_type == "shaded" && inner_type.empty()) ||
895 (outer_type == "minipage" && inner_type == "shaded") ||
896 (outer_type == "parbox" && inner_type == "shaded")) {
898 preamble.registerAutomaticallyLoadedPackage("color");
899 } else if (outer_type == "doublebox")
901 else if (outer_type.empty())
904 os << outer_type << '\n';
905 os << "position \"" << position << "\"\n";
906 os << "hor_pos \"" << hor_pos << "\"\n";
907 os << "has_inner_box " << !inner_type.empty() << "\n";
908 os << "inner_pos \"" << inner_pos << "\"\n";
909 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
911 os << "use_makebox " << use_makebox << '\n';
912 os << "width \"" << width_value << width_unit << "\"\n";
913 os << "special \"none\"\n";
914 os << "height \"" << height_value << height_unit << "\"\n";
915 os << "height_special \"" << height_special << "\"\n";
916 os << "status open\n\n";
918 // Unfortunately we can't use parse_text_in_inset:
919 // InsetBox::forcePlainLayout() is hard coded and does not
920 // use the inset layout. Apart from that do we call parse_text
921 // up to two times, but need only one check_end_layout.
923 bool const forcePlainLayout =
924 (!inner_type.empty() || use_makebox) &&
925 outer_type != "shaded" && outer_type != "framed";
926 Context context(true, parent_context.textclass);
927 if (forcePlainLayout)
928 context.layout = &context.textclass.plainLayout();
930 context.font = parent_context.font;
932 // If we have no inner box the contents will be read with the outer box
933 if (!inner_type.empty())
934 parse_text(p, os, inner_flags, outer, context);
936 // Ensure that the end of the outer box is parsed correctly:
937 // The opening brace has been eaten by parse_outer_box()
938 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
939 outer_flags &= ~FLAG_ITEM;
940 outer_flags |= FLAG_BRACE_LAST;
943 // Find end of outer box, output contents if inner_type is
944 // empty and output possible comments
945 if (!outer_type.empty()) {
946 // If we already read the inner box we have to pop
948 if (!inner_type.empty() && (inner_flags & FLAG_END))
949 active_environments.pop_back();
950 // This does not output anything but comments if
951 // inner_type is not empty (see use_ert)
952 parse_text(p, os, outer_flags, outer, context);
955 context.check_end_layout(os);
957 #ifdef PRESERVE_LAYOUT
958 // LyX puts a % after the end of the minipage
959 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
961 //handle_comment(os, "%dummy", parent_context);
964 parent_context.new_paragraph(os);
966 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
967 //handle_comment(os, "%dummy", parent_context);
970 // We add a protected space if something real follows
971 if (p.good() && p.next_token().cat() != catComment) {
972 begin_inset(os, "space ~\n");
981 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
982 Context & parent_context, string const & outer_type,
983 string const & special)
985 eat_whitespace(p, os, parent_context, false);
986 if (flags & FLAG_ITEM) {
988 if (p.next_token().cat() == catBegin)
991 cerr << "Warning: Ignoring missing '{' after \\"
992 << outer_type << '.' << endl;
993 eat_whitespace(p, os, parent_context, false);
996 unsigned int inner_flags = 0;
998 if (outer_type == "minipage" || outer_type == "parbox") {
1000 while (p.hasOpt()) {
1002 p.skip_spaces(true);
1005 p.skip_spaces(true);
1006 if (outer_type == "parbox") {
1008 if (p.next_token().cat() == catBegin)
1010 eat_whitespace(p, os, parent_context, false);
1013 if (outer_type == "shaded") {
1014 // These boxes never have an inner box
1016 } else if (p.next_token().asInput() == "\\parbox") {
1017 inner = p.get_token().cs();
1018 inner_flags = FLAG_ITEM;
1019 } else if (p.next_token().asInput() == "\\begin") {
1020 // Is this a minipage or shaded box?
1023 inner = p.getArg('{', '}');
1025 if (inner == "minipage" || inner == "shaded")
1026 inner_flags = FLAG_END;
1031 if (inner_flags == FLAG_END) {
1032 if (inner != "shaded")
1036 eat_whitespace(p, os, parent_context, false);
1038 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1039 outer_type, special, inner);
1041 if (inner_flags == FLAG_ITEM) {
1043 eat_whitespace(p, os, parent_context, false);
1045 parse_box(p, os, flags, inner_flags, outer, parent_context,
1046 outer_type, special, inner);
1051 void parse_listings(Parser & p, ostream & os, Context & parent_context)
1053 parent_context.check_layout(os);
1054 begin_inset(os, "listings\n");
1055 os << "inline false\n"
1056 << "status collapsed\n";
1057 Context context(true, parent_context.textclass);
1058 context.layout = &parent_context.textclass.plainLayout();
1059 context.check_layout(os);
1060 string const s = p.verbatimEnvironment("lstlisting");
1061 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1063 os << "\n\\backslash\n";
1064 else if (*it == '\n') {
1065 // avoid adding an empty paragraph at the end
1067 context.new_paragraph(os);
1068 context.check_layout(os);
1073 context.check_end_layout(os);
1078 /// parse an unknown environment
1079 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1080 unsigned flags, bool outer,
1081 Context & parent_context)
1083 if (name == "tabbing")
1084 // We need to remember that we have to handle '\=' specially
1085 flags |= FLAG_TABBING;
1087 // We need to translate font changes and paragraphs inside the
1088 // environment to ERT if we have a non standard font.
1089 // Otherwise things like
1090 // \large\begin{foo}\huge bar\end{foo}
1092 bool const specialfont =
1093 (parent_context.font != parent_context.normalfont);
1094 bool const new_layout_allowed = parent_context.new_layout_allowed;
1096 parent_context.new_layout_allowed = false;
1097 handle_ert(os, "\\begin{" + name + "}", parent_context);
1098 parse_text_snippet(p, os, flags, outer, parent_context);
1099 handle_ert(os, "\\end{" + name + "}", parent_context);
1101 parent_context.new_layout_allowed = new_layout_allowed;
1105 void parse_environment(Parser & p, ostream & os, bool outer,
1106 string & last_env, bool & title_layout_found,
1107 Context & parent_context)
1109 Layout const * newlayout;
1110 InsetLayout const * newinsetlayout = 0;
1111 string const name = p.getArg('{', '}');
1112 const bool is_starred = suffixIs(name, '*');
1113 string const unstarred_name = rtrim(name, "*");
1114 active_environments.push_back(name);
1116 if (is_math_env(name)) {
1117 parent_context.check_layout(os);
1118 begin_inset(os, "Formula ");
1119 os << "\\begin{" << name << "}";
1120 parse_math(p, os, FLAG_END, MATH_MODE);
1121 os << "\\end{" << name << "}";
1125 else if (name == "tabular" || name == "longtable") {
1126 eat_whitespace(p, os, parent_context, false);
1127 parent_context.check_layout(os);
1128 begin_inset(os, "Tabular ");
1129 handle_tabular(p, os, name == "longtable", parent_context);
1134 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1135 eat_whitespace(p, os, parent_context, false);
1136 parent_context.check_layout(os);
1137 begin_inset(os, "Float " + unstarred_name + "\n");
1138 // store the float type for subfloats
1139 // subfloats only work with figures and tables
1140 if (unstarred_name == "figure")
1141 float_type = unstarred_name;
1142 else if (unstarred_name == "table")
1143 float_type = unstarred_name;
1147 os << "placement " << p.getArg('[', ']') << '\n';
1148 os << "wide " << convert<string>(is_starred)
1149 << "\nsideways false"
1150 << "\nstatus open\n\n";
1151 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1153 // We don't need really a new paragraph, but
1154 // we must make sure that the next item gets a \begin_layout.
1155 parent_context.new_paragraph(os);
1157 // the float is parsed thus delete the type
1161 else if (unstarred_name == "sidewaysfigure"
1162 || unstarred_name == "sidewaystable") {
1163 eat_whitespace(p, os, parent_context, false);
1164 parent_context.check_layout(os);
1165 if (unstarred_name == "sidewaysfigure")
1166 begin_inset(os, "Float figure\n");
1168 begin_inset(os, "Float table\n");
1169 os << "wide " << convert<string>(is_starred)
1170 << "\nsideways true"
1171 << "\nstatus open\n\n";
1172 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1174 // We don't need really a new paragraph, but
1175 // we must make sure that the next item gets a \begin_layout.
1176 parent_context.new_paragraph(os);
1180 else if (name == "wrapfigure" || name == "wraptable") {
1181 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1182 eat_whitespace(p, os, parent_context, false);
1183 parent_context.check_layout(os);
1186 string overhang = "0col%";
1189 lines = p.getArg('[', ']');
1190 string const placement = p.getArg('{', '}');
1192 overhang = p.getArg('[', ']');
1193 string const width = p.getArg('{', '}');
1195 if (name == "wrapfigure")
1196 begin_inset(os, "Wrap figure\n");
1198 begin_inset(os, "Wrap table\n");
1199 os << "lines " << lines
1200 << "\nplacement " << placement
1201 << "\noverhang " << lyx::translate_len(overhang)
1202 << "\nwidth " << lyx::translate_len(width)
1203 << "\nstatus open\n\n";
1204 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1206 // We don't need really a new paragraph, but
1207 // we must make sure that the next item gets a \begin_layout.
1208 parent_context.new_paragraph(os);
1212 else if (name == "minipage") {
1213 eat_whitespace(p, os, parent_context, false);
1214 // Test whether this is an outer box of a shaded box
1216 // swallow arguments
1217 while (p.hasOpt()) {
1219 p.skip_spaces(true);
1222 p.skip_spaces(true);
1223 Token t = p.get_token();
1224 bool shaded = false;
1225 if (t.asInput() == "\\begin") {
1226 p.skip_spaces(true);
1227 if (p.getArg('{', '}') == "shaded")
1232 parse_outer_box(p, os, FLAG_END, outer,
1233 parent_context, name, "shaded");
1235 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1240 else if (name == "comment") {
1241 eat_whitespace(p, os, parent_context, false);
1242 parent_context.check_layout(os);
1243 begin_inset(os, "Note Comment\n");
1244 os << "status open\n";
1245 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1248 skip_braces(p); // eat {} that might by set by LyX behind comments
1251 else if (name == "lyxgreyedout") {
1252 eat_whitespace(p, os, parent_context, false);
1253 parent_context.check_layout(os);
1254 begin_inset(os, "Note Greyedout\n");
1255 os << "status open\n";
1256 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1259 if (!preamble.notefontcolor().empty())
1260 preamble.registerAutomaticallyLoadedPackage("color");
1263 else if (name == "framed" || name == "shaded") {
1264 eat_whitespace(p, os, parent_context, false);
1265 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1269 else if (name == "lstlisting") {
1270 eat_whitespace(p, os, parent_context, false);
1271 // FIXME handle listings with parameters
1272 // If this is added, don't forgot to handle the
1273 // automatic color package loading
1275 parse_unknown_environment(p, name, os, FLAG_END,
1276 outer, parent_context);
1278 parse_listings(p, os, parent_context);
1282 else if (!parent_context.new_layout_allowed)
1283 parse_unknown_environment(p, name, os, FLAG_END, outer,
1286 // Alignment and spacing settings
1287 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1288 // therefore are totally broken!
1289 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1290 // they are commands not environments. They are furthermore switches that
1291 // can be ended by another switches, but also by commands like \footnote or
1292 // \parbox. So the only safe way is to leave them untouched.
1293 else if (name == "center" || name == "centering" ||
1294 name == "flushleft" || name == "flushright" ||
1295 name == "singlespace" || name == "onehalfspace" ||
1296 name == "doublespace" || name == "spacing") {
1297 eat_whitespace(p, os, parent_context, false);
1298 // We must begin a new paragraph if not already done
1299 if (! parent_context.atParagraphStart()) {
1300 parent_context.check_end_layout(os);
1301 parent_context.new_paragraph(os);
1303 if (name == "flushleft")
1304 parent_context.add_extra_stuff("\\align left\n");
1305 else if (name == "flushright")
1306 parent_context.add_extra_stuff("\\align right\n");
1307 else if (name == "center" || name == "centering")
1308 parent_context.add_extra_stuff("\\align center\n");
1309 else if (name == "singlespace")
1310 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1311 else if (name == "onehalfspace")
1312 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1313 else if (name == "doublespace")
1314 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1315 else if (name == "spacing")
1316 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1317 parse_text(p, os, FLAG_END, outer, parent_context);
1318 // Just in case the environment is empty
1319 parent_context.extra_stuff.erase();
1320 // We must begin a new paragraph to reset the alignment
1321 parent_context.new_paragraph(os);
1325 // The single '=' is meant here.
1326 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1327 eat_whitespace(p, os, parent_context, false);
1328 Context context(true, parent_context.textclass, newlayout,
1329 parent_context.layout, parent_context.font);
1330 if (parent_context.deeper_paragraph) {
1331 // We are beginning a nested environment after a
1332 // deeper paragraph inside the outer list environment.
1333 // Therefore we don't need to output a "begin deeper".
1334 context.need_end_deeper = true;
1336 parent_context.check_end_layout(os);
1337 if (last_env == name) {
1338 // we need to output a separator since LyX would export
1339 // the two environments as one otherwise (bug 5716)
1340 docstring const sep = from_ascii("--Separator--");
1341 TeX2LyXDocClass const & textclass(parent_context.textclass);
1342 if (textclass.hasLayout(sep)) {
1343 Context newcontext(parent_context);
1344 newcontext.layout = &(textclass[sep]);
1345 newcontext.check_layout(os);
1346 newcontext.check_end_layout(os);
1348 parent_context.check_layout(os);
1349 begin_inset(os, "Note Note\n");
1350 os << "status closed\n";
1351 Context newcontext(true, textclass,
1352 &(textclass.defaultLayout()));
1353 newcontext.check_layout(os);
1354 newcontext.check_end_layout(os);
1356 parent_context.check_end_layout(os);
1359 switch (context.layout->latextype) {
1360 case LATEX_LIST_ENVIRONMENT:
1361 context.add_par_extra_stuff("\\labelwidthstring "
1362 + p.verbatim_item() + '\n');
1365 case LATEX_BIB_ENVIRONMENT:
1366 p.verbatim_item(); // swallow next arg
1372 context.check_deeper(os);
1373 // handle known optional and required arguments
1374 // layouts require all optional arguments before the required ones
1375 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1376 // It is impossible to place anything after the environment name,
1377 // but before the first \\item.
1378 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1379 bool need_layout = true;
1380 unsigned int optargs = 0;
1381 while (optargs < context.layout->optargs) {
1382 eat_whitespace(p, os, context, false);
1383 if (p.next_token().cat() == catEscape ||
1384 p.next_token().character() != '[')
1386 p.get_token(); // eat '['
1388 context.check_layout(os);
1389 need_layout = false;
1391 begin_inset(os, "Argument\n");
1392 os << "status collapsed\n\n";
1393 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1395 eat_whitespace(p, os, context, false);
1398 unsigned int reqargs = 0;
1399 while (reqargs < context.layout->reqargs) {
1400 eat_whitespace(p, os, context, false);
1401 if (p.next_token().cat() != catBegin)
1403 p.get_token(); // eat '{'
1405 context.check_layout(os);
1406 need_layout = false;
1408 begin_inset(os, "Argument\n");
1409 os << "status collapsed\n\n";
1410 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1412 eat_whitespace(p, os, context, false);
1416 parse_text(p, os, FLAG_END, outer, context);
1417 context.check_end_layout(os);
1418 if (parent_context.deeper_paragraph) {
1419 // We must suppress the "end deeper" because we
1420 // suppressed the "begin deeper" above.
1421 context.need_end_deeper = false;
1423 context.check_end_deeper(os);
1424 parent_context.new_paragraph(os);
1426 if (!title_layout_found)
1427 title_layout_found = newlayout->intitle;
1430 // The single '=' is meant here.
1431 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1432 eat_whitespace(p, os, parent_context, false);
1433 parent_context.check_layout(os);
1434 begin_inset(os, "Flex ");
1435 os << to_utf8(newinsetlayout->name()) << '\n'
1436 << "status collapsed\n";
1437 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1441 else if (name == "appendix") {
1442 // This is no good latex style, but it works and is used in some documents...
1443 eat_whitespace(p, os, parent_context, false);
1444 parent_context.check_end_layout(os);
1445 Context context(true, parent_context.textclass, parent_context.layout,
1446 parent_context.layout, parent_context.font);
1447 context.check_layout(os);
1448 os << "\\start_of_appendix\n";
1449 parse_text(p, os, FLAG_END, outer, context);
1450 context.check_end_layout(os);
1454 else if (known_environments.find(name) != known_environments.end()) {
1455 vector<ArgumentType> arguments = known_environments[name];
1456 // The last "argument" denotes wether we may translate the
1457 // environment contents to LyX
1458 // The default required if no argument is given makes us
1459 // compatible with the reLyXre environment.
1460 ArgumentType contents = arguments.empty() ?
1463 if (!arguments.empty())
1464 arguments.pop_back();
1465 // See comment in parse_unknown_environment()
1466 bool const specialfont =
1467 (parent_context.font != parent_context.normalfont);
1468 bool const new_layout_allowed =
1469 parent_context.new_layout_allowed;
1471 parent_context.new_layout_allowed = false;
1472 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1473 outer, parent_context);
1474 if (contents == verbatim)
1475 handle_ert(os, p.verbatimEnvironment(name),
1478 parse_text_snippet(p, os, FLAG_END, outer,
1480 handle_ert(os, "\\end{" + name + "}", parent_context);
1482 parent_context.new_layout_allowed = new_layout_allowed;
1486 parse_unknown_environment(p, name, os, FLAG_END, outer,
1490 active_environments.pop_back();
1494 /// parses a comment and outputs it to \p os.
1495 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1497 LASSERT(t.cat() == catComment, return);
1498 if (!t.cs().empty()) {
1499 context.check_layout(os);
1500 handle_comment(os, '%' + t.cs(), context);
1501 if (p.next_token().cat() == catNewline) {
1502 // A newline after a comment line starts a new
1504 if (context.new_layout_allowed) {
1505 if(!context.atParagraphStart())
1506 // Only start a new paragraph if not already
1507 // done (we might get called recursively)
1508 context.new_paragraph(os);
1510 handle_ert(os, "\n", context);
1511 eat_whitespace(p, os, context, true);
1514 // "%\n" combination
1521 * Reads spaces and comments until the first non-space, non-comment token.
1522 * New paragraphs (double newlines or \\par) are handled like simple spaces
1523 * if \p eatParagraph is true.
1524 * Spaces are skipped, but comments are written to \p os.
1526 void eat_whitespace(Parser & p, ostream & os, Context & context,
1530 Token const & t = p.get_token();
1531 if (t.cat() == catComment)
1532 parse_comment(p, os, t, context);
1533 else if ((! eatParagraph && p.isParagraph()) ||
1534 (t.cat() != catSpace && t.cat() != catNewline)) {
1543 * Set a font attribute, parse text and reset the font attribute.
1544 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1545 * \param currentvalue Current value of the attribute. Is set to the new
1546 * value during parsing.
1547 * \param newvalue New value of the attribute
1549 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1550 Context & context, string const & attribute,
1551 string & currentvalue, string const & newvalue)
1553 context.check_layout(os);
1554 string const oldvalue = currentvalue;
1555 currentvalue = newvalue;
1556 os << '\n' << attribute << ' ' << newvalue << "\n";
1557 parse_text_snippet(p, os, flags, outer, context);
1558 context.check_layout(os);
1559 os << '\n' << attribute << ' ' << oldvalue << "\n";
1560 currentvalue = oldvalue;
1564 /// get the arguments of a natbib or jurabib citation command
1565 void get_cite_arguments(Parser & p, bool natbibOrder,
1566 string & before, string & after)
1568 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1570 // text before the citation
1572 // text after the citation
1573 after = p.getFullOpt();
1575 if (!after.empty()) {
1576 before = p.getFullOpt();
1577 if (natbibOrder && !before.empty())
1578 swap(before, after);
1583 /// Convert filenames with TeX macros and/or quotes to something LyX
1585 string const normalize_filename(string const & name)
1587 Parser p(trim(name, "\""));
1590 Token const & t = p.get_token();
1591 if (t.cat() != catEscape)
1593 else if (t.cs() == "lyxdot") {
1594 // This is used by LyX for simple dots in relative
1598 } else if (t.cs() == "space") {
1608 /// Convert \p name from TeX convention (relative to master file) to LyX
1609 /// convention (relative to .lyx file) if it is relative
1610 void fix_relative_filename(string & name)
1612 if (FileName::isAbsolute(name))
1615 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1616 from_utf8(getParentFilePath())));
1620 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1621 void parse_noweb(Parser & p, ostream & os, Context & context)
1623 // assemble the rest of the keyword
1627 Token const & t = p.get_token();
1628 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1631 scrap = (p.good() && p.next_token().asInput() == "=");
1633 name += p.get_token().asInput();
1636 name += t.asInput();
1639 if (!scrap || !context.new_layout_allowed ||
1640 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1641 cerr << "Warning: Could not interpret '" << name
1642 << "'. Ignoring it." << endl;
1646 // We use new_paragraph instead of check_end_layout because the stuff
1647 // following the noweb chunk needs to start with a \begin_layout.
1648 // This may create a new paragraph even if there was none in the
1649 // noweb file, but the alternative is an invalid LyX file. Since
1650 // noweb code chunks are implemented with a layout style in LyX they
1651 // always must be in an own paragraph.
1652 context.new_paragraph(os);
1653 Context newcontext(true, context.textclass,
1654 &context.textclass[from_ascii("Scrap")]);
1655 newcontext.check_layout(os);
1658 Token const & t = p.get_token();
1659 // We abuse the parser a bit, because this is no TeX syntax
1661 if (t.cat() == catEscape)
1662 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1665 Context tmp(false, context.textclass,
1666 &context.textclass[from_ascii("Scrap")]);
1667 tmp.need_end_layout = true;
1668 tmp.check_layout(oss);
1669 os << subst(t.asInput(), "\n", oss.str());
1671 // The scrap chunk is ended by an @ at the beginning of a line.
1672 // After the @ the line may contain a comment and/or
1673 // whitespace, but nothing else.
1674 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1675 (p.next_token().cat() == catSpace ||
1676 p.next_token().cat() == catNewline ||
1677 p.next_token().cat() == catComment)) {
1678 while (p.good() && p.next_token().cat() == catSpace)
1679 os << p.get_token().asInput();
1680 if (p.next_token().cat() == catComment)
1681 // The comment includes a final '\n'
1682 os << p.get_token().asInput();
1684 if (p.next_token().cat() == catNewline)
1691 newcontext.check_end_layout(os);
1695 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1696 bool is_macro(Parser & p)
1698 Token first = p.curr_token();
1699 if (first.cat() != catEscape || !p.good())
1701 if (first.cs() == "def")
1703 if (first.cs() != "global" && first.cs() != "long")
1705 Token second = p.get_token();
1707 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1708 second.cat() == catNewline || second.cat() == catComment)) {
1709 second = p.get_token();
1712 bool secondvalid = second.cat() == catEscape;
1714 bool thirdvalid = false;
1715 if (p.good() && first.cs() == "global" && secondvalid &&
1716 second.cs() == "long") {
1717 third = p.get_token();
1719 while (p.good() && !p.isParagraph() &&
1720 (third.cat() == catSpace ||
1721 third.cat() == catNewline ||
1722 third.cat() == catComment)) {
1723 third = p.get_token();
1726 thirdvalid = third.cat() == catEscape;
1728 for (int i = 0; i < pos; ++i)
1733 return (first.cs() == "global" || first.cs() == "long") &&
1734 second.cs() == "def";
1735 return first.cs() == "global" && second.cs() == "long" &&
1736 third.cs() == "def";
1740 /// Parse a macro definition (assumes that is_macro() returned true)
1741 void parse_macro(Parser & p, ostream & os, Context & context)
1743 context.check_layout(os);
1744 Token first = p.curr_token();
1747 string command = first.asInput();
1748 if (first.cs() != "def") {
1750 eat_whitespace(p, os, context, false);
1751 second = p.curr_token();
1752 command += second.asInput();
1753 if (second.cs() != "def") {
1755 eat_whitespace(p, os, context, false);
1756 third = p.curr_token();
1757 command += third.asInput();
1760 eat_whitespace(p, os, context, false);
1761 string const name = p.get_token().cs();
1762 eat_whitespace(p, os, context, false);
1768 while (p.next_token().cat() != catBegin) {
1769 if (p.next_token().cat() == catParameter) {
1774 // followed by number?
1775 if (p.next_token().cat() == catOther) {
1776 char c = p.getChar();
1778 // number = current arity + 1?
1779 if (c == arity + '0' + 1)
1784 paramtext += p.get_token().cs();
1786 paramtext += p.get_token().cs();
1791 // only output simple (i.e. compatible) macro as FormulaMacros
1792 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1794 context.check_layout(os);
1795 begin_inset(os, "FormulaMacro");
1796 os << "\n\\def" << ert;
1799 handle_ert(os, command + ert, context);
1802 } // anonymous namespace
1805 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1808 Layout const * newlayout = 0;
1809 InsetLayout const * newinsetlayout = 0;
1810 // Store the latest bibliographystyle and nocite{*} option
1811 // (needed for bibtex inset)
1813 string bibliographystyle;
1814 bool const use_natbib = preamble.isPackageUsed("natbib");
1815 bool const use_jurabib = preamble.isPackageUsed("jurabib");
1817 bool title_layout_found = false;
1819 Token const & t = p.get_token();
1822 debugToken(cerr, t, flags);
1825 if (flags & FLAG_ITEM) {
1826 if (t.cat() == catSpace)
1829 flags &= ~FLAG_ITEM;
1830 if (t.cat() == catBegin) {
1831 // skip the brace and collect everything to the next matching
1833 flags |= FLAG_BRACE_LAST;
1837 // handle only this single token, leave the loop if done
1838 flags |= FLAG_LEAVE;
1841 if (t.cat() != catEscape && t.character() == ']' &&
1842 (flags & FLAG_BRACK_LAST))
1844 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1847 // If there is anything between \end{env} and \begin{env} we
1848 // don't need to output a separator.
1849 if (t.cat() != catSpace && t.cat() != catNewline &&
1850 t.asInput() != "\\begin")
1856 if (t.cat() == catMath) {
1857 // we are inside some text mode thingy, so opening new math is allowed
1858 context.check_layout(os);
1859 begin_inset(os, "Formula ");
1860 Token const & n = p.get_token();
1861 if (n.cat() == catMath && outer) {
1862 // TeX's $$...$$ syntax for displayed math
1864 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1866 p.get_token(); // skip the second '$' token
1868 // simple $...$ stuff
1871 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1877 else if (t.cat() == catSuper || t.cat() == catSub)
1878 cerr << "catcode " << t << " illegal in text mode\n";
1880 // Basic support for english quotes. This should be
1881 // extended to other quotes, but is not so easy (a
1882 // left english quote is the same as a right german
1884 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1885 context.check_layout(os);
1886 begin_inset(os, "Quotes ");
1892 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1893 context.check_layout(os);
1894 begin_inset(os, "Quotes ");
1901 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1902 context.check_layout(os);
1903 begin_inset(os, "Quotes ");
1910 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1911 context.check_layout(os);
1912 begin_inset(os, "Quotes ");
1919 else if (t.asInput() == "<"
1920 && p.next_token().asInput() == "<" && noweb_mode) {
1922 parse_noweb(p, os, context);
1925 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1926 check_space(p, os, context);
1928 else if (t.character() == '[' && noweb_mode &&
1929 p.next_token().character() == '[') {
1930 // These can contain underscores
1932 string const s = p.getFullOpt() + ']';
1933 if (p.next_token().character() == ']')
1936 cerr << "Warning: Inserting missing ']' in '"
1937 << s << "'." << endl;
1938 handle_ert(os, s, context);
1941 else if (t.cat() == catLetter) {
1942 context.check_layout(os);
1943 // Workaround for bug 4752.
1944 // FIXME: This whole code block needs to be removed
1945 // when the bug is fixed and tex2lyx produces
1946 // the updated file format.
1947 // The replacement algorithm in LyX is so stupid that
1948 // it even translates a phrase if it is part of a word.
1949 bool handled = false;
1950 for (int const * l = known_phrase_lengths; *l; ++l) {
1951 string phrase = t.cs();
1952 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
1953 phrase += p.get_token().cs();
1954 if (is_known(phrase, known_coded_phrases)) {
1955 handle_ert(os, phrase, context);
1959 for (size_t i = 1; i < phrase.length(); ++i)
1967 else if (t.cat() == catOther ||
1968 t.cat() == catAlign ||
1969 t.cat() == catParameter) {
1970 // This translates "&" to "\\&" which may be wrong...
1971 context.check_layout(os);
1975 else if (p.isParagraph()) {
1976 if (context.new_layout_allowed)
1977 context.new_paragraph(os);
1979 handle_ert(os, "\\par ", context);
1980 eat_whitespace(p, os, context, true);
1983 else if (t.cat() == catActive) {
1984 context.check_layout(os);
1985 if (t.character() == '~') {
1986 if (context.layout->free_spacing)
1989 begin_inset(os, "space ~\n");
1996 else if (t.cat() == catBegin &&
1997 p.next_token().cat() == catEnd) {
1999 Token const prev = p.prev_token();
2001 if (p.next_token().character() == '`' ||
2002 (prev.character() == '-' &&
2003 p.next_token().character() == '-'))
2004 ; // ignore it in {}`` or -{}-
2006 handle_ert(os, "{}", context);
2010 else if (t.cat() == catBegin) {
2011 context.check_layout(os);
2012 // special handling of font attribute changes
2013 Token const prev = p.prev_token();
2014 Token const next = p.next_token();
2015 TeXFont const oldFont = context.font;
2016 if (next.character() == '[' ||
2017 next.character() == ']' ||
2018 next.character() == '*') {
2020 if (p.next_token().cat() == catEnd) {
2025 handle_ert(os, "{", context);
2026 parse_text_snippet(p, os,
2029 handle_ert(os, "}", context);
2031 } else if (! context.new_layout_allowed) {
2032 handle_ert(os, "{", context);
2033 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2035 handle_ert(os, "}", context);
2036 } else if (is_known(next.cs(), known_sizes)) {
2037 // next will change the size, so we must
2039 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2041 if (!context.atParagraphStart())
2043 << context.font.size << "\n";
2044 } else if (is_known(next.cs(), known_font_families)) {
2045 // next will change the font family, so we
2046 // must reset it here
2047 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2049 if (!context.atParagraphStart())
2051 << context.font.family << "\n";
2052 } else if (is_known(next.cs(), known_font_series)) {
2053 // next will change the font series, so we
2054 // must reset it here
2055 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2057 if (!context.atParagraphStart())
2059 << context.font.series << "\n";
2060 } else if (is_known(next.cs(), known_font_shapes)) {
2061 // next will change the font shape, so we
2062 // must reset it here
2063 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2065 if (!context.atParagraphStart())
2067 << context.font.shape << "\n";
2068 } else if (is_known(next.cs(), known_old_font_families) ||
2069 is_known(next.cs(), known_old_font_series) ||
2070 is_known(next.cs(), known_old_font_shapes)) {
2071 // next will change the font family, series
2072 // and shape, so we must reset it here
2073 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2075 if (!context.atParagraphStart())
2077 << context.font.family
2079 << context.font.series
2081 << context.font.shape << "\n";
2083 handle_ert(os, "{", context);
2084 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2086 handle_ert(os, "}", context);
2090 else if (t.cat() == catEnd) {
2091 if (flags & FLAG_BRACE_LAST) {
2094 cerr << "stray '}' in text\n";
2095 handle_ert(os, "}", context);
2098 else if (t.cat() == catComment)
2099 parse_comment(p, os, t, context);
2102 // control sequences
2105 else if (t.cs() == "(") {
2106 context.check_layout(os);
2107 begin_inset(os, "Formula");
2109 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2114 else if (t.cs() == "[") {
2115 context.check_layout(os);
2116 begin_inset(os, "Formula");
2118 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2123 else if (t.cs() == "begin")
2124 parse_environment(p, os, outer, last_env,
2125 title_layout_found, context);
2127 else if (t.cs() == "end") {
2128 if (flags & FLAG_END) {
2129 // eat environment name
2130 string const name = p.getArg('{', '}');
2131 if (name != active_environment())
2132 cerr << "\\end{" + name + "} does not match \\begin{"
2133 + active_environment() + "}\n";
2136 p.error("found 'end' unexpectedly");
2139 else if (t.cs() == "item") {
2142 bool optarg = false;
2143 if (p.next_token().cat() != catEscape &&
2144 p.next_token().character() == '[') {
2145 p.get_token(); // eat '['
2146 s = parse_text_snippet(p, FLAG_BRACK_LAST,
2151 context.check_layout(os);
2152 if (context.has_item) {
2153 // An item in an unknown list-like environment
2154 // FIXME: Do this in check_layout()!
2155 context.has_item = false;
2157 handle_ert(os, "\\item", context);
2159 handle_ert(os, "\\item ", context);
2162 if (context.layout->labeltype != LABEL_MANUAL) {
2163 // LyX does not support \item[\mybullet]
2164 // in itemize environments
2165 handle_ert(os, "[", context);
2167 handle_ert(os, "]", context);
2168 } else if (!s.empty()) {
2169 // The space is needed to separate the
2170 // item from the rest of the sentence.
2172 eat_whitespace(p, os, context, false);
2177 else if (t.cs() == "bibitem") {
2179 context.check_layout(os);
2180 string label = convert_command_inset_arg(p.getArg('[', ']'));
2181 string key = convert_command_inset_arg(p.verbatim_item());
2182 if (contains(label, '\\') || contains(key, '\\')) {
2183 // LyX can't handle LaTeX commands in labels or keys
2184 handle_ert(os, t.asInput() + '[' + label +
2185 "]{" + p.verbatim_item() + '}',
2188 begin_command_inset(os, "bibitem", "bibitem");
2189 os << "label \"" << label << "\"\n"
2190 "key \"" << key << "\"\n";
2195 else if (is_macro(p))
2196 parse_macro(p, os, context);
2198 else if (t.cs() == "noindent") {
2200 context.add_par_extra_stuff("\\noindent\n");
2203 else if (t.cs() == "appendix") {
2204 context.add_par_extra_stuff("\\start_of_appendix\n");
2205 // We need to start a new paragraph. Otherwise the
2206 // appendix in 'bla\appendix\chapter{' would start
2208 context.new_paragraph(os);
2209 // We need to make sure that the paragraph is
2210 // generated even if it is empty. Otherwise the
2211 // appendix in '\par\appendix\par\chapter{' would
2213 context.check_layout(os);
2214 // FIXME: This is a hack to prevent paragraph
2215 // deletion if it is empty. Handle this better!
2217 "%dummy comment inserted by tex2lyx to "
2218 "ensure that this paragraph is not empty",
2220 // Both measures above may generate an additional
2221 // empty paragraph, but that does not hurt, because
2222 // whitespace does not matter here.
2223 eat_whitespace(p, os, context, true);
2226 // Must catch empty dates before findLayout is called below
2227 else if (t.cs() == "date") {
2228 string const date = p.verbatim_item();
2230 preamble.suppressDate(true);
2232 preamble.suppressDate(false);
2233 if (context.new_layout_allowed &&
2234 (newlayout = findLayout(context.textclass,
2237 output_command_layout(os, p, outer,
2238 context, newlayout);
2240 if (!title_layout_found)
2241 title_layout_found = newlayout->intitle;
2243 handle_ert(os, "\\date{" + date + '}',
2248 // Starred section headings
2249 // Must attempt to parse "Section*" before "Section".
2250 else if ((p.next_token().asInput() == "*") &&
2251 context.new_layout_allowed &&
2252 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2255 output_command_layout(os, p, outer, context, newlayout);
2257 if (!title_layout_found)
2258 title_layout_found = newlayout->intitle;
2261 // Section headings and the like
2262 else if (context.new_layout_allowed &&
2263 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2265 output_command_layout(os, p, outer, context, newlayout);
2267 if (!title_layout_found)
2268 title_layout_found = newlayout->intitle;
2271 else if (t.cs() == "caption") {
2273 context.check_layout(os);
2275 begin_inset(os, "Caption\n");
2276 Context newcontext(true, context.textclass);
2277 newcontext.font = context.font;
2278 newcontext.check_layout(os);
2279 if (p.next_token().cat() != catEscape &&
2280 p.next_token().character() == '[') {
2281 p.get_token(); // eat '['
2282 begin_inset(os, "Argument\n");
2283 os << "status collapsed\n";
2284 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2286 eat_whitespace(p, os, context, false);
2288 parse_text(p, os, FLAG_ITEM, outer, context);
2289 context.check_end_layout(os);
2290 // We don't need really a new paragraph, but
2291 // we must make sure that the next item gets a \begin_layout.
2292 context.new_paragraph(os);
2295 newcontext.check_end_layout(os);
2298 else if (t.cs() == "subfloat") {
2299 // the syntax is \subfloat[caption]{content}
2300 // if it is a table of figure depends on the surrounding float
2301 bool has_caption = false;
2303 // do nothing if there is no outer float
2304 if (!float_type.empty()) {
2305 context.check_layout(os);
2307 begin_inset(os, "Float " + float_type + "\n");
2309 << "\nsideways false"
2310 << "\nstatus collapsed\n\n";
2313 if (p.next_token().cat() != catEscape &&
2314 p.next_token().character() == '[') {
2315 p.get_token(); // eat '['
2316 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2320 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2321 // the caption comes always as the last
2323 // we must make sure that the caption gets a \begin_layout
2324 os << "\n\\begin_layout Plain Layout";
2326 begin_inset(os, "Caption\n");
2327 Context newcontext(true, context.textclass);
2328 newcontext.font = context.font;
2329 newcontext.check_layout(os);
2330 os << caption << "\n";
2331 newcontext.check_end_layout(os);
2332 // We don't need really a new paragraph, but
2333 // we must make sure that the next item gets a \begin_layout.
2334 //newcontext.new_paragraph(os);
2338 // We don't need really a new paragraph, but
2339 // we must make sure that the next item gets a \begin_layout.
2341 context.new_paragraph(os);
2344 context.check_end_layout(os);
2345 // close the layout we opened
2347 os << "\n\\end_layout\n";
2349 // if the float type is not supported or there is no surrounding float
2352 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2353 handle_ert(os, t.asInput() + '[' + opt_arg +
2354 "]{" + p.verbatim_item() + '}', context);
2356 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2360 else if (t.cs() == "includegraphics") {
2361 bool const clip = p.next_token().asInput() == "*";
2364 string const arg = p.getArg('[', ']');
2365 map<string, string> opts;
2366 vector<string> keys;
2367 split_map(arg, opts, keys);
2369 opts["clip"] = string();
2370 string name = normalize_filename(p.verbatim_item());
2372 string const path = getMasterFilePath();
2373 // We want to preserve relative / absolute filenames,
2374 // therefore path is only used for testing
2375 if (!makeAbsPath(name, path).exists()) {
2376 // The file extension is probably missing.
2377 // Now try to find it out.
2378 string const dvips_name =
2379 find_file(name, path,
2380 known_dvips_graphics_formats);
2381 string const pdftex_name =
2382 find_file(name, path,
2383 known_pdftex_graphics_formats);
2384 if (!dvips_name.empty()) {
2385 if (!pdftex_name.empty()) {
2386 cerr << "This file contains the "
2388 "\"\\includegraphics{"
2390 "However, files\n\""
2391 << dvips_name << "\" and\n\""
2392 << pdftex_name << "\"\n"
2393 "both exist, so I had to make a "
2394 "choice and took the first one.\n"
2395 "Please move the unwanted one "
2396 "someplace else and try again\n"
2397 "if my choice was wrong."
2401 } else if (!pdftex_name.empty()) {
2407 if (makeAbsPath(name, path).exists())
2408 fix_relative_filename(name);
2410 cerr << "Warning: Could not find graphics file '"
2411 << name << "'." << endl;
2413 context.check_layout(os);
2414 begin_inset(os, "Graphics ");
2415 os << "\n\tfilename " << name << '\n';
2416 if (opts.find("width") != opts.end())
2418 << translate_len(opts["width"]) << '\n';
2419 if (opts.find("height") != opts.end())
2421 << translate_len(opts["height"]) << '\n';
2422 if (opts.find("scale") != opts.end()) {
2423 istringstream iss(opts["scale"]);
2427 os << "\tscale " << val << '\n';
2429 if (opts.find("angle") != opts.end()) {
2430 os << "\trotateAngle "
2431 << opts["angle"] << '\n';
2432 vector<string>::const_iterator a =
2433 find(keys.begin(), keys.end(), "angle");
2434 vector<string>::const_iterator s =
2435 find(keys.begin(), keys.end(), "width");
2436 if (s == keys.end())
2437 s = find(keys.begin(), keys.end(), "height");
2438 if (s == keys.end())
2439 s = find(keys.begin(), keys.end(), "scale");
2440 if (s != keys.end() && distance(s, a) > 0)
2441 os << "\tscaleBeforeRotation\n";
2443 if (opts.find("origin") != opts.end()) {
2445 string const opt = opts["origin"];
2446 if (opt.find('l') != string::npos) ss << "left";
2447 if (opt.find('r') != string::npos) ss << "right";
2448 if (opt.find('c') != string::npos) ss << "center";
2449 if (opt.find('t') != string::npos) ss << "Top";
2450 if (opt.find('b') != string::npos) ss << "Bottom";
2451 if (opt.find('B') != string::npos) ss << "Baseline";
2452 if (!ss.str().empty())
2453 os << "\trotateOrigin " << ss.str() << '\n';
2455 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2457 if (opts.find("keepaspectratio") != opts.end())
2458 os << "\tkeepAspectRatio\n";
2459 if (opts.find("clip") != opts.end())
2461 if (opts.find("draft") != opts.end())
2463 if (opts.find("bb") != opts.end())
2464 os << "\tBoundingBox "
2465 << opts["bb"] << '\n';
2466 int numberOfbbOptions = 0;
2467 if (opts.find("bbllx") != opts.end())
2468 numberOfbbOptions++;
2469 if (opts.find("bblly") != opts.end())
2470 numberOfbbOptions++;
2471 if (opts.find("bburx") != opts.end())
2472 numberOfbbOptions++;
2473 if (opts.find("bbury") != opts.end())
2474 numberOfbbOptions++;
2475 if (numberOfbbOptions == 4)
2476 os << "\tBoundingBox "
2477 << opts["bbllx"] << " " << opts["bblly"] << " "
2478 << opts["bburx"] << " " << opts["bbury"] << '\n';
2479 else if (numberOfbbOptions > 0)
2480 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2481 numberOfbbOptions = 0;
2482 if (opts.find("natwidth") != opts.end())
2483 numberOfbbOptions++;
2484 if (opts.find("natheight") != opts.end())
2485 numberOfbbOptions++;
2486 if (numberOfbbOptions == 2)
2487 os << "\tBoundingBox 0bp 0bp "
2488 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2489 else if (numberOfbbOptions > 0)
2490 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2491 ostringstream special;
2492 if (opts.find("hiresbb") != opts.end())
2493 special << "hiresbb,";
2494 if (opts.find("trim") != opts.end())
2496 if (opts.find("viewport") != opts.end())
2497 special << "viewport=" << opts["viewport"] << ',';
2498 if (opts.find("totalheight") != opts.end())
2499 special << "totalheight=" << opts["totalheight"] << ',';
2500 if (opts.find("type") != opts.end())
2501 special << "type=" << opts["type"] << ',';
2502 if (opts.find("ext") != opts.end())
2503 special << "ext=" << opts["ext"] << ',';
2504 if (opts.find("read") != opts.end())
2505 special << "read=" << opts["read"] << ',';
2506 if (opts.find("command") != opts.end())
2507 special << "command=" << opts["command"] << ',';
2508 string s_special = special.str();
2509 if (!s_special.empty()) {
2510 // We had special arguments. Remove the trailing ','.
2511 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2513 // TODO: Handle the unknown settings better.
2514 // Warn about invalid options.
2515 // Check whether some option was given twice.
2519 else if (t.cs() == "footnote" ||
2520 (t.cs() == "thanks" && context.layout->intitle)) {
2522 context.check_layout(os);
2523 begin_inset(os, "Foot\n");
2524 os << "status collapsed\n\n";
2525 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2529 else if (t.cs() == "marginpar") {
2531 context.check_layout(os);
2532 begin_inset(os, "Marginal\n");
2533 os << "status collapsed\n\n";
2534 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2538 else if (t.cs() == "ensuremath") {
2540 context.check_layout(os);
2541 string const s = p.verbatim_item();
2542 //FIXME: this never triggers in UTF8
2543 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2546 handle_ert(os, "\\ensuremath{" + s + "}",
2550 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2551 if (title_layout_found) {
2553 skip_spaces_braces(p);
2555 handle_ert(os, t.asInput(), context);
2558 else if (t.cs() == "tableofcontents") {
2559 context.check_layout(os);
2560 begin_command_inset(os, "toc", "tableofcontents");
2562 skip_spaces_braces(p);
2565 else if (t.cs() == "listoffigures") {
2566 context.check_layout(os);
2567 begin_inset(os, "FloatList figure\n");
2569 skip_spaces_braces(p);
2572 else if (t.cs() == "listoftables") {
2573 context.check_layout(os);
2574 begin_inset(os, "FloatList table\n");
2576 skip_spaces_braces(p);
2579 else if (t.cs() == "listof") {
2580 p.skip_spaces(true);
2581 string const name = p.get_token().cs();
2582 if (context.textclass.floats().typeExist(name)) {
2583 context.check_layout(os);
2584 begin_inset(os, "FloatList ");
2587 p.get_token(); // swallow second arg
2589 handle_ert(os, "\\listof{" + name + "}", context);
2592 else if (t.cs() == "textrm")
2593 parse_text_attributes(p, os, FLAG_ITEM, outer,
2594 context, "\\family",
2595 context.font.family, "roman");
2597 else if (t.cs() == "textsf")
2598 parse_text_attributes(p, os, FLAG_ITEM, outer,
2599 context, "\\family",
2600 context.font.family, "sans");
2602 else if (t.cs() == "texttt")
2603 parse_text_attributes(p, os, FLAG_ITEM, outer,
2604 context, "\\family",
2605 context.font.family, "typewriter");
2607 else if (t.cs() == "textmd")
2608 parse_text_attributes(p, os, FLAG_ITEM, outer,
2609 context, "\\series",
2610 context.font.series, "medium");
2612 else if (t.cs() == "textbf")
2613 parse_text_attributes(p, os, FLAG_ITEM, outer,
2614 context, "\\series",
2615 context.font.series, "bold");
2617 else if (t.cs() == "textup")
2618 parse_text_attributes(p, os, FLAG_ITEM, outer,
2620 context.font.shape, "up");
2622 else if (t.cs() == "textit")
2623 parse_text_attributes(p, os, FLAG_ITEM, outer,
2625 context.font.shape, "italic");
2627 else if (t.cs() == "textsl")
2628 parse_text_attributes(p, os, FLAG_ITEM, outer,
2630 context.font.shape, "slanted");
2632 else if (t.cs() == "textsc")
2633 parse_text_attributes(p, os, FLAG_ITEM, outer,
2635 context.font.shape, "smallcaps");
2637 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2638 context.check_layout(os);
2639 TeXFont oldFont = context.font;
2640 context.font.init();
2641 context.font.size = oldFont.size;
2642 os << "\n\\family " << context.font.family << "\n";
2643 os << "\n\\series " << context.font.series << "\n";
2644 os << "\n\\shape " << context.font.shape << "\n";
2645 if (t.cs() == "textnormal") {
2646 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2647 output_font_change(os, context.font, oldFont);
2648 context.font = oldFont;
2650 eat_whitespace(p, os, context, false);
2653 else if (t.cs() == "textcolor") {
2654 // scheme is \textcolor{color name}{text}
2655 string const color = p.verbatim_item();
2656 // we only support the predefined colors of the color package
2657 if (color == "black" || color == "blue" || color == "cyan"
2658 || color == "green" || color == "magenta" || color == "red"
2659 || color == "white" || color == "yellow") {
2660 context.check_layout(os);
2661 os << "\n\\color " << color << "\n";
2662 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2663 context.check_layout(os);
2664 os << "\n\\color inherit\n";
2665 preamble.registerAutomaticallyLoadedPackage("color");
2667 // for custom defined colors
2668 handle_ert(os, t.asInput() + "{" + color + "}", context);
2671 else if (t.cs() == "underbar" || t.cs() == "uline") {
2672 // \underbar is not 100% correct (LyX outputs \uline
2673 // of ulem.sty). The difference is that \ulem allows
2674 // line breaks, and \underbar does not.
2675 // Do NOT handle \underline.
2676 // \underbar cuts through y, g, q, p etc.,
2677 // \underline does not.
2678 context.check_layout(os);
2679 os << "\n\\bar under\n";
2680 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2681 context.check_layout(os);
2682 os << "\n\\bar default\n";
2683 preamble.registerAutomaticallyLoadedPackage("ulem");
2686 else if (t.cs() == "sout") {
2687 context.check_layout(os);
2688 os << "\n\\strikeout on\n";
2689 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2690 context.check_layout(os);
2691 os << "\n\\strikeout default\n";
2692 preamble.registerAutomaticallyLoadedPackage("ulem");
2695 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
2696 t.cs() == "emph" || t.cs() == "noun") {
2697 context.check_layout(os);
2698 os << "\n\\" << t.cs() << " on\n";
2699 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2700 context.check_layout(os);
2701 os << "\n\\" << t.cs() << " default\n";
2702 if (t.cs() == "uuline" || t.cs() == "uwave")
2703 preamble.registerAutomaticallyLoadedPackage("ulem");
2706 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
2707 t.cs() == "vphantom") {
2708 context.check_layout(os);
2709 if (t.cs() == "phantom")
2710 begin_inset(os, "Phantom Phantom\n");
2711 if (t.cs() == "hphantom")
2712 begin_inset(os, "Phantom HPhantom\n");
2713 if (t.cs() == "vphantom")
2714 begin_inset(os, "Phantom VPhantom\n");
2715 os << "status open\n";
2716 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
2721 else if (t.cs() == "href") {
2722 context.check_layout(os);
2723 string target = p.getArg('{', '}');
2724 string name = p.getArg('{', '}');
2726 size_t i = target.find(':');
2727 if (i != string::npos) {
2728 type = target.substr(0, i + 1);
2729 if (type == "mailto:" || type == "file:")
2730 target = target.substr(i + 1);
2731 // handle the case that name is equal to target, except of "http://"
2732 else if (target.substr(i + 3) == name && type == "http:")
2735 begin_command_inset(os, "href", "href");
2737 os << "name \"" << name << "\"\n";
2738 os << "target \"" << target << "\"\n";
2739 if (type == "mailto:" || type == "file:")
2740 os << "type \"" << type << "\"\n";
2742 skip_spaces_braces(p);
2745 else if (t.cs() == "lyxline") {
2746 // swallow size argument (it is not used anyway)
2748 if (!context.atParagraphStart()) {
2749 // so our line is in the middle of a paragraph
2750 // we need to add a new line, lest this line
2751 // follow the other content on that line and
2752 // run off the side of the page
2753 // FIXME: This may create an empty paragraph,
2754 // but without that it would not be
2755 // possible to set noindent below.
2756 // Fortunately LaTeX does not care
2757 // about the empty paragraph.
2758 context.new_paragraph(os);
2760 if (preamble.indentParagraphs()) {
2761 // we need to unindent, lest the line be too long
2762 context.add_par_extra_stuff("\\noindent\n");
2764 context.check_layout(os);
2765 begin_command_inset(os, "line", "rule");
2766 os << "offset \"0.5ex\"\n"
2767 "width \"100line%\"\n"
2772 else if (t.cs() == "rule") {
2773 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
2774 string const width = p.getArg('{', '}');
2775 string const thickness = p.getArg('{', '}');
2776 context.check_layout(os);
2777 begin_command_inset(os, "line", "rule");
2778 if (!offset.empty())
2779 os << "offset \"" << translate_len(offset) << "\"\n";
2780 os << "width \"" << translate_len(width) << "\"\n"
2781 "height \"" << translate_len(thickness) << "\"\n";
2785 else if (is_known(t.cs(), known_phrases) ||
2786 (t.cs() == "protect" &&
2787 p.next_token().cat() == catEscape &&
2788 is_known(p.next_token().cs(), known_phrases))) {
2789 // LyX sometimes puts a \protect in front, so we have to ignore it
2790 // FIXME: This needs to be changed when bug 4752 is fixed.
2791 char const * const * where = is_known(
2792 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
2794 context.check_layout(os);
2795 os << known_coded_phrases[where - known_phrases];
2796 skip_spaces_braces(p);
2799 else if (is_known(t.cs(), known_ref_commands)) {
2800 string const opt = p.getOpt();
2802 context.check_layout(os);
2803 char const * const * where = is_known(t.cs(),
2804 known_ref_commands);
2805 begin_command_inset(os, "ref",
2806 known_coded_ref_commands[where - known_ref_commands]);
2807 os << "reference \""
2808 << convert_command_inset_arg(p.verbatim_item())
2812 // LyX does not support optional arguments of ref commands
2813 handle_ert(os, t.asInput() + '[' + opt + "]{" +
2814 p.verbatim_item() + "}", context);
2818 else if (use_natbib &&
2819 is_known(t.cs(), known_natbib_commands) &&
2820 ((t.cs() != "citefullauthor" &&
2821 t.cs() != "citeyear" &&
2822 t.cs() != "citeyearpar") ||
2823 p.next_token().asInput() != "*")) {
2824 context.check_layout(os);
2825 string command = t.cs();
2826 if (p.next_token().asInput() == "*") {
2830 if (command == "citefullauthor")
2831 // alternative name for "\\citeauthor*"
2832 command = "citeauthor*";
2834 // text before the citation
2836 // text after the citation
2838 get_cite_arguments(p, true, before, after);
2840 if (command == "cite") {
2841 // \cite without optional argument means
2842 // \citet, \cite with at least one optional
2843 // argument means \citep.
2844 if (before.empty() && after.empty())
2849 if (before.empty() && after == "[]")
2850 // avoid \citet[]{a}
2852 else if (before == "[]" && after == "[]") {
2853 // avoid \citet[][]{a}
2857 // remove the brackets around after and before
2858 if (!after.empty()) {
2860 after.erase(after.length() - 1, 1);
2861 after = convert_command_inset_arg(after);
2863 if (!before.empty()) {
2865 before.erase(before.length() - 1, 1);
2866 before = convert_command_inset_arg(before);
2868 begin_command_inset(os, "citation", command);
2869 os << "after " << '"' << after << '"' << "\n";
2870 os << "before " << '"' << before << '"' << "\n";
2872 << convert_command_inset_arg(p.verbatim_item())
2877 else if (use_jurabib &&
2878 is_known(t.cs(), known_jurabib_commands) &&
2879 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
2880 context.check_layout(os);
2881 string command = t.cs();
2882 if (p.next_token().asInput() == "*") {
2886 char argumentOrder = '\0';
2887 vector<string> const options =
2888 preamble.getPackageOptions("jurabib");
2889 if (find(options.begin(), options.end(),
2890 "natbiborder") != options.end())
2891 argumentOrder = 'n';
2892 else if (find(options.begin(), options.end(),
2893 "jurabiborder") != options.end())
2894 argumentOrder = 'j';
2896 // text before the citation
2898 // text after the citation
2900 get_cite_arguments(p, argumentOrder != 'j', before, after);
2902 string const citation = p.verbatim_item();
2903 if (!before.empty() && argumentOrder == '\0') {
2904 cerr << "Warning: Assuming argument order "
2905 "of jurabib version 0.6 for\n'"
2906 << command << before << after << '{'
2907 << citation << "}'.\n"
2908 "Add 'jurabiborder' to the jurabib "
2909 "package options if you used an\n"
2910 "earlier jurabib version." << endl;
2912 if (!after.empty()) {
2914 after.erase(after.length() - 1, 1);
2916 if (!before.empty()) {
2918 before.erase(before.length() - 1, 1);
2920 begin_command_inset(os, "citation", command);
2921 os << "after " << '"' << after << '"' << "\n";
2922 os << "before " << '"' << before << '"' << "\n";
2923 os << "key " << '"' << citation << '"' << "\n";
2927 else if (t.cs() == "cite"
2928 || t.cs() == "nocite") {
2929 context.check_layout(os);
2930 string after = convert_command_inset_arg(p.getArg('[', ']'));
2931 string key = convert_command_inset_arg(p.verbatim_item());
2932 // store the case that it is "\nocite{*}" to use it later for
2935 begin_command_inset(os, "citation", t.cs());
2936 os << "after " << '"' << after << '"' << "\n";
2937 os << "key " << '"' << key << '"' << "\n";
2939 } else if (t.cs() == "nocite")
2943 else if (t.cs() == "index") {
2944 context.check_layout(os);
2945 begin_inset(os, "Index idx\n");
2946 os << "status collapsed\n";
2947 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
2951 else if (t.cs() == "nomenclature") {
2952 context.check_layout(os);
2953 begin_command_inset(os, "nomenclature", "nomenclature");
2954 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
2955 if (!prefix.empty())
2956 os << "prefix " << '"' << prefix << '"' << "\n";
2957 os << "symbol " << '"'
2958 << convert_command_inset_arg(p.verbatim_item());
2959 os << "\"\ndescription \""
2960 << convert_command_inset_arg(p.verbatim_item())
2965 else if (t.cs() == "label") {
2966 context.check_layout(os);
2967 begin_command_inset(os, "label", "label");
2969 << convert_command_inset_arg(p.verbatim_item())
2974 else if (t.cs() == "printindex") {
2975 context.check_layout(os);
2976 begin_command_inset(os, "index_print", "printindex");
2977 os << "type \"idx\"\n";
2979 skip_spaces_braces(p);
2982 else if (t.cs() == "printnomenclature") {
2984 string width_type = "";
2985 context.check_layout(os);
2986 begin_command_inset(os, "nomencl_print", "printnomenclature");
2987 // case of a custom width
2989 width = p.getArg('[', ']');
2990 width = translate_len(width);
2991 width_type = "custom";
2993 // case of no custom width
2994 // the case of no custom width but the width set
2995 // via \settowidth{\nomlabelwidth}{***} cannot be supported
2996 // because the user could have set anything, not only the width
2997 // of the longest label (which would be width_type = "auto")
2998 string label = convert_command_inset_arg(p.getArg('{', '}'));
2999 if (label.empty() && width_type.empty())
3000 width_type = "none";
3001 os << "set_width \"" << width_type << "\"\n";
3002 if (width_type == "custom")
3003 os << "width \"" << width << '\"';
3005 skip_spaces_braces(p);
3008 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3009 context.check_layout(os);
3010 begin_inset(os, "script ");
3011 os << t.cs().substr(4) << '\n';
3012 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3014 if (t.cs() == "textsubscript")
3015 preamble.registerAutomaticallyLoadedPackage("subscript");
3018 else if (is_known(t.cs(), known_quotes)) {
3019 char const * const * where = is_known(t.cs(), known_quotes);
3020 context.check_layout(os);
3021 begin_inset(os, "Quotes ");
3022 os << known_coded_quotes[where - known_quotes];
3024 // LyX adds {} after the quote, so we have to eat
3025 // spaces here if there are any before a possible
3027 eat_whitespace(p, os, context, false);
3031 else if (is_known(t.cs(), known_sizes) &&
3032 context.new_layout_allowed) {
3033 char const * const * where = is_known(t.cs(), known_sizes);
3034 context.check_layout(os);
3035 TeXFont const oldFont = context.font;
3036 context.font.size = known_coded_sizes[where - known_sizes];
3037 output_font_change(os, oldFont, context.font);
3038 eat_whitespace(p, os, context, false);
3041 else if (is_known(t.cs(), known_font_families) &&
3042 context.new_layout_allowed) {
3043 char const * const * where =
3044 is_known(t.cs(), known_font_families);
3045 context.check_layout(os);
3046 TeXFont const oldFont = context.font;
3047 context.font.family =
3048 known_coded_font_families[where - known_font_families];
3049 output_font_change(os, oldFont, context.font);
3050 eat_whitespace(p, os, context, false);
3053 else if (is_known(t.cs(), known_font_series) &&
3054 context.new_layout_allowed) {
3055 char const * const * where =
3056 is_known(t.cs(), known_font_series);
3057 context.check_layout(os);
3058 TeXFont const oldFont = context.font;
3059 context.font.series =
3060 known_coded_font_series[where - known_font_series];
3061 output_font_change(os, oldFont, context.font);
3062 eat_whitespace(p, os, context, false);
3065 else if (is_known(t.cs(), known_font_shapes) &&
3066 context.new_layout_allowed) {
3067 char const * const * where =
3068 is_known(t.cs(), known_font_shapes);
3069 context.check_layout(os);
3070 TeXFont const oldFont = context.font;
3071 context.font.shape =
3072 known_coded_font_shapes[where - known_font_shapes];
3073 output_font_change(os, oldFont, context.font);
3074 eat_whitespace(p, os, context, false);
3076 else if (is_known(t.cs(), known_old_font_families) &&
3077 context.new_layout_allowed) {
3078 char const * const * where =
3079 is_known(t.cs(), known_old_font_families);
3080 context.check_layout(os);
3081 TeXFont const oldFont = context.font;
3082 context.font.init();
3083 context.font.size = oldFont.size;
3084 context.font.family =
3085 known_coded_font_families[where - known_old_font_families];
3086 output_font_change(os, oldFont, context.font);
3087 eat_whitespace(p, os, context, false);
3090 else if (is_known(t.cs(), known_old_font_series) &&
3091 context.new_layout_allowed) {
3092 char const * const * where =
3093 is_known(t.cs(), known_old_font_series);
3094 context.check_layout(os);
3095 TeXFont const oldFont = context.font;
3096 context.font.init();
3097 context.font.size = oldFont.size;
3098 context.font.series =
3099 known_coded_font_series[where - known_old_font_series];
3100 output_font_change(os, oldFont, context.font);
3101 eat_whitespace(p, os, context, false);
3104 else if (is_known(t.cs(), known_old_font_shapes) &&
3105 context.new_layout_allowed) {
3106 char const * const * where =
3107 is_known(t.cs(), known_old_font_shapes);
3108 context.check_layout(os);
3109 TeXFont const oldFont = context.font;
3110 context.font.init();
3111 context.font.size = oldFont.size;
3112 context.font.shape =
3113 known_coded_font_shapes[where - known_old_font_shapes];
3114 output_font_change(os, oldFont, context.font);
3115 eat_whitespace(p, os, context, false);
3118 else if (t.cs() == "selectlanguage") {
3119 context.check_layout(os);
3120 // save the language for the case that a
3121 // \foreignlanguage is used
3123 context.font.language = babel2lyx(p.verbatim_item());
3124 os << "\n\\lang " << context.font.language << "\n";
3127 else if (t.cs() == "foreignlanguage") {
3128 string const lang = babel2lyx(p.verbatim_item());
3129 parse_text_attributes(p, os, FLAG_ITEM, outer,
3131 context.font.language, lang);
3134 else if (t.cs() == "inputencoding") {
3135 // nothing to write here
3136 string const enc = subst(p.verbatim_item(), "\n", " ");
3140 else if (t.cs() == "ldots") {
3141 context.check_layout(os);
3142 os << "\\SpecialChar \\ldots{}\n";
3143 skip_spaces_braces(p);
3146 else if (t.cs() == "lyxarrow") {
3147 context.check_layout(os);
3148 os << "\\SpecialChar \\menuseparator\n";
3149 skip_spaces_braces(p);
3152 else if (t.cs() == "textcompwordmark") {
3153 context.check_layout(os);
3154 os << "\\SpecialChar \\textcompwordmark{}\n";
3155 skip_spaces_braces(p);
3158 else if (t.cs() == "slash") {
3159 context.check_layout(os);
3160 os << "\\SpecialChar \\slash{}\n";
3161 skip_spaces_braces(p);
3164 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3165 context.check_layout(os);
3166 os << "\\SpecialChar \\nobreakdash-\n";
3170 else if (t.cs() == "textquotedbl") {
3171 context.check_layout(os);
3176 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3177 context.check_layout(os);
3178 os << "\\SpecialChar \\@.\n";
3182 else if (t.cs() == "-") {
3183 context.check_layout(os);
3184 os << "\\SpecialChar \\-\n";
3187 else if (t.cs() == "textasciitilde") {
3188 context.check_layout(os);
3190 skip_spaces_braces(p);
3193 else if (t.cs() == "textasciicircum") {
3194 context.check_layout(os);
3196 skip_spaces_braces(p);
3199 else if (t.cs() == "textbackslash") {
3200 context.check_layout(os);
3201 os << "\n\\backslash\n";
3202 skip_spaces_braces(p);
3205 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3206 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3208 context.check_layout(os);
3212 else if (t.cs() == "char") {
3213 context.check_layout(os);
3214 if (p.next_token().character() == '`') {
3216 if (p.next_token().cs() == "\"") {
3221 handle_ert(os, "\\char`", context);
3224 handle_ert(os, "\\char", context);
3228 else if (t.cs() == "verb") {
3229 context.check_layout(os);
3230 char const delimiter = p.next_token().character();
3231 string const arg = p.getArg(delimiter, delimiter);
3233 oss << "\\verb" << delimiter << arg << delimiter;
3234 handle_ert(os, oss.str(), context);
3237 // Problem: \= creates a tabstop inside the tabbing environment
3238 // and else an accent. In the latter case we really would want
3239 // \={o} instead of \= o.
3240 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3241 handle_ert(os, t.asInput(), context);
3243 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3244 else if (t.cs().size() == 1
3245 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3246 context.check_layout(os);
3247 // try to see whether the string is in unicodesymbols
3249 string command = t.asInput() + "{"
3250 + trimSpaceAndEol(p.verbatim_item())
3252 docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
3255 cerr << "When parsing " << command
3256 << ", result is " << to_utf8(s)
3257 << "+" << to_utf8(rem) << endl;
3260 // we did not find a non-ert version
3261 handle_ert(os, command, context);
3264 else if (t.cs() == "\\") {
3265 context.check_layout(os);
3267 handle_ert(os, "\\\\" + p.getOpt(), context);
3268 else if (p.next_token().asInput() == "*") {
3270 // getOpt() eats the following space if there
3271 // is no optional argument, but that is OK
3272 // here since it has no effect in the output.
3273 handle_ert(os, "\\\\*" + p.getOpt(), context);
3276 begin_inset(os, "Newline newline");
3281 else if (t.cs() == "newline" ||
3282 (t.cs() == "linebreak" && !p.hasOpt())) {
3283 context.check_layout(os);
3284 begin_inset(os, "Newline ");
3287 skip_spaces_braces(p);
3290 else if (t.cs() == "input" || t.cs() == "include"
3291 || t.cs() == "verbatiminput") {
3292 string name = t.cs();
3293 if (t.cs() == "verbatiminput"
3294 && p.next_token().asInput() == "*")
3295 name += p.get_token().asInput();
3296 context.check_layout(os);
3297 string filename(normalize_filename(p.getArg('{', '}')));
3298 string const path = getMasterFilePath();
3299 // We want to preserve relative / absolute filenames,
3300 // therefore path is only used for testing
3301 if ((t.cs() == "include" || t.cs() == "input") &&
3302 !makeAbsPath(filename, path).exists()) {
3303 // The file extension is probably missing.
3304 // Now try to find it out.
3305 string const tex_name =
3306 find_file(filename, path,
3307 known_tex_extensions);
3308 if (!tex_name.empty())
3309 filename = tex_name;
3311 bool external = false;
3313 if (makeAbsPath(filename, path).exists()) {
3314 string const abstexname =
3315 makeAbsPath(filename, path).absFileName();
3316 string const abslyxname =
3317 changeExtension(abstexname, ".lyx");
3318 string const absfigname =
3319 changeExtension(abstexname, ".fig");
3320 fix_relative_filename(filename);
3321 string const lyxname =
3322 changeExtension(filename, ".lyx");
3324 external = FileName(absfigname).exists();
3325 if (t.cs() == "input") {
3326 string const ext = getExtension(abstexname);
3328 // Combined PS/LaTeX:
3329 // x.eps, x.pstex_t (old xfig)
3330 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3331 FileName const absepsname(
3332 changeExtension(abstexname, ".eps"));
3333 FileName const abspstexname(
3334 changeExtension(abstexname, ".pstex"));
3335 bool const xfigeps =
3336 (absepsname.exists() ||
3337 abspstexname.exists()) &&
3340 // Combined PDF/LaTeX:
3341 // x.pdf, x.pdftex_t (old xfig)
3342 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3343 FileName const abspdfname(
3344 changeExtension(abstexname, ".pdf"));
3345 bool const xfigpdf =
3346 abspdfname.exists() &&
3347 (ext == "pdftex_t" || ext == "pdf_t");
3351 // Combined PS/PDF/LaTeX:
3352 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3353 string const absbase2(
3354 removeExtension(abstexname) + "_pspdftex");
3355 FileName const abseps2name(
3356 addExtension(absbase2, ".eps"));
3357 FileName const abspdf2name(
3358 addExtension(absbase2, ".pdf"));
3359 bool const xfigboth =
3360 abspdf2name.exists() &&
3361 abseps2name.exists() && ext == "pspdftex";
3363 xfig = xfigpdf || xfigeps || xfigboth;
3364 external = external && xfig;
3367 outname = changeExtension(filename, ".fig");
3369 // Don't try to convert, the result
3370 // would be full of ERT.
3372 } else if (t.cs() != "verbatiminput" &&
3373 tex2lyx(abstexname, FileName(abslyxname),
3380 cerr << "Warning: Could not find included file '"
3381 << filename << "'." << endl;
3385 begin_inset(os, "External\n");
3386 os << "\ttemplate XFig\n"
3387 << "\tfilename " << outname << '\n';
3389 begin_command_inset(os, "include", name);
3390 os << "preview false\n"
3391 "filename \"" << outname << "\"\n";
3396 else if (t.cs() == "bibliographystyle") {
3397 // store new bibliographystyle
3398 bibliographystyle = p.verbatim_item();
3399 // If any other command than \bibliography and
3400 // \nocite{*} follows, we need to output the style
3401 // (because it might be used by that command).
3402 // Otherwise, it will automatically be output by LyX.
3405 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3406 if (t2.cat() == catBegin)
3408 if (t2.cat() != catEscape)
3410 if (t2.cs() == "nocite") {
3411 if (p.getArg('{', '}') == "*")
3413 } else if (t2.cs() == "bibliography")
3420 "\\bibliographystyle{" + bibliographystyle + '}',
3425 else if (t.cs() == "bibliography") {
3426 context.check_layout(os);
3427 begin_command_inset(os, "bibtex", "bibtex");
3428 if (!btprint.empty()) {
3429 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3430 // clear the string because the next BibTeX inset can be without the
3431 // \nocite{*} option
3434 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3435 // Do we have a bibliographystyle set?
3436 if (!bibliographystyle.empty())
3437 os << "options " << '"' << bibliographystyle << '"' << "\n";
3441 else if (t.cs() == "parbox") {
3442 // Test whether this is an outer box of a shaded box
3444 // swallow arguments
3445 while (p.hasOpt()) {
3447 p.skip_spaces(true);
3450 p.skip_spaces(true);
3452 if (p.next_token().cat() == catBegin)
3454 p.skip_spaces(true);
3455 Token to = p.get_token();
3456 bool shaded = false;
3457 if (to.asInput() == "\\begin") {
3458 p.skip_spaces(true);
3459 if (p.getArg('{', '}') == "shaded")
3464 parse_outer_box(p, os, FLAG_ITEM, outer,
3465 context, "parbox", "shaded");
3467 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3471 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3472 t.cs() == "shadowbox" || t.cs() == "doublebox")
3473 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3475 else if (t.cs() == "framebox") {
3476 string special = p.getFullOpt();
3477 special += p.getOpt();
3478 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), special);
3481 //\makebox() is part of the picture environment and different from \makebox{}
3482 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
3483 else if (t.cs() == "makebox") {
3484 string arg = t.asInput();
3485 if (p.next_token().character() == '(')
3486 //the syntax is: \makebox(x,y)[position]{content}
3487 arg += p.getFullParentheseArg();
3489 //the syntax is: \makebox[width][position]{content}
3490 arg += p.getFullOpt();
3491 handle_ert(os, arg + p.getFullOpt(), context);
3494 else if (t.cs() == "smallskip" ||
3495 t.cs() == "medskip" ||
3496 t.cs() == "bigskip" ||
3497 t.cs() == "vfill") {
3498 context.check_layout(os);
3499 begin_inset(os, "VSpace ");
3502 skip_spaces_braces(p);
3505 else if (is_known(t.cs(), known_spaces)) {
3506 char const * const * where = is_known(t.cs(), known_spaces);
3507 context.check_layout(os);
3508 begin_inset(os, "space ");
3509 os << '\\' << known_coded_spaces[where - known_spaces]
3512 // LaTeX swallows whitespace after all spaces except
3513 // "\\,". We have to do that here, too, because LyX
3514 // adds "{}" which would make the spaces significant.
3516 eat_whitespace(p, os, context, false);
3517 // LyX adds "{}" after all spaces except "\\ " and
3518 // "\\,", so we have to remove "{}".
3519 // "\\,{}" is equivalent to "\\," in LaTeX, so we
3520 // remove the braces after "\\,", too.
3525 else if (t.cs() == "newpage" ||
3526 (t.cs() == "pagebreak" && !p.hasOpt()) ||
3527 t.cs() == "clearpage" ||
3528 t.cs() == "cleardoublepage") {
3529 context.check_layout(os);
3530 begin_inset(os, "Newpage ");
3533 skip_spaces_braces(p);
3536 else if (t.cs() == "DeclareRobustCommand" ||
3537 t.cs() == "DeclareRobustCommandx" ||
3538 t.cs() == "newcommand" ||
3539 t.cs() == "newcommandx" ||
3540 t.cs() == "providecommand" ||
3541 t.cs() == "providecommandx" ||
3542 t.cs() == "renewcommand" ||
3543 t.cs() == "renewcommandx") {
3544 // DeclareRobustCommand, DeclareRobustCommandx,
3545 // providecommand and providecommandx could be handled
3546 // by parse_command(), but we need to call
3547 // add_known_command() here.
3548 string name = t.asInput();
3549 if (p.next_token().asInput() == "*") {
3550 // Starred form. Eat '*'
3554 string const command = p.verbatim_item();
3555 string const opt1 = p.getFullOpt();
3556 string const opt2 = p.getFullOpt();
3557 add_known_command(command, opt1, !opt2.empty());
3558 string const ert = name + '{' + command + '}' +
3560 '{' + p.verbatim_item() + '}';
3562 if (t.cs() == "DeclareRobustCommand" ||
3563 t.cs() == "DeclareRobustCommandx" ||
3564 t.cs() == "providecommand" ||
3565 t.cs() == "providecommandx" ||
3566 name[name.length()-1] == '*')
3567 handle_ert(os, ert, context);
3569 context.check_layout(os);
3570 begin_inset(os, "FormulaMacro");
3576 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3577 // let could be handled by parse_command(),
3578 // but we need to call add_known_command() here.
3579 string ert = t.asInput();
3582 if (p.next_token().cat() == catBegin) {
3583 name = p.verbatim_item();
3584 ert += '{' + name + '}';
3586 name = p.verbatim_item();
3591 if (p.next_token().cat() == catBegin) {
3592 command = p.verbatim_item();
3593 ert += '{' + command + '}';
3595 command = p.verbatim_item();
3598 // If command is known, make name known too, to parse
3599 // its arguments correctly. For this reason we also
3600 // have commands in syntax.default that are hardcoded.
3601 CommandMap::iterator it = known_commands.find(command);
3602 if (it != known_commands.end())
3603 known_commands[t.asInput()] = it->second;
3604 handle_ert(os, ert, context);
3607 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3608 bool starred = false;
3609 if (p.next_token().asInput() == "*") {
3613 string name = t.asInput();
3614 string const length = p.verbatim_item();
3617 bool valid = splitLatexLength(length, valstring, unit);
3618 bool known_hspace = false;
3619 bool known_vspace = false;
3620 bool known_unit = false;
3623 istringstream iss(valstring);
3626 if (t.cs()[0] == 'h') {
3627 if (unit == "\\fill") {
3632 known_hspace = true;
3635 if (unit == "\\smallskipamount") {
3637 known_vspace = true;
3638 } else if (unit == "\\medskipamount") {
3640 known_vspace = true;
3641 } else if (unit == "\\bigskipamount") {
3643 known_vspace = true;
3644 } else if (unit == "\\fill") {
3646 known_vspace = true;
3650 if (!known_hspace && !known_vspace) {
3651 switch (unitFromString(unit)) {
3672 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3673 // Literal horizontal length or known variable
3674 context.check_layout(os);
3675 begin_inset(os, "space ");
3683 if (known_unit && !known_hspace)
3685 << translate_len(length);
3687 } else if (known_unit || known_vspace) {
3688 // Literal vertical length or known variable
3689 context.check_layout(os);
3690 begin_inset(os, "VSpace ");
3698 // LyX can't handle other length variables in Inset VSpace/space
3703 handle_ert(os, name + '{' + unit + '}', context);
3704 else if (value == -1.0)
3705 handle_ert(os, name + "{-" + unit + '}', context);
3707 handle_ert(os, name + '{' + valstring + unit + '}', context);
3709 handle_ert(os, name + '{' + length + '}', context);
3713 // The single '=' is meant here.
3714 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3716 context.check_layout(os);
3717 begin_inset(os, "Flex ");
3718 os << to_utf8(newinsetlayout->name()) << '\n'
3719 << "status collapsed\n";
3720 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3725 // try to see whether the string is in unicodesymbols
3726 // Only use text mode commands, since we are in text mode here,
3727 // and math commands may be invalid (bug 6797)
3729 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
3730 rem, Encodings::TEXT_CMD);
3733 cerr << "When parsing " << t.cs()
3734 << ", result is " << to_utf8(s)
3735 << "+" << to_utf8(rem) << endl;
3736 context.check_layout(os);
3738 skip_spaces_braces(p);
3740 //cerr << "#: " << t << " mode: " << mode << endl;
3741 // heuristic: read up to next non-nested space
3743 string s = t.asInput();
3744 string z = p.verbatim_item();
3745 while (p.good() && z != " " && z.size()) {
3746 //cerr << "read: " << z << endl;
3748 z = p.verbatim_item();
3750 cerr << "found ERT: " << s << endl;
3751 handle_ert(os, s + ' ', context);
3754 string name = t.asInput();
3755 if (p.next_token().asInput() == "*") {
3756 // Starred commands like \vspace*{}
3757 p.get_token(); // Eat '*'
3760 if (!parse_command(name, p, os, outer, context))
3761 handle_ert(os, name, context);
3765 if (flags & FLAG_LEAVE) {
3766 flags &= ~FLAG_LEAVE;