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);
1089 else if (unstarred_name == "sidewaysfigure"
1090 || unstarred_name == "sidewaystable") {
1091 eat_whitespace(p, os, parent_context, false);
1092 parent_context.check_layout(os);
1093 if (unstarred_name == "sidewaysfigure")
1094 begin_inset(os, "Float figure\n");
1096 begin_inset(os, "Float table\n");
1097 os << "wide " << convert<string>(is_starred)
1098 << "\nsideways true"
1099 << "\nstatus open\n\n";
1100 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1102 // We don't need really a new paragraph, but
1103 // we must make sure that the next item gets a \begin_layout.
1104 parent_context.new_paragraph(os);
1108 else if (name == "wrapfigure" || name == "wraptable") {
1109 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1110 eat_whitespace(p, os, parent_context, false);
1111 parent_context.check_layout(os);
1114 string overhang = "0col%";
1117 lines = p.getArg('[', ']');
1118 string const placement = p.getArg('{', '}');
1120 overhang = p.getArg('[', ']');
1121 string const width = p.getArg('{', '}');
1123 if (name == "wrapfigure")
1124 begin_inset(os, "Wrap figure\n");
1126 begin_inset(os, "Wrap table\n");
1127 os << "lines " << lines
1128 << "\nplacement " << placement
1129 << "\noverhang " << lyx::translate_len(overhang)
1130 << "\nwidth " << lyx::translate_len(width)
1131 << "\nstatus open\n\n";
1132 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1134 // We don't need really a new paragraph, but
1135 // we must make sure that the next item gets a \begin_layout.
1136 parent_context.new_paragraph(os);
1140 else if (name == "minipage") {
1141 eat_whitespace(p, os, parent_context, false);
1142 parse_box(p, os, 0, FLAG_END, outer, parent_context, "", "", name);
1146 else if (name == "comment") {
1147 eat_whitespace(p, os, parent_context, false);
1148 parent_context.check_layout(os);
1149 begin_inset(os, "Note Comment\n");
1150 os << "status open\n";
1151 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1154 skip_braces(p); // eat {} that might by set by LyX behind comments
1157 else if (name == "lyxgreyedout") {
1158 eat_whitespace(p, os, parent_context, false);
1159 parent_context.check_layout(os);
1160 begin_inset(os, "Note Greyedout\n");
1161 os << "status open\n";
1162 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1167 else if (name == "framed" || name == "shaded") {
1168 eat_whitespace(p, os, parent_context, false);
1169 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1173 else if (name == "lstlisting") {
1174 eat_whitespace(p, os, parent_context, false);
1175 // FIXME handle listings with parameters
1177 parse_unknown_environment(p, name, os, FLAG_END,
1178 outer, parent_context);
1180 parse_listings(p, os, parent_context);
1184 else if (!parent_context.new_layout_allowed)
1185 parse_unknown_environment(p, name, os, FLAG_END, outer,
1188 // Alignment and spacing settings
1189 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1190 // therefore are totally broken!
1191 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1192 // they are commands not environments. They are furthermore switches that
1193 // can be ended by another switches, but also by commands like \footnote or
1194 // \parbox. So the only safe way is to leave them untouched.
1195 else if (name == "center" || name == "centering" ||
1196 name == "flushleft" || name == "flushright" ||
1197 name == "singlespace" || name == "onehalfspace" ||
1198 name == "doublespace" || name == "spacing") {
1199 eat_whitespace(p, os, parent_context, false);
1200 // We must begin a new paragraph if not already done
1201 if (! parent_context.atParagraphStart()) {
1202 parent_context.check_end_layout(os);
1203 parent_context.new_paragraph(os);
1205 if (name == "flushleft")
1206 parent_context.add_extra_stuff("\\align left\n");
1207 else if (name == "flushright")
1208 parent_context.add_extra_stuff("\\align right\n");
1209 else if (name == "center" || name == "centering")
1210 parent_context.add_extra_stuff("\\align center\n");
1211 else if (name == "singlespace")
1212 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1213 else if (name == "onehalfspace")
1214 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1215 else if (name == "doublespace")
1216 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1217 else if (name == "spacing")
1218 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1219 parse_text(p, os, FLAG_END, outer, parent_context);
1220 // Just in case the environment is empty
1221 parent_context.extra_stuff.erase();
1222 // We must begin a new paragraph to reset the alignment
1223 parent_context.new_paragraph(os);
1227 // The single '=' is meant here.
1228 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1229 eat_whitespace(p, os, parent_context, false);
1230 Context context(true, parent_context.textclass, newlayout,
1231 parent_context.layout, parent_context.font);
1232 if (parent_context.deeper_paragraph) {
1233 // We are beginning a nested environment after a
1234 // deeper paragraph inside the outer list environment.
1235 // Therefore we don't need to output a "begin deeper".
1236 context.need_end_deeper = true;
1238 parent_context.check_end_layout(os);
1239 if (last_env == name) {
1240 // we need to output a separator since LyX would export
1241 // the two environments as one otherwise (bug 5716)
1242 docstring const sep = from_ascii("--Separator--");
1243 TeX2LyXDocClass const & textclass(parent_context.textclass);
1244 if (textclass.hasLayout(sep)) {
1245 Context newcontext(parent_context);
1246 newcontext.layout = &(textclass[sep]);
1247 newcontext.check_layout(os);
1248 newcontext.check_end_layout(os);
1250 parent_context.check_layout(os);
1251 begin_inset(os, "Note Note\n");
1252 os << "status closed\n";
1253 Context newcontext(true, textclass,
1254 &(textclass.defaultLayout()));
1255 newcontext.check_layout(os);
1256 newcontext.check_end_layout(os);
1258 parent_context.check_end_layout(os);
1261 switch (context.layout->latextype) {
1262 case LATEX_LIST_ENVIRONMENT:
1263 context.add_par_extra_stuff("\\labelwidthstring "
1264 + p.verbatim_item() + '\n');
1267 case LATEX_BIB_ENVIRONMENT:
1268 p.verbatim_item(); // swallow next arg
1274 context.check_deeper(os);
1275 // handle known optional and required arguments
1276 // layouts require all optional arguments before the required ones
1277 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1278 // It is impossible to place anything after the environment name,
1279 // but before the first \\item.
1280 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1281 bool need_layout = true;
1282 unsigned int optargs = 0;
1283 while (optargs < context.layout->optargs) {
1284 eat_whitespace(p, os, context, false);
1285 if (p.next_token().cat() == catEscape ||
1286 p.next_token().character() != '[')
1288 p.get_token(); // eat '['
1290 context.check_layout(os);
1291 need_layout = false;
1293 begin_inset(os, "Argument\n");
1294 os << "status collapsed\n\n";
1295 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1297 eat_whitespace(p, os, context, false);
1300 unsigned int reqargs = 0;
1301 while (reqargs < context.layout->reqargs) {
1302 eat_whitespace(p, os, context, false);
1303 if (p.next_token().cat() != catBegin)
1305 p.get_token(); // eat '{'
1307 context.check_layout(os);
1308 need_layout = false;
1310 begin_inset(os, "Argument\n");
1311 os << "status collapsed\n\n";
1312 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1314 eat_whitespace(p, os, context, false);
1318 parse_text(p, os, FLAG_END, outer, context);
1319 context.check_end_layout(os);
1320 if (parent_context.deeper_paragraph) {
1321 // We must suppress the "end deeper" because we
1322 // suppressed the "begin deeper" above.
1323 context.need_end_deeper = false;
1325 context.check_end_deeper(os);
1326 parent_context.new_paragraph(os);
1330 // The single '=' is meant here.
1331 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1332 eat_whitespace(p, os, parent_context, false);
1333 parent_context.check_layout(os);
1334 begin_inset(os, "Flex ");
1335 os << to_utf8(newinsetlayout->name()) << '\n'
1336 << "status collapsed\n";
1337 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1341 else if (name == "appendix") {
1342 // This is no good latex style, but it works and is used in some documents...
1343 eat_whitespace(p, os, parent_context, false);
1344 parent_context.check_end_layout(os);
1345 Context context(true, parent_context.textclass, parent_context.layout,
1346 parent_context.layout, parent_context.font);
1347 context.check_layout(os);
1348 os << "\\start_of_appendix\n";
1349 parse_text(p, os, FLAG_END, outer, context);
1350 context.check_end_layout(os);
1354 else if (known_environments.find(name) != known_environments.end()) {
1355 vector<ArgumentType> arguments = known_environments[name];
1356 // The last "argument" denotes wether we may translate the
1357 // environment contents to LyX
1358 // The default required if no argument is given makes us
1359 // compatible with the reLyXre environment.
1360 ArgumentType contents = arguments.empty() ?
1363 if (!arguments.empty())
1364 arguments.pop_back();
1365 // See comment in parse_unknown_environment()
1366 bool const specialfont =
1367 (parent_context.font != parent_context.normalfont);
1368 bool const new_layout_allowed =
1369 parent_context.new_layout_allowed;
1371 parent_context.new_layout_allowed = false;
1372 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1373 outer, parent_context);
1374 if (contents == verbatim)
1375 handle_ert(os, p.verbatimEnvironment(name),
1378 parse_text_snippet(p, os, FLAG_END, outer,
1380 handle_ert(os, "\\end{" + name + "}", parent_context);
1382 parent_context.new_layout_allowed = new_layout_allowed;
1386 parse_unknown_environment(p, name, os, FLAG_END, outer,
1390 active_environments.pop_back();
1394 /// parses a comment and outputs it to \p os.
1395 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1397 LASSERT(t.cat() == catComment, return);
1398 if (!t.cs().empty()) {
1399 context.check_layout(os);
1400 handle_comment(os, '%' + t.cs(), context);
1401 if (p.next_token().cat() == catNewline) {
1402 // A newline after a comment line starts a new
1404 if (context.new_layout_allowed) {
1405 if(!context.atParagraphStart())
1406 // Only start a new paragraph if not already
1407 // done (we might get called recursively)
1408 context.new_paragraph(os);
1410 handle_ert(os, "\n", context);
1411 eat_whitespace(p, os, context, true);
1414 // "%\n" combination
1421 * Reads spaces and comments until the first non-space, non-comment token.
1422 * New paragraphs (double newlines or \\par) are handled like simple spaces
1423 * if \p eatParagraph is true.
1424 * Spaces are skipped, but comments are written to \p os.
1426 void eat_whitespace(Parser & p, ostream & os, Context & context,
1430 Token const & t = p.get_token();
1431 if (t.cat() == catComment)
1432 parse_comment(p, os, t, context);
1433 else if ((! eatParagraph && p.isParagraph()) ||
1434 (t.cat() != catSpace && t.cat() != catNewline)) {
1443 * Set a font attribute, parse text and reset the font attribute.
1444 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1445 * \param currentvalue Current value of the attribute. Is set to the new
1446 * value during parsing.
1447 * \param newvalue New value of the attribute
1449 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1450 Context & context, string const & attribute,
1451 string & currentvalue, string const & newvalue)
1453 context.check_layout(os);
1454 string const oldvalue = currentvalue;
1455 currentvalue = newvalue;
1456 os << '\n' << attribute << ' ' << newvalue << "\n";
1457 parse_text_snippet(p, os, flags, outer, context);
1458 context.check_layout(os);
1459 os << '\n' << attribute << ' ' << oldvalue << "\n";
1460 currentvalue = oldvalue;
1464 /// get the arguments of a natbib or jurabib citation command
1465 void get_cite_arguments(Parser & p, bool natbibOrder,
1466 string & before, string & after)
1468 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1470 // text before the citation
1472 // text after the citation
1473 after = p.getFullOpt();
1475 if (!after.empty()) {
1476 before = p.getFullOpt();
1477 if (natbibOrder && !before.empty())
1478 swap(before, after);
1483 /// Convert filenames with TeX macros and/or quotes to something LyX
1485 string const normalize_filename(string const & name)
1487 Parser p(trim(name, "\""));
1490 Token const & t = p.get_token();
1491 if (t.cat() != catEscape)
1493 else if (t.cs() == "lyxdot") {
1494 // This is used by LyX for simple dots in relative
1498 } else if (t.cs() == "space") {
1508 /// Convert \p name from TeX convention (relative to master file) to LyX
1509 /// convention (relative to .lyx file) if it is relative
1510 void fix_relative_filename(string & name)
1512 if (FileName::isAbsolute(name))
1515 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1516 from_utf8(getParentFilePath())));
1520 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1521 void parse_noweb(Parser & p, ostream & os, Context & context)
1523 // assemble the rest of the keyword
1527 Token const & t = p.get_token();
1528 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1531 scrap = (p.good() && p.next_token().asInput() == "=");
1533 name += p.get_token().asInput();
1536 name += t.asInput();
1539 if (!scrap || !context.new_layout_allowed ||
1540 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1541 cerr << "Warning: Could not interpret '" << name
1542 << "'. Ignoring it." << endl;
1546 // We use new_paragraph instead of check_end_layout because the stuff
1547 // following the noweb chunk needs to start with a \begin_layout.
1548 // This may create a new paragraph even if there was none in the
1549 // noweb file, but the alternative is an invalid LyX file. Since
1550 // noweb code chunks are implemented with a layout style in LyX they
1551 // always must be in an own paragraph.
1552 context.new_paragraph(os);
1553 Context newcontext(true, context.textclass,
1554 &context.textclass[from_ascii("Scrap")]);
1555 newcontext.check_layout(os);
1558 Token const & t = p.get_token();
1559 // We abuse the parser a bit, because this is no TeX syntax
1561 if (t.cat() == catEscape)
1562 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1565 Context tmp(false, context.textclass,
1566 &context.textclass[from_ascii("Scrap")]);
1567 tmp.need_end_layout = true;
1568 tmp.check_layout(oss);
1569 os << subst(t.asInput(), "\n", oss.str());
1571 // The scrap chunk is ended by an @ at the beginning of a line.
1572 // After the @ the line may contain a comment and/or
1573 // whitespace, but nothing else.
1574 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1575 (p.next_token().cat() == catSpace ||
1576 p.next_token().cat() == catNewline ||
1577 p.next_token().cat() == catComment)) {
1578 while (p.good() && p.next_token().cat() == catSpace)
1579 os << p.get_token().asInput();
1580 if (p.next_token().cat() == catComment)
1581 // The comment includes a final '\n'
1582 os << p.get_token().asInput();
1584 if (p.next_token().cat() == catNewline)
1591 newcontext.check_end_layout(os);
1595 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1596 bool is_macro(Parser & p)
1598 Token first = p.curr_token();
1599 if (first.cat() != catEscape || !p.good())
1601 if (first.cs() == "def")
1603 if (first.cs() != "global" && first.cs() != "long")
1605 Token second = p.get_token();
1607 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1608 second.cat() == catNewline || second.cat() == catComment)) {
1609 second = p.get_token();
1612 bool secondvalid = second.cat() == catEscape;
1614 bool thirdvalid = false;
1615 if (p.good() && first.cs() == "global" && secondvalid &&
1616 second.cs() == "long") {
1617 third = p.get_token();
1619 while (p.good() && !p.isParagraph() &&
1620 (third.cat() == catSpace ||
1621 third.cat() == catNewline ||
1622 third.cat() == catComment)) {
1623 third = p.get_token();
1626 thirdvalid = third.cat() == catEscape;
1628 for (int i = 0; i < pos; ++i)
1633 return (first.cs() == "global" || first.cs() == "long") &&
1634 second.cs() == "def";
1635 return first.cs() == "global" && second.cs() == "long" &&
1636 third.cs() == "def";
1640 /// Parse a macro definition (assumes that is_macro() returned true)
1641 void parse_macro(Parser & p, ostream & os, Context & context)
1643 context.check_layout(os);
1644 Token first = p.curr_token();
1647 string command = first.asInput();
1648 if (first.cs() != "def") {
1650 eat_whitespace(p, os, context, false);
1651 second = p.curr_token();
1652 command += second.asInput();
1653 if (second.cs() != "def") {
1655 eat_whitespace(p, os, context, false);
1656 third = p.curr_token();
1657 command += third.asInput();
1660 eat_whitespace(p, os, context, false);
1661 string const name = p.get_token().cs();
1662 eat_whitespace(p, os, context, false);
1668 while (p.next_token().cat() != catBegin) {
1669 if (p.next_token().cat() == catParameter) {
1674 // followed by number?
1675 if (p.next_token().cat() == catOther) {
1676 char c = p.getChar();
1678 // number = current arity + 1?
1679 if (c == arity + '0' + 1)
1684 paramtext += p.get_token().cs();
1686 paramtext += p.get_token().cs();
1691 // only output simple (i.e. compatible) macro as FormulaMacros
1692 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1694 context.check_layout(os);
1695 begin_inset(os, "FormulaMacro");
1696 os << "\n\\def" << ert;
1699 handle_ert(os, command + ert, context);
1702 } // anonymous namespace
1705 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1708 Layout const * newlayout = 0;
1709 InsetLayout const * newinsetlayout = 0;
1710 // Store the latest bibliographystyle and nocite{*} option
1711 // (needed for bibtex inset)
1713 string bibliographystyle;
1714 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1715 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1718 Token const & t = p.get_token();
1721 debugToken(cerr, t, flags);
1724 if (flags & FLAG_ITEM) {
1725 if (t.cat() == catSpace)
1728 flags &= ~FLAG_ITEM;
1729 if (t.cat() == catBegin) {
1730 // skip the brace and collect everything to the next matching
1732 flags |= FLAG_BRACE_LAST;
1736 // handle only this single token, leave the loop if done
1737 flags |= FLAG_LEAVE;
1740 if (t.cat() != catEscape && t.character() == ']' &&
1741 (flags & FLAG_BRACK_LAST))
1743 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1746 // If there is anything between \end{env} and \begin{env} we
1747 // don't need to output a separator.
1748 if (t.cat() != catSpace && t.cat() != catNewline &&
1749 t.asInput() != "\\begin")
1755 if (t.cat() == catMath) {
1756 // we are inside some text mode thingy, so opening new math is allowed
1757 context.check_layout(os);
1758 begin_inset(os, "Formula ");
1759 Token const & n = p.get_token();
1760 if (n.cat() == catMath && outer) {
1761 // TeX's $$...$$ syntax for displayed math
1763 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1765 p.get_token(); // skip the second '$' token
1767 // simple $...$ stuff
1770 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1776 else if (t.cat() == catSuper || t.cat() == catSub)
1777 cerr << "catcode " << t << " illegal in text mode\n";
1779 // Basic support for english quotes. This should be
1780 // extended to other quotes, but is not so easy (a
1781 // left english quote is the same as a right german
1783 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1784 context.check_layout(os);
1785 begin_inset(os, "Quotes ");
1791 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1792 context.check_layout(os);
1793 begin_inset(os, "Quotes ");
1800 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1801 context.check_layout(os);
1802 begin_inset(os, "Quotes ");
1809 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1810 context.check_layout(os);
1811 begin_inset(os, "Quotes ");
1818 else if (t.asInput() == "<"
1819 && p.next_token().asInput() == "<" && noweb_mode) {
1821 parse_noweb(p, os, context);
1824 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1825 check_space(p, os, context);
1827 else if (t.character() == '[' && noweb_mode &&
1828 p.next_token().character() == '[') {
1829 // These can contain underscores
1831 string const s = p.getFullOpt() + ']';
1832 if (p.next_token().character() == ']')
1835 cerr << "Warning: Inserting missing ']' in '"
1836 << s << "'." << endl;
1837 handle_ert(os, s, context);
1840 else if (t.cat() == catLetter) {
1841 context.check_layout(os);
1842 // Workaround for bug 4752.
1843 // FIXME: This whole code block needs to be removed
1844 // when the bug is fixed and tex2lyx produces
1845 // the updated file format.
1846 // The replacement algorithm in LyX is so stupid that
1847 // it even translates a phrase if it is part of a word.
1848 bool handled = false;
1849 for (int const * l = known_phrase_lengths; *l; ++l) {
1850 string phrase = t.cs();
1851 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
1852 phrase += p.get_token().cs();
1853 if (is_known(phrase, known_coded_phrases)) {
1854 handle_ert(os, phrase, context);
1858 for (size_t i = 1; i < phrase.length(); ++i)
1866 else if (t.cat() == catOther ||
1867 t.cat() == catAlign ||
1868 t.cat() == catParameter) {
1869 // This translates "&" to "\\&" which may be wrong...
1870 context.check_layout(os);
1874 else if (p.isParagraph()) {
1875 if (context.new_layout_allowed)
1876 context.new_paragraph(os);
1878 handle_ert(os, "\\par ", context);
1879 eat_whitespace(p, os, context, true);
1882 else if (t.cat() == catActive) {
1883 context.check_layout(os);
1884 if (t.character() == '~') {
1885 if (context.layout->free_spacing)
1888 begin_inset(os, "space ~\n");
1895 else if (t.cat() == catBegin &&
1896 p.next_token().cat() == catEnd) {
1898 Token const prev = p.prev_token();
1900 if (p.next_token().character() == '`' ||
1901 (prev.character() == '-' &&
1902 p.next_token().character() == '-'))
1903 ; // ignore it in {}`` or -{}-
1905 handle_ert(os, "{}", context);
1909 else if (t.cat() == catBegin) {
1910 context.check_layout(os);
1911 // special handling of font attribute changes
1912 Token const prev = p.prev_token();
1913 Token const next = p.next_token();
1914 TeXFont const oldFont = context.font;
1915 if (next.character() == '[' ||
1916 next.character() == ']' ||
1917 next.character() == '*') {
1919 if (p.next_token().cat() == catEnd) {
1924 handle_ert(os, "{", context);
1925 parse_text_snippet(p, os,
1928 handle_ert(os, "}", context);
1930 } else if (! context.new_layout_allowed) {
1931 handle_ert(os, "{", context);
1932 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1934 handle_ert(os, "}", context);
1935 } else if (is_known(next.cs(), known_sizes)) {
1936 // next will change the size, so we must
1938 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1940 if (!context.atParagraphStart())
1942 << context.font.size << "\n";
1943 } else if (is_known(next.cs(), known_font_families)) {
1944 // next will change the font family, so we
1945 // must reset it here
1946 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1948 if (!context.atParagraphStart())
1950 << context.font.family << "\n";
1951 } else if (is_known(next.cs(), known_font_series)) {
1952 // next will change the font series, so we
1953 // must reset it here
1954 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1956 if (!context.atParagraphStart())
1958 << context.font.series << "\n";
1959 } else if (is_known(next.cs(), known_font_shapes)) {
1960 // next will change the font shape, so we
1961 // must reset it here
1962 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1964 if (!context.atParagraphStart())
1966 << context.font.shape << "\n";
1967 } else if (is_known(next.cs(), known_old_font_families) ||
1968 is_known(next.cs(), known_old_font_series) ||
1969 is_known(next.cs(), known_old_font_shapes)) {
1970 // next will change the font family, series
1971 // and shape, so we must reset it here
1972 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1974 if (!context.atParagraphStart())
1976 << context.font.family
1978 << context.font.series
1980 << context.font.shape << "\n";
1982 handle_ert(os, "{", context);
1983 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1985 handle_ert(os, "}", context);
1989 else if (t.cat() == catEnd) {
1990 if (flags & FLAG_BRACE_LAST) {
1993 cerr << "stray '}' in text\n";
1994 handle_ert(os, "}", context);
1997 else if (t.cat() == catComment)
1998 parse_comment(p, os, t, context);
2001 // control sequences
2004 else if (t.cs() == "(") {
2005 context.check_layout(os);
2006 begin_inset(os, "Formula");
2008 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2013 else if (t.cs() == "[") {
2014 context.check_layout(os);
2015 begin_inset(os, "Formula");
2017 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2022 else if (t.cs() == "begin")
2023 parse_environment(p, os, outer, last_env, context);
2025 else if (t.cs() == "end") {
2026 if (flags & FLAG_END) {
2027 // eat environment name
2028 string const name = p.getArg('{', '}');
2029 if (name != active_environment())
2030 cerr << "\\end{" + name + "} does not match \\begin{"
2031 + active_environment() + "}\n";
2034 p.error("found 'end' unexpectedly");
2037 else if (t.cs() == "item") {
2040 bool optarg = false;
2041 if (p.next_token().cat() != catEscape &&
2042 p.next_token().character() == '[') {
2043 p.get_token(); // eat '['
2044 s = parse_text_snippet(p, FLAG_BRACK_LAST,
2049 context.check_layout(os);
2050 if (context.has_item) {
2051 // An item in an unknown list-like environment
2052 // FIXME: Do this in check_layout()!
2053 context.has_item = false;
2055 handle_ert(os, "\\item", context);
2057 handle_ert(os, "\\item ", context);
2060 if (context.layout->labeltype != LABEL_MANUAL) {
2061 // LyX does not support \item[\mybullet]
2062 // in itemize environments
2063 handle_ert(os, "[", context);
2065 handle_ert(os, "]", context);
2066 } else if (!s.empty()) {
2067 // The space is needed to separate the
2068 // item from the rest of the sentence.
2070 eat_whitespace(p, os, context, false);
2075 else if (t.cs() == "bibitem") {
2077 context.check_layout(os);
2078 string label = convert_command_inset_arg(p.getArg('[', ']'));
2079 string key = convert_command_inset_arg(p.verbatim_item());
2080 if (contains(label, '\\') || contains(key, '\\')) {
2081 // LyX can't handle LaTeX commands in labels or keys
2082 handle_ert(os, t.asInput() + '[' + label +
2083 "]{" + p.verbatim_item() + '}',
2086 begin_command_inset(os, "bibitem", "bibitem");
2087 os << "label \"" << label << "\"\n"
2088 "key \"" << key << "\"\n";
2093 else if (is_macro(p))
2094 parse_macro(p, os, context);
2096 else if (t.cs() == "noindent") {
2098 context.add_par_extra_stuff("\\noindent\n");
2101 else if (t.cs() == "appendix") {
2102 context.add_par_extra_stuff("\\start_of_appendix\n");
2103 // We need to start a new paragraph. Otherwise the
2104 // appendix in 'bla\appendix\chapter{' would start
2106 context.new_paragraph(os);
2107 // We need to make sure that the paragraph is
2108 // generated even if it is empty. Otherwise the
2109 // appendix in '\par\appendix\par\chapter{' would
2111 context.check_layout(os);
2112 // FIXME: This is a hack to prevent paragraph
2113 // deletion if it is empty. Handle this better!
2115 "%dummy comment inserted by tex2lyx to "
2116 "ensure that this paragraph is not empty",
2118 // Both measures above may generate an additional
2119 // empty paragraph, but that does not hurt, because
2120 // whitespace does not matter here.
2121 eat_whitespace(p, os, context, true);
2124 // Starred section headings
2125 // Must attempt to parse "Section*" before "Section".
2126 else if ((p.next_token().asInput() == "*") &&
2127 context.new_layout_allowed &&
2128 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2131 output_command_layout(os, p, outer, context, newlayout);
2135 // Section headings and the like
2136 else if (context.new_layout_allowed &&
2137 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2139 output_command_layout(os, p, outer, context, newlayout);
2143 else if (t.cs() == "caption") {
2145 context.check_layout(os);
2147 begin_inset(os, "Caption\n");
2148 Context newcontext(true, context.textclass);
2149 newcontext.font = context.font;
2150 newcontext.check_layout(os);
2151 if (p.next_token().cat() != catEscape &&
2152 p.next_token().character() == '[') {
2153 p.get_token(); // eat '['
2154 begin_inset(os, "Argument\n");
2155 os << "status collapsed\n";
2156 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2158 eat_whitespace(p, os, context, false);
2160 parse_text(p, os, FLAG_ITEM, outer, context);
2161 context.check_end_layout(os);
2162 // We don't need really a new paragraph, but
2163 // we must make sure that the next item gets a \begin_layout.
2164 context.new_paragraph(os);
2167 newcontext.check_end_layout(os);
2170 else if (t.cs() == "subfloat") {
2171 // the syntax is \subfloat[caption]{content}
2172 // if it is a table of figure depends on the surrounding float
2173 bool has_caption = false;
2175 // do nothing if there is no outer float
2176 if (!float_type.empty()) {
2177 context.check_layout(os);
2179 begin_inset(os, "Float " + float_type + "\n");
2181 << "\nsideways false"
2182 << "\nstatus collapsed\n\n";
2185 if (p.next_token().cat() != catEscape &&
2186 p.next_token().character() == '[') {
2187 p.get_token(); // eat '['
2188 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2192 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2193 // the caption comes always as the last
2195 // we must make sure that the caption gets a \begin_layout
2196 os << "\n\\begin_layout Plain Layout";
2198 begin_inset(os, "Caption\n");
2199 Context newcontext(true, context.textclass);
2200 newcontext.font = context.font;
2201 newcontext.check_layout(os);
2202 os << caption << "\n";
2203 newcontext.check_end_layout(os);
2204 // We don't need really a new paragraph, but
2205 // we must make sure that the next item gets a \begin_layout.
2206 //newcontext.new_paragraph(os);
2210 // We don't need really a new paragraph, but
2211 // we must make sure that the next item gets a \begin_layout.
2213 context.new_paragraph(os);
2216 context.check_end_layout(os);
2217 // close the layout we opened
2219 os << "\n\\end_layout\n";
2221 // if the float type is not supported or there is no surrounding float
2224 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2225 handle_ert(os, t.asInput() + '[' + opt_arg +
2226 "]{" + p.verbatim_item() + '}', context);
2228 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2232 else if (t.cs() == "includegraphics") {
2233 bool const clip = p.next_token().asInput() == "*";
2236 string const arg = p.getArg('[', ']');
2237 map<string, string> opts;
2238 vector<string> keys;
2239 split_map(arg, opts, keys);
2241 opts["clip"] = string();
2242 string name = normalize_filename(p.verbatim_item());
2244 string const path = getMasterFilePath();
2245 // We want to preserve relative / absolute filenames,
2246 // therefore path is only used for testing
2247 if (!makeAbsPath(name, path).exists()) {
2248 // The file extension is probably missing.
2249 // Now try to find it out.
2250 string const dvips_name =
2251 find_file(name, path,
2252 known_dvips_graphics_formats);
2253 string const pdftex_name =
2254 find_file(name, path,
2255 known_pdftex_graphics_formats);
2256 if (!dvips_name.empty()) {
2257 if (!pdftex_name.empty()) {
2258 cerr << "This file contains the "
2260 "\"\\includegraphics{"
2262 "However, files\n\""
2263 << dvips_name << "\" and\n\""
2264 << pdftex_name << "\"\n"
2265 "both exist, so I had to make a "
2266 "choice and took the first one.\n"
2267 "Please move the unwanted one "
2268 "someplace else and try again\n"
2269 "if my choice was wrong."
2273 } else if (!pdftex_name.empty()) {
2279 if (makeAbsPath(name, path).exists())
2280 fix_relative_filename(name);
2282 cerr << "Warning: Could not find graphics file '"
2283 << name << "'." << endl;
2285 context.check_layout(os);
2286 begin_inset(os, "Graphics ");
2287 os << "\n\tfilename " << name << '\n';
2288 if (opts.find("width") != opts.end())
2290 << translate_len(opts["width"]) << '\n';
2291 if (opts.find("height") != opts.end())
2293 << translate_len(opts["height"]) << '\n';
2294 if (opts.find("scale") != opts.end()) {
2295 istringstream iss(opts["scale"]);
2299 os << "\tscale " << val << '\n';
2301 if (opts.find("angle") != opts.end()) {
2302 os << "\trotateAngle "
2303 << opts["angle"] << '\n';
2304 vector<string>::const_iterator a =
2305 find(keys.begin(), keys.end(), "angle");
2306 vector<string>::const_iterator s =
2307 find(keys.begin(), keys.end(), "width");
2308 if (s == keys.end())
2309 s = find(keys.begin(), keys.end(), "height");
2310 if (s == keys.end())
2311 s = find(keys.begin(), keys.end(), "scale");
2312 if (s != keys.end() && distance(s, a) > 0)
2313 os << "\tscaleBeforeRotation\n";
2315 if (opts.find("origin") != opts.end()) {
2317 string const opt = opts["origin"];
2318 if (opt.find('l') != string::npos) ss << "left";
2319 if (opt.find('r') != string::npos) ss << "right";
2320 if (opt.find('c') != string::npos) ss << "center";
2321 if (opt.find('t') != string::npos) ss << "Top";
2322 if (opt.find('b') != string::npos) ss << "Bottom";
2323 if (opt.find('B') != string::npos) ss << "Baseline";
2324 if (!ss.str().empty())
2325 os << "\trotateOrigin " << ss.str() << '\n';
2327 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2329 if (opts.find("keepaspectratio") != opts.end())
2330 os << "\tkeepAspectRatio\n";
2331 if (opts.find("clip") != opts.end())
2333 if (opts.find("draft") != opts.end())
2335 if (opts.find("bb") != opts.end())
2336 os << "\tBoundingBox "
2337 << opts["bb"] << '\n';
2338 int numberOfbbOptions = 0;
2339 if (opts.find("bbllx") != opts.end())
2340 numberOfbbOptions++;
2341 if (opts.find("bblly") != opts.end())
2342 numberOfbbOptions++;
2343 if (opts.find("bburx") != opts.end())
2344 numberOfbbOptions++;
2345 if (opts.find("bbury") != opts.end())
2346 numberOfbbOptions++;
2347 if (numberOfbbOptions == 4)
2348 os << "\tBoundingBox "
2349 << opts["bbllx"] << " " << opts["bblly"] << " "
2350 << opts["bburx"] << " " << opts["bbury"] << '\n';
2351 else if (numberOfbbOptions > 0)
2352 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2353 numberOfbbOptions = 0;
2354 if (opts.find("natwidth") != opts.end())
2355 numberOfbbOptions++;
2356 if (opts.find("natheight") != opts.end())
2357 numberOfbbOptions++;
2358 if (numberOfbbOptions == 2)
2359 os << "\tBoundingBox 0bp 0bp "
2360 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2361 else if (numberOfbbOptions > 0)
2362 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2363 ostringstream special;
2364 if (opts.find("hiresbb") != opts.end())
2365 special << "hiresbb,";
2366 if (opts.find("trim") != opts.end())
2368 if (opts.find("viewport") != opts.end())
2369 special << "viewport=" << opts["viewport"] << ',';
2370 if (opts.find("totalheight") != opts.end())
2371 special << "totalheight=" << opts["totalheight"] << ',';
2372 if (opts.find("type") != opts.end())
2373 special << "type=" << opts["type"] << ',';
2374 if (opts.find("ext") != opts.end())
2375 special << "ext=" << opts["ext"] << ',';
2376 if (opts.find("read") != opts.end())
2377 special << "read=" << opts["read"] << ',';
2378 if (opts.find("command") != opts.end())
2379 special << "command=" << opts["command"] << ',';
2380 string s_special = special.str();
2381 if (!s_special.empty()) {
2382 // We had special arguments. Remove the trailing ','.
2383 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2385 // TODO: Handle the unknown settings better.
2386 // Warn about invalid options.
2387 // Check whether some option was given twice.
2391 else if (t.cs() == "footnote" ||
2392 (t.cs() == "thanks" && context.layout->intitle)) {
2394 context.check_layout(os);
2395 begin_inset(os, "Foot\n");
2396 os << "status collapsed\n\n";
2397 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2401 else if (t.cs() == "marginpar") {
2403 context.check_layout(os);
2404 begin_inset(os, "Marginal\n");
2405 os << "status collapsed\n\n";
2406 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2410 else if (t.cs() == "ensuremath") {
2412 context.check_layout(os);
2413 string const s = p.verbatim_item();
2414 //FIXME: this never triggers in UTF8
2415 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2418 handle_ert(os, "\\ensuremath{" + s + "}",
2422 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2423 // FIXME: Somehow prevent title layouts if
2424 // "maketitle" was not found
2426 skip_spaces_braces(p);
2429 else if (t.cs() == "tableofcontents") {
2430 context.check_layout(os);
2431 begin_command_inset(os, "toc", "tableofcontents");
2433 skip_spaces_braces(p);
2436 else if (t.cs() == "listoffigures") {
2437 context.check_layout(os);
2438 begin_inset(os, "FloatList figure\n");
2440 skip_spaces_braces(p);
2443 else if (t.cs() == "listoftables") {
2444 context.check_layout(os);
2445 begin_inset(os, "FloatList table\n");
2447 skip_spaces_braces(p);
2450 else if (t.cs() == "listof") {
2451 p.skip_spaces(true);
2452 string const name = p.get_token().cs();
2453 if (context.textclass.floats().typeExist(name)) {
2454 context.check_layout(os);
2455 begin_inset(os, "FloatList ");
2458 p.get_token(); // swallow second arg
2460 handle_ert(os, "\\listof{" + name + "}", context);
2463 else if (t.cs() == "textrm")
2464 parse_text_attributes(p, os, FLAG_ITEM, outer,
2465 context, "\\family",
2466 context.font.family, "roman");
2468 else if (t.cs() == "textsf")
2469 parse_text_attributes(p, os, FLAG_ITEM, outer,
2470 context, "\\family",
2471 context.font.family, "sans");
2473 else if (t.cs() == "texttt")
2474 parse_text_attributes(p, os, FLAG_ITEM, outer,
2475 context, "\\family",
2476 context.font.family, "typewriter");
2478 else if (t.cs() == "textmd")
2479 parse_text_attributes(p, os, FLAG_ITEM, outer,
2480 context, "\\series",
2481 context.font.series, "medium");
2483 else if (t.cs() == "textbf")
2484 parse_text_attributes(p, os, FLAG_ITEM, outer,
2485 context, "\\series",
2486 context.font.series, "bold");
2488 else if (t.cs() == "textup")
2489 parse_text_attributes(p, os, FLAG_ITEM, outer,
2491 context.font.shape, "up");
2493 else if (t.cs() == "textit")
2494 parse_text_attributes(p, os, FLAG_ITEM, outer,
2496 context.font.shape, "italic");
2498 else if (t.cs() == "textsl")
2499 parse_text_attributes(p, os, FLAG_ITEM, outer,
2501 context.font.shape, "slanted");
2503 else if (t.cs() == "textsc")
2504 parse_text_attributes(p, os, FLAG_ITEM, outer,
2506 context.font.shape, "smallcaps");
2508 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2509 context.check_layout(os);
2510 TeXFont oldFont = context.font;
2511 context.font.init();
2512 context.font.size = oldFont.size;
2513 os << "\n\\family " << context.font.family << "\n";
2514 os << "\n\\series " << context.font.series << "\n";
2515 os << "\n\\shape " << context.font.shape << "\n";
2516 if (t.cs() == "textnormal") {
2517 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2518 output_font_change(os, context.font, oldFont);
2519 context.font = oldFont;
2521 eat_whitespace(p, os, context, false);
2524 else if (t.cs() == "textcolor") {
2525 // scheme is \textcolor{color name}{text}
2526 string const color = p.verbatim_item();
2527 // we only support the predefined colors of the color package
2528 if (color == "black" || color == "blue" || color == "cyan"
2529 || color == "green" || color == "magenta" || color == "red"
2530 || color == "white" || color == "yellow") {
2531 context.check_layout(os);
2532 os << "\n\\color " << color << "\n";
2533 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2534 context.check_layout(os);
2535 os << "\n\\color inherit\n";
2537 // for custom defined colors
2538 handle_ert(os, t.asInput() + "{" + color + "}", context);
2541 else if (t.cs() == "underbar" || t.cs() == "uline") {
2542 // \underbar is not 100% correct (LyX outputs \uline
2543 // of ulem.sty). The difference is that \ulem allows
2544 // line breaks, and \underbar does not.
2545 // Do NOT handle \underline.
2546 // \underbar cuts through y, g, q, p etc.,
2547 // \underline does not.
2548 context.check_layout(os);
2549 os << "\n\\bar under\n";
2550 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2551 context.check_layout(os);
2552 os << "\n\\bar default\n";
2555 else if (t.cs() == "sout") {
2556 context.check_layout(os);
2557 os << "\n\\strikeout on\n";
2558 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2559 context.check_layout(os);
2560 os << "\n\\strikeout default\n";
2563 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
2564 t.cs() == "emph" || t.cs() == "noun") {
2565 context.check_layout(os);
2566 os << "\n\\" << t.cs() << " on\n";
2567 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2568 context.check_layout(os);
2569 os << "\n\\" << t.cs() << " default\n";
2572 // FIXME, the inset layout should be plain, not standard, see bug #7846
2573 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
2574 t.cs() == "vphantom") {
2575 context.check_layout(os);
2576 if (t.cs() == "phantom")
2577 begin_inset(os, "Phantom Phantom\n");
2578 if (t.cs() == "hphantom")
2579 begin_inset(os, "Phantom HPhantom\n");
2580 if (t.cs() == "vphantom")
2581 begin_inset(os, "Phantom VPhantom\n");
2582 os << "status open\n";
2583 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2587 else if (t.cs() == "href") {
2588 context.check_layout(os);
2589 string target = p.getArg('{', '}');
2590 string name = p.getArg('{', '}');
2592 size_t i = target.find(':');
2593 if (i != string::npos) {
2594 type = target.substr(0, i + 1);
2595 if (type == "mailto:" || type == "file:")
2596 target = target.substr(i + 1);
2597 // handle the case that name is equal to target, except of "http://"
2598 else if (target.substr(i + 3) == name && type == "http:")
2601 begin_command_inset(os, "href", "href");
2603 os << "name \"" << name << "\"\n";
2604 os << "target \"" << target << "\"\n";
2605 if (type == "mailto:" || type == "file:")
2606 os << "type \"" << type << "\"\n";
2608 skip_spaces_braces(p);
2611 else if (t.cs() == "lyxline") {
2612 // swallow size argument (it is not used anyway)
2614 if (!context.atParagraphStart()) {
2615 // so our line is in the middle of a paragraph
2616 // we need to add a new line, lest this line
2617 // follow the other content on that line and
2618 // run off the side of the page
2619 // FIXME: This may create an empty paragraph,
2620 // but without that it would not be
2621 // possible to set noindent below.
2622 // Fortunately LaTeX does not care
2623 // about the empty paragraph.
2624 context.new_paragraph(os);
2626 if (h_paragraph_separation == "indent") {
2627 // we need to unindent, lest the line be too long
2628 context.add_par_extra_stuff("\\noindent\n");
2630 context.check_layout(os);
2631 begin_command_inset(os, "line", "rule");
2632 os << "offset \"0.5ex\"\n"
2633 "width \"100line%\"\n"
2638 else if (t.cs() == "rule") {
2639 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
2640 string const width = p.getArg('{', '}');
2641 string const thickness = p.getArg('{', '}');
2642 context.check_layout(os);
2643 begin_command_inset(os, "line", "rule");
2644 if (!offset.empty())
2645 os << "offset \"" << translate_len(offset) << "\"\n";
2646 os << "width \"" << translate_len(width) << "\"\n"
2647 "height \"" << translate_len(thickness) << "\"\n";
2651 else if (is_known(t.cs(), known_phrases) ||
2652 (t.cs() == "protect" &&
2653 p.next_token().cat() == catEscape &&
2654 is_known(p.next_token().cs(), known_phrases))) {
2655 // LyX sometimes puts a \protect in front, so we have to ignore it
2656 // FIXME: This needs to be changed when bug 4752 is fixed.
2657 char const * const * where = is_known(
2658 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
2660 context.check_layout(os);
2661 os << known_coded_phrases[where - known_phrases];
2662 skip_spaces_braces(p);
2665 else if (is_known(t.cs(), known_ref_commands)) {
2666 string const opt = p.getOpt();
2668 context.check_layout(os);
2669 char const * const * where = is_known(t.cs(),
2670 known_ref_commands);
2671 begin_command_inset(os, "ref",
2672 known_coded_ref_commands[where - known_ref_commands]);
2673 os << "reference \""
2674 << convert_command_inset_arg(p.verbatim_item())
2678 // LyX does not support optional arguments of ref commands
2679 handle_ert(os, t.asInput() + '[' + opt + "]{" +
2680 p.verbatim_item() + "}", context);
2684 else if (use_natbib &&
2685 is_known(t.cs(), known_natbib_commands) &&
2686 ((t.cs() != "citefullauthor" &&
2687 t.cs() != "citeyear" &&
2688 t.cs() != "citeyearpar") ||
2689 p.next_token().asInput() != "*")) {
2690 context.check_layout(os);
2691 string command = t.cs();
2692 if (p.next_token().asInput() == "*") {
2696 if (command == "citefullauthor")
2697 // alternative name for "\\citeauthor*"
2698 command = "citeauthor*";
2700 // text before the citation
2702 // text after the citation
2704 get_cite_arguments(p, true, before, after);
2706 if (command == "cite") {
2707 // \cite without optional argument means
2708 // \citet, \cite with at least one optional
2709 // argument means \citep.
2710 if (before.empty() && after.empty())
2715 if (before.empty() && after == "[]")
2716 // avoid \citet[]{a}
2718 else if (before == "[]" && after == "[]") {
2719 // avoid \citet[][]{a}
2723 // remove the brackets around after and before
2724 if (!after.empty()) {
2726 after.erase(after.length() - 1, 1);
2727 after = convert_command_inset_arg(after);
2729 if (!before.empty()) {
2731 before.erase(before.length() - 1, 1);
2732 before = convert_command_inset_arg(before);
2734 begin_command_inset(os, "citation", command);
2735 os << "after " << '"' << after << '"' << "\n";
2736 os << "before " << '"' << before << '"' << "\n";
2738 << convert_command_inset_arg(p.verbatim_item())
2743 else if (use_jurabib &&
2744 is_known(t.cs(), known_jurabib_commands) &&
2745 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
2746 context.check_layout(os);
2747 string command = t.cs();
2748 if (p.next_token().asInput() == "*") {
2752 char argumentOrder = '\0';
2753 vector<string> const & options = used_packages["jurabib"];
2754 if (find(options.begin(), options.end(),
2755 "natbiborder") != options.end())
2756 argumentOrder = 'n';
2757 else if (find(options.begin(), options.end(),
2758 "jurabiborder") != options.end())
2759 argumentOrder = 'j';
2761 // text before the citation
2763 // text after the citation
2765 get_cite_arguments(p, argumentOrder != 'j', before, after);
2767 string const citation = p.verbatim_item();
2768 if (!before.empty() && argumentOrder == '\0') {
2769 cerr << "Warning: Assuming argument order "
2770 "of jurabib version 0.6 for\n'"
2771 << command << before << after << '{'
2772 << citation << "}'.\n"
2773 "Add 'jurabiborder' to the jurabib "
2774 "package options if you used an\n"
2775 "earlier jurabib version." << endl;
2777 if (!after.empty()) {
2779 after.erase(after.length() - 1, 1);
2781 if (!before.empty()) {
2783 before.erase(before.length() - 1, 1);
2785 begin_command_inset(os, "citation", command);
2786 os << "after " << '"' << after << '"' << "\n";
2787 os << "before " << '"' << before << '"' << "\n";
2788 os << "key " << '"' << citation << '"' << "\n";
2792 else if (t.cs() == "cite"
2793 || t.cs() == "nocite") {
2794 context.check_layout(os);
2795 string after = convert_command_inset_arg(p.getArg('[', ']'));
2796 string key = convert_command_inset_arg(p.verbatim_item());
2797 // store the case that it is "\nocite{*}" to use it later for
2800 begin_command_inset(os, "citation", t.cs());
2801 os << "after " << '"' << after << '"' << "\n";
2802 os << "key " << '"' << key << '"' << "\n";
2804 } else if (t.cs() == "nocite")
2808 else if (t.cs() == "index") {
2809 context.check_layout(os);
2810 begin_inset(os, "Index idx\n");
2811 os << "status collapsed\n";
2812 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
2816 else if (t.cs() == "nomenclature") {
2817 context.check_layout(os);
2818 begin_command_inset(os, "nomenclature", "nomenclature");
2819 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
2820 if (!prefix.empty())
2821 os << "prefix " << '"' << prefix << '"' << "\n";
2822 os << "symbol " << '"'
2823 << convert_command_inset_arg(p.verbatim_item());
2824 os << "\"\ndescription \""
2825 << convert_command_inset_arg(p.verbatim_item())
2830 else if (t.cs() == "label") {
2831 context.check_layout(os);
2832 begin_command_inset(os, "label", "label");
2834 << convert_command_inset_arg(p.verbatim_item())
2839 else if (t.cs() == "printindex") {
2840 context.check_layout(os);
2841 begin_command_inset(os, "index_print", "printindex");
2842 os << "type \"idx\"\n";
2844 skip_spaces_braces(p);
2847 else if (t.cs() == "printnomenclature") {
2849 string width_type = "";
2850 context.check_layout(os);
2851 begin_command_inset(os, "nomencl_print", "printnomenclature");
2852 // case of a custom width
2854 width = p.getArg('[', ']');
2855 width = translate_len(width);
2856 width_type = "custom";
2858 // case of no custom width
2859 // the case of no custom width but the width set
2860 // via \settowidth{\nomlabelwidth}{***} cannot be supported
2861 // because the user could have set anything, not only the width
2862 // of the longest label (which would be width_type = "auto")
2863 string label = convert_command_inset_arg(p.getArg('{', '}'));
2864 if (label.empty() && width_type.empty())
2865 width_type = "none";
2866 os << "set_width \"" << width_type << "\"\n";
2867 if (width_type == "custom")
2868 os << "width \"" << width << '\"';
2870 skip_spaces_braces(p);
2873 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
2874 context.check_layout(os);
2875 begin_inset(os, "script ");
2876 os << t.cs().substr(4) << '\n';
2877 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2881 else if (is_known(t.cs(), known_quotes)) {
2882 char const * const * where = is_known(t.cs(), known_quotes);
2883 context.check_layout(os);
2884 begin_inset(os, "Quotes ");
2885 os << known_coded_quotes[where - known_quotes];
2887 // LyX adds {} after the quote, so we have to eat
2888 // spaces here if there are any before a possible
2890 eat_whitespace(p, os, context, false);
2894 else if (is_known(t.cs(), known_sizes) &&
2895 context.new_layout_allowed) {
2896 char const * const * where = is_known(t.cs(), known_sizes);
2897 context.check_layout(os);
2898 TeXFont const oldFont = context.font;
2899 context.font.size = known_coded_sizes[where - known_sizes];
2900 output_font_change(os, oldFont, context.font);
2901 eat_whitespace(p, os, context, false);
2904 else if (is_known(t.cs(), known_font_families) &&
2905 context.new_layout_allowed) {
2906 char const * const * where =
2907 is_known(t.cs(), known_font_families);
2908 context.check_layout(os);
2909 TeXFont const oldFont = context.font;
2910 context.font.family =
2911 known_coded_font_families[where - known_font_families];
2912 output_font_change(os, oldFont, context.font);
2913 eat_whitespace(p, os, context, false);
2916 else if (is_known(t.cs(), known_font_series) &&
2917 context.new_layout_allowed) {
2918 char const * const * where =
2919 is_known(t.cs(), known_font_series);
2920 context.check_layout(os);
2921 TeXFont const oldFont = context.font;
2922 context.font.series =
2923 known_coded_font_series[where - known_font_series];
2924 output_font_change(os, oldFont, context.font);
2925 eat_whitespace(p, os, context, false);
2928 else if (is_known(t.cs(), known_font_shapes) &&
2929 context.new_layout_allowed) {
2930 char const * const * where =
2931 is_known(t.cs(), known_font_shapes);
2932 context.check_layout(os);
2933 TeXFont const oldFont = context.font;
2934 context.font.shape =
2935 known_coded_font_shapes[where - known_font_shapes];
2936 output_font_change(os, oldFont, context.font);
2937 eat_whitespace(p, os, context, false);
2939 else if (is_known(t.cs(), known_old_font_families) &&
2940 context.new_layout_allowed) {
2941 char const * const * where =
2942 is_known(t.cs(), known_old_font_families);
2943 context.check_layout(os);
2944 TeXFont const oldFont = context.font;
2945 context.font.init();
2946 context.font.size = oldFont.size;
2947 context.font.family =
2948 known_coded_font_families[where - known_old_font_families];
2949 output_font_change(os, oldFont, context.font);
2950 eat_whitespace(p, os, context, false);
2953 else if (is_known(t.cs(), known_old_font_series) &&
2954 context.new_layout_allowed) {
2955 char const * const * where =
2956 is_known(t.cs(), known_old_font_series);
2957 context.check_layout(os);
2958 TeXFont const oldFont = context.font;
2959 context.font.init();
2960 context.font.size = oldFont.size;
2961 context.font.series =
2962 known_coded_font_series[where - known_old_font_series];
2963 output_font_change(os, oldFont, context.font);
2964 eat_whitespace(p, os, context, false);
2967 else if (is_known(t.cs(), known_old_font_shapes) &&
2968 context.new_layout_allowed) {
2969 char const * const * where =
2970 is_known(t.cs(), known_old_font_shapes);
2971 context.check_layout(os);
2972 TeXFont const oldFont = context.font;
2973 context.font.init();
2974 context.font.size = oldFont.size;
2975 context.font.shape =
2976 known_coded_font_shapes[where - known_old_font_shapes];
2977 output_font_change(os, oldFont, context.font);
2978 eat_whitespace(p, os, context, false);
2981 else if (t.cs() == "selectlanguage") {
2982 context.check_layout(os);
2983 // save the language for the case that a
2984 // \foreignlanguage is used
2986 context.font.language = babel2lyx(p.verbatim_item());
2987 os << "\n\\lang " << context.font.language << "\n";
2990 else if (t.cs() == "foreignlanguage") {
2991 string const lang = babel2lyx(p.verbatim_item());
2992 parse_text_attributes(p, os, FLAG_ITEM, outer,
2994 context.font.language, lang);
2997 else if (t.cs() == "inputencoding") {
2998 // nothing to write here
2999 string const enc = subst(p.verbatim_item(), "\n", " ");
3003 else if (t.cs() == "ldots") {
3004 context.check_layout(os);
3005 os << "\\SpecialChar \\ldots{}\n";
3006 skip_spaces_braces(p);
3009 else if (t.cs() == "lyxarrow") {
3010 context.check_layout(os);
3011 os << "\\SpecialChar \\menuseparator\n";
3012 skip_spaces_braces(p);
3015 else if (t.cs() == "textcompwordmark") {
3016 context.check_layout(os);
3017 os << "\\SpecialChar \\textcompwordmark{}\n";
3018 skip_spaces_braces(p);
3021 else if (t.cs() == "slash") {
3022 context.check_layout(os);
3023 os << "\\SpecialChar \\slash{}\n";
3024 skip_spaces_braces(p);
3027 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3028 context.check_layout(os);
3029 os << "\\SpecialChar \\nobreakdash-\n";
3033 else if (t.cs() == "textquotedbl") {
3034 context.check_layout(os);
3039 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3040 context.check_layout(os);
3041 os << "\\SpecialChar \\@.\n";
3045 else if (t.cs() == "-") {
3046 context.check_layout(os);
3047 os << "\\SpecialChar \\-\n";
3050 else if (t.cs() == "textasciitilde") {
3051 context.check_layout(os);
3053 skip_spaces_braces(p);
3056 else if (t.cs() == "textasciicircum") {
3057 context.check_layout(os);
3059 skip_spaces_braces(p);
3062 else if (t.cs() == "textbackslash") {
3063 context.check_layout(os);
3064 os << "\n\\backslash\n";
3065 skip_spaces_braces(p);
3068 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3069 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3071 context.check_layout(os);
3075 else if (t.cs() == "char") {
3076 context.check_layout(os);
3077 if (p.next_token().character() == '`') {
3079 if (p.next_token().cs() == "\"") {
3084 handle_ert(os, "\\char`", context);
3087 handle_ert(os, "\\char", context);
3091 else if (t.cs() == "verb") {
3092 context.check_layout(os);
3093 char const delimiter = p.next_token().character();
3094 string const arg = p.getArg(delimiter, delimiter);
3096 oss << "\\verb" << delimiter << arg << delimiter;
3097 handle_ert(os, oss.str(), context);
3100 // Problem: \= creates a tabstop inside the tabbing environment
3101 // and else an accent. In the latter case we really would want
3102 // \={o} instead of \= o.
3103 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3104 handle_ert(os, t.asInput(), context);
3106 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3107 else if (t.cs().size() == 1
3108 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3109 context.check_layout(os);
3110 // try to see whether the string is in unicodesymbols
3112 string command = t.asInput() + "{"
3113 + trimSpaceAndEol(p.verbatim_item())
3115 docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
3118 cerr << "When parsing " << command
3119 << ", result is " << to_utf8(s)
3120 << "+" << to_utf8(rem) << endl;
3123 // we did not find a non-ert version
3124 handle_ert(os, command, context);
3127 else if (t.cs() == "\\") {
3128 context.check_layout(os);
3130 handle_ert(os, "\\\\" + p.getOpt(), context);
3131 else if (p.next_token().asInput() == "*") {
3133 // getOpt() eats the following space if there
3134 // is no optional argument, but that is OK
3135 // here since it has no effect in the output.
3136 handle_ert(os, "\\\\*" + p.getOpt(), context);
3139 begin_inset(os, "Newline newline");
3144 else if (t.cs() == "newline" ||
3145 (t.cs() == "linebreak" && !p.hasOpt())) {
3146 context.check_layout(os);
3147 begin_inset(os, "Newline ");
3150 skip_spaces_braces(p);
3153 else if (t.cs() == "input" || t.cs() == "include"
3154 || t.cs() == "verbatiminput") {
3155 string name = t.cs();
3156 if (t.cs() == "verbatiminput"
3157 && p.next_token().asInput() == "*")
3158 name += p.get_token().asInput();
3159 context.check_layout(os);
3160 string filename(normalize_filename(p.getArg('{', '}')));
3161 string const path = getMasterFilePath();
3162 // We want to preserve relative / absolute filenames,
3163 // therefore path is only used for testing
3164 if ((t.cs() == "include" || t.cs() == "input") &&
3165 !makeAbsPath(filename, path).exists()) {
3166 // The file extension is probably missing.
3167 // Now try to find it out.
3168 string const tex_name =
3169 find_file(filename, path,
3170 known_tex_extensions);
3171 if (!tex_name.empty())
3172 filename = tex_name;
3174 bool external = false;
3176 if (makeAbsPath(filename, path).exists()) {
3177 string const abstexname =
3178 makeAbsPath(filename, path).absFileName();
3179 string const abslyxname =
3180 changeExtension(abstexname, ".lyx");
3181 string const absfigname =
3182 changeExtension(abstexname, ".fig");
3183 fix_relative_filename(filename);
3184 string const lyxname =
3185 changeExtension(filename, ".lyx");
3187 external = FileName(absfigname).exists();
3188 if (t.cs() == "input") {
3189 string const ext = getExtension(abstexname);
3191 // Combined PS/LaTeX:
3192 // x.eps, x.pstex_t (old xfig)
3193 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3194 FileName const absepsname(
3195 changeExtension(abstexname, ".eps"));
3196 FileName const abspstexname(
3197 changeExtension(abstexname, ".pstex"));
3198 bool const xfigeps =
3199 (absepsname.exists() ||
3200 abspstexname.exists()) &&
3203 // Combined PDF/LaTeX:
3204 // x.pdf, x.pdftex_t (old xfig)
3205 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3206 FileName const abspdfname(
3207 changeExtension(abstexname, ".pdf"));
3208 bool const xfigpdf =
3209 abspdfname.exists() &&
3210 (ext == "pdftex_t" || ext == "pdf_t");
3214 // Combined PS/PDF/LaTeX:
3215 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3216 string const absbase2(
3217 removeExtension(abstexname) + "_pspdftex");
3218 FileName const abseps2name(
3219 addExtension(absbase2, ".eps"));
3220 FileName const abspdf2name(
3221 addExtension(absbase2, ".pdf"));
3222 bool const xfigboth =
3223 abspdf2name.exists() &&
3224 abseps2name.exists() && ext == "pspdftex";
3226 xfig = xfigpdf || xfigeps || xfigboth;
3227 external = external && xfig;
3230 outname = changeExtension(filename, ".fig");
3232 // Don't try to convert, the result
3233 // would be full of ERT.
3235 } else if (t.cs() != "verbatiminput" &&
3236 tex2lyx(abstexname, FileName(abslyxname),
3243 cerr << "Warning: Could not find included file '"
3244 << filename << "'." << endl;
3248 begin_inset(os, "External\n");
3249 os << "\ttemplate XFig\n"
3250 << "\tfilename " << outname << '\n';
3252 begin_command_inset(os, "include", name);
3253 os << "preview false\n"
3254 "filename \"" << outname << "\"\n";
3259 else if (t.cs() == "bibliographystyle") {
3260 // store new bibliographystyle
3261 bibliographystyle = p.verbatim_item();
3262 // If any other command than \bibliography and
3263 // \nocite{*} follows, we need to output the style
3264 // (because it might be used by that command).
3265 // Otherwise, it will automatically be output by LyX.
3268 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3269 if (t2.cat() == catBegin)
3271 if (t2.cat() != catEscape)
3273 if (t2.cs() == "nocite") {
3274 if (p.getArg('{', '}') == "*")
3276 } else if (t2.cs() == "bibliography")
3283 "\\bibliographystyle{" + bibliographystyle + '}',
3288 else if (t.cs() == "bibliography") {
3289 context.check_layout(os);
3290 begin_command_inset(os, "bibtex", "bibtex");
3291 if (!btprint.empty()) {
3292 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3293 // clear the string because the next BibTeX inset can be without the
3294 // \nocite{*} option
3297 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3298 // Do we have a bibliographystyle set?
3299 if (!bibliographystyle.empty())
3300 os << "options " << '"' << bibliographystyle << '"' << "\n";
3304 else if (t.cs() == "parbox")
3305 parse_box(p, os, 0, FLAG_ITEM, outer, context, "", "", t.cs());
3307 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3308 t.cs() == "shadowbox" || t.cs() == "doublebox")
3309 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3311 else if (t.cs() == "framebox") {
3312 string special = p.getFullOpt();
3313 special += p.getOpt();
3314 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), special);
3317 //\makebox() is part of the picture environment and different from \makebox{}
3318 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
3319 else if (t.cs() == "makebox") {
3320 string arg = t.asInput();
3321 if (p.next_token().character() == '(')
3322 //the syntax is: \makebox(x,y)[position]{content}
3323 arg += p.getFullParentheseArg();
3325 //the syntax is: \makebox[width][position]{content}
3326 arg += p.getFullOpt();
3327 handle_ert(os, arg + p.getFullOpt(), context);
3330 else if (t.cs() == "smallskip" ||
3331 t.cs() == "medskip" ||
3332 t.cs() == "bigskip" ||
3333 t.cs() == "vfill") {
3334 context.check_layout(os);
3335 begin_inset(os, "VSpace ");
3338 skip_spaces_braces(p);
3341 else if (is_known(t.cs(), known_spaces)) {
3342 char const * const * where = is_known(t.cs(), known_spaces);
3343 context.check_layout(os);
3344 begin_inset(os, "space ");
3345 os << '\\' << known_coded_spaces[where - known_spaces]
3348 // LaTeX swallows whitespace after all spaces except
3349 // "\\,". We have to do that here, too, because LyX
3350 // adds "{}" which would make the spaces significant.
3352 eat_whitespace(p, os, context, false);
3353 // LyX adds "{}" after all spaces except "\\ " and
3354 // "\\,", so we have to remove "{}".
3355 // "\\,{}" is equivalent to "\\," in LaTeX, so we
3356 // remove the braces after "\\,", too.
3361 else if (t.cs() == "newpage" ||
3362 (t.cs() == "pagebreak" && !p.hasOpt()) ||
3363 t.cs() == "clearpage" ||
3364 t.cs() == "cleardoublepage") {
3365 context.check_layout(os);
3366 begin_inset(os, "Newpage ");
3369 skip_spaces_braces(p);
3372 else if (t.cs() == "DeclareRobustCommand" ||
3373 t.cs() == "DeclareRobustCommandx" ||
3374 t.cs() == "newcommand" ||
3375 t.cs() == "newcommandx" ||
3376 t.cs() == "providecommand" ||
3377 t.cs() == "providecommandx" ||
3378 t.cs() == "renewcommand" ||
3379 t.cs() == "renewcommandx") {
3380 // DeclareRobustCommand, DeclareRobustCommandx,
3381 // providecommand and providecommandx could be handled
3382 // by parse_command(), but we need to call
3383 // add_known_command() here.
3384 string name = t.asInput();
3385 if (p.next_token().asInput() == "*") {
3386 // Starred form. Eat '*'
3390 string const command = p.verbatim_item();
3391 string const opt1 = p.getFullOpt();
3392 string const opt2 = p.getFullOpt();
3393 add_known_command(command, opt1, !opt2.empty());
3394 string const ert = name + '{' + command + '}' +
3396 '{' + p.verbatim_item() + '}';
3398 if (t.cs() == "DeclareRobustCommand" ||
3399 t.cs() == "DeclareRobustCommandx" ||
3400 t.cs() == "providecommand" ||
3401 t.cs() == "providecommandx" ||
3402 name[name.length()-1] == '*')
3403 handle_ert(os, ert, context);
3405 context.check_layout(os);
3406 begin_inset(os, "FormulaMacro");
3412 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3413 // let could be handled by parse_command(),
3414 // but we need to call add_known_command() here.
3415 string ert = t.asInput();
3418 if (p.next_token().cat() == catBegin) {
3419 name = p.verbatim_item();
3420 ert += '{' + name + '}';
3422 name = p.verbatim_item();
3427 if (p.next_token().cat() == catBegin) {
3428 command = p.verbatim_item();
3429 ert += '{' + command + '}';
3431 command = p.verbatim_item();
3434 // If command is known, make name known too, to parse
3435 // its arguments correctly. For this reason we also
3436 // have commands in syntax.default that are hardcoded.
3437 CommandMap::iterator it = known_commands.find(command);
3438 if (it != known_commands.end())
3439 known_commands[t.asInput()] = it->second;
3440 handle_ert(os, ert, context);
3443 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3444 bool starred = false;
3445 if (p.next_token().asInput() == "*") {
3449 string name = t.asInput();
3450 string const length = p.verbatim_item();
3453 bool valid = splitLatexLength(length, valstring, unit);
3454 bool known_hspace = false;
3455 bool known_vspace = false;
3456 bool known_unit = false;
3459 istringstream iss(valstring);
3462 if (t.cs()[0] == 'h') {
3463 if (unit == "\\fill") {
3468 known_hspace = true;
3471 if (unit == "\\smallskipamount") {
3473 known_vspace = true;
3474 } else if (unit == "\\medskipamount") {
3476 known_vspace = true;
3477 } else if (unit == "\\bigskipamount") {
3479 known_vspace = true;
3480 } else if (unit == "\\fill") {
3482 known_vspace = true;
3486 if (!known_hspace && !known_vspace) {
3487 switch (unitFromString(unit)) {
3508 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3509 // Literal horizontal length or known variable
3510 context.check_layout(os);
3511 begin_inset(os, "space ");
3519 if (known_unit && !known_hspace)
3521 << translate_len(length);
3523 } else if (known_unit || known_vspace) {
3524 // Literal vertical length or known variable
3525 context.check_layout(os);
3526 begin_inset(os, "VSpace ");
3534 // LyX can't handle other length variables in Inset VSpace/space
3539 handle_ert(os, name + '{' + unit + '}', context);
3540 else if (value == -1.0)
3541 handle_ert(os, name + "{-" + unit + '}', context);
3543 handle_ert(os, name + '{' + valstring + unit + '}', context);
3545 handle_ert(os, name + '{' + length + '}', context);
3549 // The single '=' is meant here.
3550 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3552 context.check_layout(os);
3553 begin_inset(os, "Flex ");
3554 os << to_utf8(newinsetlayout->name()) << '\n'
3555 << "status collapsed\n";
3556 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3561 // try to see whether the string is in unicodesymbols
3562 // Only use text mode commands, since we are in text mode here,
3563 // and math commands may be invalid (bug 6797)
3565 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
3566 rem, Encodings::TEXT_CMD);
3569 cerr << "When parsing " << t.cs()
3570 << ", result is " << to_utf8(s)
3571 << "+" << to_utf8(rem) << endl;
3572 context.check_layout(os);
3574 skip_spaces_braces(p);
3576 //cerr << "#: " << t << " mode: " << mode << endl;
3577 // heuristic: read up to next non-nested space
3579 string s = t.asInput();
3580 string z = p.verbatim_item();
3581 while (p.good() && z != " " && z.size()) {
3582 //cerr << "read: " << z << endl;
3584 z = p.verbatim_item();
3586 cerr << "found ERT: " << s << endl;
3587 handle_ert(os, s + ' ', context);
3590 string name = t.asInput();
3591 if (p.next_token().asInput() == "*") {
3592 // Starred commands like \vspace*{}
3593 p.get_token(); // Eat '*'
3596 if (!parse_command(name, p, os, outer, context))
3597 handle_ert(os, name, context);
3601 if (flags & FLAG_LEAVE) {
3602 flags &= ~FLAG_LEAVE;