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 };
114 * The starred forms are also known except for "citefullauthor",
115 * "citeyear" and "citeyearpar".
117 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
118 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
119 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
123 * No starred form other than "cite*" known.
125 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
126 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
127 // jurabib commands not (yet) supported by LyX:
129 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
130 // "footciteauthor", "footciteyear", "footciteyearpar",
131 "citefield", "citetitle", 0 };
133 /// LaTeX names for quotes
134 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
135 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
136 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
137 "guilsinglleft", "frq", "guilsinglright", 0};
139 /// the same as known_quotes with .lyx names
140 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
141 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
142 "gld", "grd", "gls", "ers", "fls",
143 "fls", "frs", "frs", 0};
145 /// LaTeX names for font sizes
146 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
147 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
149 /// the same as known_sizes with .lyx names
150 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
151 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
153 /// LaTeX 2.09 names for font families
154 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
156 /// LaTeX names for font families
157 char const * const known_font_families[] = { "rmfamily", "sffamily",
160 /// the same as known_old_font_families and known_font_families with .lyx names
161 char const * const known_coded_font_families[] = { "roman", "sans",
164 /// LaTeX 2.09 names for font series
165 char const * const known_old_font_series[] = { "bf", 0};
167 /// LaTeX names for font series
168 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
170 /// the same as known_old_font_series and known_font_series with .lyx names
171 char const * const known_coded_font_series[] = { "bold", "medium", 0};
173 /// LaTeX 2.09 names for font shapes
174 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
176 /// LaTeX names for font shapes
177 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
180 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
181 char const * const known_coded_font_shapes[] = { "italic", "slanted",
182 "smallcaps", "up", 0};
185 * Graphics file extensions known by the dvips driver of the graphics package.
186 * These extensions are used to complete the filename of an included
187 * graphics file if it does not contain an extension.
188 * The order must be the same that latex uses to find a file, because we
189 * will use the first extension that matches.
190 * This is only an approximation for the common cases. If we would want to
191 * do it right in all cases, we would need to know which graphics driver is
192 * used and know the extensions of every driver of the graphics package.
194 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
195 "ps.gz", "eps.Z", "ps.Z", 0};
198 * Graphics file extensions known by the pdftex driver of the graphics package.
199 * \sa known_dvips_graphics_formats
201 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
205 * Known file extensions for TeX files as used by \\include.
207 char const * const known_tex_extensions[] = {"tex", 0};
209 /// spaces known by InsetSpace
210 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
211 "qquad", "enspace", "enskip", "negthinspace", "hfill", "dotfill", "hrulefill",
212 "leftarrowfill", "rightarrowfill", "upbracefill", "downbracefill", 0};
214 /// the same as known_spaces with .lyx names
215 char const * const known_coded_spaces[] = { "space{}", "space{}",
216 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
217 "negthinspace{}", "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}",
218 "rightarrowfill{}", "upbracefill{}", "downbracefill{}", 0};
220 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
221 /// them in ERT. "LaTeXe" must come before "LaTeX"!
222 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
223 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
224 int const known_phrase_lengths[] = {3, 5, 7, 0};
227 /// splits "x=z, y=b" into a map and an ordered keyword vector
228 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
233 keys.resize(v.size());
234 for (size_t i = 0; i < v.size(); ++i) {
235 size_t const pos = v[i].find('=');
236 string const index = trim(v[i].substr(0, pos));
237 string const value = trim(v[i].substr(pos + 1, string::npos));
245 * Split a LaTeX length into value and unit.
246 * The latter can be a real unit like "pt", or a latex length variable
247 * like "\textwidth". The unit may contain additional stuff like glue
248 * lengths, but we don't care, because such lengths are ERT anyway.
249 * \returns true if \p value and \p unit are valid.
251 bool splitLatexLength(string const & len, string & value, string & unit)
255 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
256 //'4,5' is a valid LaTeX length number. Change it to '4.5'
257 string const length = subst(len, ',', '.');
258 if (i == string::npos)
261 if (len[0] == '\\') {
262 // We had something like \textwidth without a factor
268 value = trim(string(length, 0, i));
272 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
273 if (contains(len, '\\'))
274 unit = trim(string(len, i));
276 unit = ascii_lowercase(trim(string(len, i)));
281 /// A simple function to translate a latex length to something LyX can
282 /// understand. Not perfect, but rather best-effort.
283 bool translate_len(string const & length, string & valstring, string & unit)
285 if (!splitLatexLength(length, valstring, unit))
287 // LyX uses percent values
289 istringstream iss(valstring);
294 string const percentval = oss.str();
296 if (unit.empty() || unit[0] != '\\')
298 string::size_type const i = unit.find(' ');
299 string const endlen = (i == string::npos) ? string() : string(unit, i);
300 if (unit == "\\textwidth") {
301 valstring = percentval;
302 unit = "text%" + endlen;
303 } else if (unit == "\\columnwidth") {
304 valstring = percentval;
305 unit = "col%" + endlen;
306 } else if (unit == "\\paperwidth") {
307 valstring = percentval;
308 unit = "page%" + endlen;
309 } else if (unit == "\\linewidth") {
310 valstring = percentval;
311 unit = "line%" + endlen;
312 } else if (unit == "\\paperheight") {
313 valstring = percentval;
314 unit = "pheight%" + endlen;
315 } else if (unit == "\\textheight") {
316 valstring = percentval;
317 unit = "theight%" + endlen;
325 string translate_len(string const & length)
329 if (translate_len(length, value, unit))
331 // If the input is invalid, return what we have.
339 * Translates a LaTeX length into \p value, \p unit and
340 * \p special parts suitable for a box inset.
341 * The difference from translate_len() is that a box inset knows about
342 * some special "units" that are stored in \p special.
344 void translate_box_len(string const & length, string & value, string & unit, string & special)
346 if (translate_len(length, value, unit)) {
347 if (unit == "\\height" || unit == "\\depth" ||
348 unit == "\\totalheight" || unit == "\\width") {
349 special = unit.substr(1);
350 // The unit is not used, but LyX requires a dummy setting
363 * Find a file with basename \p name in path \p path and an extension
366 string find_file(string const & name, string const & path,
367 char const * const * extensions)
369 for (char const * const * what = extensions; *what; ++what) {
370 string const trial = addExtension(name, *what);
371 if (makeAbsPath(trial, path).exists())
378 void begin_inset(ostream & os, string const & name)
380 os << "\n\\begin_inset " << name;
384 void begin_command_inset(ostream & os, string const & name,
385 string const & latexname)
387 begin_inset(os, "CommandInset ");
388 os << name << "\nLatexCommand " << latexname << '\n';
392 void end_inset(ostream & os)
394 os << "\n\\end_inset\n\n";
398 bool skip_braces(Parser & p)
400 if (p.next_token().cat() != catBegin)
403 if (p.next_token().cat() == catEnd) {
412 /// replace LaTeX commands in \p s from the unicodesymbols file with their
414 docstring convert_unicodesymbols(docstring s)
417 for (size_t i = 0; i < s.size();) {
424 docstring parsed = encodings.fromLaTeXCommand(s, rem,
425 Encodings::TEXT_CMD);
434 /// try to convert \p s to a valid InsetCommand argument
435 string convert_command_inset_arg(string s)
438 // since we don't know the input encoding we can't use from_utf8
439 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
440 // LyX cannot handle newlines in a latex command
441 return subst(s, "\n", " ");
445 void handle_backslash(ostream & os, string const & s)
447 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
449 os << "\n\\backslash\n";
456 void handle_ert(ostream & os, string const & s, Context & context)
458 // We must have a valid layout before outputting the ERT inset.
459 context.check_layout(os);
460 Context newcontext(true, context.textclass);
461 begin_inset(os, "ERT");
462 os << "\nstatus collapsed\n";
463 newcontext.check_layout(os);
464 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
466 os << "\n\\backslash\n";
467 else if (*it == '\n') {
468 newcontext.new_paragraph(os);
469 newcontext.check_layout(os);
473 newcontext.check_end_layout(os);
478 void handle_comment(ostream & os, string const & s, Context & context)
480 // TODO: Handle this better
481 Context newcontext(true, context.textclass);
482 begin_inset(os, "ERT");
483 os << "\nstatus collapsed\n";
484 newcontext.check_layout(os);
485 handle_backslash(os, s);
486 // make sure that our comment is the last thing on the line
487 newcontext.new_paragraph(os);
488 newcontext.check_layout(os);
489 newcontext.check_end_layout(os);
494 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
496 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
499 if (checkModule(name, command))
500 return findLayoutWithoutModule(textclass, name, command);
505 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
507 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
510 if (checkModule(name, command))
511 return findInsetLayoutWithoutModule(textclass, name, command);
516 void eat_whitespace(Parser &, ostream &, Context &, bool);
520 * Skips whitespace and braces.
521 * This should be called after a command has been parsed that is not put into
522 * ERT, and where LyX adds "{}" if needed.
524 void skip_spaces_braces(Parser & p, bool keepws = false)
526 /* The following four examples produce the same typeset output and
527 should be handled by this function:
535 // Unfortunately we need to skip comments, too.
536 // We can't use eat_whitespace since writing them after the {}
537 // results in different output in some cases.
538 bool const skipped_spaces = p.skip_spaces(true);
539 bool const skipped_braces = skip_braces(p);
540 if (keepws && skipped_spaces && !skipped_braces)
541 // put back the space (it is better handled by check_space)
542 p.unskip_spaces(true);
546 void output_command_layout(ostream & os, Parser & p, bool outer,
547 Context & parent_context,
548 Layout const * newlayout)
550 TeXFont const oldFont = parent_context.font;
551 // save the current font size
552 string const size = oldFont.size;
553 // reset the font size to default, because the font size switches
554 // don't affect section headings and the like
555 parent_context.font.size = Context::normalfont.size;
556 // we only need to write the font change if we have an open layout
557 if (!parent_context.atParagraphStart())
558 output_font_change(os, oldFont, parent_context.font);
559 parent_context.check_end_layout(os);
560 Context context(true, parent_context.textclass, newlayout,
561 parent_context.layout, parent_context.font);
562 if (parent_context.deeper_paragraph) {
563 // We are beginning a nested environment after a
564 // deeper paragraph inside the outer list environment.
565 // Therefore we don't need to output a "begin deeper".
566 context.need_end_deeper = true;
568 context.check_deeper(os);
569 context.check_layout(os);
570 unsigned int optargs = 0;
571 while (optargs < context.layout->optargs) {
572 eat_whitespace(p, os, context, false);
573 if (p.next_token().cat() == catEscape ||
574 p.next_token().character() != '[')
576 p.get_token(); // eat '['
577 begin_inset(os, "OptArg\n");
578 os << "status collapsed\n\n";
579 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
581 eat_whitespace(p, os, context, false);
584 unsigned int reqargs = 0;
585 while (LYX_FORMAT >= 392 && reqargs < context.layout->reqargs) {
586 eat_whitespace(p, os, context, false);
587 if (p.next_token().cat() != catBegin)
589 p.get_token(); // eat '{'
590 begin_inset(os, "OptArg\n");
591 os << "status collapsed\n\n";
592 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
594 eat_whitespace(p, os, context, false);
597 parse_text(p, os, FLAG_ITEM, outer, context);
598 context.check_end_layout(os);
599 if (parent_context.deeper_paragraph) {
600 // We must suppress the "end deeper" because we
601 // suppressed the "begin deeper" above.
602 context.need_end_deeper = false;
604 context.check_end_deeper(os);
605 // We don't need really a new paragraph, but
606 // we must make sure that the next item gets a \begin_layout.
607 parent_context.new_paragraph(os);
608 // Set the font size to the original value. No need to output it here
609 // (Context::begin_layout() will do that if needed)
610 parent_context.font.size = size;
615 * Output a space if necessary.
616 * This function gets called for every whitespace token.
618 * We have three cases here:
619 * 1. A space must be suppressed. Example: The lyxcode case below
620 * 2. A space may be suppressed. Example: Spaces before "\par"
621 * 3. A space must not be suppressed. Example: A space between two words
623 * We currently handle only 1. and 3 and from 2. only the case of
624 * spaces before newlines as a side effect.
626 * 2. could be used to suppress as many spaces as possible. This has two effects:
627 * - Reimporting LyX generated LaTeX files changes almost no whitespace
628 * - Superflous whitespace from non LyX generated LaTeX files is removed.
629 * The drawback is that the logic inside the function becomes
630 * complicated, and that is the reason why it is not implemented.
632 void check_space(Parser & p, ostream & os, Context & context)
634 Token const next = p.next_token();
635 Token const curr = p.curr_token();
636 // A space before a single newline and vice versa must be ignored
637 // LyX emits a newline before \end{lyxcode}.
638 // This newline must be ignored,
639 // otherwise LyX will add an additional protected space.
640 if (next.cat() == catSpace ||
641 next.cat() == catNewline ||
642 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
645 context.check_layout(os);
651 * Parse all arguments of \p command
653 void parse_arguments(string const & command,
654 vector<ArgumentType> const & template_arguments,
655 Parser & p, ostream & os, bool outer, Context & context)
657 string ert = command;
658 size_t no_arguments = template_arguments.size();
659 for (size_t i = 0; i < no_arguments; ++i) {
660 switch (template_arguments[i]) {
662 // This argument contains regular LaTeX
663 handle_ert(os, ert + '{', context);
664 eat_whitespace(p, os, context, false);
665 parse_text(p, os, FLAG_ITEM, outer, context);
669 // This argument consists only of a single item.
670 // The presence of '{' or not must be preserved.
672 if (p.next_token().cat() == catBegin)
673 ert += '{' + p.verbatim_item() + '}';
675 ert += p.verbatim_item();
678 // This argument may contain special characters
679 ert += '{' + p.verbatim_item() + '}';
682 // true because we must not eat whitespace
683 // if an optional arg follows me must not strip the
684 // brackets from this one
685 if (i < no_arguments - 1 &&
686 template_arguments[i+1] == optional)
687 ert += p.getFullOpt(true);
689 ert += p.getOpt(true);
693 handle_ert(os, ert, context);
698 * Check whether \p command is a known command. If yes,
699 * handle the command with all arguments.
700 * \return true if the command was parsed, false otherwise.
702 bool parse_command(string const & command, Parser & p, ostream & os,
703 bool outer, Context & context)
705 if (known_commands.find(command) != known_commands.end()) {
706 parse_arguments(command, known_commands[command], p, os,
714 /// Parses a minipage or parbox
715 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
716 unsigned inner_flags, bool outer, Context & parent_context,
717 string const & outer_type, string const & special,
718 string const & inner_type)
722 string hor_pos = "c";
723 // We need to set the height to the LaTeX default of 1\\totalheight
724 // for the case when no height argument is given
725 string height_value = "1";
726 string height_unit = "in";
727 string height_special = "totalheight";
729 if (!inner_type.empty() && p.hasOpt()) {
730 position = p.getArg('[', ']');
731 if (position != "t" && position != "c" && position != "b") {
732 cerr << "invalid position " << position << " for "
733 << inner_type << endl;
737 latex_height = p.getArg('[', ']');
738 translate_box_len(latex_height, height_value, height_unit, height_special);
741 inner_pos = p.getArg('[', ']');
742 if (inner_pos != "c" && inner_pos != "t" &&
743 inner_pos != "b" && inner_pos != "s") {
744 cerr << "invalid inner_pos "
745 << inner_pos << " for "
746 << inner_type << endl;
747 inner_pos = position;
755 if (inner_type.empty()) {
757 latex_width = "\\columnwidth";
760 latex_width = p2.getArg('[', ']');
761 string const opt = p2.getArg('[', ']');
764 if (hor_pos != "l" && hor_pos != "c" &&
766 cerr << "invalid hor_pos " << hor_pos
767 << " for " << outer_type << endl;
773 latex_width = p.verbatim_item();
774 translate_len(latex_width, width_value, width_unit);
775 // LyX can't handle length variables
776 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
777 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
778 // Look whether there is some content after the end of the
779 // inner box, but before the end of the outer box.
780 // If yes, we need to output ERT.
782 if (inner_flags & FLAG_END)
783 p.verbatimEnvironment(inner_type);
787 if ((outer_type == "framed" && p.next_token().asInput() != "\\end") ||
788 (outer_type != "framed" && p.next_token().cat() != catEnd)) {
789 // something is between the end of the inner box and
790 // the end of the outer box, so we need to use ERT.
797 if (!outer_type.empty()) {
798 if (outer_flags & FLAG_END)
799 ss << "\\begin{" << outer_type << '}';
801 ss << '\\' << outer_type << '{';
802 if (!special.empty())
806 if (!inner_type.empty()) {
807 if (inner_flags & FLAG_END)
808 ss << "\\begin{" << inner_type << '}';
810 ss << '\\' << inner_type;
811 if (!position.empty())
812 ss << '[' << position << ']';
813 if (!latex_height.empty())
814 ss << '[' << latex_height << ']';
815 if (!inner_pos.empty())
816 ss << '[' << inner_pos << ']';
817 ss << '{' << latex_width << '}';
818 if (!(inner_flags & FLAG_END))
821 handle_ert(os, ss.str(), parent_context);
822 if (!inner_type.empty()) {
823 parse_text(p, os, inner_flags, outer, parent_context);
824 if (inner_flags & FLAG_END)
825 handle_ert(os, "\\end{" + inner_type + '}',
828 handle_ert(os, "}", parent_context);
830 if (!outer_type.empty()) {
831 parse_text(p, os, outer_flags, outer, parent_context);
832 if (outer_flags & FLAG_END)
833 handle_ert(os, "\\end{" + outer_type + '}',
836 handle_ert(os, "}", parent_context);
839 // LyX does not like empty positions, so we have
840 // to set them to the LaTeX default values here.
841 if (position.empty())
843 if (inner_pos.empty())
844 inner_pos = position;
845 parent_context.check_layout(os);
846 begin_inset(os, "Box ");
847 if (outer_type == "framed")
849 else if (outer_type == "framebox")
851 else if (outer_type == "shadowbox")
853 else if (outer_type == "shaded")
855 else if (outer_type == "doublebox")
857 else if (outer_type.empty())
860 os << outer_type << '\n';
861 os << "position \"" << position << "\"\n";
862 os << "hor_pos \"" << hor_pos << "\"\n";
863 os << "has_inner_box " << !inner_type.empty() << "\n";
864 os << "inner_pos \"" << inner_pos << "\"\n";
865 os << "use_parbox " << (inner_type == "parbox") << '\n';
866 os << "width \"" << width_value << width_unit << "\"\n";
867 os << "special \"none\"\n";
868 os << "height \"" << height_value << height_unit << "\"\n";
869 os << "height_special \"" << height_special << "\"\n";
870 os << "status open\n\n";
871 Context context(true, parent_context.textclass);
872 context.font = parent_context.font;
874 // If we have no inner box the contens will be read with the outer box
875 if (!inner_type.empty())
876 parse_text(p, os, inner_flags, outer, context);
878 // Ensure that the end of the outer box is parsed correctly:
879 // The opening brace has been eaten by parse_outer_box()
880 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
881 outer_flags &= ~FLAG_ITEM;
882 outer_flags |= FLAG_BRACE_LAST;
885 // Find end of outer box, output contents if inner_type is
886 // empty and output possible comments
887 if (!outer_type.empty()) {
888 // This does not output anything but comments if
889 // inner_type is not empty (see use_ert)
890 parse_text(p, os, outer_flags, outer, context);
893 context.check_end_layout(os);
895 #ifdef PRESERVE_LAYOUT
896 // LyX puts a % after the end of the minipage
897 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
899 //handle_comment(os, "%dummy", parent_context);
902 parent_context.new_paragraph(os);
904 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
905 //handle_comment(os, "%dummy", parent_context);
908 // We add a protected space if something real follows
909 if (p.good() && p.next_token().cat() != catComment) {
910 begin_inset(os, "space ~\n");
919 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
920 Context & parent_context, string const & outer_type,
921 string const & special)
923 eat_whitespace(p, os, parent_context, false);
924 if (flags & FLAG_ITEM) {
926 if (p.next_token().cat() == catBegin)
929 cerr << "Warning: Ignoring missing '{' after \\"
930 << outer_type << '.' << endl;
931 eat_whitespace(p, os, parent_context, false);
934 unsigned int inner_flags = 0;
935 if (outer_type == "shaded") {
936 // These boxes never have an inner box
938 } else if (p.next_token().asInput() == "\\parbox") {
939 inner = p.get_token().cs();
940 inner_flags = FLAG_ITEM;
941 } else if (p.next_token().asInput() == "\\begin") {
942 // Is this a minipage?
945 inner = p.getArg('{', '}');
947 if (inner == "minipage") {
950 eat_whitespace(p, os, parent_context, false);
951 inner_flags = FLAG_END;
955 if (inner_flags == FLAG_END) {
956 active_environments.push_back(inner);
957 parse_box(p, os, flags, FLAG_END, outer, parent_context,
958 outer_type, special, inner);
959 active_environments.pop_back();
961 parse_box(p, os, flags, inner_flags, outer, parent_context,
962 outer_type, special, inner);
967 void parse_listings(Parser & p, ostream & os, Context & parent_context)
969 parent_context.check_layout(os);
970 begin_inset(os, "listings\n");
971 os << "inline false\n"
972 << "status collapsed\n";
973 Context context(true, parent_context.textclass);
974 context.layout = &parent_context.textclass.plainLayout();
975 context.check_layout(os);
976 string const s = p.verbatimEnvironment("lstlisting");
977 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
979 os << "\n\\backslash\n";
980 else if (*it == '\n') {
981 // avoid adding an empty paragraph at the end
983 context.new_paragraph(os);
984 context.check_layout(os);
989 context.check_end_layout(os);
994 /// parse an unknown environment
995 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
996 unsigned flags, bool outer,
997 Context & parent_context)
999 if (name == "tabbing")
1000 // We need to remember that we have to handle '\=' specially
1001 flags |= FLAG_TABBING;
1003 // We need to translate font changes and paragraphs inside the
1004 // environment to ERT if we have a non standard font.
1005 // Otherwise things like
1006 // \large\begin{foo}\huge bar\end{foo}
1008 bool const specialfont =
1009 (parent_context.font != parent_context.normalfont);
1010 bool const new_layout_allowed = parent_context.new_layout_allowed;
1012 parent_context.new_layout_allowed = false;
1013 handle_ert(os, "\\begin{" + name + "}", parent_context);
1014 parse_text_snippet(p, os, flags, outer, parent_context);
1015 handle_ert(os, "\\end{" + name + "}", parent_context);
1017 parent_context.new_layout_allowed = new_layout_allowed;
1021 void parse_environment(Parser & p, ostream & os, bool outer,
1022 string & last_env, Context & parent_context)
1024 Layout const * newlayout;
1025 InsetLayout const * newinsetlayout = 0;
1026 string const name = p.getArg('{', '}');
1027 const bool is_starred = suffixIs(name, '*');
1028 string const unstarred_name = rtrim(name, "*");
1029 active_environments.push_back(name);
1031 if (is_math_env(name)) {
1032 parent_context.check_layout(os);
1033 begin_inset(os, "Formula ");
1034 os << "\\begin{" << name << "}";
1035 parse_math(p, os, FLAG_END, MATH_MODE);
1036 os << "\\end{" << name << "}";
1040 else if (name == "tabular" || name == "longtable") {
1041 eat_whitespace(p, os, parent_context, false);
1042 parent_context.check_layout(os);
1043 begin_inset(os, "Tabular ");
1044 handle_tabular(p, os, name == "longtable", parent_context);
1049 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1050 eat_whitespace(p, os, parent_context, false);
1051 parent_context.check_layout(os);
1052 begin_inset(os, "Float " + unstarred_name + "\n");
1054 os << "placement " << p.getArg('[', ']') << '\n';
1055 os << "wide " << convert<string>(is_starred)
1056 << "\nsideways false"
1057 << "\nstatus open\n\n";
1058 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1060 // We don't need really a new paragraph, but
1061 // we must make sure that the next item gets a \begin_layout.
1062 parent_context.new_paragraph(os);
1066 else if (name == "minipage") {
1067 eat_whitespace(p, os, parent_context, false);
1068 parse_box(p, os, 0, FLAG_END, outer, parent_context, "", "", name);
1072 else if (name == "comment") {
1073 eat_whitespace(p, os, parent_context, false);
1074 parent_context.check_layout(os);
1075 begin_inset(os, "Note Comment\n");
1076 os << "status open\n";
1077 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1080 skip_braces(p); // eat {} that might by set by LyX behind comments
1083 else if (name == "lyxgreyedout") {
1084 eat_whitespace(p, os, parent_context, false);
1085 parent_context.check_layout(os);
1086 begin_inset(os, "Note Greyedout\n");
1087 os << "status open\n";
1088 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1093 else if (name == "framed" || name == "shaded") {
1094 eat_whitespace(p, os, parent_context, false);
1095 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1099 else if (name == "lstlisting") {
1100 eat_whitespace(p, os, parent_context, false);
1101 // FIXME handle listings with parameters
1103 parse_unknown_environment(p, name, os, FLAG_END,
1104 outer, parent_context);
1106 parse_listings(p, os, parent_context);
1110 else if (!parent_context.new_layout_allowed)
1111 parse_unknown_environment(p, name, os, FLAG_END, outer,
1114 // Alignment and spacing settings
1115 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1116 // therefore are totally broken!
1117 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1118 // they are commands not environments. They are furthermore switches that
1119 // can be ended by another switches, but also by commands like \footnote or
1120 // \parbox. So the only safe way is to leave them untouched.
1121 else if (name == "center" || name == "centering" ||
1122 name == "flushleft" || name == "flushright" ||
1123 name == "singlespace" || name == "onehalfspace" ||
1124 name == "doublespace" || name == "spacing") {
1125 eat_whitespace(p, os, parent_context, false);
1126 // We must begin a new paragraph if not already done
1127 if (! parent_context.atParagraphStart()) {
1128 parent_context.check_end_layout(os);
1129 parent_context.new_paragraph(os);
1131 if (name == "flushleft")
1132 parent_context.add_extra_stuff("\\align left\n");
1133 else if (name == "flushright")
1134 parent_context.add_extra_stuff("\\align right\n");
1135 else if (name == "center" || name == "centering")
1136 parent_context.add_extra_stuff("\\align center\n");
1137 else if (name == "singlespace")
1138 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1139 else if (name == "onehalfspace")
1140 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1141 else if (name == "doublespace")
1142 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1143 else if (name == "spacing")
1144 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1145 parse_text(p, os, FLAG_END, outer, parent_context);
1146 // Just in case the environment is empty
1147 parent_context.extra_stuff.erase();
1148 // We must begin a new paragraph to reset the alignment
1149 parent_context.new_paragraph(os);
1153 // The single '=' is meant here.
1154 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1155 eat_whitespace(p, os, parent_context, false);
1156 Context context(true, parent_context.textclass, newlayout,
1157 parent_context.layout, parent_context.font);
1158 if (parent_context.deeper_paragraph) {
1159 // We are beginning a nested environment after a
1160 // deeper paragraph inside the outer list environment.
1161 // Therefore we don't need to output a "begin deeper".
1162 context.need_end_deeper = true;
1164 parent_context.check_end_layout(os);
1165 if (last_env == name) {
1166 // we need to output a separator since LyX would export
1167 // the two environments as one otherwise (bug 5716)
1168 docstring const sep = from_ascii("--Separator--");
1169 TeX2LyXDocClass const & textclass(parent_context.textclass);
1170 if (textclass.hasLayout(sep)) {
1171 Context newcontext(parent_context);
1172 newcontext.layout = &(textclass[sep]);
1173 newcontext.check_layout(os);
1174 newcontext.check_end_layout(os);
1176 parent_context.check_layout(os);
1177 begin_inset(os, "Note Note\n");
1178 os << "status closed\n";
1179 Context newcontext(true, textclass,
1180 &(textclass.defaultLayout()));
1181 newcontext.check_layout(os);
1182 newcontext.check_end_layout(os);
1184 parent_context.check_end_layout(os);
1187 switch (context.layout->latextype) {
1188 case LATEX_LIST_ENVIRONMENT:
1189 context.add_par_extra_stuff("\\labelwidthstring "
1190 + p.verbatim_item() + '\n');
1193 case LATEX_BIB_ENVIRONMENT:
1194 p.verbatim_item(); // swallow next arg
1200 context.check_deeper(os);
1201 parse_text(p, os, FLAG_END, outer, context);
1202 context.check_end_layout(os);
1203 if (parent_context.deeper_paragraph) {
1204 // We must suppress the "end deeper" because we
1205 // suppressed the "begin deeper" above.
1206 context.need_end_deeper = false;
1208 context.check_end_deeper(os);
1209 parent_context.new_paragraph(os);
1213 // The single '=' is meant here.
1214 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1215 eat_whitespace(p, os, parent_context, false);
1216 parent_context.check_layout(os);
1217 begin_inset(os, "Flex ");
1218 os << to_utf8(newinsetlayout->name()) << '\n'
1219 << "status collapsed\n";
1220 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1224 else if (name == "appendix") {
1225 // This is no good latex style, but it works and is used in some documents...
1226 eat_whitespace(p, os, parent_context, false);
1227 parent_context.check_end_layout(os);
1228 Context context(true, parent_context.textclass, parent_context.layout,
1229 parent_context.layout, parent_context.font);
1230 context.check_layout(os);
1231 os << "\\start_of_appendix\n";
1232 parse_text(p, os, FLAG_END, outer, context);
1233 context.check_end_layout(os);
1237 else if (known_environments.find(name) != known_environments.end()) {
1238 vector<ArgumentType> arguments = known_environments[name];
1239 // The last "argument" denotes wether we may translate the
1240 // environment contents to LyX
1241 // The default required if no argument is given makes us
1242 // compatible with the reLyXre environment.
1243 ArgumentType contents = arguments.empty() ?
1246 if (!arguments.empty())
1247 arguments.pop_back();
1248 // See comment in parse_unknown_environment()
1249 bool const specialfont =
1250 (parent_context.font != parent_context.normalfont);
1251 bool const new_layout_allowed =
1252 parent_context.new_layout_allowed;
1254 parent_context.new_layout_allowed = false;
1255 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1256 outer, parent_context);
1257 if (contents == verbatim)
1258 handle_ert(os, p.verbatimEnvironment(name),
1261 parse_text_snippet(p, os, FLAG_END, outer,
1263 handle_ert(os, "\\end{" + name + "}", parent_context);
1265 parent_context.new_layout_allowed = new_layout_allowed;
1269 parse_unknown_environment(p, name, os, FLAG_END, outer,
1273 active_environments.pop_back();
1277 /// parses a comment and outputs it to \p os.
1278 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1280 LASSERT(t.cat() == catComment, return);
1281 if (!t.cs().empty()) {
1282 context.check_layout(os);
1283 handle_comment(os, '%' + t.cs(), context);
1284 if (p.next_token().cat() == catNewline) {
1285 // A newline after a comment line starts a new
1287 if (context.new_layout_allowed) {
1288 if(!context.atParagraphStart())
1289 // Only start a new paragraph if not already
1290 // done (we might get called recursively)
1291 context.new_paragraph(os);
1293 handle_ert(os, "\n", context);
1294 eat_whitespace(p, os, context, true);
1297 // "%\n" combination
1304 * Reads spaces and comments until the first non-space, non-comment token.
1305 * New paragraphs (double newlines or \\par) are handled like simple spaces
1306 * if \p eatParagraph is true.
1307 * Spaces are skipped, but comments are written to \p os.
1309 void eat_whitespace(Parser & p, ostream & os, Context & context,
1313 Token const & t = p.get_token();
1314 if (t.cat() == catComment)
1315 parse_comment(p, os, t, context);
1316 else if ((! eatParagraph && p.isParagraph()) ||
1317 (t.cat() != catSpace && t.cat() != catNewline)) {
1326 * Set a font attribute, parse text and reset the font attribute.
1327 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1328 * \param currentvalue Current value of the attribute. Is set to the new
1329 * value during parsing.
1330 * \param newvalue New value of the attribute
1332 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1333 Context & context, string const & attribute,
1334 string & currentvalue, string const & newvalue)
1336 context.check_layout(os);
1337 string const oldvalue = currentvalue;
1338 currentvalue = newvalue;
1339 os << '\n' << attribute << ' ' << newvalue << "\n";
1340 parse_text_snippet(p, os, flags, outer, context);
1341 context.check_layout(os);
1342 os << '\n' << attribute << ' ' << oldvalue << "\n";
1343 currentvalue = oldvalue;
1347 /// get the arguments of a natbib or jurabib citation command
1348 void get_cite_arguments(Parser & p, bool natbibOrder,
1349 string & before, string & after)
1351 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1353 // text before the citation
1355 // text after the citation
1356 after = p.getFullOpt();
1358 if (!after.empty()) {
1359 before = p.getFullOpt();
1360 if (natbibOrder && !before.empty())
1361 swap(before, after);
1366 /// Convert filenames with TeX macros and/or quotes to something LyX
1368 string const normalize_filename(string const & name)
1370 Parser p(trim(name, "\""));
1373 Token const & t = p.get_token();
1374 if (t.cat() != catEscape)
1376 else if (t.cs() == "lyxdot") {
1377 // This is used by LyX for simple dots in relative
1381 } else if (t.cs() == "space") {
1391 /// Convert \p name from TeX convention (relative to master file) to LyX
1392 /// convention (relative to .lyx file) if it is relative
1393 void fix_relative_filename(string & name)
1395 if (FileName::isAbsolute(name))
1398 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1399 from_utf8(getParentFilePath())));
1403 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1404 void parse_noweb(Parser & p, ostream & os, Context & context)
1406 // assemble the rest of the keyword
1410 Token const & t = p.get_token();
1411 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1414 scrap = (p.good() && p.next_token().asInput() == "=");
1416 name += p.get_token().asInput();
1419 name += t.asInput();
1422 if (!scrap || !context.new_layout_allowed ||
1423 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1424 cerr << "Warning: Could not interpret '" << name
1425 << "'. Ignoring it." << endl;
1429 // We use new_paragraph instead of check_end_layout because the stuff
1430 // following the noweb chunk needs to start with a \begin_layout.
1431 // This may create a new paragraph even if there was none in the
1432 // noweb file, but the alternative is an invalid LyX file. Since
1433 // noweb code chunks are implemented with a layout style in LyX they
1434 // always must be in an own paragraph.
1435 context.new_paragraph(os);
1436 Context newcontext(true, context.textclass,
1437 &context.textclass[from_ascii("Scrap")]);
1438 newcontext.check_layout(os);
1441 Token const & t = p.get_token();
1442 // We abuse the parser a bit, because this is no TeX syntax
1444 if (t.cat() == catEscape)
1445 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1448 begin_inset(oss, "Newline newline");
1450 os << subst(t.asInput(), "\n", oss.str());
1452 // The scrap chunk is ended by an @ at the beginning of a line.
1453 // After the @ the line may contain a comment and/or
1454 // whitespace, but nothing else.
1455 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1456 (p.next_token().cat() == catSpace ||
1457 p.next_token().cat() == catNewline ||
1458 p.next_token().cat() == catComment)) {
1459 while (p.good() && p.next_token().cat() == catSpace)
1460 os << p.get_token().asInput();
1461 if (p.next_token().cat() == catComment)
1462 // The comment includes a final '\n'
1463 os << p.get_token().asInput();
1465 if (p.next_token().cat() == catNewline)
1472 newcontext.check_end_layout(os);
1476 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1477 bool is_macro(Parser & p)
1479 Token first = p.curr_token();
1480 if (first.cat() != catEscape || !p.good())
1482 if (first.cs() == "def")
1484 if (first.cs() != "global" && first.cs() != "long")
1486 Token second = p.get_token();
1488 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1489 second.cat() == catNewline || second.cat() == catComment)) {
1490 second = p.get_token();
1493 bool secondvalid = second.cat() == catEscape;
1495 bool thirdvalid = false;
1496 if (p.good() && first.cs() == "global" && secondvalid &&
1497 second.cs() == "long") {
1498 third = p.get_token();
1500 while (p.good() && !p.isParagraph() &&
1501 (third.cat() == catSpace ||
1502 third.cat() == catNewline ||
1503 third.cat() == catComment)) {
1504 third = p.get_token();
1507 thirdvalid = third.cat() == catEscape;
1509 for (int i = 0; i < pos; ++i)
1514 return (first.cs() == "global" || first.cs() == "long") &&
1515 second.cs() == "def";
1516 return first.cs() == "global" && second.cs() == "long" &&
1517 third.cs() == "def";
1521 /// Parse a macro definition (assumes that is_macro() returned true)
1522 void parse_macro(Parser & p, ostream & os, Context & context)
1524 context.check_layout(os);
1525 Token first = p.curr_token();
1528 string command = first.asInput();
1529 if (first.cs() != "def") {
1531 eat_whitespace(p, os, context, false);
1532 second = p.curr_token();
1533 command += second.asInput();
1534 if (second.cs() != "def") {
1536 eat_whitespace(p, os, context, false);
1537 third = p.curr_token();
1538 command += third.asInput();
1541 eat_whitespace(p, os, context, false);
1542 string const name = p.get_token().cs();
1543 eat_whitespace(p, os, context, false);
1549 while (p.next_token().cat() != catBegin) {
1550 if (p.next_token().cat() == catParameter) {
1555 // followed by number?
1556 if (p.next_token().cat() == catOther) {
1557 char c = p.getChar();
1559 // number = current arity + 1?
1560 if (c == arity + '0' + 1)
1565 paramtext += p.get_token().cs();
1567 paramtext += p.get_token().cs();
1572 // only output simple (i.e. compatible) macro as FormulaMacros
1573 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1575 context.check_layout(os);
1576 begin_inset(os, "FormulaMacro");
1577 os << "\n\\def" << ert;
1580 handle_ert(os, command + ert, context);
1583 } // anonymous namespace
1586 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1589 Layout const * newlayout = 0;
1590 InsetLayout const * newinsetlayout = 0;
1591 // Store the latest bibliographystyle and nocite{*} option
1592 // (needed for bibtex inset)
1594 string bibliographystyle;
1595 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1596 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1599 Token const & t = p.get_token();
1602 debugToken(cerr, t, flags);
1605 if (flags & FLAG_ITEM) {
1606 if (t.cat() == catSpace)
1609 flags &= ~FLAG_ITEM;
1610 if (t.cat() == catBegin) {
1611 // skip the brace and collect everything to the next matching
1613 flags |= FLAG_BRACE_LAST;
1617 // handle only this single token, leave the loop if done
1618 flags |= FLAG_LEAVE;
1621 if (t.cat() != catEscape && t.character() == ']' &&
1622 (flags & FLAG_BRACK_LAST))
1624 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1627 // If there is anything between \end{env} and \begin{env} we
1628 // don't need to output a separator.
1629 if (t.cat() != catSpace && t.cat() != catNewline &&
1630 t.asInput() != "\\begin")
1636 if (t.cat() == catMath) {
1637 // we are inside some text mode thingy, so opening new math is allowed
1638 context.check_layout(os);
1639 begin_inset(os, "Formula ");
1640 Token const & n = p.get_token();
1641 if (n.cat() == catMath && outer) {
1642 // TeX's $$...$$ syntax for displayed math
1644 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1646 p.get_token(); // skip the second '$' token
1648 // simple $...$ stuff
1651 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1657 else if (t.cat() == catSuper || t.cat() == catSub)
1658 cerr << "catcode " << t << " illegal in text mode\n";
1660 // Basic support for english quotes. This should be
1661 // extended to other quotes, but is not so easy (a
1662 // left english quote is the same as a right german
1664 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1665 context.check_layout(os);
1666 begin_inset(os, "Quotes ");
1672 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1673 context.check_layout(os);
1674 begin_inset(os, "Quotes ");
1681 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1682 context.check_layout(os);
1683 begin_inset(os, "Quotes ");
1690 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1691 context.check_layout(os);
1692 begin_inset(os, "Quotes ");
1699 else if (t.asInput() == "<"
1700 && p.next_token().asInput() == "<" && noweb_mode) {
1702 parse_noweb(p, os, context);
1705 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1706 check_space(p, os, context);
1708 else if (t.character() == '[' && noweb_mode &&
1709 p.next_token().character() == '[') {
1710 // These can contain underscores
1712 string const s = p.getFullOpt() + ']';
1713 if (p.next_token().character() == ']')
1716 cerr << "Warning: Inserting missing ']' in '"
1717 << s << "'." << endl;
1718 handle_ert(os, s, context);
1721 else if (t.cat() == catLetter) {
1722 context.check_layout(os);
1723 // Workaround for bug 4752.
1724 // FIXME: This whole code block needs to be removed
1725 // when the bug is fixed and tex2lyx produces
1726 // the updated file format.
1727 // The replacement algorithm in LyX is so stupid that
1728 // it even translates a phrase if it is part of a word.
1729 bool handled = false;
1730 for (int const * l = known_phrase_lengths; *l; ++l) {
1731 string phrase = t.cs();
1732 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
1733 phrase += p.get_token().cs();
1734 if (is_known(phrase, known_coded_phrases)) {
1735 handle_ert(os, phrase, context);
1739 for (size_t i = 1; i < phrase.length(); ++i)
1747 else if (t.cat() == catOther ||
1748 t.cat() == catAlign ||
1749 t.cat() == catParameter) {
1750 // This translates "&" to "\\&" which may be wrong...
1751 context.check_layout(os);
1755 else if (p.isParagraph()) {
1756 if (context.new_layout_allowed)
1757 context.new_paragraph(os);
1759 handle_ert(os, "\\par ", context);
1760 eat_whitespace(p, os, context, true);
1763 else if (t.cat() == catActive) {
1764 context.check_layout(os);
1765 if (t.character() == '~') {
1766 if (context.layout->free_spacing)
1769 begin_inset(os, "space ~\n");
1776 else if (t.cat() == catBegin &&
1777 p.next_token().cat() == catEnd) {
1779 Token const prev = p.prev_token();
1781 if (p.next_token().character() == '`' ||
1782 (prev.character() == '-' &&
1783 p.next_token().character() == '-'))
1784 ; // ignore it in {}`` or -{}-
1786 handle_ert(os, "{}", context);
1790 else if (t.cat() == catBegin) {
1791 context.check_layout(os);
1792 // special handling of font attribute changes
1793 Token const prev = p.prev_token();
1794 Token const next = p.next_token();
1795 TeXFont const oldFont = context.font;
1796 if (next.character() == '[' ||
1797 next.character() == ']' ||
1798 next.character() == '*') {
1800 if (p.next_token().cat() == catEnd) {
1805 handle_ert(os, "{", context);
1806 parse_text_snippet(p, os,
1809 handle_ert(os, "}", context);
1811 } else if (! context.new_layout_allowed) {
1812 handle_ert(os, "{", context);
1813 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1815 handle_ert(os, "}", context);
1816 } else if (is_known(next.cs(), known_sizes)) {
1817 // next will change the size, so we must
1819 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1821 if (!context.atParagraphStart())
1823 << context.font.size << "\n";
1824 } else if (is_known(next.cs(), known_font_families)) {
1825 // next will change the font family, so we
1826 // must reset it here
1827 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1829 if (!context.atParagraphStart())
1831 << context.font.family << "\n";
1832 } else if (is_known(next.cs(), known_font_series)) {
1833 // next will change the font series, so we
1834 // must reset it here
1835 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1837 if (!context.atParagraphStart())
1839 << context.font.series << "\n";
1840 } else if (is_known(next.cs(), known_font_shapes)) {
1841 // next will change the font shape, so we
1842 // must reset it here
1843 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1845 if (!context.atParagraphStart())
1847 << context.font.shape << "\n";
1848 } else if (is_known(next.cs(), known_old_font_families) ||
1849 is_known(next.cs(), known_old_font_series) ||
1850 is_known(next.cs(), known_old_font_shapes)) {
1851 // next will change the font family, series
1852 // and shape, so we must reset it here
1853 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1855 if (!context.atParagraphStart())
1857 << context.font.family
1859 << context.font.series
1861 << context.font.shape << "\n";
1863 handle_ert(os, "{", context);
1864 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1866 handle_ert(os, "}", context);
1870 else if (t.cat() == catEnd) {
1871 if (flags & FLAG_BRACE_LAST) {
1874 cerr << "stray '}' in text\n";
1875 handle_ert(os, "}", context);
1878 else if (t.cat() == catComment)
1879 parse_comment(p, os, t, context);
1882 // control sequences
1885 else if (t.cs() == "(") {
1886 context.check_layout(os);
1887 begin_inset(os, "Formula");
1889 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1894 else if (t.cs() == "[") {
1895 context.check_layout(os);
1896 begin_inset(os, "Formula");
1898 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1903 else if (t.cs() == "begin")
1904 parse_environment(p, os, outer, last_env, context);
1906 else if (t.cs() == "end") {
1907 if (flags & FLAG_END) {
1908 // eat environment name
1909 string const name = p.getArg('{', '}');
1910 if (name != active_environment())
1911 cerr << "\\end{" + name + "} does not match \\begin{"
1912 + active_environment() + "}\n";
1915 p.error("found 'end' unexpectedly");
1918 else if (t.cs() == "item") {
1921 bool optarg = false;
1922 if (p.next_token().cat() != catEscape &&
1923 p.next_token().character() == '[') {
1924 p.get_token(); // eat '['
1925 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1930 context.check_layout(os);
1931 if (context.has_item) {
1932 // An item in an unknown list-like environment
1933 // FIXME: Do this in check_layout()!
1934 context.has_item = false;
1936 handle_ert(os, "\\item", context);
1938 handle_ert(os, "\\item ", context);
1941 if (context.layout->labeltype != LABEL_MANUAL) {
1942 // LyX does not support \item[\mybullet]
1943 // in itemize environments
1944 handle_ert(os, "[", context);
1946 handle_ert(os, "]", context);
1947 } else if (!s.empty()) {
1948 // The space is needed to separate the
1949 // item from the rest of the sentence.
1951 eat_whitespace(p, os, context, false);
1956 else if (t.cs() == "bibitem") {
1958 context.check_layout(os);
1959 string label = convert_command_inset_arg(p.getArg('[', ']'));
1960 string key = convert_command_inset_arg(p.verbatim_item());
1961 if (contains(label, '\\') || contains(key, '\\')) {
1962 // LyX can't handle LaTeX commands in labels or keys
1963 handle_ert(os, t.asInput() + '[' + label +
1964 "]{" + p.verbatim_item() + '}',
1967 begin_command_inset(os, "bibitem", "bibitem");
1968 os << "label \"" << label << "\"\n"
1969 "key \"" << key << "\"\n";
1974 else if (is_macro(p))
1975 parse_macro(p, os, context);
1977 else if (t.cs() == "noindent") {
1979 context.add_par_extra_stuff("\\noindent\n");
1982 else if (t.cs() == "appendix") {
1983 context.add_par_extra_stuff("\\start_of_appendix\n");
1984 // We need to start a new paragraph. Otherwise the
1985 // appendix in 'bla\appendix\chapter{' would start
1987 context.new_paragraph(os);
1988 // We need to make sure that the paragraph is
1989 // generated even if it is empty. Otherwise the
1990 // appendix in '\par\appendix\par\chapter{' would
1992 context.check_layout(os);
1993 // FIXME: This is a hack to prevent paragraph
1994 // deletion if it is empty. Handle this better!
1996 "%dummy comment inserted by tex2lyx to "
1997 "ensure that this paragraph is not empty",
1999 // Both measures above may generate an additional
2000 // empty paragraph, but that does not hurt, because
2001 // whitespace does not matter here.
2002 eat_whitespace(p, os, context, true);
2005 // Starred section headings
2006 // Must attempt to parse "Section*" before "Section".
2007 else if ((p.next_token().asInput() == "*") &&
2008 context.new_layout_allowed &&
2009 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2012 output_command_layout(os, p, outer, context, newlayout);
2016 // Section headings and the like
2017 else if (context.new_layout_allowed &&
2018 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2020 output_command_layout(os, p, outer, context, newlayout);
2024 else if (t.cs() == "caption") {
2026 context.check_layout(os);
2028 begin_inset(os, "Caption\n\n");
2029 Context newcontext(true, context.textclass);
2030 newcontext.font = context.font;
2031 newcontext.check_layout(os);
2032 if (p.next_token().cat() != catEscape &&
2033 p.next_token().character() == '[') {
2034 p.get_token(); // eat '['
2035 begin_inset(os, "OptArg\n");
2036 os << "status collapsed\n";
2037 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2039 eat_whitespace(p, os, context, false);
2041 parse_text(p, os, FLAG_ITEM, outer, context);
2042 context.check_end_layout(os);
2043 // We don't need really a new paragraph, but
2044 // we must make sure that the next item gets a \begin_layout.
2045 context.new_paragraph(os);
2048 newcontext.check_end_layout(os);
2051 else if (t.cs() == "includegraphics") {
2052 bool const clip = p.next_token().asInput() == "*";
2055 string const arg = p.getArg('[', ']');
2056 map<string, string> opts;
2057 vector<string> keys;
2058 split_map(arg, opts, keys);
2060 opts["clip"] = string();
2061 string name = normalize_filename(p.verbatim_item());
2063 string const path = getMasterFilePath();
2064 // We want to preserve relative / absolute filenames,
2065 // therefore path is only used for testing
2066 if (!makeAbsPath(name, path).exists()) {
2067 // The file extension is probably missing.
2068 // Now try to find it out.
2069 string const dvips_name =
2070 find_file(name, path,
2071 known_dvips_graphics_formats);
2072 string const pdftex_name =
2073 find_file(name, path,
2074 known_pdftex_graphics_formats);
2075 if (!dvips_name.empty()) {
2076 if (!pdftex_name.empty()) {
2077 cerr << "This file contains the "
2079 "\"\\includegraphics{"
2081 "However, files\n\""
2082 << dvips_name << "\" and\n\""
2083 << pdftex_name << "\"\n"
2084 "both exist, so I had to make a "
2085 "choice and took the first one.\n"
2086 "Please move the unwanted one "
2087 "someplace else and try again\n"
2088 "if my choice was wrong."
2092 } else if (!pdftex_name.empty()) {
2098 if (makeAbsPath(name, path).exists())
2099 fix_relative_filename(name);
2101 cerr << "Warning: Could not find graphics file '"
2102 << name << "'." << endl;
2104 context.check_layout(os);
2105 begin_inset(os, "Graphics ");
2106 os << "\n\tfilename " << name << '\n';
2107 if (opts.find("width") != opts.end())
2109 << translate_len(opts["width"]) << '\n';
2110 if (opts.find("height") != opts.end())
2112 << translate_len(opts["height"]) << '\n';
2113 if (opts.find("scale") != opts.end()) {
2114 istringstream iss(opts["scale"]);
2118 os << "\tscale " << val << '\n';
2120 if (opts.find("angle") != opts.end()) {
2121 os << "\trotateAngle "
2122 << opts["angle"] << '\n';
2123 vector<string>::const_iterator a =
2124 find(keys.begin(), keys.end(), "angle");
2125 vector<string>::const_iterator s =
2126 find(keys.begin(), keys.end(), "width");
2127 if (s == keys.end())
2128 s = find(keys.begin(), keys.end(), "height");
2129 if (s == keys.end())
2130 s = find(keys.begin(), keys.end(), "scale");
2131 if (s != keys.end() && distance(s, a) > 0)
2132 os << "\tscaleBeforeRotation\n";
2134 if (opts.find("origin") != opts.end()) {
2136 string const opt = opts["origin"];
2137 if (opt.find('l') != string::npos) ss << "left";
2138 if (opt.find('r') != string::npos) ss << "right";
2139 if (opt.find('c') != string::npos) ss << "center";
2140 if (opt.find('t') != string::npos) ss << "Top";
2141 if (opt.find('b') != string::npos) ss << "Bottom";
2142 if (opt.find('B') != string::npos) ss << "Baseline";
2143 if (!ss.str().empty())
2144 os << "\trotateOrigin " << ss.str() << '\n';
2146 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2148 if (opts.find("keepaspectratio") != opts.end())
2149 os << "\tkeepAspectRatio\n";
2150 if (opts.find("clip") != opts.end())
2152 if (opts.find("draft") != opts.end())
2154 if (opts.find("bb") != opts.end())
2155 os << "\tBoundingBox "
2156 << opts["bb"] << '\n';
2157 int numberOfbbOptions = 0;
2158 if (opts.find("bbllx") != opts.end())
2159 numberOfbbOptions++;
2160 if (opts.find("bblly") != opts.end())
2161 numberOfbbOptions++;
2162 if (opts.find("bburx") != opts.end())
2163 numberOfbbOptions++;
2164 if (opts.find("bbury") != opts.end())
2165 numberOfbbOptions++;
2166 if (numberOfbbOptions == 4)
2167 os << "\tBoundingBox "
2168 << opts["bbllx"] << " " << opts["bblly"] << " "
2169 << opts["bburx"] << " " << opts["bbury"] << '\n';
2170 else if (numberOfbbOptions > 0)
2171 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2172 numberOfbbOptions = 0;
2173 if (opts.find("natwidth") != opts.end())
2174 numberOfbbOptions++;
2175 if (opts.find("natheight") != opts.end())
2176 numberOfbbOptions++;
2177 if (numberOfbbOptions == 2)
2178 os << "\tBoundingBox 0bp 0bp "
2179 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2180 else if (numberOfbbOptions > 0)
2181 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2182 ostringstream special;
2183 if (opts.find("hiresbb") != opts.end())
2184 special << "hiresbb,";
2185 if (opts.find("trim") != opts.end())
2187 if (opts.find("viewport") != opts.end())
2188 special << "viewport=" << opts["viewport"] << ',';
2189 if (opts.find("totalheight") != opts.end())
2190 special << "totalheight=" << opts["totalheight"] << ',';
2191 if (opts.find("type") != opts.end())
2192 special << "type=" << opts["type"] << ',';
2193 if (opts.find("ext") != opts.end())
2194 special << "ext=" << opts["ext"] << ',';
2195 if (opts.find("read") != opts.end())
2196 special << "read=" << opts["read"] << ',';
2197 if (opts.find("command") != opts.end())
2198 special << "command=" << opts["command"] << ',';
2199 string s_special = special.str();
2200 if (!s_special.empty()) {
2201 // We had special arguments. Remove the trailing ','.
2202 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2204 // TODO: Handle the unknown settings better.
2205 // Warn about invalid options.
2206 // Check whether some option was given twice.
2210 else if (t.cs() == "footnote" ||
2211 (t.cs() == "thanks" && context.layout->intitle)) {
2213 context.check_layout(os);
2214 begin_inset(os, "Foot\n");
2215 os << "status collapsed\n\n";
2216 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2220 else if (t.cs() == "marginpar") {
2222 context.check_layout(os);
2223 begin_inset(os, "Marginal\n");
2224 os << "status collapsed\n\n";
2225 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2229 else if (t.cs() == "ensuremath") {
2231 context.check_layout(os);
2232 string const s = p.verbatim_item();
2233 //FIXME: this never triggers in UTF8
2234 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2237 handle_ert(os, "\\ensuremath{" + s + "}",
2241 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2242 // FIXME: Somehow prevent title layouts if
2243 // "maketitle" was not found
2245 skip_spaces_braces(p);
2248 else if (t.cs() == "tableofcontents") {
2249 context.check_layout(os);
2250 begin_command_inset(os, "toc", "tableofcontents");
2252 skip_spaces_braces(p);
2255 else if (t.cs() == "listoffigures") {
2256 context.check_layout(os);
2257 begin_inset(os, "FloatList figure\n");
2259 skip_spaces_braces(p);
2262 else if (t.cs() == "listoftables") {
2263 context.check_layout(os);
2264 begin_inset(os, "FloatList table\n");
2266 skip_spaces_braces(p);
2269 else if (t.cs() == "listof") {
2270 p.skip_spaces(true);
2271 string const name = p.get_token().cs();
2272 if (context.textclass.floats().typeExist(name)) {
2273 context.check_layout(os);
2274 begin_inset(os, "FloatList ");
2277 p.get_token(); // swallow second arg
2279 handle_ert(os, "\\listof{" + name + "}", context);
2282 else if (t.cs() == "textrm")
2283 parse_text_attributes(p, os, FLAG_ITEM, outer,
2284 context, "\\family",
2285 context.font.family, "roman");
2287 else if (t.cs() == "textsf")
2288 parse_text_attributes(p, os, FLAG_ITEM, outer,
2289 context, "\\family",
2290 context.font.family, "sans");
2292 else if (t.cs() == "texttt")
2293 parse_text_attributes(p, os, FLAG_ITEM, outer,
2294 context, "\\family",
2295 context.font.family, "typewriter");
2297 else if (t.cs() == "textmd")
2298 parse_text_attributes(p, os, FLAG_ITEM, outer,
2299 context, "\\series",
2300 context.font.series, "medium");
2302 else if (t.cs() == "textbf")
2303 parse_text_attributes(p, os, FLAG_ITEM, outer,
2304 context, "\\series",
2305 context.font.series, "bold");
2307 else if (t.cs() == "textup")
2308 parse_text_attributes(p, os, FLAG_ITEM, outer,
2310 context.font.shape, "up");
2312 else if (t.cs() == "textit")
2313 parse_text_attributes(p, os, FLAG_ITEM, outer,
2315 context.font.shape, "italic");
2317 else if (t.cs() == "textsl")
2318 parse_text_attributes(p, os, FLAG_ITEM, outer,
2320 context.font.shape, "slanted");
2322 else if (t.cs() == "textsc")
2323 parse_text_attributes(p, os, FLAG_ITEM, outer,
2325 context.font.shape, "smallcaps");
2327 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2328 context.check_layout(os);
2329 TeXFont oldFont = context.font;
2330 context.font.init();
2331 context.font.size = oldFont.size;
2332 os << "\n\\family " << context.font.family << "\n";
2333 os << "\n\\series " << context.font.series << "\n";
2334 os << "\n\\shape " << context.font.shape << "\n";
2335 if (t.cs() == "textnormal") {
2336 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2337 output_font_change(os, context.font, oldFont);
2338 context.font = oldFont;
2340 eat_whitespace(p, os, context, false);
2343 else if (t.cs() == "textcolor") {
2344 // scheme is \textcolor{color name}{text}
2345 string const color = p.verbatim_item();
2346 // we only support the predefined colors of the color package
2347 if (color == "black" || color == "blue" || color == "cyan"
2348 || color == "green" || color == "magenta" || color == "red"
2349 || color == "white" || color == "yellow") {
2350 context.check_layout(os);
2351 os << "\n\\color " << color << "\n";
2352 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2353 context.check_layout(os);
2354 os << "\n\\color inherit\n";
2356 // for custom defined colors
2357 handle_ert(os, t.asInput() + "{" + color + "}", context);
2360 else if (t.cs() == "underbar") {
2361 // Do NOT handle \underline.
2362 // \underbar cuts through y, g, q, p etc.,
2363 // \underline does not.
2364 context.check_layout(os);
2365 os << "\n\\bar under\n";
2366 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2367 context.check_layout(os);
2368 os << "\n\\bar default\n";
2371 else if (t.cs() == "emph" || t.cs() == "noun") {
2372 context.check_layout(os);
2373 os << "\n\\" << t.cs() << " on\n";
2374 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2375 context.check_layout(os);
2376 os << "\n\\" << t.cs() << " default\n";
2379 else if (t.cs() == "lyxline") {
2380 context.check_layout(os);
2384 else if (is_known(t.cs(), known_phrases) ||
2385 (t.cs() == "protect" &&
2386 p.next_token().cat() == catEscape &&
2387 is_known(p.next_token().cs(), known_phrases))) {
2388 // LyX sometimes puts a \protect in front, so we have to ignore it
2389 // FIXME: This needs to be changed when bug 4752 is fixed.
2390 char const * const * where = is_known(
2391 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
2393 context.check_layout(os);
2394 os << known_coded_phrases[where - known_phrases];
2395 skip_spaces_braces(p);
2398 else if (is_known(t.cs(), known_ref_commands)) {
2399 string const opt = p.getOpt();
2401 context.check_layout(os);
2402 begin_command_inset(os, "ref", t.cs());
2403 os << "reference \""
2404 << convert_command_inset_arg(p.verbatim_item())
2408 // LyX does not support optional arguments of ref commands
2409 handle_ert(os, t.asInput() + '[' + opt + "]{" +
2410 p.verbatim_item() + "}", context);
2414 else if (use_natbib &&
2415 is_known(t.cs(), known_natbib_commands) &&
2416 ((t.cs() != "citefullauthor" &&
2417 t.cs() != "citeyear" &&
2418 t.cs() != "citeyearpar") ||
2419 p.next_token().asInput() != "*")) {
2420 context.check_layout(os);
2421 string command = t.cs();
2422 if (p.next_token().asInput() == "*") {
2426 if (command == "citefullauthor")
2427 // alternative name for "\\citeauthor*"
2428 command = "citeauthor*";
2430 // text before the citation
2432 // text after the citation
2434 get_cite_arguments(p, true, before, after);
2436 if (command == "cite") {
2437 // \cite without optional argument means
2438 // \citet, \cite with at least one optional
2439 // argument means \citep.
2440 if (before.empty() && after.empty())
2445 if (before.empty() && after == "[]")
2446 // avoid \citet[]{a}
2448 else if (before == "[]" && after == "[]") {
2449 // avoid \citet[][]{a}
2453 // remove the brackets around after and before
2454 if (!after.empty()) {
2456 after.erase(after.length() - 1, 1);
2457 after = convert_command_inset_arg(after);
2459 if (!before.empty()) {
2461 before.erase(before.length() - 1, 1);
2462 before = convert_command_inset_arg(before);
2464 begin_command_inset(os, "citation", command);
2465 os << "after " << '"' << after << '"' << "\n";
2466 os << "before " << '"' << before << '"' << "\n";
2468 << convert_command_inset_arg(p.verbatim_item())
2473 else if (use_jurabib &&
2474 is_known(t.cs(), known_jurabib_commands) &&
2475 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
2476 context.check_layout(os);
2477 string command = t.cs();
2478 if (p.next_token().asInput() == "*") {
2482 char argumentOrder = '\0';
2483 vector<string> const & options = used_packages["jurabib"];
2484 if (find(options.begin(), options.end(),
2485 "natbiborder") != options.end())
2486 argumentOrder = 'n';
2487 else if (find(options.begin(), options.end(),
2488 "jurabiborder") != options.end())
2489 argumentOrder = 'j';
2491 // text before the citation
2493 // text after the citation
2495 get_cite_arguments(p, argumentOrder != 'j', before, after);
2497 string const citation = p.verbatim_item();
2498 if (!before.empty() && argumentOrder == '\0') {
2499 cerr << "Warning: Assuming argument order "
2500 "of jurabib version 0.6 for\n'"
2501 << command << before << after << '{'
2502 << citation << "}'.\n"
2503 "Add 'jurabiborder' to the jurabib "
2504 "package options if you used an\n"
2505 "earlier jurabib version." << endl;
2507 if (!after.empty()) {
2509 after.erase(after.length() - 1, 1);
2511 if (!before.empty()) {
2513 before.erase(before.length() - 1, 1);
2515 begin_command_inset(os, "citation", command);
2516 os << "after " << '"' << after << '"' << "\n";
2517 os << "before " << '"' << before << '"' << "\n";
2518 os << "key " << '"' << citation << '"' << "\n";
2522 else if (t.cs() == "cite"
2523 || t.cs() == "nocite") {
2524 context.check_layout(os);
2525 string after = convert_command_inset_arg(p.getArg('[', ']'));
2526 string key = convert_command_inset_arg(p.verbatim_item());
2527 // store the case that it is "\nocite{*}" to use it later for
2530 begin_command_inset(os, "citation", t.cs());
2531 os << "after " << '"' << after << '"' << "\n";
2532 os << "key " << '"' << key << '"' << "\n";
2534 } else if (t.cs() == "nocite")
2538 else if (t.cs() == "index") {
2539 context.check_layout(os);
2540 begin_inset(os, "Index\n");
2541 os << "status collapsed\n";
2542 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
2546 else if (t.cs() == "nomenclature") {
2547 context.check_layout(os);
2548 begin_command_inset(os, "nomenclature", "nomenclature");
2549 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
2550 if (!prefix.empty())
2551 os << "prefix " << '"' << prefix << '"' << "\n";
2552 os << "symbol " << '"'
2553 << convert_command_inset_arg(p.verbatim_item());
2554 os << "\"\ndescription \""
2555 << convert_command_inset_arg(p.verbatim_item())
2560 else if (t.cs() == "label") {
2561 context.check_layout(os);
2562 begin_command_inset(os, "label", "label");
2564 << convert_command_inset_arg(p.verbatim_item())
2569 else if (t.cs() == "printindex") {
2570 context.check_layout(os);
2571 begin_command_inset(os, "index_print", "printindex");
2573 skip_spaces_braces(p);
2576 else if (t.cs() == "printnomenclature") {
2577 context.check_layout(os);
2578 begin_command_inset(os, "nomencl_print", "printnomenclature");
2580 skip_spaces_braces(p);
2583 else if (LYX_FORMAT >= 408 &&
2584 (t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
2585 context.check_layout(os);
2586 begin_inset(os, "script ");
2587 os << t.cs().substr(4) << '\n';
2588 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2592 else if (is_known(t.cs(), known_quotes)) {
2593 char const * const * where = is_known(t.cs(), known_quotes);
2594 context.check_layout(os);
2595 begin_inset(os, "Quotes ");
2596 os << known_coded_quotes[where - known_quotes];
2598 // LyX adds {} after the quote, so we have to eat
2599 // spaces here if there are any before a possible
2601 eat_whitespace(p, os, context, false);
2605 else if (is_known(t.cs(), known_sizes) &&
2606 context.new_layout_allowed) {
2607 char const * const * where = is_known(t.cs(), known_sizes);
2608 context.check_layout(os);
2609 TeXFont const oldFont = context.font;
2610 context.font.size = known_coded_sizes[where - known_sizes];
2611 output_font_change(os, oldFont, context.font);
2612 eat_whitespace(p, os, context, false);
2615 else if (is_known(t.cs(), known_font_families) &&
2616 context.new_layout_allowed) {
2617 char const * const * where =
2618 is_known(t.cs(), known_font_families);
2619 context.check_layout(os);
2620 TeXFont const oldFont = context.font;
2621 context.font.family =
2622 known_coded_font_families[where - known_font_families];
2623 output_font_change(os, oldFont, context.font);
2624 eat_whitespace(p, os, context, false);
2627 else if (is_known(t.cs(), known_font_series) &&
2628 context.new_layout_allowed) {
2629 char const * const * where =
2630 is_known(t.cs(), known_font_series);
2631 context.check_layout(os);
2632 TeXFont const oldFont = context.font;
2633 context.font.series =
2634 known_coded_font_series[where - known_font_series];
2635 output_font_change(os, oldFont, context.font);
2636 eat_whitespace(p, os, context, false);
2639 else if (is_known(t.cs(), known_font_shapes) &&
2640 context.new_layout_allowed) {
2641 char const * const * where =
2642 is_known(t.cs(), known_font_shapes);
2643 context.check_layout(os);
2644 TeXFont const oldFont = context.font;
2645 context.font.shape =
2646 known_coded_font_shapes[where - known_font_shapes];
2647 output_font_change(os, oldFont, context.font);
2648 eat_whitespace(p, os, context, false);
2650 else if (is_known(t.cs(), known_old_font_families) &&
2651 context.new_layout_allowed) {
2652 char const * const * where =
2653 is_known(t.cs(), known_old_font_families);
2654 context.check_layout(os);
2655 TeXFont const oldFont = context.font;
2656 context.font.init();
2657 context.font.size = oldFont.size;
2658 context.font.family =
2659 known_coded_font_families[where - known_old_font_families];
2660 output_font_change(os, oldFont, context.font);
2661 eat_whitespace(p, os, context, false);
2664 else if (is_known(t.cs(), known_old_font_series) &&
2665 context.new_layout_allowed) {
2666 char const * const * where =
2667 is_known(t.cs(), known_old_font_series);
2668 context.check_layout(os);
2669 TeXFont const oldFont = context.font;
2670 context.font.init();
2671 context.font.size = oldFont.size;
2672 context.font.series =
2673 known_coded_font_series[where - known_old_font_series];
2674 output_font_change(os, oldFont, context.font);
2675 eat_whitespace(p, os, context, false);
2678 else if (is_known(t.cs(), known_old_font_shapes) &&
2679 context.new_layout_allowed) {
2680 char const * const * where =
2681 is_known(t.cs(), known_old_font_shapes);
2682 context.check_layout(os);
2683 TeXFont const oldFont = context.font;
2684 context.font.init();
2685 context.font.size = oldFont.size;
2686 context.font.shape =
2687 known_coded_font_shapes[where - known_old_font_shapes];
2688 output_font_change(os, oldFont, context.font);
2689 eat_whitespace(p, os, context, false);
2692 else if (t.cs() == "selectlanguage") {
2693 context.check_layout(os);
2694 // save the language for the case that a
2695 // \foreignlanguage is used
2697 context.font.language = babel2lyx(p.verbatim_item());
2698 os << "\n\\lang " << context.font.language << "\n";
2701 else if (t.cs() == "foreignlanguage") {
2702 string const lang = babel2lyx(p.verbatim_item());
2703 parse_text_attributes(p, os, FLAG_ITEM, outer,
2705 context.font.language, lang);
2708 else if (t.cs() == "inputencoding") {
2709 // nothing to write here
2710 string const enc = subst(p.verbatim_item(), "\n", " ");
2714 else if (t.cs() == "ldots") {
2715 context.check_layout(os);
2716 os << "\\SpecialChar \\ldots{}\n";
2717 skip_spaces_braces(p);
2720 else if (t.cs() == "lyxarrow") {
2721 context.check_layout(os);
2722 os << "\\SpecialChar \\menuseparator\n";
2723 skip_spaces_braces(p);
2726 else if (t.cs() == "textcompwordmark") {
2727 context.check_layout(os);
2728 os << "\\SpecialChar \\textcompwordmark{}\n";
2729 skip_spaces_braces(p);
2732 else if (t.cs() == "slash") {
2733 context.check_layout(os);
2734 os << "\\SpecialChar \\slash{}\n";
2735 skip_spaces_braces(p);
2738 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
2739 context.check_layout(os);
2740 os << "\\SpecialChar \\nobreakdash-\n";
2744 else if (t.cs() == "textquotedbl") {
2745 context.check_layout(os);
2750 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2751 context.check_layout(os);
2752 os << "\\SpecialChar \\@.\n";
2756 else if (t.cs() == "-") {
2757 context.check_layout(os);
2758 os << "\\SpecialChar \\-\n";
2761 else if (t.cs() == "textasciitilde") {
2762 context.check_layout(os);
2764 skip_spaces_braces(p);
2767 else if (t.cs() == "textasciicircum") {
2768 context.check_layout(os);
2770 skip_spaces_braces(p);
2773 else if (t.cs() == "textbackslash") {
2774 context.check_layout(os);
2775 os << "\n\\backslash\n";
2776 skip_spaces_braces(p);
2779 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2780 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2782 context.check_layout(os);
2786 else if (t.cs() == "char") {
2787 context.check_layout(os);
2788 if (p.next_token().character() == '`') {
2790 if (p.next_token().cs() == "\"") {
2795 handle_ert(os, "\\char`", context);
2798 handle_ert(os, "\\char", context);
2802 else if (t.cs() == "verb") {
2803 context.check_layout(os);
2804 char const delimiter = p.next_token().character();
2805 string const arg = p.getArg(delimiter, delimiter);
2807 oss << "\\verb" << delimiter << arg << delimiter;
2808 handle_ert(os, oss.str(), context);
2811 // Problem: \= creates a tabstop inside the tabbing environment
2812 // and else an accent. In the latter case we really would want
2813 // \={o} instead of \= o.
2814 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2815 handle_ert(os, t.asInput(), context);
2817 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
2818 else if (t.cs().size() == 1
2819 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
2820 context.check_layout(os);
2821 // try to see whether the string is in unicodesymbols
2823 string command = t.asInput() + "{"
2824 + trim(p.verbatim_item())
2826 docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
2829 cerr << "When parsing " << command
2830 << ", result is " << to_utf8(s)
2831 << "+" << to_utf8(rem) << endl;
2834 // we did not find a non-ert version
2835 handle_ert(os, command, context);
2838 else if (t.cs() == "\\") {
2839 context.check_layout(os);
2841 handle_ert(os, "\\\\" + p.getOpt(), context);
2842 else if (p.next_token().asInput() == "*") {
2844 // getOpt() eats the following space if there
2845 // is no optional argument, but that is OK
2846 // here since it has no effect in the output.
2847 handle_ert(os, "\\\\*" + p.getOpt(), context);
2850 begin_inset(os, "Newline newline");
2855 else if (t.cs() == "newline" ||
2856 (t.cs() == "linebreak" && !p.hasOpt())) {
2857 context.check_layout(os);
2858 begin_inset(os, "Newline ");
2861 skip_spaces_braces(p);
2864 else if (t.cs() == "input" || t.cs() == "include"
2865 || t.cs() == "verbatiminput") {
2866 string name = t.cs();
2867 if (t.cs() == "verbatiminput"
2868 && p.next_token().asInput() == "*")
2869 name += p.get_token().asInput();
2870 context.check_layout(os);
2871 string filename(normalize_filename(p.getArg('{', '}')));
2872 string const path = getMasterFilePath();
2873 // We want to preserve relative / absolute filenames,
2874 // therefore path is only used for testing
2875 if ((t.cs() == "include" || t.cs() == "input") &&
2876 !makeAbsPath(filename, path).exists()) {
2877 // The file extension is probably missing.
2878 // Now try to find it out.
2879 string const tex_name =
2880 find_file(filename, path,
2881 known_tex_extensions);
2882 if (!tex_name.empty())
2883 filename = tex_name;
2885 bool external = false;
2887 if (makeAbsPath(filename, path).exists()) {
2888 string const abstexname =
2889 makeAbsPath(filename, path).absFileName();
2890 string const abslyxname =
2891 changeExtension(abstexname, ".lyx");
2892 string const absfigname =
2893 changeExtension(abstexname, ".fig");
2894 fix_relative_filename(filename);
2895 string const lyxname =
2896 changeExtension(filename, ".lyx");
2898 external = FileName(absfigname).exists();
2899 if (t.cs() == "input") {
2900 string const ext = getExtension(abstexname);
2902 // Combined PS/LaTeX:
2903 // x.eps, x.pstex_t (old xfig)
2904 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
2905 FileName const absepsname(
2906 changeExtension(abstexname, ".eps"));
2907 FileName const abspstexname(
2908 changeExtension(abstexname, ".pstex"));
2909 bool const xfigeps =
2910 (absepsname.exists() ||
2911 abspstexname.exists()) &&
2914 // Combined PDF/LaTeX:
2915 // x.pdf, x.pdftex_t (old xfig)
2916 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
2917 FileName const abspdfname(
2918 changeExtension(abstexname, ".pdf"));
2919 bool const xfigpdf =
2920 abspdfname.exists() &&
2921 (ext == "pdftex_t" || ext == "pdf_t");
2925 // Combined PS/PDF/LaTeX:
2926 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
2927 string const absbase2(
2928 removeExtension(abstexname) + "_pspdftex");
2929 FileName const abseps2name(
2930 addExtension(absbase2, ".eps"));
2931 FileName const abspdf2name(
2932 addExtension(absbase2, ".pdf"));
2933 bool const xfigboth =
2934 abspdf2name.exists() &&
2935 abseps2name.exists() && ext == "pspdftex";
2937 xfig = xfigpdf || xfigeps || xfigboth;
2938 external = external && xfig;
2941 outname = changeExtension(filename, ".fig");
2943 // Don't try to convert, the result
2944 // would be full of ERT.
2946 } else if (t.cs() != "verbatiminput" &&
2947 tex2lyx(abstexname, FileName(abslyxname),
2954 cerr << "Warning: Could not find included file '"
2955 << filename << "'." << endl;
2959 begin_inset(os, "External\n");
2960 os << "\ttemplate XFig\n"
2961 << "\tfilename " << outname << '\n';
2963 begin_command_inset(os, "include", name);
2964 os << "preview false\n"
2965 "filename \"" << outname << "\"\n";
2970 else if (t.cs() == "bibliographystyle") {
2971 // store new bibliographystyle
2972 bibliographystyle = p.verbatim_item();
2973 // If any other command than \bibliography and
2974 // \nocite{*} follows, we need to output the style
2975 // (because it might be used by that command).
2976 // Otherwise, it will automatically be output by LyX.
2979 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
2980 if (t2.cat() == catBegin)
2982 if (t2.cat() != catEscape)
2984 if (t2.cs() == "nocite") {
2985 if (p.getArg('{', '}') == "*")
2987 } else if (t2.cs() == "bibliography")
2994 "\\bibliographystyle{" + bibliographystyle + '}',
2999 else if (t.cs() == "bibliography") {
3000 context.check_layout(os);
3001 begin_command_inset(os, "bibtex", "bibtex");
3002 if (!btprint.empty()) {
3003 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3004 // clear the string because the next BibTeX inset can be without the
3005 // \nocite{*} option
3008 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3009 // Do we have a bibliographystyle set?
3010 if (!bibliographystyle.empty())
3011 os << "options " << '"' << bibliographystyle << '"' << "\n";
3015 else if (t.cs() == "parbox")
3016 parse_box(p, os, 0, FLAG_ITEM, outer, context, "", "", t.cs());
3018 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3019 t.cs() == "shadowbox" || t.cs() == "doublebox")
3020 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3022 else if (t.cs() == "framebox") {
3023 string special = p.getFullOpt();
3024 special += p.getOpt();
3025 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), special);
3028 //\makebox() is part of the picture environment and different from \makebox{}
3029 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
3030 else if (t.cs() == "makebox") {
3031 string arg = t.asInput();
3032 if (p.next_token().character() == '(')
3033 //the syntax is: \makebox(x,y)[position]{content}
3034 arg += p.getFullParentheseArg();
3036 //the syntax is: \makebox[width][position]{content}
3037 arg += p.getFullOpt();
3038 handle_ert(os, arg + p.getFullOpt(), context);
3041 else if (t.cs() == "smallskip" ||
3042 t.cs() == "medskip" ||
3043 t.cs() == "bigskip" ||
3044 t.cs() == "vfill") {
3045 context.check_layout(os);
3046 begin_inset(os, "VSpace ");
3049 skip_spaces_braces(p);
3052 else if (is_known(t.cs(), known_spaces)) {
3053 char const * const * where = is_known(t.cs(), known_spaces);
3054 context.check_layout(os);
3055 begin_inset(os, "space ");
3056 os << '\\' << known_coded_spaces[where - known_spaces]
3059 // LaTeX swallows whitespace after all spaces except
3060 // "\\,". We have to do that here, too, because LyX
3061 // adds "{}" which would make the spaces significant.
3063 eat_whitespace(p, os, context, false);
3064 // LyX adds "{}" after all spaces except "\\ " and
3065 // "\\,", so we have to remove "{}".
3066 // "\\,{}" is equivalent to "\\," in LaTeX, so we
3067 // remove the braces after "\\,", too.
3072 else if (t.cs() == "newpage" ||
3073 (t.cs() == "pagebreak" && !p.hasOpt()) ||
3074 t.cs() == "clearpage" ||
3075 t.cs() == "cleardoublepage") {
3076 context.check_layout(os);
3077 begin_inset(os, "Newpage ");
3080 skip_spaces_braces(p);
3083 else if (t.cs() == "DeclareRobustCommand" ||
3084 t.cs() == "DeclareRobustCommandx" ||
3085 t.cs() == "newcommand" ||
3086 t.cs() == "newcommandx" ||
3087 t.cs() == "providecommand" ||
3088 t.cs() == "providecommandx" ||
3089 t.cs() == "renewcommand" ||
3090 t.cs() == "renewcommandx") {
3091 // DeclareRobustCommand, DeclareRobustCommandx,
3092 // providecommand and providecommandx could be handled
3093 // by parse_command(), but we need to call
3094 // add_known_command() here.
3095 string name = t.asInput();
3096 if (p.next_token().asInput() == "*") {
3097 // Starred form. Eat '*'
3101 string const command = p.verbatim_item();
3102 string const opt1 = p.getFullOpt();
3103 string const opt2 = p.getFullOpt();
3104 add_known_command(command, opt1, !opt2.empty());
3105 string const ert = name + '{' + command + '}' +
3107 '{' + p.verbatim_item() + '}';
3109 if (t.cs() == "DeclareRobustCommand" ||
3110 t.cs() == "DeclareRobustCommandx" ||
3111 t.cs() == "providecommand" ||
3112 t.cs() == "providecommandx" ||
3113 name[name.length()-1] == '*')
3114 handle_ert(os, ert, context);
3116 context.check_layout(os);
3117 begin_inset(os, "FormulaMacro");
3123 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3124 // let could be handled by parse_command(),
3125 // but we need to call add_known_command() here.
3126 string ert = t.asInput();
3129 if (p.next_token().cat() == catBegin) {
3130 name = p.verbatim_item();
3131 ert += '{' + name + '}';
3133 name = p.verbatim_item();
3138 if (p.next_token().cat() == catBegin) {
3139 command = p.verbatim_item();
3140 ert += '{' + command + '}';
3142 command = p.verbatim_item();
3145 // If command is known, make name known too, to parse
3146 // its arguments correctly. For this reason we also
3147 // have commands in syntax.default that are hardcoded.
3148 CommandMap::iterator it = known_commands.find(command);
3149 if (it != known_commands.end())
3150 known_commands[t.asInput()] = it->second;
3151 handle_ert(os, ert, context);
3154 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3155 bool starred = false;
3156 if (p.next_token().asInput() == "*") {
3160 string name = t.asInput();
3161 string const length = p.verbatim_item();
3164 bool valid = splitLatexLength(length, valstring, unit);
3165 bool known_hspace = false;
3166 bool known_vspace = false;
3167 bool known_unit = false;
3170 istringstream iss(valstring);
3173 if (t.cs()[0] == 'h') {
3174 if (unit == "\\fill") {
3179 known_hspace = true;
3182 if (unit == "\\smallskipamount") {
3184 known_vspace = true;
3185 } else if (unit == "\\medskipamount") {
3187 known_vspace = true;
3188 } else if (unit == "\\bigskipamount") {
3190 known_vspace = true;
3191 } else if (unit == "\\fill") {
3193 known_vspace = true;
3197 if (!known_hspace && !known_vspace) {
3198 switch (unitFromString(unit)) {
3219 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3220 // Literal horizontal length or known variable
3221 context.check_layout(os);
3222 begin_inset(os, "space ");
3230 if (known_unit && !known_hspace)
3232 << translate_len(length);
3234 } else if (known_unit || known_vspace) {
3235 // Literal vertical length or known variable
3236 context.check_layout(os);
3237 begin_inset(os, "VSpace ");
3245 // LyX can't handle other length variables in Inset VSpace/space
3250 handle_ert(os, name + '{' + unit + '}', context);
3251 else if (value == -1.0)
3252 handle_ert(os, name + "{-" + unit + '}', context);
3254 handle_ert(os, name + '{' + valstring + unit + '}', context);
3256 handle_ert(os, name + '{' + length + '}', context);
3260 // The single '=' is meant here.
3261 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3263 context.check_layout(os);
3264 begin_inset(os, "Flex ");
3265 os << to_utf8(newinsetlayout->name()) << '\n'
3266 << "status collapsed\n";
3267 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3272 // try to see whether the string is in unicodesymbols
3273 // Only use text mode commands, since we are in text mode here,
3274 // and math commands may be invalid (bug 6797)
3276 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
3277 rem, Encodings::TEXT_CMD);
3280 cerr << "When parsing " << t.cs()
3281 << ", result is " << to_utf8(s)
3282 << "+" << to_utf8(rem) << endl;
3283 context.check_layout(os);
3285 skip_spaces_braces(p);
3287 //cerr << "#: " << t << " mode: " << mode << endl;
3288 // heuristic: read up to next non-nested space
3290 string s = t.asInput();
3291 string z = p.verbatim_item();
3292 while (p.good() && z != " " && z.size()) {
3293 //cerr << "read: " << z << endl;
3295 z = p.verbatim_item();
3297 cerr << "found ERT: " << s << endl;
3298 handle_ert(os, s + ' ', context);
3301 string name = t.asInput();
3302 if (p.next_token().asInput() == "*") {
3303 // Starred commands like \vspace*{}
3304 p.get_token(); // Eat '*'
3307 if (!parse_command(name, p, os, outer, context))
3308 handle_ert(os, name, context);
3312 if (flags & FLAG_LEAVE) {
3313 flags &= ~FLAG_LEAVE;