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"
25 #include "support/lassert.h"
26 #include "support/convert.h"
27 #include "support/FileName.h"
28 #include "support/filetools.h"
29 #include "support/lstrings.h"
38 using namespace lyx::support;
43 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
44 Context const & context, InsetLayout const * layout)
46 bool const forcePlainLayout =
47 layout ? layout->forcePlainLayout() : false;
48 Context newcontext(true, context.textclass);
50 newcontext.layout = &context.textclass.plainLayout();
52 newcontext.font = context.font;
53 parse_text(p, os, flags, outer, newcontext);
54 newcontext.check_end_layout(os);
60 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
61 Context const & context, string const & name)
63 InsetLayout const * layout = 0;
64 DocumentClass::InsetLayouts::const_iterator it =
65 context.textclass.insetLayouts().find(from_ascii(name));
66 if (it != context.textclass.insetLayouts().end())
67 layout = &(it->second);
68 parse_text_in_inset(p, os, flags, outer, context, layout);
71 /// parses a paragraph snippet, useful for example for \\emph{...}
72 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
75 Context newcontext(context);
76 // Don't inherit the paragraph-level extra stuff
77 newcontext.par_extra_stuff.clear();
78 parse_text(p, os, flags, outer, newcontext);
79 // Make sure that we don't create invalid .lyx files
80 context.need_layout = newcontext.need_layout;
81 context.need_end_layout = newcontext.need_end_layout;
86 * Thin wrapper around parse_text_snippet() using a string.
88 * We completely ignore \c context.need_layout and \c context.need_end_layout,
89 * because our return value is not used directly (otherwise the stream version
90 * of parse_text_snippet() could be used). That means that the caller needs
91 * to do layout management manually.
92 * This is intended to parse text that does not create any layout changes.
94 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
97 Context newcontext(context);
98 newcontext.need_layout = false;
99 newcontext.need_end_layout = false;
100 newcontext.new_layout_allowed = false;
101 // Avoid warning by Context::~Context()
102 newcontext.par_extra_stuff.clear();
104 parse_text_snippet(p, os, flags, outer, newcontext);
109 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
110 "vpageref", "prettyref", "eqref", 0 };
112 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
113 "vpageref", "formatted", "eqref", 0 };
117 * The starred forms are also known except for "citefullauthor",
118 * "citeyear" and "citeyearpar".
120 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
121 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
122 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
126 * No starred form other than "cite*" known.
128 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
129 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
130 // jurabib commands not (yet) supported by LyX:
132 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
133 // "footciteauthor", "footciteyear", "footciteyearpar",
134 "citefield", "citetitle", 0 };
136 /// LaTeX names for quotes
137 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
138 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
139 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
140 "guilsinglleft", "frq", "guilsinglright", 0};
142 /// the same as known_quotes with .lyx names
143 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
144 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
145 "gld", "grd", "gls", "ers", "fls",
146 "fls", "frs", "frs", 0};
148 /// LaTeX names for font sizes
149 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
150 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
152 /// the same as known_sizes with .lyx names
153 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
154 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
156 /// LaTeX 2.09 names for font families
157 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
159 /// LaTeX names for font families
160 char const * const known_font_families[] = { "rmfamily", "sffamily",
163 /// the same as known_old_font_families and known_font_families with .lyx names
164 char const * const known_coded_font_families[] = { "roman", "sans",
167 /// LaTeX 2.09 names for font series
168 char const * const known_old_font_series[] = { "bf", 0};
170 /// LaTeX names for font series
171 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
173 /// the same as known_old_font_series and known_font_series with .lyx names
174 char const * const known_coded_font_series[] = { "bold", "medium", 0};
176 /// LaTeX 2.09 names for font shapes
177 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
179 /// LaTeX names for font shapes
180 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
183 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
184 char const * const known_coded_font_shapes[] = { "italic", "slanted",
185 "smallcaps", "up", 0};
188 * Graphics file extensions known by the dvips driver of the graphics package.
189 * These extensions are used to complete the filename of an included
190 * graphics file if it does not contain an extension.
191 * The order must be the same that latex uses to find a file, because we
192 * will use the first extension that matches.
193 * This is only an approximation for the common cases. If we would want to
194 * do it right in all cases, we would need to know which graphics driver is
195 * used and know the extensions of every driver of the graphics package.
197 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
198 "ps.gz", "eps.Z", "ps.Z", 0};
201 * Graphics file extensions known by the pdftex driver of the graphics package.
202 * \sa known_dvips_graphics_formats
204 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
208 * Known file extensions for TeX files as used by \\include.
210 char const * const known_tex_extensions[] = {"tex", 0};
212 /// spaces known by InsetSpace
213 char const * const known_spaces[] = { " ", "space", ",",
214 "thinspace", "quad", "qquad", "enspace", "enskip",
215 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
216 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
217 "upbracefill", "downbracefill", 0};
219 /// the same as known_spaces with .lyx names
220 char const * const known_coded_spaces[] = { "space{}", "space{}",
221 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
222 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
223 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
224 "upbracefill{}", "downbracefill{}", 0};
226 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
227 /// them in ERT. "LaTeXe" must come before "LaTeX"!
228 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
229 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
230 int const known_phrase_lengths[] = {3, 5, 7, 0};
232 // string to store the float type to be able to determine the type of subfloats
233 string float_type = "";
236 /// splits "x=z, y=b" into a map and an ordered keyword vector
237 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
242 keys.resize(v.size());
243 for (size_t i = 0; i < v.size(); ++i) {
244 size_t const pos = v[i].find('=');
245 string const index = trimSpaceAndEol(v[i].substr(0, pos));
246 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
254 * Split a LaTeX length into value and unit.
255 * The latter can be a real unit like "pt", or a latex length variable
256 * like "\textwidth". The unit may contain additional stuff like glue
257 * lengths, but we don't care, because such lengths are ERT anyway.
258 * \returns true if \p value and \p unit are valid.
260 bool splitLatexLength(string const & len, string & value, string & unit)
264 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
265 //'4,5' is a valid LaTeX length number. Change it to '4.5'
266 string const length = subst(len, ',', '.');
267 if (i == string::npos)
270 if (len[0] == '\\') {
271 // We had something like \textwidth without a factor
277 value = trimSpaceAndEol(string(length, 0, i));
281 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
282 if (contains(len, '\\'))
283 unit = trimSpaceAndEol(string(len, i));
285 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
290 /// A simple function to translate a latex length to something LyX can
291 /// understand. Not perfect, but rather best-effort.
292 bool translate_len(string const & length, string & valstring, string & unit)
294 if (!splitLatexLength(length, valstring, unit))
296 // LyX uses percent values
298 istringstream iss(valstring);
303 string const percentval = oss.str();
305 if (unit.empty() || unit[0] != '\\')
307 string::size_type const i = unit.find(' ');
308 string const endlen = (i == string::npos) ? string() : string(unit, i);
309 if (unit == "\\textwidth") {
310 valstring = percentval;
311 unit = "text%" + endlen;
312 } else if (unit == "\\columnwidth") {
313 valstring = percentval;
314 unit = "col%" + endlen;
315 } else if (unit == "\\paperwidth") {
316 valstring = percentval;
317 unit = "page%" + endlen;
318 } else if (unit == "\\linewidth") {
319 valstring = percentval;
320 unit = "line%" + endlen;
321 } else if (unit == "\\paperheight") {
322 valstring = percentval;
323 unit = "pheight%" + endlen;
324 } else if (unit == "\\textheight") {
325 valstring = percentval;
326 unit = "theight%" + endlen;
334 string translate_len(string const & length)
338 if (translate_len(length, value, unit))
340 // If the input is invalid, return what we have.
348 * Translates a LaTeX length into \p value, \p unit and
349 * \p special parts suitable for a box inset.
350 * The difference from translate_len() is that a box inset knows about
351 * some special "units" that are stored in \p special.
353 void translate_box_len(string const & length, string & value, string & unit, string & special)
355 if (translate_len(length, value, unit)) {
356 if (unit == "\\height" || unit == "\\depth" ||
357 unit == "\\totalheight" || unit == "\\width") {
358 special = unit.substr(1);
359 // The unit is not used, but LyX requires a dummy setting
372 * Find a file with basename \p name in path \p path and an extension
375 string find_file(string const & name, string const & path,
376 char const * const * extensions)
378 for (char const * const * what = extensions; *what; ++what) {
379 string const trial = addExtension(name, *what);
380 if (makeAbsPath(trial, path).exists())
387 void begin_inset(ostream & os, string const & name)
389 os << "\n\\begin_inset " << name;
393 void begin_command_inset(ostream & os, string const & name,
394 string const & latexname)
396 begin_inset(os, "CommandInset ");
397 os << name << "\nLatexCommand " << latexname << '\n';
401 void end_inset(ostream & os)
403 os << "\n\\end_inset\n\n";
407 bool skip_braces(Parser & p)
409 if (p.next_token().cat() != catBegin)
412 if (p.next_token().cat() == catEnd) {
421 /// replace LaTeX commands in \p s from the unicodesymbols file with their
423 docstring convert_unicodesymbols(docstring s)
426 for (size_t i = 0; i < s.size();) {
433 docstring parsed = encodings.fromLaTeXCommand(s, rem,
434 Encodings::TEXT_CMD);
437 if (s.empty() || s[0] != '\\')
446 /// try to convert \p s to a valid InsetCommand argument
447 string convert_command_inset_arg(string s)
450 // since we don't know the input encoding we can't use from_utf8
451 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
452 // LyX cannot handle newlines in a latex command
453 return subst(s, "\n", " ");
457 void handle_backslash(ostream & os, string const & s)
459 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
461 os << "\n\\backslash\n";
468 void handle_ert(ostream & os, string const & s, Context & context)
470 // We must have a valid layout before outputting the ERT inset.
471 context.check_layout(os);
472 Context newcontext(true, context.textclass);
473 begin_inset(os, "ERT");
474 os << "\nstatus collapsed\n";
475 newcontext.check_layout(os);
476 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
478 os << "\n\\backslash\n";
479 else if (*it == '\n') {
480 newcontext.new_paragraph(os);
481 newcontext.check_layout(os);
485 newcontext.check_end_layout(os);
490 void handle_comment(ostream & os, string const & s, Context & context)
492 // TODO: Handle this better
493 Context newcontext(true, context.textclass);
494 begin_inset(os, "ERT");
495 os << "\nstatus collapsed\n";
496 newcontext.check_layout(os);
497 handle_backslash(os, s);
498 // make sure that our comment is the last thing on the line
499 newcontext.new_paragraph(os);
500 newcontext.check_layout(os);
501 newcontext.check_end_layout(os);
506 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
508 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
511 if (checkModule(name, command))
512 return findLayoutWithoutModule(textclass, name, command);
517 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
519 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
522 if (checkModule(name, command))
523 return findInsetLayoutWithoutModule(textclass, name, command);
528 void eat_whitespace(Parser &, ostream &, Context &, bool);
532 * Skips whitespace and braces.
533 * This should be called after a command has been parsed that is not put into
534 * ERT, and where LyX adds "{}" if needed.
536 void skip_spaces_braces(Parser & p, bool keepws = false)
538 /* The following four examples produce the same typeset output and
539 should be handled by this function:
547 // Unfortunately we need to skip comments, too.
548 // We can't use eat_whitespace since writing them after the {}
549 // results in different output in some cases.
550 bool const skipped_spaces = p.skip_spaces(true);
551 bool const skipped_braces = skip_braces(p);
552 if (keepws && skipped_spaces && !skipped_braces)
553 // put back the space (it is better handled by check_space)
554 p.unskip_spaces(true);
558 void output_command_layout(ostream & os, Parser & p, bool outer,
559 Context & parent_context,
560 Layout const * newlayout)
562 TeXFont const oldFont = parent_context.font;
563 // save the current font size
564 string const size = oldFont.size;
565 // reset the font size to default, because the font size switches
566 // don't affect section headings and the like
567 parent_context.font.size = Context::normalfont.size;
568 // we only need to write the font change if we have an open layout
569 if (!parent_context.atParagraphStart())
570 output_font_change(os, oldFont, parent_context.font);
571 parent_context.check_end_layout(os);
572 Context context(true, parent_context.textclass, newlayout,
573 parent_context.layout, parent_context.font);
574 if (parent_context.deeper_paragraph) {
575 // We are beginning a nested environment after a
576 // deeper paragraph inside the outer list environment.
577 // Therefore we don't need to output a "begin deeper".
578 context.need_end_deeper = true;
580 context.check_deeper(os);
581 context.check_layout(os);
582 unsigned int optargs = 0;
583 while (optargs < context.layout->optargs) {
584 eat_whitespace(p, os, context, false);
585 if (p.next_token().cat() == catEscape ||
586 p.next_token().character() != '[')
588 p.get_token(); // eat '['
589 begin_inset(os, "Argument\n");
590 os << "status collapsed\n\n";
591 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
593 eat_whitespace(p, os, context, false);
596 unsigned int reqargs = 0;
597 while (reqargs < context.layout->reqargs) {
598 eat_whitespace(p, os, context, false);
599 if (p.next_token().cat() != catBegin)
601 p.get_token(); // eat '{'
602 begin_inset(os, "Argument\n");
603 os << "status collapsed\n\n";
604 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
606 eat_whitespace(p, os, context, false);
609 parse_text(p, os, FLAG_ITEM, outer, context);
610 context.check_end_layout(os);
611 if (parent_context.deeper_paragraph) {
612 // We must suppress the "end deeper" because we
613 // suppressed the "begin deeper" above.
614 context.need_end_deeper = false;
616 context.check_end_deeper(os);
617 // We don't need really a new paragraph, but
618 // we must make sure that the next item gets a \begin_layout.
619 parent_context.new_paragraph(os);
620 // Set the font size to the original value. No need to output it here
621 // (Context::begin_layout() will do that if needed)
622 parent_context.font.size = size;
627 * Output a space if necessary.
628 * This function gets called for every whitespace token.
630 * We have three cases here:
631 * 1. A space must be suppressed. Example: The lyxcode case below
632 * 2. A space may be suppressed. Example: Spaces before "\par"
633 * 3. A space must not be suppressed. Example: A space between two words
635 * We currently handle only 1. and 3 and from 2. only the case of
636 * spaces before newlines as a side effect.
638 * 2. could be used to suppress as many spaces as possible. This has two effects:
639 * - Reimporting LyX generated LaTeX files changes almost no whitespace
640 * - Superflous whitespace from non LyX generated LaTeX files is removed.
641 * The drawback is that the logic inside the function becomes
642 * complicated, and that is the reason why it is not implemented.
644 void check_space(Parser & p, ostream & os, Context & context)
646 Token const next = p.next_token();
647 Token const curr = p.curr_token();
648 // A space before a single newline and vice versa must be ignored
649 // LyX emits a newline before \end{lyxcode}.
650 // This newline must be ignored,
651 // otherwise LyX will add an additional protected space.
652 if (next.cat() == catSpace ||
653 next.cat() == catNewline ||
654 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
657 context.check_layout(os);
663 * Parse all arguments of \p command
665 void parse_arguments(string const & command,
666 vector<ArgumentType> const & template_arguments,
667 Parser & p, ostream & os, bool outer, Context & context)
669 string ert = command;
670 size_t no_arguments = template_arguments.size();
671 for (size_t i = 0; i < no_arguments; ++i) {
672 switch (template_arguments[i]) {
674 // This argument contains regular LaTeX
675 handle_ert(os, ert + '{', context);
676 eat_whitespace(p, os, context, false);
677 parse_text(p, os, FLAG_ITEM, outer, context);
681 // This argument consists only of a single item.
682 // The presence of '{' or not must be preserved.
684 if (p.next_token().cat() == catBegin)
685 ert += '{' + p.verbatim_item() + '}';
687 ert += p.verbatim_item();
690 // This argument may contain special characters
691 ert += '{' + p.verbatim_item() + '}';
694 // true because we must not eat whitespace
695 // if an optional arg follows we must not strip the
696 // brackets from this one
697 if (i < no_arguments - 1 &&
698 template_arguments[i+1] == optional)
699 ert += p.getFullOpt(true);
701 ert += p.getOpt(true);
705 handle_ert(os, ert, context);
710 * Check whether \p command is a known command. If yes,
711 * handle the command with all arguments.
712 * \return true if the command was parsed, false otherwise.
714 bool parse_command(string const & command, Parser & p, ostream & os,
715 bool outer, Context & context)
717 if (known_commands.find(command) != known_commands.end()) {
718 parse_arguments(command, known_commands[command], p, os,
726 /// Parses a minipage or parbox
727 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
728 unsigned inner_flags, bool outer, Context & parent_context,
729 string const & outer_type, string const & special,
730 string const & inner_type)
734 string hor_pos = "c";
735 // We need to set the height to the LaTeX default of 1\\totalheight
736 // for the case when no height argument is given
737 string height_value = "1";
738 string height_unit = "in";
739 string height_special = "totalheight";
741 if (!inner_type.empty() && p.hasOpt()) {
742 position = p.getArg('[', ']');
743 if (position != "t" && position != "c" && position != "b") {
744 cerr << "invalid position " << position << " for "
745 << inner_type << endl;
749 latex_height = p.getArg('[', ']');
750 translate_box_len(latex_height, height_value, height_unit, height_special);
753 inner_pos = p.getArg('[', ']');
754 if (inner_pos != "c" && inner_pos != "t" &&
755 inner_pos != "b" && inner_pos != "s") {
756 cerr << "invalid inner_pos "
757 << inner_pos << " for "
758 << inner_type << endl;
759 inner_pos = position;
767 if (inner_type.empty()) {
769 latex_width = "\\columnwidth";
772 latex_width = p2.getArg('[', ']');
773 string const opt = p2.getArg('[', ']');
776 if (hor_pos != "l" && hor_pos != "c" &&
778 cerr << "invalid hor_pos " << hor_pos
779 << " for " << outer_type << endl;
785 latex_width = p.verbatim_item();
786 translate_len(latex_width, width_value, width_unit);
787 // LyX can't handle length variables
788 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
789 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
790 // Look whether there is some content after the end of the
791 // inner box, but before the end of the outer box.
792 // If yes, we need to output ERT.
794 if (inner_flags & FLAG_END)
795 p.verbatimEnvironment(inner_type);
799 if ((outer_type == "framed" && p.next_token().asInput() != "\\end") ||
800 (outer_type != "framed" && p.next_token().cat() != catEnd)) {
801 // something is between the end of the inner box and
802 // the end of the outer box, so we need to use ERT.
809 if (!outer_type.empty()) {
810 if (outer_flags & FLAG_END)
811 ss << "\\begin{" << outer_type << '}';
813 ss << '\\' << outer_type << '{';
814 if (!special.empty())
818 if (!inner_type.empty()) {
819 if (inner_flags & FLAG_END)
820 ss << "\\begin{" << inner_type << '}';
822 ss << '\\' << inner_type;
823 if (!position.empty())
824 ss << '[' << position << ']';
825 if (!latex_height.empty())
826 ss << '[' << latex_height << ']';
827 if (!inner_pos.empty())
828 ss << '[' << inner_pos << ']';
829 ss << '{' << latex_width << '}';
830 if (!(inner_flags & FLAG_END))
833 handle_ert(os, ss.str(), parent_context);
834 if (!inner_type.empty()) {
835 parse_text(p, os, inner_flags, outer, parent_context);
836 if (inner_flags & FLAG_END)
837 handle_ert(os, "\\end{" + inner_type + '}',
840 handle_ert(os, "}", parent_context);
842 if (!outer_type.empty()) {
843 parse_text(p, os, outer_flags, outer, parent_context);
844 if (outer_flags & FLAG_END)
845 handle_ert(os, "\\end{" + outer_type + '}',
848 handle_ert(os, "}", parent_context);
851 // LyX does not like empty positions, so we have
852 // to set them to the LaTeX default values here.
853 if (position.empty())
855 if (inner_pos.empty())
856 inner_pos = position;
857 parent_context.check_layout(os);
858 begin_inset(os, "Box ");
859 if (outer_type == "framed")
861 else if (outer_type == "framebox")
863 else if (outer_type == "shadowbox")
865 else if (outer_type == "shaded")
867 else if (outer_type == "doublebox")
869 else if (outer_type.empty())
872 os << outer_type << '\n';
873 os << "position \"" << position << "\"\n";
874 os << "hor_pos \"" << hor_pos << "\"\n";
875 os << "has_inner_box " << !inner_type.empty() << "\n";
876 os << "inner_pos \"" << inner_pos << "\"\n";
877 os << "use_parbox " << (inner_type == "parbox") << '\n';
878 os << "use_makebox 0\n";
879 os << "width \"" << width_value << width_unit << "\"\n";
880 os << "special \"none\"\n";
881 os << "height \"" << height_value << height_unit << "\"\n";
882 os << "height_special \"" << height_special << "\"\n";
883 os << "status open\n\n";
884 Context context(true, parent_context.textclass);
885 context.font = parent_context.font;
887 // FIXME, the inset layout should be plain, not standard, see bug #7846
889 // If we have no inner box the contens will be read with the outer box
890 if (!inner_type.empty())
891 parse_text(p, os, inner_flags, outer, context);
893 // Ensure that the end of the outer box is parsed correctly:
894 // The opening brace has been eaten by parse_outer_box()
895 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
896 outer_flags &= ~FLAG_ITEM;
897 outer_flags |= FLAG_BRACE_LAST;
900 // Find end of outer box, output contents if inner_type is
901 // empty and output possible comments
902 if (!outer_type.empty()) {
903 // This does not output anything but comments if
904 // inner_type is not empty (see use_ert)
905 parse_text(p, os, outer_flags, outer, context);
908 context.check_end_layout(os);
910 #ifdef PRESERVE_LAYOUT
911 // LyX puts a % after the end of the minipage
912 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
914 //handle_comment(os, "%dummy", parent_context);
917 parent_context.new_paragraph(os);
919 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
920 //handle_comment(os, "%dummy", parent_context);
923 // We add a protected space if something real follows
924 if (p.good() && p.next_token().cat() != catComment) {
925 begin_inset(os, "space ~\n");
934 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
935 Context & parent_context, string const & outer_type,
936 string const & special)
938 eat_whitespace(p, os, parent_context, false);
939 if (flags & FLAG_ITEM) {
941 if (p.next_token().cat() == catBegin)
944 cerr << "Warning: Ignoring missing '{' after \\"
945 << outer_type << '.' << endl;
946 eat_whitespace(p, os, parent_context, false);
949 unsigned int inner_flags = 0;
950 if (outer_type == "shaded") {
951 // These boxes never have an inner box
953 } else if (p.next_token().asInput() == "\\parbox") {
954 inner = p.get_token().cs();
955 inner_flags = FLAG_ITEM;
956 } else if (p.next_token().asInput() == "\\begin") {
957 // Is this a minipage?
960 inner = p.getArg('{', '}');
962 if (inner == "minipage") {
965 eat_whitespace(p, os, parent_context, false);
966 inner_flags = FLAG_END;
970 if (inner_flags == FLAG_END) {
971 active_environments.push_back(inner);
972 parse_box(p, os, flags, FLAG_END, outer, parent_context,
973 outer_type, special, inner);
974 active_environments.pop_back();
976 parse_box(p, os, flags, inner_flags, outer, parent_context,
977 outer_type, special, inner);
982 void parse_listings(Parser & p, ostream & os, Context & parent_context)
984 parent_context.check_layout(os);
985 begin_inset(os, "listings\n");
986 os << "inline false\n"
987 << "status collapsed\n";
988 Context context(true, parent_context.textclass);
989 context.layout = &parent_context.textclass.plainLayout();
990 context.check_layout(os);
991 string const s = p.verbatimEnvironment("lstlisting");
992 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
994 os << "\n\\backslash\n";
995 else if (*it == '\n') {
996 // avoid adding an empty paragraph at the end
998 context.new_paragraph(os);
999 context.check_layout(os);
1004 context.check_end_layout(os);
1009 /// parse an unknown environment
1010 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1011 unsigned flags, bool outer,
1012 Context & parent_context)
1014 if (name == "tabbing")
1015 // We need to remember that we have to handle '\=' specially
1016 flags |= FLAG_TABBING;
1018 // We need to translate font changes and paragraphs inside the
1019 // environment to ERT if we have a non standard font.
1020 // Otherwise things like
1021 // \large\begin{foo}\huge bar\end{foo}
1023 bool const specialfont =
1024 (parent_context.font != parent_context.normalfont);
1025 bool const new_layout_allowed = parent_context.new_layout_allowed;
1027 parent_context.new_layout_allowed = false;
1028 handle_ert(os, "\\begin{" + name + "}", parent_context);
1029 parse_text_snippet(p, os, flags, outer, parent_context);
1030 handle_ert(os, "\\end{" + name + "}", parent_context);
1032 parent_context.new_layout_allowed = new_layout_allowed;
1036 void parse_environment(Parser & p, ostream & os, bool outer,
1037 string & last_env, Context & parent_context)
1039 Layout const * newlayout;
1040 InsetLayout const * newinsetlayout = 0;
1041 string const name = p.getArg('{', '}');
1042 const bool is_starred = suffixIs(name, '*');
1043 string const unstarred_name = rtrim(name, "*");
1044 active_environments.push_back(name);
1046 if (is_math_env(name)) {
1047 parent_context.check_layout(os);
1048 begin_inset(os, "Formula ");
1049 os << "\\begin{" << name << "}";
1050 parse_math(p, os, FLAG_END, MATH_MODE);
1051 os << "\\end{" << name << "}";
1055 else if (name == "tabular" || name == "longtable") {
1056 eat_whitespace(p, os, parent_context, false);
1057 parent_context.check_layout(os);
1058 begin_inset(os, "Tabular ");
1059 handle_tabular(p, os, name == "longtable", parent_context);
1064 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1065 eat_whitespace(p, os, parent_context, false);
1066 parent_context.check_layout(os);
1067 begin_inset(os, "Float " + unstarred_name + "\n");
1068 // store the float type for subfloats
1069 // subfloats only work with figures and tables
1070 if (unstarred_name == "figure")
1071 float_type = unstarred_name;
1072 else if (unstarred_name == "table")
1073 float_type = unstarred_name;
1077 os << "placement " << p.getArg('[', ']') << '\n';
1078 os << "wide " << convert<string>(is_starred)
1079 << "\nsideways false"
1080 << "\nstatus open\n\n";
1081 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1083 // We don't need really a new paragraph, but
1084 // we must make sure that the next item gets a \begin_layout.
1085 parent_context.new_paragraph(os);
1087 // the float is parsed thus delete the type
1091 else if (unstarred_name == "sidewaysfigure"
1092 || unstarred_name == "sidewaystable") {
1093 eat_whitespace(p, os, parent_context, false);
1094 parent_context.check_layout(os);
1095 if (unstarred_name == "sidewaysfigure")
1096 begin_inset(os, "Float figure\n");
1098 begin_inset(os, "Float table\n");
1099 os << "wide " << convert<string>(is_starred)
1100 << "\nsideways true"
1101 << "\nstatus open\n\n";
1102 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1104 // We don't need really a new paragraph, but
1105 // we must make sure that the next item gets a \begin_layout.
1106 parent_context.new_paragraph(os);
1110 else if (name == "wrapfigure" || name == "wraptable") {
1111 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1112 eat_whitespace(p, os, parent_context, false);
1113 parent_context.check_layout(os);
1116 string overhang = "0col%";
1119 lines = p.getArg('[', ']');
1120 string const placement = p.getArg('{', '}');
1122 overhang = p.getArg('[', ']');
1123 string const width = p.getArg('{', '}');
1125 if (name == "wrapfigure")
1126 begin_inset(os, "Wrap figure\n");
1128 begin_inset(os, "Wrap table\n");
1129 os << "lines " << lines
1130 << "\nplacement " << placement
1131 << "\noverhang " << lyx::translate_len(overhang)
1132 << "\nwidth " << lyx::translate_len(width)
1133 << "\nstatus open\n\n";
1134 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1136 // We don't need really a new paragraph, but
1137 // we must make sure that the next item gets a \begin_layout.
1138 parent_context.new_paragraph(os);
1142 else if (name == "minipage") {
1143 eat_whitespace(p, os, parent_context, false);
1144 parse_box(p, os, 0, FLAG_END, outer, parent_context, "", "", name);
1148 else if (name == "comment") {
1149 eat_whitespace(p, os, parent_context, false);
1150 parent_context.check_layout(os);
1151 begin_inset(os, "Note Comment\n");
1152 os << "status open\n";
1153 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1156 skip_braces(p); // eat {} that might by set by LyX behind comments
1159 else if (name == "lyxgreyedout") {
1160 eat_whitespace(p, os, parent_context, false);
1161 parent_context.check_layout(os);
1162 begin_inset(os, "Note Greyedout\n");
1163 os << "status open\n";
1164 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1169 else if (name == "framed" || name == "shaded") {
1170 eat_whitespace(p, os, parent_context, false);
1171 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1175 else if (name == "lstlisting") {
1176 eat_whitespace(p, os, parent_context, false);
1177 // FIXME handle listings with parameters
1179 parse_unknown_environment(p, name, os, FLAG_END,
1180 outer, parent_context);
1182 parse_listings(p, os, parent_context);
1186 else if (!parent_context.new_layout_allowed)
1187 parse_unknown_environment(p, name, os, FLAG_END, outer,
1190 // Alignment and spacing settings
1191 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1192 // therefore are totally broken!
1193 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1194 // they are commands not environments. They are furthermore switches that
1195 // can be ended by another switches, but also by commands like \footnote or
1196 // \parbox. So the only safe way is to leave them untouched.
1197 else if (name == "center" || name == "centering" ||
1198 name == "flushleft" || name == "flushright" ||
1199 name == "singlespace" || name == "onehalfspace" ||
1200 name == "doublespace" || name == "spacing") {
1201 eat_whitespace(p, os, parent_context, false);
1202 // We must begin a new paragraph if not already done
1203 if (! parent_context.atParagraphStart()) {
1204 parent_context.check_end_layout(os);
1205 parent_context.new_paragraph(os);
1207 if (name == "flushleft")
1208 parent_context.add_extra_stuff("\\align left\n");
1209 else if (name == "flushright")
1210 parent_context.add_extra_stuff("\\align right\n");
1211 else if (name == "center" || name == "centering")
1212 parent_context.add_extra_stuff("\\align center\n");
1213 else if (name == "singlespace")
1214 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1215 else if (name == "onehalfspace")
1216 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1217 else if (name == "doublespace")
1218 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1219 else if (name == "spacing")
1220 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1221 parse_text(p, os, FLAG_END, outer, parent_context);
1222 // Just in case the environment is empty
1223 parent_context.extra_stuff.erase();
1224 // We must begin a new paragraph to reset the alignment
1225 parent_context.new_paragraph(os);
1229 // The single '=' is meant here.
1230 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1231 eat_whitespace(p, os, parent_context, false);
1232 Context context(true, parent_context.textclass, newlayout,
1233 parent_context.layout, parent_context.font);
1234 if (parent_context.deeper_paragraph) {
1235 // We are beginning a nested environment after a
1236 // deeper paragraph inside the outer list environment.
1237 // Therefore we don't need to output a "begin deeper".
1238 context.need_end_deeper = true;
1240 parent_context.check_end_layout(os);
1241 if (last_env == name) {
1242 // we need to output a separator since LyX would export
1243 // the two environments as one otherwise (bug 5716)
1244 docstring const sep = from_ascii("--Separator--");
1245 TeX2LyXDocClass const & textclass(parent_context.textclass);
1246 if (textclass.hasLayout(sep)) {
1247 Context newcontext(parent_context);
1248 newcontext.layout = &(textclass[sep]);
1249 newcontext.check_layout(os);
1250 newcontext.check_end_layout(os);
1252 parent_context.check_layout(os);
1253 begin_inset(os, "Note Note\n");
1254 os << "status closed\n";
1255 Context newcontext(true, textclass,
1256 &(textclass.defaultLayout()));
1257 newcontext.check_layout(os);
1258 newcontext.check_end_layout(os);
1260 parent_context.check_end_layout(os);
1263 switch (context.layout->latextype) {
1264 case LATEX_LIST_ENVIRONMENT:
1265 context.add_par_extra_stuff("\\labelwidthstring "
1266 + p.verbatim_item() + '\n');
1269 case LATEX_BIB_ENVIRONMENT:
1270 p.verbatim_item(); // swallow next arg
1276 context.check_deeper(os);
1277 // handle known optional and required arguments
1278 // layouts require all optional arguments before the required ones
1279 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1280 // It is impossible to place anything after the environment name,
1281 // but before the first \\item.
1282 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1283 bool need_layout = true;
1284 unsigned int optargs = 0;
1285 while (optargs < context.layout->optargs) {
1286 eat_whitespace(p, os, context, false);
1287 if (p.next_token().cat() == catEscape ||
1288 p.next_token().character() != '[')
1290 p.get_token(); // eat '['
1292 context.check_layout(os);
1293 need_layout = false;
1295 begin_inset(os, "Argument\n");
1296 os << "status collapsed\n\n";
1297 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1299 eat_whitespace(p, os, context, false);
1302 unsigned int reqargs = 0;
1303 while (reqargs < context.layout->reqargs) {
1304 eat_whitespace(p, os, context, false);
1305 if (p.next_token().cat() != catBegin)
1307 p.get_token(); // eat '{'
1309 context.check_layout(os);
1310 need_layout = false;
1312 begin_inset(os, "Argument\n");
1313 os << "status collapsed\n\n";
1314 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1316 eat_whitespace(p, os, context, false);
1320 parse_text(p, os, FLAG_END, outer, context);
1321 context.check_end_layout(os);
1322 if (parent_context.deeper_paragraph) {
1323 // We must suppress the "end deeper" because we
1324 // suppressed the "begin deeper" above.
1325 context.need_end_deeper = false;
1327 context.check_end_deeper(os);
1328 parent_context.new_paragraph(os);
1332 // The single '=' is meant here.
1333 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1334 eat_whitespace(p, os, parent_context, false);
1335 parent_context.check_layout(os);
1336 begin_inset(os, "Flex ");
1337 os << to_utf8(newinsetlayout->name()) << '\n'
1338 << "status collapsed\n";
1339 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1343 else if (name == "appendix") {
1344 // This is no good latex style, but it works and is used in some documents...
1345 eat_whitespace(p, os, parent_context, false);
1346 parent_context.check_end_layout(os);
1347 Context context(true, parent_context.textclass, parent_context.layout,
1348 parent_context.layout, parent_context.font);
1349 context.check_layout(os);
1350 os << "\\start_of_appendix\n";
1351 parse_text(p, os, FLAG_END, outer, context);
1352 context.check_end_layout(os);
1356 else if (known_environments.find(name) != known_environments.end()) {
1357 vector<ArgumentType> arguments = known_environments[name];
1358 // The last "argument" denotes wether we may translate the
1359 // environment contents to LyX
1360 // The default required if no argument is given makes us
1361 // compatible with the reLyXre environment.
1362 ArgumentType contents = arguments.empty() ?
1365 if (!arguments.empty())
1366 arguments.pop_back();
1367 // See comment in parse_unknown_environment()
1368 bool const specialfont =
1369 (parent_context.font != parent_context.normalfont);
1370 bool const new_layout_allowed =
1371 parent_context.new_layout_allowed;
1373 parent_context.new_layout_allowed = false;
1374 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1375 outer, parent_context);
1376 if (contents == verbatim)
1377 handle_ert(os, p.verbatimEnvironment(name),
1380 parse_text_snippet(p, os, FLAG_END, outer,
1382 handle_ert(os, "\\end{" + name + "}", parent_context);
1384 parent_context.new_layout_allowed = new_layout_allowed;
1388 parse_unknown_environment(p, name, os, FLAG_END, outer,
1392 active_environments.pop_back();
1396 /// parses a comment and outputs it to \p os.
1397 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1399 LASSERT(t.cat() == catComment, return);
1400 if (!t.cs().empty()) {
1401 context.check_layout(os);
1402 handle_comment(os, '%' + t.cs(), context);
1403 if (p.next_token().cat() == catNewline) {
1404 // A newline after a comment line starts a new
1406 if (context.new_layout_allowed) {
1407 if(!context.atParagraphStart())
1408 // Only start a new paragraph if not already
1409 // done (we might get called recursively)
1410 context.new_paragraph(os);
1412 handle_ert(os, "\n", context);
1413 eat_whitespace(p, os, context, true);
1416 // "%\n" combination
1423 * Reads spaces and comments until the first non-space, non-comment token.
1424 * New paragraphs (double newlines or \\par) are handled like simple spaces
1425 * if \p eatParagraph is true.
1426 * Spaces are skipped, but comments are written to \p os.
1428 void eat_whitespace(Parser & p, ostream & os, Context & context,
1432 Token const & t = p.get_token();
1433 if (t.cat() == catComment)
1434 parse_comment(p, os, t, context);
1435 else if ((! eatParagraph && p.isParagraph()) ||
1436 (t.cat() != catSpace && t.cat() != catNewline)) {
1445 * Set a font attribute, parse text and reset the font attribute.
1446 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1447 * \param currentvalue Current value of the attribute. Is set to the new
1448 * value during parsing.
1449 * \param newvalue New value of the attribute
1451 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1452 Context & context, string const & attribute,
1453 string & currentvalue, string const & newvalue)
1455 context.check_layout(os);
1456 string const oldvalue = currentvalue;
1457 currentvalue = newvalue;
1458 os << '\n' << attribute << ' ' << newvalue << "\n";
1459 parse_text_snippet(p, os, flags, outer, context);
1460 context.check_layout(os);
1461 os << '\n' << attribute << ' ' << oldvalue << "\n";
1462 currentvalue = oldvalue;
1466 /// get the arguments of a natbib or jurabib citation command
1467 void get_cite_arguments(Parser & p, bool natbibOrder,
1468 string & before, string & after)
1470 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1472 // text before the citation
1474 // text after the citation
1475 after = p.getFullOpt();
1477 if (!after.empty()) {
1478 before = p.getFullOpt();
1479 if (natbibOrder && !before.empty())
1480 swap(before, after);
1485 /// Convert filenames with TeX macros and/or quotes to something LyX
1487 string const normalize_filename(string const & name)
1489 Parser p(trim(name, "\""));
1492 Token const & t = p.get_token();
1493 if (t.cat() != catEscape)
1495 else if (t.cs() == "lyxdot") {
1496 // This is used by LyX for simple dots in relative
1500 } else if (t.cs() == "space") {
1510 /// Convert \p name from TeX convention (relative to master file) to LyX
1511 /// convention (relative to .lyx file) if it is relative
1512 void fix_relative_filename(string & name)
1514 if (FileName::isAbsolute(name))
1517 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1518 from_utf8(getParentFilePath())));
1522 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1523 void parse_noweb(Parser & p, ostream & os, Context & context)
1525 // assemble the rest of the keyword
1529 Token const & t = p.get_token();
1530 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1533 scrap = (p.good() && p.next_token().asInput() == "=");
1535 name += p.get_token().asInput();
1538 name += t.asInput();
1541 if (!scrap || !context.new_layout_allowed ||
1542 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1543 cerr << "Warning: Could not interpret '" << name
1544 << "'. Ignoring it." << endl;
1548 // We use new_paragraph instead of check_end_layout because the stuff
1549 // following the noweb chunk needs to start with a \begin_layout.
1550 // This may create a new paragraph even if there was none in the
1551 // noweb file, but the alternative is an invalid LyX file. Since
1552 // noweb code chunks are implemented with a layout style in LyX they
1553 // always must be in an own paragraph.
1554 context.new_paragraph(os);
1555 Context newcontext(true, context.textclass,
1556 &context.textclass[from_ascii("Scrap")]);
1557 newcontext.check_layout(os);
1560 Token const & t = p.get_token();
1561 // We abuse the parser a bit, because this is no TeX syntax
1563 if (t.cat() == catEscape)
1564 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1567 Context tmp(false, context.textclass,
1568 &context.textclass[from_ascii("Scrap")]);
1569 tmp.need_end_layout = true;
1570 tmp.check_layout(oss);
1571 os << subst(t.asInput(), "\n", oss.str());
1573 // The scrap chunk is ended by an @ at the beginning of a line.
1574 // After the @ the line may contain a comment and/or
1575 // whitespace, but nothing else.
1576 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1577 (p.next_token().cat() == catSpace ||
1578 p.next_token().cat() == catNewline ||
1579 p.next_token().cat() == catComment)) {
1580 while (p.good() && p.next_token().cat() == catSpace)
1581 os << p.get_token().asInput();
1582 if (p.next_token().cat() == catComment)
1583 // The comment includes a final '\n'
1584 os << p.get_token().asInput();
1586 if (p.next_token().cat() == catNewline)
1593 newcontext.check_end_layout(os);
1597 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1598 bool is_macro(Parser & p)
1600 Token first = p.curr_token();
1601 if (first.cat() != catEscape || !p.good())
1603 if (first.cs() == "def")
1605 if (first.cs() != "global" && first.cs() != "long")
1607 Token second = p.get_token();
1609 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1610 second.cat() == catNewline || second.cat() == catComment)) {
1611 second = p.get_token();
1614 bool secondvalid = second.cat() == catEscape;
1616 bool thirdvalid = false;
1617 if (p.good() && first.cs() == "global" && secondvalid &&
1618 second.cs() == "long") {
1619 third = p.get_token();
1621 while (p.good() && !p.isParagraph() &&
1622 (third.cat() == catSpace ||
1623 third.cat() == catNewline ||
1624 third.cat() == catComment)) {
1625 third = p.get_token();
1628 thirdvalid = third.cat() == catEscape;
1630 for (int i = 0; i < pos; ++i)
1635 return (first.cs() == "global" || first.cs() == "long") &&
1636 second.cs() == "def";
1637 return first.cs() == "global" && second.cs() == "long" &&
1638 third.cs() == "def";
1642 /// Parse a macro definition (assumes that is_macro() returned true)
1643 void parse_macro(Parser & p, ostream & os, Context & context)
1645 context.check_layout(os);
1646 Token first = p.curr_token();
1649 string command = first.asInput();
1650 if (first.cs() != "def") {
1652 eat_whitespace(p, os, context, false);
1653 second = p.curr_token();
1654 command += second.asInput();
1655 if (second.cs() != "def") {
1657 eat_whitespace(p, os, context, false);
1658 third = p.curr_token();
1659 command += third.asInput();
1662 eat_whitespace(p, os, context, false);
1663 string const name = p.get_token().cs();
1664 eat_whitespace(p, os, context, false);
1670 while (p.next_token().cat() != catBegin) {
1671 if (p.next_token().cat() == catParameter) {
1676 // followed by number?
1677 if (p.next_token().cat() == catOther) {
1678 char c = p.getChar();
1680 // number = current arity + 1?
1681 if (c == arity + '0' + 1)
1686 paramtext += p.get_token().cs();
1688 paramtext += p.get_token().cs();
1693 // only output simple (i.e. compatible) macro as FormulaMacros
1694 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1696 context.check_layout(os);
1697 begin_inset(os, "FormulaMacro");
1698 os << "\n\\def" << ert;
1701 handle_ert(os, command + ert, context);
1704 } // anonymous namespace
1707 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1710 Layout const * newlayout = 0;
1711 InsetLayout const * newinsetlayout = 0;
1712 // Store the latest bibliographystyle and nocite{*} option
1713 // (needed for bibtex inset)
1715 string bibliographystyle;
1716 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1717 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1720 Token const & t = p.get_token();
1723 debugToken(cerr, t, flags);
1726 if (flags & FLAG_ITEM) {
1727 if (t.cat() == catSpace)
1730 flags &= ~FLAG_ITEM;
1731 if (t.cat() == catBegin) {
1732 // skip the brace and collect everything to the next matching
1734 flags |= FLAG_BRACE_LAST;
1738 // handle only this single token, leave the loop if done
1739 flags |= FLAG_LEAVE;
1742 if (t.cat() != catEscape && t.character() == ']' &&
1743 (flags & FLAG_BRACK_LAST))
1745 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1748 // If there is anything between \end{env} and \begin{env} we
1749 // don't need to output a separator.
1750 if (t.cat() != catSpace && t.cat() != catNewline &&
1751 t.asInput() != "\\begin")
1757 if (t.cat() == catMath) {
1758 // we are inside some text mode thingy, so opening new math is allowed
1759 context.check_layout(os);
1760 begin_inset(os, "Formula ");
1761 Token const & n = p.get_token();
1762 if (n.cat() == catMath && outer) {
1763 // TeX's $$...$$ syntax for displayed math
1765 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1767 p.get_token(); // skip the second '$' token
1769 // simple $...$ stuff
1772 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1778 else if (t.cat() == catSuper || t.cat() == catSub)
1779 cerr << "catcode " << t << " illegal in text mode\n";
1781 // Basic support for english quotes. This should be
1782 // extended to other quotes, but is not so easy (a
1783 // left english quote is the same as a right german
1785 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1786 context.check_layout(os);
1787 begin_inset(os, "Quotes ");
1793 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1794 context.check_layout(os);
1795 begin_inset(os, "Quotes ");
1802 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1803 context.check_layout(os);
1804 begin_inset(os, "Quotes ");
1811 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1812 context.check_layout(os);
1813 begin_inset(os, "Quotes ");
1820 else if (t.asInput() == "<"
1821 && p.next_token().asInput() == "<" && noweb_mode) {
1823 parse_noweb(p, os, context);
1826 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1827 check_space(p, os, context);
1829 else if (t.character() == '[' && noweb_mode &&
1830 p.next_token().character() == '[') {
1831 // These can contain underscores
1833 string const s = p.getFullOpt() + ']';
1834 if (p.next_token().character() == ']')
1837 cerr << "Warning: Inserting missing ']' in '"
1838 << s << "'." << endl;
1839 handle_ert(os, s, context);
1842 else if (t.cat() == catLetter) {
1843 context.check_layout(os);
1844 // Workaround for bug 4752.
1845 // FIXME: This whole code block needs to be removed
1846 // when the bug is fixed and tex2lyx produces
1847 // the updated file format.
1848 // The replacement algorithm in LyX is so stupid that
1849 // it even translates a phrase if it is part of a word.
1850 bool handled = false;
1851 for (int const * l = known_phrase_lengths; *l; ++l) {
1852 string phrase = t.cs();
1853 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
1854 phrase += p.get_token().cs();
1855 if (is_known(phrase, known_coded_phrases)) {
1856 handle_ert(os, phrase, context);
1860 for (size_t i = 1; i < phrase.length(); ++i)
1868 else if (t.cat() == catOther ||
1869 t.cat() == catAlign ||
1870 t.cat() == catParameter) {
1871 // This translates "&" to "\\&" which may be wrong...
1872 context.check_layout(os);
1876 else if (p.isParagraph()) {
1877 if (context.new_layout_allowed)
1878 context.new_paragraph(os);
1880 handle_ert(os, "\\par ", context);
1881 eat_whitespace(p, os, context, true);
1884 else if (t.cat() == catActive) {
1885 context.check_layout(os);
1886 if (t.character() == '~') {
1887 if (context.layout->free_spacing)
1890 begin_inset(os, "space ~\n");
1897 else if (t.cat() == catBegin &&
1898 p.next_token().cat() == catEnd) {
1900 Token const prev = p.prev_token();
1902 if (p.next_token().character() == '`' ||
1903 (prev.character() == '-' &&
1904 p.next_token().character() == '-'))
1905 ; // ignore it in {}`` or -{}-
1907 handle_ert(os, "{}", context);
1911 else if (t.cat() == catBegin) {
1912 context.check_layout(os);
1913 // special handling of font attribute changes
1914 Token const prev = p.prev_token();
1915 Token const next = p.next_token();
1916 TeXFont const oldFont = context.font;
1917 if (next.character() == '[' ||
1918 next.character() == ']' ||
1919 next.character() == '*') {
1921 if (p.next_token().cat() == catEnd) {
1926 handle_ert(os, "{", context);
1927 parse_text_snippet(p, os,
1930 handle_ert(os, "}", context);
1932 } else if (! context.new_layout_allowed) {
1933 handle_ert(os, "{", context);
1934 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1936 handle_ert(os, "}", context);
1937 } else if (is_known(next.cs(), known_sizes)) {
1938 // next will change the size, so we must
1940 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1942 if (!context.atParagraphStart())
1944 << context.font.size << "\n";
1945 } else if (is_known(next.cs(), known_font_families)) {
1946 // next will change the font family, so we
1947 // must reset it here
1948 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1950 if (!context.atParagraphStart())
1952 << context.font.family << "\n";
1953 } else if (is_known(next.cs(), known_font_series)) {
1954 // next will change the font series, so we
1955 // must reset it here
1956 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1958 if (!context.atParagraphStart())
1960 << context.font.series << "\n";
1961 } else if (is_known(next.cs(), known_font_shapes)) {
1962 // next will change the font shape, so we
1963 // must reset it here
1964 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1966 if (!context.atParagraphStart())
1968 << context.font.shape << "\n";
1969 } else if (is_known(next.cs(), known_old_font_families) ||
1970 is_known(next.cs(), known_old_font_series) ||
1971 is_known(next.cs(), known_old_font_shapes)) {
1972 // next will change the font family, series
1973 // and shape, so we must reset it here
1974 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1976 if (!context.atParagraphStart())
1978 << context.font.family
1980 << context.font.series
1982 << context.font.shape << "\n";
1984 handle_ert(os, "{", context);
1985 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1987 handle_ert(os, "}", context);
1991 else if (t.cat() == catEnd) {
1992 if (flags & FLAG_BRACE_LAST) {
1995 cerr << "stray '}' in text\n";
1996 handle_ert(os, "}", context);
1999 else if (t.cat() == catComment)
2000 parse_comment(p, os, t, context);
2003 // control sequences
2006 else if (t.cs() == "(") {
2007 context.check_layout(os);
2008 begin_inset(os, "Formula");
2010 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2015 else if (t.cs() == "[") {
2016 context.check_layout(os);
2017 begin_inset(os, "Formula");
2019 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2024 else if (t.cs() == "begin")
2025 parse_environment(p, os, outer, last_env, context);
2027 else if (t.cs() == "end") {
2028 if (flags & FLAG_END) {
2029 // eat environment name
2030 string const name = p.getArg('{', '}');
2031 if (name != active_environment())
2032 cerr << "\\end{" + name + "} does not match \\begin{"
2033 + active_environment() + "}\n";
2036 p.error("found 'end' unexpectedly");
2039 else if (t.cs() == "item") {
2042 bool optarg = false;
2043 if (p.next_token().cat() != catEscape &&
2044 p.next_token().character() == '[') {
2045 p.get_token(); // eat '['
2046 s = parse_text_snippet(p, FLAG_BRACK_LAST,
2051 context.check_layout(os);
2052 if (context.has_item) {
2053 // An item in an unknown list-like environment
2054 // FIXME: Do this in check_layout()!
2055 context.has_item = false;
2057 handle_ert(os, "\\item", context);
2059 handle_ert(os, "\\item ", context);
2062 if (context.layout->labeltype != LABEL_MANUAL) {
2063 // LyX does not support \item[\mybullet]
2064 // in itemize environments
2065 handle_ert(os, "[", context);
2067 handle_ert(os, "]", context);
2068 } else if (!s.empty()) {
2069 // The space is needed to separate the
2070 // item from the rest of the sentence.
2072 eat_whitespace(p, os, context, false);
2077 else if (t.cs() == "bibitem") {
2079 context.check_layout(os);
2080 string label = convert_command_inset_arg(p.getArg('[', ']'));
2081 string key = convert_command_inset_arg(p.verbatim_item());
2082 if (contains(label, '\\') || contains(key, '\\')) {
2083 // LyX can't handle LaTeX commands in labels or keys
2084 handle_ert(os, t.asInput() + '[' + label +
2085 "]{" + p.verbatim_item() + '}',
2088 begin_command_inset(os, "bibitem", "bibitem");
2089 os << "label \"" << label << "\"\n"
2090 "key \"" << key << "\"\n";
2095 else if (is_macro(p))
2096 parse_macro(p, os, context);
2098 else if (t.cs() == "noindent") {
2100 context.add_par_extra_stuff("\\noindent\n");
2103 else if (t.cs() == "appendix") {
2104 context.add_par_extra_stuff("\\start_of_appendix\n");
2105 // We need to start a new paragraph. Otherwise the
2106 // appendix in 'bla\appendix\chapter{' would start
2108 context.new_paragraph(os);
2109 // We need to make sure that the paragraph is
2110 // generated even if it is empty. Otherwise the
2111 // appendix in '\par\appendix\par\chapter{' would
2113 context.check_layout(os);
2114 // FIXME: This is a hack to prevent paragraph
2115 // deletion if it is empty. Handle this better!
2117 "%dummy comment inserted by tex2lyx to "
2118 "ensure that this paragraph is not empty",
2120 // Both measures above may generate an additional
2121 // empty paragraph, but that does not hurt, because
2122 // whitespace does not matter here.
2123 eat_whitespace(p, os, context, true);
2126 // Starred section headings
2127 // Must attempt to parse "Section*" before "Section".
2128 else if ((p.next_token().asInput() == "*") &&
2129 context.new_layout_allowed &&
2130 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2133 output_command_layout(os, p, outer, context, newlayout);
2137 // Section headings and the like
2138 else if (context.new_layout_allowed &&
2139 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2141 output_command_layout(os, p, outer, context, newlayout);
2145 else if (t.cs() == "caption") {
2147 context.check_layout(os);
2149 begin_inset(os, "Caption\n");
2150 Context newcontext(true, context.textclass);
2151 newcontext.font = context.font;
2152 newcontext.check_layout(os);
2153 if (p.next_token().cat() != catEscape &&
2154 p.next_token().character() == '[') {
2155 p.get_token(); // eat '['
2156 begin_inset(os, "Argument\n");
2157 os << "status collapsed\n";
2158 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2160 eat_whitespace(p, os, context, false);
2162 parse_text(p, os, FLAG_ITEM, outer, context);
2163 context.check_end_layout(os);
2164 // We don't need really a new paragraph, but
2165 // we must make sure that the next item gets a \begin_layout.
2166 context.new_paragraph(os);
2169 newcontext.check_end_layout(os);
2172 else if (t.cs() == "subfloat") {
2173 // the syntax is \subfloat[caption]{content}
2174 // if it is a table of figure depends on the surrounding float
2175 bool has_caption = false;
2177 // do nothing if there is no outer float
2178 if (!float_type.empty()) {
2179 context.check_layout(os);
2181 begin_inset(os, "Float " + float_type + "\n");
2183 << "\nsideways false"
2184 << "\nstatus collapsed\n\n";
2187 if (p.next_token().cat() != catEscape &&
2188 p.next_token().character() == '[') {
2189 p.get_token(); // eat '['
2190 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2194 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2195 // the caption comes always as the last
2197 // we must make sure that the caption gets a \begin_layout
2198 os << "\n\\begin_layout Plain Layout";
2200 begin_inset(os, "Caption\n");
2201 Context newcontext(true, context.textclass);
2202 newcontext.font = context.font;
2203 newcontext.check_layout(os);
2204 os << caption << "\n";
2205 newcontext.check_end_layout(os);
2206 // We don't need really a new paragraph, but
2207 // we must make sure that the next item gets a \begin_layout.
2208 //newcontext.new_paragraph(os);
2212 // We don't need really a new paragraph, but
2213 // we must make sure that the next item gets a \begin_layout.
2215 context.new_paragraph(os);
2218 context.check_end_layout(os);
2219 // close the layout we opened
2221 os << "\n\\end_layout\n";
2223 // if the float type is not supported or there is no surrounding float
2226 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2227 handle_ert(os, t.asInput() + '[' + opt_arg +
2228 "]{" + p.verbatim_item() + '}', context);
2230 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2234 else if (t.cs() == "includegraphics") {
2235 bool const clip = p.next_token().asInput() == "*";
2238 string const arg = p.getArg('[', ']');
2239 map<string, string> opts;
2240 vector<string> keys;
2241 split_map(arg, opts, keys);
2243 opts["clip"] = string();
2244 string name = normalize_filename(p.verbatim_item());
2246 string const path = getMasterFilePath();
2247 // We want to preserve relative / absolute filenames,
2248 // therefore path is only used for testing
2249 if (!makeAbsPath(name, path).exists()) {
2250 // The file extension is probably missing.
2251 // Now try to find it out.
2252 string const dvips_name =
2253 find_file(name, path,
2254 known_dvips_graphics_formats);
2255 string const pdftex_name =
2256 find_file(name, path,
2257 known_pdftex_graphics_formats);
2258 if (!dvips_name.empty()) {
2259 if (!pdftex_name.empty()) {
2260 cerr << "This file contains the "
2262 "\"\\includegraphics{"
2264 "However, files\n\""
2265 << dvips_name << "\" and\n\""
2266 << pdftex_name << "\"\n"
2267 "both exist, so I had to make a "
2268 "choice and took the first one.\n"
2269 "Please move the unwanted one "
2270 "someplace else and try again\n"
2271 "if my choice was wrong."
2275 } else if (!pdftex_name.empty()) {
2281 if (makeAbsPath(name, path).exists())
2282 fix_relative_filename(name);
2284 cerr << "Warning: Could not find graphics file '"
2285 << name << "'." << endl;
2287 context.check_layout(os);
2288 begin_inset(os, "Graphics ");
2289 os << "\n\tfilename " << name << '\n';
2290 if (opts.find("width") != opts.end())
2292 << translate_len(opts["width"]) << '\n';
2293 if (opts.find("height") != opts.end())
2295 << translate_len(opts["height"]) << '\n';
2296 if (opts.find("scale") != opts.end()) {
2297 istringstream iss(opts["scale"]);
2301 os << "\tscale " << val << '\n';
2303 if (opts.find("angle") != opts.end()) {
2304 os << "\trotateAngle "
2305 << opts["angle"] << '\n';
2306 vector<string>::const_iterator a =
2307 find(keys.begin(), keys.end(), "angle");
2308 vector<string>::const_iterator s =
2309 find(keys.begin(), keys.end(), "width");
2310 if (s == keys.end())
2311 s = find(keys.begin(), keys.end(), "height");
2312 if (s == keys.end())
2313 s = find(keys.begin(), keys.end(), "scale");
2314 if (s != keys.end() && distance(s, a) > 0)
2315 os << "\tscaleBeforeRotation\n";
2317 if (opts.find("origin") != opts.end()) {
2319 string const opt = opts["origin"];
2320 if (opt.find('l') != string::npos) ss << "left";
2321 if (opt.find('r') != string::npos) ss << "right";
2322 if (opt.find('c') != string::npos) ss << "center";
2323 if (opt.find('t') != string::npos) ss << "Top";
2324 if (opt.find('b') != string::npos) ss << "Bottom";
2325 if (opt.find('B') != string::npos) ss << "Baseline";
2326 if (!ss.str().empty())
2327 os << "\trotateOrigin " << ss.str() << '\n';
2329 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2331 if (opts.find("keepaspectratio") != opts.end())
2332 os << "\tkeepAspectRatio\n";
2333 if (opts.find("clip") != opts.end())
2335 if (opts.find("draft") != opts.end())
2337 if (opts.find("bb") != opts.end())
2338 os << "\tBoundingBox "
2339 << opts["bb"] << '\n';
2340 int numberOfbbOptions = 0;
2341 if (opts.find("bbllx") != opts.end())
2342 numberOfbbOptions++;
2343 if (opts.find("bblly") != opts.end())
2344 numberOfbbOptions++;
2345 if (opts.find("bburx") != opts.end())
2346 numberOfbbOptions++;
2347 if (opts.find("bbury") != opts.end())
2348 numberOfbbOptions++;
2349 if (numberOfbbOptions == 4)
2350 os << "\tBoundingBox "
2351 << opts["bbllx"] << " " << opts["bblly"] << " "
2352 << opts["bburx"] << " " << opts["bbury"] << '\n';
2353 else if (numberOfbbOptions > 0)
2354 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2355 numberOfbbOptions = 0;
2356 if (opts.find("natwidth") != opts.end())
2357 numberOfbbOptions++;
2358 if (opts.find("natheight") != opts.end())
2359 numberOfbbOptions++;
2360 if (numberOfbbOptions == 2)
2361 os << "\tBoundingBox 0bp 0bp "
2362 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2363 else if (numberOfbbOptions > 0)
2364 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2365 ostringstream special;
2366 if (opts.find("hiresbb") != opts.end())
2367 special << "hiresbb,";
2368 if (opts.find("trim") != opts.end())
2370 if (opts.find("viewport") != opts.end())
2371 special << "viewport=" << opts["viewport"] << ',';
2372 if (opts.find("totalheight") != opts.end())
2373 special << "totalheight=" << opts["totalheight"] << ',';
2374 if (opts.find("type") != opts.end())
2375 special << "type=" << opts["type"] << ',';
2376 if (opts.find("ext") != opts.end())
2377 special << "ext=" << opts["ext"] << ',';
2378 if (opts.find("read") != opts.end())
2379 special << "read=" << opts["read"] << ',';
2380 if (opts.find("command") != opts.end())
2381 special << "command=" << opts["command"] << ',';
2382 string s_special = special.str();
2383 if (!s_special.empty()) {
2384 // We had special arguments. Remove the trailing ','.
2385 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2387 // TODO: Handle the unknown settings better.
2388 // Warn about invalid options.
2389 // Check whether some option was given twice.
2393 else if (t.cs() == "footnote" ||
2394 (t.cs() == "thanks" && context.layout->intitle)) {
2396 context.check_layout(os);
2397 begin_inset(os, "Foot\n");
2398 os << "status collapsed\n\n";
2399 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2403 else if (t.cs() == "marginpar") {
2405 context.check_layout(os);
2406 begin_inset(os, "Marginal\n");
2407 os << "status collapsed\n\n";
2408 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2412 else if (t.cs() == "ensuremath") {
2414 context.check_layout(os);
2415 string const s = p.verbatim_item();
2416 //FIXME: this never triggers in UTF8
2417 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2420 handle_ert(os, "\\ensuremath{" + s + "}",
2424 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2425 // FIXME: Somehow prevent title layouts if
2426 // "maketitle" was not found
2428 skip_spaces_braces(p);
2431 else if (t.cs() == "tableofcontents") {
2432 context.check_layout(os);
2433 begin_command_inset(os, "toc", "tableofcontents");
2435 skip_spaces_braces(p);
2438 else if (t.cs() == "listoffigures") {
2439 context.check_layout(os);
2440 begin_inset(os, "FloatList figure\n");
2442 skip_spaces_braces(p);
2445 else if (t.cs() == "listoftables") {
2446 context.check_layout(os);
2447 begin_inset(os, "FloatList table\n");
2449 skip_spaces_braces(p);
2452 else if (t.cs() == "listof") {
2453 p.skip_spaces(true);
2454 string const name = p.get_token().cs();
2455 if (context.textclass.floats().typeExist(name)) {
2456 context.check_layout(os);
2457 begin_inset(os, "FloatList ");
2460 p.get_token(); // swallow second arg
2462 handle_ert(os, "\\listof{" + name + "}", context);
2465 else if (t.cs() == "textrm")
2466 parse_text_attributes(p, os, FLAG_ITEM, outer,
2467 context, "\\family",
2468 context.font.family, "roman");
2470 else if (t.cs() == "textsf")
2471 parse_text_attributes(p, os, FLAG_ITEM, outer,
2472 context, "\\family",
2473 context.font.family, "sans");
2475 else if (t.cs() == "texttt")
2476 parse_text_attributes(p, os, FLAG_ITEM, outer,
2477 context, "\\family",
2478 context.font.family, "typewriter");
2480 else if (t.cs() == "textmd")
2481 parse_text_attributes(p, os, FLAG_ITEM, outer,
2482 context, "\\series",
2483 context.font.series, "medium");
2485 else if (t.cs() == "textbf")
2486 parse_text_attributes(p, os, FLAG_ITEM, outer,
2487 context, "\\series",
2488 context.font.series, "bold");
2490 else if (t.cs() == "textup")
2491 parse_text_attributes(p, os, FLAG_ITEM, outer,
2493 context.font.shape, "up");
2495 else if (t.cs() == "textit")
2496 parse_text_attributes(p, os, FLAG_ITEM, outer,
2498 context.font.shape, "italic");
2500 else if (t.cs() == "textsl")
2501 parse_text_attributes(p, os, FLAG_ITEM, outer,
2503 context.font.shape, "slanted");
2505 else if (t.cs() == "textsc")
2506 parse_text_attributes(p, os, FLAG_ITEM, outer,
2508 context.font.shape, "smallcaps");
2510 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2511 context.check_layout(os);
2512 TeXFont oldFont = context.font;
2513 context.font.init();
2514 context.font.size = oldFont.size;
2515 os << "\n\\family " << context.font.family << "\n";
2516 os << "\n\\series " << context.font.series << "\n";
2517 os << "\n\\shape " << context.font.shape << "\n";
2518 if (t.cs() == "textnormal") {
2519 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2520 output_font_change(os, context.font, oldFont);
2521 context.font = oldFont;
2523 eat_whitespace(p, os, context, false);
2526 else if (t.cs() == "textcolor") {
2527 // scheme is \textcolor{color name}{text}
2528 string const color = p.verbatim_item();
2529 // we only support the predefined colors of the color package
2530 if (color == "black" || color == "blue" || color == "cyan"
2531 || color == "green" || color == "magenta" || color == "red"
2532 || color == "white" || color == "yellow") {
2533 context.check_layout(os);
2534 os << "\n\\color " << color << "\n";
2535 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2536 context.check_layout(os);
2537 os << "\n\\color inherit\n";
2539 // for custom defined colors
2540 handle_ert(os, t.asInput() + "{" + color + "}", context);
2543 else if (t.cs() == "underbar" || t.cs() == "uline") {
2544 // \underbar is not 100% correct (LyX outputs \uline
2545 // of ulem.sty). The difference is that \ulem allows
2546 // line breaks, and \underbar does not.
2547 // Do NOT handle \underline.
2548 // \underbar cuts through y, g, q, p etc.,
2549 // \underline does not.
2550 context.check_layout(os);
2551 os << "\n\\bar under\n";
2552 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2553 context.check_layout(os);
2554 os << "\n\\bar default\n";
2557 else if (t.cs() == "sout") {
2558 context.check_layout(os);
2559 os << "\n\\strikeout on\n";
2560 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2561 context.check_layout(os);
2562 os << "\n\\strikeout default\n";
2565 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
2566 t.cs() == "emph" || t.cs() == "noun") {
2567 context.check_layout(os);
2568 os << "\n\\" << t.cs() << " on\n";
2569 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2570 context.check_layout(os);
2571 os << "\n\\" << t.cs() << " default\n";
2574 // FIXME, the inset layout should be plain, not standard, see bug #7846
2575 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
2576 t.cs() == "vphantom") {
2577 context.check_layout(os);
2578 if (t.cs() == "phantom")
2579 begin_inset(os, "Phantom Phantom\n");
2580 if (t.cs() == "hphantom")
2581 begin_inset(os, "Phantom HPhantom\n");
2582 if (t.cs() == "vphantom")
2583 begin_inset(os, "Phantom VPhantom\n");
2584 os << "status open\n";
2585 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2589 else if (t.cs() == "href") {
2590 context.check_layout(os);
2591 string target = p.getArg('{', '}');
2592 string name = p.getArg('{', '}');
2594 size_t i = target.find(':');
2595 if (i != string::npos) {
2596 type = target.substr(0, i + 1);
2597 if (type == "mailto:" || type == "file:")
2598 target = target.substr(i + 1);
2599 // handle the case that name is equal to target, except of "http://"
2600 else if (target.substr(i + 3) == name && type == "http:")
2603 begin_command_inset(os, "href", "href");
2605 os << "name \"" << name << "\"\n";
2606 os << "target \"" << target << "\"\n";
2607 if (type == "mailto:" || type == "file:")
2608 os << "type \"" << type << "\"\n";
2610 skip_spaces_braces(p);
2613 else if (t.cs() == "lyxline") {
2614 // swallow size argument (it is not used anyway)
2616 if (!context.atParagraphStart()) {
2617 // so our line is in the middle of a paragraph
2618 // we need to add a new line, lest this line
2619 // follow the other content on that line and
2620 // run off the side of the page
2621 // FIXME: This may create an empty paragraph,
2622 // but without that it would not be
2623 // possible to set noindent below.
2624 // Fortunately LaTeX does not care
2625 // about the empty paragraph.
2626 context.new_paragraph(os);
2628 if (h_paragraph_separation == "indent") {
2629 // we need to unindent, lest the line be too long
2630 context.add_par_extra_stuff("\\noindent\n");
2632 context.check_layout(os);
2633 begin_command_inset(os, "line", "rule");
2634 os << "offset \"0.5ex\"\n"
2635 "width \"100line%\"\n"
2640 else if (t.cs() == "rule") {
2641 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
2642 string const width = p.getArg('{', '}');
2643 string const thickness = p.getArg('{', '}');
2644 context.check_layout(os);
2645 begin_command_inset(os, "line", "rule");
2646 if (!offset.empty())
2647 os << "offset \"" << translate_len(offset) << "\"\n";
2648 os << "width \"" << translate_len(width) << "\"\n"
2649 "height \"" << translate_len(thickness) << "\"\n";
2653 else if (is_known(t.cs(), known_phrases) ||
2654 (t.cs() == "protect" &&
2655 p.next_token().cat() == catEscape &&
2656 is_known(p.next_token().cs(), known_phrases))) {
2657 // LyX sometimes puts a \protect in front, so we have to ignore it
2658 // FIXME: This needs to be changed when bug 4752 is fixed.
2659 char const * const * where = is_known(
2660 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
2662 context.check_layout(os);
2663 os << known_coded_phrases[where - known_phrases];
2664 skip_spaces_braces(p);
2667 else if (is_known(t.cs(), known_ref_commands)) {
2668 string const opt = p.getOpt();
2670 context.check_layout(os);
2671 char const * const * where = is_known(t.cs(),
2672 known_ref_commands);
2673 begin_command_inset(os, "ref",
2674 known_coded_ref_commands[where - known_ref_commands]);
2675 os << "reference \""
2676 << convert_command_inset_arg(p.verbatim_item())
2680 // LyX does not support optional arguments of ref commands
2681 handle_ert(os, t.asInput() + '[' + opt + "]{" +
2682 p.verbatim_item() + "}", context);
2686 else if (use_natbib &&
2687 is_known(t.cs(), known_natbib_commands) &&
2688 ((t.cs() != "citefullauthor" &&
2689 t.cs() != "citeyear" &&
2690 t.cs() != "citeyearpar") ||
2691 p.next_token().asInput() != "*")) {
2692 context.check_layout(os);
2693 string command = t.cs();
2694 if (p.next_token().asInput() == "*") {
2698 if (command == "citefullauthor")
2699 // alternative name for "\\citeauthor*"
2700 command = "citeauthor*";
2702 // text before the citation
2704 // text after the citation
2706 get_cite_arguments(p, true, before, after);
2708 if (command == "cite") {
2709 // \cite without optional argument means
2710 // \citet, \cite with at least one optional
2711 // argument means \citep.
2712 if (before.empty() && after.empty())
2717 if (before.empty() && after == "[]")
2718 // avoid \citet[]{a}
2720 else if (before == "[]" && after == "[]") {
2721 // avoid \citet[][]{a}
2725 // remove the brackets around after and before
2726 if (!after.empty()) {
2728 after.erase(after.length() - 1, 1);
2729 after = convert_command_inset_arg(after);
2731 if (!before.empty()) {
2733 before.erase(before.length() - 1, 1);
2734 before = convert_command_inset_arg(before);
2736 begin_command_inset(os, "citation", command);
2737 os << "after " << '"' << after << '"' << "\n";
2738 os << "before " << '"' << before << '"' << "\n";
2740 << convert_command_inset_arg(p.verbatim_item())
2745 else if (use_jurabib &&
2746 is_known(t.cs(), known_jurabib_commands) &&
2747 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
2748 context.check_layout(os);
2749 string command = t.cs();
2750 if (p.next_token().asInput() == "*") {
2754 char argumentOrder = '\0';
2755 vector<string> const & options = used_packages["jurabib"];
2756 if (find(options.begin(), options.end(),
2757 "natbiborder") != options.end())
2758 argumentOrder = 'n';
2759 else if (find(options.begin(), options.end(),
2760 "jurabiborder") != options.end())
2761 argumentOrder = 'j';
2763 // text before the citation
2765 // text after the citation
2767 get_cite_arguments(p, argumentOrder != 'j', before, after);
2769 string const citation = p.verbatim_item();
2770 if (!before.empty() && argumentOrder == '\0') {
2771 cerr << "Warning: Assuming argument order "
2772 "of jurabib version 0.6 for\n'"
2773 << command << before << after << '{'
2774 << citation << "}'.\n"
2775 "Add 'jurabiborder' to the jurabib "
2776 "package options if you used an\n"
2777 "earlier jurabib version." << endl;
2779 if (!after.empty()) {
2781 after.erase(after.length() - 1, 1);
2783 if (!before.empty()) {
2785 before.erase(before.length() - 1, 1);
2787 begin_command_inset(os, "citation", command);
2788 os << "after " << '"' << after << '"' << "\n";
2789 os << "before " << '"' << before << '"' << "\n";
2790 os << "key " << '"' << citation << '"' << "\n";
2794 else if (t.cs() == "cite"
2795 || t.cs() == "nocite") {
2796 context.check_layout(os);
2797 string after = convert_command_inset_arg(p.getArg('[', ']'));
2798 string key = convert_command_inset_arg(p.verbatim_item());
2799 // store the case that it is "\nocite{*}" to use it later for
2802 begin_command_inset(os, "citation", t.cs());
2803 os << "after " << '"' << after << '"' << "\n";
2804 os << "key " << '"' << key << '"' << "\n";
2806 } else if (t.cs() == "nocite")
2810 else if (t.cs() == "index") {
2811 context.check_layout(os);
2812 begin_inset(os, "Index idx\n");
2813 os << "status collapsed\n";
2814 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
2818 else if (t.cs() == "nomenclature") {
2819 context.check_layout(os);
2820 begin_command_inset(os, "nomenclature", "nomenclature");
2821 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
2822 if (!prefix.empty())
2823 os << "prefix " << '"' << prefix << '"' << "\n";
2824 os << "symbol " << '"'
2825 << convert_command_inset_arg(p.verbatim_item());
2826 os << "\"\ndescription \""
2827 << convert_command_inset_arg(p.verbatim_item())
2832 else if (t.cs() == "label") {
2833 context.check_layout(os);
2834 begin_command_inset(os, "label", "label");
2836 << convert_command_inset_arg(p.verbatim_item())
2841 else if (t.cs() == "printindex") {
2842 context.check_layout(os);
2843 begin_command_inset(os, "index_print", "printindex");
2844 os << "type \"idx\"\n";
2846 skip_spaces_braces(p);
2849 else if (t.cs() == "printnomenclature") {
2851 string width_type = "";
2852 context.check_layout(os);
2853 begin_command_inset(os, "nomencl_print", "printnomenclature");
2854 // case of a custom width
2856 width = p.getArg('[', ']');
2857 width = translate_len(width);
2858 width_type = "custom";
2860 // case of no custom width
2861 // the case of no custom width but the width set
2862 // via \settowidth{\nomlabelwidth}{***} cannot be supported
2863 // because the user could have set anything, not only the width
2864 // of the longest label (which would be width_type = "auto")
2865 string label = convert_command_inset_arg(p.getArg('{', '}'));
2866 if (label.empty() && width_type.empty())
2867 width_type = "none";
2868 os << "set_width \"" << width_type << "\"\n";
2869 if (width_type == "custom")
2870 os << "width \"" << width << '\"';
2872 skip_spaces_braces(p);
2875 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
2876 context.check_layout(os);
2877 begin_inset(os, "script ");
2878 os << t.cs().substr(4) << '\n';
2879 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2883 else if (is_known(t.cs(), known_quotes)) {
2884 char const * const * where = is_known(t.cs(), known_quotes);
2885 context.check_layout(os);
2886 begin_inset(os, "Quotes ");
2887 os << known_coded_quotes[where - known_quotes];
2889 // LyX adds {} after the quote, so we have to eat
2890 // spaces here if there are any before a possible
2892 eat_whitespace(p, os, context, false);
2896 else if (is_known(t.cs(), known_sizes) &&
2897 context.new_layout_allowed) {
2898 char const * const * where = is_known(t.cs(), known_sizes);
2899 context.check_layout(os);
2900 TeXFont const oldFont = context.font;
2901 context.font.size = known_coded_sizes[where - known_sizes];
2902 output_font_change(os, oldFont, context.font);
2903 eat_whitespace(p, os, context, false);
2906 else if (is_known(t.cs(), known_font_families) &&
2907 context.new_layout_allowed) {
2908 char const * const * where =
2909 is_known(t.cs(), known_font_families);
2910 context.check_layout(os);
2911 TeXFont const oldFont = context.font;
2912 context.font.family =
2913 known_coded_font_families[where - known_font_families];
2914 output_font_change(os, oldFont, context.font);
2915 eat_whitespace(p, os, context, false);
2918 else if (is_known(t.cs(), known_font_series) &&
2919 context.new_layout_allowed) {
2920 char const * const * where =
2921 is_known(t.cs(), known_font_series);
2922 context.check_layout(os);
2923 TeXFont const oldFont = context.font;
2924 context.font.series =
2925 known_coded_font_series[where - known_font_series];
2926 output_font_change(os, oldFont, context.font);
2927 eat_whitespace(p, os, context, false);
2930 else if (is_known(t.cs(), known_font_shapes) &&
2931 context.new_layout_allowed) {
2932 char const * const * where =
2933 is_known(t.cs(), known_font_shapes);
2934 context.check_layout(os);
2935 TeXFont const oldFont = context.font;
2936 context.font.shape =
2937 known_coded_font_shapes[where - known_font_shapes];
2938 output_font_change(os, oldFont, context.font);
2939 eat_whitespace(p, os, context, false);
2941 else if (is_known(t.cs(), known_old_font_families) &&
2942 context.new_layout_allowed) {
2943 char const * const * where =
2944 is_known(t.cs(), known_old_font_families);
2945 context.check_layout(os);
2946 TeXFont const oldFont = context.font;
2947 context.font.init();
2948 context.font.size = oldFont.size;
2949 context.font.family =
2950 known_coded_font_families[where - known_old_font_families];
2951 output_font_change(os, oldFont, context.font);
2952 eat_whitespace(p, os, context, false);
2955 else if (is_known(t.cs(), known_old_font_series) &&
2956 context.new_layout_allowed) {
2957 char const * const * where =
2958 is_known(t.cs(), known_old_font_series);
2959 context.check_layout(os);
2960 TeXFont const oldFont = context.font;
2961 context.font.init();
2962 context.font.size = oldFont.size;
2963 context.font.series =
2964 known_coded_font_series[where - known_old_font_series];
2965 output_font_change(os, oldFont, context.font);
2966 eat_whitespace(p, os, context, false);
2969 else if (is_known(t.cs(), known_old_font_shapes) &&
2970 context.new_layout_allowed) {
2971 char const * const * where =
2972 is_known(t.cs(), known_old_font_shapes);
2973 context.check_layout(os);
2974 TeXFont const oldFont = context.font;
2975 context.font.init();
2976 context.font.size = oldFont.size;
2977 context.font.shape =
2978 known_coded_font_shapes[where - known_old_font_shapes];
2979 output_font_change(os, oldFont, context.font);
2980 eat_whitespace(p, os, context, false);
2983 else if (t.cs() == "selectlanguage") {
2984 context.check_layout(os);
2985 // save the language for the case that a
2986 // \foreignlanguage is used
2988 context.font.language = babel2lyx(p.verbatim_item());
2989 os << "\n\\lang " << context.font.language << "\n";
2992 else if (t.cs() == "foreignlanguage") {
2993 string const lang = babel2lyx(p.verbatim_item());
2994 parse_text_attributes(p, os, FLAG_ITEM, outer,
2996 context.font.language, lang);
2999 else if (t.cs() == "inputencoding") {
3000 // nothing to write here
3001 string const enc = subst(p.verbatim_item(), "\n", " ");
3005 else if (t.cs() == "ldots") {
3006 context.check_layout(os);
3007 os << "\\SpecialChar \\ldots{}\n";
3008 skip_spaces_braces(p);
3011 else if (t.cs() == "lyxarrow") {
3012 context.check_layout(os);
3013 os << "\\SpecialChar \\menuseparator\n";
3014 skip_spaces_braces(p);
3017 else if (t.cs() == "textcompwordmark") {
3018 context.check_layout(os);
3019 os << "\\SpecialChar \\textcompwordmark{}\n";
3020 skip_spaces_braces(p);
3023 else if (t.cs() == "slash") {
3024 context.check_layout(os);
3025 os << "\\SpecialChar \\slash{}\n";
3026 skip_spaces_braces(p);
3029 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3030 context.check_layout(os);
3031 os << "\\SpecialChar \\nobreakdash-\n";
3035 else if (t.cs() == "textquotedbl") {
3036 context.check_layout(os);
3041 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3042 context.check_layout(os);
3043 os << "\\SpecialChar \\@.\n";
3047 else if (t.cs() == "-") {
3048 context.check_layout(os);
3049 os << "\\SpecialChar \\-\n";
3052 else if (t.cs() == "textasciitilde") {
3053 context.check_layout(os);
3055 skip_spaces_braces(p);
3058 else if (t.cs() == "textasciicircum") {
3059 context.check_layout(os);
3061 skip_spaces_braces(p);
3064 else if (t.cs() == "textbackslash") {
3065 context.check_layout(os);
3066 os << "\n\\backslash\n";
3067 skip_spaces_braces(p);
3070 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3071 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3073 context.check_layout(os);
3077 else if (t.cs() == "char") {
3078 context.check_layout(os);
3079 if (p.next_token().character() == '`') {
3081 if (p.next_token().cs() == "\"") {
3086 handle_ert(os, "\\char`", context);
3089 handle_ert(os, "\\char", context);
3093 else if (t.cs() == "verb") {
3094 context.check_layout(os);
3095 char const delimiter = p.next_token().character();
3096 string const arg = p.getArg(delimiter, delimiter);
3098 oss << "\\verb" << delimiter << arg << delimiter;
3099 handle_ert(os, oss.str(), context);
3102 // Problem: \= creates a tabstop inside the tabbing environment
3103 // and else an accent. In the latter case we really would want
3104 // \={o} instead of \= o.
3105 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3106 handle_ert(os, t.asInput(), context);
3108 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3109 else if (t.cs().size() == 1
3110 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3111 context.check_layout(os);
3112 // try to see whether the string is in unicodesymbols
3114 string command = t.asInput() + "{"
3115 + trimSpaceAndEol(p.verbatim_item())
3117 docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
3120 cerr << "When parsing " << command
3121 << ", result is " << to_utf8(s)
3122 << "+" << to_utf8(rem) << endl;
3125 // we did not find a non-ert version
3126 handle_ert(os, command, context);
3129 else if (t.cs() == "\\") {
3130 context.check_layout(os);
3132 handle_ert(os, "\\\\" + p.getOpt(), context);
3133 else if (p.next_token().asInput() == "*") {
3135 // getOpt() eats the following space if there
3136 // is no optional argument, but that is OK
3137 // here since it has no effect in the output.
3138 handle_ert(os, "\\\\*" + p.getOpt(), context);
3141 begin_inset(os, "Newline newline");
3146 else if (t.cs() == "newline" ||
3147 (t.cs() == "linebreak" && !p.hasOpt())) {
3148 context.check_layout(os);
3149 begin_inset(os, "Newline ");
3152 skip_spaces_braces(p);
3155 else if (t.cs() == "input" || t.cs() == "include"
3156 || t.cs() == "verbatiminput") {
3157 string name = t.cs();
3158 if (t.cs() == "verbatiminput"
3159 && p.next_token().asInput() == "*")
3160 name += p.get_token().asInput();
3161 context.check_layout(os);
3162 string filename(normalize_filename(p.getArg('{', '}')));
3163 string const path = getMasterFilePath();
3164 // We want to preserve relative / absolute filenames,
3165 // therefore path is only used for testing
3166 if ((t.cs() == "include" || t.cs() == "input") &&
3167 !makeAbsPath(filename, path).exists()) {
3168 // The file extension is probably missing.
3169 // Now try to find it out.
3170 string const tex_name =
3171 find_file(filename, path,
3172 known_tex_extensions);
3173 if (!tex_name.empty())
3174 filename = tex_name;
3176 bool external = false;
3178 if (makeAbsPath(filename, path).exists()) {
3179 string const abstexname =
3180 makeAbsPath(filename, path).absFileName();
3181 string const abslyxname =
3182 changeExtension(abstexname, ".lyx");
3183 string const absfigname =
3184 changeExtension(abstexname, ".fig");
3185 fix_relative_filename(filename);
3186 string const lyxname =
3187 changeExtension(filename, ".lyx");
3189 external = FileName(absfigname).exists();
3190 if (t.cs() == "input") {
3191 string const ext = getExtension(abstexname);
3193 // Combined PS/LaTeX:
3194 // x.eps, x.pstex_t (old xfig)
3195 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3196 FileName const absepsname(
3197 changeExtension(abstexname, ".eps"));
3198 FileName const abspstexname(
3199 changeExtension(abstexname, ".pstex"));
3200 bool const xfigeps =
3201 (absepsname.exists() ||
3202 abspstexname.exists()) &&
3205 // Combined PDF/LaTeX:
3206 // x.pdf, x.pdftex_t (old xfig)
3207 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3208 FileName const abspdfname(
3209 changeExtension(abstexname, ".pdf"));
3210 bool const xfigpdf =
3211 abspdfname.exists() &&
3212 (ext == "pdftex_t" || ext == "pdf_t");
3216 // Combined PS/PDF/LaTeX:
3217 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3218 string const absbase2(
3219 removeExtension(abstexname) + "_pspdftex");
3220 FileName const abseps2name(
3221 addExtension(absbase2, ".eps"));
3222 FileName const abspdf2name(
3223 addExtension(absbase2, ".pdf"));
3224 bool const xfigboth =
3225 abspdf2name.exists() &&
3226 abseps2name.exists() && ext == "pspdftex";
3228 xfig = xfigpdf || xfigeps || xfigboth;
3229 external = external && xfig;
3232 outname = changeExtension(filename, ".fig");
3234 // Don't try to convert, the result
3235 // would be full of ERT.
3237 } else if (t.cs() != "verbatiminput" &&
3238 tex2lyx(abstexname, FileName(abslyxname),
3245 cerr << "Warning: Could not find included file '"
3246 << filename << "'." << endl;
3250 begin_inset(os, "External\n");
3251 os << "\ttemplate XFig\n"
3252 << "\tfilename " << outname << '\n';
3254 begin_command_inset(os, "include", name);
3255 os << "preview false\n"
3256 "filename \"" << outname << "\"\n";
3261 else if (t.cs() == "bibliographystyle") {
3262 // store new bibliographystyle
3263 bibliographystyle = p.verbatim_item();
3264 // If any other command than \bibliography and
3265 // \nocite{*} follows, we need to output the style
3266 // (because it might be used by that command).
3267 // Otherwise, it will automatically be output by LyX.
3270 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3271 if (t2.cat() == catBegin)
3273 if (t2.cat() != catEscape)
3275 if (t2.cs() == "nocite") {
3276 if (p.getArg('{', '}') == "*")
3278 } else if (t2.cs() == "bibliography")
3285 "\\bibliographystyle{" + bibliographystyle + '}',
3290 else if (t.cs() == "bibliography") {
3291 context.check_layout(os);
3292 begin_command_inset(os, "bibtex", "bibtex");
3293 if (!btprint.empty()) {
3294 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3295 // clear the string because the next BibTeX inset can be without the
3296 // \nocite{*} option
3299 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3300 // Do we have a bibliographystyle set?
3301 if (!bibliographystyle.empty())
3302 os << "options " << '"' << bibliographystyle << '"' << "\n";
3306 else if (t.cs() == "parbox")
3307 parse_box(p, os, 0, FLAG_ITEM, outer, context, "", "", t.cs());
3309 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3310 t.cs() == "shadowbox" || t.cs() == "doublebox")
3311 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3313 else if (t.cs() == "framebox") {
3314 string special = p.getFullOpt();
3315 special += p.getOpt();
3316 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), special);
3319 //\makebox() is part of the picture environment and different from \makebox{}
3320 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
3321 else if (t.cs() == "makebox") {
3322 string arg = t.asInput();
3323 if (p.next_token().character() == '(')
3324 //the syntax is: \makebox(x,y)[position]{content}
3325 arg += p.getFullParentheseArg();
3327 //the syntax is: \makebox[width][position]{content}
3328 arg += p.getFullOpt();
3329 handle_ert(os, arg + p.getFullOpt(), context);
3332 else if (t.cs() == "smallskip" ||
3333 t.cs() == "medskip" ||
3334 t.cs() == "bigskip" ||
3335 t.cs() == "vfill") {
3336 context.check_layout(os);
3337 begin_inset(os, "VSpace ");
3340 skip_spaces_braces(p);
3343 else if (is_known(t.cs(), known_spaces)) {
3344 char const * const * where = is_known(t.cs(), known_spaces);
3345 context.check_layout(os);
3346 begin_inset(os, "space ");
3347 os << '\\' << known_coded_spaces[where - known_spaces]
3350 // LaTeX swallows whitespace after all spaces except
3351 // "\\,". We have to do that here, too, because LyX
3352 // adds "{}" which would make the spaces significant.
3354 eat_whitespace(p, os, context, false);
3355 // LyX adds "{}" after all spaces except "\\ " and
3356 // "\\,", so we have to remove "{}".
3357 // "\\,{}" is equivalent to "\\," in LaTeX, so we
3358 // remove the braces after "\\,", too.
3363 else if (t.cs() == "newpage" ||
3364 (t.cs() == "pagebreak" && !p.hasOpt()) ||
3365 t.cs() == "clearpage" ||
3366 t.cs() == "cleardoublepage") {
3367 context.check_layout(os);
3368 begin_inset(os, "Newpage ");
3371 skip_spaces_braces(p);
3374 else if (t.cs() == "DeclareRobustCommand" ||
3375 t.cs() == "DeclareRobustCommandx" ||
3376 t.cs() == "newcommand" ||
3377 t.cs() == "newcommandx" ||
3378 t.cs() == "providecommand" ||
3379 t.cs() == "providecommandx" ||
3380 t.cs() == "renewcommand" ||
3381 t.cs() == "renewcommandx") {
3382 // DeclareRobustCommand, DeclareRobustCommandx,
3383 // providecommand and providecommandx could be handled
3384 // by parse_command(), but we need to call
3385 // add_known_command() here.
3386 string name = t.asInput();
3387 if (p.next_token().asInput() == "*") {
3388 // Starred form. Eat '*'
3392 string const command = p.verbatim_item();
3393 string const opt1 = p.getFullOpt();
3394 string const opt2 = p.getFullOpt();
3395 add_known_command(command, opt1, !opt2.empty());
3396 string const ert = name + '{' + command + '}' +
3398 '{' + p.verbatim_item() + '}';
3400 if (t.cs() == "DeclareRobustCommand" ||
3401 t.cs() == "DeclareRobustCommandx" ||
3402 t.cs() == "providecommand" ||
3403 t.cs() == "providecommandx" ||
3404 name[name.length()-1] == '*')
3405 handle_ert(os, ert, context);
3407 context.check_layout(os);
3408 begin_inset(os, "FormulaMacro");
3414 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3415 // let could be handled by parse_command(),
3416 // but we need to call add_known_command() here.
3417 string ert = t.asInput();
3420 if (p.next_token().cat() == catBegin) {
3421 name = p.verbatim_item();
3422 ert += '{' + name + '}';
3424 name = p.verbatim_item();
3429 if (p.next_token().cat() == catBegin) {
3430 command = p.verbatim_item();
3431 ert += '{' + command + '}';
3433 command = p.verbatim_item();
3436 // If command is known, make name known too, to parse
3437 // its arguments correctly. For this reason we also
3438 // have commands in syntax.default that are hardcoded.
3439 CommandMap::iterator it = known_commands.find(command);
3440 if (it != known_commands.end())
3441 known_commands[t.asInput()] = it->second;
3442 handle_ert(os, ert, context);
3445 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3446 bool starred = false;
3447 if (p.next_token().asInput() == "*") {
3451 string name = t.asInput();
3452 string const length = p.verbatim_item();
3455 bool valid = splitLatexLength(length, valstring, unit);
3456 bool known_hspace = false;
3457 bool known_vspace = false;
3458 bool known_unit = false;
3461 istringstream iss(valstring);
3464 if (t.cs()[0] == 'h') {
3465 if (unit == "\\fill") {
3470 known_hspace = true;
3473 if (unit == "\\smallskipamount") {
3475 known_vspace = true;
3476 } else if (unit == "\\medskipamount") {
3478 known_vspace = true;
3479 } else if (unit == "\\bigskipamount") {
3481 known_vspace = true;
3482 } else if (unit == "\\fill") {
3484 known_vspace = true;
3488 if (!known_hspace && !known_vspace) {
3489 switch (unitFromString(unit)) {
3510 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3511 // Literal horizontal length or known variable
3512 context.check_layout(os);
3513 begin_inset(os, "space ");
3521 if (known_unit && !known_hspace)
3523 << translate_len(length);
3525 } else if (known_unit || known_vspace) {
3526 // Literal vertical length or known variable
3527 context.check_layout(os);
3528 begin_inset(os, "VSpace ");
3536 // LyX can't handle other length variables in Inset VSpace/space
3541 handle_ert(os, name + '{' + unit + '}', context);
3542 else if (value == -1.0)
3543 handle_ert(os, name + "{-" + unit + '}', context);
3545 handle_ert(os, name + '{' + valstring + unit + '}', context);
3547 handle_ert(os, name + '{' + length + '}', context);
3551 // The single '=' is meant here.
3552 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3554 context.check_layout(os);
3555 begin_inset(os, "Flex ");
3556 os << to_utf8(newinsetlayout->name()) << '\n'
3557 << "status collapsed\n";
3558 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3563 // try to see whether the string is in unicodesymbols
3564 // Only use text mode commands, since we are in text mode here,
3565 // and math commands may be invalid (bug 6797)
3567 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
3568 rem, Encodings::TEXT_CMD);
3571 cerr << "When parsing " << t.cs()
3572 << ", result is " << to_utf8(s)
3573 << "+" << to_utf8(rem) << endl;
3574 context.check_layout(os);
3576 skip_spaces_braces(p);
3578 //cerr << "#: " << t << " mode: " << mode << endl;
3579 // heuristic: read up to next non-nested space
3581 string s = t.asInput();
3582 string z = p.verbatim_item();
3583 while (p.good() && z != " " && z.size()) {
3584 //cerr << "read: " << z << endl;
3586 z = p.verbatim_item();
3588 cerr << "found ERT: " << s << endl;
3589 handle_ert(os, s + ' ', context);
3592 string name = t.asInput();
3593 if (p.next_token().asInput() == "*") {
3594 // Starred commands like \vspace*{}
3595 p.get_token(); // Eat '*'
3598 if (!parse_command(name, p, os, outer, context))
3599 handle_ert(os, name, context);
3603 if (flags & FLAG_LEAVE) {
3604 flags &= ~FLAG_LEAVE;