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", "hfill", "dotfill", "hrulefill",
196 "leftarrowfill", "rightarrowfill", "upbracefill", "downbracefill", 0};
198 /// the same as known_spaces with .lyx names
199 char const * const known_coded_spaces[] = { "space{}", "space{}",
200 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
201 "negthinspace{}", "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}",
202 "rightarrowfill{}", "upbracefill{}", "downbracefill{}", 0};
205 /// splits "x=z, y=b" into a map and an ordered keyword vector
206 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
211 keys.resize(v.size());
212 for (size_t i = 0; i < v.size(); ++i) {
213 size_t const pos = v[i].find('=');
214 string const index = trim(v[i].substr(0, pos));
215 string const value = trim(v[i].substr(pos + 1, string::npos));
223 * Split a LaTeX length into value and unit.
224 * The latter can be a real unit like "pt", or a latex length variable
225 * like "\textwidth". The unit may contain additional stuff like glue
226 * lengths, but we don't care, because such lengths are ERT anyway.
227 * \returns true if \p value and \p unit are valid.
229 bool splitLatexLength(string const & len, string & value, string & unit)
233 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
234 //'4,5' is a valid LaTeX length number. Change it to '4.5'
235 string const length = subst(len, ',', '.');
236 if (i == string::npos)
239 if (len[0] == '\\') {
240 // We had something like \textwidth without a factor
246 value = trim(string(length, 0, i));
250 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
251 if (contains(len, '\\'))
252 unit = trim(string(len, i));
254 unit = ascii_lowercase(trim(string(len, i)));
259 /// A simple function to translate a latex length to something LyX can
260 /// understand. Not perfect, but rather best-effort.
261 bool translate_len(string const & length, string & valstring, string & unit)
263 if (!splitLatexLength(length, valstring, unit))
265 // LyX uses percent values
267 istringstream iss(valstring);
272 string const percentval = oss.str();
274 if (unit.empty() || unit[0] != '\\')
276 string::size_type const i = unit.find(' ');
277 string const endlen = (i == string::npos) ? string() : string(unit, i);
278 if (unit == "\\textwidth") {
279 valstring = percentval;
280 unit = "text%" + endlen;
281 } else if (unit == "\\columnwidth") {
282 valstring = percentval;
283 unit = "col%" + endlen;
284 } else if (unit == "\\paperwidth") {
285 valstring = percentval;
286 unit = "page%" + endlen;
287 } else if (unit == "\\linewidth") {
288 valstring = percentval;
289 unit = "line%" + endlen;
290 } else if (unit == "\\paperheight") {
291 valstring = percentval;
292 unit = "pheight%" + endlen;
293 } else if (unit == "\\textheight") {
294 valstring = percentval;
295 unit = "theight%" + endlen;
303 string translate_len(string const & length)
307 if (translate_len(length, value, unit))
309 // If the input is invalid, return what we have.
317 * Translates a LaTeX length into \p value, \p unit and
318 * \p special parts suitable for a box inset.
319 * The difference from translate_len() is that a box inset knows about
320 * some special "units" that are stored in \p special.
322 void translate_box_len(string const & length, string & value, string & unit, string & special)
324 if (translate_len(length, value, unit)) {
325 if (unit == "\\height" || unit == "\\depth" ||
326 unit == "\\totalheight" || unit == "\\width") {
327 special = unit.substr(1);
328 // The unit is not used, but LyX requires a dummy setting
341 * Find a file with basename \p name in path \p path and an extension
344 string find_file(string const & name, string const & path,
345 char const * const * extensions)
347 for (char const * const * what = extensions; *what; ++what) {
348 string const trial = addExtension(name, *what);
349 if (makeAbsPath(trial, path).exists())
356 void begin_inset(ostream & os, string const & name)
358 os << "\n\\begin_inset " << name;
362 void begin_command_inset(ostream & os, string const & name,
363 string const & latexname)
365 begin_inset(os, "CommandInset ");
366 os << name << "\nLatexCommand " << latexname << '\n';
370 void end_inset(ostream & os)
372 os << "\n\\end_inset\n\n";
376 bool skip_braces(Parser & p)
378 if (p.next_token().cat() != catBegin)
381 if (p.next_token().cat() == catEnd) {
390 void handle_ert(ostream & os, string const & s, Context & context)
392 // We must have a valid layout before outputting the ERT inset.
393 context.check_layout(os);
394 Context newcontext(true, context.textclass);
395 begin_inset(os, "ERT");
396 os << "\nstatus collapsed\n";
397 newcontext.check_layout(os);
398 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
400 os << "\n\\backslash\n";
401 else if (*it == '\n') {
402 newcontext.new_paragraph(os);
403 newcontext.check_layout(os);
407 newcontext.check_end_layout(os);
412 void handle_comment(ostream & os, string const & s, Context & context)
414 // TODO: Handle this better
415 Context newcontext(true, context.textclass);
416 begin_inset(os, "ERT");
417 os << "\nstatus collapsed\n";
418 newcontext.check_layout(os);
419 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
421 os << "\n\\backslash\n";
425 // make sure that our comment is the last thing on the line
426 newcontext.new_paragraph(os);
427 newcontext.check_layout(os);
428 newcontext.check_end_layout(os);
433 Layout const * findLayout(TextClass const & textclass, string const & name)
435 DocumentClass::const_iterator lit = textclass.begin();
436 DocumentClass::const_iterator len = textclass.end();
437 for (; lit != len; ++lit)
438 if (lit->latexname() == name)
444 void eat_whitespace(Parser &, ostream &, Context &, bool);
448 * Skips whitespace and braces.
449 * This should be called after a command has been parsed that is not put into
450 * ERT, and where LyX adds "{}" if needed.
452 void skip_spaces_braces(Parser & p)
454 /* The following four examples produce the same typeset output and
455 should be handled by this function:
463 // Unfortunately we need to skip comments, too.
464 // We can't use eat_whitespace since writing them after the {}
465 // results in different output in some cases.
466 bool const skipped_spaces = p.skip_spaces(true);
467 bool const skipped_braces = skip_braces(p);
468 if (skipped_spaces && !skipped_braces)
469 // put back the space (it is better handled by check_space)
470 p.unskip_spaces(true);
474 void output_command_layout(ostream & os, Parser & p, bool outer,
475 Context & parent_context,
476 Layout const * newlayout)
478 parent_context.check_end_layout(os);
479 Context context(true, parent_context.textclass, newlayout,
480 parent_context.layout, parent_context.font);
481 if (parent_context.deeper_paragraph) {
482 // We are beginning a nested environment after a
483 // deeper paragraph inside the outer list environment.
484 // Therefore we don't need to output a "begin deeper".
485 context.need_end_deeper = true;
487 context.check_deeper(os);
488 context.check_layout(os);
489 unsigned int optargs = 0;
490 while (optargs < context.layout->optargs) {
491 eat_whitespace(p, os, context, false);
492 if (p.next_token().character() != '[')
494 p.get_token(); // eat '['
495 begin_inset(os, "OptArg\n");
496 os << "status collapsed\n\n";
497 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
499 eat_whitespace(p, os, context, false);
503 // This is the code needed to parse required arguments, but
504 // required arguments come into being only much later than the
505 // file format tex2lyx is presently outputting.
506 unsigned int reqargs = 0;
507 while (reqargs < context.layout->reqargs) {
508 eat_whitespace(p, os, context, false);
509 if (p.next_token().character() != '{')
511 p.get_token(); // eat '{'
512 begin_inset(os, "OptArg\n");
513 os << "status collapsed\n\n";
514 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
516 eat_whitespace(p, os, context, false);
520 parse_text(p, os, FLAG_ITEM, outer, context);
521 context.check_end_layout(os);
522 if (parent_context.deeper_paragraph) {
523 // We must suppress the "end deeper" because we
524 // suppressed the "begin deeper" above.
525 context.need_end_deeper = false;
527 context.check_end_deeper(os);
528 // We don't need really a new paragraph, but
529 // we must make sure that the next item gets a \begin_layout.
530 parent_context.new_paragraph(os);
535 * Output a space if necessary.
536 * This function gets called for every whitespace token.
538 * We have three cases here:
539 * 1. A space must be suppressed. Example: The lyxcode case below
540 * 2. A space may be suppressed. Example: Spaces before "\par"
541 * 3. A space must not be suppressed. Example: A space between two words
543 * We currently handle only 1. and 3 and from 2. only the case of
544 * spaces before newlines as a side effect.
546 * 2. could be used to suppress as many spaces as possible. This has two effects:
547 * - Reimporting LyX generated LaTeX files changes almost no whitespace
548 * - Superflous whitespace from non LyX generated LaTeX files is removed.
549 * The drawback is that the logic inside the function becomes
550 * complicated, and that is the reason why it is not implemented.
552 void check_space(Parser & p, ostream & os, Context & context)
554 Token const next = p.next_token();
555 Token const curr = p.curr_token();
556 // A space before a single newline and vice versa must be ignored
557 // LyX emits a newline before \end{lyxcode}.
558 // This newline must be ignored,
559 // otherwise LyX will add an additional protected space.
560 if (next.cat() == catSpace ||
561 next.cat() == catNewline ||
562 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
565 context.check_layout(os);
571 * Parse all arguments of \p command
573 void parse_arguments(string const & command,
574 vector<ArgumentType> const & template_arguments,
575 Parser & p, ostream & os, bool outer, Context & context)
577 string ert = command;
578 size_t no_arguments = template_arguments.size();
579 for (size_t i = 0; i < no_arguments; ++i) {
580 switch (template_arguments[i]) {
582 // This argument contains regular LaTeX
583 handle_ert(os, ert + '{', context);
584 eat_whitespace(p, os, context, false);
585 parse_text(p, os, FLAG_ITEM, outer, context);
589 // This argument consists only of a single item.
590 // The presence of '{' or not must be preserved.
592 if (p.next_token().cat() == catBegin)
593 ert += '{' + p.verbatim_item() + '}';
595 ert += p.verbatim_item();
598 // This argument may contain special characters
599 ert += '{' + p.verbatim_item() + '}';
602 // true because we must not eat whitespace
603 ert += p.getOpt(true);
607 handle_ert(os, ert, context);
612 * Check whether \p command is a known command. If yes,
613 * handle the command with all arguments.
614 * \return true if the command was parsed, false otherwise.
616 bool parse_command(string const & command, Parser & p, ostream & os,
617 bool outer, Context & context)
619 if (known_commands.find(command) != known_commands.end()) {
620 parse_arguments(command, known_commands[command], p, os,
628 /// Parses a minipage or parbox
629 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
630 Context & parent_context, bool use_parbox)
634 // We need to set the height to the LaTeX default of 1\\totalheight
635 // for the case when no height argument is given
636 string height_value = "1";
637 string height_unit = "in";
638 string height_special = "totalheight";
640 if (p.next_token().asInput() == "[") {
641 position = p.getArg('[', ']');
642 if (position != "t" && position != "c" && position != "b") {
644 cerr << "invalid position for minipage/parbox" << endl;
646 if (p.next_token().asInput() == "[") {
647 latex_height = p.getArg('[', ']');
648 translate_box_len(latex_height, height_value, height_unit, height_special);
650 if (p.next_token().asInput() == "[") {
651 inner_pos = p.getArg('[', ']');
652 if (inner_pos != "c" && inner_pos != "t" &&
653 inner_pos != "b" && inner_pos != "s") {
654 inner_pos = position;
655 cerr << "invalid inner_pos for minipage/parbox"
663 string const latex_width = p.verbatim_item();
664 translate_len(latex_width, width_value, width_unit);
665 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
666 // LyX can't handle length variables
671 ss << "\\begin{minipage}";
672 if (!position.empty())
673 ss << '[' << position << ']';
674 if (!latex_height.empty())
675 ss << '[' << latex_height << ']';
676 if (!inner_pos.empty())
677 ss << '[' << inner_pos << ']';
678 ss << "{" << latex_width << "}";
681 handle_ert(os, ss.str(), parent_context);
682 parent_context.new_paragraph(os);
683 parse_text_in_inset(p, os, flags, outer, parent_context);
685 handle_ert(os, "}", parent_context);
687 handle_ert(os, "\\end{minipage}", parent_context);
689 // LyX does not like empty positions, so we have
690 // to set them to the LaTeX default values here.
691 if (position.empty())
693 if (inner_pos.empty())
694 inner_pos = position;
695 parent_context.check_layout(os);
696 begin_inset(os, "Box Frameless\n");
697 os << "position \"" << position << "\"\n";
698 os << "hor_pos \"c\"\n";
699 os << "has_inner_box 1\n";
700 os << "inner_pos \"" << inner_pos << "\"\n";
701 os << "use_parbox " << use_parbox << "\n";
702 os << "width \"" << width_value << width_unit << "\"\n";
703 os << "special \"none\"\n";
704 os << "height \"" << height_value << height_unit << "\"\n";
705 os << "height_special \"" << height_special << "\"\n";
706 os << "status open\n\n";
707 parse_text_in_inset(p, os, flags, outer, parent_context);
709 #ifdef PRESERVE_LAYOUT
710 // LyX puts a % after the end of the minipage
711 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
713 //handle_comment(os, "%dummy", parent_context);
716 parent_context.new_paragraph(os);
718 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
719 //handle_comment(os, "%dummy", parent_context);
722 // We add a protected space if something real follows
723 if (p.good() && p.next_token().cat() != catComment) {
724 begin_inset(os, "space ~\n");
733 /// parse an unknown environment
734 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
735 unsigned flags, bool outer,
736 Context & parent_context)
738 if (name == "tabbing")
739 // We need to remember that we have to handle '\=' specially
740 flags |= FLAG_TABBING;
742 // We need to translate font changes and paragraphs inside the
743 // environment to ERT if we have a non standard font.
744 // Otherwise things like
745 // \large\begin{foo}\huge bar\end{foo}
747 bool const specialfont =
748 (parent_context.font != parent_context.normalfont);
749 bool const new_layout_allowed = parent_context.new_layout_allowed;
751 parent_context.new_layout_allowed = false;
752 handle_ert(os, "\\begin{" + name + "}", parent_context);
753 parse_text_snippet(p, os, flags, outer, parent_context);
754 handle_ert(os, "\\end{" + name + "}", parent_context);
756 parent_context.new_layout_allowed = new_layout_allowed;
760 void parse_environment(Parser & p, ostream & os, bool outer,
761 string & last_env, Context & parent_context)
763 Layout const * newlayout;
764 string const name = p.getArg('{', '}');
765 const bool is_starred = suffixIs(name, '*');
766 string const unstarred_name = rtrim(name, "*");
767 active_environments.push_back(name);
769 if (is_math_env(name)) {
770 parent_context.check_layout(os);
771 begin_inset(os, "Formula ");
772 os << "\\begin{" << name << "}";
773 parse_math(p, os, FLAG_END, MATH_MODE);
774 os << "\\end{" << name << "}";
778 else if (name == "tabular" || name == "longtable") {
779 eat_whitespace(p, os, parent_context, false);
780 parent_context.check_layout(os);
781 begin_inset(os, "Tabular ");
782 handle_tabular(p, os, name == "longtable", parent_context);
787 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
788 eat_whitespace(p, os, parent_context, false);
789 parent_context.check_layout(os);
790 begin_inset(os, "Float " + unstarred_name + "\n");
791 if (p.next_token().asInput() == "[") {
792 os << "placement " << p.getArg('[', ']') << '\n';
794 os << "wide " << convert<string>(is_starred)
795 << "\nsideways false"
796 << "\nstatus open\n\n";
797 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
799 // We don't need really a new paragraph, but
800 // we must make sure that the next item gets a \begin_layout.
801 parent_context.new_paragraph(os);
805 else if (name == "minipage") {
806 eat_whitespace(p, os, parent_context, false);
807 parse_box(p, os, FLAG_END, outer, parent_context, false);
811 else if (name == "comment") {
812 eat_whitespace(p, os, parent_context, false);
813 parent_context.check_layout(os);
814 begin_inset(os, "Note Comment\n");
815 os << "status open\n";
816 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
819 skip_braces(p); // eat {} that might by set by LyX behind comments
822 else if (name == "lyxgreyedout") {
823 eat_whitespace(p, os, parent_context, false);
824 parent_context.check_layout(os);
825 begin_inset(os, "Note Greyedout\n");
826 os << "status open\n";
827 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
832 else if (name == "framed" || name == "shaded") {
833 eat_whitespace(p, os, parent_context, false);
834 parent_context.check_layout(os);
835 if (name == "framed")
836 begin_inset(os, "Box Framed\n");
838 begin_inset(os, "Box Shaded\n");
839 os << "position \"t\"\n"
844 "width \"100col%\"\n"
847 "height_special \"totalheight\"\n"
849 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
854 else if (!parent_context.new_layout_allowed)
855 parse_unknown_environment(p, name, os, FLAG_END, outer,
858 // Alignment and spacing settings
859 // FIXME (bug xxxx): These settings can span multiple paragraphs and
860 // therefore are totally broken!
861 // Note that \centering, raggedright, and raggedleft cannot be handled, as
862 // they are commands not environments. They are furthermore switches that
863 // can be ended by another switches, but also by commands like \footnote or
864 // \parbox. So the only safe way is to leave them untouched.
865 else if (name == "center" || name == "centering" ||
866 name == "flushleft" || name == "flushright" ||
867 name == "singlespace" || name == "onehalfspace" ||
868 name == "doublespace" || name == "spacing") {
869 eat_whitespace(p, os, parent_context, false);
870 // We must begin a new paragraph if not already done
871 if (! parent_context.atParagraphStart()) {
872 parent_context.check_end_layout(os);
873 parent_context.new_paragraph(os);
875 if (name == "flushleft")
876 parent_context.add_extra_stuff("\\align left\n");
877 else if (name == "flushright")
878 parent_context.add_extra_stuff("\\align right\n");
879 else if (name == "center" || name == "centering")
880 parent_context.add_extra_stuff("\\align center\n");
881 else if (name == "singlespace")
882 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
883 else if (name == "onehalfspace")
884 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
885 else if (name == "doublespace")
886 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
887 else if (name == "spacing")
888 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
889 parse_text(p, os, FLAG_END, outer, parent_context);
890 // Just in case the environment is empty
891 parent_context.extra_stuff.erase();
892 // We must begin a new paragraph to reset the alignment
893 parent_context.new_paragraph(os);
897 // The single '=' is meant here.
898 else if ((newlayout = findLayout(parent_context.textclass, name)) &&
899 newlayout->isEnvironment()) {
900 eat_whitespace(p, os, parent_context, false);
901 Context context(true, parent_context.textclass, newlayout,
902 parent_context.layout, parent_context.font);
903 if (parent_context.deeper_paragraph) {
904 // We are beginning a nested environment after a
905 // deeper paragraph inside the outer list environment.
906 // Therefore we don't need to output a "begin deeper".
907 context.need_end_deeper = true;
909 parent_context.check_end_layout(os);
910 if (last_env == name) {
911 // we need to output a separator since LyX would export
912 // the two environments as one otherwise (bug 5716)
913 docstring const sep = from_ascii("--Separator--");
914 TeX2LyXDocClass const & textclass(parent_context.textclass);
915 if (textclass.hasLayout(sep)) {
916 Context newcontext(parent_context);
917 newcontext.layout = &(textclass[sep]);
918 newcontext.check_layout(os);
919 newcontext.check_end_layout(os);
921 parent_context.check_layout(os);
922 begin_inset(os, "Note Note\n");
923 os << "status closed\n";
924 Context newcontext(true, textclass,
925 &(textclass.defaultLayout()));
926 newcontext.check_layout(os);
927 newcontext.check_end_layout(os);
929 parent_context.check_end_layout(os);
932 switch (context.layout->latextype) {
933 case LATEX_LIST_ENVIRONMENT:
934 context.add_par_extra_stuff("\\labelwidthstring "
935 + p.verbatim_item() + '\n');
938 case LATEX_BIB_ENVIRONMENT:
939 p.verbatim_item(); // swallow next arg
945 context.check_deeper(os);
946 parse_text(p, os, FLAG_END, outer, context);
947 context.check_end_layout(os);
948 if (parent_context.deeper_paragraph) {
949 // We must suppress the "end deeper" because we
950 // suppressed the "begin deeper" above.
951 context.need_end_deeper = false;
953 context.check_end_deeper(os);
954 parent_context.new_paragraph(os);
958 else if (name == "appendix") {
959 // This is no good latex style, but it works and is used in some documents...
960 eat_whitespace(p, os, parent_context, false);
961 parent_context.check_end_layout(os);
962 Context context(true, parent_context.textclass, parent_context.layout,
963 parent_context.layout, parent_context.font);
964 context.check_layout(os);
965 os << "\\start_of_appendix\n";
966 parse_text(p, os, FLAG_END, outer, context);
967 context.check_end_layout(os);
971 else if (known_environments.find(name) != known_environments.end()) {
972 vector<ArgumentType> arguments = known_environments[name];
973 // The last "argument" denotes wether we may translate the
974 // environment contents to LyX
975 // The default required if no argument is given makes us
976 // compatible with the reLyXre environment.
977 ArgumentType contents = arguments.empty() ?
980 if (!arguments.empty())
981 arguments.pop_back();
982 // See comment in parse_unknown_environment()
983 bool const specialfont =
984 (parent_context.font != parent_context.normalfont);
985 bool const new_layout_allowed =
986 parent_context.new_layout_allowed;
988 parent_context.new_layout_allowed = false;
989 parse_arguments("\\begin{" + name + "}", arguments, p, os,
990 outer, parent_context);
991 if (contents == verbatim)
992 handle_ert(os, p.verbatimEnvironment(name),
995 parse_text_snippet(p, os, FLAG_END, outer,
997 handle_ert(os, "\\end{" + name + "}", parent_context);
999 parent_context.new_layout_allowed = new_layout_allowed;
1003 parse_unknown_environment(p, name, os, FLAG_END, outer,
1007 active_environments.pop_back();
1011 /// parses a comment and outputs it to \p os.
1012 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1014 LASSERT(t.cat() == catComment, return);
1015 if (!t.cs().empty()) {
1016 context.check_layout(os);
1017 handle_comment(os, '%' + t.cs(), context);
1018 if (p.next_token().cat() == catNewline) {
1019 // A newline after a comment line starts a new
1021 if (context.new_layout_allowed) {
1022 if(!context.atParagraphStart())
1023 // Only start a new paragraph if not already
1024 // done (we might get called recursively)
1025 context.new_paragraph(os);
1027 handle_ert(os, "\n", context);
1028 eat_whitespace(p, os, context, true);
1031 // "%\n" combination
1038 * Reads spaces and comments until the first non-space, non-comment token.
1039 * New paragraphs (double newlines or \\par) are handled like simple spaces
1040 * if \p eatParagraph is true.
1041 * Spaces are skipped, but comments are written to \p os.
1043 void eat_whitespace(Parser & p, ostream & os, Context & context,
1047 Token const & t = p.get_token();
1048 if (t.cat() == catComment)
1049 parse_comment(p, os, t, context);
1050 else if ((! eatParagraph && p.isParagraph()) ||
1051 (t.cat() != catSpace && t.cat() != catNewline)) {
1060 * Set a font attribute, parse text and reset the font attribute.
1061 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1062 * \param currentvalue Current value of the attribute. Is set to the new
1063 * value during parsing.
1064 * \param newvalue New value of the attribute
1066 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1067 Context & context, string const & attribute,
1068 string & currentvalue, string const & newvalue)
1070 context.check_layout(os);
1071 string const oldvalue = currentvalue;
1072 currentvalue = newvalue;
1073 os << '\n' << attribute << ' ' << newvalue << "\n";
1074 parse_text_snippet(p, os, flags, outer, context);
1075 context.check_layout(os);
1076 os << '\n' << attribute << ' ' << oldvalue << "\n";
1077 currentvalue = oldvalue;
1081 /// get the arguments of a natbib or jurabib citation command
1082 void get_cite_arguments(Parser & p, bool natbibOrder,
1083 string & before, string & after)
1085 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1087 // text before the citation
1089 // text after the citation
1090 after = p.getFullOpt();
1092 if (!after.empty()) {
1093 before = p.getFullOpt();
1094 if (natbibOrder && !before.empty())
1095 swap(before, after);
1100 /// Convert filenames with TeX macros and/or quotes to something LyX
1102 string const normalize_filename(string const & name)
1104 Parser p(trim(name, "\""));
1107 Token const & t = p.get_token();
1108 if (t.cat() != catEscape)
1110 else if (t.cs() == "lyxdot") {
1111 // This is used by LyX for simple dots in relative
1115 } else if (t.cs() == "space") {
1125 /// Convert \p name from TeX convention (relative to master file) to LyX
1126 /// convention (relative to .lyx file) if it is relative
1127 void fix_relative_filename(string & name)
1129 if (FileName::isAbsolute(name))
1132 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1133 from_utf8(getParentFilePath())));
1137 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1138 void parse_noweb(Parser & p, ostream & os, Context & context)
1140 // assemble the rest of the keyword
1144 Token const & t = p.get_token();
1145 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1148 scrap = (p.good() && p.next_token().asInput() == "=");
1150 name += p.get_token().asInput();
1153 name += t.asInput();
1156 if (!scrap || !context.new_layout_allowed ||
1157 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1158 cerr << "Warning: Could not interpret '" << name
1159 << "'. Ignoring it." << endl;
1163 // We use new_paragraph instead of check_end_layout because the stuff
1164 // following the noweb chunk needs to start with a \begin_layout.
1165 // This may create a new paragraph even if there was none in the
1166 // noweb file, but the alternative is an invalid LyX file. Since
1167 // noweb code chunks are implemented with a layout style in LyX they
1168 // always must be in an own paragraph.
1169 context.new_paragraph(os);
1170 Context newcontext(true, context.textclass,
1171 &context.textclass[from_ascii("Scrap")]);
1172 newcontext.check_layout(os);
1175 Token const & t = p.get_token();
1176 // We abuse the parser a bit, because this is no TeX syntax
1178 if (t.cat() == catEscape)
1179 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1182 begin_inset(oss, "Newline newline");
1184 os << subst(t.asInput(), "\n", oss.str());
1186 // The scrap chunk is ended by an @ at the beginning of a line.
1187 // After the @ the line may contain a comment and/or
1188 // whitespace, but nothing else.
1189 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1190 (p.next_token().cat() == catSpace ||
1191 p.next_token().cat() == catNewline ||
1192 p.next_token().cat() == catComment)) {
1193 while (p.good() && p.next_token().cat() == catSpace)
1194 os << p.get_token().asInput();
1195 if (p.next_token().cat() == catComment)
1196 // The comment includes a final '\n'
1197 os << p.get_token().asInput();
1199 if (p.next_token().cat() == catNewline)
1206 newcontext.check_end_layout(os);
1210 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1211 bool is_macro(Parser & p)
1213 Token first = p.curr_token();
1214 if (first.cat() != catEscape || !p.good())
1216 if (first.cs() == "def")
1218 if (first.cs() != "global" && first.cs() != "long")
1220 Token second = p.get_token();
1222 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1223 second.cat() == catNewline || second.cat() == catComment)) {
1224 second = p.get_token();
1227 bool secondvalid = second.cat() == catEscape;
1229 bool thirdvalid = false;
1230 if (p.good() && first.cs() == "global" && secondvalid &&
1231 second.cs() == "long") {
1232 third = p.get_token();
1234 while (p.good() && !p.isParagraph() &&
1235 (third.cat() == catSpace ||
1236 third.cat() == catNewline ||
1237 third.cat() == catComment)) {
1238 third = p.get_token();
1241 thirdvalid = third.cat() == catEscape;
1243 for (int i = 0; i < pos; ++i)
1248 return (first.cs() == "global" || first.cs() == "long") &&
1249 second.cs() == "def";
1250 return first.cs() == "global" && second.cs() == "long" &&
1251 third.cs() == "def";
1255 /// Parse a macro definition (assumes that is_macro() returned true)
1256 void parse_macro(Parser & p, ostream & os, Context & context)
1258 context.check_layout(os);
1259 Token first = p.curr_token();
1262 string command = first.asInput();
1263 if (first.cs() != "def") {
1265 eat_whitespace(p, os, context, false);
1266 second = p.curr_token();
1267 command += second.asInput();
1268 if (second.cs() != "def") {
1270 eat_whitespace(p, os, context, false);
1271 third = p.curr_token();
1272 command += third.asInput();
1275 eat_whitespace(p, os, context, false);
1276 string const name = p.get_token().cs();
1277 eat_whitespace(p, os, context, false);
1283 while (p.next_token().cat() != catBegin) {
1284 if (p.next_token().cat() == catParameter) {
1289 // followed by number?
1290 if (p.next_token().cat() == catOther) {
1291 char c = p.getChar();
1293 // number = current arity + 1?
1294 if (c == arity + '0' + 1)
1299 paramtext += p.get_token().cs();
1301 paramtext += p.get_token().cs();
1306 // only output simple (i.e. compatible) macro as FormulaMacros
1307 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1309 context.check_layout(os);
1310 begin_inset(os, "FormulaMacro");
1311 os << "\n\\def" << ert;
1314 handle_ert(os, command + ert, context);
1317 } // anonymous namespace
1320 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1323 Layout const * newlayout = 0;
1324 // Store the latest bibliographystyle and nocite{*} option
1325 // (needed for bibtex inset)
1327 string bibliographystyle;
1328 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1329 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1332 Token const & t = p.get_token();
1335 cerr << "t: " << t << " flags: " << flags << "\n";
1338 if (flags & FLAG_ITEM) {
1339 if (t.cat() == catSpace)
1342 flags &= ~FLAG_ITEM;
1343 if (t.cat() == catBegin) {
1344 // skip the brace and collect everything to the next matching
1346 flags |= FLAG_BRACE_LAST;
1350 // handle only this single token, leave the loop if done
1351 flags |= FLAG_LEAVE;
1354 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1356 if (t.character() == '}' && (flags & FLAG_BRACE_LAST))
1359 // If there is anything between \end{env} and \begin{env} we
1360 // don't need to output a separator.
1361 if (t.cat() != catSpace && t.cat() != catNewline &&
1362 t.asInput() != "\\begin")
1368 if (t.cat() == catMath) {
1369 // we are inside some text mode thingy, so opening new math is allowed
1370 context.check_layout(os);
1371 begin_inset(os, "Formula ");
1372 Token const & n = p.get_token();
1373 if (n.cat() == catMath && outer) {
1374 // TeX's $$...$$ syntax for displayed math
1376 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1378 p.get_token(); // skip the second '$' token
1380 // simple $...$ stuff
1383 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1389 else if (t.cat() == catSuper || t.cat() == catSub)
1390 cerr << "catcode " << t << " illegal in text mode\n";
1392 // Basic support for english quotes. This should be
1393 // extended to other quotes, but is not so easy (a
1394 // left english quote is the same as a right german
1396 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1397 context.check_layout(os);
1398 begin_inset(os, "Quotes ");
1404 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1405 context.check_layout(os);
1406 begin_inset(os, "Quotes ");
1413 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1414 context.check_layout(os);
1415 begin_inset(os, "Quotes ");
1422 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1423 context.check_layout(os);
1424 begin_inset(os, "Quotes ");
1431 else if (t.asInput() == "<"
1432 && p.next_token().asInput() == "<" && noweb_mode) {
1434 parse_noweb(p, os, context);
1437 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1438 check_space(p, os, context);
1440 else if (t.character() == '[' && noweb_mode &&
1441 p.next_token().character() == '[') {
1442 // These can contain underscores
1444 string const s = p.getFullOpt() + ']';
1445 if (p.next_token().character() == ']')
1448 cerr << "Warning: Inserting missing ']' in '"
1449 << s << "'." << endl;
1450 handle_ert(os, s, context);
1453 else if (t.cat() == catLetter ||
1454 t.cat() == catOther ||
1455 t.cat() == catAlign ||
1456 t.cat() == catParameter) {
1457 // This translates "&" to "\\&" which may be wrong...
1458 context.check_layout(os);
1462 else if (p.isParagraph()) {
1463 if (context.new_layout_allowed)
1464 context.new_paragraph(os);
1466 handle_ert(os, "\\par ", context);
1467 eat_whitespace(p, os, context, true);
1470 else if (t.cat() == catActive) {
1471 context.check_layout(os);
1472 if (t.character() == '~') {
1473 if (context.layout->free_spacing)
1476 begin_inset(os, "space ~\n");
1483 else if (t.cat() == catBegin &&
1484 p.next_token().cat() == catEnd) {
1486 Token const prev = p.prev_token();
1488 if (p.next_token().character() == '`' ||
1489 (prev.character() == '-' &&
1490 p.next_token().character() == '-'))
1491 ; // ignore it in {}`` or -{}-
1493 handle_ert(os, "{}", context);
1497 else if (t.cat() == catBegin) {
1498 context.check_layout(os);
1499 // special handling of font attribute changes
1500 Token const prev = p.prev_token();
1501 Token const next = p.next_token();
1502 TeXFont const oldFont = context.font;
1503 if (next.character() == '[' ||
1504 next.character() == ']' ||
1505 next.character() == '*') {
1507 if (p.next_token().cat() == catEnd) {
1512 handle_ert(os, "{", context);
1513 parse_text_snippet(p, os,
1516 handle_ert(os, "}", context);
1518 } else if (! context.new_layout_allowed) {
1519 handle_ert(os, "{", context);
1520 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1522 handle_ert(os, "}", context);
1523 } else if (is_known(next.cs(), known_sizes)) {
1524 // next will change the size, so we must
1526 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1528 if (!context.atParagraphStart())
1530 << context.font.size << "\n";
1531 } else if (is_known(next.cs(), known_font_families)) {
1532 // next will change the font family, so we
1533 // must reset it here
1534 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1536 if (!context.atParagraphStart())
1538 << context.font.family << "\n";
1539 } else if (is_known(next.cs(), known_font_series)) {
1540 // next will change the font series, so we
1541 // must reset it here
1542 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1544 if (!context.atParagraphStart())
1546 << context.font.series << "\n";
1547 } else if (is_known(next.cs(), known_font_shapes)) {
1548 // next will change the font shape, so we
1549 // must reset it here
1550 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1552 if (!context.atParagraphStart())
1554 << context.font.shape << "\n";
1555 } else if (is_known(next.cs(), known_old_font_families) ||
1556 is_known(next.cs(), known_old_font_series) ||
1557 is_known(next.cs(), known_old_font_shapes)) {
1558 // next will change the font family, series
1559 // and shape, so we must reset it here
1560 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1562 if (!context.atParagraphStart())
1564 << context.font.family
1566 << context.font.series
1568 << context.font.shape << "\n";
1570 handle_ert(os, "{", context);
1571 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1573 handle_ert(os, "}", context);
1577 else if (t.cat() == catEnd) {
1578 if (flags & FLAG_BRACE_LAST) {
1581 cerr << "stray '}' in text\n";
1582 handle_ert(os, "}", context);
1585 else if (t.cat() == catComment)
1586 parse_comment(p, os, t, context);
1589 // control sequences
1592 else if (t.cs() == "(") {
1593 context.check_layout(os);
1594 begin_inset(os, "Formula");
1596 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1601 else if (t.cs() == "[") {
1602 context.check_layout(os);
1603 begin_inset(os, "Formula");
1605 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1610 else if (t.cs() == "begin")
1611 parse_environment(p, os, outer, last_env, context);
1613 else if (t.cs() == "end") {
1614 if (flags & FLAG_END) {
1615 // eat environment name
1616 string const name = p.getArg('{', '}');
1617 if (name != active_environment())
1618 cerr << "\\end{" + name + "} does not match \\begin{"
1619 + active_environment() + "}\n";
1622 p.error("found 'end' unexpectedly");
1625 else if (t.cs() == "item") {
1628 bool optarg = false;
1629 if (p.next_token().character() == '[') {
1630 p.get_token(); // eat '['
1631 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1636 context.check_layout(os);
1637 if (context.has_item) {
1638 // An item in an unknown list-like environment
1639 // FIXME: Do this in check_layout()!
1640 context.has_item = false;
1642 handle_ert(os, "\\item", context);
1644 handle_ert(os, "\\item ", context);
1647 if (context.layout->labeltype != LABEL_MANUAL) {
1648 // LyX does not support \item[\mybullet]
1649 // in itemize environments
1650 handle_ert(os, "[", context);
1652 handle_ert(os, "]", context);
1653 } else if (!s.empty()) {
1654 // The space is needed to separate the
1655 // item from the rest of the sentence.
1657 eat_whitespace(p, os, context, false);
1662 else if (t.cs() == "bibitem") {
1664 context.check_layout(os);
1665 begin_command_inset(os, "bibitem", "bibitem");
1666 os << "label \"" << p.getOptContent() << "\"\n";
1667 os << "key \"" << p.verbatim_item() << "\"\n";
1671 else if (is_macro(p))
1672 parse_macro(p, os, context);
1674 else if (t.cs() == "noindent") {
1676 context.add_par_extra_stuff("\\noindent\n");
1679 else if (t.cs() == "appendix") {
1680 context.add_par_extra_stuff("\\start_of_appendix\n");
1681 // We need to start a new paragraph. Otherwise the
1682 // appendix in 'bla\appendix\chapter{' would start
1684 context.new_paragraph(os);
1685 // We need to make sure that the paragraph is
1686 // generated even if it is empty. Otherwise the
1687 // appendix in '\par\appendix\par\chapter{' would
1689 context.check_layout(os);
1690 // FIXME: This is a hack to prevent paragraph
1691 // deletion if it is empty. Handle this better!
1693 "%dummy comment inserted by tex2lyx to "
1694 "ensure that this paragraph is not empty",
1696 // Both measures above may generate an additional
1697 // empty paragraph, but that does not hurt, because
1698 // whitespace does not matter here.
1699 eat_whitespace(p, os, context, true);
1702 // Starred section headings
1703 // Must attempt to parse "Section*" before "Section".
1704 else if ((p.next_token().asInput() == "*") &&
1705 context.new_layout_allowed &&
1706 (newlayout = findLayout(context.textclass, t.cs() + '*')) &&
1707 newlayout->isCommand()) {
1708 TeXFont const oldFont = context.font;
1709 // save the current font size
1710 string const size = oldFont.size;
1711 // reset the font size to default, because the
1712 // font size switches don't affect section
1713 // headings and the like
1714 context.font.size = known_coded_sizes[0];
1715 output_font_change(os, oldFont, context.font);
1718 output_command_layout(os, p, outer, context, newlayout);
1719 // set the font size to the original value
1720 context.font.size = size;
1721 output_font_change(os, oldFont, context.font);
1725 // Section headings and the like
1726 else if (context.new_layout_allowed &&
1727 (newlayout = findLayout(context.textclass, t.cs())) &&
1728 newlayout->isCommand()) {
1729 TeXFont const oldFont = context.font;
1730 // save the current font size
1731 string const size = oldFont.size;
1732 // reset the font size to default, because the font size switches don't
1733 // affect section headings and the like
1734 context.font.size = known_coded_sizes[0];
1735 output_font_change(os, oldFont, context.font);
1737 output_command_layout(os, p, outer, context, newlayout);
1738 // set the font size to the original value
1739 context.font.size = size;
1740 output_font_change(os, oldFont, context.font);
1744 else if (t.cs() == "caption") {
1745 // FIXME: this should get some cleanup. All
1746 // the \begin_layout:s are output by the
1749 context.check_layout(os);
1751 begin_inset(os, "Caption\n\n");
1752 os << "\\begin_layout "
1753 << to_utf8(context.textclass.defaultLayout().name())
1755 if (p.next_token().character() == '[') {
1756 p.get_token(); // eat '['
1757 begin_inset(os, "OptArg\n");
1758 os << "status collapsed\n";
1759 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1761 eat_whitespace(p, os, context, false);
1763 parse_text(p, os, FLAG_ITEM, outer, context);
1764 context.check_end_layout(os);
1765 // We don't need really a new paragraph, but
1766 // we must make sure that the next item gets a \begin_layout.
1767 context.new_paragraph(os);
1770 os << "\\end_layout\n";
1773 else if (t.cs() == "includegraphics") {
1774 bool const clip = p.next_token().asInput() == "*";
1777 string const arg = p.getArg('[', ']');
1778 map<string, string> opts;
1779 vector<string> keys;
1780 split_map(arg, opts, keys);
1782 opts["clip"] = string();
1783 string name = normalize_filename(p.verbatim_item());
1785 string const path = getMasterFilePath();
1786 // We want to preserve relative / absolute filenames,
1787 // therefore path is only used for testing
1788 if (!makeAbsPath(name, path).exists()) {
1789 // The file extension is probably missing.
1790 // Now try to find it out.
1791 string const dvips_name =
1792 find_file(name, path,
1793 known_dvips_graphics_formats);
1794 string const pdftex_name =
1795 find_file(name, path,
1796 known_pdftex_graphics_formats);
1797 if (!dvips_name.empty()) {
1798 if (!pdftex_name.empty()) {
1799 cerr << "This file contains the "
1801 "\"\\includegraphics{"
1803 "However, files\n\""
1804 << dvips_name << "\" and\n\""
1805 << pdftex_name << "\"\n"
1806 "both exist, so I had to make a "
1807 "choice and took the first one.\n"
1808 "Please move the unwanted one "
1809 "someplace else and try again\n"
1810 "if my choice was wrong."
1814 } else if (!pdftex_name.empty()) {
1820 if (makeAbsPath(name, path).exists())
1821 fix_relative_filename(name);
1823 cerr << "Warning: Could not find graphics file '"
1824 << name << "'." << endl;
1826 context.check_layout(os);
1827 begin_inset(os, "Graphics ");
1828 os << "\n\tfilename " << name << '\n';
1829 if (opts.find("width") != opts.end())
1831 << translate_len(opts["width"]) << '\n';
1832 if (opts.find("height") != opts.end())
1834 << translate_len(opts["height"]) << '\n';
1835 if (opts.find("scale") != opts.end()) {
1836 istringstream iss(opts["scale"]);
1840 os << "\tscale " << val << '\n';
1842 if (opts.find("angle") != opts.end()) {
1843 os << "\trotateAngle "
1844 << opts["angle"] << '\n';
1845 vector<string>::const_iterator a =
1846 find(keys.begin(), keys.end(), "angle");
1847 vector<string>::const_iterator s =
1848 find(keys.begin(), keys.end(), "width");
1849 if (s == keys.end())
1850 s = find(keys.begin(), keys.end(), "height");
1851 if (s == keys.end())
1852 s = find(keys.begin(), keys.end(), "scale");
1853 if (s != keys.end() && distance(s, a) > 0)
1854 os << "\tscaleBeforeRotation\n";
1856 if (opts.find("origin") != opts.end()) {
1858 string const opt = opts["origin"];
1859 if (opt.find('l') != string::npos) ss << "left";
1860 if (opt.find('r') != string::npos) ss << "right";
1861 if (opt.find('c') != string::npos) ss << "center";
1862 if (opt.find('t') != string::npos) ss << "Top";
1863 if (opt.find('b') != string::npos) ss << "Bottom";
1864 if (opt.find('B') != string::npos) ss << "Baseline";
1865 if (!ss.str().empty())
1866 os << "\trotateOrigin " << ss.str() << '\n';
1868 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1870 if (opts.find("keepaspectratio") != opts.end())
1871 os << "\tkeepAspectRatio\n";
1872 if (opts.find("clip") != opts.end())
1874 if (opts.find("draft") != opts.end())
1876 if (opts.find("bb") != opts.end())
1877 os << "\tBoundingBox "
1878 << opts["bb"] << '\n';
1879 int numberOfbbOptions = 0;
1880 if (opts.find("bbllx") != opts.end())
1881 numberOfbbOptions++;
1882 if (opts.find("bblly") != opts.end())
1883 numberOfbbOptions++;
1884 if (opts.find("bburx") != opts.end())
1885 numberOfbbOptions++;
1886 if (opts.find("bbury") != opts.end())
1887 numberOfbbOptions++;
1888 if (numberOfbbOptions == 4)
1889 os << "\tBoundingBox "
1890 << opts["bbllx"] << " " << opts["bblly"] << " "
1891 << opts["bburx"] << " " << opts["bbury"] << '\n';
1892 else if (numberOfbbOptions > 0)
1893 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1894 numberOfbbOptions = 0;
1895 if (opts.find("natwidth") != opts.end())
1896 numberOfbbOptions++;
1897 if (opts.find("natheight") != opts.end())
1898 numberOfbbOptions++;
1899 if (numberOfbbOptions == 2)
1900 os << "\tBoundingBox 0bp 0bp "
1901 << opts["natwidth"] << " " << opts["natheight"] << '\n';
1902 else if (numberOfbbOptions > 0)
1903 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1904 ostringstream special;
1905 if (opts.find("hiresbb") != opts.end())
1906 special << "hiresbb,";
1907 if (opts.find("trim") != opts.end())
1909 if (opts.find("viewport") != opts.end())
1910 special << "viewport=" << opts["viewport"] << ',';
1911 if (opts.find("totalheight") != opts.end())
1912 special << "totalheight=" << opts["totalheight"] << ',';
1913 if (opts.find("type") != opts.end())
1914 special << "type=" << opts["type"] << ',';
1915 if (opts.find("ext") != opts.end())
1916 special << "ext=" << opts["ext"] << ',';
1917 if (opts.find("read") != opts.end())
1918 special << "read=" << opts["read"] << ',';
1919 if (opts.find("command") != opts.end())
1920 special << "command=" << opts["command"] << ',';
1921 string s_special = special.str();
1922 if (!s_special.empty()) {
1923 // We had special arguments. Remove the trailing ','.
1924 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1926 // TODO: Handle the unknown settings better.
1927 // Warn about invalid options.
1928 // Check whether some option was given twice.
1932 else if (t.cs() == "footnote" ||
1933 (t.cs() == "thanks" && context.layout->intitle)) {
1935 context.check_layout(os);
1936 begin_inset(os, "Foot\n");
1937 os << "status collapsed\n\n";
1938 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1942 else if (t.cs() == "marginpar") {
1944 context.check_layout(os);
1945 begin_inset(os, "Marginal\n");
1946 os << "status collapsed\n\n";
1947 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1951 else if (t.cs() == "ensuremath") {
1953 context.check_layout(os);
1954 string const s = p.verbatim_item();
1955 //FIXME: this never triggers in UTF8
1956 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
1959 handle_ert(os, "\\ensuremath{" + s + "}",
1963 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1964 // FIXME: Somehow prevent title layouts if
1965 // "maketitle" was not found
1967 skip_spaces_braces(p);
1970 else if (t.cs() == "tableofcontents") {
1971 context.check_layout(os);
1972 begin_command_inset(os, "toc", "tableofcontents");
1974 skip_spaces_braces(p);
1977 else if (t.cs() == "listoffigures") {
1978 context.check_layout(os);
1979 begin_inset(os, "FloatList figure\n");
1981 skip_spaces_braces(p);
1984 else if (t.cs() == "listoftables") {
1985 context.check_layout(os);
1986 begin_inset(os, "FloatList table\n");
1988 skip_spaces_braces(p);
1991 else if (t.cs() == "listof") {
1992 p.skip_spaces(true);
1993 string const name = p.get_token().cs();
1994 if (context.textclass.floats().typeExist(name)) {
1995 context.check_layout(os);
1996 begin_inset(os, "FloatList ");
1999 p.get_token(); // swallow second arg
2001 handle_ert(os, "\\listof{" + name + "}", context);
2004 else if (t.cs() == "textrm")
2005 parse_text_attributes(p, os, FLAG_ITEM, outer,
2006 context, "\\family",
2007 context.font.family, "roman");
2009 else if (t.cs() == "textsf")
2010 parse_text_attributes(p, os, FLAG_ITEM, outer,
2011 context, "\\family",
2012 context.font.family, "sans");
2014 else if (t.cs() == "texttt")
2015 parse_text_attributes(p, os, FLAG_ITEM, outer,
2016 context, "\\family",
2017 context.font.family, "typewriter");
2019 else if (t.cs() == "textmd")
2020 parse_text_attributes(p, os, FLAG_ITEM, outer,
2021 context, "\\series",
2022 context.font.series, "medium");
2024 else if (t.cs() == "textbf")
2025 parse_text_attributes(p, os, FLAG_ITEM, outer,
2026 context, "\\series",
2027 context.font.series, "bold");
2029 else if (t.cs() == "textup")
2030 parse_text_attributes(p, os, FLAG_ITEM, outer,
2032 context.font.shape, "up");
2034 else if (t.cs() == "textit")
2035 parse_text_attributes(p, os, FLAG_ITEM, outer,
2037 context.font.shape, "italic");
2039 else if (t.cs() == "textsl")
2040 parse_text_attributes(p, os, FLAG_ITEM, outer,
2042 context.font.shape, "slanted");
2044 else if (t.cs() == "textsc")
2045 parse_text_attributes(p, os, FLAG_ITEM, outer,
2047 context.font.shape, "smallcaps");
2049 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2050 context.check_layout(os);
2051 TeXFont oldFont = context.font;
2052 context.font.init();
2053 context.font.size = oldFont.size;
2054 os << "\n\\family " << context.font.family << "\n";
2055 os << "\n\\series " << context.font.series << "\n";
2056 os << "\n\\shape " << context.font.shape << "\n";
2057 if (t.cs() == "textnormal") {
2058 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2059 output_font_change(os, context.font, oldFont);
2060 context.font = oldFont;
2062 eat_whitespace(p, os, context, false);
2065 else if (t.cs() == "textcolor") {
2066 // scheme is \textcolor{color name}{text}
2067 string const color = p.verbatim_item();
2068 // we only support the predefined colors of the color package
2069 if (color == "black" || color == "blue" || color == "cyan"
2070 || color == "green" || color == "magenta" || color == "red"
2071 || color == "white" || color == "yellow") {
2072 context.check_layout(os);
2073 os << "\n\\color " << color << "\n";
2074 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2075 context.check_layout(os);
2076 os << "\n\\color inherit\n";
2078 // for custom defined colors
2079 handle_ert(os, t.asInput() + "{" + color + "}", context);
2082 else if (t.cs() == "underbar") {
2083 // Do NOT handle \underline.
2084 // \underbar cuts through y, g, q, p etc.,
2085 // \underline does not.
2086 context.check_layout(os);
2087 os << "\n\\bar under\n";
2088 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2089 context.check_layout(os);
2090 os << "\n\\bar default\n";
2093 else if (t.cs() == "emph" || t.cs() == "noun") {
2094 context.check_layout(os);
2095 os << "\n\\" << t.cs() << " on\n";
2096 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2097 context.check_layout(os);
2098 os << "\n\\" << t.cs() << " default\n";
2101 else if (t.cs() == "lyxline") {
2102 context.check_layout(os);
2106 else if (is_known(t.cs(), known_ref_commands)) {
2107 context.check_layout(os);
2108 begin_command_inset(os, "ref", t.cs());
2109 // LyX cannot handle newlines in a latex command
2110 // FIXME: Move the substitution into parser::getOpt()?
2111 os << subst(p.getOpt(), "\n", " ");
2112 os << "reference " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2116 else if (use_natbib &&
2117 is_known(t.cs(), known_natbib_commands) &&
2118 ((t.cs() != "citefullauthor" &&
2119 t.cs() != "citeyear" &&
2120 t.cs() != "citeyearpar") ||
2121 p.next_token().asInput() != "*")) {
2122 context.check_layout(os);
2123 string command = t.cs();
2124 if (p.next_token().asInput() == "*") {
2128 if (command == "citefullauthor")
2129 // alternative name for "\\citeauthor*"
2130 command = "citeauthor*";
2132 // text before the citation
2134 // text after the citation
2136 get_cite_arguments(p, true, before, after);
2138 if (command == "cite") {
2139 // \cite without optional argument means
2140 // \citet, \cite with at least one optional
2141 // argument means \citep.
2142 if (before.empty() && after.empty())
2147 if (before.empty() && after == "[]")
2148 // avoid \citet[]{a}
2150 else if (before == "[]" && after == "[]") {
2151 // avoid \citet[][]{a}
2155 // remove the brackets around after and before
2156 if (!after.empty()) {
2158 after.erase(after.length() - 1, 1);
2159 // LyX cannot handle newlines in the parameter
2160 after = subst(after, "\n", " ");
2162 if (!before.empty()) {
2164 before.erase(before.length() - 1, 1);
2165 // LyX cannot handle newlines in the parameter
2166 before = subst(before, "\n", " ");
2168 begin_command_inset(os, "citation", command);
2169 os << "after " << '"' << after << '"' << "\n";
2170 os << "before " << '"' << before << '"' << "\n";
2171 os << "key " << '"' << p.verbatim_item() << '"' << "\n";
2175 else if (use_jurabib &&
2176 is_known(t.cs(), known_jurabib_commands) &&
2177 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
2178 context.check_layout(os);
2179 string command = t.cs();
2180 if (p.next_token().asInput() == "*") {
2184 char argumentOrder = '\0';
2185 vector<string> const & options = used_packages["jurabib"];
2186 if (find(options.begin(), options.end(),
2187 "natbiborder") != options.end())
2188 argumentOrder = 'n';
2189 else if (find(options.begin(), options.end(),
2190 "jurabiborder") != options.end())
2191 argumentOrder = 'j';
2193 // text before the citation
2195 // text after the citation
2197 get_cite_arguments(p, argumentOrder != 'j', before, after);
2199 string const citation = p.verbatim_item();
2200 if (!before.empty() && argumentOrder == '\0') {
2201 cerr << "Warning: Assuming argument order "
2202 "of jurabib version 0.6 for\n'"
2203 << command << before << after << '{'
2204 << citation << "}'.\n"
2205 "Add 'jurabiborder' to the jurabib "
2206 "package options if you used an\n"
2207 "earlier jurabib version." << endl;
2209 if (!after.empty()) {
2211 after.erase(after.length() - 1, 1);
2213 if (!before.empty()) {
2215 before.erase(before.length() - 1, 1);
2217 begin_command_inset(os, "citation", command);
2218 os << "after " << '"' << after << '"' << "\n";
2219 os << "before " << '"' << before << '"' << "\n";
2220 os << "key " << '"' << citation << '"' << "\n";
2224 else if (t.cs() == "cite"
2225 || t.cs() == "nocite") {
2226 context.check_layout(os);
2227 // LyX cannot handle newlines in a latex command
2228 string after = subst(p.getOptContent(), "\n", " ");
2229 string key = subst(p.verbatim_item(), "\n", " ");
2230 // store the case that it is "\nocite{*}" to use it later for
2233 begin_command_inset(os, "citation", t.cs());
2234 os << "after " << '"' << after << '"' << "\n";
2235 os << "key " << '"' << key << '"' << "\n";
2241 else if (t.cs() == "index") {
2242 context.check_layout(os);
2243 begin_inset(os, "Index\n");
2244 os << "status collapsed\n";
2245 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2249 else if (t.cs() == "nomenclature") {
2250 context.check_layout(os);
2251 begin_command_inset(os, "nomenclature", "nomenclature");
2252 // LyX cannot handle newlines in a latex command
2253 string prefix = subst(p.getOptContent(), "\n", " ");
2254 if (!prefix.empty())
2255 os << "prefix " << '"' << prefix << '"' << "\n";
2256 os << "symbol " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2257 os << "description " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2261 else if (t.cs() == "label") {
2262 context.check_layout(os);
2263 begin_command_inset(os, "label", "label");
2264 // LyX cannot handle newlines in a latex command
2265 os << "name " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2269 else if (t.cs() == "printindex") {
2270 context.check_layout(os);
2271 begin_command_inset(os, "index_print", "printindex");
2273 skip_spaces_braces(p);
2276 else if (t.cs() == "printnomenclature") {
2277 context.check_layout(os);
2278 begin_command_inset(os, "nomencl_print", "printnomenclature");
2280 skip_spaces_braces(p);
2283 else if (t.cs() == "url") {
2284 context.check_layout(os);
2285 begin_inset(os, "Flex URL\n");
2286 os << "status collapsed\n";
2287 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2291 else if (LYX_FORMAT >= 408 &&
2292 (t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
2293 context.check_layout(os);
2294 begin_inset(os, "script ");
2295 os << t.cs().substr(4) << '\n';
2296 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2300 else if (is_known(t.cs(), known_quotes)) {
2301 char const * const * where = is_known(t.cs(), known_quotes);
2302 context.check_layout(os);
2303 begin_inset(os, "Quotes ");
2304 os << known_coded_quotes[where - known_quotes];
2306 // LyX adds {} after the quote, so we have to eat
2307 // spaces here if there are any before a possible
2309 eat_whitespace(p, os, context, false);
2313 else if (is_known(t.cs(), known_sizes) &&
2314 context.new_layout_allowed) {
2315 char const * const * where = is_known(t.cs(), known_sizes);
2316 context.check_layout(os);
2317 TeXFont const oldFont = context.font;
2318 // the font size index differs by 1, because the known_coded_sizes
2319 // has additionally a "default" entry
2320 context.font.size = known_coded_sizes[where - known_sizes + 1];
2321 output_font_change(os, oldFont, context.font);
2322 eat_whitespace(p, os, context, false);
2325 else if (is_known(t.cs(), known_font_families) &&
2326 context.new_layout_allowed) {
2327 char const * const * where =
2328 is_known(t.cs(), known_font_families);
2329 context.check_layout(os);
2330 TeXFont const oldFont = context.font;
2331 context.font.family =
2332 known_coded_font_families[where - known_font_families];
2333 output_font_change(os, oldFont, context.font);
2334 eat_whitespace(p, os, context, false);
2337 else if (is_known(t.cs(), known_font_series) &&
2338 context.new_layout_allowed) {
2339 char const * const * where =
2340 is_known(t.cs(), known_font_series);
2341 context.check_layout(os);
2342 TeXFont const oldFont = context.font;
2343 context.font.series =
2344 known_coded_font_series[where - known_font_series];
2345 output_font_change(os, oldFont, context.font);
2346 eat_whitespace(p, os, context, false);
2349 else if (is_known(t.cs(), known_font_shapes) &&
2350 context.new_layout_allowed) {
2351 char const * const * where =
2352 is_known(t.cs(), known_font_shapes);
2353 context.check_layout(os);
2354 TeXFont const oldFont = context.font;
2355 context.font.shape =
2356 known_coded_font_shapes[where - known_font_shapes];
2357 output_font_change(os, oldFont, context.font);
2358 eat_whitespace(p, os, context, false);
2360 else if (is_known(t.cs(), known_old_font_families) &&
2361 context.new_layout_allowed) {
2362 char const * const * where =
2363 is_known(t.cs(), known_old_font_families);
2364 context.check_layout(os);
2365 TeXFont const oldFont = context.font;
2366 context.font.init();
2367 context.font.size = oldFont.size;
2368 context.font.family =
2369 known_coded_font_families[where - known_old_font_families];
2370 output_font_change(os, oldFont, context.font);
2371 eat_whitespace(p, os, context, false);
2374 else if (is_known(t.cs(), known_old_font_series) &&
2375 context.new_layout_allowed) {
2376 char const * const * where =
2377 is_known(t.cs(), known_old_font_series);
2378 context.check_layout(os);
2379 TeXFont const oldFont = context.font;
2380 context.font.init();
2381 context.font.size = oldFont.size;
2382 context.font.series =
2383 known_coded_font_series[where - known_old_font_series];
2384 output_font_change(os, oldFont, context.font);
2385 eat_whitespace(p, os, context, false);
2388 else if (is_known(t.cs(), known_old_font_shapes) &&
2389 context.new_layout_allowed) {
2390 char const * const * where =
2391 is_known(t.cs(), known_old_font_shapes);
2392 context.check_layout(os);
2393 TeXFont const oldFont = context.font;
2394 context.font.init();
2395 context.font.size = oldFont.size;
2396 context.font.shape =
2397 known_coded_font_shapes[where - known_old_font_shapes];
2398 output_font_change(os, oldFont, context.font);
2399 eat_whitespace(p, os, context, false);
2402 else if (t.cs() == "selectlanguage") {
2403 context.check_layout(os);
2404 // save the language for the case that a
2405 // \foreignlanguage is used
2407 context.font.language = subst(p.verbatim_item(), "\n", " ");
2408 os << "\\lang " << context.font.language << "\n";
2411 else if (t.cs() == "foreignlanguage") {
2412 context.check_layout(os);
2413 os << "\n\\lang " << subst(p.verbatim_item(), "\n", " ") << "\n";
2414 os << subst(p.verbatim_item(), "\n", " ");
2415 // FIXME: the second argument of selectlanguage
2416 // has to be parsed (like for \textsf, for
2418 // set back to last selectlanguage
2419 os << "\n\\lang " << context.font.language << "\n";
2422 else if (t.cs() == "inputencoding") {
2423 // nothing to write here
2424 string const enc = subst(p.verbatim_item(), "\n", " ");
2428 else if (t.cs() == "LyX" || t.cs() == "TeX"
2429 || t.cs() == "LaTeX") {
2430 context.check_layout(os);
2432 skip_spaces_braces(p);
2435 else if (t.cs() == "LaTeXe") {
2436 context.check_layout(os);
2438 skip_spaces_braces(p);
2441 else if (t.cs() == "ldots") {
2442 context.check_layout(os);
2443 os << "\\SpecialChar \\ldots{}\n";
2444 skip_spaces_braces(p);
2447 else if (t.cs() == "lyxarrow") {
2448 context.check_layout(os);
2449 os << "\\SpecialChar \\menuseparator\n";
2450 skip_spaces_braces(p);
2453 else if (t.cs() == "textcompwordmark") {
2454 context.check_layout(os);
2455 os << "\\SpecialChar \\textcompwordmark{}\n";
2456 skip_spaces_braces(p);
2459 else if (t.cs() == "slash") {
2460 context.check_layout(os);
2461 os << "\\SpecialChar \\slash{}\n";
2462 skip_spaces_braces(p);
2465 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
2466 context.check_layout(os);
2467 os << "\\SpecialChar \\nobreakdash-\n";
2471 else if (t.cs() == "textquotedbl") {
2472 context.check_layout(os);
2477 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2478 context.check_layout(os);
2479 os << "\\SpecialChar \\@.\n";
2483 else if (t.cs() == "-") {
2484 context.check_layout(os);
2485 os << "\\SpecialChar \\-\n";
2488 else if (t.cs() == "textasciitilde") {
2489 context.check_layout(os);
2491 skip_spaces_braces(p);
2494 else if (t.cs() == "textasciicircum") {
2495 context.check_layout(os);
2497 skip_spaces_braces(p);
2500 else if (t.cs() == "textbackslash") {
2501 context.check_layout(os);
2502 os << "\n\\backslash\n";
2503 skip_spaces_braces(p);
2506 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2507 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2509 context.check_layout(os);
2513 else if (t.cs() == "char") {
2514 context.check_layout(os);
2515 if (p.next_token().character() == '`') {
2517 if (p.next_token().cs() == "\"") {
2522 handle_ert(os, "\\char`", context);
2525 handle_ert(os, "\\char", context);
2529 else if (t.cs() == "verb") {
2530 context.check_layout(os);
2531 char const delimiter = p.next_token().character();
2532 string const arg = p.getArg(delimiter, delimiter);
2534 oss << "\\verb" << delimiter << arg << delimiter;
2535 handle_ert(os, oss.str(), context);
2538 // Problem: \= creates a tabstop inside the tabbing environment
2539 // and else an accent. In the latter case we really would want
2540 // \={o} instead of \= o.
2541 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2542 handle_ert(os, t.asInput(), context);
2544 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
2545 else if (t.cs().size() == 1
2546 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
2547 context.check_layout(os);
2548 // try to see whether the string is in unicodesymbols
2550 string command = t.asInput() + "{"
2551 + trim(p.verbatim_item())
2553 docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
2556 cerr << "When parsing " << command
2557 << ", result is " << to_utf8(s)
2558 << "+" << to_utf8(rem) << endl;
2561 // we did not find a non-ert version
2562 handle_ert(os, command, context);
2565 else if (t.cs() == "\\") {
2566 context.check_layout(os);
2567 string const next = p.next_token().asInput();
2569 handle_ert(os, "\\\\" + p.getOpt(), context);
2570 else if (next == "*") {
2572 handle_ert(os, "\\\\*" + p.getOpt(), context);
2575 begin_inset(os, "Newline newline");
2580 else if (t.cs() == "newline"
2581 || t.cs() == "linebreak") {
2582 context.check_layout(os);
2583 begin_inset(os, "Newline ");
2586 skip_spaces_braces(p);
2589 else if (t.cs() == "input" || t.cs() == "include"
2590 || t.cs() == "verbatiminput") {
2591 string name = t.cs();
2592 if (t.cs() == "verbatiminput"
2593 && p.next_token().asInput() == "*")
2594 name += p.get_token().asInput();
2595 context.check_layout(os);
2596 string filename(normalize_filename(p.getArg('{', '}')));
2597 string const path = getMasterFilePath();
2598 // We want to preserve relative / absolute filenames,
2599 // therefore path is only used for testing
2600 if ((t.cs() == "include" || t.cs() == "input") &&
2601 !makeAbsPath(filename, path).exists()) {
2602 // The file extension is probably missing.
2603 // Now try to find it out.
2604 string const tex_name =
2605 find_file(filename, path,
2606 known_tex_extensions);
2607 if (!tex_name.empty())
2608 filename = tex_name;
2610 bool external = false;
2612 if (makeAbsPath(filename, path).exists()) {
2613 string const abstexname =
2614 makeAbsPath(filename, path).absFileName();
2615 string const abslyxname =
2616 changeExtension(abstexname, ".lyx");
2617 string const absfigname =
2618 changeExtension(abstexname, ".fig");
2619 fix_relative_filename(filename);
2620 string const lyxname =
2621 changeExtension(filename, ".lyx");
2623 external = FileName(absfigname).exists();
2624 if (t.cs() == "input") {
2625 string const ext = getExtension(abstexname);
2627 // Combined PS/LaTeX:
2628 // x.eps, x.pstex_t (old xfig)
2629 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
2630 FileName const absepsname(
2631 changeExtension(abstexname, ".eps"));
2632 FileName const abspstexname(
2633 changeExtension(abstexname, ".pstex"));
2634 bool const xfigeps =
2635 (absepsname.exists() ||
2636 abspstexname.exists()) &&
2639 // Combined PDF/LaTeX:
2640 // x.pdf, x.pdftex_t (old xfig)
2641 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
2642 FileName const abspdfname(
2643 changeExtension(abstexname, ".pdf"));
2644 bool const xfigpdf =
2645 abspdfname.exists() &&
2646 (ext == "pdftex_t" || ext == "pdf_t");
2650 // Combined PS/PDF/LaTeX:
2651 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
2652 string const absbase2(
2653 removeExtension(abstexname) + "_pspdftex");
2654 FileName const abseps2name(
2655 addExtension(absbase2, ".eps"));
2656 FileName const abspdf2name(
2657 addExtension(absbase2, ".pdf"));
2658 bool const xfigboth =
2659 abspdf2name.exists() &&
2660 abseps2name.exists() && ext == "pspdftex";
2662 xfig = xfigpdf || xfigeps || xfigboth;
2663 external = external && xfig;
2666 outname = changeExtension(filename, ".fig");
2668 // Don't try to convert, the result
2669 // would be full of ERT.
2671 } else if (t.cs() != "verbatiminput" &&
2672 tex2lyx(abstexname, FileName(abslyxname),
2679 cerr << "Warning: Could not find included file '"
2680 << filename << "'." << endl;
2684 begin_inset(os, "External\n");
2685 os << "\ttemplate XFig\n"
2686 << "\tfilename " << outname << '\n';
2688 begin_command_inset(os, "include", name);
2689 os << "preview false\n"
2690 "filename \"" << outname << "\"\n";
2695 else if (t.cs() == "bibliographystyle") {
2696 // store new bibliographystyle
2697 bibliographystyle = p.verbatim_item();
2698 // output new bibliographystyle.
2699 // This is only necessary if used in some other macro than \bibliography.
2700 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2703 else if (t.cs() == "bibliography") {
2704 context.check_layout(os);
2705 begin_command_inset(os, "bibtex", "bibtex");
2706 if (!btprint.empty()) {
2707 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
2708 // clear the string because the next BibTeX inset can be without the
2709 // \nocite{*} option
2712 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
2713 // Do we have a bibliographystyle set?
2714 if (!bibliographystyle.empty())
2715 os << "options " << '"' << bibliographystyle << '"' << "\n";
2719 else if (t.cs() == "parbox")
2720 parse_box(p, os, FLAG_ITEM, outer, context, true);
2722 //\makebox() is part of the picture environment and different from \makebox{}
2723 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
2724 else if (t.cs() == "makebox") {
2725 string arg = t.asInput();
2726 if (p.next_token().character() == '(')
2727 //the syntax is: \makebox(x,y)[position]{content}
2728 arg += p.getFullParentheseArg();
2730 //the syntax is: \makebox[width][position]{content}
2731 arg += p.getFullOpt();
2732 handle_ert(os, arg + p.getFullOpt(), context);
2735 else if (t.cs() == "smallskip" ||
2736 t.cs() == "medskip" ||
2737 t.cs() == "bigskip" ||
2738 t.cs() == "vfill") {
2739 context.check_layout(os);
2740 begin_inset(os, "VSpace ");
2743 skip_spaces_braces(p);
2746 else if (is_known(t.cs(), known_spaces)) {
2747 char const * const * where = is_known(t.cs(), known_spaces);
2748 context.check_layout(os);
2749 begin_inset(os, "space ");
2750 os << '\\' << known_coded_spaces[where - known_spaces]
2753 // LaTeX swallows whitespace after all spaces except
2754 // "\\,". We have to do that here, too, because LyX
2755 // adds "{}" which would make the spaces significant.
2757 eat_whitespace(p, os, context, false);
2758 // LyX adds "{}" after all spaces except "\\ " and
2759 // "\\,", so we have to remove "{}".
2760 // "\\,{}" is equivalent to "\\," in LaTeX, so we
2761 // remove the braces after "\\,", too.
2766 else if (t.cs() == "newpage" ||
2767 t.cs() == "pagebreak" ||
2768 t.cs() == "clearpage" ||
2769 t.cs() == "cleardoublepage") {
2770 context.check_layout(os);
2771 begin_inset(os, "Newpage ");
2774 skip_spaces_braces(p);
2777 else if (t.cs() == "newcommand" ||
2778 t.cs() == "providecommand" ||
2779 t.cs() == "renewcommand") {
2780 // providecommand could be handled by parse_command(),
2781 // but we need to call add_known_command() here.
2782 string name = t.asInput();
2783 if (p.next_token().asInput() == "*") {
2784 // Starred form. Eat '*'
2788 string const command = p.verbatim_item();
2789 string const opt1 = p.getOpt();
2790 string const opt2 = p.getFullOpt();
2791 add_known_command(command, opt1, !opt2.empty());
2792 string const ert = name + '{' + command + '}' +
2794 '{' + p.verbatim_item() + '}';
2796 if (t.cs() == "providecommand")
2797 handle_ert(os, ert, context);
2799 context.check_layout(os);
2800 begin_inset(os, "FormulaMacro");
2806 else if (t.cs() == "hspace" || t.cs() == "vspace") {
2807 bool starred = false;
2808 if (p.next_token().asInput() == "*") {
2812 string name = t.asInput();
2813 string const length = p.verbatim_item();
2816 bool valid = splitLatexLength(length, valstring, unit);
2817 bool known_hspace = false;
2818 bool known_vspace = false;
2819 bool known_unit = false;
2822 istringstream iss(valstring);
2825 if (t.cs()[0] == 'h') {
2826 if (unit == "\\fill") {
2831 known_hspace = true;
2834 if (unit == "\\smallskipamount") {
2836 known_vspace = true;
2837 } else if (unit == "\\medskipamount") {
2839 known_vspace = true;
2840 } else if (unit == "\\bigskipamount") {
2842 known_vspace = true;
2843 } else if (unit == "\\fill") {
2845 known_vspace = true;
2849 if (!known_hspace && !known_vspace) {
2850 switch (unitFromString(unit)) {
2871 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
2872 // Literal horizontal length or known variable
2873 context.check_layout(os);
2874 begin_inset(os, "space ");
2882 if (known_unit && !known_hspace)
2884 << translate_len(length);
2886 } else if (known_unit || known_vspace) {
2887 // Literal vertical length or known variable
2888 context.check_layout(os);
2889 begin_inset(os, "VSpace ");
2897 // LyX can't handle other length variables in Inset VSpace/space
2902 handle_ert(os, name + '{' + unit + '}', context);
2903 else if (value == -1.0)
2904 handle_ert(os, name + "{-" + unit + '}', context);
2906 handle_ert(os, name + '{' + valstring + unit + '}', context);
2908 handle_ert(os, name + '{' + length + '}', context);
2913 // try to see whether the string is in unicodesymbols
2914 // Only use text mode commands, since we are in text mode here,
2915 // and math commands may be invalid (bug 6797)
2917 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
2918 rem, Encodings::TEXT_CMD);
2921 cerr << "When parsing " << t.cs()
2922 << ", result is " << to_utf8(s)
2923 << "+" << to_utf8(rem) << endl;
2924 context.check_layout(os);
2926 skip_spaces_braces(p);
2928 //cerr << "#: " << t << " mode: " << mode << endl;
2929 // heuristic: read up to next non-nested space
2931 string s = t.asInput();
2932 string z = p.verbatim_item();
2933 while (p.good() && z != " " && z.size()) {
2934 //cerr << "read: " << z << endl;
2936 z = p.verbatim_item();
2938 cerr << "found ERT: " << s << endl;
2939 handle_ert(os, s + ' ', context);
2942 string name = t.asInput();
2943 if (p.next_token().asInput() == "*") {
2944 // Starred commands like \vspace*{}
2945 p.get_token(); // Eat '*'
2948 if (!parse_command(name, p, os, outer, context))
2949 handle_ert(os, name, context);
2953 if (flags & FLAG_LEAVE) {
2954 flags &= ~FLAG_LEAVE;