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)
46 Context newcontext(true, context.textclass);
47 newcontext.font = context.font;
48 parse_text(p, os, flags, outer, newcontext);
49 newcontext.check_end_layout(os);
55 /// parses a paragraph snippet, useful for example for \\emph{...}
56 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
59 Context newcontext(context);
60 // Don't inherit the paragraph-level extra stuff
61 newcontext.par_extra_stuff.clear();
62 parse_text(p, os, flags, outer, newcontext);
63 // Make sure that we don't create invalid .lyx files
64 context.need_layout = newcontext.need_layout;
65 context.need_end_layout = newcontext.need_end_layout;
70 * Thin wrapper around parse_text_snippet() using a string.
72 * We completely ignore \c context.need_layout and \c context.need_end_layout,
73 * because our return value is not used directly (otherwise the stream version
74 * of parse_text_snippet() could be used). That means that the caller needs
75 * to do layout management manually.
76 * This is intended to parse text that does not create any layout changes.
78 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
81 Context newcontext(context);
82 newcontext.need_layout = false;
83 newcontext.need_end_layout = false;
84 newcontext.new_layout_allowed = false;
85 // Avoid warning by Context::~Context()
86 newcontext.par_extra_stuff.clear();
88 parse_text_snippet(p, os, flags, outer, newcontext);
93 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
94 "vpageref", "prettyref", "eqref", 0 };
98 * The starred forms are also known except for "citefullauthor",
99 * "citeyear" and "citeyearpar".
101 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
102 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
103 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
107 * No starred form other than "cite*" known.
109 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
110 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
111 // jurabib commands not (yet) supported by LyX:
113 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
114 // "footciteauthor", "footciteyear", "footciteyearpar",
115 "citefield", "citetitle", 0 };
117 /// LaTeX names for quotes
118 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
119 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
120 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
121 "guilsinglleft", "frq", "guilsinglright", 0};
123 /// the same as known_quotes with .lyx names
124 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
125 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
126 "gld", "grd", "gls", "ers", "fls",
127 "fls", "frs", "frs", 0};
129 /// LaTeX names for font sizes
130 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
131 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
133 /// the same as known_sizes with .lyx names plus a default entry
134 char const * const known_coded_sizes[] = { "default", "tiny", "scriptsize", "footnotesize",
135 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
137 /// LaTeX 2.09 names for font families
138 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
140 /// LaTeX names for font families
141 char const * const known_font_families[] = { "rmfamily", "sffamily",
144 /// the same as known_old_font_families and known_font_families with .lyx names
145 char const * const known_coded_font_families[] = { "roman", "sans",
148 /// LaTeX 2.09 names for font series
149 char const * const known_old_font_series[] = { "bf", 0};
151 /// LaTeX names for font series
152 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
154 /// the same as known_old_font_series and known_font_series with .lyx names
155 char const * const known_coded_font_series[] = { "bold", "medium", 0};
157 /// LaTeX 2.09 names for font shapes
158 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
160 /// LaTeX names for font shapes
161 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
164 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
165 char const * const known_coded_font_shapes[] = { "italic", "slanted",
166 "smallcaps", "up", 0};
169 * Graphics file extensions known by the dvips driver of the graphics package.
170 * These extensions are used to complete the filename of an included
171 * graphics file if it does not contain an extension.
172 * The order must be the same that latex uses to find a file, because we
173 * will use the first extension that matches.
174 * This is only an approximation for the common cases. If we would want to
175 * do it right in all cases, we would need to know which graphics driver is
176 * used and know the extensions of every driver of the graphics package.
178 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
179 "ps.gz", "eps.Z", "ps.Z", 0};
182 * Graphics file extensions known by the pdftex driver of the graphics package.
183 * \sa known_dvips_graphics_formats
185 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
189 * Known file extensions for TeX files as used by \\include.
191 char const * const known_tex_extensions[] = {"tex", 0};
193 /// spaces known by InsetSpace
194 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
195 "qquad", "enspace", "enskip", "negthinspace", 0};
197 /// the same as known_spaces with .lyx names
198 char const * const known_coded_spaces[] = { "space{}", "space{}",
199 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
200 "negthinspace{}", 0};
203 /// splits "x=z, y=b" into a map and an ordered keyword vector
204 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
209 keys.resize(v.size());
210 for (size_t i = 0; i < v.size(); ++i) {
211 size_t const pos = v[i].find('=');
212 string const index = trim(v[i].substr(0, pos));
213 string const value = trim(v[i].substr(pos + 1, string::npos));
221 * Split a LaTeX length into value and unit.
222 * The latter can be a real unit like "pt", or a latex length variable
223 * like "\textwidth". The unit may contain additional stuff like glue
224 * lengths, but we don't care, because such lengths are ERT anyway.
225 * \returns true if \p value and \p unit are valid.
227 bool splitLatexLength(string const & len, string & value, string & unit)
231 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
232 //'4,5' is a valid LaTeX length number. Change it to '4.5'
233 string const length = subst(len, ',', '.');
234 if (i == string::npos)
237 if (len[0] == '\\') {
238 // We had something like \textwidth without a factor
244 value = trim(string(length, 0, i));
248 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
249 if (contains(len, '\\'))
250 unit = trim(string(len, i));
252 unit = ascii_lowercase(trim(string(len, i)));
257 /// A simple function to translate a latex length to something LyX can
258 /// understand. Not perfect, but rather best-effort.
259 bool translate_len(string const & length, string & valstring, string & unit)
261 if (!splitLatexLength(length, valstring, unit))
263 // LyX uses percent values
265 istringstream iss(valstring);
270 string const percentval = oss.str();
272 if (unit.empty() || unit[0] != '\\')
274 string::size_type const i = unit.find(' ');
275 string const endlen = (i == string::npos) ? string() : string(unit, i);
276 if (unit == "\\textwidth") {
277 valstring = percentval;
278 unit = "text%" + endlen;
279 } else if (unit == "\\columnwidth") {
280 valstring = percentval;
281 unit = "col%" + endlen;
282 } else if (unit == "\\paperwidth") {
283 valstring = percentval;
284 unit = "page%" + endlen;
285 } else if (unit == "\\linewidth") {
286 valstring = percentval;
287 unit = "line%" + endlen;
288 } else if (unit == "\\paperheight") {
289 valstring = percentval;
290 unit = "pheight%" + endlen;
291 } else if (unit == "\\textheight") {
292 valstring = percentval;
293 unit = "theight%" + endlen;
301 string translate_len(string const & length)
305 if (translate_len(length, value, unit))
307 // If the input is invalid, return what we have.
315 * Translates a LaTeX length into \p value, \p unit and
316 * \p special parts suitable for a box inset.
317 * The difference from translate_len() is that a box inset knows about
318 * some special "units" that are stored in \p special.
320 void translate_box_len(string const & length, string & value, string & unit, string & special)
322 if (translate_len(length, value, unit)) {
323 if (unit == "\\height" || unit == "\\depth" ||
324 unit == "\\totalheight" || unit == "\\width") {
325 special = unit.substr(1);
326 // The unit is not used, but LyX requires a dummy setting
339 * Find a file with basename \p name in path \p path and an extension
342 string find_file(string const & name, string const & path,
343 char const * const * extensions)
345 for (char const * const * what = extensions; *what; ++what) {
346 string const trial = addExtension(name, *what);
347 if (makeAbsPath(trial, path).exists())
354 void begin_inset(ostream & os, string const & name)
356 os << "\n\\begin_inset " << name;
360 void begin_command_inset(ostream & os, string const & name,
361 string const & latexname)
363 begin_inset(os, "CommandInset ");
364 os << name << "\nLatexCommand " << latexname << '\n';
368 void end_inset(ostream & os)
370 os << "\n\\end_inset\n\n";
374 bool skip_braces(Parser & p)
376 if (p.next_token().cat() != catBegin)
379 if (p.next_token().cat() == catEnd) {
388 void handle_ert(ostream & os, string const & s, Context & context)
390 // We must have a valid layout before outputting the ERT inset.
391 context.check_layout(os);
392 Context newcontext(true, context.textclass);
393 begin_inset(os, "ERT");
394 os << "\nstatus collapsed\n";
395 newcontext.check_layout(os);
396 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
398 os << "\n\\backslash\n";
399 else if (*it == '\n') {
400 newcontext.new_paragraph(os);
401 newcontext.check_layout(os);
405 newcontext.check_end_layout(os);
410 void handle_comment(ostream & os, string const & s, Context & context)
412 // TODO: Handle this better
413 Context newcontext(true, context.textclass);
414 begin_inset(os, "ERT");
415 os << "\nstatus collapsed\n";
416 newcontext.check_layout(os);
417 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
419 os << "\n\\backslash\n";
423 // make sure that our comment is the last thing on the line
424 newcontext.new_paragraph(os);
425 newcontext.check_layout(os);
426 newcontext.check_end_layout(os);
431 Layout const * findLayout(TextClass const & textclass, string const & name)
433 DocumentClass::const_iterator lit = textclass.begin();
434 DocumentClass::const_iterator len = textclass.end();
435 for (; lit != len; ++lit)
436 if (lit->latexname() == name)
442 void eat_whitespace(Parser &, ostream &, Context &, bool);
446 * Skips whitespace and braces.
447 * This should be called after a command has been parsed that is not put into
448 * ERT, and where LyX adds "{}" if needed.
450 void skip_spaces_braces(Parser & p)
452 /* The following four examples produce the same typeset output and
453 should be handled by this function:
461 // Unfortunately we need to skip comments, too.
462 // We can't use eat_whitespace since writing them after the {}
463 // results in different output in some cases.
464 bool const skipped_spaces = p.skip_spaces(true);
465 bool const skipped_braces = skip_braces(p);
466 if (skipped_spaces && !skipped_braces)
467 // put back the space (it is better handled by check_space)
468 p.unskip_spaces(true);
472 void output_command_layout(ostream & os, Parser & p, bool outer,
473 Context & parent_context,
474 Layout const * newlayout)
476 parent_context.check_end_layout(os);
477 Context context(true, parent_context.textclass, newlayout,
478 parent_context.layout, parent_context.font);
479 if (parent_context.deeper_paragraph) {
480 // We are beginning a nested environment after a
481 // deeper paragraph inside the outer list environment.
482 // Therefore we don't need to output a "begin deeper".
483 context.need_end_deeper = true;
485 context.check_deeper(os);
486 context.check_layout(os);
487 unsigned int optargs = 0;
488 while (optargs < context.layout->optargs) {
489 eat_whitespace(p, os, context, false);
490 if (p.next_token().character() != '[')
492 p.get_token(); // eat '['
493 begin_inset(os, "OptArg\n");
494 os << "status collapsed\n\n";
495 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
497 eat_whitespace(p, os, context, false);
501 // This is the code needed to parse required arguments, but
502 // required arguments come into being only much later than the
503 // file format tex2lyx is presently outputting.
504 unsigned int reqargs = 0;
505 while (reqargs < context.layout->reqargs) {
506 eat_whitespace(p, os, context, false);
507 if (p.next_token().character() != '{')
509 p.get_token(); // eat '{'
510 begin_inset(os, "OptArg\n");
511 os << "status collapsed\n\n";
512 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
514 eat_whitespace(p, os, context, false);
518 parse_text(p, os, FLAG_ITEM, outer, context);
519 context.check_end_layout(os);
520 if (parent_context.deeper_paragraph) {
521 // We must suppress the "end deeper" because we
522 // suppressed the "begin deeper" above.
523 context.need_end_deeper = false;
525 context.check_end_deeper(os);
526 // We don't need really a new paragraph, but
527 // we must make sure that the next item gets a \begin_layout.
528 parent_context.new_paragraph(os);
533 * Output a space if necessary.
534 * This function gets called for every whitespace token.
536 * We have three cases here:
537 * 1. A space must be suppressed. Example: The lyxcode case below
538 * 2. A space may be suppressed. Example: Spaces before "\par"
539 * 3. A space must not be suppressed. Example: A space between two words
541 * We currently handle only 1. and 3 and from 2. only the case of
542 * spaces before newlines as a side effect.
544 * 2. could be used to suppress as many spaces as possible. This has two effects:
545 * - Reimporting LyX generated LaTeX files changes almost no whitespace
546 * - Superflous whitespace from non LyX generated LaTeX files is removed.
547 * The drawback is that the logic inside the function becomes
548 * complicated, and that is the reason why it is not implemented.
550 void check_space(Parser & p, ostream & os, Context & context)
552 Token const next = p.next_token();
553 Token const curr = p.curr_token();
554 // A space before a single newline and vice versa must be ignored
555 // LyX emits a newline before \end{lyxcode}.
556 // This newline must be ignored,
557 // otherwise LyX will add an additional protected space.
558 if (next.cat() == catSpace ||
559 next.cat() == catNewline ||
560 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
563 context.check_layout(os);
569 * Parse all arguments of \p command
571 void parse_arguments(string const & command,
572 vector<ArgumentType> const & template_arguments,
573 Parser & p, ostream & os, bool outer, Context & context)
575 string ert = command;
576 size_t no_arguments = template_arguments.size();
577 for (size_t i = 0; i < no_arguments; ++i) {
578 switch (template_arguments[i]) {
580 // This argument contains regular LaTeX
581 handle_ert(os, ert + '{', context);
582 eat_whitespace(p, os, context, false);
583 parse_text(p, os, FLAG_ITEM, outer, context);
587 // This argument may contain special characters
588 ert += '{' + p.verbatim_item() + '}';
591 // true because we must not eat whitespace
592 ert += p.getOpt(true);
596 handle_ert(os, ert, context);
601 * Check whether \p command is a known command. If yes,
602 * handle the command with all arguments.
603 * \return true if the command was parsed, false otherwise.
605 bool parse_command(string const & command, Parser & p, ostream & os,
606 bool outer, Context & context)
608 if (known_commands.find(command) != known_commands.end()) {
609 parse_arguments(command, known_commands[command], p, os,
617 /// Parses a minipage or parbox
618 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
619 Context & parent_context, bool use_parbox)
623 // We need to set the height to the LaTeX default of 1\\totalheight
624 // for the case when no height argument is given
625 string height_value = "1";
626 string height_unit = "in";
627 string height_special = "totalheight";
629 if (p.next_token().asInput() == "[") {
630 position = p.getArg('[', ']');
631 if (position != "t" && position != "c" && position != "b") {
633 cerr << "invalid position for minipage/parbox" << endl;
635 if (p.next_token().asInput() == "[") {
636 latex_height = p.getArg('[', ']');
637 translate_box_len(latex_height, height_value, height_unit, height_special);
639 if (p.next_token().asInput() == "[") {
640 inner_pos = p.getArg('[', ']');
641 if (inner_pos != "c" && inner_pos != "t" &&
642 inner_pos != "b" && inner_pos != "s") {
643 inner_pos = position;
644 cerr << "invalid inner_pos for minipage/parbox"
652 string const latex_width = p.verbatim_item();
653 translate_len(latex_width, width_value, width_unit);
654 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
655 // LyX can't handle length variables
660 ss << "\\begin{minipage}";
661 if (!position.empty())
662 ss << '[' << position << ']';
663 if (!latex_height.empty())
664 ss << '[' << latex_height << ']';
665 if (!inner_pos.empty())
666 ss << '[' << inner_pos << ']';
667 ss << "{" << latex_width << "}";
670 handle_ert(os, ss.str(), parent_context);
671 parent_context.new_paragraph(os);
672 parse_text_in_inset(p, os, flags, outer, parent_context);
674 handle_ert(os, "}", parent_context);
676 handle_ert(os, "\\end{minipage}", parent_context);
678 // LyX does not like empty positions, so we have
679 // to set them to the LaTeX default values here.
680 if (position.empty())
682 if (inner_pos.empty())
683 inner_pos = position;
684 parent_context.check_layout(os);
685 begin_inset(os, "Box Frameless\n");
686 os << "position \"" << position << "\"\n";
687 os << "hor_pos \"c\"\n";
688 os << "has_inner_box 1\n";
689 os << "inner_pos \"" << inner_pos << "\"\n";
690 os << "use_parbox " << use_parbox << "\n";
691 os << "width \"" << width_value << width_unit << "\"\n";
692 os << "special \"none\"\n";
693 os << "height \"" << height_value << height_unit << "\"\n";
694 os << "height_special \"" << height_special << "\"\n";
695 os << "status open\n\n";
696 parse_text_in_inset(p, os, flags, outer, parent_context);
698 #ifdef PRESERVE_LAYOUT
699 // LyX puts a % after the end of the minipage
700 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
702 //handle_comment(os, "%dummy", parent_context);
705 parent_context.new_paragraph(os);
707 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
708 //handle_comment(os, "%dummy", parent_context);
711 // We add a protected space if something real follows
712 if (p.good() && p.next_token().cat() != catComment) {
713 os << "\\InsetSpace ~\n";
721 /// parse an unknown environment
722 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
723 unsigned flags, bool outer,
724 Context & parent_context)
726 if (name == "tabbing")
727 // We need to remember that we have to handle '\=' specially
728 flags |= FLAG_TABBING;
730 // We need to translate font changes and paragraphs inside the
731 // environment to ERT if we have a non standard font.
732 // Otherwise things like
733 // \large\begin{foo}\huge bar\end{foo}
735 bool const specialfont =
736 (parent_context.font != parent_context.normalfont);
737 bool const new_layout_allowed = parent_context.new_layout_allowed;
739 parent_context.new_layout_allowed = false;
740 handle_ert(os, "\\begin{" + name + "}", parent_context);
741 parse_text_snippet(p, os, flags, outer, parent_context);
742 handle_ert(os, "\\end{" + name + "}", parent_context);
744 parent_context.new_layout_allowed = new_layout_allowed;
748 void parse_environment(Parser & p, ostream & os, bool outer,
749 string & last_env, Context & parent_context)
751 Layout const * newlayout;
752 string const name = p.getArg('{', '}');
753 const bool is_starred = suffixIs(name, '*');
754 string const unstarred_name = rtrim(name, "*");
755 active_environments.push_back(name);
757 if (is_math_env(name)) {
758 parent_context.check_layout(os);
759 begin_inset(os, "Formula ");
760 os << "\\begin{" << name << "}";
761 parse_math(p, os, FLAG_END, MATH_MODE);
762 os << "\\end{" << name << "}";
766 else if (name == "tabular" || name == "longtable") {
767 eat_whitespace(p, os, parent_context, false);
768 parent_context.check_layout(os);
769 begin_inset(os, "Tabular ");
770 handle_tabular(p, os, name == "longtable", parent_context);
775 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
776 eat_whitespace(p, os, parent_context, false);
777 parent_context.check_layout(os);
778 begin_inset(os, "Float " + unstarred_name + "\n");
779 if (p.next_token().asInput() == "[") {
780 os << "placement " << p.getArg('[', ']') << '\n';
782 os << "wide " << convert<string>(is_starred)
783 << "\nsideways false"
784 << "\nstatus open\n\n";
785 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
787 // We don't need really a new paragraph, but
788 // we must make sure that the next item gets a \begin_layout.
789 parent_context.new_paragraph(os);
793 else if (name == "minipage") {
794 eat_whitespace(p, os, parent_context, false);
795 parse_box(p, os, FLAG_END, outer, parent_context, false);
799 else if (name == "comment") {
800 eat_whitespace(p, os, parent_context, false);
801 parent_context.check_layout(os);
802 begin_inset(os, "Note Comment\n");
803 os << "status open\n";
804 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
807 skip_braces(p); // eat {} that might by set by LyX behind comments
810 else if (name == "lyxgreyedout") {
811 eat_whitespace(p, os, parent_context, false);
812 parent_context.check_layout(os);
813 begin_inset(os, "Note Greyedout\n");
814 os << "status open\n";
815 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
820 else if (name == "framed") {
821 eat_whitespace(p, os, parent_context, false);
822 parent_context.check_layout(os);
823 begin_inset(os, "Note Framed\n");
824 os << "status open\n";
825 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
830 else if (name == "shaded") {
831 eat_whitespace(p, os, parent_context, false);
832 parent_context.check_layout(os);
833 begin_inset(os, "Note Shaded\n");
834 os << "status open\n";
835 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
840 else if (!parent_context.new_layout_allowed)
841 parse_unknown_environment(p, name, os, FLAG_END, outer,
844 // Alignment and spacing settings
845 // FIXME (bug xxxx): These settings can span multiple paragraphs and
846 // therefore are totally broken!
847 // Note that \centering, raggedright, and raggedleft cannot be handled, as
848 // they are commands not environments. They are furthermore switches that
849 // can be ended by another switches, but also by commands like \footnote or
850 // \parbox. So the only safe way is to leave them untouched.
851 else if (name == "center" || name == "centering" ||
852 name == "flushleft" || name == "flushright" ||
853 name == "singlespace" || name == "onehalfspace" ||
854 name == "doublespace" || name == "spacing") {
855 eat_whitespace(p, os, parent_context, false);
856 // We must begin a new paragraph if not already done
857 if (! parent_context.atParagraphStart()) {
858 parent_context.check_end_layout(os);
859 parent_context.new_paragraph(os);
861 if (name == "flushleft")
862 parent_context.add_extra_stuff("\\align left\n");
863 else if (name == "flushright")
864 parent_context.add_extra_stuff("\\align right\n");
865 else if (name == "center" || name == "centering")
866 parent_context.add_extra_stuff("\\align center\n");
867 else if (name == "singlespace")
868 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
869 else if (name == "onehalfspace")
870 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
871 else if (name == "doublespace")
872 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
873 else if (name == "spacing")
874 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
875 parse_text(p, os, FLAG_END, outer, parent_context);
876 // Just in case the environment is empty
877 parent_context.extra_stuff.erase();
878 // We must begin a new paragraph to reset the alignment
879 parent_context.new_paragraph(os);
883 // The single '=' is meant here.
884 else if ((newlayout = findLayout(parent_context.textclass, name)) &&
885 newlayout->isEnvironment()) {
886 eat_whitespace(p, os, parent_context, false);
887 Context context(true, parent_context.textclass, newlayout,
888 parent_context.layout, parent_context.font);
889 if (parent_context.deeper_paragraph) {
890 // We are beginning a nested environment after a
891 // deeper paragraph inside the outer list environment.
892 // Therefore we don't need to output a "begin deeper".
893 context.need_end_deeper = true;
895 parent_context.check_end_layout(os);
896 if (last_env == name) {
897 // we need to output a separator since LyX would export
898 // the two environments as one otherwise (bug 5716)
899 docstring const sep = from_ascii("--Separator--");
900 TeX2LyXDocClass const & textclass(parent_context.textclass);
901 if (LYX_FORMAT >= 273 && textclass.hasLayout(sep)) {
902 Context newcontext(parent_context);
903 newcontext.layout = &(textclass[sep]);
904 newcontext.check_layout(os);
905 newcontext.check_end_layout(os);
907 parent_context.check_layout(os);
908 begin_inset(os, "Note Note\n");
909 os << "status closed\n";
910 Context newcontext(true, textclass,
911 &(textclass.defaultLayout()));
912 newcontext.check_layout(os);
913 newcontext.check_end_layout(os);
915 parent_context.check_end_layout(os);
918 switch (context.layout->latextype) {
919 case LATEX_LIST_ENVIRONMENT:
920 context.add_par_extra_stuff("\\labelwidthstring "
921 + p.verbatim_item() + '\n');
924 case LATEX_BIB_ENVIRONMENT:
925 p.verbatim_item(); // swallow next arg
931 context.check_deeper(os);
932 parse_text(p, os, FLAG_END, outer, context);
933 context.check_end_layout(os);
934 if (parent_context.deeper_paragraph) {
935 // We must suppress the "end deeper" because we
936 // suppressed the "begin deeper" above.
937 context.need_end_deeper = false;
939 context.check_end_deeper(os);
940 parent_context.new_paragraph(os);
944 else if (name == "appendix") {
945 // This is no good latex style, but it works and is used in some documents...
946 eat_whitespace(p, os, parent_context, false);
947 parent_context.check_end_layout(os);
948 Context context(true, parent_context.textclass, parent_context.layout,
949 parent_context.layout, parent_context.font);
950 context.check_layout(os);
951 os << "\\start_of_appendix\n";
952 parse_text(p, os, FLAG_END, outer, context);
953 context.check_end_layout(os);
957 else if (known_environments.find(name) != known_environments.end()) {
958 vector<ArgumentType> arguments = known_environments[name];
959 // The last "argument" denotes wether we may translate the
960 // environment contents to LyX
961 // The default required if no argument is given makes us
962 // compatible with the reLyXre environment.
963 ArgumentType contents = arguments.empty() ?
966 if (!arguments.empty())
967 arguments.pop_back();
968 // See comment in parse_unknown_environment()
969 bool const specialfont =
970 (parent_context.font != parent_context.normalfont);
971 bool const new_layout_allowed =
972 parent_context.new_layout_allowed;
974 parent_context.new_layout_allowed = false;
975 parse_arguments("\\begin{" + name + "}", arguments, p, os,
976 outer, parent_context);
977 if (contents == verbatim)
978 handle_ert(os, p.verbatimEnvironment(name),
981 parse_text_snippet(p, os, FLAG_END, outer,
983 handle_ert(os, "\\end{" + name + "}", parent_context);
985 parent_context.new_layout_allowed = new_layout_allowed;
989 parse_unknown_environment(p, name, os, FLAG_END, outer,
993 active_environments.pop_back();
997 /// parses a comment and outputs it to \p os.
998 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1000 LASSERT(t.cat() == catComment, return);
1001 if (!t.cs().empty()) {
1002 context.check_layout(os);
1003 handle_comment(os, '%' + t.cs(), context);
1004 if (p.next_token().cat() == catNewline) {
1005 // A newline after a comment line starts a new
1007 if (context.new_layout_allowed) {
1008 if(!context.atParagraphStart())
1009 // Only start a new paragraph if not already
1010 // done (we might get called recursively)
1011 context.new_paragraph(os);
1013 handle_ert(os, "\n", context);
1014 eat_whitespace(p, os, context, true);
1017 // "%\n" combination
1024 * Reads spaces and comments until the first non-space, non-comment token.
1025 * New paragraphs (double newlines or \\par) are handled like simple spaces
1026 * if \p eatParagraph is true.
1027 * Spaces are skipped, but comments are written to \p os.
1029 void eat_whitespace(Parser & p, ostream & os, Context & context,
1033 Token const & t = p.get_token();
1034 if (t.cat() == catComment)
1035 parse_comment(p, os, t, context);
1036 else if ((! eatParagraph && p.isParagraph()) ||
1037 (t.cat() != catSpace && t.cat() != catNewline)) {
1046 * Set a font attribute, parse text and reset the font attribute.
1047 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1048 * \param currentvalue Current value of the attribute. Is set to the new
1049 * value during parsing.
1050 * \param newvalue New value of the attribute
1052 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1053 Context & context, string const & attribute,
1054 string & currentvalue, string const & newvalue)
1056 context.check_layout(os);
1057 string const oldvalue = currentvalue;
1058 currentvalue = newvalue;
1059 os << '\n' << attribute << ' ' << newvalue << "\n";
1060 parse_text_snippet(p, os, flags, outer, context);
1061 context.check_layout(os);
1062 os << '\n' << attribute << ' ' << oldvalue << "\n";
1063 currentvalue = oldvalue;
1067 /// get the arguments of a natbib or jurabib citation command
1068 void get_cite_arguments(Parser & p, bool natbibOrder,
1069 string & before, string & after)
1071 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1073 // text before the citation
1075 // text after the citation
1076 after = p.getFullOpt();
1078 if (!after.empty()) {
1079 before = p.getFullOpt();
1080 if (natbibOrder && !before.empty())
1081 swap(before, after);
1086 /// Convert filenames with TeX macros and/or quotes to something LyX
1088 string const normalize_filename(string const & name)
1090 Parser p(trim(name, "\""));
1093 Token const & t = p.get_token();
1094 if (t.cat() != catEscape)
1096 else if (t.cs() == "lyxdot") {
1097 // This is used by LyX for simple dots in relative
1101 } else if (t.cs() == "space") {
1111 /// Convert \p name from TeX convention (relative to master file) to LyX
1112 /// convention (relative to .lyx file) if it is relative
1113 void fix_relative_filename(string & name)
1115 if (FileName::isAbsolute(name))
1118 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1119 from_utf8(getParentFilePath())));
1123 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1124 void parse_noweb(Parser & p, ostream & os, Context & context)
1126 // assemble the rest of the keyword
1130 Token const & t = p.get_token();
1131 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1134 scrap = (p.good() && p.next_token().asInput() == "=");
1136 name += p.get_token().asInput();
1139 name += t.asInput();
1142 if (!scrap || !context.new_layout_allowed ||
1143 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1144 cerr << "Warning: Could not interpret '" << name
1145 << "'. Ignoring it." << endl;
1149 // We use new_paragraph instead of check_end_layout because the stuff
1150 // following the noweb chunk needs to start with a \begin_layout.
1151 // This may create a new paragraph even if there was none in the
1152 // noweb file, but the alternative is an invalid LyX file. Since
1153 // noweb code chunks are implemented with a layout style in LyX they
1154 // always must be in an own paragraph.
1155 context.new_paragraph(os);
1156 Context newcontext(true, context.textclass,
1157 &context.textclass[from_ascii("Scrap")]);
1158 newcontext.check_layout(os);
1161 Token const & t = p.get_token();
1162 // We abuse the parser a bit, because this is no TeX syntax
1164 if (t.cat() == catEscape)
1165 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1167 os << subst(t.asInput(), "\n", "\n\\newline\n");
1168 // The scrap chunk is ended by an @ at the beginning of a line.
1169 // After the @ the line may contain a comment and/or
1170 // whitespace, but nothing else.
1171 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1172 (p.next_token().cat() == catSpace ||
1173 p.next_token().cat() == catNewline ||
1174 p.next_token().cat() == catComment)) {
1175 while (p.good() && p.next_token().cat() == catSpace)
1176 os << p.get_token().asInput();
1177 if (p.next_token().cat() == catComment)
1178 // The comment includes a final '\n'
1179 os << p.get_token().asInput();
1181 if (p.next_token().cat() == catNewline)
1188 newcontext.check_end_layout(os);
1191 } // anonymous namespace
1194 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1197 Layout const * newlayout = 0;
1198 // Store the latest bibliographystyle (needed for bibtex inset)
1199 string bibliographystyle;
1200 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1201 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1204 Token const & t = p.get_token();
1207 cerr << "t: " << t << " flags: " << flags << "\n";
1210 if (flags & FLAG_ITEM) {
1211 if (t.cat() == catSpace)
1214 flags &= ~FLAG_ITEM;
1215 if (t.cat() == catBegin) {
1216 // skip the brace and collect everything to the next matching
1218 flags |= FLAG_BRACE_LAST;
1222 // handle only this single token, leave the loop if done
1223 flags |= FLAG_LEAVE;
1226 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1228 if (t.character() == '}' && (flags & FLAG_BRACE_LAST))
1231 // If there is anything between \end{env} and \begin{env} we
1232 // don't need to output a separator.
1233 if (t.cat() != catSpace && t.cat() != catNewline &&
1234 t.asInput() != "\\begin")
1240 if (t.cat() == catMath) {
1241 // we are inside some text mode thingy, so opening new math is allowed
1242 context.check_layout(os);
1243 begin_inset(os, "Formula ");
1244 Token const & n = p.get_token();
1245 if (n.cat() == catMath && outer) {
1246 // TeX's $$...$$ syntax for displayed math
1248 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1250 p.get_token(); // skip the second '$' token
1252 // simple $...$ stuff
1255 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1261 else if (t.cat() == catSuper || t.cat() == catSub)
1262 cerr << "catcode " << t << " illegal in text mode\n";
1264 // Basic support for english quotes. This should be
1265 // extended to other quotes, but is not so easy (a
1266 // left english quote is the same as a right german
1268 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1269 context.check_layout(os);
1270 begin_inset(os, "Quotes ");
1276 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1277 context.check_layout(os);
1278 begin_inset(os, "Quotes ");
1285 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1286 context.check_layout(os);
1287 begin_inset(os, "Quotes ");
1294 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1295 context.check_layout(os);
1296 begin_inset(os, "Quotes ");
1303 else if (t.asInput() == "<"
1304 && p.next_token().asInput() == "<" && noweb_mode) {
1306 parse_noweb(p, os, context);
1309 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1310 check_space(p, os, context);
1312 else if (t.character() == '[' && noweb_mode &&
1313 p.next_token().character() == '[') {
1314 // These can contain underscores
1316 string const s = p.getFullOpt() + ']';
1317 if (p.next_token().character() == ']')
1320 cerr << "Warning: Inserting missing ']' in '"
1321 << s << "'." << endl;
1322 handle_ert(os, s, context);
1325 else if (t.cat() == catLetter ||
1326 t.cat() == catOther ||
1327 t.cat() == catAlign ||
1328 t.cat() == catParameter) {
1329 // This translates "&" to "\\&" which may be wrong...
1330 context.check_layout(os);
1334 else if (p.isParagraph()) {
1335 if (context.new_layout_allowed)
1336 context.new_paragraph(os);
1338 handle_ert(os, "\\par ", context);
1339 eat_whitespace(p, os, context, true);
1342 else if (t.cat() == catActive) {
1343 context.check_layout(os);
1344 if (t.character() == '~') {
1345 if (context.layout->free_spacing)
1348 os << "\\InsetSpace ~\n";
1353 else if (t.cat() == catBegin &&
1354 p.next_token().cat() == catEnd) {
1356 Token const prev = p.prev_token();
1358 if (p.next_token().character() == '`' ||
1359 (prev.character() == '-' &&
1360 p.next_token().character() == '-'))
1361 ; // ignore it in {}`` or -{}-
1363 handle_ert(os, "{}", context);
1367 else if (t.cat() == catBegin) {
1368 context.check_layout(os);
1369 // special handling of font attribute changes
1370 Token const prev = p.prev_token();
1371 Token const next = p.next_token();
1372 TeXFont const oldFont = context.font;
1373 if (next.character() == '[' ||
1374 next.character() == ']' ||
1375 next.character() == '*') {
1377 if (p.next_token().cat() == catEnd) {
1382 handle_ert(os, "{", context);
1383 parse_text_snippet(p, os,
1386 handle_ert(os, "}", context);
1388 } else if (! context.new_layout_allowed) {
1389 handle_ert(os, "{", context);
1390 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1392 handle_ert(os, "}", context);
1393 } else if (is_known(next.cs(), known_sizes)) {
1394 // next will change the size, so we must
1396 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1398 if (!context.atParagraphStart())
1400 << context.font.size << "\n";
1401 } else if (is_known(next.cs(), known_font_families)) {
1402 // next will change the font family, so we
1403 // must reset it here
1404 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1406 if (!context.atParagraphStart())
1408 << context.font.family << "\n";
1409 } else if (is_known(next.cs(), known_font_series)) {
1410 // next will change the font series, so we
1411 // must reset it here
1412 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1414 if (!context.atParagraphStart())
1416 << context.font.series << "\n";
1417 } else if (is_known(next.cs(), known_font_shapes)) {
1418 // next will change the font shape, so we
1419 // must reset it here
1420 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1422 if (!context.atParagraphStart())
1424 << context.font.shape << "\n";
1425 } else if (is_known(next.cs(), known_old_font_families) ||
1426 is_known(next.cs(), known_old_font_series) ||
1427 is_known(next.cs(), known_old_font_shapes)) {
1428 // next will change the font family, series
1429 // and shape, so we must reset it here
1430 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1432 if (!context.atParagraphStart())
1434 << context.font.family
1436 << context.font.series
1438 << context.font.shape << "\n";
1440 handle_ert(os, "{", context);
1441 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1443 handle_ert(os, "}", context);
1447 else if (t.cat() == catEnd) {
1448 if (flags & FLAG_BRACE_LAST) {
1451 cerr << "stray '}' in text\n";
1452 handle_ert(os, "}", context);
1455 else if (t.cat() == catComment)
1456 parse_comment(p, os, t, context);
1459 // control sequences
1462 else if (t.cs() == "(") {
1463 context.check_layout(os);
1464 begin_inset(os, "Formula");
1466 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1471 else if (t.cs() == "[") {
1472 context.check_layout(os);
1473 begin_inset(os, "Formula");
1475 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1480 else if (t.cs() == "begin")
1481 parse_environment(p, os, outer, last_env, context);
1483 else if (t.cs() == "end") {
1484 if (flags & FLAG_END) {
1485 // eat environment name
1486 string const name = p.getArg('{', '}');
1487 if (name != active_environment())
1488 cerr << "\\end{" + name + "} does not match \\begin{"
1489 + active_environment() + "}\n";
1492 p.error("found 'end' unexpectedly");
1495 else if (t.cs() == "item") {
1498 bool optarg = false;
1499 if (p.next_token().character() == '[') {
1500 p.get_token(); // eat '['
1501 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1506 context.check_layout(os);
1507 if (context.has_item) {
1508 // An item in an unknown list-like environment
1509 // FIXME: Do this in check_layout()!
1510 context.has_item = false;
1512 handle_ert(os, "\\item", context);
1514 handle_ert(os, "\\item ", context);
1517 if (context.layout->labeltype != LABEL_MANUAL) {
1518 // LyX does not support \item[\mybullet]
1519 // in itemize environments
1520 handle_ert(os, "[", context);
1522 handle_ert(os, "]", context);
1523 } else if (!s.empty()) {
1524 // The space is needed to separate the
1525 // item from the rest of the sentence.
1527 eat_whitespace(p, os, context, false);
1532 else if (t.cs() == "bibitem") {
1534 context.check_layout(os);
1535 begin_command_inset(os, "bibitem", "bibitem");
1536 os << "label \"" << p.getOptContent() << "\"\n";
1537 os << "key \"" << p.verbatim_item() << "\"\n";
1541 else if (t.cs() == "def") {
1542 context.check_layout(os);
1543 eat_whitespace(p, os, context, false);
1544 string name = p.get_token().cs();
1545 eat_whitespace(p, os, context, false);
1551 while (p.next_token().cat() != catBegin) {
1552 if (p.next_token().cat() == catParameter) {
1557 // followed by number?
1558 if (p.next_token().cat() == catOther) {
1559 char c = p.getChar();
1561 // number = current arity + 1?
1562 if (c == arity + '0' + 1)
1567 paramtext += p.get_token().cs();
1569 paramtext += p.get_token().cs();
1574 // only output simple (i.e. compatible) macro as FormulaMacros
1575 string ert = "\\def\\" + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1577 context.check_layout(os);
1578 begin_inset(os, "FormulaMacro");
1582 handle_ert(os, ert, context);
1585 else if (t.cs() == "noindent") {
1587 context.add_par_extra_stuff("\\noindent\n");
1590 else if (t.cs() == "appendix") {
1591 context.add_par_extra_stuff("\\start_of_appendix\n");
1592 // We need to start a new paragraph. Otherwise the
1593 // appendix in 'bla\appendix\chapter{' would start
1595 context.new_paragraph(os);
1596 // We need to make sure that the paragraph is
1597 // generated even if it is empty. Otherwise the
1598 // appendix in '\par\appendix\par\chapter{' would
1600 context.check_layout(os);
1601 // FIXME: This is a hack to prevent paragraph
1602 // deletion if it is empty. Handle this better!
1604 "%dummy comment inserted by tex2lyx to "
1605 "ensure that this paragraph is not empty",
1607 // Both measures above may generate an additional
1608 // empty paragraph, but that does not hurt, because
1609 // whitespace does not matter here.
1610 eat_whitespace(p, os, context, true);
1613 // Starred section headings
1614 // Must attempt to parse "Section*" before "Section".
1615 else if ((p.next_token().asInput() == "*") &&
1616 context.new_layout_allowed &&
1617 (newlayout = findLayout(context.textclass, t.cs() + '*')) &&
1618 newlayout->isCommand()) {
1619 TeXFont const oldFont = context.font;
1620 // save the current font size
1621 string const size = oldFont.size;
1622 // reset the font size to default, because the
1623 // font size switches don't affect section
1624 // headings and the like
1625 context.font.size = known_coded_sizes[0];
1626 output_font_change(os, oldFont, context.font);
1629 output_command_layout(os, p, outer, context, newlayout);
1630 // set the font size to the original value
1631 context.font.size = size;
1632 output_font_change(os, oldFont, context.font);
1636 // Section headings and the like
1637 else if (context.new_layout_allowed &&
1638 (newlayout = findLayout(context.textclass, t.cs())) &&
1639 newlayout->isCommand()) {
1640 TeXFont const oldFont = context.font;
1641 // save the current font size
1642 string const size = oldFont.size;
1643 // reset the font size to default, because the font size switches don't
1644 // affect section headings and the like
1645 context.font.size = known_coded_sizes[0];
1646 output_font_change(os, oldFont, context.font);
1648 output_command_layout(os, p, outer, context, newlayout);
1649 // set the font size to the original value
1650 context.font.size = size;
1651 output_font_change(os, oldFont, context.font);
1655 else if (t.cs() == "caption") {
1656 // FIXME: this should get some cleanup. All
1657 // the \begin_layout:s are output by the
1660 context.check_layout(os);
1662 begin_inset(os, "Caption\n\n");
1663 os << "\\begin_layout "
1664 << to_utf8(context.textclass.defaultLayout().name())
1666 if (p.next_token().character() == '[') {
1667 p.get_token(); // eat '['
1668 begin_inset(os, "OptArg\n");
1669 os << "status collapsed\n";
1670 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1672 eat_whitespace(p, os, context, false);
1674 parse_text(p, os, FLAG_ITEM, outer, context);
1675 context.check_end_layout(os);
1676 // We don't need really a new paragraph, but
1677 // we must make sure that the next item gets a \begin_layout.
1678 context.new_paragraph(os);
1681 os << "\\end_layout\n";
1684 else if (t.cs() == "includegraphics") {
1685 bool const clip = p.next_token().asInput() == "*";
1688 string const arg = p.getArg('[', ']');
1689 map<string, string> opts;
1690 vector<string> keys;
1691 split_map(arg, opts, keys);
1693 opts["clip"] = string();
1694 string name = normalize_filename(p.verbatim_item());
1696 string const path = getMasterFilePath();
1697 // We want to preserve relative / absolute filenames,
1698 // therefore path is only used for testing
1699 if (!makeAbsPath(name, path).exists()) {
1700 // The file extension is probably missing.
1701 // Now try to find it out.
1702 string const dvips_name =
1703 find_file(name, path,
1704 known_dvips_graphics_formats);
1705 string const pdftex_name =
1706 find_file(name, path,
1707 known_pdftex_graphics_formats);
1708 if (!dvips_name.empty()) {
1709 if (!pdftex_name.empty()) {
1710 cerr << "This file contains the "
1712 "\"\\includegraphics{"
1714 "However, files\n\""
1715 << dvips_name << "\" and\n\""
1716 << pdftex_name << "\"\n"
1717 "both exist, so I had to make a "
1718 "choice and took the first one.\n"
1719 "Please move the unwanted one "
1720 "someplace else and try again\n"
1721 "if my choice was wrong."
1725 } else if (!pdftex_name.empty())
1729 if (makeAbsPath(name, path).exists())
1730 fix_relative_filename(name);
1732 cerr << "Warning: Could not find graphics file '"
1733 << name << "'." << endl;
1735 context.check_layout(os);
1736 begin_inset(os, "Graphics ");
1737 os << "\n\tfilename " << name << '\n';
1738 if (opts.find("width") != opts.end())
1740 << translate_len(opts["width"]) << '\n';
1741 if (opts.find("height") != opts.end())
1743 << translate_len(opts["height"]) << '\n';
1744 if (opts.find("scale") != opts.end()) {
1745 istringstream iss(opts["scale"]);
1749 os << "\tscale " << val << '\n';
1751 if (opts.find("angle") != opts.end()) {
1752 os << "\trotateAngle "
1753 << opts["angle"] << '\n';
1754 vector<string>::const_iterator a =
1755 find(keys.begin(), keys.end(), "angle");
1756 vector<string>::const_iterator s =
1757 find(keys.begin(), keys.end(), "width");
1758 if (s == keys.end())
1759 s = find(keys.begin(), keys.end(), "height");
1760 if (s == keys.end())
1761 s = find(keys.begin(), keys.end(), "scale");
1762 if (s != keys.end() && distance(s, a) > 0)
1763 os << "\tscaleBeforeRotation\n";
1765 if (opts.find("origin") != opts.end()) {
1767 string const opt = opts["origin"];
1768 if (opt.find('l') != string::npos) ss << "left";
1769 if (opt.find('r') != string::npos) ss << "right";
1770 if (opt.find('c') != string::npos) ss << "center";
1771 if (opt.find('t') != string::npos) ss << "Top";
1772 if (opt.find('b') != string::npos) ss << "Bottom";
1773 if (opt.find('B') != string::npos) ss << "Baseline";
1774 if (!ss.str().empty())
1775 os << "\trotateOrigin " << ss.str() << '\n';
1777 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1779 if (opts.find("keepaspectratio") != opts.end())
1780 os << "\tkeepAspectRatio\n";
1781 if (opts.find("clip") != opts.end())
1783 if (opts.find("draft") != opts.end())
1785 if (opts.find("bb") != opts.end())
1786 os << "\tBoundingBox "
1787 << opts["bb"] << '\n';
1788 int numberOfbbOptions = 0;
1789 if (opts.find("bbllx") != opts.end())
1790 numberOfbbOptions++;
1791 if (opts.find("bblly") != opts.end())
1792 numberOfbbOptions++;
1793 if (opts.find("bburx") != opts.end())
1794 numberOfbbOptions++;
1795 if (opts.find("bbury") != opts.end())
1796 numberOfbbOptions++;
1797 if (numberOfbbOptions == 4)
1798 os << "\tBoundingBox "
1799 << opts["bbllx"] << " " << opts["bblly"] << " "
1800 << opts["bburx"] << " " << opts["bbury"] << '\n';
1801 else if (numberOfbbOptions > 0)
1802 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1803 numberOfbbOptions = 0;
1804 if (opts.find("natwidth") != opts.end())
1805 numberOfbbOptions++;
1806 if (opts.find("natheight") != opts.end())
1807 numberOfbbOptions++;
1808 if (numberOfbbOptions == 2)
1809 os << "\tBoundingBox 0bp 0bp "
1810 << opts["natwidth"] << " " << opts["natheight"] << '\n';
1811 else if (numberOfbbOptions > 0)
1812 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1813 ostringstream special;
1814 if (opts.find("hiresbb") != opts.end())
1815 special << "hiresbb,";
1816 if (opts.find("trim") != opts.end())
1818 if (opts.find("viewport") != opts.end())
1819 special << "viewport=" << opts["viewport"] << ',';
1820 if (opts.find("totalheight") != opts.end())
1821 special << "totalheight=" << opts["totalheight"] << ',';
1822 if (opts.find("type") != opts.end())
1823 special << "type=" << opts["type"] << ',';
1824 if (opts.find("ext") != opts.end())
1825 special << "ext=" << opts["ext"] << ',';
1826 if (opts.find("read") != opts.end())
1827 special << "read=" << opts["read"] << ',';
1828 if (opts.find("command") != opts.end())
1829 special << "command=" << opts["command"] << ',';
1830 string s_special = special.str();
1831 if (!s_special.empty()) {
1832 // We had special arguments. Remove the trailing ','.
1833 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1835 // TODO: Handle the unknown settings better.
1836 // Warn about invalid options.
1837 // Check whether some option was given twice.
1841 else if (t.cs() == "footnote" ||
1842 (t.cs() == "thanks" && context.layout->intitle)) {
1844 context.check_layout(os);
1845 begin_inset(os, "Foot\n");
1846 os << "status collapsed\n\n";
1847 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1851 else if (t.cs() == "marginpar") {
1853 context.check_layout(os);
1854 begin_inset(os, "Marginal\n");
1855 os << "status collapsed\n\n";
1856 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1860 else if (t.cs() == "ensuremath") {
1862 context.check_layout(os);
1863 string const s = p.verbatim_item();
1864 //FIXME: this never triggers in UTF8
1865 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
1868 handle_ert(os, "\\ensuremath{" + s + "}",
1872 else if (t.cs() == "hfill") {
1873 context.check_layout(os);
1874 os << "\n\\hfill\n";
1879 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1880 // FIXME: Somehow prevent title layouts if
1881 // "maketitle" was not found
1883 skip_spaces_braces(p);
1886 else if (t.cs() == "tableofcontents") {
1887 context.check_layout(os);
1888 begin_command_inset(os, "toc", "tableofcontents");
1890 skip_spaces_braces(p);
1893 else if (t.cs() == "listoffigures") {
1894 context.check_layout(os);
1895 begin_inset(os, "FloatList figure\n");
1897 skip_spaces_braces(p);
1900 else if (t.cs() == "listoftables") {
1901 context.check_layout(os);
1902 begin_inset(os, "FloatList table\n");
1904 skip_spaces_braces(p);
1907 else if (t.cs() == "listof") {
1908 p.skip_spaces(true);
1909 string const name = p.get_token().cs();
1910 if (context.textclass.floats().typeExist(name)) {
1911 context.check_layout(os);
1912 begin_inset(os, "FloatList ");
1915 p.get_token(); // swallow second arg
1917 handle_ert(os, "\\listof{" + name + "}", context);
1920 else if (t.cs() == "textrm")
1921 parse_text_attributes(p, os, FLAG_ITEM, outer,
1922 context, "\\family",
1923 context.font.family, "roman");
1925 else if (t.cs() == "textsf")
1926 parse_text_attributes(p, os, FLAG_ITEM, outer,
1927 context, "\\family",
1928 context.font.family, "sans");
1930 else if (t.cs() == "texttt")
1931 parse_text_attributes(p, os, FLAG_ITEM, outer,
1932 context, "\\family",
1933 context.font.family, "typewriter");
1935 else if (t.cs() == "textmd")
1936 parse_text_attributes(p, os, FLAG_ITEM, outer,
1937 context, "\\series",
1938 context.font.series, "medium");
1940 else if (t.cs() == "textbf")
1941 parse_text_attributes(p, os, FLAG_ITEM, outer,
1942 context, "\\series",
1943 context.font.series, "bold");
1945 else if (t.cs() == "textup")
1946 parse_text_attributes(p, os, FLAG_ITEM, outer,
1948 context.font.shape, "up");
1950 else if (t.cs() == "textit")
1951 parse_text_attributes(p, os, FLAG_ITEM, outer,
1953 context.font.shape, "italic");
1955 else if (t.cs() == "textsl")
1956 parse_text_attributes(p, os, FLAG_ITEM, outer,
1958 context.font.shape, "slanted");
1960 else if (t.cs() == "textsc")
1961 parse_text_attributes(p, os, FLAG_ITEM, outer,
1963 context.font.shape, "smallcaps");
1965 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1966 context.check_layout(os);
1967 TeXFont oldFont = context.font;
1968 context.font.init();
1969 context.font.size = oldFont.size;
1970 os << "\n\\family " << context.font.family << "\n";
1971 os << "\n\\series " << context.font.series << "\n";
1972 os << "\n\\shape " << context.font.shape << "\n";
1973 if (t.cs() == "textnormal") {
1974 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1975 output_font_change(os, context.font, oldFont);
1976 context.font = oldFont;
1978 eat_whitespace(p, os, context, false);
1981 else if (t.cs() == "textcolor") {
1982 // scheme is \textcolor{color name}{text}
1983 string const color = p.verbatim_item();
1984 // we only support the predefined colors of the color package
1985 if (color == "black" || color == "blue" || color == "cyan"
1986 || color == "green" || color == "magenta" || color == "red"
1987 || color == "white" || color == "yellow") {
1988 context.check_layout(os);
1989 os << "\n\\color " << color << "\n";
1990 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1991 context.check_layout(os);
1992 os << "\n\\color inherit\n";
1994 // for custom defined colors
1995 handle_ert(os, t.asInput() + "{" + color + "}", context);
1998 else if (t.cs() == "underbar") {
1999 // Do NOT handle \underline.
2000 // \underbar cuts through y, g, q, p etc.,
2001 // \underline does not.
2002 context.check_layout(os);
2003 os << "\n\\bar under\n";
2004 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2005 context.check_layout(os);
2006 os << "\n\\bar default\n";
2009 else if (t.cs() == "emph" || t.cs() == "noun") {
2010 context.check_layout(os);
2011 os << "\n\\" << t.cs() << " on\n";
2012 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2013 context.check_layout(os);
2014 os << "\n\\" << t.cs() << " default\n";
2017 else if (t.cs() == "lyxline") {
2018 context.check_layout(os);
2022 else if (is_known(t.cs(), known_ref_commands)) {
2023 context.check_layout(os);
2024 begin_command_inset(os, "ref", t.cs());
2025 // LyX cannot handle newlines in a latex command
2026 // FIXME: Move the substitution into parser::getOpt()?
2027 os << subst(p.getOpt(), "\n", " ");
2028 os << "reference " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2032 else if (use_natbib &&
2033 is_known(t.cs(), known_natbib_commands) &&
2034 ((t.cs() != "citefullauthor" &&
2035 t.cs() != "citeyear" &&
2036 t.cs() != "citeyearpar") ||
2037 p.next_token().asInput() != "*")) {
2038 context.check_layout(os);
2039 string command = t.cs();
2040 if (p.next_token().asInput() == "*") {
2044 if (command == "citefullauthor")
2045 // alternative name for "\\citeauthor*"
2046 command = "citeauthor*";
2048 // text before the citation
2050 // text after the citation
2052 get_cite_arguments(p, true, before, after);
2054 if (command == "cite") {
2055 // \cite without optional argument means
2056 // \citet, \cite with at least one optional
2057 // argument means \citep.
2058 if (before.empty() && after.empty())
2063 if (before.empty() && after == "[]")
2064 // avoid \citet[]{a}
2066 else if (before == "[]" && after == "[]") {
2067 // avoid \citet[][]{a}
2071 // remove the brackets around after and before
2072 if (!after.empty()) {
2074 after.erase(after.length() - 1, 1);
2075 // LyX cannot handle newlines in the parameter
2076 after = subst(after, "\n", " ");
2078 if (!before.empty()) {
2080 before.erase(before.length() - 1, 1);
2081 // LyX cannot handle newlines in the parameter
2082 before = subst(before, "\n", " ");
2084 begin_command_inset(os, "citation", command);
2085 os << "after " << '"' << after << '"' << "\n";
2086 os << "before " << '"' << before << '"' << "\n";
2087 os << "key " << '"' << p.verbatim_item() << '"' << "\n";
2091 else if (use_jurabib &&
2092 is_known(t.cs(), known_jurabib_commands) &&
2093 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
2094 context.check_layout(os);
2095 string command = t.cs();
2096 if (p.next_token().asInput() == "*") {
2100 char argumentOrder = '\0';
2101 vector<string> const & options = used_packages["jurabib"];
2102 if (find(options.begin(), options.end(),
2103 "natbiborder") != options.end())
2104 argumentOrder = 'n';
2105 else if (find(options.begin(), options.end(),
2106 "jurabiborder") != options.end())
2107 argumentOrder = 'j';
2109 // text before the citation
2111 // text after the citation
2113 get_cite_arguments(p, argumentOrder != 'j', before, after);
2115 string const citation = p.verbatim_item();
2116 if (!before.empty() && argumentOrder == '\0') {
2117 cerr << "Warning: Assuming argument order "
2118 "of jurabib version 0.6 for\n'"
2119 << command << before << after << '{'
2120 << citation << "}'.\n"
2121 "Add 'jurabiborder' to the jurabib "
2122 "package options if you used an\n"
2123 "earlier jurabib version." << endl;
2125 if (!after.empty()) {
2127 after.erase(after.length() - 1, 1);
2129 if (!before.empty()) {
2131 before.erase(before.length() - 1, 1);
2133 begin_command_inset(os, "citation", command);
2134 os << "after " << '"' << after << '"' << "\n";
2135 os << "before " << '"' << before << '"' << "\n";
2136 os << "key " << '"' << citation << '"' << "\n";
2140 else if (t.cs() == "cite") {
2141 context.check_layout(os);
2142 // LyX cannot handle newlines in a latex command
2143 string after = subst(p.getOptContent(), "\n", " ");
2144 begin_command_inset(os, "citation", "cite");
2145 os << "after " << '"' << after << '"' << "\n";
2146 os << "key " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2150 else if (t.cs() == "index") {
2151 context.check_layout(os);
2152 begin_inset(os, "Index\n");
2153 os << "status collapsed\n";
2154 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2158 else if (t.cs() == "nomenclature") {
2159 context.check_layout(os);
2160 begin_command_inset(os, "nomenclature", "nomenclature");
2161 // LyX cannot handle newlines in a latex command
2162 string prefix = subst(p.getOptContent(), "\n", " ");
2163 if (!prefix.empty())
2164 os << "prefix " << '"' << prefix << '"' << "\n";
2165 os << "symbol " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2166 os << "description " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2170 else if (t.cs() == "label") {
2171 context.check_layout(os);
2172 begin_command_inset(os, "label", "label");
2173 // LyX cannot handle newlines in a latex command
2174 os << "name " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2178 else if (t.cs() == "printindex") {
2179 context.check_layout(os);
2180 begin_command_inset(os, "index_print", "printindex");
2182 skip_spaces_braces(p);
2185 else if (t.cs() == "printnomenclature") {
2186 context.check_layout(os);
2187 begin_command_inset(os, "nomencl_print", "printnomenclature");
2189 skip_spaces_braces(p);
2192 else if (t.cs() == "url") {
2193 context.check_layout(os);
2194 begin_inset(os, "Flex URL\n");
2195 os << "status collapsed\n";
2196 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2200 else if (LYX_FORMAT >= 408 &&
2201 (t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
2202 context.check_layout(os);
2203 begin_inset(os, "script ");
2204 os << t.cs().substr(4) << '\n';
2205 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2209 else if (is_known(t.cs(), known_quotes)) {
2210 char const * const * where = is_known(t.cs(), known_quotes);
2211 context.check_layout(os);
2212 begin_inset(os, "Quotes ");
2213 os << known_coded_quotes[where - known_quotes];
2215 // LyX adds {} after the quote, so we have to eat
2216 // spaces here if there are any before a possible
2218 eat_whitespace(p, os, context, false);
2222 else if (is_known(t.cs(), known_sizes) &&
2223 context.new_layout_allowed) {
2224 char const * const * where = is_known(t.cs(), known_sizes);
2225 context.check_layout(os);
2226 TeXFont const oldFont = context.font;
2227 // the font size index differs by 1, because the known_coded_sizes
2228 // has additionally a "default" entry
2229 context.font.size = known_coded_sizes[where - known_sizes + 1];
2230 output_font_change(os, oldFont, context.font);
2231 eat_whitespace(p, os, context, false);
2234 else if (is_known(t.cs(), known_font_families) &&
2235 context.new_layout_allowed) {
2236 char const * const * where =
2237 is_known(t.cs(), known_font_families);
2238 context.check_layout(os);
2239 TeXFont const oldFont = context.font;
2240 context.font.family =
2241 known_coded_font_families[where - known_font_families];
2242 output_font_change(os, oldFont, context.font);
2243 eat_whitespace(p, os, context, false);
2246 else if (is_known(t.cs(), known_font_series) &&
2247 context.new_layout_allowed) {
2248 char const * const * where =
2249 is_known(t.cs(), known_font_series);
2250 context.check_layout(os);
2251 TeXFont const oldFont = context.font;
2252 context.font.series =
2253 known_coded_font_series[where - known_font_series];
2254 output_font_change(os, oldFont, context.font);
2255 eat_whitespace(p, os, context, false);
2258 else if (is_known(t.cs(), known_font_shapes) &&
2259 context.new_layout_allowed) {
2260 char const * const * where =
2261 is_known(t.cs(), known_font_shapes);
2262 context.check_layout(os);
2263 TeXFont const oldFont = context.font;
2264 context.font.shape =
2265 known_coded_font_shapes[where - known_font_shapes];
2266 output_font_change(os, oldFont, context.font);
2267 eat_whitespace(p, os, context, false);
2269 else if (is_known(t.cs(), known_old_font_families) &&
2270 context.new_layout_allowed) {
2271 char const * const * where =
2272 is_known(t.cs(), known_old_font_families);
2273 context.check_layout(os);
2274 TeXFont const oldFont = context.font;
2275 context.font.init();
2276 context.font.size = oldFont.size;
2277 context.font.family =
2278 known_coded_font_families[where - known_old_font_families];
2279 output_font_change(os, oldFont, context.font);
2280 eat_whitespace(p, os, context, false);
2283 else if (is_known(t.cs(), known_old_font_series) &&
2284 context.new_layout_allowed) {
2285 char const * const * where =
2286 is_known(t.cs(), known_old_font_series);
2287 context.check_layout(os);
2288 TeXFont const oldFont = context.font;
2289 context.font.init();
2290 context.font.size = oldFont.size;
2291 context.font.series =
2292 known_coded_font_series[where - known_old_font_series];
2293 output_font_change(os, oldFont, context.font);
2294 eat_whitespace(p, os, context, false);
2297 else if (is_known(t.cs(), known_old_font_shapes) &&
2298 context.new_layout_allowed) {
2299 char const * const * where =
2300 is_known(t.cs(), known_old_font_shapes);
2301 context.check_layout(os);
2302 TeXFont const oldFont = context.font;
2303 context.font.init();
2304 context.font.size = oldFont.size;
2305 context.font.shape =
2306 known_coded_font_shapes[where - known_old_font_shapes];
2307 output_font_change(os, oldFont, context.font);
2308 eat_whitespace(p, os, context, false);
2311 else if (t.cs() == "selectlanguage") {
2312 context.check_layout(os);
2313 // save the language for the case that a
2314 // \foreignlanguage is used
2316 context.font.language = subst(p.verbatim_item(), "\n", " ");
2317 os << "\\lang " << context.font.language << "\n";
2320 else if (t.cs() == "foreignlanguage") {
2321 context.check_layout(os);
2322 os << "\n\\lang " << subst(p.verbatim_item(), "\n", " ") << "\n";
2323 os << subst(p.verbatim_item(), "\n", " ");
2324 // FIXME: the second argument of selectlanguage
2325 // has to be parsed (like for \textsf, for
2327 // set back to last selectlanguage
2328 os << "\n\\lang " << context.font.language << "\n";
2331 else if (t.cs() == "inputencoding") {
2332 // nothing to write here
2333 string const enc = subst(p.verbatim_item(), "\n", " ");
2337 else if (t.cs() == "LyX" || t.cs() == "TeX"
2338 || t.cs() == "LaTeX") {
2339 context.check_layout(os);
2341 skip_spaces_braces(p);
2344 else if (t.cs() == "LaTeXe") {
2345 context.check_layout(os);
2347 skip_spaces_braces(p);
2350 else if (t.cs() == "ldots") {
2351 context.check_layout(os);
2352 os << "\\SpecialChar \\ldots{}\n";
2353 skip_spaces_braces(p);
2356 else if (t.cs() == "lyxarrow") {
2357 context.check_layout(os);
2358 os << "\\SpecialChar \\menuseparator\n";
2359 skip_spaces_braces(p);
2362 else if (t.cs() == "textcompwordmark") {
2363 context.check_layout(os);
2364 os << "\\SpecialChar \\textcompwordmark{}\n";
2365 skip_spaces_braces(p);
2368 else if (LYX_FORMAT >= 307 && t.cs() == "slash") {
2369 context.check_layout(os);
2370 os << "\\SpecialChar \\slash{}\n";
2371 skip_spaces_braces(p);
2374 else if (LYX_FORMAT >= 307 && t.cs() == "nobreakdash") {
2375 context.check_layout(os);
2376 os << "\\SpecialChar \\nobreakdash\n";
2379 else if (t.cs() == "textquotedbl") {
2380 context.check_layout(os);
2385 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2386 context.check_layout(os);
2387 os << "\\SpecialChar \\@.\n";
2391 else if (t.cs() == "-") {
2392 context.check_layout(os);
2393 os << "\\SpecialChar \\-\n";
2396 else if (t.cs() == "textasciitilde") {
2397 context.check_layout(os);
2399 skip_spaces_braces(p);
2402 else if (t.cs() == "textasciicircum") {
2403 context.check_layout(os);
2405 skip_spaces_braces(p);
2408 else if (t.cs() == "textbackslash") {
2409 context.check_layout(os);
2410 os << "\n\\backslash\n";
2411 skip_spaces_braces(p);
2414 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2415 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2417 context.check_layout(os);
2421 else if (t.cs() == "char") {
2422 context.check_layout(os);
2423 if (p.next_token().character() == '`') {
2425 if (p.next_token().cs() == "\"") {
2430 handle_ert(os, "\\char`", context);
2433 handle_ert(os, "\\char", context);
2437 else if (t.cs() == "verb") {
2438 context.check_layout(os);
2439 char const delimiter = p.next_token().character();
2440 string const arg = p.getArg(delimiter, delimiter);
2442 oss << "\\verb" << delimiter << arg << delimiter;
2443 handle_ert(os, oss.str(), context);
2446 // Problem: \= creates a tabstop inside the tabbing environment
2447 // and else an accent. In the latter case we really would want
2448 // \={o} instead of \= o.
2449 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2450 handle_ert(os, t.asInput(), context);
2452 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
2453 else if (t.cs().size() == 1
2454 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
2455 context.check_layout(os);
2456 // try to see whether the string is in unicodesymbols
2458 string command = t.asInput() + "{"
2459 + trim(p.verbatim_item())
2461 docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
2464 cerr << "When parsing " << command
2465 << ", result is " << to_utf8(s)
2466 << "+" << to_utf8(rem) << endl;
2469 // we did not find a non-ert version
2470 handle_ert(os, command, context);
2473 else if (t.cs() == "\\") {
2474 context.check_layout(os);
2475 string const next = p.next_token().asInput();
2477 handle_ert(os, "\\\\" + p.getOpt(), context);
2478 else if (next == "*") {
2480 handle_ert(os, "\\\\*" + p.getOpt(), context);
2483 os << "\n\\newline\n";
2487 else if (t.cs() == "newline") {
2488 context.check_layout(os);
2489 os << "\n\\" << t.cs() << "\n";
2490 skip_spaces_braces(p);
2493 else if (t.cs() == "input" || t.cs() == "include"
2494 || t.cs() == "verbatiminput") {
2495 string name = t.cs();
2496 if (t.cs() == "verbatiminput"
2497 && p.next_token().asInput() == "*")
2498 name += p.get_token().asInput();
2499 context.check_layout(os);
2500 string filename(normalize_filename(p.getArg('{', '}')));
2501 string const path = getMasterFilePath();
2502 // We want to preserve relative / absolute filenames,
2503 // therefore path is only used for testing
2504 if ((t.cs() == "include" || t.cs() == "input") &&
2505 !makeAbsPath(filename, path).exists()) {
2506 // The file extension is probably missing.
2507 // Now try to find it out.
2508 string const tex_name =
2509 find_file(filename, path,
2510 known_tex_extensions);
2511 if (!tex_name.empty())
2512 filename = tex_name;
2516 if (makeAbsPath(filename, path).exists()) {
2517 string const abstexname =
2518 makeAbsPath(filename, path).absFileName();
2519 string const abslyxname =
2520 changeExtension(abstexname, ".lyx");
2521 string const absfigname =
2522 changeExtension(abstexname, ".fig");
2523 fix_relative_filename(filename);
2524 string const lyxname =
2525 changeExtension(filename, ".lyx");
2526 if (t.cs() == "input" && FileName(absfigname).exists()) {
2527 FileName const absepsname(
2528 changeExtension(abstexname, ".eps"));
2529 FileName const abspdfname(
2530 changeExtension(abstexname, ".pdf"));
2531 string const ext = getExtension(abstexname);
2532 bool const xfigpdf =
2533 abspdfname.exists() && ext == "pdftex_t";
2534 bool const xfigeps =
2535 absepsname.exists() && ext == "pstex_t";
2536 xfig = xfigpdf || xfigeps;
2539 outname = changeExtension(filename, ".fig");
2540 } else if (t.cs() != "verbatiminput" &&
2541 tex2lyx(abstexname, FileName(abslyxname),
2548 cerr << "Warning: Could not find included file '"
2549 << filename << "'." << endl;
2553 begin_inset(os, "External\n");
2554 os << "\ttemplate XFig\n"
2555 << "\tfilename " << outname << '\n';
2557 begin_command_inset(os, "include", name);
2558 os << "preview false\n"
2559 "filename \"" << outname << "\"\n";
2564 else if (t.cs() == "bibliographystyle") {
2565 // store new bibliographystyle
2566 bibliographystyle = p.verbatim_item();
2567 // output new bibliographystyle.
2568 // This is only necessary if used in some other macro than \bibliography.
2569 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2572 else if (t.cs() == "bibliography") {
2573 context.check_layout(os);
2574 begin_command_inset(os, "bibtex", "bibtex");
2575 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
2576 // Do we have a bibliographystyle set?
2577 if (!bibliographystyle.empty())
2578 os << "options " << '"' << bibliographystyle << '"' << "\n";
2582 else if (t.cs() == "parbox")
2583 parse_box(p, os, FLAG_ITEM, outer, context, true);
2585 //\makebox() is part of the picture environment and different from \makebox{}
2586 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
2587 else if (t.cs() == "makebox") {
2588 string arg = t.asInput();
2589 if (p.next_token().character() == '(')
2590 //the syntax is: \makebox(x,y)[position]{content}
2591 arg += p.getFullParentheseArg();
2593 //the syntax is: \makebox[width][position]{content}
2594 arg += p.getFullOpt();
2595 handle_ert(os, arg + p.getFullOpt(), context);
2598 else if (t.cs() == "smallskip" ||
2599 t.cs() == "medskip" ||
2600 t.cs() == "bigskip" ||
2601 t.cs() == "vfill") {
2602 context.check_layout(os);
2603 begin_inset(os, "VSpace ");
2606 skip_spaces_braces(p);
2609 else if (is_known(t.cs(), known_spaces)) {
2610 char const * const * where = is_known(t.cs(), known_spaces);
2611 context.check_layout(os);
2612 os << "\\InsetSpace ";
2613 os << '\\' << known_coded_spaces[where - known_spaces]
2615 // LaTeX swallows whitespace after all spaces except
2616 // "\\,". We have to do that here, too, because LyX
2617 // adds "{}" which would make the spaces significant.
2619 eat_whitespace(p, os, context, false);
2620 // LyX adds "{}" after all spaces except "\\ " and
2621 // "\\,", so we have to remove "{}".
2622 // "\\,{}" is equivalent to "\\," in LaTeX, so we
2623 // remove the braces after "\\,", too.
2628 else if (t.cs() == "newpage" ||
2629 t.cs() == "clearpage" ||
2630 t.cs() == "cleardoublepage") {
2631 context.check_layout(os);
2632 os << "\n\\" << t.cs() << "\n";
2633 skip_spaces_braces(p);
2636 else if (t.cs() == "newcommand" ||
2637 t.cs() == "providecommand" ||
2638 t.cs() == "renewcommand") {
2639 // these could be handled by parse_command(), but
2640 // we need to call add_known_command() here.
2641 string name = t.asInput();
2642 if (p.next_token().asInput() == "*") {
2643 // Starred form. Eat '*'
2647 string const command = p.verbatim_item();
2648 string const opt1 = p.getOpt();
2649 string const opt2 = p.getFullOpt();
2650 add_known_command(command, opt1, !opt2.empty());
2651 string const ert = name + '{' + command + '}' +
2653 '{' + p.verbatim_item() + '}';
2655 context.check_layout(os);
2656 begin_inset(os, "FormulaMacro");
2661 else if (t.cs() == "vspace") {
2662 bool starred = false;
2663 if (p.next_token().asInput() == "*") {
2667 string const length = p.verbatim_item();
2670 bool valid = splitLatexLength(length, valstring, unit);
2671 bool known_vspace = false;
2672 bool known_unit = false;
2675 istringstream iss(valstring);
2678 if (unit == "\\smallskipamount") {
2680 known_vspace = true;
2681 } else if (unit == "\\medskipamount") {
2683 known_vspace = true;
2684 } else if (unit == "\\bigskipamount") {
2686 known_vspace = true;
2687 } else if (unit == "\\fill") {
2689 known_vspace = true;
2692 if (!known_vspace) {
2693 switch (unitFromString(unit)) {
2714 if (known_unit || known_vspace) {
2715 // Literal length or known variable
2716 context.check_layout(os);
2717 begin_inset(os, "VSpace ");
2725 // LyX can't handle other length variables in Inset VSpace
2726 string name = t.asInput();
2731 handle_ert(os, name + '{' + unit + '}', context);
2732 else if (value == -1.0)
2733 handle_ert(os, name + "{-" + unit + '}', context);
2735 handle_ert(os, name + '{' + valstring + unit + '}', context);
2737 handle_ert(os, name + '{' + length + '}', context);
2742 // try to see whether the string is in unicodesymbols
2743 // Only use text mode commands, since we are in text mode here,
2744 // and math commands may be invalid (bug 6797)
2746 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
2747 rem, Encodings::TEXT_CMD);
2750 cerr << "When parsing " << t.cs()
2751 << ", result is " << to_utf8(s)
2752 << "+" << to_utf8(rem) << endl;
2753 context.check_layout(os);
2755 skip_spaces_braces(p);
2757 //cerr << "#: " << t << " mode: " << mode << endl;
2758 // heuristic: read up to next non-nested space
2760 string s = t.asInput();
2761 string z = p.verbatim_item();
2762 while (p.good() && z != " " && z.size()) {
2763 //cerr << "read: " << z << endl;
2765 z = p.verbatim_item();
2767 cerr << "found ERT: " << s << endl;
2768 handle_ert(os, s + ' ', context);
2771 string name = t.asInput();
2772 if (p.next_token().asInput() == "*") {
2773 // Starred commands like \vspace*{}
2774 p.get_token(); // Eat '*'
2777 if (!parse_command(name, p, os, outer, context))
2778 handle_ert(os, name, context);
2782 if (flags & FLAG_LEAVE) {
2783 flags &= ~FLAG_LEAVE;